content
stringlengths
0
14.9M
filename
stringlengths
44
136
#' @title Waterfall Charts #' @docType package #' #' @description #' Create waterfall or "McKinsey" charts #' #' @details #' This package provides support for creating waterfall #' charts in R using both traditional base and lattice graphics. #' #' @author #' James P. Howard, II <[email protected]> #' "_PACKAGE" #> [1] "_PACKAGE"
/scratch/gouwar.j/cran-all/cranData/waterfall/R/waterfall.R
## Copyright (c) 2008-2016, James P. Howard, II <[email protected]> ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## ## Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## ## Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in ## the documentation and/or other materials provided with the ## distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #' @title Waterfall Chart #' #' @description #' Creates a waterfall chart using Lattice #' #' @param x a formula describing the form of conditioning plot. The #' formula is generally of the form 'y ~ x | g1 * g2 * ...', indicating #' that plots of 'y' (on the y axis) versus 'x' (on the x axis) should #' be produced conditional on the variables 'g1, g2, ...'. However, the #' conditioning variables 'g1,g2,...' may be omitted. #' #' @param data a data frame containing values (or more precisely, #' anything that is a valid 'envir' argument in 'eval', e.g., a list or #' an environment) for any variables in the formula, as well as 'groups' #' and 'subset' if applicable. If not found in 'data', or if 'data' is #' unspecified, the variables are looked for in the environment of the #' formula. #' #' @param groups a vector expected to act as a grouping variable within #' each panel, typically used to distinguish different groups by varying #' graphical parameters like color and line type. Unlike with the #' \link{barchart} function, groups specifies where subtotals columns, #' should appear. There is a subtotal created for each group specified. #' If no groups are given, a summary column is still reported. #' #' @param horizontal This argument is used to process the arguments to #' these high level functions, but more importantly, it is passed as an #' argument to the panel function, which is supposed to use it as #' appropriate. #' #' @param panel This draws the actual plot after \link{bwplot} has done #' the difficult work of processing the formula. #' #' @param prepanel This function returns the \link{bwplot} information #' on the number of columns to display and where to place labels. #' #' @param box.ratio specifies the ratio of the width of the rectangles #' to the interrectangle space. #' #' @param origin initial offset relative to the x axis. The value #' serves as the logical starting point for the first column and any #' summary column. Defaults to 0. #' #' @param level.lines if FALSE, the lines connecting adjacent boxes are #' ommitted from the display. #' #' @param summaryname name of the summary column, usually "Total" #' #' @param ... further arguments. #' #' @details #' #' This function closely mimics the \link{barchart} interface, but #' provides a type of chart called a waterfall plot, showing how #' multiple subvalues contribute to a total sum. #' #' The bulk of the work is actually processed in \link{bwplot} which #' defines where tickmarks and other information outside the plot itself #' are placed. Only a formula method is provided. #' #' Matrix and vector interfaces are not provided because mimicing the #' behavior of \link{barchart} for those interfaces produces #' unintellible and undefined graphic output. #' #' @references #' #' Andrew Jaquith, \emph{Security Metrics: Replacing Fear, #' Uncertainty, and Doubt} (Boston: Addison-Wesley Professional, 2007), #' 170-172. #' #' Ethan M. Rasiel, \emph{The McKinsey Way: Using the Techniques of the #' World's Top Strategic Consultants to Help You and Your Business} (New #' York: McGraw-Hill, 1999), 113-118. #' #' @examples #' data(rasiel) #' data(jaquith) #' waterfallchart(value~label, data=rasiel, groups=rasiel$subtotal) #' waterfallchart(factor~score, data=jaquith) #' #' @import lattice #' #' @export waterfallchart <- function (x, data = NULL, groups = NULL, horizontal = FALSE, panel = panel.waterfallchart, prepanel = prepanel.waterfallchart, summaryname = "Total", box.ratio = 2, origin = 0, level.lines = TRUE, ...) UseMethod("waterfallchart") #' @export waterfallchart.formula <- function (x, data = NULL, groups = NULL, horizontal = FALSE, panel = panel.waterfallchart, prepanel = prepanel.waterfallchart, summaryname = "Total", box.ratio = 2, origin = 0, level.lines = TRUE, ...) { ocall <- sys.call(sys.parent()) ocall[[1]] <- quote(waterfallchart) ccall <- match.call() ccall$data <- data ccall$panel <- panel ccall$prepanel <- prepanel ccall$box.ratio <- box.ratio if(is.null(groups)) ccall$groups <- rep(summaryname, nrow(data)) ## Let lattice do the hard work ccall[[1]] <- quote(bwplot) ans <- eval.parent(ccall) ans$call <- ocall ans } panel.waterfallchart <- function (x, y, box.ratio = 1, box.width = box.ratio/(1 + box.ratio), horizontal = FALSE, origin = 0, reference = TRUE, groups = NULL, summaryname = NULL, col = if (is.null(groups)) plot.polygon$col else superpose.polygon$col, border = if (is.null(groups)) plot.polygon$border else superpose.polygon$border, lty = if (is.null(groups)) plot.polygon$lty else superpose.polygon$lty, lwd = if (is.null(groups)) plot.polygon$lwd else superpose.polygon$lwd, level.lines = TRUE, ...) { plot.polygon <- trellis.par.get("plot.polygon") superpose.polygon <- trellis.par.get("superpose.polygon") reference.line <- trellis.par.get("reference.line") keep <- (function(x, y, groups, subscripts, ...) { !is.na(x) & !is.na(y) })(x = x, y = y, ...) if (!any(keep)) return() x <- as.numeric(x[keep]) y <- as.numeric(y[keep]) grplst <- sort(unique(groups)) baseline <- rep(origin, (l = length(x) + length(grplst)) + 1) ## The following block of code reorganizes the data into the final ## format. The same block is used above. if (horizontal) { data <- merge(data.frame(x, y, groups, groupsy = y)[order(groups, y), ], data.frame(x = rep(NA, length(grplst)), y = rep(NA, length(grplst)), groups = grplst, groupsy = grplst), all = TRUE) data <- data[order(data$groups, data$y), ] if (is.null(origin)) { origin <- current.panel.limits()$xlim[1] reference <- FALSE } if (reference) panel.abline(h = origin, col = reference.line$col, lty = reference.line$lty, lwd = reference.line$lwd) for (i in 1:l) { if (is.na(data[i, ]$y)) { height <- origin - (baseline[i + 1] = baseline[i]) color <- col[2] } else { baseline[i + 1] <- baseline[i] + (height = data[i, ]$x) color <- col[1] } panel.rect(y = i, x = baseline[i], col = color, lty = lty, lwd = lwd, height = box.width, width = height, just = c("left", "centre")) } if (level.lines == TRUE) for (i in 2:l - 1) panel.lines(y = c(i, i + 1), x = baseline[i + 1], col = border, lty = lty, lwd = lwd) } else { data <- merge(data.frame(x, y, groups, groupsx = x)[order(groups, x), ], data.frame(x = rep(NA, length(grplst)), y = rep(NA, length(grplst)), groups = grplst, groupsx = grplst), all = TRUE) data <- data[order(data$groups, data$x), ] if (is.null(origin)) { origin <- current.panel.limits()$ylim[1] reference <- FALSE } if (reference) panel.abline(h = origin, col = reference.line$col, lty = reference.line$lty, lwd = reference.line$lwd) for (i in 1:l) { if (is.na(data[i, ]$y)) { height <- origin - (baseline[i + 1] = baseline[i]) color <- col[2] } else { baseline[i + 1] <- baseline[i] + (height = data[i, ]$y) color <- col[1] } panel.rect(x = i, y = baseline[i], col = color, lty = lty, lwd = lwd, width = box.width, height = height, just = c("centre", "bottom")) } if (level.lines == TRUE) for (i in 2:l - 1) panel.lines(x = c(i, i + 1), y = baseline[i + 1], col = border, lty = lty, lwd = lwd) } } prepanel.waterfallchart <- function (x, y, horizontal = FALSE, origin = 0, groups = NULL, summaryname = NULL, ...) { if (any(!is.na(x) & !is.na(y))) { grplst <- sort(unique(groups)) baseline <- rep(origin, (l = length(x) + length(grplst))) ## The following block of code reorganizes the data into the final ## format. The same block is used above. if (horizontal) { data <- merge(data.frame(x, y, groups, groupsy = y)[order(groups, y), ], data.frame(x = rep(NA, length(grplst)), y = rep(NA, length(grplst)), groups = grplst, groupsy = grplst), all = TRUE) data <- data[order(data$groups, data$y), ] list(ylim = levels(factor(data$groupsy, levels = data$groupsy)), yat = sort(unique(as.numeric(data$groupsy, levels = data$groupsy))), xlim = { for (i in 1:(l - 1)) { if (!is.na(data[i, ]$x)) baseline[i + 1] <- baseline[i] + data[i, ]$x else baseline[i + 1] <- baseline[i] } range(baseline) }, dx = 1, dy = 1) } else { data <- merge(data.frame(x, y, groups, groupsx = x)[order(groups, x), ], data.frame(x = rep(NA, length(grplst)), y = rep(NA, length(grplst)), groups = grplst, groupsx = grplst), all = TRUE) data <- data[order(data$groups, data$x), ] list(xlim = levels(factor(data$groupsx, levels = data$groupsx)), xat = sort(unique(as.numeric(data$groupsx, levels = data$groupsx))), ylim = { for (i in 1:(l - 1)) { if (!is.na(data[i, ]$y)) baseline[i + 1] <- baseline[i] + data[i, ]$y else baseline[i + 1] <- baseline[i] } range(baseline) }, dx = 1, dy = 1) } } else list(xlim = c(NA, NA), ylim = c(NA, NA), dx = 1, dy = 1) }
/scratch/gouwar.j/cran-all/cranData/waterfall/R/waterfallchart.R
## Copyright (c) 2008-2016, James P. Howard, II <[email protected]> ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## ## Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## ## Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in ## the documentation and/or other materials provided with the ## distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #' @title Waterfall Plot #' #' @description #' Creates a waterfall plot with vertical or horizontal bars. #' #' @param height a vector of values describing the height of the bars #' that make up the plot. Matrices are not supported. #' #' @param width optional vector of bar widths. Re-cycled to length the #' number of bars drawn. Specifying a single value will have no visible #' effect unless 'xlim' is specified. #' #' @param space #' the amount of space (as a fraction of the average bar width) #' left before each bar. May be given as a single number or one number #' per bar. If not given explicitly, it defaults to 0.2. #' #' @param names.arg a vector of names to be plotted below each bar If #' this argument is omitted, then the names are taken from the 'names' #' attribute of 'height.' #' #' @param horiz a logical value. If 'FALSE', the bars are drawn #' vertically with the first bar to the left. If 'TRUE', the bars are #' drawn horizontally with the first at the bottom. #' #' @param density a vector giving the density of shading lines, in lines #' per inch, for the bars or bar components. The default value of 'NULL' #' means that no shading lines are drawn. Non-positive values of #' 'density' also inhibit the drawing of shading lines. #' #' @param angle the slope of shading lines, given as an angle in degrees #' (counter-clockwise), for the bars or bar components. #' #' @param col a vector of colors for the bars or bar components. By #' default, grey is used. #' #' @param border the color to be used for the border of the bars. Use #' 'border = NA' to omit borders. If there are shading lines, 'border = #' TRUE' means use the same colour for the border as forr the shading #' lines. #' #' @param main overall title for the plot. #' #' @param sub subtitle for the plot. #' #' @param xlab a label for the x-axis. #' @param ylab a label for the y-axis. #' @param xlim limits for the x-axis. #' @param ylim limits for the y-axis. #' @param xpd logical. Should bars be allowed to outside region? #' #' @param axes logical. If 'TRUE', a vertical (or horizontal, if #' 'horiz' is true) axis is drawn. #' #' @param axisnames logical. If 'TRUE', and if there are 'names.arg' #' (see above), the other axis is drawn (with 'lty=0') and labeled. #' #' @param cex.axis expansion factor for numeric axis labels. #' @param cex.names expansion factor for axis names (bar labels). #' @param plot logical. If 'FALSE', nothing is plotted. #' #' @param axis.lty the graphics parameter 'lty' applied to the axis and #' tick marks of the categorical (default horizontal) axis. Note that by #' default the axis is suppressed. #' #' @param offset initial offset relative to the x axis. The value #' serves as the logical starting point for the first column and any #' summary column. Defaults to 0. #' #' @param add logical specifying if bars should be added to an already #' existing plot; defaults to 'FALSE'. #' #' @param summary create a summary column. A summary column provides a #' final sum column showing the relative change from the offset. If a #' summary is requested and names.arg is set, the names.arg vector must #' include one extra entry with the summary column's name. Defaults to #' FALSE. #' #' @param rev reverse the order of columns? Defaults to FALSE. #' #' @param level.lines if FALSE, the lines connecting adjacent boxes are #' ommitted from the display. #' #' @param ... arguments to be passed to other methods. For the default #' method these can include further arguments (such as 'axes', 'asp' and #' 'main') and graphical parameters (see 'par') which are passed to #' 'plot.window()', 'title()' and 'axis'. #' #' @details #' #' This function closely mimics the \link{barplot} interface, but #' provides a type of chart called a waterfall plot, showing how multiple #' subvalues contribute to a total sum. #' #' This is a generic function, it currently only has a default method. A #' formula interface may be added eventually. #' #' @return A numeric vector say 'mp', giving the coordinates of #' \emph{all} the bar midpoints drawn, useful for adding to the graph. #' #' @references #' #' Andrew Jaquith, \emph{Security Metrics: Replacing Fear, #' Uncertainty, and Doubt} (Boston: Addison-Wesley Professional, 2007), #' 170-172. #' #' Ethan M. Rasiel, \emph{The McKinsey Way: Using the Techniques of the #' World's Top Strategic Consultants to Help You and Your Business} (New #' York: McGraw-Hill, 1999), 113-118. #' #' @examples #' data(rasiel) #' waterfallplot(rasiel$value, names.arg=rasiel$label) #' #' @importFrom graphics par #' @importFrom graphics plot.new #' @importFrom graphics plot.window #' @importFrom graphics rect #' @importFrom graphics lines #' @importFrom graphics axis #' @importFrom graphics title #' #' @export waterfallplot <- function (height, width = 1, space = NULL, names.arg = NULL, horiz = FALSE, density = NULL, angle = 45, col = NULL, border = par("fg"), main = NA, sub = NA, xlab = NULL, ylab = NULL, xlim = NULL, ylim = NULL, xpd = TRUE, axes = TRUE, axisnames = TRUE, cex.axis = par("cex.axis"), cex.names = par("cex.axis"), plot = TRUE, axis.lty = 0, offset = 0, add = FALSE, summary = FALSE, rev = FALSE, level.lines = TRUE, ...) { ## Set up the initial environment respaxis <- 2 expaxis <- 1 l <- length(height) if (summary == TRUE) { height[l + 1] = -sum(height) l = l + 1 } if (rev == TRUE) { height = rev(height) if (summary == TRUE) height = -height } if (!is.null(names.arg) && length(names.arg) != l) stop("incorrect number of names") if (!is.null(names(height))) names.arg <- names(height) density.vec <- rep(density, l, length.out = l) angle.vec <- rep(angle, l, length.out = l) if (is.null(col)) col <- "grey" col.vec <- rep(col, l, length.out = l) border.vec <- rep(border, l, length.out = l) ## Assemble the baseline and topline vectors. Default the spacing ## between bars to 1/5 of the average bar width. Create the same ## initial offset as present in barplot() width.vec <- rep(width, l, length.out = l) if (is.null(space)) space <- 0.2 space.vec <- rep(space, l + 1, length.out = l + 1) space.vec <- space.vec * mean(width.vec) leftline <- rightline <- topline <- baseline <- rep(offset, l) leftline[1] <- space.vec[1] for (i in 1:l) { topline[i] <- baseline[i] + height[i] baseline[i + 1] <- topline[i] rightline[i] <- leftline[i] + width.vec[i] leftline[i + 1] <- rightline[i] + space.vec[i + 1] } ticks.vec = rep(0, times = l) ## Wait, do we need to turns this on its side? Barplot uses an ## internal function that rearranges the order of arguments. This is ## a bit less hassle to do it once, though the line drawing functions ## will need to be checked later. if (horiz == TRUE) { oldtopline <- topline topline <- leftline leftline <- oldtopline oldbaseline <- baseline baseline <- rightline rightline <- oldbaseline respaxis <- 1 expaxis <- 2 for (i in 1:l) ticks.vec[i] <- (baseline[i] + topline[i])/2 } else { for (i in 1:l) ticks.vec[i] <- (leftline[i] + rightline[i])/2 } if (is.null(xlim)) xlim <- c(min(leftline), max(rightline)) if (is.null(ylim)) ylim <- c(min(topline, baseline), max(topline, baseline)) if (plot == TRUE) { if (add == FALSE) plot.new() plot.window(xlim = xlim, ylim = ylim, ...) for (i in 1:l) rect(leftline[i], baseline[i], rightline[i], topline[i], density = density.vec[i], angle = angle.vec[i], col = col.vec[i], border = border.vec[i], xpd = xpd, ...) if (level.lines == TRUE) if (horiz == TRUE) for (i in 1:(l - 1)) lines(c(leftline[i], leftline[i]), c(baseline[i], topline[i + 1]), ...) else for (i in 1:(l - 1)) lines(c(rightline[i], leftline[i + 1]), c(topline[i], baseline[i + 1]), ...) if (!is.null(names.arg) && axisnames) axis(expaxis, at = ticks.vec, labels = names.arg, lty = axis.lty, cex.axis = cex.names, ...) if (axes == TRUE) axis(respaxis, cex.axis = cex.axis, ...) title(main = main, sub = sub, xlab = xlab, ylab = ylab, ...) } invisible(ticks.vec) }
/scratch/gouwar.j/cran-all/cranData/waterfall/R/waterfallplot.R
## Andrew Jaquith, Security Metrics: Replacing Fear, Uncertainty, and ## Doubt (Boston: Addison-Wesley Professional, 2007), 170-172. `jaquith` <- structure(list(factor = c("Administrative interfaces", "Authentication/access control", "Configuration management", "Cryptographic algorithms", "Information gathering", "Input validation", "Parameter manipulation", "Sensitive data handling", "Session management"), score = c(36.2, 85.2, 36.3, 6.8, 11, 46.3, 31.5, 34.5, 44)), .Names = c("factor", "score"), row.names = c(NA, 9L), class = "data.frame")
/scratch/gouwar.j/cran-all/cranData/waterfall/data/jaquith.R
## Ethan M. Rasiel, The McKinsey Way: Using the Techniques of the ## World's Top Strategic Consultants to Help You and Your Business ## (New York: McGraw-Hill, 1999), 113-118. `rasiel` <- structure(list(label = structure(c(3L, 4L, 2L, 1L, 5L), .Label = c("Gains", "Interest", "Net Sales", "Expenses", "Taxes"), class = "factor"), value = c(150L, -170L, 18L, 10L, -2L), subtotal = structure(c(1L, 1L, 2L, 2L, 2L), .Label = c("EBIT", "Net Income"), class = "factor")), .Names = c("label", "value", "subtotal"), class = "data.frame", row.names = c(NA, -5L))
/scratch/gouwar.j/cran-all/cranData/waterfall/data/rasiel.R
data(rasiel) data(jaquith) require(grid) old.promot <- devAskNewPage(ask = TRUE) waterfallchart(value~label, data=rasiel, groups=subtotal) waterfallchart(factor~score, data=jaquith) devAskNewPage(old.prompt)
/scratch/gouwar.j/cran-all/cranData/waterfall/demo/waterfallchart.R
data(rasiel) waterfallplot(rasiel$value, names.arg=rasiel$label)
/scratch/gouwar.j/cran-all/cranData/waterfall/demo/waterfallplot.R
#' Create waterfall charts #' #' @name waterfall #' @author Based on \code{grattan_waterfall} from the 'grattanCharts' package (\url{https://github.com/HughParsonage/grattanCharts}). #' @param .data a \code{data.frame} containing two columns, one with the values, the other with the labels #' @param values a numeric vector making up the heights of the rectangles in the waterfall #' @param labels the labels corresponding to each vector, marked on the x-axis #' @param rect_text_labels (character) a character vector of the same length as values that are placed on the rectangles #' @param rect_text_size size of the text in the rectangles #' @param rect_text_labels_anchor (character) How should \code{rect_text_labels} be positioned? In future releases, we might have support for north or south anchors, or for directed positioning (negative down, positive up) etc. For now, only centre is supported. #' @param put_rect_text_outside_when_value_below (numeric) the text labels accompanying a rectangle of this height will be placed outside the box: below if it's negative; above if it's positive. #' @param calc_total (logical, default: \code{FALSE}) should the final pool of the waterfall be calculated (and placed on the chart) #' @param total_axis_text (character) the text appearing on the axis underneath the total rectangle #' @param total_rect_text (character) the text in the middle of the rectangle of the total rectangle #' @param total_rect_color the color of the final rectangle #' @param total_rect_border_color the border color of the total rectangle #' @param total_rect_text_color the color of the final rectangle's label text #' @param fill_colours Colours to be used to fill the rectangles, in order. Disregarded if \code{fill_by_sign} is \code{TRUE} (the default). #' @param fill_by_sign (logical, default: \code{TRUE}) should positive and negative values each have the same colour? #' @param rect_width (numeric) the width of the rectangle, relative to the space between each label factor #' @param rect_border the border colour around the rectangles. Provide either a single color, that will be used for each rectangle, or one color for each rectangle. Choose \code{NA} if no border is desired. #' @param draw_lines (logical, default: \code{TRUE}) should lines be drawn between successive rectangles #' @param linetype the linetype for the draw_lines #' @param lines_anchors a character vector of length two specifying the horizontal placement of the drawn lines relative to the preceding and successive rectangles, respectively #' @param draw_axis.x (character) one of "none", "behind", "front" whether to draw an x.axis line and whether to draw it behind or in front of the rectangles, default is behind #' @param theme_text_family (character) Passed to the \code{text} argument in \code{ggplot2::theme}. #' @param scale_y_to_waterfall (logical, default: \code{TRUE}) Should the default range of the y-axis be from the bottom of the lowest pool to the top of the highest? If \code{FALSE}, which was the only option before version 0.1.2, the range of the plot is more balanced around the y-axis. #' @param print_plot (logical) Whether or not the plot should be printed. By default, \code{TRUE}, which means it cannot be assigned. #' @param ggplot_object_name (character) A quoted valid object name to which ggplot layers may be added after the function has run. Ignored if \code{print} is \code{FALSE}. #' @examples #' waterfall(values = round(rnorm(5), 1), labels = letters[1:5], calc_total = TRUE) #' waterfall(.data = data.frame(category = letters[1:5], #' value = c(100, -20, 10, 20, 110)), #' fill_colours = colorRampPalette(c("#1b7cd6", "#d5e6f2"))(5), #' fill_by_sign = FALSE) #' @export waterfall <- function(.data = NULL, values, labels, rect_text_labels = values, rect_text_size = 1, rect_text_labels_anchor = "centre", put_rect_text_outside_when_value_below = 0.05*(max(cumsum(values)) - min(cumsum(values))), calc_total = FALSE, total_axis_text = "Total", total_rect_text = sum(values), total_rect_color = "black", total_rect_border_color = "black", total_rect_text_color = "white", fill_colours = NULL, fill_by_sign = TRUE, rect_width = 0.7, rect_border = "black", draw_lines = TRUE, lines_anchors = c("right", "left"), linetype = "dashed", draw_axis.x = "behind", theme_text_family = "", scale_y_to_waterfall = TRUE, print_plot = FALSE, ggplot_object_name = "mywaterfall") { if (!is.null(.data)) { if (!is.data.frame(.data)) { stop("`.data` was a ", class(.data)[1], ", but must be a data.frame.") } if (ncol(.data) < 2L) { stop("`.data` had fewer than two columns, yet two are required: labels and values.") } dat <- as.data.frame(.data) char_cols <- vapply(dat, is.character, FALSE) factor_cols <- vapply(dat, is.factor, FALSE) num_cols <- vapply(dat, is.numeric, FALSE) if (!xor(num_cols[1], num_cols[2]) || sum(char_cols[1:2], factor_cols[1:2], num_cols[1:2]) != 2L) { const_width_name <- function(noms) { if (is.data.frame(noms)) { noms <- names(noms) } max_width <- max(nchar(noms)) formatC(noms, width = max_width) } stop("`.data` did not contain exactly one numeric column and exactly one character or factor ", "column in its first two columns.\n\t", "1st column: '", const_width_name(dat)[1], "'\t", sapply(dat, class)[1], "\n\t", "2nd column: '", const_width_name(dat)[2], "'\t", sapply(dat, class)[2]) } if (num_cols[1L]) { .data_values <- .subset2(dat, 1L) .data_labels <- .subset2(dat, 2L) } else { .data_values <- .subset2(dat, 2L) .data_labels <- .subset2(dat, 1L) } if (!missing(values) && !missing(labels)) { warning(".data and values and labels supplied, .data ignored") } else { values <- .data_values labels <- as.character(.data_labels) } } if (!(length(values) == length(labels) && length(values) == length(rect_text_labels))) { stop("values, labels, fill_colours, and rect_text_labels must all have same length") } if (rect_width > 1) warning("rect_Width > 1, your chart may look terrible") number_of_rectangles <- length(values) north_edge <- cumsum(values) south_edge <- c(0, cumsum(values)[-length(values)]) # fill by sign means rectangles' fill colour is given by whether they are going up or down gg_color_hue <- function(n) { hues = seq(15, 375, length = n + 1) grDevices::hcl(h = hues, l = 65, c = 100)[seq_len(n)] } if(fill_by_sign){ if (!is.null(fill_colours)){ warning("fill_colours is given but fill_by_sign is TRUE so fill_colours will be ignored.") } fill_colours <- ifelse(values >= 0, gg_color_hue(2)[2], gg_color_hue(2)[1]) } else { if (is.null(fill_colours)){ fill_colours <- gg_color_hue(number_of_rectangles) } } # Check if length of rectangle border colors matches the number of rectangles rect_border_matching <- length(rect_border) == number_of_rectangles if (!(rect_border_matching || length(rect_border) == 1)) { stop("rect_border must be a single colour or one colour for each rectangle") } if(!(grepl("^[lrc]", lines_anchors[1]) && grepl("^[lrc]", lines_anchors[2]))) # left right center stop("lines_anchors must be a pair of any of the following: left, right, centre") if (grepl("^l", lines_anchors[1])) anchor_left <- rect_width / 2 if (grepl("^c", lines_anchors[1])) anchor_left <- 0 if (grepl("^r", lines_anchors[1])) anchor_left <- -1 * rect_width / 2 if (grepl("^l", lines_anchors[2])) anchor_right <- -1 * rect_width / 2 if (grepl("^c", lines_anchors[2])) anchor_right <- 0 if (grepl("^r", lines_anchors[2])) anchor_right <- rect_width / 2 if (!calc_total) { p <- if (scale_y_to_waterfall) { ggplot2::ggplot(data.frame(x = c(labels, labels), y = c(south_edge, north_edge)), ggplot2::aes_string(x = "x", y = "y")) } else { ggplot2::ggplot(data.frame(x = labels, y = values), ggplot2::aes_string(x = "x", y = "y")) } p <- p + ggplot2::geom_blank() + ggplot2::theme(axis.title = ggplot2::element_blank()) } else { p <- if (scale_y_to_waterfall) { ggplot2::ggplot(data.frame(x = c(labels, total_axis_text, labels, total_axis_text), y = c(south_edge, north_edge, south_edge[number_of_rectangles], north_edge[number_of_rectangles])), ggplot2::aes_string(x = "x", y = "y")) } else { ggplot2::ggplot(data.frame(x = c(labels, total_axis_text), y = c(values, north_edge[number_of_rectangles])), ggplot2::aes_string(x = "x", y = "y")) } p <- p + ggplot2::geom_blank() + ggplot2::theme(axis.title = ggplot2::element_blank()) } if (grepl("behind", draw_axis.x)){ p <- p + ggplot2::geom_hline(yintercept = 0) } for (i in seq_along(values)){ p <- p + ggplot2::annotate("rect", xmin = i - rect_width/2, xmax = i + rect_width/2, ymin = south_edge[i], ymax = north_edge[i], colour = rect_border[[if (rect_border_matching) i else 1]], fill = fill_colours[i]) if (i > 1 && draw_lines){ p <- p + ggplot2::annotate("segment", x = i - 1 - anchor_left, xend = i + anchor_right, linetype = linetype, y = south_edge[i], yend = south_edge[i]) } } # rect_text_labels for (i in seq_along(values)){ if(abs(values[i]) > put_rect_text_outside_when_value_below){ p <- p + ggplot2::annotate("text", x = i, y = 0.5 * (north_edge[i] + south_edge[i]), family = theme_text_family, label = ifelse(rect_text_labels[i] == values[i], ifelse(values[i] < 0, paste0("\U2212", -1 * values[i]), values[i]), rect_text_labels[i]), size = rect_text_size/(5/14)) } else { p <- p + ggplot2::annotate("text", x = i, y = north_edge[i], family = theme_text_family, label = ifelse(rect_text_labels[i] == values[i], ifelse(values[i] < 0, paste0("\U2212", -1 * values[i]), values[i]), rect_text_labels[i]), vjust = ifelse(values[i] >= 0, -0.2, 1.2), size = rect_text_size/(5/14)) } } if (calc_total){ p <- p + ggplot2::annotate("rect", xmin = number_of_rectangles + 1 - rect_width/2, xmax = number_of_rectangles + 1 + rect_width/2, ymin = 0, ymax = north_edge[number_of_rectangles], colour = total_rect_border_color, fill = total_rect_color) + ggplot2::annotate("text", x = number_of_rectangles + 1, y = 0.5 * north_edge[number_of_rectangles], family = theme_text_family, label = ifelse(total_rect_text == sum(values), ifelse(north_edge[number_of_rectangles] < 0, paste0("\U2212", -1 * north_edge[number_of_rectangles]), north_edge[number_of_rectangles]), total_rect_text), color = total_rect_text_color, size = rect_text_size/(5/14)) + ggplot2::scale_x_discrete(labels = c(labels, total_axis_text)) if (draw_lines){ p <- p + ggplot2::annotate("segment", x = number_of_rectangles - anchor_left, xend = number_of_rectangles + 1 + anchor_right, y = north_edge[number_of_rectangles], yend = north_edge[number_of_rectangles], linetype = linetype) } } else { p <- p + ggplot2::scale_x_discrete(labels = labels) } if (grepl("front", draw_axis.x)){ p <- p + ggplot2::geom_hline(yintercept = 0) } if (print_plot){ # Allow modifications beyond the function call if (ggplot_object_name %in% ls(.GlobalEnv)) warning("Overwriting ", ggplot_object_name, " in global environment.") assign(ggplot_object_name, p, inherits = TRUE) print(p) } else { return(p) } }
/scratch/gouwar.j/cran-all/cranData/waterfalls/R/waterfall.R
#' Al10SABI algorithm #' #' Applies the Al10SABI algorithm #' #' @param w857 numeric. Value at wavelength of 857 nm #' @param w644 numeric. Value at wavelength of 644 nm #' @param w458 numeric. Value at wavelength of 458 nm #' @param w529 numeric. Value at wavelength of 529 nm #' #' @return SpatRaster or numeric #' #' @references Alawadi, F. Detection of surface algal blooms using the newly developed algorithm surface algal bloom index (SABI). Proc. SPIE 2010, 7825. #' #' @family algorithms #' @export Al10SABI <- function(w857, w644, w458, w529){ (w857 - w644) / (w458 + w529) } #' Am092Bsub algorithm #' #' Applies the Am092Bsub algorithm #' #' @param w681 numeric. Value at wavelength of 681 nm #' @param w665 numeric. Value at wavelength of 665 nm #' #' @return SpatRaster or numeric #' #' @references Amin, R.; Zhou, J.; Gilerson, A.; Gross, B.; Moshary, F.; Ahmed, S. Novel optical techniques for detecting and classifying toxic dinoflagellate Karenia brevis blooms using satellite imagery. Opt. Express 2009, 17, 9126–9144. #' #' @family algorithms #' @export Am092Bsub <- function(w681, w665){ w681 - w665 } #' Am09KBBI algorithm #' #' Applies the Am09KBBI algorithm #' #' @param w686 numeric. Value at wavelength of 686 nm #' @param w658 numeric. Value at wavelength of 658 nm #' #' @return SpatRaster or numeric #' #' @references Amin, R.; Zhou, J.; Gilerson, A.; Gross, B.; Moshary, F.; Ahmed, S.; Novel optical techniques for detecting and classifying toxic dinoflagellate Karenia brevis blooms using satellite imagery, Optics Express, 2009, 17, 11, 1-13. #' #' @family algorithms #' @export Am09KBBI <- function(w686, w658){ (w686 - w658)/(w686 + w658) } #' Be16FLHblue_WV2 algorithm #' #' Applies the Be16FLHblue_WV2 algorithm #' #' @param w529 numeric. Value at wavelength of 529 nm #' @param w644 numeric. Value at wavelength of 644 nm #' @param w458 numeric. Value at wavelength of 458 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.A. and 22 others; Comparison of satellite reflectance algorithms for estimating chlorophyll-a in a temperate reservoir using coincident hyperspectral aircraft imagery and dense coincident surface observations, Remote Sens. Environ., 2016, 178, 15-30. #' #' @family algorithms #' @export Be16FLHblue_WV2 <- function(w529, w644, w458){ (w529) - (w644 + (w458 - w644)*((546-478)/(659-478))) } #' Be16FLHblue_S2 algorithm #' #' Applies the Be16FLHblue_S2 algorithm #' #' @param w529 numeric. Value at wavelength of 529 nm #' @param w644 numeric. Value at wavelength of 644 nm #' @param w458 numeric. Value at wavelength of 458 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.A. and 22 others; Comparison of satellite reflectance algorithms for estimating chlorophyll-a in a temperate reservoir using coincident hyperspectral aircraft imagery and dense coincident surface observations, Remote Sens. Environ., 2016, 178, 15-30. #' #' @family algorithms #' @export Be16FLHblue_S2 <- function(w529, w644, w458){ (w529) - (w644 + (w458 - w644)*((560-490)/(665-490))) } #' Be16FLHblue_LS8 algorithm #' #' Applies the Be16FLHblue_LS8 algorithm #' #' @param w529 numeric. Value at wavelength of 529 nm #' @param w644 numeric. Value at wavelength of 644 nm #' @param w458 numeric. Value at wavelength of 458 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.A. and 22 others; Comparison of satellite reflectance algorithms for estimating chlorophyll-a in a temperate reservoir using coincident hyperspectral aircraft imagery and dense coincident surface observations, Remote Sens. Environ., 2016, 178, 15-30. #' #' @family algorithms #' @export Be16FLHblue_LS8 <- function(w529, w644, w458){ (w529) - (w644 + (w458 - w644)*((563-483)/(655-483))) } #' Be16FLHblue_MERIS algorithm #' #' Applies the Be16FLHblue_MERIS algorithm #' #' @param w529 numeric. Value at wavelength of 529 nm #' @param w644 numeric. Value at wavelength of 644 nm #' @param w458 numeric. Value at wavelength of 458 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.A. and 22 others; Comparison of satellite reflectance algorithms for estimating chlorophyll-a in a temperate reservoir using coincident hyperspectral aircraft imagery and dense coincident surface observations, Remote Sens. Environ., 2016, 178, 15-30. #' #' @family algorithms #' @export Be16FLHblue_MERIS <- function(w529, w644, w458){ (w529) - (w644 + (w458 - w644)*((510-442)/(665-442))) } #' Be16FLHblue_OLCI algorithm #' #' Applies the Be16FLHblue_OLCI algorithm #' #' @param w529 numeric. Value at wavelength of 529 nm #' @param w644 numeric. Value at wavelength of 644 nm #' @param w458 numeric. Value at wavelength of 458 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.A. and 22 others; Comparison of satellite reflectance algorithms for estimating chlorophyll-a in a temperate reservoir using coincident hyperspectral aircraft imagery and dense coincident surface observations, Remote Sens. Environ., 2016, 178, 15-30. #' #' @family algorithms #' @export Be16FLHblue_OLCI <- function(w529, w644, w458){ (w529) - (w644 + (w458 - w644)*((510-443)/(665-443))) } #' Be16FLHviolet_WV2 algorithm #' #' Applies the Be16FLHviolet_WV2 algorithm #' #' @param w529 numeric. Value at wavelength of 529 nm #' @param w644 numeric. Value at wavelength of 644 nm #' @param w458 numeric. Value at wavelength of 429 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.A. and 22 others; Comparison of satellite reflectance algorithms for estimating chlorophyll-a in a temperate reservoir using coincident hyperspectral aircraft imagery and dense coincident surface observations, Remote Sens. Environ., 2016, 178, 15-30. #' #' @family algorithms #' @export Be16FLHviolet_WV2 <- function(w529, w644, w458){ (w529) - (w644 + (w458 - w644)*((546-427)/(659-427))) } #' Be16FLHviolet_S2 algorithm #' #' Applies the Be16FLHviolet_S2 algorithm #' #' @param w529 numeric. Value at wavelength of 529 nm #' @param w644 numeric. Value at wavelength of 644 nm #' @param w458 numeric. Value at wavelength of 429 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.A. and 22 others; Comparison of satellite reflectance algorithms for estimating chlorophyll-a in a temperate reservoir using coincident hyperspectral aircraft imagery and dense coincident surface observations, Remote Sens. Environ., 2016, 178, 15-30. #' #' @family algorithms #' @export Be16FLHviolet_S2 <- function(w529, w644, w458){ (w529) - (w644 + (w458 - w644)*((560-443)/(665-443))) } #' Be16FLHviolet_LS8 algorithm #' #' Applies the Be16FLHviolet_LS8 algorithm #' #' @param w529 numeric. Value at wavelength of 529 nm #' @param w644 numeric. Value at wavelength of 644 nm #' @param w458 numeric. Value at wavelength of 429 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.A. and 22 others; Comparison of satellite reflectance algorithms for estimating chlorophyll-a in a temperate reservoir using coincident hyperspectral aircraft imagery and dense coincident surface observations, Remote Sens. Environ., 2016, 178, 15-30. #' #' @family algorithms #' @export Be16FLHviolet_LS8 <- function(w529, w644, w458){ (w529) - (w644 + (w458 - w644)*((563-443)/(655-443))) } #' Be16FLHviolet_MERIS algorithm #' #' Applies the Be16FLHviolet_MERIS algorithm #' #' @param w529 numeric. Value at wavelength of 529 nm #' @param w644 numeric. Value at wavelength of 644 nm #' @param w458 numeric. Value at wavelength of 429 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.A. and 22 others; Comparison of satellite reflectance algorithms for estimating chlorophyll-a in a temperate reservoir using coincident hyperspectral aircraft imagery and dense coincident surface observations, Remote Sens. Environ., 2016, 178, 15-30. #' #' @family algorithms #' @export Be16FLHviolet_MERIS <- function(w529, w644, w458){ (w529) - (w644 + (w458 - w644)*((510-412)/(665-412))) } #' Be16FLHviolet_OLCI algorithm #' #' Applies the Be16FLHviolet_OLCI algorithm #' #' @param w529 numeric. Value at wavelength of 529 nm #' @param w644 numeric. Value at wavelength of 644 nm #' @param w458 numeric. Value at wavelength of 429 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.A. and 22 others; Comparison of satellite reflectance algorithms for estimating chlorophyll-a in a temperate reservoir using coincident hyperspectral aircraft imagery and dense coincident surface observations, Remote Sens. Environ., 2016, 178, 15-30. #' #' @family algorithms #' @export Be16FLHviolet_OLCI <- function(w529, w644, w458){ (w529) - (w644 + (w458 - w644)*((510-413)/(665-413))) } #' Be16NDPhyI algorithm #' #' Applies the Be16NDPhyI algorithm #' #' @param w700 numeric. Value at wavelength of 700 nm #' @param w622 numeric. Value at wavelength of 622 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be16NDPhyI <- function(w700, w622){ (w700 - w622) / (w700 + w622) } #' De933BDA algorithm #' #' Applies the De933BDA algorithm #' #' @param w600 numeric. Value at wavelength of 600 nm #' @param w648 numeric. Value at wavelength of 648 nm #' @param w625 numeric. Value at wavelength of 625 nm #' #' @return SpatRaster or numeric #' #' @references Dekker, A.; Detection of the optical water quality parameters for eutrophic waters by high resolution remote sensing, Ph.D. thesis, 1993, Free University, Amsterdam. #' #' @family algorithms #' @export De933BDA <- function(w600, w648, w625){ (w600 - w648 - w625) } #' Gi033BDA algorithm #' #' Applies the Gi033BDA algorithm #' #' @param w672 numeric. Value at wavelength of 672 nm #' @param w715 numeric. Value at wavelength of 715 nm #' @param w757 numeric. Value at wavelength of 757 nm #' #' @return SpatRaster or numeric #' #' @references Gitelson, A.A.; U. Gritz, and M. N. Merzlyak.; Relationships between leaf chlorophyll content and spectral reflectance and algorithms for non-destructive chlorophyll assessment in higher plant leaves. J. Plant Phys. 2003, 160, 271-282. #' #' @family algorithms #' @export Gi033BDA <- function(w672, w715, w757){ ((1 / w672) - (1 / w715)) * (w757) } #' Go04MCI algorithm #' #' Applies the Go04MCI algorithm #' #' @param w709 numeric. Value at wavelength of 709 nm #' @param w681 numeric. Value at wavelength of 681 nm #' @param w753 numeric. Value at wavelength of 753 nm #' #' @return SpatRaster or numeric #' #' @references Gower, J.F.R.; Brown,L.; Borstad, G.A.; Observation of chlorophyll fluorescence in west coast waters of Canada using the MODIS satellite sensor. Can. J. Remote Sens., 2004, 30 (1), 17–25. #' #' @family algorithms #' @export Go04MCI <- function(w709, w681, w753){ (w709-w681-(w753-w681)*((709-681)/(753-681))) } #' HU103BDA algorithm #' #' Applies the HU103BDA algorithm #' #' @param w615 numeric. Value at wavelength of 615 nm #' @param w600 numeric. Value at wavelength of 600 nm #' @param w725 numeric. Value at wavelength of 725 nm #' #' @return SpatRaster or numeric #' #' @references Hunter, P.D.; Tyler, A.N.; Willby, N.J.; Gilvear, D.J.; The spatial dynamics of vertical migration by Microcystis aeruginosa in a eutrophic shallow lake: A case study using high spatial resolution time-series airborne remote sensing. Limn. Oceanogr. 2008, 53, 2391-2406. #' #' @family algorithms #' @export HU103BDA <- function(w615, w600, w725){ (((1/w615)-(1/w600))-w725) } #' Kn07KIVU algorithm #' #' Applies the Kn07KIVU algorithm #' #' @param w458 numeric. Value at wavelength of 458 nm #' @param w644 numeric. Value at wavelength of 644 nm #' @param w529 numeric. Value at wavelength of 529 nm #' #' @return SpatRaster or numeric #' #' @references Kneubuhler, M.; Frank T.; Kellenberger, T.W; Pasche N.; Schmid M.; Mapping chlorophyll-a in Lake Kivu with remote sensing methods. 2007, Proceedings of the Envisat Symposium 2007, Montreux, Switzerland 23–27 April 2007 (ESA SP-636, July 2007). #' #' @family algorithms #' @export Kn07KIVU <- function(w458, w644, w529){ (w458-w644)/(w529) } #' MI092BDA algorithm #' #' Applies the MI092BDA algorithm #' #' @param w700 numeric. Value at wavelength of 700 nm #' @param w600 numeric. Value at wavelength of 600 nm #' #' @return SpatRaster or numeric #' #' @references Mishra, S.; Mishra, D.R.; Schluchter, W. M., A novel algorithm for predicting PC concentrations in cyanobacteria: A proximal hyperspectral remote sensing approach. Remote Sens., 2009, 1, 758–775. #' #' @family algorithms #' @export MI092BDA <- function(w700, w600){ w700/w600 } #' MM092BDA algorithm #' #' Applies the MM092BDA algorithm #' #' @param w724 numeric. Value at wavelength of 724 nm #' @param w600 numeric. Value at wavelength of 600 nm #' #' @return SpatRaster or numeric #' #' @references Mishra, S.; Mishra, D.R.; Schluchter, W. M., A novel algorithm for predicting PC concentrations in cyanobacteria: A proximal hyperspectral remote sensing approach. Remote Sens., 2009, 1, 758–775. #' #' @family algorithms #' @export MM092BDA <- function(w724, w600){ w724/w600 } #' MM12NDCI algorithm #' #' Applies the MM12NDCI algorithm #' #' @param w715 numeric. Value at wavelength of 714 nm #' @param w686 numeric. Value at wavelength of 686 nm #' #' @return SpatRaster or numeric #' #' @references Mishra, S.; and Mishra, D.R. Normalized difference chlorophyll index: A novel model for remote estimation of chlorophyll-a concentration in turbid productive waters, Remote Sens. Environ., 2012, 117, 394-406. #' #' @family algorithms #' @export MM12NDCI <- function(w715, w686){ (w715 - w686) / (w715 + w686) } #' MM143BDAopt algorithm #' #' Applies the MM143BDAopt algorithm #' #' @param w629 numeric. Value at wavelength of 629 nm #' @param w659 numeric. Value at wavelength of 659 nm #' @param w724 numeric. Value at wavelength of 724 nm #' #' @return SpatRaster or numeric #' #' @references Mishra, S.; Mishra, D.R.; A novel remote sensing algorithm to quantify phycocyanin in cyanobacterial algal blooms, Env. Res. Lett., 2014, 9 (11), DOI:10.1088/1748-9326/9/11/114003 #' #' @family algorithms #' @export MM143BDAopt <- function(w629, w659, w724){ ((1/w629)-(1/w659))*(w724) } #' SI052BDA algorithm #' #' Applies the SI052BDA algorithm #' #' @param w709 numeric. Value at wavelength of 709 nm #' @param w620 numeric. Value at wavelength of 620 nm #' #' @return SpatRaster or numeric #' #' @references Simis, S. G. H.; Peters, S.W. M.; Gons, H. J.; Remote sensing of the cyanobacteria pigment phycocyanin in turbid inland water. Limn. Oceanogr., 2005, 50, 237–245. #' #' @family algorithms #' @export SI052BDA <- function(w709, w620){ (w709/w620) } #' SM122BDA algorithm #' #' Applies the SM122BDA algorithm #' #' @param w709 numeric. Value at wavelength of 709 nm #' @param w600 numeric. Value at wavelength of 600 nm #' #' @return SpatRaster or numeric #' #' @references Mishra, S. Remote sensing of cyanobacteria in turbid productive waters, PhD Dissertation. Mississippi State University, USA. 2012. #' #' @family algorithms #' @export SM122BDA <- function(w709, w600){ (w709/w600) } #' SY002BDA algorithm #' #' Applies the SY002BDA algorithm #' #' @param w650 numeric. Value at wavelength of 650 nm #' @param w625 numeric. Value at wavelength of 625 nm #' #' @return SpatRaster or numeric #' #' @references Schalles, J.; Yacobi, Y. Remote detection and seasonal patterns of phycocyanin, carotenoid and chlorophyll-a pigments in eutrophic waters. Archiv fur Hydrobiologie, Special Issues Advances in Limnology, 2000, 55,153–168. #' #' @family algorithms #' @export SY002BDA <- function(w650, w625){ (w650/w625) } #' Be16NDTIblue algorithm #' #' Applies the Be16NDTIblue algorithm #' #' @param w658 numeric. Value at wavelength of 658 nm #' @param w458 numeric. Value at wavelength of 458 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be16NDTIblue <- function(w658, w458){ (w658-w458)/(w658+w458) } #' Be16NDTIviolet algorithm #' #' Applies the Be16NDTIviolet algorithm #' #' @param w658 numeric. Value at wavelength of 658 nm #' @param w444 numeric. Value at wavelength of 444 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be16NDTIviolet <- function(w658, w444){ (w658-w444)/(w658+w444) } #' Be16FLHBlueRedNIR_WV2 algorithm #' #' Applies the Be16FLHBlueRedNIR_WV2 algorithm #' #' @param w658 numeric. Value at wavelength of 658 nm #' @param w857 numeric. Value at wavelength of 857 nm #' @param w458 numeric. Value at wavelength of 458 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be16FLHBlueRedNIR_WV2 <- function(w658, w857, w458){ (w658)-(w857+(w458-w857)*((659-478)/(833-478))) } #' Be16FLHBlueRedNIR_S2 algorithm #' #' Applies the Be16FLHBlueRedNIR_S2 algorithm #' #' @param w658 numeric. Value at wavelength of 658 nm #' @param w857 numeric. Value at wavelength of 857 nm #' @param w458 numeric. Value at wavelength of 458 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be16FLHBlueRedNIR_S2 <- function(w658, w857, w458){ (w658)-(w857+(w458-w857)*((665-490)/(865-490))) } #' Be16FLHBlueRedNIR_LS8 algorithm #' #' Applies the Be16FLHBlueRedNIR_LS8 algorithm #' #' @param w658 numeric. Value at wavelength of 658 nm #' @param w857 numeric. Value at wavelength of 857 nm #' @param w458 numeric. Value at wavelength of 458 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be16FLHBlueRedNIR_LS8 <- function(w658, w857, w458){ (w658)-(w857+(w458-w857)*((655-483)/(865-483))) } #' Be16FLHBlueRedNIR_MERIS algorithm #' #' Applies the Be16FLHBlueRedNIR_MERIS algorithm #' #' @param w658 numeric. Value at wavelength of 658 nm #' @param w857 numeric. Value at wavelength of 857 nm #' @param w458 numeric. Value at wavelength of 458 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be16FLHBlueRedNIR_MERIS <- function(w658, w857, w458){ (w658)-(w857+(w458-w857)*((665-442)/(865-442))) } #' Be16FLHBlueRedNIR_OLCI algorithm #' #' Applies the Be16FLHBlueRedNIR_OLCI algorithm #' #' @param w658 numeric. Value at wavelength of 658 nm #' @param w857 numeric. Value at wavelength of 857 nm #' @param w458 numeric. Value at wavelength of 458 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be16FLHBlueRedNIR_OLCI <- function(w658, w857, w458){ (w658)-(w857+(w458-w857)*((665-443)/(865-443))) } #' Be16FLHGreenRedNIR_WV2 algorithm #' #' Applies the Be16FLHGreenRedNIR_WV2 algorithm #' #' @param w658 numeric. Value at wavelength of 658 nm #' @param w857 numeric. Value at wavelength of 857 nm #' @param w558 numeric. Value at wavelength of 558 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be16FLHGreenRedNIR_WV2 <- function(w658, w857, w558){ (w658)-(w857+(w558-w857)*((659-546)/(833-546))) } #' Be16FLHGreenRedNIR_S2 algorithm #' #' Applies the Be16FLHGreenRedNIR_S2 algorithm #' #' @param w658 numeric. Value at wavelength of 658 nm #' @param w857 numeric. Value at wavelength of 857 nm #' @param w558 numeric. Value at wavelength of 558 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be16FLHGreenRedNIR_S2 <- function(w658, w857, w558){ (w658)-(w857+(w558-w857)*((665-560)/(865-560))) } #' Be16FLHGreenRedNIR_LS8 algorithm #' #' Applies the Be16FLHGreenRedNIR_LS8 algorithm #' #' @param w658 numeric. Value at wavelength of 658 nm #' @param w857 numeric. Value at wavelength of 857 nm #' @param w558 numeric. Value at wavelength of 558 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be16FLHGreenRedNIR_LS8 <- function(w658, w857, w558){ (w658)-(w857+(w558-w857)*((665-563)/(865-563))) } #' Be16FLHGreenRedNIR_MERIS algorithm #' #' Applies the Be16FLHGreenRedNIR_MERIS algorithm #' #' @param w658 numeric. Value at wavelength of 658 nm #' @param w857 numeric. Value at wavelength of 857 nm #' @param w558 numeric. Value at wavelength of 558 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be16FLHGreenRedNIR_MERIS <- function(w658, w857, w558){ (w658)-(w857+(w558-w857)*((665-560)/(865-560))) } #' Be16FLHGreenRedNIR_OLCI algorithm #' #' Applies the Be16FLHGreenRedNIR_OLCI algorithm #' #' @param w658 numeric. Value at wavelength of 658 nm #' @param w857 numeric. Value at wavelength of 857 nm #' @param w558 numeric. Value at wavelength of 558 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be16FLHGreenRedNIR_OLCI <- function(w658, w857, w558){ (w658)-(w857+(w558-w857)*((665-560)/(865-560))) } #' Be16FLHVioletRedNIR_WV2 algorithm #' #' Applies the Be16FLHVioletRedNIR_WV2 algorithm #' #' @param w658 numeric. Value at wavelength of 658 nm #' @param w857 numeric. Value at wavelength of 857 nm #' @param w444 numeric. Value at wavelength of 444 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be16FLHVioletRedNIR_WV2 <- function(w658, w857, w444){ (w658)-(w857+(w444-w857)*((659-427)/(833-427))) } #' Be16FLHVioletRedNIR_S2 algorithm #' #' Applies the Be16FLHVioletRedNIR_S2 algorithm #' #' @param w658 numeric. Value at wavelength of 658 nm #' @param w857 numeric. Value at wavelength of 857 nm #' @param w444 numeric. Value at wavelength of 444 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be16FLHVioletRedNIR_S2 <- function(w658, w857, w444){ (w658)-(w857+(w444-w857)*((659-443)/(833-443))) } #' Be16FLHVioletRedNIR_LS8 algorithm #' #' Applies the Be16FLHVioletRedNIR_LS8 algorithm #' #' @param w658 numeric. Value at wavelength of 658 nm #' @param w857 numeric. Value at wavelength of 857 nm #' @param w444 numeric. Value at wavelength of 444 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be16FLHVioletRedNIR_LS8 <- function(w658, w857, w444){ (w658)-(w857+(w444-w857)*((659-443)/(833-443))) } #' Be16FLHVioletRedNIR_MERIS algorithm #' #' Applies the Be16FLHVioletRedNIR_MERIS algorithm #' #' @param w658 numeric. Value at wavelength of 658 nm #' @param w857 numeric. Value at wavelength of 857 nm #' @param w444 numeric. Value at wavelength of 444 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be16FLHVioletRedNIR_MERIS <- function(w658, w857, w444){ (w658)-(w857+(w444-w857)*((659-442)/(833-442))) } #' Be16FLHVioletRedNIR_OLCI algorithm #' #' Applies the Be16FLHVioletRedNIR_OLCI algorithm #' #' @param w658 numeric. Value at wavelength of 658 nm #' @param w857 numeric. Value at wavelength of 857 nm #' @param w444 numeric. Value at wavelength of 444 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be16FLHVioletRedNIR_OLCI <- function(w658, w857, w444){ (w658)-(w857+(w444-w857)*((659-443)/(833-443))) } #' Wy08CI algorithm #' #' Applies the Wy08CI algorithm #' #' @param w681 numeric. Value at wavelength of 681 nm #' @param w665 numeric. Value at wavelength of 665 nm #' @param w709 numeric. Value at wavelength of 709 nm #' #' @return SpatRaster or numeric #' #' @references Wynne, T. T., Stumpf, R. P., Tomlinson, M. C., Warner, R. A., Tester, P. A., Dyble, J.; Relating spectral shape to cyanobacterial blooms in the Laurentian Great Lakes. Int. J. Remote Sens., 2008, 29, 3665–3672. #' #' @family algorithms #' @export Wy08CI <- function(w681, w665, w709){ -1*(w681-w665-(w709-w665)*((681-665)/(708-665))) } #' Da052BDA algorithm #' #' Applies the Da052BDA algorithm #' #' @param w714 numeric. Value at wavelength of 714 nm #' @param w672 numeric. Value at wavelength of 672 nm #' #' @return SpatRaster or numeric #' #' @references Wynne, T. T., Stumpf, R. P., Tomlinson, M. C., Warner, R. A., Tester, P. A., Dyble, J.; Relating spectral shape to cyanobacterial blooms in the Laurentian Great Lakes. Int. J. Remote Sens., 2008, 29, 3665–3672. #' #' @family algorithms #' @export #' Da052BDA <- function(w714, w672){ (w714/w672) } #' Be162B643sub629 algorithm #' #' Applies the Be162B643sub629 algorithm #' #' @param w644 numeric. Value at wavelength of 644 nm #' @param w629 numeric. Value at wavelength of 729 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be162B643sub629 <- function(w644, w629){ (w644-w629) } #' Be162B700sub601 algorithm #' #' Applies the Be162B700sub601 algorithm #' #' @param w700 numeric. Value at wavelength of 700 nm #' @param w601 numeric. Value at wavelength of 601 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be162B700sub601 <- function(w700, w601){ (w700-w601) } #' Be162BsubPhy algorithm #' #' Applies the Be162BsubPhy algorithm #' #' @param w715 numeric. Value at wavelength of 715 nm #' @param w615 numeric. Value at wavelength of 615 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be162BsubPhy <- function(w715, w615){ (w715-w615) } #' Be16NDPhyI644over615 algorithm #' #' Applies the Be16NDPhyI644over615 algorithm #' #' @param w644 numeric. Value at wavelength of 644 nm #' @param w615 numeric. Value at wavelength of 615 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be16NDPhyI644over615 <- function(w644, w615){ (w644-w615)/(w644+w615) } #' Be16NDPhyI644over629 algorithm #' #' Applies the Be16NDPhyI644over629 algorithm #' #' @param w644 numeric. Value at wavelength of 644 nm #' @param w629 numeric. Value at wavelength of 629 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be16NDPhyI644over629 <- function(w644, w629){ (w644-w629)/(w644+w629) } #' Be16Phy2BDA644over629 algorithm #' #' Applies the Be16Phy2BDA644over629 algorithm #' #' @param w644 numeric. Value at wavelength of 644 nm #' @param w629 numeric. Value at wavelength of 629 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export Be16Phy2BDA644over629 <- function(w644, w629){ (w644/w629) } #' MM12NDCIalt algorithm #' #' Applies the MM12NDCIalt algorithm #' #' @param w700 numeric. Value at wavelength of 700 nm #' @param w658 numeric. Value at wavelength of 658 nm #' #' @return SpatRaster or numeric #' #' @references Mishra, S.; Mishra, D.R.; A novel remote sensing algorithm to quantify phycocyanin in cyanobacterial algal blooms, Env. Res. Lett., 2014, 9 (11), DOI:10.1088/1748-9326/9/11/114003 #' #' @family algorithms #' @export MM12NDCIalt <- function(w700, w658){ ((w700-w658)/(w700+w658)) } #' TurbBe16GreenPlusRedBothOverViolet algorithm #' #' Applies the TurbBe16GreenPlusRedBothOverViolet algorithm #' #' @param w558 numeric. Value at wavelength of 558 nm #' @param w658 numeric. Value at wavelength of 658 nm #' @param w444 numeric. Value at wavelength of 444 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export TurbBe16GreenPlusRedBothOverViolet <- function(w558, w658, w444){ ((w558+w658)/w444) } #' TurbBe16RedOverViolet algorithm #' #' Applies the TurbBe16RedOverViolet algorithm #' #' @param w658 numeric. Value at wavelength of 658 nm #' @param w444 numeric. Value at wavelength of 444 nm #' #' @return SpatRaster or numeric #' #' @references Beck, R.; Xu, M.; Zhan, S.; Liu, H.; Johansen, R.A.; Tong, S.; Yang, B.; Shu, S.; Wu, Q.; Wang, S.; Berling, K.; Murray, A.; Emery, E.; Reif, M.; Harwood, J.; Young, J.; Martin, M.; Stillings, G.; Stumpf, R.; Su, H.; Ye, Z.; Huang, Y. Comparison of Satellite Reflectance Algorithms for Estimating Phycocyanin Values and Cyanobacterial Total Biovolume in a Temperate Reservoir Using Coincident Hyperspectral Aircraft Imagery and Dense Coincident Surface Observations. Remote Sens. 2017, 9, 538. #' #' @family algorithms #' @export TurbBe16RedOverViolet <- function(w658, w444){ (w658/w444) } #' TurbBow06RedOverGreen algorithm #' #' Applies the TurbBow06RedOverGreen algorithm #' #' @param w658 numeric. Value at wavelength of 658 nm #' @param w558 numeric. Value at wavelength of 558 nm #' #' @return SpatRaster or numeric #' #' @references Bowers, D. G., and C. E. Binding. 2006. The Optical Properties of Mineral Suspended Particles: A Review and Synthesis.” Estuarine Coastal and Shelf Science 67 (1–2): 219–230. doi:10.1016/j.ecss.2005.11.010. #' #' @family algorithms #' @export TurbBow06RedOverGreen <- function(w658, w558){ (w658/w558) } #' TurbChip09NIROverGreen algorithm #' #' Applies the TurbChip09NIROverGreen algorithm #' #' @param w857 numeric. Value at wavelength of 857 nm #' @param w558 numeric. Value at wavelength of 558 nm #' #' @return SpatRaster or numeric #' #' @references Chipman, J. W.; Olmanson, L.G.; Gitelson, A.A.; Remote sensing methods for lake management: A guide for resource managers and decision-makers. 2009, Developed by the North American Lake Management Society in collaboration with Dartmouth College, University of Minnesota, and University of Nebraska for the United States Environmental Protection Agency. #' #' @family algorithms #' @export TurbChip09NIROverGreen <- function(w857, w558){ (w857/w558) } #' TurbDox02NIRoverRed algorithm #' #' Applies the TurbDox02NIRoverRed algorithm #' #' @param w857 numeric. Value at wavelength of 857 nm #' @param w658 numeric. Value at wavelength of 658 nm #' #' @return SpatRaster or numeric #' #' @references Doxaran, D., Froidefond, J.-M.; Castaing, P. ; A reflectance band ratio used to estimate suspended matter concentrations in sediment-dominated coastal waters, Remote Sens., 2002, 23, 5079-5085. #' #' @family algorithms #' @export TurbDox02NIRoverRed <- function(w857, w658){ (w857/w658) } #' TurbFrohn09GreenPlusRedBothOverBlue algorithm #' #' Applies the TurbFrohn09GreenPlusRedBothOverBlue algorithm #' #' @param w558 numeric. Value at wavelength of 558 nm #' @param w658 numeric. Value at wavelength of 658 nm #' @param w458 numeric. Value at wavelength of 458 nm #' #' @return SpatRaster or numeric #' #' @references Frohn, R. C., & Autrey, B. C. (2009). Water quality assessment in the Ohio River using new indices for turbidity and chlorophyll-a with Landsat-7 Imagery. Draft Internal Report, U.S. Environmental Protection Agency. #' #' @family algorithms #' @export TurbFrohn09GreenPlusRedBothOverBlue <- function(w558, w658, w458){ ((w558+w658)/w458) } #' TurbHarr92NIR algorithm #' #' Applies the TurbHarr92NIR algorithm #' #' @param w857 numeric. Value at wavelength of 857 nm #' #' @return SpatRaster or numeric #' #' @references Schiebe F.R., Harrington J.A., Ritchie J.C. Remote-Sensing of Suspended Sediments—the Lake Chicot, Arkansas Project. Int. J. Remote Sens. 1992;13:1487–1509. #' #' @family algorithms #' @export TurbHarr92NIR <- function(w857){ (w857) } #' TurbLath91RedOverBlue algorithm #' #' Applies the TurbLath91RedOverBlue algorithm #' #' @param w658 numeric. Value at wavelength of 658 nm #' @param w458 numeric. Value at wavelength of 458 nm #' #' @return SpatRaster or numeric #' #' @references Lathrop, R. G., Jr., T. M. Lillesand, and B. S. Yandell, 1991. Testing the utility of simple multi-date Thematic Mapper calibration algorithms for monitoring turbid inland waters. International Journal of Remote Sensing #' #' @family algorithms #' @export TurbLath91RedOverBlue <- function(w658, w458){ (w658/w458) } #' TurbMoore80Red algorithm #' #' Applies the TurbMoore80Red algorithm #' #' @param w658 numeric. Value at wavelength of 658 nm #' #' @return SpatRaster or numeric #' #' @references Moore, G.K., Satellite remote sensing of water turbidity, Hydrological Sciences, 1980, 25, 4, 407-422. #' #' @family algorithms #' @export TurbMoore80Red <- function(w658){ (w658) }
/scratch/gouwar.j/cran-all/cranData/waterquality/R/algorithms.R
#' Run linear model (lm) #' #'The function runs a linear model on a single water quality parameter and a water quality algorithm #' and returns a data frame containing the following: #' r^2, p-value, slope, and intercept of the model #' #' @param parameter A string specifying water quality parameter #' @param algorithm A string specifying water quality algorithm #' @param df data frame containing the values for parameter and algorithm arguments #' @return A data frame of the model results #' #' @references Johansen, Richard; et al. (2018). Evaluating the portability of satellite derived chlorophyll-a algorithms for temperate inland lakes using airborne hyperspectral imagery and dense surface observations. Harmful Algae. 76. 10.1016/j.hal.2018.05.001. #' @references R Core Team (2018). R: A language and environment for statistical computing. R Foundation for Statistical Computing, Vienna, Austria. URL https://www.R-project.org/. #' #' @family extract_lm #' @export extract_lm <- function(parameter, algorithm, df){ my_lm = lm(as.formula(paste(parameter, "~" ,algorithm)), data =df) R_Squared = summary(my_lm)$r.squared P_Value = summary(my_lm)$coefficients[8] Slope = summary(my_lm)$coefficients[2] Intercept = summary(my_lm)$coefficients[1] tibble::tibble(R_Squared = R_Squared, Slope = Slope, Intercept = Intercept, P_Value = P_Value) } #' Run linear model with crossvalidation #' #'The function runs a linear model on a single water quality parameter and a water quality algorithm and conducts #' a k-folds cross validation, which returns a data frame containing the following: #' The r^2, p-value, slope, intercept of the global lm model & #' average r^2, average RMSE, average MAE from the crossvalidated model #' #' @param parameter water quality parameter #' @param algorithm water quality algorithm #' @param df data frame containing the values for parameter and algorithm arguments #' @param train_method A string specifying which classification or regression model to use (Default = "lm"). See ?caret::train for more details #' @param control_method A string specifying the resampling method (Default = "repeatedcv"). See ?caret::trainControl for more details #' @param folds the number of folds to be used in the cross validation model #' @param nrepeats the number of iterations to be used in the cross validation model #' #' @return A data frame of the model results #' #' @references Johansen, Richard; et al. (2018). Evaluating the portability of satellite derived chlorophyll-a algorithms for temperate inland lakes using airborne hyperspectral imagery and dense surface observations. Harmful Algae. 76. 10.1016/j.hal.2018.05.001. #' @references R Core Team (2018). R: A language and environment for statistical computing. R Foundation for Statistical Computing, Vienna, Austria. URL https://www.R-project.org/. #' @references Max Kuhn. Contributions from Jed Wing, Steve Weston, Andre Williams, Chris Keefer, Allan Engelhardt, Tony Cooper, Zachary Mayer, Brenton Kenkel, the R Core Team, Michael Benesty, Reynald Lescarbeau, Andrew Ziem, Luca Scrucca, Yuan Tang, Can Candan and Tyler Hunt. (2018). caret: Classification and Regression Training. R package version 6.0-81. https://CRAN.R-project.org/package=caret #' #' @family extract_lm #' @export #' #' @importFrom stats lm as.formula na.exclude #' @importFrom caret trainControl train getTrainPerf #' extract_lm_cv <- function(parameter, algorithm, df, train_method = "lm", control_method = "repeatedcv", folds = 3, nrepeats =5){ if (!requireNamespace("caret", quietly = TRUE)) stop("package caret required, please install it first") my_formula = as.formula(paste(parameter, "~" ,algorithm)) caret_model = caret::train(form = my_formula, data = df, method = "lm", na.action = na.exclude, #repeated k-fold validation trControl = caret::trainControl(method = "repeatedcv", number = folds, repeats = nrepeats)) my_lm = caret_model$finalModel CV_R_Squared = caret::getTrainPerf(caret_model)[, "TrainRsquared"] RMSE = caret::getTrainPerf(caret_model)[, "TrainRMSE"] MAE = caret::getTrainPerf(caret_model)[, "TrainMAE"] R_Squared = summary(my_lm)$r.squared P_Value = summary(my_lm)$coefficients[8] Slope = summary(my_lm)$coefficients[2] Intercept = summary(my_lm)$coefficients[1] tibble::tibble(R_Squared = R_Squared, Slope = Slope, Intercept = Intercept, P_Value = P_Value, CV_R_Squared = CV_R_Squared, RMSE = RMSE, MAE = MAE) } #' Run linear model with crossvalidation over multiple independent and dependent variables #' #'The function runs a linear model on a list of x and list of y variables and conducts #' a k-folds cross validation, which returns a data frame containing the following: #' The r^2, p-value, slope, intercept of the global lm model & #' average r^2, average RMSE, average MAE from the crossvalidated model #' #' @param parameters the list of a water quality parameters to be evaluated #' @param algorithms the list of water quality algorithms to be evaluated #' @param df data frame containing the values for parameters and algorithms arguments #' @param train_method A string specifying which classification or regression model to use (Default = "lm"). See ?caret::train for more details #' @param control_method A string specifying the resampling method (Default = "repeatedcv"). See ?caret::trainControl for more details #' @param folds the number of folds to be used in the cross validation model #' @param nrepeats the number of iterations to be used in the cross validation model #' #' @return A data frame of the model results #' #' @references Johansen, Richard; et al. (2018). Evaluating the portability of satellite derived chlorophyll-a algorithms for temperate inland lakes using airborne hyperspectral imagery and dense surface observations. Harmful Algae. 76. 10.1016/j.hal.2018.05.001. #' @references R Core Team (2018). R: A language and environment for statistical computing. R Foundation for Statistical Computing, Vienna, Austria. URL https://www.R-project.org/. #' @references Max Kuhn. Contributions from Jed Wing, Steve Weston, Andre Williams, Chris Keefer, Allan Engelhardt, Tony Cooper, Zachary Mayer, Brenton Kenkel, the R Core Team, Michael Benesty, Reynald Lescarbeau, Andrew Ziem, Luca Scrucca, Yuan Tang, Can Candan and Tyler Hunt. (2018). caret: Classification and Regression Training. R package version 6.0-81. https://CRAN.R-project.org/package=caret #' #' @family extract_lm #' @export #' #' @importFrom purrr map_chr map_dfr #' extract_lm_cv_multi <- function(parameters, algorithms, df, train_method = "lm", control_method = "repeatedcv", folds = 3, nrepeats = 5){ if (!requireNamespace("caret", quietly = TRUE)) stop("package caret required, please install it first") list = list() for (i in seq_along(parameters)) { names(algorithms) <- algorithms %>% purrr::map_chr(., ~ paste0(parameters[[i]], "_",.)) list[[i]] = algorithms %>% purrr::map_dfr(~extract_lm_cv(parameter = parameters[[i]], algorithm = ., df = df, train_method = train_method, control_method = control_method, folds = folds, nrepeats = nrepeats), .id = "Algorithms") } extract_lm_cv_multi_results <- (do.call(rbind, list)) } #' Run linear model with crossvalidation over multiple dependent and all numeric independent variables in a data frame #' #'The function runs a linear model on a list of x and list of y variables and conducts #' a k-folds cross validation, which returns a data frame containing the following: #' The r^2, p-value, slope, intercept of the global lm model & #' average r^2, average RMSE, average MAE from the crossvalidated model #' #' @param parameters the list of dependent variables to be evaluated #' @param df data frame containing the values for parameter and algorithm arguments #' @param train_method A string specifying which classification or regression model to use (Default = "lm"). See ?caret::train for more details #' @param control_method A string specifying the resampling method (Default = "repeatedcv"). See ?caret::trainControl for more details #' @param folds the number of folds to be used in the cross validation model #' @param nrepeats the number of iterations to be used in the cross validation model #' #' @return A data frame of the model results #' #' @references Johansen, Richard; et al. (2018). Evaluating the portability of satellite derived chlorophyll-a algorithms for temperate inland lakes using airborne hyperspectral imagery and dense surface observations. Harmful Algae. 76. 10.1016/j.hal.2018.05.001. #' @references R Core Team (2018). R: A language and environment for statistical computing. R Foundation for Statistical Computing, Vienna, Austria. URL https://www.R-project.org/. #' @references Max Kuhn. Contributions from Jed Wing, Steve Weston, Andre Williams, Chris Keefer, Allan Engelhardt, Tony Cooper, Zachary Mayer, Brenton Kenkel, the R Core Team, Michael Benesty, Reynald Lescarbeau, Andrew Ziem, Luca Scrucca, Yuan Tang, Can Candan and Tyler Hunt. (2018). caret: Classification and Regression Training. R package version 6.0-81. https://CRAN.R-project.org/package=caret #' #' @family extract_lm #' @export #' #' @importFrom purrr map_chr map_dfr #' extract_lm_cv_all <- function(parameters, df, train_method = "lm", control_method = "repeatedcv", folds = 3, nrepeats = 5){ if (!requireNamespace("caret", quietly = TRUE)) stop("package caret required, please install it first") list = list() for (i in seq_along(parameters)) { algorithms = df %>% dplyr::select(which(sapply(., class) == "numeric"), -parameters) %>% names() names(algorithms) <- algorithms %>% purrr::map_chr(., ~ paste0(parameters[[i]], "_", .)) list[[i]] = algorithms %>% purrr::map_dfr(~extract_lm_cv(parameter = parameters[[i]], algorithm = ., df = df, train_method = train_method, control_method = control_method, folds = folds, nrepeats = nrepeats), .id = "Algorithms") } extract_lm_cv_all_results <- (do.call(rbind, list)) }
/scratch/gouwar.j/cran-all/cranData/waterquality/R/extract_lm_functions.R
#' Create waterquality Map with sampling points and optional histogram #' #'This function wraps the tmap package to help users generate fast and simple #'data visualization of their WQ_calc raster output along with optional #'geospatial objects and histogram #' #' @param WQ_raster Raster file generated from `wq_calc` or other GeoTiff file #' @param sample_points geospatial file (.shp or .gpkg) containing sampling locations #' @param map_title text used to generate title of map #' @param raster_style method to process the color scale when col is a numeric variable. Please refer to the style argument in the ?tmap::tm_raster() function for more details (Default is "quantile"). #' @param histogram Option to add or remove a histogram of the data values. (Default is TRUE) #' @return A data visualization of the results #' #' @family Map_WQ models #' @export Map_WQ_raster <- function(WQ_raster, sample_points, map_title, raster_style = "quantile", histogram = TRUE) { if (!requireNamespace("tmap", quietly = TRUE)) stop("package tmap required, please install it first") tmap::tm_shape(WQ_raster) + tmap::tm_raster(title = map_title, style = raster_style, n = 8, midpoint = NA, palette = "viridis", legend.reverse = TRUE, legend.hist = histogram) + tmap::tm_legend(outside = TRUE, hist.width = 2) + if(missing(sample_points)){ tmap::tm_scale_bar(text.size = 0.75) + tmap::tm_grid(labels.inside.frame = FALSE, labels.size = 1, n.x = 5, n.y = 5, projection = "+proj=longlat", alpha = 0.35) }else{ tmap::tm_shape(sample_points) + tmap::tm_dots(size = 0.1, alpha = 0.75) tmap::tm_scale_bar(text.size = 0.75) + tmap::tm_grid(labels.inside.frame = FALSE, labels.size = 1, n.x = 5, n.y = 5, projection = "+proj=longlat", alpha = 0.35) } }
/scratch/gouwar.j/cran-all/cranData/waterquality/R/map_wq.R
#' Pipe operator #' #' See \code{magrittr::\link[magrittr:pipe]{\%>\%}} for details. #' #' @name %>% #' @rdname pipe #' @keywords internal #' @export #' @importFrom magrittr %>% #' @usage lhs \%>\% rhs NULL
/scratch/gouwar.j/cran-all/cranData/waterquality/R/utils-pipe.R
#' @keywords internal "_PACKAGE" ## quiets concerns of R CMD check re: the .'s that appear in pipelines if(getRversion() >= "2.15.1") utils::globalVariables(c("."))
/scratch/gouwar.j/cran-all/cranData/waterquality/R/waterquality-package.R
#' wq_algorithms database #' #' A dataset containing the information about the water quality algorithms #' #' @format A tibble with 91 rows and 4 variables: #' * name: algorithm name #' * funs: algorithm function #' * satellite: satellite/instrument name ("worldview2", "sentinel2", "landsat8", "modis", or "meris") #' * bands: list of the bands used from the given satellite/instrument "wq_algorithms"
/scratch/gouwar.j/cran-all/cranData/waterquality/R/wq_algorithms.R
#' Water quality calculation #' #' Calculates a set of water quality indices #' #' @param terraRast Terra SpatRaster containing a satellite data #' @param alg Name (e.g. [Am09KBBI()]) or type of the algorithm ("chlorophyll", "phycocyanin", "turbidity") or "all" #' @param sat Name of the satellite or instrument ("worldview2", "sentinel2", "landsat8", "modis", "meris", or "OLCI") #' @param ... Other arguments passed on to [terra::rast()] #' #' @importFrom methods is #' #' @return SpatRaster #' #' @examples #' library(terra) #' #' # sentinel2 example #' s2 = terra::rast(system.file("raster/S2_Harsha.tif", package = "waterquality")) #' s2_Al10SABI = wq_calc(s2, alg = "Al10SABI", sat = "sentinel2") #' s2_two_alg = wq_calc(s2, alg = c("TurbChip09NIROverGreen", "Am092Bsub"), sat = "sentinel2") #' #' \dontrun{( #' s2_wq = wq_calc(s2, alg = "all", sat = "sentinel2") #' #' # landsat8 example #' l8 = terra::rast(system.file("raster/L8_Taylorsville.tif", package = "waterquality")) #' l8_wq = wq_calc(s2, alg = "all", sat = "landsat8") #' )} #' @export wq_calc = function(terraRast, alg = "all", sat, ...){ #if (!is(terraRast, 'rast')) stop ("Input object needs to be of the Terra Raster class") sats = c("worldview2", "sentinel2", "landsat8", "modis", "meris", "OLCI") if (!sat %in% sats) stop ("Unknown satellite or instrument.", "Please provide one of: 'worldview2', ", "'sentinel2', 'landsat8', 'modis', or 'meris'") if ("all" %in% alg){ algorithms_sel = waterquality::wq_algorithms } else if (any(c("chlorophyll", "phycocyanin", "turbidity") %in% alg)){ algorithms_sel = waterquality::wq_algorithms[waterquality::wq_algorithms$type %in% alg, ] } else{ algorithms_sel = waterquality::wq_algorithms[waterquality::wq_algorithms$name %in% alg, ] if (nrow(algorithms_sel) == 0) stop ("Unknown algorithm name/type: ", paste(alg, collapse = ", ")) alg_valid = alg %in% algorithms_sel$name if (!all(alg_valid)) warning("Some of the algorithms do not exist: ", paste(alg[!alg_valid], collapse = ", ")) } algorithms_sel = algorithms_sel[algorithms_sel$satellite == sat, ] if (nrow(algorithms_sel) == 0) stop ("Some of the algorithms are not ", "available for the selected satellite.\n", "Please provide appropriate algorithms' names") nr_of_bands = max(unlist(algorithms_sel$bands)) if (nr_of_bands > terra::nlyr(terraRast)) stop ("Terra Raster Stack for ", sat, " needs to have at least ", nr_of_bands, " layers") result = list() for (i in seq_len(nrow(algorithms_sel))){ terraRast_sel = terraRast[[algorithms_sel$bands[[i]]]] result[[i]] = terra::lapp(terraRast_sel, fun = algorithms_sel$funs[[i]]) names(result[[i]]) = algorithms_sel$name[[i]] cat(algorithms_sel$name[[i]], "calculated!\n") } terra::rast(result, ...) }
/scratch/gouwar.j/cran-all/cranData/waterquality/R/wq_calc.R
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>", echo = TRUE) ## ---- results='hide', message=FALSE, warning=FALSE---------------------------- library(waterquality) library(terra) Harsha <- terra::rast(system.file("raster/S2_Harsha.tif", package = "waterquality")) ## ----results='hide', message=FALSE, warning=FALSE----------------------------- Harsha_Am092Bsub <- wq_calc(terraRast = Harsha, alg = "MM12NDCI", sat = "sentinel2") ## ---- fig.height = 5, fig.width = 6------------------------------------------- terra::plot(Harsha_Am092Bsub) ## ----results='hide', message=FALSE, warning=FALSE----------------------------- Harsha_Multiple <- wq_calc(terraRast = Harsha, alg = c("MM12NDCI", "Am092Bsub", "Da052BDA"), sat = "sentinel2") ## ---- fig.height = 5, fig.width = 6------------------------------------------- terra::plot(Harsha_Multiple) ## ----results='hide', message=FALSE, warning=FALSE----------------------------- Harsha_PC <- wq_calc(Harsha, alg = "chlorophyll", sat = "sentinel2") ## ---- fig.height = 5, fig.width = 6------------------------------------------- terra::plot(Harsha_PC) ## ---- results='hide', message=FALSE, warning=FALSE---------------------------- Harsha_All <- wq_calc(Harsha, alg = "all", sat = "sentinel2") ## ----fig.height = 5, fig.width = 6-------------------------------------------- terra::plot(Harsha_All) # Only displays first 16 of 28 ## ---- results='hide', message=FALSE, warning=FALSE---------------------------- library(waterquality) library(terra) library(tmap) library(sf) s2 = terra::rast(system.file("raster/S2_Harsha.tif", package = "waterquality")) MM12NDCI = wq_calc(s2, alg = "MM12NDCI", sat = "sentinel2") samples = terra::vect(system.file("raster/Harsha_Simple_Points_CRS.gpkg", package = "waterquality")) lake_extent = terra::vect(system.file("raster/Harsha_Lake_CRS.gpkg", package = "waterquality")) ## ----fig.height = 5, fig.width = 6-------------------------------------------- Map_WQ_raster(WQ_raster = MM12NDCI, sample_points = samples, map_title= "Water Quality Map", raster_style = "quantile", histogram = TRUE) ## ---- eval = FALSE------------------------------------------------------------ # #Input raster image # wq_raster <- terra::rast("C:/temp/my_raster.tif") # # #Input shapefile # wq_samples <- terra::vect('C:/temp/my_samples.shp') # # #Extract values from raster and combine with shapefile # waterquality_data <- data.frame(wq_samples, terra::extract(wq_raster, wq_samples)) # # #Export results as csv file # write.csv(waterquality_data, file = "C:/temp/waterquality_data.csv") ## ---- results='hide', message=FALSE, warning=FALSE---------------------------- library(waterquality) library(caret) df <- read.csv(system.file("raster/waterquality_data.csv", package = "waterquality")) ## ---- message=FALSE, warning=FALSE-------------------------------------------- extract_lm(parameter = "Chl_ugL", algorithm = "MM12NDCI", df = df) ## ---- message=FALSE, warning=FALSE-------------------------------------------- extract_lm_cv(parameter = "Chl_ugL", algorithm = "MM12NDCI", df = df, train_method = "lm", control_method = "repeatedcv", folds = 3, nrepeats = 5) ## ---- message=FALSE, warning=FALSE-------------------------------------------- # Create series of strings to be used for parameters and algorithms arguments algorithms <- c(names(df[6:10])) parameters <- c(names(df[3:5])) extract_lm_cv_multi_results <- extract_lm_cv_multi(parameters = parameters, algorithms = algorithms, df = df, train_method = "lm", control_method = "repeatedcv", folds = 3, nrepeats = 5) head(extract_lm_cv_multi_results) ## ---- message=FALSE, warning=FALSE-------------------------------------------- extract_lm_cv_all_results <- extract_lm_cv_all(parameters = parameters, df = df, train_method = "lm", control_method = "repeatedcv", folds = 3, nrepeats = 5) head(extract_lm_cv_all_results)
/scratch/gouwar.j/cran-all/cranData/waterquality/inst/doc/waterquality_vignette.R
--- title: "Introduction to the waterquality package" author: "Richard Johansen, Jakub Nowosad, Molly Reif, and Erich Emery" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction to the waterquality package} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", echo = TRUE) ``` The main purpose of **waterquality** is to quickly and easily convert satellite-based reflectance imagery into one or many well-known water quality indices designed for the detection of harmful algal blooms (HABs) using the following pigment proxies: chlorophyll-a, blue-green algae (phycocyanin), and turbidity. Currently, this package is able to process [40 algorithms](https://rajohansen.github.io/waterquality/reference/index.html) for the following satellite-based imagers: WorldView-2 and -3, Sentinel-2, Landsat-8, MODIS, MERIS, and OLCI. In order to improve the aesthetics of the `wq_calc` output, a series of intuitive `Map_WQ` functions were developed to help reduce technical barriers due to coding and the myriad of map options. Additional functionality of the package includes a series of `extract_lm` functions which wrap the ["Fitting Linear Models"](https://www.rdocumentation.org/packages/stats/versions/3.6.2/topics/lm) and the ["caret"](http://topepo.github.io/caret/index.html) packages to quickly generate a suite of regression models with standardized outputs. These functions range from simple linear models for a single dependent and independent variable to robust linear regression using crossvalidation over multiple dependent and independent variables. These functions are extremely useful when conducting experimental testing on a large number of satellite algorithms across multiple water quality parameters. **NOTE** these functions require ground-truth data in order to develop the models. For an example of our entire research workflow, which includes data acquisition, image pre-processing, analyses, and results please see our publication entitled ["Waterquality: An Open-Source R Package for the Detection and Quantification of Cyanobacterial Harmful Algal Blooms and Water Quality"](https://erdc-library.erdc.dren.mil/jspui/bitstream/11681/35053/3/ERDC-EL%20TR-19-20.pdf). ## Algorithms Currently, the package includes a total of [40 algorithms](https://rajohansen.github.io/waterquality/reference/index.html) that can be applied for the detection of the three parameters. **NOTE** not all sensors are capable of using all algorithms due to their spectral configurations. Each of the algorithms are searchable within the package, where there is a reference to the original paper (Ex. `?Am092Bsub()`). Each algorithm is also linked to the original papers water quality parameters (chlorophyll-a, phycocyanin, turbidity) by type, which allows users to select all algorithms for that type. The final outputs are raster stacked images which represent relative index values and are not direct estimations of chlorophyll-a, phycocyanin, or turbidity values. However, relative index values can be converted to estimated concentration values using the `extract_lm` functions and ground truth measurements. ## Water Quality Functions ### wq_calc() The main function of this package is called `wq_calc()` which calculates water quality indices by using a reflectance raster stack as an input, user-defined algorithm(s) selection, and satellite configuration selection corresponding to the following three arguments: `terraRast`, `alg`, and `sat`. - `terraRast` - The input reflectance image to be used in band algorithm calculation. - `alg` - Determines the indices to be utilized: - Single Algorithm - Multiple Algorithm - Type of Algorithm - All Possible Algorithms - `sat` - Determines the appropriate spectral configuration and subsequently appropriate algorithms to be calculated from predefined list: - WorldView-2 - Sentinel-2 - Landsat-8 - MODIS - MERIS - OLCI #### Single Algorithm ```{r, results='hide', message=FALSE, warning=FALSE} library(waterquality) library(terra) Harsha <- terra::rast(system.file("raster/S2_Harsha.tif", package = "waterquality")) ``` ```{r,results='hide', message=FALSE, warning=FALSE} Harsha_Am092Bsub <- wq_calc(terraRast = Harsha, alg = "MM12NDCI", sat = "sentinel2") ``` ```{r, fig.height = 5, fig.width = 6} terra::plot(Harsha_Am092Bsub) ``` #### Multiple Algorithms ```{r,results='hide', message=FALSE, warning=FALSE} Harsha_Multiple <- wq_calc(terraRast = Harsha, alg = c("MM12NDCI", "Am092Bsub", "Da052BDA"), sat = "sentinel2") ``` ```{r, fig.height = 5, fig.width = 6} terra::plot(Harsha_Multiple) ``` #### Type of Algorithm ```{r,results='hide', message=FALSE, warning=FALSE} Harsha_PC <- wq_calc(Harsha, alg = "chlorophyll", sat = "sentinel2") ``` ```{r, fig.height = 5, fig.width = 6} terra::plot(Harsha_PC) ``` #### All Algorithms ```{r, results='hide', message=FALSE, warning=FALSE} Harsha_All <- wq_calc(Harsha, alg = "all", sat = "sentinel2") ``` ```{r,fig.height = 5, fig.width = 6} terra::plot(Harsha_All) # Only displays first 16 of 28 ``` ## Mapping Functions ### Map_WQ_raster This function wraps the ["tmap"](https://cran.r-project.org/package=tmap) package to help users to efficiently generate a map of a raster image which can be overlaid with optional geospatial objects and data histogram. In order to simplify this process and reduce the technical expertise required, the number of arguments were reduced to the following: - `WQ_raster` - Raster file generated from `wq_calc` or other GeoTiff file - `sample_points` - geospatial file (.shp or .gpkg) containing sampling locations - `map_title` - text used to generate title of map - `raster_style` - method to process the color scale when col is a numeric variable. Please refer to the style argument in the `?tmap::tm_raster()` function for more details (Default is "quantile"). - `histogram` - Option to add or remove a histogram of the data values. (Default is TRUE) #### Raster with points ```{r, results='hide', message=FALSE, warning=FALSE} library(waterquality) library(terra) library(tmap) library(sf) s2 = terra::rast(system.file("raster/S2_Harsha.tif", package = "waterquality")) MM12NDCI = wq_calc(s2, alg = "MM12NDCI", sat = "sentinel2") samples = terra::vect(system.file("raster/Harsha_Simple_Points_CRS.gpkg", package = "waterquality")) lake_extent = terra::vect(system.file("raster/Harsha_Lake_CRS.gpkg", package = "waterquality")) ``` ```{r,fig.height = 5, fig.width = 6} Map_WQ_raster(WQ_raster = MM12NDCI, sample_points = samples, map_title= "Water Quality Map", raster_style = "quantile", histogram = TRUE) ``` ## Modeling Functions Developing models is an essential step in water quality monitoring, and this requires sufficient coincident ground truth data. These functions have been developed to combine user-provided ground truth data and the results from the `wq_calc` function to generate a single or series of regression models. These functions have been developed to easily conduct linear models with standardized outputs, providing intuitive yet robust options. Most effectively, the functions will utilize a single comma delimited (.csv) file as the data frame source. Although these functions were designed for our water quality research, they can be used as standalone functions for any data to generate the same standardized outputs containing the following: **Global Model** - r^2^ - p-value - slope - intercept **Crossvalidated Model** - average r^2^ - average RMSE - average MAE Additionally, we have provided code that might be useful to help users import and extract the data from a raster stack image (i.e. output from `wq_calc`), combine it with a geospatial object (i.e shapefiles of sample locations), and export the results to a .csv file to be used in the modeling functions. ```{r, eval = FALSE} #Input raster image wq_raster <- terra::rast("C:/temp/my_raster.tif") #Input shapefile wq_samples <- terra::vect('C:/temp/my_samples.shp') #Extract values from raster and combine with shapefile waterquality_data <- data.frame(wq_samples, terra::extract(wq_raster, wq_samples)) #Export results as csv file write.csv(waterquality_data, file = "C:/temp/waterquality_data.csv") ``` ### extract_lm - `parameter` A string specifying water quality parameter - `algorithm` A string specifying water quality algorithm - `df` data frame containing the values for parameter and algorithm arguments #### Example ```{r, results='hide', message=FALSE, warning=FALSE} library(waterquality) library(caret) df <- read.csv(system.file("raster/waterquality_data.csv", package = "waterquality")) ``` ```{r, message=FALSE, warning=FALSE} extract_lm(parameter = "Chl_ugL", algorithm = "MM12NDCI", df = df) ``` ### extract_lm_cv - `parameter` A string specifying water quality parameter - `algorithm` A string specifying water quality algorithm - `df` data frame containing the values for parameter and algorithm arguments - `train_method` A string specifying which classification or regression model to use (Default = "lm"). See ?caret::train for more details - `control_method` A string specifying the resampling method (Default = "repeatedcv"). See ?caret::trainControl for more details - `folds` the number of folds to be used in the cross validation model (Default = 3) - `nrepeats` the number of iterations to be used in the cross validation model (Default = 5) #### Example ```{r, message=FALSE, warning=FALSE} extract_lm_cv(parameter = "Chl_ugL", algorithm = "MM12NDCI", df = df, train_method = "lm", control_method = "repeatedcv", folds = 3, nrepeats = 5) ``` ### extract_lm_cv_multi - `parameters` list of water quality parameters - `algorithms` list of water quality algorithms - `df` data frame containing the values for parameter and algorithm arguments - `train_method` A string specifying which classification or regression model to use (Default = "lm"). See ?caret::train for more details - `control_method` A string specifying the resampling method (Default = "repeatedcv"). See ?caret::trainControl for more details - `folds` the number of folds to be used in the cross validation model (Default = 3) - `nrepeats` the number of iterations to be used in the cross validation model (Default = 5) #### Example ```{r, message=FALSE, warning=FALSE} # Create series of strings to be used for parameters and algorithms arguments algorithms <- c(names(df[6:10])) parameters <- c(names(df[3:5])) extract_lm_cv_multi_results <- extract_lm_cv_multi(parameters = parameters, algorithms = algorithms, df = df, train_method = "lm", control_method = "repeatedcv", folds = 3, nrepeats = 5) head(extract_lm_cv_multi_results) ``` ### extract_lm_cv_all - `parameters` list of water quality parameters - `df` data frame containing the values for parameter and algorithm arguments - `train_method` A string specifying which classification or regression model to use (Default = "lm"). See ?caret::train for more details - `control_method` A string specifying the resampling method (Default = "repeatedcv"). See ?caret::trainControl for more details - `folds` the number of folds to be used in the cross validation model (Default = 3) - `nrepeats` the number of iterations to be used in the cross validation model (Default = 5) #### Example ```{r, message=FALSE, warning=FALSE} extract_lm_cv_all_results <- extract_lm_cv_all(parameters = parameters, df = df, train_method = "lm", control_method = "repeatedcv", folds = 3, nrepeats = 5) head(extract_lm_cv_all_results) ``` ## Acknowledgements The waterquality package was developed with funding from the U.S. Army Corps of Engineers. The authors would also like to thank the University of Cincinnati Library's Research & Data Services and the University of Cincinnati's Space Informatics Lab for their expertise and technical services. ## Credit To cite this library, please use the following entry: Johansen R., Reif M., Emery E., Nowosad J., Beck R., Xu M., Liu H., waterquality: An Open-Source R Package for the Detection and Quantification of Cyanobacterial Harmful Algal Blooms and Water Quality. USACE ERDC/EL TR-19-20; DOI: 10.21079/11681/35053 @Article{, author = {Richard Johansen and Molly Reif and Erich Emery and Jakub Nowosad and Richard Beck and Min Xu and Hongxing Liu}, title = {waterquality: An Open-Source R Package for the Detection and Quantification of Cyanobacterial Harmful Algal Blooms and Water Quality}, year = {2019}, doi = {10.21079/11681/35053}, journal = {USACE ERDC/EL TR-19-20}, }
/scratch/gouwar.j/cran-all/cranData/waterquality/inst/doc/waterquality_vignette.Rmd
--- title: "Introduction to the waterquality package" author: "Richard Johansen, Jakub Nowosad, Molly Reif, and Erich Emery" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction to the waterquality package} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", echo = TRUE) ``` The main purpose of **waterquality** is to quickly and easily convert satellite-based reflectance imagery into one or many well-known water quality indices designed for the detection of harmful algal blooms (HABs) using the following pigment proxies: chlorophyll-a, blue-green algae (phycocyanin), and turbidity. Currently, this package is able to process [40 algorithms](https://rajohansen.github.io/waterquality/reference/index.html) for the following satellite-based imagers: WorldView-2 and -3, Sentinel-2, Landsat-8, MODIS, MERIS, and OLCI. In order to improve the aesthetics of the `wq_calc` output, a series of intuitive `Map_WQ` functions were developed to help reduce technical barriers due to coding and the myriad of map options. Additional functionality of the package includes a series of `extract_lm` functions which wrap the ["Fitting Linear Models"](https://www.rdocumentation.org/packages/stats/versions/3.6.2/topics/lm) and the ["caret"](http://topepo.github.io/caret/index.html) packages to quickly generate a suite of regression models with standardized outputs. These functions range from simple linear models for a single dependent and independent variable to robust linear regression using crossvalidation over multiple dependent and independent variables. These functions are extremely useful when conducting experimental testing on a large number of satellite algorithms across multiple water quality parameters. **NOTE** these functions require ground-truth data in order to develop the models. For an example of our entire research workflow, which includes data acquisition, image pre-processing, analyses, and results please see our publication entitled ["Waterquality: An Open-Source R Package for the Detection and Quantification of Cyanobacterial Harmful Algal Blooms and Water Quality"](https://erdc-library.erdc.dren.mil/jspui/bitstream/11681/35053/3/ERDC-EL%20TR-19-20.pdf). ## Algorithms Currently, the package includes a total of [40 algorithms](https://rajohansen.github.io/waterquality/reference/index.html) that can be applied for the detection of the three parameters. **NOTE** not all sensors are capable of using all algorithms due to their spectral configurations. Each of the algorithms are searchable within the package, where there is a reference to the original paper (Ex. `?Am092Bsub()`). Each algorithm is also linked to the original papers water quality parameters (chlorophyll-a, phycocyanin, turbidity) by type, which allows users to select all algorithms for that type. The final outputs are raster stacked images which represent relative index values and are not direct estimations of chlorophyll-a, phycocyanin, or turbidity values. However, relative index values can be converted to estimated concentration values using the `extract_lm` functions and ground truth measurements. ## Water Quality Functions ### wq_calc() The main function of this package is called `wq_calc()` which calculates water quality indices by using a reflectance raster stack as an input, user-defined algorithm(s) selection, and satellite configuration selection corresponding to the following three arguments: `terraRast`, `alg`, and `sat`. - `terraRast` - The input reflectance image to be used in band algorithm calculation. - `alg` - Determines the indices to be utilized: - Single Algorithm - Multiple Algorithm - Type of Algorithm - All Possible Algorithms - `sat` - Determines the appropriate spectral configuration and subsequently appropriate algorithms to be calculated from predefined list: - WorldView-2 - Sentinel-2 - Landsat-8 - MODIS - MERIS - OLCI #### Single Algorithm ```{r, results='hide', message=FALSE, warning=FALSE} library(waterquality) library(terra) Harsha <- terra::rast(system.file("raster/S2_Harsha.tif", package = "waterquality")) ``` ```{r,results='hide', message=FALSE, warning=FALSE} Harsha_Am092Bsub <- wq_calc(terraRast = Harsha, alg = "MM12NDCI", sat = "sentinel2") ``` ```{r, fig.height = 5, fig.width = 6} terra::plot(Harsha_Am092Bsub) ``` #### Multiple Algorithms ```{r,results='hide', message=FALSE, warning=FALSE} Harsha_Multiple <- wq_calc(terraRast = Harsha, alg = c("MM12NDCI", "Am092Bsub", "Da052BDA"), sat = "sentinel2") ``` ```{r, fig.height = 5, fig.width = 6} terra::plot(Harsha_Multiple) ``` #### Type of Algorithm ```{r,results='hide', message=FALSE, warning=FALSE} Harsha_PC <- wq_calc(Harsha, alg = "chlorophyll", sat = "sentinel2") ``` ```{r, fig.height = 5, fig.width = 6} terra::plot(Harsha_PC) ``` #### All Algorithms ```{r, results='hide', message=FALSE, warning=FALSE} Harsha_All <- wq_calc(Harsha, alg = "all", sat = "sentinel2") ``` ```{r,fig.height = 5, fig.width = 6} terra::plot(Harsha_All) # Only displays first 16 of 28 ``` ## Mapping Functions ### Map_WQ_raster This function wraps the ["tmap"](https://cran.r-project.org/package=tmap) package to help users to efficiently generate a map of a raster image which can be overlaid with optional geospatial objects and data histogram. In order to simplify this process and reduce the technical expertise required, the number of arguments were reduced to the following: - `WQ_raster` - Raster file generated from `wq_calc` or other GeoTiff file - `sample_points` - geospatial file (.shp or .gpkg) containing sampling locations - `map_title` - text used to generate title of map - `raster_style` - method to process the color scale when col is a numeric variable. Please refer to the style argument in the `?tmap::tm_raster()` function for more details (Default is "quantile"). - `histogram` - Option to add or remove a histogram of the data values. (Default is TRUE) #### Raster with points ```{r, results='hide', message=FALSE, warning=FALSE} library(waterquality) library(terra) library(tmap) library(sf) s2 = terra::rast(system.file("raster/S2_Harsha.tif", package = "waterquality")) MM12NDCI = wq_calc(s2, alg = "MM12NDCI", sat = "sentinel2") samples = terra::vect(system.file("raster/Harsha_Simple_Points_CRS.gpkg", package = "waterquality")) lake_extent = terra::vect(system.file("raster/Harsha_Lake_CRS.gpkg", package = "waterquality")) ``` ```{r,fig.height = 5, fig.width = 6} Map_WQ_raster(WQ_raster = MM12NDCI, sample_points = samples, map_title= "Water Quality Map", raster_style = "quantile", histogram = TRUE) ``` ## Modeling Functions Developing models is an essential step in water quality monitoring, and this requires sufficient coincident ground truth data. These functions have been developed to combine user-provided ground truth data and the results from the `wq_calc` function to generate a single or series of regression models. These functions have been developed to easily conduct linear models with standardized outputs, providing intuitive yet robust options. Most effectively, the functions will utilize a single comma delimited (.csv) file as the data frame source. Although these functions were designed for our water quality research, they can be used as standalone functions for any data to generate the same standardized outputs containing the following: **Global Model** - r^2^ - p-value - slope - intercept **Crossvalidated Model** - average r^2^ - average RMSE - average MAE Additionally, we have provided code that might be useful to help users import and extract the data from a raster stack image (i.e. output from `wq_calc`), combine it with a geospatial object (i.e shapefiles of sample locations), and export the results to a .csv file to be used in the modeling functions. ```{r, eval = FALSE} #Input raster image wq_raster <- terra::rast("C:/temp/my_raster.tif") #Input shapefile wq_samples <- terra::vect('C:/temp/my_samples.shp') #Extract values from raster and combine with shapefile waterquality_data <- data.frame(wq_samples, terra::extract(wq_raster, wq_samples)) #Export results as csv file write.csv(waterquality_data, file = "C:/temp/waterquality_data.csv") ``` ### extract_lm - `parameter` A string specifying water quality parameter - `algorithm` A string specifying water quality algorithm - `df` data frame containing the values for parameter and algorithm arguments #### Example ```{r, results='hide', message=FALSE, warning=FALSE} library(waterquality) library(caret) df <- read.csv(system.file("raster/waterquality_data.csv", package = "waterquality")) ``` ```{r, message=FALSE, warning=FALSE} extract_lm(parameter = "Chl_ugL", algorithm = "MM12NDCI", df = df) ``` ### extract_lm_cv - `parameter` A string specifying water quality parameter - `algorithm` A string specifying water quality algorithm - `df` data frame containing the values for parameter and algorithm arguments - `train_method` A string specifying which classification or regression model to use (Default = "lm"). See ?caret::train for more details - `control_method` A string specifying the resampling method (Default = "repeatedcv"). See ?caret::trainControl for more details - `folds` the number of folds to be used in the cross validation model (Default = 3) - `nrepeats` the number of iterations to be used in the cross validation model (Default = 5) #### Example ```{r, message=FALSE, warning=FALSE} extract_lm_cv(parameter = "Chl_ugL", algorithm = "MM12NDCI", df = df, train_method = "lm", control_method = "repeatedcv", folds = 3, nrepeats = 5) ``` ### extract_lm_cv_multi - `parameters` list of water quality parameters - `algorithms` list of water quality algorithms - `df` data frame containing the values for parameter and algorithm arguments - `train_method` A string specifying which classification or regression model to use (Default = "lm"). See ?caret::train for more details - `control_method` A string specifying the resampling method (Default = "repeatedcv"). See ?caret::trainControl for more details - `folds` the number of folds to be used in the cross validation model (Default = 3) - `nrepeats` the number of iterations to be used in the cross validation model (Default = 5) #### Example ```{r, message=FALSE, warning=FALSE} # Create series of strings to be used for parameters and algorithms arguments algorithms <- c(names(df[6:10])) parameters <- c(names(df[3:5])) extract_lm_cv_multi_results <- extract_lm_cv_multi(parameters = parameters, algorithms = algorithms, df = df, train_method = "lm", control_method = "repeatedcv", folds = 3, nrepeats = 5) head(extract_lm_cv_multi_results) ``` ### extract_lm_cv_all - `parameters` list of water quality parameters - `df` data frame containing the values for parameter and algorithm arguments - `train_method` A string specifying which classification or regression model to use (Default = "lm"). See ?caret::train for more details - `control_method` A string specifying the resampling method (Default = "repeatedcv"). See ?caret::trainControl for more details - `folds` the number of folds to be used in the cross validation model (Default = 3) - `nrepeats` the number of iterations to be used in the cross validation model (Default = 5) #### Example ```{r, message=FALSE, warning=FALSE} extract_lm_cv_all_results <- extract_lm_cv_all(parameters = parameters, df = df, train_method = "lm", control_method = "repeatedcv", folds = 3, nrepeats = 5) head(extract_lm_cv_all_results) ``` ## Acknowledgements The waterquality package was developed with funding from the U.S. Army Corps of Engineers. The authors would also like to thank the University of Cincinnati Library's Research & Data Services and the University of Cincinnati's Space Informatics Lab for their expertise and technical services. ## Credit To cite this library, please use the following entry: Johansen R., Reif M., Emery E., Nowosad J., Beck R., Xu M., Liu H., waterquality: An Open-Source R Package for the Detection and Quantification of Cyanobacterial Harmful Algal Blooms and Water Quality. USACE ERDC/EL TR-19-20; DOI: 10.21079/11681/35053 @Article{, author = {Richard Johansen and Molly Reif and Erich Emery and Jakub Nowosad and Richard Beck and Min Xu and Hongxing Liu}, title = {waterquality: An Open-Source R Package for the Detection and Quantification of Cyanobacterial Harmful Algal Blooms and Water Quality}, year = {2019}, doi = {10.21079/11681/35053}, journal = {USACE ERDC/EL TR-19-20}, }
/scratch/gouwar.j/cran-all/cranData/waterquality/vignettes/waterquality_vignette.Rmd
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 rwatTinflex <- function(n, kappa, mu, cT, rho) { .Call('_watson_rwatTinflex', PACKAGE = 'watson', n, kappa, mu, cT, rho) } rwatACG <- function(n, kappa, mu, b = -10) { .Call('_watson_rwatACG', PACKAGE = 'watson', n, kappa, mu, b) } #' @title Random Sampling from a Mixture of Watson Distributions #' @description \code{rmwat} generates a random sample from a mixture of multivariate Watson distributions. #' @param n an integer giving the number of samples to draw. #' @param weights a numeric vector with non-negative elements giving the mixture probabilities. #' @param kappa a numeric vector giving the kappa parameters of the mixture components. #' @param mu a numeric matrix with columns giving the mu parameters of the mixture components. #' @param method a string indicating whether ACG sampler (\code{method = "acg"}), Tinflex sampler (\code{method = "tinflex"}) or automatic selection (\code{method = "auto"}) of the sampler should be used, default: "acg". #' @param b a positive numeric hyper-parameter used in the sampling. If not a positive value is given, optimal choice of b is used, default: -10. #' @param rho performance parameter: requested upper bound for ratio of area below hat to area below squeeze (numeric). See \code{\link[Tinflex]{Tinflex.setup}}, default: 1.1. #' @return A matrix with rows equal to the generated values. #' @details The function generates samples from finite mixtures of Watson distributions, #' using methods from Sablica, Hornik and Leydold (2022) \url{https://research.wu.ac.at/en/publications/random-sampling-from-the-watson-distribution}. #' @examples #' #' ## simulate from Watson distribution #' sample1 <- rmwat(n = 20, weights = 1, kappa = 20, mu = matrix(c(1,1,1),nrow = 3)) #' #' ## simulate from a mixture of Watson distributions #' sample2 <- rmwat(n = 20, weights = c(0.5,0.5), kappa = c(-200,-200), #' mu = matrix(c(1,1,1,-1,1,1),nrow = 3)) #' @rdname rmwat #' @references Sablica, Hornik and Leydold (2022). Random Sampling from the Watson Distribution \url{https://research.wu.ac.at/en/publications/random-sampling-from-the-watson-distribution}. #' @export rmwat <- function(n, weights, kappa, mu, method = "acg", b = -10, rho = 1.1) { .Call('_watson_rmwat', PACKAGE = 'watson', n, weights, kappa, mu, method, b, rho) } g <- function(alpha, beta, x, N = 30L) { .Call('_watson_g', PACKAGE = 'watson', alpha, beta, x, N) } kummerM <- function(alpha, beta, r) { .Call('_watson_kummerM', PACKAGE = 'watson', alpha, beta, r) } log_hyperg_1F1 <- function(alpha, beta, r, N = 10L) { .Call('_watson_log_hyperg_1F1', PACKAGE = 'watson', alpha, beta, r, N) } diam_clus1 <- function(data, K, maxiter = 100L) { .Call('_watson_diam_clus1', PACKAGE = 'watson', data, K, maxiter) } diam_clus2 <- function(data, K, maxiter = 100L) { .Call('_watson_diam_clus2', PACKAGE = 'watson', data, K, maxiter) } predictC1 <- function(data, kappa_vector, mu_matrix, pi_vector, E_type, K) { .Call('_watson_predictC1', PACKAGE = 'watson', data, kappa_vector, mu_matrix, pi_vector, E_type, K) } predictC2 <- function(data, kappa_vector, mu_matrix, pi_vector, E_type, K) { .Call('_watson_predictC2', PACKAGE = 'watson', data, kappa_vector, mu_matrix, pi_vector, E_type, K) } log_like1 <- function(data, kappa_vector, mu_matrix, pi_vector, K, beta, n) { .Call('_watson_log_like1', PACKAGE = 'watson', data, kappa_vector, mu_matrix, pi_vector, K, beta, n) } log_like2 <- function(data, kappa_vector, mu_matrix, pi_vector, K, beta, n) { .Call('_watson_log_like2', PACKAGE = 'watson', data, kappa_vector, mu_matrix, pi_vector, K, beta, n) } EM1 <- function(data, K, E_type, M_type, minalpha = 0, convergence = TRUE, maxiter = 100L, N = 30L, reltol = 1e-9, start = NULL, verbose = FALSE) { .Call('_watson_EM1', PACKAGE = 'watson', data, K, E_type, M_type, minalpha, convergence, maxiter, N, reltol, start, verbose) } EM2 <- function(data, K, E_type, M_type, minalpha = 0, convergence = TRUE, maxiter = 100L, N = 30L, reltol = 1e-9, start = NULL, verbose = FALSE) { .Call('_watson_EM2', PACKAGE = 'watson', data, K, E_type, M_type, minalpha, convergence, maxiter, N, reltol, start, verbose) }
/scratch/gouwar.j/cran-all/cranData/watson/R/RcppExports.R
#' @useDynLib watson #' @importFrom Rcpp sourceCpp #' @import Tinflex NULL #' @export print.watfit <- function(x, ...){ cat("Fitted " , x$K ,"-components Watson mixture: \n\n", sep = "") cat("Weights:", x$weights, "\n") cat("Kappa:", x$kappa_vector, "\n\n") cat("Mu: \n") print(x$mu_matrix) cat("\nLog-likelihood: ", x$L, ", Average log-likelihood: ", x$L/x$details$n , "\n", sep = "") } #' @export coef.watfit <- function(object, ...) object[c("weights", "kappa_vector", "mu_matrix")] #' @export logLik.watfit <- function(object, newdata, ...){ if (missing(newdata)) { return(object$ll) } else { if(inherits(newdata, "Matrix")){ log_like2(newdata, object$kappa_vector, object$mu_matrix, object$weights, object$K, object$details$beta, nrow(newdata)) } else{ log_like1(newdata, object$kappa_vector, object$mu_matrix, object$weights, object$K, object$details$beta, nrow(newdata)) } } } #' @export predict.watfit <- function(object, newdata = NULL, type = c("class_ids", "memberships"), ...){ type <- match.arg(type) M <- if(is.null(newdata)){ object$a_posterior } else { if(inherits(newdata, "Matrix")){ predictC2(newdata, object$kappa_vector, object$mu_matrix, object$weights, object$details$E, object$K) } else{ predictC1(newdata, object$kappa_vector, object$mu_matrix, object$weights, object$details$E, object$K) } } v <- if(type == "class_ids") max.col(M) else M attr(v, "loglik") <- attr(M, "loglik") v } #' @title Diametrical clustering #' @description \code{diam_clus} clusters axial data on sphere using the algorithm proposed in Dhillon et al. (2003). #' @param x a numeric data matrix, with rows corresponding to observations. Can be a dense matrix, #' or any of the supported sparse matrices from \code{\link[Matrix]{Matrix}} package by \code{\link[Rcpp]{Rcpp}}. #' @param k an integer giving the number of mixture components. #' @param niter integer indicating the number of iterations of the diametrical clustering algorithm, default: 100. #' @return a matrix with the concentration directions with an attribute "id" defining the classified categories. #' @examples #' ## Generate a sample #' a <- rmwat(n = 200, weights = c(0.5,0.5), kappa = c(20, 20), #' mu = matrix(c(1,1,-1,1),nrow = 2)) #' ## Fit basic model #' q <- diam_clus(a, 2) #' @rdname diam_clus #' @references Inderjit S Dhillon, Edward M Marcotte, and Usman Roshan. Diametrical clustering #' for identifying anti-correlated gene clusters. Bioinformatics, 19(13):1612-1619, 2003. #' @export diam_clus <- function(x, k, niter = 100){ if(inherits(x, "Matrix")){ a = diam_clus2(x,k,niter) } else{ a = diam_clus1(x,k,niter) } a } #' @title Fit Mixtures of Watson Distributions #' @description \code{watson} fits a finite mixture of multivariate Watson distributions. #' @param x a numeric data matrix, with rows corresponding to observations. Can be a dense matrix, #' or any of the supported sparse matrices from \code{\link[Matrix]{Matrix}} package by \code{\link[Rcpp]{Rcpp}}. #' @param k an integer giving the number of mixture components. #' @param control a list of control parameters. See Details. #' @param ... a list of control parameters (overriding those specified in control). #' @return An object of class "watfit" representing the fitted mixture, which is a list containing the fitted #' weights, concentrations parameters (kappa), concentrations directions (mu) and further metadata. #' @details watson returns an object of class "watfit" representing the fitted mixture of Watson #' distributions model. Available methods for such objects include \code{\link[stats]{coef}}, \code{\link[stats]{logLik}}, \code{\link[base]{print}} and \code{\link[stats]{predict}}. #' \code{\link[stats]{predict}} has an extra type argument with possible values \code{"class_ids"} (default) and \code{"memberships"} #' for indicating hard or soft prediction, respectively. #' #' The mixture of Watson distributions is fitted using EM variants as specified by control #' option E (specifying the E-step employed), with possible values "softmax" (default), "hardmax" or #' "stochmax". For "stochmax", class assignments are drawn from the posteriors for each observation in the E-step as #' outlined as SEM in Celeux and Govaert (1992). The stopping criterion for this algorithm is by default #' changed to not check for convergence (logical control option converge), but to return the parameters with #' the maximum likelihood encountered. #' #' In the M-step, the parameters of the respective component distributions #' are estimated via maximum likelihood, which is accomplished by solving the equation #' \deqn{g(\alpha,\beta, \kappa)=r,} #' where #' \deqn{0<\alpha<\beta, \ 0\leq r\leq 1} #' and #' \deqn{g(\alpha, \beta, \kappa) = (\alpha/\beta)M(\alpha+1, \beta+1, \kappa)/M(\alpha, \beta, \kappa),} with M being the Kummer's function. #' Via control argument M, one can specify how to (approximately) solve these equations. #' The possible methods are: #' #' "Sra_2007" #' uses the approximation of Sra (2007). #' #' "BBG" #' uses the approximation of Bijral et al. (2007), without the correction term. #' #' "BBG_c" #' uses the approximation of Bijral et al. (2007), with the correction term. #' #' "Sra_Karp_2013" #' uses the bounds derived in Sra and Karp (2013), with the decision rule . #' #' "bisection" #' uses a bisection to solve the problem using evaluation proposed in Writeup1 (2018). #' #' "newton" #' uses a bracketet type of Neton algorithm to solve the problem using evaluation proposed in Writeup1 (2018). (Default.) #' #' "lognewton" #' uses a bracketet type of Neton algorithm to solve the problem \eqn{log(g((\alpha, \beta, \kappa)) = log(r)} #' using evaluation proposed in Writeup1 (2018). #' #' Additional control parameters are as follows. #' #' maxiter #' an integer giving the maximal number of EM iterations to be performed, default: 100. #' #' reltol #' the minimum relative improvement of the objective function per iteration. If improvement is less, the EM #' algorithm will stop under the assumption that no further significant improvement can be made, defaults #' to sqrt(.Machine$double.eps). #' #' ids #' either a vector of class memberships or TRUE which implies that the class memberships are obtained from #' the attribute named "id" of the input data; these class memberships are used for initializing the EM #' algorithm and the algorithm is stopped after the first iteration. #' #' init_iter #' a numeric vector setting the number of diametrical clustering iterations to do, before the EM starts, default: 0. #' #' start #' a specification of the starting values to be employed. Can be a list of matrices giving the memberships #' of objects to components. This information is combined with the \code{init_iter} parameter and together form #' the initialization procedure. If nothing is given, the starting values are drwan randomly. #' #' If several starting values are specified, the EM algorithm is performed individually to each starting #' value, and the best solution found is returned. #' #' nruns #' an integer giving the number of EM runs to be performed. Default: 1. Only used if start is not given. #' #' minweight #' a numeric indicating the minimum prior probability. Components falling below this threshold are removed #' during the iteration. If is greater than 1, the value is taken as the minimal number of observations in a component, default: 0 if #' E = "softmax" and 2 if other type of E-method is used . #' #' converge #' a logical, if TRUE the EM algorithm is stopped if the reltol criterion is met and the current parameter #' estimate is returned. If FALSE the EM algorithm is run for maxiter iterations and the parametrizations #' with the maximum likelihood encountered during the EM algorithm is returned. Default: TRUE, changed to #' FALSE if E="stochmax". #' #' N #' an integer indicating number of iteration used when the Kummer function is approximate, default: 30. #' #' verbose #' a logical indicating whether to provide some output on algorithmic progress, default: FALSE. #' #' @examples #' \donttest{ #' ## Generate a sample with two orthogonal circles (negative kappas) #' a <- rmwat(n = 200, weights = c(0.5,0.5), kappa = c(-200,-200), #' mu = matrix(c(1,1,1,-1,1,1),nrow = 3)) #' ## Fit basic model #' q <- watson(a, 2) #' ## Fit the models, giving the true categories #' q <- watson(a, 2, ids=TRUE) #' ## Fit a model with hard-assignment, and 50 runs #' q <- watson(a, 2, E = "hard", nruns = 50) #' ## Print details #' q #' ## Extract coefficients #' coef(q) #' ## Calculate likelihood for new data #' a2 <- rmwat(n = 20, weights = c(0.5,0.5), kappa = c(-200,-200), #' mu = matrix(c(1,1,1,-1,1,1),nrow = 3)) #' logLik(q, a2) #' ## Compare the fitted classes to the true ones: #' table(True = attr(a, "id"), Fitted = predict(q)) #' } #' @rdname watson #' @export watson <- function(x, k, control = list(), ...){ control <- c(control, list(...)) idd <- attr(x, "id") x <- as.matrix(x) attr(x, "id") <- idd n <- nrow(x) p <- ncol(x) sparse <- inherits(x, "Matrix") maxiter <- control$maxiter if(is.null(maxiter)) maxiter <- 100L reltol <- control$reltol if(is.null(reltol)) reltol <- sqrt(.Machine$double.eps) E_methods <- c("softmax", "hardmax", "stochmax") E_type <- control$E if(is.null(E_type)){ E_type <- "softmax" } else { pos <- pmatch(tolower(E_type), tolower(E_methods)) if(is.na(pos)) stop("Invalid E-step method.") E_type <- E_methods[pos] } M_methods <- c("newton","lognewton", "bisection", "BBG", "Sra_2007", "BBG_c", "Sra_Karp_2013") M_type <- control$M if(is.null(M_type)){ M_type <- "newton" } else { pos <- pmatch(tolower(M_type), tolower(M_methods)) if(is.na(pos)) stop("Invalid M-step method.") M_type <- M_methods[pos] } minweight <- control$minweight if(is.null(minweight)){ minweight <- if(E_type == "softmax") 0 else 2/n } else if(minweight >= 1 && n>minweight){ minweight <- minweight/n } else if(n <= minweight || minweight<0){ stop("minweight must be in [0,1) or [1,n)") } converge <- control$converge if(is.null(converge)) { converge <- if(E_type == "stochmax") FALSE else TRUE } N <- control$N if(is.null(N)) { N <- 30L } verbose <- control$verbose if (is.null(verbose)) verbose <- getOption("verbose") ids <- control$ids start <- control$start init_iter <- control$init_iter nruns <- control$nruns if(!is.null(ids)) { if(identical(ids, TRUE)){ ids <- attr(x, "id") ids <- as.integer(as.factor(ids)) } else { ids <- as.integer(as.factor(ids)) if(length(ids)!=n) stop("length of 'ids' needs to match the number of observations") } k <- max(ids) maxiter <- 0L init_iter <- if(is.null(init_iter)) 0L else init_iter[1] if(!is.null(nruns) || !is.null(start)) warning("control arguments 'nruns' and 'start' ignored because 'ids' are specified") nruns <- 1L beta_mat <- matrix(0, n, k) beta_mat[cbind(seq_len(n), ids)] <- 1 start <- list(list(given = TRUE, init_iter = init_iter, matrix = beta_mat)) } else{ if(is.null(start)) { if(is.null(nruns)){ nruns <- if(is.null(init_iter)) 1L else length(init_iter) }else{ if(nruns >= 1L){ nruns <- floor(nruns) } else{ stop("nruns must be greater or equal than 1") } } init_iter <- if(is.null(init_iter)) rep_len(as.list(0L),nruns) else rep_len(as.list(init_iter),nruns) given <- rep(list(FALSE), nruns) matrix <- rep(list(matrix(0,1,1)),nruns) start <- lapply(1:nruns, function(i) list(given = given[[i]], init_iter = init_iter[[i]], matrix = matrix[[i]])) } else { matrix <- if(!is.list(start)) rep(list(start),nruns) else start nruns <- length(matrix) init_iter <- if(is.null(init_iter)) rep_len(as.list(0L),nruns) else rep_len(as.list(init_iter),nruns) given <- rep(list(TRUE), nruns) start <- lapply(1:nruns, function(i) list(given = given[[i]], init_iter = init_iter[[i]], matrix = matrix[[i]])) } } obj <- if(sparse){ EM2(data = x, K = k, E_type = E_type, M_type = M_type, minalpha = minweight, convergence = converge, maxiter = maxiter, N = N, reltol = reltol, start = start, verbose = verbose) } else{ EM1(data = x, K = k, E_type = E_type, M_type = M_type, minalpha = minweight, convergence = converge, maxiter = maxiter, N = N, reltol = reltol, start = start, verbose = verbose) } details <- list(p = p, n = n, beta = p/2, reltol = reltol, maxiter = maxiter, E = E_type, M = M_type, minweight = minweight, N = N, converge = converge, sparse = sparse) K <- dim(obj[[2]])[2] ll <- structure(obj[[5]], class = "logLik", df = (p+1)*K - 1, nobs = n) obj <- c(list(x), list(K), obj, list(ll), list(details)) names(obj) <- c("data", "K" ,"a_posterior", "kappa_vector", "mu_matrix", "weights", "L", "ll", "details") nam <- paste("clus",1:K, sep = "_") colnames(obj$a_posterior) <- nam colnames(obj$kappa_vector) <- nam colnames(obj$mu_matrix) <- nam colnames(obj$weights) <- nam class(obj) <- "watfit" obj }
/scratch/gouwar.j/cran-all/cranData/watson/R/watson.R
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 read_wav_dr <- function(path) { .Call(`_wav_read_wav_dr`, path) } write_wav_int <- function(x, path, sample_rate = 44100L, bit_depth = 16L, normalize = TRUE) { .Call(`_wav_write_wav_int`, x, path, sample_rate, bit_depth, normalize) } write_wav_dbl <- function(x, path, sample_rate = 44100L, bit_depth = 32L) { .Call(`_wav_write_wav_dbl`, x, path, sample_rate, bit_depth) }
/scratch/gouwar.j/cran-all/cranData/wav/R/RcppExports.R
## usethis namespace: start #' @useDynLib wav, .registration = TRUE ## usethis namespace: end NULL ## usethis namespace: start #' @importFrom Rcpp sourceCpp ## usethis namespace: end NULL
/scratch/gouwar.j/cran-all/cranData/wav/R/package.R
#' Read/write wav files #' #' Efficiently read and write [WAV files](https://en.wikipedia.org/wiki/WAV). #' #' @param path Path to file that will be read or written to. #' @param x Numeric matrix with dimensions `[n_channels, n_samples]`. Values in #' the matrix should be `<double>` in the range `[-1, 1]` or integers in the range #' `[-.Machine$integer.max, .Machine$integer.max]` ie. 32 bits signed integers #' like R integers containing the amplitudes. Depending on the value of `normalize` #' and the `bit_depth` you can use different ranges. #' @param sample_rate Sample rate in Hz of the associated samples. #' @param bit_depth Bit depth of associated samples. This only affects the precision #' data is saved to the file. #' @param normalize Boolean idicating wheter integers should be normalized before #' writing. Only used when [write_wav()] is called with a integer matrix. #' For example when you write a sample with a amplitude value of `2147483647` #' and `bit_depth = 8`, you would need to normalize this integer so it #' actually refers to the maximum unsigned int available (i.e. `255`). #' You can avoid normalizing when the amplitudes are already in the correct integer #' range for the `bit_depth` you are saving, in this case provide `normalize = FALSE`. #' @param ... Currently unused. #' #' #' @returns #' - When reading: A numeric matrix with samples. It also contains the attributes `sample_rate` #' and `bit_depth`. #' - When writing: A boolean which is `TRUE` if writing was sucessful and `FALSE` #' otherwise. #' #' @examples #' x <- matrix(sin(440 * seq(0, 2*pi, length = 44100)), nrow=1) #' tmp <- tempfile(fileext = ".wav") #' write_wav(x, tmp) #' y <- read_wav(tmp) #' all.equal(as.numeric(x), as.numeric(y), tolerance = 1e-7) #' #' @export read_wav <- function(path) { read_wav_dr(path.expand(path)) } #' @describeIn read_wav Write a wav file. #' @export write_wav <- function(x, path, sample_rate = 44100, bit_depth = 32, ..., normalize = TRUE) { if (length(list(...)) > 0) stop("... shouldn't be used. Maybe you have a typo in the argument name?") if (nrow(x) > 65535) { stop("Number of channels exceeded. Maximum is ", 65535, " got ", nrow(x)) } if (is.integer(x)) { write_wav_int(x, path, sample_rate = sample_rate, bit_depth, normalize) } else if (is.double(x)) { if (any(x < -1) || any(x > 1)) { stop("When inputs is numeric, amplitudes should be in the range [-1,1].") } write_wav_dbl(x, path, sample_rate = sample_rate, bit_depth) } else { stop("Only integers and double matrices are supported.") } }
/scratch/gouwar.j/cran-all/cranData/wav/R/wav.R
#' @title Continuous wavelet transform #' #' @description #' This function computes the continuous wavelet transform for some families of wavelet #' bases: "MORLET", "DOG", "PAUL" and "HAAR". #' It is a translation from the Matlab(R) function published by Torrence and Compo #' (Torrence & Compo, 1998). #' #' The difference between \code{cwt_wst} and \code{cwt} from package \code{Rwave} is that #' \code{cwt_wst} normalizes using \eqn{L^2} and \code{cwt} uses \eqn{L^1}. #' #' #' @usage cwt_wst(signal, #' dt = 1, #' scales = NULL, #' powerscales = TRUE, #' wname = c("MORLET", "DOG", "PAUL", "HAAR", "HAAR2"), #' wparam = NULL, #' waverad = NULL, #' border_effects = c("BE", "PER", "SYM"), #' makefigure = TRUE, #' time_values = NULL, #' energy_density = FALSE, #' figureperiod = TRUE, #' xlab = "Time", #' ylab = NULL, #' main = NULL, #' zlim = NULL) #' #' @param signal A vector containing the signal whose wavelet transform is wanted. #' @param dt Numeric. The time step of the signal. #' @param scales A vector containing the wavelet scales at which the CWT #' is computed. This can be either a vector with all the scales or, following Torrence #' and Compo 1998, a vector of 3 elements with the minimum scale, the maximum scale and #' the number of suboctaves per octave (in this case, \code{powerscales} must be TRUE in #' order to construct power 2 scales using a base 2 logarithmic scale). If \code{scales} #' is NULL, they are automatically constructed. #' @param powerscales Logical. It must be TRUE (default) in these cases: #' \itemize{ #' \item If \code{scales} are power 2 scales, i.e. they use a base 2 logarithmic scale. #' \item If we want to construct power 2 scales automatically. In this case, \code{scales} #' must be \code{NULL}. #' \item If we want to construct power 2 scales from \code{scales}. In this case, #' \code{length(scales)} must be 3. #' } #' @param wname A string, equal to "MORLET", "DOG", "PAUL", "HAAR" or "HAAR2". The #' difference between "HAAR" and "HAAR2" is that "HAAR2" is more accurate but slower. #' @param wparam The corresponding nondimensional parameter for the wavelet function #' (Morlet, DoG or Paul). #' @param waverad Numeric. The radius of the wavelet used in the computations for the cone #' of influence. If it is not specified, it is asumed to be \eqn{\sqrt{2}} for Morlet and DoG, #' \eqn{1/\sqrt{2}} for Paul and 0.5 for Haar. #' @param border_effects String, equal to "BE", "PER" or "SYM", which indicates how to #' manage the border effects which arise usually when a convolution is performed on #' finite-length signals. #' \itemize{ #' \item "BE": Padding time series with zeroes. #' \item "PER": Using boundary wavelets (periodization of the original time series). #' \item "SYM": Using a symmetric catenation of the original time series. #' } #' @param makefigure Logical. If TRUE (default), a figure with the wavelet power spectrum #' is plotted. #' @param time_values A numerical vector of length \code{length(signal)} containing custom #' time values for the figure. If NULL (default), it will be computed starting at 0. #' @param energy_density Logical. If TRUE (default), divide the wavelet power spectrum by #' the scales in the figure and so, values for different scales are comparable. #' @param figureperiod Logical. If TRUE (default), periods are used in the figure instead #' of scales. #' @param xlab A string giving a custom X axis label. #' @param ylab A string giving a custom Y axis label. If NULL (default) the Y label is #' either "Scale" or "Period" depending on the value of \code{figureperiod}. #' @param main A string giving a custom main title for the figure. If NULL #' (default) the main title is either "Wavelet Power Spectrum / Scales" or "Wavelet Power #' Spectrum" depending on the value of \code{energy_density}. #' @param zlim A vector of length 2 with the limits for the z-axis (the color bar). #' #' @return A list with the following fields: #' \itemize{ #' \item \code{coefs}: A matrix of size \code{length(signal)} x \code{length(scales)}, #' containing the CWT coefficients of the signal. #' \item \code{scales}: The vector of scales. #' \item \code{fourierfactor}: A factor for converting scales into periods. #' \item \code{coi_maxscale}: A vector of length \code{length(signal)} containing the #' values of the maximum scale from which there are border effects at each time. #' } #' #' @examples #' dt <- 0.1 #' time <- seq(0, 50, dt) #' signal <- c(sin(pi * time), sin(pi * time / 2)) #' cwt <- cwt_wst(signal = signal, dt = dt, energy_density = TRUE) #' #' @section References: #' #' C. Torrence, G. P. Compo. A practical guide to wavelet analysis. B. Am. Meteorol. Soc. #' 79 (1998), 61–78. #' #' @export #' cwt_wst <- function(signal, dt = 1, scales = NULL, powerscales = TRUE, wname = c("MORLET", "DOG", "PAUL", "HAAR", "HAAR2"), wparam = NULL, waverad = NULL, border_effects = c("BE", "PER", "SYM"), makefigure = TRUE, time_values = NULL, energy_density = FALSE, figureperiod = TRUE, xlab = "Time", ylab = NULL, main = NULL, zlim = NULL ) { wname <- toupper(wname) wname <- match.arg(wname) if (is.null(waverad)) { if ((wname == "MORLET") || (wname == "DOG")) { waverad <- sqrt(2) } else if (wname == "PAUL") { waverad <- 1 / sqrt(2) } else { # HAAR waverad <- 0.5 } } border_effects <- toupper(border_effects) border_effects <- match.arg(border_effects) nt <- length(signal) fourierfactor <- fourier_factor(wname = wname, wparam = wparam) if (is.null(scales)) { scmin <- 2 / fourierfactor scmax <- floor(nt / (2 * waverad)) if (powerscales) { scales <- pow2scales(c(scmin, scmax, ceiling(256 / log2(scmax / scmin)))) } else { scales <- seq(scmin, scmax, by = (scmax - scmin) / 256) } scalesdt <- scales * dt } else { if (powerscales && length(scales) == 3) { scales <- pow2scales(scales) } else { if (is.unsorted(scales)) { warning("Scales were not sorted.") scales <- sort(scales) } aux <- diff(log2(scales)) if (powerscales && ((max(aux) - min(aux)) / max(aux) > 0.05)) { warning("Scales seem like they are not power 2 scales. Powerscales set to FALSE.") powerscales <- FALSE } } scalesdt <- scales scales <- scales / dt } ns <- length(scales) if (border_effects == "BE") { nt_ini <- 1 nt_end <- nt } else if (border_effects == "PER") { ndatcat <- ceiling(ceiling(waverad * scales[ns]) / nt) # Number of catenations = ndatcat * 2 + 1 ntcat <- (ndatcat * 2 + 1) * nt datcat <- numeric(ntcat) for (itcat in 1:ntcat) { datcat[itcat] = signal[itcat - floor((itcat - 1) / nt) * nt] } signal <- datcat nt_ini <- ndatcat * nt + 1 nt_end <- nt_ini + nt - 1 } else if (border_effects == "SYM") { ndatcat <- ceiling(ceiling(waverad * scales[ns]) / nt) # Number of catenations = ndatcat * 2 + 1 dat_sym <- signal aux <- rev(signal) for (icat in 1:ndatcat) { dat_sym <- c(aux, dat_sym, aux) aux <- rev(aux) } signal <- dat_sym nt_ini <- ndatcat * nt + 1 nt_end <- nt_ini + nt - 1 } nt <- length(signal) coefs <- matrix(0, nrow = nt, ncol = ns) if (wname == "HAAR") { precision <- max(12, floor(log2(max(scales))) + 4) step <- 2 ^ (-precision) xval <- seq(from = 0, to = 1 + step, by = step) xmax <- max(xval) psi_integ <- xval * (xval < 1 / 2) + (1 - xval) * (xval >= 1 / 2) for (k in 1:ns) { a <- scales[k] j <- 1 + floor((0:a * xmax) / (a * step)) if (length(j) == 1) { j <- c(1, 1) } f <- rev(psi_integ[j]) coefs[, k] <- -sqrt(a) * core(diff(stats::convolve(signal, f, type = "open")), nt) } } else if (wname == "HAAR2") { for (j in 1:ns) { kmatrix <- matrix(0, nrow = nt, ncol = nt) klen <- floor((scales[j] - 1) / 2) kfrac <- (((scales[j] - 1) / 2) - klen) for (i in 1:nt) { kmin <- max(1, i - klen) kmax <- min(nt, i + klen) if (kmin <= (i - 1)) { kmatrix[kmin:(i - 1), i] <- 1 #for (k in kmin:(i - 1)) { # coefs[i, j] = coefs[i, j] + signal[k] #} } if (kmin >= 2) { kmatrix[kmin - 1, i] <- kfrac #coefs[i, j] <- coefs[i, j] + signal[kmin - 1] * kfrac } if (kmax >= (i + 1)) { kmatrix[(i + 1):kmax, i] <- -1 #for (k in (i + 1):kmax) { # coefs[i, j] = coefs[i, j] - signal[k] #} } if (kmax <= (nt - 1)) { kmatrix[kmax + 1, i] <- -kfrac #coefs[i, j] <- coefs[i, j] - signal[kmax + 1] * kfrac } } coefs[, j] <- signal %*% kmatrix / sqrt(scales[j]) #coefs[, j] <- coefs[, j] / sqrt(scales[j]) } } else { f <- stats::fft(signal) k <- 1:trunc(nt / 2) k <- k * 2 * pi / nt k <- c(0, k, -k[trunc((nt - 1) / 2):1]) n <- length(k) if (wname == "MORLET") { if (is.null(wparam)) { wparam <- 6 } expnt <- -(diag(x = scales, ncol = ns) %*% matrix(rep(k, ns), nrow = ns, byrow = T) - wparam) ^ 2 / 2 expnt <- sweep(expnt, MARGIN = 2, (k > 0), `*`) Norm <- sqrt(scales * k[2]) *pi ^ (-.25) * sqrt(n) daughter <- diag(x = Norm, ncol = ns) %*% exp(expnt) daughter <- sweep(daughter, MARGIN = 2, (k > 0), `*`) coefs <- coefs + 1i*coefs } else if (wname == "PAUL") { if (is.null(wparam)) { wparam <- 4 } coefs <- coefs + 1i*coefs expnt <- -diag(x = scales, ncol = ns) %*% matrix(rep(k, ns), nrow = ns, byrow = T) expnt <- sweep(expnt, MARGIN = 2, (k > 0), `*`) Norm <- sqrt(scales * k[2]) * (2 ^ wparam / sqrt(wparam * prod(2:(2 * wparam - 1)))) * sqrt(n) daughter <- diag(x = Norm, ncol = ns) %*% expnt ^ wparam * exp(expnt) daughter <- sweep(daughter, MARGIN = 2, (k > 0), `*`) coefs <- coefs + 1i*coefs } else if (wname == "DOG") { if (is.null(wparam)) { wparam <- 2 } preexpnt <- (diag(x = scales, ncol = ns) %*% matrix(rep(k, ns), nrow = ns, byrow = T)) expnt <- -preexpnt ^ 2 / 2 Norm <- sqrt(scales * k[2] / gamma(wparam + 0.5)) * sqrt(n) daughter <- diag(x = -Norm * (1i ^ wparam), ncol = ns) %*% preexpnt ^ wparam * exp(expnt) } coefs <- stats::mvfft(t(sweep(daughter, MARGIN = 2, f, `*`)), inverse = TRUE) / length(f) } coefs <- coefs[nt_ini:nt_end, 1:ns] * sqrt(dt) nt <- nt_end - nt_ini + 1 # COI coi_maxscale <- numeric(nt) for (i in 1:nt) { coi_maxscale[i] <- dt * min(i - 1, nt - i) / waverad } # Make figure if (makefigure) { if (is.null(time_values)) { X <- seq(0, (nt - 1) * dt, dt) } else { if (length(time_values) != nt) { warning("Invalid length of time_values vector. Changing to default.") X <- seq(0, (nt - 1) * dt, dt) } else { X <- time_values } } ylab_aux <- ylab if (figureperiod) { Y <- fourierfactor * scalesdt coi <- fourierfactor * coi_maxscale if (is.null(ylab)) ylab <- "Period" } else { Y <- scalesdt coi <- coi_maxscale if (is.null(ylab)) ylab <- "Scale" } if (energy_density) { Z <- t(t(abs(coefs) ^ 2) / scalesdt) if (is.null(main)) main <- "Wavelet Power Spectrum / Scales" } else { Z <- abs(coefs) ^ 2 if (is.null(main)) main <- "Wavelet Power Spectrum" } if (ns > 1) { wavPlot( Z = Z, X = X, Y = Y, Ylog = powerscales, coi = coi, Xname = xlab, Yname = ylab, Zname = main, zlim = zlim ) } else { if (is.null(ylab_aux)) { if (energy_density) { ylab <- "Wavelet Power Spectrum / Scales" } else { ylab <- "Wavelet Power Spectrum" } } plot(X, Z, type = "l", xlab = xlab, ylab = ylab, main = main, xaxt = "n") axis(side = 1, at = X[1 + floor((0:8) * (nt - 1) / 8)]) abline(v = range(X[(coi > Y)]), lty = 2) } } return(list( coefs = coefs, scales = scalesdt, fourierfactor = fourierfactor, coi_maxscale = coi_maxscale )) } #' @title Extracts the center of a vector #' #' @description #' This function is an internal function which extracts from a vector \code{x}, #' the center of the vector of length \code{n}. It emulates the Matlab(R) function \code{wkeep}. #' This function is used by the cwt_wst function when the HAAR wavelet is selected. #' @usage core(x,n) #' #' @param x A vector from wich the center is extracted. #' @param n Numeric. The length of the center of \code{x}. core <- function(x, n) { if (n > length(x)) { stop("Error. The length of the vector x should be greater than n.") } if (n == length(x)) { extracted <- x } else { if (length(x) %% 2 == 0){ # Length of x is even center1 <- length(x) / 2 center2 <- length(x) / 2 + 1 if (n %% 2 == 1) { # n is odd n1 <- center1 - floor(n / 2) n2 <- center2 + floor(n / 2) - 1 } else { # n is even n1 <- center1 - (n / 2 - 1) n2 <- center2 + (n / 2 - 1) } } else { # Length of x is odd center <- floor(length(x) / 2) + 1 if (n %% 2 == 1) { # n is odd n1 <- center - floor(n / 2) n2 <- center + floor(n / 2) } else { # n is even n1 <- center - n / 2 n2 <- center + (n / 2 - 1) } } extracted <- x[n1:n2] } return(extracted) }
/scratch/gouwar.j/cran-all/cranData/wavScalogram/R/cwt_wst.R
#' @title Fourier factor of a wavelet #' #' @description This function computes the Fourier factor of a wavelet, according to #' Torrence and Compo (1998). #' #' @usage fourier_factor(wname = c("MORLET", "DOG", "PAUL", "HAAR", "HAAR2"), #' wparam = NULL) #' #' @param wname A string, equal to "MORLET", "DOG", "PAUL", "HAAR" or "HAAR2" that #' determines the wavelet function. #' @param wparam The corresponding nondimensional parameter for the wavelet function #' (Morlet, DoG or Paul). #' #' @return The numeric value of the Fourier factor. #' #' @examples #' ff <- fourier_factor(wname = "DOG", wparam = 6) #' #' @section References: #' #' C. Torrence, G. P. Compo. A practical guide to wavelet analysis. B. Am. Meteorol. Soc. #' 79 (1998), 61–78. #' #' @export #' fourier_factor <- function(wname = c("MORLET", "DOG", "PAUL", "HAAR", "HAAR2"), wparam = NULL) { wname <- toupper(wname) wname <- match.arg(wname) if (wname == "MORLET") { if (is.null(wparam)) { wparam <- 6 } ff <- (4 * pi) / (wparam + sqrt(2 + wparam ^ 2)) } else if (wname == "PAUL") { if (is.null(wparam)) { wparam <- 4 } ff <- 4 * pi / (2 * wparam + 1) } else if (wname == "DOG") { if (is.null(wparam)) { wparam <- 2 } ff <- 2 * pi * sqrt(2 / (2 * wparam + 1)) } else { # HAAR ff <- 1 } return(ff) }
/scratch/gouwar.j/cran-all/cranData/wavScalogram/R/fourier_factor.R
#' @title Power 2 scales #' #' @description This function constructs power 2 scales (i.e. using a base 2 logarithmic #' scale) from a vector of three elements with the minimum scale, the maximum scale and #' the number of suboctaves per octave, following Torrence and Compo 1998. #' #' @usage pow2scales(scales) #' #' @param scales A vector of three elements with the minimum scale, the maximum scale and #' the number ofsuboctaves per octave. #' #' @return A vector with all the scales. #' #' @examples #' scales <- pow2scales(c(2,128,8)) #' #' @section References: #' #' C. Torrence, G. P. Compo. A practical guide to wavelet analysis. B. Am. Meteorol. Soc. #' 79 (1998), 61–78. #' #' @export #' pow2scales <- function(scales) { if(length(scales) == 3) { scmin <- scales[1] scmax <- scales[2] J1 <- log2(scmax / scmin) Dj <- scales[3] scales <- scmin * 2 ^ ((0:floor(J1 * Dj)) / Dj) if (scales[length(scales)] < scmax) { scales <- c(scales, scmax) } } else { stop("For power scales, a vector of length three should be provided.") } return(scales) }
/scratch/gouwar.j/cran-all/cranData/wavScalogram/R/pow2scales.R
#' @title Scale index of a signal #' #' @description This function computes the scale index of a signal in the scale interval #' \eqn{[s_0,s_1]}, for a given set of scale parameters \eqn{s_1} and taking \eqn{s_0} as #' the minimum scale (see Benítez et al. 2010). #' #' The scale index of a signal in the scale interval \eqn{[s_0,s_1]} is given by the #' quotient \deqn{\frac{S(s_{min})}{S(s_{max})},}{S(s_{min})/S(s_{max})} where \eqn{S} is #' the scalogram, \eqn{s_{max} \in [s_0,s_1]} is the smallest scale such that #' \eqn{S(s)\le S(s_{max})} for all \eqn{s \in [s_0,s_1]}, and #' \eqn{s_{min} \in [s_{max},2s_1]} is the smallest scale such that #' \eqn{S(s_{min})\le S(s)} for all \eqn{s \in [s_{max},2s_1]}. #' #' @usage scale_index(signal = NULL, #' scalog = NULL, #' dt = 1, #' scales = NULL, #' powerscales = TRUE, #' s1 = NULL, #' wname = c("MORLET", "DOG", "PAUL", "HAAR", "HAAR2"), #' wparam = NULL, #' waverad = NULL, #' border_effects = c("BE", "INNER", "PER", "SYM"), #' makefigure = TRUE, #' figureperiod = TRUE, #' plot_scalog = FALSE, #' xlab = NULL, #' ylab = "Scale index", #' main = "Scale Index") #' #' @param signal A vector containing the signal whose scale indices are wanted. #' @param scalog A vector containing the scalogram from which the scale indices are going #' to be computed. If \code{scalog} is not \code{NULL}, then \code{signal}, \code{waverad} #' and \code{border_effects} are not necessary and they are ignored. #' @param dt Numeric. The time step of the signals. #' @param scales A vector containing the wavelet scales at wich the scalogram #' is computed. This can be either a vector with all the scales or, following Torrence #' and Compo 1998, a vector of 3 elements with the minimum scale, the maximum scale and #' the number of suboctaves per octave (in this case, \code{powerscales} must be TRUE in #' order to construct power 2 scales using a base 2 logarithmic scale). If \code{scales} #' is NULL, they are automatically constructed. #' @param powerscales Logical. It must be TRUE (default) in these cases: #' \itemize{ #' \item If \code{scales} are power 2 scales, i.e. they use a base 2 logarithmic scale. #' \item If we want to construct power 2 scales automatically. In this case, \code{scales} #' must be \code{NULL}. #' \item If we want to construct power 2 scales from \code{scales}. In this case, #' \code{length(scales)} must be 3. #' } #' @param s1 A vector containing the scales \eqn{s_1}. The scale indices are computed in #' the intervals \eqn{[s_0,s_1]}, where \eqn{s_0} is the minimum scale in \code{scales}. #' If \code{s1} are not power 2 scales, then \code{scales} should not be power 2 scales #' either and hence, \code{powerscales} must be \code{FALSE}. #' @param wname A string, equal to "MORLET", "DOG", "PAUL", "HAAR" or "HAAR2". The #' difference between "HAAR" and "HAAR2" is that "HAAR2" is more accurate but slower. #' @param wparam The corresponding nondimensional parameter for the wavelet function #' (Morlet, DoG or Paul). #' @param waverad Numeric. The radius of the wavelet used in the computations for the cone #' of influence. If it is not specified, it is asumed to be \eqn{\sqrt{2}} for Morlet and DoG, #' \eqn{1/\sqrt{2}} for Paul and 0.5 for Haar. #' @param border_effects A string, equal to "BE", "INNER", "PER" or "SYM", which indicates #' how to manage the border effects which arise usually when a convolution is performed on #' finite-lenght signals. #' \itemize{ #' \item "BE": With border effects, padding time series with zeroes. #' \item "INNER": Normalized inner scalogram with security margin adapted for each #' different scale. #' \item "PER": With border effects, using boundary wavelets (periodization of the #' original time series). #' \item "SYM": With border effects, using a symmetric catenation of the original time #' series. #' } #' @param makefigure Logical. If TRUE (default), a figure with the scale indices is #' plotted. #' @param figureperiod Logical. If TRUE (default), periods are used in the figure instead #' of scales. #' @param plot_scalog Logical. If TRUE, it plots the scalogram from which the scale indices #' are computed. #' @param xlab A string giving a custom X axis label. If NULL (default) the X label is #' either "s1" or "Period of s1" depending on the value of \code{figureperiod}. #' @param ylab A string giving a custom Y axis label. #' @param main A string giving a custom main title for the figure. #' #' @return A list with the following fields: #' \itemize{ #' \item \code{si}: A vector with the scale indices. #' \item \code{s0}: The scale \eqn{s_0}. #' \item \code{s1}: A vector with the scales \eqn{s_1}. #' \item \code{smax}: A vector with the scales \eqn{s_{max}}. #' \item \code{smin}: A vector with the scales \eqn{s_{min}}. #' \item \code{scalog}: A vector with the scalogram from which the scale indices are #' computed. #' \item \code{scalog_smax}: A vector with the maximum scalogram values \eqn{S(s_{max})}. #' \item \code{scalog_smin}: A vector with the minimum scalogram values \eqn{S(s_{min})}. #' \item \code{fourierfactor}: A factor for converting scales into periods. #' } #' #' @examples #' #' dt <- 0.1 #' time <- seq(0, 50, dt) #' signal <- c(sin(pi * time), sin(pi * time / 2)) #' si <- scale_index(signal = signal, dt = dt) #' #' # Another way, giving the scalogram instead of the signal: #' #' sc <- scalogram(signal = signal, dt = dt, energy_density = FALSE, makefigure = FALSE) #' si <- scale_index(scalog = sc$scalog, scales = sc$scales, dt = dt) #' #' @section References: #' #' R. Benítez, V. J. Bolós, M. E. Ramírez. A wavelet-based tool for studying #' non-periodicity. Comput. Math. Appl. 60 (2010), no. 3, 634-641. #' #' @export #' scale_index <- function(signal = NULL, scalog = NULL, dt = 1, scales = NULL, powerscales = TRUE, s1 = NULL, wname = c("MORLET", "DOG", "PAUL", "HAAR", "HAAR2"), wparam = NULL, waverad = NULL, border_effects = c("BE", "INNER", "PER", "SYM"), makefigure = TRUE, figureperiod = TRUE, plot_scalog = FALSE, xlab = NULL, ylab = "Scale index", main = "Scale Index") { wname <- toupper(wname) wname <- match.arg(wname) fourierfactor <- fourier_factor(wname = wname, wparam = wparam) if (!is.null(scales)) { if (powerscales && length(scales) == 3) { scales <- pow2scales(scales) } else { if (is.unsorted(scales)) { warning("Scales were not sorted.") scales <- sort(scales) } aux <- diff(log2(scales)) if (powerscales && ((max(aux) - min(aux)) / max(aux) > 0.05)) { warning("Scales seem like they are not power 2 scales. Powerscales set to FALSE.") powerscales <- FALSE } } ns <- length(scales) } if (is.null(scalog)) { if (is.null(signal)) { stop("We need a signal or a scalogram (sc).") } if (is.null(waverad)) { if ((wname == "MORLET") || (wname == "DOG")) { waverad <- sqrt(2) } else if (wname == "PAUL") { waverad <- 1 / sqrt(2) } else { # HAAR waverad <- 0.5 } } border_effects <- toupper(border_effects) border_effects <- match.arg(border_effects) nt <- length(signal) if (is.null(scales)) { scmin <- 2 * dt / fourierfactor if (is.null(s1)) { scmax <- floor(nt / (2 * waverad)) * dt } else { scmax <- 2 * max(s1) } if (powerscales) { scales <- pow2scales(c(scmin, scmax, ceiling(256 / log2(scmax / scmin)))) } else { scales <- seq(scmin, scmax, by = (scmax - scmin) / 256) } ns <- length(scales) } } else { if (is.null(scales)) { stop("Scales are needed.") } if (ns != length(scalog)) { stop("The number of scales does not match with length(scalog).") } } if (is.null(s1)) { if (scales[ns] < 2 * scales[1]) { stop("We need larger scales.") } index_s1 <- which(scales <= scales[ns] / 2) s1 <- scales[index_s1] ns1 <- length(s1) index_2s1 <- matrix(0, nrow = ns1, ncol = 1) for (i in 1:ns1) { index_2s1[i] <- max(which(scales <= 2 * s1[i])) } } else { if (is.unsorted(s1)) { s1 <- sort(s1) } ns1 <- length(s1) if (s1[1] < scales[1]){ stop("s1 must be >= the minimum scale.") } if (2*s1[ns1] > scales[ns]) { stop("2*s1 must be <= the maximum scale.") } if (ns1 > 1) { aux <- diff(log2(s1)) if (powerscales && ((max(aux) - min(aux)) / max(aux) > 0.05)) { warning("Scales s1 seem like they are not power 2 scales. You should set powerscales = FALSE or the figure will not be correct.") } } index_s1 <- matrix(0, nrow = ns1, ncol = 1) index_2s1 <- matrix(0, nrow = ns1, ncol = 1) for (i in 1:ns1) { index_s1[i] <- max(which(scales <= s1[i])) index_2s1[i] <- max(which(scales <= 2 * s1[i])) } } scales <- scales[1:index_2s1[ns1]] ns <- length(scales) if (ns < 4) { stop("We need more scales.") } if (is.null(scalog)) { sc <- scalogram(signal = signal, dt = dt, scales = scales, powerscales = FALSE, wname = wname, wparam = wparam, waverad = waverad, border_effects = border_effects, energy_density = FALSE, makefigure = FALSE) scalog <- sc$scalog } else { scalog <- scalog[1:ns] } epsilon <- max(scalog) * 1e-6 # This is considered the "numerical zero". si <- matrix(0, nrow = ns1, ncol = 1) scalog_smin <- si scalog_smax <- si smax <- si smin <- si for (i in 1:ns1) { # Computation of smax scalog_smax[i] <- max(scalog[1:index_s1[i]]) index_smax <- which.max(scalog[1:index_s1[i]]) smax[i] <- scales[index_smax] # Computation of smin scalog_smin[i] <- min(scalog[index_smax:index_2s1[i]]) index_smin <- which.min(scalog[index_smax:index_2s1[i]]) smin[i] <- scales[index_smax + index_smin - 1] # Computation of SI if (scalog_smax[i] < epsilon) { si[i] <- 0 } else { si[i] <- scalog_smin[i] / scalog_smax[i] } } if (plot_scalog) { if (figureperiod) { X <- fourierfactor * scales xlab_scalog <- "Period" } else { X <- scales xlab_scalog <- "Scale" } if (powerscales) { plot(log2(X), scalog, type = "l", xlab = xlab_scalog, ylab = "Scalogram", main = "Scalogram", xaxt = "n") axis(side = 1, at = floor(log2(X)), labels = 2^(floor(log2(X)))) } else { plot(X, scalog, type = "l", xlab = xlab_scalog, ylab = "Scalogram", main = "Scalogram", xaxt = "n") axis(side = 1, at = X[1 + floor((0:8) * (ns - 1) / 8)]) } } if (makefigure ) { if (ns1 > 1) { if (figureperiod) { X <- fourierfactor * s1 if (is.null(xlab)) xlab <- expression('Period of s'[1]) } else { X <- s1 if (is.null(xlab)) xlab <- expression('s'[1]) } if (powerscales) { plot(log2(X), si, type = "l", xlab = xlab, ylab = ylab, main = main, ylim = c(0, 1), xaxt = "n") axis(side = 1, at = floor(log2(X)), labels = 2^(floor(log2(X)))) } else { plot(X, si, type = "l", xlab = xlab, ylab = ylab, main = main, ylim = c(0, 1), xaxt = "n") axis(side = 1, at = X[1 + floor((0:8) * (ns1 - 1) / 8)]) } } else { warning("We can't plot a line with just one point.") } } return(list(si = si, s0 = scales[1], s1 = s1, smax = smax, smin = smin, scalog = scalog, scalog_smax = scalog_smax, scalog_smin = scalog_smin, fourierfactor = fourierfactor) ) }
/scratch/gouwar.j/cran-all/cranData/wavScalogram/R/scale_index.R
#' @title Scalogram of a signal #' #' @description This function computes the normalized scalogram of a signal for the scales #' given. It is important to note that the notion of scalogram here is analogous #' to the spectrum of the Fourier transform. It gives the contribution of each scale to #' the total energy of the signal. For each scale \eqn{s}, it is defined as the square #' root of the integral of the squared modulus of the wavelet transform w.r.t. the time #' variable \eqn{t}, i.e. #' #' \deqn{S(s):= (\int_{-\infty}^{+\infty}|Wf(t,s)|^2 dt)^{1/2}.}{% #' S(s):=(integral_{-\infty}^{+\infty}|Wf(t,s)|^2 dt)^{1/2}.} #' #' "Normalized" means that the scalogram is divided by the square root of the number of #' times, for comparison purposes between different values of the parameter #' \code{border_effects}. #' #' @usage scalogram(signal, #' dt = 1, #' scales = NULL, #' powerscales = TRUE, #' wname = c("MORLET", "DOG", "PAUL", "HAAR", "HAAR2"), #' wparam = NULL, #' waverad = NULL, #' border_effects = c("BE", "INNER", "PER", "SYM"), #' energy_density = TRUE, #' makefigure = TRUE, #' figureperiod = TRUE, #' xlab = NULL, #' ylab = "Scalogram", #' main = "Scalogram") #' #' @param signal A vector containing the signal whose scalogram is wanted. #' @param dt Numeric. The time step of the signal. #' @param scales A vector containing the wavelet scales at wich the scalogram #' is computed. This can be either a vector with all the scales or, following Torrence #' and Compo 1998, a vector of 3 elements with the minimum scale, the maximum scale and #' the number of suboctaves per octave (in this case, \code{powerscales} must be TRUE in #' order to construct power 2 scales using a base 2 logarithmic scale). If \code{scales} #' is NULL, they are automatically constructed. #' @param powerscales Logical. It must be TRUE (default) in these cases: #' \itemize{ #' \item If \code{scales} are power 2 scales, i.e. they use a base 2 logarithmic scale. #' \item If we want to construct power 2 scales automatically. In this case, \code{scales} #' must be \code{NULL}. #' \item If we want to construct power 2 scales from \code{scales}. In this case, #' \code{length(scales)} must be 3. #' } #' @param wname A string, equal to "MORLET", "DOG", "PAUL", "HAAR" or "HAAR2". The #' difference between "HAAR" and "HAAR2" is that "HAAR2" is more accurate but slower. #' @param wparam The corresponding nondimensional parameter for the wavelet function #' (Morlet, DoG or Paul). #' @param waverad Numeric. The radius of the wavelet used in the computations for the cone #' of influence. If it is not specified, it is asumed to be \eqn{\sqrt{2}} for Morlet and DoG, #' \eqn{1/\sqrt{2}} for Paul and 0.5 for Haar. #' @param border_effects String, equal to "BE", "INNER", "PER" or "SYM", which indicates #' how to manage the border effects which arise usually when a convolution is performed on #' finite-lenght signals. #' \itemize{ #' \item "BE": With border effects, padding time series with zeroes. #' \item "INNER": Normalized inner scalogram with security margin adapted for each #' different scale. #' \item "PER": With border effects, using boundary wavelets (periodization of the #' original time series). #' \item "SYM": With border effects, using a symmetric catenation of the original time #' series. #' } #' @param energy_density Logical. If TRUE (default), divide the scalogram by the square #' root of the scales for convert it into energy density. #' @param makefigure Logical. If TRUE (default), a figure with the scalogram is plotted. #' @param figureperiod Logical. If TRUE (default), periods are used in the figure instead #' of scales. #' @param xlab A string giving a custom X axis label. If NULL (default) the X label is #' either "Scale" or "Period" depending on the value of \code{figureperiod}. #' @param ylab A string giving a custom Y axis label. #' @param main A string giving a custom main title for the figure. #' #' @return A list with the following fields: #' \itemize{ #' \item \code{scalog}: A vector of length \code{length(scales)}, containing the values of #' the scalogram at each scale. #' \item \code{scales}: The vector of scales. #' \item \code{energy}: If \code{energy_density} is TRUE, it is the \eqn{L^2} norm of #' \code{scalog}. #' \item \code{fourierfactor}: A factor for converting scales into periods. #' } #' #' @examples #' dt <- 0.1 #' time <- seq(0, 50, dt) #' signal <- c(sin(pi * time), sin(pi * time / 2)) #' scalog <- scalogram(signal = signal, dt = dt, border_effects = "INNER") #' #' @section References: #' #' C. Torrence, G. P. Compo. A practical guide to wavelet analysis. B. Am. Meteorol. Soc. #' 79 (1998), 61–78. #' #' V. J. Bolós, R. Benítez, R. Ferrer, R. Jammazi. The windowed scalogram difference: a #' novel wavelet tool for comparing time series. Appl. Math. Comput., 312 (2017), 49-65. #' #' @export #' scalogram <- function(signal, dt = 1, scales = NULL, powerscales = TRUE, wname = c("MORLET", "DOG", "PAUL", "HAAR", "HAAR2"), wparam = NULL, waverad = NULL, border_effects = c("BE", "INNER", "PER", "SYM"), energy_density = TRUE, makefigure = TRUE, figureperiod = TRUE, xlab = NULL, ylab = "Scalogram", main = "Scalogram") { wname <- toupper(wname) wname <- match.arg(wname) if (is.null(waverad)) { if ((wname == "MORLET") || (wname == "DOG")) { waverad <- sqrt(2) } else if (wname == "PAUL") { waverad <- 1 / sqrt(2) } else { # HAAR waverad <- 0.5 } } border_effects <- toupper(border_effects) border_effects <- match.arg(border_effects) if (border_effects == "INNER") { border_effects_cwt <- "BE" } else { border_effects_cwt <- border_effects } if (!is.null(scales) && powerscales && (length(scales) != 3)) { if (is.unsorted(scales)) { warning("Scales were not sorted.") scales <- sort(scales) } aux <- diff(log2(scales)) if ((max(aux) - min(aux)) / max(aux) > 0.05) { warning("Scales seem like they are not power 2 scales. Powerscales set to FALSE.") powerscales <- FALSE } } nt <- length(signal) cwt <- cwt_wst(signal = signal, dt = dt, scales = scales, powerscales = powerscales, wname = wname, wparam = wparam, waverad = waverad, border_effects = border_effects_cwt, makefigure = FALSE) scalesdt <- cwt$scales scales <- scalesdt / dt ns <- length(scales) coefs <- matrix(cwt$coefs, nrow = nt, ncol = ns) scalog <- numeric(ns) if (border_effects == "INNER") { for (i in 1:ns) { nt_margin <- ceiling(waverad * scales[i]) nt_end <- nt - nt_margin nt_ini <- nt_margin if (nt_end < nt_ini){ print("We need more times for these scales") scalog <- scalog[1:(i - 1)] scales <- scales[1:(i - 1)] scalesdt <- scalesdt[1:(i - 1)] ns <- i - 1 break } scalog[i] <- sqrt(sum(abs(coefs[nt_ini:nt_end, i]) ^ 2)) scalog[i] <- scalog[i] / sqrt(nt_end - nt_ini + 1) # Normalization } } else { scalog <- sqrt(colSums(abs(coefs) ^ 2)) scalog <- scalog / sqrt(nt) # Normalization } energy <- NA if (energy_density) { scalog <- scalog / sqrt(scalesdt) energy <- sqrt(sum(scalog ^ 2)) } fourierfactor <- cwt$fourierfactor if (makefigure) { if (figureperiod) { X <- fourierfactor * scalesdt if (is.null(xlab)) xlab <- "Period" } else { X <- scalesdt if (is.null(xlab)) xlab <- "Scale" } if (powerscales) { plot(log2(X), scalog, type = "l", xlab = xlab, ylab = ylab, main = main, xaxt = "n") axis(side = 1, at = floor(log2(X)), labels = 2^(floor(log2(X)))) } else { plot(X, scalog, type = "l", xlab = xlab, ylab = ylab, main = main, xaxt = "n") axis(side = 1, at = X[1 + floor((0:8) * (ns - 1) / 8)]) } } return(list( scalog = scalog, scales = scalesdt, energy = energy, fourierfactor = fourierfactor )) }
/scratch/gouwar.j/cran-all/cranData/wavScalogram/R/scalogram.R
#' @title Wavelet plots #' #' @description This function plots a function of two variables (usually times and #' scales). It is suitable for plotting windowed scalograms, windowed scalogram #' differences, wavelet coherences and windowed scale indices. #' #' @usage wavPlot(Z, #' X = NULL, #' Y = NULL, #' Ylog = FALSE, #' Yrev = TRUE, #' zlim = NULL, #' coi = NULL, #' rdist = NULL, #' sig95 = NULL, #' sig05 = NULL, #' Xname = "X", #' Yname = "Y", #' Zname = "Z") #' #' @param Z A matrix with the images of the function to be plotted. #' @param X A vector with x-coordinates (times). #' @param Y A vector with y-coordinates (scales). #' @param Ylog Logical. Considers logarithmic scale for the y-axis. #' @param Yrev Logical. Considers reverse the y-axis. #' @param zlim A vector of length 2 with the limits for the z-axis (the color bar). #' @param coi A vector of size \code{length(X)} with the y-coordinates of the frontier of #' the cone of influence. #' @param rdist Numeric. Only for WSD plots, margin in the y-axis where appear border #' effects. #' @param sig95 Logical matrix with the same size as Z. TRUE if the corresponding point in #' Z is inside the significance at 95\%. #' @param sig05 Logical matrix with the same size as Z. TRUE if the corresponding point in #' Z is inside the significance at 5\%. #' @param Xname A string with the name of the x-axis. #' @param Yname A string with the name of the y-axis. #' @param Zname A string with the name of the function. #' #' @importFrom fields image.plot #' @importFrom grDevices colorRampPalette rgb #' @importFrom graphics axis contour image lines plot segments #' @importFrom stats quantile rnorm sd #' #' @examples #' #' nt <- 1500 #' time <- 1:nt #' sd_noise <- 0.2 #% In Bolós et al. 2017 Figure 1, sd_noise = 1. #' signal1 <- rnorm(n = nt, mean = 0, sd = sd_noise) + sin(time / 10) #' signal2 <- rnorm(n = nt, mean = 0, sd = sd_noise) + sin(time / 10) #' signal2[500:1000] = signal2[500:1000] + sin((500:1000) / 2) #' \dontrun{ #' wsd <- wsd(signal1 = signal1, signal2 = signal2, mc_nrand = 10, makefigure = FALSE) #' wavPlot(Z = -log2(wsd$wsd), X = wsd$t, Y = wsd$scales, Ylog = TRUE, coi = wsd$coi, #' rdist = wsd$rdist, sig95 = wsd$signif95, sig05 = wsd$signif05, Xname = "Time", #' Yname = "Scale", Zname = "-log2(WSD)") #' } #' #' @export #' wavPlot <- function(Z, X = NULL, Y = NULL, Ylog = FALSE, Yrev = TRUE, zlim = NULL, coi = NULL, rdist = NULL, sig95 = NULL, sig05 = NULL, Xname = "X", Yname = "Y", Zname = "Z") { Xlen <- dim(Z)[1] Ylen <- dim(Z)[2] if (is.null(X)) { X <- 1:Xlen } if (is.null(Y)) { Y <- 1:Ylen } COLORS <- c("#0000AA", "#000EB8", "#001CC6", "#002BD4", "#0039E3", "#0047F1", "#0055FF", "#0063FF", "#0071FF", "#0080FF", "#008EFF", "#009CFF", "#00AAFF", "#0DB8FF", "#1BC6FF", "#28D4FF", "#36E3FF", "#43F1FF", "#51FFFF", "#5EFFF2", "#6BFFE4", "#79FFD7", "#86FFC9", "#94FFBC", "#A1FFAE", "#AEFFA1", "#BCFF94", "#C9FF86", "#D7FF79", "#E4FF6B", "#F2FF5E", "#FFFF51", "#FFF143", "#FFE336", "#FFD528", "#FFC61B", "#FFB80D", "#FFAA00", "#FF9C00", "#FF8E00", "#FF8000", "#FF7100", "#FF6300", "#FF5500", "#F14700", "#E33900", "#D52B00", "#C61C00", "#B80E00", "#AA0000") if (Ylog) { YY <- log2(Y) Ystep <- 1 #labels <- floor(2 ^ (seq(from = YY[1], to = YY[Ylen], by = Ystep))) labels <- round(2 ^ (seq(from = YY[1], to = YY[Ylen], by = Ystep)), 2) if(!is.null(coi)) { plotcoi <- log2(coi) } } else { YY <- Y Ystep <- (Y[Ylen] - Y[1]) / 6 #labels <- floor(seq(from = YY[1], to = YY[Ylen], by = Ystep)) labels <- round(seq(from = YY[1], to = YY[Ylen], by = Ystep), 2) if(!is.null(coi)) { plotcoi <- coi } } if (Yrev) { Yini <- Ylen Yend <- 1 Ystep <- -Ystep if(!is.null(coi)) { plotcoi <- (YY[Ylen] - plotcoi + YY[1]) } } else { Yini <- 1 Yend <- Ylen } image.plot( X, YY, Z[, Yini:Yend], col = COLORS, yaxt = "n", xlab = Xname, ylab = Yname, main = Zname, ylim = c(YY[1], YY[Ylen]), zlim = zlim ) # Axis ticks and labels axis( side = 2, at = seq(from = YY[Yini], to = YY[Yend], by = Ystep), labels = labels ) # COI if (!is.null(coi)) { coi_matrix <- matrix(NA, nrow = Xlen, ncol = Ylen) for (i in 1:Xlen) { coi_matrix[i, Y > coi[i]] <- 1 } pal <- colorRampPalette(c(rgb(1, 1, 1), rgb(0, 0, 0))) COLORS2 <- add.alpha(pal(20), 0.5) image(X, YY, coi_matrix[, Yini:Yend], col = COLORS2, add = T) segments(x0 = X[-Xlen], x1 = X[-1], y0 = plotcoi[-Xlen], y1 = plotcoi[-1]) } # Y margins if (!is.null(rdist)) { ymargin_up <- numeric(Xlen) ymargin_down <- YY[rdist] ymargin_matrix <- matrix(NA, nrow = Xlen, ncol = Ylen) ymargin_matrix[, 1:rdist] <- 1 for (i in 1:Xlen) { aux <- max(which(!is.na(Z[i, ])))-rdist+1 ymargin_up[i] <- YY[aux] ymargin_matrix[i, aux:Ylen] <- 1 } if (Yrev) { ymargin_up <- (YY[Ylen] - ymargin_up + YY[1]) ymargin_down <- (YY[Ylen] - ymargin_down + YY[1]) } pal <- colorRampPalette(c(rgb(1, 1, 1), rgb(0, 0, 0))) COLORS2 <- add.alpha(pal(20), 0.5) image(X, YY, ymargin_matrix[, Yini:Yend], col = COLORS2, add = T) segments(x0 = X[1], x1 = X[Xlen], y0 = ymargin_down, y1 = ymargin_down) segments(x0 = X[-Xlen], x1 = X[-1], y0 = ymargin_up[-Xlen], y1 = ymargin_up[-1]) } # Significance levels if (!is.null(sig95)) { contour(x = X, y = YY, z = sig95[, Yini:Yend], levels = 1, col = "black", lwd = 1, drawlabels = FALSE, add = TRUE) } if (!is.null(sig05)) { contour(x = X, y = YY, z = sig05[, Yini:Yend], levels = 1, col = "white", lwd = 1, drawlabels = FALSE, add = TRUE) } } add.alpha <- function(COLORS, ALPHA){ if(missing(ALPHA)) stop("provide a value for alpha between 0 and 1") RGB <- grDevices::col2rgb(COLORS, alpha=TRUE) RGB[4,] <- round(RGB[4,]*ALPHA) NEW.COLORS <- grDevices::rgb(RGB[1,], RGB[2,], RGB[3,], RGB[4,], maxColorValue = 255) return(NEW.COLORS) }
/scratch/gouwar.j/cran-all/cranData/wavScalogram/R/wavPlot.R
#' @title Wavelet radius #' #' @description #' This function computes an approximation of the effective radius of a mother wavelet. #' #' @usage wavelet_radius(wname = c("MORLET", "DOG", "PAUL", "HAAR", "HAAR2"), #' wparam = NULL, #' perc = .0025, #' scale = 100, #' n = 1000, #' makefigure = FALSE) #' #' @param wname A string, equal to "MORLET", "DOG", "PAUL", "HAAR" or "HAAR2". The #' difference between "HAAR" and "HAAR2" is that "HAAR2" is more accurate but slower. #' @param wparam The corresponding nondimensional parameter for the wavelet function #' (Morlet, DoG or Paul). #' @param perc Numeric. The wavelet radius is computed so that the area covered is at #' least the 100*(1-\code{perc})\% of the total area of the mother wavelet. #' @param scale Numeric. Scale of the wavelet used in the computations. It only affects #' the accuracy. #' @param n Numeric. The computations use a time series of length \eqn{2n+1}. #' @param makefigure Logical. Plots a figure with the real part of the mother wavelet and #' its modulus. #' #' @return A list with the following fields: #' \itemize{ #' \item \code{left}: The radius on the left. #' \item \code{right}: The radius on the right. #' } #' #' @examples #' waverad <- wavelet_radius(wname = "MORLET", makefigure = TRUE) #' #' @export #' wavelet_radius <- function(wname = c("MORLET", "DOG", "PAUL", "HAAR", "HAAR2"), wparam = NULL, perc = .0025, scale = 100, n = 1000, makefigure = FALSE) { wname <- toupper(wname) wname <- match.arg(wname) signal <- c(numeric(n), 1, numeric(n)) nt <- 2 * n + 1 cwt <- cwt_wst(signal = signal, scales = scale, powerscales = FALSE, wname = wname, wparam = wparam, waverad = 1, # For not calling wavelet_radius infinitely! makefigure = FALSE) coefs <- cwt$coefs abscoefs <- abs(coefs) area <- numeric(nt) area[1] <- abscoefs[1] for (i in 2:nt) { area[i] <- area[i - 1] + abscoefs[i] } kk <- perc * area[nt] / 2 i_right <- max(which(area <= kk)) right <- (n + 1 - i_right - (kk - area[i_right]) / abscoefs[i_right + 1]) / scale abscoefs_rev <- rev(abscoefs) area_rev <- numeric(nt) area_rev[1] <- abscoefs_rev[1] for (i in 2:nt) { area_rev[i] <- area_rev[i - 1] + abscoefs_rev[i] } i_left <- max(which(area_rev <= kk)) left <- (n + 1 - i_left - (kk - area_rev[i_left]) / abscoefs_rev[i_left + 1]) / scale i_left <- 2 * n + 2 - i_left if (makefigure) { i_left_margin <- min(nt, i_left + floor((i_left - n - 1) / 4)) i_right_margin <- max(1, i_right - floor((n + 1 - i_right) / 4)) xleft <- - (i_left_margin - n - 1) / scale xright <- (n + 1 - i_right_margin) / scale x <- seq(from = xleft, to = xright, by = 1 / scale) ylim <- sqrt(scale) * range(abscoefs, Re(coefs)) plot(x, sqrt(scale) * abscoefs[i_left_margin:i_right_margin], type = "l", xlab = "t", ylab = "", ylim = ylim, lty = 3) lines(x, sqrt(scale) * Re(coefs[i_left_margin:i_right_margin])) segments(x0 = -right, x1 = -right, y0 = ylim[1], y1 = ylim[2]) segments(x0 = left, x1 = left, y0 = ylim[1], y1 = ylim[2]) } return(list( left = left, right = right )) }
/scratch/gouwar.j/cran-all/cranData/wavScalogram/R/wavelet_radius.R
#' @title Windowed scale index #' #' @description This function computes the windowed scale indices of a signal in the scale #' interval \eqn{[s_0,s_1]}, for a given set of scale parameters \eqn{s_1} and taking #' \eqn{s_0} as the minimum scale (see Benítez et al. 2010). #' #' The windowed scale index of a signal in the scale interval \eqn{[s_0,s_1]} centered at #' time \eqn{tc} and with time windows radius \code{windowrad} is given by the quotient #' \deqn{\frac{WS_{windowrad}(tc,s_{min})}{WS_{windowrad}(tc,s_{max})},}{WS_{windowrad} #' (tc,s_{min})/WS_{windowrad}(tc,s_{max}),} #' where \eqn{WS_{windowrad}} is the corresponding windowed scalogram with time windows #' radius \code{windowrad}, \eqn{s_{max} \in [s_0,s_1]} is the smallest scale such that #' \eqn{WS_{windowrad}(tc,s)\le WS_{windowrad}(tc,s_{max})} for all \eqn{s \in [s_0,s_1]}, #' and \eqn{s_{min} \in [s_{max},2s_1]} is the smallest scale such that #' \eqn{WS_{windowrad}(tc,s_{min})\le WS_{windowrad}(tc,s)} for all #' \eqn{s \in [s_{max},2s_1]}. #' #' @usage windowed_scale_index(signal = NULL, #' wsc = NULL, #' wsc_coi = NULL, #' dt = 1, #' scales = NULL, #' powerscales = TRUE, #' s1 = NULL, #' windowrad = NULL, #' delta_t = NULL, #' wname = c("MORLET", "DOG", "PAUL", "HAAR", "HAAR2"), #' wparam = NULL, #' waverad = NULL, #' border_effects = c("BE", "INNER", "PER", "SYM"), #' makefigure = TRUE, #' time_values = NULL, #' figureperiod = TRUE, #' plot_wsc = FALSE, #' xlab = "Time", #' ylab = NULL, #' main = "Windowed Scale Index", #' zlim = NULL) #' #' @param signal A vector containing the signal whose windowed scale indices are wanted. #' @param wsc A matrix containing the windowed scalograms from which the windowed scale #' indices are going to be computed (number of times x number of scales, as it is returned #' by the \code{windowed_scalogram} function). If \code{wsc} is not \code{NULL}, then #' \code{signal}, \code{windowrad}, \code{delta_t}, \code{waverad} and #' \code{border_effects} are not necessary and they are ignored. #' @param wsc_coi A vector of length \code{nrow(wsc)} (i.e. number of times) containing #' the values of the maximum scale at each time from which there are border effects in the #' windowed scalogram \code{wsc}. If \code{wsc} is \code{NULL}, then \code{wsc_coi} is not #' necessary and it is ignored. #' @param dt Numeric. The time step of the signal. #' @param scales A vector containing the wavelet scales at wich the windowed scalograms #' are computed. This can be either a vector with all the scales or, following Torrence #' and Compo 1998, a vector of 3 elements with the minimum scale, the maximum scale and #' the number of suboctaves per octave. In the first case, \code{powerscales} must be #' \code{FALSE} if the given scales are not power 2 scales. In the second case, #' \code{powerscales} must be \code{TRUE} in order to construct power 2 scales using a #' base 2 logarithmic scale). If \code{scales} is NULL, they are automatically constructed. #' @param powerscales Logical. It must be TRUE (default) only in these cases: #' \itemize{ #' \item If \code{scales} are power 2 scales, i.e. they use a base 2 logarithmic scale. #' \item If we want to construct power 2 scales automatically. In this case, \code{scales} #' must be \code{NULL}. #' \item If we want to construct power 2 scales from \code{scales}. In this case, #' \code{length(scales)} must be 3. #' } #' Otherwise, it must be \code{FALSE}. #' @param s1 A vector containing the scales \eqn{s_1}. The windowed scale indices are #' computed in the intervals \eqn{[s_0,s_1]}, where \eqn{s_0} is the minimum scale in #' \code{scales}. If \code{s1} are not power 2 scales, then \code{scales} should not be #' power 2 scales either and hence, \code{powerscales} must be \code{FALSE}. #' @param windowrad Integer. Time radius for the windows, measured in dt. By default, #' it is set to \eqn{ceiling(length(signal) / 20)}. #' @param delta_t Integer. Increment of time for the construction of windows central #' times, measured in \code{dt}. By default, it is set to #' \eqn{ceiling(length(signal) / 256)}. #' @param wname A string, equal to "MORLET", "DOG", "PAUL", "HAAR" or "HAAR2". The #' difference between "HAAR" and "HAAR2" is that "HAAR2" is more accurate but slower. #' @param wparam The corresponding nondimensional parameter for the wavelet function #' (Morlet, DoG or Paul). #' @param waverad Numeric. The radius of the wavelet used in the computations for the cone #' of influence. If it is not specified, it is asumed to be \eqn{\sqrt{2}} for Morlet and DoG, #' \eqn{1/\sqrt{2}} for Paul and 0.5 for Haar. #' @param border_effects A string, equal to "BE", "INNER", "PER" or "SYM", which indicates #' how to manage the border effects which arise usually when a convolution is performed on #' finite-lenght signals. #' \itemize{ #' \item "BE": With border effects, padding time series with zeroes. #' \item "INNER": Normalized inner scalogram with security margin adapted for each #' different scale. #' \item "PER": With border effects, using boundary wavelets (periodization of the #' original time series). #' \item "SYM": With border effects, using a symmetric catenation of the original time #' series. #' } #' @param makefigure Logical. If TRUE (default), a figure with the windowed scale indices #' is plotted. #' @param time_values A numerical vector of length \code{length(signal)} containing custom #' time values for the figure. If NULL (default), it will be computed starting at 0. #' @param figureperiod Logical. If TRUE (default), periods are used in the figure instead #' of scales. #' @param plot_wsc Logical. If TRUE, it plots the windowed scalograms from which the #' windowed scale indices are computed. #' @param xlab A string giving a custom X axis label. #' @param ylab A string giving a custom Y axis label. If NULL (default) the Y label is #' either "s1" or "Period of s1" depending on the value of \code{figureperiod} if #' \code{length(s1) > 1}, or "Windowed Scale Index" if \code{length(s1) == 1}. #' @param main A string giving a custom main title for the figure. #' @param zlim A vector of length 2 with the limits for the z-axis (the color bar). #' #' @return A list with the following fields: #' \itemize{ #' \item \code{wsi}: A matrix of size \code{length(tcentral)} x \code{length(s1)} #' containing the values of the corresponding windowed scale indices. #' \item \code{s0}: The scale \eqn{s_0}. #' \item \code{s1}: The vector of scales \eqn{s_1}. #' \item \code{smax}: A matrix of size \code{length(tcentral)} x \code{length(s1)} #' containing the scales \eqn{s_{max}}. #' \item \code{smin}: A matrix of size \code{length(tcentral)} x \code{length(s1)} #' containing the scales \eqn{s_{min}}. #' \item \code{wsc}: A matrix of size \code{length(tcentral)} x \code{length(scales)} #' containing the windowed scalograms from which the windowed scale indices are computed. #' \item \code{scalog_smax}: A matrix of size \code{length(tcentral)} x \code{length(s1)} #' containing the values of the corresponding scalograms at scales \eqn{s_{max}}. #' \item \code{scalog_smin}: A matrix of size \code{length(tcentral)} x \code{length(s1)} #' containing the values of the corresponding scalograms at scales \eqn{s_{min}}. #' \item \code{tcentral}: The vector of central times used in the computation of #' \code{wsi}. #' \item \code{windowrad}: Radius for the time windows, measured in \code{dt}. #' \item \code{fourierfactor}: A factor for converting scales into periods. #' \item \code{coi_maxscale}: A vector of length \code{length(tcentral)} containing the #' values of the maximum scale at each time from which there are border effects. #' } #' #' @importFrom graphics abline #' #' @examples #' #' dt <- 0.1 #' time <- seq(0, 50, dt) #' signal <- c(sin(pi * time), sin(pi * time / 2)) #' # First, we try with default s1 scales (a vector with a wide range of values for s1). #' wsi_full <- windowed_scale_index(signal = signal, dt = dt, figureperiod = FALSE) #' # Next, we choose a meaningful s1 value, greater than all relevant scales. #' wsi <- windowed_scale_index(signal = signal, dt = dt, s1 = 4, figureperiod = FALSE) #' #' # Another way, giving the windowed scalograms instead of the signal: #' #' wsc <- windowed_scalogram(signal = signal, dt = dt, figureperiod = FALSE, #' energy_density = FALSE, makefigure = FALSE) #' wsi_full <- windowed_scale_index(wsc = wsc$wsc, wsc_coi = wsc$coi_maxscale, #' scales = wsc$scales, time_values = wsc$tcentral, #' figureperiod = FALSE) #' wsi <- windowed_scale_index(wsc = wsc$wsc, wsc_coi = wsc$coi_maxscale, #' scales = wsc$scales, s1 = 4, time_values = wsc$tcentral, #' figureperiod = FALSE) #' #' @section References: #' #' R. Benítez, V. J. Bolós, M. E. Ramírez. A wavelet-based tool for studying #' non-periodicity. Comput. Math. Appl. 60 (2010), no. 3, 634-641. #' #' @export #' windowed_scale_index <- function(signal = NULL, wsc = NULL, wsc_coi = NULL, dt = 1, scales = NULL, powerscales = TRUE, s1 = NULL, windowrad = NULL, delta_t = NULL, wname = c("MORLET", "DOG", "PAUL", "HAAR", "HAAR2"), wparam = NULL, waverad = NULL, border_effects = c("BE", "INNER", "PER", "SYM"), makefigure = TRUE, time_values = NULL, figureperiod = TRUE, plot_wsc = FALSE, xlab = "Time", ylab = NULL, main = "Windowed Scale Index", zlim = NULL) { wname <- toupper(wname) wname <- match.arg(wname) fourierfactor <- fourier_factor(wname = wname, wparam = wparam) if (!is.null(scales)) { if (powerscales && length(scales) == 3) { scales <- pow2scales(scales) } else { if (is.unsorted(scales)) { warning("Scales were not sorted.") scales <- sort(scales) } aux <- diff(log2(scales)) if (powerscales && ((max(aux) - min(aux)) / max(aux) > 0.05)) { warning("Scales seem like they are not power 2 scales. Powerscales set to FALSE.") powerscales <- FALSE } } ns <- length(scales) } if (is.null(wsc)) { if (is.null(signal)) { stop("We need a signal or a windowed scalogram (wsc).") } if (is.null(waverad)) { if ((wname == "MORLET") || (wname == "DOG")) { waverad <- sqrt(2) } else if (wname == "PAUL") { waverad <- 1 / sqrt(2) } else { # HAAR waverad <- 0.5 } } border_effects <- toupper(border_effects) border_effects <- match.arg(border_effects) nt <- length(signal) if (is.null(delta_t)) { delta_t <- ceiling(nt / 256) } if (is.null(windowrad)) { windowrad <- ceiling(nt / 20) } else { windowrad <- min(windowrad, floor((nt - 1) / 2)) } if (is.null(scales)) { scmin <- 2 * dt / fourierfactor if (is.null(s1)) { scmax <- floor((nt - 2 * windowrad) / (2 * waverad)) * dt } else { scmax <- 2 * max(s1) } if (powerscales) { scales <- pow2scales(c(scmin, scmax, ceiling(256 / log2(scmax / scmin)))) } else { scales <- seq(scmin, scmax, by = (scmax - scmin) / 256) } ns <- length(scales) } } else { if (is.null(scales)) { stop("Scales are needed.") } if (ns != ncol(wsc)) { stop("The number of scales does not match with ncol(wsc).") } } if (is.null(s1)) { if (scales[ns] < 2 * scales[1]) { stop("We need larger scales.") } index_s1 <- which(scales <= scales[ns] / 2) s1 <- scales[index_s1] ns1 <- length(s1) index_2s1 <- numeric(ns1) for (j in 1:ns1) { index_2s1[j] <- max(which(scales <= 2 * s1[j])) } } else { if (is.unsorted(s1)) { s1 <- sort(s1) } ns1 <- length(s1) if (s1[1] < scales[1]){ stop("s1 must be >= the minimum scale.") } if (2 * s1[ns1] > scales[ns]) { stop("2*s1 must be <= the maximum scale.") } if (ns1 > 1) { aux <- diff(log2(s1)) if (powerscales && ((max(aux) - min(aux)) / max(aux) > 0.05)) { warning("Scales s1 seem like they are not power 2 scales. You should set powerscales = FALSE or the figure will not be correct.") } } index_s1 <- numeric(ns1) index_2s1 <- numeric(ns1) for (j in 1:ns1) { index_s1[j] <- max(which(scales <= s1[j])) index_2s1[j] <- max(which(scales <= 2 * s1[j])) } } scales <- scales[1:index_2s1[ns1]] ns <- length(scales) if (ns < 4) { stop("We need more scales.") } if (is.null(wsc)) { wsc <- windowed_scalogram(signal = signal, dt = dt, scales = scales, powerscales = FALSE, windowrad = windowrad, delta_t = delta_t, wname = wname, wparam = wparam, waverad = waverad, border_effects = border_effects, energy_density = FALSE, makefigure = FALSE) tcentraldt <- wsc$tcentral nwsi <- length(tcentraldt) coi_maxscale <- wsc$coi_maxscale / 2 wsc <- wsc$wsc } else { wsc <- wsc[, 1:ns] nwsi <- nrow(wsc) nt <- nwsi if (!is.null(delta_t)) { dt <- dt * delta_t } delta_t <- 1 tcentraldt <- seq(from = 1, by = dt, length.out = nwsi) coi_maxscale <- NULL if (!is.null(wsc_coi)) { if (length(wsc_coi) == nwsi) { coi_maxscale <- wsc_coi / 2 } else { warning("Invalid length of wsc_coi.") } } } wsi <- matrix(NA, nrow = nwsi, ncol = ns1) scalog_smax <- wsi scalog_smin <- wsi smax <- wsi smin <- wsi epsilon <- max(wsc, na.rm = TRUE) * 1e-6 # This is considered the "numerical zero" for (i in 1:nwsi) { # Si todo es NA hay que saltarlo: if (any(!is.na(wsc[i, index_2s1]))) { ni <- max(which(!is.na(wsc[i, index_2s1]))) # If border_effects = "INNER" there are NA in wsc. for (j in 1:ni) { scalog_smax[i, j] <- max(wsc[i, 1:index_s1[j]]) if (scalog_smax[i, j] > epsilon) { index_smax <- which.max(wsc[i, 1:index_s1[j]]) smax[i, j] <- scales[index_smax] scalog_smin[i, j] <- min(wsc[i, index_smax:index_2s1[j]]) index_smin <- which.min(wsc[i, index_smax:index_2s1[j]]) smin[i, j] <- scales[index_smax + index_smin - 1] wsi[i, j] <- scalog_smin[i, j] / scalog_smax[i, j] } } } } if (plot_wsc) { if (figureperiod) { Y <- fourierfactor * scales if (is.null(coi_maxscale)) { coi <- NULL } else { coi <- fourierfactor * coi_maxscale * 2 } ylab_wsc <- "Period" } else { Y <- scales coi <- coi_maxscale * 2 ylab_wsc <- "Scale" } if (is.null(time_values)) { X <- tcentraldt } else { if (length(time_values) != nt) { warning("Invalid length of time_values vector. Changing to default.") X <- tcentraldt } else { aux <- floor((nt - (nwsi - 1) * delta_t + 1) / 2) X <- time_values[seq(from = aux, to = aux + (nwsi - 1) * delta_t, by = delta_t)] } } if (length(Y) > 1) { wavPlot( Z = wsc, X = X, Y = Y, Ylog = powerscales, coi = coi, Xname = "Time", Yname = ylab_wsc, Zname = "Windowed Scalogram" ) } else { ylab <- "Windowed Scalogram" plot(X, wsc, type = "l", xlab = "Time", ylab = ylab_wsc, main = "Windowed Scalogram", xaxt = "n") axis(side = 1, at = X[1 + floor((0:8) * (nwsi - 1) / 8)]) abline(v = range(X[(coi > Y)]), lty = 2) } } if (makefigure) { if (figureperiod) { Y <- fourierfactor * s1 if (is.null(coi_maxscale)) { coi <- NULL } else { coi <- fourierfactor * coi_maxscale } if ((is.null(ylab)) && length(Y) > 1) ylab <- expression('Period of s'[1]) } else { Y <- s1 coi <- coi_maxscale if ((is.null(ylab)) && length(Y) > 1) ylab <- expression('s'[1]) } if (is.null(time_values)) { X <- tcentraldt } else { if (length(time_values) != nt) { warning("Invalid length of time_values vector. Changing to default.") X <- tcentraldt } else { aux <- floor((nt - (nwsi - 1) * delta_t + 1) / 2) X <- time_values[seq(from = aux, to = aux + (nwsi - 1) * delta_t, by = delta_t)] } } if (length(Y) > 1) { wavPlot( Z = wsi, X = X, Y = Y, Ylog = powerscales, coi = coi, Xname = xlab, Yname = ylab, Zname = main, zlim = zlim ) } else { if (is.null(ylab)) ylab <- "Windowed Scale Index" plot(X, wsi, type = "l", xlab = xlab, ylab = ylab, main = main, ylim = c(0, 1), xaxt = "n") axis(side = 1, at = X[1 + floor((0:8) * (nwsi - 1) / 8)]) abline(v = range(X[(coi > Y)]), lty = 2) } } return(list( wsi = wsi, s0 = scales[1], s1 = s1, smax = smax, smin = smin, wsc = wsc, scalog_smax = scalog_smax, scalog_smin = scalog_smin, tcentral = tcentraldt, windowrad = windowrad, fourierfactor = fourierfactor, coi_maxscale = coi_maxscale )) }
/scratch/gouwar.j/cran-all/cranData/wavScalogram/R/windowed_scale_index.R
#' @title Windowed scalograms of a signal #' #' @description This function computes the normalized windowed scalograms of a signal for #' the scales given. It is computed using time windows with radius \code{windowrad} #' centered at a vector of central times with increment of time \code{delta_t}. It is #' important to note that the notion of scalogram here is analogous to the spectrum of the #' Fourier transform. It gives the contribution of each scale to the total energy of the #' signal. For each scale \eqn{s} and central time \eqn{tc}, it is defined as the square #' root of the integral of the squared modulus of the wavelet transform w.r.t the time #' variable \eqn{t}, i.e. #' #' \deqn{WS_{windowrad}(tc,s):= #' (\int_{tc-windowrad}^{tc+windowrad}|Wf(t,s)|^2 dt)^{1/2}.}{WS_{windowrad}(tc,s):= #' (integral_{tc-windowrad}^{tc+windowrad}|Wf(t,s)|^2 dt)^{1/2}.} #' #' "Normalized" means that the windowed scalograms are divided by the square root of the #' length of the respective time windows in order to be comparable between them. #' #' #' @usage windowed_scalogram(signal, #' dt = 1, #' scales = NULL, #' powerscales = TRUE, #' windowrad = NULL, #' delta_t = NULL, #' wname = c("MORLET", "DOG", "PAUL", "HAAR", "HAAR2"), #' wparam = NULL, #' waverad = NULL, #' border_effects = c("BE", "INNER", "PER", "SYM"), #' energy_density = TRUE, #' makefigure = TRUE, #' time_values = NULL, #' figureperiod = TRUE, #' xlab = "Time", #' ylab = NULL, #' main = "Windowed Scalogram", #' zlim = NULL) #' #' @param signal A vector containing the signal whose windowed scalogram is wanted. #' @param dt Numeric. The time step of the signal. #' @param scales A vector containing the wavelet scales at wich the windowed scalograms #' are computed. This can be either a vector with all the scales or, following Torrence #' and Compo 1998, a vector of 3 elements with the minimum scale, the maximum scale and #' the number of suboctaves per octave. In the first case, \code{powerscales} must be #' \code{FALSE} if the given scales are not power 2 scales. In the second case, #' \code{powerscales} must be \code{TRUE} in order to construct power 2 scales using a #' base 2 logarithmic scale). If \code{scales} is NULL, they are automatically constructed. #' @param powerscales Logical. It must be TRUE (default) only in these cases: #' \itemize{ #' \item If \code{scales} are power 2 scales, i.e. they use a base 2 logarithmic scale. #' \item If we want to construct power 2 scales automatically. In this case, \code{scales} #' must be \code{NULL}. #' \item If we want to construct power 2 scales from \code{scales}. In this case, #' \code{length(scales)} must be 3. #' } #' Otherwise, it must be \code{FALSE}. #' @param windowrad Integer. Time radius for the windows, measured in \code{dt}. By #' default, it is set to \eqn{ceiling(length(signal) / 20)}. #' @param delta_t Integer. Increment of time for the construction of windows central #' times, measured in \code{dt}. By default, it is set to #' \eqn{ceiling(length(signal) / 256)}. #' @param wname A string, equal to "MORLET", "DOG", "PAUL", "HAAR" or "HAAR2". The #' difference between "HAAR" and "HAAR2" is that "HAAR2" is more accurate but slower. #' @param wparam The corresponding nondimensional parameter for the wavelet function #' (Morlet, DoG or Paul). #' @param waverad Numeric. The radius of the wavelet used in the computations for the cone #' of influence. If it is not specified, it is asumed to be \eqn{\sqrt{2}} for Morlet and DoG, #' \eqn{1/\sqrt{2}} for Paul and 0.5 for Haar. #' @param border_effects String, equal to "BE", "INNER", "PER" or "SYM", which indicates #' how to manage the border effects which arise usually when a convolution is performed on #' finite-lenght signals. #' \itemize{ #' \item "BE": With border effects, padding time series with zeroes. #' \item "INNER": Normalized inner scalogram with security margin adapted for each #' different scale. Although there are no border effects, it is shown as a regular COI #' the zone in which the length of \eqn{J(s)} (see Benítez et al. 2010) is smaller and #' it has to be normalized. #' \item "PER": With border effects, using boundary wavelets (periodization of the #' original time series). #' \item "SYM": With border effects, using a symmetric catenation of the original time #' series. #' } #' @param energy_density Logical. If TRUE (default), divide the scalograms by the square #' root of the scales for convert them into energy density. #' @param makefigure Logical. If TRUE (default), a figure with the scalograms is plotted. #' @param time_values A numerical vector of length \code{length(signal)} containing custom #' time values for the figure. If NULL (default), it will be computed starting at 0. #' @param figureperiod Logical. If TRUE (default), periods are used in the figure instead #' of scales. #' @param xlab A string giving a custom X axis label. #' @param ylab A string giving a custom Y axis label. If NULL (default) the Y label is #' either "Scale" or "Period" depending on the value of \code{figureperiod} if #' \code{length(scales) > 1}, or "Windowed Scalogram" if \code{length(scales) == 1}. #' @param main A string giving a custom main title for the figure. #' @param zlim A vector of length 2 with the limits for the z-axis (the color bar). #' #' @return A list with the following fields: #' \itemize{ #' \item \code{wsc}: A matrix of size \code{length(tcentral)} x \code{length(scales)} #' containing the values of the windowed scalograms at each scale and at each time window. #' \item \code{tcentral}: The vector of central times at which the windows are centered. #' \item \code{scales}: The vector of the scales. #' \item \code{windowrad}: Radius for the time windows, measured in \code{dt}. #' \item \code{fourierfactor}: A factor for converting scales into periods. #' \item \code{coi_maxscale}: A vector of length \code{length(tcentral)} containing the #' values of the maximum scale from which there are border effects for the respective #' central time. #' } #' #' @importFrom graphics abline #' #' @examples #' dt <- 0.1 #' time <- seq(0, 50, dt) #' signal <- c(sin(pi * time), sin(pi * time / 2)) #' wscalog <- windowed_scalogram(signal = signal, dt = dt) #' #' #' @section References: #' #' C. Torrence, G. P. Compo. A practical guide to wavelet analysis. B. Am. Meteorol. Soc. #' 79 (1998), 61–78. #' #' V. J. Bolós, R. Benítez, R. Ferrer, R. Jammazi. The windowed scalogram difference: a #' novel wavelet tool for comparing time series. Appl. Math. Comput., 312 (2017), 49-65. #' #' R. Benítez, V. J. Bolós, M. E. Ramírez. A wavelet-based tool for studying #' non-periodicity. Comput. Math. Appl. 60 (2010), no. 3, 634-641. #' #' @export #' windowed_scalogram <- function(signal, dt = 1, scales = NULL, powerscales = TRUE, windowrad = NULL, delta_t = NULL, wname = c("MORLET", "DOG", "PAUL", "HAAR", "HAAR2"), wparam = NULL, waverad = NULL, border_effects = c("BE", "INNER", "PER", "SYM"), energy_density = TRUE, makefigure = TRUE, time_values = NULL, figureperiod = TRUE, xlab = "Time", ylab = NULL, main = "Windowed Scalogram", zlim = NULL) { # require(zoo) # require(Matrix) wname <- toupper(wname) wname <- match.arg(wname) if (is.null(waverad)) { if ((wname == "MORLET") || (wname == "DOG")) { waverad <- sqrt(2) } else if (wname == "PAUL") { waverad <- 1 / sqrt(2) } else { # HAAR waverad <- 0.5 } } border_effects <- toupper(border_effects) border_effects <- match.arg(border_effects) if (border_effects == "INNER") { border_effects_cwt <- "BE" } else { border_effects_cwt <- border_effects } nt <- length(signal) if (is.null(delta_t)) { delta_t <- ceiling(nt / 256) } if (is.null(windowrad)) { windowrad <- ceiling(nt / 20) } else { windowrad <- min(windowrad, floor((nt - 1) / 2)) } fourierfactor <- fourier_factor(wname = wname, wparam = wparam) if (is.null(scales)) { scmin <- 2 / fourierfactor scmax <- floor((nt - 2 * windowrad) / (2 * waverad)) if (powerscales) { scales <- pow2scales(c(scmin, scmax, ceiling(256 / log2(scmax / scmin)))) } else { scales <- seq(scmin, scmax, by = (scmax - scmin) / 256) } scalesdt <- scales * dt } else { if (powerscales && length(scales) == 3) { scales <- pow2scales(scales) } else { if (is.unsorted(scales)) { warning("Scales were not sorted.") scales <- sort(scales) } aux <- diff(log2(scales)) if (powerscales && ((max(aux) - min(aux)) / max(aux) > 0.05)) { warning("Scales seem like they are not power 2 scales. Powerscales set to FALSE.") powerscales <- FALSE } } scalesdt <- scales scales <- scales / dt } ns <- length(scales) cwt <- cwt_wst(signal = signal, dt = dt, scales = scalesdt, powerscales = FALSE, wname = wname, wparam = wparam, waverad = waverad, border_effects = border_effects_cwt, makefigure = FALSE) coefs <- cwt$coefs if (border_effects == "INNER") { wrs <- ceiling(waverad * scales) tcentral_ini <- max(1 + windowrad, 1 + wrs[1] - windowrad) tcentral_end <- min(nt - windowrad, nt - wrs[1] + windowrad) if (tcentral_ini > tcentral_end) { stop("We need a larger signal") } tcentral <- seq(from = tcentral_ini, to = tcentral_end, by = delta_t) ntcentral <- length(tcentral) wsc <- matrix(NA, nrow = ntcentral, ncol = ns) abscoefs2 <- matrix(abs(coefs) ^ 2, nrow = nt, ncol = ns) # Regular version for (i in 1:ntcentral) { for (j in 1:ns) { t_ini <- max(tcentral[i] - windowrad, 1 + wrs[j]) t_end <- min(tcentral[i] + windowrad, nt - wrs[j]) if (t_ini <= t_end) { wsc[i, j] <- sqrt(abs(sum(abscoefs2[t_ini:t_end, j]))) # abs: sometimes wsc is negative due to numerical errors wsc[i, j] <- wsc[i, j] / sqrt(t_end - t_ini + 1) # Normalization } } } wsc <- as.matrix(wsc) } else { tcentral_ini <- 1 + windowrad tcentral_end <- nt - windowrad tcentral <- seq(from = tcentral_ini, to = tcentral_end, by = delta_t) ntcentral <- length(tcentral) wsc <- matrix(0, nrow = ntcentral, ncol = ns) abscoefs2 <- matrix(abs(coefs) ^ 2, nrow = nt, ncol = ns) if (delta_t < windowrad) { # Fast version for (j in 1:ns) { wsc[1, j] <- sum(abscoefs2[1:(1 + 2 * windowrad), j]) for (i in 2:ntcentral) { wsc[i, j] <- wsc[i-1, j] - sum(abscoefs2[(tcentral[i] - windowrad - delta_t):(tcentral[i] - windowrad - 1), j]) + sum(abscoefs2[(tcentral[i] + windowrad - delta_t + 1):(tcentral[i] + windowrad), j]) } } } else { # Regular version for (i in 1:ntcentral) { for (j in 1:ns) { wsc[i, j] <- sum(abscoefs2[(tcentral[i] - windowrad):(tcentral[i] + windowrad), j]) } } } wsc <- as.matrix(sqrt(abs(wsc))) # abs: sometimes wsc is negative due to numerical errors wsc <- wsc / sqrt(2 * windowrad + 1) # Normalization } # COI coi_maxscale <- numeric(ntcentral) for (i in 1:ntcentral) { coi_maxscale[i] <- dt * min(tcentral[i] - windowrad - 1, nt - tcentral[i] - windowrad) / waverad } tcentraldt <- tcentral * dt # Energy density if (energy_density) { wsc <- t(t(wsc) / sqrt(scalesdt)) } # Make figure if (makefigure) { if (figureperiod) { Y <- fourierfactor * scalesdt coi <- fourierfactor * coi_maxscale if (is.null(ylab)) ylab <- "Period" } else { Y <- scalesdt coi <- coi_maxscale if (is.null(ylab)) ylab <- "Scale" } if (is.null(time_values)) { X <- tcentraldt } else { if (length(time_values) != nt) { warning("Invalid length of time_values vector. Changing to default.") X <- tcentraldt } else { X <- time_values[tcentral] } } if (length(Y) > 1) { wavPlot( Z = wsc, X = X, Y = Y, Ylog = powerscales, coi = coi, Xname = xlab, Yname = ylab, Zname = main, zlim = zlim ) } else { if (is.null(ylab)) ylab <- "Windowed Scalogram" plot(X, wsc, type = "l", xlab = xlab, ylab = ylab, main = main, xaxt = "n") axis(side = 1, at = X[1 + floor((0:8) * (ntcentral - 1) / 8)]) abline(v = range(X[(coi > Y)]), lty = 2) } } return(list( wsc = wsc, tcentral = tcentraldt, scales = scalesdt, windowrad = windowrad, fourierfactor = fourierfactor, coi_maxscale = as.numeric(coi_maxscale) )) }
/scratch/gouwar.j/cran-all/cranData/wavScalogram/R/windowed_scalogram.R
#' @title Windowed Scalogram Difference #' #' @description This function computes the Windowed Scalogram Difference of two signals. #' The definition and details can be found in (Bolós et al. 2017). #' #' @usage wsd(signal1, #' signal2, #' dt = 1, #' scaleparam = NULL, #' windowrad = NULL, #' rdist = NULL, #' delta_t = NULL, #' normalize = c("NO", "ENERGY", "MAX", "SCALE"), #' refscale = NULL, #' wname = c("MORLET", "DOG", "PAUL", "HAAR", "HAAR2"), #' wparam = NULL, #' waverad = NULL, #' border_effects = c("BE", "INNER", "PER", "SYM"), #' mc_nrand = 0, #' commutative = TRUE, #' wscnoise = 0.02, #' compensation = 0, #' energy_density = TRUE, #' parallel = FALSE, #' makefigure = TRUE, #' time_values = NULL, #' figureperiod = TRUE, #' xlab = "Time", #' ylab = NULL, #' main = "-log2(WSD)", #' zlim = NULL) #' #' @param signal1 A vector containing the first signal. #' @param signal2 A vector containing the second signal (its length should be equal to #' that of \code{signal1}). #' @param dt Numeric. The time step of the signals. #' @param scaleparam A vector of three elements with the minimum scale, the maximum scale #' and the number of suboctaves per octave for constructing power 2 scales (following #' Torrence and Compo 1998). If NULL, they are automatically constructed. #' @param windowrad Integer. Time radius for the windows, measured in \code{dt}. By #' default, it is set to \eqn{ceiling(length(signal1) / 20)}. #' @param rdist Integer. Log-scale radius for the windows measured in suboctaves. By #' default, it is set to \eqn{ceiling(length(scales) / 20)}. #' @param delta_t Integer. Increment of time for the construction of windows central #' times, measured in \code{dt}. By default, it is set to #' \eqn{ceiling(length(signal1) / 256)}. #' @param normalize String, equal to "NO", "ENERGY", "MAX" or "SCALE". If "ENERGY", signals are #' divided by their respective energies. If "MAX", each signal is divided by the maximum #' value attained by its scalogram. In these two cases, \code{energy_density} must be TRUE. #' Finally, if "SCALE", each signal is divided by their scalogram value at scale #' \code{refscale}. #' @param refscale Numeric. The reference scale for \code{normalize}. #' @param wname A string, equal to "MORLET", "DOG", "PAUL", "HAAR" or "HAAR2". The #' difference between "HAAR" and "HAAR2" is that "HAAR2" is more accurate but slower. #' @param wparam The corresponding nondimensional parameter for the wavelet function #' (Morlet, DoG or Paul). #' @param waverad Numeric. The radius of the wavelet used in the computations for the cone #' of influence. If it is not specified, it is asumed to be \eqn{\sqrt{2}} for Morlet and DoG, #' \eqn{1/\sqrt{2}} for Paul and 0.5 for Haar. #' @param border_effects String, equal to "BE", "INNER", "PER" or "SYM", #' which indicates how to manage the border effects which arise usually when a convolution #' is performed on finite-lenght signals. #' \itemize{ #' \item "BE": With border effects, padding time series with zeroes. #' \item "INNER": Normalized inner scalogram with security margin adapted for each #' different scale. #' \item "PER": With border effects, using boundary wavelets (periodization of the #' original time series). #' \item "SYM": With border effects, using a symmetric catenation of the original time #' series. #' } #' @param mc_nrand Integer. Number of Montecarlo simulations to be performed in order to #' determine the 95\% and 5\% significance contours. #' @param commutative Logical. If TRUE (default) the commutative windowed scalogram #' difference. Otherwise a non-commutative (but simpler) version is computed (see Bolós et #' al. 2017). #' @param wscnoise Numeric in \eqn{[0,1]}. If a (windowed) scalogram takes values close to #' zero, some problems may appear because we are considering relative differences. #' Specifically, we can get high relative differences that in fact are not relevant, or #' even divisions by zero. #' #' If we consider absolute differences this would not happen but, on the other hand, #' using absolute differences is not appropriate for scalogram values not close to zero. #' #' So, the parameter \code{wscnoise} stablishes a threshold for the scalogram values #' above which a relative difference is computed, and below which a difference #' proportional to the absolute difference is computed (the proportionality factor is #' determined by requiring continuity). #' #' Finally, \code{wscnoise} can be interpreted as the relative amplitude of the noise in #' the scalograms and is chosen in order to make a relative (\eqn{= 0}), absolute #' (\eqn{= 1}) or mix (in \eqn{(0,1)}) difference between scalograms. Default value is #' set to \eqn{0.02}. #' @param compensation Numeric. It is an alternative to \code{wscnoise} for #' preventing numerical errors or non-relevant high relative differences when scalogram #' values are close to zero (see Bolós et al. 2017). It should be a non-negative #' relatively small value. #' @param energy_density Logical. If TRUE (default), divide the scalograms by the square #' root of the scales for convert them into energy density. Note that it does not affect #' the results if \code{wscnoise} \eqn{= 0}. #' @param parallel Logical. If TRUE, it uses function \code{parApply} from package #' \code{parallel} for the Montecarlo simulations. When FALSE (default) it uses the normal #' \code{apply} function. #' @param makefigure Logical. If TRUE (default), a figure with the WSD is plotted. #' @param time_values A numerical vector of length \code{length(signal)} containing custom #' time values for the figure. If NULL (default), it will be computed starting at 0. #' @param figureperiod Logical. If TRUE (default), periods are used in the figure instead #' of scales. #' @param xlab A string giving a custom X axis label. #' @param ylab A string giving a custom Y axis label. If NULL (default) the Y label is #' either "Scale" or "Period" depending on the value of \code{figureperiod}. #' @param main A string giving a custom main title for the figure. #' @param zlim A vector of length 2 with the limits for the z-axis (the color bar). #' #' @importFrom parallel parApply detectCores makeCluster stopCluster #' @importFrom abind abind #' #' @return A list with the following fields: #' \itemize{ #' \item \code{wsd}: A matrix of size \code{length(tcentral)} x \code{length(scales)} #' containing the values of the windowed scalogram differences at each scale and at each #' time window. #' \item \code{tcentral}: The vector of central times used in the computations of the #' windowed scalograms. #' \item \code{scales}: The vector of scales. #' \item \code{windowrad}: Radius for the time windows of the windowed scalograms, #' measured in \code{dt}. #' \item \code{rdist}: The log-scale radius for the windows measured in suboctaves. #' \item \code{signif95}: A logical matrix of size \code{length(tcentral)} x #' \code{length(scales)}. If TRUE, the corresponding point of the \code{wsd} matrix is in #' the 95\% significance. #' \item \code{signif05}: A logical matrix of size \code{length(tcentral)} x #' \code{length(scales)}. If TRUE, the corresponding point of the \code{wsd} matrix is in #' the 5\% significance. #' \item \code{fourierfactor}: A factor for converting scales into periods. #' \item \code{coi_maxscale}: A vector of length \code{length(tcentral)} containing the #' values of the maximum scale from which there are border effects for the respective #' central time. #' } #' #' @examples #' #' nt <- 1500 #' time <- 1:nt #' sd_noise <- 0.2 #% In Bolós et al. 2017 Figure 1, sd_noise = 1. #' signal1 <- rnorm(n = nt, mean = 0, sd = sd_noise) + sin(time / 10) #' signal2 <- rnorm(n = nt, mean = 0, sd = sd_noise) + sin(time / 10) #' signal2[500:1000] = signal2[500:1000] + sin((500:1000) / 2) #' \dontrun{ #' wsd <- wsd(signal1 = signal1, signal2 = signal2) #' } #' #' @section References: #' C. Torrence, G. P. Compo. A practical guide to wavelet analysis. B. Am. Meteorol. Soc. #' 79 (1998), 61–78. #' #' V. J. Bolós, R. Benítez, R. Ferrer, R. Jammazi. The windowed scalogram difference: a #' novel wavelet tool for comparing time series. Appl. Math. Comput., 312 (2017), 49-65. #' #' @export #' wsd <- function(signal1, signal2, dt = 1, scaleparam = NULL, windowrad = NULL, rdist = NULL, delta_t = NULL, normalize = c("NO", "ENERGY", "MAX", "SCALE"), refscale = NULL, wname = c("MORLET", "DOG", "PAUL", "HAAR", "HAAR2"), wparam = NULL, waverad = NULL, border_effects = c("BE", "INNER", "PER", "SYM"), mc_nrand = 0, commutative = TRUE, wscnoise = 0.02, compensation = 0, energy_density = TRUE, parallel = FALSE, makefigure = TRUE, time_values = NULL, figureperiod = TRUE, xlab = "Time", ylab = NULL, main = "-log2(WSD)", zlim = NULL) { # require(abind) wname <- toupper(wname) wname <- match.arg(wname) border_effects <- toupper(border_effects) border_effects <- match.arg(border_effects) normalize <- toupper(normalize) normalize <- match.arg(normalize) if (is.null(waverad)) { if ((wname == "MORLET") || (wname == "DOG")) { waverad <- sqrt(2) } else if (wname == "PAUL") { waverad <- 1 / sqrt(2) } else { # HAAR waverad <- 0.5 } } nt <- length(signal1) if (nt != length(signal2)) { stop("Signals must have the same length.") } if (is.null(delta_t)) { delta_t <- ceiling(nt / 256) } if (is.null(windowrad)) { windowrad <- ceiling(nt / 20) } else if (windowrad > floor((nt - 1) / 2)) { windowrad <- floor((nt - 1) / 2) print("Windowrad re-adjusted.") } fourierfactor <- fourier_factor(wname = wname, wparam = wparam) if (is.null(scaleparam)) { scmin <- 2 / fourierfactor scmax <- floor((nt - 2 * windowrad) / (2 * waverad)) scaleparam <- c(scmin * dt, scmax * dt, ceiling(256 / log2(scmax / scmin))) } scalesdt <- pow2scales(scaleparam) scales <- scalesdt / dt ns <- length(scales) if (is.null(rdist)) { rdist <- ceiling(ns / 20) } ### Normalization & Scalograms if (normalize != "NO") { if ((!energy_density) && (normalize != "SCALE")) { warning("For energy or max normalization, energy_density is set to TRUE.") energy_density <- TRUE } if (normalize == "SCALE") { if (is.null(refscale)) { stop("No refscale parameter specified for normalization.") } else { scales_aux <- refscale } } else { scales_aux <- scalesdt } scalog1 <- scalogram(signal = signal1, dt = dt, scales = scales_aux, powerscales = FALSE, border_effects = border_effects, energy_density = energy_density, wname = wname, wparam = wparam, waverad = waverad, makefigure = FALSE) scalog2 <- scalogram(signal = signal2, dt = dt, scales = scales_aux, powerscales = FALSE, border_effects = border_effects, energy_density = energy_density, wname = wname, wparam = wparam, waverad = waverad, makefigure = FALSE) # Normalization if (normalize == "ENERGY") { signal1 <- signal1 / scalog1$energy signal2 <- signal2 / scalog2$energy } else { # MAX or SCALE signal1 <- signal1 / max(scalog1$scalog) signal2 <- signal2 / max(scalog2$scalog) } } ### Windowed scalograms wsc1 <- windowed_scalogram( signal = signal1, dt = dt, scales = scalesdt, powerscales = FALSE, border_effects = border_effects, energy_density = energy_density, windowrad = windowrad, delta_t = delta_t, wname = wname, wparam = wparam, waverad = waverad, makefigure = FALSE) wsc2 <- windowed_scalogram( signal = signal2, dt = dt, scales = scalesdt, powerscales = FALSE, border_effects = border_effects, energy_density = energy_density, windowrad = windowrad, delta_t = delta_t, wname = wname, wparam = wparam, waverad = waverad, makefigure = FALSE) nwsc <- length(wsc1$tcentral) # Compensation fc <- 1 - compensation / max(wsc1$wsc, wsc2$wsc, na.rm = TRUE) wsc1$wsc <- compensation + fc * wsc1$wsc wsc2$wsc <- compensation + fc * wsc2$wsc ### Relative distances between scalograms wsd <- matrix(NA, nrow = nwsc, ncol = ns) noise1 <- wscnoise * max(wsc1$wsc, na.rm = TRUE) if (commutative) { noise2 <- wscnoise * max(wsc2$wsc, na.rm = TRUE) A <- 0.25 * ((wsc1$wsc - wsc2$wsc) / pmax(wsc1$wsc, noise1) + (wsc1$wsc - wsc2$wsc) / pmax(wsc2$wsc, noise2)) ^ 2 } else { A <- ((wsc1$wsc - wsc2$wsc) / pmax(wsc1$wsc, noise1)) ^ 2 } for (i in 1:nwsc) { maxsct <- max(which(!is.na(A[i, ]))) for (j in 1:maxsct) { kmin <- max(1, j - rdist) kmax <- min(maxsct, j + rdist) aux <- (2 * rdist + 1)/(kmax - kmin + 1) wsd[i, j] <- sum(A[i, kmin:kmax]) * aux } } wsd <- sqrt(wsd) ### Montecarlo if (mc_nrand > 0) { mean1 <- mean(signal1) mean2 <- mean(signal2) sd1 <- sd(signal1) sd2 <- sd(signal2) distrnd <- array(0, dim = c(nwsc, ns, mc_nrand)) print("Montecarlo...") rndSignals1 <- matrix(rnorm(mc_nrand * nt, mean = mean1, sd = sd1), nrow = mc_nrand, ncol = nt) rndSignals2 <- matrix(rnorm(mc_nrand * nt, mean = mean2, sd = sd2), nrow = mc_nrand, ncol = nt) rndSignals <- array(c(rndSignals1, rndSignals2), dim = c(mc_nrand, nt, 2)) if(parallel) { # require(parallel) no_cores <- detectCores() - 1 # Initiate cluster cl1 <- makeCluster(no_cores) parApply( cl = cl1, rndSignals, MARGIN = 1, FUN = function(x) { aux_rnd_dist <- wsd( signal1 = x[, 1], signal2 = x[, 2], dt = dt, scaleparam = scaleparam, delta_t = delta_t, windowrad = windowrad, rdist = rdist, normalize = normalize, wname = wname, wparam = wparam, waverad = waverad, border_effects = border_effects, mc_nrand = 0, commutative = commutative, compensation = compensation, wscnoise = wscnoise, energy_density = energy_density, parallel = parallel, makefigure = FALSE) } ) -> kk stopCluster(cl1) } else { apply( rndSignals, MARGIN = 1, FUN = function(x) { aux_rnd_dist <- wsd( signal1 = x[, 1], signal2 = x[, 2], dt = dt, scaleparam = scaleparam, delta_t = delta_t, windowrad = windowrad, rdist = rdist, normalize = normalize, wname = wname, wparam = wparam, waverad = waverad, border_effects = border_effects, mc_nrand = 0, commutative = commutative, compensation = compensation, wscnoise = wscnoise, energy_density = energy_density, parallel = parallel, makefigure = FALSE) } ) -> kk } lapply( kk, function(x) { abind(x$wsd, along = 3) } ) -> kk2 do.call(abind, kk2) -> distrnd # Significance print("Computing significance contours...") kk95 <- matrix(0, nrow = nwsc, ncol = ns) kk05 <- matrix(0, nrow = nwsc, ncol = ns) Aux <- -log2(distrnd) kk95 <- apply( X = Aux, MARGIN = c(1, 2), FUN = function(x) quantile(x, .95, na.rm = TRUE) ) kk05 <- apply( X = Aux, MARGIN = c(1, 2), FUN = function(x) quantile(x, .05, na.rm = TRUE) ) wsdsig95 <- ((-log2(wsd) - kk95) > 0) wsdsig05 <- ((-log2(wsd) - kk05) > 0) } else { wsdsig95 <- NULL wsdsig05 <- NULL } ### COI WSC coi_wsc <- wsc1$coi_maxscale ### Make figure tcentraldt <- wsc1$tcentral if (makefigure) { if (figureperiod) { Y <- fourierfactor * scalesdt coi <- fourierfactor * coi_wsc if (is.null(ylab)) ylab <- "Period" } else { Y <- scalesdt coi <- coi_wsc if (is.null(ylab)) ylab <- "Scale" } if (is.null(time_values)) { X <- tcentraldt } else { if (length(time_values) != nt) { warning("Invalid length of time_values vector. Changing to default.") X <- tcentraldt } else { aux <- floor((nt - (nwsc - 1) * delta_t + 1) / 2) X <- time_values[seq(from = aux, to = aux + (nwsc - 1) * delta_t, by = delta_t)] } } wavPlot( Z = -log2(wsd), X = X, Y = Y, Ylog = TRUE, coi = coi, rdist = rdist, sig95 = wsdsig95, sig05 = wsdsig05, Xname = xlab, Yname = ylab, Zname = main, zlim = zlim ) } return(list( wsd = wsd, tcentral = tcentraldt, scales = scalesdt, windowrad = windowrad, rdist = rdist, signif95 = wsdsig95, signif05 = wsdsig05, fourierfactor = fourierfactor, coi_maxscale = coi_wsc )) }
/scratch/gouwar.j/cran-all/cranData/wavScalogram/R/wsd.R
"fill.mat" <- function(mat.row, coeffs) { return(coeffs[mat.row[1]:mat.row[2]]) } "print.wb" <- function(x, ...) { cat("Wave.band credible bands object\n") cat("Bands produced for x in data component of length: ", length(x$data), "\n") cat("Credible intervals are in the bands component\n") cat("Wave.band Bayesian hyperparameter alpha was: ", x$param$alpha, "\n") cat("Wave.band Bayesian hyperparameter beta was: ", x$param$beta, "\n") cat("Wave.band Wavelet filter number was: ", x$param$filter.number, "\n") cat("Wave.band Wavelet family was: ", x$param$family, "\n") cat("Type of input (data or test signal):", x$param$type, "\n") cat("Rsnr (if applicable): ", x$param$rsnr, "\n") } "summary.wb" <- function(object, ...) { print.wb(object, ...) } "plot.wb" <- function(x, col = FALSE, ...) { # # Data should be the output from running wave.band # # Plots the BayesThresh estimate with 99% credible intervals # and the data. # # # If col=TRUE, then the plot should look the same as that generated # by wave.band; otherwise a different plot that looks better # in black and white is produced. # n <- length(x$data) xtmp <- (1:n)/n if(x$param$type != "data") y <- test.data(type = x$param$type, rsnr = x$ param$rsnr, n = n, signal = 1)$y if(col) { plot(xtmp, x$data, type = "l", xlab = "x", ylab = "y", ylim = range(x$data, x$bands$l99, x$ bands$u99)) lines(xtmp, x$data, col = 3) lines(xtmp, x$bands$l99, col = 2) lines(xtmp, x$bands$u99, col = 2) lines(xtmp, x$bands$pointest, col = 4) if(x$param$type != "data") lines(x, y, lty = 2) } else { plot(xtmp, x$data, xlab = "x", ylab = "y", ylim = range( x$data, x$bands$l99, x$bands$u99), pch = ".") lines(xtmp, x$bands$l99) lines(xtmp, x$bands$u99) lines(xtmp, x$bands$pointest, lwd = 2) if(x$param$type != "data") lines(x, y, lty = 2) } } "power.sum" <- function(alphas.wd, pow = 2, verbose = TRUE, type = "approx", plotfn = FALSE) { # # This function evaluates the sum # # sum_{j,k} alpha_{j,k} psi_{j,k}^{pow}(x) # # where the psi_{j,k} are mother wavelets of some kind. The .wd # object alphas.wd contains the alpha_{j,k} in its $D component, # and specifies the wavlet to use in its $filter component. # # # NB: if pow=2, there should be a coefficient of # phi_{0,0}^2(x) to take care of as well. # # Exact and approximate solutions are available; the approximation # is very good and takes about 1/3 the time of the exact solution. # # Firstly, extract some components of alphas.wd for later use: # filter.number = alphas.wd$filter$filter.number family = alphas.wd$filter$family J <- nlevelsWT(alphas.wd) # # J is log_2(length(data)). Note that this function implicitly # requires J to be at least 5 (data of length 32). # # Create a .wd object full of zeros for use as a work space, # and a copy that we'll build our estimate in. # zero.wd <- wd(rep(0, 2^J), filter.number = filter.number, family = family) estimate.wd <- zero.wd # # If asked, do the exact version # if(type != "approx") { if(verbose) cat("Evaluating the exact solution\n") exact.sum <- rep(0, 2^J) if(pow == 2) { if(verbose) cat("Including overall scaling function\n" ) phisq <- wr(putC(zero.wd, level = 0, v = 1))^ pow exact.sum <- exact.sum + accessC(alphas.wd, level = 0) * phisq } for(j in 0:(J - 1)) { if(verbose) cat(c("Starting work on level", j, "\n")) for(k in 0:(2^j - 1)) { before <- k after <- 2^j - k - 1 psisq <- wr(putD(zero.wd, level = j, v = c(rep(0, before), 1, rep( 0, after))))^pow exact.sum <- exact.sum + accessD( alphas.wd, level = j)[k + 1] * psisq } } if(type == "exact" && plotfn == TRUE) plot(exact.sum, xlab = "x", ylab = "y", type = "l") if(type == "exact") return(exact.sum) } # # Do levels j = 0,...,J-4 by getting psi^pow_{j,0} and shifting # (if necessary) to get psi^pow_{j,k}. The approximation is # by scaling coefficients at level j+3. # if(verbose) cat("Evaluating the approximate sum\n") if(pow == 2) { if(verbose) cat("Including overall scaling function\n") pow.coeffs <- accessC(wd(wr(putC(zero.wd, level = 0, v = 1))^pow, filter.number = filter.number, family = family), level = 3) tmp <- pow.coeffs * accessC(alphas.wd, level = 0) estimate.wd <- putC(estimate.wd, level = 3, v = tmp) } for(j in 0:(J - 4)) { if(verbose) cat(c("Starting work on level", j, "\n")) pow.coeffs <- accessC(wd(wr(putD(zero.wd, level = j, v = c(1, rep(0, 2^j - 1))))^pow, filter.number = filter.number, family = family), level = j + 3) pow.coeffs <- rep(pow.coeffs, 2) starts <- ((2^j):1) * 8 + 1 stops <- starts + 2^(j + 3) - 1 tmp <- t(apply(cbind(starts, stops), 1, fill.mat, pow.coeffs)) tmp <- accessD(alphas.wd, level = j) * tmp tmp <- apply(tmp, 2, sum) + accessC(estimate.wd, level = j + 3) estimate.wd <- putC(estimate.wd, level = j + 3, v = tmp ) } # # At finer levels, can only go up as far as level J-1. # Use the wavelet coeffs as well as the scaling coeffs to compensate. # for(j in (J - 3):(J - 1)) { if(verbose) cat(c("Starting work on level", j, "\n")) starts <- ((2^j):1) * (2^(J - 1 - j)) + 1 stops <- starts + 2^(J - 1) - 1 psijtothepow.wd <- wd(wr(putD(zero.wd, level = j, v = c( 1, rep(0, 2^j - 1))))^pow, filter.number = filter.number, family = family) # # Scaling coeffs first # pow.coeffs <- rep(accessC(psijtothepow.wd, level = J - 1), 2) tmp <- t(apply(cbind(starts, stops), 1, fill.mat, pow.coeffs)) tmp <- accessD(alphas.wd, level = j) * tmp tmp <- apply(tmp, 2, sum) + accessC(estimate.wd, level = J - 1) estimate.wd <- putC(estimate.wd, level = J - 1, v = tmp ) # # Now the wavelet coefficients # pow.coeffs <- rep(accessD(psijtothepow.wd, level = J - 1), 2) tmp <- t(apply(cbind(starts, stops), 1, fill.mat, pow.coeffs)) tmp <- accessD(alphas.wd, level = j) * tmp tmp <- apply(tmp, 2, sum) + accessD(estimate.wd, level = J - 1) estimate.wd <- putD(estimate.wd, level = J - 1, v = tmp ) } estimate <- wrow(estimate.wd) if(plotfn) { if(type == "approx") plot(estimate, type = "l", xlab = "x", ylab = "y") else { plot(exact.sum, type = "l", xlab = "x", ylab = "y", ylim = range(c(estimate, exact.sum))) lines(estimate, col = 2) } } if(type == "both") return(list(estimate = estimate, exact.sum = exact.sum) ) return(estimate) } "test.data" <- function(type = "ppoly", n = 512, signal = 1, rsnr = 7, plotfn = FALSE) { x <- seq(0., 1., length = n + 1)[1:n] # elseif strcmp(Name,'Bumps'), # pos = [ .1 .13 .15 .23 .25 .40 .44 .65 .76 .78 .81]; # hgt = [ 4 5 3 4 5 4.2 2.1 4.3 3.1 5.1 4.2]; # wth = [.005 .005 .006 .01 .01 .03 .01 .01 .005 .008 .005]; # sig = zeros(size(t)); # for j =1:length(pos) # sig = sig + hgt(j)./( 1 + abs((t - pos(j))./wth(j))).^4; # end if(type == "ppoly") { y <- rep(0., n) xsv <- (x <= 0.5) y[xsv] <- -16. * x[xsv]^3. + 12. * x[xsv]^2. xsv <- (x > 0.5) & (x <= 0.75) y[xsv] <- (x[xsv] * (16. * x[xsv]^2. - 40. * x[xsv] + 28.))/3. - 1.5 xsv <- x > 0.75 y[xsv] <- (x[xsv] * (16. * x[xsv]^2. - 32. * x[xsv] + 16.))/3. } else if(type == "blocks") { t <- c(0.10000000000000001, 0.13, 0.14999999999999999, 0.23000000000000001, 0.25, 0.40000000000000002, 0.44, 0.65000000000000002, 0.76000000000000001, 0.78000000000000003, 0.81000000000000005) h <- c(4., -5., 3., -4., 5., -4.2000000000000002, 2.1000000000000001, 4.2999999999999998, -3.1000000000000001, 2.1000000000000001, -4.2000000000000002 ) y <- rep(0., n) for(i in seq(1., length(h))) { y <- y + (h[i] * (1. + sign(x - t[i])))/2. } } else if(type == "bumps") { t <- c(0.10000000000000001, 0.13, 0.14999999999999999, 0.23000000000000001, 0.25, 0.40000000000000002, 0.44, 0.65000000000000002, 0.76000000000000001, 0.78000000000000003, 0.81000000000000005) h <- c(4., 5., 3., 4., 5., 4.2000000000000002, 2.1000000000000001, 4.2999999999999998, 3.1000000000000001, 5.0999999999999996, 4.2000000000000002) w <- c(0.0050000000000000001, 0.0050000000000000001, 0.0060000000000000001, 0.01, 0.01, 0.029999999999999999, 0.01, 0.01, 0.0050000000000000001, 0.0080000000000000002, 0.0050000000000000001) y <- rep(0, n) for(j in 1:length(t)) { y <- y + h[j]/(1. + abs((x - t[j])/w[j]))^ 4. } } else if(type == "heavi") y <- 4. * sin(4. * pi * x) - sign(x - 0.29999999999999999) - sign(0.71999999999999997 - x) else if(type == "doppler") { eps <- 0.050000000000000003 y <- sqrt(x * (1. - x)) * sin((2. * pi * (1. + eps))/ (x + eps)) } else { cat(c("test.data: unknown test function type", type, "\n")) cat(c("Terminating\n")) return("NoType") } y <- y/sqrt(var(y)) * signal ynoise <- y + rnorm(n, 0, signal/rsnr) if(plotfn == TRUE) { if(type == "ppoly") mlab = "Piecewise polynomial" if(type == "blocks") mlab = "Blocks" if(type == "bumps") mlab = "Bumps" if(type == "heavi") mlab = "HeaviSine" if(type == "doppler") mlab = "Doppler" plot(x, y, type = "l", lwd = 2, main = mlab, ylim = range(c(y, ynoise))) lines(x, ynoise, col = 2) lines(x, y) } return(list(x = x, y = y, ynoise = ynoise, type = type, rsnr = rsnr)) } "wave.band" <- function(data = 0, alpha = 0.5, beta = 1., filter.number = 8, family = "DaubLeAsymm", bc = "periodic", dev = var, j0 = 3., plotfn = TRUE, retvalue = TRUE, n = 128, type = "data", rsnr = 3) { # # Data should be a vector of noisy data of length 2^J # # Alternatively, specify type to be "ppoly", "blocks", "bumps", # "doppler", or "heavi" and wave.band will call test.data. # if(type == "data") { n <- length(data) if (n < 8) stop("Length of data should be >= 8") ispow <- !is.na(IsPowerOfTwo(n)) if(ispow && (n < 1025)) data <- list(x = (1:n)/n, ynoise = data) else { cat("Warning: ") if(n > 1025) cat("data vector is too long (over 1024)\n" ) else cat("length of data is not a power of two\n" ) return(NULL) } } if(type != "data") { data <- test.data(type = type, rsnr = rsnr, n = n) if(is.list(data) == FALSE) return(NULL) } # # Estimation of hyperparamters C1 and C2 via universal thresholding; # Entirely unchanged from BAYES.THR # ywd <- wd(data$ynoise, filter.number = filter.number, family = family, bc = bc) sigma <- sqrt(dev(accessD(ywd, level = (nlevelsWT(ywd) - 1.)))) uvt <- threshold(ywd, policy = "universal", type = "soft", dev = dev, by.level = FALSE, levels = (nlevelsWT(ywd) - 1.), return.threshold = TRUE) universal <- threshold(ywd, policy = "manual", value = uvt, type = "soft", dev = dev, levels = j0:(nlevelsWT(ywd) - 1.)) nsignal <- rep(0., nlevelsWT(ywd)) sum2 <- rep(0., nlevelsWT(ywd)) for(j in 0.:(nlevelsWT(ywd) - 1.)) { coefthr <- accessD(universal, level = j) nsignal[j + 1.] <- sum(abs(coefthr) > 0.) if(nsignal[j + 1.] > 0.) sum2[j + 1.] <- sum(coefthr[abs(coefthr) > 0.]^ 2.) } C <- seq(1000., 15000., 50.) l <- rep(0., length(C)) lev <- seq(0., nlevelsWT(ywd) - 1.) v <- 2.^( - alpha * lev) for(i in 1.:length(C)) { l[i] <- 0.5 * sum( - nsignal * (logb(sigma^2. + C[ i] * v) + 2. * logb(pnorm(( - sigma * sqrt( 2. * logb(2.^nlevelsWT(ywd))))/sqrt(sigma^2. + C[i] * v)))) - sum2/2./(sigma^2. + C[i] * v)) } C1 <- C[l == max(l)] tau2 <- C1 * v p <- 2. * pnorm(( - sigma * sqrt(2. * logb(2.^nlevelsWT(ywd))))/ sqrt(sigma^2. + tau2)) if(beta == 1.) C2 <- sum(nsignal/p)/nlevelsWT(ywd) else C2 <- (1. - 2.^(1. - beta))/(1. - 2.^((1. - beta) * nlevelsWT(ywd))) * sum(nsignal/p) pr <- pmin(1., C2 * 2.^( - beta * lev)) rat <- tau2/(sigma^2. + tau2) # # Now we work out the cumulants of the wavelet coefficients. # K1.wd <- wd(rep(0, n), filter.number = filter.number, family = family, bc = bc) K2.wd <- K1.wd K3.wd <- K1.wd K4.wd <- K1.wd bayesthresh.wd <- ywd # # Deal with the cumulants of the scaling coefficient: # c00 <- accessC(ywd, level = 0) K1.wd <- putC(K1.wd, level = 0, v = c00) K2.wd <- putC(K2.wd, level = 0, v = sigma^2) # # Now the cumulants of the wavelet coefficients: # for(j in 0.:(nlevelsWT(ywd) - 1.)) { coef <- accessD(ywd, level = j) w <- ((1. - pr[j + 1.])/pr[j + 1.])/(sqrt((sigma^2 * rat[j + 1])/tau2[j + 1.])) * exp(( - rat[j + 1] * coef^2)/(2 * sigma^2)) z <- 0.5 * (1. + pmin(w, 1.)) median <- sign(coef) * pmax(0., rat[j + 1.] * abs( coef) - sigma * sqrt(rat[j + 1.]) * qnorm( z)) bayesthresh.wd <- putD(bayesthresh.wd, level = j, v = median) g <- 1/(1 + w) gt <- 1 - g # # First cumulant # k1 <- g * coef * rat[j + 1] K1.wd <- putD(K1.wd, level = j, v = k1) # # Second cumulant # k2 <- (g * rat[j + 1] * (coef^2 * rat[j + 1] * gt + sigma^2)) K2.wd <- putD(K2.wd, level = j, v = k2) # # Third cumulant: # k3 <- (g * gt * coef * rat[j + 1]^2 * (coef^2 * rat[ j + 1] * (1 - 2 * g) + 3 * sigma^2)) K3.wd <- putD(K3.wd, level = j, v = k3) # # Fourth cumulant: # k4 <- (g * gt * rat[j + 1]^2 * (coef^4 * rat[j + 1]^ 2 * (1 - 6 * g * gt) + 6 * coef^2 * rat[j + 1] * sigma^2 * (1 - 2 * g) + 3 * sigma^4)) K4.wd <- putD(K4.wd, level = j, v = k4) } # # Got wavelet coefficient cumulants; now want the cumulants of # the function estimate. # bayesthresh.wr <- wr(bayesthresh.wd) K1 <- wrow(K1.wd) K2 <- power.sum(K2.wd, pow = 2, verbose = FALSE) K3 <- power.sum(K3.wd, pow = 3, verbose = FALSE) K4 <- power.sum(K4.wd, pow = 4, verbose = FALSE) cumulants <- cbind(K1, K2, K3, K4) bands <- t(apply(cumulants, 1, wb.johnson.lims)) # # Now prepare output: # cumulants <- list(one = cumulants[, 1], two = cumulants[, 2], three = cumulants[, 3], four = cumulants[, 4]) Kr.wd <- list(one = K1.wd, two = K2.wd, three = K3.wd, four = K4.wd) bands <- list(pointest = bayesthresh.wr, l80 = bands[, 2], u80 = bands[, 3], w80 = bands[, 3] - bands[, 2], l90 = bands[, 4], u90 = bands[, 5], w90 = bands[, 5] - bands[ , 4], l95 = bands[, 6], u95 = bands[, 7], w95 = bands[ , 7] - bands[, 6], l99 = bands[, 8], u99 = bands[, 9], w99 = bands[, 9] - bands[, 8]) param <- list(alpha = alpha, beta = beta, filter.number = filter.number, family = family, type = type, rsnr = rsnr) if(retvalue) returnable <- list(data = data$ynoise, cumulants = cumulants, Kr.wd = Kr.wd, bands = bands, param = param) class(returnable) <- "wb" # # And, if asked, draw some pictures: # if(plotfn == TRUE) { plot(data$x, data$ynoise, type = "l", xlab = "x", ylab = "y", ylim = range(data$ynoise, bands$l99, bands$u99)) lines(data$x, data$ynoise, col = 3) if(type != "data") lines(data$x, data$y, lty = 2) lines(data$x, bands$l99, col = 2) lines(data$x, bands$u99, col = 2) lines(data$x, bands$pointest, col = 4) } if(retvalue) return(returnable) } "wb.johnson.lims" <- function(k, verbose = FALSE) { # Returns the upper and lower 100*siglvl/2 points of the # Johnson curve with first four cumulants as given in k, using # algorithms as99 and as100. This is done for siglvl = 0.2, 0.1, # 0.05, and 0.01. # # First we calculate the input parameters required by the FORTRAN # function "jnsn()": # k[1]: the mean # sd: the standard deviation # rbeta1: sqrt(beta1) in terms of Pearson curves. # NB: it takes the sign of k[3]; this is required # by the algorithm that finds the percentiles. # beta2: parameter beta2 of a Pearson curve; # sd <- sqrt(k[2]) rbeta1 <- k[3]/sd^3 beta2 <- k[4]/sd^4 + 3 # # NB: the "+3" in the anove line is because the usual # definition of beta2 is in terms of moments about the # mean; this is what happens when you use cumulants instead # lims <- rep(0, 9) zvalues <- matrix(rep(0, 16), ncol = 2) zvalues[, 2] <- c(0.10000000000000001, 0.90000000000000002, 0.050000000000000003, 0.94999999999999996, 0.025000000000000001, 0.97499999999999998, 0.0050000000000000001, 0.995) zvalues[, 1] <- qnorm(zvalues[, 2]) # # Next use jnsn() to find the Johnson curve with these parameters. # temp <- .Fortran(C_jnsn, XBAR = as.double(k[1]), SD = as.double(sd), RB1 = as.double(rbeta1), BB2 = as.double(beta2), ITYPE = as.integer(0), GAMMA = as.double(0), DELTA = as.double(0), XLAM = as.double(0), XI = as.double(0), IFAULT = as.integer(0)) lims[1] <- temp$IFAULT # # Now use ajv() to get the required points of this distribution, # via the function wb.johnson.lookup. # lims[2:9] <- apply(zvalues, 1, wb.johnson.lookup, parameters = temp) return(lims) } "wb.johnson.lookup" <- function(zval, parameters) { zvalue <- zval[1] temp <- .Fortran(C_ajv, SNV = as.double(zvalue), JVAL = as.double(0), ITYPE = as.integer(parameters$ITYPE), GAMMA = as.double(parameters$GAMMA), DELTA = as.double(parameters$DELTA), XLAM = as.double(parameters$XLAM), XI = as.double(parameters$XI), IFAULT = as.integer(0)) return(temp$JVAL) } "wrow" <- function(wd, start.level = 0., verbose = FALSE, bc = wd$bc, return.object = FALSE, filter.number = wd$filter$filter.number, family = wd$filter$family) { if(IsEarly(wd)) { ConvertMessage() stop() } if(verbose == TRUE) cat("Argument checking...") if(verbose == TRUE) cat("Argument checking\n") ctmp <- oldClass(wd) if(is.null(ctmp)) stop("wd has no class") else if(ctmp != "wd") stop("wd is not of class wd") if(start.level < 0.) stop("start.level must be nonnegative") if(start.level >= nlevelsWT(wd)) stop("start.level must be less than the number of levels" ) if(is.null(wd$filter$filter.number)) stop("NULL filter.number for wd") if(bc != wd$bc) warning("Boundary handling is different to original") if(wd$type == "station") stop("Use convert to generate wst object and then AvBasis or InvBasis" ) if(wd$bc == "interval") { warning("All optional arguments ignored for \"wavelets on the interval\" transform" ) return(wr.int(wd)) } type <- wd$type filter <- filter.select(filter.number = filter.number, family = family) LengthH <- length(filter$H) if(verbose == TRUE) cat("...done\nFirst/last database...") r.first.last.c <- wd$fl.dbase$first.last.c[(start.level + 1.): (nlevelsWT(wd) + 1.), ] r.first.last.d <- matrix(wd$fl.dbase$first.last.d[(start.level + 1.):(nlevelsWT(wd)), ], ncol = 3.) ntotal <- r.first.last.c[1., 3.] + r.first.last.c[1., 2.] - r.first.last.c[1., 1.] + 1. names(ntotal) <- NULL C <- wd$C #C <- c(rep(0., length = (ntotal - length(C))), C) Nlevels <- nlevelsWT(wd) - start.level error <- 0. if(verbose == TRUE) cat("...built\n") if(verbose == TRUE) { cat("Reconstruction...") error <- 1. } ntype <- switch(type, wavelet = 1., station = 2.) if(is.null(ntype)) stop("Unknown type of decomposition") nbc <- switch(bc, periodic = 1., symmetric = 2.) if(is.null(nbc)) stop("Unknown boundary handling") if(!is.complex(wd$D)) { wavelet.reconstruction <- .C(C_wavereconsow, C = as.double(C), D = as.double(wd$D), H = as.double(filter$H), LengthH = as.integer(LengthH), nlevels = as.integer(Nlevels), firstC = as.integer(r.first.last.c[, 1.]), lastC = as.integer(r.first.last.c[, 2.]), offsetC = as.integer(r.first.last.c[, 3.]), firstD = as.integer(r.first.last.d[, 1.]), lastD = as.integer(r.first.last.d[, 2.]), offsetD = as.integer(r.first.last.d[, 3.]), type = as.integer(ntype), nbc = as.integer(nbc), error = as.integer(error)) } else { wavelet.reconstruction <- .C("comwr", CR = as.double(Re(C)), CI = as.double(Im(C)), LengthC = as.integer(length(C)), DR = as.double(Re(wd$D)), DI = as.double(Im(wd$D)), LengthD = as.integer(length(wd$D)), HR = as.double(Re(filter$H)), HI = as.double(Im(filter$H)), GR = as.double(Re(filter$G)), GI = as.double(Im(filter$G)), LengthH = as.integer(LengthH), nlevels = as.integer(Nlevels), firstC = as.integer(r.first.last.c[, 1.]), lastC = as.integer(r.first.last.c[ , 2.]), offsetC = as.integer(r.first.last.c[, 3.]), firstD = as.integer(r.first.last.d[ , 1.]), lastD = as.integer(r.first.last.d[, 2.]), offsetD = as.integer(r.first.last.d[, 3.]), ntype = as.integer(ntype), nbc = as.integer(nbc), error = as.integer(error), PACKAGE="waveband") } if(verbose == TRUE) cat("done\n") error <- wavelet.reconstruction$error if(error != 0.) { cat("Error code returned from wavereconsow: ", error, "\n") stop("wavereconsow returned error") } fl.dbase <- wd$fl.dbase if(!is.complex(wd$D)) { l <- list(C = wavelet.reconstruction$C, D = wavelet.reconstruction$D, fl.dbase = fl.dbase, nlevels = nlevelsWT(wd), filter = filter, type = type, bc = bc, date = date()) } else { l <- list(C = complex(real = wavelet.reconstruction$ CR, imaginary = wavelet.reconstruction$CI), D = complex(real = wavelet.reconstruction$DR, imaginary = wavelet.reconstruction$DI), fl.dbase = fl.dbase, nlevels = nlevelsWT(wd), filter = filter, type = type, bc = bc, date = date()) } oldClass(l) <- "wd" if(return.object == TRUE) return(l) else return(accessC(l)) stop("Shouldn't get here\n") }
/scratch/gouwar.j/cran-all/cranData/waveband/R/WBfunctions.r
"test.data" <- function(type = "ppoly", n = 512, signal = 1, rsnr = 7, plotfn = FALSE) { x <- seq(0., 1., length = n + 1)[1:n] # elseif strcmp(Name,'Bumps'), # pos = [ .1 .13 .15 .23 .25 .40 .44 .65 .76 .78 .81]; # hgt = [ 4 5 3 4 5 4.2 2.1 4.3 3.1 5.1 4.2]; # wth = [.005 .005 .006 .01 .01 .03 .01 .01 .005 .008 .005]; # sig = zeros(size(t)); # for j =1:length(pos) # sig = sig + hgt(j)./( 1 + abs((t - pos(j))./wth(j))).^4; # end if(type == "ppoly") { y <- rep(0., n) xsv <- (x <= 0.5) y[xsv] <- -16. * x[xsv]^3. + 12. * x[xsv]^2. xsv <- (x > 0.5) & (x <= 0.75) y[xsv] <- (x[xsv] * (16. * x[xsv]^2. - 40. * x[xsv] + 28.))/3. - 1.5 xsv <- x > 0.75 y[xsv] <- (x[xsv] * (16. * x[xsv]^2. - 32. * x[xsv] + 16.))/3. } else if(type == "blocks") { t <- c(0.10000000000000001, 0.13, 0.14999999999999999, 0.23000000000000001, 0.25, 0.40000000000000002, 0.44, 0.65000000000000002, 0.76000000000000001, 0.78000000000000003, 0.81000000000000005) h <- c(4., -5., 3., -4., 5., -4.2000000000000002, 2.1000000000000001, 4.2999999999999998, -3.1000000000000001, 2.1000000000000001, -4.2000000000000002 ) y <- rep(0., n) for(i in seq(1., length(h))) { y <- y + (h[i] * (1. + sign(x - t[i])))/2. } } else if(type == "bumps") { t <- c(0.10000000000000001, 0.13, 0.14999999999999999, 0.23000000000000001, 0.25, 0.40000000000000002, 0.44, 0.65000000000000002, 0.76000000000000001, 0.78000000000000003, 0.81000000000000005) h <- c(4., 5., 3., 4., 5., 4.2000000000000002, 2.1000000000000001, 4.2999999999999998, 3.1000000000000001, 5.0999999999999996, 4.2000000000000002) w <- c(0.0050000000000000001, 0.0050000000000000001, 0.0060000000000000001, 0.01, 0.01, 0.029999999999999999, 0.01, 0.01, 0.0050000000000000001, 0.0080000000000000002, 0.0050000000000000001) y <- rep(0, n) for(j in 1:length(t)) { y <- y + h[j]/(1. + abs((x - t[j])/w[j]))^ 4. } } else if(type == "heavi") y <- 4. * sin(4. * pi * x) - sign(x - 0.29999999999999999) - sign(0.71999999999999997 - x) else if(type == "doppler") { eps <- 0.050000000000000003 y <- sqrt(x * (1. - x)) * sin((2. * pi * (1. + eps))/ (x + eps)) } else { cat(c("test.data: unknown test function type", type, "\n")) cat(c("Terminating\n")) return("NoType") } y <- y/sqrt(var(y)) * signal ynoise <- y + rnorm(n, 0, signal/rsnr) if(plotfn == TRUE) { if(type == "ppoly") mlab = "Piecewise polynomial" if(type == "blocks") mlab = "Blocks" if(type == "bumps") mlab = "Bumps" if(type == "heavi") mlab = "HeaviSine" if(type == "doppler") mlab = "Doppler" plot(x, y, type = "l", lwd = 2, main = mlab, ylim = range(c(y, ynoise))) lines(x, ynoise, col = 2) lines(x, y) } return(list(x = x, y = y, ynoise = ynoise, type = type, rsnr = rsnr)) }
/scratch/gouwar.j/cran-all/cranData/waveband/R/test.data.R
# # # This file contains all the functions to perform # the WaveD transform in R. The top fucntion is WaveD. # # # # # Written for R by Marc Raimondo # and Michael Stewart, the University of Sydney, 2006. # Copyright (c) 2006. # # references: ``Wavelet deconvolution in a periodic setting'' # by I.M. Johnstone, G. Kerkyacharian, D. Picard and M. Raimondo (2004).[JKPR] # The paper is available by www from Marc Raimondo's web page # # # ``Translation Invariant Deconvolution in a periodic setting'' # by D.Donoho and M. Raimondo (2005). IJWMIP # The paper is available by www from Marc Raimondo's web page # # # Software Manual: "The WaveD Transform in R" # by Marc Raimondo and Michael Stewart # available from the Journal of Statistical Software (2007) # # R-code version by Marc Raimondo and Michael Stewart University of Sydney 2006. # # # # # # ######################################################################### WaveD<-function(yobs,g=c(1,rep(0,(length(yobs)-1))),MC=FALSE,SOFT=FALSE,F=find.j1(g,scale(yobs))[2],L=3,deg=3,eta=sqrt(6),thr=maxithresh(yobs,g,eta=eta),label="WaveD") { # 1-d Wavelet deconvolution. # Inputs (required) # yobs =f*g+Noise # g Sample of the (known) function g # Inputs (optional) # L Lowest resolution level (default=3) # F Finest resolution level (default=Automatic) # deg deg of the Meyer Wavelet (default=3) # eta: smoothing parameter (default=conservative sqrt(6)) # Outputs # fhat= Estimated function 'f' # # # reference: [JKPR04] ################################ cl <- match.call() ###Preliminary parameter estimation################# nn<-length(yobs); J<-log2(nn); psyJ_fft<-wavelet_YM(J-2,J,deg); yobs_fft<-fft(yobs); yobs_w<- FWT_TI(yobs_fft,psyJ_fft); noise=sqrt(nn)*yobs_w[1:(nn/2)]; s<-mad(noise); ###################################################### ##Ordinary deconvolution############################## g_fft<-fft(g); x_fft<-yobs_fft/g_fft; #################################################Threshold set up if(length(thr)<F-L && length(thr)>1){thr=c(thr,rep(thr[length(thr)],log2(nn))); warning("Vector of threshold has not length J-L \n")} if(length(thr)==1){thr=rep(thr[1],log2(length(yobs)))} ############################################################################# #############if MC=TRUE WaveD returns only the TI-WaveD estimator############ if(MC){ # loop to compute up coefficients up to F phyJ_fft<-scaling_YM(L,J,deg); f_Coarse <- IFWT_TI(x_fft,phyJ_fft,L,thr[1],nn,SOFT=SOFT); f_sum<-f_Coarse #if F=J-1 use fine_YM instead of wavelet_YM if (F<J-1) (Fmax<-F) else (Fmax<-J-2) for (j in L:Fmax){ psyJ_fft<-wavelet_YM(j,J,deg); f_detail <- IFWT_TI(x_fft,psyJ_fft,j,thr[j-L+2],nn,SOFT=SOFT); f_sum<-f_sum+f_detail; } if (Fmax==J-2) { j=J-1; psyJ_fft<-fine_YM(j,J,deg); f_detail = IFWT_TI(x_fft,psyJ_fft,j,thr[j-L+2],nn,SOFT=SOFT); f_sum=f_sum+f_detail; y=f_sum} else {y=f_sum} } ############################################################################ ############################################################################ #############if MC=FALSE WaveD returns a full WaveD class output############ else{ ################################################################# #Aux computation for waved outputs M=find.j1(g,s)[1]; y_thr0_w=FWaveD(yobs,g=g,thr=0,F=F,SOFT=SOFT); #Note here should be F+1 due to IwaveD which stops at to F-1 y0=IWaveD(y_thr0_w,L,deg,(F+1)); y_TI=WaveD(yobs,g,MC=TRUE,F=F,thr=thr); # Compute FWaveD and threshold y_w=FWaveD(yobs,g=g,thr=thr,F=F,SOFT=SOFT); y_res=y_thr0_w-y_w; # # Invert the WaveD Transform # #Note here should be F+1 due to IwaveD goes to F-1 y=IWaveD(y_w,L,deg,(F+1)); #######################Summary list######################### if(SOFT){pol='Soft'}else{pol='Hard'} pv=shapiro.test(yobs_w*sqrt(nn))$p; if(pv<0.01) { print("Warning, WaveD-fit residuals normality-test P-value=") print(pv) print("larger threshold eta-constant may be required") } if(length(thr)==1){thr=rep(thr[1],F-L+2)} output=list(sd=s,noise=noise,j1=find.j1(g,scale(yobs))[2],Coarse=L,degree=deg,Low=L,M=M,thr=thr[1:(F-L+2)],w=y_thr0_w,w.thr=y_w,FWaveD=y_thr0_w,iw=y0,ordinary=y,waved=y_TI,POLICY=pol,residuals=y_res[1:(2^(F+1))],percent=threshsum(y_res,L,F),levels=c(L,L:F),eta=eta,F=F,n=nn,data=yobs,g=g,p=pv,label="WaveD",call=cl) class(output)="wvd" output } } ##################################################### ##################################################### ##################################################### ##########functions for ordinary WaveD below######### ################################################## ################################################## PhaseC<-function(l,j) # #Phase matrix to compute wavelet coefficients # in the Fourier Domain # { nb=2^j-1 k=0:nb k=matrix(k,nrow=1) l=matrix(l,nrow=1) mat=t(l)%*%k phase_mat=exp(2*pi*1i*mat/(2^j)); } # Written by Marc Raimondo (the University of Sydney), 2006. # Comments? e-mail [email protected] ######################################## ######################################## WaveDjC<-function(y_fft,f2fft,j) # compute--scaling--coef--at-level-j # uses Plancherel equality. # Usage # coef=coefj(f1fft,phij0fft,j,n) # Inputs # y_fft=fft(yobs) # f2fft=fft(phij0) or fft(psij0) accordingly # j=resolution level # n=sample size # Outputs # vector of coefs at resolution level j: length= 2^j { n=length(y_fft); j1=j-1; j2=j1-1; x2=2^j1+2^j2+4; l1=(0:x2); l2=((n-x2):(n-1)); l_0=c(l1,l2); l1=l1+1; l2=l2+1; l_1=c(l1,l2); #initial vector without phase # corresponds to k=0. y1=y_fft[l_1]; v1=matrix(y1,nrow=1); v2=f2fft[l_1]; v2=matrix(v2,nrow=1); #componentwise multiplication vector1=v1*Conj(v2); #matrix of phases phasemat=PhaseC(l_0,j); #coef is the product # of vector1 by phase matrix: y=Re(vector1%*%phasemat)/(n^2); } ############################## ############################## WaveDjD<-function(y_fft,f2fft,j) # compute--wavelet--coef--at-level-j #changed # uses Plancherel equality. # Usage # coef=coefj(f1fft,phij0fft,j,n) # Inputs # y_fft=fft(yobs) # f2fft=fft(phij0) or fft(psij0) accordingly # j=resolution level # n=sample size # Outputs # vector of coefs at resolution level j: length= 2^j { n=length(y_fft); j1=j-1; j2=j1-1; j3=j-3; x1=2^j1-2^j3-1; x2=2^j+2^j2+8; l1=(x1:x2); l2=((n-x2):(n-x1+2)); l_1=c(l1,l2); l_0=l_1-1; #initial vector without phase # corresponds to k=0. y1=y_fft[l_1]; v1=matrix(y1,nrow=1); v2=f2fft[l_1]; v2=matrix(v2,nrow=1); #componentwise multiplication vector1=v1*Conj(v2); #matrix of phases phasemat=PhaseC(l_0,j); #coef is the product # of vector1 by phase matrix: y=Re(vector1%*%phasemat)/(n^2); } ############################## ############################## WaveDjF<-function(f1fft,f2fft,j) # compute--fine wavelet--coef--at-level-j #changed # uses Plancherel equality. # Usage # coef=coefj(f1fft,phij0fft,j,n) # Inputs # f1fft=fft(yobs) # f2fft=fft(phij0) or fft(psij0) accordingly # j=resolution level # n=sample size # Outputs # vector of coefs at resolution level j: length= 2^j { n=length(f1fft); j1=j-1; j2=j-2; j3=j-3; j1=j-1; j2=j-2; j3=j-3; x1=2^j1-2^j3; x2=2^j+2^j1+2^j3+14; l_1=(x1:x2); l_0=l_1-1; #initial vector without phase # corresponds to k=0. y1=f1fft[l_1]; v1=matrix(y1,nrow=1); v2=f2fft[l_1]; v2=matrix(v2,nrow=1); #componentwise multiplication vector1=v1*Conj(v2); #matrix of phases phasemat=PhaseC(l_0,j); #coef is the product # of vector1 by phase matrix: y=Re(vector1%*%phasemat)/(n^2); } ######################################## ######################################## FWaveD<-function(y,g=1,L=3,deg=3,F=(log2(length(y))-1),thr=rep(0,log2(length(y))),SOFT=FALSE) # FWaveD: Forward WaveD Transform # Usage # w = FWaveD(y,g,L,deg,F,SOFT) # Inputs # y 1-d signal; length(y) = 2^J # g sample of known function; length(g)= 2^J # L Coarsest Level of V_0; L << J # deg degree of polynomial window 2 <= deg <=4 # F Finest resolution level # SOFT: thresholding policy (default=HARD) # Outputs # w 1-d estimated wavelet transform of f from x=f*g+noise. # Note: if g has no input, returns the Meyer transform # Description # This algorithm is based on [JKPR] . { x = y; nn = length(y); J = log2(nn); if(length(thr)<F-L && length(thr)>1 ){thr=c(thr,rep(thr[length(thr)],log2(nn))); warning("Vector of threshold has not length J-L \n")} if(length(thr)==1){thr=rep(thr[1],log2(length(y)))} ############################################################# y_fft = fft(y); if(length(g)==1){g_fft=rep(1,nn)}else{ g_fft= fft(g);} ## w=rep(0,nn); # Perform deconvolution in the Fourier domain y_fft=y_fft/g_fft; ##################################### if(SOFT){ # # Compute Coefficients at Coarse Level. # waveL0_fft=scaling_YM(L,J,deg); w[1:(2^L)] = HardThresh(WaveDjC(y_fft,waveL0_fft,L),thr[1]); # # Loop to Get Detail Coefficients for levels j=L,...,F. # for (j in L:F){ waveJ0_fft=wavelet_YM(j,J,deg); w[(2^j+1):(2^(j+1))] = SoftThresh(WaveDjD(y_fft,waveJ0_fft,j),thr[j-L+2]); } # # Calculate Fine Level Detail Coefficients (for j=J-1). # if F=J-1 if(F==J-1){ waveJ_fft=fine_YM(J-1,J,deg); co= WaveDjF(y_fft,waveJ_fft,J-1); w[(2^(J-1)+1):2^J] = SoftThresh(WaveDjF(y_fft,waveJ_fft,J-1),thr[J-L+1]); y=w;}else{y=w} }else { # # Compute Coefficients at Coarse Level. # waveL0_fft=scaling_YM(L,J,deg); w[1:(2^L)] = HardThresh(WaveDjC(y_fft,waveL0_fft,L),thr[1]); # # Loop to Get Detail Coefficients for levels j=L,...,F. # for (j in L:F){ waveJ0_fft=wavelet_YM(j,J,deg); w[(2^j+1):(2^(j+1))] = HardThresh(WaveDjD(y_fft,waveJ0_fft,j),thr[j-L+2]); } # # Calculate Fine Level Detail Coefficients (for j=J-1). # if necessary if(F==J-1){ waveJ_fft=fine_YM(J-1,J,deg); co= WaveDjF(y_fft,waveJ_fft,J-1); w[(2^(J-1)+1):2^J] = HardThresh(WaveDjF(y_fft,waveJ_fft,J-1),thr[J-L+1]); y=w}else{y=w}; } } ################## ################### projVj<-function(beta,n,deg) # projection onto Vj # Usage # y = projVj(beta,n) # # Inputs # beta=wavelet coef at resolution level j # n=sample size # deg=degree of Meyer wavelet { nj = length(beta); j = log2(nj); #computing fine sampling of Psy(j,0)_fft psyJ_fft=scaling_YM(j,log2(n),deg); #dyadic grid at resolution level j dyad_grid=(1:(2^j))/2^j; #index of non-zero wavelet coef dyad_grid=floor(n*dyad_grid); dyad_grid=dyad_grid-dyad_grid[1]+1; #zero padding on fine sampling x_w=rep(0,n); #imbedding non-zero wavelet coef on fine grid x_w[dyad_grid]=beta; #computing projection at level j #in the Fourier domain (convolution) x_w_fft=fft(x_w); y_fft=x_w_fft*psyJ_fft; y=Re(fft(y_fft,inverse=TRUE)); } #################################### #################################### projWj<-function(beta,n,deg) # projection onto Wj # Usage # y = projWj(beta,n) # # Inputs # beta=wavelet coef at resolution level j # n=sample size # deg=degree of Meyer wavelet { nj = length(beta); j = log2(nj); #computing fine sampling of Psy(j,0)_fft psyJ_fft=wavelet_YM(j,log2(n),deg); #dyadic grid at resolution level j dyad_grid=(1:(2^j))/2^j; #index of non-zero wavelet coef dyad_grid=floor(n*dyad_grid); dyad_grid=dyad_grid-dyad_grid[1]+1; #zero padding on fine sampling x_w=rep(0,n); #imbedding non-zero wavelet coef on fine grid x_w[dyad_grid]=beta; #computing projection at level j #in the Fourier domain (convolution) x_w_fft=fft(x_w); y_fft=x_w_fft*psyJ_fft; y=Re(fft(y_fft,inverse=TRUE)); } ############################# ############################# projFj<-function(beta,n,deg) # projection onto Fj # Usage # y = projFj(beta,n) # # Inputs # beta=wavelet coef at resolution level j # n=sample size # deg=degree of Meyer wavelet { nj = length(beta); j = log2(nj); #computing fine sampling of Psy(j,0)_fft psyJ_fft=fine_YM(j,log2(n),deg); #dyadic grid at resolution level j dyad_grid=(1:(2^j))/2^j; #index of non-zero wavelet coef dyad_grid=floor(n*dyad_grid); dyad_grid=dyad_grid-dyad_grid[1]+1; #zero padding on fine sampling x_w=rep(0,n); #imbedding non-zero wavelet coef on fine grid x_w[dyad_grid]=beta; #computing projection at level j #in the Fourier domain (convolution) x_w_fft=fft(x_w); y_fft=x_w_fft*psyJ_fft; y=Re(fft(y_fft,inverse=TRUE)); } ################################################ ################################################# IWaveD<-function(w,C=3,deg=3,F=log2(length(w))) # IWaveD -- Inverse WaveD Transform (periodized Meyer Wavelet) # # Inputs # w 1-d wavelet transform, length(wc) = 2^J. # L Coarsest Level of V_0; L << J # deg degree of polynomial window 2 <= deg <=4 # Outputs # x 1-d reconstructed signal; length(x) = 2^J # # Description # The IWaveD transform is obtained by the command # f = IFWaveD_PL(w,C,deg,F) # to reconstruct x, use the IWaveD_YM. # { nn = length(w); wc = w; if (F==log2(nn)){ J=F} else{J=F+1}; # # Reconstruct Projection at Coarse Level. # f_sum=0; beta = w[1:(2^C)]; f_sum =projVj(beta,nn,deg); # # Loop to Get Projections at detail levels j=C,...,J-2. # for (j in C:(J-2)){ alpha = w[dyad(j)]; detail_proj =projWj(alpha,nn,deg); f_sum=f_sum+detail_proj; } # # Calculate Projection for fine detail level, j=J-1. # if (F==log2(nn)) { alpha = w[dyad(J-1)]; fine_detail = projFj(alpha,nn,deg); f_sum=f_sum+fine_detail} y = f_sum/nn } ######################################################### ######################################################### ######################################################### ##########functions for TI-WaveD below################### # # # This file contains all the fucntions to perform TIWaveD # (Tranlation Invariant Wavelet Deconvolution) # # ####################################################################### findONE<-function(x) # #find location of >=1 # { n1<-sum(x>=1) (sort.list(-(x>=1)*1))[1:n1] } ######################################################################## findZERO<-function(x) # #find location of <=0 # { n1<-sum(x<=0) (sort.list(-(x<=0)*1))[1:n1] } ######################################################################### MeyerWindow<-function(xi,deg) { # # WindowMeyer -- auxiliary window function for Meyer wavelets. # # nu = WindowMeyer(xi,deg) # Inputs # xi abscissa values for window evaluation # deg degree of the polynomial defining Nu on [0,1] # 1 <= deg <= 3 # Outputs # nu polynomial of degree 'deg' if x in [0,1] # 1 if x > 1 and 0 if x < 0. # # # if (deg==3){ nu = xi^4 * ( 35 - 84 * xi + 70 * xi^2 - 20 * xi^3) } else if (deg==2){ nu = xi^3*(10 -15* xi + 6*xi^2)} else if (deg == 1){ nu = xi^2* (3 - 2*xi)} else if (deg == 0){ nu = xi} ix0<-findZERO(xi) if (length(ix0)>0) {nu[ix0]<-rep(0,length(ix0))} ix1<-findONE(xi) if (length(ix1)>0) {nu[ix1]<-rep(1,length(ix1))} y=nu } ######################################################################################## phyHAT<-function(x,deg) { # auxillary function for computing Meyer scaling function # in the Fourier domain aux1<-MeyerWindow((3*abs(x)-1),deg) cos_part<-cos(pi*aux1/2); y1<-cos_part*(abs(x)>1/3 & abs(x)<=2/3); y2<-rep(1,length(x))*(abs(x)<=1/3); y<-y1+y2; } ################################################################################ psyHAT<-function(x,deg) { # auxillary function for computing Meyer wavelet function # in the Fourier domain aux1<-MeyerWindow((3*abs(x)-1),deg) aux2<-MeyerWindow((3*abs(x)/2-1),deg) sin_part<-(exp(-1i*pi*x))*sin(pi*aux1/2); cos_part<-(exp(-1i*pi*x))*cos(pi*aux2/2); y1<-sin_part*(abs(x)>1/3 & abs(x)<=2/3); y2<-cos_part*(abs(x)>2/3 & abs(x)<=4/3); y=y1+y2; } ###########################################################################3 scaling_YM<-function(j,j_max,deg) { #generate phyHAT(j,0)--the fft of the scaling function--in the periodic setting. # deg=deg of the Meyer wavelet (1,2,3). # Written for R by Marc Raimondo # and Michael Stewart, the University of Sydney, 2006. # Copyright (c) 2006. # # reference: ``Translation Invariant Deconvolution in a periodic setting'' # by D.Donoho and M. Raimondo (2005). IJWMIP # The paper is available by www from # http://www.usyd.edu.au/u/marcr/ # omega_pos<-seq(0,10/(2*pi),by=1/(2^j)) n_pos<-length(omega_pos); nn<-2^j_max; aux1=phyHAT(omega_pos,deg); #rotate and take zero out psyHAT_LEFT=rep(0,nn); psyHAT_LEFT[1:n_pos]<-aux1; aux2<-psyHAT_LEFT; aux2<-aux2[-1] aux2<-c(aux2, 0); psyHAT_RIGHT<-Conj(rot90(aux2)); y<-(psyHAT_RIGHT+psyHAT_LEFT)*2^(-j/2)*nn; } ########################################################################### wavelet_YM<-function(j,j_max,deg) { #generate psyHAT(j,0)--the fft of the wavelet function--in the periodic setting. # deg=deg of the Meyer wavelet (1,2,3). omega_pos<-seq(0,10/(2*pi),by=1/(2^j)) n_pos<-length(omega_pos); nn<-2^j_max; omega_neg<-seq(-10/(2*pi),-1/2^j,,by=1/(2^j)) n_omega<-2*length(omega_pos)-1; n<-2^j_max-n_omega; aux1<-psyHAT(omega_pos,deg); #rotate and take zero out psyHAT_LEFT=rep(0,nn); psyHAT_LEFT[1:n_pos]<-aux1; aux2<-psyHAT_LEFT; aux2<-aux2[-1] aux2<-c(aux2, 0); psyHAT_RIGHT<-Conj(rot90(aux2)); y<-(psyHAT_RIGHT+psyHAT_LEFT)*2^(-j/2)*nn; } ############################################################################## fine_YM<-function(j,j_max,deg) { #generate psyHAT--the fft of the wavelet function--in the periodic setting. # deg=deg of the Meyer wavelet (1,2,3). # at the finest resolution level omega_pos<-seq(0,10/(2*pi),by=1/(2^j)); n_pos<-2^j-2^(j-3); nn<-2^j_max; aux1<-psyHAT(omega_pos,deg); #rotate and take zero out n2<-n_pos+2^(j-3)+1; psyHAT_LEFT=rep(0,n2); psyHAT_LEFT[1:n_pos]<-aux1[1:n_pos]; psyHAT_LEFT[(n_pos+1):(n_pos+2^(j-3)+1)]<--1; aux2<-psyHAT_LEFT; aux2<-aux2[-1] psyHAT_RIGHT<-Conj(rot90(psyHAT_LEFT)); psyHAT_RIGHT<-psyHAT_RIGHT[-1]; psyHAT_RIGHT<-psyHAT_RIGHT[-length(psyHAT_RIGHT)] y<-c(psyHAT_LEFT, psyHAT_RIGHT)*2^(-j/2)*nn; } ######################################################################## rot90<-function(x) { # #is the 90 degree counterclockwise rotation of matrix x. # if (is.null(dim(x))){ n1=length(x) x[n1:1] } else { n1=dim(x)[1] t(x)[n1:1,] } } ################################################################# HardThresh<-function(y,t) { # HardThresh -- Apply Hard Threshold # Usage # x = HardThresh(y,t) # Inputs # y Noisy Data # t Threshold # Outputs # x y 1_{|y|>t} # x = y * (abs(y) > t); # Written for R by Marc Raimondo # and Michael Stewart, the University of Sydney, 2006. # # # Reference: David Donoho and Iain Johnstone JASA 1994. # # } ################################################################# SoftThresh<-function(y,t) { # SoftThresh -- Apply Hard Threshold # Usage # x = HardThresh(y,t) # Inputs # y Noisy Data # t Threshold # Outputs # x y sign(y)(|y|-t)_+ # aux=(abs(y)-t); aux=(aux+abs(aux))/2; x = sign(y) * aux; # Written for R by Marc Raimondo # and Michael Stewart, the University of Sydney, 2006. # # # Reference: David Donoho and Iain Johnstone JASA 1994. # # } ################################################################################## MultiThresh1<-function(s,g,L,eta) { # MultiThresh --Find optimal threshold by level-by-level. # # Inputs # s Noise-sd (or estimate). # g_fft noisy Sample of g_fft # L Lowest resolution level=C (Coarsest) # eta smoothing parameter (default=1) # Outputs # y= vector of thresholds from level=L to J-1. # # reference: ``Wavelet deconvolution in a periodic setting'' # by I.M. Johnstone, G. Kerkyacharian, D. Picard and M. Raimondo (2004).[JKPR] # The paper is available (as a prepint) by www from # http://rome:www.usyd.edu.au/u/marcr/ #compute optimal threshold for deconvolution # based on the Fourier transform of g. # For the last resolution level we use spline extrapolation. n=length(g); g_fft<-fft(g); F<-log(n)/log(2); thr<-rep(0,F-L-1); for (j in L:(F-2)){ thr[j-L+1] <- (sum(abs(g_fft[dyad(j)])^(-2))+sum(abs(g_fft[n-dyad(j)+1])^(-2)))/2^j ; } aux1<-s*sqrt(thr)*sqrt(log(n)/n)*(eta/sqrt(4*pi)); #linear extrapolation for Jmax n1<-length(aux1); d1<-(aux1[n1]-aux1[1])/(n1-1); aux2<-(n1+1)*d1; y<-c(aux1, aux2); } ################################################################# ################################################################ # # # # # FWT_TI<-function(f_fft,psyJ_fft) { # #Inputs: f_fft=fft(f) # psyJ_fft=fft(Ondelette au niveau 'lev') # lev=resolution level # thr=threshold # nn=length(f) # # Output: wavelet coefficients at resolution level lev (non-ordered in time) # nn<-length(f_fft); Aj_fft<-f_fft*psyJ_fft; #need to scale *sqrt(pi) as in Matlab Aj<-Re(fft(Aj_fft,inverse=TRUE))/(nn*nn); # Written by Marc Raimondo, the University of Sydney, # Comments? e-mail [email protected] } ########################################################33 ########################################################### scale<-function(yobs,L=3,deg=3) { # scale-estimation-for-Meyer-Wavelet-coefficients # Can be used for -direct-and--indirect-noisy--observations # Inputs # yobs 1-d signal; length(x) = 2^J # L Coarsest Level of V_0; L << J # deg degree of polynomial window 2 <= deg <=4 # # Outputs # y=estimated noise standard deviation. n<-length(yobs); J<-round(log(n)/log(2),1); j<-J-1; psyJ_fft<-fine_YM(j,J,deg); # psyJ_fft<-wavelet_YM(j-1,J,deg); x_fft<-fft(yobs); yobs_w<- FWT_TI(x_fft,psyJ_fft); y<-mad(yobs_w*sqrt(n)); #y<-sqrt(var(yobs_w*sqrt(n))); # Written by Marc Raimondo, the University of Sydney, 2003. # Comments? e-mail [email protected] } ############################################################## # IFWT_TI<-function(f_fft,psyJ_fft,lev,thr,nn,SOFT=FALSE) { # #Inputs: f_fft=fft(f) # psyJ_fft=fft(Ondelette au niveau 'lev') # lev=resolution level # thr=threshold # nn=length(f) if (SOFT){ Aj_fft<-f_fft*psyJ_fft; Aj<-Re(fft(Aj_fft,inverse<-TRUE))/(nn^2); Bj<-SoftThresh(Aj,thr); Bj_fft<-fft(Bj); fj_fft<-Bj_fft*Conj(psyJ_fft); J <- log2(nn); y<-Re(fft(fj_fft,inverse=TRUE))/(nn*2^(J-lev)); }else{ Aj_fft<-f_fft*psyJ_fft; Aj<-Re(fft(Aj_fft,inverse<-TRUE))/(nn^2); Bj<-HardThresh(Aj,thr); Bj_fft<-fft(Bj); fj_fft<-Bj_fft*Conj(psyJ_fft); J <- log2(nn); y<-Re(fft(fj_fft,inverse=TRUE))/(nn*2^(J-lev)); } } ################################################## # # dyad<-function(j) { # dyad -- Index entire j-th dyad of 1-d wavelet xform # Usage # ix = dyad(j); # Inputs # j integer # Outputs # ix list of all indices of wavelet coeffts at j-th level i <- (2^(j)+1):(2^(j+1)) ; } # Original version by David L. Donoho # Copyright (c) 1993. # Written for R by Marc raimondo (University of Sydney) ############################################################################################# # # # fftshift<-function(x) { # # for visualizing the Fourier transform with the zero-frequency component in the middle of the spectrum. # m=length(x); p = ceiling(m/2); new_index = c(((p+1):m),(1:p)); y=x[new_index]; } ################################################################### ########################################################################## speczoom<-function(y_test,fenetre) { #Plot of spectrum with zero frequency in the middle # of the window #input is y_test (kconvolution kernel) # fenetre is (window size) n=length(y_test); y_fft=fft(y_test); a=n/2-fenetre/2+1; b=n/2+fenetre/2+1; spectrum=fftshift(y_fft); spectrum=spectrum[a:b]; x=(a:b)-n/2-1; #subplot(211) #plot((1:n)/n,y_test,'-.b'); #subplot(212); #plot(x,log(abs(dum)),'-.r'); plot(x,log(abs(spectrum)),type='l',xlim=c(-500,500),ylim=c(-6,0)); y=log(abs(spectrum)); #min(abs(dum)) } # ########################################################### ########################################################### fftshift<-function(y) { # # Shift zero-frequency component to center of spectrum. # n=length(y); n2=floor(n/2); ind1=(1:n2); ind2=((n2+1):n); aux1=(y[ind1]); aux2=y[ind2]; y=c(aux2,aux1); } # # Written for R by Marc raimondo (University of Sydney) ######################################################## ######################################################## stoptime<-function(g,sigma) { # compute the stoping time # in the Fourier domain using noisy egein values #Input: # g=noisy fft of convolution kernel # sigma=estimated noise's sd #Output # [M,J_1]=stime(g,sigma) # where M is frequency cut-off # and J_1 is corresponding resolution level cut-off n=length(g); #bandwidth h=n/2; aux=log(abs(g[1:h])); threshold_fft=log((sigma/sqrt(n)))+ log((log(sqrt(n)/sigma))^(1/2)); aux1=1*(aux[1:h]- threshold_fft)>0; vs1=sort(aux1); ind1=sort.list(aux1); freq_cut=ind1[1]; resolution_cut=floor(log2(freq_cut))-1; if (min(aux1)>0){ y=c(n/2,(log2(n)-1))} else { y=c(freq_cut,resolution_cut); } } # ############################################################ ############################################################# find.j1<-function(g,sigma) # compute the stoping time # in the Fourier domain using noisy eigen values # --scaled to band-limited wavelet with 2^{j/2}=sqrt{l} # for more details see [CR05] #Input: # g =convolution kernel # sigma=estimated noise's sd #Output # [M,J_1]=stime(g,sigma) # where M is frequency cut-off # and J_1 is corresponding resolution level cut-off ###################################################### # # { g_fft=fft(g); n=length(g_fft); aux2=g_fft[(1:(n/2))]; aux3=sqrt((1:(n/2))); aux4=aux2/aux3; aux5=rot90(aux4); aux6=c(aux4,aux5); y=stoptime(aux6,sigma); } ###################################################### ###################################################### multires <- function(wcUntrimmed,lowest=3,coarse=3,highestplot=NULL,descending=FALSE,sc=1) #this function plots MRA { L <- log2(length(wcUntrimmed)) if((L%%1)>0) warning("Vector of wavelet coefficients has length not a power of 2\n") wc <- wcUntrimmed[-(1:(2^coarse))] #print(rbind(length(wcUntrimmed),length(wc))) highest <- ceiling(L)-1 if(is.null(highestplot)) highestplot <- highest reslev <- rep(coarse:highest,2^(coarse:highest)) #print(cbind(wc,reslev)) num <- numeric() for(i in (min(reslev):max(reslev))){num <- c(num,2*(1:(2^i))-1)} #cbind(num,den) M <- 2*max(abs(wc))/sc; den <- 2^(reslev+1) ind <- (reslev>=lowest)&(reslev<=highestplot) x <- (num/den)[ind] y1 <- reslev[ind] if(descending) y1 <- (highest+lowest-y1) leny1=length(y1) lenwcind <- length(wc[ind]) #print(cbind(leny1,lenwcind)) y2 <- y1 + wc[ind]/M cbind(x,y1,y2) plot(c(x[1],x[1]),c(y1[1],y2[1]),type="l",xlim=range(x),ylim=range(c(y1,y2)),lab=c(5,highestplot-lowest+1,7),xlab="",ylab="Resolution Level") for(i in 2:length(x)){ lines(c(x[i],x[i]),c(y1[i],y2[i])) } } #################################################### #################################################### maxithresh<-function(data,g,L=2,F=(log2(length(data))-1),eta=sqrt(6)) { # maxithresh --Find optimal threshold level-by-level. # # Inputs # data: y=f*g+noise. # g: convolution kernel (sample of) # L: here should be Lowest set to L-1, to match C in FOurier domain # F: Finest resolution level # eta smoothing parameter (default=sqrt(6)) # Outputs # y= vector of thresholds from level=L to F. # # reference: ``Wavelet deconvolution in a periodic setting'' # by I.M. Johnstone, G. Kerkyacharian, D. Picard and M. Raimondo (2004).[JKPR] # The paper is available (as a prepint) by www from # http://www.maths.usyd.edu.au/u/marcr/ #compute optimal threshold for deconvolution # based on the Fourier transform of g. s=scale(data); n=length(g); g_fft<-fft(g); thr<-rep(0,F-L); if (F==(log2(n)-1)) { for (j in L:(F-1)){ thr[j-L+1] <- (sum(abs(g_fft[dyad(j)])^(-2))+sum(abs(g_fft[n-dyad(j)+1])^(-2)))/2^j ; } aux1<-s*sqrt(thr)*sqrt(log(n)/n)*(eta/sqrt(4*pi)); #linear extrapolation for Jmax n1<-length(aux1); d1<-(aux1[n1]-aux1[1])/(n1-1); aux2<-(n1+1)*d1; y<-c(aux1, aux2); } else { for (j in L:(F)){ thr[j-L+1] <- (sum(abs(g_fft[dyad(j)])^(-2))+sum(abs(g_fft[n-dyad(j)+1])^(-2)))/2^j ; } aux1<-s*sqrt(thr)*sqrt(log(n)/n)*(eta/sqrt(4*pi)); y<-aux1; } } ##################################### ##################################### threshsum<-function(w.res,L=3,F=(log2(length(w.res))-1)) # # Usage # out = threshsum(w.res,L=3,F=log2(length(w))-1) # Inputs # w.res:residual after thresholding # # L Coarsest Level of V_0; L << J # F Finest resolution level # Outputs # percentage of thresholding per level # j=C,L,L+1,...,F (incl.scaling) { res=rep(0,F-L+1); #scaling coef sum1=sum(abs(w.res[1:(2^L)])<=0) res[1]=sum1/2^L; # # Loop to Get Detail Coefficients for levels j=L,...,F. # for (j in L:F){ sum1=sum(abs(w.res[dyad(j)])<=0) res[j-L+2]=sum1/2^j; } y=1-res; } ######################################### ######################################### plotspec<-function(g,s) { #This function plots #the log spectrum and the optimal noise threshold #which is used to find_j1 n=length(g); fen=n/2-2; g_fft=fft(g); sigma=s; speczoom(g,n) aux2=g_fft[(1:(n/2))]; aux3=sqrt((1:(n/2))); aux4=aux2/aux3; aux5=rot90(aux4); aux6=c(aux4,aux5); ##### threshold_fft=log((sigma/sqrt(n)))+ log((log(sqrt(n)/sigma))^(1/2)); fen=n/2-2; aux3=log(sqrt((1:fen/2))); aux5=rot90(aux3); aux6=c(aux5, aux3); aux7=aux6+threshold_fft; lines((-fen:(fen-1)),aux7,lty=2) } #################################################################### #################################################################### ########################################################## ########################################################## summary.wvd<-function(object,...) { #this function gives a summary #of objects of class 'WaveD' #as produced by the WaveD function # y.wvd=WaveD(y,g) y.wvd=object lab=y.wvd$label n=y.wvd$n; t = (1:n)/n; cat("\nCall:\n", deparse(y.wvd$call), "\n\n", sep = "") cat('Degree of Meyer wavelet =',y.wvd$deg,', Coarse resolution level=',y.wvd$L) cat('\n') cat('Sample size =',y.wvd$n,', Maximum resolution level=',log2(y.wvd$n)-1,'.') cat('\n') cat('WaveD optimal Fourier freq=',y.wvd$M, '; WaveD optimal fine resolution level j1=',y.wvd$j1) cat('\n') if(y.wvd$j1!=y.wvd$F){ cat('Warning: WaveD finest resolution level has been set to F=',y.wvd$F) cat('\n')} opt.thr=round(maxithresh(y.wvd$data,y.wvd$g,eta=y.wvd$eta),3); opt.thr=opt.thr[1:length(y.wvd$lev)]; aux=prod(opt.thr==round(y.wvd$thr,3)); if(aux){threshold='Maxiset threshold'}else{threshold='Manual threshold'} cat('The choice of the threshold is:',threshold) cat('\n') cat('Thresholding policy=',y.wvd$POL, '. Threshold constant gamma=',round(y.wvd$eta,3)) cat('\n') cat('\n') mat.thr=matrix(rep(0,3*length(y.wvd$thr)),ncol=3) mat.thr[,2]=round(y.wvd$thr,3); mat.thr[,3]=round(y.wvd$per,3); nb=y.wvd$F-y.wvd$L+2; aux=rep(0,nb); aux[1]=round(max(abs(y.wvd$w[1:2^y.wvd$C])),3) for (j in 2:nb){ aux[j]=round(max(abs(y.wvd$w[dyad(y.wvd$L+j-2)])),3) } mat.thr[,1]=aux; dimnames(mat.thr) <- list(paste("level ",y.wvd$lev," ",sep=""),c('Max|w|','Threshold',' % of thresholding')) print(mat.thr) cat('\n') cat('Noise-proxy statistics:\n') cat(c('Estimated standard deviation= ',round(y.wvd$s,3))) cat('\n') cat(c('Shapiro test for normality, P=',round(y.wvd$p,5))) cat('\n') } ############################################################## ############################################################# plot.wvd<-function(x,...) { #this fucntion gives (generic) plot #of objects of class 'wvd' #as produced by the WaveD function y.wvd=x n=y.wvd$n; t = (1:n)/n; par(mfrow=c(2,2)) plot(t,y.wvd$data,type='l',main='Observations') multires(y.wvd$w.thr,highestplot=y.wvd$F) title(main='Thresholded FWaveD transform ') plotspec(y.wvd$g,y.wvd$s) title(main=cbind('Fourier domain, optimal resolution level F=',y.wvd$j1)) plot(t,y.wvd$waved,type='l',main='TI-WaveD estimate') #readline() #par(mfrow=c(2,2)) #multires(y.wvd$w,hi=y.wvd$F) #title(main='FWaveD transform (without thresholding)') #multires(y.wvd$w.thr,hi=y.wvd$F) #title(main='Thresholded FWaveD transform ') #plot(t,y.wvd$iw,type='l',main='Inverse WaveD transform (no thresholding)') #plot(t,y.wvd$ordinary,type='l',main='Ordinary WaveD estimate') cat('Hit enter to see the next plot\n') readline() par(mfrow=c(2,2)) par(pty='s') noise.scaled=y.wvd$noise/y.wvd$s; plot(noise.scaled,type='l',main=cbind('Noise proxy. Shapiro test for normality, P=',round(y.wvd$p,3))) plot(seq(-4,4,le=n),dnorm(seq(-4,4,le=n)),type='l',lwd=2,lty=2,xlab=' ',ylab=' ',main='N(0,1) pdf:dashed curve, estimated density: plain curve') lines(density(noise.scaled),lwd=2) qqnorm(noise.scaled,cex=0.4) qqline(noise.scaled,lwd=2) boxplot(noise.scaled,main='Boxplot',horizontal=TRUE) par(pty='m') } # Written by Marc Raimondo and Michael Stewart, # the University of Sydney, 2006. # Copyright (c) 2005. # Comments? e-mail [email protected] # # Setting up noisy-blur-signal model parameters. # n=sample size # a=box-car width (preferrably a quadratic irrational e.g. a=1/sqrt(5) # al, be=shape and scale of Gamma pdf. # sigma_xxx=noise level. ############################################################## # below are aux function to perform example.waved # # # # This file contains all the functions to perform # example.wave.R, the script that implement the experiment # for wavelet deconvolution. # # # # Written for R by Marc Raimondo # and Michael Stewart, the University of Sydney, 2006. # Copyright (c) 2006. # # reference: ``Wavelet deconvolution in a periodic setting'' # by I.M. Johnstone, G. Kerkyacharian, D. Picard and M. Raimondo (2004).[JKPR] # # The paper is available by www from # http://www.usyd.edu.au/u/marcr/ # ################################################################# make.lidar<-function(n){ # #Make artificial lidar signal # t<-(1:n)/n 1*(t>0.15)*(t<0.65)+1*(t>0.28)*(t<0.48)+(133.33*t-106.66)*(t>0.8)*(t<0.815)+(-133.33*t+110.6639)*(t>0.815)*(t<0.83)+(133.33*t-119.997)*(t>0.9)*(t<0.915)+(-133.33*t+123.9969)*(t>0.915)*(t<0.93) } ########################################################3 ########################################################## BlurSignal<-function(f,g) { # #compute the convolution of f and g # nf=length(f) f.fft<-fft(f) g.fft<-fft(g) fg.fft<-f.fft*g.fft Re(fft(fg.fft,inverse=TRUE))/nf } ######################################################## ################################################################### make.doppler<-function(n) # #Make doppler signal # { t<-(1:n)/n sig = (sqrt(t*(1-t)))*sin((2*pi*1.05)/(t+0.05)); } # # As in [DJ94] # ################################ ################################ ####################################### ######################################## dyadjk<-function(j,k) { # dyadjk -- return Index of wavelet coefficient (j,k)-- # Usage # ix = dyad(j,k); # Inputs # j integers # Outputs # Index of wavelet coefficient (j,k) in the vector of wavelet coef. ix=dyad(j)[1]+k; } # ############################################## # # # Below is the function that generates # data examples of [RS] # ################################################ waved.example<-function(pr=TRUE,gr=TRUE) { if(pr){ n=2^11 al = 0.5 be=0.25 seed=11; sigma.med=0.05 t = (1:n)/n } if(!pr){ cat('Please enter the sample size (must be a power of 2, default n=2048, should be>256 to run all figures) \n') n <- readline() if(n==''){n=2048} n=as.numeric(n) cat('\n') cat('Please enter the noise sd ( default sd=0.05) \n') sigma.med <- readline() if(sigma.med==''){sigma.med=0.05} sigma.med=as.numeric(sigma.med) cat('\n') cat('Please enter the Degree of Ill-Posedness (default=0.5) \n') al <- readline() if(al==''){al=0.5} al=as.numeric(al) cat('\n') cat('Please enter the scale parameter of the blurring kernel (default=0.25) \n') be <- readline() if(be==''){be=0.25} be=as.numeric(be) cat('Please enter the seed number (must be >0, default=11) \n') seed <- readline() if(seed==''){seed=11} seed=as.numeric(seed) cat('\n') } ############################################################ t=(1:n)/n temp<-dgamma(t,shape=al,scale=be); aux1<-max(temp) temp2<-temp/aux1 aux2<-sum(temp2) GAMMA<-temp2/aux2 GAMMA=GAMMA; LIDAR<-make.lidar(n)/1.7 DOPPLER=make.doppler(n)*1.9; lidar.blur=BlurSignal(LIDAR,GAMMA) doppler.blur=BlurSignal(DOPPLER,GAMMA) set.seed(seed) noise=rnorm(n); noiseT=rt(n,2); sdnoise=sqrt(var(noise)); noiseT=noiseT/sdnoise; lidar.noisy=lidar.blur+sigma.med*noise doppler.noisy=doppler.blur+sigma.med*noise ##t noise data lidar.noisyT=lidar.blur+sigma.med*noiseT doppler.noisyT=doppler.blur+sigma.med*noiseT GAMMA_fft=fft(GAMMA); GAMMA_fft_noisy=GAMMA_fft+sigma.med*fft(noise)/sqrt(n); GAMMA_noisy=Re(fft(GAMMA_fft_noisy,inverse=TRUE))/n; g=GAMMA; g.noisy=GAMMA_noisy; ##t-noise GAMMA_fft_noisyT=GAMMA_fft+sigma.med*fft(noiseT)/sqrt(n); GAMMA_noisyT=Re(fft(GAMMA_fft_noisyT,inverse=TRUE))/n; g.noisyT=GAMMA_noisyT; ############################ ## ## Graphics display below if gr=TRUE if(gr){ cat('-------------------------------------------------------\n') cat('Initializing noisy-blurred signals model:\n') cat('sample size n =',n) cat('\n') cat('noise sd = ',sigma.med) cat('\n') # cat('Convolution kernel g:\n') cat('gamma-distribution with shape paremeter=',al) cat('\n') cat('and scale parameter= ',be) cat('\n') cat('(effective) Degree of Ill-Posedness (DIP)= ',al) cat('\n') cat('The seed number has been set to ',seed) cat('\n') cat('\n') cat('Blurred Signals to Noise Ratios:\n') bsnrl<-round(10*log(var(lidar.blur)/sigma.med^2)/log(10),1) cat('Lidar BSNR(dB) =',bsnrl) cat('\n') bsnrl<-round(10*log(var(doppler.blur)/sigma.med^2)/log(10),1) cat('Doppler BSNR(dB) =',bsnrl) cat('\n') cat('-------------------------------------------------------\n') ###run figures below if(pr){ cat('This is the same set up as in: \n') cat('The WaveD Transform in R by Raimondo and Stewart [RS].\n') cat('To change model parameters use data.demo=waved.example(F) \n') } cat('\n') if(!pr){ cat('This is not the same set up as in: \n') cat('The WaveD Transform in R by Raimondo and Stewart [RS].\n') cat('To get the same model parameters as in [RS] use data.demo=waved.example(T) \n') cat('Warning: the figures/captions of [RS] may not be relevant when using new model parameters. \n') } cat('\n') ######################################################## cat('Would you like to see the output? (Y/N) \n') answer <- readline() pr2=switch(answer,y=,Y=TRUE,FALSE) cat('-------------------------------------------------------\n') if(pr2){ ###################################################### cat('Figure 1 shows the original LIDAR and doppler signals\n') par(mfrow=c(1,2)) plot(t,LIDAR,type='l') plot(t,DOPPLER,type='l') cat('Hit enter to see the next plot\n') readline() cat('-------------------------------------------------------\n') ###################################################### cat('Figure 2 shows the blurred LIDAR and doppler signals\n') par(mfrow=c(1,2)) plot(t,lidar.blur,type='l') plot(t,doppler.blur,type='l') cat('Hit enter to see the next plot\n') readline() cat('-------------------------------------------------------\n') #################################################### cat('Figure 3 shows the noisy-blurred LIDAR and doppler signals\n') par(mfrow=c(1,2)) plot(t,lidar.noisy,type='l') plot(t,doppler.noisy,type='l') ##########################3 #cat('Hit enter to execute the WaveD command\n') #readline() Fmax=floor(log(length(lidar.noisy))/log(2))-1 lidar.wvd=WaveD(lidar.blur,g,F=6,thr=0) lidar.noisy.wvd=WaveD(lidar.noisy,g,F=6,thr=0) ############################## cat('Hit enter to see the next plot\n') readline() par(mfrow=c(2,2)) multires(lidar.wvd$w,lowest=3,highestplot=6) multires(lidar.noisy.wvd$w,lowest=3,highestplot=6) plot(t,lidar.wvd$iw,type='l') plot(t,lidar.noisy.wvd$iw,type='l') cat('-------------------------------------------------------\n') ################################################ cat('Figure 4 of [RS] shows a wavelet decomposition of the LIDAR signal\n') cat('Left: wavelet transform from noise free data, right...from noisy data\n') cat('Top plots are wavelet coefficients according to time and resolution level\n') cat('Bottom plots are corresponding inverse wavelet transforms\n') cat('Left plots illustrate: large wavelet coefficeint nearby LIDAR discontinuities \n') cat('Right plots illustrate: noise effect on wavelet coefficient increases with resolution level \n') cat('Hit enter to see the next plot\n') readline() ########################################## cat('-------------------------------------------------------\n') cat('Figure 5 of [RS] shows the effect of a large threshold (right) and small threshold (left) \n') par(mfrow=c(1,2)) plot(t,WaveD(lidar.noisy,g,F=6,thr=0.2)$ord,type='l') plot(t,WaveD(lidar.noisy,g,F=6,thr=0.02)$ord,type='l') cat('Hit enter to see the next plot\n') cat('-------------------------------------------------------\n') ########################################################### readline() cat('Figure 6 of [RS] shows the effect of the Maxiset threshold, left plots: no thresholding, right plots: Maxiset Thresholding \n') par(mfrow=c(2,2)) lidar.maxi.wvd=WaveD(lidar.noisy,g); multires(lidar.maxi.wvd$w,lowest=3,highestplot=6) multires(lidar.maxi.wvd$w.thr,lowest=3,highestplot=6) plot(t,WaveD(lidar.noisy,g,F=6,thr=0)$ord,type='l') plot(t,WaveD(lidar.noisy,g,F=6)$ord,type='l') cat('Hit enter to see the next plot\n') cat('-------------------------------------------------------\n') readline() ############################################## cat('Figure 7 of [RS]: the Maxiset threshold do not prevent noise in high resolution level... \n') cat('Computing the full WaveD transform takes approx.15sec...\n') lidar.Fmax.wvd=WaveD(lidar.noisy,g,F=Fmax) par(mfrow=c(1,2)) multires(lidar.Fmax.wvd$w.thr) plot(t,lidar.Fmax.wvd$ord,type='l') cat('Hit enter to see the next plot\n') cat('-------------------------------------------------------\n') readline() ####################################### par(mfrow=c(1,2)) cat('Figure 8 of [RS]: To prevent noise in high resolution levels \n') cat(' WaveD is fitted with an adaptive level selection in the Fourier domain \n') cat('(left) noise free eigen values: maximum Fourier freq=', lidar.maxi.wvd$M,'\n') cat('(left) noise free eigen values: maximum Resolution level=', lidar.maxi.wvd$F,'\n') lidar.NEV.wvd=WaveD(lidar.noisy,g.noisy) cat('(right) noisy eigen values: maximum Fourier freq=', lidar.NEV.wvd$M,'\n') cat('(right) noisy eigen values: maximum Resolution level=', lidar.NEV.wvd$F,'\n') plotspec(lidar.maxi.wvd$g,lidar.maxi.wvd$s) plotspec(g.noisy,lidar.maxi.wvd$s) cat('Hit enter to see the next plot\n') cat('-------------------------------------------------------\n') readline() ####################################### cat('Figure 9 of [RS]: cycle-spining improves the WaveD fit (right) \n') cat('Ordinary WaveD (left), Translation Invariant WaveD (right)\n') par(mfrow=c(1,2)) plot(t,lidar.maxi.wvd$ord,type='l') plot(t,lidar.maxi.wvd$waved,type='l') cat('Hit enter to see the next plot\n') cat('-------------------------------------------------------\n') ########################################## readline() cat('Figure [10] of [RS]: WaveD with Hard thresholding (left), soft thresholding (right)\n') lidar.soft.wvd=WaveD(lidar.noisy,g,SOFT=TRUE) plot(t,lidar.maxi.wvd$ord,type='l') plot(t,lidar.soft.wvd$ord,type='l') cat('Hit enter to see the next plot\n') cat('-------------------------------------------------------\n') readline() ############################################# cat('Figure [11],[12] of [RS]: WaveD analysis of the blurred Doppler in Gaussian noise\n') cat('Illustration of the plot function for wvd objects\n') cat('The first 4 plots illustrate the WaveD fit \n') cat('The last 4 plots show a residual/noise analysis after a WaveD fit\n') doppler.wvd=WaveD(doppler.noisy,g); plot(doppler.wvd) cat('Hit enter to read the summary of the doppler.wvd object \n') readline() cat('-------------------------------------------------------\n') summary(doppler.wvd) ############################################ cat('Hit enter to see the next plot\n') cat('-------------------------------------------------------\n') readline() print('Figure 14,13: WaveD fit to lidar data with non-Gaussian noise (default setting)') cat('Hit enter to plot the lidarT.wvd object \n') readline() lidarT.wvd=WaveD(lidar.noisyT,g) plot(lidarT.wvd) print('The TI-WaveD estimate exhibits a large noise residual even after thresholding') cat('Hit enter to read the summary of the lidarT.wvd object \n') readline() cat('-------------------------------------------------------\n') summary(lidarT.wvd) print('The P-value of the Shapiro test=0 suggesting a non-Gaussian noise') cat('Hit enter to see the next plot \n') readline() ############################################################# print('Figure 15: Improved WaveD fit to lidar data with non-Gaussian noise') lidarTS.wvd=WaveD(lidar.noisyT,g,SOFT=TRUE) lidarT8.wvd=WaveD(lidar.noisyT,g,eta=sqrt(8)) lidarT12.wvd=WaveD(lidar.noisyT,g,eta=sqrt(12)) par(mfrow=c(2,2)) plot(t,lidarTS.wvd$ord,type='l',lwd=2,main='(a)') lines(t,LIDAR,lwd=2,lty=2) plot(t,lidarT8.wvd$ord,type='l',lwd=2,main='(b)') lines(t,LIDAR,lwd=2,lty=2) plot(t,lidarT8.wvd$waved,type='l',lwd=2,main='(c)') lines(t,LIDAR,lwd=2,lty=2) plot(t,lidarT12.wvd$waved,type='l',lwd=2,main='(d)') lines(t,LIDAR,lwd=2,lty=2) cat('Hit enter to see the next figure\n') readline() cat('-------------------------------------------------------\n') ############################################################################# cat('Figure 16: LIDAR WaveD estimation with noisy eigen values\n') plot(lidar.NEV.wvd) ############################################ cat('This is the last Figure.\n') } } output=list(lidar.noisy=lidar.noisy, lidar.noisyT=lidar.noisyT,doppler.noisyT=doppler.noisyT,lidar.blur=lidar.blur, doppler.noisy=doppler.noisy, doppler.blur=doppler.blur,t=t,n=n,g=GAMMA,lidar=LIDAR,doppler=DOPPLER,seed=seed,sigma=sigma.med, g.noisy=GAMMA_noisy,g.noisyT=g.noisyT,dip=be,k.scale=al) }
/scratch/gouwar.j/cran-all/cranData/waved/R/functionINIT.R
cat('Would you like to use the default parameter setting \n') cat('to reproduce the figures of: The WaveD Transform in R \n') cat(' by Marc Raimondo and Michael Stewart, Journal of Statistical Software (2007).\n') cat('Yes or No (Y/N)?\n') answer <- readline() pr=switch(answer,y=,Y=TRUE,FALSE) data.demo=waved.example(pr)
/scratch/gouwar.j/cran-all/cranData/waved/demo/waved.R
align <- function(wt, coe=FALSE, inverse=FALSE){ # error checking if(!inverse){ if(wt@aligned) stop("Unnecessary proceedure: 'wt' object is already aligned.") } else { if(!wt@aligned) stop("Unnecessary proceedure: 'wt' object is already unaligned.") } if(is.na(match(class(wt), c("dwt", "modwt")))) stop("Invalid argument: 'wt' must be of class 'dwt' or 'modwt'") filter <- wt@filter if(filter@transform == "modwt") modwt <- TRUE J <- length(wt@W) # a function to align the wavelet and scaling coefficients align.coef <- function(wt.coef, wavelet, coe, modwt, inverse){ shift.coef <- lapply(1:J, function(j,coef,filter,wavelet,coe,modwt,inverse){ shift <- wt.filter.shift(filter, j, wavelet, coe, modwt) N <- dim(coef[[j]])[1] if(shift >= N) shift <- shift - floor(shift/N)*N if(shift == 0){ shiftcoef <- coef[[j]] } else { if(dim(coef[[j]])[2] == 1){ if(!inverse) shiftcoef <- as.matrix(c(coef[[j]][(shift+1):N,], coef[[j]][1:shift,])) else shiftcoef <- as.matrix(c(coef[[j]][(N-shift+1):N,], coef[[j]][1:(N-shift),])) } else { if(!inverse) shiftcoef <- rbind(coef[[j]][(shift+1):N,], coef[[j]][1:shift,]) else{ shiftcoef <- rbind(coef[[j]][(N-shift+1):N,], coef[[j]][1:(N-shift),]) } } } return(shiftcoef) }, coef=wt.coef, filter=filter, wavelet=wavelet, coe=coe, modwt=modwt, inverse=inverse) return(shift.coef) } # align the coefficients wt.shifted <- wt wt.shifted@W <- align.coef(wt@W, wavelet=TRUE, coe=coe, modwt=modwt, inverse=inverse) wt.shifted@V <- align.coef(wt@V, wavelet=FALSE, coe=coe, modwt=modwt, inverse=inverse) if(!inverse) wt.shifted@aligned <- TRUE else wt.shifted@aligned <- FALSE return(wt.shifted) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/align.R
setClass("wt.filter", representation(L="integer", level="integer", h="numeric", g="numeric", wt.class="character", wt.name="character", transform="character")) setClass("dwt", representation(W="list", V="list", filter="wt.filter", level="integer", n.boundary="numeric", boundary="character", series="matrix", class.X="character", attr.X="list", aligned="logical", coe = "logical")) setClass("modwt", representation(W="list", V="list", filter="wt.filter", level="integer", n.boundary="numeric", boundary="character", series="matrix", class.X="character", attr.X="list", aligned="logical", coe = "logical")) setClass("mra", representation(D="list", S="list", filter="wt.filter", level="integer", boundary="character", series="matrix", class.X="character", attr.X="list", method="character")) #setMethod("plot", signature=(x="x", y="missing"), plot.dwt) #setMethod("print", signature(x="dwt"), function(x,...) print.dwt(x,...)) #UseMethod("print", dwt)
/scratch/gouwar.j/cran-all/cranData/wavelets/R/classdef.R
dwt <- function(X, filter="la8", n.levels, boundary="periodic", fast=TRUE){ # error checking if(is.na(match(class(X)[1], c("numeric", "ts", "mts", "matrix", "data.frame")))) stop("Invalid argument: 'X' must be of class 'numeric','ts', 'mts', 'matrix', or 'data.frame'.") if(is.na(match(class(filter), c("character", "wt.filter", "numeric", "integer")))) stop("Invalid argument: 'filter' must be of class 'character','wt.filter','numeric', or 'integer'.") if(class(filter) == "wt.filter"){ if(filter@transform == "modwt") stop("Invalid argument: 'transform' element of agrument 'filter' must be equal to 'dwt'.") } if(is.na(match(boundary, c("periodic","reflection")))) stop("Invalid argument value for 'boundary'") if(!is.null(dim(X))){ if(dim(X)[1] == 1){ stop("Unacceptable dimensions: number of observations for columns of X must be greater than 1.") } } # get wavelet coeficients and length if(class(filter) == "character" | class(filter) == "numeric" | class(filter) == "integer") filter <- wt.filter(filter) L <- filter@L # convert X to a matrix class.X <- class(X)[1] attr.X <- attributes(X) if(is.null(attr.X)) attr.X <- list() if(class.X == "mts") attributes(X)[3:4] <- NULL else X <- matrix(X) dim.X <- dim(X) N <- dim(X)[1] n.series <- dim(X)[2] # determine the level of decomposition if(missing(n.levels)) J <- as.integer(floor(log(((N-1)/(L-1))+1)/log(2))) else if(!is.numeric(n.levels) | (round(n.levels) != n.levels)) stop("Invalid argument value: 'n.levels' must be an integer value") else if(n.levels > log(N)/log(2)) stop(paste("Invalid argument value: 'n.levels' cannot be greater than ", floor(log(N)/log(2)), sep="")) else J <- as.integer(n.levels) # reflect X for reflection method if(boundary == "reflection"){ X <- extend.series(X) N <- 2*N } # initialize variables for pyramid algorithm Vj <- X n.boundary <- rep(NA, J) W.coefs <- as.list(rep(NA, length=J)) names(W.coefs) <- lapply(1:J, function(j, x){names(x)[j] <- paste("W",j,sep="")}, x=W.coefs) V.coefs <- as.list(rep(NA, length=J)) names(V.coefs) <- lapply(1:J, function(j, x){names(x)[j] <- paste("V",j,sep="")}, x=V.coefs) # implement the pyramid algorithm for(j in 1:J){ if(round(dim(Vj)[1]/2) != dim(Vj)[1]/2){ Vj <- Vj[-1,] if(class(Vj) == "numeric") Vj <- as.matrix(Vj) } if(fast){ Wout <- Vout <- rep(0, length=dim(Vj)[1]/2) analysis <- sapply(1:n.series, function(i,v,f,Wout,Vout){ out <- .C("dwt_forward", as.double(v[,i]), as.integer(length(v[,i])), as.double(f@h), as.double(f@g), as.integer(f@L), as.double(Wout), as.double(Vout), PACKAGE="wavelets") return(c(out[[6]],out[[7]])) }, v=Vj, f=filter, Wout=Wout, Vout=Vout) } else { analysis <- sapply(1:n.series, function(i,v,f){ out <- dwt.forward(v[,i],f) return(c(out$W,out$V)) }, v=Vj, f=filter) } Wj <- matrix(analysis[1:(N/(2^j)),], ncol=n.series) Vj <- matrix(analysis[(N/(2^j)+1):(N/(2^(j-1))),], ncol=n.series) W.coefs[[j]] <- Wj V.coefs[[j]] <- Vj Lj <- ceiling((L-2)*(1-(1/(2^j)))) Nj <- N/(2^j) n.boundary[j] <- min(Lj,Nj) } # create dwt object for ouput dwt <- new("dwt", W = W.coefs, V = V.coefs, filter = filter, level = J, n.boundary = n.boundary, boundary = boundary, series = X, class.X = class.X, attr.X = attr.X, aligned = FALSE, coe = FALSE) return(dwt) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/dwt.R
dwt.backward <- function(W, V, filter){ # error checking if(class(W) != "numeric") stop("Invalid argument: 'W' must be of class 'numeric' or 'matrix'.") if(class(V) != "numeric") stop("Invalid argument: 'V' must be of class 'numeric' or 'matrix'.") if(class(filter) != "wt.filter") stop("Invalid argument: 'filter' must be of class 'wt.filter'.") if(filter@transform == "modwt") stop("Invalid argument: 'transform' element of agrument 'filter' must be equal to 'dwt'.") M <- length(V) h <- filter@h g <- filter@g L <- length(h) Vj <- rep(NA, length=2*M) l <- -2 m <- -1 for(t in 0:(M-1)){ l <- l+2 m <- m+2 u <- t i <- 1 k <- 0 Vj[l+1] <- h[i+1]*W[u+1] + g[i+1]*V[u+1] Vj[m+1] <- h[k+1]*W[u+1] + g[k+1]*V[u+1] if(L > 2){ for(n in 1:((L/2)-1)){ u <- u+1 if(u >= M) u <- 0 i <- i+2 k <- k+2 Vj[l+1] <- Vj[l+1] + h[i+1]*W[u+1] + g[i+1]*V[u+1] Vj[m+1] <- Vj[m+1] + h[k+1]*W[u+1] + g[k+1]*V[u+1] } } } return(Vj) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/dwt.backward.R
dwt.forward <- function(V, filter){ # error checking if(class(V) != "numeric") stop("Invalid argument: 'V' must be of class 'numeric' or 'matrix'.") if(class(filter) != "wt.filter") stop("Invalid argument: 'filter' must be of class 'wt.filter'.") if(filter@transform == "modwt") stop("Invalid argument: 'transform' element of agrument 'filter' must be equal to 'dwt'.") h <- filter@h g <- filter@g L <- filter@L M <- length(V) Wj <- rep(NA, length=(M/2)) Vj <- rep(NA, length=(M/2)) for(t in 0:(M/2 - 1)){ u <- 2*t + 1 Wjt <- h[1]*V[u+1] Vjt <- g[1]*V[u+1] for(n in 1:(L-1)){ u <- u - 1 if(u < 0) u <- M - 1 Wjt <- Wjt + h[n+1]*V[u+1] Vjt <- Vjt + g[n+1]*V[u+1] } Wj[t+1] <- Wjt Vj[t+1] <- Vjt } results <- list(W = Wj, V = Vj) return(results) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/dwt.forward.R
extend.series <- function(X, method="reflection", length="double", n, j){ # error checking if(is.na(match(class(X)[1], c("numeric", "ts", "matrix", "data.frame")))) stop("Invalid argument: 'X' must be of class 'numeric','ts', 'matrix', or 'data.frame'.") if(is.na(match(method, c("periodic","reflection","zeros","mean","reflection.inverse")))) stop("Invalid argument value for 'method'") if(is.na(match(length, c("arbitrary","powerof2","double")))) stop("Invalid argument value for 'length'") if(length == "arbitrary"){ if(missing(n)) stop("Unspecified argument: argument 'n' must be specified when length='arbitrary'.") else if(round(n) != n) stop("Invalid argument: 'n' must be an integer value.") } if(length == "powerof2"){ if(missing(j)) stop("Unspecified argument: argument 'j' must be specified when length='powerof2'.") if(round(j) != j) stop("Invalid argument: 'j' must be an integer value.") } # store the old class for output class.X <- class(X)[1] if(class.X != "matrix"){ attr.X <- attributes(X) X <- as.matrix(X) } dim.X <- dim(X) if((dim.X[1] == 1) & (dim.X[2] > 1)){ X <- t(X) N <- dim.X[2] } else N <- dim.X[1] # determine final length 'n' of series after extension if(length == "arbitrary"){ if(n <= N) stop("Invalid argument: 'n' must be greater than length of series when length='arbitrary'.") } else if(length == "powerof2"){ k <- N/(2^j) if(round(k) == k) stop("Invalid argument: length of series should not be multiple of 2^j when length='powerof2'.") else n <- ceiling(k)*2^j } else if(length == "double") n <- 2*N # extend the series to length 'n' if(method == "periodic") X <- apply(X, 2, rep, length=n) if(method == "reflection") X <- apply(X, 2, function(x,n){rep(c(x,rev(x)),length=n)}, n=n) if(method == "zeros") X <- apply(X, 2, function(x,n){c(x,rep(0,length=n-N))}, n=n) if(method == "mean") X <- apply(X, 2, function(x,n){c(x,rep(mean(x),length=n-N))}, n=n) if(method == "reflection.inverse") X <- apply(X, 2, function(x,n,N){rep(c(x,2*x[N]-rev(x)),length=n)}, n=n, N=N) # return X in orginal form if(class.X != "matrix"){ if(class.X == "data.frame") X <- as.data.frame(X) attributes(X) <- attr.X } return(X) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/extend.series.R
figure108.wt.filter <- function(filter.objects, level = 1, l = NULL, wavelet = TRUE) { draw.leftlabels <- function(y.llabs, left.usrlabelpos) { for (i in 1:length(y.llabs)) { text(left.usrlabelpos, (length(list.filter)-i)*rangeperplot, y.llabs[[i]], xpd = TRUE, cex = .7) } } if(class(filter.objects) != "list") { if(class(filter.objects) == "wt.filter") { if([email protected] != "none") { filter.objects <- wt.filter([email protected], level = level) } else { filter.objects <- wt.filter(filter.objects@h, level = level) } } if(class(filter.objects) == "character") { filter.objects <- wt.filter(tolower(filter.objects), level = level) } if(class(filter.objects) == "numeric") { filter.objects <- wt.filter(filter.objects, level = level) } filter.objects <- list(filter.objects) } for(i in 1:length(filter.objects)) { if(class(filter.objects[[i]]) == "numeric") { filter.objects[[i]] <- wt.filter(filter.objects[[i]]) } if(class(filter.objects[[i]]) == "character") { filter.objects[[i]] <- wt.filter(tolower(filter.objects[[i]])) } if(class(filter.objects[[i]]) != "wt.filter") { stop("Invalid argument: Every element of filter.objects must be of class 'numeric','character', or 'wt.filter'.") } } if(wavelet == TRUE) { list.filter <- list(filter.objects[[1]]@h) if(length(filter.objects) != 1) { for(i in 2:length(filter.objects)) { list.filter <- c(list.filter, list(filter.objects[[i]]@h)) } } } else { list.filter <- list(filter.objects[[1]]@g) if(length(filter.objects) != 1) { for(i in 2:length(filter.objects)) { list.filter <- c(list.filter, list(filter.objects[[i]]@g)) } } } if(is.null(l) == TRUE) { l <- 0:(length(list.filter[[1]]) - 1) if(length(list.filter) != 1) { for(i in 2:length(list.filter)) { if(max(l) < length(list.filter[[i]])) { l <- 0:(length(list.filter[[i]]) - 1) } } } } else { if(class(l) == "numeric" && length(l) > 1) { l <- max(l) } l <- 0:l for(i in 1:length(list.filter)) { if(max(l) < length(list.filter[[i]])) { l <- 0:(length(list.filter[[i]]) - 1) } } } for(i in 1:length(list.filter)) { if(max(l) > (length(list.filter[[i]]) - 1)) { add.NA <- rep(NA, times = max(l) - (length(list.filter[[i]]) - 1)) list.filter[[i]] <- c(list.filter[[i]], add.NA) } } min.list <- 0 max.list <- 0 for(i in 1:length(list.filter)) { if(min.list > min(list.filter[[i]], na.rm = TRUE)) { min.list <- min(list.filter[[i]], na.rm = TRUE) } } for(i in 1:length(list.filter)) { if(max.list < max(list.filter[[i]], na.rm = TRUE)) { max.list <- max(list.filter[[i]], na.rm = TRUE) } } plotarray <- 1:length(levels) if(abs(max.list) >= abs(min.list)) { rangeperplot <- 2*max.list } else { rangeperplot <- 2*min.list } jstartline <- min.list totalrange <- length(list.filter)*(rangeperplot) for(j in plotarray) { jstartline <- jstartline + rangeperplot plotarray[j] <- jstartline } plot(1, 1, type = "n", xlim = c(0, max(l)), ylim = c(min.list, totalrange + min.list), axes = FALSE, frame.plot = TRUE, xlab = "", ylab = "") axis(1) for(i in 1:length(list.filter)) { par(new = TRUE) shifty1 <- (length(list.filter)-i)*rangeperplot shifty2 <- (length(list.filter)-i)*rangeperplot + list.filter[[i]] abline(h = shifty1, lty = 1) segments(l, shifty1, l, shifty2) points(l, shifty2, pch = 15) } y.llabs <- rep(NA, times = length(filter.objects)) for(i in 1:length(filter.objects)) { if(filter.objects[[i]]@wt.name == "haar") { y.llabs[i] <- "Haar" } else { y.llabs[i] <- toupper(filter.objects[[i]]@wt.name) } } draw.leftlabels(y.llabs, par()$usr[1] - abs(par()$usr[1])) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/figure108.wt.filter.R
figure98.wt.filter <- function(filter, levels = NULL, wavelet = TRUE, y.normalize = TRUE) { draw.leftlabels <- function(y.llabs, left.usrlabelpos) { for (i in 1:length(y.llabs)) { text(left.usrlabelpos, (length(list.filter)-i)*rangeperplot + abs(min.list), y.llabs[[i]], xpd = TRUE) } } if(is.null(levels) == TRUE) { levels <- 1:7 } if(class(levels) == "numeric" && length(levels) == 1) { levels <- 1:levels } if(class(filter) == "numeric") { if(length(filter)%%2 != 0) { stop("Invalid argument: filter length must be even.") } filter.name <- "" } if(class(filter) == "character") { if(tolower(filter) != "haar") { filter.name <- toupper(filter) } else { filter.name <- "Haar" } filter <- tolower(filter) } if(class(filter) == "wt.filter") { filter.name <- toupper([email protected]) filter <- filter@h } if(wavelet == TRUE) { list.filter <- list(wt.filter(filter, level = levels[1])@h) if(length(levels) != 1) { for(i in 2:length(levels)) { list.filter <- c(list.filter, list(wt.filter(filter, level = levels[i])@h)) } } } else { list.filter <- list(wt.filter(filter, level = levels[1])@g) if(length(levels) != 1) { for(i in 2:length(levels)) { list.filter <- c(list.filter, list(wt.filter(filter, level = levels[i])@g)) } } } min.list <- 0 max.list <- 0 for(i in 1:length(list.filter)) { if(min.list > min(list.filter[[i]])) { min.list <- min(list.filter[[i]]) } } for(i in 1:length(list.filter)) { if(max.list < max(list.filter[[i]])) { max.list <- max(list.filter[[i]]) } } plotarray <- 1:length(levels) rangeperplot <- 2*max.list jstartline <- min.list totalrange <- length(list.filter)*(rangeperplot) if(y.normalize == TRUE) { for(i in 1:length(list.filter)) { if(max.list - abs(max(list.filter[[i]])) < max.list - abs(min(list.filter[[i]]))) { scale <- max.list/abs(max(list.filter[[i]])) } else { scale <- max.list/abs(min(list.filter[[i]])) } list.filter[[i]] <- list.filter[[i]]*scale } } for(j in plotarray) { jstartline <- jstartline + rangeperplot plotarray[j] <- jstartline } plot(0, 0, type = "n", xlim = c(0, length(list.filter[[1]])-1), ylim = c(min.list, totalrange), axes = FALSE, frame.plot = TRUE, xlab = "l", ylab = "j") for(i in 1:length(list.filter)) { par(new = TRUE) plot(0, 0, type = "n", xlim = c(0, length(list.filter[[i]])-1), ylim = c(min.list, totalrange), axes = FALSE, frame.plot = TRUE, xlab = "", ylab = "") par(xaxp = c(0,length(list.filter[[i]])-1,1)) axis(1, at = axTicks(1), labels = c(0, expression(L[j]-1))) shifty <- (length(list.filter)-i)*rangeperplot + abs(min.list) lines(0:(length(list.filter[[i]])-1), shifty + list.filter[[i]], type = "l") abline(h = shifty, lty = 2) } y.llabs <- as.character(levels) draw.leftlabels(y.llabs, par()$usr[1] - abs(par()$usr[1])) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/figure98.wt.filter.R
idwt <- function(wt, fast=TRUE){ # error checking if(class(wt) != "dwt") stop("Incorrect argument: wt must be an object of class 'dwt'.") # unalign if wt is aligned if(wt@aligned) wt <- align(wt, coe=wt@coe, inverse = TRUE) # setup for inverse pyramid algorithm filter <- wt@filter J <- length(wt@W) Vj <- wt@V[[J]] N <- dim(wt@series)[1] n.series <- dim(wt@W[[1]])[2] # implement inverse pyramid algorithm for(j in J:1){ Wj <- wt@W[[j]] Mj <- N/(2^j) if(fast){ Vout <- rep(0, length=2*Mj) Vj <- sapply(1:n.series, function(i,w,v,f,M,Vout){ out <- .C("dwt_backward", as.double(w[,i]), as.double(v[,i]), as.integer(M), as.double(f@h), as.double(f@g), as.integer(f@L), as.double(Vout), PACKAGE="wavelets") return(out[[7]]) }, w=Wj, v=Vj, f=filter, M=Mj, Vout=Vout) } else { Vj <- sapply(1:n.series, function(i,w,v,f){ return(out <- dwt.backward(w[,i],v[,i],f)) }, w=Wj, v=Vj, f=filter) } } # construct the time series in its original format for output X <- round(Vj,5) if(wt@boundary == "reflection") X <- X[1:(dim(X)[1]/2),] if([email protected] == "mts"){ attributes(X) <- [email protected] } else if([email protected] == "data.frame"){ X <- as.data.frame(X) attributes(X) <- [email protected] } else { attributes(X) <- [email protected] class(X) <- [email protected] } if([email protected] == "numeric") attributes(X) <- NULL return(X) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/idwt.R
imodwt <- function(wt, fast=TRUE){ # error checking if(class(wt) != "modwt") stop("Incorrect argument: wt must be an object of class 'modwt'.") # unalign if wt is aligned if(wt@aligned) wt <- align(wt, coe=wt@coe, inverse = TRUE) # setup for inverse pyramid algorithm filter <- wt@filter J <- length(wt@W) Vj <- wt@V[[J]] n.series <- dim(wt@W[[1]])[2] # implement inverse pyramid algorithm for(j in J:1){ Wj <- wt@W[[j]] if(fast){ Vout <- rep(0, length=dim(Vj)[1]) Vj <- sapply(1:n.series, function(i,w,v,f,j,Vout){ out <- .C("modwt_backward", as.double(w[,i]), as.double(v[,i]), as.integer(j), as.integer(length(w[,i])), as.double(f@h), as.double(f@g), as.integer(f@L), as.double(Vout), PACKAGE="wavelets") return(out[[8]]) }, w=Wj, v=Vj, f=filter, j=j, Vout=Vout) } else { Vj <- sapply(1:n.series, function(i,w,v,f,j){ return(out <- modwt.backward(w[,i],v[,i],f,j)) }, w=Wj, v=Vj, f=filter, j=j) } } # construct the time series in its original format for output X <- round(Vj,5) if(wt@boundary == "reflection") X <- X[1:(dim(X)[1]/2),] if([email protected] == "mts"){ attributes(X) <- [email protected] } else if([email protected] == "data.frame"){ X <- as.data.frame(X) attributes(X) <- [email protected] } else { attributes(X) <- [email protected] class(X) <- [email protected] } if([email protected] == "numeric") attributes(X) <- NULL return(X) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/imodwt.R
modwt <- function(X, filter="la8", n.levels, boundary="periodic", fast=TRUE){ # error checking if(is.na(match(class(X)[1], c("numeric", "ts", "mts", "matrix", "data.frame")))) stop("Invalid argument: 'X' must be of class 'numeric','ts', 'mts', 'matrix', or 'data.frame'.") if(is.na(match(class(filter), c("character", "wt.filter", "numeric", "integer")))) stop("Invalid argument: 'filter' must be of class 'character','wt.filter','numeric', or 'integer'.") if(class(filter) == "wt.filter"){ if(filter@transform == "dwt") stop("Invalid argument: 'transform' element of agrument 'filter' must be equal to 'modwt'.") } if(is.na(match(boundary, c("periodic","reflection")))) stop("Invalid argument value for 'boundary'") if(!is.null(dim(X))){ if(dim(X)[1] == 1){ stop("Unacceptable dimensions: number of observations for columns of X must be greater than 1.") } } # get wavelet coeficients and length if(class(filter) == "character" | class(filter) == "numeric" | class(filter) == "integer") filter <- wt.filter(filter, modwt=TRUE) L <- filter@L # convert X to a matrix class.X <- class(X)[1] attr.X <- attributes(X) if(is.null(attr.X)) attr.X <- list() if(class.X == "mts") attributes(X)[3:4] <- NULL else X <- as.matrix(X) dim.X <- dim(X) N <- dim(X)[1] n.series <- dim(X)[2] # determine the level of decomposition if(missing(n.levels)){ J <- as.integer(floor(log(((N-1)/(L-1))+1)/log(2))) } else if(!is.numeric(n.levels) | (round(n.levels) != n.levels)){ stop("Invalid argument value: 'n.levels' must be an integer value") } else J <- as.integer(n.levels) # reflect X for reflection method if(boundary == "reflection"){ X <- extend.series(X) N <- 2*N } # initialize variables for pyramid algorithm Vj <- X n.boundary <- rep(NA, J) W.coefs <- as.list(rep(NA, length=J)) names(W.coefs) <- lapply(1:J, function(j, x){names(x)[j] <- paste("W",j,sep="")}, x=W.coefs) V.coefs <- as.list(rep(NA, length=J)) names(V.coefs) <- lapply(1:J, function(j, x){names(x)[j] <- paste("V",j,sep="")}, x=V.coefs) # implement the pyramid algorithm for(j in 1:J){ if(fast){ Wout <- Vout <- rep(0, length=dim(Vj)[1]) analysis <- sapply(1:n.series, function(i,v,f,j,Wout,Vout){ out <- .C("modwt_forward", as.double(v[,i]), as.integer(length(v[,i])), as.integer(j), as.double(f@h), as.double(f@g), as.integer(f@L), as.double(Wout), as.double(Vout), PACKAGE="wavelets") return(c(out[[7]],out[[8]])) }, v=Vj, f=filter, j=j, Wout=Wout, Vout=Vout) } else { analysis <- sapply(1:n.series, function(i,v,f,j){ out <- modwt.forward(v[,i],f,j) return(c(out$W,out$V)) }, v=Vj, f=filter, j=j) } Wj <- matrix(analysis[1:N,], ncol=n.series) Vj <- matrix(analysis[(N+1):(2*N),], ncol=n.series) W.coefs[[j]] <- Wj V.coefs[[j]] <- Vj Lj <- (2^j-1)*(L-1)+1 n.boundary[j] <- min(Lj,N) } # creat modwt object for ouput modwt <- new("modwt", W = W.coefs, V = V.coefs, filter = filter, level = J, n.boundary = n.boundary, boundary = boundary, series = X, class.X = class.X, attr.X = attr.X, aligned = FALSE, coe = FALSE) return(modwt) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/modwt.R
modwt.backward <- function(W, V, filter, j){ # error checking if(class(W) != "numeric") stop("Invalid argument: 'W' must be of class 'numeric' or 'matrix'.") if(class(V) != "numeric") stop("Invalid argument: 'V' must be of class 'numeric' or 'matrix'.") if(class(filter) != "wt.filter") stop("Invalid argument: 'filter' must be of class 'wt.filter'.") if(filter@transform == "dwt") stop("Invalid argument: 'transform' element of agrument 'filter' must be equal to 'modwt'.") if(is.na(match(class(j), c("numeric", "integer")))) stop("Invalid argument: 'j' must be of class 'numeric' or 'integer'.") if(length(j) != 1) stop("Invalid argument: 'j' must have length 1.") N <- length(V) h <- filter@h g <- filter@g L <- length(h) Vj <- rep(NA, length=N) for(t in 0:(N-1)){ k <- t Vjt <- h[1]*W[k+1] + g[1]*V[k+1] for(n in 1:(L-1)){ k <- k + 2^(j-1) if(k >= N) k <- k - floor(k/N)*N Vjt <- Vjt + h[n+1]*W[k+1] + g[n+1]*V[k+1] } Vj[t+1] <- Vjt } return(Vj) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/modwt.backward.R
modwt.forward <- function(V, filter, j){ # error checking if(class(V) != "numeric") stop("Invalid argument: 'V' must be of class 'numeric' or 'matrix'.") if(class(filter) != "wt.filter") stop("Invalid argument: 'filter' must be of class 'wt.filter'.") if(filter@transform == "dwt") stop("Invalid argument: 'transform' element of agrument 'filter' must be equal to 'modwt'.") if(is.na(match(class(j), c("numeric", "integer")))) stop("Invalid argument: 'j' must be of class 'numeric' or 'integer'.") if(length(j) != 1) stop("Invalid argument: 'j' must have length 1.") N <- length(V) h <- filter@h g <- filter@g L <- filter@L Wj <- rep(NA, length=N) Vj <- rep(NA, length=N) for(t in 0:(N-1)){ k <- t Wjt <- h[1]*V[k+1] Vjt <- g[1]*V[k+1] for(n in 1:(L-1)){ k <- k - 2^(j-1) if(k < 0) k <- k + ceiling(-k/N)*N Wjt <- Wjt + h[n+1]*V[k+1] Vjt <- Vjt + g[n+1]*V[k+1] } Wj[t+1] <- Wjt Vj[t+1] <- Vjt } results <- list(W = Wj, V = Vj) return(results) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/modwt.forward.R
mra <- function(X, filter="la8", n.levels, boundary="periodic", fast=TRUE, method="dwt"){ # error checking if(is.na(match(method, c("dwt","modwt")))) stop("Invalid argument value for 'method'") # initializations J <- n.levels details <- as.list(rep(NA, length=J)) names(details) <- lapply(1:J, function(j, x){names(x)[j] <- paste("D",j,sep="")}, x=details) smooths <- as.list(rep(NA, length=J)) names(smooths) <- lapply(1:J, function(j, x){names(x)[j] <- paste("S",j,sep="")}, x=smooths) # compute wavelet transform and other necessary values if(method == "dwt"){ wt <- dwt(X, filter, n.levels, boundary, fast) } else wt <- modwt(X, filter, n.levels, boundary, fast) filter <- wt@filter n.series <- dim(wt@W[[1]])[2] N <- dim(wt@series)[1] # compute the details and smooths for(j in 1:J){ Wj <- wt@W[[j]] Vj <- wt@V[[j]] DWj <- Wj SWj <- matrix(rep(0, length=length(Wj)), ncol=n.series) DVj <- matrix(rep(0, length=length(Wj)), ncol=n.series) SVj <- Vj # compute the details and smooths for level j for(k in j:1){ if(fast){ if(method == "dwt"){ Vout <- rep(0, length=2*dim(DWj)[1]) DVj <- sapply(1:n.series, function(i,w,v,f,Vout){ return(.C("dwt_backward", as.double(w[,i]), as.double(v[,i]), as.integer(length(w[,i])), as.double(f@h), as.double(f@g), as.integer(f@L), as.double(Vout), PACKAGE="wavelets")[[7]]) }, w=DWj, v=DVj, f=filter, Vout=Vout) SVj <- sapply(1:n.series, function(i,w,v,f,Vout){ return(.C("dwt_backward", as.double(w[,i]), as.double(v[,i]), as.integer(length(v[,i])), as.double(f@h), as.double(f@g), as.integer(f@L), as.double(Vout), PACKAGE="wavelets")[[7]]) }, w=SWj, v=SVj, f=filter, Vout=Vout) } else { Vout <- rep(0, length=dim(DWj)[1]) DVj <- sapply(1:n.series, function(i,w,v,f,k,Vout){ return(.C("modwt_backward", as.double(w[,i]), as.double(v[,i]), as.integer(k), as.integer(length(w[,i])), as.double(f@h), as.double(f@g), as.integer(f@L), as.double(Vout), PACKAGE="wavelets")[[8]]) }, w=DWj, v=DVj, f=filter, k=k, Vout=Vout) SVj <- sapply(1:n.series, function(i,w,v,f,k,Vout){ return(.C("modwt_backward", as.double(w[,i]), as.double(v[,i]), as.integer(k), as.integer(length(v[,i])), as.double(f@h), as.double(f@g), as.integer(f@L), as.double(Vout), PACKAGE="wavelets")[[8]]) }, w=SWj, v=SVj, f=filter, k=k, Vout=Vout) } } else { if(method == "dwt"){ DVj <- sapply(1:n.series, function(i,w,v,f){ return(out <- dwt.backward(w[,i],v[,i],f)) }, w=DWj, v=DVj, f=filter) SVj <- sapply(1:n.series, function(i,w,v,f){ return(out <- dwt.backward(w[,i],v[,i],f)) }, w=SWj, v=SVj, f=filter) } else { DVj <- sapply(1:n.series, function(i,w,v,f,k){ return(out <- modwt.backward(w[,i],v[,i],f,k)) }, w=DWj, v=DVj, f=filter, k=k) SVj <- sapply(1:n.series, function(i,w,v,f,k){ return(out <- modwt.backward(w[,i],v[,i],f,k)) }, w=SWj, v=SVj, f=filter, k=k) } } DWj <- matrix(rep(0, length=length(DVj)), ncol=n.series) SWj <- DWj } details[[j]] <- DVj smooths[[j]] <- SVj } # create mra object for output mra <- new("mra", D = details, S = smooths, filter = filter, level = as.integer(J), boundary = boundary, series = wt@series, class.X = [email protected], attr.X = [email protected], method = method) return(mra) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/mra.R
plot.dwt <- function (x, levels = NULL, draw.boundary = FALSE, type = "stack", col.plot = "black", col.boundary = "red", X.xtick.at = NULL, X.ytick.at = NULL, Stack.xtick.at = NULL, Stack.ytick.at = NULL, X.xlab = "t", y.rlabs = TRUE, plot.X = TRUE, plot.W = TRUE, plot.V = TRUE, ...) { stackplot.dwt <- function ( x , w.range, v.range, col.plot, col.boundary, draw.boundary = FALSE, X.xtick.at = NULL, X.ytick.at = NULL, Stack.xtick.at = NULL, Stack.ytick.at = NULL, X.xlab = "t", plot.X = TRUE) { innerplot <- function(x, y, type = "l", xtick.at, ytick.at) { if(is.null(xtick.at) == FALSE || is.null(ytick.at) == FALSE) { plot(x, y, type = "l", axes = FALSE, frame.plot = TRUE) if(is.null(xtick.at) == FALSE) { axis(1, at = axTicks(1, xtick.at)) xtickrate <- xtick.at } else { axis(1) xtickrate <- par("xaxp") } if(is.null(ytick.at) == FALSE) { axis(2, at = axTicks(2, ytick.at)) ytickrate <- ytick.at } else { axis(2) ytickrate <- par("yaxp") } } else { plot(x, y, type = "l") xtickrate <- par("xaxp") ytickrate <- par("yaxp") } tickrate <- list(xtick = xtickrate, ytick = ytickrate) tickrate } if(plot.X) { nf <- layout(matrix(c(2,2,1,1), 2, 2, byrow=TRUE), c(1,2), c(2,1), TRUE) par(mai = c(.6, .4, .1, .6)) if( x @class.X == "ts" || x @class.X == "mts") { x.range <- x @attr.X$tsp[1]: x @attr.X$tsp[2] } else{ x.range <- 1:dim( x @series)[1] } tickrate <- innerplot(x.range, x @series[,1], type = "l", X.xtick.at, X.ytick.at) right.usrplotrange <- par()$usr[2] - par()$usr[1] NDCplotrange <- par()$plt[2] - par()$plt[1] marginpos <- (1-par()$plt[2])/2 right.usrlabelpos <- ((marginpos*right.usrplotrange)/NDCplotrange) + par()$usr[2] text(right.usrlabelpos, 0, "X", xpd = TRUE) mtext(X.xlab, side = 1, line = 2) par(mai = c(0, .4, .1, .6)) } if(plot.X == FALSE) { par(mai = c(.4, .4, .1, .6)) if(is.null(Stack.xtick.at) == FALSE) { xtickrate <- Stack.xtick.at } else { xtickrate <- NULL } if(is.null(Stack.ytick.at) == FALSE) { ytickrate <- Stack.ytick.at } else { ytickrate <- NULL } tickrate <- list(xtick = xtickrate, ytick = ytickrate) } if (draw.boundary) { matrixlist <- list(dwt = as.matrix.dwt( x , w.range, v.range), posbound = boundary.as.matrix.dwt( x , w.range, v.range, positive = TRUE), negbound = boundary.as.matrix.dwt( x , w.range, v.range, positive = FALSE)) col <- c(col.plot, col.boundary, col.boundary) } else { matrixlist <- list(dwt = as.matrix.dwt( x , w.range, v.range)) col <- col.plot } if(is.null(w.range) == FALSE) { gammawave <- wt.filter.shift( x @filter, w.range, wavelet = TRUE) } if(is.null(v.range) == FALSE) { gammascale <- wt.filter.shift( x @filter, v.range, wavelet = FALSE) } if(y.rlabs) { rightlabels <- labels.dwt(w.range = w.range, v.range = v.range, gammah = gammawave, gammag = gammascale) } else { rightlabels <- NULL } stackplot(matrixlist, y = NULL, y.rlabs = rightlabels, col = col, xtick.at = tickrate$xtick, ytick.at = tickrate$ytick) } boundary.as.matrix.dwt <- function( x , w.range, v.range, positive = TRUE) { Lprimej <- x @n.boundary if(is.null(w.range) == FALSE) { wavecoefmatrix <- array(NA, c(2*dim( x @series)[1], length(w.range))) Wjplot <- rep(NA, 2*dim( x @series)[1]) wavecoefmatrix.index <- 0 for (j in w.range) { wavecoefmatrix.index <- wavecoefmatrix.index + 1 levelshift <- waveletshift.dwt( x @filter@L, j, dim( x @series)[1])%%(2^j) rightgamma <- wt.filter.shift( x @filter, j, wavelet = TRUE) leftgamma <- Lprimej[j] - rightgamma if(positive) { boundaryheight <- max( x @W[[j]]) } else { boundaryheight <- min( x @W[[j]]) } if(leftgamma != 0) { leftboundarypos <- leftgamma*(2^j) + .5*(2^j) - levelshift } else { leftboundarypos <- 0 } if(rightgamma != 0) { rightboundarypos <- dim( x @series)[1] - rightgamma*(2^j) + .5*(2^j) - levelshift } else { rightboundarypos <- 0 } if(leftboundarypos != 0 && rightboundarypos != 0) { leftspace <- rep(NA, 2*leftboundarypos - 1) middlespace <- rep(NA, 2*(rightboundarypos - leftboundarypos) - 1) rightspace <- rep(NA, 2*(dim( x @series)[1] - rightboundarypos)) Wjplot <- c(leftspace, boundaryheight, middlespace, boundaryheight, rightspace) } if(leftboundarypos == 0 && rightboundarypos != 0) { middlespace <- rep(NA, 2*rightboundarypos - 1) rightspace <- rep(NA, 2*(dim( x @series)[1] - rightboundarypos)) Wjplot <- c(middlespace, boundaryheight, rightspace) } if(leftboundarypos != 0 && rightboundarypos == 0) { leftspace <- rep(NA, 2*leftboundarypos - 1) middlespace <- rep(NA, 2*(dim( x @series)[1] - leftboundarypos)) Wjplot <- c(leftspace, boundaryheight, middlespace) } wavecoefmatrix[,wavecoefmatrix.index] <- Wjplot } } if(is.null(v.range) == FALSE) { scalecoefmatrix <- array(NA, c(2*dim( x @series)[1], length(v.range))) Vjplot <- rep(NA, 2*dim( x @series)[1]) scalecoefmatrix.index <- 0 for(j in v.range) { scalecoefmatrix.index <- scalecoefmatrix.index + 1 levelshift <- scalingshift.dwt( x @filter@L, j, dim( x @series)[1])%%(2^j) rightgamma <- wt.filter.shift( x @filter, j, wavelet = FALSE) leftgamma <- Lprimej[j] - rightgamma Vj <- x @V[[j]][,1] - mean( x @V[[j]][,1]) if(positive) { boundaryheight <- max(Vj) } else { boundaryheight <- min(Vj) } if(leftgamma != 0) { leftboundarypos <- leftgamma*(2^j) + .5*(2^j) - levelshift } else { leftboundarypos <- 0 } if(rightgamma != 0) { rightboundarypos <- dim( x @series)[1] - rightgamma*(2^j) + .5*(2^j) - levelshift } else { rightboundarypos <- 0 } if(leftboundarypos != 0 && rightboundarypos != 0) { leftspace <- rep(NA, 2*leftboundarypos - 1) middlespace <- rep(NA, 2*(rightboundarypos - leftboundarypos) - 1) rightspace <- rep(NA, 2*(dim( x @series)[1] - rightboundarypos)) Vjplot <- c(leftspace, boundaryheight, middlespace, boundaryheight, rightspace) } if(leftboundarypos == 0 && rightboundarypos != 0) { middlespace <- rep(NA, 2*rightboundarypos - 1) rightspace <- rep(NA, 2*(dim( x @series)[1] - rightboundarypos)) Vjplot <- c(middlespace, boundaryheight, rightspace) } if(leftboundarypos != 0 && rightboundarypos == 0) { leftspace <- rep(NA, 2*leftboundarypos - 1) rightspace <- rep(NA, 2*(dim( x @series)[1] - leftboundarypos)) Vjplot <- c(leftspace, boundaryheight, rightspace) } scalecoefmatrix[,scalecoefmatrix.index] <- Vjplot } } if(is.null(w.range) == FALSE && is.null(v.range) == FALSE) { if( x @class.X == "ts" || x @class.X == "mts") { rownames(wavecoefmatrix) <- seq( x @attr.X$tsp[1]-.5, x @attr.X$tsp[2], by = .5) rownames(scalecoefmatrix) <- seq( x @attr.X$tsp[1]-.5, x @attr.X$tsp[2], by = .5) } else { rownames(wavecoefmatrix) <- seq(.5, dim( x @series)[1], by = .5) rownames(scalecoefmatrix) <- seq(.5, dim( x @series)[1], by = .5) } results <- cbind(wavecoefmatrix, scalecoefmatrix) } if(!is.null(w.range) && is.null(v.range)) { if( x @class.X == "ts" || x @class.X == "mts") { rownames(wavecoefmatrix) <- seq( x @attr.X$tsp[1]-.5, x @attr.X$tsp[2], by = .5) } else { rownames(wavecoefmatrix) <- seq(.5, dim( x @series)[1], by = .5) } results <- wavecoefmatrix } if(is.null(w.range) && !is.null(v.range)) { if( x @class.X == "ts" || x @class.X == "mts") { rownames(scalecoefmatrix) <- seq( x @attr.X$tsp[1]-.5, x @attr.X$tsp[2], by = .5) } else { rownames(scalecoefmatrix) <- seq(.5, dim( x @series)[1], by = .5) } results <- scalecoefmatrix } results } as.matrix.dwt <- function ( x , w.range, v.range) { if( x @aligned) { x <- align( x , inverse = TRUE) } if(is.null(w.range) == FALSE) { wavecoefmatrix <- array(NA, c(dim( x @series)[1], length(w.range))) Wjplot <- rep(NA, dim( x @series)[1]) wavecoefmatrix.index <- 0 for (j in w.range) { Wjplot <- rep(NA, dim( x @series)[1]) wavecoefmatrix.index <- wavecoefmatrix.index + 1 Wj <- x @W[[j]][,1] Wjplot[(2^j)*(1:length(Wj))] <- Wj Wjplot <- levelshift.dwt(Wjplot, waveletshift.dwt( x @filter@L, j, dim( x @series)[1])) wavecoefmatrix[,wavecoefmatrix.index] <- Wjplot } } if(is.null(v.range) == FALSE) { scalecoefmatrix <- array(NA, c(dim( x @series)[1], length(v.range))) Vjplot <- rep(NA, dim( x @series)[1]) scalecoefmatrix.index <- 0 for(k in v.range) { scalecoefmatrix.index <- scalecoefmatrix.index + 1 Vj <- x @V[[k]][,1] - mean( x @V[[k]][,1]) Vjplot[(2^k)*(1:length(Vj))] <- Vj Vjplot <- levelshift.dwt(Vjplot, scalingshift.dwt( x @filter@L, k, dim( x @series)[1])) scalecoefmatrix[,scalecoefmatrix.index] <- Vjplot } } if(is.null(w.range) == FALSE && is.null(v.range) == FALSE) { if( x @class.X == "ts" || x @class.X == "mts") { rownames(wavecoefmatrix) <- x @attr.X$tsp[1]: x @attr.X$tsp[2] rownames(scalecoefmatrix) <- x @attr.X$tsp[1]: x @attr.X$tsp[2] } else { rownames(wavecoefmatrix) <- 1:dim( x @series)[1] rownames(scalecoefmatrix) <- 1:dim( x @series)[1] } results <- cbind(wavecoefmatrix, scalecoefmatrix) } if(is.null(w.range) == FALSE && is.null(v.range)) { if( x @class.X == "ts" || x @class.X == "mts") { rownames(wavecoefmatrix) <- x @attr.X$tsp[1]: x @attr.X$tsp[2] } else { rownames(wavecoefmatrix) <- 1:dim( x @series)[1] } results <- wavecoefmatrix } if(is.null(w.range) && is.null(v.range) == FALSE) { if( x @class.X == "ts" || x @class.X == "mts") { rownames(scalecoefmatrix) <- x @attr.X$tsp[1]: x @attr.X$tsp[2] } else { rownames(scalecoefmatrix) <- 1:dim( x @series)[1] } results <- scalecoefmatrix } results } labels.dwt <- function (w.range = NULL, v.range = NULL, gammah = NULL, gammag = NULL) { verticallabel <- list() if(is.null(w.range) == FALSE) { for (j in 1:length(w.range)) { label <- substitute(paste(T^-gamma,W[level]), list(gamma = gammah[j], level = w.range[j])) verticallabel <- c(verticallabel, label) } } if(is.null(v.range) == FALSE) { for (i in 1:length(v.range)) { label <- substitute(paste(T^-gamma,V[level]), list(gamma = gammag[i], level = v.range[i])) verticallabel <- c(verticallabel, label) } } results <- verticallabel results } levelshift.dwt <- function (level, shift) { if(shift != 0) { level <- c(level[(shift+1):length(level)], level[1:shift]) } level } if (type == "stack") { if(class( x ) != "dwt") { stop("Invalid argument: 'dwt' object must be of class dwt.") } if(is.null(levels)) { w.range <- 1: x @level v.range <- max(w.range) } if(class(levels) == "numeric") { if(length(levels) == 1) { w.range <- 1:levels v.range <- max(w.range) } else { w.range <- levels v.range <- max(w.range) } } if(class(levels) == "list") { if(length(levels) < 1) { w.range <- 1: x @level v.range <- max(w.range) } if(length(levels) == 1) { w.range <- levels[[1]] v.range <- max(w.range) } else { w.range <- levels[[1]] v.range <- levels[[2]] } } if(class(levels) != "list" && class(levels) != "vector" && class(levels) != "numeric" && is.null(levels) == FALSE) { stop("Invalid argument: Levels must be numeric, vector, or list.") } if(plot.W == FALSE) { w.range <- NULL } if(plot.V == FALSE) { v.range <- NULL } if(plot.W == FALSE && plot.V == FALSE) { stop("Invalid argument: At least one of plot.W or plot.V must be TRUE") } if(is.null(w.range) == FALSE) { if(min(w.range) < 1 || x @level < max(w.range)) { stop("Invalid argument: Elements of 'levels' must be compatible with the level of decomposition of the 'dwt' object.") } } if(is.null(v.range) == FALSE) { if(min(v.range) < 1 || x @level < max(v.range)) { stop("Invalid argument: Elements of 'levels' must be compatible with the level of decomposition of the 'dwt' object.") } } stackplot.dwt( x , w.range, v.range, col.plot, col.boundary, draw.boundary = draw.boundary, X.xtick.at = X.xtick.at, X.ytick.at = X.ytick.at, Stack.xtick.at = Stack.xtick.at, Stack.ytick.at = Stack.ytick.at, X.xlab = X.xlab, plot.X = plot.X) } else { stop("Only the stackplot is currently implemented.") } }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/plot.dwt.R
plot.dwt.multiple <- function( x, levels = NULL, ylim = NULL, draw.dashed.lines = TRUE, draw.level.labels = TRUE, col = c("red","blue"), ...) { inner.plot.level <- function(dwt.object, w.range, v.range, col = c("red", "blue")) { prev.plotcolor <- col[2] index <- 0 for(i in w.range) { plotted.level <- FALSE if(prev.plotcolor == col[2] && plotted.level == FALSE) { prev.plotcolor <- col[1] lines((index+1):(index + length(dwt.object@W[[i]][,1])), as.vector(dwt.object@W[[i]][,1]), col = prev.plotcolor) index <- index + length(dwt.object@W[[i]][,1]) plotted.level <- TRUE } if(prev.plotcolor == col[1] && plotted.level == FALSE) { prev.plotcolor <- col[2] lines((index+1):(index + length(dwt.object@W[[i]][,1])), as.vector(dwt.object@W[[i]][,1]), col = prev.plotcolor) index <- index + length(dwt.object@W[[i]][,1]) plotted.level <- TRUE } } for(i in v.range) { plotted.level <- FALSE if(prev.plotcolor == col[2] && plotted.level == FALSE) { prev.plotcolor <- col[1] lines((index+1):(index + length(dwt.object@V[[i]][,1])), as.vector(dwt.object@V[[i]][,1]), col = prev.plotcolor) index <- index + length(dwt.object@V[[i]][,1]) plotted.level <- TRUE } if(prev.plotcolor == col[1] && plotted.level == FALSE) { prev.plotcolor <- col[2] lines((index+1):(index + length(dwt.object@V[[i]][,1])), as.vector(dwt.object@V[[i]][,1]), col = prev.plotcolor) index <- index + length(dwt.object@V[[i]][,1]) plotted.level <- TRUE } } } inner.plot <- function(levels, range, filter.name = NULL, type = "h", level.labels = NULL, ylim = NULL, xlim = NULL, ylab = NULL, xlab = "", draw.dashed.lines = TRUE, draw.xaxis.label = FALSE) { draw.dash <- function(range) { range.shift <- 0 for(i in 1:length(range)) { abline(v=range.shift+range[i], lty = 2) range.shift <- range.shift + range[i] } } draw.level.labels <- function(level.labels, range) { range.shift <- 0 if(length(level.labels) > 3) { level.labels <- c(level.labels[1:3], "...") } for(i in 1:length(level.labels)) { mtext(level.labels[[i]], side = 3, at = range.shift + range[[i]]/2, line = 1) range.shift <- range.shift + range[[i]] } } if(is.null(ylab)) { ylab = filter.name } plot(1:length(levels), y = levels, type = type, ylab = ylab, axes = FALSE, frame.plot = TRUE, ylim = ylim, xaxs = "i", xlim = c(0,length(levels))) axis(2) if(draw.xaxis.label) { axis(1, labels = TRUE) } else { axis(1, labels = FALSE) } if(is.null(xlab) == FALSE) { mtext(xlab, side = 1, line = 2) } if(draw.dashed.lines) { par(new = FALSE) draw.dash(range) } if(is.null(level.labels) == FALSE) { par(new=FALSE) draw.level.labels(level.labels, range) } } concatenate.levels <- function( x, w.range, v.range) { list.levels <- list() for(i in 1:length( x)) { dwt.object <- x[[i]] concatenated.levels <- NULL for(j in w.range) { concatenated.levels <- c(concatenated.levels, as.vector(dwt.object@W[[j]][,1])) } for(j in v.range) { concatenated.levels <- c(concatenated.levels, as.vector(dwt.object@W[[j]][,1])) } list.one.level <- list(concatenated.levels) list.levels <- c(list.levels, list.one.level) } list.levels } range.levels <- function(dwt.object, w.range, v.range) { range.levels <- NULL for(j in w.range) { range.levels <- c(range.levels, length(dwt.object@W[[j]][,1])) } for(j in v.range) { range.levels <- c(range.levels, length(dwt.object@W[[j]][,1])) } range.levels } if(class( x) =="dwt") { x <- list( x) } if (class( x) != "list") { stop("Invalid argument: ' x' must be of class 'dwt', 'list'") } else { for(i in 1:length( x)) { if(class( x[[i]]) != "dwt") { stop("Invalid argument: elements of ' x' must be of class 'dwt'") } } } if(is.null(levels)) { minlevel <- x[[1]]@level for(i in 1:length( x)) { minlevel <- min(minlevel, x[[i]]@level) } w.range <- 1:minlevel v.range <- max(w.range) } if(class(levels) == "numeric") { if(length(levels) == 1) { w.range <- 1:levels v.range <- max(w.range) } else { w.range <- levels v.range <- max(w.range) } } if(class(levels) == "integer") { if(length(levels) == 1) { w.range <- 1:levels v.range <- max(w.range) } else { w.range <- levels v.range <- max(w.range) } } if(class(levels) == "list") { w.range <- levels[[1]] v.range <- levels[[2]] } par(omi = c(.6, 0, .4, 0)) par(mfrow = c(length( x),1)) concatenated.levels <- concatenate.levels( x, w.range, v.range) range <- range.levels( x[[1]], w.range, v.range) if(is.null(ylim)) { minimum <- min(concatenated.levels[[1]]) maximum <- max(concatenated.levels[[1]]) if(length(concatenated.levels) > 1) { for(i in 2:length(concatenated.levels)) { if(minimum > min(concatenated.levels[[i]])) { minimum <- min(concatenated.levels[[i]]) } } for(i in 2:length(concatenated.levels)) { if(maximum < max(concatenated.levels[[i]])) { maximum <- max(concatenated.levels[[i]]) } } } ylim <- c(floor(minimum), ceiling(maximum)) } if(draw.level.labels) { level.labels <- NULL for (j in 1:length(w.range)) { label <- substitute(W[level], list(level = w.range[j])) level.labels <- c(level.labels, label) } for (i in 1:length(v.range)) { label <- substitute(V[level], list(level = v.range[i])) level.labels <- c(level.labels, label) } } else { level.labels <- NULL } for(i in 1:length( x)) { levels <- concatenated.levels[[i]] if(i == 1 && length( x) == 1) { par(mai = c(0, .8, 0, .4)) inner.plot(levels, range, x[[i]]@[email protected], type = "n", level.labels = level.labels, ylim = ylim, draw.dashed.lines = draw.dashed.lines, draw.xaxis.label= TRUE, xlab = "n") inner.plot.level( x[[i]], w.range, v.range) } if(i == 1 && length( x) != 1) { par(mai = c(.1, .8, 0, .4)) inner.plot(levels, range, x[[i]]@[email protected], type = "n", level.labels = level.labels, ylim = ylim, draw.dashed.lines = draw.dashed.lines, draw.xaxis.label = FALSE) inner.plot.level( x[[i]], w.range, v.range, col = col) } if(i != 1 && i != length( x)) { par(mai = c(.1, .8, 0, .4)) inner.plot(levels, range, x[[i]]@[email protected], type = "n", ylim = ylim, draw.dashed.lines = draw.dashed.lines, draw.xaxis.label = FALSE) inner.plot.level( x[[i]], w.range, v.range, col = col) } if(i == length( x) && i != 1) { par(mai = c(.1, .8, 0, .4)) inner.plot(levels, range, x[[i]]@[email protected], type = "n", ylim = ylim, draw.dashed.lines = draw.dashed.lines, draw.xaxis.label = TRUE, xlab = "n") inner.plot.level( x[[i]], w.range, v.range, col = col) } } }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/plot.dwt.multiple.R
plot.modwt <- function( x , levels = NULL, draw.boundary = FALSE, type = "stack", col.plot = "black", col.boundary = "red", X.xtick.at = NULL, X.ytick.at = NULL, Stack.xtick.at = NULL, Stack.ytick.at = NULL, X.xlab = "t", y.rlabs = TRUE, plot.X = TRUE, plot.W = TRUE, plot.V = TRUE, ...) { stackplot.modwt <- function ( x , w.range, v.range, col.plot, col.boundary, draw.boundary, X.xtick.at, X.ytick.at, Stack.xtick.at, Stack.ytick.at, X.xlab = "t", plot.X = TRUE) { innerplot <- function(x, y, type = "l", xtick.at, ytick.at) { if(is.null(xtick.at) == FALSE || is.null(ytick.at) == FALSE) { plot(x, y, type = "l", axes = FALSE, frame.plot = TRUE) if(is.null(xtick.at) == FALSE) { axis(1, at = axTicks(1, xtick.at)) xtickrate <- xtick.at } else { axis(1) xtickrate <- par("xaxp") } if(is.null(ytick.at) == FALSE) { axis(2, at = axTicks(2, ytick.at)) ytickrate <- ytick.at } else { axis(2) ytickrate <- par("yaxp") } } else { plot(x, y, type = "l") xtickrate <- par("xaxp") ytickrate <- par("yaxp") } tickrate <- list(xtick = xtickrate, ytick = ytickrate) tickrate } if(plot.X) { nf <- layout(matrix(c(2,2,1,1), 2, 2, byrow=TRUE), c(1,2), c(2,1), TRUE) par(mai = c(.6, .4, .1, .6)) if( x @class.X == "ts" || x @class.X == "mts") { x.range <- x @attr.X$tsp[1]: x @attr.X$tsp[2] } else{ x.range <- 1:dim( x @series)[1] } tickrate <- innerplot(x.range, x @series[,1], type = "l", X.xtick.at, X.ytick.at) right.usrplotrange <- par()$usr[2] - par()$usr[1] NDCplotrange <- par()$plt[2] - par()$plt[1] marginpos <- (1-par()$plt[2])/2 right.usrlabelpos <- ((marginpos*right.usrplotrange)/NDCplotrange) + par()$usr[2] text(right.usrlabelpos, 0, "X", xpd = TRUE) mtext(X.xlab, side = 1, line = 2) par(mai = c(0, .4, .1, .6)) } if(plot.X == FALSE) { par(mai = c(.4, .4, .1, .6)) if(is.null(Stack.xtick.at) == FALSE) { xtickrate <- Stack.xtick.at } else { xtickrate <- NULL } if(is.null(Stack.ytick.at) == FALSE) { ytickrate <- Stack.ytick.at } else { ytickrate <- NULL } tickrate <- list(xtick = xtickrate, ytick = ytickrate) } if(is.null(w.range) == FALSE) { gammawave = wt.filter.shift( x @filter, w.range, wavelet = TRUE, modwt = TRUE) } if(is.null(v.range) == FALSE) { gammascale = wt.filter.shift( x @filter, v.range, wavelet = FALSE, modwt = TRUE) } if(y.rlabs) { rightlabels <- labels.modwt(w.range = w.range, v.range = v.range, gammah = gammawave, gammag = gammascale) } else { rightlabels <- NULL } if (draw.boundary) { matrixlist <- list(modwt = as.matrix.modwt( x , w.range, v.range), posbound = boundary.as.matrix.modwt( x , w.range, v.range, positive = TRUE), negbound = boundary.as.matrix.modwt( x , w.range, v.range, positive = FALSE)) col <- c(col.plot, col.boundary, col.boundary) stackplot(matrixlist, y = NULL, y.rlabs = rightlabels, type = c("l", "h", "h"), col = col, xtick.at = tickrate$xtick, ytick.at = tickrate$ytick) } else { matrixlist <- list(modwt = as.matrix.modwt( x , w.range, v.range)) col <- col.plot stackplot(matrixlist, y = NULL, y.rlabs = rightlabels, type = "l", col = col, xtick.at = tickrate$xtick, ytick.at = tickrate$ytick) } } boundary.as.matrix.modwt <- function( x , w.range, v.range, positive = TRUE) { if(is.null(w.range) == FALSE) { wavecoefmatrix <- array(NA, c(2*dim( x @series)[1], length(w.range))) Wjplot <- rep(NA, 2*dim( x @series)[1]) wavecoefmatrix.index <- 0 W.Ljs <- ((2^w.range) - 1)*( x @filter@L - 1) + 1 for (j in w.range) { wavecoefmatrix.index <- wavecoefmatrix.index + 1 if(positive) { boundaryheight <- max( x @W[[j]]) } else { boundaryheight <- min( x @W[[j]]) } leftspace <- rep(NA, 2*(W.Ljs[wavecoefmatrix.index] - 2 - vjH.modwt( x @filter@L, j, dim( x @series)[1])) - 1) rightspace <- rep(NA, 2*(vjH.modwt( x @filter@L, j, dim( x @series)[1]))) middlespace <- rep(NA, 2*dim( x @series)[1] - 2 - length(leftspace) - length(rightspace)) Wjplot <- c(leftspace, boundaryheight, middlespace, boundaryheight, rightspace) wavecoefmatrix[,wavecoefmatrix.index] <- Wjplot } rownames(wavecoefmatrix) <- seq(.5, dim( x @series)[1], by = .5) } if(is.null(v.range) == FALSE) { scalecoefmatrix <- array(NA, c(2*dim( x @series)[1], length(v.range))) Vjplot <- rep(NA, 2*dim( x @series)[1]) scalecoefmatrix.index <- 0 V.Ljs <- ((2^v.range) - 1)*( x @filter@L - 1) + 1 for(j in v.range) { scalecoefmatrix.index <- scalecoefmatrix.index + 1 Vj <- x @V[[j]][,1] - mean( x @V[[j]][,1]) if(positive) { boundaryheight <- max(Vj) } else { boundaryheight <- min(Vj) } leftspace <- rep(NA, 2*(V.Ljs[scalecoefmatrix.index] - 2 - vjG.modwt( x @filter@L, j, dim( x @series)[1])) - 1) rightspace <- rep(NA, 2*(vjG.modwt( x @filter@L, j, dim( x @series)[1]))) middlespace <- rep(NA, 2*dim( x @series)[1] - 2 - length(leftspace) - length(rightspace)) Vjplot <- c(leftspace, boundaryheight, middlespace, boundaryheight, rightspace) scalecoefmatrix[,scalecoefmatrix.index] <- Vjplot } rownames(scalecoefmatrix) <- seq(.5, dim( x @series)[1], by = .5) } if(is.null(w.range) == FALSE && is.null(v.range) == FALSE) { results <- cbind(wavecoefmatrix, scalecoefmatrix) } if(is.null(w.range) == FALSE && is.null(v.range)) { results <- wavecoefmatrix } if(is.null(w.range) && is.null(v.range) == FALSE) { results <- scalecoefmatrix } results } as.matrix.modwt <- function ( x , w.range, v.range) { if(is.null(w.range) == FALSE) { wavecoefmatrix <- array(NA, c(dim( x @series)[1], length(w.range))) wavecoefmatrix.index <- 0 for (j in w.range) { wavecoefmatrix.index <- wavecoefmatrix.index + 1 Wjplot <- x @W[[j]][,1] Wjplot <- levelshift.modwt(Wjplot, wt.filter.shift( x @filter, j, wavelet = TRUE, modwt=TRUE)) wavecoefmatrix[,wavecoefmatrix.index] <- Wjplot } rownames(wavecoefmatrix) <- 1:dim( x @series)[1] } if(is.null(v.range) == FALSE) { scalecoefmatrix <- array(NA, c(dim( x @series)[1], length(v.range))) scalecoefmatrix.index <- 0 for(k in v.range) { scalecoefmatrix.index <- scalecoefmatrix.index + 1 Vjplot <- x @V[[k]][,1] - mean( x @V[[k]][,1]) Vjplot <- levelshift.modwt(Vjplot, wt.filter.shift( x @filter, k, wavelet = FALSE, modwt=TRUE)) scalecoefmatrix[,scalecoefmatrix.index] <- Vjplot } rownames(scalecoefmatrix) <- 1:dim( x @series)[1] } if(is.null(w.range) == FALSE && is.null(v.range) == FALSE) { results <- cbind(wavecoefmatrix, scalecoefmatrix) } if(is.null(w.range) == FALSE && is.null(v.range)) { results <- wavecoefmatrix } if(is.null(w.range) && is.null(v.range) == FALSE) { results <- scalecoefmatrix } results } labels.modwt <- function (w.range = NULL, v.range = NULL, gammah = NULL, gammag = NULL) { verticallabel <- list() if(is.null(w.range) == FALSE && is.null(gammah) == FALSE) { for (j in 1:length(w.range)) { label <- substitute(paste(T^-gamma,W[level]), list(gamma = gammah[j], level = w.range[j])) verticallabel <- c(verticallabel, label) } } if(is.null(v.range) == FALSE && is.null(gammag) == FALSE) { for (i in 1:length(v.range)) { label <- substitute(paste(T^-gamma,V[level]), list(gamma = gammag[i], level = v.range[i])) verticallabel <- c(verticallabel, label) } } results <- verticallabel results } levelshift.modwt <- function(level, shift) { if(shift != 0) { level <- c(level[(round(shift)+1):length(level)], level[1:round(shift)]) } level } shift.modwt <- function(L, j, N) { Lj <- ((2^j)-1)*(L-1) + 1 shift <- min(Lj - 2, N-1) shift } vjH.modwt <- function (L, j, N) { Lj <- ((2^j)-1)*(L-1) + 1 if (L == 10 || L == 18) { vjH <- (-Lj/2) + 1 } else if (L == 14) { vjH <- (-Lj/2) - 1 } else { vjH <- -Lj/2 } vjH <- abs(vjH) } vjG.modwt <- function (L, j, N) { Lj <- ((2^j)-1)*(L-1) + 1 if (L == 10 || L == 18) { vjG <- -((Lj-1)*L)/(2*(L-1)) } else if (L == 14) { vjG <- -((Lj-1)*(L-4))/(2*(L-1)) } else { vjG <- -((Lj-1)*(L-2))/(2*(L-1)) } vjG <- abs(vjG) vjG } if (type == "stack") { if(class( x ) != "modwt") { stop("Invalid argument: 'modwt' object must be of class modwt.") } if(is.null(levels)) { w.range <- 1: x @level v.range <- max(w.range) } if(class(levels) == "numeric") { if(length(levels) == 1) { w.range <- 1:levels v.range <- max(w.range) } else { w.range <- levels v.range <- max(w.range) } } if(class(levels) == "list") { if(length(levels) < 1) { w.range <- 1:x@level v.range <- max(w.range) } if(length(levels) == 1) { w.range <- levels[[1]] v.range <- max(w.range) } else { w.range <- levels[[1]] v.range <- levels[[2]] } } if(class(levels) != "list" && class(levels) != "vector" && class(levels) != "numeric" && is.null(levels) == FALSE) { stop("Invalid argument: 'levels' must be numeric, vector, or list.") } if(plot.W == FALSE) { w.range <- NULL } if(plot.V == FALSE) { v.range <- NULL } if(plot.W == FALSE && plot.V == FALSE) { stop("At least one of plot.W or plot.V must be TRUE") } if(is.null(w.range) == FALSE) { if(min(w.range) < 1 || x @level < max(w.range)) { stop("Invalid argument: elements of 'levels' must be compatible with the level of decomposition of the 'modwt' object.") } } if(is.null(v.range) == FALSE) { if(min(v.range) < 1 || x @level < max(v.range)) { stop("Invalid argument: elements of 'levels' must be compatible with the level of decomposition of the 'modwt' object.") } } stackplot.modwt( x , w.range, v.range, col.plot, col.boundary, draw.boundary = draw.boundary, X.xtick.at = X.xtick.at, X.ytick.at = X.ytick.at, Stack.xtick.at = Stack.xtick.at, Stack.ytick.at = Stack.ytick.at, X.xlab = X.xlab, plot.X = plot.X) } else { stop("Only the stackplot is currently implemented.") } }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/plot.modwt.R
print.dwt <- function(x, ...) { printlevel <- function(coef.level) { if(length(coef.level) > 6) { coef.level.begin <- formatC(coef.level[1:3], format = "e") coef.level.end <- formatC(coef.level[(length(coef.level)-2):(length(coef.level))], format = "e") cat(c(coef.level.begin , "..." , coef.level.end)) cat("\n") } else { cat(formatC(coef.level, format = "e")) cat("\n") } } cat("DWT Wavelet Coefficients:\n") for(i in 1:x@level) { cat(paste("Level",i)) cat("\n") for(j in 1:dim(x@series)[2]) { cat(paste(paste(paste("Series",j),":", sep = ""),"")) printlevel(x@W[[i]][,j]) } } cat("\n") cat("DWT Scaling Coefficients:\n") for(i in 1:x@level) { cat(paste("Level",i)) cat("\n") for(j in 1:dim(x@series)[2]) { cat(paste(paste(paste("Series",j),":", sep = ""),"")) printlevel(x@V[[i]][,j]) } } cat("\n") cat("Length of Original Series: ") cat(dim(x@series)[1]) cat("\n") cat("Wavelet Coefficients Aligned? ") if(x@aligned == FALSE) { cat("FALSE\n") } else { cat("TRUE\n") } cat("Center of Energy Method Used? ") if(x@coe == FALSE) { cat("FALSE\n") } else { cat("TRUE\n") } cat("\n") cat("Boundary Method: ") cat(paste(toupper(substr(x@boundary, start = 1, stop =1)), substr(x@boundary, start = 2, stop = nchar(x@boundary)), sep = "")) cat("\n") cat("Number of Boundaries Coefficients per Level:\n") for(i in 1:length([email protected])) { cat(paste(paste(paste("Level",i),":", sep = ""),"")) cat([email protected][i]) cat("\n") } cat("\n") cat("Filter Class: ") cat(x@[email protected]) cat("\n") cat("Filter Name: ") cat(toupper(x@[email protected])) cat("\n") cat("Filter Length: ") cat(x@filter@L) cat("\n") invisible(x) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/print.dwt.R
print.modwt <- function(x, ...) { printlevel <- function(coef.level) { if(length(coef.level) > 6) { coef.level.begin <- formatC(coef.level[1:3], format = "e") coef.level.end <- formatC(coef.level[(length(coef.level)-2):(length(coef.level))], format = "e") cat(c(coef.level.begin , "..." , coef.level.end)) cat("\n") } else { cat(formatC(coef.level, format = "e")) cat("\n") } } cat("MODWT Wavelet Coefficients:\n") for(i in 1:x@level) { cat(paste("Level",i)) cat("\n") for(j in 1:dim(x@series)[2]) { cat(paste(paste(paste("Series",j),":", sep = ""),"")) printlevel(x@W[[i]][,j]) } } cat("\n") cat("MODWT Scaling Coefficients:\n") for(i in 1:x@level) { cat(paste("Level",i)) cat("\n") for(j in 1:dim(x@series)[2]) { cat(paste(paste(paste("Series",j),":", sep = ""),"")) printlevel(x@V[[i]][,j]) } } cat("\n") cat("Length of Original Series: ") cat(dim(x@series)[1]) cat("\n") cat("Wavelet Coefficients Aligned? ") if(x@aligned == FALSE) { cat("FALSE\n") } else { cat("TRUE\n") } #print whether center of energy method used cat("Center of Energy Method Used? ") if(x@coe == FALSE) { cat("FALSE\n") } else { cat("TRUE\n") } cat("\n") cat("Boundary Method: ") cat(paste(toupper(substr(x@boundary, start = 1, stop =1)), substr(x@boundary, start = 2, stop = nchar(x@boundary)), sep = "")) cat("\n") cat("Number of Boundaries Coefficients per Level:\n") for(i in 1:length([email protected])) { cat(paste(paste(paste("Level",i),":", sep = ""),"")) cat([email protected][i]) cat("\n") } cat("\n") cat("Filter Class: ") cat(x@[email protected]) cat("\n") cat("Filter Name: ") cat(toupper(x@[email protected])) cat("\n") cat("Filter Length: ") cat(x@filter@L) cat("\n") invisible(x) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/print.modwt.R
print.wt.filter <- function(x, ...) { printlevel <- function(coef.level) { if(length(coef.level) > 6) { coef.level.begin <- formatC(coef.level[1:3], format = "e") coef.level.end <- formatC(coef.level[(length(coef.level)-2):(length(coef.level))], format = "e") cat(c(coef.level.begin , "..." , coef.level.end)) cat("\n") } else { cat(formatC(coef.level, format = "e")) cat("\n") } } cat("Filter Class: ") cat([email protected]) cat("\n") cat("Name: ") cat(toupper([email protected])) cat("\n") cat("Length: ") cat(x@L) cat("\n") cat("Level: ") cat(x@level) cat("\n") cat("Wavelet Coefficients: ") printlevel(x@h) cat("Scaling Coefficients: ") printlevel(x@g) cat("\n") invisible(x) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/print.wt.filter.R
scalingshift.dwt <- function (L, j, N = NULL) { if(L%%2 == 1){ stop("Filter must be of even length.") } Lj <- ((2^j)-1)*(L-1) + 1 if (L == 10 || L == 18) { vjG <- -((Lj-1)*L)/(2*(L-1)) } else if (L == 14) { vjG <- -((Lj-1)*(L-4))/(2*(L-1)) } else { vjG <- -((Lj-1)*(L-2))/(2*(L-1)) } if(is.null(N) == FALSE) { shift <- abs(vjG)%%N } else { shift <- abs(vjG) } shift }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/scalingshift.dwt.R
squaredgain.wt.filter <- function(filter, level = 1, N = NULL, draw.bands = TRUE, wavelet = TRUE) { if(class(filter) == "numeric") { filter <- wt.filter(filter) } if(class(filter) == "character") { filter <- wt.filter(tolower(filter), level = level) } if(class(filter) != "wt.filter") { stop("Invalid argument: filter must be of class vector, character, or string.") } if(wavelet) { filter.vector <- filter@h wavelet.string <- "Wavelet Filter" } else { filter.vector <- filter@g wavelet.string <- "Scaling Filter" } if(length(filter.vector) < 1024 && is.null(N)) { N <- 1024 } if(length(filter.vector) > 1024 && is.null(N)) { j <- ceiling(log(length(filter.vector))/log(2)) N <- 2^j } j <- filter@level if(N-length(filter.vector) > 0) { zeroes <- rep(0, N-length(filter.vector)) filter.vector <- c(filter.vector, zeroes) } Hf <- fft(filter.vector) absHf <- abs(Hf) squaredHf <- absHf^2 x <- seq((1/N),1/2, (1/N)) if([email protected] != "haar") { if([email protected] == "none") { filter.name <- "" } else { filter.name <- toupper([email protected]) } } else { filter.name <- "Haar" } plot(x, squaredHf[1:(N*.5)], type = "l", xlab = "f", ylab = "", main = paste("Squared gain function for ", filter.name, "Level",j,wavelet.string)) if(draw.bands) { abline(v = 1/(2^(j+1)), lty = 2) abline(v = 1/(2^j), lty = 2) } }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/squaredgain.wt.filter.R
stackplot <- function (x, y = NULL, type = "h", axes.labels = FALSE, xlab = "", ylab = "", y.llabs = NULL, y.rlabs = NULL, draw.divides = TRUE, xtick.at = NULL, ytick.at = NULL, col = "black", main = "") { innerstackplot <- function(x, matrix, type, colorp, vertshift, plotarray) { plotmatrix <- matrix plot(x, plotmatrix[,1], type = type, xlim = xlimits, ylim = c(mindata[1], mindata[1] + totalrange), ylab = ylab, xlab = xlab, axes = FALSE, frame.plot = TRUE, col = colorp) if(dim(plotmatrix)[2] > 1) { if(type == "h") { for (i in 2:dim(plotmatrix)[2]) { shifty1 <- vertshift[i] shifty2 <- plotmatrix[,i] + vertshift[i] segments(x, shifty1, x, shifty2, col = colorp) } } if(type == "l") { for (i in 2:dim(plotmatrix)[2]) { shifty2 <- plotmatrix[,i] + vertshift[i] lines(x, shifty2, col = colorp) } } } } find.rightlabelpos <- function () { right.usrplotrange <- par()$usr[2] - par()$usr[1] NDCplotrange <- par()$plt[2] - par()$plt[1] marginpos <- (1-par()$plt[2])/2 right.usrlabelpos <- ((marginpos*right.usrplotrange)/NDCplotrange) + par()$usr[2] right.usrlabelpos } draw.rightlabels <- function(y.rlabs, right.usrlabelpos, vertshift) { for (i in 1:length(y.rlabs)) { text(right.usrlabelpos, vertshift[i], y.rlabs[[i]], xpd = TRUE) } } find.leftlabelpos <- function () { left.usrplotrange <- par()$usr[1] NDCplotrange <- par()$plt[1] marginpos <- (par()$plt[1])/2 left.usrlabelpos <- ((marginpos*left.usrplotrange)/NDCplotrange) left.usrlabelpos } draw.leftlabels <- function(y.llabs, left.usrlabelpos, vertshift) { for (i in 1:length(y.llabs)) { text(left.usrlabelpos, vertshift[i], y.llabs[[i]], xpd = TRUE) } } coercetomatrix <- function(y) { for(i in 1:length(y)) { if(class(y[[i]])[1] == "mts" || class(y[[i]])[1] == "ts") { x.start <- start(y[[i]])[1] x.end <- end(y[[i]])[1] x.range <- x.start:x.end if(class(y[[i]])[1] == "mts") { y.matrix <- NULL for(j in 1:length(y[[i]][1,])) { y.matrix <- cbind(y.matrix, as.matrix(y[[i]][,j])) } y[[i]] <- y.matrix } else { y[[i]] <- as.matrix(y[[i]]) } rownames(y[[i]]) <- x.range } if(class(y[[i]])[1] != "matrix") { y[[i]] <- as.matrix(y[[i]]) } } y } if(is.null(y) == TRUE) { y <- x if(class(y)[1] != "list") { y <- list(y) } y <- coercetomatrix(y) if(is.null(rownames(y[[1]])) == TRUE) { x <- list(1:length(y[[1]][,1])) if(length(y) != 1) { for(k in 2:length(y)) { x <- c(x, list(1:length(y[[k]][,1]))) } } } else { x <- list(as.numeric(rownames(y[[1]]))) if(length(y) != 1) { for(k in 2:length(y)) { if(is.null(rownames(y[[k]])) == TRUE) { x <- c(x, list(1:length(y[[k]][,1]))) } else { x <- c(x, list(as.numeric(rownames(y[[k]])))) } } } } } else { if(class(x) != "list") { x <- list(x) } if(class(y) != "list") { y <- list(y) } y <- coercetomatrix(y) if(length(x) != length(y)) { k <- 0 add.type <- x[[1]] for(k in 1:(length(y) - length(x))) { x <- c(x, list(add.type)) } } for(k in 1:length(y)) { if(length(x[[k]]) != length(y[[k]][,1])) { stop("x and y lengths differ.") } } } if(length(x[[1]]) != length(y[[1]][,1])) { stop("x and y lengths differ.") } if(is.null(type[[1]] == TRUE)) { type[[1]] <- "h" } if(length(type) < length(y)) { for(i in 2:length(y)) { type <- c(type, list(type[[i-1]])) } } if (length(col) < length(y)) { if(is.null(col[1] == TRUE)) { col[1] <- "black" } for(i in 2:length(y)) { if(is.null(col[i]) == TRUE) { col <- c(col, col[i-1]) } } } plotmatrix <- as.matrix(y[[1]]) plotarray <- 1:dim(plotmatrix)[2] rangeperplot <- NULL mindata <- NULL for(i in 1:length(plotmatrix[1,])) { if(min(plotmatrix[,i], na.rm = TRUE) > 0) { range <- max(plotmatrix[,i], na.rm = TRUE) mindata <- c(mindata, 0) rangeperplot <- c(rangeperplot, range) } if(min(plotmatrix[,i], na.rm = TRUE) < 0) { if(max(plotmatrix[,i], na.rm = TRUE) < 0) { range <- abs(min(plotmatrix[,i], na.rm = TRUE)) mindata <- c(mindata, min(plotmatrix[,i], na.rm = TRUE)) rangeperplot <- c(rangeperplot, range) } else { range <- max(plotmatrix[,i], na.rm = TRUE) - min(plotmatrix[,i], na.rm = TRUE) mindata <- c(mindata, min(plotmatrix[,i], na.rm = TRUE)) rangeperplot <- c(rangeperplot, range) } } } totalrange <- sum(rangeperplot) jstartline <- mindata[1] for (j in plotarray) { jstartline <- jstartline + rangeperplot[j] plotarray[j] <- jstartline } xlimits <- c(min(x[[1]]), max(x[[1]])) if(axes.labels == TRUE) { plot(0, 0, type = "n", xlim = xlimits, ylim = c(mindata[1], mindata[1] + totalrange), ylab = ylab, xlab = xlab, frame.plot = TRUE, main = main) } else { plot(0, 0, type = "n", xlim = xlimits, ylim = c(mindata[1], mindata[1] + totalrange), ylab = ylab, xlab = xlab, axes = FALSE, frame.plot = TRUE, main = main) } if(is.null(xtick.at) == FALSE && is.null(xlab) == TRUE) { axis(1, at = axTicks(1, xtick.at), labels = FALSE) } if(is.null(xtick.at) == FALSE && is.null(xlab) == FALSE) { axis(1, at = axTicks(1, xtick.at), labels = FALSE) } if(is.null(xtick.at) == TRUE && is.null(xlab) == TRUE) { axis(1, labels = FALSE) } if(is.null(xtick.at) == TRUE && is.null(xlab) == FALSE) { axis(1, labels = FALSE) } if(is.null(ytick.at) == FALSE && is.null(ylab) == TRUE) { ytickrate <- (ytick.at[2] - ytick.at[1])/ytick.at[3] interval <- (totalrange - mindata[1])/ytickrate axis(2, at = axTicks(2, c(mindata[1], totalrange, interval)), labels = FALSE) } if(is.null(ytick.at) == FALSE && is.null(ylab) == FALSE) { ytickrate <- (ytick.at[2] - ytick.at[1])/ytick.at[3] interval <- (totalrange - mindata[1])/ytickrate axis(2, at = axTicks(2, c(mindata[1], totalrange, interval)), labels = FALSE) } if(is.null(ytick.at) == TRUE && is.null(ylab) == TRUE) { axis(2, labels = FALSE) } if(is.null(ytick.at) == TRUE && is.null(ylab) == FALSE) { axis(2, labels = FALSE) } vertshift = rep(0, dim(plotmatrix)[2]) sum <- 0 if(dim(plotmatrix)[2] > 1) { for (j in 2:dim(plotmatrix)[2]) { if(max(plotmatrix[,(j-1)], na.rm = TRUE) < 0) { #so min is less than 0 vertshift[j] <- sum + abs(min(plotmatrix[,j], na.rm=TRUE)) sum <- sum + abs(min(plotmatrix[,j], na.rm=TRUE)) } if(min(plotmatrix[,(j)], na.rm = TRUE) > 0) { #so max is greater than 0 vertshift[j] <- sum + max(plotmatrix[,(j-1)], na.rm=TRUE) sum <- sum + max(plotmatrix[,(j-1)], na.rm=TRUE) } if(min(plotmatrix[,(j)], na.rm = TRUE) <= 0 && max(plotmatrix[,(j-1)], na.rm = TRUE) >= 0) { vertshift[j] <- sum + max(plotmatrix[,(j-1)], na.rm=TRUE) - min(plotmatrix[,j], na.rm=TRUE) sum <- sum + max(plotmatrix[,(j-1)], na.rm=TRUE) - min(plotmatrix[,j], na.rm=TRUE) } if(draw.divides == TRUE) { abline(plotarray[j-1], 0) } } } par(new = TRUE) for(i in 1:length(y)) { innerstackplot(x[[i]], y[[i]], type = type[[i]], colorp = col[i], vertshift, plotarray) par(new = TRUE) } if(is.null(y.rlabs) == FALSE) { draw.rightlabels(y.rlabs, find.rightlabelpos(), vertshift) } if(is.null(y.llabs) == FALSE) { draw.leftlabels(y.llabs, find.leftlabelpos(), vertshift) } par(new = FALSE) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/stackplot.R
summary.dwt <- function(object, ...) { cat("Number of Points in Original Series: ") cat(dim(object@series)[1]) cat("\n") cat("Number of Levels Decomposed: ") cat(object@level) cat("\n") cat("Filter Name: ") cat(toupper(object@[email protected])) cat("\n") cat("Boundary Method: ") bmethod <- object@boundary ncn <- nchar(bmethod) cat(paste(toupper(substr(object@boundary, start = 1, stop =1)), substr(object@boundary, start = 2, stop = nchar(object@boundary)), sep = "")) cat("\n") cat("Sum of Squares of Wavelet Coefficients:\n") for(i in 1:object@level) { cat(paste("Level",i)) cat("\n") for(j in 1:dim(object@series)[2]) { cat(paste(paste(paste("Series",j),":", sep = ""),"")) cat(sum(object@W[[i]][,j]^2)) cat("\n") } } cat("\n") cat("Sum of Squares of Scaling Coefficients:\n") for(i in 1:object@level) { cat(paste("Level",i)) cat("\n") for(j in 1:dim(object@series)[2]) { cat(paste(paste(paste("Series",j),":", sep = ""),"")) cat(sum(object@V[[i]][,j]^2)) cat("\n") } } cat("\n") invisible(object) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/summary.dwt.R
summary.modwt <- function(object, ...) { cat("Number of Points in Original Series: ") cat(dim(object@series)[1]) cat("\n") cat("Number of Levels Decomposed: ") cat(object@level) cat("\n") cat("Filter Name: ") cat(toupper(object@[email protected])) cat("\n") cat("Boundary Method: ") cat(paste(toupper(substr(object@boundary, start = 1, stop =1)), substr(object@boundary, start = 2, stop = nchar(object@boundary)), sep = "")) cat("\n") cat("Sum of Squares of Wavelet Coefficients:\n") for(i in 1:object@level) { cat(paste("Level",i)) cat("\n") for(j in 1:dim(object@series)[2]) { cat(paste(paste(paste("Series",j),":", sep = ""),"")) cat(sum(object@W[[i]][,j]^2)) cat("\n") } } cat("\n") cat("Sum of Squares of Scaling Coefficients:\n") for(i in 1:object@level) { cat(paste("Level",i)) cat("\n") for(j in 1:dim(object@series)[2]) { cat(paste(paste(paste("Series",j),":", sep = ""),"")) cat(sum(object@V[[i]][,j]^2)) cat("\n") } } cat("\n") invisible(object) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/summary.modwt.R
summary.wt.filter <- function(object, ...) { cat("Filter Class: ") cat([email protected]) cat("\n") cat("Name: ") cat(toupper([email protected])) cat("\n") cat("Length: ") cat(object@L) cat("\n") invisible(object) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/summary.wt.filter.R
waveletshift.dwt <- function (L, j, N = NULL) { if(L%%2 == 1){ stop("Filter must be of even length.") } Lj <- ((2^j)-1)*(L-1) + 1 if (L == 10 || L == 18) { vjH <- (-Lj/2) + 1 } else if (L == 14) { vjH <- (-Lj/2) - 1 } else { vjH <- -Lj/2 } if(is.null(N) == FALSE) { shift <- abs(vjH)%%N } else { shift <- abs(vjH) } shift }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/waveletshift.dwt.R
wt.filter <- function(filter="la8", modwt=FALSE, level=1){ # error checking if(is.na(match(class(filter), c("numeric", "character","integer")))) stop("Invalid argument: 'filter' must be of class 'character', 'numeric', or 'integer'") # create 'wt.filter' object if coeficients are supplied if((class(filter) == "numeric") | (class(filter) == "integer")){ if(round(length(filter)/2) != length(filter)/2) stop("Invalid argument: filter length must be even.") if(modwt) transform <- "modwt" else transform <- "dwt" wt.filter <- new("wt.filter", L=length(filter), h=filter, g=wt.filter.qmf(filter), wt.class="none", wt.name="none", transform=transform) } else { # create 'wt.filter' object if character string is supplied haar.filter <- function(mod=FALSE){ class <- "Daubechies" name <- "haar" L <- as.integer(2) g <- c( 0.7071067811865475, 0.7071067811865475 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } d4.filter <- function(mod=FALSE){ class <- "Daubechies" name <- "d4" L <- as.integer(4) g <- c( 0.4829629131445341, 0.8365163037378077, 0.2241438680420134, -0.1294095225512603 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } d6.filter <- function(mod=FALSE){ class <- "Daubechies" name <- "d6" L <- as.integer(6) g <- c( 0.3326705529500827, 0.8068915093110928, 0.4598775021184915, -0.1350110200102546, -0.0854412738820267, 0.0352262918857096 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } d8.filter <- function(mod=FALSE){ class <- "Daubechies" name <- "d8" L <- as.integer(8) g <- c( 0.2303778133074431, 0.7148465705484058, 0.6308807679358788, -0.0279837694166834, -0.1870348117179132, 0.0308413818353661, 0.0328830116666778, -0.0105974017850021 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } d10.filter <- function(mod=FALSE){ class <- "Daubechies" name <- "d10" L <- as.integer(10) g <- c( 0.1601023979741930, 0.6038292697971898, 0.7243085284377729, 0.1384281459013204, -0.2422948870663824, -0.0322448695846381, 0.0775714938400459, -0.0062414902127983, -0.0125807519990820, 0.0033357252854738 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } d12.filter <- function(mod=FALSE){ class <- "Daubechies" name <- "d12" L <- as.integer(12) g <- c( 0.1115407433501094, 0.4946238903984530, 0.7511339080210954, 0.3152503517091980, -0.2262646939654399, -0.1297668675672624, 0.0975016055873224, 0.0275228655303053, -0.0315820393174862, 0.0005538422011614, 0.0047772575109455, -0.0010773010853085 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } d14.filter <- function(mod=FALSE){ class <- "Daubechies" name <- "d14" L <- as.integer(14) g <- c( 0.0778520540850081, 0.3965393194819136, 0.7291320908462368, 0.4697822874052154, -0.1439060039285293, -0.2240361849938538, 0.0713092192668312, 0.0806126091510820, -0.0380299369350125, -0.0165745416306664, 0.0125509985560993, 0.0004295779729214, -0.0018016407040474, 0.0003537137999745 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } d16.filter <- function(mod=FALSE){ class <- "Daubechies" name <- "d16" L <- as.integer(16) g <- c( 0.0544158422431049, 0.3128715909143031, 0.6756307362972904, 0.5853546836541907, -0.0158291052563816, -0.2840155429615702, 0.0004724845739124, 0.1287474266204837, -0.0173693010018083, -0.0440882539307952, 0.0139810279173995, 0.0087460940474061, -0.0048703529934518, -0.0003917403733770, 0.0006754494064506, -0.0001174767841248 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } d18.filter <- function(mod=FALSE){ class <- "Daubechies" name <- "d18" L <- as.integer(18) g <- c( 0.0380779473638791, 0.2438346746125939, 0.6048231236901156, 0.6572880780512955, 0.1331973858249927, -0.2932737832791761, -0.0968407832229524, 0.1485407493381306, 0.0307256814793395, -0.0676328290613302, 0.0002509471148340, 0.0223616621236805, -0.0047232047577520, -0.0042815036824636, 0.0018476468830564, 0.0002303857635232, -0.0002519631889427, 0.0000393473203163 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } d20.filter <- function(mod=FALSE){ class <- "Daubechies" name <- "d20" L <- as.integer(20) g <- c( 0.0266700579005546, 0.1881768000776863, 0.5272011889317202, 0.6884590394536250, 0.2811723436606485, -0.2498464243272283, -0.1959462743773399, 0.1273693403357890, 0.0930573646035802, -0.0713941471663697, -0.0294575368218480, 0.0332126740593703, 0.0036065535669880, -0.0107331754833036, 0.0013953517470692, 0.0019924052951930, -0.0006858566949566, -0.0001164668551285, 0.0000935886703202, -0.0000132642028945 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } la8.filter <- function(mod=FALSE){ class <- "Least Asymmetric" name <- "la8" L <- as.integer(8) g <- c( -0.0757657147893407, -0.0296355276459541, 0.4976186676324578, 0.8037387518052163, 0.2978577956055422, -0.0992195435769354, -0.0126039672622612, 0.0322231006040713 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } la10.filter <- function(mod=FALSE){ class <- "Least Asymmetric" name <- "la10" L <- as.integer(10) g <- c( 0.0195388827353869, -0.0211018340249298, -0.1753280899081075, 0.0166021057644243, 0.6339789634569490, 0.7234076904038076, 0.1993975339769955, -0.0391342493025834, 0.0295194909260734, 0.0273330683451645 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } la12.filter <- function(mod=FALSE){ class <- "Least Asymmetric" name <- "la12" L <- as.integer(12) g <- c( 0.0154041093273377, 0.0034907120843304, -0.1179901111484105, -0.0483117425859981, 0.4910559419276396, 0.7876411410287941, 0.3379294217282401, -0.0726375227866000, -0.0210602925126954, 0.0447249017707482, 0.0017677118643983, -0.0078007083247650 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } la14.filter <- function(mod=FALSE){ class <- "Least Asymmetric" name <- "la14" L <- as.integer(14) g <- c( 0.0102681767084968, 0.0040102448717033, -0.1078082377036168, -0.1400472404427030, 0.2886296317509833, 0.7677643170045710, 0.5361019170907720, 0.0174412550871099, -0.0495528349370410, 0.0678926935015971, 0.0305155131659062, -0.0126363034031526, -0.0010473848889657, 0.0026818145681164 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } la16.filter <- function(mod=FALSE){ class <- "Least Asymmetric" name <- "la16" L <- as.integer(16) g <- c( -0.0033824159513594, -0.0005421323316355, 0.0316950878103452, 0.0076074873252848, -0.1432942383510542, -0.0612733590679088, 0.4813596512592012, 0.7771857516997478, 0.3644418948359564, -0.0519458381078751, -0.0272190299168137, 0.0491371796734768, 0.0038087520140601, -0.0149522583367926, -0.0003029205145516, 0.0018899503329007 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } la18.filter <- function(mod=FALSE){ class <- "Least Asymmetric" name <- "la18" L <- as.integer(18) g <- c( 0.0010694900326538, -0.0004731544985879, -0.0102640640276849, 0.0088592674935117, 0.0620777893027638, -0.0182337707798257, -0.1915508312964873, 0.0352724880359345, 0.6173384491413523, 0.7178970827642257, 0.2387609146074182, -0.0545689584305765, 0.0005834627463312, 0.0302248788579895, -0.0115282102079848, -0.0132719677815332, 0.0006197808890549, 0.0014009155255716 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } la20.filter <- function(mod=FALSE){ class <- "Least Asymmetric" name <- "la20" L <- as.integer(20) g <- c( 0.0007701598091030, 0.0000956326707837, -0.0086412992759401, -0.0014653825833465, 0.0459272392237649, 0.0116098939129724, -0.1594942788575307, -0.0708805358108615, 0.4716906668426588, 0.7695100370143388, 0.3838267612253823, -0.0355367403054689, -0.0319900568281631, 0.0499949720791560, 0.0057649120455518, -0.0203549398039460, -0.0008043589345370, 0.0045931735836703, 0.0000570360843390, -0.0004593294205481 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } bl14.filter <- function(mod=FALSE){ class <- "Best Localized" name <- "bl14" L <- as.integer(14) g <- c( 0.0120154192834842, 0.0172133762994439, -0.0649080035533744, -0.0641312898189170, 0.3602184608985549, 0.7819215932965554, 0.4836109156937821, -0.0568044768822707, -0.1010109208664125, 0.0447423494687405, 0.0204642075778225, -0.0181266051311065, -0.0032832978473081, 0.0022918339541009 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } bl18.filter <- function(mod=FALSE){ class <- "Best Localized" name <- "bl18" L <- as.integer(18) g <- c( 0.0002594576266544, -0.0006273974067728, -0.0019161070047557, 0.0059845525181721, 0.0040676562965785, -0.0295361433733604, -0.0002189514157348, 0.0856124017265279, -0.0211480310688774, -0.1432929759396520, 0.2337782900224977, 0.7374707619933686, 0.5926551374433956, 0.0805670008868546, -0.1143343069619310, -0.0348460237698368, 0.0139636362487191, 0.0057746045512475 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } bl20.filter <- function(mod=FALSE){ class <- "Best Localized" name <- "bl20" L <- as.integer(20) g <- c( 0.0008625782242896, 0.0007154205305517, -0.0070567640909701, 0.0005956827305406, 0.0496861265075979, 0.0262403647054251, -0.1215521061578162, -0.0150192395413644, 0.5137098728334054, 0.7669548365010849, 0.3402160135110789, -0.0878787107378667, -0.0670899071680668, 0.0338423550064691, -0.0008687519578684, -0.0230054612862905, -0.0011404297773324, 0.0050716491945793, 0.0003401492622332, -0.0004101159165852 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } c6.filter <- function(mod=FALSE){ class <- "Coiflet" name <- "c6" L <- as.integer(6) g <- c( -0.0156557285289848, -0.0727326213410511, 0.3848648565381134, 0.8525720416423900, 0.3378976709511590, -0.0727322757411889 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } c12.filter <- function(mod=FALSE){ class <- "Coiflet" name <- "c12" L <- as.integer(12) g <- c( -0.0007205494453679, -0.0018232088707116, 0.0056114348194211, 0.0236801719464464, -0.0594344186467388, -0.0764885990786692, 0.4170051844236707, 0.8127236354493977, 0.3861100668229939, -0.0673725547222826, -0.0414649367819558, 0.0163873364635998 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } c18.filter <- function(mod=FALSE){ class <- "Coiflet" name <- "c18" L <- as.integer(18) g <- c( -0.0000345997728362, -0.0000709833031381, 0.0004662169601129, 0.0011175187708906, -0.0025745176887502, -0.0090079761366615, 0.0158805448636158, 0.0345550275730615, -0.0823019271068856, -0.0717998216193117, 0.4284834763776168, 0.7937772226256169, 0.4051769024096150, -0.0611233900026726, -0.0657719112818552, 0.0234526961418362, 0.0077825964273254, -0.0037935128644910 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } c24.filter <- function(mod=FALSE){ class <- "Coiflet" name <- "c24" L <- as.integer(24) g <- c( -0.0000017849850031, -0.0000032596802369, 0.0000312298758654, 0.0000623390344610, -0.0002599745524878, -0.0005890207562444, 0.0012665619292991, 0.0037514361572790, -0.0056582866866115, -0.0152117315279485, 0.0250822618448678, 0.0393344271233433, -0.0962204420340021, -0.0666274742634348, 0.4343860564915321, 0.7822389309206135, 0.4153084070304910, -0.0560773133167630, -0.0812666996808907, 0.0266823001560570, 0.0160689439647787, -0.0073461663276432, -0.0016294920126020, 0.0008923136685824 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } c30.filter <- function(mod=FALSE){ class <- "Coiflet" name <- "c30" L <- as.integer(30) g <- c( -0.0000000951765727, -0.0000001674428858, 0.0000020637618516, 0.0000037346551755, -0.0000213150268122, -0.0000413404322768, 0.0001405411497166, 0.0003022595818445, -0.0006381313431115, -0.0016628637021860, 0.0024333732129107, 0.0067641854487565, -0.0091642311634348, -0.0197617789446276, 0.0326835742705106, 0.0412892087544753, -0.1055742087143175, -0.0620359639693546, 0.4379916262173834, 0.7742896037334738, 0.4215662067346898, -0.0520431631816557, -0.0919200105692549, 0.0281680289738655, 0.0234081567882734, -0.0101311175209033, -0.0041593587818186, 0.0021782363583355, 0.0003585896879330, -0.0002120808398259 ) if(modwt == TRUE){ g <- g/sqrt(2) transform <- "modwt" } else transform <- "dwt" h <- wt.filter.qmf(g, inverse=TRUE) wt.filter <- new("wt.filter", L=L, h=h, g=g, wt.class=class, wt.name=name, transform=transform) return(wt.filter) } wt.filter <- switch(filter, haar=haar.filter(), d2=haar.filter(), d4=d4.filter(), d6=d6.filter(), d8=d8.filter(), d10=d10.filter(), d12=d12.filter(), d14=d14.filter(), d16=d16.filter(), d18=d18.filter(), d20=d20.filter(), la8=la8.filter(), la10=la10.filter(), la12=la12.filter(), la14=la14.filter(), la16=la16.filter(), la18=la18.filter(), la20=la20.filter(), bl14=bl14.filter(), bl18=bl18.filter(), bl20=bl20.filter(), c6=c6.filter(), c12=c12.filter(), c18=c18.filter(), c24=c24.filter(), c30=c30.filter() ) } if(is.null(wt.filter)) stop("Invalid filter name.") else { if(level > 1) wt.filter <- wt.filter.equivalent(wt.filter, J=level) else wt.filter@level <- as.integer(1) return(wt.filter) } }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/wt.filter.R
wt.filter.equivalent <- function(wt.filter, J){ L <- wt.filter@L h <- wt.filter@h g <- wt.filter@g L.last <- L h.last <- h g.last <- g for(j in 2:J){ L.new <- (2^j - 1)*(L-1) + 1 hj <- NULL gj <- NULL for(l in 0:(L.new - 1)){ u <- l ifelse(u >= L, g.mult <- 0, g.mult <- g[u+1]) hjl <- g.mult*h.last[1] gjl <- g.mult*g.last[1] for(k in 1:(L.last-1)){ u <- u-2 if((u < 0) | (u >= L)) g.mult <- 0 else g.mult <- g[u+1] hjl <- hjl + g.mult*h.last[k+1] gjl <- gjl + g.mult*g.last[k+1] } hj <- c(hj,hjl) gj <- c(gj,gjl) } h.last <- hj g.last <- gj L.last <- L.new } wt.filter@L <- as.integer(L.last) wt.filter@h <- h.last wt.filter@g <- g.last wt.filter@level <- as.integer(J) return(wt.filter) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/wt.filter.equivalent.R
wt.filter.qmf <- function(x, inverse=FALSE){ L <- length(x) y <- x[L:1]*(-1)^(1:L) # x[L:1] is twice as fast as rev(x) if(inverse) y <- x[L:1]*(-1)^((1:L)-1) return(y) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/wt.filter.qmf.R
wt.filter.shift <- function(filter, J, wavelet=TRUE, coe=FALSE, modwt=FALSE){ # error checking if(is.na(match(class(filter), c("character", "wt.filter", "numeric", "integer")))) stop("Invalid argument: 'filter' must be of class 'character', 'wt.filter', 'numeric' or 'integer'") if((length(setdiff(J, round(J)) != 0) | (sum(J <= 0) != 0))) stop("Invalid argument: all elements of 'J' must be a positive integers.") # create filter if necessary if(!is.na(match(class(filter), c("numeric","integer","character")))) filter <- wt.filter(filter, modwt=modwt) L <- filter@L # calculate level 1 shift (equation 112e) if(!coe){ if(([email protected] == "Daubechies") & !is.na(match(L, c(2,4)))){ if(L == 2) nu <- 0 if(L == 4) nu <- 1 } else if([email protected] == "Least Asymmetric"){ if(!is.na(match(L,c(8,12,16,20)))) delta <- 1 if(L == 10 | L == 18) delta <- 0 if(L == 14) delta <- 2 nu <- abs(-(L/2) + delta) } else if([email protected] == "Coiflet") { nu <- abs(-2*L/3 + 1) } else if([email protected] == "Best Localized") { if(L == 14) nu <- 5 if(L == 18) nu <- 11 if(L == 20) nu <- 9 } else nu <- sum((1:(L-1))*filter@g[-1]^2)/sum(filter@g^2) } else { nu <- sum((1:(L-1))*filter@g[-1]^2)/sum(filter@g^2) } # calculate shift for each j > 1 (equation 114c) if([email protected] != "haar"){ shift <- sapply(J, function(j, wavelet){ if(j > 1){ if(wavelet) shift <- (2^(j-1))*(L-1) - nu else shift <- (2^j -1)*nu } else { if(wavelet) shift <- L - nu - 1 else shift <- nu } }, wavelet=wavelet) } else { if(!modwt){ shift <- 0^J } else { shift <- 2^(J-1) } } # calculate shift for dwt if(filter@transform == "dwt") shift <- ceiling(((shift+1)/(2^J))-1) return(shift) }
/scratch/gouwar.j/cran-all/cranData/wavelets/R/wt.filter.shift.R
heatmap_wave.local.multiple.correlation <- #3.1.0. function(Lst, xaxt="s", ci=NULL, pdf.write=NULL) { ##Producing heat map if (xaxt[1]!="s"){ at <- xaxt[[1]] label <- xaxt[[2]] xaxt <- "n" } cor <- Lst$cor J <- length(Lst$YmaxR)-1 par(mfcol=c(1,1), las=1, pty="m", mar=c(2,3,1,0)+.1, oma=c(0.1,1.2,1.2,1.2)) scale.labs <- c(paste0(2^(1:J),"-",2^((1:J)+1)),"smooth") if (!is.null(pdf.write)) cairo_pdf(paste0("heat_",pdf.write,"_WLMC.pdf"), width=11.69,height=8.27) if (is.null(ci)||ci=="center") {val <- sapply(cor,function(x){x[["val"]]}) } else if (ci=="lower") {val <- sapply(cor,function(x){x[["lo"]]}) } else if (ci=="upper"){val <- sapply(cor,function(x){x[["up"]]})} clim <- range(sapply(cor,function(x){x[["val"]]})) mark <- paste0("\u00A9jfm-wavemulcor3.1.0_",Sys.time()," ") plot3D::image2D(z=val, x=1:nrow(val), y=1:ncol(val), main="", sub="", xlab="", ylab="", xaxt=xaxt, yaxt="n", cex.axis=0.75, colkey=list(cex.axis=0.75), clim=clim, clab=expression(varphi), rasterImage=TRUE, contour=list(lwd=2, col=plot3D::jet.col(11))) if(xaxt!="s") {axis(side=1, at=at, labels=label, cex.axis=0.75)} axis(side=2, at=1:ncol(val),labels=scale.labs, las=1, cex.axis=0.75) text(x=grconvertX(0.1,from="npc"), y=grconvertY(0.98,from="npc"), labels=mark, col=rgb(0,0,0,.1),cex=.2) par(las=0) title(main='Wavelet Local Multiple Correlation', outer=TRUE) mtext("period", side=2, outer=TRUE, adj=0.5) if (!is.null(pdf.write)) dev.off() return() }
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/heatmap_wave.local.multiple.correlation.R
heatmap_wave.local.multiple.cross.correlation <- #3.1.1 function(Lst, lmax, lag.first=FALSE, xaxt="s", ci=NULL, pdf.write=NULL) { ##Producing cross-correlation plot if (xaxt[1]!="s"){ at <- xaxt[[1]] label <- xaxt[[2]] xaxt <- "n" } cor <- Lst$cor lag.max <- trunc((ncol(cor$d1$vals)-1)/2) lag0 <- lag.max+1 YmaxR <- Lst$YmaxR J <- length(Lst$YmaxR)-1 level.labs <- c(paste("level",1:J),paste("s",J)) scale.labs <- c(paste0(2^(1:J),"-",2^((1:J)+1)),"smooth") lag.labs <- c(paste("lead",lag.max:1),paste("lag",0:lag.max)) if (is.null(ci)||ci=="center") {clim <- range(sapply(cor,function(x){x[["vals"]]})) } else if (ci=="lower") {clim <- range(sapply(cor,function(x){x[["lower"]]})) } else if (ci=="upper"){clim <- range(sapply(cor,function(x){x[["upper"]]}))} mark <- paste0("\u00A9jfm-wavemulcor3.1.0_",Sys.time()," ") if(lag.first){ par(mfcol=c(lmax+1,2), las=1, pty="m", mar=c(2,3,1,0)+.1, oma=c(0.1,1.2,1.2,1.2)) if (!is.null(pdf.write)) cairo_pdf(paste0("heat_",pdf.write,"_WLMCC_lags.pdf"), width=8.27,height=11.69) for(i in c(-lmax:0,lmax:1)+lag0) { # val <- sapply(cor,function(x){x[["vals"]][,i]}) if (is.null(ci)||ci=="center") {val <- sapply(cor,function(x){x[["vals"]][,i]}) } else if (ci=="lower") {val <- sapply(cor,function(x){x[["lower"]][,i]}) } else if (ci=="upper"){val <- sapply(cor,function(x){x[["upper"]][,i]})} colkey <- FALSE if (i==lag0) colkey <- list(cex.axis=0.75) plot3D::image2D(z=val, x=1:nrow(val), y=1:ncol(val), main=lag.labs[i], sub="", xlab="", ylab="", xaxt=xaxt, yaxt="n", cex.axis=0.75, colkey=colkey, clim=clim, clab=expression(varphi), rasterImage=TRUE, contour=list(lwd=2, col=plot3D::jet.col(11))) text(x=grconvertX(0.1,from="npc"), y=grconvertY(0.97,from="npc"), labels=mark, col=rgb(0,0,0,.1),cex=.2) par(las=0) if(xaxt!="s") {axis(side=1, at=at, labels=label, cex.axis=0.75)} axis(side=2, at = if(i<=lag0) 1:ncol(val) else FALSE, labels = if(i<=lag0) scale.labs else FALSE, las=1, cex.axis=0.75) } title(main='Wavelet Local Multiple Cross-Correlation', outer=TRUE) mtext("period", side=2, outer=TRUE, adj=0.5) if (!is.null(pdf.write)) dev.off() } else{ par(mfrow=c(ceiling((J+1)/2),2), las=1, pty="m", mar=c(2,3,1,0)+.1, oma=c(0.1,1.2,1.2,1.2)) if (!is.null(pdf.write)) cairo_pdf(paste0("heat_",pdf.write,"_WLMCC_levels.pdf"), width=8.27,height=11.69) for(j in (J+1):1) { # val <- cor[[j]]$vals if (is.null(ci)||ci=="center") {val <- cor[[j]]$vals[,lag0+(-lmax:lmax)] } else if (ci=="lower") {val <- cor[[j]]$lower[,lag0+(-lmax:lmax)] } else if (ci=="upper"){val <- cor[[j]]$upper[,lag0+(-lmax:lmax)]} colkey <- FALSE if (j==1) colkey <- list(cex.axis=0.75) plot3D::image2D(z=val, x=1:nrow(val), y=1:ncol(val), main=level.labs[j], sub="", xlab="", ylab="", xaxt=xaxt, yaxt="n", cex.axis=0.75, colkey=colkey, clim=clim, clab=expression(varphi), rasterImage=TRUE, contour=list(lwd=2, col=plot3D::jet.col(11))) text(x=grconvertX(0.1,from="npc"), y=grconvertY(0.97,from="npc"), labels=mark, col=rgb(0,0,0,.15),cex=.2) par(las=0) if(xaxt!="s") {axis(side=1, at=at, labels=label, cex.axis=0.75)} axis(side=2, at = if((J%%2==0&j%%2==1)||(J%%2==1&j%%2==0)) 1:ncol(val) else FALSE, labels = if((J%%2==0&j%%2==1)||(J%%2==1&j%%2==0)) lag.labs[lag0+(-lmax:lmax)] else FALSE, las=1, cex.axis=0.75) } title(main='Wavelet Local Multiple Cross-Correlation', outer=TRUE) mtext("lead / lag", side=2, outer=TRUE, adj=0.5) if (!is.null(pdf.write)) dev.off() } return() }
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/heatmap_wave.local.multiple.cross.correlation.R
heatmap_wave.multiple.cross.correlation <- #3.1.0. function(Lst, lmax, by=3, ci=NULL, pdf.write=NULL) { ##Producing heat map if (is.null(ci)||ci=="center") {cor <- Lst$xy.mulcor } else if (ci=="lower") {cor <- Lst$ci.mulcor$lower } else if (ci=="upper"){cor <- Lst$ci.mulcor$upper} J <- length(Lst$YmaxR)-1 par(mfcol=c(1,1), las=1, pty="m", mar=c(2,3,1,0)+.1, oma=c(0.1,1.2,1.2,1.2)) scale.labs <- c(paste0(2^(1:J),"-",2^((1:J)+1)),"smooth") if (!is.null(pdf.write)) cairo_pdf(paste0("heat_",pdf.write,"_WMCC.pdf"), width=11.69,height=8.27) val <- t(cor) #sapply(cor,function(x){x[["val"]]}) mark <- paste0("\u00A9jfm-wavemulcor3.1.0_",Sys.time()," ") plot3D::image2D(z=val, x=1:nrow(val), y=1:ncol(val), main="", sub="", xlab="", ylab="", cex.axis=0.75, xaxt="n", yaxt="n", clab = expression(varphi), colkey=list(cex.axis=0.75), rasterImage=TRUE, contour=list(lwd=2, col=plot3D::jet.col(11))) axis(side=1, at=seq(1,2*lmax+1,by=lmax/by), labels=seq(-lmax,lmax,by=lmax/by), cex.axis=0.75) axis(side=2, at=1:ncol(val),labels=scale.labs, las=1, cex.axis=0.75) text(x=grconvertX(0.1,from="npc"), y=grconvertY(0.98,from="npc"), labels=mark, col=rgb(0,0,0,.1),cex=.2) par(las=0) title(main='Wavelet Multiple Cross-Correlation', outer=TRUE) mtext('lag', side=1, outer=FALSE, adj=0.5) mtext("period", side=2, outer=TRUE, adj=0.5) if (!is.null(pdf.write)) dev.off() return() }
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/heatmap_wave.multiple.cross.correlation.R
#---------------------------------------------------------- local.multiple.correlation <- #2.2.2 function(xx, M, window="gauss", p=.975, ymaxr=NULL) { window <- substr(tolower(window),1,4) if (window=="unif"){ #uniform window: weights <- function(z,M) {w<-z<=M; w/sum(w)} } else if (window=="clev"||window=="tric"){ #Cleveland tricube window: weights <- function(z,M) {w<-z<=M; w<-w*(1-abs(z/M)^3)^3; w/sum(w)} } else if (window=="epan"||window=="para"){ #Epanechnikov parabolic window: weights <- function(z,M) {w<-z<=M; w<-w*(1-abs(z/M)^2); w/sum(w)} } else if (window=="bart"||window=="tria"){ #Bartlett triangular window: weights <- function(z,M) {w<-z<=M; w<-w*(1-abs(z/M)); w/sum(w)} } else if (window=="wend"){ #Wendland 1995 window: weights <- function(z,M) {w<-z<=M; w<-w*(1-abs(z/M))^4*(1+4*abs(z/M)); w/sum(w)} } else if (window=="gaus"){ #gauss window: weights <- function(z,M) {w<-1/exp((z/M)^2); w/sum(w)} } else {stop("wrong window type")} weighted <- function(x,s,M) {z<-abs( seq_along(x)-s ); w<-weights(z,M); w*x} #s=observation number; z=distance |t-s| weightedsq <- function(x,s,M) {z<-abs( seq_along(x)-s ); w<-weights(z,M); w^2*x} sum.of.squares <- function(x) { sum(x^2, na.rm=TRUE) / sum(!is.na(x)) } sum.of.not.squares <- function(x) { sum(x, na.rm=TRUE) / sum(!is.na(x)) } d <- length(xx) #number of series dd <- d*(d-1)/2 #number of correlations N <- nrow(xx) #number of observations val <- lo <- up <- YmaxR <- matrix(nrow=N) for (s in 1:N) { x.w <- x.var <- vector("list", d) for(j in 1:d) { x.w[[j]] <- weighted( xx[[j]] ,s,M) #xx.w[[j]][[i]][[s]] x.var[[j]] <- sum.of.squares(x.w[[j]]) } xy.cor <- vector("list", dd) jk <- 0 for(k in 1:(d-1)) { for(j in (k+1):d) { jk <- jk+1 if (is.null(attr(xx,"wave"))) { xy.cor[[jk]] <- cor(x.w[[j]],x.w[[k]],use="complete.obs") } else { xy.w <- as.vector( x.w[[j]] * x.w[[k]] ) xy.cov <- sum.of.not.squares(xy.w) xy.cor[[jk]] <- xy.cov / sqrt(x.var[[j]] * x.var[[k]]) } if(sum(is.infinite(xy.cor[[jk]]))>0) browser() }} r <- unlist(xy.cor) if (is.na(sum(r))||is.nan(sum(r))){ Pimax <- xy.mulcor <- NA } else{ P <- diag(d)/2 P[lower.tri(P)] <- r P <- P+t(P) if (qr(P)$rank < d) {xy.mulcor <- 1; Pimax <- NA} else { Pidiag <- diag(solve(P)) if(is.null(ymaxr)) { Pimax <- which.max(Pidiag) ## detect i | x[i] on rest x gives max R2 } else {Pimax <- ymaxr} sgnr <- 1 if (dd==1) sgnr <- sign(r) xy.mulcor <- sgnr*sqrt(1-1/Pidiag[Pimax]) ## max(sqrt(1-1/diag(solve(P)))) if (abs(xy.mulcor)>1) browser() }} #} swsq <- sum( weightedsq( !is.na(xx[[1]]) ,s,M) ,na.rm=TRUE) Nhat <- 1/swsq if (Nhat>=3) sqrtN <- sqrt(Nhat-3) else sqrtN <- NaN val[s] <- xy.mulcor lo[s] <- tanh(atanh(xy.mulcor)-qnorm(p)/sqrtN) if (dd>1) lo[s] <- pmax(lo[s],0) ## wavemulcor can only be negative in bivariate case up[s] <- tanh(atanh(xy.mulcor)+qnorm(p)/sqrtN) YmaxR[s] <- Pimax } # end for (s in 1:N) loop # val <- as.data.frame(val) # lo <- as.data.frame(lo) # up <- as.data.frame(up) # YmaxR <- as.data.frame(YmaxR) # names(val) <- names(lo) <- names(up) <- names(YmaxR) <- names(xx[[1]]) Lst <- list(val=val,lo=lo,up=up,YmaxR=YmaxR) return(Lst) } #--------------------------------------------------------------
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/local.multiple.correlation.R
#---------------------------------------------------------- local.multiple.cross.correlation <- #2.3.0 function(xx, M, window="gauss", lag.max=NULL, p=.975, ymaxr=NULL) { window <- substr(tolower(window),1,4) if (window=="unif"){ #uniform window: weights <- function(z,M) {w<-z<=M; w/sum(w)} } else if (window=="clev"||window=="tric"){ #Cleveland tricube window: weights <- function(z,M) {w<-z<=M; w<-w*(1-abs(z/M)^3)^3; w/sum(w)} } else if (window=="epan"||window=="para"){ #Epanechnikov parabolic window: weights <- function(z,M) {w<-z<=M; w<-w*(1-abs(z/M)^2); w/sum(w)} } else if (window=="bart"||window=="tria"){ #Bartlett triangular window: weights <- function(z,M) {w<-z<=M; w<-w*(1-abs(z/M)); w/sum(w)} } else if (window=="wend"){ #Wendland 1995 window: weights <- function(z,M) {w<-z<=M; w<-w*(1-abs(z/M))^4*(1+4*abs(z/M)); w/sum(w)} } else if (window=="gaus"){ #gauss window: weights <- function(z,M) {w<-1/exp((z/M)^2); w/sum(w)} } else {stop("wrong window type")} weighted <- function(x,s,M) {z<-abs( seq_along(x)-s ); w<-weights(z,M); w*x} #s=observation number; z=distance |t-s| weightedsq <- function(x,s,M) {z<-abs( seq_along(x)-s ); w<-weights(z,M); w^2*x} sum.of.squares <- function(x) { sum(x^2, na.rm=TRUE) / sum(!is.na(x)) } sum.of.not.squares <- function(x) { sum(x, na.rm=TRUE) / sum(!is.na(x)) } d <- length(xx) #number of series dd <- d*(d-1)/2 #number of correlations N <- nrow(xx) #number of observations if(is.null(lag.max)) {lag.max <- trunc(sqrt(length(xx[[1]]))/2)} lm <- min(length(xx[[1]])-1, lag.max, na.rm=TRUE) val <- lo <- up <- matrix(nrow=N,ncol=2*lm+1) YmaxR <- matrix(nrow=N) for (s in 1:N) { x.w <- x.var <- vector("list", d) for(j in 1:d) { x.w[[j]] <- weighted( xx[[j]] ,s,M) #xx.w[[j]][[i]][[s]] x.var[[j]] <- sum.of.squares(x.w[[j]]) } xy.cor <- vector("list", dd) jk <- 0 for(k in 1:(d-1)) { for(j in (k+1):d) { jk <- jk+1 if (is.null(attr(xx,"wave"))) { xy.cor[[jk]] <- cor(x.w[[j]],x.w[[k]],use="complete.obs") } else { xy.w <- as.vector( x.w[[j]] * x.w[[k]] ) xy.cov <- sum.of.not.squares(xy.w) xy.cor[[jk]] <- xy.cov / sqrt(x.var[[j]] * x.var[[k]]) } if(sum(is.infinite(xy.cor[[jk]]))>0) browser() }} r <- unlist(xy.cor) xy.mulcor <- matrix(nrow=2*lm+1) if (is.na(sum(r))||is.nan(sum(r))){ Pimax <- xy.mulcor[lm+1] <- NA } else{ P <- diag(d)/2 P[lower.tri(P)] <- r P <- P+t(P) if (qr(P)$rank < d) {xy.mulcor <- 1; Pimax <- NA} else { Pidiag <- diag(solve(P)) if(is.null(ymaxr)) { Pimax <- which.max(Pidiag) ## detect i | x[i] on rest x gives max R2 } else {Pimax <- ymaxr} sgnr <- 1 if (dd==1) sgnr <- sign(r) xy.mulcor[lm+1] <- sgnr*sqrt(1-1/Pidiag[Pimax]) ## max(sqrt(1-1/diag(solve(P)))) if (abs(xy.mulcor[lm+1])>1) browser() ## lag=0: this must be same as in local.multiple.correlation }} #} if(lm>0) { x <- as.matrix(as.data.frame(x.w[-Pimax])) y <- x.w[[Pimax]] z <- y vlength <- length(y) for(j in 1:lm) { ## now we obtain R2 of var[Pimax] with lagged values y <- c(y[2:vlength], NA) ## Note: var[Pimax] lags behind the others: y[t+j]<--x[t]hat lm_yx <- summary(lm(formula = y ~ x)) sgnr <- 1 if (dd==1) sgnr <- sign(cor(y,x,use="complete.obs")) xy.mulcor[lm+1+j] <- sgnr*sqrt( lm_yx$r.squared ) z <- c(NA, z[1:(vlength-1)]) ## Note: var[Pimax] leads the others: x[t]hat<--z[t-j] lm_zx <- summary(lm(formula = z ~ x)) sgnr <- 1 if (dd==1) sgnr <- sign(cor(z,x,use="complete.obs")) xy.mulcor[lm+1-j] <- sgnr*sqrt( lm_zx$r.squared ) }} swsq <- sum( weightedsq( !is.na(xx[[1]]) ,s,M) ,na.rm=TRUE) Nhat <- 1/swsq if (Nhat>=3) sqrtN <- sqrt(Nhat-3) else sqrtN <- NaN val[s,] <- xy.mulcor lo[s,] <- tanh(atanh(xy.mulcor)-qnorm(p)/sqrtN) if (dd>1) lo[s,] <- pmax(lo[s,],0) ## wavemulcor can only be negative in bivariate case up[s,] <- tanh(atanh(xy.mulcor)+qnorm(p)/sqrtN) YmaxR[s] <- Pimax } # end for (s in 1:N) loop Lst <- list(vals=val,lower=lo,upper=up,YmaxR=YmaxR) return(Lst) } #--------------------------------------------------------------
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/local.multiple.cross.correlation.R
#---------------------------------------------------------- local.multiple.cross.regression <- #3.0.0 function(xx, M, window="gauss", lag.max=NULL, p=.975, ymaxr=NULL) { window <- substr(tolower(window),1,4) if (window=="unif"){ #uniform window: weights <- function(z,M) {w<-z<=M; w/sum(w)} } else if (window=="clev"||window=="tric"){ #Cleveland tricube window: weights <- function(z,M) {w<-z<=M; w<-w*(1-abs(z/M)^3)^3; w/sum(w)} } else if (window=="epan"||window=="para"){ #Epanechnikov parabolic window: weights <- function(z,M) {w<-z<=M; w<-w*(1-abs(z/M)^2); w/sum(w)} } else if (window=="bart"||window=="tria"){ #Bartlett triangular window: weights <- function(z,M) {w<-z<=M; w<-w*(1-abs(z/M)); w/sum(w)} } else if (window=="wend"){ #Wendland 1995 window: weights <- function(z,M) {w<-z<=M; w<-w*(1-abs(z/M))^4*(1+4*abs(z/M)); w/sum(w)} } else if (window=="gaus"){ #gauss window: weights <- function(z,M) {w<-1/exp((z/M)^2); w/sum(w)} } else {stop("wrong window type")} weighted <- function(x,s,M) {z<-abs( seq_along(x)-s ); w<-weights(z,M); w*x} #s=observation number; z=distance |t-s| weightedsq <- function(x,s,M) {z<-abs( seq_along(x)-s ); w<-weights(z,M); w^2*x} sum.of.squares <- function(x) { sum(x^2, na.rm=TRUE) / sum(!is.na(x)) } sum.of.not.squares <- function(x) { sum(x, na.rm=TRUE) / sum(!is.na(x)) } d <- length(xx) #number of series dd <- d*(d-1)/2 #number of correlations N <- nrow(xx) #number of observations if(is.null(lag.max)) {lag.max <- trunc(sqrt(length(xx[[1]]))/2)} lm <- min(length(xx[[1]])-1, lag.max, na.rm=TRUE) val <- lo <- up <- matrix(nrow=N,ncol=2*lm+1) YmaxR <- matrix(nrow=N) rval<- rstd<- rlow<- rupp<- rtst<- rpva<- rord<- array(dim=c(N,2*lm+1,d+1)) for (s in 1:N) { x.w <- x.var <- vector("list", d) for(j in 1:d) { x.w[[j]] <- weighted( xx[[j]] ,s,M) #xx.w[[j]][[i]][[s]] x.var[[j]] <- sum.of.squares(x.w[[j]]) } xy.cor <- vector("list", dd) jk <- 0 for(k in 1:(d-1)) { for(j in (k+1):d) { jk <- jk+1 if (is.null(attr(xx,"wave"))) { xy.cor[[jk]] <- cor(x.w[[j]],x.w[[k]],use="complete.obs") } else { xy.w <- as.vector( x.w[[j]] * x.w[[k]] ) xy.cov <- sum.of.not.squares(xy.w) xy.cor[[jk]] <- xy.cov / sqrt(x.var[[j]] * x.var[[k]]) } if(sum(is.infinite(xy.cor[[jk]]))>0) browser() }} r <- unlist(xy.cor) xy.mulcor <- matrix(nrow=2*lm+1) if (is.na(sum(r))||is.nan(sum(r))){ Pimax <- xy.mulcor[lm+1] <- NA } else{ P <- diag(d)/2 P[lower.tri(P)] <- r P <- P+t(P) if (qr(P)$rank < d) {xy.mulcor <- 1; Pimax <- NA} else { Pidiag <- diag(solve(P)) if(is.null(ymaxr)) { Pimax <- which.max(Pidiag) ## detect i | x[i] on rest x gives max R2 } else {Pimax <- ymaxr} sgnr <- 1 if (dd==1) sgnr <- sign(r) xy.mulcor[lm+1] <- sgnr*sqrt(1-1/Pidiag[Pimax]) ## max(sqrt(1-1/diag(solve(P)))) if (abs(xy.mulcor[lm+1])>1) browser() ## lag=0: this must be same as in local.multiple.correlation }} #} depvar <- matrix(c(-1,0,Inf,0),1,4) if (is.null(names(xx))) row.names(depvar) <- "Y" else row.names(depvar) <- names(xx[Pimax]) x <- as.matrix(as.data.frame(x.w[-Pimax])) y <- x.w[[Pimax]] ## Note: var[Pimax] contemporaneous with the others: y[t]<--x[t]hat lm_yx <- summary(lm(formula = y ~ x)) xy.mulreg <- lm_yx$coefficients if(Pimax<nrow(xy.mulreg)) xy.mulreg.r <- xy.mulreg[(Pimax+1):nrow(xy.mulreg),,drop=FALSE] else xy.mulreg.r<-NULL xy.mulreg <- rbind(xy.mulreg[1:Pimax,,drop=FALSE], depvar, xy.mulreg.r) if (is.null(names(xx))) row.names(z)[1] <- "b0" else row.names(xy.mulreg) <- c("b0",names(xx)) rval[s,lm+1,] <- xy.mulreg[,'Estimate'] rstd[s,lm+1,] <- xy.mulreg[,'Std. Error'] rlow[s,lm+1,] <- xy.mulreg[,'Estimate']-qt(p,N-d)*xy.mulreg[,'Std. Error'] rupp[s,lm+1,] <- xy.mulreg[,'Estimate']+qt(p,N-d)*xy.mulreg[,'Std. Error'] rtst[s,lm+1,] <- xy.mulreg[,'t value'] rpva[s,lm+1,] <- xy.mulreg[,'Pr(>|t|)'] rord[s,lm+1,] <- match(abs(xy.mulreg[,'t value']),sort(abs(xy.mulreg[,'t value']),decreasing=TRUE)) ## next 3 lines to check xy.mulcor above # sgnr <- 1 # if (dd==1) sgnr <- sign(cor(y,x,use="complete.obs")) # xy.mulcor2[lm+1] <- sgnr*sqrt( lm_yx$r.squared ) if(lm>0) { z <- y vlength <- length(y) for(j in 1:lm) { ## now we obtain R2 of var[Pimax] with lagged values y <- c(y[2:vlength], NA) ## Note: var[Pimax] lags behind the others: y[t+j]<--x[t]hat lm_yx <- summary(lm(formula = y ~ x)) sgnr <- 1 if (dd==1) sgnr <- sign(cor(y,x,use="complete.obs")) xy.mulcor[lm+1+j] <- sgnr*sqrt( lm_yx$r.squared ) xy.mulreg <- lm_yx$coefficients if(Pimax<nrow(xy.mulreg)) xy.mulreg.r <- xy.mulreg[(Pimax+1):nrow(xy.mulreg),,drop=FALSE] else xy.mulreg.r<-NULL xy.mulreg <- rbind(xy.mulreg[1:Pimax,,drop=FALSE], depvar, xy.mulreg.r) if (is.null(names(xx))) row.names(z)[1] <- "b0" else row.names(xy.mulreg) <- c("b0",names(xx)) rval[s,lm+1+j,] <- xy.mulreg[,'Estimate'] rstd[s,lm+1+j,] <- xy.mulreg[,'Std. Error'] rlow[s,lm+1+j,] <- xy.mulreg[,'Estimate']-qt(p,N-d)*xy.mulreg[,'Std. Error'] rupp[s,lm+1+j,] <- xy.mulreg[,'Estimate']+qt(p,N-d)*xy.mulreg[,'Std. Error'] rtst[s,lm+1+j,] <- xy.mulreg[,'t value'] rpva[s,lm+1+j,] <- xy.mulreg[,'Pr(>|t|)'] rord[s,lm+1+j,] <- match(abs(xy.mulreg[,'t value']),sort(abs(xy.mulreg[,'t value']),decreasing=TRUE)) z <- c(NA, z[1:(vlength-1)]) ## Note: var[Pimax] leads the others: x[t]hat<--z[t-j] lm_zx <- summary(lm(formula = z ~ x)) sgnr <- 1 if (dd==1) sgnr <- sign(cor(z,x,use="complete.obs")) xy.mulcor[lm+1-j] <- sgnr*sqrt( lm_zx$r.squared ) xy.mulreg <- lm_zx$coefficients if(Pimax<nrow(xy.mulreg)) xy.mulreg.r <- xy.mulreg[(Pimax+1):nrow(xy.mulreg),,drop=FALSE] else xy.mulreg.r<-NULL xy.mulreg <- rbind(xy.mulreg[1:Pimax,,drop=FALSE], depvar, xy.mulreg.r) if (is.null(names(xx))) row.names(z)[1] <- "b0" else row.names(xy.mulreg) <- c("b0",names(xx)) rval[s,lm+1-j,] <- xy.mulreg[,'Estimate'] rstd[s,lm+1-j,] <- xy.mulreg[,'Std. Error'] rlow[s,lm+1-j,] <- xy.mulreg[,'Estimate']-qt(p,N-d)*xy.mulreg[,'Std. Error'] rupp[s,lm+1-j,] <- xy.mulreg[,'Estimate']+qt(p,N-d)*xy.mulreg[,'Std. Error'] rtst[s,lm+1-j,] <- xy.mulreg[,'t value'] rpva[s,lm+1-j,] <- xy.mulreg[,'Pr(>|t|)'] rord[s,lm+1-j,] <- match(abs(xy.mulreg[,'t value']),sort(abs(xy.mulreg[,'t value']),decreasing=TRUE)) }} swsq <- sum( weightedsq( !is.na(xx[[1]]) ,s,M) ,na.rm=TRUE) Nhat <- 1/swsq if (Nhat>=3) sqrtN <- sqrt(Nhat-3) else sqrtN <- NaN val[s,] <- xy.mulcor lo[s,] <- tanh(atanh(xy.mulcor)-qnorm(p)/sqrtN) if (dd>1) lo[s,] <- pmax(lo[s,],0) ## wavemulcor can only be negative in bivariate case up[s,] <- tanh(atanh(xy.mulcor)+qnorm(p)/sqrtN) YmaxR[s] <- Pimax } # end for (s in 1:N) loop dimnames(rval)[[3]] <- dimnames(rlow)[[3]] <- dimnames(rupp)[[3]] <- row.names(xy.mulreg) outcor <- list(vals=val,lower=lo,upper=up) outreg <- list( rval=rval, rstd=rstd, rlow=rlow, rupp=rupp, rtst=rtst, rord=rord, rpva=rpva ) Lst <- list(cor=outcor,reg=outreg,YmaxR=YmaxR,data=xx) return(Lst) } #--------------------------------------------------------------
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/local.multiple.cross.regression.R
#---------------------------------------------------------- local.multiple.regression <- #3.0.0. function(xx, M, window="gauss", p=.975, ymaxr=NULL) { window <- substr(tolower(window),1,4) if (window=="unif"){ #uniform window: weights <- function(z,M) {w<-z<=M; w/sum(w)} } else if (window=="clev"||window=="tric"){ #Cleveland tricube window: weights <- function(z,M) {w<-z<=M; w<-w*(1-abs(z/M)^3)^3; w/sum(w)} } else if (window=="epan"||window=="para"){ #Epanechnikov parabolic window: weights <- function(z,M) {w<-z<=M; w<-w*(1-abs(z/M)^2); w/sum(w)} } else if (window=="bart"||window=="tria"){ #Bartlett triangular window: weights <- function(z,M) {w<-z<=M; w<-w*(1-abs(z/M)); w/sum(w)} } else if (window=="wend"){ #Wendland 1995 window: weights <- function(z,M) {w<-z<=M; w<-w*(1-abs(z/M))^4*(1+4*abs(z/M)); w/sum(w)} } else if (window=="gaus"){ #gauss window: weights <- function(z,M) {w<-1/exp((z/M)^2); w/sum(w)} } else {stop("wrong window type")} weighted <- function(x,s,M) {z<-abs( seq_along(x)-s ); w<-weights(z,M); w*x} #s=observation number; z=distance |t-s| weightedsq <- function(x,s,M) {z<-abs( seq_along(x)-s ); w<-weights(z,M); w^2*x} sum.of.squares <- function(x) { sum(x^2, na.rm=TRUE) / sum(!is.na(x)) } sum.of.not.squares <- function(x) { sum(x, na.rm=TRUE) / sum(!is.na(x)) } d <- length(xx) #number of series dd <- d*(d-1)/2 #number of correlations N <- nrow(xx) #number of observations val <- lo <- up <- YmaxR <- matrix(nrow=N) rval<- rstd<- rlow<- rupp<- rtst<- rpva<- rord<- matrix(nrow=N,ncol=d+1) # rcor<-matrix(nrow=N) for (s in 1:N) { x.w <- x.var <- vector("list", d) for(j in 1:d) { x.w[[j]] <- weighted( xx[[j]] ,s,M) #xx.w[[j]][[i]][[s]] x.var[[j]] <- sum.of.squares(x.w[[j]]) } xy.cor <- vector("list", dd) jk <- 0 for(k in 1:(d-1)) { for(j in (k+1):d) { jk <- jk+1 if (is.null(attr(xx,"wave"))) { xy.cor[[jk]] <- cor(x.w[[j]],x.w[[k]],use="complete.obs") } else { xy.w <- as.vector( x.w[[j]] * x.w[[k]] ) xy.cov <- sum.of.not.squares(xy.w) xy.cor[[jk]] <- xy.cov / sqrt(x.var[[j]] * x.var[[k]]) } if(sum(is.infinite(xy.cor[[jk]]))>0) browser() }} r <- unlist(xy.cor) if (is.na(sum(r))||is.nan(sum(r))){ Pimax <- xy.mulcor <- NA } else{ P <- diag(d)/2 P[lower.tri(P)] <- r P <- P+t(P) if (qr(P)$rank < d) {xy.mulcor <- 1; Pimax <- NA} else { Pidiag <- diag(solve(P)) if(is.null(ymaxr)) { Pimax <- which.max(Pidiag) ## detect i | x[i] on rest x gives max R2 } else {Pimax <- ymaxr} sgnr <- 1 if (dd==1) sgnr <- sign(r) xy.mulcor <- sgnr*sqrt(1-1/Pidiag[Pimax]) ## max(sqrt(1-1/diag(solve(P)))) if (abs(xy.mulcor)>1) browser() depvar <- matrix(c(-1,0,Inf,0),1,4) if (is.null(names(xx))) row.names(depvar) <- "Y" else row.names(depvar) <- names(xx[Pimax]) x <- as.matrix(as.data.frame(x.w[-Pimax])) y <- x.w[[Pimax]] lm_yx <- summary(lm(formula = y ~ x)) xy.mulreg <- lm_yx$coefficients #NOTE: sqrt(summary(lm(formula = y ~ x))$r.squared) == xy.mulcor!! (checked!) if(Pimax<nrow(xy.mulreg)) xy.mulreg.r <- xy.mulreg[(Pimax+1):nrow(xy.mulreg),,drop=FALSE] else xy.mulreg.r<-NULL xy.mulreg <- rbind(xy.mulreg[1:Pimax,,drop=FALSE], depvar, xy.mulreg.r) if (is.null(names(xx))) row.names(z)[1] <- "b0" else row.names(xy.mulreg) <- c("b0",names(xx)) # xy.mulreg <- z[order(z[,4]),1:2] #coefficients (and their stdvs) ordered from most to least significant }} #} swsq <- sum( weightedsq( !is.na(xx[[1]]) ,s,M) ,na.rm=TRUE) Nhat <- 1/swsq if (Nhat>=3) sqrtN <- sqrt(Nhat-3) else sqrtN <- NaN val[s] <- xy.mulcor lo[s] <- tanh(atanh(xy.mulcor)-qnorm(p)/sqrtN) if (dd>1) lo[s] <- pmax(lo[s],0) ## wavemulcor can only be negative in bivariate case up[s] <- tanh(atanh(xy.mulcor)+qnorm(p)/sqrtN) YmaxR[s] <- Pimax # rcor[s] <- sqrt(summary(lm(formula = y ~ x))$r.squared) rval[s,] <- xy.mulreg[,'Estimate'] rstd[s,] <- xy.mulreg[,'Std. Error'] rlow[s,] <- xy.mulreg[,'Estimate']-qt(p,N-d)*xy.mulreg[,'Std. Error'] rupp[s,] <- xy.mulreg[,'Estimate']+qt(p,N-d)*xy.mulreg[,'Std. Error'] rtst[s,] <- xy.mulreg[,'t value'] rpva[s,] <- xy.mulreg[,'Pr(>|t|)'] rord[s,] <- match(abs(xy.mulreg[,'t value']),sort(abs(xy.mulreg[,'t value']),decreasing=TRUE)) } # end for (s in 1:N) loop colnames(rval) <- colnames(rlow) <- colnames(rupp) <- row.names(xy.mulreg) outcor <- list(val=val,lo=lo,up=up) outreg <- list( rval=rval, rstd=rstd, rlow=rlow, rupp=rupp, rtst=rtst, rord=rord, rpva=rpva ) #) #vars=t(sapply(rval,names)) --> names of variables: useful if somehow reordered Lst <- list(cor=outcor,reg=outreg,YmaxR=YmaxR,data=xx) return(Lst) } #--------------------------------------------------------------
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/local.multiple.regression.R
plot_local.multiple.correlation <- #3.1.0. function(Lst, xaxt="s") { ##Producing correlation plot if (xaxt[1]!="s"){ at <- xaxt[[1]] label <- xaxt[[2]] xaxt <- "n" } cor <- as.data.frame(Lst$cor) YmaxR <- Lst$YmaxR N <- length(YmaxR) xxnames <- names(Lst$data) par(mfrow=c(1,1), las=1, mar=c(5,4,4,2)+.1) ymin <- min(cor) ymax <- max(cor) mark <- paste0("\u00A9jfm-wavemulcor3.1.0_",Sys.time()," ") matplot(1:N, cor, type="n", xaxt=xaxt, ylim=c(ymin-0.1,ymax+0.1), xlab="", ylab="Local Multiple Correlation") abline(h=0) ##Add Straight horiz and vert Lines to a Plot matlines(1:N,cor, lty=c(1,2,2), col=c(1,2,2)) mtext(mark, side=1, line=-1, adj=1, col=rgb(0,0,0,.1),cex=.2) if (length(unique(YmaxR))==1) { mtext(xxnames[YmaxR][1], at=1, side=3, line=-1, cex=.8) } else { xvaru <- t(t(which(diff(sign(diff(as.matrix(cor[,"val"]))))==-2))+1) xvarl <- t(t(which(diff(sign(diff(as.matrix(cor[,"val"]))))==2))+1) xvar <- t(t(which(abs(diff(sign(diff(as.matrix(cor[,"val"])))))==2))+1) xvar2 <- xvar[-length(xvar)]+diff(xvar)/2 mtext(xxnames[YmaxR][xvaru], at=xvaru, side=3, line=-.5, cex=.5) mtext(xxnames[YmaxR][xvar2], at=xvar2, side=3, line=-1, cex=.5) mtext(xxnames[YmaxR][xvarl], at=xvarl, side=3, line=-1.5, cex=.5) } if (xaxt!="s") axis(side=1, at=at, labels=label) return() }
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/plot_local.multiple.correlation.R
plot_local.multiple.cross.correlation <- #3.1.0 function(Lst, lmax, xaxt="s"){ ##Producing correlation plot if (xaxt[1]!="s"){ at <- xaxt[[1]] label <- xaxt[[2]] xaxt <- "n" } val <- Lst$cor$vals low.ci <- Lst$cor$lower upp.ci <- Lst$cor$upper lag.max <- trunc((ncol(val)-1)/2) lag0 <- lag.max+1 YmaxR <- Lst$YmaxR N <- length(YmaxR) xxnames <- names(Lst$data) lag.labs <- c(paste("lead",lag.max:1),paste("lag",0:lag.max)) ymim <- -0.1 if (length(Lst$data)<3) ymim <- -1 par(mfcol=c(lmax+1,2), las=1, pty="m", mar=c(2,3,1,0)+.1, oma=c(1.2,1.2,0,0)) mark <- paste0("\u00A9jfm-wavemulcor3.1.0_",Sys.time()," ") for(i in c(-lmax:0,lmax:1)+lag0) { plot(1:N,val[,i], type="l", lty=1, ylim=c(ymim,1), xaxt=xaxt, xlab="", ylab="", main=lag.labs[i]) abline(h=0) ##Add Straight horiz lines(low.ci[,i], lty=1, col=2) ##Add Connected Line Segments to a Plot lines(upp.ci[,i], lty=1, col=2) mtext(mark, side=1, line=-1, adj=1, col=rgb(0,0,0,.1),cex=.2) # xvar <- seq(1,N,M) if (length(unique(YmaxR))==1) { mtext(xxnames[YmaxR][1], at=1, side=3, line=-1, cex=.8) } else { xvaru <- t(t(which(diff(sign(diff(as.matrix(val[,i]))))==-2))+1) xvarl <- t(t(which(diff(sign(diff(as.matrix(val[,i]))))==2))+1) # xvar <- t(t(which(abs(diff(sign(diff(as.matrix(val[,i])))))==2))+1) # xvar2 <- xvar[-length(xvar)]+diff(xvar)/2 mtext(xxnames[YmaxR][xvaru], at=xvaru, side=3, line=-.5, cex=.5) # mtext(xxnames[YmaxR][xvar2], at=xvar2, side=3, line=-1, cex=.5) mtext(xxnames[YmaxR][xvarl], at=xvarl, side=3, line=-1, cex=.5) } if (xaxt!="s") axis(side=1, at=at, labels=label) } par(las=0) mtext('time', side=1, outer=TRUE, adj=0.5) mtext('Local Multiple Cross-Correlation', side=2, outer=TRUE, adj=0.5) return() }
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/plot_local.multiple.cross.correlation.R
plot_local.multiple.cross.regression <- #3.1.0 function(Lst, lmax, nsig=2, xaxt="s"){ ##Producing regression plot # requireNamespace(magrittr) if (xaxt[1]!="s"){ at <- xaxt[[1]] label <- xaxt[[2]] xaxt <- "n" } val <- Lst$cor$vals reg.vals <- Lst$reg$rval[,,-1] #exclude constant reg.stdv <- Lst$reg$rstd[,,-1] reg.lows <- Lst$reg$rlow[,,-1] reg.upps <- Lst$reg$rupp[,,-1] reg.pval <- Lst$reg$rpva[,,-1] reg.order <- Lst$reg$rord[,,-1]-1 reg.order[reg.order==0] <- reg.vals[reg.order==0] <- #exclude dependent variable reg.stdv[reg.order==0] <- reg.lows[reg.order==0] <- reg.upps[reg.order==0] <- reg.pval[reg.order==0] <- NA lag.max <- trunc((ncol(val)-1)/2) lag0 <- lag.max+1 YmaxR <- Lst$YmaxR N <- length(YmaxR) xxnames <- names(Lst$data) lag.labs <- c(paste("lead",lag.max:1),paste("lag",0:lag.max)) reg.vars <- t(matrix(xxnames,length(Lst$data),N)) reg.sel <- reg.order<=nsig & reg.pval<=0.05 #select firs nsig 5%signif. predictors reg.vals.sig <- reg.vals*reg.sel reg.lows.sig <- reg.lows*reg.sel reg.upps.sig <- reg.upps*reg.sel # reg.pval.sig <- reg.pval*reg.sel reg.order.sig <- reg.order*reg.sel reg.vals.sig[reg.vals.sig==0] <- reg.lows.sig[reg.lows.sig==0] <- reg.upps.sig[reg.upps.sig==0] <- # reg.pval.sig[reg.pvals.sig==0] <- reg.order.sig[reg.order.sig==0] <- NA # requireNamespace(RColorBrewer) mycolors <- RColorBrewer::brewer.pal(n=8, name="Dark2") par(mfcol=c(lmax+1,2), las=1, pty="m", mar=c(2,3,1,0)+.1, oma=c(1.2,1.2,0,0)) ymin <- min(reg.vals,na.rm=TRUE) #head(unique(sort(reg.vals[,,-1])))[2] ymax <- max(reg.vals,na.rm=TRUE) mark <- paste0("\u00A9jfm-wavemulcor3.1.0_",Sys.time()," ") for(i in c(-lmax:0,lmax:1)+lag0) { matplot(1:N,reg.vals[,i,], ylim=c(ymin-0.1,ymax+0.1), type="n", xaxt=xaxt, lty=3, col=8, xlab="", ylab="", main=lag.labs[i]) # shade <- 1.96*reg.stdv %>% apply(1,max) for (j in dim(reg.stdv)[3]:1){ shade <- 1.96*reg.stdv[,i,j] polygon(c(1:N,rev(1:N)),c(-shade,rev(shade)), col=gray(0.8,alpha=0.2), border=NA) } matlines(1:N,reg.vals[,i,], lty=1, col=8) if(abs(ymax-ymin)<3) lo<-2 else lo<-4 abline(h=seq(floor(ymin),ceiling(ymax),length.out=lo),col=8) matlines(1:N, reg.vals.sig[,i,], lty=1, lwd=2, col=mycolors) matlines(1:N, reg.lows.sig[,i,], lty=2, col=mycolors) matlines(1:N, reg.upps.sig[,i,], lty=2, col=mycolors) mtext(mark, side=1, line=-1, adj=1, col=rgb(0,0,0,.1),cex=.2) col <- (reg.order[,i,]<=3)*1 +(reg.order[,i,]>3)*8 # xvar <- seq(1,N,M) xvar <- t(t(which(abs(diff(sign(diff(reg.vals[,i,]))))==2,arr.ind=TRUE))+c(1,0)) text(xvar, reg.vals[xvar,i,], labels=reg.vars[xvar,], col=col,cex=.3) text(xvar, reg.vals[xvar,i,], labels=reg.order[xvar,i,],pos=1, col=col,cex=.3) if (length(unique(YmaxR))==1) { mtext(xxnames[YmaxR][1], at=1, side=3, line=-1, cex=.5) } else { xvaru <- t(t(which(diff(sign(diff(as.matrix(val[,i]))))==-2))+1) xvarl <- t(t(which(diff(sign(diff(as.matrix(val[,i]))))==2))+1) # xvar <- t(t(which(abs(diff(sign(diff(as.matrix(val[,i])))))==2))+1) # xvar2 <- xvar[-length(xvar)]+diff(xvar)/2 mtext(xxnames[YmaxR][xvaru], at=xvaru, side=3, line=-.5, cex=.3) # mtext(xxnames[YmaxR][xvar2], at=xvar2, side=3, line=-1, cex=.5) mtext(xxnames[YmaxR][xvarl], at=xvarl, side=3, line=-1, cex=.3) } if (xaxt!="s") axis(side=1, at=at, labels=label) } par(las=0) mtext('time', side=1, outer=TRUE, adj=0.5) mtext('Local Multiple Cross-Regression', side=2, outer=TRUE, adj=0.5) return() }
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/plot_local.multiple.cross.regression.R
plot_local.multiple.regression <- #3.1.0. function(Lst, nsig=2, xaxt="s") { ##Producing regression plot # requireNamespace(magrittr) if (xaxt[1]!="s"){ at <- xaxt[[1]] label <- xaxt[[2]] xaxt <- "n" } cor <- as.data.frame(Lst$cor) reg.vals <- Lst$reg$rval[,-1] #exclude constant reg.stdv <- Lst$reg$rstd[,-1] reg.lows <- Lst$reg$rlow[,-1] reg.upps <- Lst$reg$rupp[,-1] reg.pval <- Lst$reg$rpva[,-1] reg.order <- Lst$reg$rord[,-1]-1 reg.order[reg.order==0] <- reg.vals[reg.order==0] <- #exclude dependent variable reg.stdv[reg.order==0] <- reg.lows[reg.order==0] <- reg.upps[reg.order==0] <- reg.pval[reg.order==0] <- NA YmaxR <- Lst$YmaxR N <- length(YmaxR) xxnames <- names(Lst$data) reg.vars <- t(matrix(xxnames,length(Lst$data),N)) reg.sel <- reg.order<=nsig & reg.pval<=0.05 #select firs nsig 5%signif. predictors reg.vals.sig <- reg.vals*reg.sel reg.lows.sig <- reg.lows*reg.sel reg.upps.sig <- reg.upps*reg.sel # reg.pval.sig <- reg.pval*reg.sel reg.order.sig <- reg.order*reg.sel reg.vals.sig[reg.vals.sig==0] <- reg.lows.sig[reg.lows.sig==0] <- reg.upps.sig[reg.upps.sig==0] <- # reg.pval.sig[reg.pvals.sig==0] <- reg.order.sig[reg.order.sig==0] <- NA # requireNamespace(RColorBrewer) mycolors <- RColorBrewer::brewer.pal(n=8, name="Dark2") par(mfrow=c(1,1), las=1, mar=c(5,4,4,2)+.1) ymin <- min(reg.vals.sig,na.rm=TRUE) ymax <- max(reg.vals.sig,na.rm=TRUE) mark <- paste0("\u00A9jfm-wavemulcor3.1.0_",Sys.time()," ") matplot(1:N,reg.vals, ylim=c(ymin-0.1,ymax+0.1), type="n", xaxt=xaxt, lty=3, col=8, xlab="", ylab="Local Multiple Regression") # shade <- 1.96*reg.stdv %>% apply(1,max) # for (i in 1:6){ # y1 <- yearcrisis[1,i]; y2 <- yearcrisis[2,i] # ndy <- ifelse (y2<20, 260, 79) #nof days in year = 5*52=260, except last year 2020=79 # days <- c(((y1-1)*260+1),((y2-1)*260+ndy)-10) # polygon(c(days,rev(days)), c(ymin-0.1,ymin-0.1,ymax+0.1,ymax+0.1), col="grey95", border=NA) # } for (i in ncol(reg.stdv):1){ shade <- 1.96*reg.stdv[,i] polygon(c(1:N,rev(1:N)),c(-shade,rev(shade)), col=gray(0.8,alpha=0.2), border=NA) } matlines(1:N,reg.vals, lty=1, col=8) # v <- (reg.vals*(reg.pval<=0.05) %>% replace(.==0,NA)) #%>% replace(.==-1.,NA) # matlines(1:N,v, lty=1, col=mycolors[8]) if(abs(ymax-ymin)<3) lo<-2 else lo<-4 abline(h=seq(floor(ymin),ceiling(ymax),length.out=lo),col=8) matlines(1:N, reg.vals.sig, lty=1, lwd=2, col=mycolors) matlines(1:N, reg.lows.sig, lty=2, col=mycolors) matlines(1:N, reg.upps.sig, lty=2, col=mycolors) mtext(mark, side=1, line=-1, adj=1, col=rgb(0,0,0,.1),cex=.2) col <- (reg.order.sig<=nsig)*1 +(reg.order.sig>=nsig)*8 # xvar <- seq(1,N,M) xvar <- t(t(which(abs(diff(sign(diff(reg.vals.sig))))==2,arr.ind=T))+c(1,0)) text(xvar[,1], reg.vals.sig[xvar], labels=reg.vars[xvar], col=col[xvar], cex=.8) text(xvar[,1], reg.vals.sig[xvar], labels=reg.order[xvar],pos=1, col=col[xvar],cex=.5) if (length(unique(YmaxR))==1) { mtext(xxnames[YmaxR][1], at=1, side=3, line=-1, cex=.8) } else { xvaru <- t(t(which(diff(sign(diff(as.matrix(cor[,"val"]))))==-2))+1) xvarl <- t(t(which(diff(sign(diff(as.matrix(cor[,"val"]))))==2))+1) xvar <- t(t(which(abs(diff(sign(diff(as.matrix(cor[,"val"])))))==2))+1) xvar2 <- xvar[-length(xvar)]+diff(xvar)/2 mtext(xxnames[YmaxR][xvaru], at=xvaru, side=3, line=-.5, cex=.5) mtext(xxnames[YmaxR][xvar2], at=xvar2, side=3, line=-1, cex=.5) mtext(xxnames[YmaxR][xvarl], at=xvarl, side=3, line=-1.5, cex=.5) } if (xaxt!="s") axis(side=1, at=at, labels=label) return() }
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/plot_local.multiple.regression.R
plot_wave.local.multiple.correlation <- #3.1.0. function(Lst, xaxt="s"){ ##Producing correlation plot if (xaxt[1]!="s"){ at <- xaxt[[1]] label <- xaxt[[2]] xaxt <- "n" } cor <- Lst$cor YmaxR <- Lst$YmaxR J <- length(Lst$YmaxR)-1 N <- length(Lst$data[[1]][[1]]) xxnames <- names(Lst$data) valnames <- c(paste("level",1:J),paste("s",J)) par(mfrow=c(ceiling((J+1)/2),2), las=1, pty="m", mar=c(2,3,1,0)+.1, oma=c(1.2,1.2,0,0)) mark <- paste0("\u00A9jfm-wavemulcor3.1.0_",Sys.time()," ") for(j in (J+1):1) { vj <- as.data.frame(cor[[j]]) #cbind(val[,j],lo[,j],up[,j]) ymin <- min(vj, na.rm=TRUE) ymax <- max(vj, na.rm=TRUE) matplot(1:N,vj, ylim=c(ymin-0.1,ymax+0.1), #before:dont remember why vj[,-2] here and lines(lo[,j]...) below type="l", lty=c(1,2,2), col=c(1,2,2), xaxt=xaxt, xlab="", ylab="", main=valnames[j]) if(xaxt!="s" & j<=(J+1)) {axis(side=1, at=at, labels=label)} mtext(mark, side=1, line=-1, adj=1, col=rgb(0,0,0,.1),cex=.2) abline(h=0) ##Add Straight horiz and vert Lines to a Plot if (length(unique(YmaxR[[j]]))==1) { mtext(xxnames[YmaxR[[j]][1]], at=1, side=3, line=-1, cex=.8) } else { xvaru <- t(t(which(diff(sign(diff(as.matrix(cor[[j]][["val"]]))))==-2))+1) xvarl <- t(t(which(diff(sign(diff(as.matrix(cor[[j]][["val"]]))))==2))+1) xvar <- t(t(which(abs(diff(sign(diff(as.matrix(cor[[j]][["val"]])))))==2))+1) xvar2 <- xvar[-length(xvar)]+diff(xvar)/2 mtext(xxnames[YmaxR[[j]][xvaru]], at=xvaru, side=3, line=-.5, cex=.5) mtext(xxnames[YmaxR[[j]][xvar2]], at=xvar2, side=3, line=-1, cex=.5) mtext(xxnames[YmaxR[[j]][xvarl]], at=xvarl, side=3, line=-1.5, cex=.5) } } par(las=0) # mtext('time', side=1, outer=TRUE, adj=0.5) mtext('Wavelet Local Multiple Correlation', side=2, outer=TRUE, adj=0.5) }
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/plot_wave.local.multiple.correlation.R
plot_wave.local.multiple.cross.correlation <- #3.1.0 function(Lst, lmax, lag.first=FALSE, xaxt="s", pdf.write=NULL) { ##Producing cross-correlation plot if (xaxt[1]!="s"){ at <- xaxt[[1]] label <- xaxt[[2]] xaxt <- "n" } blocki <- function(lab){ mark <- paste0("\u00A9jfm-wavemulcor3.1.0_",Sys.time()," ") plot(1:N,vj$vals[,i], type="l", lty=1, ylim=c(ymin,1), xaxt=xaxt, xlab="", ylab="", main=lab) abline(h=0) ##Add Straight horiz lines(vj$lower[,i], lty=1, col=2) ##Add Connected Line Segments to a Plot lines(vj$upper[,i], lty=1, col=2) mtext(mark, side=1, line=-1, adj=1, col=rgb(0,0,0,.1),cex=.2) # xvar <- seq(1,N,M) if (length(unique(YmaxR[[j]]))==1) { mtext(xxnames[YmaxR[[j]]][1], at=1, side=3, line=-1, cex=.5) } else { xvaru <- t(t(which(diff(sign(diff(as.matrix(vj$vals[,i]))))==-2))+1) xvarl <- t(t(which(diff(sign(diff(as.matrix(vj$vals[,i]))))==2))+1) # xvar <- t(t(which(abs(diff(sign(diff(as.matrix(vj$vals[,i])))))==2))+1) # xvar2 <- xvar[-length(xvar)]+diff(xvar)/2 mtext(xxnames[YmaxR[[j]]][xvaru], at=xvaru, side=3, line=-.5, cex=.3) # mtext(xxnames[YmaxR[[j]]][xvar2], at=xvar2, side=3, line=-1, cex=.3) mtext(xxnames[YmaxR[[j]]][xvarl], at=xvarl, side=3, line=-1, cex=.3) } if (xaxt!="s") axis(side=1, at=at, labels=label) } cor <- Lst$cor YmaxR <- Lst$YmaxR J <- length(Lst$YmaxR)-1 N <- length(Lst$data[[1]][[1]]) xxnames <- names(Lst$data) level.lab <- c(paste("level",1:J),paste("s",J)) lagnames <- c(paste("Lead",lmax:1),paste("Lag",0:lmax)) ymin <- -0.1 if (length(Lst$data)<3) ymin <- -1 if(lag.first){ for(i in c(-lmax:0,lmax:1)+lmax+1) { if (!is.null(pdf.write)) cairo_pdf(paste0("plot_",pdf.write,"_WLMCC_",lagnames[i],".pdf"), width=8.27,height=11.69) par(mfrow=c(ceiling((J+1)/2),2), las=1, pty="m", mar=c(2,3,1,0)+.1, oma=c(1.2,1.2,1.2,0)) for(j in (J+1):1) { vj <- cor[[j]] blocki(level.lab[j]) } par(las=0) mtext('time', side=1, outer=TRUE, adj=0.5) mtext('Wavelet Local Multiple Cross-Correlation', side=2, outer=TRUE, adj=0.5) mtext(lagnames[i], side=3, outer=TRUE, adj=0.5) if (!is.null(pdf.write)) dev.off() } } else{ for(j in 1:(J+1)) { vj <- cor[[j]] if (!is.null(pdf.write)) cairo_pdf(paste0(pdf.write,"_WLMCC_",level.lab[j],".pdf"), width=8.27,height=11.69) par(mfcol=c(lmax+1,2), las=1, pty="m", mar=c(2,3,1,0)+.1, oma=c(1.2,1.2,1.2,0)) for(i in c(-lmax:0,lmax:1)+lmax+1) { # for(i in 1:(2*lmax+1)) { blocki(lagnames[i]) } par(las=0) mtext('time', side=1, outer=TRUE, adj=0.5) mtext('Wavelet Local Multiple Cross-Correlation', side=2, outer=TRUE, adj=0.5) mtext(level.lab[j], side=3, outer=TRUE, adj=0.5) if (!is.null(pdf.write)) dev.off() } } return() }
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/plot_wave.local.multiple.cross.correlation.R
plot_wave.local.multiple.cross.regression <- #3.1.0 function(Lst, lmax, nsig=2, xaxt="s", pdf.write=NULL){ ##Producing cross-regression plot # requireNamespace(magrittr) if (xaxt[1]!="s"){ at <- xaxt[[1]] label <- xaxt[[2]] xaxt <- "n" } cor <- Lst$cor reg <- Lst$reg YmaxR <- Lst$YmaxR J <- length(Lst$YmaxR)-1 N <- length(Lst$data[[1]][[1]]) xxnames <- names(Lst$data) level.lab <- c(paste("level",1:J),paste("s",J)) lagnames <- c(paste("Lead",lmax:1),paste("Lag",0:lmax)) reg.vars <- t(matrix(xxnames,length(Lst$data),N)) # requireNamespace(RColorBrewer) mycolors <- RColorBrewer::brewer.pal(n=8, name="Dark2") reg.vars <- t(matrix(xxnames,length(Lst$data),N)) #xy.mulcor$xy.mulreg$vars[1:J,] for(j in 1:(J+1)) { vj <- lapply(reg[[j]],function(x){x[,,-1]}) #exclude constant vj$rord <- vj$rord-1 vj$rord[vj$rord==0] <- vj$rval[vj$rord==0] <- #exclude dependent variable vj$rstd[vj$rord==0] <- vj$rlow[vj$rord==0] <- vj$rupp[vj$rord==0] <- vj$rpva[vj$rord==0] <- NA vj.sel <- vj$rord<=nsig & vj$rpva<=0.05 #select firs nsig 5%signif. predictors vj$rval.sig <- vj$rval*vj.sel vj$rlow.sig <- vj$rlow*vj.sel vj$rupp.sig <- vj$rupp*vj.sel # vj$rpva.sig <- vj$rpva*vj.sel vj$rord.sig <- vj$rord*vj.sel vj$rval.sig[vj$rval.sig==0] <- vj$rlow.sig[vj$rlow.sig==0] <- vj$rupp.sig[vj$rupp.sig==0] <- vj$rord.sig[vj$rord.sig==0] <- NA if (!is.null(pdf.write)) cairo_pdf(paste0("plot_",pdf.write,"_WLMCR_",level.lab[j],".pdf"), width=8.27,height=11.69) mark <- paste0("\u00A9jfm-wavemulcor3.1.0_",Sys.time()," ") par(mfcol=c(lmax+1,2), las=1, pty="m", mar=c(2,3,1,0)+.1, oma=c(1.2,1.2,1.2,0)) ymin <- min(vj$rval,na.rm=TRUE) #head(unique(sort(vj$rval)))[2] ymax <- max(vj$rval,na.rm=TRUE) for(i in c(-lmax:0,lmax:1)+lmax+1) { matplot(1:N,vj$rval[,i,], ylim=c(ymin-0.1,ymax+0.1), type="n", xaxt=xaxt, lty=3, col=8, xlab="", ylab="", main=lagnames[i]) # shade <- 1.96*vj$rstd %>% apply(1,max) for (k in dim(vj$rstd)[3]:1){ shade <- 1.96*vj$rstd[,i,k] polygon(c(1:N,rev(1:N)),c(-shade,rev(shade)), col=gray(0.8,alpha=0.2), border=NA) } matlines(1:N,vj$rval[,i,], lty=1, col=8) if(abs(ymax-ymin)<3) lo<-2 else lo<-4 abline(h=seq(floor(ymin),ceiling(ymax),length.out=lo),col=8) matlines(1:N, vj$rval.sig[,i,], lty=1, lwd=2, col=mycolors) matlines(1:N, vj$rlow.sig[,i,], lty=2, col=mycolors) matlines(1:N, vj$rupp.sig[,i,], lty=2, col=mycolors) mtext(mark, side=1, line=-1, adj=1, col=rgb(0,0,0,.1),cex=.2) col <- (vj$rord[,i,]<=3)*1 +(vj$rord[,i,]>3)*8 # xvar <- seq(1,N,M) xvar <- t(t(which(abs(diff(sign(diff(vj$rval[,i,]))))==2,arr.ind=TRUE))+c(1,0)) text(xvar, vj$rval[xvar,i,2], labels=reg.vars[xvar,2], col=col,cex=.3) text(xvar, vj$rval[xvar,i,], labels=vj$rord[xvar,i,],pos=1, col=col,cex=.3) if (length(unique(YmaxR[[j]]))==1) { mtext(xxnames[YmaxR[[j]]][1], at=1, side=3, line=-1, cex=.5) } else { xvaru <- t(t(which(diff(sign(diff(as.matrix(vj$rval[,i,]))))==-2))+1) xvarl <- t(t(which(diff(sign(diff(as.matrix(vj$rval[,i,]))))==2))+1) # xvar <- t(t(which(abs(diff(sign(diff(as.matrix(vj$rval[,i])))))==2))+1) # xvar2 <- xvar[-length(xvar)]+diff(xvar)/2 mtext(xxnames[YmaxR[[j]]][xvaru], at=xvaru, side=3, line=-1, cex=.3) # mtext(xxnames[YmaxR[[j]]][xvar2], at=xvar2, side=3, line=-1, cex=.3) mtext(xxnames[YmaxR[[j]]][xvarl], at=xvarl, side=3, line=-1, cex=.3) } if (xaxt!="s") axis(side=1, at=at, labels=label) } par(las=0) mtext('time', side=1, outer=TRUE, adj=0.5) mtext('Wavelet Local Multiple Cross-Regression', side=2, outer=TRUE, adj=0.5) mtext(level.lab[j], side=3, outer=TRUE, adj=0.5) if (!is.null(pdf.write)) dev.off() } return() }
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/plot_wave.local.multiple.cross.regression.R
plot_wave.local.multiple.regression <- #3.1.0. function(Lst,nsig=2, xaxt="s"){ ##Producing regression plot # requireNamespace(magrittr) if (xaxt[1]!="s"){ at <- xaxt[[1]] label <- xaxt[[2]] xaxt <- "n" } cor <- Lst$cor reg <- Lst$reg YmaxR <- Lst$YmaxR J <- length(Lst$YmaxR)-1 N <- length(Lst$data[[1]][[1]]) xxnames <- names(Lst$data) reg.vars <- t(matrix(xxnames,length(Lst$data),N)) #xy.mulcor$xy.mulreg$vars[1:J,] valnames <- c(paste("level",1:J),paste("s",J)) # requireNamespace(RColorBrewer) mycolors <- RColorBrewer::brewer.pal(n=8, name="Dark2") par(mfrow=c(ceiling((J+1)/2),2), las=1, pty="m", mar=c(2,3,1,0)+.1, oma=c(1.2,1.2,0,0)) for (j in (J+1):1){ reg.vals <- reg[[j]]$rval[,-1] #exclude constant reg.stdv <- reg[[j]]$rstd[,-1] reg.lows <- reg[[j]]$rlow[,-1] reg.upps <- reg[[j]]$rupp[,-1] reg.pval <- reg[[j]]$rpva[,-1] reg.order <- reg[[j]]$rord[,-1]-1 reg.order[reg.order==0] <- reg.vals[reg.order==0] <- #exclude dependent variable reg.stdv[reg.order==0] <- reg.lows[reg.order==0] <- reg.upps[reg.order==0] <- reg.pval[reg.order==0] <- NA reg.sel <- reg.order<=nsig & reg.pval<=0.05 #select firs nsig 5%signif. predictors reg.vals.sig <- reg.vals*reg.sel reg.lows.sig <- reg.lows*reg.sel reg.upps.sig <- reg.upps*reg.sel # reg.pval.sig <- reg.pval*reg.sel reg.order.sig <- reg.order*reg.sel reg.vals.sig[reg.vals.sig==0] <- reg.lows.sig[reg.lows.sig==0] <- reg.upps.sig[reg.upps.sig==0] <- # reg.pval.sig[reg.pvals.sig==0] <- reg.order.sig[reg.order.sig==0] <- NA # ymin <- min(reg.lows,na.rm=TRUE) # ymax <- max(reg.upps,na.rm=TRUE) ymin <- min(reg.vals,na.rm=T) ymax <- max(reg.vals,na.rm=T) mark <- paste0("\u00A9jfm-wavemulcor3.1.0_",Sys.time()," ") matplot(1:N,reg.vals, ylim=c(ymin-0.1,ymax+0.1), type="n", xaxt=xaxt, lty=3, xlab="", ylab="", main=valnames[j], col=8) # shade <- 1.96*reg.stdv %>% apply(1,max) for (i in ncol(reg.stdv):1){ shade <- 1.96*reg.stdv[,i] polygon(c(1:N,rev(1:N)),c(-shade,rev(shade)), col=gray(0.8,alpha=0.2), border=NA) } matlines(1:N,reg.vals, lty=1, col=8) # v <- (reg.vals*(reg.pval<=0.05) %>% replace(.==0,NA)) #%>% replace(.==-1.,NA) # matlines(1:N,v, lty=1, col=mycolors[8]) if(abs(ymax-ymin)<3) lo<-2 else lo<-4 abline(h=seq(floor(ymin),ceiling(ymax),length.out=lo),col=8) matlines(1:N, reg.vals.sig, lty=1, lwd=2, col=mycolors) matlines(1:N, reg.lows.sig, lty=2, col=mycolors) matlines(1:N, reg.upps.sig, lty=2, col=mycolors) mtext(mark, side=1, line=-1, adj=1, col=rgb(0,0,0,.1),cex=.2) if(j<=(J+1) & xaxt!="s") {axis(side=1, at=at, labels=label)} col <- (reg.order.sig<=nsig)*1 +(reg.order.sig>=nsig)*8 # xvar <- seq(1,N,M) xvar <- t(t(which(abs(diff(sign(diff(reg.vals.sig))))==2,arr.ind=T))+c(1,0)) text(xvar[,1], reg.vals.sig[xvar], labels=reg.vars[xvar], col=col[xvar], cex=.8) text(xvar[,1], reg.vals.sig[xvar], labels=reg.order[xvar],pos=1, col=col[xvar],cex=.5) # if (length(unique(YmaxR[[j]]))==1) { # mtext(xxnames[YmaxR[[j]][1]], at=1, side=3, line=-1, cex=.8) # } else { # xvaru <- t(t(which(diff(sign(diff(as.matrix(cor[[j]][["val"]]))))==-2))+1) # xvarl <- t(t(which(diff(sign(diff(as.matrix(cor[[j]][["val"]]))))==2))+1) # xvar <- t(t(which(abs(diff(sign(diff(as.matrix(cor[[j]][["val"]])))))==2))+1) # xvar2 <- xvar[-length(xvar)]+diff(xvar)/2 # mtext(xxnames[YmaxR[[j]][xvaru]], at=xvaru, side=3, line=-.5, cex=.5) # mtext(xxnames[YmaxR[[j]][xvar2]], at=xvar2, side=3, line=-1, cex=.5) # mtext(xxnames[YmaxR[[j]][xvarl]], at=xvarl, side=3, line=-1.5, cex=.5) # } } par(las=0) # mtext('time', side=1, outer=TRUE, adj=0.5) mtext('Wavelet Local Multiple Regression', side=2, outer=TRUE, adj=0.5) return() }
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/plot_wave.local.multiple.regression.R
plot_wave.multiple.correlation <- #3.1.0. function(Lst) { ##Producing correlation plot J <- length(Lst$YmaxR)-1 xxnames <- names(Lst$data) cor <- Lst$xy.mulcor[1:J,] YmaxR <- Lst$YmaxR[1:J] par(mfrow=c(1,1), las=1, mar=c(5,4,4,2)+.1) ymin <- min(cor) ymax <- max(cor) mark <- paste0("\u00A9jfm-wavemulcor3.1.0_",Sys.time()," ") matplot(2^(0:(J-1)), cor, ylim=c(ymin-0.1,ymax+0.1), type="b", log="x", pch="*LU", cex=c(1.5,.75,.75), xaxt="n", lty=c(1,2,2), col=c(1,4,4), xlab="wavelet scale", ylab="Wavelet Multiple Correlation", cex.axis=0.75) mtext(mark, side=1, line=-1, adj=1, col=rgb(0,0,0,.1),cex=.2) abline(h=0) axis(side=1, at=2^(0:(J-1))) if (length(unique(YmaxR))==1) { mtext(xxnames[YmaxR][1], side=3, at=1, line=1, cex=.8) }else { mtext(xxnames[YmaxR], side=3, at=2^(0:J), line=-0.5, cex=.5) } return() }
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/plot_wave.multiple.correlation.R
plot_wave.multiple.cross.correlation <- #3.1.0. function (Lst, lmax, by=3) { ##Producing cross-correlation plot J <- length(Lst$YmaxR)-1 xxnames <- names(Lst$data) returns.cross.cor <- Lst$xy.mulcor returns.lower.ci <- Lst$ci.mulcor$lower returns.upper.ci <- Lst$ci.mulcor$upper YmaxR <- Lst$YmaxR valnames <- c(paste("level",1:J),paste("s",J)) par(mfrow=c(ceiling((J+1)/2),2), las=1, pty="m", mar=c(2,3,1,0)+.1, oma=c(1.2,1.2,0,0)) ymin <- -0.1 if (length(Lst$data)<3) ymin <- -1 mark <- paste0("\u00A9jfm-wavemulcor3.1.0_",Sys.time()," ") for(j in (J+1):1) { matplot((1:(2*lmax+1)),returns.cross.cor[j,], type="l", lty=1, ylim=c(ymin,1), xaxt="n", xlab="", ylab="", main=valnames[j]) if(j<3) {axis(side=1, at=seq(1,2*lmax+1,by=lmax/by), labels=seq(-lmax,lmax,by=lmax/by))} #axis(side=2, at=c(-.2, 0, .5, 1)) abline(h=0,v=lmax+1) ##Add Straight horiz and vert Lines to a Plot lines(returns.lower.ci[j,], lty=2, col=2) ##Add Connected Line Segments to a Plot lines(returns.upper.ci[j,], lty=2, col=2) mtext(mark, side=1, line=-1, adj=1, col=rgb(0,0,0,.1),cex=.2) if (length(unique(YmaxR))==1) { mtext(xxnames[YmaxR][1], side=3, at=1, line=-1, cex=.8) }else { mtext(xxnames[YmaxR], side=3, at=seq(1,2*lmax+1,by=lmax/by), line=-1, cex=.5) } } par(las=0) mtext('lag', side=1, outer=TRUE, adj=0.5) mtext('Wavelet Multiple Cross-Correlation', side=2, outer=TRUE, adj=0.5) return() }
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/plot_wave.multiple.cross.correlation.R
plot_wave.multiple.cross.regression <- #3.1.1 function(Lst, lmax, nsig=2, by=3) { ##Producing cross-regression plot # requireNamespace(magrittr) J <- length(Lst$YmaxR)-1 YmaxR <- Lst$YmaxR[1:J] xxnames <- names(Lst$data) vars <- t(matrix(xxnames,length(Lst$data),2*lmax+1)) #Lst$xy.mulreg$vars[1:J,] valnames <- c(paste("level",1:J),paste("s",J)) # requireNamespace(RColorBrewer) mycolors <- RColorBrewer::brewer.pal(n=8, name="Dark2") par(mfrow=c(ceiling((J+1)/2),2), las=1, pty="m", mar=c(2,3,1,0)+.1, oma=c(1.2,1.2,0,0)) mark <- paste0("\u00A9jfm-wavemulcor3.1.0_",Sys.time()," ") for(j in (J+1):1) { vals <- Lst$xy.mulreg$rval[[j]][,-1] #exclude constant stdv <- Lst$xy.mulreg$rstd[[j]][,-1] lows <- Lst$xy.mulreg$rlow[[j]][,-1] pval <- Lst$xy.mulreg$rpva[[j]][,-1] upps <- Lst$xy.mulreg$rupp[[j]][,-1] order <- Lst$xy.mulreg$rord[[j]][,-1]-1 order[order==0] <- vals[order==0] <- #exclude dependent variable stdv[order==0] <- lows[order==0] <- upps[order==0] <- pval[order==0] <- NA sel <- order<=nsig & pval<=0.05 #select firs nsig 5%signif. predictors vals.sig <- vals*sel lows.sig <- lows*sel upps.sig <- upps*sel # pval.sig <- pval*sel order.sig <- order*sel vals.sig[vals.sig==0] <- lows.sig[lows.sig==0] <- upps.sig[upps.sig==0] <- # pval.sig[pvals.sig==0] <- order.sig[order.sig==0] <- NA # ymin <- min(lows,na.rm=TRUE) # ymax <- max(upps,na.rm=TRUE) ymin <- min(vals,na.rm=TRUE) ymax <- max(vals,na.rm=TRUE) matplot(1:(2*lmax+1),vals, ylim=c(ymin-0.1,ymax+0.1), xaxt="n", type="n", lty=3, xlab="", ylab="", main=valnames[j], col=8) # shade <- 1.96*reg.stdv %>% apply(1,max) for (i in ncol(stdv):1){ shade <- 1.96*stdv[,i] polygon(c(1:(2*lmax+1),(2*lmax+1):1),c(-shade,rev(shade)), col=gray(0.8,alpha=0.2), border=NA) } matlines(1:(2*lmax+1),vals, lty=1, col=8) if(abs(ymax-ymin)<3) lo<-2 else lo<-4 abline(h=seq(floor(ymin),ceiling(ymax),length.out=lo),col=8) abline(v=lmax+1,col=8) matlines(1:(2*lmax+1),vals.sig, lty=1, lwd=2, col=mycolors) matlines(1:(2*lmax+1),lows.sig, lty=2, col=mycolors) matlines(1:(2*lmax+1),upps.sig, lty=2, col=mycolors) mtext(mark, side=1, line=-1, adj=1, col=rgb(0,0,0,.1),cex=.2) if(j<3) {axis(side=1, at=seq(1, 2*lmax+1, by=lmax/by), labels=seq(-lmax, lmax, by=lmax/by))} #axis(side=2, at=c(-.2, 0, .5, 1)) xvar <- seq(1,2*lmax+1,6) col <- (order<=3)*1 +(order>1)*8 text(xvar,vals[xvar,], labels=vars[xvar,], col=col[xvar,], cex=.5) text(xvar,vals[xvar,], labels=order[xvar,],pos=1, col=col[xvar,], cex=.5) if (length(unique(YmaxR))==1) { mtext(xxnames[YmaxR][1], side=3, at=1, line=-1, cex=.8) }else { mtext(xxnames[YmaxR], side=3, at=seq(1,2*lmax+1,by=lmax/by), line=-1, cex=.5) } } par(las=0) mtext('lag', side=1, outer=TRUE, adj=0.5) mtext('Wavelet Multiple Cross-Regression', side=2, outer=TRUE, adj=0.5) return() }
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/plot_wave.multiple.cross.regression.R
plot_wave.multiple.regression <- #3.1.0. function(Lst, nsig=2) { ##Producing regression plot # requireNamespace(magrittr) J <- length(Lst$YmaxR)-1 vals <- Lst$xy.mulreg$rval[1:J,-1] #exclude constant stdv <- Lst$xy.mulreg$rstd[1:J,-1] lows <- Lst$xy.mulreg$rlow[1:J,-1] upps <- Lst$xy.mulreg$rupp[1:J,-1] pval <- Lst$xy.mulreg$rpva[1:J,-1] order <- Lst$xy.mulreg$rord[1:J,-1]-1 order[order==0] <- NA #exclude dependent variable vars <- t(matrix(colnames(vals),length(Lst$data),J)) YmaxR <- Lst$YmaxR[1:J] xxnames <- names(Lst$data) sel <- order<=nsig & pval<=0.05 #select firs nsig 5%signif. predictors vals.sig <- vals*sel lows.sig <- lows*sel upps.sig <- upps*sel # pval.sig <- pval*sel order.sig <- order*sel vals.sig[vals.sig==0] <- lows.sig[lows.sig==0] <- upps.sig[upps.sig==0] <- # pval.sig[pvals.sig==0] <- order.sig[order.sig==0] <- NA # requireNamespace(RColorBrewer) mycolors <- RColorBrewer::brewer.pal(n = 8, name = "Dark2") par(mfrow=c(1,1), las=1, mar=c(5,4,4,2)+.1) ymin <- min(vals.sig,na.rm=TRUE) ymax <- max(vals.sig,na.rm=TRUE) x <- 2^(0:(J-1)) mark <- paste0("\u00A9jfm-wavemulcor3.1.0_",Sys.time()," ") matplot(x,vals, log="x", ylim=c(ymin-0.1,ymax+0.1), type="n", xaxt="n", lty=3, col=8, cex.axis=0.75, xlab="wavelet scale", ylab="Wavelet Multiple Regression") # shade <- 1.96*stdv %>% apply(1,max) for (i in ncol(stdv):1){ shade <- 1.96*stdv[,i] polygon(c(x,rev(x)),c(-shade,rev(shade)), col=gray(0.8,alpha=0.2), border=NA) } matlines(x,vals, log="x", lty=1, col=8) # v <- (vals*(pval<=0.05)) %>% replace(.==0,NA) #%>% replace(.==-1.,NA) # matlines(x,v, log="x",lty=1, col=mycolors[8]) # v <- (vals*(rbind(pval[-1,],tail(pval,1))<=0.05)) %>% replace(.==0,NA) #%>% replace(.==-1.,NA) # matlines(tail(x,2),v[(J-1):J,], log="x",lty=1, col=mycolors[8]) if(abs(ymax-ymin)<3) lo<-2 else lo<-4 mtext(mark, side=1, line=-1, adj=1, col=rgb(0,0,0,.1),cex=.2) abline(h=seq(floor(ymin),ceiling(ymax),length.out=lo),col=8) matlines(x, vals.sig, log="x", type="b", pch="*", lty=1, lwd=2, col=mycolors) matlines(x, lows.sig, log="x", type="b", pch="*",lty=2, col=mycolors) matlines(x, upps.sig, log="x", type="b", pch="*",lty=2, col=mycolors) col <- (order.sig<=nsig)*1 +(order.sig>=nsig)*8 # xvar <- seq(1,N,M) text(x, vals.sig, labels=vars, col=col, cex=.5) text(x, vals.sig, labels=order,pos=1, col=col, cex=.5) if (length(unique(YmaxR))==1) { mtext(xxnames[YmaxR][1],at=1, side=3, line=-1, outer=TRUE, cex=.8) }else { mtext(xxnames[YmaxR], at=2^(0:J), side=3, line=-0.5, cex=.5) } axis(side=1, at=x) return() }
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/plot_wave.multiple.regression.R
wave.local.multiple.correlation <- #2.2.2 function(xx, M, window="gauss", p=.975, ymaxr=NULL) { df.swap.list <- function(xx){ yy <- list() for (i in seq_along(xx[[1]])){ yy[[i]] <- as.data.frame( lapply(xx,'[[',i) ) names(yy[[i]]) <- names(xx) attr(yy[[i]],"wave") <- attr(xx[[1]],"class") } names(yy) <- names(xx[[1]]) return(yy) } d <- length(xx) #number of series dd <- d*(d-1)/2 #number of correlations l <- length(xx[[1]]) #number of scales J+1 (wavelet coefficients at levels 1 to J plus the scaling coeffs at level J+1) # N <- length(xx[[1]][[1]]) #number of observations wav <- attr(xx[[1]],"wavelet") if(substr(wav,1,1)=="h") {L<-2 } else if(substr(wav,1,1)=="d") {L<-as.numeric(substring(wav,2)) } else if(substr(wav,1,1)=="l") {L<-as.numeric(substring(wav,3))} else L<-8 ###IMPORTANT: must shift wave coeffs to left by L_i/2 at each level to be in phase with time series!!! (Getal, p.145) for(j in 1:d) { xx[[j]] <- phase.shift(xx[[j]], wav) } val <- lo <- up <- YmaxR <- list() x <- df.swap.list(xx) cat("\nlev:") for(i in 1:l) { cat(sprintf("%s",i)) out <- local.multiple.correlation(x[[i]], M, window=window, p=p, ymaxr=ymaxr) val[[i]] <- out$val lo[[i]] <- out$lo up[[i]] <- out$up YmaxR[[i]]<- out$YmaxR } val <- as.data.frame(val) lo <- as.data.frame(lo) up <- as.data.frame(up) YmaxR <- as.data.frame(YmaxR) names(val) <- names(lo) <- names(up) <- names(YmaxR) <- names(xx[[1]]) Lst <- list(val=val,lo=lo,up=up,YmaxR=YmaxR) return(Lst) } #--------------------------------------------------------------
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/wave.local.multiple.correlation.R
wave.local.multiple.cross.correlation <- #2.3.0 function(xx, M, window="gauss", lag.max=NULL, p=.975, ymaxr=NULL) { df.swap.list <- function(xx){ yy <- list() for (i in seq_along(xx[[1]])){ yy[[i]] <- as.data.frame( lapply(xx,'[[',i) ) names(yy[[i]]) <- names(xx) attr(yy[[i]],"wave") <- attr(xx[[1]],"class") } names(yy) <- names(xx[[1]]) return(yy) } d <- length(xx) #number of series dd <- d*(d-1)/2 #number of correlations l <- length(xx[[1]]) #number of scales J+1 (wavelet coefficients at levels 1 to J plus the scaling coeffs at level J+1) # N <- length(xx[[1]][[1]]) #number of observations wav <- attr(xx[[1]],"wavelet") if(substr(wav,1,1)=="h") {L<-2 } else if(substr(wav,1,1)=="d") {L<-as.numeric(substring(wav,2)) } else if(substr(wav,1,1)=="l") {L<-as.numeric(substring(wav,3))} else L<-8 ###IMPORTANT: must shift wave coeffs to left by L_i/2 at each level to be in phase with time series!!! (Getal, p.145) for(j in 1:d) { xx[[j]] <- phase.shift(xx[[j]], wav) } val <- lo <- up <- YmaxR <- list() x <- df.swap.list(xx) cat("\nlev:") for(i in 1:l) { cat(sprintf("%s",i)) out <- local.multiple.cross.correlation(x[[i]], M, window=window, lag.max=lag.max, p=p, ymaxr=ymaxr) val[[i]] <- as.data.frame(out$val) lo[[i]] <- as.data.frame(out$lo) up[[i]] <- as.data.frame(out$up) YmaxR[[i]]<- as.vector(out$YmaxR) } names(val) <- names(lo) <- names(up) <- names(YmaxR) <- names(xx[[1]]) Lst <- list(val=val,lo=lo,up=up,YmaxR=YmaxR) return(Lst) } #--------------------------------------------------------------
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/wave.local.multiple.cross.correlation.R
wave.local.multiple.cross.regression <- #3.0.0 function(xx, M, window="gauss", lag.max=NULL, p=.975, ymaxr=NULL) { df.swap.list <- function(xx){ yy <- list() for (i in seq_along(xx[[1]])){ yy[[i]] <- as.data.frame( lapply(xx,'[[',i) ) names(yy[[i]]) <- names(xx) attr(yy[[i]],"wave") <- attr(xx[[1]],"class") } names(yy) <- names(xx[[1]]) return(yy) } d <- length(xx) #number of series dd <- d*(d-1)/2 #number of correlations l <- length(xx[[1]]) #number of scales J+1 (wavelet coefficients at levels 1 to J plus the scaling coeffs at level J+1) # N <- length(xx[[1]][[1]]) #number of observations wav <- attr(xx[[1]],"wavelet") if(substr(wav,1,1)=="h") {L<-2 } else if(substr(wav,1,1)=="d") {L<-as.numeric(substring(wav,2)) } else if(substr(wav,1,1)=="l") {L<-as.numeric(substring(wav,3))} else L<-8 ###IMPORTANT: must shift wave coeffs to left by L_i/2 at each level to be in phase with time series!!! (Getal, p.145) for(j in 1:d) { xx[[j]] <- phase.shift(xx[[j]], wav) } cor <- reg <- YmaxR <- list() x <- df.swap.list(xx) cat("\nlev:") for(i in 1:l) { cat(sprintf("%s",i)) out <- local.multiple.cross.regression(x[[i]], M, window=window, lag.max=lag.max, p=p, ymaxr=ymaxr) cor[[i]] <- out$cor reg[[i]] <- out$reg YmaxR[[i]] <- out$YmaxR } YmaxR <- as.data.frame(YmaxR) names(cor) <- names(reg) <- names(YmaxR) <- names(xx[[1]]) Lst <- list(cor=cor,reg=reg,YmaxR=YmaxR,data=xx) return(Lst) } #--------------------------------------------------------------
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/wave.local.multiple.cross.regression.R
wave.local.multiple.regression <- #3.0.0 function(xx, M, window="gauss", p=.975, ymaxr=NULL) { df.swap.list <- function(xx){ yy <- list() for (i in seq_along(xx[[1]])){ yy[[i]] <- as.data.frame( lapply(xx,'[[',i) ) names(yy[[i]]) <- names(xx) attr(yy[[i]],"wave") <- attr(xx[[1]],"class") } names(yy) <- names(xx[[1]]) return(yy) } d <- length(xx) #number of series dd <- d*(d-1)/2 #number of correlations l <- length(xx[[1]]) #number of scales J+1 (wavelet coefficients at levels 1 to J plus the scaling coeffs at level J+1) # N <- length(xx[[1]][[1]]) #number of observations wav <- attr(xx[[1]],"wavelet") if(substr(wav,1,1)=="h") {L<-2 } else if(substr(wav,1,1)=="d") {L<-as.numeric(substring(wav,2)) } else if(substr(wav,1,1)=="l") {L<-as.numeric(substring(wav,3))} else L<-8 ###IMPORTANT: must shift wave coeffs to left by L_i/2 at each level to be in phase with time series!!! (Getal, p.145) for(j in 1:d) { xx[[j]] <- phase.shift(xx[[j]], wav) } cor <- reg <- YmaxR <- list() x <- df.swap.list(xx) cat("\nlev:") for(i in 1:l) { cat(sprintf("%s",i)) out <- local.multiple.regression(x[[i]], M, window=window, p=p, ymaxr=ymaxr) cor[[i]] <- out$cor reg[[i]] <- out$reg YmaxR[[i]]<- out$YmaxR } YmaxR <- as.data.frame(YmaxR) names(cor) <- names(reg) <- names(YmaxR) <- names(xx[[1]]) Lst <- list(cor=cor,reg=reg,YmaxR=YmaxR,data=xx) return(Lst) } #--------------------------------------------------------------
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/wave.local.multiple.regression.R
wave.multiple.correlation <- #2.2.3 function(xx, N=length(xx[[1]][[1]]), p = .975, ymaxr=NULL) { sum.of.squares <- function(x) { sum(x^2, na.rm=TRUE) / sum(!is.na(x)) } sum.of.not.squares <- function(x) { sum(x, na.rm=TRUE) / sum(!is.na(x)) } d <- length(xx) #number of series dd <- d*(d-1)/2 #number of correlations l <- length(xx[[1]]) #number of scales J+1 (wavelet coefficients at levels 1 to J plus the scaling coeffs at level J+1) # N <- length(xx[[1]][[1]]) #number of observations x.var <- vector("list", d) for(j in 1:d) { x.var[[j]] <- unlist(lapply(xx[[j]], sum.of.squares)) } xy.cor <- vector("list", dd) xy <- vector("list", l) jk <- 0 for(k in 1:(d-1)) { for(j in (k+1):d) { jk <- jk+1 for(i in 1:l) { xy[[i]] <- as.vector(xx[[j]][[i]] * xx[[k]][[i]]) } xy.cov <- unlist(lapply(xy, sum.of.not.squares)) xy.cor[[jk]] <- xy.cov / sqrt(x.var[[j]] * x.var[[k]]) }} xy.cor.vec <- matrix(unlist(xy.cor),l,dd) xy.mulcor <- vector("numeric", l) ##xy.mulcor <- matrix(NA,l,1,dimnames=list(names(xy.cor[[1]]))) YmaxR <- vector("numeric",l) for(i in 1:l) { r <- xy.cor.vec[i,] P <- diag(d)/2 P[lower.tri(P)] <- r P <- P+t(P) Pidiag <- diag(solve(P)) if(is.null(ymaxr)) { YmaxR[i] <- Pimax <- which.max(Pidiag) ## detect i | x[i] on rest x gives max R2 } else {YmaxR[i] <- Pimax <- ymaxr} sgnr <- 1 if (dd==1) sgnr <- sign(r) xy.mulcor[[i]] <- sgnr*sqrt(1-1/Pidiag[Pimax]) ## max(sqrt(1-1/diag(solve(P)))) } n <- trunc(N/2^(1:l)) sqrtn <- sapply(n,function(x){if (x>=3) sqrt(x-3) else NaN}) alow <- atanh(xy.mulcor)-qnorm(p)/sqrtn if (dd>1) alow <- pmax(alow,0) ## wavemulcor can only be negative in bivariate case aupp <- atanh(xy.mulcor)+qnorm(p)/sqrtn out <- data.frame( wavemulcor=xy.mulcor, lower=tanh(alow), upper=tanh(aupp) ) Lst <- list(xy.mulcor=as.matrix(out),YmaxR=YmaxR) return(Lst) }
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/wave.multiple.correlation.R
wave.multiple.cross.correlation <- #2.2.3 function(xx, lag.max=NULL, p=.975, ymaxr=NULL) { sum.of.squares <- function(x) { sum(x^2, na.rm=TRUE) / sum(!is.na(x)) } sum.of.not.squares <- function(x) { sum(x, na.rm=TRUE) / sum(!is.na(x)) } d <- length(xx) #number of series dd <- d*(d-1)/2 #number of correlations l <- length(xx[[1]]) #number of scales J+1 (wavelet coefficients at levels 1 to J plus the scaling coeffs at level J+1) N <- length(xx[[1]][[1]]) #number of observations if(is.null(lag.max)) {lag.max <- trunc(sqrt(length(xx[[1]][[l]]))/2)} lm <- min(length(xx[[1]][[l]])-1, lag.max, na.rm=TRUE) x.var <- vector("list", d) for(j in 1:d) { x.var[[j]] <- unlist(lapply(xx[[j]], sum.of.squares)) } xy.cor <- vector("list", dd) xy <- vector("list", l) jk <- 0 for(k in 1:(d-1)) { for(j in (k+1):d) { jk <- jk+1 for(i in 1:l) { xy[[i]] <- as.vector(xx[[j]][[i]] * xx[[k]][[i]]) } xy.cov <- unlist(lapply(xy, sum.of.not.squares)) xy.cor[[jk]] <- xy.cov / sqrt(x.var[[j]] * x.var[[k]]) }} xy.cor.vec <- matrix(unlist(xy.cor),l,dd) xy.mulcor <- matrix(0, l, 2*lm+1) ## Note: [ 1 2 ... lm-1 lm | lm+1 | lm+2 ... 2*lm 2*lm+1 ] ## [ ...Pimax var leads | 0 | Pimax var lags... ] YmaxR <- vector("numeric",l) for(i in 1:l) { r <- xy.cor.vec[i,] P <- diag(d)/2 P[lower.tri(P)] <- r P <- P+t(P) Pidiag <- diag(solve(P)) if(is.null(ymaxr)) { YmaxR[i] <- Pimax <- which.max(Pidiag) ## detect i | x[i] on rest x gives max R2 } else {YmaxR[i] <- Pimax <- ymaxr} sgnr <- 1 if (dd==1) sgnr <- sign(r) xy.mulcor[i,lm+1] <- sgnr*sqrt(1-1/Pidiag[Pimax]) ## lag=0: this must be same as in wave.multiple.correlation if(lm>0) { x <- sapply(xx[-Pimax],'[[',i) y <- sapply(xx[Pimax],'[[',i) z <- y vlength <- length(y) for(j in 1:lm) { ## now we obtain R2 of var[Pimax] with lagged values y <- c(y[2:vlength], NA) z <- c(NA, z[1:(vlength-1)]) lm_yx <- summary(lm(formula = y ~ x)) lm_zx <- summary(lm(formula = z ~ x)) sgnr <- 1 if (dd==1) sgnr <- sign(cor(y,x,use="complete.obs")) xy.mulcor[i,lm+1+j] <- sgnr*sqrt( lm_yx$r.squared ) ## Note: var[Pimax] lags behind the others: y[t+j]<--x[t]hat sgnr <- 1 if (dd==1) sgnr <- sign(cor(z,x,use="complete.obs")) xy.mulcor[i,lm+1-j] <- sgnr*sqrt( lm_zx$r.squared ) ## Note: var[Pimax] leads the others: x[t]hat<--z[t-j] }} } # end of for(i in 1:l) loop lags <- length(-lm:lm) oldw <- getOption("warn") options(warn = -1) sqrtn <- sqrt(matrix(trunc(N/2^(1:l)), nrow=l, ncol=lags) - 3) options(warn = oldw) alow <- atanh(xy.mulcor)-qnorm(p)/sqrtn if (dd>1) alow <- pmax(alow,0) ## wavemulcor can only be negative in bivariate case aupp <- atanh(xy.mulcor)+qnorm(p)/sqrtn ci.mulcor <- list( lower=tanh(alow), upper=tanh(aupp) ) Lst <- list(xy.mulcor=xy.mulcor,ci.mulcor=ci.mulcor,YmaxR=YmaxR) return(Lst) }
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/wave.multiple.cross.correlation.R
wave.multiple.cross.regression <- #3.0.0 function(xx, lag.max=NULL, p = .975, ymaxr=NULL) { sum.of.squares <- function(x) { sum(x^2, na.rm=TRUE) / sum(!is.na(x)) } sum.of.not.squares <- function(x) { sum(x, na.rm=TRUE) / sum(!is.na(x)) } asnum <- function(x){setNames(as.numeric(x),names(x))} d <- length(xx) #number of series dd <- d*(d-1)/2 #number of correlations l <- length(xx[[1]]) #number of scales J+1 (wavelet coefficients at levels 1 to J plus the scaling coeffs at level J+1) N <- length(xx[[1]][[1]]) #number of observations if(is.null(lag.max)) {lag.max <- trunc(sqrt(length(xx[[1]][[l]]))/2)} lm <- min(length(xx[[1]][[l]])-1, lag.max, na.rm=TRUE) x.var <- vector("list", d) for(j in 1:d) { x.var[[j]] <- unlist(lapply(xx[[j]], sum.of.squares)) } xy.cor <- vector("list", dd) xy <- vector("list", l) jk <- 0 for(k in 1:(d-1)) { for(j in (k+1):d) { jk <- jk+1 for(i in 1:l) { xy[[i]] <- as.vector(xx[[j]][[i]] * xx[[k]][[i]]) } xy.cov <- unlist(lapply(xy, sum.of.not.squares)) xy.cor[[jk]] <- xy.cov / sqrt(x.var[[j]] * x.var[[k]]) }} xy.cor.vec <- matrix(unlist(xy.cor),l,dd) xy.mulcor <- matrix(0, l, 2*lm+1) rval <- rstd <- rlow <- rupp <- rtst <- rpva <- rord <- vector("list", l) # xy.mulreg <- lapply(vector("list", l), function(x) {vector("list",2*lm+1)}) ## Note: [ 1 2 ... lm-1 lm | lm+1 | lm+2 ... 2*lm 2*lm+1 ] ## [ ...Pimax var leads | 0 | Pimax var lags... ] YmaxR <- vector("numeric",l) for(i in 1:l) { xy.mulreg <- vector("list",2*lm+1) r <- xy.cor.vec[i,] P <- diag(d)/2 P[lower.tri(P)] <- r P <- P+t(P) Pidiag <- diag(solve(P)) if(is.null(ymaxr)) { YmaxR[i] <- Pimax <- which.max(Pidiag) ## detect i | x[i] on rest x gives max R2 } else {YmaxR[i] <- Pimax <- ymaxr} sgnr <- 1 if (dd==1) sgnr <- sign(r) xy.mulcor[i,lm+1] <- sgnr*sqrt(1-1/Pidiag[Pimax]) ## lag=0: this must be same as in wave.multiple.correlation x0 <- sapply(xx[-Pimax],'[[',i) y0 <- sapply(xx[Pimax],'[[',i) depvar <- matrix(c(-1,0,Inf,0),1,4) if (is.null(names(xx))) row.names(depvar) <- "Y" else row.names(depvar) <- names(xx[Pimax]) z0 <- summary(lm(formula = y0 ~ x0))$coefficients if(Pimax<nrow(z0)) z1 <- z0[(Pimax+1):nrow(z0),,drop=FALSE] else z1 <- NULL z0 <- rbind(z0[1:Pimax,,drop=FALSE], depvar, z1) if (is.null(names(xx))) row.names(z0)[1] <- "b0" else row.names(z0) <- c("b0",names(xx)) xy.mulreg[[lm+1]] <- z0 # xy.mulreg <- z[order(z[,4]),1:2] #coefficients (and their stdvs) ordered from most to least significant ## lag=0: this must be same as in wave.multiple.regression if(lm>0) { x <- x0 z <- y <- y0 vlength <- length(y) for(j in 1:lm) { ## now we obtain R2 of var[Pimax] with lagged values y <- c(y[2:vlength], NA) z <- c(NA, z[1:(vlength-1)]) lm_yx <- summary(lm(formula = y ~ x)) lm_zx <- summary(lm(formula = z ~ x)) sgnr <- 1 if (dd==1) sgnr <- sign(cor(y,x,use="complete.obs")) xy.mulcor[i,lm+1+j] <- sgnr*sqrt( lm_yx$r.squared ) ## Note: var[Pimax] lags behind the others: y[t+j]<--x[t]hat zjr <- lm_yx$coefficients if(Pimax<nrow(zjr)) z1 <- zjr[(Pimax+1):nrow(zjr),,drop=FALSE] else z1 <- NULL zjr <- rbind(zjr[1:Pimax,,drop=FALSE], depvar, z1) if (is.null(names(xx))) row.names(zjr)[1] <- "b0" else row.names(zjr) <- c("b0",names(xx)) xy.mulreg[[lm+1+j]] <- zjr sgnr <- 1 if (dd==1) sgnr <- sign(cor(z,x,use="complete.obs")) xy.mulcor[i,lm+1-j] <- sgnr*sqrt( lm_zx$r.squared ) ## Note: var[Pimax] leads the others: x[t]hat<--z[t-j] zjl <- lm_zx$coefficients if(Pimax<nrow(zjl)) z1 <- zjl[(Pimax+1):nrow(zjl),,drop=FALSE] else z1 <- NULL zjl <- rbind(zjl[1:Pimax,,drop=FALSE], depvar, z1) if (is.null(names(xx))) row.names(zjl)[1] <- "b0" else row.names(zjl) <- c("b0",names(xx)) xy.mulreg[[lm+1-j]] <- zjl }} rval[[i]] <- lapply(xy.mulreg, function(x){x[,'Estimate']}) rstd[[i]] <- lapply(xy.mulreg, function(x){x[,'Std. Error']}) rlow[[i]] <- lapply(xy.mulreg, function(x){x[,'Estimate']-qt(p,N-d)*x[,'Std. Error']}) rupp[[i]] <- lapply(xy.mulreg, function(x){x[,'Estimate']+qt(p,N-d)*x[,'Std. Error']}) rtst[[i]] <- lapply(xy.mulreg, function(x){x[,'t value']}) rpva[[i]] <- lapply(xy.mulreg, function(x){x[,'Pr(>|t|)']}) rord[[i]] <- lapply(xy.mulreg, function(x){match(abs(x[,'t value']),sort(abs(x[,'t value']),decreasing=TRUE))}) rval[[i]] <- t(sapply(rval[[i]],asnum)) rstd[[i]] <- t(sapply(rstd[[i]],asnum)) rlow[[i]] <- t(sapply(rlow[[i]],asnum)) rupp[[i]] <- t(sapply(rupp[[i]],asnum)) rtst[[i]] <- t(sapply(rtst[[i]],asnum)) rpva[[i]] <- t(sapply(rpva[[i]],asnum)) rord[[i]] <- t(sapply(rord[[i]],asnum)) } # end for(i in 1:l) loop lags <- length(-lm:lm) oldw <- getOption("warn") options(warn = -1) sqrtn <- sqrt(matrix(trunc(N/2^(1:l)), nrow=l, ncol=lags) - 3) options(warn = oldw) alow <- atanh(xy.mulcor)-qnorm(p)/sqrtn if (dd>1) alow <- pmax(alow,0) ## wavemulcor can only be negative in bivariate case aupp <- atanh(xy.mulcor)+qnorm(p)/sqrtn ci.mulcor <- list( lower=tanh(alow), upper=tanh(aupp) ) xy.mulreg <- list( rval=rval, rstd=rstd, rlow=rlow, rupp=rupp, rtst=rtst, rord=rord, rpva=rpva ) xy.mulreg <- lapply(xy.mulreg,setNames,names(xx[[1]])) #) #vars=t(sapply(rval,names)) --> names of variables: useful if somehow reordered Lst <- list(xy.mulcor=xy.mulcor,ci.mulcor=ci.mulcor,xy.mulreg=xy.mulreg,YmaxR=YmaxR,data=xx) return(Lst) }
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/wave.multiple.cross.regression.R
wave.multiple.regression <- #3.0.0 function(xx, N=length(xx[[1]][[1]]), p=.975, ymaxr=NULL) { sum.of.squares <- function(x) { sum(x^2, na.rm=TRUE) / sum(!is.na(x)) } sum.of.not.squares <- function(x) { sum(x, na.rm=TRUE) / sum(!is.na(x)) } d <- length(xx) #number of series dd <- d*(d-1)/2 #number of correlations l <- length(xx[[1]]) #number of scales J+1 (wavelet coefficients at levels 1 to J plus the scaling coeffs at level J+1) # N <- length(xx[[1]][[1]]) #number of observations x.var <- vector("list", d) for(j in 1:d) { x.var[[j]] <- unlist(lapply(xx[[j]], sum.of.squares)) } xy.cor <- vector("list", dd) xy <- vector("list", l) jk <- 0 for(k in 1:(d-1)) { for(j in (k+1):d) { jk <- jk+1 for(i in 1:l) { xy[[i]] <- as.vector(xx[[j]][[i]] * xx[[k]][[i]]) } xy.cov <- unlist(lapply(xy, sum.of.not.squares)) xy.cor[[jk]] <- xy.cov / sqrt(x.var[[j]] * x.var[[k]]) }} xy.cor.vec <- matrix(unlist(xy.cor),l,dd) xy.mulcor <- vector("numeric", l) ##xy.mulcor <- matrix(NA,l,1,dimnames=list(names(xy.cor[[1]]))) xy.mulreg <- vector("list", l) YmaxR <- vector("numeric",l) for(i in 1:l) { r <- xy.cor.vec[i,] P <- diag(d)/2 P[lower.tri(P)] <- r P <- P+t(P) Pidiag <- diag(solve(P)) if(is.null(ymaxr)) { YmaxR[i] <- Pimax <- which.max(Pidiag) ## detect i | x[i] on rest x gives max R2 } else {YmaxR[i] <- Pimax <- ymaxr} sgnr <- 1 if (dd==1) sgnr <- sign(r) xy.mulcor[[i]] <- sgnr*sqrt(1-1/Pidiag[Pimax]) ## max(sqrt(1-1/diag(solve(P)))) x <- sapply(xx[-Pimax],'[[',i) y <- sapply(xx[Pimax],'[[',i) depvar <- matrix(c(-1,0,Inf,0),1,4) if (is.null(names(xx))) row.names(depvar) <- "Y" else row.names(depvar) <- names(xx[Pimax]) z <- summary(lm(formula = y ~ x))$coefficients if(Pimax<nrow(z)) zr <- z[(Pimax+1):nrow(z),,drop=FALSE] else zr<-NULL z <- rbind(z[1:Pimax,,drop=FALSE], depvar, zr) if (is.null(names(xx))) row.names(z)[1] <- "b0" else row.names(z) <- c("b0",names(xx)) xy.mulreg[[i]] <- z # xy.mulreg[[i]] <- z[order(z[,4]),1:2] #coefficients (and their stdvs) ordered from most to least significant } n <- trunc(N/2^(1:l)) sqrtn <- sapply(n,function(x){if (x>=3) sqrt(x-3) else NaN}) alow <- atanh(xy.mulcor)-qnorm(p)/sqrtn if (dd>1) alow <- pmax(alow,0) aupp <- atanh(xy.mulcor)+qnorm(p)/sqrtn outcor <- data.frame( wavemulcor=xy.mulcor, lower=tanh(alow), upper=tanh(aupp) ) rval <- lapply(xy.mulreg, function(x){x[,'Estimate']}) rstd <- lapply(xy.mulreg, function(x){x[,'Std. Error']}) rlow <- lapply(xy.mulreg, function(x){x[,'Estimate']-qt(p,N-d)*x[,'Std. Error']}) rupp <- lapply(xy.mulreg, function(x){x[,'Estimate']+qt(p,N-d)*x[,'Std. Error']}) rtst <- lapply(xy.mulreg, function(x){x[,'t value']}) rpva <- lapply(xy.mulreg, function(x){x[,'Pr(>|t|)']}) rord <- lapply(xy.mulreg, function(x){match(abs(x[,'t value']),sort(abs(x[,'t value']),decreasing=TRUE))}) asnum <- function(x){setNames(as.numeric(x),names(x))} outreg <- list( rval=t(sapply(rval,asnum)), rstd=t(sapply(rstd,asnum)), rlow=t(sapply(rlow,asnum)), rupp=t(sapply(rupp,asnum)), rtst=t(sapply(rtst,asnum)), rord=t(sapply(rord,asnum)), rpva=t(sapply(rpva,asnum)) ) #) #vars=t(sapply(rval,names)) --> names of variables: useful if somehow reordered Lst <- list(xy.mulcor=as.matrix(outcor),xy.mulreg=outreg,YmaxR=YmaxR,data=xx) return(Lst) }
/scratch/gouwar.j/cran-all/cranData/wavemulcor/R/wave.multiple.regression.R
## ----knitr_setup, include = FALSE--------------------------------------------- knitr::opts_chunk$set( echo = TRUE, message=FALSE, results = "asis", fig.width=7, fig.height=5, fig.asp=0.5, collapse = TRUE, comment = "#>" # dev = 'pdf' ) ## ----setup, include = FALSE--------------------------------------------------- rm(list = ls()) # clear objects graphics.off() # close graphics windows # library(wavemulcor) data(exchange) returns <- diff(log(as.matrix(exchange))) returns <- ts(returns, start=1970, freq=12) N <- dim(returns)[1] ## ----label=wmc_code,echo=c(-1:-3,-6:-8)--------------------------------------- ## Based on data from Figure 7.8 in Gencay, Selcuk and Whitcher (2001) ## plus one random series. wf <- "d4" J <- trunc(log2(N))-3 set.seed(140859) demusd.modwt <- brick.wall(modwt(returns[,"DEM.USD"], wf, J), wf) jpyusd.modwt <- brick.wall(modwt(returns[,"JPY.USD"], wf, J), wf) xrand.modwt <- brick.wall(modwt(rnorm(length(returns[,"DEM.USD"])), wf, J), wf) xx <- list(demusd.modwt, jpyusd.modwt, xrand.modwt) names(xx) <- c("DEM.USD","JPY.USD","rand") Lst <- wave.multiple.correlation(xx) ## ----label=plot_wmc, echo=-1:-2, results='hide'------------------------------- ##Producing correlation plot Lst <- wave.multiple.regression(xx) plot_wave.multiple.correlation(Lst) ## ----label=wmr_code----------------------------------------------------------- Lst <- wave.multiple.regression(xx) ## ----label=plot_wmr, echo=-1, results='hide'---------------------------------- ##Producing regression plot plot_wave.multiple.regression(Lst) # nsig=2) ## ----label=wmcr_code,echo=-5:-6----------------------------------------------- wf <- "d4" J <- trunc(log2(N))-3 lmax <- 36 set.seed(140859) demusd.modwt <- brick.wall(modwt(returns[,"DEM.USD"], wf, J), wf) jpyusd.modwt <- brick.wall(modwt(returns[,"JPY.USD"], wf, J), wf) rand.modwt <- brick.wall(modwt(rnorm(length(returns[,"DEM.USD"])), wf, J), wf) # --------------------------- xx <- list(demusd.modwt, jpyusd.modwt, rand.modwt) names(xx) <- c("DEM.USD","JPY.USD","rand") Lst <- wave.multiple.cross.regression(xx, lmax) ## ----label=heat_wmcc, echo=-1, results='hide'--------------------------------- ##Producing correlation heat map heatmap_wave.multiple.cross.correlation(Lst, lmax) #, by=3, ci=NULL, pdf.write=NULL) ## ----label=plot_wmcc, echo=-1, results='hide'--------------------------------- ##Producing correlation plot plot_wave.multiple.cross.correlation(Lst, lmax) #, by=2) ## ----label=plot_wmcr, echo=-1, results='hide'--------------------------------- ##Producing correlation plot plot_wave.multiple.cross.regression(Lst, lmax) #, by=2) ## ----label=wlmr_code,echo=-7:-8, results='hide'------------------------------- wf <- "d4" M <- 30 window <- "gauss" #uniform" J <- trunc(log2(N))-3 set.seed(140859) demusd.modwt <- brick.wall(modwt(returns[,"DEM.USD"], wf, J), wf) jpyusd.modwt <- brick.wall(modwt(returns[,"JPY.USD"], wf, J), wf) xrand.modwt <- brick.wall(modwt(rnorm(length(returns[,"DEM.USD"])), wf, J), wf) xx <- list(demusd.modwt, jpyusd.modwt, xrand.modwt) names(xx) <- c("DEM.USD","JPY.USD","rand") Lst <- wave.local.multiple.regression(xx, M, window=window) #, ymaxr=1) ## ----label=heat_wlmc, echo=-1, results='hide'--------------------------------- ##Producing correlation heat map heatmap_wave.local.multiple.correlation(Lst) #, xaxt="s", ci=NULL, pdf.write=NULL) ## ----label=plot_wlmc, echo=-1, results='hide'--------------------------------- ##Producing line plots with CI plot_wave.local.multiple.correlation(Lst) #, xaxt="s") ## ----label=plot_wlmr, echo=-1, results='hide'--------------------------------- ##Producing regression plots plot_wave.local.multiple.regression(Lst) #, xaxt="s") ## ----label=wlmcr_code,echo=-7:-8, results='hide'------------------------------ wf <- "d4" M <- 30 window <- "gauss" #uniform" J <- trunc(log2(N))-3 lmax <- 5 set.seed(140859) demusd.modwt <- brick.wall(modwt(returns[,"DEM.USD"], wf, J), wf) jpyusd.modwt <- brick.wall(modwt(returns[,"JPY.USD"], wf, J), wf) rand.modwt <- brick.wall(modwt(rnorm(length(returns[,"DEM.USD"])), wf, J), wf) xx <- list(demusd.modwt, jpyusd.modwt, rand.modwt) names(xx) <- c("DEM.USD","JPY.USD","rand") Lst <- wave.local.multiple.cross.regression(xx, M, window=window, lag.max=lmax) #, ymaxr=1) ## ----label=heat_wlmcc_lag, echo=-1, results='hide'---------------------------- ##Producing cross-correlation heat map heatmap_wave.local.multiple.cross.correlation(Lst, lmax=lmax, lag.first=FALSE) #, xaxt="s", ci=NULL, pdf.write=NULL) ## ----label=heat_wlmcc_lev, echo=-1, results='hide'---------------------------- ##Producing cross-correlation heat map heatmap_wave.local.multiple.cross.correlation(Lst, lmax=2, lag.first=TRUE) #, xaxt="s", ci=NULL, pdf.write=NULL) ## ----label=plot_wlmcc, echo=-1, eval=FALSE------------------------------------ # ##Producing cross-correlation plot # plot_wave.local.multiple.cross.correlation(Lst, lmax, lag.first=FALSE) #, xaxt="s") ## ----label=plot_wlmcr, echo=-1, eval=FALSE------------------------------------ # ##Producing cross-regression plot # plot_wave.local.multiple.cross.regression(Lst, lmax, nsig=2) #, xaxt="s")
/scratch/gouwar.j/cran-all/cranData/wavemulcor/inst/doc/wavemulcor-vignette.R
--- title: "**wavemulcor:**" subtitle: "Wavelet Routines for Global and Local\n\n Multiple Regression and Correlation" package: wavemulcor V. 3.1.2 date: "`r Sys.Date()`" author: J Fernández-Macho\cr Dpt.\ of Quantitative Methods\cr University of the Basque Country (UPV/EHU) abstract: | Wavelet routines that calculate single sets of wavelet multiple regressions and correlations (WMR and WMC), and cross-regressions and cross-correlations (WMCR and WMCC) from a multivariate time series. Also, dynamic versions of the routines allow the wavelet local multiple (cross-)regressions (WLMR and WLMCR) and (cross-)correlations (WLMC and WLMCC) to evolve over time. They can later be plotted in single graphs, as an alternative to trying to make sense out of several sets of wavelet correlations or wavelet cross-correlations. The code is based on the calculation, at each wavelet scale, of the square root of the coefficient of determination in a linear combination of variables for which such coefficient of determination is a maximum. # header-includes: # - \usepackage{framed} # output: # rmarkdown::pdf_document: # keep_tex: true # keep_md: true # classoption: a4paper bibliography: "jfbib4wavemulcor.bib" toc: TRUE vignette: > %\VignetteIndexEntry{wavemulcor} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r knitr_setup, include = FALSE} knitr::opts_chunk$set( echo = TRUE, message=FALSE, results = "asis", fig.width=7, fig.height=5, fig.asp=0.5, collapse = TRUE, comment = "#>" # dev = 'pdf' ) ``` ```{r setup, include = FALSE} rm(list = ls()) # clear objects graphics.off() # close graphics windows # library(wavemulcor) data(exchange) returns <- diff(log(as.matrix(exchange))) returns <- ts(returns, start=1970, freq=12) N <- dim(returns)[1] ``` ## Introduction Data evolution along time may be the consequence of heterogeneous causes occurring at different time scales or frequencies. This is not easily taken into account by traditional time series analysis (TSA) either in the time domain or in the frequency domain (Fourier analysis). These two approaches take opposite ways of exposing the information present in the time series under study. Thus, time domain TSA provides full time resolution at the cost of discarding all frequency information and, conversely, Fourier analysis has full frequency resolution but no information in time. The more recent wavelet analysis gets sort of in the middle by offering a compromise, with partial resolution in both time and frequency domains, so that we can separate periodic components at different timescales and observe how they evolve over time [@PerciW00;@AguiaS14]. ### Wavelet correlation Just like the standard correlation measure, wavelet correlation aims to evaluate the degree of association between two time series but on a scale-by-scale basis. Since the seminal work of Whitcher _etal._ [-@WhitcGP00] and the release of the _waveslim_ package [@Whitc15], pairwise wavelet correlations haven been widely used in many different scientific fields. However, standard wavelet correlations are restricted to pairs of time series. This is not helpful when dealing with a set of several time series since we would need to handle many wavelet correlation graphs and even more cross-correlation graphs. In this case, we would rather ask for a single measure of the overall association among them. Of course, this is even complicated further if we want to extend the comparison to the actual plethora of regression coefficients involved. ### Wavelet multiple regression and correlation The wavelet multiple regression and correlation analysis proposed in Fernández-Macho [-@Ferna12;-@Ferna18] extends wavelet correlation methodology to handle multivariate time series. As their names imply, the wavelet multiple regression (WMR) and cross-regression (WMCR) estimate a complete set of regression coefficients, together with their corresponding standard deviations and significance statistics, related to the overall statistical relationships that might exist at different timescales among observations on a multivariate time series. As special cases, the wavelet multiple correlation (WMC) and cross-correlation (WMCC) refer to just the actual measure of the degree of overall statistical relationships within the multivariate set of variables. ### Local vs. global wavelet multiple regression Similarly, in a non-stationary context, the wavelet local multiple regression (WLMR) and correlation (WLMC) estimate and measure the time-evolving statistical relationships at different timescales within a multivariate data set. The usual practice of combining standard bivariate wavelet correlation analysis with rolling time windows is clearly inadequate as this needs to calculate, plot and compare a large number of wavelet regression and correlation graphs that now would require an additional time dimension. This renders pairwise multiscale comparisons pointless in practice. <!-- see [@Ranta10;@DajcmFK12;@Ranta13;@Benhm13;@TiwarMA16] among others, for examples just involving correlations. --> Besides, some consideration as to appropriateness of the usual rectangular rolling window needs to be taken into account. See Fernández-Macho [-@Ferna18;-@Ferna19a] for a brief introduction to wavelet methods and a discussion of the spectral properties of local windows needed for dynamic wavelet methods. ## The wavemulcor package Package _wavemulcor_ produces estimates of multiscale global or local multiple regressions and correlations along with approximate confidence intervals. It makes use of the maximal overlap discrete wavelet transform described in Percival and Walden [-@PerciW00], and implemented by the _modwt_ function in the _waveslim_ **R** package developed by Whitcher [-@Whitc15]. <!-- (see also [@GencaSW02]); --> It contains several routines <!-- wave.multiple.correlation}, {wave.multiple.cross.correlation} and {wave.local.multiple.correlation}, --> that calculate single sets of, respectively, global wavelet multiple regressions (WMC, WMR), global wavelet multiple cross-regressions (WMCC, WMCR) and time-localized wavelet multiple regressions (WLMC, WLMR) from a dataset of $n$ variables. <!-- They can later be plotted in single graphs, as an alternative to trying to make sense out of ${n(n-1)/2}$ --> <!-- sets of global wavelet correlations or ${n(n-1)/2 \cdot J}$ sets of global wavelet cross-correlations or --> <!-- ${n(n-1)/2 \cdot [J \times T]}$ sets of local wavelet regressions and correlations respectively. --> The code is based on the calculation, at each wavelet scale $\lambda_j$, of the square root of the coefficient of determination in that linear combination of either global or locally weighted wavelet coefficients for which such coefficient of determination is a maximum. For reference, we can write such linear combination as $w_{yj}=\beta w_{xj}$, where $w_{yj}$ is the normalizing wavelet variable and $\beta w_{xj}$ is the linear combination of the rest of wavelet variables. Package _wavemulcor_ can be obtained from The Comprehensive **R** Archive Network (CRAN) at https://cran.r-project.org/package=wavemulcor. ### WMR: wavelet multiple regression and correlation These two wavelet routines produce estimates of multiscale multiple regressions together with their approximate confidence intervals. The following example illustrates WMC with a tri-variate series consisting of the same exchange rate returns data as in Gençay _etal._ [-@GencaSW02], DEM-USD, JPY-USD, <!-- Figure 7.8, --> plus one random variable: ```{r label=wmc_code,echo=c(-1:-3,-6:-8)} ## Based on data from Figure 7.8 in Gencay, Selcuk and Whitcher (2001) ## plus one random series. wf <- "d4" J <- trunc(log2(N))-3 set.seed(140859) demusd.modwt <- brick.wall(modwt(returns[,"DEM.USD"], wf, J), wf) jpyusd.modwt <- brick.wall(modwt(returns[,"JPY.USD"], wf, J), wf) xrand.modwt <- brick.wall(modwt(rnorm(length(returns[,"DEM.USD"])), wf, J), wf) xx <- list(demusd.modwt, jpyusd.modwt, xrand.modwt) names(xx) <- c("DEM.USD","JPY.USD","rand") Lst <- wave.multiple.correlation(xx) ``` The output from this function consists of a list of two elements: * _xy.mulcor_, a $J\times 3$ matrix with as many rows as levels in the wavelet transform object. The first column provides the point estimate for the wavelet multiple correlation, followed by the lower and upper bounds from the confidence interval, and * _YmaxR_, a numeric vector giving, at each wavelet level, the index number of the normalizing wavelet variable $w_y$ whose correlation is calculated (maximized by default) against a linear combination of the rest. The output can be presented in a table or graph using the **R** code of our choice. A quick but nice option is to use the auxiliary routine _plot_wave.multiple.correlation_ that produces a standard WMC plot: ```{r label=plot_wmc, echo=-1:-2, results='hide'} ##Producing correlation plot Lst <- wave.multiple.regression(xx) plot_wave.multiple.correlation(Lst) ``` The figure shows the wavelet multiple correlation for the exchange rate returns. The dashed lines correspond to the upper and lower bounds of the corresponding 95% confidence interval. The variables named on top [^1] give, at each scale, the largest multiple correlation obtained from a linear combination of the variables. As an option, we can overrule this by explicitly naming the normalizing variable. [^1]: { This feature needs _Lst_ to be output from _wave.multiple.regression_.} For a complete regression output we can use WMR. A similar code chunk as the one before provides an example of its usage, but with the last line replaced by: ```{r label=wmr_code} Lst <- wave.multiple.regression(xx) ``` It produces a first element with the same correlation output as _wave.multiple.correlation_ plus a second element _xy.mulreg_ with a list of relevant regression statistics, namely, the regression estimates at each wavelet level together with their standard deviations, confidence interval lower and upper bounds, the $t$ statistic values and p-values, and the indexes of the regressors when sorted by significance. As before, this output can be fed into **R** code to produce tables and graphs of our choice. Alternatively, the auxiliary routine _plot_wave.multiple.regression_ will give us a standard WMR plot: ```{r label=plot_wmr, echo=-1, results='hide'} ##Producing regression plot plot_wave.multiple.regression(Lst) # nsig=2) ``` The figure plots the wavelet multiple regression for the exchange rate returns, with different colors for each regression coefficient. The dashed lines correspond to the upper and lower bounds of their 95% confidence interval. Note that, in order not to crowd the plot excessively, we can choose to plot _nsig_ regression coefficients only (the default is $nsig=2$.) As before, the variables named on top give, at each scale, the largest multiple correlation from a linear combination of the variables. The names of the _nsig_ most significant regressors are also printed along the regression wavelet line. The shaded area represent the compound 95% significance interval around zero. ### WMCR: wavelet multiple cross-regression and cross-correlation Wavelet cross-regressions are, in principle, the same as wavelet regressions but with a temporal time shift between the normalizing wavelet variable $w_y$ and its regressors $w_x$ at each of the wavelet levels. If the shift is positive (_lag_) we say that $y$ lags the rest of the variables at that wavelet level, if it is negative (_lead_) we say that $y$ leads. The next example uses WMCR (or WMCC) with the same tri-variate series of exchange rate returns data as before: <!-- (_cf_ [@GencaSW02], Figure~7.9): --> ```{r label=wmcr_code,echo=-5:-6} wf <- "d4" J <- trunc(log2(N))-3 lmax <- 36 set.seed(140859) demusd.modwt <- brick.wall(modwt(returns[,"DEM.USD"], wf, J), wf) jpyusd.modwt <- brick.wall(modwt(returns[,"JPY.USD"], wf, J), wf) rand.modwt <- brick.wall(modwt(rnorm(length(returns[,"DEM.USD"])), wf, J), wf) # --------------------------- xx <- list(demusd.modwt, jpyusd.modwt, rand.modwt) names(xx) <- c("DEM.USD","JPY.USD","rand") Lst <- wave.multiple.cross.regression(xx, lmax) ``` The output from this function is made up of several elements:[^2] * _xy.mulcor_, similar as before but taking into account the time shifts. That is, it contains _wavemulcor_, _lower_, _upper_, three $J\times lmax$ matrices of correlation coefficients and corresponding lower and upper bounds confidence interval bounds. * _xy.mulreg_, with a list of arrays containing relevant regression statistics for all wavelet levels, and lags and leads. * _YmaxR_, with the same content as _wave.multiple.regression_ before. [^2]: { Alternatively, if only wavelet multiple cross-correlations are needed, we can use the legacy routine _wave.multiple.cross.correlation(xx, lmax)_.} For a compact visualization with no confidence intervals, the cross-correlation output can be fed into a *heatmap_* auxiliary routine to obtain a standard heat map representation the WMCC: ```{r label=heat_wmcc, echo=-1, results='hide'} ##Producing correlation heat map heatmap_wave.multiple.cross.correlation(Lst, lmax) #, by=3, ci=NULL, pdf.write=NULL) ``` More generally, the output can also be fed into *plot_* auxiliary routines to obtain a standard WMCC plot: ```{r label=plot_wmcc, echo=-1, results='hide'} ##Producing correlation plot plot_wave.multiple.cross.correlation(Lst, lmax) #, by=2) ``` ...and a standard WMCR plot: ```{r label=plot_wmcr, echo=-1, results='hide'} ##Producing correlation plot plot_wave.multiple.cross.regression(Lst, lmax) #, by=2) ``` Both figures show, at one plot per wavelet level, the respective wavelet multiple cross-correlation and cross-regression coefficients for the exchange rate returns with their corresponding 95% confidence interval upper and lower bounds. ### WLMR: wavelet local multiple regression and correlation This wavelet routine produces an estimate of the multiscale local multiple correlation from a set of $n$ variables together with approximate confidence intervals. The routine calculates one single set of wavelet multiple correlations over time that can be plotted in either one single heat map or $J$ line graphs (the former is useful if confidence intervals are explicitly needed but the latter is usually the best graphic option). The third example uses WLMR (or WLMC) with the same tri-variate series of exchange rate returns data as before: ```{r label=wlmr_code,echo=-7:-8, results='hide'} wf <- "d4" M <- 30 window <- "gauss" #uniform" J <- trunc(log2(N))-3 set.seed(140859) demusd.modwt <- brick.wall(modwt(returns[,"DEM.USD"], wf, J), wf) jpyusd.modwt <- brick.wall(modwt(returns[,"JPY.USD"], wf, J), wf) xrand.modwt <- brick.wall(modwt(rnorm(length(returns[,"DEM.USD"])), wf, J), wf) xx <- list(demusd.modwt, jpyusd.modwt, xrand.modwt) names(xx) <- c("DEM.USD","JPY.USD","rand") Lst <- wave.local.multiple.regression(xx, M, window=window) #, ymaxr=1) ``` The output from this function has the following main elements:[^3] * _cor_, similar as before but taking into the evolution over time. It contains _val_, _lo_, _up_, three matrices of wavelet correlation coefficients over time and corresponding lower and upper bounds confidence interval bounds. * _reg_, with a list of matrices containing relevant regression statistics for all wavelet levels over time. * _YmaxR_, with the same content as _wave.multiple.regression_ before. [^3]: { Alternatively, if only wavelet local multiple correlations are needed, we can use the legacy _routine wave.local.multiple.correlation(xx, lmax)_.} The output can be fed into a *heatmap_* auxiliary routine to obtain a standard heat map, which is the recommended way to visualize the WLMC: ```{r label=heat_wlmc, echo=-1, results='hide'} ##Producing correlation heat map heatmap_wave.local.multiple.correlation(Lst) #, xaxt="s", ci=NULL, pdf.write=NULL) ``` The figure shows how the WLMC evolves both over time and across wavelet levels, the latter shown as time periods $(2^j,2^{j+1}]$ after conversion into their corresponding time units intervals. As nice as they are, heat maps cannot offer the information provided by the confidence intervals and, besides, cannot be sensibly used for visualizing WLMR output. For those we need to use the *plot_* auxiliary routines to obtain a standard WLMC plot: ```{r label=plot_wlmc, echo=-1, results='hide'} ##Producing line plots with CI plot_wave.local.multiple.correlation(Lst) #, xaxt="s") ``` ...and a standard WLMR plot: ```{r label=plot_wlmr, echo=-1, results='hide'} ##Producing regression plots plot_wave.local.multiple.regression(Lst) #, xaxt="s") ``` Both figures show, at one plot per wavelet level, the respective wavelet local multiple correlation and regression coefficients for the exchange rate returns with their corresponding 95% confidence interval upper and lower bounds. ### WLMCR: wavelet local multiple cross-regression and cross-correlation Just as you were expecting by now, there are also routines that calculate local regressions at different lags and leads. The output structure should be obvious once we have learned to handle the previous _local_ and _cross_ functions, since WLMCR, and the simpler WLMCC, are but a combination of both features. ```{r label=wlmcr_code,echo=-7:-8, results='hide'} wf <- "d4" M <- 30 window <- "gauss" #uniform" J <- trunc(log2(N))-3 lmax <- 5 set.seed(140859) demusd.modwt <- brick.wall(modwt(returns[,"DEM.USD"], wf, J), wf) jpyusd.modwt <- brick.wall(modwt(returns[,"JPY.USD"], wf, J), wf) rand.modwt <- brick.wall(modwt(rnorm(length(returns[,"DEM.USD"])), wf, J), wf) xx <- list(demusd.modwt, jpyusd.modwt, rand.modwt) names(xx) <- c("DEM.USD","JPY.USD","rand") Lst <- wave.local.multiple.cross.regression(xx, M, window=window, lag.max=lmax) #, ymaxr=1) ``` As before, there are also auxiliary *heatmap_* and *plot_* routines to handle standard heat maps and plots similar to the ones presented above but extended over the requested lags and leads. For example, _heatmap_wave.local.multiple.cross.correlation_ produces a page of $J+1$ standard WLMC heat maps: ```{r label=heat_wlmcc_lag, echo=-1, results='hide'} ##Producing cross-correlation heat map heatmap_wave.local.multiple.cross.correlation(Lst, lmax=lmax, lag.first=FALSE) #, xaxt="s", ci=NULL, pdf.write=NULL) ``` Note that we can use the option _lag.first=TRUE_ to alter the role of lags and levels in the plots. That is, it will make one plot per lag, where the vertical axis are wavelet periods, same as with *heatmap_wave.local.multiple.correlation* before. ```{r label=heat_wlmcc_lev, echo=-1, results='hide'} ##Producing cross-correlation heat map heatmap_wave.local.multiple.cross.correlation(Lst, lmax=2, lag.first=TRUE) #, xaxt="s", ci=NULL, pdf.write=NULL) ``` Once again, if confidence intervals are required we need to use the *plot_* auxiliary routines to obtain a standard WLMCC plots: ```{r label=plot_wlmcc, echo=-1, eval=FALSE} ##Producing cross-correlation plot plot_wave.local.multiple.cross.correlation(Lst, lmax, lag.first=FALSE) #, xaxt="s") ``` ```{r label=plot_wlmcr, echo=-1, eval=FALSE} ##Producing cross-regression plot plot_wave.local.multiple.cross.regression(Lst, lmax, nsig=2) #, xaxt="s") ``` Their respective outputs are each made up of as many graphs as wavelet levels and typically can extend several pages, therefore they will not be presented in this vignette. However, it is sucintly described in the documentation of the package and you are kindly invited to try it. ## References
/scratch/gouwar.j/cran-all/cranData/wavemulcor/inst/doc/wavemulcor-vignette.Rmd
--- title: "**wavemulcor:**" subtitle: "Wavelet Routines for Global and Local\n\n Multiple Regression and Correlation" package: wavemulcor V. 3.1.2 date: "`r Sys.Date()`" author: J Fernández-Macho\cr Dpt.\ of Quantitative Methods\cr University of the Basque Country (UPV/EHU) abstract: | Wavelet routines that calculate single sets of wavelet multiple regressions and correlations (WMR and WMC), and cross-regressions and cross-correlations (WMCR and WMCC) from a multivariate time series. Also, dynamic versions of the routines allow the wavelet local multiple (cross-)regressions (WLMR and WLMCR) and (cross-)correlations (WLMC and WLMCC) to evolve over time. They can later be plotted in single graphs, as an alternative to trying to make sense out of several sets of wavelet correlations or wavelet cross-correlations. The code is based on the calculation, at each wavelet scale, of the square root of the coefficient of determination in a linear combination of variables for which such coefficient of determination is a maximum. # header-includes: # - \usepackage{framed} # output: # rmarkdown::pdf_document: # keep_tex: true # keep_md: true # classoption: a4paper bibliography: "jfbib4wavemulcor.bib" toc: TRUE vignette: > %\VignetteIndexEntry{wavemulcor} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r knitr_setup, include = FALSE} knitr::opts_chunk$set( echo = TRUE, message=FALSE, results = "asis", fig.width=7, fig.height=5, fig.asp=0.5, collapse = TRUE, comment = "#>" # dev = 'pdf' ) ``` ```{r setup, include = FALSE} rm(list = ls()) # clear objects graphics.off() # close graphics windows # library(wavemulcor) data(exchange) returns <- diff(log(as.matrix(exchange))) returns <- ts(returns, start=1970, freq=12) N <- dim(returns)[1] ``` ## Introduction Data evolution along time may be the consequence of heterogeneous causes occurring at different time scales or frequencies. This is not easily taken into account by traditional time series analysis (TSA) either in the time domain or in the frequency domain (Fourier analysis). These two approaches take opposite ways of exposing the information present in the time series under study. Thus, time domain TSA provides full time resolution at the cost of discarding all frequency information and, conversely, Fourier analysis has full frequency resolution but no information in time. The more recent wavelet analysis gets sort of in the middle by offering a compromise, with partial resolution in both time and frequency domains, so that we can separate periodic components at different timescales and observe how they evolve over time [@PerciW00;@AguiaS14]. ### Wavelet correlation Just like the standard correlation measure, wavelet correlation aims to evaluate the degree of association between two time series but on a scale-by-scale basis. Since the seminal work of Whitcher _etal._ [-@WhitcGP00] and the release of the _waveslim_ package [@Whitc15], pairwise wavelet correlations haven been widely used in many different scientific fields. However, standard wavelet correlations are restricted to pairs of time series. This is not helpful when dealing with a set of several time series since we would need to handle many wavelet correlation graphs and even more cross-correlation graphs. In this case, we would rather ask for a single measure of the overall association among them. Of course, this is even complicated further if we want to extend the comparison to the actual plethora of regression coefficients involved. ### Wavelet multiple regression and correlation The wavelet multiple regression and correlation analysis proposed in Fernández-Macho [-@Ferna12;-@Ferna18] extends wavelet correlation methodology to handle multivariate time series. As their names imply, the wavelet multiple regression (WMR) and cross-regression (WMCR) estimate a complete set of regression coefficients, together with their corresponding standard deviations and significance statistics, related to the overall statistical relationships that might exist at different timescales among observations on a multivariate time series. As special cases, the wavelet multiple correlation (WMC) and cross-correlation (WMCC) refer to just the actual measure of the degree of overall statistical relationships within the multivariate set of variables. ### Local vs. global wavelet multiple regression Similarly, in a non-stationary context, the wavelet local multiple regression (WLMR) and correlation (WLMC) estimate and measure the time-evolving statistical relationships at different timescales within a multivariate data set. The usual practice of combining standard bivariate wavelet correlation analysis with rolling time windows is clearly inadequate as this needs to calculate, plot and compare a large number of wavelet regression and correlation graphs that now would require an additional time dimension. This renders pairwise multiscale comparisons pointless in practice. <!-- see [@Ranta10;@DajcmFK12;@Ranta13;@Benhm13;@TiwarMA16] among others, for examples just involving correlations. --> Besides, some consideration as to appropriateness of the usual rectangular rolling window needs to be taken into account. See Fernández-Macho [-@Ferna18;-@Ferna19a] for a brief introduction to wavelet methods and a discussion of the spectral properties of local windows needed for dynamic wavelet methods. ## The wavemulcor package Package _wavemulcor_ produces estimates of multiscale global or local multiple regressions and correlations along with approximate confidence intervals. It makes use of the maximal overlap discrete wavelet transform described in Percival and Walden [-@PerciW00], and implemented by the _modwt_ function in the _waveslim_ **R** package developed by Whitcher [-@Whitc15]. <!-- (see also [@GencaSW02]); --> It contains several routines <!-- wave.multiple.correlation}, {wave.multiple.cross.correlation} and {wave.local.multiple.correlation}, --> that calculate single sets of, respectively, global wavelet multiple regressions (WMC, WMR), global wavelet multiple cross-regressions (WMCC, WMCR) and time-localized wavelet multiple regressions (WLMC, WLMR) from a dataset of $n$ variables. <!-- They can later be plotted in single graphs, as an alternative to trying to make sense out of ${n(n-1)/2}$ --> <!-- sets of global wavelet correlations or ${n(n-1)/2 \cdot J}$ sets of global wavelet cross-correlations or --> <!-- ${n(n-1)/2 \cdot [J \times T]}$ sets of local wavelet regressions and correlations respectively. --> The code is based on the calculation, at each wavelet scale $\lambda_j$, of the square root of the coefficient of determination in that linear combination of either global or locally weighted wavelet coefficients for which such coefficient of determination is a maximum. For reference, we can write such linear combination as $w_{yj}=\beta w_{xj}$, where $w_{yj}$ is the normalizing wavelet variable and $\beta w_{xj}$ is the linear combination of the rest of wavelet variables. Package _wavemulcor_ can be obtained from The Comprehensive **R** Archive Network (CRAN) at https://cran.r-project.org/package=wavemulcor. ### WMR: wavelet multiple regression and correlation These two wavelet routines produce estimates of multiscale multiple regressions together with their approximate confidence intervals. The following example illustrates WMC with a tri-variate series consisting of the same exchange rate returns data as in Gençay _etal._ [-@GencaSW02], DEM-USD, JPY-USD, <!-- Figure 7.8, --> plus one random variable: ```{r label=wmc_code,echo=c(-1:-3,-6:-8)} ## Based on data from Figure 7.8 in Gencay, Selcuk and Whitcher (2001) ## plus one random series. wf <- "d4" J <- trunc(log2(N))-3 set.seed(140859) demusd.modwt <- brick.wall(modwt(returns[,"DEM.USD"], wf, J), wf) jpyusd.modwt <- brick.wall(modwt(returns[,"JPY.USD"], wf, J), wf) xrand.modwt <- brick.wall(modwt(rnorm(length(returns[,"DEM.USD"])), wf, J), wf) xx <- list(demusd.modwt, jpyusd.modwt, xrand.modwt) names(xx) <- c("DEM.USD","JPY.USD","rand") Lst <- wave.multiple.correlation(xx) ``` The output from this function consists of a list of two elements: * _xy.mulcor_, a $J\times 3$ matrix with as many rows as levels in the wavelet transform object. The first column provides the point estimate for the wavelet multiple correlation, followed by the lower and upper bounds from the confidence interval, and * _YmaxR_, a numeric vector giving, at each wavelet level, the index number of the normalizing wavelet variable $w_y$ whose correlation is calculated (maximized by default) against a linear combination of the rest. The output can be presented in a table or graph using the **R** code of our choice. A quick but nice option is to use the auxiliary routine _plot_wave.multiple.correlation_ that produces a standard WMC plot: ```{r label=plot_wmc, echo=-1:-2, results='hide'} ##Producing correlation plot Lst <- wave.multiple.regression(xx) plot_wave.multiple.correlation(Lst) ``` The figure shows the wavelet multiple correlation for the exchange rate returns. The dashed lines correspond to the upper and lower bounds of the corresponding 95% confidence interval. The variables named on top [^1] give, at each scale, the largest multiple correlation obtained from a linear combination of the variables. As an option, we can overrule this by explicitly naming the normalizing variable. [^1]: { This feature needs _Lst_ to be output from _wave.multiple.regression_.} For a complete regression output we can use WMR. A similar code chunk as the one before provides an example of its usage, but with the last line replaced by: ```{r label=wmr_code} Lst <- wave.multiple.regression(xx) ``` It produces a first element with the same correlation output as _wave.multiple.correlation_ plus a second element _xy.mulreg_ with a list of relevant regression statistics, namely, the regression estimates at each wavelet level together with their standard deviations, confidence interval lower and upper bounds, the $t$ statistic values and p-values, and the indexes of the regressors when sorted by significance. As before, this output can be fed into **R** code to produce tables and graphs of our choice. Alternatively, the auxiliary routine _plot_wave.multiple.regression_ will give us a standard WMR plot: ```{r label=plot_wmr, echo=-1, results='hide'} ##Producing regression plot plot_wave.multiple.regression(Lst) # nsig=2) ``` The figure plots the wavelet multiple regression for the exchange rate returns, with different colors for each regression coefficient. The dashed lines correspond to the upper and lower bounds of their 95% confidence interval. Note that, in order not to crowd the plot excessively, we can choose to plot _nsig_ regression coefficients only (the default is $nsig=2$.) As before, the variables named on top give, at each scale, the largest multiple correlation from a linear combination of the variables. The names of the _nsig_ most significant regressors are also printed along the regression wavelet line. The shaded area represent the compound 95% significance interval around zero. ### WMCR: wavelet multiple cross-regression and cross-correlation Wavelet cross-regressions are, in principle, the same as wavelet regressions but with a temporal time shift between the normalizing wavelet variable $w_y$ and its regressors $w_x$ at each of the wavelet levels. If the shift is positive (_lag_) we say that $y$ lags the rest of the variables at that wavelet level, if it is negative (_lead_) we say that $y$ leads. The next example uses WMCR (or WMCC) with the same tri-variate series of exchange rate returns data as before: <!-- (_cf_ [@GencaSW02], Figure~7.9): --> ```{r label=wmcr_code,echo=-5:-6} wf <- "d4" J <- trunc(log2(N))-3 lmax <- 36 set.seed(140859) demusd.modwt <- brick.wall(modwt(returns[,"DEM.USD"], wf, J), wf) jpyusd.modwt <- brick.wall(modwt(returns[,"JPY.USD"], wf, J), wf) rand.modwt <- brick.wall(modwt(rnorm(length(returns[,"DEM.USD"])), wf, J), wf) # --------------------------- xx <- list(demusd.modwt, jpyusd.modwt, rand.modwt) names(xx) <- c("DEM.USD","JPY.USD","rand") Lst <- wave.multiple.cross.regression(xx, lmax) ``` The output from this function is made up of several elements:[^2] * _xy.mulcor_, similar as before but taking into account the time shifts. That is, it contains _wavemulcor_, _lower_, _upper_, three $J\times lmax$ matrices of correlation coefficients and corresponding lower and upper bounds confidence interval bounds. * _xy.mulreg_, with a list of arrays containing relevant regression statistics for all wavelet levels, and lags and leads. * _YmaxR_, with the same content as _wave.multiple.regression_ before. [^2]: { Alternatively, if only wavelet multiple cross-correlations are needed, we can use the legacy routine _wave.multiple.cross.correlation(xx, lmax)_.} For a compact visualization with no confidence intervals, the cross-correlation output can be fed into a *heatmap_* auxiliary routine to obtain a standard heat map representation the WMCC: ```{r label=heat_wmcc, echo=-1, results='hide'} ##Producing correlation heat map heatmap_wave.multiple.cross.correlation(Lst, lmax) #, by=3, ci=NULL, pdf.write=NULL) ``` More generally, the output can also be fed into *plot_* auxiliary routines to obtain a standard WMCC plot: ```{r label=plot_wmcc, echo=-1, results='hide'} ##Producing correlation plot plot_wave.multiple.cross.correlation(Lst, lmax) #, by=2) ``` ...and a standard WMCR plot: ```{r label=plot_wmcr, echo=-1, results='hide'} ##Producing correlation plot plot_wave.multiple.cross.regression(Lst, lmax) #, by=2) ``` Both figures show, at one plot per wavelet level, the respective wavelet multiple cross-correlation and cross-regression coefficients for the exchange rate returns with their corresponding 95% confidence interval upper and lower bounds. ### WLMR: wavelet local multiple regression and correlation This wavelet routine produces an estimate of the multiscale local multiple correlation from a set of $n$ variables together with approximate confidence intervals. The routine calculates one single set of wavelet multiple correlations over time that can be plotted in either one single heat map or $J$ line graphs (the former is useful if confidence intervals are explicitly needed but the latter is usually the best graphic option). The third example uses WLMR (or WLMC) with the same tri-variate series of exchange rate returns data as before: ```{r label=wlmr_code,echo=-7:-8, results='hide'} wf <- "d4" M <- 30 window <- "gauss" #uniform" J <- trunc(log2(N))-3 set.seed(140859) demusd.modwt <- brick.wall(modwt(returns[,"DEM.USD"], wf, J), wf) jpyusd.modwt <- brick.wall(modwt(returns[,"JPY.USD"], wf, J), wf) xrand.modwt <- brick.wall(modwt(rnorm(length(returns[,"DEM.USD"])), wf, J), wf) xx <- list(demusd.modwt, jpyusd.modwt, xrand.modwt) names(xx) <- c("DEM.USD","JPY.USD","rand") Lst <- wave.local.multiple.regression(xx, M, window=window) #, ymaxr=1) ``` The output from this function has the following main elements:[^3] * _cor_, similar as before but taking into the evolution over time. It contains _val_, _lo_, _up_, three matrices of wavelet correlation coefficients over time and corresponding lower and upper bounds confidence interval bounds. * _reg_, with a list of matrices containing relevant regression statistics for all wavelet levels over time. * _YmaxR_, with the same content as _wave.multiple.regression_ before. [^3]: { Alternatively, if only wavelet local multiple correlations are needed, we can use the legacy _routine wave.local.multiple.correlation(xx, lmax)_.} The output can be fed into a *heatmap_* auxiliary routine to obtain a standard heat map, which is the recommended way to visualize the WLMC: ```{r label=heat_wlmc, echo=-1, results='hide'} ##Producing correlation heat map heatmap_wave.local.multiple.correlation(Lst) #, xaxt="s", ci=NULL, pdf.write=NULL) ``` The figure shows how the WLMC evolves both over time and across wavelet levels, the latter shown as time periods $(2^j,2^{j+1}]$ after conversion into their corresponding time units intervals. As nice as they are, heat maps cannot offer the information provided by the confidence intervals and, besides, cannot be sensibly used for visualizing WLMR output. For those we need to use the *plot_* auxiliary routines to obtain a standard WLMC plot: ```{r label=plot_wlmc, echo=-1, results='hide'} ##Producing line plots with CI plot_wave.local.multiple.correlation(Lst) #, xaxt="s") ``` ...and a standard WLMR plot: ```{r label=plot_wlmr, echo=-1, results='hide'} ##Producing regression plots plot_wave.local.multiple.regression(Lst) #, xaxt="s") ``` Both figures show, at one plot per wavelet level, the respective wavelet local multiple correlation and regression coefficients for the exchange rate returns with their corresponding 95% confidence interval upper and lower bounds. ### WLMCR: wavelet local multiple cross-regression and cross-correlation Just as you were expecting by now, there are also routines that calculate local regressions at different lags and leads. The output structure should be obvious once we have learned to handle the previous _local_ and _cross_ functions, since WLMCR, and the simpler WLMCC, are but a combination of both features. ```{r label=wlmcr_code,echo=-7:-8, results='hide'} wf <- "d4" M <- 30 window <- "gauss" #uniform" J <- trunc(log2(N))-3 lmax <- 5 set.seed(140859) demusd.modwt <- brick.wall(modwt(returns[,"DEM.USD"], wf, J), wf) jpyusd.modwt <- brick.wall(modwt(returns[,"JPY.USD"], wf, J), wf) rand.modwt <- brick.wall(modwt(rnorm(length(returns[,"DEM.USD"])), wf, J), wf) xx <- list(demusd.modwt, jpyusd.modwt, rand.modwt) names(xx) <- c("DEM.USD","JPY.USD","rand") Lst <- wave.local.multiple.cross.regression(xx, M, window=window, lag.max=lmax) #, ymaxr=1) ``` As before, there are also auxiliary *heatmap_* and *plot_* routines to handle standard heat maps and plots similar to the ones presented above but extended over the requested lags and leads. For example, _heatmap_wave.local.multiple.cross.correlation_ produces a page of $J+1$ standard WLMC heat maps: ```{r label=heat_wlmcc_lag, echo=-1, results='hide'} ##Producing cross-correlation heat map heatmap_wave.local.multiple.cross.correlation(Lst, lmax=lmax, lag.first=FALSE) #, xaxt="s", ci=NULL, pdf.write=NULL) ``` Note that we can use the option _lag.first=TRUE_ to alter the role of lags and levels in the plots. That is, it will make one plot per lag, where the vertical axis are wavelet periods, same as with *heatmap_wave.local.multiple.correlation* before. ```{r label=heat_wlmcc_lev, echo=-1, results='hide'} ##Producing cross-correlation heat map heatmap_wave.local.multiple.cross.correlation(Lst, lmax=2, lag.first=TRUE) #, xaxt="s", ci=NULL, pdf.write=NULL) ``` Once again, if confidence intervals are required we need to use the *plot_* auxiliary routines to obtain a standard WLMCC plots: ```{r label=plot_wlmcc, echo=-1, eval=FALSE} ##Producing cross-correlation plot plot_wave.local.multiple.cross.correlation(Lst, lmax, lag.first=FALSE) #, xaxt="s") ``` ```{r label=plot_wlmcr, echo=-1, eval=FALSE} ##Producing cross-regression plot plot_wave.local.multiple.cross.regression(Lst, lmax, nsig=2) #, xaxt="s") ``` Their respective outputs are each made up of as many graphs as wavelet levels and typically can extend several pages, therefore they will not be presented in this vignette. However, it is sucintly described in the documentation of the package and you are kindly invited to try it. ## References
/scratch/gouwar.j/cran-all/cranData/wavemulcor/vignettes/wavemulcor-vignette.Rmd
#' Calculate the fetch length around a point #' #' Given a point, a shoreline layer and a vector of wind directions (bearings), #' \code{fetch_len} calculates the distance from point to shore for each bearing. #' #' The fetch length (or fetch) is the distance of open water over which the wind #' can blow in a specific direction. Note that bearings represent the direction #' from where the wind originates. #' #' The optional \code{spread} argument defines relative directions that are #' added to each main bearing to produce a set of sub-bearings. The fetch lengths #' calculated for each sub-bearing are averaged with weights proportional to #' \code{cos(spread)}. By default, \code{spread = 0} and fetch length is #' calculated for the main bearings only. #' #' The input data can be in either geographic (long, lat) or projected coordinates, #' but \code{p} and \code{shoreline} must share the same coordinate system. Distances #' are calculated using the \code{\link[sf]{st_distance}} function from the sf package #' and expressed in the units of the coordinate system used, or in meters if using #' geographic coordinates. For geographic coordinates, we recommend setting #' \code{sf_use_s2(FALSE)}, which results in \code{st_distance} using the ellipsoid #' distance calculation (requires the lwgeom package), instead of the less precise #' spherical distance calculation. For projected coordinates, the Euclidean distance #' is calculated. #' #' If the shoreline layer is composed of polygons rather than lines, the function #' verifies that the input point is outside all polygons (i.e. in water). If this is #' not the case, it issues a warning and returns a vector of \code{NA}. #' #' @param p Simple feature (sf or sfc) object representing a single point. #' @param bearings Vector of bearings, in degrees. #' @param shoreline Simple feature (sf or sfc) object representing the #' shoreline, in either line or polygon format. #' @param dmax Maximum value of fetch length, returned if there is no land #' within a distance of \code{dmax} from a given bearing. #' @param spread Vector of relative bearings (in degrees) for which #' to calculate fetch around each main bearing (see details). #' @param projected Deprecated argument, kept for backwards compatibility. #' @param check_inputs Should the validity of inputs be checked? It is #' recommended to keep this TRUE, unless this function is called repeatedly from #' another function that already checks inputs. #' @return A named vector representing the fetch length for each direction #' given in \code{bearings}. #' @examples #' pt <- st_sfc(st_point(c(0, 0)), crs = st_crs(4326)) #' # Shoreline is a rectangle from (-0.2, 0.25) to (0.3, 0.5) #' rect <- st_polygon(list(cbind(c(rep(-0.2, 2), rep(0.3, 2), -0.2), #' c(0.25, rep(0.3, 2), rep(0.25, 2))))) #' land <- st_sfc(rect, crs = st_crs(4326)) #' fetch_len(pt, bearings = c(0, 45, 225, 315), land, #' dmax = 50000, spread = c(-10, 0, 10)) #' @seealso \code{\link{fetch_len_multi}} for an efficient alternative when #' computing fetch length for multiple points. #' @export fetch_len <- function(p, bearings, shoreline, dmax, spread = 0, projected = FALSE, check_inputs = TRUE) { # Convert sp objects to sf format if(is(p, "SpatialPointsDataFrame")) p <- st_as_sf(p) if(is(p, "SpatialPoints")) p <- st_as_sfc(p) if(is(shoreline, "SpatialLinesDataFrame") || is(shoreline, "SpatialPolygonsDataFrame")) { shoreline <- st_as_sf(shoreline) } if(is(shoreline, "SpatialLines") || is(shoreline, "SpatialPolygons")) { shoreline <- st_as_sfc(shoreline) } # Extract geometry columns if p or shoreline are sf objects if(is(p, "sf")) p <- st_geometry(p) if(is(shoreline, "sf")) shoreline <- st_geometry(shoreline) if (check_inputs) { if (!is(p, "sfc_POINT")) stop("p must be a spatial point in sf or sp format.") if(length(p) != 1) stop("p must be a single point.") if (!(is(shoreline, "sfc_LINESTRING") || is(shoreline, "sfc_MULTILINESTRING") || is(shoreline, "sfc_POLYGON") || is(shoreline, "sfc_MULTIPOLYGON"))) { stop("shoreline must be a spatial object in sf or sp format containing lines or polygons.") } if (st_crs(p) != st_crs(shoreline)) { stop("projections of p and shoreline do not match.") } if (!is.vector(bearings, "numeric")) stop("bearings must be a numeric vector.") if (!is.vector(spread, "numeric")) stop("spread must be a numeric vector.") if (!is.vector(dmax, "numeric") || length(dmax) != 1 || dmax <= 0) { stop("dmax must be a single number greater than 0.") } } # If shoreline is a polygons (land) layer, check that point is not on land if (is(shoreline, "sfc_POLYGON") || is(shoreline, "sfc_MULTIPOLYGON")) { suppressMessages( in_water <- length(st_intersection(p, shoreline)) == 0 ) if(!in_water) { warning("point on land, returning NA") return(setNames(rep(NA, length(bearings)), bearings)) } } # Clip shoreline layer to a rectangle around point # to guarantee at least dmax on each side clip_rect <- get_clip_rect(p, dmax) suppressMessages( shore_clip <- st_intersection(shoreline, clip_rect) ) # If no land within rectangle, return dmax for all bearings if (length(shore_clip) == 0) { return(setNames(rep(dmax, length(bearings)), bearings)) } # Convert to multilinestring (if not already lines) # since line-line intersections are needed later shore_clip <- st_cast(shore_clip, "MULTILINESTRING") # Calculate fetch if (all(spread == 0)) { # If no sub-bearings, just return distance to shore for each bearing fetch_res <- vapply(bearings, function(b) dist_shore(p, shore_clip, b, dmax), 0) } else { # Calculate the distance to shore for each sub-bearing bear_mat <- outer(bearings, spread, "+") dists <- vapply(bear_mat, function(b) dist_shore(p, shore_clip, b, dmax), 0) dim(dists) <- dim(bear_mat) # Return weighted means of the sub-bearing fetch values # with weights proportional to the cosine (relative to their main bearing) weights <- cospi(spread / 180) weights <- weights / sum(weights) fetch_res <- as.vector(dists %*% weights) } names(fetch_res) <- as.character(bearings) fetch_res } #' Calculate the fetch length for multiple points #' #' \code{fetch_len_multi} provides two methods to efficiently compute fetch length #' for multiple points. #' #' With \code{method = "btree"} (default), the fetch calculation for each point only uses #' the geometries within the \code{shoreline} layer that intersect with a rectangular #' buffer of size \code{dmax} around that point. (The name is based on a previous version #' of the function that implemented this method using the \code{gBinarySTRtreeQuery} function #' from the rgeos package.) #' #' With \code{method = "clip"}, the \code{shoreline} is clipped to its intersection #' with a polygon formed by the union of all the individual points' rectangular buffers. #' #' In both cases, \code{\link{fetch_len}} is then applied to each point, #' using only the necessary portion of the shoreline. #' #' Generally, the "clip" method will produce the biggest time savings when #' points are clustered within distances less than \code{dmax} (so their #' clipping rectangles overlap), whereas the "btree" method will be more #' efficient when the shoreline is composed of multiple geometrical objects #' and points are distant from each other. #' #' @param pts Simple features (sf or sfc) object containing point data. #' @param bearings Vector of bearings, in degrees. #' @param shoreline Simple feature (sf or sfc) object representing the #' shoreline, in either line or polygon format. #' @param dmax Maximum value of fetch length, returned if there is no land #' within a distance of \code{dmax} from a given bearing. #' @param spread Vector of relative bearings (in degrees) for which #' to calculate fetch around each main bearing. #' @param method Whether to use the "btree" (default) or "clip" method. #' See below for more details. #' @param projected Deprecated argument, kept for backwards compatibility. #' @return A matrix of fetch lengths, with one row by point in \code{pts} and #' one column by bearing in \code{bearings}. #' @seealso \code{\link{fetch_len}} for details on the fetch length computation. #' @export fetch_len_multi <- function(pts, bearings, shoreline, dmax, spread = 0, method = "btree", projected = FALSE) { # Convert sp objects to sf format if(is(pts, "SpatialPointsDataFrame")) pts <- st_as_sf(pts) if(is(pts, "SpatialPoints")) pts <- st_as_sfc(pts) if(is(shoreline, "SpatialLinesDataFrame") || is(shoreline, "SpatialPolygonsDataFrame")) { shoreline <- st_as_sf(shoreline) } if(is(shoreline, "SpatialLines") || is(shoreline, "SpatialPolygons")) { shoreline <- st_as_sfc(shoreline) } # Extract geometry columns if pts or shoreline are sf objects if(is(pts, "sf")) pts <- st_geometry(pts) if(is(shoreline, "sf")) shoreline <- st_geometry(shoreline) # Check inputs match.arg(method, choices = c("btree", "clip")) if (!is(pts, "sfc_POINT")) stop("pts must be a spatial point in sf or sp format.") if (!(is(shoreline, "sfc_LINESTRING") || is(shoreline, "sfc_MULTILINESTRING") || is(shoreline, "sfc_POLYGON") || is(shoreline, "sfc_MULTIPOLYGON"))) { stop("shoreline must be a spatial object in sf or sp format containing lines or polygons.") } if (st_crs(pts) != st_crs(shoreline)) { stop("projections of p and shoreline do not match.") } if (!is.vector(bearings, "numeric")) stop("bearings must be a numeric vector.") if (!is.vector(spread, "numeric")) stop("spread must be a numeric vector.") if (!is.vector(dmax, "numeric") || length(dmax) != 1 || dmax <= 0) { stop("dmax must be a single number greater than 0.") } # Create rectangular buffers around each point rect_list <- lapply(1:length(pts), function(i) get_clip_rect(pts[i], dmax)) rect_buf <- do.call(c, rect_list) if (method == "btree") { # Generate list of shoreline geometry indices that intersect each rectangle suppressMessages( btree <- st_intersects(rect_buf, shoreline) ) # Calculate fetch for point at index i using btree fetch_i <- function(i) { if (length(btree[[i]]) == 0) { setNames(rep(dmax, length(bearings)), bearings) } else { fetch_len(pts[i], bearings, shoreline[btree[[i]]], dmax, spread, check_inputs = FALSE) } } # Calculate fetch for all points and return a (points x bearings) matrix fetch_res <- t(vapply(1:length(pts), fetch_i, rep(0, length(bearings)))) } else { # method == "clip" # Clip shoreline to a merged buffer around all points suppressMessages({ rect_buf <- st_union(rect_buf) sub_shore <- st_intersection(shoreline, rect_buf) }) fetch_res <- t( vapply(1:length(pts), function(i) fetch_len(pts[i], bearings, sub_shore, dmax, spread, check_inputs = FALSE), rep(0, length(bearings))) ) } fetch_res } #### Helper functions below are not exported by the package #### # Returns the distance from point p to shoreline following bearing bear and up to distance dmax # Uses the geodetic distance if in geographic coordinates, # or the Euclidean distance if in projected coordinates dist_shore <- function(p, shoreline, bear, dmax) { if (st_is_longlat(p)) { # Draw geodesic line of length dmax with given start point and bearing # Line drawn with a point every dmax/500 geo_line <- geosphere::gcIntermediate(st_coordinates(p), geosphere::destPoint(st_coordinates(p), bear, dmax), n = 500, breakAtDateLine = TRUE, addStartEnd = TRUE ) if (is.list(geo_line)) { geo_line <- st_multilinestring(geo_line) } else { geo_line <- st_linestring(geo_line) } bline <- st_sfc(geo_line, crs = st_crs(shoreline)) } else { # Draw line of length dmax with given start point and bearing bline <- bearing_line(p, bear, dmax) } # Return (minimum) distance from p to intersection of bearing line and shoreline # If no intersection, fetch is dmax suppressMessages( land_int <- st_intersection(bline, shoreline) ) if (length(land_int) == 0) { d <- dmax } else { d <- min(st_distance(p, land_int)) } d }
/scratch/gouwar.j/cran-all/cranData/waver/R/fetch_len.R
#### Some utility functions to create / manipulate spatial objects (not exported) # Create a polygon (simple feature) corresponding to rectangle with given coords poly_rect <- function(xmin, ymin, xmax, ymax) { st_polygon(list(cbind(c(rep(xmin, 2), rep(xmax, 2), xmin), c(ymin, rep(ymax, 2), rep(ymin, 2))))) } # Create a linestring (simple feature) starting at p, of length len, # along given bearing (in degrees) # Note: This function is meant to be used with a projected CRS bearing_line <- function(p, bearing, len) { l1 <- st_linestring(rbind( st_coordinates(p), st_coordinates(p) + len * c(sinpi(bearing / 180), cospi(bearing / 180)) )) st_sfc(l1, crs = st_crs(p)) } # Create clipping rectangle around point p (sfc_POINT object for a single point) # to guarantee at least dmax on each side # dmax either in meters (if longlat coordinates) or in the projection's coordinates get_clip_rect <- function(p, dmax) { if (st_is_longlat(p)) { lat_dist <- 111600 # approx. distance (in m) between degrees of latitude long <- st_coordinates(p)[1] lat <- st_coordinates(p)[2] ybuf <- dmax / lat_dist xbuf <- ybuf / cospi(abs(lat) / 180) # Split clip_rect in two if it would overlap international date line if (long - xbuf < -180) { westr <- poly_rect(-180, lat - ybuf, long + xbuf, lat + ybuf) eastr <- poly_rect(long - xbuf + 360, lat - ybuf, 180, lat + ybuf) suppressMessages( clip_rect <- st_union(st_sfc(westr, eastr, crs = st_crs(p))) ) } else if(long + xbuf > 180) { westr <- poly_rect(-180, lat - ybuf, long + xbuf - 360, lat + ybuf) eastr <- poly_rect(long - xbuf, lat - ybuf, 180, lat + ybuf) suppressMessages( clip_rect <- st_union(st_sfc(westr, eastr, crs = st_crs(p))) ) } else { r1 <- poly_rect(long - xbuf, lat - ybuf, long + xbuf, lat + ybuf) clip_rect <- st_sfc(r1, crs = st_crs(p)) } } else { x <- st_coordinates(p)[1] y <- st_coordinates(p)[2] r1 <- poly_rect(x - dmax, y - dmax, x + dmax, y + dmax) clip_rect <- st_sfc(r1, crs = st_crs(p)) } clip_rect }
/scratch/gouwar.j/cran-all/cranData/waver/R/sp_utils.R