content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
BootWPTOS <-
function(x, levs, indices, filter.number=1, family="DaubExPhase", Bsims=200, lapplyfn=lapply, ret.all=FALSE){
#
# Get the name of the data object, x, to be tested
#
DNAME <- deparse(substitute(x))
#
# Check for any illegal values
#
if (any(is.na(x)) || any(is.nan(x)) || any(is.infinite(x)))
stop("NA/NaN/Inf found in x")
#
# Compute the wavelet packet test statistic on the actual data
#
TS <- WPts(x=x, levs=levs, indices=indices, filter.number=filter.number, family=family)
#
# Create a function to run the bootstrap
#
bsfn <- function(dummy, x, levs, indices, filter.number, family) {
# Note: nothing is done with the dummy argument
#
# Compute surrogate of time series x
#
xs <- as.numeric(surrogate(x=x, ns=1, fft=TRUE, amplitude=TRUE))
if (any(is.na(x)) || any(is.nan(x)) || any(is.infinite(x)))
stop("NA/NaN/Inf found (in bsfn)")
#
# Compute test statistic on surrogate series
#
TS <- WPts(x=xs, levs=levs, indices=indices,
filter.number=filter.number, family=family)
return(TS)
}
#
# Create a list where every entry is equal to the single number: Bsims-1
#
dummy.ip <- vector("list", Bsims - 1)
#
# Apply the bootstrap function to every entry in the dummy list
# Note, the bootstrap function takes the object x forms a surrogate
# applies test statistic to the surrogate and returns the test statistic.
#
ans <- lapplyfn(dummy.ip, bsfn, x=x, levs=levs, indices=indices,
filter.number=filter.number, family=family)
#
# Convert the answer list to a vector
#
ans <- unlist(ans)
#
# Append the value of the test statistic on the data to all the bootstrap vals
#
TS <- c(TS, ans)
#
# Work out the bootstrap p-value
#
p.value <- sum(TS[1] < TS[-1])/Bsims
#
# For debugging purposes return all the test statistics and the computed
# p-value in a list
#
if (ret.all==TRUE) {
l <- list(TS=TS, p.value=p.value)
return(l)
}
#
# Otherwise return the information in the form of a standard hypothesis
# test object.
#
htest.obj <- list(statistic = TS[1], p.value = p.value,
method = "WPBootTOS test of stationarity",
data.name = DNAME, Bootvals = TS)
class(htest.obj) <- c("BootTOS", "htest")
return(htest.obj)
}
|
/scratch/gouwar.j/cran-all/cranData/BootWPTOS/R/BootWPTOS.R
|
WPTOSpickout <-
function(x, level, index, filter.number=1, family="DaubExPhase",
plot.it=FALSE, verbose=FALSE, lowlev=3, highlev, nomsize=0.05) {
if (missing(highlev)) {
J <- IsPowerOfTwo(length(x))
highlev <- floor(J/2)+1
}
#
# Compute wavelet packet transform of data
#
xwpst <- wpst(x, filter.number=1, family="DaubExPhase")
#
# Extract level and index number relating to packet you're interested in
#
xCoefs <- accessD(xwpst, level=level, index=index)
#
# Form b-spectrum (raw wavelet packet periodogram)
#
Ijk <- xCoefs^2
#
# Plot it if necessary
#
if (plot.it==TRUE) {
ts.plot(x)
lines(Ijk, col=2)
}
#
# Compute Haar wavelet transform of raw wavelet packet periodogram
#
Ijk.haar <- wd(Ijk, filter.number=1, family="DaubExPhase")
#
# Under null hypothesis each scale levels is N(0, sigma) .
#
# Estimate sigma for each scale.
#
sigma <- rep(0, J-1)
for(j in highlev:lowlev) {
sigma[j] <- mad(accessD(Ijk.haar, level=j))
}
#
# Count how many coefficients we're going to test in total
#
totalc <- 0
for(j in highlev:lowlev) {
totalc <- totalc + 2^j
}
#
# Work out Bonferonni size
#
mcsize <- nomsize/totalc
#
# Work out appropriate equivalent Z-value
#
z.mcsize <- abs(qnorm(mcsize/2))
ans.haar <- Ijk.haar
if (lowlev>0)
ans.haar <- nullevels(ans.haar, 0:(lowlev-1))
if (highlev < J-1)
ans.haar <- nullevels(ans.haar, (highlev+1):(J-1))
#
# Now do t test for each coefficient
#
survive_count <- 0
for(j in highlev:lowlev) {
y <- accessD(Ijk.haar, lev=j)
z <- y/sigma[j]
z [ abs(z) < z.mcsize] <- 0
survive_count <- survive_count + sum(abs(z) > 0)
ans.haar <- putD(ans.haar, lev=j, v=z)
}
if (verbose==TRUE)
cat("Number of Significant Coefficients: ", survive_count, "\n")
l <- list(x=x, level=level, index=index, sigcoefs=ans.haar, nreject=survive_count, ntests=totalc, bonsize=mcsize)
class(l) <- "toswp"
return(l)
}
|
/scratch/gouwar.j/cran-all/cranData/BootWPTOS/R/WPTOSpickout.R
|
WPts <-
function(x, levs, indices, filter.number=1, family="DaubExPhase")
{
#
# Computes wavelet packet test statistic on time series x
#
# On wavelet packets indexed by levels in levs and indices in indices.
#
#
# Compute nondecimated wavelet packet transform on series
#
xwpst <- wpst(x, filter.number=filter.number, family=family)
#
# See how many levels and indices we have to compute the statistic on
# and do some other argument checking (ie levels are positive and < J)
#
nlev <- length(levs)
nind <- length(indices)
if (nlev != nind)
stop("Number of levels and number of indices has to be the same")
J <- nlevelsWT(xwpst)
if (any(levs < 0))
stop("All levels have to be >= 0")
if (any(levs >= J))
stop("All levels have to be < log_2(n)")
#
# Now check that indices for each level are correct
#
for(i in 1:nlev) {
newlev <- J - levs[i]
maxix <- 2^newlev
if (indices[i] < 0)
stop("All indices have to be >= 0")
if (indices[i] >= maxix)
stop(paste("Index ", indices[i], " is invalid for level ", levs[i], ". Max index is: ", maxix-1))
}
#
# Now compute and return test statistic
#
the.ts <- 0
for(i in 1:nlev) {
xwp <- accessD(xwpst, level=levs[i], index=indices[i])^2
the.ts <- the.ts + var(xwp)
}
the.ts <- the.ts/nlev
return(the.ts)
}
|
/scratch/gouwar.j/cran-all/cranData/BootWPTOS/R/WPts.R
|
plot.toswp <-
function (x, sub = NULL, xlab = "Time", arrow.length = 0.05,
verbose = FALSE, ...)
{
object <- x
x <- x$x
if (is.null(sub))
sub <- paste("Packet:", paste("(", object$level, ",", object$index,")", sep=""), "Using Bonferonni:", object$nreject,
" rejected.")
#
# Plot the original time series in gray
#
ts.plot(x, xlab = xlab, sub = sub, col = "gray80", ...)
st <- summary.toswp(object, quiet=TRUE)
if (is.null(st))
return(NULL)
nreject <- st$nreject
st <- st$rejlist
stHlevs <- NULL
for (i in 1:length(st)) {
stHlevs <- c(stHlevs, st[[i]][1])
}
lyn <- min(stHlevs)
lyx <- max(stHlevs)
nHlevs <- length(lyn:lyx)
ry <- range(x)
mny <- ry[1]
mxy <- ry[2]
mainy <- seq(from = mny, to = mxy, length = nHlevs + 1)
littley <- seq(from = 0, to = (mainy[2] - mainy[1]), length = lyx -
lyn + 2)
if (verbose == TRUE) {
cat("nHlevs: ", nHlevs, "\n")
cat("mny, mxy: ", mny, mxy, "\n")
cat("mainy: ")
print(mainy)
}
abline(h = mainy[1:(length(mainy) - 1)], lty = 2)
axis(4, at = mainy[1:(length(mainy) - 1)], labels = lyn:lyx)
J <- IsPowerOfTwo(length(x))
for (i in 1:length(st)) {
stH <- st[[i]][1]
ix <- st[[i]][c(-1)]
for (j in 1:length(ix)) {
xl <- 2^(J - stH) * (ix[j] - 1)
xr <- 2^(J - stH) * (ix[j])
yy <- mainy[stH - min(stHlevs) + 1]
#+ littley[stH - lyn + 1]
arrows(x0 = xl, x1 = xr, y0 = yy, y1 = yy, code = 3,
col = 2, length = arrow.length)
if (verbose == TRUE) {
cat("stH: ", stH, "\n")
cat("[xl, xt] ", xl, xr, mainy[stH - min(stHlevs) +
1], "\n")
scan()
}
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/BootWPTOS/R/plot.toswp.R
|
print.toswp <-
function (x, ...)
{
cat("Class 'toswp' : Wavelet Packet Test of Stationarity Object :\n")
cat(" ~~~~ : List with", length(x), "components with names\n")
cat(" ", names(x), "\n\n")
cat("\nsummary(.):\n----------\n")
summary.toswp(x)
}
|
/scratch/gouwar.j/cran-all/cranData/BootWPTOS/R/print.toswp.R
|
summary.toswp <-
function (object, quiet=FALSE, ...)
{
#
# Identify and return significant Haar wavelet coefficients
#
hwtosop <- object
ntests <- object$ntests
rejpval <- object$bonsize
bonreject <- object$nreject
sigcoefs <- object$sigcoefs
level <- object$level
index <- object$index
if (quiet == FALSE) {
cat("Number of individual tests:", ntests, "\n")
cat("Bonferroni p-value was:", rejpval, "\n")
cat("Tests rejected:", bonreject, "\n")
}
v <- NULL
count <- 1
if (bonreject != 0) {
if (quiet == FALSE)
cat("Listing Bonferroni rejects...\n")
sJ <- nlevelsWT(sigcoefs)
for (k in 0:(sJ - 1)) {
dk <- accessD(sigcoefs, level=k)
ix <- which(dk != 0)
if (length(ix) > 0) {
if (quiet == FALSE) {
cat("Wavelet Packet ", paste("(", level, ",", index, "):", sep=""), paste("HWTlev: ", k,".", sep=""), "Indices: ")
for(i in 1:length(ix))
cat(ix[i], " ")
cat("\n")
}
v[[count]] <- c(k, ix)
count <- count + 1
}
}
vret <- list(rejlist = v, nreject = bonreject)
}
else
vret <- NULL
return(invisible(vret))
}
|
/scratch/gouwar.j/cran-all/cranData/BootWPTOS/R/summary.toswp.R
|
#' Bootstrap QTL analysis for accurate effect size estimation
#'
#' Performs cis-QTL mapping using MatrixEQTL then performs a bootstrap
#' analysis to obtain unbiased effect size estimates for traits with
#' significant evidence of genetic regulation correcting for the
#' "Winner's Curse" arising from lead-SNP selection.
#'
#' @details
#' Although the package interface and documentation describe the use of
#' \code{BootstrapQTL} for \emph{cis}-eQTL mapping, the package can be
#' applied to any QTL study of quantitative traits with chromosomal
#' positions, for example \emph{cis}-QTL mapping of epigenetic
#' modifications. Any matrix of molecular trait data can be provided
#' to the \code{'gene'} argument provided a corresponding \code{'genepos'}
#' 'data.frame' detailing the chromosomal positions of each trait is
#' provided.
#'
#' \subsection{Cis-eQTL mapping:}{
#' EQTL mapping is performed using the
#' \code{\link[MatrixEQTL:MatrixEQTL-package]{MatrixEQTL}} package. A three step
#' hieararchical multiple testing correction procedure is used to
#' determine significant eGenes and eSNPs. At the first step, nominal
#' p-values from \code{\link[MatrixEQTL:MatrixEQTL-package]{MatrixEQTL}} for all
#' \emph{cis}-SNPs are adjusted for each gene separately using the
#' method specified in the \code{'local_correction'} argument
#' (Bonferroni correction by default). In the second step, the best
#' adjusted p-value is taken for each gene, and this set of locally
#' adjusted p-values is corrected for multiple testing across all genes
#' using the methods pecified in the \code{'global_correction'} argument
#' (FDR correction by default). In the third step, an eSNP significance
#' threshold on the locally corrected p-values is determined as the
#' locally corrected p-value corresponding to the globally corrected
#' p-value threshold of 0.05.
#'
#' A gene is considered a significant eGene if its globally corrected
#' p-value is < 0.05, and a SNP is considered a significant eSNP for
#' that eGene if its locally corrected p-value < the eSNP significance
#' threshold.
#'
#' The default settings for \code{'local_correction'} and
#' \code{'global_correction'} were found to best control eGene false
#' discovery rate without sacrificing sensitivity (see citation).
#' }
#' \subsection{Winner's Curse correction:}{
#' EQTL effect sizes of significant eSNPs on significant eGenes are
#' typically overestimated when compared to replication datasets
#' (see citation). \code{BootstrapEQTL} removes this overestimation by
#' performing a bootstrap procedure after eQTL mapping.
#'
#' Three Winner's Curse correction methods are available: the Shrinkage
#' method, the Out of Sample method, and the Weighted Estimator method.
#' All three methods work on the same basic principle of performing
#' repeated sample bootstrapping to partition the dataset into two
#' groups: an eQTL detection group comprising study samples select via
#' random sampling with replacement, and an eQTL effect size estimation
#' group comprising the remaining samples not selected via the random
#' sampling. The default estimator, \code{'correction_type = "shrinkage"'},
#' provided the most accurate corrected effect sizes in our simulation
#' study (see citation).
#'
#' The \strong{shrinkage method} ("shrinkage" in
#' \code{'correction_type'}) corrects for the Winner's Curse by
#' measuring the average difference between the eQTL effect size
#' in the bootstrap detection group and the bootstrap estimation group,
#' then subtracting this difference from the naive eQTL effect size
#' estimate obtained from the eGene detection analysis prior to the
#' bootstrap procedure.
#'
#' The \strong{out of sample method} ("out_of_sample" in
#' \code{'correction_type'}) corrects for the Winner's Curse by taking
#' the average eQTL effect size across bootstrap estimation groups as
#' an unbiased effect size estimate.
#'
#' The \strong{weighted estimator method} ("weighted" in
#' \code{'correction_type'}) corrects for the Winner's Curse by taking
#' a weighted average of the nominal estimate of the eQTL effect size
#' and the average of eQTL effect sizes across the bootstrap estimation
#' groups: \eqn{0.368 * naive_estimate + 0.632 *
#' mean(bootstrap estimation group effect sizes)}.
#'
#' In all three methods bootstrap effect sizes only contribute to
#' the Winner's Curse correction if the corresponding eSNP is
#' significantly associated with the eGene in the bootstrap detection
#' group (locally corrected bootstrap P-value < eSNP significance
#' threshold determing in the eQTL mapping step).
#'
#' Note that eQTLs may not remain significant in all bootstraps, so the
#' effective number of bootstraps used to obtain the Winner's Curse
#' estimate will typically be lower than the number of bootstraps
#' specified in \code{'n_bootstraps'}. The number of bootstraps that
#' were significant for each eQTL are reported in the
#' \code{'correction_boots'} column of the returned table.
#' }
#' \subsection{Winner's Curse corrected effect sizes}{
#' The user should be aware that ability to correct for Winner's Curse
#' can vary across significant eQTLs depending on their statistical
#' power (\emph{i.e. minor allele frequency, true effect size, and
#' study sample size}). Users should be skeptical of corrected effect
#' sizes that are larger than the nominal effect sizes estimated by
#' \code{\link[MatrixEQTL:MatrixEQTL-package]{MatrixEQTL}}, which likely reflects low
#' power for eQTL detection rather than an underestimated effect size.
#' }
#' \subsection{Bootstrap warning messages:}{
#' It is possible for bootstrap analyses to fail due to the reduced
#' sample sizes of the bootstrap detection and bootstrap estimation
#' groups. For example, the bootstrap resampling may lead to an
#' detection or estimation groups in which all individuals are
#' homozygous for an eSNP or have no variance in their supplied
#' covariates (\emph{e.g.} the estimation group may comprise
#' individuals all of the same sex). In this case the bootstrap will
#' fail for all eQTLs since \code{\link[MatrixEQTL:MatrixEQTL-package]{MatrixEQTL}} will
#' be unable to perform the model fitting.
#'
#' Failed bootstraps are reported after the bootstrap procedure in
#' a series of warning messages indicating the number of bootstrap
#' failures grouped by the reason for the bootstrap failure.
#' }
#'
#' @param snps \code{\link[MatrixEQTL:SlicedData-class]{SlicedData}} object containing genotype
#' information used as input into \code{\link[MatrixEQTL]{Matrix_eQTL_main}}.
#' @param gene \code{\link[MatrixEQTL:SlicedData-class]{SlicedData}} object containing gene expression
#' information used as input into \code{\link[MatrixEQTL]{Matrix_eQTL_main}}.
#' @param snpspos \code{data.frame} object with information about SNP locations.
#' Used in conjunction with \code{'genespos'} and \code{'cisDist'} to
#' determine SNPs in \emph{cis} of each gene. Must have three columns: \enumerate{
#' \item 'snpid' describing the name of the SNP and corresponding to rows in
#' the 'snps' matrix.
#' \item 'chr' describing the chromosome for each SNP.
#' \item 'pos' describing the position of the SNP on the chromosome.
#' }
#' @param genepos \code{data.frame} object with information about transcript locations.
#' Used in conjunction with \code{'snpspos'} and \code{'cisDist'} to
#' determine SNPs in \emph{cis} of each gene. Must have four columns: \enumerate{
#' \item 'geneid' describing the name of the gene and corresponding to rows in
#' the 'gene' matrix.
#' \item 'chr' describing the chromosome for each SNP.
#' \item 'left' describing the start position of the transcript.
#' \item 'right' describing the end position of the transcript.
#' }
#' Note that \code{\link[MatrixEQTL]{Matrix_eQTL_main}} tests all
#' variants within \code{cisDist} of the start or end of the gene.
#' If you wish instead to test all variants within \code{cisDist} of
#' the transcription start site, you should specify this location in
#' both the 'left' and 'right' columns of the \code{genepos}
#' data.frame. Similarly, when analysing a molecular phenotype that
#' have a single chromosomal position then the 'left' and 'right'
#' columns should both contain the same position.
#' @param cvrt \code{\link[MatrixEQTL:SlicedData-class]{SlicedData}} object containing covariate
#' information used as input into \code{\link[MatrixEQTL]{Matrix_eQTL_main}}.
#' Argument can be ignored in the case of no covariates.
#' @param n_bootstraps number of bootstraps to run.
#' @param n_cores number of cores to parallise the bootstrap procedure
#' over.
#' @param eGene_detection_file_name \code{character}, \code{connection} or \code{NULL}.
#' File to save local \emph{cis} associations to in the eGene detection analysis. Corresponds
#' to the \code{output_file_name.cis} argument in \code{\link[MatrixEQTL]{Matrix_eQTL_main}}.
#' If a file with this name exists it is overwritten, if \code{NULL} output is not saved
#' to file.
#' @param bootstrap_file_directory \code{character} or \code{NULL}. If not \code{NULL},
#' files will be saved in this directory storing local \emph{cis} associations for
#' the bootstrap eGene detection group (detection_bootstrapnumber.txt) and local
#' \emph{cis} associations the bootstrap left-out eGene effect size estimation
#' group (estimation_bootstrapnumber.txt). Estimation group files will only be saved
#' where signficant eGenes are also significant in the bootstrap detection group
#' (see Details). Corresponds to the \code{output_file_name.cis} argument in the
#' respective calls to \code{\link[MatrixEQTL]{Matrix_eQTL_main}}. Files in this
#' directory will be overwritten if they already exist.
#' @param cisDist \code{numeric}. Argument to \code{\link[MatrixEQTL]{Matrix_eQTL_main}}
#' controlling the maximum distance from a gene to consider tests for
#' eQTL mapping.
#' @param local_correction multiple testing correction method to use when
#' correcting p-values across all SNPs at each gene (see EQTL mapping
#' section in Details). Can be a method specified in \code{\link[stats:p.adjust]{p.adjust.methods}},
#' "qvalue" for the \code{\link[qvalue]{qvalue}} package, or "eigenMT"
#' if EigenMT has been used to estimate the number effective independent
#' tests (see \code{eigenMT_tests_per_gene}).
#' @param global_correction multiple testing correction method to use when
#' correcting p-values across all genes after performing local correction
#' (see EQTL mapping section in Details). Must be a method specified in
#' \code{\link[stats:p.adjust]{p.adjust.methods}} or "qvalue" for the
#' \code{\link[qvalue]{qvalue}} package.
#' @param correction_type \code{character}. One of "shrinkage", "out_of_sample"
#' or "weighted". Determines which Winner's Curse correction method is
#' used (see Details).
#' @param errorCovariance \code{numeric matrix} argument to \code{\link[MatrixEQTL]{Matrix_eQTL_main}}
#' specifying the error covariance.
#' @param useModel \code{integer} argument to \code{\link[MatrixEQTL]{Matrix_eQTL_main}}
#' specifying the type of model to fit between each SNP and gene. Should be one of
#' \code{\link[MatrixEQTL]{modelLINEAR}}, \code{\link[MatrixEQTL]{modelANOVA}}, or
#' \code{\link[MatrixEQTL]{modelLINEAR_CROSS}}.
#' @param eigenMT_tests_per_gene \code{data.frame} containing the number of effective
#' independent tests for each gene estimated by the EigenMT (\url{https://github.com/joed3/eigenMT}).
#' Ignore unless \code{'local_correction="eigenMT"'}.
#'
#' @return
#' A \code{data.frame} (or \code{\link[data.table]{data.table}} if the
#' user has the library loaded) containing the results for each significant eQTL:
#' \describe{
#' \item{\code{'eGene':}}{The eQTL eGene.}
#' \item{\code{'eSNP':}}{The eQTL eSNP.}
#' \item{\code{'statistic':}}{The test statistic for the association between the eGene and eSNP.}
#' \item{\code{'nominal_beta':}}{The eQTL effect size for the \code{eGene}-\code{eSNP}
#' pair estimated by \code{\link[MatrixEQTL:MatrixEQTL-package]{MatrixEQTL}}.}
#' \item{\code{'corrected_beta':}}{The eQTL effect size after adjustment for the \code{winners_curse}.}
#' \item{\code{'winners_curse':}}{The amount of effect size overestimation determined by the
#' bootstrap analysis (See Details).}
#' \item{\code{'correction_boots':}}{The number of bootstraps that contributed to the estimation of
#' the \code{winners_curse}, \emph{i.e.} the number of bootstraps in which the \code{eSNP}
#' remained significantly associated with the \code{eGene} (see Details).}
#' \item{\code{'nominal_pval':}}{The p-value for the \code{eGene}-\code{eSNP} pair
#' from the \code{\link[MatrixEQTL:MatrixEQTL-package]{MatrixEQTL}} analysis.}
#' \item{\code{'eSNP_pval':}}{The locally corrected p-value for the \code{eGene}-\code{eSNP} pair (see Details).}
#' \item{\code{'eGene_pval':}}{The globally corrected p-value for the \code{eGene} based on its top eSNP (see Details).}
#' }
#'
#' @import foreach
#' @import data.table
#' @import MatrixEQTL
#' @importFrom stats p.adjust p.adjust.methods
#' @importFrom utils sessionInfo
#'
#' @export
#'
#' @examples
#' # Locations for example data from the MatrixEQTL package
#' base.dir = find.package('MatrixEQTL');
#' SNP_file_name = paste(base.dir, "/data/SNP.txt", sep="");
#' snps_location_file_name = paste(base.dir, "/data/snpsloc.txt", sep="");
#' expression_file_name = paste(base.dir, "/data/GE.txt", sep="");
#' gene_location_file_name = paste(base.dir, "/data/geneloc.txt", sep="");
#' covariates_file_name = paste(base.dir, "/data/Covariates.txt", sep="");
#'
#' # Load the SNP data
#' snps = SlicedData$new();
#' snps$fileDelimiter = "\t"; # the TAB character
#' snps$fileOmitCharacters = "NA"; # denote missing values;
#' snps$fileSkipRows = 1; # one row of column labels
#' snps$fileSkipColumns = 1; # one column of row labels
#' snps$fileSliceSize = 2000; # read file in slices of 2,000 rows
#' snps$LoadFile(SNP_file_name);
#'
#' # Load the data detailing the position of each SNP
#' snpspos = read.table(snps_location_file_name, header = TRUE, stringsAsFactors = FALSE);
#'
#' # Load the gene expression data
#' gene = SlicedData$new();
#' gene$fileDelimiter = "\t"; # the TAB character
#' gene$fileOmitCharacters = "NA"; # denote missing values;
#' gene$fileSkipRows = 1; # one row of column labels
#' gene$fileSkipColumns = 1; # one column of row labels
#' gene$fileSliceSize = 2000; # read file in slices of 2,000 rows
#' gene$LoadFile(expression_file_name);
#'
#' # Load the data detailing the position of each gene
#' genepos = read.table(gene_location_file_name, header = TRUE, stringsAsFactors = FALSE);
#'
#' # Load the covariates data
#' cvrt = SlicedData$new();
#' cvrt$fileDelimiter = "\t"; # the TAB character
#' cvrt$fileOmitCharacters = "NA"; # denote missing values;
#' cvrt$fileSkipRows = 1; # one row of column labels
#' cvrt$fileSkipColumns = 1; # one column of row labels
#' if(length(covariates_file_name)>0) {
#' cvrt$LoadFile(covariates_file_name);
#' }
#'
#' # Run the BootstrapQTL analysis
#' eQTLs <- BootstrapQTL(snps, gene, snpspos, genepos, cvrt, n_bootstraps=10, n_cores=2)
#'
BootstrapQTL <- function(
snps, gene, snpspos, genepos, cvrt=SlicedData$new(),
n_bootstraps=200, n_cores=1, eGene_detection_file_name=NULL,
bootstrap_file_directory=NULL, cisDist=1e6,
local_correction="bonferroni", global_correction="fdr",
correction_type="shrinkage", errorCovariance=numeric(),
useModel=modelLINEAR, eigenMT_tests_per_gene=NULL
) {
# R CMD check complains about data.table columns and foreach iterators
# being undefined global variables or functions. The following
# statements are functionally useless other than to suppress the R CMD
# check warnings
global_pval <- NULL
local_pval <- NULL
id_boot <- NULL
bootstrap <- NULL
id_boot <- NULL
error <- NULL
error_type <- NULL
N <- NULL
statistic <- NULL
corrected_beta <- NULL
winners_curse <- NULL
correction_boots <- NULL
pvalue <- NULL
eSNP_pval <- NULL
eGene_pval <- NULL
##--------------------------------------------------------------------
## Check inputs will be OK first - want function to crash at the start
## instead of after several hours running MatrixEQTL if inputs
## are bad.
##--------------------------------------------------------------------
# Check class of 'snps' and 'gene'
if (!("SlicedData" %in% class(snps)) || !("SlicedData" %in% class(gene)) ||
!("SlicedData" %in% class(cvrt))) {
stop("'snps', 'gene', and 'cvrt' must be objects of type \"SlicedData\"")
}
# Check column names are in same order
if (!(all(snps$columnNames == gene$columnNames))) {
stop("'snps' and 'gene' column names must be in same order")
}
if (cvrt$nCols() != 0 && !(all(cvrt$columnNames == gene$columnNames))) {
stop("'cvrt' column names must be in same order as 'snps' and 'gene'")
}
# Check multiple testing adjustment methods are ok
mult.test.methods <- c(p.adjust.methods, "qvalue")
if (length(local_correction) > 1 || !(local_correction %in% c(mult.test.methods, "eigenMT"))) {
stop("'local_correction' must be one of ", paste(paste0('"', mult.test.methods, '"'), ", or \"eigenMT\""))
}
if (length(global_correction) > 1 || !(global_correction %in% mult.test.methods)) {
stop("'local_correction' must be one of ", paste(paste0('"', p.adjust.methods, '"'), ", or \"qvalue\""))
}
if ((local_correction == "qvalue" || global_correction == "qvalue") &&
!pkgReqCheck("qvalue")) {
stop("'qvalue' package not installed")
}
if (local_correction == "eigenMT" && (
is.null(eigenMT_tests_per_gene) ||
!is.data.frame(eigenMT_tests_per_gene) ||
nrow(eigenMT_tests_per_gene) != gene$nRows() ||
ncol(eigenMT_tests_per_gene) != 2 ||
!is.numeric(eigenMT_tests_per_gene[,2]) ||
any(is.na(eigenMT_tests_per_gene[,2])) ||
!all(eigenMT_tests_per_gene[,1] %in% rownames(gene)) ||
!all(rownames(gene) %in% eigenMT_tests_per_gene[,1])
)) {
stop("'eigenMT_tests_per_gene' must be a data.frame containing the number of effective independent tests per gene")
}
if (!is.null(eigenMT_tests_per_gene)) {
eigenMT_tests_per_gene <- as.data.table(eigenMT_tests_per_gene)
setnames(eigenMT_tests_per_gene, c("gene", "n_tests"))
}
# Check correction_type input is ok
if (length(correction_type) > 1 || !(correction_type %in% c("shrinkage", "out_of_sample", "weighted"))) {
stop('\'correction_type\' must be one of "shrinkage", "out_of_sample", or "weighted"')
}
# Force cis-eQTL analysis
if (missing(snpspos) || is.null(snpspos) || (length(snpspos) == 1 && is.na(snpspos))) {
stop("'snpspos' must be provided")
}
if (missing(genepos) || is.null(genepos) || (length(genepos) == 1 && is.na(genepos))) {
stop("'genepos' must be provided")
}
# Check snpspos and genepos inputs
if (!is.data.frame(snpspos) && ncol(snpspos) != 3) {
stop("'snpspos' must be a data.frame with 3 columns")
}
if (!is.data.frame(genepos) && ncol(genepos) != 4) {
stop("'genepos' must be a data.frame with 4 columns")
}
# Check files and directories are ok
if (!is.null(eGene_detection_file_name) && length(eGene_detection_file_name) > 1) {
stop("Only 1 file may be specified in 'eGene_detection_file_name'")
}
if (!is.null(bootstrap_file_directory) && length(bootstrap_file_directory) > 1) {
stop("Only 1 directory may be specified in 'bootstrap_file_directory'")
}
if (!is.null(bootstrap_file_directory)) {
tryCatch({
dir.create(bootstrap_file_directory, showWarnings=FALSE)
}, error=function(e) {
stop("Could not create or access directory specified in 'bootstrap_file_directory'")
})
}
# Check number of bootstraps
if (n_bootstraps < 0) {
stop("'n_bootstraps' must be >= 0")
}
# Check cisDist
if (length(cisDist) != 1 || !is.numeric(cisDist) || !is.finite(cisDist) || cisDist < 1) {
stop("'cisDist' must be a number > 0")
}
##--------------------------------------------------------------------
## Set up and check options that need to be reset at end of the
## function
##--------------------------------------------------------------------
on.exit({ cat("Restoring global environment...\n") })
# stringsAsFactors=TRUE causes crashes here
saf <- options("stringsAsFactors")[[1]]
options(stringsAsFactors=FALSE)
on.exit(options(stringsAsFactors=saf), add=TRUE)
# Check if the user has already loaded data.table: if not, load it and
# make sure we return the table as a data.frame
has.data.table <- !("data.table" %in% names(sessionInfo()$loadedOnly))
if (!has.data.table) {
suppressMessages(requireNamespace("data.table")) # silently load without tutorial message
}
# Set up parallel computing environment
if (n_cores > 1) {
par_setup <- setupParallel(n_cores, verbose=TRUE, reporterCore=FALSE)
on.exit({
cleanupCluster(par_setup$cluster, par_setup$predef)
}, add = TRUE)
} else {
foreach::registerDoSEQ() # prevents %dopar% from throwing warning
}
##--------------------------------------------------------------------
## Perform QTL mapping and nominal effect size estimation
##--------------------------------------------------------------------
cat("Mapping QTLs and obtaining nominal effect size estimates...\n")
# Run Matrix eQTL to determine significant eGenes and get nominal
# estimates for their effect sizes
eQTLs <- Matrix_eQTL_main(
snps = snps,
gene = gene,
cvrt = cvrt,
pvOutputThreshold = 0, # we don't need the Trans eQTL pvalues
errorCovariance = errorCovariance,
pvOutputThreshold.cis = 1,
snpspos = snpspos,
genepos = genepos,
cisDist = cisDist,
output_file_name=NULL,
output_file_name.cis=eGene_detection_file_name,
# noFDRsaveMemory=ifelse(is.null(eGene_detection_file_name), FALSE, TRUE),
noFDRsaveMemory=FALSE, # See: https://github.com/andreyshabalin/MatrixEQTL/issues/8
useModel=modelLINEAR,
verbose=FALSE
);
# Load the table of all cis-Assocations
cis_assocs <- get_cis_assocs(eQTLs, eGene_detection_file_name)
# Perform hierarchcial correction
cis_assocs <- hierarchical_correction(cis_assocs, local_correction, global_correction, eigenMT_tests_per_gene)
# Determine significance threshold for eSNPs
eSNP_threshold <- get_eSNP_threshold(cis_assocs)
# Filter to significant associations
sig_assocs <- cis_assocs[global_pval < 0.05 & local_pval < eSNP_threshold]
if (nrow(sig_assocs) == 0) {
stop("No significant associations detected")
}
if (n_bootstraps > 0) {
##--------------------------------------------------------------------
## Apply filters prior to bootstrapping to speed up calculations and
## minimise memory usage
##--------------------------------------------------------------------
cat("Optimising data for bootstrap procedure...\n")
# Filter 'genes' and 'snps' to just the significant assocations
sig_pairs <- sig_assocs[,list(gene, snps)]
gene_boot <- gene$Clone()
gene_boot$RowReorder(which(rownames(gene_boot) %in% sig_assocs[,gene]))
genepos <- genepos[genepos[,1] %in% sig_assocs[,gene], ]
# If we don't need to run the bootstrap analysis for all cis-SNPs, we
# can filter to just the significant eSNPs
if (local_correction %in% c("bonferroni", "none")) {
tests_per_gene <- cis_assocs[gene %in% sig_assocs[,gene], list(n_tests=.N), by=gene]
} else if (local_correction == "eigenMT") {
tests_per_gene <- eigenMT_tests_per_gene
} else {
tests_per_gene <- NULL
}
if (!is.null(tests_per_gene)) {
snps_boot <- snps$Clone()
snps_boot$RowReorder(which(rownames(snps_boot) %in% sig_assocs[,snps]))
} else {
snps_boot <- snps
}
snpspos <- snpspos[snpspos[,1] %in% sig_assocs[,snps],]
# Make sure only necessary objects are ported to each worker
boot_objs <- c("cvrt", "snps_boot", "gene_boot", "snpspos",
"genepos", "bootstrap_file_directory", "sig_pairs",
"tests_per_gene", "local_correction", "eSNP_threshold",
"errorCovariance", "cisDist", "useModel")
other_objs <- ls()[!(ls() %in% boot_objs)]
##--------------------------------------------------------------------
## Run the bootstrap procedure
##--------------------------------------------------------------------
cat("Running bootstrap procedure for", n_bootstraps, "bootstraps on", getDoParWorkers(), "cores.\n")
# Run MatrixEQTL in each bootstrap detection group and estimation
# group
boot_eGenes <- foreach(id_boot = seq_len(n_bootstraps),
.inorder = FALSE, .noexport=other_objs,
.init = data.table(error=character(0), error_type=character(0)),
.combine = rbind_dt # rbind with FILL = TRUE as default
) %dopar% {
##--------------------------------------------------------------------
## Detection group gene detection
##--------------------------------------------------------------------
tryCatch({ # WHY IS EXCEPTION HANDLING SO HARD IN THIS TERRIBLE LANGUAGE?
# Silently load packages on parallel workers
suppressMessages(requireNamespace("data.table"))
suppressMessages(requireNamespace("MatrixEQTL"))
n_samples <- ncol(snps_boot)
id_detection <- sample(seq_len(n_samples), n_samples, replace = TRUE)
id_estimation <- setdiff(seq_len(n_samples), id_detection)
# Copy and subset the gene and snp data for the bootstrap
# detection group
gene_detection <- gene_boot$Clone()
gene_detection$ColumnSubsample(id_detection)
snps_detection <- snps_boot$Clone()
snps_detection$ColumnSubsample(id_detection)
cvrt_detection <- cvrt$Clone()
cvrt_detection$ColumnSubsample(id_detection)
# File to save detection group cis associations
if (is.null(bootstrap_file_directory)) {
detection_file <- NULL
} else {
detection_file <- file.path(bootstrap_file_directory, paste0("detection_", id_boot, ".txt"))
}
# Run MatrixEQTL on the detection group
# Revisit to remove unneccesary parameters
eQTL_detection <- Matrix_eQTL_main(
snps = snps_detection,
gene = gene_detection,
cvrt = cvrt_detection,
pvOutputThreshold = 0, # we don't need the Trans eQTL pvalues
useModel = useModel,
errorCovariance = errorCovariance,
pvOutputThreshold.cis = 1,
snpspos = snpspos,
genepos = genepos,
cisDist = cisDist,
output_file_name=NULL,
output_file_name.cis=detection_file,
#noFDRsaveMemory=ifelse(is.null(detection_file), FALSE, TRUE),
noFDRsaveMemory=FALSE, # See: https://github.com/andreyshabalin/MatrixEQTL/issues/8
verbose=FALSE
)
# Load the table of all cis-Assocations
detection_cis_assocs <- get_cis_assocs(eQTL_detection, detection_file)
# Perform local SNP correction
detection_cis_assocs <- hierarchical_correction(detection_cis_assocs, local_correction, "none", tests_per_gene)
# Filter to just significant eSNP-eGene pairs (i.e. some SNPs may
# be in cis with multiple genes, but only associated with 1)
detection_cis_assocs <- detection_cis_assocs[sig_pairs, on=c("gene", "snps")]
# Filter to associations that are significant in this bootstrap
detection_sig_assocs <- detection_cis_assocs[local_pval < eSNP_threshold]
# Filter columns
detection_sig_assocs <- detection_sig_assocs[, list(gene, snps, detection_beta=beta)]
# Add identifier columns
detection_sig_assocs[, bootstrap := id_boot]
# If there are no significant associations in this bootstrap we
# can move to the next one
if(nrow(detection_sig_assocs) == 0) {
return(NULL)
}
##----------------------------------------------------------------
## Estimation group effect size re-estimation
##----------------------------------------------------------------
tryCatch({
# Filter to significant genes and SNPs in the detection group
gene_estimation <- gene_boot$Clone()
gene_estimation$RowReorder(which(gene_estimation$GetAllRowNames() %in% detection_sig_assocs[,gene]))
gene_estimation$ColumnSubsample(id_estimation)
snps_estimation <- snps_boot$Clone()
snps_estimation$RowReorder(which(snps_estimation$GetAllRowNames() %in% detection_sig_assocs[,snps]))
snps_estimation$ColumnSubsample(id_estimation)
cvrt_estimation <- cvrt$Clone()
cvrt_estimation$ColumnSubsample(id_estimation)
# File to save estimation group associations
if (is.null(bootstrap_file_directory)) {
estimation_file <- NULL
} else {
estimation_file <- file.path(bootstrap_file_directory, paste0("detection_", id_boot, ".txt"))
}
# Run MatrixEQTl in the estimation group
eQTL_estimation <- Matrix_eQTL_main(
snps = snps_estimation,
gene = gene_estimation,
cvrt = cvrt_estimation,
pvOutputThreshold = 0, # we don't need the Trans eQTL pvalues
useModel = useModel,
errorCovariance = errorCovariance,
pvOutputThreshold.cis = 1,
snpspos = snpspos,
genepos = genepos,
cisDist = cisDist,
output_file_name=NULL,
output_file_name.cis=estimation_file,
#noFDRsaveMemory=ifelse(is.null(detection_file), FALSE, TRUE),
noFDRsaveMemory=FALSE, # See: https://github.com/andreyshabalin/MatrixEQTL/issues/8
verbose=FALSE
)
# Load the table of all cis-assocations
estimation_cis_assocs <- get_cis_assocs(eQTL_estimation, estimation_file)
# Create final table to return
sig_boot_assocs <- merge(detection_sig_assocs,
estimation_cis_assocs[, list(gene, snps, estimation_beta=beta)],
by=c("gene", "snps"))
return(sig_boot_assocs)
}, error=function(e) {
return(data.table(bootstrap=id_boot, error=e$message, error_type="estimation"))
})
}, error=function(e) {
return(data.table(bootstrap=id_boot, error=e$message, error_type="detection"))
})
}
##--------------------------------------------------------------------
## Collate bootstrap errors
##--------------------------------------------------------------------
# Report failed bootstraps if any
if (boot_eGenes[,sum(!is.na(error))] > 0) {
errors <- boot_eGenes[!is.na(error), .N, by=list(error, error_type)]
for (ii in errors[,.I]) {
warning(errors[ii, N], "/", n_bootstraps, " bootstraps failed with",
" error '", errors[ii, error], "' in the bootstrap ",
errors[ii, error_type], " group.", immediate.=TRUE)
}
}
boot_eGenes <- boot_eGenes[is.na(error)]
##--------------------------------------------------------------------
## Remove effect of the winners curse based on bootstrap estimates
##--------------------------------------------------------------------
cat("Removing winner's curse...\n")
# Calculate the effect of the winner's curse. If effect sizes have been
# estimated using the top bootstrap eSNP then we need to account for the
# fact that different eSNPs with anti-correlated minor allele frequencies
# may have been the top SNP at each bootstrap
sig_assocs <- correct_winners_curse(boot_eGenes, sig_assocs, correction_type)
##--------------------------------------------------------------------
## Prepare table to be returned
##--------------------------------------------------------------------
# Relabel columns
sig_assocs <- sig_assocs[,list(eGene=gene, eSNPs=snps, statistic, nominal_beta=beta,
corrected_beta, winners_curse, correction_boots,
nominal_pval=pvalue, eSNP_pval=local_pval,
eGene_pval=global_pval)]
} else {
sig_assocs <- sig_assocs[,list(eGene=gene, eSNPs=snps, statistic, nominal_beta=beta,
nominal_pval=pvalue, eSNP_pval=local_pval,
eGene_pval=global_pval)]
}
# Sort table by significance
sig_assocs <- sig_assocs[order(abs(statistic), decreasing=TRUE)][order(eSNP_pval)][order(eGene_pval)]
# If the user has not loaded data.table themselves cast back to a
# data frame to avoid confusion
if (!has.data.table) {
sig_assocs <- as.data.frame(sig_assocs)
}
on.exit({ cat("Done!\n") }, add=TRUE)
return(sig_assocs)
}
|
/scratch/gouwar.j/cran-all/cranData/BootstrapQTL/R/BootstrapQTL.R
|
### Apply hierarchical multiple testing correction
###
### @param cis_assocs data.table of cis-associations from MatrixEQTL
### @param local multiple testing correction method to use at each gene.
### @param global multiple testing correction method to us across all genes.
### @param tests_per_gene a data.table providing the number of cis SNPs /
### independent tests for each gene.
###
### @return a data.table containing only significant eGenes or significant
### eSNPs
hierarchical_correction <- function(cis_assocs, local, global, tests_per_gene=NULL) {
# Suppress CRAN notes about data.table columns
local_pval <- NULL
pvalue <- NULL
n_tests <- NULL
gene <- NULL
statistic <- NULL
global_pval <- NULL
# Apply local correction across SNPs at each gene
if (!is.null(tests_per_gene)) { # i.e. Bonferroni when test only performed on some SNPs
cis_assocs <- merge(cis_assocs, tests_per_gene, by="gene")
cis_assocs[, local_pval := adjust_p(pvalue, method=local, N=unique(n_tests)), by=gene]
} else {
cis_assocs[, local_pval := adjust_p(pvalue, method=local), by=gene]
}
# Apply global correction across genes using the best p-value per gene
cis_assocs <- cis_assocs[order(abs(statistic), decreasing=TRUE)]
top_assocs <- cis_assocs[, .SD[which.min(local_pval)], by="gene"]
top_assocs[,global_pval := adjust_p(local_pval, method=global)]
cis_assocs <- merge(cis_assocs, top_assocs[,list(gene, global_pval)], by="gene")
return(cis_assocs)
}
### Adjust p-values for multiple tests
adjust_p <- function(pvals, method, N=NULL) {
if (method == "qvalue") {
qvalue::qvalue(pvals)$qvalues
} else if (method == "eigenMT") {
pmin(pvals * N, 1)
} else {
p.adjust(pvals, method, n=ifelse(is.null(N), length(pvals), N))
}
}
### Determine the eSNP significance threshold after hiearchical correction
###
### @param cis_assocs a table of hierarchically corrected associations
get_eSNP_threshold <- function(cis_assocs) {
# Suppress CRAN NOTES
statistic <- NULL
local_pval <- NULL
global_pval <- NULL
# What is the locally corrected p-value corresponding to the global
# correction threshold of 0.05?
cis_assocs <- cis_assocs[order(abs(statistic), decreasing=TRUE)]
top_assocs <- cis_assocs[, .SD[which.min(local_pval)], by="gene"]
top_assocs <- top_assocs[order(global_pval)]
n_sig <- top_assocs[,sum(global_pval < 0.05)]
eSNP_threshold <- top_assocs[n_sig:(n_sig+1), mean(local_pval)]
return(eSNP_threshold)
}
|
/scratch/gouwar.j/cran-all/cranData/BootstrapQTL/R/mult_test.R
|
### Set up a parallel backend
###
### Set up a backend with the requested number of cores, or use existing backend
### if the user has set one up already.
###
### @param nCores number of cores requested.
### @param verbose logical; Is verbose printing on?
### @param reporterCore logical; is there a reporter core?
###
### @details
### If \code{verbose = TRUE} and \code{reporterCore = TRUE} then an extra core
### will be registered for reporting: This core simply sits and prints out
### progress bars for the permutation procedure.
###
### @return
### A list containing the total number of cores registered, the registered
### cluster if on a Windows machine, whether an existing parallel backend
### is being used, and the number of OMP and BLAS threads set in the current
### R session.
setupParallel <- function(nCores, verbose, reporterCore) {
if (is.null(nCores)) {
if (pkgReqCheck("parallel")) {
if (parallel::detectCores() > 1) {
nCores <- parallel::detectCores() - 1
} else {
nCores <- 1
}
} else {
nCores <- 1
if (verbose) cat("Unable to find 'parallel' package, running on 1 core.\n")
}
}
if (!is.numeric(nCores) || length(nCores) > 1 || nCores < 1)
stop("'n_cores' must be a single number greater than 0")
# Defaults to return
cl <- NULL
predef <- FALSE
# First, check whether the user has already set up a parallel backend. In this
# case, we can ignore the `nCores` argument.
if (foreach::getDoParWorkers() > 1) {
if (verbose) cat("Ignoring 'n_cores': parallel backend detected.\n")
if (reporterCore) {
if (verbose) {
cat("Reserving 1 core for progress reporting.", foreach::getDoParWorkers() - 1,
"cores will be used for computation.\n")
}
}
nCores <- foreach::getDoParWorkers()
predef <- TRUE
}
# If the user is on a Windows machine, we have to use the `doParallel` package
else if (.Platform$OS.type == "windows") {
# Quietly load parallel backend packages. Throw our own warning and
# continue
if(pkgReqCheck("doParallel")) {
# we need an additional thread to monitor and report progress
workerCores <- nCores
if (verbose && reporterCore) {
nCores <- nCores + 1
}
cl <- parallel::makeCluster(nCores, type="PSOCK")
doParallel::registerDoParallel(cl)
if (verbose) cat("Registering", workerCores, "cores for bootstrap procedure.\n")
if (workerCores > parallel::detectCores()) {
stop(
"Requested number of cores (", workerCores, ") is higher than the ",
"number of available cores (", parallel::detectCores(),
"). Using too many cores may cause the machine to thrash/freeze."
)
}
} else {
nCores <- 1
# We want to immediately print a warning for the user, not at the end
# once the analysis has finished.
cat("Warning: unable to utilise multiple cores. Please install the 'doParallel' package",
"to enable parallel computation.\n", file=stderr())
warning("Package required for parallel computation not installed")
}
} else if (.Platform$OS.type == "unix" && nCores > 1) {
# Quietly load parallel backend packages. Throw our own warning and
# continue
if (pkgReqCheck("doMC")) {
# we need an additional thread to monitor and report progress
workerCores <- nCores
if (verbose && reporterCore) {
nCores <- nCores + 1
}
doMC::registerDoMC(nCores)
if (verbose) cat("Registering", workerCores, "cores for bootstrap procedure.\n")
if ((nCores - 1) > parallel::detectCores()) {
stop(
"Requested number of cores (", workerCores, ") is higher than the ",
"number of available cores (", parallel::detectCores(),
"). Using too many cores may cause the machine to thrash/freeze."
)
}
} else {
nCores <- 1
# We want to immediately print a warning for the user, not at the end
# once the analysis has finished.
cat("Warning: unable to utilise multiple cores. Please install the 'doMC' package",
"to enable parallel computation.\n", file=stderr())
warning("Package required for parallel computation not installed")
}
} else {
if (verbose) cat("Registering 1 core for bootstrap procedure.\n")
}
return(list(nCores=nCores, cluster=cl, predef=predef))
}
### De-register a parallel backend
###
### @param cluster registered cluster on a Windows machine
### @param predef logical; was a pre-existing parallel backend used?
cleanupCluster <- function(cluster, predef) {
if (!is.null(cluster)) {
if (pkgReqCheck("parallel")) {
# Clobber the backend
parallel::stopCluster(cluster)
cl <- parallel::makeCluster(1, type="PSOCK")
doParallel::registerDoParallel(cl)
parallel::stopCluster(cl)
doParallel::stopImplicitCluster()
}
} else if (!predef) {
if (pkgReqCheck("doMC")) {
doMC::registerDoMC(1)
}
}
}
### Silently check and load a package into the namespace
###
### @param pkg name of the package to check
###
### @return logical; \code{TRUE} if the package is installed and can be loaded.
pkgReqCheck <- function(pkg) {
suppressMessages(suppressWarnings(requireNamespace(pkg, quietly=TRUE)))
}
### Get table of cis associations from MatrixEQTL output
###
### @param meqtl_obj object returend by Matrix_eQTL_main
### @param output_file file associations were saved to
###
### @return data.table of all cis-associations
get_cis_assocs <- function(meqtl_obj, output_file) {
if (is.null(output_file)) {
cis_assocs <- as.data.table(meqtl_obj$cis$eqtls)
} else {
cis_assocs <- fread(output_file)
setnames(cis_assocs, c("SNP", "t-stat", "p-value"), c("snps", "statistic", "pvalue"))
}
return(cis_assocs)
}
### rbind two data tables while filling in missing columns with NA
###
### used as an argument to foreach's .combine
rbind_dt <- function(...) {
rbind(..., fill=TRUE)
}
|
/scratch/gouwar.j/cran-all/cranData/BootstrapQTL/R/utils.R
|
### Calculate the effect of the winner's curse across
###
### @param boot_eGenes effect size estimates from the bootstrap analysis
### @param sig_assocs effect size estimates from the mapping analysis
### @param estimator estimator type
correct_winners_curse <- function(boot_eGenes, sig_assocs, estimator="shrinkage") {
# CRAN NOTE suppression:
gene <- NULL
snps <- NULL
detection_beta <- NULL
estimation_beta <- NULL
bootstrap <- NULL
nominal_beta <- NULL
winners_curse <- NULL
corrected_beta <- NULL
correction_boots <- NULL
winners_curse <- NULL
corrected_beta <- NULL
correction_boots <- NULL
tryCatch({ # Failure condition: no significant bootstraps
effect_sizes <- merge(boot_eGenes[,list(gene, snps, detection_beta, estimation_beta, bootstrap)],
sig_assocs[,list(gene, snps, nominal_beta=beta)], by=c("gene", "snps"))
# Force the effect size sign to always be in the same direction
effect_sizes[, detection_beta := abs(detection_beta) * sign(nominal_beta)]
effect_sizes[, estimation_beta := abs(estimation_beta) * sign(nominal_beta)]
if (estimator == "shrinkage") {
effect_sizes <- effect_sizes[, list(
corrected_beta=unique(nominal_beta) - mean(detection_beta - estimation_beta),
correction_boots=.N, nominal_beta=unique(nominal_beta)
), by=list(gene, snps)]
} else if (estimator == "out_of_sample") {
effect_sizes <- effect_sizes[, list(
corrected_beta=mean(estimation_beta),
correction_boots=.N, nominal_beta=unique(nominal_beta)
), by=list(gene, snps)]
} else if (estimator == "weighted") {
effect_sizes <- effect_sizes[, list(
corrected_beta=0.368*unique(nominal_beta) + 0.632 * mean(estimation_beta),
correction_boots=.N, nominal_beta=unique(nominal_beta)
), by=list(gene, snps)]
}
effect_sizes[, winners_curse := nominal_beta - corrected_beta]
sig_assocs <- merge(sig_assocs,
effect_sizes[,list(gene, snps, winners_curse, corrected_beta, correction_boots)],
by=c("gene", "snps"))
}, error=function(e) {
warning("No significant eSNPs were significant in any bootstrap", immediate.=TRUE)
sig_assocs[, winners_curse := NA_real_]
sig_assocs[, corrected_beta := NA_real_]
sig_assocs[, correction_boots := NA_real_]
})
sig_assocs[is.na(correction_boots), correction_boots := 0] # For genes where no bootstraps are significant
return(sig_assocs)
}
|
/scratch/gouwar.j/cran-all/cranData/BootstrapQTL/R/winners_curse.R
|
Baoptbd <-
function(trt.N,blk.N,alpha,beta,nrep,brep,itr.cvrgval) {
#House keeping
arrays=t(combn(trt.N,2))
na=dim(arrays)[1]
del.1<-matrix(1000,na,3)
desbest.1<-matrix(0,nrep*2,blk.N)
aoptbest.1<-matrix(0,nrep,2)
rsampb<-setdiff(unique(round(rbeta(brep,alpha,beta),5)),c(0,1))
nmcmc<-length(rsampb)
#Start iteration
for(irep in 1:nrep){
#Initial design with its corresponding Ascore value
des<-intcbd(trt.N,blk.N)
if(trt.N==blk.N&trt.N>3&irep<(trt.N-1)) {in.desns=matrix(0,(trt.N-3)*2,blk.N)
in.desns0=rbind(seq(1,trt.N),c(seq(1,trt.N)[2:trt.N],1))
for(i in 1:(trt.N-3)) {in.desns01=cbind(rbind(seq(1,(trt.N-i)),c(seq(1,(trt.N-i))[2:(trt.N-i)],1)),rbind(rep(1,i),((trt.N-i+1):trt.N))); in.desns[c((i-1)*2+1,i*2),]=in.desns01}
in.desns=rbind(rbind(seq(1,trt.N),c(seq(1,trt.N)[2:trt.N],1)),in.desns)
des=in.desns[c((irep-1)*2+1,irep*2),]}
aopts={};
imcmc=1;
for(imcmc in 1:nmcmc){
rv=1;
theta=rsampb[imcmc];
cmat<-cmatbd(trt.N,blk.N,theta,des)
aopts1=sum(diag(ginv(cmat)))
aopts<-rbind(aopts,aopts1)
}
aopt=mean(aopts)
acold=aopt
descold=t(des)
cdel=100
i=1;
ivalacold={}
for(i in 1:blk.N){
for(j in 1:na){
temp=descold[i,]
if(all(descold[i,]==arrays[j,])) {aopt=acold; del.1[j,]<-c(j,(acold-aopt),aopt); next}
descold[i,]=arrays[j,]
trtin<-contrasts(as.factor(t(descold)),contrasts=FALSE)[as.factor(t(descold)),]
R.trt<-t(trtin)%*%trtin
if (rankMatrix(R.trt)[1]<trt.N) {aopt=1000; del.1[j,]<-c(j,(acold-aopt),aopt); next}
cmato=cmatbd(trt.N,blk.N, 0,t(descold))
egv<-sort(eigen(cmato)$values)
if(egv[2]<0.000001) {aopt=1000; del.1[j,]<-c(j,(acold-aopt),aopt); next}
aopts={};
imcmc=1;
for(imcmc in 1:nmcmc){
rv=1;
theta=rsampb[imcmc];
cmat=cmatbd(trt.N,blk.N,theta,t(descold))
aopts1=sum(diag(ginv(cmat)))
aopts<-rbind(aopts,aopts1)
}
aopt=mean(aopts)
del.n<-del.1[j,]<-c(j,(acold-aopt),aopt)
descold[i,]=temp
}
del.1<-del.1[order(del.1[,3]),]
delbest=t(del.1[1,])
descold[i,]=arrays[delbest[1],]
acold=delbest[3]
#print(acold)
cdel=delbest[2]
ivalacold=rbind(ivalacold, c(i,acold))
if(i>itr.cvrgval) if(all(ivalacold[c(i-(itr.cvrgval-2),i),2]==ivalacold[i-(itr.cvrgval-1),2])) break
}
next.it<- if (irep==1) {desbest.1=t(descold)} else {desbest.1=rbind(desbest.1,t(descold))}
aoptbest.1[irep,]=c(irep,acold)
}
best=aoptbest.1[order(aoptbest.1[,2]),]
nb=best[1,1]
Ascore<-best[1,2]
Aoptde<- desbest.1[c((nb-1)*2+1,nb*2),]
if(trt.N!=3) {tkmessageBox(title="Search completed",message=paste("Search completed",sep=""))}
cnames=paste0("blk",1:blk.N)
dimnames(Aoptde)=list(NULL,cnames)
Aopt_sum2<-list("v"=trt.N,"b"=blk.N,alpha=alpha,beta=beta,nrep=nrep, brep=brep,itr.cvrgval=itr.cvrgval, "OptdesF"=Aoptde,"Optcrtsv" =Ascore)
return(Aopt_sum2)
}
|
/scratch/gouwar.j/cran-all/cranData/Boptbd/R/Baoptbd.R
|
Bdoptbd <-
function(trt.N,blk.N,alpha,beta,nrep,brep,itr.cvrgval) {
#House keeping
arrays=t(combn(trt.N,2))
na=dim(arrays)[1]
del.1<-matrix(10^20,na,3)
desbest.1<-matrix(0,nrep*2,blk.N)
doptbest.1<-matrix(0,nrep,2)
rsampb<-setdiff(unique(round(rbeta(brep,alpha,beta),5)),c(0,1))
nmcmc<-length(rsampb)
for(irep in 1:nrep){
des<-intcbd(trt.N,blk.N)
if(trt.N==blk.N&trt.N>3&irep<(trt.N-1)) {in.desns=matrix(0,(trt.N-3)*2,blk.N)
in.desns0=rbind(seq(1,trt.N),c(seq(1,trt.N)[2:trt.N],1))
for(i in 1:(trt.N-3)) {in.desns01=cbind(rbind(seq(1,(trt.N-i)),c(seq(1,(trt.N-i))[2:(trt.N-i)],1)),rbind(rep(1,i),((trt.N-i+1):trt.N))); in.desns[c((i-1)*2+1,i*2),]=in.desns01}
in.desns=rbind(rbind(seq(1,trt.N),c(seq(1,trt.N)[2:trt.N],1)),in.desns)
des=in.desns[c((irep-1)*2+1,irep*2),]}
dopts={};
imcmc=1;
for(imcmc in 1:nmcmc){
rv=1;
theta=rsampb[imcmc];
cmat<-cmatbd(trt.N,blk.N,theta,des)
degv<-sort(eigen(cmat)$values)
degvp<-degv[2:length(degv)]
dopts1<-prod(1/degvp)
dopts<-rbind(dopts,dopts1)
}
dopt=mean(dopts)
dcold=dopt
descold=t(des)
cdel=100
i=1;
ivaldcold={}
for (i in 1:blk.N){
j=1;
for (j in 1:na){
temp=descold[i,]
if(all(descold[i,]==arrays[j,])) {dopt=dcold; del.1[j,]<-c(j,(dcold-dopt),dopt); next}
descold[i,]=arrays[j,]
trtin<-contrasts(as.factor(t(descold)),contrasts=FALSE)[as.factor(t(descold)),]
R.trt<-t(trtin)%*%trtin
if (rankMatrix(R.trt)[1]<trt.N) {dopt=10^20; del.1[j,]<-c(j,(dcold-dopt),dopt); next}
cmato=cmatbd(trt.N,blk.N, 0,t(descold))
egv<-sort(eigen(cmato)$values)
if(egv[2]<0.000001) {dopt=10^20; del.1[j,]<-c(j,(dcold-dopt),dopt); next}
dopts={};
imcmc=1;
for(imcmc in 1:nmcmc){
rv=1;
theta=rsampb[imcmc];
cmat=cmatbd(trt.N,blk.N,theta,t(descold))
degv<-sort(eigen(cmat)$values)
degvp<-degv[2:length(degv)]
dopts1<-prod(1/degvp)
dopts<-rbind(dopts,dopts1)
}
dopt=mean(dopts)
del.n<-del.1[j,]<-c(j,(dcold-dopt),dopt)
descold[i,]=temp
}
del.1<-del.1[order(del.1[,3]),]
delbest=t(del.1[1,])
descold[i,]=arrays[delbest[1],]
dcold=delbest[3]
cdel=delbest[2]
ivaldcold=rbind(ivaldcold, c(i,dcold))
if(i>itr.cvrgval) if(all(ivaldcold[c(i-(itr.cvrgval-2),i),2]==ivaldcold[i-(itr.cvrgval-1),2])) break
}
if (irep==1) {desbest.1=t(descold)} else {desbest.1=rbind(desbest.1,t(descold))}
doptbest.1[irep,]=c(irep,dcold)
}
best=doptbest.1[order(doptbest.1[,2]),]
nb=best[1,1]
Dscore<-best[1,2]
Doptde<- desbest.1[c((nb-1)*2+1,nb*2),]
tkmessageBox(title="Search completed",message=paste("Search completed",sep=""))
cnames=paste0("blk",1:blk.N)
dimnames(Doptde)=list(NULL,cnames)
Dopt_sum2<-list("v"=trt.N,"b"=blk.N,alpha=alpha,beta=beta,nrep=nrep, brep=brep,itr.cvrgval=itr.cvrgval, "OptdesF"=Doptde,"Optcrtsv" =Dscore)
return(Dopt_sum2)
}
|
/scratch/gouwar.j/cran-all/cranData/Boptbd/R/Bdoptbd.R
|
Boptbd <-
function(trt.N,blk.N,alpha,beta,nrep,brep,itr.cvrgval,Optcrit="",...)UseMethod("Boptbd")
|
/scratch/gouwar.j/cran-all/cranData/Boptbd/R/Boptbd.R
|
Boptbd.default <-
function(trt.N,blk.N,alpha,beta,nrep,brep,itr.cvrgval,Optcrit="",...)
{
trt.N=as.numeric(trt.N)
blk.N=as.numeric(blk.N)
alpha=as.numeric(alpha)
beta=as.numeric(beta)
brep=as.numeric(brep)
nrep=as.numeric(nrep)
itr.cvrgval=as.numeric(itr.cvrgval)
#"===================================================================================================="
if(is.na(alpha)|alpha<=0){
tkmessageBox(title="Error",message=paste("Please insert correct value of alpha, it should be greater than 0, click OK to reset.",sep=""),icon = "error");
stop("Wrong value of 'alpha', it should be greater than 0")
}#end of if
if(is.na(beta)|beta<=0){
tkmessageBox(title="Error",message=paste("Please insert correct value of beta, it should be greater than 0, click OK to reset.",sep=""),icon = "error");
stop("Wrong value of 'beta', it should be between 0")
}#end of if
if(is.na(trt.N)|is.na(blk.N)|trt.N!=round(trt.N)|blk.N!=round(blk.N)) {
tkmessageBox(title="Error",message=paste("Please insert correct format of the number of treatments and arrays. The number of treatments and arrays should be an integer, click OK to reset the values.",sep=""),icon = "error");
stop("Wrong format of 'trt.N' and/or 'blk.N', both should be an integer")
}#end of if
if(trt.N<3|blk.N<3){
tkmessageBox(title="Error",message=paste("The number of blocks and treatments should be greater than or equal to 3, click Ok to reset.",sep=""),icon = "error");
stop("Very small value of number of treatments and/or blocks, minimum value of the two is 3")
}#end of if
if(trt.N-blk.N>1){
tkmessageBox(title="Error",message=paste("The number of arrays should be greater than or equal to the number of treatments minus one, click Ok to reset.",sep=""),icon = "error");
stop("The number of treatments are larger than the number of arrays minus one (trt.N>blk.N-1)")
}#end of if
if(trt.N>10|blk.N>10){
tkmessageBox(title="Information",message=paste("This might take some minutes, please be patient...",sep=""))
}#end of if
if(is.na(itr.cvrgval)|itr.cvrgval<2|itr.cvrgval!=round(itr.cvrgval)){
tkmessageBox(title="Error",message=paste("The number of iteration for the exchange procedure should be a positive integer greater than or equal to two, click OK to reset.",sep=""),icon = "error");
stop("Wrong value of 'itr.cvrgval', it should be greater than or equal to two (only positive integer values)")
}#end of if
if(is.na(nrep)|nrep<2|nrep!=round(nrep)){
tkmessageBox(title="Error",message=paste("The number of replications should be a positive integer greater than or equal to two, click OK to reset.",sep=""),icon = "error");
stop("Wrong value of 'nrep', it should be greater than or equal to two (only positive integer values)")
}#end of if
#"===================================================================================================="
if(!is.element(Optcrit,c("A","D"))){stop("The optimality criterion 'Optcrit' is not correctly specified")}
#if(!is.element(Alg,c("trtE","arrayE"))){stop("The algorithm 'Alg' is not correctly specified")}
if(itr.cvrgval>blk.N) itr.cvrgval<-blk.N
if(Optcrit=="A") {
optbd_mae<-Baoptbd(trt.N,blk.N,alpha,beta,nrep,brep,itr.cvrgval)} else if(
Optcrit=="D") {
optbd_mae<-Bdoptbd(trt.N,blk.N,alpha,beta,nrep,brep,itr.cvrgval)} else{
stop("The optimality criterion is not specified")}
#optbd_mae$Alg="Array exchange"} #end of if
optbd_mae$call<-match.call()
optbd_mae$Optcrit<-Optcrit
#optbd_mae$Cmat<-cmatbd.mae(optbd_mae$v,optbd_mae$b,optbd_mae$theta,optbd_mae$OptdesF)
trtin <- contrasts(as.factor(optbd_mae$OptdesF), contrasts = FALSE)[as.factor(optbd_mae$OptdesF), ]
vec1 <- rep(1, optbd_mae$b * 2)
vec_trtr <- t(trtin) %*% vec1
optbd_mae$equireplicate<-all(vec_trtr==vec_trtr[1])
optbd_mae$vtrtrep<-t(vec_trtr)
#"======================================================================================"
titleoptbd<-list(c(" --------------------------------------- ",paste("Title: Bayesian ",Optcrit,"-optimal block design Date:", format(Sys.time(), "%a %b %d %Y %H:%M:%S"),sep=""),
" --------------------------------------- "))
write.table(titleoptbd, file =file.path(tempdir(), paste(Optcrit,"optbd_summary.csv",sep = "")),append=T ,sep = ",", row.names=FALSE, col.names=FALSE)
parcomb<-list(c(" Parametric combination:", "Number of treatments:", "Number of blocks:",
"Alpha value:","Beta value:", "Number of replications:","Number of MCMC selections:","Number of exchange iteration:", "Optimality criterion used:"," ","Design obtained:"),
c(" ",optbd_mae$v,optbd_mae$b,optbd_mae$alpha,optbd_mae$beta,optbd_mae$nrep,optbd_mae$brep,optbd_mae$itr.cvrgval,optbd_mae$Alg,paste(Optcrit,"-optimality criterion",sep="")," "," "))
write.table(parcomb, file = file.path(tempdir(), paste(Optcrit,"optbd_summary.csv",sep = "")),append=T ,sep = ",", row.names=FALSE, col.names=FALSE)
optde<-list("",rbind(paste0("Ary",1:optbd_mae$b),optbd_mae$OptdesF))
write.table(optde, file = file.path(tempdir(), paste(Optcrit,"optbd_summary.csv",sep = "")),append=T ,sep = ",", row.names=FALSE, col.names=FALSE)
write.table(list(c("",paste(Optcrit,"-score value:",sep=""), "Equireplicate:",""),c("",optbd_mae$Optcrtsv,optbd_mae$equireplicate,"")), file = file.path(tempdir(), paste(Optcrit,"optbd_summary.csv",sep = "")),append=T ,sep = ",", row.names=FALSE, col.names=FALSE)
write.table(list(c("Treatment:", "Treatment replication:"),rbind(1:optbd_mae$v,optbd_mae$vtrtrep)), file = file.path(tempdir(), paste(Optcrit,"optbd_summary.csv",sep = "")),append=T ,sep = ",", row.names=FALSE, col.names=FALSE)
optbd_mae$file_loc<-file.path(tempdir(), paste(Optcrit,"optbd_summary.csv",sep = ""))
optbd_mae$file_loc2<-paste("Summary of obtained Bayesian ",Optcrit,"-optimal block design is also saved at:",sep="")
#"======================================================================================"
class(optbd_mae)<-"Boptbd"
optbd_mae
}
|
/scratch/gouwar.j/cran-all/cranData/Boptbd/R/Boptbd.default.R
|
cmatbd <-
function(trt.N,blk.N,theta,des){
k=2
trtin<-contrasts(as.factor(des),contrasts=FALSE)[as.factor(des),]
blk.1<-rep(1:blk.N,each=2)
blkin<-contrasts(as.factor(blk.1),contrasts=FALSE)[as.factor(blk.1),]
vec.1<-rep(1,blk.N*2)
R.trt<-t(trtin)%*%trtin
N.tb<-t(trtin)%*%blkin
r.trt<-t(trtin)%*%vec.1
cmat<-R.trt-(1/k)*(N.tb%*%t(N.tb))+theta*((1/k)*(N.tb%*%t(N.tb))-(1/(blk.N*k))*(r.trt%*%t(r.trt)))
cmat
}
|
/scratch/gouwar.j/cran-all/cranData/Boptbd/R/cmatbd.R
|
fixparBbd <-
function(Optcrit){
trt.I<-tclVar(paste("3"));#Number of treatments (default)
blk.I<-tclVar(paste("3"));#Number of blocks (default)
alpha.I<-tclVar(paste("0.1"));#Alpha value (default)
beta.I<-tclVar(paste("0.1"));#Beta value (default)
brep.I<-tclVar(paste("10"));#Nuber of MCMC selection (default)
rep.I<-tclVar(paste("10"));#Number of replications (default)
itrcvrgval.I<-tclVar(paste("6"));#Initial convergence value (default)
cbValue.I<-tclVar("0")
cbValue3.I<-tclVar("0")
#"=============================================================================="
optcrtF<-function(Optcrit){
nrep<-as.numeric(tclvalue(rep.I))
trt.N<-as.numeric(tclvalue(trt.I))
blk.N<-as.numeric(tclvalue(blk.I))
alpha<-as.numeric(tclvalue(alpha.I))
beta<-as.numeric(tclvalue(beta.I))
brep<-as.numeric(tclvalue(brep.I))
cbVal<-as.numeric(tclvalue(cbValue.I))
itr.cvrgval<-as.numeric(tclvalue(itrcvrgval.I))
if(itr.cvrgval>blk.N) itr.cvrgval<-blk.N
cbVal3<-as.numeric(tclvalue(cbValue3.I))
if(Optcrit=="A"){
optbdFS=Boptbd(trt.N,blk.N,alpha,beta,nrep,brep,itr.cvrgval,Optcrit="A")}
if(Optcrit=="D") {
optbdFS=Boptbd(trt.N,blk.N,alpha,beta,nrep,brep,itr.cvrgval,Optcrit="D")}
if(cbVal3=="1") optbdFS=summary(optbdFS)
print(optbdFS)
if(cbVal=="1") {graphoptBbd(trt.N, blk.N,alpha,beta,optbdFS$OptdesF,Optcrit)}
}
#"=============================================================================="
fiPar<-tktoplevel()
fontHeading<- tkfont.create(family="times",size=40,weight="bold")
fontHeading3<-tkfont.create(family="times",size=10,weight="bold")
fontHeading2<-tkfont.create(family="times",size=14,weight="bold")
fontHeading4<-tkfont.create(family="times",size=12,weight="bold")
tkwm.title(fiPar,"Set parameter values")
fiParF<-tkframe(fiPar)
fiParFup<- tkframe(fiParF,relief="groove",borderwidth=2)
fiParFmid<-tkframe(fiParF,relief="sunken",borderwidth=2)
fiParFlow<-tkframe(fiParF,relief="sunken",borderwidth=2)
fiParFlow2<-tkframe(fiParF,relief="groove",borderwidth=2)
trt.in<-trt.I
blk.in<-blk.I
alpha.in<-alpha.I
beta.in<-beta.I
brep.in<-brep.I
rep.in<-rep.I
itrcvrgval.in<-itrcvrgval.I
cbValue.in<-cbValue.I
cbValue3.in<-cbValue3.I
trt.i1<-tkentry(fiParFup,width=11,textvariable=trt.in)
blk.i1<-tkentry(fiParFup,width=11,textvariable=blk.in)
alpha.i1<-tkentry(fiParFup,width=11,textvariable=alpha.in)
beta.i1<-tkentry(fiParFup,width=11,textvariable=beta.in)
brep.i1<-tkentry(fiParFup,width=11,textvariable=brep.in)
rep.i1<-tkentry(fiParFup,width=11,textvariable=rep.in)
itrcvrgval.i1<-tkentry(fiParFup,width=11,textvariable=itrcvrgval.in)
cbValue.i1<-tkcheckbutton(fiPar)
tkconfigure(cbValue.i1,variable=cbValue.in)
cbValue.i3<-tkcheckbutton(fiPar)
tkconfigure(cbValue.i3,variable=cbValue3.in)
tkgrid(tklabel(fiParF,text=" Fix Value of Parameters ",font=fontHeading2))
tkgrid(tklabel(fiParFup,text="Number of treatments: "),trt.i1)
tkgrid(tklabel(fiParFup,text="Number of blocks (arrays): "),blk.i1)
tkgrid(tklabel(fiParFup,text="Alpha value: "),alpha.i1)
tkgrid(tklabel(fiParFup,text="Beta value: "),beta.i1)
tkgrid(tklabel(fiParFup,text="Number of MC selections: "),brep.i1)
tkgrid(tklabel(fiParFup,text="Number of replications: "),rep.i1)
tkgrid(tklabel(fiParFup,text="Iterations for exchange Procedure: "),itrcvrgval.i1)
tkgrid(tklabel(fiParFmid,text="Show graphical layout ", font=fontHeading4),cbValue.i1)
tkgrid(tklabel(fiParFmid,text="Show Summary result ", font=fontHeading4),cbValue.i3)
tkgrid(tklabel(fiParFlow,text=" ",font=0.01))#empty line
exitFP<-function() {
closeQ=tkmessageBox(title = "Exit set parameter values", message = "You are leaving set parameter values window",
icon = "info", type = "okcancel", default = "cancel")
if(as.character(closeQ)=="ok") tkdestroy(fiPar)
}#end of exitFP
exit.but2a<-tkbutton(fiParF,text="Exit",command=exitFP,width=10)
serch.but<-function(Optcrit){
if (Optcrit=="A") but.A<-tkgrid(tkbutton(fiParFlow2,text="Search Bayesian A-opt block design",command=function()optcrtF("A"),width=27), exit.but2a)
if (Optcrit=="D") but.A<-tkgrid(tkbutton(fiParFlow2,text="Search D-opt block design",command=function()optcrtF("D"),width=22), exit.but2a)
return(but.A)
}#end of serch.but
tkgrid(tklabel(fiParFlow2,text=" ",font=0.00001))
serch.but(Optcrit)
tkgrid(tklabel(fiParFlow2,text=" ",font=0.00001))
tkgrid(fiParFup)
tkgrid(tklabel(fiParF,text="---------------------------------", font=fontHeading3))
tkgrid(fiParFlow)
tkgrid(tklabel(fiParF,text="---------------------------------", font=fontHeading3))
tkgrid(fiParFmid)
tkgrid(tklabel(fiParF,text="---------------------------------", font=fontHeading3))
tkgrid(fiParFlow2)
tkgrid(fiParF)
}
|
/scratch/gouwar.j/cran-all/cranData/Boptbd/R/fixparBbd.R
|
graphoptBbd <-
function(trt.N, blk.N,alpha,beta,OptdesF,Optcrit) {
trtblkthetano<-paste("(",paste(trt.N, blk.N, alpha, beta, sep=", "),")",sep="")
NOptcrtr<-paste(Optcrit,"-optimal",sep="")#name of optimality criteria
NOptcrtrG<-paste("Graph_layout_B",Optcrit,"optbd",sep="")#name of folder where the graphical layout will be saved
NOptcrtrG2<-paste("_Gout_B",Optcrit,"optbd.pdf",sep="")
NgoutT=paste("Graphical layout of Bayesian",NOptcrtr, "block", "design", sep=" ")
NgoutT1=paste(paste("(v, b, alpha, beta) =",trtblkthetano,sep=" "))
graph.des <- make_graph(as.numeric(as.factor(OptdesF)), directed = FALSE)
graph.desid <- tkplot(graph.des, canvas.width=515, canvas.height=500,layout=layout.kamada.kawai,vertex.color="cyan",edge.color="black")
canvas <- tk_canvas(graph.desid)
padding <- 100
coords <- norm_coords(layout=layout.kamada.kawai(graph.des), 0+padding, 450-padding,
50+padding, 500-padding)
tk_set_coords(graph.desid, coords)
width <- as.numeric(tkcget(canvas, "-width"))
height <- as.numeric(tkcget(canvas, "-height"))
tkcreate(canvas, "text", width/2, 25, text=NgoutT,
justify="center", font=tcltk::tkfont.create(family="helvetica",size=12,weight="bold"))
tkcreate(canvas, "text", width/2, 45, text=NgoutT1,
justify="center", font=tcltk::tkfont.create(family="helvetica",size=12,weight="bold"))
graph.OutlayoptBlk<-tempdir()
obtdes.goutloptBlk<-paste(graph.OutlayoptBlk,paste(trtblkthetano,NOptcrtrG2,sep=""),sep="/")
obtdes.goutloptBlk2<-paste(graph.OutlayoptBlk,trtblkthetano,sep="\\")
pdf(file=obtdes.goutloptBlk)
plot(graph.des,edge.arrow.size=5, vertex.size=20, margin=0.5,
layout=layout.kamada.kawai,vertex.color="cyan",edge.color="black")
title(paste("Graphical layout of Bayesian ", Optcrit,"-optimal block design",sep=""),
sub = paste("Bayesian ",Optcrit,"-optimal block design",sep=""),cex.main = 1, font.main= 1, col.main= "black")
mtext(paste("(v, b, alpha, beta) = (",paste(trt.N, blk.N, alpha, beta, sep=", "),")",sep=" "), line = -0.50, col = "blue", font = 1)
dev.off()
file_loc<-graph.OutlayoptBlk
file_loc2<-paste("Graphical layout of Bayesian ", NOptcrtr, " block design is also saved in .pdf at:",sep=" ")
message(file_loc2,"\n",file_loc,"\n\n")
}
|
/scratch/gouwar.j/cran-all/cranData/Boptbd/R/graphoptBbd.R
|
intcbd <-
function(trt.N,blk.N){
arrays<-t(combn(trt.N,2))
na=dim(arrays)[1]
Con.egv.check=0.00000001
while(Con.egv.check<0.000001){
All.trt.check=trt.N-1
while(All.trt.check <trt.N){
des.p<-if(blk.N>na) {c(sample(1:na,na,replace=FALSE), sample(1:na,blk.N-na,replace=TRUE))} else {
sample(1:na,blk.N,replace=FALSE)}
des<-t(arrays[des.p,])
trtin<-contrasts(as.factor(des),contrasts=FALSE)[as.factor(des),]
R.trt<-t(trtin)%*%trtin
All.trt.check<-rankMatrix(R.trt)
}
cmato=cmatbd(trt.N,blk.N, 0,des)
egv<-sort(eigen(cmato)$values)
Con.egv.check<-egv[2]
}
return(des)
}
|
/scratch/gouwar.j/cran-all/cranData/Boptbd/R/intcbd.R
|
mmenuBbd <-
function(){
fontHeading<- tkfont.create(family="times",size=40,weight="bold")#,slant="italic")
fontHeading3<-tkfont.create(family="times",size=10,weight="bold")
AMVDEopt.top<-tktoplevel()
tkwm.title(AMVDEopt.top,"Bayesian Optimal Block Designs")
tkgrid(tklabel(AMVDEopt.top,text=" Bayesian_optbd 1.0.5 ",font=fontHeading))
tkgrid(tklabel(AMVDEopt.top,text="",font=fontHeading))
Fixp.butA<-tkbutton(AMVDEopt.top,text="Bayesian A-Optimal Block Design",font=fontHeading3,command=function()fixparBbd("A"),width=30)
Fixp.butD<-tkbutton(AMVDEopt.top,text="Bayesian D-Optimal Block Design",font=fontHeading3,command=function() fixparBbd("D"),width=30)
exitMM<-function() {
closeQ=tkmessageBox(title = "Bye...", message = "Bye..., Enjoy your optimal design",
icon = "info", type = "okcancel", default = "cancel")
if(as.character(closeQ)=="ok") tkdestroy(AMVDEopt.top)
}#end of exitMM
ExitWin.but<-tkbutton(AMVDEopt.top,text="Exit",font=fontHeading3,command=exitMM,width=15)
tkgrid(Fixp.butA)
tkgrid(tklabel(AMVDEopt.top,text="",font=fontHeading3))
tkgrid(Fixp.butD)
tkgrid(tklabel(AMVDEopt.top,text="",font=fontHeading3))
tkgrid(ExitWin.but)
tkgrid(tklabel(AMVDEopt.top,text="",font=fontHeading)) }
|
/scratch/gouwar.j/cran-all/cranData/Boptbd/R/mmenuBbd.R
|
print.Boptbd <-
function(x,...)
{
cat("\n --------------------------------------- \n")
cat("Title: Bayesian ",x$Optcrit,"-optimal block design ","Date: ", format(Sys.time(), "%a %b %d %Y %H:%M:%S"),"\n",sep="")
cat(" --------------------------------------- \n")
cat("Call:\n")
print(x$call)
cat("\nResultant Bayesian ",x$Optcrit,"-optimal block design:\n",sep="")
cat("\n")
print(data.frame(x$OptdesF))
cat("\n", x$file_loc2,"\n", x$file_loc,"\n")
cat("\n")
}
|
/scratch/gouwar.j/cran-all/cranData/Boptbd/R/print.Boptbd.R
|
print.summary.Boptbd <-
function(x,...)
{
cat("\n --------------------------------------- \n")
cat("Title: ","Bayesian ",x$Optcrit,"-optimal block design ","Date: ", format(Sys.time(), "%a %b %d %Y %H:%M:%S"),"\n",sep="")
cat(" --------------------------------------- \n")
cat("Call:\n")
print(x$call)
cat("\nParametric combinations:\n")
cat("\nNumber of treatments: ", x$v, "\n")
cat("Number of blocks: ", x$b, "\n")
cat("Alpha value: ", x$alpha, "\n")
cat("Beta value: ", x$beta, "\n")
cat("Number of MC selections: ", x$brep, "\n")
cat("Number of replications: ", x$nrep, "\n")
cat("Number of exchange iteration: ", x$itr.cvrgval, "\n")
#cat("Algorithm used: ", x$Alg, "\n")
cat("Optimality criterion used: Bayesian ", x$Optcrit, "-optimality criteria\n",sep="")
cat("\nResultant Bayesian ",x$Optcrit,"-optimal block design:\n",sep="")
cat("\n")
print(data.frame(x$OptdesF))
cat("\n")
cat(x$Optcrit,"-Score value: ", x$Optcrtsv, "\n",sep="")
plot(x$grphlt,edge.arrow.size=5, vertex.size=20, margin=0.5,
layout=layout.kamada.kawai,vertex.color="cyan",edge.color="black")
title(paste("Graphical layout of Bayesian", paste(x$Optcrit,"-optimal block design",sep=""),sep=" "),
sub = NULL,cex.main = 1, font.main= 1, col.main= "black")
mtext(paste("(v, b, alpha,beta) =", " (",paste(x$v, x$b, x$alpha, x$beta, sep=", "),")",sep=""), line = -0.50, col = "blue", font = 1)
cat("\n", x$file_loc2,"\n", x$file_loc,"\n")
cat("\n")
}
|
/scratch/gouwar.j/cran-all/cranData/Boptbd/R/print.summary.Boptbd.R
|
summary.Boptbd <-
function(object,...)
{
optbd_maes<-object
optbd_maes$grphlt<-make_graph(as.numeric(as.factor(object$OptdesF)), directed = FALSE)
class(optbd_maes)<-"summary.Boptbd"
optbd_maes
}
|
/scratch/gouwar.j/cran-all/cranData/Boptbd/R/summary.Boptbd.R
|
# Core of Boruta
#' @export
#' @rdname Boruta
Boruta<-function(x,...)
UseMethod("Boruta")
#' Feature selection with the Boruta algorithm
#'
#' Boruta is an all relevant feature selection wrapper algorithm, capable of working with any classification method that output variable importance measure (VIM); by default, Boruta uses Random Forest.
#' The method performs a top-down search for relevant features by comparing original attributes' importance with importance achievable at random, estimated using their permuted copies, and progressively eliminating irrelevant features to stabilise that test.
#' @rdname Boruta
#' @method Boruta default
#' @param x data frame of predictors.
#' @param y response vector; factor for classification, numeric vector for regression, \code{Surv} object for survival (supports depends on importance adapter capabilities).
#' @param getImp function used to obtain attribute importance.
#' The default is getImpRfZ, which runs random forest from the \code{ranger} package and gathers Z-scores of mean decrease accuracy measure.
#' It should return a numeric vector of a size identical to the number of columns of its first argument, containing importance measure of respective attributes.
#' Any order-preserving transformation of this measure will yield the same result.
#' It is assumed that more important attributes get higher importance. +-Inf are accepted, NaNs and NAs are treated as 0s, with a warning.
#' @param pValue confidence level. Default value should be used.
#' @param mcAdj if set to \code{TRUE}, a multiple comparisons adjustment using the Bonferroni method will be applied. Default value should be used; older (1.x and 2.x) versions of Boruta were effectively using \code{FALSE}.
#' @param maxRuns maximal number of importance source runs.
#' You may increase it to resolve attributes left Tentative.
#' @param holdHistory if set to \code{TRUE}, the full history of importance is stored and returned as the \code{ImpHistory} element of the result.
#' Can be used to decrease a memory footprint of Boruta in case this side data is not used, especially when the number of attributes is huge; yet it disables plotting of such made \code{Boruta} objects and the use of the \code{\link{TentativeRoughFix}} function.
#' @param doTrace verbosity level. 0 means no tracing, 1 means reporting decision about each attribute as soon as it is justified, 2 means the same as 1, plus reporting each importance source run, 3 means the same as 2, plus reporting of hits assigned to yet undecided attributes.
#' @param ... additional parameters passed to \code{getImp}.
#' @return An object of class \code{Boruta}, which is a list with the following components:
#' \item{finalDecision}{a factor of three value: \code{Confirmed}, \code{Rejected} or \code{Tentative}, containing final result of feature selection.}
#' \item{ImpHistory}{a data frame of importances of attributes gathered in each importance source run.
#' Beside predictors' importances, it contains maximal, mean and minimal importance of shadow attributes in each run.
#' Rejected attributes get \code{-Inf} importance.
#' Set to \code{NULL} if \code{holdHistory} was given \code{FALSE}.}
#' \item{timeTaken}{time taken by the computation.}
#' \item{impSource}{string describing the source of importance, equal to a comment attribute of the \code{getImp} argument.}
#' \item{call}{the original call of the \code{Boruta} function.}
#' @details Boruta iteratively compares importances of attributes with importances of shadow attributes, created by shuffling original ones.
#' Attributes that have significantly worst importance than shadow ones are being consecutively dropped.
#' On the other hand, attributes that are significantly better than shadows are admitted to be Confirmed.
#' Shadows are re-created in each iteration.
#' Algorithm stops when only Confirmed attributes are left, or when it reaches \code{maxRuns} importance source runs.
#' If the second scenario occurs, some attributes may be left without a decision.
#' They are claimed Tentative.
#' You may try to extend \code{maxRuns} or lower \code{pValue} to clarify them, but in some cases their importances do fluctuate too much for Boruta to converge.
#' Instead, you can use \code{\link{TentativeRoughFix}} function, which will perform other, weaker test to make a final decision, or simply treat them as undecided in further analysis.
#' @references Miron B. Kursa, Witold R. Rudnicki (2010). Feature Selection with the Boruta Package.
#' \emph{Journal of Statistical Software, 36(11)}, p. 1-13.
#' URL: \doi{10.18637/jss.v036.i11}
#' @export
#' @examples
#' set.seed(777)
#'
#' #Boruta on the "small redundant XOR" problem; read ?srx for details
#' data(srx)
#' Boruta(Y~.,data=srx)->Boruta.srx
#'
#' #Results summary
#' print(Boruta.srx)
#'
#' #Result plot
#' plot(Boruta.srx)
#'
#' #Attribute statistics
#' attStats(Boruta.srx)
#'
#' #Using alternative importance source, rFerns
#' Boruta(Y~.,data=srx,getImp=getImpFerns)->Boruta.srx.ferns
#' print(Boruta.srx.ferns)
#'
#' #Verbose
#' Boruta(Y~.,data=srx,doTrace=2)->Boruta.srx
#'
#' \dontrun{
#' #Boruta on the iris problem extended with artificial irrelevant features
#' #Generate said features
#' iris.extended<-data.frame(iris,apply(iris[,-5],2,sample))
#' names(iris.extended)[6:9]<-paste("Nonsense",1:4,sep="")
#' #Run Boruta on this data
#' Boruta(Species~.,data=iris.extended,doTrace=2)->Boruta.iris.extended
#' #Nonsense attributes should be rejected
#' print(Boruta.iris.extended)
#' }
#'
#' \dontrun{
#' #Boruta on the HouseVotes84 data from mlbench
#' library(mlbench); data(HouseVotes84)
#' na.omit(HouseVotes84)->hvo
#' #Takes some time, so be patient
#' Boruta(Class~.,data=hvo,doTrace=2)->Bor.hvo
#' print(Bor.hvo)
#' plot(Bor.hvo)
#' plotImpHistory(Bor.hvo)
#' }
#' \dontrun{
#' #Boruta on the Ozone data from mlbench
#' library(mlbench); data(Ozone)
#' library(randomForest)
#' na.omit(Ozone)->ozo
#' Boruta(V4~.,data=ozo,doTrace=2)->Bor.ozo
#' cat('Random forest run on all attributes:\n')
#' print(randomForest(V4~.,data=ozo))
#' cat('Random forest run only on confirmed attributes:\n')
#' print(randomForest(ozo[,getSelectedAttributes(Bor.ozo)],ozo$V4))
#' }
#' \dontrun{
#' #Boruta on the Sonar data from mlbench
#' library(mlbench); data(Sonar)
#' #Takes some time, so be patient
#' Boruta(Class~.,data=Sonar,doTrace=2)->Bor.son
#' print(Bor.son)
#' #Shows important bands
#' plot(Bor.son,sort=FALSE)
#' }
Boruta.default<-function(x,y,pValue=0.01,mcAdj=TRUE,maxRuns=100,doTrace=0,holdHistory=TRUE,getImp=getImpRfZ,...){
#Timer starts... now!
timeStart<-Sys.time()
#Extract the call to store in output
cl<-match.call()
cl[[1]]<-as.name('Boruta')
#Convert x into a data.frame
if(!is.data.frame(x))
x<-data.frame(x)
##Some checks on x & y
if(length(grep('^shadow',names(x)))>0)
stop('Attributes with names starting from "shadow" are reserved for internal use. Please rename them.')
if(maxRuns<11)
stop('maxRuns must be greater than 10.')
##Expands the information system with newly built random attributes and calculates importance
addShadowsAndGetImp<-function(decReg,runs){
#xSha is going to be a data frame with shadow attributes; time to init it.
xSha<-x[,decReg!="Rejected",drop=F]
while(dim(xSha)[2]<5) xSha<-cbind(xSha,xSha); #There must be at least 5 random attributes.
#Now, we permute values in each attribute
nSha<-ncol(xSha)
data.frame(lapply(xSha,sample))->xSha
names(xSha)<-paste('shadow',1:nSha,sep="")
#Notifying user of our progress
if(doTrace>1)
message(sprintf(' %s. run of importance source...',runs))
#Calling importance source; "..." can be used by the user to pass rf attributes (for instance ntree)
impRaw<-getImp(cbind(x[,decReg!="Rejected"],xSha),y,...)
if(!is.numeric(impRaw))
stop("getImp result is not a numeric vector. Please check the given getImp function.")
if(length(impRaw)!=sum(decReg!="Rejected")+ncol(xSha))
stop("getImp result has a wrong length. Please check the given getImp function.")
if(any(is.na(impRaw)|is.nan(impRaw))){
impRaw[is.na(impRaw)|is.nan(impRaw)]<-0
warning("getImp result contains NA(s) or NaN(s); replacing with 0(s), yet this is suspicious.")
}
#Importance must have Rejected attributes put on place and filled with -Infs
imp<-rep(-Inf,nAtt+nSha);names(imp)<-c(attNames,names(xSha))
impRaw->imp[c(decReg!="Rejected",rep(TRUE,nSha))]
shaImp<-imp[(nAtt+1):length(imp)];imp[1:nAtt]->imp
return(list(imp=imp,shaImp=shaImp))
}
##Assigns hits
assignHits<-function(hitReg,curImp){
curImp$imp>max(curImp$shaImp)->hits
if(doTrace>2){
uncMask<-decReg=="Tentative"
intHits<-sum(hits[uncMask])
if(intHits>0)
message(sprintf("Assigned hit to %s attribute%s out of %s undecided.",sum(hits[uncMask]),if(intHits==1) "" else "s",sum(uncMask)))
else
message("None of undecided attributes scored a hit.")
}
hitReg[hits]<-hitReg[hits]+1
return(hitReg)
}
##Checks whether number of hits is significant
doTests<-function(decReg,hitReg,runs){
pAdjMethod<-ifelse(mcAdj[1],'bonferroni','none')
#If attribute is significantly more frequent better than shadowMax, its claimed Confirmed
toAccept<-stats::p.adjust(stats::pbinom(hitReg-1,runs,0.5,lower.tail=FALSE),method=pAdjMethod)<pValue
(decReg=="Tentative" & toAccept)->toAccept
#If attribute is significantly more frequent worse than shadowMax, its claimed Rejected (=irrelevant)
toReject<-stats::p.adjust(stats::pbinom(hitReg,runs,0.5,lower.tail=TRUE),method=pAdjMethod)<pValue
(decReg=="Tentative" & toReject)->toReject
#Update decReg
decReg[toAccept]<-"Confirmed";"Rejected"->decReg[toReject]
#Report progress
if(doTrace>0){
nAcc<-sum(toAccept)
nRej<-sum(toReject)
nLeft<-sum(decReg=="Tentative")
if(nAcc+nRej>0)
message(sprintf("After %s iterations, +%s: ",runs,format(difftime(Sys.time(),timeStart),digits=2)))
if(nAcc>0)
message(sprintf(" confirmed %s attribute%s: %s",
nAcc,ifelse(nAcc==1,'','s'),.attListPrettyPrint(attNames[toAccept])))
if(nRej>0)
message(sprintf(" rejected %s attribute%s: %s",
nRej,ifelse(nRej==1,'','s'),.attListPrettyPrint(attNames[toReject])))
if(nAcc+nRej>0)
if(nLeft>0){
message(sprintf(" still have %s attribute%s left.\n",
nLeft,ifelse(nLeft==1,'','s')))
}else{
if(nAcc+nRej>0) message(" no more attributes left.\n")
}
}
return(decReg)
}
##Creating some useful constants
nAtt<-ncol(x); nrow(x)->nObjects
attNames<-names(x); c("Tentative","Confirmed","Rejected")->confLevels
##Initiate state
decReg<-factor(rep("Tentative",nAtt),levels=confLevels)
hitReg<-rep(0,nAtt);names(hitReg)<-attNames
impHistory<-list()
runs<-0
##Main loop
while(any(decReg=="Tentative") && (runs+1->runs)<maxRuns){
curImp<-addShadowsAndGetImp(decReg,runs)
hitReg<-assignHits(hitReg,curImp)
decReg<-doTests(decReg,hitReg,runs)
#If needed, update impHistory with scores obtained in this iteration
if(holdHistory){
imp<-c(curImp$imp,
shadowMax=max(curImp$shaImp),
shadowMean=mean(curImp$shaImp),
shadowMin=min(curImp$shaImp))
impHistory<-c(impHistory,list(imp))
}
}
##Building result
impHistory<-do.call(rbind,impHistory)
names(decReg)<-attNames
ans<-list(finalDecision=decReg,ImpHistory=impHistory,
pValue=pValue,maxRuns=maxRuns,light=TRUE,mcAdj=mcAdj,
timeTaken=Sys.time()-timeStart,roughfixed=FALSE,call=cl,
impSource=comment(getImp))
"Boruta"->class(ans)
return(ans)
}
.attListPrettyPrint<-function(x,limit=5){
x<-sort(x)
if(length(x)<limit+1)
return(sprintf("%s;",paste(x,collapse=", ")))
sprintf("%s and %s more;",paste(utils::head(x,limit),collapse=", "),length(x)-limit)
}
#' @rdname Boruta
#' @method Boruta formula
#' @param formula alternatively, formula describing model to be analysed.
#' @param data in which to interpret formula.
#' @export
Boruta.formula<-function(formula,data,...){
make_df(formula,data,parent.frame())->d
##Run Boruta
ans<-Boruta.default(d$X,d$Y,...)
ans$call<-match.call()
ans$call[[1]]<-as.name('Boruta')
formula->ans$call[["formula"]]
return(ans)
}
#' Print Boruta object
#'
#' Print method for the Boruta objects.
#' @method print Boruta
#' @param x an object of a class Boruta.
#' @param ... additional arguments passed to \code{\link{print}}.
#' @return Invisible copy of \code{x}.
#' @export
print.Boruta<-function(x,...){
stopifnot(inherits(x,'Boruta'))
cat(paste('Boruta performed ',dim(x$ImpHistory)[1],' iterations in ',format(x$timeTaken),'.\n',sep=''))
if(x$roughfixed) cat(paste('Tentatives roughfixed over the last ',x$averageOver,' iterations.\n',sep=''))
if(sum(x$finalDecision=='Confirmed')==0){
cat(' No attributes deemed important.\n')} else {
writeLines(strwrap(paste(sum(x$finalDecision=='Confirmed'),' attributes confirmed important: ',
.attListPrettyPrint(names(x$finalDecision[x$finalDecision=='Confirmed']))),indent=1))
}
if(sum(x$finalDecision=='Rejected')==0){
cat(' No attributes deemed unimportant.\n')} else {
writeLines(strwrap(paste(sum(x$finalDecision=='Rejected'),' attributes confirmed unimportant: ',
.attListPrettyPrint(names(x$finalDecision[x$finalDecision=='Rejected']))),indent=1))
}
if(sum(x$finalDecision=='Tentative')!=0){
writeLines(strwrap(paste(sum(x$finalDecision=='Tentative'),' tentative attributes left: ',
.attListPrettyPrint(names(x$finalDecision[x$finalDecision=='Tentative']))),indent=1))
}
invisible(x)
}
#' Small redundant XOR data
#'
#' A synthetic data set with 32 rows corresponding to all combinations of values of five logical features, A, B, N1, N2 and N3.
#' The decision Y is equal to A xor B, hence N1--N3 are irrelevant attributes.
#' The set also contains 3 additional features, A or B (AoB), A and B (AnB) and not A (nA), which provide a redundant, but still relevant way to reconstruct Y.
#'
#' This is set is an easy way to demonstrate the difference between all relevant feature selection methods, which should select all features except N1--N3, and minimal optimal ones, which will probably ignore most of them.
#' @format A data frame with 8 predictors, 4 relevant: A, B, AoB, AnB and nA, as well as 3 irrelevant N1, N2 and N3, and decision attribute Y.
#' @source \url{https://blog.mbq.me/relevance-and-redundancy/}
#' @usage data(srx)
"srx"
|
/scratch/gouwar.j/cran-all/cranData/Boruta/R/Boruta.R
|
make_df<-function(formula,data,enc){
if(missing(enc)) enc<-parent.frame()
if(missing(data)){
env<-enc
have<-c()
}else{
if(!is.data.frame(data)) stop("data must be a data.frame")
env<-data
have<-names(data)
}
to_delete<-c()
to_add<-c()
new_features<-list()
has_dot<-FALSE
f<-stats::as.formula(formula)
Ye<-f[[2]]
Y<-eval(Ye,env,enc)
Yn<-deparse(Ye)
if(is.symbol(Ye)&&(Yn%in%have)) to_delete<-Yn
f[[3]]->f
while(TRUE){
if(length(f)==3){
oper<-deparse(f[[1]])
element<-f[[3]]
if(length(element)!=1)
if(!identical(element[[1]],quote(I)))
stop("Invalid sub-expression ",deparse(element))
}else{
#This is the last element
oper<-'+'
element<-f
}
if(oper=='-'){
if(!is.symbol(element))
stop(sprintf("Cannot omit something that is not a feature name (%s)",deparse(element)))
element<-deparse(element)
if(!(element%in%have))
stop(sprintf("Cannot omit %s which is not in data",element))
to_delete<-c(to_delete,element)
}else if(oper=='+'){
if(is.symbol(element)){
deparse(element)->en
if(en=='.'){
if(missing(data)) stop("Cannot use `.` without data")
has_dot<-TRUE
}else{
if(en%in%have){
to_add<-c(to_add,en)
}else{
eval(element,env,enc)->val
new_features<-c(new_features,stats::setNames(list(val),en))
}
}
}else{
eval(element,env,enc)->val
new_features<-c(new_features,stats::setNames(list(val),deparse(element)))
}
}else
stop(sprintf("Invalid operator `%s`; only `+` & `-` allowed",oper))
if(length(f)<3) break
f<-f[[2]]
}
if(has_dot){
to_delete<-setdiff(to_delete,to_add)
X<-data
if(length(to_delete)>0)
X<-X[,setdiff(names(X),to_delete),drop=FALSE]
if(length(new_features)>0)
X<-data.frame(X,new_features)
}else{
if(!missing(data)){
X<-data[,setdiff(to_add,to_delete),drop=FALSE]
if(length(new_features)>0)
X<-data.frame(X,new_features)
}else if(length(new_features)>0){
X<-data.frame(new_features)
} #else can't happen because of formula syntax properties; Y~ is invalid
}
list(X=X,Y=Y)
}
|
/scratch/gouwar.j/cran-all/cranData/Boruta/R/formula.R
|
# Importance sources
#' randomForest importance adapters
#'
#' Those function is intended to be given to a \code{getImp} argument of \code{\link{Boruta}} function to be called by the Boruta algorithm as an importance source.
#' \code{getImpLegacyRfZ} generates default, normalized permutation importance, \code{getImpLegacyRfRaw} raw permutation importance, finally \code{getImpLegacyRfGini} generates Gini index importance, all using \code{\link[randomForest]{randomForest}} as a Random Forest algorithm implementation.
#' @name getImpLegacyRf
#' @rdname getImpLegacyRf
#' @aliases getImpLegacyRfZ getImpLegacyRfGini getLegacyImpRfRaw
#' @note The \code{getImpLegacyRfZ} function was a default importance source in Boruta versions prior to 5.0; since then \code{\link{ranger}} Random Forest implementation is used instead of \code{\link[randomForest]{randomForest}}, for speed, memory conservation and an ability to utilise multithreading.
#' Both importance sources should generally lead to the same results, yet there are differences.
#'
#' Most notably, ranger by default treats factor attributes as ordered (and works very slow if instructed otherwise with \code{respect.unordered.factors=TRUE}); on the other hand it lifts 32 levels limit specific to \code{\link[randomForest]{randomForest}}.
#' To this end, Boruta decision for factor attributes may be different.
#'
#' Random Forest methods has two main parameters, number of attributes tried at each split and the number of trees in the forest; first one is called \code{mtry} in both implementations, but the second \code{ntree} in \code{\link[randomForest]{randomForest}} and \code{num.trees} in \code{\link{ranger}}.
#' To this end, to maintain compatibility, \code{getImpRf*} functions still accept \code{ntree} parameter relaying it into \code{num.trees}.
#' Still, both parameters take the same defaults in both implementations (square root of the number all all attributes and 500 respectively).
#'
#' Moreover, \code{\link{ranger}} brings some addition capabilities to Boruta, like analysis of survival problems or sticky variables which are always considered on splits.
#'
#' Finally, the results for the same PRNG seed will be different.
#' @param x data frame of predictors including shadows.
#' @param y response vector.
#' @param ... parameters passed to the underlying \code{\link[randomForest]{randomForest}} call; they are relayed from \code{...} of \code{\link{Boruta}}.
#' @examples
#' set.seed(777)
#' #Add some nonsense attributes to iris dataset by shuffling original attributes
#' iris.extended<-data.frame(iris,apply(iris[,-5],2,sample))
#' names(iris.extended)[6:9]<-paste("Nonsense",1:4,sep="")
#' #Run Boruta on this data
#' Boruta(Species~.,getImp=getImpLegacyRfZ,
#' data=iris.extended,doTrace=2)->Boruta.iris.extended
#' #Nonsense attributes should be rejected
#' print(Boruta.iris.extended)
#' @export
getImpLegacyRfZ<-function(x,y,...){
randomForest::randomForest(x,y,
importance=TRUE,keep.forest=FALSE,...)->rf
randomForest::importance(rf,1,scale=TRUE)[,1]
}
comment(getImpLegacyRfZ)<-'randomForest normalized permutation importance'
#' @rdname getImpLegacyRf
#' @export
getImpLegacyRfRaw<-function(x,y,...){
randomForest::randomForest(x,y,
importance=TRUE,keep.forest=FALSE,...)->rf
randomForest::importance(rf,1,scale=FALSE)[,1]
}
comment(getImpLegacyRfRaw)<-'randomForest raw permutation importance'
#' @rdname getImpLegacyRf
#' @export
getImpLegacyRfGini<-function(x,y,...){
randomForest::randomForest(x,y,
keep.forest=FALSE,...)->rf
randomForest::importance(rf,2,scale=FALSE)[,1]
}
comment(getImpLegacyRfGini)<-'randomForest Gini index importance'
#' ranger Random Forest importance adapters
#'
#' Those function is intended to be given to a \code{getImp} argument of \code{\link{Boruta}} function to be called by the Boruta algorithm as an importance source.
#' \code{getImpRfZ} generates default, normalized permutation importance, \code{getImpRfRaw} raw permutation importance, finally \code{getImpRfGini} generates Gini index importance.
#' @name getImpRf
#' @rdname getImpRf
#' @aliases getImpRfZ getImpRfGini getImpRfRaw
#' @param x data frame of predictors including shadows.
#' @param y response vector.
#' @param ntree Number of trees in the forest; copied into \code{\link{ranger}}'s native num.trees, put to retain transparent compatibility with randomForest.
#' @param num.trees Number of trees in the forest, as according to \code{\link{ranger}}'s nomenclature. If not given, set to \code{ntree} value. If both are given, \code{num.trees} takes precedence.
#' @param ... parameters passed to the underlying \code{\link{ranger}} call; they are relayed from \code{...} of \code{\link{Boruta}}.
#' @note Prior to Boruta 5.0, \code{getImpLegacyRfZ} function was a default importance source in Boruta; see \link{getImpLegacyRf} for more details.
#' @export
getImpRfZ<-function(x,y,ntree=500,num.trees=ntree,...){
if(inherits(y,"Surv")){
x$shadow.Boruta.time<-y[,"time"]
x$shadow.Boruta.status<-y[,"status"]
return(ranger::ranger(data=x,
dependent.variable.name="shadow.Boruta.time",
status.variable.name="shadow.Boruta.status",
num.trees=num.trees,importance="permutation",
scale.permutation.importance=TRUE,
write.forest=FALSE,...)$variable.importance)
}
#Abusing the fact that Boruta disallows attributes with names
# starting from "shadow"
x$shadow.Boruta.decision<-y
ranger::ranger(data=x,dependent.variable.name="shadow.Boruta.decision",
num.trees=num.trees,importance="permutation",
scale.permutation.importance=TRUE,
write.forest=FALSE,...)$variable.importance
}
comment(getImpRfZ)<-'ranger normalized permutation importance'
#' @rdname getImpRf
#' @export
getImpRfGini<-function(x,y,ntree=500,num.trees=ntree,...){
if(inherits(y,"Surv"))
stop("Ranger cannot produce Gini importance for survival problems.")
x$shadow.Boruta.decision<-y
ranger::ranger(data=x,dependent.variable.name="shadow.Boruta.decision",
num.trees=num.trees,importance="impurity",
scale.permutation.importance=FALSE,
write.forest=FALSE,...)$variable.importance
}
comment(getImpRfGini)<-'ranger Gini index importance'
#' @rdname getImpRf
#' @export
getImpRfRaw<-function(x,y,ntree=500,num.trees=ntree,...){
if(inherits(y,"Surv")){
x$shadow.Boruta.time<-y[,"time"]
x$shadow.Boruta.status<-y[,"status"]
return(ranger::ranger(data=x,
dependent.variable.name="shadow.Boruta.time",
status.variable.name="shadow.Boruta.status",
num.trees=num.trees,importance="permutation",
write.forest=FALSE,...)$variable.importance)
}
x$shadow.Boruta.decision<-y
ranger::ranger(data=x,dependent.variable.name="shadow.Boruta.decision",
num.trees=num.trees,importance="permutation",
scale.permutation.importance=FALSE,
write.forest=FALSE,...)$variable.importance
}
comment(getImpRfRaw)<-'ranger raw permutation importance'
#' ranger Extra-trees importance adapters
#'
#' Those function is intended to be given to a \code{getImp} argument of \code{\link{Boruta}} function to be called by the Boruta algorithm as an importance source.
#' \code{getImpExtraZ} generates default, normalized permutation importance, \code{getImpExtraRaw} raw permutation importance, finally \code{getImpExtraGini} generates Gini impurity importance.
#' @name getImpExtra
#' @rdname getImpExtra
#' @aliases getImpExtraZ getImpExtraGini getImpExtraRaw
#' @param x data frame of predictors including shadows.
#' @param y response vector.
#' @param ntree Number of trees in the forest; copied into \code{\link{ranger}}'s native num.trees, put to retain transparent compatibility with randomForest.
#' @param num.trees Number of trees in the forest, as according to \code{\link{ranger}}'s nomenclature. If not given, set to \code{ntree} value. If both are given, \code{num.trees} takes precedence.
#' @param ... parameters passed to the underlying \code{\link{ranger}} call; they are relayed from \code{...} of \code{\link{Boruta}}. Note that these function work just by setting \code{splitrule} to \code{"extratrees"}.
#' @export
getImpExtraZ<-function(x,y,ntree=500,num.trees=ntree,...)
getImpRfZ(x,y,ntree=ntree,splitrule="extratrees",...)
comment(getImpExtraZ)<-'ranger normalized permutation importance'
#' @rdname getImpExtra
#' @export
getImpExtraGini<-function(x,y,ntree=500,num.trees=ntree,...)
getImpRfGini(x,y,ntree=ntree,splitrule="extratrees",...)
comment(getImpExtraGini)<-'ranger extra-trees Gini index importance'
#' @rdname getImpExtra
#' @export
getImpExtraRaw<-function(x,y,ntree=500,num.trees=ntree,...)
getImpRfRaw(x,y,ntree=ntree,splitrule="extratrees",...)
comment(getImpExtraRaw)<-'ranger extra-trees raw permutation importance'
#' Random Ferns importance
#'
#' This function is intended to be given to a \code{getImp} argument of \code{\link{Boruta}} function to be called by the Boruta algorithm as an importance source.
#' @param x data frame of predictors including shadows.
#' @param y response vector.
#' @param ... parameters passed to the underlying \code{\link[rFerns]{rFerns}} call; they are relayed from \code{...} of \code{\link{Boruta}}.
#' @export
#' @note Random Ferns importance calculation should be much faster than using Random Forest; however, one must first optimize the value of the \code{depth} parameter and
#' it is quite likely that the number of ferns in the ensemble required for the importance to converge will be higher than the number of trees in case of Random Forest.
getImpFerns<-function(x,y,...){
f<-rFerns::rFerns(x,y,
saveForest=FALSE,importance=TRUE,...)
f$importance[,1]
}
comment(getImpFerns)<-'rFerns importance'
#' Xgboost importance
#'
#' This function is intended to be given to a \code{getImp} argument of \code{\link{Boruta}} function to be called by the Boruta algorithm as an importance source.
#' This functionality is inspired by the Python package BoostARoota by Chase DeHan.
#' In practice, due to the eager way XgBoost works, this adapter changes Boruta into minimal optimal method, hence I strongly recommend against using this.
#' @param x data frame of predictors including shadows.
#' @param y response vector.
#' @param nrounds Number of rounds; passed to the underlying \code{\link[xgboost]{xgboost}} call.
#' @param verbose Verbosity level of xgboost; either 0 (silent) or 1 (progress reports). Passed to the underlying \code{\link[xgboost]{xgboost}} call.
#' @param ... other parameters passed to the underlying \code{\link[xgboost]{xgboost}} call.
#' Similarly as \code{nrounds} and \code{verbose}, they are relayed from \code{...} of \code{\link{Boruta}}.
#' For convenience, this function sets \code{nrounds} to 5 and verbose to 0, but this can be overridden.
#' @note Only dense matrix interface is supported; all predictions given to \code{\link{Boruta}} call have to be numeric (not integer).
#' Categorical features should be split into indicator attributes.
#' @references \url{https://github.com/chasedehan/BoostARoota}
#' @export
getImpXgboost<-function(x,y,nrounds=5,verbose=0,...){
for(e in 1:ncol(x)) x[,e]<-as.numeric(x[,e])
xgboost::xgb.importance(
model=xgboost::xgboost(
data=as.matrix(x),
label=y,
nrounds=nrounds,
verbose=verbose,
...
)
)->imp
stats::setNames(rep(0,ncol(x)),colnames(x))->ans
ans[imp$Feature]<-imp$Gain
ans
}
comment(getImpXgboost)<-'xgboost gain importance'
|
/scratch/gouwar.j/cran-all/cranData/Boruta/R/importance.R
|
# Supplementary routines for Boruta.
#' Extract attribute statistics
#'
#' \code{attStats} shows a summary of a Boruta run in an attribute-centred way.
#' It produces a data frame containing some importance stats as well as the number of hits that attribute scored and the decision it was given.
#' @param x an object of a class Boruta, from which attribute stats should be extracted.
#' @return A data frame containing, for each attribute that was originally in information system, mean, median, maximal and minimal importance, number of hits normalised to number of importance source runs performed and the decision copied from \code{finalDecision}.
#' @note When using a Boruta object generated by a \code{\link{TentativeRoughFix}}, the resulting data frame will consist a rough-fixed decision.
#' @note \code{x} has to be made with \code{holdHistory} set to \code{TRUE} for this code to run.
#' @export
#' @examples
#' \dontrun{
#' library(mlbench); data(Sonar)
#' #Takes some time, so be patient
#' Boruta(Class~.,data=Sonar,doTrace=2)->Bor.son
#' print(Bor.son)
#' stats<-attStats(Bor.son)
#' print(stats)
#' plot(normHits~meanImp,col=stats$decision,data=stats)
#' }
attStats<-function(x){
stopifnot(inherits(x,'Boruta'))
if(is.null(x$ImpHistory))
stop('Importance history was not stored during the Boruta run.')
lz<-lapply(1:ncol(x$ImpHistory),function(i) x$ImpHistory[is.finite(x$ImpHistory[,i]),i])
colnames(x$ImpHistory)->names(lz)
mr<-lz$shadowMax; lz[1:(length(lz)-3)]->lz
t(sapply(lz,function(x) c(mean(x),stats::median(x),min(x),max(x),sum(mr[1:length(x)]<x)/length(mr))))->st
st<-data.frame(st,x$finalDecision)
names(st)<-c("meanImp","medianImp","minImp","maxImp","normHits","decision")
return(st)
}
#' Extract names of the selected attributes
#'
#' \code{getSelectedAttributes} returns a vector of names of attributes selected during a Boruta run.
#' @param x an object of a class Boruta, from which relevant attributes names should be extracted.
#' @param withTentative if set to \code{TRUE}, Tentative attributes will be also returned.
#' @return A character vector with names of the relevant attributes.
#' @export
#' @examples
#' \dontrun{
#' data(iris)
#' #Takes some time, so be patient
#' Boruta(Species~.,data=iris,doTrace=2)->Bor.iris
#' print(Bor.iris)
#' print(getSelectedAttributes(Bor.iris))
#' }
getSelectedAttributes<-function(x,withTentative=FALSE){
stopifnot(inherits(x,'Boruta'))
names(x$finalDecision)[
x$finalDecision%in%(if(!withTentative) "Confirmed" else c("Confirmed","Tentative"))
]
}
#' Rough fix of Tentative attributes
#'
#' In some circumstances (too short Boruta run, unfortunate mixing of shadow attributes, tricky dataset\ldots), Boruta can leave some attributes Tentative.
#' \code{TentativeRoughFix} performs a simplified, weaker test for judging such attributes.
#' @param x an object of a class Boruta.
#' @param averageOver Either number of last importance source runs to
#' average over or Inf for averaging over the whole Boruta run.
#' @return A Boruta class object with modified \code{finalDecision} element.
#' Such object has few additional elements:
#' \item{originalDecision}{Original \code{finalDecision}.}
#' \item{averageOver}{Copy of \code{averageOver} parameter.}
#' @details Function claims as Confirmed those attributes that
#' have median importance higher than the median importance of
#' maximal shadow attribute, and the rest as Rejected.
#' Depending of the user choice, medians for the test
#' are count over last round, all rounds or N last
#' importance source runs.
#' @note This function should be used only when strict decision is
#' highly desired, because this test is much weaker than Boruta
#' and can lower the confidence of the final result.
#' @note \code{x} has to be made with \code{holdHistory} set to
#' \code{TRUE} for this code to run.
#' @export
TentativeRoughFix<-function(x,averageOver=Inf){
stopifnot(inherits(x,'Boruta'))
if(is.null(x$ImpHistory))
stop('Importance history was not stored during the Boruta run.')
if(!is.numeric(averageOver))
stop('averageOver should be a numeric vector.')
if(length(averageOver)!=1)
stop('averageOver should be a one-element vector.')
if(averageOver<1)
stop('averageOver should be positive.')
tentIdx<-which(x$finalDecision=='Tentative')
if(length(tentIdx)==0){
warning('There are no Tentative attributes! Returning original object.')
return(x)
}
nRuns<-dim(x$ImpHistory)[1]
if(averageOver>nRuns)
averageOver<-nRuns
impHistorySubset<-x$ImpHistory[(nRuns-averageOver+1):nRuns,]
medianTentImp<-apply(impHistorySubset[,tentIdx,drop=FALSE],2,stats::median)
medianShaMaxImp<-stats::median(impHistorySubset[,'shadowMax'])
medianTentImp>medianShaMaxImp->toOrdain
ans<-x
ans$roughfixed<-TRUE
ans$averageOver<-averageOver
ans$originalDecision<-x$finalDecision
ans$finalDecision[tentIdx[toOrdain]]<-'Confirmed'
ans$finalDecision[tentIdx[!toOrdain]]<-'Rejected'
return(ans)
}
##generateCol is internally used by plot.Boruta and plotImpHistory
generateCol<-function(x,colCode,col,numShadow){
#Checking arguments
if(is.null(col) & length(colCode)!=4)
stop('colCode should have 4 elements.')
#Generating col
if(is.null(col)){
rep(colCode[4],length(x$finalDecision)+numShadow)->cc
cc[c(x$finalDecision=='Confirmed',rep(FALSE,numShadow))]<-colCode[1]
cc[c(x$finalDecision=='Tentative',rep(FALSE,numShadow))]<-colCode[2]
cc[c(x$finalDecision=='Rejected',rep(FALSE,numShadow))]<-colCode[3]
col=cc
}
return(col)
}
#' Plot Boruta object
#'
#' Default plot method for Boruta objects, showing boxplots of attribute importances over run.
#' @method plot Boruta
#' @param x an object of a class Boruta.
#' @param colCode a vector containing colour codes for attribute decisions, respectively Confirmed, Tentative, Rejected and shadow.
#' @param sort controls whether boxplots should be ordered, or left in original order.
#' @param whichShadow a logical vector controlling which shadows should be drawn; switches respectively max shadow, mean shadow and min shadow.
#' @param col standard \code{col} attribute. If given, suppresses effects of \code{colCode}.
#' @param xlab X axis label that will be passed to \code{\link{boxplot}}.
#' @param ylab Y axis label that will be passed to \code{\link{boxplot}}.
#' @param ... additional graphical parameter that will be passed to \code{\link{boxplot}}.
#' @note If \code{col} is given and \code{sort} is \code{TRUE}, the \code{col} will be permuted, so that its order corresponds to attribute order in \code{ImpHistory}.
#' @note This function will throw an error when \code{x} lacks importance history, i.e., was made with \code{holdHistory} set to \code{FALSE}.
#' @return Invisible copy of \code{x}.
#' @examples
#' \dontrun{
#' library(mlbench); data(HouseVotes84)
#' na.omit(HouseVotes84)->hvo
#' #Takes some time, so be patient
#' Boruta(Class~.,data=hvo,doTrace=2)->Bor.hvo
#' print(Bor.hvo)
#' plot(Bor.hvo)
#' }
#' @export
plot.Boruta<-function(x,colCode=c('green','yellow','red','blue'),sort=TRUE,whichShadow=c(TRUE,TRUE,TRUE),
col=NULL,xlab='Attributes',ylab='Importance',...){
#Checking arguments
stopifnot(inherits(x,'Boruta'))
if(is.null(x$ImpHistory))
stop('Importance history was not stored during the Boruta run.')
#Removal of -Infs and conversion to a list
lz<-lapply(1:ncol(x$ImpHistory),function(i) x$ImpHistory[is.finite(x$ImpHistory[,i]),i])
colnames(x$ImpHistory)->names(lz)
#Selection of shadow meta-attributes
numShadow<-sum(whichShadow)
lz[c(rep(TRUE,length(x$finalDecision)),whichShadow)]->lz
#Generating color vector
col<-generateCol(x,colCode,col,numShadow)
#Ordering boxes due to attribute median importance
if(sort){
ii<-order(sapply(lz,stats::median))
lz[ii]->lz; col<-col[ii]
}
#Final plotting
graphics::boxplot(lz,xlab=xlab,ylab=ylab,col=col,...)
invisible(x)
}
#' Plot Boruta object as importance history
#'
#' Alternative plot method for Boruta objects, showing matplot of attribute importances over run.
#' @param x an object of a class Boruta.
#' @param colCode a vector containing colour codes for attribute decisions, respectively Confirmed, Tentative, Rejected and shadow.
#' @param col standard \code{col} attribute, passed to \code{\link{matplot}}. If given, suppresses effects of \code{colCode}.
#' @param type Plot type that will be passed to \code{\link{matplot}}.
#' @param lty Line type that will be passed to \code{\link{matplot}}.
#' @param pch Point mark type that will be passed to \code{\link{matplot}}.
#' @param xlab X axis label that will be passed to \code{\link{matplot}}.
#' @param ylab Y axis label that will be passed to \code{\link{matplot}}.
#' @param ... additional graphical parameter that will be passed to \code{\link{matplot}}.
#' @note This function will throw an error when \code{x} lacks importance history, i.e., was made with \code{holdHistory} set to \code{FALSE}.
#' @return Invisible copy of \code{x}.
#' @examples
#' \dontrun{
#' library(mlbench); data(Sonar)
#' #Takes some time, so be patient
#' Boruta(Class~.,data=Sonar,doTrace=2)->Bor.son
#' print(Bor.son)
#' plotImpHistory(Bor.son)
#' }
#' @export
plotImpHistory<-function(x,colCode=c('green','yellow','red','blue'),col=NULL,type="l",lty=1,pch=0,
xlab='Classifier run',ylab='Importance',...){
#Checking arguments
stopifnot(inherits(x,'Boruta'))
if(is.null(x$ImpHistory))
stop('Importance history was not stored during the Boruta run.')
col<-generateCol(x,colCode,col,3)
#Final plotting
graphics::matplot(0:(nrow(x$ImpHistory)-1),x$ImpHistory,xlab=xlab,ylab=ylab,col=col,type=type,lty=lty,pch=pch,...)
invisible(x)
}
#' Export Boruta result as a formula
#'
#' Functions which convert the Boruta selection into a formula, so that it could be passed further to other functions.
#' @param x an object of a class Boruta, made using a formula interface.
#' @return Formula, corresponding to the Boruta results.
#' \code{getConfirmedFormula} returns only Confirmed attributes, \code{getNonRejectedFormula} also adds Tentative ones.
#' @note This operation is possible only when Boruta selection was invoked using a formula interface.
#' @rdname getFormulae
#' @export
getConfirmedFormula<-function(x){
stopifnot(inherits(x,'Boruta'))
if(is.null(x$call[["formula"]]))
stop('The model for this Boruta run was not a formula.')
deparse(x$call[["formula"]][[2]])->dec
preds<-paste(names(x$finalDecision)[x$finalDecision=='Confirmed'],collapse="+")
return(stats::as.formula(sprintf('%s~%s',dec,preds)))
}
#' @rdname getFormulae
#' @export
getNonRejectedFormula<-function(x){
stopifnot(inherits(x,'Boruta'))
if(is.null(x$call[["formula"]]))
stop('The model for this Boruta run was not a formula.')
deparse(x$call[["formula"]][[2]])->dec
preds<-paste(names(x$finalDecision)[x$finalDecision!='Rejected'],collapse="+")
return(stats::as.formula(sprintf('%s~%s',dec,preds)))
}
|
/scratch/gouwar.j/cran-all/cranData/Boruta/R/tools.R
|
# Input transformations which compose with importance adapters
fixna<-function(x){
nm<-is.na(x)
if(!any(nm)) return(x)
if(all(nm)) return(rep(0,length(x)))
x[nm]<-sample(x[!nm],sum(nm),replace=TRUE)
x
}
#' Impute transdapter
#'
#' Wraps the importance adapter to accept NAs in input.
#'
#' @param adapter importance adapter to transform.
#' @return transformed importance adapter which can be fed into \code{getImp} argument of the \code{\link{Boruta}} function.
#' @note An all-NA feature will be converted to all zeroes, which should be ok as a totally non-informative value with most methods, but it is not universally correct.
#' Ideally, one should avoid having such features in input altogether.
#' @examples
#' \dontrun{
#' set.seed(777)
#' data(srx)
#' srx_na<-srx
#' # Randomly punch 25 holes in the SRX data
#' holes<-25
#' holes<-cbind(
#' sample(nrow(srx),holes,replace=TRUE),
#' sample(ncol(srx),holes,replace=TRUE)
#' )
#' srx_na[holes]<-NA
#' # Use impute transdapter to mitigate them with internal imputation
#' Boruta(Y~.,data=srx_na,getImp=imputeTransdapter(getImpRfZ))
#' }
#' @export
imputeTransdapter<-function(adapter=getImpRfZ){
composition<-function(x,y,...)
adapter(
data.frame(lapply(x,fixna)),
fixna(y),
...
)
comment(composition)<-sprintf("%s, wrapped into imputation transdapter",comment(adapter))
composition
}
#' Decohere transdapter
#'
#' Applies the decoherence transformation to the input, destroying all multivariate interactions.
#' It will trash the Boruta result, only apply if you know what are you doing!
#' Works only for categorical decision.
#'
#' @param adapter importance adapter to transform.
#' @return transformed importance adapter which can be fed into \code{getImp} argument of the \code{\link{Boruta}} function.
#' @examples
#' set.seed(777)
#' # SRX data only contains multivariate interactions
#' data(srx)
#' # Decoherence transform removes them all,
#' # leaving no confirmed features
#' Boruta(Y~.,data=srx,getImp=decohereTransdapter())
#' @export
decohereTransdapter<-function(adapter=getImpRfZ){
composition<-function(x,y,...){
stopifnot(is.factor(y))
mix<-function(x) as.data.frame(lapply(x,sample),row.names=rownames(x))
unsplit(lapply(split(x,y),mix),y)->xd
adapter(
xd,
y,
...
)
}
comment(composition)<-sprintf("%s, wrapped into decoherence transdapter",comment(adapter))
composition
}
#' Conditional transdapter
#'
#' Applies downstream importance source on a given object strata and averages their outputs.
#'
#' @param groups groups.
#' @param adapter importance adapter to transform.
#' @return transformed importance adapter which can be fed into \code{getImp} argument of the \code{\link{Boruta}} function.
#' @export
conditionalTransdapter<-function(groups,adapter=getImpRfZ){
as.numeric(table(groups))/length(groups)->w
stopifnot(is.factor(groups))
composition<-function(x,y,...)
colSums(w*t(sapply(levels(groups),function(l) adapter(x[groups==l,],y[groups==l],...))))
comment(composition)<-sprintf("%s, wrapped into conditional transdapter",comment(adapter))
composition
}
|
/scratch/gouwar.j/cran-all/cranData/Boruta/R/trandapters.R
|
### R code from vignette source 'inahurry.Rnw'
###################################################
### code chunk number 1: setGeneration
###################################################
set.seed(17)
data(iris)
irisE<-cbind(
setNames(
data.frame(apply(iris[,-5],2,sample)),
sprintf("Nonsense%d",1:4)
),
iris
)
###################################################
### code chunk number 2: Boruta
###################################################
library(Boruta)
Boruta(Species~.,data=irisE)->BorutaOnIrisE
BorutaOnIrisE
###################################################
### code chunk number 3: BorutaReduendancy
###################################################
irisR<-cbind(
irisE,
SpoilerFeature=iris$Species
)
Boruta(Species~.,data=irisR)
###################################################
### code chunk number 4: BorutaPlots
###################################################
par(mfrow=c(1,2))
plot(BorutaOnIrisE)
plotImpHistory(BorutaOnIrisE)
###################################################
### code chunk number 5: attStats
###################################################
attStats(BorutaOnIrisE)
###################################################
### code chunk number 6: BorutaFe
###################################################
library(rFerns)
Boruta(Species~.,data=irisE,getImp=getImpFerns)
|
/scratch/gouwar.j/cran-all/cranData/Boruta/inst/doc/inahurry.R
|
### R code from vignette source 'transdapters.Rnw'
###################################################
### code chunk number 1: noop
###################################################
library(Boruta)
noopTransdapter<-function(adapter=getImpRfZ){
adapter
}
###################################################
### code chunk number 2: noopuse
###################################################
set.seed(17)
Boruta(Species~.,iris,getImp=noopTransdapter())
###################################################
### code chunk number 3: srximp
###################################################
set.seed(17)
data(srx)
srx_na<-srx
# Randomly punch 25 holes in the SRX data
holes<-25
holes<-cbind(
sample(nrow(srx),holes,replace=TRUE),
sample(ncol(srx),holes,replace=TRUE)
)
srx_na[holes]<-NA
# Use impute transdapter to mitigate them with internal imputation
Boruta(Y~.,srx_na,getImp=imputeTransdapter(getImpRfZ))
###################################################
### code chunk number 4: srxdeco
###################################################
set.seed(17)
Boruta(Y~.,srx,getImp=decohereTransdapter())
|
/scratch/gouwar.j/cran-all/cranData/Boruta/inst/doc/transdapters.R
|
# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
cxPerm <- function(A) {
.Call(`_BosonSampling_cxPerm`, A)
}
cxPermMinors <- function(C) {
.Call(`_BosonSampling_cxPermMinors`, C)
}
rePerm <- function(B) {
.Call(`_BosonSampling_rePerm`, B)
}
|
/scratch/gouwar.j/cran-all/cranData/BosonSampling/R/RcppExports.R
|
bosonSampler = function(A, sampleSize, perm = FALSE){
#
# A complex matrix
#
# out: samples = list of boson sample mode sequences
# perms = list of associated permanents
# pmfs = list of associated pmfs
#
# transpose A -- benefit since both R and Armadillo store matrices in column order
A = t(A)
#
m = ncol(A); n = nrow(A)
modeSeqList = permList = pmfList = c()
for(k in 1:sampleSize){
#
# permute rows of A, if more than one
#
if(n>1) A = A[sample(n),]
#
# start with row 1 and sample the first mode c_1
# i.e. the first mode in an individual sample sequence
#
firstMode = sample(1:m,size = 1,prob = (Mod(A[1,]))^2)
if(n == 1){
modeSeqList = c(modeSeqList, firstMode)
if(perm){
permList = c(permList,A[1,])
pmfList = c(pmfList,(Mod(A[1,]))^2)
}
next
}
#
# now sample remaining modes c_2,c_3,...,c_n in an individual sequence
#
modeSeq = firstMode
for(modeLimit in 2:n){
subPerm = cxPermMinors(matrix(A[1:modeLimit, modeSeq],ncol = modeLimit-1))
#
# permanents of submatrices using Laplace-type expansion
#
permVector = t(subPerm) %*% A[1:modeLimit,]
#
# next mode in an individual sequence
#
nextMode = sample(1:m, size = 1, prob = (Mod(permVector))^2)
# increment mode sequence
modeSeq = c(modeSeq, nextMode)
}
# build list of sample sequences and associated permanents/pmfs
modeSeqList = cbind(modeSeqList,modeSeq)
if(perm){
finalPerm = permVector[nextMode]
permList = c(permList,finalPerm)
pmfList = c(pmfList,Mod(finalPerm)^2/ prod(factorial(tabulate(modeSeq))))
}
}
list(values = matrix(modeSeqList,nrow = n),perms = permList, pmfs = pmfList)
}
|
/scratch/gouwar.j/cran-all/cranData/BosonSampling/R/bosonSampler.R
|
#' Random unitary
#'
#' Generates a random unitary matrix (square)
#' @param size Dimension of matrix
#' @keywords complex
#' @export
#' @examples
#' m = 25
#' set.seed(7)
#' U = randomUnitary(m)
#' #
#' n = 5 # First n columns
#' A = U[,1:n]
randomUnitary = function(size){
B = qr(matrix(complex(real = stats::rnorm(size^2), imaginary = stats::rnorm(size^2)),size))
R_Diag = sign(Re(diag(qr.R(B))))
qr.Q(B)%*%diag(R_Diag)
}
# ##
# k = 25
# A = matrix(complex(real = rnorm(k^2), imaginary = rnorm(k^2)),nrow = k,byrow = F)
# B = as.matrix(A[,-k])
# c(cxPerm(A),sum(cxPermMinorsV2(B)*A[,k]))
|
/scratch/gouwar.j/cran-all/cranData/BosonSampling/R/randomUnitary.R
|
#' Compute a Berry-Esseen-type bound
#'
#' This function returns a valid value \mjseqn{\delta_n} for the bound
#' \mjtdeqn{\sup_{x \in R}
#' \left| \textrm{Prob}(S_n \leq x) - \Phi(x) \right|
#' \leq \delta_n,
#' }{\sup_{x \in \mathbb{R}}
#' \left| \textrm{Prob}(S_n \leq x) - \Phi(x) \right|
#' \leq \delta_n,
#' }{sup_{x \in \mathbb{R}} | Prob(S_n <= x) - \Phi(x) | <= \delta_n,
#' }
#'
#' where \mjseqn{X_1, \dots, X_n} be \mjseqn{n} independent centered variables,
#' and \mjseqn{S_n} be their normalized sum, in the sense that
#' \mjseqn{S_n := \sum_{i=1}^n X_i / \textrm{sd}(\sum_{i=1}^n X_i)}.
#' This bounds follows from the triangular inequality
#' and the bound on the difference between a cdf and its 1st-order Edgeworth Expansion.
#'
#' \loadmathjax
#'
#' Note that the variables \mjseqn{X_1, \dots, X_n} must be independent
#' but may have different distributions (if \code{setup$iid = FALSE}).
#'
#'
#' @inheritParams Bound_EE1
#'
#' @return A vector of the same size as \code{n} with values \mjseqn{\delta_n}
#' such that
#' \mjtdeqn{\sup_{x \in R}
#' \left| \textrm{Prob}(S_n \leq x) - \Phi(x) \right|
#' \leq \delta_n.
#' }{\sup_{x \in \mathbb{R}}
#' \left| \textrm{Prob}(S_n \leq x) - \Phi(x) \right|
#' \leq \delta_n.
#' }{sup_{x \in R} | Prob(S_n <= x) - \Phi(x) | <= \delta_n.
#' }
#'
#'
#' @references Derumigny A., Girard L., and Guyonvarch Y. (2021).
#' Explicit non-asymptotic bounds for the distance to the first-order Edgeworth expansion,
#' ArXiv preprint \href{https://arxiv.org/abs/2101.05780}{arxiv:2101.05780}.
#'
#' @seealso \code{\link{Bound_EE1}()} for a bound on the distance
#' to the first-order Edgeworth expansion.
#'
#' @examples
#' setup = list(continuity = FALSE, iid = FALSE, no_skewness = FALSE)
#' regularity = list(C0 = 1, p = 2, kappa = 0.99)
#'
#' computedBound_EE1 <- Bound_EE1(
#' setup = setup, n = 150, K4 = 9,
#' regularity = regularity, eps = 0.1 )
#'
#' computedBound_BE <- Bound_BE(
#' setup = setup, n = 150, K4 = 9,
#' regularity = regularity, eps = 0.1 )
#'
#' print(c(computedBound_EE1, computedBound_BE))
#'
#' @export
#'
Bound_BE <- function(
setup = list(continuity = FALSE, iid = FALSE, no_skewness = FALSE),
n,
K4 = 9, K3 = NULL, lambda3 = NULL, K3tilde = NULL,
regularity = list(C0 = 1, p = 2),
eps = 0.1)
{
ub_DeltanE <- Bound_EE1(
setup = setup, n = n,
K4 = K4, K3 = K3, lambda3 = lambda3, K3tilde = K3tilde,
regularity = regularity, eps = eps)
if (setup$no_skewness){
ub_DeltanB <- ub_DeltanE
} else {
# If skewness, bounds on lambda3n is required.
# It can be supplied by the user or obtained from K3 (or K4).
env <- environment(); Update_bounds_on_moments(env)
ub_DeltanB <- ub_DeltanE +
abs(lambda3) * stats::dnorm(0, mean = 0, sd = 1) / (6 * sqrt(n))
}
return(ub_DeltanB)
}
|
/scratch/gouwar.j/cran-all/cranData/BoundEdgeworth/R/Bound_BE.R
|
#' Uniform bound on Edgeworth expansion
#'
#' This function computes a non-asymptotically uniform bound on
#' the difference between the cdf of a normalized sum of random variables
#' and its 1st order Edgeworth expansion.
#' It returns a valid value \mjseqn{\delta_n} such that
#' \mjtdeqn{\sup_{x \in R}
#' \left| \textrm{Prob}(S_n \leq x) - \Phi(x)
#' - \frac{\lambda_{3,n}}{6\sqrt{n}}(1-x^2) \varphi(x) \right|
#' \leq \delta_n,}{
#' \sup_{x \in \mathbb{R}}
#' \left| \textrm{Prob}(S_n \leq x) - \Phi(x)
#' - \frac{\lambda_{3,n}}{6\sqrt{n}}(1-x^2) \varphi(x) \right|
#' \leq \delta_n,}{
#' \sup_{x \in R} | Prob(S_n \leq x) - \Phi(x)
#' - \frac{\lambda_{3,n}}{6\sqrt{n}}(1-x^2) \varphi(x) |
#' \leq \delta_n,}
#' where \mjseqn{X_1, \dots, X_n} be \mjseqn{n} independent centered variables,
#' and \mjseqn{S_n} be their normalized sum, in the sense that
#' \mjseqn{S_n := \sum_{i=1}^n X_i / \textrm{sd}(\sum_{i=1}^n X_i)}.
#' Here \mjseqn{\lambda_{3,n}} denotes the average skewness of
#' the variables \mjseqn{X_1, \dots, X_n}.
#'
#' \loadmathjax
#'
#' Note that the variables \mjseqn{X_1, \dots, X_n} must be independent
#' but may have different distributions (if \code{setup$iid = FALSE}).
#'
#'
#' @import mathjaxr
#'
#'
#' @param setup logical vector of size 3 made up of
#' the following components: \itemize{
#' \item \code{continuity}: if \code{TRUE}, assume that the distribution is continuous.
#'
#' \item \code{iid}: if \code{TRUE}, assume that the random variables are i.i.d.
#'
#' \item \code{no_skewness}: if \code{TRUE}, assume that the distribution is unskewed.
#' }
#'
#' @param regularity list of length up to 3
#' (only used in the \code{continuity=TRUE} framework)
#' with the following components:\itemize{
#'
#' \item \code{C0} and \code{p}: only used in the \code{iid=FALSE} case.
#' It corresponds to the assumption of a polynomial bound on \mjseqn{f_{S_n}}:
#' \mjseqn{|f_{S_n}(u)| \leq C_0 \times u^{-p}} for every \mjseqn{u > a_n},
#' where \mjseqn{a_n := 2 t_1^* \pi \sqrt{n} / K3tilde}.
#'
#' \item \code{kappa}: only used in the \code{iid=TRUE} case.
#' Corresponds to a bound on the modulus of the characteristic function of
#' the standardized \mjseqn{X_n}. More precisely, \code{kappa} is an upper bound on
#' \mjseqn{kappa :=} sup of modulus of \mjseqn{f_{X_n / \sigma_n}(t)}
#' over all \mjseqn{t} such that \mjseqn{|t| \geq 2 t_1^* \pi / K3tilde}.
#' }
#'
#' @param n sample size ( = number of random variables that appear in the sum).
#'
#' @param K4 bound on the 4th normalized moment of the random variables.
#' We advise to use K4 = 9 as a general case which covers most ``usual'' distributions.
#'
#' @param K3 bound on the 3rd normalized moment.
#' If not given, an upper bound on \code{K3} will be derived from the value of \code{K4}.
#'
#' @param lambda3 (average) skewness of the variables.
#' If not given, an upper bound on \mjseqn{abs(lambda3)}
#' will be derived from the value of \code{K4}.
#'
#' @param K3tilde value of
#' \mjtdeqn{K_{3,n} + \frac{1}{n}\sum_{i=1}^n
#' E|X_i| \sigma_{X_i}^2 / \overline{B}_n^3}{
#' K_{3,n} + \frac{1}{n}\sum_{i=1}^n
#' \mathbb{E}|X_i| \sigma_{X_i}^2 / \overline{B}_n^3}{
#' K_{3,n} + \frac{1}{n}\sum_{i=1}^n E|X_i| \sigma_{X_i}^2 / \overline{B}_n^3}
#' where \mjseqn{\overline{B}_n := \sqrt{(1/n) \sum_{i=1}^n E[X_i^2]}}.
#' If not given, an upper bound on \code{K3tilde} will be derived
#' from the value of \code{K4}.
#'
#' @param eps a value between 0 and 1/3 on which several terms depends.
#' Any value of \code{eps} will give a valid upper bound but some may give
#' tighter results than others.
#'
#' @param verbose if it is \code{0} the function is silent (no printing).
#' Higher values of \code{verbose} give more precise information about the computation.
#' \code{verbose = 1} prints the values of the intermediary terms that are summed
#' to produce the final bound. This can be useful to understand which term has
#' the largest contribution to the bound.
#'
#' @return A vector of the same size as \code{n} with values \mjseqn{\delta_n}
#' such that
#' \mjtdeqn{\sup_{x \in R}
#' \left| \textrm{Prob}(S_n \leq x) - \Phi(x)
#' - \frac{\lambda_{3,n}}{6\sqrt{n}}(1-x^2) \varphi(x) \right|
#' \leq \delta_n.}{
#' \sup_{x \in \mathbb{R}}
#' \left| \textrm{Prob}(S_n \leq x) - \Phi(x)
#' - \frac{\lambda_{3,n}}{6\sqrt{n}}(1-x^2) \varphi(x) \right|
#' \leq \delta_n.}{
#' \sup_{x \in R} | Prob(S_n \leq x) - \Phi(x)
#' - \frac{\lambda_{3,n}}{6\sqrt{n}}(1-x^2) \varphi(x) |
#' \leq \delta_n.}
#'
#' @references
#' Derumigny A., Girard L., and Guyonvarch Y. (2021).
#' Explicit non-asymptotic bounds for the distance to the first-order Edgeworth expansion,
#' ArXiv preprint \href{https://arxiv.org/abs/2101.05780}{arxiv:2101.05780}.
#'
#' @seealso \code{\link{Bound_BE}()} for a Berry-Esseen bound.
#'
#' \code{\link{Gauss_test_powerAnalysis}()} for a power analysis of the classical
#' Gauss test that is uniformly valid based on this bound on the Edgeworth
#' expansion.
#'
#'
#' @examples
#' setup = list(continuity = TRUE, iid = FALSE, no_skewness = TRUE)
#' regularity = list(C0 = 1, p = 2)
#'
#' computedBound <- Bound_EE1(
#' setup = setup, n = c(150, 2000), K4 = 9,
#' regularity = regularity, eps = 0.1 )
#'
#' setup = list(continuity = TRUE, iid = TRUE, no_skewness = TRUE)
#' regularity = list(kappa = 0.99)
#'
#' computedBound2 <- Bound_EE1(
#' setup = setup, n = c(150, 2000), K4 = 9,
#' regularity = regularity, eps = 0.1 )
#'
#' setup = list(continuity = FALSE, iid = FALSE, no_skewness = TRUE)
#'
#' computedBound3 <- Bound_EE1(
#' setup = setup, n = c(150, 2000), K4 = 9, eps = 0.1 )
#'
#' setup = list(continuity = FALSE, iid = TRUE, no_skewness = TRUE)
#'
#' computedBound4 <- Bound_EE1(
#' setup = setup, n = c(150, 2000), K4 = 9, eps = 0.1 )
#'
#' print(computedBound)
#' print(computedBound2)
#' print(computedBound3)
#' print(computedBound4)
#'
#' @export
#'
Bound_EE1 <- function(
setup = list(continuity = FALSE, iid = FALSE, no_skewness = FALSE),
n,
K4 = 9, K3 = NULL, lambda3 = NULL, K3tilde = NULL,
regularity = list(C0 = 1, p = 2),
eps = 0.1,
verbose = 0)
{
# Check 'setup' argument and define shortcuts
if ( !all(sapply(X = setup, FUN = is.logical)) || length(setup) != 3) {
stop("'setup' should be a logical vector of size 3.")
}
continuity <- setup$continuity
iid <- setup$iid
no_skewness <- setup$no_skewness
# A bound on K4 needs to be provided.
# If bounds on lambda3, K3, and K3tilde are not provided,
# we use upper bounds that can be defined from K4 only.
env <- environment(); Update_bounds_on_moments(env)
# No continuity case (moment condition only)
if (!continuity) {
if (!iid & !no_skewness) {
ub_DeltanE = Bound_EE1_nocont_inid_skew (
n = n, eps = eps, K4 = K4, K3 = K3, K3tilde = K3tilde, lambda3 = lambda3, verbose = verbose)
} else if (!iid & no_skewness) {
ub_DeltanE = Bound_EE1_nocont_inid_noskew (
n = n, eps = eps, K4 = K4, K3tilde = K3tilde, verbose = verbose)
} else if (iid & !no_skewness) {
ub_DeltanE = Bound_EE1_nocont_iid_skew (
n = n, eps = eps, K4 = K4, K3 = K3, K3tilde = K3tilde, lambda3 = lambda3, verbose = verbose)
} else if (iid & no_skewness) {
ub_DeltanE = Bound_EE1_nocont_iid_noskew (
n = n, eps = eps, K4 = K4, K3tilde = K3tilde, verbose = verbose)
}
# Continuity case (additional regularity conditions)
} else {
if (!iid & !no_skewness) {
ub_DeltanE_wo_int_fSn = Bound_EE1_cont_inid_skew_wo_int_fSn (
n = n, eps = eps, K4 = K4, K3 = K3, lambda3 = lambda3, K3tilde = K3tilde, verbose = verbose)
} else if (!iid & no_skewness) {
ub_DeltanE_wo_int_fSn = Bound_EE1_cont_inid_noskew_wo_int_fSn (
n = n, eps = eps, K4 = K4, K3tilde = K3tilde, verbose = verbose)
} else if (iid & !no_skewness) {
ub_DeltanE_wo_int_fSn = Bound_EE1_cont_iid_skew_wo_int_fSn (
n = n, eps = eps, K4 = K4, K3 = K3, lambda3 = lambda3, K3tilde = K3tilde, verbose = verbose)
} else if (iid & no_skewness) {
ub_DeltanE_wo_int_fSn = Bound_EE1_cont_iid_noskew_wo_int_fSn (
n = n, eps = eps, K4 = K4, K3 = K3, K3tilde = K3tilde, verbose = verbose)
}
smoothness_additional_term = Smoothness_additional_term(
n = n, K3tilde = K3tilde, regularity = regularity, iid = iid)
if (verbose){
cat("Smoothness additional term:", smoothness_additional_term, "\n")
}
ub_DeltanE = ub_DeltanE_wo_int_fSn + smoothness_additional_term
}
return(ub_DeltanE)
}
#' Additional smoothness term
#'
#' It checks if \code{regularity} is well-formated, and if so,
#' it computes the additional smoothness term.
#'
#' @examples
#'
#' Smoothness_additional_term(n = 1000, K3tilde = 6, regularity = list(C0 = 1, p = 2), iid = FALSE)
#' Smoothness_additional_term(n = 1000, K3tilde = 6, regularity = list(kappa = 0.99), iid = TRUE)
#'
#' @noRd
#'
Smoothness_additional_term <- function(n, K3tilde, regularity, iid){
a_n <- pmin(2 * Value_t1star() * pi * sqrt(n) / K3tilde,
16 * pi^3 * n^2 / K3tilde^4 )
b_n <- 16 * pi^4 * n^2 / K3tilde^4
success = TRUE
switch (as.character(length(regularity)),
"1" = {
if ((names(regularity) == "kappa") && (iid)) {
result = Value_cst_bound_modulus_psi() / pi *
regularity$kappa^n * log(b_n / a_n)
} else {
success = FALSE
}
},
"2" = {
if (identical(names(regularity), c("C0", "p")) ||
identical(names(regularity), c("p", "C0"))) {
result = Value_cst_bound_modulus_psi() / pi *
regularity$C0 * (a_n^(- regularity$p) - b_n^(- regularity$p))
} else {
success = FALSE
}
},
{ success = FALSE }
)
if (!success) {
stop("'regularity' should be either a list with C0 and p; or, ",
"in the iid case only, a list with only kappa")
}
return (result)
}
#' Update missing moments based on upper bounds
#'
#' Indeed, K3, lambda3, K3tilde optional since an upper bound on K4 is enough to
#' upper bound them.
#'
#' @param env an environment including a vector named K4.
#'
#' @return NULL.
#' But after running this function,
#' K3, lambda3, and K3tilde are set if they were NULL before.
#'
#' @noRd
#'
Update_bounds_on_moments <- function(env) {
# Bound (by K4) on K3 if its value (or bound on it) is no provided
if (is.null(env$K3)){
env$K3 <- env$K4^(3/4)
}
# Bound (by K3) on lambda3 if its value (or bound on it) is no provided
# In fact, a bound on abs(lambda3) and only abs(lambda3) or lambda3^2
# is involved, thus fine.
if (is.null(env$lambda3)){
env$lambda3 <- Value_cst_bound_abs_lambda3_by_K3() * env$K3
}
# Bound on K3tilde (by K3) if its value (or bound on it) is no provided
if (is.null(env$K3tilde)){
if (env$setup$iid){
env$K3tilde <- env$K3 + 1
} else {
env$K3tilde <- 2 * env$K3
}
}
return (NULL)
}
|
/scratch/gouwar.j/cran-all/cranData/BoundEdgeworth/R/Bound_EE1.R
|
# These are the functions to compute the bounds for Theorem A.4 and A.5
# WITHOUT the term involving the integral of f_{S_n}
# 1.0253 / pi * int_{a_n}^{b_n} |f_{S_n}(t)| / t dt
# Hence the suffix: _wo_int_fSn for these four main functions
# This term is dealt with given the regularity conditions in the final
# user function Bound_EE1().
#------------------------------------------------------------------------------#
# Main functions #####
#------------------------------------------------------------------------------#
#' Compute the bound of Theorem A.4
#' (Theorem 3.1 under Assumption 2.1: inid case)
#' in the skewness case (Equation (23))
#' WITHOUT the term involving the integral of f_{S_n}
#'
#' @examples
#' Bound_EE1_cont_inid_skew_wo_int_fSn(n = 300, eps = 0.1, K4 = 9, K3tilde = 6, lambda3 = 1, K3 = 4)
#'
#' @noRd
#'
Bound_EE1_cont_inid_skew_wo_int_fSn <- function(n, eps, K4, K3, lambda3, K3tilde, verbose)
{
if (verbose > 0){
cat("Continuous, inid, potentially skewed case.\n")
}
main_term <-
Bound_EE1_cont_common_part_noskewness(eps = eps, n = n, K4 = K4)
if (verbose > 0){
cat("Main term:", main_term ,"\n")
}
additional_term_skewness <-
0.037 * e_1n(eps = eps, noskewness = FALSE) * lambda3^2 / n
if (verbose > 0){
cat("Additional skewness term:", additional_term_skewness ,"\n")
}
remainder_term <-
r2n_inid_skew(eps = eps, n = n, lambda3 = lambda3,
K3tilde = K3tilde, K4 = K4, K3 = K3)
if (verbose > 0){
cat("Remainder term:", remainder_term ,"\n")
}
return(main_term + additional_term_skewness + remainder_term)
}
#' Compute the bound of Theorem A.4
#' (Theorem 3.1 under Assumption 2.1: inid case)
#' in the noskewness case (Equation (24))
#' WITHOUT the term involving the integral of f_{S_n}
#' @examples
#' Bound_EE1_cont_inid_noskew_wo_int_fSn(n = 300, eps = 0.1, K4 = 9, K3tilde = 6)
#' Bound_EE1_cont_inid_noskew_wo_int_fSn(n = 300, eps = 0.1, K4 = 12, K3tilde = 6)
#'
#' @noRd
Bound_EE1_cont_inid_noskew_wo_int_fSn <- function(n, eps, K4, K3tilde, verbose)
{
if (verbose > 0){
cat("Continuous, inid, no-skewed case.\n")
}
main_term <-
Bound_EE1_cont_common_part_noskewness(eps = eps, n = n, K4 = K4)
if (verbose > 0){
cat("Main term:", main_term ,"\n")
}
remainder_term <-
r2n_inid_noskew(eps = eps, n = n, K3tilde = K3tilde, K4 = K4)
if (verbose > 0){
cat("Remainder term:", remainder_term ,"\n")
}
return(main_term + remainder_term)
}
#' Compute the bound of Theorem A.5
#' (Theorem 3.1 under Assumption 2.2: iid case)
#' in the skewness case (Equation (29))
#' WITHOUT the term involving the integral of f_{S_n}
#'
#' @examples
#' Bound_EE1_cont_iid_skew_wo_int_fSn(n = 300, eps = 0.1, K4 = 9, K3tilde = 6, lambda3 = 1, K3 = 4)
#' Bound_EE1_cont_iid_skew_wo_int_fSn(n = 500, eps = 0.1, K4 = 9, K3tilde = 6, lambda3 = 1, K3 = 4)
#'
#' @noRd
#'
Bound_EE1_cont_iid_skew_wo_int_fSn <- function(n, eps, K4, K3, lambda3, K3tilde, verbose)
{
if (verbose > 0){
cat("Continuous, iid, potentially skewed case.\n")
}
main_term <-
Bound_EE1_cont_common_part_noskewness(eps = eps, n = n, K4 = K4)
if (verbose > 0){
cat("Main term:", main_term ,"\n")
}
additional_term_skewness <-
0.037 * e_3(eps = eps) * lambda3^2 / n
if (verbose > 0){
cat("Additional skewness term:", additional_term_skewness ,"\n")
}
remainder_term <-
r2n_iid_skew(eps = eps, n = n, lambda3 = lambda3,
K3tilde = K3tilde, K4 = K4, K3 = K3, verbose = verbose - 1)
if (verbose > 0){
cat("Remainder term:", remainder_term ,"\n")
}
return(main_term + additional_term_skewness + remainder_term)
}
#' Compute the bound of Theorem A.5
#' (Theorem 3.1 under Assumption 2.2: iid case)
#' in the noskewness case (Equation (30))
#' WITHOUT the term involving the integral of f_{S_n}
#'
#' @examples
#' Bound_EE1_cont_iid_noskew_wo_int_fSn(n = 300, eps = 0.1, K4 = 9, K3tilde = 6, K3 = 4)
#' Bound_EE1_cont_iid_noskew_wo_int_fSn(n = 300, eps = 0.02, K4 = 9, K3tilde = 6, K3 = 4)
#'
#' @noRd
#'
Bound_EE1_cont_iid_noskew_wo_int_fSn <- function(n, eps, K4, K3, K3tilde, verbose)
{
if (verbose > 0){
cat("Continuous, iid, no-skewed case.\n")
}
main_term <-
Bound_EE1_cont_common_part_noskewness(eps = eps, n = n, K4 = K4)
if (verbose > 0){
cat("Main term:", main_term ,"\n")
}
remainder_term <-
r2n_iid_noskew(eps = eps, n = n, K3tilde = K3tilde, K4 = K4, K3 = K3)
if (verbose > 0){
cat("Remainder term:", remainder_term ,"\n")
}
return(main_term + remainder_term)
}
#------------------------------------------------------------------------------#
# Main term #####
#------------------------------------------------------------------------------#
#' Main term of Theorem A.4 and A.5, excluding skewness
#'
#' @examples
#' Bound_EE1_cont_common_part_noskewness(n = 300, eps = 0.1, K4 = 9)
#' Bound_EE1_cont_common_part_noskewness(n = 1000, eps = 0.1, K4 = 9)
#'
#' @noRd
#'
Bound_EE1_cont_common_part_noskewness <- function(n, eps, K4){
return(
0.327 * K4 * (1/12 + 1 / (4 * (1 - 3*eps)^2)) / n
)
}
#------------------------------------------------------------------------------#
# Remainder terms #####
#------------------------------------------------------------------------------#
#' Compute the remainder r_{2,n}^{inid, skew}(epsilon)
#' defined in Equation (27) of the paper, in section A.4
#'
#' @examples
#' r2n_inid_skew(eps = 0.1, n = 200, lambda3 = 2, K3tilde = 6, K3 = 5, K4 = 9)
#' r2n_inid_skew(eps = 0.1, n = 500, lambda3 = 2, K3tilde = 6, K3 = 5, K4 = 12)
#'
#' @noRd
#'
r2n_inid_skew <- function(n, eps, K4, K3, lambda3, K3tilde)
{
value_Rn_inid_integrated <- Rn_inid_integrated(
eps = eps, n = n, K4 = K4, lambda3 = lambda3, noskewness = FALSE)
value_Delta_curly_brace_part <- Delta_curly_brace_part_r2n(
eps = eps, p = 3, n = n, K4 = K4, K3tilde = K3tilde)
upper_end_Gamma <- 16 *pi^3 * n^2 / K3tilde^4
lower_end_Gamma <- pmin( sqrt(2*eps) * (n/K4)^(1/4) , upper_end_Gamma )
return(
1.2533 * K3tilde^4 / (16 * pi^4 * n^2) +
0.3334 * K3tilde^4 * abs(lambda3) / (16 * pi^4 * n^(5/2)) +
14.1961 * K3tilde^16 / ((2*pi)^16 * n^8) +
4.3394 * K3tilde^12 * abs(lambda3) / ((2*pi)^12 * n^(13/2)) +
abs(lambda3) * abs(Upper_incomplete_gamma(3/2, upper_end_Gamma) -
Upper_incomplete_gamma(3/2, lower_end_Gamma) ) / sqrt(n) +
value_Rn_inid_integrated +
Value_cst_bound_modulus_psi() * K3 * value_Delta_curly_brace_part / (6 * pi * sqrt(n)) +
common_diffGamma_r2n(n = n, K3tilde = K3tilde)
)
}
#' Compute the remainder r_{2,n}^{inid, noskew}(epsilon)
#' defined in Equation (28) of the paper, in section A.4
#'
#' @examples
#' r2n_inid_noskew(eps = 0.1, n = 200, K3tilde = 6, K4 = 9)
#' r2n_inid_noskew(eps = 0.1, n = 500, K3tilde = 6, K4 = 12)
#'
#' @noRd
#'
r2n_inid_noskew <- function(eps, n, K3tilde, K4)
{
value_Rn_inid_integrated <- Rn_inid_integrated(
eps = eps, noskewness = TRUE, n = n, K4 = K4)
value_Delta_curly_brace_part <- Delta_curly_brace_part_r2n(
eps = eps, p = 4, n = n, K4 = K4, K3tilde = K3tilde)
return(
1.2533 * K3tilde^4 / (16 * pi^4 * n^2) +
14.1961 * K3tilde^16 / ((2*pi)^16 * n^8) +
value_Rn_inid_integrated +
Value_cst_bound_modulus_psi() * K4 * value_Delta_curly_brace_part / (6 * pi * n) +
common_diffGamma_r2n(n = n, K3tilde = K3tilde)
)
}
#' Compute the remainder r_{2,n}^{iid, skew}(epsilon)
#' defined in Equation (33) of the paper, in section A.5
#'
#' @examples
#' r2n_iid_skew(eps = 0.1, n = 200, lambda3 = 2, K3tilde = 6, K3 = 5, K4 = 9)
#' r2n_iid_skew(eps = 0.1, n = 200, lambda3 = 2, K3tilde = 6, K3 = 5, K4 = 12)
#'
#' @noRd
#'
r2n_iid_skew <- function(eps, n, lambda3, K3tilde, K4, K3, verbose = 0)
{
value_Rn_iid_integrated <- Rn_iid_integrated(
eps = eps, n = n, K4 = K4, lambda3 = lambda3, noskewness = FALSE)
if (verbose > 0){
cat(" Rn_iid_integrated:", value_Rn_iid_integrated , "\n")
}
upper_end_Gamma_1 <- 16 * pi^3 * n^2 / K3tilde^4
lower_end_Gamma_1 <- pmin( sqrt(2*eps) * (n/K4)^(1/4) , upper_end_Gamma_1 )
upper_end_Gamma_2 <- 2^5 * pi^6 * n^4 / K3tilde^8
lower_end_Gamma_2 <- pmin( eps * sqrt(n / (16 * K4)), upper_end_Gamma_2)
r2n_iid_skew_1 = 1.2533 * K3tilde^4 / (16 * pi^4 * n^2)
r2n_iid_skew_2 = 0.3334 * K3tilde^4 * abs(lambda3) / (16 * pi^4 * n^(5/2))
r2n_iid_skew_3 = 14.1961 * K3tilde^16 / ((2*pi)^16 * n^8)
r2n_iid_skew_4 = 4.3394 * K3tilde^12 * abs(lambda3) / ((2*pi)^12 * n^(13/2))
r2n_iid_skew_5 = abs(lambda3) * (Upper_incomplete_gamma(3/2, lower_end_Gamma_1) -
Upper_incomplete_gamma(3/2, upper_end_Gamma_1)) / sqrt(n)
r2n_iid_skew_6 = Value_cst_bound_modulus_psi() * 2^(5/2) * K3 / (3 * pi * sqrt(n)) *
(Upper_incomplete_gamma(3/2, lower_end_Gamma_2) -
Upper_incomplete_gamma(3/2, upper_end_Gamma_2))
r2n_iid_skew_7 = 1.306 * ( e_2n(eps = eps, noskewness = FALSE ,
n = n, K4 = K4, lambda3 = lambda3)
- e_3(eps = eps) ) * lambda3^2 / (36 * n)
r2n_iid_skew_8 = common_diffGamma_r2n(n = n, K3tilde = K3tilde)
result = r2n_iid_skew_1 + r2n_iid_skew_2 + r2n_iid_skew_3 + r2n_iid_skew_4 +
r2n_iid_skew_5 + value_Rn_iid_integrated +
r2n_iid_skew_6 + r2n_iid_skew_7 + r2n_iid_skew_8
if (verbose > 0){
cat(" Other components of r2n_iid_skew:\n ",
paste0(paste0(
c("r2n_iid_skew_1", "r2n_iid_skew_2", "r2n_iid_skew_3", "r2n_iid_skew_4",
"r2n_iid_skew_5", "r2n_iid_skew_6", "r2n_iid_skew_7", "r2n_iid_skew_8"), ": ",
c(r2n_iid_skew_1, r2n_iid_skew_2, r2n_iid_skew_3, r2n_iid_skew_4,
r2n_iid_skew_5, r2n_iid_skew_6, r2n_iid_skew_7, r2n_iid_skew_8)) , "\n ") )
}
if (verbose > 1){
cat(" Components of r2n_iid_skew_6:\n")
cat(" Cst:", Value_cst_bound_modulus_psi(), "\n")
cat(" K3:", K3, "\n")
cat(" lower_end_Gamma_2:", lower_end_Gamma_2, "\n")
cat(" upper_end_Gamma_2:", upper_end_Gamma_2, "\n")
cat(" Upper_incomplete_gamma_1:", Upper_incomplete_gamma(3/2, lower_end_Gamma_2), "\n")
cat(" Upper_incomplete_gamma_2:", Upper_incomplete_gamma(3/2, upper_end_Gamma_2), "\n\n")
cat("Note that 'r2n_iid_skew_6' decrease exponentially fast to 0,",
"but this only occurs asymptotically.\n",
"For n around 10^6 this term is still visible,",
"and this term completely disappear (< 10^{-10}) for n > 10^8.\n",
"It is computed as: \n Cst * 2^(5/2) * K3 / (3 * pi * sqrt(n))",
"* (Upper_incomplete_gamma_1 - Upper_incomplete_gamma_2)",
"\n Here it is: \n ", Value_cst_bound_modulus_psi(),
"*", "2^(5/2) *", K3, "/", "(3 * pi *", sqrt(n), ")",
"* (", Upper_incomplete_gamma(3/2, lower_end_Gamma_2),
"-", Upper_incomplete_gamma(3/2, upper_end_Gamma_2), ")",
"\n which gives: ", r2n_iid_skew_6, ".\n\n")
}
return (result)
}
#' Compute the remainder r_{2,n}^{iid, noskew}(epsilon)
#' defined in Equation (34) of the paper, in section A.5
#'
#' @examples
#' r2n_iid_noskew(eps = 0.1, n = 200, K3tilde = 6, K4 = 9, K3 = 4)
#' r2n_iid_noskew(eps = 0.1, n = 500, K3tilde = 6, K4 = 12, K3 = 7)
#'
#' @noRd
#'
r2n_iid_noskew <- function(eps, n, K3tilde, K4, K3)
{
value_Rn_iid_integrated <- Rn_iid_integrated(
eps = eps, n = n, K4 = K4, noskewness = TRUE)
upper_end_Gamma <- 2^5 * pi^6 * n^4 / K3^8
lower_end_Gamma <- pmin( eps * sqrt(n / (16 * K4)) , upper_end_Gamma)
return(
1.2533 * K3tilde^4 / (16 * pi^4 * n^2) +
14.1961 * K3tilde^16 / ((2*pi)^16 * n^8) +
value_Rn_iid_integrated +
16 * Value_cst_bound_modulus_psi() * K3 *
abs( Upper_incomplete_gamma(2, upper_end_Gamma) -
Upper_incomplete_gamma(2, lower_end_Gamma) ) /(3 * pi * n) +
common_diffGamma_r2n(n = n, K3tilde = K3tilde)
)
}
#------------------------------------------------------------------------------#
# Helper functions for the remainder terms #####
#------------------------------------------------------------------------------#
#' Compute the curly brace related to Delta for
#' r_{2,n}^{inid, skew} and r_{2,n}^{inid, noskew}
#'
#' @param p : parameter not introduced in the paper but to wrap-up
#' the two expressions for r_{2,n}^{inid, skew} and r_{2,n}^{inid, noskew}
#' p = 3 for r_{2,n}^{inid, skew}
#' p = 4 for r_{2,n}^{inid, noskew}
#'
#' @examples
#' Delta_curly_brace_part_r2n(eps = 0.1, p = 3, n = c(150, 2000), K4 = 10, K3tilde = 5)
#'
#' @noRd
#'
Delta_curly_brace_part_r2n <- function(eps, p, n, K4, K3tilde){
Delta <- Delta_of_K4_and_n(K4 = K4, n = n)
upper_end_Delta0 <- 16 * pi^3 * n^2 / K3tilde^4
lower_end_Delta0 <- sqrt(2*eps) * (n/K4)^(1/4)
upper_end_Delta_not0 = Delta * pmin(2 * eps * sqrt(n/K4) ,
2^8 * pi^6 * n^4 / K3tilde^8)
lower_end_Delta_not0 = 2^8 * pi^6 * Delta * n^4 / K3tilde^8
value = ifelse(Delta == 0,
yes = ifelse(upper_end_Delta0 <= lower_end_Delta0,
0,
(upper_end_Delta0^p - lower_end_Delta0^p) / p ) ,
no = 0.5 * abs(Delta)^(- p/2) *
abs( Lower_incomplete_gamma(p / 2, lower_end_Delta_not0) -
Lower_incomplete_gamma(p / 2, upper_end_Delta_not0) )
)
return(value)
}
#' @examples
#' common_diffGamma_r2n(n = 300, K3tilde = 6)
#'
#' @noRd
common_diffGamma_r2n <- function(n, K3tilde)
{
bound_modulus_psi <- Value_cst_bound_modulus_psi()
t1star <- Value_t1star()
valueT <- 16 * pi^4 * n^2 / K3tilde^4
shortcut <- (1 - 4 * pi * Value_chi1() * t1star)
J4 <- bound_modulus_psi / pi *
abs(Upper_incomplete_gamma(0, pmin(valueT^(1/2),
valueT^2) * shortcut / (2 * pi^2) ) -
Upper_incomplete_gamma(0, pmin(t1star^2 * valueT^(1/2),
valueT^2 / pi^2) * shortcut / 2) )
J5 <- bound_modulus_psi / pi *
abs(Upper_incomplete_gamma(0, pmin(valueT^(1/2), valueT^2) / (2 * pi^2) ) -
Upper_incomplete_gamma(0, valueT^2 /(2 * pi^2) ) )
return (J4 + J5)
}
|
/scratch/gouwar.j/cran-all/cranData/BoundEdgeworth/R/Bound_EE1_cont.R
|
# These are the functions to compute the bounds for Theorem A.2 and A.3
#------------------------------------------------------------------------------#
# Main functions #####
#------------------------------------------------------------------------------#
#' Compute the bound of Theorem A.2
#' (Theorem 2.1 under Assumption 2.1: inid, no-continuity)
#' in the skewness case (Equation (11))
#'
#' @examples
#' Bound_EE1_nocont_inid_skew(n = 300, eps = 0.1, K4 = 9, K3tilde = 6, lambda3 = 1, K3 = 4)
#' Bound_EE1_nocont_inid_skew(n = 500, eps = 0.1, K4 = 9, K3tilde = 6, lambda3 = 1, K3 = 4)
#'
#' @noRd
#'
Bound_EE1_nocont_inid_skew <- function(n, eps, K4, K3, K3tilde, lambda3, verbose)
{
if (verbose > 0){
cat("Potentially non continuous, inid, potentially skewed case.\n")
}
main_term <-
Bound_EE1_nocont_common_part_noskewness(eps = eps, n = n,
K4 = K4, K3tilde = K3tilde)
if (verbose > 0){
cat("Main term:", main_term ,"\n")
}
additional_term_skewness <-
(0.054 * abs(lambda3) * K3tilde +
0.037 * e_1n(eps = eps, noskewness = FALSE) * lambda3^2) / n
if (verbose > 0){
cat("Additional skewness term:", additional_term_skewness ,"\n")
}
remainder_term <-
r1n_inid_skew(eps = eps, n = n, lambda3 = lambda3,
K3tilde = K3tilde, K4 = K4, K3 = K3)
if (verbose > 0){
cat("Remainder term:", remainder_term ,"\n")
}
return(main_term + additional_term_skewness + remainder_term)
}
#' Compute the bound of Theorem A.2
#' (Theorem 2.1 under Assumption 2.1: inid, no-continuity)
#' in the noskewness case (Equation (12))
#'
#' @examples
#' Bound_EE1_nocont_inid_noskew(n = 300, eps = 0.1, K4 = 9, K3tilde = 6)
#' Bound_EE1_nocont_inid_noskew(n = 300, eps = 0.2, K4 = 9, K3tilde = 6)
#' Bound_EE1_nocont_inid_noskew(n = 300, eps = 0.05, K4 = 9, K3tilde = 6)
#'
#' @noRd
#'
Bound_EE1_nocont_inid_noskew <- function(n, eps, K4, K3tilde, verbose)
{
if (verbose > 0){
cat("Potentially non continuous, inid, no-skewed case.\n")
}
main_term <-
Bound_EE1_nocont_common_part_noskewness(eps = eps, n = n,
K4 = K4, K3tilde = K3tilde)
if (verbose > 0){
cat("Main term:", main_term ,"\n")
}
remainder_term <-
r1n_inid_noskew(eps = eps, n = n, K4 = K4, K3tilde = K3tilde)
if (verbose > 0){
cat("Remainder term:", remainder_term ,"\n")
}
return(main_term + remainder_term)
}
#' Compute the bound of Theorem A.3
#' (Theorem 2.1 under Assumption 2.2: iid, no-continuity)
#' in the skewness case (Equation (17))
#'
#' @examples
#' Bound_EE1_nocont_iid_skew(n = 200, eps = 0.1, K4 = 9, K3 = 3, lambda3 = 1, K3tilde = 5)
#' Bound_EE1_nocont_iid_skew(n = 500, eps = 0.2, K4 = 12, K3 = 4, lambda3 = 3, K3tilde = 7)
#'
#' @noRd
#'
Bound_EE1_nocont_iid_skew <- function(n, eps, K4, K3, lambda3, K3tilde, verbose)
{
if (verbose > 0){
cat("Potentially non continuous, iid, potentially skewed case.\n")
}
main_term <-
Bound_EE1_nocont_common_part_noskewness(eps = eps, n = n,
K4 = K4, K3tilde = K3tilde)
if (verbose > 0){
cat("Main term:", main_term ,"\n")
}
additional_term_skewness <-
(0.054 * abs(lambda3) * K3tilde + 0.037 * e_3(eps) * lambda3^2) / n
if (verbose > 0){
cat("Additional skewness term:", additional_term_skewness ,"\n")
}
remainder_term <-
r1n_iid_skew(eps = eps, n = n, lambda3 = lambda3,
K3tilde = K3tilde, K4 = K4, K3 = K3)
if (verbose > 0){
cat("Remainder term:", remainder_term ,"\n")
}
return(main_term + additional_term_skewness + remainder_term)
}
#' Compute the bound of Theorem A.3
#' (Theorem 2.1 under Assumption 2.2: iid, no-continuity)
#' in the noskewness case (Equation (18))
#'
#' @examples
#' Bound_EE1_nocont_iid_noskew(n = 200, eps = 0.1, K4 = 9, K3tilde = 5)
#' Bound_EE1_nocont_iid_noskew(n = 500, eps = 0.2, K4 = 12, K3tilde = 7)
#'
#' @noRd
#'
Bound_EE1_nocont_iid_noskew <- function(n, eps, K4, K3tilde, verbose)
{
if (verbose > 0){
cat("Potentially non continuous, iid, no-skewed case.\n")
}
main_term <-
Bound_EE1_nocont_common_part_noskewness(eps = eps, n = n, K4 = K4, K3tilde = K3tilde)
if (verbose > 0){
cat("Main term:", main_term ,"\n")
}
remainder_term <-
r1n_iid_noskew(eps = eps, n = n, K4 = K4, K3tilde = K3tilde)
if (verbose > 0){
cat("Remainder term:", remainder_term ,"\n")
}
return(main_term + remainder_term)
}
#------------------------------------------------------------------------------#
# Main term #####
#------------------------------------------------------------------------------#
# Main term of Theorem A.2 and A.3, excluding skewness
#'
#' @examples
#' Bound_EE1_nocont_common_part_noskewness(n = 300, eps = 0.1, K4 = 9, K3tilde = 5)
#' Bound_EE1_nocont_common_part_noskewness(n = 1000, eps = 0.1, K4 = 9, K3tilde = 5)
#'
#' @noRd
#'
Bound_EE1_nocont_common_part_noskewness <- function(eps, n, K4, K3tilde){
return(
0.1995 * K3tilde / sqrt(n) +
(0.031 * K3tilde^2 + 0.327 * K4 * (1/12 + 1 / (4 * (1 - 3*eps)^2))) / n
)
}
#------------------------------------------------------------------------------#
# Remainder terms #####
#------------------------------------------------------------------------------#
#' Compute the remainder r_{1,n}^{inid, skew}(epsilon)
#' defined in Equation (15) of the paper, in section A.2
#'
#' @examples
#' r1n_inid_skew(eps = 0.1, n = 200, lambda3 = 2, K3tilde = 6, K3 = 5, K4 = 9)
#' r1n_inid_skew(eps = 0.1, n = 500, lambda3 = 2, K3tilde = 6, K3 = 5, K4 = 12)
#'
#' @noRd
#'
r1n_inid_skew <- function(eps, n, lambda3, K3tilde, K3, K4)
{
value_Rn_inid_integrated <- Rn_inid_integrated(
eps = eps, n = n, K4 = K4, lambda3 = lambda3, noskewness = FALSE)
value_Delta_curly_brace_part <- Delta_curly_brace_part_r1n(
eps = eps, p = 3, n = n, K4 = K4, K3tilde = K3tilde)
min_lower_end_Gamma <- pmin(sqrt(2*eps) * (n/K4)^(1/4), 2 * sqrt(n) / K3tilde)
return(
(14.1961 + 67.0415) * K3tilde^4 / (16 * pi^4 * n^2) +
4.3394 * abs(lambda3) * K3tilde^3 / (8 * pi^3 * n^2) +
value_Rn_inid_integrated +
abs(lambda3) *
(Upper_incomplete_gamma(3/2, min_lower_end_Gamma) -
Upper_incomplete_gamma(3/2, 2*sqrt(n) / K3tilde)) / sqrt(n) +
Value_cst_bound_modulus_psi() * K3 *
value_Delta_curly_brace_part / (6 * pi * sqrt(n))
)
}
#' Compute the remainder r_{1,n}^{inid, noskew}(epsilon)
#' defined in Equation (16) of the paper, in section A.2
#'
#' @examples
#' r1n_inid_noskew(eps = 0.1, n = 150, K3tilde = 4, K4 = 9)
#' r1n_inid_noskew(eps = 0.05, n = 500, K3tilde = 4, K4 = 9)
#'
#' @noRd
#'
r1n_inid_noskew <- function(eps, n, K3tilde, K4)
{
value_Rn_inid_integrated <- Rn_inid_integrated(
eps = eps, noskewness = TRUE, n = n, K4 = K4)
value_Delta_curly_brace_part <- Delta_curly_brace_part_r1n(
eps = eps, p = 4, n = n, K4 = K4, K3tilde = K3tilde)
return(
(14.1961 + 67.0415) * K3tilde^4 / (16 * pi^4 * n^2) +
value_Rn_inid_integrated +
Value_cst_bound_modulus_psi() * K4 *
value_Delta_curly_brace_part / (6 * pi * n)
)
}
#' Compute the remainder term r_{1,n}^{iid, skew}(epsilon)
#' defined in Equation (21) of the paper, in section A.3
#'
#' @examples
#' r1n_iid_skew(eps = 0.1, n = 200, K4 = 9, K3 = 5, K3tilde = 7, lambda3 = 6)
#' r1n_iid_skew(eps = 0.05, n = 100, K4 = 9, K3 = 5, K3tilde = 7, lambda3 = 6)
#'
#' @noRd
#'
r1n_iid_skew <- function(eps, n, K4, K3, K3tilde, lambda3)
{
value_Rn_iid_integrated <- Rn_iid_integrated(
eps = eps, noskewness = FALSE, n = n, K4 = K4, lambda3 = lambda3)
value_e2n <- e_2n(
eps = eps, noskewness = FALSE, n = n, K4 = K4, lambda3 = lambda3)
min_lower_end_Gamma <- pmin(sqrt(2*eps) * (n/K4)^(1/4), 2 * sqrt(n) / K3tilde)
return(
(14.1961 + 67.0415) * K3tilde^4 / (16 * pi^4 * n^2) +
4.3394 * abs(lambda3) * K3tilde^3 / (8 * pi^3 * n^2) +
value_Rn_iid_integrated +
1.306 * (value_e2n - e_3(eps)) * lambda3^2 / (36 * n) +
abs(lambda3) *
(Upper_incomplete_gamma(3/2, min_lower_end_Gamma) -
Upper_incomplete_gamma(3/2, 2 * sqrt(n) / K3tilde)) / sqrt(n) +
Value_cst_bound_modulus_psi() * 2^(5/2) * K3 / (3 * pi * sqrt(n)) *
(Upper_incomplete_gamma(3/2, min_lower_end_Gamma^2 / 8) -
Upper_incomplete_gamma(3/2, 4 * n / (8 * K3tilde^2)))
)
}
#' Compute the remainder term r_{1,n}^{iid, noskew}(epsilon)
#' defined in Equation (22) of the paper, in section A.3
#'
#' @examples
#' r1n_iid_noskew(eps = 0.1, n = 300, K4 = 9, K3tilde = 6)
#' r1n_iid_noskew(eps = 0.1, n = 500, K4 = 12, K3tilde = 6)
#'
#' @noRd
#'
r1n_iid_noskew <- function(eps, n, K4, K3tilde)
{
value_Rn_iid_integrated <- Rn_iid_integrated(
eps = eps, noskewness = TRUE, n = n, K4 = K4)
min_lower_end_Gamma <- pmin(sqrt(2*eps) * (n/K4)^(1/4), 2 * sqrt(n) / K3tilde)
return(
(14.1961 + 67.0415) * K3tilde^4 / (16 * pi^4 * n^2) +
value_Rn_iid_integrated +
16 * Value_cst_bound_modulus_psi() * K4 / (3 * pi * n) *
(Upper_incomplete_gamma(2, min_lower_end_Gamma^2 / 8) -
Upper_incomplete_gamma(2, 4 * n / (8 * K3tilde^2)))
)
}
#------------------------------------------------------------------------------#
# Helper functions for the remainder terms #####
#------------------------------------------------------------------------------#
#' Compute the quantity \eqn{\Delta} that intervenes in the expression
#' of r_{1,n}^{inid, skew} and r_{1,n}^{inid, noskew}
#'
#' @noRd
Delta_of_K4_and_n <- function(K4, n){
return((1 - 4*Value_chi1() - sqrt(K4/n)) / 2)
}
#' Compute the curly brace term related to Delta for
#' r_{1,n}^{inid, skew} and r_{1,n}^{inid, noskew}
#'
#' @param p : parameter not introduced in the paper but to wrap-up
#' the two expressions for r_{1,n}^{inid, skew} and r_{1,n}^{inid, noskew}
#' p = 3 for r_{1,n}^{inid, skew}
#' p = 4 for r_{1,n}^{inid, noskew}
#'
#' @examples
#' Delta_curly_brace_part_r1n(eps = 0.1, p = 3, n = c(150, 2000), K4 = 10, K3tilde = 5)
#'
#' @noRd
#'
Delta_curly_brace_part_r1n <- function(eps, p, n, K4, K3tilde){
Delta <- Delta_of_K4_and_n(K4 = K4, n = n)
upper_end_Delta0 <- 2 * sqrt(n) / K3tilde
lower_end_Delta0 <- sqrt(2*eps) * (n/K4)^(1/4)
upper_end_Delta_not0 <- 2 * Delta * pmin(eps * sqrt(n/K4), 2 * n / K3tilde^2)
lower_end_Delta_not0 <- 4 * Delta * n / K3tilde^2
value = ifelse(Delta == 0,
yes = ifelse(upper_end_Delta0 <= lower_end_Delta0,
0,
(upper_end_Delta0^p - lower_end_Delta0^p) / p ),
no = 0.5 * abs(Delta)^(- p/2) *
abs( Lower_incomplete_gamma(p/2, lower_end_Delta_not0) -
Lower_incomplete_gamma(p/2, upper_end_Delta_not0) )
)
return(value)
}
#' Function to computes e_3(epsilon)
#' defined in Section A.3
#'
#' @example
#' e_3(eps = 0.1)
#'
#' @noRd
#'
e_3 <- function(eps){
return(exp(eps^2 / 6 + eps^2 / (2 * (1 - 3*eps))^2))
}
|
/scratch/gouwar.j/cran-all/cranData/BoundEdgeworth/R/Bound_EE1_nocont.R
|
# These are the functions to call recurrent numerical constants
#' @return the value of the constant \eqn{\chi_1}
#' See paragraph 'Additional notation' at the end of section 1 of the paper
#'
#' @noRd
#'
Value_chi1 <- function(){return(0.09916191)}
#' @return the value of the constant \eqn{t_1^*}
#' See paragraph 'Additional notation' at the end of section 1 of the paper
#'
#' @noRd
#'
Value_t1star <- function(){return(0.6359658)}
#' @return the value of the numerical constant that appears
#' to upper bound the modulus of the function \eqn{\Psi}
#' See Equation (9), section A.1 of the paper:
#' \eqn{|Psi(t)| \leq 1.0253 / (2 * pi * |t|)}
#' N.B.: the denominator 2 pi is not included as it sometimes cancel out;
#' it only returns the numerator: 1.0253
#'
#' @noRd
#'
Value_cst_bound_modulus_psi <- function(){return(1.0253)}
#' @return the value of the numerical constant that appears
#' to upper bound the absolute value of lambda3 by K3 (Pinelis, 2011, Theorem 1)
#' \eqn{\abs{\lambda_3} \leq 0.621 K_3}
#' See for instance in Example 2.2 of the paper
#'
#' @noRd
#'
Value_cst_bound_abs_lambda3_by_K3 <- function(){return(0.621)}
|
/scratch/gouwar.j/cran-all/cranData/BoundEdgeworth/R/Constants.R
|
#' Computation of power and sufficient sample size for the one-sided Gauss test
#'
#' Let \mjseqn{X_1, \dots, X_n} be \mjseqn{n} i.i.d. variables
#' with mean \mjseqn{\mu}, variance \mjseqn{\sigma^2}.
#' Assume that we want to test the hypothesis
#' \mjseqn{H_0: \mu \leq \mu_0} against the alternative \mjseqn{H_1: \mu \leq \mu_0}.
#' Let \mjseqn{\eta := (\mu - \mu_0) / \sigma} be the effect size,
#' i.e. the distance between the null and the alternative hypotheses,
#' measured in terms of standard deviations.
#'
#' There is a relation between the sample size \code{n}, the effect size \code{eta}
#' and the power \code{beta}. This function takes as an input two of these quantities
#' and return the third one.
#'
#' \loadmathjax
#' @import mathjaxr
#'
#' @param n sample size
#'
#' @param eta the effect size \mjseqn{\eta} that
#' characterizes the alternative hypothesis
#'
#' @param beta the power of detecting the effect \code{eta} using the sample size \code{n}
#'
#' @param alpha the level of the test
#'
#' @param K4 the kurtosis of the \mjseqn{X_i}
#'
#' @param kappa Regularity parameter of the distribution of the \mjseqn{X_i}
#' It corresponds to a bound on the modulus of the characteristic function
#' of the standardized \mjseqn{X_n}.
#' More precisely, \code{kappa} is an upper bound on
#' \mjseqn{kappa :=} sup of modulus of \mjseqn{f_{X_n / \sigma_n}(t)}
#' over all \mjseqn{t} such that \mjseqn{|t| \geq 2 t_1^* \pi / K3tilde}.
#'
#' @return The computed value of either the sufficient sample size \code{n},
#' or the minimum effect size \code{eta}, or the power \code{beta}.
#'
#' @references
#' Derumigny A., Girard L., and Guyonvarch Y. (2021).
#' Explicit non-asymptotic bounds for the distance to the first-order Edgeworth expansion,
#' ArXiv preprint \href{https://arxiv.org/abs/2101.05780}{arxiv:2101.05780}.
#'
#' @examples
#'
#' # Sufficient sample size to detect an effect of 0.5 standard deviation with probability 80%
#' Gauss_test_powerAnalysis(eta = 0.5, beta = 0.8)
#' # We can detect an effect of 0.5 standard deviations with probability 80% for n >= 548
#'
#' # Power of an experiment to detect an effect of 0.5 with a sample size of n = 800
#' Gauss_test_powerAnalysis(eta = 0.5, n = 800)
#' # We can detect an effect of 0.5 standard deviations with probability 85.1% for n = 800
#'
#' # Smallest effect size that can be detected with a probability of 80% for a sample size of n = 800
#' Gauss_test_powerAnalysis(n = 800, beta = 0.8)
#' # We can detect an effect of 0.114 standard deviations with probability 80% for n = 800
#'
#'
#' @export
#'
Gauss_test_powerAnalysis = function(eta = NULL, n = NULL, beta = NULL,
alpha = 0.05, K4 = 9, kappa = 0.99){
if (is.null(eta) + is.null(n) + is.null(beta) != 1){
stop("Exactly two of 'eta', 'n', 'beta' should be known ",
"( = not set to NULL) to be able to find the third one.")
}
if (is.null(beta)){
result = Gauss_test_power(eta = eta, n = n,
alpha = alpha, K4 = K4, kappa = kappa)
names(result) <- "beta"
} else if (is.null(n)){
res = stats::uniroot(
f = function(n){Gauss_test_power(eta = eta, n = n,
alpha = alpha, K4 = K4, kappa = kappa) - beta},
interval = c(1, 10^10))
result = ceiling(res$root)
names(result) <- "n"
} else {
res = stats::uniroot(
f = function(eta){Gauss_test_power(eta = eta, n = n,
alpha = alpha, K4 = K4, kappa = kappa) - beta},
interval = c(0, 1))
result = res[["root"]]
names(result) <- "eta"
}
return (result)
}
# compute beta from eta and n
Gauss_test_power = function(eta, n, alpha, K4, kappa){
delta_n = BoundEdgeworth::Bound_BE(
setup = list(continuity = TRUE, iid = TRUE, no_skewness = FALSE),
n = n, K4 = K4, regularity = list(kappa = kappa), eps = 0.1)
qnormalpha = stats::qnorm(1 - alpha)
result = 1 - stats::pnorm( qnormalpha - eta * sqrt(n) ) -
0.621 * K4^(3/4) * (1 - ( qnormalpha - eta * sqrt(n) )^2 ) *
stats::dnorm( qnormalpha - eta * sqrt(n) ) / (6 * sqrt(n)) - delta_n
return (result)
}
|
/scratch/gouwar.j/cran-all/cranData/BoundEdgeworth/R/Gauss_test_power.R
|
#------------------------------------------------------------------------------#
# Main function #####
#------------------------------------------------------------------------------#
#' Function that compute integrated R_n^iid
#' denoted with a bar: \eqn{\bar{R}_n^{iid}(eps)} in the paper
#' and defined in section C.3.2.
#'
#' @examples
#' Rn_iid_integrated(eps = 0.1, noskewness = TRUE, n = 300, K4 = 9)
#' Rn_iid_integrated(eps = 0.1, noskewness = FALSE, n = 300, K4 = 9, lambda3 = 6)
#'
#' @noRd
#'
Rn_iid_integrated <- function(eps, noskewness, n, K4, lambda3 = NULL)
{
bound_modulus_psi <- Value_cst_bound_modulus_psi()
denom <- 2 * (1 - 3*eps)^2 * pi
tildeA2n <- bound_modulus_psi / denom * K4 / (24 * n^2) *
2^(3) * Standard_gamma(4)
tildeA5n <- bound_modulus_psi / denom * K4^2 / (576 * n^3) *
2^(4) * Standard_gamma(5)
val_e_2n <- e_2n(
eps = eps, noskewness = noskewness, n = n, K4 = K4, lambda3 = lambda3)
val_P_2n <- P_2n(
eps = eps, noskewness = noskewness, n = n, K4 = K4, lambda3 = lambda3)
tildeA6n <- bound_modulus_psi / pi * val_e_2n / (8 * n^2) *
(K4 / 12 + 1 / (4 * (1 - 3*eps)^2) + val_P_2n / (576 * (1 - 3*eps)^2)) *
2^(4) * Standard_gamma(5)
if (isTRUE(noskewness)) {
tildeA1n <- tildeA3n <- tildeA4n <- tildeA7n <- 0
} else {
tildeA1n <- bound_modulus_psi / denom * abs(lambda3) / (6 * n^(3/2)) *
2^(0.5) * Standard_gamma(1.5)
tildeA3n <- bound_modulus_psi / denom * lambda3^2 / (36 * n^2) *
2^(3) * Standard_gamma(4)
tildeA4n <- bound_modulus_psi / denom * K4 * abs(lambda3) / (72 * n^(5/2)) *
2^(3.5) * Standard_gamma(4.5)
tildeA7n <- bound_modulus_psi / pi * val_e_2n * abs(lambda3) / (12 * n^(3/2)) *
(K4 / 12 + 1 / (4 * (1 - 3*eps)^2) + val_P_2n / (576 * (1 - 3*eps)^2)) *
2^(3.5) * Standard_gamma(4.5)
}
return(tildeA1n + tildeA2n + tildeA3n + tildeA4n + tildeA5n + tildeA6n + tildeA7n)
}
#------------------------------------------------------------------------------#
# Auxiliary functions #####
#------------------------------------------------------------------------------#
#' Function that computes P_{2,n}(eps)
#' defined in section C.2 of the paper.
#'
#' @examples
#' P_2n(eps = 0.1, noskewness = TRUE, n = 500, K4 = 9)
#' P_2n(eps = 0.1, noskewness = FALSE, n = 500, K4 = 9, lambda3 = 6)
#'
#' @noRd
#'
P_2n <- function(eps, noskewness, n, K4, lambda3 = NULL){
val_P_2n_noskewness <-
48 * eps * sqrt(K4/n) +
4 * eps^2 * K4 / n
if (isTRUE(noskewness)) {
val_P_2n <- val_P_2n_noskewness
} else {
val_P_2n <- val_P_2n_noskewness +
96 * sqrt(2*eps) * abs(lambda3) / (K4^(1/4) * n^(1/4)) +
32 * eps * lambda3^2 / sqrt(K4 * n) +
16 * sqrt(2) * K4^(1/4) * abs(lambda3) * eps^(3/2) / n^(3/4)
}
return (val_P_2n)
}
#' Function that computes e_{2,n}(eps)
#' defined in section C.2 of the paper.
#'
#' @examples
#' e_2n(eps = 0.1, noskewness = TRUE, n = 500, K4 = 9)
#' e_2n(eps = 0.1, noskewness = FALSE, n = 500, K4 = 9, lambda3 = 6)
#'
#' @noRd
#'
e_2n <- function(eps, noskewness, n, K4, lambda3 = NULL){
val_P_2n <- P_2n(
eps = eps, noskewness = noskewness, n = n, K4 = K4, lambda3 = lambda3)
val_e_2n <- exp(eps^2 *
(1/6 + 1/(2 * (1 - 3*eps)^2) +
2 * val_P_2n / (576 * (1 - 3*eps)^2)))
return(val_e_2n)
}
|
/scratch/gouwar.j/cran-all/cranData/BoundEdgeworth/R/Rn_iid_integrated.R
|
#------------------------------------------------------------------------------#
# Main function #####
#------------------------------------------------------------------------------#
#' Function that compute integrated R_n^inid
#' denoted with a bar: \eqn{\bar{R}_n^{inid}(eps)} in the paper
#' and defined in section C.3.1.
#'
#' @examples
#' Rn_inid_integrated(eps = 0.1, noskewness = TRUE, n = 200, K4 = 9)
#' Rn_inid_integrated(eps = 0.1, noskewness = FALSE, n = 200, K4 = 9, lambda3 = 6)
#'
#' @noRd
#'
Rn_inid_integrated <- function(eps, noskewness, n, K4, lambda3 = NULL)
{
bound_modulus_psi <- Value_cst_bound_modulus_psi()
denom <- (1 - 3 * eps)^2 * pi
A1n <- bound_modulus_psi / (48 * denom) * (K4 / n)^(3/2) *
2^(3) * Standard_gamma(4)
A2n <- bound_modulus_psi / (24^2 * 2 * denom) * (K4 / n)^2 *
2^(4) * Standard_gamma(5)
val_e1n <- e_1n(eps = eps, noskewness = noskewness)
val_P1n <- P_1n(eps = eps, noskewness = noskewness)
A6n <- bound_modulus_psi * val_e1n / (2 * pi) *
(K4 / n)^2 *
(1/24 + val_P1n / (2 * (1 - 3 * eps)^2))^2 *
2^(4) * Standard_gamma(5)
if (isTRUE(noskewness)) {
A3n <- A4n <- A5n <- A7n <- 0
} else {
A3n <- bound_modulus_psi / (12 * denom) * (K4 / n)^(5/4) *
2^(2.5) * Standard_gamma(3.5)
A4n <- bound_modulus_psi / (72 * denom) * (K4 / n)^(3/2) *
2^(3) * Standard_gamma(4)
A5n <- bound_modulus_psi / (144 * denom) * (K4 / n)^(7/4) *
2^(3.5) * Standard_gamma(4.5)
A7n <- bound_modulus_psi * val_e1n / (6 * pi) *
abs(lambda3) * K4 / n^(3/2) *
(1/24 + val_P1n / (2 * (1 - 3 * eps)^2)) *
2^(4) * Standard_gamma(5)
}
return (A1n + A2n + A3n + A4n + A5n + A6n + A7n)
}
#------------------------------------------------------------------------------#
# Auxiliary functions #####
#------------------------------------------------------------------------------#
#' Function that computes P_{1,n}(eps)
#' defined in section C.1 of the paper.
#'
#' @examples
#' P_1n(eps = 0.1, noskewness = TRUE)
#' P_1n(eps = 0.1, noskewness = FALSE)
#'
#' @noRd
#'
P_1n <- function(eps, noskewness){
val_P_1n_noskewness <-
(144 + 48*eps + 4*eps^2) / 576
if (isTRUE(noskewness)){
val_P_1n <- val_P_1n_noskewness
} else {
additional_part_skewness <-
(96*sqrt(2*eps) + 32*eps + 16*sqrt(2)*eps^(3/2)) / 576
val_P_1n <- val_P_1n_noskewness + additional_part_skewness
}
return(val_P_1n)
}
#' Function that computes e_{1,n}(eps)
#' defined in section C.1 of the paper.
#'
#' @examples
#' e_1n(eps = 0.1, noskewness = TRUE)
#' e_1n(eps = 0.1, noskewness = FALSE)
#'
#' @noRd
#'
e_1n <- function(eps, noskewness){
val_P_1n <- P_1n(eps = eps, noskewness = noskewness)
val_e_1n <- exp(eps^2 * (1/6 + 2*val_P_1n / (1 - 3*eps)^2))
return(val_e_1n)
}
|
/scratch/gouwar.j/cran-all/cranData/BoundEdgeworth/R/Rn_inid_integrated.R
|
# These are special functions used in our bounds
# See paragraph 'Additional notation' at the end of section 1 of the paper
#' Wrap-up for the standard (complete) gamma function
#' denoted \eqn{\Gamma} in the paper.
#' Already implemented as such in R but to avoid confusion with the lower
#' and upper incomplete Gamma functions.
#'
#' @noRd
#'
Standard_gamma <- function(x){
return( gamma(x) )
}
#' Upper Incomplete gamma function
#' denoted \eqn{\Gamma(a,x) := \int_x^{+\infty} u^{a-1} e^{-u} du} in the paper.
#' Can be computed numerically using the package \texttt{expint}~\citep{goulet2016expint} in R.
#' Reference: https://search.r-project.org/CRAN/refmans/expint/html/gammainc.html
#'
#' @noRd
#'
Upper_incomplete_gamma <- function(a, x){
return( suppressWarnings( { expint::gammainc(a = a, x = x) } ) )
}
#' (extended) Lower Incomplete Gamma function
#' \gamma(a, x) := \int_0^x |v|^{a-1} \exp(-v) dv.
#' extended since if x is negative, it is not the usual lower incomplete
#' gamma function due to the absolute value in the integrand.
#'
#' @examples
#' Lower_incomplete_gamma(a = 2, x = 3)
#' stats::pgamma(q = 3, shape = 2, rate = 1, lower.tail = TRUE)
#'
#' Lower_incomplete_gamma(a = 2, x = -0.5)
#' Lower_incomplete_gamma_for_negative_x(a = 2, x = -0.5)
#'
#' # Lower_incomplete_gamma(a = 0, x = -0.5) # defined for a > 0 only
#'
#' Lower_incomplete_gamma(a = 2, x = c(-0.5, -0.2, 3, 8))
#'
#' @noRd
#'
Lower_incomplete_gamma <- function(a, x){
result <- rep(0, length(x))
which_positive <- which(x > 0)
if (length(which_positive > 0)){
result[which_positive] <- gamma(a) * stats::pgamma(x[which_positive], shape = a,
rate = 1, lower.tail = TRUE)
}
which_negative <- which(x < 0)
if (length(which_negative > 0)){
result[which_negative] <- Lower_incomplete_gamma_for_negative_x(a = a, x = x[which_negative])
}
return (result)
}
#' Compute \eqn{\gamma(a,x)} for negative x
#' In this case, the function is not the usual lower incomplete gamma function;
#' we compute it by numerical integration using \code{stats::integrate}.
#'
#' @examples
#' # We check that it is the same
#' Lower_incomplete_gamma_for_negative_x(a = 2, x = -0.5)
#'
#' f_integrand_here <- function(u){abs(u)^(2 - 1) * exp(-u)}
#' stats::integrate(f = f_integrand_here, lower = 0, upper = -0.5)
#'
#' @noRd
#'
Lower_incomplete_gamma_for_negative_x <- function(a, x)
{
# Function to be integrated
f_integrand <- function(u){abs(u)^(a - 1) * exp(-u)}
res_integrate <- unlist(lapply(X = x, FUN = function (x) {
(stats::integrate(f = f_integrand, lower = 0, upper = x))$value} ) )
return( res_integrate )
}
|
/scratch/gouwar.j/cran-all/cranData/BoundEdgeworth/R/SpecialFunctions.R
|
#' @name boundary_null_distrib
#' @title Null distribution for overlap statistics
#' @description
#' Creates custom probability distributions for two boundary statistics (number of subgraphs and length
#' of the longest subgraph). Given a SpatRaster object, simulates n iterations of random raster
#' surfaces from a neutral model.
#'
#' @param x A SpatRaster object.
#' @param convert TRUE if x contains numeric trait data that needs to be converted to boundary intensities. default = FALSE.
#' @param cat TRUE if the input SpatRaster contains a categorical variable. default = FALSE.
#' @param threshold A value between 0 and 1. The proportion of cells to keep as boundary elements. default = 0.2.
#' @param n_iterations An integer indicating the number of iterations for the function.
#' A value of 100 or 1000 is recommended to produce sufficient resolution for downstream
#' statistical tests. default = 10.
#' @param model Neutral model to use. Options: 'random' (stochastic), 'gaussian' (Gaussian random field),
#' and 'random_cluster' (modified random clusters method)
#' @param p If using modified random clusters, proportion of cells to be marked in percolated raster.Higher values of p
#' produce larger clusters. Default: p = 0.5
#' @param progress If progress = TRUE (default) a progress bar will be displayed.
#'
#' @return A list of two probability distribution functions for boundary statistics.
#' @examples \donttest{
#' data(T.cristatus)
#' T.cristatus <- terra::rast(T.cristatus_matrix, crs = T.cristatus_crs)
#' terra::ext(T.cristatus) <- T.cristatus_ext
#'
#' T.crist_bound_null <- boundary_null_distrib(T.cristatus, cat = TRUE, n_iterations = 100,
#' model = 'random_cluster')
#' }
#'
#' @author Amy Luo
#' @references Saura, S. & Martínez-Millán, J. (2000). Landscape patterns simulation with a modified random clusters method. Landscape Ecology, 15:661-678.
#' @export
boundary_null_distrib <- function(x, convert = FALSE, cat = FALSE, threshold = 0.2, n_iterations = 10, model = 'random', p = 0.5,
progress = TRUE) {
# progress bar
if (progress == TRUE) {progress_bar = txtProgressBar(min = 0, max = n_iterations, initial = 0, char = '+', style = 3)}
# make output vectors for repeat loop
n_subgraph = c(); longest_subgraph = c()
# n iterations of random boundaries + stats
rep = 0
repeat {
# simulate random raster with boundary elements ----
repeat {
if (model == 'random') {
x_sim <- random_raster_sim(x)
} else if (model == 'gaussian') {
x_sim <- gauss_random_field_sim(x)
} else if (model == 'random_cluster') {
x_sim <- mod_random_clust_sim(x, p)
}
if (cat == F) {
x_boundary <- define_boundary(x_sim, threshold, convert)
} else {
x_boundary <- categorical_boundary(x_sim)
}
if (sum(terra::values(x_boundary) == 1, na.rm = TRUE) >= 1) {break}
}
# number of subgraphs ----
count <- terra::patches(x_boundary, directions = 8, zeroAsNA = TRUE) %>%
terra::values(.) %>%
max(., na.rm = TRUE)
n_subgraph = append(n_subgraph, count)
# maximum length of a subgraph ----
xpolygon <- terra::subst(x_boundary, 0, NA) %>%
terra::as.polygons(., na.rm = TRUE) %>%
terra::buffer(., 0.001) %>%
terra::disagg(.) %>%
sf::st_as_sf(.)
lengths <- c()
for (i in 1:nrow(xpolygon)) {
lengths <- sf::st_geometry(xpolygon[i,]) %>%
sf::st_cast(., "POINT") %>%
sf::st_distance(.) %>%
max(.) %>%
append(lengths, .) %>%
as.numeric(.)
}
longest_subgraph <- max(lengths) %>%
append(longest_subgraph, .)
# loop count and break ----
rep = rep + 1
if (progress == TRUE) {setTxtProgressBar(progress_bar, rep)}
if (rep >= n_iterations) {
if (progress == TRUE) {close(progress_bar)}
break
}
}
# output
n_subgraph <- pdqr::new_p(n_subgraph, type = 'continuous')
longest_subgraph <- pdqr::new_p(longest_subgraph, type = 'continuous')
distribs <- list(n_subgraph, longest_subgraph)
names(distribs) <- c('n_subgraph', 'longest_subgraph')
message('DONE')
return(distribs)
}
|
/scratch/gouwar.j/cran-all/cranData/BoundaryStats/R/boundary_null_distrib.R
|
# number of subgraphs ----
#' @name n_subgraph
#' @title Number of subgraphs
#' @description Statistical test the for number of subgraphs, or sets of contiguous boundary elements, in the data.
#'
#' @param x A SpatRaster object with boundary elements.
#' @param null_distrib A list of probability functions output from boundary_null_distrib().
#'
#' @return The number of subgraphs in the raster and a p-value.
#' @examples \donttest{
#' data(T.cristatus)
#' T.cristatus <- terra::rast(T.cristatus_matrix, crs = T.cristatus_crs)
#' terra::ext(T.cristatus) <- T.cristatus_ext
#'
#' T.crist_boundaries <- categorical_boundary(T.cristatus)
#' T.crist_bound_null <- boundary_null_distrib(T.cristatus, cat = TRUE, n_iterations = 100,
#' model = 'random_cluster')
#'
#' n_subgraph(T.crist_boundaries, T.crist_bound_null)
#' }
#'
#' @author Amy Luo
#' @references Jacquez, G.M., Maruca,I S. & Fortin M.-J. (2000) From fields to objects: A review of geographic boundary analysis. Journal of Geographical Systems, 3, 221, 241.
#' @export
n_subgraph <- function(x, null_distrib) {
count <- terra::patches(x, directions = 8, zeroAsNA = TRUE) %>%
terra::values(.) %>%
max(., na.rm = TRUE)
p <- null_distrib$n_subgraph(count) %>%
ifelse(. > 0.5, 1 - ., .) %>%
as.numeric(.)
names(count) <- 'n subgraphs'
names(p) <-'p-value'
return(c(count, p))
}
#length of the longest subgraph ----
#' @name max_subgraph
#' @title Length of the longest subgraph
#' @description Statistical test for the length of the longest subgraph, or set of contiguous boundary elements.
#'
#' @param x A SpatRaster object with boundary elements.
#' @param null_distrib A list of probability functions output from boundary_null_distrib().
#'
#' @return The length of the longest subgraph and a p-value.
#' @examples \donttest{
#' data(T.cristatus)
#' T.cristatus <- terra::rast(T.cristatus_matrix, crs = T.cristatus_crs)
#' terra::ext(T.cristatus) <- T.cristatus_ext
#'
#' Tcrist_boundaries <- categorical_boundary(T.cristatus)
#' T.crist_bound_null <- boundary_null_distrib(T.cristatus, cat = TRUE, n_iterations = 100,
#' model = 'random_cluster')
#'
#' max_subgraph(Tcrist_boundaries, T.crist_bound_null)
#' }
#'
#' @author Amy Luo
#' @references Jacquez, G.M., Maruca,I S. & Fortin M.-J. (2000) From fields to objects: A review of geographic boundary analysis. Journal of Geographical Systems, 3, 221, 241.
#' @export
max_subgraph <- function(x, null_distrib) {
xpolygon <- terra::subst(x, 0, NA) %>%
terra::as.polygons(., na.rm = TRUE) %>%
terra::buffer(., 0.001) %>%
terra::disagg(.) %>%
sf::st_as_sf(.)
lengths <- c()
for (i in 1:nrow(xpolygon)) {
lengths <- sf::st_geometry(xpolygon[i,]) %>%
sf::st_cast(., "POINT") %>%
sf::st_distance(.) %>%
max(.) %>%
append(lengths, .) %>%
as.numeric(.)
}
max_length <- max(lengths)
# statistical test
p <- null_distrib$longest_subgraph(max_length) %>%
ifelse(. > 0.5, 1 - ., .) %>%
as.numeric(.)
names(p) <-'p-value'
names(max_length) <- 'length of longest boundary'
return(c(max_length, p))
}
|
/scratch/gouwar.j/cran-all/cranData/BoundaryStats/R/boundary_statistics.R
|
#' @name categorical_boundary
#' @title Define the boundary elements of a SpatRaster with categorical data
#' @description Creates boundary element cells where patches of two categories meet.
#'
#' @param x A SpatRaster object.
#' @return A SpatRaster object with cell values 1 for boundary elements and 0 for other cells
#'
#' @examples \donttest{
#' data(grassland)
#' grassland <- terra::rast(grassland_matrix, crs = grassland_crs)
#' terra::ext(grassland) <- grassland_ext
#'
#' grassland_boundaries <- categorical_boundary(grassland)
#' }
#'
#' @author Amy Luo
#' @export
categorical_boundary <- function(x) {
x_poly <- terra::as.polygons(x)
mask <- terra::aggregate(x_poly) %>%
terra::as.lines(.) %>%
terra::rasterize(., terra::rast(x))
fill <- terra::aggregate(x_poly) %>%
terra::rasterize(., terra::rast(x), field = 0)
x_boundary <- terra::as.lines(x_poly) %>%
terra::rasterize(., terra::rast(x)) %>%
terra::merge(., fill) %>%
terra::mask(., mask, maskvalues = 1, updatevalue = 0)
terra::crs(x_boundary) <- terra::crs(x)
return(x_boundary)
}
|
/scratch/gouwar.j/cran-all/cranData/BoundaryStats/R/categorical_boundary.R
|
#' @title Afrixalus delicatus genetic groups
#' @description Raster data representing interpolated genetic group assignments for Afrixalus delicatus
#' based on analyses in Barratt et al. 2018.
#' @docType data
#' @usage data(A.delicatus)
#' @references Barratt et al. (2013) Molecular Ecology 27:4289–4308
#' @format A matrix to be converted into a SpatRaster object with a EPSG:4210 projection.
#' @keywords datasets
#' @source \doi{10.5061/dryad.315km76}
'A.delicatus_matrix'
#' @title Afrixalus delicatus genetic groups extent
#' @description Extent for A.delicatus_matrix
#' @docType data
#' @usage data(A.delicatus)
#' @references Barratt et al. (2013) Molecular Ecology 27:4289–4308
#' @format Numeric vector of length length 4
#' @keywords datasets
#' @source \doi{10.5061/dryad.315km76}
'A.delicatus_ext'
#' @title Afrixalus delicatus genetic groups projection
#' @description Projection for A.delicatus_matrix
#' @docType data
#' @usage data(A.delicatus)
#' @references Barratt et al. (2013) Molecular Ecology 27:4289–4308
#' @format Projection crs object
#' @keywords datasets
#' @source \doi{10.5061/dryad.315km76}
'A.delicatus_crs'
#' @title Afrixalus sylvaticus genetic groups
#' @description Raster data representing interpolated genetic group assignments for Afrixalus sylvaticus
#' based on analyses in Barratt et al. 2018.
#' @docType data
#' @usage data(A.sylvaticus)
#' @references Barratt et al. (2013) Molecular Ecology 27:4289–4308
#' @format A matrix to be converted into a SpatRaster object with a EPSG:4210 projection.
#' @keywords datasets
#' @source \doi{10.5061/dryad.315km76}
'A.sylvaticus_matrix'
#' @title Afrixalus sylvaticus genetic groups extent
#' @description Extent for A.sylvaticus_matrix
#' @docType data
#' @usage data(A.sylvaticus)
#' @references Barratt et al. (2013) Molecular Ecology 27:4289–4308
#' @format Numeric vector of length length 4
#' @keywords datasets
#' @source \doi{10.5061/dryad.315km76}
'A.sylvaticus_ext'
#' @title Afrixalus sylvaticus genetic groups projection
#' @description Projection for A.sylvaticus_matrix
#' @docType data
#' @usage data(A.sylvaticus)
#' @references Barratt et al. (2013) Molecular Ecology 27:4289–4308
#' @format Projection crs object
#' @keywords datasets
#' @source \doi{10.5061/dryad.315km76}
'A.sylvaticus_crs'
#' @title Leptopelis concolor genetic groups
#' @description Raster data representing interpolated genetic group assignments for Leptopelis concolor
#' based on analyses in Barratt et al. 2018.
#' @docType data
#' @usage data(L.concolor)
#' @references Barratt et al. (2013) Molecular Ecology 27:4289–4308
#' @format A matrix to be converted into a SpatRaster object with a EPSG:4210 projection.
#' @keywords datasets
#' @source \doi{10.5061/dryad.315km76}
'L.concolor_matrix'
#' @title Leptopelis concolor genetic groups extent
#' @description Extent for L.concolor_matrix
#' @docType data
#' @usage data(L.concolor)
#' @references Barratt et al. (2013) Molecular Ecology 27:4289–4308
#' @format Numeric vector of length length 4
#' @keywords datasets
#' @source \doi{10.5061/dryad.315km76}
'L.concolor_ext'
#' @title Leptopelis concolor genetic groups projection
#' @description Projection
#' @docType data
#' @usage data(L.concolor)
#' @references Barratt et al. (2013) Molecular Ecology 27:4289–4308
#' @format Projection crs object
#' @keywords datasets
#' @source \doi{10.5061/dryad.315km76}
'L.concolor_crs'
#' @title Leptopelis flavomaculatus genetic groups
#' @description Raster data representing interpolated genetic group assignments for Leptopelis flavomaculatus
#' based on analyses in Barratt et al. 2018.
#' @docType data
#' @usage data(L.flavomaculatus)
#' @references Barratt et al. (2013) Molecular Ecology 27:4289–4308
#' @format A matrix to be converted into a SpatRaster object with a EPSG:4210 projection.
#' @keywords datasets
#' @source \doi{10.5061/dryad.315km76}
'L.flavomaculatus_matrix'
#' @title Leptopelis flavomaculatus genetic groups extent
#' @description Extent for L.flavomaculatus_ext
#' @docType data
#' @usage data(L.flavomaculatus)
#' @references Barratt et al. (2013) Molecular Ecology 27:4289–4308
#' @format Numeric vector of length length 4
#' @keywords datasets
#' @source \doi{10.5061/dryad.315km76}
'L.flavomaculatus_ext'
#' @title Leptopelis flavomaculatus genetic groups projection
#' @description Projection for L.flavomaculatus_matrix
#' @docType data
#' @usage data(L.flavomaculatus)
#' @references Barratt et al. (2013) Molecular Ecology 27:4289–4308
#' @format Projection crs object
#' @keywords datasets
#' @source \doi{10.5061/dryad.315km76}
'L.flavomaculatus_crs'
#' @title Ecoregion data for East Africa
#' @description Raster data of ecoregions in East Africa
#' @docType data
#' @usage data(ecoregions)
#' @references Barratt et al. (2013) Molecular Ecology 27:4289–4308
#' @format A matrix to be converted into a SpatRaster object with a EPSG:4210 projection.
#' @keywords datasets
#' @source \doi{10.5061/dryad.315km76}
'ecoregions_matrix'
#' @title Ecoregion data for East Africa extent
#' @description Extent for ecoregions_matrix
#' @docType data
#' @usage data(ecoregions)
#' @references Barratt et al. (2013) Molecular Ecology 27:4289–4308
#' @format Numeric vector of length length 4
#' @keywords datasets
#' @source \doi{10.5061/dryad.315km76}
'ecoregions_ext'
#' @title Ecoregion data for East Africa projection
#' @description Projection for ecoregions_matrix
#' @docType data
#' @usage data(ecoregions)
#' @references Barratt et al. (2013) Molecular Ecology 27:4289–4308
#' @format Projection crs object
#' @keywords datasets
#' @source \doi{10.5061/dryad.315km76}
'ecoregions_crs'
#' @title Grassland land cover
#' @description Raster land cover data from the LifeWatch Wallonia-Brussels ecotope database and used in Cox et al. 2023. Downsampled to match T. cristatus raster
#' @docType data
#' @usage data(grassland)
#' @references
#' Cox et al. (2023) Conservation Genetics
#' Radoux et al. (2019) Remote Sens 11:354.
#' @format A matrix to be converted into a SpatRaster object with a EPSG:4326 projection.
#' @keywords datasets
#' @source \doi{10.5061/dryad.bk3j9kdhz}
'grassland_matrix'
#' @title Grassland land cover extent
#' @description Extent for grassland_matrix
#' @docType data
#' @usage data(grassland)
#' @references
#' Cox et al. (2023) Conservation Genetics
#' Radoux et al. (2019) Remote Sens 11:354.
#' @format Numeric vector of length length 4
#' @keywords datasets
#' @source \doi{10.5061/dryad.bk3j9kdhz}
'grassland_ext'
#' @title Grassland land cover projection
#' @description Projection for grassland_matrix
#' @docType data
#' @usage data(grassland)
#' @references
#' Cox et al. (2023) Conservation Genetics
#' Radoux et al. (2019) Remote Sens 11:354.
#' @format Projection crs object
#' @keywords datasets
#' @source \doi{10.5061/dryad.bk3j9kdhz}
'grassland_crs'
#' @title Triturus cristatus genetic groups
#' @description Raster data representing interpolated genetic group assignments for Triturus cristatus
#' based on analyses in Cox et al. 2023
#' @docType data
#' @usage data(T.cristatus)
#' @references Cox et al. (2023) Conservation Genetics
#' @format A matrix to be converted into a SpatRaster object with a EPSG:4326 projection.
#' @keywords datasets
#' @source \doi{10.5061/dryad.bk3j9kdhz}
'T.cristatus_matrix'
#' @title Triturus cristatus genetic groups extent
#' @description Extent for T.cristatus_matrix
#' @docType data
#' @usage data(T.cristatus)
#' @references Cox et al. (2023) Conservation Genetics
#' @format Numeric vector of length length 4
#' @keywords datasets
#' @source \doi{10.5061/dryad.bk3j9kdhz}
'T.cristatus_ext'
#' @title Triturus cristatus genetic groups projection
#' @description Projection for T.cristatus_matrix
#' @docType data
#' @usage data(T.cristatus)
#' @references Cox et al. (2023) Conservation Genetics
#' @format ces Barratt et al. (2013) Molecular Ecology 27:4289–4308
#' @format Projection crs object
#' @keywords datasets
#' @source \doi{10.5061/dryad.bk3j9kdhz}
'T.cristatus_crs'
|
/scratch/gouwar.j/cran-all/cranData/BoundaryStats/R/data.R
|
#' @name define_boundary
#' @title Define the boundary elements of a SpatRaster with numeric data or boundary intensities
#' @description
#'
#' Defines boundaries in a SpatRaster object by keeping a proportion of the cells with the highest
#' boundary intensity values. If the SpatRaster contains trait values, the values can be converted
#' to boundary/edge values (convert = T) using a Sobel-Feldman operator.
#'
#' @param x A SpatRaster object.
#' @param threshold A value between 0 and 1. The proportion of cells to keep as boundary elements. default = 0.2.
#' @param convert logical. If TRUE, convert values of each cell from trait values to boundary intensities. default = FALSE.
#'
#' @return A SpatRaster object with cell values 1 for boundary elements and 0 for other cells
#'
#' @examples \donttest{
#' data(grassland)
#' grassland <- terra::rast(grassland_matrix, crs = grassland_crs)
#' terra::ext(grassland) <- grassland_ext
#'
#' grassland_boundaries <- define_boundary(grassland, 0.1)
#' }
#'
#' @author Amy Luo
#' @references
#' Fortin, M.J. et al. (2000) Issues related to the detection of boundaries. Landscape Ecology, 15, 453-466.
#' Jacquez, G.M., Maruca,I S. & Fortin M.-J. (2000) From fields to objects: A review of geographic boundary analysis. Journal of Geographical Systems, 3, 221, 241.
#' @export
define_boundary <- function (x, threshold = 0.2, convert = FALSE) {
# if the raster contains trait values, estimate first partial derivatives of the cells in lon and lat directions
if (convert == TRUE) {x <- sobel_operator(x)}
# sort the cell values from highest to lowest, then find the value above which only the threshold
# proportion of cells would be kept
threshold_value <- terra::values(x) %>%
na.omit(.) %>%
sort(., decreasing = TRUE) %>%
head(., round(length(.) * threshold)) %>%
min(.)
# Check proportion of cells above threshold value. Sometimes there are a lot of redundant cell values, so if there
# are redundancies at the threshold value, then the proportion of cells kept will be higher than the threshold.
prop <- terra::values(x, dataframe = TRUE) %>%
na.omit(.) %>%
.[. >= threshold_value] %>%
length(.)/length(na.omit(terra::values(x)))
# so we'll keep reducing the threshold value until the proportion of cells kept is below the threshold
if (threshold_value %% 1 == 0) { # sometimes the boundary values are integers
while (prop > threshold) {
threshold_value = threshold_value + 1 # so increase the threshold value by 1
prop <- terra::values(x) %>%
na.omit(.) %>%
.[. >= threshold_value] %>%
length(.)/length(na.omit(terra::values(x)))
}
} else { # sometimes the boundary values are float
rep = 0
while (prop > threshold) {
threshold_value = threshold_value * 1.1 # so increase the threshold value by 10%
prop <- terra::values(x, dataframe = TRUE) %>% # until the proportion of cells kept < threshold
na.omit(.) %>%
.[. >= threshold_value] %>%
length(.)/length(na.omit(terra::values(x)))
rep = rep + 1
if (rep >= 10) {break} # break after 10 reps if it gets that far
}
}
# make raster with boundary elements (filter out cells with values below threshold)
boundaries <- terra::as.matrix(x, wide = T)
for (row in 1:nrow(boundaries)) {
for (col in 1:ncol(boundaries))
if(!is.na(boundaries[row, col])) {
if (boundaries[row, col] < threshold_value) {boundaries[row, col] = 0} else {boundaries[row, col] = 1}
}
}
# remove singleton boundary elements
for (row in 1:nrow(boundaries)) {
for (col in 1:ncol(boundaries)) {
if (!is.na(boundaries[row, col])) {
if(boundaries[row, col] == 1) {
# name all neighboring cells
if (row > 1) {up = boundaries[row - 1, col]} else {up = NA}
if (row < nrow(boundaries)) {down = boundaries[row + 1, col]} else {down = NA}
if (col > 1) {left = boundaries[row, col - 1]} else {left = NA}
if (col < ncol(boundaries)) {right = boundaries[row, col + 1]} else {right = NA}
if (row > 1 & col > 1) {upleft = boundaries[row - 1, col - 1]} else {upleft = NA}
if (row > 1 & col < ncol(boundaries)) {upright = boundaries[row - 1, col + 1]} else {upright = NA}
if (row < nrow(boundaries) & col > 1) {downleft = boundaries[row + 1, col - 1]} else {downleft = NA}
if (row < nrow(boundaries) & col < ncol(boundaries)) {downright = boundaries[row + 1, col + 1]} else {downright = NA}
# test whether any neighbors are boundary elements
neighbors <- c(up, down, left, right, upleft, upright, downleft, downright)
# if not, then set the focal cell to 0 (change focal cell to not boundary element)
if(1 %in% neighbors == F) {boundaries[row, col] = 0}
}
}
}
}
boundaries <- terra::rast(boundaries)
terra::ext(boundaries) <- terra::ext(x)
return(boundaries)
}
|
/scratch/gouwar.j/cran-all/cranData/BoundaryStats/R/define_boundary.R
|
#' @name gauss_random_field_sim
#' @title Gaussian random field neutral model
#' @description Simulates a gaussian random field as a neutral landscape of the same extent and resolution as the
#' input raster, using the same spatial autocorrelation range as the input
#'
#' @param x A SpatRaster object.
#' @return A SpatRaster object with boundary elements.
#'
#' @examples \donttest{
#' #' data(grassland)
#' grassland <- terra::rast(grassland_matrix, crs = grassland_crs)
#' terra::ext(grassland) <- grassland_ext
#'
#' simulation <- gauss_random_field_sim(grassland)
#' terra::plot(simulation)
#' }
#'
#' @author Amy Luo
#' @references
#' James, P. M. A., Fleming, R.A., & Fortin, M.-J. (2010) Identifying significant scale-specific spatial boundaries using wavelets and null models: Spruce budworm defoliation in Ontario, Canada as a case study. Landscape Ecology, 6, 873-887.
#' @export
gauss_random_field_sim <- function (x) {
# estimate autocorrelation range using local Moran's I + LISA clustering
cell_vals <- terra::cells(x) %>%
terra::values(x)[.] %>%
as.data.frame(.)
lisa_clusters <- terra::as.polygons(x, dissolve = F) %>%
sf::st_as_sf(.) %>%
rgeoda::queen_weights(.) %>%
rgeoda::local_moran(., cell_vals) %>%
rgeoda::lisa_clusters(.) %>%
data.frame(cellID = terra::cells(x), group = .)
cells_to_fill <- terra::rowColFromCell(x, terra::cells(x))
x_cluster <- terra::rast(nrow = terra::nrow(x), ncol = terra::ncol(x), crs = terra::crs(x), extent = terra::ext(x))
index = 1
for (i in sequence(nrow(lisa_clusters))) {
x_cluster[cells_to_fill[i,1], cells_to_fill[i,2]] <- lisa_clusters[index, 2]
index = index + 1
}
x_cluster <- terra::as.polygons(x_cluster, na.rm = TRUE) %>%
terra::buffer(., 0.01) %>%
terra::disagg(.) %>%
sf::st_as_sf(.) %>%
sf::st_area(.)
cell_size <- terra::cellSize(x, transform = T) %>%
terra::values(.) %>%
mean(.)
corr_range <- sqrt(as.numeric(median(x_cluster)))/sqrt(cell_size)
# simulate raster
repeat {
invisible(capture.output(
x_sim <- try(list(1:terra::nrow(x), 1:terra::ncol(x)) %>%
fields::circulantEmbeddingSetup(., cov.args = list(p = 2, aRange = corr_range)) %>%
fields::circulantEmbedding(.) %>%
terra::rast(.),
silent = TRUE)
))
if(is(x_sim) == 'try-error') {corr_range = corr_range * 0.9} else {break}
}
# make extent and projection match input data
terra::crs(x_sim) <- terra::crs(x)
terra::ext(x_sim) <- terra::ext(x)
x_sim <- terra::mask(x_sim, x)
# transform value range of simulated raster
x_sim <- terra::values(x) %>%
na.omit(.) %>%
range(.) %>%
scales::rescale(terra::as.matrix(x_sim, wide = TRUE), to = .) %>%
matrix(., nrow = nrow(x_sim), ncol = ncol(x_sim)) %>%
terra::rast(.)
terra::ext(x_sim) <- terra::ext(x)
terra::crs(x_sim) <- terra::crs(x)
# if input values are all integers, make all simulated values integers
if (all(na.omit(terra::values(x)) %% 1 == 0)) {terra::values(x_sim) <- round(terra::values(x_sim))}
# output
return(x_sim)
}
|
/scratch/gouwar.j/cran-all/cranData/BoundaryStats/R/gauss_random_field_sim.R
|
#' @importFrom stats na.omit rnorm median
#' @importFrom utils setTxtProgressBar txtProgressBar head capture.output
#' @importFrom methods is
#' @importFrom magrittr %>%
#' @import igraph
NULL
#' @importFrom utils globalVariables
utils::globalVariables(c('.', 'long', 'lat', 'region', 'patches'))
|
/scratch/gouwar.j/cran-all/cranData/BoundaryStats/R/globals.R
|
#' @name mod_random_clust_sim
#' @title Modified random cluster neutral landscape model
#' @description Simulates a neutral landscape of the same extent and resolution as the input raster, with the same
#' distribution of values.
#'
#' @param x A SpatRaster object.
#' @param p The proportion of cells to be marked in percolated raster. Higher values of p produce larger clusters.
#' @return A SpatRaster object with boundary elements.
#'
#' @examples
#' data(grassland)
#' grassland <- terra::rast(grassland_matrix, crs = grassland_crs)
#' terra::ext(grassland) <- grassland_ext
#'
#' simulation <- mod_random_clust_sim(grassland, p = 0.6)
#' terra::plot(simulation)
#'
#' @author Amy Luo
#' @references
#' Saura, S. & Martínez-Millán, J. (2000) Landscape patterns simulation with a modified random clusters method. Landscape Ecology, 15, 661 – 678.
#' @export
mod_random_clust_sim <- function (x, p) {
# A: make percolated raster, where proportion of filled cells = p_cluster
x_sim <- matrix(nrow = terra::nrow(x), ncol = terra::ncol(x))
for (i in 1:length(x_sim)) {
if (stats::runif(1) <= p) {x_sim[i] = 1} else {x_sim[i] = 0}
}
# B: find clusters in raster
x_sim <- terra::rast(x_sim, crs = terra::crs(x), ext = terra::ext(x)) %>%
terra::patches(., zeroAsNA = TRUE)
x_sim[is.na(x_sim)] <- 0
x_sim[x_sim != 0] <- x_sim[x_sim != 0] + nrow(terra::unique(x))
# C: assign clusters to categories
prop <- terra::freq(x, digits = 2) %>% # proportions of cells in category
as.data.frame(.) %>%
tibble::add_column(., p = .$count/sum(.$count)) %>%
.[order(.$p),c(2, 4)]
clump_selection_order <- sample(terra::unique(x_sim)[-1,])
areas <- terra::cellSize(x_sim)
total_area <- terra::expanse(x_sim)
row = 1
for (i in clump_selection_order) {
assignment = prop[row, 1]; max_prop = prop[row, 2]
terra::values(x_sim)[terra::values(x_sim) == i] <- assignment
current_prop <- which(terra::values(x_sim) == assignment) %>%
areas[.] %>%
sum(.)/total_area %>%
.[,2]
if (current_prop >= max_prop) {row = row + 1}
if (row > nrow(prop)) {break}
}
# D: fill in the rest of the cells
cells_to_fill <- terra::cells(x_sim, 0)[[1]]
for (i in cells_to_fill) {
choices <- terra::adjacent(x_sim, i)[1,] %>%
x_sim[.] %>%
subset(., patches != 0) %>%
table(.) %>%
as.data.frame(.)
if (length(choices != 0)) {
choices <- as.vector(choices[choices$Freq == max(choices$Freq), 1])
if (length(choices > 1)) {x_sim[i] = as.numeric(sample(choices, 1))} else {x_sim[1] = as.numeric(choices)}
} else {
x_sim[i] <- sample(prop[,1], 1, prob = prop[,2])
}
}
# crop extent of filled values to input data range
x_sim <- terra::mask(x_sim, x)
return(x_sim)
}
|
/scratch/gouwar.j/cran-all/cranData/BoundaryStats/R/mod_random_clust_sim.R
|
#' @name overlap_null_distrib
#' @title Null distribution for boundary overlap statistics
#' @description
#' Creates custom probability distributions for three boundary overlap statistics (directly overlapping
#' boundary elements, minimum distance between boundary elements in x to y, and minimum distance
#' between elements in x and y). Given two SpatRaster objects with the same extent, projection, and
#' resolution, simulates n iterations of random raster surfaces from neutral model(s).
#'
#' @param x A SpatRaster object. If rand_both = FALSE, only this raster will be modeled.
#' @param y A SpatRaster object. If rand_both = FALSE, this raster does not change.
#' @param rand_both TRUE if distribution of traits in x and y should be modeled.
#' @param x_convert TRUE if x contains numeric trait data that needs to be converted to boundary intensities. default = FALSE.
#' @param y_convert TRUE if y contains numeric trait data that needs to be converted to boundary intensities. default = FALSE.
#' @param x_cat TRUE if x contains a categorical variable. default = FALSE.
#' @param y_cat TRUE if y contains a categorical variable. default = FALSE.
#' @param threshold A value between 0 and 1. The proportion of cells to keep as
#' boundary elements. Default = 0.2.
#' @param n_iterations An integer indicating the number of iterations for the function. A value of 100 or 1000
#' is recommended to produce sufficient resolution for downstream statistical tests. default = 10.
#' @param x_model Neutral model to use. Options: 'random' (stochastic), 'gaussian' (Gaussian random field),
#' and 'random_cluster' (modified random clusters method)
#' @param y_model Neutral model to use for y.
#' @param px If using modified random clusters for x, proportion of cells to be marked in percolated raster. Higher values of
#' p produce larger clusters. Default = 0.5
#' @param py If using modified random clusters for y, proportion of cells to be marked in percolated raster. Higher values of
#' p produce larger clusters. Default = 0.5
#' @param progress If progress = TRUE (default) a progress bar will be displayed.
#'
#' @return A list of probability distribution functions for boundary overlap statistics.
#'
#' @examples \donttest{
#' data(T.cristatus)
#' T.cristatus <- terra::rast(T.cristatus_matrix, crs = T.cristatus_crs)
#' terra::ext(T.cristatus) <- T.cristatus_ext
#'
#' data(grassland)
#' grassland <- terra::rast(grassland_matrix, crs = grassland_crs)
#' terra::ext(grassland) <- grassland_ext
#'
#' Tcrist_ovlp_null <- overlap_null_distrib(T.cristatus, grassland, rand_both = FALSE,
#' x_cat = TRUE, n_iterations = 100, x_model = 'random_cluster')
#' }
#'
#' @author Amy Luo
#' @references Saura, S. & Martínez-Millán, J. (2000). Landscape patterns simulation with a modified random clusters method. Landscape Ecology, 15:661-678.
#' @export
overlap_null_distrib <- function(x, y, rand_both, x_convert = FALSE, y_convert = FALSE, x_cat = FALSE, y_cat = FALSE,
threshold = 0.2, n_iterations = 10, x_model = 'random', y_model = 'random',
px = 0.5, py = 0.5, progress = TRUE) {
# progress bar
if (progress == TRUE) {progress_bar = txtProgressBar(min = 0, max = n_iterations, initial = 0, char = '+', style = 3)}
# make output vectors for repeat loop
Odirect = c(); Ox = c(); Oxy = c()
# if not randomizing y model, find boundaries in y
if (rand_both == FALSE) {
if (y_cat == FALSE) {
y_boundary <- define_boundary(y, threshold, y_convert)
} else {
y_boundary <- categorical_boundary(y)
}
}
# n iterations of random boundaries + stats
rep = 0
repeat {
# make random rasters with boundary elements (only for x if not randomizing y) ----
repeat {
if (x_model == 'random') {
x_sim <- random_raster_sim(x)
} else if (x_model == 'gaussian') {
x_sim <- gauss_random_field_sim(x)
} else if (x_model == 'random_cluster') {
x_sim <- mod_random_clust_sim(x, px)
}
if (x_cat == FALSE) {
x_boundary <- define_boundary(x_sim, threshold, x_convert)
} else {
x_boundary <- categorical_boundary(x_sim)
}
if (sum(terra::values(x_boundary) == 1, na.rm = TRUE) >= 1) {break}
}
if (rand_both == TRUE) {
repeat {
if (y_model == 'random') {
y_sim <- random_raster_sim(y)
} else if (y_model == 'gaussian') {
y_sim <- gauss_random_field_sim(y)
} else if (y_model == 'random_cluster') {
y_sim <- mod_random_clust_sim(y, py)
}
if (y_cat == FALSE) {
y_boundary <- define_boundary(y_sim, threshold, y_convert)
} else {
y_boundary <- categorical_boundary(y_sim)
}
if (sum(terra::values(y_boundary) == 1, na.rm = TRUE) >= 1) {break}
}
}
# direct overlap statistic ----
xx <- terra::cells(x_boundary, 1)[[1]]
yy <- terra::cells(y_boundary, 1)[[1]]
count <- length(intersect(xx, yy))
Odirect <- append(Odirect, count)
# average minimum distance statistic (Ox; one boundary influences the other) ----
x_min_distances <- c()
x_bound_cells <- terra::xyFromCell(x_boundary, terra::cells(x_boundary, 1)[[1]])
y_bound_cells <- terra::xyFromCell(y_boundary, terra::cells(y_boundary, 1)[[1]])
dists <- terra::distance(x_bound_cells, y_bound_cells, lonlat = T)
for (i in sequence(nrow(dists))) {x_min_distances <- append(x_min_distances, min(dists[i,]))} # for each x boundary cell, the minimum distance to a y boundary cell
x_ave_min_dist <- mean(x_min_distances)
Ox <- append(Ox, x_ave_min_dist)
# average minimum distance statistic (Oxy; both boundaries influence each other) ----
# distance matrix already calculated in last portion, just recalculate the average minimum distance
xy_min_distances <- c()
for (i in sequence(nrow(dists))) {xy_min_distances <- append(xy_min_distances, min(dists[i,]))} # for each x boundary cell, the minimum distance to a y boundary cell
for (i in sequence(ncol(dists))) {xy_min_distances <- append(xy_min_distances, min(dists[,i]))} # for each x boundary cell, the minimum distance to a y boundary cell
ave_min_dist <- mean(xy_min_distances)
Oxy <- mean(xy_min_distances) %>%
append(Oxy, .)
# loop count and break ----
rep = rep + 1
if (progress == TRUE) {setTxtProgressBar(progress_bar, rep)}
if (rep >= n_iterations) {
if (progress == TRUE) {close(progress_bar)}
break
}
}
# output
Odirect <- pdqr::new_p(Odirect, type = 'continuous')
Ox <- pdqr::new_p(Ox, type = 'continuous')
Oxy <- pdqr::new_p(Oxy, type = 'continuous')
distribs <- list(Odirect, Ox, Oxy)
names(distribs) <- c('Odirect', 'Ox', 'Oxy')
message('DONE')
return(distribs)
}
|
/scratch/gouwar.j/cran-all/cranData/BoundaryStats/R/overlap_null_distrib.R
|
# Odirect ----
#' @name Odirect
#' @title Direct overlap between boundary elements.
#' @description Statistical test for the number of directly overlapping boundary elements of two traits.
#'
#' @param x A SpatRaster object with boundary elements.
#' @param y A SpatRaster object with boundary elements.
#' @param null_distrib A list of probability functions output from overlap_null_distrib().
#'
#' @return The number of directly overlapping boundary elements and a p-value.
#' @examples \donttest{
#' data(T.cristatus)
#' T.cristatus <- terra::rast(T.cristatus_matrix, crs = T.cristatus_crs)
#' terra::ext(T.cristatus) <- T.cristatus_ext
#'
#' data(grassland)
#' grassland <- terra::rast(grassland_matrix, crs = grassland_crs)
#' terra::ext(grassland) <- grassland_ext
#'
#' Tcrist_ovlp_null <- overlap_null_distrib(T.cristatus, grassland, rand_both = FALSE,
#' x_cat = TRUE, n_iterations = 100, x_model = 'random_cluster')
#' Tcrist_boundaries <- categorical_boundary(T.cristatus)
#' grassland_boundaries <- define_boundary(grassland, 0.1)
#'
#' Odirect(Tcrist_boundaries, grassland_boundaries, Tcrist_ovlp_null)
#' }
#'
#' @author Amy Luo
#' @references
#' Jacquez, G.M., Maruca,I S. & Fortin, M.-J. (2000) From fields to objects: A review of geographic boundary analysis. Journal of Geographical Systems, 3, 221, 241.
#' Fortin, M.-J., Drapeau, P. & Jacquez, G.M. (1996) Quantification of the Spatial Co-Occurrences of Ecological Boundaries. Oikos, 77, 51-60.
#' @export
Odirect <- function(x, y, null_distrib) {
xx <- terra::cells(x, 1)[[1]]
yy <- terra::cells(y, 1)[[1]]
count <- length(intersect(xx, yy))
p <- null_distrib$Odirect(count) %>%
ifelse(. > 0.5, 1 - ., .) %>%
as.numeric(.)
names(p) <-'p-value'
names(count) <- 'n overlapping boundary elements'
return(c(count, p))
}
# Ox ----
#' @name Ox
#' @title Average minimum distance from x boundary elements to nearest y boundary element.
#' @description
#' Statistical test for the average minimum distance between each boundary element in raster x
#' and the nearest boundary element in raster y. Uses Euclidean distance. The boundaries of
#' trait x depend on the boundaries of trait y.
#'
#' @param x A SpatRaster object with boundary elements.
#' @param y A SpatRaster object with boundary elements.
#' @param null_distrib A list of probability functions output from overlap_null_distrib().
#'
#' @return The average minimum distance and a p-value.
#'
#' @examples \donttest{
#' data(T.cristatus)
#' T.cristatus <- terra::rast(T.cristatus_matrix, crs = T.cristatus_crs)
#' terra::ext(T.cristatus) <- T.cristatus_ext
#'
#' data(grassland)
#' grassland <- terra::rast(grassland_matrix, crs = grassland_crs)
#' terra::ext(grassland) <- grassland_ext
#'
#' Tcrist_ovlp_null <- overlap_null_distrib(T.cristatus, grassland, rand_both = FALSE,
#' x_cat = TRUE, n_iterations = 100, x_model = 'random_cluster')
#' Tcrist_boundaries <- categorical_boundary(T.cristatus)
#' grassland_boundaries <- define_boundary(grassland, 0.1)
#'
#' Ox(Tcrist_boundaries, grassland_boundaries, Tcrist_ovlp_null)
#' }
#'
#' @author Amy Luo
#' @references
#' Jacquez, G.M., Maruca,I S. & Fortin,M.-J. (2000) From fields to objects: A review of geographic boundary analysis. Journal of Geographical Systems, 3, 221, 241.
#' Fortin, M.-J., Drapeau, P. & Jacquez, G.M. (1996) Quantification of the Spatial Co-Occurrences of Ecological Boundaries. Oikos, 77, 51-60.
#' @export
Ox <- function(x, y, null_distrib) {
x_min_distances <- c()
x_bound_cells <- terra::xyFromCell(x, terra::cells(x, 1)[[1]])
y_bound_cells <- terra::xyFromCell(y, terra::cells(y, 1)[[1]])
dists <- terra::distance(x_bound_cells, y_bound_cells, lonlat = T)
for (i in sequence(nrow(dists))) {x_min_distances <- append(x_min_distances, min(dists[i,]))} # for each x boundary cell, the minimum distance to a y boundary cell
ave_min_dist <- mean(x_min_distances)
names(ave_min_dist) <- 'average minimum distance (x depends on y)'
p <- null_distrib$Ox(ave_min_dist) %>%
ifelse(. > 0.5, 1 - ., .) %>%
as.numeric(.)
names(p) <- 'p-value'
return(c(ave_min_dist, p))
}
# Oxy ----
#' @name Oxy
#' @title Average minimum distance between boundary elements of two variables
#' @description
#' Statistical test for the average minimum distance between boundary elements in two raster layers.
#' Uses Euclidean distance. Boundaries for each trait affect one another reciprocally (x affects y
#' and y affects x).
#'
#' @param x A SpatRaster object with boundary elements.
#' @param y A SpatRaster object with boundary elements.
#' @param null_distrib A list of probability functions output from overlap_null_distrib().
#'
#' @return p-value
#' @examples \donttest{
#' data(T.cristatus)
#' T.cristatus <- terra::rast(T.cristatus_matrix, crs = T.cristatus_crs)
#' terra::ext(T.cristatus) <- T.cristatus_ext
#'
#' data(grassland)
#' grassland <- terra::rast(grassland_matrix, crs = grassland_crs)
#' terra::ext(grassland) <- grassland_ext
#'
#' Tcrist_ovlp_null <- overlap_null_distrib(T.cristatus, grassland, rand_both = FALSE,
#' x_cat = TRUE, n_iterations = 100, x_model = 'random_cluster')
#' Tcrist_boundaries <- categorical_boundary(T.cristatus)
#' grassland_boundaries <- define_boundary(grassland, 0.1)
#'
#' Oxy(Tcrist_boundaries, grassland_boundaries, Tcrist_ovlp_null)
#' }
#'
#' @author Amy Luo
#' @references
#' Jacquez, G.M., Maruca,I S. & Fortin, M.-J. (2000) From fields to objects: A review of geographic boundary analysis. Journal of Geographical Systems, 3, 221, 241.
#' Fortin, M.-J., Drapeau, P. & Jacquez, G.M. (1996) Quantification of the Spatial Co-Occurrences of Ecological Boundaries. Oikos, 77, 51-60.
#' @export
Oxy <- function(x, y, null_distrib) {
min_distances <- c()
x_bound_cells <- terra::xyFromCell(x, terra::cells(x, 1)[[1]])
y_bound_cells <- terra::xyFromCell(y, terra::cells(y, 1)[[1]])
dists <- terra::distance(x_bound_cells, y_bound_cells, lonlat = T)
for (i in sequence(nrow(dists))) {min_distances <- append(min_distances, min(dists[i,]))} # for each x boundary cell, the minimum distance to a y boundary cell
for (i in sequence(ncol(dists))) {min_distances <- append(min_distances, min(dists[,i]))} # for each x boundary cell, the minimum distance to a y boundary cell
ave_min_dist <- mean(min_distances)
names(ave_min_dist) <- 'average minimum distance'
p <- null_distrib$Oxy(ave_min_dist) %>%
ifelse(. > 0.5, 1 - ., .) %>%
as.numeric(.)
names(p) <- 'p-value'
return(c(ave_min_dist, p))
}
|
/scratch/gouwar.j/cran-all/cranData/BoundaryStats/R/overlap_statistics.R
|
#' @name plot_boundary
#' @title Map the boundary elements of two raster layers
#' @description
#' This is a wrapper function for ggplot2 that will produce a map of boundary
#' elements for two traits and show where boundary elements intersect.
#'
#' @param x A SpatRaster object with boundary elements.
#' @param y A SpatRaster object with boundary elements.
#' @param color Optional. A character vector of up to three colors (x boundary, y boundary, and overlapping elements).
#' @param trait_names Optional. A character vector with up to two elements (legend name for x and legend name for y).
#'
#' @return A ggplot2 object.
#'
#' @examples
#' data(T.cristatus)
#' T.cristatus <- terra::rast(T.cristatus_matrix, crs = T.cristatus_crs)
#' terra::ext(T.cristatus) <- T.cristatus_ext
#'
#' data(grassland)
#' grassland <- terra::rast(grassland_matrix, crs = grassland_crs)
#' terra::ext(grassland) <- grassland_ext
#'
#' Tcrist_boundaries <- categorical_boundary(T.cristatus)
#' grassland_boundaries <- define_boundary(grassland, 0.1)
#'
#' plot_boundary(Tcrist_boundaries, grassland_boundaries)
#'
#' @author Amy Luo
#' @export
plot_boundary <- function(x, y, color = NA, trait_names = NA) {
# prep boundary layers to plot
x_layer <- terra::as.data.frame(x, xy = TRUE, na.rm = TRUE) %>%
.[.[,3] != 0,]
colnames(x_layer) <- c('long', 'lat', 'values')
y_layer <- terra::as.data.frame(y, xy = TRUE, na.rm = TRUE) %>%
.[.[,3] != 0,]
colnames(y_layer) <- c('long', 'lat', 'values')
# make overlap layer
xx <- terra::cells(x, 1)[[1]]
yy <- terra::cells(y, 1)[[1]]
cells_to_fill <- intersect(xx, yy) %>%
terra::rowColFromCell(x, .) %>%
t(.) %>%
as.data.frame(.)
overlap <- terra::rast(nrow = terra::nrow(x), ncol = terra::ncol(x), crs = terra::crs(x), extent = terra::ext(x))
index = 1
for (i in cells_to_fill) {
overlap[i[1], i[2]] <- 1
index = index + 1
}
overlap <- terra::as.data.frame(overlap, xy = TRUE, na.rm = TRUE)
colnames(overlap) <- c('long', 'lat', 'values')
# if there are inputs for colors and layer names, change the colors from default
fill_col <- c('Trait 1' = '#6EC6CA', 'Trait 2' = '#CCABD8', 'Overlap' = '#055B5C')
if (all(is.na(color))) {
fill_col <- fill_col
} else if (length(color) > 1) {
if(!is.na(color[1])) {fill_col[1] = color[1]}
if(!is.na(color[2])) {fill_col[2] = color[2]}
if(!is.na(color[3])) {fill_col[3] = color[3]}
}
if(!is.na(trait_names[1])) {names(fill_col)[1] <- trait_names[1]}
if(!is.na(trait_names[2])) {names(fill_col)[2] <- trait_names[2]}
# make plot
world_map <- ggplot2::map_data('world')
p <- ggplot2::ggplot(mapping = ggplot2::aes(long, lat)) +
ggplot2::geom_map(data = world_map, map = world_map, ggplot2::aes(map_id = region), fill = '#e8e8e8') +
ggplot2::geom_tile(data = x_layer, ggplot2::aes(fill = names(fill_col)[1])) + # first boundary layer
ggplot2::geom_tile(data = y_layer, ggplot2::aes(fill = names(fill_col)[2])) + # second boundary layer
ggplot2::geom_tile(data = overlap, ggplot2::aes(fill = names(fill_col)[3])) + # overlapping boundary elements
ggplot2::scale_fill_manual(values = fill_col) +
ggplot2::coord_sf(xlim = terra::ext(x)[1:2], ylim = terra::ext(x)[3:4]) +
ggplot2::theme_minimal() +
ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 90, vjust = 0.5, hjust=1)) +
ggplot2::labs(x = 'Longitude', y = 'Latitude', fill = 'Boundary Type')
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/BoundaryStats/R/plot_boundary.R
|
#' @name random_raster_sim
#' @title Stochastic neutral landscape model
#' @description Simulates a spatially stochastic neutral landscape of the same extent and resolution as the input
#' raster, with the same distribution of values.
#'
#' @param x A SpatRaster object.
#' @return A SpatRaster object with boundary elements.
#'
#' @examples
#' data(grassland)
#' grassland <- terra::rast(grassland_matrix, crs = grassland_crs)
#' terra::ext(grassland) <- grassland_ext
#'
#' simulation <- random_raster_sim(grassland)
#' terra::plot(simulation)
#'
#' @author Amy Luo
#' @references
#' James, P. M. A., Fleming, R.A., & Fortin, M.-J. (2010) Identifying significant scale-specific spatial boundaries using wavelets and null models: Spruce budworm defoliation in Ontario, Canada as a case study. Landscape Ecology, 6, 873-887.
#' @export
random_raster_sim <- function (x) {
values <- terra::values(x) %>%
na.omit(.) %>%
sample(.)
cells_to_fill <- terra::cells(x) %>%
terra::rowColFromCell(x, .) %>%
t(.) %>%
as.data.frame(.)
x_sim <- terra::rast(nrow = terra::nrow(x), ncol = terra::ncol(x), crs = terra::crs(x), extent = terra::ext(x))
index = 1
for (i in cells_to_fill) {
x_sim[i[1], i[2]] <- values[index]
index = index + 1
}
return(x_sim)
}
|
/scratch/gouwar.j/cran-all/cranData/BoundaryStats/R/random_raster_sim.R
|
#' @name sobel_operator
#' @title Sobel-Feldman operator for edge detection
#' @description Uses a Sobel-Feldman operator (3x3 kernel) to detect internal edges in a SpatRaster object.
#'
#' @param x A SpatRaster object.
#' @return A SpatRaster object with boundary values.
#'
#' @examples
#' data(T.cristatus)
#' T.cristatus <- terra::rast(T.cristatus_matrix, crs = T.cristatus_crs)
#' terra::ext(T.cristatus) <- T.cristatus_ext
#'
#' edges <- sobel_operator(T.cristatus)
#' terra::plot(edges)
#'
#' @author Amy Luo
#' @export
sobel_operator <- function(x) {
x_mat <- terra::as.matrix(x, wide = TRUE)
gx <- matrix(c(1, 2, 1, 0, 0, 0, -1, -2, -1), nrow = 3)
gy <- matrix(c(1, 0, -1, 2, 0, -2, 1, 0, -1), nrow = 3)
d <- matrix(nrow = nrow(x_mat), ncol = ncol(x_mat))
a <- matrix(nrow = 3, ncol = 3)
for (row in 1:nrow(x_mat)) {
for (col in 1:ncol(x_mat)) {
# values in raster to multiply by mask
if(row - 1 > 0 & col - 1 > 0) {a[1,1] = x_mat[row - 1, col - 1]} else {a[1,1] = 0}
if (row - 1 > 0) {a[1,2] = x_mat[row - 1, col]} else {a[1,2] = 0}
if(row - 1 > 0 & col < ncol(x_mat)) {a[1,3] = x_mat[row - 1, col + 1]} else {a[1,3] = 0}
if (col - 1 > 0) {a[2,1] = x_mat[row, col - 1]} else {a[2,1] = 0}
a[2,2] = x_mat[row, col]
if (col < ncol(x_mat)) {a[2,3] = x_mat[row, col + 1]} else {a[2,3] = 0}
if (row < nrow(x_mat) & col - 1 > 0) {a[3,1] = x_mat[row + 1, col - 1]} else {a[3,1] = 0}
if (row < nrow(x_mat)) {a[3,2] = x_mat[row + 1, col]} else {a[3,2] = 0}
if (row < nrow(x_mat) & col < ncol(x_mat)) {a[3,3] = x_mat[row + 1, col + 1]} else {a[3,3] = 0}
gxa <- sum(gx*a)
gya <- sum(gy*a)
d[row, col] = sqrt(gxa ^ 2 + gya ^ 2)
}
}
out <- terra::rast(d)
for (i in 1:length(out)) {
if (length(terra::adjacent(out, i, 'queen')) < 8) {terra::values(out)[i] = 0}
}
terra::ext(out) <- terra::ext(x)
terra::crs(out) <- terra::crs(x)
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/BoundaryStats/R/sobel_operator.R
|
## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
## ----message = FALSE----------------------------------------------------------
library(BoundaryStats)
library(terra)
library(magrittr)
## ----fig.width = 8, fig.height = 6--------------------------------------------
data(ecoregions)
ecoregions <- rast(ecoregions_matrix, crs = ecoregions_crs)
ext(ecoregions) <- ecoregions_ext
plot(ecoregions)
## ----fig.width = 8, fig.height = 6--------------------------------------------
data(L.flavomaculatus)
L.flavomaculatus <- rast(L.flavomaculatus_matrix, crs = L.flavomaculatus_crs)
ext(L.flavomaculatus) <- L.flavomaculatus_ext
plot(L.flavomaculatus)
## -----------------------------------------------------------------------------
crs(ecoregions) <- crs(L.flavomaculatus)
ecoregions <- resample(ecoregions, L.flavomaculatus) %>%
crop(., L.flavomaculatus) %>%
mask(., L.flavomaculatus)
L.flavomaculatus <- crop(L.flavomaculatus, ecoregions) %>%
mask(., ecoregions)
## ----fig.width = 8, fig.height = 6--------------------------------------------
ecoregions_boundaries <- categorical_boundary(ecoregions)
L.flavomaculatus_boundaries <- categorical_boundary(L.flavomaculatus)
## ----warning = FALSE, fig.width = 8, fig.height = 6---------------------------
plot_boundary(L.flavomaculatus_boundaries, ecoregions_boundaries, trait_names = c('A. delicatus genetic group', 'Ecoregion'))
## -----------------------------------------------------------------------------
L.flav_bound.null <- boundary_null_distrib(L.flavomaculatus, cat = T, n_iterations = 10, model = 'random_cluster', p = 0.5, progress = F)
## -----------------------------------------------------------------------------
n_subgraph(L.flavomaculatus_boundaries, L.flav_bound.null)
max_subgraph(L.flavomaculatus_boundaries, L.flav_bound.null)
## -----------------------------------------------------------------------------
L.flav_overlap.null <- overlap_null_distrib(L.flavomaculatus, ecoregions, rand_both = F, x_cat = T, n_iterations = 10, x_model = 'random_cluster', px = 0.5, progress = F)
## -----------------------------------------------------------------------------
Odirect(L.flavomaculatus_boundaries, ecoregions_boundaries, L.flav_overlap.null)
Ox(L.flavomaculatus_boundaries, ecoregions_boundaries, L.flav_overlap.null)
Oxy(L.flavomaculatus_boundaries, ecoregions_boundaries, L.flav_overlap.null)
|
/scratch/gouwar.j/cran-all/cranData/BoundaryStats/inst/doc/BoundaryStats.R
|
---
title: "BoundaryStats Analysis Workflow"
author: "Amy Luo"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{BoundaryStats Analysis Workflow}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
This vignette is a walkthrough of the workflow for calculating boundary statistics and boundary overlap statistics for two ecological variables. Here, we use East African ecoregion data and genomic analyses from Barratt et al. 2018. The following code tests for (1) whether there are significant geographic boundaries between genetic groups of the frog species *Leptopelis flavomaculatus* and (2) whether those boundaries overlap significantly with ecoregion boundaries.
## Load packages used in this vignette
```{r message = FALSE}
library(BoundaryStats)
library(terra)
library(magrittr)
```
## Input data
### Ecoregion data
``` {r fig.width = 8, fig.height = 6}
data(ecoregions)
ecoregions <- rast(ecoregions_matrix, crs = ecoregions_crs)
ext(ecoregions) <- ecoregions_ext
plot(ecoregions)
```
### Genetic data
These data are based on the ADMIXTURE results from Barratt et al. 2018. The point data (assignment probabilities for each individual) have been interpolated using universal kriging to produce a raster surface.
```{r fig.width = 8, fig.height = 6}
data(L.flavomaculatus)
L.flavomaculatus <- rast(L.flavomaculatus_matrix, crs = L.flavomaculatus_crs)
ext(L.flavomaculatus) <- L.flavomaculatus_ext
plot(L.flavomaculatus)
```
### Matching datasets
In order to test for significant overlap between the traits, the SpatRaster objects need to be aligned in extent, resolution, and projection. We are first matching the projection, then downsampling and cropping the ecoregion raster to match the genetic data. We are also masking the genetic raster with the ecoregion, since it originally includes space off the coastline.
```{r}
crs(ecoregions) <- crs(L.flavomaculatus)
ecoregions <- resample(ecoregions, L.flavomaculatus) %>%
crop(., L.flavomaculatus) %>%
mask(., L.flavomaculatus)
L.flavomaculatus <- crop(L.flavomaculatus, ecoregions) %>%
mask(., ecoregions)
```
## Define trait boundaries and ecoregion boundaries
There are two functions to define geographical boundaries in BoundaryStats, which take different data. The function define_boundary() takes either continuous trait data and boundary intensities. If inputting continuous trait data, use convert = T to convert from trait data into boundaries. If inputting boundary intensity data (e.g., urbanization metrics if urban land uses are boundaries), use convert = F to define boundaries based on an intensity threshold.
The two datasets in this vignette are categorical--ecoregion and genetic group identity--so we are using the other boundary definition function, categorical_boundary() to identify spatial transitions from one category to another.
```{r fig.width = 8, fig.height = 6}
ecoregions_boundaries <- categorical_boundary(ecoregions)
L.flavomaculatus_boundaries <- categorical_boundary(L.flavomaculatus)
```
## Plot boundary overlap
The overlap in boundaries between two variables can be plotted using the plot_boundary() function, which is a wrapper for ggplot2.
```{r warning = FALSE, fig.width = 8, fig.height = 6}
plot_boundary(L.flavomaculatus_boundaries, ecoregions_boundaries, trait_names = c('A. delicatus genetic group', 'Ecoregion'))
```
## Calculate boundary statistics
### Create null distributions
The function boundary_null_distrib() simulates neutral landscapes based on the input data. The default number of iterations is 10, but a value between 100 and 1000 is recommended. This step may take a while, depending on the selected neutral model and number of iterations, so we are maintaining the default 10 iterations.
Three neutral models are currently available: complete stochasticity (default), Gaussian random fields, and modified random clusters. Random cluster models are suited to categorical variables like group identity (cat = T), so we use it here.
```{r}
L.flav_bound.null <- boundary_null_distrib(L.flavomaculatus, cat = T, n_iterations = 10, model = 'random_cluster', p = 0.5, progress = F)
```
### Run statistical tests
n_subgraph is the number of subgraphs (i.e., contiguous groups of cells representing boundaries), and max_subgraph is the length of the longest subgraph.
```{r}
n_subgraph(L.flavomaculatus_boundaries, L.flav_bound.null)
max_subgraph(L.flavomaculatus_boundaries, L.flav_bound.null)
```
## Calculate boundary overlap statistics
### Create null distributions
Usage for overlap_null_distrib is similar to boundary_null_distrib, but takes raster surfaces for two traits (x and y), along with arguments for each trait. Since we are testing the effects of relatively static ecoregions on L. flavomaculatus population structure, we are not going to simulate randomized rasters for the ecoregions.
```{r}
L.flav_overlap.null <- overlap_null_distrib(L.flavomaculatus, ecoregions, rand_both = F, x_cat = T, n_iterations = 10, x_model = 'random_cluster', px = 0.5, progress = F)
```
### Run statistical tests
Odirect is the number of directly overlapping boundary elements between the two variables. Ox is the average minimum distance for a a Trait x boundary element to the nearest Trait y boundary element. It assumes that boundaries for Trait x depend on the boundaries in Trait y. Oxy is the average minimum distance between boundary elements in x and y (x and y affect each other reciprocally).
```{r}
Odirect(L.flavomaculatus_boundaries, ecoregions_boundaries, L.flav_overlap.null)
Ox(L.flavomaculatus_boundaries, ecoregions_boundaries, L.flav_overlap.null)
Oxy(L.flavomaculatus_boundaries, ecoregions_boundaries, L.flav_overlap.null)
```
## Citation
Barratt, C.D., Bwong, B.A., Jehle, R., Liedtke, C.H., Nagel, P., Onstein, R.E., Portik, D.M., Streicher, J.W. & Loader, S.P. (2018) Vanishing refuge? Testing the forest refuge hypothesis in coastal East Africa using genome‐wide sequence data for seven amphibians. Molecular Ecology, 27, 4289-4308.
|
/scratch/gouwar.j/cran-all/cranData/BoundaryStats/inst/doc/BoundaryStats.Rmd
|
---
title: "BoundaryStats Analysis Workflow"
author: "Amy Luo"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{BoundaryStats Analysis Workflow}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
This vignette is a walkthrough of the workflow for calculating boundary statistics and boundary overlap statistics for two ecological variables. Here, we use East African ecoregion data and genomic analyses from Barratt et al. 2018. The following code tests for (1) whether there are significant geographic boundaries between genetic groups of the frog species *Leptopelis flavomaculatus* and (2) whether those boundaries overlap significantly with ecoregion boundaries.
## Load packages used in this vignette
```{r message = FALSE}
library(BoundaryStats)
library(terra)
library(magrittr)
```
## Input data
### Ecoregion data
``` {r fig.width = 8, fig.height = 6}
data(ecoregions)
ecoregions <- rast(ecoregions_matrix, crs = ecoregions_crs)
ext(ecoregions) <- ecoregions_ext
plot(ecoregions)
```
### Genetic data
These data are based on the ADMIXTURE results from Barratt et al. 2018. The point data (assignment probabilities for each individual) have been interpolated using universal kriging to produce a raster surface.
```{r fig.width = 8, fig.height = 6}
data(L.flavomaculatus)
L.flavomaculatus <- rast(L.flavomaculatus_matrix, crs = L.flavomaculatus_crs)
ext(L.flavomaculatus) <- L.flavomaculatus_ext
plot(L.flavomaculatus)
```
### Matching datasets
In order to test for significant overlap between the traits, the SpatRaster objects need to be aligned in extent, resolution, and projection. We are first matching the projection, then downsampling and cropping the ecoregion raster to match the genetic data. We are also masking the genetic raster with the ecoregion, since it originally includes space off the coastline.
```{r}
crs(ecoregions) <- crs(L.flavomaculatus)
ecoregions <- resample(ecoregions, L.flavomaculatus) %>%
crop(., L.flavomaculatus) %>%
mask(., L.flavomaculatus)
L.flavomaculatus <- crop(L.flavomaculatus, ecoregions) %>%
mask(., ecoregions)
```
## Define trait boundaries and ecoregion boundaries
There are two functions to define geographical boundaries in BoundaryStats, which take different data. The function define_boundary() takes either continuous trait data and boundary intensities. If inputting continuous trait data, use convert = T to convert from trait data into boundaries. If inputting boundary intensity data (e.g., urbanization metrics if urban land uses are boundaries), use convert = F to define boundaries based on an intensity threshold.
The two datasets in this vignette are categorical--ecoregion and genetic group identity--so we are using the other boundary definition function, categorical_boundary() to identify spatial transitions from one category to another.
```{r fig.width = 8, fig.height = 6}
ecoregions_boundaries <- categorical_boundary(ecoregions)
L.flavomaculatus_boundaries <- categorical_boundary(L.flavomaculatus)
```
## Plot boundary overlap
The overlap in boundaries between two variables can be plotted using the plot_boundary() function, which is a wrapper for ggplot2.
```{r warning = FALSE, fig.width = 8, fig.height = 6}
plot_boundary(L.flavomaculatus_boundaries, ecoregions_boundaries, trait_names = c('A. delicatus genetic group', 'Ecoregion'))
```
## Calculate boundary statistics
### Create null distributions
The function boundary_null_distrib() simulates neutral landscapes based on the input data. The default number of iterations is 10, but a value between 100 and 1000 is recommended. This step may take a while, depending on the selected neutral model and number of iterations, so we are maintaining the default 10 iterations.
Three neutral models are currently available: complete stochasticity (default), Gaussian random fields, and modified random clusters. Random cluster models are suited to categorical variables like group identity (cat = T), so we use it here.
```{r}
L.flav_bound.null <- boundary_null_distrib(L.flavomaculatus, cat = T, n_iterations = 10, model = 'random_cluster', p = 0.5, progress = F)
```
### Run statistical tests
n_subgraph is the number of subgraphs (i.e., contiguous groups of cells representing boundaries), and max_subgraph is the length of the longest subgraph.
```{r}
n_subgraph(L.flavomaculatus_boundaries, L.flav_bound.null)
max_subgraph(L.flavomaculatus_boundaries, L.flav_bound.null)
```
## Calculate boundary overlap statistics
### Create null distributions
Usage for overlap_null_distrib is similar to boundary_null_distrib, but takes raster surfaces for two traits (x and y), along with arguments for each trait. Since we are testing the effects of relatively static ecoregions on L. flavomaculatus population structure, we are not going to simulate randomized rasters for the ecoregions.
```{r}
L.flav_overlap.null <- overlap_null_distrib(L.flavomaculatus, ecoregions, rand_both = F, x_cat = T, n_iterations = 10, x_model = 'random_cluster', px = 0.5, progress = F)
```
### Run statistical tests
Odirect is the number of directly overlapping boundary elements between the two variables. Ox is the average minimum distance for a a Trait x boundary element to the nearest Trait y boundary element. It assumes that boundaries for Trait x depend on the boundaries in Trait y. Oxy is the average minimum distance between boundary elements in x and y (x and y affect each other reciprocally).
```{r}
Odirect(L.flavomaculatus_boundaries, ecoregions_boundaries, L.flav_overlap.null)
Ox(L.flavomaculatus_boundaries, ecoregions_boundaries, L.flav_overlap.null)
Oxy(L.flavomaculatus_boundaries, ecoregions_boundaries, L.flav_overlap.null)
```
## Citation
Barratt, C.D., Bwong, B.A., Jehle, R., Liedtke, C.H., Nagel, P., Onstein, R.E., Portik, D.M., Streicher, J.W. & Loader, S.P. (2018) Vanishing refuge? Testing the forest refuge hypothesis in coastal East Africa using genome‐wide sequence data for seven amphibians. Molecular Ecology, 27, 4289-4308.
|
/scratch/gouwar.j/cran-all/cranData/BoundaryStats/vignettes/BoundaryStats.Rmd
|
# The BoutrosLab.plotting.general package is copyright (c) 2014 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# Bx downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which max arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
prep.axis <- function(
at,
data,
which.arg
) {
if (is.null(at)) {
return(at);
}
else if (is.logical(at)) {
return(at);
}
else if (length(at) > 1) {
return(at);
}
out <- list();
if ('auto' == at) {
out <- auto.axis(
x = data
);
}
else if ('auto.linear' == at) {
out <- auto.axis(
x = data,
log.scaled = FALSE
);
}
else if ('auto.log' == at) {
out <- auto.axis(
x = data,
log.scaled = TRUE
);
}
else {
stop(paste0('Invalid input to ', which.arg, ': ', at));
}
return(out);
}
auto.axis <- function(
x,
pretty = TRUE,
log.scaled = NA,
log.zero = 0.1,
max.factor = 1,
min.factor = 1,
include.origin = TRUE,
num.labels = 5,
max.min.log10.diff = 2
) {
out <- list();
x <- as.numeric(x);
# Get max and min to plot
max.x <- max(x, na.rm = TRUE) * max.factor;
min.x <- min(x, na.rm = TRUE) * min.factor;
# Make sure x is all > 0 to consider log scale
if (all(x > 0, na.rm = TRUE)) {
# Determine scale based on skewness
skewness.x <- skewness(x, na.rm = TRUE);
# Handle zero values so that they can still be plotted even log(0) = -Inf
zero.i <- which(0 == x);
logx <- log(x, 10);
if (length(zero.i) > 0) {
# use a proxy for log(0)
logx[zero.i] <- log.zero;
}
if (max.x - min.x != 0) {
# x.log10.diff scale should be more than 2
cond1 <- log10(max.x - min.x) > max.min.log10.diff;
}
else {
cond1 <- FALSE; # vector x only contains 0
}
#skewness.x should be larger than skewness.log10(x)
cond2 <- (skewness.x > skewness(logx, na.rm = TRUE));
}
else {
cond1 <- FALSE;
cond2 <- FALSE;
}
# Decide log scale or not based on cond1 and cond2
if (cond1 && cond2) {
out$log.scaled <- TRUE;
if (!is.na(log.scaled) && !log.scaled) {
out$log.scaled <- FALSE;
}
}
else {
out$log.scaled <- FALSE;
# Force log scale
if (!is.na(log.scaled) && log.scaled) {
out$log.scaled <- TRUE;
if (!all(x > 0, na.rm = TRUE)) {
stop('can not use log-scale as the input vector contains negative values.');
}
}
}
if (out$log.scaled) {
out$x <- logx;
min.x <- min(out$x, na.rm = TRUE);
max.x <- max(out$x, na.rm = TRUE);
out$at <- generate.at(min.x, max.x, pretty, include.origin, num.labels);
# set axis labels
out$axis.lab <- sapply(
out$at[-1], # Remove 1
FUN = function(x) {
substitute(bold('10' ^ a), list(a = as.character(x)));
}
);
out$axis.lab <- c(expression(bold('0')), out$axis.lab);
}
else {
# For variables that are continuous and will not be plotted on a log-scale
# Set axis increments
out$x <- x;
out$at <- generate.at(min.x, max.x, pretty, include.origin, num.labels);
# Set axis labels
if (abs(mean(x, na.rm = TRUE)) > 1000 || abs(mean(x, na.rm = TRUE)) < 0.001 ) {
out$axis.lab <- as.power10.expression(out$at);
}
else {
out$axis.lab <- out$at;
}
}
return(out);
}
generate.at <- function(min.x, max.x, pretty = TRUE, include.origin = TRUE, num.labels = 4) {
out <- c();
if (pretty) {
if (max.x * min.x <= 0 || include.origin == FALSE) {
out <- pretty(c(min.x, max.x), n = num.labels - 1);
}
else {
if (min.x > 0 && include.origin == TRUE) {
out <- pretty(c(0, max.x), n = num.labels - 1);
}
if (max.x < 0 && include.origin == TRUE) {
out <- pretty(c(min.x, 0), n = num.labels - 1);
}
}
}
else {
if (max.x * min.x <= 0 || include.origin == FALSE) {
out <- seq(min.x, max.x, length.out = num.labels);
}
else {
if (min.x > 0 && include.origin == TRUE) {
out <- seq(0, max.x, length.out = num.labels);
}
if (max.x < 0 && include.origin == TRUE) {
out <- seq(min.x, 0, length.out = num.labels);
}
}
}
return(out);
}
as.power10.expression <- function(x) {
x <- unlist(x);
out <- sapply(x, function(y) {
y <- as.numeric(y);
# No need to do anything if x = 0
if (0 == y) {
return(expression(bold('0')));
}
# Otherwise, convert x to power of 10 and split by e
y <- as.numeric(unlist(strsplit(sprintf('%e', y), split = 'e')));
# If x[1] = 1, then a should be omitted.
if (1 != y[1]) {
y <- substitute(bold(a %*% '10' ^ b), list(a = as.character(y[1]), b = as.character(y[2])));
}
else {
y <- substitute(bold('10' ^ b), list(b = as.character(y[2])));
}
# Return as expression otherwise list
as.expression(y);
});
# Return as expression
return(out);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/auto.axis.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2014 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO GENERATE GRADIENT COLOUR PALETTES #################################################
colour.gradient <- color.gradient <- function(colour, length) {
# create the range of colours, such that the colours range from white to black (this creates a greater value range)
palette.ramp <- colorRampPalette(c('white', colour, 'black'));
# creating the palette.ramp to have two extra colours serves to account for the added white and black
# Setting the range to be from [2:length + 1] serves to ignore the white and black
colour.palette <- palette.ramp(length + 2)[2:(length + 1)];
return(colour.palette);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/colour.gradient.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO CREATE A COVARIATE BAR GROB ########################################################
covariates.grob <- function(
covariates, ord, side = 'right', size = 1, grid.row = NULL, grid.col = NULL, grid.border = NULL,
row.lines = NULL, col.lines = NULL, reorder.grid.index = FALSE, x = 0.5, y =0.5
) {
# This function creates a grid graphical object representing a covariate bar
# It is adapted from the function latticeExtra:::dendrogramGrob
# Remove padding so the covariate bars line up properly with the axes
lattice.old.factor <- lattice.getOption('axis.padding')$factor;
lattice.options('axis.padding' = list(factor = 0.5));
# Calculate the scale for the covariate bars
native.xscale <- c(1, length(ord)) + c(-1, 1) * lattice.getOption('axis.padding')$factor;
native.unit <- 1 / diff(native.xscale);
ncovariates <- length(covariates);
key.gf <- NULL;
# Create grob for either the right or top side of the image
switch(
side,
right = {
# Create the layout for the grob at the right of the image
key.layout <- grid.layout(
nrow = 1,
ncol = ncovariates,
heights = unit(1, 'null'),
widths = unit(
x = c(rep(size, ncovariates)),
units = c(rep('lines', ncovariates))
),
respect = FALSE
);
# Create a frame using this layout
key.gf <- frameGrob(layout = key.layout);
# Place each of the covariate bars
for (i in seq_len(ncovariates)) {
covariatesi <- covariates[[i]];
typei <- names(covariates)[i];
switch(
typei,
rect = {
key.gf <- placeGrob(
frame = key.gf,
grob = rectGrob(
y = (order(ord) - native.xscale[1]) * native.unit,
height = native.unit,
gp = do.call(gpar, covariatesi)
),
row = 1,
col = i
);
}
);
}
# Draw row grid lines
if (!is.null(grid.row)) {
if (!is.list(grid.row)) {
stop('Argument grid.row of covariates.grob must be a list of arguments to gpar.');
}
# By default, draw all row lines
if (is.null(row.lines)) {
row.lines <- 0:length(ord);
}
# Make sure user-specified lines are in bounds
else if (any(row.lines < 0) || any(row.lines > length(ord))) {
stop('Argument row.lines of covariates.grob out of bounds.');
}
for (i in row.lines) {
index <- if (reorder.grid.index) { order(ord)[i] } else { i };
key.gf <- placeGrob(
frame = key.gf,
grob = linesGrob(
x = c(0, 1),
y = if (i == 0) { c(0, 0) } else { rep(index * native.unit, 2) },
gp = do.call(gpar, grid.row)
),
row = 1,
col = NULL
);
}
}
# Draw column grid lines
if (!is.null(grid.col)) {
if (!is.list(grid.col)) {
stop('Argument grid.col of covariates.grob must be a list of arguments to gpar.');
}
# By default, draw all column lines
if (is.null(col.lines)) {
col.lines <- 0:ncovariates;
}
# Make sure user-specified lines are in bounds
else if (any(col.lines < 0) || any(col.lines > ncovariates)) {
stop('Argument col.lines of covariates.grob out of bounds.');
}
for (i in col.lines) {
key.gf <- placeGrob(
frame = key.gf,
grob = linesGrob(
x = if (i == 0) { c(0, 0) } else { c(1, 1) },
y = c(0, 1),
gp = do.call(gpar, grid.col)
),
row = 1,
col = if (i == 0) { 1 } else { i }
);
}
}
# Draw border
if (!is.null(grid.border)) {
if (!is.list(grid.border)) {
stop('Argument grid.border of covariates.grob must be a list.');
}
grid.border[['fill']] <- 'transparent';
key.gf <- placeGrob(
frame = key.gf,
grob = rectGrob(
gp = do.call(gpar, grid.border)
),
row = NULL,
col = NULL
);
}
},
top = {
# Create the layout for the grob at the top of the image
key.layout <- grid.layout(
nrow = ncovariates,
ncol = 1,
widths = unit(1, 'null'),
heights = unit(
x = c(rep(size, ncovariates)),
units = c(rep('lines', ncovariates))
),
respect = FALSE
);
# Create a frame using this layout
key.gf <- frameGrob(layout = key.layout);
# Place each of the covariate bars
for (i in seq_len(ncovariates)) {
covariatesi <- covariates[[i]];
typei <- names(covariates)[i];
switch(
typei,
rect = {
key.gf <- placeGrob(
frame = key.gf,
grob = rectGrob(
x = (order(ord) - native.xscale[1]) * native.unit,
width = native.unit,
gp = do.call(gpar, covariatesi)
),
row = i,
col = 1
);
}
);
}
# Draw column grid lines
if (!is.null(grid.col)) {
if (!is.list(grid.col)) {
stop('Argument grid.col of covariates.grob must be a list.');
}
# By default, draw all column lines
if (is.null(col.lines)) {
col.lines <- 0:length(ord);
}
# Make sure user-specified lines are in bounds
else if (any(col.lines < 0) || any(col.lines > length(ord))) {
stop('Argument col.lines of covariates.grob out of bounds.');
}
for (i in col.lines) {
index <- if (reorder.grid.index) { order(ord)[i] } else { i };
key.gf <- placeGrob(
frame = key.gf,
grob = linesGrob(
x = if (i == 0) { c(0, 0) } else { rep(index * native.unit, 2) },
y = c(0, 1),
gp = do.call(gpar, grid.col)
),
row = NULL,
col = 1
);
}
}
# Draw row grid lines
if (!is.null(grid.row)) {
if (!is.list(grid.row)) {
stop('Argument grid.row of covariates.grob must be a list.');
}
# By default, draw all row lines
if (is.null(row.lines)) {
row.lines <- 0:ncovariates;
}
# Make sure user-specified lines are in bounds
else if (any(row.lines < 0) || any(row.lines > ncovariates)) {
stop('Argument row.lines of covariates.grob out of bounds.');
}
for (i in row.lines) {
key.gf <- placeGrob(
frame = key.gf,
grob = linesGrob(
x = c(0, 1),
y = if (i == 0) { c(0, 0) } else { c(1, 1) },
gp = do.call(gpar, grid.row)
),
row = if (i == 0) { 1 } else { i },
col = 1
);
}
}
# Draw border
if (!is.null(grid.border)) {
if (!is.list(grid.border)) {
stop('Argument grid.border of covariates.grob must be a list.');
}
grid.border[['fill']] <- 'transparent';
key.gf <- placeGrob(
frame = key.gf,
grob = rectGrob(
gp = do.call(gpar, grid.border)
),
row = NULL,
col = NULL
);
}
}
);
# Restore original lattice setting
lattice.options('axis.padding' = list(factor = lattice.old.factor));
# set x and y coordinates
key.gf$framevp$y <- unit(y, 'npc');
key.gf$framevp$x <- unit(x, 'npc');
# Return the grob
return(key.gf);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/covariates.grob.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2013 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO CREATE BARPLOTS ###################################################################
create.barplot <- function(
formula, data, groups = NULL, stack = FALSE, filename = NULL, main = NULL, main.just = 'center',
main.x = 0.5, main.y = 0.5, main.cex = 3, xlab.label = tail(sub('~', '', formula[-2]), 1),
ylab.label = tail(sub('~', '', formula[-3]), 1), xlab.cex = 2, ylab.cex = 2, xlab.col = 'black',
ylab.col = 'black', xlab.top.label = NULL, xlab.top.cex = 2, xlab.top.col = 'black',
xlab.top.just = 'center', xlab.top.x = 0.5, xlab.top.y = 0, abline.h = NULL, abline.v = NULL,
abline.lty = 1, abline.lwd = NULL, abline.col = 'black', axes.lwd = 1, add.grid = FALSE, xgrid.at = xat,
ygrid.at = yat, grid.lwd = 5, grid.col = NULL, xaxis.lab = TRUE, yaxis.lab = TRUE, xaxis.col = 'black',
yaxis.col = 'black', xaxis.fontface = 'bold', yaxis.fontface = 'bold', xaxis.cex = 1.5, yaxis.cex = 1.5,
xaxis.rot = 0, yaxis.rot = 0, xaxis.tck = 1, yaxis.tck = 1, xlimits = NULL, ylimits = NULL, xat = TRUE,
yat = TRUE, layout = NULL, as.table = FALSE, x.spacing = 0, y.spacing = 0, x.relation = 'same',
y.relation = 'same', top.padding = 0.5, bottom.padding = 1, right.padding = 1, left.padding = 1,
key.bottom = 0.1, ylab.axis.padding = 0.5, xlab.axis.padding = 0.5, col = 'black', border.col = 'black',
border.lwd = 1, plot.horizontal = FALSE, background.col = 'transparent', origin = 0, reference = TRUE,
box.ratio = 2, sample.order = 'none', group.labels = FALSE, key = list(text = list(lab = c(''))),
legend = NULL, add.text = FALSE, text.labels = NULL, text.x = NULL, text.y = NULL, text.col = 'black',
text.cex = 1, text.fontface = 'bold', strip.col = 'white', strip.cex = 1, y.error.up = NULL,
y.error.down = y.error.up, y.error.bar.col = 'black', error.whisker.width = width / (nrow(data) * 4),
error.bar.lwd = 1, error.whisker.angle = 90, add.rectangle = FALSE, xleft.rectangle = NULL, ybottom.rectangle = NULL,
xright.rectangle = NULL, ytop.rectangle = NULL, col.rectangle = 'grey85', alpha.rectangle = 1,
line.func = NULL, line.from = 0, line.to = 0, line.col = 'transparent', line.infront = TRUE,
text.above.bars = list(labels = NULL, padding = NULL, bar.locations = NULL, rotation = 0),
raster = NULL, raster.vert = TRUE, raster.just = 'center', raster.width.dim = unit(2 / 37, 'npc'),
height = 6, width = 6, size.units = 'in', resolution = 1600, enable.warnings = FALSE,
description = 'Created with BoutrosLab.plotting.general', style = 'BoutrosLab', preload.default = 'custom',
use.legacy.settings = FALSE, inside.legend.auto = FALSE, disable.factor.sorting = FALSE
) {
### needed to copy in case using variable to define rectangles dimensions
rectangle.info <- list(
xright = xright.rectangle,
xleft = xleft.rectangle,
ytop = ytop.rectangle,
ybottom = ybottom.rectangle
);
text.info <- list(
labels = text.labels,
x = text.x,
y = text.y,
col = text.col,
cex = text.cex,
fontface = text.fontface
);
if (!is.null(yat) && length(yat) == 1) {
if (yat == 'auto') {
if (stack == TRUE) {
# run once to get data readjustment (in case log)
s <- split(data, data[toString(formula[[3]])]);
final.list <- list();
for (x in 1:length(s)) {
final.list[[x]] <- sum(s[[x]][toString(formula[[2]])]);
}
out <- auto.axis(final.list, log.scaled = FALSE);
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
else {
out <- auto.axis(unlist(data[toString(formula[[2]])]));
data[toString(formula[[2]])] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
}
else if (yat == 'auto.linear') {
if (stack == TRUE) {
# run once to get data readjustment (in case log)
s <- split(data, data[toString(formula[[3]])]);
final.list <- list();
for (x in 1:length(s)) {
final.list[[x]] <- sum(s[[x]][toString(formula[[2]])]);
}
out <- auto.axis(final.list, log.scaled = FALSE);
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
else {
out <- auto.axis(unlist(data[toString(formula[[2]])]), log.scaled = FALSE);
data[toString(formula[[2]])] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
}
else if (yat == 'auto.log') {
out <- auto.axis(unlist(data[toString(formula[[2]])]), log.scaled = TRUE);
data[toString(formula[[2]])] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
}
if (!is.null(xat) && length(xat) == 1) {
if (xat == 'auto') {
if (stack == TRUE) {
# run once to get data readjustment (in case log)
s <- split(data, data[toString(formula[[3]])]);
final.list <- list();
for (x in 1:length(s)) {
final.list[[x]] <- sum(s[[x]][toString(formula[[2]])]);
}
out <- auto.axis(final.list, log.scaled = FALSE);
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
else {
out <- auto.axis(unlist(data[toString(formula[[3]])]));
data[toString(formula[[3]])] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
}
else if (xat == 'auto.linear') {
if (stack == TRUE) {
# run once to get data readjustment (in case log)
s <- split(data, data[toString(formula[[3]])]);
final.list <- list();
for (x in 1:length(s)) {
final.list[[x]] <- sum(s[[x]][toString(formula[[2]])]);
}
out <- auto.axis(final.list, log.scaled = FALSE);
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
else {
out <- auto.axis(unlist(data[toString(formula[[3]])]), log.scaled = FALSE);
data[toString(formula[[3]])] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
}
else if (xat == 'auto.log') {
out <- auto.axis(unlist(data[toString(formula[[3]])]), log.scaled = TRUE);
data[toString(formula[[3]])] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
}
####### Error checking ########
tryCatch(
expr = {
if (is.null(formula)) { stop(); }
as.formula(formula);
},
error = function(message) {
stop('Invalid formula.');
}
);
# add preloaded defaults
if (preload.default == 'paper') {
}
else if (preload.default == 'web') {
}
# allow a gray spectrum if groups is specified and only a single colour is given
groups.new <- eval(substitute(groups), data, parent.frame());
if (!is.null(groups.new) && 1 == length(col) && col == 'grey') {
col <- grey(1:nlevels(as.factor(groups.new)) / nlevels(as.factor(groups.new)));
}
# check class of conditioning variable
if ('|' %in% all.names(formula)) {
variable <- sub('^\\s+', '', unlist(strsplit(toString(formula[length(formula)]), '\\|'))[2]);
if (variable %in% names(data)) {
cond.class <- class(data[, variable]);
if (cond.class %in% c('integer', 'numeric')) {
warning(
'Numeric values detected for conditional variable. If text labels are desired, please convert conditional variable to character.'
);
}
rm(cond.class);
}
}
# Now make the actual plot object
trellis.object <- lattice::barchart(
formula,
data,
panel = function(x, y, subscripts, groups = groups.new, ...) {
# add rectangle
if (add.rectangle) {
panel.rect(
xleft = rectangle.info$xleft,
ybottom = rectangle.info$ybottom,
xright = rectangle.info$xright,
ytop = rectangle.info$ytop,
col = col.rectangle,
alpha = alpha.rectangle,
border = NA
);
}
if (!is.null(text.above.bars$labels)) {
if (!is.null(groups.new)) {
stop("Argument 'text.above.bars' does not work with grouped plots.");
}
# Common arguments for both horizontal and vertical orientation
text.above.bars.args <- list(
labels = text.above.bars$labels,
srt = text.above.bars$rotation
);
# Keep all additional arguments passed to text.above.bars
# This is the equivalent of ... to an argument
text.above.bars.args <- c(
text.above.bars.args,
text.above.bars[
! names(text.above.bars) %in%
c('labels', 'padding', 'bar.locations', 'rotation', 'srt')
]
);
# change orientation if requested
if (plot.horizontal) {
text.above.bars.args$x <- x[text.above.bars$bar.locations] + text.above.bars$padding;
text.above.bars.args$y <- text.above.bars$bar.locations;
}
else {
text.above.bars.args$x <- text.above.bars$bar.locations;
text.above.bars.args$y <- y[text.above.bars$bar.locations] + text.above.bars$padding;
}
do.call(panel.text, text.above.bars.args);
}
# add background shading
# if (add.background.shading) {
# if (!is.null(background.shading.xpos)) {
# if (length(background.shading.xpos)%%2 == 1) {
# xleft <- background.shading.xpos[seq(1,length(background.shading.xpos)-1,2)];
# xright <- background.shading.xpos[seq(2,length(background.shading.xpos)-1,2)];
# }
# else {
# xleft <- background.shading.xpos[seq(1,length(background.shading.xpos),2)];
# xright <- background.shading.xpos[seq(2,length(background.shading.xpos),2)];
# }
# }
# else {
# xleft <- xlimits[1];
# xright <- xlimits[2];
# }
# if (!is.null(background.shading.ypos)) {
# if (length(background.shading.ypos)%%2 == 1) {
# ybottom <- background.shading.ypos[seq(1,length(background.shading.ypos)-1,2)];
# ytop <- background.shading.ypos[seq(2,length(background.shading.ypos)-1,2)];
# }
# else {
# ybottom <- background.shading.ypos[seq(1,length(background.shading.ypos),2)];
# ytop <- background.shading.ypos[seq(2,length(background.shading.ypos),2)];
# }
# }
# else {
# ybottom <- ylimits[1];
# ytop <- ylimits[2];
# }
# panel.rect(
# xleft = xleft,
# ybottom = ybottom,
# xright = xright,
# ytop = ytop,
# col = background.shading.colour,
# border = 'transparent'
# );
# }
# add grid-lines
if (add.grid) {
panel.abline(
v = BoutrosLab.plotting.general::generate.at.final(
at.input = xgrid.at,
limits = xlimits,
data.vector = data$x
),
h = BoutrosLab.plotting.general::generate.at.final(
at.input = ygrid.at,
limits = ylimits,
data.vector = data$y
),
col = if (is.null(grid.col)) { trellis.par.get('reference.line')$col } else { grid.col },
lwd = grid.lwd,
);
}
# Add the barplot
panel.barchart(x, y, subscripts = subscripts, groups = groups.new, border = border.col, lwd = border.lwd, ..., origin = origin);
# add lines superimposed
if (length(line.func) > 0 && !line.infront) {
panel.curve(expr = line.func, from = line.from, to = line.to, col = line.col);
}
panel.abline(h = abline.h, lty = abline.lty, lwd = abline.lwd, col = abline.col);
panel.abline(v = abline.v, lty = abline.lty, lwd = abline.lwd, col = abline.col);
if (length(line.func) > 0 && line.infront) {
panel.curve(expr = line.func, from = line.from, to = line.to, col = line.col);
}
# Add text to plot
if (add.text) {
panel.text(
x = text.info$x,
y = text.info$y,
labels = text.info$labels,
col = text.info$col,
cex = text.info$cex,
fontface = text.info$fontface
);
}
# add error bars
if (!is.null(y.error.up)) {
# handle x-position offset due to groups
if (!is.null(groups)) {
num.groups <- length(subscripts) / length(unique(groups));
group.num <- (subscripts - 1) %/% num.groups;
if (length(unique(group.num)) %% 2 == 1) {
group.num <- group.num - trunc(length(unique(group.num)) / 2);
}
else {
number.of.groups <- trunc(length(unique(group.num)) / 2);
subtr <- 1 + 2 * (number.of.groups - 1);
group.num <- group.num * 2 - subtr;
}
offset <- (6 / (nrow(data) * 4)) * (group.num) * (1.75 - (0.85 * (length(unique(groups)) + 1) %% 2));
}
else {
offset <- 0;
}
if (!plot.horizontal) {
panel.arrows(
# convert to numeric to handle when x is a factor
x0 = as.numeric(x) + offset,
y0 = y + y.error.up,
x1 = as.numeric(x) + offset,
y1 = y - y.error.down,
length = error.whisker.width,
angle = error.whisker.angle,
ends = 'both',
col = y.error.bar.col,
lwd = error.bar.lwd
);
}
else {
panel.arrows(
# convert to numeric to handle when x is a factor
y0 = as.numeric(y) + offset,
x0 = x + y.error.up,
y1 = as.numeric(y) + offset,
x1 = x - y.error.down,
length = error.whisker.width,
angle = error.whisker.angle,
ends = 'both',
col = y.error.bar.col,
lwd = error.bar.lwd
);
}
}
# add raster fill
if (!is.null(raster)) {
if (raster.vert) {
grid.raster(
raster,
x = x,
y = 0,
height = y,
just = raster.just,
default.units = 'native',
width = raster.width.dim
);
}
else {
grid.raster(
raster,
x = 0,
width = x,
y = y,
just = raster.just,
default.units = 'native',
height = raster.width.dim
);
}
}
},
horizontal = plot.horizontal,
main = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = main,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
cex = main.cex,
just = main.just,
x = main.x,
y = main.y
)
),
xlab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.label,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
cex = xlab.cex,
col = xlab.col
)
),
xlab.top = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.top.label,
cex = xlab.top.cex,
col = xlab.top.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
just = xlab.top.just,
x = xlab.top.x,
y = xlab.top.y
)
),
ylab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = ylab.label,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
cex = ylab.cex,
col = ylab.col
)
),
scales = list(
x = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
labels = xaxis.lab,
cex = xaxis.cex,
rot = xaxis.rot,
col = xaxis.col,
limits = xlimits,
at = xat,
tck = xaxis.tck,
relation = x.relation,
fontface = if ('Nature' == style) { 'plain' } else { xaxis.fontface },
alternating = FALSE
)
),
y = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
labels = yaxis.lab,
cex = yaxis.cex,
rot = yaxis.rot,
col = yaxis.col,
limits = ylimits,
at = yat,
tck = yaxis.tck,
relation = y.relation,
fontface = if ('Nature' == style) { 'plain' } else { yaxis.fontface },
alternating = FALSE
)
)
),
between = list(
x = x.spacing,
y = y.spacing
),
par.settings = list(
axis.line = list(
lwd = axes.lwd,
col = if ('Nature' == style) { 'transparent' } else { 'black' }
),
layout.heights = list(
top.padding = top.padding,
main = if (is.null(main)) { 0.3 } else { 1 },
main.key.padding = 0.1,
key.top = 0.1,
key.axis.padding = 0.1,
axis.top = 0.7,
axis.bottom = 1.0,
axis.xlab.padding = xlab.axis.padding,
xlab = 1,
xlab.key.padding = 0.1,
key.bottom = key.bottom,
key.sub.padding = 0.1,
sub = 0.1,
bottom.padding = bottom.padding
),
layout.widths = list(
left.padding = left.padding,
key.left = 0,
key.ylab.padding = 0.5,
ylab = 1,
ylab.axis.padding = ylab.axis.padding,
axis.left = 1,
axis.panel = 0.3,
strip.left = 0.3,
panel = 1,
between = 1,
axis.right = 1,
axis.key.padding = 1,
key.right = 1,
right.padding = right.padding
),
strip.background = list(
col = strip.col
),
panel.background = list(
col = background.col
)
),
par.strip.text = list(
cex = strip.cex
),
col = col,
layout = layout,
as.table = as.table,
key = key,
legend = legend,
pretty = TRUE,
stack = stack,
reference = reference,
box.ratio = box.ratio
);
if (disable.factor.sorting == TRUE) {
sorting.param <- '';
if (plot.horizontal) {
sorting.param <- 'y';
if (is.null(trellis.object$y.scales$labels) || (is.logical(trellis.object$y.scales$labels[1]) && trellis.object$y.scales$labels[1] == TRUE)) {
default.labels <- unique(as.character(trellis.object$panel.args[[1]][[sorting.param]]));
trellis.object$y.scales$labels <- default.labels;
}
}
else {
sorting.param <- 'x';
if (is.null(trellis.object$x.scales$labels) || (is.logical(trellis.object$x.scales$labels[1]) && trellis.object$x.scales$labels[1] == TRUE)) {
default.labels <- unique(as.character(trellis.object$panel.args[[1]][[sorting.param]]));
trellis.object$x.scales$labels <- default.labels;
}
}
unique.mapping <- list();
count <- 1;
for (x in trellis.object$panel.args[[1]][[sorting.param]]) {
if (is.null(unique.mapping[[as.character(x)]])) {
unique.mapping[as.character(x)] <- count;
count <- count + 1;
}
}
temp.data <- as.character(trellis.object$panel.args[[1]][[sorting.param]]);
for (x in 1:length(temp.data)) {
temp.data[x] <- as.character(unique.mapping[as.character(trellis.object$panel.args[[1]][[sorting.param]][[x]])][[1]]);
}
trellis.object$panel.args[[1]][[sorting.param]] <- as.numeric(temp.data);
}
if (inside.legend.auto) {
extra.parameters <- list('data' = data, 'plot.horizontal' = plot.horizontal, 'formula' = formula, 'groups' = groups,
'stack' = stack, 'ylimits' = trellis.object$y.limits, 'xlimits' = trellis.object$x.limits);
coords <- c();
coords <- .inside.auto.legend('create.barplot', filename, trellis.object, height, width, extra.parameters);
trellis.object$legend$inside$x <- coords[1];
trellis.object$legend$inside$y <- coords[2];
}
# add grouped labels
if (group.labels) {
num.groups <- length(trellis.object$panel.args[[1]]$x) / length(unique(trellis.object$panel.args[[1]]$x));
intialaddition <- (1 / 3) / num.groups;
additions <- intialaddition * 2;
newxat <- NULL;
if (is.logical(trellis.object$x.scales$at)) {
trellis.object$x.scales$at <- c(1:length(unique(trellis.object$panel.args[[1]]$x)));
}
for (i in trellis.object$x.scales$at) {
for (j in c(1:num.groups)) {
newxat <- c(newxat, i - 1 / 3 + intialaddition + additions * (j - 1));
}
}
trellis.object$x.scales$at <- newxat;
}
# reorder the bars in decreasing or increasing order if specified
if (is.null(sample.order) || is.na(sample.order)) { sample.order <- 'none'; }
if (sample.order[1] != 'none') {
for (i in 1:length(trellis.object$panel.args)) {
# will need two separate ways for horizontal and non - horizontal
if (!plot.horizontal) {
num.bars <- length(unique(trellis.object$panel.args[[1]]$x));
if (length(unique(sample.order)) == num.bars) {
if (length(xaxis.lab) == 1 && xaxis.lab) {
ordering <- rev(match(sample.order, trellis.object$panel.args[[i]]$x));
}
else {
ordering <- rev(match(sample.order, trellis.object$x.scales$labels));
}
}
if (length(sample.order) == 1) {
if(! sample.order %in% c('decreasing', 'increasing')) {
stop('sample.order should be `decreasing` or `increasing`');
}
# This looks backwards but gets reversed later
# Might want to revisit if it makes more sense to sort in correct order here
sample.order.decreasing <- sample.order != 'decreasing';
ordering <- order(
trellis.object$panel.args[[1]]$y[c(1:num.bars)],
decreasing = sample.order.decreasing
);
}
# if label locations are specified, change them
if (xat != TRUE) {
newxat <- NULL;
for (j in rev(ordering)) {
if (length(which(xat == j) > 0)) {
newxat <- c(newxat, which(rev(ordering) == j));
}
else { newxat <- c(newxat, 0); }
}
trellis.object$x.scales$at <- newxat;
}
# if labels were not specified reorder the default ones
if (length(xaxis.lab) == 1 && xaxis.lab) {
trellis.object$x.scales$labels <- rep(
trellis.object$panel.args[[i]]$x[rev(ordering)],
length(trellis.object$panel.args[[1]]$x) / num.bars
);
}
# if labels are specified reorder the specified ones
else {
trellis.object$x.scales$labels <- rev(trellis.object$x.scales$labels[rev(ordering)]);
warning('WARNING: the label order you specified has been reordered.');
}
for (j in 0:(length(trellis.object$panel.args[[1]]$x) / num.bars - 1)) {
# reorder values of bars
trellis.object$panel.args[[i]]$y[c( (1 + j * num.bars) : (num.bars * (j + 1) ) )] <- rev(
trellis.object$panel.args[[i]]$y[ordering + num.bars * j]
);
# reorder values of x to order in logical order
trellis.object$panel.args[[i]]$x <- rep(1:length(ordering), length(trellis.object$panel.args[[1]]$x) / num.bars);
}
}
else {
num.bars <- length(unique(trellis.object$panel.args[[1]]$y));
if (length(unique(sample.order)) == num.bars) {
if (length(yaxis.lab) == 1 && yaxis.lab) {
ordering <- rev(match(sample.order, sort(sample.order)[trellis.object$panel.args[[i]]$y]));
}
else {
ordering <- rev(match(sample.order, sort(sample.order)[trellis.object$y.scales$labels]));
}
}
if (length(sample.order) == 1) {
if(! sample.order %in% c('decreasing', 'increasing')) {
stop('sample.order should be `decreasing` or `increasing`');
}
sample.order.decreasing <- sample.order != 'decreasing';
ordering <- order(
trellis.object$panel.args[[1]]$x[c(1:num.bars)],
decreasing = sample.order.decreasing
);
}
if (!yat) {
newyat <- NULL;
for (j in rev(ordering)) {
if (length(which(yat == j) > 0)) {
newyat <- c(newyat, which(rev(ordering) == j));
}
else {
newyat <- c(newyat, 0);
}
}
trellis.object$y.scales$at <- newyat;
}
if (length(yaxis.lab) == 1 && yaxis.lab) {
trellis.object$y.scales$labels <- rep(
trellis.object$panel.args[[i]]$y[ordering],
length(trellis.object$panel.args[[1]]$y) / num.bars
);
}
else {
trellis.object$y.scales$labels <- rev(trellis.object$y.scales$labels[ordering]);
warning('WARNING: the label order you specified has been reordered.');
}
for (j in 0:(length(trellis.object$panel.args[[1]]$y) / num.bars - 1)) {
trellis.object$panel.args[[i]]$x[c( (1 + j * num.bars) : (num.bars * (j + 1) ) )] <-
trellis.object$panel.args[[i]]$x[ordering + num.bars * j];
trellis.object$panel.args[[i]]$y <- rep(1:length(ordering), length(trellis.object$panel.args[[1]]$y) / num.bars);
}
}
}
y.error.up <- y.error.up[rev(ordering)];
y.error.down <- y.error.down[rev(ordering)];
}
# If Nature style requested, change figure accordingly
if ('Nature' == style) {
# Re-add bottom and left axes
trellis.object$axis <- function(side, line.col = 'black', ...) {
# Only draw axes on the left and bottom
if (side %in% c('bottom', 'left')) {
axis.default(side = side, line.col = 'black', ...);
lims <- current.panel.limits();
panel.abline(h = lims$ylim[1], v = lims$xlim[1]);
}
}
# Ensure sufficient resolution for graphs
if (resolution < 1200) {
resolution <- 1200;
warning('Setting resolution to 1200 dpi.');
}
# Other required changes which are not accomplished here
warning('Nature also requires italicized single-letter variables and
en-dashes for ranges and negatives. See example in documentation for how to do this.');
warning('Avoid red-green colour schemes, create TIFF files, do not outline the figure or legend.');
}
# Otherwise use the BL style if requested
else if ('BoutrosLab' == style) {
# Nothing happens
}
# if neither of the above is requested, give a warning
else {
warning("The style parameter only accepts 'Nature' or 'BoutrosLab'.");
}
# output the object
return(
BoutrosLab.plotting.general::write.plot(
trellis.object = trellis.object,
filename = filename,
height = height,
width = width,
size.units = size.units,
resolution = resolution,
enable.warnings = enable.warnings,
description = description
)
);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/create.barplot.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO CREATE BOXPLOTS ###################################################################
create.boxplot <- function(
formula, data, filename = NULL, main = NULL, main.just = 'center', main.x = 0.5, main.y = 0.5,
main.cex = 3, add.stripplot = FALSE, jitter.factor = 1, jitter.amount = NULL, points.pch = 19,
points.col = 'darkgrey', points.cex = 0.5, points.alpha = 1, abline.h = NULL, abline.v = NULL,
abline.lty = NULL, abline.lwd = NULL, abline.col = 'black', add.rectangle = FALSE,
xleft.rectangle = NULL, ybottom.rectangle = NULL, xright.rectangle = NULL, ytop.rectangle = NULL,
col.rectangle = 'transparent', alpha.rectangle = 1, box.ratio = 1, col = 'transparent', alpha = 1,
border.col = 'black', symbol.cex = 0.8, lwd = 1, outliers = TRUE, sample.order = 'none', order.by = 'median',
xlab.label = tail(sub('~', '', formula[-2]), 1), ylab.label = tail(sub('~', '', formula[-3]), 1),
xlab.cex = 2, ylab.cex = 2, xlab.col = 'black', ylab.col = 'black', xlab.top.label = NULL, xlab.top.cex = 2,
xlab.top.col = 'black', xlab.top.just = 'center', xlab.top.x = 0.5, xlab.top.y = 0, xlimits = NULL,
ylimits = NULL, xat = TRUE, yat = TRUE, xaxis.lab = TRUE, yaxis.lab = TRUE, xaxis.cex = 1.5, yaxis.cex = 1.5,
xaxis.col = 'black', yaxis.col = 'black', xaxis.fontface = 'bold', yaxis.fontface = 'bold', xaxis.rot = 0,
yaxis.rot = 0, xaxis.tck = c(1, 0), yaxis.tck = 1, layout = NULL, as.table = FALSE, x.spacing = 0, y.spacing = 0,
x.relation = 'same', y.relation = 'same', top.padding = 0.5, bottom.padding = 2, right.padding = 1,
left.padding = 2, ylab.axis.padding = 0, add.text = FALSE, text.labels = NULL, text.x = NULL, text.y = NULL,
text.anchor = 'centre', text.col = 'black', text.cex = 1, text.fontface = 'bold',
key = NULL, legend = NULL, strip.col = 'white', strip.cex = 1, strip.fontface = 'bold',
line.func = NULL, line.from = 0, line.to = 0, line.col = 'transparent', line.infront = TRUE,
height = 6, width = 6, size.units = 'in', resolution = 1600, enable.warnings = FALSE,
description = 'Created with BoutrosLab.plotting.general', style = 'BoutrosLab', preload.default = 'custom',
use.legacy.settings = FALSE, disable.factor.sorting = FALSE
) {
parsed.formula <- unlist(strsplit(deparse(formula), ' [~|] '));
formula.is.split <- '|' %in% all.names(formula);
rectangle.info <- list(
xright = xright.rectangle,
xleft = xleft.rectangle,
ytop = ytop.rectangle,
ybottom = ybottom.rectangle
);
points.info <- list(
pch = points.pch,
col = points.col,
cex = points.cex,
alpha = points.alpha,
groups = if (formula.is.split) { data[, parsed.formula[2]]; } else { NULL; }
);
text.info <- list(
labels = text.labels,
x = text.x,
y = text.y,
anchor = text.anchor,
col = text.col,
cex = text.cex,
fontface = text.fontface
);
out <- prep.axis(
at = xat,
data = unlist(data[toString(formula[[3]])]),
which.arg = 'xat'
);
if (is.list(out)) {
data[toString(formula[[3]])] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
out <- prep.axis(
at = yat,
data = unlist(data[toString(formula[[2]])]),
which.arg = 'yat'
);
if (is.list(out)) {
data[toString(formula[[2]])] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
# add preloaded defaults
if (preload.default == 'paper') {
}
else if (preload.default == 'web') {
}
# parameter check
if (!is.numeric(text.anchor) && !(tolower(text.anchor) %in% c('centre', 'center', 'left', 'right'))) {
stop("Argument 'text.anchor' must be either numeric or one of 'left', 'right', and 'centre'.");
}
# Sort out text.anchor parameter
# if left/right aligned, set text parameter adj to 0/1.
if ('centre' == tolower(text.anchor) || 'center' == tolower(text.anchor)) {
text.anchor <- 0.5;
}
else if ('left' == tolower(text.anchor)) {
text.anchor <- 0;
}
else if ('right' == tolower(text.anchor)) {
text.anchor <- 1;
}
# add stripplot if requested
if (add.stripplot & outliers) {
outliers <- FALSE;
}
# check class of conditioning variable
if (formula.is.split) {
variable <- sub('^\\s+', '', unlist(strsplit(toString(formula[length(formula)]), '\\|'))[2]);
if (variable %in% names(data)) {
cond.class <- class(data[, variable]);
if (cond.class %in% c('integer', 'numeric')) {
warning(
'Numeric values detected for conditional variable. If text labels are desired, please convert conditional variable to character.'
);
}
rm(cond.class);
}
}
# Now make the actual plot object
trellis.object <- lattice::bwplot(
x = formula,
data,
panel = function(subscripts, ...) {
# add stripplot in background if requested
if (add.stripplot) {
panel.stripplot(
jitter.data = TRUE,
factor = jitter.factor,
amount = jitter.amount,
pch = points.info$pch,
col = points.info$col,
groups = points.info$groups,
subscripts = if (!is.null(points.info$groups)) { subscripts; } else { NULL; },
cex = points.info$cex,
alpha = points.info$alpha,
...
);
}
# if requested add user defined rectangle
if (add.rectangle) {
panel.rect(
xleft = rectangle.info$xleft,
ybottom = rectangle.info$ybottom,
xright = rectangle.info$xright,
ytop = rectangle.info$ytop,
col = col.rectangle,
alpha = alpha.rectangle,
border = NA
);
}
# create box plot
panel.bwplot(pch = '|', col = 'black', ...);
# add line if requested (behind)
if (length(line.func) > 0 && line.infront == FALSE) {
panel.curve(expr = line.func, from = line.from, to = line.to, col = line.col);
}
# add ablines
panel.abline(h = abline.h, lty = abline.lty, lwd = abline.lwd, col = abline.col);
panel.abline(v = abline.v, lty = abline.lty, lwd = abline.lwd, col = abline.col);
# else add line in front if requested
if (length(line.func) > 0 && line.infront == TRUE) {
panel.curve(expr = line.func, from = line.from, to = line.to, col = line.col);
}
# Add text to plot
if (add.text) {
which.packet <- parent.frame(2)$which.packet;
panel.text(
x = text.info$x,
y = text.info$y,
labels = text.info$labels[which.packet],
col = text.info$col,
cex = text.info$cex,
fontface = text.info$fontface,
adj = text.info$anchor
);
}
# Add pvalues if requested
},
fill = grDevices::adjustcolor(col, alpha),
main = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = main,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
cex = main.cex,
adj = 0,
just = main.just,
x = main.x,
y = main.y
)
),
# Workaround so that setting yaxis.lab = NULL will remove the yaxis label
# https://github.com/deepayan/lattice/issues/26
default.scales = list(
x = list(
labels = xaxis.lab
),
y = list(
labels = yaxis.lab
)
),
xlab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.label,
cex = xlab.cex,
col = xlab.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' }
)
),
xlab.top = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.top.label,
cex = xlab.top.cex,
col = xlab.top.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
just = xlab.top.just,
x = xlab.top.x,
y = xlab.top.y
)
),
ylab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = ylab.label,
cex = ylab.cex,
col = ylab.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' }
)
),
between = list(
x = x.spacing,
y = y.spacing
),
scales = list(
x = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
rot = xaxis.rot,
limits = xlimits,
cex = xaxis.cex,
col = xaxis.col,
at = xat,
relation = x.relation,
tck = xaxis.tck,
fontface = if ('Nature' == style) { 'plain' } else { xaxis.fontface }
)
),
y = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
rot = yaxis.rot,
limits = ylimits,
cex = yaxis.cex,
col = yaxis.col,
tck = yaxis.tck,
at = yat,
relation = y.relation,
fontface = if ('Nature' == style) { 'plain' } else { yaxis.fontface }
)
),
alternating = 1
),
par.settings = list(
axis.line = list(
lwd = lwd,
col = if ('Nature' == style) { 'transparent' } else { 'black' }
),
layout.heights = list(
top.padding = top.padding,
main = if (is.null(main)) { 0.3 } else { 1 },
main.key.padding = 0.1,
key.top = 0.1,
key.axis.padding = 0.1,
axis.top = 0.7,
axis.bottom = 1.0,
axis.xlab.padding = 0.1,
xlab = 1,
xlab.key.padding = 0.5,
key.bottom = 0.1,
key.sub.padding = 0.1,
sub = 0.1,
bottom.padding = bottom.padding
),
layout.widths = list(
left.padding = left.padding,
key.left = 0,
key.ylab.padding = 0.3,
ylab = 1,
ylab.axis.padding = ylab.axis.padding,
axis.left = 1,
axis.panel = 0.3,
strip.left = 0.3,
panel = 1,
between = 1,
axis.right = 1,
axis.key.padding = 1,
key.right = 1,
right.padding = right.padding
),
box.dot = list(
pch = 19,
col = border.col,
lty = 1
),
box.rectangle = list(
lwd = lwd,
col = border.col,
lty = 1
),
box.umbrella = list(
lwd = lwd,
col = border.col,
lty = 1
),
plot.symbol = list(
col = border.col,
pch = 19,
cex = symbol.cex
),
strip.background = list(
col = strip.col
)
),
par.strip.text = list(
cex = strip.cex,
fontface = strip.fontface
),
do.out = outliers,
layout = layout,
as.table = as.table,
pretty = TRUE,
key = key,
legend = legend,
box.ratio = box.ratio
);
if (disable.factor.sorting == TRUE) {
sorting.param <- '';
if (is.factor(trellis.object$panel.args[[1]][['y']])) {
sorting.param <- 'y';
if (is.null(trellis.object$y.scales$labels) || (is.logical(trellis.object$y.scales$labels[1]) && trellis.object$y.scales$labels[1] == TRUE)) {
default.labels <- unique(as.character(trellis.object$panel.args[[1]][[sorting.param]]));
trellis.object$y.scales$labels <- default.labels;
}
}
else {
sorting.param <- 'x';
if (is.null(trellis.object$x.scales$labels) || (is.logical(trellis.object$x.scales$labels[1]) && trellis.object$x.scales$labels[1] == TRUE)) {
default.labels <- unique(as.character(trellis.object$panel.args[[1]][[sorting.param]]));
trellis.object$x.scales$labels <- default.labels;
}
}
unique.mapping <- list();
count <- 1;
for (x in trellis.object$panel.args[[1]][[sorting.param]]) {
if (is.null(unique.mapping[[as.character(x)]])) {
unique.mapping[as.character(x)] <- count;
count <- count + 1;
}
}
temp.data <- as.character(trellis.object$panel.args[[1]][[sorting.param]]);
for (x in 1:length(temp.data)) {
temp.data[x] <- as.character(unique.mapping[as.character(trellis.object$panel.args[[1]][[sorting.param]][[x]])][[1]]);
}
trellis.object$panel.args[[1]][[sorting.param]] <- as.numeric(temp.data);
}
# reorder by median
if (sample.order == 'increasing' | sample.order == 'decreasing') {
if (is.numeric(trellis.object$panel.args[[1]]$x)) {
num.boxes <- levels(trellis.object$panel.args[[1]]$y);
values.to.sort.by <- NULL;
# create a list of values to sort by for each box
for (i in c(1:length(num.boxes))) {
if (order.by == 'median') {
values.to.sort.by[i] <- median(trellis.object$panel.args[[1]]$x[trellis.object$panel.args[[1]]$y == num.boxes[[i]]]);
}
else if (order.by == 'mean') {
values.to.sort.by[i] <- mean(trellis.object$panel.args[[1]]$x[trellis.object$panel.args[[1]]$y == num.boxes[[i]]]);
}
else if (order.by == 'min') {
values.to.sort.by[i] <- min(trellis.object$panel.args[[1]]$x[trellis.object$panel.args[[1]]$y == num.boxes[[i]]]);
}
else if (order.by == 'max') {
values.to.sort.by[i] <- max(trellis.object$panel.args[[1]]$x[trellis.object$panel.args[[1]]$y == num.boxes[[i]]]);
}
}
ranks <- rank(values.to.sort.by, ties.method = 'random');
# swap the rankings if decreasing order is specified
if (sample.order == 'decreasing') { ranks <- rank(values.to.sort.by * ( -1 ), ties.method = 'random'); }
newlocations <- NULL;
# create a list of the newlocations each box 'level' will appear
for (i in c(1:length(num.boxes))) {
newlocations[[i]] <- grep(num.boxes[i], trellis.object$panel.args[[1]]$y);
}
# replace the old values of the level with the new one based on rank
for (i in c(1:length(num.boxes))) {
trellis.object$panel.args[[1]]$y[newlocations[[i]]] <- num.boxes[ranks[i]];
}
# if labels were not specified reorder the default ones
if (length(yaxis.lab) == 1 && yaxis.lab) {
for (i in c(1:length(num.boxes))) {
trellis.object$y.scales$labels[ranks[i]] <- num.boxes[i];
}
}
else {
newlabels <- NULL;
for (i in c(1:length(num.boxes))) {
newlabels[ranks[i]] <- trellis.object$y.scales$labels[i];
}
trellis.object$y.scales$labels <- newlabels;
warning('WARNING: the label order you specified has been reordered.');
}
}
else {
num.boxes <- levels(trellis.object$panel.args[[1]]$x);
values.to.sort.by <- NULL;
# create a list of the values to sort by for each box
for (i in c(1:length(num.boxes))) {
if (order.by == 'median') {
values.to.sort.by[i] <- median(trellis.object$panel.args[[1]]$y[trellis.object$panel.args[[1]]$x == num.boxes[[i]]]);
}
else if (order.by == 'mean') {
values.to.sort.by[i] <- mean(trellis.object$panel.args[[1]]$y[trellis.object$panel.args[[1]]$x == num.boxes[[i]]]);
}
else if (order.by == 'min') {
values.to.sort.by[i] <- min(trellis.object$panel.args[[1]]$y[trellis.object$panel.args[[1]]$x == num.boxes[[i]]]);
}
else if (order.by == 'max') {
values.to.sort.by[i] <- max(trellis.object$panel.args[[1]]$y[trellis.object$panel.args[[1]]$x == num.boxes[[i]]]);
}
}
ranks <- rank(values.to.sort.by, ties.method = 'random');
if (sample.order == 'decreasing') { ranks <- rank(values.to.sort.by * (-1), ties.method = 'random'); }
newlocations <- NULL;
for (i in c(1:length(num.boxes))) {
newlocations[[i]] <- grep(num.boxes[i], trellis.object$panel.args[[1]]$x);
}
for (i in c(1:length(num.boxes))) {
trellis.object$panel.args[[1]]$x[newlocations[[i]]] <- num.boxes[ranks[i]];
}
if (length(xaxis.lab) == 1 && xaxis.lab) {
for (i in c(1:length(num.boxes))) {
trellis.object$x.scales$labels[ranks[i]] <- num.boxes[i];
}
}
else {
newlabels <- NULL;
for (i in c(1:length(num.boxes))) {
newlabels[ranks[i]] <- trellis.object$x.scales$labels[i];
}
trellis.object$x.scales$labels <- newlabels;
warning('WARNING: the label order you specified has been reordered.');
}
}
}
# If Nature style requested, change figure accordingly
if ('Nature' == style) {
# Re-add bottom and left axes
trellis.object$axis <- function(side, line.col = 'black', ...) {
# Only draw axes on the left and bottom
if (side %in% c('bottom', 'left')) {
axis.default(side = side, line.col = 'black', ...);
lims <- current.panel.limits();
panel.abline(h = lims$ylim[1], v = lims$xlim[1]);
}
}
# Ensure sufficient resolution for graphs
if (resolution < 1200) {
resolution <- 1200;
warning('Setting resolution to 1200 dpi.');
}
# Other required changes which are not accomplished here
warning('Nature also requires italicized single-letter variables and en-dashes
for ranges and negatives. See example in documentation for how to do this.');
warning('Avoid red-green colour schemes, create TIFF files, do not outline the figure or legend.');
}
# Otherwise use the BL style if requested
else if ('BoutrosLab' == style) {
# Nothing happens
}
else {
warning("The style parameter only accepts 'Nature' or 'BoutrosLab'.");
}
# output the object
return(
BoutrosLab.plotting.general::write.plot(
trellis.object = trellis.object,
filename = filename,
height = height,
width = width,
size.units = size.units,
resolution = resolution,
enable.warnings = enable.warnings,
description = description
)
);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/create.boxplot.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO CREATE COLOURKEYS #################################################################
create.colourkey <- create.colorkey <- function(
x, scale.data = FALSE, colour.scheme = c(), total.colours = 99, colour.centering.value = 0,
colour.alpha = 1, fill.colour = 'darkgray', at = NULL, colourkey.labels.at = NULL,
colourkey.labels = colourkey.labels.at, colourkey.labels.cex = 1, placement = NULL
) {
### SUBSET DATA ###############################################################################
# Scale the data if necessary
if (scale.data) {
x <- t(x);
x <- scale(x);
x <- t(x);
}
### AUTOMATIC COLOUR-KEY HANDLING #############################################################
# work out data ranges, break point locations, and colour-number from input parameters
if (is.null(at)) {
min.value <- min(x - colour.centering.value, na.rm = TRUE);
max.value <- max(x - colour.centering.value, na.rm = TRUE);
at <- seq(from = min.value, to = max.value, length.out = total.colours);
}
else {
min.value <- min(at - colour.centering.value, na.rm = TRUE);
max.value <- max(at - colour.centering.value, na.rm = TRUE);
max.at <- max(at);
min.at <- min(at);
if (max(x, na.rm = TRUE) > max.at) {
warning(
paste(
'max(x) =',
max(x, na.rm = TRUE),
'is greater than max(at) = ',
max.at,
'Clipped data will be plotted'
)
);
x[x > max.at] <- max(at);
}
if (min(x, na.rm = TRUE) < min.at) {
warning(
paste(
'min(x) =',
min(x, na.rm = TRUE),
'is greater than min(at) = ',
min.at,
'Clipped data will be plotted'
)
);
x[x < min.at] <- min(at);
}
total.colours <- max(length(at), total.colours);
}
# determine whether the data is one-sided or two-sided
is.twosided <- sign(min.value) != sign(max.value);
# colour-handling: use a default colour scheme if one was not provided
if (0 == length(colour.scheme)) {
if (is.twosided) {
colour.scheme <- c('red', 'white', 'blue');
}
else {
colour.scheme <- c('white', 'blue');
}
}
# colour-handling: first handle legacy cases
if (1 == length(colour.scheme)) {
if (colour.scheme == 'RedWhiteBlue') { colour.scheme <- c('red', 'white', 'blue'); }
else if (colour.scheme == 'WhiteBlack') { colour.scheme <- c('white', 'black'); }
else if (colour.scheme == 'BlueWhiteYellow') { colour.scheme <- c('blue', 'white', 'yellow'); }
else { stop('Unknown colour scheme:', colour.scheme); }
}
# colour-handling: next cover one-sided colour schemes
if (2 == length(colour.scheme)) {
colour.function <- colorRamp(colour.scheme, space = 'Lab');
my.palette <- rgb(colour.function(seq(0, 1, 1 / total.colours) ^ colour.alpha), maxColorValue = 255);
}
# colour-handling: then handle two-sided colour schemes
if (3 == length(colour.scheme)) {
# warn the user if they try to use a three-colour scheme with one-sided data
if (!is.twosided) { warning('Using a three-colour scheme with one-sided data is not advised!'); }
# create the colour scheme
colour.function.low <- colorRamp(colour.scheme[1 : 2], space = 'Lab');
colour.function.high <- colorRamp(colour.scheme[2 : 3], space = 'Lab');
# the number of negative colours is based on the fraction of the range that's below the center value
# the number of positive colours is based on the number of negatives
# leave one colour free for the center value
neg.colours <- min.value / (max.value - min.value) * (total.colours - 1);
neg.colours <- ceiling(abs(neg.colours));
pos.colours <- total.colours - neg.colours - 1;
# there is a potential for the colour allocation to go wrong when:
# 1) we have one-sided data
# 2) the colour-centering is at zero
# 3) a three-colour scheme is requested
# We try to automatically detect this case and provide a fix
if (neg.colours < 1 | pos.colours < 1) {
warning('Colour allocation scheme failed, moving to a default method');
neg.colours <- round(total.colours / 2);
pos.colours <- round(total.colours / 2);
}
# create the colour palette
my.palette <- c(
rgb( colour.function.low(seq(0, 1, 1 / neg.colours) ^ colour.alpha), maxColorValue = 255),
# this helps ensure that the values are centered properly
colour.scheme[2],
rgb( colour.function.high(seq(0, 1, 1 / pos.colours) ^ (1 / colour.alpha)), maxColorValue = 255)
);
}
# allow colour-schemes with > 3 colours
if (3 < length(colour.scheme)) {
# only allow this behaviour with at-colour-type-handling
if (is.null(at)) { stop('>3-colour schemes only work when at is specified'); }
# create the colour scheme
my.palette <- c(colour.scheme);
}
# colour-handling: lastly ensure that a palette was defined somehow
if (!exists('my.palette')) {
stop('Somehow no palette was ever defined');
}
# create the colour-key
colour.key <- draw.colorkey(
key = list(
space = 'bottom',
size = 1,
width = 1,
height = 1,
at = at,
col = my.palette,
labels = list(
cex = colourkey.labels.cex,
at = colourkey.labels.at,
labels = colourkey.labels,
fontface = 'bold'
),
tick.number = 3
),
vp = placement,
draw = TRUE
);
# output the object
return(colour.key);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/create.colourkey.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO CREATE DENDROGRAM ##################################################################
create.dendrogram <- function(
x, clustering.method = 'diana', cluster.dimension = 'col', distance.method = 'correlation',
cor.method = 'pearson', force.clustering = FALSE, same.as.matrix = FALSE
) {
if (same.as.matrix) {
x <- t(apply(x, 2, rev));
}
# This function will create a dendrogram using either row-wise or column-wise clustering
# It is called from the create.heatmap function when clustering is required and no dendrograms are provided
# verify proper input formatting
if (length(cluster.dimension) > 1) { stop('Only handles one cluster dimension at a time.'); }
# initialize variable to store dendrogram
dd <- 0;
# initialize variable to store distance matrix
distance.matrix <- 0;
# Perform column-wise or row-wise clustering as requested
if (cluster.dimension %in% c('col', 'column', 'cols', 'columns')) {
# Don't bother trying to cluster if the dimension is too large
if (dim(x)[2] > 6000 && !force.clustering) {
stop('Unclusterable matrix: dim(data.cluster)[2] = ', dim(x)[2]);
}
# Create dissimilarity matrix
if ('correlation' == distance.method) {
distance.matrix <- as.dist(1 - cor(x, use = 'pairwise', method = cor.method));
}
else if (distance.method %in% c('euclidean', 'maximum', 'manhattan', 'canberra', 'binary', 'minkowski', 'jaccard')) {
distance.matrix <- dist(t(x), method = distance.method);
}
else {
stop('Unknown distance.method: ', distance.method);
}
}
else if (cluster.dimension %in% c('row', 'rows')) {
# Don't bother trying to cluster if the dimension is too large
if (dim(x)[1] > 6000 && !force.clustering) {
stop('Unclusterable matrix: dim(data.cluster)[1] = ', dim(x)[1]);
}
# Create dissimilarity matrix
if ('correlation' == distance.method) {
distance.matrix <- as.dist(1 - cor(t(x), use = 'pairwise', method = cor.method));
}
else if (distance.method %in% c('euclidean', 'maximum', 'manhattan', 'canberra', 'binary', 'minkowski', 'jaccard')) {
distance.matrix <- dist(x, method = distance.method);
}
else {
stop('Unknown distance.method: ', distance.method);
}
}
else {
# throw an error if we are asked to compute a dendrogram that is not by row or column
stop('Unknown cluster.dimension for create.dendrogram: ', cluster.dimension);
}
# make sure this is a clusterable matrix
if (any(is.na(distance.matrix))) {
stop('Unclusterable matrix: some distances are NULL or NA.');
}
# now handle all possible clustering methods using the distance matrix
if ('diana' == clustering.method) {
dd <- as.dendrogram(as.hclust(diana(x = distance.matrix)));
}
else if (clustering.method %in% c('ward', 'ward.D', 'ward.D2', 'single', 'complete', 'average', 'mcquitty', 'median', 'centroid')) {
dd <- as.dendrogram(hclust(d = distance.matrix, method = clustering.method));
}
else {
stop('Unknown clustering method: ', clustering.method);
}
# Return the dendrogram created
return(dd);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/create.dendrogram.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO CREATE DENSITYPLOTS ################################################################
create.densityplot <- function(
x, filename = NULL, main = NULL, main.just = 'center', main.x = 0.5, main.y = 0.5, main.cex = 3,
xlab.label = NULL, ylab.label = 'Density', xlab.cex = 2, ylab.cex = 2, xlab.col = 'black', ylab.col = 'black',
xlab.top.label = NULL, xlab.top.cex = 2, xlab.top.col = 'black', xlab.top.just = 'center', xlab.top.x = 0.5,
xlab.top.y = 0, type = 'l', lty = 'solid', cex = 0.75, pch = 19, col = 'black', lwd = 2, bandwidth = 'nrd0',
bandwidth.adjust = 1, xlimits = NULL, ylimits = NULL, xat = TRUE, yat = TRUE, xaxis.lab = NA, yaxis.lab = NA,
xaxis.cex = 1.5, yaxis.cex = 1.5, xaxis.rot = 0, yaxis.rot = 0, xaxis.col = 'black', yaxis.col = 'black',
xaxis.fontface = 'bold', yaxis.fontface = 'bold', xaxis.tck = 1, yaxis.tck = 1, xgrid.at = xat,
ygrid.at = yat, key = list(text = list(lab = c(''))), legend = NULL, top.padding = 0.1, bottom.padding = 0.7,
left.padding = 0.5, right.padding = 0.1, add.axes = FALSE, abline.h = NULL, abline.v = NULL, abline.lty = NULL,
abline.lwd = NULL, abline.col = 'black', add.rectangle = FALSE, xleft.rectangle = NULL,
ybottom.rectangle = NULL, xright.rectangle = NULL, ytop.rectangle = NULL, col.rectangle = 'transparent',
alpha.rectangle = 1, add.text = FALSE, text.labels = NULL, text.x = NULL, text.y = NULL, text.anchor = 'centre', text.col = 'black',
text.cex = 1, text.fontface = 'bold', height = 6, width = 6, size.units = 'in', resolution = 1600, enable.warnings = FALSE,
description = 'Created with BoutrosLab.plotting.general', style = 'BoutrosLab', preload.default = 'custom', use.legacy.settings = FALSE,
inside.legend.auto = FALSE
) {
### needed to copy in case using variable to define rectangles dimensions
rectangle.info <- list(
xright = xright.rectangle,
xleft = xleft.rectangle,
ytop = ytop.rectangle,
ybottom = ybottom.rectangle
);
text.info <- list(
labels = text.labels,
x = text.x,
y = text.y,
col = text.col,
cex = text.cex,
fontface = text.fontface,
anchor = text.anchor
);
if (!is.null(yat) && length(yat) == 1) {
if (yat == 'auto') {
out <- auto.axis(unlist(x[[1]]));
x[[1]] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
else if (yat == 'auto.linear') {
out <- auto.axis(unlist(x[[1]]), log.scaled = FALSE);
x[[1]] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
else if (yat == 'auto.log') {
out <- auto.axis(unlist(x[[1]]), log.scaled = TRUE);
x[[1]] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
}
if (!is.null(xat) && length(xat) == 1) {
if (xat == 'auto') {
out <- auto.axis(unlist(x[[2]]));
x[[2]] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
else if (xat == 'auto.linear') {
out <- auto.axis(unlist(x[[2]]), log.scaled = FALSE);
x[[2]] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
else if (xat == 'auto.log') {
out <- auto.axis(unlist(x[[2]]), log.scaled = TRUE);
x[[2]] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
}
# add preloaded defaults
if (preload.default == 'paper') {
}
else if (preload.default == 'web') {
}
# create an object to store all the data
data.to.plot <- data.frame(
x = rep(0, 512 * length(x)),
y = rep(0, 512 * length(x)),
groups = rep(NA, 512 * length(x))
);
for (i in 1:length(x)) {
this.density <- density(
x[[i]],
bw = bandwidth,
adjust = bandwidth.adjust,
na.rm = TRUE
);
start.point <- 1 + (i - 1) * 512;
end.point <- start.point + 512 - 1;
data.to.plot$x[start.point:end.point] <- this.density$x;
data.to.plot$y[start.point:end.point] <- this.density$y;
data.to.plot$groups[start.point:end.point] <- rep(names(x)[i], 512);
}
# avoid groups being plotted in alphabetical factor order.
# this seems to cause disjoint with other parameters like col
data.to.plot$groups <- factor(
data.to.plot$groups,
levels = unique(data.to.plot$groups)
);
if (length(yat) == 1 && yat == TRUE && length(ylimits) == 0) {
maximum <- max(data.to.plot$y);
# if minimum is greater than 0 make sure to display 0
lognumber <- floor(log(maximum, 10));
# depending on difference, the labels will be multiples of 5,10 or 20
if (maximum < (10 ** lognumber * 4)) { factor <- (10 ** lognumber) / 2; }
else if (maximum < (10 ** lognumber * 7)) { factor <- (10 ** lognumber); }
else { factor <- (10 ** lognumber) * 2; }
addition <- factor / 2;
# depending on minimum create a sequence of at locations with padding
at <- seq(0, factor * round(maximum / factor) + addition, factor);
maximum <- maximum + addition;
ylimits <- c(0, maximum);
yat <- at;
}
if (length(xat) == 1 && xat == TRUE && length(xlimits) == 0) {
minimum <- min(data.to.plot$x);
maximum <- max(data.to.plot$x);
# if minimum is greater than 0 make sure to display 0
minimum <- min(minimum, 0);
difference <- maximum - minimum;
lognumber <- floor(log(difference, 10));
# depending on difference, the labels will be multiples of 5,10 or 20
if (difference < (10 ** lognumber * 4)) { factor <- (10 ** lognumber) / 2; }
else if (difference < (10 ** lognumber * 7)) { factor <- (10 ** lognumber); }
else { factor <- (10 ** lognumber) * 2; }
addition <- factor / 2;
# depending on minimum create a sequence of at locations with padding
if (minimum == 0) { at <- seq(0, factor * round(maximum / factor) + addition, factor); }
else {
at <- seq(factor * round(minimum / factor), factor * round(maximum / factor) + addition, factor);
# only add padding to minium if it is not 0
minimum <- minimum - addition;
}
# add padding to max
maximum <- maximum + addition;
xlimits <- c(minimum, maximum);
xat <- at;
}
# create the plot
trellis.object <- lattice::xyplot(
y ~ x,
data.to.plot,
panel = function(groups.local = data.to.plot$groups, subscripts, type.local = type, ...) {
# add rectangle
if (add.rectangle) {
panel.rect(
xleft = rectangle.info$xleft,
ybottom = rectangle.info$ybottom,
xright = rectangle.info$xright,
ytop = rectangle.info$ytop,
col = col.rectangle,
alpha = alpha.rectangle,
border = NA
);
}
panel.abline(h = abline.h, lty = abline.lty, lwd = abline.lwd, col = abline.col);
panel.abline(v = abline.v, lty = abline.lty, lwd = abline.lwd, col = abline.col);
# Add text to plot
if (add.text) {
panel.text(
x = text.info$x,
y = text.info$y,
labels = text.info$labels,
col = text.info$col,
cex = text.info$cex,
fontface = text.info$fontface,
adj = text.info$anchor
);
}
# if requested, add x=0, y=0 lines
if (add.axes) {
panel.abline(
h = 0,
v = 0,
col.line = 'black',
lty = 'dashed',
lwd = 1.5
);
}
# if grid-lines are requested, over-ride default behaviour
if ('g' %in% type) {
panel.abline(
v = BoutrosLab.plotting.general::generate.at.final(
at.input = xgrid.at,
limits = xlimits,
data.vector = data.to.plot$x
),
h = BoutrosLab.plotting.general::generate.at.final(
at.input = ygrid.at,
limits = ylimits,
data.vector = data.to.plot$y
),
col = trellis.par.get('reference.line')$col
);
panel.xyplot(
groups = groups.local,
grid = FALSE,
subscripts = subscripts,
type = setdiff(type.local, 'g'),
...
);
}
# create the main plot
panel.xyplot(
groups = groups.local,
subscripts = subscripts,
type = setdiff(type.local, 'g'),
...
);
},
type = type,
lwd = lwd,
lty = lty,
col = col,
main = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = main,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
cex = main.cex,
just = main.just,
x = main.x,
y = main.y
)
),
xlab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.label,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
cex = xlab.cex,
col = xlab.col
)
),
xlab.top = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.top.label,
cex = xlab.top.cex,
col = xlab.top.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
just = xlab.top.just,
x = xlab.top.x,
y = xlab.top.y
)
),
ylab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = ylab.label,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
cex = ylab.cex,
col = ylab.col
)
),
scales = list(
x = get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
cex = xaxis.cex,
rot = xaxis.rot,
col = xaxis.col,
fontface = if ('Nature' == style) { 'plain' } else { xaxis.fontface },
limits = xlimits,
axs = 'r',
at = xat,
tck = xaxis.tck,
labels = xaxis.lab
)
),
y = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
cex = yaxis.cex,
rot = yaxis.rot,
col = yaxis.col,
fontface = if ('Nature' == style) { 'plain' } else { yaxis.fontface },
limits = ylimits,
at = yat,
tck = xaxis.tck,
labels = yaxis.lab
)
)
),
key = key,
legend = legend,
par.settings = list(
axis.line = list(
lwd = 2.25,
col = if ('Nature' == style) { 'transparent' } else { 'black' }
),
layout.heights = list(
top.padding = top.padding,
main = if (is.null(main)) { 0.3 } else { 1 },
main.key.padding = 0.1,
key.top = 0.1,
key.axis.padding = 0.1,
axis.top = 1,
axis.bottom = 1,
axis.xlab.padding = 1,
xlab = 1,
xlab.key.padding = 0.5,
key.bottom = 0.1,
key.sub.padding = 0.1,
sub = 0.1,
bottom.padding = bottom.padding
),
layout.widths = list(
left.padding = left.padding,
key.left = 0.1,
key.ylab.padding = 0.1,
ylab = 1,
ylab.axis.padding = 1,
axis.left = 1,
axis.right = 1,
axis.key.padding = 0.1,
key.right = 0.1,
right.padding = right.padding
)
)
);
if (inside.legend.auto) {
extra.parameters <- list('data' = data.to.plot, 'ylimits' = trellis.object$y.limits, 'xlimits' = trellis.object$x.limits);
coords <- c();
coords <- .inside.auto.legend('create.densityplot', filename, trellis.object, height, width, extra.parameters);
trellis.object$legend$inside$x <- coords[1];
trellis.object$legend$inside$y <- coords[2];
}
# If Nature style requested, change figure accordingly
if ('Nature' == style) {
# Re-add bottom and left axes
trellis.object$axis <- function(side, line.col = 'black', ...) {
# Only draw axes on the left and bottom
if (side %in% c('bottom', 'left')) {
axis.default(side = side, line.col = 'black', ...);
lims <- current.panel.limits();
panel.abline(h = lims$ylim[1], v = lims$xlim[1]);
}
}
# Ensure sufficient resolution for graphs
if (resolution < 1200) {
resolution <- 1200;
warning('Setting resolution to 1200 dpi.');
}
# Other required changes which are not accomplished here
warning('Nature also requires italicized single-letter variables and en-dashes
for ranges and negatives. See example in documentation for how to do this.');
warning('Avoid red-green colour schemes, create TIFF files, do not outline the figure or legend.');
}
# Otherwise use the BL style if requested
else if ('BoutrosLab' == style) {
# Nothing happens
}
# if neither of the above is requested, give a warning
else {
warning("The style parameter only accepts 'Nature' or 'BoutrosLab'.");
}
# output the object
return(
BoutrosLab.plotting.general::write.plot(
trellis.object = trellis.object,
filename = filename,
height = height,
width = width,
size.units = size.units,
resolution = resolution,
enable.warnings = enable.warnings,
description = description
)
);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/create.densityplot.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2013 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO CREATE DOTMAPS #####################################################################
create.dotmap <- function(x, bg.data = NULL, filename = NULL, main = NULL, main.just = 'center',
main.x = 0.5, main.y = 0.5, pch = 19, pch.border.col = 'black', add.grid = TRUE, xaxis.lab = colnames(x),
yaxis.lab = rownames(x), xaxis.rot = 0, yaxis.rot = 0, main.cex = 3, xlab.cex = 2, ylab.cex = 2,
xlab.label = NULL, ylab.label = NULL, xlab.col = 'black', ylab.col = 'black', xlab.top.label = NULL,
xlab.top.cex = 2, xlab.top.col = 'black', xlab.top.just = 'center', xlab.top.x = 0.5, xlab.top.y = 0,
xaxis.cex = 1.5, yaxis.cex = 1.5, xaxis.col = 'black', yaxis.col = 'black', xaxis.tck = 1, yaxis.tck = 1,
axis.top = 1, axis.bottom = 1, axis.left = 1, axis.right = 1, top.padding = 0.1, bottom.padding = 0.7,
right.padding = 0.1, left.padding = 0.5, key.ylab.padding = 0.1, key = list(text = list(lab = c(''))), legend = NULL, col.lwd = 1.5,
row.lwd = 1.5, spot.size.function = 'default', spot.colour.function = 'default', na.spot.size = 7,
na.pch = 4, na.spot.size.colour = 'black', grid.colour = NULL, colour.scheme = 'white', total.colours = 99,
at = NULL, colour.centering.value = 0, colourkey = FALSE, colourkey.labels.at = NULL,
colourkey.labels = NULL, colourkey.cex = 1, colour.alpha = 1, bg.alpha = 0.5, fill.colour = 'white',
key.top = 0.1, height = 6, width = 6, size.units = 'in', resolution = 1600, enable.warnings = FALSE,
col.colour = 'black', row.colour = 'black', description = 'Created with BoutrosLab.plotting.general',
add.rectangle = FALSE, xleft.rectangle = NULL, ybottom.rectangle = NULL, xright.rectangle = NULL,
ytop.rectangle = NULL, col.rectangle = 'transparent', border.rectangle=NULL, lwd.rectangle = NULL,
alpha.rectangle = 1, xaxis.fontface = 'bold', yaxis.fontface = 'bold', dot.colour.scheme = NULL,
style = 'BoutrosLab', preload.default = 'custom', use.legacy.settings = FALSE, remove.symmetric = FALSE, lwd = 2) {
### needed to copy in case using variable to define rectangles dimensions
rectangle.info <- list(
xright = xright.rectangle,
xleft = xleft.rectangle,
ytop = ytop.rectangle,
ybottom = ybottom.rectangle
);
if (preload.default == 'paper') {
}
else if (preload.default == 'web') {
}
data.subset <- TRUE;
if (remove.symmetric == TRUE) {
if (ncol(x) != nrow(x)) {
stop('can only use remove.symmetric with matrices of same length and width');
}
data.subset <- c();
for (i in c(1:nrow(x))) {
for (j in c(1:nrow(x))) {
if(j > i) {
data.subset <- c(data.subset, T);
}
else {
data.subset <- c(data.subset, F);
}
}
}
}
x <- as.data.frame(x);
temp <- x; # 'temp' used for column/row catagorization function
# determine size/colour functions
switch(
as.character(class(spot.size.function)),
'character' = {
if (spot.size.function == 'default') {
spot.size.function <- function(x) { 0.1 + (2 * abs(x)); }
}
},
'numeric' = {
returnval <- spot.size.function;
spot.size.function <- function(x) { returnval; }
}
);
if (as.character(class(spot.colour.function) == 'character')) {
switch(
spot.colour.function,
'default' = {
spot.colour.function <- function(x) {
colours <- rep('white', length(x));
colours[sign(x) == -1] <- BoutrosLab.plotting.general::default.colours(2, palette.type = 'dotmap')[1];
colours[sign(x) == 1] <- BoutrosLab.plotting.general::default.colours(2, palette.type = 'dotmap')[2];
return(colours);
}
},
'discrete' = {
if (length(unique(unlist(x))) > length(dot.colour.scheme)) {
stop(paste('Not enough colours specified to use discrete function: need at least', length(unique(unlist(x))), 'colours'));
}
spot.colour.function <- function(x) {
unique.values <- unique(x);
colours <- rep('white', length(x));
for (i in c(1:length(unique.values))) {
colours[x == unique.values[i]] <- dot.colour.scheme[i];
}
return(colours);
}
},
'columns' = {
spot.colour.function <- function(x) {
# The following does not use the parameter 'x' and instead used the variable 'temp'
no.unique.columns <- length(unique(colnames(temp)));
no.rows <- length(rownames(temp));
# Checks for repeated colnames and throws an error if there is
if (no.unique.columns != length(colnames(temp))) {
stop(paste('Remove repeated column names'));
}
new.colnames <- seq(1, no.unique.columns, 1);
colnames(temp) <- new.colnames;
temp <- stack(temp);
temp$values <- temp$ind;
temp$ind <- NULL;
index <- 1;
colours <- rep('white', no.unique.columns * no.rows);
for (i in c(1:no.unique.columns)) {
for (j in c(1:no.rows)) {
colours[index] <- default.colours(12)[(i %% 12) + 1];
index <- index + 1;
}
}
return(colours);
}
},
'rows' = {
spot.colour.function <- function(x) {
# The following does not use the parameter 'x' and instead used the variable 'temp'
no.columns <- length(colnames(temp));
no.unique.rows <- length(unique(rownames(temp)));
# Checks for repeated rownames and throws an error if there is
if (no.unique.rows != length(rownames(temp))) {
stop(paste('Remove repeated row names'));
}
colour.per.column <- c(1:no.unique.rows);
for (i in 0:no.unique.rows) {
colour.per.column[i + 1] <- default.colours(12)[(i %% 12) + 1];
}
temp <- stack(temp);
temp$ind <- NULL;
index <- 1;
for (i in c(1:no.columns)) {
for (j in c(1:no.unique.rows)) {
temp$values[index] <- colour.per.column[j];
index <- index + 1;
}
}
return(temp);
}
}
);
}
# set spot size/colour
spot.sizes <- spot.size.function(stack(x)$values);
spot.colours <- spot.colour.function(stack(x)$values);
spot.border <- pch.border.col;
# Ensure a bg.data value is provided
if (!is.null(bg.data)) {
if (length(colour.scheme) == 1 && colour.scheme == 'white') {
warning("bg.data is set, but colour.scheme is set to default 'white'. No background colours will be displayed. Changing bg.data to NULL");
bg.data <- NULL;
}
}
if (is.null(bg.data)) {
# Set bg.data to x: Ensures a default value of the correct size
bg.data <- x;
# Ensure 'fake' bg.data values are never displayed
if (colourkey) {
warning('No bg.data set, but colourkey is set to TRUE. Changing colourkey to FALSE');
colourkey <- FALSE;
}
if (length(colour.scheme) != 1 || colour.scheme != 'white') {
warning("No bg.data set, but colour.scheme is set to non-default value. Changing colour.scheme to 'white'.");
colour.scheme <- 'white';
}
}
if (is.null(at)) {
min.value <- min(bg.data - colour.centering.value, na.rm = TRUE);
max.value <- max(bg.data - colour.centering.value, na.rm = TRUE);
at <- seq(from = min.value, to = max.value, length.out = total.colours);
}
else {
min.value <- min(at - colour.centering.value, na.rm = TRUE);
max.value <- max(at - colour.centering.value, na.rm = TRUE);
min.at <- min(at);
max.at <- max(at);
if (min(bg.data, na.rm = TRUE) < min.at) {
warning(
paste(
'min(bg.data) = ',
min(bg.data, na.rm = TRUE),
'is smaller than min(at) = ',
min.at,
'Clipped data will be plotted'
)
);
bg.data[bg.data < min.at] <- min(at);
}
if (max(bg.data, na.rm = TRUE) > max.at) {
warning(
paste(
'max(bg.data) = ',
max(bg.data, na.rm = TRUE),
'is greater than max(at) = ',
max.at,
'Clipped data will be plotted'
)
);
bg.data[bg.data > max.at] <- max(at);
}
total.colours <- max(length(at), total.colours);
}
# change alpha value to work for rgb function
if (bg.alpha <= 1 && bg.alpha >= 0) {
bg.alpha <- bg.alpha * 255;
}
# colour-handling: first handle legacy cases
if (1 == length(colour.scheme)) {
if (colour.scheme == 'RedWhiteBlue') { colour.scheme <- c('red', 'white', 'blue'); }
else if (colour.scheme == 'WhiteBlack') { colour.scheme <- c('white', 'black'); }
else if (colour.scheme == 'BlueWhiteYellow') { colour.scheme <- c('blue', 'white', 'yellow'); }
else if (colour.scheme == 'white') { colour.scheme <- c('white', 'white'); }
else {
warning(paste('Unknown colour scheme:', colour.scheme));
return(0);
}
}
# one-sided colour schemes
if (2 == length(colour.scheme)) {
colour.function <- colorRamp(colour.scheme, space = 'Lab');
my.palette <- rgb(colour.function(seq(0, 1, 1 / total.colours) ^ colour.alpha), alpha = bg.alpha, maxColorValue = 255);
}
# two-sided colour schemes
else if (3 == length(colour.scheme)) {
# warn user if they use three-colour scheme with one-sided data
is.twosided <- sign(min.value) != sign(max.value);
if (!is.twosided) {
warning('Using a three-colour scheme with one-sided data is not advised!');
}
# create colour scheme
colour.function.low <- colorRamp(colour.scheme[1:2], space = 'Lab');
colour.function.high <- colorRamp(colour.scheme[2:3], space = 'Lab');
# The number of negative colours is based on the fraction of the range that's below the center value
# The number of positive colours is based on the number of negatives
# Leave one colour free for the center value
neg.colours <- min.value / (max.value - min.value) * (total.colours - 1);
neg.colours <- ceiling(abs(neg.colours));
pos.colours <- total.colours - neg.colours - 1;
# There is potential for colour allocation to go wrong when:
# 1) There is one-sided data
# 2) The colour-centering is at zero
# 3) A three-colour scheme is requested
# Try to automatically detect this case and provide a fix
if (neg.colours < 1 | pos.colours < 1) {
warning('Colour allocation scheme failed, moving to a default method');
neg.colours <- round(total.colours / 2);
pos.colours <- round(total.colours / 2);
}
# create colour palette
my.palette <- c(
rgb(colour.function.low(seq(0, 1, 1 / neg.colours) ^ colour.alpha), alpha = bg.alpha, maxColorValue = 255),
colour.scheme[2],
rgb(colour.function.high(seq(0, 1, 1 / pos.colours) ^ (1 / colour.alpha)), alpha = bg.alpha, maxColorValue = 255)
);
}
else {
my.palette <- c();
for (n in 1:length(colour.scheme)) {
colour.function <- colorRamp(c('white', colour.scheme[n]), space = 'Lab');
my.palette <- c(my.palette, rgb(colour.function(1 ^ colour.alpha), alpha = bg.alpha, maxColorValue = 255));
}
}
# format bg.data
bg.data <- as.data.frame(bg.data);
# constructing coordinate system
# note that we're forcing the 'natural' ordering of rows here
y.coords <- rep(nrow(x):1, ncol(x));
x.coords <- c();
for (i in 1:ncol(x)) { x.coords <- c(x.coords, rep(i, nrow(x))); }
bg.data <- data.frame(
x = x.coords,
y = y.coords,
freq = stack(bg.data)$values
);
if (colourkey) {
colourkey <- list(
size = 1,
space = 'bottom',
width = 1.25,
height = 1.0,
labels = list(
cex = colourkey.cex,
at = colourkey.labels.at,
labels = colourkey.labels
),
tick.number = 3
);
}
if (!is.null(grid.colour)) {
row.colour <- grid.colour;
col.colour <- grid.colour;
cat(paste0('CAUTION: grid.colour is DEPRECATED! Use row.colour/col.colour. Using: ', grid.colour, '\n'));
}
if (any(is.na(x))) {
tmp.pch <- pch;
pch[is.na(x)] <- na.pch;
pch[!is.na(x)] <- tmp.pch;
spot.colours[is.na(x)] <- na.spot.size.colour;
spot.sizes[is.na(x)] <- na.spot.size;
rm(tmp.pch);
}
if (is.null(lwd.rectangle) & !is.null(border.rectangle)) {
lwd.rectangle <- 1;
}
trellis.object <- lattice::levelplot(
freq ~ x * y,
bg.data,
subset = data.subset,
panel = function(...) {
panel.fill(col = fill.colour);
panel.levelplot(...);
# add rectangle if requested
# if (add.rectangle) {
# panel.rect(
# xleft = xleft.rectangle,
# ybottom = ybottom.rectangle,
# xright = xright.rectangle,
# ytop = ytop.rectangle,
# col = col.rectangle,
# alpha = alpha.rectangle,
# border = ifelse(is.null(border.rectangle),NA,border.rectangle),
# lwd = lwd.rectangle
# );
# }
# add grid if requested
if (add.grid) {
if(remove.symmetric == TRUE) {
for(i in c(1:max(bg.data$y))) {
panel.lines(x = c(0,max(bg.data$x) - (i)) + 0.5, y = i + 0.5, col=col.colour, lwd = col.lwd);
}
for(i in c(1:max(bg.data$x))) {
panel.lines(x = i + 0.5, y = c(0,max(bg.data$y) - (i)) + 0.5, col=row.colour, lwd = row.lwd);
}
}
else {
panel.abline(
h = min(bg.data$y):max(bg.data$y) - 0.5,
v = 0,
col.line = row.colour,
lwd = row.lwd
);
panel.abline(
v = min(bg.data$x):max(bg.data$x) - 0.5,
h = 0,
col.line = col.colour,
lwd = col.lwd
);
}
}
if (add.rectangle) {
panel.rect(
xleft = rectangle.info$xleft,
ybottom = rectangle.info$ybottom,
xright = rectangle.info$xright,
ytop = rectangle.info$ytop,
col = col.rectangle,
alpha = alpha.rectangle,
border = ifelse(is.null(border.rectangle), NA, border.rectangle),
lwd = lwd.rectangle
);
}
# NOTE: different ways to handle border and fill for pch < 21 and pch >= 21
panel.xyplot(
type = 'p',
cex = spot.sizes,
pch = pch,
col = mapply(
function(pch, spot.colours, spot.border) {
if (pch %in% 0:20) { return(spot.colours); } else
if (pch %in% 21:25) { return(spot.border); }
},
pch, spot.colours = spot.colours, spot.border = spot.border
),
fill = mapply(
function(pch, spot.colours) {
if (pch %in% 0:20) { NA; } else
if (pch %in% 21:25) { return(spot.colours); }
},
pch, spot.colours = spot.colours
),
key = key,
legend = legend,
...
);
},
at = at,
key = key,
legend = legend,
col.regions = my.palette,
colorkey = colourkey,
main = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = main,
fontface = if ('Nature' == style) {'plain'} else ('bold'),
cex = main.cex,
just = main.just,
x = main.x,
y = main.y
)
),
xlab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.label,
fontface = if ('Nature' == style) {'plain'} else ('bold'),
cex = xlab.cex,
col = xlab.col
)
),
xlab.top = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.top.label,
cex = xlab.top.cex,
col = xlab.top.col,
fontface = if ('Nature' == style) {'plain'} else {'bold'},
just = xlab.top.just,
x = xlab.top.x,
y = xlab.top.y
)
),
ylab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = ylab.label,
fontface = if ('Nature' == style) {'plain'} else ('bold'),
cex = ylab.cex,
col = ylab.col
)
),
scales = list(
x = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
labels = xaxis.lab,
cex = xaxis.cex,
rot = xaxis.rot,
col = xaxis.col,
tck = xaxis.tck,
limits = c( min(bg.data$x, na.rm = TRUE) - 0.5, max(bg.data$x, na.rm = TRUE) + 0.5 ),
at = min(bg.data$x, na.rm = TRUE):max(bg.data$x, na.rm = TRUE),
fontface = if ('Nature' == style) {'plain'} else (xaxis.fontface)
)
),
y = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
labels = rev(yaxis.lab),
cex = yaxis.cex, # necessary because we forcing the 'natural' ordering of rows when making bg.data
rot = yaxis.rot,
col = yaxis.col,
tck = yaxis.tck,
limits = c( min(bg.data$y, na.rm = TRUE) - 0.5, max(bg.data$y, na.rm = TRUE) + 0.5 ),
at = min(bg.data$y, na.rm = TRUE):max(bg.data$y, na.rm = TRUE),
fontface = if ('Nature' == style) {'plain'} else (yaxis.fontface)
)
)
),
par.settings = list(
axis.line = list(
lwd = lwd,
col = if(remove.symmetric == TRUE) { 'transparent'; } else { 'black'; }
),
layout.heights = list(
top.padding = top.padding,
main = if (is.null(main)) { 0.3} else { 1 },
main.key.padding = 0.1,
key.top = key.top,
key.axis.padding = 0.1,
axis.top = axis.top,
axis.bottom = axis.bottom,
axis.xlab.padding = 1,
xlab = if (is.null(xaxis.lab)) {0.1} else {1},
xlab.key.padding = 0.5,
key.bottom = 1,
key.sub.padding = 0.1,
sub = 0.1,
bottom.padding = bottom.padding
),
layout.widths = list(
left.padding = left.padding,
key.left = 1,
key.ylab.padding = key.ylab.padding,
ylab = if (is.null(yaxis.lab)) {0.1} else {1},
ylab.axis.padding = 1,
axis.left = axis.left,
axis.right = axis.right,
axis.key.padding = 0.1,
key.right = 1,
right.padding = right.padding
)
)
);
if (remove.symmetric == TRUE) {
# Re-add bottom and left axes
trellis.object$axis <- function(side, line.col = 'black', ...) {
# Only draw axes on the left and bottom
if (side %in% c('bottom', 'left')) {
axis.default(side = side, line.col = 'black', ...);
lims <- current.panel.limits();
panel.abline(h = lims$ylim[1], v = lims$xlim[1], lwd = lwd);
}
}
}
# If Nature style requested, change figure accordingly
if ('Nature' == style) {
# Ensure sufficient resolution for graphs
if (resolution < 1200) {
resolution <- 1200;
warning('Setting resolution to 1200 dpi.');
}
# Other required changes which are not accomplished here
warning('Nature also requires italicized single-letter variables and en-dashes
for ranges and negatives. See example in documentation for how to do this.');
warning('Avoid red-green colour schemes, create TIFF files, do not outline the figure or legend');
}
else if ('BoutrosLab' == style) {
# Nothing happens
}
else {
warning("The style parameter only accepts 'Nature' or 'BoutrosLab'.");
}
# output the object
return(
BoutrosLab.plotting.general::write.plot(
trellis.object = trellis.object,
filename = filename,
height = height,
width = width,
size.units = size.units,
resolution = resolution,
enable.warnings = enable.warnings,
description = description
)
);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/create.dotmap.R
|
# The BoutrosLab plotting.general package is copyright (c) 2011 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO CREATE GIF #######################################################################
create.gif <- function(exec.func, parameters, number.of.frames, delay = 40, filename) {
png(filename = 'writeGifTemp%03d.png');
for (i in (1:number.of.frames)) {
print(do.call(exec.func, parameters[[i]]));
}
dev.off();
# convert pngs to one gif using ImageMagick
system(paste(paste('convert -delay ', delay), paste(' writeGifTemp* ', filename)));
# cleaning up
file.remove(list.files(pattern = 'writeGifTemp'));
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/create.gif.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO CREATE HEATMAPS ####################################################################
create.heatmap <- function(x, filename = NULL, clustering.method = 'diana', cluster.dimensions = 'both',
rows.distance.method = 'correlation', cols.distance.method = 'correlation', cor.method = 'pearson',
row.dendrogram = list(), col.dendrogram = list(), plot.dendrograms = 'both', force.clustering = FALSE,
criteria.list = TRUE, covariates = list(), covariates.grid.row = NULL, covariates.grid.col = NULL,
covariates.grid.border = NULL, covariates.row.lines = NULL, covariates.col.lines = NULL,
covariates.reorder.grid.index = FALSE, covariates.padding = 0.25, covariates.top = list(),
covariates.top.grid.row = NULL, covariates.top.grid.col = NULL, covariates.top.grid.border = NULL,
covariates.top.row.lines = NULL, covariates.top.col.lines = NULL, covariates.top.reorder.grid.index = FALSE,
covariates.top.padding = 0.25, covariate.legends = list(), legend.cex = 1, legend.title.cex = 1,
legend.title.just = 'centre', legend.title.fontface = 'bold', legend.border = NULL, legend.border.padding = 1,
legend.layout = NULL, legend.between.col = 1, legend.between.row = 1, legend.side = 'left',
main = list(label = ''), main.just = 'center', main.x = 0.5, main.y = 0.5, main.cex = 3, right.size.add = 1,
top.size.add = 1, right.dendrogram.size = 2.5, top.dendrogram.size = 2.5, scale.data = FALSE, yaxis.lab = NULL,
xaxis.lab = NULL, xaxis.lab.top = NULL, xaxis.cex = 1.5, xaxis.top.cex = NULL, yaxis.cex = 1.5, xlab.cex = 2,
ylab.cex = 2, xlab.top.label = NULL, xlab.top.cex = 2, xlab.top.col = 'black', xlab.top.just = 'center',
xlab.top.x = 0.5, xlab.top.y = 0, xat = TRUE, xat.top = NULL, yat = TRUE, xaxis.tck = NULL, xaxis.top.tck = NULL,
yaxis.tck = NULL, xaxis.col = 'black', yaxis.col = 'black', col.pos = NULL, row.pos = NULL, cell.text = '',
text.fontface = 1, text.cex = 1, text.col = 'black', text.position = NULL, text.offset = 0,
text.use.grid.coordinates = TRUE, colourkey.cex = 3.6, xaxis.rot = 90, xaxis.rot.top = 90, yaxis.rot = 0,
xlab.label = '', ylab.label = '', xlab.col = 'black', ylab.col = 'black', axes.lwd = 2, gridline.order = 'h',
grid.row = FALSE, grid.col = FALSE, force.grid.row = FALSE, force.grid.col = FALSE, grid.limit = 50,
row.lines = seq(0, ncol(x), 1) + 0.5, col.lines = seq(0, nrow(x), 1) + 0.5, colour.scheme = c(), total.colours = 99,
colour.centering.value = 0, colour.alpha = 1, fill.colour = 'darkgray', at = NULL, print.colour.key = TRUE,
colourkey.labels.at = NULL, colourkey.labels = NULL, top.padding = 0.1, bottom.padding = 0.5, right.padding = 0.5,
left.padding = 0.5, x.alternating = 1, shrink = 1, row.colour = 'black', col.colour = 'black', row.lwd = 1, col.lwd = 1,
grid.colour = NULL, grid.lwd = NULL, width = 6, height = 6, size.units = 'in', resolution = 1600,
enable.warnings = FALSE, xaxis.covariates = NULL, xaxis.covariates.y = 0, yaxis.covariates = NULL,
yaxis.covariates.x = NULL, description = 'Created with BoutrosLab.plotting.general', xaxis.fontface = 'bold',
yaxis.fontface = 'bold', symbols = list(borders = NULL, squares = NULL, circles = NULL), same.as.matrix = FALSE,
input.colours = FALSE, axis.xlab.padding = 0.1, stratified.clusters.rows = NULL, stratified.clusters.cols = NULL,
inside.legend = NULL, style = 'BoutrosLab', preload.default = 'custom', use.legacy.settings = FALSE
) {
### PARAMETER CHECKING #########################################################################
if (preload.default == 'paper') {
}
else if (preload.default == 'web') {
}
# check that the resolution and size are sufficient for the dimensions of the data
# using a conservative estimate that the heatmap is 50% of the plot
# try to set default for xaxis.covariates.y value, if levelplot is resized user will have to input own value
if (is.null(yaxis.covariates.x) && !is.null(yaxis.covariates)) {
yaxis.covariates.x <- -0.037 * length(yaxis.covariates);
}
main <- unlist(main, use.names = FALSE);
if (size.units == 'in') {
if (nrow(x) > resolution * width * 0.5) {
warning('HEATMAP: There are probably not enough pixels to represent all the columns in the heatmap. Try increasing the resolution or width.');
}
if (ncol(x) > resolution * height * 0.5) {
warning('HEATMAP: There are probably not enough pixels to represent all the rows in the heatmap. Try increasing the resolution or height.');
}
}
# if you only have one column, you start to get weird behaviour, duplicating it fixes that.
if (ncol(x) == 1) {
x <- t(cbind(x, x));
}
# transpose matrix to keep original form
if (same.as.matrix == TRUE) {
x <- t(apply(x, 2, rev));
for (i in c(1:(length(yaxis.lab) / 2))) {
temp <- yaxis.lab[i];
yaxis.lab[i] <- yaxis.lab[length(yaxis.lab) - i + 1];
yaxis.lab[length(yaxis.lab) - i + 1] <- temp;
}
}
# function to colour stratified dendrograms
colbranches <- function(node, col) {
# Find the attributes of current node
node.attributes <- attributes(node);
# Colour edges with requested colour
attr(node, 'edgePar') <- c(node.attributes$edgePar, list(col = col, lwd = 2));
return(node);
}
### CUSTOMIZE AXIS LABEL SIZES #################################################################
data.directory <- system.file('optimal.heatmap.cex.txt', package = 'BoutrosLab.plotting.general');
# check to see if the file was actually found
if (!any(file.exists(data.directory))) {
stop('Unable to find reference heatmap cex file (for x and y labels)');
}
# read in the listing of all reference xaxis.cex and yaxis.cex values
xyaxis.ref.cex <- read.table(
file = data.directory,
header = TRUE,
sep = '\t',
row.names = NULL,
as.is = TRUE
);
# vectorize all x-axis characteristics
xaxis.cex <- rep(xaxis.cex, length.out = nrow(x));
xaxis.rot <- rep(xaxis.rot, length.out = nrow(x));
xaxis.col <- rep(xaxis.col, length.out = nrow(x));
xaxis.rot[2] <- xaxis.rot.top;
# vectorize all y-axis characteristics
yaxis.cex <- rep(yaxis.cex, length.out = ncol(x));
yaxis.col <- rep(yaxis.col, length.out = ncol(x));
# see if we can map a customized xaxis label-size, but set a reasonable default
xaxis.cex[is.na(xaxis.cex)] <- ifelse(
test = nrow(x) < max(xyaxis.ref.cex$NumberOfRows),
yes = xyaxis.ref.cex$optimal.cex[nrow(x)],
no = 0
);
# see if we can map a customized xaxis label-size, but set a reasonable default
yaxis.cex[is.na(yaxis.cex)] <- ifelse(
test = ncol(x) < max(xyaxis.ref.cex$NumberOfRows),
yes = xyaxis.ref.cex$optimal.cex[ncol(x)],
no = 0
);
### SUBSET DATA ################################################################################
# Extract a subset of data to work with
x <- x[criteria.list, ];
x <- as.matrix(x);
if (TRUE == input.colours) {
s <- unique(unlist(as.list(x)));
for (i in c(1:length(s))) {
x[x == s[i]] <- i;
}
storage.mode(x) <- 'numeric';
total.colours <- length(s) + 1;
colour.scheme <- s;
}
# Scale the data if necessary
if (scale.data) {
x <- t(x);
x <- scale(x);
x <- t(x);
}
# specifying top covariate
if (length(covariates.top) > 0) {
for (i in c(1:length(covariates.top))) {
if (!is.null(covariates.top[[i]]$col) && covariates.top[[i]]$col != 'transparent') {
break;
}
if (i == length(covariates.top)) {
covariates.top.grid.border <- list(col = 'black', lwd = 2);
}
}
}
# Set default behaviour of x and y axes labels
# NB: The rownames() and colnames() calls in the if() statements below are *correct*.
# Somehow the function is inverting what I think of as rows/columns (i.e. doing a t())
if (1 == length(xaxis.lab)) { if (is.na(xaxis.lab)) { xaxis.lab <- rownames(x); } }
if (1 == length(yaxis.lab)) { if (is.na(yaxis.lab)) { yaxis.lab <- colnames(x); } }
### ERROR CHECKING FOR PARAMETERS #############################################################
# error checking for column dendrogram
if (length(col.dendrogram) > 0) {
# ensure user did not specify both a dendrogram and a clustering method
if (clustering.method != 'none' && cluster.dimensions %in% c('both', 'col', 'column', 'cols', 'columns')) {
stop('Cannot provide a column dendrogram and also perform column-wise clustering');
}
# ensure dendrogram is correct class
if (!is(col.dendrogram, 'dendrogram')) {
stop('Invalid col.dendrogram parameter -- must be a dendrogram object');
}
# ensure dendrogram is correct size
if (length(order.dendrogram(col.dendrogram)) != nrow(x)) {
stop('Invalid col.dendrogram: should be of size ', nrow(x));
}
}
# error checking for the row dendrogram
if (length(row.dendrogram) > 0) {
# ensure user did not specify both a dendrogram and a clustering method
if (clustering.method != 'none' && cluster.dimensions %in% c('both', 'row', 'rows')) {
stop('Cannot provide a row dendrogram and also perform row-wise clustering');
}
# ensure dendrogram is correct class
if (!is(row.dendrogram, 'dendrogram')) {
stop('Invalid row.dendrogram parameter -- must be a dendrogram object');
}
# ensure dendrogram is correct size
if (length(order.dendrogram(row.dendrogram)) != ncol(x)) {
stop('Invalid row.dendrogram: should be of size ', ncol(x));
}
}
#error checking for input.colours = TRUE
if (input.colours == TRUE) {
if (clustering.method != 'none') {
stop('Cannot cluster data if input.colours == TRUE');
}
if (!is.null(at)) {
stop('at should not be specificed if input.colours == TRUE');
}
}
### CLUSTERING & COVARIATES ###################################################################
legend <- list();
# Specify lattice settings for any images
lattice.old.factor <- lattice.getOption('axis.padding')$factor;
lattice.options('axis.padding' = list(factor = 0.5));
# Include a column-based dendrogram if desired
# Note: Because of the inversion of rows & columns, the heatmap's column-based dendrogram
# corresponds to the rows of the matrix
dd.row.order <- NULL;
dd.col.order <- NULL;
if (length(col.dendrogram) > 0) {
dd.row <- col.dendrogram;
}
else if (clustering.method != 'none' && cluster.dimensions %in% c('both', 'col', 'column', 'cols', 'columns')) {
dd.row <- NULL;
if (length(stratified.clusters.cols) > 0) {
# loop through strata if stratified clusters have been specified
for (i in c(1:length(stratified.clusters.cols))) {
dd.row[[i]] <- BoutrosLab.plotting.general::create.dendrogram(
x = x[stratified.clusters.cols[[i]], ],
clustering.method = clustering.method,
cluster.dimension = 'row',
cor.method = cor.method,
distance.method = cols.distance.method,
force.clustering = force.clustering
);
}
# calculate the new row order based on the clusters
for (i in c(1:length(stratified.clusters.cols))) {
dd.row.order <- c(dd.row.order, stratified.clusters.cols[[i]][order.dendrogram(dd.row[[i]])]);
}
# merge each dendrogram together
dd.row <- do.call(merge, dd.row);
# readjust all the rows/cols (they all want to be placed in the same spot)
leafcount <- 0;
stratacount <- 1;
addition <- 0;
dd.row <- dendrapply(
dd.row,
function(n) {
if (is.leaf(n)) {
n[1] <- n[1] + addition;
leafcount <<- leafcount + 1;
if (leafcount == length(stratified.clusters.cols[[stratacount]])) {
addition <<- addition + length(stratified.clusters.cols[[stratacount]]);
stratacount <<- stratacount + 1;
leafcount <<- 0;
}
}
return(n);
}
);
}
else {
dd.row <- BoutrosLab.plotting.general::create.dendrogram(
x = x,
clustering.method = clustering.method,
cluster.dimension = 'row',
distance.method = cols.distance.method,
cor.method = cor.method,
force.clustering = force.clustering
);
}
}
if (exists('dd.row')) {
# reorder data for plotting
if (length(stratified.clusters.cols) > 0) {
x <- x[dd.row.order, ];
}
else {
x <- x[order.dendrogram(dd.row), ];
}
# reorder the cell.text
if (length(cell.text) > 1) {
col.pos <- match(col.pos, order.dendrogram(dd.row));
}
# reorder label characteristics to match clustering
if (length(stratified.clusters.cols) > 0) {
xaxis.lab <- xaxis.lab[dd.row.order];
xaxis.cex <- xaxis.cex[dd.row.order];
xaxis.rot <- xaxis.rot[dd.row.order];
xaxis.col <- xaxis.col[dd.row.order];
}
else {
xaxis.lab <- xaxis.lab[order.dendrogram(dd.row)];
xaxis.cex <- xaxis.cex[order.dendrogram(dd.row)];
xaxis.rot <- xaxis.rot[order.dendrogram(dd.row)];
xaxis.col <- xaxis.col[order.dendrogram(dd.row)];
}
# if covariate bars are to be drawn, create them using the dendrogram ordering
if (length(covariates.top) > 0) {
covariates.top.grob <- BoutrosLab.plotting.general::covariates.grob(
# reverse the covariates on the top dimension so the two match
covariates = rev(covariates.top),
ord = order.dendrogram(dd.row),
side = 'top',
size = top.size.add,
grid.row = covariates.top.grid.row,
grid.col = covariates.top.grid.col,
grid.border = covariates.top.grid.border,
row.lines = covariates.top.row.lines,
col.lines = covariates.top.col.lines,
reorder.grid.index = covariates.top.reorder.grid.index
);
}
# create dendrogram grob if desired
if (plot.dendrograms %in% c('both', 'top')) {
dendrogram.top.grob <- latticeExtra::dendrogramGrob(
x = dd.row,
ord = order.dendrogram(dd.row),
side = 'top',
size = top.dendrogram.size,
type = 'rectangle'
);
if (length(stratified.clusters.cols) > 0) {
# this will remove the top of grob so that the unrelated dendrograms are not joined
dendrogram.top.grob$children[[1]]$children[[1]]$y0 <-
dendrogram.top.grob$children[[1]]$children[[1]]$y0[
c( (1 + length(stratified.clusters.cols) * 2):length(dendrogram.top.grob$children[[1]]$children[[1]]$y0))
];
dendrogram.top.grob$children[[1]]$children[[1]]$y1 <-
dendrogram.top.grob$children[[1]]$children[[1]]$y1[
c( (1 + length(stratified.clusters.cols) * 2):length(dendrogram.top.grob$children[[1]]$children[[1]]$y1))
];
dendrogram.top.grob$children[[1]]$children[[1]]$x0 <-
dendrogram.top.grob$children[[1]]$children[[1]]$x0[
c( (1 + length(stratified.clusters.cols) * 2):length(dendrogram.top.grob$children[[1]]$children[[1]]$x0))
];
dendrogram.top.grob$children[[1]]$children[[1]]$x1 <-
dendrogram.top.grob$children[[1]]$children[[1]]$x1[
c( (1 + length(stratified.clusters.cols) * 2):length(dendrogram.top.grob$children[[1]]$children[[1]]$x1))
];
}
}
# if both covariates and dendrograms are to be drawn, place them in a grid and set the legend to hold the approntate grob
if (length(covariates.top) > 0 && plot.dendrograms %in% c('both', 'top')) {
top.layout <- grid.layout(
nrow = 3,
ncol = 1,
widths = unit(1, 'null'),
heights = unit(
c(1, covariates.top.padding, 1),
c('grobheight', 'lines', 'grobheight'),
list(dendrogram.top.grob, NULL, covariates.top.grob)
)
);
top.grob <- frameGrob(layout = top.layout);
top.grob <- placeGrob(
frame = top.grob,
grob = dendrogram.top.grob,
row = 1,
col = 1
);
top.grob <- placeGrob(
frame = top.grob,
grob = covariates.top.grob,
row = 3,
col = 1
);
legend[['top']] <- list(fun = top.grob);
}
else if (length(covariates.top) > 0) {
legend[['top']] <- list(fun = covariates.top.grob);
}
else if (plot.dendrograms %in% c('both', 'top')) {
legend[['top']] <- list(fun = dendrogram.top.grob);
}
}
# Include a row-based dendrogram if desired
# Note: Because of the inversion of rows & columns, the heatmap's row-based dendrogram
# corresponds to the columns of the matrix
if (length(row.dendrogram) > 0) {
dd.col <- row.dendrogram;
}
else if (clustering.method != 'none' && cluster.dimensions %in% c('both', 'row', 'rows')) {
dd.col <- NULL;
# loop through strata if stratified clusters have been specified
if (length(stratified.clusters.rows) > 0) {
for (i in c(1:length(stratified.clusters.rows))) {
dd.col[[i]] <- BoutrosLab.plotting.general::create.dendrogram(
x = x[, stratified.clusters.rows[[i]]],
clustering.method = clustering.method,
cluster.dimension = 'col',
distance.method = rows.distance.method,
cor.method = cor.method,
force.clustering = force.clustering
);
}
# calculate the new row order based on the clusters
for (i in c(1:length(stratified.clusters.rows))) {
dd.col.order <- c(dd.col.order, stratified.clusters.rows[[i]][order.dendrogram(dd.col[[i]])]);
}
# merge each dendrogram together
dd.col <- do.call(merge, dd.col);
# readjust all the rows/cols (they all want to be placed in the same spot)
leafcount <- 0;
stratacount <- 1;
addition <- 0;
dd.col <- dendrapply(
dd.col,
function(node) {
if (is.leaf(node)) {
node[1] <- node[1] + addition;
leafcount <<- leafcount + 1;
if (leafcount == length(stratified.clusters.rows[[stratacount]])) {
addition <<- addition + length(stratified.clusters.rows[[stratacount]]);
stratacount <<- stratacount + 1;
leafcount <<- 0;
}
}
return(node);
}
);
}
else {
dd.col <- BoutrosLab.plotting.general::create.dendrogram(
x = x,
clustering.method = clustering.method,
cluster.dimension = 'col',
distance.method = rows.distance.method,
cor.method = cor.method,
force.clustering = force.clustering
);
}
}
if (exists('dd.col')) {
# reorder data for plotting
if (length(stratified.clusters.rows) > 0) {
x <- x[, dd.col.order];
}
else {
x <- x[, order.dendrogram(dd.col)];
}
# reorder the cell.text
if (length(cell.text) > 1) {
row.pos <- match(row.pos, order.dendrogram(dd.col));
}
# reorder label characteristics to match clustering
if (length(stratified.clusters.rows) > 0) {
yaxis.lab <- yaxis.lab[dd.col.order];
yaxis.cex <- yaxis.cex[dd.col.order];
yaxis.col <- yaxis.col[dd.col.order];
}
else {
yaxis.lab <- yaxis.lab[order.dendrogram(dd.col)];
yaxis.cex <- yaxis.cex[order.dendrogram(dd.col)];
yaxis.col <- yaxis.col[order.dendrogram(dd.col)];
}
# if covariate bars are to be drawn, create them using the dendrogram ordering
if (length(covariates) > 0) {
covariates.right.grob <- BoutrosLab.plotting.general::covariates.grob(
covariates = covariates,
ord = order.dendrogram(dd.col),
side = 'right',
size = right.size.add,
grid.row = covariates.grid.row,
grid.col = covariates.grid.col,
grid.border = covariates.grid.border,
row.lines = covariates.row.lines,
col.lines = covariates.col.lines,
reorder.grid.index = covariates.reorder.grid.index
);
}
# create dendrogram grob if desired
if (plot.dendrograms %in% c('both', 'right')) {
dendrogram.right.grob <- latticeExtra::dendrogramGrob(
x = dd.col,
ord = order.dendrogram(dd.col),
side = 'right',
size = right.dendrogram.size,
type = 'rectangle'
);
if (length(stratified.clusters.rows) > 0) {
# this will remove the top of the grob
dendrogram.right.grob$children[[1]]$children[[1]]$y0 <-
dendrogram.right.grob$children[[1]]$children[[1]]$y0[
c( (1 + length(stratified.clusters.rows) * 2):length(dendrogram.right.grob$children[[1]]$children[[1]]$y0))
];
dendrogram.right.grob$children[[1]]$children[[1]]$y1 <-
dendrogram.right.grob$children[[1]]$children[[1]]$y1[
c( (1 + length(stratified.clusters.rows) * 2):length(dendrogram.right.grob$children[[1]]$children[[1]]$y1))
];
dendrogram.right.grob$children[[1]]$children[[1]]$x0 <-
dendrogram.right.grob$children[[1]]$children[[1]]$x0[
c( (1 + length(stratified.clusters.rows) * 2):length(dendrogram.right.grob$children[[1]]$children[[1]]$x0))
];
dendrogram.right.grob$children[[1]]$children[[1]]$x1 <-
dendrogram.right.grob$children[[1]]$children[[1]]$x1[
c( (1 + length(stratified.clusters.rows) * 2):length(dendrogram.right.grob$children[[1]]$children[[1]]$x1))
];
}
}
# if both covariates and dendrograms are to be drawn, place them in a grid
# set the legend to hold the appropriate grob
if (length(covariates) > 0 && plot.dendrograms %in% c('both', 'right')) {
right.layout <- grid.layout(
nrow = 1,
ncol = 3,
widths = unit(
c(1, covariates.padding, 1),
c('grobwidth', 'lines', 'grobwidth'),
list(covariates.right.grob, NULL, dendrogram.right.grob)
),
heights = unit(1, 'null')
);
right.grob <- frameGrob(layout = right.layout);
right.grob <- placeGrob(
frame = right.grob,
grob = covariates.right.grob,
row = 1,
col = 1
);
right.grob <- placeGrob(
frame = right.grob,
grob = dendrogram.right.grob,
row = 1,
col = 3
);
legend[['right']] <- list(fun = right.grob);
}
else if (length(covariates) > 0) {
legend[['right']] <- list(fun = covariates.right.grob);
}
else if (plot.dendrograms %in% c('both', 'right')) {
legend[['right']] <- list(fun = dendrogram.right.grob);
}
}
# if dendrograms/clustering are not used but covariates given, draw covariate bars with default ordering
if (!exists('dd.row') && length(covariates.top) > 0) {
top.grob <- BoutrosLab.plotting.general::covariates.grob(
# reverse the covariates on the top dimension so the two match
covariates = rev(covariates.top),
ord = c(1:nrow(x)),
side = 'top',
size = top.size.add,
grid.row = covariates.top.grid.row,
grid.col = covariates.top.grid.col,
grid.border = covariates.top.grid.border,
row.lines = covariates.top.row.lines,
col.lines = covariates.top.col.lines,
reorder.grid.index = covariates.top.reorder.grid.index
);
legend[['top']] <- list(fun = top.grob);
}
if (!exists('dd.col') && length(covariates) > 0) {
right.grob <- BoutrosLab.plotting.general::covariates.grob(
covariates = covariates,
ord = c(1:ncol(x)),
side = 'right',
size = right.size.add,
grid.row = covariates.grid.row,
grid.col = covariates.grid.col,
grid.border = covariates.grid.border,
row.lines = covariates.row.lines,
col.lines = covariates.col.lines,
reorder.grid.index = covariates.reorder.grid.index
);
legend[['right']] <- list(fun = right.grob);
}
# draw covariate legends
if (length(covariate.legends) > 0) {
# get font family for grobPack which is different from what lattice accepts
font.family <- 'sans';
# create grob representing the legend
if (is.null(legend.layout)) {
legend.layout <- c(1, length(covariate.legends));
}
legend.grob.left <- NULL;
legend.grob.top <- NULL;
legend.grob.right <- NULL;
if (length(legend.side) > 1 && length(covariate.legends[legend.side == 'left']) > 0) {
legend.grob.left <- BoutrosLab.plotting.general::legend.grob(
legends = covariate.legends[legend.side == 'left'],
label.cex = legend.cex,
title.cex = legend.title.cex,
title.just = legend.title.just,
title.fontface = legend.title.fontface,
font.family = font.family,
border = legend.border,
border.padding = legend.border.padding,
layout = legend.layout,
between.col = legend.between.col,
between.row = legend.between.row
);
}
else if (length(legend.side) == 1 && legend.side == 'left') {
legend.grob.left <- BoutrosLab.plotting.general::legend.grob(
legends = covariate.legends,
label.cex = legend.cex,
title.cex = legend.title.cex,
title.just = legend.title.just,
title.fontface = legend.title.fontface,
font.family = font.family,
border = legend.border,
border.padding = legend.border.padding,
layout = legend.layout,
between.col = legend.between.col,
between.row = legend.between.row
);
}
if (length(legend.side) > 1 && length(covariate.legends[legend.side == 'top']) > 0) {
legend.grob.top <- BoutrosLab.plotting.general::legend.grob(
legends = covariate.legends[legend.side == 'top'],
label.cex = legend.cex,
title.cex = legend.title.cex,
title.just = legend.title.just,
title.fontface = legend.title.fontface,
font.family = font.family,
border = legend.border,
border.padding = legend.border.padding,
layout = c(length(covariate.legends), 1),
between.col = legend.between.col,
between.row = legend.between.row
);
}
else if (length(legend.side) == 1 && legend.side == 'top') {
legend.grob.top <- BoutrosLab.plotting.general::legend.grob(
legends = covariate.legends,
label.cex = legend.cex,
title.cex = legend.title.cex,
title.just = legend.title.just,
title.fontface = legend.title.fontface,
font.family = font.family,
border = legend.border,
border.padding = legend.border.padding,
layout = c(length(covariate.legends), 1),
between.col = legend.between.col,
between.row = legend.between.row
);
}
if (length(legend.side) > 1 && length(covariate.legends[legend.side == 'right']) > 0) {
legend.grob.right <- BoutrosLab.plotting.general::legend.grob(
legends = covariate.legends[legend.side == 'right'],
label.cex = legend.cex,
title.cex = legend.title.cex,
title.just = legend.title.just,
title.fontface = legend.title.fontface,
font.family = font.family,
border = legend.border,
border.padding = legend.border.padding,
layout = legend.layout,
between.col = legend.between.col,
between.row = legend.between.row
);
}
else if (length(legend.side) == 1 && legend.side == 'right') {
legend.grob.right <- BoutrosLab.plotting.general::legend.grob(
legends = covariate.legends,
label.cex = legend.cex,
title.cex = legend.title.cex,
title.just = legend.title.just,
title.fontface = legend.title.fontface,
font.family = font.family,
border = legend.border,
border.padding = legend.border.padding,
layout = legend.layout,
between.col = legend.between.col,
between.row = legend.between.row
);
}
#legend.grob <- BoutrosLab.plotting.general::legend.grob(
# legends = covariate.legends,
# label.cex = legend.cex,
# title.cex = legend.title.cex,
# title.just = legend.title.just,
# title.fontface = legend.title.fontface,
# font.family = font.family,
# border = legend.border,
# border.padding = legend.border.padding,
# layout = legend.layout,
# between.col = legend.between.col,
# between.row = legend.between.row
# );
# add the legend grob to the image
if (!is.null(legend.grob.left)) {
legend[['left']] <- list(fun = legend.grob.left);
}
if (!is.null(legend.grob.right)) {
# check if we have already drawn something on the right side
right.grob <- legend[['right']][['fun']];
if (is.null(right.grob)) {
legend[['right']] <- list(fun = legend.grob.right);
}
else {
# NOTE: the convertUnit() call requires an open device
# Check if any devices are open at this point
# If not, the device created by the convertUnit() call
# will be closed below
devices.open <- FALSE;
if (length(dev.list()) > 0) {
devices.open <- TRUE;
}
# determine width of legend grob in cm
legend.width.cm <- convertUnit(
grobWidth(legend.grob.right),
unitTo = 'cm',
axisFrom = 'x',
typeFrom = 'dimension',
valueOnly = TRUE
);
# close the open device if it was opened for convertUnit()
if (!devices.open) {
dev.off();
# remove the empty Rplots.pdf file if one was created (non-interactive)
if (file.exists('Rplots.pdf')) {
unlink('Rplots.pdf');
}
}
# make a layout for the existing grob plus the legend
right.layout.final <- grid.layout(
nrow = 1,
ncol = 2,
widths = unit(
x = c(1, legend.width.cm + 0.5),
units = c('grobwidth', 'cm'),
data = list(right.grob, NULL)
),
heights = unit(1, 'null'),
respect = FALSE
);
# create a frame using this layout
right.grob.final <- frameGrob(layout = right.layout.final);
# place the existing grob
right.grob.final <- placeGrob(
frame = right.grob.final,
grob = right.grob,
row = 1,
col = 1
);
# place the legend
right.grob.final <- placeGrob(
frame = right.grob.final,
grob = legend.grob.right,
row = 1,
col = 2
);
legend[['right']] <- list(fun = right.grob.final);
}
}
if (!is.null(legend.grob.top)) {
# check if we have already drawn something on the top
top.grob <- legend[['top']][['fun']];
if (is.null(top.grob)) {
legend[['top']] <- list(fun = legend.grob.top);
}
else {
# NOTE: the convertUnit() call requires an open device
# Check if any devices are open at this point
# If not, the device created by the convertUnit() call
# will be closed below
devices.open <- FALSE;
if (length(dev.list()) > 0) {
devices.open <- TRUE;
}
# determine height of legend grob
legend.height.cm <- convertUnit(
grobHeight(legend.grob.top),
unitTo = 'cm',
axisFrom = 'y',
typeFrom = 'dimension',
valueOnly = TRUE
);
# close the open device if it was opened for convertUnit()
if (!devices.open) {
dev.off();
# Remove the empty Rplots.pdf file if one was created (non-interactive)
if (file.exists('Rplots.pdf')) {
unlink('Rplots.pdf');
}
}
# make a layout for the existing grob plus the legend
top.layout.final <- grid.layout(
ncol = 1,
nrow = 2,
heights = unit(
x = c(legend.height.cm + 0.5, 1),
units = c('cm', 'grobheight'),
data = list(NULL, top.grob)
),
widths = unit(1, 'null'),
respect = FALSE
);
# create a frame using this layout
top.grob.final <- frameGrob(layout = top.layout.final);
# place the existing grob
top.grob.final <- placeGrob(
frame = top.grob.final,
grob = legend.grob.top,
row = 1,
col = 1
);
# place the legend
top.grob.final <- placeGrob(
frame = top.grob.final,
grob = top.grob,
row = 2,
col = 1
);
legend[['top']] <- list(fun = top.grob.final);
}
}
}
legend[['inside']] <- inside.legend;
# draw xaxis covariates
xaxis.cov.height.cm <- 0;
if (!is.null(xaxis.covariates)) {
if (exists('dd.row')) {
xaxis.covariate.grob <- BoutrosLab.plotting.general::covariates.grob(
covariates = xaxis.covariates,
ord = order.dendrogram(dd.row),
side = 'top'
);
}
else {
xaxis.covariate.grob <- BoutrosLab.plotting.general::covariates.grob(
covariates = xaxis.covariates,
ord = c(1:nrow(x)),
side = 'top'
);
}
legend[['inside']] <- list(
fun = xaxis.covariate.grob,
x = 0.5,
y = xaxis.covariates.y
);
xaxis.cov.height.cm <- convertUnit(
grobHeight(xaxis.covariate.grob),
unitTo = 'cm',
axisFrom = 'y',
typeFrom = 'dimension',
valueOnly = TRUE
);
xaxis.cov.height.cm <- xaxis.cov.height.cm * 5;
if (is.null(xaxis.lab)) {
xaxis.lab <- rep(' ', nrow(x));
}
}
# draw yaxis covariates
yaxis.cov.height.cm <- 0;
if (!is.null(yaxis.covariates)) {
if (exists('dd.col')) {
yaxis.covariate.grob <- BoutrosLab.plotting.general::covariates.grob(
covariates = yaxis.covariates,
ord = order.dendrogram(dd.col),
side = 'right'
);
}
else {
yaxis.covariate.grob <- BoutrosLab.plotting.general::covariates.grob(
covariates = yaxis.covariates,
ord = c(1:ncol(x)),
side = 'right'
);
}
if (!is.null(xaxis.covariates)) {
grob.layout <- grid.layout(1,1);
grob.frame <- frameGrob(layout = grob.layout);
legend[['inside']]$fun$framevp$x <- unit(legend[['inside']]$x, 'npc');
legend[['inside']]$fun$framevp$y <- unit(legend[['inside']]$y - 0.0185 * length(xaxis.covariates), 'npc');
grob.frame <- placeGrob(grob.frame,legend[['inside']]$fun);
yaxis.covariate.grob$framevp$x <- unit(yaxis.covariates.x + 0.0185 * length(yaxis.covariates), 'npc');
yaxis.covariate.grob$framevp$y <- unit(0.5, 'npc');
grob.frame <- placeGrob(grob.frame,yaxis.covariate.grob);
legend[['inside']]$fun <- grob.frame;
legend[['inside']]$x <- 0.5;
legend[['inside']]$y <- 0.5;
}
else {
legend[['inside']] <- list(
fun = yaxis.covariate.grob,
x = yaxis.covariates.x,
y = 0.5
);
}
yaxis.cov.height.cm <- convertUnit(
grobWidth(yaxis.covariate.grob),
unitTo = 'cm',
axisFrom = 'y',
typeFrom = 'dimension',
valueOnly = TRUE
);
yaxis.cov.height.cm <- yaxis.cov.height.cm * 5;
if (is.null(yaxis.lab)) {
yaxis.lab <- rep(' ', ncol(x));
}
}
# restore original lattice setting
lattice.options('axis.padding' = list(factor = lattice.old.factor));
### AUTOMATIC COLOUR-KEY HANDLING ##############################################################
# work out data ranges, break point locations, and colour-number from input parameters
if (is.null(at)) {
min.value <- min(x - colour.centering.value, na.rm = TRUE);
max.value <- max(x - colour.centering.value, na.rm = TRUE);
at <- seq(from = min.value, to = max.value, length.out = total.colours);
if (all(1 == at)) { # handle cases with a single colour/value of x
at <- c(1:2); # all values of x are 1. The 2 prevents an error, since duplicate values of at are not permitted
# create the colour scheme
my.palette <- c(colour.scheme);
}
}
else {
min.value <- min(at - colour.centering.value, na.rm = TRUE);
max.value <- max(at - colour.centering.value, na.rm = TRUE);
max.at <- max(at);
min.at <- min(at);
if (max(x, na.rm = TRUE) > max.at) {
warning(
paste(
'max(x) =',
max(x, na.rm = TRUE),
'is greater than max(at) = ',
max.at,
'Clipped data will be plotted'
)
);
x[x > max.at] <- max(at);
}
if (min(x, na.rm = TRUE) < min.at) {
warning(
paste(
'min(x) =',
min(x, na.rm = TRUE),
'is greater than min(at) = ',
min.at,
'Clipped data will be plotted'
)
);
x[x < min.at] <- min(at);
}
total.colours <- max(length(at), total.colours);
}
# determine whether the data is one-sided or two-sided
is.twosided <- sign(min.value) != sign(max.value);
# colour-handling: use a default colour scheme if one was not provided
if (0 == length(colour.scheme)) {
if (is.twosided) {
colour.scheme <- c('blue', 'white', 'red');
}
else {
colour.scheme <- c('white', 'red');
}
}
# automatically approximate colour.alpha
if (colour.alpha == 'automatic') {
max.x <- max(as.numeric(x));
min.x <- min(as.numeric(x));
middle.x <- (max.x + min.x) / 2;
difference <- max.x - min.x;
upper.limit.count <- length(as.numeric(x)[as.numeric(x) > max.x - difference * 0.2]) +
length(as.numeric(x)[as.numeric(x) < min.x + difference * 0.2]);
lower.limit.count <- length(as.numeric(x)[as.numeric(x) > middle.x - difference * 0.2 & as.numeric(x) < middle.x + difference * 0.2]);
ratio <- (lower.limit.count - upper.limit.count) / lower.limit.count;
if (ratio < 0) {ratio <- ratio * lower.limit.count / upper.limit.count};
colour.alpha <- 1 + ratio * 0.5;
}
# colour-handling: first handle legacy cases
if (1 == length(colour.scheme) && FALSE == input.colours) {
if (colour.scheme == 'RedWhiteBlue') { colour.scheme <- c('red', 'white', 'blue'); }
else if (colour.scheme == 'WhiteBlack') { colour.scheme <- c('white', 'black'); }
else if (colour.scheme == 'BlueWhiteYellow') { colour.scheme <- c('blue', 'white', 'yellow'); }
else { stop('Unknown colour scheme:', colour.scheme); }
}
# colour-handling: next cover one-sided colour schemes
if (2 == length(colour.scheme)) {
colour.function <- colorRamp(colour.scheme, space = 'Lab');
my.palette <- rgb(colour.function(seq(0, 1, 1 / total.colours) ^ colour.alpha), maxColorValue = 255);
}
# colour-handling: then handle two-sided colour schemes
if (3 == length(colour.scheme)) {
# warn the user if they try to use a three-colour scheme with one-sided data
if (!is.twosided) { warning('Using a three-colour scheme with one-sided data is not advised!'); }
# create the colour scheme
colour.function.low <- colorRamp(colour.scheme[1:2], space = 'Lab');
colour.function.high <- colorRamp(colour.scheme[2:3], space = 'Lab');
# the number of negative colours is based on the fraction of the range that's below the center value
# the number of positive colours is based on the number of negatives
# leave one colour free for the center value
neg.colours <- min.value / (max.value - min.value) * (total.colours - 1);
neg.colours <- ceiling(abs(neg.colours));
pos.colours <- total.colours - neg.colours - 1;
# there is a potential for the colour allocation to go wrong when:
# 1) we have one-sided data
# 2) the colour-centering is at zero
# 3) a three-colour scheme is requested
# We try to automatically detect this case and provide a fix
if (neg.colours < 1 | pos.colours < 1) {
warning('Colour allocation scheme failed, moving to a default method');
neg.colours <- round(total.colours / 2);
pos.colours <- round(total.colours / 2);
}
# create the colour palette
my.palette <- c(
rgb( colour.function.low(seq(0, 1, 1 / neg.colours) ^ colour.alpha), maxColorValue = 255),
colour.scheme[2], # this helps ensure that the values are centered properly
rgb( colour.function.high(seq(0, 1, 1 / pos.colours) ^ (1 / colour.alpha)), maxColorValue = 255)
);
}
# allow colour-schemes with > 3 colours
if (3 < length(colour.scheme)) {
# warn the user if they do this
if (enable.warnings) { warning('Using a >three-colour scheme!'); }
# only allow this behaviour with at-colour-type-handling
if (is.null(at)) { stop('>3-colour schemes only work when at is specified'); }
# create the colour scheme
my.palette <- c(colour.scheme);
}
# colour-handling: lastly ensure that a palette was defined somehow
if (!exists('my.palette')) {
stop('Somehow no palette was ever defined');
}
# create the colour-key
if (print.colour.key) {
colour.key <- list(
space = 'bottom',
size = 1,
width = 1.25,
height = 1.0,
labels = list(
cex = colourkey.cex,
at = colourkey.labels.at,
labels = colourkey.labels
),
tick.number = 3
);
}
else {
colour.key <- FALSE;
}
### HEATMAP GENERATION #########################################################################
if (is.null(xlab.top.label)) {
# if x-labels are on top, put xlabel on top too
if (2 == x.alternating) {
xlab.top.label <- xlab.label;
xlab.label <- '';
}
}
# determine length of tck marks
# tick lengths depend on xaxis.tck and x.alternating
x.tck <- c(0, 0);
if (x.alternating > 0) {
if (!is.null(xaxis.tck)) {
if (1 == x.alternating) {
x.tck <- c(xaxis.tck, 0);
}
else if (2 == x.alternating) {
x.tck <- c(0, xaxis.tck);
}
else {
# special case to print on top and below
x.tck <- c(xaxis.tck, xaxis.tck);
}
}
else if (nrow(x) < 65) {
if (1 == x.alternating) {
x.tck <- c(0.2 + xaxis.cov.height.cm, 0.2);
}
else if (2 == x.alternating) {
x.tck <- c(0.2, xaxis.cov.height.cm);
}
else {
# special case to print on top and below
x.tck <- c(0.2 + xaxis.cov.height.cm, 0.2 + xaxis.cov.height.cm);
}
}
else {
if (1 == x.alternating) {
x.tck <- c(0 + xaxis.cov.height.cm, 0);
}
else if (2 == x.alternating) {
x.tck <- c(0, xaxis.cov.height.cm);
}
# special case to print on top and below
else {
x.tck <- c(0 + xaxis.cov.height.cm, 0 + xaxis.cov.height.cm);
}
}
}
if (!is.null(grid.colour)) {
row.colour <- grid.colour;
col.colour <- grid.colour;
cat(paste0('CAUTION: grid.colour is DEPRECATED! Use row.colour/col.colour. Using: ', grid.colour, '\n'));
}
if (!is.null(grid.lwd)) {
row.lwd <- grid.lwd;
col.lwd <- grid.lwd;
cat(paste0('CAUTION: grid.lwd is DEPRECATED! Use row.lwd/col.lwd. Using: ', grid.lwd, '\n'));
}
# function to draw different top and bottom axes
xscale.components.new <- function(...) {
args <- xscale.components.default(...);
args$top <- args$bottom;
if (length(xat.top) == 0) {
xat.top <- c(1:length(xaxis.lab.top));
}
args$top$ticks$at <- xat.top;
args$top$labels$at <- xat.top;
args$top$labels$labels <- xaxis.lab.top;
return(args);
}
if (is.null(xaxis.top.cex)) {xaxis.top.cex <- xaxis.cex;}
# look at nrow and ncol and if exceed limit (for now, default limit = 50), turn off grid lines
if ( (ncol(x) > grid.limit & grid.row == TRUE) & force.grid.row != TRUE) {
grid.row <- FALSE;
cat(paste0('Warning: number of rows exceeded limit (', grid.limit, '), row lines are turned off.
Please set "force.grid.row" to TRUE to override this\n'));
}
if ( (nrow(x) > grid.limit & grid.col == TRUE) & force.grid.col != TRUE) {
grid.col <- FALSE;
cat(paste0('Warning: number of colum ns exceeded limit (', grid.limit, '), column lines are turned off.
Please set "force.grid.col" to TRUE to override this\n'));
}
# create heatmap
trellis.object <- lattice::levelplot(
x,
panel = function(...) {
panel.fill(col = fill.colour);
panel.levelplot(...);
if (text.use.grid.coordinates) {
panel.text(col.pos, row.pos, cell.text, font = text.fontface, cex = text.cex, col = text.col, pos = text.position, offset = text.offset);
}
else {
for (i in 1:length(cell.text)) {
grid.text(
x = unit(text.position[[i]][1], 'npc'),
y = unit(text.position[[i]][2], 'npc'),
label = cell.text[i],
gp = gpar(col = text.col, cex = text.cex, fontface = text.fontface));
}
}
positions <- NULL;
colours <- NULL;
bordercolours <- 'white';
sizes <- NULL;
xright <- NULL;
xleft <- NULL;
ytop <- NULL;
ybottom <- NULL;
if (with(symbols, !is.null(symbols$borders) || !is.null(symbols$circles) || !is.null(symbols$squares))) {
# divide up the three types of symbols
borders <- symbols$borders;
squares <- symbols$squares;
circles <- symbols$circles;
# add borders if requested
if (!is.null(borders)) {
for (i in 1:length(borders)) {
if (3 == length(borders[[i]])) {
# find positions on heatmap where the symbols should be drawn
if (same.as.matrix == TRUE) {
borders[[i]]$x <- t(apply(borders[[i]]$x, 2, rev));
}
positions[[i]] <- which(borders[[i]]$x);
# gather all the necessary colours from those positions in the colour matrix
bordercolours <- c(bordercolours, as.vector(borders[[i]]$col[positions[[i]]]));
# gather all the necessary sizes from those positions in the size matrix
sizes <- c(sizes, as.vector(borders[[i]]$size[positions[[i]]]));
# calculate the actual positions needed for each coordinate on the heatmap
xright <- c(xright, positions[[i]] %% nrow(borders[[i]]$x));
xright <- replace(xright, xright == 0, nrow(borders[[i]]$x));
xleft <- c(xleft, positions[[i]] %% nrow(borders[[i]]$x));
xleft <- replace(xleft, xleft == 0, nrow(borders[[i]]$x));
ytop <- c(ytop, (positions[[i]] - 0.01) %/% nrow(borders[[i]]$x) + 1);
ybottom <- c(ybottom, (positions[[i]] - 0.01) %/% nrow(borders[[i]]$x) + 1);
colours <- c(colours, rep('transparent', length(positions[[i]])));
}
else {
if (same.as.matrix == TRUE) {
templeft <- borders[[i]]$xleft;
tempright <- borders[[i]]$xright;
borders[[i]]$xleft <- borders[[i]]$ybottom;
borders[[i]]$xright <- borders[[i]]$ytop;
borders[[i]]$ybottom <- ncol(x) - tempright + 1;
borders[[i]]$ytop <- ncol(x) - templeft + 1;
}
xright <- c(xright, borders[[i]]$xright);
xleft <- c(xleft, borders[[i]]$xleft);
ytop <- c(ytop, borders[[i]]$ytop);
ybottom <- c(ybottom, borders[[i]]$ybottom);
sizes <- c(sizes, borders[[i]]$size);
bordercolours <- c(bordercolours, borders[[i]]$col);
colours <- c(colours, 'transparent');
}
}
# adjust coordinates to be at edge of cells
ybottom <- ybottom - 0.5;
xleft <- xleft - 0.5;
ytop <- ytop + 0.5;
xright <- xright + 0.5;
}
# add squares if requested
if (!is.null(squares)) {
for (i in 1:length(squares)) {
if (same.as.matrix == TRUE) {
squares[[i]]$x <- t(apply(squares[[i]]$x, 2, rev));
}
positions[[i]] <- which(squares[[i]]$x);
bordercolours <- c(bordercolours, rep('transparent', length(positions[[i]])));
sizes <- c(sizes, as.vector(squares[[i]]$size[positions[[i]]]));
xright <- c(xright, positions[[i]] %% nrow(squares[[i]]$x));
xright <- replace(xright, xright == 0, nrow(squares[[i]]$x));
xleft <- c(xleft, positions[[i]] %% nrow(squares[[i]]$x));
xleft <- replace(xleft, xleft == 0, nrow(squares[[i]]$x));
ytop <- c(ytop, (positions[[i]] - 0.01) %/% nrow(squares[[i]]$x) + 1);
ybottom <- c(ybottom, (positions[[i]] - 0.01) %/% nrow(squares[[i]]$x) + 1);
colours <- c(colours, as.vector(squares[[i]]$col[positions[[i]]]));
}
}
if (!is.null(xright)) {
panel.rect(
xleft = xleft + (sizes * 0.01),
ybottom = ybottom + (sizes * 0.01),
ytop = ytop - (sizes * 0.01),
xright = xright - (sizes * 0.01),
col = colours,
alpha = 1,
border = bordercolours,
lwd = sizes
);
}
xright <- NULL;
ytop <- NULL;
colours <- NULL;
sizes <- NULL;
# add circles if requested
if (!is.null(circles)) {
for (i in 1:length(circles)) {
if (same.as.matrix == TRUE) {
circles[[i]]$x <- t(apply(circles[[i]]$x, 2, rev));
}
positions[[i]] <- which(circles[[i]]$x);
sizes <- c(sizes, as.vector(circles[[i]]$size[positions[[i]]]));
xright <- c(xright, positions[[i]] %% nrow(circles[[i]]$x));
xright <- replace(xright, xright == 0, nrow(circles[[i]]$x));
ytop <- c(ytop, (positions[[i]] - 0.01) %/% nrow(circles[[i]]$x) + 1);
colours <- c(colours, as.vector(circles[[i]]$col[positions[[i]]]));
}
}
if (!is.null(xright)) {
grid.circle(
x = xright,
y = ytop,
r = sizes * 0.01,
draw = TRUE,
default.units = 'native',
gp = gpar(fill = colours, col = 'transparent')
);
}
}
# draw grid lines if requested
if ('h' == gridline.order) {
if (grid.row) {
panel.abline(
h = row.lines,
v = 0,
col.line = row.colour,
lwd = row.lwd
);
}
if (grid.col) {
panel.abline(
h = 0,
v = col.lines,
col.line = col.colour,
lwd = col.lwd
);
}
}
else if ('v' == gridline.order) {
if (grid.col) {
panel.abline(
h = 0,
v = col.lines,
col.line = col.colour,
lwd = col.lwd
);
}
if (grid.row) {
panel.abline(
h = row.lines,
v = 0,
col.line = row.colour,
lwd = row.lwd
);
}
}
},
aspect = 'fill',
scales = list(
x = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
labels = xaxis.lab,
cex = xaxis.cex,
col = xaxis.col,
tck = x.tck,
alternating = x.alternating,
rot = xaxis.rot,
at = xat,
fontface = if ('Nature' == style) {'plain'} else (xaxis.fontface)
)
),
y = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
labels = yaxis.lab,
cex = yaxis.cex,
col = yaxis.col,
rot = yaxis.rot,
tck = if (! is.null(yaxis.tck)) {
c(yaxis.tck, 0);
}
else if (ncol(x) < 65) {
c(0.2 + yaxis.cov.height.cm, 0.2)
}
else {
c(0 + yaxis.cov.height.cm, 0)
},
axs = 'r',
alternating = 1,
at = yat,
fontface = if ('Nature' == style) {'plain'} else (yaxis.fontface)
)
)
),
xscale.components = xscale.components.new,
# axis = axis.CF,
col.regions = my.palette,
colorkey = colour.key,
legend = legend,
par.settings = list(
axis.line = list(
lwd = axes.lwd
),
layout.heights = list(
top.padding = top.padding,
main = if (main == '') { 0.1 } else { 1.0 },
main.key.padding = if ('' == main) { 0.1 } else { 1.0 },
key.top = 1,
key.axis.padding = if (ncol(x) < 30) { 0.9 } else { 0.5 },
axis.top = if (1 == x.alternating) { 0.1 } else { 1.0 },
axis.bottom = if (is.null(xaxis.lab)) { 0.2 } else { 1.0 },
axis.xlab.padding = axis.xlab.padding,
xlab = if (!is.expression(xlab.label) && '' == xlab.label) { 0.1 } else { 1 },
xlab.key.padding = 0.5,
key.bottom = 1,
key.sub.padding = 0.1,
sub = 0.1,
bottom.padding = bottom.padding
),
layout.widths = list(
left.padding = left.padding,
key.left = 1,
key.ylab.padding = if ( (!is.expression(ylab.label) && '' == ylab.label) || 0 == length(covariate.legends)) { 0.1 } else { 1.0 },
ylab = if (!is.expression(ylab.label) && '' == ylab.label) { 0.1 } else { 1 },
ylab.axis.padding = 0.1,
axis.left = 1,
axis.right = 0.1,
axis.key.padding = if (nrow(x) < 30) { 0.9 } else { 0.5 },
key.right = 1,
right.padding = right.padding
),
par.xlab.text = list(
cex = xaxis.cex,
lineheight = xaxis.cex
),
par.ylab.text = list(
cex = yaxis.cex,
lineheight = yaxis.cex
)
),
lattice.options = list(
axis.padding = list(
factor = 0.5
)
),
xlab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.label,
cex = xlab.cex,
col = xlab.col,
fontface = if ('Nature' == style) {'plain'} else ('bold')
)
),
xlab.top = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.top.label,
cex = xlab.top.cex,
col = xlab.top.col,
fontface = if ('Nature' == style) {'plain'} else {'bold'},
just = xlab.top.just,
x = xlab.top.x,
y = xlab.top.y
)
),
ylab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = ylab.label,
cex = ylab.cex,
col = ylab.col,
fontface = if ('Nature' == style) {'plain'} else ('bold')
)
),
main = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = main,
cex = main.cex,
fontface = if ('Nature' == style) {'plain'} else ('bold'),
just = main.just,
x = main.x
)
),
shrink = shrink,
pretty = TRUE,
at = at
);
# If Nature style requested, change figure accordingly
if ('Nature' == style) {
# Ensure sufficient resolution for graphs
if (resolution < 1200) {
resolution <- 1200;
warning('Setting resolution to 1200 dpi.');
}
# Other required changes which are not accomplished here
warning('Nature also requires italicized single-letter variables and en-dashes
for ranges and negatives. See example in documentation for how to do this.');
warning('Avoid red-green colour schemes, create TIFF files, do not outline the figure or legend');
}
else if ('BoutrosLab' == style) {
# Nothing happens
}
else {
warning("The style parameter only accepts 'Nature' or 'BoutrosLab'.");
}
# output the object
return(
BoutrosLab.plotting.general::write.plot(
trellis.object = trellis.object,
filename = filename,
height = height,
width = width,
size.units = size.units,
resolution = resolution,
enable.warnings = enable.warnings,
description = description
)
);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/create.heatmap.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO CREATE HEXBINPLOTS #################################################################
create.hexbinplot <- function(
formula, data, filename = NULL, main = NULL, main.just = 'center', main.x = 0.5, main.y = 0.5,
main.cex = 3, aspect = 'xy', trans = NULL, inv = NULL, colour.scheme = NULL, colourkey = TRUE,
colourcut = seq(0, 1, length = 11), mincnt = 1, maxcnt = NULL, xbins = 30, legend.title = NULL,
xlab.label = tail(sub('~', '', formula[-2]), 1), ylab.label = tail(sub('~', '', formula[-3]), 1),
xlab.cex = 2, ylab.cex = 2, xlab.col = 'black', ylab.col = 'black', xlab.top.label = NULL, xlab.top.cex = 2,
xlab.top.col = 'black', xlab.top.just = 'center', xlab.top.x = 0.5, xlab.top.y = 0, xlimits = NULL,
ylimits = NULL, xat = TRUE, yat = TRUE, xaxis.lab = NA, yaxis.lab = NA, xaxis.cex = 1.5, yaxis.cex = 1.5,
xaxis.rot = 0, yaxis.rot = 0, xaxis.col = 'black', yaxis.col = 'black', xaxis.tck = 1, yaxis.tck = 1,
xaxis.fontface = 'bold', yaxis.fontface = 'bold', layout = NULL, as.table = FALSE, x.relation = 'same',
y.relation = 'same', x.spacing = 0, y.spacing = 0, strip.col = 'white', strip.cex = 1, strip.fontface = 'bold',
add.grid = FALSE, abline.h = NULL, abline.v = NULL, abline.lty = NULL, abline.lwd = NULL,
abline.col = 'black', abline.front = FALSE, add.xyline = FALSE, xyline.col = 'black', xyline.lwd = 1,
xyline.lty = 1, add.curves = FALSE, curves.exprs = NULL, curves.from = min(data, na.rm = TRUE),
curves.to = max(data, na.rm = TRUE), curves.col = 'black', curves.lwd = 2, curves.lty = 1,
add.text = FALSE, text.labels = NULL, text.x = NULL, text.y = NULL, text.col = 'black', text.cex = 1,
text.fontface = 'bold', add.axes = FALSE, top.padding = 0.1, bottom.padding = 0.7, left.padding = 0.5,
right.padding = 0.1, add.rectangle = FALSE, xleft.rectangle = NULL, ybottom.rectangle = NULL,
xright.rectangle = NULL, ytop.rectangle = NULL, col.rectangle = 'transparent', alpha.rectangle = 1,
background.col = 'transparent', key = NULL, legend = NULL, height = 6, width = 6, size.units = 'in',
resolution = 1600, enable.warnings = FALSE, description = 'Created with BoutrosLab.plotting.general',
style = 'BoutrosLab', preload.default = 'custom', use.legacy.settings = FALSE, inside.legend.auto = FALSE
) {
# IMPORTANT NOTE:
# - the implementation of this function is different from any other functions in the library
# - it uses do.call() because the maxcnt parameter is passed using missing()
# - to successfully pass arguments with this problem elsewhere, you need to create a list of arguments
# - then check if your passed argument !is.null (or whatever you set as the default) and add to the list
# - then run do.call() on the list
# - this *may* mess up substitute calls
# - in future, avoid use of missing()
# WARNING:
# - if 'maxcnt' is passed, make sure it is not smaller than the actual maximum count (value depends on nbins).
# - Otherwise, some data may be lost. If you aren't sure what the actual max count is, run this function without
# - specifying the 'maxcnt' parameter using the desired number of bins.
### needed to copy in case using variable to define rectangles dimensions
rectangle.info <- list(
xright = xright.rectangle,
xleft = xleft.rectangle,
ytop = ytop.rectangle,
ybottom = ybottom.rectangle
);
text.info <- list(
labels = text.labels,
x = text.x,
y = text.y,
col = text.col,
cex = text.cex,
fontface = text.fontface
);
out <- prep.axis(
at = xat,
data = unlist(data[toString(formula[[3]])]),
which.arg = 'xat'
);
if (is.list(out)) {
data[toString(formula[[3]])] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
out <- prep.axis(
at = yat,
data = unlist(data[toString(formula[[2]])]),
which.arg = 'yat'
);
if (is.list(out)) {
data[toString(formula[[2]])] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
# check class of conditioning variable
if ('|' %in% all.names(formula)) {
variable <- sub('^\\s+', '', unlist(strsplit(toString(formula[length(formula)]), '\\|'))[2]);
if (variable %in% names(data)) {
cond.class <- class(data[, variable]);
if (cond.class %in% c('integer', 'numeric')) {
warning(
'Numeric values detected for conditional variable. If text labels are desired, please convert conditional variable to character.'
);
}
rm(cond.class);
}
}
# add preloaded defaults
if (preload.default == 'paper') {
}
else if (preload.default == 'web') {
}
# update/modify legend title if desired
if (!is.null(legend.title) & !is.null(key)) {
stop('ERROR: cannot modify default title while additional key is being supplied; please use legend to specify additional keys.');
}
if (!is.null(legend.title) & is.null(key)) {
if (!is.list(legend.title)) {
legend.title <- list(lab = legend.title, x = 1, y = 1.1);
}
else if (is.null(legend.title$lab) || is.null(legend.title$x) || is.null(legend.title$y)) {
stop('ERROR: if supplying modified legend title as a list, must provide all of list(lab, x, y) components.');
}
key <- list(
text = list(
lab = legend.title$lab,
cex = 1.5
),
x = legend.title$x,
y = legend.title$y
);
}
# fill in the defined parameters
parameter.list <- list(
formula,
data,
panel = function(...) {
# add rectangle if requested
if (add.rectangle) {
panel.rect(
xleft = rectangle.info$xleft,
ybottom = rectangle.info$ybottom,
xright = rectangle.info$xright,
ytop = rectangle.info$ytop,
col = col.rectangle,
alpha = alpha.rectangle,
border = NA
);
}
# if axes are requested
if (add.axes) {
panel.abline(
h = 0,
v = 0,
col.line = 'black',
lty = 'dashed',
lwd = 1.5
);
}
# if abline should be placed behind
# create and add abline to empty plot
if (abline.front == FALSE) {
panel.xyplot(
0,
0,
type = 'g',
col.line = 'black',
grid = add.grid
);
panel.abline(h = abline.h, lty = abline.lty, lwd = abline.lwd, col = abline.col);
panel.abline(v = abline.v, lty = abline.lty, lwd = abline.lwd, col = abline.col);
}
# otherwise, if abline is to be placed in front
# create hexbin plot
panel.hexbinplot(...);
# and then add abline
if (abline.front == TRUE) {
panel.xyplot(
0,
0,
type = 'g',
col.line = 'black',
grid = add.grid
);
panel.abline(h = abline.h, lty = abline.lty, lwd = abline.lwd, col = abline.col);
panel.abline(v = abline.v, lty = abline.lty, lwd = abline.lwd, col = abline.col);
}
# if xy line is requested
if (add.xyline) {
panel.abline(
a = 0,
b = 1,
lwd = xyline.lwd,
lty = xyline.lty,
col = xyline.col
);
}
# if requested, add curve segments
if (add.curves) {
if (length(curves.exprs) > 1) {
if (1 == length(curves.from)) { curves.from <- rep(curves.from, length(curves.exprs)); }
if (1 == length(curves.to)) { curves.to <- rep(curves.to, length(curves.exprs)); }
if (1 == length(curves.col)) { curves.col <- rep(curves.col, length(curves.exprs)); }
if (1 == length(curves.lwd)) { curves.lwd <- rep(curves.lwd, length(curves.exprs)); }
if (1 == length(curves.lty)) { curves.lty <- rep(curves.lty, length(curves.exprs)); }
}
for (i in 1:length(curves.exprs)) {
with(
data = new.env(),
expr = panel.curve(
expr = curves.exprs[[i]](x),
from = curves.from[i],
to = curves.to[i],
col = curves.col[i],
lwd = curves.lwd[i],
lty = curves.lty[i]
)
);
}
}
# Add text to plot
if (add.text) {
panel.text(
x = text.info$x,
y = text.info$y,
labels = text.info$labels,
col = text.info$col,
cex = text.info$cex,
fontface = text.info$fontface
);
}
},
aspect = aspect,
trans = trans,
inv = inv,
xbins = xbins,
colramp = if (is.null(colour.scheme)) { function(n) { LinGray(n, beg = 90, end = 15) } } else { colour.scheme },
colorkey = colourkey,
colorcut = colourcut,
mincnt = mincnt,
main = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = main,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
cex = main.cex,
just = main.just,
x = main.x,
y = main.y
)
),
xlab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.label,
cex = xlab.cex,
col = xlab.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' }
)
),
xlab.top = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.top.label,
cex = xlab.top.cex,
col = xlab.top.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
just = xlab.top.just,
x = xlab.top.x,
y = xlab.top.y
)
),
ylab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = ylab.label,
cex = ylab.cex,
col = ylab.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' }
)
),
scales = list(
alternating = FALSE,
x = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
labels = xaxis.lab,
cex = xaxis.cex,
col = xaxis.col,
rot = xaxis.rot,
tck = xaxis.tck,
limits = xlimits,
relation = x.relation,
at = xat,
fontface = if ('Nature' == style) { 'plain' } else { xaxis.fontface }
)
),
y = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
labels = yaxis.lab,
cex = yaxis.cex,
col = yaxis.col,
rot = yaxis.rot,
tck = yaxis.tck,
limits = ylimits,
relation = y.relation,
at = yat,
fontface = if ('Nature' == style) { 'plain' } else { yaxis.fontface }
)
)
),
between = list(
x = x.spacing,
y = y.spacing
),
layout = layout,
as.table = as.table,
par.settings = list(
axis.line = list(lwd = 2),
layout.heights = list(
top.padding = top.padding,
main = if (is.null(main)) { 0.3 } else { 1 },
main.key.padding = 0.1,
key.top = 0.1,
key.axis.padding = 0.1,
axis.top = 1,
axis.bottom = 1,
axis.xlab.padding = 1,
xlab = 1,
xlab.key.padding = 0.5,
key.bottom = 0.1,
key.sub.padding = 0.1,
sub = 0.1,
bottom.padding = bottom.padding
),
layout.widths = list(
left.padding = left.padding,
key.left = 0.1,
key.ylab.padding = 0.1,
ylab = 1,
ylab.axis.padding = 1,
axis.left = 1,
axis.right = 0.1,
axis.key.padding = 3,
key.right = if (colourkey) { 1 } else { 0.1 },
right.padding = right.padding
),
panel.background = list(
col = background.col
),
strip.background = list(
col = strip.col
)
),
par.strip.text = list(
cex = strip.cex,
fontface = strip.fontface
),
key = key,
legend = legend,
grid = add.grid
);
# check if the maxcnt parameter has been passed
if (!is.null(maxcnt)) {
parameter.list[['maxcnt']] <- maxcnt;
}
# actually create the plot
trellis.object <- base::do.call(
what = 'hexbinplot',
args = parameter.list
);
# update/modify legend title if desired
if (!is.null(legend.title)) {
trellis.object$legend$right$args$cex.title = 0;
}
if (inside.legend.auto) {
extra.parameters <- list('x' = trellis.object$panel.args[[1]]$x, 'y' = trellis.object$panel.args[[1]]$y, 'ylimits' = trellis.object$y.limits,
'xlimits' = trellis.object$x.limits, 'xbins' = xbins, 'aspect.ratio' = trellis.object$panel.args.common$.aspect.ratio);
coords <- c();
coords <- .inside.auto.legend('create.hexbinplot', filename, trellis.object, height, width, extra.parameters);
trellis.object$legend$inside$x <- coords[1];
trellis.object$legend$inside$y <- coords[2];
}
# If Nature style requested, change figure accordingly
if ('Nature' == style) {
# Ensure sufficient resolution for graphs
if (resolution < 1200) {
resolution <- 1200;
warning('Setting resolution to 1200 dpi.');
}
# Other required changes which are not accomplished here
warning('Nature also requires italicized single-letter variables and en-dashes
for ranges and negatives. See example in documentation for how to do this.');
warning('Avoid red-green colour schemes, create TIFF files, do not outline the figure or legend');
}
# Otherwise use the BL style if requested
else if ('BoutrosLab' == style) {
# Nothing happens
}
# if neither of the above is requested, give a warning
else {
warning("The style parameter only accepts 'Nature' or 'BoutrosLab'.");
}
# output the object
return(
BoutrosLab.plotting.general::write.plot(
trellis.object = trellis.object,
filename = filename,
height = height,
width = width,
size.units = size.units,
resolution = resolution,
enable.warnings = enable.warnings,
description = description
)
);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/create.hexbinplot.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO CREATE HISTOGRAMS ##################################################################
create.histogram <- function(
x, data, filename = NULL, main = NULL, main.just = 'center', main.x = 0.5, main.y = 0.5, main.cex = 3,
xlab.label = NULL, ylab.label = NULL, xlab.cex = 2, ylab.cex = 2, xlab.col = 'black', ylab.col = 'black',
xaxis.lab = TRUE, yaxis.lab = TRUE, xaxis.cex = 1.5, yaxis.cex = 1.5, xlimits = NULL, ylimits = NULL,
xat = TRUE, yat = TRUE, xaxis.rot = 0, yaxis.rot = 0, xaxis.col = 'black', yaxis.col = 'black',
xaxis.tck = 1, yaxis.tck = 1, xaxis.fontface = 'bold', yaxis.fontface = 'bold', xlab.top.label = NULL,
xlab.top.cex = 2, xlab.top.col = 'black', xlab.top.just = 'center', xlab.top.x = 0.5, xlab.top.y = 0,
type = 'percent', breaks = NULL, col = 'white', border.col = 'black', lwd = 2, lty = 1, layout = NULL, x.spacing = 0, y.spacing = 0,
x.relation = 'same', y.relation = 'same', strip.col = 'white', strip.cex = 1, top.padding = 0.1,
bottom.padding = 0.7, right.padding = 0.1, left.padding = 0.5, ylab.axis.padding = 0, abline.h = NULL,
abline.v = NULL, abline.col = 'black', abline.lwd = 1, abline.lty = 1, key = NULL, legend = NULL,
add.text = FALSE, text.labels = NULL, text.x = NULL, text.y = NULL, text.col = 'black',
text.cex = 1, text.fontface = 'bold',
add.rectangle = FALSE, xleft.rectangle = NULL, ybottom.rectangle = NULL, xright.rectangle = NULL,
ytop.rectangle = NULL, col.rectangle = 'transparent', alpha.rectangle = 1, height = 6, width = 6,
size.units = 'in', resolution = 1600, enable.warnings = FALSE,
description = 'Created with BoutrosLab.plotting.general', style = 'BoutrosLab', preload.default = 'custom',
use.legacy.settings = FALSE, inside.legend.auto = FALSE
) {
### needed to copy in case using variable to define rectangles dimensions
rectangle.info <- list(
xright = xright.rectangle,
xleft = xleft.rectangle,
ytop = ytop.rectangle,
ybottom = ybottom.rectangle
);
# 'data' parameter shoud only be set if x if a formula
# otherwise a warning will be thrown (even if data = NULL), although the plot will still be created
# temporarily turn off warnings to avoid confusion
options(warn = -1);
# add preloaded defaults
if (preload.default == 'paper') {
}
else if (preload.default == 'web') {
}
text.info <- list(
labels = text.labels,
x = text.x,
y = text.y,
col = text.col,
cex = text.cex,
fontface = text.fontface
);
# Now make the actual plot object
trellis.object <- lattice::histogram(
x = x,
data = data,
panel = function(...) {
# turn warnings back on
options(warn = 0);
panel.histogram(border = border.col, ...);
# add rectangle if requested
if (add.rectangle) {
panel.rect(
xleft = rectangle.info$xleft,
ybottom = rectangle.info$ybottom,
xright = rectangle.info$xright,
ytop = rectangle.info$ytop,
col = col.rectangle,
alpha = alpha.rectangle,
border = NA
);
}
# if requested, add user-defined horizontal line
if (!is.null(abline.h)) {
panel.abline(
h = abline.h,
lty = abline.lty,
lwd = abline.lwd,
col = abline.col
);
}
# if requested, add user-defined vertical line
if (!is.null(abline.v)) {
panel.abline(
v = abline.v,
lty = abline.lty,
lwd = abline.lwd,
col = abline.col
);
}
# Add text to plot
if (add.text) {
panel.text(
x = text.info$x,
y = text.info$y,
labels = text.info$labels,
col = text.info$col,
cex = text.info$cex,
fontface = text.info$fontface
);
}
},
type = type,
col = col,
lwd = lwd,
lty = lty,
breaks = breaks,
main = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = main,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
cex = main.cex,
just = main.just,
x = main.x,
y = main.y
)
),
xlab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.label,
cex = xlab.cex,
col = xlab.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' }
)
),
xlab.top = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.top.label,
cex = xlab.top.cex,
col = xlab.top.col,
fontface = if ('Nature' == style) { 'plain' }else { 'bold' },
just = xlab.top.just,
x = xlab.top.x,
x = xlab.top.y
)
),
ylab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = ylab.label,
cex = ylab.cex,
col = ylab.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' }
)
),
scales = list(
x = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
labels = xaxis.lab,
cex = xaxis.cex,
col = xaxis.col,
rot = xaxis.rot,
tck = xaxis.tck,
fontface = if ('Nature' == style) { 'plain' } else { xaxis.fontface },
limits = xlimits,
at = xat,
relation = x.relation,
alternating = FALSE
)
),
y = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
labels = yaxis.lab,
cex = yaxis.cex,
col = yaxis.col,
rot = yaxis.rot,
tck = yaxis.tck,
fontface = if ('Nature' == style) { 'plain' } else { yaxis.fontface },
limits = ylimits,
at = yat,
relation = y.relation,
alternating = FALSE
)
)
),
between = list(
x = x.spacing,
y = y.spacing
),
par.settings = list(
axis.line = list(
lwd = 2,
col = if ('Nature' == style) {'transparent'} else { 'black' }
),
layout.heights = list(
top.padding = top.padding,
main = if (is.null(main)) { 0.3} else { 1 },
main.key.padding = 0.1,
key.top = 0.1,
key.axis.padding = 0.1,
axis.top = 1,
axis.bottom = 1,
axis.xlab.padding = 1,
xlab = 1,
xlab.key.padding = 0.5,
key.bottom = 0.1,
key.sub.padding = 0.1,
sub = 0.1,
bottom.padding = bottom.padding
),
layout.widths = list(
left.padding = left.padding,
key.left = 0.1,
key.ylab.padding = 0.1,
ylab = 1,
ylab.axis.padding = ylab.axis.padding,
axis.left = 1,
axis.right = 1,
axis.key.padding = 0.1,
key.right = 0.1,
right.padding = right.padding
),
strip.background = list(
col = strip.col
)
),
par.strip.text = list(
cex = strip.cex
),
layout = layout,
key = key,
legend = legend
);
if (inside.legend.auto) {
extra.parameters <- list('x' = trellis.object$panel.args[[1]]$x, 'ylimits' = trellis.object$y.limits,
'xlimits' = trellis.object$x.limits, 'breaks' = breaks, 'nint' = trellis.object$panel.args.common$nint, 'type' = type);
coords <- c();
coords <- .inside.auto.legend('create.histogram', filename, trellis.object, height, width, extra.parameters);
trellis.object$legend$inside$x <- coords[1];
trellis.object$legend$inside$y <- coords[2];
}
# If Nature style requested, change figure accordingly
if ('Nature' == style) {
# Re-add bottom and left axes
trellis.object$axis <- function(side, line.col = 'black', ...) {
# Only draw axes on the left and bottom
if (side %in% c('bottom', 'left')) {
axis.default(side = side, line.col = 'black', ...);
lims <- current.panel.limits();
panel.abline(h = lims$ylim[1], v = lims$xlim[1]);
}
}
# Ensure sufficient resolution for graphs
if (resolution < 1200) {
resolution <- 1200;
warning('Setting resolution to 1200 dpi.');
}
# Other required changes which are not accomplished here
warning('Nature also requires italicized single-letter variables and en-dashes
for ranges and negatives. See example in documentation for how to do this.');
warning('Avoid red-green colour schemes, create TIFF files, do not outline the figure or legend.');
}
# Otherwise use the BL style if requested
else if ('BoutrosLab' == style) {
# Nothing happens
}
# if neither of the above is requested, give a warning
else {
warning("The style parameter only accepts 'Nature' or 'BoutrosLab'.");
}
# output the object
return(
BoutrosLab.plotting.general::write.plot(
trellis.object = trellis.object,
filename = filename,
height = height,
width = width,
size.units = size.units,
resolution = resolution,
enable.warnings = enable.warnings,
description = description
)
);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/create.histogram.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2013 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO CREATE MANHATTANPLOTS ##############################################################
create.manhattanplot <- function(
formula, data, filename = NULL, main = NULL, main.just = 'center', main.x = 0.5, main.y = 0.5,
main.cex = 3, xlab.label = tail(sub('~', '', formula[-2]), 1), ylab.label = tail(sub('~', '', formula[-3]), 1),
xlab.cex = 2, ylab.cex = 2, xlab.col = 'black', ylab.col = 'black', xlab.top.label = NULL, xlab.top.cex = 2,
xlab.top.col = 'black', xlab.top.just = 'center', xlab.top.x = 0.5, xlab.top.y = 0, xlimits = NULL,
ylimits = NULL, xat = TRUE, yat = TRUE, xaxis.lab = NA, yaxis.lab = NA, xaxis.log = FALSE, yaxis.log = FALSE,
xaxis.cex = 1.5, yaxis.cex = 1.5, xaxis.rot = 0, yaxis.rot = 0, xaxis.fontface = 'plain', yaxis.fontface = 'plain',
xaxis.col = 'black', yaxis.col = 'black', xaxis.tck = 0, yaxis.tck = c(1, 1), horizontal = FALSE, type = 'p',
cex = 2, pch = '.', col = 'black', lwd = 1, lty = 1, alpha = 1, strip.col = 'white', strip.cex = 1,
axes.lwd = 1, axes.lty = 'dashed', key = list(text = list(lab = c(''))), legend = NULL, layout = NULL,
as.table = FALSE, x.spacing = 0, y.spacing = 0, x.relation = 'same', y.relation = 'same', top.padding = 0,
bottom.padding = 0, right.padding = 0, left.padding = 0, key.top = 0, key.left.padding = 0, ylab.axis.padding = 1,
axis.key.padding = 1, abline.h = NULL, abline.col = 'black', abline.lwd = 1, abline.lty = 1, add.rectangle = FALSE,
xleft.rectangle = NULL, ybottom.rectangle = NULL, xright.rectangle = NULL, ytop.rectangle = NULL,
col.rectangle = 'transparent', alpha.rectangle = 1, add.points = FALSE, points.x = NULL, points.y = NULL,
points.pch = 19, points.col = 'black', points.cex = 1, add.text = FALSE, text.labels = NULL, text.x = NULL,
text.y = NULL, text.col = 'black', text.cex = 1, text.fontface = 'bold', height = 6, width = 10, size.units = 'in',
resolution = 1600, enable.warnings = FALSE, style = 'BoutrosLab',
description = 'Created with BoutrosLab.plotting.general', preload.default = 'custom', use.legacy.settings = FALSE,
inside.legend.auto = FALSE, ...
) {
### needed to copy in case using variable to define rectangles dimensions
rectangle.info <- list(
xright = xright.rectangle,
xleft = xleft.rectangle,
ytop = ytop.rectangle,
ybottom = ybottom.rectangle
);
text.info <- list(
labels = text.labels,
x = text.x,
y = text.y,
col = text.col,
cex = text.cex,
fontface = text.fontface
);
out <- prep.axis(
at = xat,
data = unlist(data[toString(formula[[3]])]),
which.arg = 'xat'
);
if (is.list(out)) {
data[toString(formula[[3]])] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
out <- prep.axis(
at = yat,
data = unlist(data[toString(formula[[2]])]),
which.arg = 'yat'
);
if (is.list(out)) {
data[toString(formula[[2]])] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
# add preloaded defaults
if (preload.default == 'paper') {
}
else if (preload.default == 'web') {
}
# Now make the actual plot object
trellis.object <- lattice::xyplot(
formula,
data,
panel = function(subscripts, type.local = type, abline.local = abline, ...) {
# add rectangle
if (add.rectangle) {
panel.rect(
xleft = rectangle.info$xleft,
ybottom = rectangle.info$ybottom,
xright = rectangle.info$xright,
ytop = rectangle.info$ytop,
col = col.rectangle,
alpha = alpha.rectangle,
border = NA
);
}
# if requested, add user-defined horizontal line
if (!is.null(abline.h)) {
panel.abline(
h = abline.h,
lty = abline.lty,
lwd = abline.lwd,
col = abline.col
);
}
# create the main plot
panel.xyplot(
subscripts = subscripts,
type = setdiff(type.local, 'g'),
alpha = alpha,
horizontal = horizontal,
...
);
# Add text to plot
if (add.text) {
panel.text(
x = text.info$x,
y = text.info$y,
labels = text.info$labels,
col = text.info$col,
cex = text.info$cex,
fontface = text.info$fontface
);
}
},
type = type,
cex = cex,
pch = pch,
col = col,
lwd = lwd,
lty = lty,
main = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = main,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
cex = main.cex,
just = main.just,
x = main.x,
y = main.y
)
),
xlab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.label,
cex = xlab.cex,
col = xlab.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' }
)
),
xlab.top = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.top.label,
cex = xlab.top.cex,
col = xlab.top.col,
fontface = if ('Nature' == style) { 'plain' } else {'bold'},
just = xlab.top.just,
x = xlab.top.x,
y = xlab.top.y
)
),
ylab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = ylab.label,
cex = ylab.cex,
col = ylab.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' }
)
),
scales = list(
x = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
cex = xaxis.cex,
rot = xaxis.rot,
limits = xlimits,
fontface = if ('Nature' == style) { 'plain' } else { xaxis.fontface },
col = xaxis.col,
at = xat,
labels = xaxis.lab,
log = xaxis.log,
relation = x.relation,
alternating = FALSE,
tck = xaxis.tck
)
),
y = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
cex = yaxis.cex,
rot = yaxis.rot,
limits = ylimits,
fontface = if ('Nature' == style) { 'plain' } else { yaxis.fontface },
col = yaxis.col,
at = yat,
labels = yaxis.lab,
log = yaxis.log,
relation = y.relation,
alternating = FALSE,
tck = yaxis.tck
)
)
),
between = list(
x = x.spacing,
y = y.spacing
),
layout = layout,
as.table = as.table,
par.settings = list(
axis.line = list(
lwd = axes.lwd,
col = if ('Nature' == style) {'transparent'} else { 'black' }
),
layout.heights = list(
top.padding = top.padding,
main = if (is.null(main)) { 0.3 } else { 1 },
main.key.padding = 0.1,
key.top = key.top,
key.axis.padding = 0.1,
axis.top = 1,
axis.bottom = 1,
axis.xlab.padding = 1,
xlab = 1,
xlab.key.padding = 0.5,
key.bottom = 0.1,
key.sub.padding = 0.1,
sub = 0.1,
bottom.padding = bottom.padding
),
layout.widths = list(
left.padding = left.padding,
key.left = key.left.padding,
key.ylab.padding = 0.5,
ylab = 1,
ylab.axis.padding = ylab.axis.padding,
axis.left = 1,
axis.panel = 0.3,
strip.left = 0.3,
panel = 1,
between = 1,
axis.right = 1,
axis.key.padding = axis.key.padding,
key.right = 1,
right.padding = right.padding
),
strip.background = list(
col = strip.col
)
),
par.strip.text = list(
cex = strip.cex
),
key = key,
legend = legend
);
if (inside.legend.auto) {
extra.parameters <- list('x' = trellis.object$panel.args[[1]]$x, 'y' = trellis.object$panel.args[[1]]$y,
'ylimits' = trellis.object$y.limits, 'xlimits' = trellis.object$x.limits);
coords <- c();
coords <- .inside.auto.legend('create.manhattanplot', filename, trellis.object, height, width, extra.parameters);
trellis.object$legend$inside$x <- coords[1];
trellis.object$legend$inside$y <- coords[2];
}
# If Nature style requested, change figure accordingly
if ('Nature' == style) {
# Re-add bottom and left axes
trellis.object$axis <- function(side, line.col = 'black', ...) {
# Only draw axes on the left and bottom
if (side %in% c('bottom', 'left')) {
axis.default(side = side, line.col = 'black', ...);
lims <- current.panel.limits();
panel.abline(h = lims$ylim[1], v = lims$xlim[1]);
}
}
# Ensure sufficient resolution for graphs
if (resolution < 1200) {
resolution <- 1200;
warning('Setting resolution to 1200 dpi.');
}
# Other required changes which are not accomplished here
warning('Nature also requires italicized single-letter variables and en-dashes
for ranges and negatives. See example in documentation for how to do this.');
warning('Avoid red-green colour schemes, create TIFF files, do not outline the figure or legend.');
}
# Otherwise use the BL style if requested
else if ('BoutrosLab' == style) {
# Nothing happens
}
# if neither of the above is requested, give a warning
else {
warning("The style parameter only accepts 'Nature' or 'BoutrosLab'.");
}
# output the object
return(
BoutrosLab.plotting.general::write.plot(
trellis.object = trellis.object,
filename = filename,
height = height,
width = width,
size.units = size.units,
resolution = resolution,
enable.warnings = enable.warnings,
description = description
)
);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/create.manhattanplot.R
|
### Custom printing function for multipanel object
### This is needed because without it, the returned object is a grob which you must call grid.draw(x) on, this way, we can simply print the object.
print.multipanel <- function(x, ...) {
## set class to that of a grid object
class(x) <- c('frame', 'gTree', 'grob', 'gDesc');
## close previous items if exist
if (!is.null(dev.list()) && length(unlist(grid.ls(print = FALSE))) > 0) {
grid.remove(grid.ls(print = FALSE)$name[1], redraw = TRUE);
}
## draw the plot like a grob
grid.draw(x);
}
plot.multipanel <- print.multipanel
create.multipanelplot <- function(plot.objects = NULL, filename = NULL, height = 10, width = 10, resolution = 1000,
plot.objects.heights = c(rep(1, layout.height)), plot.objects.widths = c(rep(1, layout.width)), layout.width = 1,
layout.height = length(plot.objects), main = '', main.x = 0.5, main.y = 0.5, x.spacing = 0, y.spacing= 0,
xlab.label = '', xlab.cex = 2, ylab.label = '', ylab.label.right = '',
ylab.cex = 2, main.cex = 3, legend = NULL, left.padding = 0,
ylab.axis.padding = c(rep(0, layout.width)), xlab.axis.padding = c(rep(0, layout.height)), bottom.padding = 0,
top.padding = 0, right.padding = 0, layout.skip = c(rep(FALSE, layout.width * layout.height)), left.legend.padding = 2,
right.legend.padding = 2, bottom.legend.padding = 2, top.legend.padding = 2,
description = 'Created with BoutrosLab.plotting.general', size.units = 'in', enable.warnings = FALSE, style= 'BoutrosLab',
use.legacy.settings = FALSE) {
## make axis.padding appropriate length if only 1 value specified
if (1 == length(ylab.axis.padding)) {
ylab.axis.padding <- rep(ylab.axis.padding, layout.width);
}
if (1 == length(xlab.axis.padding)) {
xlab.axis.padding <- rep(xlab.axis.padding, layout.height);
}
### ERROR CHECKING ###
if (length(plot.objects.heights) != layout.height) {
stop('plot.objects.heights must have layout.height number of entries');
}
if (length(plot.objects.widths) != layout.width) {
stop('plot.objects.widths must have layout.width number of entries');
}
if (length(layout.skip) != layout.width * layout.height) {
stop('layout.skip must have same number of entries as layout.width * layout.height');
}
if (!is.list(plot.objects)) {
stop('plot.objects must be a list');
}
if (length(ylab.axis.padding) != layout.width) {
stop('ylab.axis.padding must be the same size as layout.width');
}
if (length(xlab.axis.padding) != layout.height) {
stop('xlab.axis.padding must be the same size as layout.height');
}
if (is.null(ylab.label)) ylab.label <- ''
if (is.null(xlab.label)) xlab.label <- ''
padding.text.to.padding.ratio <- 6.04; # this is used to align plots with diffrent label sizes
tick.to.padding.ratio <- 0.9484252; # this is used to evaluate length of ticks (is equivalent to 1mm)
additional.padding <- 1; # this is additional padding for labels that goes above calculation (takes care of overhanging values)
### MINOR ADJUSTMENTS TO MAKE VALUES SEEM MORE LOGICAL
x.spacing <- x.spacing / 10;
y.spacing <- y.spacing / 10;
### HANDLE SKIP LAYOUT ###
newplots <- list();
plotnum <- 1;
## ADD BLANKS FOR LAYOUT.SKIP
for (i in c(1:(layout.width * layout.height))) {
if (plotnum <= length(plot.objects) && FALSE == layout.skip[i]) {
newplots[i] <- plot.objects[plotnum];
plotnum <- plotnum + 1;
}
else {
newplots[[i]] <- rectGrob(gp = gpar(col = 'white', alpha = 0));
}
}
plot.objects <- newplots;
layout.height <- layout.height * 2;
layout.width <- layout.width * 2;
newplots <- list();
plotnum <- 1;
### ADD IN BETWEEN GROBS TO REPRESENT X AND Y SPACING (PREVENTS PUSHING OF EDGE PLOTS)
for (k in c(1:layout.height)) {
for (i in c(1:layout.width)) {
if (0 == i %% 2 || 0 == k %% 2) {
newplots[[i + (k - 1) * (layout.width)]] <- rectGrob(gp = gpar(col = 'white', alpha = 0));
}
else {
newplots[i + (k - 1) * (layout.width)] <- plot.objects[plotnum];
plotnum <- plotnum + 1;
}
}
}
plot.objects <- newplots;
### PAR SETTINGS EQUIVALENT ###
for (i in c(1:length(plot.objects))) {
# make all paddings the same (in order to line them up) -- needed or plots wont line up properly
if (!is.null(plot.objects[[i]]$par.settings)) {
plot.objects[[i]]$par.settings$layout.widths$left.padding <- 0;
plot.objects[[i]]$par.settings$layout.widths$key.left <- 1;
plot.objects[[i]]$par.settings$layout.widths$key.ylab.padding <- 1;
plot.objects[[i]]$par.settings$layout.widths$ylab <- 1;
plot.objects[[i]]$par.settings$layout.widths$ylab.axis.padding <- 0;
plot.objects[[i]]$par.settings$layout.widths$axis.left <- 0;
plot.objects[[i]]$par.settings$layout.widths$axis.right <- 0;
plot.objects[[i]]$par.settings$layout.widths$axis.key.padding <- 1;
plot.objects[[i]]$par.settings$layout.widths$key.right <- 1;
plot.objects[[i]]$par.settings$layout.widths$right.padding <- 0;
plot.objects[[i]]$par.settings$layout.heights$top.padding <- 0;
plot.objects[[i]]$par.settings$layout.heights$main <- 1;
plot.objects[[i]]$par.settings$layout.heights$main.key.padding <- 1;
plot.objects[[i]]$par.settings$layout.heights$key.top <- 1;
plot.objects[[i]]$par.settings$layout.heights$key.axis.padding <- 1;
plot.objects[[i]]$par.settings$layout.heights$axis.top <- 0;
plot.objects[[i]]$par.settings$layout.heights$axis.bottom <- 0;
plot.objects[[i]]$par.settings$layout.heights$axis.xlab.padding <- 0;
plot.objects[[i]]$par.settings$layout.heights$xlab <- 1;
plot.objects[[i]]$par.settings$layout.heights$xlab.key.padding <- 1;
plot.objects[[i]]$par.settings$layout.heights$key.bottom <- 1;
plot.objects[[i]]$par.settings$layout.heights$key.sub.padding <- 0;
plot.objects[[i]]$par.settings$layout.heights$sub <- 0;
plot.objects[[i]]$par.settings$layout.heights$bottom.padding <- 0;
if (use.legacy.settings) {
plot.objects[[i]]$main$fontfamily <- 'Arial';
plot.objects[[i]]$ylab$fontfamily <- 'Arial';
plot.objects[[i]]$xlab$fontfamily <- 'Arial';
plot.objects[[i]]$xlab.top$fontfamily <- 'Arial';
plot.objects[[i]]$x.scales$fontfamily <- 'Arial';
plot.objects[[i]]$y.scales$fontfamily <- 'Arial';
}
}
}
### SPACING #####
#make y spacing into an array of proper length
if (1 == length(y.spacing)) {
y.spacing <- rep(y.spacing, layout.height / 2);
}
if (1 == length(x.spacing)) {
x.spacing <- rep(x.spacing, layout.width / 2);
}
# adjust widths to accuratly using the x and y spacing values
plot.objects.widths <- as.vector(rbind(plot.objects.widths, x.spacing));
plot.objects.heights <- as.vector(rbind(plot.objects.heights, y.spacing));
plot.objects.heights[length(plot.objects.heights)] <- 0;
plot.objects.widths[length(plot.objects.widths)] <- 0;
### PADDING ####
#variables to represent amount of padding needed
### X AND Y PLOT AXIS LABELS
largest.y.axis <- list();
largest.x.axis <- list();
largest.top.x.axis <- list();
### TICKS
left.ticks <- list();
bottom.ticks <- list();
### X AND Y AXIS LABELS
y.label.size <- list();
x.label.size <- list();
### MAIN PLOT LABEL
main.size <- list();
### LEGENDS
left.legend <- 0;
right.legend <- 0;
bottom.legend <- 0;
top.legend <- 0;
for (i in c(1:length(plot.objects))) {
largest.y.axis[i] <- 0;
left.ticks[i] <- 0;
largest.x.axis[i] <- 0;
bottom.ticks[i] <- 0;
x.label.size[i] <- 0;
y.label.size[i] <- 0;
main.size[i] <- 0;
left.legend[i] <- 0;
right.legend[i] <- 0;
top.legend[i] <- 0;
bottom.legend[i] <- 0;
largest.top.x.axis[i] <- 0;
# set variables for each plot according to their respective plot values
if (!is.null(plot.objects[[i]]$par.settings)) {
### GET GROB INFO FOR SIMPLE VARS
top.legend[i] <- get.legend.height(plot.objects[[i]]$legend$top, filename, width, height, resolution);
bottom.legend[i] <- get.legend.height(plot.objects[[i]]$legend$bottom, filename, width, height, resolution);
left.legend[i] <- get.legend.width(plot.objects[[i]]$legend$left, filename, width, height, resolution);
right.legend[i] <- get.legend.width(plot.objects[[i]]$legend$right, filename, width, height, resolution);
main.size[i] <- get.text.grob.height(plot.objects[[i]]$main$label, plot.objects[[i]]$main$cex,
0, filename, width, height, resolution);
y.label.size[i] <- get.text.grob.width(plot.objects[[i]]$ylab$label, plot.objects[[i]]$ylab$cex,
90, filename, width, height, resolution);
x.label.size[i] <- get.text.grob.height(plot.objects[[i]]$xlab$label, plot.objects[[i]]$xlab$cex,
0, filename, width, height, resolution);
left.ticks[i] <- plot.objects[[i]]$y.scales$tck[1] * tick.to.padding.ratio;
bottom.ticks[i] <- plot.objects[[i]]$x.scales$tck[1] * tick.to.padding.ratio;
## from data and labels -- get the actual labels that will be in plot as strings
y.axis.labs <- reformat.labels(plot.objects[[i]]$y.scales$labels, plot.objects[[i]]$panel.args[[1]]$y);
x.axis.labs <- reformat.labels(plot.objects[[i]]$x.scales$labels, plot.objects[[i]]$panel.args[[1]]$x);
x.axis.top.labs <- reformat.labels(plot.objects[[i]]$xlab.top$label, NULL);
largest.y.axis[i] <- get.text.grob.width(
y.axis.labs,
plot.objects[[i]]$y.scales$cex,
plot.objects[[i]]$y.scales$rot[1],
filename,
width,
height,
resolution
);
largest.x.axis[i] <- get.text.grob.height(
x.axis.labs,
plot.objects[[i]]$x.scales$cex,
plot.objects[[i]]$x.scales$rot[1],
filename,
width,
height,
resolution
);
largest.top.x.axis[i] <- get.text.grob.height(
x.axis.top.labs,
plot.objects[[i]]$xlab.top$cex,
0,
filename,
width,
height,
resolution
);
}
}
# add the correct amount of padding to each plot based on the column (use ylab axis)
for (i in c(1:layout.width)) {
max.axis <- max(unlist(largest.y.axis[seq(i, length(plot.objects), layout.width)]));
max.ticks <- max(unlist(left.ticks[seq(i, length(plot.objects), layout.width)]));
max.labels <- max(unlist(y.label.size[seq(i, length(plot.objects), layout.width)]));
max.right.legend <- max(unlist(right.legend[seq(i, length(plot.objects), layout.width)]));
max.left.legend <- max(unlist(left.legend[seq(i, length(plot.objects), layout.width)]));
for (j in seq(i, length(plot.objects), layout.width)) {
diff.max.labels <- abs(max.labels - y.label.size[[j]]);
to.add <- (max.axis + diff.max.labels + max.labels/2) / padding.text.to.padding.ratio + max.ticks + additional.padding;
if (!is.null(plot.objects[[j]]$par.settings)) {
diff.right.legend <- abs(right.legend[j] - max.right.legend) / padding.text.to.padding.ratio;
diff.left.legend <- abs(left.legend[j] - max.left.legend) / padding.text.to.padding.ratio;
#if(diff.right.legend != 0) {diff.right.legend <- diff.right.legend + 1 / padding.text.to.padding.ratio}
if(diff.left.legend != 0) {diff.left.legend <- diff.left.legend + 1 / padding.text.to.padding.ratio}
### if has legend, must account for minor key padding
plot.objects[[j]]$par.settings$layout.widths$ylab.axis.padding <- ylab.axis.padding[ceiling(i / 2)] + to.add;
plot.objects[[j]]$par.settings$layout.widths$left.padding <- plot.objects[[j]]$par.settings$layout.widths$left.padding + diff.left.legend;
plot.objects[[j]]$par.settings$layout.widths$right.padding <- plot.objects[[j]]$par.settings$layout.widths$right.padding + diff.right.legend;
}
}
}
# add the correct amount of padding to each plot based on the row (use xlab axis)
for (i in seq(1, length(plot.objects), layout.width)) {
max.axis <- max(unlist(largest.x.axis[seq(i, i + layout.width - 1, 1)]));
max.ticks <- max(unlist(bottom.ticks[seq(i, i + layout.width - 1, 1)]));
max.labels <- max(unlist(x.label.size[seq(i, i + layout.width - 1, 1)]));
max.main <- max(unlist(main.size[seq(i, i + layout.width - 1, 1)])) / 2;
max.top.legend <- max(unlist(top.legend[seq(i, i + layout.width - 1, 1)]));
max.bottom.legend <- max(unlist(bottom.legend[seq(i, i + layout.width - 1, 1)]));
max.axis.top <- max(unlist(largest.top.x.axis[seq(i, i + layout.width - 1, 1)]));
for (j in c(i:(i + layout.width - 1))) {
diff.max.labels <- abs(max.labels - x.label.size[[j]]);
to.add <- (max.axis + diff.max.labels + max.labels/2) / padding.text.to.padding.ratio + max.ticks + additional.padding;
if (j <= length(plot.objects) && !is.null(plot.objects[[j]]$par.settings)) {
diff.top.legend <- abs(top.legend[j] - max.top.legend) / padding.text.to.padding.ratio;
diff.bottom.legend <- abs(bottom.legend[j] - max.bottom.legend) / padding.text.to.padding.ratio;
diff.axis.top <- abs(largest.top.x.axis[[j]] - max.axis.top) / padding.text.to.padding.ratio;
#if(diff.top.legend != 0) {diff.top.legend <- diff.top.legend + 1 / padding.text.to.padding.ratio}
if(diff.bottom.legend != 0) {diff.bottom.legend <- diff.bottom.legend + 1 / padding.text.to.padding.ratio}
### if has legend, must account for minor key padding
plot.objects[[j]]$par.settings$layout.heights$axis.xlab.padding <- xlab.axis.padding[ceiling(i / (layout.width * 2))] + to.add;
if (max.main != 0 && (is.null(plot.objects[[j]]$main$label) || nchar(plot.objects[[j]]$main$label) == 0)) {
plot.objects[[j]]$main$label <- '\t'; #make sure it thinks a label is there
}
plot.objects[[j]]$par.settings$layout.heights$top.padding <- plot.objects[[j]]$par.settings$layout.heights$top.padding + diff.top.legend + diff.axis.top;
plot.objects[[j]]$par.settings$layout.heights$bottom.padding <-
plot.objects[[j]]$par.settings$layout.heights$bottom.padding + diff.bottom.legend;
plot.objects[[j]]$par.settings$layout.heights$main.key.padding <-
plot.objects[[j]]$par.settings$layout.heights$main.key.padding + (max.main / padding.text.to.padding.ratio);
}
}
}
#grobs representing main labels on each side
main.label <- textGrob(main, gp = gpar(cex = main.cex, fontface = 'bold',
fontfamily = get.defaults(property = 'fontfamily', use.legacy.settings = use.legacy.settings || ('Nature' == style))),
x = main.x,
y = main.y);
y.label <- textGrob(ylab.label, gp = gpar(cex = ylab.cex, fontface = 'bold',
fontfamily = get.defaults(property = 'fontfamily', use.legacy.settings = use.legacy.settings || ('Nature' == style))),
rot = 90);
y.label.right <- textGrob(ylab.label.right, gp = gpar(cex = ylab.cex, fontface = 'bold',
fontfamily = get.defaults(property = 'fontfamily', use.legacy.settings = use.legacy.settings || ('Nature' == style))),
rot = -90);
x.label <- textGrob(xlab.label, gp = gpar(cex = xlab.cex, fontface = 'bold',
fontfamily = get.defaults( property = 'fontfamily', use.legacy.settings = use.legacy.settings || ('Nature' == style)))
);
### IF LEGENDS ARE KEYS, MUST BE MADE INTO GROBS FIRST
if (identical(legend$left$fun, draw.key) || identical(legend$left$fun, draw.colorkey)) {
legend$left$fun <- do.call(legend$left$fun, list(key = legend$left$args$key));
}
if (identical(legend$right$fun, draw.key) || identical(legend$right$fun, draw.colorkey)) {
legend$right$fun <- do.call(legend$right$fun, list(key = legend$right$args$key));
}
if (identical(legend$bottom$fun, draw.key) || identical(legend$bottom$fun, draw.colorkey)) {
legend$bottom$fun <- do.call(legend$bottom$fun, list(key = legend$bottom$args$key));
}
if (identical(legend$top$fun, draw.key) || identical(legend$top$fun, draw.colorkey)) {
legend$top$fun <- do.call(legend$top$fun, list(key = legend$top$args$key));
}
if (identical(legend$inside$fun, draw.key) || identical(legend$inside$fun, draw.colorkey)) {
legend$inside$fun <- do.call(legend$inside$fun, list(key = legend$inside$args$key));
}
### LEFT,RIGHT,TOP,BOTTOM GROBS ############
### LEFT GROB
if (!is.null(legend$left$fun)) {
width.legend <- convertUnit(
grobWidth(legend$left$fun),
unitTo = 'lines',
axisFrom = 'x',
typeFrom = 'dimension',
valueOnly = TRUE
);
width.text <- 0;
if (nchar(ylab.label) > 0) {
width.text <- convertUnit(
grobWidth(y.label),
unitTo = 'lines',
axisFrom = 'x',
typeFrom = 'dimension',
valueOnly = TRUE
);
}
left.layout.final <- grid.layout(
nrow = 1,
ncol = 4,
widths = unit(
x = c(left.padding, width.text, width.legend, left.legend.padding),
units = c('lines', 'lines', 'lines', 'lines')
),
heights = unit(1, 'null'),
respect = FALSE
);
left.grob <- frameGrob(layout = left.layout.final);
left.grob <- placeGrob(
frame = left.grob,
grob = rectGrob(gp = gpar(col = 'white', alpha = 0)),
row = 1,
col = 1
);
left.grob <- placeGrob(
frame = left.grob,
grob = y.label,
row = 1,
col = 2
);
left.grob <- placeGrob(
frame = left.grob,
grob = legend$left$fun,
row = 1,
col = 3
);
left.grob <- placeGrob(
frame = left.grob,
grob = rectGrob(gp = gpar(col = 'white', alpha = 0)),
row = 1,
col = 4
);
}
else {
width.text <- 0;
if (nchar(ylab.label) > 0) {
width.text <- convertUnit(
grobWidth(y.label),
unitTo = 'lines',
axisFrom = 'x',
typeFrom = 'dimension',
valueOnly = TRUE
);
}
left.layout.final <- grid.layout(
nrow = 1,
ncol = 3,
widths = unit(
x = c(left.padding, width.text, left.legend.padding),
units = c('lines', 'lines', 'lines')
),
heights = unit(1, 'null'),
respect = FALSE
);
left.grob <- frameGrob(layout = left.layout.final);
left.grob <- placeGrob(
frame = left.grob,
grob = rectGrob(gp = gpar(col = 'white', alpha = 0)),
row = 1,
col = 1
);
left.grob <- placeGrob(
frame = left.grob,
grob = y.label,
row = 1,
col = 2
);
left.grob <- placeGrob(
frame = left.grob,
grob = rectGrob(gp = gpar(col = 'white', alpha = 0)),
row = 1,
col = 3
);
}
### RIGHT GROB
if (!is.null(legend$right$fun)) {
width.legend <- convertUnit(
grobWidth(legend$right$fun),
unitTo = 'lines',
axisFrom = 'x',
typeFrom = 'dimension',
valueOnly = TRUE
);
width.text <- 0;
if (nchar(ylab.label.right) > 0) {
width.text <- convertUnit(
grobWidth(y.label.right),
unitTo = 'lines',
axisFrom = 'x',
typeFrom = 'dimension',
valueOnly = TRUE
);
}
right.layout.final <- grid.layout(
nrow = 1,
ncol = 4,
widths = unit(
x = c(right.legend.padding, width.legend, width.text, right.padding),
units = c('lines', 'lines', 'lines', 'lines')
),
heights = unit(1, 'null'),
respect = FALSE
);
right.grob <- frameGrob(layout = right.layout.final);
right.grob <- placeGrob(
frame = right.grob,
grob = rectGrob(gp = gpar(col = 'white', alpha = 0)),
row = 1,
col = 1
);
right.grob <- placeGrob(
frame = right.grob,
grob = legend$right$fun,
row = 1,
col = 2
);
right.grob <- placeGrob(
frame = right.grob,
grob = y.label.right,
row = 1,
col = 3
);
right.grob <- placeGrob(
frame = right.grob,
grob = rectGrob(gp = gpar(col = 'white', alpha = 0)),
row = 1,
col = 4
);
}
else {
width.text <- 0;
if (nchar(ylab.label.right) > 0) {
width.text <- convertUnit(
grobWidth(y.label.right),
unitTo = 'lines',
axisFrom = 'x',
typeFrom = 'dimension',
valueOnly = TRUE
);
}
right.layout.final <- grid.layout(
nrow = 1,
ncol = 3,
widths = unit(
x = c(right.legend.padding, width.text, right.padding),
units = c('lines', 'lines', 'lines')
),
heights = unit(1, 'null'),
respect = FALSE
);
right.grob <- frameGrob(layout = right.layout.final);
right.grob <- placeGrob(
frame = right.grob,
grob = rectGrob(gp = gpar(col = 'white', alpha = 0)),
row = 1,
col = 1
);
right.grob <- placeGrob(
frame = right.grob,
grob = y.label.right,
row = 1,
col = 2
);
right.grob <- placeGrob(
frame = right.grob,
grob = rectGrob(gp = gpar(col = 'white', alpha = 0)),
row = 1,
col = 3
);
}
### BOTTOM GROB
if (!is.null(legend$bottom$fun)) {
height.legend <- convertUnit(
grobHeight(legend$bottom$fun),
unitTo = 'lines',
axisFrom = 'x',
typeFrom = 'dimension',
valueOnly = TRUE
);
height.text <- 0;
if (nchar(xlab.label) > 0) {
height.text <- convertUnit(
grobHeight(x.label),
unitTo = 'lines',
axisFrom = 'x',
typeFrom = 'dimension',
valueOnly = TRUE
);
}
bottom.layout.final <- grid.layout(
nrow = 4,
ncol = 1,
heights = unit(
x = c(bottom.legend.padding, height.legend, height.text, bottom.padding),
units = c('lines', 'lines', 'lines', 'lines')
),
widths = unit(1, 'null'),
respect = FALSE
);
bottom.grob <- frameGrob(layout = bottom.layout.final);
bottom.grob <- placeGrob(
frame = bottom.grob,
grob = rectGrob(gp = gpar(col = 'white', alpha = 0)),
row = 1,
col = 1
);
bottom.grob <- placeGrob(
frame = bottom.grob,
grob = legend$bottom$fun,
row = 2,
col = 1
);
bottom.grob <- placeGrob(
frame = bottom.grob,
grob = x.label,
row = 3,
col = 1
);
bottom.grob <- placeGrob(
frame = bottom.grob,
grob = rectGrob(gp = gpar(col = 'white', alpha = 0)),
row = 4,
col = 1
);
}
else {
height.text <- 0;
if (nchar(xlab.label) > 0) {
height.text <- convertUnit(
grobHeight(x.label),
unitTo = 'lines',
axisFrom = 'x',
typeFrom = 'dimension',
valueOnly = TRUE
);
}
bottom.layout.final <- grid.layout(
nrow = 4,
ncol = 1,
heights = unit(
x = c(bottom.legend.padding, height.text, bottom.padding),
units = c('lines', 'lines', 'lines')
),
widths = unit(1, 'null'),
respect = FALSE
);
bottom.grob <- frameGrob(layout = bottom.layout.final);
bottom.grob <- placeGrob(
frame = bottom.grob,
grob = rectGrob(gp = gpar(col = 'white', alpha = 0)),
row = 1,
col = 1
);
bottom.grob <- placeGrob(
frame = bottom.grob,
grob = x.label,
row = 2,
col = 1
);
bottom.grob <- placeGrob(
frame = bottom.grob,
grob = rectGrob(gp = gpar(col = 'white', alpha = 0)),
row = 3,
col = 1
);
}
### TOP GROB
if (!is.null(legend$top$fun)) {
height.legend <- convertUnit(
grobHeight(legend$top$fun),
unitTo = 'lines',
axisFrom = 'x',
typeFrom = 'dimension',
valueOnly = TRUE
);
height.text <- 0;
if (nchar(main) > 0) {
height.text <- convertUnit(
grobHeight(main.label),
unitTo = 'lines',
axisFrom = 'x',
typeFrom = 'dimension',
valueOnly = TRUE
);
}
top.layout.final <- grid.layout(
nrow = 4,
ncol = 1,
heights = unit(
x = c(top.padding, height.text, height.legend, top.legend.padding),
units = c('lines', 'lines', 'lines', 'lines')
),
widths = unit(1, 'null'),
respect = FALSE
);
top.grob <- frameGrob(layout = top.layout.final);
top.grob <- placeGrob(
frame = top.grob,
grob = rectGrob(gp = gpar(col = 'white', alpha = 0)),
row = 1,
col = 1
);
top.grob <- placeGrob(
frame = top.grob,
grob = rectGrob(gp = gpar(col = 'white', alpha = 0)),
row = 3,
col = 1
);
top.grob <- placeGrob(
frame = top.grob,
grob = main.label,
row = 2,
col = 1
);
top.grob <- placeGrob(
frame = top.grob,
grob = legend$top$fun,
row = 4,
col = 1
);
}
else {
height.text <- 0;
if (nchar(main) > 0) {
height.text <- convertUnit(
grobHeight(main.label),
unitTo = 'lines',
axisFrom = 'x',
typeFrom = 'dimension',
valueOnly = TRUE
);
}
top.layout.final <- grid.layout(
nrow = 3,
ncol = 1,
heights = unit(
x = c(top.padding, height.text, top.legend.padding),
units = c('lines', 'lines', 'lines')
),
widths = unit(1, 'null'),
respect = FALSE
);
top.grob <- frameGrob(layout = top.layout.final);
top.grob <- placeGrob(
frame = top.grob,
grob = rectGrob(gp = gpar(col = 'white', alpha = 0)),
row = 2,
col = 1
);
top.grob <- placeGrob(
frame = top.grob,
grob = rectGrob(gp = gpar(col = 'white', alpha = 0)),
row = 1,
col = 1
);
top.grob <- placeGrob(
frame = top.grob,
grob = main.label,
row = 3,
col = 1
);
}
# create grob of all plots
grob <- arrangeGrob(
grobs = plot.objects,
heights = plot.objects.heights,
widths = plot.objects.widths,
ncol = layout.width,
nrow = layout.height,
top = top.grob,
left = left.grob,
bottom = bottom.grob,
right = right.grob
);
## Add white background color
grob <- gtable_add_grob(grob, grobs = rectGrob(gp = gpar(fill = 'white', lwd = 0)), 1, 1, nrow(grob), ncol(grob), 0);
grob.layout <- grid.layout(1,1);
grob.frame <- frameGrob(layout = grob.layout);
grob.frame <- placeGrob(grob.frame,grob);
#### INSIDE GROBS
if (!is.null(legend$inside$fun)) {
if (!is.null(legend$inside$x)) {
legend$inside$fun$framevp$x <- unit(legend$inside$x, 'npc');
}
if (!is.null(legend$inside$y)) {
legend$inside$fun$framevp$y <- unit(legend$inside$y, 'npc');
}
## add the inside legend to a frameGrob
grob.frame <- placeGrob(grob.frame,legend$inside$fun);
}
grob <- grob.frame;
# If Nature style requested, change figure accordingly
if ('Nature' == style) {
# Ensure sufficient resolution for graphs
if (resolution < 1200) {
resolution <- 1200;
warning('Setting resolution to 1200 dpi.');
}
# Other required changes which are not accomplished here
warning('Nature also requires italicized single-letter variables and en-dashes for ranges and negatives.
See example in documentation for how to do this.');
warning('Avoid red-green colour schemes, create TIFF files, do not outline the figure or legend');
}
class(grob) <- 'multipanel';
# return grob
if (!is.null(filename)) {
BoutrosLab.plotting.general::write.plot(
trellis.object = grob,
filename = filename,
height = height,
width = width,
size.units = size.units,
resolution = resolution,
enable.warnings = enable.warnings,
description = description
);
}
else {
# return grob itself
return(grob);
}
}
### Labels can get a bit weird because they come in many shapes and forms
### (i.e, expressions, NA, NULL....) --- this is intended to check for all those
## from data and labels -- get the actual labels that will be in plot as strings
reformat.labels <- function(labels, data.values) {
if (is.expression(labels[1])) {
y.axis.labs <- labels;
}
else if (is.null(labels) || anyNA(labels) || (length(labels) == 1 && labels == TRUE)) {
if (!is.null(data.values)) {
if (!is.null(levels(data.values))) {
y.axis.labs <- levels(data.values);
}
else {
yvals <- as.numeric(data.values);
y.axis.labs <- pretty(yvals[is.finite(yvals)]);
}
}
else {
y.axis.labs <- '';
}
}
else {
y.axis.labs <- labels;
}
return(y.axis.labs);
}
get.legend.height <- function(legend, filename, width, height, resolution) {
if (is.element('function', class(legend$fun))) {
#if (class(legend$fun) == 'function') {
legend$fun <- do.call(legend$fun, legend$args);
}
#grob size depends on image type and size -- must simulate opening the device
extension <- file_ext(filename);
if (!is.null(filename)) {
# cairo is not available on M1 Macs, so fallback to default if necessary
bitmap.type <- getOption('bitmapType')
if (capabilities('cairo')) {
bitmap.type <- 'cairo'
}
if ('tiff' == extension) {
tiff(filename = paste0(tempdir(),'/temp-multipanel'), type = bitmap.type, height = height, width = width, res = resolution);
}
else if ('png' == extension) {
png(filename = paste0(tempdir(),'/temp-multipanel'), type = bitmap.type, height = height, width = width, res = resolution);
}
else if ('pdf' == extension) {
cairo_pdf(filename = paste0(tempdir(),'/temp-multipanel'), height = height, width = width);
}
else if ('svg' == extension) {
svg(filename = paste0(tempdir(),'/temp-multipanel'), height = height, width = width);
}
else if ('eps' == extension) {
postscript(height = height, width = width);
}
else {
stop('File type not supported');
}
}
if (is.null(legend)) {
height.legend <- 0;
}
else if (is.grob(legend$fun)) {
height.legend <- convertUnit(
grobHeight(legend$fun),
unitTo = 'points',
axisFrom = 'y',
typeFrom = 'dimension'
);
}
else {
grob <- do.call(legend$fun, list(key = legend$args$key, draw = FALSE));
height.legend <- convertUnit(
grobHeight(grob),
unitTo = 'points',
axisFrom = 'y',
typeFrom = 'dimension'
);
}
if (!is.null(filename)) {
dev.off()
}
return(as.integer(height.legend));
}
get.legend.width <- function(legend, filename, width, height, resolution) {
if (is.element('function', class(legend$fun))) {
legend$fun <- do.call(legend$fun, legend$args);
}
#grob size depends on image type and size -- must simulate opening the device
extension <- file_ext(filename);
if (!is.null(filename)) {
# cairo is not available on M1 Macs, so fallback to default if necessary
bitmap.type <- getOption('bitmapType')
if (capabilities('cairo')) {
bitmap.type <- 'cairo'
}
if ('tiff' == extension) {
tiff(filename = paste0(tempdir(),'/temp-multipanel'), type = bitmap.type, height = height, width = width, res = resolution);
}
else if ('png' == extension) {
png(filename = paste0(tempdir(),'/temp-multipanel'), type = bitmap.type, height = height, width = width, res = resolution);
}
else if ('pdf' == extension) {
cairo_pdf(filename = paste0(tempdir(),'/temp-multipanel'), height = height, width = width);
}
else if ('svg' == extension) {
svg(filename = paste0(tempdir(),'/temp-multipanel'), height = height, width = width);
}
else if ('eps' == extension) {
postscript(height = height, width = width);
}
else {
stop('File type not supported');
}
}
if (is.null(legend)) {
width.legend <- 0;
}
else if (is.grob(legend$fun)) {
width.legend <- convertUnit(
grobWidth(legend$fun),
unitTo = 'points',
axisFrom = 'x',
typeFrom = 'dimension'
);
}
else {
grob <- do.call(legend$fun, list(key = legend$args$key, draw = FALSE));
width.legend <- convertUnit(
grobWidth(grob),
unitTo = 'points',
axisFrom = 'x',
typeFrom = 'dimension'
);
}
if (!is.null(filename)) {
dev.off();
}
return(as.integer(width.legend));
}
### function to get the grob width given the text and specification parameters##
get.text.grob.width <- function(labels, cex, rot, filename, width, height, resolution) {
#grob size depends on image type and size -- must simulate opening the device
if (is.null(labels)) {
return(0);
}
extension <- file_ext(filename);
if (!is.null(filename)) {
# cairo is not available on M1 Macs, so fallback to default if necessary
bitmap.type <- getOption('bitmapType')
if (capabilities('cairo')) {
bitmap.type <- 'cairo'
}
if ('tiff' == extension) {
tiff(filename = paste0(tempdir(),'/temp-multipanel'), type = bitmap.type, height = height, width = width, res = resolution);
}
else if ('png' == extension) {
png(filename = paste0(tempdir(),'/temp-multipanel'), type = bitmap.type, height = height, width = width, res = resolution);
}
else if ('pdf' == extension) {
cairo_pdf(filename = paste0(tempdir(),'/temp-multipanel'), height = height, width = width);
}
else if ('svg' == extension) {
svg(filename = paste0(tempdir(),'/temp-multipanel'), height = height, width = width);
}
else if ('eps' == extension) {
postscript(height = height, width = width);
}
else {
stop('File type not supported');
}
}
# if not an empty label or all blank, create the grob, and get its width
if (0 < length(labels) && !(all('' == as.character(labels)))) {
grob <- textGrob(labels, gp = gpar(cex = cex, lineheight = 1), rot = rot, x = c(rep(0.5, length(labels))), y = c(rep(0.5, length(labels))));
width.grob <- convertUnit(
grobWidth(grob),
unitTo = 'points',
axisFrom = 'x',
typeFrom = 'dimension',
valueOnly = TRUE
);
}
else {
width.grob <- 0;
}
### make sure to turn off the dev or we will have one open for every time this is called
if (!is.null(filename)) {
dev.off();
}
return(width.grob);
}
### function to get the grob height given the text and specification parameters##
get.text.grob.height <- function(labels, cex, rot, filename, width, height, resolution) {
#grob size depends on image type and size -- must simulate opening the device
if (is.null(labels)) {
return(0);
}
extension <- file_ext(filename);
if (!is.null(filename)) {
# cairo is not available on M1 Macs, so fallback to default if necessary
bitmap.type <- getOption('bitmapType')
if (capabilities('cairo')) {
bitmap.type <- 'cairo'
}
if ('tiff' == extension) {
tiff(filename = paste0(tempdir(),'/temp-multipanel'), type = bitmap.type, height = height, width = width, res = resolution);
}
else if ('png' == extension) {
png(filename = paste0(tempdir(),'/temp-multipanel'), type = bitmap.type, height = height, width = width, res = resolution);
}
else if ('pdf' == extension) {
cairo_pdf(filename = paste0(tempdir(),'/temp-multipanel'), height = height, width = width);
}
else if ('svg' == extension) {
svg(filename = paste0(tempdir(),'/temp-multipanel'), height = height, width = width);
}
else if ('eps' == extension) {
postscript(height = height, width = width);
}
else {
stop('File type not supported');
}
}
# if not an empty label or all blank, create the grob, and get its height
if (0 < length(labels) && !(all('' == as.character(labels)))) {
grob <- textGrob(labels, gp = gpar(cex = cex, lineheight = 1), rot = rot, x = c(rep(0.5, length(labels))), y = c(rep(0.5, length(labels))));
height.grob <- convertUnit(
grobHeight(grob),
unitTo = 'points',
axisFrom = 'y',
typeFrom = 'dimension',
valueOnly = TRUE
);
}
else {
height.grob <- 0;
}
### make sure to turn off the dev or we will have one open for every time this is called
if (!is.null(filename)) {
dev.off();
}
return(height.grob);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/create.multipanelplot.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2013 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO CREATE MULTIPLOT ###################################################################
create.multiplot <- function(plot.objects, filename = NULL, panel.heights = c(1, 1), panel.widths = 1, main = NULL,
main.just = 'center', main.x = 0.5, main.y = 0.5, main.cex = 3, main.key.padding = 1,
ylab.padding = 5, xlab.padding = 5, xlab.to.xaxis.padding = 2, right.padding = 1,
left.padding = 1, top.padding = 0.5, bottom.padding = 0.5, xlab.label = NULL,
ylab.label = NULL, xlab.cex = 2, ylab.cex = 2, xlab.top.label = NULL, xaxis.top.tck.lab = NULL, xat.top = TRUE, xlab.top.cex = 2,
xaxis.top.idx = NULL, xlab.top.col = 'black', xlab.top.just = 'center', xlab.top.x = 0.5, xlab.top.y = 0,
xaxis.cex = 1.5, yaxis.cex = 1.5, xaxis.labels = TRUE, yaxis.labels = TRUE,
xaxis.alternating = 1, yaxis.alternating = 1, xat = TRUE, yat = TRUE, xlimits = NULL,
ylimits = NULL, xaxis.rot = 0, xaxis.rot.top = 0, xaxis.fontface = 'bold', y.tck.dist=0.5, x.tck.dist=0.5, yaxis.fontface = 'bold',
x.spacing = 1, y.spacing = 1, x.relation = 'same', y.relation = 'same',
xaxis.tck = c(0.75, 0.75), yaxis.tck = c(0.75, 0.75), axes.lwd = 1.5, key.right.padding = 1,
key.left.padding = 1, key.bottom.padding = 1, xlab.key.padding = 0.5, height = 6, width = 6, size.units = 'in',
resolution = 1600, enable.warnings = FALSE, key = list(text = list(lab = c(''))),
legend = NULL, print.new.legend = FALSE, merge.legends = FALSE,
plot.layout = c(1, length(plot.objects)), layout.skip = rep(FALSE, length(plot.objects)),
description = 'Created with BoutrosLab.plotting.general',
plot.labels.to.retrieve = NULL, style = 'BoutrosLab', remove.all.border.lines = FALSE,
preload.default = 'custom', plot.for.carry.over.when.same = 1, get.dendrogram.from = NULL,
dendrogram.right.size = NULL, dendrogram.right.x = NULL, dendrogram.right.y = NULL,
dendrogram.top.size = NULL, dendrogram.top.x = NULL, dendrogram.top.y = NULL, use.legacy.settings = FALSE) {
if (preload.default == 'paper') {
}
else if (preload.default == 'web') {
}
# check that plots are trellis objects
for (i in 1:length(plot.objects)) {
if (!inherits(plot.objects[[i]], 'trellis')) {
stop('Please only use trellis objects for this function');
}
}
# Collect the axis limites, labels and at from all the plots
xaxis.labels.plots <- list()[1:length(plot.objects)];
yaxis.labels.plots <- list()[1:length(plot.objects)];
xat.plots <- list()[1:length(plot.objects)];
yat.plots <- list()[1:length(plot.objects)];
xlimits.plots <- list()[1:length(plot.objects)];
ylimits.plots <- list()[1:length(plot.objects)];
# combine plot objects together and set layout
combined.plot.objects <- c(plot.objects[[1]], layout = plot.layout);
if (length(plot.objects) > 1) {
for (i in 1:length(plot.objects)) {
if (i > 1) {
combined.plot.objects <- c(combined.plot.objects, plot.objects[[i]], layout = plot.layout, merge.legends = merge.legends);
}
# record each plot's axis values
if (length(plot.objects[[i]]$x.scales$labels) > 0) {
xaxis.labels.plots[[i]] <- plot.objects[[i]]$x.scales$labels;
}
if (length(plot.objects[[i]]$y.scales$labels) > 0) {
yaxis.labels.plots[[i]] <- plot.objects[[i]]$y.scales$labels;
}
xat.plots[[i]] <- plot.objects[[i]]$x.scales$at;
yat.plots[[i]] <- plot.objects[[i]]$y.scales$at;
xlimits.plots[[i]] <- plot.objects[[i]]$x.limits;
ylimits.plots[[i]] <- plot.objects[[i]]$y.limits;
}
}
if (is.null(xaxis.top.idx)) {
xaxis.top.idx <- length(plot.objects);
}
# specify tck marks for different alternating settings
if (0 == xaxis.alternating) { xaxis.tck <- c(0, 0); }
else if (1 == xaxis.alternating) { xaxis.tck[2] <- 0; }
else if (2 == xaxis.alternating) { xaxis.tck[1] <- 0; }
# specify tck marks for different alternating settings
if (0 == yaxis.alternating) { yaxis.tck <- c(0, 0); }
else if (1 == yaxis.alternating) { yaxis.tck[2] <- 0; }
else if (2 == yaxis.alternating) { yaxis.tck[1] <- 0; }
# if there are axis labels or tck locations for each plot, then the relations need to be free
if ( (typeof(yaxis.labels) == 'list') || (typeof(yat) == 'list')) {
y.relation <- 'free';
}
if ( (typeof(xaxis.labels) == 'list') || (typeof(xat) == 'list')) {
x.relation <- 'free';
}
# if user asked to retrieve previous plot labels, then the relations need to be free
if (!is.null(plot.labels.to.retrieve)) {
y.relation <- 'free';
x.relation <- 'free';
}
# Checks to see if there are NULL value(s) in the limit lists
x.atleast.one.null <- FALSE;
if (!is.null(xlimits) && is.null(plot.labels.to.retrieve)) {
for (i in 1:length(xlimits)) {
if (is.null(xlimits[[i]])) {
x.atleast.one.null <- TRUE;
break;
}
}
}
# If there are NULL value(s) or limit=NULL, then replace the NULL value(s)
if (is.null(xlimits) || x.atleast.one.null) {
xlimits <- replace.nulls(
xlimits,
xlimits.plots[[plot.for.carry.over.when.same]],
xlimits.plots,
x.relation);
}
if (!is.null(xat) && !anyNA(xat) && 1 == length(xat) && xat == TRUE) {
xat <- if ('same' == x.relation) {xat.plots[[plot.for.carry.over.when.same]]} else {xat.plots};
}
if (!is.null(xaxis.labels) && !anyNA(xaxis.labels) && 1 == length(xaxis.labels) && xaxis.labels == TRUE) {
xaxis.labels <- if ('same' == x.relation) {xaxis.labels.plots[[plot.for.carry.over.when.same]]} else {xaxis.labels.plots};
}
y.atleast.one.null <- FALSE;
if (!is.null(ylimits) && is.null(plot.labels.to.retrieve)) {
for (i in 1:length(ylimits)) {
if (is.null(ylimits[[i]])) {
y.atleast.one.null <- TRUE;
break;
}
}
}
if (is.null(ylimits) || y.atleast.one.null) {
ylimits <- replace.nulls(
ylimits,
ylimits.plots[[plot.for.carry.over.when.same]],
ylimits.plots,
y.relation);
}
if (!is.null(yat) && !anyNA(yat) && 1 == length(yat) && yat == TRUE) {
yat <- if ('same' == y.relation) {yat.plots[[plot.for.carry.over.when.same]]} else {yat.plots};
}
if (!is.null(yaxis.labels) && !anyNA(yaxis.labels) && 1 == length(yaxis.labels) && yaxis.labels == TRUE) {
yaxis.labels <- if ('same' == y.relation) {yaxis.labels.plots[[plot.for.carry.over.when.same]]} else {yaxis.labels.plots};
}
# consolidate all the parameters together for updating the lattice
x.scale <- list(
alternating = xaxis.alternating,
tck = xaxis.tck,
labels = xaxis.labels,
cex = xaxis.cex,
at = xat,
rot = c(xaxis.rot, xaxis.rot.top),
limits = xlimits,
fontface = if ('Nature' == style) {'plain'} else (xaxis.fontface),
relation = x.relation
);
y.scale <- list(
alternating = yaxis.alternating,
tck = yaxis.tck,
labels = yaxis.labels,
cex = yaxis.cex,
at = yat,
rot = 0,
limits = ylimits,
fontface = if ('Nature' == style) {'plain'} else (yaxis.fontface),
relation = y.relation
);
# function to draw different top and bottom axes
xscale.components.new <- function(...) {
args <- xscale.components.default(...);
packet <- which.packet();
if (!is.null(packet)) {
if (packet == xaxis.top.idx) {
args$top <- args$bottom;
if (length(xat.top) == 0) {
xat.top <- c(1:length(xaxis.top.tck.lab));
}
args$top$ticks$at <- xat.top;
args$top$labels$at <- xat.top;
args$top$labels$labels <- xaxis.top.tck.lab;
}
}
return(args);
}
xscale.components.old <- function(...) {
args <- xscale.components.default(...);
return(args);
}
xscale.list <- list(xscale.components.old, xscale.components.old, xscale.components.new);
trellis.object <- update(
combined.plot.objects,
relation = 'free',
skip = layout.skip,
between = list(y = y.spacing, x = x.spacing),
scales = list(
x = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = x.scale
),
y = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = y.scale
)
),
main = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = main,
fontface = if ('Nature' == style) {'plain'} else ('bold'),
cex = main.cex,
just = main.just,
x = main.x,
y = main.y
)
),
xlab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.label,
fontface = if ('Nature' == style) {'plain'} else ('bold'),
cex = xlab.cex
)
),
xlab.top = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.top.label,
cex = xlab.top.cex,
col = xlab.top.col,
fontface = if ('Nature' == style) {'plain'} else {'bold'},
just = xlab.top.just,
x = xlab.top.x,
y = xlab.top.y
)
),
ylab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = rev(ylab.label),
fontface = if ('Nature' == style) {'plain'} else ('bold'),
cex = ylab.cex
)
),
par.settings = list(
axis.line = list(
lwd = axes.lwd,
col = if ('Nature' == style) {'transparent'} else ('black')
),
layout.heights = list(
panel = rev(panel.heights),
top.padding = top.padding,
main = if (is.null(main)) { 0.3 } else { 1 },
main.key.padding = main.key.padding,
key.top = 0.1,
key.axis.padding = 0.1,
axis.top = 0.7,
axis.bottom = 1.0,
axis.xlab.padding = xlab.to.xaxis.padding,
xlab = 1,
xlab.key.padding = xlab.key.padding,
key.bottom = key.bottom.padding,
key.sub.padding = 0.1,
sub = 0.1,
bottom.padding = bottom.padding
),
layout.widths = list(
left.padding = left.padding,
key.left = key.left.padding,
key.ylab.padding = 0.5,
ylab = 1,
ylab.axis.padding = ylab.padding,
xlab.axis.padding = xlab.padding,
axis.left = 1,
axis.panel = 0.3,
strip.left = 0.3,
panel = panel.widths,
between = 1,
axis.right = 1,
axis.key.padding = 1,
key.right = key.right.padding,
right.padding = right.padding
),
axis.components = list(left = list(pad1 = y.tck.dist), bottom = list(pad1 = x.tck.dist))
),
key = key,
legend = if (print.new.legend) {legend} else {combined.plot.objects$legend}
);
if (!is.null(xaxis.top.tck.lab)) {
trellis.object <- update(trellis.object, xscale.components = xscale.components.new);
}
# update above doesn't seem to go through so force it here
trellis.object$x.limits <- xlimits;
trellis.object$y.limits <- ylimits;
if (!is.null(get.dendrogram.from)) {
if (print.new.legend) {
trellis.object$legend <- legend;
}
old.legend.top <- plot.objects[[get.dendrogram.from]]$legend$top$fun;
if (!is.null(old.legend.top)) {
if (is.null(trellis.object$legend$top$fun) || print.new.legend == FALSE) {
trellis.object$legend$top$fun <- old.legend.top;
trellis.object$legend$top$fun$framevp$width <- unit(dendrogram.top.size, 'npc');
trellis.object$legend$top$fun$framevp$height <- unit(dendrogram.top.size, 'npc');
trellis.object$legend$top$fun$framevp$x <- unit(dendrogram.top.x, 'points');
trellis.object$legend$top$fun$framevp$y <- unit(dendrogram.top.y, 'points');
}
else {
old.legend.top.height.cm <- convertUnit(
grobHeight(old.legend.top),
unitTo = 'cm',
axisFrom = 'y',
typeFrom = 'dimension',
valueOnly = TRUE
);
old.legend.top$framevp$width <- unit(dendrogram.top.size, 'npc');
old.legend.top$framevp$height <- unit(dendrogram.top.size, 'npc');
old.legend.top$framevp$x <- unit(dendrogram.top.x, 'points');
old.legend.top$framevp$y <- unit(dendrogram.top.y, 'points');
top.layout.final <- grid.layout(
ncol = 1,
nrow = 2,
heights = unit(
x = c(old.legend.top.height.cm + 2, 1),
units = c('cm', 'grobheight'),
data = list(NULL, old.legend.top)
),
widths = unit(1, 'null'),
respect = FALSE
);
# create a frame using this layout
top.grob.final <- frameGrob(layout = top.layout.final);
# place the existing grob
top.grob.final <- placeGrob(
frame = top.grob.final,
grob = old.legend.top,
row = 1,
col = 1
);
# place the legend
top.grob.final <- placeGrob(
frame = top.grob.final,
grob = trellis.object$legend$top$fun,
row = 2,
col = 1
);
trellis.object$legend$top$fun <- top.grob.final;
}
}
old.legend.right <- plot.objects[[get.dendrogram.from]]$legend$right$fun;
if (!is.null(old.legend.right)) {
if (is.null(trellis.object$legend$right$fun) || print.new.legend == FALSE) {
trellis.object$legend$right$fun <- old.legend.right;
trellis.object$legend$right$fun$framevp$width <- unit(dendrogram.right.size, 'npc');
trellis.object$legend$right$fun$framevp$height <- unit(dendrogram.right.size, 'npc');
trellis.object$legend$right$fun$framevp$x <- unit(dendrogram.right.x, 'points');
trellis.object$legend$right$fun$framevp$y <- unit(dendrogram.right.y, 'points');
}
else {
old.legend.right.width.cm <- convertUnit(
grobWidth(old.legend.right),
unitTo = 'cm',
axisFrom = 'x',
typeFrom = 'dimension',
valueOnly = TRUE
);
old.legend.right$framevp$width <- unit(dendrogram.right.size, 'npc');
old.legend.right$framevp$height <- unit(dendrogram.right.size, 'npc');
old.legend.right$framevp$x <- unit(dendrogram.right.x, 'points');
old.legend.right$framevp$y <- unit(dendrogram.right.y, 'points');
right.layout.final <- grid.layout(
nrow = 1,
ncol = 2,
widths = unit(
x = c(1, old.legend.right.width.cm + 2),
units = c('grobwidth', 'cm'),
data = list(old.legend.right, NULL)
),
heights = unit(1, 'null'),
respect = FALSE
);
right.grob.final <- frameGrob(layout = right.layout.final);
# place the existing grob
right.grob.final <- placeGrob(
frame = right.grob.final,
grob = old.legend.right,
row = 1,
col = 1
);
# place the legend
right.grob.final <- placeGrob(
frame = right.grob.final,
grob = trellis.object$legend$right$fun,
row = 1,
col = 2
);
trellis.object$legend$right$fun <- right.grob.final;
}
}
}
# pulling forward a combination of axis limits, at and labels from the individual plots
# and the values passed to multiplot as a argument to the created mutliplot
if (!is.null(plot.labels.to.retrieve)) {
nxaxis.labels <- list();
nyaxis.labels <- list();
nxat <- list();
nyat <- list();
nxlimits <- list();
nylimits <- list();
for (p in c(1:length(plot.objects))) {
# if the plot is listed in plot.labels.to.retrieve, use the values from the individual plots
if (p %in% plot.labels.to.retrieve) {
nxlimits[[p]] <- plot.objects[[p]]$x.limits;
nxat[[p]] <- plot.objects[[p]]$x.scales$at;
nylimits[[p]] <- plot.objects[[p]]$y.limits;
nyat[[p]] <- plot.objects[[p]]$y.scales$at;
if (length(plot.objects[[p]]$x.scales$labels) > 0) {
nxaxis.labels[[p]] <- plot.objects[[p]]$x.scales$labels;
}
else {
nxaxis.labels[[p]] <- TRUE;
}
if (length(plot.objects[[p]]$y.scales$labels) > 0) {
nyaxis.labels[[p]] <- plot.objects[[p]]$y.scales$labels;
}
else {
nyaxis.labels[[p]] <- TRUE;
}
}
# if the plot is not listed in plot.labels.to.retrieve, use the values pass to multiplot as arguments
else {
nxlimits[[p]] <- xlimits[[p]];
nxat[[p]] <- xat[[p]];
nylimits[[p]] <- ylimits[[p]];
nyat[[p]] <- yat[[p]];
if (length(xaxis.labels) >= p) {
nxaxis.labels[[p]] <- xaxis.labels[[p]];
}
else {
nxaxis.labels[[p]] <- TRUE;
}
if (length(yaxis.labels) >= p) {
nyaxis.labels[[p]] <- yaxis.labels[[p]];
}
else {
nyaxis.labels[[p]] <- TRUE;
}
}
}
trellis.object$x.limits <- nxlimits;
trellis.object$y.limits <- nylimits;
trellis.object$x.scales$at <- nxat;
trellis.object$y.scales$at <- nyat;
trellis.object$x.scales$labels <- nxaxis.labels;
trellis.object$y.scales$labels <- nyaxis.labels;
}
# There is a glitch in update.trellis that prevents us from declaring multiple 'inside' legends
# To get around this, we'll add in a special case to just set the 'legend' manually
if (sum(names(legend) == 'inside', na.rm = TRUE) > 1) {
trellis.object$legend <- legend;
}
# If flag set to TRUE for removing all border lines, reset panel border lines
# TODO: RSUN, allow custom setting to redraw certain border lines
if (remove.all.border.lines) {
trellis.object <- update(
trellis.object,
reference = FALSE,
par.settings = list(
axis.line = list(
col = 0,
scales = list(col = 0, tck = c(0, 0)),
panel = function(...) {
lims <- current.panel.limits();
panel.abline(h = lims$ylim[1], v = lims$xlim[1], col = 0);
}
)
)
);
}
# If Nature style requested, change figure accordingly
if ('Nature' == style) {
# Re-add bottom and left axes
trellis.object$axis <- function(side, line.col = 'black', ...) {
# Only draw axes on the left and bottom
if (side %in% c('bottom', 'left')) {
axis.default(side = side, line.col = 'black', ...);
lims <- current.panel.limits();
panel.abline(h = lims$ylim[1], v = lims$xlim[1]);
}
}
# Ensure sufficient resolution for graphs
if (resolution < 1200) {
resolution <- 1200;
warning('Setting resolution to 1200 dpi.');
}
# Other required changes which are not accomplished here
warning('Nature also requires italicized single-letter variables and en-dashes
for ranges and negatives. See example in documentation for how to do this.');
warning('Avoid red-green colour schemes, create TIFF files, do not outline the figure or legend');
}
else if ('BoutrosLab' == style) {
# Nothing happens
}
else {
warning("The style parameter only accepts 'Nature' or 'BoutrosLab'.");
}
return(
BoutrosLab.plotting.general::write.plot(
trellis.object = trellis.object,
filename = filename,
height = height,
width = width,
size.units = size.units,
resolution = resolution,
enable.warnings = enable.warnings,
description = description
)
);
}
### FUNCTION TO REPLACE ANY NULL VALUES IN XLIMITS OR YLIMITS ######################################
replace.nulls <- function(limits, carry.over, limits.plots, relation) {
if (is.null(limits)) {
limits <-
if ('same' == relation) {carry.over}
else {limits.plots};
}
else if ('same' == relation) {
limits <- carry.over;
}
else {
for (i in 1:length(limits)) {
if (is.null(limits[[i]])) {
limits[[i]] <- limits.plots[[i]];
}
}
}
return(limits);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/create.multiplot.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2013 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO CREATE POLYGONPLOT ################################################################
create.polygonplot <- function(
formula, data, filename = NULL, groups = NULL, main = NULL, main.just = 'center', main.x = 0.5, main.y = 0.5,
main.cex = 3, max, min, col = 'white', alpha = 0.5, border.col = 'black',
strip.col = 'white', strip.cex = 1, type = 'p', cex = 0.75, pch = 19, lwd = 1, lty = 1, axes.lwd = 1,
xlab.label = tail(sub('~', '', formula[-2]), 1), ylab.label = tail(sub('~', '', formula[-3]), 1),
xlab.cex = 2, ylab.cex = 2, xlab.col = 'black', ylab.col = 'black', xlab.top.label = NULL, xlab.top.cex = 2,
xlab.top.col = 'black', xlab.top.just = 'center', xlab.top.x = 0.5, xlab.top.y = 0, xaxis.lab = TRUE,
yaxis.lab = TRUE, xaxis.cex = 1.5, yaxis.cex = 1.5, xaxis.rot = 0, yaxis.rot = 0, xaxis.log = FALSE,
yaxis.log = FALSE, xaxis.fontface = 'bold', yaxis.fontface = 'bold', xaxis.col = 'black', yaxis.col = 'black',
xaxis.tck = 1, yaxis.tck = 1, xlimits = NULL, ylimits = NULL, xat = TRUE, yat = TRUE, layout = NULL,
as.table = FALSE, x.spacing = 0, y.spacing = 0, x.relation = 'same', y.relation = 'same', top.padding = 0.5,
bottom.padding = 2, right.padding = 1, left.padding = 2, ylab.axis.padding = 0, add.border = FALSE, add.xy.border = NULL,
add.median = FALSE, median.lty = 3, median.lwd = 1.5, use.loess.border = FALSE, use.loess.median = FALSE,
median = NULL, median.col = 'black', extra.points = NULL, extra.points.pch = 21, extra.points.type = 'p',
extra.points.col = 'black', extra.points.fill = 'white', extra.points.cex = 1, add.rectangle = FALSE,
xleft.rectangle = NULL, ybottom.rectangle = NULL, xright.rectangle = NULL, ytop.rectangle = NULL,
col.rectangle = 'transparent', alpha.rectangle = 1, xgrid.at = xat, ygrid.at = yat, grid.lty = 1,
grid.col = 'grey', grid.lwd = 0.3, add.xyline = FALSE, xyline.col = 'black', xyline.lwd = 1, xyline.lty = 1,
abline.h = NULL, abline.v = NULL, abline.col = 'black', abline.lwd = 1, abline.lty = 1, add.text = FALSE,
text.labels = NULL, text.x = NULL, text.y = NULL, text.col = 'black', text.cex = 1, text.fontface = 'bold',
key = NULL, legend = NULL, height = 6, width = 6, size.units = 'in', resolution = 1600, enable.warnings = FALSE,
description = 'Created with BoutrosLab.plotting.general', style = 'BoutrosLab', preload.default = 'custom',
use.legacy.settings = FALSE, inside.legend.auto = FALSE
) {
if (!missing(add.xy.border)) {
add.border <- add.xy.border;
warning('add.xy.border is deprecated. Use add.border instead');
}
### needed to copy in case using variable to define rectangles dimensions
rectangle.info <- list(
xright = xright.rectangle,
xleft = xleft.rectangle,
ytop = ytop.rectangle,
ybottom = ybottom.rectangle
);
text.info <- list(
labels = text.labels,
x = text.x,
y = text.y,
col = text.col,
cex = text.cex,
fontface = text.fontface
);
extra.points.info <- list(
x = extra.points$x,
y = extra.points$y,
type = extra.points.type,
pch = extra.points.pch,
col = extra.points.col,
cex = extra.points.cex,
fill = extra.points.fill
);
if (!is.null(yat) && length(yat) == 1) {
if (yat == 'auto') {
out <- auto.axis(unlist(data[toString(formula[[2]])]));
data[toString(formula[[2]])] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
else if (yat == 'auto.linear') {
out <- auto.axis(unlist(data[toString(formula[[2]])]), log.scaled = FALSE);
data[toString(formula[[2]])] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
else if (yat == 'auto.log') {
out <- auto.axis(unlist(data[toString(formula[[2]])]), log.scaled = TRUE);
data[toString(formula[[2]])] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
}
if (!is.null(xat) && length(xat) == 1) {
if (xat == 'auto') {
out <- auto.axis(unlist(data[toString(formula[[3]])]));
data[toString(formula[[3]])] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
else if (xat == 'auto.linear') {
out <- auto.axis(unlist(data[toString(formula[[3]])]), log.scaled = FALSE);
data[toString(formula[[3]])] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
else if (xat == 'auto.log') {
out <- auto.axis(unlist(data[toString(formula[[3]])]), log.scaled = TRUE);
data[toString(formula[[3]])] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
}
# add preloaded defaults
if (preload.default == 'paper') {
}
else if (preload.default == 'web') {
}
# update groups function
groups.new <- eval(substitute(groups), data, parent.frame());
# auto set parameters
if (length(xat) == 1 && xat == TRUE && length(xlimits) == 0) {
if (!is.null(data)) {
minimum <- 0;
maximum <- length(data[[1]]);
difference <- maximum - minimum;
lognumber <- floor(log(difference, 10));
# depending on difference, the labels will be multiples of 5,10 or 20
if (difference < (10 ** lognumber * 4)) { factor <- (10 ** lognumber) / 2; }
else if (difference < (10 ** lognumber * 7)) { factor <- (10 ** lognumber); }
else { factor <- (10 ** lognumber) * 2; }
addition <- factor / 2;
# depending on minimum create a sequence of at locations with padding
at <- seq(0, factor * round(maximum / factor) + addition, factor);
xlimits <- c(minimum, maximum);
xat <- at;
}
}
if (length(yat) == 1 && yat == TRUE && length(ylimits) == 0) {
if (!is.null(data)) {
minimum <- min(min);
maximum <- max(max);
# if minimum is greater than 0 make sure to display 0
minimum <- min(minimum, 0);
difference <- maximum - minimum;
lognumber <- floor(log(difference, 10));
# depending on difference, the labels will be multiples of 5,10 or 20
if (difference < (10 ** lognumber * 4)) { factor <- (10 ** lognumber) / 2; }
else if (difference < (10 ** lognumber * 7)) { factor <- (10 ** lognumber); }
else { factor <- (10 ** lognumber) * 2; }
addition <- factor / 2;
# depending on minimum create a sequence of at locations with padding
if (minimum == 0) {
at <- seq(0, factor * round(maximum / factor) + addition, factor);
}
else {
at <- seq(factor * round(minimum / factor), factor * round(maximum / factor) + addition, factor);
# only add padding to minimum if it is not 0
minimum <- minimum - addition;
}
# add padding to max
maximum <- maximum + addition;
ylimits <- c(minimum, maximum);
yat <- at;
}
}
# create the plot object
trellis.object <- lattice::xyplot(
formula,
data,
max = max,
min = min,
median = median,
panel = function(x, y, col = col, border = border.col, groups = groups.new, subscripts, ...) {
# add rectangle if requested
# want rectangle in the background, and only plotted once
# => add first, outside of grouping if/else split
if (add.rectangle) {
panel.rect(
xleft = rectangle.info$xleft,
ybottom = rectangle.info$ybottom,
xright = rectangle.info$xright,
ytop = rectangle.info$ytop,
col = col.rectangle,
alpha = alpha.rectangle,
border = NA
);
}
# if requested, add y=x line
if (add.xyline) {
panel.abline(
a = 0,
b = 1,
lwd = xyline.lwd,
lty = xyline.lty,
col = xyline.col
);
}
# if no grouping variable, draw a single polygon
if (is.null(groups.new)) {
# draw polygon
panel.polygon(
x = c(x, rev(x)),
y = if (use.loess.border) {
c(predict(loess(max[subscripts] ~ x)), rev(predict(loess(min[subscripts] ~ x))))
}
else {
c(max[subscripts], rev(min[subscripts]))
},
col = col,
...
);
# draw xy points along border of polygon
if (add.border) {
panel.xyplot(
x = c(x, rev(x)),
y = c(max[subscripts], rev(min[subscripts])),
type = 'l',
col = border.col
);
}
# draw median line
if (add.median & !is.null(median)) {
panel.xyplot(
x = x,
y = if (use.loess.median) { predict(loess(median[subscripts] ~ x)) } else { median[subscripts] },
type = 'l',
lwd = median.lwd,
col = median.col,
lty = median.lty
);
}
# draw extra points
if (!is.null(extra.points)) {
panel.xyplot(
x = extra.points.info$x,
y = extra.points.info$y,
groups = groups,
subscripts = subscripts,
type = extra.points.info$type,
pch = extra.points.info$pch,
col = extra.points.info$col,
cex = extra.points.info$cex,
fill = extra.points.info$fill
);
}
# add background grid
if (!is.null(xgrid.at) || !is.null(ygrid.at)) {
panel.abline(
v = xgrid.at,
h = ygrid.at,
lty = grid.lty,
col = grid.col,
lwd = grid.lwd,
alpha = 0.5
);
}
# if requested, add y=x line
if (add.xyline) {
panel.abline(
a = 0,
b = 1,
lwd = xyline.lwd,
lty = xyline.lty,
col = xyline.col
);
}
# if requested, add user-defined horizontal line
if (!is.null(abline.h)) {
panel.abline(
h = abline.h,
lty = abline.lty,
lwd = abline.lwd,
col = abline.col
);
}
# if requested, add user-defined vertical line
if (!is.null(abline.v)) {
panel.abline(
v = abline.v,
lty = abline.lty,
lwd = abline.lwd,
col = abline.col
);
}
# if requested, add text
if (add.text) {
panel.text(
x = text.info$x,
y = text.info$y,
labels = text.info$labels,
col = text.info$col,
cex = text.info$cex,
fontface = text.info$fontface
);
}
}
else {
# Grouping variable exists - need to draw separate polygons for each level
# can't use ternary operator because need to return vectors
border.col <- if (length(border.col) == 1) { rep(border.col, length(subscripts)); } else {
as.character(factor(x = groups, labels = border.col));
}
add.border <- if (length(add.border) == 1) { rep(add.border, length(subscripts)); } else {
as.character(factor(x = groups, labels = add.border));
}
median.col <- if (length(median.col) == 1) { rep(median.col, length(subscripts)); } else {
as.character(factor(x = groups, labels = median.col));
}
median.lty <- if (length(median.lty) == 1) { rep(median.lty, length(subscripts)); } else {
as.numeric(factor(x = groups, labels = median.lty));
}
median.lwd <- if (length(median.lwd) == 1) { rep(median.lwd, length(subscripts)); } else {
as.character(factor(x = groups, labels = median.lwd));
}
# Plot polygons
# this is plotted with different graphical parameters for each distinct value of the grouping variable
panel.superpose(
x,
y,
groups = groups.new,
subscripts,
panel.groups = function(x, y, max, min, groups = groups.new, subscripts, type, add.xy.plot = add.xy.plot, ..., font, fontface) {
group.num <- 1;
for (i in 1:length(unique(groups))) {
if (groups[subscripts[1]] == unique(groups)[i]) {
group.num <- i;
break;
}
}
# draw polygon
panel.polygon(
x = c(x, rev(x)),
y = if (use.loess.border) {
c(predict(loess(max[subscripts] ~ x)), rev(predict(loess(min[subscripts] ~ x))))
}
else {
c(max[subscripts], rev(min[subscripts]))
},
type,
...
);
if ((length(add.border) == 1 && add.border) || add.border[group.num]) {
polygon.border <- border.col[subscripts];
} else {
polygon.border <- 'black';
}
# draw polygon borders
panel.xyplot(
x = c(x, rev(x), x[1]),
y = c(max[subscripts], rev(min[subscripts]), max[subscripts][1]),
type = 'l',
col = polygon.border,
lwd = lwd
);
# draw median line
if (add.median & !is.null(median)) {
panel.xyplot(
x = x,
y = if (use.loess.median) { predict(loess(median[subscripts] ~ x)) } else { median[subscripts] },
type = 'l',
lwd = median.lwd[subscripts],
col = median.col[subscripts],
lty = median.lty[subscripts]
);
}
# add extra points, assuming same grouping as original data
if (!is.null(extra.points)) {
panel.xyplot(
x = extra.points.info$x,
y = extra.points.info$y,
#groups = groups,
#subscripts = subscripts,
type = extra.points.info$type,
pch = extra.points.info$pch,
col = extra.points.info$col,
cex = extra.points.info$cex,
fill = extra.points.info$fill
);
}
# add background grid
if (!is.null(xgrid.at) || !is.null(ygrid.at)) {
panel.abline(
v = xgrid.at,
h = ygrid.at,
lty = grid.lty,
col = grid.col,
lwd = grid.lwd,
alpha = 0.5
);
}
# if requested, add user-defined horizontal line
if (!is.null(abline.h)) {
panel.abline(
h = abline.h,
lty = abline.lty,
lwd = abline.lwd,
col = abline.col
);
}
# if requested, add user-defined vertical line
if (!is.null(abline.v)) {
panel.abline(
v = abline.v,
lty = abline.lty,
lwd = abline.lwd,
col = abline.col
);
}
# if requested, add text
if (add.text) {
panel.text(
x = text.info$x,
y = text.info$y,
labels = text.info$labels,
col = text.info$col,
cex = text.info$cex,
fontface = text.info$fontface
);
}
},
alpha = alpha,
col = col,
border = 'white',
...
);
}
},
type = type,
cex = cex,
pch = pch,
col = col,
lwd = lwd,
lty = lty,
main = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = main,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
cex = main.cex,
just = main.just,
x = main.x,
y = main.y
)
),
xlab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.label,
cex = xlab.cex,
col = xlab.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' }
)
),
xlab.top = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.top.label,
cex = xlab.top.cex,
col = xlab.top.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
just = xlab.top.just,
x = xlab.top.x,
y = xlab.top.y
)
),
ylab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = ylab.label,
cex = ylab.cex,
col = ylab.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' }
)
),
between = list(
x = x.spacing,
y = y.spacing
),
scales = list(
x = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
labels = xaxis.lab,
log = xaxis.log,
fontface = if ('Nature' == style) { 'plain' } else { xaxis.fontface },
rot = xaxis.rot,
limits = xlimits,
cex = xaxis.cex,
col = xaxis.col,
at = xat,
relation = x.relation,
alternating = FALSE,
tck = xaxis.tck
)
),
y = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
labels = yaxis.lab,
fontface = if ('Nature' == style) { 'plain' } else { yaxis.fontface },
limits = ylimits,
cex = yaxis.cex,
col = yaxis.col,
rot = yaxis.rot,
tck = yaxis.tck,
at = yat,
log = yaxis.log,
relation = y.relation
)
)
),
par.settings = list(
axis.line = list(
lwd = axes.lwd,
col = if ('Nature' == style) { 'transparent' } else { 'black' }
),
layout.heights = list(
top.padding = top.padding,
main = if (is.null(main)) { 0.3 } else { 3 },
main.key.padding = 0.1,
key.top = 0.1,
key.axis.padding = 0.1,
axis.top = 1,
axis.bottom = 1,
axis.xlab.padding = 1,
xlab = 1,
xlab.key.padding = 0.5,
key.bottom = 0.1,
key.sub.padding = 0.1,
sub = 0.1,
bottom.padding = bottom.padding
),
layout.widths = list(
left.padding = left.padding,
key.left = 0.1,
key.ylab.padding = 0.1,
ylab = 1,
ylab.axis.padding = 1,
axis.left = 1,
axis.right = 1,
axis.key.padding = 1,
key.right = 1,
right.padding = right.padding
),
strip.background = list(
col = strip.col
)
),
par.strip.text = list(
cex = strip.cex
),
layout = layout,
as.table = as.table,
pretty = TRUE,
key = key,
legend = legend
);
if (inside.legend.auto) {
extra.parameters <- list('formula' = formula, 'data' = data, 'ylimits' = trellis.object$y.limits,
'xlimits' = trellis.object$x.limits, 'extra.points' = extra.points, 'max' = max, 'min' = min);
coords <- c();
coords <- .inside.auto.legend('create.polygonplot', filename, trellis.object, height, width, extra.parameters);
trellis.object$legend$inside$x <- coords[1];
trellis.object$legend$inside$y <- coords[2];
}
# If Nature style requested, change figure accordingly
if ('Nature' == style) {
# Re-add bottom and left axes
trellis.object$axis <- function(side, line.col = 'black', ...) {
# Only draw axes on the left and bottom
if (side %in% c('bottom', 'left')) {
axis.default(side = side, line.col = 'black', ...);
lims <- current.panel.limits();
panel.abline(h = lims$ylim[1], v = lims$xlim[1]);
}
}
# Ensure sufficient resolution for graphs
if (resolution < 1200) {
resolution <- 1200;
warning('Setting resolution to 1200 dpi.');
}
# Other required changes which are not accomplished here
warning('Nature also requires italicized single-letter variables and en-dashes
for ranges and negatives. See example in documentation for how to do this.');
warning('Avoid red-green colour schemes, create TIFF files, do not outline the figure or legend.');
}
# Otherwise use the BL style if requested
else if ('BoutrosLab' == style) {
# Nothing happens
}
# if neither of the above is requested, give a warning
else {
warning("The style parameter only accepts 'Nature' or 'BoutrosLab'.");
}
# output the object
return(
BoutrosLab.plotting.general::write.plot(
trellis.object = trellis.object,
filename = filename,
height = height,
width = width,
size.units = size.units,
resolution = resolution,
enable.warnings = enable.warnings,
description = description
)
);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/create.polygonplot.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO CREATE QQPLOT COMPARISON ###########################################################
create.qqplot.comparison <- function(
x, data = NULL, filename = NULL, groups = NULL, main = NULL, main.just = 'center', main.x = 0.5,
main.y = 0.5, main.cex = 3, aspect = 'fill', prepanel = NULL, xlab.label = NULL, ylab.label = NULL,
xlab.cex = 2, ylab.cex = 2, xlab.col = 'black', ylab.col = 'black', xlimits = NULL, ylimits = NULL,
xat = TRUE, yat = TRUE, xaxis.lab = NA, yaxis.lab = NA, xaxis.cex = 1.5, yaxis.cex = 1.5,
xaxis.fontface = 'bold', yaxis.fontface = 'bold', xaxis.log = FALSE, yaxis.log = FALSE, xaxis.rot = 0,
yaxis.rot = 0, xaxis.col = 'black', yaxis.col = 'black', xaxis.tck = 1, yaxis.tck = 1,
xlab.top.label = NULL, xlab.top.cex = 2, xlab.top.col = 'black', xlab.top.just = 'center',
xlab.top.x = 0.5, xlab.top.y = 0, add.grid = FALSE, xgrid.at = xat, ygrid.at = yat, type = 'p', cex = 0.75,
pch = 19, col = 'black', lwd = 1, lty = 1, axes.lwd = 2.25, key = list(text = list(lab = c(''))),
legend = NULL, add.rectangle = FALSE, xleft.rectangle = NULL, ybottom.rectangle = NULL,
xright.rectangle = NULL, ytop.rectangle = NULL, col.rectangle = 'transparent', alpha.rectangle = 1,
top.padding = 3, bottom.padding = 0.7, left.padding = 0.5, right.padding = 0.1,
height = 6, width = 6, size.units = 'in', resolution = 1600, enable.warnings = FALSE,
description = 'Created with BoutrosLab.plotting.general', style = 'BoutrosLab', preload.default = 'custom',
use.legacy.settings = FALSE, inside.legend.auto = FALSE
) {
### needed to copy in case using variable to define rectangles dimensions
rectangle.info <- list(
xright = xright.rectangle,
xleft = xleft.rectangle,
ytop = ytop.rectangle,
ybottom = ybottom.rectangle
);
if (!is.null(yat) && length(yat) == 1) {
if (yat == 'auto') {
out <- auto.axis(unlist(x[[1]]));
x[[1]] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
else if (yat == 'auto.linear') {
out <- auto.axis(unlist(x[[1]]), log.scaled = FALSE);
x[[1]] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
else if (yat == 'auto.log') {
out <- auto.axis(unlist(x[[1]]), log.scaled = TRUE);
x[[1]] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
}
if (!is.null(xat) && length(xat) == 1) {
if (xat == 'auto') {
out <- auto.axis(unlist(x[[2]]));
x[[2]] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
else if (xat == 'auto.linear') {
out <- auto.axis(unlist(x[[2]]), log.scaled = FALSE);
x[[2]] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
else if (xat == 'auto.log') {
out <- auto.axis(unlist(x[[2]]), log.scaled = TRUE);
x[[2]] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
}
# add preloaded defaults
if (preload.default == 'paper') {
}
else if (preload.default == 'web') {
}
# x should be a formula or a list of data whose length is 2
if (as.character(class(x) == 'list')) {
# create an object to store the data, since the function qq can only handle formula method
data.to.plot <- data.frame(
x = c(x[[1]], x[[2]]),
y = c(rep(1, length(x[[1]])), rep(2, length(x[[2]])))
);
formula.to.plot <- y ~ x;
z <- data.to.plot$x;
# set x-axis and y-axis label defaults
# if the label is NULL, then we leave it as blank;
# if the label is NA, then we use a specific default label.
if (!is.null(xlab.label) & !is.expression(xlab.label)) {
if (is.na(xlab.label)) {
xlab.label <- 'sample one';
}
}
if (!is.null(ylab.label) & !is.expression(ylab.label)) {
if (is.na(ylab.label)) {
ylab.label <- 'sample two';
}
}
}
else {
formula.to.plot <- x;
data.to.plot <- data;
# parse the formula to get x-axis and y-axis labels defaults
parseform <- latticeParseFormula(as.formula(formula.to.plot), data = data.to.plot);
y <- parseform$left;
z <- parseform$right;
y <- as.factorOrShingle(y);
# if x-axis labels is NA, set the default
if (!is.null(xlab.label) & !is.expression(xlab.label)) {
if (is.na(xlab.label)) {
# get the name of the first sample from the formula
if (is.factor(y)) {
xlab.label <- unique(levels(y))[1];
}
else {
xlab.label <- paste(parseform$left.name, ':', as.character(unique(levels(y)[[1]])));
}
}
}
# if y-axis labels is NA, set the default
if (!is.null(ylab.label) & !is.expression(ylab.label)) {
if (is.na(ylab.label)) {
# get the name of the second sample from the formula
if (is.factor(y)) {
ylab.label <- unique(levels(y))[2];
}
else { ylab.label <- paste(parseform$left.name, ':', as.character(unique(levels(y)[[2]]))); }
}
}
}
# set main label defaults
# if the label is NULL, then we leave it as blank;
# if the label is NA, then we use a specific default label.
if (!is.null(main) & !is.expression(main)) {
if (is.na(main)) {
main <- 'Q-Q plot';
}
}
# create the object to store all the data
trellis.object <- lattice::qq(
x = formula.to.plot,
data = data.to.plot,
panel = function(type.local = type, groups.local = groups, subscripts, identifier = 'qq', ...) {
# add rectangle if requested
if (add.rectangle) {
panel.rect(
xleft = rectangle.info$xleft,
ybottom = rectangle.info$ybottom,
xright = rectangle.info$xright,
ytop = rectangle.info$ytop,
col = col.rectangle,
alpha = alpha.rectangle,
border = NA
);
}
# if grid-lines are requested, over-ride default behaviour
if ('g' %in% type || add.grid == TRUE) {
panel.abline(
v = BoutrosLab.plotting.general::generate.at.final(
at.input = xgrid.at,
limits = xlimits,
data.vector = z
),
h = BoutrosLab.plotting.general::generate.at.final(
at.input = ygrid.at,
limits = ylimits,
data.vector = z
),
col = trellis.par.get('reference.line')$col
);
}
panel.qq(..., groups = groups.local, subscripts = subscripts, identifier = 'qq');
},
aspect = aspect,
type = type,
cex = cex,
pch = pch,
col = col,
lwd = lwd,
lty = lty,
main = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = main,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
cex = main.cex,
just = main.just,
x = main.x,
y = main.y
)
),
xlab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.label,
cex = xlab.cex,
col = xlab.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' }
)
),
xlab.top = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.top.label,
cex = xlab.top.cex,
col = xlab.top.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
just = xlab.top.just,
x = xlab.top.x,
y = xlab.top.y
)
),
ylab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = ylab.label,
cex = ylab.cex,
col = ylab.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' }
)
),
scales = list(
x = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
cex = xaxis.cex,
rot = xaxis.rot,
col = xaxis.col,
limits = xlimits,
fontface = if ('Nature' == style) { 'plain' } else { xaxis.fontface },
at = xat,
labels = xaxis.lab,
log = xaxis.log,
tck = xaxis.tck,
alternating = FALSE
)
),
y = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
cex = yaxis.cex,
rot = yaxis.rot,
col = yaxis.col,
limits = ylimits,
fontface = if ('Nature' == style) { 'plain' } else { yaxis.fontface },
at = yat,
labels = yaxis.lab,
log = yaxis.log,
tck = yaxis.tck,
alternating = FALSE
)
)
),
key = key,
legend = legend,
par.settings = list(
axis.line = list(
lwd = axes.lwd,
col = if ('Nature' == style) { 'transparent' } else { 'black' }
),
layout.heights = list(
top.padding = top.padding,
main = if (is.null(main)) { 0.3 } else { 1 },
main.key.padding = 0.1,
key.top = 0.1,
key.axis.padding = 0.1,
axis.top = 1,
axis.bottom = 1,
axis.xlab.padding = 1,
xlab = 1,
xlab.key.padding = 0.5,
key.bottom = 0.1,
key.sub.padding = 0.1,
sub = 0.1,
bottom.padding = bottom.padding
),
layout.widths = list(
left.padding = left.padding,
key.left = 0.1,
key.ylab.padding = 0.1,
ylab = 1,
ylab.axis.padding = 1,
axis.left = 1,
axis.right = 1,
axis.key.padding = 0.1,
key.right = 0.1,
right.padding = right.padding
)
)
);
if (inside.legend.auto) {
extra.parameters <- list('x' = trellis.object$panel.args[[1]]$x, 'y' = trellis.object$panel.args[[1]]$y,
'ylimits' = trellis.object$y.limits, 'xlimits' = trellis.object$x.limits);
coords <- c();
coords <- .inside.auto.legend('create.qqplot.comparison', filename, trellis.object, height, width, extra.parameters);
trellis.object$legend$inside$x <- coords[1];
trellis.object$legend$inside$y <- coords[2];
}
# If Nature style requested, change figure accordingly
if ('Nature' == style) {
# Re-add bottom and left axes
trellis.object$axis <- function(side, line.col = 'black', ...) {
# Only draw axes on the left and bottom
if (side %in% c('bottom', 'left')) {
axis.default(side = side, line.col = 'black', ...);
lims <- current.panel.limits();
panel.abline(h = lims$ylim[1], v = lims$xlim[1]);
}
}
# Ensure sufficient resolution for graphs
if (resolution < 1200) {
resolution <- 1200;
warning('Setting resolution to 1200 dpi.');
}
# Other required changes which are not accomplished here
warning('Nature also requires italicized single-letter variables and en-dashes
for ranges and negatives. See example in documentation for how to do this.');
warning('Avoid red-green colour schemes, create TIFF files, do not outline the figure or legend.');
}
# Otherwise use the BL style if requested
else if ('BoutrosLab' == style) {
# Nothing happens
}
# if neither of the above is requested, give a warning
else {
warning("The style parameter only accepts 'Nature' or 'BoutrosLab'.");
}
# output the object
return(
BoutrosLab.plotting.general::write.plot(
trellis.object = trellis.object,
filename = filename,
height = height,
width = width,
size.units = size.units,
resolution = resolution,
enable.warnings = enable.warnings,
description = description
)
);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/create.qqplot.comparison.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO CREATE QQPLOT FIT #################################################################
create.qqplot.fit <- function(
x, data = NA, filename = NULL, groups = NULL, confidence.bands = FALSE, conf = 0.95,
confidence.method = 'both', reference.line.method = 'quartiles', distribution = qnorm, aspect = 'fill',
prepanel = NULL, main = NULL, main.just = 'center', main.x = 0.5, main.y = 0.5, main.cex = 3,
xlab.label = NULL, ylab.label = NULL, xlab.cex = 2, ylab.cex = 2, xlab.col = 'black', ylab.col = 'black',
xlab.top.label = NULL, xlab.top.cex = 2, xlab.top.col = 'black', xlab.top.just = 'center', xlab.top.x = 0.5,
xlab.top.y = 0, xlimits = NULL, ylimits = NULL, xat = TRUE, yat = TRUE, xaxis.lab = NA, yaxis.lab = NA,
xaxis.cex = 1.5, yaxis.cex = 1.5, xaxis.col = 'black', yaxis.col = 'black', xaxis.fontface = 'bold',
yaxis.fontface = 'bold', xaxis.log = FALSE, yaxis.log = FALSE, xaxis.rot = 0, yaxis.rot = 0, xaxis.tck = 1,
yaxis.tck = 1, add.grid = FALSE, xgrid.at = xat, ygrid.at = yat, type = 'p', cex = 0.75, pch = 19, col = 'black',
col.line = 'grey', lwd = 2, lty = 1, axes.lwd = 2.25, key = list(text = list(lab = c(''))), legend = NULL,
add.rectangle = FALSE, xleft.rectangle = NULL, ybottom.rectangle = NULL, xright.rectangle = NULL,
ytop.rectangle = NULL, col.rectangle = 'transparent', alpha.rectangle = 1, top.padding = 3, bottom.padding = 0.7,
left.padding = 0.5, right.padding = 0.1, height = 6, width = 6, size.units = 'in', resolution = 1600,
enable.warnings = FALSE, description = 'Created with BoutrosLab.plotting.general',
style = 'BoutrosLab', preload.default = 'custom', use.legacy.settings = FALSE, inside.legend.auto = FALSE
) {
### needed to copy in case using variable to define rectangles dimensions
rectangle.info <- list(
xright = xright.rectangle,
xleft = xleft.rectangle,
ytop = ytop.rectangle,
ybottom = ybottom.rectangle
);
if (!is.null(yat) && length(yat) == 1) {
if (yat == 'auto') {
out <- auto.axis(unlist(x[[1]]));
x[[1]] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
else if (yat == 'auto.linear') {
out <- auto.axis(unlist(x[[1]]), log.scaled = FALSE);
x[[1]] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
else if (yat == 'auto.log') {
out <- auto.axis(unlist(x[[1]]), log.scaled = TRUE);
x[[1]] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
}
if (!is.null(xat) && length(xat) == 1) {
if (xat == 'auto') {
out <- auto.axis(unlist(x[[2]]));
x[[2]] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
else if (xat == 'auto.linear') {
out <- auto.axis(unlist(x[[2]]), log.scaled = FALSE);
x[[2]] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
else if (xat == 'auto.log') {
out <- auto.axis(unlist(x[[2]]), log.scaled = TRUE);
x[[2]] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
}
# add preloaded defaults
if (preload.default == 'paper') {
}
else if (preload.default == 'web') {
}
# set main, x-axis and y-axis label defaults
# if the label is NULL, then we leave it as blank;
# if the label is NA, then we use a specific default label.
if (!is.null(main) & !is.expression(main)) {
if (is.na(main)) {
main <- 'Q-Q plot';
}
}
if (!is.null(xlab.label) & !is.expression(xlab.label)) {
if (is.na(xlab.label)) {
xlab.label <- deparse(substitute(distribution));
}
}
if (!is.null(ylab.label) & !is.expression(ylab.label)) {
if (is.na(ylab.label)) {
ylab.label <- latticeParseFormula(as.formula(x), data = data)$right.name;
}
}
# create the object to store all the data
trellis.object <- lattice::qqmath(
x = x,
data = data,
distribution = distribution,
aspect = aspect,
prepanel = prepanel.qqmathline,
panel = function(
x,
type.local = type,
groups.local = groups,
subscripts,
distribution.local = distribution,
col.local = col.line,
col = col,
lwd = lwd,
...
) {
# add rectangle if requested
if (add.rectangle) {
panel.rect(
xleft = rectangle.info$xleft,
ybottom = rectangle.info$ybottom,
xright = rectangle.info$xright,
ytop = rectangle.info$ytop,
col = col.rectangle,
alpha = alpha.rectangle,
border = NA
);
}
# if grid-lines are requested, over-ride default behaviour
if ('g' %in% type || add.grid == TRUE) {
panel.abline(
v = BoutrosLab.plotting.general::generate.at.final(
at.input = xgrid.at,
limits = xlimits,
data.vector = x
),
h = BoutrosLab.plotting.general::generate.at.final(
at.input = ygrid.at,
limits = ylimits,
data.vector = x
),
col = trellis.par.get('reference.line')$col
);
}
# draw the reference line, could be one of the following:
# quartile: across 1/4 and 3/4 quantiles
# diagonal: abline(0,1),
# robust: best fit by linear regression
if (reference.line.method == 'quartiles') {
panel.qqmathline(
x,
distribution = distribution.local,
groups = groups.local,
subscripts = subscripts,
lwd = lwd,
col = col.line,
...
);
}
if (reference.line.method == 'diagonal' & !confidence.bands) {
panel.abline(0, 1);
}
if (reference.line.method == 'robust' & !confidence.bands) {
tmp.data <- BoutrosLab.plotting.general::create.qqplot.fit.confidence.interval(
x = x,
distribution = distribution,
conf = conf,
conf.method = confidence.method,
reference.line.method = reference.line.method
);
a <- tmp.data$a;
b <- tmp.data$b;
panel.abline(a, b);
}
# if confidence bands are requested
if (confidence.bands) {
# for non-grouped data
if (is.null(groups)) {
# store the value to create the confidence bands
tmp.ci <- BoutrosLab.plotting.general::create.qqplot.fit.confidence.interval(
x = x,
distribution = distribution,
conf = conf,
conf.method = confidence.method,
reference.line.method = reference.line.method
);
if (!reference.line.method == 'quartiles') {
panel.abline(tmp.ci$a, tmp.ci$b);
}
# using the returned value to plot
if (confidence.method == 'both') {
panel.polygon(
x = c(tmp.ci$z[tmp.ci$u], rev(tmp.ci$z[tmp.ci$l])),
y = c(tmp.ci$upper.sim, rev(tmp.ci$lower.sim)),
col = '#e6e6e6',
border = '#e6e6e6',
alpha = 0.5
);
if (confidence.method == 'both') {
panel.lines(tmp.ci$z, tmp.ci$upper.pw, lty = 1, lwd = lwd, col = '#b5b5b5');
panel.lines(tmp.ci$z, tmp.ci$lower.pw, lty = 1, lwd = lwd, col = '#b5b5b5');
panel.lines(tmp.ci$z[tmp.ci$u], tmp.ci$upper.sim, lty = 1, lwd = lwd, col = '#e6e6e6');
panel.lines(tmp.ci$z[tmp.ci$l], tmp.ci$lower.sim, lty = 1, lwd = lwd, col = '#e6e6e6');
}
else {
if (confidence.method == 'simultaneous') {
panel.lines(tmp.ci$z[tmp.ci$u], tmp.ci$upper.sim, lty = 1, lwd = lwd, col = '#e6e6e6');
panel.lines(tmp.ci$z[tmp.ci$l], tmp.ci$lower.sim, lty = 1, lwd = lwd, col = '#e6e6e6');
}
if (confidence.method == 'pointwise') {
panel.lines(tmp.ci$z, tmp.ci$upper.pw, lty = 1, lwd = 2, col = '#b5b5b5');
panel.lines(tmp.ci$z, tmp.ci$lower.pw, lty = 1, lwd = 2, col = '#b5b5b5');
}
}
panel.polygon(
x = c(tmp.ci$z, rev(tmp.ci$z)),
y = c(tmp.ci$upper.pw, rev(tmp.ci$lower.pw)),
col = '#b5b5b5',
border = '#b5b5b5',
alpha = 0.5
);
draw.key(
list(
text = list(
lab = c('pointwise', 'simultaneous')
),
points = list(
pch = 15,
col = c('#b5b5b5', '#e6e6e6')
)
),
draw = TRUE,
vp = viewport(x = unit(0.82, 'npc'), y = unit(0.06, 'npc'))
);
}
else {
if (confidence.method == 'simultaneous') {
panel.polygon(
x = c(tmp.ci$z[tmp.ci$u], rev(tmp.ci$z[tmp.ci$l])),
y = c(tmp.ci$upper.sim, rev(tmp.ci$lower.sim)),
col = '#e6e6e6',
border = '#e6e6e6',
alpha = 0.5
);
}
if (confidence.method == 'pointwise') {
panel.polygon(
x = c(tmp.ci$z, rev(tmp.ci$z)),
y = c(tmp.ci$upper.pw, rev(tmp.ci$lower.pw)),
col = '#b5b5b5',
border = '#b5b5b5',
alpha = 0.5
);
}
}
}
# for grouped data
else {
grouped.data <- split(x, groups);
groups.names <- sort(unique(groups.local));
number.groups <- length(groups.names);
for (k in 1:number.groups) {
# store the value to create the confidence bands for each group
tmp.ci <- BoutrosLab.plotting.general::create.qqplot.fit.confidence.interval(
x = grouped.data[[groups.names[k]]],
distribution = distribution,
conf = conf,
conf.method = confidence.method
);
if (!reference.line.method == 'quartiles') {
panel.abline(tmp.ci$a, tmp.ci$b);
}
# using the returned value to plot
if (confidence.method == 'both') {
panel.polygon(
x = c(tmp.ci$z[tmp.ci$u], rev(tmp.ci$z[tmp.ci$l])),
y = c(tmp.ci$upper.sim, rev(tmp.ci$lower.sim)),
col = '#e6e6e6',
border = '#e6e6e6',
alpha = 0.5
);
panel.polygon(
x = c(tmp.ci$z, rev(tmp.ci$z)),
y = c(tmp.ci$upper.pw, rev(tmp.ci$lower.pw)),
col = '#b5b5b5',
border = '#b5b5b5',
alpha = 0.5
);
# draw the key to indicate the two methods only once
if (1 == k) {
draw.key(
list(
text = list(
lab = c('pointwise', 'simultaneous')
),
points = list(
pch = 15,
col = c('#b5b5b5', '#e6e6e6')
)
),
draw = TRUE,
vp = viewport(x = unit(0.82, 'npc'), y = unit(0.06, 'npc'))
);
}
}
else {
if (confidence.method == 'simultaneous') {
panel.polygon(
x = c(tmp.ci$z[tmp.ci$u], rev(tmp.ci$z[tmp.ci$l])),
y = c(tmp.ci$upper.sim, rev(tmp.ci$lower.sim)),
col = '#e6e6e6',
border = '#e6e6e6',
alpha = 0.5
);
}
if (confidence.method == 'pointwise') {
panel.polygon(
x = c(tmp.ci$z, rev(tmp.ci$z)),
y = c(tmp.ci$upper.pw, rev(tmp.ci$lower.pw)),
col = '#b5b5b5',
border = '#b5b5b5',
alpha = 0.5
);
}
}
}
}
}
# draw the main plot
panel.qqmath(
x,
distribution = distribution.local,
groups = groups.local,
subscripts = subscripts,
col = col,
...
);
},
type = type,
cex = cex,
pch = pch,
col = col,
lwd = lwd,
lty = lty,
main = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = main,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
cex = main.cex,
just = main.just,
x = main.x,
y = main.y
)
),
xlab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.label,
cex = xlab.cex,
col = xlab.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' }
)
),
xlab.top = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.top.label,
cex = xlab.top.cex,
col = xlab.top.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
just = xlab.top.just,
x = xlab.top.x,
y = xlab.top.y
)
),
ylab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = ylab.label,
cex = ylab.cex,
col = ylab.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' }
)
),
scales = list(
x = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
cex = xaxis.cex,
rot = xaxis.rot,
col = xaxis.col,
limits = xlimits,
fontface = if ('Nature' == style) { 'plain' } else { xaxis.fontface },
at = xat,
labels = xaxis.lab,
log = xaxis.log,
tck = xaxis.tck,
alternating = FALSE
)
),
y = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
cex = yaxis.cex,
rot = yaxis.rot,
col = yaxis.col,
limits = ylimits,
fontface = if ('Nature' == style) { 'plain' } else { yaxis.fontface },
at = yat,
labels = yaxis.lab,
log = yaxis.log,
tck = yaxis.tck,
alternating = FALSE
)
)
),
key = key,
legend = legend,
par.settings = list(
axis.line = list(
lwd = axes.lwd,
col = if ('Nature' == style) { 'transparent' } else { 'black' }
),
layout.heights = list(
top.padding = top.padding,
main = if (is.null(main)) { 0.3 } else { 1 },
main.key.padding = 0.1,
key.top = 0.1,
key.axis.padding = 0.1,
axis.top = 1,
axis.bottom = 1,
axis.xlab.padding = 1,
xlab = 1,
xlab.key.padding = 0.5,
key.bottom = 0.1,
key.sub.padding = 0.1,
sub = 0.1,
bottom.padding = bottom.padding
),
layout.widths = list(
left.padding = left.padding,
key.left = 0.1,
key.ylab.padding = 0.1,
ylab = 1,
ylab.axis.padding = 1,
axis.left = 1,
axis.right = 1,
axis.key.padding = 0.1,
key.right = 0.1,
right.padding = right.padding
)
)
);
if (inside.legend.auto) {
extra.parameters <- list('x' = trellis.object$panel.args[[1]]$x,
'ylimits' = trellis.object$y.limits, 'xlimits' = trellis.object$x.limits);
coords <- c();
coords <- .inside.auto.legend('create.qqplot.fit', filename, trellis.object, height, width, extra.parameters);
trellis.object$legend$inside$x <- coords[1];
trellis.object$legend$inside$y <- coords[2];
}
# If Nature style requested, change figure accordingly
if ('Nature' == style) {
# Re-add bottom and left axes
trellis.object$axis <- function(side, line.col = 'black', ...) {
# Only draw axes on the left and bottom
if (side %in% c('bottom', 'left')) {
axis.default(side = side, line.col = 'black', ...);
lims <- current.panel.limits();
panel.abline(h = lims$ylim[1], v = lims$xlim[1]);
}
}
# Ensure sufficient resolution for graphs
if (resolution < 1200) {
resolution <- 1200;
warning('Setting resolution to 1200 dpi.');
}
# Other required changes which are not accomplished here
warning('Nature also requires italicized single-letter variables and en-dashes
for ranges and negatives. See example in documentation for how to do this.');
warning('Avoid red-green colour schemes, create TIFF files, do not outline the figure or legend.');
}
# Otherwise use the BL style if requested
else if ('BoutrosLab' == style) {
# Nothing happens
}
# if neither of the above is requested, give a warning
else {
warning("The style parameter only accepts 'Nature' or 'BoutrosLab'.");
}
# output the object
return(
BoutrosLab.plotting.general::write.plot(
trellis.object = trellis.object,
filename = filename,
height = height,
width = width,
size.units = size.units,
resolution = resolution,
enable.warnings = enable.warnings,
description = description
)
);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/create.qqplot.fit.R
|
# The BoutrosLab.statistics.general package is copyright (c) 2011 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
create.qqplot.fit.confidence.interval <- function(x, distribution = qnorm, conf = 0.95, conf.method = "both", reference.line.method = "quartiles") {
# remove the NA and sort the sample
# the QQ plot is the plot of the sorted sample against the corresponding quantile from the theoretical distribution
sorted.sample <- sort(x[!is.na(x)]);
# the corresponding probabilities, should be (i - 0.5)/n, where i = 1,2,3,...,n
probabilities <- ppoints(length(sorted.sample));
# the corresponding quantile under the theoretical distribution
theoretical.quantile <- distribution(probabilities);
if(reference.line.method == "quartiles") {
# get the numbers of the 1/4 and 3/4 quantile in order to draw a reference line
quantile.x.axis <- quantile(sorted.sample, c(0.25, 0.75));
quantile.y.axis <- distribution(c(0.25, 0.75));
# the intercept and slope of the reference line
b <- (quantile.x.axis[2] - quantile.x.axis[1]) / (quantile.y.axis[2] - quantile.y.axis[1]);
a <- quantile.x.axis[1] - b * quantile.y.axis[1];
}
if(reference.line.method == "diagonal") {
a <- 0;
b <- 1;
}
if(reference.line.method == "robust") {
coef.linear.model <- coef(lm(sorted.sample ~ theoretical.quantile));
a <- coef.linear.model[1];
b <- coef.linear.model[2];
}
# the reference line
fit.value <- a + b * theoretical.quantile;
# create some vectors to store the returned values
upper.pw <- NULL;
lower.pw <- NULL;
upper.sim <- NULL;
lower.sim <- NULL;
u <- NULL; # a vector of logical value of whether the probabilities are in the interval [0,1] for the upper band
l <- NULL; # a vector of logical value of whether the probabilities are in the interval [0,1] for the lower band
### pointwise method
if (conf.method == "both" | conf.method == "pointwise") {
# create the numeric derivative of the theoretical quantile distribution
numeric.derivative <- function(p) {
# set the change in independent variable
h <- 10^(-6);
if (h * length(sorted.sample) > 1) { h <- 1 / (length(sorted.sample) + 1); }
# the function
return((distribution(p + h/2) - distribution(p - h/2)) / h);
}
# the standard errors of pointwise method
data.standard.error <- b * numeric.derivative(probabilities) * qnorm(1 - (1 - conf)/2) * sqrt(probabilities * (1 - probabilities) / length(sorted.sample));
# confidence interval of pointwise method
upper.pw <- fit.value + data.standard.error;
lower.pw <- fit.value - data.standard.error;
}
### simultaneous method
if (conf.method == "both" | conf.method == "simultaneous") {
# get the threshold value for the statistics---the absolute difference of the empirical cdf and the theoretical cdf
# Note that this statistics should follow a kolmogorov distribution when the sample size is large
# the critical value from the Kolmogorov-Smirnov Test
critical.value <- BoutrosLab.plotting.general::critical.value.ks.test(length(sorted.sample), conf);
# under the null hypothesis, get the CI for the probabilities
# the probabilities of the fitted value under the empirical cdf
expected.prob <- ecdf(sorted.sample)(fit.value);
# the probability should be in the interval [0, 1]
u <- (expected.prob + critical.value) >= 0 & (expected.prob + critical.value) <= 1;
l <- (expected.prob - critical.value) >= 0 & (expected.prob - critical.value) <= 1;
# get the corresponding quantiles from the theoretical distribution
z.upper <- distribution((expected.prob + critical.value)[u]);
z.lower <- distribution((expected.prob - critical.value)[l]);
# confidence interval of simultaneous method
upper.sim <- a + b * z.upper;
lower.sim <- a + b * z.lower;
}
# return the values for constructing the Confidence Bands of one sample QQ plot
# the list to store the returned values
returned.values <- list(
a = a,
b = b,
z = theoretical.quantile,
upper.pw = upper.pw,
lower.pw = lower.pw,
u = u,
l = l,
upper.sim = upper.sim,
lower.sim = lower.sim
);
return (returned.values);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/create.qqplot.fit.confidence.interval.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2013 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### inside.ellipse #################################################################################
#
# PURPOSE
# Produces an NxM matrix of booleans corresponding to N data points (data.x and data.y)
# being inside M ellipses (ellipse.center.x, ellipse.radii.x, ellipse.center.y, ellipse.radii.y).
#
# INPUT
# ellipse.center.x: is an numeric defining the x coordinate(s) of the ellipse center
# ellipse.center.y: is an numeric defining the y coordinate(s) of the ellipse center
# ellipse.radii.x: is an numeric defining the radius(radii) lengths along the x axis
# ellipse.radii.y: is an numeric defining the radius(radii) lengths along the y axis
# data.x: the numeric data x coordinates of the data points to check if they are inside the ellipse
# data.y: the numeric data y coordinates of the data points to check if they are inside the ellipse
#
# OUTPUT
# An NxM matrix of booleans where N defines all the data points and M are all the possible ellipses.
#
####################################################################################################
inside.ellipse <- function(ellipse.center.x, ellipse.center.y, ellipse.radii.x, ellipse.radii.y, data.x, data.y) {
### PARAMETER CHECK ########################################################################
# ensure input variables are numeric, otherwise throw a warning.
if (!is.numeric(ellipse.center.x) || !is.numeric(ellipse.radii.x) || !is.numeric(ellipse.center.y) ||
!is.numeric(ellipse.radii.y) || !is.numeric(data.x) || !is.numeric(data.y)) {
warning('In inside.ellipse: input variables are not all numeric.');
}
# ensure input variable are vectors, otherwise throw a warning.
if (!is.vector(ellipse.center.x) || !is.vector(ellipse.radii.x) || !is.vector(ellipse.center.y) ||
!is.vector(ellipse.radii.y) || !is.vector(data.x) || !is.vector(data.y)) {
warning('In inside.ellipse: input variables are not all vectors.');
}
# ensure the lengths of the variables defining all the ellipses are the same
if (!(
length(ellipse.center.x) == length(ellipse.center.y) &&
length(ellipse.radii.x) == length(ellipse.radii.y) &&
length(ellipse.center.x) == length(ellipse.radii.x)
)) {
warning('In inside ellipse: The length of ellipse.center.x, ellipse.radii.x, ellipse.center.y and ellipse.radii.y are not all the same.');
}
# ensure the lengths of the data points are the same
if (!length(data.x) == length(data.y)) {
warning('In inside.ellipse: The length of data.x and data.y are different.');
}
### ELLIPSE CALCULATION ####################################################################
# for every element in data.x and every element in ellipse.center.x, compute the cartesian
# subtraction, such that the resulting variable is a matrix with row i representing
# the difference between the ith data.x and all the ellipse.center.x
difference.x <- outer(
X = data.x,
Y = ellipse.center.x,
FUN = '-'
);
# for every element in data.y and every element in ellipse.center.y, compute the cartesian
# subtraction, such that the resulting variable is a matrix with row i representing
# the difference between the ith data.y and all the ellipse.center.y
difference.y <- outer(
X = data.y,
Y = ellipse.center.y,
FUN = '-'
);
# a matrix of booleans corresponding to the outcome of data points data.x and data.y being inside ellipses
# defined by the 4 ellipse variables (ellipse.center.x, ellipse.center.y, ellipse.radii.x, ellipse.radii.y).
# Currently this matrix has rows as the data.points and columns as the ellipses. Thus at row i and column j
# We have data.point i and ellipse j.
inside.ellipse.outcome <- ( (difference.x / ellipse.radii.x) ^ 2) + ( (difference.y / ellipse.radii.y) ^ 2) <= 1;
return(inside.ellipse.outcome);
}
### inside.rectangle ###############################################################################
#
# PURPOSE
# Produces an NxM matrix of booleans corresponding to N data points (data.x and data.y)
# being inside M ellipses (ellipse.center.x, ellipse.radii.x, ellipse.center.y, ellipse.radii.y).
#
# INPUT
# rectangle.center.x: is an numeric defining the x coordinate(s) of the rectangle center
# rectangle.center.y: is an numeric defining the y coordinate(s) of the rectangle center
# rectangle.width: is an numeric defining the width (the length of the rectangle along the x axis) of the rectangle
# rectangle.height: is an numeric defining the height (the length of the rectangle along the y axis) of the rectangle
# data.x: the numeric data x coordinates of the data points to check if they are inside the ellipse
# data.y: the numeric data y coordinates of the data points to check if they are inside the ellipse
#
# OUTPUT
# An NxM matrix of booleans where N defines all the data points and M are all the possible rectangles.
#
####################################################################################################
inside.rectangle <- function(rectangle.center.x, rectangle.center.y, rectangle.width, rectangle.height, data.x, data.y) {
### PARAMETER CHECK ########################################################################
# ensure all variables are numeric, otherwise throw a warning
if (!is.numeric(rectangle.center.x) || !is.numeric(rectangle.center.y) || !is.numeric(rectangle.width)
|| !is.numeric(rectangle.height) || !is.numeric(data.x) || !is.numeric(data.y)) {
warning('Variables passed to inside.rectangle are not all numeric.');
}
# ensure all variables are vectors, otherwise throw a warning
if (!is.vector(rectangle.center.x) || !is.vector(rectangle.center.y) || !is.vector(rectangle.width)
|| !is.vector(rectangle.height) || !is.vector(data.x) || !is.vector(data.y)) {
warning('Variables passed to inside.rectangle are not all vectors.');
}
# ensure all variables defining the rectangles are of the same length
if (length(rectangle.center.x) != length(rectangle.center.y) || length(rectangle.height) != length(rectangle.width)) {
warning('Variables which define the rectangle in inside.rectangle are not all of the same length.');
}
# ensure all variables defining the data points are of the same length
if (length(data.x) != length(data.y)) {
warning('Variables which define the data points in inside.rectangle are no all of the same length.');
}
### RECTANGLE CALCULATION ##################################################################
# replicate values in rectangle.center.x by the length of data.x
# this is done to vectorize the boolean calculation and to avoid matrices.
# in general we are computing the cartesian outcome of all defined rectangles and all
# data points, thus we need some variable to contain at least n x m scalars.
# this is that variable
tmp.x <- rep(
x = rectangle.center.x,
each = length(data.x)
);
# same as tmp.x except for y values
tmp.y <- rep(
x = rectangle.center.y,
each = length(data.y)
);
# check if any data points are within the width of the label. Since we have a vector
# repeated rectangle.center.x values such that the first element is repeated by the length
# of data.x followed by the second elment and so forth. We can use vector recycling to ensure
# that ever rectangle.center.x will be compared with every data.x
inside.rectangle.outcome.x <- (tmp.x - (rectangle.width / 2)) < data.x & data.x < (tmp.x + (rectangle.width / 2));
# same as inside.rectangle.outcome.x, except for y values
inside.rectangle.outcome.y <- (tmp.y - (rectangle.height / 2)) < data.y & data.y < (tmp.y + (rectangle.height / 2));
# generate a matrix of booleans outlining where data falls inside the any of the defined
# rectangles.
inside.rectangle.outcome <- matrix(
data = inside.rectangle.outcome.x & inside.rectangle.outcome.y,
ncol = length(data.x),
byrow = TRUE
);
return(inside.rectangle.outcome);
}
### FUNCTION TO CREATE SCATTERPLOTS ###############################################################
create.lollipopplot <- create.scatterplot <- function(
formula, data, filename = NULL, groups = NULL, main = NULL, main.just = 'center', main.x = 0.5,
main.y = 0.5, main.cex = 3, xlab.label = tail(sub('~', '', formula[-2]), 1),
ylab.label = tail(sub('~', '', formula[-3]), 1), xlab.cex = 2, ylab.cex = 2, xlab.col = 'black',
ylab.col = 'black', xlab.top.label = NULL, xlab.top.cex = 2, xlab.top.col = 'black', xlab.top.just = 'center',
xlab.top.x = 0.5, xlab.top.y = 0, xlimits = NULL, ylimits = NULL, xat = TRUE, yat = TRUE, xaxis.lab = NA,
yaxis.lab = NA, xaxis.log = FALSE, yaxis.log = FALSE, xaxis.cex = 1.5, yaxis.cex = 1.5, xaxis.rot = 0,
yaxis.rot = 0, xaxis.fontface = 'bold', yaxis.fontface = 'bold', xaxis.col = 'black', yaxis.col = 'black',
xaxis.tck = c(1, 1), yaxis.tck = c(1, 1), add.grid = FALSE, xgrid.at = xat, ygrid.at = yat, grid.colour = NULL,
horizontal = FALSE, type = 'p', cex = 0.75, pch = 19, col = 'black', col.border = 'black', lwd = 1, lty = 1,
alpha = 1, axes.lwd = 1, strip.col = 'white', strip.cex = 1, strip.fontface = 'bold', y.error.up = NULL,
y.error.down = y.error.up, x.error.right = NULL, x.error.left = x.error.right, y.error.bar.col = 'black',
x.error.bar.col = y.error.bar.col, error.whisker.angle = 90, error.bar.lwd = 1, error.bar.length = 0.1,
key = list(text = list(lab = c(''))), legend = NULL, top.padding = 0.1, bottom.padding = 0.7,
right.padding = 0.1, left.padding = 0.5, key.top = 0.1, key.left.padding = 0, ylab.axis.padding = 1,
axis.key.padding = 1, layout = NULL, as.table = FALSE, x.spacing = 0, y.spacing = 0, x.relation = 'same',
y.relation = 'same', add.axes = FALSE, axes.lty = 'dashed', add.xyline = FALSE, xyline.col = 'black',
xyline.lwd = 1, xyline.lty = 1, abline.h = NULL, abline.v = NULL, abline.col = 'black', abline.lwd = 1,
abline.lty = 1, add.curves = FALSE, curves.exprs = NULL, curves.from = min(data, na.rm = TRUE),
curves.to = max(data, na.rm = TRUE), curves.col = 'black', curves.lwd = 2, curves.lty = 1, add.rectangle = FALSE,
xleft.rectangle = NULL, ybottom.rectangle = NULL, xright.rectangle = NULL, ytop.rectangle = NULL,
col.rectangle = 'transparent', alpha.rectangle = 1, add.points = FALSE, points.x = NULL, points.y = NULL,
points.pch = 19, points.col = 'black', points.col.border = 'black', points.cex = 1, add.line.segments = FALSE,
line.start = NULL, line.end = NULL, line.col = 'black', line.lwd = 1, add.text = FALSE, text.labels = NULL,
text.x = NULL, text.y = NULL, text.col = 'black', text.cex = 1, text.fontface = 'bold', text.guess.labels = FALSE,
text.guess.skip.labels = TRUE, text.guess.ignore.radius = FALSE, text.guess.ignore.rectangle = FALSE,
text.guess.radius.factor = 1, text.guess.buffer.factor = 1, text.guess.label.position = NULL, height = 6,
width = 6, size.units = 'in', resolution = 1600, enable.warnings = FALSE,
description = 'Created with BoutrosLab.plotting.general', style = 'BoutrosLab', preload.default = 'custom',
group.specific.colouring = TRUE, use.legacy.settings = FALSE, inside.legend.auto = FALSE,
regions.labels = c(), regions.start = c(), regions.stop = c(), regions.color = c('red'), regions.cex = 1,
regions.alpha = 1, lollipop.bar.y = NULL, lollipop.bar.color = 'gray', ...
) {
function.name <- match.call()[[1]];
lollipop.plot <- FALSE;
if (function.name == 'create.lollipopplot') {
lollipop.plot <- TRUE;
}
### needed to copy in case using variable to define rectangles dimensions
rectangle.info <- list(
xright = xright.rectangle,
xleft = xleft.rectangle,
ytop = ytop.rectangle,
ybottom = ybottom.rectangle
);
text.info <- list(
labels = text.labels,
x = text.x,
y = text.y,
col = text.col,
cex = text.cex,
fontface = text.fontface
);
# check class of conditioning variable
if ('|' %in% all.names(formula)) {
variable <- sub('^\\s+', '', unlist(strsplit(toString(formula[length(formula)]), '\\|'))[2]);
if (variable %in% names(data)) {
cond.class <- class(data[, variable]);
if (cond.class %in% c('integer', 'numeric')) {
warning(
'Numeric values detected for conditional variable. If text labels are desired, please convert conditional variable to character.'
);
}
rm(cond.class);
}
}
out <- prep.axis(
at = xat,
data = unlist(data[toString(formula[[3]])]),
which.arg = 'xat'
);
if (is.list(out)) {
data[toString(formula[[3]])] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
out <- prep.axis(
at = yat,
data = unlist(data[toString(formula[[2]])]),
which.arg = 'yat'
);
if (is.list(out)) {
data[toString(formula[[2]])] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
# add preloaded defaults
if (preload.default == 'paper') {
}
else if (preload.default == 'web') {
}
# update groups function
groups.new <- eval(substitute(groups), data, parent.frame());
# error checking
if (add.curves & !all(sapply(data, is.numeric))) {
warning('Curves cannot be drawn with grouping variables.');
data <- data[, sapply(data, is.numeric)];
}
# auto set parameters
if (length(xat) == 1 && xat == TRUE && length(xlimits) == 0) {
adjustedformula <- as.formula(paste0(as.character(formula[2]), '~', strsplit(as.character(formula[3]), ' [|] ')[[1]][1]));
if (is.numeric(model.frame(adjustedformula, data)[1, 2])) {
minimum <- min(model.frame(adjustedformula, data)[2]);
maximum <- max(model.frame(adjustedformula, data)[2]);
# if minimum is greater than 0 make sure to display 0
minimum <- min(minimum, 0);
difference <- maximum - minimum;
lognumber <- floor(log(difference, 10));
# depending on difference, the labels will be multiples of 5, 10 or 20
if (difference < (10 ** lognumber * 4)) { factor <- (10 ** lognumber) / 2; }
else if (difference < (10 ** lognumber * 7)) { factor <- (10 ** lognumber); }
else { factor <- (10 ** lognumber) * 2; }
addition <- factor / 2;
# depending on minimum create a sequence of at locations with padding
if (minimum == 0) { at <- seq(0, factor * round(maximum / factor) + addition, factor); }
else {
at <- seq(factor * round(minimum / factor), factor * round(maximum / factor) + addition, factor);
# only add padding to minimum if it is not 0
minimum <- minimum - addition;
}
# add padding to max
maximum <- maximum + addition;
xlimits <- c(minimum, maximum);
xat <- at;
}
}
if (length(yat) == 1 && yat == TRUE && length(ylimits) == 0) {
adjustedformula <- as.formula(paste0(as.character(formula[2]), '~', strsplit(as.character(formula[3]), ' [|] ')[[1]][1]));
if (is.numeric(as.vector(model.frame(adjustedformula, data)[1, 1]))) {
minimum <- min(model.frame(adjustedformula, data)[1]);
maximum <- max(model.frame(adjustedformula, data)[1]);
# if minimum is greater than 0 make sure to display 0
minimum <- min(minimum, 0);
# special case, if all y are the same value, and that value is 0
if ((minimum == 0) & (maximum == 0)) {
minimum <- -1;
maximum <- 1;
}
difference <- maximum - minimum;
lognumber <- floor(log(difference, 10));
# special case, if all y are the same value, and that value is < 0
if ((difference == 0) & (minimum < 0)) {
maximum <- max(maximum, 0);
difference <- maximum - minimum;
lognumber <- floor(log(difference, 10));
}
# depending on difference, the labels will be multiples of 5,10 or 20
if (difference < (10 ** lognumber * 4)) { factor <- (10 ** lognumber) / 2; }
else if (difference < (10 ** lognumber * 7)) { factor <- (10 ** lognumber); }
else { factor <- (10 ** lognumber) * 2; }
addition <- factor / 2;
# depending on minimum create a sequence of at locations with padding
if (minimum == 0) {
at <- seq(0, factor * round(maximum / factor) + addition, factor);
}
else {
at <- seq(factor * round(minimum / factor), factor * round(maximum / factor) + addition, factor);
# only add padding to minimum if it is not 0
minimum <- minimum - addition;
}
# add padding to max
maximum <- maximum + addition;
ylimits <- c(minimum, maximum);
yat <- at;
}
}
# If formula contains conditioning variables, then only one colour is allowed for
# horizontal error bars, and one colour is allowed for vertical error bars.
# In other words, under conditioning, the error bar colouring currently does NOT
# respect grouping. This issue needs to be resolved in the future.
if ('|' %in% all.names(formula)) {
if (length(x.error.bar.col) > 1) {
stop(
paste(
'When there are conditioning variables, only one horizontal error bar colour is currently supported, but length of given x.error.bar.col is ',
length(x.error.bar.col),
'.',
sep = ''
)
);
}
if (length(y.error.bar.col) > 1) {
stop(
paste(
'When there are conditioning variables, only one vertical error bar colour is currently supported, but length of given y.error.bar.col is ',
length(y.error.bar.col),
'.',
sep = ''
)
);
}
}
# If formula does NOT contain conditioning variables,
# then group-specific error bar colouring is supported.
else if (group.specific.colouring == TRUE) {
# generate the vector of colours for horizontal error bars, by remapping
# the levels of the grouping variable according to x.error.bar.col
# if x.error.bar.col is NOT a vector, do nothing
if (length(x.error.bar.col) > 1) {
if (length(x.error.bar.col) == length(levels(groups))) {
x.error.bar.col <- as.character(factor(groups, labels = x.error.bar.col));
}
else {
stop(
paste(
'The number (',
length(levels(groups)),
') of levels of the grouping variable does not equal the length (',
length(x.error.bar.col),
') of x.error.bar.col.',
' set group.specific.colouring = FALSE to acoomplish this',
sep = ''
)
);
}
}
# generate the vector of colours for vertical error bars, by remapping
# the levels of the grouping variable according to y.error.bar.col
# if y.error.bar.col is NOT a vector, do nothing
if (length(y.error.bar.col) > 1) {
if (length(y.error.bar.col) == length(levels(groups))) {
y.error.bar.col <- as.character(factor(groups, labels = y.error.bar.col));
}
else {
stop(
paste(
'The number (',
length(levels(groups)),
') of levels of the grouping variable does not equal the length (',
length(y.error.bar.col),
') of y.error.bar.col.',
' set group.specific.colouring = FALSE to acoomplish this',
sep = ''
)
);
}
}
}
### AUTOMATIC LABEL POSITIONING ################################################################
# Variables to decide whether or not the program should continue with the automatic
# labeling algorithm. This variables purpose is to help organize the code and prevent
# a large amount of indentation
safe.to.guess <- TRUE;
added.x <- vector();
added.y <- vector();
if (add.text) {
### VARIABLE DECLARATION ###############################################################
# These variables are used to define only those values which are used in the automatic label
# positioning algorithm
guess.x <- vector();
guess.y <- vector();
guess.labels <- vector();
guess.col <- vector();
guess.cex <- vector();
guess.fontface <- vector();
guess.skip.labels <- vector();
guess.radius.factor <- vector();
guess.buffer.factor <- vector();
guess.label.position <- vector();
guess.ignore.radius <- vector();
guess.ignore.rectangle <- vector();
### PARAMETER CHECKS ###################################################################
# in order to automatically guess label positions, the user must have defined at least
# one value in text.guess.labels to be TRUE.
if (!any(text.guess.labels)) {
# No label positions will be guessed
safe.to.guess <- FALSE;
}
# The block within this if statement has organized parameter checks checking if the data types
# of the input variables are correct. If a single variable or multiple variables are incorrect
# a warning will be thrown per incorrect variable and safe.to.guess will become FALSE preventing
# any further paramter blocks from occuring and the overall automatic label positioning algorithm
if (safe.to.guess) {
# Ensure text.x is a numeric
if (!is.numeric(text.x)) {
warning("Argument 'text.x' is not numeric, automatic label positioning will not occur.");
safe.to.guess <- FALSE;
}
# Ensure text.y is a numeric
if (!is.numeric(text.y)) {
warning("Argument 'text.y' is not numeric, automatic label positioning will not occur.");
safe.to.guess <- FALSE;
}
# Ensure text.guess.radius.factor is a numeric
if (!is.numeric(text.guess.radius.factor)) {
warning("Argument 'text.guess.radius.factor' is not numeric, automatic label positioning will not occur.");
safe.to.guess <- FALSE;
}
# Ensure text.guess.buffer.factor is a numeric
if (!is.numeric(text.guess.buffer.factor)) {
warning("Argument 'text.guess.buffer.factor' is not numeric, automatic label positioning will not occur.");
safe.to.guess <- FALSE;
}
# Ensure text.guess.label.position is a integer
if (!is.numeric(text.guess.label.position) & !is.null(text.guess.label.position)) {
warning("Argument 'text.guess.label.position' is not numeric, automatic label positioning will not occur.");
safe.to.guess <- FALSE;
}
# Ensure text.guess.labels is logical
if (!is.logical(text.guess.labels)) {
warning("Argument 'text.guess.labels' is not logical, automatic label positioning will not occur.");
safe.to.guess <- FALSE;
}
# Ensure text.skip.labels is logical
if (!is.logical(text.guess.skip.labels)) {
warning("Argument 'text.guess.skip.labels' is not logical, automatic label positioning will not occur.");
safe.to.guess <- FALSE;
}
# Ensure text.ignore.radius is logical
if (!is.logical(text.guess.ignore.radius)) {
warning("Argument 'text.guess.ignore.radius' is not logical, automatic label positioning will not occur.");
safe.to.guess <- FALSE;
}
# Ensure text.guess.ignore.rectangle is logical
if (!is.logical(text.guess.ignore.rectangle)) {
warning("Argument 'text.guess.ignore.rectangle' is not logical, automatic label positioning will not occur.");
safe.to.guess <- FALSE;
}
}
# The block within this if statement has organized parameter checks checking if all variables
# are multiples of the largest fundamental variable. Fundamental variables are text.guess.labels,
# text.x or text.y. If a single variable or multiple variables are not multiples of the max length
# of these three variables a warning will be thrown per incorrect variable and safe.to.guess will
# become FALSE preventing any further paramter blocks from occuring and the overall automatic
# label positioning algorithm.
if (safe.to.guess) {
# Calculate the max length of the variables. This is used to check if all
# other variables are multiples of this length.
len <- max(length(text.guess.labels), length(text.x), length(text.x));
# Check if text.x is a multiple of text.guess.labels or text.y
if (len %% length(text.x) != 0) {
warning("Argument 'text.x' is not a multiple of 'text.guess.labels' or 'text.y'.");
safe.to.guess <- FALSE;
}
# Check if text.y is a multiple of text.guess.labels or text.x
if (len %% length(text.y) != 0) {
warning("Argument 'text.y' is not a multiple of 'text.guess.labels' or 'text.x'.");
safe.to.guess <- FALSE;
}
# Check if text.guess.labels is a multiple of text.x or text.y
if (len %% length(text.guess.labels) != 0) {
warning("Argument 'text.guess.labels' is not a multiple of 'text.x' or 'text.y'.");
safe.to.guess <- FALSE;
}
# Check if text.guess.radius.factor is a multiple of text.guess.labels, text.x or text.y
if (len %% length(text.guess.radius.factor) != 0) {
warning("Argument 'text.guess.radius.factor' is not a multiple of 'text.guess.labels', 'text.x' or 'text.y'.");
safe.to.guess <- FALSE;
}
# Check if text.guess.buffer.factor is a multiple of text.guess.labels, text.x or text.y
if (len %% length(text.guess.buffer.factor) != 0) {
warning("Argument 'text.guess.buffer.factor' is not a multiple of 'text.guess.labels', 'text.x' or 'text.y'.");
safe.to.guess <- FALSE;
}
# Check if text.guess.label.position is a multiple of text.guess.labels, text.x or text.y
if (!is.null(text.guess.label.position)) {
if (len %% length(text.guess.label.position) != 0) {
warning("Argument 'text.guess.label.position' is not a multiple of 'text.guess.labels', 'text.x' or 'text.y'.");
safe.to.guess <- FALSE;
}
}
# Check if text.guess.skip.labels is a multiple of text.guess.labels, text.x or text.y
if (len %% length(text.guess.skip.labels) != 0) {
warning("Argument 'text.guess.skip.labels' is not a multiple of 'text.guess.labels', 'text.x' or 'text.y'.");
safe.to.guess <- FALSE;
}
# Check if text.guess.ignore.radius is a multiple of text.guess.labels, text.x or text.y
if (len %% length(text.guess.ignore.radius) != 0) {
warning("Argument 'text.guess.ignore.radius' is not a multiple of 'text.guess.labels', 'text.x' or 'text.y'.");
safe.to.guess <- FALSE;
}
# Check if text.guess.ignore.rectangle is a multiple of text.guess.labels, text.x or text.y
if (len %% length(text.guess.ignore.rectangle) != 0) {
warning("Argument 'test.guess.ignore.rectangle' is not a multiple of 'text.guess.labels', 'text.x' or 'text.y'.");
safe.to.guess <- FALSE;
}
}
# This is the final if block for safe.to.guess. If all other paramter checks have passed
# The algorithm will continue.
if (safe.to.guess) {
# The following code makes all variables the same length so that variables can be
# divided into two groups. The first group being the set of variables responsible
# for manual labeling positioning. The second gorup being the set of variables
# responsible for automatic labelling.
len <- max(length(text.guess.labels), length(text.x), length(text.x));
text.x <- rep(
x = text.x,
times = len / length(text.x)
);
text.y <- rep(
x = text.y,
times = len / length(text.y)
);
text.col <- rep(
x = text.col,
times = len / length(text.col)
);
text.cex <- rep(
x = text.cex,
times = len / length(text.cex)
);
text.fontface <- rep(
x = text.fontface,
times = len / length(text.fontface)
);
text.guess.skip.labels <- rep(
x = text.guess.skip.labels,
times = len / length(text.guess.skip.labels)
);
text.guess.labels <- rep(
x = text.guess.labels,
times = len / length(text.guess.labels)
);
text.guess.ignore.radius <- rep(
x = text.guess.ignore.radius,
times = len / length(text.guess.ignore.radius)
);
text.guess.ignore.rectangle <- rep(
x = text.guess.ignore.rectangle,
times = len / length(text.guess.ignore.rectangle)
);
text.guess.radius.factor <- rep(
x = text.guess.radius.factor,
times = len / length(text.guess.radius.factor)
);
text.guess.buffer.factor <- rep(
x = text.guess.buffer.factor,
times = len / length(text.guess.buffer.factor)
);
if (!is.null(text.guess.label.position)) {
text.guess.label.position <- rep(
x = text.guess.label.position,
times = len / length(text.guess.label.position)
);
}
# These are the variables responsible for the automatic labeling
# separate the values from the mixed paramters into the only
# automatic labeling variables
guess.x <- text.x[text.guess.labels];
guess.y <- text.y[text.guess.labels];
guess.labels <- text.labels[text.guess.labels];
guess.col <- text.col[text.guess.labels];
guess.cex <- text.cex[text.guess.labels];
guess.fontface <- text.fontface[text.guess.labels];
guess.skip.labels <- text.guess.skip.labels[text.guess.labels];
guess.radius.factor <- text.guess.radius.factor[text.guess.labels];
guess.buffer.factor <- text.guess.buffer.factor[text.guess.labels];
if (!is.null(text.guess.label.position)) {
guess.label.position <- text.guess.label.position[text.guess.labels];
}
guess.ignore.radius <- text.guess.ignore.radius[text.guess.labels];
guess.ignore.rectangle <- text.guess.ignore.rectangle[text.guess.labels];
# These are the variables responsible for the manual labeling
# remove all the automatic labeling values as they have already
# been stored in separate variables.
text.x <- text.x[!text.guess.labels];
text.y <- text.y[!text.guess.labels];
text.labels <- text.labels[!text.guess.labels];
text.col <- text.col[!text.guess.labels];
text.cex <- text.cex[!text.guess.labels];
text.fontface <- text.fontface[!text.guess.labels];
# This is the variable which will store the final guessed values from the
# automatic labeling algorithm for the x coordinate. It corresponds to the
# x position for the center of the label (rectangle).
final.x <- vector(
mode = 'numeric',
length = length(guess.x)
);
# The same as final.x except for the y coordinate
final.y <- vector(
mode = 'numeric',
length = length(guess.x)
);
# obtain x and y values from data to use in calculations
adjustedformula <- as.formula(paste0(as.character(formula[2]), '~', strsplit(as.character(formula[3]), ' [|] ')[[1]][1]));
data.x <- as.numeric(as.matrix(model.frame(adjustedformula, data)[2]));
data.y <- as.numeric(as.matrix(model.frame(adjustedformula, data)[1]));
# boolean used to check if xlimits or ylimits are defined
# There are two options at defining the data space for a trellis object. One can
# poorly estimate using the range of the data or they can have the best estimate by
# using defined xlimits and ylimits of a graph. In order to produce accurate label positions
# it is recommended that xlimits and ylimits be defined
better.guess <- TRUE;
# check if xlimits is defined to obtain range for radius and text width calculations
if (is.null(xlimits)) {
warning("Argument 'xlimits' is undefined, collision of text and points is more likely.");
better.guess <- FALSE;
}
# check is ylimits is defined to obtain range for radius and text width calculations
if (is.null(ylimits)) {
warning("Argument 'ylimits' is undefined, collision of text and points is more likely.");
better.guess <- FALSE;
}
# try and determine the plot range to calculate the most accurate radius
range.x <- NA;
range.y <- NA;
# vectors storing the added guessed positions. This is different from final.x and
# final.y as they will not store NA's if variables are skipped
added.x <- vector();
added.y <- vector();
# if xlimits and ylimits are defined, use these for range calculations
if (better.guess) {
range.x <- xlimits[2] - xlimits[1];
range.y <- ylimits[2] - ylimits[1];
}
else {
# otherwise, guess that the graph limits will be close to the extremities
tmp.x <- range(data.x);
range.x <- tmp.x[2] - tmp.x[1];
tmp.y <- range(data.y);
range.y <- tmp.y[2] - tmp.y[1];
}
# vectors storing the added guessed positions. This is different from final.x and
# final.y as they will not store NA's if variables are skipped
for (i in 1:length(guess.x)) {
# calculates the text width of each label.
# used to check if points are in label position areas
unit.text.width <- strwidth(
s = guess.labels[i],
units = 'figure',
cex = guess.cex[i]
);
# calculates the text height of each label.
# used to check if points are in label position areas
unit.text.height <- strheight(
s = guess.labels[i],
units = 'figure',
cex = guess.cex[i]
);
# calculate the width of some character string.
# This string has been predetermined to produce relatively good
# radius lengths
unit.radius <- strwidth(
s = '----',
units = 'figure',
cex = guess.cex[i]
);
unit.buffer <- unit.radius;
# if radius.factor is defined, adjust unit.radius by the factor
unit.radius <- unit.radius * guess.radius.factor[i];
# if radius.factor is defined, adjust unit.radius by the factor
unit.buffer <- unit.buffer * guess.buffer.factor[i];
# produce 360 potential points around each (guess.x, guess.y)
angles <- 0:359 * pi / 180;
# Calculate the x axis radius of the ellipse for
radius.x <- guess.x[i] + (unit.radius * range.y * cos(angles));
buffer.x <- guess.x[i] + ( (unit.radius + unit.buffer) * range.x * cos(angles));
radius.y <- guess.y[i] + (unit.radius * range.y * sin(angles));
buffer.y <- guess.y[i] + ( (unit.radius + unit.buffer) * range.y * sin(angles));
# Determine the center positions of the text boxes
rect.x <- (guess.x[i] + ( (unit.text.width / 2) + unit.radius) * range.x * cos(angles));
rect.y <- (guess.y[i] + ( (unit.text.height / 2) + unit.radius) * range.y * sin(angles));
if (is.numeric(guess.label.position[i])) {
rect.x <- (guess.x[i] + ( (unit.text.width / 2) + unit.radius) * range.x * cos(guess.label.position[i] * pi / 180));
rect.y <- (guess.y[i] + ( (unit.text.height / 2) + unit.radius) * range.y * sin(guess.label.position[i] * pi / 180));
final.x[i] <- rect.x;
final.y[i] <- rect.y;
added.x <- c(added.x, final.x[i]);
added.y <- c(added.y, final.y[i]);
}
else {
# We remove the data point which is identical to guess.x and guess.y so that the algorithm
# doesn't mistakenly consider this as a point within the ellipse, which will result in removed
# label positions.
valid.data.points <- !(data.x == guess.x[i] & data.y == guess.y[i]);
# This is a boolean for each potential label position around a single guess.x and guess.y.
# During the algorithm, positions around an ellipse are determined to be suitable or not
# suitable for label positioning. If they are sutiable they remain true, otherwise, they
# are false and are no longer available for labelling.
valid.labels <- rep(TRUE, 360);
# Enter the ellipse calculation portion of the algorithm
if (!guess.ignore.radius[i]) {
in.ellipse <- as.vector(inside.ellipse(
ellipse.center.x = guess.x[i],
ellipse.center.y = guess.y[i],
ellipse.radii.x = (unit.radius + unit.buffer) * range.x,
ellipse.radii.y = (unit.radius + unit.buffer) * range.y,
data.x = data.x[valid.data.points],
data.y = data.y[valid.data.points]
));
if (any(in.ellipse)) {
for (j in order(in.ellipse, decreasing = TRUE)[1:sum(in.ellipse)]) {
tmp.x <- data.x[valid.data.points][j];
tmp.y <- data.y[valid.data.points][j];
line.slope <- (tmp.y - guess.y[i]) / (tmp.x - guess.x[i]);
perp.line.slope <- -1 / line.slope;
vertical.shift <- guess.y[i] - (perp.line.slope * guess.x[i]);
other.x <- tmp.x + 1;
other.y <- (perp.line.slope * other.x) + vertical.shift;
if (!is.finite(perp.line.slope)) {
other.y <- guess.y + 1;
other.x <- guess.x;
}
# INFORMATION PLEASE
position <- sign(
(other.x - guess.x[i]) * (buffer.y - guess.y[i]) -
(other.y - guess.y[i]) * (buffer.x - guess.x[i])
);
# COMMENTS
if (!is.finite(perp.line.slope)) {
if (tmp.x >= guess.x[i]) {
valid.labels <- valid.labels & (position < 1);
}
else {
valid.labels <- valid.labels & (position > -1);
}
}
else if (tmp.x >= (tmp.y - vertical.shift) / perp.line.slope) {
valid.labels <- valid.labels & (position < 1);
}
else {
valid.labels <- valid.labels & (position > -1);
}
}
}
}
# COMMENT
if (!guess.ignore.rectangle[i]) {
in.rectangle <- inside.rectangle(
rectangle.center.x = rect.x[valid.labels],
rectangle.center.y = rect.y[valid.labels],
rectangle.width = unit.text.width * range.x,
rectangle.height = unit.text.height * range.y,
data.x = c(data.x[valid.data.points], added.x),
data.y = c(data.y[valid.data.points], added.y)
);
valid.labels[valid.labels] <- !(apply(in.rectangle, 1, any));
}
middle.x <- mean(data.x);
middle.y <- mean(data.y);
if (any(valid.labels) || !guess.skip.labels[i]) {
if (!any(valid.labels) && !guess.skip.labels[i]) {
valid.labels <- rep(TRUE, 360);
}
# COMMENT lapply instead of this stuff?
longest.arcs <- 0;
current.arcs <- 0;
indexes <- vector();
if (!all(valid.labels)) {
valid.labels.true.pos <- which(valid.labels);
if (tail(valid.labels.true.pos, n = 1) == length(valid.labels)) {
tail.arc <- vector();
last <- length(valid.labels) + 1;
index <- 0;
for (j in length(valid.labels.true.pos):1) {
if (last == valid.labels.true.pos[j] + 1) {
tail.arc <- c(tail.arc, index);
index <- index - 1;
last <- valid.labels.true.pos[j];
}
else {
break;
}
}
valid.labels.true.pos <- c(
rev(tail.arc),
valid.labels.true.pos[1:(length(valid.labels.true.pos) - length(tail.arc))]
);
}
arcs <- 0;
prev <- valid.labels.true.pos[1] - 1;
index <- 1;
arc.index <- vector();
for (j in 1:length(valid.labels.true.pos)) {
if (valid.labels.true.pos[j] == prev + 1) {
arcs[index] <- arcs[index] + 1;
if (j == length(valid.labels.true.pos)) {
arc.index <- c(arc.index, valid.labels.true.pos[j - arcs[index] / 2]);
}
}
else {
arc.index <- c(arc.index, valid.labels.true.pos[j - arcs[index] / 2]);
arcs <- c(arcs, 1);
index <- index + 1;
}
prev <- valid.labels.true.pos[j];
}
longest.arc <- max(arcs);
selected.arcs <- arc.index[arcs == longest.arc];
if (sum(selected.arcs) > 1) {
distance <- sqrt( (rect.x[selected.arcs] - middle.x) ^ 2 + (rect.y[selected.arcs] - middle.y) ^ 2);
selected.arcs <- selected.arcs[order(distance, decreasing = TRUE)][1];
}
### SELECT THE POINTS TO LABEL #########################################
final.x[i] <- rect.x[selected.arcs];
final.y[i] <- rect.y[selected.arcs];
added.x <- c(added.x, final.x[i]);
added.y <- c(added.y, final.y[i]);
}
else {
### any all ... confusing
if (!any(valid.labels)) {
final.x[i] <- NA;
final.y[i] <- NA;
}
else {
distance <- sqrt( (rect.x - middle.x) ^ 2 + (rect.y - middle.y) ^ 2);
selected.arcs <- order(distance, decreasing = TRUE)[1];
final.x[i] <- rect.x[selected.arcs];
final.y[i] <- rect.y[selected.arcs];
added.x <- c(added.x, final.x[i]);
added.y <- c(added.y, final.y[i]);
}
}
}
}
}
}
}
# create a scatterplot and save it as a trellis object
trellis.object <- lattice::xyplot(
formula,
data,
panel = function(
x,
y,
y.error.up.local = y.error.up,
y.error.down.local = y.error.down,
groups.local = groups.new,
subscripts,
type.local = type,
abline.local = abline,
...
) {
# add background rectangle if requested
if (add.rectangle) {
panel.rect(
xleft = rectangle.info$xleft,
ybottom = rectangle.info$ybottom,
xright = rectangle.info$xright,
ytop = rectangle.info$ytop,
col = col.rectangle,
alpha = alpha.rectangle,
border = NA
);
}
if (lollipop.plot) {
# min and max values for lollipop plot
max.x <- if (is.null(xlimits)) {max(x) + (max(x) - min(x)) * 0.07} else { xlimits[2] };
min.x <- if (is.null(xlimits)) {min(x) - (max(x) - min(x)) * 0.07} else { xlimits[1] };
max.y <- if (is.null(ylimits)) {max(y) + (max(y) - min(y)) * 0.07} else { ylimits[2] };
min.y <- if (is.null(ylimits)) {min(y) - (max(y) - min(y)) * 0.07} else { ylimits[1] };
bar.y.top <- if (is.null(lollipop.bar.y)) {min.y + (max.y - min.y) * 0.06 } else { lollipop.bar.y + (max.y - min.y) * 0.06 };
bar.y.bottom <- if (is.null(lollipop.bar.y)) {min.y + (max.y - min.y) * 0.01 } else { lollipop.bar.y + (max.y - min.y) * 0.01 };
region.y.top <- if (is.null(lollipop.bar.y)) {min.y + (max.y - min.y) * 0.065 } else { lollipop.bar.y + (max.y - min.y) * 0.065 };
region.y.bottom <- if (is.null(lollipop.bar.y)) {min.y + (max.y - min.y) * 0.005 } else { lollipop.bar.y + (max.y - min.y) * 0.005 };
bar.x.left <- min.x + (max.x - min.x) * 0.01;
bar.x.right <- min.x + (max.x - min.x) * 0.99;
for (i in c(1:length(x))) {
panel.xyplot(
x = c(x[i], x[i]),
y = c(bar.y.top, y[i]),
type = 'l',
col.line = 'black',
lwd = 1.5
);
}
panel.rect(
xleft = bar.x.left,
ybottom = bar.y.bottom,
xright = bar.x.right,
ytop = bar.y.top,
col = lollipop.bar.color,
alpha = 1,
border = NA
);
if (length(regions.start) > 0 && length(regions.stop) > 0) {
panel.rect(
xleft = regions.start,
ybottom = region.y.bottom,
xright = regions.stop,
ytop = region.y.top,
col = regions.color,
alpha = regions.alpha,
border = NA
);
panel.text(
x = (regions.start + regions.stop) / 2,
y = (bar.y.top + bar.y.bottom) / 2,
labels = regions.labels,
col = 'black',
cex = regions.cex,
fontface = 'bold'
);
}
}
# if requested, add x=0, y=0 lines
if (add.axes) {
panel.abline(
h = 0,
v = 0,
col.line = 'black',
lty = axes.lty,
lwd = 1.5
);
}
# if requested, add y=x line
if (add.xyline) {
panel.abline(
a = 0,
b = 1,
lwd = xyline.lwd,
lty = xyline.lty,
col = xyline.col
);
}
# if requested, add curve segments
if (add.curves) {
if (length(curves.exprs) > 1) {
if (1 == length(curves.from)) { curves.from <- rep(curves.from, length(curves.exprs)); }
if (1 == length(curves.to)) { curves.to <- rep(curves.to, length(curves.exprs)); }
if (1 == length(curves.col)) { curves.col <- rep(curves.col, length(curves.exprs)); }
if (1 == length(curves.lwd)) { curves.lwd <- rep(curves.lwd, length(curves.exprs)); }
if (1 == length(curves.lty)) { curves.lty <- rep(curves.lty, length(curves.exprs)); }
}
for (i in 1:length(curves.exprs)) {
with(
data = new.env(),
expr = panel.curve(
expr = curves.exprs[[i]](x),
from = curves.from[i],
to = curves.to[i],
col = curves.col[i],
lwd = curves.lwd[i],
lty = curves.lty[i]
)
);
}
}
# if grid-lines are requested, over-ride default behaviour
if ('g' %in% type || add.grid == TRUE) {
# create the grid-lines
panel.abline(
v = BoutrosLab.plotting.general::generate.at.final(
at.input = xgrid.at,
limits = xlimits,
data.vector = data$x
),
h = BoutrosLab.plotting.general::generate.at.final(
at.input = ygrid.at,
limits = ylimits,
data.vector = data$y
),
col = if (!is.null(grid.colour)) { grid.colour; } else { trellis.par.get('reference.line')$col }
);
}
# create the main plot
panel.xyplot(
x,
y,
groups = groups.local,
subscripts = subscripts,
type = setdiff(type.local, 'g'),
alpha = alpha,
horizontal = horizontal,
...
);
# if requested, add y-axis (i.e. vertical) error bars
if (!is.null(y.error.up.local)) {
panel.arrows(
x, y + y.error.up.local[subscripts], x, y - y.error.down.local[subscripts],
groups = groups.local,
length = error.bar.length,
angle = error.whisker.angle,
ends = 'both',
col = y.error.bar.col,
lwd = error.bar.lwd
);
}
# if requested, add x-axis (i.e. horizontal) error bars
if (!is.null(x.error.right)) {
panel.arrows(
x + x.error.right[subscripts], y, x - x.error.left[subscripts], y,
groups = groups.local,
length = error.bar.length,
angle = error.whisker.angle,
ends = 'both',
col = x.error.bar.col,
lwd = error.bar.lwd
);
}
# if requested, add user-defined horizontal line
if (!is.null(abline.h)) {
panel.abline(
h = abline.h,
lty = abline.lty,
lwd = abline.lwd,
col = abline.col
);
}
# if requested, add user-defined vertical line
if (!is.null(abline.v)) {
panel.abline(
v = abline.v,
lty = abline.lty,
lwd = abline.lwd,
col = abline.col
);
}
# if requested, add additional lines
if (add.line.segments) {
for (i in 1:length(line.start)) {
with(
data = new.env(),
expr = panel.segments(
x, line.start[[i]][subscripts], x, line.end[[i]][subscripts],
col = line.col[[i]],
lwd = line.lwd[[i]],
lineend = 1
)
);
}
}
# if requested, add additional points
if (add.points) {
panel.points(
x = points.x,
y = points.y,
pch = points.pch,
col = mapply(
function(pch, spot.colours, spot.border) {
if (pch %in% 0:20) { return(spot.colours); } else if (pch %in% 21:25) { return(spot.border); }
},
points.pch,
spot.colours = points.col,
spot.border = points.col.border
),
fill = mapply(
function(pch, spot.colours) {
if (pch %in% 0:20) { NA; } else if (pch %in% 21:25) { return(spot.colours); }
},
points.pch,
spot.colours = points.col
),
cex = points.cex
);
}
# if requested, add point labels
if (any(!text.guess.labels) && add.text) {
panel.text(
x = text.info$x,
y = text.info$y,
labels = text.info$labels,
col = text.info$col,
cex = text.info$cex,
fontface = text.info$fontface
);
}
if (any(text.guess.labels) && add.text && safe.to.guess) {
panel.text(
x = final.x,
y = final.y,
labels = guess.labels,
col = guess.col,
cex = guess.cex,
fontface = guess.fontface
);
}
},
type = type,
cex = cex,
pch = pch,
col = mapply(
function(point.pch, point.colours, point.border) {
if (point.pch %in% 0:20) { return(point.colours); } else
if (point.pch %in% 21:25) { return(point.border); } else
if (! point.pch %in% 0:25) { return(point.colours); }
},
point.pch = pch,
point.colours = col,
point.border = col.border
),
fill = mapply(
function(point.pch, point.colours) {
if (point.pch %in% 0:20) { NA; } else
if (point.pch %in% 21:25) { return(point.colours); } else
if (! point.pch %in% 0:25) { return(point.colours); }
},
point.pch = pch,
point.colours = col
),
lwd = lwd,
lty = lty,
main = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = main,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
cex = main.cex,
just = main.just,
x = main.x,
y = main.y
)
),
xlab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.label,
cex = xlab.cex,
col = xlab.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' }
)
),
xlab.top = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.top.label,
cex = xlab.top.cex,
col = xlab.top.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
just = xlab.top.just,
x = xlab.top.x,
y = xlab.top.y
)
),
ylab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = ylab.label,
cex = ylab.cex,
col = ylab.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' }
)
),
scales = list(
x = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
cex = xaxis.cex,
rot = xaxis.rot,
limits = xlimits,
fontface = if ('Nature' == style) { 'plain' } else { xaxis.fontface },
col = xaxis.col,
at = xat,
labels = xaxis.lab,
log = xaxis.log,
relation = x.relation,
alternating = FALSE,
tck = xaxis.tck
)
),
y = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
cex = yaxis.cex,
rot = yaxis.rot,
limits = ylimits,
fontface = if ('Nature' == style) { 'plain' } else { yaxis.fontface },
col = yaxis.col,
at = yat,
labels = yaxis.lab,
log = yaxis.log,
relation = y.relation,
alternating = FALSE,
tck = yaxis.tck
)
)
),
between = list(
x = x.spacing,
y = y.spacing
),
layout = layout,
as.table = as.table,
par.settings = list(
axis.line = list(
lwd = axes.lwd,
col = if ('Nature' == style) { 'transparent' } else { 'black' }
),
layout.heights = list(
top.padding = top.padding,
main = if (is.null(main)) { 0.3 } else { 1 },
main.key.padding = 0.1,
key.top = key.top,
key.axis.padding = 0.1,
axis.top = 1,
axis.bottom = 1,
axis.xlab.padding = 1,
xlab = 1,
xlab.key.padding = 0.5,
key.bottom = 0.1,
key.sub.padding = 0.1,
sub = 0.1,
bottom.padding = bottom.padding
),
layout.widths = list(
left.padding = left.padding,
key.left = key.left.padding,
key.ylab.padding = 0.5,
ylab = 1,
ylab.axis.padding = ylab.axis.padding,
axis.left = 1,
axis.panel = 0.3,
strip.left = 0.3,
panel = 1,
between = 1,
axis.right = 1,
axis.key.padding = axis.key.padding,
key.right = 1,
right.padding = right.padding
),
strip.background = list(
col = strip.col
)
),
par.strip.text = list(
cex = strip.cex,
fontface = strip.fontface
),
key = key,
legend = legend
);
if (inside.legend.auto) {
extra.parameters <- list('data' = data, 'formula' = formula, 'ylimits' = trellis.object$y.limits,
'xlimits' = trellis.object$x.limits);
coords <- c();
coords <- .inside.auto.legend('create.scatterplot', filename, trellis.object, height, width, extra.parameters);
trellis.object$legend$inside$x <- coords[1];
trellis.object$legend$inside$y <- coords[2];
}
# If Nature style requested, change figure accordingly
if ('Nature' == style) {
# Re-add bottom and left axes
trellis.object$axis <- function(side, line.col = 'black', ...) {
# Only draw axes on the left and bottom
if (side %in% c('bottom', 'left')) {
axis.default(side = side, line.col = 'black', ...);
lims <- current.panel.limits();
panel.abline(h = lims$ylim[1], v = lims$xlim[1]);
}
}
# Ensure sufficient resolution for graphs
if (resolution < 1200) {
resolution <- 1200;
warning('Setting resolution to 1200 dpi.');
}
# Other required changes which are not accomplished here
warning('Nature also requires italicized single-letter variables and en-dashes
for ranges and negatives. See example in documentation for how to do this.');
warning('Avoid red-green colour schemes, create TIFF files, do not outline the figure or legend.');
}
# Otherwise use the BL style if requested
else if ('BoutrosLab' == style) {
# Nothing happens
}
# if neither of the above is requested, give a warning
else {
warning("The style parameter only accepts 'Nature' or 'BoutrosLab'.");
}
# output the object
return(
BoutrosLab.plotting.general::write.plot(
trellis.object = trellis.object,
filename = filename,
height = height,
width = width,
size.units = size.units,
resolution = resolution,
enable.warnings = enable.warnings,
description = description
)
);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/create.scatterplot.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO CREATE SEGPLOTS ###################################################################
create.segplot <- function(
formula, data, filename = NULL, main = NULL, main.just = 'center', main.x = 0.5, main.y = 0.5, main.cex = 3,
xlab.label = tail(sub('~', '', formula[-2]), 1), ylab.label = tail(sub('~', '', formula[-3]), 1),
xlab.cex = 2, ylab.cex = 2, xlab.col = 'black', ylab.col = 'black', xlab.top.label = NULL, xlab.top.cex = 2,
xlab.top.col = 'black', xlab.top.just = 'center', xlab.top.x = 0.5, xlab.top.y = 0, xaxis.lab = TRUE,
yaxis.lab = TRUE, xaxis.cex = 1.5, yaxis.cex = 1.5, xaxis.col = 'black', yaxis.col = 'black',
xaxis.fontface = 'bold', yaxis.fontface = 'bold', xaxis.rot = 0, yaxis.rot = 0, xaxis.tck = 1,
yaxis.tck = 1, xlimits = NULL, ylimits = NULL, xat = TRUE, yat = TRUE, abline.h = NULL, abline.v = NULL,
abline.lty = 1, abline.lwd = 1, abline.col = 'black', segments.col = 'black', segments.lwd = 1,
layout = NULL, as.table = FALSE, x.spacing = 0, y.spacing = 0, x.relation = 'same', y.relation = 'same',
top.padding = 0.5, bottom.padding = 2, right.padding = 1, left.padding = 2, ylab.axis.padding = 0,
level = NULL, col.regions = NULL, centers = NULL, plot.horizontal = TRUE, draw.bands = FALSE, pch = 16,
symbol.col = 'black', symbol.cex = 1, add.rectangle = FALSE, xleft.rectangle = NULL, ybottom.rectangle = NULL,
xright.rectangle = NULL, ytop.rectangle = NULL, col.rectangle = 'transparent', alpha.rectangle = 1,
axes.lwd = 1, key = NULL, legend = NULL, height = 6, width = 6, size.units = 'in', resolution = 1600,
enable.warnings = FALSE, description = 'Created with BoutrosLab.plotting.general',
style = 'BoutrosLab', preload.default = 'custom', use.legacy.settings = FALSE, inside.legend.auto = FALSE,
disable.factor.sorting = FALSE
) {
### needed to copy in case using variable to define rectangles dimensions
rectangle.info <- list(
xright = xright.rectangle,
xleft = xleft.rectangle,
ytop = ytop.rectangle,
ybottom = ybottom.rectangle
);
# add preloaded defaults
if (preload.default == 'paper') {
}
else if (preload.default == 'web') {
}
# add some error checking
if (!plot.horizontal) {
warning('Be aware that vertical segplots can not be used as the first plot in a multiplot. Consider using create.scatterplot instead.');
}
# Now make the actual plot object
trellis.object <- lattice::levelplot(
x = formula,
data,
prepanel = prepanel.segplot,
panel = function( abline.local = abline, ...) {
# add rectangle if requested
if (add.rectangle) {
panel.rect(
xleft = rectangle.info$xleft,
ybottom = rectangle.info$ybottom,
xright = rectangle.info$xright,
ytop = rectangle.info$ytop,
col = col.rectangle,
alpha = alpha.rectangle,
border = NA
);
}
# add bands if requested
if (!is.logical(draw.bands)) {
panel.rect(
xleft = data$min[draw.bands],
ybottom = draw.bands - 0.25,
xright = data$max[draw.bands],
ytop = draw.bands + 0.25,
col = segments.col,
alpha = 1,
border = NA
);
}
else if (draw.bands == TRUE) {
panel.rect(
xleft = data$min,
ybottom = seq(0.75, 10, 1),
xright = data$max,
ytop = seq(1.25, 11, 1),
col = segments.col,
alpha = 1,
border = NA
);
}
# if requested, add user-defined vertical line
if (!is.null(abline.v)) {
panel.abline(
v = abline.v,
lty = abline.lty,
lwd = abline.lwd,
col = abline.col
);
}
# if requested, add user-defined horizontal line
if (!is.null(abline.h)) {
panel.abline(
h = abline.h,
lty = abline.lty,
lwd = abline.lwd,
col = abline.col
);
}
panel.segplot(
col = segments.col,
fill = segments.col,
lwd = segments.lwd,
pch = pch,
col.regions = col.regions,
level = level,
centers = centers,
horizontal = plot.horizontal,
draw.bands = FALSE,
...,
)
},
main = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = main,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
cex = main.cex,
just = main.just,
x = main.x,
y = main.y
)
),
xlab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.label,
cex = xlab.cex,
col = xlab.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' }
)
),
xlab.top = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.top.label,
cex = xlab.top.cex,
col = xlab.top.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
just = xlab.top.just,
x = xlab.top.x,
y = xlab.top.y
)
),
ylab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = ylab.label,
cex = ylab.cex,
col = ylab.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' }
)
),
between = list(
x = x.spacing,
y = y.spacing
),
scales = list(
x = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
labels = xaxis.lab,
rot = xaxis.rot,
limits = xlimits,
cex = xaxis.cex,
col = xaxis.col,
fontface = if ('Nature' == style) { 'plain' } else { xaxis.fontface },
at = xat,
relation = x.relation,
tck = xaxis.tck
)
),
y = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
labels = yaxis.lab,
cex = yaxis.cex,
col = yaxis.col,
fontface = if ('Nature' == style) { 'plain' } else { yaxis.fontface },
rot = yaxis.rot,
tck = yaxis.tck,
limits = ylimits,
at = yat,
relation = y.relation,
alternating = FALSE
)
),
alternating = 1
),
par.settings = list(
axis.line = list(
lwd = axes.lwd,
col = if ('Nature' == style) { 'transparent' } else { 'black' }
),
layout.heights = list(
top.padding = top.padding,
main = if (is.null(main)) { 0.3 } else { 1 },
main.key.padding = 0.1,
key.top = 0.1,
key.axis.padding = 0.1,
axis.top = 0.7,
axis.bottom = 1.0,
axis.xlab.padding = 0.1,
xlab = 1,
xlab.key.padding = 0.5,
key.bottom = 0.1,
key.sub.padding = 0.1,
sub = 0.1,
bottom.padding = bottom.padding
),
layout.widths = list(
left.padding = left.padding,
key.left = 0,
key.ylab.padding = 0.3,
ylab = 1,
ylab.axis.padding = ylab.axis.padding,
axis.left = 1,
axis.panel = 0.3,
strip.left = 0.3,
panel = 1,
between = 1,
axis.right = 1,
axis.key.padding = 1,
key.right = 1,
right.padding = right.padding
),
plot.symbol = list(
col = symbol.col,
cex = symbol.cex
)
),
colorkey = FALSE,
layout = layout,
as.table = as.table,
pretty = TRUE,
key = key,
legend = legend
);
if (disable.factor.sorting == TRUE) {
sorting.param <- 'z';
if (plot.horizontal) {
if (is.null(trellis.object$y.scales$labels) || (is.logical(trellis.object$y.scales$labels[1]) && trellis.object$y.scales$labels[1] == TRUE)) {
default.labels <- unique(as.character(trellis.object$panel.args.common[[sorting.param]]));
trellis.object$y.scales$labels <- default.labels;
}
}
else {
if (is.null(trellis.object$x.scales$labels) || (is.logical(trellis.object$x.scales$labels[1]) && trellis.object$x.scales$labels[1] == TRUE)) {
default.labels <- unique(as.character(trellis.object$panel.args.common[[sorting.param]]));
trellis.object$x.scales$labels <- default.labels;
trellis.object$x.scales$at <- seq(1, length(default.labels), 1);
trellis.object$x.limits <- c(0, length(default.labels) + 1);
}
}
unique.mapping <- list();
count <- 1;
for (x in trellis.object$panel.args.common[[sorting.param]]) {
if (is.null(unique.mapping[[as.character(x)]])) {
unique.mapping[as.character(x)] <- count;
count <- count + 1;
}
}
temp.data <- as.character(trellis.object$panel.args.common[[sorting.param]]);
for (x in 1:length(temp.data)) {
temp.data[x] <- as.character(unique.mapping[as.character(trellis.object$panel.args.common[[sorting.param]][[x]])][[1]]);
}
trellis.object$panel.args.common[[sorting.param]] <- as.numeric(temp.data);
}
if (inside.legend.auto) {
extra.parameters <- list('x' = trellis.object$panel.args.common$x, 'y' = trellis.object$panel.args.common$y,
'ylimits' = trellis.object$y.limits, 'xlimits' = trellis.object$x.limits);
coords <- c();
coords <- .inside.auto.legend('create.segplot', filename, trellis.object, height, width, extra.parameters);
trellis.object$legend$inside$x <- coords[1];
trellis.object$legend$inside$y <- coords[2];
}
# If Nature style requested, change figure accordingly
if ('Nature' == style) {
# Re-add bottom and left axes
trellis.object$axis <- function(side, line.col = 'black', ...) {
# Only draw axes on the left and bottom
if (side %in% c('bottom', 'left')) {
axis.default(side = side, line.col = 'black', ...);
lims <- current.panel.limits();
panel.abline(h = lims$ylim[1], v = lims$xlim[1]);
}
}
# Ensure sufficient resolution for graphs
if (resolution < 1200) {
resolution <- 1200;
warning('Setting resolution to 1200 dpi.');
}
# Other required changes which are not accomplished here
warning('Nature also requires italicized single-letter variables and en-dashes
for ranges and negatives. See example in documentation for how to do this.');
warning('Avoid red-green colour schemes, create TIFF files, do not outline the figure or legend.');
}
# Otherwise use the BL style if requested
else if ('BoutrosLab' == style) {
# Nothing happens
}
# if neither of the above is requested, give a warning
else {
warning("The style parameter only accepts 'Nature' or 'BoutrosLab'.");
}
# output the object
return(
BoutrosLab.plotting.general::write.plot(
trellis.object = trellis.object,
filename = filename,
height = height,
width = width,
size.units = size.units,
resolution = resolution,
enable.warnings = enable.warnings,
description = description
)
);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/create.segplot.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2013 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO CREATE STRIPPLOTS #################################################################
create.stripplot <- function(
formula, data, filename = NULL, groups = NULL, jitter.data = FALSE, jitter.factor = 1, jitter.amount = NULL,
main = NULL, main.just = 'center', main.x = 0.5, main.y = 0.5, main.cex = 3,
xlab.label = tail(sub('~', '', formula[-2]), 1), ylab.label = tail(sub('~', '', formula[-3]), 1),
xlab.cex = 2, ylab.cex = 2, xlab.col = 'black', ylab.col = 'black', xlab.top.label = NULL,
xlab.top.cex = 2, xlab.top.col = 'black', xlab.top.just = 'center', xlab.top.x = 0.5, xlab.top.y = 0,
xaxis.lab = TRUE, yaxis.lab = TRUE, xaxis.cex = 1.5, yaxis.cex = 1.5, xaxis.col = 'black',
yaxis.col = 'black', xaxis.fontface = 'bold', yaxis.fontface = 'bold', xaxis.rot = 0, yaxis.rot = 0,
xaxis.tck = 0, yaxis.tck = 1, xlimits = NULL, ylimits = NULL, xat = TRUE, yat = TRUE, lwd = 1,
pch = 19, col = 'black', col.border = 'black', fill = 'transparent', colour.alpha = 1, cex = 0.75,
top.padding = 0.1, bottom.padding = 0.7, right.padding = 0.3, left.padding = 0.5, ylab.axis.padding = 1,
layout = NULL, as.table = TRUE, x.spacing = 0, y.spacing = 0, add.median = FALSE, median.values = NULL,
add.rectangle = FALSE, xleft.rectangle = NULL, ybottom.rectangle = NULL, xright.rectangle = NULL,
ytop.rectangle = NULL, col.rectangle = 'transparent', alpha.rectangle = 1, strip.col = 'white', strip.cex = 1,
strip.fontface = 'bold', key = NULL, legend = NULL, height = 6, width = 6, size.units = 'in',
resolution = 1600, enable.warnings = FALSE, description = 'Created with BoutrosLab.plotting.general',
style = 'BoutrosLab', preload.default = 'custom', use.legacy.settings = FALSE, inside.legend.auto = FALSE,
disable.factor.sorting = FALSE
) {
### needed to copy in case using variable to define rectangles dimensions
rectangle.info <- list(
xright = xright.rectangle,
xleft = xleft.rectangle,
ytop = ytop.rectangle,
ybottom = ybottom.rectangle
);
if (!is.null(yat) && length(yat) == 1) {
if (yat == 'auto') {
out <- auto.axis(unlist(data[toString(formula[[2]])]));
data[toString(formula[[2]])] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
else if (yat == 'auto.linear') {
out <- auto.axis(unlist(data[toString(formula[[2]])]), log.scaled = FALSE);
data[toString(formula[[2]])] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
else if (yat == 'auto.log') {
out <- auto.axis(unlist(data[toString(formula[[2]])]), log.scaled = TRUE);
data[toString(formula[[2]])] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
}
if (!is.null(xat) && length(xat) == 1) {
if (xat == 'auto') {
out <- auto.axis(unlist(data[toString(formula[[3]])]));
data[toString(formula[[3]])] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
else if (xat == 'auto.linear') {
out <- auto.axis(unlist(data[toString(formula[[3]])]), log.scaled = FALSE);
data[toString(formula[[3]])] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
else if (xat == 'auto.log') {
out <- auto.axis(unlist(data[toString(formula[[3]])]), log.scaled = TRUE);
data[toString(formula[[3]])] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
}
# add preloaded defaults
if (preload.default == 'paper') {
}
else if (preload.default == 'web') {
}
# update groups function
groups.new <- eval(substitute(groups), data, parent.frame());
# Now make the actual plot object
trellis.object <- lattice::stripplot(
formula,
data,
panel = function(groups.local = groups.new, subscripts, ...) {
# add rectangle if requested
if (add.rectangle) {
panel.rect(
xleft = rectangle.info$xleft,
ybottom = rectangle.info$ybottom,
xright = rectangle.info$xright,
ytop = rectangle.info$ytop,
col = col.rectangle,
alpha = alpha.rectangle,
border = NA
);
}
# make the stripplot
panel.stripplot(
jitter.data = jitter.data,
factor = jitter.factor,
amount = jitter.amount,
groups = groups.new,
subscripts = subscripts,
...
);
# if requested, add lines indicating the group median
if (add.median && is.null(median.values)) {
warning('median.values must be specified to median to be added.');
}
else if (add.median && !is.null(median.values)) {
meds <- median.values;
xlocs <- seq_along(meds);
panel.segments(
xlocs - 1 / 4, meds, xlocs + 1 / 4, meds,
lwd = 2,
col = 'red'
);
}
},
type = 'p',
cex = cex,
pch = pch,
col = mapply(
function(pch, spot.colours, spot.border) {
if (pch %in% 0:20) { return(spot.colours); } else if (pch %in% 21:25) { return(spot.border); }
},
pch,
spot.colours = col,
spot.border = col.border
),
fill = mapply(
function(pch, spot.colours) {
if (pch %in% 0:20) { NA; } else if (pch %in% 21:25) { return(spot.colours); }
},
pch,
spot.colours = col
),
alpha = colour.alpha,
main = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = main,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
cex = main.cex,
just = main.just,
x = main.x,
y = main.y
)
),
xlab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.label,
cex = xlab.cex,
col = xlab.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' }
)
),
xlab.top = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.top.label,
cex = xlab.top.cex,
col = xlab.top.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
just = xlab.top.just,
x = xlab.top.x,
y = xlab.top.y
)
),
ylab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = ylab.label,
cex = ylab.cex,
col = ylab.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' }
)
),
scales = list(
x = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
labels = xaxis.lab,
cex = xaxis.cex,
rot = xaxis.rot,
col = xaxis.col,
limits = xlimits,
at = xat,
fontface = if ('Nature' == style) { 'plain' } else { xaxis.fontface },
alternating = FALSE,
tck = xaxis.tck
)
),
y = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
labels = yaxis.lab,
cex = yaxis.cex,
col = yaxis.col,
limits = ylimits,
at = yat,
tck = yaxis.tck,
fontface = if ('Nature' == style) { 'plain' } else { yaxis.fontface },
alternating = FALSE,
rot = yaxis.rot
)
)
),
between = list(
x = x.spacing,
y = y.spacing
),
par.settings = list(
axis.line = list(
lwd = lwd,
col = if ('Nature' == style) { 'transparent' } else { 'black' }
),
layout.heights = list(
top.padding = top.padding,
main = if (is.null(main)) { 0.3 } else { 1 },
main.key.padding = 0.1,
key.top = 0.1,
key.axis.padding = 0.1,
axis.top = 1,
axis.bottom = 1,
axis.xlab.padding = 1,
xlab = 1,
xlab.key.padding = 0.5,
key.bottom = 0.1,
key.sub.padding = 0.1,
sub = 0.1,
bottom.padding = bottom.padding
),
layout.widths = list(
left.padding = left.padding,
key.left = 0.1,
key.ylab.padding = 0.1,
ylab = 1,
ylab.axis.padding = ylab.axis.padding,
axis.left = 1,
axis.right = 1,
axis.key.padding = 0.1,
key.right = 1,
right.padding = right.padding
),
strip.background = list(
col = strip.col
)
),
par.strip.text = list(
cex = strip.cex,
fontface = strip.fontface
),
layout = layout,
as.table = as.table,
key = key,
legend = legend
);
if (disable.factor.sorting == TRUE) {
sorting.param <- '';
if (is.factor(trellis.object$panel.args[[1]][['y']])) {
sorting.param <- 'y';
if (is.null(trellis.object$y.scales$labels) || (is.logical(trellis.object$y.scales$labels[1]) &&
trellis.object$y.scales$labels[1] == TRUE)) {
default.labels <- unique(as.character(trellis.object$panel.args[[1]][[sorting.param]]));
trellis.object$y.scales$labels <- default.labels;
}
}
else {
sorting.param <- 'x';
if (is.null(trellis.object$x.scales$labels) || (is.logical(trellis.object$x.scales$labels[1]) &&
trellis.object$x.scales$labels[1] == TRUE)) {
default.labels <- unique(as.character(trellis.object$panel.args[[1]][[sorting.param]]));
trellis.object$x.scales$labels <- default.labels;
}
}
unique.mapping <- list();
count <- 1;
for (x in trellis.object$panel.args[[1]][[sorting.param]]) {
if (is.null(unique.mapping[[as.character(x)]])) {
unique.mapping[as.character(x)] <- count;
count <- count + 1;
}
}
temp.data <- as.character(trellis.object$panel.args[[1]][[sorting.param]]);
for (x in 1:length(temp.data)) {
temp.data[x] <- as.character(unique.mapping[as.character(trellis.object$panel.args[[1]][[sorting.param]][[x]])][[1]]);
}
trellis.object$panel.args[[1]][[sorting.param]] <- as.numeric(temp.data);
}
if (inside.legend.auto) {
extra.parameters <- list('x' = trellis.object$panel.args[[1]]$x, 'y' = trellis.object$panel.args[[1]]$y, 'ylimits' = trellis.object$y.limits,
'xlimits' = trellis.object$x.limits, 'horizontal' = trellis.object$panel.args.common$horizontal);
coords <- c();
coords <- .inside.auto.legend('create.stripplot', filename, trellis.object, height, width, extra.parameters);
trellis.object$legend$inside$x <- coords[1];
trellis.object$legend$inside$y <- coords[2];
}
# If Nature style requested, change figure accordingly
if ('Nature' == style) {
# Re-add bottom and left axes
trellis.object$axis <- function(side, line.col = 'black', ...) {
# Only draw axes on the left and bottom
if (side %in% c('bottom', 'left')) {
axis.default(side = side, line.col = 'black', ...);
lims <- current.panel.limits();
panel.abline(h = lims$ylim[1], v = lims$xlim[1]);
}
}
# Ensure sufficient resolution for graphs
if (resolution < 1200) {
resolution <- 1200;
warning('Setting resolution to 1200 dpi.');
}
# Other required changes which are not accomplished here
warning('Nature also requires italicized single-letter variables and en-dashes
for ranges and negatives. See example in documentation for how to do this.');
warning('Avoid red-green colour schemes, create TIFF files, do not outline the figure or legend');
}
# Otherwise use the BL style if requested
else if ('BoutrosLab' == style) {
# Nothing happens
}
# if neither of the above is requested, give a warning
else {
warning("The style parameter only accepts 'Nature' or 'BoutrosLab'.");
}
# output the object
return(
BoutrosLab.plotting.general::write.plot(
trellis.object = trellis.object,
filename = filename,
height = height,
width = width,
size.units = size.units,
resolution = resolution,
enable.warnings = enable.warnings,
description = description
)
);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/create.stripplot.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO CREATE VIOLIN PLOTS ###############################################################
create.violinplot <- function(
formula, data, filename = NULL, main = NULL, main.just = 'center', main.x = 0.5, main.y = 0.5,
main.cex = 3, xlab.label = tail(sub('~', '', formula[-2]), 1), ylab.label = tail(sub('~', '', formula[-3]), 1),
xlab.cex = 2, ylab.cex = 2, xlab.col = 'black', ylab.col = 'black', xlab.top.label = NULL,
xlab.top.cex = 2, xlab.top.col = 'black', xlab.top.just = 'center', xlab.top.x = 0.5, xlab.top.y = 0,
xaxis.lab = TRUE, yaxis.lab = TRUE, xaxis.cex = 1.5, yaxis.cex = 1.5, xaxis.col = 'black',
yaxis.col = 'black', xaxis.fontface = 'bold', yaxis.fontface = 'bold', xaxis.rot = 0, yaxis.rot = 0,
xaxis.tck = c(1, 0), yaxis.tck = c(1, 1), ylimits = NULL, yat = TRUE, col = 'black', lwd = 1,
border.lwd = 1, bandwidth = 'nrd0', bandwidth.adjust = 1, extra.points = NULL, extra.points.pch = 21,
extra.points.col = 'white', extra.points.border = 'black', extra.points.cex = 1, start = NULL,
end = NULL, scale = FALSE, plot.horizontal = FALSE, top.padding = 0.1, bottom.padding = 0.7,
left.padding = 0.5, right.padding = 0.3, key = NULL, legend = NULL, add.rectangle = FALSE,
xleft.rectangle = NULL, ybottom.rectangle = NULL, xright.rectangle = NULL, ytop.rectangle = NULL,
col.rectangle = 'transparent', alpha.rectangle = 1, height = 6, width = 6, resolution = 1600,
size.units = 'in', enable.warnings = FALSE, description = 'Created with BoutrosLab.plotting.general',
style = 'BoutrosLab', preload.default = 'custom', use.legacy.settings = FALSE, disable.factor.sorting = FALSE
) {
### needed to copy in case using variable to define rectangles dimensions
rectangle.info <- list(
xright = xright.rectangle,
xleft = xleft.rectangle,
ytop = ytop.rectangle,
ybottom = ybottom.rectangle
);
# add preloaded defaults
if (preload.default == 'paper') {
}
else if (preload.default == 'web') {
}
# Temp function to allow differential violin colour filling
# panel.violin() author has been emailed about issue in the
# original function preventing differential colouring.
.panel.violin.mod <- function(x, y, box.ratio = 1, box.width = box.ratio / (1 + box.ratio),
horizontal = TRUE, alpha = plot.polygon$alpha, border = plot.polygon$border,
lty = plot.polygon$lty, lwd = plot.polygon$lwd, col = plot.polygon$col,
varwidth = FALSE, bw = bandwidth, adjust = bandwidth.adjust, kernel = NULL,
window = NULL, width = NULL, n = 50, from = NULL, to = NULL,
cut = NULL, na.rm = TRUE, ..., identifier = 'violin') {
if (all(is.na(x) | is.na(y))) { return(); }
x <- as.numeric(x);
y <- as.numeric(y);
plot.polygon <- trellis.par.get('plot.polygon');
darg <- list();
darg$bw <- bw;
darg$adjust <- adjust;
darg$kernel <- kernel;
darg$window <- window;
darg$width <- width;
darg$n <- n;
darg$from <- from;
darg$to <- to;
darg$cut <- cut;
darg$na.rm <- na.rm;
my.density <- function(x) {
ans <- try(
do.call('density', c(list(x = x), darg)),
silent = TRUE
);
if (inherits(ans, 'try-error')) {
list(x = rep(x[1], 3), y = c(0, 1, 0));
}
else { ans; }
}
numeric.list <- if (horizontal) { split(x, factor(y)); } else { split(y, factor(x)); }
levels.fos <- as.numeric(names(numeric.list));
# check colours are appropriate length
if (length(col) < length(levels.fos)) { col <- rep(col, length(levels.fos)); }
d.list <- lapply(numeric.list, my.density);
dx.list <- lapply(d.list, '[[', 'x');
dy.list <- lapply(d.list, '[[', 'y');
max.d <- sapply(dy.list, max);
if (varwidth) { max.d[] <- max(max.d); }
cur.limits <- current.panel.limits();
xscale <- cur.limits$xlim;
yscale <- cur.limits$ylim;
height <- box.width;
## Modified from methods::hasArg.
hasGroupNumber <- function() {
aname <- 'group.number';
fnames <- names(formals(sys.function(sys.parent())));
if (is.na(match(aname, fnames))) {
if (is.na(match('...', fnames))) { FALSE; }
else {
dots.call <- eval(quote(substitute(list(...))), sys.parent());
!is.na(match(aname, names(dots.call)));
}
}
else { FALSE; }
}
if (hasGroupNumber()) {
group <- list(...)$group.number;
}
else { group <- 0; }
if (horizontal) {
for (i in seq_along(levels.fos)) {
if (is.finite(max.d[i])) {
pushViewport(
viewport(
y = unit(levels.fos[i], 'native'),
height = unit(height, 'native'),
yscale = c(max.d[i] * c(-1, 1)),
xscale = xscale
)
);
grid.polygon(
x = c(dx.list[[i]], rev(dx.list[[i]])),
y = c(dy.list[[i]], -rev(dy.list[[i]])),
default.units = 'native',
name = trellis.grobname(
identifier,
type = 'panel',
group = group
),
gp = gpar(fill = col[i], col = border, lty = lty, lwd = lwd, alpha = alpha)
);
popViewport();
}
}
}
else {
for (i in seq_along(levels.fos)) {
if (is.finite(max.d[i])) {
pushViewport(
viewport(
x = unit(levels.fos[i], 'native'),
width = unit(height, 'native'),
xscale = c(max.d[i] * c(-1, 1)),
yscale = yscale
)
);
grid.polygon(
y = c(dx.list[[i]], rev(dx.list[[i]])),
x = c(dy.list[[i]], -rev(dy.list[[i]])),
default.units = 'native',
name = trellis.grobname(
identifier,
type = 'panel',
group = group
),
gp = gpar(fill = col[i], col = border, lty = lty, lwd = lwd, alpha = alpha)
);
popViewport();
}
}
}
invisible();
}
# Now make the actual plot object
trellis.object <- lattice::bwplot(
formula,
data,
panel = function(from = start, to = end, varwidth = scale, ...) {
# add rectangle if requested
if (add.rectangle) {
panel.rect(
xleft = rectangle.info$xleft,
ybottom = rectangle.info$ybottom,
xright = rectangle.info$xright,
ytop = rectangle.info$ytop,
col = col.rectangle,
alpha = alpha.rectangle,
border = NA
);
}
# update the plot parameters
if (is.null(from) || is.null(to)) {
.panel.violin.mod(varwidth = varwidth, ...);
}
else {
.panel.violin.mod(from = from, to = to, varwidth = varwidth, ...);
}
# add extra points if requested
if (!is.null(extra.points)) {
for (i in 1:length(extra.points)) {
if (is.na(extra.points.pch[i])) { extra.points.pch[i] <- extra.points.pch[1]; }
if (is.na(extra.points.col[i])) { extra.points.col[i] <- extra.points.col[1]; }
if (is.na(extra.points.cex[i])) { extra.points.cex[i] <- extra.points.cex[1]; }
if (is.na(extra.points.border[i])) { extra.points.border[i] <- extra.points.border[1]; }
for (j in 1:length(extra.points[[i]])) {
if (!is.na(extra.points[[i]][j])) {
panel.xyplot(
x = j,
y = extra.points[[i]][j],
pch = extra.points.pch[i],
col = if (extra.points.pch[i] %in% 0:20) { extra.points.col[i]; } else if
(extra.points.pch[i] %in% 21:25) { extra.points.border[i]; },
fill = if (extra.points.pch[i] %in% 0:20) { NA; } else if
(extra.points.pch[i] %in% 21:25) { extra.points.col[i]; },
cex = extra.points.cex[i]
);
}
}
}
}
},
main = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = main,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
cex = main.cex,
just = main.just,
x = main.x,
y = main.y
)
),
xlab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.label,
cex = xlab.cex,
col = xlab.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' }
)
),
xlab.top = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.top.label,
cex = xlab.top.cex,
col = xlab.top.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
just = xlab.top.just,
x = xlab.top.x,
y = xlab.top.y
)
),
ylab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = ylab.label,
cex = ylab.cex,
col = ylab.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' }
)
),
scales = list(
lwd = 1,
x = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
labels = xaxis.lab,
cex = xaxis.cex,
rot = xaxis.rot,
col = xaxis.col,
tck = xaxis.tck,
fontface = if ('Nature' == style) { 'plain' } else { xaxis.fontface }
)
),
y = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
labels = yaxis.lab,
cex = yaxis.cex,
limits = ylimits,
at = yat,
rot = yaxis.rot,
col = yaxis.col,
tck = yaxis.tck,
fontface = if ('Nature' == style) { 'plain' } else { yaxis.fontface }
)
)
),
par.settings = list(
axis.line = list(
lwd = lwd,
col = if ('Nature' == style) { 'transparent' } else { 'black' }
),
layout.heights = list(
top.padding = top.padding,
main = if (is.null(main)) { 0.3 } else { 1 },
main.key.padding = 0.1,
key.top = 0.1,
key.axis.padding = 0.1,
axis.top = 1,
axis.bottom = 1,
axis.xlab.padding = 1,
xlab = 1,
xlab.key.padding = 0.5,
key.bottom = 0.1,
key.sub.padding = 0.1,
sub = 0.1,
bottom.padding = bottom.padding
),
layout.widths = list(
left.padding = left.padding,
key.left = 0.1,
key.ylab.padding = 0.1,
ylab = 1,
ylab.axis.padding = 1,
axis.left = 1,
axis.right = 1,
axis.panel = 0.3,
strip.left = 0.3,
panel = 1,
between = 1,
axis.right = 1,
axis.key.padding = 0.1,
right.padding = right.padding
),
box.dot = list(
pch = 19,
col = '#000000',
lty = 1
),
box.rectangle = list(
lwd = 3,
col = '#000000',
lty = 1
),
box.umbrella = list(
lwd = 2,
col = '#000000',
lty = 1
),
plot.symbol = list(
col = '#000000',
pch = 19,
cex = 0.5
),
plot.polygon = list(
col = col,
lwd = border.lwd
)
),
pch = '|',
pretty = TRUE,
horizontal = plot.horizontal,
key = key,
legend = legend
);
if (disable.factor.sorting == TRUE) {
sorting.param <- '';
if (plot.horizontal) {
sorting.param <- 'y';
if (is.null(trellis.object$y.scales$labels) || (is.logical(trellis.object$y.scales$labels[1]) && trellis.object$y.scales$labels[1] == TRUE)) {
default.labels <- unique(as.character(trellis.object$panel.args[[1]][[sorting.param]]));
trellis.object$y.scales$labels <- default.labels;
}
}
else {
sorting.param <- 'x';
if (is.null(trellis.object$x.scales$labels) || (is.logical(trellis.object$x.scales$labels[1]) && trellis.object$x.scales$labels[1] == TRUE)) {
default.labels <- unique(as.character(trellis.object$panel.args[[1]][[sorting.param]]));
trellis.object$x.scales$labels <- default.labels;
}
}
unique.mapping <- list();
count <- 1;
for (x in trellis.object$panel.args[[1]][[sorting.param]]) {
if (is.null(unique.mapping[[as.character(x)]])) {
unique.mapping[as.character(x)] <- count;
count <- count + 1;
}
}
temp.data <- as.character(trellis.object$panel.args[[1]][[sorting.param]]);
for (x in 1:length(temp.data)) {
temp.data[x] <- as.character(unique.mapping[as.character(trellis.object$panel.args[[1]][[sorting.param]][[x]])][[1]]);
}
trellis.object$panel.args[[1]][[sorting.param]] <- as.numeric(temp.data);
}
# If Nature style requested, change figure accordingly
if ('Nature' == style) {
# Re-add bottom and left axes
trellis.object$axis <- function(side, line.col = 'black', ...) {
# Only draw axes on the left and bottom
if (side %in% c('bottom', 'left')) {
axis.default(side = side, line.col = 'black', ...);
lims <- current.panel.limits();
panel.abline(h = lims$ylim[1], v = lims$xlim[1]);
}
}
# Ensure sufficient resolution for graphs
if (resolution < 1200) {
resolution <- 1200;
warning('Setting resolution to 1200 dpi.');
}
# Other required changes which are not accomplished here
warning('Nature also requires italicized single-letter variables and en-dashes
for ranges and negatives. See example in documentation for how to do this.');
warning('Avoid red-green colour schemes, create TIFF files, do not outline the figure or legend.');
}
# Otherwise use the BL style if requested
else if ('BoutrosLab' == style) {
# Nothing happens
}
# if neither of the above is requested, give a warning
else {
warning("The style parameter only accepts 'Nature' or 'BoutrosLab'.");
}
# output the object
return(
BoutrosLab.plotting.general::write.plot(
trellis.object = trellis.object,
filename = filename,
height = height,
width = width,
size.units = size.units,
resolution = resolution,
enable.warnings = enable.warnings,
description = description
)
);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/create.violinplot.R
|
# The BoutrosLab.statistics.general package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
critical.value.ks.test <- function(n, conf, alternative = "two.sided") {
if(alternative == "one-sided") conf <- 1- (1-conf)*2;
# for the small sample size
if (n < 50) {
# use the exact distribution from the C code in R
exact.kolmogorov.pdf <- function(x) {
p <- .Call("pKolmogorov2x", p = as.double(x), as.integer(n), PACKAGE = "BoutrosLab.plotting.general");
return(p - conf);
}
critical.value <- uniroot(exact.kolmogorov.pdf, lower = 0, upper = 1)$root;
}
# if the sample size is large(>50), under the null hypothesis, the absolute value of the difference
# of the empirical cdf and the theoretical cdf should follow a kolmogorov distribution
if (n >= 50) {
# pdf of the kolmogorov distribution minus the confidence level
kolmogorov.pdf <- function(x) {
i <- 1:10^4;
sqrt(2*pi) / x * sum(exp(-(2*i - 1)^2*pi^2/(8*x^2))) - conf;
}
# the root of the function above
# is the critical value for a specific confidence level multiplied by sqrt(n);
critical.value <- uniroot(kolmogorov.pdf , lower = 10^(-6), upper = 3)$root / sqrt(n);
}
return(critical.value);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/critical.value.ks.test.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO RETURN DEFAULT COLOUR PALETTES ####################################################
default.colours <- default.colors <- function(
number.of.colours = 2, palette.type = 'qual', is.greyscale = TRUE, is.venn = FALSE
) {
### HANDLE VENN DIAGRAM CASES #################################################################
# Default Venn diagram colour schemes
venn.cols <- c('red', 'dodgerblue', 'yellow');
venn.text <- c('darkred', 'darkblue', 'darkorange');
venn4.cols <- c('dodgerblue', 'springgreen', 'mediumpurple', 'palevioletred');
venn4.text <- c('darkblue', 'darkgreen', 'darkorchid4', 'darkred');
# Check if input combinations are valid
if (!is.null(palette.type) && is.venn == TRUE) {
warning('Do not specify a palette type if using a venn diagram. Setting palette type to NULL.');
palette.type <- NULL;
}
else if (is.null(palette.type) && is.venn == FALSE) {
stop('No palette type is specified.');
}
else if (length(number.of.colours) > 1 && is.venn == TRUE) {
warning('Multiple venn diagram colour schemes is not supported. Setting number.of.colours to first number specified.');
number.of.colours <- number.of.colours[1];
}
# Create venn diagram palette
if (is.venn) {
if (number.of.colours <= 3) {
palette <- venn.cols[1:number.of.colours];
palette.text <- venn.text[1:number.of.colours];
}
else if (number.of.colours == 4) {
palette <- venn4.cols;
palette.text <- venn4.text;
}
else {
stop('There is no venn diagram colour scheme consisting of more than 4 colours available.');
}
return(list(palette, palette.text));
}
### CREATE ALL OTHER PALETTES ##################################################################
div.one <- rgb(179, 43, 43, maxColorValue = 255);
div.two <- rgb(221, 78, 78, maxColorValue = 255);
div.thr <- rgb(235, 124, 124, maxColorValue = 255);
div.fou <- rgb(247, 190, 190, maxColorValue = 255);
div.fiv <- rgb(190, 244, 247, maxColorValue = 255);
div.six <- rgb(128, 205, 209, maxColorValue = 255);
div.sev <- rgb(69, 180, 187, maxColorValue = 255);
div.eig <- rgb(24, 139, 145, maxColorValue = 255);
col.fiv <- rgb(255 / 255, 225 / 255, 238 / 255);
col.fou <- rgb(244 / 255, 224 / 255, 166 / 255);
col.thr <- rgb(177 / 255, 211 / 255, 154 / 255);
col.two <- rgb(101 / 255, 180 / 255, 162 / 255);
col.one <- rgb(51 / 255, 106 / 255, 144 / 255);
pastel.one <- rgb(250, 229, 161, maxColorValue = 255);
pastel.two <- rgb(153, 193, 154, maxColorValue = 255);
pastel.thr <- rgb(114, 95, 122, maxColorValue = 255);
pastel.fou <- rgb(180, 105, 112, maxColorValue = 255);
pastel.fiv <- rgb(253, 252, 183, maxColorValue = 255);
pastel.six <- rgb(135, 179, 196, maxColorValue = 255);
pastel.sev <- rgb(133, 161, 115, maxColorValue = 255);
pastel.eig <- rgb(192, 153, 104, maxColorValue = 255);
pastel.nin <- rgb(203, 116, 245, maxColorValue = 255);
pastel.ten <- rgb(140, 201, 174, maxColorValue = 255);
pastel.ele <- rgb(190, 123, 187, maxColorValue = 255);
pastel.twe <- rgb(172, 232, 233, maxColorValue = 255);
spiral.morning.one <- rgb(84, 42, 133, maxColorValue = 255);
spiral.morning.two <- rgb(185, 47, 90, maxColorValue = 255);
spiral.morning.thr <- rgb(217, 113, 62, maxColorValue = 255);
spiral.morning.fou <- rgb(225, 199, 93, maxColorValue = 255);
spiral.morning.fiv <- rgb(234, 255, 128, maxColorValue = 255);
spiral.morning.six <- rgb(204, 247, 210, maxColorValue = 255);
spiral.dusk.one <- rgb(60, 78, 176, maxColorValue = 255);
spiral.dusk.two <- rgb(130, 94, 188, maxColorValue = 255);
spiral.dusk.thr <- rgb(198, 129, 216, maxColorValue = 255);
spiral.dusk.fou <- rgb(248, 180, 227, maxColorValue = 255);
spiral.dusk.fiv <- rgb(255, 229, 226, maxColorValue = 255);
spiral.afternoon.one <- rgb(132, 58, 28, maxColorValue = 255);
spiral.afternoon.two <- rgb(164, 141, 35, maxColorValue = 255);
spiral.afternoon.thr <- rgb(91, 203, 142, maxColorValue = 255);
spiral.afternoon.fou <- rgb(137, 195, 208, maxColorValue = 255);
spiral.afternoon.fiv <- rgb(214, 222, 255, maxColorValue = 255);
spiral.dawn.one <- rgb(143, 56, 185, maxColorValue = 255);
spiral.dawn.two <- rgb(215, 99, 195, maxColorValue = 255);
spiral.dawn.thr <- rgb(224, 134, 150, maxColorValue = 255);
spiral.dawn.fou <- rgb(232, 190, 162, maxColorValue = 255);
spiral.dawn.fiv <- rgb(241, 235, 148, maxColorValue = 255);
spiral.noon.one <- rgb(19, 10, 102, maxColorValue = 255);
spiral.noon.two <- rgb(13, 80, 140, maxColorValue = 255);
spiral.noon.thr <- rgb(90, 191, 87, maxColorValue = 255);
spiral.noon.fou <- rgb(230, 226, 92, maxColorValue = 255);
spiral.noon.fiv <- rgb(255, 193, 206, maxColorValue = 255);
spiral.night.one <- rgb(67, 26, 44, maxColorValue = 255);
spiral.night.two <- rgb(43, 35, 120, maxColorValue = 255);
spiral.night.thr <- rgb(21, 67, 137, maxColorValue = 255);
spiral.night.fou <- rgb(43, 185, 197, maxColorValue = 255);
spiral.night.fiv <- rgb(205, 231, 64, maxColorValue = 255);
### ORGANIZE PALETTES ##########################################################################
# Add new schemes to this list
schemes <- list(
dotmap = c('dodgerblue2', 'darkorange1'),
seq = BoutrosLab.plotting.general::colour.gradient('chartreuse4', 5),
div = c(div.one, div.two, div.thr, div.fou, div.fiv, div.six, div.sev, div.eig),
survival = c('royalblue2', 'firebrick', 'chartreuse3', 'purple4', 'plum1', 'orange', 'maroon3', 'turquoise3', 'chocolate4', 'lightcoral'),
qual = c('orange', 'chartreuse4', 'darkorchid4', 'gold', 'dodgerblue', 'firebrick3',
'yellowgreen', 'darkorange1', 'slateblue4', 'seagreen3', 'violetred3', 'turquoise3'),
pastel = c(pastel.one, pastel.two, pastel.thr, pastel.fou, pastel.fiv, pastel.six, pastel.sev,
pastel.eig, pastel.nin, pastel.ten, pastel.ele, pastel.twe),
spiral.dawn = c(spiral.dawn.one, spiral.dawn.two, spiral.dawn.thr, spiral.dawn.fou, spiral.dawn.fiv),
spiral.sunrise = c(col.one, col.two, col.thr, col.fou, col.fiv),
spiral.morning = c(spiral.morning.one, spiral.morning.two, spiral.morning.thr, spiral.morning.fou, spiral.morning.fiv, spiral.morning.six),
spiral.noon = c(spiral.noon.one, spiral.noon.two, spiral.noon.thr, spiral.noon.fou, spiral.noon.fiv),
spiral.afternoon = c(spiral.afternoon.one, spiral.afternoon.two, spiral.afternoon.thr, spiral.afternoon.fou, spiral.afternoon.fiv),
spiral.dusk = c(spiral.dusk.one, spiral.dusk.two, spiral.dusk.thr, spiral.dusk.fou, spiral.dusk.fiv),
spiral.night = c(spiral.night.one, spiral.night.two, spiral.night.thr, spiral.night.fou, spiral.night.fiv),
old.seq = c('darkolivegreen3', 'darkolivegreen4', 'darkolivegreen', 'darkgreen', 'black'),
old.div = c('darkorange', 'darkolivegreen4', 'goldenrod1', 'darkgreen', 'darkolivegreen3', 'orange',
'darkolivegreen', 'darkorange3'),
old.qual1 = c('orange', 'chartreuse4', 'darkorchid4', 'firebrick3', 'lightgrey', 'tan4', 'dodgerblue', 'orchid', 'black'),
old.qual2 = c('orange', 'chartreuse4', 'darkorchid4', 'firebrick3', 'gold', 'dodgerblue', 'yellowgreen',
'darkorange1', 'slateblue4', 'seagreen3', 'violetred3', 'turquoise3'),
chromosomes = c('darkred', 'firebrick1', 'pink1', 'darkorange3', 'darkorange', 'tan1', 'goldenrod3',
'gold', 'khaki', 'darkgreen', 'forestgreen', 'greenyellow', 'darkblue', 'dodgerblue', 'skyblue',
'darkslateblue', 'slateblue3', 'mediumpurple1', 'darkorchid4', 'orchid3', 'plum', 'violetred', 'grey31', 'grey0'),
seq.yellowgreen = c('lightyellow', 'darkolivegreen1', 'lawngreen', 'chartreuse3', 'green4', 'darkgreen'),
seq.green = c('mintcream', 'darkseagreen1', 'lightgreen', 'springgreen3', 'springgreen4', 'darkgreen'),
seq.greenblue = c('lightcyan', 'paleturquoise', 'turquoise1', 'darkturquoise', 'darkcyan', 'darkslategray'),
seq.blue = c('aliceblue', 'lightblue1', 'lightskyblue', 'deepskyblue', 'dodgerblue3', 'dodgerblue4'),
seq.bluepurple = c('aliceblue', 'lightsteelblue1', 'cornflowerblue', 'mediumslateblue', 'blueviolet', 'slateblue4'),
seq.purple = c('thistle1', 'plum1', 'orchid1', 'orchid3', 'orchid4', 'mediumpurple4'),
seq.purplered = c('lavenderblush', 'pink', 'palevioletred1', 'violetred1', 'maroon', 'violetred4'),
seq.redorange = c('peachpuff', 'lightsalmon', 'coral', 'orangered', 'orangered3', 'orangered4'),
seq.orange = c('papayawhip', 'navajowhite', 'darkgoldenrod1', 'darkorange', 'darkorange3', 'darkorange4')
);
# additional sequential colour schemes for cases when multiple sequential or binary schemes are requested
# this list specifies the order in which they are returned
sequential.schemes <- list(
seq.yellowgreen = schemes$seq.yellowgreen,
seq.green = schemes$seq.green,
seq.greenblue = schemes$seq.greenblue,
seq.blue = schemes$seq.blue,
seq.bluepurple = schemes$seq.bluepurple,
seq.purple = schemes$seq.purple,
seq.purplered = schemes$seq.purplered,
seq.redorange = schemes$seq.redorange,
seq.orange = schemes$seq.orange
);
### CREATE PALETTE #############################################################################
# check if number of colour schemes requested equals number of palette types specified (else return error)
if (length(number.of.colours) != length(palette.type)) {
stop('The number of colours schemes requested must equal the number of palette types specified.');
}
# Create palette
if (length(number.of.colours) > 1) {
palette <- vector(mode = 'list', length = length(number.of.colours));
}
else { palette <- c(); }
# Return all the palettes for display
if (1 == length(palette.type) && palette.type == 'all') { return(schemes); }
# Keep track of used schemes
used.schemes <- c();
for (i in 1:length(number.of.colours)) {
# Checking if palette.types are available
if (length(schemes[[palette.type[i]]]) < 1 && 'binary' != palette.type[i]) {
stop(paste('Invalid palette type', palette.type[i], 'is specified.'));
}
# check that the scheme has not been repeated
if ('seq' != palette.type[i] && 'binary' != palette.type[i]) {
if (palette.type[i] %in% used.schemes) {
warning('Duplicate palettes will be returned.');
}
}
# count how many sequential schemes have already been used
seq.count <- sum(c(used.schemes == 'seq', used.schemes == 'binary'));
used.schemes <- c(used.schemes, palette.type[i]);
# the first binary colour scheme will be white/black
binary.colour <- 'black';
if (seq.count > 0 && seq.count < length(sequential.schemes)) {
if ('seq' == palette.type[i]) {
palette.type[i] <- names(sequential.schemes[i]);
}
else if ('binary' == palette.type[i]) {
binary.colour <- sequential.schemes[[names(sequential.schemes[i])]][4];
print(binary.colour);
}
}
# check if binary schemes requested
if (palette.type[i] == 'binary' && as.numeric(number.of.colours[i]) > 2) {
warning('Binary colour schemes only return white and one other colour.');
}
# warning if the duplicate scheme returned
if (9 <= seq.count) {
warning('Duplicate palettes will be returned.');
}
# check that the reqested number of colours exists for the palette
if (length(schemes[[palette.type[i]]]) > 1 && number.of.colours[i] > length(schemes[[palette.type[i]]])) {
stop(paste0('The requested ', palette.type[i], ' colour scheme has a length of ',
length(schemes[[palette.type[i]]]), ' colours. You requested ', number.of.colours[i], '.'));
}
else if (length(sequential.schemes[[palette.type[i]]]) > 1 && number.of.colours[i] > length(sequential.schemes[[palette.type[i]]])) {
stop(paste0('The requested ', palette.type[i], ' colour scheme has a length of ',
length(sequential.schemes[[palette.type[i]]]), ' colours. You requested ', number.of.colours[i], '.'));
}
# Add to the final palette
if (length(schemes[[palette.type[i]]]) > 1) {
if (1 == length(number.of.colours)) { palette <- schemes[[palette.type[i]]][1:number.of.colours[i]]; }
else { palette[[i]] <- schemes[[palette.type[i]]][1:number.of.colours[i]]; }
}
else if (length(sequential.schemes[[palette.type[i]]]) > 1) {
if (1 == length(number.of.colours)) { palette <- sequential.schemes[[palette.type[i]]][1:number.of.colours[i]]; }
else { palette[[i]] <- sequential.schemes[[palette.type[i]]][1:number.of.colours[i]]; }
}
else if ('binary' == palette.type[i]) {
if (1 == length(number.of.colours)) { palette <- c('white', 'black'); }
else { palette[[i]] <- c('white', binary.colour); }
}
### CHECK GREYSCALE ############################################################################
# internal function to estimate greyscale compatibility
check.greyscale <- function(palette.to.check) {
grey.cols <- vector(length = length(palette.to.check));
i <- 0;
for (col in palette.to.check) {
rgbcol <- col2rgb(col);
greyval <- (0.2989 * rgbcol[1, 1]) + (0.5870 * rgbcol[2, 1]) + (0.1140 * rgbcol[3, 1]);
greyval <- greyval / 2.55;
greyval <- round(greyval);
i <- i + 1;
grey.cols[i] <- greyval;
}
minimum.difference <- min(diff(sort(grey.cols)));
# The cutoff value could be more scientifically chosen...
if (minimum.difference < 10) {
warning('Colour scheme may not be greyscale compatible.');
}
}
# run greyscale check (only if there is more than one colour selected)
if (is.greyscale && palette.type[i] != 'binary') {
if (1 == number.of.colours[i]) { next; }
else if (1 == length(number.of.colours)) { check.greyscale(palette); }
else { check.greyscale(palette[[i]]); }
}
}
return(palette);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/default.colours.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO DISPLAY COLOURS INCLUDING HOW THEY APPEAR IN GREYSCALE ############################
display.colours <- display.colors <- function(cols, names = cols) {
number.of.colours <- length(cols);
if (length(cols) != length(names)) {
stop('The number of colours and the number of names must be equal.');
}
plot.new();
par(mar = c(1, 1, 1, 1));
# set spacing
rect.y <- (par('usr')[4] - par('usr')[3]) / number.of.colours;
starting.y <- par('usr')[4] - rect.y / 2;
rect.x <- (par('usr')[2] - abs(par('usr')[1])) / 3;
starting.x <- (par('usr')[2] - abs(par('usr')[1])) / 3;
# Add the names of each colour
for (i in 1:length(names)) {
text(
x = starting.x / 2,
y = starting.y,
labels = names[i]
);
starting.y <- starting.y - rect.y;
}
starting.y <- par('usr')[4];
# draw coloured rectangles
for (i in 1:length(cols)) {
rect(
xleft = starting.x * 2,
ybottom = (starting.y - rect.y),
xright = rect.x,
ytop = starting.y,
col = cols[i],
lwd = 0
);
starting.y <- starting.y - rect.y;
}
# reset spacing variables to draw greyscale half
starting.y <- par('usr')[4];
# starting.x <- par('usr')[2];
ending.x <- (par('usr')[2] - abs(par('usr')[1])) / 3;
# draw greyscale rectangles
grey.cols <- vector(length = length(cols));
i <- 0;
for (col in cols) {
# convert R colour to rgb
rgbcol <- col2rgb(col);
# convert rgb colour to greyscale
greyval <- (0.2989 * rgbcol[1, 1]) + (0.5870 * rgbcol[2, 1]) + (0.1140 * rgbcol[3, 1]);
greyval <- greyval / 2.55;
greyval <- round(greyval);
i <- i + 1;
grey.cols[i] <- paste('grey', greyval, sep = '');
}
for (i in 1:length(grey.cols)) {
rect(
xleft = starting.x * 3,
ybottom = (starting.y - rect.y),
xright = rect.x * 2,
ytop = starting.y,
col = grey.cols[i],
lwd = 0
);
starting.y <- starting.y - rect.y;
}
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/display.colours.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO DISPLAY STATISTICAL RESULT ########################################################
# Description:
# Produces an expression containing a statistical result in scientific notation,
# ready to be displayed in a plot.
# Input variables:
# - The number to be put in scientific notation
# - The statistics type ("P", "Q", etc.)
# Output variables: An expression.
display.statistical.result <- function(
x, lower.cutoff = 2.2e-50, scientific.cutoff = 0.001, digits = 2, statistic.type = 'P', symbol = ': '
) {
# If x is smaller or equal to lower.cutoff, then the expression returned describes x
# simply as being smaller than lower.cutoff
if (lower.cutoff >= x) {
pvalue <- substitute(
expr = paste(statistic.type, ' < ', base %*% 10 ^ exponent, phantom('|')[phantom('|')]),
env = list(
base = unlist(
BoutrosLab.plotting.general::scientific.notation(
x = lower.cutoff,
digits = digits,
type = 'list'
)[1]
),
exponent = unlist(
BoutrosLab.plotting.general::scientific.notation(
x = lower.cutoff,
digits = digits,
type = 'list'
)[2]
),
statistic.type = statistic.type
)
);
pvalue <- as.expression(pvalue);
}
# If x is greater or equal to scientific.cutoff, standard decimal notation is used in
# the returned expression, rather than scientific notation
else if (scientific.cutoff <= x) {
pvalue <- as.expression(paste(statistic.type, symbol, signif(x, digits = digits), sep = ''));
}
# The following branch of the conditional statement is executed if and only if
# lower.cutoff < x < scientific.cutoff. In this case, in the final expression
# x will be displayed in scientific notation.
else {
pvalue <- substitute(
expr = paste(statistic.type, symbol, base %*% 10 ^ exponent, phantom('|')[phantom('|')]),
env = list(
base = unlist(
BoutrosLab.plotting.general::scientific.notation(
x = x,
digits = digits,
type = 'list'
)[1]
),
exponent = unlist(
BoutrosLab.plotting.general::scientific.notation(
x = x,
digits = digits,
type = 'list'
)[2]
),
statistic.type = statistic.type,
symbol = symbol
)
);
pvalue <- as.expression(pvalue);
}
return(pvalue);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/display.statistical.result.R
|
# The BoutrosLab.dist.overload package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
# File src/library/stats/R/dist.R
# Part of the R package, http://www.R-project.org
#
# 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.
#
# A copy of the GNU General Public License is available at
# http://www.r-project.org/Licenses/
dist <- function(x, method="euclidean", diag=FALSE, upper=FALSE, p=2)
{
## account for possible spellings of euclid?an
if(!is.na(pmatch(method, "euclidian")))
method <- "euclidean"
METHODS <- c("euclidean", "maximum",
"manhattan", "canberra", "binary", "minkowski", "jaccard")
method <- pmatch(method, METHODS)
if(is.na(method))
stop("invalid distance method")
if(method == -1)
stop("ambiguous distance method")
x <- as.matrix(x)
N <- nrow(x)
if (!is.double(x)) storage.mode(x) <- "double"
attrs <- if(method == 6L)
list(Size = N, Labels = dimnames(x)[[1L]], Diag = diag,
Upper = upper, method = METHODS[method],
p = p, call = match.call(), class = "dist")
else
list(Size = N, Labels = dimnames(x)[[1L]], Diag = diag,
Upper = upper, method = METHODS[method],
call = match.call(), class = "dist")
.Call("Cdist", x, method, attrs, p, PACKAGE = "BoutrosLab.plotting.general")
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/dist.R
|
export.to.file <- function(dirname, funcname, data, filename) {
user <- system('whoami', intern = T);
out.filename <- 'data-df.tsv';
date <- as.character(Sys.Date());
numeric.data <- c();
num.numeric <- 0;
num.factor <- 0;
num.integer <- 0;
num.rows <- 0;
num.cols <- 0;
if (is.null(filename)) {
filename <- 'None';
}
switch(
as.character(class(data)),
'list' = {
num.numeric <- length(data);
numeric.data <- unlist(data);
num.rows <- length(data[[1]]);
num.cols <- length(data);
},
'numeric' = {
num.numeric <- 1;
numeric.data <- data;
num.rows <- length(data);
num.cols <- 1;
},
'data.frame' =, 'matrix' = {
num.rows <- nrow(data);
num.cols <- ncol(data);
for (i in 1:num.cols) {
switch(
as.character(class(data[, i])),
'numeric' = {
num.numeric <- num.numeric + 1;
numeric.data <- c(numeric.data, data[, i]);
},
'integer' = {
num.integer <- num.integer + 1;
},
'factor' = {
num.factor <- num.factor + 1;
}
);
}
}
);
df.to.add <- NULL;
if (num.numeric == 0) {
df.to.add <- data.frame(user = c(user), filename = c(filename), date = date, func.name = c(funcname),
data.type = c(class(data)), nrow = num.rows, ncol = num.cols, numeric = c(num.numeric),
factor = c(num.factor), integer = c(num.integer), max = c(0), min = c(0), median = c(0));
}
else {
df.to.add <- data.frame(user = c(user), filename = c(filename), date = date, func.name = c(funcname),
data.type = c(class(data)), nrow = num.rows, ncol = num.cols, numeric = c(num.numeric),
factor = c(num.factor), integer = c(num.integer), max = c(max(numeric.data, na.rm = T)),
min = c(min(numeric.data, na.rm = T)), median = c(median(numeric.data, na.rm = T)));
}
if (!is.null(df.to.add)) {
if (!file.exists(paste(dirname, out.filename, sep = '/'))) {
write.table(df.to.add, paste(dirname, out.filename, sep = '/'), sep = '\t', row.names = F, col.names = T);
}
else {
datainfo.dataframe <- read.table(paste(dirname, out.filename, sep = '/'), header = T, fill = T);
index = -1;
for(i in 1:nrow(datainfo.dataframe)) {
## check if user, filename, date appears in dataframe
if(datainfo.dataframe[i,]$user == user && datainfo.dataframe[i,]$filename == filename && datainfo.dataframe[i,]$date == date) {
index = i;
}
}
if (index != -1) {
datainfo.dataframe[index, ] <- df.to.add;
write.table(datainfo.dataframe, paste(dirname, out.filename, sep = '/'), sep = '\t', row.names = F, col.names = T);
}
else {
write.table(df.to.add, paste(dirname, out.filename, sep = '/'), sep = '\t', row.names = F, col.names = F, append = T);
}
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/export.to.file.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO SET COLOUR SCHEMES ################################################################
force.colour.scheme <- force.color.scheme <- function(
x = NA, scheme, fill.colour = 'slategrey', include.names = FALSE, return.factor = FALSE, return.scheme = FALSE
) {
# some error checking
if (as.character(class(x) == 'factor')) {
stop("Argument 'x' cannot be a factor: please coerce to character before passing.");
}
if (scheme == 'psa.categorical') {
x.processed <- x;
if (length(grep(x = x, '-|>')) == 0) {
x <- as.numeric(x);
x.processed <- rep('0 - 9.9', length(x));
x.processed[x >= 10 & x < 20] <- '10 - 19.9';
if (any(x >= 20, na.rm = TRUE)) {
x.processed[x >= 20] <- '>= 20';
}
if (any(is.na(x))) {
x.processed[is.na(x)] <- NA;
}
}
x <- x.processed;
}
else if (scheme == 'age.categorical.default') {
x.processed <- x;
if (length(grep(x = x, '-|>|<')) == 0) {
x <- as.numeric(x);
x.processed <- rep('<50', length(x));
x.processed[x >= 50 & x < 60] <- '50 - 60';
x.processed[x >= 60 & x < 70] <- '60 - 70';
if (any(x >= 70, na.rm = TRUE)) {
x.processed[x >= 70] <- '>= 70';
}
if (any(is.na(x))) {
x.processed[is.na(x)] <- NA;
}
}
x <- x.processed;
}
else if (scheme == 'age.categorical.prostate') {
x.processed <- x;
if (length(grep(x = x, '-|>|<')) == 0) {
x <- as.numeric(x);
x.processed <- rep('<40', length(x));
x.processed[x >= 40 & x < 50] <- '40 - 50';
x.processed[x >= 50 & x < 65] <- '50 - 65';
x.processed[x >= 65 & x < 70] <- '65 - 70';
if (any(x >= 70, na.rm = TRUE)) {
x.processed[x >= 70] <- '>= 70';
}
if (any(is.na(x))) {
x.processed[is.na(x)] <- NA;
}
}
x <- x.processed;
}
else if (scheme == 'age.gradient') {
x[x < 40] <- 40;
x[x > 70] <- 70;
colour.x <- x - 40;
colour.x <- colour.x / 30.0;
colour.scheme <- c('white', 'black');
colour.function <- colorRamp(colour.scheme, space = 'rgb');
my.palette <- rgb(colour.function(colour.x), maxColorValue = 255);
return(my.palette);
}
else if (scheme == 'psa.gradient') {
x[x < 0] <- 0;
x[x > 20] <- 20;
x <- x / 20.0;
colour.scheme <- c('white', 'darkred');
colour.function <- colorRamp(colour.scheme, space = 'rgb');
my.palette <- rgb(colour.function(x), maxColorValue = 255);
return(my.palette);
}
else if (scheme == 'heteroplasmy') {
x.processed <- x;
x <- as.numeric(x);
x.processed <- rep('NA', length(x));
x.processed[x >= 0 & x < 0.2] <- '0';
x.processed[x >= 0.2 & x < 0.4] <- '1';
x.processed[x >= 0.4 & x < 0.6] <- '2';
x.processed[x >= 0.6 & x <= 1] <- '3';
x <- x.processed;
}
else if (scheme == 'mt.annotation') {
x.processed <- x;
x.processed[grepl('MT-T', x.processed)] <- 'MT-T';
x.processed[grepl('MT-RNR', x.processed)] <- 'MT-RNR';
x.processed[grepl('MT-NC', x.processed)] <- 'MT-NC';
x.processed[grepl('MT-OL', x.processed)] <- 'MT-OL';
x <- x.processed;
}
# Set all input to lower case
x <- tolower(x);
scheme <- tolower(scheme);
# loading tissue colours
# skeletal
cartilage <- rgb(90 / 255, 90 / 255, 90 / 255);
bone <- rgb(150 / 255, 150 / 255, 150 / 255);
# adipose
adipose <- rgb(156 / 255, 65 / 255, 13 / 255);
# excretory
bladder <- rgb(98 / 255, 47 / 255, 9 / 255);
kidney <- rgb(213 / 255, 119 / 255, 80 / 255);
# circulatory
blood <- rgb(173 / 255, 12 / 255, 9 / 255);
heart <- rgb(248 / 255, 15 / 255, 15 / 255);
# muscular
muscle <- rgb(243 / 255, 173 / 255, 178 / 255);
# endocrine
hypothalamus <- rgb(135 / 255, 98 / 255, 44 / 255);
pituitary <- rgb(183 / 255, 148 / 255, 75 / 255);
thyroid <- rgb(219 / 255, 195 / 255, 132 / 255);
parathyroid <- rgb(245 / 255, 233 / 255, 179 / 255);
skin <- rgb(255 / 255, 173 / 255, 77 / 255);
# gastrointestinal
salivarygland <- rgb(68 / 255, 88 / 255, 25 / 255);
esophagus <- rgb(116 / 255, 140 / 255, 52 / 255);
stomach <- rgb(150 / 255, 196 / 255, 82 / 255);
liver <- rgb(197 / 255, 230 / 255, 149 / 255);
gallbladder <- rgb(4 / 255, 92 / 255, 31 / 255);
pancreas <- rgb(44 / 255, 145 / 255, 80 / 255);
intestine <- rgb(77 / 255, 194 / 255, 104 / 255);
colon <- rgb(133 / 255, 231 / 255, 133 / 255);
# respiratory
pharynx <- rgb(27 / 255, 93 / 255, 99 / 255);
larynx <- rgb(36 / 255, 131 / 255, 139 / 255);
trachea <- rgb(48 / 255, 175 / 255, 186 / 255);
diaphragm <- rgb(91 / 255, 210 / 255, 220 / 255);
lung <- rgb(173 / 255, 237 / 255, 243 / 255);
# nervous
nerve <- rgb(32 / 255, 90 / 255, 205 / 255);
spine <- rgb(58 / 255, 121 / 255, 245 / 255);
brain <- rgb(111 / 255, 156 / 255, 244 / 255);
eye <- rgb(154 / 255, 183 / 255, 241 / 255);
# reproductive
breast <- rgb(104 / 255, 15 / 255, 78 / 255);
ovary <- rgb(224 / 255, 131 / 255, 197 / 255);
uterus <- rgb(246 / 255, 189 / 255, 229 / 255);
prostate <- rgb(152 / 255, 41 / 255, 119 / 255);
testes <- rgb(204 / 255, 66 / 255, 160 / 255);
# immune
lymph <- rgb(82 / 255, 49 / 255, 166 / 255);
leukocyte <- rgb(144 / 255, 114 / 255, 219 / 255);
spleen <- rgb(195 / 255, 181 / 255, 225 / 255);
# load tumour stage colours
i <- rgb(255 / 255, 211 / 255, 153 / 255);
ii <- rgb(255 / 255, 174 / 255, 69 / 255);
iii <- rgb(184 / 255, 114 / 255, 23 / 255);
iv <- rgb(119 / 255, 70 / 255, 7 / 255);
# load risk colours
high <- rgb(155 / 255, 19 / 255, 19 / 255);
low <- rgb(234 / 255, 196 / 255, 120 / 255);
old.high <- rgb(252 / 255, 87 / 255, 75 / 255);
old.low <- rgb(112 / 255, 221 / 255, 240 / 255);
# load MSI colours
old.msi.high <- rgb(147 / 255, 183 / 255, 235 / 255);
old.msi.low <- rgb(50 / 255, 119 / 255, 216 / 255);
old.mss <- rgb(42 / 255, 82 / 255, 138 / 255);
# new scheme is based on old CNV colours (green-yellow)
msi.high <- rgb(84 / 255, 161 / 255, 76 / 255);
msi.low <- rgb(186 / 255, 219 / 255, 96 / 255);
mss <- rgb(243 / 255, 239 / 255, 82 / 255);
# load tumour sample type colours
primary <- rgb(181 / 255, 127 / 255, 212 / 255);
metastatic <- rgb(114 / 255, 23 / 255, 165 / 255);
# load CNV colours
amplification <- rgb(252 / 255, 87 / 255, 75 / 255);
deletion <- rgb(112 / 255, 221 / 255, 240 / 255);
loh <- rgb(53 / 255, 158 / 255, 87 / 255);
neutral <- 'white';
# organism
human <- rgb(158, 82, 53, maxColorValue = 255);
rat <- rgb(191, 136, 116, maxColorValue = 255);
mouse <- rgb(232, 212, 203, maxColorValue = 255);
# chromosome
chr.1 <- rgb(222, 71, 171, maxColorValue = 255);
chr.2 <- rgb(114, 190, 151, maxColorValue = 255);
chr.3 <- rgb(247, 247, 151, maxColorValue = 255);
chr.4 <- rgb(124, 116, 155, maxColorValue = 255);
chr.5 <- rgb(232, 87, 38, maxColorValue = 255);
chr.6 <- rgb(179, 149, 248, maxColorValue = 255);
chr.7 <- rgb(220, 135, 71, maxColorValue = 255);
chr.8 <- rgb(150, 213, 61, maxColorValue = 255);
chr.9 <- rgb(220, 133, 238, maxColorValue = 255);
chr.10 <- rgb(125, 50, 179, maxColorValue = 255);
chr.11 <- rgb(136, 219, 104, maxColorValue = 255);
chr.12 <- rgb(120, 170, 241, maxColorValue = 255);
chr.13 <- rgb(217, 198, 202, maxColorValue = 255);
chr.14 <- rgb(51, 108, 128, maxColorValue = 255);
chr.15 <- rgb(247, 202, 68, maxColorValue = 255);
chr.16 <- rgb(50, 199, 199, maxColorValue = 255);
chr.17 <- rgb(212, 197, 242, maxColorValue = 255);
chr.18 <- rgb(153, 84, 147, maxColorValue = 255);
chr.19 <- rgb(248, 139, 120, maxColorValue = 255);
chr.20 <- rgb(71, 94, 204, maxColorValue = 255);
chr.21 <- rgb(224, 189, 140, maxColorValue = 255);
chr.22 <- rgb(158, 40, 0, maxColorValue = 255);
chr.x <- rgb(242, 187, 210, maxColorValue = 255);
chr.y <- rgb(182, 235, 234, maxColorValue = 255);
# biomolecule
dna <- rgb(205, 238, 240, maxColorValue = 255);
rna <- rgb(169, 192, 236, maxColorValue = 255);
protein <- rgb(178, 150, 223, maxColorValue = 255);
carbohydrate <- rgb(202, 113, 145, maxColorValue = 255);
lipid <- rgb(231, 221, 54, maxColorValue = 255);
# snv
nonsynonymous <- rgb(177 / 255, 213 / 255, 181 / 255);
stopgain <- rgb(249 / 255, 179 / 255, 142 / 255);
frameshiftdeletion <- rgb(154 / 255, 163 / 255, 242 / 255);
#clincal T3
clinical.t3.1 <- rgb(255, 247, 223, maxColorValue = 255);
clinical.t3.2 <- rgb(221, 246, 139, maxColorValue = 255);
clinical.t3.3 <- rgb(109, 196, 110, maxColorValue = 255);
clinical.t3.4 <- rgb(47, 109, 96, maxColorValue = 255);
clinical.t3.5 <- rgb(25, 55, 81, maxColorValue = 255);
clinical.t3.6 <- rgb(8, 0, 16, maxColorValue = 255);
#clinical T9
clinical.t9.1 <- rgb(143, 161, 82, maxColorValue = 255);
clinical.t9.2 <- rgb(178, 200, 105, maxColorValue = 255);
clinical.t9.3 <- rgb(221, 246, 139, maxColorValue = 255);
clinical.t9.4 <- rgb(56, 145, 58, maxColorValue = 255);
clinical.t9.5 <- rgb(109, 196, 110, maxColorValue = 255);
clinical.t9.6 <- rgb(179, 238, 180, maxColorValue = 255);
clinical.t9.7 <- rgb(47, 109, 96, maxColorValue = 255);
clinical.t9.8 <- rgb(94, 194, 170, maxColorValue = 255);
clinical.t9.9 <- rgb(192, 231, 222, maxColorValue = 255);
#heteroplasmy
heteroplasmy.0 <- 'white';
heteroplasmy.1 <- 'lightskyblue';
heteroplasmy.2 <- 'dodgerblue';
heteroplasmy.3 <- 'mediumblue';
#MT annotation
mt.annotation.1 <- '#B041FF';
mt.annotation.2 <- '#5EFB6E';
mt.annotation.3 <- '#005000';
mt.annotation.4 <- '#2B65EC';
mt.annotation.5 <- '#FF6E32';
mt.annotation.6 <- '#A00000';
mt.annotation.7 <- '#FFFF78';
mt.annotation.8 <- 'white';
#ISUP Grade
isup.grade.1 <- 'cornsilk';
isup.grade.2 <- 'yellow';
isup.grade.3 <- 'orange';
isup.grade.4 <- 'maroon3';
isup.grade.5 <- 'red';
# irregular spacing is used here to allow for visual mapping between colours and corresponding values
avail.schemes <- list(
tissue = list(
levels = c('cartilage', 'bone', 'adipose', 'bladder', 'kidney', 'blood', 'heart', 'muscle',
'hypothalamus', 'pituitary', 'thyroid', 'parathyroid', 'skin', 'salivary gland', 'esophagus',
'stomach', 'liver', 'gall bladder', 'pancreas', 'intestine', 'colon', 'pharynx', 'larynx', 'trachea',
'diaphragm', 'lung', 'nerve', 'spine', 'brain', 'eye', 'breast', 'ovary', 'uterus', 'prostate', 'testes',
'lymph', 'leukocyte', 'spleen'),
colours = c(cartilage, bone, adipose, bladder, kidney, blood, heart, muscle, hypothalamus, pituitary, thyroid,
parathyroid, skin, salivarygland, esophagus, stomach, liver, gallbladder, pancreas, intestine, colon,
pharynx, larynx, trachea, diaphragm, lung, nerve, spine, brain, eye, breast, ovary, uterus, prostate, testes,
lymph, leukocyte, spleen)
),
chromosome = list(
levels = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 'x', 'y'),
colours = c(chr.1, chr.2, chr.3, chr.4, chr.5, chr.6, chr.7, chr.8, chr.9, chr.10, chr.11, chr.12, chr.13, chr.14,
chr.15, chr.16, chr.17, chr.18, chr.19, chr.20, chr.21, chr.22, chr.x, chr.y)
),
old.chromosome = list(
levels = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 'x', 'y'),
colours = c('darkred', 'firebrick1', 'pink1', 'darkorange3', 'darkorange', 'tan1', 'goldenrod3', 'gold', 'khaki',
'darkgreen', 'forestgreen', 'greenyellow', 'darkblue', 'dodgerblue', 'skyblue', 'darkslateblue', 'slateblue3',
'mediumpurple1', 'darkorchid4', 'orchid3', 'plum', 'violetred', 'grey31', 'grey0')
),
annovar.annotation.collapsed2 = list(
levels = c('nonsynonymous', 'stopgain-stoploss', 'splicing', 'frameshift indel', 'synonymous', 'utr5-utr3',
'nonframeshift indel', 'intronic', 'intergenic', 'other'),
colours = c('darkseagreen4', 'orchid4', 'darkturquoise', 'darkorange', 'gold1', 'grey30', 'grey50', 'grey70', 'grey90', 'white')
),
annovar.annotation = list(
levels = c('nonsynonymous snv', 'stopgain snv', 'stoploss snv', 'frameshift deletion', 'frameshift substitution', 'splicing', 'synonymous snv'),
colours = c('darkseagreen4', 'orchid4', 'darkturquoise', 'darkorange', 'darkorange4', 'gold1', 'darkgrey')
),
annovar.annotation.collapsed = list(
levels = c('nonsynonymous snv', 'stopgain snv', 'stoploss snv', 'frameshift indel', 'splicing'),
colours = c('darkseagreen4', 'orchid4', 'darkturquoise', 'darkorange', 'gold1')
),
snv = list(
levels = c('nonsynonymous', 'stop gain', 'frameshift deletion', 'nonframeshift deletion', 'splicing', 'unknown'),
colours = c(nonsynonymous, stopgain, frameshiftdeletion, 'gold', 'skyblue', 'plum')
),
biomolecule = list(
levels = c('dna', 'rna', 'protein', 'carbohydrate', 'lipid'),
colours = c(dna, rna, protein, carbohydrate, lipid)
),
sex = list(
levels = c('male', 'female'),
colours = c('lightskyblue', 'lightpink')
),
stage = list(
levels = c('i', 'ii', 'iii', 'iv'),
colours = c(i, ii, iii, iv)
),
risk = list(
levels = c('high', 'low'),
colours = c(high, low)
),
old.risk = list(
levels = c('high', 'low'),
colours = c(old.high, old.low)
),
msi = list(
levels = c('msi-high', 'msi-low', 'mss'),
colours = c(msi.high, msi.low, mss)
),
old.msi = list(
levels = c('msi-high', 'msi-low', 'mss'),
colours = c(old.msi.high, old.msi.low, old.mss)
),
tumour = list(
levels = c('primary', 'metastatic'),
colours = c(primary, metastatic)
),
cnv = list(
levels = c('amplification', 'deletion', 'loh', 'neutral'),
colours = c(amplification, deletion, loh, neutral)
),
old.cnv = list(
levels = c('amplification', 'deletion', 'loh', 'neutral'),
colours = c(msi.high, msi.low, mss, neutral)
),
organism = list(
levels = c('human', 'rat', 'mouse'),
colours = c(human, rat, mouse)
),
clinicalt3 = list(
levels = c('t0', 't1', 't2', 't3', 't4', 't5'),
colours = c(clinical.t3.1, clinical.t3.2, clinical.t3.3, clinical.t3.4, clinical.t3.5, clinical.t3.6)
),
clinicalt9 = list(
levels = c('t1a', 't1b', 't1c', 't2a', 't2b', 't2c', 't3a', 't3b', 't3c'),
colours = c(clinical.t9.1, clinical.t9.2, clinical.t9.3, clinical.t9.4, clinical.t9.5, clinical.t9.6,
clinical.t9.7, clinical.t9.8, clinical.t9.9)
),
gleason.score = list(
levels = c('3+3', '3+4', '4+3', '4+4', '4+5', '3+5', '5+3', '5+4', '5+5', 'missing', 'NA'),
colours = c('white', 'yellow', 'orange', 'red', 'brown', 'maroon3', 'magenta4', 'mediumblue', 'black', 'slategrey', 'slategrey')
),
gleason.sum = list(
levels = c(5, 6, 7, 8, 9, 'missing', 'NA'),
colours = c('#FEEBE2', '#FBB4B9', '#F768A1', '#C51B8A', '#7A0177', 'slategrey', 'slategrey', 'slategrey')
),
tissue.color = list(
levels = c('blood', 'frozen', 'ffpe'),
colours = c('orangered4', 'peachpuff2', 'rosybrown')
),
psa.categorical = list(
levels = c('0 - 9.9', '10 - 19.9', '>= 20'),
colours = c('#FEE6CE', '#FDAE6B', '#E6550D')
),
age.categorical.default = list(
levels = c('<50', '50 - 60', '60 - 70', '>= 70'),
colours = c('gray100', 'gray66', 'gray33', 'gray0')
),
age.categorical.prostate = list(
levels = c('<40', '40 - 50', '50 - 65', '65 - 70', '>= 70'),
colours = c('gray100', 'gray75', 'gray50', 'gray25', 'gray0')
),
heteroplasmy = list(
levels = c('0', '1', '2', '3'),
colours = c(heteroplasmy.0, heteroplasmy.1, heteroplasmy.2, heteroplasmy.3)
),
mt.annotation = list(
levels = c('mt-dloop', 'mt-t', 'mt-rnr', 'mt-nd1', 'mt-nd2', 'mt-nd3', 'mt-nd4l', 'mt-nd4l/mt-nd4', 'mt-nd4',
'mt-nd5', 'mt-nd6', 'mt-co1', 'mt-co2', 'mt-co3', 'mt-atp6/mt-co3', 'mt-atp6', 'mt-atp8/mt-atp6',
'mt-atp8', 'mt-cyb', 'mt-nc', 'mt-ol'),
colours = c(mt.annotation.1, mt.annotation.2, mt.annotation.3, mt.annotation.4, mt.annotation.4, mt.annotation.4,
mt.annotation.4, mt.annotation.4, mt.annotation.4, mt.annotation.4, mt.annotation.4, mt.annotation.6,
mt.annotation.6, mt.annotation.6, mt.annotation.6, mt.annotation.7, mt.annotation.7, mt.annotation.7,
mt.annotation.5, mt.annotation.8, mt.annotation.8)
),
isup.grade = list(
levels = c('1', '2', '3', '4', '5'),
colours = c(isup.grade.1, isup.grade.2, isup.grade.3, isup.grade.4, isup.grade.5)
)
);
if (is.null(avail.schemes[[scheme]]) && scheme != 'all') {
stop('Scheme not found!');
}
# format return values
to.return <- list();
# if return.scheme is requested
if (return.scheme) {
if ('all' == scheme) {
to.return[['scheme']] <- avail.schemes;
}
else {
to.return[['scheme']] <- avail.schemes[[scheme]];
}
}
# check to see if more than 1 type unknown. 1 is expected for 'none' or similar, but 2+ likely to be error.
if (1 < sum(!unique(x) %in% avail.schemes[[scheme]]$levels)) {
warning('More than one unique entry of x is not found in scheme. Perhaps an error?');
}
x.as.factor <- factor(x, levels = avail.schemes[[scheme]]$levels);
# if return.factor is requested
if (return.factor) {
to.return[['return.factor']] <- x.as.factor;
}
x.colours <- avail.schemes[[scheme]]$colours[x.as.factor];
x.colours[is.na(x.colours)] <- fill.colour;
# return the converted list
if (include.names) {
names(x.colours) <- x;
}
to.return[['colours']] <- x.colours;
if (1 == length(to.return)) {
return(to.return[[1]]);
}
else {
return(to.return);
}
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/force.colour.scheme.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2011 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO SET CUSTOM TICK MARK LOCATIONS ####################################################
generate.at.final <- function(at.input, limits, data.vector) {
at.final <- NULL;
if (is.numeric(at.input)) {
at.final <- at.input;
}
else {
if (is.null(limits)) {
# making the range slightly larger than the at range
# this allows grid-lines to appear, rather than merge into the axes
extended.range <- range(data.vector) + 0.1 * (max(data.vector) - min(data.vector)) * c(-1, 1);
at.final <- pretty(lattice.options()$default.args$xscale.components(extended.range)$bottom$ticks$at);
}
else {
at.final <- pretty(x = limits);
}
}
return(at.final);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/generate.at.final.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO CREATE CORRELATION KEY ############################################################
get.corr.key <- function(
x, y, label.items = c('spearman', 'spearman.p'), x.pos = 0.03, y.pos = 0.97, key.corner = NULL,
key.cex = 1, key.title = NULL, title.cex = 1, alpha.background = 0, num.decimals = 2,
border = 'white') {
# use 'all' as an alternative to all the label items
if (label.items[1] == 'all') {
label.items <- c('spearman', 'pearson', 'kendall', 'beta0', 'beta1', 'spearman.p', 'pearson.p', 'kendall.p', 'beta1.p');
}
# define the corner of the key used for the x.pos and y.pos
if (is.null(key.corner)) {
if (x.pos < .5 & y.pos < .5) { corner <- c(0, 0); }
if (x.pos < .5 & y.pos >= .5) { corner <- c(0, 1); }
if (x.pos >= .5 & y.pos < .5) { corner <- c(1, 0); }
if (x.pos >= .5 & y.pos >= .5) { corner <- c(1, 1); }
}
# define some variables
key.list <- NULL;
# loop through each item label and add it to the key
for (i in label.items) {
# define the symbol
if (grepl('pearson', i)) { corr.symbol <- quote(R); }
if (grepl('spearman', i)) { corr.symbol <- quote(rho); }
if (grepl('kendall', i)) { corr.symbol <- quote(tau); }
if (grepl('eta', i)) { corr.symbol <- quote(Beta); }
# calculate the correlation values
if (i %in% c('spearman', 'pearson', 'kendall')) {
key.item <- substitute(
corr.symbol == paste(correlation, phantom('|')[phantom('|')], phantom('|') ^ phantom('|')),
env = list(
correlation = format(
round(
BoutrosLab.plotting.general::get.correlation.p.and.corr(
x = x,
y = y,
method = i
)[1],
digits = num.decimals
),
nsmall = num.decimals
),
corr.symbol = corr.symbol
)
);
}
# calculate beta0 i.e. intercept
if (i == 'beta0') {
key.item <- substitute(
Beta[0] == paste(beta.effect, phantom('|')[phantom('|')], phantom('|') ^ phantom('|')),
env = list(
beta.effect = format(round(coef(lm(y ~ x))[1], num.decimals), nsmall = num.decimals)
)
);
}
# calculate beta1 i.e. slope
if (i == 'beta1') {
key.item <- substitute(
Beta[1] == paste(beta.effect, phantom('|')[phantom('|')], phantom('|') ^ phantom('|')),
env = list(
beta.effect = format(round(coef(lm(y ~ x))[2], num.decimals), nsmall = num.decimals)
)
);
}
# calculate robust beta0 i.e. intercept
if (i == 'beta0.robust') {
key.item <- substitute(
Beta[paste(0, ',rob')] == paste(beta.effect, phantom('|')[phantom('|')], phantom('|') ^ phantom('|')),
env = list(
beta.effect = format(round(coef(rlm(y ~ x))[1], num.decimals), nsmall = num.decimals)
)
);
}
# calculate robust beta1 i.e. slope
if (i == 'beta1.robust') {
key.item <- substitute(
Beta[paste(1, ',rob')] == paste(beta.effect, phantom('|')[phantom('|')], phantom('|') ^ phantom('|')),
env = list(
beta.effect = format(round(coef(rlm(y ~ x))[2], num.decimals), nsmall = num.decimals)
)
);
}
# calculate the correlation pvalues
if (i %in% c('spearman.p', 'pearson.p', 'kendall.p')) {
if (BoutrosLab.plotting.general::get.correlation.p.and.corr(x = x, y = y, method = gsub('.p', '', i, fixed = TRUE))[2] > 0) {
key.item <- substitute(
P[corr.symbol] == paste(base %*% 10 ^ exponent, phantom('|')[phantom('|')] ),
env = list(
base = unlist(
BoutrosLab.plotting.general::scientific.notation(
x = BoutrosLab.plotting.general::get.correlation.p.and.corr(
x = x,
y = y,
method = gsub('.p', '', i, fixed = TRUE)
)[2],
digits = 2,
type = 'list'
)[1]
),
exponent = unlist(
BoutrosLab.plotting.general::scientific.notation(
x = BoutrosLab.plotting.general::get.correlation.p.and.corr(
x = x,
y = y,
method = gsub('.p', '', i, fixed = TRUE)
)[2],
digits = 2,
type = 'list'
)[2]
),
corr.symbol = corr.symbol
)
);
}
# if the p.value is 0 set it the minimum value
else {
key.item <- expression(paste('P < 2.2 x', 10 ^ -16, phantom('|')[phantom('|')]));
}
}
# calculate the wald test for beta
if (i == 'beta1.p') {
if (coef(summary(lm(y ~ x)))[2, 4] > 0) {
key.item <- substitute(
P[B[1]] == paste(base %*% 10 ^ exponent, phantom('|')[phantom('|')]),
env = list(
base = unlist(BoutrosLab.plotting.general::scientific.notation(
x = coef(summary(lm(y ~ x)))[2, 4],
digits = 2,
type = 'list'
)[1]),
exponent = unlist(BoutrosLab.plotting.general::scientific.notation(
x = coef(summary(lm(y ~ x)))[2, 4],
digits = 2,
type = 'list'
)[2])
)
);
}
# if the p.value is 0 set it the minimum value
else {
key.item <- expression(paste('P < 2.2 x', 10 ^ -16, phantom('|')[phantom('|')]));
}
}
# calculate the wald test for beta
if (i == 'beta1.robust.p') {
if (coef(summary(lm(y ~ x)))[2, 4] > 0) {
key.item <- substitute(
P[B[paste(1, ',rob')]] == paste(base %*% 10 ^ exponent, phantom('|')[phantom('|')]),
env = list(
base = unlist(BoutrosLab.plotting.general::scientific.notation(
x = 2 * pt(coef(summary(rlm(y ~ x)))[2, 3],
df = summary(rlm(y ~ x))$df[2],
lower.tail = FALSE),
digits = 2,
type = 'list'
)[1]),
exponent = unlist(BoutrosLab.plotting.general::scientific.notation(
x = 2 * pt(coef(summary(rlm(y ~ x)))[2, 3],
df = summary(rlm(y ~ x))$df[2],
lower.tail = FALSE),
digits = 2,
type = 'list'
)[2])
)
);
}
# if the p.value is 0 set it the minimum value
else {
key.item <- expression(paste(P[phantom(0)], '< 2.2 x', 10 ^ -16, phantom('|')[phantom('|')] ));
}
}
# add each item to the vector of labels
key.list <- c(key.list, as.expression(key.item));
}
# define the key
key <- list(
text = list(
lab = key.list,
cex = key.cex,
fontface = 'bold'
),
padding.text = 0,
x = x.pos,
y = y.pos,
corner = corner,
title = key.title,
cex.title = title.cex,
background = 'white',
alpha.background = alpha.background,
border = border
);
return(key);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/get.corr.key.R
|
# The BoutrosLab.statistics.general package is copyright (c) 2011 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
get.correlation.p.and.corr <- function(x, y, alternative = 'two.sided', method = 'pearson') {
x = as.numeric(x);
y = as.numeric(y);
if( (method == 'spearman') & ( anyDuplicated(x) | anyDuplicated(y) ) ) {exact = FALSE;}
else {exact = TRUE;}
tryCatch(
expr = as.vector(
unlist(
cor.test(
x = x,
y = y,
alternative = alternative,
method = method,
exact = exact
)[c('estimate', 'p.value')]
)
),
error = function(e) { return ( c(NA, NA)); }
);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/get.correlation.p.and.corr.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO GET OPERATING SYSTEM PROPERTIES ###################################################
get.defaults <- function(property = 'fontfamily', os.type = .Platform$OS.type, add.to.list = NULL, use.legacy.settings = FALSE) {
# *nix specific settings
if (os.type == 'unix') {
if (property == 'fontfamily') {
if (length(add.to.list) > 0) {
#add.to.list[['fontfamily']] <- if (use.legacy.settings) {'Arial';} else {'ArialMT';}
}
else {
# add.to.list <- if (use.legacy.settings) {'Arial';} else {'ArialMT';}
}
}
}
# windows specific and default settings
else {
if (property == 'fontfamily') {
if (length(add.to.list) > 0) {
#add.to.list[["fontfamily"]] <- 'Arial'; # PCB -- seems no need to be making these settings anymore, defaults work
}
else {
#add.to.list <- 'Arial'; # PCB -- seems no need to be making these settings anymore, defaults work
}
}
}
return(add.to.list);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/get.defaults.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO GET LINE BREAKS ###################################################################
get.line.breaks <- function(x) {
v <- rep(NA, length(x));
for (i in 2:length(v)) {
v[i] <- ifelse(x[i] != x[i - 1], TRUE, FALSE);
}
# find breaks and add padding
breaks <- which(v) - 0.5;
return(breaks);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/get.line.breaks.R
|
.inside.auto.legend <- function(function.name, filename, trellis.object, height, width, extra.parameters) {
if (is.null(filename)) {
height <- 7;
}
if (is.null(filename)) {
width <- 7;
}
extension <- file_ext(filename);
if (!is.null(filename)) {
# cairo is not available on M1 Macs, so fallback to default if necessary
bitmap.type <- getOption('bitmapType')
if (capabilities('cairo')) {
bitmap.type <- 'cairo'
}
if ('tiff' == extension) {
tiff(filename = 'temp', type = bitmap.type, units = 'in', height = height, width = width, res = 92);
}
else if ('png' == extension) {
png(filename = 'temp', type = bitmap.type, units = 'in', height = height, width = width, res = 1000);
}
else if ('pdf' == extension) {
cairo_pdf(filename = 'temp', height = height, width = width);
}
else if ('svg' == extension) {
svg(filename = 'temp', height = height, width = width);
}
else if ('eps' == extension) {
postscript(height = height, width = width);
}
else {
stop('File type not supported');
}
}
else {
cairo_pdf(filename = 'temp', height = height, width = width);
}
plot(trellis.object);
#### START OF INSIDE LEGEND CODE
### get down to figure viewport
downViewport('plot_01.figure.vp');
### get width of figure and grob respectively
width.fig <- convertUnit(
current.viewport()$width,
unitTo = 'points',
axisFrom = 'x',
typeFrom = 'dimension',
valueOnly = TRUE
);
height.fig <- convertUnit(
current.viewport()$height,
unitTo = 'points',
axisFrom = 'y',
typeFrom = 'dimension',
valueOnly = TRUE
);
### ADD A LITTLE EXTRA TO MAKE GROBS MORE PICKY ABOUT SIZING
height.grob <- convertUnit(
grobHeight(trellis.object$legend$inside$fun),
unitTo = 'points',
axisFrom = 'y',
typeFrom = 'dimension',
valueOnly = TRUE
) * 1.05;
width.grob <- convertUnit(
grobWidth(trellis.object$legend$inside$fun),
unitTo = 'points',
axisFrom = 'x',
typeFrom = 'dimension',
valueOnly = TRUE
) * 1.05;
dev.off();
file.remove('temp');
### convert data into proper form
ret.coords <- do.call(paste0('.', function.name, '.inside.legend'), list(height.fig, width.fig, height.grob, width.grob, extra.parameters));
return(ret.coords);
}
.create.barplot.inside.legend <- function(height.fig, width.fig, height.grob, width.grob, extra.parameters) {
### VALUES FOR POINT DISTRIBUTION
data <- extra.parameters$data;
plot.horizontal <- extra.parameters$plot.horizontal;
formula <- extra.parameters$formula;
groups <- extra.parameters$groups;
stack <- extra.parameters$stack;
ylimits <- extra.parameters$ylimits;
xlimits <- extra.parameters$xlimits;
pass.through.mid <- 1;
pass.through.top <- 100;
value.param <- if (plot.horizontal) {formula[[3]]} else {formula[[2]]}
index.param <- if (plot.horizontal) {formula[[2]]} else {formula[[3]]}
# handle splitting of data cases
if (!is.null(eval(substitute(groups), data, parent.frame())) || stack == TRUE) {
s <- split(data, data[toString(index.param)]);
f <- list();
for (x in 1:length(s)) {
if (stack == TRUE) {
f[[x]] <- sum(s[[x]][toString(value.param)]);
}
else {
f[[x]] <- max(s[[x]][toString(value.param)]);
}
}
data <- f;
}
else {
data <- data[[toString(value.param)]];
}
max.height.val <- list();
min.height.val <- list();
max.width.val <- list();
min.width.val <- list();
### FIGURE OUT WHERE TO PUT THE GROB
grob.y <- height.fig - height.fig * 0.025;
grob.x <- 0 + width.fig * 0.025;
min.x <- width.fig;
min.y <- -1;
min.val <- 100000;
### FIND OPTIMAL PLACEMENT OF GROB
if (!plot.horizontal) {
### GET MAX
if (is.null(ylimits)) {
diff <- max(unlist(data)) - min(unlist(data));
max <- max(unlist(data) + diff * 0.07);
min <- min(unlist(data) - diff * 0.07);
}
else {
max <- ylimits[2];
min <- ylimits[1];
}
### EVALUATE TRUE LOCATION BASED ON POINTS FROM VALUE
points.per.value <- height.fig / (max - min);
points.per.bar <- width.fig / length(data);
### SET LOCATION OF THE MAX AND MIN WIDTHS
for (i in 1:length(data)) {
max.height.val[[i]] <- data[[i]] * points.per.value;
max.width.val[[i]] <- i * points.per.bar;
min.width.val[[i]] <- (i - 1) * points.per.bar;
}
for (y in seq(grob.y, height.grob * 0.975, -3)) {
for (x in seq(grob.x, (width.fig - width.grob) * 0.975, 3)) {
val <- 0;
for (i in 1:length(max.height.val)) {
if (x <= max.width.val[[i]] && (x + width.grob) >= min.width.val[[i]]) {
if (y > max.height.val[[i]] && (y - height.grob) < max.height.val[[i]]) {
val <- val + pass.through.top;
}
else if (y <= max.height.val[[i]] && (y - height.grob) <= max.height.val[[i]]) {
val <- val + pass.through.mid;
}
}
}
if (val < min.val || ( ( (val == 0 && y >= min.y ) || (val != 0 && y <= min.y)) && x <= min.x) && min.val == val) {
min.val <- val;
min.x <- x;
min.y <- y;
}
}
}
}
else {
if (is.null(xlimits)) {
diff <- max(unlist(data)) - min(unlist(data));
max <- max(unlist(data) + diff * 0.07);
min <- min(unlist(data) - diff * 0.07);
}
else {
max <- xlimits[2];
min <- xlimits[1];
}
points.per.value <- width.fig / (max - min);
points.per.bar <- height.fig / length(data);
for (i in 1:length(data)) {
max.width.val[[i]] <- data[[i]] * points.per.value;
max.height.val[[i]] <- height.fig - (i - 1) * points.per.bar;
min.height.val[[i]] <- height.fig - (i) * points.per.bar;
}
max.width.val <- rev(max.width.val);
for (y in seq(grob.y, height.grob * 0.975, -3)) {
for (x in seq(grob.x, (width.fig - width.grob) * 0.975, 3)) {
val <- 0;
for (i in 1:length(max.height.val)) {
if ( (y - width.grob) <= max.height.val[[i]] && (y) >= min.height.val[[i]]) {
if ( (x + width.grob) > max.width.val[[i]] && x < max.width.val[[i]]) {
val <- val + pass.through.top;
}
else if ( (x + width.grob) <= max.width.val[[i]] && x <= max.width.val[[i]]) {
val <- val + pass.through.mid;
}
}
}
if (val < min.val || (y >= min.y && x >= min.x) && min.val == val) {
min.val <- val;
min.x <- x;
min.y <- y;
}
}
}
}
return(c(min.x / width.fig, min.y / height.fig));
}
.create.hexbinplot.inside.legend <- function(height.fig, width.fig, height.grob, width.grob, extra.parameters) {
### GATHER ALL INFO FROM HEXBINPLOT
x <- as.vector(unlist(extra.parameters$x));
y <- as.vector(unlist(extra.parameters$y));
ylimits <- extra.parameters$ylimits;
xlimits <- extra.parameters$xlimits;
### CALCULATE THE MAX VALUES OF X and Y
max.x <- NULL;
min.x <- NULL;
max.y <- NULL;
min.y <- NULL;
if (is.null(xlimits)) {
diff <- max(data$x) - min(data$x);
max.x <- max(unlist(data) + diff * 0.07);
min.x <- min(unlist(data) - diff * 0.07);
}
else {
max.x <- xlimits[2];
min.x <- xlimits[1];
}
if (is.null(ylimits)) {
diff <- max(data$y) - min(data$y);
max.y <- max(unlist(data) + diff * 0.07);
min.y <- min(unlist(data) - diff * 0.07);
}
else {
max.y <- ylimits[2];
min.y <- ylimits[1];
}
### GET AMOUNT OF POINTS PER VALUE
points.per.y <- height.fig / (max.y - min.y);
points.per.x <- width.fig / (max.x - min.x);
grob.y <- height.fig - height.fig * 0.025;
grob.x <- 0 + width.fig * 0.025;
total.crossed <- -1;
ret.x <- 0;
ret.y <- 0;
data <- data.frame(x = x, y = y);
### FIND OPTIMAL PLACEMENT OF GROB
for (y.val in seq(grob.y, height.grob * 0.975, -5)) {
for (x.val in seq(grob.x, (width.fig - width.grob) * 0.975, 5)) {
crossed <- 0;
data.to.use <- subset(data, ( (data$x - min.x) * points.per.x <= (x.val + width.grob) ) & ( (data$x - min.x) * points.per.x >= x.val) &
( (data$y - min.y) * points.per.y <= y.val) & ( (data$y - min.y) * points.per.y >= (y.val - height.grob) ) );
crossed <- nrow(data.to.use);
if (total.crossed == -1 || (crossed < total.crossed || (y.val >= ret.y && x.val >= ret.x) && crossed == total.crossed)) {
total.crossed <- crossed;
ret.x <- x.val;
ret.y <- y.val;
}
}
}
return(c(ret.x / width.fig, ret.y / height.fig));
}
.create.densityplot.inside.legend <- function(height.fig, width.fig, height.grob, width.grob, extra.parameters) {
### GET DATA FROM DENSITY PLOT
data <- extra.parameters$data;
ylimits <- extra.parameters$ylimits;
xlimits <- extra.parameters$xlimits;
### FIND MAX AND MIN VALUES
max.x <- NULL;
min.x <- NULL;
max.y <- NULL;
min.y <- NULL;
if (is.null(xlimits)) {
diff <- max(data$x) - min(data$x);
max.x <- max(unlist(data) + diff * 0.07);
min.x <- min(unlist(data) - diff * 0.07);
}
else {
max.x <- xlimits[2];
min.x <- xlimits[1];
}
if (is.null(ylimits)) {
diff <- max(data$y) - min(data$y);
max.y <- max(unlist(data) + diff * 0.07);
min.y <- min(unlist(data) - diff * 0.07);
}
else {
max.y <- ylimits[2];
min.y <- ylimits[1];
}
### POINTS PER VALUE IN PLOT
points.per.y <- height.fig / (max.y - min.y);
points.per.x <- width.fig / (max.x - min.x);
grob.y <- height.fig - height.fig * 0.025;
grob.x <- 0 + width.fig * 0.025;
total.crossed <- -1;
ret.x <- 0;
ret.y <- 0;
x.vals <- unlist(data[1]);
y.vals <- unlist(data[2]);
### FIND OPTIMAL PLACEMENT OF GROB
for (y in seq(grob.y, height.grob * 0.975, -5)) {
for (x in seq(grob.x, (width.fig - width.grob) * 0.975, 5)) {
crossed <- 0;
for (i in 1:nrow(data)) {
if ( (x.vals[i] - min.x) * points.per.x <= ( x + width.grob ) && (x.vals[i] - min.x) * points.per.x >= x &&
( y.vals[i] - min.y ) * points.per.y <= y && ( y.vals[i] - min.y ) * points.per.y >= ( y - height.grob )) {
crossed <- crossed + 1;
}
}
if (total.crossed == -1 || (crossed < total.crossed || ( y >= ret.y && x >= ret.x ) && crossed == total.crossed)) {
total.crossed <- crossed;
ret.x <- x;
ret.y <- y;
}
}
}
return(c(ret.x / width.fig, ret.y / height.fig));
}
.create.histogram.inside.legend <- function(height.fig, width.fig, height.grob, width.grob, extra.parameters) {
### VALUES FOR POINT DISTRIBUTION
data <- extra.parameters$x;
ylimits <- extra.parameters$ylimits;
xlimits <- extra.parameters$xlimits;
breaks <- extra.parameters$breaks;
nint <- extra.parameters$nint;
type <- extra.parameters$type;
## convert to proper format
bar.locations.min <- c();
bar.locations.max <- c();
### GET MAX AND MIN VALUES
max.x <- NULL;
min.x <- NULL;
max.y <- NULL;
min.y <- NULL;
if (is.null(xlimits)) {
diff <- max(data) - min(data);
max.x <- max(unlist(data) + diff * 0.07);
min.x <- min(unlist(data) - diff * 0.07);
}
else {
max.x <- xlimits[2];
min.x <- xlimits[1];
}
if (!is.null(breaks)) {
bar.locations.min <- c(min.x, breaks);
bar.locations.max <- c(breaks, max.x);
}
else {
breaks <- do.breaks(range(data, finite = TRUE), nint);
bar.locations.min <- breaks[1:length(breaks) - 1];
bar.locations.max <- breaks[2:length(breaks)];
}
### ADJUST BASED ON HISTOGRAM TYPE
if (type == 'percent') {
counts <- 100 * do.call('hist', list(x = data, plot = FALSE, breaks = breaks))$counts / length(data);
}
else if (type == 'count') {
counts <- do.call('hist', list(x = data, plot = FALSE, breaks = breaks))$counts;
}
else if (type == 'density') {
counts <- do.call('hist', list(x = data, plot = FALSE, breaks = breaks))$density;
}
if (is.null(ylimits)) {
diff <- max(counts);
max.y <- max(counts + diff * 0.07);
min.y <- min(0 - diff * 0.07);
}
else {
max.y <- ylimits[2];
min.y <- ylimits[1];
}
### GET POINTS PER EACH VALUE
points.per.y <- height.fig / (max.y - min.y);
points.per.x <- width.fig / (max.x - min.x);
pass.through.mid <- 1;
pass.through.top <- 100;
bar.locations.min <- (bar.locations.min - min.x) * points.per.x;
bar.locations.max <- (bar.locations.max - min.x) * points.per.x;
counts <- (counts - min.y) * points.per.y;
### FIGURE OUT WHERE TO PUT THE GROB
grob.y <- height.fig - height.fig * 0.025;
grob.x <- 0 + width.fig * 0.025;
x.ret.val <- width.fig;
y.ret.val <- -1;
min.val <- 100000;
for (y.val in seq(grob.y, height.grob * 0.975, -3)) {
for (x.val in seq(grob.x, (width.fig - width.grob) * 0.975, 3)) {
val <- 0;
for (i in 1:length(counts)) {
if ( (y.val - height.grob) <= counts[i] && (y.val) >= 0) {
if ( (x.val + width.grob) > bar.locations.min[i] && x.val < bar.locations.max[i]) {
val <- val + pass.through.top;
}
else if ( (x.val + width.grob) <= bar.locations.max[i] && x.val <= bar.locations.max[i]) {
val <- val + pass.through.mid;
}
}
}
if (val < min.val || (y.val >= y.ret.val && x.val <= x.ret.val) && min.val == val) {
min.val <- val;
x.ret.val <- x.val;
y.ret.val <- y.val;
}
}
}
return(c(x.ret.val / width.fig, y.ret.val / height.fig));
}
.create.polygonplot.inside.legend <- function(height.fig, width.fig, height.grob, width.grob, extra.parameters) {
### GET DATA FROM POLYGON PLOT
data <- extra.parameters$data;
formula <- extra.parameters$formula;
ylimits <- extra.parameters$ylimits;
xlimits <- extra.parameters$xlimits;
extra.points <- extra.parameters$extra.points;
max.vals <- extra.parameters$max;
min.vals <- extra.parameters$min;
### GET MAX AND MIN VALUES OF PLOT
max.x <- NULL;
min.x <- NULL;
max.y <- NULL;
min.y <- NULL;
x.data <- unlist(data[toString(formula[[3]])]);
if (is.null(xlimits)) {
diff <- max(x.data) - min(x.data);
max.x <- max(x.data + diff * 0.07);
min.x <- min(x.data - diff * 0.07);
}
else {
max.x <- xlimits[2];
min.x <- xlimits[1];
}
if (is.null(ylimits)) {
diff <- max(max.vals) - min(min.vals);
max.y <- max(max.vals + diff * 0.07);
min.y <- min(min.vals - diff * 0.07);
}
else {
max.y <- ylimits[2];
min.y <- ylimits[1];
}
### GET POINTS PER EACH VALUE IN PLOT
points.per.y <- height.fig / (max.y - min.y);
points.per.x <- width.fig / (max.x - min.x);
grob.y <- height.fig - height.fig * 0.025;
grob.x <- 0 + width.fig * 0.025;
total.crossed <- -1;
ret.x <- 0;
ret.y <- 0;
x.data <- as.vector(x.data);
names(data) <- c('x', 'max', 'min');
if (!is.null(extra.points)) {
extra.points <- as.data.frame(extra.points);
}
### FIND OPTIMAL PLACEMENT OF GROB
for (y.val in seq(grob.y, height.grob * 0.975, -5)) {
for (x.val in seq(grob.x, (width.fig - width.grob) * 0.975, 5)) {
crossed <- 0;
data.to.use.polygon <- subset(data, ( (x.data - min.x) * points.per.x <= (x.val + width.grob)) & ( (x.data - min.x) * points.per.x >= x.val) &
( ( (min.vals - min.y) * points.per.y <= y.val) & ( (min.vals - min.y) * points.per.y >= (y.val - height.grob)) |
( (max.vals - min.y) * points.per.y <= y.val) & ( (max.vals - min.y) * points.per.y >= (y.val - height.grob))));
if (!is.null(extra.points)) {
data.to.use.extra.points <- subset(extra.points, ( (extra.points$x - min.x) * points.per.x <= (x.val + width.grob)) &
( (extra.points$x - min.x) * points.per.x >= x.val) & ( (extra.points$y - min.y) * points.per.y <= y.val) &
( (extra.points$y - min.y) * points.per.y >= (y.val - height.grob)));
crossed <- nrow(data.to.use.polygon) + nrow(data.to.use.extra.points);
}
else {
crossed <- nrow(data.to.use.polygon);
}
if (total.crossed == -1 || (crossed < total.crossed || (y.val >= ret.y && x.val >= ret.x) && crossed == total.crossed)) {
total.crossed <- crossed;
ret.x <- x.val;
ret.y <- y.val;
}
}
}
return(c(ret.x / width.fig, ret.y / height.fig));
}
.create.manhattanplot.inside.legend <- function(height.fig, width.fig, height.grob, width.grob, extra.parameters) {
### GET DATA FROM MANHATTAN PLOT
x <- as.vector(unlist(extra.parameters$x));
y <- as.vector(unlist(extra.parameters$y));
ylimits <- extra.parameters$ylimits;
xlimits <- extra.parameters$xlimits;
### GET MINIMUM AND MAXIMUM VALUES OF PLOT
max.x <- NULL;
min.x <- NULL;
max.y <- NULL;
min.y <- NULL;
if (is.null(xlimits)) {
diff <- max(x) - min(x);
max.x <- max(x + diff * 0.07);
min.x <- min(x - diff * 0.07);
}
else {
max.x <- xlimits[2];
min.x <- xlimits[1];
}
if (is.null(ylimits)) {
diff <- max(y) - min(y);
max.y <- max(y + diff * 0.07);
min.y <- min(y - diff * 0.07);
}
else {
max.y <- ylimits[2];
min.y <- ylimits[1];
}
### GET AMOUNT OF POINTS PER VALUE OF PLOT
points.per.y <- height.fig / (max.y - min.y);
points.per.x <- width.fig / (max.x - min.x);
grob.y <- height.fig - height.fig * 0.025;
grob.x <- 0 + width.fig * 0.025;
total.crossed <- -1;
ret.x <- 0;
ret.y <- 0;
data <- data.frame(x = x, y = y);
### FIND OPTIMAL PLACEMENT OF GROB
for (y.val in seq(grob.y, height.grob * 0.975, -5)) {
for (x.val in seq(grob.x, (width.fig - width.grob) * 0.975, 5)) {
data.to.use <- subset(data, ( (data$x - min.x) * points.per.x <= (x.val + width.grob)) & ( (data$x - min.x) * points.per.x >= x.val) &
( (data$y - min.y) * points.per.y <= y.val) & ( (data$y - min.y) * points.per.y >= (y.val - height.grob)));
crossed <- nrow(data.to.use);
if (total.crossed == -1 || crossed < total.crossed) {
total.crossed <- crossed;
ret.x <- x.val;
ret.y <- y.val;
}
}
}
return(c(ret.x / width.fig, ret.y / height.fig));
}
.create.qqplot.comparison.inside.legend <- function(height.fig, width.fig, height.grob, width.grob, extra.parameters) {
### GET VALUES FROM QQ COMPARISON PLOT
x <- as.vector(unlist(extra.parameters$x));
y <- as.vector(unlist(extra.parameters$y));
ylimits <- extra.parameters$ylimits;
xlimits <- extra.parameters$xlimits;
### GET MAX AND MIN VALUES OF THE PLOT
max.x <- NULL;
min.x <- NULL;
max.y <- NULL;
min.y <- NULL;
if (is.null(xlimits)) {
diff <- max(x) - min(x);
max.x <- max(x + diff * 0.07);
min.x <- min(x - diff * 0.07);
}
else {
max.x <- xlimits[2];
min.x <- xlimits[1];
}
if (is.null(ylimits)) {
diff <- max(y) - min(y);
max.y <- max(y + diff * 0.07);
min.y <- min(y - diff * 0.07);
}
else {
max.y <- ylimits[2];
min.y <- ylimits[1];
}
### GET NUMBER OF POINTS PER VALUE OF PLOT
points.per.y <- height.fig / (max.y - min.y);
points.per.x <- width.fig / (max.x - min.x);
grob.y <- height.fig - height.fig * 0.025;
grob.x <- 0 + width.fig * 0.025;
total.crossed <- -1;
ret.x <- 0;
ret.y <- 0;
data <- data.frame(x = x, y = y);
### FIND OPTIMAL PLACEMENT OF THE GROB
for (y.val in seq(grob.y, height.grob * 0.975, -5)) {
for (x.val in seq(grob.x, (width.fig - width.grob) * 0.975, 5)) {
data.to.use <- subset(data, ( (data$x - min.x) * points.per.x <= (x.val + width.grob)) & ( (data$x - min.x) * points.per.x >= x.val) &
( (data$y - min.y) * points.per.y <= y.val) & ( (data$y - min.y) * points.per.y >= (y.val - height.grob)));
crossed <- nrow(data.to.use);
if (total.crossed == -1 || crossed < total.crossed) {
total.crossed <- crossed;
ret.x <- x.val;
ret.y <- y.val;
}
}
}
return(c(ret.x / width.fig, ret.y / height.fig));
}
.create.qqplot.fit.inside.legend <- function(height.fig, width.fig, height.grob, width.grob, extra.parameters) {
### GET VALUES FROM QQ PLOT FIT
y <- as.vector(unlist(extra.parameters$x));
ylimits <- extra.parameters$ylimits;
xlimits <- extra.parameters$xlimits;
n.data <- length(y);
y <- sort(y);
x <- c();
for ( i in 1:n.data) {
x <- c(x, i / n.data);
}
### GET MIN AND MAX VALUE OF THE PLOT
max.x <- NULL;
min.x <- NULL;
max.y <- NULL;
min.y <- NULL;
if (is.null(xlimits)) {
diff <- max(x) - min(x);
max.x <- max(x + diff * 0.07);
min.x <- min(x - diff * 0.07);
}
else {
max.x <- xlimits[2];
min.x <- xlimits[1];
}
if (is.null(ylimits)) {
diff <- max(y) - min(y);
max.y <- max(y + diff * 0.07);
min.y <- min(y - diff * 0.07);
}
else {
max.y <- ylimits[2];
min.y <- ylimits[1];
}
### NUMBER OF POINTS PER VALUE OF THE PLOT
points.per.y <- height.fig / (max.y - min.y);
points.per.x <- width.fig / (max.x - min.x);
grob.y <- height.fig - height.fig * 0.025;
grob.x <- 0 + width.fig * 0.025;
total.crossed <- -1;
ret.x <- 0;
ret.y <- 0;
data <- data.frame(x = x, y = y);
### FIND OPTIMAL PLACE FOR THE GROB
for (y.val in seq(grob.y, height.grob * 0.975, -5)) {
for (x.val in seq(grob.x, (width.fig - width.grob) * 0.975, 5)) {
data.to.use <- subset(data, ( (data$x - min.x) * points.per.x <= (x.val + width.grob)) & ( (data$x - min.x) * points.per.x >= x.val) &
( (data$y - min.y) * points.per.y <= y.val) & ( (data$y - min.y) * points.per.y >= (y.val - height.grob)));
crossed <- nrow(data.to.use);
if (total.crossed == -1 || crossed < total.crossed) {
total.crossed <- crossed;
ret.x <- x.val;
ret.y <- y.val;
}
}
}
return(c(ret.x / width.fig, ret.y / height.fig));
}
.create.segplot.inside.legend <- function(height.fig, width.fig, height.grob, width.grob, extra.parameters) {
### GET VALUES FROM SEGPLOT
min.vals <- as.vector(unlist(extra.parameters$x));
max.vals <- as.vector(unlist(extra.parameters$y));
y <- c(1:length(min.vals));
ylimits <- extra.parameters$ylimits;
xlimits <- extra.parameters$xlimits;
### GET MIN AND MAX VALUE OF PLOT
max.x <- NULL;
min.x <- NULL;
max.y <- NULL;
min.y <- NULL;
if (is.null(xlimits) || !is.numeric(xlimits)) {
diff <- max(max.vals) - min(min.vals);
max.x <- max(max.vals + diff * 0.07);
min.x <- min(min.vals - diff * 0.07);
}
else {
max.x <- xlimits[2];
min.x <- xlimits[1];
}
if (is.null(ylimits) || !is.numeric(ylimits)) {
diff <- max(y) - min(y);
max.y <- max(y + diff * 0.07);
min.y <- min(y - diff * 0.07);
}
else {
max.y <- ylimits[2];
min.y <- ylimits[1];
}
### NUMBER OF POINTS PER VALUE IN PLOT
points.per.y <- height.fig / (max.y - min.y);
points.per.x <- width.fig / (max.x - min.x);
grob.y <- height.fig - height.fig * 0.025;
grob.x <- 0 + width.fig * 0.025;
total.crossed <- -1;
ret.x <- 0;
ret.y <- 0;
data <- data.frame(min.vals = min.vals, max.vals = max.vals, y = y);
### FIND OPTIMAL GROB PLACEMENT
for (y.val in seq(grob.y, height.grob * 0.975, -5)) {
for (x.val in seq(grob.x, (width.fig - width.grob) * 0.975, 5)) {
data.to.use <- subset(data, ( (data$min.vals - min.x) * points.per.x <= (x.val + width.grob)) &
( (data$max.vals - min.x) * points.per.x >= (x.val)) &
( (data$y - min.y) * points.per.y <= y.val) & ( (data$y - min.y) * points.per.y >= (y.val - height.grob)));
crossed <- nrow(data.to.use);
if (total.crossed == -1 || (crossed < total.crossed || (y.val >= ret.y && x.val >= ret.x) && crossed == total.crossed)) {
total.crossed <- crossed;
ret.x <- x.val;
ret.y <- y.val;
}
}
}
return(c(ret.x / width.fig, ret.y / height.fig));
}
.create.stripplot.inside.legend <- function(height.fig, width.fig, height.grob, width.grob, extra.parameters) {
### GET VALUES FROM STRIPPLOT
horizontal <- extra.parameters$horizontal;
x <- unlist(extra.parameters$x);
y <- unlist(extra.parameters$y);
ylimits <- extra.parameters$ylimits;
xlimits <- extra.parameters$xlimits;
unique.vals <- NULL;
### HANDLE HORIZONTAL CASES AND FIND UNIQUE VALUES FOR ROWS
if (horizontal) {
if (is.null(levels(y))) {
unique.vals <- as.character(unique(y));
}
else {
unique.vals <- as.character(levels(y));
}
y <- as.character(y);
for (i in 1:length(unique.vals) ) {
y[as.character(y) == unique.vals[i]] <- as.character(i);
}
y <- as.integer(y);
}
else {
if (is.null(levels(x))) {
unique.vals <- as.character(unique(x));
}
else {
unique.vals <- as.character(levels(x));
}
x <- as.character(x);
for ( i in 1:length(unique.vals) ) {
x[as.character(x) == unique.vals[i]] <- as.character(i);
}
x <- as.integer(x);
}
### GET THE IMN AND MAX VALUES OF PLOT
max.x <- NULL;
min.x <- NULL;
max.y <- NULL;
min.y <- NULL;
if (is.null(xlimits) || !is.numeric(xlimits)) {
diff <- max(x) - min(x);
max.x <- max(x + diff * 0.07);
min.x <- min(x - diff * 0.07);
}
else {
max.x <- xlimits[2];
min.x <- xlimits[1];
}
if (is.null(ylimits) || !is.numeric(ylimits)) {
diff <- max(y) - min(y);
max.y <- max(y + diff * 0.07);
min.y <- min(y - diff * 0.07);
}
else {
max.y <- ylimits[2];
min.y <- ylimits[1];
}
### POINTS PER VALUE OF PLOT
points.per.y <- height.fig / (max.y - min.y);
points.per.x <- width.fig / (max.x - min.x);
grob.y <- height.fig - height.fig * 0.025;
grob.x <- 0 + width.fig * 0.025;
total.crossed <- -1;
ret.x <- 0;
ret.y <- 0;
data <- data.frame(x = x, y = y);
for (y.val in seq(grob.y, height.grob * 0.975, -5)) {
for (x.val in seq(grob.x, (width.fig - width.grob) * 0.975, 5)) {
data.to.use <- subset(data, ( (data$x - min.x) * points.per.x <= (x.val + width.grob)) & ( (data$x - min.x) * points.per.x >= x.val) &
( (data$y - min.y) * points.per.y <= y.val) & ( (data$y - min.y) * points.per.y >= (y.val - height.grob)));
crossed <- nrow(data.to.use);
if (total.crossed == -1 || (crossed < total.crossed || (y.val >= ret.y && x.val >= ret.x) && crossed == total.crossed)) {
total.crossed <- crossed;
ret.x <- x.val;
ret.y <- y.val;
}
}
}
return(c(ret.x / width.fig, ret.y / height.fig));
}
.create.scatterplot.inside.legend <- function(height.fig, width.fig, height.grob, width.grob, extra.parameters) {
data <- extra.parameters$data;
formula <- extra.parameters$formula;
ylimits <- extra.parameters$ylimits;
xlimits <- extra.parameters$xlimits;
max.x <- NULL;
min.x <- NULL;
max.y <- NULL;
min.y <- NULL;
x.data <- unlist(data[toString(formula[[3]])]);
y.data <- unlist(data[toString(formula[[2]])]);
if (is.null(xlimits)) {
diff <- max(x.data) - min(x.data);
max.x <- max(x.data + diff * 0.07);
min.x <- min(x.data - diff * 0.07);
}
else {
max.x <- xlimits[2];
min.x <- xlimits[1];
}
if (is.null(ylimits)) {
diff <- max(y.data) - min(y.data);
max.y <- max(y.data + diff * 0.07);
min.y <- min(y.data - diff * 0.07);
}
else {
max.y <- ylimits[2];
min.y <- ylimits[1];
}
points.per.y <- height.fig / (max.y - min.y);
points.per.x <- width.fig / (max.x - min.x);
grob.y <- height.fig - height.fig * 0.025;
grob.x <- 0 + width.fig * 0.025;
total.crossed <- -1;
ret.x <- 0;
ret.y <- 0;
names(data) <- c(toString(formula[[3]]), toString(formula[[2]]));
for (y.val in seq(grob.y, height.grob * 0.975, -5)) {
for (x.val in seq(grob.x, (width.fig - width.grob) * 0.975, 5)) {
data.to.use <- subset(data, ( (data$x - min.x) * points.per.x <= (x.val + width.grob)) & ( (data$x - min.x) * points.per.x >= x.val) &
( (data$y - min.y) * points.per.y <= y.val) & ( (data$y - min.y) * points.per.y >= (y.val - height.grob)));
crossed <- nrow(data.to.use);
if (total.crossed == -1 || (crossed < total.crossed || (y.val >= ret.y && x.val >= ret.x) && crossed == total.crossed)) {
total.crossed <- crossed;
ret.x <- x.val;
ret.y <- y.val;
}
}
}
return(c(ret.x / width.fig, ret.y / height.fig));
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/inside.auto.legend.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO CREATE A LEGEND GROB ###############################################################
legend.grob <- function(
legends, label.cex = 1, title.cex = 1, title.just = 'centre', title.fontface = 'bold',
font.family = NULL, size = 3, border = NULL, border.padding = 1, layout = c(1, length(legends)),
between.col = 1, between.row = 1, use.legacy.settings = FALSE, x = 0.5, y = 0.5, background.col = 'white', background.alpha = 0
) {
# NOTE: calls to 'draw.key' may open a device for drawing (even with 'draw = FALSE' set)
# As far as I can tell, draw.key opens a new device only if no devices are open already
# The current solution is to call dev.off() at the end of the function, but only if
# no devices were open to start (ie. the open device was created by draw.key)
# This prevents erroneously closing a device that the user had opened prior to calling
# the function
# Check if any devices are open when the function is called
# If not, the device created by draw.key will be closed at the end of the function call
devices.open <- FALSE;
if (length(dev.list()) > 0) {
devices.open <- TRUE;
}
legend.grob.final <- NULL;
if (length(legends) > 0) {
if (is.null(font.family)) {
font.family <- BoutrosLab.plotting.general::get.defaults(property = 'fontfamily', use.legacy.settings = use.legacy.settings);
}
num.legends <- length(legends);
# If user-specified layout is not the right size, use a default layout
if (layout[1] * layout[2] < num.legends) {
warning('User-specified legend layout is not large enough. Using default layout.');
layout <- c(1, num.legends);
}
# Create a layout for the legends
# Each legend gets an extra row for its title
# There is also an extra empty row/column inserted between each of the legends to allow for nicer spacing
row.buffer <- 3;
col.buffer <- 2;
legend.layout <- grid.layout(
ncol = layout[1] * col.buffer - 1,
nrow = layout[2] * row.buffer - 1,
heights = unit(
c(0, 0, rep(c(between.row, 0, 0), layout[2] - 1)),
c(rep('lines', layout[2] * row.buffer - 1))
),
widths = unit(
c(rep(c(0, between.col), layout[1] - 1), 0),
c(rep('lines', layout[1] * col.buffer - 1))
)
);
# Create a frame using this layout
legend.grob.final <- frameGrob(layout = legend.layout, gp = gpar(fill = 'black', alpha = 1));
legend.grob.final <- placeGrob(legend.grob.final,
rectGrob(gp =
gpar(fill = background.col,
col = background.col,
alpha = background.alpha)),
row = NULL, col = NULL);
# Create each legend
for (i in 1:num.legends) {
legendi <- legends[[i]];
typei <- names(legends)[i];
if (is.null(legendi[['continuous.amount']])) {
legendi[['continuous.amount']] <- 100;
}
# Figure out where this legend should go in the layout (ordered row-wise)
legend.row <- if (i %% layout[1] == 0) { i / layout[1] } else { floor(i / layout[1]) + 1 }
legend.col <- if (i %% layout[1] == 0) { layout[1] } else { i %% layout[1] }
# Create the title of this legend
if (!is.null(legendi[['title']])) {
# Draw a grob representing the title
title.x.coord <- 0.5;
if ('left' == title.just) {
title.x.coord <- 0;
}
else if ('right' == title.just) {
title.x.coord <- 1;
}
title.grob <- textGrob(
label = legendi[['title']],
just = c(title.just, 'top'),
x = title.x.coord,
y = 1,
gp = gpar(
cex = title.cex,
fontface = title.fontface,
fontfamily = font.family
)
);
# Get the height of this grob so we can add white space around it
title.grob.height <- convertHeight(
grobHeight(title.grob),
unitTo = 'lines',
valueOnly = TRUE
);
# Add the title to the frame
legend.grob.final <- packGrob(
frame = legend.grob.final,
grob = title.grob,
row = row.buffer * (legend.row - 1) + 1,
col = col.buffer * (legend.col - 1) + 1,
height = max(
legend.grob.final$framevp$layout$heights[row.buffer * (legend.row - 1) + 1],
unit(title.grob.height + 0.4, 'lines')
),
force.height = TRUE,
);
}
# Create a key describing the content of the legend
# The first column is the coloured shapes and
# the second column is the corresponding text labels
if (!is.null(legendi[['continuous']]) && legendi[['continuous']] == TRUE) {
legendi[['height']] <- if (is.null(legendi[['height']])) { 2 } else { legendi[['height']] };
legendi[['width']] <- if (is.null(legendi[['width']])) { 2 } else { legendi[['width']] };
colorRamp <- colorRampPalette(legendi[['colours']]);
labels.at <- legendi[['at']];
if (!is.null(legendi[['labels']]) && (is.null(labels.at))) {
n.labels <- length(legendi[['labels']]);
# Uses 0-100% as a default range
max.value <- if (!is.null(legendi[['continuous.amount']])) legendi[['continuous.amount']] else 100;
boundaries <- seq(0, max.value, length.out = n.labels + 1);
labels.at <- sapply(
1:(length(boundaries) - 1),
FUN = function(i) boundaries[i] + (boundaries[i + 1] - boundaries[i]) / 2
);
}
legend.key <- list(
space = if (!is.null(legendi[['angle']]) && legendi[['angle']] != 0) { 'bottom' } else { 'right' },
between = 0.5,
rep = TRUE,
just = c('left', 'top'),
tick.number = if (is.null(legendi[['tck.number']])) { 0 } else { legendi[['tck.number']] },
tck = if (is.null(legendi[['tck']])) { 0 } else { legendi[['tck']] },
at = do.breaks(c(0, legendi[['continuous.amount']]), legendi[['continuous.amount']]),
col = colorRamp,
width = if (!is.null(legendi[['angle']]) && legendi[['angle']] != 0) { legendi[['height']] } else { legendi[['width']] },
labels = list(
labels = if (is.null(legendi[['labels']])) { c('') } else { legendi[['labels']] },
at = labels.at,
cex = if (is.null(legendi[['cex']])) { 0.8 } else { legendi[['cex']] },
rot = if (is.null(legendi[['labels.rot']])) { 0 } else { legendi[['labels.rot']] }
)
);
color.key.grob <- draw.colorkey(
key = legend.key,
draw = FALSE
);
# adjust justification to line up with key style legends
color.key.grob$framevp$layout$valid.just <- c(0,1);
color.key.grob$framevp$valid.just <- c(0,0.5);
# need padding to line up with key style legends
color.key.grob$framevp$x <- unit(0,'npc') + unit(1.69,'points');
# set sizes
color.key.grob$framevp$height <- unit(legendi[['height']], 'lines');
color.key.grob$framevp$width <- unit(legendi[['width']], 'lines');
if (!is.null(legendi[['pos.x']])) { color.key.grob$framevp$x <- unit(legendi[['pos.x']],'npc'); }
if (!is.null(legendi[['pos.y']])) { color.key.grob$framevp$y <- unit(legendi[['pos.y']],'npc'); }
# Add the legend to the frame
legend.grob.final <- packGrob(
frame = legend.grob.final,
grob = color.key.grob,
row = row.buffer * (legend.row - 1) + 2,
col = col.buffer * (legend.col - 1) + 1,
height = max(
unit(legendi[['height']], 'lines'),
legend.grob.final$framevp$layout$heights[row.buffer * (legend.row - 1) + 1]
),
force.height = TRUE,
);
}
else {
legend.key <- list(
just = c('left', 'top'),
between = 0.5,
rep = FALSE
);
if (typei %in% c('rect', 'legend')) {
legend.key$rectangles <- list(
col = legendi[['colours']],
size = if (is.null(legendi[['size']])) { size } else { legendi[['size']] },
height = 1,
border = legendi[['border']]
);
} else if ('point' == typei) {
legend.key$points <- list(
col = if (!is.null(legendi[['col']])) { legendi[['col']] } else { legendi[['colours']] },
cex = if (is.null(legendi[['cex']])) { size } else { legendi[['cex']] },
fill = legendi[['fill']],
pch = if (is.null(legendi[['pch']])) { 19 } else { legendi[['pch']] }
);
# Add extra row spacing for points by default
legend.key$padding.text <- legend.key$points$cex * 2;
} else {
stop('type ', typei, ' unknown');
}
if (!is.null(legendi[['padding.text']])) {
legend.key$padding.text <- legendi[['padding.text']];
}
legend.key$text = list(
legendi[['labels']],
cex = label.cex,
fontfamily = font.family
);
# Add the legend to the frame
legend.grob.final <- packGrob(
frame = legend.grob.final,
grob = draw.key(key = legend.key, draw = FALSE),
row = row.buffer * (legend.row - 1) + 2,
col = col.buffer * (legend.col - 1) + 1
);
}
}
# Draw border if specified
if (!is.null(border)) {
if (!is.list(border)) {
stop('Argument border of legend.grob must be a list.');
}
border[['fill']] <- 'transparent';
# Calculate the width and height of the legend
legend.grob.width <- convertWidth(
grobWidth(legend.grob.final),
unitTo = 'lines',
valueOnly = TRUE
);
legend.grob.height <- convertHeight(
grobHeight(legend.grob.final),
unitTo = 'lines',
valueOnly = TRUE
);
# Create new grid grob to hold centered legend with border
border.layout <- grid.layout(
nrow = 1,
ncol = 1,
widths = unit(legend.grob.width + border.padding, 'lines'),
heights = unit(legend.grob.height + border.padding, 'lines')
);
border.grob <- frameGrob(layout = border.layout);
# Place legend grob
border.grob <- placeGrob(
frame = border.grob,
grob = legend.grob.final,
row = 1,
col = 1
);
# Add border
border.grob <- placeGrob(
frame = border.grob,
grob = rectGrob(
gp = do.call(gpar, border)
),
row = NULL,
col = NULL
);
# Update return object
legend.grob.final <- border.grob;
}
# Close the device if it was created by draw.key
if (!devices.open) {
dev.off();
# Remove the empty Rplots.pdf file if one was created (non-interactive)
if (file.exists('Rplots.pdf')) {
unlink('Rplots.pdf');
}
}
}
# set x and y coordinates
legend.grob.final$framevp$y <- unit(y, 'npc');
legend.grob.final$framevp$x <- unit(x, 'npc');
return(legend.grob.final);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/legend.grob.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2012 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO PARSE FORMULAS ####################################################################
parse.formula <- function(formula) {
# In written order of original formula
unlist(strsplit(deparse(formula), ' [~|] '));
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/parse.formula.R
|
### pcawg.colours.R #########################################################################
#
# Authors:
# Jennifer Aguiar
# Constance Li ([email protected])
# Nathaniel Schmitz ([email protected])
#
### DESCRIPTION ####################################################################################
#
# Return standard PCAWG colour palettes. Case insensitive.
#
# To see all available schemes, set: scheme='all', return.scheme = FALSE
# To return all full schemes, set: scheme='all', return.scheme = TRUE
# To return specific full schemes, set: scheme=<wanted scheme>, return.scheme = TRUE
# Note: x will be ignored when scheme='all' OR return.scheme = TRUE
# To return colours for specific values,
### ARGUMENTS ######################################################################################
# x Chracter vector with terms to be mapped to colours. Ignored if scheme='all' or
# return.scheme=TRUE
# scheme String specifying desired colour scheme. To see all available schemes, use
# scheme='all', returns.scheme=FALSE
# fill.colour Unrecognized output will be filled with this colour. Default to 'slategrey'
# return.scheme TRUE/FALSE. Set to true to return full specified scheme. Set to false to map
# x to colours
#
### MAIN ###########################################################################################
pcawg.colours <- function(
x = NULL,
scheme = NULL,
fill.colour = 'slategrey',
return.scheme = FALSE
) {
# Define all colours
# Coding SNV mutation subtypes & consequences
nonsynonymous <- '#698B69';
synonymous <- '#FFD700';
stop.gain <- '#8B4789';
stop.loss <- '#DA70D6';
indel.frameshift <- '#FF8C00';
indel.nonframeshift <- '#003366';
splicing <- '#00CED1';
# Non-coding SNV mutation subtypes, consequences & gene types
non.coding <- '#A80015';
promoter <- '#4C191E';
enhancer <- '#7F000F';
operator <- '#A84955';
silencer <- '#E78A96';
insulator <- '#FFC1C9';
lnc.rna <- '#331900';
snc.rna <- '#594027';
t.rna <- '#A87849';
r.rna <- '#E7B98A';
mi.rna <- '#FFE0C1';
utr5.utr3 <- '#1A1A1A';
intronic <- '#4D4D4D';
intergenic <- '#7F7F7F';
telomeres <- '#B3B3B3';
# Structral variant mutation subtypes
cna.gain <- '#FF0000';
cna.loss <- '#0000FF';
inversion <- '#FFA500';
transposition <- '#7300E7';
translocation <- '#458B00';
insertion <- '#1BE7FF';
# Chromosomes
chr1 <- '#DE47AB';
chr2 <- '#72BE97';
chr3 <- '#F7F797';
chr4 <- '#7C749B';
chr5 <- '#E85726';
chr6 <- '#B395F8';
chr7 <- '#DC8747';
chr8 <- '#96D53D';
chr9 <- '#DC85EE';
chr10 <- '#7D32B3';
chr11 <- '#88DB68';
chr12 <- '#78AAF1';
chr13 <- '#D9C6CA';
chr14 <- '#336C80';
chr15 <- '#F7CA44';
chr16 <- '#32C7C7';
chr17 <- '#D4C5F2';
chr18 <- '#995493';
chr19 <- '#F88B78';
chr20 <- '#475ECC';
chr21 <- '#E0BD8C';
chr22 <- '#9E2800';
chrx <- '#F2BBD2';
chry <- '#B6EBEA';
# Sex
male <- '#B6EBEA';
female <- '#F2BBD2';
# Tumour stage;
st.one <- '#FFFFFF';
st.two <- '#FFFF00';
st.three <- '#FFA500';
st.four <- '#FF0000';
st.one.two <- '#FFE4B5';
st.one.three <- '#EEE8AA';
st.two.one <- '#FFD700';
st.two.three <- '#F4A460';
# TNM Cat
tnm.zero <- '#FFFFFF';
tn.one <- '#FFD399';
tn.two <- '#FFAE45';
tn.three <- '#B87217';
tn.four <- '#774607';
m.one <- '#000000';
tnm.x <- '#708090';
# Grade
gr.one <- '#FFFFFF';
gr.two <- '#9CF0FC';
gr.three <- '#335FE5';
gr.four <- '#003366';
gr.well <- '#FFFFFF';
gr.mod <- '#9CE750';
gr.poor <- '#00CC00';
gr.un <- '#005900';
pr.three.three <- '#FFFFFF';
pr.three.four <- '#FFFF00';
pr.three.five <- '#CD2990';
pr.four.three <- '#FFA500';
pr.four.four <- '#FF0000';
pr.four.five <- '#A52A2A';
pr.five.three <- '#8B008B';
pr.five.four <- '#0000CD';
pr.five.five <- '#000000';
# Primary or Met
primary <- '#FFFFFF';
metastatic <- '#7217A5';
# Generic
other <- '#E5E5E5';
unknown <- '#708090';
# Tumour Subtype
biliary.adenoca <- '#00CD66';
bladder.tcc <- '#EEAD0E';
bone.osteosarc <- '#FFD700';
bone.leiomyo <- '#FFEC8B';
# New naming for tumour types
softtissue.leiomyo <- '#FFEC8B';
softtissue.liposarc <- '#CDCB50';
bone.epith <- '#ADAC44';
breast.adenoca <- '#CD6090';
cervix.scc <- '#79CDCD';
cns.medullo <- '#D8BFD8';
cns.piloastro <- '#B0B0B0';
cns.gbm <- '#3D3D3D';
cns.gbm.alt <- '#4A4A4A';
cns.oligo <- '#787878';
colorect.adenoca <- '#191970';
eso.adenoca <- '#1E90FF';
head.scc <- '#8B2323';
kidney.rcc <- '#FF4500';
kidney.chrcc <- '#B32F0B';
liver.hcc <- '#006400';
lung.scc <- '#FDF5E6';
lung.adenoca <- '#FFFFFF';
lymph.bnhl <- '#698B22';
lymph.cll <- '#698B22';
myeloid.mpn <- '#FFC100';
myeloid.aml <- '#CD6600';
ovary.adenoca <- '#008B8B';
panc.adenoca <- '#7A378B';
panc.endocrine <- '#E066FF';
prost.adenoca <- '#87CEFA';
skin.melanoma <- '#000000';
stomach.adenoca <- '#BFEFFF';
thy.adenoca <- '#9370DB';
uterus.adenoca <- '#FF8C69';
bone.cart <- '#DDCDCD';
bone.cart.alt <- '#F0EE60';
breast.lobularca <- '#DDCDCD';
breast.lobularca.alt <- '#F095BD';
breast.dcis <- '#DDCDCD';
lymph.nos <- '#DDCDCD';
lymph.nos.alt <- '#698B22';
myeloid.mds <- '#DDCDCD';
cervix.adenoca <- '#DDCDCD';
#-----------------------------------------------------------------------------------------------
# Some input checking & processing
if (as.character(class(x)) == 'factor') {
stop('x cannot be a factor: please coerce to character before passing');
}
# Some parameters override provided input x.
if ( (scheme == 'all' || return.scheme) && length(x) != 0) {
warning('Input x ignored when scheme = \'all\' OR return.scheme = TRUE. Returning all schemes');
}
scheme <- tolower(scheme);
x.input <- tolower(x);
x.input <- gsub('-', '.', x.input);
if (return.scheme || scheme == 'all') {
x.input <- NULL;
}
colour.schemes <- list(
coding.snv = list(
levels = c(
'nonsynonymous',
'synonymous',
'stopgain',
'stoploss',
'indel.frameshift',
'indel.nonframeshift',
'splicing'
),
colours = c(
nonsynonymous,
synonymous,
stop.gain,
stop.loss,
indel.frameshift,
indel.nonframeshift,
splicing
)
),
noncoding.snv = list(
levels = c(
'noncoding',
'promoter',
'enhancer',
'operator',
'silencer',
'insulator',
'lncrna',
'sncrna',
'trna',
'rrna',
'mirna',
'utr5.utr3',
'intronic',
'intergenic',
'telomeres'
),
colours = c(
non.coding,
promoter,
enhancer,
operator,
silencer,
insulator,
lnc.rna,
snc.rna,
t.rna,
r.rna,
mi.rna,
utr5.utr3,
intronic,
intergenic,
telomeres
)
),
# ADD TFBS
structural.variants = list(
levels = c(
'cna.gain',
'cna.loss',
'inversion',
'transposition',
'translocation',
'insertion'
),
colours = c(
cna.gain,
cna.loss,
inversion,
transposition,
translocation,
insertion
)
),
chromosomes = list(
levels = c(
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'10',
'11',
'12',
'13',
'14',
'15',
'16',
'17',
'18',
'19',
'20',
'21',
'22',
'x',
'y'
),
colours = c(
chr1,
chr2,
chr3,
chr4,
chr5,
chr6,
chr7,
chr8,
chr9,
chr10,
chr11,
chr12,
chr13,
chr14,
chr15,
chr16,
chr17,
chr18,
chr19,
chr20,
chr21,
chr22,
chrx,
chry
)
),
sex = list(
levels = c(
'male',
'female'
),
colours = c(
male,
female
)
),
stage.arabic = list(
levels = c(
'1',
'2',
'3',
'4'
),
colours = c(
st.one,
st.two,
st.three,
st.four
)
),
stage.roman = list(
levels = c(
'i',
'i.ii',
'i.iii',
'ii',
'ii.i',
'ii.iii',
'iii',
'iv'
),
colours = c(
st.one,
st.one.two,
st.one.three,
st.two,
st.two.one,
st.two.three,
st.three,
st.four
)
),
t.category = list(
levels = c(
'0',
'1',
'2',
'3',
'4',
'x'
),
colours = c(
tnm.zero,
tn.one,
tn.two,
tn.three,
tn.four,
tnm.x
)
),
n.category = list(
levels = c(
'0',
'1',
'2',
'3',
'4',
'x'
),
colours = c(
tnm.zero,
tn.one,
tn.two,
tn.three,
tn.four,
tnm.x
)
),
m.category = list(
levels = c(
'0',
'1',
'x'
),
colours = c(
tnm.zero,
m.one,
tnm.x
)
),
grade = list(
levels = c(
'G1',
'G2',
'G3',
'G4'
),
colours = c(
gr.one,
gr.two,
gr.three,
gr.four
)
),
grade.word = list(
levels = c(
'well.differentiated',
'moderately.differentiated',
'poorly.differentiated',
'undifferentiated'
),
colours = c(
gr.well,
gr.mod,
gr.poor,
gr.un
)
),
prostate.grade = list(
levels = c(
'3+3',
'3+4',
'3+5',
'4+3',
'4+4',
'4+5',
'5+3',
'5+4',
'5+5'
),
colours = c(
pr.three.three,
pr.three.four,
pr.three.five,
pr.four.three,
pr.four.four,
pr.four.five,
pr.five.three,
pr.five.four,
pr.five.five
)
),
primary.met = list(
levels = c(
'primary',
'metastatic'
),
colours = c(
primary,
metastatic
)
),
tumour.subtype = list(
levels = c(
'biliary.adenoca',
'bladder.tcc',
'bone.osteosarc',
'bone.leiomyo',
'bone.epith',
'softtissue.leiomyo',
'softtissue.liposarc',
'breast.adenoca',
'cervix.scc',
'cns.medullo',
'cns.piloastro',
'cns.gbm',
'cns.gbm.alt',
'cns.oligo',
'colorect.adenoca',
'eso.adenoca',
'head.scc',
'kidney.rcc',
'kidney.chrcc',
'liver.hcc',
'lung.scc',
'lung.adenoca',
'lymph.bnhl',
'lymph.cll',
'myeloid.mpn',
'myeloid.aml',
'ovary.adenoca',
'panc.adenoca',
'panc.endocrine',
'prost.adenoca',
'skin.melanoma',
'stomach.adenoca',
'thy.adenoca',
'uterus.adenoca',
'bone.cart',
'bone.cart.alt',
'breast.lobularca',
'breast.lobularca.alt',
'breast.dcis',
'lymph.nos',
'myeloid.mds',
'cervix.adenoca'
),
colours = c(
biliary.adenoca,
bladder.tcc,
bone.osteosarc,
bone.leiomyo,
bone.epith,
softtissue.leiomyo,
softtissue.liposarc,
breast.adenoca,
cervix.scc,
cns.medullo,
cns.piloastro,
cns.gbm,
cns.gbm.alt,
cns.oligo,
colorect.adenoca,
eso.adenoca,
head.scc,
kidney.rcc,
kidney.chrcc,
liver.hcc,
lung.scc,
lung.adenoca,
lymph.bnhl,
lymph.cll,
myeloid.mpn,
myeloid.aml,
ovary.adenoca,
panc.adenoca,
panc.endocrine,
prost.adenoca,
skin.melanoma,
stomach.adenoca,
thy.adenoca,
uterus.adenoca,
bone.cart,
bone.cart.alt,
breast.lobularca,
breast.lobularca.alt,
breast.dcis,
lymph.nos,
myeloid.mds,
cervix.adenoca
)
),
organ.system = list(
levels = c(
'biliary',
'bladder',
'bone.softtissue',
'breast',
'cervix',
'cns',
'colon.rectum',
'esophagus',
'head.neck',
'kidney',
'liver',
'lung',
'lymphoid',
'myeloid',
'ovary',
'pancreas',
'prostate',
'skin',
'stomach',
'thyroid',
'uterus'
),
colours = c(
biliary.adenoca,
bladder.tcc,
bone.leiomyo,
breast.adenoca,
cervix.scc,
cns.oligo,
colorect.adenoca,
eso.adenoca,
head.scc,
kidney.rcc,
liver.hcc,
lung.scc,
lymph.bnhl,
myeloid.aml,
ovary.adenoca,
panc.adenoca,
prost.adenoca,
skin.melanoma,
stomach.adenoca,
thy.adenoca,
uterus.adenoca
)
),
project.code = list(
levels = c(
'lica',
'lihc',
'linc',
'liri',
'paca',
'eopc',
'prad',
'brca',
'kirc',
'kirp',
'reca',
'ov',
'dlbc',
'maly',
'cll',
'clle',
'pbca',
'mela',
'skcm',
'coad',
'read',
'stad',
'ucec',
'hnsc',
'orca',
'esad',
'lusc',
'thca',
'kich',
'paen',
'luad',
'gbm',
'sarc',
'btca',
'cmdi',
'blca',
'boca',
'cesc',
'lgg',
'laml'
),
colours = c(
liver.hcc,
liver.hcc,
liver.hcc,
liver.hcc,
panc.adenoca,
prost.adenoca,
prost.adenoca,
breast.adenoca,
kidney.rcc,
kidney.rcc,
kidney.rcc,
ovary.adenoca,
lymph.bnhl,
lymph.bnhl,
lymph.bnhl,
lymph.bnhl,
cns.oligo,
skin.melanoma,
skin.melanoma,
colorect.adenoca,
colorect.adenoca,
stomach.adenoca,
uterus.adenoca,
head.scc,
head.scc,
eso.adenoca,
lung.scc,
thy.adenoca,
kidney.rcc,
panc.adenoca,
lung.scc,
cns.oligo,
bone.leiomyo,
biliary.adenoca,
myeloid.aml,
bladder.tcc,
bone.leiomyo,
cervix.scc,
cns.oligo,
myeloid.aml
)
)
);
# Error if wanted scheme doesn't match existing schemes
if (is.null(colour.schemes[[scheme]]) && scheme != 'all') {
stop('Scheme not found!');
}
# Return full specified schemes if return.scheme is TRUE
if (return.scheme & 'all' == scheme) {
return(colour.schemes);
}
else if (return.scheme & 'all' != scheme) {
return(colour.schemes[[scheme]]);
}
else if (!return.scheme & 'all' == scheme) {
return(names(colour.schemes));
}
# Form output colours
matched <- match(x.input, colour.schemes[[scheme]]$levels);
x.colours <- colour.schemes[[scheme]]$colours[matched];
names(x.colours) <- colour.schemes[[scheme]]$levels[matched];
# Deal with unrecognized input by setting to fill colour (slategray by default)
if (any(is.na(x.colours))) {
warning('Unrecognized input value for x. Default to fill.colour.');
}
x.colours[which(is.na(x.colours))] <- fill.colour;
return(x.colours);
}
# Copyright (c) 2016 Ontario Institute for Cancer Research
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
# associated documentation files (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge, publish, distribute,
# sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
# NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
# OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/pcawg.colours.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2011 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO CONVERT TO SCIENTIFIC NOTATION ####################################################
scientific.notation <- function(x, digits = 1, type = 'expression') {
# handle lists appropriately
if (length(x) > 1) {
return(
append(
BoutrosLab.plotting.general::scientific.notation(x[1]),
BoutrosLab.plotting.general::scientific.notation(x[-1])
)
);
}
# handle zeros
if (!x) { return(0); }
# determine the exponent & base
exponent <- floor(log10(x));
base <- sprintf(paste('%.', digits, 'f', sep = ''), x / 10 ^ exponent);
# return the value
if (type == 'expression') {
return(as.expression(substitute(base %*% 10 ^ exponent, list(base = base, exponent = exponent))));
}
else if (type == 'list') {
return(list(base = base, exponent = exponent));
}
else {
warning("Return type can only be 'expression' or 'list'.");
}
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/scientific.notation.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2014 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO DISPLAY AVAILABLE COLOUR SCHEMES ##################################################
show.available.palettes <- function(
type = 'general', filename = NULL, height = 5, width = 8, resolution = 300
) {
type <- tolower(type);
### DISPLAY GENERAL SCHEMES ###################################################################
# The general schemes are those found in the default.colours function
if ('general' == type) {
# Get the default colours
general <- default.colours(palette.type = 'all');
all.colours <- stack(general)$values;
# Encoding the colours as numbers
max.length <- 0;
for (i in 1:length(general)) {
if (length(general[[i]]) > max.length) {
max.length <- length(general[[i]]);
}
}
count <- 1;
for (i in 1:length(general)) {
for (j in 1:max.length) {
if (!is.na(general[[i]][j])) {
general[[i]][j] <- count;
count <- count + 1;
}
}
}
for (i in 1:length(general)) {
if (length(general[[i]]) < max.length) {
length(general[[i]]) <- max.length;
}
}
# Making the data frame numeric for heatmap functionality
reordered.data <- as.data.frame(lapply(general, as.numeric));
# Using the heatmap function to display the colour palettes
BoutrosLab.plotting.general::create.heatmap(
filename = filename,
# reverse order of columns for display
x = reordered.data[c(rev(seq(1, dim(reordered.data)[2], 1)))],
clustering.method = 'none',
colour.scheme = all.colours,
total.colours = (length(all.colours) + 1),
fill.colour = 'white',
grid.row = TRUE,
grid.col = TRUE,
row.colour = 'white',
col.colour = 'white',
row.lwd = 10,
axes.lwd = 0,
print.colour.key = FALSE,
# Reverse order of names to match reversed data frame
yaxis.lab = rev(names(general)),
yaxis.cex = 1,
yaxis.fontface = 1,
height = height,
width = width,
resolution = resolution
);
}
### DISPLAY SPECIFIC SCHEMES ##################################################################
else if ('specific' == type) {
specific <- force.colour.scheme(x = '', scheme = 'all', return.scheme = TRUE)$scheme;
# sort by length, longest first
swapped <- TRUE;
while (TRUE == swapped) {
swapped <- FALSE;
for (i in 2:length(specific)) {
if (length(specific[[i - 1]]$colours) < length(specific[[i]]$colours)) {
temp <- specific[i];
temp.name <- names(specific)[i];
specific[i] <- specific[i - 1];
names(specific)[i] <- names(specific)[i - 1];
specific[i - 1] <- temp;
names(specific)[i - 1] <- temp.name;
swapped <- TRUE;
}
}
}
number.of.colours <- 0;
for (i in 1:length(specific)) {
number.of.colours <- number.of.colours + length(specific[[i]]$levels);
}
# calculate layout: (assumption: longest palette is much longer than others -- therefore sets height of plot)
# adding one spacer for the header text
display.height <- length(specific[[1]]$colours) + 1;
formatted.data <- data.frame();
# initate with first row
temp.col <- c(0, specific[[1]]$colours);
for (i in 2:length(specific)) {
potential.length <- length(temp.col) + length(specific[[i - 1]]$colours) + 2;
if (potential.length <= display.height && i < length(specific)) {
temp.col <- c(temp.col, NA, 0, specific[[i]]$colours);
}
else {
# special case for the last row
if (length(specific) == i) {
temp.col <- c(temp.col, NA, 0, specific[[i]]$colours);
}
# add previous col to data frame
length(temp.col) <- display.height;
# check if inital row has been added
if (0 == ncol(formatted.data)) {
formatted.data <- temp.col;
}
else {
formatted.data <- cbind(formatted.data, temp.col);
}
# add spacers for labels
spacer.col <- NA;
length(spacer.col) <- display.height;
spacing.for.labels <- 0;
for (word in 1:length(temp.col)) {
if (nchar(temp.col[2]) > spacing.for.labels) {
spacing.for.labels <- nchar(temp.col[2]);
}
}
for (k in 1:spacing.for.labels) {
formatted.data <- cbind(formatted.data, spacer.col);
}
# make a new row and add 0 for header
# using 0 instead of NA to mark headers in order to locate them later
temp.col <- c(0, specific[[i]]$colours);
}
}
# save the matrix with colour codes to find white swatches later
colour.coded.data <- formatted.data;
# map colours to numbers
all.colours <- character();
for (i in 1:length(specific)) {
all.colours <- c(all.colours, specific[[i]]$colours);
}
colour.number <- 1;
for (i in 1:length(formatted.data)) {
if (!is.na(formatted.data[i]) && 0 != formatted.data[i]) {
formatted.data[i] <- colour.number;
colour.number <- colour.number + 1;
}
}
enumerated.data <- as.data.frame(apply(formatted.data, c(1, 2), as.numeric));
# get labels
labels <- character();
bold.text <- numeric();
offset <- numeric();
for (i in 1:length(specific)) {
labels <- c(labels, names(specific)[i], specific[[i]]$levels);
bold.text <- c(bold.text, 2, rep(1, length(specific[[i]]$levels)));
offset <- c(offset, -0.5, rep(1, length(specific[[i]]$levels)));
}
label.col.positions <- which(!is.na(enumerated.data), arr.ind = TRUE)[, 2];
label.row.positions <- which(!is.na(enumerated.data), arr.ind = TRUE)[, 1];
# adding border around white swatches
border.matrix <- matrix(
nrow = nrow(colour.coded.data),
ncol = ncol(colour.coded.data),
data = FALSE
);
border.colour.matrix <- matrix(
nrow = nrow(colour.coded.data),
ncol = ncol(colour.coded.data),
data = 'grey'
);
border.size.matrix <- matrix(
nrow = nrow(colour.coded.data),
ncol = ncol(colour.coded.data),
data = 0.25
);
symbol.locations <- list(
borders = list(
list(
x = border.matrix,
col = border.colour.matrix,
size = border.size.matrix
)
)
);
symbol.locations$borders[[1]]$x[which('white' == colour.coded.data, arr.ind = TRUE)] <- TRUE;
# display the colours using the heatmap function
create.heatmap(
filename = filename,
x = enumerated.data,
same.as.matrix = TRUE,
# adding white for the header spaces, which are labelled 0
colour.scheme = c('white', all.colours),
total.colours = (length(all.colours) + 2),
fill.colour = 'white',
clustering.method = 'none',
axes.lwd = 0,
print.colour.key = FALSE,
# adding headers and labels
col.pos = label.col.positions,
# flipping the rows to match the colour layout
row.pos = (display.height + 1 - label.row.positions),
cell.text = labels,
text.position = 4,
text.offset = offset,
text.col = 'black',
text.cex = 0.75,
text.fontface = bold.text,
# adding borders around white swatches
symbols = symbol.locations,
height = height,
width = width,
resolution = resolution
);
}
else {
stop('Invalid value supplied to type parameter.');
}
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/show.available.palettes.R
|
# The BoutrosLab.plotting.general package is copyright (c) 2013 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
thousands.split <- function(nums) {
to.return <- {};
for (k in c(1:length(nums))) {
text <- format(nums[k], scientific = FALSE);
num.sets <- trunc(nchar(text) / 3); #number of sets of 3
remaining.letters <- nchar(text) %% 3; # remainder
final.str <- ''; #string to be manipulated
#handle remainder first (first set of < 3)
if (remaining.letters != 0) {
final.str <- substring(text, 1, remaining.letters);
text <- substring(text, remaining.letters + 1, nchar(text));
}
#split the text up
sst <- strsplit(text, '')[[1]];
#grab sets of 3
out <- paste0(sst[c(TRUE, FALSE, FALSE)], sst[c(FALSE, TRUE, FALSE)], sst[c(FALSE, FALSE, TRUE)]);
#insert comma in between each set
if (num.sets != 0) {
for (i in c(1:num.sets)) {
if (remaining.letters == 0 && i == 1) {
final.str <- out[i];
}
else {
final.str <- paste0(final.str, ',', out[i]);
}
}
}
to.return[k] <- final.str;
}
return(to.return);
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/thousands.split.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.