content
stringlengths
0
14.9M
filename
stringlengths
44
136
ask_file <- function(file, ask) { if (!ask) { return(TRUE) } if (file.exists(file)) { return(yesno("Overwrite file '", file, "'?")) } yesno("Create file '", file, "'?") } bh <- function(stock, alpha, beta) { unname(alpha * stock / (1 + (beta * stock))) } ri <- function(stock, alpha, beta) { unname(alpha * stock * exp(-beta * stock)) } add_parameters <- function(x, object) { object <- as.data.frame(unclass(object)) object$pi <- NULL merge(x, object) } drop_constant_parameters <- function(x) { parameters <- parameters() parameters <- parameters[parameters != "pi"] bol <- vapply(parameters, function(y) length(unique(x[[y]])) == 1, TRUE) parameters <- parameters[bol] x[parameters] <- NULL x } drop_all_parameters <- function(x) { parameters <- parameters() parameters <- parameters[parameters != "pi"] x[parameters] <- NULL x } quantiles <- function(x, level) { x <- unlist(x) x <- stats::quantile(x, c(0.5, (1 - level) / 2, (1 - level) / 2 + level)) setNames(x, c("estimate", "lower", "upper")) } sanitize <- function(x) { x[is.nan(x)] <- 0 x[x < 0] <- 0 x } tabulate_yield_pi <- function(pi, object, Ly, harvest, biomass, all) { object <- set_par(object, "pi", pi) yield <- ypr_tabulate_yield( object = object, Ly = Ly, harvest = harvest, biomass = biomass, type = "actual", all = all ) yield$Type <- NULL yield } sum_fish <- function(x) { ecotype <- x$Ecotype[1] x$Ecotype <- NULL x[] <- lapply(x, sum) x[[1]] <- x[[1]] / nrow(x) x <- x[1, ] x$Ecotype <- ecotype x } .sub <- function(x, pattern, replacement) { sub(pattern, replacement, x) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/internal.R
#' Tests if is a Population, Populations or Ecotypes #' @param x The object to test. #' @export #' @examples #' is.ypr_population(ypr_population()) is.ypr_population <- function(x) { is_ypr_population(x) } #' @describeIn is.ypr_population Test if is a Population #' @export #' @examples #' is_ypr_population(ypr_population()) is_ypr_population <- function(x) { inherits(x, "ypr_population") } #' @describeIn is.ypr_population Test if is a Populations #' @export #' @examples #' is.ypr_populations(ypr_populations()) is.ypr_populations <- function(x) { is_ypr_populations(x) } #' @describeIn is.ypr_population Test if is a Populations #' @export #' @examples #' is_ypr_population(ypr_populations()) is_ypr_populations <- function(x) { inherits(x, "ypr_populations") } #' @describeIn is.ypr_population Test if is an Ecotypes #' @export #' @examples #' is.ypr_ecotypes(ypr_ecotypes()) is.ypr_ecotypes <- function(x) { is_ypr_ecotypes(x) } #' @describeIn is.ypr_population Test if is an Ecotypes #' @export #' @examples #' is_ypr_ecotypes(ypr_ecotypes()) is_ypr_ecotypes <- function(x) { inherits(x, "ypr_ecotypes") }
/scratch/gouwar.j/cran-all/cranData/ypr/R/is.R
#' Population Names #' #' Generates set of unique names based on differences in parameter values. #' `r lifecycle::badge('deprecated')` #' @param population An object of class ypr_population, ypr_populations or ypr_ecotypes. #' @return A character vector of the unique parameter based names. #' @seealso [`ypr_names()`] #' #' @export ypr_population_names <- function(population) { lifecycle::deprecate_soft("0.5.3", "ypr_population_names()", "ypr_names()") ypr_names(population) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/names-deprec.R
#' Population(s) or Ecotype Names #' #' Generates set of unique names based on differences in parameter values. #' #' Parameter RPR is ignored because it is irrelevant to population(s) and does not #' distinguish between ecotypes. #' #' @param x An object of class ypr_population, ypr_populations or ypr_ecotypes. #' @param ... Unused. #' #' @return A character vector of the unique parameter based names. #' @export ypr_names <- function(x, ...) { UseMethod("ypr_names") } #' @describeIn ypr_names Population Names #' @export #' @examples #' ypr_names(ypr_population()) ypr_names.ypr_population <- function(x, ...) { chk_unused(...) "Pop_1" } #' @describeIn ypr_names Populations Names #' @export #' @examples #' ypr_names(ypr_populations()) ypr_names.ypr_populations <- function(x, ...) { chk_unused(...) x <- as_tibble(x) x$RPR <- NULL x <- x[, vapply( x, FUN = function(x) length(unique(x)) > 1, TRUE )] if (!ncol(x)) { return(paste0("Pop_", seq_len(nrow(x)))) } x <- as.list(x) x <- purrr::map( x, .sub, pattern = "[.]", replacement = "_" ) x <- purrr::map2( x, names(x), function(x, y) paste(y, x, sep = "_") ) x <- purrr::transpose(x) x <- purrr::map( x, function(x) { paste0(unname(unlist(x)), collapse = "_" ) } ) names <- unlist(x) duplicates <- unique(names[duplicated(names)]) for (duplicate in duplicates) { bol <- names == duplicate names[bol] <- paste(names[bol], "Pop", 1:sum(bol), sep = "_") } names } #' @describeIn ypr_names Ecotypes Names #' @export #' @examples #' ypr_names(ypr_populations()) ypr_names.ypr_ecotypes <- function(x, ...) { chk_unused(...) x <- as_ypr_populations(x) names <- ypr_names(x) names <- .sub(names, "^Pop_", "Eco_") names }
/scratch/gouwar.j/cran-all/cranData/ypr/R/names.R
#' @import chk yesno lifecycle #' @importFrom ggplot2 ggplot #' @importFrom purrr map map2 transpose #' @importFrom tidyplus only #' @importFrom stats update setNames #' @importFrom tibble as_tibble #' @importFrom graphics plot #' @importFrom lifecycle deprecated NULL
/scratch/gouwar.j/cran-all/cranData/ypr/R/namespace.R
optimize <- function(object, Ly, harvest, biomass) { stats::optimize(yield_pi, c(0, 1), object = object, Ly = Ly, harvest = harvest, biomass = biomass, maximum = TRUE )$maximum } #' Optimize Capture #' #' Finds the interval annual capture probability (pi) that maximises the yield #' for a given population. #' #' @inheritParams params #' @return The interval annual capture probability (pi) that maximises the #' yield. #' @family calculate #' @aliases ypr_optimise #' @export #' @examples #' ypr_optimize(ypr_population()) ypr_optimize <- function(object, Ly = 0, harvest = TRUE, biomass = FALSE) { chk_number(Ly) chk_gte(Ly) chk_flag(biomass) chk_flag(harvest) yield <- optimize( object = object, Ly = Ly, harvest = harvest, biomass = biomass ) sanitize(yield) } #' @export ypr_optimise <- ypr_optimize
/scratch/gouwar.j/cran-all/cranData/ypr/R/optimise.R
set_par <- function(object, par, value) { if(is.ypr_population(object)) { object[[par]] <- value } else { for(i in seq_len(length(object))) { object[[i]] <- set_par(object[[i]], par, value = value) } } object } get_par <- function(object, par) { return(object[[par]]) } get_pars <- function(object, par) { unname(purrr::map_dbl(object, get_par, par)) } #' Get Parameter Value #' #' @param object A ypr object. #' @param par A string of the parameter. #' #' @return A numeric or integer scalar or vector of the parameter value. #' @export #' #' @examples #' ypr_get_par(ypr_population()) ypr_get_par <- function(object, par = "pi") { chk_string(par) chk_subset(par, parameters()) if(is.ypr_population(object)) { return(get_par(object, par)) } pars <- get_pars(object, par) if(is.ypr_populations(object)) { return(pars) } if(!par %in% ecoall_parameters()) { return(pars) } only(pars) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/par.R
#' Parameter Descriptions for ypr Functions #' @param tmax The maximum age (yr). #' @param k The VB growth coefficient (yr-1). #' @param Linf The VB mean maximum length (cm). #' @param t0 The (theoretical) age at zero length (yr). #' @param k2 The VB growth coefficient after length L2 (yr-1). #' @param Linf2 The VB mean maximum length after length L2 (cm). #' @param L2 The length (or age if negative) at which growth switches from the #' first to second phase (cm or yr). #' @param Wb The weight (as a function of length) scaling exponent. #' @param Ls The length (or age if negative) at which 50 % mature (cm or yr). #' @param Sp The maturity (as a function of length) power. #' @param es The annual probability of a mature fish spawning. #' @param Sm The spawning mortality probability. #' @param fb The fecundity (as a function of weight) scaling exponent. #' @param tR The age from which survival is density-independent (yr). #' @param BH Recruitment follows a Beverton-Holt (1) or Ricker (0) relationship. #' @param Rk The lifetime spawners per spawner at low density (or the egg to tR survival if between 0 and 1). #' @param n The annual interval natural mortality rate from age tR. #' @param nL The annual interval natural mortality rate from length Ln. #' @param Ln The length (or age if negative) at which the natural mortality #' rate switches from n to nL (cm or yr). #' @param Lv The length (or age if negative) at which 50 % vulnerable to harvest #' (cm or yr). #' @param Vp The vulnerability to harvest (as a function of length) power. #' @param Llo The lower harvest slot length (cm). #' @param Lup The upper harvest slot length (cm). #' @param Nc The slot limits non-compliance probability. #' @param pi A vector of probabilities of capture to calculate the yield for. #' @param rho The release probability. #' @param Hm The hooking mortality probability. #' @param Rmax The number of recruits at the carrying capacity (ind). #' @param Wa The (extrapolated) weight of a 1 cm individual (g). #' @param fa The (theoretical) fecundity of a 1 g female (eggs). #' @param q The catchability (annual probability of capture) for a unit of #' effort. #' @param RPR The relative proportion of recruits that are of the ecotype. #' @param all A flag specifying whether to include all parameter values. #' @param u A flag specifying whether to plot the exploitation rate as opposed #' to the capture rate. #' @param percent A flag specifying whether to plot the number of fish as a #' percent or frequency (the default). #' @param color A string of the color around each bar (or NULL). #' @param population An object of class [ypr_population()]. #' @param populations An object of class [ypr_populations()]. #' @param ecotypes An object of class [ypr_ecotypes()]. #' @param plot_values A flag specifying whether to plot the actual and optimal #' values. #' @param Ly The minimum length (trophy) fish to consider when calculating the #' yield (cm). #' @param harvest A flag specifying whether to calculate the yield for harvested #' fish or captures. #' @param biomass A flag specifying whether to calculate the yield in terms of #' the biomass versus number of individuals. #' @param title A string of the report title. #' @param date A date of the report date. #' @param file A string of the path to the file (without the extension). #' @param binwidth A positive integer of the width of the bins for grouping. #' @param type A string indicating whether to include 'both' or just the #' 'actual' or 'optimal' yield. #' @param object The population or populations. #' @param ... Unused parameters. #' @param expand A flag specifying whether to expand parameter combinations. #' @param view A flag specifying whether to view the report (after rendering it #' to html). #' @param ask A flag specifying whether to ask before overwriting or creating a #' file. #' @param description A string describing the population. #' @param age A numeric vector of the age (yr). #' @param length A numeric vector of the length (cm). #' @param names A character vector of unique ecotype names. #' @param x The object to coerce. #' @keywords internal #' @name params NULL
/scratch/gouwar.j/cran-all/cranData/ypr/R/params.R
#' Plot Biomass #' #' Produces a frequency histogram of the total fish 'Biomass' or 'Eggs' #' deposition by 'Age' class. #' #' @inheritParams params #' @inheritParams ypr_plot_schedule #' @return A ggplot2 object. #' @seealso [ggplot2::geom_histogram()] #' @family biomass #' @family plot #' @export #' @examples #' ypr_plot_biomass(ypr_population(), color = "white") ypr_plot_biomass <- function(population, y = "Biomass", color = NULL) { if (!requireNamespace("ggplot2")) err("Package 'ggplot2' must be installed.") if (!requireNamespace("scales")) err("Package 'scales' must be installed.") chk_string(y) chk_subset(y, c("Biomass", "Eggs")) biomass <- ypr_tabulate_biomass(population) labels <- if (sum(biomass[[y]]) >= 1000) { scales::comma } else { ggplot2::waiver() } ggplot2::ggplot(data = biomass, ggplot2::aes_string(x = "Age", weight = y)) + (if (is.null(color)) { ggplot2::geom_bar(width = 1) } else { ggplot2::geom_bar(width = 1, color = color) }) + ggplot2::scale_y_continuous(y, labels = labels) + ggplot2::expand_limits(x = 0, y = 0) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/plot-biomass.R
#' Plot Fish #' #' Produces a frequency histogram of the number of fish in the 'Survivors', #' 'Spawners', 'Caught', 'Harvested' or 'Released' categories by 'Length', 'Age' #' or 'Weight' class. #' #' @inheritParams params #' @inheritParams ypr_plot_schedule #' @return A ggplot2 object. #' @seealso [ggplot2::geom_histogram()] #' @family fish #' @family plot #' @export #' @examples #' ypr_plot_fish(ypr_population(), color = "white") ypr_plot_fish <- function(population, x = "Age", y = "Survivors", percent = FALSE, binwidth = 1L, color = NULL) { if (!requireNamespace("ggplot2")) err("Package 'ggplot2' must be installed.") if (!requireNamespace("scales")) err("Package 'scales' must be installed.") chk_string(y) chk_subset(y, c( "Survivors", "Spawners", "Caught", "Harvested", "Released", "HandlingMortalities" )) chk_flag(percent) fish <- ypr_tabulate_fish(population, x = x, binwidth = binwidth) if (percent) fish[[y]] <- fish[[y]] / sum(fish[[y]]) labels <- if (percent) { scales::percent } else if (sum(fish[[y]]) >= 1000) { scales::comma } else { ggplot2::waiver() } gp <- ggplot2::ggplot(data = fish) + (if(length(unique(fish$Ecotype)) == 1) { ggplot2::aes_string(x = x, weight = y) } else { ggplot2::aes_string(x = x, weight = y, fill = "Ecotype") }) + (if (is.null(color)) { ggplot2::geom_bar(width = binwidth) } else { ggplot2::geom_bar(width = binwidth, color = color) }) + ggplot2::scale_y_continuous(y, labels = labels) + ggplot2::expand_limits(x = 0, y = 0) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/plot-fish.R
#' Plot Population or Ecotypes Schedule Terms #' #' Produces a bivariate line plot of two schedule terms. #' #' @inheritParams params #' @param x A string of the term on the x-axis. #' @param y A string of the term on the y-axis. #' @return A ggplot2 object. #' @family schedule #' @family plot #' @export #' @examples #' ypr_plot_schedule(ypr_population()) ypr_plot_schedule <- function(population, x = "Age", y = "Length") { if (!requireNamespace("ggplot2")) err("Package 'ggplot2' must be installed.") if (!requireNamespace("scales")) err("Package 'scales' must be installed.") schedule <- ypr_tabulate_schedule(object = population) chk_string(x) chk_subset(x, values = colnames(schedule)) chk_string(y) chk_subset(y, values = colnames(schedule)) labels <- if (sum(schedule[[y]]) >= 1000) scales::comma else ggplot2::waiver() ecotype <- "Ecotype" %in% names(schedule) && length(unique(schedule$Ecotype)) > 1 group <- if(ecotype) "Ecotype" else NULL color <- if(ecotype) "Ecotype" else NULL ggplot2::ggplot(data = schedule, ggplot2::aes_string(x = x, y = y, group = group, color = color)) + ggplot2::geom_line() + ggplot2::scale_y_continuous(y, labels = labels) + ggplot2::expand_limits(x = 0, y = 0) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/plot-schedule.R
#' Plot Stock-Recruitment Curve #' #' @inheritParams params #' @return A ggplot2 object. #' @family sr #' @family plot #' @export #' @examples #' ypr_plot_sr(ypr_population(Rk = 10)) #' ypr_plot_sr(ypr_population(Rk = 10, BH = 0L)) ypr_plot_sr <- function(population, Ly = 0, harvest = TRUE, biomass = FALSE, plot_values = TRUE) { if (!requireNamespace("ggplot2")) err("Package 'ggplot2' must be installed.") if (!requireNamespace("scales")) err("Package 'scales' must be installed.") chk_number(Ly) chk_gte(Ly) chk_flag(biomass) chk_flag(harvest) chk_flag(plot_values) schedule <- ypr_tabulate_schedule(population) BH <- ypr_get_par(population, "BH") Rmax <- ypr_get_par(population, "Rmax") schedule <- as.list(schedule) schedule$BH <- BH schedule$Rmax <- Rmax schedule <- c(schedule, sr(schedule, population)) data <- with(schedule, { data <- data.frame(Eggs = seq(0, to = only(phi) * only(R0) * 2, length.out = 100)) fun <- if (BH == 1L) bh else ri data$Recruits <- fun(data$Eggs, alpha, beta) data }) data2 <- ypr_tabulate_sr( population, Ly = Ly, harvest = harvest, biomass = biomass ) data2$Type <- factor(data2$Type, levels = c("actual", "optimal", "unfished")) data2 <- rbind(data2, data2, data2) data2$Recruits[1:3] <- 0 data2$Eggs[7:9] <- 0 labels_x <- if (sum(data[["Eggs"]]) >= 1000) { scales::comma } else { ggplot2::waiver() } labels_y <- if (sum(data[["Recruits"]]) >= 1000) { scales::comma } else { ggplot2::waiver() } ggplot2::ggplot( data = data, ggplot2::aes_string( x = "Eggs", y = "Recruits" ) ) + ( if (plot_values) { ggplot2::geom_path( data = data2, ggplot2::aes_string( group = "Type", color = "Type" ), linetype = "dotted" ) } else { NULL }) + ggplot2::geom_line() + ggplot2::expand_limits(x = 0, y = 0) + ggplot2::scale_x_continuous(labels = labels_x) + ggplot2::scale_y_continuous(labels = labels_y) + ggplot2::scale_color_manual(values = c("red", "blue", "black")) + NULL }
/scratch/gouwar.j/cran-all/cranData/ypr/R/plot-sr.R
#' Plot Yield by Capture #' #' Plots the 'Yield', 'Age', 'Length', 'Weight', 'Effort', or 'YPUE' by the #' annual interval capture/exploitation probability. #' #' @inheritParams params #' @inheritParams ypr_plot_schedule #' @return A ggplot2 object. #' @family populations #' @family yield #' @family plot #' @examples #' \dontrun{ #' ypr_plot_yield(ypr_populations( #' Rk = c(2.5, 4.6), #' Llo = c(0, 60) #' ), #' plot_values = FALSE #' ) + #' ggplot2::facet_wrap(~Llo) + #' ggplot2::aes_string(group = "Rk", color = "Rk") + #' ggplot2::scale_color_manual(values = c("black", "blue")) #' #' ypr_plot_yield(ypr_populations(Rk = c(2.5, 4.6), Llo = c(0, 60))) + #' ggplot2::facet_grid(Rk ~ Llo) #' } #' #' ypr_plot_yield(ypr_population()) #' @export #' ypr_plot_yield <- function(object, ...) { UseMethod("ypr_plot_yield") } #' @describeIn ypr_plot_yield Plot Yield by Capture #' @export ypr_plot_yield.default <- function(object, y = "Yield", pi = seq(0, 1, length.out = 100), Ly = 0, harvest = TRUE, biomass = FALSE, u = harvest, plot_values = TRUE, ...) { chkor_vld(vld_is(object, "ypr_population"), vld_is(object, "ypr_ecotypes")) if (!requireNamespace("ggplot2")) err("Package 'ggplot2' must be installed.") if (!requireNamespace("scales")) err("Package 'scales' must be installed.") chk_number(Ly) chk_gte(Ly) chk_flag(biomass) chk_flag(harvest) chk_string(y) chk_subset(y, c("Yield", "Age", "Length", "Weight", "Effort", "YPUE")) chk_flag(u) data <- ypr_tabulate_yields( object, pi = pi, Ly = Ly, harvest = harvest, biomass = biomass ) data2 <- ypr_tabulate_yield( object = object, Ly = Ly, harvest = harvest, biomass = biomass ) data$YPUE <- data$Yield / data$Effort data2$YPUE <- data2$Yield / data2$Effort data1 <- data2 data3 <- data2 data1[c("Yield", "Age", "Length", "Weight", "Effort", "YPUE")] <- 0 data3[c("pi", "u")] <- 0 data2 <- rbind(data1, data2, data3, stringsAsFactors = FALSE) xlab <- if (u) "Exploitation Probability (%)" else "Capture Probability (%)" x <- if (u) "u" else "pi" ggplot2::ggplot(data = data, ggplot2::aes_string(x = x, y = y)) + ( if (plot_values) { list( ggplot2::geom_path( data = data2, ggplot2::aes_string( group = "Type", color = "Type" ), linetype = "dotted" ), ggplot2::scale_color_manual(values = c("red", "blue")) ) } else { NULL }) + ggplot2::geom_line() + ggplot2::expand_limits(x = 0) + ggplot2::scale_x_continuous(xlab, labels = scales::percent) + NULL } #' @describeIn ypr_plot_yield Plot Yield by Capture #' @export ypr_plot_yield.ypr_populations <- function(object, y = "Yield", pi = seq(0, 1, length.out = 100), Ly = 0, harvest = TRUE, biomass = FALSE, u = harvest, plot_values = TRUE, ...) { if (!requireNamespace("ggplot2")) err("Package 'ggplot2' must be installed.") if (!requireNamespace("scales")) err("Package 'scales' must be installed.") chk_string(y) chk_subset(y, c("Yield", "Age", "Length", "Weight", "Effort", "YPUE")) chk_flag(u) data <- ypr_tabulate_yields(object, pi = pi, Ly = Ly, harvest = harvest, biomass = biomass ) data2 <- ypr_tabulate_yield( object = object, Ly = Ly, harvest = harvest, biomass = biomass ) data$YPUE <- data$Yield / data$Effort data2$YPUE <- data2$Yield / data2$Effort parameters <- setdiff(intersect(colnames(data), parameters()), "pi") for (parameter in parameters) { data[[parameter]] <- factor( paste0(parameter, ": ", data[[parameter]]), levels = unique(paste0(parameter, ": ", sort(data[[parameter]]))) ) data2[[parameter]] <- factor( paste0(parameter, ": ", data2[[parameter]]), levels = unique(paste0(parameter, ": ", sort(data2[[parameter]]))) ) } data1 <- data2 data3 <- data2 data1[c("Yield", "Age", "Length", "Weight", "Effort", "YPUE")] <- 0 data3[c("pi", "u")] <- 0 data2 <- rbind(data1, data2, data3, stringsAsFactors = FALSE) xlab <- if (u) "Exploitation Probability (%)" else "Capture Probability (%)" x <- if (u) "u" else "pi" ggplot2::ggplot(data = data, ggplot2::aes_string(x = x, y = y)) + ( if (plot_values) { list( ggplot2::geom_path( data = data2, ggplot2::aes_string( group = "Type", color = "Type" ), linetype = "dotted" ), ggplot2::scale_color_manual(values = c("red", "blue")) ) } else { NULL }) + ggplot2::geom_line() + ggplot2::expand_limits(x = 0) + ggplot2::scale_x_continuous(xlab, labels = scales::percent) + NULL }
/scratch/gouwar.j/cran-all/cranData/ypr/R/plot-yield.R
#' Plot Population Schedule #' #' @param x The population to plot. #' @param type A string specifying the plot type. #' Possible values include 'b', 'p' and 'l'. #' @param ... Additional arguments passed to [graphics::plot] function. #' @return An invisible copy of the original object. #' @seealso [graphics::plot] #' @export #' @examples #' \dontrun{ #' plot(ypr_population()) #' } plot.ypr_population <- function(x, type = "b", ...) { check_population(x) schedule <- ypr_tabulate_schedule(x) with(schedule, { plot(Length ~ Age, xlim = c(0, max(Age)), ylim = c(0, max(Length)), type = type, ... ) plot(Weight ~ Length, xlim = c(0, max(Length)), ylim = c(0, max(Weight)), type = type, ... ) plot(Fecundity ~ Length, xlim = c(0, max(Length)), ylim = c(0, max(Fecundity)), type = type, ... ) plot(Spawning ~ Length, xlim = c(0, max(Length)), ylim = c(0, 1), type = type, ... ) plot(Vulnerability ~ Length, xlim = c(0, max(Length)), ylim = c(0, 1), type = type, ... ) plot(NaturalMortality ~ Length, xlim = c(0, max(Length)), ylim = c(0, 1), type = type, ... ) plot(FishingMortality ~ Length, xlim = c(0, max(Length)), ylim = c(0, 1), type = type, ... ) plot(Survivorship ~ Age, xlim = c(0, max(Age)), ylim = c(0, 1), type = type, ... ) plot(FishedSurvivorship ~ Age, xlim = c(0, max(Age)), ylim = c(0, 1), type = type, ... ) }) invisible(x) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/plot.R
#' Population Parameters #' #' Generates an object of class `ypr_population`. #' #' @inheritParams params #' @param pi The annual capture probability. #' @return An object of class `ypr_population`. #' @export #' @examples #' ypr_population(k = 0.1, Linf = 90) ypr_population <- function(tmax = 20L, k = 0.15, Linf = 100, t0 = 0, k2 = 0.15, Linf2 = 100, L2 = 1000, Wb = 3, Ls = 50, Sp = 100, es = 1, Sm = 0, fb = 1, tR = 1L, BH = 1L, Rk = 3, n = 0.2, nL = 0.2, Ln = 1000, Lv = 50, Vp = 100, Llo = 0, Lup = 1000, Nc = 0, pi = 0.2, rho = 0, Hm = 0, Rmax = 1, Wa = 0.01, fa = 1, q = 0.1, RPR = 1) { population <- as.list(environment()) class(population) <- c("ypr_population") check_population(population) population }
/scratch/gouwar.j/cran-all/cranData/ypr/R/population.R
#' Populations #' #' @inheritParams params #' @inheritParams ypr_update #' #' @return A list of [ypr_population()] objects #' @family populations #' @export #' @examples #' ypr_populations(Rk = c(2.5, 4.6), Hm = c(0.2, 0.05)) ypr_populations <- function(..., expand = TRUE, names = NULL) { chk_flag(expand) chk_null_or(names, vld = vld_character) population <- ypr_population() parameters <- list(...) if (!length(parameters)) { populations <- list(population) class(populations) <- "ypr_populations" return(populations) } chk_named(parameters, x_name = "`...`") chk_subset(names(parameters), parameters(), x_name = "`names(...)`") chk_unique(names(parameters), x_name = "`names(...)`") if (expand) { parameters <- lapply(parameters, function(x) sort(unique(x))) parameters <- expand.grid(parameters) } else { lengths <- vapply(parameters, length, FUN.VALUE = 1L) lengths <- unique(lengths) lengths <- lengths[lengths != 1] if (length(lengths) > 1) { err( "Non-scalar parameter values must all be the same length (not ", cc(sort(lengths), conj = " and ", brac = ""), ")" ) } parameters <- as.data.frame(parameters) } populations <- list() for (i in seq_len(nrow(parameters))) { population <- as.list(parameters[i, , drop = FALSE]) attr(population, "out.attrs") <- NULL populations[[i]] <- do.call("ypr_population", population) } class(populations) <- "ypr_populations" if(!is.null(names)) { chk_not_any_na(names) chk_unique(names) if (!chk::vld_equal(length(populations), length(names))) { chk::abort_chk(paste0("Number of populations and names do not match. ", length(populations), " != ", length(names))) } } else { names <- ypr_names(populations) } names(populations) <- names populations }
/scratch/gouwar.j/cran-all/cranData/ypr/R/populations.R
#' @export print.ypr_population <- function(x, ...) { suppressWarnings(check_population(x)) nchar <- nchar(names(x)) nchar <- max(nchar) - nchar + 1 space <- vapply( nchar, function(x) paste0(rep(" ", times = x), collapse = ""), "" ) x <- paste0(names(x), ":", space, x, collapse = "\n") x <- paste0(x, "\n", collapse = "") cat(x) invisible(x) } #' @export print.ypr_populations <- function(x, ...) { suppressWarnings(check_populations(x)) if (length(x) == 1) { return(print(x[[1]])) } x$FUN <- c x <- do.call("mapply", x) x <- as.data.frame(x) x <- lapply(x, function(x) if (length(unique(x)) == 1) x[1] else x) nchar <- nchar(names(x)) nchar <- max(nchar) - nchar + 1 space <- vapply( nchar, function(x) paste0(rep(" ", times = x), collapse = ""), "" ) names <- names(x) x <- lapply(x, paste0, collapse = ", ") x <- paste0(names, ":", space, x, collapse = "\n") x <- paste0(x, "\n", collapse = "") cat(x) invisible(x) } ### Add ecotype and proportion and weight formatted as other things #' @export print.ypr_ecotypes <- function(x, ...) { suppressWarnings(check_ecotypes(x)) if (length(x) == 1) { ### should print with name and weight so not confused return(print(x[[1]])) } eco_names <- attr(x, "names") x$FUN <- c x <- do.call("mapply", x) x <- as.data.frame(x) x <- lapply(x, function(x) if (length(unique(x)) == 1) x[1] else x) nchar <- nchar(names(x)) nchar <- max(nchar) - nchar + 1 space <- vapply( nchar, function(x) paste0(rep(" ", times = x), collapse = ""), "" ) names <- names(x) x <- lapply(x, paste0, collapse = ", ") x <- paste0(names, ":", space, x, collapse = "\n") x <- paste0(x, "\n", collapse = "") eco_names <- paste0(eco_names, collapse = ", ") eco_names <- paste0("Ecotype", ": ", eco_names, collapse = "\n") eco_names <- paste0(eco_names, "\n", collapse = "") cat(x, eco_names, sep = "") invisible(x) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/print.R
get_prop <- function(x) { x <- ypr_get_par(x, "RPR") x / sum(x) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/prop.R
integer_parameters <- function() { .parameters$Parameter[.parameters$Integer == 1] } parameters <- function() { .parameters$Parameter } ecoall_parameters <- function() { .parameters$Parameter[.parameters$EcoAll == 1] } lines_population <- function(population) { population <- unclass(population) population <- lapply(population, as.character) population <- mapply(paste, names(population), population, sep = " = ") population <- unlist(population) population[integer_parameters()] <- paste0( population[integer_parameters()], "L" ) population <- paste(population, collapse = ", ") paste0("ypr_population(", population, ")", collapse = "") } #' Report #' #' Creates an Rmd file that can be used to generate a report. #' #' @inheritParams params #' @return An invisible character vector of the contents of the file. #' @family tabulate #' @export #' @examples #' \dontrun{ #' ypr_report(ypr_population(), file = tempfile(), ask = FALSE) #' } ypr_report <- function(population, Ly = 0, harvest = TRUE, biomass = FALSE, title = "Population Report", description = "", date = Sys.Date(), file = "report", view = FALSE, ask = TRUE) { check_population(population) chk_number(Ly) chk_gte(Ly) chk_flag(biomass) chk_flag(harvest) chk_string(title) chk_string(description) chk_date(date) chk_string(file) chk_flag(view) chk_flag(ask) if (!requireNamespace("usethis")) err("Package 'usethis' must be installed.") if (grepl("[.](R|r)md$", file)) { wrn("File extension on argument `file` is deprecated (please remove).") file <- .sub(file, "[.](R|r)md$", "") } file <- p0(file, ".Rmd") if (!ask_file(file, ask)) { return(invisible(character(0))) } data <- list( title = title, date = date, description = description, population = lines_population(population), Ly = Ly, harvest = harvest, biomass = biomass ) usethis::use_template( template = "template-report.Rmd", save_as = file, data = data, package = "ypr" ) if (view) { if (!requireNamespace("rmarkdown")) { err("Package 'rmarkdown' is required to render the report to html.") } file_html <- p0(.sub(file, "[.](R|r)md$", ""), ".html") if (!ask_file(file_html, ask)) { return(invisible(readLines(file))) } rmarkdown::render(file, output_format = "html_document", quiet = TRUE) if (!requireNamespace("rstudioapi")) { err("Package 'rstudioapi' is required to view the html report.") } rstudioapi::viewer(file_html) } invisible(readLines(file)) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/report.R
sr <- function(schedule, object) { schedule <- as.list(schedule) schedule$BH <- ypr_get_par(object, "BH") schedule$Rk <- ypr_get_par(object, "Rk") schedule$Rmax <- ypr_get_par(object, "Rmax") R0 <- 1 sr <- with(schedule, { phi <- sum(Fecundity * Spawning / 2 * Survivorship) phiF <- sum(Fecundity * Spawning / 2 * FishedSurvivorship) if(Rk <= 1) { Rk <- Rk * phi } alpha <- Rk / phi if (BH) { beta <- (alpha * phi - 1) / (R0 * phi) kappa <- alpha / beta R0F <- (alpha * phiF - 1) / (beta * phiF) } else { beta <- log(alpha * phi) / (R0 * phi) kappa <- alpha / (beta * exp(1)) R0F <- log(alpha * phiF) / (beta * phiF) } beta <- beta * kappa / Rmax R0 <- R0 / kappa * Rmax R0F <- R0F / kappa * Rmax S0 <- sum(Spawning * Survivorship * R0) S0F <- sum(Spawning * FishedSurvivorship * R0F) sr <- data.frame( alpha = alpha, beta = beta, Rk = Rk, phi = phi, phiF = phiF, R0 = R0, R0F = R0F, S0 = S0, S0F = S0F ) }) as_tibble(sr) } #' Stock-Recruitment Parameters #' #' Returns a single rowed data frame of the SR parameters: #' \describe{ #' \item{alpha}{Survival from egg to age tR at low density} #' \item{beta}{Density-dependence} #' \item{Rk}{Lifetime spawners per spawner at low density} #' \item{phi}{Lifetime eggs deposited per recruit at unfished equilibrium} #' \item{phiF}{Lifetime eggs deposited per recruit at the fished equilibrium} #' \item{R0}{Age tR recruits at the unfished equilibrium} #' \item{R0F}{Age tR recruits at the fished equilibrium} #' \item{S0}{Spawners at the unfished equilibrium} #' \item{S0F}{Spawners at the fished equilibrium} #' } #' #' @inheritParams params #' @return A data frame of the SR parameters. #' @family sr #' @export #' @examples #' ypr_sr(ypr_population()) # Beverton-Holt #' ypr_sr(ypr_population(BH = 0L)) # Ricker ypr_sr <- function(object) { if(!inherits(object, "ypr")) schedule <- ypr_tabulate_schedule(object) sr <- sr(schedule, object) sr$R0F <- max(sr$R0F, 0) sr$S0F <- max(sr$S0F, 0) sr }
/scratch/gouwar.j/cran-all/cranData/ypr/R/sr.R
#' Tabulate Biomass (and Eggs) #' #' Produces a data frame of the 'Weight' and 'Fecundity' and the number of #' 'Survivors' and 'Spawners' and the total 'Biomass' and 'Eggs' by 'Age' class. #' #' @inheritParams params #' @return A data frame #' @family tabulate #' @family biomass #' @export #' @examples #' ypr_tabulate_biomass(ypr_population()) ypr_tabulate_biomass <- function(population) { schedule <- ypr_tabulate_schedule(population) fish <- ypr_tabulate_fish(population) schedule <- schedule[c("Age", "Length", "Weight", "Fecundity")] fish <- fish[c("Survivors", "Spawners")] biomass <- cbind(schedule, fish) biomass$Biomass <- biomass$Weight * biomass$Survivors biomass$Eggs <- (biomass$Fecundity * biomass$Spawners) / 2 as_tibble(biomass) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/tabulate-biomass.R
sum_fish_table <- function(table, binwidth) { breaks <- seq(0, max(table[[1]] + binwidth), by = binwidth) table[[1]] <- cut(table[[1]], breaks = breaks) table[[1]] <- as.integer(table[[1]]) * binwidth table <- split(table, table[[1]]) table <- lapply(table, sum_fish) table <- do.call("rbind", table) row.names(table) <- NULL table } #' Tabulate Fish Numbers #' #' Produces a data frame of the number of fish in the 'Survivors', 'Spawners', #' 'Caught', 'Harvested', 'Released' and 'HandlingMortalities' categories by #' 'Length', 'Age' or 'Weight' class and 'Ecotype' (NA if not applicable) #' #' @inheritParams params #' @inheritParams ypr_plot_schedule #' @return A data frame #' @family tabulate #' @family fish #' @export #' @examples #' ypr_tabulate_fish(ypr_population()) ypr_tabulate_fish <- function(population, x = "Age", binwidth = 1L) { chk_string(x) chk_subset(x, c("Age", "Length", "Weight")) chk_whole_number(binwidth) chk_range(binwidth, c(1L, 1000L)) table <- ypr_tabulate_schedule(population) table <- as.data.frame(table) R0F <- sr(table, population)$R0F R0F <- max(0, R0F) pi <- ypr_get_par(population) Hm <- ypr_get_par(population, "Hm") table$Survivors <- table$FishedSurvivorship * R0F table$Spawners <- table$Survivors * table$Spawning table$Caught <- table$Survivors * table$Vulnerability * pi table$Harvested <- table$Caught * table$Retention table$Released <- table$Caught * (1 - table$Retention) table$HandlingMortalities <- table$Released * Hm if(!"Ecotype" %in% colnames(table)) table$Ecotype <- 1 table <- table[c( x, "Survivors", "Spawners", "Caught", "Harvested", "Released", "HandlingMortalities", "Ecotype" )] table <- split(table, table$Ecotype) table <- lapply(table, sum_fish_table, binwidth) table <- do.call("rbind", table) row.names(table) <- NULL if(length(unique(table$Ecotype)) == 1L) table$Ecotype <- NA_character_ as_tibble(table) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/tabulate-fish.R
#' Tabulate Population Parameters #' #' @inheritParams params #' @return A table of population parameters #' @family tabulate #' @family parameters #' @export #' @examples #' ypr_tabulate_parameters(ypr_population()) ypr_tabulate_parameters <- function(population) { check_population(population) parameters <- data.frame( Parameter = names(population), Value = unname(unlist(population)), stringsAsFactors = FALSE ) pattern <- "(\\\\item[{])([^}]+)([}])([{])([^}]+)([}])" rd <- tools::Rd_db("ypr")$ypr_population.Rd rd <- paste0(as.character(rd), collapse = "") gp <- gregexpr(pattern, rd) rd <- regmatches(rd, gp)[[1]] data <- data.frame( Parameter = .sub(rd, pattern, "\\2"), Description = .sub(rd, pattern, "\\5"), stringsAsFactors = FALSE ) parameters <- merge(parameters, data, by = "Parameter", sort = FALSE) as_tibble(parameters) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/tabulate-parameters.R
#' Life-History Schedule #' #' Generates the life-history schedule by age for a population. #' #' @keywords internal #' @description #' `r lifecycle::badge('deprecated')` #' #' DEPRECATED: Replace `ypr_schedule()` with `ypr_tabulate_schedule()` #' #' @export ypr_schedule <- function(population) { lifecycle::deprecate_warn( when = "0.4.0", what = "ypr_schedule()", with = "ypr_tabulate_schedule()" ) ypr_tabulate_schedule(population) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/tabulate-schedule-deprec.R
#' Life-History Schedule #' #' Generates the life-history schedule by age for a population. #' #' @inheritParams params #' @return A tibble of the life-history schedule by age. #' @family tabulate #' @family schedule #' @export #' @examples #' ypr_tabulate_schedule(ypr_population()) #' ypr_tabulate_schedule(ypr_ecotypes(Linf = c(10, 20))) ypr_tabulate_schedule <- function(object, ...) { UseMethod("ypr_tabulate_schedule") } #' @describeIn ypr_tabulate_schedule Tabulate Schedule #' @export ypr_tabulate_schedule.ypr_population <- function(object, ...) { check_population(object) chk::chk_unused(...) schedule <- impl_tabulate_schedule(object) as_tibble(schedule) } #' @describeIn ypr_tabulate_schedule Tabulate Schedule #' @export ypr_tabulate_schedule.ypr_ecotypes <- function(object, ...) { check_ecotypes(object) chk::chk_unused(...) schedules <- lapply(object, impl_tabulate_schedule) proportions <- get_prop(object) eco_names <- names(object) schedules <- mapply(function(schedules, proportions, eco_names) { schedules[["Ecotype"]] <- eco_names schedules[["Proportion"]] <- proportions as_tibble(schedules) }, schedules, proportions, eco_names, SIMPLIFY = FALSE) schedule <- do.call("rbind", schedules) schedule$Survivorship <- schedule$Survivorship * schedule$Proportion schedule$FishedSurvivorship <- schedule$FishedSurvivorship * schedule$Proportion schedule } impl_tabulate_schedule <- function(population) { schedule <- with(population, { t <- tR:tmax nt <- length(t) L <- length_at_age(population, t) W <- Wa * L^Wb E <- fa * W^fb if (Ls < 0) Ls <- length_at_age(population, -Ls) S <- exp(log(L / 1000) * Sp) / (exp(log(Ls / 1000) * Sp) + exp(log(L / 1000) * Sp)) * es N <- rep(n, nt) if (Ln < 0) Ln <- length_at_age(population, -Ln) N[L >= Ln] <- nL N <- 1 - ((1 - N) * (1 - S * Sm)) if (Lv < 0) Lv <- length_at_age(population, -Lv) V <- exp(log(L / 1000) * Vp) / (exp(log(Lv / 1000) * Vp) + exp(log(L / 1000) * Vp)) C <- pi * V R <- rep(1 - rho, nt) R[L < Llo | L > Lup] <- Nc U <- C * R + C * (1 - R) * Hm TotalMortality <- 1 - (1 - N) * (1 - U) Survivorship <- cumprod(1 - N) Survivorship <- c(1, Survivorship[-nt]) FishedSurvivorship <- cumprod(1 - TotalMortality) FishedSurvivorship <- c(1, FishedSurvivorship[-nt]) data.frame( Age = t, Length = L, Weight = W, Fecundity = E, Spawning = S, NaturalMortality = N, Vulnerability = V, Retention = R, FishingMortality = U, Survivorship = Survivorship, FishedSurvivorship = FishedSurvivorship ) }) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/tabulate-schedule.R
#' Tabulate Stock-Recruitment Parameters #' #' @inheritParams params #' @return A data.frame of stock-recruitment parameters. #' @family tabulate #' @family populations #' @family sr #' @export #' @examples #' ypr_tabulate_sr(ypr_population()) # Beverton-Holt #' ypr_tabulate_sr(ypr_population(BH = 0L)) # Ricker #' ypr_tabulate_sr(ypr_populations(Rk = c(2.5, 4.6))) ypr_tabulate_sr <- function(object, ...) { UseMethod("ypr_tabulate_sr") } #' @describeIn ypr_tabulate_sr Tabulate Stock-Recruitment Parameters #' @export ypr_tabulate_sr.default <- function(object, Ly = 0, harvest = TRUE, biomass = FALSE, all = FALSE, ...) { chkor_vld(vld_is(object, "ypr_population"), vld_is(object, "ypr_ecotypes")) sr <- ypr_sr(object) sr$BH <- ypr_get_par(object, "BH") pi <- ypr_get_par(object) object_pi <- ypr_optimise( object, Ly = Ly, harvest = harvest, biomass = biomass ) object <- set_par(object, "pi", object_pi) optimal_sr <- ypr_sr(object) table <- with(sr, { data <- data.frame( Type = c("unfished", "actual", "optimal"), pi = c(0, pi, object_pi), u = ypr_exploitation(object, c(0, pi, object_pi)), Eggs = c(phi * R0, phiF * R0F, optimal_sr$phiF * optimal_sr$R0F), stringsAsFactors = FALSE ) fun <- if (only(BH) == 1L) bh else ri data$Recruits <- fun(data$Eggs, alpha, beta) data$Spawners <- c(S0, S0F, optimal_sr$S0F) data$Fecundity <- data$Eggs / data$Spawners * 2 data }) if (all) table <- add_parameters(table, object) as_tibble(table) } #' @describeIn ypr_tabulate_sr Tabulate Stock-Recruitment Parameters #' @export ypr_tabulate_sr.ypr_populations <- function(object, Ly = 0, harvest = TRUE, biomass = FALSE, all = FALSE, ...) { chk_flag(all) sr <- lapply(object, ypr_tabulate_sr, Ly = Ly, harvest = harvest, biomass = biomass, all = TRUE, ... ) sr <- do.call("rbind", sr) if (!all) sr <- drop_constant_parameters(sr) as_tibble(sr) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/tabulate-sr.R
#' Tabulate Yield #' #' @inheritParams params #' #' @return A data frame. #' @family tabulate #' @family populations #' @family yield #' @export #' @examples #' ypr_tabulate_yield(ypr_population()) #' ypr_tabulate_yield(ypr_populations(Rk = c(3, 5))) ypr_tabulate_yield <- function(object, ...) { UseMethod("ypr_tabulate_yield") } #' @describeIn ypr_tabulate_yield Tabulate Yield #' @export ypr_tabulate_yield.default <- function(object, Ly = 0, harvest = TRUE, biomass = FALSE, type = "both", all = FALSE, ...) { chkor_vld(vld_is(object, "ypr_population"), vld_is(object, "ypr_ecotypes")) chk_string(type) chk_subset(type, c("both", "actual", "optimal")) actual_pi <- ypr_get_par(object) actual_yield <- ypr_yield(object, Ly = Ly, harvest = harvest, biomass = biomass ) if (type == "actual") { yield <- data.frame( Type = "actual", pi = actual_pi, u = ypr_exploitation(object, actual_pi), Yield = actual_yield, Age = attr(actual_yield, "Age"), Length = attr(actual_yield, "Length"), Weight = attr(actual_yield, "Weight"), Effort = attr(actual_yield, "Effort"), stringsAsFactors = FALSE ) } else { optimal_pi <- ypr_optimize(object, Ly = Ly, harvest = harvest, biomass = biomass ) object <- ypr_update(object, pi = optimal_pi) optimal_yield <- ypr_yield(object, Ly = Ly, harvest = harvest, biomass = biomass ) yield <- data.frame( Type = c("actual", "optimal"), pi = c(actual_pi, optimal_pi), u = ypr_exploitation(object, c(actual_pi, optimal_pi)), Yield = c(actual_yield, optimal_yield), Age = c(attr(actual_yield, "Age"), attr(optimal_yield, "Age")), Length = c(attr(actual_yield, "Length"), attr(optimal_yield, "Length")), Weight = c(attr(actual_yield, "Weight"), attr(optimal_yield, "Weight")), Effort = c(attr(actual_yield, "Effort"), attr(optimal_yield, "Effort")), stringsAsFactors = FALSE ) if (type == "optimal") { yield <- yield[yield$Type == "optimal", ] } } if (all) yield <- add_parameters(yield, object) as_tibble(yield) } #' @describeIn ypr_tabulate_yield Tabulate Yield #' @export ypr_tabulate_yield.ypr_populations <- function(object, Ly = 0, harvest = TRUE, biomass = FALSE, type = "both", all = FALSE, ...) { chk_flag(all) yield <- lapply(object, ypr_tabulate_yield, Ly = Ly, harvest = harvest, biomass = biomass, type = type, all = TRUE, ... ) yield <- do.call("rbind", yield) if (!all) yield <- drop_constant_parameters(yield) as_tibble(yield) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/tabulate-yield.R
#' Tabulate Yields #' #' @inheritParams params #' #' @return A data frame. #' @family tabulate #' @family populations #' @export #' @examples #' ypr_tabulate_yields(ypr_population()) #' ypr_tabulate_yields( #' ypr_populations( #' Rk = c(3, 5) #' ), #' pi = seq(0, 1, length.out = 10) #' ) #' ypr_tabulate_yields(ypr_ecotypes(Linf = c(10, 20))) ypr_tabulate_yields <- function(object, ...) { UseMethod("ypr_tabulate_yields") } #' @describeIn ypr_tabulate_yields Tabulate Yields #' @export ypr_tabulate_yields.default <- function(object, pi = seq(0, 1, length.out = 100), Ly = 0, harvest = TRUE, biomass = FALSE, all = FALSE, ...) { chkor_vld(vld_is(object, "ypr_population"), vld_is(object, "ypr_ecotypes")) chk_number(Ly) chk_numeric(pi) chk_not_empty(pi) chk_not_any_na(pi) chk_range(pi, c(0, 1)) yields <- lapply(pi, tabulate_yield_pi, object = object, Ly = Ly, harvest = harvest, biomass = biomass, all = all ) yields <- do.call(rbind, yields) as_tibble(yields) } #' @describeIn ypr_tabulate_yields Tabulate Yields #' @export ypr_tabulate_yields.ypr_populations <- function(object, pi = seq(0, 1, length.out = 100), Ly = 0, harvest = TRUE, biomass = FALSE, all = FALSE, ...) { chk_flag(all) yield <- lapply(object, ypr_tabulate_yields, pi = pi, Ly = Ly, harvest = harvest, biomass = biomass, all = TRUE, ... ) yield <- do.call("rbind", yield) if (!all) yield <- drop_constant_parameters(yield) as_tibble(yield) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/tabulate-yields.R
save_csv <- function(x) { path <- tempfile(fileext = ".csv") readr::write_csv(x, path) path } expect_snapshot_data <- function(x, name) { testthat::skip_on_ci() testthat::skip_on_os("windows") path <- save_csv(x) testthat::expect_snapshot_file(path, paste0(name, ".csv")) } save_png <- function(x, width = 400, height = 400) { path <- tempfile(fileext = ".png") grDevices::png(path, width = width, height = height) on.exit(grDevices::dev.off()) print(x) path } expect_snapshot_plot <- function(x, name) { testthat::skip_on_ci() testthat::skip_on_os("windows") path <- save_png(x) testthat::expect_snapshot_file(path, paste0(name, ".png")) } ## Inspiration from usethis package https://usethis.r-lib.org/index.html ## If session temp directory appears to be, or be within, a project, there ## will be large scale, spurious test failures. ## The IDE sometimes leaves .Rproj files behind in session temp directory or ## one of its parents. ## Delete such files manually. create_local_package <- function(dir = tempfile(pattern = "testpkg"), env = parent.frame()) { old_project <- proj_get_() # this could be `NULL`, i.e. no active project old_wd <- getwd() # not necessarily same as `old_project` withr::defer( { unlink(dir, recursive = TRUE) }, envir = env ) withr::with_options( list(usethis.quiet = TRUE), usethis::create_package( dir, rstudio = FALSE, open = FALSE, check_name = FALSE ) ) withr::defer(usethis::proj_set(old_project, force = TRUE), envir = env) usethis::proj_set(dir) withr::defer( { setwd(old_wd) }, envir = env ) setwd(usethis::proj_get()) invisible(usethis::proj_get()) } proj <- new.env(parent = emptyenv()) proj_get_ <- function() proj$cur proj_set_ <- function(path) { old <- proj$cur proj$cur <- path invisible(old) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/test-helpers.R
#' @export unique.ypr_populations <- function(x, ...) { x <- as.data.frame(x) x <- unique(x) as_ypr_populations(x) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/unique.R
#' Update a Population Object #' #' `r lifecycle::badge('deprecated')` for [`ypr_update()`]. #' #' @param population A ypr_population object. #' @param ... One or more parameter values from `ypr_population()`. #' #' @export ypr_population_update <- function(population, ...) { lifecycle::deprecate_soft(" 0.5.3", "ypr_population_update()", "ypr_update()") check_population(population) ypr_update(population, ...) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/update-deprec.R
#' Update a YPR Object #' Currently just works with scalar parameters for populations and ecotypes. #' #' @param x A population, populations or ecotypes object to update. #' @param ... One or more parameter values from `ypr_population()`. #' @export ypr_update <- function(x, ...) { UseMethod("ypr_update") } #' @export update.ypr_population <- function(object, ...) { ypr_update(object, ...) } #' @export update.ypr_populations <- function(object, ...) { ypr_update(object, ...) } #' @export update.ypr_ecotypes <- function(object, ...) { ypr_update(object, ...) } #' @describeIn ypr_update Update Population Parameters #' #' @export #' @examples #' ypr_update(ypr_population(), Rk = 2.5) ypr_update.ypr_population <- function(x, ...) { parameters <- list(...) x[names(parameters)] <- unname(parameters) check_population(x) x } #' @describeIn ypr_update Update Populations Parameters #' #' @export #' @examples #' ypr_update(ypr_populations(Rk = c(2.5, 4)), Rk = 2.5) ypr_update.ypr_populations <- function(x, ...) { x <- lapply(x, ypr_update, ...) class(x) <- "ypr_populations" names(x) <- ypr_names(x) x } #' @describeIn ypr_update Update Populations Parameters #' #' @export #' @examples #' ypr_update(ypr_ecotypes(Linf = c(2.5, 4)), k = 1.5) ypr_update.ypr_ecotypes <- function(x, ...) { x <- lapply(x, ypr_update, ...) class(x) <- "ypr_ecotypes" names(x) <- ypr_names(x) check_ecotypes(x) x }
/scratch/gouwar.j/cran-all/cranData/ypr/R/update.R
#' Length At Age #' #' @inheritParams params #' @return A double vector of the lengths. #' @family calculate #' @export #' @examples #' ypr_length_at_age(ypr_population(), seq(0, 5, by = 0.5)) ypr_length_at_age <- function(population, age) { check_population(population) chk_numeric(age) chk_vector(age) chk_gte(age) length_at_age(population, age) } #' Age At Length #' #' @inheritParams params #' @return A double vector of the lengths. #' @family calculate #' @export #' @examples #' ypr_age_at_length(ypr_population(), seq(0, 100, by = 10)) ypr_age_at_length <- function(population, length) { check_population(population) chk_numeric(length) chk_vector(length) chk_gte(length) age_at_length(population, length) } inst2inter <- function(x) { 1 - exp(-x) } inter2inst <- function(x) { -log(1 - x) } length_at_age <- function(population, age) { with(population, { if (L2 < 0) L2 <- Linf * (1 - exp(-k * (-L2 - t0))) L <- Linf * (1 - exp(-k * (age - t0))) t2 <- -log(1 - min(L2 / Linf, 1)) / k + t0 L[age > t2] <- L2 + (Linf2 - L2) * (1 - exp(-k2 * (age[age > t2] - t2))) L[L < 0] <- 0 L }) } age_at_length <- function(population, length) { with(population, { if (L2 < 0) L2 <- Linf * (1 - exp(-k * (-L2 - t0))) t <- -log(1 - pmin(length / Linf, 1)) / k + t0 t2 <- -log(1 - pmin(L2 / Linf, 1)) / k + t0 t[t > t2] <- -log(1 - pmin((length[t > t2] - L2) / (Linf2 - L2), 1)) / k2 + t2 t }) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/utils.R
yield <- function(schedule, object, Ly = 0, harvest = TRUE, biomass = FALSE) { schedule <- as.list(schedule) schedule$pi <- ypr_get_par(object) schedule$q <- ypr_get_par(object, "q") schedule <- c(schedule, sr(schedule, object)) yield <- with(schedule, { FishedSurvivorship[Length < Ly] <- 0 yield <- R0F * FishedSurvivorship * Vulnerability * pi if (harvest) yield <- yield * Retention age <- weighted.mean(Age, yield) length <- weighted.mean(Length, yield) weight <- weighted.mean(Weight, yield) effort <- log(1 - pi) / log(1 - q) if (biomass) { yield <- yield * Weight / 1000 } yield <- sum(yield) if (yield <= 0) { age <- NA length <- NA weight <- NA } attr(yield, "Age") <- age attr(yield, "Length") <- length attr(yield, "Weight") <- weight attr(yield, "Effort") <- effort yield }) yield } yield_pi <- function(pi, object, Ly, harvest, biomass) { object <- set_par(object, "pi", pi) schedule <- ypr_tabulate_schedule(object) yield(schedule, object, Ly = Ly, harvest = harvest, biomass = biomass) } #' Yield #' #' Calculates the yield for a population. #' #' By default, with `Rmax = 1` the number of individuals is the proportion of #' the recruits at the carrying capacity. If the yield is given in terms of the #' biomass (kg) then the scaling also depends on the value of `Wa` (g). #' #' @inheritParams params #' @return The yield as number of fish or biomass. #' @family yield #' @family calculate #' @export #' @examples #' ypr_yield(ypr_population()) #' ypr_yield(ypr_ecotypes(Linf = c(100, 200))) ypr_yield <- function(object, Ly = 0, harvest = TRUE, biomass = FALSE, ...) { chk_number(Ly) chk_gte(Ly) chk_flag(biomass) chk_flag(harvest) schedule <- ypr_tabulate_schedule(object) yield <- yield( schedule, object, Ly = Ly, harvest = harvest, biomass = biomass ) sanitize(yield) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/yield.R
#' Yields #' #' Calculates the yield(s) for a population based on one or more capture rates. #' #' @inheritParams params #' @return A numeric vector of the yields. #' @family yield #' @family calculate #' @export #' @examples #' pi <- seq(0, 1, length.out = 30) #' plot(pi, ypr_yields(ypr_population(), pi), type = "l") ypr_yields <- function(object, pi = seq(0, 1, length.out = 100), Ly = 0, harvest = TRUE, biomass = FALSE) { chk_number(Ly) chk_gte(Ly) chk_flag(biomass) chk_flag(harvest) chk_numeric(pi) chk_not_empty(pi) chk_not_any_na(pi) chk_range(pi, c(0, 1)) yields <- vapply(pi, FUN = yield_pi, FUN.VALUE = 1, object = object, Ly = Ly, harvest = harvest, biomass = biomass ) sanitize(yields) }
/scratch/gouwar.j/cran-all/cranData/ypr/R/yields.R
#' @keywords internal "_PACKAGE" ## usethis namespace: start ## usethis namespace: end NULL
/scratch/gouwar.j/cran-all/cranData/ypr/R/ypr-package.R
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 4 ) ## ----------------------------------------------------------------------------- library(ypr) library(ggplot2) # for plotting ecotypes <- ypr_ecotypes( Linf2 = 200, L2 = c(100, 50), Ls = c(50, 75), pi = 0.05, names = c("small", "large"), RPR = c(0.8, 0.2)) ypr_plot_schedule(ecotypes) + scale_color_manual(values = c("black", "blue")) ypr_plot_schedule(ecotypes, x = "Age", y = "Spawning") + scale_color_manual(values = c("black", "blue")) ## ---- fig.width=6, fig.height=4----------------------------------------------- ypr_plot_fish(ecotypes, color = "white") + scale_fill_manual(values = c("black", "blue")) ypr_plot_fish(ecotypes, x = "Length", y = "Caught", color = "white", binwidth = 15) + scale_fill_manual(values = c("black", "blue")) ## ---- fig.width=6, fig.height=4----------------------------------------------- ypr_plot_sr(ecotypes, biomass = TRUE) ypr_tabulate_sr(ecotypes, biomass = TRUE) ## ---- fig.width=6, fig.height=4----------------------------------------------- ypr_tabulate_yield(ecotypes, biomass = TRUE) ypr_plot_yield(ecotypes, biomass = TRUE)
/scratch/gouwar.j/cran-all/cranData/ypr/inst/doc/ecotypes.R
--- title: "Ecotypes" author: "Joe Thorley and Ayla Pearson" date: "`r Sys.Date()`" bibliography: bibliography.bib output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Ecotypes} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 4 ) ``` ## Ecotypes In the `ypr` package a population is considered to be group of interbreeding fish that are indistinguishable to anglers. Ecotypes are groups of individuals with a population that have different life-history strategies. Consequently, ecotypes must share key fishery (`pi`, `Llo`, `Lup`, `Nc`, `rho`, `Hm` and `q`) and stock recruitment (`BH`, `RK`, `tR` and `Rmax`) parameters.y To use a yield-per-recruit approach it is also necessary to assume that the relative proportion of recruits (`RPR`) adopting each life-history strategy is independent of the size and composition of the parental stock. ## Two Ecotypes Consider a population with a smaller ecotype and a second larger ecotype that delays maturation in order to achieve sufficient size to switch to piscivory which allows it to grow much larger. ```{r} library(ypr) library(ggplot2) # for plotting ecotypes <- ypr_ecotypes( Linf2 = 200, L2 = c(100, 50), Ls = c(50, 75), pi = 0.05, names = c("small", "large"), RPR = c(0.8, 0.2)) ypr_plot_schedule(ecotypes) + scale_color_manual(values = c("black", "blue")) ypr_plot_schedule(ecotypes, x = "Age", y = "Spawning") + scale_color_manual(values = c("black", "blue")) ``` ### Fish ```{r, fig.width=6, fig.height=4} ypr_plot_fish(ecotypes, color = "white") + scale_fill_manual(values = c("black", "blue")) ypr_plot_fish(ecotypes, x = "Length", y = "Caught", color = "white", binwidth = 15) + scale_fill_manual(values = c("black", "blue")) ``` ### Stock-Recruitment ```{r, fig.width=6, fig.height=4} ypr_plot_sr(ecotypes, biomass = TRUE) ypr_tabulate_sr(ecotypes, biomass = TRUE) ``` ### Yield ```{r, fig.width=6, fig.height=4} ypr_tabulate_yield(ecotypes, biomass = TRUE) ypr_plot_yield(ecotypes, biomass = TRUE) ```
/scratch/gouwar.j/cran-all/cranData/ypr/inst/doc/ecotypes.Rmd
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 4 ) ## ---- echo=FALSE-------------------------------------------------------------- library(ypr) nparameters <- length(ypr_population()) caption <- paste("Table 1. The", nparameters, "parameters with their default values and descriptions.") table <- ypr_tabulate_parameters(ypr_population()) table$Description <- sub("\n", " ", table$Description) knitr::kable(table, caption = caption) ## ----------------------------------------------------------------------------- population <- ypr_population() ypr_plot_schedule(population, "Age", "Length") ## ----------------------------------------------------------------------------- ypr_plot_schedule(ypr_population_update(population, L2 = 75, Linf2 = 200), "Age", "Length") ## ----------------------------------------------------------------------------- population <- ypr_population_update(population, Wa = 0.01, Wb = 3) ypr_plot_schedule(population, "Length", "Weight") ## ----------------------------------------------------------------------------- population <- ypr_population_update(population, fa = 1, fb = 1) ypr_plot_schedule(population, "Weight", "Fecundity") ## ----------------------------------------------------------------------------- population <- ypr_population_update(population, Ls = 50, Sp = 10, es = 0.8) ypr_plot_schedule(population, "Length", "Spawning") ## ----------------------------------------------------------------------------- ypr_plot_schedule(population, "Length", "NaturalMortality") ## ----------------------------------------------------------------------------- ypr_plot_schedule(ypr_population_update(population, nL = 0.15, Ln = 60), "Length", "NaturalMortality") ## ----------------------------------------------------------------------------- population <- ypr_population_update(population, Sm = 0.5) ypr_plot_schedule(population, "Length", "NaturalMortality") ## ----------------------------------------------------------------------------- population <- ypr_population_update(population, Lv = 50, Vp = 50) ypr_plot_schedule(population, "Length", "Vulnerability") ## ----------------------------------------------------------------------------- population <- ypr_population_update(population, rho = 0.5, Llo = 40, Lup = 70, Nc = 0.1) ypr_plot_schedule(population, "Length", "Retention") ## ----------------------------------------------------------------------------- population <- ypr_population_update(population, pi = 0.3, Hm = 0.2) ypr_plot_schedule(population, "Length", "FishingMortality") ## ----------------------------------------------------------------------------- population <- ypr_population_update(population, Rk = 3) ypr_plot_sr(population, plot_values = FALSE) ## ----------------------------------------------------------------------------- population <- ypr_population_update(population, BH = 0L) ypr_plot_sr(population, plot_values = FALSE) ## ----------------------------------------------------------------------------- ypr_plot_schedule(population, "Age", "Survivorship") ## ----------------------------------------------------------------------------- ypr_plot_yield(population, harvest = TRUE, biomass = TRUE, Ly = 60) ypr_tabulate_yield(population, harvest = TRUE, biomass = TRUE, Ly = 60) ## ----------------------------------------------------------------------------- ypr_plot_yield(population, y = "Effort", harvest = TRUE, biomass = TRUE, Ly = 60) ## ----------------------------------------------------------------------------- ypr_plot_yield(population, y = "YPUE", harvest = TRUE, biomass = TRUE, Ly = 60)
/scratch/gouwar.j/cran-all/cranData/ypr/inst/doc/ypr.R
--- title: "Get Started with ypr" author: "Joe Thorley" date: "`r Sys.Date()`" bibliography: bibliography.bib output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Get Started with ypr} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 4 ) ``` ## Introduction > Fish are born, they grow, they reproduce and they die – whether from natural causes or from fishing. That’s it. Modelers just use complicated (or not so complicated) math to iron out the details. @cooper_guide_2006 Equilibrium based yield per recruit (YPR) methods [@walters_fisheries_2004] estimate the capture rate that optimizes the yield under the assumption that there is no stochasticity and all density-dependence is captured by the stock-recruitment relationship. The remaining population processes of growth, reproduction and death are captured through a series of relatively straight-forward deterministic equations. ```{r, echo=FALSE} library(ypr) nparameters <- length(ypr_population()) caption <- paste("Table 1. The", nparameters, "parameters with their default values and descriptions.") table <- ypr_tabulate_parameters(ypr_population()) table$Description <- sub("\n", " ", table$Description) knitr::kable(table, caption = caption) ``` ## Growth ### Length In `ypr` length (in cm) at age ($t$) is assumed to follow a Von Bertalanffy growth curve $$L = L_{\infty} \cdot (1 - \exp(-k \cdot (t-t_0)))$$ ```{r} population <- ypr_population() ypr_plot_schedule(population, "Age", "Length") ``` which can be biphasic ```{r} ypr_plot_schedule(ypr_population_update(population, L2 = 75, Linf2 = 200), "Age", "Length") ``` ### Weight The weight ($W$) at a given length is assumed to follow the classic allometric relationship $$W = w_\alpha \cdot L^{w_\beta}$$ ```{r} population <- ypr_population_update(population, Wa = 0.01, Wb = 3) ypr_plot_schedule(population, "Length", "Weight") ``` Its worth noting that $w_\alpha$, which is the extrapolated weight (g) of a 1 cm individual, is a scaling constant that only affects the estimate of the yield (when calculated in terms of the biomass), ie, it does not affect the estimate of the optimal capture rate. ## Reproduction ### Fecundity The fecundity ($F$) is assumed to scale allometrically with the weight according to the equation $$F = f_\alpha \cdot W^{f_\beta}$$ ```{r} population <- ypr_population_update(population, fa = 1, fb = 1) ypr_plot_schedule(population, "Weight", "Fecundity") ``` $f_\alpha$, which is the extrapolated eggs produced by a 1 g female, is a scaling constant with no effect on the yield or optimal capture rate. ### Spawning The probability of spawning at length $L$ is determined by the equation $$S = \frac{L^{S_p}}{L_s^{S_p} + L^{S_p}} \cdot es$$ ```{r} population <- ypr_population_update(population, Ls = 50, Sp = 10, es = 0.8) ypr_plot_schedule(population, "Length", "Spawning") ``` ## Death ### Natural Mortality By default the natural annual interval mortality rate ($n$) is assumed to be constant ```{r} ypr_plot_schedule(population, "Length", "NaturalMortality") ``` although like growth it can vary biphasically ```{r} ypr_plot_schedule(ypr_population_update(population, nL = 0.15, Ln = 60), "Length", "NaturalMortality") ``` The natural mortality rate can also be affected by spawning mortality ```{r} population <- ypr_population_update(population, Sm = 0.5) ypr_plot_schedule(population, "Length", "NaturalMortality") ``` ### Fishing Mortality The vulnerability to capture ($V$) is assumed to vary by length as follows $$V = \frac{L^{V_p}}{L_v^{V_p} + L^{V_p}}$$ ```{r} population <- ypr_population_update(population, Lv = 50, Vp = 50) ypr_plot_schedule(population, "Length", "Vulnerability") ``` If $V_p$ is 100 then vulnerability is effectively knife-edged. The probabilty of being retained if captured ($R$) depends on the release rate ($\rho$), the slot limits ($L_{lo}$ and $L_{up}$) and the non-compliance with the limits ($N_c$) ```{r} population <- ypr_population_update(population, rho = 0.5, Llo = 40, Lup = 70, Nc = 0.1) ypr_plot_schedule(population, "Length", "Retention") ``` The fishing mortality ($U$) depends on $V$, $R$ and the probability of capture when fully vulnerable ($pi$) as well as the hooking mortality ($H_m$) $$U = V \cdot \pi \cdot R + V \cdot \pi \cdot (1 - R) \cdot H_m$$ The calculation assumes that a released fish cannot be recaught in the same year. ```{r} population <- ypr_population_update(population, pi = 0.3, Hm = 0.2) ypr_plot_schedule(population, "Length", "FishingMortality") ``` ## Recruitment With growth, reproduction and death defined, the final task is to estimate the recruitment (birth) rate. This requires the lifetime number of spawners per spawner at low density ($R_k$) and the recruitment age ($R_t$; by default 1) to be defined. If recruitment follows a Beverton-Holt ($BH = 1$) curve then $$R = \frac{\alpha \cdot E}{(\beta \cdot E + 1)}$$ ```{r} population <- ypr_population_update(population, Rk = 3) ypr_plot_sr(population, plot_values = FALSE) ``` where $E$ is the annual eggs (stock) and $R$ is the annual recruits at age $R_t$. With a Ricker curve ($BH = 0$) the relationship is as follows $$R = \alpha \cdot E \cdot \exp (-\beta \cdot E)$$ ```{r} population <- ypr_population_update(population, BH = 0L) ypr_plot_sr(population, plot_values = FALSE) ``` The number of recruits at the carrying capacity ($R_\text{max}$) is a scaling constant that only affects the estimate of the yield. Before calculating the recruitment it is important to introduce the concept of the (unfished) survivorship ($lx_a$) which is the probability of a recruit surviving to age $a$ in the absence of fish mortality. ```{r} ypr_plot_schedule(population, "Age", "Survivorship") ``` The unfished survivorship ($lx_a$) is defined recursively by $$lx_{R_t} = 1, lx_a = lx_{a-1} \cdot (1-N_{a-1}) \;\text{for}\; a > R_t$$ where $N_a$ is the annual interval natural mortality at age $a$. And the fished survivorship ($lx_a^F$) is $$lx_{R_t}^F = 1, lx_a^F = lx_{a-1}^F \cdot (1 - (1 - N_{a-1}) \cdot (1 - U_{a-1})) \;\text{for}\; a > R_t$$ The lifetime number of eggs deposited per (unfished) recruit ($\phi$) is then just $$\phi = \sum_{a = R_t}^{t_\text{max}} lx_a \cdot F_a/2 \cdot S_a$$ where $t_\text{max}$ is the maximum age considered (by default `r ypr_population()$tmax`) and $F_a$ the fecundity at age $a$ is divided by two as the sex ratio is assumed to 1:1 and $S_a$ is the probability of spawning. The fished equivalent is denoted $\phi_F$. It important to realize that at the unfished equilibrium the annual number of recruits ($R_0$) is related to the annual egg deposition according to the following equation $$E_0 = \phi \cdot R_0$$ By definition $$\alpha = \frac{R_k \cdot R_0}{E_0} = \frac{R_k}{\phi}$$ The $\beta$ term of the Beverton-Holt curve can then be found by rearranging the following formula $$R_0 = \frac{\alpha \cdot \phi \cdot R_0}{\beta \cdot \phi \cdot R_0 + 1}$$ $$\beta \cdot \phi \cdot R_0 + 1 = \alpha \cdot \phi$$ $$\beta = \frac{\alpha \cdot \phi - 1}{\phi \cdot R_0}$$ The equivalent equation for the Ricker curve is arrived at as follows $$R_0 = \alpha \cdot \phi \cdot R_0 \cdot \exp (-\beta \cdot \phi \cdot R_0)$$ $$\frac{1}{\exp (-\beta \cdot \phi \cdot R_0)} = \alpha \cdot \phi$$ $$\beta \cdot \phi \cdot R_0 = \log(\alpha \cdot \phi)$$ $$\beta = \frac{\log(\alpha \cdot \phi)}{\phi \cdot R_0}$$ The number of recruits at the fished equilibrium ($R_{0F}$) can then be found for the Beverton-Holt curve as follows $$R_{0F} = \frac{\alpha \cdot \phi_F \cdot R_{0F}}{\beta \cdot \phi_F \cdot R_{0F} + 1}$$ $$\beta \cdot \phi_F \cdot R_{0F} + 1 = \alpha \cdot \phi_F$$ $$R_{0F} = \frac{\alpha \cdot \phi_F - 1}{\beta \cdot \phi_F}$$ and for the Ricker $$R_{0F} = \alpha \cdot \phi_F \cdot R_{0F} \cdot \exp (-\beta \cdot \phi_F \cdot R_{0F})$$ $$\frac{1}{\exp(-\beta \cdot \phi_F \cdot R_{0F})} = \alpha \cdot \phi_F$$ $$\beta \cdot \phi_F \cdot R_{0F} = \log(\alpha \cdot \phi_F)$$ $$R_{0F} = \frac{\log(\alpha \cdot \phi_F)}{\beta \cdot \phi_F}$$ Finally the estimates are rescaled so that the carrying capacity is identical to $R_\text{max}$ through the following transformations $$ \beta = \beta \cdot \kappa / R_\text{max} $$ $$ R_0 = R_0 / \kappa \cdot R_\text{max} $$ $$ R_{0F} = R_{0F} / \kappa \cdot R_\text{max} $$ where $\kappa$, which is the carrying capacity in the original scale, is $\alpha/\beta$ for the Beverton-Holt and $\alpha/(\beta \cdot e)$ for the Ricker curve. ## Yield When the yield is simply the number of fish caught (irrespective of the weight or whether or not its harvested) then it is given by $$Y = \sum_{a = R_t}^{t_\text{max}} R_{0F} \cdot lx_a^F \cdot \pi \cdot V_a$$ if only harvested fish are considered it becomes $$Y = \sum_{a = R_t}^{t_\text{max}} R_{0F} \cdot lx_a^F \cdot \pi \cdot V_a \cdot R$$ and if the total weight (in kg) is important then its $$Y = \sum_{a = R_t}^{t_\text{max}} R_{0F} \cdot lx_a^F \cdot \pi \cdot V_a \cdot R \cdot W_a/1000$$ and if only trophy fish are to be considered then its $$Y = \sum_{a = R_t}^{t_\text{max}} \text{if}(La < L_y)\ 0\ \text{else}\ R_{0F} \cdot lx_a^F \cdot \pi \cdot V_a \cdot R \cdot W_a/1000$$ where $L_y$ is the minimum length of a trophy fish. ```{r} ypr_plot_yield(population, harvest = TRUE, biomass = TRUE, Ly = 60) ypr_tabulate_yield(population, harvest = TRUE, biomass = TRUE, Ly = 60) ``` ## Efficiency The catchability `q` indicates the probability of capture for a unit of effort ($E$). It is assumed to be related to $\pi$ according to the relationship $$\pi = 1 - \exp(\log(1-q)\cdot E)$$ which can be rearranged to give $$E = \frac{\log(1-\pi)}{\log(1-q)}.$$ ```{r} ypr_plot_yield(population, y = "Effort", harvest = TRUE, biomass = TRUE, Ly = 60) ``` ```{r} ypr_plot_yield(population, y = "YPUE", harvest = TRUE, biomass = TRUE, Ly = 60) ``` ## References
/scratch/gouwar.j/cran-all/cranData/ypr/inst/doc/ypr.Rmd
--- title: "{{{ title }}}" date: "{{{ date }}}" output: html_document --- ```{r setup, include = FALSE} knitr::opts_chunk$set( echo = FALSE, fig.width = 4, fig.height = 4 ) ``` {{{ description }}} ```{r} library(ypr) population <- {{{ population }}} ``` ```{r} knitr::kable(ypr_tabulate_parameters(population)) ``` ```{r} ypr_plot_schedule(population) ypr_plot_schedule(population, "Length", "Weight") ypr_plot_schedule(population, "Weight", "Fecundity") ypr_plot_schedule(population, "Length", "Spawning") ``` ```{r} ypr_plot_schedule(population, "Length", "Vulnerability") ypr_plot_schedule(population, "Length", "Retention") ypr_plot_schedule(population, "Length", "FishingMortality") ypr_plot_schedule(population, "Length", "NaturalMortality") ``` ```{r} ypr_plot_fish(population, color = "white") ypr_plot_fish(population, "Length", "Caught") ypr_plot_fish(population, "Age", "Spawners", color = "white") ypr_plot_fish(population, "Length", "Spawners") ypr_plot_biomass(population, color = "white") ypr_plot_biomass(population, y = "Eggs", color = "white") ``` ```{r, fig.width = 6, fig.height = 4} ypr_plot_sr(population) knitr::kable(ypr_sr(population)) knitr::kable(ypr_tabulate_sr(population)) ``` ```{r, fig.width = 6, fig.height = 4} ypr_plot_yield(population, Ly = {{{ Ly }}}, harvest = {{{ harvest }}}, biomass = {{{ biomass }}}) knitr::kable(ypr_tabulate_yield(population, Ly = {{{ Ly }}}, harvest = {{{ harvest }}}, biomass = {{{ biomass }}})) ```
/scratch/gouwar.j/cran-all/cranData/ypr/inst/templates/template-report.Rmd
--- title: "Ecotypes" author: "Joe Thorley and Ayla Pearson" date: "`r Sys.Date()`" bibliography: bibliography.bib output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Ecotypes} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 4 ) ``` ## Ecotypes In the `ypr` package a population is considered to be group of interbreeding fish that are indistinguishable to anglers. Ecotypes are groups of individuals with a population that have different life-history strategies. Consequently, ecotypes must share key fishery (`pi`, `Llo`, `Lup`, `Nc`, `rho`, `Hm` and `q`) and stock recruitment (`BH`, `RK`, `tR` and `Rmax`) parameters.y To use a yield-per-recruit approach it is also necessary to assume that the relative proportion of recruits (`RPR`) adopting each life-history strategy is independent of the size and composition of the parental stock. ## Two Ecotypes Consider a population with a smaller ecotype and a second larger ecotype that delays maturation in order to achieve sufficient size to switch to piscivory which allows it to grow much larger. ```{r} library(ypr) library(ggplot2) # for plotting ecotypes <- ypr_ecotypes( Linf2 = 200, L2 = c(100, 50), Ls = c(50, 75), pi = 0.05, names = c("small", "large"), RPR = c(0.8, 0.2)) ypr_plot_schedule(ecotypes) + scale_color_manual(values = c("black", "blue")) ypr_plot_schedule(ecotypes, x = "Age", y = "Spawning") + scale_color_manual(values = c("black", "blue")) ``` ### Fish ```{r, fig.width=6, fig.height=4} ypr_plot_fish(ecotypes, color = "white") + scale_fill_manual(values = c("black", "blue")) ypr_plot_fish(ecotypes, x = "Length", y = "Caught", color = "white", binwidth = 15) + scale_fill_manual(values = c("black", "blue")) ``` ### Stock-Recruitment ```{r, fig.width=6, fig.height=4} ypr_plot_sr(ecotypes, biomass = TRUE) ypr_tabulate_sr(ecotypes, biomass = TRUE) ``` ### Yield ```{r, fig.width=6, fig.height=4} ypr_tabulate_yield(ecotypes, biomass = TRUE) ypr_plot_yield(ecotypes, biomass = TRUE) ```
/scratch/gouwar.j/cran-all/cranData/ypr/vignettes/ecotypes.Rmd
--- title: "Get Started with ypr" author: "Joe Thorley" date: "`r Sys.Date()`" bibliography: bibliography.bib output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Get Started with ypr} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 4 ) ``` ## Introduction > Fish are born, they grow, they reproduce and they die – whether from natural causes or from fishing. That’s it. Modelers just use complicated (or not so complicated) math to iron out the details. @cooper_guide_2006 Equilibrium based yield per recruit (YPR) methods [@walters_fisheries_2004] estimate the capture rate that optimizes the yield under the assumption that there is no stochasticity and all density-dependence is captured by the stock-recruitment relationship. The remaining population processes of growth, reproduction and death are captured through a series of relatively straight-forward deterministic equations. ```{r, echo=FALSE} library(ypr) nparameters <- length(ypr_population()) caption <- paste("Table 1. The", nparameters, "parameters with their default values and descriptions.") table <- ypr_tabulate_parameters(ypr_population()) table$Description <- sub("\n", " ", table$Description) knitr::kable(table, caption = caption) ``` ## Growth ### Length In `ypr` length (in cm) at age ($t$) is assumed to follow a Von Bertalanffy growth curve $$L = L_{\infty} \cdot (1 - \exp(-k \cdot (t-t_0)))$$ ```{r} population <- ypr_population() ypr_plot_schedule(population, "Age", "Length") ``` which can be biphasic ```{r} ypr_plot_schedule(ypr_population_update(population, L2 = 75, Linf2 = 200), "Age", "Length") ``` ### Weight The weight ($W$) at a given length is assumed to follow the classic allometric relationship $$W = w_\alpha \cdot L^{w_\beta}$$ ```{r} population <- ypr_population_update(population, Wa = 0.01, Wb = 3) ypr_plot_schedule(population, "Length", "Weight") ``` Its worth noting that $w_\alpha$, which is the extrapolated weight (g) of a 1 cm individual, is a scaling constant that only affects the estimate of the yield (when calculated in terms of the biomass), ie, it does not affect the estimate of the optimal capture rate. ## Reproduction ### Fecundity The fecundity ($F$) is assumed to scale allometrically with the weight according to the equation $$F = f_\alpha \cdot W^{f_\beta}$$ ```{r} population <- ypr_population_update(population, fa = 1, fb = 1) ypr_plot_schedule(population, "Weight", "Fecundity") ``` $f_\alpha$, which is the extrapolated eggs produced by a 1 g female, is a scaling constant with no effect on the yield or optimal capture rate. ### Spawning The probability of spawning at length $L$ is determined by the equation $$S = \frac{L^{S_p}}{L_s^{S_p} + L^{S_p}} \cdot es$$ ```{r} population <- ypr_population_update(population, Ls = 50, Sp = 10, es = 0.8) ypr_plot_schedule(population, "Length", "Spawning") ``` ## Death ### Natural Mortality By default the natural annual interval mortality rate ($n$) is assumed to be constant ```{r} ypr_plot_schedule(population, "Length", "NaturalMortality") ``` although like growth it can vary biphasically ```{r} ypr_plot_schedule(ypr_population_update(population, nL = 0.15, Ln = 60), "Length", "NaturalMortality") ``` The natural mortality rate can also be affected by spawning mortality ```{r} population <- ypr_population_update(population, Sm = 0.5) ypr_plot_schedule(population, "Length", "NaturalMortality") ``` ### Fishing Mortality The vulnerability to capture ($V$) is assumed to vary by length as follows $$V = \frac{L^{V_p}}{L_v^{V_p} + L^{V_p}}$$ ```{r} population <- ypr_population_update(population, Lv = 50, Vp = 50) ypr_plot_schedule(population, "Length", "Vulnerability") ``` If $V_p$ is 100 then vulnerability is effectively knife-edged. The probabilty of being retained if captured ($R$) depends on the release rate ($\rho$), the slot limits ($L_{lo}$ and $L_{up}$) and the non-compliance with the limits ($N_c$) ```{r} population <- ypr_population_update(population, rho = 0.5, Llo = 40, Lup = 70, Nc = 0.1) ypr_plot_schedule(population, "Length", "Retention") ``` The fishing mortality ($U$) depends on $V$, $R$ and the probability of capture when fully vulnerable ($pi$) as well as the hooking mortality ($H_m$) $$U = V \cdot \pi \cdot R + V \cdot \pi \cdot (1 - R) \cdot H_m$$ The calculation assumes that a released fish cannot be recaught in the same year. ```{r} population <- ypr_population_update(population, pi = 0.3, Hm = 0.2) ypr_plot_schedule(population, "Length", "FishingMortality") ``` ## Recruitment With growth, reproduction and death defined, the final task is to estimate the recruitment (birth) rate. This requires the lifetime number of spawners per spawner at low density ($R_k$) and the recruitment age ($R_t$; by default 1) to be defined. If recruitment follows a Beverton-Holt ($BH = 1$) curve then $$R = \frac{\alpha \cdot E}{(\beta \cdot E + 1)}$$ ```{r} population <- ypr_population_update(population, Rk = 3) ypr_plot_sr(population, plot_values = FALSE) ``` where $E$ is the annual eggs (stock) and $R$ is the annual recruits at age $R_t$. With a Ricker curve ($BH = 0$) the relationship is as follows $$R = \alpha \cdot E \cdot \exp (-\beta \cdot E)$$ ```{r} population <- ypr_population_update(population, BH = 0L) ypr_plot_sr(population, plot_values = FALSE) ``` The number of recruits at the carrying capacity ($R_\text{max}$) is a scaling constant that only affects the estimate of the yield. Before calculating the recruitment it is important to introduce the concept of the (unfished) survivorship ($lx_a$) which is the probability of a recruit surviving to age $a$ in the absence of fish mortality. ```{r} ypr_plot_schedule(population, "Age", "Survivorship") ``` The unfished survivorship ($lx_a$) is defined recursively by $$lx_{R_t} = 1, lx_a = lx_{a-1} \cdot (1-N_{a-1}) \;\text{for}\; a > R_t$$ where $N_a$ is the annual interval natural mortality at age $a$. And the fished survivorship ($lx_a^F$) is $$lx_{R_t}^F = 1, lx_a^F = lx_{a-1}^F \cdot (1 - (1 - N_{a-1}) \cdot (1 - U_{a-1})) \;\text{for}\; a > R_t$$ The lifetime number of eggs deposited per (unfished) recruit ($\phi$) is then just $$\phi = \sum_{a = R_t}^{t_\text{max}} lx_a \cdot F_a/2 \cdot S_a$$ where $t_\text{max}$ is the maximum age considered (by default `r ypr_population()$tmax`) and $F_a$ the fecundity at age $a$ is divided by two as the sex ratio is assumed to 1:1 and $S_a$ is the probability of spawning. The fished equivalent is denoted $\phi_F$. It important to realize that at the unfished equilibrium the annual number of recruits ($R_0$) is related to the annual egg deposition according to the following equation $$E_0 = \phi \cdot R_0$$ By definition $$\alpha = \frac{R_k \cdot R_0}{E_0} = \frac{R_k}{\phi}$$ The $\beta$ term of the Beverton-Holt curve can then be found by rearranging the following formula $$R_0 = \frac{\alpha \cdot \phi \cdot R_0}{\beta \cdot \phi \cdot R_0 + 1}$$ $$\beta \cdot \phi \cdot R_0 + 1 = \alpha \cdot \phi$$ $$\beta = \frac{\alpha \cdot \phi - 1}{\phi \cdot R_0}$$ The equivalent equation for the Ricker curve is arrived at as follows $$R_0 = \alpha \cdot \phi \cdot R_0 \cdot \exp (-\beta \cdot \phi \cdot R_0)$$ $$\frac{1}{\exp (-\beta \cdot \phi \cdot R_0)} = \alpha \cdot \phi$$ $$\beta \cdot \phi \cdot R_0 = \log(\alpha \cdot \phi)$$ $$\beta = \frac{\log(\alpha \cdot \phi)}{\phi \cdot R_0}$$ The number of recruits at the fished equilibrium ($R_{0F}$) can then be found for the Beverton-Holt curve as follows $$R_{0F} = \frac{\alpha \cdot \phi_F \cdot R_{0F}}{\beta \cdot \phi_F \cdot R_{0F} + 1}$$ $$\beta \cdot \phi_F \cdot R_{0F} + 1 = \alpha \cdot \phi_F$$ $$R_{0F} = \frac{\alpha \cdot \phi_F - 1}{\beta \cdot \phi_F}$$ and for the Ricker $$R_{0F} = \alpha \cdot \phi_F \cdot R_{0F} \cdot \exp (-\beta \cdot \phi_F \cdot R_{0F})$$ $$\frac{1}{\exp(-\beta \cdot \phi_F \cdot R_{0F})} = \alpha \cdot \phi_F$$ $$\beta \cdot \phi_F \cdot R_{0F} = \log(\alpha \cdot \phi_F)$$ $$R_{0F} = \frac{\log(\alpha \cdot \phi_F)}{\beta \cdot \phi_F}$$ Finally the estimates are rescaled so that the carrying capacity is identical to $R_\text{max}$ through the following transformations $$ \beta = \beta \cdot \kappa / R_\text{max} $$ $$ R_0 = R_0 / \kappa \cdot R_\text{max} $$ $$ R_{0F} = R_{0F} / \kappa \cdot R_\text{max} $$ where $\kappa$, which is the carrying capacity in the original scale, is $\alpha/\beta$ for the Beverton-Holt and $\alpha/(\beta \cdot e)$ for the Ricker curve. ## Yield When the yield is simply the number of fish caught (irrespective of the weight or whether or not its harvested) then it is given by $$Y = \sum_{a = R_t}^{t_\text{max}} R_{0F} \cdot lx_a^F \cdot \pi \cdot V_a$$ if only harvested fish are considered it becomes $$Y = \sum_{a = R_t}^{t_\text{max}} R_{0F} \cdot lx_a^F \cdot \pi \cdot V_a \cdot R$$ and if the total weight (in kg) is important then its $$Y = \sum_{a = R_t}^{t_\text{max}} R_{0F} \cdot lx_a^F \cdot \pi \cdot V_a \cdot R \cdot W_a/1000$$ and if only trophy fish are to be considered then its $$Y = \sum_{a = R_t}^{t_\text{max}} \text{if}(La < L_y)\ 0\ \text{else}\ R_{0F} \cdot lx_a^F \cdot \pi \cdot V_a \cdot R \cdot W_a/1000$$ where $L_y$ is the minimum length of a trophy fish. ```{r} ypr_plot_yield(population, harvest = TRUE, biomass = TRUE, Ly = 60) ypr_tabulate_yield(population, harvest = TRUE, biomass = TRUE, Ly = 60) ``` ## Efficiency The catchability `q` indicates the probability of capture for a unit of effort ($E$). It is assumed to be related to $\pi$ according to the relationship $$\pi = 1 - \exp(\log(1-q)\cdot E)$$ which can be rearranged to give $$E = \frac{\log(1-\pi)}{\log(1-q)}.$$ ```{r} ypr_plot_yield(population, y = "Effort", harvest = TRUE, biomass = TRUE, Ly = 60) ``` ```{r} ypr_plot_yield(population, y = "YPUE", harvest = TRUE, biomass = TRUE, Ly = 60) ``` ## References
/scratch/gouwar.j/cran-all/cranData/ypr/vignettes/ypr.Rmd
#################################################################################################################################### ################################## Err ############################################################################################# # >> Err = new.env() #################################################################################################################################### Err$msg = "" Err$prefix = "ypssc" Err$tab = " " Err$msgDash = " - " Err$fullprefix = "" Err$funcType = "" Err$msgType = "" Err$msgColon = " : " Err$lenOfLine = 50 Err$boxLen = 60 Err$checkAndWriteMsg = function() { # checkAndWriteMsg >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Err$checkMsg() Err$writeMsg() } Err$checkMsg = function() { # checkMsg >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> if( is.character(Err$msg) ) { Err$msgType = "character" } else if( is.double(Err$msg) | is.integer(Err$msg) ) { Err$msgType = "double" } else { stop( paste("Please provide either character/string or double/integer message for ", Err$funcType, sep = ""), call. = FALSE) } } Err$writeMsg = function() { # writeMsg >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Err$msg = gsub("\n", " \n ", Err$msg) if( Err$prefix == "" ) { Err$fullprefix = paste( Err$tab, Err$funcType, Err$msgColon, sep = "" ) } else { Err$fullprefix = paste( Err$tab, Err$prefix, Err$msgDash, Err$funcType, Err$msgColon, sep = "" ) } if( Err$msgType == "character" ) { lines = Err$getListOfLines(Err$msg) for( i in 1:length(lines) ) { msg = paste(Err$fullprefix, lines[i], sep = "") writeLines(msg) } } else { if( Err$msg < 0 ) { stop( paste("Please provide non-negetive integer.", funcType, sep = ""), call. = FALSE) } else if( Err$msg == 0 ) { writeLines("") } else { for( i in 1:Err$msg ) { writeLines(Err$fullprefix) } } } } Err$getListOfLines = function(text) { # writeMsg >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> words = unlist( strsplit(text, " ") ) lines = c() l = 0; w = 0 while( w < length(words) ) { l = l + 1 w = w + 1 if( words[w] == "\n" ) { lines[l] = ""; next} else{ lines[l] = words[w]} while( nchar(lines[l]) <= Err$lenOfLine & w < length(words) ) { w = w + 1 if( words[w] == "\n" ) { break } else{ lines[l] = paste( lines[l], words[w], sep = " " ) } } } return(lines) } #################################################################################################################################### Err$help = function() { # note >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> prefixCurrent = Err$prefix Err$prefix = "Err" tab = Err$tab Err$box( paste("Usage:", "\n", "\n", tab, "Set Prefix (optional):", "\n", "\n", tab, tab, "Err$prefix = 'Shashank'", "\n", "\n", tab, "Methods for displaying Notes, Warnings, Fatal error", "\n", tab, tab, "Err$note('your text')", "\n", tab, tab, "Err$warn('your text')", "\n", tab, tab, "Err$abort('your text')", "\n", sep = "") ) Err$prefix = prefixCurrent } Err$note = function(msg) { # note >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Err$msg = msg; Err$funcType = "NOTE"; Err$checkAndWriteMsg() msg = 15 } Err$warn = function(msg) { # warn >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Err$msg = msg; Err$funcType = "WARNING"; Err$checkAndWriteMsg() } Err$abort = function(msg) { # abort >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Err$note(0) Err$msg = msg; Err$funcType = "FATAL"; Err$checkAndWriteMsg() Err$note(0) Err$msg = "Aborting..."; Err$funcType = "FATAL"; Err$checkAndWriteMsg() Err$note(0) Err$note(0) exit() } Err$box = function(msg) { # box >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Err$note(0) Err$note( paste0( rep(">", Err$boxLen), collapse = '' ) ) Err$note(1) Err$note( msg ) Err$note(1) Err$note( paste0( rep("<", Err$boxLen), collapse = '' ) ) Err$note(0) } Err$reset = function() { # reset >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Err$prefix = "ypssc" } #################################################################################################################################### ################################## Err ############################################################################################# #################################################################################################################################### #################################################################################################################################### ################################## Help Code ####################################################################################### # >> # Err$note( "dummy text dummy text dummy text dummy text dummy text dummy text dummy text dummy text dummy text dummy text dummy text dummy text dummy text dummy text " ) # Err$note( "dummy text dummy text \n dummy text dummy text \ndummy text\n dummy text dummy text dummy text\ndummy text dummy text dummy text dummy text dummy text \n dummy text " ) # Err$note( 0 ) # Err$note( 1 ) # Err$note( 2 ) # << ################################## Help Code ####################################################################################### ####################################################################################################################################
/scratch/gouwar.j/cran-all/cranData/ypssc/R/Err.R
#################################################################################################################################### ##################################### auxil functions ############################################################################## #################################################################################################################################### filter <- dplyr::filter #################################################################################################################################### ##################################### checkFileInput() ############################################################################# # >> checkFileInput <- function( pathFileInput = NULL ){ # Checking if `pathFileInput` is provided or the file exists >> if ( is.null(pathFileInput) ) { isFile = FALSE } else { isFile = file.exists( pathFileInput ) | startsWith( pathFileInput, "https") } # Selecting an input file from a doalog box if `pathFileInput` is not provided or if `pathFileInput` does not exists >> if ( !isFile ) { msg = paste0( "Argument `pathFileInput` is not provided.\n", " or \n", "The file does not exists.\n", "\n", "Input csv file generated from MaxQuant is necessary to run this function.\n", "\n", "Do you want to select an input csv file generated from MaxQuant?" ) Err$warn( 0 ) Err$warn( msg ) response = dlgMessage( msg, type = "yesno" )$res if ( response == "yes" ) { msgSelectFile = "Please select an input csv file generated from MaxQuant." Err$note( 0 ) Err$note( paste0( "A dialog box must have been opened.\n", msgSelectFile ) ) pathFileInput = dlg_open( title = msgSelectFile )$res } else { updateUserFailure( "Argument `pathFileInput` is not provided." ) } } # Printing `pathFileInput` provided >> Err$note( 0 ) Err$note( paste0( "Provided input csv file generated from MaxQuant:\n", "'", pathFileInput, "'" ) ) return( pathFileInput ) } # << ##################################### checkFileInput() ############################################################################# #################################################################################################################################### #################################################################################################################################### ##################################### checkDirOutput() ############################################################################# # >> checkDirOutput <- function( pathDirOutput = NULL ){ # Checking if `pathDirOutput` is provided or the dir exists >> if ( is.null(pathDirOutput) ) { isDir = FALSE } else { isDir = dir.exists( pathDirOutput ) } # Selecting an output dir from a doalog box if `pathDirOutput` is not provided or if `pathDirOutput` does not exists >> if ( !isDir ) { msg = paste0( "Argument `pathDirOutput` is not provided.\n", " or \n", "The directory does not exists.\n", "\n", "Do you want to select an output directory? \n", "'Yes': Then select. \n", "'No' : Then the current working directory will be selected." ) Err$warn( 0 ) Err$warn( msg ) response = dlgMessage( msg, type = "yesno" )$res if ( response == "yes" ) { msgSelectDir = "Please select an output directory." Err$note( 0 ) Err$note( paste0( "A dialog box must have been opened. \n", msgSelectDir ) ) pathDirOutput = dlg_dir( title = msgSelectDir )$res } else { pathDirOutput = getwd() } } # Printing `pathDirOutput` provided >> Err$note( 0 ) Err$note( paste0( "Provided output directory where the output files will be saved:\n", "'", pathDirOutput, "'" ) ) return( pathDirOutput ) } # << ##################################### checkDirOutput() ############################################################################# #################################################################################################################################### #################################################################################################################################### ##################################### readFileInput() ############################################################################## # >> readFileInput <- function( pathFileInput, isTest ) { Err$note(0) Err$note( paste0( "Reading input file...." ) ) # Reading csv file >> df = read.csv( pathFileInput ) # Removing the columns that are not needed and finding the columns containing sample information >> df = df[ , -which( names(df) %in% c( "Sequence","N.term.cleavage.window", "C.term.cleavage.window","Amino.acid.before", "First.amino.acid","Second.amino.acid", "Second.last.amino.acid","Last.amino.acid", "Amino.acid.after","A.Count","R.Count","N.Count", "D.Count","C.Count","Q.Count","E.Count", "G.Count","H.Count","I.Count","L.Count", "K.Count","M.Count","F.Count","P.Count", "S.Count","T.Count","W.Count","Y.Count", "V.Count","U.Count","O.Count","Length", "Missed.cleavages","Mass", "Leading.razor.protein","Gene.names", "Protein.names","Unique..Groups.", "Unique..Proteins.","Charges","PEP", "Score","Experiment.ST168.THF.A", "Experiment.ST168.THF.O", "Experiment.ST169.DMSO.A","Experiment.ST169.DMSO.O", "Experiment.ST170.But.A","Experiment.ST170.But.O", "Intensity.ST168.THF.A", "Intensity.ST168.THF.O", "Intensity.ST169.DMSO.A", "Intensity.ST169.DMSO.O", "Intensity.ST170.But.A", "id","Protein.group.IDs","Mod..peptide.IDs", "Evidence.IDs","MS.MS.IDs","Best.MS.MS", "Oxidation..M..site.IDs","Taxonomy.IDs", "MS.MS.Count" ) ) ] names = names(df) sampleNames = names[ grepl("Intensity.", names) ] sampleNamesUpdate = gsub( '\\.|Intensity.', ' ', sampleNames ) names_list = vector() i = 1 pb = winProgressBar( title = "progress bar", min = 0, max = length(sampleNames), width = 300 ) for ( i in 1 : length(sampleNames) ) { # temp = paste(sampleNamesUpdate[i],' \n \n ') temp = sampleNamesUpdate[i] names_list = c( names_list, temp ) Sys.sleep(0.1) setWinProgressBar( pb, i, title = paste( sampleNamesUpdate[i], ' ', round(i/length(sampleNames)*100, 0), "% done") ) } close(pb) # Conformation about sample names from user >> if ( !isTest ) { sampleNameConfirmation = dlgMessage( c( "Identified sample names in the uploaded file:", "\n", names_list, "\n", "If it is correct, please enter 'Yes'" ), type = "yesno" )$res } else { sampleNameConfirmation = "yes" } if ( sampleNameConfirmation != "yes" ) { msg = paste0( "Wrong sample names.\n", "\n", "Please re-run the program using correct input file." ) updateUserFailure( msg ) } # Returning multiple variables as a R-list >> dataFileInput = list() dataFileInput$df = df dataFileInput$sampleNames = sampleNames dataFileInput$sampleNamesUpdate = sampleNamesUpdate Err$note( "Done." ) return( dataFileInput ) } # << ##################################### readFileInput() ############################################################################## #################################################################################################################################### #################################################################################################################################### ##################################### creatOutputDir() ############################################################################# # >> creatOutputDir <- function( pathDirOutput, type = "secondary" ) { Err$note(0) Err$note( paste0( "Creating output directory" ) ) dateTimeCurrent = format( Sys.time(), "%Y%m%d_%H%M%S" ) # << get current date and time nameDirOutput = paste0( "ypssc_", dateTimeCurrent, "_", type ) # << name of the output folder pathDirOutput = paste0( pathDirOutput, "/", nameDirOutput ) # << path of the output folder dir.create( pathDirOutput ) # creating new folder for output files setwd( pathDirOutput ) # << setting working dir to "pathDirOutput" to write output files Err$note( "Done." ) Err$note( paste0( "Output directory created:\n", "'", getwd(), "'" ) ) return( dateTimeCurrent ) } ##################################### creatOutputDir() ############################################################################# #################################################################################################################################### #################################################################################################################################### ##################################### removeRows() ################################################################################# # >> removeRows <- function( df, dateTimeCurrent, isTest ) { Err$note(0) Err$note( paste0( "Filtering input file:" ) ) if ( !isTest ) { # Removing rows containing doubious proteins >> removeDoubious = dlgMessage( paste0( "Do you want to remove the rows containing doubious proteins?\n", "Rows that have 2 or more protiens assigned to one identified peptide are called doubious\n", "Answer with yes or no" ), type = "yesno" )$res if ( removeDoubious == "yes" ) { Err$note( "Removing rows containing doubious proteins..." ) df = filter( df, !grepl( ';', df$Proteins ) ) } # Removing rows that contains peptides that matched to decoy that has reverse >> removeReverse = dlgMessage( paste0( "Do you want to remove rows that contains peptides that matched to decoy that has reverse ", "sequnce of real protein?\n", "Theses proteins are usually removed.\n", "Answer with yes or no" ), type = "yesno" )$res if ( removeReverse == "yes" ) { Err$note( "Removing rows that contains peptides that matched to decoy that has reverse..." ) df = filter( df, !grepl( '\\+', df$Reverse ) ) } # Removing rows that contains peptides that are showing signs of contamination >> removeContaminant = dlgMessage( paste0( "Do you want to remove rows that contains peptides that are showing signs of contamination?\n", "Theses proteins are usually removed.\n", "Answer with yes or no" ), type = "yesno" )$res if ( removeContaminant == "yes" ) { Err$note( "Removing rows that contains peptides that are showing signs of contamination..." ) df = filter( df, !grepl( '\\+', df$Potential.contaminant ) ) } # Removing rows that contains peptides that are not showing any intensity >> removeNoIntensity = dlgMessage( paste( "Do you want to remove rows that contains peptides that are not showing any intensity?\n", "Theses proteins are usually removed.\n", "Answer with yes or no" ), type = "yesno" )$res if ( removeNoIntensity == "yes" ) { Err$note( "Removing rows that contains peptides that are not showing any intensity..." ) df = filter( df, df$Intensity > 0 ) } } else { df = filter( df, !grepl( ';', df$Proteins ) ) df = filter( df, !grepl( '\\+', df$Reverse ) ) df = filter( df, !grepl( '\\+', df$Potential.contaminant ) ) df = filter( df, df$Intensity > 0 ) } # Print Done >> Err$note( "Done." ) # Writing new df to output file in output dir >> Err$note(0) Err$note( "Writing filtered file to output file in output dir..." ) nameFile = paste0( dateTimeCurrent, "_", 'df.csv' ) write.csv( df, nameFile, row.names = FALSE ) Err$note( "Done." ) # Err$note( paste0( "Output file created:\n", # "'", getwd(), "/", nameFile, "'" ) ) updateUserFileCreated( nameFile ) return( df ) } ##################################### removeRows() ################################################################################# #################################################################################################################################### #################################################################################################################################### ################################## updateUserFailure ############################################################################### # >> updateUserFailure <- function( msg, isTest = FALSE ) { msg = paste0( msg, "\n", "\n", "Analysis failed!" ) if ( !isTest ) { tkmessageBox( title = "Error", message = msg, icon = "error", type = "ok" ) } Err$abort( msg ) } # << ################################## updateUserFailure ############################################################################### #################################################################################################################################### #################################################################################################################################### ################################## updateUserSuccess ############################################################################### # >> updateUserSuccess <- function( isTest = FALSE ) { msg = paste0( "Analysis completed successfully! \n", "\n", "Please see output files at: \n", "'", getwd(), "'" ) if ( !isTest ) { tkmessageBox( title = "Success", message = msg, icon = "info", type = "ok" ) } Err$note(0) Err$box(msg) Err$note(0) } # << ################################## updateUserSuccess ############################################################################### #################################################################################################################################### #################################################################################################################################### ################################## updateUserFileCreated ########################################################################### # >> updateUserFileCreated <- function( nameFile ) { Err$note( paste0( "Output file created:\n", "'", getwd(), "/", nameFile, "'" ) ) } # << ################################## updateUserFileCreated ########################################################################### #################################################################################################################################### #################################################################################################################################### ##################################### auxil functions ############################################################################## ####################################################################################################################################
/scratch/gouwar.j/cran-all/cranData/ypssc/R/auxil.R
#################################################################################################################################### #################################################################################################################################### # >> #' @title calculationAlphaHelix #' @param df Dataframe for input file data. #' @param sampleNames Names of the samples found in the input file. #' @param sampleNamesUpdate Updated names of the samples found in the input file. #' @param dateTimeCurrent Date and time at the time the simulation began. #' @noRd # << #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### ##################################### calculationAlphaHelix() ###################################################################### # >> calculationAlphaHelix <- function( df, sampleNames, sampleNamesUpdate, dateTimeCurrent ) { # Performing Alpha-helix calculation for database #### Err$prefix = "Alpha" Err$note(0) Err$note( "Performing Alpha-helix calculation for database..." ) dataBase_alpha = select( dataBase_alpha, c(1,2) ) num_Pro_aaa = unique( dataBase_alpha$id ) protein = vector() num_aaa_pro_DB = vector() pb_1 = winProgressBar( title = "progress bar", min = 0, max = length(num_Pro_aaa), width = 300 ) i = 1 for( i in 1 : length(num_Pro_aaa) ) { item = num_Pro_aaa[i] proteins = filter( dataBase_alpha, id == item ) num_aaa_pro_DB_temp = length(proteins$id) num_aaa_pro_DB = c( num_aaa_pro_DB_temp, num_aaa_pro_DB ) protein = c( unique(proteins$id), protein ) proteins = vector() num_aaa_pro_DB_temp = vector() setWinProgressBar( pb_1, i, title = paste( 'Alpha-helix calculation for database ', round( i/length(num_Pro_aaa)*100, 0 ), "% done") ) } Err$note("Done." ) close(pb_1) # Calculating the number of amino acids for alpha #### aaa = data.frame( id = protein, num_aaa = num_aaa_pro_DB ) cal_for_database = left_join( dataBase_numOfAA, aaa, by = 'id' ) Sys.sleep(0.5) # Samples #### i = 1 for( i in 1 : length(sampleNames) ) { Err$note( 0 ) Err$note( paste0("Working on sample: ", sampleNamesUpdate[i] ) ) Err$note( 1 ) # Peptides in the sample >> Err$note( "Geting list of peptides..." ) temp = which( names(df) == sampleNames[i] ) sample_peptides = filter( df, df[,temp] > 0 ) Err$note("Done." ) nameFile = gsub( " ", "_", paste0( dateTimeCurrent, " ", 'list of peptides in', sampleNamesUpdate[i], '.csv' ), fixed = FALSE ) write.csv( sample_peptides, nameFile, row.names = FALSE ) updateUserFileCreated( nameFile ) Err$note( 1 ) sample = paste( as.character(sampleNamesUpdate[i]), '_ peptides' ) assign( sample, sample_peptides ) # Proteins in the sample >> Err$note( "Geting list of proteins..." ) sample_proteins = unique(sample_peptides$Proteins) Err$note("Done." ) nameFile = gsub( " ", "_", paste0( dateTimeCurrent, " ", 'list of proteins in', sampleNamesUpdate[i], '.csv' ), fixed = FALSE ) write.csv( sample_proteins, nameFile, row.names = FALSE ) updateUserFileCreated( nameFile ) Err$note( 1 ) sample = paste( as.character(sampleNamesUpdate[i]), '_ proteins' ) assign( sample, sample_proteins ) # Calculating alpha-helix coverage for samples >> Err$note( "Calculating alpha-helix coverage for samples..." ) proteins_in_s = vector() aa_in_s = vector() aaa_in_s = vector() pb_2 = winProgressBar( title = "progress bar", min = 0, max = length(sample_proteins), width = 300 ) j = 1 for( j in 1 : length(sample_proteins) ) { item = sample_proteins[j] Pro_chunk = filter( sample_peptides, sample_peptides$Proteins == item ) k = 1 list_aa_s = vector() for( k in 1 : length(Pro_chunk$Proteins) ) { start = Pro_chunk$Start.position[k] end = Pro_chunk$End.position[k] list_aa_s_temp = seq(start:end) list_aa_s_temp = list_aa_s_temp+start-1 list_aa_s = c( list_aa_s_temp, list_aa_s ) list_aa_s_temp = vector() } proteins_temp = item proteins_in_s = c( proteins_temp, proteins_in_s ) proteins_temp = vector() aa_in_s_temp = length( unique(list_aa_s) ) aa_in_s = c( aa_in_s_temp, aa_in_s ) aa_in_s_temp = vector() protein_chunk_dataBase = filter( dataBase_alpha, id == item ) aaa_in_s_temp = unique(list_aa_s)%in%protein_chunk_dataBase$n aaa_in_s_temp = sum(aaa_in_s_temp) aaa_in_s = c( aaa_in_s_temp, aaa_in_s ) aaa_in_s_temp = vector() results = data.frame( id = proteins_in_s, num_amino_acids_in_sample = aa_in_s, num_alpha_amino_acids_in_sample = aaa_in_s ) results = left_join( results, cal_for_database, by = 'id' ) setWinProgressBar( pb_2, j, title = paste( 'Alpha-helix calculation for ', sampleNames[i], ' ', round( j/length(sample_proteins)*100, 0 ), "% done") ) } Err$note( "Done" ) nameFile = gsub( " ", "_", paste0( dateTimeCurrent, " ", 'alpha helix analysis of', sampleNamesUpdate[i], '.csv' ), fixed = FALSE ) write.csv( results, nameFile, row.names = FALSE ) updateUserFileCreated( nameFile ) close(pb_2) } Err$reset() return( invisible(NULL) ) } # << ##################################### calculationAlphaHelix() ###################################################################### ####################################################################################################################################
/scratch/gouwar.j/cran-all/cranData/ypssc/R/calculationAlphaHelix.R
#################################################################################################################################### #################################################################################################################################### # >> #' @title calculationBetaSheet #' @param df Dataframe for input file data. #' @param sampleNames Names of the samples found in the input file. #' @param sampleNamesUpdate Updated names of the samples found in the input file. #' @param dateTimeCurrent Date and time at the time the simulation began. #' @noRd # << #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### ##################################### calculationBetaSheet() ####################################################################### # >> calculationBetaSheet <- function( df, sampleNames, sampleNamesUpdate, dateTimeCurrent ) { # Performing Beta-sheet calculation for database #### Err$prefix = "Beta" Err$note(0) Err$note( "Performing Beta-sheet calculation for database..." ) dataBase_beta = select( dataBase_beta, c(1,2) ) num_Pro_baa = unique( dataBase_beta$id ) protein = vector() num_baa_pro_DB = vector() pb_1 = winProgressBar( title = "progress bar", min = 0, max = length(num_Pro_baa), width = 300 ) i = 1 for( i in 1 : length(num_Pro_baa) ) { item = num_Pro_baa[i] proteins = filter( dataBase_beta, id == item ) num_baa_pro_DB_temp = length(proteins$id) num_baa_pro_DB = c( num_baa_pro_DB_temp, num_baa_pro_DB ) protein = c( unique(proteins$id), protein ) proteins = vector() num_baa_pro_DB_temp = vector() setWinProgressBar( pb_1, i, title = paste( 'Beta-sheet calculation for database ', round( i/length(num_Pro_baa)*100, 0 ), "% done") ) } Err$note("Done." ) close(pb_1) # Calculating the number of amino acids for beta #### baa = data.frame( id = protein, num_baa = num_baa_pro_DB ) cal_for_database = left_join( dataBase_numOfAA, baa, by = 'id' ) Sys.sleep(0.5) # Samples #### i = 1 for( i in 1 : length(sampleNames) ) { Err$note( 0 ) Err$note( paste0("Working on sample: ", sampleNamesUpdate[i] ) ) Err$note( 1 ) # Peptides in the sample >> Err$note( "Geting list of peptides..." ) temp = which( names(df) == sampleNames[i] ) sample_peptides = filter( df, df[,temp] > 0 ) Err$note("Done." ) nameFile = gsub( " ", "_", paste0( dateTimeCurrent, " ", 'list of peptides in', sampleNamesUpdate[i], '.csv' ), fixed = FALSE ) write.csv( sample_peptides, nameFile, row.names = FALSE ) updateUserFileCreated( nameFile ) Err$note( 1 ) sample = paste( as.character(sampleNamesUpdate[i]), '_ peptides' ) assign( sample, sample_peptides ) # Proteins in the sample >> Err$note( "Geting list of proteins..." ) sample_proteins = unique(sample_peptides$Proteins) Err$note("Done." ) nameFile = gsub( " ", "_", paste0( dateTimeCurrent, " ", 'list of proteins in', sampleNamesUpdate[i], '.csv' ), fixed = FALSE ) write.csv( sample_proteins, nameFile, row.names = FALSE ) updateUserFileCreated( nameFile ) Err$note( 1 ) sample = paste( as.character(sampleNamesUpdate[i]), '_ proteins' ) assign( sample, sample_proteins ) # Calculating beta-sheet coverage for samples >> Err$note( "Calculating beta-sheet coverage for samples..." ) proteins_in_s = vector() aa_in_s = vector() baa_in_s = vector() pb_2 = winProgressBar( title = "progress bar", min = 0, max = length(sample_proteins), width = 300 ) j = 1 for( j in 1 : length(sample_proteins) ) { item = sample_proteins[j] Pro_chunk = filter( sample_peptides, sample_peptides$Proteins == item ) k = 1 list_aa_s = vector() for( k in 1 : length(Pro_chunk$Proteins) ) { start = Pro_chunk$Start.position[k] end = Pro_chunk$End.position[k] list_aa_s_temp = seq(start:end) list_aa_s_temp = list_aa_s_temp+start-1 list_aa_s = c( list_aa_s_temp, list_aa_s ) list_aa_s_temp = vector() } proteins_temp = item proteins_in_s = c( proteins_temp, proteins_in_s ) proteins_temp = vector() aa_in_s_temp = length( unique(list_aa_s) ) aa_in_s = c( aa_in_s_temp, aa_in_s ) aa_in_s_temp = vector() protein_chunk_dataBase = filter( dataBase_beta, id == item ) baa_in_s_temp = unique(list_aa_s)%in%protein_chunk_dataBase$n baa_in_s_temp = sum(baa_in_s_temp) baa_in_s = c( baa_in_s_temp, baa_in_s ) baa_in_s_temp = vector() results = data.frame( id = proteins_in_s, num_amino_acids_in_sample = aa_in_s, num_beta_amino_acids_in_sample = baa_in_s ) results = left_join( results, cal_for_database, by = 'id' ) setWinProgressBar( pb_2, j, title = paste( 'Beta-sheet calculation for ', sampleNames[i], ' ', round( j/length(sample_proteins)*100, 0 ), "% done") ) } Err$note( "Done" ) nameFile = gsub( " ", "_", paste0( dateTimeCurrent, " ", 'beta sheet analysis of', sampleNamesUpdate[i], '.csv' ), fixed = FALSE ) write.csv( results, nameFile, row.names = FALSE ) updateUserFileCreated( nameFile ) close(pb_2) } Err$reset() return( invisible(NULL) ) } # << ##################################### calculationBetaSheet() ####################################################################### ####################################################################################################################################
/scratch/gouwar.j/cran-all/cranData/ypssc/R/calculationBetaSheet.R
#################################################################################################################################### #################################################################################################################################### # >> #' @title calculationChain #' @param df Dataframe for input file data. #' @param sampleNames Names of the samples found in the input file. #' @param sampleNamesUpdate Updated names of the samples found in the input file. #' @param dateTimeCurrent Date and time at the time the simulation began. #' @noRd # << #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### ##################################### calculationChain() ########################################################################### # >> calculationChain <- function( df, sampleNames, sampleNamesUpdate, dateTimeCurrent ) { # Performing Alpha-helix calculation for database #### Err$prefix = "Chain" Err$note(0) Err$note( "Performing chain calculation for database..." ) dataBase_chain = select( dataBase_chain, c(1,2) ) num_Pro_caa = unique( dataBase_chain$id ) protein = vector() num_caa_pro_DB = vector() pb_1 = winProgressBar( title = "progress bar", min = 0, max = length(num_Pro_caa), width = 300) i = 1 for( i in 1 : length(num_Pro_caa) ) { item = num_Pro_caa[i] proteins = filter( dataBase_chain, id == item ) num_caa_pro_DB_temp = length(proteins$id) num_caa_pro_DB = c( num_caa_pro_DB_temp, num_caa_pro_DB ) protein = c( unique(proteins$id), protein ) proteins = vector() num_caa_pro_DB_temp = vector() setWinProgressBar( pb_1, i, title = paste( 'chain calculation for database ', round( i/length(num_Pro_caa)*100, 0 ), "% done") ) } Err$note("Done." ) close(pb_1) # Calculating the number of amino acids for chain #### caa = data.frame( id = protein, num_caa = num_caa_pro_DB ) cal_for_database = left_join( dataBase_numOfAA, caa, by = 'id' ) Sys.sleep(0.5) # Samples #### i = 1 for( i in 1 : length(sampleNames) ) { Err$note( 0 ) Err$note( paste0("Working on sample: ", sampleNamesUpdate[i] ) ) Err$note( 1 ) # Peptides in the sample >> Err$note( "Geting list of peptides..." ) temp = which( names(df) == sampleNames[i] ) sample_peptides = filter( df, df[,temp] > 0 ) Err$note("Done." ) nameFile = gsub( " ", "_", paste0( dateTimeCurrent, " ", 'list of peptides in', sampleNamesUpdate[i], '.csv' ), fixed = FALSE ) write.csv( sample_peptides, nameFile, row.names = FALSE ) updateUserFileCreated( nameFile ) Err$note( 1 ) sample = paste( as.character(sampleNamesUpdate[i]), '_ peptides' ) assign( sample, sample_peptides ) # Proteins in the sample >> Err$note( "Geting list of proteins..." ) sample_proteins = unique(sample_peptides$Proteins) Err$note("Done." ) nameFile = gsub( " ", "_", paste0( dateTimeCurrent, " ", 'list of proteins in', sampleNamesUpdate[i], '.csv' ), fixed = FALSE ) write.csv( sample_proteins, nameFile, row.names = FALSE ) updateUserFileCreated( nameFile ) Err$note( 1 ) sample = paste( as.character(sampleNamesUpdate[i]), '_ proteins' ) assign( sample, sample_proteins ) # Calculating chain coverage for samples >> Err$note( "Calculating chain coverage for samples..." ) proteins_in_s = vector() aa_in_s = vector() caa_in_s = vector() pb_2 = winProgressBar( title = "progress bar", min = 0, max = length(sample_proteins), width = 300 ) j = 1 for( j in 1 : length(sample_proteins) ) { item = sample_proteins[j] Pro_chunk = filter( sample_peptides, sample_peptides$Proteins == item ) k = 1 list_aa_s = vector() for( k in 1 : length(Pro_chunk$Proteins) ) { start = Pro_chunk$Start.position[k] end = Pro_chunk$End.position[k] list_aa_s_temp = seq(start:end) list_aa_s_temp = list_aa_s_temp+start-1 list_aa_s = c( list_aa_s_temp, list_aa_s ) list_aa_s_temp = vector() } proteins_temp = item proteins_in_s = c( proteins_temp, proteins_in_s ) proteins_temp = vector() aa_in_s_temp = length( unique(list_aa_s) ) aa_in_s = c( aa_in_s_temp, aa_in_s ) aa_in_s_temp = vector() protein_chunk_dataBase = filter( dataBase_chain, id == item ) caa_in_s_temp = unique(list_aa_s)%in%protein_chunk_dataBase$n caa_in_s_temp = sum(caa_in_s_temp) caa_in_s = c( caa_in_s_temp, caa_in_s ) caa_in_s_temp = vector() results = data.frame( id = proteins_in_s, num_amino_acids_in_sample = aa_in_s, num_chain_amino_acids_in_sample = caa_in_s ) results = left_join( results, cal_for_database, by = 'id' ) setWinProgressBar( pb_2, j, title = paste( 'Chain calculation for ', sampleNames[i], ' ', round( j/length(sample_proteins)*100, 0 ), "% done") ) } Err$note( "Done" ) nameFile = gsub( " ", "_", paste0( dateTimeCurrent, " ", 'chain analysis of', sampleNamesUpdate[i], '.csv' ), fixed = FALSE ) write.csv( results, nameFile, row.names = FALSE ) updateUserFileCreated( nameFile ) close(pb_2) } Err$reset() return( invisible(NULL) ) } # << ##################################### calculationChain() ########################################################################### ####################################################################################################################################
/scratch/gouwar.j/cran-all/cranData/ypssc/R/calculationChain.R
#################################################################################################################################### ################################## exit ############################################################################################ # >> exit <- function() { opt = options(show.error.messages = FALSE) on.exit(options(opt)) stop() } # << ################################## exit ############################################################################################ #################################################################################################################################### #################################################################################################################################### ################################## exit (old) ###################################################################################### # >> # exit <- function() { # .Internal(.invokeRestart(list(NULL, NULL), NULL)) # } # << ################################## exit (old) ###################################################################################### ####################################################################################################################################
/scratch/gouwar.j/cran-all/cranData/ypssc/R/exit.R
#################################################################################################################################### #################################################################################################################################### # >> #' @title Alpha Helix Calculator #' @description Form bottom-up proteomics data of proteins (peptides), this function determines the sections of proteins (in #' percentage) with alpha-helix, structure. #' @param pathFileInput Path of the input csv file generated from MaxQuant. \cr #' \cr #' MaxQuant is a quantitative proteomics software designed to analyze large mass-spectrometric data. The input of MaxQuant is a #' raw file (.raw) from high-resolution mass spectrometers. After analysis of the raw file in MaxQuant, the program generates a #' folder named “combined”. \cr #' \cr #' In this folder there is another folder named “txt” which contains many files with text format (.txt). One of the files called #' “peptides” which is the input of the ypssc to calculate secondary structures. ypssc has been designed such a way that can #' analyzed and extract information regarding the sample regardless of the name that user chosen for the sample. #' @param pathDirOutput Path of the directory to which the output files will be generated. #' @param ... (for developer use only) #' @return The output of the program is a csv file (.csv) that contains 5 columns, and the number of rows depends on the number of #' proteins in the sample. \cr #' \cr #' First column contains the ID of the identified alpha-helix proteins in the sample, second column contains the number of identified #' amino acids from the corresponding protein, third column contains number of identified amino acids with alpha-helix structure, #' fourth column contains the number of amino acids that the protein originally has in the SSDYP, and fifth column contains the #' number of amino acids with alpha-helix structure that the protein originally has in the SSDYP. \cr #' \cr #' These columns should provide all information that the user needs to know about the protein and its structural information as #' well as structural information about the parts of the protein that has been identified in the sample. \cr #' \cr #' In addition, it also generates 4 more '.csv' files. \cr #' 1. The no. of proteins found in the sample. \cr #' 2. The no. of peptides found in the sample. \cr #' 3. The no. of amino acids for each protein in database. \cr #' 4. It is the input file from MaxQuant that's been cleaned up for the sole purpose of calculating secondary structures. #' @examples #' \dontrun{ #' findAlpha( pathFileInput = "some/path/to/inputFile.csv", #' pathDirOutput = "some/path/to/outputDir/" ) #' #' findAlpha() #' } #' @seealso [`findSecondary`], [`findBeta`], [`findChain`] #' @export # << #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### ##################################### findAlpha() ################################################################################## # >> findAlpha = function( pathFileInput = NULL, pathDirOutput = NULL, ... ) { startTime = Sys.time() originalWorkingDir = getwd() if ( length(c(...)) != 0 ) { isTest = c(...)[1] } else { isTest = FALSE } # Print intro >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Err$box( "Alpha Helix Calculator started..." ) # Checking if 'pathFileInput' is provided or exists >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> pathFileInput = checkFileInput( pathFileInput ) # Checking if 'pathDirOutput' is provided >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> pathDirOutput = checkDirOutput( pathDirOutput ) # Reading the input sample file >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> dataFileInput = readFileInput( pathFileInput, isTest ) df = dataFileInput$df sampleNames = dataFileInput$sampleNames sampleNamesUpdate = dataFileInput$sampleNamesUpdate # Creating output folder >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> dateTimeCurrent = creatOutputDir( pathDirOutput, "alpha" ) # Removing the rows that are not needed >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> df = removeRows( df, dateTimeCurrent, isTest ) # Writing `dataBase_numOfAA` >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> write.csv( dataBase_numOfAA, paste0( dateTimeCurrent, "_dataBase_numOfAA.csv" ), row.names = FALSE ) # Alpha helix calculation for dataBase >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> calculationAlphaHelix( df, sampleNames, sampleNamesUpdate, dateTimeCurrent ) # End >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> updateUserSuccess(isTest) endTime = Sys.time() timeTaken = endTime - startTime Err$note(0); Err$note( paste0( "Time taken for the ypssc run: ", format(timeTaken) ) ) Err$note(0); Err$note(0) # Setting working directory back to original >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> setwd( originalWorkingDir ) return( invisible(NULL) ) } # << ##################################### findAlpha() ################################################################################## ####################################################################################################################################
/scratch/gouwar.j/cran-all/cranData/ypssc/R/findAlpha.R
#################################################################################################################################### #################################################################################################################################### # >> #' @title Beta Sheet Calculator #' @description Form bottom-up proteomics data of proteins (peptides), this function determines the sections of proteins (in #' percentage) with beta-sheet, structure. #' @param pathFileInput Path of the input csv file generated from MaxQuant. \cr #' \cr #' MaxQuant is a quantitative proteomics software designed to analyze large mass-spectrometric data. The input of MaxQuant is a #' raw file (.raw) from high-resolution mass spectrometers. After analysis of the raw file in MaxQuant, the program generates a #' folder named “combined”. \cr #' \cr #' In this folder there is another folder named “txt” which contains many files with text format (.txt). One of the files called #' “peptides” which is the input of the ypssc to calculate secondary structures. ypssc has been designed such a way that can #' analyzed and extract information regarding the sample regardless of the name that user chosen for the sample. #' @param pathDirOutput Path of the directory to which the output files will be generated. #' @param ... (for developer use only) #' @return The output of the program is a csv file (.csv) that contains 5 columns, and the number of rows depends on the number of #' proteins in the sample. \cr #' \cr #' First column contains the ID of the identified alpha-helix proteins in the sample, second column contains the number of identified #' amino acids from the corresponding protein, third column contains number of identified amino acids with secondary structure, #' fourth column contains the number of amino acids that the protein originally has in the SSDYP, and fifth column contains the #' number of amino acids with beta-sheet that the protein originally has in the SSDYP. \cr #' \cr #' These columns should provide all information that the user needs to know about the protein and its structural information as #' well as structural information about the parts of the protein that has been identified in the sample. \cr #' \cr #' In addition, it also generates 4 more '.csv' files. \cr #' 1. The no. of proteins found in the sample. \cr #' 2. The no. of peptides found in the sample. \cr #' 3. The no. of amino acids for each protein in database. \cr #' 4. It is the input file from MaxQuant that's been cleaned up for the sole purpose of calculating secondary structures. #' @examples #' \dontrun{ #' findBeta( pathFileInput = "some/path/to/inputFile.csv", #' pathDirOutput = "some/path/to/outputDir/" ) #' #' findBeta() #' } #' @seealso [`findSecondary`], [`findAlpha`], [`findChain`] #' @export # << #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### ##################################### findBeta() ################################################################################### # >> findBeta = function( pathFileInput = NULL, pathDirOutput = NULL, ... ) { startTime = Sys.time() originalWorkingDir = getwd() if ( length(c(...)) != 0 ) { isTest = c(...)[1] } else { isTest = FALSE } # Print intro >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Err$box( "Beta Sheet Calculator started..." ) # Checking if 'pathFileInput' is provided or exists >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> pathFileInput = checkFileInput( pathFileInput ) # Checking if 'pathDirOutput' is provided >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> pathDirOutput = checkDirOutput( pathDirOutput ) # Reading the input sample file >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> dataFileInput = readFileInput( pathFileInput, isTest ) df = dataFileInput$df sampleNames = dataFileInput$sampleNames sampleNamesUpdate = dataFileInput$sampleNamesUpdate # Creating output folder >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> dateTimeCurrent = creatOutputDir( pathDirOutput, "beta" ) # Removing the rows that are not needed >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> df = removeRows( df, dateTimeCurrent, isTest ) # Writing `dataBase_numOfAA` >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> write.csv( dataBase_numOfAA, paste0( dateTimeCurrent, "_dataBase_numOfAA.csv" ), row.names = FALSE ) # Alpha helix calculation for dataBase >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> calculationBetaSheet( df, sampleNames, sampleNamesUpdate, dateTimeCurrent ) # End >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> updateUserSuccess(isTest) endTime = Sys.time() timeTaken = endTime - startTime Err$note(0); Err$note( paste0( "Time taken for the ypssc run: ", format(timeTaken) ) ) Err$note(0); Err$note(0) # Setting working directory back to original >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> setwd( originalWorkingDir ) return( invisible(NULL) ) } # << ##################################### findBeta() ################################################################################### ####################################################################################################################################
/scratch/gouwar.j/cran-all/cranData/ypssc/R/findBeta.R
#################################################################################################################################### #################################################################################################################################### # >> #' @title Chain Calculator #' @description Form bottom-up proteomics data of proteins (peptides), this function determines the sections of proteins (in #' percentage) with primary, structure. #' @param pathFileInput Path of the input csv file generated from MaxQuant. \cr #' \cr #' MaxQuant is a quantitative proteomics software designed to analyze large mass-spectrometric data. The input of MaxQuant is a #' raw file (.raw) from high-resolution mass spectrometers. After analysis of the raw file in MaxQuant, the program generates a #' folder named “combined”. \cr #' \cr #' In this folder there is another folder named “txt” which contains many files with text format (.txt). One of the files called #' “peptides” which is the input of the ypssc to calculate secondary structures. ypssc has been designed such a way that can #' analyzed and extract information regarding the sample regardless of the name that user chosen for the sample. #' @param pathDirOutput Path of the directory to which the output files will be generated. #' @param ... (for developer use only) #' @return The output of the program is a csv file (.csv) that contains 5 columns, and the number of rows depends on the number of #' proteins in the sample. \cr #' \cr #' First column contains the ID of the identified alpha-helix proteins in the sample, second column contains the number of identified #' amino acids from the corresponding protein, third column contains number of identified amino acids with secondary structure, #' fourth column contains the number of amino acids that the protein originally has in the SSDYP, and fifth column contains the #' number of amino acids in chain structure that the protein originally has in the SSDYP. \cr #' \cr #' These columns should provide all information that the user needs to know about the protein and its structural information as #' well as structural information about the parts of the protein that has been identified in the sample. \cr #' \cr #' In addition, it also generates 4 more '.csv' files. \cr #' 1. The no. of proteins found in the sample. \cr #' 2. The no. of peptides found in the sample. \cr #' 3. The no. of amino acids for each protein in database. \cr #' 4. It is the input file from MaxQuant that's been cleaned up for the sole purpose of calculating secondary structures. #' @examples #' \dontrun{ #' findChain( pathFileInput = "some/path/to/inputFile.csv", #' pathDirOutput = "some/path/to/outputDir/" ) #' #' findChain() #' } #' @seealso [`findSecondary`], [`findAlpha`], [`findBeta`] #' @export # << #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### ##################################### findChain() ################################################################################## # >> findChain <- function( pathFileInput = NULL, pathDirOutput = NULL, ... ) { startTime = Sys.time() originalWorkingDir = getwd() if ( length(c(...)) != 0 ) { isTest = c(...)[1] } else { isTest = FALSE } # Print intro >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Err$box( "Chain Calculator started..." ) # Checking if 'pathFileInput' is provided or exists >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> pathFileInput = checkFileInput( pathFileInput ) # Checking if 'pathDirOutput' is provided >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> pathDirOutput = checkDirOutput( pathDirOutput ) # Reading the input sample file >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> dataFileInput = readFileInput( pathFileInput, isTest ) df = dataFileInput$df sampleNames = dataFileInput$sampleNames sampleNamesUpdate = dataFileInput$sampleNamesUpdate # Creating output folder >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> dateTimeCurrent = creatOutputDir( pathDirOutput, "chain" ) # Removing the rows that are not needed >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> df = removeRows( df, dateTimeCurrent, isTest ) # Writing `dataBase_numOfAA` >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> write.csv( dataBase_numOfAA, paste0( dateTimeCurrent, "_dataBase_numOfAA.csv" ), row.names = FALSE ) # Chain calculation for dataBase >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> calculationChain ( df, sampleNames, sampleNamesUpdate, dateTimeCurrent ) # End >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> updateUserSuccess(isTest) endTime = Sys.time() timeTaken = endTime - startTime Err$note(0); Err$note( paste0( "Time taken for the ypssc run: ", format(timeTaken) ) ) Err$note(0); Err$note(0) # Setting working directory back to original >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> setwd( originalWorkingDir ) return( invisible(NULL) ) } # << ##################################### findChain() ################################################################################## ####################################################################################################################################
/scratch/gouwar.j/cran-all/cranData/ypssc/R/findChain.R
#################################################################################################################################### #################################################################################################################################### # >> #' @title Secondary Structure Calculator #' @description Form bottom-up proteomics data of proteins (peptides), this function determines the sections of proteins (in #' percentage) with secondary structure like alpha-helix, beta sheet; also determines the parts that has primary structure. #' @param pathFileInput Path of the input csv file generated from MaxQuant. \cr #' \cr #' MaxQuant is a quantitative proteomics software designed to analyze large mass-spectrometric data. The input of MaxQuant is a #' raw file (.raw) from high-resolution mass spectrometers. After analysis of the raw file in MaxQuant, the program generates a #' folder named “combined”. \cr #' \cr #' In this folder there is another folder named “txt” which contains many files with text format (.txt). One of the files called #' “peptides” which is the input of the ypssc to calculate secondary structures. ypssc has been designed such a way that can #' analyzed and extract information regarding the sample regardless of the name that user chosen for the sample. #' @param pathDirOutput Path of the directory to which the output files will be generated. #' @param ... (for developer use only) #' @import dplyr #' @import readxl #' @import stringr #' @import eulerr #' @import Peptides #' @import utils #' @import svDialogs #' @import tcltk #' @return The output of the program is a csv file (.csv) that contains 5 columns, and the number of rows depends on the number of #' proteins in the sample. \cr #' \cr #' First column contains the ID of the identified alpha-helix proteins in the sample, second column contains the number of identified #' amino acids from the corresponding protein, third column contains number of identified amino acids with secondary structure, #' fourth column contains the number of amino acids that the protein originally has in the SSDYP, and fifth column contains the #' number of amino acids with secondary structure that the protein originally has in the SSDYP. \cr #' \cr #' These columns should provide all information that the user needs to know about the protein and its structural information as #' well as structural information about the parts of the protein that has been identified in the sample. \cr #' \cr #' In addition, it also generates 4 more '.csv' files. \cr #' 1. The no. of proteins found in the sample. \cr #' 2. The no. of peptides found in the sample. \cr #' 3. The no. of amino acids for each protein in database. \cr #' 4. It is the input file from MaxQuant that's been cleaned up for the sole purpose of calculating secondary structures. #' @examples #' \dontrun{ #' findSecondary( pathFileInput = "some/path/to/inputFile.csv", #' pathDirOutput = "some/path/to/outputDir/" ) #' #' findSecondary() #' } #' @seealso [`findAlpha`], [`findBeta`], [`findChain`] #' @export # << #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### ##################################### findSecondary() ############################################################################## # >> findSecondary <- function( pathFileInput = NULL, pathDirOutput = NULL, ... ) { startTime = Sys.time() originalWorkingDir = getwd() if ( length(c(...)) != 0 ) { isTest = c(...)[1] } else { isTest = FALSE } # Print intro >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Err$box( "Secondary Structure Calculator started..." ) # Checking if 'pathFileInput' is provided or exists >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> pathFileInput = checkFileInput( pathFileInput ) # Checking if 'pathDirOutput' is provided >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> pathDirOutput = checkDirOutput( pathDirOutput ) # Reading the input sample file >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> dataFileInput = readFileInput( pathFileInput, isTest ) df = dataFileInput$df sampleNames = dataFileInput$sampleNames sampleNamesUpdate = dataFileInput$sampleNamesUpdate # Creating output folder >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> dateTimeCurrent = creatOutputDir( pathDirOutput, "secondary" ) # Removing the rows that are not needed >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> df = removeRows( df, dateTimeCurrent, isTest ) # Writing `dataBase_numOfAA` >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> write.csv( dataBase_numOfAA, paste0( dateTimeCurrent, "_dataBase_numOfAA.csv" ), row.names = FALSE ) # Alpha helix calculation for dataBase >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> calculationAlphaHelix( df, sampleNames, sampleNamesUpdate, dateTimeCurrent ) # Beta-sheet calculation for dataBase >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> calculationBetaSheet ( df, sampleNames, sampleNamesUpdate, dateTimeCurrent ) # Chain calculation for dataBase >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> calculationChain ( df, sampleNames, sampleNamesUpdate, dateTimeCurrent ) # End >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> updateUserSuccess(isTest) endTime = Sys.time() timeTaken = endTime - startTime Err$note(0); Err$note( paste0( "Time taken for the ypssc run: ", format(timeTaken) ) ) Err$note(0); Err$note(0) # Setting working directory back to original >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> setwd( originalWorkingDir ) return( invisible(NULL) ) } # << ##################################### findSecondary() ############################################################################## ####################################################################################################################################
/scratch/gouwar.j/cran-all/cranData/ypssc/R/findSecondary.R
packageName = "ypssc" #################################################################################################################################### ################################## ypssc-package-doc ############################################################################### # >> #' #' @details #' #----------------------------------------------------------------------------------------------------------------------------------- #' \describe{\item{_**What is `ypssc`?**_}{ #----------------------------------------------------------------------------------------------------------------------------------- #' #' **`ypssc`** is an extension for NetSurfP-2.0 which is specifically designed to analyze the results of bottom-up proteomics that #' is primarily analyzed with MaxQuant. We call this tool _**Yeast Proteome Secondary Structure Calculator**_ (**`ypssc`**). #' #' \out{<hr>} #' #' **Functionalities in `ypssc`**: #' #' 1. [`findSecondary`] #' #' 2. [`findAlpha`] #' #' 3. [`findBeta`] #' #' 4. [`findChain`] #' #' (Click the above links to find out more about these functionalities and their usage.) #' #' \out{<hr>} #' #' **Note:** NetSurfP #' #' - NetSurfP-1.0 is a prediction tool for secondary structures using neural network. #' #' - NetSurfP-2.0 is an extension of NetSurfP-1.0 which utilized deep neural network to predict secondary structures with the #' accuracy of 85%. In addition to accuracy, this tool presents reduced computational time compared to other methods. #' #' - NetSurfP-2.0 is designed to be user friendly and efficient in calculation time of large number of sequences. In addition to #' that the output of the calculation is available in many formats that would make further data analysis even easier. #' #' - NetSurfP-2.0 is available as a web-sever (http://www.cbs.dtu.dk/services/NetSurfP-2.0/) which can accept up to 4000 sequences #' at a time. #' #' }} #' #' \out{<hr>} #' #----------------------------------------------------------------------------------------------------------------------------------- #' \describe{\item{_**Why this package?**_}{ #----------------------------------------------------------------------------------------------------------------------------------- #' #' This tool is designed to process large number of yeast peptides that produced as a results of whole yeast cell proteome digestion #' and provide a coherent picture of secondary structure of proteins. NetSurfP-2.0 is not designed to do this task. #' #' \out{<hr>} #' #' **Drawbacks of NetSurfP-2.0** #' #' - First, NetSurfP-2.0 is not designed to accept as many peptides at once, therefore the process of uploading the sequences and #' waiting for the calculations to be complete is extremely time consuming. #' #' - Second, even if all sequences uploaded successfully and the results are back, it would be almost impossible to combine the #' results that have been produced for each individual peptide (hundreds of thousands of spread sheets) to get a coherent #' picture of the secondary structure of the proteins. #' #' \out{<hr>} #' #' **Advantages of `ypssc`** #' #' - **`ypssc`**, on one hand benefits forms the accuracy of NetSurfP-2.0 to calculate secondary structure and on the other hand #' address the issue of analyzing so many peptides with NetSurfP-2.0 by eliminating the need for direct analysis of the peptides #' from bottom-up proteomics. #' #' - Instead of direct analysis of peptides by NetSurfP-2.0 which raises the problem of combining the results of peptides to #' proteins, the whole yeast proteome has been analyzed once by NetSurfP-2.0 and kept as Secondary Structure Database for Yeast #' Proteome (SSDYP). Then the peptides form the experiment are matched and compared to this database to extract secondary #' structure of the peptides. #' #' }} #' #' \out{<hr>} #' #----------------------------------------------------------------------------------------------------------------------------------- #' \describe{\item{_**Methodology**_}{ #----------------------------------------------------------------------------------------------------------------------------------- #' #' The SSDYP contains structural information for all amino acids of whole yeast proteome (Over 3000,000 amino acids) which contains #' over 6700 proteins. For a hypothetical protein, the SSDYP contains the ID of the protein, amino acids with numbers and structural #' information for each amino acid. Focusing on the hypothetical protein, in the real sample, there are many peptides identified #' from the hypothetical protein. **`ypssc`** first finds all the peptides that belongs to the hypothetical protein and arrange them #' based on the numbers of the amino acids; then it removes the parts of the protein that have been identified more than once in #' multiple peptides and collapses the population of identified peptides in the sample into one sequence that represents the #' coverage of the hypothetical protein. The result would show that which part of the protein is identified, and which part is #' missing. Then, **`ypssc`** matches the the sequence that identified in the sample with SSDYP to find the structural information #' about amino acids. #' #' }} #' #' \out{<hr>} #' #################################################################################################################################### #' #' @seealso [`findSecondary`], [`findAlpha`], [`findBeta`], [`findChain`] #' # << ################################## ypssc-package-doc ############################################################################### #################################################################################################################################### #' #' @keywords internal "_PACKAGE" # The following block is used by usethis to automatically manage # roxygen namespace tags. Modify with care! ## usethis namespace: start ## usethis namespace: end NULL
/scratch/gouwar.j/cran-all/cranData/ypssc/R/ypssc-package.R
# Class Definitions # This source MUST be loaded first # Class 'yuima.pars' # parameter object included in 'yuima.model' setClass("model.parameter",representation(all="character", common="character", diffusion="character", drift="character", jump="character", measure="character", # Insert parameters for starting conditions xinit="character" ) ) # Class 'yuima.model' setClass("yuima.model",representation(drift="expression", diffusion="list", hurst="ANY", jump.coeff="list", #jump.coeff="expression", measure="list", measure.type="character", parameter="model.parameter", state.variable="character", jump.variable="character", time.variable="character", noise.number="numeric", equation.number="numeric", dimension="numeric", solve.variable="character", # xinit="numeric", xinit="expression", J.flag="logical" ) ) # Class 'carma.info' setClass("carma.info", representation(p="numeric", q="numeric", loc.par="character", scale.par="character", ar.par="character", ma.par="character", lin.par="character", Carma.var="character", Latent.var="character", XinExpr="logical") ) # Class 'yuima.carma' setClass("yuima.carma", representation(info="carma.info"), contains="yuima.model") # Class Compound Poisson setClass("yuima.poisson", contains="yuima.model") # Class 'yuima.data' # we want yuimaS4 to use any class of data as input # the original data will be stored in OrigData # we convert these objects internally to "zoo" object # in the future, we may want to use more flexible # classes setClass("yuima.data", representation(original.data = "ANY", zoo.data = "ANY" ) ) # Class 'yuima.sampling' # sampling is now empty, but should give informations on the sampling # type, rate, deltas, etc. setClass("yuima.sampling", representation(Initial = "numeric", Terminal = "numeric", n = "numeric", delta = "numeric", grid = "ANY", random = "ANY", regular = "logical", sdelta = "numeric", sgrid = "ANY", oindex = "ANY", interpolation = "character" ) ) # Class 'yuima.functional' # functional model used in 'asymptotic term' procedure setClass("yuima.functional", representation(F = "ANY", f = "list", xinit = "numeric", e = "numeric" ) ) # Class 'yuima' # this is the principal class of yuima project. It may contain up to # three slots for now: the data, the model and the sampling setClass("yuima.characteristic", representation(equation.number = "numeric", time.scale = "numeric" ) ) setClass("yuima", representation(data = "yuima.data", model = "yuima.model", sampling = "yuima.sampling", characteristic = "yuima.characteristic", functional = "yuima.functional" ) ) # Class yuima.carma.qmle setClass("yuima.carma.qmle",representation(Incr.Lev = "ANY", model = "yuima.carma", logL.Incr = "ANY" ), contains="mle" ) setClass("yuima.qmle",representation( model = "yuima.model"), contains="mle" ) setClass("yuima.CP.qmle",representation(Jump.times = "ANY", Jump.values = "ANY", X.values = "ANY", model = "yuima.model", threshold="ANY"), contains="mle" ) setClass("summary.yuima.carma.qmle",representation(MeanI = "ANY", SdI = "ANY", logLI = "ANY", TypeI = "ANY", NumbI = "ANY", StatI ="ANY", model = "yuima.carma", Additional.Info = "ANY"), contains="summary.mle" ) setClass("summary.yuima.CP.qmle", representation(NJ = "ANY", MeanJ = "ANY", SdJ = "ANY", MeanT = "ANY", Jump.times = "ANY", Jump.values = "ANY", X.values = "ANY", model = "yuima.model", threshold = "ANY"), contains="summary.mle" ) setClass("summary.yuima.qmle", representation( model = "yuima.model", threshold = "ANY", Additional.Info = "ANY"), contains="summary.mle" ) # The yuima.carma.qmle extends the S4 class "mle". It contains three slots: Estimated Levy, # The description of the carma model and the mle.
/scratch/gouwar.j/cran-all/cranData/yuima/R/AllClasses.R
is.CarmaHawkes<-function(obj){ if(is(obj,"yuima")) return(is(obj@model, "yuima.carmaHawkes")) if(is(obj,"yuima.model")) return(is(obj, "yuima.carmaHawkes")) return(FALSE) } # CARMA Hawkes Utilities Atilde<-function(a,b){ # a <- [a_1,...a_p] # b <- [b_0,...,b_{p-1}] d <- length(a) btrue<-numeric(length =d) btrue[1:length(b)]<-b lastrow <- btrue-rev(a) if(d>1){ A <- cbind(0,diag(1,d-1,d-1)) Atilde <-rbind(A,lastrow) }else{ Atilde <- as.matrix(lastrow) } rownames(Atilde) <- rep(" ",d) return(Atilde) } myebold<-function(d){ res <- matrix(0, d,1) res[d]<-1 return(res) } bbold<-function(b,d){ btrue<-numeric(length =d) btrue[1:length(b)]<-b return(btrue) } Atildetilde<-function(a,b,p){ res <- matrix(0, p*(p+1)/2, p*(p+1)/2) aaa<- length(b) btrue<-numeric(length =p) btrue[1:aaa]<-b b<-btrue for(j in c(1:p)){ for(i in c(1:p)){ dimrow <- p-j+1 dimcol <- p-i+1 if(dimrow==dimcol){ #DMat<- Matr(0,dimrow,dimcol) posdf<- j*p-sum(c(0:(j-1))) if(dimrow!=1){ id<-matrix(0,dimrow,dimcol) id[1,2]<-1 DMat<-Atilde(a=a[1:dimrow],b[j:aaa]) + id }else{ DMat<- as.matrix(2*tail(btrue-rev(a),1L)) } res[(posdf-dimrow+1):posdf,(posdf-dimrow+1):posdf]<-DMat } if(dimrow<dimcol){ posdfcol<- i*p-sum(c(0:(i-1))) posdfrow<- j*p-sum(c(0:(j-1))) LMat<- matrix(0,dimrow,dimcol) if(dimrow!=1){ LMat[dim(LMat)[1],j-i+1]<-b[i]-a[p-i+1] }else{ LMat[dim(LMat)[1],j-i+1]<-2*(b[i]-a[p-i+1]) } res[(posdfrow-dimrow+1):posdfrow,(posdfcol-dimcol+1):posdfcol]<-LMat } if(dimrow==dimcol+1){ posdfcol<- i*p-sum(c(0:(i-1))) posdfrow<- j*p-sum(c(0:(j-1))) UMat<- rbind(0,diag(dimcol)) res[(posdfrow-dimrow+1):posdfrow,(posdfcol-dimcol+1):posdfcol]<-UMat } } } return(res) } BboldFunct<-function(b,p){ aaa<- length(b) btrue<-numeric(length =p) btrue[1:aaa]<-b b<-btrue #Bbold[1,]<-b if(p>1){ Bbold<- diag(rep(b[1],p)) Bbold[1,]<-b for(i in c(2:p)){ A0<-matrix(0,i-1,p-i+1) if(p-i+1!=1){ Ai<-diag(rep(b[i],p-i+1)) }else{Ai <- as.matrix(b[i])} Ai[1,]<-b[i:p] dumA <- rbind(A0,Ai) Bbold<- cbind(Bbold,dumA) } }else{ Bbold<-as.matrix(b) } return(Bbold) } Ctilde <- function(mu,b,p){ if(p>1){ Ctilde <- matrix(0,p,p) Ctilde[p,1] <- mu for(j in c(1:(p-1))){ dum<- matrix(0,p-j,p) dum[p-j,j+1]<- mu Ctilde<- rbind(Ctilde,dum) } aaa<- length(b) btrue<-numeric(length =p) btrue[1:aaa]<-b dumVec <- numeric(length =p) dumVec[p]<- 2*mu vect <- btrue+dumVec Ctilde[p*(p+1)/2,]<- vect }else{ Ctilde <- as.matrix(b+2*mu) } return(Ctilde) } ExpIncr<-function(mu,b,a,X0,t0,ti1,ti2){ At<-Atilde(a,b) Ainv<-solve(At) d <- length(a) ebold <-myebold(d) bb<-bbold(b,d) term1 <-t(bb)%*%Ainv res <- mu*(1-term1%*%ebold)*(ti2-ti1) res <- res+term1%*%(expm(At*(ti2-t0))-expm(At*(ti1-t0)))%*%(X0+Ainv%*%ebold*mu) return(res) } tripletExpInt <- function(A11,A12,A22,A23,A33,T1){ # dA <- dim(A) # dB <- dim(B) # bigA<- cbind(A,C) # dummy <-matrix(0,dB[1],dA[2]) # big1<- cbind(dummy,B) # bigA<-rbind(bigA,big1) dA11 <- dim(A11) dA12 <- dim(A12) dA22<-dim(A22) dA23 <- dim(A23) dA33 <- dim(A33) dummy <-matrix(0,dA11[1],dA23[2]) bigA<- cbind(A11,A12,dummy) dummy <-matrix(0,dA22[1],dA23[2]) big1 <- cbind(dummy,A22,A23) bigA<-rbind(bigA,big1) dummy<- matrix(0,dA33[1],dA11[2]+dA22[2]) big1 <- cbind(dummy,A33) bigA<-rbind(bigA,big1) return(bigA) #res <- expm(bigA*T1)[1:dA[1], 1:dB[2]+dA[2]] } makeSymm <- function(m) { m[upper.tri(m)] <- t(m)[upper.tri(m)] return(m) } doubleExpInt <- function(A,C,B,T1){ dA <- dim(A) dB <- dim(B) bigA<- cbind(A,C) dummy <-matrix(0,dB[1],dA[2]) big1<- cbind(dummy,B) bigA<-rbind(bigA,big1) res <- expm(bigA*T1)[1:dA[1], 1:dB[2]+dA[2]] } VtrillX0 <- function(X0, Att, At, Ct, mu, p, t0=0, T1){ e<- matrix(0,p,1) e[p,1]<-1 et <- matrix(0,p*(p+1)/2,1) et[p*(p+1)/2,1]<-1 XX0<- as.matrix(X0)%*%t(as.matrix(X0)) vtXX0<-as.matrix(XX0[lower.tri(XX0,T)]) AttInv<-solve(Att) AtInv <-solve(At) term1 <- expm(Att*(T1-t0))%*%(vtXX0+mu*AttInv%*%et-mu*AttInv%*%Ct%*%AtInv%*%e )# ->0 as T->+\infty term2 <- mu*AttInv%*%Ct%*%AtInv%*%e - mu*AttInv%*%et B12<-doubleExpInt(A=Att,C=Ct,B=At,T1=T1) term3 <- B12%*%expm(-At*t0)%*%(X0+AtInv%*%e*mu) return(list(res =term1+term2+term3, term1=term1, term2=term2, term3=term3)) } gfunct <- function(a,b,mu){ p<-length(a) At<-Atilde(a,b) eb<-myebold(p) AtInv <- solve(At) Att <- Atildetilde(a,b,p) AttInv <- solve(Att) etilde <- myebold(p*(p+1)/2) B <- BboldFunct(b,p) Ct <- Ctilde(mu,b,p) aaa <- length(b) btrue<-numeric(length =p) btrue[1:aaa]<-b b<-btrue const <- AtInv*mu Term1 <- as.numeric(t(b)%*%AtInv%*%eb) res <- eb*Term1-eb+AtInv%*%eb*mu*Term1+B%*%AttInv%*%(etilde-Ct%*%AtInv%*%eb) return(mu*AtInv%*%res) } # Function For simulation of the trajectories S_Kfunction <- function(S_old, T_k, T_old, A, Id){ res<- expm(A*(T_k-T_old))%*%(S_old + Id) return(res) } S_KfunctionSim <- function(S_old, T_k, T_old, A, Id){ res<- expm(A*(T_k-T_old))%*%(S_old ) + Id return(res) } ConditionForSimul <-function(x,U,S_k, T_k, A, Ainv, Id, bbold1, ebold1, mu, t0=0, X0){ res0 <- mu*(x-T_k)+t(bbold1)%*%expm(A*(T_k-t0))%*%(Ainv%*%(expm(A*(x-T_k))-Id)%*%X0) res0 <-res0+t(bbold1)%*%S_k%*%(Ainv%*%(expm(A*(x-T_k))-Id)%*%ebold1) res<-log(U)+as.numeric(res0) return(res) } simulateCarmaHawkes <-function(mu,b,a,X0,t0=0,FinalTime){ p<- length(a) A <- Atilde(a, numeric(length =p)) Ainv <- solve(A) bbold1 <- bbold(b,p) ebold1 <- myebold(p) JumpTime <- NULL U<-runif(1) JumpTime <- -log(U)/mu if(JumpTime<FinalTime){ Cond<-TRUE }else{ return(NULL) } S_old <- diag(1,p,p) Id <- diag(1,p,p) T_old<-JumpTime S_k <- S_old T_k <- JumpTime while(Cond){ U<-runif(1) # S_old <-S_Kfunction(S_k, T_k, T_old, A, Id) S_k <-S_KfunctionSim(S_k, T_k, T_old, A, Id) T_old <- T_k res<-uniroot(f=ConditionForSimul,interval=c(T_k, 10*FinalTime), U=U,S_k=S_k, T_k=T_k, A=A, Ainv=Ainv, Id=Id, bbold1=bbold1, ebold1=ebold1, mu=mu, X0=X0) T_k<-res$root if(T_k<=FinalTime){ JumpTime<-c(JumpTime,T_k) #cat("\n",T_k) f_u<-ConditionForSimul(x=10*FinalTime,U,S_k, T_k, A, Ainv, Id, bbold1, ebold1, mu, t0=0, X0) f_l<-ConditionForSimul(x=T_k,U,S_k, T_k, A, Ainv, Id, bbold1, ebold1, mu, t0=0, X0) if(f_u*f_l>=0){ Cond=FALSE # cat("\n vedi ", T_k) } }else{ Cond <- FALSE } } #CountProc <- 1:length(JumpTime) JumpTime<- c(0,JumpTime) return(JumpTime) } aux.simulateCarmaHawkes<- function(object, true.parameter){ model <- object@model ar.par <- true.parameter[model@[email protected]] ma.par <- true.parameter[model@[email protected]] if(!model@info@XinExpr){ X0 <- rep(0,model@info@p) }else{ yuima.stop("X0 will be available as soon as possible") } mu <- true.parameter[model@[email protected]] t0 <- object@sampling@Initial[1] FinalTime <- object@sampling@Terminal[1] res <- simulateCarmaHawkes(mu = mu,b = ma.par,a = ar.par, X0 = X0,t0 = t0, FinalTime = FinalTime) numb<-length(res) if(length(object@model@[email protected])==0){ param <- 1 names(param)<- object@model@[email protected] Nt<-cumsum(c(0,rand(object@model@measure$df, n=numb, param=param))) }else{ yuima.stop("Jump size different from 1 will be available as soon as possible") } Nt<-matrix(Nt) colnames(Nt)<-object@model@[email protected] res1<-zoo(x=Nt, order.by=res) mydata <- setData(original.data = res1) obsgrid <- na.approx(res1,xout=object@sampling@grid[[1]], method ="constant") [email protected][[1]]<-obsgrid object@data <- mydata object@[email protected] <- object@model@[email protected] # Check Again return(object) } SimThinAlg <- function(x,FinalT, p, q){ mu0<-x[1] a0<-x[1:p+1] b0<-x[1:(q+1)+p+1] b0 <- bbold(b0,p) A <- Atilde(a0, numeric(length =p)) eigenvalues <- sort(eigen(A)$values,decreasing = TRUE) dumexp <- 1:p-1 S <- kronecker(t(eigenvalues),as.matrix(dumexp),"^") #S_new%*%diag(eigenvalues)%*%solve(S_new) # coef<-as.matrix(sqrt(sum(abs(t(b0)%*%S)^2))*sqrt(sum(abs(solve(S)%*%myebold(p))^2))) expcoef <- as.matrix(-max(Re(eigenvalues))) # Initialize JumpTime <- NA s <- 0 n <- 0 U<-runif(1) JumpTime[1] <- -log(U)/mu0 S_k <- diag(1,p,p) Id <- diag(1,p,p) S_k_H <- diag(1) Id_H <- diag(1) s <- s+ JumpTime[1] T_old <- 0 T_k <- JumpTime[1] S_k <-S_KfunctionSim(S_k, T_k, T_old, A, Id) S_k_H <-S_KfunctionSim(S_k_H, T_k, T_old, -expcoef, Id_H) bbold1 <- bbold(b0,p) ebold1 <- myebold(p) n<-1 #i=0 while(s<FinalT){ U<-runif(1) # S_old <-S_Kfunction(S_k, T_k, T_old, A, Id) lambda_k_bar <- as.numeric(mu0+exp(-expcoef*(s-T_k))*coef*S_k_H) omega <- -log(U)/lambda_k_bar s <- s+omega D <- runif(1) lambda_k <- mu0+ as.numeric(t(bbold1)%*%expm(A*(s-T_k))%*%S_k%*%ebold1) if(lambda_k_bar*D<lambda_k){ n<-n+1 T_old <- T_k T_k <- s JumpTime <- c(JumpTime, T_k) S_k <-S_KfunctionSim(S_k, T_k, T_old, A, Id) S_k_H <-S_KfunctionSim(S_k_H, T_k, T_old, -expcoef, Id_H) } #i<-i+1 # cat("\n",i) } if(T_k <=FinalT){ res <- zoo(0:n,order.by = c(0,JumpTime)) }else{ JumpTime <- JumpTime[-n] res <- zoo(1:n-1, order.by =c(0,JumpTime)) } return(res) } aux.simulateCarmaHawkes_thin<- function(object, true.parameter){ model <- object@model p <- length(model@[email protected]) q <- length(model@[email protected]) if(!model@info@XinExpr){ X0 <- rep(0,p) }else{ yuima.stop("X0 will be available as soon as possible") } # mu <- true.parameter[model@[email protected]] # t0 <- object@sampling@Initial[1] true.parameter <- true.parameter[c(model@[email protected],model@[email protected],model@[email protected])] FinalTime <- object@sampling@Terminal[1] res <- SimThinAlg(x=true.parameter,FinalT=FinalTime, p = p, q = q-1) numb<-length(res) if(length(object@model@[email protected])==0){ param <- 1 names(param)<- object@model@[email protected] Nt<-cumsum(c(0,rand(object@model@measure$df, n=numb, param=param))) }else{ yuima.stop("Jump size different from 1 will be available as soon as possible") } Nt<-matrix(Nt) colnames(Nt)<-object@model@[email protected] res1<-zoo(x=Nt, order.by=index(res)) mydata <- setData(original.data = res1) obsgrid <- na.approx(res1,xout=object@sampling@grid[[1]], method ="constant") [email protected][[1]]<-obsgrid object@data <- mydata object@[email protected] <- object@model@[email protected] # Check Again return(object) } Int_LikelihoodCarmaHawkes <- function(x,p,q,JumpTime,T_k, numbOfJump, t0 = 0, Id = diag(p), X0 = matrix(0,p), display = FALSE){ mu<-x[1] a<-x[1:p+1] b<-x[1:(q+1)+p+1] A <- Atilde(a,rep(0,p)) InvA <- solve(A) bbold1 <- bbold(b,p) ebold1 <- myebold(p) res0<-mu*(T_k-t0) dum <- t(bbold1)%*%InvA res1 <- dum%*%(expm(A*(T_k-t0))-Id)%*%X0 lambda<-numeric(length=numbOfJump) S<-Id*0 #S_Kfunction(Id, T_k=JumpTime[1], JumpTime[1], A, Id) hawkes #S<-S_Kfunction(Id, T_k=JumpTime[1], JumpTime[1], A, Id) # interstep <- expm(A*(JumpTime[1]-t0))%*%X0+S%*%ebold1 lambda[1]<-mu# + as.numeric(t(bbold1)%*%interstep) for(i in c(2:numbOfJump)){ S<-S_Kfunction(S, T_k=JumpTime[i], JumpTime[i-1], A, Id) interstep <- expm(A*(JumpTime[i]-t0))%*%X0+S%*%ebold1 lambda[i]<-mu+as.numeric(t(bbold1)%*%interstep) } if(any(is.infinite(lambda))){ res <--10^6 }else{ if(any(is.nan(lambda))){ res <--10^6 }else{ if(all(lambda>0)){ res1 <- res1+dum%*%S%*%ebold1-numbOfJump*dum%*%ebold1 res <--res0-as.numeric(res1)+sum(log(lambda[-1])) if(display){cat("\n", c(res,x))} }else{ res<--10^6 } } } return(-res/numbOfJump) } EstimCarmaHawkes <- function(yuima, start, est.method = "qmle", method = "BFGS", lower = NULL, upper = NULL, lags = NULL, display = FALSE){ model <- yuima@model names.par <- c(model@[email protected], model@[email protected], model@[email protected]) cond0 <- all(names(start) %in% names.par) #& all(names.par %in% names(start)) if(!cond0){ yuima.stop(paste("names in start are ", paste(names(start), collapse = ", "), " while param names in the model are ", paste(names.par, collapse = ", "), collapse ="")) } true.par <- start[names.par] p <- model@info@p q <- model@info@q t0 <- yuima@sampling@Initial[1] if(est.method=="qmle"){ JumpTime <- time(yuima@[email protected]) T_k <- tail(JumpTime,1L) #t0 <- JumpTime[1] if(is.null(lower) & is.null(upper)){ res <- optim(par=true.par,fn = Int_LikelihoodCarmaHawkes, p = p,q=q, JumpTime = JumpTime, T_k= T_k, numbOfJump=tail(as.numeric(yuima@[email protected]),1L), t0=t0,Id=diag(1,p,p), display = display, method = method) }else{ yuima.stop("constraints will be available as soon as possible.") } res$value <- res$value*T_k }else{ yuima.warn("We estimate the Carma(p,q)-Hawkes using the empirical autocorrelation function") yuima.stop("This method is not available yet!!! It will be implemented as soon as possible") } return(res) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/AuxMethodForCARMAHawkes.R
## Here we write all auxiliar functions for the Point Process ## Regression Model is.PPR <- function(yuimaPPR){is(yuimaPPR,"yuima.PPR")} Internal.LogLikPPR <- function(param,my.envd1=NULL, my.envd2=NULL,my.envd3=NULL, commonPar = FALSE, auxModel = NULL, auxPar = NULL){ param<-unlist(param) if(any(my.envd3$CondIntensityInKern)){ IntLambda<- InternalConstractionIntensityFeedBackIntegrand(param,my.envd1, my.envd2,my.envd3) }else{ IntLambda<-InternalConstractionIntensity2(param,my.envd1, my.envd2,my.envd3) } # IntLambda<-InternalConstractionIntensity(param,my.envd1, # my.envd2,my.envd3) Index<-my.envd3$gridTime if(my.envd3$YUIMA.PPR@gFun@dimension[1]==1){ Integr1a <- -sum(IntLambda[-length(IntLambda)]*my.envd3$YUIMA.PPR@sampling@delta,na.rm=TRUE) Integr1b <- -sum(IntLambda[-1]*my.envd3$YUIMA.PPR@sampling@delta,na.rm=TRUE) Integr1 <- (Integr1a+Integr1b)/2 # if(is.nan(Integr1)){ # Integr1 <- -10^6 # } if(length(my.envd3$YUIMA.PPR@[email protected])>0){ cond1 <- my.envd3$YUIMA.PPR@[email protected] %in% my.envd3$YUIMA.PPR@[email protected] cond2 <- diff(as.numeric(my.envd3$YUIMA.PPR@[email protected][,cond1])) #Integr2<- sum(log(IntLambda[-1][cond2!=0]),na.rm=TRUE) Integr2 <- sum(log(IntLambda[cond2!=0]),na.rm=TRUE) #Integr2 <- (Integr2a+Integr2b)/2 logLik <- Integr1+Integr2 }else{ yuima.stop("Spal") } if(is.null(my.envd1$oldpar)){ oldpar <- param }else{ oldpar <- my.envd1$oldpar } ret <- -logLik/sum(cond2,na.rm=TRUE) if(commonPar){ #ret<- ret-quasilogl(auxModel,param = param[auxModel@model@parameter@all])/auxModel@sampling@n[1] ret<- -logLik-quasilogl(auxModel,param = param[auxModel@model@parameter@all]) } }else{ posAAA <- dim(IntLambda)[2] logLik <- 0 Njump <- 0 cond0 <- length(my.envd3$YUIMA.PPR@[email protected])>0 for(hh in c(1:my.envd3$YUIMA.PPR@gFun@dimension[1])){ Integr1a <- -sum(IntLambda[hh ,-posAAA]*my.envd3$YUIMA.PPR@sampling@delta,na.rm=TRUE) Integr1b <- -sum(IntLambda[hh ,-1]*my.envd3$YUIMA.PPR@sampling@delta,na.rm=TRUE) Integr1 <- (Integr1a+Integr1b)/2 if(cond0){ cond1 <- my.envd3$YUIMA.PPR@[email protected] %in% my.envd3$YUIMA.PPR@[email protected][hh] cond2 <- diff(as.numeric(my.envd3$YUIMA.PPR@[email protected][,cond1])) #Integr2<- sum(log(IntLambda[-1][cond2!=0]),na.rm=TRUE) Integr2 <- sum(log(IntLambda[hh, cond2!=0]),na.rm=TRUE) #Integr2 <- (Integr2a+Integr2b)/2 logLik <- logLik+Integr1+Integr2 Njump <- Njump + sum(cond2,na.rm=TRUE) ret <- -logLik/Njump } } } # if(is.nan(Integr2)){ # Integr2 <- -10^6 # } #+sum((param-oldpar)^2*param^2)/2 # line 40 necessary for the development of the cod #cat("\n ",logLik, param) #assign("oldpar",param,envir = my.envd1) return(ret) } quasiLogLik.PPR <- function(yuimaPPR, parLambda=list(), method=method, fixed = list(), lower, upper, call, ...){ yuimaPPR->yuimaPPR parLambda->param # gfun<-yuimaPPR@gFun@formula gfun<-yuimaPPR@gFun@formula dimIntegr <- length(yuimaPPR@Kernel@Integrand@IntegrandList) Integrand2 <- character(length=dimIntegr) for(i in c(1:dimIntegr)){ #Integrand1 <- as.character(yuimaPPR@Kernel@Integrand@IntegrandList[[i]]) #timeCond <- paste0(" * (",yuimaPPR@[email protected]@var.time," < ",yuimaPPR@[email protected]@upper.var,")") #Integrand2[i] <-paste0(Integrand1,timeCond) Integrand2[i] <- as.character(yuimaPPR@Kernel@Integrand@IntegrandList[[i]]) } Integrand2<- matrix(Integrand2,yuimaPPR@Kernel@Integrand@dimIntegrand[1],yuimaPPR@Kernel@Integrand@dimIntegrand[2]) # for(j in c(1:yuimaPPR@Kernel@Integrand@dimIntegrand[2])){ # Integrand2[,j]<-paste0(Integrand2[,j]," * d",yuimaPPR@[email protected]@var.dx[j]) # } colnames(Integrand2) <- paste0("d",yuimaPPR@[email protected]@var.dx) NamesIntegrandExpr <- as.character(matrix(colnames(Integrand2), dim(Integrand2)[1],dim(Integrand2)[2], byrow = TRUE)) # Integrand2expr<- parse(text=Integrand2) if(yuimaPPR@Kernel@Integrand@dimIntegrand[1]==1){ Integrand2expr<- parse(text=Integrand2) }else{ Integrand2expr <- list() for(hh in c(1:yuimaPPR@Kernel@Integrand@dimIntegrand[1])){ Integrand2expr[[hh]] <- parse(text=Integrand2[hh,]) } } gridTime <- time(yuimaPPR@[email protected]) # yuimaPPR@[email protected]@var.dx if(any(yuimaPPR@[email protected]@var.dx %in% yuimaPPR@[email protected])){ my.envd1<-new.env() ExistdN<-TRUE }else{ ExistdN<-FALSE } Univariate<-FALSE if(length(yuimaPPR@[email protected])==1){ Univariate<-TRUE } if(any(yuimaPPR@[email protected]@var.dx %in% yuimaPPR@PPR@covariates)){ my.envd2<-new.env() ExistdX<-TRUE }else{ my.envd2<-new.env() ExistdX<-FALSE } my.envd3 <- new.env() namesparam<-names(param) resCov<-NULL NoFeedBackIntensity <- TRUE commonPar <- FALSE if(!(all(namesparam %in% yuimaPPR@PPR@allparamPPR) && length(namesparam)==length(yuimaPPR@PPR@allparamPPR))){ if(length(yuimaPPR@PPR@common)==0){ if(!all(yuimaPPR@[email protected] %in% yuimaPPR@[email protected])|yuimaPPR@PPR@RegressWithCount){ NoFeedBackIntensity <- FALSE } if(NoFeedBackIntensity){ namesCov <-yuimaPPR@PPR@covariates posCov <- length(namesCov) dummydrift <- as.character(yuimaPPR@model@drift[1:posCov]) dummydiff0<- NULL for(j in c(1:posCov)){ dummydiff0<-c(dummydiff0, as.character(unlist(yuimaPPR@model@diffusion[[j]]))) } dummydiff <- matrix(dummydiff0, nrow = posCov, ncol = length(dummydiff0)/posCov) dimJump <- length(yuimaPPR@[email protected][[1]])-length(yuimaPPR@[email protected]) if(dimJump>0){ dummyJump0<- NULL for(j in c(1:posCov)){ dummyJump0 <- c(dummyJump0, as.character(unlist(yuimaPPR@[email protected][[j]][1:dimJump]))) } dummyJump <- matrix(dummyJump0, nrow=posCov,ncol=dimJump) dummyModel <- setModel(drift = dummydrift, diffusion = dummydiff, jump.coeff =dummyJump, measure = list(df=yuimaPPR@model@measure$df), measure.type = yuimaPPR@[email protected][posCov], solve.variable = yuimaPPR@PPR@covariates, state.variable = yuimaPPR@PPR@covariates, xinit=yuimaPPR@model@xinit[posCov]) dummydata<-setData(original.data = yuimaPPR@[email protected][,1:posCov],delta = yuimaPPR@sampling@delta) dummyMod1 <-setYuima(model = dummyModel, data=dummydata) dummyMod1@sampling<-yuimaPPR@sampling resCov <- qmleLevy(yuima = dummyMod1, start=param[dummyMod1@model@parameter@all], lower = lower[dummyMod1@model@parameter@all],upper=upper[dummyMod1@model@parameter@all]) } } }else{ if(!all(yuimaPPR@[email protected] %in% yuimaPPR@[email protected])|yuimaPPR@PPR@RegressWithCount){ NoFeedBackIntensity <- FALSE } if(!all(yuimaPPR@[email protected] %in% yuimaPPR@[email protected])|yuimaPPR@PPR@RegressWithCount){ NoFeedBackIntensity <- FALSE } if(NoFeedBackIntensity){ namesCov <-yuimaPPR@PPR@covariates posCov <- length(namesCov) dummydrift <- as.character(yuimaPPR@model@drift[1:posCov]) # dummydiff0<- NULL # for(j in c(1:posCov)){ # dummydiff0<-c(dummydiff0, # as.character(unlist(yuimaPPR@model@diffusion[[j]]))) # } # # dummydiff <- matrix(dummydiff0, nrow = posCov, # ncol = length(dummydiff0)/posCov) dimJump <- length(yuimaPPR@[email protected][[1]])-length(yuimaPPR@[email protected]) if(dimJump>0){ dummyJump0<- NULL for(j in c(1:posCov)){ dummyJump0 <- c(dummyJump0, as.character(unlist(yuimaPPR@[email protected][[j]][1:dimJump]))) } dummyJump <- matrix(dummyJump0, nrow=posCov,ncol=dimJump) # dummyModel <- setModel(drift = dummydrift, # diffusion = dummydiff, jump.coeff =dummyJump, # measure = list(df=yuimaPPR@model@measure$df), # measure.type = yuimaPPR@[email protected][posCov], # solve.variable = yuimaPPR@PPR@covariates, # state.variable = yuimaPPR@PPR@covariates, # xinit=yuimaPPR@model@xinit[posCov]) dummyModel <- setModel(drift = dummydrift, diffusion = dummyJump, solve.variable = yuimaPPR@PPR@covariates, state.variable = yuimaPPR@PPR@covariates, xinit=yuimaPPR@model@xinit[posCov]) dummydata<-setData(original.data = yuimaPPR@[email protected][,1:posCov],delta = yuimaPPR@sampling@delta) dummyMod1 <-setYuima(model = dummyModel, data=dummydata) dummyMod1@sampling<-yuimaPPR@sampling commonPar <- TRUE # resCov <- qmleLevy(yuima = dummyMod1, # start=param[dummyMod1@model@parameter@all], # lower = lower[dummyMod1@model@parameter@all],upper=upper[dummyMod1@model@parameter@all]) } } #return(NULL) } } # construction my.envd1 if(ExistdN){ # Names expression assign("NamesIntgra", NamesIntegrandExpr, envir=my.envd1) #dN namedX <-NULL namedJumpTimeX <- NULL for(i in c(1:length(yuimaPPR@[email protected]@var.dx))){ if(yuimaPPR@[email protected]@var.dx[i] %in% yuimaPPR@[email protected]){ cond <- yuimaPPR@[email protected] %in% yuimaPPR@[email protected]@var.dx[i] namedX<-c(namedX,paste0("d",yuimaPPR@[email protected]@var.dx[i])) namedJumpTimeX <-c(namedJumpTimeX,paste0("JumpTime.d",yuimaPPR@[email protected]@var.dx[i])) dummyData <- diff(as.numeric(yuimaPPR@[email protected][,cond]))# We consider only Jump dummyJumpTime <- gridTime[-1][dummyData!=0] dummyData2 <- diff(unique(cumsum(dummyData))) #dummyData3 <- zoo(dummyData2,order.by = dummyJumpTime) # dummyData3 <- rep(1,length(dummyData2)) #JumpTime <- dummyJumpTime # Jump <- lapply(X=as.numeric(gridTime), FUN = function(X,JumpT,Jump){Jump[JumpT<X]}, # JumpT = dummyJumpTime, Jump = as.numeric(dummyData3!=0)) Jump <- lapply(X=as.numeric(gridTime), FUN = function(X,JumpT,Jump){Jump[JumpT<X]}, JumpT = dummyJumpTime, Jump = dummyData2) assign(paste0("d",yuimaPPR@[email protected]@var.dx[i]), Jump , envir=my.envd1) dummyJumpTimeNew <- lapply(X=as.numeric(gridTime), FUN = function(X,JumpT){JumpT[JumpT<X]}, JumpT = dummyJumpTime) assign(paste0("JumpTime.d",yuimaPPR@[email protected]@var.dx[i]), dummyJumpTimeNew ,envir=my.envd1) } } assign("namedX",namedX, envir = my.envd1) assign("namedJumpTimeX",namedJumpTimeX, envir = my.envd1) assign("var.time",yuimaPPR@[email protected]@var.time,envir=my.envd1) assign("t.time",yuimaPPR@[email protected]@upper.var,envir=my.envd1) #CountingVariable PosListCountingVariable <- NULL for(i in c(1:length(yuimaPPR@[email protected]))){ # cond <- yuimaPPR@[email protected] %in% yuimaPPR@[email protected][i] # dummyData <-unique(yuimaPPR@[email protected][,cond])[-1] # assign(yuimaPPR@[email protected][i], rep(1,length(dummyData)),envir=my.envd1) cond <- yuimaPPR@[email protected] %in% yuimaPPR@[email protected][i] #JUMPTIME <- tail(my.envd1$JumpTime.dN,1L)[[1]] JUMPTIME <- tail(my.envd1[[paste0("JumpTime.d",yuimaPPR@[email protected]@var.dx[i])]],1L)[[1]] condTime <- gridTime %in% JUMPTIME dummyData <- yuimaPPR@[email protected][condTime,cond] dummyDataA <- lapply(X=as.numeric(gridTime), FUN = function(X,JumpT,Jump){Jump[JumpT<X]}, JumpT = JUMPTIME, Jump = dummyData) dummyList <- paste0("List_",yuimaPPR@[email protected][i]) PosListCountingVariable <- c(PosListCountingVariable,dummyList) assign(dummyList, dummyDataA, envir=my.envd1) assign(yuimaPPR@[email protected][i], numeric(length=0L), envir=my.envd1) } assign("PosListCountingVariable", PosListCountingVariable, envir=my.envd1) # Covariates if(length(yuimaPPR@PPR@covariates)>0){ # Covariates should be identified at jump time PosListCovariates <- NULL for(i in c(1:length(yuimaPPR@PPR@covariates))){ # cond <- yuimaPPR@[email protected] %in% yuimaPPR@PPR@covariates[i] # condTime <- gridTime %in% my.envd1$JumpTime.dN # assign(yuimaPPR@PPR@covariates[i],yuimaPPR@[email protected][condTime,cond],envir = my.envd1) cond <- yuimaPPR@[email protected] %in% yuimaPPR@PPR@covariates[i] #dummyData <-yuimaPPR@[email protected][,cond] dummyData <- yuimaPPR@[email protected][condTime, cond] dummyDataB <- lapply(X=as.numeric(gridTime), FUN = function(X,JumpT,Jump){Jump[JumpT<X]}, JumpT = JUMPTIME, Jump = dummyData) dummyListCov <- paste0("List_",yuimaPPR@PPR@covariates[i]) PosListCovariates <- c(PosListCovariates,dummyListCov) assign(dummyListCov, dummyDataB,envir=my.envd1) assign(yuimaPPR@PPR@covariates[i], numeric(length=0L),envir=my.envd1) } assign("PosListCovariates", PosListCovariates,envir=my.envd1) } } # end coonstruction my.envd1 # construction my.envd2 if(ExistdX){ #Covariate #CountingVariable # for(i in c(1:length(yuimaPPR@[email protected]))){ # cond <- yuimaPPR@[email protected] %in% yuimaPPR@[email protected][i] # dummyData <-yuimaPPR@[email protected][,cond] # assign(yuimaPPR@[email protected][i], dummyData,envir=my.envd1) # } #Covariate dummyData<-NULL #CountingVariable for(i in c(1:length(yuimaPPR@[email protected]))){ cond <- yuimaPPR@[email protected] %in% yuimaPPR@[email protected][i] dummyData <-as.numeric(yuimaPPR@[email protected][,cond]) # assign(yuimaPPR@[email protected][i], dummyData[-length(dummyData)],envir=my.envd2) assign(yuimaPPR@[email protected][i], dummyData,envir=my.envd2) } namedX<-NULL namedJumpTimeX<-NULL for(i in c(1:length(yuimaPPR@[email protected]@var.dx))){ if(yuimaPPR@[email protected]@var.dx[i] %in% yuimaPPR@PPR@covariates){ cond <- yuimaPPR@[email protected] %in% yuimaPPR@[email protected]@var.dx[i] namedX<-c(namedX,paste0("d",yuimaPPR@[email protected]@var.dx[i])) namedJumpTimeX <-c(namedJumpTimeX,paste0("JumpTime.d",yuimaPPR@[email protected]@var.dx[i])) dummyData <- diff(as.numeric(yuimaPPR@[email protected][,cond]))# We consider only Jump #dummyJumpTime <- gridTime[-1][dummyData>0] #assign(paste0("d",yuimaPPR@[email protected]@var.dx[i]), dummyData ,envir=my.envd2) assign(paste0("d",yuimaPPR@[email protected]@var.dx[i]), c(0,dummyData) ,envir=my.envd2) #assign(paste0("JumpTime.d",yuimaPPR@[email protected]@var.dx[i]), gridTime[-1] ,envir=my.envd2) assign(paste0("JumpTime.d",yuimaPPR@[email protected]@var.dx[i]), as.numeric(gridTime) ,envir=my.envd2) } } assign("namedX",namedX, envir = my.envd2) assign("namedJumpTimeX",namedJumpTimeX, envir = my.envd2) assign("var.time",yuimaPPR@[email protected]@var.time,envir=my.envd2) assign("t.time",yuimaPPR@[email protected]@upper.var,envir=my.envd2) for(i in c(1:length(yuimaPPR@PPR@covariates))){ cond <- yuimaPPR@[email protected] %in% yuimaPPR@PPR@covariates[i] #dummyData <-yuimaPPR@[email protected][,cond] dummyData <-as.numeric(yuimaPPR@[email protected][, cond]) #assign(yuimaPPR@PPR@covariates[i], dummyData[-length(dummyData)],envir=my.envd2) assign(yuimaPPR@PPR@covariates[i], dummyData,envir=my.envd2) } }else{ assign("KerneldX",NULL,envir=my.envd2) } # end construction my.envd2 # construction my.envd3 #Covariate dimCov<-length(yuimaPPR@PPR@covariates) if(dimCov>0){ for(i in c(1:dimCov)){ cond <- yuimaPPR@[email protected] %in% yuimaPPR@PPR@covariates[i] dummyData <- yuimaPPR@[email protected][,cond] assign(yuimaPPR@PPR@covariates[i], dummyData,envir=my.envd3) } } #CountingVariable for(i in c(1:length(yuimaPPR@[email protected]))){ cond <- yuimaPPR@[email protected] %in% yuimaPPR@[email protected][i] dummyData <-cumsum(c(as.numeric(yuimaPPR@[email protected][1,cond]!=0),as.numeric(diff(yuimaPPR@[email protected][,cond])!=0))) assign(yuimaPPR@[email protected][i], dummyData,envir=my.envd3) } #time assign(yuimaPPR@[email protected], gridTime, my.envd3) #Model assign("YUIMA.PPR",yuimaPPR,envir=my.envd3) assign("namesparam",namesparam,envir=my.envd3) assign("gfun",gfun,envir=my.envd3) assign("Integrand2",Integrand2,envir=my.envd3) assign("Integrand2expr",Integrand2expr,envir=my.envd3) # assign("gridTime",as.numeric(gridTime),envir=my.envd3) l1 =as.list(as.numeric(gridTime)) l2 = as.list(c(1:length(l1))) l3 = mapply(c, l1, l2, SIMPLIFY=FALSE) assign("gridTime",l3,envir=my.envd3) assign("Univariate",Univariate,envir=my.envd3) assign("ExistdN",ExistdN,envir=my.envd3) assign("ExistdX",ExistdX,envir=my.envd3) assign("JumpTimeLogical",c(FALSE,as.integer(diff(my.envd3$N))!=0),envir=my.envd3) assign("CondIntensityInKern", my.envd3$YUIMA.PPR@[email protected] %in% all.vars(my.envd3$Integrand2expr), envir=my.envd3) out<-NULL # quasilogl(dummyMod1,param = param[dummyMod1@model@parameter@all]) # commonPar if(length(lower)==0 && length(upper)>0 && length(fixed)==0){ if(commonPar){ out <- optim(par=param, fn=Internal.LogLikPPR, my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, method = method, upper = upper, commonPar=commonPar, auxModel = dummyMod1) # return(out) }else{ out <- optim(par=param, fn=Internal.LogLikPPR, my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, method = method, upper=upper, ...) } } if(length(lower)==0 && length(upper)==0 && length(fixed)>0){ if(commonPar){ out <- optim(par=param, fn=Internal.LogLikPPR, my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, method = method, fixed = fixed, commonPar=commonPar, auxModel = dummyMod1) # return(out) }else{ out <- optim(par=param, fn=Internal.LogLikPPR, my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, method = method, fixed = fixed, ...) } } if(length(lower)>0 && length(upper)==0 && length(fixed)==0){ if(commonPar){ out <- optim(par=param, fn=Internal.LogLikPPR, my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, method = method, lower = lower, commonPar=commonPar, auxModel = dummyMod1) # return(out) }else{ out <- optim(par = param, fn=Internal.LogLikPPR, my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, method = method, lower=lower, ...) } } if(length(lower)>0 && length(upper)>0 && length(fixed)==0){ if(commonPar){ out <- optim(par=param, fn=Internal.LogLikPPR, my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, method = method, lower = lower, upper = upper, commonPar=commonPar, auxModel = dummyMod1) # return(out) }else{ out <- optim(par=param, fn=Internal.LogLikPPR, my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, method = method, upper = upper, lower=lower, ...) } } if(length(lower)==0 && length(upper)>0 && length(fixed)>0){ if(commonPar){ out <- optim(par=param, fn=Internal.LogLikPPR, my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, method = method, upper = upper, fixed = fixed, commonPar=commonPar, auxModel = dummyMod1) # return(out) }else{ out <- optim(par=param, fn=Internal.LogLikPPR, my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, method = method, upper = upper, fixed = fixed, ...) } } if(length(lower)>0 && length(upper)==0 && length(fixed)>0){ if(commonPar){ out <- optim(par=param, fn=Internal.LogLikPPR, my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, method = method, lower = lower, fixed = fixed, commonPar=commonPar, auxModel = dummyMod1) # return(out) }else{ out <- optim(par=param, fn=Internal.LogLikPPR, my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, method = method, lower = lower, fixed = fixed, ...) } } if(length(lower)>0 && length(upper)>0 && length(fixed)>0){ if(commonPar){ out <- optim(par=param, fn=Internal.LogLikPPR, my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, method = method, lower = lower, fixed = fixed, upper = upper, commonPar=commonPar, auxModel = dummyMod1) # return(out) }else{ out <- optim(par=param, fn=Internal.LogLikPPR, my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, method = method, lower = lower, fixed = fixed, upper = upper, ...) } } if(is.null(out)){ if(commonPar){ out <- optim(par=param, fn=Internal.LogLikPPR, my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, method = method, commonPar=commonPar, auxModel = dummyMod1) # return(out) }else{ out <- optim(par=param, fn=Internal.LogLikPPR, my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, method = method, ...) } } if(commonPar){ Hessian <- tryCatch(optimHess(as.list(out$par), fn=Internal.LogLikPPR, my.envd1=my.envd1, my.envd2=my.envd2, my.envd3=my.envd3, commonPar=commonPar, auxModel = dummyMod1), error=function(){NULL}) if(is.null(Hessian)){ vcov <- matrix(NA,length(out$par), length(out$par)) }else{ vcov <- solve(Hessian) } minuslog <- out$value final_res<-new("yuima.PPR.qmle", call = call, coef = out$par, fullcoef = out$par, vcov = vcov, min = minuslog, details = out, minuslogl = Internal.LogLikPPR, method = method, nobs=integer(), model=my.envd3$YUIMA.PPR) return(final_res) } Hessian <- tryCatch(optimHess(as.list(out$par), fn=Internal.LogLikPPR, my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3), error=function(){NULL}) if(!is.null(Hessian)){ Hessian <- Hessian[yuimaPPR@PPR@allparamPPR,yuimaPPR@PPR@allparamPPR] } cond1 <- my.envd3$YUIMA.PPR@[email protected] %in% my.envd3$YUIMA.PPR@[email protected] cond2 <- diff(as.numeric(my.envd3$YUIMA.PPR@[email protected][,cond1])) N.jump <- sum(cond2,na.rm=TRUE) if(is.null(Hessian)){ vcov <- matrix(NA,length(out$par[yuimaPPR@PPR@allparamPPR]), length(out$par[yuimaPPR@PPR@allparamPPR])) }else{ vcov <- solve(Hessian)/N.jump } minuslog <- out$value*N.jump final_res<-new("yuima.PPR.qmle", call = call, coef = out$par[yuimaPPR@PPR@allparamPPR], fullcoef = out$par[yuimaPPR@PPR@allparamPPR], vcov = vcov, min = minuslog, details = out, minuslogl = Internal.LogLikPPR, method = method, nobs=as.integer(N.jump), model=my.envd3$YUIMA.PPR) if(!is.null(resCov)){ return(list(PPR=final_res,Covariates=resCov)) } if(!NoFeedBackIntensity){ if(all(yuimaPPR@[email protected] %in% yuimaPPR@[email protected])){ myMod <- yuimaPPR@model myYuima <- setYuima(data = yuimaPPR@data, model = yuimaPPR@model, sampling = yuimaPPR@sampling) resCov <- qmleLevy(yuima = myYuima, start=param[myMod@parameter@all],upper=upper[myMod@parameter@all], lower=lower[myMod@parameter@all]) }else{ if(all(yuimaPPR@[email protected] %in% yuimaPPR@[email protected])){ OrigData <- yuimaPPR@[email protected] IntensityData <- Intensity.PPR(final_res@model, param=coef(final_res)) mylambda <- [email protected] NewData0 <- cbind(OrigData,mylambda) colnames(NewData0) <- yuimaPPR@[email protected] NewData<-setData(zoo(NewData0, order.by = index([email protected][[1]]))) }else{ NewData <- yuimaPPR@data } lengthOrigVar <- length(yuimaPPR@[email protected]) if(length(yuimaPPR@[email protected])>lengthOrigVar){ lengthVar <- length(yuimaPPR@[email protected]) }else{ lengthVar<-lengthOrigVar } DummyDrift <- as.character(rep(0,lengthVar)) DummyDrift[1:lengthOrigVar] <- as.character(yuimaPPR@model@drift) dummydiff0<- NULL for(j in c(1:lengthOrigVar)){ dummydiff0<-c(dummydiff0, as.character(unlist(yuimaPPR@model@diffusion[[j]]))) } dummydiff <- matrix(dummydiff0, nrow = lengthOrigVar, ncol = length(dummydiff0)/lengthOrigVar) if(length(yuimaPPR@[email protected])!=0){ if(lengthVar-lengthOrigVar>0){ dummydiff <- rbind(dummydiff,matrix("0", nrow = lengthVar-lengthOrigVar,dim(dummydiff)[2])) } } dummyJump0 <- NULL for(j in c(1:lengthOrigVar)){ dummyJump0 <- c(dummyJump0, as.character(unlist(yuimaPPR@[email protected][[j]][]))) } dummyJump <- matrix(dummyJump0, nrow=lengthOrigVar,ncol=length(dummyJump0)/lengthOrigVar, byrow = T) if(length(yuimaPPR@[email protected])!=0){ dummyJump1<- matrix(as.character(diag(lengthVar)),lengthVar,lengthVar) dummyJump1[1:lengthOrigVar,1:lengthOrigVar] <- dummyJump } # aaa<-setModel(drift="1",diffusion = "1") # [email protected] # yuimaPPR@[email protected] meas.type <- rep("code",lengthVar) myMod <- setModel(drift = DummyDrift, diffusion = dummydiff, jump.coeff = dummyJump1, jump.variable = yuimaPPR@[email protected], measure = list(df=yuimaPPR@model@measure$df), measure.type = meas.type, solve.variable = yuimaPPR@[email protected], #solve.variable = yuimaPPR@[email protected], state.variable = yuimaPPR@[email protected]) myYuima <- setYuima(data = NewData, model = myMod) myYuima@sampling <- yuimaPPR@sampling resCov <- qmleLevy(yuima = myYuima, start=param[myMod@parameter@all],upper=upper[myMod@parameter@all], lower=lower[myMod@parameter@all]) } return(list(PPR=final_res,Covariates=resCov)) } return(final_res) } # quasiLogLik.PPR <- function(yuimaPPR, parLambda=list(), method=method, fixed = list(), # lower, upper, call, ...){ # # yuimaPPR->yuimaPPR # parLambda->param # gfun<-yuimaPPR@gFun@formula # # dimIntegr <- length(yuimaPPR@Kernel@Integrand@IntegrandList) # Integrand2 <- character(length=dimIntegr) # for(i in c(1:dimIntegr)){ # Integrand1 <- as.character(yuimaPPR@Kernel@Integrand@IntegrandList[[i]]) # timeCond <- paste0(" * (",yuimaPPR@[email protected]@var.time," < ",yuimaPPR@[email protected]@upper.var,")") # Integrand2[i] <-paste0(Integrand1,timeCond) # } # # Integrand2<- matrix(Integrand2,yuimaPPR@Kernel@Integrand@dimIntegrand[1],yuimaPPR@Kernel@Integrand@dimIntegrand[2]) # # # for(j in c(1:yuimaPPR@Kernel@Integrand@dimIntegrand[2])){ # Integrand2[,j]<-paste0(Integrand2[,j]," * d",yuimaPPR@[email protected]@var.dx[j]) # } # colnames(Integrand2) <- paste0("d",yuimaPPR@[email protected]@var.dx) # NamesIntegrandExpr <- as.character(matrix(colnames(Integrand2), dim(Integrand2)[1],dim(Integrand2)[2], byrow = TRUE)) # Integrand2expr<- parse(text=Integrand2) # # gridTime <- time(yuimaPPR@[email protected]) # # yuimaPPR@[email protected]@var.dx # if(any(yuimaPPR@[email protected]@var.dx %in% yuimaPPR@[email protected])){ # my.envd1<-new.env() # ExistdN<-TRUE # }else{ # ExistdN<-FALSE # } # Univariate<-FALSE # if(length(yuimaPPR@[email protected])==1){ # Univariate<-TRUE # } # if(any(!(yuimaPPR@[email protected]@var.dx %in% yuimaPPR@[email protected]))){ # my.envd2<-new.env() # ExistdX<-TRUE # }else{ # my.envd2<-new.env() # ExistdX<-FALSE # } # # my.envd3 <- new.env() # namesparam<-names(param) # if(!(all(namesparam %in% yuimaPPR@PPR@allparamPPR) && length(namesparam)==length(yuimaPPR@PPR@allparamPPR))){ # return(NULL) # } # # # construction my.envd1 # if(ExistdN){ # # #CountingVariable # for(i in c(1:length(yuimaPPR@[email protected]))){ # cond <- yuimaPPR@[email protected][i] %in% yuimaPPR@[email protected] # dummyData <-unique(yuimaPPR@[email protected][,cond])[-1] # assign(yuimaPPR@[email protected][i], dummyData,envir=my.envd1) # } # # Names expression # assign("NamesIntgra", NamesIntegrandExpr, envir=my.envd1) # #dN # namedX <-NULL # for(i in c(1:length(yuimaPPR@[email protected]@var.dx))){ # if(yuimaPPR@[email protected]@var.dx[i] %in% yuimaPPR@[email protected]){ # cond <- yuimaPPR@[email protected] %in% yuimaPPR@[email protected]@var.dx[i] # namedX<-c(namedX,paste0("d",yuimaPPR@[email protected]@var.dx[i])) # dummyData <- diff(as.numeric(yuimaPPR@[email protected][,cond]))# We consider only Jump # dummyJumpTime <- gridTime[-1][dummyData>0] # dummyData2 <- diff(unique(cumsum(dummyData))) # dummyData3 <- zoo(dummyData2,order.by = dummyJumpTime) # assign(paste0("d",yuimaPPR@[email protected]@var.dx[i]), dummyData3 ,envir=my.envd1) # } # } # assign("namedX",namedX, envir = my.envd1) # assign("var.time",yuimaPPR@[email protected]@var.time,envir=my.envd1) # assign("t.time",yuimaPPR@[email protected]@upper.var,envir=my.envd1) # # # Covariates # if(length(yuimaPPR@PPR@covariates)>1){ # # Covariates should be identified at jump time # return(NULL) # } # # } # # end coonstruction my.envd1 # # # construction my.envd2 # if(ExistdX){ # #Covariate # # #CountingVariable # for(i in c(1:length(yuimaPPR@[email protected]))){ # cond <- yuimaPPR@[email protected][i] %in% yuimaPPR@[email protected] # dummyData <-yuimaPPR@[email protected][,cond] # assign(yuimaPPR@[email protected][i], dummyData,envir=my.envd1) # } # # # }else{ # assign("KerneldX",NULL,envir=my.envd2) # } # # # end construction my.envd2 # # # construction my.envd3 # # #Covariate # # #CountingVariable # for(i in c(1:length(yuimaPPR@[email protected]))){ # cond <- yuimaPPR@[email protected][i] %in% yuimaPPR@[email protected] # dummyData <-yuimaPPR@[email protected][,cond] # assign(yuimaPPR@[email protected][i], dummyData,envir=my.envd3) # } # #time # assign(yuimaPPR@[email protected], gridTime, my.envd3) # # #Model # assign("YUIMA.PPR",yuimaPPR,envir=my.envd3) # assign("namesparam",namesparam,envir=my.envd3) # assign("gfun",gfun,envir=my.envd3) # assign("Integrand2",Integrand2,envir=my.envd3) # assign("Integrand2expr",Integrand2expr,envir=my.envd3) # # assign("gridTime",gridTime,envir=my.envd3) # assign("Univariate",Univariate,envir=my.envd3) # assign("ExistdN",ExistdN,envir=my.envd3) # assign("ExistdX",ExistdX,envir=my.envd3) # out<-NULL # # if(length(lower)==0 && length(upper)>0 && length(fixed)==0){ # out <- optim(par=param, fn=Internal.LogLikPPR, # my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, # method = method, upper=upper, ...) # # } # # if(length(lower)==0 && length(upper)==0 && length(fixed)>0){ # out <- optim(par=param, fn=Internal.LogLikPPR, # my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, # method = method, fixed = fixed, ...) # # } # # # if(length(lower)>0 && length(upper)==0 && length(fixed)==0){ # out <- optim(par = param, fn=Internal.LogLikPPR, # my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, # method = method, lower=lower, ...) # } # # if(length(lower)>0 && length(upper)>0 && length(fixed)==0){ # out <- optim(par=param, fn=Internal.LogLikPPR, # my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, # method = method, upper = upper, # lower=lower, ...) # } # # # if(length(lower)==0 && length(upper)>0 && length(fixed)>0){ # out <- optim(par=param, fn=Internal.LogLikPPR, # my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, # method = method, upper = upper, # fixed = fixed, ...) # } # # if(length(lower)>0 && length(upper)==0 && length(fixed)>0){ # out <- optim(par=param, fn=Internal.LogLikPPR, # my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, # method = method, lower = lower, # fixed = fixed, ...) # } # # # if(length(lower)>0 && length(upper)>0 && length(fixed)>0){ # out <- optim(par=param, fn=Internal.LogLikPPR, # my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, # method = method, lower = lower, fixed = fixed, upper = upper, ...) # } # # # if(is.null(out)){ # out <- optim(par=param, fn=Internal.LogLikPPR, # my.envd1=my.envd1,my.envd2=my.envd2,my.envd3=my.envd3, # method = method, ...) # } # # # return(out) # # } lambdaFromData <- function(yuimaPPR, PPRData=NULL, parLambda=list()){ if(is.null(PPRData)){ PPRData<-yuimaPPR@data }else{ # checklambdaFromData(yuimaPPR,PPRData) } if(!any(names(parLambda) %in% yuimaPPR@PPR@allparamPPR)){yuima.stop("1 ...")} if(!any(yuimaPPR@PPR@allparamPPR %in% names(parLambda))){yuima.stop("2 ...")} Time <- index(yuimaPPR@[email protected][[1]]) envPPR <- list() dY <- paste0("d",yuimaPPR@[email protected]) for(i in (c(1:(length(Time)-1)))){ envPPR[[i]]<-new.env() assign(yuimaPPR@gFun@[email protected],rep(Time[i+1],i),envir=envPPR[[i]]) assign(yuimaPPR@[email protected],Time[1:i],envir=envPPR[[i]]) if(length(yuimaPPR@PPR@covariates)>0){ for(j in c(1:length(yuimaPPR@PPR@covariates))){ cond<-colnames(yuimaPPR@[email protected])%in%yuimaPPR@PPR@covariates[[j]] assign(yuimaPPR@PPR@covariates[[j]], as.numeric(yuimaPPR@[email protected][1:(i+1),cond]), envir=envPPR[[i]]) } } for(j in c(1:length(yuimaPPR@[email protected]))){ cond<-colnames(yuimaPPR@[email protected])%in%yuimaPPR@[email protected][[j]] assign(yuimaPPR@[email protected][[j]], as.numeric(yuimaPPR@[email protected][1:(i+1),cond]), envir=envPPR[[i]]) } for(j in c(1:length(yuimaPPR@[email protected]))){ cond<-c(colnames(yuimaPPR@[email protected]),yuimaPPR@[email protected])%in%c(yuimaPPR@[email protected],yuimaPPR@[email protected])[[j]] if(any(cond[-length(cond)])){ assign(paste0("d",yuimaPPR@[email protected][[j]]), diff(as.numeric(yuimaPPR@[email protected][1:(i+1),cond[-length(cond)]])), envir=envPPR[[i]]) } if(tail(cond,n=1L)){ assign(paste0("d",yuimaPPR@[email protected][[j]]), as.numeric(diff(Time[1:(i+1),cond[-length(cond)]])), envir=envPPR[[i]]) } } } IntKernExpr<- function(Kern,dy){ dum<-paste(Kern,dy,sep="*") dum<-paste0(dum, collapse = " + ") dum <- paste0("sum( ", dum, " )") return(parse(text = dum)) } IntegKern <- lapply(yuimaPPR@Kernel@Integrand@IntegrandList,IntKernExpr,dY) Integrator <- t(as.matrix(eval(parse(text=dY[1]),envir=envPPR[[length(envPPR)]]))) if(length(dY)>1){ for(i in c(2:length(dY))){ Integrator <- rbind(Integrator, t(as.matrix(eval(parse(text=dY[1]),envir=envPPR[[length(envPPR)]])))) } } assign("Integrator",Integrator,envir=envPPR[[length(envPPR)]]) assign("Nlamb",length(yuimaPPR@[email protected]),envir=envPPR[[length(envPPR)]]) res<-aux.lambdaFromData(param = unlist(parLambda), gFun=yuimaPPR@gFun, Kern =IntegKern, intensityParm = yuimaPPR@PPR@allparamPPR, envPPR) return(res) } # my.lapply <- function (X, FUN, ...){ # # FUN <- match.fun(FUN) # .Internal(lapply(X, FUN)) # } myfun3<-function(X,Kern){ t(simplify2array(lapply(Kern, FUN=DumFun, Y = X), higher = (TRUE == "array")))} dumFun2<-function(X,Y){list2env(Y,envir=X)} aux.lambdaFromData <-function(param, gFun, Kern, intensityParm, envPPR,logLikelihood = FALSE){ lapply(envPPR,FUN=dumFun2,Y=as.list(param)) lastEnv <- tail(envPPR,n=1L)[[1]] # gFunVect<- t(simplify2array(my.lapply(gFun@formula, FUN=DumFun, # Y = lastEnv), higher = (TRUE == "array"))) gFunVect<- matrix(unlist(lapply(gFun@formula, FUN=DumFun, Y = lastEnv)),nrow=lastEnv$Nlamb,byrow=TRUE) # IntKer<- simplify2array(my.lapply(envPPR,function(my.env){ # t(simplify2array(my.lapply(Kern, FUN=DumFun, # Y = my.env), higher = (TRUE == "array")))}), # higher = (TRUE == "array") # ) # IntKer<- simplify2array(my.lapply(envPPR,myfun3,Kern=Kern), # higher = (TRUE == "array") # ) # IntKer<- matrix(unlist(my.lapply(envPPR,myfun3,Kern=Kern)), # nrow=1,byrow=TRUE) IntKer<- matrix(unlist(lapply(envPPR,myfun3,Kern=Kern)), nrow=lastEnv$Nlamb) # lambda <- gFunVect+cbind(0,IntKer) lambda <- gFunVect+IntKer time <- (c(lastEnv$s,lastEnv$t[1])) if(!logLikelihood){ Intensity <- zoo(t(lambda), order.by = time) return(Intensity) } dn <- dim(lambda) if(dn[1]==1){ #logLiklihood2 <- -sum(lambda*diff(time)[1]) logLiklihood2 <- -1/2*sum((lambda[1:(length(lambda)-1)]+lambda[2:(length(lambda))])*diff(time)[1]) logLiklihood1 <- sum(log(lambda)*lastEnv$CountVar) # logLiklihood2 <- -sum(lambda*diff(time)) # dummyLamb <- lambda[lastEnv$CountVar] # #logLiklihood1 <- sum(log(dummyLamb[-length(dummyLamb)])) # logLiklihood1 <- sum(log(dummyLamb)) # newlamb <- unique(as.numeric(lambda)) # # cond <- as.numeric(lastEnv$CountVar)!=0 # timeJ <- time[-1][cond] # timeJ1 <- unique(c(0,timeJ,lastEnv$t[1])) # logLiklihood2 <- -sum(newlamb*diff(timeJ1)) # InternCount<-c(0:length(timeJ)) # if((length(timeJ)+2)==length(timeJ1)){ # InternCount <- c(InternCount,tail(InternCount, n=1L)) # } # # logLiklihood1 <- sum(log(newlamb)*diff(InternCount)) }else{ #### NO Rewrite # logLiklihood2 <- -rowSums(lambda[,-1]*diff(time)[1]) # logLiklihood1 <- rowSums(log(lambda[,-1])*lastEnv$Integrator) logLiklihood2 <- -rowSums(lambda*diff(time)[1]) #cond <- t(apply(as.matrix(lastEnv$CountVar),FUN = "diff",MARGIN = 2))!=0 logLiklihood1 <- rowSums(log(lambda)*lastEnv$CountVar) } if(is.nan(logLiklihood1)){ logLiklihood1 <- -10^10 } if(is.nan(logLiklihood2)){ logLiklihood2 <- -10^10 } minusLoglik <- -sum(logLiklihood2+logLiklihood1) # cat(sprintf("\n%.5f",minusLoglik)) # cat(sprintf("\n%.5f",param)) return(minusLoglik) } DumFun<- function(X,Y){eval(X,envir=Y)}
/scratch/gouwar.j/cran-all/cranData/yuima/R/AuxMethodforPPR.R
qmleL <- function(yuima, t, ...){ call <- match.call() times <- time(yuima@[email protected][[1]]) minT <- as.numeric(times[1]) maxT <- as.numeric(times[length(times)]) if(missing(t) ) t <- mean(c(minT,maxT)) if(t<minT || t>maxT) yuima.stop("time 't' out of bounds") grid <- times[which(times<=t)] tmp <- subsampling(yuima, grid=grid) mydots <- as.list(call)[-1] mydots$t <- NULL mydots$yuima <- tmp tmp <- do.call("qmle", args=mydots) tmp } qmleR <- function (yuima, t, ...) { call <- match.call() times <- time(yuima@[email protected][[1]]) minT <- as.numeric(times[1]) maxT <- as.numeric(times[length(times)]) if (missing(t)) t <- mean(c(minT, maxT)) if (t < minT || t > maxT) yuima.stop("time 't' out of bounds") grid <- times[which(times >= t)] tmp <- subsampling(yuima, grid = grid) mydots <- as.list(call)[-1] mydots$t <- NULL mydots$yuima <- tmp tmp <- do.call("qmle", args=mydots) tmp } CPointOld <- function(yuima, param1, param2, print=FALSE, plot=FALSE){ d.size <- yuima@[email protected] n <- length(yuima)[1] d.size <- yuima@[email protected] env <- new.env() assign("X", as.matrix(onezoo(yuima)), envir=env) assign("deltaX", matrix(0, n-1, d.size), envir=env) for(t in 1:(n-1)) env$deltaX[t,] <- env$X[t+1,] - env$X[t,] assign("h", deltat(yuima@[email protected][[1]]), envir=env) assign("time", as.numeric(index(yuima@[email protected][[1]])), envir=env) QL1 <- pminusquasilogl(yuima=yuima, param=param1, print=print, env) QL2 <- pminusquasilogl(yuima=yuima, param=param2, print=print, env) D <- sapply(2:(n-1), function(x) sum(QL1[1:x]) + sum(QL2[-(1:x)])) D <- c(D[1], D, D[length(D)]) D <- ts(D, start=0, deltat=deltat(yuima@[email protected][[1]])) if(plot) plot(D,type="l", main="change point statistic") tau.hat <- index(yuima@[email protected][[1]])[which.min(D)] return(list(tau=tau.hat, param1=param1, param2=param2)) } # partial quasi-likelihood # returns a vector of conditionational minus-log-likelihood terms # the whole negative log likelihood is the sum pminusquasilogl <- function(yuima, param, print=FALSE, env){ diff.par <- yuima@model@parameter@diffusion fullcoef <- diff.par npar <- length(fullcoef) nm <- names(param) oo <- match(nm, fullcoef) if(any(is.na(oo))) oo <- oo[-which(is.na(oo))] if(any(is.na(oo))) yuima.stop("some named arguments in 'param' are not arguments to the supplied yuima model") param <- param[order(oo)] nm <- names(param) idx.diff <- match(diff.par, nm) h <- env$h theta1 <- unlist(param[idx.diff]) n.theta1 <- length(theta1) n.theta <- n.theta1 d.size <- yuima@[email protected] #n <- length(yuima)[1] n <- dim(env$X)[1] vec <- env$deltaX K <- -0.5*d.size * log( (2*pi*h) ) QL <- 0 pn <- numeric(n-1) diff <- diffusion.term(yuima, param, env) dimB <- dim(diff[, , 1]) if(is.null(dimB)){ # one dimensional X for(t in 1:(n-1)){ yB <- diff[, , t]^2 logdet <- log(yB) pn[t] <- K - 0.5*logdet-0.5*vec[t, ]^2/(h*yB) QL <- QL+pn[t] } } else { # multidimensional X for(t in 1:(n-1)){ yB <- diff[, , t] %*% t(diff[, , t]) logdet <- log(det(yB)) if(is.infinite(logdet) ){ # should we return 1e10? pn[t] <- log(1) yuima.warn("singular diffusion matrix") return(1e10) }else{ pn[t] <- K - 0.5*logdet + ((-1/(2*h))*t(vec[t, ])%*%solve(yB)%*%vec[t, ]) QL <- QL+pn[t] } } } if(!is.finite(QL)){ yuima.warn("quasi likelihood is too small to calculate.") QL <- 1e10 } if(print==TRUE){ yuima.warn(sprintf("NEG-QL: %f, %s", -QL, paste(names(param),param,sep="=",collapse=", "))) } return(-pn) } pminusquasiloglL <- function(yuima, param, print=FALSE, env){ diff.par <- yuima@model@parameter@diffusion fullcoef <- diff.par npar <- length(fullcoef) nm <- names(param) oo <- match(nm, fullcoef) if(any(is.na(oo))) yuima.stop("some named arguments in 'param' are not arguments to the supplied yuima model") param <- param[order(oo)] nm <- names(param) idx.diff <- match(diff.par, nm) h <- env$h theta1 <- unlist(param[idx.diff]) n.theta1 <- length(theta1) n.theta <- n.theta1 d.size <- yuima@[email protected] n <- length(yuima)[1] vec <- env$deltaX K <- -0.5*d.size * log( (2*pi*h) ) QL <- 0 pn <- numeric(n-1) diff <- diffusion.term(yuima, param, env) dimB <- dim(diff[, , 1]) if(is.null(dimB)){ # one dimensional X for(t in 1:(n-1)){ yB <- diff[, , t]^2 logdet <- log(yB) pn[t] <- K - 0.5*logdet-0.5*vec[t, ]^2/(h*yB) QL <- QL+pn[t] } } else { # multidimensional X for(t in 1:(n-1)){ yB <- diff[, , t] %*% t(diff[, , t]) logdet <- log(det(yB)) if(is.infinite(logdet) ){ # should we return 1e10? pn[t] <- log(1) yuima.warn("singular diffusion matrix") return(1e10) }else{ pn[t] <- K - 0.5*logdet + ((-1/(2*h))*t(vec[t, ])%*%solve(yB)%*%vec[t, ]) QL <- QL+pn[t] } } } if(!is.finite(QL)){ yuima.warn("quasi likelihood is too small to calculate.") QL <- 1e10 } if(print==TRUE){ yuima.warn(sprintf("NEG-QL: %f, %s", -QL, paste(names(param),param,sep="=",collapse=", "))) } return(-pn) } # symmetrized version pminusquasiloglsym <- function(yuima, param, print=FALSE, env){ diff.par <- yuima@model@parameter@diffusion fullcoef <- diff.par npar <- length(fullcoef) nm <- names(param) oo <- match(nm, fullcoef) if(any(is.na(oo))) yuima.stop("some named arguments in 'param' are not arguments to the supplied yuima model") param <- param[order(oo)] nm <- names(param) idx.diff <- match(diff.par, nm) h <- env$h theta1 <- unlist(param[idx.diff]) n.theta1 <- length(theta1) n.theta <- n.theta1 d.size <- yuima@[email protected] n <- dim(env$X)[1]-1 idx0 <- 1:round((n-1)/2) vec <- matrix((env$X[2*idx0+1]-2* env$X[2*idx0]+env$X[2*idx0-1])/sqrt(2), length(idx0), dim(env$X)[2]) K <- -0.5*d.size * log( (2*pi*h) ) QL <- 0 pn <- numeric(length(idx0)) diff <- diffusion.term(yuima, param, env) dimB <- dim(diff[, , 1]) if(is.null(dimB)){ # one dimensional X for(t in idx0){ yB <- diff[, , 2*t-1]^2 logdet <- log(yB) pn[t] <- K - 0.5*logdet-0.5*vec[t, ]^2/(h*yB) QL <- QL+pn[t] } } else { # multidimensional X for(t in idx0[-length(idx0)]){ yB <- diff[, , 2*t-1] %*% t(diff[, , 2*t-1]) logdet <- log(det(yB)) if(is.infinite(logdet) ){ # should we return 1e10? pn[t] <- log(1) yuima.warn("singular diffusion matrix") return(1e10) }else{ pn[t] <- K - 0.5*logdet + ((-1/(2*h))*t(vec[t, ])%*%solve(yB)%*%vec[t, ]) QL <- QL+pn[t] } } } if(!is.finite(QL)){ yuima.warn("quasi likelihood is too small to calculate.") QL <- 1e10 } if(print==TRUE){ yuima.warn(sprintf("NEG-QL: %f, %s", -QL, paste(names(param),param,sep="=",collapse=", "))) } return(-pn) } CPoint <- function(yuima, param1, param2, print=FALSE, symmetrized=FALSE, plot=FALSE){ d.size <- yuima@[email protected] n <- length(yuima)[1] d.size <- yuima@[email protected] env <- new.env() assign("X", as.matrix(onezoo(yuima)), envir=env) assign("deltaX", matrix(0, n-1, d.size), envir=env) for(t in 1:(n-1)) env$deltaX[t,] <- env$X[t+1,] - env$X[t,] assign("h", deltat(yuima@[email protected][[1]]), envir=env) assign("time", as.numeric(index(yuima@[email protected][[1]])), envir=env) QL1 <- NULL QL2 <- NULL if(!symmetrized){ QL1 <- pminusquasilogl(yuima=yuima, param=param1, print=print, env) QL2 <- pminusquasilogl(yuima=yuima, param=param2, print=print, env) } else { QL1 <- pminusquasiloglsym(yuima=yuima, param=param1, print=print, env) QL2 <- pminusquasiloglsym(yuima=yuima, param=param2, print=print, env) } nn <- length(QL1) D <- sapply(2:(nn-1), function(x) sum(QL1[1:x]) + sum(QL2[-(1:x)])) D <- c(D[1], D, D[length(D)]) if(symmetrized) D <- ts(D, start=0, deltat=2*deltat(yuima@[email protected][[1]])) else D <- ts(D, start=0, deltat=deltat(yuima@[email protected][[1]])) if(plot) plot(D,type="l", main="change point statistic") # tau.hat <- index(yuima@[email protected][[1]])[which.min(D)] tau.hat <- index(D)[which.min(D)] return(list(tau=tau.hat, param1=param1, param2=param2)) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/CPoint.R
# In this file we develop the procedure described in Brockwell, Davis and Yang (2012) # for estimation of the underlying noise once the parameters of carma(p,q) are previously # obtained yuima.eigen2arparam<-function(lambda){ MatrixLamb<-diag(lambda) matrixR<-matrix(NA,length(lambda),length(lambda)) for(i in c(1:length(lambda))){ matrixR[,i]<-lambda[i]^c(0:(length(lambda)-1)) } AMatrix<-matrixR%*%MatrixLamb%*%solve(matrixR) acoeff<-AMatrix[length(lambda),] } yuima.carma.eigen<-function(A){ diagA<-eigen(A) diagA$values<-diagA$values[order(diagA$values, na.last = TRUE, decreasing = TRUE)] n_eigenval<-length(diagA$values) diagA$vectors<-matrix(diagA$values[1]^(c(1:n_eigenval)-1),n_eigenval,1) if(n_eigenval>=2){ for (i in 2:n_eigenval){ diagA$vectors<-cbind(diagA$vectors, matrix(diagA$values[i]^(c(1:n_eigenval)-1),n_eigenval,1)) } } return(diagA) } StateVarX<-function(y,tt,X_0,B,discr.eul){ # The code obtains the first q-1 state variable using eq 5.1 in Brockwell, Davis and Yang 2011 Time<-length(tt) q<-length(X_0) e_q<-rep(0,q) e_q[q]<-1 X_0<-matrix(X_0,q,1) e_q<-matrix(e_q,q,1) X<-matrix(0,q,Time) int<-matrix(0,q,1) for (i in c(3:Time)){ if(discr.eul==FALSE){ int<-int+(expm(B*(tt[i]-tt[(i-1)]))%*%(e_q*y[i-1]))*(tt[i]-tt[(i-1)]) X[,i]<-as.matrix(expm(B*tt[i])%*%X_0+int) }else{ X[,i]<-X[,i-1]+(B%*%X[,i-1])*(tt[i]-tt[(i-1)])+(e_q*y[i-1])*(tt[i]-tt[(i-1)]) } } return(X) } # StateVarXp<-function(y,X_q,tt,B,q,p){ # # The code computes the state variable X using the derivatives of eq 5.2 # # see Brockwell, Davis and Yang 2011 # # diagMatB<-yuima.carma.eigen(B) # if(length(diagMatB$values)>1){ # MatrD<-diag(diagMatB$values) # }else{ # MatrD<-as.matrix(diagMatB$values) # } # MatrR<-diagMatB$vectors # idx.r<-c(q:(p-1)) # elem.X <-length(idx.r) # YMatr<-matrix(0,q,length(y)) # YMatr[q,]<-y # OutherX<-matrix(NA,elem.X,length(y)) # # OutherXalt<-matrix(NA,q,length(y)) # for(i in 1:elem.X){ # OutherX[i,]<-((MatrR%*%MatrD^(idx.r[i])%*%solve(MatrR))%*%X_q+ # (MatrR%*%MatrD^(idx.r[i]-1)%*%solve(MatrR))%*%YMatr)[1,] # } # X.StatVar<-rbind(X_q,OutherX) # return(X.StatVar) # } StateVarXp<-function(y,X_q,tt,B,q,p,nume.Der){ # The code computes the state variable X using the derivatives of eq 5.2 # see Brockwell, Davis and Yang 2011 if(nume.Der==FALSE){ yuima.warn("We need to develop this part in the future for gaining speed") return(NULL) # diagMatB<-yuima.carma.eigen(B) # if(length(diagMatB$values)>1){ # MatrD<-diag(diagMatB$values) # }else{ # MatrD<-as.matrix(diagMatB$values) # } # MatrR<-diagMatB$vectors # idx.r<-c(q:(p-1)) # elem.X <-length(idx.r) # YMatr<-matrix(0,q,length(y)) # YMatr[q,]<-y # OutherX<-matrix(NA,elem.X,length(y)) # # OutherXalt<-matrix(NA,q,length(y)) # for(i in 1:elem.X){ # OutherX[i,]<-((MatrR%*%MatrD^(idx.r[i])%*%solve(MatrR))%*%X_q+ # (MatrR%*%MatrD^(idx.r[i]-1)%*%solve(MatrR))%*%YMatr)[1,] # } # X.StatVar<-rbind(X_q,OutherX) # return(X.StatVar) }else{ X_q0<-as.numeric(X_q[1,]) qlen<-length(X_q0) X.StatVar<-matrix(0,p,qlen) X.StatVar[1,]<-X_q0[1:length(X_q0)] diffStatVar<-diff(X_q0) difftime<-diff(tt)[1] for(i in 2:p){ in.count<-(p-i+1) fin.count<-length(diffStatVar) dummyDer<-(diffStatVar/difftime) X.StatVar[i,c(1:length(dummyDer))]<-(dummyDer) diffStatVar<-diff(dummyDer) # if(in.count-1>0){ # difftime<-difftime[c((in.count-1):fin.count)] # }else{difftime<-difftime[c((in.count):fin.count)]} } X.StatVar[c(1:dim(X_q)[1]),]<-X_q return(X.StatVar[,c(1:length(dummyDer))]) } } bEvalPoly<-function(b,lambdax){ result<-sum(b*lambdax^(c(1:length(b))-1)) return(result) } aEvalPoly<-function(a,lambdax){ p<-length(a) a.new<-c(1,a[c(1:(p-1))]) pa.new<-c(p:1)*a.new result<-sum(pa.new*lambdax^(c(p:1)-1)) return(result) } CarmaNoise<-function(yuima, param, data=NULL,NoNeg.Noise=FALSE){ if( missing(param) ) yuima.stop("Parameter values are missing.") if(!is.list(param)) yuima.stop("Argument 'param' must be of list type.") vect.param<-as.numeric(param) name.param<-names(param) names(vect.param)<-name.param if(is(yuima,"yuima")){ model<-yuima@model if(is.null(data)){ observ<-yuima@data }else{observ<-data} }else{ if(is(yuima,"yuima.carma")){ model<-yuima if(is.null(data)){ yuima.stop("Missing data") } observ<-data } } if(!is(observ,"yuima.data")){ yuima.stop("Data must be an object of class yuima.data-class") } info<-model@info numb.ar<-info@p name.ar<-paste([email protected],c(numb.ar:1),sep="") ar.par<-vect.param[name.ar] numb.ma<-info@q name.ma<-paste([email protected],c(0:numb.ma),sep="") ma.par<-vect.param[name.ma] loc.par=NULL if (length([email protected])!=0){ loc.par<-vect.param[[email protected]] } scale.par=NULL if (length([email protected])!=0){ scale.par<-vect.param[[email protected]] } lin.par=NULL if (length([email protected])!=0){ lin.par<-vect.param[[email protected]] } ttt<[email protected][[1]] tt<-index(ttt) y<-coredata(ttt) levy<-yuima.CarmaNoise(y,tt,ar.par,ma.par, loc.par, scale.par, lin.par,NoNeg.Noise) inc.levy<-diff(as.numeric(levy)) return(inc.levy[-1]) #We start to compute the increments from the second observation. } yuima.CarmaNoise<-function(y,tt,ar.par,ma.par, loc.par=NULL, scale.par=NULL, lin.par=NULL, NoNeg.Noise=FALSE){ if(!is.null(loc.par)){ y<-y-loc.par # yuima.warn("the loc.par will be implemented as soon as possible") # return(NULL) } if(NoNeg.Noise==TRUE){ if(length(ar.par)==length(ma.par)){ yuima.warn("The case with no negative jump needs to test deeply") #mean.y<-tail(ma.par,n=1)/ar.par[1]*scale.par mean.y<-mean(y) #y<-y-mean.y mean.L1<-mean.y/tail(ma.par,n=1)*ar.par[1]/scale.par } } if(!is.null(scale.par)){ ma.parAux<-ma.par*scale.par names(ma.parAux)<-names(ma.par) ma.par<-ma.parAux # yuima.warn("the scale.par will be implemented as soon as possible") # return(NULL) } if(!is.null(lin.par)){ yuima.warn("the lin.par will be implemented as soon as possible") return(NULL) } p<-length(ar.par) q<-length(ma.par) A<-MatrixA(ar.par[c(p:1)]) b_q<-tail(ma.par,n=1) ynew<-y/b_q if(q==1){ yuima.warn("The Derivatives for recovering noise have been performed numerically.") nume.Der<-TRUE X_qtot<-ynew X.StVa<-matrix(0,p,length(ynew)) X_q<-X_qtot[c(1:length(X_qtot))] X.StVa[1,]<-X_q if(p>1){ diffY<-diff(ynew) diffX<-diff(tt)[1] for (i in c(2:p)){ dummyDerY<-diffY/diffX X.StVa[i,c(1:length(dummyDerY))]<-(dummyDerY) diffY<-diff(dummyDerY) } X.StVa<-X.StVa[,c(1:length(dummyDerY))] } #yuima.warn("the car(p) process will be implemented as soon as possible") #return(NULL) }else{ newma.par<-ma.par/b_q # We build the matrix B which is necessary for building eq 5.2 B<-MatrixA(newma.par[c(1:(q-1))]) diagB<-yuima.carma.eigen(B) e_q<-rep(0,(q-1)) if((q-1)>0){ e_q[(q-1)]<-1 X_0<-rep(0,(q-1)) }else{ e_q<-1 X_0<-0 } discr.eul<-TRUE # We use the Euler discretization of eq 5.1 in Brockwell, Davis and Yang X_q<-StateVarX(ynew,tt,X_0,B,discr.eul) nume.Der<-TRUE #plot(t(X_q)) X.StVa<-StateVarXp(ynew,X_q,tt,B,q-1,p,nume.Der) #Checked once the numerical derivatives have been used #plot(y) } diagA<-yuima.carma.eigen(A) BinLambda<-rep(NA,length(ma.par)) for(i in c(1:length(diagA$values))){ BinLambda[i]<-bEvalPoly(ma.par,diagA$values[i]) } if(length(BinLambda)==1){ MatrBLam<-as.matrix(BinLambda) }else{ MatrBLam<-diag(BinLambda) } # We get the Canonical Vector Space in eq 2.17 Y_CVS<-MatrBLam%*%solve(diagA$vectors)%*%X.StVa #Canonical Vector Space # We verify the prop 2 in the paper "Estimation for Non-Negative Levy Driven CARMA process # yver1<-Y_CVS[1,]+Y_CVS[2,]+Y_CVS[3,] # plot(yver1) # plot(y) # Prop 2 Verified even in the case of q=0 idx.r<-match(0,Im(diagA$values)) lambda.r<-Re(diagA$values[idx.r]) if(is.na(idx.r)){ yuima.warn("all eigenvalues are immaginary numbers") idx.r<-1 lambda.r<-diagA$values[idx.r] } int<-0 derA<-aEvalPoly(ar.par[c(p:1)],lambda.r) # if(q==1){ # tt<-tt[p:length(tt)] # # CHECK HERE 15/01 # } if(nume.Der==TRUE){ tt<-tt[p:length(tt)] # CHECK HERE 15/01 } lev.und<-matrix(0,1,length(tt)) Alternative<-FALSE if(Alternative==TRUE){ incr.vect<-(X.StVa[,2:dim(X.StVa)[2]]-X.StVa[,1:(dim(X.StVa)[2]-1)])-(A%*%X.StVa[,1:(dim(X.StVa)[2]-1)] # +(matrix(c(0,mean.L1),2,(dim(X.StVa)[2]-1)))/diff(tt)[1] )*diff(tt)[1] #+(matrix(c(0,mean.L1),2,(dim(X.StVa)[2]-1))) lev.und<-as.matrix(cumsum(as.numeric(incr.vect[dim(X.StVa)[1],])),1,length(tt)) }else{ for(t in c(2:length(tt))){ int<-int+Y_CVS[idx.r,t-1]*(tt[t]-tt[t-1]) lev.und[,t]<-derA/BinLambda[idx.r]*(Y_CVS[idx.r,t]-Y_CVS[idx.r,1]-lambda.r*int) } } # if(NoNeg.Noise==TRUE){ # if(length(ar.par)==length(ma.par)){ # if(Alternative==TRUE){ # mean.Ltt<-mean.L1*tt[c(2:length(tt))] # }else{mean.Ltt<-mean.L1*tt} # lev.und<-lev.und+mean.Ltt # # } # } return(Re(lev.und)) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/CarmaNoise.R
##-------------------------------------------------------------------------- ## Author : Alexandre Brouste ## Project: Yuima ##-------------------------------------------------------------------------- ##-------------------------------------------------------------------------- ## Input mesh : mesh grid where the fBm is evaluated ## H : self-similarity parameter ## dim : valued in R^dim ## ## ## Output : simulation of a standard fractional Brownian noise ## for the mesh grid evaluation by Choleki s ## decomposition of the covariance matrix of the fGn. ##-------------------------------------------------------------------------- ##-------------------------------------------------------------------------- ## Complexity O(N^3) via method chol.... mais mieux pour dim different ## Taille memoire N^2 ## ------------------------------------------------------------------------- CholeskyfGn <- function( mesh , H , dim ){ H2 <- 2*H mesh<-mesh[[1]] N<-length(mesh)-2 # N+1 is the size of the fGn sample to be simulated fGn<-matrix(0,dim,N+1) matcov <- matrix(0,N+1,N+1) # Covariance matrix of the fGn for (i in (1:(N+1))) { j <- i:(N+1) matcov[i, j]<- 0.5 * (abs(mesh[i+1]-mesh[j])^H2 + abs(mesh[i]-mesh[j+1])^H2 - abs(mesh[i] - mesh[j])^H2-abs(mesh[i+1] - mesh[j+1])^H2) matcov[j, i]<- matcov[i, j] } L <- chol(matcov) for (k in 1:dim){ Z <- rnorm(N+1) fGn[k,] <- t(L) %*% Z } return(fGn) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/CholeskyfGn.R
# In order to deal the cogarch model in the \texttt{yuima} package # We define a new class called \texttt{yuima.cogarch} and its structure # is similar to those used for the carma model. # The class \texttt{yuima.cogarch} extends the \texttt{yuima.model} and has # an additional slot that contains informations about the model stored in an object of # class \texttt{cogarch.info}. # The class \texttt{cogarch.info} is build internally by the function \texttt{setCogarch} and it is a # the first slot of an object of class \texttt{yuima.cogarch}. # Class 'cogarch.info' setClass("cogarch.info", representation(p="numeric", q="numeric", ar.par="character", ma.par="character", loc.par="character", Cogarch.var="character", V.var="character", Latent.var="character", XinExpr="logical", measure="list", measure.type="character") ) # Class 'yuima.cogarch' setClass("yuima.cogarch", representation(info="cogarch.info"), contains="yuima.model") # Class 'gmm.cogarch' setClass("cogarch.est",representation( yuima = "yuima", objFun="character"), contains="mle" ) setClass("summary.cogarch.est", representation(objFun = "ANY", objFunVal = "ANY", object = "ANY"), contains="summary.mle" ) setClass("cogarch.est.incr", representation(Incr.Lev = "ANY", logL.Incr = "ANY" ), contains="cogarch.est" ) setClass("summary.cogarch.est.incr", representation(logL.Incr = "ANY", MeanI = "ANY", SdI = "ANY", logLI = "ANY", TypeI = "ANY", NumbI = "ANY", StatI ="ANY"), contains="summary.cogarch.est" ) # setClass("cogarch.gmm.incr",representation(Incr.Lev = "ANY", # model = "yuima.cogarch", # logL.Incr = "ANY", # objFun="character" # ), # contains="mle" # ) # # setClass("cogarch.gmm",representation( # model = "yuima.cogarch", # objFun="character"), # contains="mle" # ) # setClass("gmm.cogarch", # contains="mle" # )
/scratch/gouwar.j/cran-all/cranData/yuima/R/ClassCogarch.R
# Class 'yuima.carmaHawkes' setClass("carmaHawkes.info", representation(p = "numeric", q = "numeric", Counting.Process = "character", base.Int = "character", ar.par = "character", ma.par = "character", Intensity.var = "character", Latent.var = "character", XinExpr = "logical", Type.Jump = "logical") ) # Initialization Carma.Hawkes Info setMethod("initialize", "carmaHawkes.info", function(.Object, p=numeric(), q=numeric(), Counting.Process = character(), base.Int=character(), ar.par=character(), ma.par=character(), Intensity.var=character(), Latent.var=character(), XinExpr=logical(), Type.Jump=logical()){ .Object@p <- p .Object@q <- q [email protected] <- Counting.Process [email protected] <- base.Int [email protected] <- ar.par [email protected] <- ma.par [email protected] <- Intensity.var [email protected] <- Latent.var .Object@XinExpr <- XinExpr [email protected] <- Type.Jump return(.Object) }) setClass("yuima.carmaHawkes", representation(info="carmaHawkes.info"), contains="yuima.model") setMethod("initialize", "yuima.carmaHawkes", function(.Object, info = new("carmaHawkes.info"), drift = expression() , diffusion = list() , hurst = 0.5, jump.coeff = expression(), measure=list(), measure.type=character(), parameter = new("model.parameter"), state.variable = "lambda", jump.variable = "N", time.variable = "t", noise.number = numeric(), equation.number = numeric(), dimension = numeric(), solve.variable = character(), xinit = expression(), J.flag = logical()){ .Object@info <- info .Object@drift <- drift .Object@diffusion <- diffusion .Object@hurst <- hurst [email protected] <- jump.coeff .Object@measure <- measure [email protected] <- measure.type .Object@parameter <- parameter [email protected] <- state.variable [email protected] <- jump.variable [email protected] <- time.variable [email protected] <- noise.number [email protected] <- equation.number .Object@dimension <- dimension [email protected] <- solve.variable .Object@xinit <- xinit [email protected] <- J.flag return(.Object) }) # setCarmaHawkes function setCarmaHawkes <- function(p, q, law = NULL, base.Int = "mu0", ar.par="a", ma.par = "b", Counting.Process = "N", Intensity.var = "lambda", Latent.var = "x", time.var = "t", Type.Jump = FALSE, XinExpr = FALSE){ if(is.null(law)){ mylaw<-setLaw(rng = function(n){rconst(n,1)}, density=function(x){dconst(x,1)}, time.var = time.var) Type.Jump <- TRUE }else{ mylaw <- law } ar.par1 <- paste0(ar.par,1:p) ma.par1 <- paste0(ma.par,0:q) carmaHawkesInfo <- new("carmaHawkes.info", p=p, q=q, Counting.Process = Counting.Process, base.Int=base.Int, ar.par=ar.par1, ma.par=ma.par1, Intensity.var=Intensity.var, Latent.var=Latent.var, XinExpr=XinExpr, Type.Jump=Type.Jump) InternalCarma <- setCarma(p,q, loc.par=base.Int, Carma.var=Intensity.var, ar.par = ar.par, ma.par = ma.par, Latent.var=Latent.var, diffusion=NULL, # time.variable = time.var, # jump.variable = Counting.Process, measure= list(df = "dconst"), measure.type="code", XinExpr = XinExpr) # prova1 <- setCarma(p,q, loc.par=base.Int, # Carma.var=Intensity.var, # ar.par = ar.par, # ma.par = ma.par, # Latent.var=Intensity.var, diffusion=NULL, # time.variable = "s", jump.variable = Counting.Process, # measure= list(df= mylaw), # measure.type="code", # XinExpr = XinExpr) InternalCarma@measure<-list(df=mylaw) [email protected]<-time.var [email protected] <- Counting.Process CARMA_HAWKES <- new("yuima.carmaHawkes", info = carmaHawkesInfo, drift = InternalCarma@drift, diffusion = InternalCarma@diffusion, hurst = InternalCarma@hurst, jump.coeff = [email protected], measure = InternalCarma@measure, measure.type = [email protected], parameter = InternalCarma@parameter, state.variable = [email protected], jump.variable = [email protected], time.variable = [email protected], noise.number = [email protected], equation.number = [email protected], dimension = InternalCarma@dimension, solve.variable = [email protected], xinit = InternalCarma@xinit, J.flag = [email protected]) return(CARMA_HAWKES) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/ClassMethodsForCarmaHawkes.R
# The following example is necessary for the structure of # the PPR Data # library(yuima) # Terminal <- 10 # samp <- setSampling(T=Terminal,n=1000) # # # Ex 1. (Simple homogeneous Poisson process) # mod1 <- setPoisson(intensity="lambda", df=list("dconst(z,1)")) # set.seed(123) # y1 <- simulate(mod1, true.par=list(lambda=1),sampling=samp) # y1@[email protected] # simprvKern->yuimaPPR get.counting.data<-function(yuimaPPR,type="zoo"){ count <- yuimaPPR@[email protected] dimCount <- length(count) Time_Arrivals_Grid <- index(yuimaPPR@[email protected][[1]]) if(dimCount==1){ cond <- yuimaPPR@[email protected] %in% count Count.Var <- yuimaPPR@[email protected][,cond] } Time_Arrivals <- t(Time_Arrivals_Grid[1]) colnames(Time_Arrivals) <- "Time" Obser <- t(yuimaPPR@[email protected][1,]) colnames(Obser) <- yuimaPPR@[email protected] cond <- diff(Count.Var)==1 Time_Arrivals <- rbind(Time_Arrivals,as.matrix(Time_Arrivals_Grid[-1][cond])) if(is(yuimaPPR@[email protected],"matrix")){ Obser <- rbind(Obser,yuimaPPR@[email protected][-1,][cond,]) }else{ Obser <- rbind(Obser,as.matrix(yuimaPPR@[email protected][-1][cond])) } Data <- zoo(x = Obser,order.by = Time_Arrivals) # plot(Data) if(type=="zoo"){ Data <- Data return(Data) } if(type=="yuima.PPR"){ yuimaPPR@[email protected] <- Data return(yuimaPPR) } if(type=="matrix"){ Data <- cbind(Time_Arrivals, Obser) return(Data) } yuima.stop("type is not supported.") } DataPPR <- function(CountVar, yuimaPPR, samp){ if(!is(yuimaPPR,"yuima.PPR")){ yuima.stop("...") } if(!is(samp,"yuima.sampling")){ yuima.stop("...") } if(!is(CountVar,"zoo")){ yuima.stop("...") } names <- colnames(CountVar) if(all(names %in% yuimaPPR@[email protected]) && all(yuimaPPR@[email protected] %in% names)){ TimeArr <- index(CountVar) grid <- samp@grid[[1]] dimData <- dim(CountVar)[2] DataOr <- NULL for(i in c(1:dimData)){ prv <- approx(x=TimeArr, y = CountVar[,i], xout = grid, method = "constant")$y DataOr <- cbind(DataOr,prv) } DataFin <- zoo(DataOr, order.by = grid) colnames(DataFin) <- names myData <- setData(DataFin) yuimaPPR@data <- myData yuimaPPR@sampling <- samp return(yuimaPPR) }else{ dummy <- paste0("The labels of variables should be ", paste0(yuimaPPR@[email protected],collapse= ", "),collapse = " ") yuima.stop(dummy) } }
/scratch/gouwar.j/cran-all/cranData/yuima/R/DataPPR.R
yuima.PhamBreton.Alg<-function(a){ p<-length(a) gamma<-a[p:1] if(p>2){ gamma[p]<-a[1] alpha<-matrix(NA,p,p) for(j in 1:p){ if(is.integer(as.integer(j)/2)){ alpha[p,j]<-0 alpha[p-1,j]<-0 }else{ alpha[p,j]<-a[j] alpha[p-1,j]<-a[j+1]/gamma[p] } } for(n in (p-1):1){ gamma[n]<-alpha[n+1,2]-alpha[n,2] for(j in 1:n-1){ alpha[n-1,j]<-(alpha[n+1,j+2]-alpha[n,j+2])/gamma[n] } alpha[n-1,n-1]<-alpha[n+1,n+1]/gamma[n] } gamma[1]<-alpha[2,2] } return(gamma) } Diagnostic.Carma<-function(carma){ if(!is(carma@model,"yuima.carma")) yuima.stop("model is not a carma") if(!is(carma,"mle")) yuima.stop("object does not belong to yuima.qmle-class or yuima.carma.qmle-class ") param<-coef(carma) info <- carma@model@info numb.ar<-info@p name.ar<-paste([email protected],c(numb.ar:1),sep="") ar.par<-param[name.ar] statCond<-FALSE if(min(yuima.PhamBreton.Alg(ar.par[numb.ar:1]))>=0) statCond<-TRUE return(statCond) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/DiagnosticCarma.R
# We write a Diagnostic function that evaluates the following quantity Diagnostic.Cogarch <- function(yuima.cogarch, param = list(), matrixS = NULL , mu = 1, display =TRUE){ if(missing(yuima.cogarch)) yuima.stop("yuima.cogarch or yuima object is missing.") if((length(param)==0 && !is(yuima.cogarch, "cogarch.est"))){ yuima.stop("missing values parameters") } if(is(yuima.cogarch,"yuima")){ model<-yuima.cogarch@model }else{ if(is(yuima.cogarch,"yuima.cogarch")){ model<-yuima.cogarch }else{ if(is(yuima.cogarch,"cogarch.est")){ model<-yuima.cogarch@yuima@model if(length(param)==0){ param<-coef(yuima.cogarch) } } } } if(!is.COGARCH(model)){ yuima.warn("The model does not belong to the class yuima.cogarch") } info <- model@info numb.ar <- info@q ar.name <- paste([email protected],c(numb.ar:1),sep="") numb.ma <- info@p ma.name <- paste([email protected],c(1:numb.ma),sep="") loc.par <- [email protected] if(is.list(param)){ param <- unlist(param) } xinit.name0 <- model@parameter@xinit idx <- na.omit(match(c(loc.par, ma.name), xinit.name0)) xinit.name <- xinit.name0[-idx] fullcoeff <- c(ar.name, ma.name, loc.par,xinit.name) nm<-names(param) if(!all(xinit.name %in% nm)){ fullcoeff <- c(ar.name, ma.name, loc.par) } oo <- match(nm, fullcoeff) if(!is(yuima.cogarch,"cogarch.est")){ if(length(na.omit(oo))!=length(fullcoeff)) yuima.stop("some named arguments in 'param' are not arguments to the supplied yuima.cogarch model") } acoeff <- param[ma.name] b <- param[ar.name] cost<- param[loc.par] # Check Strictly Stationary condition Amatr<-MatrixA(b[c(info@q:1)]) if(is.null(matrixS)){ Dum <- yuima.carma.eigen(Amatr) matrixS <- Dum$vectors lambda.eig <- Dum$values }else{ if(!is.matrix(matrixS)){ if(dim(matrixS)[1]!=dim(matrixS)[2]){ yuima.stop("matrixS must be an object of class matrix") }else{ if(dim(matrixS)[1]!=numb.ar) yuima.stop("matrixS must be an square matrix. Its row number is equal to the dimension of autoregressive coefficients") } } lambda.eig<-diag(solve(matrixS)%*%Amatr%*%matrixS) } lambda1<- max(Re(lambda.eig)) # we find lambda1 ev.dum<-matrix(0,1,info@q) ev.dum[1,info@q] <- 1 av.dum <-matrix(0,info@q,1) av.dum[c(1:info@p),1]<-acoeff if(display==TRUE){ cat(paste0("\n COGARCH(",info@p,info@q,") model \n")) } matrforck<-solve(matrixS)%*%(av.dum%*%ev.dum)%*%matrixS if(is.complex(matrforck)){ A2Matrix<-Conj(t(matrforck))%*%matrforck SpectNorm<-max(sqrt(as.numeric(abs(eigen(A2Matrix)$values)))) }else{ A2Matrix<-t(matrforck)%*%matrforck SpectNorm<-max(sqrt(abs(eigen(A2Matrix)$values))) } if(SpectNorm*mu < -lambda1){ if(display==TRUE){ cat("\n The process is strictly stationary\n The unconditional first moment of the Variance process exists \n") } res.stationarity <- TRUE }else{ if(display==TRUE){ cat("\n We are not able to establish if the process is stationary \n Try a new S matrix such that the Companion matrix is diagonalizable") } res.stationarity <- "Try a different S matrix" } # Check the positivity massage <- "\n We are not able to establish the positivity of the Variance \n" res.pos <- " " if(info@p==1){ if(is.numeric(lambda.eig) && all(lambda.eig<0)){ massage <- "\n the Variance is a positive process \n" res.pos <- TRUE } if(is.complex(lambda.eig) && all(Im(lambda.eig)==0) && all(Re(lambda.eig) < 0)){ massage <- "\n the Variance is a positive process \n" res.pos <- TRUE } } if((info@q==2 && info@p==2 )){ if(is.numeric(lambda.eig)|| (is.complex(lambda.eig) && all(Im(lambda.eig)==0))){ if(acoeff[1]>=-acoeff[2]*lambda1){ massage <- "\n the Variance is a positive process \n" res.pos <- TRUE }else{ massage <- "\n the Variance process is not strictly positive \n" res.pos <- FALSE } } } if(info@p>=2 && info@q>info@p){ gamma.eig<-polyroot(acoeff) if(all(Im(gamma.eig)==0)){ gamm.eig<-as.numeric(gamma.eig) } if( all(Re(gamma.eig)<0) && all(Re(lambda.eig)<0)){ NewLamb <- sort(Re(lambda.eig),decreasing = T) NewGam <- sort(Re(gamma.eig),decreasing = T) if(cumsum(NewLamb[c(1:(info@p-1))])>=cumsum(NewGam[c(1:(info@p-1))])){ massage <- "\n The Variance process is strictly positive. \n" res.pos<-TRUE } } } if(display==TRUE){ cat(massage) } res1<-StationaryMoments(cost,b,acoeff,mu) res <- list(meanVarianceProc=res1$ExpVar, meanStateVariable=res1$ExpStatVar, stationary = res.stationarity, positivity = res.pos) return(invisible(res)) } yuima.norm2<-function(x){ res<-sqrt(max(eigen(t(x) %*% x)$values)) return(res) } StationaryMoments<-function(cost,b,acoeff,mu=1){ # We obtain stationary mean of State process # stationary mean of the variance # E\left(Y\right)=-a_{0}m_{2}\left(A+m_{2}ea'\right)^{-1}e q<-length(b) a <- e <- matrix(0,nrow=q,ncol=1) e[q,1] <- 1 p<-length(acoeff) a[1:p,1] <- acoeff B_tilde <- MatrixA(b[c(q:1)])+mu*e%*%t(a) if(q>1){ invB<-rbind(c(-B_tilde[q,-1],1)/B_tilde[q,1],cbind(diag(q-1),matrix(0,q-1,1))) }else{invB<-1/B_tilde} ExpStatVar <- -cost*mu*invB%*%e ExpVar <- cost+t(a)%*%ExpStatVar res <- list(ExpVar=ExpVar, ExpStatVar=ExpStatVar) return(res) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/DiagnosticCogarch.R
# Method for construction of function and operator of yuima # object setMap <- function(func, yuima, out.var = "", nrow =1 ,ncol=1){ # A function has three kind of inputs # parameters that is a scalar # Process that is an object of class yuima # Time that is an object of sample grid res <- aux.setMaps(func, yuima, out.var = out.var, nrow =1 , ncol=1, type="Maps") return(res) # if(missing(yuima)){ # yuima.stop("yuima object is missing.") # } # # if(missing(func)){ # yuima.stop("function is missing.") # return(NULL) # } # # # if(is.array(func)){ # # dimens<-dim(func) # # }else{ # # if(length(func)!=(nrow*ncol)){ # # yuima.warn("nrow*ncol is different from the dim of image. f becomes a vector function") # # func<-as.matrix(func) # # dimens<-dim(func) # # }else{ # # func<-matrix(func,nrow = nrow, ncol = ncol) # # dimens<-dim(func) # # } # # } # # resFunc<-constFunc(func, nrow, ncol) # # func <- resFunc$func # dimens <- resFunc$dimens # # # if(is(yuima, "yuima.model")){ # # mod<-yuima # # yuima<-setYuima(model = mod) # # }else{ # # if(is(yuima, "yuima")){ # # mod<-yuima@model # # }else{ # # yuima.stop("yuima must be an object of class yuima or yuima.model") # # } # # } # # # modDum <- ExtYuimaMod(yuima) # mod <- modDum$mod # yuima <- modDum$yuima # # paramfunc<-NULL # ddd<-prod(dimens) # funcList<-as.list(character(length=ddd)) # func<-as.character(func) # for(i in c(1:ddd)){ # funcList[[i]]<-parse(text=func[i]) # paramfunc<-c(paramfunc,all.vars(funcList[[i]])) # } # # funcList<-array(funcList,dim=dimens) # # for(j in c(1:ncol)){ # # for(i in c(1:nrow)){ # # funcList[[i+(j-1)*nrow]]<-parse(text = func[i,j]) # # paramfunc<-c(paramfunc,all.vars(funcList[[i+(j-1)*nrow]])) # # } # # } # paramfunc<-unique(paramfunc) # common<-mod@parameter@common # # Cond<-(mod@parameter@all %in% paramfunc) # common <- c(common,mod@parameter@all[Cond]) # Cond <- (paramfunc %in% [email protected]) # if(sum(Cond)==0){ # yuima.warn("function does not depend on solve.variable") # } # paramfunc<-paramfunc[!Cond] # # Cond <- (paramfunc %in% [email protected]) # paramfunc <- paramfunc[!Cond] # if(length(out.var)==1){ # out.var<-rep(out.var,ddd) # } # param <- new("param.Output", # out.var = out.var, # allparam = unique(c(paramfunc,mod@parameter@all)), # allparamMap = paramfunc, # common = common, # Input.var = [email protected], # [email protected]) # # objFunc <- new("info.Output", formula = funcList, # dimension=dimens, type ="Maps") # # res<-new("yuima.Output", # param = param, # Output = objFunc, # yuima=yuima ) # # return(res) } aux.setMaps <- function(func, yuima, out.var = "", nrow =1 ,ncol=1, type="Maps"){ if(missing(yuima)){ yuima.stop("yuima object is missing.") } if(missing(func)){ yuima.stop("function is missing.") return(NULL) } # if(is.array(func)){ # dimens<-dim(func) # }else{ # if(length(func)!=(nrow*ncol)){ # yuima.warn("nrow*ncol is different from the dim of image. f becomes a vector function") # func<-as.matrix(func) # dimens<-dim(func) # }else{ # func<-matrix(func,nrow = nrow, ncol = ncol) # dimens<-dim(func) # } # } resFunc<-constFunc(func, nrow, ncol) func <- resFunc$func dimens <- resFunc$dimens # if(is(yuima, "yuima.model")){ # mod<-yuima # yuima<-setYuima(model = mod) # }else{ # if(is(yuima, "yuima")){ # mod<-yuima@model # }else{ # yuima.stop("yuima must be an object of class yuima or yuima.model") # } # } modDum <- ExtYuimaMod(yuima) mod <- modDum$mod yuima <- modDum$yuima paramfunc<-NULL ddd<-prod(dimens) funcList<-as.list(character(length=ddd)) funcList <- vector(mode ="expression", length=ddd) func<-as.character(func) for(i in c(1:ddd)){ #funcList[[i]]<-parse(text=func[i]) funcList[i]<-parse(text=func[i]) paramfunc<-c(paramfunc,all.vars(funcList[[i]])) } # funcList<-array(funcList,dim=dimens) # for(j in c(1:ncol)){ # for(i in c(1:nrow)){ # funcList[[i+(j-1)*nrow]]<-parse(text = func[i,j]) # paramfunc<-c(paramfunc,all.vars(funcList[[i+(j-1)*nrow]])) # } # } paramfunc<-unique(paramfunc) common<-mod@parameter@common Cond<-(mod@parameter@all %in% paramfunc) common <- c(common,mod@parameter@all[Cond]) Cond <- (paramfunc %in% [email protected]) if(sum(Cond)==0){ yuima.warn("function does not depend on solve.variable") } paramfunc<-paramfunc[!Cond] Cond <- (paramfunc %in% [email protected]) paramfunc <- paramfunc[!Cond] if(length(out.var)==1){ out.var<-rep(out.var,ddd) } param <- new("param.Map", out.var = out.var, allparam = unique(c(paramfunc,mod@parameter@all)), allparamMap = paramfunc, common = common, Input.var = [email protected], [email protected]) objFunc <- new("info.Map", formula = funcList, dimension=dimens, type = type, param=param) res<-new("yuima.Map", Output = objFunc, yuima=yuima ) return(res) } setIntegral <- function(yuima, integrand, var.dx, lower.var, upper.var, out.var = "", nrow =1 ,ncol=1){ type <- "Integral" res <- aux.setIntegral(yuima = yuima, integrand = integrand, var.dx = var.dx, lower.var = lower.var, upper.var = upper.var, out.var = out.var, nrow = nrow , ncol = ncol, type = type) return(res) # param <- list(allparam=unique(allparam), common=common, # IntegrandParam = paramIntegrand) # # return(list(param = param, IntegrandList=IntegrandList, # var.dx=var.dx, lower.var=lower.var, upper.var=upper.var, # out.var=out.var, dimIntegrand = dimension)) } aux.setIntegral <- function(yuima, integrand, var.dx, lower.var, upper.var, out.var = "", nrow =1 ,ncol=1, type = "Integral"){ if(missing(yuima)){ yuima.stop("yuima object is missing.") } if(missing(integrand)){ yuima.stop("Integrand function is missing") } if(missing(var.dx)){ yuima.stop("dx object is missing.") } if(!is(integrand,"yuima.Map")){ resFunc<-constFunc(func=integrand, nrow, ncol) }else{ resFunc <-list() resFunc$func <- integrand@Output@formula resFunc$dimens <- integrand@Output@dimension if(!(integrand@Output@[email protected]%in%[email protected])){ yuima.warn("check integrand function") } } Integrand <- resFunc$func dimension <- resFunc$dimens modDum <- ExtYuimaMod(yuima) mod <- modDum$mod yuima <- modDum$yuima paramIntegrand <- NULL ddd <- prod(dimension) IntegrandList <- as.list(character(length=ddd)) Integrand <- as.character(Integrand) for(i in c(1:ddd)){ IntegrandList[[i]]<-parse(text=Integrand[i]) paramIntegrand<-c(paramIntegrand,all.vars(IntegrandList[[i]])) } paramIntegrand<-unique(paramIntegrand) common<-mod@parameter@common Cond<-(mod@parameter@all %in% paramIntegrand) common <- c(common,mod@parameter@all[Cond]) # solve variable Cond <- (paramIntegrand %in% [email protected]) if(sum(Cond)==0){ yuima.warn("Integrand fuction does not depend on solve.variable") } paramIntegrand <- paramIntegrand[!Cond] # state variable Cond <- (paramIntegrand %in% [email protected]) if(sum(Cond)==0){ yuima.warn("Integrand fuction does not depend on state.variable") } paramIntegrand <- paramIntegrand[!Cond] # time variable Cond <- (paramIntegrand %in% [email protected]) paramIntegrand <- paramIntegrand[!Cond] # upper.var if((upper.var == [email protected])||(lower.var == [email protected])){ yuima.stop("upper.var or lower.var must be different from time.variable") } Cond <- (paramIntegrand %in% upper.var) paramIntegrand <- paramIntegrand[!Cond] Cond <- (paramIntegrand %in% lower.var) paramIntegrand <- paramIntegrand[!Cond] allparam <- c(mod@parameter@all, unique(paramIntegrand)) if(type == "Integral"){ cond1 <-c(var.dx %in% c([email protected], [email protected])) if(sum(cond1)!=dimension[2]){ yuima.stop("var.dx must be contains only components of solve variable or time variable") } } my.param.Integral <- new("param.Integral", allparam = unique(allparam), common = common, Integrandparam = paramIntegrand) my.variable.Integral <- new("variable.Integral", var.dx = var.dx, lower.var = lower.var, upper.var = upper.var, out.var = out.var, var.time = yuima@[email protected]) my.integrand <- new("Integrand", IntegrandList=IntegrandList, dimIntegrand = dimension) my.Integral<-new("Integral.sde", param.Integral = my.param.Integral, variable.Integral = my.variable.Integral, Integrand = my.integrand) res<-new("yuima.Integral",Integral=my.Integral, yuima=yuima) return(res) } # setOperator <- function(operator, X, Y, # out.var = "", nrow =1 ,ncol=1){ # if(is(X, "yuima.model")&& is(Y, "yuima.model")){ # modtot <- rbind(X,Y) # } # #assign("mod1",mod1) # Oper<- strsplit(operator,split="")[[1]] # if([email protected][email protected]){ # yuima.stop("the models must have the same dimension") # } # func <- matrix(character(),[email protected],1) # condX <- (Oper %in% "X") # condY <- (Oper %in% "Y") # for(i in c(1:[email protected])){ # dummyCond <- Oper # dummyCond[condX] <- [email protected][i] # dummyCond[condY] <- [email protected][i] # func[i,] <- paste0(dummyCond,collapse ="") # } # # res <- setMaps(func = func, yuima = modtot, # # out.var = out.var, nrow = nrow , ncol = ncol) # res <- aux.setMaps(func = func, yuima = modtot, # out.var = out.var, nrow = nrow , # ncol=ncol, type="Operator") # return(res) # } # # setIntensity <- function(...){ # return(NULL) # } constFunc<-function(func, nrow, ncol){ if(is.array(func)){ dimens<-dim(func) }else{ if(length(func)!=(nrow*ncol)){ yuima.warn("nrow*ncol is different from the dim of image. f becomes a vector function") func<-as.matrix(func) dimens<-dim(func) }else{ func<-matrix(func,nrow = nrow, ncol = ncol) dimens<-dim(func) } } return(list(func=func, dimens = dimens)) } ExtYuimaMod <- function(yuima){ if(is(yuima, "yuima.model")){ mod<-yuima yuima<-setYuima(model = mod) }else{ if(is(yuima, "yuima")){ mod<-yuima@model }else{ yuima.stop("yuima must be an object of class yuima or yuima.model") } } return(list(mod=mod, yuima=yuima)) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/FunctionAndOperators.R
## information criteria IC <- function(drif = NULL, diff = NULL, jump.coeff = NULL, data = NULL, Terminal = 1, add.settings = list(), start, lower, upper, ergodic = TRUE, stepwise = FALSE, weight = FALSE, rcpp = FALSE, ...){ Levy <- FALSE if(length(jump.coeff) > 0){ torf.jump <- (jump.coeff == "0") for(i in 1:length(jump.coeff)){ if(torf.jump[i] == FALSE){ Levy <- TRUE stepwise <- TRUE break } } } if(Levy == FALSE && ergodic == FALSE){ stepwise <- FALSE } settings <- list(hurst = 0.5, measure = list(), measure.type = character(), state.variable = "x", jump.variable = "z", time.variable = "t", solve.variable = "x") if(length(add.settings) > 0){ match.settings <- match(names(add.settings), names(settings)) for(i in 1:length(match.settings)){ settings[[match.settings[i]]] <- add.settings[[i]] } } if(stepwise == FALSE){ # Joint ## Candidate models yuimas <- NULL if(ergodic == TRUE){ joint <- TRUE for(i in 1:length(diff)){ for(j in 1:length(drif)){ mod <- setModel(drift = drif[[j]], diffusion = diff[[i]], hurst = settings[[1]], measure = settings[[2]], measure.type = settings[[3]], state.variable = settings[[4]], jump.variable = settings[[5]], time.variable = settings[[6]], solve.variable = settings[[7]]) if(is.matrix(data) == FALSE){ n <- length(data)-1 modsamp <- setSampling(Terminal = Terminal, n = n) modyuima <- setYuima(model = mod, sampling = modsamp) sub.zoo.data <- list(zoo(x = data, order.by = modyuima@sampling@grid[[1]])) names(sub.zoo.data)[1] <- "Series 1" }else{ n <- nrow(data)-1 modsamp <- setSampling(Terminal = Terminal, n = n) modyuima <- setYuima(model = mod, sampling = modsamp) sub.zoo.data <- list() for(j in 1:ncol(data)){ sub.zoo.data <- c(sub.zoo.data, list(zoo(x = data[,j], order.by = modyuima@sampling@grid[[1]]))) names(sub.zoo.data)[j] <- paste("Series", j) } } modyuima@[email protected] <- sub.zoo.data yuimas <- c(yuimas, list(modyuima)) } } }else{ joint <- FALSE for(i in 1:length(diff)){ if(is.matrix(data) == FALSE){ mod <- setModel(drift = "0", diffusion = diff[[i]], hurst = settings[[1]], measure = settings[[2]], measure.type = settings[[3]], state.variable = settings[[4]], jump.variable = settings[[5]], time.variable = settings[[6]], solve.variable = settings[[7]]) n <- length(data)-1 modsamp <- setSampling(Terminal = Terminal, n = n) modyuima <- setYuima(model = mod, sampling = modsamp) sub.zoo.data <- list(zoo(x = data, order.by = modyuima@sampling@grid[[1]])) names(sub.zoo.data)[1] <- "Series 1" }else{ zerovec <- rep("0", length=ncol(data)) mod <- setModel(drift = zerovec, diffusion = diff[[i]], hurst = settings[[1]], measure = settings[[2]], measure.type = settings[[3]], state.variable = settings[[4]], jump.variable = settings[[5]], time.variable = settings[[6]], solve.variable = settings[[7]]) n <- nrow(data)-1 modsamp <- setSampling(Terminal = Terminal, n = n) modyuima <- setYuima(model = mod, sampling = modsamp) sub.zoo.data <- list() for(j in 1:ncol(data)){ sub.zoo.data <- c(sub.zoo.data, list(zoo(x = data[,j], order.by = modyuima@sampling@grid[[1]]))) names(sub.zoo.data)[j] <- paste("Series", j) } } modyuima@[email protected] <- sub.zoo.data yuimas <- c(yuimas, list(modyuima)) } } mod.num <- length(yuimas) ## Model comparison Esti <- BIC <- QBIC <- AIC <- NULL for(i in 1:mod.num){ yuima <- yuimas[[i]] #alpha <- yuima@model@parameter@drift #beta <- yuima@model@parameter@diffusion para.num.init <- match(yuima@model@parameter@all, names(start)) para.num.low <- match(yuima@model@parameter@all, names(lower)) para.num.upp <- match(yuima@model@parameter@all, names(upper)) para.start <- NULL para.lower <- NULL para.upper <- NULL for(j in 1:length(yuima@model@parameter@all)){ para.start <- c(para.start, list(start[[para.num.init[j]]])) para.lower <- c(para.lower, list(lower[[para.num.low[j]]])) para.upper <- c(para.upper, list(upper[[para.num.upp[j]]])) } names(para.start) <- yuima@model@parameter@all names(para.lower) <- yuima@model@parameter@all names(para.upper) <- yuima@model@parameter@all mle <- qmle(yuima, start = para.start, lower = para.lower, upper = para.upper, method = "L-BFGS-B", joint = joint, rcpp = rcpp) hess <- list(mle@details$hessian) hess.diff <- subset(hess[[1]], rownames(hess[[1]])%in%yuima@model@parameter@diffusion, select=yuima@model@parameter@diffusion) hess.drif <- subset(hess[[1]], rownames(hess[[1]])%in%yuima@model@parameter@drift, select=yuima@model@parameter@drift) esti <- list(coef(mle)) names(esti[[1]]) <- c(yuima@model@parameter@diffusion, yuima@model@parameter@drift) bic <- summary(mle)@m2logL+length(yuima@model@parameter@drift)*log(Terminal)+length(yuima@model@parameter@diffusion)*log(n) if(det(hess.diff) > 0 && det(hess.drif) > 0){ qbic <- summary(mle)@m2logL+log(det(hess.diff))+log(det(hess.drif)) }else{ qbic <- summary(mle)@m2logL+length(yuima@model@parameter@drift)*log(Terminal)+length(yuima@model@parameter@diffusion)*log(n) } aic <- summary(mle)@m2logL+2*(length(yuima@model@parameter@drift)+length(yuima@model@parameter@diffusion)) Esti <- c(Esti, esti) BIC <- c(BIC, bic) QBIC <- c(QBIC, qbic) AIC <- c(AIC, aic) } BIC.opt <- which.min(BIC) QBIC.opt <- which.min(QBIC) AIC.opt <- which.min(AIC) ## Names if(ergodic == TRUE){ for(i in 1:length(diff)){ for(j in 1:length(drif)){ names(Esti)[(length(drif)*(i-1)+j)] <- paste("diffusion_", i, " & drift_", j, sep = "") } } BIC <- matrix(BIC, length(drif), length(diff)) QBIC <- matrix(QBIC, length(drif), length(diff)) AIC <- matrix(AIC, length(drif), length(diff)) diff.name <- numeric(length(diff)) drif.name <- numeric(length(drif)) for(i in 1:length(diff)){ diff.name[i] <- paste("scale", i, sep = "_") } colnames(BIC) <- colnames(QBIC) <- colnames(AIC) <- diff.name for(i in 1:length(drif)){ drif.name[i] <- paste("drift", i, sep = "_") } rownames(BIC) <- rownames(QBIC) <- rownames(AIC) <- drif.name }else{ for(i in 1:length(diff)){ names(Esti)[i] <- paste("scale", i, sep = "_") } diff.name <- numeric(length(diff)) for(i in 1:length(diff)){ diff.name[i] <- paste("scale", i, sep = "_") } names(BIC) <- names(QBIC) <- diff.name } ## Model weights if(weight == TRUE){ BIC.weight <- exp(-(1/2)*(BIC-BIC[BIC.opt]))/sum(exp(-(1/2)*(BIC-BIC[BIC.opt]))) QBIC.weight <- exp(-(1/2)*(QBIC-QBIC[QBIC.opt]))/sum(exp(-(1/2)*(QBIC-QBIC[QBIC.opt]))) AIC.weight <- exp(-(1/2)*(AIC-AIC[AIC.opt]))/sum(exp(-(1/2)*(AIC-AIC[AIC.opt]))) if(ergodic == TRUE){ BIC.weight <- matrix(BIC.weight, length(drif), length(diff)) QBIC.weight <- matrix(QBIC.weight, length(drif), length(diff)) AIC.weight <- matrix(AIC.weight, length(drif), length(diff)) colnames(BIC.weight) <- colnames(QBIC.weight) <- colnames(AIC.weight) <- diff.name rownames(BIC.weight) <- rownames(QBIC.weight) <- rownames(AIC.weight) <- drif.name }else{ names(BIC.weight) <- names(QBIC.weight) <- diff.name } } ## Results diff.copy <- diff drif.copy <- drif for(i in 1:length(diff)){ names(diff.copy)[i] <- paste("scale", i, sep = "_") } if(ergodic == TRUE){ for(i in 1:length(drif)){ names(drif.copy)[i] <- paste("drift", i, sep = "_") } diff.BIC.opt <- (BIC.opt-1)%/%length(drif)+1 diff.QBIC.opt <- (QBIC.opt-1)%/%length(drif)+1 diff.AIC.opt <- (AIC.opt-1)%/%length(drif)+1 drif.BIC.opt <- (BIC.opt+(length(drif)-1))%%length(drif)+1 drif.QBIC.opt <- (QBIC.opt+(length(drif)-1))%%length(drif)+1 drif.AIC.opt <- (AIC.opt+(length(drif)-1))%%length(drif)+1 }else{ drif <- NULL } call <- match.call() model.coef <- list(drift = drif.copy, scale = diff.copy) if(length(drif) >0){ bic.selected.coeff <- list(drift = drif[[drif.BIC.opt]], scale = diff[[diff.BIC.opt]]) qbic.selected.coeff <- list(drift = drif[[drif.QBIC.opt]], scale = diff[[diff.QBIC.opt]]) aic.selected.coeff <- list(drift = drif[[drif.AIC.opt]], scale = diff[[diff.AIC.opt]]) }else{ bic.selected.coeff <- list(drift = NULL, scale = diff[[BIC.opt]]) qbic.selected.coeff <- list(drift = NULL, scale = diff[[QBIC.opt]]) aic.selected.coeff <- list(drift = NULL, scale = NULL) AIC <- NULL AIC.weight <- NULL } ic.selected <- list(BIC = bic.selected.coeff, QBIC = qbic.selected.coeff, AIC = aic.selected.coeff) if(weight == TRUE){ ak.weight <- list(BIC = BIC.weight, QBIC = QBIC.weight, AIC = AIC.weight) }else{ ak.weight <- NULL } final_res <- list(call = call, model = model.coef, par = Esti, BIC = BIC, QBIC = QBIC, AIC = AIC, weight = ak.weight, selected = ic.selected) }else{ # Stepwise pena.aic <- function(yuimaaic, data, pdiff, moment){ tmp.env <- new.env() aic1para <- yuimaaic@model@parameter@diffusion for(i in 1:length(aic1para)){ aic1match <- match(aic1para[i], names(pdiff)[i]) assign(aic1para[i], pdiff[aic1match], envir=tmp.env) } aic1state <- yuimaaic@[email protected] aic1ldata <- length(data)-1 aic1dx <- diff(data) assign(aic1state, data, envir=tmp.env) aic1ter <- yuimaaic@sampling@Terminal aic1diff <- eval(yuimaaic@model@diffusion[[1]], envir=tmp.env) if(length(aic1diff) == 1){ aic1diff <- rep(aic1diff, aic1ldata) } aic1sum <- 0 for(i in 1:aic1ldata){ subaic1sum <- (aic1dx[i]/aic1diff[i])^moment aic1sum <- aic1sum + subaic1sum } return(aic1sum/aic1ter) } Esti1 <- BIC1 <- QBIC1 <- AIC1 <- NULL Esti2.bic <- Esti2.qbic <- Esti2.aic <- BIC2 <- QBIC2 <- AIC2 <- NULL # First step yuimas1 <- swbeta <- NULL if(Levy == TRUE){ diff <- jump.coeff } for(i in 1:length(diff)){ ## Candidate models if(is.matrix(data) == FALSE){ mod <- setModel(drift = "0", diffusion = diff[[i]], hurst = settings[[1]], measure = settings[[2]], measure.type = settings[[3]], state.variable = settings[[4]], jump.variable = settings[[5]], time.variable = settings[[6]], solve.variable = settings[[7]]) n <- length(data)-1 modsamp <- setSampling(Terminal = Terminal, n = n) modyuima <- setYuima(model = mod, sampling = modsamp) sub.zoo.data <- list(zoo(x = data, order.by = modyuima@sampling@grid[[1]])) names(sub.zoo.data)[1] <- "Series 1" }else{ zerovec <- rep("0", length=ncol(data)) mod <- setModel(drift = zerovec, diffusion = diff[[i]], hurst = settings[[1]], measure = settings[[2]], measure.type = settings[[3]], state.variable = settings[[4]], jump.variable = settings[[5]], time.variable = settings[[6]], solve.variable = settings[[7]]) n <- nrow(data)-1 modsamp <- setSampling(Terminal = Terminal, n = n) modyuima <- setYuima(model = mod, sampling = modsamp) sub.zoo.data <- list() for(j in 1:ncol(data)){ sub.zoo.data <- c(sub.zoo.data, list(zoo(x = data[,j], order.by = modyuima@sampling@grid[[1]]))) names(sub.zoo.data)[j] <- paste("Series", j) } } modyuima@[email protected] <- sub.zoo.data yuimas1 <- c(yuimas1, list(modyuima)) ## Model comparison yuima <- modyuima swbeta <- c(swbeta, list(yuima@model@parameter@diffusion)) para.num.init <- match(swbeta[[i]], names(start)) para.num.low <- match(swbeta[[i]], names(lower)) para.num.upp <- match(swbeta[[i]], names(upper)) para.start <- NULL para.lower <- NULL para.upper <- NULL for(j in 1:length(swbeta[[i]])){ para.start <- c(para.start, list(start[[para.num.init[j]]])) para.lower <- c(para.lower, list(lower[[para.num.low[j]]])) para.upper <- c(para.upper, list(upper[[para.num.upp[j]]])) } names(para.start) <- swbeta[[i]] names(para.lower) <- swbeta[[i]] names(para.upper) <- swbeta[[i]] mle <- qmle(yuima, start = para.start, lower = para.lower, upper = para.upper, method = "L-BFGS-B", joint = FALSE, rcpp = rcpp) hess <- mle@details$hessian esti <- list(coef(mle)) names(esti[[1]]) <- swbeta[[i]] if(is.matrix(data) == FALSE && Levy == TRUE){ bic <- summary(mle)@m2logL+(length(swbeta[[i]])/(yuima@sampling@delta))*log(yuima@sampling@Terminal) qbic <- summary(mle)@m2logL+(length(swbeta[[i]])/(yuima@sampling@delta))*log(yuima@sampling@Terminal) }else{ bic <- summary(mle)@m2logL+length(swbeta[[i]])*log(n) if(det(hess) > 0){ qbic <- summary(mle)@m2logL+log(det(hess)) }else{ qbic <- summary(mle)@m2logL+length(swbeta[[i]])*log(n) } } if(is.matrix(data) == FALSE && Levy == TRUE){ aic <- summary(mle)@m2logL+length(swbeta[[i]])*((1/yuima@sampling@delta)*pena.aic(yuima,data,coef(mle),4)-(pena.aic(yuima,data,coef(mle),2))^2) }else{ aic <- summary(mle)@m2logL+2*length(swbeta[[i]]) } Esti1 <- c(Esti1, esti) BIC1 <- c(BIC1, bic) QBIC1 <- c(QBIC1, qbic) AIC1 <- c(AIC1, aic) } BIC.opt1 <- which.min(BIC1) QBIC.opt1 <- which.min(QBIC1) AIC.opt1 <- which.min(AIC1) ## Names for(i in 1:length(diff)){ names(Esti1)[i] <- paste("scale", i, sep = "_") names(BIC1)[i] <- paste("scale", i, sep = "_") names(QBIC1)[i] <- paste("scale", i, sep = "_") names(AIC1)[i] <- paste("scale", i, sep = "_") } ## Model weights if(weight == TRUE){ BIC.weight1 <- exp(-(1/2)*(BIC1-BIC1[BIC.opt1]))/sum(exp(-(1/2)*(BIC1-BIC1[BIC.opt1]))) QBIC.weight1 <- exp(-(1/2)*(QBIC1-QBIC1[QBIC.opt1]))/sum(exp(-(1/2)*(QBIC1-QBIC1[QBIC.opt1]))) AIC.weight1 <- exp(-(1/2)*(AIC1-AIC1[AIC.opt1]))/sum(exp(-(1/2)*(AIC1-AIC1[AIC.opt1]))) for(i in 1:length(diff)){ names(BIC.weight1)[i] <- paste("scale", i, sep = "_") names(QBIC.weight1)[i] <- paste("scale", i, sep = "_") names(AIC.weight1)[i] <- paste("scale", i, sep = "_") } } # Second step ## Use the selection results of first step diff.row.bic <- length(yuimas1[[BIC.opt1]]@model@diffusion) Diff.esti.bic <- NULL Esti1.chr.bic <- as.character(Esti1[[BIC.opt1]]) Diff.esti.bic <- diff[[BIC.opt1]] for(i in 1:diff.row.bic){ if(length(Esti1.chr.bic) == 1){ Diff.esti.bic.sub <- gsub(swbeta[[BIC.opt1]][1], Esti1.chr.bic[1], yuimas1[[BIC.opt1]]@model@diffusion[[i]]) }else{ Diff.esti.bic.sub <- gsub(swbeta[[BIC.opt1]][1], Esti1.chr.bic[1], yuimas1[[BIC.opt1]]@model@diffusion[[i]]) for(j in 1:(length(Esti1.chr.bic)-1)){ Diff.esti.bic.sub <- gsub(swbeta[[BIC.opt1]][(j+1)], Esti1.chr.bic[(j+1)], Diff.esti.bic.sub) } } # if(class(Diff.esti.bic) == "character"){ if(inherits(Diff.esti.bic, "character")){ Diff.esti.bic <- Diff.esti.bic.sub } else { Diff.esti.bic[i,] <- Diff.esti.bic.sub } } diff.row.qbic <- length(yuimas1[[QBIC.opt1]]@model@diffusion) Diff.esti.qbic <- NULL Esti1.chr.qbic <- as.character(Esti1[[QBIC.opt1]]) Diff.esti.qbic <- diff[[QBIC.opt1]] for(i in 1:diff.row.qbic){ if(length(Esti1.chr.qbic) == 1){ Diff.esti.qbic.sub <- gsub(swbeta[[QBIC.opt1]][1], Esti1.chr.qbic[1], yuimas1[[QBIC.opt1]]@model@diffusion[[i]]) }else{ Diff.esti.qbic.sub <- gsub(swbeta[[QBIC.opt1]][1], Esti1.chr.qbic[1], yuimas1[[QBIC.opt1]]@model@diffusion[[i]]) for(j in 1:(length(Esti1.chr.qbic)-1)){ Diff.esti.qbic.sub <- gsub(swbeta[[QBIC.opt1]][(j+1)], Esti1.chr.qbic[(j+1)], Diff.esti.qbic.sub) } } #if(class(Diff.esti.qbic) == "character"){ if(inherits(Diff.esti.qbic,"character")){ Diff.esti.qbic <- Diff.esti.qbic.sub } else { Diff.esti.qbic[i,] <- Diff.esti.qbic.sub } } diff.row.aic <- length(yuimas1[[AIC.opt1]]@model@diffusion) Diff.esti.aic <- NULL Esti1.chr.aic <- as.character(Esti1[[AIC.opt1]]) Diff.esti.aic <- diff[[AIC.opt1]] for(i in 1:diff.row.aic){ if(length(Esti1.chr.aic) == 1){ Diff.esti.aic.sub <- gsub(swbeta[[AIC.opt1]][1], Esti1.chr.aic[1], yuimas1[[AIC.opt1]]@model@diffusion[[i]]) }else{ Diff.esti.aic.sub <- gsub(swbeta[[AIC.opt1]][1], Esti1.chr.aic[1], yuimas1[[AIC.opt1]]@model@diffusion[[i]]) for(j in 1:(length(Esti1.chr.aic)-1)){ Diff.esti.aic.sub <- gsub(swbeta[[AIC.opt1]][(j+1)], Esti1.chr.aic[(j+1)], Diff.esti.aic.sub) } } #if(class(Diff.esti.aic) == "character"){ if(inherits(Diff.esti.aic, "character")){ Diff.esti.aic <- Diff.esti.aic.sub } else { Diff.esti.aic[i,] <- Diff.esti.aic.sub } } yuimas2.bic <- yuimas2.qbic <- yuimas2.aic <- swalpha <- NULL for(i in 1:length(drif)){ ## Candidate models if(is.matrix(data) == FALSE){ mod.bic <- setModel(drift = drif[[i]], diffusion = Diff.esti.bic, hurst = settings[[1]], measure = settings[[2]], measure.type = settings[[3]], state.variable = settings[[4]], jump.variable = settings[[5]], time.variable = settings[[6]], solve.variable = settings[[7]]) mod.qbic <- setModel(drift = drif[[i]], diffusion = Diff.esti.qbic, hurst = settings[[1]], measure = settings[[2]], measure.type = settings[[3]], state.variable = settings[[4]], jump.variable = settings[[5]], time.variable = settings[[6]], solve.variable = settings[[7]]) mod.aic <- setModel(drift = drif[[i]], diffusion = Diff.esti.aic, hurst = settings[[1]], measure = settings[[2]], measure.type = settings[[3]], state.variable = settings[[4]], jump.variable = settings[[5]], time.variable = settings[[6]], solve.variable = settings[[7]]) n <- length(data)-1 modsamp <- setSampling(Terminal = Terminal, n = n) modyuima.bic <- setYuima(model = mod.bic, sampling = modsamp) modyuima.qbic <- setYuima(model = mod.qbic, sampling = modsamp) modyuima.aic <- setYuima(model = mod.aic, sampling = modsamp) sub.zoo.data.bic <- list(zoo(x = data, order.by = modyuima.bic@sampling@grid[[1]])) sub.zoo.data.qbic <- list(zoo(x = data, order.by = modyuima.qbic@sampling@grid[[1]])) sub.zoo.data.aic <- list(zoo(x = data, order.by = modyuima.aic@sampling@grid[[1]])) names(sub.zoo.data.bic)[1] <- names(sub.zoo.data.qbic)[1] <- names(sub.zoo.data.aic)[1] <- "Series 1" }else{ mod.bic <- setModel(drift = drif[[i]], diffusion = Diff.esti.bic, hurst = settings[[1]], measure = settings[[2]], measure.type = settings[[3]], state.variable = settings[[4]], jump.variable = settings[[5]], time.variable = settings[[6]], solve.variable = settings[[7]]) mod.qbic <- setModel(drift = drif[[i]], diffusion = Diff.esti.qbic, hurst = settings[[1]], measure = settings[[2]], measure.type = settings[[3]], state.variable = settings[[4]], jump.variable = settings[[5]], time.variable = settings[[6]], solve.variable = settings[[7]]) mod.aic <- setModel(drift = drif[[i]], diffusion = Diff.esti.aic, hurst = settings[[1]], measure = settings[[2]], measure.type = settings[[3]], state.variable = settings[[4]], jump.variable = settings[[5]], time.variable = settings[[6]], solve.variable = settings[[7]]) n <- nrow(data)-1 modsamp <- setSampling(Terminal = Terminal, n = n) modyuima.bic <- setYuima(model = mod.bic, sampling = modsamp) modyuima.qbic <- setYuima(model = mod.qbic, sampling = modsamp) modyuima.aic <- setYuima(model = mod.bic, sampling = modsamp) sub.zoo.data.bic <- sub.zoo.data.qbic <- sub.zoo.data.aic <- list() for(j in 1:ncol(data)){ sub.zoo.data.bic <- c(sub.zoo.data.bic, list(zoo(x = data[,j], order.by = modyuima.bic@sampling@grid[[1]]))) sub.zoo.data.qbic <- c(sub.zoo.data.qbic, list(zoo(x = data[,j], order.by = modyuima.qbic@sampling@grid[[1]]))) sub.zoo.data.aic <- c(sub.zoo.data.aic, list(zoo(x = data[,j], order.by = modyuima.aic@sampling@grid[[1]]))) names(sub.zoo.data.bic)[j] <- names(sub.zoo.data.qbic)[j] <- names(sub.zoo.data.aic)[j] <- paste("Series", j) } } modyuima.bic@[email protected] <- sub.zoo.data.bic modyuima.qbic@[email protected] <- sub.zoo.data.qbic modyuima.aic@[email protected] <- sub.zoo.data.aic yuimas2.bic <- c(yuimas2.bic, list(modyuima.bic)) yuimas2.qbic <- c(yuimas2.qbic, list(modyuima.qbic)) yuimas2.aic <- c(yuimas2.aic, list(modyuima.aic)) ## Model comparison swalpha <- c(swalpha, list(modyuima.bic@model@parameter@drift)) para.number.init <- match(swalpha[[i]], names(start)) para.number.low <- match(swalpha[[i]], names(lower)) para.number.upp <- match(swalpha[[i]], names(upper)) para.start <- NULL para.lower <- NULL para.upper <- NULL for(j in 1:length(swalpha[[i]])){ para.start <- c(para.start, list(start[[para.number.init[j]]])) para.lower <- c(para.lower, list(lower[[para.number.low[j]]])) para.upper <- c(para.upper, list(upper[[para.number.upp[j]]])) } names(para.start) <- swalpha[[i]] names(para.lower) <- swalpha[[i]] names(para.upper) <- swalpha[[i]] mle.bic <- qmle(modyuima.bic, start = para.start, lower = para.lower, upper = para.upper, method = "L-BFGS-B", rcpp = rcpp) mle.qbic <- qmle(modyuima.qbic, start = para.start, lower = para.lower, upper = para.upper, method = "L-BFGS-B", rcpp = rcpp) mle.aic <- qmle(modyuima.aic, start = para.start, lower = para.lower, upper = para.upper, method = "L-BFGS-B", rcpp = rcpp) hess2 <- mle.qbic@details$hessian esti.bic <- list(coef(mle.bic)) esti.qbic <- list(coef(mle.qbic)) esti.aic <- list(coef(mle.aic)) names(esti.bic[[1]]) <- names(esti.qbic[[1]]) <- names(esti.aic[[1]]) <- swalpha[[i]] bic <- summary(mle.bic)@m2logL+length(swalpha[[i]])*log(Terminal) if(det(hess2) > 0){ qbic <- summary(mle.qbic)@m2logL+log(det(hess2)) }else{ qbic <- summary(mle.qbic)@m2logL+length(swalpha[[i]])*log(Terminal) } aic <- summary(mle.aic)@m2logL+2*length(swalpha[[i]]) Esti2.bic <- c(Esti2.bic, esti.bic) Esti2.qbic <- c(Esti2.qbic, esti.qbic) Esti2.aic <- c(Esti2.aic, esti.aic) BIC2 <- c(BIC2, bic) QBIC2 <- c(QBIC2, qbic) AIC2 <- c(AIC2, aic) } BIC.opt2 <- which.min(BIC2) QBIC.opt2 <- which.min(QBIC2) AIC.opt2 <- which.min(AIC2) ## Names for(i in 1:length(drif)){ names(Esti2.bic)[i] <- paste("drift", i, sep = "_") names(Esti2.qbic)[i] <- paste("drift", i, sep = "_") names(Esti2.aic)[i] <- paste("drift", i, sep = "_") names(BIC2)[i] <- paste("drift", i, sep = "_") names(QBIC2)[i] <- paste("drift", i, sep = "_") names(AIC2)[i] <- paste("drift", i, sep = "_") } ## Model weights if(weight == TRUE){ BIC.weight.full <- QBIC.weight.full <- AIC.weight.full <- matrix(0, length(drif), length(diff)) for(i in 1:length(diff)){ diff.row <- length(yuimas1[[i]]@model@diffusion) Esti1.chr <- as.character(Esti1[[i]]) Diff.esti <- diff[[i]] for(j in 1:diff.row){ if(length(Esti1.chr) == 1){ Diff.esti.sub <- gsub(swbeta[[i]][1], Esti1.chr[1], yuimas1[[i]]@model@diffusion[[j]]) }else{ Diff.esti.sub <- gsub(swbeta[[i]][1], Esti1.chr[1], yuimas1[[i]]@model@diffusion[[j]]) for(k in 1:(length(Esti1.chr)-1)){ Diff.esti.sub <- gsub(swbeta[[i]][(k+1)], Esti1.chr[(k+1)], Diff.esti.sub) } } #if(class(Diff.esti) == "character"){ if(inherits(Diff.esti, "character")){ Diff.esti <- Diff.esti.sub } else { Diff.esti[j,] <- Diff.esti.sub } } BIC2.sub <- QBIC2.sub <- AIC2.sub <- NULL for(j in 1:length(drif)){ if(is.matrix(data) == FALSE){ mod <- setModel(drift = drif[[j]], diffusion = Diff.esti, hurst = settings[[1]], measure = settings[[2]], measure.type = settings[[3]], state.variable = settings[[4]], jump.variable = settings[[5]], time.variable = settings[[6]], solve.variable = settings[[7]]) n <- length(data)-1 modsamp <- setSampling(Terminal = Terminal, n = n) modyuima <- setYuima(model = mod, sampling = modsamp) sub.zoo.data <- list(zoo(x = data, order.by = modyuima@sampling@grid[[1]])) names(sub.zoo.data)[1] <- "Series 1" }else{ mod <- setModel(drift = drif[[j]], diffusion = Diff.esti, hurst = settings[[1]], measure = settings[[2]], measure.type = settings[[3]], state.variable = settings[[4]], jump.variable = settings[[5]], time.variable = settings[[6]], solve.variable = settings[[7]]) n <- nrow(data)-1 modsamp <- setSampling(Terminal = Terminal, n = n) modyuima <- setYuima(model = mod, sampling = modsamp) sub.zoo.data <- list() for(k in 1:ncol(data)){ sub.zoo.data <- c(sub.zoo.data, list(zoo(x = data[,k], order.by = modyuima@sampling@grid[[1]]))) names(sub.zoo.data)[k] <- paste("Series", k) } } modyuima@[email protected] <- sub.zoo.data para.number.init <- match(swalpha[[j]], names(start)) para.number.low <- match(swalpha[[j]], names(lower)) para.number.upp <- match(swalpha[[j]], names(upper)) para.start <- NULL para.lower <- NULL para.upper <- NULL for(k in 1:length(swalpha[[j]])){ para.start <- c(para.start, list(start[[para.number.init[k]]])) para.lower <- c(para.lower, list(lower[[para.number.low[k]]])) para.upper <- c(para.upper, list(upper[[para.number.upp[k]]])) } names(para.start) <- swalpha[[j]] names(para.lower) <- swalpha[[j]] names(para.upper) <- swalpha[[j]] mle.weight <- qmle(modyuima, start = para.start, lower = para.lower, upper = para.upper, method = "L-BFGS-B", rcpp = rcpp) hess.weight <- mle.weight@details$hessian esti.weight <- list(coef(mle.weight)) names(esti.weight[[1]]) <- swalpha[[j]] bic <- summary(mle.weight)@m2logL+length(swalpha[[j]])*log(Terminal) if(det(hess.weight) > 0){ qbic <- summary(mle.weight)@m2logL+log(det(hess.weight)) }else{ qbic <- summary(mle.weight)@m2logL+length(swalpha[[j]])*log(Terminal) } aic <- summary(mle.weight)@m2logL+2*length(swalpha[[j]]) BIC2.sub <- c(BIC2.sub, bic) QBIC2.sub <- c(QBIC2.sub, qbic) AIC2.sub <- c(AIC2.sub, aic) } BIC2.sub.opt <- which.min(BIC2.sub) QBIC2.sub.opt <- which.min(QBIC2.sub) AIC2.sub.opt <- which.min(AIC2.sub) BIC.weight2 <- exp(-(1/2)*(BIC2.sub-BIC2.sub[BIC2.sub.opt]))/sum(exp(-(1/2)*(BIC2.sub-BIC2.sub[BIC2.sub.opt]))) QBIC.weight2 <- exp(-(1/2)*(QBIC2.sub-QBIC2.sub[BIC2.sub.opt]))/sum(exp(-(1/2)*(QBIC2.sub-QBIC2.sub[QBIC2.sub.opt]))) AIC.weight2 <- exp(-(1/2)*(AIC2.sub-AIC2.sub[AIC2.sub.opt]))/sum(exp(-(1/2)*(AIC2.sub-AIC2.sub[AIC2.sub.opt]))) BIC.weight.full[,i] <- BIC.weight1[i]*BIC.weight2 QBIC.weight.full[,i] <- QBIC.weight1[i]*QBIC.weight2 AIC.weight.full[,i] <- AIC.weight1[i]*AIC.weight2 } colname.weight <- numeric(length(diff)) rowname.weight <- numeric(length(drif)) for(i in 1:length(diff)){ colname.weight[i] <- paste("scale", i, sep = "_") } colnames(BIC.weight.full) <- colname.weight colnames(QBIC.weight.full) <- colname.weight colnames(AIC.weight.full) <- colname.weight for(i in 1:length(drif)){ rowname.weight[i] <- paste("drift", i, sep = "_") } rownames(BIC.weight.full) <- rowname.weight rownames(QBIC.weight.full) <- rowname.weight rownames(AIC.weight.full) <- rowname.weight } ## Results diff.copy <- diff drif.copy <- drif for(i in 1:length(diff)){ names(diff.copy)[i] <- paste("scale", i, sep = "_") } for(i in 1:length(drif)){ names(drif.copy)[i] <- paste("drift", i, sep = "_") } BIC <- list(first = BIC1, second = BIC2) QBIC <- list(first = QBIC1, second = QBIC2) AIC <- list(first = AIC1, second = AIC2) if(is.matrix(data) == FALSE && Levy == TRUE){ Esti <- list(first = Esti1, second.bic = NULL, second.qbic = Esti2.qbic, second.aic = Esti2.aic) }else{ Esti <- list(first = Esti1, second.bic = Esti2.bic, second.qbic = Esti2.qbic, second.aic = Esti2.aic) } call <- match.call() model.coef <- list(drift = drif.copy, scale = diff.copy) bic.selected.coeff <- list(drift = drif[[BIC.opt2]], scale = diff[[BIC.opt1]]) qbic.selected.coeff <- list(drift = drif[[QBIC.opt2]], scale = diff[[QBIC.opt1]]) aic.selected.coeff <- list(drift = drif[[AIC.opt2]], scale = diff[[AIC.opt1]]) if(is.matrix(data) == FALSE && Levy == TRUE){ ic.selected <- list(BIC = NULL, QBIC = qbic.selected.coeff, AIC = aic.selected.coeff) }else{ ic.selected <- list(BIC = bic.selected.coeff, QBIC = qbic.selected.coeff, AIC = aic.selected.coeff) } if(weight == TRUE){ if(is.matrix(data) == FALSE && Levy == TRUE){ ak.weight <- list(BIC = NULL, QBIC = QBIC.weight.full, AIC = AIC.weight.full) }else{ ak.weight <- list(BIC = BIC.weight.full, QBIC = QBIC.weight.full, AIC = AIC.weight.full) } }else{ ak.weight <- NULL } if(is.matrix(data) == FALSE && Levy == TRUE){ final_res <- list(call = call, model = model.coef, par = Esti, BIC = NULL, QBIC = QBIC, AIC = AIC, weight = ak.weight, selected = ic.selected) }else{ final_res <- list(call = call, model = model.coef, par = Esti, BIC = BIC, QBIC = QBIC, AIC = AIC, weight = ak.weight, selected = ic.selected) } } class(final_res) <- "yuima.ic" return(final_res) } print.yuima.ic <- function(x, ...){ cat("\nCall:\n") print(x$call) cat("\nInformation criteria:\n") cat("\nBIC:\n") print(x$BIC) cat("\nQBIC:\n") print(x$QBIC) cat("\nAIC:\n") print(x$AIC) #if(class(x$AIC) == "matrix"){ #if(is.matrix(x$AIC)){ # fixed by YK # if(!is.null(x$AIC)){ # cat("\nAIC:\n") # print(x$AIC) # } #} #if(class(x$AIC) == "list"){ #if(is.list(class(x$AIC))){ # fixed by YK # if(!is.null(x$AIC$first)){ # cat("\nAIC:\n") # print(x$AIC) # } #} invisible(x) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/IC.R
JBtest<-function(yuima,start,lower,upper,alpha,skewness=TRUE,kurtosis=TRUE,withdrift=FALSE){ ## The new options "skewness" and "kurtosis" are added (3/27). ## Multivariate Mardia's skewness is tentativity written, not work now (5/30), workable (6/6)!. if(yuima@[email protected] == 1){ data <- get.zoo.data(yuima) s.size<-yuima@sampling@n modelstate<-yuima@[email protected] modeltime<-yuima@[email protected] DRIFT<-yuima@model@drift DIFFUSION<-yuima@model@diffusion PARLENGS<-length(yuima@model@parameter@drift)+length(yuima@model@parameter@diffusion) XINIT<-yuima@model@xinit X<-as.numeric(data[[1]]) dX <- abs(diff(X)) odX <- sort(dX, decreasing=TRUE) plot(yuima,main="Original path") abline(0,0,lty=5) pX<-X[1:(s.size-1)] sY<-as.numeric(data[[1]]) derDIFFUSION<-D(DIFFUSION[[1]],modelstate) tmp.env<-new.env() INTENSITY<-eval(yuima@model@measure$intensity) inc<-double(s.size-1) inc<-X[2:(s.size)]-pX preservedinc<-inc ainc<-abs(inc) oinc<-sort(ainc,decreasing=TRUE) if(length(yuima@model@parameter@measure)!=0){ extp <- match(yuima@model@parameter@measure, yuima@model@parameter@all) extplow <- match(yuima@model@parameter@measure, names(lower)) extpupp <- match(yuima@model@parameter@measure, names(upper)) extpsta <- match(yuima@model@parameter@measure, names(start)) lower <- lower[-extplow] upper <- upper[-extpupp] start <- start[-extpsta] yuima@model@parameter@all <- yuima@model@parameter@all[-extp] yuima@model@parameter@measure <- as.character("abcdefg") yuima@model@measure$df$expr <- expression(dunif(z,abcdefg,10)) lower <- c(lower,abcdefg=2-10^(-2)) upper <- c(upper,abcdefg=2+10^(-2)) start <- c(start,abcdefg=2) yuima@model@parameter@all <- c(yuima@model@parameter@all,as.character("abcdefg")) }else{ yuima@model@parameter@measure <- as.character("abcdefg") yuima@model@measure$df$expr <- expression(dunif(z,abcdefg,10)) lower <- c(lower,abcdefg=2-10^(-2)) upper <- c(upper,abcdefg=2+10^(-2)) start <- c(start,abcdefg=2) yuima@model@parameter@all <- c(yuima@model@parameter@all,as.character("abcdefg")) } #yuima@model@drift<-expression((0)) qmle<-qmle(yuima, start = start, lower = lower, upper = upper,threshold = oinc[1]+1) # initial estimation parameter<-yuima@model@parameter@all mp<-match(names(qmle@coef),parameter) esort <- qmle@coef[order(mp)] for(i in 1:length(parameter)) { assign(parameter[i],esort[[i]],envir=tmp.env) } resi<-double(s.size-1) derv<-double(s.size-1) total<-c() j.size<-c() assign(modeltime,yuima@sampling@delta,envir=tmp.env) h<-yuima@sampling@delta assign(modelstate,pX,envir=tmp.env) diff.term<-eval(DIFFUSION[[1]],envir=tmp.env) drif.term<-eval(DRIFT,envir=tmp.env) if(length(diff.term)==1){ diff.term <- rep(diff.term, s.size) } if(length(drif.term)==1){ drif.term <- rep(drif.term, s.size) } # vectorization (note. if an expression type object does not include state.variable, the length of the item after "eval" operation is 1.) for(s in 1:(s.size-1)){ nova<-sqrt((diff.term)^2) # normalized variance resi[s]<-(1/(nova[s]*sqrt(h)))*(inc[s]-h*withdrift*drif.term[s]) } assign(modelstate,pX,envir=tmp.env) derv<-eval(derDIFFUSION,envir=tmp.env) if(length(derv)==1){ derv<-rep(derv,s.size) # vectorization } mresi<-mean(resi) vresi<-mean((resi-mresi)^2) snr<-(resi-mresi)/sqrt(vresi) isnr<-snr if(skewness==TRUE&kurtosis==FALSE){ bias<-3*sqrt(h)*sum(derv) JB<-1/(6*s.size)*(sum(snr^3)-bias)^2 rqmle<-list() # jump removed qmle statis<-c() # the value of JB statistics limJB<-5*INTENSITY*yuima@sampling@Terminal # the limit of JB repetition klarinc<-numeric(floor(limJB)) k<-1 if(JB<=qchisq(alpha,df=1,ncp=0,lower.tail=FALSE,log.p=FALSE)){ print("There is no jump.") result<-list(OGQMLE=qmle@coef[1:PARLENGS]) }else{ while(JB>qchisq(alpha,df=1,ncp=0,lower.tail=FALSE,log.p=FALSE)) { klarinc[k]<-which(ainc==oinc[k]) ## detect the largest increment j.size<-append(j.size,round(preservedinc[klarinc[k]],digits=3)) rqmle[[k]]<-qmle(yuima, start = start, lower = lower, upper = upper, threshold = oinc[k]-(oinc[k]-oinc[k+1])/2)@coef ## calculate the modified qmle mp<-match(names(rqmle[[k]]),parameter) resort <- rqmle[[k]][order(mp)] for(i in 1:length(parameter)) { assign(parameter[i],resort[[i]],envir=tmp.env) } diff.term<-eval(DIFFUSION[[1]],envir=tmp.env) drif.term<-eval(DRIFT,envir=tmp.env) if(length(diff.term)==1){ diff.term <- rep(diff.term, s.size-1) } if(length(drif.term)==1){ drif.term <- rep(drif.term, s.size-1) } # vectorization for(s in 1:(s.size-1)){ nova<-sqrt((diff.term)^2) # normalized variance resi[s]<-(1/(nova[s]*sqrt(h)))*(inc[s]-h*withdrift*drif.term[s]) } ## rebuild Euler-residuals derv<-eval(derDIFFUSION,envir=tmp.env) if(length(derv)==1){ derv<-rep(derv,s.size) # vectorization } ## rebuild derivative vector resi[klarinc]<-0 derv[klarinc]<-0 mresi<-mean(resi) vresi<-mean((resi-mresi)^2) snr<-(resi-mresi)/sqrt(vresi) ## rebuild self-normalized residuals snr[klarinc]<-0 bias<-3*sqrt(h)*sum(derv) JB<-1/(6*(s.size-k))*(sum(snr^3)-bias)^2 jump.point<-klarinc[k] points(jump.point*h,sY[klarinc[k]],col="red", type="h", lty=3, lwd=2) points(jump.point*h,sY[klarinc[k]],col="red", pch="+",lwd=2) points(jump.point*h,0,col="red", pch=17,cex=1.5) total<-append(total,as.character(round(jump.point*h,digits=3))) statis<-append(statis,JB) k<-k+1 if(k == floor(limJB)) { warning("Removed jumps seems to be too many. Change intensity for more removal.") break } } par(mfrow=c(2,2)) # plot(isnr,main="Raw self-normalized residual") par(new=T) abline(0,0,lty=5,col="green") snr <- snr[-(klarinc)] # h <- dpih(snr) # bins <- seq(min(snr)-0.1, max(snr)+0.1+h, by=h) # hist(snr, prob=1, breaks=bins,xlim=c(-3,3),ylim=c(0,1)) hist(snr, freq = FALSE, breaks = "freedman-diaconis", xlim=c(min(snr),max(snr)),ylim=c(0,1)) xval <- seq(min(snr),max(snr),0.01) # to add plot the corresponding density lines(xval,dnorm(xval,0,1),xlim=c(-3,3),ylim=c(0,1),col="red",main="Jump removed self-normalized residual") if(k > 2){ estimat<-matrix(0,PARLENGS,k-1) for(i in 1:(k-1)){ for(j in 1:PARLENGS){ estimat[j,i]<-rqmle[[i]][j] } } oo<-match(parameter,names(estimat[1,])) parameter<-parameter[order(oo)] for(i in 1:PARLENGS){ plot(estimat[i,], main=paste("Transition of",parameter[i]), xlab="The number of trial",ylab = "Estimated value",type="l",xlim = c(1,k-1),xaxp = c(1,k-1,k-2)) } plot(log(statis),main="Transition of the logJB statistics", xlab="The number of trial",ylab="log JB" ,type="l",xlim = c(1,k-1),xaxp = c(1,k-1,k-2)) par(new=T) abline(log(qchisq(alpha,df=1,ncp=0,lower.tail=FALSE,log.p=FALSE)),0,lty=5,col="red") } names(j.size)<-total removed<-j.size resname<-c("Jump size") names(resname)<-"Jump time" removed<-append(resname,removed) result<-list(Removed=removed,OGQMLE=qmle@coef[1:PARLENGS],JRGQMLE=rqmle[[k-1]][1:PARLENGS]) } }else if(skewness==FALSE&kurtosis==TRUE){ JB<-1/(24*s.size)*(sum(snr^4-3))^2 fbias<-rep(3,s.size-1) rqmle<-list() # jump removed qmle statis<-c() # the value of JB statistics limJB<-5*INTENSITY*yuima@sampling@Terminal # the limit of JB repetition klarinc<-numeric(floor(limJB)) k<-1 if(JB<=qchisq(alpha,df=1,ncp=0,lower.tail=FALSE,log.p=FALSE)){ print("There is no jump.") result<-list(OGQMLE=qmle@coef[1:PARLENGS]) }else{ while(JB>qchisq(alpha,df=1,ncp=0,lower.tail=FALSE,log.p=FALSE)) { klarinc[k]<-which(ainc==oinc[k]) ## detect the largest increment j.size<-append(j.size,round(preservedinc[klarinc[k]],digits=3)) rqmle[[k]]<-qmle(yuima, start = start, lower = lower, upper = upper, threshold = oinc[k]-(oinc[k]-oinc[k+1])/2)@coef ## calculate the modified qmle mp<-match(names(rqmle[[k]]),parameter) resort <- rqmle[[k]][order(mp)] for(i in 1:length(parameter)) { assign(parameter[i],resort[[i]],envir=tmp.env) } diff.term<-eval(DIFFUSION[[1]],envir=tmp.env) drif.term<-eval(DRIFT,envir=tmp.env) if(length(diff.term)==1){ diff.term <- rep(diff.term, s.size-1) } if(length(drif.term)==1){ drif.term <- rep(drif.term, s.size-1) } # vectorization for(s in 1:(s.size-1)){ nova<-sqrt((diff.term)^2) # normalized variance resi[s]<-(1/(nova[s]*sqrt(h)))*(inc[s]-h*withdrift*drif.term[s]) } ## rebuild Euler-residuals derv<-eval(derDIFFUSION,envir=tmp.env) if(length(derv)==1){ derv<-rep(derv,s.size) # vectorization } resi[klarinc]<-0 derv[klarinc]<-0 mresi<-mean(resi) vresi<-mean((resi-mresi)^2) snr<-(resi-mresi)/sqrt(vresi) ## rebuild self-normalized residuals snr[klarinc]<-0 fbias[klarinc]<-0 JB<-1/(24*(s.size-k))*(sum(snr^4-fbias))^2 jump.point<-klarinc[k] points(jump.point*h,sY[klarinc[k]],col="red", type="h", lty=3, lwd=2) points(jump.point*h,sY[klarinc[k]],col="red", pch="+",lwd=2) points(jump.point*h,0,col="red", pch=17,cex=1.5) total<-append(total,as.character(round(jump.point*h,digits=3))) statis<-append(statis,JB) k<-k+1 if(k == floor(limJB)) { warning("Removed jumps seems to be too many. Change intensity for more removal.") break } } par(mfrow=c(2,2)) # plot(isnr,main="Raw self-normalized residual") par(new=T) abline(0,0,lty=5,col="green") snr <- snr[-(klarinc)] # h <- dpih(snr) # bins <- seq(min(snr)-0.1, max(snr)+0.1+h, by=h) # hist(snr, prob=1, breaks=bins,xlim=c(-3,3),ylim=c(0,1)) hist(snr, freq = FALSE, breaks = "freedman-diaconis", xlim=c(min(snr),max(snr)),ylim=c(0,1)) xval <- seq(min(snr),max(snr),0.01) # to add plot the corresponding density lines(xval,dnorm(xval,0,1),xlim=c(-3,3),ylim=c(0,1),col="red",main="Jump removed self-normalized residual") if(k > 2){ estimat<-matrix(0,PARLENGS,k-1) for(i in 1:(k-1)){ for(j in 1:PARLENGS){ estimat[j,i]<-rqmle[[i]][j] } } oo<-match(parameter,names(estimat[1,])) parameter<-parameter[order(oo)] for(i in 1:PARLENGS){ plot(estimat[i,], main=paste("Transition of",parameter[i]), xlab="The number of trial",ylab = "Estimated value",type="l",xlim = c(1,k-1),xaxp = c(1,k-1,k-2)) } plot(log(statis),main="Transition of the logJB statistics", xlab="The number of trial",ylab="log JB" ,type="l",xlim = c(1,k-1),xaxp = c(1,k-1,k-2)) par(new=T) abline(log(qchisq(alpha,df=1,ncp=0,lower.tail=FALSE,log.p=FALSE)),0,lty=5,col="red") } names(j.size)<-total removed<-j.size resname<-c("Jump size") names(resname)<-"Jump time" removed<-append(resname,removed) result<-list(Removed=removed,OGQMLE=qmle@coef[1:PARLENGS],JRGQMLE=rqmle[[k-1]][1:PARLENGS]) } }else{ fbias<-rep(3,s.size-1) bias<-3*sqrt(h)*sum(derv) JB<-1/(6*s.size)*(sum(snr^3)-bias)^2+1/(24*s.size)*(sum(snr^4-fbias))^2 rqmle<-list() # jump removed qmle statis<-c() # the value of JB statistics limJB<-5*INTENSITY*yuima@sampling@Terminal # the limit of JB repetition klarinc<-numeric(floor(limJB)) k<-1 if(JB<=qchisq(alpha,df=2,ncp=0,lower.tail=FALSE,log.p=FALSE)){ print("There is no jump.") result<-list(OGQMLE=qmle@coef[1:PARLENGS]) }else{ while(JB>qchisq(alpha,df=2,ncp=0,lower.tail=FALSE,log.p=FALSE)) { klarinc[k]<-which(ainc==oinc[k]) ## detect the largest increment j.size<-append(j.size,round(preservedinc[klarinc[k]],digits=3)) rqmle[[k]]<-qmle(yuima, start = start, lower = lower, upper = upper, threshold = oinc[k]-(oinc[k]-oinc[k+1])/2)@coef ## calculate the modified qmle mp<-match(names(rqmle[[k]]),parameter) resort <- rqmle[[k]][order(mp)] for(i in 1:length(parameter)) { assign(parameter[i],resort[[i]],envir=tmp.env) } diff.term<-eval(DIFFUSION[[1]],envir=tmp.env) drif.term<-eval(DRIFT,envir=tmp.env) if(length(diff.term)==1){ diff.term <- rep(diff.term, s.size-1) } if(length(drif.term)==1){ drif.term <- rep(drif.term, s.size-1) } # vectorization for(s in 1:(s.size-1)){ nova<-sqrt((diff.term)^2) # normalized variance resi[s]<-(1/(nova[s]*sqrt(h)))*(inc[s]-h*withdrift*drif.term[s]) } ## rebuild Euler-residuals derv<-eval(derDIFFUSION,envir=tmp.env) if(length(derv)==1){ derv<-rep(derv,s.size) # vectorization } ## rebuild derivative vector resi[klarinc]<-0 derv[klarinc]<-0 mresi<-mean(resi) vresi<-mean((resi-mresi)^2) snr<-(resi-mresi)/sqrt(vresi) ## rebuild self-normalized residuals snr[klarinc]<-0 bias<-3*sqrt(h)*sum(derv) fbias[klarinc]<-0 JB<-1/(6*(s.size-k))*(sum(snr^3)-bias)^2+1/(24*(s.size-k))*(sum(snr^4-fbias))^2 jump.point<-klarinc[k] points(jump.point*h,sY[klarinc[k]],col="red", type="h", lty=3, lwd=2) points(jump.point*h,sY[klarinc[k]],col="red", pch="+",lwd=2) points(jump.point*h,0,col="red", pch=17,cex=1.5) total<-append(total,as.character(round(jump.point*h,digits=3))) statis<-append(statis,JB) k<-k+1 if(k == floor(limJB)) { warning("Removed jumps seems to be too many. Change intensity for more removal.") break } } par(mfrow=c(2,2)) # plot(isnr,main="Raw snr") par(new=T) abline(0,0,lty=5,col="green") snr <- snr[-(klarinc)] # h <- dpih(snr) # bins <- seq(min(snr)-0.1, max(snr)+0.1+h, by=h) # hist(snr, prob=1, breaks=bins,xlim=c(-3,3),ylim=c(0,1)) hist(snr, freq = FALSE, breaks = "freedman-diaconis", xlim=c(min(snr),max(snr)),ylim=c(0,1)) xval <- seq(min(snr),max(snr),0.01) # to add plot the corresponding density lines(xval,dnorm(xval,0,1),xlim=c(-3,3),ylim=c(0,1),col="red",main="Jump removed self-normalized residual") if(k > 2){ estimat<-matrix(0,PARLENGS,k-1) for(i in 1:(k-1)){ for(j in 1:PARLENGS){ estimat[j,i]<-rqmle[[i]][j] } } oo<-match(parameter,names(estimat[1,])) parameter<-parameter[order(oo)] for(i in 1:PARLENGS){ plot(estimat[i,], main=paste("Transition of",parameter[i]), xlab="The number of trial",ylab = "Estimated value",type="l",xlim = c(1,k-1),xaxp = c(1,k-1,k-2)) } plot(log(statis),main="Transition of the logJB statistics", xlab="The number of trial",ylab="log JB" ,type="l",xlim = c(1,k-1),xaxp = c(1,k-1,k-2)) par(new=T) abline(log(qchisq(alpha,df=2,ncp=0,lower.tail=FALSE,log.p=FALSE)),0,lty=5,col="red") } names(j.size)<-total removed<-j.size resname<-c("Jump size") names(resname)<-"Jump time" removed<-append(resname,removed) result<-list(Removed=removed,OGQMLE=qmle@coef[1:PARLENGS],JRGQMLE=rqmle[[k-1]][1:PARLENGS]) } } # }else{ # ## Multivariate version based on Mardia's kurtosis, not work now ! # DRIFT <- yuima@model@drift # DIFFUSION <- yuima@model@diffusion # d.size <- yuima@[email protected] # data <- matrix(0,length(yuima@[email protected][[1]]),d.size) # for(i in 1:d.size) data[,i] <- as.numeric(yuima@[email protected][[i]]) # dx_set <- as.matrix((data-rbind(numeric(d.size),as.matrix(data[-length(data[,1]),])))[-1,]) # preservedinc <- dx_set # ainc <- numeric(length(yuima@[email protected][[1]])-1) # for(i in 1:length(yuima@[email protected][[1]])-1){ # ainc[i] <- sqrt(t(dx_set[i,])%*%dx_set[i,]) # } # oinc<-sort(ainc,decreasing=TRUE) # qmle<-qmle(yuima, start = start, lower = lower, upper = upper,threshold = oinc[1]+1) # initial estimation # # parameter<-yuima@model@parameter@all # mp<-match(names(qmle@coef),parameter) # esort <- qmle@coef[order(mp)] # # tmp.env <- new.env() # for(i in 1:length(parameter)) # { # assign(parameter[i],esort[[i]],envir=tmp.env) # } # # noise_number <- yuima@[email protected] # # for(i in 1:d.size) assign(yuima@[email protected][i], data[-length(data[,1]),i], envir=tmp.env) # # d_b <- NULL # for(i in 1:d.size){ # if(length(eval(DRIFT[[i]],envir=tmp.env))==(length(data[,1])-1)){ # d_b[[i]] <- DRIFT[[i]] #this part of model includes "x"(state.variable) # } # else{ # if(is.na(c(DRIFT[[i]][2]))){ #ex. yuima@model@drift=expression(0) (we hope "expression((0))") # DRIFT[[i]] <- parse(text=paste(sprintf("(%s)", DRIFT[[i]])))[[1]] # } # d_b[[i]] <- parse(text=paste("(",DRIFT[[i]][2],")*rep(1,length(data[,1])-1)",sep="")) # #vectorization # } # } # # v_a<-matrix(list(NULL),d.size,noise_number) # for(i in 1:d.size){ # for(j in 1:noise_number){ # if(length(eval(DIFFUSION[[i]][[j]],envir=tmp.env))==(length(data[,1])-1)){ # v_a[[i,j]] <- DIFFUSION[[i]][[j]] #this part of model includes "x"(state.variable) # } # else{ # if(is.na(c(DIFFUSION[[i]][[j]][2]))){ # DIFFUSION[[i]][[j]] <- parse(text=paste(sprintf("(%s)", DIFFUSION[[i]][[j]])))[[1]] # } # v_a[[i,j]] <- parse(text=paste("(",DIFFUSION[[i]][[j]][2],")*rep(1,length(data[,1])-1)",sep="")) # #vectorization # } # } # } # # resi<-NULL # nvari<-matrix(0,d.size,noise_number) # drivec<-numeric(d.size) # for(k in 1:(length(data[,1])-1)){ # for(i in 1:d.size) # { # for(j in 1:noise_number){ # nvari[i,j]<-eval(v_a[[i,j]],envir=tmp.env)[k] # } # drivec[i]<-eval(d_b[[i]],envir=tmp.env)[k] # } # resi[[k]]<-1/sqrt(yuima@sampling@delta[[1]])*solve(t(nvari)%*%nvari)%*%t(nvari)%*%(dx_set[k,]-withdrift*drivec) # } # # mresi<-numeric(d.size) # for(k in 1:(length(data[,1])-1)){ # mresi<-mresi+resi[[k]] # } # mresi<-mresi/(length(data[,1])-1) # # svresi<-matrix(0,d.size,d.size) # for(k in 1:(length(data[,1])-1)){ # svresi<-svresi+(resi[[k]]-mresi)%*%t(resi[[k]]-mresi) # } # svresi<-svresi/(length(data[,1])-1) # # snr<-NULL # invsvresi<-solve(svresi) # U <- svd(invsvresi)$u # V <- svd(invsvresi)$v # D <- diag(sqrt(svd(invsvresi)$d)) # sqinvsvresi <- U %*% D %*% t(V) # for(k in 1:(length(data[,1])-1)){ # snr[[k]]<-sqinvsvresi%*%(resi[[k]]-mresi) # } # fourmom<-numeric(1) # for(k in 1:(length(data[,1])-1)){ # fourmom<-fourmom+(t(snr[[k]])%*%snr[[k]])^2 # } # # Mard<-1/((length(data[,1])-1)*8*d.size*(d.size+2))*(fourmom-(length(data[,1])-1)*d.size*(d.size+2))^2 # if(Mard<=qchisq(alpha,df=1,ncp=0,lower.tail=FALSE,log.p=FALSE)){ # print("There is no jump.") # }else{ # INTENSITY<-eval(yuima@model@measure$intensity) # limMard<-5*INTENSITY*yuima@sampling@Terminal[1] # # the limit of the Mardia's kurtosis based opration repetition # klarinc<-numeric(floor(limMard)) # statis<-c() # trial<-1 # jumpdec<-NULL # rqmle<<-NULL # result<-NULL # while((Mard>qchisq(alpha,df=1,ncp=0,lower.tail=FALSE,log.p=FALSE))){ # klarinc[trial]<-which(ainc==oinc[trial]) ## detect the largest increment # jumpdec[[trial]]<-preservedinc[klarinc[trial],] # rqmle[[trial]]<-qmle(yuima, start = start, lower = lower, upper = upper, threshold = oinc[trial]-(oinc[trial]-oinc[trial+1])/2)@coef # ## calculate the modified qmle # mp<-match(names(rqmle[[trial]]),parameter) # resort <- rqmle[[trial]][order(mp)] # # for(i in 1:length(parameter)) # { # assign(parameter[i],resort[[i]],envir=tmp.env) # } # # # d_b <- NULL # for(i in 1:d.size){ # if(length(eval(DRIFT[[i]],envir=tmp.env))==(length(data[,1])-1)){ # d_b[[i]] <- DRIFT[[i]] #this part of model includes "x"(state.variable) # } # else{ # if(is.na(c(DRIFT[[i]][2]))){ #ex. yuima@model@drift=expression(0) (we hope "expression((0))") # DRIFT[[i]] <- parse(text=paste(sprintf("(%s)", DRIFT[[i]])))[[1]] # } # d_b[[i]] <- parse(text=paste("(",DRIFT[[i]][2],")*rep(1,length(data[,1])-1)",sep="")) # #vectorization # } # } # # v_a<-matrix(list(NULL),d.size,noise_number) # for(i in 1:d.size){ # for(j in 1:noise_number){ # if(length(eval(DIFFUSION[[i]][[j]],envir=tmp.env))==(length(data[,1])-1)){ # v_a[[i,j]] <- DIFFUSION[[i]][[j]] #this part of model includes "x"(state.variable) # } # else{ # if(is.na(c(DIFFUSION[[i]][[j]][2]))){ # DIFFUSION[[i]][[j]] <- parse(text=paste(sprintf("(%s)", DIFFUSION[[i]][[j]])))[[1]] # } # v_a[[i,j]] <- parse(text=paste("(",DIFFUSION[[i]][[j]][2],")*rep(1,length(data[,1])-1)",sep="")) # #vectorization # } # } # } # # resi<-NULL # nvari<-matrix(0,d.size,noise_number) # drivec<-numeric(d.size) # # for(k in 1:(length(data[,1])-1)){ # for(i in 1:d.size) # { # for(j in 1:noise_number){ # nvari[i,j]<-eval(v_a[[i,j]],envir=tmp.env)[k] # } # drivec[i]<-eval(d_b[[i]],envir=tmp.env)[k] # } # if(sum(k == klarinc)==0) resi[[k]] <- 1/sqrt(yuima@sampling@delta[[1]])*solve(t(nvari)%*%nvari)%*%t(nvari)%*%(dx_set[k,]--withdrift*drivec) # else resi[[k]] <- numeric(d.size) # } # # mresi<-numeric(d.size) # for(k in 1:(length(data[,1])-1)){ # mresi<-mresi+resi[[k]] # } # mresi<-mresi/(length(data[,1])-1) # # svresi<-matrix(0,d.size,d.size) # for(k in 1:(length(data[,1])-1)){ # svresi<-svresi+(resi[[k]]-mresi)%*%t(resi[[k]]-mresi) # } # svresi<-svresi/(length(data[,1])-1) # # snr<-NULL # invsvresi<-solve(svresi) # U <- svd(invsvresi)$u # V <- svd(invsvresi)$v # D <- diag(sqrt(svd(invsvresi)$d)) # sqinvsvresi <- U %*% D %*% t(V) # for(k in 1:(length(data[,1])-1)){ # if(sum(k == klarinc)==0) snr[[k]]<-sqinvsvresi%*%(resi[[k]]-mresi) # else snr[[k]] <- numeric(d.size) # } # fourmom<-numeric(1) # for(k in 1:(length(data[,1])-1)){ # fourmom<-fourmom+(t(snr[[k]])%*%snr[[k]])^2 # } # # Mard<-1/((length(data[,1])-1-trial)*8*d.size*(d.size+2))*(fourmom-(length(data[,1])-1)*d.size*(d.size+2))^2 # statis[trial]<-Mard # trial<-trial+1 # if(trial == floor(limMard)) # { # warning("Removed jumps seems to be too many. Change intensity for more removal.") # result[[1]]<-jumpdec # result[[2]]<-rqmle[[trial-1]] # break # } # result[[1]]<-jumpdec # result[[2]]<-rqmle[[trial-1]] # } # } # } plot(odX, type="p", main="Ordered absolute-value increments with threshold", ylab="increment sizes") abline(odX[k-1],0,lty=5,col="red") # arrows(2*s.size/3,odX[k-1],2*s.size/3,odX[k-1]+2.5, col="red") text(4*s.size/5,odX[k-1],labels="Threshold") } result }
/scratch/gouwar.j/cran-all/cranData/yuima/R/JBtest.R
# In this function we consider different kind estimation procedures for COGARCH(P,Q) # Model. is.COGARCH <- function(obj){ if(is(obj,"yuima")) return(is(obj@model, "yuima.cogarch")) if(is(obj,"yuima.cogarch")) return(is(obj, "yuima.cogarch")) return(FALSE) } yuima.acf<-function(data,lag.max, forward=TRUE){ if(forward==FALSE){ burndata<-lag.max+1 dataused<-as.list(numeric(length=burndata+1)) Time<-length(data) dataformean<-data[burndata:Time] dataused[[1]]<-mean(dataformean) dataused[[2]]<-mean(dataformean^2) mu<-mean(dataformean) leng <-length(dataformean) var1<-sum((dataformean-mu)*(dataformean-mu))/leng res1<-numeric(length=lag.max) elem<-matrix(0,lag.max,(Time-lag.max)) for (t in (lag.max+1):(Time)){ # h<-leng-lag.max # elem<-(data[(1+t):leng]-mu)*(data[1:h]-mu)/(leng*var1) # res1[t+1]<-sum(elem) h <-c(lag.max:1) elem[,(t-lag.max)]<-(data[(t-h)[order(t-h,decreasing=TRUE)]]-mu)*(data[t]-mu)/(var1) } for(h in 3:(lag.max+2)){ dataused[[h]]<-sum(elem[h-2,])/leng } elem0<-rbind(t(as.matrix(dataformean)),elem) # res1<-res1 # acfr<-res1[2:(lag.max+1)] #analogously to Matlab program }else{ burndata<-lag.max dataused<-as.list(numeric(length=burndata+1)) Time<-length(data) dataformean<-data[1:(Time-burndata)] dataused[[1]]<-mean(dataformean) dataused[[2]]<-mean(dataformean^2) mu<-mean(dataformean) leng <-length(dataformean) var1<-sum((dataformean-mu)*(dataformean-mu))/leng res1<-numeric(length=lag.max) elem<-matrix(0,lag.max,(Time-lag.max)) for (t in 1:(Time-(lag.max))){ # h<-leng-lag.max # elem<-(data[(1+t):leng]-mu)*(data[1:h]-mu)/(leng*var1) # res1[t+1]<-sum(elem) h <-c(1:lag.max) elem[,t]<-(data[(t+h)]-mu)*(data[t]-mu)/(var1) } for(h in 3:(lag.max+2)){ dataused[[h]]<-sum(elem[h-2,])/leng } elem0<-rbind(t(as.matrix(dataformean)),elem) } return(list(dataused=dataused, elem=elem0, leng=leng)) } # The estimation procedure for cogarch(p,q) implemented in this code are based on the # Chadraa phd's thesis gmm<-function(yuima, data = NULL, start, method="BFGS", fixed = list(), lower, upper, lag.max = NULL, equally.spaced = FALSE, aggregation=TRUE, Est.Incr = "NoIncr", objFun = "L2"){ print <- FALSE aggr.G <- equally.spaced call <- match.call() if(objFun=="L1" && method!="Nelder-Mead"){ yuima.warn("Mean absolute error minimization is available only for 'method=Nelder-Mead'. yuima sets automatically 'method=Nelder-Mead' ") method<-"Nelder.Mead" } if(objFun=="L1" && (length(fixed)!=0 || !missing(lower) || !missing(upper))){ yuima.stop("Constraints are not allow for the minimization of Mean absolute error") } codelist.objFun <- c("L1","L2","L2CUE", "TWOSTEPS") if(any(is.na(match(objFun,codelist.objFun)))){ yuima.stop("Value of objFun not available. Please choose among L1, L2, L2CUE, TWOSTEPS") } codelist.Est.Incr <- c("NoIncr","Incr","IncrPar") if(any(is.na(match(Est.Incr,codelist.Est.Incr)))){ yuima.stop("Value of Est.Incr not available. Please choose among NoIncr, Incr, IncrPar ") } if( missing(yuima)) yuima.stop("yuima object is missing.") if( missing(start) ) yuima.stop("Starting values for the parameters are missing.") if( !is.COGARCH(yuima) ) yuima.stop("The model is not an object of class yuima.") if( !is(yuima,"yuima") && missing(data) ) yuima.stop("data are missing.") if(is(yuima,"yuima")){ model<-yuima@model if(is.null(data)){ observ<-yuima@data }else{observ<-data} }else{ if(is(yuima,"yuima.cogarch")){ model<-yuima if(is.null(data)){ yuima.stop("Missing data") } observ<-data } } if(!is(observ,"yuima.data")){ yuima.stop("Data must be an object of class yuima.data-class") } if( !missing(upper) && (method!="L-BFGS-B"||method!="brent")){ yuima.warn("The upper requires L-BFGS-B or brent methods. We change method in L-BFGS-B") method <- "L-BFGS-B" } if( !missing(lower) && (method!="L-BFGS-B"||method!="brent")){ yuima.warn("The lower constraints requires L-BFGS-B or brent methods. We change method in L-BFGS-B") method <- "L-BFGS-B" } if( !missing(fixed) && (method!="L-BFGS-B"||method!="brent")){ yuima.warn("The fixed constraints requires L-BFGS-B or brent methods. We change method in L-BFGS-B") method <- "L-BFGS-B" } # We identify the model parameters info <- model@info numb.ar <- info@q ar.name <- paste([email protected],c(numb.ar:1),sep="") numb.ma <- info@p ma.name <- paste([email protected],c(1:numb.ma),sep="") loc.par <- [email protected] #xinit.name <- paste([email protected], c(1:numb.ar), sep = "") xinit.name0 <- model@parameter@xinit idx <- na.omit(match(c(loc.par, ma.name), xinit.name0)) xinit.name <- xinit.name0[-idx] meas.par <- model@parameter@measure if(length(meas.par)==0 && Est.Incr=="IncrPar"){ yuima.warn("The dimension of measure parameters is zero, yuima changes 'Est.Incr = IncrPar' into 'Est.Incr = Incr'") Est.Incr <- "Incr" } fixed.name <- names(fixed) if(info@q==1){ # nm <- c(names(start), "EL1", "phi1","phi2") nm <- c(names(start), "EL1") }else{ # nm <- c(names(start), "EL1", "M2Lev","M4Lev") nm <- c(names(start), "EL1") } # We identify the index of parameters if(length(meas.par)!=0){ if(info@q==1){ # fullcoeff <- c(ar.name, ma.name, loc.par, xinit.name, measure.par, "EL1", "phi1","phi2") fullcoeff <- c(ar.name, ma.name, loc.par, xinit.name, meas.par, "EL1") }else{ # fullcoeff <- c(ar.name, ma.name, loc.par, xinit.name, measure.par, "EL1", "M2Lev","M4Lev") fullcoeff <- c(ar.name, ma.name, loc.par, xinit.name, meas.par, "EL1") } }else{ if(info@q==1){ # fullcoeff <- c(ar.name, ma.name, loc.par, xinit.name, "EL1", "phi1","phi2") fullcoeff <- c(ar.name, ma.name, loc.par, xinit.name, "EL1") }else{ # fullcoeff <- c(ar.name, ma.name, loc.par, xinit.name, "EL1", "M2Lev","M4Lev") fullcoeff <- c(ar.name, ma.name, loc.par, xinit.name, "EL1") } } oo <- match(nm, fullcoeff) if(any(is.na(oo))) yuima.stop("some named arguments in 'start' are not arguments to the supplied yuima model") if(info@q==1){ # start <- c(start, EL1 = 1, phi1=-1, phi2=-1) start <- c(start, EL1 = 1) }else{ # start <- c(start, EL1 = 1, M2Lev=1, M4Lev=2) start <- c(start, EL1 = 1) } start <- start[order(oo)] nm <- names(start) ar.idx <- match(ar.name, fullcoeff) ma.idx <- match(ma.name, fullcoeff) loc.idx <- match(loc.par, fullcoeff) meas.idx <- match(meas.par, fullcoeff) fixed.idx <- match(fixed.name, fullcoeff) EL1.idx <- match("EL1",fullcoeff) # We decide to pass EL1 as parameter !!! env <- new.env() # n <- length(observ)[1] #n <- attr([email protected],"tsp")[2] n <- length(index([email protected])) #Lag assign("lag", lag.max, envir=env) # Data assign("Data", as.matrix(onezoo(observ)[,1]), envir=env) #assign("deltaData", (n-1)/index([email protected][[1]])[n], envir=env) assign("deltaData", 1/yuima@sampling@delta, envir=env) assign("time.obs",length(env$Data),envir=env) # Order assign("p", info@p, envir=env) assign("q", info@q, envir=env) # Idx assign("ar.idx", ar.idx, envir=env) assign("ma.idx", ma.idx, envir=env) assign("loc.idx", loc.idx, envir=env) assign("meas.idx", meas.idx, envir=env) assign("EL1.idx", EL1.idx, envir=env) objFunDummy <- NULL if(objFun=="TWOSTEPS"||objFun=="L2CUE"){ objFunDummy <- objFun objFun <- "L2" } assign("objFun",objFun, envir=env) if(aggr.G==TRUE){ if(floor(env$deltaData)!=env$deltaData){ yuima.stop("the n/Terminal in sampling information is not an integer. equally.spaced=FALSE is recommended") } } if(aggr.G==TRUE){ # Aggregate returns G #dt<-round(deltat(onezoo(observ)[,1])*10^5)/10^5 # Time<-index([email protected][[1]])[n] G_i <- diff(env$Data[seq(1,length(env$Data),by=env$deltaData)]) r<-1 }else{ dummydata<-index(onezoo(observ)[,1]) unitarytime<-floor(dummydata) index<-!duplicated(unitarytime) G_i <- diff(env$Data[index]) r <- 1 } d <- min(floor(sqrt(length(G_i))),env$lag) assign("d", d, envir=env) typeacf <- "correlation" assign("typeacf", typeacf, envir=env) # CovQuad <- acf(G_i^2,plot=FALSE,lag.max=d,type=typeacf)$acf[-1] example<-yuima.acf(data=G_i^2,lag.max=d) dummyEmpiricalMoM<-as.numeric(example$dataused) CovQuad <- as.numeric(example$dataused)[-c(1:2)] # assign("G_i", G_i, envir=env) assign("r", r, envir=env) #mu_G2 <- as.numeric(example$dataused)[1] mu_G2<-mean(G_i^2) assign("mu_G2", mu_G2, envir=env) #var_G2 <- as.numeric(example$dataused)[2] - mu_G2^2 var_G2 <- mean(G_i^4) - mu_G2^2 assign("var_G2", var_G2, envir=env) assign("score",example$elem,envir=env ) assign("leng",example$leng,envir=env ) #CovQuad <-log(abs(yuima.acf(data=G_i^2,lag.max=min(d,env$lag)))) assign("CovQuad", CovQuad, envir=env) objectiveFun <- function(p,env) { mycoef <- as.list(p) if(length(c(fixed.idx, meas.idx))>0){ ## SMI 2/9/14 names(mycoef) <- nm[-c(fixed.idx,meas.idx)] ## SMI 2/9/14 }else{ names(mycoef) <- nm } ErrTerm(yuima=yuima, param=mycoef, print=print, env) } if(method!="L-BFGS-B"&&method!="brent"){ out<- optim(start, objectiveFun, method = method, env=env, hessian = TRUE) }else{ if(length(fixed)!=0 && !missing(upper) && !missing(lower)){ out<- optim(start, objectiveFun, method = method, fixed=as.numeric(fixed), lower=as.numeric(lower), upper=as.numeric(upper), env=env) }else{ if(!missing(upper) && !missing(lower)){ out<- optim(start, objectiveFun, method = method, lower=as.numeric(lower), upper=as.numeric(upper), env=env) } if(length(fixed)!=0 && !missing(lower)){ out<- optim(start, objectiveFun, method = method, fixed=as.numeric(fixed), lower=as.numeric(lower), env=env) } if(!missing(upper) && length(fixed)!=0){ out<- optim(start, objectiveFun, method = method, fixed=as.numeric(fixed), upper=as.numeric(upper), env=env) } } if(length(fixed)!=0 && missing(upper) && missing(lower)){ out<- optim(start, objectiveFun, method = method, fixed=as.numeric(fixed), env=env) } if(length(fixed)==0 && !missing(upper) && missing(lower)){ out<- optim(start, objectiveFun, method = method, upper=as.numeric(upper), env=env) } if(length(fixed)==0 && missing(upper) && !missing(lower)){ out<- optim(start, objectiveFun, method = method, lower=as.numeric(lower), env=env) } } # Alternative way for calculating Variance Covariance Matrix # sig2eps<-out$value/d # # dumHess<- out$hessian[c(ar.name, ma.name),c(ar.name, ma.name)]/(2*sig2eps) # vcovgmm<-solve(dumHess) # sqrt(diag(vcovgmm)) if(!is.null(objFunDummy)){ assign("objFun",objFunDummy, envir=env) bvect<-out$par[ar.name] bq<-bvect[1] avect<-out$par[ma.name] a1<-avect[1] out$par[loc.par]<-(bq-a1)*mu_G2/(bq*r) # Determine the Variance-Covariance Matrix if(length(meas.par)!=0){ idx.dumm<-match(meas.par,names(out$par)) out$par<-out$par[- idx.dumm] } dimOutp<-length(out$par)-(1+info@q) coef <- out$par[c(1:dimOutp)] vcov<-matrix(NA, dimOutp, dimOutp) names_coef<-names(coef) colnames(vcov) <- names_coef rownames(vcov) <- names_coef mycoef <- start min <- out$value # # call gradVect0<-MM_grad_Cogarch(p=info@p, q=info@q, acoeff=avect,cost=out$par[loc.par], b=bvect, r=env$r, h=seq(1, env$d, by = 1)*env$r, type=typeacf, m2=env$mu_G2, var=env$var_G2) score0 <- MM_Cogarch(p=info@p, q=info@q, acoeff=avect,cost=out$par[loc.par], b=bvect, r=env$r, h=seq(1, env$d, by = 1)*env$r, type=typeacf, m2=env$mu_G2, var=env$var_G2) idx.aaa<-match(loc.par,names_coef) # gradVect <- gradVect0[names_coef[-idx.aaa], ] gradVect <- gradVect0[names_coef[-idx.aaa],CovQuad>0] # score <- c(score0$acfG2)%*%matrix(1,1,example$leng) score <- c(score0$acfG2[CovQuad>0])%*%matrix(1,1,example$leng) #We need to write the matrix W for the matrix sandwhich #plot(as.numeric(example$dataused)[-1],type="h") #S_matrix # EmpirScore <-score-example$elem[-1,] exampelem <-example$elem[-1,] EmpirScore <-score-exampelem[CovQuad>0,] Omega_est <- tryCatch((1/example$leng*EmpirScore%*%t(EmpirScore)), error=function(theta){NULL}) W_est <-tryCatch(chol2inv(Omega_est),error=function(theta){NULL}) if(!is.null(W_est)){ assign("W_est",W_est,envir=env) start0<-unlist(start) start0[names(out$par)]<-out$par start <- as.list(start0) #start<-out$par if(method!="L-BFGS-B"&&method!="brent"){ out<- optim(start, objectiveFun, method = method, env=env) }else{ if(length(fixed)!=0 && !missing(upper) && !missing(lower)){ out<- optim(start, objectiveFun, method = method, fixed=as.numeric(fixed), lower=as.numeric(lower), upper=as.numeric(upper), env=env) }else{ if(!missing(upper) && !missing(lower)){ out<- optim(start, objectiveFun, method = method, lower=as.numeric(lower), upper=as.numeric(upper), env=env) } if(length(fixed)!=0 && !missing(lower)){ out<- optim(start, objectiveFun, method = method, fixed=as.numeric(fixed), lower=as.numeric(lower), env=env) } if(!missing(upper) && length(fixed)!=0){ out<- optim(start, objectiveFun, method = method, fixed=as.numeric(fixed), upper=as.numeric(upper), env=env) } } if(length(fixed)!=0 && missing(upper) && missing(lower)){ out<- optim(start, objectiveFun, method = method, fixed=as.numeric(fixed), env=env) } if(length(fixed)==0 && !missing(upper) && missing(lower)){ out<- optim(start, objectiveFun, method = method, upper=as.numeric(upper), env=env) } if(length(fixed)==0 && missing(upper) && !missing(lower)){ out<- optim(start, objectiveFun, method = method, lower=as.numeric(lower), env=env) } } }else{ yuima.warn("Method TWOSTEPS or L2CUE Changed in L2 since First W failed to compute") } } bvect<-out$par[ar.name] bq<-bvect[1] avect<-out$par[ma.name] a1<-avect[1] out$par[loc.par]<-(bq-a1)*mu_G2/(bq*r) # Determine the Variance-Covariance Matrix if(length(meas.par)!=0){ idx.dumm<-match(meas.par,names(out$par)) out$par<-out$par[- idx.dumm] } dimOutp<-length(out$par)-(1+info@q) coef <- out$par[c(1:dimOutp)] vcov<-matrix(NA, dimOutp, dimOutp) names_coef<-names(coef) colnames(vcov) <- names_coef rownames(vcov) <- names_coef # mycoef <- start min <- out$value # # call if(objFun!="L1"){ gradVect0<-MM_grad_Cogarch(p=info@p, q=info@q, acoeff=avect,cost=out$par[loc.par], b=bvect, r=env$r, h=seq(1, env$d, by = 1)*env$r, type=typeacf, m2=env$mu_G2, var=env$var_G2) score0 <- MM_Cogarch(p=info@p, q=info@q, acoeff=avect,cost=out$par[loc.par], b=bvect, r=env$r, h=seq(1, env$d, by = 1)*env$r, type=typeacf, m2=env$mu_G2, var=env$var_G2) if(objFun == "L2"){ # min <- log(sum((score0$acfG2[CovQuad>0]-CovQuad[CovQuad>0])^2)) min <- log(sum((score0$acfG2-CovQuad)^2)) #min <- log(sum((score0$acfG2[CovQuad>0]-CovQuad[CovQuad>0])^2)) } idx.aaa<-match(loc.par,names_coef) # gradVect <- gradVect0[names_coef[-idx.aaa], ] gradVect <- gradVect0[names_coef[-idx.aaa],CovQuad>0] # score <- c(score0$acfG2)%*%matrix(1,1,example$leng) score <- c(score0$acfG2[CovQuad>0])%*%matrix(1,1,example$leng) #We need to write the matrix W for the matrix sandwhich #plot(as.numeric(example$dataused)[-1],type="h") #S_matrix # EmpirScore <-score-example$elem[-1,] exampelem <-example$elem[-1,] EmpirScore <-score-exampelem[CovQuad>0,] Omega_est<-tryCatch((1/example$leng*EmpirScore%*%t(EmpirScore)), error=function(theta){NULL}) if(is.null(Omega_est)){ Omega_est<-matrix(NA,dim(EmpirScore)[1],dim(EmpirScore)[1]) } if(is.null(objFunDummy)){ Gmatr<-gradVect%*%t(gradVect) CentMat<-gradVect%*%Omega_est%*%t(gradVect) Var_Matr0 <- tryCatch(solve(Gmatr)%*%CentMat%*%solve(Gmatr)/example$leng, error=function(theta){NULL}) }else{ #Gmatr<-gradVect%*%W_est%*%t(gradVect) #CentMat<-gradVect%*%W_est%*%Omega_est%*%W_est%*%t(gradVect) Var_Matr0 <- tryCatch(solve(gradVect%*%solve(Omega_est)%*%t(gradVect))/example$leng, error=function(theta){NULL}) #Var_Matr0 <- solve(Gmatr)/example$leng } if(!is.null(Var_Matr0)){ aaa<-dimOutp-1 vcov[c(1:aaa),c(1:aaa)]<-Var_Matr0 } # Var_Matr <- solve(gradVect%*%t(gradVect)) #vcov <- Var_Matr # vcov[loc.par,]<-NA # vcov[,loc.par]<-NA #out$par[loc.par]<-(bq-a1)*mu_G2/(bq*r) } # Build an object of class mle # if(Est.Incr=="NoIncr"){ # res<-new("cogarch.est", call = call, coef = coef, fullcoef = unlist(coef), # vcov = vcov, min = min, details = list(), # method = character(), # model = setYuima(model=model), # objFun = objFun # ) # } # if(Est.Incr=="Incr"||Est.Incr=="IncrPar"){ # L.Incr<-cogarchNoise(yuima = model, data=observ, # param=as.list(coef), mu=1) # ttt<[email protected][[1]] # tt<-index(ttt) # L.Incr_Fin <- zoo(L.Incr$incr.L,tt[(1+length(tt)-length(L.Incr$incr.L)):length(tt)]) # } # if(Est.Incr=="Incr"){ # # Build an object of class cogarch.gmm.incr # res<-new("cogarch.est.incr", call = call, coef = coef, fullcoef = unlist(coef), # vcov = vcov, min = min, details = list(), # method = character(), # Incr.Lev = L.Incr_Fin, # model = setYuima(data = L.Incr$Cogarch, # model=model), nobs=as.integer(length(L.Incr)+1), # logL.Incr = numeric(), # objFun= objFun # ) # } # if(Est.Incr=="IncrPar"){ # #estimationLevy # # fixedCon <- constdum(fixed, meas.par) # lowerCon <- constdum(lower, meas.par) # upperCon <- constdum(upper, meas.par) # if(aggregation==TRUE){ # if(floor(n/index([email protected][[1]])[n])!=env$deltaData){ # yuima.stop("the n/Terminal in sampling information is not an integer. Aggregation=FALSE is recommended") # } # inc.levy1<-diff(cumsum(c(0,L.Incr$incr.L))[seq(from=1, # to=yuima@sampling@n[1], # by=env$deltaData # )]) # }else{ # inc.levy1 <- L.Incr$incr.L # } # # result.Lev <- gmm.Est.Lev(Increment.lev=c(0,inc.levy1), # param0=start[meas.par], # fixed = fixedCon[meas.par], # lower=lowerCon[meas.par], # upper=upperCon[meas.par], # measure=model@measure, # [email protected], # aggregation=aggregation, # dt=1/env$deltaData # ) # # if(is.null(result.Lev)){ # res<-new("cogarch.est.incr", call = call, coef = coef, fullcoef = unlist(coef), # vcov = vcov, min = min, details = list(), # method = character(), # Incr.Lev=L.Incr_Fin, # model = setYuima(data = L.Incr$Cogarch, # model=model), # nobs=as.integer(length(L.Incr)+1), # logL.Incr = numeric(), # objFun= objFun # ) # # } # else{ # Inc.Parm<-result.Lev$estLevpar # IncVCOV<-result.Lev$covLev # if(length(meas.par)==length(Inc.Parm)){ # names(Inc.Parm)<-meas.par # rownames(IncVCOV)<-as.character(meas.par) # colnames(IncVCOV)<-as.character(meas.par) # } # name.parm.cog<-names(coef) # coef<-c(coef,Inc.Parm) # # names.par<-names(coef) # cov<-NULL # cov<-matrix(NA,length(names.par),length(names.par)) # rownames(cov)<-names.par # colnames(cov)<-names.par # # cov[unique(name.parm.cog),unique(name.parm.cog)]<-vcov # cov[names(Inc.Parm),names(Inc.Parm)]<-IncVCOV # cov<-cov # # res<-new("cogarch.est.incr", call = call, coef = coef, fullcoef = unlist(coef), # vcov = cov, min = min, details = list(), # method = character(), # Incr.Lev=L.Incr_Fin, # model = setYuima(data = L.Incr$Cogarch, # model=model), nobs=as.integer(length(L.Incr)+1), # logL.Incr = tryCatch(-result.Lev$value,error=function(theta){NULL}), # objFun= objFun # ) # # } # # # } res <- ExtraNoiseFromEst(Est.Incr, call, coef, vcov, min, details = list(), method = character(), model, objFun, observ, fixed, meas.par, lower, upper, env, yuima, start, aggregation) return(res) } ExtraNoiseFromEst <- function(Est.Incr, call, coef, vcov, min, details = list(), method = character(), model, objFun, observ, fixed, meas.par, lower, upper, env, yuima, start, aggregation){ n <- length(index([email protected])) if(Est.Incr=="NoIncr"){ res<-new("cogarch.est", call = call, coef = coef, fullcoef = unlist(coef), vcov = vcov, min = min, details = details, method = method, yuima = setYuima(model=model), objFun = objFun ) } if(Est.Incr=="Incr"||Est.Incr=="IncrPar"){ L.Incr<-cogarchNoise(yuima=model, data=observ, param=as.list(coef), mu=1) ttt<[email protected][[1]] tt<-index(ttt) L.Incr_Fin <- zoo(L.Incr$incr.L,tt[(1+length(tt)-length(L.Incr$incr.L)):length(tt)]) } if(Est.Incr=="Incr"){ # Build an object of class cogarch.gmm.incr res<-new("cogarch.est.incr", call = call, coef = coef, fullcoef = unlist(coef), vcov = vcov, min = min, details = list(), method = character(), Incr.Lev = L.Incr_Fin, yuima = setYuima(data = L.Incr$Cogarch, model=model), nobs=as.integer(length(L.Incr)+1), logL.Incr = numeric(), objFun= objFun ) } if(Est.Incr=="IncrPar"){ #estimationLevy fixedCon <- constdum(fixed, meas.par) lowerCon <- constdum(lower, meas.par) upperCon <- constdum(upper, meas.par) if(aggregation==TRUE){ if(floor(n/index([email protected][[1]])[n])!=env$deltaData){ yuima.stop("the n/Terminal in sampling information is not an integer. aggregation=FALSE is recommended") } inc.levy1<-diff(cumsum(c(0,L.Incr$incr.L))[seq(from=1, to=yuima@sampling@n[1], by=env$deltaData )]) }else{ inc.levy1 <- L.Incr$incr.L } result.Lev <- gmm.Est.Lev(Increment.lev=c(0,inc.levy1), param0=start[meas.par], fixed = fixedCon[meas.par], lower=lowerCon[meas.par], upper=upperCon[meas.par], measure=model@measure, [email protected], aggregation=aggregation, dt=env$deltaData )##Modified 17/05/2016 if(is.null(result.Lev)){ res<-new("cogarch.est.incr", call = call, coef = coef, fullcoef = unlist(coef), vcov = vcov, min = min, details = list(), method = character(), Incr.Lev=L.Incr_Fin, yuima = setYuima(data = L.Incr$Cogarch, model=model), nobs=as.integer(length(L.Incr)+1), logL.Incr = numeric(), objFun= objFun ) } else{ Inc.Parm<-result.Lev$estLevpar IncVCOV<-result.Lev$covLev if(length(meas.par)==length(Inc.Parm)){ names(Inc.Parm)<-meas.par rownames(IncVCOV)<-as.character(meas.par) colnames(IncVCOV)<-as.character(meas.par) } name.parm.cog<-names(coef) coef<-c(coef,Inc.Parm) names.par<-names(coef) cov<-NULL cov<-matrix(NA,length(names.par),length(names.par)) rownames(cov)<-names.par colnames(cov)<-names.par cov[unique(name.parm.cog),unique(name.parm.cog)]<-vcov cov[names(Inc.Parm),names(Inc.Parm)]<-IncVCOV cov<-cov res<-new("cogarch.est.incr", call = call, coef = coef, fullcoef = unlist(coef), vcov = cov, min = min, details = list(), method = character(), Incr.Lev=L.Incr_Fin, yuima = setYuima(data = L.Incr$Cogarch, model=model), nobs=as.integer(length(L.Incr)+1), logL.Incr = tryCatch(-result.Lev$value,error=function(theta){NULL}), objFun= objFun ) } } return(res) } constdum<-function(fixed, meas.par){ fixedCon<-list() if(!missing(fixed)){ measure.par.dum.idx<-na.omit(names(fixed[meas.par])) if(length(measure.par.dum.idx)!=0){ fixedCon<-fixed[measure.par.dum.idx] } } } gmm.Est.Lev<-function(Increment.lev, param0, fixed=list(), lower=list(), upper=list(), measure, measure.type, aggregation, dt, noCPFFT = TRUE){ fixed.carma <- unlist(fixed) lower.carma <- unlist(lower) upper.carma <- unlist(upper) Dummy <- TRUE if(noCPFFT && measure.type=="CP"){ L<-cumsum(c(0,Increment.lev)) mod1 <- setPoisson(intensity=as.character(measure$intensity), df=list(as.character(measure$df$expr))) Yui1<-setYuima(data=setData(L,delta=dt), model=mod1) Noise <- qmle(yuima=Yui1, start=param0, upper = upper.carma, lower=lower.carma, fixed = fixed.carma) result.Lev <- list(estLevpar = coef(Noise), covLev = Noise@vcov, value = Noise@min) return(result.Lev) } CPlist <- c("dnorm","dgamma", "dexp") codelist <- c("rvgamma","rNIG","rIG", "rgamma") if(measure.type=="CP"){ tmp <- regexpr("\\(", measure$df$exp)[1] measurefunc <- substring(measure$df$exp, 1, tmp-1) if(is.na(match(measurefunc,CPlist))){ yuima.warn("COGARCH(p,q): Other compound poisson processes will be implemented as soon as") Dummy <- FALSE } } if(measure.type=="code"){ tmp <- regexpr("\\(", measure$df$exp)[1] measurefunc <- substring(measure$df$exp, 1, tmp-1) if(is.na(match(measurefunc,codelist))){ yuima.warn("COGARCH(p,q): Other Levy measure will be implemented as soon as possible") Dummy <- FALSE } } if(Dummy){ #env$h<-dt result.Lev <- yuima.Estimation.Lev(Increment.lev=Increment.lev, param0=unlist(param0), fixed.carma=fixed.carma, lower.carma=lower.carma, upper.carma=upper.carma, measure=measurefunc, measure.type=measure.type, aggregation=aggregation, dt=dt) }else{ result.Lev<-NULL } return(result.Lev) } ErrTerm <- function(yuima, param, print, env){ typeacf <- env$typeacf param <- as.numeric(param) G_i <- env$G_i r <- env$r mu_G2 <- env$mu_G2 var_G2 <- env$var_G2 d <- env$d CovQuad <-env$CovQuad h <- seq(1, d, by = 1)*r cost <- env$loc.idx b <- env$ar.idx a <- env$ma.idx meanL1 <- param[env$EL1.idx] # meanL1 <- 1 # if(env$q == 1){ # # beta <- param[cost]*param[b] # eta <- param[b] # phi <- param[a] # # # phi1 <- param[env$phi1.idx] # # phi2 <- param[env$phi2.idx] # #theo_mu_G2 <- meanL1*r*beta/abs(phi1) # phi1 <- meanL1*r*beta/mu_G2 # # termA <- (6*mu_G2/r*beta/abs(phi1)*(2*eta/phi-meanL1)*(r-(1-exp(-r*abs(phi1)))/abs(phi1))+2*beta^2/phi^2*r) # phi2 <-2*termA*abs(phi1)/((var_G2-2*mu_G2^2)*abs(phi1)+termA) # if(typeacf == "covariance"){ # TheoCovQuad <- meanL1*beta^2/abs(phi1)^3*(2*eta/phi-meanL1)* # (2/abs(phi2)-1/abs(phi1))*(1-exp(-r*abs(phi1)))*(exp(r*abs(phi1))-1)* # exp(-h*abs(phi1)) # }else{ # TheoCovQuad <- meanL1*beta^2/abs(phi1)^3*(2*eta/phi-meanL1)* # (2/abs(phi2)-1/abs(phi1))*(1-exp(-r*abs(phi1)))*(exp(r*abs(phi1))-1)* # exp(-h*abs(phi1))/(var_G2) # } # # } if(env$q >= 1){ TheoCovQuad <- numeric(length = length(h)) cost<-param[cost] # for(i in c(1:length(h))){ MomentCog <- MM_Cogarch(p = env$p, q = env$q, acoeff=param[a], cost=cost, b=param[b], r = r, h = h, type = typeacf, m2=mu_G2, var=var_G2) TheoCovQuad <- MomentCog$acfG2 # } theo_mu_G2 <- MomentCog$meanG2 #param[cost]<-MomentCog$cost } if(env$objFun=="L2"){ # res <- log(sum((TheoCovQuad[CovQuad>0]-CovQuad[CovQuad>0])^2)) # emp <- log(CovQuad[CovQuad>0]) # theo <- log(TheoCovQuad[CovQuad>0]) # res <- log(sum((abs(TheoCovQuad)-abs(CovQuad))^2)) res <- sum((log(TheoCovQuad[CovQuad>0])-log(CovQuad[CovQuad>0]))^2) # res <- sum((TheoCovQuad[CovQuad>0]-CovQuad[CovQuad>0])^2) # res <- sum((TheoCovQuad-CovQuad)^2) # res <- sum((log(abs(TheoCovQuad))-log(abs(CovQuad)))^2) # res <- sum((log(TheoCovQuad[CovQuad>0]))-log(CovQuad[CovQuad>0]))^2) return(res) } if(env$objFun=="TWOSTEPS"){ TheoMoM<-log(TheoCovQuad[CovQuad>0]) #TheoMoM<-log(abs(TheoCovQuad)) #TheoMoM<-TheoCovQuad[CovQuad>0] #dumScore <- (TheoMoM%*%matrix(1,1,env$leng))-env$score[-1,] #W_est<-chol2inv(dumScore%*%t(dumScore)/env$leng) W_est<-env$W_est CompMoM0<-TheoMoM-c(log(CovQuad[CovQuad>0])) #CompMoM0<-TheoMoM-c(log(abs(CovQuad))) #CompMoM0<-TheoMoM-CovQuad[CovQuad>0] CompMoM<-matrix(CompMoM0,1,length(CompMoM0)) res <- as.numeric(CompMoM%*%W_est%*%t(CompMoM)) # TheoMoM<-TheoCovQuad[CovQuad>0] # intrDum<-env$score[-1,] # # dumScore <- (TheoMoM%*%matrix(1,1,env$leng))-intrDum[CovQuad>0,] # W_est<-chol2inv(dumScore%*%t(dumScore)/env$leng) # CompMoM0<-TheoMoM-c(CovQuad[CovQuad>0]) # CompMoM<-matrix(CompMoM0,1,length(CompMoM0)) # res <- as.numeric(CompMoM%*%W_est%*%t(CompMoM)) return(res) } if(env$objFun=="L1"){ res <- log(sum(abs(c(TheoCovQuad)-c(CovQuad)))) return(res) } if(env$objFun=="L2CUE"){ #TheoMoM<-TheoCovQuad # #TheoMoM<-log(TheoCovQuad[CovQuad>0]) TheoMoM<-TheoCovQuad[CovQuad>0] intrDum<-env$score[-1,] dumScore <- (TheoMoM%*%matrix(1,1,env$leng))-intrDum[CovQuad>0,] W_est<-chol2inv(dumScore%*%t(dumScore)/env$leng) CompMoM0<-TheoMoM-c(CovQuad[CovQuad>0]) CompMoM<-matrix(CompMoM0,1,length(CompMoM0)) res <- as.numeric(CompMoM%*%W_est%*%t(CompMoM)) return(res) } } MM_Cogarch <- function(p, q, acoeff,cost, b, r, h, type, m2, var){ # The code developed here is based on the acf for squared returns derived in the # Chaadra phd Thesis a <- e <- matrix(0,nrow=q,ncol=1) e[q,1] <- 1 a[1:p,1] <- acoeff bq <- b[1] a1 <- a[1] # # Matching only the autocorrelation we are not able to estimate the a_0 parameter # nevertheless using the theoretical formula of the expectaion of squared returns we # are able to fix this parameter for having a perfect match between theoretical and # empirical mean # We recall that under the assumption of levy process is centered the mean at time 1 of the # squared returns and the mean of the corresponding levy measure are equals. mu<-1 # we assume variance of the underlying L\'evy is one meanL1<-mu cost<-(bq-mu*a1)*m2/(bq*r) B<- MatrixA(b[c(q:1)]) B_tilde <- B+mu*e%*%t(a) meanG2 <- cost*bq*r/(bq-mu*a1)*meanL1 Inf_eps <- IdentM <- diag(q) if(q==1){ Inf_eps[q,q] <- -1/(2*B_tilde[1,1]) } if(q==2){ Inf_eps[q,q] <- -B_tilde[2,1] Inf_eps <- 1/(2*B_tilde[2,1]*B_tilde[2,2])*Inf_eps } if(q==3){ Inf_eps[1,1] <- B_tilde[3,3]/B_tilde[3,1] Inf_eps[q,q] <- -B_tilde[3,2] Inf_eps[1,3] <- -1 Inf_eps[3,1] <- -1 Inf_eps <- 1/(2*(B_tilde[3,3]*B_tilde[3,2]+B_tilde[3,1]))*Inf_eps } if(q>=4){ Inf_eps <- round(AsympVar(B_tilde,e,lower=0,upper=100,delta=0.01)*10^5)/10^5 } #term <- expm(B_tilde*h) term <- lapply(h,"yuimaExpm",B=B_tilde) #invB <- solve(B_tilde) # In this case we can use the analytical form for Companion Matrix??? # We invert the B_tilde using the Inverse of companion matrix if(q>1){ invB<-rbind(c(-B_tilde[q,-1],1)/B_tilde[q,1],cbind(diag(q-1),matrix(0,q-1,1))) }else{invB<-1/B_tilde} term1 <- invB%*%(IdentM-expm(-B_tilde*r)) term2 <- (expm(B_tilde*r)-IdentM) P0_overRho <- 2*mu^2*(3*invB%*%(invB%*%term2-r*IdentM)-IdentM)%*%Inf_eps Q0_overRho <- 6*mu*((r*IdentM-invB%*%term2)%*%Inf_eps -invB%*%(invB%*%term2-r*IdentM)%*%Inf_eps%*%t(B_tilde))%*%e # Q0_overRho <- 6*mu*((r*IdentM-invB%*%term2)%*%Inf_eps # -invB%*%(invB%*%term2-r*IdentM)%*%Inf_eps%*%t(B))%*%e m_overRho <- as.numeric(t(a)%*%Inf_eps%*%a) Den<- (m_overRho*meanL1^2/m2^2*var*r^2+t(a)%*%Q0_overRho+t(a)%*%P0_overRho%*%a+1) num <-(meanL1^2/m2^2*var-2*mu^2)*r^2 rh0 <- as.numeric(num/Den) Inf_eps1 <- Inf_eps*rh0 Ph_withouterm <- term1%*%invB%*%term2%*%Inf_eps1*mu^2 Ph<-lapply(term,"%*%",Ph_withouterm) Qh_without <- term1%*%(-term2%*%Inf_eps1-invB%*%term2%*%Inf_eps1%*%t(B_tilde))%*%e*mu Qh<-lapply(term,"%*%",Qh_without) # Qh <- mu*term%*%term1%*%(-term2%*%Inf_eps1-invB%*%term2%*%Inf_eps1%*%t(B))%*%e m <- m_overRho*rh0 atrasp<-t(a) if(type=="correlation"){ VarTheo<-as.numeric(rh0*atrasp%*%P0_overRho%*%a+rh0*atrasp%*%Q0_overRho+2*r^2*mu^2+rh0) acfG2 <- (as.numeric(lapply(Ph,"yuimaQuadrForm",at=atrasp,a=a)) + as.numeric(lapply(Qh,"yuimaInnerProd",at=atrasp)))/VarTheo }else{ coeff <- cost^2*bq^2/((1-m)*(bq-mu*a1)^2) acfG2 <- coeff*( as.numeric(lapply(Ph,"yuimaQuadrForm",at=atrasp,a=a)) + as.numeric(lapply(Qh,"yuimaInnerProd",at=atrasp)) ) } res <- list(acfG2=acfG2, meanG2=meanG2) return(res) } MM_grad_Cogarch <- function(p, q, acoeff,cost, b, r, h, type, m2, var){ eps<-10^(-3) PartialP<-matrix(0,p,length(h)) epsA<-eps*diag(p) for(i in c(1:p)){ LeftApproxP<-MM_Cogarch(p, q, acoeff-epsA[i,],cost, b, r, h, type, m2, var) RightApproxP<-MM_Cogarch(p, q, acoeff[i]+epsA[i,],cost, b, r, h, type, m2, var) PartialP[i,]<-(RightApproxP$acfG2-LeftApproxP$acfG2)/(2*eps) } PartialQ<-matrix(0,q,length(h)) epsB<-eps*diag(q) for(i in c(1:q)){ LeftApproxQ<-MM_Cogarch(p, q, acoeff,cost, b-epsB[i,], r, h, type, m2, var) RightApproxQ<-MM_Cogarch(p, q, acoeff,cost, b+epsB[i,], r, h, type, m2, var) PartialQ[i,]<-(RightApproxQ$acfG2-LeftApproxQ$acfG2)/(2*eps) } # LeftApproxCost<-MM_Cogarch(p, q, acoeff,cost-eps, b, r, h, type, m2, var) # RightApproxCost<-MM_Cogarch(p, q, acoeff,cost+eps, b, r, h, type, m2, var) # PartialCost0<-(c(RightApproxCost$meanG2,RightApproxCost$acfG2)-c(LeftApproxCost$meanG2,LeftApproxCost$acfG2))/(2*eps) # PartialCost<-matrix(PartialCost0,1, (length(h)+1)) namesCoeff<-names(c(acoeff,b)) res<-rbind(PartialP,PartialQ) rownames(res)<-namesCoeff return(res) } yuimaQuadrForm<-function(P,a,at){at%*%P%*%a} yuimaInnerProd<-function(P,at){at%*%P} yuimaExpm<-function(h,B){expm(B*h)} AsympVar<-function(B_tilde,e,lower=0,upper=100,delta=0.1){ part<-seq(lower,upper-delta, by=delta)+delta/2 last <- length(part) Integrand <- as.matrix(matrix(0,length(e),length(e))) for(i in c(1:last)){ Integrand<-Integrand+expm(B_tilde*part[i])%*%e%*%t(e)%*%expm(t(B_tilde)*part[i])*delta } return(Integrand) } setMethod("plot",signature(x="cogarch.est.incr"), function(x, type="l" ,...){ Time<-index([email protected]) Incr.L<-coredata([email protected]) if(is.complex(Incr.L)){ yuima.warn("Complex increments. We plot only the real part") Incr.L<-Re(Incr.L) } # model <- x@model # EndT <- Time[length(Time)] # numb <- (length(Incr.L)+1) plot(x= Time,y= Incr.L, type=type,...) } ) setMethod("summary", "cogarch.est", function (object, ...) { cmat <- cbind(Estimate = object@coef, `Std. Error` = sqrt(diag(object@vcov))) obj<- object@min labFun <- object@objFun tmp <- new("summary.cogarch.est", call = object@call, coef = cmat, m2logL = 0, #model = object@model, objFun = labFun, objFunVal = obj, object = object ) tmp } ) # errorfun <- function(estimates, labelFun = "L2"){ # if(LabelFun == "L2"){ # # } # # } setMethod("show", "summary.cogarch.est", function (object) { if(object@objFun == "PseudoLogLik"){ cat("PML estimation\n\nCall:\n") }else{ cat("GMM estimation\n\nCall:\n") } print(object@call) cat("\nCoefficients:\n") print(coef(object)) if(object@objFun == "PseudoLogLik"){ cat("\n",paste0(paste("-2 ", object@objFun),":"), 2*object@objFunVal, "\n") }else{ cat("\n",paste0(paste("Log.objFun", object@objFun),":"), object@objFunVal, "\n") } #cat("objFun", object@min, "\n") dummy <- Diagnostic.Cogarch(object@object, display = FALSE) info <- object@object@yuima@model@info nameMod <- paste0("Cogarch(",info@p, ",", info@q, ") model:", collapse = "") if(dummy$stationary){ cat("\n", nameMod, "Stationarity conditions are satisfied.\n") }else{ cat("\n", nameMod, "Stationarity conditions are not satisfied.\n") } if(dummy$positivity){ cat("\n", nameMod, "Variance process is positive.\n") }else{ cat("\n", nameMod, "Variance process is not positive.\n") } } ) setMethod("summary", "cogarch.est.incr", function (object, ...) { cmat <- cbind(Estimate = object@coef, `Std. Error` = sqrt(diag(object@vcov))) m2logL <- 0 data<-Re(coredata([email protected])) data<- data[!is.na(data)] obj<- object@min labFun <- object@objFun tmp <- new("summary.cogarch.est.incr", call = object@call, coef = cmat, m2logL = m2logL, objFun = labFun, objFunVal = obj, MeanI = mean(data), SdI = sd(data), logLI = [email protected], TypeI = object@yuima@[email protected], NumbI = length(data), StatI =summary(data), object = object ) tmp } ) # setMethod("show", "summary.cogarch.est.incr", function (object) { if(object@objFun == "PseudoLogLik"){ cat("Two Stages PSEUDO-LogLik estimation \n\nCall:\n") }else{ cat("Two Stages GMM estimation \n\nCall:\n") } print(object@call) cat("\nCoefficients:\n") print(coef(object)) # cat("\n-2 log L:", object@m2logL, "\n") cat("\n",paste0(paste("Log.objFun", object@objFun),":"), object@objFunVal, "\n") cat(sprintf("\n\nNumber of increments: %d\n",object@NumbI)) cat(sprintf("\nAverage of increments: %f\n",object@MeanI)) cat(sprintf("\nStandard Dev. of increments: %f\n",object@SdI)) if(!is.null(object@logLI)){ cat(sprintf("\n\n-2 log L of increments: %f\n",-2*object@logLI)) } cat("\nSummary statistics for increments:\n") print(object@StatI) cat("\n") dummy <- Diagnostic.Cogarch(object@object, display = FALSE) info <- object@object@yuima@model@info nameMod <- paste0("Cogarch(",info@p, ",", info@q, ") model:", collapse = "") if(dummy$stationary){ cat("\n", nameMod, "Stationarity conditions are satisfied.\n") }else{ cat("\n", nameMod, "Stationarity conditions are not satisfied.\n") } if(dummy$positivity){ cat("\n", nameMod, "Variance process is positive.\n") }else{ cat("\n", nameMod, "Variance process is not positive.\n") } } )
/scratch/gouwar.j/cran-all/cranData/yuima/R/MM.COGARCH.R
aux.funForLaw <- function(object, param, my.env, dummy){ # param <- unlist(param) name.par <- names(param) if(length([email protected])>=1){ if([email protected]%in%name.par){ assign([email protected],param[[[email protected]]], envir = my.env) }else{ yuima.stop("time.var is not assigned") } param <- param[!(name.par %in% [email protected])] name.par <- names(param) } if(length(param)>0){ if(length(param)!=length([email protected])){ yuima.stop("mismatch arguments") } for(i in c(1: length(param))){ cond<[email protected] %in% name.par[[i]] assign([email protected][cond], param[[i]], envir = my.env) } } res <- eval(parse(text=dummy),envir=my.env) return(res) } # rng aux.rand<- function(object, n, param, ...){ dummy <- deparse(object@rng)[1] dummy <- gsub("function ", deparse(substitute(object@rng)), dummy) my.env <- new.env() assign("n", n, envir = my.env) res <- aux.funForLaw(object, param, my.env, dummy) return(res) # param <- unlist(param) # name.par <- names(param) # if(length([email protected])>=1){ # if([email protected]%in%name.par){ # assign([email protected],param[[email protected]], envir = my.env) # }else{ # yuima.stop("time.var is not assigned") # } # param <- param[!(name.par %in% [email protected])] # name.par <- names(param) # } # if(length(param)>0){ # if(length(param)!=length([email protected])){ # yuima.stop("mismatch arguments") # } # for(i in c(1: length(param))){ # cond<[email protected] %in% name.par[i] # assign([email protected][cond], param[i], envir = my.env) # } # } # res <- eval(parse(text=dummy),envir=my.env) # return(res) } setGeneric("rand", function(object, n, param, ...){ standardGeneric("rand") } ) # dens setGeneric("dens", function(object, x, param, log = FALSE, ...) standardGeneric("dens") ) aux.dens<- function(object, x, param, log, ...){ dummy <- deparse(object@density)[1] dummy <- gsub("function ", deparse(substitute(object@density)), dummy) my.env <- new.env() assign("x", x, envir = my.env) res <- aux.funForLaw(object, param, my.env, dummy) if(log){res <- log(res)} return(as.numeric(res)) } # CDF # cdf setGeneric("cdf", function(object, q, param, ...) standardGeneric("cdf") ) aux.cdf<- function(object, q, param, ...){ dummy <- deparse(object@cdf)[1] dummy <- gsub("function ", deparse(substitute(object@cdf)), dummy) my.env <- new.env() assign("q", q, envir = my.env) res <- aux.funForLaw(object, param, my.env, dummy) return(as.numeric(res)) } # quantile setGeneric("quant", function(object, p, param, ...) standardGeneric("quant") ) aux.quant <- function(object, p, param, ...){ dummy <- deparse(object@quantile)[1] dummy <- gsub("function ", deparse(substitute(object@quantile)), dummy) my.env <- new.env() assign("p", p, envir = my.env) res <- aux.funForLaw(object, param, my.env, dummy) return(as.numeric(res)) } # characteristic setGeneric("char", function(object, u, param, ...) standardGeneric("char") ) aux.char <- function(object, u, param, ...){ dummy <- deparse(object@characteristic)[1] dummy <- gsub("function ", deparse(substitute(object@characteristic)), dummy) my.env <- new.env() assign("u", u, envir = my.env) res <- aux.funForLaw(object, param, my.env, dummy) return(as.numeric(res)) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/MethodForLaw.R
# Here we insert new classes for extending the object of classes yuima setClass("param.Map", representation(out.var = "character", allparam = "character", allparamMap = "character", common = "character", Input.var = "character", time.var = "character")) setClass("info.Map", representation(formula="vector", dimension="numeric", type="character", param = "param.Map")) setClass("yuima.Map", representation(Output = "info.Map"), contains="yuima" ) # Initialization setMethod("initialize", "param.Map", function(.Object, out.var = character(), allparam = character(), allparamMap = character(), common = character(), Input.var = character(), time.var = character()){ [email protected] <- out.var .Object@allparam <- allparam .Object@allparamMap <- allparamMap .Object@common <- common [email protected] <-Input.var [email protected] <- time.var return(.Object) } ) # setMethod("initialize", "info.Map", function(.Object, formula = vector(mode = expression), dimension = numeric(), type = character(), param = new("param.Map")){ .Object@formula <- formula .Object@dimension <- dimension .Object@type <- type .Object@param <- param return(.Object) } ) setMethod("initialize", "yuima.Map", function(.Object, #param = new("param.Map"), Output = new("info.Map"), yuima = new("yuima")){ #.Object@param <- param .Object@Output <- Output .Object@data <- yuima@data .Object@model <- yuima@model .Object@sampling <- yuima@sampling .Object@characteristic <- yuima@characteristic .Object@functional <- yuima@functional return(.Object) } ) # # Class for yuima.integral is structured as follows: # param.Integral # Integral$param$allparam # Integral$param$common # Integral$param$IntegrandParam setClass("param.Integral",representation(allparam = "character", common = "character", Integrandparam = "character") ) # setMethod("initialize","param.Integral", function(.Object, allparam = character(), common = character(), Integrandparam = character()){ .Object@allparam <- allparam .Object@common <- common .Object@Integrandparam <- Integrandparam return(.Object) } ) # # # variable.Integral # # Integral$var.dx # # Integral$lower.var # # Integral$upper.var # # Integral$out.var # # Integral$var.time <-"s" # setClass("variable.Integral", representation(var.dx = "character", lower.var = "character", upper.var = "character", out.var = "character", var.time = "character") ) # setMethod("initialize","variable.Integral", function(.Object, var.dx = character(), lower.var = character(), upper.var = character(), out.var = character(), var.time = character()){ [email protected] <- var.dx [email protected] <- lower.var [email protected] <- upper.var [email protected] <- out.var [email protected] <- var.time return(.Object) } ) # Integrand # Integral$IntegrandList # Integral$dimIntegrand setClass("Integrand", representation(IntegrandList = "list", dimIntegrand = "numeric") ) setMethod("initialize","Integrand", function(.Object, IntegrandList = list(), dimIntegrand = numeric()){ .Object@IntegrandList <- IntegrandList .Object@dimIntegrand <- dimIntegrand return(.Object) } ) # # # Integral.sde # setClass("Integral.sde", representation(param.Integral = "param.Integral", variable.Integral = "variable.Integral", Integrand = "Integrand") ) # setMethod("initialize", "Integral.sde", function(.Object, param.Integral = new("param.Integral"), variable.Integral = new("variable.Integral"), Integrand = new("Integrand")){ [email protected] <- param.Integral [email protected] <- variable.Integral .Object@Integrand <- Integrand return(.Object) } ) # # # yuima.Integral # setClass("yuima.Integral", representation( Integral = "Integral.sde"), contains = "yuima" ) # setMethod("initialize", "yuima.Integral", function(.Object, Integral = new("Integral.sde"), yuima = new("yuima")){ .Object@Integral <- Integral #.Object@param <- param #.Object@Output <- Output .Object@data <- yuima@data .Object@model <- yuima@model .Object@sampling <- yuima@sampling .Object@characteristic <- yuima@characteristic .Object@functional <- yuima@functional return(.Object) } ) # # yuima.multimodel. We replacate the yuima.model class in order to # describe from mathematical point of view the multi dimensional jump # diffusion model setClass("yuima.multimodel", contains="yuima.model") setClass("yuima.snr", representation(call = "call", coef = "numeric", snr = "numeric", model = "yuima.model"), prototype = list(call = NULL, coef = NULL, snr = NULL, model = NULL)) ## yuima.qmle.incr-class #setClassUnion("yuima.qmle.incr", members=c("yuima.carma.qmle","cogarch.est.incr")) setClass("yuima.qmleLevy.incr",representation(Incr.Lev = "ANY", logL.Incr = "ANY", minusloglLevy="function", Levydetails= "list", Data = "ANY"), contains="yuima.qmle") setMethod("initialize", "yuima.qmleLevy.incr", function(.Object, Incr.Lev = NULL, logL.Incr = NULL, minusloglLevy=function(){NULL}, Levydetails= list(), Data=NULL, yuima = new("yuima.qmle")){ [email protected] <- Incr.Lev #.Object@param <- param #.Object@Output <- Output [email protected] <- logL.Incr .Object@Levydetails<- Levydetails .Object@minusloglLevy <- minusloglLevy .Object@Data <- Data .Object@model <- yuima@model .Object@call <- yuima@call .Object@coef <- yuima@coef .Object@fullcoef <- yuima@fullcoef .Object@vcov <- yuima@vcov .Object@min <-yuima@min .Object@details<- yuima@details .Object@minuslogl<-yuima@minuslogl .Object@nobs<-yuima@nobs .Object@method<-yuima@method return(.Object) } )
/scratch/gouwar.j/cran-all/cranData/yuima/R/NewClasses.R
setClass("info.PPR", representation(allparam = "character", allparamPPR = "character", common ="character", counting.var = "character", var.dx = "character", upper.var = "character", lower.var = "character", covariates = "character", var.dt = "character", additional.info = "character", Info.measure = "list", RegressWithCount = "logical", IntensWithCount = "logical") ) setClass("yuima.PPR", representation(PPR = "info.PPR", gFun = "info.Map", Kernel = "Integral.sde"), contains="yuima" ) setMethod("initialize", "info.PPR", function(.Object, allparam = character(), allparamPPR = character(), common = character(), counting.var = character(), var.dx = character(), upper.var = character(), lower.var = character(), covariates = character(), var.dt = character(), additional.info = character(), Info.measure = list(), RegressWithCount = FALSE, IntensWithCount = TRUE){ .Object@allparam <- allparam .Object@allparamPPR <- allparamPPR .Object@common <- common [email protected] <- counting.var [email protected] <- var.dx [email protected] <- upper.var [email protected] <- lower.var .Object@covariates <- covariates [email protected] <- var.dt [email protected] <- additional.info [email protected] <- Info.measure .Object@RegressWithCount <- RegressWithCount .Object@IntensWithCount <- IntensWithCount return(.Object) } ) setMethod("initialize", "yuima.PPR", function(.Object, PPR = new("info.PPR"), gFun = new("info.Map"), Kernel = new("Integral.sde"), yuima = new("yuima")){ #.Object@param <- param .Object@PPR <- PPR .Object@gFun <- gFun .Object@Kernel <- Kernel .Object@data <- yuima@data .Object@model <- yuima@model .Object@sampling <- yuima@sampling .Object@characteristic <- yuima@characteristic .Object@functional <- yuima@functional return(.Object) } ) setClass("yuima.Hawkes", contains="yuima.PPR" ) # Class yuima.PPR.qmle setClass("yuima.PPR.qmle",representation( model = "yuima.PPR"), contains="mle" ) setClass("summary.yuima.PPR.qmle", representation( model = "yuima.PPR"), contains="summary.mle" ) setMethod("show", "summary.yuima.PPR.qmle", function (object) { cat("Quasi-Maximum likelihood estimation\n\nCall:\n") print(object@call) cat("\nCoefficients:\n") print(coef(object)) cat("\n-2 log L:", object@m2logL, "\n") } )
/scratch/gouwar.j/cran-all/cranData/yuima/R/PointProcessClasses.R
# This code is useful for estimation of the COGARCH(p,q) model according the PseudoLogLikelihood # maximization procedure developed in Iacus et al. 2015 # PseudoLogLik.COGARCH <- function(yuima, start, method="BFGS", fixed = list(), lower, upper, Est.Incr, call, grideq, aggregation,...){ if(is(yuima,"yuima")){ model <- yuima@model info <- model@info Data <- onezoo(yuima) } time <- index(Data) Obs <- as.numeric(as.matrix(Data)[,1]) my.env <- new.env() param <- unlist(start) assign("mycog",model,envir=my.env) meas.par <- model@parameter@measure if(length(meas.par)==0 && Est.Incr=="IncrPar"){ yuima.warn("The dimension of measure parameters is zero, yuima changes 'Est.Incr = IncrPar' into 'Est.Incr = Incr'") Est.Incr <- "Incr" } ar.names <- paste0([email protected],c(1:info@q)) ma.names <- paste0([email protected],c(1:info@p)) start.state <- paste0(paste0([email protected],0),c(1:info@q)) e <- matrix(0, info@q,1) e[info@q,1] <- 1 assign("e", e, envir = my.env) assign("start.state", start.state, envir = my.env) assign("q", info@q, envir = my.env) assign("p", info@p, envir = my.env) assign("B", matrix(0,info@q,info@q), envir = my.env) # consider two cases: # 1) equally spaced grid if(grideq){ assign("Deltat", tail(index(Data),1)/length(index(Data)), envir = my.env) # assign("Deltat", diff(time)[1], envir = my.env) # 2) no-equally spaced grid assign("grideq", TRUE, envir = my.env) }else{ assign("Deltat", diff(time), envir = my.env) assign("grideq", FALSE, envir = my.env) } assign("Obs", (diff(Obs))^2, envir = my.env) assign("nObs",length(Obs),envir = my.env) assign("ar.names", ar.names, envir = my.env) assign("ma.names", ma.names, envir = my.env) assign("loc.par",[email protected], envir = my.env) I <- diag(info@q) assign("I",I, envir = my.env) param1 <- param[c(my.env$loc.par, ma.names, ar.names)] out<-NULL if(length(lower)==0 && length(upper)>0 && length(fixed)==0){ out <- optim(par=param1, fn=minusloglik.COGARCH1, method = method, upper=upper, env = my.env,...) } if(length(lower)==0 && length(upper)==0 && length(fixed)>0){ out <- optim(par=param1, fn=minusloglik.COGARCH1, method = method, fixed=fixed, env = my.env,...) } if(length(lower)>0 && length(upper)==0 && length(fixed)==0){ out <- optim(par=param1, fn=minusloglik.COGARCH1, method = method, lower=lower, env = my.env,...) } if(length(lower)>0 && length(upper)>0 && length(fixed)==0){ out <- optim(par=param1, fn=minusloglik.COGARCH1, method = method, upper = upper, lower=lower, env = my.env,...) } if(length(lower)==0 && length(upper)>0 && length(fixed)>0){ out <- optim(par=param1, fn=minusloglik.COGARCH1, method = method, upper = upper, fixed = fixed, env = my.env,...) } if(length(lower)>0 && length(upper)==0 && length(fixed)>0){ out <- optim(par=param1, fn=minusloglik.COGARCH1, method = method, lower = lower, fixed = fixed, env = my.env,...) } if(length(lower)>0 && length(upper)>0 && length(fixed)>0){ out <- optim(par=param1, fn=minusloglik.COGARCH1, method = method, lower = lower, fixed = fixed, upper = upper, env = my.env,...) } if(is.null(out)){ out <- optim(par=param1, fn=minusloglik.COGARCH1, method = method, env = my.env,...) } # control= list(maxit=100), # Write the object mle with result # my.env1 <- my.env # my.env1$grideq <- TRUE resHessian<-tryCatch(optimHess(par = out$par, fn = minusloglik.COGARCH1, env = my.env),error=function(theta){NULL}) bvect<-out$par[ar.names] bq<-bvect[1] avect<-out$par[ma.names] a1<-avect[1] a0<-out$par[[email protected]] # if(length(meas.par)!=0){ # idx.dumm<-match(meas.par,names(out$par)) # out$par<-out$par[- idx.dumm] # } # # idx.dumm1<-match(start.state,names(out$par)) coef <- out$par #coef <- out$par vcov<-matrix(NA, length(coef), length(coef)) names_coef<-names(coef) colnames(vcov)[1:length(names_coef)] <- names_coef rownames(vcov)[1:length(names_coef)] <- names_coef if(!is.null(resHessian)){ vcov[c(1:length(names_coef)),c(1:length(names_coef))]<- tryCatch(solve(resHessian),error=function(resHessian){NA}) } mycoef <- start # min <- out$value objFun <- "PseudoLogLik" # min <- numeric() min <- out$value # res<-new("cogarch.est", call = call, coef = coef, fullcoef = unlist(coef), # vcov = vcov, min = min, details = list(), # method = character(), # model = model, # objFun = objFun # ) env <- list(deltaData = yuima@sampling@delta) res <- ExtraNoiseFromEst(Est.Incr, call, coef, vcov, min, details = list(), method = character(), model, objFun, observ=yuima@data, fixed, meas.par, lower, upper, env, yuima, start, aggregation) return(res) } minusloglik.COGARCH1<-function(param,env){ # assign("start.state", start.state, envir = my.env) # assign("q", info@q, envir = my.env) # assign("p", info@p, envir = my.env) # assign("time", time, envir = my.env) # assign("Obs", Obs, envir = my.env) # assign("nObs",length(Obs),envir = my.env) # assign("ar.names", ar.names, envir = my.env) # assign("ma.names", ma.names, envir = my.env) # assign("loc.par",[email protected], envir = my.env) a0<-param[env$loc.par] bq<-param[env$ar.names[env$q]] a1<-param[env$ma.names[1]] stateMean <- a0/(bq-a1)*as.matrix(c(1,numeric(length=(env$q-1)))) penalty <- 0 CondStat <- Diagnostic.Cogarch(env$mycog,param = as.list(param),display = FALSE) if(CondStat$stationary=="Try a different S matrix"){ penalty <-penalty + 10^6 } if(CondStat$positivity==" "){ penalty <- penalty + 10^6 } #param[env$start.state]<-stateMean state <- stateMean # state <- param[env$start.state] DeltaG2 <- env$Obs B <- env$B if(env$q>1){ #B[1:(env$q-1),] <- c(matrix(0,(env$p-1),1), diag(env$q-1)) B[1:(env$q-1),] <- cbind(matrix(0,(env$q-1),1), diag(env$q-1)) } B[env$q,] <- -param[env$ar.names[env$q:1]] a<-matrix(0,env$q,1) a[1:env$p,]<-param[env$ma.names] ta<-t(a) e <- env$e Btilde <-B+e%*%ta InvBtilde <- solve(Btilde) V1 <- a0+ta%*% state V <- V1[1] Deltat<- env$Deltat I <- env$I # VarDeltaG <- 0 PseudologLik <- 0 # DeltatB1 <- lapply(as.list(Deltat), function(dt,B){expm(B*dt)} , B) # # DeltatB <- lapply(as.list(Deltat), "*" , B) # # assign("DeltatB",as.list(DeltatB),.GlobalEnv) # outputB <- matrix(unlist(DeltatB1), ncol = env$q, byrow = TRUE) if(env$grideq){ DeltatB1 <- expm(B*Deltat) # DeltatB2 <- lapply(as.list(Deltat), function(dt,B){expm(B*dt)} , Btilde) # # DeltatB <- lapply(as.list(Deltat), "*" , B) # # assign("DeltatB",as.list(DeltatB),.GlobalEnv) # outputB2 <- matrix(unlist(DeltatB2), ncol = env$q, byrow = TRUE) DeltatB2 <- expm(Btilde*Deltat) # DeltatB3 <- lapply(as.list(-Deltat), function(dt,B){expm(B*dt)} , Btilde) # outputB3 <- matrix(unlist(DeltatB3), ncol = env$q, byrow = TRUE) DeltatB3 <- expm(-Btilde*Deltat) dummyMatr <- ta%*%DeltatB2%*%InvBtilde%*%(I-DeltatB3) dummyeB1 <- e%*%ta%*%DeltatB1 #aa <- .Call("myfun1", DeltatB1, state) PseudologLik <-.Call("pseudoLoglik_COGARCH1", a0, bq, a1, stateMean, Q=as.integer(env$q), DeltaG2, Deltat, DeltatB1, a, e, V, nObs=as.integer(env$nObs-1), dummyMatr, dummyeB1) - penalty #cat(sprintf("\n%.5f ", PseudologLik)) # # # PseudologLikR<-0 # V1 <- a0+ta%*% state # V <- V1[1] # # # for(i in c(1:(env$nObs-1))){ # # # cat(sprintf("\n dummy1R %.10f ",dummyMatr%*%(state-stateMean) )) # # d <- 0 # # for(j in 1:2){ # # d<- d+dummyMatr[1,j]*(state[j]-stateMean[j]) # # cat(sprintf("\n %d dummy1R %.10f ",j,d )) # # } # VarDeltaG <- a0*Deltat*bq/(bq-a1)+ dummyMatr%*%(state-stateMean) # # VarDeltaG <- VarDeltaG[1] # #state <- (I+DeltaG2[i]/V*e%*%ta)%*%DeltatB1%*%state+a0*DeltaG2[i]/V*e # state <- DeltatB1%*%state+DeltaG2[i]/V*dummyeB1%*%state+a0*DeltaG2[i]/V*e # #state <- DeltatB1%*%state+dummyeB1%*%state # # cat(sprintf("\n d1 %.10f d2 %.10f", DeltatB1%*%state, dummyeB1%*%state)); # V <- a0+ta%*% state # V <- V[1] # if(is.nan(VarDeltaG)) # VarDeltaG<- 10^(-6) # PseudologLikR<--0.5*(DeltaG2[i]/VarDeltaG+log(VarDeltaG)+log(2.*3.14159265))+PseudologLikR # # cat(sprintf("\n%.5f - %.5f %.5f - %.5f",VarDeltaG, state[1], state[2],V )) # cat(sprintf("\n Part %.10f partial %.10f ", PseudologLikR, VarDeltaG)) # if(is.nan(V)) # V <- 10^(-6) # # } # # # cat(sprintf("\n%.5f - %.5f",PseudologLikR, PseudologLik)) # # # # # }else{ # DeltatB1 <- lapply(as.list(Deltat), function(dt,B){expm(B*dt)} , B) # DeltatB2 <- lapply(as.list(Deltat), function(dt,B){expm(B*dt)} , Btilde) # DeltatB3 <- lapply(as.list(-Deltat), function(dt,B){expm(B*dt)} , Btilde) # # for(i in c(1:(env$nObs-1))){ # VarDeltaG <- as.numeric(a0*Deltat[i]*bq/(bq-a1)+ta%*%DeltatB2[[i]]%*%InvBtilde%*%(I-DeltatB3[[i]])%*%(state-stateMean)) # state <- (I+DeltaG2[i]/V*e%*%ta)%*%DeltatB1[[i]]%*%state+a0*DeltaG2[i]/V*e # V <- as.numeric(a0+ta%*% state) # PseudologLik<--1/2*(DeltaG2[i]/VarDeltaG+log(VarDeltaG)+log(2*pi))+PseudologLik # } # # PseudologLik <- 0 PseudologLik <- Irregular_PseudoLoglik_COG(lengthObs=(env$nObs-1), B, Btilde, InvBtilde, a0, bq, a1, V, PseudologLik, ta, state, stateMean, e, DeltaG2, Deltat) PseudologLik<-PseudologLik-penalty # # for(i in c(1:(env$nObs-1))){ # VarDeltaG <- a0*Deltat*bq/(bq-a1)+ dummyMatr%*%(state-stateMean) # #state <- (I+DeltaG2[i]/V*e%*%ta)%*%DeltatB1%*%state+a0*DeltaG2[i]/V*e # state <- DeltatB1%*%state+DeltaG2[i]/V*dummyeB1%*%state+a0*DeltaG2[i]/V*e # V <- as.numeric(a0+ta%*% state) # PseudologLik<--1/2*(DeltaG2[i]/VarDeltaG+log(VarDeltaG)+log(2*pi))+PseudologLik # } # for(i in c(1:(env$nObs-1))){ # VarDeltaG <- as.numeric(a0*Deltat[i]*bq/(bq-a1)+t(a)%*%DeltatB2[[i]]%*%InvBtilde%*%(I-DeltatB3[[i]])%*%(state-stateMean)) # state <- (I+DeltaG2[i]/V*e%*%t(a))%*%DeltatB1[[i]]%*%state+a0*DeltaG2[i]/V*e # V <- as.numeric(a0+t(a)%*% state) # PseudologLik<--1/2*(DeltaG2[i]/VarDeltaG+log(VarDeltaG)+log(2*pi)) # } # dummyMatr <- ta%*%DeltatB2%*%InvBtilde%*%(I-DeltatB3) # dummyeB1 <- e%*%ta%*%DeltatB1 # PseudologLik1 <- 0 # for(i in c(1:(env$nObs-1))){ # VarDeltaG <- as.numeric(a0*Deltat*bq/(bq-a1)+dummyMatr%*%(state-stateMean)) # state <- DeltatB1%*%state+DeltaG2[i]/V*dummyeB1%*%state+a0*DeltaG2[i]/V*e # V <- as.numeric(a0+ta%*% state) # PseudologLik1 <- -1/2*(DeltaG2[i]/VarDeltaG+log(VarDeltaG)+log(2*pi)) # if(is.finite(PseudologLik1)){ # PseudologLik <- PseudologLik1 + PseudologLik # } # } } minusPseudoLogLik <- -PseudologLik return(minusPseudoLogLik) } # res<-.Call("pseudoLoglik_COGARCH", a0, bq, a1, stateMean, Q=as.integer(env$q), # state, DeltaG2, Deltat, DeltatB, B, a, e, # Btilde, InvBtilde, V, I, VarDeltaG, # PseudologLik, nObs = as.integer(env$nObs-1), fn = quote(expm(x)) , rho= .GlobalEnv, # PACKAGE = "yuima") # # output <- matrix(unlist(res), ncol = env$q, byrow = TRUE) # res <- res
/scratch/gouwar.j/cran-all/cranData/yuima/R/PseudoLogLikCOGARCH.R
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 evalKernelCpp <- function(Integrand2, Integrand2expr, myenvd1, myenvd2, ExistdN, ExistdX, gridTime, dimCol, NameCol, JumpTimeName) { .Call('_yuima_evalKernelCpp', PACKAGE = 'yuima', Integrand2, Integrand2expr, myenvd1, myenvd2, ExistdN, ExistdX, gridTime, dimCol, NameCol, JumpTimeName) } evalKernelCpp2 <- function(Integrand2, Integrand2expr, myenvd1, myenvd2, CondIntensity, NameCountingVar, Namecovariates, ExistdN, ExistdX, gridTime, dimCol, NameCol, JumpTimeName) { .Call('_yuima_evalKernelCpp2', PACKAGE = 'yuima', Integrand2, Integrand2expr, myenvd1, myenvd2, CondIntensity, NameCountingVar, Namecovariates, ExistdN, ExistdX, gridTime, dimCol, NameCol, JumpTimeName) } sqnorm <- function(x) { .Call('_yuima_sqnorm', PACKAGE = 'yuima', x) } makeprop <- function(mu, sample, low, up) { .Call('_yuima_makeprop', PACKAGE = 'yuima', mu, sample, low, up) } is_zero <- function(x) { .Call('_yuima_is_zero', PACKAGE = 'yuima', x) } cpp_split <- function(str, sep) { .Call('_yuima_cpp_split', PACKAGE = 'yuima', str, sep) } cpp_paste <- function(x, y, sep) { .Call('_yuima_cpp_paste', PACKAGE = 'yuima', x, y, sep) } cpp_collapse <- function(str, sep) { .Call('_yuima_cpp_collapse', PACKAGE = 'yuima', str, sep) } cpp_outer <- function(x, y) { .Call('_yuima_cpp_outer', PACKAGE = 'yuima', x, y) } cpp_ito_outer <- function(x, y) { .Call('_yuima_cpp_ito_outer', PACKAGE = 'yuima', x, y) } cpp_label <- function(I) { .Call('_yuima_cpp_label', PACKAGE = 'yuima', I) } cpp_ito_product <- function(idx, dZ, Z_K, K, d, a, p, q = 0L) { .Call('_yuima_cpp_ito_product', PACKAGE = 'yuima', idx, dZ, Z_K, K, d, a, p, q) } cpp_E <- function(str) { .Call('_yuima_cpp_E', PACKAGE = 'yuima', str) } cpp_ito <- function(K_set, dZ, Z_K, d, r) { .Call('_yuima_cpp_ito', PACKAGE = 'yuima', K_set, dZ, Z_K, d, r) } W1 <- function(crossdx, b, A, h) { .Call('_yuima_W1', PACKAGE = 'yuima', crossdx, b, A, h) } W2 <- function(dx, b, h) { .Call('_yuima_W2', PACKAGE = 'yuima', dx, b, h) } Irregular_PseudoLoglik_COG <- function(lengthObs, B, Btilde, InvBtilde, a0, bq, a1, V, PseudologLik, ta, state, stateMean, e, DeltaG2, Deltat) { .Call('_yuima_Irregular_PseudoLoglik_COG', PACKAGE = 'yuima', lengthObs, B, Btilde, InvBtilde, a0, bq, a1, V, PseudologLik, ta, state, stateMean, e, DeltaG2, Deltat) } detcpp <- function(A) { .Call('_yuima_detcpp', PACKAGE = 'yuima', A) } Smake <- function(b, d) { .Call('_yuima_Smake', PACKAGE = 'yuima', b, d) } solvecpp <- function(A) { .Call('_yuima_solvecpp', PACKAGE = 'yuima', A) } sub_f <- function(S, b) { .Call('_yuima_sub_f', PACKAGE = 'yuima', S, b) } likndim <- function(dx, b, A, h) { .Call('_yuima_likndim', PACKAGE = 'yuima', dx, b, A, h) } residualCpp <- function(dx, a, b, w, h) { .Call('_yuima_residualCpp', PACKAGE = 'yuima', dx, a, b, w, h) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/RcppExports.R
WoodChanfGn <- function( mesh , H , dimmesh ) { ##-------------------------------------------------------------------------- ## Author : Alexandre Brouste ## Project: Yuima ##-------------------------------------------------------------------------- ##-------------------------------------------------------------------------- ## Input mesh : mesh grid where the fBm is evaluated ## H : self-similarity parameter ## dim : valued in R^dim ## ## ## Output : ##-------------------------------------------------------------------------- ##-------------------------------------------------------------------------- ## Complexity ? ## ------------------------------------------------------------------------- mesh<-mesh[[1]] N<-length(mesh)-2 # N+1 is the size of the fGn sample to be simulated fGn<-matrix(0,dimmesh,N+1) T<-mesh[N+2] H2 <- 2*H k <- 0:N autocov<-0.5 * (abs(k-1)^H2 - 2*(k)^H2 + (k+1)^H2) * (T/(N+1))^H2 # g(0),g(1),g(n-1),g(1) ligne1C<-autocov[1 + c(0:N,(N-1):1)] lambdak<-Re(fft(ligne1C,inverse = TRUE)) for (k in 1:dimmesh){ zr <- rnorm(N+1) zi <- rnorm(N-1) zr[c(1,N+1)] <- zr[c(1,N+1)]*sqrt(2) zr <- c(zr[1:(N+1)], zr[N:2]) zi <- c(0,zi,0,-zi[(N-1):1]) z <- Re(fft((zr + 1i* zi) * sqrt(lambdak), inverse = TRUE)) fGn[k,]<-z[1:(N+1)] / (2*sqrt(N)) } #Traitement des zeros #La matrice est definie positive (voir 17) return(fGn) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/WoodChanfGn.R
##::quasi-bayes function setGeneric("adaBayes", function(yuima, start,prior,lower,upper, method="mcmc",iteration=NULL,mcmc,rate=1.0, rcpp=TRUE,algorithm="randomwalk",center=NULL,sd=NULL,rho=NULL,path=FALSE ) standardGeneric("adaBayes") ) # # adabayes<- setClass("adabayes",contains = "mle", # slots = c(mcmc="list", accept_rate="list",coef = "numeirc", # call="call",vcov="matrix",fullcoef="numeric",model="yuima.model")) adabayes<- setClass("adabayes", #contains = "mle", slots = c(mcmc="list", accept_rate="list",coef = "numeric",call="call",vcov="matrix",fullcoef="numeric")) setMethod("adaBayes", "yuima", function(yuima, start,prior,lower,upper, method="mcmc",iteration=NULL,mcmc,rate=1.0,rcpp=TRUE, algorithm="randomwalk",center=NULL,sd=NULL,rho=NULL,path=FALSE ) { if(length(iteration)>0){mcmc=iteration} mean=unlist(center) joint <- FALSE fixed <- numeric(0) print <- FALSE call <- match.call() if( missing(yuima)) yuima.stop("yuima object is missing.") ## param handling ## FIXME: maybe we should choose initial values at random within lower/upper ## at present, qmle stops if(missing(lower) || missing(upper)){ if(missing(prior)){ lower = numeric(0) upper = numeric(0) pdlist <- numeric(length(yuima@model@parameter@all)) names(pdlist) <- yuima@model@parameter@all for(i in 1: length(pdlist)){ lower = append(lower,-Inf) upper = append(upper,Inf) } } # yuima.stop("lower or upper is missing.") } diff.par <- yuima@model@parameter@diffusion drift.par <- yuima@model@parameter@drift jump.par <- yuima@model@parameter@jump measure.par <- yuima@model@parameter@measure common.par <- yuima@model@parameter@common ## BEGIN Prior construction if(!missing(prior)){ priorLower = numeric(0) priorUpper = numeric(0) pdlist <- numeric(length(yuima@model@parameter@all)) names(pdlist) <- yuima@model@parameter@all for(i in 1: length(pdlist)){ if(prior[[names(pdlist)[i]]]$measure.type=="code"){ expr <- prior[[names(pdlist)[i]]]$df code <- suppressWarnings(sub("^(.+?)\\(.+", "\\1", expr, perl=TRUE)) args <- unlist(strsplit(suppressWarnings(sub("^.+?\\((.+)\\)", "\\1", expr, perl=TRUE)), ",")) pdlist[i] <- switch(code, dunif=paste("function(z){return(dunif(z, ", args[2], ", ", args[3],"))}"), dnorm=paste("function(z){return(dnorm(z,", args[2], ", ", args[3], "))}"), dbeta=paste("function(z){return(dbeta(z, ", args[2], ", ", args[3], "))}"), dgamma=paste("function(z){return(dgamma(z, ", args[2], ", ", args[3], "))}"), dexp=paste("function(z){return(dexp(z, ", args[2], "))}") ) qf <- switch(code, dunif=paste("function(z){return(qunif(z, ", args[2], ", ", args[3],"))}"), dnorm=paste("function(z){return(qnorm(z,", args[2], ", ", args[3], "))}"), dbeta=paste("function(z){return(qbeta(z, ", args[2], ", ", args[3], "))}"), dgamma=paste("function(z){return(qgamma(z, ", args[2], ", ", args[3], "))}"), dexp=paste("function(z){return(qexp(z, ", args[2], "))}") ) priorLower = append(priorLower,eval(parse("text"=qf))(0.00)) priorUpper = append(priorUpper,eval(parse("text"=qf))(1.00)) } } #20200518kaino names(priorLower)<-names(pdlist) names(priorUpper)<-names(pdlist) if(missing(lower) || missing(upper)){ lower <- priorLower upper <- priorUpper } else{ #20200518kaino #if(sum(unlist(lower)<priorLower) + sum(unlist(upper)>priorUpper) > 0){ if(sum(unlist(lower)<priorLower[names(lower)]) + sum(unlist(upper)>priorUpper[names(upper)]) > 0){ yuima.stop("lower&upper of prior are out of parameter space.") } } #20200518 #names(lower) <- names(pdlist) #names(upper) <- names(pdlist) pd <- function(param){ value <- 1 for(i in 1:length(pdlist)){ value <- value*eval(parse(text=pdlist[[i]]))(param[[i]]) } return(value) } }else{ pd <- function(param) return(1) } ## END Prior construction if(!is.list(lower)){ lower <- as.list(lower) } if(!is.list(upper)){ upper <- as.list(upper) } JointOptim <- joint if(length(common.par)>0){ JointOptim <- TRUE yuima.warn("Drift and diffusion parameters must be different. Doing joint estimation, asymptotic theory may not hold true.") } if(length(jump.par)+length(measure.par)>0) yuima.stop("Cannot estimate the jump models, yet") fulcoef <- NULL if(length(diff.par)>0) fulcoef <- diff.par if(length(drift.par)>0) fulcoef <- c(fulcoef, drift.par) if(length(yuima@model@parameter@common)>0){ fulcoef<-unique(fulcoef) } fixed.par <- names(fixed) if (any(!(fixed.par %in% fulcoef))) yuima.stop("Some named arguments in 'fixed' are not arguments to the supplied yuima model") nm <- names(start) npar <- length(nm) oo <- match(nm, fulcoef) if(any(is.na(oo))) yuima.stop("some named arguments in 'start' are not arguments to the supplied yuima model") start <- start[order(oo)] if(!missing(prior)){ #20200525kaino #pdlist <- pdlist[order(oo)] pdlist <- pdlist[names(start)] } nm <- names(start) idx.diff <- match(diff.par, nm) idx.drift <- match(drift.par,nm) if(length(common.par)>0){ idx.common=match(common.par,nm) idx.drift=setdiff(idx.drift,idx.common) } idx.fixed <- match(fixed.par, nm) tmplower <- as.list( rep( -Inf, length(nm))) names(tmplower) <- nm if(!missing(lower)){ idx <- match(names(lower), names(tmplower)) if(any(is.na(idx))) yuima.stop("names in 'lower' do not match names fo parameters") tmplower[ idx ] <- lower } lower <- tmplower tmpupper <- as.list( rep( Inf, length(nm))) names(tmpupper) <- nm if(!missing(upper)){ idx <- match(names(upper), names(tmpupper)) if(any(is.na(idx))) yuima.stop("names in 'lower' do not match names fo parameters") tmpupper[ idx ] <- upper } upper <- tmpupper d.size <- yuima@[email protected] #20200601kaino if (is.CARMA(yuima)){ # 24/12 d.size <-1 } n <- length(yuima)[1] G <- rate if(G<=0 || G>1){ yuima.stop("rate G should be 0 < G <= 1") } n_0 <- floor(n^G) if(n_0 < 2) n_0 <- 2 #######data is reduced to n_0 before qmle(16/11/2016) env <- new.env() #assign("X", yuima@[email protected][1:n_0,], envir=env) assign("X", as.matrix(onezoo(yuima)[1:n_0,]), envir=env) assign("deltaX", matrix(0, n_0 - 1, d.size), envir=env) assign("time", as.numeric(index(yuima@[email protected][[1]])), envir=env) #20200601kaino if (is.CARMA(yuima)){ #24/12 If we consider a carma model, # the observations are only the first column of env$X # assign("X", as.matrix(onezoo(yuima)), envir=env) # env$X<-as.matrix(env$X[,1]) # assign("deltaX", matrix(0, n-1, d.size)[,1], envir=env) env$X<-as.matrix(env$X[,1]) env$deltaX<-as.matrix(env$deltaX[,1]) assign("time.obs",length(env$X),envir=env) assign("p", yuima@model@info@p, envir=env) assign("q", yuima@model@info@q, envir=env) assign("V_inf0", matrix(diag(rep(1,env$p)),env$p,env$p), envir=env) } assign("Cn.r", rep(1,n_0-1), envir=env) for(t in 1:(n_0-1)) env$deltaX[t,] <- env$X[t+1,] - env$X[t,] assign("h", deltat(yuima@[email protected][[1]]), envir=env) pp<-0 if(env$h >= 1){ qq <- 2/G }else{ while(1){ if(n*env$h^pp < 0.1) break pp <- pp + 1 } qq <- max(pp,2/G) } C.temper.diff <- n_0^(2/(qq*G)-1) #this is used in pg. C.temper.drift <- (n_0*env$h)^(2/(qq*G)-1) #this is used in pg. mle <- qmle(yuima, "start"=start, "lower"=lower,"upper"=upper, "method"="L-BFGS-B",rcpp=rcpp) start <- as.list(mle@coef) sigma.diff=NULL sigma.drift=NULL if(length(sd)<npar){ sigma=mle@vcov; } # if(length(diff.par)>0){ # sigma.diff=diag(1,length(diff.par)) # for(i in 1:length(diff.par)){ # sigma.diff[i,i]=sd[[diff.par[i]]] # } # } # # if(length(drift.par)>0){ # sigma.drift=diag(1,length(drift.par)) # for(i in 1:length(drift.par)){ # sigma.drift[i,i]=sd[[drift.par[i]]] # } # } #} # mu.diff=NULL # mu.drift=NULL # # # if(length(mean)<npar){ # mu.diff=NULL # mu.drift=NULL} #else{ # if(length(diff.par)>0){ # for(i in 1:length(diff.par)){ # mu.diff[i]=mean[[diff.par[i]]] # } # } # # if(length(drift.par)>0){ # for(i in 1:length(drift.par)){ # mu.drift[i]=mean[[drift.par[i]]] # } # } # } ####mpcn make proposal sqn<-function(x,LL){ vv=x%*%LL zz=sum(vv*vv) if(zz<0.0000001){ zz=0.0000001 } return(zz) } # mpro<-function(mu,sample,low,up,rho,LL,L){ # d=length(mu); # tmp=mu+sqrt(rho)*(sample-mu); # tmp = mu+sqrt(rho)*(sample-mu); # dt=(sample-mu)%*%LL%*%(sample-mu) # tmp2 = 2.0/dt; # while(1){ # prop = tmp+rnorm(d)*L*sqrt((1.0-rho)/rgamma(1,0.5*d,tmp2)); # if((sum(low>prop)+sum(up<prop))==0) break; # } # return(prop) # } make<-function(mu,sample,low,up,rho,LL,L){ d=length(mu); tmp=mu+sqrt(rho)*(sample-mu); dt=sqn(sample-mu,LL); tmp2 = 2.0/dt; prop = tmp+rnorm(d)%*%L*sqrt((1.0-rho)/rgamma(1,0.5*d,scale=tmp2)); # for(i in 1:100){ # prop = tmp+rnorm(d)*sqrt((1.0-rho)/rgamma(1,0.5*d,tmp2)); # if((sum(low>prop)+sum(up<prop))==0){break;} # flg=flg+1; # } # if(flg>100){print("error")}else{ # return(prop) # } return(prop) } integ <- function(idx.fixed=NULL,f=f,start=start,par=NULL,hessian=FALSE,upper,lower){ if(length(idx.fixed)==0){ intf <- hcubature(f,lowerLimit=unlist(lower),upperLimit=unlist(upper),fDim=(length(upper)+1))$integral }else{ intf <- hcubature(f,lowerLimit=unlist(lower[-idx.fixed]),upperLimit=unlist(upper[-idx.fixed]),fDim=(length(upper[-idx.fixed])+1))$integral } return(intf[-1]/intf[1]) } mcinteg <- function(idx.fixed=NULL,f=f,p,start=start,par=NULL,hessian=FALSE,upper,lower,mean,vcov,mcmc){ #vcov=vcov[nm,nm];#Song add if(setequal(unlist(drift.par),unlist(diff.par))&(length(mean)>length(diff.par))){mean=mean[1:length(diff.par)]} if(length(idx.fixed)==0){#only have drift or diffusion part intf <- mcintegrate(f,p,lowerLimit=lower,upperLimit=upper,mean,vcov,mcmc) }else{ intf <- mcintegrate(f,p,lowerLimit=lower[-idx.fixed],upperLimit=upper[-idx.fixed],mean[-idx.fixed],vcov[-idx.fixed,-idx.fixed],mcmc) } return(intf) } mcintegrate <- function(f,p, lowerLimit, upperLimit,mean,vcov,mcmc){ acc=0 if(algorithm=="randomwalk"){ x_c <- mean if(path){ X <- matrix(0,mcmc,length(mean)) acc=0 } nm=length(mean) if(length(vcov)!=(nm^2)){ vcov=diag(1,nm,nm)*vcov[1:nm,1:nm] } sigma=NULL if(length(sd)>0&length(sd)==npar){ sigma=diag(sd,npar,npar); if(length(idx.fixed)>0){ vcov=sigma[-idx.fixed,-idx.fixed] }else{ vcov=sigma; } } p_c <- p(x_c) val <- f(x_c) if(path) X[1,] <- x_c # if(length(mean)>1){ # x <- rmvnorm(mcmc-1,mean,vcov) # q <- dmvnorm(x,mean,vcov) # q_c <- dmvnorm(mean,mean,vcov) # }else{ # x <- rnorm(mcmc-1,mean,sqrt(vcov)) # q <- dnorm(x,mean,sqrt(vcov)) # q_c <- dnorm(mean,mean,sqrt(vcov)) # } # for(i in 1:(mcmc-1)){ if(length(mean)>1){ x_n <- rmvnorm(1,x_c,vcov) #if(sum(x_n<lowerLimit)==0 & sum(x_n>upperLimit)==0) break }else{ x_n <- rnorm(1,x_c,sqrt(vcov)) #if(sum(x_n<lowerLimit)==0 & sum(x_n>upperLimit)==0) break } if(sum(x_n<lowerLimit)==0 & sum(x_n>upperLimit)==0){ p_n <- p(x_n) u <- log(runif(1)) a <- p_n-p_c if(u<a){ p_c <- p_n # q_c <- q_n x_c <- x_n acc=acc+1 } } if(path) X[i+1,] <- x_c #} val <- val+f(x_c) } if(path){ return(list(val=unlist(val/mcmc),X=X,acc=acc/mcmc)) }else{ return(list(val=unlist(val/mcmc))) } } else if(tolower(algorithm)=="mpcn"){ #MpCN if(path) X <- matrix(0,mcmc,length(mean)) if((sum(idx.diff==idx.fixed)==0)){ if(length(center)>0){ if(length(idx.fixed)>0){ mean =unlist(center[-idx.fixed]) }else{ mean =unlist(center) ##drift or diffusion parameter only } } } # if((sum(idx.diff==idx.fixed)>0)){ # if(length(center)>0){ # mean =unlist(center[-idx.fixed]) # } # } x_n <- mean val <- mean L=diag(1,length(mean));LL=L; nm=length(mean) LL=vcov; if(length(vcov)!=(nm^2)){ LL=diag(1,nm,nm) } if(length(sd)>0&length(sd)==npar){ sigma=diag(sd,npar,npar); if(length(idx.fixed)>0){ LL=sigma[-idx.fixed,-idx.fixed] }else{ LL=sigma; } } # if(length(pre_conditionnal)==1){ # LL=t(chol(solve(vcov)));L=chol(vcov); # } if(length(rho)==0){rho=0.8} logLik_old <- p(x_n)+0.5*length(mean)*log(sqn(x_n-mean,LL)) if(path) X[1,] <- x_n for(i in 1:(mcmc-1)){ prop <- make(mean,x_n,unlist(lowerLimit),unlist(upperLimit),rho,LL,L) if((sum(prop<lowerLimit)+sum(prop>upperLimit))==0){ logLik_new <- p(prop)+0.5*length(mean)*log(sqn(prop-mean,LL)) u <- log(runif(1)) if( logLik_new-logLik_old > u){ x_n <- prop logLik_old <- logLik_new acc=acc+1 } } if(path) X[i+1,] <- x_n val <- val+f(x_n) } #return(unlist(val/mcmc)) if(path){ return(list(val=unlist(val/mcmc),X=X,acc=acc/mcmc)) }else{ return(list(val=unlist(val/mcmc))) } } } #print(mle@coef) flagNotPosDif <- 0 for(i in 1:npar){ if(mle@vcov[i,i] <= 0) flagNotPosDif <- 1 #Check mle@vcov is positive difinite matrix } if(flagNotPosDif == 1){ mle@vcov <- diag(c(rep(1 / n_0,length(diff.par)),rep(1 / (n_0 * env$h), npar-length(diff.par)))) # Redifine mle@vcov } # cov.diff=mle@vcov[1:length(diff.par),1:length(diff.par)] # cov.drift=mle@vcov[(length(diff.par)+1):(length(diff.par)+length(drift.par)),(length(diff.par)+1):(length(diff.par)+length(drift.par))] # if(missing(cov){ # }else{ # cov.diff=cov[[1]] # cov.drift=cov[[2]] tmp <- minusquasilogl(yuima=yuima, param=mle@coef, print=print, env,rcpp=rcpp) g <- function(p,fixed,idx.fixed){ mycoef <- mle@coef #mycoef <- as.list(p) if(length(idx.fixed)>0){ mycoef[-idx.fixed] <- p mycoef[idx.fixed] <- fixed }else{ mycoef <- as.list(p) names(mycoef) <- nm } return(c(1,p)*exp(-minusquasilogl(yuima=yuima, param=mycoef, print=print, env,rcpp=rcpp)+tmp)*pd(param=mycoef)) } pg <- function(p,fixed,idx.fixed){ mycoef <- start #mycoef <- as.list(p) if(length(idx.fixed)>0){ mycoef[-idx.fixed] <- p mycoef[idx.fixed] <- fixed }else{ mycoef <- as.list(p) names(mycoef) <- nm } # mycoef <- as.list(p) # names(mycoef) <- nm #return(exp(-minusquasilogl(yuima=yuima, param=mycoef, print=print, env)+tmp)*pd(param=mycoef)) #return(-minusquasilogl(yuima=yuima, param=mycoef, print=print, env,rcpp=rcpp)+tmp+log(pd(param=mycoef)))#log if(sum(idx.diff==idx.fixed)>0){ #return(C.temper.diff*(-minusquasilogl(yuima=yuima, param=mycoef, print=print, env,rcpp=rcpp)+tmp+log(pd(param=mycoef))))#log return(C.temper.drift*(-minusquasilogl(yuima=yuima, param=mycoef, print=print, env,rcpp=rcpp)+tmp+log(pd(param=mycoef))))#log }else{ #return(C.temper.drift*(-minusquasilogl(yuima=yuima, param=mycoef, print=print, env,rcpp=rcpp)+tmp+log(pd(param=mycoef))))#log return(C.temper.diff*(-minusquasilogl(yuima=yuima, param=mycoef, print=print, env,rcpp=rcpp)+tmp+log(pd(param=mycoef))))#log } } idf <- function(p){return(p)} # fj <- function(p) { # mycoef <- as.list(p) # names(mycoef) <- nm # mycoef[fixed.par] <- fixed # minusquasilogl(yuima=yuima, param=mycoef, print=print, env) # } X.diff <- NULL X.drift <- NULL oout <- NULL HESS <- matrix(0, length(nm), length(nm)) colnames(HESS) <- nm rownames(HESS) <- nm HaveDriftHess <- FALSE HaveDiffHess <- FALSE if(length(start)){ # if(JointOptim){ ### joint optimization # if(length(start)>1){ #multidimensional optim # oout <- optim(start, fj, method = method, hessian = TRUE, lower=lower, upper=upper) # HESS <- oout$hessian # HaveDriftHess <- TRUE # HaveDiffHess <- TRUE # } else { ### one dimensional optim # opt1 <- optimize(f, ...) ## an interval should be provided # opt1 <- list(par=integ(f=f,upper=upper,lower=lower,fDim=length(lower)+1),objective=0) # oout <- list(par = opt1$minimum, value = opt1$objective) # } ### endif( length(start)>1 ) # } else { ### first diffusion, then drift theta1 <- NULL acc.diff<-NULL old.fixed <- fixed old.start <- start if(length(idx.diff)>0){ ## DIFFUSION ESTIMATIOn first old.fixed <- fixed old.start <- start new.start <- start[idx.diff] # considering only initial guess for diffusion new.fixed <- fixed if(length(idx.drift)>0) new.fixed[nm[idx.drift]] <- start[idx.drift] fixed <- new.fixed fixed.par <- names(fixed) idx.fixed <- match(fixed.par, nm) names(new.start) <- nm[idx.diff] f <- function(p){return(g(p,fixed,idx.fixed))} pf <- function(p){return(pg(p,fixed,idx.fixed))} if(length(unlist(new.start))>1){ # oout <- do.call(optim, args=mydots) if(method=="mcmc"){ #oout <- list(par=mcinteg(idx.fixed=idx.fixed,f=idf,p=pf,upper=upper,lower=lower,mean=mle@coef,vcov=mle@vcov,mcmc=mcmc)) mci=mcinteg(idx.fixed=idx.fixed,f=idf,p=pf,upper=upper,lower=lower,mean=mle@coef,vcov=mle@vcov,mcmc=mcmc) X.diff=mci$X acc.diff=mci$acc oout <- list(par=mci$val) }else{ oout <- list(par=integ(idx.fixed=idx.fixed,f=f,upper=upper,lower=lower,start=start)) } } else { # opt1 <- do.call(optimize, args=mydots) if(method=="mcmc"){ #opt1 <- list(minimum=mcinteg(idx.fixed=idx.fixed,f=idf,p=pf,upper=upper,lower=lower,mean=mle@coef,vcov=mle@vcov,mcmc=mcmc)) mci=mcinteg(idx.fixed=idx.fixed,f=idf,p=pf,upper=upper,lower=lower,mean=mle@coef,vcov=mle@vcov,mcmc=mcmc) if(path) X.diff=mci$X acc.diff=mci$acc opt1 <- list(minimum=mci$val) }else{ opt1 <- list(minimum=integ(idx.fixed=idx.fixed,f=f,upper=upper,lower=lower)) } theta1 <- opt1$minimum #names(theta1) <- diff.par # oout <- list(par = theta1, value = opt1$objective) oout <- list(par=theta1,value=0) } theta1 <- oout$par #names(theta1) <- nm[idx.diff] names(theta1) <- diff.par } ## endif(length(idx.diff)>0) theta2 <- NULL acc.drift<-NULL if(length(idx.drift)>0 & setequal(unlist(drift.par),unlist(diff.par))==FALSE){ ## DRIFT estimation with first state diffusion estimates fixed <- old.fixed start <- old.start new.start <- start[idx.drift] # considering only initial guess for drift new.fixed <- fixed new.fixed[names(theta1)] <- theta1 fixed <- new.fixed fixed.par <- names(fixed) idx.fixed <- match(fixed.par, nm) names(new.start) <- nm[idx.drift] f <- function(p){return(g(p,fixed,idx.fixed))} pf <- function(p){return(pg(p,fixed,idx.fixed))} if(length(unlist(new.start))>1){ # oout1 <- do.call(optim, args=mydots) if(method=="mcmc"){ #oout1 <- list(par=mcinteg(idx.fixed=idx.fixed,f=idf,p=pf,upper=upper,lower=lower,mean=mle@coef,vcov=mle@vcov,mcmc=mcmc)) mci=mcinteg(idx.fixed=idx.fixed,f=idf,p=pf,upper=upper,lower=lower,mean=mle@coef,vcov=mle@vcov,mcmc=mcmc) if(path) X.drift=mci$X acc.drift=mci$acc #20200601kaino #oout1 <- list(minimum=mci$val) oout1 <- list(par=mci$val) }else{ oout1 <- list(par=integ(idx.fixed=idx.fixed,f=f,upper=upper,lower=lower)) } } else { # opt1 <- do.call(optimize, args=mydots) if(method=="mcmc"){ #opt1 <- list(minimum=mcinteg(idx.fixed=idx.fixed,f=idf,p=pf,upper=upper,lower=lower,mean=mle@coef,vcov=mle@vcov,mcmc=mcmc)) mci=mcinteg(idx.fixed=idx.fixed,f=idf,p=pf,upper=upper,lower=lower,mean=mle@coef,vcov=mle@vcov,mcmc=mcmc) X.drift=mci$X acc.drift=mci$acc opt1 <- list(minimum=mci$val) }else{ opt1 <- list(minimum=integ(idx.fixed=idx.fixed,f=f,upper=upper,lower=lower)) } theta2 <- opt1$minimum names(theta2) <-nm[-idx.fixed] oout1 <- list(par = theta2, value = as.numeric(opt1$objective)) } theta2 <- oout1$par } ## endif(length(idx.drift)>0) oout1 <- list(par=c(theta1, theta2)) names(oout1$par) <-nm # c(diff.par,drift.par) oout <- oout1 # } ### endif JointOptim } else { list(par = numeric(0L), value = f(start)) } # if(path){ # return(list(coef=oout$par,X.diff=X.diff,X.drift=X.drift,accept_rate=accept_rate)) # }else{ # return(list(coef=oout$par)) # } fDrift <- function(p) { mycoef <- as.list(p) names(mycoef) <- drift.par mycoef[diff.par] <- coef[diff.par] minusquasilogl(yuima=yuima, param=mycoef, print=print, env,rcpp=rcpp) } fDiff <- function(p) { mycoef <- as.list(p) names(mycoef) <- diff.par mycoef[drift.par] <- coef[drift.par] minusquasilogl(yuima=yuima, param=mycoef, print=print, env,rcpp=rcpp) } coef <- oout$par control=list() par <- coef names(par) <- nm #names(par) <- c(diff.par, drift.par) #nm <- c(diff.par, drift.par) # print(par) # print(coef) conDrift <- list(trace = 5, fnscale = 1, parscale = rep.int(5, length(drift.par)), ndeps = rep.int(0.001, length(drift.par)), maxit = 100L, abstol = -Inf, reltol = sqrt(.Machine$double.eps), alpha = 1, beta = 0.5, gamma = 2, REPORT = 10, type = 1, lmm = 5, factr = 1e+07, pgtol = 0, tmax = 10, temp = 10) conDiff <- list(trace = 5, fnscale = 1, parscale = rep.int(5, length(diff.par)), ndeps = rep.int(0.001, length(diff.par)), maxit = 100L, abstol = -Inf, reltol = sqrt(.Machine$double.eps), alpha = 1, beta = 0.5, gamma = 2, REPORT = 10, type = 1, lmm = 5, factr = 1e+07, pgtol = 0, tmax = 10, temp = 10) # nmsC <- names(con) # if (method == "Nelder-Mead") # con$maxit <- 500 # if (method == "SANN") { # con$maxit <- 10000 # con$REPORT <- 100 # } # con[(namc <- names(control))] <- control # if (length(noNms <- namc[!namc %in% nmsC])) # warning("unknown names in control: ", paste(noNms, collapse = ", ")) # if (con$trace < 0) # warning("read the documentation for 'trace' more carefully") # else if (method == "SANN" && con$trace && as.integer(con$REPORT) == # 0) # stop("'trace != 0' needs 'REPORT >= 1'") # if (method == "L-BFGS-B" && any(!is.na(match(c("reltol", # "abstol"), namc)))) # warning("method L-BFGS-B uses 'factr' (and 'pgtol') instead of 'reltol' and 'abstol'") # npar <- length(par) # if (npar == 1 && method == "Nelder-Mead") # warning("one-diml optimization by Nelder-Mead is unreliable: use optimize") # if(!HaveDriftHess & (length(drift.par)>0)){ #hess2 <- .Internal(optimhess(coef[drift.par], fDrift, NULL, conDrift)) hess2 <- optimHess(coef[drift.par], fDrift, NULL, control=conDrift) HESS[drift.par,drift.par] <- hess2 } if(!HaveDiffHess & (length(diff.par)>0)){ #hess1 <- .Internal(optimhess(coef[diff.par], fDiff, NULL, conDiff)) hess1 <- optimHess(coef[diff.par], fDiff, NULL, control=conDiff) HESS[diff.par,diff.par] <- hess1 } oout$hessian <- HESS # vcov <- if (length(coef)) # solve(oout$hessian) # else matrix(numeric(0L), 0L, 0L) mycoef <- as.list(coef) names(mycoef) <- nm mycoef[fixed.par] <- fixed #min <- minusquasilogl(yuima=yuima, param=mycoef, print=print, env,rcpp=rcpp) # # new("mle", call = call, coef = coef, fullcoef = unlist(mycoef), # # # vcov = vcov, min = min, details = oout, minuslogl = minusquasilogl, # vcov = vcov, details = oout, # method = method) mcmc_sample<-cbind(X.diff,X.drift) mcmc<-list() lf=length(diff.par) vcov=matrix(0,npar,npar) if(path){ if(lf>1){ vcov[1:lf,1:lf]=cov(X.diff) }else if(lf==1){ vcov[1:lf,1:lf]=var(X.diff) } if((npar-lf)>1){ vcov[(lf+1):npar,(lf+1):npar]=cov(X.drift) }else if((npar-lf)==1){ vcov[(lf+1):npar,(lf+1):npar]=var(X.drift) } } accept_rate<-list() if(path){ for(i in 1:npar){ mcmc[[i]]=as.mcmc(mcmc_sample[,i]) } #para_drift=yuima@model@parameter@drift[yuima@model@parameter@drift!=yuima@model@parameter@common] names(mcmc) <-nm;# c(yuima@model@parameter@diffusion,para_drift) accept_rate=list(acc.drift,acc.diff) names(accept_rate)<-c("accepte.rate.drift","accepte.rate.diffusion") }else{ mcmc=list("NULL") accept_rate=list("NULL") } fulcoef = unlist(mycoef); new("adabayes",mcmc=mcmc, accept_rate=accept_rate,coef=fulcoef,call=call,vcov=vcov,fullcoef=fulcoef) } ) setGeneric("coef") setMethod("coef", "adabayes", function(object) object@fullcoef )
/scratch/gouwar.j/cran-all/cranData/yuima/R/adaBayes.R
#' Class for the asymptotic expansion of diffusion processes #' #' The \code{yuima.ae} class is used to describe the output of the functions \code{\link{ae}} and \code{\link{aeMarginal}}. #' #' @slot order integer. The order of the expansion. #' @slot var character. The state variables. #' @slot u.var character. The variables of the characteristic function. #' @slot eps.var character. The perturbation variable. #' @slot characteristic expression. The characteristic function. #' @slot density expression. The probability density function. #' @slot Z0 numeric. The solution to the deterministic process obtained by setting the perturbation to zero. #' @slot Mu numeric. The drift vector for the representation of Z1. #' @slot Sigma matrix. The diffusion matrix for the representation of Z1. #' @slot c.gamma list. The coefficients of the Hermite polynomials. #' @slot h.gamma list. Hermite polynomials. #' setClass("yuima.ae", slots = c( order = "integer", var = "character", u.var = "character", eps.var = "character", characteristic = "expression", density = "expression", Z0 = "numeric", Mu = "numeric", Sigma = "matrix", c.gamma = "list", h.gamma = "list" )) #' Constructor for yuima.ae #' @rdname yuima.ae-class setMethod("initialize", "yuima.ae", function(.Object, order, var, u.var, eps.var, characteristic, Z0, Mu, Sigma, c.gamma, verbose){ ######################################################## # Set density # ######################################################## if(verbose) { cat(paste0('Computing distribution...')) time <- Sys.time() } tmp <- calculus::hermite(var = var, sigma = solve(Sigma), order = 3*order) h.gamma <- lapply(tmp, function(x) x$f) .Object@density <- sapply(0:order, function(m) { if(m>0){ pdf <- sapply(1:m, function(m){ g <- c.gamma[[m]][sapply(c.gamma[[m]], function(x) x!=0)] if(length(g)==0) return(0) h <- h.gamma[names(g)] p <- paste(calculus::wrap(g), calculus::wrap(h), sep = "*", collapse = " + ") paste(paste0(eps.var, "^", m), calculus::wrap(p), sep = " * ") }) pdf <- paste(pdf, collapse = " + ") pdf <- paste0(1, " + ", pdf) } else { pdf <- 1 } kernel <- sprintf('%s * exp(%s)', ((2*pi)^(-length(var)/2)*(det(Sigma)^(-0.5))), (-0.5 * solve(Sigma)) %inner% (var %outer% var)) pdf <- paste0(kernel, " * (", pdf, ")") for(i in 1:length(var)) { z <- sprintf("(((%s - %s)/%s) - %s)", var[i], Z0[var[i]], eps.var, Mu[i]) pdf <- gsub(x = pdf, pattern = paste0("\\b",var[i],"\\b"), replacement = z) pdf <- sprintf("(%s) / abs(%s)", pdf, eps.var) } return(parse(text = pdf)) }) if(verbose) { cat(sprintf(' (%s sec)\n', difftime(Sys.time(), time, units = "secs")[[1]])) time <- Sys.time() } ######################################################## # Set object # ######################################################## .Object@order <- order .Object@var <- var [email protected] <- u.var [email protected] <- eps.var .Object@characteristic <- characteristic .Object@Z0 <- Z0 .Object@Mu <- Mu .Object@Sigma <- Sigma [email protected] <- c.gamma [email protected] <- h.gamma # return return(.Object) }) #' Plot method for an object of class yuima.ae #' @rdname yuima.ae-class setMethod("plot", signature(x = "yuima.ae"), function(x, grids = list(), eps = 1, order = NULL, ...){ n <- length(x@var) for(z in x@var){ margin <- aeMarginal(ae = x, var = z) grid <- grids[z] if(is.null(grid[[1]])){ mu <- aeMean(ae = margin, eps = eps, order = order)[[1]] sd <- aeSd(ae = margin, eps = eps, order = order)[[1]] grid <- list(seq(mu-5*sd, mu+5*sd, length.out = 1000)) names(grid) <- z } dens <- do.call('aeDensity', c(grid, list(ae = margin, eps = eps, order = order))) plot(x = grid[[1]], y = dens, type = 'l', xlab = z, ylab = 'Density', ...) } }) #' Asymptotic Expansion #' #' Asymptotic expansion of uni-dimensional and multi-dimensional diffusion processes. #' #' @param model an object of \code{\link{yuima-class}} or \code{\link{yuima.model-class}}. #' @param xinit initial value vector of state variables. #' @param order integer. The asymptotic expansion order. Higher orders lead to better approximations but longer computational times. #' @param true.parameter named list of parameters. #' @param sampling a \code{\link{yuima.sampling-class}} object. #' @param eps.var character. The perturbation variable. #' @param solver the solver for ordinary differential equations. One of \code{"rk4"} (more accurate) or \code{"euler"} (faster). #' @param verbose logical. Print on progress? Default \code{FALSE}. #' #' @return An object of \code{\link{yuima.ae-class}} #' #' @details #' If \code{sampling} is not provided, then \code{model} must be an object of \code{\link{yuima-class}} with non-empty \code{sampling}. #' #' if \code{eps.var} does not appear in the model specification, then it is internally added in front of the diffusion matrix to apply the asymptotic expansion scheme. #' #' @author #' Emanuele Guidotti <[email protected]> #' #' @examples #' #' # model #' gbm <- setModel(drift = 'mu*x', diffusion = 'sigma*x', solve.variable = 'x') #' #' # settings #' xinit <- 100 #' par <- list(mu = 0.01, sigma = 0.2) #' sampling <- setSampling(Initial = 0, Terminal = 1, n = 1000) #' #' # asymptotic expansion #' approx <- ae(model = gbm, sampling = sampling, order = 4, true.parameter = par, xinit = xinit) #' #' # exact density #' x <- seq(50, 200, by = 0.1) #' exact <- dlnorm(x = x, meanlog = log(xinit)+(par$mu-0.5*par$sigma^2)*1, sdlog = par$sigma*sqrt(1)) #' #' # compare #' plot(x, exact, type = 'l', ylab = "Density") #' lines(x, aeDensity(x = x, ae = approx, order = 1), col = 2) #' lines(x, aeDensity(x = x, ae = approx, order = 2), col = 3) #' lines(x, aeDensity(x = x, ae = approx, order = 3), col = 4) #' lines(x, aeDensity(x = x, ae = approx, order = 4), col = 5) #' #' @importFrom calculus %dot% #' @importFrom calculus %inner% #' @importFrom calculus %mx% #' @importFrom calculus %outer% #' @importFrom calculus %prod% #' @importFrom calculus %sum% #' @importFrom calculus %gradient% #' #' @export #' ae <- function(model, xinit, order = 1L, true.parameter = list(), sampling = NULL, eps.var = 'eps', solver = "rk4", verbose = FALSE){ obj.class <- class(model) if(!is.null(sampling)){ if(obj.class=='yuima'){ stop('model must be of class yuima.model when sampling is provided') } else if(obj.class=='yuima.model'){ model <- setYuima(model = model, sampling = sampling) } else stop('model must be of class yuima or yuima.model') } else if(obj.class!='yuima'){ stop('model must be of class yuima when sampling is not provided') } if(!model@sampling@regular) stop('ae needs regular sampling') if(length(sampling@grid)!=1) stop('ae needs a unidimensional sampling grid') if(length(model@[email protected])>0) stop('ae does not support jump processes') if(model@model@hurst!=0.5) stop('ae does not support fractional processes') # temporary disable calculus.auto.wrap calculus.auto.wrap <- options(calculus.auto.wrap = FALSE) on.exit(options(calculus.auto.wrap), add = TRUE) ######################################################## # dz # ######################################################## dz <- function(i){ paste0('d', i, '.', AE$z) } dz.nu <- function(i, nu){ dz <- dz(i) z <- sapply(1:AE$d, function(i) rep(dz[i], nu[i]), simplify = F) z <- paste(unlist(z), collapse = ' * ') if(z=='') z <- '1' return(z) } ######################################################## # Z.I # ######################################################## Z.I <- function(I, bar = FALSE) { tmp <- NULL for(i in I){ z.i <- dz(i = i) if(bar) { z.i <- c( z.i, ifelse(i==1, 1, 0) ) } z.i <- array(z.i) if(is.null(tmp)) tmp <- z.i else tmp <- tmp %outer% z.i } return(tmp) } # Hermite Valued Expectation HVE <- function(nu, K){ # convert to label nu <- label(nu) # for each nu' H <- sapply(names(AE$c.nu[[nu]]), function(nu.prime) { c(AE$c.nu[[nu]][[nu.prime]]) * as.numeric(AE$Ez.T[AE$Ez.K[[label(K)]][[nu.prime]]]) }) if(is.null(dim(H))) H <- sum(H) else H <- rowSums(H) return(H) } # Tensor Valued Expectation TVE <- function(K){ K <- K + 1 nu <- AE$nu[[sum(K)]] E <- apply(nu, 2, function(nu){ c <- (1i)^sum(nu) / prod(factorial(nu)) * HVE(nu = nu, K = K) c <- c/prod(factorial(K)) paste0(AE$u,"^",nu, collapse = "*") %prod% array(calculus::wrap(c)) }) if(is.null(dim(E))) E <- cpp_collapse(E, ' + ') else E <- apply(E, 1, function(x) cpp_collapse(x, ' + ')) E <- array(E, dim = rep(AE$d, length(K))) return(E) } # Characteristic function psi <- function(m){ martingale <- sprintf('exp(%s)', (calculus::wrap(1i*AE$Mu) %inner% AE$u) %sum% ((-0.5 * AE$Sigma) %inner% (AE$u %outer% AE$u))) if(m>0){ psi <- cpp_collapse(paste0(AE$eps.var, "^", (1:m)) %prod% calculus::wrap(AE$P.m[1:m]), " + ") psi <- 1 %sum% psi } else { psi <- 1 } psi <- paste0(martingale," * (", psi, ")") for(i in 1:AE$d) psi <- gsub(x = psi, pattern = paste0("\\b",AE$u[i],"\\b"), replacement = calculus::wrap(paste(AE$eps.var,"*",AE$u[i]))) psi <- paste0("exp((",1i,") * (",AE$u %inner% AE$Ez.T[AE$z],")) * (", psi, ")") return(parse(text = psi)) } # label for partitions label <- function(I){ paste(I, collapse = ',') } ######################################################## # AE environment # ######################################################## AE <- new.env() # expansion order AE$m <- as.integer(order) # expansion variable AE$eps.var <- eps.var # model parameters AE$par <- true.parameter AE$par[[AE$eps.var]] <- 0 # model dimension AE$d <- model@[email protected] # noise dimension AE$r <- model@[email protected] + 1 # solve variables AE$z <- model@[email protected] # extended solve variables AE$z.bar <- c(AE$z, AE$eps.var) # characteristic function variables AE$u <- paste0('u', 1:AE$d) # simulation initial value AE$xinit <- xinit # timing if verbose if(verbose) time <- Sys.time() ######################################################## # V: V[,1] -> V_{0}; V[,2] -> V_{1} # ######################################################## AE$V <- NULL # drift drift <- calculus::e2c(model@model@drift) # diffusion diffusion <- unlist(lapply(model@model@diffusion, calculus::e2c)) diffusion <- as.array(matrix(diffusion, nrow = AE$d, ncol = AE$r-1, byrow = TRUE)) # expansion coefficient is.eps.diffusion <- any(grepl(x = diffusion, pattern = paste0('\\b',AE$eps.var,'\\b'))) is.eps.drift <- any(grepl(x = drift, pattern = paste0('\\b',AE$eps.var,'\\b'))) if(!is.eps.diffusion){ diffusion <- AE$eps.var %prod% calculus::wrap(diffusion) } else { test <- parse(text = diffusion) env <- AE$par env[[AE$eps.var]] <- 0 for(z in AE$z) env[[z]] <- runif(n = 100, min = -999, max = 999) is.ok <- suppressWarnings(sapply(test, function(expr){ all(eval(expr, env)==0, na.rm = TRUE) })) if(!all(is.ok)){ stop('diffusion must vanish when evaluated at epsilon = 0') } } # building V... AE$V <- array(c(drift, diffusion), c(AE$d, AE$r)) ######################################################## # dV # ######################################################## AE$dV <- list() if(verbose) cat('Computing dV...') # parse v only once expr <- array(parse(text = AE$V), dim = dim(AE$V)) # for j up to twice the expansion order... for(j in 1:(2*AE$m)) { # differentiate expression expr <- calculus::derivative(expr, var = AE$z.bar, deparse = FALSE) # convert to char tmp <- calculus::e2c(expr) # break if dV vanishes if(all(tmp=="0")) break # evaluate at eps = 0 if(!is.eps.diffusion & !is.eps.drift){ # auto: eps * diffusion -> boost performance zero <- grepl(x = tmp, pattern = paste0('\\b',AE$eps.var,'\\b')) tmp[zero] <- "0" } else { # user defined: gsub tmp[] <- gsub(x = tmp, pattern = paste0('\\b',AE$eps.var,'\\b'), replacement = "0") } # drop white spaces (!important) tmp[] <- gsub(x = tmp, pattern = ' ', replacement = '', fixed = T) # store dV AE$dV[[j]] <- tmp } if(verbose) { cat(sprintf(' %s derivatives (%s sec)\n', length(unlist(AE$dV)), difftime(Sys.time(), time, units = "secs")[[1]])) time <- Sys.time() } ######################################################## # dZ # ######################################################## AE$dZ <- list() if(verbose) cat('Computing dZ...') # for j up to twice the expnasion order... for(k in 1:(2*AE$m)) { # get partitions of k I.set <- calculus::partitions(n = k) # building dZ... AE$dZ[[k]] <- "0" # for each I in I.set lapply(I.set, function(I){ # length I j <- length(I) # if dV[[j]] does not vanish if(j <= length(AE$dV)){ # compute U U <- (factorial(sum(I))/prod(factorial(c( I, table(I) )))) %prod% calculus::wrap(AE$dV[[j]]) # isolate coefficients U[] <- paste0('{',U,'}') # add to dZ AE$dZ[[k]] <- AE$dZ[[k]] %sum% ( U %dot% Z.I(I = I, bar = TRUE) ) } # void return(NULL) }) } if(verbose) { cat(sprintf(' (%s sec)\n', difftime(Sys.time(), time, units = "secs")[[1]])) time <- Sys.time() } ######################################################## # K.set # ######################################################## AE$K.set <- NULL # for n up to 4 times the expansion order... for(n in 1:(4*AE$m)){ # store K.set AE$K.set <- c(AE$K.set, calculus::partitions(n = n, max = 2*AE$m)) } ######################################################## # Z.K # ######################################################## AE$Z.K <- lapply(AE$K.set, function(K) Z.I(I = K)) names(AE$Z.K) <- lapply(AE$K.set, label) ######################################################## if(verbose) cat('Computing Ito ODE system...') ito <- cpp_ito(K_set = AE$K.set, dZ = AE$dZ, Z_K = AE$Z.K, d = AE$d, r = AE$r) AE$ito.lhs <- ito$lhs AE$ito.rhs <- ito$rhs AE$ito.rhs.var <- ito$rhs.var if(verbose) { cat(sprintf(' %s equations (%s sec)\n', length(AE$ito.rhs)+AE$d, difftime(Sys.time(), time, units = "secs")[[1]])) time <- Sys.time() } ######################################################## if(verbose) cat('Reducing Ito ODE system...') AE$nu <- list() AE$Ez.K <- list() # nu indices for(k in 1:(2*AE$m)) AE$nu[[k]] <- calculus::partitions(n = k, length = AE$d, fill = TRUE, perm = TRUE, equal = FALSE) # find needed terms for(i in 1:AE$m) { for(l in 1:i){ K.set <- calculus::partitions(n = i, length = l, perm = TRUE) lapply(K.set, function(K) { K <- K+1 AE$Ez.K[[label(K)]] <- list() apply(AE$nu[[sum(K)]], 2, function(nu) { # store AE$Ez.K[[label(K)]][[label(nu)]] <- cpp_E( dz.nu(i = 1, nu = nu) %prod% Z.I(I = K) ) # void return(NULL) }) # void return(NULL) }) } } ######################################################## AE$Ez.T <- list() AE$Ez <- unique(unlist(AE$Ez.K)) # drop duplicated equations idx <- which(!duplicated(AE$ito.lhs)) AE$ito.lhs <- AE$ito.lhs[idx] AE$ito.rhs <- AE$ito.rhs[idx] AE$ito.rhs.var <- AE$ito.rhs.var[idx] while(TRUE){ # needed equation id idx <- which(AE$ito.lhs %in% AE$Ez) # additional needed var add <- unique(unlist(AE$ito.rhs.var[idx])) add <- add[!(add %in% AE$Ez)] # break or store if(length(add)==0) break AE$Ez <- c(AE$Ez, add) } # drop equations not needed idx <- which(AE$ito.lhs %in% AE$Ez) AE$ito.lhs <- AE$ito.lhs[idx] AE$ito.rhs <- AE$ito.rhs[idx] AE$ito.rhs.var <- AE$ito.rhs.var[idx] # plug zero if empty equation while(TRUE){ idx <- which(AE$ito.rhs=='') if(length(idx)==0) break zero <- AE$ito.lhs[idx] AE$Ez.T[zero] <- 0 AE$ito.lhs <- AE$ito.lhs[-idx] AE$ito.rhs <- AE$ito.rhs[-idx] pattern <- gsub(zero, pattern = '.', replacement = '\\.', fixed = T) pattern <- gsub(pattern, pattern = '_', replacement = '\\_', fixed = T) pattern <- paste0(pattern, collapse = '|') pattern <- paste0(' \\* (',pattern,')\\b') AE$ito.rhs <- unlist(lapply(strsplit(AE$ito.rhs, split = ' + ', fixed = T), function(x){ is.zero <- grepl(x = x, pattern = pattern) x <- x[!is.zero] if(length(x)==0) return("") else return(paste(x, collapse = ' + ')) })) } if(verbose) { cat(sprintf(' %s equations (%s sec)\n', length(AE$ito.rhs)+AE$d, difftime(Sys.time(), time, units = "secs")[[1]])) time <- Sys.time() } ######################################################## if(verbose) cat('Solving Ito ODE system...') # Ito ODE lhs <- c(AE$z, AE$ito.lhs) rhs <- c(AE$V[,1], AE$ito.rhs) # Initial values xinit <- c(rep(AE$xinit, length.out = AE$d), rep(0, length(lhs)-AE$d)) names(xinit) <- lhs # Solve Ez.T <- calculus::ode(f = rhs, var = xinit, times = sampling@grid[[1]], params = AE$par, timevar = model@[email protected], drop = TRUE, method = solver) AE$Ez.T <- c(as.list(Ez.T), AE$Ez.T) if(verbose) { cat(sprintf(' (%s sec)\n', difftime(Sys.time(), time, units = "secs")[[1]])) time <- Sys.time() } ######################################################## if(verbose) cat('Computing Sigma matrix...') y.lhs <- array(paste('y', gsub(AE$z %outer% AE$z, pattern = " * ", replacement = "_", fixed = T), sep = '.'), dim = rep(AE$d, 2)) y.rhs <- calculus::wrap(AE$V[,1] %gradient% AE$z) %mx% y.lhs y.0 <- diag(AE$d) dim(y.lhs) <- NULL dim(y.rhs) <- NULL dim(y.0) <- NULL y.lhs <- c(AE$z, y.lhs) y.rhs <- c(AE$V[,1], y.rhs) y.0 <- c(rep(AE$xinit, length.out = AE$d), y.0) names(y.0) <- y.lhs times <- sampling@grid[[1]] n.times <- length(times) x <- calculus::ode(f = y.rhs, var = y.0, times = times, params = AE$par, timevar = model@[email protected], method = solver) y <- x[, -c(1:AE$d), drop = FALSE] z <- as.data.frame(x[, c(1:AE$d), drop = FALSE]) if(!is.null(model@[email protected])) z[[model@[email protected]]] <- times y.s <- lapply(1:n.times, function(i) matrix(y[i,], nrow = AE$d)) y_inv.s <- lapply(y.s, solve) dV <- AE$V %gradient% AE$eps.var dV.s <- calculus::evaluate(dV, as.data.frame(c(z, AE$par))) dV.s <- lapply(1:n.times, function(i) array(dV.s[i,], dim = dim(dV))) if(length(dV.s)==1) dV.s = rep(dV.s, n.times) # Mu if(all(dV[,1,]=="0")){ AE$Mu <- array(0, dim = AE$d) } else { Mu <- sapply(1:n.times, function(i){ y_inv.s[[i]] %*% dV.s[[i]][,1,] }) if(is.null(dim(Mu))) { n <- length(Mu) Mu <- ( sum(Mu[c(-1,-n)]) + sum(Mu[c(1,n)])/2 ) * sampling@delta } else { n <- ncol(Mu) Mu <- ( rowSums(Mu[,c(-1,-n)]) + rowSums(Mu[,c(1,n)])/2 ) * sampling@delta } AE$Mu <- array(y.s[[n.times]] %*% Mu) } # Sigma S <- sapply(1:n.times, function(i){ a <- y.s[[n.times]] %*% y_inv.s[[i]] %*% dV.s[[i]][,-1,] a %*% t(a) }) if(is.null(dim(S))) { n <- length(S) S <- ( sum(S[c(-1,-n)]) + sum(S[c(1,n)])/2 ) * sampling@delta } else { n <- ncol(S) S <- ( rowSums(S[,c(-1,-n)]) + rowSums(S[,c(1,n)])/2 ) * sampling@delta } AE$Sigma <- array(S, dim = c(AE$d,AE$d)) if(verbose) { cat(sprintf(' (%s sec)\n', difftime(Sys.time(), time, units = "secs")[[1]])) time <- Sys.time() } ######################################################## # Hermite coefficients if(verbose) cat(paste0('Computing Hermite...')) tmp <- calculus::hermite(var = AE$z, sigma = AE$Sigma, order = 2*AE$m, transform = solve(AE$Sigma) %dot% calculus::wrap(AE$z %sum% -AE$Mu)) AE$c.nu <- lapply(tmp, function(x) { coef <- as.list(x$terms$coef) names(coef) <- rownames(x$terms) return(coef) }) AE$h.nu <- lapply(tmp, function(x) x$f) if(verbose) { cat(sprintf(' (%s sec)\n', difftime(Sys.time(), time, units = "secs")[[1]])) time <- Sys.time() } ######################################################## AE$ul <- list(array(AE$u)) if(AE$m > 1) for(l in 2:AE$m){ AE$ul[[l]] <- AE$ul[[l-1]] %outer% AE$u } AE$ul <- lapply(AE$ul, function(ul){ array(unlist(lapply(strsplit(ul, split = " * ", fixed = T), function(u) { u <- table(u) paste0(names(u),"^",u, collapse = "*") })), dim = dim(ul)) }) ######################################################## if(verbose) cat('Computing characteristic function...') AE$psi <- list() for(m in 1:AE$m) { AE$psi[[m]] <- list() for(l in 1:m){ K.set <- calculus::partitions(n = m, length = l, perm = TRUE) psi.m.l <- unlist(lapply(K.set, function(K){ calculus::wrap((1i)^l) %prod% calculus::wrap((calculus::wrap(TVE(K = K)) %inner% AE$ul[[l]])) })) expr <- (1/factorial(l)) %prod% calculus::wrap(cpp_collapse(psi.m.l, ' + ')) AE$psi[[m]][[l]] <- calculus::taylor(expr, var = AE$u, order = m+2*l)$f } } AE$P.m = sapply(AE$psi, function(p.m.l) cpp_collapse(unlist(p.m.l), " + ")) AE$c.gamma <- lapply(1:AE$m, function(m) { p <- calculus::taylor(AE$P.m[m], var = AE$u, order = 3*m) coef <- Re(p$terms$coef/(1i)^p$terms$degree) coef <- as.list(coef) names(coef) <- rownames(p$terms) return(coef) }) AE$PSI <- sapply(0:AE$m, psi) if(verbose) { cat(sprintf(' (%s sec)\n', difftime(Sys.time(), time, units = "secs")[[1]])) time <- Sys.time() } ######################################################## return(new( "yuima.ae", order = AE$m, var = AE$z, u.var = AE$u, eps.var = AE$eps.var, characteristic = AE$PSI, Z0 = unlist(AE$Ez.T[AE$z]), Mu = as.numeric(AE$Mu), Sigma = AE$Sigma, c.gamma = AE$c.gamma, verbose = verbose )) } #' Asymptotic Expansion - Density #' #' @param ... named argument, data.frame, list, or environment specifying the grid to evaluate the density. See examples. #' @param ae an object of class \code{\link{yuima.ae-class}}. #' @param eps numeric. The intensity of the perturbation. #' @param order integer. The expansion order. If \code{NULL} (default), it uses the maximum order used in \code{ae}. #' #' @return Probability density function evaluated on the given grid. #' #' @examples #' #' # model #' gbm <- setModel(drift = 'mu*x', diffusion = 'sigma*x', solve.variable = 'x') #' #' # settings #' xinit <- 100 #' par <- list(mu = 0.01, sigma = 0.2) #' sampling <- setSampling(Initial = 0, Terminal = 1, n = 1000) #' #' # asymptotic expansion #' approx <- ae(model = gbm, sampling = sampling, order = 4, true.parameter = par, xinit = xinit) #' #' # The following are all equivalent methods to specify the grid via .... #' # Notice that the character 'x' corresponds to the solve.variable of the yuima model. #' #' # 1) named argument #' x <- seq(50, 200, by = 0.1) #' density <- aeDensity(x = x, ae = approx, order = 4) #' # 2) data frame #' df <- data.frame(x = seq(50, 200, by = 0.1)) #' density <- aeDensity(df, ae = approx, order = 4) #' # 3) environment #' env <- new.env() #' env$x <- seq(50, 200, by = 0.1) #' density <- aeDensity(env, ae = approx, order = 4) #' # 4) list #' lst <- list(x = seq(50, 200, by = 0.1)) #' density <- aeDensity(lst, ae = approx, order = 4) #' #' # exact density #' exact <- dlnorm(x = x, meanlog = log(xinit)+(par$mu-0.5*par$sigma^2)*1, sdlog = par$sigma*sqrt(1)) #' #' # compare #' plot(x = exact, y = density, xlab = "Exact", ylab = "Approximated") #' #' @export #' aeDensity <- function(..., ae, eps = 1, order = NULL){ if(is.null(order)) order <- ae@order pdf <- ae@density[order+1] env <- list(...) if(length(env)==1) if(is.list(env[[1]]) | is.environment(env[[1]])) env <- env[[1]] env[[[email protected]]] <- eps return(eval(expr = pdf, envir = env)) } #' Asymptotic Expansion - Marginals #' #' @param ae an object of class \code{\link{yuima.ae-class}}. #' @param var variables of the marginal distribution to compute. #' #' @return An object of \code{\link{yuima.ae-class}} #' #' @examples #' #' # multidimensional model #' gbm <- setModel(drift = c('mu*x1','mu*x2'), #' diffusion = matrix(c('sigma1*x1',0,0,'sigma2*x2'), nrow = 2), #' solve.variable = c('x1','x2')) #' #' # settings #' xinit <- c(100, 100) #' par <- list(mu = 0.01, sigma1 = 0.2, sigma2 = 0.1) #' sampling <- setSampling(Initial = 0, Terminal = 1, n = 1000) #' #' # asymptotic expansion #' approx <- ae(model = gbm, sampling = sampling, order = 3, true.parameter = par, xinit = xinit) #' #' # extract marginals #' margin1 <- aeMarginal(ae = approx, var = "x1") #' margin2 <- aeMarginal(ae = approx, var = "x2") #' #' # compare with exact solution for marginal 1 #' x1 <- seq(50, 200, by = 0.1) #' exact <- dlnorm(x = x1, meanlog = log(xinit[1])+(par$mu-0.5*par$sigma1^2), sdlog = par$sigma1) #' plot(x1, exact, type = 'p', ylab = "Density") #' lines(x1, aeDensity(x1 = x1, ae = margin1, order = 3), col = 2) #' #' # compare with exact solution for marginal 2 #' x2 <- seq(50, 200, by = 0.1) #' exact <- dlnorm(x = x2, meanlog = log(xinit[2])+(par$mu-0.5*par$sigma2^2), sdlog = par$sigma2) #' plot(x2, exact, type = 'p', ylab = "Density") #' lines(x2, aeDensity(x2 = x2, ae = margin2, order = 3), col = 2) #' #' @export #' aeMarginal <- function(ae, var){ # init keep <- ae@var %in% var if(sum(!keep)==0) return(ae) # vanish marginal coefficients c.gamma <- [email protected] for(i in 1:length(c.gamma)) for(j in 1:length(c.gamma[[i]])){ o <- as.numeric(unlist(strsplit(x = names(c.gamma[[i]][j]), split = ','))) if(any(o[!keep]>0)){ c.gamma[[i]][[j]] <- 0 } else { names(c.gamma[[i]])[j] <- paste(o[keep], collapse = ',') } } # characteristic characteristic <- sapply(calculus::e2c(ae@characteristic), function(psi) { for(u in [email protected][!keep]) psi <- gsub(x = psi, pattern = paste0("\\b",u,"\\b"), replacement = 0) return(calculus::c2e(psi)) }) # return return(new( "yuima.ae", order = ae@order, var = ae@var[keep], u.var = [email protected][keep], eps.var = [email protected], characteristic = characteristic, Z0 = ae@Z0[keep], Mu = ae@Mu[keep], Sigma = ae@Sigma[keep, keep, drop = FALSE], c.gamma = c.gamma, verbose = FALSE )) } #' Asymptotic Expansion - Functionals #' #' Compute the expected value of functionals. #' #' @param f character. The functional. #' @param bounds named list of integration bounds in the form \code{list(x = c(xmin, xmax), y = c(ymin, ymax), ...)} #' @param ae an object of class \code{\link{yuima.ae-class}}. #' @param eps numeric. The intensity of the perturbation. #' @param order integer. The expansion order. If \code{NULL} (default), it uses the maximum order used in \code{ae}. #' @param ... additional arguments passed to \code{\link[cubature]{cubintegrate}}. #' #' @return return value of \code{\link[cubature]{cubintegrate}}. The expectation of the functional provided. #' #' @examples #' #' # model #' gbm <- setModel(drift = 'mu*x', diffusion = 'sigma*x', solve.variable = 'x') #' #' # settings #' xinit <- 100 #' par <- list(mu = 0.01, sigma = 0.2) #' sampling <- setSampling(Initial = 0, Terminal = 1, n = 1000) #' #' # asymptotic expansion #' approx <- ae(model = gbm, sampling = sampling, order = 4, true.parameter = par, xinit = xinit) #' #' # compute the mean via integration #' aeExpectation(f = 'x', bounds = list(x = c(0,1000)), ae = approx) #' #' # compare with the mean computed by differentiation of the characteristic function #' aeMean(approx) #' #' @export #' aeExpectation <- function(f, bounds, ae, eps = 1, order = NULL, ...){ f <- calculus::c2e(f) var <- names(bounds) ae <- aeMarginal(ae = ae, var = var) lower <- sapply(bounds, function(x) x[1]) upper <- sapply(bounds, function(x) x[2]) args <- list(...) args$f <- function(x) { names(x) <- var x <- as.list(x) eval(f, envir = x) * aeDensity(x, ae = ae, eps = eps, order = order) } args$lower <- lower args$upper <- upper if(is.null(args$method)) args$method <- 'hcubature' return(do.call("cubintegrate", args)) } #' Asymptotic Expansion - Characteristic Function #' #' @param ... named argument, data.frame, list, or environment specifying the grid to evaluate the characteristic function. See examples. #' @param ae an object of class \code{\link{yuima.ae-class}}. #' @param eps numeric. The intensity of the perturbation. #' @param order integer. The expansion order. If \code{NULL} (default), it uses the maximum order used in \code{ae}. #' #' @return Characteristic function evaluated on the given grid. #' #' @examples #' #' # model #' gbm <- setModel(drift = 'mu*x', diffusion = 'sigma*x', solve.variable = 'x') #' #' # settings #' xinit <- 100 #' par <- list(mu = 0.01, sigma = 0.2) #' sampling <- setSampling(Initial = 0, Terminal = 1, n = 1000) #' #' # asymptotic expansion #' approx <- ae(model = gbm, sampling = sampling, order = 4, true.parameter = par, xinit = xinit) #' #' # The following are all equivalent methods to specify the grid via .... #' # Notice that the character 'u1' corresponds to the 'u.var' of the ae object. #' [email protected] #' #' # 1) named argument #' u1 <- seq(0, 1, by = 0.1) #' psi <- aeCharacteristic(u1 = u1, ae = approx, order = 4) #' # 2) data frame #' df <- data.frame(u1 = seq(0, 1, by = 0.1)) #' psi <- aeCharacteristic(df, ae = approx, order = 4) #' # 3) environment #' env <- new.env() #' env$u1 <- seq(0, 1, by = 0.1) #' psi <- aeCharacteristic(env, ae = approx, order = 4) #' # 4) list #' lst <- list(u1 = seq(0, 1, by = 0.1)) #' psi <- aeCharacteristic(lst, ae = approx, order = 4) #' #' @export #' aeCharacteristic <- function(..., ae, eps = 1, order = NULL){ if(is.null(order)) order <- ae@order psi <- ae@characteristic[order+1] env <- list(...) if(length(env)==1) if(is.list(env[[1]]) | is.environment(env[[1]])) env <- env[[1]] env[[[email protected]]] <- eps return(eval(expr = psi, envir = env)) } #' Asymptotic Expansion - Moments #' #' @param ae an object of class \code{\link{yuima.ae-class}}. #' @param m integer. The moment order. In case of multidimensional processes, it is possible to compute cross-moments by providing a vector of the same length as the state variables. #' @param eps numeric. The intensity of the perturbation. #' @param order integer. The expansion order. If \code{NULL} (default), it uses the maximum order used in \code{ae}. #' #' @return numeric. #' #' @examples #' #' # model #' gbm <- setModel(drift = 'mu*x', diffusion = 'sigma*x', solve.variable = 'x') #' #' # settings #' xinit <- 100 #' par <- list(mu = 0.01, sigma = 0.2) #' sampling <- setSampling(Initial = 0, Terminal = 1, n = 1000) #' #' # asymptotic expansion #' approx <- ae(model = gbm, sampling = sampling, order = 4, true.parameter = par, xinit = xinit) #' #' # second moment, expansion order max #' aeMoment(ae = approx, m = 2) #' #' # second moment, expansion order 3 #' aeMoment(ae = approx, m = 2, order = 3) #' #' # second moment, expansion order 2 #' aeMoment(ae = approx, m = 2, order = 2) #' #' # second moment, expansion order 1 #' aeMoment(ae = approx, m = 2, order = 1) #' #' @export #' aeMoment <- function(ae, m = 1, eps = 1, order = NULL){ if(is.null(order)) order <- ae@order psi <- ae@characteristic[order+1] env <- c() env[[email protected]] <- 0 env[[email protected]] <- eps return(Re((-1i)^sum(m) * calculus::evaluate(calculus::derivative(psi, var = [email protected], order = m, deparse = FALSE), env))) } #' Asymptotic Expansion - Mean #' #' @param ae an object of class \code{\link{yuima.ae-class}}. #' @param eps numeric. The intensity of the perturbation. #' @param order integer. The expansion order. If \code{NULL} (default), it uses the maximum order used in \code{ae}. #' #' @return numeric. #' #' @examples #' #' # model #' gbm <- setModel(drift = 'mu*x', diffusion = 'sigma*x', solve.variable = 'x') #' #' # settings #' xinit <- 100 #' par <- list(mu = 0.01, sigma = 0.2) #' sampling <- setSampling(Initial = 0, Terminal = 1, n = 1000) #' #' # asymptotic expansion #' approx <- ae(model = gbm, sampling = sampling, order = 4, true.parameter = par, xinit = xinit) #' #' # expansion order max #' aeMean(ae = approx) #' #' # expansion order 1 #' aeMean(ae = approx, order = 1) #' #' @export #' aeMean <- function(ae, eps = 1, order = NULL){ return(aeMoment(ae = ae, m = 1, eps = eps, order = order)) } #' Asymptotic Expansion - Standard Deviation #' #' @param ae an object of class \code{\link{yuima.ae-class}}. #' @param eps numeric. The intensity of the perturbation. #' @param order integer. The expansion order. If \code{NULL} (default), it uses the maximum order used in \code{ae}. #' #' @return numeric. #' #' @examples #' #' # model #' gbm <- setModel(drift = 'mu*x', diffusion = 'sigma*x', solve.variable = 'x') #' #' # settings #' xinit <- 100 #' par <- list(mu = 0.01, sigma = 0.2) #' sampling <- setSampling(Initial = 0, Terminal = 1, n = 1000) #' #' # asymptotic expansion #' approx <- ae(model = gbm, sampling = sampling, order = 4, true.parameter = par, xinit = xinit) #' #' # expansion order max #' aeSd(ae = approx) #' #' # expansion order 1 #' aeSd(ae = approx, order = 1) #' #' @export #' aeSd <- function(ae, eps = 1, order = NULL){ m1 <- aeMoment(ae = ae, m = 1, eps = eps, order = order) m2 <- aeMoment(ae = ae, m = 2, eps = eps, order = order) return(sqrt(m2-m1^2)) } #' Asymptotic Expansion - Skewness #' #' @param ae an object of class \code{\link{yuima.ae-class}}. #' @param eps numeric. The intensity of the perturbation. #' @param order integer. The expansion order. If \code{NULL} (default), it uses the maximum order used in \code{ae}. #' #' @return numeric. #' #' @examples #' #' # model #' gbm <- setModel(drift = 'mu*x', diffusion = 'sigma*x', solve.variable = 'x') #' #' # settings #' xinit <- 100 #' par <- list(mu = 0.01, sigma = 0.2) #' sampling <- setSampling(Initial = 0, Terminal = 1, n = 1000) #' #' # asymptotic expansion #' approx <- ae(model = gbm, sampling = sampling, order = 4, true.parameter = par, xinit = xinit) #' #' # expansion order max #' aeSkewness(ae = approx) #' #' # expansion order 1 #' aeSkewness(ae = approx, order = 1) #' #' @export #' aeSkewness <- function(ae, eps = 1, order = NULL){ m1 <- aeMoment(ae = ae, m = 1, eps = eps, order = order) m2 <- aeMoment(ae = ae, m = 2, eps = eps, order = order) m3 <- aeMoment(ae = ae, m = 3, eps = eps, order = order) return((m3-3*m1*m2+2*m1^3)/sqrt(m2-m1^2)^3) } #' Asymptotic Expansion - Kurtosis #' #' @param ae an object of class \code{\link{yuima.ae-class}}. #' @param eps numeric. The intensity of the perturbation. #' @param order integer. The expansion order. If \code{NULL} (default), it uses the maximum order used in \code{ae}. #' #' @return numeric. #' #' @examples #' #' # model #' gbm <- setModel(drift = 'mu*x', diffusion = 'sigma*x', solve.variable = 'x') #' #' # settings #' xinit <- 100 #' par <- list(mu = 0.01, sigma = 0.2) #' sampling <- setSampling(Initial = 0, Terminal = 1, n = 1000) #' #' # asymptotic expansion #' approx <- ae(model = gbm, sampling = sampling, order = 4, true.parameter = par, xinit = xinit) #' #' # expansion order max #' aeKurtosis(ae = approx) #' #' # expansion order 1 #' aeKurtosis(ae = approx, order = 1) #' #' @export #' aeKurtosis <- function(ae, eps = 1, order = NULL){ m1 <- aeMoment(ae = ae, m = 1, eps = eps, order = order) m2 <- aeMoment(ae = ae, m = 2, eps = eps, order = order) m3 <- aeMoment(ae = ae, m = 3, eps = eps, order = order) m4 <- aeMoment(ae = ae, m = 4, eps = eps, order = order) return((m4-4*m1*m3+6*m1^2*m2-3*m1^4)/sqrt(m2-m1^2)^4) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/ae.R
yuima.warn <- function(x){ cat(sprintf("\nYUIMA: %s\n", x)) } # in this source we note formulae like latex setGeneric("asymptotic_term", function(yuima,block=100, rho, g, expand.var="e") standardGeneric("asymptotic_term")) setMethod("asymptotic_term",signature(yuima="yuima"), function(yuima,block=100, rho, g, expand.var="e"){ if(is.null(yuima@model)) stop("model object is missing!") if(is.null(yuima@sampling)) stop("sampling object is missing!") if(is.null(yuima@functional)) stop("functional object is missing!") f <- getf(yuima@functional) F <- getF(yuima@functional) ##:: fix bug 07/23 #e <- gete(yuima@functional) assign(expand.var, gete(yuima@functional)) Terminal <- yuima@sampling@Terminal[1] division <- yuima@sampling@n[1] xinit <- getxinit(yuima@functional) state <- yuima@[email protected] V0 <- yuima@model@drift V <- yuima@model@diffusion r.size <- yuima@[email protected] d.size <- yuima@[email protected] k.size <- length(F) # print("compute X.t0") X.t0 <- Get.X.t0(yuima, expand.var=expand.var) delta <- deltat(X.t0) ##:: fix bug 07/23 pars <- expand.var #yuima@model@parameter@all[1] #epsilon # fix bug 20110628 if(k.size==1){ G <- function(x){ n <- length(x) res <- numeric(0) for(i in 1:n){ res <- append(res,g(x[i])) } return(res) } }else{ G <- function(x) return(g(x)) } # function to return symbolic derivatives of myfunc by mystate(multi-state) Derivation.vector <- function(myfunc,mystate,dim1,dim2){ tmp <- vector(dim1*dim2,mode="expression") for(i in 1:dim1){ for(j in 1:dim2){ tmp[(i-1)*dim2+j] <- parse(text=deparse(D(myfunc[i],mystate[j]))) } } return(tmp) } # function to return symbolic derivatives of myfunc by mystate(single state) Derivation.scalar <- function(myfunc,mystate,dim){ tmp <- vector(dim,mode="expression") for(i in 1:dim){ tmp[i] <- parse(text=deparse(D(myfunc[i],mystate))) } return(tmp) } # function to solve Y_{t} (between (13.9) and (13.10)) using runge kutta method. Y_{t} is GL(d) valued (matrices) Get.Y <- function(env){ ## init dt <- env$delta assign(pars,0) ## epsilon=0 Yinit <- as.vector(diag(d.size)) Yt <- Yinit Y <- Yinit k <- numeric(d.size*d.size) k1 <- numeric(d.size*d.size) k2 <- numeric(d.size*d.size) k3 <- numeric(d.size*d.size) k4 <- numeric(d.size*d.size) Ystate <- paste("y",1:(d.size*d.size),sep="") F <- NULL F.n <- vector(d.size,mode="expression") for(n in 1:d.size){ for(i in 1:d.size){ F.tmp <- dx.drift[((i-1)*d.size+1):(i*d.size)] F.n[i] <- parse(text=paste(paste("(",F.tmp,")","*", Ystate[((n-1)*d.size+1):(n*d.size)],sep=""), collapse="+")) } F <- append(F,F.n) } ## runge kutta for(t in 1:(division-1)){ ## Xt for(i in 1:d.size){ assign(state[i],X.t0[t,i]) ## state[i] is x_i, for example. } ## k1 for(i in 1:(d.size*d.size)){ assign(Ystate[i],Yt[i]) } for(i in 1:(d.size*d.size)){ k1[i] <- dt*eval(F[i]) } ## k2 for(i in 1:(d.size*d.size)){ assign(Ystate[i],Yt[i]+k1[i]/2) } for(i in 1:(d.size*d.size)){ k2[i] <- dt*eval(F[i]) } ## k3 for(i in 1:(d.size*d.size)){ assign(Ystate[i],Yt[i]+k2[i]/2) } for(i in 1:(d.size*d.size)){ k3[i] <- dt*eval(F[i]) } ## k4 ##modified ## Xt+1 for(i in 1:d.size){ assign(state[i],X.t0[t+1,i]) } ## for(i in 1:(d.size*d.size)){ assign(Ystate[i],Yt[i]+k3[i]) } for(i in 1:(d.size*d.size)){ k4[i] <- dt*eval(F[i]) } ## F(Y(t+dt)) k <- (k1+k2+k2+k3+k3+k4)/6 Yt <- Yt+k Y <- rbind(Y,Yt) } ## return matrix : (division+1)*(d.size*d.size) rownames(Y) <- NULL colnames(Y) <- Ystate return(ts(Y,deltat=dt,start=0)) } #l*t e_F <- function(X.t0,tmp.F,env){ d.size <- env$d.size k.size <- env$k.size division <- env$division result <- matrix(0,k.size,division) assign(pars[1],0) de.F <- list() for(k in 1:k.size){ de.F[[k]] <- parse(text=deparse(D(tmp.F[k],pars[1]))) } for(t in 1:division){ for(d in 1:d.size){ assign(state[d],X.t0[t,d]) } for(k in 1:k.size){ result[k,t] <- eval(de.F[[k]]) } } return(result) } # function to calculate mu in thesis p5 funcmu <- function(e=0,env){ d.size <- env$d.size k.size <- env$k.size division <- env$division delta <- env$delta n1 <- length(get_e_f0) n2 <- sum(get_e_f0 == 0) n3 <- length(get_e_F) n4 <- sum(get_e_F == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) if(n == 0){ mu1 <- double(k.size) }else{ mu1 <- apply(get_e_f0,1,sum) * delta + get_e_F[,division] } n5 <- length(get_Y_e_V0) n6 <- sum(get_Y_e_V0 == 0) n <- n5 - n6 if(n == 0){ mu2 <- double(k.size) }else{ n7 <- length(get_x_F) n8 <- sum(get_x_F == 0) n <- n7 - n8 if(n == 0){ mu2_1 <- double(k.size) }else{ mu2_1 <- matrix(get_x_F[,,division],k.size,d.size) %*% tmpY[,,d.size] %*% matrix(apply(get_Y_e_V0,1,sum),d.size,1) * delta } n9 <- length(get_x_f0) n10 <- sum(get_x_f0 == 0) n <- n7 - n8 if(n == 0){ mu2_2 <- double(k.size) }else{ mu2_2 <- double(k.size) for(l in 1:k.size){ for(i in 1:d.size){ for(j in 1:d.size){ tmp1 <- I0(get_Y_e_V0[j,],env) tmp2 <- get_x_f0[l,i,] * tmpY[i,j,] * tmp1 mu2_2[l] <- mu2_2[l] + I0(tmp2,env) } } } } mu2 <- mu2_1 + mu2_2 } mu <- mu1 + mu2 return(mu) } # function to calculate a_{s}^{alpha} in bookchapter p5 #k*r*t funca <- function(e=0,env=env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size division <- env$division delta <- env$delta first <- get_e_f second <- array(0,dim=c(k.size,r.size,division)) second.tmp <- matrix(get_x_F[,,division],k.size,d.size) %*% tmpY[,,division] for(t in 1:division){ second[,,t] <- second.tmp %*% matrix(get_Y_e_V[,,t],d.size,r.size) } third <- array(0,dim=c(k.size,r.size,division)) third.tmp <- matrix(0,k.size,d.size) n1 <- length(get_x_f0) n2 <- sum(get_x_f0 == 0) n <- n1 - n2 third[,,division] <- 0 ## modified 12/06 if(n != 0){ for(s in (division-1):1){ third.tmp <- third.tmp + matrix(get_x_f0[,,s],k.size,d.size) %*% tmpY[,,s] * delta third[,,s] <- third.tmp %*% matrix(get_Y_e_V[,,s],d.size,r.size) } } result <- first + second + third return(result) #size:array[k.size,r.size,division] } # function to calculate sigma in thesis p5 # require: aMat funcsigma <- function(e=0,env=env){ k.size <- env$k.size division <- env$division delta <- env$delta sigma <- matrix(0,k.size,k.size) #size:matrix[k.size,k.size] for(t in 1:(division-1)){ a.t <- matrix(aMat[,,t],k.size,r.size) sigma <- sigma + (a.t %*% t(a.t)) * delta } # Singularity check if(any(eigen(sigma)$value<=0.0001)){ yuima.warn("Eigen value of covariance matrix in very small.") } return(sigma) } ## integrate start:1 end:t number to integrate:block # because integration at all 0:T takes too much time, # we sample only 'block' points and use trapezium rule to integrate make.range.for.trapezium.fomula <- function(t,block){ if(t/block <= 1){ # block >= t : just use all points range <- c(1:t) }else{ # make array which includes points to use range <- as.integer( (c(0:block) * (t/block))+1) if( range[block+1] < t){ range[block+2] <- t }else if( range[block+1] > t){ range[block+1] <- t } } return(range) } ## multi dimension gausian distribusion normal <- function(x,mu,Sigma){ if(length(x)!=length(mu)){ print("Error:length of x != one of mu") } dimension <- length(x) tmp <- 1/((sqrt(2*pi))^dimension * sqrt(det(Sigma))) * exp(-1/2 * t((x-mu)) %*% solve(Sigma) %*% (x-mu) ) return(tmp) } ## get d0 ## get.d0.term <- function(){ ## get g(z)*pi0(z) ##modified # gz_pi0 <- function(z){ # return( G(z) * H0 *normal(z,mu=mu,Sigma=Sigma)) # } gz_pi0 <- function(z){ tmpz <- matA %*% z return(G(tmpz) * H0 * normal(tmpz,mu=mu,Sigma=Sigma)) #det(matA) = 1 } ## gz_pi02 <- function(z){ return(G(z) * H0 * dnorm(z,mean=mu,sd=sqrt(Sigma))) } ## integrate if( k.size ==1){ # use 'integrate' if k=1 tmp <- integrate(gz_pi02,mu-7*sqrt(Sigma),mu+7*sqrt(Sigma))$value }else if( 2 <= k.size || k.size <= 20 ){ # use 'cubature' to solve multi-dimentional integration lambda <- eigen(Sigma)$values matA <- eigen(Sigma)$vector lower <- c() upper <- c() for(k in 1:k.size){ max <- 7 * sqrt(lambda[k]) lower[k] <- - max upper[k] <- max } #if(require(cubature)){ tmp <- adaptIntegrate(gz_pi0, lowerLimit=lower,upperLimit=upper)$integral # } else { # tmp <- NA # } }else{ stop("length k is too big.") } return(tmp) } ############################################################################### # following funcs are part of d1 term # because they are finally integrated at 'get.d1.term()', # these funcs are called over and over again. # so, we use trapezium rule for integration to save time and memory. # these funcs almost calculate each formulas including trapezium integration. # see each formulas in thesis to know what these funcs do. # some funcs do alternative calculation at k=1. # it depends on 'integrate()' function ############################################################################### #a:l, b:l*j*r*t/j*r*t, c:l*r*t #l ft1_1 <- function(a1,env){ k.size <- env$k.size result <- a1 return(result) } #first:l*k*k, second:l ft1_2 <- function(b1,env){ d.size <- env$d.size k.size <- env$k.size block <- env$block first <- array(0,dim=c(k.size,k.size,k.size)) second <- double(k.size) for(l in 1:k.size){ for(j in 1:d.size){ tmp <- I_12(b1[[1]][l,j,,],b1[[2]][j,,],env) first[l,,] <- first[l,,] + tmp$first[,,block] second <- second + tmp$second[block] } } return(list(first=first,second=second)) } #l*k ft1_3 <- function(c1,env){ k.size <- env$k.size block <- env$block result <- matrix(0,k.size,k.size) for(l in 1:k.size){ tmp <- I_1(c1[l,,],env) result[l,] <- tmp[,block] } return(result) } F_tilde1__1 <- function(get_F_tilde1,env){ k.size <- env$k.size temp <- list() temp$first <- array(0,dim=c(k.size,k.size,k.size)) temp$second <- matrix(0,k.size,k.size) temp$third <- double(k.size) calc.range <- c(1:3) tmp1 <- get_F_tilde1$result1 n1 <- length(tmp1) n2 <- sum(tmp1 == 0) if(n1 == n2){ calc.range <- calc.range[calc.range != 1] } tmp2 <- get_F_tilde1$result2[[1]] n3 <- length(tmp2) n4 <- sum(tmp2 == 0) tmp3 <- get_F_tilde1$result2[[2]] n5 <- length(tmp3) n6 <- sum(tmp3 == 0) n <- (n3 - n4 != 0) * (n5 - n6 != 0) if(n == 0){ calc.range <- calc.range[calc.range != 2] } tmp3 <- get_F_tilde1$result3 n7 <- length(tmp3) n8 <- sum(tmp3 == 0) if(n7 == n8){ calc.range <- calc.range[calc.range != 3] } for(i in calc.range){ tmp <- switch(i,"a","b","c") result <- switch(tmp,"a"=ft1_1(get_F_tilde1[[i]],env), "b"=ft1_2(get_F_tilde1[[i]],env), "c"=ft1_3(get_F_tilde1[[i]],env)) nlist <- length(result) if(nlist != 2){ tmp1 <- length(dim(result)) #2 or NULL if(tmp1 == 0){ tmp1 <- 3 } temp[[tmp1]] <- temp[[tmp1]] + result }else{ temp[[1]] <- temp[[1]] + result[[1]] temp[[3]] <- temp[[3]] + result[[2]] } } first <- temp$first second <- temp$second third <- temp$third return(list(first=first,second=second,third=third)) } F_tilde1_x <- function(l,x){ first <- matrix(get_F_tilde1__1$first[l,,], k.size,k.size) result1 <- 0 for(k1 in 1:k.size){ for(k2 in 1:k.size){ result1 <- result1 + first[k1,k2] * x[k1] * x[k2] } } second <- get_F_tilde1__1$second[l,] result2 <- 0 for(k1 in 1:k.size){ result2 <- result2 + second[k1] * x[k1] } result3 <- get_F_tilde1__1$third[l] result <- result1 + result2 + result3 return(result) } #h:d*block #first:numeric(1), second:k.size*block Di_bar <- function(h,env){ block <- env$block first <- double(1) tmp4 <- matrix(0,r.size,block) tmp6 <- matrix(0,r.size,block) tmp5 <- matrix(0,r.size,block) for(i in 1:d.size){ tmp1 <- h[i,] * get_Y_D[i,] first <- first + I0(tmp1,env)[block] for(j in 1:d.size){ tmp2 <- h[i,] * tmpY[i,j,] tmp3 <- I0(tmp2,env) tmp4 <- tmp4 + tmp3[block] * get_Y_e_V[j,,] for(r in 1:r.size){ tmp5[r,] <- tmp3 * get_Y_e_V[j,r,] } tmp6 <- tmp6 + tmp5 } } tmp7 <- tmp4 - tmp6 second <- I_1(tmp7,env) return(list(first=first,second=second)) } Di_bar_x <- function(h,x){ tmp1 <- Di_bar(h,env) tmp2 <- tmp1$second result <- tmp1$first + I_1_x(x,tmp2,env) return(result) } get.P2 <- function(z){ block <- env$block if(k.size==1){ First <- Di_bar_x(di.rho,z) Second <- rep(de.rho %*% Diff[block,] * delta ,length(z)) }else{ First <- Di_bar_x(di.rho,z) Second <- de.rho %*% Diff[block,] * delta } tmp <- First + Second return(tmp) } # now calculate pi1 using funcs above get.pi1 <- function(z){ First <- 0 z.tilda <- z - mu if(k.size ==1){ zlen <- length(z) result <- c() for(i in 1:zlen){ First <- (F_tilde1_x(1,z.tilda[i]+delta) * dnorm(z[i]+delta,mean=mu,sd=sqrt(Sigma)) - F_tilde1_x(1,z.tilda[i]) * dnorm(z[i],mean=mu,sd=sqrt(Sigma)))/delta Second <- get.P2(z.tilda[i]) * dnorm(z[i],mean=mu,sd=sqrt(Sigma)) result[i] <- First + Second } }else{ tmp <- numeric(k.size) for(k in 1:k.size){ dif <- numeric(k.size) dif[k] <- dif[k] + delta z.delta <- z.tilda + dif tmp[k] <- (F_tilde1_x(k,z.delta) * normal(z.delta,numeric(k.size),Sigma) - F_tilde1_x(k,z.tilda) * normal(z.tilda,numeric(k.size),Sigma))/delta } First <- sum(tmp) Second <- get.P2(z.tilda) * normal(z.tilda,numeric(k.size),Sigma) result <- First + Second } pi1 <- - H0 * result return(pi1) } # calculate d1 ## get.d1.term<- function(){ ## get g(z)*pi1(z) gz_pi1 <- function(z){ tmp <- G(z) * get.pi1(z) return( tmp ) } ## integrate if(k.size == 1){ # use 'integrate()' tmp <- integrate(gz_pi1,mu-7*sqrt(Sigma),mu+7*sqrt(Sigma))$value }else if(2 <= k.size || k.size <= 20){ lambda <- eigen(Sigma)$values matA <- eigen(Sigma)$vector gz_pi1 <- function(z){ tmpz <- matA %*% z tmp <- G(tmpz) * get.pi1(tmpz) #det(matA) = 1 return( tmp ) } my.x <- matrix(0,k.size,20^k.size) dt <- 1 for(k in 1:k.size){ max <- 7 * sqrt(lambda[k]) min <- -7 * sqrt(lambda[k]) tmp.x <- seq(min,max,length=20) dt <- dt * (tmp.x[2] - tmp.x[1]) my.x[k,] <- rep(tmp.x,each=20^(k.size-k),times=20^(k-1)) } tmp <- 0 for(i in 1:20^k.size){ tmp <- tmp + gz_pi1(my.x[,i]) } tmp <- tmp * dt }else{ stop("length k is too long.") } return(tmp) } # 'rho' is a given function of (X,e) (p.7 formula(13.19)) # d(rho)/di get.di.rho <- function(){ assign(pars[1],0) di.rho <- numeric(d.size) tmp <- matrix(0,d.size,block+1) for(i in 1:d.size){ di.rho[i] <- deriv(rho,state[i]) } for(t in 1:(block+1)){ for(i in 1:d.size){ assign(state[i],X.t0[t,i]) } for(j in 1:d.size){ tmp[j,t]<- attr(eval(di.rho[j]),"grad") } } return(tmp) } # d(rho)/de get.de.rho <- function(){ assign(pars[1],0) tmp <- matrix(0,1,block+1) de.rho <- deriv(rho,pars[1]) for(t in 1:(block+1)){ for(i in 1:d.size){ assign(state[i],X.t0[t,i]) } tmp[1,t]<- attr(eval(de.rho),"grad") } return(tmp) } # H_{t}^{e} at t=0 (see formula (13.19)) # use trapezium integration get.H0 <- function(){ assign(pars[1],0) tmp <- matrix(0,1,division-1) for(t in 1:(division-1)){ for(i in 1:d.size){ assign(state[i],X.t0[t,i]) } tmp[1,t] <- eval(rho) } H0 <- exp(-(sum(tmp) * delta)) return(as.double(H0) ) } ################################################# # Here is an entry point of 'asymptotic_term()' # ################################################# ## initialization part division <- nrow(X.t0) delta <- Terminal/(division - 1) # make expressions of derivation of V0 dx.drift <- Derivation.vector(V0,state,d.size,d.size) de.drift <- Derivation.scalar(V0,pars,d.size) dede.drift <- Derivation.scalar(de.drift,pars,d.size) # make expressions of derivation of V dx.diffusion <- as.list(NULL) for(i in 1:d.size){ dx.diffusion[i] <- list(Derivation.vector(V[[i]],state,d.size,r.size)) } de.diffusion <- as.list(NULL) for(i in 1:d.size){ de.diffusion[i] <- list(Derivation.scalar(V[[i]],pars,r.size)) } dede.diffusion <- as.list(NULL) for(i in 1:d.size){ dede.diffusion[i] <- list(Derivation.scalar(de.diffusion[[i]],pars,r.size)) } dxdx.drift <- list() dxdx.diffusion <- list() for(i1 in 1:d.size){ dxdx.drift[[i1]] <- list() dxdx.diffusion[[i1]] <- list() for(i2 in 1:d.size){ dxdx.drift[[i1]][[i2]] <- list() dxdx.diffusion[[i1]][[i2]] <- list() for(i in 1:d.size){ tmp1 <- parse(text=deparse(D(V0[i],state[i2]))) dxdx.drift[[i1]][[i2]][i] <- parse(text=deparse(D(tmp1,state[i1]))) dxdx.diffusion[[i1]][[i2]][[i]] <- list() for(r in 1:r.size){ tmp2 <- parse(text=deparse(D(V[[i]][r],state[i2]))) dxdx.diffusion[[i1]][[i2]][[i]][r] <- parse(text=deparse(D(tmp2,state[i1]))) } } } } dxde.drift <- list() dxde.diffusion <- list() for(i1 in 1:d.size){ dxde.drift[[i1]] <- list() dxde.diffusion[[i1]] <- list() for(i in 1:d.size){ tmp1 <- parse(text=deparse(D(V0[i],pars[1]))) dxde.drift[[i1]][i] <- parse(text=deparse(D(tmp1,state[i1]))) dxde.diffusion[[i1]][[i]] <- list() for(r in 1:r.size){ tmp2 <- parse(text=deparse(D(V[[i]][r],pars[1]))) dxde.diffusion[[i1]][[i]][r] <- parse(text=deparse(D(tmp2,state[i1]))) } } } env <- new.env() env$d.size <- d.size env$r.size <- r.size env$k.size <- k.size env$division <- division env$delta <- delta env$state <- state env$pars <- pars env$block <- division env$my.range <- c(1:division) # yuima.warn("Get variables ...") Y <- Get.Y(env=env) tmpY <- array(0,dim=c(d.size,d.size,division)) invY <- array(0,dim=c(d.size,d.size,division)) for(t in 1:division){ tmpY[,,t] <- matrix(Y[t,],d.size,d.size) invY[,,t] <- solve(tmpY[,,t]) } env$invY <- invY get_e_f0 <- e_f0(X.t0,f,env) get_e_f <- e_f(X.t0,f,env) get_x_f0 <- x_f0(X.t0,f,env) get_e_F <- e_F(X.t0,F,env) get_x_F <- x_F(X.t0,F,env) get_Y_e_V0 <- Y_e_V0(X.t0,de.drift,env) get_Y_e_V <- Y_e_V(X.t0,de.diffusion,env) mu <- funcmu(env=env) aMat <- funca(env=env) ## 2010/11/24, TBC Sigma <- funcsigma(env=env) invSigma <- solve(Sigma) di.rho <- get.di.rho() de.rho <- get.de.rho() H0 <- get.H0() # yuima.warn("Done.") ## calculation # yuima.warn("Calculating d0 ...") d0 <- get.d0.term() # yuima.warn("Done\n") # yuima.warn("Calculating d1 term ...") # prepare for trapezium integration my.range <- make.range.for.trapezium.fomula(division,block) my.diff <- my.range[2:(block+1)] - my.range[1:block] Diff <- matrix(0,block+1,block+1) for(t in 2:length(my.range)){ for(s in 1:t){ if( s==1 || t==s ){ if(s==1){ Diff[t,s] <- my.diff[s] }else if(t==s){ Diff[t,s] <- my.diff[s-1] } }else{ Diff[t,s] <- my.diff[s-1] + my.diff[s] } } } Diff <- Diff / 2 # trapezium integrations need "/2" env$aMat <- aMat env$mu <- mu env$Sigma <- Sigma env$invSigma <- invSigma env$invY <- array(invY[,,my.range],dim=c(d.size,d.size,block+1)) env$block <- block + 1 env$my.range <- my.range env$Diff <- Diff tmpY <- array(tmpY[,,my.range],dim=c(d.size,d.size,block+1)) get_Y_e_V0 <- Y_e_V0(X.t0,de.drift,env) get_Y_e_V <- Y_e_V(X.t0,de.diffusion,env) get_Y_D <- Y_D(X.t0,tmpY,get_Y_e_V0,env) get_Y_x1_x2_V0 <- Y_x1_x2_V0(X.t0,dxdx.drift,env) get_Y_x1_x2_V <- Y_x1_x2_V(X.t0,dxdx.diffusion,env) get_Y_x_e_V0 <- Y_x_e_V0(X.t0,dxde.drift,env) get_Y_x_e_V <- Y_x_e_V (X.t0,dxde.diffusion,env) get_Y_e_e_V0 <- Y_e_e_V0(X.t0,dede.drift,env) get_Y_e_e_V <- Y_e_e_V(X.t0,dede.diffusion,env) get_D0_t <- D0_t(tmpY, get_Y_D, get_Y_e_V) get_e_t <- e_t(tmpY, get_Y_e_V, get_Y_D, get_Y_x1_x2_V0, get_Y_x_e_V0, get_Y_e_e_V0, env) get_U_t <- U_t(tmpY, get_Y_D, get_Y_x1_x2_V0, get_Y_x_e_V0, env) get_U_hat_t <- U_hat_t(tmpY, get_Y_e_V, get_Y_D, get_Y_x1_x2_V0, get_Y_x_e_V, env) get_E0_t <- E0_t(tmpY, get_Y_e_V, get_Y_x1_x2_V0, get_Y_e_e_V, get_e_t, get_U_t, get_U_hat_t, env) get_e_f0 <- e_f0(X.t0,f,env) get_e_f <- e_f(X.t0,f,env) get_x_f0 <- x_f0(X.t0,f,env) get_x1_x2_f0 <- x1_x2_f0(X.t0,f,env) get_x1_x2_f <- x1_x2_f(X.t0,f,env) get_x_e_f0 <- x_e_f0(X.t0,f,env) get_x_e_f <- x_e_f(X.t0,f,env) get_e_e_f0 <- e_e_f0(X.t0,f,env) get_e_e_f <- e_e_f(X.t0,f,env) get_F_t <- F_t (tmpY, get_Y_e_V, get_Y_D, get_x1_x2_f0, get_x_e_f0, get_e_e_f0, env) get_W_t <- W_t (tmpY, get_Y_D, get_x1_x2_f0, get_x_e_f0, env) get_W_hat_t <- W_hat_t (tmpY, get_Y_e_V, get_x1_x2_f0, get_x_e_f, env) get_F_tilde1_1 <- F_tilde1_1(tmpY, get_Y_e_V, get_x1_x2_f0, get_e_e_f, get_F_t, get_W_t, get_W_hat_t, env) get_F_tilde1_2 <- F_tilde1_2(get_E0_t,get_x_f0,env) get_x_F <- x_F(X.t0,F,env) get_x1_x2_F <- x1_x2_F(X.t0,F,env) get_x_e_F <- x_e_F(X.t0,F,env) get_e_e_F <- e_e_F(X.t0,F,env) get_F_tilde1_3 <- F_tilde1_3(get_E0_t,get_x_F,env) get_F_tilde1_4 <- F_tilde1_4(tmpY, get_Y_e_V, get_Y_D, get_x_F, get_x1_x2_F, get_x_e_F, get_e_e_F, env) get_F_tilde1 <- F_tilde1(get_F_tilde1_1, get_F_tilde1_2, get_F_tilde1_3, get_F_tilde1_4) get_F_tilde1__1 <- F_tilde1__1(get_F_tilde1,env) d1 <- get.d1.term() # yuima.warn("Done\n") terms <- list(d0=d0, d1=d1, Sigma=Sigma) return(terms) })
/scratch/gouwar.j/cran-all/cranData/yuima/R/asymptotic_term_second.R
yuima.warn <- function(x){ cat(sprintf("\nYUIMA: %s\n", x)) } # in this source we note formulae like latex setGeneric("asymptotic_term", function(yuima,block=100, rho, g, expand.var="e") standardGeneric("asymptotic_term")) setMethod("asymptotic_term",signature(yuima="yuima"), function(yuima,block=100, rho, g, expand.var="e"){ if(is.null(yuima@model)) stop("model object is missing!") if(is.null(yuima@sampling)) stop("sampling object is missing!") if(is.null(yuima@functional)) stop("functional object is missing!") f <- getf(yuima@functional) F <- getF(yuima@functional) ##:: fix bug 07/23 #e <- gete(yuima@functional) assign(expand.var, gete(yuima@functional)) Terminal <- yuima@sampling@Terminal[1] division <- yuima@sampling@n[1] xinit <- getxinit(yuima@functional) state <- yuima@[email protected] V0 <- yuima@model@drift V <- yuima@model@diffusion r.size <- yuima@[email protected] d.size <- yuima@[email protected] k.size <- length(F) print("compute X.t0") X.t0 <- Get.X.t0(yuima, expand.var=expand.var) delta <- deltat(X.t0) ##:: fix bug 07/23 pars <- expand.var #yuima@model@parameter@all[1] #epsilon # fix bug 20110628 if(k.size==1){ G <- function(x){ n <- length(x) res <- numeric(0) for(i in 1:n){ res <- append(res,g(x[i])) } return(res) } }else{ G <- function(x) return(g(x)) } # function to return symbolic derivatives of myfunc by mystate(multi-state) Derivation.vector <- function(myfunc,mystate,dim1,dim2){ tmp <- vector(dim1*dim2,mode="expression") for(i in 1:dim1){ for(j in 1:dim2){ tmp[(i-1)*dim2+j] <- parse(text=deparse(D(myfunc[i],mystate[j]))) } } return(tmp) } # function to return symbolic derivatives of myfunc by mystate(single state) Derivation.scalar <- function(myfunc,mystate,dim){ tmp <- vector(dim,mode="expression") for(i in 1:dim){ tmp[i] <- parse(text=deparse(D(myfunc[i],mystate))) } return(tmp) } # function to solve Y_{t} (between (13.9) and (13.10)) using runge kutta method. Y_{t} is GL(d) valued (matrices) Get.Y <- function(env){ ## init dt <- env$delta assign(pars,0) ## epsilon=0 Yinit <- as.vector(diag(d.size)) Yt <- Yinit Y <- Yinit k <- numeric(d.size*d.size) k1 <- numeric(d.size*d.size) k2 <- numeric(d.size*d.size) k3 <- numeric(d.size*d.size) k4 <- numeric(d.size*d.size) Ystate <- paste("y",1:(d.size*d.size),sep="") F <- NULL F.n <- vector(d.size,mode="expression") for(n in 1:d.size){ for(i in 1:d.size){ F.tmp <- dx.drift[((i-1)*d.size+1):(i*d.size)] F.n[i] <- parse(text=paste(paste("(",F.tmp,")","*", Ystate[((n-1)*d.size+1):(n*d.size)],sep=""), collapse="+")) } F <- append(F,F.n) } ## runge kutta for(t in 1:(division-1)){ ## Xt for(i in 1:d.size){ assign(state[i],X.t0[t,i]) ## state[i] is x_i, for example. } ## k1 for(i in 1:(d.size*d.size)){ assign(Ystate[i],Yt[i]) } for(i in 1:(d.size*d.size)){ k1[i] <- dt*eval(F[i]) } ## k2 for(i in 1:(d.size*d.size)){ assign(Ystate[i],Yt[i]+k1[i]/2) } for(i in 1:(d.size*d.size)){ k2[i] <- dt*eval(F[i]) } ## k3 for(i in 1:(d.size*d.size)){ assign(Ystate[i],Yt[i]+k2[i]/2) } for(i in 1:(d.size*d.size)){ k3[i] <- dt*eval(F[i]) } ## k4 ##modified ## Xt+1 for(i in 1:d.size){ assign(state[i],X.t0[t+1,i]) } ## for(i in 1:(d.size*d.size)){ assign(Ystate[i],Yt[i]+k3[i]) } for(i in 1:(d.size*d.size)){ k4[i] <- dt*eval(F[i]) } ## F(Y(t+dt)) k <- (k1+k2+k2+k3+k3+k4)/6 Yt <- Yt+k Y <- rbind(Y,Yt) } ## return matrix : (division+1)*(d.size*d.size) rownames(Y) <- NULL colnames(Y) <- Ystate return(ts(Y,deltat=dt,start=0)) } #l*t e_F <- function(X.t0,tmp.F,env){ d.size <- env$d.size k.size <- env$k.size division <- env$division result <- matrix(0,k.size,division) assign(pars[1],0) de.F <- list() for(k in 1:k.size){ de.F[[k]] <- parse(text=deparse(D(tmp.F[k],pars[1]))) } for(t in 1:division){ for(d in 1:d.size){ assign(state[d],X.t0[t,d]) } for(k in 1:k.size){ result[k,t] <- eval(de.F[[k]]) } } return(result) } # function to calculate mu in thesis p5 funcmu <- function(e=0,env){ d.size <- env$d.size k.size <- env$k.size division <- env$division delta <- env$delta n1 <- length(get_e_f0) n2 <- sum(get_e_f0 == 0) n3 <- length(get_e_F) n4 <- sum(get_e_F == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) if(n == 0){ mu1 <- double(k.size) }else{ mu1 <- apply(get_e_f0,1,sum) * delta + get_e_F[,division] } n5 <- length(get_Y_e_V0) n6 <- sum(get_Y_e_V0 == 0) n <- n5 - n6 if(n == 0){ mu2 <- double(k.size) }else{ n7 <- length(get_x_F) n8 <- sum(get_x_F == 0) n <- n7 - n8 if(n == 0){ mu2_1 <- double(k.size) }else{ mu2_1 <- matrix(get_x_F[,,division],k.size,d.size) %*% tmpY[,,d.size] %*% matrix(apply(get_Y_e_V0,1,sum),d.size,1) * delta } n9 <- length(get_x_f0) n10 <- sum(get_x_f0 == 0) n <- n7 - n8 if(n == 0){ mu2_2 <- double(k.size) }else{ mu2_2 <- double(k.size) for(l in 1:k.size){ for(i in 1:d.size){ for(j in 1:d.size){ tmp1 <- I0(get_Y_e_V0[j,],env) tmp2 <- get_x_f0[l,i,] * tmpY[i,j,] * tmp1 mu2_2[l] <- mu2_2[l] + I0(tmp2,env) } } } } mu2 <- mu2_1 + mu2_2 } mu <- mu1 + mu2 return(mu) } # function to calculate a_{s}^{alpha} in bookchapter p5 #k*r*t funca <- function(e=0,env=env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size division <- env$division delta <- env$delta first <- get_e_f second <- array(0,dim=c(k.size,r.size,division)) second.tmp <- matrix(get_x_F[,,division],k.size,d.size) %*% tmpY[,,division] for(t in 1:division){ second[,,t] <- second.tmp %*% matrix(get_Y_e_V[,,t],d.size,r.size) } third <- array(0,dim=c(k.size,r.size,division)) third.tmp <- matrix(0,k.size,d.size) n1 <- length(get_x_f0) n2 <- sum(get_x_f0 == 0) n <- n1 - n2 third[,,division] <- 0 if(n != 0){ for(s in (division-1):1){ third.tmp <- third.tmp + matrix(get_x_f0[,,s],k.size,d.size) %*% tmpY[,,s] * delta third[,,s] <- third.tmp %*% matrix(get_Y_e_V[,,s],d.size,r.size) } } result <- first + second + third return(result) #size:array[k.size,r.size,division] } # function to calculate sigma in thesis p5 # require: aMat funcsigma <- function(e=0,env=env){ k.size <- env$k.size division <- env$division delta <- env$delta sigma <- matrix(0,k.size,k.size) #size:matrix[k.size,k.size] for(t in 1:(division-1)){ a.t <- matrix(aMat[,,t],k.size,r.size) sigma <- sigma + (a.t %*% t(a.t)) * delta } # Singularity check if(any(eigen(sigma)$value<=0.0001)){ yuima.warn("Eigen value of covariance matrix in very small.") } return(sigma) } ## integrate start:1 end:t number to integrate:block # because integration at all 0:T takes too much time, # we sample only 'block' points and use trapezium rule to integrate make.range.for.trapezium.fomula <- function(t,block){ if(t/block <= 1){ # block >= t : just use all points range <- c(1:t) }else{ # make array which includes points to use range <- as.integer( (c(0:block) * (t/block))+1) if( range[block+1] < t){ range[block+2] <- t }else if( range[block+1] > t){ range[block+1] <- t } } return(range) } ## multi dimension gausian distribusion normal <- function(x,mu,Sigma){ if(length(x)!=length(mu)){ print("Error:length of x != one of mu") } dimension <- length(x) tmp <- 1/((sqrt(2*pi))^dimension * sqrt(det(Sigma))) * exp(-1/2 * t((x-mu)) %*% solve(Sigma) %*% (x-mu) ) return(tmp) } ## get d0 ## get.d0.term <- function(){ ## get g(z)*pi0(z) ##modified # gz_pi0 <- function(z){ # return( G(z) * H0 *normal(z,mu=mu,Sigma=Sigma)) # } gz_pi0 <- function(z){ tmpz <- matA %*% z return(G(tmpz) * H0 * normal(tmpz,mu=mu,Sigma=Sigma)) #det(matA) = 1 } ## gz_pi02 <- function(z){ return(G(z) * H0 * dnorm(z,mean=mu,sd=sqrt(Sigma))) } ## integrate if( k.size ==1){ # use 'integrate' if k=1 tmp <- integrate(gz_pi02,mu-7*sqrt(Sigma),mu+7*sqrt(Sigma))$value }else if( 2 <= k.size || k.size <= 20 ){ # use 'cubature' to solve multi-dimentional integration lambda <- eigen(Sigma)$values matA <- eigen(Sigma)$vector lower <- c() upper <- c() for(k in 1:k.size){ max <- 7 * sqrt(lambda[k]) lower[k] <- - max upper[k] <- max } # if(require(cubature)){ tmp <- adaptIntegrate(gz_pi0, lowerLimit=lower,upperLimit=upper)$integral # } else { # tmp <- NA #} }else{ stop("length k is too big.") } return(tmp) } ############################################################################### # following funcs are part of d1 term # because they are finally integrated at 'get.d1.term()', # these funcs are called over and over again. # so, we use trapezium rule for integration to save time and memory. # these funcs almost calculate each formulas including trapezium integration. # see each formulas in thesis to know what these funcs do. # some funcs do alternative calculation at k=1. # it depends on 'integrate()' function ############################################################################### #a:l, b:l*j*r*t/j*r*t, c:l*r*t #l ft1_1 <- function(a1,env){ k.size <- env$k.size result <- a1 return(result) } #first:l*k*k, second:l ft1_2 <- function(b1,env){ d.size <- env$d.size k.size <- env$k.size block <- env$block first <- array(0,dim=c(k.size,k.size,k.size)) second <- double(k.size) for(l in 1:k.size){ for(j in 1:d.size){ tmp <- I_12(b1[[1]][l,j,,],b1[[2]][j,,],env) first[l,,] <- first[l,,] + tmp$first[,,block] second <- second + tmp$second[block] } } return(list(first=first,second=second)) } #l*k ft1_3 <- function(c1,env){ k.size <- env$k.size block <- env$block result <- matrix(0,k.size,k.size) for(l in 1:k.size){ tmp <- I_1(c1[l,,],env) result[l,] <- tmp[,block] } return(result) } F_tilde1__1 <- function(get_F_tilde1,env){ k.size <- env$k.size temp <- list() temp$first <- array(0,dim=c(k.size,k.size,k.size)) temp$second <- matrix(0,k.size,k.size) temp$third <- double(k.size) calc.range <- c(1:3) tmp1 <- get_F_tilde1$result1 n1 <- length(tmp1) n2 <- sum(tmp1 == 0) if(n1 == n2){ calc.range <- calc.range[calc.range != 1] } tmp2 <- get_F_tilde1$result2[[1]] n3 <- length(tmp2) n4 <- sum(tmp2 == 0) tmp3 <- get_F_tilde1$result2[[2]] n5 <- length(tmp3) n6 <- sum(tmp3 == 0) n <- (n3 - n4 != 0) * (n5 - n6 != 0) if(n == 0){ calc.range <- calc.range[calc.range != 2] } tmp3 <- get_F_tilde1$result3 n7 <- length(tmp3) n8 <- sum(tmp3 == 0) if(n7 == n8){ calc.range <- calc.range[calc.range != 3] } for(i in calc.range){ tmp <- switch(i,"a","b","c") result <- switch(tmp,"a"=ft1_1(get_F_tilde1[[i]],env), "b"=ft1_2(get_F_tilde1[[i]],env), "c"=ft1_3(get_F_tilde1[[i]],env)) nlist <- length(result) if(nlist != 2){ tmp1 <- length(dim(result)) #2 or NULL if(tmp1 == 0){ tmp1 <- 3 } temp[[tmp1]] <- temp[[tmp1]] + result }else{ temp[[1]] <- temp[[1]] + result[[1]] temp[[3]] <- temp[[3]] + result[[2]] } } first <- temp$first second <- temp$second third <- temp$third return(list(first=first,second=second,third=third)) } F_tilde1_x <- function(l,x){ first <- matrix(get_F_tilde1__1$first[l,,], k.size,k.size) result1 <- 0 for(k1 in 1:k.size){ for(k2 in 1:k.size){ result1 <- result1 + first[k1,k2] * x[k1] * x[k2] } } second <- get_F_tilde1__1$second[l,] result2 <- 0 for(k1 in 1:k.size){ result2 <- result2 + second[k1] * x[k1] } result3 <- get_F_tilde1__1$third[l] result <- result1 + result2 + result3 return(result) } #h:d*block #first:numeric(1), second:r.size*block, third:r.size*block Di_bar <- function(h,env){ block <- env$block first <- double(1) second <- matrix(0,r.size,block) third <- matrix(0,r.size,block) tmp4 <- matrix(0,r.size,block) for(i in 1:d.size){ tmp1 <- h[i,] * get_Y_D[i,] first <- first + I0(tmp1,env)[block] for(j in 1:d.size){ tmp2 <- h[i,] * tmpY[i,j,] tmp3 <- I0(tmp2,env) second <- second + tmp3[block] * get_Y_e_V[j,,] for(r in 1:r.size){ tmp4[r,] <- tmp3 * get_Y_e_V[j,r,] } third <- third + tmp4 } } return(list(first=first,second=second,third=third)) } Di_bar_x <- function(h,x){ tmp1 <- Di_bar(h,env) for(r in 1:r.size){ tmp2 <- I_1(tmp1$second[r,],env) tmp3 <- I_1(tmp1$third[r,],env) result <- tmp1$first + I_1_x(x,tmp2,env) - I_1_x(x,tmp3,env) } return(result) } get.P2 <- function(z){ if(k.size==1){ First <- Di_bar_x(di.rho,z) Second <- rep(de.rho %*% Diff[block,] * delta ,length(z)) }else{ First <- Di_bar_x(di.rho,z) Second <- de.rho %*% Diff[block,] * delta } tmp <- First + Second } # now calculate pi1 using funcs above get.pi1 <- function(z){ First <- 0 z.tilda <- z - mu if(k.size ==1){ zlen <- length(z) result <- c() for(i in 1:zlen){ First <- (F_tilde1_x(1,z.tilda[i]+delta) * dnorm(z[i]+delta,mean=mu,sd=sqrt(Sigma)) - F_tilde1_x(1,z.tilda[i]) * dnorm(z[i],mean=mu,sd=sqrt(Sigma)))/delta Second <- get.P2(z.tilda[i]) * dnorm(z[i],mean=mu,sd=sqrt(Sigma)) result[i] <- First + Second } }else{ tmp <- numeric(k.size) for(k in 1:k.size){ dif <- numeric(k.size) dif[k] <- dif[k] + delta z.delta <- z.tilda + dif tmp[k] <- (F_tilde1_x(k,z.delta) * normal(z.delta,numeric(k.size),Sigma) - F_tilde1_x(k,z.tilda) * normal(z.tilda,numeric(k.size),Sigma))/delta } First <- sum(tmp) Second <- get.P2(z.tilda) * normal(z.tilda,numeric(k.size),Sigma) result <- First + Second } pi1 <- - H0 * result return(pi1) } # calculate d1 ## get.d1.term<- function(){ ## get g(z)*pi1(z) gz_pi1 <- function(z){ tmp <- G(z) * get.pi1(z) return( tmp ) } ## integrate if(k.size == 1){ # use 'integrate()' tmp <- integrate(gz_pi1,mu-7*sqrt(Sigma),mu+7*sqrt(Sigma))$value }else if(2 <= k.size || k.size <= 20){ lambda <- eigen(Sigma)$values matA <- eigen(Sigma)$vector gz_pi1 <- function(z){ tmpz <- matA %*% z tmp <- G(tmpz) * get.pi1(tmpz) #det(matA) = 1 return( tmp ) } my.x <- matrix(0,k.size,20^k.size) dt <- 1 for(k in 1:k.size){ max <- 7 * sqrt(lambda[k]) min <- -7 * sqrt(lambda[k]) tmp.x <- seq(min,max,length=20) dt <- dt * (tmp.x[2] - tmp.x[1]) my.x[k,] <- rep(tmp.x,each=20^(k.size-k),times=20^(k-1)) } tmp <- 0 for(i in 1:20^k.size){ tmp <- tmp + gz_pi1(my.x[,i]) } tmp <- tmp * dt }else{ stop("length k is too long.") } return(tmp) } # 'rho' is a given function of (X,e) (p.7 formula(13.19)) # d(rho)/di get.di.rho <- function(){ assign(pars[1],0) di.rho <- numeric(d.size) tmp <- matrix(0,d.size,block+1) for(i in 1:d.size){ di.rho[i] <- deriv(rho,state[i]) } for(t in 1:(block+1)){ for(i in 1:d.size){ assign(state[i],X.t0[t,i]) } for(j in 1:d.size){ tmp[j,t]<- attr(eval(di.rho[j]),"grad") } } return(tmp) } # d(rho)/de get.de.rho <- function(){ assign(pars[1],0) tmp <- matrix(0,1,block+1) de.rho <- deriv(rho,pars[1]) for(t in 1:(block+1)){ for(i in 1:d.size){ assign(state[i],X.t0[t,i]) } tmp[1,t]<- attr(eval(de.rho),"grad") } return(tmp) } # H_{t}^{e} at t=0 (see formula (13.19)) # use trapezium integration get.H0 <- function(){ assign(pars[1],0) tmp <- matrix(0,1,division-1) for(t in 1:(division-1)){ for(i in 1:d.size){ assign(state[i],X.t0[t,i]) } tmp[1,t] <- eval(rho) } H0 <- exp(-(sum(tmp) * delta)) return(as.double(H0) ) } ##third expansion p2_z <- function(z){ if(k.size == 1){ zlen <- length(z) result <- c() for(i in 1:zlen){ result[i] <- p2(z[i],get_F_tilde1__2,get_F_tilde2, get_F_tilde1H1,get_H2_1,get_H2_2,get_H2_3,env) } }else{ result <- p2(z,get_F_tilde1__2,get_F_tilde2, get_F_tilde1H1,get_H2_1,get_H2_2,get_H2_3,env) } return(result) } d2.term <- function(){ gz_p2 <- function(z){ result <- H0 * G(z) * p2_z(z) return(result) } if(k.size == 1){ ztmp <- seq(mu-7*sqrt(Sigma),mu+7*sqrt(Sigma),length=1000) dt <- ztmp[2] - ztmp[1] my.diff <- diff(ztmp) my.diff[1] <- my.diff[1]/2 my.diff <- c(my.diff,my.diff[1]) p2tmp <- gz_p2(ztmp) result <- p2tmp %*% my.diff }else if(2 <= k.size || k.size <= 20){ lambda <- eigen(Sigma)$values matA <- eigen(Sigma)$vector gz_p2 <- function(z){ tmpz <- matA %*% z tmp <- H0 * G(tmpz) * p2_z(tmpz) #det(matA) = 1 return( tmp ) } my.x <- matrix(0,k.size,20^k.size) dt <- 1 for(k in 1:k.size){ max <- 7 * sqrt(lambda[k]) min <- -7 * sqrt(lambda[k]) tmp.x <- seq(min,max,length=20) dt <- dt * (tmp.x[2] - tmp.x[1]) my.x[k,] <- rep(tmp.x,each=20^(k.size-k),times=20^(k-1)) } result <- 0 for(i in 1:20^k.size){ result <- result + gz_p2(my.x[,i]) } result <- result * dt }else{ stop("length k is too long.") } return(result) } ################################################# # Here is an entry point of 'asymptotic_term()' # ################################################# ## initialization part division <- nrow(X.t0) delta <- Terminal/(division - 1) # make expressions of derivation of V0 dx.drift <- Derivation.vector(V0,state,d.size,d.size) de.drift <- Derivation.scalar(V0,pars,d.size) dede.drift <- Derivation.scalar(de.drift,pars,d.size) # make expressions of derivation of V dx.diffusion <- as.list(NULL) for(i in 1:d.size){ dx.diffusion[i] <- list(Derivation.vector(V[[i]],state,d.size,r.size)) } de.diffusion <- as.list(NULL) for(i in 1:d.size){ de.diffusion[i] <- list(Derivation.scalar(V[[i]],pars,r.size)) } dede.diffusion <- as.list(NULL) for(i in 1:d.size){ dede.diffusion[i] <- list(Derivation.scalar(de.diffusion[[i]],pars,r.size)) } dxdx.drift <- list() dxdx.diffusion <- list() for(i1 in 1:d.size){ dxdx.drift[[i1]] <- list() dxdx.diffusion[[i1]] <- list() for(i2 in 1:d.size){ dxdx.drift[[i1]][[i2]] <- list() dxdx.diffusion[[i1]][[i2]] <- list() for(i in 1:d.size){ tmp1 <- parse(text=deparse(D(V0[i],state[i2]))) dxdx.drift[[i1]][[i2]][i] <- parse(text=deparse(D(tmp1,state[i1]))) dxdx.diffusion[[i1]][[i2]][[i]] <- list() for(r in 1:r.size){ tmp2 <- parse(text=deparse(D(V[[i]][r],state[i2]))) dxdx.diffusion[[i1]][[i2]][[i]][r] <- parse(text=deparse(D(tmp2,state[i1]))) } } } } dxde.drift <- list() dxde.diffusion <- list() for(i1 in 1:d.size){ dxde.drift[[i1]] <- list() dxde.diffusion[[i1]] <- list() for(i in 1:d.size){ tmp1 <- parse(text=deparse(D(V0[i],pars[1]))) dxde.drift[[i1]][i] <- parse(text=deparse(D(tmp1,state[i1]))) dxde.diffusion[[i1]][[i]] <- list() for(r in 1:r.size){ tmp2 <- parse(text=deparse(D(V[[i]][r],pars[1]))) dxde.diffusion[[i1]][[i]][r] <- parse(text=deparse(D(tmp2,state[i1]))) } } } env <- new.env() env$d.size <- d.size env$r.size <- r.size env$k.size <- k.size env$division <- division env$delta <- delta env$state <- state env$pars <- pars env$block <- division env$my.range <- c(1:division) yuima.warn("Get variables ...") Y <- Get.Y(env=env) tmpY <- array(0,dim=c(d.size,d.size,division)) invY <- array(0,dim=c(d.size,d.size,division)) for(t in 1:division){ tmpY[,,t] <- matrix(Y[t,],d.size,d.size) invY[,,t] <- solve(tmpY[,,t]) } env$invY <- invY get_e_f0 <- e_f0(X.t0,f,env) get_e_f <- e_f(X.t0,f,env) get_x_f0 <- x_f0(X.t0,f,env) get_e_F <- e_F(X.t0,F,env) get_x_F <- x_F(X.t0,F,env) get_Y_e_V0 <- Y_e_V0(X.t0,de.drift,env) get_Y_e_V <- Y_e_V(X.t0,de.diffusion,env) mu <- funcmu(env=env) aMat <- funca(env=env) ## 2010/11/24, TBC Sigma <- funcsigma(env=env) invSigma <- solve(Sigma) di.rho <- get.di.rho() de.rho <- get.de.rho() H0 <- get.H0() yuima.warn("Done.") ## calculation yuima.warn("Calculating d0 ...") d0 <- get.d0.term() yuima.warn("Done\n") yuima.warn("Calculating d1 term ...") # prepare for trapezium integration my.range <- make.range.for.trapezium.fomula(division,block) my.diff <- my.range[2:(block+1)] - my.range[1:block] Diff <- matrix(0,block+1,block+1) for(t in 2:length(my.range)){ for(s in 1:t){ if( s==1 || t==s ){ if(s==1){ Diff[t,s] <- my.diff[s] }else if(t==s){ Diff[t,s] <- my.diff[s-1] } }else{ Diff[t,s] <- my.diff[s-1] + my.diff[s] } } } Diff <- Diff / 2 # trapezium integrations need "/2" env$aMat <- aMat env$mu <- mu env$Sigma <- Sigma env$invSigma <- invSigma env$invY <- array(invY[,,my.range],dim=c(d.size,d.size,block+1)) env$block <- block + 1 env$my.range <- my.range env$Diff <- Diff tmpY <- array(tmpY[,,my.range],dim=c(d.size,d.size,block+1)) get_Y_e_V0 <- Y_e_V0(X.t0,de.drift,env) get_Y_e_V <- Y_e_V(X.t0,de.diffusion,env) get_Y_D <- Y_D(X.t0,tmpY,get_Y_e_V0,env) get_Y_x1_x2_V0 <- Y_x1_x2_V0(X.t0,dxdx.drift,env) get_Y_x1_x2_V <- Y_x1_x2_V(X.t0,dxdx.diffusion,env) get_Y_x_e_V0 <- Y_x_e_V0(X.t0,dxde.drift,env) get_Y_x_e_V <- Y_x_e_V (X.t0,dxde.diffusion,env) get_Y_e_e_V0 <- Y_e_e_V0(X.t0,dede.drift,env) get_Y_e_e_V <- Y_e_e_V(X.t0,dede.diffusion,env) get_D0_t <- D0_t(tmpY, get_Y_D, get_Y_e_V) get_e_t <- e_t(tmpY, get_Y_e_V, get_Y_D, get_Y_x1_x2_V0, get_Y_x_e_V0, get_Y_e_e_V0, env) get_U_t <- U_t(tmpY, get_Y_D, get_Y_x1_x2_V0, get_Y_x_e_V0, env) get_U_hat_t <- U_hat_t(tmpY, get_Y_e_V, get_Y_D, get_Y_x1_x2_V0, get_Y_x_e_V, env) get_E0_t <- E0_t(tmpY, get_Y_e_V, get_Y_x1_x2_V0, get_Y_e_e_V, get_e_t, get_U_t, get_U_hat_t, env) get_e_f0 <- e_f0(X.t0,f,env) get_e_f <- e_f(X.t0,f,env) get_x_f0 <- x_f0(X.t0,f,env) get_x1_x2_f0 <- x1_x2_f0(X.t0,f,env) get_x1_x2_f <- x1_x2_f(X.t0,f,env) get_x_e_f0 <- x_e_f0(X.t0,f,env) get_x_e_f <- x_e_f(X.t0,f,env) get_e_e_f0 <- e_e_f0(X.t0,f,env) get_e_e_f <- e_e_f(X.t0,f,env) get_F_t <- F_t (tmpY, get_Y_e_V, get_Y_D, get_x1_x2_f0, get_x_e_f0, get_e_e_f0, env) get_W_t <- W_t (tmpY, get_Y_D, get_x1_x2_f0, get_x_e_f0, env) get_W_hat_t <- W_hat_t (tmpY, get_Y_e_V, get_x1_x2_f0, get_x_e_f, env) get_F_tilde1_1 <- F_tilde1_1(tmpY, get_Y_e_V, get_x1_x2_f0, get_e_e_f, get_F_t, get_W_t, get_W_hat_t, env) get_F_tilde1_2 <- F_tilde1_2(get_E0_t,get_x_f0,env) get_x_F <- x_F(X.t0,F,env) get_x1_x2_F <- x1_x2_F(X.t0,F,env) get_x_e_F <- x_e_F(X.t0,F,env) get_e_e_F <- e_e_F(X.t0,F,env) get_F_tilde1_3 <- F_tilde1_3(get_E0_t,get_x_F,env) get_F_tilde1_4 <- F_tilde1_4(tmpY, get_Y_e_V, get_Y_D, get_x_F, get_x1_x2_F, get_x_e_F, get_e_e_F, env) get_F_tilde1 <- F_tilde1(get_F_tilde1_1, get_F_tilde1_2, get_F_tilde1_3, get_F_tilde1_4) get_F_tilde1__1 <- F_tilde1__1(get_F_tilde1,env) d1 <- get.d1.term() yuima.warn("Done\n") ##third get_F_tilde1__2 <- F_tilde1__2(get_F_tilde1,env) dxdxdx.drift <- list() for(i1 in 1:d.size){ dxdxdx.drift[[i1]] <- list() for(i2 in 1:d.size){ dxdxdx.drift[[i1]][[i2]] <- list() for(i3 in 1:d.size){ tmp1 <- parse(text=deparse(D(V0[i],state[i2]))) dxdxdx.drift[[i1]][[i2]][[i3]] <- list() for(i in 1:d.size){ tmp1 <- parse(text=deparse(D(V0[i],state[i3]))) tmp2 <- parse(text=deparse(D(tmp1,state[i2]))) dxdxdx.drift[[i1]][[i2]][[i3]][i] <- parse(text=deparse(D(tmp2,state[i1]))) } } } } dxdxde.drift <- list() dxdxde.diffusion <- list() for(i1 in 1:d.size){ dxdxde.drift[[i1]] <- list() dxdxde.diffusion[[i1]] <- list() for(i2 in 1:d.size){ dxdxde.drift[[i1]][[i2]] <- list() dxdxde.diffusion[[i1]][[i2]] <- list() for(i in 1:d.size){ tmp1 <- dxde.drift[[i2]][[i]] dxdxde.drift[[i1]][[i2]][i] <- parse(text=deparse(D(tmp1,state[i1]))) dxdxde.diffusion[[i1]][[i2]][[i]] <- list() for(r in 1:r.size){ tmp2 <- dxde.diffusion[[i2]][[i]][[r]] dxdxde.diffusion[[i1]][[i2]][[i]][r] <- parse(text=deparse(D(tmp2,state[i1]))) } } } } dxdede.drift <- list() dxdede.diffusion <- list() for(i1 in 1:d.size){ dxdede.drift[[i1]] <- list() dxdede.diffusion[[i1]] <- list() for(i in 1:d.size){ tmp1 <- dxde.drift[[i1]][[i]] dxdede.drift[[i1]][i] <- parse(text=deparse(D(tmp1,pars[1]))) dxdede.diffusion[[i1]][[i]] <- list() for(r in 1:r.size){ tmp2 <- dxde.diffusion[[i1]][[i]][[r]] dxdede.diffusion[[i1]][[i]][r] <- parse(text=deparse(D(tmp2,pars[1]))) } } } dedede.drift <- list() dedede.diffusion <- list() for(i in 1:d.size){ tmp1 <- parse(text=deparse(D(V0[i],pars[1]))) tmp2 <- parse(text=deparse(D(tmp1,pars[1]))) dedede.drift[[i]] <- parse(text=deparse(D(tmp2,pars[1]))) dedede.diffusion[[i]] <- list() for(r in 1:r.size){ tmp3 <- parse(text=deparse(D(V[[i]][r],pars[1]))) tmp4 <- parse(text=deparse(D(tmp3,pars[1]))) dedede.diffusion[[i]][r] <- parse(text=deparse(D(tmp4,pars[1]))) } } get_Y_x1_x2_x3_V0 <- Y_x1_x2_x3_V0(X.t0,dxdxdx.drift,env) get_Y_x1_x2_e_V0 <- Y_x1_x2_e_V0(X.t0,dxdxde.drift,env) get_Y_x1_x2_e_V <- Y_x1_x2_e_V (X.t0,dxdxde.diffusion,env) get_Y_x_e_e_V0 <- Y_x_e_e_V0(X.t0,dxdede.drift,env) get_Y_x_e_e_V <- Y_x_e_e_V (X.t0,dxdede.diffusion,env) get_Y_e_e_e_V0 <- Y_e_e_e_V0(X.t0,dedede.drift,env) get_Y_e_e_e_V <- Y_e_e_e_V(X.t0,dedede.diffusion,env) get_x1_x2_x3_f0 <- x1_x2_x3_f0(X.t0,f,env) get_x1_x2_x3_f <- x1_x2_x3_f(X.t0,f,env) get_x1_x2_e_f0 <- x1_x2_e_f0(X.t0,f,env) get_x1_x2_e_f <- x1_x2_e_f(X.t0,f,env) get_x_e_e_f0 <- x_e_e_f0(X.t0,f,env) get_x_e_e_f <- x_e_e_f(X.t0,f,env) get_e_e_e_f0 <- e_e_e_f0(X.t0,f,env) get_e_e_e_f <- e_e_e_f(X.t0,f,env) get_x1_x2_x3_F <- x1_x2_x3_F(X.t0,F,env) get_x1_x2_e_F <- x1_x2_e_F(X.t0,F,env) get_x_e_e_F <- x_e_e_F(X.t0,F,env) get_e_e_e_F <- e_e_e_F(X.t0,F,env) get_C_hat1 <- C_hat1(tmpY, get_Y_e_V, get_Y_D, get_Y_x1_x2_V0, get_Y_e_e_V, get_e_t, get_U_t, get_U_hat_t, env) get_C_hat2 <- C_hat2(tmpY, get_Y_e_V, get_Y_x1_x2_V0, get_Y_x_e_V0, get_Y_e_e_V, get_e_t, get_U_t, get_U_hat_t, env) get_C_hat3 <- C_hat3(tmpY, get_Y_e_V, get_Y_D, get_Y_x1_x2_x3_V0, env) get_C_hat4 <- C_hat4(tmpY, get_Y_e_V, get_Y_D, get_Y_x1_x2_e_V0, env) get_C_hat5 <- C_hat5(tmpY, get_Y_e_V, get_Y_D, get_Y_x_e_e_V0, env) get_C_hat6 <- C_hat6(tmpY, get_Y_e_e_e_V0, env) get_C_hat7 <- C_hat7(tmpY, get_Y_e_V, get_Y_x1_x2_V0, get_Y_x_e_V, get_Y_e_e_V, get_e_t, get_U_t, get_U_hat_t, env) get_C_hat8 <- C_hat8(tmpY, get_Y_e_V, get_Y_D, get_Y_x1_x2_e_V, env) get_C_hat9 <- C_hat9(tmpY, get_Y_e_V, get_Y_D, get_Y_x_e_e_V, env) get_C_hat10 <- C_hat10(tmpY, get_Y_e_e_e_V, env) get_C0_t <- C0_t(get_C_hat1, get_C_hat2, get_C_hat3, get_C_hat4, get_C_hat5, get_C_hat6, get_C_hat7, get_C_hat8, get_C_hat9, get_C_hat10) get_F_tilde2_1_1 <- F_tilde2_1_1(get_x_f0,get_C0_t,env) get_F_tilde2_1_2 <- F_tilde2_1_2(get_x_F,get_C0_t,env) get_D_E <- D_E(tmpY, get_Y_e_V, get_Y_D, get_Y_x1_x2_V0, get_Y_e_e_V, get_e_t, get_U_t, get_U_hat_t, env) get_F_tilde2_2_1 <- F_tilde2_2_1(get_x1_x2_f0,get_D_E,env) get_F_tilde2_2_2 <- F_tilde2_2_2(get_x1_x2_F,get_D_E,env) get_F_tilde2_3_1 <- F_tilde2_3_1(tmpY, get_Y_e_V, get_Y_x1_x2_V0, get_Y_e_e_V, get_U_t, get_U_hat_t, get_e_t, get_x_e_f0, env) get_E0_bar <- E0_bar(get_E0_t,env) get_F_tilde2_3_2 <- F_tilde2_3_2(get_E0_bar, get_x_e_F, env) get_D_a <- D_a(tmpY, get_Y_e_V, get_Y_D, env) get_D_b <- D_b(tmpY, get_Y_e_V, get_Y_D, env) get_D_c <- D_c(tmpY, get_Y_e_V, get_Y_D, env) get_F_tilde2_4_1 <- F_tilde2_4_1(get_x1_x2_x3_f0, get_x1_x2_e_f0, get_x_e_e_f0, get_e_e_e_f0, get_D_a, get_D_b, get_D_c, env) get_F_tilde2_4_2 <- F_tilde2_4_2(get_x1_x2_x3_F, get_x1_x2_e_F, get_x_e_e_F, get_e_e_e_F, get_D_a, get_D_b, get_D_c, env) get_F_tilde2_5 <- F_tilde2_5(tmpY, get_Y_e_V, get_Y_x1_x2_V0, get_Y_e_e_V, get_e_t, get_U_t, get_U_hat_t, get_x_e_f, env) get_F_tilde2_6 <- F_tilde2_6(tmpY, get_Y_e_V, get_Y_D, get_x1_x2_e_f, env) get_F_tilde2_7 <- F_tilde2_7(tmpY, get_Y_e_V, get_Y_D, get_x_e_e_f, env) get_F_tilde2_8 <- F_tilde2_8(get_e_e_e_f,env) get_F_tilde2 <- F_tilde2(get_F_tilde2_1_1, get_F_tilde2_1_2, get_F_tilde2_2_1, get_F_tilde2_2_2, get_F_tilde2_3_1, get_F_tilde2_3_2, get_F_tilde2_4_1, get_F_tilde2_4_2, get_F_tilde2_5, get_F_tilde2_6, get_F_tilde2_7, get_F_tilde2_8) #added get_x_rho <- x_rho(X.t0,rho,env) get_e_rho <- e_rho(X.t0,rho,env) get_x1_x2_rho <- x1_x2_rho(X.t0,rho,env) get_x_e_rho <- x_e_rho(X.t0,rho,env) get_e_e_rho <- e_e_rho(X.t0,rho,env) ##modified n1 <- length(get_x_rho) n2 <- sum(get_x_rho == 0) n3 <- length(get_e_rho) n4 <- sum(get_e_rho == 0) n5 <- length(get_x1_x2_rho) n6 <- sum(get_x1_x2_rho == 0) n7 <- length(get_x_e_rho) n8 <- sum(get_x_e_rho == 0) n9 <- length(get_e_e_rho) n10 <- sum(get_e_e_rho == 0) n <- (n1 - n2 != 0) + (n3 - n4 != 0) + (n5 - n6 != 0) + (n7 - n8 != 0) + (n9 - n10 != 0) if(n != 0){ get_scH_0_1 <- scH_0_1(get_Y_D,get_e_rho,get_x_rho,env) get_scH_1_1 <- scH_1_1(tmpY,get_Y_e_V,get_x_rho,env) get_scH_1_2 <- scH_1_2(get_scH_1_1,env) get_F_tilde1H1 <- F_tilde1H1(get_F_tilde1,get_scH_0_1,get_scH_1_1,get_scH_1_2,env) get_H2_1 <- H2_1(get_scH_0_1,get_scH_1_1,get_scH_1_2,env) get_H2_2 <- H2_2(get_D_b,get_D_c,get_x1_x2_rho,get_x_e_rho,get_e_e_rho) get_H2_3 <- H2_3(get_E0_bar,get_x_rho) }else{ p2 <- function(z,get_F_tilde1__2,get_F_tilde2,env){ k.size <- env$k.size delta <- env$delta mu <- env$mu Sigma <- env$Sigma z.tilde <- z - mu first <- 0 second <- 0 if(k.size == 1){ first <- (F_tilde1__2_x(1,1,z.tilde+2*delta,get_F_tilde1__2,env) * dnorm(z+2*delta,mean=mu,sd=sqrt(Sigma)) - 2 * F_tilde1__2_x(1,1,z.tilde+delta,get_F_tilde1__2,env) * dnorm(z+delta,mean=mu,sd=sqrt(Sigma)) + F_tilde1__2_x(1,1,z.tilde,get_F_tilde1__2,env) * dnorm(z,mean=mu,sd=sqrt(Sigma)))/(delta)^2 first <- first/2 second <- (F_tilde2_x(1,z.tilde+delta,get_F_tilde2,env) * dnorm(z+delta,mean=mu,sd=sqrt(Sigma)) - F_tilde2_x(1,z.tilde,get_F_tilde2,env) * dnorm(z,mean=mu,sd=sqrt(Sigma)))/delta }else{ tmp1 <- matrix(0,k.size,k.size) for(l1 in 1:k.size){ for(l2 in 1:k.size){ dif1 <- numeric(k.size) dif2 <- numeric(k.size) dif1[l1] <- dif1[l1] + delta dif2[l2] <- dif2[l2] + delta tmp1[l1,l2] <- (F_tilde1__2_x(l1,l2,z.tilde+dif1+dif2,get_F_tilde1__2,env) * ft_norm(z+dif1+dif2,env) - F_tilde1__2_x(l1,l2,z.tilde+dif1,get_F_tilde1__2,env) * ft_norm(z+dif1,env) - F_tilde1__2_x(l1,l2,z.tilde+dif2,get_F_tilde1__2,env) * ft_norm(z+dif2,env) + F_tilde1__2_x(l1,l2,z.tilde,get_F_tilde1__2,env) * ft_norm(z,env))/(delta)^2 } } first <- sum(tmp1)/2 tmp2 <- double(k.size) for(l in 1:k.size){ dif <- numeric(k.size) dif[l] <- dif[l] + delta tmp2[l] <- (F_tilde2_x(l,z.tilde+dif,get_F_tilde2,env) * ft_norm(z+dif,env) - F_tilde2_x(l,z.tilde,get_F_tilde2,env) * ft_norm(z,env))/delta } second <- sum(tmp2) } result <- first - second return(result) } p2_z <- function(z){ if(k.size == 1){ zlen <- length(z) result <- c() for(i in 1:zlen){ result[i] <- p2(z[i],get_F_tilde1__2,get_F_tilde2,env) } }else{ result <- p2(z,get_F_tilde1__2,get_F_tilde2,env) } return(result) } } d2 <- d2.term() terms <- list(d0=d0, d1=d1, d2=d2) return(terms) })
/scratch/gouwar.j/cran-all/cranData/yuima/R/asymptotic_term_third.R
########################### # third expansion # ########################### #bi:r.size*division #aMat:k.size*r.size*division #Sigma:k.size*k.size #env:d.size,r.size,k.size,division,delta,state,pars,aMat,mu,Sigma, # invSigma,invY,block,my.range,Diff #first:k*k*k*t, second:k*t I_123 <- function(b1,b2,b3,env){ r.size <- env$r.size k.size <- env$k.size delta <- env$delta aMat <- env$aMat invSigma <- env$invSigma block <- env$block my.range <- env$my.range Diff <- env$Diff n1 <- length(b1) n2 <- sum(b1 == 0) n3 <- length(b2) n4 <- sum(b2 == 0) n5 <- length(b3) n6 <- sum(b3 == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) * (n5 - n6 != 0) if(n == 0){ first <- array(0,dim=c(k.size,k.size,k.size,block)) second <- matrix(0,k.size,block) return(list(first=first,second=second)) } b1a <- matrix(0,k.size,block) b2a <- matrix(0,k.size,block) b3a <- matrix(0,k.size,block) if(r.size == 1){ b1 <- matrix(b1,1,block) b2 <- matrix(b2,1,block) b3 <- matrix(b3,1,block) } for(t in 1:block){ b1a[,t] <- matrix(b1[,t],1,r.size) %*% t(matrix(aMat[,,my.range[t]],k.size,r.size)) b2a[,t] <- matrix(b2[,t],1,r.size) %*% t(matrix(aMat[,,my.range[t]],k.size,r.size)) b3a[,t] <- matrix(b3[,t],1,r.size) %*% t(matrix(aMat[,,my.range[t]],k.size,r.size)) } first <- array(0,dim=c(k.size,k.size,k.size,block)) tmp1 <- matrix(0,k.size,block) tmp2 <- array(0,dim=c(k.size,k.size,block)) tmp3 <- array(0,dim=c(k.size,k.size,k.size,block)) for(t in 2:block){ tmp1[,t] <- b3a %*% Diff[t,] * delta } for(k1 in 1:k.size){ for(k2 in 1:k.size){ for(t in 2:block){ tmp2[k1,k2,t] <- (b2a[k1,] * tmp1[k2,]) %*% Diff[t,] * delta } } } for(k1 in 1:k.size){ for(k2 in 1:k.size){ for(k3 in 1:k.size){ for(t in 2:block){ tmp3[k1,k2,k3,t] <- (b1a[k1,] * tmp2[k2,k3,]) %*% Diff[t,] * delta } } } } for(k1 in 1:k.size){ for(k2 in 1:k.size){ for(t in 1:block){ first[k1,k2,,t] <- matrix(tmp3[k1,k2,,t],1,k.size) %*% invSigma } } } for(k1 in 1:k.size){ for(k3 in 1:k.size){ for(t in 1:block){ first[k1,,k3,t] <- matrix(first[k1,,k3,t],1,k.size) %*% invSigma } } } for(k2 in 1:k.size){ for(k3 in 1:k.size){ for(t in 1:block){ first[,k2,k3,t] <- matrix(first[,k2,k3,t],1,k.size) %*% invSigma } } } second1 <- matrix(0,k.size,block) for(t in 1:block){ for(k1 in 1:k.size){ for(k2 in 1:k.size){ second1[,t] <- second1[,t] + tmp3[k1,k2,,t] * invSigma[k1,k2] } } second1[,t] <- matrix(second1[,t],1,k.size) %*% invSigma } second2 <- matrix(0,k.size,block) for(t in 1:block){ for(k1 in 1:k.size){ for(k3 in 1:k.size){ second2[,t] <- second2[,t] + tmp3[k1,,k3,t] * invSigma[k1,k3] } } second2[,t] <- matrix(second2[,t],1,k.size) %*% invSigma } second3 <- matrix(0,k.size,block) for(t in 1:block){ for(k2 in 1:k.size){ for(k3 in 1:k.size){ second3[,t] <- second3[,t] + tmp3[,k2,k3,t] * invSigma[k2,k3] } } second3[,t] <- matrix(second3[,t],1,k.size) %*% invSigma } second <- - second1 - second2 - second3 return(list(first=first,second=second)) } I_123_x <- function(x,get_I_123,env){ k.size <- env$k.size block <- env$block first <- array(get_I_123$first[,,,block],dim=c(k.size,k.size,k.size)) for(k1 in 1:k.size){ for(k2 in 1:k.size){ for(k3 in 1:k.size){ result1 <- result1 + first[k1,k2,k3] * x[k1] * x[k2] * x[k3] } } } second <- get_I_123$second[,block] result2 <- matrix(x,1,k.size) %*% matrix(second,k.size,1) result <- result1 + result2 return(result) } #first:k*k*k*k*t, second:k*k*t, third:t I_1234 <- function(b1,b2,b3,b4,env){ r.size <- env$r.size k.size <- env$k.size delta <- env$delta aMat <- env$aMat invSigma <- env$invSigma block <- env$block my.range <- env$my.range Diff <- env$Diff n1 <- length(b1) n2 <- sum(b1 == 0) n3 <- length(b2) n4 <- sum(b2 == 0) n5 <- length(b3) n6 <- sum(b3 == 0) n7 <- length(b4) n8 <- sum(b4 == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) * (n5 - n6 != 0) * (n7 - n8 != 0) if(n == 0){ first <- array(0,dim=c(k.size,k.size,k.size,k.size,block)) second <- array(0,dim=c(k.size,k.size,block)) third <- double(block) return(list(first=first,second=second,third=third)) } b1a <- matrix(0,k.size,block) b2a <- matrix(0,k.size,block) b3a <- matrix(0,k.size,block) b4a <- matrix(0,k.size,block) if(r.size == 1){ b1 <- matrix(b1,1,block) b2 <- matrix(b2,1,block) b3 <- matrix(b3,1,block) b4 <- matrix(b4,1,block) } for(t in 1:block){ b1a[,t] <- matrix(b1[,t],1,r.size) %*% t(matrix(aMat[,,my.range[t]],k.size,r.size)) b2a[,t] <- matrix(b2[,t],1,r.size) %*% t(matrix(aMat[,,my.range[t]],k.size,r.size)) b3a[,t] <- matrix(b3[,t],1,r.size) %*% t(matrix(aMat[,,my.range[t]],k.size,r.size)) b4a[,t] <- matrix(b4[,t],1,r.size) %*% t(matrix(aMat[,,my.range[t]],k.size,r.size)) } first <- array(0,dim=c(k.size,k.size,k.size,k.size,block)) tmp1 <- matrix(0,k.size,block) tmp2 <- array(0,dim=c(k.size,k.size,block)) tmp3 <- array(0,dim=c(k.size,k.size,k.size,block)) tmp4 <- array(0,dim=c(k.size,k.size,k.size,k.size,block)) for(t in 2:block){ tmp1[,t] <- b4a %*% Diff[t,] * delta } for(k1 in 1:k.size){ for(k2 in 1:k.size){ for(t in 2:block){ tmp2[k1,k2,t] <- (b3a[k1,] * tmp1[k2,]) %*% Diff[t,] * delta } } } for(k1 in 1:k.size){ for(k2 in 1:k.size){ for(k3 in 1:k.size){ for(t in 2:block){ tmp3[k1,k2,k3,t] <- (b2a[k1,] * tmp2[k2,k3,]) %*% Diff[t,] * delta } } } } for(k1 in 1:k.size){ for(k2 in 1:k.size){ for(k3 in 1:k.size){ for(k4 in 1:k.size){ for(t in 2:block){ tmp4[k1,k2,k3,k4,t] <- (b1a[k1,] * tmp3[k2,k3,k4,]) %*% Diff[t,]* delta } } } } } for(k1 in 1:k.size){ for(k2 in 1:k.size){ for(k3 in 1:k.size){ for(t in 1:block){ first[k1,k2,k3,,t] <- matrix(tmp4[k1,k2,k3,,t],1,k.size) %*% invSigma } } } } for(k1 in 1:k.size){ for(k2 in 1:k.size){ for(k4 in 1:k.size){ for(t in 1:block){ first[k1,k2,,k4,t] <- matrix(first[k1,k2,,k4,t],1,k.size) %*% invSigma } } } } for(k1 in 1:k.size){ for(k3 in 1:k.size){ for(k4 in 1:k.size){ for(t in 1:block){ first[k1,,k3,k4,t] <- matrix(first[k1,,k3,k4,t],1,k.size) %*% invSigma } } } } for(k2 in 1:k.size){ for(k3 in 1:k.size){ for(k4 in 1:k.size){ for(t in 1:block){ first[,k2,k3,k4,t] <- matrix(first[,k2,k3,k4,t],1,k.size) %*% invSigma } } } } second1 <- array(0,dim=c(k.size,k.size,block)) tmp5 <- array(0,dim=c(k.size,k.size,block)) for(t in 1:block){ for(k1 in 1:k.size){ for(k2 in 1:k.size){ tmp5[,,t] <- tmp5[,,t] + tmp4[k1,k2,,,t] * invSigma[k1,k2] } } } for(k3 in 1:k.size){ for(t in 1:block){ second1[k3,,t] <- matrix(tmp5[k3,,t],1,k.size) %*% invSigma } } for(k4 in 1:k.size){ for(t in 1:block){ second1[,k4,t] <- matrix(second1[,k4,t],1,k.size) %*% invSigma } } second2 <- array(0,dim=c(k.size,k.size,block)) tmp6 <- array(0,dim=c(k.size,k.size,block)) for(t in 1:block){ for(k1 in 1:k.size){ for(k3 in 1:k.size){ tmp6[,,t] <- tmp6[,,t] + tmp4[k1,,k3,,t] * invSigma[k1,k3] } } } for(k2 in 1:k.size){ for(t in 1:block){ second2[k2,,t] <- matrix(tmp6[k2,,t],1,k.size) %*% invSigma } } for(k4 in 1:k.size){ for(t in 1:block){ second2[,k4,t] <- matrix(second2[,k4,t],1,k.size) %*% invSigma } } second3 <- array(0,dim=c(k.size,k.size,block)) tmp7 <- array(0,dim=c(k.size,k.size,block)) for(t in 1:block){ for(k1 in 1:k.size){ for(k4 in 1:k.size){ tmp7[,,t] <- tmp7[,,t] + tmp4[k1,,,k4,t] * invSigma[k1,k4] } } } for(k2 in 1:k.size){ for(t in 1:block){ second3[k2,,t] <- matrix(tmp7[k2,,t],1,k.size) %*% invSigma } } for(k3 in 1:k.size){ for(t in 1:block){ second3[,k3,t] <- matrix(second3[,k3,t],1,k.size) %*% invSigma } } second4 <- array(0,dim=c(k.size,k.size,block)) for(t in 1:block){ for(k2 in 1:k.size){ for(k3 in 1:k.size){ second4[,,t] <- second4[,,t] + tmp4[,k2,k3,,t] * invSigma[k2,k3] } } } for(k1 in 1:k.size){ for(t in 1:block){ second4[k1,,t] <- matrix(second4[k1,,t],1,k.size) %*% invSigma } } for(k4 in 1:k.size){ for(t in 1:block){ second4[,k4,t] <- matrix(second4[,k4,t],1,k.size) %*% invSigma } } second5 <- array(0,dim=c(k.size,k.size,block)) for(t in 1:block){ for(k2 in 1:k.size){ for(k4 in 1:k.size){ second5[,,t] <- second5[,,t] + tmp4[,k2,,k4,t] * invSigma[k2,k4] } } } for(k1 in 1:k.size){ for(t in 1:block){ second5[k1,,t] <- matrix(second5[k1,,t],1,k.size) %*% invSigma } } for(k3 in 1:k.size){ for(t in 1:block){ second5[,k3,t] <- matrix(second5[,k3,t],1,k.size) %*% invSigma } } second6 <- array(0,dim=c(k.size,k.size,block)) for(t in 1:block){ for(k3 in 1:k.size){ for(k4 in 1:k.size){ second6[,,t] <- second6[,,t] + tmp4[,,k3,k4,t] * invSigma[k3,k4] } } } for(k1 in 1:k.size){ for(t in 1:block){ second6[k1,,t] <- matrix(second6[k1,,t],1,k.size) %*% invSigma } } for(k2 in 1:k.size){ for(t in 1:block){ second6[,k2,t] <- matrix(second6[,k2,t],1,k.size) %*% invSigma } } second <- - second1 - second2 - second3 - second4 - second5 - second6 third1 <- double(block) for(t in 1:block){ for(k3 in 1:k.size){ for(k4 in 1:k.size){ third1[t] <- third1[t] + tmp5[k3,k4,t] * invSigma[k3,k4] } } } third2 <- double(block) for(t in 1:block){ for(k2 in 1:k.size){ for(k4 in 1:k.size){ third2[t] <- third2[t] + tmp6[k2,k4,t] * invSigma[k2,k4] } } } third3 <- double(block) d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range for(t in 1:block){ for(k2 in 1:k.size){ for(k3 in 1:k.size){ third3[t] <- third3[t] + tmp6[k2,k3,t] * invSigma[k2,k3] } } } third <- third1 + third2 + third3 return(list(first=first,second=second,third=third)) } I_1234_x <- function(x,get_I_1234,env){ k.size <- env$k.size block <- env$block first <- array(get_I_1234$first[,,,,block], dim=c(k.size,k.size,k.size,k.size)) for(k1 in 1:k.size){ for(k2 in 1:k.size){ for(k3 in 1:k.size){ for(k4 in 1:k.size){ result1 <- result1 + first[k1,k2,k3,k4] * x[k1] * x[k2] * x[k3] * x[k4] } } } } second <- matrix(get_I_1234$second[,,block],k.size,k.size) result2 <- t(matrix(x,k.size,1)) %*% second %*% matrix(x,k.size,1) third <- get_I_1234$third[block] result <- result1 + result2 + third return(result) } b1b2 <- function(b1,b2,env){ r.size <- env$r.size block <- env$block result <- double(block) n1 <- length(b1) n2 <- sum(b1 == 0) n3 <- length(b2) n4 <- sum(b2 == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) if(n == 0){ return(result) } if(r.size == 1){ b1 <- matrix(b1,1,block) b2 <- matrix(b2,1,block) } for(t in 1:block){ result[t] <- matrix(b1[,t],1,r.size) %*% matrix(b2[,t],r.size,1) } return(result) } b1_b2 <- function(b1,b2,env){ delta <- env$delta block <- env$block Diff <- env$Diff tmp <- b1b2(b1,b2,env) result <- double(block) for(t in 1:block){ result[t] <- tmp %*% Diff[t,] * delta } return(result) } I0 <- function(f,env){ delta <- env$delta block <- env$block Diff <- env$Diff result <- double(block) n1 <- length(f) n2 <- sum(f == 0) n <- n1 - n2 if(n == 0){ return(result) } for(t in 1:block){ result[t] <- f %*% Diff[t,] * delta } return(result) } #k*t I_1 <- function(b1,env){ r.size <- env$r.size k.size <- env$k.size delta <- env$delta aMat <- env$aMat invSigma <- env$invSigma block <- env$block my.range <- env$my.range Diff <- env$Diff result <- matrix(0,k.size,block) n1 <- length(b1) n2 <- sum(b1 == 0) if(n1 == n2){ return(result) } b1a <- matrix(0,k.size,block) if(r.size == 1){ b1 <- matrix(b1,1,block) } # b1 <- matrix(b1, ncol=block) # FIXME: should be a matrix with block-columns but it is a scalar for(t in 1:block){ # print(str(b1)) #print(t) #print(block) #print(str(b1[,t])) #print(r.size) b1a[,t] <- matrix(b1[,t],1,r.size) %*% t(matrix(aMat[,,my.range[t]],k.size,r.size)) } for(t in 2:block){ result[,t] <- t(invSigma) %*% b1a %*% Diff[t,] * delta } return(result) } I_1_x <- function(x,get_I_1,env){ k.size <- env$k.size block <- env$block tmp <- get_I_1[,block] result <- matrix(tmp,1,k.size) %*% matrix(x,k.size,1) return(result) } #first:k*k*t, second:t I_12 <- function(b1,b2,env){ r.size <- env$r.size k.size <- env$k.size delta <- env$delta aMat <- env$aMat Sigma <- env$Sigma invSigma <- env$invSigma block <- env$block my.range <- env$my.range Diff <- env$Diff n1 <- length(b1) n2 <- sum(b1 == 0) n3 <- length(b2) n4 <- sum(b2 == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) if(n == 0){ first <- array(0,dim=c(k.size,k.size,block)) second <- double(block) return(list(first=first,second=second)) } b1a <- matrix(0,k.size,block) b2a <- matrix(0,k.size,block) if(r.size == 1){ b1 <- matrix(b1,1,block) b2 <- matrix(b2,1,block) } for(t in 1:block){ b1a[,t] <- matrix(b1[,t],1,r.size) %*% t(matrix(aMat[,,my.range[t]],k.size,r.size)) b2a[,t] <- matrix(b2[,t],1,r.size) %*% t(matrix(aMat[,,my.range[t]],k.size,r.size)) } first <- array(0,dim=c(k.size,k.size,block)) tmp1 <- matrix(0,k.size,block) tmp2 <- array(0,dim=c(k.size,k.size,block)) for(t in 2:block){ tmp1[,t] <- b2a %*% Diff[t,] * delta } for(k1 in 1:k.size){ for(k2 in 1:k.size){ for(t in 2:block){ tmp2[k1,k2,t] <- (b1a[k1,] * tmp1[k2,]) %*% Diff[t,] * delta } } } for(k1 in 1:k.size){ for(t in 1:block){ first[k1,,t] <- matrix(tmp2[k1,,t],1,k.size) %*% invSigma } } for(k2 in 1:k.size){ for(t in 1:block){ first[,k2,t] <- matrix(first[,k2,t],1,k.size) %*% invSigma } } second <- double(block) for(t in 1:block){ for(k1 in 1:k.size){ for(k2 in 1:k.size){ second[t] <- second[t] + tmp2[k1,k2,t] * invSigma[k1,k2] } } } second <- - second return(list(first=first,second=second)) } I_12_x <- function(x,get_I_12,env){ k.size <- env$k.size block <- env$block first <- matrix(get_I_12$first[,,block],k.size,k.size) second <- get_I_12$second[block] result <- matrix(x,1,k.size) %*% first %*% matrix(x,k.size,1) + second return(result) } #first:k*k*t, second:t I_1_2 <- function(b1,b2,env){ k.size <- env$k.size block <- env$block n1 <- length(b1) n2 <- sum(b1 == 0) n3 <- length(b2) n4 <- sum(b2 == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) if(n == 0){ first <- array(0,dim=c(k.size,k.size,block)) second <- double(block) return(list(first=first,second=second)) } first.tmp <- I_12(b1,b2,env) second.tmp <- I_12(b2,b1,env) third.tmp <- b1_b2(b1,b2,env) first <- first.tmp$first + second.tmp$first second <- first.tmp$second + second.tmp$second + third.tmp return(list(first=first,second=second)) } I_1_2_x <- function(x,get_I_1_2,env){ result <- I_12_x(x,get_I_1_2,env) return(result) } #first:k*k*t, second:t I_1_23 <- function(b1,b2,b3,env){ r.size <- env$r.size k.size <- env$k.size block <- env$block my.range <- env$my.range Diff <- env$Diff n1 <- length(b1) n2 <- sum(b1 == 0) n3 <- length(b2) n4 <- sum(b2 == 0) n5 <- length(b3) n6 <- sum(b3 == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) * (n5 - n6 != 0) if(n == 0){ first <- array(0,dim=c(k.size,k.size,k.size,block)) second <- matrix(0,k.size,block) return(list(first=first,second=second)) } first.tmp <- I_123(b1,b2,b3,env) second.tmp <- I_123(b2,b1,b3,env) third.tmp <- I_123(b2,b3,b1,env) tmp1 <- b1_b2(b1,b3,env) tmp2 <- matrix(0,r.size,block) if(r.size == 1){ b2 <- matrix(b2,1,block) } for(t in 1:block){ tmp2[,t] <- tmp1[t] * b2[,t] } fourth.tmp <- I_1(tmp2,env) tmp3 <- b1b2(b1,b2,env) tmp4 <- I_1(b3,env) tmp5 <- matrix(0,k.size,block) for(t in 1:block){ tmp5[,t] <- tmp3[t] * tmp4[,t] } fifth.tmp <- matrix(0,k.size,block) for(k in 1:k.size){ fifth.tmp[k,] <- I0(tmp5[k,],env) } first <- first.tmp$first + second.tmp$first + third.tmp$first second <- first.tmp$second + second.tmp$second + third.tmp$second + fourth.tmp + fifth.tmp return(list(first=first,second=second)) } I_1_23_x <- function(x,get_I_1_23,env){ result <- I_123_x(x,get_I_1_23,env) return(result) } #first:k*k*t, second:t I_12_3 <- function(b1,b2,b3,env){ r.size <- env$r.size k.size <- env$k.size block <- env$block n1 <- length(b1) n2 <- sum(b1 == 0) n3 <- length(b2) n4 <- sum(b2 == 0) n5 <- length(b3) n6 <- sum(b3 == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) * (n5 - n6 != 0) if(n == 0){ first <- array(0,dim=c(k.size,k.size,k.size,block)) second <- matrix(0,k.size,block) return(list(first=first,second=second)) } first.tmp <- I_123(b1,b2,b3,env) second.tmp <- I_123(b1,b3,b2,env) tmp1 <- b1_b2(b2,b3,env) tmp2 <- matrix(0,r.size,block) if(r.size == 1){ b1 <- matrix(b1,1,block) } for(t in 1:block){ tmp2[,t] <- tmp1[t] * b1[,t] } third.tmp <- I_1(tmp2,env) first <- first.tmp$first + second.tmp$first second <- first.tmp$second + second.tmp$second + third.tmp return(list(first=first,second=second)) } I_12_3_x <- function(x,get_I_12_3,env){ result <- I_123_x(x,get_I_12_3,env) return(result) } #first:k*k*t, second:t I_1_2_3 <- function(b1,b2,b3,env){ k.size <- env$k.size block <- env$block n1 <- length(b1) n2 <- sum(b1 == 0) n3 <- length(b2) n4 <- sum(b2 == 0) n5 <- length(b3) n6 <- sum(b3 == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) * (n5 - n6 != 0) if(n == 0){ first <- array(0,dim=c(k.size,k.size,k.size,block)) second <- matrix(0,k.size,block) return(list(first=first,second=second)) } first.tmp <- I_123(b1,b2,b3,env) second.tmp <- I_123(b2,b1,b3,env) third.tmp <- I_123(b2,b3,b1,env) fourth.tmp <- I_123(b1,b3,b2,env) fifth.tmp <- I_123(b3,b1,b2,env) sixth.tmp <- I_123(b3,b2,b1,env) tmp1 <- b1_b2(b1,b3,env) tmp2 <- I_1(b2,env) seventh.tmp <- matrix(0,k.size,block) for(t in 1:block){ seventh.tmp[,t] <- tmp1[t] * tmp2[,t] } tmp3 <- b1_b2(b1,b2,env) tmp4 <- I_1(b3,env) eighth.tmp <- matrix(0,k.size,block) for(t in 1:block){ eighth.tmp[,t] <- tmp3[t] * tmp4[,t] } tmp5 <- b1_b2(b2,b3,env) tmp6 <- I_1(b1,env) ninth.tmp <- matrix(0,k.size,block) for(t in 1:block){ ninth.tmp[,t] <- tmp5[t] * tmp6[,t] } first <- first.tmp$first + second.tmp$first + third.tmp$first + fourth.tmp$first + fifth.tmp$first + sixth.tmp$first second <- first.tmp$second + second.tmp$second + third.tmp$second + fourth.tmp$second + fifth.tmp$second + sixth.tmp$second + seventh.tmp + eighth.tmp + ninth.tmp return(list(first=first,second=second)) } I_1_2_3_x <- function(x,get_I_1_2_3,env){ result <- I_123_x(x,get_I_1_2_3,env) return(result) } #first:k*k*k*k*t, second:k*k*t, third:t I_12_34 <- function(b1,b2,b3,b4,env){ r.size <- env$r.size k.size <- env$k.size block <- env$block n1 <- length(b1) n2 <- sum(b1 == 0) n3 <- length(b2) n4 <- sum(b2 == 0) n5 <- length(b3) n6 <- sum(b3 == 0) n7 <- length(b4) n8 <- sum(b4 == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) * (n5 - n6 != 0) * (n7 - n8 != 0) if(n == 0){ first <- array(0,dim=c(k.size,k.size,k.size,k.size,block)) second <- array(0,dim=c(k.size,k.size,block)) third <- double(block) return(list(first=first,second=second,third=third)) } first.tmp <- I_1234(b1,b2,b3,b4,env) second.tmp <- I_1234(b1,b3,b4,b2,env) third.tmp <- I_1234(b1,b3,b2,b4,env) tmp1 <- b1_b2(b2,b4,env) tmp2 <- matrix(0,r.size,block) if(r.size == 1){ b1 <- matrix(b1,1,block) b2 <- matrix(b2,1,block) b3 <- matrix(b3,1,block) b4 <- matrix(b4,1,block) } for(t in 1:block){ tmp2[,t] <- tmp1[t] * b3[,t] } fourth.tmp <- I_12(b1,tmp2,env) tmp3 <- b1_b2(b2,b3,env) tmp4 <- matrix(0,r.size,block) for(t in 1:block){ tmp4[,t] <- tmp3[t] * b1[,t] } fifth.tmp <- I_12(tmp4,b4,env) tmp5 <- matrix(0,r.size,block) for(t in 1:block){ tmp5[,t] <- tmp3[t] * b4[,t] } sixth.tmp <- I_12(b1,tmp5,env) seventh.tmp <- I_1234(b3,b4,b1,b2,env) eighth.tmp <- I_1234(b3,b1,b2,b4,env) ninth.tmp <- I_1234(b3,b1,b4,b2,env) tmp6 <- b1_b2(b4,b2,env) tmp7 <- matrix(0,r.size,block) for(t in 1:block){ tmp7[,t] <- tmp6[t] * b1[,t] } tenth.tmp <- I_12(b3,tmp7,env) tmp8 <- b1_b2(b4,b1,env) tmp9 <- matrix(0,r.size,block) for(t in 1:block){ tmp9[,t] <- tmp8[t] * b3[,t] } eleventh.tmp <- I_12(tmp9,b2,env) tmp10 <- matrix(0,r.size,block) for(t in 1:block){ tmp10[,t] <- tmp8[t] * b2[,t] } twelfth.tmp <- I_12(b3,tmp10,env) tmp11 <- b1_b2(b1,b3,env) tmp12 <- I_12(b2,b4,env) thirteenth.tmp <- tmp12 for(t in 1:block){ thirteenth.tmp$first[,,t] <- tmp11[t] * tmp12$first[,,t] thirteenth.tmp$second[t] <- tmp11[t] * tmp12$second[t] } tmp13 <- matrix(0,r.size,block) for(t in 1:block){ tmp13[,t] <- tmp11[t] * b2[,t] } fourteenth.tmp <- I_12(tmp13,b4,env) tmp14 <- I_12(b4,b2,env) fifteenth.tmp <- tmp14 for(t in 1:block){ fifteenth.tmp$first[,,t] <- tmp11[t] * tmp14$first[,,t] fifteenth.tmp$second[t] <- tmp11[t] * tmp14$second[t] } tmp15 <- matrix(0,r.size,block) for(t in 1:block){ tmp15[,t] <- tmp11[t] * b4[,t] } sixteenth.tmp <- I_12(tmp15,b2,env) tmp16 <- b1_b2(b4,b2,env) tmp17 <- matrix(0,r.size,block) for(t in 1:block){ tmp17[,t] <- tmp16[t] * b3[,t] } tmp18 <- b1b2(b1,tmp17,env) seventeenth.tmp <- I0(tmp18,env) first <- first.tmp$first + second.tmp$first + third.tmp$first + seventh.tmp$first + eighth.tmp$first + ninth.tmp$first second <- first.tmp$second + second.tmp$second + third.tmp$second + fourth.tmp$first + fifth.tmp$first - sixth.tmp$first + seventh.tmp$second + eighth.tmp$second + ninth.tmp$second + tenth.tmp$first + eleventh.tmp$first - twelfth.tmp$first + thirteenth.tmp$first - fourteenth.tmp$first + fifteenth.tmp$first - sixteenth.tmp$first third <- first.tmp$third + second.tmp$third + third.tmp$third + fourth.tmp$second + fifth.tmp$second - sixth.tmp$second + seventh.tmp$third + eighth.tmp$third + ninth.tmp$third + tenth.tmp$second + eleventh.tmp$second - twelfth.tmp$second + thirteenth.tmp$second - fourteenth.tmp$second + fifteenth.tmp$second - sixteenth.tmp$second + seventeenth.tmp return(list(first=first,second=second,third=third)) } I_12_34_x <- function(x,get_I_12_34,env){ result <- I_1234_x(x,get_I_12_34,env) return(result) } #first:k*k*k*k*t, second:k*k*t, third:t I_1_2_34 <- function(b1,b2,b3,b4,env){ division <- env$division first.tmp <- I_12_34(b1,b2,b3,b4,env) second.tmp <- I_12_34(b2,b1,b3,b4,env) tmp1 <- b1_b2(b1,b2,env) tmp2 <- I_12(b3,b4,env) third.tmp <- tmp2 for(t in 1:division){ third.tmp$first[,,t] <- tmp1[t] * tmp2$first[,,t] third.tmp$second[t] <- tmp1[t] * tmp2$second[t] } first <- first.tmp$first + second.tmp$first second <- first.tmp$second + second.tmp$second + third.tmp$first third <- first.tmp$third + second.tmp$third + third.tmp$second return(list(first=first,second=second,third=third)) } I_1_2_34_x <- function(x,get_I_1_2_34,env){ result <- I_1234_x(x,get_I_1_2_34,env) return(result) } I_1_2_3_4 <- function(b1,b2,b3,b4){ } ##p16 Lemma3 I0_a <- function(b1,c1,env){ r.size <- env$r.size block <- env$block first.coef <- I0(c1,env) first <- b1 if(r.size == 1){ b1 <- matrix(b1,1,block) } second <- matrix(0,r.size,block) for(r in 1:r.size){ second[r,] <- first.coef * b1[r,] } return(list(first.coef=first.coef,first=first,second=second)) } I0_b <- function(b1,b2,c1,env){ r.size <- env$r.size block <- env$block first.coef <- I0(c1,env) first <- list() first[[1]] <- b1 first[[2]] <- b2 second <- list() second[[1]] <- matrix(0,r.size,block) if(r.size == 1){ b1 <- matrix(b1,1,block) } for(r in 1:r.size){ second[[1]][r,] <- first.coef * b1[r,] } second[[2]] <- b2 return(list(first.coef=first.coef,first=first,second=second)) } I0_c <- function(b1,b2,c1,c2,env){ r.size <- env$r.size block <- env$block tmp1 <- I0(c2,env) tmp2 <- c1 * tmp1 first.coef <- I0(tmp2,env) first <- list() first[[1]] <- b1 first[[2]] <- b2 second <- list() second[[1]] <- matrix(0,r.size,block) if(r.size == 1){ b1 <- matrix(b1,1,block) } for(r in 1:r.size){ second[[1]][r,] <- first.coef * b1[r,] } second[[2]] <- b2 third.coef <- I0(c1,env) third <- list() third[[1]] <- matrix(0,r.size,block) for(r in 1:r.size){ third[[1]][r,] <- tmp1 * b1[r,] } third[[2]] <- b2 fourth <- list() fourth[[1]] <- matrix(0,r.size,block) for(r in 1:r.size){ fourth[[1]][r,] <- third.coef * tmp1 * b1[r,] } fourth[[2]] <- b2 return(list(first.coef=first.coef,first=first,second=second, third.coef=third.coef,third=third,fourth=fourth)) } #d*t Y_e_V0 <- function(X.t0,de.drift,env){ d.size <- env$d.size state <- env$state pars <- env$pars invY <- env$invY block <- env$block my.range <- env$my.range result <- matrix(0,d.size,block) tmp <- c() assign(pars[1],0) for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(d in 1:d.size){ tmp[d] <- eval(de.drift[[d]]) } result[,t] <- invY[,,t] %*% tmp } return(result) } #d*r*t Y_e_V <- function(X.t0,de.diffusion,env){ d.size <- env$d.size r.size <- env$r.size state <- env$state pars <- env$pars invY <- env$invY block <- env$block my.range <- env$my.range result <- array(0,dim=c(d.size,r.size,block)) tmp <- matrix(0,d.size,r.size) assign(pars[1],0) for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(i in 1:d.size){ for(r in 1:r.size){ tmp[i,r] <- eval(de.diffusion[[i]][[r]]) } } result[,,t] <- invY[,,t] %*% tmp } return(result) } #d*t Y_D <- function(X.t0,tmpY,get_Y_e_V0,env){ d.size <- env$d.size delta <- env$delta block <- env$block Diff <- env$Diff result <- matrix(0,d.size,block) for(i in 1:d.size){ for(t in 2:block){ result[i,] <- get_Y_e_V0[i,] %*% Diff[t,] * delta } } for(t in 2:block){ result[,t] <- tmpY[,,t] %*% result[,t] } return(result) } #d*d*d*t Y_x1_x2_V0 <- function(X.t0,dxdx.drift,env){ d.size <- env$d.size state <- env$state pars <- env$pars invY <- env$invY block <- env$block my.range <- env$my.range result <- array(0,dim=c(d.size,d.size,d.size,block)) tmp <- c() assign(pars[1],0) for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp.drift <- dxdx.drift[[i1]][[i2]] for(d in 1:d.size){ tmp[d] <- eval(tmp.drift[[d]]) } result[i1,i2,,t] <- invY[,,t] %*% tmp } } } return(result) } #d*d*d*r*t Y_x1_x2_V <- function(X.t0,dxdx.diffusion,env){ d.size <- env$d.size r.size <- env$r.size state <- env$state pars <- env$pars invY <- env$invY block <- env$block my.range <- env$my.range result <- array(0,dim=c(d.size,d.size,d.size,r.size,block)) tmp <- matrix(0,d.size,r.size) assign(pars[1],0) for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp.diffusion <- dxdx.diffusion[[i1]][[i2]] for(i in 1:d.size){ for(r in 1:r.size){ tmp[i,r] <- eval(tmp.diffusion[[i]][[r]]) } } result[i1,i2,,,t] <- invY[,,t] %*% tmp } } } return(result) } #d*d*t Y_x_e_V0 <- function(X.t0,dxde.drift,env){ d.size <- env$d.size state <- env$state pars <- env$pars invY <- env$invY block <- env$block my.range <- env$my.range result <- array(0,dim=c(d.size,d.size,block)) tmp <- c() assign(pars[1],0) for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(i1 in 1:d.size){ tmp.drift <- dxde.drift[[i1]] for(d in 1:d.size){ tmp[d] <- eval(tmp.drift[[d]]) } result[i1,,t] <- invY[,,t] %*% tmp } } return(result) } #d*d*r*t Y_x_e_V <- function(X.t0,dxde.diffusion,env){ d.size <- env$d.size r.size <- env$r.size state <- env$state pars <- env$pars invY <- env$invY block <- env$block my.range <- env$my.range result <- array(0,dim=c(d.size,d.size,r.size,block)) tmp <- matrix(0,d.size,r.size) assign(pars[1],0) for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(i1 in 1:d.size){ tmp.diffusion <- dxde.diffusion[[i1]] for(i in 1:d.size){ for(r in 1:r.size){ tmp[i,r] <- eval(tmp.diffusion[[i]][[r]]) } } result[i1,,,t] <- invY[,,t] %*% tmp } } return(result) } #d*t Y_e_e_V0 <- function(X.t0,dede.drift,env){ d.size <- env$d.size state <- env$state pars <- env$pars invY <- env$invY block <- env$block my.range <- env$my.range result <- matrix(0,d.size,block) tmp <- c() assign(pars[1],0) for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(d in 1:d.size){ tmp[d] <- eval(dede.drift[[d]]) } result[,t] <- invY[,,t] %*% tmp } return(result) } #d*r*t Y_e_e_V <- function(X.t0,dede.diffusion,env){ d.size <- env$d.size r.size <- env$r.size state <- env$state pars <- env$pars invY <- env$invY block <- env$block my.range <- env$my.range result <- array(0,dim=c(d.size,r.size,block)) tmp <- matrix(0,d.size,r.size) assign(pars[1],0) for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(i in 1:d.size){ for(r in 1:r.size){ tmp[i,r] <- eval(dede.diffusion[[i]][[r]]) } } result[,,t] <- invY[,,t] %*% tmp } return(result) } #d*d*d*d*t Y_x1_x2_x3_V0 <- function(X.t0,dxdxdx.drift,env){ d.size <- env$d.size state <- env$state pars <- env$pars invY <- env$invY block <- env$block my.range <- env$my.range result <- array(0,dim=c(d.size,d.size,d.size,d.size,block)) tmp <- c() assign(pars[1],0) for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(i3 in 1:d.size){ tmp.drift <- dxdxdx.drift[[i1]][[i2]][[i3]] for(d in 1:d.size){ tmp[d] <- eval(tmp.drift[[d]]) } result[i1,i2,i3,,t] <- invY[,,t] %*% tmp } } } } return(result) } #d*d*d*t Y_x1_x2_e_V0 <- function(X.t0,dxdxde.drift,env){ d.size <- env$d.size state <- env$state pars <- env$pars invY <- env$invY block <- env$block my.range <- env$my.range result <- array(0,dim=c(d.size,d.size,d.size,block)) tmp <- c() assign(pars[1],0) for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp.drift <- dxdxde.drift[[i1]][[i2]] for(d in 1:d.size){ tmp[d] <- eval(tmp.drift[[d]]) } result[i1,i2,,t] <- invY[,,t] %*% tmp } } } return(result) } #d*d*d*r*t Y_x1_x2_e_V <- function(X.t0,dxdxde.diffusion,env){ d.size <- env$d.size r.size <- env$r.size state <- env$state pars <- env$pars invY <- env$invY block <- env$block my.range <- env$my.range result <- array(0,dim=c(d.size,d.size,d.size,r.size,block)) tmp <- matrix(0,d.size,r.size) assign(pars[1],0) for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp.diffusion <- dxdxde.diffusion[[i1]][[i2]] for(i in 1:d.size){ for(r in 1:r.size){ tmp[i,r] <- eval(tmp.diffusion[[i]][[r]]) } } result[i1,i2,,,t] <- invY[,,t] %*% tmp } } } return(result) } #d*d*t Y_x_e_e_V0 <- function(X.t0,dxdede.drift,env){ d.size <- env$d.size state <- env$state pars <- env$pars invY <- env$invY block <- env$block my.range <- env$my.range result <- array(0,dim=c(d.size,d.size,block)) tmp <- c() assign(pars[1],0) for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(i1 in 1:d.size){ tmp.drift <- dxdede.drift[[i1]] for(d in 1:d.size){ tmp[d] <- eval(tmp.drift[[d]]) } result[i1,,t] <- invY[,,t] %*% tmp } } return(result) } #d*d*r*t Y_x_e_e_V <- function(X.t0,dxdede.diffusion,env){ d.size <- env$d.size r.size <- env$r.size state <- env$state pars <- env$pars invY <- env$invY block <- env$block my.range <- env$my.range result <- array(0,dim=c(d.size,d.size,r.size,block)) tmp <- matrix(0,d.size,r.size) assign(pars[1],0) for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(i1 in 1:d.size){ tmp.diffusion <- dxdede.diffusion[[i1]] for(i in 1:d.size){ for(r in 1:r.size){ tmp[i,r] <- eval(tmp.diffusion[[i]][[r]]) } } result[i1,,,t] <- invY[,,t] %*% tmp } } return(result) } #d*t Y_e_e_e_V0 <- function(X.t0,dedede.drift,env){ d.size <- env$d.size state <- env$state pars <- env$pars invY <- env$invY block <- env$block my.range <- env$my.range result <- matrix(0,d.size,block) tmp <- c() assign(pars[1],0) for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(d in 1:d.size){ tmp[d] <- eval(dedede.drift[[d]]) } result[,t] <- invY[,,t] %*% tmp } return(result) } #d*r*t Y_e_e_e_V <- function(X.t0,dedede.diffusion,env){ d.size <- env$d.size r.size <- env$r.size state <- env$state pars <- env$pars invY <- env$invY block <- env$block my.range <- env$my.range result <- array(0,dim=c(d.size,r.size,block)) tmp <- matrix(0,d.size,r.size) assign(pars[1],0) for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(i in 1:d.size){ for(r in 1:r.size){ tmp[i,r] <- eval(dedede.diffusion[[i]][[r]]) } } result[,,t] <- invY[,,t] %*% tmp } return(result) } D0_t <- function(tmpY, get_Y_D, get_Y_e_V){ first <- get_Y_D second.coef <- tmpY second <- get_Y_e_V return(list(first=first,second.coef=second.coef,second=second)) } #i*t e_t <- function(tmpY, get_Y_e_V, get_Y_D, get_Y_x1_x2_V0, get_Y_x_e_V0, get_Y_e_e_V0, env){ d.size <- env$d.size delta <- env$delta block <- env$block Diff <- env$Diff result <- matrix(0,d.size,block) first <- matrix(0,d.size,block) second <- matrix(0,d.size,block) third <- matrix(0,d.size,block) fourth <- matrix(0,d.size,block) first.tmp <- array(0,dim=c(d.size,d.size,block)) second.tmp <- array(0,dim=c(d.size,d.size,block)) third.tmp <- array(0,dim=c(d.size,d.size,block)) for(i in 1:d.size){ for(j in 1:d.size){ for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(j1 in 1:d.size){ for(j2 in 1:d.size){ tmp1 <- b1_b2(get_Y_e_V[j1,,],get_Y_e_V[j2,,],env) tmp2 <- double(block) for(t in 2:block){ tmp2[t] <- (get_Y_x1_x2_V0[i1,i2,j,] * tmpY[i1,j1,] * tmpY[i2,j2,] * tmp1) %*% Diff[t,] * delta } first.tmp[i,j,] <- first.tmp[i,j,] + tmp2 } } tmp3 <- double(block) for(t in 2:block){ tmp3[t] <- (get_Y_x1_x2_V0[i1,i2,j,] * get_Y_D[i1,] * get_Y_D[i2,]) %*% Diff[t,] * delta } second.tmp[i,j,] <- second.tmp[i,j,] + tmp3 } tmp4 <- double(block) for(t in 2:block){ tmp4[t] <- (get_Y_x_e_V0[i1,j,] * get_Y_D[i1,]) %*% Diff[t,] * delta } third.tmp[i,j,] <- third.tmp[i,j,] + tmp4 } tmp5 <- double(block) for(t in 2:block){ tmp5[t] <- get_Y_e_e_V0[j,] %*% Diff[t,] * delta } first[i,] <- first[i,] + first.tmp[i,j,] * tmpY[i,j,] second[i,] <- second[i,] + second.tmp[i,j,] * tmpY[i,j,] third[i,] <- third[i,] + 2 * third.tmp[i,j,] * tmpY[i,j,] fourth[i,] <- fourth[i,] + tmp5 * tmpY[i,j,] } } result <- first + second + third + fourth return(result) } #j1*j*s U_t <- function(tmpY, get_Y_D, get_Y_x1_x2_V0, get_Y_x_e_V0, env){ d.size <- env$d.size block <- env$block result <- array(0,dim=c(d.size,d.size,block)) first <- array(0,dim=c(d.size,d.size,block)) second <- array(0,dim=c(d.size,d.size,block)) for(j1 in 1:d.size){ for(j in 1:d.size){ for(s in 1:block){ for(i1 in 1:d.size){ tmp.Y <- as.matrix(tmpY[,,s]) for(i2 in 1:d.size){ first[j1,j,s] <- first[j1,j,s] + get_Y_x1_x2_V0[i1,i2,j,s] * get_Y_D[i1,s] * tmp.Y[i2,j1] } second[j1,j,s] <- second[j1,j,s] + get_Y_x_e_V0[i1,j,s] * tmp.Y[i1,j1] } } } } result <- first + second return(result) } #j1*j*r*t U_hat_t <- function(tmpY, get_Y_e_V, get_Y_D, get_Y_x1_x2_V0, get_Y_x_e_V, env){ d.size <- env$d.size r.size <- env$r.size block <- env$block result <- array(0,dim=c(d.size,d.size,r.size,block)) first <- array(0,dim=c(d.size,d.size,r.size,block)) second <- array(0,dim=c(d.size,d.size,r.size,block)) for(j1 in 1:d.size){ for(j in 1:d.size){ for(s in 1:block){ tmp.Y <- as.matrix(tmpY[,,s]) for(i1 in 1:d.size){ first[j1,j,,s] <- first[j1,j,,s] + get_Y_x_e_V[i1,j,,s] * tmp.Y[i1,j1] } } } } for(j1 in 1:d.size){ for(j in 1:d.size){ for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(j2 in 1:d.size){ tmp1 <- get_Y_x1_x2_V0[i1,i2,j,] * tmpY[i1,j1,] * tmpY[i2,j2,] tmp2 <- I0(tmp1,env) tmp3 <- matrix(0,r.size,block) for(r in 1:r.size){ tmp3[r,] <- tmp2 * get_Y_e_V[j2,r,] } second[j1,j,,] <- second[j1,j,,] + tmp3 } } } } } result <- first - second return(result) } E0_t <- function(tmpY, get_Y_e_V, get_Y_x1_x2_V0, get_Y_e_e_V, get_e_t, get_U_t, get_U_hat_t, env){ d.size <- env$d.size r.size <- env$r.size block <- env$block first <- get_e_t second.coef <- array(0,dim=c(d.size,d.size,d.size,block)) # i, j1, j2, t for(i in 1:d.size){ for(j1 in 1:d.size){ for(j2 in 1:d.size){ for(j in 1:d.size){ tmp2 <- double(block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp1 <- get_Y_x1_x2_V0[i1,i2,j,] * tmpY[i1,j1,] * tmpY[i2,j2,] tmp2 <- tmp2 + tmp1 } } second.coef[i,j1,j2,] <- second.coef[i,j1,j2,] + 2 * tmpY[i,j,] * I0(tmp2,env) } } } } second <- list() second[[1]] <- get_Y_e_V second[[2]] <- get_Y_e_V third.coef <- array(0,dim=c(d.size,d.size,block)) # i, j1, t for(j1 in 1:d.size){ for(j in 1:d.size){ tmp3 <- I0(get_U_t[j1,j,],env) for(i in 1:d.size){ third.coef[i,j1,] <- third.coef[i,j1,] + 2 * tmpY[i,j,] * tmp3 } } } third <- get_Y_e_V fourth.coef <- - 2 * tmpY fourth <- array(0,dim=c(d.size,r.size,block)) for(j in 1:d.size){ for(j1 in 1:d.size){ tmp4 <- I0(get_U_t[j1,j,],env) for(r in 1:r.size){ fourth[j,r,] <- fourth[j,r,] + tmp4 * get_Y_e_V[j1,r,] } } } fifth.coef <- 2 * tmpY fifth <- list() fifth[[1]] <- get_U_hat_t fifth[[2]] <- get_Y_e_V sixth.coef <- tmpY sixth <- get_Y_e_e_V return(list(first=first,second.coef=second.coef,second=second, third.coef=third.coef,third=third, fourth.coef=fourth.coef,fourth=fourth, fifth.coef=fifth.coef,fifth=fifth, sixth.coef=sixth.coef,sixth=sixth)) } #l*t e_f0 <- function(X.t0,tmp.f,env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- matrix(0,k.size,block) assign(pars[1],0) de.f0 <- list() for(k in 1:k.size){ de.f0[[k]] <- parse(text=deparse(D(tmp.f[[1]][k],pars[1]))) } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(k in 1:k.size){ result[k,t] <- eval(de.f0[[k]]) } } return(result) } #l*r*t e_f <- function(X.t0,tmp.f,env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(k.size,r.size,block)) assign(pars[1],0) de.f <- list() for(k in 1:k.size){ de.f[[k]] <- list() for(r in 1:r.size){ de.f[[k]][r] <- parse(text=deparse(D(tmp.f[[r+1]][k],pars[1]))) } } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(k in 1:k.size){ for(r in 1:r.size){ result[k,r,t] <- eval(de.f[[k]][[r]]) } } } return(result) } #l*i*t x_f0 <- function(X.t0,tmp.f,env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(k.size,d.size,block)) assign(pars[1],0) dx.f0 <- list() for(k in 1:k.size){ dx.f0[[k]] <- list() for(i in 1:d.size){ dx.f0[[k]][i] <- parse(text=deparse(D(tmp.f[[1]][k],state[i]))) } } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(k in 1:k.size){ for(i in 1:d.size){ result[k,i,t] <- eval(dx.f0[[k]][[i]]) } } } return(result) } #l*i1*i2*t x1_x2_f0 <- function(X.t0,tmp.f,env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(k.size,d.size,d.size,block)) assign(pars[1],0) dxdx.f0 <- list() for(k in 1:k.size){ dxdx.f0[[k]] <- list() for(i1 in 1:d.size){ dxdx.f0[[k]][[i1]] <- list() for(i2 in 1:d.size){ dxdx.f0[[k]][[i1]][i2] <- parse(text=deparse(D(D(tmp.f[[1]][k],state[i2]),state[i1]))) } } } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(k in 1:k.size){ for(i1 in 1:d.size){ for(i2 in 1:d.size){ result[k,i1,i2,t] <- eval(dxdx.f0[[k]][[i1]][[i2]]) } } } } return(result) } #l*i1*i2*r*t x1_x2_f <- function(X.t0,tmp.f,env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(k.size,d.size,d.size,r.size,block)) assign(pars[1],0) dxdx.f <- list() for(k in 1:k.size){ dxdx.f[[k]] <- list() for(i1 in 1:d.size){ dxdx.f[[k]][[i1]] <- list() for(i2 in 1:d.size){ dxdx.f[[k]][[i1]][[i2]] <- list() for(r in 1:r.size){ dxdx.f[[k]][[i1]][[i2]][r] <- parse(text=deparse(D(D(tmp.f[[r+1]][k],state[i2]),state[i1]))) } } } } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(k in 1:k.size){ for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(r in 1:r.size){ result[k,i1,i2,r,t] <- eval(dxdx.f[[k]][[i1]][[i2]][[r]]) } } } } } return(result) } #l*i*t x_e_f0 <- function(X.t0,tmp.f,env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(k.size,d.size,block)) assign(pars[1],0) dxde.f0 <- list() for(k in 1:k.size){ dxde.f0[[k]] <- list() for(i in 1:d.size){ dxde.f0[[k]][i] <- parse(text=deparse(D(D(tmp.f[[1]][k],pars[1]),state[i]))) } } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(k in 1:k.size){ for(i in 1:d.size){ result[k,i,t] <- eval(dxde.f0[[k]][[i]]) } } } return(result) } #l*i*r*t x_e_f <- function(X.t0,tmp.f,env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(k.size,d.size,r.size,block)) assign(pars[1],0) dxde.f <- list() for(k in 1:k.size){ dxde.f[[k]] <- list() for(i in 1:d.size){ dxde.f[[k]][[i]] <- list() for(r in 1:r.size){ dxde.f[[k]][[i]][r] <- parse(text=deparse(D(D(tmp.f[[r+1]][k],pars[1]),state[i]))) } } } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(k in 1:k.size){ for(i in 1:d.size){ for(r in 1:r.size){ result[k,i,r,t] <- eval(dxde.f[[k]][[i]][[r]]) } } } } return(result) } #l*t e_e_f0 <- function(X.t0,tmp.f,env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- matrix(0,k.size,block) assign(pars[1],0) dede.f0 <- list() for(k in 1:k.size){ dede.f0[[k]] <- parse(text=deparse(D(D(tmp.f[[1]][k],pars[1]),pars[1]))) } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(k in 1:k.size){ result[k,t] <- eval(dede.f0[[k]]) } } return(result) } #l*r*t e_e_f <- function(X.t0,tmp.f,env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(k.size,r.size,block)) assign(pars[1],0) dede.f <- list() for(k in 1:k.size){ dede.f[[k]] <- list() for(r in 1:r.size){ dede.f[[k]][r] <- parse(text=deparse(D(D(tmp.f[[r+1]][k],pars[1]),pars[1]))) } } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(k in 1:k.size){ for(r in 1:r.size){ result[k,r,t] <- eval(dede.f[[k]][[r]]) } } } return(result) } #l*i1*i2*i3*t x1_x2_x3_f0 <- function(X.t0,tmp.f,env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(k.size,d.size,d.size,d.size,block)) assign(pars[1],0) dxdxdx.f0 <- list() for(k in 1:k.size){ dxdxdx.f0[[k]] <- list() for(i1 in 1:d.size){ dxdxdx.f0[[k]][[i1]] <- list() for(i2 in 1:d.size){ dxdxdx.f0[[k]][[i1]][[i2]] <- list() for(i3 in 1:d.size){ dxdxdx.f0[[k]][[i1]][[i2]][i3] <- parse(text=deparse(D(D(D(tmp.f[[1]][k],state[i3]),state[i2]),state[i1]))) } } } } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(k in 1:k.size){ for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(i3 in 1:d.size){ result[k,i1,i2,i3,t] <- eval(dxdxdx.f0[[k]][[i1]][[i2]][[i3]]) } } } } } return(result) } #l*i1*i2*i3*r*t x1_x2_x3_f <- function(X.t0,tmp.f,env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(k.size,d.size,d.size,d.size,r.size,block)) assign(pars[1],0) dxdxdx.f <- list() for(k in 1:k.size){ dxdxdx.f[[k]] <- list() for(i1 in 1:d.size){ dxdxdx.f[[k]][[i1]] <- list() for(i2 in 1:d.size){ dxdxdx.f[[k]][[i1]][[i2]] <- list() for(i3 in 1:d.size){ dxdxdx.f[[k]][[i1]][[i2]][[i3]] <- list() for(r in 1:r.size){ dxdxdx.f[[k]][[i1]][[i2]][[i3]][r] <- parse(text=deparse(D(D(D(tmp.f[[r+1]][k],state[i3]),state[i2]),state[i1]))) } } } } } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(k in 1:k.size){ for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(i3 in 1:d.size){ for(r in 1:r.size){ result[k,i1,i2,i3,r,t] <- eval(dxdxdx.f[[k]][[i1]][[i2]][[i3]][[r]]) } } } } } } return(result) } #l*i1*i2*t x1_x2_e_f0 <- function(X.t0,tmp.f,env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(k.size,d.size,d.size,block)) assign(pars[1],0) dxdxde.f0 <- list() for(k in 1:k.size){ dxdxde.f0[[k]] <- list() for(i1 in 1:d.size){ dxdxde.f0[[k]][[i1]] <- list() for(i2 in 1:d.size){ dxdxde.f0[[k]][[i1]][i2] <- parse(text=deparse(D(D(D(tmp.f[[1]][k],pars[1]),state[i2]),state[i1]))) } } } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(k in 1:k.size){ for(i1 in 1:d.size){ for(i2 in 1:d.size){ result[k,i1,i2,t] <- eval(dxdxde.f0[[k]][[i1]][[i2]]) } } } } return(result) } #l*i1*i2*r*t x1_x2_e_f <- function(X.t0,tmp.f,env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(k.size,d.size,d.size,r.size,block)) assign(pars[1],0) dxdxde.f <- list() for(k in 1:k.size){ dxdxde.f[[k]] <- list() for(i1 in 1:d.size){ dxdxde.f[[k]][[i1]] <- list() for(i2 in 1:d.size){ dxdxde.f[[k]][[i1]][[i2]] <- list() for(r in 1:r.size){ dxdxde.f[[k]][[i1]][[i2]][r] <- parse(text=deparse(D(D(D(tmp.f[[r+1]][k],pars[1]),state[i2]),state[i1]))) } } } } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(k in 1:k.size){ for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(r in 1:r.size){ result[k,i1,i2,r,t] <- eval(dxdxde.f[[k]][[i1]][[i2]][[r]]) } } } } } return(result) } #l*i*t x_e_e_f0 <- function(X.t0,tmp.f,env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(k.size,d.size,block)) assign(pars[1],0) dxdede.f0 <- list() for(k in 1:k.size){ dxdede.f0[[k]] <- list() for(i in 1:d.size){ dxdede.f0[[k]][i] <- parse(text=deparse(D(D(D(tmp.f[[1]][k],pars[1]),pars[1]),state[i]))) } } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(k in 1:k.size){ for(i in 1:d.size){ result[k,i,t] <- eval(dxdede.f0[[k]][[i]]) } } } return(result) } #l*i*r*t x_e_e_f <- function(X.t0,tmp.f,env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(k.size,d.size,r.size,block)) assign(pars[1],0) dxdede.f <- list() for(k in 1:k.size){ dxdede.f[[k]] <- list() for(i in 1:d.size){ dxdede.f[[k]][[i]] <- list() for(r in 1:r.size){ dxdede.f[[k]][[i]][r] <- parse(text=deparse(D(D(D(tmp.f[[r+1]][k],pars[1]),pars[1]),state[i]))) } } } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(k in 1:k.size){ for(i in 1:d.size){ for(r in 1:r.size){ result[k,i,r,t] <- eval(dxdede.f[[k]][[i]][[r]]) } } } } return(result) } #l*t e_e_e_f0 <- function(X.t0,tmp.f,env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- matrix(0,k.size,block) assign(pars[1],0) dedede.f0 <- list() for(k in 1:k.size){ dedede.f0[[k]] <- parse(text=deparse(D(D(D(tmp.f[[1]][k],pars[1]),pars[1]),pars[1]))) } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(k in 1:k.size){ result[k,t] <- eval(dedede.f0[[k]]) } } return(result) } #l*r*t e_e_e_f <- function(X.t0,tmp.f,env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(k.size,r.size,block)) dedede.f <- list() for(k in 1:k.size){ dedede.f[[k]] <- list() for(r in 1:r.size){ dedede.f[[k]][r] <- parse(text=deparse(D(D(D(tmp.f[[r+1]][k],pars[1]),pars[1]),pars[1]))) } } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(k in 1:k.size){ for(r in 1:r.size){ result[k,r,t] <- eval(dedede.f[[k]][[r]]) } } } return(result) } ##p.19 #l*t F_t <- function(tmpY, get_Y_e_V, get_Y_D, get_x1_x2_f0, get_x_e_f0, get_e_e_f0, env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size delta <- env$delta block <- env$block Diff <- env$Diff result <- matrix(0,k.size,block) first <- matrix(0,k.size,block) second <- matrix(0,k.size,block) third <- matrix(0,k.size,block) fourth <- matrix(0,k.size,block) for(l in 1:k.size){ for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(j1 in 1:d.size){ for(j2 in 1:d.size){ tmp1 <- b1_b2(get_Y_e_V[j1,,],get_Y_e_V[j2,,],env) tmp2 <- double(block) for(t in 2:block){ tmp2[t] <- (get_x1_x2_f0[l,i1,i2,] * tmpY[i1,j1,] * tmpY[i2,j2,] * tmp1) %*% Diff[t,] * delta } first[l,] <- first[l,] + tmp2 } } tmp3 <- double(block) for(t in 2:block){ tmp3[t] <- (get_x1_x2_f0[l,i1,i2,] * get_Y_D[i1,] * get_Y_D[i2,]) %*% Diff[t,] * delta } second[l,] <- second[l,] + tmp3 } tmp4 <- double(block) for(t in 2:block){ tmp4[t] <- (get_x_e_f0[l,i1,] * get_Y_D[i1,]) %*% Diff[t,] * delta } third[l,] <- third[l,] + 2 * tmp4 } tmp5 <- double(block) for(t in 2:block){ tmp5[t] <- get_e_e_f0[l,] %*% Diff[t,] * delta } fourth[l,] <- fourth[l,] + tmp5 } result <- first + second + third + fourth return(result) } #l*j1*t W_t <- function(tmpY, get_Y_D, get_x1_x2_f0, get_x_e_f0, env){ d.size <- env$d.size k.size <- env$k.size block <- env$block result <- array(0,dim=c(k.size,d.size,block)) first <- array(0,dim=c(k.size,d.size,block)) second <- array(0,dim=c(k.size,d.size,block)) for(l in 1:k.size){ for(j1 in 1:d.size){ for(i1 in 1:d.size){ for(i2 in 1:d.size){ first[l,j1,] <- first[l,j1,] + get_x1_x2_f0[l,i1,i2,] * get_Y_D[i1,] * tmpY[i2,j1,] } second[l,j1,] <- second[l,j1,] + get_x_e_f0[l,i1,] * tmpY[i1,j1,] } } } result <- first + second return(result) } #l*j1*r*t W_hat_t <- function(tmpY, get_Y_e_V, get_x1_x2_f0, get_x_e_f, env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size block <- env$block result <- array(0,dim=c(k.size,d.size,r.size,block)) first <- array(0,dim=c(k.size,d.size,r.size,block)) for(l in 1:k.size){ for(j1 in 1:d.size){ for(r in 1:r.size){ for(i1 in 1:d.size){ first[l,j1,r,] <- first[l,j1,r,] + get_x_e_f[l,i1,r,] * tmpY[i1,j1,] } } } } second <- array(0,dim=c(k.size,d.size,r.size,block)) for(l in 1:k.size){ for(j1 in 1:d.size){ for(j2 in 1:d.size){ tmp2 <- double(block) tmp3 <- matrix(0,r.size,block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp1 <- get_x1_x2_f0[l,i1,i2,] * tmpY[i1,j1,] * tmpY[i2,j2,] tmp2 <- tmp2 + tmp1 } } for(r in 1:r.size){ tmp3[r,] <- I0(tmp2,env) * get_Y_e_V[j2,r,] } second[l,j1,,] <- second[l,j1,,] + tmp3 } } } result <- first - second return(result) } #first:l, second:l*j2*r*t&j2*r*t, third:l*r*t F_tilde1_1 <- function(tmpY, get_Y_e_V, get_x1_x2_f0, get_e_e_f, get_F_t, get_W_t, get_W_hat_t, env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size block <- env$block first <- get_F_t[block] second <- list() second[[1]] <- array(0,dim=c(k.size,d.size,r.size,block)) second[[2]] <- get_Y_e_V for(l in 1:k.size){ for(j1 in 1:d.size){ for(j2 in 1:d.size){ tmp2 <- double(block) tmp3 <- double(1) for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp1 <- get_x1_x2_f0[l,i1,i2,] * tmpY[i1,j1,] * tmpY[i2,j2,] tmp2 <- tmp2 + tmp1 } } tmp3 <- tmp3 + 2 * I0(tmp2,env)[block] for(r in 1:r.size){ second[[1]][l,j2,r,] <- second[[1]][l,j2,r,] + tmp3 * get_Y_e_V[j1,r,] } } } } third.coef <- array(0,dim=c(k.size,d.size,block)) #l, j1, t third <- array(0,dim=c(k.size,r.size,block)) for(l in 1:k.size){ for(j1 in 1:d.size){ third.coef[l,j1,] <- 2 * I0(get_W_t[l,j1,],env) for(r in 1:r.size){ third[l,r,] <- third[l,r,] + third.coef[l,j1,block] * get_Y_e_V[j1,r,] } } } fourth <- array(0,dim=c(k.size,r.size,block)) for(l in 1:k.size){ for(j1 in 1:d.size){ for(r in 1:r.size){ fourth[l,r,] <- fourth[l,r,] - third.coef[l,j1,] * get_Y_e_V[j1,r,] } } } fifth <- list() fifth[[1]] <- 2 * get_W_hat_t fifth[[2]] <- get_Y_e_V sixth <- get_e_e_f second[[1]] <- second[[1]] + fifth[[1]] third <- third + fourth + sixth return(list(first=first,second=second,third=third)) } #first:d*k*k*t, second:d*k*t, third:d*t E0_bar <- function(get_E0_t,env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size block <- env$block first.tmp <- get_E0_t$first second.coef <- get_E0_t$second.coef second.wtmp <- get_E0_t$second second.tmp <- list() second.tmp$first <- array(0,dim=c(d.size,k.size,k.size,block)) second.tmp$second <- matrix(0,d.size,block) n1 <- length(second.coef) n2 <- sum(second.coef == 0) n3 <- length(second.wtmp[[1]]) n4 <- sum(second.wtmp[[1]] == 0) n5 <- length(second.wtmp[[2]]) n6 <- sum(second.wtmp[[2]] == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) * (n5 - n6 != 0) for(j1 in 1:1:d.size){ if(n == 0){ break } for(j2 in 1:d.size){ tmp1 <- I_12(second.wtmp[[1]][j1,,],second.wtmp[[2]][j2,,],env) for(i in 1:d.size){ for(t in 1:block){ second.tmp$first[i,,,t] <- second.tmp$first[i,,,t] + second.coef[i,j1,j2,t] * tmp1$first[,,t] second.tmp$second[i,t] <- second.tmp$second[i,t] + second.coef[i,j1,j2,t] * tmp1$second[t] } } } } third.coef <- get_E0_t$third.coef third.wtmp <- get_E0_t$third third.tmp <- array(0,dim=c(d.size,k.size,block)) n7 <- length(third.coef) n8 <- sum(third.coef == 0) n9 <- length(third.wtmp) n10 <- sum(third.wtmp == 0) n <- (n7 - n8 != 0) * (n9 - n10 != 0) for(i in 1:d.size){ if(n == 0){ break } for(j1 in 1:d.size){ tmp2 <- I_1(third.wtmp[j1,,],env) for(t in 1:block){ third.tmp[i,,t] <- third.tmp[i,,t] + third.coef[i,j1,t] * tmp2[,t] } } } fourth.coef <- get_E0_t$fourth.coef fourth.wtmp <- get_E0_t$fourth fourth.tmp <- array(0,dim=c(d.size,k.size,block)) fifth.coef <- get_E0_t$fifth.coef fifth.wtmp <- get_E0_t$fifth fifth.tmp <- list() fifth.tmp$first <- array(0,dim=c(d.size,k.size,k.size,block)) fifth.tmp$second <- matrix(0,d.size,block) sixth.coef <- get_E0_t$sixth.coef sixth.wtmp <- get_E0_t$sixth sixth.tmp <- array(0,dim=c(d.size,k.size,block)) n11 <- length(sixth.wtmp) n12 <- sum(sixth.wtmp == 0) n <- n11 - n12 for(i in 1:d.size){ for(j in 1:d.size){ tmp3 <- I_1(fourth.wtmp[j,,],env) for(k in 1:k.size){ fourth.tmp[i,k,] <- fourth.tmp[i,k,] + fourth.coef[i,j,] * tmp3[k,] } for(j1 in 1:d.size){ tmp4 <- I_12(fifth.wtmp[[1]][j1,j,,],fifth.wtmp[[2]][j1,,],env) for(t in 1:block){ fifth.tmp$first[i,,,t] <- fifth.tmp$first[i,,,t] + fifth.coef[i,j,t] * tmp4$first[,,t] fifth.tmp$second[i,t] <- fifth.tmp$second[i,t] + fifth.coef[i,j,t] * tmp4$second[t] } } } if(n == 0){ next } tmp5 <- I_1(sixth.wtmp[j,,],env) for(i in 1:d.size){ for(k in 1:k.size){ sixth.tmp[i,k,] <- sixth.tmp[i,k,] + sixth.coef[i,j,] * tmp5[k,] } } } first <- second.tmp$first + fifth.tmp$first second <- third.tmp + fourth.tmp + sixth.tmp third <- first.tmp + second.tmp$second + fifth.tmp$second return(list(first=first,second=second,third=third)) } E0_bar_x <- function(x,get_E0_bar,env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size result <- double(d.size) for(i in 1:d.size){ first.tmp <- list() first.tmp$first <- get_E0_bar$first[i,,,] first.tmp$second <- get_E0_bar$third[i,] second.tmp <- get_E0_bar$second[i,,] result1 <- I_12_x(x,first.tmp,env) result2 <- I_1_x(x,second.tmp,env) result[i] <- result1 + result2 } return(result) } #first:l, second:l*j2*r*t&j2*r*t, third:l*r*t F_tilde1_2 <- function(get_E0_t,get_x_f0,env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size block <- env$block result1 <- get_E0_t$first first <- double(k.size) for(l in 1:k.size){ for(i in 1:d.size){ tmp1 <- get_x_f0[l,i,] * result1[i,] first[l] <- first[l] + I0(tmp1,env)[block] } } result2.coef <- get_E0_t$second.coef result2 <- get_E0_t$second[[1]] second <- list() second[[1]] <- array(0,dim=c(k.size,d.size,r.size,block)) #l,j2,r,t second[[2]] <- result2 third <- list() third[[1]] <- array(0,dim=c(k.size,d.size,r.size,block)) third[[2]] <- result2 for(l in 1:k.size){ for(j2 in 1:d.size){ for(j1 in 1:d.size){ tmp3 <- double(block) for(i in 1:d.size){ tmp2 <- get_x_f0[l,i,] * result2.coef[i,j1,j2,] tmp3 <- tmp3 + tmp2 } tmp4 <- I0(tmp3,env) for(r in 1:r.size){ second[[1]][l,j2,r,] <- second[[1]][l,j2,r,] + tmp4[block] * result2[j1,r,] third[[1]][l,j2,r,] <- third[[1]][l,j2,r,] - tmp4 * result2[j1,r,] } } } } result4.coef <- get_E0_t$third.coef fourth <- array(0,dim=c(k.size,r.size,block)) fifth <- array(0,dim=c(k.size,r.size,block)) for(l in 1:k.size){ for(j1 in 1:d.size){ tmp6 <- double(block) for(i in 1:d.size){ tmp5 <- get_x_f0[l,i,] * result4.coef[i,j1,] tmp6 <- tmp6 + tmp5 } tmp7 <- I0(tmp6,env) for(r in 1:r.size){ fourth[l,r,] <- fourth[l,r,] + tmp7[block] * result2[j1,r,] fifth[l,r,] <- fifth[l,r,] - tmp7 * result2[j1,r,] } } } result6.coef <- get_E0_t$fourth.coef result6 <- get_E0_t$fourth result8 <- get_E0_t$fifth[[1]] result10 <- get_E0_t$sixth sixth <- array(0,dim=c(k.size,r.size,block)) seventh <- array(0,dim=c(k.size,r.size,block)) eighth <- list() eighth[[1]] <- array(0,dim=c(k.size,d.size,r.size,block)) eighth[[2]] <- result2 ninth <- list() ninth[[1]] <- array(0,dim=c(k.size,d.size,r.size,block)) ninth[[2]] <- result2 tenth <- array(0,dim=c(k.size,r.size,block)) eleventh <- array(0,dim=c(k.size,r.size,block)) for(l in 1:k.size){ for(j in 1:d.size){ tmp9 <- double(block) for(i in 1:d.size){ tmp8 <- get_x_f0[l,i,] * result6.coef[i,j,] tmp9 <- tmp9 + tmp8 } tmp10 <- I0(tmp9,env) for(r in 1:r.size){ sixth[l,r,] <- sixth[l,r,] + tmp10[block] * result6[j,r,] seventh[l,r,] <- seventh[l,r,] - tmp10 * result6[j,r,] for(j1 in 1:d.size){ eighth[[1]][l,j1,r,] <- eighth[[1]][l,j1,r,] - tmp10[block] * result8[j1,j,r,] ninth[[1]][l,j1,r,] <- ninth[[1]][l,j1,r,] + tmp10 * result8[j1,j,r,] } tenth[l,r,] <- tenth[l,r,] - tmp10[block]/2 * result10[j,r,] eleventh[l,r,] <- eleventh[l,r,] + tmp10/2 * result10[j,r,] } } } second[[1]] <- second[[1]] + third[[1]] + eighth[[1]] + ninth[[1]] third <- fourth + fifth + sixth + seventh + tenth + eleventh return(list(first=first,second=second,third=third)) } #first:l*t, second.coef:l*j1*j2*t, second:j1*r*t&j2*r*t, #third.coef:l*j1*t, third:j1*r*t, fourth.coef:l*j*t, fourth:j*r*t, #fifth.coef:l*j*t, fifth:j1*j*r*t&j1*r*t, sixth.coef:l*j*t, #sixth:j*r*t ##p.22 #l*i*t x_F <- function(X.t0,F,env){ d.size <- env$d.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(k.size,d.size,block)) assign(pars[1],0) dx.F <- list() for(l in 1:k.size){ dx.F[[l]] <- list() for(i in 1:d.size){ dx.F[[l]][i] <- parse(text=deparse(D(F[l],state[i]))) } } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(l in 1:k.size){ for(i in 1:d.size){ result[l,i,t] <- eval(dx.F[[l]][[i]]) } } } return(result) } #l*i1*i2*t x1_x2_F <- function(X.t0,F,env){ d.size <- env$d.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(k.size,d.size,d.size,block)) assign(pars[1],0) dxdx.F <- list() for(l in 1:k.size){ dxdx.F[[l]] <- list() for(i1 in 1:d.size){ dxdx.F[[l]][[i1]] <- list() for(i2 in 1:d.size){ dxdx.F[[l]][[i1]][i2] <- parse(text=deparse(D(D(F[l],state[i2]),state[i1]))) } } } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(l in 1:k.size){ for(i1 in 1:d.size){ for(i2 in 1:d.size){ result[l,i1,i2,t] <- eval(dxdx.F[[l]][[i1]][[i2]]) } } } } return(result) } #l*i*t x_e_F <- function(X.t0,F,env){ d.size <- env$d.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(k.size,d.size,block)) assign(pars[1],0) dxde.F <- list() for(l in 1:k.size){ dxde.F[[l]] <- list() for(i in 1:d.size){ dxde.F[[l]][i] <- parse(text=deparse(D(D(F[l],pars[1]),state[i]))) } } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(l in 1:k.size){ for(i in 1:d.size){ result[l,i,t] <- eval(dxde.F[[l]][[i]]) } } } return(result) } #l*t e_e_F <- function(X.t0,F,env){ d.size <- env$d.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- matrix(0,k.size,block) assign(pars[1],0) dede.F <- list() for(l in 1:k.size){ dede.F[[l]] <- parse(text=deparse(D(D(F[l],pars[1]),pars[1]))) } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(l in 1:k.size){ result[l,t] <- eval(dede.F[[l]]) } } return(result) } #l*i1*i2*i3*t x1_x2_x3_F <- function(X.t0,F,env){ d.size <- env$d.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(k.size,d.size,d.size,d.size,block)) assign(pars[1],0) dxdxdx.F <- list() for(l in 1:k.size){ dxdxdx.F[[l]] <- list() for(i1 in 1:d.size){ dxdxdx.F[[l]][[i1]] <- list() for(i2 in 1:d.size){ dxdxdx.F[[l]][[i1]][[i2]] <- list() for(i3 in 1:d.size){ dxdxdx.F[[l]][[i1]][[i2]][i3] <- parse(text=deparse(D(D(D(F[l],state[i3]),state[i2]),state[i1]))) } } } } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(l in 1:k.size){ for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(i3 in 1:d.size){ result[l,i1,i2,i3,t] <- eval(dxdxdx.F[[l]][[i1]][[i2]][[i3]]) } } } } } return(result) } #l*i1*i2*t x1_x2_e_F <- function(X.t0,F,env){ d.size <- env$d.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(k.size,d.size,d.size,block)) assign(pars[1],0) dxdxde.F <- list() for(l in 1:k.size){ dxdxde.F[[l]] <- list() for(i1 in 1:d.size){ dxdxde.F[[l]][[i1]] <- list() for(i2 in 1:d.size){ dxdxde.F[[l]][[i1]][i2] <- parse(text=deparse(D(D(D(F[l],pars[1]),state[i2]),state[i1]))) } } } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(l in 1:k.size){ for(i1 in 1:d.size){ for(i2 in 1:d.size){ result[l,i1,i2,t] <- eval(dxdxde.F[[l]][[i1]][[i2]]) } } } } return(result) } #l*i*t x_e_e_F <- function(X.t0,F,env){ d.size <- env$d.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(k.size,d.size,block)) assign(pars[1],0) dxdede.F <- list() for(l in 1:k.size){ dxdede.F[[l]] <- list() for(i in 1:d.size){ dxdede.F[[l]][i] <- parse(text=deparse(D(D(D(F[l],pars[1]),pars[1]),state[i]))) } } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(l in 1:k.size){ for(i in 1:d.size){ result[l,i,t] <- eval(dxdede.F[[l]][[i]]) } } } return(result) } #l*t e_e_e_F <- function(X.t0,F,env){ d.size <- env$d.size k.size <- env$k.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- matrix(0,k.size,block) assign(pars[1],0) dedede.F <- list() for(l in 1:k.size){ dedede.F[[l]] <- parse(text=deparse(D(D(D(F[l],pars[1]),pars[1]),pars[1]))) } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(l in 1:k.size){ result[l,t] <- eval(dedede.F[[l]]) } } return(result) } #first:l,second:l*j2*r*t&j2*r*t,third:l*r*t F_tilde1_3 <- function(get_E0_t,get_x_F,env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size block <- env$block result1 <- get_E0_t$first first <- double(k.size) for(l in 1:k.size){ for(i in 1:d.size){ tmp1 <- get_x_F[l,i,block] * result1[i,block] first[l] <- first[l] + tmp1 } } result2.coef <- get_E0_t$second.coef result2 <- get_E0_t$second[[1]] second <- list() second[[1]] <- array(0,dim=c(k.size,d.size,r.size,block)) second[[2]] <- result2 for(l in 1:k.size){ for(j1 in 1:d.size){ for(j2 in 1:d.size){ tmp3 <- double(1) for(i in 1:d.size){ tmp2 <- get_x_F[l,i,block] * result2.coef[i,j1,j2,block] tmp3 <- tmp3 + tmp2 } for(r in 1:r.size){ second[[1]][l,j2,r,] <- second[[1]][l,j2,r,] + tmp3 * result2[j1,r,] } } } } result3.coef <- get_E0_t$third.coef third <- array(0,dim=c(k.size,r.size,block)) for(l in 1:k.size){ for(j1 in 1:d.size){ tmp5 <- double(1) for(i in 1:d.size){ tmp4 <- get_x_F[l,i,block] * result3.coef[i,j1,block] tmp5 <- tmp5 + tmp4 } for(r in 1:r.size){ third[l,r,] <- third[l,r,] + tmp5 * result2[j1,r,] } } } result4.coef <- get_E0_t$fourth.coef result4 <- get_E0_t$fourth result5 <- get_E0_t$fifth[[1]] result6 <- get_E0_t$sixth fourth <- array(0,dim=c(k.size,r.size,block)) fifth <- list() fifth[[1]] <- array(0,dim=c(k.size,d.size,r.size,block)) fifth[[2]] <- result2 sixth <- array(0,dim=c(k.size,r.size,block)) for(l in 1:k.size){ for(j in 1:d.size){ tmp7 <- double(1) for(i in 1:d.size){ tmp6 <- get_x_F[l,i,block] * result4.coef[i,j,block] tmp7 <- tmp7 + tmp6 } for(r in 1:r.size){ fourth[l,r,] <- fourth[l,r,] + tmp7 * result4[j,r,] for(j1 in 1:d.size){ fifth[[1]][l,j1,r,] <- fifth[[1]][l,j1,r,] - tmp7 * result5[j1,j,r,] } sixth[l,r,] <- sixth[l,r,] - tmp7/2 * result6[j1,r,] } } } second[[1]] <- second[[1]] + fifth[[1]] third <- third + fourth + sixth return(list(first=first,second=second,third=third)) } #first:l,second:l*j2*r*t&j2*r*t,third:l*r*t F_tilde1_4 <- function(tmpY, get_Y_e_V, get_Y_D, get_x_F, get_x1_x2_F, get_x_e_F, get_e_e_F, env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size block <- env$block first <- double(k.size) for(l in 1:k.size){ for(i1 in 1:d.size){ for(i2 in 1:d.size){ first[l] <- first[l] + get_x1_x2_F[l,i1,i2,block] * get_Y_D[i1,block] * get_Y_D[i2,block] } } } second <- double(k.size) for(l in 1:k.size){ for(i in 1:d.size){ second[l] <- second[l] + 2 * get_x_e_F[l,i,block] * get_Y_D[i1,block] } } third <- get_e_e_F[,block] fourth <- array(0,dim=c(k.size,r.size,block)) for(l in 1:k.size){ for(j1 in 1:d.size){ tmp1 <- double(1) for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp1 <- tmp1 + 2 * get_x1_x2_F[l,i1,i2,block] * get_Y_D[i1,block] * tmpY[i2,j1,block] } } for(r in 1:r.size){ fourth[l,r,] <- fourth[l,r,] + tmp1 * get_Y_e_V[j1,r,] } } } fifth <- array(0,dim=c(k.size,r.size,block)) for(l in 1:k.size){ for(j in 1:d.size){ tmp2 <- double(1) for(i in 1:d.size){ tmp2 <- tmp2 + 2 * get_x_e_F[l,i,block] * tmpY[i,j,block] } for(r in 1:r.size){ fifth[l,r,] <- fifth[l,r,] + tmp2 * get_Y_e_V[j,r,] } } } sixth <- list() sixth[[1]] <- array(0,dim=c(k.size,d.size,r.size,block)) sixth[[2]] <- get_Y_e_V seventh <- double(k.size) for(l in 1:k.size){ for(j1 in 1:d.size){ for(j2 in 1:d.size){ tmp3 <- double(1) for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp3 <- tmp3 + 2 * get_x1_x2_F[l,i1,i2,block] * tmpY[i1,j1,block] * tmpY[i2,j2,block] } } for(r in 1:r.size){ sixth[[1]][l,j2,r,] <- sixth[[1]][l,j2,r,] + tmp3 * get_Y_e_V[j1,r,] } tmp4 <- b1_b2(get_Y_e_V[j1,,],get_Y_e_V[j2,,],env)[block] seventh[l] <- seventh[l] + tmp3/2 * tmp4 } } } first <- first + second + third + seventh second <- list() second[[1]] <- sixth[[1]] second[[2]] <- sixth[[2]] third <- fourth + fifth return(list(first=first,second=second,third=third)) } #result1:l, result2:l*j2*r*t/j2*r*t, result3:l*r*t F_tilde1 <- function(get_F_tilde1_1, get_F_tilde1_2, get_F_tilde1_3, get_F_tilde1_4){ result1 <- get_F_tilde1_1$first + get_F_tilde1_2$first + get_F_tilde1_3$first + get_F_tilde1_4$first result1 <- result1/2 result2 <- list() result2[[1]] <- get_F_tilde1_1$second[[1]] + get_F_tilde1_2$second[[1]] + get_F_tilde1_3$second[[1]] + get_F_tilde1_4$second[[1]] result2[[1]] <- result2[[1]]/2 result2[[2]] <- get_F_tilde1_1$second[[2]] result3 <- get_F_tilde1_1$third + get_F_tilde1_2$third + get_F_tilde1_3$third + get_F_tilde1_4$third result3 <- result3/2 return(list(result1=result1,result2=result2,result3=result3)) } ##p.31(I) #a:l, b:l*j*r*t/j*r*t, c:l*r*t #l1*l2 ft_1 <- function(a1,a2,env){ k.size <- env$k.size result <- matrix(0,k.size,k.size) for(l1 in 1:k.size){ for(l2 in 1:k.size){ result[l1,l2] <- a1[l1] * a2[l2] } } return(result) } #first:l1*l2*k*k, second:l1*l2 ft_2 <- function(a1,b1,env){ d.size <- env$d.size k.size <- env$k.size block <- env$block first <- array(0,dim=c(k.size,k.size,k.size,k.size)) second <- matrix(0,k.size,k.size) for(l2 in 1:k.size){ for(j in 1:d.size){ tmp <- I_12(b1[[1]][l2,j,,],b1[[2]][j,,],env) for(l1 in 1:k.size){ first[l1,l2,,] <- first[l1,l2,,] + a1[l1] * tmp$first[,,block] second[l1,l2] <- second[l1,l2] + a1[l1] * tmp$second[block] } } } return(list(first=first,second=second)) } #l1*l2*k ft_3 <- function(a1,c1,env){ k.size <- env$k.size block <- env$block result <- array(0,dim=c(k.size,k.size,k.size)) for(l2 in 1:k.size){ tmp <- I_1(c1[l2,,],env) for(l1 in 1:k.size){ result[l1,l2,] <- a1[l1] * tmp[,block] } } return(result) } #first:l1*l2*k*k*k*k, second:l1*l2*k*k*, third:l1*l2 ft_4 <- function(b1,b2,env){ d.size <- env$d.size k.size <- env$k.size block <- env$block first <- array(0,dim=c(k.size,k.size,k.size,k.size,k.size,k.size)) second <- array(0,dim=c(k.size,k.size,k.size,k.size)) third <- matrix(0,k.size,k.size) for(l1 in 1:k.size){ for(l2 in 1:k.size){ for(j1 in 1:d.size){ for(j2 in 1:d.size){ tmp <- I_12_34(b1[[1]][l1,j1,,],b1[[2]][j1,,], b2[[1]][l2,j2,,],b2[[2]][j2,,],env) first[l1,l2,,,,] <- first[l1,l2,,,,] + tmp$first[,,,,block] second[l1,l2,,] <- second[l1,l2,,] + tmp$second[,,block] third[l1,l2] <- third[l1,l2] + tmp$third[block] } } } } return(list(first=first,second=second,third=third)) } #first:l1*l2*k*k*k, second:l1*l2*k ft_5 <- function(b1,c1,env){ d.size <- env$d.size k.size <- env$k.size block <- env$block first <- array(0,dim=c(k.size,k.size,k.size,k.size,k.size)) second <- array(0,dim=c(k.size,k.size,k.size)) for(l1 in 1:k.size){ for(l2 in 1:k.size){ for(j in 1:d.size){ tmp <- I_1_23(c1[l2,,],b1[[1]][l1,j,,],b1[[2]][j,,],env) first[l1,l2,,,] <- first[l1,l2,,,] + tmp$first[,,,block] second[l1,l2,] <- second[l1,l2,] + tmp$second[,block] } } } return(list(first=first,second=second)) } #first:l1*l2*k*k, second:l1*l2 ft_6 <- function(c1,c2,env){ k.size <- env$k.size block <- env$block first <- array(0,dim=c(k.size,k.size,k.size,k.size)) second <- matrix(0,k.size,k.size) for(l1 in 1:k.size){ for(l2 in 1:k.size){ tmp <- I_1_2(c1[l1,,],c2[l2,,],env) first[l1,l2,,] <- tmp$first[,,block] second[l1,l2] <- tmp$second[block] } } return(list(first=first,second=second)) } #first:l1*l2*k*k*k*k, second:l1*l2*k*k*k, #third:l1*l2*k*k, fourth:l1*l2*k, fifth:l1*l2 F_tilde1__2 <- function(get_F_tilde1,env){ k.size <- env$k.size temp <- list() temp$first <- array(0,dim=c(k.size,k.size,k.size,k.size,k.size,k.size)) temp$second <- array(0,dim=c(k.size,k.size,k.size,k.size,k.size)) temp$third <- array(0,dim=c(k.size,k.size,k.size,k.size)) temp$fourth <- array(0,dim=c(k.size,k.size,k.size)) temp$fifth <- matrix(0,k.size,k.size) calc.range <- c(1:3) tmp1 <- get_F_tilde1$result1 n1 <- length(tmp1) n2 <- sum(tmp1 == 0) if(n1 == n2){ calc.range <- calc.range[calc.range != 1] } tmp2 <- get_F_tilde1$result2[[1]] n3 <- length(tmp2) n4 <- sum(tmp2 == 0) tmp3 <- get_F_tilde1$result2[[2]] n5 <- length(tmp3) n6 <- sum(tmp3 == 0) n <- (n3 - n4 != 0) * (n5 - n6 != 0) if(n == 0){ calc.range <- calc.range[calc.range != 2] } tmp3 <- get_F_tilde1$result3 n7 <- length(tmp3) n8 <- sum(tmp3 == 0) if(n7 == n8){ calc.range <- calc.range[calc.range != 3] } for(i1 in calc.range){ for(i2 in calc.range){ tmp1 <- switch(i1,"a","b","c") tmp2 <- switch(i2,"a","b","c") tmp <- paste(tmp1,tmp2,sep="") result <- switch(tmp,"aa"=ft_1(get_F_tilde1[[i1]],get_F_tilde1[[i2]],env), "ab"=ft_2(get_F_tilde1[[i1]],get_F_tilde1[[i2]],env), "ac"=ft_3(get_F_tilde1[[i1]],get_F_tilde1[[i2]],env), "ba"=ft_2(get_F_tilde1[[i2]],get_F_tilde1[[i1]],env), "bb"=ft_4(get_F_tilde1[[i1]],get_F_tilde1[[i2]],env), "bc"=ft_5(get_F_tilde1[[i1]],get_F_tilde1[[i2]],env), "ca"=ft_3(get_F_tilde1[[i2]],get_F_tilde1[[i1]],env), "cb"=ft_5(get_F_tilde1[[i2]],get_F_tilde1[[i1]],env), "cc"=ft_6(get_F_tilde1[[i1]],get_F_tilde1[[i2]],env)) nlist <- length(result) if(nlist != 2 && nlist != 3){ tmp3 <- 7 - length(dim(result)) #4 or 5 temp[[tmp3]] <- temp[[tmp3]] + result }else if(nlist == 2){ tmp4 <- 7 - length(dim(result[[1]])) #2 or 3 temp[[tmp4]] <- temp[[tmp4]] + result[[1]] tmp5 <- 7 - length(dim(result[[2]])) #4 or 5 temp[[tmp5]] <- temp[[tmp5]] + result[[2]] }else{ temp[[1]] <- temp[[1]] + result[[1]] temp[[3]] <- temp[[3]] + result[[2]] temp[[5]] <- temp[[5]] + result[[3]] } } } first <- temp$first second <- temp$second third <- temp$third fourth <- temp$fourth fifth <- temp$fifth return(list(first=first,second=second,third=third, fourth=fourth,fifth=fifth)) } F_tilde1__2_x <- function(l1,l2,x,get_F_tilde1__2,env){ k.size <- env$k.size first <- array(get_F_tilde1__2$first[l1,l2,,,,], dim=c(k.size,k.size,k.size,k.size)) result1 <- 0 for(k1 in 1:k.size){ for(k2 in 1:k.size){ for(k3 in 1:k.size){ for(k4 in 1:k.size){ result1 <- result1 + first[k1,k2,k3,k4] * x[k1] * x[k2] * x[k3] * x[k4] } } } } second <- array(get_F_tilde1__2$second[l1,l2,,,], dim=c(k.size,k.size,k.size)) result2 <- 0 for(k1 in 1:k.size){ for(k2 in 1:k.size){ for(k3 in 1:k.size){ result2 <- result2 + second[k1,k2,k3] * x[k1] * x[k2] * x[k3] } } } third <- matrix(get_F_tilde1__2$third[l1,l2,,], k.size,k.size) result3 <- 0 for(k1 in 1:k.size){ for(k2 in 1:k.size){ result3 <- result3 + third[k1,k2] * x[k1] * x[k2] } } fourth <- get_F_tilde1__2$fourth[l1,l2,] result4 <- 0 for(k1 in 1:k.size){ result4 <- result4 + fourth[k1] * x[k1] } fifth <- get_F_tilde1__2$fifth[l1,l2] result <- result1 + result2 + result3 + result4 + fifth return(result) } ##p.32(II)-1 #b:r*t, c:1*t #k*t C_b <- function(b,c1,c2,env){ k.size <- env$k.size block <- env$block result <- matrix(0,k.size,block) tmp1 <- I_1(b,env) for(k in 1:k.size){ tmp2 <- c2 * tmp1[k,] tmp3 <- I0(tmp2,env) result[k,] <- c1 * tmp3 } return(result) } #first:k*k*t, second:t C_c <- function(b1,b2,c1,c2,env){ k.size <- env$k.size block <- env$block first <- array(0,dim=c(k.size,k.size,block)) tmp1 <- I_12(b1,b2,env) for(k1 in 1:k.size){ for(k2 in 1:k.size){ tmp2 <- c2 * tmp1$first[k1,k2,] tmp3 <- I0(tmp2,env) first[k1,k2,] <- c1 * tmp3 } } second <- double(block) tmp4 <- c2 * tmp1$second tmp5 <- I0(tmp4,env) second <- c1 * tmp5 return(list(first=first,second=second)) } #first:k*k*t, second:t C_d <- function(b1,b2,c1,c2,env){ k.size <- env$k.size block <- env$block first <- array(0,dim=c(k.size,k.size,block)) tmp1 <- I_1_2(b1,b2,env) for(k1 in 1:k.size){ for(k2 in 1:k.size){ tmp2 <- c2 * tmp1$first[k1,k2,] tmp3 <- I0(tmp2,env) first[k1,k2,] <- c1 * tmp3 } } tmp4 <- c2 * tmp1$second tmp5 <- I0(tmp4,env) second <- c1 * tmp5 return(list(first=first,second=second)) } #first:k*k*k*t, second:k*t C_e <- function(b1,b2,b3,c1,c2,env){ k.size <- env$k.size block <- env$block first <- array(0,dim=c(k.size,k.size,k.size,block)) tmp1 <- I_1_23(b1,b2,b3,env) for(k1 in 1:k.size){ for(k2 in 1:k.size){ for(k3 in 1:k.size){ tmp2 <- c2 * tmp1$first[k1,k2,k3,] tmp3 <- I0(tmp2,env) first[k1,k2,k3,] <- c1 * tmp3 } } } second <- matrix(0,k.size,block) for(k in 1:k.size){ tmp4 <- c2 * tmp1$second[k,] tmp5 <- I0(tmp4,env) second[k,] <- c1 * tmp5 } return(list(first=first,second=second)) } #k*t C_f <- function(b1,c1,env){ k.size <- env$k.size block <- env$block result <- matrix(0,k.size,block) tmp1 <- I_1(b1,env) for(k in 1:k.size){ result[k,] <- c1 * tmp1[k,] } return(result) } #first:k*k*t, second:t C_g <- function(b1,b2,c1,env){ k.size <- env$k.size block <- env$block first <- array(0,dim=c(k.size,k.size,block)) tmp1 <- I_12(b1,b2,env) for(k1 in 1:k.size){ for(k2 in 1:k.size){ first[k1,k2,] <- c1 * tmp1$first[k1,k2,] } } second <- c1 * tmp1$second return(list(first=first,second=second)) } #first:k*k*k*t, second:k*t C_h <- function(b1,b2,b3,c1,env){ k.size <- env$k.size block <- env$block first <- array(0,dim=c(k.size,k.size,k.size,block)) tmp1 <- I_123(b1,b2,b3,env) for(k1 in 1:k.size){ for(k2 in 1:k.size){ for(k3 in 1:k.size){ first[k1,k2,k3,] <- c1 * tmp1$first[k1,k2,k3,] } } } second <- matrix(0,k.size,block) for(k in 1:k.size){ second[k,] <- c1 * tmp1$second[k,] } return(list(first=first,second=second)) } #first:k*k*k*t, second:k*t C_i <- function(b1,b2,b3,c1,c2,env){ k.size <- env$k.size block <- env$block first <- array(0,dim=c(k.size,k.size,k.size,block)) tmp1 <- I_1_2_3(b1,b2,b3,env) for(k1 in 1:k.size){ for(k2 in 1:k.size){ for(k3 in 1:k.size){ tmp2 <- c2 * tmp1$first[k1,k2,k3,] tmp3 <- I0(tmp2,env) first[k1,k2,k3,] <- c1 * tmp3 } } } second <- matrix(0,k.size,block) for(k in 1:k.size){ tmp4 <- c2 * tmp1$second[k,] tmp5 <- I0(tmp4,env) second[k,] <- c1 * tmp5 } return(list(first=first,second=second)) } ##p.24 #first:i*k*k*k*t, second:i*k*k*t, third:i*k*t, fourth:i*t C_hat1 <- function(tmpY, get_Y_e_V, get_Y_D, get_Y_x1_x2_V0, get_Y_e_e_V, get_e_t, get_U_t, get_U_hat_t, env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size block <- env$block first.tmp <- matrix(0,d.size,block) n1 <- length(get_Y_x1_x2_V0) n2 <- sum(get_Y_x1_x2_V0 == 0) n3 <- length(get_Y_D) n4 <- sum(get_Y_D == 0) n5 <- length(get_e_t) n6 <- sum(get_e_t == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) * (n5 - n6 != 0) for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ tmp2 <- double(block) for(i3 in 1:d.size){ for(i4 in 1:d.size){ tmp1 <- 3 * get_Y_x1_x2_V0[i3,i4,j,] * get_Y_D[i3,] * get_e_t[i4,] tmp2 <- tmp2 + I0(tmp1,env) } } first.tmp[i,] <- first.tmp[i,] + tmpY[i,j,] * tmp2 } } second.tmp <- list() second.tmp$first <- array(0,dim=c(d.size,k.size,k.size,block)) second.tmp$second <- matrix(0,d.size,block) n <- (n1 - n2 != 0) * (n3 - n4 != 0) for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ for(i3 in 1:d.size){ for(i4 in 1:d.size){ for(j1 in 1:d.size){ for(j2 in 1:d.size){ for(j4 in 1:d.size){ tmp4 <- double(block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp3 <- get_Y_x1_x2_V0[i1,i2,j4,] * tmpY[i1,j1,] * tmpY[i2,j2,] tmp4 <- tmp4 + I0(tmp3,env) } } tmp5 <- 6 * get_Y_x1_x2_V0[i3,i4,j,] * get_Y_D[i3,] * tmpY[i4,j4,] * tmp4 tmp6 <- C_c(get_Y_e_V[j1,,],get_Y_e_V[j2,,],tmpY[i,j,],tmp5,env) second.tmp$first[i,,,] <- second.tmp$first[i,,,] + tmp6$first second.tmp$second[i,] <- second.tmp$second[i,] + tmp6$second } } } } } } } third.tmp <- array(0,dim=c(d.size,k.size,block)) fourth.tmp <- array(0,dim=c(d.size,k.size,block)) fifth.tmp <- list() fifth.tmp$first <- array(0,dim=c(d.size,k.size,k.size,block)) fifth.tmp$second <- matrix(0,d.size,block) sixth.tmp <- array(0,dim=c(d.size,k.size,block)) n <- (n1 - n2 != 0) * (n3 - n4 != 0) tmp11 <- matrix(0,r.size,block) for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ for(i3 in 1:d.size){ for(i4 in 1:d.size){ for(j1 in 1:d.size){ for(j4 in 1:d.size){ tmp7 <- I0(get_U_t[j1,j4,],env) tmp8 <- 6 * get_Y_x1_x2_V0[i3,i4,j,] * get_Y_D[i3,] * tmpY[i4,j4,] * tmp7 tmp9 <- C_b(get_Y_e_V[j1,,],tmpY[i,j,],tmp8,env) third.tmp[i,,] <- third.tmp[i,,] + tmp9 tmp10 <- 6 * get_Y_x1_x2_V0[i3,i4,j,] * get_Y_D[i3,] * tmpY[i4,j4,] for(t in 1:block){ tmp11[,t] <- tmp7[t] * get_Y_e_V[j1,,t] } tmp12 <- C_b(tmp11,tmpY[i,j,],tmp10,env) fourth.tmp[i,,] <- fourth.tmp[i,,] - tmp12 tmp13 <- C_c(get_U_hat_t[j1,j4,,],get_Y_e_V[j1,,],tmpY[i,j,],tmp10,env) fifth.tmp$first[i,,,] <- fifth.tmp$first[i,,,] + tmp13$first fifth.tmp$second[i,] <- fifth.tmp$second[i,] + tmp13$second tmp14 <- C_b(get_Y_e_e_V[j4,,],tmpY[i,j,],tmp10/2,env) sixth.tmp[i,,] <- sixth.tmp[i,,] + tmp14 } } } } } } seventh.tmp <- array(0,dim=c(d.size,k.size,block)) n <- (n1 - n2 != 0) * (n5 - n6 != 0) for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ for(i3 in 1:d.size){ for(i4 in 1:d.size){ for(j3 in 1:d.size){ tmp15 <- 3 * get_Y_x1_x2_V0[i3,i4,j,] * tmpY[i3,j3,] * get_e_t[i4,] tmp16 <- C_b(get_Y_e_V[j3,,],tmpY[i,j,],tmp15,env) seventh.tmp[i,,] <- seventh.tmp[i,,] + tmp16 } } } } } eighth.tmp <- list() eighth.tmp$first <- array(0,dim=c(d.size,k.size,k.size,k.size,block)) eighth.tmp$second <- array(0,dim=c(d.size,k.size,block)) n <- n1 - n2 for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ for(i3 in 1:d.size){ for(i4 in 1:d.size){ for(j1 in 1:d.size){ for(j2 in 1:d.size){ for(j4 in 1:d.size){ tmp18 <- double(block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp17 <- get_Y_x1_x2_V0[i1,i2,j4,] * tmpY[i1,j1,] * tmpY[i2,j2,] tmp18 <- tmp18 + I0(tmp17,env) } } tmp19 <- 6 * get_Y_x1_x2_V0[i3,i4,j,] * tmpY[i3,j3,] * tmpY[i4,j4,] * tmp18 tmp20 <- C_e(get_Y_e_V[j3,,],get_Y_e_V[j1,,],get_Y_e_V[j2,,],tmpY[i,j,],tmp19,env) eighth.tmp$first[i,,,,] <- eighth.tmp$first[i,,,,] + tmp20$first eighth.tmp$second[i,,] <- eighth.tmp$second[i,,] + tmp20$second } } } } } } } ninth.tmp <- list() ninth.tmp$first <- array(0,dim=c(d.size,k.size,k.size,block)) ninth.tmp$second <- matrix(0,d.size,block) tenth.tmp <- list() tenth.tmp$first <- array(0,dim=c(d.size,k.size,k.size,block)) tenth.tmp$second <- matrix(0,d.size,block) eleventh.tmp <- list() eleventh.tmp$first <- array(0,dim=c(d.size,k.size,k.size,k.size,block)) eleventh.tmp$second <- array(0,dim=c(d.size,k.size,block)) twelfth.tmp <- list() twelfth.tmp$first <- array(0,dim=c(d.size,k.size,k.size,block)) twelfth.tmp$second <- matrix(0,d.size,block) n <- n1 - n2 tmp25 <- matrix(0,r.size,block) for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ for(i3 in 1:d.size){ for(i4 in 1:d.size){ for(j1 in 1:d.size){ for(j4 in 1:d.size){ tmp21 <- I0(get_U_t[j1,j4,],env) tmp22 <- 6 * get_Y_x1_x2_V0[i3,i4,j,] * tmpY[i3,j3,] * tmpY[i4,j4,] * tmp21 tmp23 <- C_d(get_Y_e_V[j3,,],get_Y_e_V[j1,,],tmpY[i,j,],tmp22,env) ninth.tmp$first[i,,,] <- ninth.tmp$first[i,,,] + tmp23$first ninth.tmp$second[i,] <- ninth.tmp$second[i,] + tmp23$second tmp24 <- 6 * get_Y_x1_x2_V0[i3,i4,j,] * tmpY[i3,j3,] * tmpY[i4,j4,] for(t in 1:block){ tmp25[,t] <- tmp21[t] * get_Y_e_V[j1,,t] } tmp26 <- C_d(get_Y_e_V[j3,,],tmp25,tmpY[i,j,],tmp24,env) tenth.tmp$first[i,,,] <- tenth.tmp$first[i,,,] - tmp26$first tenth.tmp$second[i,] <- tenth.tmp$second[i,] - tmp26$second tmp27 <- C_e(get_Y_e_V[j3,,],get_U_hat_t[j1,j4,,],get_Y_e_V[j1,,],tmpY[i,j,],tmp24,env) eleventh.tmp$first[i,,,,] <- eleventh.tmp$first[i,,,,] + tmp27$first eleventh.tmp$second[i,,] <- eleventh.tmp$second[i,,] + tmp27$second tmp28 <- C_d(get_Y_e_V[j3,,],get_Y_e_e_V[j4,,],tmpY[i,j,],tmp24/2,env) twelfth.tmp$first[i,,,] <- twelfth.tmp$first[i,,,] + tmp28$first twelfth.tmp$second[i,] <- twelfth.tmp$second[i,] + tmp28$second } } } } } } first <- eighth.tmp$first + eleventh.tmp$first second <- second.tmp$first + fifth.tmp$first + ninth.tmp$first + tenth.tmp$first + twelfth.tmp$first third <- third.tmp + fourth.tmp + sixth.tmp + seventh.tmp + eighth.tmp$second + eleventh.tmp$second fourth <- first.tmp + second.tmp$second + fifth.tmp$second + ninth.tmp$second + tenth.tmp$second + twelfth.tmp$second return(list(first=first,second=second,third=third, fourth=fourth)) } #first:i*k*k*t, second:i*k*t, third:i*t C_hat2 <- function(tmpY, get_Y_e_V, get_Y_x1_x2_V0, get_Y_x_e_V0, get_Y_e_e_V, get_e_t, get_U_t, get_U_hat_t, env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size block <- env$block first.tmp <- matrix(0,d.size,block) n1 <- length(get_Y_x1_x2_V0) n2 <- sum(get_Y_x1_x2_V0 == 0) n3 <- length(get_e_t) n4 <- sum(get_e_t == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ tmp2 <- double(block) for(i3 in 1:d.size){ tmp1 <- 3 * get_Y_x_e_V0[i3,j,] * get_e_t[i3,] tmp2 <- tmp2 + I0(tmp1,env) } first.tmp[i,] <- first.tmp[i,] + tmpY[i,j,] * tmp2 } } second.tmp <- list() second.tmp$first <- array(0,dim=c(d.size,k.size,k.size,block)) second.tmp$second <- matrix(0,d.size,block) n5 <- length(get_Y_x_e_V0) n6 <- sum(get_Y_x_e_V0 == 0) n <- (n1 - n2 != 0) * (n5 - n6 != 0) for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ for(i3 in 1:d.size){ for(j1 in 1:d.size){ for(j2 in 1:d.size){ for(j3 in 1:d.size){ tmp4 <- double(block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp3 <- get_Y_x1_x2_V0[i1,i2,j3,] * tmpY[i1,j1,] * tmpY[i2,j2,] tmp4 <- tmp4 + I0(tmp3,env) } } tmp5 <- 6 * get_Y_x_e_V0[i3,j,] * tmpY[i3,j3,] * tmp4 tmp6 <- C_c(get_Y_e_V[j1,,],get_Y_e_V[j2,,],tmpY[i,j,],tmp5,env) second.tmp$first[i,,,] <- second.tmp$first[i,,,] + tmp6$first second.tmp$second[i,] <- second.tmp$second[i,] + tmp6$second } } } } } } third.tmp <- array(0,dim=c(d.size,k.size,block)) fourth.tmp <- array(0,dim=c(d.size,k.size,block)) fifth.tmp <- list() fifth.tmp$first <- array(0,dim=c(d.size,k.size,k.size,block)) fifth.tmp$second <- matrix(0,d.size,block) sixth.tmp <- array(0,dim=c(d.size,k.size,block)) n <- n1 - n2 tmp11 <- matrix(0,r.size,block) for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ for(i3 in 1:d.size){ for(j1 in 1:d.size){ for(j3 in 1:d.size){ tmp7 <- I0(get_U_t[j1,j3,],env) tmp8 <- 6 * get_Y_x_e_V0[i3,j,] * tmpY[i3,j3,] * tmp7 tmp9 <- C_b(get_Y_e_V[j1,,],tmpY[i,j,],tmp8,env) third.tmp[i,,] <- third.tmp[i,,] + tmp9 tmp10 <- 6 * get_Y_x_e_V0[i3,j,] * tmpY[i3,j3,] for(r in 1:r.size){ tmp11[r,] <- tmp7 * get_Y_e_V[j1,r,] } tmp12 <- C_b(tmp11,tmpY[i,j,],tmp10,env) fourth.tmp[i,,] <- fourth.tmp[i,,] - tmp12 tmp13 <- C_c(get_U_hat_t[j1,j3,,],get_Y_e_V[j1,,],tmpY[i,j,],tmp10,env) fifth.tmp$first[i,,,] <- fifth.tmp$first[i,,,] + tmp13$first fifth.tmp$second[i,] <- fifth.tmp$second[i,] + tmp13$second tmp14 <- C_b(get_Y_e_e_V[j3,,],tmpY[i,j,],tmp10/2,env) sixth.tmp[i,,] <- sixth.tmp[i,,] + tmp14 } } } } } first <- second.tmp$first + fifth.tmp$first second <- third.tmp + fourth.tmp + sixth.tmp third <- first.tmp + second.tmp$second + fifth.tmp$second return(list(first=first,second=second,third=third)) } #first:i*k*k*k*t, second:i*k*k*t, third:i*k*t, fourth:i*t C_hat3 <- function(tmpY, get_Y_e_V, get_Y_D, get_Y_x1_x2_x3_V0, env){ d.size <- env$d.size k.size <- env$k.size block <- env$block first.tmp <- matrix(0,d.size,block) n1 <- length(get_Y_x1_x2_x3_V0) n2 <- sum(get_Y_x1_x2_x3_V0 == 0) n3 <- length(get_Y_D) n4 <- sum(get_Y_D == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ tmp2 <- double(block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(i3 in 1:d.size){ tmp1 <- get_Y_x1_x2_x3_V0[i1,i2,i3,j,] * get_Y_D[i1,] * get_Y_D[i2,] * get_Y_D[i3,] tmp2 <- tmp2 + I0(tmp1,env) } } } first.tmp[i,] <- first.tmp[i,] + tmpY[i,j,] * tmp2 } } second.tmp <- array(0,dim=c(d.size,k.size,block)) for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ for(j3 in 1:d.size){ tmp4 <- double(block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(i3 in 1:d.size){ tmp3 <- get_Y_x1_x2_x3_V0[i1,i2,i3,j3,] * get_Y_D[i1,] * get_Y_D[i2,] * tmpY[i3,j3,] tmp4 <- tmp4 + tmp3 } } } tmp5 <- C_b(get_Y_e_V[j3,,],tmpY[i,j,],tmp4,env) second.tmp[i,,] <- second.tmp[i,,] + 3 * tmp5 } } } third.tmp <- list() third.tmp$first <- array(0,dim=c(d.size,k.size,k.size,block)) third.tmp$second <- matrix(0,d.size,block) for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ for(j2 in 1:d.size){ for(j3 in 1:d.size){ tmp7 <- double(block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(i3 in 1:d.size){ tmp6 <- get_Y_x1_x2_x3_V0[i1,i2,i3,j,] * get_Y_D[i1,] * tmpY[i2,j2,] * tmpY[i3,j3,] tmp7 <- tmp7 + tmp6 } } } tmp8 <- C_d(get_Y_e_V[j2,,],get_Y_e_V[j3,,],tmpY[i,j,],tmp7,env) third.tmp$first[i,,,] <- third.tmp$first[i,,,] + 3 * tmp8$first third.tmp$second[i,] <- third.tmp$second[i,] + 3 * tmp8$second } } } } fourth.tmp <- list() fourth.tmp$first <- array(0,dim=c(d.size,k.size,k.size,k.size,block)) fourth.tmp$second <- array(0,dim=c(d.size,k.size,block)) n <- n1 - n2 for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ for(j1 in 1:d.size){ for(j2 in 1:d.size){ for(j3 in 1:d.size){ tmp10 <- double(block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(i3 in 1:d.size){ tmp9 <- get_Y_x1_x2_x3_V0[i1,i2,i3,j,] * tmpY[i1,j1,] * tmpY[i2,j2,] * tmpY[i3,j3,] tmp10 <- tmp10 + tmp9 } } } tmp11 <- C_i(get_Y_e_V[j1,,],get_Y_e_V[j2,,],get_Y_e_V[j3,,],tmpY[i,j,],tmp10,env) fourth.tmp$first[i,,,,] <- fourth.tmp$first[i,,,,] + tmp11$first fourth.tmp$second[i,,] <- fourth.tmp$second[i,,] + tmp11$second } } } } } first <- fourth.tmp$first second <- third.tmp$first third <- second.tmp + fourth.tmp$second fourth <- first.tmp + third.tmp$second return(list(first=first,second=second,third=third, fourth=fourth)) } #first:i*k*k*t, second:i*k*t, third:i*t C_hat4 <- function(tmpY, get_Y_e_V, get_Y_D, get_Y_x1_x2_e_V0, env){ d.size <- env$d.size k.size <- env$k.size block <- env$block n1 <- length(get_Y_x1_x2_e_V0) n2 <- sum(get_Y_x1_x2_e_V0 == 0) n3 <- length(get_Y_D) n4 <- sum(get_Y_D == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) first.tmp <- matrix(0,d.size,block) for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ tmp2 <- double(block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp1 <- 3 * get_Y_x1_x2_e_V0[i1,i2,j,] * get_Y_D[i1,] * get_Y_D[i2,] tmp2 <- tmp2 + I0(tmp1,env) } } first.tmp[i,] <- first.tmp[i,] + tmpY[i,j,] * tmp2 } } second.tmp <- array(0,dim=c(d.size,k.size,block)) for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ for(j2 in 1:d.size){ tmp4 <- double(block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp3 <- 6 * get_Y_x1_x2_e_V0[i1,i2,j,] * get_Y_D[i1,] * tmpY[i2,j2,] tmp4 <- tmp4 + tmp3 } } tmp5 <- C_b(get_Y_e_V[j2,,],tmpY[i,j,],tmp4,env) second.tmp[i,,] <- second.tmp[i,,] + tmp5 } } } third.tmp <- list() third.tmp$first <- array(0,dim=c(d.size,k.size,k.size,block)) third.tmp$second <- matrix(0,d.size,block) n <- n1 - n2 for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ for(j1 in 1:d.size){ for(j2 in 1:d.size){ tmp7 <- double(block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp6 <- 3 * get_Y_x1_x2_e_V0[i1,i2,j,] * tmpY[i1,j1,] * tmpY[i2,j2,] tmp7 <- tmp7 + tmp6 } } tmp8 <- C_d(get_Y_e_V[j1,,],get_Y_e_V[j2,,],tmpY[i,j,],tmp7,env) third.tmp$first[i,,,] <- third.tmp$first[i,,,] + tmp8$first third.tmp$second[i,] <- third.tmp$second[i,] + tmp8$second } } } } first <- third.tmp$first second <- second.tmp third <- first.tmp + third.tmp$second return(list(first=first,second=second,third=third)) } #first:i*k*t, second:i*t C_hat5 <- function(tmpY, get_Y_e_V, get_Y_D, get_Y_x_e_e_V0, env){ d.size <- env$d.size k.size <- env$k.size block <- env$block n1 <- length(get_Y_x_e_e_V0) n2 <- sum(get_Y_x_e_e_V0 == 0) n3 <- length(get_Y_D) n4 <- sum(get_Y_D == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) first.tmp <- matrix(0,d.size,block) for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ tmp2 <- double(block) for(i1 in 1:d.size){ tmp1 <- 3 * get_Y_x_e_e_V0[i1,j,] * get_Y_D[i1,] tmp2 <- tmp2 + I0(tmp1,env) } first.tmp[i,] <- first.tmp[i,] + tmpY[i,j,] * tmp2 } } second.tmp <- array(0,dim=c(d.size,k.size,block)) n <- n1 - n2 for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ for(j1 in 1:d.size){ tmp4 <- double(block) for(i1 in 1:d.size){ tmp3 <- 3 * get_Y_x_e_e_V0[i1,j,] * tmpY[i1,j1,] tmp4 <- tmp4 + tmp3 } tmp5 <- C_b(get_Y_e_V[j1,,],tmpY[i,j,],tmp4,env) second.tmp[i,,] <- second.tmp[i,,] + tmp5 } } } first <- second.tmp second <- first.tmp return(list(first=first,second=second)) } #i*t C_hat6 <- function(tmpY, get_Y_e_e_e_V0, env){ d.size <- env$d.size k.size <- env$k.size block <- env$block result <- matrix(0,d.size,block) n1 <- length(get_Y_e_e_e_V0) n2 <- sum(get_Y_e_e_e_V0 == 0) n <- n1 - n2 for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ tmp1 <- I0(get_Y_e_e_e_V0[j,],env) result[i,] <- result[i,] + tmpY[i,j,] * tmp1 } } return(result) } #first:i*k*k*k*t, second:i*k*k*t, third:i*k*t, fourth:i*t C_hat7 <- function(tmpY, get_Y_e_V, get_Y_x1_x2_V0, get_Y_x_e_V, get_Y_e_e_V, get_e_t, get_U_t, get_U_hat_t, env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size block <- env$block first.tmp <- array(0,dim=c(d.size,k.size,block)) n1 <- length(get_Y_x_e_V) n2 <- sum(get_Y_x_e_V == 0) n3 <- length(get_e_t) n4 <- sum(get_e_t == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) tmp1 <- matrix(0,r.size,block) for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ tmp2 <- matrix(0,r.size,block) for(i3 in 1:d.size){ for(r in 1:r.size){ tmp1[r,] <- 3 * get_Y_x_e_V[i3,j,r,] * get_e_t[i3,] } tmp2 <- tmp2 + tmp1 } tmp3 <- C_f(tmp2,tmpY[i,j,],env) first.tmp[i,,] <- first.tmp[i,,] + tmp3 } } second.tmp <- list() second.tmp$first <- array(0,dim=c(d.size,k.size,k.size,k.size,block)) second.tmp$second <- array(0,dim=c(d.size,k.size,block)) n5 <- length(get_Y_x1_x2_V0) n6 <- sum(get_Y_x1_x2_V0 == 0) n <- (n1 - n2 != 0) * (n5 - n6 != 0) tmp7 <- matrix(0,r.size,block) for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ for(i3 in 1:d.size){ for(j1 in 1:d.size){ for(j2 in 1:d.size){ for(j3 in 1:d.size){ tmp5 <- double(block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp4 <- get_Y_x1_x2_V0[i1,i2,j3,] * tmpY[i1,j1,] * tmpY[i2,j2,] tmp5 <- tmp5 + tmp4 } } tmp6 <- I0(tmp5,env) for(r in 1:r.size){ tmp7[r,] <- 6 * get_Y_x_e_V[i3,j,r,] * tmpY[i3,j3,] * tmp6 } tmp8 <- C_h(tmp7,get_Y_e_V[j1,,],get_Y_e_V[j2,,],tmpY[i,j,],env) second.tmp$first[i,,,,] <- second.tmp$first[i,,,,] + tmp8$first second.tmp$second[i,,] <- second.tmp$second[i,,] + tmp8$second } } } } } } third.tmp <- list() third.tmp$first <- array(0,dim=c(d.size,k.size,k.size,block)) third.tmp$second <- matrix(0,d.size,block) fourth.tmp <- list() fourth.tmp$first <- array(0,dim=c(d.size,k.size,k.size,block)) fourth.tmp$second <- matrix(0,d.size,block) fifth.tmp <- list() fifth.tmp$first <- array(0,dim=c(d.size,k.size,k.size,k.size,block)) fifth.tmp$second <- array(0,dim=c(d.size,k.size,block)) sixth.tmp <- list() sixth.tmp$first <- array(0,dim=c(d.size,k.size,k.size,block)) sixth.tmp$second <- matrix(0,d.size,block) tmp10 <- matrix(0,r.size,block) tmp12 <- matrix(0,r.size,block) tmp13 <- matrix(0,r.size,block) for(i in 1:d.size){ for(j in 1:d.size){ for(i3 in 1:d.size){ for(j1 in 1:d.size){ for(j3 in 1:d.size){ tmp9 <- I0(get_U_t[j1,j3,],env) for(r in 1:r.size){ tmp10[r,] <- 6 * get_Y_x_e_V[i3,j,r,] * tmpY[i3,j3,] * tmp9 } tmp11 <- C_g(tmp9,get_Y_e_V[j1,,],tmpY[i,j,],env) third.tmp$first[i,,,] <- third.tmp$first[i,,,] + tmp11$first third.tmp$second[i,] <- third.tmp$second[i,] + tmp11$second for(r in 1:r.size){ tmp12[r,] <- 6 * get_Y_x_e_V[i3,j,r,] * tmpY[i3,j3,] tmp13[r,] <- tmp9 * get_Y_e_V[j1,r,] } tmp14 <- C_g(tmp12,tmp13,tmpY[i,j,],env) fourth.tmp$first[i,,,] <- fourth.tmp$first[i,,,] - tmp14$first fourth.tmp$second[i,] <- fourth.tmp$second[i,] - tmp14$second tmp15 <- C_h(tmp12,get_U_hat_t[j1,j3,,],get_Y_e_V[j1,,],tmpY[i,j,],env) fifth.tmp$first[i,,,,] <- fifth.tmp$first[i,,,,] + tmp15$first fifth.tmp$second[i,,] <- fifth.tmp$second[i,,] + tmp15$second tmp16 <- C_g(tmp12/2,get_Y_e_e_V[j3,,],tmpY[i,j,],env) sixth.tmp$first[i,,,] <- sixth.tmp$first[i,,,] + tmp16$first sixth.tmp$second[i,] <- sixth.tmp$second[i,] + tmp16$second } } } } } first <- second.tmp$first + fifth.tmp$first second <- third.tmp$first + fourth.tmp$first + sixth.tmp$first third <- first.tmp + second.tmp$second + fifth.tmp$second fourth <- third.tmp$second + fourth.tmp$second + sixth.tmp$second return(list(first=first,second=second,third=third, fourth=fourth)) } #first:i*k*k*k*t, second:i*k*k*t, third:i*k*t, fourth:i*t C_hat8 <- function(tmpY, get_Y_e_V, get_Y_D, get_Y_x1_x2_e_V, env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size block <- env$block first.tmp <- array(0,dim=c(d.size,k.size,block)) n1 <- length(get_Y_x1_x2_e_V) n2 <- sum(get_Y_x1_x2_e_V == 0) n3 <- length(get_Y_D) n4 <- sum(get_Y_D == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) tmp1 <- matrix(0,r.size,block) for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ tmp2 <- matrix(0,r.size,block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(r in 1:r.size){ tmp1[r,] <- 3 * get_Y_x1_x2_e_V[i1,i2,j,r,] * get_Y_D[i1,] * get_Y_D[i2,] } tmp2 <- tmp2 + tmp1 } } tmp3 <- C_f(tmp2,tmpY[i,j,],env) first.tmp[i,,] <- first.tmp[i,,] + tmp3 } } second.tmp <- list() second.tmp$first <- array(0,dim=c(d.size,k.size,k.size,block)) second.tmp$second <- matrix(0,d.size,block) tmp4 <- matrix(0,r.size,block) for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ for(j2 in 1:d.size){ tmp5 <- matrix(0,r.size,block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(r in 1:r.size){ tmp4[r,] <- 6 * get_Y_x1_x2_e_V[i1,i2,j,r,] * get_Y_D[i1,] * tmpY[i2,j2,] } tmp5 <- tmp5 + tmp4 } } tmp6 <- C_g(tmp5,get_Y_e_V[j2,,],tmpY[i,j,],env) second.tmp$first[i,,,] <- second.tmp$first[i,,,] + tmp6$first second.tmp$second[i,] <- second.tmp$second[i,] + tmp6$second } } } third.tmp <- list() third.tmp$first <- array(0,dim=c(d.size,k.size,k.size,k.size,block)) third.tmp$second <- array(0,dim=c(d.size,k.size,block)) n <- n1 - n2 tmp7 <- matrix(0,r.size,block) for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ for(j1 in 1:d.size){ for(j2 in 1:d.size){ tmp8 <- matrix(0,r.size,block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(r in 1:r.size){ tmp7[r,] <- 6 * get_Y_x1_x2_e_V[i1,i2,j,r,] * tmpY[i1,j1,] * tmpY[i2,j2,] } tmp8 <- tmp8 + tmp7 } } tmp9 <- C_h(tmp8,get_Y_e_V[j1,,],get_Y_e_V[j2,,],tmpY[i,j,],env) third.tmp$first[i,,,,] <- third.tmp$first[i,,,,] + tmp9$first third.tmp$second[i,,] <- third.tmp$second[i,,] + tmp9$second } } } } fourth.tmp <- array(0,dim=c(d.size,k.size,block)) tmp11 <- matrix(0,r.size,block) for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ for(j1 in 1:d.size){ for(j2 in 1:d.size){ tmp10 <- b1_b2(get_Y_e_V[j1,,],get_Y_e_V[j2,,],env) tmp12 <- matrix(0,r.size,block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(r in 1:r.size){ tmp11[r,] <- 3 * get_Y_x1_x2_e_V[i1,i2,j,r,] * tmpY[i1,j1,] * tmpY[i2,j2,] * tmp10 } tmp12 <- tmp12 + tmp11 } } tmp13 <- C_f(tmp12,tmpY[i,j,],env) fourth.tmp[i,,] <- fourth.tmp[i,,] + tmp13 } } } } first <- third.tmp$first second <- second.tmp$first third <- first.tmp + third.tmp$second + fourth.tmp fourth <- second.tmp$second return(list(first=first,second=second,third=third, fourth=fourth)) } #first:i*k*k*t, second:i*k*t, third:i*t C_hat9 <- function(tmpY, get_Y_e_V, get_Y_D, get_Y_x_e_e_V, env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size block <- env$block n1 <- length(get_Y_x_e_e_V) n2 <- sum(get_Y_x_e_e_V == 0) n3 <- length(get_Y_D) n4 <- sum(get_Y_D == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) first.tmp <- array(0,dim=c(d.size,k.size,block)) tmp1 <- matrix(0,r.size,block) for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ tmp2 <- matrix(0,r.size,block) for(i1 in 1:d.size){ for(r in 1:r.size){ tmp1[r,] <- get_Y_x_e_e_V[i1,j,r,] * get_Y_D[i1,] } tmp2 <- tmp2 + tmp1 } tmp3 <- C_f(tmp2,tmpY[i,j,],env) first.tmp[i,,] <- first.tmp[i,,] + tmp3 } } second.tmp <- list() second.tmp$first <- array(0,dim=c(d.size,k.size,k.size,block)) second.tmp$second <- matrix(0,d.size,block) n <- n1 - n2 tmp4 <- matrix(0,r.size,block) for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ for(j1 in 1:d.size){ tmp5 <- matrix(0,r.size,block) for(i1 in 1:d.size){ for(r in 1:r.size){ tmp4[r,] <- get_Y_x_e_e_V[i1,j,r,] * tmpY[i1,j1,] } tmp5 <- tmp5 + tmp4 } tmp6 <- C_g(tmp5,get_Y_e_V[j1,,],tmpY[i,j,],env) second.tmp$first[i,,,] <- second.tmp$first[i,,,] + tmp6$first second.tmp$second[i,] <- second.tmp$second[i,] + tmp6$second } } } first <- 3 * second.tmp$first second <- 3 * first.tmp third <- 3 * second.tmp$second return(list(first=first,second=second,third=third)) } #first:i*k*t C_hat10 <- function(tmpY, get_Y_e_e_e_V, env){ d.size <- env$d.size k.size <- env$k.size block <- env$block result <- array(0,dim=c(d.size,k.size,block)) n1 <- length(get_Y_e_e_e_V) n2 <- sum(get_Y_e_e_e_V == 0) n <- n1 - n2 for(i in 1:d.size){ if(n == 0){ break } for(j in 1:d.size){ result[i,,] <- result[i,,] + C_f(get_Y_e_e_e_V[j,,],tmpY[i,j,],env) } } return(result) } #first:i*k*k*k*t, second:i*k*k*t, third:i*k*t, fourth:i*t C0_t <- function(get_C_hat1, get_C_hat2, get_C_hat3, get_C_hat4, get_C_hat5, get_C_hat6, get_C_hat7, get_C_hat8, get_C_hat9, get_C_hat10){ result1 <- get_C_hat1 result2 <- get_C_hat2 result3 <- get_C_hat3 result4 <- get_C_hat4 result5 <- get_C_hat5 result6 <- get_C_hat6 result7 <- get_C_hat7 result8 <- get_C_hat8 result9 <- get_C_hat9 result10 <- get_C_hat10 first <- result1$first + result3$first + result7$first + result8$first second <- result1$second + result2$first + result3$second + result4$first + result7$second + result8$second + result9$first third <- result1$third + result2$second + result3$third + result4$second + result5$first + result7$third + result8$third + result9$second + result10 fourth <- result1$fourth + result2$third + result3$fourth + result4$third + result5$second + result6 + result7$fourth + result8$fourth + result9$third return(list(first=first,second=second,third=third, fourth=fourth)) } ##p.32(II)-1 #first:l*k*k*k*t, second:l*k*k*t, third:l*k*t, fourth:l*t F_tilde2_1_1 <- function(get_x_f0,get_C0_t,env){ d.size <- env$d.size k.size <- env$k.size block <- env$block first <- array(0,dim=c(k.size,k.size,k.size,k.size,block)) second <- array(0,dim=c(k.size,k.size,k.size,block)) third <- array(0,dim=c(k.size,k.size,block)) fourth <- matrix(0,k.size,block) n1 <- length(get_x_f0) n2 <- sum(get_x_f0 == 0) n <- n1 - n2 for(l in 1:k.size){ if(n == 0){ break } for(i in 1:d.size){ for(k1 in 1:k.size){ for(k2 in 1: k.size){ for(k3 in 1:k.size){ tmp1 <- get_x_f0[l,i,] * get_C0_t$first[i,k1,k2,k3,] first[l,k1,k2,k3,] <- first[l,k1,k2,k3,] + I0(tmp1,env)/6 } tmp2 <- get_x_f0[l,i,] * get_C0_t$second[i,k1,k2,] second[l,k1,k2,] <- second[l,k1,k2,] + I0(tmp2,env)/6 } tmp3 <- get_x_f0[l,i,] * get_C0_t$third[i,k1,] third[l,k1,] <- third[l,k1,] + I0(tmp3,env)/6 } tmp4 <- get_x_f0[l,i,] * get_C0_t$fourth[i,] fourth[l,] <- fourth[l,] + I0(tmp4,env)/6 } } return(list(first=first,second=second,third=third, fourth=fourth)) } #first:l*k*k*k*t, second:l*k*k*t, third:l*k*t, fourth:l*t F_tilde2_1_2 <- function(get_x_F,get_C0_t,env){ d.size <- env$d.size k.size <- env$k.size block <- env$block first <- array(0,dim=c(k.size,k.size,k.size,k.size,block)) second <- array(0,dim=c(k.size,k.size,k.size,block)) third <- array(0,dim=c(k.size,k.size,block)) fourth <- matrix(0,k.size,block) n1 <- length(get_x_F) n2 <- sum(get_x_F == 0) n <- n1 - n2 for(l in 1:k.size){ if(n == 0){ break } for(i in 1:d.size){ for(k1 in 1:k.size){ for(k2 in 1: k.size){ for(k3 in 1:k.size){ tmp1 <- get_x_F[l,i,] * get_C0_t$first[i,k1,k2,k3,] first[l,k1,k2,k3,] <- first[l,k1,k2,k3,] + tmp1/6 } tmp2 <- get_x_F[l,i,] * get_C0_t$second[i,k1,k2,] second[l,k1,k2,] <- second[l,k1,k2,] + tmp2/6 } tmp3 <- get_x_F[l,i,] * get_C0_t$third[i,k1,] third[l,k1,] <- third[l,k1,] + tmp3/6 } tmp4 <- get_x_F[l,i,] * get_C0_t$fourth[i,] fourth[l,] <- fourth[l,] + tmp4/6 } } return(list(first=first,second=second,third=third, fourth=fourth)) } ##p.33(II)-2 #first:i3*i4*k*k*k*t, second:i3*i4*k*k*t, third:i3*i4*k*t, fourth:i3*i4*t D_E <- function(tmpY, get_Y_e_V, get_Y_D, get_Y_x1_x2_V0, get_Y_e_e_V, get_e_t, get_U_t, get_U_hat_t, env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size block <- env$block first.tmp <- array(0,dim=c(d.size,d.size,block)) n1 <- length(get_Y_D) n2 <- sum(get_Y_D == 0) n <- n1 - n2 for(i3 in 1:d.size){ if(n == 0){ break } for(i4 in 1:d.size){ first.tmp[i3,i4,] <- get_Y_D[i3,] * get_e_t[i4,] } } second.tmp <- list() second.tmp$first <- array(0,dim=c(d.size,d.size,k.size,k.size,block)) second.tmp$second <- array(0,dim=c(d.size,d.size,block)) n3 <- length(get_Y_x1_x2_V0) n4 <- sum(get_Y_x1_x2_V0 == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) I0_V0_Y_Y <- array(0,dim=c(d.size,d.size,d.size,block)) #j1,j2,j4,t for(j1 in 1:d.size){ if(n3 == n4){ break } for(j2 in 1:d.size){ for(j4 in 1:d.size){ tmp2 <- double(block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp1 <- get_Y_x1_x2_V0[i1,i2,j4,] * tmpY[i1,j1,] * tmpY[i2,j2,] tmp2 <- tmp2 + tmp1 } } I0_V0_Y_Y[j1,j2,j4,] <- I0_V0_Y_Y[j1,j2,j4,] + I0(tmp2,env) } } } for(j1 in 1:d.size){ if(n == 0){ break } for(j2 in 1:d.size){ tmp3 <- I_12(get_Y_e_V[j1,,],get_Y_e_V[j2,,],env) for(i3 in 1:d.size){ for(i4 in 1:d.size){ tmp4 <- double(block) for(j4 in 1:d.size){ tmp4 <- tmp4 + 2 * get_Y_D[i3,] * tmpY[i4,j4,] * I0_V0_Y_Y[j1,j2,j4,] } for(t in 1:block){ second.tmp$first[i3,i4,,,t] <- second.tmp$first[i3,i4,,,t] + tmp4[t] * tmp3$first[,,t] second.tmp$second[i3,i4,t] <- second.tmp$second[i3,i4,t] + tmp4[t] * tmp3$second[t] } } } } } third.tmp <- array(0,dim=c(d.size,d.size,k.size,block)) n5 <- length(get_U_t) n6 <- sum(get_U_t == 0) n <- (n1 - n2 != 0) * (n5 - n6 != 0) I0_U <- array(0,dim=c(d.size,d.size,block)) #j1,j4,t for(j1 in 1:d.size){ if(n5 == n6){ break } for(j4 in 1:d.size){ I0_U[j1,j4,] <- I0(get_U_t[j1,j4,],env) } } for(j1 in 1:d.size){ if(n == 0){ break } tmp5 <- I_1(get_Y_e_V[j1,,],env) for(i3 in 1:d.size){ for(i4 in 1:d.size){ tmp6 <- double(block) for(j4 in 1:d.size){ tmp6 <- tmp6 + 2 * get_Y_D[i3,] * tmpY[i4,j4,] * I0_U[j1,j4,] } for(k in 1:k.size){ third.tmp[i3,i4,k,] <- third.tmp[i3,i4,k,] + tmp6 * tmp5[k,] } } } } fourth.tmp <- array(0,dim=c(d.size,d.size,k.size,block)) tmp7 <- matrix(0,r.size,block) for(j4 in 1:d.size){ if(n == 0){ break } tmp8 <- matrix(0,r.size,block) for(j1 in 1:d.size){ for(r in 1:r.size){ tmp7[r,] <- I0_U[j1,j4,] * get_Y_e_V[j1,r,] } tmp8 <- tmp8 + tmp7 } tmp9 <- I_1(tmp8,env) for(i3 in 1:d.size){ for(i4 in 1:d.size){ for(k in 1:k.size){ fourth.tmp[i3,i4,k,] <- fourth.tmp[i3,i4,k,] - 2 * get_Y_D[i3,] * tmpY[i4,j4,] * tmp9[k,] } } } } fifth.tmp <- list() fifth.tmp$first <- array(0,dim=c(d.size,d.size,k.size,k.size,block)) fifth.tmp$second <- array(0,dim=c(d.size,d.size,block)) n <- n1 - n2 for(j1 in 1:d.size){ if(n == 0){ break } for(j4 in 1:d.size){ tmp10 <- I_12(get_U_hat_t[j1,j4,,],get_Y_e_V[j1,,],env) for(i3 in 1:d.size){ for(i4 in 1:d.size){ for(t in 1:block){ fifth.tmp$first[i3,i4,,,t] <- fifth.tmp$first[i3,i4,,,t] + 2 * get_Y_D[i3,t] * tmpY[i4,j4,t] * tmp10$first[,,t] fifth.tmp$second[i3,i4,t] <- fifth.tmp$second[i3,i4,t] + 2 * get_Y_D[i3,t] * tmpY[i4,j4,t] * tmp10$second[t] } } } } } sixth.tmp <- array(0,dim=c(d.size,d.size,k.size,block)) n7 <- length(get_Y_e_e_V) n8 <- sum(get_Y_e_e_V == 0) n <- (n1 - n2 != 0) * (n7 - n8 != 0) for(j4 in 1:d.size){ if(n == 0){ break } tmp11 <- I_1(get_Y_e_e_V[j4,,],env) for(i3 in 1:d.size){ for(i4 in 1:d.size){ for(k in 1:k.size){ sixth.tmp[i3,i4,k,] <- sixth.tmp[i3,i4,k,] + get_Y_D[i3,] * tmpY[i4,j4,] * tmp11[k,] } } } } seventh.tmp <- array(0,dim=c(d.size,d.size,k.size,block)) n9 <- length(get_e_t) n10 <- sum(get_e_t == 0) n <- n9 - n10 for(j3 in 1:d.size){ if(n == 0){ break } tmp12 <- I_1(get_Y_e_V[j3,,],env) for(i3 in 1:d.size){ for(i4 in 1:d.size){ for(k in 1:k.size){ seventh.tmp[i3,i4,k,] <- seventh.tmp[i3,i4,k,] + tmpY[i3,j3,] * get_e_t[i4,] * tmp12[k,] } } } } eighth.tmp <- list() eighth.tmp$first <- array(0,dim=c(d.size,d.size,k.size,k.size,k.size,block)) eighth.tmp$second <- array(0,dim=c(d.size,d.size,k.size,block)) n <- n3 - n4 for(j1 in 1:d.size){ if(n == 0){ break } for(j2 in 1:d.size){ for(j3 in 1:d.size){ tmp13 <- I_1_23(get_Y_e_V[j3,,],get_Y_e_V[j1,,],get_Y_e_V[j2,,],env) for(i3 in 1:d.size){ for(i4 in 1:d.size){ tmp14 <- double(block) for(j4 in 1:d.size){ tmp14 <- tmp14 + 2 * tmpY[i3,j3,] * tmpY[i4,j4,] * I0_V0_Y_Y[j1,j2,j4,] } for(t in 1:block){ eighth.tmp$first[i3,i4,,,,t] <- eighth.tmp$first[i3,i4,,,,t] + tmp14[t] * tmp13$first[,,,t] eighth.tmp$second[i3,i4,,t] <- eighth.tmp$second[i3,i4,,t] + tmp14[t] * tmp13$second[,t] } } } } } } ninth.tmp <- list() ninth.tmp$first <- array(0,dim=c(d.size,d.size,k.size,k.size,block)) ninth.tmp$second <- array(0,dim=c(d.size,d.size,block)) n <- n5 - n6 for(j1 in 1:d.size){ if(n == 0){ break } for(j3 in 1:d.size){ tmp15 <- I_1_2(get_Y_e_V[j3,,],get_Y_e_V[j1,,],env) for(i3 in 1:d.size){ for(i4 in 1:d.size){ tmp16 <- double(block) for(j4 in 1:d.size){ tmp16 <- tmp16 + 2 * tmpY[i3,j3,] * tmpY[i4,j4,] * I0_U[j1,j4,] } for(t in 1:block){ ninth.tmp$first[i3,i4,,,t] <- ninth.tmp$first[i3,i4,,,t] + tmp16[t] * tmp15$first[,,t] ninth.tmp$second[i3,i4,t] <- ninth.tmp$second[i3,i4,t] + tmp16[t] * tmp15$second[t] } } } } } tenth.tmp <- list() tenth.tmp$first <- array(0,dim=c(d.size,d.size,k.size,k.size,block)) tenth.tmp$second <- array(0,dim=c(d.size,d.size,block)) for(j3 in 1:d.size){ if(n == 0){ break } for(j4 in 1:d.size){ tmp17 <- matrix(0,r.size,block) for(j1 in 1:d.size){ for(r in 1:r.size){ tmp17[r,] <- tmp17[r,] + I0_U[j1,j4,] * get_Y_e_V[j1,r,] } } tmp18 <- I_1_2(get_Y_e_V[j3,,],tmp17,env) for(i3 in 1:d.size){ for(i4 in 1:d.size){ tmp19 <- 2 * tmpY[i3,j3,] * tmpY[i4,j4,] for(t in 1:block){ tenth.tmp$first[i3,i4,,,t] <- tenth.tmp$first[i3,i4,,,t] - tmp19[t] * tmp18$first[,,t] tenth.tmp$second[i3,i4,t] <- tenth.tmp$second[i3,i4,t] - tmp19[t] * tmp18$second[t] } } } } } eleventh.tmp <- list() eleventh.tmp$first <- array(0,dim=c(d.size,d.size,k.size,k.size,k.size,block)) eleventh.tmp$second <- array(0,dim=c(d.size,d.size,k.size,block)) for(j1 in 1:d.size){ for(j3 in 1:d.size){ for(j4 in 1:d.size){ tmp20 <- I_1_23(get_Y_e_V[j3,,],get_U_hat_t[j1,j4,,],get_Y_e_V[j1,,],env) for(i3 in 1:d.size){ for(i4 in 1:d.size){ tmp21 <- 2 * tmpY[i3,j3,] * tmpY[i4,j4,] for(t in 1:block){ eleventh.tmp$first[i3,i4,,,,t] <- eleventh.tmp$first[i3,i4,,,,t] + tmp21[t] * tmp20$first[,,,t] eleventh.tmp$second[i3,i4,,t] <- eleventh.tmp$second[i3,i4,,t] + tmp21[t] * tmp20$second[,t] } } } } } } twelfth.tmp <- list() twelfth.tmp$first <- array(0,dim=c(d.size,d.size,k.size,k.size,block)) twelfth.tmp$second <- array(0,dim=c(d.size,d.size,block)) n <- n7 - n8 for(j3 in 1:d.size){ if(n == 0){ break } for(j4 in 1:d.size){ tmp22 <- I_1_2(get_Y_e_V[j3,,],get_Y_e_e_V[j4,,],env) for(i3 in 1:d.size){ for(i4 in 1:d.size){ tmp23 <- tmpY[i3,j3,] * tmpY[i4,j4,] for(t in 1:block){ twelfth.tmp$first[i3,i4,,,t] <- twelfth.tmp$first[i3,i4,,,t] + tmp23[t] * tmp22$first[,,t] twelfth.tmp$second[i3,i4,t] <- twelfth.tmp$second[i3,i4,t] + tmp23[t] * tmp22$second[t] } } } } } first <- eighth.tmp$first + eleventh.tmp$first second <- second.tmp$first + fifth.tmp$first + ninth.tmp$first + tenth.tmp$first + twelfth.tmp$first third <- third.tmp + fourth.tmp + sixth.tmp + seventh.tmp + eighth.tmp$second + eleventh.tmp$second fourth <- first.tmp + second.tmp$second + fifth.tmp$second + ninth.tmp$second + tenth.tmp$second + twelfth.tmp$second return(list(first=first,second=second,third=third, fourth=fourth)) } #first:l*k*k*k*t, second:l*k*k*t, third:l*k*t, fourth:l*t F_tilde2_2_1 <- function(get_x1_x2_f0,get_D_E,env){ d.size <- env$d.size k.size <- env$k.size block <- env$block first <- array(0,dim=c(k.size,k.size,k.size,k.size,block)) second <- array(0,dim=c(k.size,k.size,k.size,block)) third <- array(0,dim=c(k.size,k.size,block)) fourth <- matrix(0,k.size,block) n1 <- length(get_x1_x2_f0) n2 <- sum(get_x1_x2_f0 == 0) n <- n1 - n2 for(l in 1:k.size){ if(n == 0){ break } for(i3 in 1:d.size){ for(i4 in 1:d.size){ for(k1 in 1:k.size){ for(k2 in 1:k.size){ for(k3 in 1:k.size){ tmp1 <- get_x1_x2_f0[l,i3,i4,] * get_D_E$first[i3,i4,k1,k2,k3,] first[l,k1,k2,k3,] <- first[l,k1,k2,k3,] + I0(tmp1,env)/2 } tmp2 <- get_x1_x2_f0[l,i3,i4,] * get_D_E$second[i3,i4,k1,k2,] second[l,k1,k2,] <- second[l,k1,k2,] + I0(tmp2,env)/2 } tmp3 <- get_x1_x2_f0[l,i3,i4,] * get_D_E$third[i3,i4,k1,] third[l,k1,] <- third[l,k1,] + I0(tmp3,env)/2 } tmp4 <- get_x1_x2_f0[l,i3,i4,] * get_D_E$fourth[i3,i4,] fourth[l,] <- fourth[l,] + I0(tmp4,env)/2 } } } return(list(first=first,second=second,third=third, fourth=fourth)) } #first:l*k*k*k*t, second:l*k*k*t, third:l*k*t, fourth:l*t F_tilde2_2_2 <- function(get_x1_x2_F,get_D_E,env){ d.size <- env$d.size k.size <- env$k.size block <- env$block first <- array(0,dim=c(k.size,k.size,k.size,k.size,block)) second <- array(0,dim=c(k.size,k.size,k.size,block)) third <- array(0,dim=c(k.size,k.size,block)) fourth <- matrix(0,k.size,block) n1 <- length(get_x1_x2_F) n2 <- sum(get_x1_x2_F == 0) n <- n1 - n2 for(l in 1:k.size){ if(n == 0){ break } for(i3 in 1:d.size){ for(i4 in 1:d.size){ for(k1 in 1: k.size){ for(k2 in 1:k.size){ for(k3 in 1:k.size){ tmp1 <- get_x1_x2_F[l,i3,i4,] * get_D_E$first[i4,i3,k1,k2,k3,] first[l,k1,k2,k3,] <- first[l,k1,k2,k3,] + tmp1/2 } tmp2 <- get_x1_x2_F[l,i3,i4,] * get_D_E$second[i4,i3,k1,k2,] second[l,k1,k2,] <- second[l,k1,k2,] + tmp2/2 } tmp3 <- get_x1_x2_F[l,i3,i4,] * get_D_E$third[i4,i3,k1,] third[l,k1,] <- third[l,k1,] + tmp3/2 } tmp4 <- get_x1_x2_F[l,i3,i4,] * get_D_E$fourth[i4,i3,] fourth[l,] <- fourth[l,] + tmp4/2 } } } return(list(first=first,second=second,third=third, fourth=fourth)) } ##p.34(II)-3 #first:l*k*k*t, second:l*k*t, third:l*t F_tilde2_3_1 <- function(tmpY, get_Y_e_V, get_Y_x1_x2_V0, get_Y_e_e_V, get_U_t, get_U_hat_t, get_e_t, get_x_e_f0, env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size block <- env$block h.tmp <- get_x_e_f0/2 first <- array(0,dim=c(k.size,k.size,k.size,block)) second <- array(0,dim=c(k.size,k.size,block)) third <- matrix(0,k.size,block) first.tmp <- matrix(0,k.size,block) n1 <- length(h.tmp) n2 <- sum(h.tmp == 0) n3 <- length(get_e_t) n4 <- sum(get_e_t == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) for(l in 1:k.size){ if(n == 0){ break } tmp1 <- double(block) for(i in 1:d.size){ tmp1 <- tmp1 + h.tmp[l,i,] * get_e_t[i,] } first.tmp[l,] <- I0(tmp1,env) } second.tmp <- list() second.tmp$first <- array(0,dim=c(k.size,k.size,k.size,block)) second.tmp$second <- matrix(0,k.size,block) n5 <- length(get_Y_x1_x2_V0) n6 <- sum(get_Y_x1_x2_V0 == 0) n <- (n1 - n2 != 0) * (n5 - n6 != 0) I0.tmp1 <- array(0,dim=c(k.size,d.size,d.size,block)) #l,j1,j2,t for(l in 1:k.size){ for(j1 in 1:d.size){ for(j2 in 1:d.size){ for(i in 1:d.size){ for(j in 1:d.size){ tmp3 <- double(block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp2 <- get_Y_x1_x2_V0[i1,i2,j,] * tmpY[i1,j1,] * tmpY[i2,j2,] tmp3 <- tmp3 + tmp2 } } tmp4 <- 2 * h.tmp[l,i,] * tmpY[i,j,] * I0(tmp3,env) tmp5 <- I0(tmp4,env) I0.tmp1[l,j1,j2,] <- I0.tmp1[l,j1,j2,] + tmp5 } } } } } for(l in 1:k.size){ if(n == 0){ break } for(j1 in 1:d.size){ for(j2 in 1:d.size){ tmp6 <- I_12(get_Y_e_V[j1,,],get_Y_e_V[j2,,],env) for(t in 1:block){ second.tmp$first[l,,,t] <- second.tmp$first[l,,,t] + I0.tmp1[l,j1,j2,t] * tmp6$first[,,t] second.tmp$second[l,t] <- second.tmp$second[l,t] + I0.tmp1[l,j1,j2,t] * tmp6$second[t] } } } } third.tmp <- list() third.tmp$first <- array(0,dim=c(k.size,k.size,k.size,block)) third.tmp$second <- matrix(0,k.size,block) tmp7 <- matrix(0,r.size,block) for(l in 1:k.size){ if(n == 0){ break } for(j1 in 1:d.size){ for(j2 in 1:d.size){ for(r in 1:r.size){ tmp7[r,] <- I0.tmp1[l,j1,j2,] * get_Y_e_V[j1,r,] } tmp8 <- I_12(tmp7,get_Y_e_V[j2,,],env) for(t in 1:block){ third.tmp$first[l,,,t] <- third.tmp$first[l,,,t] - tmp8$first[,,t] third.tmp$second[l,t] <- third.tmp$second[l,t] - tmp8$second[t] } } } } fourth.tmp <- array(0,dim=c(k.size,k.size,block)) fifth.tmp <- array(0,dim=c(k.size,k.size,block)) n7 <- length(get_U_t) n8 <- sum(get_U_t == 0) n <- (n1 - n2 != 0) * (n7 - n8 != 0) tmp12 <- matrix(0,r.size,block) I0_U <- array(0,dim=c(d.size,d.size,block)) #j1,j,t for(j1 in 1:d.size){ for(j in 1:d.size){ I0_U[j1,j,] <- I0_U[j1,j,] + I0(get_U_t[j1,j,],env) } } for(l in 1:k.size){ if(n == 0){ break } for(j1 in 1:d.size){ tmp9 <- double(block) for(i in 1:d.size){ for(j in 1:d.size){ tmp9 <- tmp9 + 2 * h.tmp[l,i,] * tmpY[i,j,] * I0_U[j1,j,] } } tmp10 <- I0(tmp9,env) tmp11 <- I_1(get_Y_e_V[j1,,],env) for(k in 1:k.size){ fourth.tmp[l,k,] <- fourth.tmp[l,k,] + tmp10 * tmp11[k,] } for(r in 1:r.size){ tmp12[r,] <- tmp10 * get_Y_e_V[j1,r,] } tmp13 <- I_1(tmp12,env) for(k in 1:k.size){ fifth.tmp[l,k,] <- fifth.tmp[l,k,] - tmp13[k,] } } } sixth.tmp <- array(0,dim=c(k.size,k.size,block)) tmp14 <- matrix(0,r.size,block) I0.tmp2 <- array(0,dim=c(k.size,d.size,block)) #l,j,t for(l in 1:k.size){ if(n == 0){ break } for(j in 1:d.size){ for(i in 1:d.size){ I0.tmp2[l,j,] <- I0.tmp2[l,j,] + 2 * h.tmp[l,i,] * tmpY[i,j,] } I0.tmp2[l,j,] <- I0(I0.tmp2[l,j,],env) tmp15 <- matrix(0,k.size,block) for(j1 in 1:d.size){ for(r in 1:r.size){ tmp14[r,] <- I0_U[j1,j,] * get_Y_e_V[j1,r,] } tmp15 <- tmp15 + I_1(tmp14,env) } for(k in 1:k.size){ sixth.tmp[l,k,] <- sixth.tmp[l,k,] - I0.tmp2[l,j,] * tmp15[k,] } } } seventh.tmp <- array(0,dim=c(k.size,k.size,block)) tmp16 <- matrix(0,r.size,block) for(l in 1:k.size){ if(n == 0){ break } tmp17 <- matrix(0,r.size,block) for(j in 1:d.size){ for(j1 in 1:d.size){ for(r in 1:r.size){ tmp16[r,] <- I0.tmp2[l,j,] * I0_U[j1,j,] * get_Y_e_V[j1,r,] } tmp17 <- tmp17 + tmp16 } } seventh.tmp[l,,] <- I_1(tmp17,env) } eighth.tmp <- list() eighth.tmp$first <- array(0,dim=c(k.size,k.size,k.size,block)) eighth.tmp$second <- matrix(0,k.size,block) n <- n1 - n2 for(l in 1:k.size){ if(n == 0){ break } for(j in 1:d.size){ for(j1 in 1:d.size){ tmp18 <- I_12(get_U_hat_t[j1,j,,],get_Y_e_V[j1,,],env) for(t in 1:block){ eighth.tmp$first[l,,,t] <- eighth.tmp$first[l,,,t] + I0.tmp2[l,j,t] * tmp18$first[,,t] eighth.tmp$second[l,t] <- eighth.tmp$second[l,t] + I0.tmp2[l,j,t] * tmp18$second[t] } } } } ninth.tmp <- list() ninth.tmp$first <- array(0,dim=c(k.size,k.size,k.size,block)) ninth.tmp$second <- matrix(0,k.size,block) tmp19 <- matrix(0,r.size,block) for(l in 1:k.size){ if(n == 0){ break } for(j in 1:d.size){ for(j1 in 1:d.size){ for(r in 1:r.size){ tmp19[r,] <- I0.tmp2[l,j,] * get_U_hat_t[j1,j,r,] } tmp20 <- I_12(tmp19,get_Y_e_V[j1,,],env) ninth.tmp$first[l,,,] <- ninth.tmp$first[l,,,] - tmp20$first ninth.tmp$second[l,] <- ninth.tmp$second[l,] - tmp20$second } } } tenth.tmp <- array(0,dim=c(k.size,k.size,block)) n9 <- length(get_Y_e_e_V) n10 <- sum(get_Y_e_e_V == 0) n <- (n1 - n2 != 0) * (n9 - n10 != 0) for(l in 1:k.size){ if(n == 0){ break } for(j in 1:d.size){ tmp21 <- I0.tmp2[l,j,]/2 tmp22 <- I_1(get_Y_e_e_V[j,,],env) for(k in 1:k.size){ tenth.tmp[l,k,] <- tenth.tmp[l,k,] + tmp21 * tmp22[k,] } } } eleventh.tmp <- array(0,dim=c(k.size,k.size,block)) tmp24 <- matrix(0,r.size,block) for(l in 1:k.size){ tmp25 <- matrix(0,r.size,block) for(j in 1:d.size){ tmp23 <- I0.tmp2[l,j,]/2 for(r in 1:r.size){ tmp24[r,] <- tmp23 * get_Y_e_e_V[j,r,] } tmp25 <- tmp25 + tmp24 } eleventh.tmp[l,,] <- - I_1(tmp25,env) } first <- second.tmp$first + third.tmp$first + eighth.tmp$first + ninth.tmp$first second <- fourth.tmp + fifth.tmp + sixth.tmp + seventh.tmp + tenth.tmp + eleventh.tmp third <- first.tmp + second.tmp$second + third.tmp$second + eighth.tmp$second + ninth.tmp$second return(list(first=first,second=second,third=third)) } #first:l*k*k*t, second:l*k*t, third:l*t F_tilde2_3_2 <- function(get_E0_bar, get_x_e_F, env){ d.size <- env$d.size k.size <- env$k.size block <- env$block first <- array(0,dim=c(k.size,k.size,k.size,block)) second <- array(0,dim=c(k.size,k.size,block)) third <- matrix(0,k.size,block) n1 <- length(get_x_e_F) n2 <- sum(get_x_e_F == 0) n <- n1 - n2 for(l in 1:k.size){ if(n == 0){ break } for(i in 1:d.size){ tmp1 <- get_x_e_F[l,i,]/2 for(k1 in 1:k.size){ for(k2 in 1:k.size){ first[l,k1,k2,] <- first[l,k1,k2,] + tmp1 * get_E0_bar$first[i,k1,k2,] } second[l,k1,] <- second[l,k1,] + tmp1 * get_E0_bar$second[i,k1,] } third[l,] <- third[l,] + tmp1 * get_E0_bar$third[i,] } } return(list(first=first,second=second,third=third)) } ##p.34(II)-4 #first:i1*i2*i3*k*k*k*t, second:i1*i2*i3*k*k*t, third:i1*i2*i3*k*t, fourth:i1*i2*i3*t D_a <- function(tmpY, get_Y_e_V, get_Y_D, env){ d.size <- env$d.size k.size <- env$k.size block <- env$block first.tmp <- array(0,dim=c(d.size,d.size,d.size,block)) n1 <- length(get_Y_D) n2 <- sum(get_Y_D == 0) n <- n1 - n2 for(i1 in 1:d.size){ if(n == 0){ break } for(i2 in 1:d.size){ for(i3 in 1:d.size){ first.tmp[i1,i2,i3,] <- get_Y_D[i1,] * get_Y_D[i2,] * get_Y_D[i3,] } } } second.tmp <- array(0,dim=c(d.size,d.size,d.size,k.size,block)) for(j3 in 1:d.size){ if(n == 0){ break } tmp1 <- I_1(get_Y_e_V[j3,,],env) for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(i3 in 1:d.size){ tmp2 <- 3 * get_Y_D[i1,] * get_Y_D[i2,] * tmpY[i3,j3,] for(k in 1:k.size){ second.tmp[i1,i2,i3,k,] <- second.tmp[i1,i2,i3,k,] + tmp2 * tmp1[k,] } } } } } third.tmp <- list() third.tmp$first <- array(0,dim=c(d.size,d.size,d.size,k.size,k.size,block)) third.tmp$second <- array(0,dim=c(d.size,d.size,d.size,block)) for(j2 in 1:d.size){ if(n == 0){ break } for(j3 in 1:d.size){ tmp3 <- I_1_2(get_Y_e_V[j2,,],get_Y_e_V[j3,,],env) for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(i3 in 1:d.size){ tmp4 <- 3 * get_Y_D[i1,] * tmpY[i2,j2,] * tmpY[i3,j3,] for(t in 1:block){ third.tmp$first[i1,i2,i3,,,t] <- third.tmp$first[i1,i2,i3,,,t] + tmp4[t] * tmp3$first[,,t] third.tmp$second[i1,i2,i3,t] <- third.tmp$second[i1,i2,i3,t] + tmp4[t] * tmp3$second[t] } } } } } } fourth.tmp <- list() fourth.tmp$first <- array(0,dim=c(d.size,d.size,d.size,k.size,k.size,k.size,block)) fourth.tmp$second <- array(0,dim=c(d.size,d.size,d.size,k.size,block)) for(j1 in 1:d.size){ for(j2 in 1:d.size){ for(j3 in 1:d.size){ tmp5 <- I_1_2_3(get_Y_e_V[j1,,],get_Y_e_V[j2,,],get_Y_e_V[j3,,],env) for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(i3 in 1:d.size){ tmp6 <- tmpY[i1,j1,] * tmpY[i2,j2,] * tmpY[i3,j3,] for(t in 1:block){ fourth.tmp$first[i1,i2,i3,,,,t] <- fourth.tmp$first[i1,i2,i3,,,,t] + tmp6[t] * tmp5$first[,,,t] fourth.tmp$second[i1,i2,i3,,t] <- fourth.tmp$second[i1,i2,i3,,t] + tmp6[t] * tmp5$second[,t] } } } } } } } first <- fourth.tmp$first second <- third.tmp$first third <- second.tmp + fourth.tmp$second fourth <- first.tmp + third.tmp$second return(list(first=first,second=second,third=third, fourth=fourth)) } #first:i1*i2*k*k*t, second:i1*i2*k*t, third:i1*i2*t D_b <- function(tmpY, get_Y_e_V, get_Y_D, env){ d.size <- env$d.size k.size <- env$k.size block <- env$block first.tmp <- array(0,dim=c(d.size,d.size,block)) n1 <- length(get_Y_D) n2 <- sum(get_Y_D == 0) n <- n1 - n2 for(i1 in 1:d.size){ if(n == 0){ break } for(i2 in 1:d.size){ first.tmp[i1,i2,] <- get_Y_D[i1,] * get_Y_D[i2,] } } second.tmp <- array(0,dim=c(d.size,d.size,k.size,block)) for(j1 in 1:d.size){ if(n == 0){ break } tmp1 <- I_1(get_Y_e_V[j2,,],env) for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp2 <- 2 * get_Y_D[i1,] * tmpY[i2,j2,] for(k in 1:k.size){ second.tmp[i1,i2,k,] <- second.tmp[i1,i2,k,] + tmp2 * tmp1[k,] } } } } third.tmp <- list() third.tmp$first <- array(0,dim=c(d.size,d.size,k.size,k.size,block)) third.tmp$second <- array(0,dim=c(d.size,d.size,block)) for(j1 in 1:d.size){ for(j2 in 1:d.size){ tmp3 <- I_1_2(get_Y_e_V[j1,,],get_Y_e_V[j2,,],env) for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp4 <- tmpY[i1,j1,] * tmpY[i2,j2,] for(t in 1:block){ third.tmp$first[i1,i2,,,t] <- third.tmp$first[i1,i2,,,t] + tmp4[t] * tmp3$first[,,t] third.tmp$second[i1,i2,t] <- third.tmp$second[i1,i2,t] + tmp4[t] * tmp3$second[t] } } } } } first <- third.tmp$first second <- second.tmp third <- first.tmp + third.tmp$second return(list(first=first,second=second,third=third)) } #first:i1*k*t, second:i1*t D_c <- function(tmpY, get_Y_e_V, get_Y_D, env){ d.size <- env$d.size k.size <- env$k.size block <- env$block first.tmp <- get_Y_D second.tmp <- array(0,dim=c(d.size,k.size,block)) for(j1 in 1:d.size){ tmp1 <- I_1(get_Y_e_V[j1,,],env) for(i1 in 1:d.size){ tmp2 <- tmpY[i1,j1,] for(k in 1:k.size){ second.tmp[i1,k,] <- second.tmp[i1,k,] + tmp2 * tmp1[k,] } } } first <- second.tmp second <- first.tmp return(list(first=first,second=second)) } #first:l*k*k*k*t, second:l*k*k*t, third:l*k*t, fourth:l*t F_tilde2_4_1 <- function(get_x1_x2_x3_f0, get_x1_x2_e_f0, get_x_e_e_f0, get_e_e_e_f0, get_D_a, get_D_b, get_D_c, env){ d.size <- env$d.size k.size <- env$k.size block <- env$block first.tmp <- list() first.tmp$first <- array(0,dim=c(k.size,k.size,k.size,k.size,block)) first.tmp$second <- array(0,dim=c(k.size,k.size,k.size,block)) first.tmp$third <- array(0,dim=c(k.size,k.size,block)) first.tmp$fourth <- matrix(0,k.size,block) n1 <- length(get_x1_x2_x3_f0) n2 <- sum(get_x1_x2_x3_f0) n <- n1 - n2 for(l in 1:k.size){ if(n == 0){ break } for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(i3 in 1:d.size){ tmp1 <- get_x1_x2_x3_f0[l,i1,i2,i3,] for(k1 in 1:k.size){ for(k2 in 1:k.size){ for(k3 in 1:k.size){ tmp2 <- tmp1 * get_D_a$first[i1,i2,i3,k1,k2,k3,] first.tmp$first[l,k1,k2,k3,] <- first.tmp$first[l,k1,k2,k3,] + I0(tmp2,env)/6 } tmp3 <- tmp1 * get_D_a$second[i1,i2,i3,k1,k2,] first.tmp$second[l,k1,k2,] <- first.tmp$second[l,k1,k2,] + I0(tmp3,env)/6 } tmp4 <- tmp1 * get_D_a$third[i1,i2,i3,k1,] first.tmp$third[l,k1,] <- first.tmp$third[l,k1,] + I0(tmp4,env)/6 } tmp5 <- tmp1 * get_D_a$fourth[i1,i2,i3,] first.tmp$fourth[l,] <- first.tmp$fourth[l,] + I0(tmp5,env)/6 } } } } second.tmp <- list() second.tmp$first <- array(0,dim=c(k.size,k.size,k.size,block)) second.tmp$second <- array(0,dim=c(k.size,k.size,block)) second.tmp$third <- matrix(0,k.size,block) n3 <- length(get_x1_x2_e_f0) n4 <- sum(get_x1_x2_e_f0 == 0) n <- n3 - n4 for(l in 1:k.size){ if(n == 0){ break } for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp6 <- get_x1_x2_e_f0[l,i1,i2,] for(k1 in 1:k.size){ for(k2 in 1:k.size){ tmp7 <- tmp6 * get_D_b$first[i1,i2,k1,k2,] second.tmp$first[l,k1,k2,] <- second.tmp$first[l,k1,k2,] + I0(tmp7,env)/2 } tmp8 <- tmp6 * get_D_b$second[i1,i2,k1,] second.tmp$second[l,k1,] <- second.tmp$second[l,k1,] + I0(tmp8,env)/2 } tmp9 <- tmp6 * get_D_b$third[i1,i2,] second.tmp$third[l,] <- second.tmp$third[l,] + I0(tmp9,env)/2 } } } third.tmp <- list() third.tmp$first <- array(0,dim=c(k.size,k.size,block)) third.tmp$second <- matrix(0,k.size,block) n5 <- length(get_x_e_e_f0) n6 <- sum(get_x_e_e_f0 == 0) n <- n5 - n6 for(l in 1:k.size){ if(n == 0){ break } for(i1 in 1:d.size){ tmp10 <- get_x_e_e_f0[l,i1,] for(k1 in 1:k.size){ tmp11 <- tmp10 * get_D_c$first[i1,k1,] third.tmp$first[l,k1,] <- third.tmp$first[l,k1,] + I0(tmp11,env)/2 } tmp12 <- tmp10 * get_D_c$second[i1,] third.tmp$second[l,] <- third.tmp$second[l,] + I0(tmp12,env)/2 } } fourth.tmp <- matrix(0,k.size,block) for(l in 1:k.size){ fourth.tmp[l,] <- I0(get_e_e_e_f0[l,],env)/6 } first <- first.tmp$first second <- first.tmp$second + second.tmp$first third <- first.tmp$third + second.tmp$second + third.tmp$first fourth <- first.tmp$fourth + second.tmp$third + third.tmp$second + fourth.tmp return(list(first=first,second=second,third=third, fourth=fourth)) } #first:l*k*k*k*t, second:l*k*k*t, third:l*k*t, fourth:l*t F_tilde2_4_2 <- function(get_x1_x2_x3_F, get_x1_x2_e_F, get_x_e_e_F, get_e_e_e_F, get_D_a, get_D_b, get_D_c, env){ d.size <- env$d.size k.size <- env$k.size block <- env$block first.tmp <- list() first.tmp$first <- array(0,dim=c(k.size,k.size,k.size,k.size,block)) first.tmp$second <- array(0,dim=c(k.size,k.size,k.size,block)) first.tmp$third <- array(0,dim=c(k.size,k.size,block)) first.tmp$fourth <- matrix(0,k.size,block) n1 <- length(get_x1_x2_x3_F) n2 <- sum(get_x1_x2_x3_F == 0) n <- n1 - n2 for(l in 1:k.size){ if(n == 0){ break } for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(i3 in 1:d.size){ tmp1 <- get_x1_x2_x3_F[l,i1,i2,i3,]/6 for(k1 in 1:k.size){ for(k2 in 1:k.size){ for(k3 in 1:k.size){ tmp2 <- tmp1 * get_D_a$first[i1,i2,i3,k1,k2,k3,] first.tmp$first[l,k1,k2,k3,] <- first.tmp$first[l,k1,k2,k3,] + tmp2 } tmp3 <- tmp1 * get_D_a$second[i1,i2,i3,k1,k2,] first.tmp$second[l,k1,k2,] <- first.tmp$second[l,k1,k2,] + tmp3 } tmp4 <- tmp1 * get_D_a$third[i1,i2,i3,k1,] first.tmp$third[l,k1,] <- first.tmp$third[l,k1,] + tmp4 } tmp5 <- tmp1 * get_D_a$fourth[i1,i2,i3,] first.tmp$fourth[l,] <- first.tmp$fourth[l,] + tmp5 } } } } second.tmp <- list() second.tmp$first <- array(0,dim=c(k.size,k.size,k.size,block)) second.tmp$second <- array(0,dim=c(k.size,k.size,block)) second.tmp$third <- matrix(0,k.size,block) n3 <- length(get_x1_x2_e_F) n4 <- sum(get_x1_x2_e_F == 0) n <- n3 - n4 for(l in 1:k.size){ if(n == 0){ break } for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp6 <- get_x1_x2_e_F[l,i1,i2,]/2 for(k1 in 1:k.size){ for(k2 in 1:k.size){ tmp7 <- tmp6 * get_D_b$first[i1,i2,k1,k2,] second.tmp$first[l,k1,k2,] <- second.tmp$first[l,k1,k2,] + tmp7 } tmp8 <- tmp6 * get_D_b$second[i1,i2,k1,] second.tmp$second[l,k1,] <- second.tmp$second[l,k1,] + tmp8 } tmp9 <- tmp6 * get_D_b$third[i1,i2,] second.tmp$third[l,] <- second.tmp$third[l,] + tmp9 } } } third.tmp <- list() third.tmp$first <- array(0,dim=c(k.size,k.size,block)) third.tmp$second <- matrix(0,k.size,block) n5 <- length(get_x_e_e_F) n6 <- sum(get_x_e_e_F == 0) n <- n5 - n6 for(l in 1:k.size){ if(n == 0){ break } for(i1 in 1:d.size){ tmp10 <- get_x_e_e_F[l,i1,]/2 for(k1 in 1:k.size){ tmp11 <- tmp10 * get_D_c$first[i1,k1,] third.tmp$first[l,k1,] <- third.tmp$first[l,k1,] + tmp11 } tmp12 <- tmp10 * get_D_c$second[i1,] third.tmp$second[l,] <- third.tmp$second[l,] + tmp12 } } fourth.tmp <- matrix(0,k.size,block) for(l in 1:k.size){ fourth.tmp[l,] <- I0(get_e_e_e_F[l,],env)/6 } first <- first.tmp$first second <- first.tmp$second + second.tmp$first third <- first.tmp$third + second.tmp$second + third.tmp$first fourth <- first.tmp$fourth + second.tmp$third + third.tmp$second + fourth.tmp return(list(first=first,second=second,third=third, fourth=fourth)) } ##p.36(II)-5 #first:l*k*k*k*t, second:l*k*k*t, third:l*k*t, fourth:l*t F_tilde2_5 <- function(tmpY, get_Y_e_V, get_Y_x1_x2_V0, get_Y_e_e_V, get_e_t, get_U_t, get_U_hat_t, get_x_e_f, env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size block <- env$block first.tmp <- array(0,dim=c(k.size,k.size,block)) n1 <- length(get_x_e_f) n2 <- sum(get_x_e_f == 0) n3 <- length(get_e_t) n4 <- sum(get_e_t == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) tmp1 <- matrix(0,r.size,block) for(l in 1:k.size){ if(n == 0){ break } tmp2 <- matrix(0,r.size,block) for(i in 1:d.size){ for(r in 1:r.size){ tmp1[r,] <- get_x_e_f[l,i,r,] * get_e_t[i,] } tmp2 <- tmp2 + tmp1 } first.tmp[l,,] <- first.tmp[l,,] + I_1(tmp2,env)/2 } second.tmp <- list() second.tmp$first <- array(0,dim=c(k.size,k.size,k.size,k.size,block)) second.tmp$second <- array(0,dim=c(k.size,k.size,block)) n5 <- length(get_Y_x1_x2_V0) n6 <- sum(get_Y_x1_x2_V0 == 0) n <- (n1 - n2 != 0) * (n5 - n6 != 0) tmp5 <- matrix(0,r.size,block) for(l in 1:k.size){ if(n == 0){ break } for(j1 in 1:d.size){ for(j2 in 1:d.size){ tmp6 <- matrix(0,r.size,block) for(j3 in 1:d.size){ for(i3 in 1:d.size){ tmp4 <- double(block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ tmp3 <- get_Y_x1_x2_V0[i1,i2,j3,] * tmpY[i1,j1,] * tmpY[i2,j2,] tmp4 <- tmp4 + I0(tmp3,env) } } for(r in 1:r.size){ tmp5[r,] <- get_x_e_f[l,i3,r,] * tmpY[i3,j3,] * tmp4 } tmp6 <- tmp6 + tmp5 } } tmp7 <- I_123(tmp6,get_Y_e_V[j1,,],get_Y_e_V[j2,,],env) second.tmp$first[l,,,,] <- second.tmp$first[l,,,,] + tmp7$first second.tmp$second[l,,] <- second.tmp$second[l,,] + tmp7$second } } } third.tmp <- list() third.tmp$first <- array(0,dim=c(k.size,k.size,k.size,block)) third.tmp$second <- matrix(0,k.size,block) fourth.tmp <- list() fourth.tmp$first <- array(0,dim=c(k.size,k.size,k.size,block)) fourth.tmp$second <- matrix(0,k.size,block) fifth.tmp <- list() fifth.tmp$first <- array(0,dim=c(k.size,k.size,k.size,k.size,block)) fifth.tmp$second <- array(0,dim=c(k.size,k.size,block)) sixth.tmp <- list() sixth.tmp$first <- array(0,dim=c(k.size,k.size,k.size,block)) sixth.tmp$second <- matrix(0,k.size,block) n5 <- length(get_U_t) n6 <- sum(get_U_t == 0) n <- n5 - n6 f_Y <- array(0,dim=c(k.size,d.size,r.size,block)) #l,j3,r,t for(l in 1:k.size){ if(n == 0){ break } for(j3 in 1:d.size){ for(i3 in 1:d.size){ for(r in 1:r.size){ f_Y[l,j3,r,] <- f_Y[l,j3,r,] + get_x_e_f[l,i3,r,] * tmpY[i3,j3,] } } } } tmp9 <- matrix(0,r.size,block) tmp13 <- matrix(0,r.size,block) for(l in 1:k.size){ if(n == 0){ break } for(j1 in 1:d.size){ tmp10 <- matrix(0,r.size,block) for(j3 in 1:d.size){ tmp8 <- I0(get_U_t[j1,j3,],env) for(r in 1:r.size){ tmp9[r,] <- f_Y[l,j3,r,] * tmp8 } tmp10 <- tmp10 + tmp9 } tmp11 <- I_12(tmp10,get_Y_e_V[j1,,],env) third.tmp$first[l,,,] <- third.tmp$first[l,,,] + tmp11$first third.tmp$second[l,] <- third.tmp$second[l,] + tmp11$second } for(j3 in 1:d.size){ tmp14 <- matrix(0,r.size,block) for(j1 in 1:d.size){ tmp12 <- I0(get_U_t[j1,j3,],env) for(r in 1:r.size){ tmp13[r,] <- tmp12 * get_Y_e_V[j1,r,] } tmp14 <- tmp14 + tmp13 } tmp15 <- I_12(f_Y[l,j3,,],tmp14,env) fourth.tmp$first[l,,,] <- fourth.tmp$first[l,,,] - tmp15$first fourth.tmp$second[l,] <- fourth.tmp$second[l,] - tmp15$second } for(j3 in 1:d.size){ for(j1 in 1:d.size){ tmp16 <- I_123(f_Y[l,j3,,],get_U_hat_t[j1,j3,,],get_Y_e_V[j1,,],env) fifth.tmp$first[l,,,,] <- fifth.tmp$first[l,,,,] + tmp16$first fifth.tmp$second[l,,] <- fifth.tmp$second[l,,] + tmp16$second } tmp17 <- I_12(f_Y[l,j3,,]/2,get_Y_e_e_V[j3,,],env) sixth.tmp$first[l,,,] <- sixth.tmp$first[l,,,] + tmp17$first sixth.tmp$second[l,] <- sixth.tmp$second[l,] + tmp17$second } } first <- second.tmp$first + fifth.tmp$first second <- third.tmp$first + fourth.tmp$first + sixth.tmp$first third <- first.tmp + second.tmp$second + fifth.tmp$second fourth <- third.tmp$second + fourth.tmp$second + sixth.tmp$second return(list(first=first,second=second,third=third, fourth=fourth)) } ##p.36(II)-6 #first:l*k*k*k*t, second:l*k*k*t, third:l*k*t, fourth:l*t F_tilde2_6 <- function(tmpY, get_Y_e_V, get_Y_D, get_x1_x2_e_f, env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size block <- env$block first.tmp <- array(0,dim=c(k.size,k.size,block)) n1 <- length(get_x1_x2_e_f) n2 <- sum(get_x1_x2_e_f == 0) n3 <- length(get_Y_D) n4 <- sum(get_Y_D == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) tmp1 <- matrix(0,r.size,block) for(l in 1:k.size){ if(n == 0){ break } tmp2 <- matrix(0,r.size,block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(r in 1:r.size){ tmp1[r,] <- get_x1_x2_e_f[l,i1,i2,r,] * get_Y_D[i1,] * get_Y_D[i2,] } tmp2 <- tmp2 + tmp1 } } tmp3 <- I_1(tmp2,env)/2 first.tmp[l,,] <- first.tmp[l,,] + tmp3 } second.tmp <- list() second.tmp$first <- array(0,dim=c(k.size,k.size,k.size,block)) second.tmp$second <- matrix(0,k.size,block) tmp4 <- matrix(0,r.size,block) for(l in 1:k.size){ if(n == 0){ break } for(j2 in 1:d.size){ tmp5 <- matrix(0,r.size,block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(r in 1:r.size){ tmp4[r,] <- get_x1_x2_e_f[l,i1,i2,r,] * get_Y_D[i1,] * tmpY[i2,j2,] } tmp5 <- tmp5 + tmp4 } } tmp6 <- I_12(tmp5,get_Y_e_V[j2,,],env) second.tmp$first[l,,,] <- second.tmp$first[l,,,] + tmp6$first second.tmp$second[l,] <- second.tmp$second[l,] + tmp6$second } } third.tmp <- list() third.tmp$first <- array(0,dim=c(k.size,k.size,k.size,k.size,block)) third.tmp$second <- array(0,dim=c(k.size,k.size,block)) n <- n1 - n2 tmp7 <- matrix(0,r.size,block) for(l in 1:k.size){ if(n == 0){ break } for(j1 in 1:d.size){ for(j2 in 1:d.size){ tmp8 <- matrix(0,r.size,block) for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(r in 1:r.size){ tmp7[r,] <- get_x1_x2_e_f[l,i1,i2,r,] * tmpY[i1,j1,] * tmpY[i2,j2,] } tmp8 <- tmp8 + tmp7 } } tmp9 <- I_123(tmp8,get_Y_e_V[j1,,],get_Y_e_V[j2,,],env) third.tmp$first[l,,,,] <- third.tmp$first[l,,,,] + tmp9$first third.tmp$second[l,,] <- third.tmp$second[l,,] + tmp9$second } } } fourth.tmp <- array(0,dim=c(k.size,k.size,block)) tmp11 <- matrix(0,r.size,block) for(l in 1:k.size){ if(n == 0){ break } tmp12 <- matrix(0,r.size,block) for(j1 in 1:d.size){ for(j2 in 1:d.size){ tmp10 <- b1_b2(get_Y_e_V[j1,,],get_Y_e_V[j2,,],env) for(i1 in 1:d.size){ for(i2 in 1:d.size){ for(r in 1:r.size){ tmp11[r,] <- get_x1_x2_e_f[l,i1,i2,r,] * tmpY[i1,j1,] * tmpY[i2,j2,] * tmp10 } tmp12 <- tmp12 + tmp11 } } } } tmp13 <- I_1(tmp12,env)/2 fourth.tmp[l,,] <- fourth.tmp[l,,] + tmp13 } first <- third.tmp$first second <- second.tmp$first third <- first.tmp + third.tmp$second + fourth.tmp fourth <- second.tmp$second return(list(first=first,second=second,third=third, fourth=fourth)) } ##p.36(II)-7 #first:l*k*k*t, second:l*k*t, third:l*t F_tilde2_7 <- function(tmpY, get_Y_e_V, get_Y_D, get_x_e_e_f, env){ d.size <- env$d.size r.size <- env$r.size k.size <- env$k.size block <- env$block first.tmp <- array(0,dim=c(k.size,k.size,block)) n1 <- length(get_x_e_e_f) n2 <- sum(get_x_e_e_f == 0) n3 <- length(get_Y_D) n4 <- sum(get_Y_D == 0) n <- (n1 - n2 != 0) * (n3 - n4 != 0) tmp1 <- matrix(0,r.size,block) for(l in 1:k.size){ if(n == 0){ break } tmp2 <- matrix(0,r.size,block) for(i1 in 1:d.size){ for(r in 1:r.size){ tmp1[r,] <- get_x_e_e_f[l,i1,r,] * get_Y_D[i1,] } tmp2 <- tmp2 + tmp1 } tmp3 <- I_1(tmp2,env)/2 first.tmp[l,,] <- first.tmp[l,,] + tmp3 } second.tmp <- list() second.tmp$first <- array(0,dim=c(k.size,k.size,k.size,block)) second.tmp$second <- matrix(0,k.size,block) n <- n1 - n2 tmp4 <- matrix(0,r.size,block) for(l in 1:k.size){ if(n == 0){ break } for(j1 in 1:d.size){ tmp5 <- matrix(0,r.size,block) for(i1 in 1:d.size){ for(r in 1:r.size){ tmp4[r,] <- get_x_e_e_f[l,i1,r,] * tmpY[i1,j1,] } tmp5 <- tmp5 + tmp4 } tmp6 <- I_12(tmp5/2,get_Y_e_V[j1,,],env) second.tmp$first[l,,,] <- second.tmp$first[l,,,] + tmp6$first second.tmp$second[l,] <- second.tmp$second[l,] + tmp6$second } } first <- second.tmp$first second <- first.tmp third <- second.tmp$second return(list(first=first,second=second,third=third)) } ##p.37(II)-8 #l*k*t F_tilde2_8 <- function(get_e_e_e_f,env){ k.size <- env$k.size block <- env$block result <- array(0,dim=c(k.size,k.size,block)) n1 <- length(get_e_e_e_f) n2 <- sum(get_e_e_e_f == 0) n <- n1 - n2 for(l in 1:k.size){ if(n == 0){ break } result[l,,] <- I_1(get_e_e_e_f[l,,],env)/6 } return(result) } ##p.6(1.19) #first:l*k*k*k*t, second:l*k*k*t, third:l*k*t, fourth:l*t F_tilde2 <- function(get_F_tilde2_1_1, get_F_tilde2_1_2, get_F_tilde2_2_1, get_F_tilde2_2_2, get_F_tilde2_3_1, get_F_tilde2_3_2, get_F_tilde2_4_1, get_F_tilde2_4_2, get_F_tilde2_5, get_F_tilde2_6, get_F_tilde2_7, get_F_tilde2_8){ result1_1 <- get_F_tilde2_1_1 result1_2 <- get_F_tilde2_1_2 result2_1 <- get_F_tilde2_2_1 result2_2 <- get_F_tilde2_2_2 result3_1 <- get_F_tilde2_3_1 result3_2 <- get_F_tilde2_3_2 result4_1 <- get_F_tilde2_4_1 result4_2 <- get_F_tilde2_4_2 result5 <- get_F_tilde2_5 result6 <- get_F_tilde2_6 result7 <- get_F_tilde2_7 result8 <- get_F_tilde2_8 first <- result1_1$first + result1_2$first + result2_1$first + result2_2$first + result4_1$first + result4_2$first + result5$first + result6$first second <- result1_1$second + result1_2$second + result2_1$second + result2_2$second + result3_1$first + result3_2$first + result4_1$second + result4_2$second + result5$second + result6$second + result7$first third <- result1_1$third + result1_2$third + result2_1$third + result2_2$third + result3_1$second + result3_2$second + result4_1$third + result4_2$third + result5$third + result6$third + result7$second + result8 fourth <- result1_1$fourth + result1_2$fourth + result2_1$fourth + result2_2$fourth + result3_1$third + result3_2$third + result4_1$fourth + result4_2$fourth + result5$fourth + result6$fourth + result7$third return(list(first=first,second=second,third=third, fourth=fourth)) } F_tilde2_x <- function(l,x,get_F_tilde2,env){ k.size <- env$k.size block <- env$block first <- array(get_F_tilde2$first[l,,,,], dim=c(k.size,k.size,k.size,block)) result1 <- 0 for(k1 in 1:k.size){ for(k2 in 1:k.size){ for(k3 in 1:k.size){ result1 <- result1 + first[k1,k2,k3,block] * x[k1] * x[k2] * x[k3] } } } second <- array(get_F_tilde2$second[l,,,], dim=c(k.size,k.size,block)) result2 <- 0 for(k1 in 1:k.size){ for(k2 in 1:k.size){ result2 <- result2 + second[k1,k2,block] * x[k1] * x[k2] } } third <- matrix(get_F_tilde2$third[l,,], k.size,block) result3 <- 0 for(k1 in 1:k.size){ result3 <- result3 + third[k1,block] * x[k1] } fourth <- get_F_tilde2$fourth[l,block] result <- result1 + result2 + result3 + fourth return(result) } ##p.38(III) #d*t x_rho <- function(X.t0,tmp.rho,env){ d.size <- env$d.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(d.size,block)) assign(pars[1],0) de.rho <- list() for(i in 1:d.size){ de.rho[[i]] <- parse(text=deparse(D(tmp.rho,state[i]))) } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(i in 1:d.size){ result[i,t] <- eval(de.rho[[i]]) } } return(result) } #t e_rho <- function(X.t0,tmp.rho,env){ d.size <- env$d.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(block)) assign(pars[1],0) tmp <- parse(text=deparse(D(tmp.rho,pars[1]))) for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } result[t] <- eval(tmp) } return(result) } #d*d*t x1_x2_rho <- function(X.t0,tmp.rho,env){ d.size <- env$d.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(d.size,d.size,block)) assign(pars[1],0) dxdx.rho <- list() for(i1 in 1:d.size){ dxdx.rho[[i1]] <- list() for(i2 in 1:d.size){ dxdx.rho[[i1]][[i2]] <- parse(text=deparse(D(D(tmp.rho,state[i2]),state[i1]))) } } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(i1 in 1:d.size){ for(i2 in 1:d.size){ result[i1,i2,t] <- eval(dxdx.rho[[i1]][[i2]]) } } } return(result) } #d*t x_e_rho <- function(X.t0,tmp.rho,env){ d.size <- env$d.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- array(0,dim=c(d.size,block)) assign(pars[1],0) dxde.rho <- list() for(i in 1:d.size){ dxde.rho[[i]] <- parse(text=deparse(D(D(tmp.rho,pars[1]),state[i]))) } for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } for(i in 1:d.size){ result[i,t] <- eval(dxde.rho[[i]]) } } return(result) } #t e_e_rho <- function(X.t0,tmp.rho,env){ d.size <- env$d.size state <- env$state pars <- env$pars block <- env$block my.range <- env$my.range result <- double(block) assign(pars[1],0) tmp <- parse(text=deparse(D(D(tmp.rho,pars[1]),pars[1]))) for(t in 1:block){ for(d in 1:d.size){ assign(state[d],X.t0[my.range[t],d]) } result[t] <- eval(tmp) } return(result) } #numeric scH_0_1 <- function(get_Y_D,get_e_rho,get_x_rho,env){ d.size <- env$d.size block <- env$block result <- - I0(get_e_rho,env)[block] for(i in 1:d.size){ result <- result - I0(get_x_rho[i,] * get_Y_D[i,],env)[block] } return(result) } #d*t/d*r*t scH_1_1 <- function(tmpY,get_Y_e_V,get_x_rho,env){ d.size <- env$d.size block <- env$block coef <- array(0,dim=c(d.size,block)) for(j in 1:d.size){ tmp <- double(block) for(t in 1:block){ tmp[t] <- get_x_rho[,t] %*% tmpY[,j,t] } # # for(i in 1:d.size){ # tmp <- tmp + get_x_rho[i,] * tmpY[i,j,] # } coef[j,] <- I0(tmp,env) } integrand <- get_Y_e_V return(list(coef=coef,integrand=integrand)) } #r*t scH_1_2 <- function(get_scH_1_1,env){ r.size <- env$r.size block <- env$block result <- array(0,dim=c(r.size,block)) coef <- get_scH_1_1$coef integrand <- get_scH_1_1$integrand for(t in 1:block){ for(r in 1:r.size){ result[r,t] <- integrand[,r,t] %*% coef[,t] } } return(result) } F_tilde1H1 <- function(get_F_tilde1,get_scH_0_1,get_scH_1_1,get_scH_1_2,env){ k.size <- env$k.size d.size <- env$d.size r.size <- env$r.size block <- env$block # print(block) coef1 <- get_F_tilde1$result1[[1]][,block] # FIXME: this is broken, should have the same dimension as block but has 2 coef2 <- get_F_tilde1$result2[[1]][,block] coef3 <- get_F_tilde1$result3[[1]][,block] coef4 <- get_F_tilde1$result4[[1]][,block] coef5 <- get_F_tilde1$result5[[1]][,block] coef6 <- get_F_tilde1$result6[[1]][,block] coef7 <- get_F_tilde1$result7[[1]][,block] coef8 <- array(get_F_tilde1$result8[[1]][,,block],dim=c(k.size,d.size)) coef9 <- array(get_F_tilde1$result9[[1]][,,block],dim=c(k.size,d.size)) coef10 <- get_F_tilde1$result10[[1]] coef11 <- array(get_F_tilde1$result11[[1]][,,block],dim=c(k.size,d.size)) coef12 <- get_F_tilde1$result12[[1]] coef13 <- array(get_F_tilde1$result13[[1]][,,block],dim=c(k.size,d.size)) coef14 <- get_F_tilde1$result14[[1]] coef15 <- array(get_F_tilde1$result15[[1]][,,block],dim=c(k.size,d.size)) coef16 <- get_F_tilde1$result16[[1]] coef17 <- array(get_F_tilde1$result17[[1]][,,block],dim=c(k.size,d.size)) coef18 <- array(get_F_tilde1$result18[[1]][,,block],dim=c(k.size,d.size)) coef19 <- array(get_F_tilde1$result19[[1]][,,block],dim=c(k.size,d.size)) coef20 <- array(get_F_tilde1$result20[[1]][,,block],dim=c(k.size,d.size)) coef21 <- array(get_F_tilde1$result21[[1]][,,block],dim=c(k.size,d.size)) coef22 <- array(get_F_tilde1$result22[[1]][,,,block],dim=c(k.size,d.size,d.size)) coef23 <- get_F_tilde1$result23[[1]] coef24 <- array(get_F_tilde1$result24[[1]][,,,block],dim=c(k.size,d.size,d.size)) coef25 <- get_F_tilde1$result25[[1]] coef26 <- array(get_F_tilde1$result26[[1]][,,block],dim=c(k.size,d.size)) coef27 <- get_F_tilde1$result27[[1]] coef28 <- array(get_F_tilde1$result28[[1]][,,,block],dim=c(k.size,d.size,d.size)) coef29 <- array(get_F_tilde1$result29[[1]][,,block],dim=c(k.size,d.size)) coef30 <- array(get_F_tilde1$result30[[1]][,,,block],dim=c(k.size,d.size,d.size)) integrand1 <- get_F_tilde1$result1[[2]] integrand2 <- get_F_tilde1$result2[[2]] integrand3 <- get_F_tilde1$result3[[2]] integrand4 <- get_F_tilde1$result4[[2]] integrand5 <- get_F_tilde1$result5[[2]] integrand6 <- get_F_tilde1$result6[[2]] integrand7 <- get_F_tilde1$result7[[2]] integrand8 <- get_F_tilde1$result8[[2]] integrand9 <- get_F_tilde1$result9[[2]] integrand10 <- get_F_tilde1$result10[[2]] integrand11 <- get_F_tilde1$result11[[2]] integrand12 <- get_F_tilde1$result12[[2]] integrand13 <- get_F_tilde1$result13[[2]] integrand14 <- get_F_tilde1$result14[[2]] integrand15 <- get_F_tilde1$result15[[2]] integrand16 <- get_F_tilde1$result16[[2]] integrand17 <- get_F_tilde1$result17[[2]] integrand18 <- get_F_tilde1$result18[[2]] integrand19 <- get_F_tilde1$result19[[2]] integrand20 <- get_F_tilde1$result20[[2]] integrand21 <- get_F_tilde1$result21[[2]] integrand22 <- get_F_tilde1$result22[[2]] integrand23 <- get_F_tilde1$result23[[2]] integrand24 <- get_F_tilde1$result24[[2]] integrand25 <- get_F_tilde1$result25[[2]] integrand26 <- get_F_tilde1$result26[[2]] integrand27 <- get_F_tilde1$result27[[2]] integrand28 <- get_F_tilde1$result28[[2]] integrand29 <- get_F_tilde1$result29[[2]] integrand30 <- get_F_tilde1$result30[[2]] coef <- get_scH_1_1$coef[,block] integrand <- get_scH_1_1$integrand ##modified obj1 <- coef1 + coef2 + coef3 + coef4 + coef5 + coef6 + coef7 obj2 <- coef10 * integrand10 + coef12 * integrand12 + coef14 * integrand14 + coef16 * integrand16 obj3 <- array(0,dim=c(k.size,r.size,block)) result0 <- obj1 * get_scH_0_1 result1 <- array(0,dim=c(k.size,k.size,block)) result3 <- list() for(l in 1:k.size){ ##modified tmp1 <- coef10 * integrand10[l,,] + coef12 * integrand12[l,,] + coef14 * integrand14[l,,] + coef16 * integrand16[l,,] tmp1 <- obj2[l,,] tmp2 <- array(0,dim=c(r.size,block)) for(j in 1:d.size){ tmp2 <- tmp2 + coef8[l,j] * integrand8[j,,] + coef9[l,j] * integrand9[j,,] + coef11[l,j] * integrand11[j,,] + coef13[l,j] * integrand13[j,,] + coef15[l,j] * integrand15[j,,] + coef17[l,j] * integrand17[j,,] + coef18[l,j] * integrand18[j,,] + coef19[l,j] * integrand19[j,,] + coef20[l,j] * integrand20[j,,] + coef21[l,j] * integrand21[j,,] obj3[l,,] <- as.matrix(obj3[l,,] + coef[j] * integrand[j,,]) } tmp3 <- get_scH_0_1 * (tmp1 + tmp2) + obj1[l] * (obj3[l,,] + get_scH_1_2) result1[l,,] <- I_1(array(tmp3,dim=c(r.size,block)),env) result3[[l]] <- I_1_2(tmp1 + tmp2,obj3[l,,] + get_scH_1_2,env) } result2 <- list() result4 <- list() for(l in 1:k.size){ result2[[l]] <- list(first=array(0,dim=c(k.size,k.size,block)),second=double(block)) result4[[l]] <- list(first=array(0,dim=c(k.size,k.size,k.size,block)),second=array(0,dim=c(k.size,block))) for(j1 in 1:d.size){ tmp23.1 <- I_12(get_scH_0_1 * integrand23[[1]][l,j1,,],integrand23[[2]][j1,,],env) tmp25.1 <- I_12(get_scH_0_1 * integrand25[[1]][l,j1,,],integrand25[[2]][j1,,],env) tmp27.1 <- I_12(get_scH_0_1 * integrand27[[1]][l,j1,,],integrand27[[2]][j1,,],env) result2[[l]]$first <- result2[[l]]$first + coef23 * tmp23.1$first + coef25 * tmp25.1$first + coef27 * tmp27.1$first result2[[l]]$second <- result2[[l]]$second + coef23 * tmp23.1$second + coef25 * tmp25.1$second + coef27 * tmp27.1$second tmp23.2 <- I_1_23(get_scH_1_2 + obj3[l,,],integrand23[[1]][l,j1,,],integrand23[[2]][j1,,],env) tmp25.2 <- I_1_23(get_scH_1_2 + obj3[l,,],integrand25[[1]][l,j1,,],integrand25[[2]][j1,,],env) tmp27.2 <- I_1_23(get_scH_1_2 + obj3[l,,],integrand27[[1]][l,j1,,],integrand27[[2]][j1,,],env) result4[[l]]$first <- result4[[l]]$first + coef23 * tmp23.2$first + coef25 * tmp25.2$first + coef27 * tmp27.2$first result4[[l]]$second <- result4[[l]]$second + coef23 * tmp23.2$second + coef25 * tmp25.2$second + coef27 * tmp27.2$second obj22 <- array(0,dim=c(r.size,block)) obj24 <- array(0,dim=c(r.size,block)) obj26 <- array(0,dim=c(r.size,block)) obj28 <- array(0,dim=c(r.size,block)) obj29 <- array(0,dim=c(r.size,block)) obj30 <- array(0,dim=c(r.size,block)) for(j2 in 1:d.size){ obj22 <- obj22 + coef22[l,j1,j2] * integrand22[[2]][j2,,] obj24 <- obj24 + coef24[l,j1,j2] * integrand24[[2]][j2,,] obj28 <- obj28 + coef28[l,j1,j2] * integrand28[[2]][j2,,] obj30 <- obj30 + coef30[l,j1,j2] * integrand30[[2]][j2,,] obj26 <- obj26 + coef26[l,j2] * integrand26[[1]][j1,j2,,] obj29 <- obj29 + coef29[l,j2] * integrand29[[1]][j1,j2,,] } tmp22.1 <- I_12(get_scH_0_1 * integrand22[[1]][j1,,],array(obj22,dim=c(r.size,block)),env) tmp24.1 <- I_12(get_scH_0_1 * integrand24[[1]][j1,,],array(obj24,dim=c(r.size,block)),env) tmp28.1 <- I_12(get_scH_0_1 * integrand28[[1]][j1,,],array(obj28,dim=c(r.size,block)),env) tmp30.1 <- I_12(get_scH_0_1 * integrand30[[1]][j1,,],array(obj30,dim=c(r.size,block)),env) tmp26.1 <- I_12(get_scH_0_1 * array(obj26,dim=c(r.size,block)),integrand26[[2]][j1,,],env) tmp29.1 <- I_12(get_scH_0_1 * array(obj29,dim=c(r.size,block)),integrand29[[2]][j1,,],env) result2[[l]]$first <- result2[[l]]$first + tmp22.1$first + tmp29.1$first + tmp24.1$first + tmp26.1$first + tmp28.1$first + tmp30.1$first result2[[l]]$second <- result2[[l]]$second + tmp22.1$second + tmp29.1$second + tmp24.1$second + tmp26.1$second + tmp28.1$second + tmp30.1$second tmp22.2 <- I_1_23(get_scH_1_2 + obj3[l,,],integrand22[[1]][j1,,],array(obj22,dim=c(r.size,block)),env) tmp24.2 <- I_1_23(get_scH_1_2 + obj3[l,,],integrand24[[1]][j1,,],array(obj24,dim=c(r.size,block)),env) tmp28.2 <- I_1_23(get_scH_1_2 + obj3[l,,],integrand28[[1]][j1,,],array(obj28,dim=c(r.size,block)),env) tmp30.2 <- I_1_23(get_scH_1_2 + obj3[l,,],integrand30[[1]][j1,,],array(obj30,dim=c(r.size,block)),env) tmp26.2 <- I_1_23(get_scH_1_2 + obj3[l,,],array(obj26,dim=c(r.size,block)),integrand26[[2]][j1,,],env) tmp29.2 <- I_1_23(get_scH_1_2 + obj3[l,,],array(obj29,dim=c(r.size,block)),integrand29[[2]][j1,,],env) result4[[l]]$first <- result4[[l]]$first + tmp22.2$first + tmp29.2$first + tmp24.2$first + tmp26.2$first + tmp28.2$first + tmp30.2$first result4[[l]]$second <- result4[[l]]$second + tmp22.2$second + tmp29.2$second + tmp24.2$second + tmp26.2$second + tmp28.2$second + tmp30.2$second } } return(list(result0=result0,result1=result1,result2=result2, result3=result3,result4=result4)) } F_tilde1H1_x <- function(l,x,get_F_tilde1H1,env){ block <- env$block result0 <- get_F_tilde1H1$result0 result1 <- get_F_tilde1H1$result1 result2 <- get_F_tilde1H1$result2 result3 <- get_F_tilde1H1$result3 result4 <- get_F_tilde1H1$result4 result <- result0[l] + I_1_x(x,result1[l,,],env)[block] + I_12_x(x,result2[[l]],env)[block] + I_1_2_x(x,result3[[l]],env)[block] + I_1_23_x(x,result4[[l]],env)[block] return(result) } ##p.39(IV)-1 #result1:numeric, result2:i*j/i*j;list, result3:numeric/list, #result4:i/i;list, result5:i/i*k*t, result6:numeric/k*t H2_1 <- function(get_scH_0_1,get_scH_1_1,get_scH_1_2,env){ d.size <- env$d.size k.size <- env$k.size r.size <- env$r.size block <- env$block coef <- get_scH_1_1$coef integrand <- get_scH_1_1$integrand result1 <- get_scH_0_1^2 #mathcal{H}_{0;1}^2 result2 <- list() #mathcal{H}_{1;1}^2 result3 <- list() #mathcal{H}_{1;2}^2 result4 <- list() #2mathcal{H}_{0;1}mathcal{H}_{1;1} result5 <- list() #2mathcal{H}_{1;1}mathcal{H}_{1;2} result6 <- list() #2mathcal{H}_{1;2}mathcal{H}_{0;1} result2[[1]] <- matrix(coef[,block],d.size,1) %*% matrix(coef[,block],1,d.size) result3[[1]] <- 1 result4[[1]] <- 2 * get_scH_0_1 * coef[,block] result5[[1]] <- 2 * coef[,block] result6[[1]] <- 2 * get_scH_0_1 result2[[2]] <- array(list(),dim=c(d.size,d.size)) result3[[2]] <- I_1_2(get_scH_1_2,get_scH_1_2,env) result4[[2]] <- array(0,dim=c(d.size,k.size,block)) result5[[2]] <- list() result6[[2]] <- I_1(get_scH_1_2,env) for(i in 1:d.size){ for(j in 1:d.size){ result2[[2]][i,j][[1]] <- I_1_2(integrand[i,,],integrand[j,,],env) } result4[[2]][i,,] <- I_1(integrand[i,,],env) result5[[2]][[i]] <- I_1_2(integrand[i,,],get_scH_1_2,env) } return(list(result1=result1,result2=result2,result3=result3, result4=result4,result5=result5,result6=result6)) } ##p.39(IV)-2 ##remark:I0 is removed #result1:i1*i2*t/i1*i2*k*k*t & i1*i2*k*t & i1*i2*t, #result2:i1*t/i1*k*t & i1*t, #result3:t/numeric H2_2 <- function(get_D_b,get_D_c,get_x_x_rho,get_x_e_rho,get_e_e_rho){ result1 <- list() result2 <- list() result3 <- list() result1[[1]] <- get_x_x_rho result2[[1]] <- 2 * get_x_e_rho result3[[1]] <- get_e_e_rho result1[[2]] <- get_D_b result2[[2]] <- get_D_c result3[[2]] <- 0 return(list(result1=result1,result2=result2,result3=result3)) } ##p.39(IV)-3 ##remark:I0&H0_T is removed #coef:i*t, integrand:i*k*k*t & i*k*t & i*t H2_3 <- function(get_E0_bar,get_x_rho){ return(list(coef=get_x_rho,integrand=get_E0_bar)) } ##p.38(IV) ##remark:H0_T is removed H2_x <- function(x,get_H2_1,get_H2_2,get_H2_3,env){ k.size <- env$k.size d.size <- env$d.size block <- env$block result1_1 <- get_H2_1$result1 result2_1 <- get_H2_1$result2 result3_1 <- get_H2_1$result3 result4_1 <- get_H2_1$result4 result5_1 <- get_H2_1$result5 result6_1 <- get_H2_1$result6 ##modified result1_2 <- get_H2_2$result1 result2_2 <- get_H2_2$result2 # result2_3 <- get_H2_2$result3 result3_2 <- get_H2_2$result3 H2_1_x <- result1_1 + result3_1[[1]] * I_1_2_x(x,result3_1[[2]],env) + result6_1[[1]] * I_1_x(x,as.matrix(result6_1[[2]]),env) # H2_2_x <- I0(result2_3[[1]],env)[block] H2_2_x <- I0(result3_2[[1]],env)[block] H2_3_x <- 0 first1_2 <- array(result1_2[[2]]$first,dim=c(d.size,d.size,k.size,k.size,block)) second1_2 <- array(result1_2[[2]]$second,dim=c(d.size,d.size,k.size,block)) third1_2 <- array(result1_2[[2]]$third,dim=c(d.size,d.size,block)) first2_2 <- result2_2[[2]]$first second2_2 <- result2_2[[2]]$second H2_3coef <- get_H2_3$coef get_E0_bar_x <- as.matrix(E0_bar_x(x,get_H2_3$integrand,env)) for(i in 1:d.size){ for(j in 1:d.size){ H2_1_x <- H2_1_x + result2_1[[1]][i,j] * I_1_2_x(x,result2_1[[2]][i,j][[1]],env)[block] tmp <- list(first=first1_2[i,j,,,],second=third1_2[i,j,]) integrand1 <- I_1_x(x,t(as.matrix(second1_2[i,j,,])),env) + I_12_x(x,tmp,env) H2_2_x <- H2_2_x + I0(result1_2[[1]][i,j,] * integrand1,env)[block] } H2_1_x <- H2_1_x + result4_1[[1]][i] * I_1_2_x(x,result5_1[[2]][[i]],env)[block] + result5_1[[1]][i] * I_1_x(x,t(as.matrix(result4_1[[2]][i,,])),env)[block] integrand2 <- result2_2[[1]][i,] * (second2_2[i,]+I_1_x(x,t(as.matrix(first2_2[i,,])),env)) H2_2_x <- H2_2_x + I0(integrand2,env)[block] H2_3_x <- H2_3_x + I0(H2_3coef[i,] * get_E0_bar_x[i,],env)[block] } result <- H2_1_x/2-H2_2_x/2-H2_3_x/2 return(result) } ft_norm <- function(x,env){ k.size <- env$k.size mu <- env$mu Sigma <- env$Sigma invSigma <- env$invSigma denominator <- (sqrt(2*pi))^k.size * sqrt(det(Sigma)) numerator <- exp(-1/2 * t((x-mu)) %*% invSigma %*% (x-mu)) result <- numerator/denominator return(result) } # p2 <- function(z,get_F_tilde1__2,get_F_tilde2, # get_F_tilde1H1,get_H2_1,get_H2_2,get_H2_3,env){ # # k.size <- env$k.size # delta <- env$delta # mu <- env$mu # Sigma <- env$Sigma # # z.tilde <- z - mu # # first <- 0 # second <- 0 # third <- 0 #added # # if(k.size == 1){ # # first <- (F_tilde1__2_x(1,1,z.tilde+2*delta,get_F_tilde1__2,env) * # dnorm(z+2*delta,mean=mu,sd=sqrt(Sigma)) - # 2 * F_tilde1__2_x(1,1,z.tilde+delta,get_F_tilde1__2,env) * # dnorm(z+delta,mean=mu,sd=sqrt(Sigma)) + # F_tilde1__2_x(1,1,z.tilde,get_F_tilde1__2,env) * # dnorm(z,mean=mu,sd=sqrt(Sigma)))/(delta)^2 # # first <- first/2 # # second <- (F_tilde2_x(1,z.tilde+delta,get_F_tilde2,env) * # dnorm(z+delta,mean=mu,sd=sqrt(Sigma)) - # F_tilde2_x(1,z.tilde,get_F_tilde2,env) * # dnorm(z,mean=mu,sd=sqrt(Sigma)))/delta # ##added:start # obj1 <- F_tilde1H1_x(1,z.tilde+delta,get_F_tilde1H1,env) # # obj2 <- F_tilde1H1_x(1,z.tilde,get_F_tilde1H1,env) # # third <- (obj1 * dnorm(z+delta,mean=mu,sd=sqrt(Sigma)) - # obj2 * dnorm(z,mean=mu,sd=sqrt(Sigma)))/delta # # forth <- H2_x(z.tilde,get_H2_1,get_H2_2,get_H2_3,env) * #dnorm(z,mean=mu,sd=sqrt(Sigma)) #adde#d:end # # }else{ # # tmp1 <- matrix(0,k.size,k.size) # # for(l1 in 1:k.size){ # for(l2 in 1:k.size){ # # dif1 <- numeric(k.size) # dif2 <- numeric(k.size) # dif1[l1] <- dif1[l1] + delta # dif2[l2] <- dif2[l2] + delta # # tmp1[l1,l2] <- (F_tilde1__2_x(l1,l2,z.tilde+dif1+dif2,get_F_tilde1__2,env) * # ft_norm(z+dif1+dif2,env) - # F_tilde1__2_x(l1,l2,z.tilde+dif1,get_F_tilde1__2,env) * # ft_norm(z+dif1,env) - # F_tilde1__2_x(l1,l2,z.tilde+dif2,get_F_tilde1__2,env) * # ft_norm(z+dif2,env) + # F_tilde1__2_x(l1,l2,z.tilde,get_F_tilde1__2,env) * # ft_norm(z,env))/(delta)^2 # # } # } # # first <- sum(tmp1)/2 # # tmp2 <- double(k.size) # tmp3 <- double(k.size) #added # # for(l in 1:k.size){ # # dif <- numeric(k.size) # dif[l] <- dif[l] + delta # # tmp2[l] <- (F_tilde2_x(l,z.tilde+dif,get_F_tilde2,env) * # ft_norm(z+dif,env) - # F_tilde2_x(l,z.tilde,get_F_tilde2,env) * # ft_norm(z,env))/delta # ##added:start # obj1 <- F_tilde1H1_x(l,z.tilde+dif,get_F_tilde1H1,env) # # obj2 <- F_tilde1H1_x(l,z.tilde,get_F_tilde1H1,env) # # tmp3[l] <- (obj1 * ft_norm(z+dif,env) - # obj2 * ft_norm(z,env))/delta ##added:end # # } # # second <- sum(tmp2) # third <- sum(tmp3) #added # forth <- H2_x(z.tilde,get_H2_1,get_H2_2,get_H2_3,env)*ft_norm(z,env) #added # } # # result <- first - second - # third + forth #added # return(result) # } # # # p2_z <- function(z){ # # if(k.size == 1){ # zlen <- length(z) # result <- c() # # for(i in 1:zlen){ # result[i] <- p2(z[i],get_F_tilde1__2,get_F_tilde2, # get_F_tilde1H1,get_H2_1,get_H2_2,get_H2_3,env) # } # }else{ # result <- p2(z,get_F_tilde1__2,get_F_tilde2, # get_F_tilde1H1,get_H2_1,get_H2_2,get_H2_3,env) # } # # return(result) # } # d2.term <- function(){ # # gz_p2 <- function(z){ # # result <- H0 * G(z) * p2_z(z) # return(result) # } # # if(k.size == 1){ # # ztmp <- seq(mu-7*sqrt(Sigma),mu+7*sqrt(Sigma),length=1000) # dt <- ztmp[2] - ztmp[1] # # p2tmp <- gz_p2(ztmp) # # result <- sum(p2tmp) * dt # # }else if(2 <= k.size || k.size <= 20){ # # lambda <- eigen(Sigma)$values # matA <- eigen(Sigma)$vector # # gz_p2 <- function(z){ # tmpz <- matA %*% z # tmp <- H0 * G(tmpz) * p2_z(tmpz) #det(matA) = 1 # return( tmp ) # } # # my.x <- matrix(0,k.size,20^k.size) # dt <- 1 # # for(k in 1:k.size){ # max <- 5 * sqrt(lambda[k]) # min <- -5 * sqrt(lambda[k]) # tmp.x <- seq(min,max,length=20) # dt <- dt * (tmp.x[2] - tmp.x[1]) # my.x[k,] <- rep(tmp.x,each=20^(k.size-k),times=20^(k-1)) # } # # tmp <- 0 # # for(i in 1:20^k.size){ # tmp <- tmp + gz_pi1(my.x[,i]) # } # # tmp <- tmp * dt # # }else{ # stop("length k is too long.") # } # # return(result) # } #
/scratch/gouwar.j/cran-all/cranData/yuima/R/asymptotic_term_third_function.R
########################################################################## # Barndorff-Nielsen and Shephard jump test ########################################################################## setGeneric("bns.test", function(yuima,r=rep(1,4),type="standard",adj=TRUE) standardGeneric("bns.test")) setMethod("bns.test",signature(yuima="yuima"), function(yuima,r=rep(1,4),type="standard",adj=TRUE) bns.test(yuima@data,r,type,adj)) setMethod("bns.test",signature(yuima="yuima.data"), function(yuima,r=rep(1,4),type="standard",adj=TRUE){ # functions for computing the test statistics bns.stat_standard <- function(yuima,r=rep(1,4)){ JV <- mpv(yuima,r=2)-mpv(yuima,r=c(1,1)) IQ <- mpv(yuima,r) return(JV/sqrt((pi^2/4+pi-5)*IQ)) } bns.stat_ratio <- function(yuima,r=rep(1,4),adj=TRUE){ bpv <- mpv(yuima,r=c(1,1)) RJ <- 1-bpv/mpv(yuima,r=2) avar <- mpv(yuima,r)/bpv^2 if(adj){ avar[avar<1] <- 1 } return(RJ/sqrt((pi^2/4+pi-5)*avar)) } bns.stat_log <- function(yuima,r=rep(1,4),adj=TRUE){ bpv <- mpv(yuima,r=c(1,1)) RJ <- log(mpv(yuima,r=2)/bpv) avar <- mpv(yuima,r)/bpv^2 if(adj){ avar[avar<1] <- 1 } return(RJ/sqrt((pi^2/4+pi-5)*avar)) } # main body of the test procedure data <- get.zoo.data(yuima) d.size <- length(data) n <- integer(d.size) for(d in 1:d.size){ n[d] <- sum(!is.na(as.numeric(data[[d]]))) if(n[d]<2) { stop("length of data (w/o NA) must be more than 1") } } switch(type, "standard"="<-"(bns,bns.stat_standard(yuima,r)), "ratio"="<-"(bns,bns.stat_ratio(yuima,r,adj)), "log"="<-"(bns,bns.stat_log(yuima,r,adj))) bns <- sqrt(n)*bns result <- vector(d.size,mode="list") for(d in 1:d.size){ p <- pnorm(bns[d],lower.tail=FALSE) result[[d]] <- list(statistic=c(BNS=bns[d]),p.value=p, method="Barndorff-Nielsen and Shephard jump test", data.names=paste("x",d,sep="")) class(result[[d]]) <- "htest" } return(result) })
/scratch/gouwar.j/cran-all/cranData/yuima/R/bns.test.R
# cce() Cumulative Covariance Estimator # # CumulativeCovarianceEstimator # # returns a matrix of var-cov estimates ######################################################## # functions for the synchronization ######################################################## # refresh time ## data: a list of zoos refresh_sampling <- function(data){ d.size <- length(data) if(d.size>1){ #ser.times <- vector(d.size, mode="list") #ser.times <- lapply(data,time) ser.times <- lapply(lapply(data,"time"),"as.numeric") ser.lengths <- sapply(data,"length") ser.samplings <- vector(d.size, mode="list") #refresh.times <- c() if(0){ tmp <- sapply(ser.times,"[",1) refresh.times[1] <- max(tmp) I <- rep(1,d.size) for(d in 1:d.size){ #ser.samplings[[d]][1] <- max(which(ser.times[[d]]<=refresh.times[1])) while(!(ser.times[[d]][I[d]+1]>refresh.times[1])){ I[d] <- I[d]+1 if((I[d]+1)>ser.lengths[d]){ break } } ser.samplings[[d]][1] <- I[d] } i <- 1 #while(all(sapply(ser.samplings,"[",i)<ser.lengths)){ while(all(I<ser.lengths)){ J <- I tmp <- double(d.size) for(d in 1:d.size){ #tmp[d] <- ser.times[[d]][min(which(ser.times[[d]]>refresh.times[i])) repeat{ J[d] <- J[d] + 1 tmp[d] <- ser.times[[d]][J[d]] if((!(J[d]<ser.lengths))||(tmp[d]>refresh.times[i])){ break } } } i <- i+1 refresh.times[i] <- max(tmp) for(d in 1:d.size){ #ser.samplings[[d]][i] <- max(which(ser.times[[d]]<=refresh.times[i])) while(!(ser.times[[d]][I[d]+1]>refresh.times[i])){ I[d] <- I[d]+1 if((I[d]+1)>ser.lengths[d]){ break } } ser.samplings[[d]][i] <- I[d] } } } MinL <- min(ser.lengths) refresh.times <- double(MinL) refresh.times[1] <- max(sapply(ser.times,"[",1)) #idx <- matrix(.C("refreshsampling", # as.integer(d.size), # integer(d.size), # as.double(unlist(ser.times)), # as.double(refresh.times), # as.integer(append(ser.lengths,0,after=0)), # min(sapply(ser.times,FUN="tail",n=1)), # as.integer(MinL), # result=integer(d.size*MinL))$result,ncol=d.size) idx <- matrix(.C("refreshsampling", as.integer(d.size), integer(d.size), as.double(unlist(ser.times)), as.double(refresh.times), as.integer(ser.lengths), as.integer(diffinv(ser.lengths[-d.size],xi=0)), min(sapply(ser.times,FUN="tail",n=1)), as.integer(MinL), result=integer(d.size*MinL), PACKAGE = "yuima")$result, # PACKAGE is added (YK, Dec 4, 2018) ncol=d.size) result <- vector(d.size, mode="list") for(d in 1:d.size){ #result[[d]] <- data[[d]][ser.samplings[[d]]] result[[d]] <- data[[d]][idx[,d]] } return(result) }else{ return(data) } } # refresh sampling for PHY ## data: a list of zoos refresh_sampling.PHY <- function(data){ d.size <- length(data) if(d.size>1){ ser.times <- lapply(lapply(data,"time"),"as.numeric") ser.lengths <- sapply(data,"length") #refresh.times <- max(sapply(ser.times,"[",1)) ser.samplings <- vector(d.size,mode="list") if(0){ for(d in 1:d.size){ ser.samplings[[d]][1] <- 1 } I <- rep(1,d.size) i <- 1 while(all(I<ser.lengths)){ flag <- integer(d.size) for(d in 1:d.size){ while(I[d]<ser.lengths[d]){ I[d] <- I[d]+1 if(ser.times[[d]][I[d]]>refresh.times[i]){ flag[d] <- 1 ser.samplings[[d]][i+1] <- I[d] break } } } if(any(flag<rep(1,d.size))){ break }else{ i <- i+1 tmp <- double(d.size) for(d in 1:d.size){ tmp[d] <- ser.times[[d]][ser.samplings[[d]][i]] } refresh.times <- append(refresh.times,max(tmp)) } } } MinL <- min(ser.lengths) refresh.times <- double(MinL) refresh.times[1] <- max(sapply(ser.times,"[",1)) #obj <- .C("refreshsamplingphy", # as.integer(d.size), # integer(d.size), # as.double(unlist(ser.times)), # rtimes=as.double(refresh.times), # as.integer(append(ser.lengths,0,after=0)), # min(sapply(ser.times,FUN="tail",n=1)), # as.integer(MinL), # Samplings=integer(d.size*(MinL+1)), # rNum=integer(1)) obj <- .C("refreshsamplingphy", as.integer(d.size), integer(d.size), as.double(unlist(ser.times)), rtimes=as.double(refresh.times), as.integer(ser.lengths), as.integer(diffinv(ser.lengths[-d.size],xi=0)), min(sapply(ser.times,FUN="tail",n=1)), as.integer(MinL), Samplings=integer(d.size*(MinL+1)), rNum=integer(1), PACKAGE = "yuima") # PACKAGE is added (YK, Dec 4, 2018) refresh.times <- obj$rtimes[1:obj$rNum] idx <- matrix(obj$Samplings,ncol=d.size) result <- vector(d.size, mode="list") for(d in 1:d.size){ #result[[d]] <- data[[d]][ser.samplings[[d]]] result[[d]] <- data[[d]][idx[,d]] } return(list(data=result,refresh.times=refresh.times)) }else{ return(list(data=data,refresh.times=as.numeric(time(data[[1]])))) } } # Bibinger's synchronization algorithm ## x: a zoo y: a zoo Bibsynchro <- function(x,y){ xtime <- as.numeric(time(x)) ytime <- as.numeric(time(y)) xlength <- length(xtime) ylength <- length(ytime) N.max <- max(xlength,ylength) if(0){ mu <- integer(N.max) w <- integer(N.max) q <- integer(N.max) r <- integer(N.max) if(xtime[1]<ytime[1]){ I <- 1 while(xtime[I]<ytime[1]){ I <- I+1 if(!(I<xlength)){ break } } #mu0 <- min(which(ytime[1]<=xtime)) mu0 <- I if(ytime[1]<xtime[mu0]){ #q[1] <- mu0-1 q[1] <- mu0 }else{ #q[1] <- mu0 q[1] <- mu0+1 } r[1] <- 2 }else if(xtime[1]>ytime[1]){ I <- 1 while(xtime[I]<ytime[1]){ I <- I+1 if(!(I<xlength)){ break } } #w0 <- min(which(xtime[1]<=ytime)) w0 <- I q[1] <- 2 if(xtime[1]<ytime[w0]){ #r[1] <- w0-1 r[1] <- w0 }else{ #r[1] <- w0 r[1] <- w0+1 } }else{ q[1] <- 2 r[1] <- 2 } i <- 1 repeat{ #while((q[i]<xlength)&&(r[i]<ylength)){ if(xtime[q[i]]<ytime[r[i]]){ #tmp <- which(ytime[r[i]]<=xtime) #if(identical(all.equal(tmp,integer(0)),TRUE)){ # break #} #mu[i] <- min(tmp) if(xtime[xlength]<ytime[r[i]]){ break } I <- q[i] while(xtime[I]<ytime[r[i]]){ I <- I+1 } mu[i] <- I w[i] <- r[i] if(ytime[r[i]]<xtime[mu[i]]){ #q[i+1] <- mu[i]-1 q[i+1] <- mu[i] }else{ #q[i+1] <- mu[i] q[i+1] <- mu[i]+1 } r[i+1] <- r[i]+1 }else if(xtime[q[i]]>ytime[r[i]]){ #tmp <- which(xtime[q[i]]<=ytime) #if(identical(all.equal(tmp,integer(0)),TRUE)){ # break #} if(xtime[q[i]]>ytime[ylength]){ break } mu[i] <- q[i] #w[i] <- min(tmp) I <- r[i] while(xtime[q[i]]>ytime[I]){ I <- I+1 } w[i] <- I q[i+1] <- q[i]+1 if(xtime[q[i]]<ytime[w[i]]){ #r[i+1] <- w[i]-1 r[i+1] <- w[i] }else{ #r[i+1] <- w[i] r[i+1] <- w[i]+1 } }else{ mu[i] <- q[i] w[i] <- r[i] q[i+1] <- q[i]+1 r[i+1] <- r[i]+1 } i <- i+1 if((q[i]>=xlength)||(r[i]>=ylength)){ break } } mu[i] <- q[i] w[i] <- r[i] } sdata <- .C("bibsynchro", as.double(xtime), as.double(ytime), as.integer(xlength), as.integer(ylength), mu=integer(N.max), w=integer(N.max), q=integer(N.max), r=integer(N.max), Num=integer(1), PACKAGE = "yuima") Num <- sdata$Num #return(list(xg=as.numeric(x)[mu[1:i]], # xl=as.numeric(x)[q[1:i]-1], # ygamma=as.numeric(y)[w[1:i]], # ylambda=as.numeric(y)[r[1:i]-1], # num.data=i)) return(list(xg=as.numeric(x)[sdata$mu[1:Num]+1], xl=as.numeric(x)[sdata$q[1:Num]], ygamma=as.numeric(y)[sdata$w[1:Num]+1], ylambda=as.numeric(y)[sdata$r[1:Num]], num.data=Num)) } ############################################################## # functions for tuning parameter ############################################################## set_utime <- function(data){ init.min <- min(as.numeric(sapply(data, FUN = function(x) time(x)[1]))) term.max <- max(as.numeric(sapply(data, FUN = function(x) tail(time(x), n=1)))) return(23400 * (term.max - init.min)) } # Barndorff-Nielsen et al. (2009) RV.sparse <- function(zdata,frequency=1200,utime){ znum <- as.numeric(zdata) ztime <- as.numeric(time(zdata))*utime n.size <- length(zdata) end <- ztime[n.size] grid <- seq(ztime[1],end,by=frequency) n.sparse <- length(grid) #result <- double(frequency) #result <- 0 #I <- rep(1,n.sparse) #for(t in 1:frequency){ # for(i in 1:n.sparse){ # while((ztime[I[i]+1]<=grid[i])&&(I[i]<n.size)){ # I[i] <- I[i]+1 # } # } # result[t] <- sum(diff(znum[I])^2) #result <- result+sum(diff(znum[I])^2) # grid <- grid+rep(1,n.sparse) # if(grid[n.sparse]>end){ # grid <- grid[-n.sparse] # I <- I[-n.sparse] # n.sparse <- n.sparse-1 # } #} K <- floor(end-grid[n.sparse]) + 1 zmat <- matrix(.C("ctsubsampling", as.double(znum), as.double(ztime), as.integer(frequency), as.integer(n.sparse), as.integer(n.size), as.double(grid), result=double(frequency*n.sparse), PACKAGE = "yuima")$result, n.sparse,frequency) result <- double(frequency) result[1:K] <- colSums(diff(zmat[,1:K])^2) result[-(1:K)] <- colSums(diff(zmat[-n.sparse,-(1:K)])^2) return(mean(result)) #return(result/frequency) #return(znum[I]) } Omega_BNHLS <- function(zdata,sec=120,utime){ #q <- ceiling(sec/mean(diff(as.numeric(time(zdata))*utime))) #q <- ceiling(sec*(length(zdata)-1)/utime) ztime <- as.numeric(time(zdata)) q <- ceiling(sec*(length(zdata)-1)/(utime*(tail(ztime,n=1)-head(ztime,n=1)))) obj <- diff(as.numeric(zdata),lag=q) n <- length(obj) #result <- 0 result <- double(q) for(i in 1:q){ tmp <- obj[seq(i,n,by=q)] n.tmp <- sum(tmp!=0) if(n.tmp>0){ result[i] <- sum(tmp^2)/(2*n.tmp) } } #return(result/q) return(mean(result)) } NSratio_BNHLS <- function(zdata,frequency=1200,sec=120,utime){ IV <- RV.sparse(zdata,frequency,utime) Omega <- Omega_BNHLS(zdata,sec,utime) return(Omega/IV) } # Pre-averaging estimator selectParam.pavg <- function(data,utime,frequency=1200,sec=120, a.theta,b.theta,c.theta){ if(missing(utime)) utime <- set_utime(data) NS <- sapply(data,FUN=NSratio_BNHLS,frequency=frequency,sec=sec,utime=utime) coef <- (b.theta+sqrt(b.theta^2+3*a.theta*c.theta))/a.theta return(sqrt(coef*NS)) } selectParam.TSCV <- function(data,utime,frequency=1200,sec=120){ if(missing(utime)) utime <- set_utime(data) NS <- sapply(data,FUN=NSratio_BNHLS,frequency=frequency,sec=sec, utime=utime) return((12*NS)^(2/3)) } selectParam.GME <- function(data,utime,frequency=1200,sec=120){ if(missing(utime)) utime <- set_utime(data) NS <- sapply(data,FUN=NSratio_BNHLS,frequency=frequency,sec=sec, utime=utime) a.theta <- 52/35 #b.theta <- (12/5)*(NS^2+3*NS) b.theta <- (24/5)*(NS^2+2*NS) c.theta <- 48*NS^2 return(sqrt((b.theta+sqrt(b.theta^2+12*a.theta*c.theta))/(2*a.theta))) } selectParam.RK <- function(data,utime,frequency=1200,sec=120,cstar=3.5134){ if(missing(utime)) utime <- set_utime(data) NS <- sapply(data,FUN=NSratio_BNHLS,frequency=frequency,sec=sec, utime=utime) return(cstar*(NS^(2/5))) } if(0){ selectParam_BNHLS <- function(yuima,method,utime=1,frequency=1200,sec=120,kappa=7585/1161216, kappabar=151/20160,kappatilde=1/24,cstar=3.51){ data <- get.zoo.data(yuima) switch(method, "PHY"=selectParam.PHY(data,utime,frequency,sec,kappa,kappabar,kappatilde), "GME"=selectParam.GME(data,utime,frequency,sec), "RK"=selectParam.RK(data,utime,frequency,sec,cstar), "PTHY"=selectParam.PHY(data,utime,frequency,sec,kappa,kappabar,kappatilde)) } } ############################################################### # functions for selecting the threshold functions ############################################################### # local universal thresholding method ## Bipower variation ### x: a zoo lag: a positive integer BPV <- function(x,lag=1){ n <- length(x)-1 dt <- diff(as.numeric(time(x))) obj <- abs(diff(as.numeric(x)))/sqrt(dt) result <- (pi/2)*(obj[1:(n-lag)]*dt[1:(n-lag)])%*%obj[(1+lag):n] return(result) } ## local univaersal thresholding method ### data: a list of zoos coef: a positive number local_univ_threshold <- function(data,coef=5,eps=0.1){ d.size <- length(data) result <- vector(d.size,mode="list") for(d in 1:d.size){ x <- data[[d]] #x <- as.numeric(data[[d]]) n <- length(x)-1 dt <- diff(as.numeric(time(x))) obj <- abs(diff(as.numeric(x)))/sqrt(dt) #dx <- diff(as.numeric(x)) #xtime <- time(x) #xtime <- time(data[[d]]) #if(is.numeric(xtime)){ # r <- max(diff(xtime)) #}else{ # xtime <- as.numeric(xtime) #r <- max(diff(xtime))/(length(x)-1) # r <- max(diff(xtime))/(tail(xtime,n=1)-head(xtime,n=1)) #} #K <- ceiling(sqrt(1/r)) #K <- max(ceiling(sqrt(1/r)),3) K <- max(ceiling(n^0.5),3) coef2 <- coef^2 rho <- double(n+1) #tmp <- coef2*sum(dx^2)*n^(eps-1) #tmp <- double(n+1) #tmp[-(1:(K-1))] <- coef2*n^eps*rollmean(dx^2,k=K-1,align="left") #tmp[1:(K-1)] <- tmp[K] #dx[dx^2>tmp[-(n+1)]] <- 0 if(K<n){ #rho[1:K] <- coef2*(mad(diff(as.numeric(x)[1:(K+1)]))/0.6745)^2 #rho[1:K] <- coef2*2*log(K)*(mad(diff(x[1:(K+1)]))/0.6745)^2 #for(i in (K+1):n){ # rho[i] <- coef2*2*log(length(x))*BPV(x[(i-K):(i-1)])/(K-2) #} #rho[-(1:K)] <- coef2*2*log(n)^(1+eps)* # #rollapply(x[-n],width=K,FUN=BPV,align="left")/(K-2) rho[-(1:(K-1))] <- coef2*n^eps*(pi/2)* rollmean((obj*dt)[-n]*obj[-1],k=K-2,align="left") #rho[-(1:(K-1))] <- coef2*n^eps*rollmean(dx^2,k=K-1,align="left") rho[1:(K-1)] <- rho[K] }else{ #rho <- coef2*(mad(diff(as.numeric(x)))/0.6745)^2 #rho <- coef2*(mad(diff(x))/0.6745)^2 #rho <- coef2*2*log(n)^(1+eps)*BPV(x) rho <- coef2*n^(eps-1)*BPV(x) #rho <- coef2*sum(dx^2)*n^(eps-1) } result[[d]] <- rho[-(n+1)] } return(result) } ################################################################# # functions for calculating the estimators ################################################################# # Hayashi-Yoshida estimator ## data: a list of zoos HY <- function(data) { n.series <- length(data) # allocate memory ser.X <- vector(n.series, mode="list") # data in 'x' ser.times <- vector(n.series, mode="list") # time index in 'x' ser.diffX <- vector(n.series, mode="list") # difference of data for(i in 1:n.series){ # set data and time index ser.X[[i]] <- as.numeric(data[[i]]) # we need to transform data into numeric to avoid problem with duplicated indexes below ser.times[[i]] <- as.numeric(time(data[[i]])) # set difference of the data ser.diffX[[i]] <- diff( ser.X[[i]] ) } # core part of cce cmat <- matrix(0, n.series, n.series) # cov for(i in 1:n.series){ for(j in i:n.series){ #I <- rep(1,n.series) #Checking Starting Point #repeat{ #while((I[i]<length(ser.times[[i]])) && (I[j]<length(ser.times[[j]]))){ # if(ser.times[[i]][I[i]] >= ser.times[[j]][I[j]+1]){ # I[j] <- I[j]+1 # }else if(ser.times[[i]][I[i]+1] <= ser.times[[j]][I[j]]){ # I[i] <- I[i]+1 # }else{ # break # } #} #Main Component if(i!=j){ #while((I[i]<length(ser.times[[i]])) && (I[j]<length(ser.times[[j]]))) { # cmat[j,i] <- cmat[j,i] + (ser.diffX[[i]])[I[i]]*(ser.diffX[[j]])[I[j]] # if(ser.times[[i]][I[i]+1]>ser.times[[j]][I[j]+1]){ # I[j] <- I[j] + 1 # }else if(ser.times[[i]][I[i]+1]<ser.times[[j]][I[j]+1]){ # I[i] <- I[i] +1 # }else{ # I[i] <- I[i]+1 # I[j] <- I[j]+1 # } #} cmat[j,i] <- .C("HayashiYoshida",as.integer(length(ser.times[[i]])), as.integer(length(ser.times[[j]])),as.double(ser.times[[i]]), as.double(ser.times[[j]]),as.double(ser.diffX[[i]]), as.double(ser.diffX[[j]]),value=double(1), PACKAGE = "yuima")$value }else{ cmat[i,j] <- sum(ser.diffX[[i]]^2) } cmat[i,j] <- cmat[j,i] } } return(cmat) } ######################################################### # Modulated realized covariance (Cristensen et al.(2010)) ## data: a list of zoos theta: a positive number ## g: a real-valued function on [0,1] (a weight function) ## delta: a positive number MRC <- function(data,theta,kn,g,delta=0,adj=TRUE){ n.series <- length(data) #if(missing(theta)&&missing(kn)) # theta <- selectParam.pavg(data,utime=utime,a.theta=151/80640, # b.theta=1/96,c.theta=1/6) if(missing(theta)) theta <- 1 cmat <- matrix(0, n.series, n.series) # cov # synchronize the data and take the differences #diffX <- lapply(lapply(refresh_sampling(data),"as.numeric"),"diff") #diffX <- do.call("rbind",diffX) # transform to matrix diffX <- diff(do.call("cbind",lapply(refresh_sampling(data),"as.numeric"))) #Num <- ncol(diffX) Num <- nrow(diffX) if(missing(kn)) kn <- floor(mean(theta)*Num^(1/2+delta)) kn <- min(max(kn,2),Num+1) weight <- sapply((1:(kn-1))/kn,g) psi2.kn <- sum(weight^2) # pre-averaging #myfunc <- function(dx)rollapplyr(dx,width=kn-1,FUN="%*%",weight) #barX <- apply(diffX,1,FUN=myfunc) barX <- filter(diffX,filter=rev(weight),method="c",sides=1)[(kn-1):Num,] cmat <- (Num/(Num-kn+2))*t(barX)%*%barX/psi2.kn if(delta==0){ psi1.kn <- kn^2*sum(diff(c(0,weight,0))^2) scale <- psi1.kn/(theta^2*psi2.kn*2*Num) #cmat <- cmat-scale*diffX%*%t(diffX) cmat <- cmat-scale*t(diffX)%*%diffX if(adj) cmat <- cmat/(1-scale) } return(cmat) } ######################################################### # Pre-averaged Hayashi-Yoshida estimator ## data: a list of zoos theta: a positive number ## g: a real-valued function on [0,1] (a weight function) ## refreshing: a logical value (if TRUE we use the refreshed data) PHY <- function(data,theta,kn,g,refreshing=TRUE,cwise=TRUE){ n.series <- length(data) #if(missing(theta)&&missing(kn)) # theta <- selectParam.pavg(data,a.theta=7585/1161216, # b.theta=151/20160,c.theta=1/24) if(missing(theta)) theta <- 0.15 cmat <- matrix(0, n.series, n.series) # cov if(refreshing){ if(cwise){ if(missing(kn)){# refreshing,cwise,missing kn theta <- matrix(theta,n.series,n.series) theta <- (theta+t(theta))/2 for(i in 1:n.series){ for(j in i:n.series){ if(i!=j){ resample <- refresh_sampling.PHY(list(data[[i]],data[[j]])) dat <- resample$data ser.numX <- length(resample$refresh.times)-1 # set data and time index ser.X <- lapply(dat,"as.numeric") ser.times <- lapply(lapply(dat,"time"),"as.numeric") # set difference of the data ser.diffX <- lapply(ser.X,"diff") # pre-averaging kn <- min(max(ceiling(theta[i,j]*sqrt(ser.numX)),2),ser.numX) weight <- sapply((1:(kn-1))/kn,g) psi.kn <- sum(weight) #ser.barX <- list(rollapplyr(ser.diffX[[1]],width=kn-1,FUN="%*%",weight), # rollapplyr(ser.diffX[[2]],width=kn-1,FUN="%*%",weight)) ser.barX <- list(filter(ser.diffX[[1]],rev(weight),method="c", sides=1)[(kn-1):length(ser.diffX[[1]])], filter(ser.diffX[[2]],rev(weight),method="c", sides=1)[(kn-1):length(ser.diffX[[2]])]) ser.num.barX <- sapply(ser.barX,"length")-1 # core part of cce #start <- kn+1 #end <- 1 #for(k in 1:ser.num.barX[1]){ # while(!(ser.times[[1]][k]<ser.times[[2]][start])&&((start-kn)<ser.num.barX[2])){ # start <- start + 1 # } # while((ser.times[[1]][k+kn]>ser.times[[2]][end+1])&&(end<ser.num.barX[2])){ # end <- end + 1 # } # cmat[i,j] <- cmat[i,j] + ser.barX[[1]][k]*sum(ser.barX[[2]][(start-kn):end]) #} cmat[i,j] <- .C("pHayashiYoshida", as.integer(kn), as.integer(ser.num.barX[1]), as.integer(ser.num.barX[2]), as.double(ser.times[[1]]), as.double(ser.times[[2]]), as.double(ser.barX[[1]]), as.double(ser.barX[[2]]), value=double(1), PACKAGE = "yuima")$value cmat[i,j] <- cmat[i,j]/(psi.kn^2) cmat[j,i] <- cmat[i,j] }else{ diffX <- diff(as.numeric(data[[i]])) kn <- min(max(ceiling(theta[i,i]*sqrt(length(diffX))),2), length(data[[i]])) weight <- sapply((1:(kn-1))/kn,g) psi.kn <- sum(weight) #barX <- rollapplyr(diffX,width=kn-1,FUN="%*%",weight) barX <- filter(diffX,rev(weight),method="c", sides=1)[(kn-1):length(diffX)] tmp <- barX[-length(barX)] #cmat[i,j] <- tmp%*%rollapply(tmp,width=2*(kn-1)+1,FUN="sum",partial=TRUE)/(psi.kn)^2 cmat[i,j] <- tmp%*%rollsum(c(double(kn-1),tmp,double(kn-1)), k=2*(kn-1)+1)/(psi.kn)^2 } } } }else{# refreshing,cwise,not missing kn kn <- matrix(kn,n.series,n.series) for(i in 1:n.series){ for(j in i:n.series){ if(i!=j){ resample <- refresh_sampling.PHY(list(data[[i]],data[[j]])) dat <- resample$data ser.numX <- length(resample$refresh.times)-1 # set data and time index ser.X <- lapply(dat,"as.numeric") ser.times <- lapply(lapply(dat,"time"),"as.numeric") # set difference of the data ser.diffX <- lapply(ser.X,"diff") # pre-averaging knij <- min(max(kn[i,j],2),ser.numX+1) weight <- sapply((1:(knij-1))/knij,g) psi.kn <- sum(weight) #ser.barX <- list(rollapplyr(ser.diffX[[1]],width=knij-1,FUN="%*%",weight), # rollapplyr(ser.diffX[[2]],width=knij-1,FUN="%*%",weight)) ser.barX <- list(filter(ser.diffX[[1]],rev(weight),method="c", sides=1)[(knij-1):length(ser.diffX[[1]])], filter(ser.diffX[[2]],rev(weight),method="c", sides=1)[(knij-1):length(ser.diffX[[2]])]) ser.num.barX <- sapply(ser.barX,"length")-1 # core part of cce #start <- knij+1 #end <- 1 #for(k in 1:ser.num.barX[1]){ # while(!(ser.times[[1]][k]<ser.times[[2]][start])&&((start-knij)<ser.num.barX[2])){ # start <- start + 1 # } # while((ser.times[[1]][k+knij]>ser.times[[2]][end+1])&&(end<ser.num.barX[2])){ # end <- end + 1 # } # cmat[i,j] <- cmat[i,j] + ser.barX[[1]][k]*sum(ser.barX[[2]][(start-knij):end]) #} cmat[i,j] <- .C("pHayashiYoshida", as.integer(knij), as.integer(ser.num.barX[1]), as.integer(ser.num.barX[2]), as.double(ser.times[[1]]), as.double(ser.times[[2]]), as.double(ser.barX[[1]]), as.double(ser.barX[[2]]), value=double(1), PACKAGE = "yuima")$value cmat[i,j] <- cmat[i,j]/(psi.kn^2) cmat[j,i] <- cmat[i,j] }else{ diffX <- diff(as.numeric(data[[i]])) # pre-averaging kni <- min(max(kn[i,i],2),length(data[[i]])) weight <- sapply((1:(kni-1))/kni,g) psi.kn <- sum(weight) #barX <- rollapplyr(diffX,width=kni-1,FUN="%*%",weight) barX <- filter(diffX,rev(weight),method="c", sides=1)[(kni-1):length(diffX)] tmp <- barX[-length(barX)] # core part of cce #cmat[i,j] <- tmp%*%rollapply(tmp,width=2*(kni-1)+1,FUN="sum",partial=TRUE)/(psi.kn)^2 cmat[i,j] <- tmp%*%rollsum(c(double(kni-1),tmp,double(kni-1)), k=2*(kni-1)+1)/(psi.kn)^2 } } } } }else{# refreshing,non-cwise # synchronize the data resample <- refresh_sampling.PHY(data) data <- resample$data ser.numX <- length(resample$refresh.times)-1 # if missing kn, we choose it following Barndorff-Nielsen et al. (2011) if(missing(kn)){ kn <- min(max(ceiling(mean(theta)*sqrt(ser.numX)),2),ser.numX+1) } kn <- kn[1] weight <- sapply((1:(kn-1))/kn,g) # allocate memory ser.X <- vector(n.series, mode="list") # data in 'x' ser.times <- vector(n.series, mode="list") # time index in 'x' ser.diffX <- vector(n.series, mode="list") # difference of data ser.barX <- vector(n.series, mode="list") # pre-averaged data ser.num.barX <- integer(n.series) for(i in 1:n.series){ # set data and time index ser.X[[i]] <- as.numeric(data[[i]]) # we need to transform data into numeric to avoid problem with duplicated indexes below ser.times[[i]] <- as.numeric(time(data[[i]])) # set difference of the data ser.diffX[[i]] <- diff( ser.X[[i]] ) # pre-averaging #ser.barX[[i]] <- rollapplyr(ser.diffX[[i]],width=kn-1,FUN="%*%",weight) ser.barX[[i]] <- filter(ser.diffX[[i]],rev(weight),method="c", sides=1)[(kn-1):length(ser.diffX[[i]])] ser.num.barX[i] <- length(ser.barX[[i]])-1 } # core part of cce for(i in 1:n.series){ for(j in i:n.series){ if(i!=j){ #start <- kn+1 #end <- 1 #for(k in 1:ser.num.barX[i]){ # while(!(ser.times[[i]][k]<ser.times[[j]][start])&&((start-kn)<ser.num.barX[j])){ # start <- start + 1 # } # while((ser.times[[i]][k+kn]>ser.times[[j]][end+1])&&(end<ser.num.barX[j])){ # end <- end + 1 # } # cmat[i,j] <- cmat[i,j] + ser.barX[[i]][k]*sum(ser.barX[[j]][(start-kn):end]) #} cmat[i,j] <- .C("pHayashiYoshida", as.integer(kn), as.integer(ser.num.barX[i]), as.integer(ser.num.barX[j]), as.double(ser.times[[i]]), as.double(ser.times[[j]]), as.double(ser.barX[[i]]), as.double(ser.barX[[j]]), value=double(1), PACKAGE = "yuima")$value cmat[j,i] <- cmat[i,j] }else{ tmp <- ser.barX[[i]][1:ser.num.barX[i]] #cmat[i,j] <- tmp%*%rollapply(tmp,width=2*(kn-1)+1,FUN="sum",partial=TRUE) cmat[i,j] <- tmp%*%rollsum(c(double(kn-1),tmp,double(kn-1)), k=2*(kn-1)+1) } } } psi.kn <- sum(weight) cmat <- cmat/(psi.kn^2) } }else{# non-refreshing if(cwise){# non-refreshing,cwise theta <- matrix(theta,n.series,n.series) theta <- (theta+t(theta))/2 if(missing(kn)){ ntmp <- matrix(sapply(data,"length"),n.series,n.series) ntmp <- ntmp+t(ntmp) diag(ntmp) <- diag(ntmp)/2 kn <- ceiling(theta*sqrt(ntmp)) kn[kn<2] <- 2 # kn must be larger than 1 } kn <- matrix(kn,n.series,n.series) for(i in 1:n.series){ for(j in i:n.series){ if(i!=j){ dat <- list(data[[i]],data[[j]]) # set data and time index ser.X <- lapply(dat,"as.numeric") ser.times <- lapply(lapply(dat,"time"),"as.numeric") # set difference of the data ser.diffX <- lapply(ser.X,"diff") # pre-averaging knij <- min(kn[i,j],sapply(ser.X,"length")) # kn must be less than the numbers of the observations weight <- sapply((1:(knij-1))/knij,g) #ser.barX <- list(rollapplyr(ser.diffX[[1]],width=knij-1,FUN="%*%",weight), # rollapplyr(ser.diffX[[2]],width=knij-1,FUN="%*%",weight)) ser.barX <- list(filter(ser.diffX[[1]],rev(weight),method="c", sides=1)[(knij-1):length(ser.diffX[[1]])], filter(ser.diffX[[2]],rev(weight),method="c", sides=1)[(knij-1):length(ser.diffX[[2]])]) ser.num.barX <- sapply(ser.barX,"length")-1 psi.kn <- sum(weight) # core part of cce start <- knij+1 end <- 1 #for(k in 1:ser.num.barX[1]){ # while(!(ser.times[[1]][k]<ser.times[[2]][start])&&((start-knij)<ser.num.barX[2])){ # start <- start + 1 # } # while((ser.times[[1]][k+knij]>ser.times[[2]][end+1])&&(end<ser.num.barX[2])){ # end <- end + 1 # } # cmat[i,j] <- cmat[i,j] + ser.barX[[1]][k]*sum(ser.barX[[2]][(start-knij):end]) #} cmat[i,j] <- .C("pHayashiYoshida", as.integer(knij), as.integer(ser.num.barX[1]), as.integer(ser.num.barX[2]), as.double(ser.times[[1]]), as.double(ser.times[[2]]), as.double(ser.barX[[1]]), as.double(ser.barX[[2]]), value=double(1), PACKAGE = "yuima")$value cmat[i,j] <- cmat[i,j]/(psi.kn^2) cmat[j,i] <- cmat[i,j] }else{ diffX <- diff(as.numeric(data[[i]])) # pre-averaging kni <- min(kn[i,i],length(data[[i]])) # kn must be less than the number of the observations weight <- sapply((1:(kni-1))/kni,g) psi.kn <- sum(weight) #barX <- rollapplyr(diffX,width=kni-1,FUN="%*%",weight) barX <- filter(diffX,rev(weight),method="c", sides=1)[(kni-1):length(diffX)] tmp <- barX[-length(barX)] #cmat[i,j] <- tmp%*%rollapply(tmp,width=2*(kni-1)+1,FUN="sum",partial=TRUE)/(psi.kn)^2 cmat[i,j] <- tmp%*%rollsum(c(double(kni-1),tmp,double(kni-1)), k=2*(kni-1)+1)/(psi.kn)^2 } } } }else{# non-refreshing, non-cwise # allocate memory ser.X <- vector(n.series, mode="list") # data in 'x' ser.times <- vector(n.series, mode="list") # time index in 'x' ser.diffX <- vector(n.series, mode="list") # difference of data ser.numX <- integer(n.series) ser.barX <- vector(n.series, mode="list") for(i in 1:n.series){ # set data and time index ser.X[[i]] <- as.numeric(data[[i]]) # we need to transform data into numeric to avoid problem with duplicated indexes below ser.times[[i]] <- as.numeric(time(data[[i]])) # set difference of the data ser.diffX[[i]] <- diff( ser.X[[i]] ) ser.numX[i] <- length(ser.diffX[[i]]) } # pre-averaging if(missing(kn)){ kn <- min(max(ceiling(mean(theta)*sqrt(sum(ser.numX))),2), ser.numX+1) } kn <- kn[1] weight <- sapply((1:(kn-1))/kn,g) psi.kn <- sum(weight) for(i in 1:n.series){ #ser.barX[[i]] <- rollapplyr(ser.diffX[[i]],width=kn-1,FUN="%*%",weight) ser.barX[[i]] <- filter(ser.diffX[[i]],rev(weight),method="c", sides=1)[(kn-1):length(ser.diffX[[i]])] } ser.num.barX <- sapply(ser.barX,"length")-1 # core part of cce cmat <- matrix(0, n.series, n.series) # cov for(i in 1:n.series){ for(j in i:n.series){ if(i!=j){ #start <- kn+1 #end <- 1 #for(k in 1:ser.num.barX[i]){ # while(!(ser.times[[i]][k]<ser.times[[j]][start])&&((start-kn)<ser.num.barX[j])){ # start <- start + 1 # } # while((ser.times[[i]][k+kn]>ser.times[[j]][end+1])&&(end<ser.num.barX[j])){ # end <- end + 1 # } # cmat[i,j] <- cmat[i,j] + ser.barX[[i]][k]*sum(ser.barX[[j]][(start-kn):end]) #} cmat[i,j] <- .C("pHayashiYoshida", as.integer(kn), as.integer(ser.num.barX[i]), as.integer(ser.num.barX[j]), as.double(ser.times[[i]]), as.double(ser.times[[j]]), as.double(ser.barX[[i]]), as.double(ser.barX[[j]]), value=double(1), PACKAGE = "yuima")$value cmat[j,i] <- cmat[i,j] }else{ tmp <- ser.barX[[i]][1:ser.num.barX[i]] #cmat[i,j] <- tmp%*%rollapply(tmp,width=2*(kn-1)+1,FUN="sum",partial=TRUE) cmat[i,j] <- tmp%*%rollsum(c(double(kn-1),tmp,double(kn-1)), k=2*(kn-1)+1) } } } cmat <- cmat/(psi.kn^2) } } return(cmat) } ################################################################ # previous tick Two Scales realized CoVariance ## data: a list of zoos c.two: a postive number TSCV <- function(data,K,c.two,J=1,adj=TRUE,utime){ #X <- do.call("rbind",lapply(refresh_sampling(data),"as.numeric")) #N <- ncol(X) X <- do.call("cbind",lapply(refresh_sampling(data),"as.numeric")) N <- nrow(X) if(missing(K)){ if(missing(c.two)) c.two <- selectParam.TSCV(data,utime=utime) K <- ceiling(mean(c.two)*N^(2/3)) } scale <- (N-K+1)*J/(K*(N-J+1)) #diffX1 <- apply(X,1,"diff",lag=K) #diffX2 <- apply(X,1,"diff",lag=J) diffX1 <- diff(X,lag=K) diffX2 <- diff(X,lag=J) cmat <- t(diffX1)%*%diffX1/K-scale*t(diffX2)%*%diffX2/J if(adj) cmat <- cmat/(1-scale) return(cmat) } ################################################################ # Generalized multiscale estimator ## data: a list of zoos c.multi: a postive number GME <- function(data,c.multi,utime){ d.size <- length(data) if(missing(c.multi)) c.multi <- selectParam.GME(data,utime=utime) c.multi <- matrix(c.multi,d.size,d.size) c.multi <- (c.multi+t(c.multi))/2 cmat <- matrix(0,d.size,d.size) for(i in 1:d.size){ for(j in i:d.size){ if(i!=j){ sdata <- Bibsynchro(data[[i]],data[[j]]) N <- sdata$num.data M <- ceiling(c.multi[i,j]*sqrt(N)) M <- min(c(M,N)) # M must be smaller than N M <- max(c(M,2)) # M must be lager than 2 alpha <- 12*(1:M)^2/(M^3-M)-6*(1:M)/(M^2-1)-6*(1:M)/(M^3-M) #tmp <- double(M) #for(m in 1:M){ # tmp[m] <- (sdata$xg[m:N]-sdata$xl[1:(N-m+1)])%*% # (sdata$ygamma[m:N]-sdata$ylambda[1:(N-m+1)]) #} tmp <- .C("msrc", as.integer(M), as.integer(N), as.double(sdata$xg), as.double(sdata$xl), as.double(sdata$ygamma), as.double(sdata$ylambda), result=double(M), PACKAGE = "yuima")$result cmat[i,j] <- (alpha/(1:M))%*%tmp }else{ X <- as.numeric(data[[i]]) N <- length(X)-1 M <- ceiling(c.multi[i,j]*sqrt(N)) M <- min(c(M,N)) # M must be smaller than N M <- max(c(M,2)) # M must be lager than 2 alpha <- 12*(1:M)^2/(M^3-M)-6*(1:M)/(M^2-1)-6*(1:M)/(M^3-M) #tmp <- double(M) #for(m in 1:M){ #tmp[m] <- sum((X[m:N]-X[1:(N-m+1)])^2) # tmp[m] <- sum(diff(X,lag=m)^2) #} tmp <- .C("msrc", as.integer(M), as.integer(N), as.double(X[-1]), as.double(X[1:N]), as.double(X[-1]), as.double(X[1:N]), result=double(M), PACKAGE = "yuima")$result cmat[i,j] <- (alpha/(1:M))%*%tmp } cmat[j,i] <- cmat[i,j] } } return(cmat) } ################################################################ # Realized kernel ## data: a list of zoos ## kernel: a real-valued function on [0,infty) (a kernel) ## H: a positive number m: a postive integer RK <- function(data,kernel,H,c.RK,eta=3/5,m=2,ftregion=0,utime){ # if missing kernel, we use the Parzen kernel if(missing(kernel)){ kernel <- function(x){ if(x<=1/2){ return(1-6*x^2+6*x^3) }else if(x<=1){ return(2*(1-x)^3) }else{ return(0) } } } d <- length(data) tmp <- lapply(refresh_sampling(data),"as.numeric") #tmp <- do.call("rbind",tmp) tmp <- do.call("cbind",tmp) #n <- max(c(ncol(tmp)-2*m+1,2)) n <- max(c(nrow(tmp)-2*m+1,2)) # if missing H, we select it following Barndorff-Nielsen et al.(2011) if(missing(H)){ if(missing(c.RK)) c.RK <- selectParam.RK(data,utime=utime) H <- mean(c.RK)*n^eta } #X <- matrix(0,d,n+1) X <- matrix(0,n+1,d) #X[,1] <- apply(matrix(tmp[,1:m],d,m),1,"sum")/m #X[,1] <- apply(matrix(tmp[,1:m],d,m),1,"mean") X[1,] <- colMeans(matrix(tmp[1:m,],m,d)) #X[,2:n] <- tmp[,(m+1):(m+n-1)] X[2:n,] <- tmp[(m+1):(m+n-1),] #X[,n+1] <- apply(matrix(tmp[,(n+m):(n+2*m-1)],d,m),1,"sum")/m #X[,n+1] <- apply(matrix(tmp[,(n+m):(n+2*m-1)],d,m),1,"mean") X[n+1,] <- colMeans(matrix(tmp[(n+m):(n+2*m-1),],m,d)) cc <- floor(ftregion*H) # flat-top region Kh <- rep(1,cc) Kh <- append(Kh,sapply(((cc+1):(n-1))/H,kernel)) h.size <- max(which(Kh!=0)) #diffX <- apply(X,1,FUN="diff") #diffX <- diff(X) #Gamma <- array(0,dim=c(h.size+1,d,d)) #for(h in 1:(h.size+1)) # Gamma[h,,] <- t(diffX)[,h:n]%*%diffX[1:(n-h+1),] Gamma <- acf(diff(X),lag.max=h.size,type="covariance", plot=FALSE,demean=FALSE)$acf*n cmat <- matrix(0,d,d) for (i in 1:d){ cmat[,i] <- kernel(0)*Gamma[1,,i]+ Kh[1:h.size]%*%(Gamma[-1,,i]+Gamma[-1,i,]) } return(cmat) } ############################################################# # QMLE (Ait-Sahalia et al.(2010)) ## Old sources if(0){ ql.xiu <- function(zdata){ diffX <- diff(as.numeric(zdata)) inv.difft <- diff(as.numeric(time(zdata)))^(-1) n <- length(diffX) a <- 4*inv.difft*sin((pi/2)*seq(1,2*n-1,by=2)/(2*n+1))^2 z <- double(n) for(k in 1:n){ z[k] <- cos(pi*((2*k-1)/(2*n+1))*(1:n-1/2))%*%diffX } z <- sqrt(2/(n+1/2))*z #z <- sqrt(2/(n+1/2))*cos(pi*((2*(1:n)-1)/(2*n+1))%o%(1:n-1/2))%*%diffX z2 <- inv.difft*z^2 n.ql <- function(v){ V <- v[1]+a*v[2] return(sum(log(V)+V^(-1)*z2)) } gr <- function(v){ V <- v[1]+a*v[2] obj <- V^(-1)-V^(-2)*z2 return(c(sum(obj),sum(a*obj))) } return(list(n.ql=n.ql,gr=gr)) } cce.qmle <- function(data,opt.method="BFGS",vol.init=NA, covol.init=NA,nvar.init=NA,ncov.init=NA,...,utime){ d.size <- length(data) dd <- d.size*(d.size-1)/2 vol.init <- matrix(vol.init,1,d.size) nvar.init <- matrix(vol.init,1,d.size) covol.init <- matrix(covol.init,2,dd) ncov.init <- matrix(ncov.init,2,dd) if(missing(utime)) utime <- set_utime(data) cmat <- matrix(0,d.size,d.size) for(i in 1:d.size){ for(j in i:d.size){ if(i!=j){ idx <- d.size*(i-1)-(i-1)*i/2+(j-i) dat <- refresh_sampling(list(data[[i]],data[[j]])) dattime <- apply(do.call("rbind", lapply(lapply(dat,"time"),"as.numeric")), 2,"max") dat[[1]] <- zoo(as.numeric(dat[[1]]),dattime) dat[[2]] <- zoo(as.numeric(dat[[2]]),dattime) dat1 <- dat[[1]]+dat[[2]] dat2 <- dat[[1]]-dat[[2]] ql1 <- ql.xiu(dat1) ql2 <- ql.xiu(dat2) Sigma1 <- covol.init[1,idx] Sigma2 <- covol.init[2,idx] Omega1 <- ncov.init[1,idx] Omega2 <- ncov.init[2,idx] if(is.na(Sigma1)) Sigma1 <- RV.sparse(dat1,frequency=1200,utime=utime) if(is.na(Sigma2)) Sigma2 <- RV.sparse(dat2,frequency=1200,utime=utime) if(is.na(Omega1)) Omega1 <- Omega_BNHLS(dat1,sec=120,utime=utime) if(is.na(Omega2)) Omega2 <- Omega_BNHLS(dat2,sec=120,utime=utime) #par1 <- optim(par1,fn=ql.ks(dat1),method=opt.method) #par2 <- optim(par2,fn=ql.ks(dat2),method=opt.method) par1 <- constrOptim(theta=c(Sigma1,Omega1), f=ql1$n.ql,grad=ql1$gr,method=opt.method, ui=diag(2),ci=0,...)$par[1] par2 <- constrOptim(theta=c(Sigma2,Omega2), f=ql2$n.ql,grad=ql2$gr,method=opt.method, ui=diag(2),ci=0,...)$par[1] cmat[i,j] <- (par1-par2)/4 cmat[j,i] <- cmat[i,j] }else{ ql <- ql.xiu(data[[i]]) Sigma <- vol.init[i] Omega <- nvar.init[i] if(is.na(Sigma)) Sigma <- RV.sparse(data[[i]],frequency=1200,utime=utime) if(is.na(Omega)) Omega <- Omega_BNHLS(data[[i]],sec=120,utime=utime) #cmat[i,i] <- optim(par,fn=ql.ks(data[[i]]),method=opt.method) cmat[i,i] <- constrOptim(theta=c(Sigma,Omega),f=ql$n.ql,grad=ql$gr, method=opt.method, ui=diag(2),ci=0,...)$par[1] } } } return(cmat) } } ## New sources (2014/11/10, use arima0) cce.qmle <- function(data,vol.init=NA,covol.init=NA,nvar.init=NA,ncov.init=NA){ d.size <- length(data) dd <- d.size*(d.size-1)/2 vol.init <- matrix(vol.init,1,d.size) nvar.init <- matrix(vol.init,1,d.size) covol.init <- matrix(covol.init,2,dd) ncov.init <- matrix(ncov.init,2,dd) cmat <- matrix(0,d.size,d.size) for(i in 1:d.size){ for(j in i:d.size){ if(i!=j){ idx <- d.size*(i-1)-(i-1)*i/2+(j-i) dat <- refresh_sampling(list(data[[i]],data[[j]])) dat[[1]] <- diff(as.numeric(dat[[1]])) dat[[2]] <- diff(as.numeric(dat[[2]])) n <- length(dat[[1]]) Sigma1 <- covol.init[1,idx] Sigma2 <- covol.init[2,idx] Omega1 <- ncov.init[1,idx] Omega2 <- ncov.init[2,idx] init <- (-2*Omega1-Sigma1/n+sqrt(Sigma1*(4*Omega1+Sigma1/n)/n))/(2*Omega1) obj <- arima0(dat[[1]]+dat[[2]],order=c(0,0,1),include.mean=FALSE, init=init) par1 <- n*obj$sigma2*(1+obj$coef)^2 init <- (-2*Omega2-Sigma2/n+sqrt(Sigma2*(4*Omega2+Sigma2/n)/n))/(2*Omega2) obj <- arima0(dat[[1]]-dat[[2]],order=c(0,0,1),include.mean=FALSE, init=init) par2 <- n*obj$sigma2*(1+obj$coef)^2 cmat[i,j] <- (par1-par2)/4 cmat[j,i] <- cmat[i,j] }else{ dx <- diff(as.numeric(data[[i]])) n <- length(dx) Sigma <- vol.init[i] Omega <- nvar.init[i] init <- (-2*Omega-Sigma/n+sqrt(Sigma*(4*Omega+Sigma/n)/n))/(2*Omega) obj <- arima0(dx,order=c(0,0,1),include.mean=FALSE,init=init) cmat[i,i] <- n*obj$sigma2*(1+obj$coef)^2 } } } return(cmat) } ################################################################## # Separating information maximum likelihood estimator (Kunitomo and Sato (2008)) SIML <- function(data,mn,alpha=0.4){ d.size <- length(data) data <- lapply(refresh_sampling(data),"as.numeric") data <- do.call("cbind",data) n.size <- nrow(data)-1 if(missing(mn)){ mn <- ceiling(n.size^alpha) } #C <- matrix(1,n.size,n.size) #C[upper.tri(C)] <- 0 #P <- matrix(0,n.size,n.size) #for(j in 1:n.size){ # for(k in 1:n.size){ # P[j,k] <- sqrt(2/(n.size+1/2))*cos((2*pi/(2*n.size+1))*(j-1/2)*(k-1/2)) # } #} #Z <- data[-1,]-matrix(1,n.size,1)%*%matrix(data[1,],1,d.size) #Z <- sqrt(n.size)*t(P)%*%solve(C)%*%Z #diff.Y <- apply(data,2,"diff") diff.Y <- diff(data) #Z <- matrix(0,n.size,d.size) #for(j in 1:n.size){ # pj <- sqrt(2/(n.size+1/2))*cos((2*pi/(2*n.size+1))*(j-1/2)*(1:n.size-1/2)) # Z[j,] <- matrix(pj,1,n.size)%*%diff.Y #} #Z <- matrix(0,mn,d.size) #for(j in 1:mn){ # pj <- sqrt(2/(n.size+1/2))*cos((2*pi/(2*n.size+1))*(j-1/2)*(1:n.size-1/2)) # Z[j,] <- matrix(pj,1,n.size)%*%diff.Y #} #Z <- sqrt(n.size)*Z Z <- sqrt(n.size)* sqrt(2/(n.size+1/2))*cos((2*pi/(2*n.size+1))*(1:mn-1/2)%o%(1:n.size-1/2))%*% diff.Y cmat <- matrix(0,d.size,d.size) for(k in 1:mn){ cmat <- cmat+matrix(Z[k,],d.size,1)%*%matrix(Z[k,],1,d.size) } return(cmat/mn) } ############################################################# # Truncated Hayashi-Yoshida estimator ## data: a list of zoos ## threshold: a numeric vector or a list of numeric vectors or zoos THY <- function(data,threshold) { n.series <- length(data) if(missing(threshold)){ threshold <- local_univ_threshold(data,coef=5,eps=0.1) }else if(is.numeric(threshold)){ threshold <- matrix(threshold,1,n.series) } #if(n.series <2) # stop("Please provide at least 2-dimensional time series") # allocate memory ser.X <- vector(n.series, mode="list") # data in 'x' ser.times <- vector(n.series, mode="list") # time index in 'x' ser.diffX <- vector(n.series, mode="list") # difference of data ser.rho <- vector(n.series, mode="list") for(i in 1:n.series){ # set data and time index ser.X[[i]] <- as.numeric(data[[i]]) # we need to transform data into numeric to avoid problem with duplicated indexes below ser.times[[i]] <- as.numeric(time(data[[i]])) # set difference of the data with truncation ser.diffX[[i]] <- diff( ser.X[[i]] ) if(is.numeric(threshold)){ ser.rho[[i]] <- rep(threshold[i],length(ser.diffX[[i]])) }else{ ser.rho[[i]] <- as.numeric(threshold[[i]]) } # thresholding ser.diffX[[i]][ser.diffX[[i]]^2>ser.rho[[i]]] <- 0 } # core part of cce cmat <- matrix(0, n.series, n.series) # cov for(i in 1:n.series){ for(j in i:n.series){ #I <- rep(1,n.series) #Checking Starting Point #repeat{ # if(ser.times[[i]][I[i]] >= ser.times[[j]][I[j]+1]){ # I[j] <- I[j]+1 # }else if(ser.times[[i]][I[i]+1] <= ser.times[[j]][I[j]]){ # I[i] <- I[i]+1 # }else{ # break # } #} #Main Component if(i!=j){ #while((I[i]<length(ser.times[[i]])) && (I[j]<length(ser.times[[j]]))) { # cmat[j,i] <- cmat[j,i] + (ser.diffX[[i]])[I[i]]*(ser.diffX[[j]])[I[j]] # if(ser.times[[i]][I[i]+1]>ser.times[[j]][I[j]+1]){ # I[j] <- I[j] + 1 # }else if(ser.times[[i]][I[i]+1]<ser.times[[j]][I[j]+1]){ # I[i] <- I[i] +1 # }else{ # I[i] <- I[i]+1 # I[j] <- I[j]+1 # } #} cmat[j,i] <- .C("HayashiYoshida",as.integer(length(ser.times[[i]])), as.integer(length(ser.times[[j]])),as.double(ser.times[[i]]), as.double(ser.times[[j]]),as.double(ser.diffX[[i]]), as.double(ser.diffX[[j]]),value=double(1), PACKAGE = "yuima")$value }else{ cmat[i,j] <- sum(ser.diffX[[i]]^2) } cmat[i,j] <- cmat[j,i] } } return(cmat) } ######################################################### # Pre-averaged truncated Hayashi-Yoshida estimator ## data: a list of zoos theta: a postive number ## g: a real-valued function on [0,1] (a weight function) ## threshold: a numeric vector or a list of numeric vectors or zoos ## refreshing: a logical value (if TRUE we use the refreshed data) PTHY <- function(data,theta,kn,g,threshold,refreshing=TRUE, cwise=TRUE,eps=0.2){ n.series <- length(data) #if(missing(theta)&&missing(kn)) # theta <- selectParam.pavg(data,a.theta=7585/1161216, # b.theta=151/20160,c.theta=1/24) if(missing(theta)) theta <- 0.15 cmat <- matrix(0, n.series, n.series) # cov if(refreshing){ if(cwise){ if(missing(kn)){# refreshing,cwise,missing kn theta <- matrix(theta,n.series,n.series) theta <- (theta+t(theta))/2 for(i in 1:n.series){ for(j in i:n.series){ if(i!=j){ resample <- refresh_sampling.PHY(list(data[[i]],data[[j]])) dat <- resample$data ser.numX <- length(resample$refresh.times)-1 # set data and time index ser.X <- lapply(dat,"as.numeric") ser.times <- lapply(lapply(dat,"time"),"as.numeric") # set difference of the data ser.diffX <- lapply(ser.X,"diff") # pre-averaging kn <- min(max(ceiling(theta[i,j]*sqrt(ser.numX)),2),ser.numX) weight <- sapply((1:(kn-1))/kn,g) psi.kn <- sum(weight) #ser.barX <- list(rollapplyr(ser.diffX[[1]],width=kn-1,FUN="%*%",weight), # rollapplyr(ser.diffX[[2]],width=kn-1,FUN="%*%",weight)) ser.barX <- list(filter(ser.diffX[[1]],rev(weight),method="c", sides=1)[(kn-1):length(ser.diffX[[1]])], filter(ser.diffX[[2]],rev(weight),method="c", sides=1)[(kn-1):length(ser.diffX[[2]])]) ser.num.barX <- sapply(ser.barX,"length") # thresholding if(missing(threshold)){ for(ii in 1:2){ K <- ceiling(ser.num.barX[ii]^(3/4)) obj0 <- abs(ser.barX[[ii]]) obj1 <- (pi/2)*obj0[1:(ser.num.barX[ii]-kn)]*obj0[-(1:kn)] if(min(K,ser.num.barX[ii]-1)<2*kn){ #v.hat <- (median(obj0)/0.6745)^2 v.hat <- mean(obj1) }else{ v.hat <- double(ser.num.barX[ii]) #v.hat[1:K] <- (median(obj0[1:K])/0.6745)^2 v.hat[-(1:K)] <- rollmean(obj1[1:(ser.num.barX[ii]-2*kn)],k=K-2*kn+1,align="left") v.hat[1:K] <- v.hat[K+1] } #rho <- 2*log(ser.num.barX[ii])* # (median(abs(ser.barX[[ii]])/sqrt(v.hat))/0.6745)^2*v.hat rho <- 2*log(ser.num.barX[ii])^(1+eps)*v.hat ser.barX[[ii]][ser.barX[[ii]]^2>rho] <- 0 } }else if(is.numeric(threshold)){ threshold <- matrix(threshold,1,n.series) ser.barX[[1]][ser.barX[[1]]^2>threshold[i]] <- 0 ser.barX[[2]][ser.barX[[2]]^2>threshold[j]] <- 0 }else{ ser.barX[[1]][ser.barX[[1]]^2>threshold[[i]][1:ser.num.barX[1]]] <- 0 ser.barX[[2]][ser.barX[[2]]^2>threshold[[j]][1:ser.num.barX[2]]] <- 0 } ser.num.barX <- ser.num.barX-1 # core part of cce #start <- kn+1 #end <- 1 #for(k in 1:ser.num.barX[1]){ # while(!(ser.times[[1]][k]<ser.times[[2]][start])&&((start-kn)<ser.num.barX[2])){ # start <- start + 1 # } # while((ser.times[[1]][k+kn]>ser.times[[2]][end+1])&&(end<ser.num.barX[2])){ # end <- end + 1 # } # cmat[i,j] <- cmat[i,j] + ser.barX[[1]][k]*sum(ser.barX[[2]][(start-kn):end]) #} cmat[i,j] <- .C("pHayashiYoshida", as.integer(kn), as.integer(ser.num.barX[1]), as.integer(ser.num.barX[2]), as.double(ser.times[[1]]), as.double(ser.times[[2]]), as.double(ser.barX[[1]]), as.double(ser.barX[[2]]), value=double(1), PACKAGE = "yuima")$value cmat[i,j] <- cmat[i,j]/(psi.kn^2) cmat[j,i] <- cmat[i,j] }else{ diffX <- diff(as.numeric(data[[i]])) # pre-averaging kn <- min(max(ceiling(theta[i,i]*sqrt(length(diffX))),2), length(data[[i]])) weight <- sapply((1:(kn-1))/kn,g) psi.kn <- sum(weight) #barX <- rollapplyr(diffX,width=kn-1,FUN="%*%",weight) barX <- filter(diffX,rev(weight),method="c", sides=1)[(kn-1):length(diffX)] num.barX <- length(barX) # thresholding if(missing(threshold)){ K <- ceiling(num.barX^(3/4)) #K <- ceiling(kn^(3/2)) obj0 <- abs(barX) obj1 <- (pi/2)*obj0[1:(num.barX-kn)]*obj0[-(1:kn)] if(min(K,num.barX-1)<2*kn){ #v.hat <- (median(obj0)/0.6745)^2 v.hat <- mean(obj1) }else{ v.hat <- double(num.barX) #v.hat[1:K] <- (median(obj0[1:K])/0.6745)^2 v.hat[-(1:K)] <- rollmean(obj1[1:(num.barX-2*kn)],k=K-2*kn+1,align="left") v.hat[1:K] <- v.hat[K+1] } #rho <- 2*log(num.barX)* # (median(abs(barX)/sqrt(v.hat))/0.6745)^2*v.hat rho <- 2*log(num.barX)^(1+eps)*v.hat barX[barX^2>rho] <- 0 }else if(is.numeric(threshold)){ threshold <- matrix(threshold,1,n.series) barX[barX^2>threshold[i]] <- 0 }else{ barX[barX^2>threshold[[i]][1:num.barX]] <- 0 } tmp <- barX[-num.barX] #cmat[i,j] <- tmp%*%rollapply(tmp,width=2*(kn-1)+1,FUN="sum",partial=TRUE)/(psi.kn)^2 cmat[i,j] <- tmp%*%rollsum(c(double(kn-1),tmp,double(kn-1)), k=2*(kn-1)+1)/(psi.kn)^2 } } } }else{# refreshing,cwise,not missing kn kn <- matrix(kn,n.series,n.series) for(i in 1:n.series){ for(j in i:n.series){ if(i!=j){ resample <- refresh_sampling.PHY(list(data[[i]],data[[j]])) dat <- resample$data ser.numX <- length(resample$refresh.times)-1 knij <- min(max(kn[i,j],2),ser.numX+1) weight <- sapply((1:(knij-1))/knij,g) psi.kn <- sum(weight) # set data and time index ser.X <- lapply(dat,"as.numeric") ser.times <- lapply(lapply(dat,"time"),"as.numeric") # set difference of the data ser.diffX <- lapply(ser.X,"diff") # pre-averaging #ser.barX <- list(rollapplyr(ser.diffX[[1]],width=knij-1,FUN="%*%",weight), # rollapplyr(ser.diffX[[2]],width=knij-1,FUN="%*%",weight)) ser.barX <- list(filter(ser.diffX[[1]],rev(weight),method="c", sides=1)[(knij-1):length(ser.diffX[[1]])], filter(ser.diffX[[2]],rev(weight),method="c", sides=1)[(knij-1):length(ser.diffX[[2]])]) ser.num.barX <- sapply(ser.barX,"length") # thresholding if(missing(threshold)){ for(ii in 1:2){ K <- ceiling(ser.num.barX[ii]^(3/4)) obj0 <- abs(ser.barX[[ii]]) obj1 <- (pi/2)*obj0[1:(ser.num.barX[ii]-knij)]*obj0[-(1:knij)] if(min(K,ser.num.barX[ii]-1)<2*knij){ #v.hat <- (median(obj0)/0.6745)^2 v.hat <- mean(obj1) }else{ v.hat <- double(ser.num.barX[ii]) #v.hat[1:K] <- (median(obj0[1:K])/0.6745)^2 v.hat[-(1:K)] <- rollmean(obj1[1:(ser.num.barX[ii]-2*knij)],k=K-2*knij+1,align="left") v.hat[1:K] <- v.hat[K+1] } #rho <- 2*log(ser.num.barX[ii])* # (median(abs(ser.barX[[ii]])/sqrt(v.hat))/0.6745)^2*v.hat rho <- 2*log(ser.num.barX[ii])^(1+eps)*v.hat ser.barX[[ii]][ser.barX[[ii]]^2>rho] <- 0 } }else if(is.numeric(threshold)){ threshold <- matrix(threshold,1,n.series) ser.barX[[1]][ser.barX[[1]]^2>threshold[i]] <- 0 ser.barX[[2]][ser.barX[[2]]^2>threshold[j]] <- 0 }else{ ser.barX[[1]][ser.barX[[1]]^2>threshold[[i]][1:ser.num.barX[1]]] <- 0 ser.barX[[2]][ser.barX[[2]]^2>threshold[[j]][1:ser.num.barX[2]]] <- 0 } ser.num.barX <- ser.num.barX-1 # core part of cce #start <- knij+1 #end <- 1 #for(k in 1:ser.num.barX[1]){ # while(!(ser.times[[1]][k]<ser.times[[2]][start])&&((start-knij)<ser.num.barX[2])){ # start <- start + 1 # } # while((ser.times[[1]][k+knij]>ser.times[[2]][end+1])&&(end<ser.num.barX[2])){ # end <- end + 1 # } # cmat[i,j] <- cmat[i,j] + ser.barX[[1]][k]*sum(ser.barX[[2]][(start-knij):end]) #} cmat[i,j] <- .C("pHayashiYoshida", as.integer(knij), as.integer(ser.num.barX[1]), as.integer(ser.num.barX[2]), as.double(ser.times[[1]]), as.double(ser.times[[2]]), as.double(ser.barX[[1]]), as.double(ser.barX[[2]]), value=double(1), PACKAGE = "yuima")$value cmat[i,j] <- cmat[i,j]/(psi.kn^2) cmat[j,i] <- cmat[i,j] }else{ diffX <- diff(as.numeric(data[[i]])) # pre-averaging kni <- min(max(kni,2),length(data[[i]])) weight <- sapply((1:(kni-1))/kni,g) psi.kn <- sum(weight) #barX <- rollapplyr(diffX,width=kni-1,FUN="%*%",weight) barX <- filter(diffX,rev(weight),method="c", sides=1)[(kni-1):length(diffX)] num.barX <- length(barX) # thresholding if(missing(threshold)){ K <- ceiling(num.barX^(3/4)) #K <- ceiling(kn^(3/2)) obj0 <- abs(barX) obj1 <- (pi/2)*obj0[1:(num.barX-kni)]*obj0[-(1:kni)] if(min(K,num.barX-1)<2*kni){ #v.hat <- (median(obj0)/0.6745)^2 v.hat <- mean(obj1) }else{ v.hat <- double(num.barX) #v.hat[1:K] <- (median(obj0[1:K])/0.6745)^2 v.hat[-(1:K)] <- rollmean(obj1[1:(num.barX-2*kni)],k=K-2*kni+1,align="left") v.hat[1:K] <- v.hat[K+1] } #rho <- 2*log(num.barX)* # (median(abs(barX)/sqrt(v.hat))/0.6745)^2*v.hat rho <- 2*log(num.barX)^(1+eps)*v.hat barX[barX^2>rho] <- 0 }else if(is.numeric(threshold)){ threshold <- matrix(threshold,1,n.series) barX[barX^2>threshold[i]] <- 0 }else{ barX[barX^2>threshold[[i]][1:num.barX]] <- 0 } tmp <- barX[-num.barX] #cmat[i,j] <- tmp%*%rollapply(tmp,width=2*(kni-1)+1,FUN="sum",partial=TRUE)/(psi.kn)^2 cmat[i,j] <- tmp%*%rollsum(c(double(kni-1),tmp,double(kni-1)), k=2*(kni-1)+1)/(psi.kn)^2 } } } } }else{# refreshing,non-cwise # synchronize the data resample <- refresh_sampling.PHY(data) data <- resample$data ser.numX <- length(resample$refresh.times)-1 # if missing kn, we choose it following Barndorff-Nielsen et al. (2011) if(missing(kn)){ kn <- min(max(ceiling(mean(theta)*sqrt(ser.numX)),2),ser.numX+1) } kn <- kn[1] weight <- sapply((1:(kn-1))/kn,g) # allocate memory ser.X <- vector(n.series, mode="list") # data in 'x' ser.times <- vector(n.series, mode="list") # time index in 'x' ser.diffX <- vector(n.series, mode="list") # difference of data ser.barX <- vector(n.series, mode="list") # pre-averaged data ser.num.barX <- integer(n.series) for(i in 1:n.series){ # set data and time index ser.X[[i]] <- as.numeric(data[[i]]) # we need to transform data into numeric to avoid problem with duplicated indexes below ser.times[[i]] <- as.numeric(time(data[[i]])) # set difference of the data ser.diffX[[i]] <- diff( ser.X[[i]] ) } # thresholding if(missing(threshold)){ #coef <- 2*coef*kn/sqrt(ser.numX) for(i in 1:n.series){ #ser.num.barX[i] <- ser.numX[i]-kn+2 #ser.barX[[i]] <- double(ser.num.barX[i]) #for(j in 1:ser.num.barX[i]){ # ser.barX[[i]][j] <- sapply((1:(kn-1))/kn,g)%*%ser.diffX[[i]][j:(j+kn-2)] #} #ser.barX[[i]] <- rollapplyr(ser.diffX[[i]],width=kn-1,FUN="%*%",weight) ser.barX[[i]] <- filter(ser.diffX[[i]],rev(weight),method="c", sides=1)[(kn-1):length(ser.diffX[[i]])] ser.num.barX[i] <- length(ser.barX[[i]]) K <- ceiling(ser.num.barX[i]^(3/4)) obj0 <- abs(ser.barX[[i]]) obj1 <- (pi/2)*obj0[1:(ser.num.barX[i]-kn)]*obj0[-(1:kn)] if(min(K,ser.num.barX[i]-1)<2*kn){ #v.hat <- (median(obj0)/0.6745)^2 v.hat <- mean(obj1) }else{ v.hat <- double(ser.num.barX[i]) #v.hat[1:K] <- (median(obj0[1:K])/0.6745)^2 v.hat[-(1:K)] <- rollmean(obj1[1:(ser.num.barX[i]-2*kn)], k=K-2*kn+1,align="left") v.hat[1:K] <- v.hat[K+1] } #rho <- 2*log(ser.num.barX[ii])* # (median(abs(ser.barX[[ii]])/sqrt(v.hat))/0.6745)^2*v.hat rho <- 2*log(ser.num.barX[i])^(1+eps)*v.hat ser.barX[[i]][ser.barX[[i]]^2>rho] <- 0 } }else if(is.numeric(threshold)){ threshold <- matrix(threshold,1,n.series) for(i in 1:n.series){ #ser.num.barX[i] <- ser.numX[i]-kn+2 #ser.barX[[i]] <- double(ser.num.barX[i]) #for(j in 1:ser.num.barX[i]){ # tmp <- sapply((1:(kn-1))/kn,g)%*%ser.diffX[[i]][j:(j+kn-2)] # if(tmp^2>threshold[i]){ # ser.barX[[i]][j] <- 0 # }else{ # ser.barX[[i]][j] <- tmp # } #} #ser.barX[[i]] <- rollapplyr(ser.diffX[[i]],width=kn-1,FUN="%*%",weight) ser.barX[[i]] <- filter(ser.diffX[[i]],rev(weight),method="c", sides=1)[(kn-1):length(ser.diffX[[i]])] ser.num.barX[i] <- length(ser.barX[[i]]) ser.barX[[i]][ser.barX[[i]]^2>threshold[i]] <- 0 } }else{ for(i in 1:n.series){ #ser.num.barX[i] <- ser.numX[i]-kn+2 #ser.barX[[i]] <- double(ser.num.barX[i]) #for(j in 1:ser.num.barX[i]){ # tmp <- sapply((1:(kn-1))/kn,g)%*%ser.diffX[[i]][j:(j+kn-2)] # if(tmp^2>threshold[[i]][j]){ # ser.barX[[i]][j] <- 0 # }else{ # ser.barX[[i]][j] <- tmp # } #} #ser.barX[[i]] <- rollapplyr(ser.diffX[[i]],width=kn-1,FUN="%*%",weight) ser.barX[[i]] <- filter(ser.diffX[[i]],rev(weight),method="c", sides=1)[(kn-1):length(ser.diffX[[i]])] ser.num.barX[i] <- length(ser.barX[[i]]) ser.barX[[i]][ser.barX[[i]]^2>threshold[[i]][1:ser.num.barX[i]]] <- 0 } } ser.num.barX <- ser.num.barX-1 # core part of cce for(i in 1:n.series){ for(j in i:n.series){ if(i!=j){ #start <- kn+1 #end <- 1 #for(k in 1:ser.num.barX[i]){ # while(!(ser.times[[i]][k]<ser.times[[j]][start])&&((start-kn)<ser.num.barX[j])){ # start <- start + 1 # } # while((ser.times[[i]][k+kn]>ser.times[[j]][end+1])&&(end<ser.num.barX[j])){ # end <- end + 1 # } # cmat[i,j] <- cmat[i,j] + ser.barX[[i]][k]*sum(ser.barX[[j]][(start-kn):end]) #} cmat[i,j] <- .C("pHayashiYoshida", as.integer(kn), as.integer(ser.num.barX[i]), as.integer(ser.num.barX[j]), as.double(ser.times[[i]]), as.double(ser.times[[j]]), as.double(ser.barX[[i]]), as.double(ser.barX[[j]]), value=double(1), PACKAGE = "yuima")$value cmat[j,i] <- cmat[i,j] }else{ tmp <- ser.barX[[i]][1:ser.num.barX[i]] #cmat[i,j] <- tmp%*%rollapply(tmp,width=2*(kn-1)+1,FUN="sum",partial=TRUE) cmat[i,j] <- tmp%*%rollsum(c(double(kn-1),tmp,double(kn-1)), k=2*(kn-1)+1) } } } psi.kn <- sum(weight) cmat <- cmat/(psi.kn^2) } }else{# non-refreshing if(cwise){# non-refreshing,cwise theta <- matrix(theta,n.series,n.series) theta <- (theta+t(theta))/2 if(missing(kn)){ ntmp <- matrix(sapply(data,"length"),n.series,n.series) ntmp <- ntmp+t(ntmp) diag(ntmp) <- diag(ntmp)/2 kn <- ceiling(theta*sqrt(ntmp)) kn[kn<2] <- 2 # kn must be larger than 1 } kn <- matrix(kn,n.series,n.series) for(i in 1:n.series){ for(j in i:n.series){ if(i!=j){ dat <- list(data[[i]],data[[j]]) # set data and time index ser.X <- lapply(dat,"as.numeric") ser.times <- lapply(lapply(dat,"time"),"as.numeric") # set difference of the data ser.diffX <- lapply(ser.X,"diff") # pre-averaging knij <- min(kn[i,j],sapply(ser.X,"length")) # kn must be less than the numbers of the observations weight <- sapply((1:(knij-1))/knij,g) psi.kn <- sum(weight) #ser.barX <- list(rollapplyr(ser.diffX[[1]],width=knij-1,FUN="%*%",weight), # rollapplyr(ser.diffX[[2]],width=knij-1,FUN="%*%",weight)) ser.barX <- list(filter(ser.diffX[[1]],rev(weight),method="c", sides=1)[(knij-1):length(ser.diffX[[1]])], filter(ser.diffX[[2]],rev(weight),method="c", sides=1)[(knij-1):length(ser.diffX[[2]])]) ser.num.barX <- sapply(ser.barX,"length") # thresholding if(missing(threshold)){ for(ii in 1:2){ K <- ceiling(ser.num.barX[ii]^(3/4)) obj0 <- abs(ser.barX[[ii]]) obj1 <- (pi/2)*obj0[1:(ser.num.barX[ii]-knij)]*obj0[-(1:knij)] if(min(K,ser.num.barX[ii]-1)<2*knij){ #v.hat <- (median(obj0)/0.6745)^2 v.hat <- mean(obj1) }else{ v.hat <- double(ser.num.barX[ii]) #v.hat[1:K] <- (median(obj0[1:K])/0.6745)^2 v.hat[-(1:K)] <- rollmean(obj1[1:(ser.num.barX[ii]-2*knij)],k=K-2*knij+1,align="left") v.hat[1:K] <- v.hat[K+1] } #rho <- 2*log(ser.num.barX[ii])* # (median(abs(ser.barX[[ii]])/sqrt(v.hat))/0.6745)^2*v.hat rho <- 2*log(ser.num.barX[ii])^(1+eps)*v.hat ser.barX[[ii]][ser.barX[[ii]]^2>rho] <- 0 } }else if(is.numeric(threshold)){ threshold <- matrix(threshold,1,n.series) ser.barX[[1]][ser.barX[[1]]^2>threshold[i]] <- 0 ser.barX[[2]][ser.barX[[2]]^2>threshold[j]] <- 0 }else{ ser.barX[[1]][ser.barX[[1]]^2>threshold[[i]][1:ser.num.barX[1]]] <- 0 ser.barX[[2]][ser.barX[[2]]^2>threshold[[j]][1:ser.num.barX[2]]] <- 0 } ser.num.barX <- ser.num.barX-1 # core part of cce #start <- knij+1 #end <- 1 #for(k in 1:ser.num.barX[1]){ # while(!(ser.times[[1]][k]<ser.times[[2]][start])&&((start-knij)<ser.num.barX[2])){ # start <- start + 1 # } # while((ser.times[[1]][k+knij]>ser.times[[2]][end+1])&&(end<ser.num.barX[2])){ # end <- end + 1 # } # cmat[i,j] <- cmat[i,j] + ser.barX[[1]][k]*sum(ser.barX[[2]][(start-knij):end]) #} cmat[i,j] <- .C("pHayashiYoshida", as.integer(knij), as.integer(ser.num.barX[1]), as.integer(ser.num.barX[2]), as.double(ser.times[[1]]), as.double(ser.times[[2]]), as.double(ser.barX[[1]]), as.double(ser.barX[[2]]), value=double(1), PACKAGE = "yuima")$value cmat[i,j] <- cmat[i,j]/(psi.kn^2) cmat[j,i] <- cmat[i,j] }else{ diffX <- diff(as.numeric(data[[i]])) # pre-averaging kni <- min(kn[i,i],length(data[[i]])) # kn must be less than the number of the observations weight <- sapply((1:(kni-1))/kni,g) psi.kn <- sum(weight) #barX <- rollapplyr(diffX,width=kni-1,FUN="%*%",weight) barX <- filter(diffX,rev(weight),method="c", sides=1)[(kni-1):length(diffX)] num.barX <- length(barX) # thrsholding if(missing(threshold)){ K <- ceiling(num.barX^(3/4)) #K <- ceiling(kn^(3/2)) obj0 <- abs(barX) obj1 <- (pi/2)*obj0[1:(num.barX-kni)]*obj0[-(1:kni)] if(min(K,num.barX-1)<2*kni){ #v.hat <- (median(obj0)/0.6745)^2 v.hat <- mean(obj1) }else{ v.hat <- double(num.barX) #v.hat[1:K] <- (median(obj0[1:K])/0.6745)^2 v.hat[-(1:K)] <- rollmean(obj1[1:(num.barX-2*kni)],k=K-2*kni+1,align="left") v.hat[1:K] <- v.hat[K+1] } #rho <- 2*log(num.barX)* # (median(abs(barX)/sqrt(v.hat))/0.6745)^2*v.hat rho <- 2*log(num.barX)^(1+eps)*v.hat barX[barX^2>rho] <- 0 }else if(is.numeric(threshold)){ threshold <- matrix(threshold,1,n.series) barX[barX^2>threshold[i]] <- 0 }else{ barX[barX^2>threshold[[i]][1:num.barX]] <- 0 } tmp <- barX[-num.barX] #cmat[i,j] <- tmp%*%rollapply(tmp,width=2*(kni-1)+1,FUN="sum",partial=TRUE)/(psi.kn)^2 cmat[i,j] <- tmp%*%rollsum(c(double(kni-1),tmp,double(kni-1)), k=2*(kni-1)+1)/(psi.kn)^2 } } } }else{# non-refreshing, non-cwise # allocate memory ser.X <- vector(n.series, mode="list") # data in 'x' ser.times <- vector(n.series, mode="list") # time index in 'x' ser.diffX <- vector(n.series, mode="list") # difference of data ser.numX <- integer(n.series) ser.barX <- vector(n.series, mode="list") for(i in 1:n.series){ # set data and time index ser.X[[i]] <- as.numeric(data[[i]]) # we need to transform data into numeric to avoid problem with duplicated indexes below ser.times[[i]] <- as.numeric(time(data[[i]])) # set difference of the data ser.diffX[[i]] <- diff( ser.X[[i]] ) ser.numX[i] <- length(ser.diffX[[i]]) } # if missing kn, we select it following Barndorff-Nielsen et al.(2011) if(missing(kn)){ kn <- min(max(ceiling(mean(theta)*sqrt(sum(ser.numX))),2), ser.numX+1) } kn <- kn[1] weight <- sapply((1:(kn-1))/kn,g) psi.kn <- sum(weight) ser.num.barX <- integer(n.series) # pre-averaging and thresholding if(missing(threshold)){ for(i in 1:n.series){ #ser.barX[[i]] <- rollapplyr(ser.diffX[[i]],width=kn-1,FUN="%*%",weight) ser.barX[[i]] <- filter(ser.diffX[[i]],rev(weight),method="c", sides=1)[(kn-1):length(ser.diffX[[i]])] ser.num.barX[i] <- length(ser.barX[[i]]) K <- ceiling(ser.num.barX[i]^(3/4)) obj0 <- abs(ser.barX[[i]]) obj1 <- (pi/2)*obj0[1:(ser.num.barX[i]-kn)]*obj0[-(1:kn)] if(min(K,ser.num.barX[i]-1)<2*kn){ #v.hat <- (median(obj0)/0.6745)^2 v.hat <- mean(obj1) }else{ v.hat <- double(ser.num.barX[i]) #v.hat[1:K] <- (median(obj0[1:K])/0.6745)^2 v.hat[-(1:K)] <- rollmean(obj1[1:(ser.num.barX[i]-2*kn)],k=K-2*kn+1,align="left") v.hat[1:K] <- v.hat[K+1] } #rho <- 2*log(ser.num.barX[ii])* # (median(abs(ser.barX[[ii]])/sqrt(v.hat))/0.6745)^2*v.hat rho <- 2*log(ser.num.barX[i])^(1+eps)*v.hat ser.barX[[i]][ser.barX[[i]]^2>rho] <- 0 } }else if(is.numeric(threshold)){ threshold <- matrix(threshold,1,n.series) for(i in 1:n.series){ ser.barX[[i]] <- rollapplyr(ser.diffX[[i]],width=kn-1,FUN="%*%",weight) ser.num.barX[i] <- length(ser.barX[[i]]) ser.barX[[i]][ser.barX[[i]]^2>threshold[i]] <- 0 } }else{ for(i in 1:n.series){ ser.barX[[i]] <- rollapplyr(ser.diffX[[i]],width=kn-1,FUN="%*%",weight) ser.num.barX[i] <- length(ser.barX[[i]]) ser.barX[[i]][ser.barX[[i]]^2>threshold[[i]][1:ser.num.barX[i]]] <- 0 } } ser.num.barX <- ser.num.barX-1 # core part of cce cmat <- matrix(0, n.series, n.series) # cov for(i in 1:n.series){ for(j in i:n.series){ if(i!=j){ #start <- kn+1 #end <- 1 #for(k in 1:ser.num.barX[i]){ # while(!(ser.times[[i]][k]<ser.times[[j]][start])&&((start-kn)<ser.num.barX[j])){ # start <- start + 1 # } # while((ser.times[[i]][k+kn]>ser.times[[j]][end+1])&&(end<ser.num.barX[j])){ # end <- end + 1 # } # cmat[i,j] <- cmat[i,j] + ser.barX[[i]][k]*sum(ser.barX[[j]][(start-kn):end]) #} cmat[i,j] <- .C("pHayashiYoshida", as.integer(kn), as.integer(ser.num.barX[i]), as.integer(ser.num.barX[j]), as.double(ser.times[[i]]), as.double(ser.times[[j]]), as.double(ser.barX[[i]]), as.double(ser.barX[[j]]), value=double(1), PACKAGE = "yuima")$value cmat[j,i] <- cmat[i,j] }else{ tmp <- ser.barX[[i]][1:ser.num.barX[i]] #cmat[i,j] <- tmp%*%rollapply(tmp,width=2*(kn-1)+1,FUN="sum",partial=TRUE) cmat[i,j] <- tmp%*%rollsum(c(double(kn-1),tmp,double(kn-1)), k=2*(kn-1)+1) } } } cmat <- cmat/(psi.kn^2) } } return(cmat) } ################################################################### # subsampled realized covariance SRC <- function(data,frequency=300,avg=TRUE,utime){ d.size <- length(data) if(missing(utime)) utime <- set_utime(data) # allocate memory ser.X <- vector(d.size, mode="list") # data in 'x' ser.times <- vector(d.size, mode="list") # time index in 'x' ser.numX <- double(d.size) for(d in 1:d.size){ # set data and time index ser.X[[d]] <- as.numeric(data[[d]]) # we need to transform data into numeric to avoid problem with duplicated indexes below ser.times[[d]] <- as.numeric(time(data[[d]]))*utime ser.numX[d] <- length(ser.X[[d]]) } Init <- max(sapply(ser.times,FUN="head",n=1)) Terminal <- max(sapply(ser.times,FUN="tail",n=1)) grid <- seq(Init,Terminal,by=frequency) n.sparse <- length(grid) #I <- matrix(1,d.size,n.sparse) K <- floor(Terminal-grid[n.sparse]) + 1 sdiff1 <- array(0,dim=c(d.size,n.sparse-1,K)) sdiff2 <- array(0,dim=c(d.size,n.sparse-2,frequency-K)) for(d in 1:d.size){ subsample <- matrix(.C("ctsubsampling",as.double(ser.X[[d]]), as.double(ser.times[[d]]), as.integer(frequency),as.integer(n.sparse), as.integer(ser.numX[d]),as.double(grid), result=double(frequency*n.sparse), PACKAGE = "yuima")$result, n.sparse,frequency) sdiff1[d,,] <- diff(subsample[,1:K]) sdiff2[d,,] <- diff(subsample[-n.sparse,-(1:K)]) } if(avg){ #cmat <- matrix(0,d.size,d.size) #for(t in 1:frequency){ # sdiff <- matrix(0,d.size,n.sparse-1) # for(d in 1:d.size){ # for(i in 1:n.sparse){ # while((ser.times[[d]][I[d,i]+1]<=grid[i])&&(I[d,i]<ser.numX[d])){ # I[d,i] <- I[d,i]+1 # } # } # sdiff[d,] <- diff(ser.X[[d]][I[d,]]) # } # cmat <- cmat + sdiff%*%t(sdiff) # grid <- grid+rep(1,n.sparse) # if(grid[n.sparse]>Terminal){ # grid <- grid[-n.sparse] #I <- I[,-n.sparse] # n.sparse <- n.sparse-1 # I <- matrix(I[,-n.sparse],d.size,n.sparse) # } #} #cmat <- cmat/frequency cmat <- matrix(rowMeans(cbind(apply(sdiff1,3,FUN=function(x) x %*% t(x)), apply(sdiff2,3,FUN=function(x) x %*% t(x)))), d.size,d.size) }else{ #sdiff <- matrix(0,d.size,n.sparse-1) #for(d in 1:d.size){ # for(i in 1:n.sparse){ # while((ser.times[[d]][I[d,i]+1]<=grid[i])&&(I[d,i]<ser.numX[d])){ # I[d,i] <- I[d,i]+1 # } # } # sdiff[d,] <- diff(ser.X[[d]][I[d,]]) #} #cmat <- sdiff%*%t(sdiff) if(K>0){ cmat <- sdiff1[,,1]%*%t(sdiff1[,,1]) }else{ cmat <- sdiff2[,,1]%*%t(sdiff2[,,1]) } } return(cmat) } ############################################################## # subsampled realized bipower covariation BPC <- function(sdata){ d.size <- nrow(sdata) cmat <- matrix(0,d.size,d.size) for(i in 1:d.size){ for(j in i:d.size){ if(i!=j){ cmat[i,j] <- (BPV(sdata[i,]+sdata[j,])-BPV(sdata[i,]-sdata[j,]))/4 cmat[j,i] <- cmat[i,j] }else{ cmat[i,i] <- BPV(sdata[i,]) } } } return(cmat) } SBPC <- function(data,frequency=300,avg=TRUE,utime){ d.size <- length(data) if(missing(utime)) utime <- set_utime(data) # allocate memory ser.X <- vector(d.size, mode="list") # data in 'x' ser.times <- vector(d.size, mode="list") # time index in 'x' ser.numX <- double(d.size) for(d in 1:d.size){ # set data and time index ser.X[[d]] <- as.numeric(data[[d]]) # we need to transform data into numeric to avoid problem with duplicated indexes below ser.times[[d]] <- as.numeric(time(data[[d]]))*utime ser.numX[d] <- length(ser.X[[d]]) } Init <- max(sapply(ser.times,FUN="head",n=1)) Terminal <- max(sapply(ser.times,FUN="tail",n=1)) grid <- seq(Init,Terminal,by=frequency) n.sparse <- length(grid) #I <- matrix(1,d.size,n.sparse) K <- floor(Terminal-grid[n.sparse]) + 1 sdata1 <- array(0,dim=c(d.size,n.sparse,K)) sdata2 <- array(0,dim=c(d.size,n.sparse-1,frequency-K)) for(d in 1:d.size){ subsample <- matrix(.C("ctsubsampling",as.double(ser.X[[d]]), as.double(ser.times[[d]]), as.integer(frequency),as.integer(n.sparse), as.integer(ser.numX[d]),as.double(grid), result=double(frequency*n.sparse), PACKAGE = "yuima")$result, n.sparse,frequency) sdata1[d,,] <- subsample[,1:K] sdata2[d,,] <- subsample[-n.sparse,-(1:K)] } if(avg){ cmat <- matrix(0,d.size,d.size) #for(t in 1:frequency){ # sdata <- matrix(0,d.size,n.sparse) # for(d in 1:d.size){ # for(i in 1:n.sparse){ # while((ser.times[[d]][I[d,i]+1]<=grid[i])&&(I[d,i]<ser.numX[d])){ # I[d,i] <- I[d,i]+1 # } # } # sdata[d,] <- ser.X[[d]][I[d,]] # } # cmat <- cmat + BPC(sdata) # grid <- grid+rep(1,n.sparse) # if(grid[n.sparse]>Terminal){ # grid <- grid[-n.sparse] #I <- I[,-n.sparse] # n.sparse <- n.sparse-1 # I <- matrix(I[,-n.sparse],d.size,n.sparse) # } #} #cmat <- cmat/frequency cmat <- matrix(rowMeans(cbind(apply(sdata1,3,FUN=BPC), apply(sdata2,3,FUN=BPC))), d.size,d.size) }else{ #sdata <- matrix(0,d.size,n.sparse) #for(d in 1:d.size){ # for(i in 1:n.sparse){ # while((ser.times[[d]][I[d,i]+1]<=grid[i])&&(I[d,i]<ser.numX[d])){ # I[d,i] <- I[d,i]+1 # } # } # sdata[d,] <- ser.X[[d]][I[d,]] #} #cmat <- BPC(sdata) if(K>0){ cmat <- BPC(sdata1[,,1]) }else{ cmat <- BPC(sdata2[,,1]) } } return(cmat) } # # CumulativeCovarianceEstimator # # returns a matrix of var-cov estimates setGeneric("cce", function(x,method="HY",theta,kn,g=function(x)min(x,1-x), refreshing=TRUE,cwise=TRUE, delta=0,adj=TRUE,K,c.two,J=1,c.multi, kernel,H,c.RK,eta=3/5,m=2,ftregion=0, vol.init=NA,covol.init=NA,nvar.init=NA,ncov.init=NA, mn,alpha=0.4,frequency=300,avg=TRUE, threshold,utime,psd=FALSE) standardGeneric("cce")) setMethod("cce",signature(x="yuima"), function(x,method="HY",theta,kn,g=function(x)min(x,1-x), refreshing=TRUE,cwise=TRUE, delta=0,adj=TRUE,K,c.two,J=1,c.multi, kernel,H,c.RK,eta=3/5,m=2,ftregion=0, vol.init=NA,covol.init=NA, nvar.init=NA,ncov.init=NA,mn,alpha=0.4, frequency=300,avg=TRUE,threshold,utime,psd=FALSE) cce(x@data,method=method,theta=theta,kn=kn,g=g,refreshing=refreshing, cwise=cwise,delta=delta,adj=adj,K=K,c.two=c.two,J=J, c.multi=c.multi,kernel=kernel,H=H,c.RK=c.RK,eta=eta,m=m, ftregion=ftregion,vol.init=vol.init, covol.init=covol.init,nvar.init=nvar.init, ncov.init=ncov.init,mn=mn,alpha=alpha, frequency=frequency,avg=avg,threshold=threshold, utime=utime,psd=psd)) setMethod("cce",signature(x="yuima.data"), function(x,method="HY",theta,kn,g=function(x)min(x,1-x), refreshing=TRUE,cwise=TRUE, delta=0,adj=TRUE,K,c.two,J=1,c.multi, kernel,H,c.RK,eta=3/5,m=2,ftregion=0, vol.init=NA,covol.init=NA, nvar.init=NA,ncov.init=NA,mn,alpha=0.4, frequency=300,avg=TRUE,threshold,utime,psd=FALSE){ data <- get.zoo.data(x) d.size <- length(data) for(i in 1:d.size){ # NA data must be skipped idt <- which(is.na(data[[i]])) if(length(idt>0)){ data[[i]] <- data[[i]][-idt] } if(length(data[[i]])<2) { stop("length of data (w/o NA) must be more than 1") } } cmat <- NULL switch(method, "HY"="<-"(cmat,HY(data)), "PHY"="<-"(cmat,PHY(data,theta,kn,g,refreshing,cwise)), "MRC"="<-"(cmat,MRC(data,theta,kn,g,delta,adj)), "TSCV"="<-"(cmat,TSCV(data,K,c.two,J,adj,utime)), "GME"="<-"(cmat,GME(data,c.multi,utime)), "RK"="<-"(cmat,RK(data,kernel,H,c.RK,eta,m,ftregion,utime)), "QMLE"="<-"(cmat,cce.qmle(data,vol.init,covol.init, nvar.init,ncov.init)), "SIML"="<-"(cmat,SIML(data,mn,alpha)), "THY"="<-"(cmat,THY(data,threshold)), "PTHY"="<-"(cmat,PTHY(data,theta,kn,g,threshold, refreshing,cwise)), "SRC"="<-"(cmat,SRC(data,frequency,avg,utime)), "SBPC"="<-"(cmat,SBPC(data,frequency,avg,utime))) if(is.null(cmat)) stop("method is not available") if(psd){ #tmp <- svd(cmat%*%cmat) #cmat <- tmp$u%*%diag(sqrt(tmp$d))%*%t(tmp$v) tmp <- eigen(cmat) cmat <- tmp$vectors %*% (abs(tmp$values) * t(tmp$vectors)) } if(d.size>1){ #if(all(diag(cmat)>0)){ #sdmat <- diag(sqrt(diag(cmat))) #cormat <- solve(sdmat) %*% cmat %*% solve(sdmat) #}else{ # cormat <- NA #} cormat <- cov2cor(cmat) }else{ cormat <- as.matrix(1) } rownames(cmat) <- names(data) colnames(cmat) <- names(data) rownames(cormat) <- names(data) colnames(cormat) <- names(data) return(list(covmat=cmat,cormat=cormat)) })
/scratch/gouwar.j/cran-all/cranData/yuima/R/cce.R
###################################################### # High-Dimensional Cumulative Covariance Estimator # by Factor Modeling and Regularization ###################################################### cce.factor <- function(yuima, method = "HY", factor = NULL, PCA = FALSE, nfactor = "interactive", regularize = "glasso", taper, group = 1:(dim(yuima) - length(factor)), lambda = "bic", weight = TRUE, nlambda = 10, ratio, N, thr.type = "soft", thr = NULL, tau = NULL, par.alasso = 1, par.scad = 3.7, thr.delta = 0.01, frequency = 300, utime, ...){ cmat <- cce(yuima, method = method, frequency = frequency,utime = utime, ...)$covmat if(missing(N)) N <- effective.n(yuima, method, frequency, utime) if(PCA){ ed <- eigen(cmat, symmetric = TRUE) pc <- ed$values if(nfactor == "interactive"){ plot(pc, type = "h", ylab = "PC scores", main = "Scree plot") nfactor <- readline("Type the number of factors you want to use. \n") } if(nfactor == 0){ factor <- NULL sigma.z <- sigma.y beta.hat <- NULL sigma.x <- NULL }else{ factor <- "PCA" sigma.x <- diag(ed$values[1:nfactor], nfactor) inv.sigma.x <- solve(sigma.x) beta.hat <- as.matrix(ed$vectors[ ,1:nfactor]) sigma.f <- tcrossprod(beta.hat %*% sigma.x, beta.hat) sigma.z <- cmat - sigma.f } }else{ pc <- NULL if(is.null(factor)){ sigma.z <- cmat beta.hat <- NULL sigma.x <- NULL }else{ if(is.character(factor)) factor <- which(rownames(cmat) %in% factor) sigma.y <- as.matrix(cmat[-factor,-factor]) sigma.x <- as.matrix(cmat[factor,factor]) sigma.yx <- as.matrix(cmat[-factor,factor]) # is sigma.x singular? inv.sigma.x <- solve(sigma.x) beta.hat <- sigma.yx %*% inv.sigma.x sigma.f <- tcrossprod(beta.hat %*% sigma.x, beta.hat) sigma.z <- sigma.y - sigma.f } } reg.result <- cce.regularize(sigma.z, regularize, taper, group, lambda, weight, nlambda, ratio, N, thr.type, thr, tau, par.alasso, par.scad, thr.delta) if(is.null(factor)){ covmat.y <- reg.result$cmat premat.y <- reg.result$pmat }else{ covmat.y <- sigma.f + reg.result$cmat # using Sherman-Morisson-Woodbury formula to compute the inverse beta.pmat <- crossprod(beta.hat, reg.result$pmat) premat.y <- reg.result$pmat - crossprod(beta.pmat, solve(inv.sigma.x + beta.pmat %*% beta.hat) %*% beta.pmat) } return(list(covmat.y = covmat.y, premat.y = premat.y, beta.hat = beta.hat, covmat.x = sigma.x, covmat.z = reg.result$cmat, premat.z = reg.result$pmat, sigma.z = sigma.z, pc = pc)) } cce.regularize <- function(cmat, method = "tapering", taper, group, lambda = "bic", weight = TRUE, nlambda = 10, ratio, N, thr.type = "hard", thr = NULL, tau = NULL, par.alasso = 1, par.scad = 3.7, thr.delta = 0.01){ result <- switch(method, tapering = cce.taper(cmat, taper, group), glasso = rglasso(cmat, lambda, weight, nlambda, ratio, N), eigen.cleaning = eigen.cleaning(cmat, N), thresholding = cce.thr(cmat, thr.type, thr, tau, par.alasso, par.scad, thr.delta)) return(result) } ## if matrix inversion is failed, the result is set to NA myinv <- function(X){ result <- try(solve(X), silent = TRUE) #if(!is.numeric(result)) result <- try(ginv(X)) if(!is.numeric(result)) result <- NA return(result) } ################################## # tapering related functions ################################## cce.taper <- function(cmat, taper, group){ if(missing(taper)){ taper <- outer(group, group, FUN = function(x, y) x == y) } cmat.tilde <- cmat * taper return(list(cmat = cmat.tilde, pmat = myinv(cmat.tilde))) } ################################## # glasso related functions ################################## rglasso.path <- function(S, lambda, weight = TRUE, nlambda, ratio){ if(weight){ W <- sqrt(diag(S) %o% diag(S)) }else{ W <- matrix(1, nrow(S), ncol(S)) } diag(W) <- 0 if(missing(lambda)){ lambda.max <- max(abs((S/W)[upper.tri(S)])) lambda.min <- ratio * lambda.max lambda <- exp(seq(log(lambda.min), log(lambda.max), length = nlambda)) } f <- function(rho){ res <- glassoFast::glassoFast(S, rho * W) return(list(w = res$w, wi = res$wi)) } out <- lapply(lambda, FUN = f) w <- lapply(out, function(x) x$w) wi <- lapply(out, function(x) x$wi) return(list(w = w, wi = wi, lambda = lambda)) } IC.rglasso <- function(out, s, n){ f <- function(wi){ nll <- -log(det(wi)) + sum(wi * s) J <- sum(wi[upper.tri(wi, diag = TRUE)] != 0) return(c(aic = nll + (2/n)*J, bic = nll + (log(n)/n)*J)) } res <- sapply(out$wi, FUN = f) return(res) } effective.n <- function(yuima, method, frequency, utime){ if(method == "HY" | method == "THY"){ out <- min(length(yuima)) }else if(method == "SRC" | method == "SBPC"){ if(missing(utime)) utime <- set_utime(get.zoo.data(yuima)) out <- utime/frequency }else if(method == "RK" | method == "SIML"){ out <- min(length(yuima))^(2/5) }else if(method == "TSCV"){ out <- min(length(yuima))^(1/3) }else{ out <- sqrt(min(length(yuima))) } return(out) } rglasso <- function(S, lambda = "aic", weight = TRUE, nlambda = 10, ratio, N){ if(lambda == "aic" | lambda == "bic"){ if(missing(ratio)) ratio <- sqrt(log(nrow(S))/N) out <- rglasso.path(S, weight = weight, nlambda = nlambda, ratio = ratio) ic <- IC.rglasso(out, S, N) idx <- which.min(ic[lambda, ]) #w <- out$w[[idx]] wi <- out$wi[[idx]] w <- solve(wi) lambda <- out$lambda[idx] }else{ out <- rglasso.path(S, lambda = lambda, weight = weight) #w <- out$w[[1]] wi <- out$wi[[1]] w <- solve(wi) } attr(w, "lambda") <- lambda attr(wi, "lambda") <- lambda dimnames(w) <- dimnames(S) dimnames(wi) <- dimnames(S) return(list(cmat = w, pmat = wi)) } ################################## # eigen.cleaning related functions ################################## eigen.cleaning <- function(S, N){ p <- ncol(S) #if(missing(N)) N <- effective.n(yuima, method, frequency, utime) q <- N/p R <- cov2cor(S) ed <- eigen(R, symmetric = TRUE) lambda <- ed$values sigma2 <- 1 - max(lambda)/p lambda.max <- sigma2 * (1 + 1/q + 2/sqrt(q)) idx <- (lambda > lambda.max) delta <- (sum(lambda[lambda > 0]) - sum(lambda[idx]))/(p - sum(idx)) lambda[!idx] <- delta obj <- sqrt(diag(S)) cmat <- tcrossprod(ed$vectors %*% diag(lambda), ed$vectors) cmat <- obj * cmat %*% diag(obj) #pmat <- solve(cmat) pmat <- tcrossprod(ed$vectors %*% diag(1/lambda), ed$vectors) pmat <- (1/obj) * cmat %*% diag(1/obj) dimnames(cmat) <- dimnames(S) dimnames(pmat) <- dimnames(S) return(list(cmat = cmat, pmat = pmat)) } ################################## # thresholding related functions ################################## thr.hard <- function(S, thr){ out <- S * (abs(S) > thr) diag(out) <- diag(S) return(out) } thr.soft <- function(S, thr){ out <- sign(S) * pmax(abs(S) - thr, 0) diag(out) <- diag(S) return(out) } thr.alasso <- function(S, thr, par.alasso = 1){ out <- sign(S) * pmax(abs(S) - thr^(par.alasso + 1)/abs(S)^par.alasso, 0) diag(out) <- diag(S) return(out) } thr.scad <- function(S, thr, par.scad = 3.7){ out <- S idx <- (abs(S) <= par.scad * thr) out[idx] <- ((par.scad - 1) * S[idx] - sign(S[idx]) * par.scad * thr[idx])/(par.scad - 2) idx <- (abs(S) <= 2 * thr) out[idx] <- sign(S[idx]) * pmax(abs(S[idx]) - thr[idx], 0) diag(out) <- diag(S) return(out) } thr.fun <- function(S, type = "hard", thr, par.alasso = 1, par.scad = 3.7){ thr <- matrix(thr, nrow(S), ncol(S)) out <- switch (type, hard = thr.hard(S, thr), soft = thr.soft(S, thr), alasso = thr.alasso(S, thr, par.alasso), scad = thr.scad(S, thr, par.scad) ) return(out) } check.pd <- function(S){ lambda <- min(eigen(S, symmetric = TRUE, only.values = TRUE)$values) if(lambda < 0 | isTRUE(all.equal(lambda, 0))){ return(FALSE) }else{ return(TRUE) } } cce.thr <- function(S, type = "hard", thr = NULL, tau = NULL, par.alasso = 1, par.scad = 3.7, thr.delta = 0.01){ if(is.null(thr)){ if(is.null(tau)){ #if(check.pd(S)){ # tau <- 0 #}else{ # # R <- cov2cor(S) # tau.seq <- sort(abs(R[upper.tri(R)])) + .Machine$double.eps # # for(tau in tau.seq){ # tmp.R <- thr.fun(R, type, tau, par.alasso, par.scad) # if(check.pd(tmp.R)) break # } #} R <- cov2cor(S) tau.seq <- seq(0, 1, by = thr.delta) for(tau in tau.seq){ tmp.R <- thr.fun(R, type, tau, par.alasso, par.scad) if(check.pd(tmp.R)) break } #f <- function(tau){ # tmp.R <- thr.fun(R, type, tau, par.alasso, par.scad) # return(min(eigen(tmp.R)$value)) #} #tau <- uniroot(f, interval = c(0, 1))$root } thr <- tau * tcrossprod(sqrt(diag(S))) } cmat <- thr.fun(S, type, thr, par.alasso, par.scad) pmat <- myinv(cmat) attr(cmat, "thr") <- thr attr(pmat, "thr") <- thr dimnames(cmat) <- dimnames(S) dimnames(pmat) <- dimnames(S) return(list(cmat = cmat, pmat = pmat)) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/cce.factor.R
## 7/8/2021 Kito ## Some functions didn't work when 'fixed' parameters are given. (at present, qmle and adaBayes) ## We added functions below to allow functions above to work with fixed params by rewriting yuima model. transform.drift <- function(drift, fixed, unfixed.nms, state.nms ,index, unfixed.vals, state.vals){## Kurisaki 4/10/2021 drift <- drift fixed <- fixed unfixed.nms <- unfixed.nms state.nms <- state.nms unfixed.vals <- unfixed.vals state.vals <- state.vals ## substitute for the fixed parameters for(var in names(fixed)) { assign(var, fixed[[var]]) } ## substitute for the unfixed parameters i <- 1 for(nm in unfixed.nms) { assign(nm, unfixed.vals[i]) i <- i+1 } ## substitute for the state parameters i <- 1 for(nm in state.nms) { assign(nm, state.vals[,i]) i <- i+1 } eval(drift[index]) } transform.diffusion <- function(diffusion, fixed, unfixed.nms, state.nms, row, index, unfixed.vals, state.vals){ diffusion <- diffusion fixed <- fixed unfixed.nms <- unfixed.nms state.nms <- state.nms unfixed.vals <- unfixed.vals state.vals <- state.vals ## substitute for the fixed parameters for(var in names(fixed)) { assign(var, fixed[[var]]) } ## substitute x for the unfixed parameters i <- 1 for(nm in unfixed.nms) { assign(nm, unfixed.vals[i]) i <- i+1 } ## substitute for the state parameters i <- 1 for(nm in state.nms) { assign(nm, state.vals[,i]) i <- i+1 } eval(diffusion[[row]][index]) } transform.jump <- function(jump, fixed, unfixed.nms, state.nms, row, index, unfixed.vals, state.vals){ jump <- jump fixed <- fixed unfixed.nms <- unfixed.nms state.nms <- state.nms unfixed.vals <- unfixed.vals state.vals <- state.vals ## substitute for the fixed parameters for(var in names(fixed)) { assign(var, fixed[[var]]) } ## substitute for the unfixed parameters i <- 1 for(nm in unfixed.nms) { assign(nm, unfixed.vals[i]) i <- i+1 } ## substitute for the state parameters i <- 1 for(nm in state.nms) { assign(nm, state.vals[,i]) i <- i+1 } eval(jump[[row]][index]) } changeFixedParametersToConstant <- function(yuima, fixed) { env <- new.env() # environment to calculate estimation yuima = yuima fixed = fixed # list of names of unfixed parameters drift.unfixed.nms = yuima@model@parameter@drift[!is.element(yuima@model@parameter@drift, names(fixed))] diffusion.unfixed.nms = yuima@model@parameter@diffusion[!is.element(yuima@model@parameter@diffusion, names(fixed))] # list of names of state variables state.nms = yuima@[email protected] # arguments for new.drift.func & new.diffusion.func state.vals = paste("matrix(c(", paste(state.nms, collapse=", "), "), ncol=", length(state.nms),")") drift.unfixed.vals = paste("c(", paste(drift.unfixed.nms, collapse=", "), ")") diffusion.unfixed.vals = paste("c(", paste(diffusion.unfixed.nms, collapse=", "), ")") new.drift.func <- function(index, unfixed.vals, state.vals){transform.drift(yuima@model@drift, fixed, drift.unfixed.nms, state.nms, index, unfixed.vals, state.vals)} new.diffusion.func <- function(row, index, unfixed.vals, state.vals){transform.diffusion(yuima@model@diffusion, fixed, diffusion.unfixed.nms, state.nms, row, index, unfixed.vals, state.vals)} # new drift and diffusion term transformed.drift <- paste("new.drift.func(", 1:length(yuima@model@drift), ", ", drift.unfixed.vals, ", ", state.vals, ")", sep="") vector.diffusion <- c() for(row in 1:length(yuima@model@diffusion)) { vector.diffusion <- c(vector.diffusion, paste("new.diffusion.func(", row, ", ", 1:length(yuima@model@diffusion[[row]]), ", ", diffusion.unfixed.vals, ", ", state.vals, ")", sep="")) } transformed.diffusion <- matrix(vector.diffusion, nrow = length(yuima@model@diffusion),byrow=T) # new jump term if(length(yuima@[email protected]) > 0) { jump.unfixed.nms <- yuima@model@parameter@jump[!is.element(yuima@model@parameter@jump, names(fixed))] jump.unfixed.vals = paste("c(", paste(jump.unfixed.nms, collapse=", "), ")") new.jump.func <- function(row, index, unfixed.vals, state.vals){transform.jump(yuima@[email protected], fixed, jump.unfixed.nms, state.nms, row, index, unfixed.vals, state.vals)} vector.jump <- c() for(row in 1:length(yuima@[email protected])) { vector.jump <- c(vector.jump, paste("new.jump.func(", row, ", ", 1:length(yuima@[email protected][[row]]), ", ", jump.unfixed.vals, ", ", state.vals, ")", sep="")) } transformed.jump <- matrix(vector.jump, nrow = length(yuima@[email protected]),byrow=T) new.measure = list() measure.params <- yuima@model@parameter@measure df.measure.params <- measure.params if(yuima@[email protected]=="CP"){ intensity <- as.character(yuima@model@measure$intensity) if(is.element(intensity, names(fixed))) { df.measure.params <- df.measure.params[-which(df.measure.params %in% intensity)] intensity = as.character(fixed[intensity]) } new.measure[["intensity"]] <- intensity } df <- yuima@model@measure$df expr <- df$expr cal <- as.call(expr[[1]]) params <- as.list(cal[-1]) for(i in 1:length(params)) { if(is.element(c(params[[i]]), names(fixed))) { params[[i]] <- fixed[[params[[i]]]] } } cal[-1] <- as.call(params) new.measure[["df"]] <- list(as.character(as.expression(cal))) } else { transformed.jump <- NULL new.measure <- list() } new.ymodel <- setModel(drift = transformed.drift, diffusion = transformed.diffusion, hurst = yuima@model@hurst, jump.coeff = transformed.jump, measure = new.measure, measure.type = yuima@[email protected], state.variable = yuima@[email protected], jump.variable = yuima@[email protected], time.variable = yuima@[email protected], solve.variable = yuima@[email protected], xinit = yuima@model@xinit) new.yuima <- setYuima(data = yuima@data, model = new.ymodel, sampling = yuima@sampling, characteristic = yuima@characteristic, functional = yuima@functional) return(list(new.yuima=new.yuima, env=env)) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/changeFixedToConstant.R
# In this code we implement a filter that returns the increments of the undelying levy process # if the model is a COGARCH(P,Q) # Using the squared of returns, we obtain the increment of Levy process using the relation # Y_t=e^{A\Delta t}Y_{t-\Delta t}+e^{A\left(\Delta t\right)}e\left(\Delta G_{t}\right)^{2}. # for the state process $Y_t$ and then the levy increments definely are: # \Delta L_{t}=\frac{\Delta G_{t}}{\sqrt{V_{t}}}. cogarchNoise<-function(yuima, data=NULL, param, mu=1){ yuima.cogarch <- yuima if(missing(yuima.cogarch)) yuima.stop("yuima.cogarch or yuima object is missing.") if(length(param)==0) yuima.stop("missing values parameters") if(!is.COGARCH(yuima.cogarch)){ yuima.warn("The model does not belong to the class yuima.cogarch") } if(is(yuima.cogarch,"yuima")){ model<-yuima.cogarch@model if(is.null(data)){ observ<-yuima.cogarch@data }else{observ<-data} }else{ if(is(yuima.cogarch,"yuima.cogarch")){ model<-yuima.cogarch if(is.null(data)){ yuima.stop("Missing data") } observ<-data } } info <- model@info numb.ar <- info@q ar.name <- paste([email protected],c(numb.ar:1),sep="") numb.ma <- info@p ma.name <- paste([email protected],c(1:numb.ma),sep="") loc.par <- [email protected] nm <- c(names(param)) param<-as.numeric(param) names(param)<-nm xinit.name0 <- model@parameter@xinit idx <- na.omit(match(c(loc.par, ma.name), xinit.name0)) xinit.name <- xinit.name0[-idx] fullcoeff <- c(ar.name, ma.name, loc.par,xinit.name) # oo <- match(nm, fullcoeff) # # if(any(is.na(oo))) # yuima.stop("some named arguments in 'param' are not arguments to the supplied yuima.cogarch model") acoeff <- param[ma.name] b <- param[ar.name] cost<- param[loc.par] Data<-as.matrix(onezoo(observ)[,1]) #freq<-round(frequency(onezoo(observ)[,1])) freq<- diff(time(onezoo(observ))) res<-auxcogarch.noise(cost,b,acoeff,mu,Data,freq,[email protected]) return(res) } auxcogarch.noise<-function(cost,b,acoeff,mu,Data,freq,lab){ res<-StationaryMoments(cost,b,acoeff,mu) ExpY0<-res$ExpStatVar q<-length(b) a <- e <- matrix(0,nrow=q,ncol=1) e[q,1] <- 1 p<-length(acoeff) a[1:p,1] <- acoeff B <- MatrixA(b[c(q:1)]) DeltaG <- c(0,diff(Data)) squaredG <- DeltaG^2 Process_Y <- ExpY0 # Process_Y1 <- ExpY0 # Process_Y <- as.matrix(50.33) var_V<-cost + sum(a*Process_Y) # delta <- 1/freq deltatot <- c(0,freq) for(t in c(2:(length(Data)))){ # Y_t=e^{A\Delta t}Y_{t-\Delta t}+e^{A\left(\Delta t\right)}e\left(\Delta G_{t}\right)^{2} delta <- deltatot[t] Process_Y <- cbind(Process_Y, (expm(B*delta)%*%(Process_Y[,t-1]+e*squaredG[t]))) # Process_Y1 <- merge(Process_Y1, (expm(B*delta)%*%(Process_Y1[,t-1]+e*squaredG[t]))) #Process_Y <- cbind(Process_Y, (Process_Y[,t-1]+delta*B%*%Process_Y[,t-1]+e*squaredG[t])) # sim[t,3:ncolsim]<-sim[t-1,3:ncolsim]+(AMatrix*Delta)%*%sim[t-1,3:ncolsim]+evect*sim[t-1,2]*incr.L[2,t-1] # sim[t,2]<-value.a0+tavect%*%sim[t-1,3:ncolsim] # sim[t,1]<-sim[t-1,1]+sqrt(sim[t,2])*incr.L[1,t] var_V[t] <- cost + t(a)%*%Process_Y[,t-1] } #\Delta L_{t}=\frac{\Delta G_{t}}{\sqrt{V_{t}}}. incr.L<- DeltaG/sqrt(var_V) CogDum <- cbind(var_V,t(Process_Y)) DumRet <- as.numeric(Data[1]+cumsum(DeltaG)) Cog <- cbind(DumRet,CogDum) colnames(Cog) <- lab Cog <- zoo(Cog, order.by = cumsum(deltatot)) # Dataset on true irregular grid Cogarch <- setData(Cog) res<-list(incr.L=incr.L, Cogarch=Cogarch) return(res) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/cogarchNoise.R
## function to provide the preliminary explicit estimator get_preliminaryEstimators <- function(data){ # use data returned from calling simulate_CIR() n <- dim(data)[2]-1 # we have observations at t_j for j=0,...,n, this equals n+1 observations in total # -> therefore, n is the number of observations minus 1. h <- as.numeric(data[1,2]) # as the vector containing the t always starts with 0, this equals diff(data[1,])[1] # and thus gives h if the t_j are chosen to be equidistant. X_major <- data[2,-1] # the observations of the CIR process starting at t_1=h. X_minor <- head(data[2,], -1) # the observations of the CIR process discarding j=n. X_mean_major <- mean(X_major) # mean of all observations without j=0. X_mean_minor <- mean(X_minor) # mean of all observations without j=n. beta_0n <- -1/h * log( sum((X_minor - X_mean_minor) * (X_major - X_mean_major)) / # calculate estimate for beta from Eq. (2.6) sum( (X_minor - X_mean_minor) ^ 2 ) ) alpha_0n <- (X_mean_major - exp(-beta_0n * h) * X_mean_minor) * beta_0n / (1 - exp(-beta_0n * h) ) # calculate estimate for alpha from Eq. (2.5) to_gamma_numerator <- (X_major - exp(-beta_0n * h) * X_minor - alpha_0n / beta_0n * (1 - exp(-beta_0n * h))) ^ 2 to_gamma_denominator <- (1 - exp(-beta_0n * h)) / beta_0n * (exp(-beta_0n * h) * X_minor + alpha_0n * (1 - exp(-beta_0n * h)) / (2 * beta_0n) ) gamma_0n <- 1 / n * sum(to_gamma_numerator / to_gamma_denominator) # calculate estimate for gamma from Eq. (2.7), where first the numerator and denominator # are computed separately. return(as.matrix(c(alpha_0n, beta_0n, gamma_0n))) # return the estimated parameter vector. } ### ONE STEP IMPROVEMENT # first we need a few auxiliary functions #the mean of the CIR with parameter (alpha,beta,gamma) conditioned on X_h=x mu<- function(alpha,beta,gamma,x,h){ return(exp(-beta*h)*x+alpha/beta*(1-exp(-beta*h))) } #derivatives of the mean of CIR with parameter (alpha,beta,gamma) conditioned on X_h=x mu_alpha <-function(alpha,beta,gamma,x,h) { return ((1-exp(-beta*h))/beta) } mu_alpha_alpha<-function(alpha,beta,gamma,x,h) { return (0) } mu_alpha_beta <- function(alpha,beta,gamma,x,h) { return ( (exp(-beta*h)*(beta*h+1)-1)/beta^2) } mu_alpha_gamma <- function(alpha,beta,gamma,x,h) { return (0) } mu_beta <- function(alpha,beta,gamma,x,h) { return(-h*exp(-beta*h)*x+alpha*(exp(-beta*h)*(beta*h+1)-1)/beta^2) } mu_beta_beta <- function(alpha,beta,gamma,x,h) { return(h^2*exp(-beta*h)*x+alpha*(exp(-beta*h)*(-beta^2*h^2-2*beta*h-2)+2)/beta^3) } mu_beta_gamma <- function(alpha,beta,gamma,x,h) { return(0) } mu_gamma <- function(alpha,beta,gamma,x,h) { return(0) } mu_gamma_gamma <- function(alpha,beta,gamma,x,h) { return(0) } #the variance of CIR with parameter (alpha,beta,gamma) conditioned on X_h=x sigma_mod <- function(alpha,beta,gamma,x,h){ ## HM 2022/6/21: sigma --> sigma_mod return(gamma/beta*(1-exp(-beta*h))*(exp(-beta*h)*x+alpha/(2*beta)*(1-exp(-beta*h)))) } #derivatives of the variance of CIR with parameter (alpha,beta,gamma) conditioned on X_h=x sigma_alpha <- function(alpha,beta,gamma,x,h) { return(gamma*(1-exp(-beta*h))^2/(2*beta^2)) } sigma_alpha_alpha <- function(alpha,beta,gamma,x,h) { return(0) } sigma_alpha_beta <- function(alpha,beta,gamma,x,h) { return(- gamma*exp(-2*beta*h)*(exp(beta*h)-1)*(-beta*h+exp(beta*h)-1)/beta^3) } sigma_alpha_gamma <- function(alpha,beta,gamma,x,h) { return((1-exp(-beta*h))^2/(2*beta^2)) } sigma_beta <- function(alpha, beta, gamma, x, h) { exp(-2 * h * beta) / beta ^3 * ( x * beta * (2 * h * beta - exp(h * beta) * (h * beta + 1) + 1) - alpha * (exp(beta * h) - 1) * (-h * beta + exp(h * beta) - 1) ) } sigma_beta_beta <- function(alpha,beta,gamma,x,h) { exp(-2 * beta * h) / (beta ^ 4) * ( alpha * (2 * h * beta * (h * beta + 2) + 3 * exp(2 * beta * h) - exp(h * beta) * (h * beta * (h * beta + 4) + 6) + 3) + x * beta * (exp(beta * h) * (h ^ 2 * beta ^ 2 + 2 * h * beta + 2) - 2 * (2 * h ^ 2 * beta ^ 2 + 2 * h * beta + 1)) ) } sigma_beta_gamma <- function(alpha,beta,gamma,x,h) { return(h*exp(-beta*h)*(exp(-beta*h)*x/beta+alpha*(1-exp(-beta*h))/(2*beta^2))+(1-exp(-beta*h))* (-exp(-beta*h)*(beta*h+1)/beta^2*x+alpha*exp(-beta*h)*(beta*h-2*exp(beta*h)+2)/(2*beta^3))) } sigma_gamma <- function(alpha,beta,gamma,x,h) { return((1-exp(-beta*h))*(exp(-beta*h)*x+alpha/(2*beta)*(1-exp(-beta*h)))/beta) } sigma_gamma_gamma <- function(alpha,beta,gamma,x,h) { return(0) } #the inverse of the Hessian matrix of H_n H_n_Hessian <- function(alpha,beta,gamma,x,h) { mu <- mu(alpha,beta,gamma,x,h) mu_1 <- mu_alpha(alpha,beta,gamma,x,h) mu_2 <- mu_beta(alpha,beta,gamma,x,h) mu_3 <- mu_gamma(alpha,beta,gamma,x,h) mu_11 <- mu_alpha_alpha(alpha,beta,gamma,x,h) mu_12 <- mu_alpha_beta(alpha,beta,gamma,x,h) mu_13 <- mu_alpha_gamma(alpha,beta,gamma,x,h) mu_22 <- mu_beta_beta(alpha,beta,gamma,x,h) mu_23 <- mu_beta_gamma(alpha,beta,gamma,x,h) mu_33 <- mu_gamma_gamma(alpha,beta,gamma,x,h) sigma <- sigma_mod(alpha,beta,gamma,x,h) ## HM 2022/6/21: sigma --> sigma_mod sigma_1 <- sigma_alpha(alpha,beta,gamma,x,h) sigma_2 <- sigma_beta(alpha,beta,gamma,x,h) sigma_3 <- sigma_gamma(alpha,beta,gamma,x,h) sigma_11 <- sigma_alpha_alpha(alpha,beta,gamma,x,h) sigma_12 <- sigma_alpha_beta(alpha,beta,gamma,x,h) sigma_13 <- sigma_alpha_gamma(alpha,beta,gamma,x,h) sigma_22 <- sigma_beta_beta(alpha,beta,gamma,x,h) sigma_23 <- sigma_beta_gamma(alpha,beta,gamma,x,h) sigma_33 <- sigma_gamma_gamma(alpha,beta,gamma,x,h) H_11 <- -0.5*sum( (sigma_11*sigma-sigma_1*sigma_1)/sigma^2-(sigma_11*sigma-2*sigma_1*sigma_1)/sigma^3*(x-mu)^2+ 2*sigma_1/sigma^2*(x-mu)*mu_1- 2*(mu_11*sigma-mu_1*sigma_1)*(x-mu)/sigma^2+2*mu_1*mu_1/sigma) H_22 <- -0.5*sum( (sigma_22*sigma-sigma_2*sigma_2)/sigma^2-(sigma_22*sigma-2*sigma_2*sigma_2)/sigma^3*(x-mu)^2+ 2*sigma_2/sigma^2*(x-mu)*mu_2- 2*(mu_22*sigma-mu_2*sigma_2)*(x-mu)/sigma^2+2*mu_2*mu_2/sigma) H_33 <- -0.5*sum( (sigma_33*sigma-sigma_3*sigma_3)/sigma^2-(sigma_33*sigma-2*sigma_3*sigma_3)/sigma^3*(x-mu)^2+ 2*sigma_3/sigma^2*(x-mu)*mu_3- 2*(mu_33*sigma-mu_3*sigma_3)*(x-mu)/sigma^2+2*mu_3*mu_3/sigma) H_12 <- -0.5*sum( (sigma_12*sigma-sigma_1*sigma_2)/sigma^2-(sigma_12*sigma-2*sigma_1*sigma_2)/sigma^2*(x-mu)^2+ 2*sigma_1/sigma^2*(x-mu)*mu_2- 2*(mu_12*sigma-mu_1*sigma_2)*(x-mu)/sigma^2+2*mu_1*mu_2/sigma) H_13 <- -0.5*sum( (sigma_13*sigma-sigma_1*sigma_3)/sigma^2-(sigma_13*sigma-2*sigma_1*sigma_3)/sigma^3*(x-mu)^2+ 2*sigma_1/sigma^2*(x-mu)*mu_3- 2*(mu_13*sigma-mu_1*sigma_3)*(x-mu)/sigma^2+2*mu_1*mu_3/sigma) H_23 <- -0.5*sum( (sigma_23*sigma-sigma_2*sigma_3)/sigma^2-(sigma_23*sigma-2*sigma_2*sigma_3)/sigma^3*(x-mu)^2+ 2*sigma_2/sigma^2*(x-mu)*mu_3- 2*(mu_23*sigma-mu_2*sigma_3)*(x-mu)/sigma^2+2*mu_2*mu_3/sigma) H_det <- H_11*H_22*H_33+H_12*H_23*H_13+H_13*H_12*H_23-H_13*H_22*H_13-H_11*H_23*H_23-H_12*H_12*H_33 return(matrix(1/H_det*c(H_22*H_33-H_23^2,H_13*H_23-H_12*H_33, H_12*H_23-H_13*H_22, H_13*H_23-H_12*H_33,H_11*H_33-H_13^2,H_13*H_12-H_11*H_23, H_12*H_23-H_13*H_22,H_13*H_12-H_11*H_23, H_11*H_22-H_12^2),nrow=3)) } #derivatives of the function H_n(theta) H_n_alpha <- function(alpha,beta,gamma,x,h){ x_minor <- head(x, -1) x_major <- x[-1] sigma_deriv <- sigma_alpha(alpha,beta,gamma,x_minor,h) sigma <- sigma_mod(alpha,beta,gamma,x_minor,h) ## HM 2022/6/21: sigma --> sigma_mod mu <- mu(alpha,beta,gamma,x_minor,h) mu_deriv <- mu_alpha(alpha,beta,gamma,x_minor,h) return (sum(-0.5*(sigma_deriv/sigma-sigma_deriv/sigma^2*(x_major-mu)^2-2/sigma*(x_major-mu)*mu_deriv))) } H_n_beta <- function(alpha,beta,gamma,x,h){ x_minor <- head(x, -1) x_major <- x[-1] sigma_deriv <- sigma_beta(alpha,beta,gamma,x_minor,h) sigma <- sigma_mod(alpha,beta,gamma,x_minor,h) ## HM 2022/6/21: sigma --> sigma_mod mu <- mu(alpha,beta,gamma,x_minor,h) mu_deriv <- mu_beta(alpha,beta,gamma,x_minor,h) return (sum(-0.5*(sigma_deriv/sigma-sigma_deriv/sigma^2*(x_major-mu)^2-2/sigma*(x_major-mu)*mu_deriv))) } H_n_gamma <- function(alpha,beta,gamma,x,h){ x_minor <- head(x, -1) x_major <- x[-1] sigma_deriv <- sigma_gamma(alpha,beta,gamma,x_minor,h) sigma <- sigma_mod(alpha,beta,gamma,x_minor,h) ## HM 2022/6/21: sigma --> sigma_mod mu <- mu(alpha,beta,gamma,x_minor,h) return (sum(-0.5*(sigma_deriv/sigma-sigma_deriv/sigma^2*(x_major-mu)^2))) } get_finalEstimators_scoring <- function(data) { prelim_estim <- get_preliminaryEstimators(data) #We need the preliminary estimator for the one step improvement alpha <- prelim_estim[1] beta <- prelim_estim[2] gamma <- prelim_estim[3] T <- tail(data[1,],1) #T is the time of the last observation n*h n<- length(data[1,])-1 #number of observations minus 1 x<-data[2,-1] h<-data[1,2] H_n<-c(H_n_alpha(alpha,beta,gamma,x,h),H_n_beta(alpha,beta,gamma,x,h),H_n_gamma(alpha,beta,gamma,x,h)) #calculate estimate from Eq. return(c(alpha,beta,gamma)+diag(c(1/T,1/T,1/n))%*% matrix(c(alpha*(2*alpha-gamma)/beta, 2*alpha-gamma,0,2*alpha-gamma,2*beta,0,0,0,2*gamma^2),nrow=3,byrow=TRUE)%*% H_n) } get_finalEstimators_newton <- function(data) { prelim_estim <- get_preliminaryEstimators(data) alpha <- prelim_estim[1] beta <- prelim_estim[2] gamma <- prelim_estim[3] T <- tail(data[1,],1) n<- length(data[1,])-1 x<-data[2,-1] h<-data[1,2] H_n<-c(H_n_alpha(alpha,beta,gamma,x,h),H_n_beta(alpha,beta,gamma,x,h),H_n_gamma(alpha,beta,gamma,x,h)) return(c(alpha,beta,gamma)-H_n_Hessian(alpha,beta,gamma,x,h)%*%H_n) } fitCIR<- function(data){ if( (max(diff(data[1,]))/ min(diff(data[1,])) -1) > 1e-10 ) stop('Please use equidistant sampling points') # fittedCIR.yuima <- setModel(drift="alpha - beta*x", diffusion="sqrt(gamma*x)", solve.variable=c("x")) return(list(get_preliminaryEstimators(data),get_finalEstimators_newton(data),get_finalEstimators_scoring(data) # ,fittedCIR.yuima )) } # ###Examples of usage # ##If the sampling points are not equidistant, there will be an corresponding output. # data <- sim.CIR(alpha=3,beta=1,gamma=1,time.points = c(0,0.1,0.2,0.25,0.3)) # fit.CIR(data) # ##Otherwise it calculate the three estimators # data <- sim.CIR(alpha=3,beta=1,gamma=1,n=1000,h=0.1,equi.dist=TRUE) # fit.CIR(data)
/scratch/gouwar.j/cran-all/cranData/yuima/R/fitCIR.R
hyavar <- function(yuima, bw, nonneg = TRUE, psd = TRUE){ x <- get.zoo.data(yuima) n.series <- length(x) # allocate memory ser.X <- vector(n.series, mode="list") # data in 'x' ser.times <- vector(n.series, mode="list") # time index in 'x' ser.diffX <- vector(n.series, mode="list") ser.num <- integer(n.series) # number of observations avar.cov <- diag(n.series) # asymptotic variances of cce(yuima)$covmat avar.cor <- diag(0, n.series) # asymptotic variances of cce(yuima)$cormat for(i in 1:n.series){ # NA data must be skipped idt <- which(is.na(x[[i]])) if(length(idt>0)){ x[[i]] <- x[[i]][-idt] } if(length(x[[i]])<2) { stop("length of data (w/o NA) must be more than 1") } # set data and time index ser.X[[i]] <- as.numeric(x[[i]]) # we need to transform data into numeric to avoid problem with duplicated indexes below ser.times[[i]] <- as.numeric(time(x[[i]])) ser.diffX[[i]] <- diff(ser.X[[i]]) # set number of observations ser.num[i] <- length(ser.X[[i]]) } # Computing the Hayashi-Yoshida estimator result <- cce(yuima, psd = psd) cmat <- result$covmat if(n.series > 1){ if(missing(bw)){ bw <- matrix(0, n.series, n.series) for(i in 1:(n.series - 1)){ for(j in (i + 1):n.series){ Init <- min(ser.times[[i]][1], ser.times[[j]][1]) Term <- max(ser.times[[i]][ser.num[i]], ser.times[[j]][ser.num[j]]) bw[i, j] <- (Term - Init) * min(ser.num[c(i,j)])^(-0.45) bw[j, i] <- bw[i, j] } } } } bw <- matrix(bw, n.series, n.series) for(i in 1:n.series){ avar.cov[i, i] <- (2/3) * sum(ser.diffX[[i]]^4) for(j in 1:i){ if(i > j){ N.max <- max(ser.num[i],ser.num[j]) avar <- .C("hyavar", as.double(ser.times[[i]]), as.double(ser.times[[j]]), as.integer(ser.num[i]), as.integer(ser.num[j]), as.double(ser.X[[i]]), as.double(ser.X[[j]]), as.integer(N.max), as.double(bw[i, j]), avar = double(4), PACKAGE = "yuima")$avar ## avar[1] = var(HYij), avar[2] = cov(HYii, HYij), avar[3] = cov(HYij, HYjj), avar[4] = cov(HYii, HYjj) avar.cov[i, j] <- avar[1] avar.cov[j, i] <- avar[1] Pi <- matrix(c(avar.cov[i,i], avar[2], avar[4], avar[2], avar[1], avar[3], avar[4], avar[3], avar.cov[j,j]), 3, 3) if(nonneg){ # Taking the spectral absolute value of Pi tmp <- eigen(Pi, symmetric = TRUE) Pi <- tmp$vectors %*% diag(abs(tmp$values)) %*% t(tmp$vectors) } d <- c(-0.5 * cmat[i,j]/cmat[i,i], 1, -0.5 * cmat[i,j]/cmat[j,j]) avar.cor[i, j] <- d %*% Pi %*% d / (cmat[i,i] * cmat[j,j]) avar.cor[j, i] <- avar.cor[i, j] } } } return(list(covmat = cmat, cormat = result$cormat, avar.cov = avar.cov, avar.cor = avar.cor)) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/hyavar.R
# auxiliar function for the evaluation of g(t,X_t,N_t, theta) internalGfunFromPPRModel <- function(gfun,my.envd3, univariate=TRUE){ if(univariate){ res<-as.numeric(eval(gfun, envir=my.envd3)) }else{res<-NULL} return(res) } # auxiliar function for the evaluation of Kernel InternalKernelFromPPRModel<-function(Integrand2,Integrand2expr,my.envd1=NULL,my.envd2=NULL, Univariate=TRUE, ExistdN, ExistdX, gridTime){ if(Univariate){ if(ExistdN){ dimCol<- dim(Integrand2)[2] NameCol<-colnames(Integrand2) assign(my.envd1$t.time,gridTime, envir=my.envd1) IntegralKernel<- 0 for(i in c(1:dimCol)){ cond <- NameCol[i] %in% my.envd1$NamesIntgra assign(my.envd1$var.time, time(my.envd1[[my.envd1$namedX[cond]]]), my.envd1) # since it is just univariate we don't need a cycle for IntegralKernelDum<- sum(eval(Integrand2expr[cond], envir=my.envd1)) IntegralKernel<-IntegralKernel+IntegralKernelDum # cat("\n", IntegralKernel) } } }else{ return(NULL) } return(IntegralKernel) } # auxiliar function for the evaluation of Intensity InternalConstractionIntensity<-function(param,my.envd1=NULL, my.envd2=NULL,my.envd3=NULL){ paramPPR <- my.envd3$YUIMA.PPR@PPR@allparamPPR namesparam <-my.envd3$namesparam gridTime <-my.envd3$gridTime Univariate <-my.envd3$Univariate ExistdN <-my.envd3$ExistdN ExistdX <-my.envd3$ExistdX gfun<-my.envd3$gfun Integrand2<-my.envd3$Integrand2 Integrand2expr<-my.envd3$Integrand2expr if(ExistdN){ for(i in c(1:length(paramPPR))){ cond<-namesparam %in% paramPPR[i] assign(paramPPR[i], param[cond], envir = my.envd1 ) } } if(ExistdX){ for(i in c(1:length(paramPPR))){ cond<-namesparam %in% paramPPR[i] assign(paramPPR[i], param[cond], envir = my.envd2) } } #param for(i in c(1:length(paramPPR))){ cond<-namesparam %in% paramPPR[i] assign(paramPPR[i], param[cond], envir = my.envd3) } KerneldN<- numeric(length=length(gridTime)) for(i in c(1:length(gridTime))){ KerneldN[i] <- InternalKernelFromPPRModel(Integrand2,Integrand2expr,my.envd1=my.envd1,my.envd2=my.envd2, Univariate=Univariate, ExistdN, ExistdX, gridTime=gridTime[i]) } # KerneldN <- sapply(X=as.numeric(gridTime),FUN = InternalKernelFromPPRModel, # Integrand2=Integrand2, Integrand2expr = Integrand2expr,my.envd1=my.envd1,my.envd2=my.envd2, # Univariate=Univariate, ExistdN =ExistdN, ExistdX=ExistdX ) KerneldCov<- numeric(length=length(gridTime)) Evalgfun <- internalGfunFromPPRModel(gfun,my.envd3, univariate=Univariate) result<-KerneldN+KerneldCov+Evalgfun } InternalConstractionIntensityFeedBackIntegrand<-function(param,my.envd1, my.envd2,my.envd3){ paramPPR <- my.envd3$YUIMA.PPR@PPR@allparamPPR namesparam <-my.envd3$namesparam gridTime <-my.envd3$gridTime Univariate <-my.envd3$Univariate ExistdN <-my.envd3$ExistdN ExistdX <-my.envd3$ExistdX gfun<-my.envd3$gfun allVarsInG<- all.vars(gfun) CondIntFeedBacksToG <- my.envd3$YUIMA.PPR@[email protected] %in% allVarsInG Integrand2<-my.envd3$Integrand2 Integrand2expr<-my.envd3$Integrand2expr if(ExistdN){ for(i in c(1:length(paramPPR))){ cond<-namesparam %in% paramPPR[i] assign(paramPPR[i], param[cond], envir = my.envd1 ) } } if(ExistdX){ for(i in c(1:length(paramPPR))){ cond<-namesparam %in% paramPPR[i] assign(paramPPR[i], param[cond], envir = my.envd2) } } #param for(i in c(1:length(paramPPR))){ cond<-namesparam %in% paramPPR[i] assign(paramPPR[i], param[cond], envir = my.envd3) } # for(i in c(1:length(gridTime))){ # KerneldN[i] <- InternalKernelFromPPRModel(Integrand2,Integrand2expr,my.envd1=my.envd1,my.envd2=my.envd2, # Univariate=Univariate, ExistdN, ExistdX, gridTime=gridTime[i]) # } if(Univariate){ NameCol <- colnames(Integrand2) # Kernel <- sapply(X=gridTime,FUN = InternalKernelFromPPRModel3, # Integrand2=Integrand2, Integrand2expr = Integrand2expr,my.envd1=my.envd1,my.envd2=my.envd2, # my.envd3=my.envd3, # Univariate=Univariate, ExistdN =ExistdN, ExistdX=ExistdX, # dimCol=dim(Integrand2)[2], NameCol = NameCol, # JumpTimeName =paste0("JumpTime.",NameCol)) # Kernel <- evalKernelCpp2(Integrand2, # Integrand2expr, # my.envd1, my.envd2, my.envd3$YUIMA.PPR@PPR@IntensWithCount, # my.envd3$YUIMA.PPR@[email protected], # my.envd3$YUIMA.PPR@PPR@covariates, # ExistdN, ExistdX, # gridTime, dimCol = dim(Integrand2)[2], NameCol = NameCol, # JumpTimeName =paste0("JumpTime.",NameCol)) # Evalgfun <- internalGfunFromPPRModel(gfun[i],my.envd3, univariate=TRUE) # result<-Kernel+Evalgfun kernel <- numeric(length = length(gridTime)) Intensity <- numeric(length = length(gridTime)) JumpTimeName <- paste0("JumpTime.", NameCol) dimCol <- dim(Integrand2)[2] IntensityatJumpTime<-as.list(numeric(length=length(gridTime))) differentialCounting <- paste0("d", c(my.envd3$YUIMA.PPR@[email protected], my.envd3$YUIMA.PPR@[email protected])) if(!CondIntFeedBacksToG){ EvalGFUN <- eval(gfun,envir=my.envd3) Intensity[1]<-EvalGFUN[1] } aaaa<- length(gridTime) CondallJump <- rep(FALSE,aaaa+1) for(t in c(2:aaaa)){ assign(my.envd1$t.time,gridTime[[t]][1],envir=my.envd1) for(j in c(1:dimCol)){ if(NameCol[j] %in% differentialCounting){ # Intensity at Jump Time assign(my.envd3$YUIMA.PPR@[email protected], IntensityatJumpTime[[t-1]], envir=my.envd1) # Counting Var at Jump Time assign(my.envd3$YUIMA.PPR@[email protected], my.envd1[[my.envd1$PosListCountingVariable]][[t]], envir=my.envd1) # Jump time <= t assign(my.envd1$var.time,my.envd1[[JumpTimeName[j]]][[t]],envir=my.envd1) KerneldN <- sum(eval(Integrand2expr,envir=my.envd1)*my.envd1[[my.envd1$namedX[j]]][[t]]) kernel[t-1] <- KerneldN } } # Evaluation gFun if(!CondIntFeedBacksToG){ #EvalGFUN <- eval(gfun,envir=my.envd3) if(t<=aaaa){ Intensity[t]<- EvalGFUN[t-1]+kernel[t-1] } }else{ # Here we evaluate gFun time by time } for(j in c(1:dimCol)){ if(t+1<=aaaa){ if(NameCol[j] %in% differentialCounting){ # CondallJump[t] <-my.envd3$JumpTimeLogical[t] IntensityatJumpTime[[t]]<- Intensity[CondallJump[-1]] } } } if(t==77){ ff<-2 } } }else{ n.row <- length(my.envd3$YUIMA.PPR@[email protected]) n.col <- length(gridTime) result <- matrix(NA,n.row, n.col) #Kernel<- numeric(length=n.col-1) dimCol<- dim(Integrand2)[2] NameCol<-colnames(Integrand2) JumpTimeName <- paste0("JumpTime.",NameCol) for(i in c(1:n.row)){ # Kernel <- sapply(X=gridTime,FUN = InternalKernelFromPPRModel2, # Integrand2=t(Integrand2[i,]), Integrand2expr = Integrand2expr[[i]],my.envd1=my.envd1,my.envd2=my.envd2, # Univariate=TRUE, ExistdN =ExistdN, ExistdX=ExistdX, dimCol=dimCol, NameCol = NameCol, # JumpTimeName =JumpTimeName) # Kernel <- evalKernelCpp2(t(Integrand2[i,]), Integrand2expr[[i]], # my.envd1, my.envd2, my.envd3$YUIMA.PPR@PPR@IntensWithCount, # my.envd3$YUIMA.PPR@[email protected], # my.envd3$YUIMA.PPR@PPR@covariates, # ExistdN, ExistdX, # gridTime, dimCol = dim(Integrand2)[2], NameCol = NameCol, # JumpTimeName =paste0("JumpTime.",NameCol)) # Evalgfun <- internalGfunFromPPRModel(gfun[i],my.envd3, univariate=TRUE) # result[i,]<-Kernel+Evalgfun } } return(Intensity) } InternalKernelFromPPRModel2<-function(Integrand2,Integrand2expr,my.envd1=NULL,my.envd2=NULL, Univariate=TRUE, ExistdN, ExistdX, gridTime, dimCol, NameCol, JumpTimeName){ if(Univariate){ # JumpTimeName <- paste0("JumpTime.",NameCol[i]) # dimCol<- dim(Integrand2)[2] # NameCol<-colnames(Integrand2) if(ExistdN){ assign(my.envd1$t.time,gridTime, envir=my.envd1) } if(ExistdX){ assign(my.envd2$t.time,gridTime, envir=my.envd2) } IntegralKernel<- 0 for(i in c(1:dimCol)){ # cond <- NameCol[i] %in% my.envd1$NamesIntgra # assign(my.envd1$var.time, time(my.envd1[[my.envd1$namedX[cond]]]), my.envd1) # since it is just univariate we don't need a cycle for if(ExistdN){ # cond <- paste0("JumpTime.",NameCol[i]) %in% my.envd1$namedJumpTimeX # cond <- my.envd1$namedJumpTimeX %in% paste0("JumpTime.",NameCol[i]) cond <- my.envd1$namedJumpTimeX %in% JumpTimeName[i] if(any(cond)){ assign(my.envd1$var.time,my.envd1[[my.envd1$namedJumpTimeX[cond]]],envir=my.envd1) # condpos <- NameCol %in% my.envd1$namedX condpos <- my.envd1$namedX %in% NameCol[i] if(any(condpos)){ IntegralKernelDum<- sum(eval(Integrand2expr[condpos], envir=my.envd1),na.rm=TRUE) IntegralKernel<-IntegralKernel+IntegralKernelDum } } } if(ExistdX){ # cond <- paste0("JumpTime.",NameCol[i]) %in% my.envd2$namedJumpTimeX # cond <- my.envd2$namedJumpTimeX %in% paste0("JumpTime.",NameCol[i]) cond <- my.envd2$namedJumpTimeX %in% JumpTimeName[i] if(any(cond)){ assign(my.envd2$var.time,my.envd2[[my.envd2$namedJumpTimeX[cond]]],envir=my.envd2) # condpos <- NameCol %in% my.envd2$namedX condpos <- my.envd2$namedX %in% NameCol[i] if(any(condpos)){ IntegralKernelDum<- sum(eval(Integrand2expr[condpos], envir=my.envd2)) IntegralKernel<-IntegralKernel+IntegralKernelDum } } } } }else{ return(NULL) } return(IntegralKernel) } InternalKernelFromPPRModel3<-function(Integrand2,Integrand2expr,my.envd1=NULL,my.envd2=NULL,my.envd3=NULL, Univariate=TRUE, ExistdN, ExistdX, gridTime, dimCol, NameCol, JumpTimeName){ if(Univariate){ # JumpTimeName <- paste0("JumpTime.",NameCol[i]) # dimCol<- dim(Integrand2)[2] # NameCol<-colnames(Integrand2) if(ExistdN){ #assign(my.envd1$t.time,gridTime[1], envir=my.envd1) my.envd1[[my.envd1$t.time]]<-gridTime[1] } if(ExistdX){ assign(my.envd2$t.time,gridTime[1], envir=my.envd2) } if(my.envd3$YUIMA.PPR@PPR@IntensWithCount){ for(i in c(1:length(my.envd3$YUIMA.PPR@[email protected]))){ # assign(my.envd3$YUIMA.PPR@[email protected][i], # my.envd1[[my.envd1$PosListCountingVariable[i]]][[gridTime[2]]] # ,envir = my.envd1) my.envd1[[my.envd3$YUIMA.PPR@[email protected][i]]]<-my.envd1[[my.envd1$PosListCountingVariable[i]]][[gridTime[2]]] } if(length(my.envd3$YUIMA.PPR@PPR@covariates)>0){ for(i in c(1:length(my.envd3$YUIMA.PPR@PPR@covariates))){ # assign(my.envd3$YUIMA.PPR@PPR@covariates[i], # my.envd1[[my.envd1$PosListCovariates[i]]][[gridTime[2]]] # ,envir = my.envd1) my.envd1[[my.envd3$YUIMA.PPR@PPR@covariates[i]]]<-my.envd1[[my.envd1$PosListCovariates[i]]][[gridTime[2]]] } } } IntegralKernel<- 0 for(i in c(1:dimCol)){ # cond <- NameCol[i] %in% my.envd1$NamesIntgra # assign(my.envd1$var.time, time(my.envd1[[my.envd1$namedX[cond]]]), my.envd1) # since it is just univariate we don't need a cycle for if(ExistdN){ # cond <- paste0("JumpTime.",NameCol[i]) %in% my.envd1$namedJumpTimeX # cond <- my.envd1$namedJumpTimeX %in% paste0("JumpTime.",NameCol[i]) cond <- my.envd1$namedJumpTimeX %in% JumpTimeName[i] if(any(cond)){ assign(my.envd1$var.time,my.envd1[[my.envd1$namedJumpTimeX[cond]]][[gridTime[2]]],envir=my.envd1) # condpos <- NameCol %in% my.envd1$namedX #condpos <- my.envd1$namedX %in% NameCol[i] condpos <- NameCol %in% NameCol[i] if(any(condpos)){ InterDum <- eval(Integrand2expr[condpos], envir=my.envd1)*my.envd1[[NameCol[i]]][[gridTime[2]]] IntegralKernelDum<- sum(InterDum,na.rm=TRUE) IntegralKernel<-IntegralKernel+IntegralKernelDum } } } if(ExistdX){ # cond <- paste0("JumpTime.",NameCol[i]) %in% my.envd2$namedJumpTimeX # cond <- my.envd2$namedJumpTimeX %in% paste0("JumpTime.",NameCol[i]) cond <- my.envd2$namedJumpTimeX %in% JumpTimeName[i] if(any(cond)){ #assign(my.envd2$var.time,my.envd2[[my.envd2$namedJumpTimeX[cond]]],envir=my.envd2) assign(my.envd2$var.time,my.envd2[[my.envd2$namedJumpTimeX[cond]]][1:gridTime[2]],envir=my.envd2) # condpos <- my.envd2$namedX %in% NameCol condpos <- NameCol %in% NameCol[i] if(any(condpos)){ IntegralKernelDum<- sum(eval(Integrand2expr[condpos], envir=my.envd2)*my.envd2[[NameCol[i]]][1:gridTime[2]] , na.rm=TRUE) IntegralKernel<-IntegralKernel+IntegralKernelDum } } } } }else{ return(NULL) } return(IntegralKernel) } InternalConstractionIntensity2<-function(param,my.envd1=NULL, my.envd2=NULL,my.envd3=NULL){ paramPPR <- my.envd3$YUIMA.PPR@PPR@allparamPPR namesparam <-my.envd3$namesparam gridTime <-my.envd3$gridTime Univariate <-my.envd3$Univariate ExistdN <-my.envd3$ExistdN ExistdX <-my.envd3$ExistdX gfun<-my.envd3$gfun Integrand2<-my.envd3$Integrand2 Integrand2expr<-my.envd3$Integrand2expr if(ExistdN){ for(i in c(1:length(paramPPR))){ cond<-namesparam %in% paramPPR[i] assign(paramPPR[i], param[cond], envir = my.envd1 ) } } if(ExistdX){ for(i in c(1:length(paramPPR))){ cond<-namesparam %in% paramPPR[i] assign(paramPPR[i], param[cond], envir = my.envd2) } } #param for(i in c(1:length(paramPPR))){ cond<-namesparam %in% paramPPR[i] assign(paramPPR[i], param[cond], envir = my.envd3) } # for(i in c(1:length(gridTime))){ # KerneldN[i] <- InternalKernelFromPPRModel(Integrand2,Integrand2expr,my.envd1=my.envd1,my.envd2=my.envd2, # Univariate=Univariate, ExistdN, ExistdX, gridTime=gridTime[i]) # } if(Univariate){ # Kernel<- numeric(length=length(gridTime)) NameCol <- colnames(Integrand2) # Kernel <- sapply(X=gridTime,FUN = InternalKernelFromPPRModel2, # Integrand2=Integrand2, Integrand2expr = Integrand2expr,my.envd1=my.envd1,my.envd2=my.envd2, # Univariate=Univariate, ExistdN =ExistdN, ExistdX=ExistdX, # dimCol=dim(Integrand2)[2], NameCol = NameCol, # JumpTimeName =paste0("JumpTime.",NameCol)) # NameCol <- colnames(Integrand2) # Kernel <- evalKernelCpp(Integrand2, Integrand2expr,my.envd1, my.envd2, # ExistdN, ExistdX, gridTime, dim(Integrand2)[2], NameCol, # paste0("JumpTime.",NameCol)) # Kernel <- sapply(X=gridTime,FUN = InternalKernelFromPPRModel3, # Integrand2=Integrand2, Integrand2expr = Integrand2expr,my.envd1=my.envd1,my.envd2=my.envd2, # my.envd3=my.envd3, # Univariate=Univariate, ExistdN =ExistdN, ExistdX=ExistdX, # dimCol=dim(Integrand2)[2], NameCol = NameCol, # JumpTimeName =paste0("JumpTime.",NameCol)) Kernel <- evalKernelCpp2(Integrand2, Integrand2expr, my.envd1, my.envd2, my.envd3$YUIMA.PPR@PPR@IntensWithCount, my.envd3$YUIMA.PPR@[email protected], my.envd3$YUIMA.PPR@PPR@covariates, ExistdN, ExistdX, gridTime, dimCol = dim(Integrand2)[2], NameCol = NameCol, JumpTimeName =paste0("JumpTime.",NameCol)) #KerneldCov<- numeric(length=length(gridTime)) Evalgfun <- internalGfunFromPPRModel(gfun,my.envd3, univariate=Univariate) result<-Kernel+Evalgfun }else{ n.row <- length(my.envd3$YUIMA.PPR@[email protected]) n.col <- length(gridTime) result <- matrix(NA,n.row, n.col) #Kernel<- numeric(length=n.col-1) dimCol<- dim(Integrand2)[2] NameCol<-colnames(Integrand2) JumpTimeName <- paste0("JumpTime.",NameCol) for(i in c(1:n.row)){ # Kernel <- pvec(v=gridTime,FUN = InternalKernelFromPPRModel2, # Integrand2=t(Integrand2[i,]), Integrand2expr = Integrand2expr[[i]],my.envd1=my.envd1,my.envd2=my.envd2, # Univariate=TRUE, ExistdN =ExistdN, ExistdX=ExistdX, dimCol=dimCol, NameCol = NameCol, # JumpTimeName =JumpTimeName) # Kernel <- sapply(X=gridTime,FUN = InternalKernelFromPPRModel2, # Integrand2=t(Integrand2[i,]), Integrand2expr = Integrand2expr[[i]],my.envd1=my.envd1,my.envd2=my.envd2, # Univariate=TRUE, ExistdN =ExistdN, ExistdX=ExistdX, dimCol=dimCol, NameCol = NameCol, # JumpTimeName =JumpTimeName) # Kernel <- sapply(X=gridTime,FUN = evalKernelCppPvec, # Integrand2=t(Integrand2[i,]), Integrand2expr = Integrand2expr[[i]], # myenvd1=my.envd1,myenvd2=my.envd2, # ExistdN =ExistdN, ExistdX=ExistdX, # dimCol=dimCol, NameCol = NameCol, # JumpTimeName =JumpTimeName) # Kernel <- evalKernelCpp(t(Integrand2[i,]), Integrand2expr[[i]],my.envd1, my.envd2, # ExistdN, ExistdX, gridTime, dimCol, NameCol, # JumpTimeName) Kernel <- evalKernelCpp2(t(Integrand2[i,]), Integrand2expr[[i]], my.envd1, my.envd2, my.envd3$YUIMA.PPR@PPR@IntensWithCount, my.envd3$YUIMA.PPR@[email protected], my.envd3$YUIMA.PPR@PPR@covariates, ExistdN, ExistdX, gridTime, dimCol = dim(Integrand2)[2], NameCol = NameCol, JumpTimeName =paste0("JumpTime.",NameCol)) Evalgfun <- internalGfunFromPPRModel(gfun[i],my.envd3, univariate=TRUE) result[i,]<-Kernel+Evalgfun } } return(result) } Intensity.PPR <- function(yuimaPPR,param){ # I need three envirnment # 1. my.envd1 is used when the counting variable is integrator # 2. my.envd2 is used when covariates or time are integrator # 3. my.envd3 for gfun gfun<-yuimaPPR@gFun@formula dimIntegr <- length(yuimaPPR@Kernel@Integrand@IntegrandList) Integrand2 <- character(length=dimIntegr) for(i in c(1:dimIntegr)){ #Integrand1 <- as.character(yuimaPPR@Kernel@Integrand@IntegrandList[[i]]) #timeCond <- paste0(" * (",yuimaPPR@[email protected]@var.time," < ",yuimaPPR@[email protected]@upper.var,")") #Integrand2[i] <-paste0(Integrand1,timeCond) Integrand2[i] <- as.character(yuimaPPR@Kernel@Integrand@IntegrandList[[i]]) } Integrand2<- matrix(Integrand2,yuimaPPR@Kernel@Integrand@dimIntegrand[1],yuimaPPR@Kernel@Integrand@dimIntegrand[2]) # for(j in c(1:yuimaPPR@Kernel@Integrand@dimIntegrand[2])){ # Integrand2[,j]<-paste0(Integrand2[,j]," * d",yuimaPPR@[email protected]@var.dx[j]) # } colnames(Integrand2) <- paste0("d",yuimaPPR@[email protected]@var.dx) NamesIntegrandExpr <- as.character(matrix(colnames(Integrand2), dim(Integrand2)[1],dim(Integrand2)[2], byrow = TRUE)) # if(yuimaPPR@Kernel@Integrand@dimIntegrand[2]==1 & yuimaPPR@Kernel@Integrand@dimIntegrand[1]==1) # Integrand2expr<- parse(text=Integrand2) # # if(yuimaPPR@Kernel@Integrand@dimIntegrand[2]>1 & yuimaPPR@Kernel@Integrand@dimIntegrand[1]==1){ # dum <- paste0(Integrand2,collapse=" + ") # Integrand2expr <- parse(text=dum) # } if(yuimaPPR@Kernel@Integrand@dimIntegrand[1]==1){ Integrand2expr <- parse(text=Integrand2) }else{ Integrand2expr <- list() for(hh in c(1:yuimaPPR@Kernel@Integrand@dimIntegrand[1])){ Integrand2expr[[hh]] <- parse(text=Integrand2[hh,]) } } gridTime <- time(yuimaPPR@[email protected]) yuimaPPR@[email protected]@var.dx if(any(yuimaPPR@[email protected]@var.dx %in% yuimaPPR@[email protected])){ my.envd1<-new.env() ExistdN<-TRUE }else{ ExistdN<-FALSE } Univariate<-FALSE if(length(yuimaPPR@[email protected])==1){ Univariate<-TRUE } if(any(yuimaPPR@[email protected]@var.dx %in% yuimaPPR@PPR@covariates)){ my.envd2<-new.env() ExistdX<-TRUE }else{ my.envd2<-new.env() ExistdX<-FALSE } my.envd3 <- new.env() namesparam<-names(param) if(!(all(namesparam %in% yuimaPPR@PPR@allparamPPR) && length(namesparam)==length(yuimaPPR@PPR@allparamPPR))){ return(NULL) } # construction my.envd1 if(ExistdN){ #CountingVariable # for(i in c(1:length(yuimaPPR@[email protected]))){ # cond <- yuimaPPR@[email protected] %in% yuimaPPR@[email protected][i] # condTime <- gridTime %in% my.envd1$JumpTime.dN # dummyData <- yuimaPPR@[email protected][condTime,cond] # assign(yuimaPPR@[email protected][i], as.numeric(dummyData),envir=my.envd1) # } # Names expression assign("NamesIntgra", NamesIntegrandExpr, envir=my.envd1) #dN namedX <-NULL namedJumpTimeX <- NULL for(i in c(1:length(yuimaPPR@[email protected]@var.dx))){ if(yuimaPPR@[email protected]@var.dx[i] %in% yuimaPPR@[email protected]){ cond <- yuimaPPR@[email protected] %in% yuimaPPR@[email protected]@var.dx[i] namedX<-c(namedX,paste0("d",yuimaPPR@[email protected]@var.dx[i])) namedJumpTimeX <-c(namedJumpTimeX,paste0("JumpTime.d",yuimaPPR@[email protected]@var.dx[i])) dummyData <- diff(as.numeric(yuimaPPR@[email protected][,cond]))# We consider only Jump #dummyJumpTime <- gridTime[-1][dummyData>0] dummyJumpTime <- gridTime[-1][dummyData!=0] dummyData2 <- diff(unique(cumsum(dummyData))) #dummyData3 <- zoo(dummyData2,order.by = dummyJumpTime) dummyData3 <- dummyData2 JumpTime <- dummyJumpTime Jump <- lapply(X=as.numeric(gridTime), FUN = function(X,JumpT,Jump){Jump[JumpT<X]}, JumpT = dummyJumpTime, Jump = as.numeric(dummyData3!=0)) assign(paste0("d",yuimaPPR@[email protected]@var.dx[i]), Jump , envir=my.envd1) dummyJumpTimeNew <- lapply(X=as.numeric(gridTime), FUN = function(X,JumpT){JumpT[JumpT<X]}, JumpT = dummyJumpTime) assign(paste0("JumpTime.d",yuimaPPR@[email protected]@var.dx[i]), dummyJumpTimeNew ,envir=my.envd1) } } assign("namedX",namedX, envir = my.envd1) assign("namedJumpTimeX",namedJumpTimeX, envir = my.envd1) assign("var.time",yuimaPPR@[email protected]@var.time,envir=my.envd1) assign("t.time",yuimaPPR@[email protected]@upper.var,envir=my.envd1) #CountingVariable PosListCountingVariable <- NULL for(i in c(1:length(yuimaPPR@[email protected]))){ cond <- yuimaPPR@[email protected] %in% yuimaPPR@[email protected][i] JUMPTIME <- tail(my.envd1[[paste0("JumpTime.d",yuimaPPR@[email protected]@var.dx[i])]],1L)[[1]] condTime <- gridTime %in% JUMPTIME dummyData <- yuimaPPR@[email protected][condTime,cond] dummyDataA <- lapply(X=as.numeric(gridTime), FUN = function(X,JumpT,Jump){Jump[JumpT<X]}, JumpT = JUMPTIME, Jump = dummyData) dummyList <- paste0("List_",yuimaPPR@[email protected][i]) PosListCountingVariable <- c(PosListCountingVariable,dummyList) assign(dummyList, dummyDataA, envir=my.envd1) assign(yuimaPPR@[email protected][i], numeric(length=0L), envir=my.envd1) } assign("PosListCountingVariable", PosListCountingVariable, envir=my.envd1) # Covariates if(length(yuimaPPR@PPR@covariates)>0){ # Covariates should be identified at jump time # return(NULL) PosListCovariates <- NULL for(i in c(1:length(yuimaPPR@PPR@covariates))){ cond <- yuimaPPR@[email protected] %in% yuimaPPR@PPR@covariates[i] #dummyData <-yuimaPPR@[email protected][,cond] dummyData <- yuimaPPR@[email protected][condTime, cond] dummyDataB <- lapply(X=as.numeric(gridTime), FUN = function(X,JumpT,Jump){Jump[JumpT<X]}, JumpT = JUMPTIME, Jump = dummyData) dummyListCov <- paste0("List_",yuimaPPR@PPR@covariates[i]) PosListCovariates <- c(PosListCovariates,dummyListCov) assign(dummyListCov, dummyDataB,envir=my.envd1) assign(yuimaPPR@PPR@covariates[i], numeric(length=0L),envir=my.envd1) } assign("PosListCovariates", PosListCovariates,envir=my.envd1) } } # end coonstruction my.envd1 # construction my.envd2 if(ExistdX){ #Covariate dummyData<-NULL #CountingVariable for(i in c(1:length(yuimaPPR@[email protected]))){ cond <- yuimaPPR@[email protected] %in% yuimaPPR@[email protected][i] dummyData <-as.numeric(yuimaPPR@[email protected][,cond]) # assign(yuimaPPR@[email protected][i], dummyData[-length(dummyData)],envir=my.envd2) assign(yuimaPPR@[email protected][i], dummyData,envir=my.envd2) } namedX<-NULL namedJumpTimeX<-NULL for(i in c(1:length(yuimaPPR@[email protected]@var.dx))){ if(yuimaPPR@[email protected]@var.dx[i] %in% yuimaPPR@PPR@covariates){ cond <- yuimaPPR@[email protected] %in% yuimaPPR@[email protected]@var.dx[i] namedX<-c(namedX,paste0("d",yuimaPPR@[email protected]@var.dx[i])) namedJumpTimeX <-c(namedJumpTimeX,paste0("JumpTime.d",yuimaPPR@[email protected]@var.dx[i])) dummyData <- diff(as.numeric(yuimaPPR@[email protected][,cond]))# We consider only Jump #dummyJumpTime <- gridTime[-1][dummyData>0] #assign(paste0("d",yuimaPPR@[email protected]@var.dx[i]), dummyData ,envir=my.envd2) assign(paste0("d",yuimaPPR@[email protected]@var.dx[i]), c(0,dummyData) ,envir=my.envd2) #assign(paste0("JumpTime.d",yuimaPPR@[email protected]@var.dx[i]), gridTime[-1] ,envir=my.envd2) assign(paste0("JumpTime.d",yuimaPPR@[email protected]@var.dx[i]), as.numeric(gridTime) ,envir=my.envd2) } } assign("namedX",namedX, envir = my.envd2) assign("namedJumpTimeX",namedJumpTimeX, envir = my.envd2) assign("var.time",yuimaPPR@[email protected]@var.time,envir=my.envd2) assign("t.time",yuimaPPR@[email protected]@upper.var,envir=my.envd2) for(i in c(1:length(yuimaPPR@PPR@covariates))){ cond <- yuimaPPR@[email protected] %in% yuimaPPR@PPR@covariates[i] #dummyData <-yuimaPPR@[email protected][,cond] dummyData <-as.numeric(yuimaPPR@[email protected][, cond]) #assign(yuimaPPR@PPR@covariates[i], dummyData[-length(dummyData)],envir=my.envd2) assign(yuimaPPR@PPR@covariates[i], dummyData,envir=my.envd2) } }else{ assign("KerneldX",NULL,envir=my.envd2) } # end construction my.envd2 # construction my.envd3 #Covariate dimCov <- length(yuimaPPR@PPR@covariates) if(dimCov>0){ for(j in c(1:dimCov)){ cond <- yuimaPPR@[email protected] %in% yuimaPPR@PPR@covariates[j] dummyData <-yuimaPPR@[email protected][,cond] assign(yuimaPPR@PPR@covariates[j], dummyData,envir=my.envd3) } } #CountingVariable for(i in c(1:length(yuimaPPR@[email protected]))){ cond <- yuimaPPR@[email protected] %in% yuimaPPR@[email protected][i] dummyData <-yuimaPPR@[email protected][,cond] assign(yuimaPPR@[email protected][i], dummyData,envir=my.envd3) } #time assign(yuimaPPR@[email protected], gridTime, my.envd3) #Model assign("YUIMA.PPR",yuimaPPR,envir=my.envd3) assign("namesparam",namesparam,envir=my.envd3) assign("gfun",gfun,envir=my.envd3) assign("Integrand2",Integrand2,envir=my.envd3) assign("Integrand2expr",Integrand2expr,envir=my.envd3) l1 =as.list(as.numeric(gridTime)) l2 = as.list(c(1:(length(l1)))) l3 = mapply(c, l1, l2, SIMPLIFY=FALSE) assign("gridTime",l3,envir=my.envd3) assign("Univariate",Univariate,envir=my.envd3) assign("ExistdN",ExistdN,envir=my.envd3) assign("ExistdX",ExistdX,envir=my.envd3) assign("JumpTimeLogical",c(FALSE,as.integer(diff(my.envd3$N))!=0),envir=my.envd3) # end construction my.envd3 ################################ # Start Intensity construction # ################################ #We define the parameters value for each environment param<-unlist(param) # if(my.envd3$YUIMA.PPR@[email protected] %in% all.vars(my.envd3$Integrand2expr)){ # result <- InternalConstractionIntensityFeedBackIntegrand(param,my.envd1, # my.envd2,my.envd3) # }else{ # result<-InternalConstractionIntensity2(param,my.envd1, # my.envd2,my.envd3) # } myvardummy <- NULL for(i in c(1:length(my.envd3$Integrand2expr))){ myvardummy <- c(myvardummy, all.vars(my.envd3$Integrand2expr[[i]])) } myvardummy<-unique(myvardummy) if(any(my.envd3$YUIMA.PPR@[email protected] %in% myvardummy)){ result <- InternalConstractionIntensityFeedBackIntegrand(param,my.envd1, my.envd2,my.envd3) }else{ result<-InternalConstractionIntensity2(param,my.envd1, my.envd2,my.envd3) } #if(class(result)=="matrix"){ if(inherits(result, "matrix")){ # YK, Mar. 22, 2022 my.matr <- t(result) colnames(my.matr) <-paste0("lambda",c(1:yuimaPPR@Kernel@Integrand@dimIntegrand[1])) Int2<-zoo(my.matr,order.by = gridTime) }else{ Int2<-zoo(as.matrix(result),order.by = gridTime) colnames(Int2)<-"lambda" } res<-setData(Int2) return(res) } # Intensity.PPR <- function(yuimaPPR,param){ # # I need three envirnment # # 1. my.envd1 is used when the counting variable is integrator # # 2. my.envd2 is used when covariates or time are integrator # # 3. my.envd3 for gfun # # gfun<-yuimaPPR@gFun@formula # # dimIntegr <- length(yuimaPPR@Kernel@Integrand@IntegrandList) # Integrand2 <- character(length=dimIntegr) # for(i in c(1:dimIntegr)){ # Integrand1 <- as.character(yuimaPPR@Kernel@Integrand@IntegrandList[[i]]) # timeCond <- paste0(" * (",yuimaPPR@[email protected]@var.time," < ",yuimaPPR@[email protected]@upper.var,")") # Integrand2[i] <-paste0(Integrand1,timeCond) # } # # Integrand2<- matrix(Integrand2,yuimaPPR@Kernel@Integrand@dimIntegrand[1],yuimaPPR@Kernel@Integrand@dimIntegrand[2]) # # # for(j in c(1:yuimaPPR@Kernel@Integrand@dimIntegrand[2])){ # Integrand2[,j]<-paste0(Integrand2[,j]," * d",yuimaPPR@[email protected]@var.dx[j]) # } # colnames(Integrand2) <- paste0("d",yuimaPPR@[email protected]@var.dx) # NamesIntegrandExpr <- as.character(matrix(colnames(Integrand2), dim(Integrand2)[1],dim(Integrand2)[2], byrow = TRUE)) # Integrand2expr<- parse(text=Integrand2) # # gridTime <- time(yuimaPPR@[email protected]) # # yuimaPPR@[email protected]@var.dx # if(any(yuimaPPR@[email protected]@var.dx %in% yuimaPPR@[email protected])){ # my.envd1<-new.env() # ExistdN<-TRUE # }else{ # ExistdN<-FALSE # } # Univariate<-FALSE # if(length(yuimaPPR@[email protected])==1){ # Univariate<-TRUE # } # if(any(!(yuimaPPR@[email protected]@var.dx %in% yuimaPPR@[email protected]))){ # my.envd2<-new.env() # ExistdX<-TRUE # }else{ # my.envd2<-new.env() # ExistdX<-FALSE # } # # my.envd3 <- new.env() # namesparam<-names(param) # if(!(all(namesparam %in% yuimaPPR@PPR@allparamPPR) && length(namesparam)==length(yuimaPPR@PPR@allparamPPR))){ # return(NULL) # } # # # construction my.envd1 # if(ExistdN){ # # #CountingVariable # for(i in c(1:length(yuimaPPR@[email protected]))){ # cond <- yuimaPPR@[email protected][i] %in% yuimaPPR@[email protected] # dummyData <-unique(yuimaPPR@[email protected][,cond])[-1] # assign(yuimaPPR@[email protected][i], dummyData,envir=my.envd1) # } # # Names expression # assign("NamesIntgra", NamesIntegrandExpr, envir=my.envd1) # #dN # namedX <-NULL # for(i in c(1:length(yuimaPPR@[email protected]@var.dx))){ # if(yuimaPPR@[email protected]@var.dx[i] %in% yuimaPPR@[email protected]){ # cond <- yuimaPPR@[email protected] %in% yuimaPPR@[email protected]@var.dx[i] # namedX<-c(namedX,paste0("d",yuimaPPR@[email protected]@var.dx[i])) # dummyData <- diff(as.numeric(yuimaPPR@[email protected][,cond]))# We consider only Jump # dummyJumpTime <- gridTime[-1][dummyData>0] # dummyData2 <- diff(unique(cumsum(dummyData))) # dummyData3 <- zoo(dummyData2,order.by = dummyJumpTime) # assign(paste0("d",yuimaPPR@[email protected]@var.dx[i]), dummyData3 ,envir=my.envd1) # } # } # assign("namedX",namedX, envir = my.envd1) # assign("var.time",yuimaPPR@[email protected]@var.time,envir=my.envd1) # assign("t.time",yuimaPPR@[email protected]@upper.var,envir=my.envd1) # # # Covariates # if(length(yuimaPPR@PPR@covariates)>1){ # # Covariates should be identified at jump time # return(NULL) # } # # } # # end coonstruction my.envd1 # # # construction my.envd2 # if(ExistdX){ # #Covariate # # #CountingVariable # for(i in c(1:length(yuimaPPR@[email protected]))){ # cond <- yuimaPPR@[email protected][i] %in% yuimaPPR@[email protected] # dummyData <-yuimaPPR@[email protected][,cond] # assign(yuimaPPR@[email protected][i], dummyData,envir=my.envd1) # } # # # }else{ # assign("KerneldX",NULL,envir=my.envd2) # } # # # end construction my.envd2 # # # construction my.envd3 # # #Covariate # # #CountingVariable # for(i in c(1:length(yuimaPPR@[email protected]))){ # cond <- yuimaPPR@[email protected][i] %in% yuimaPPR@[email protected] # dummyData <-yuimaPPR@[email protected][,cond] # assign(yuimaPPR@[email protected][i], dummyData,envir=my.envd3) # } # #time # assign(yuimaPPR@[email protected], gridTime, my.envd3) # # #Model # assign("YUIMA.PPR",yuimaPPR,envir=my.envd3) # assign("namesparam",namesparam,envir=my.envd3) # assign("gfun",gfun,envir=my.envd3) # assign("Integrand2",Integrand2,envir=my.envd3) # assign("Integrand2expr",Integrand2expr,envir=my.envd3) # # assign("gridTime",gridTime,envir=my.envd3) # assign("Univariate",Univariate,envir=my.envd3) # assign("ExistdN",ExistdN,envir=my.envd3) # assign("ExistdX",ExistdX,envir=my.envd3) # # # # end construction my.envd3 # # # # # # ################################ # # Start Intensity construction # # ################################ # #We define the parameters value for each environment # # param<-unlist(param) # # result<-InternalConstractionIntensity(param,my.envd1, # my.envd2,my.envd3) # # Int2<-zoo(as.matrix(result),order.by = gridTime) # colnames(Int2)<-"lambda" # res<-setData(Int2) # return(res) # # # }
/scratch/gouwar.j/cran-all/cranData/yuima/R/lambdaPPR.R
# Initial version of lasso estimation for SDEs # fixes a small bug in passing arguments to the # inner optim function lasso <- function (yuima, lambda0, start, delta = 1, ...) { call <- match.call() if (missing(yuima)) yuima.stop("yuima object 'yuima' is missing.") pars <- yuima@model@parameter@all npars <- length(pars) if (missing(lambda0)) { lambda0 <- rep(1, npars) names(lambda0) <- pars lambda0 <- as.list(lambda0) } if(!is.list(lambda0)){ lambda0 <- as.numeric(lambda0) lambda0 <- as.numeric(matrix(lambda0, npars,1)) names(lambda0) <- pars lambda0 <- as.list(lambda0) } if (missing(start)) yuima.stop("Starting values for the parameters are missing.") fail <- lapply(lambda0, function(x) as.numeric(NA)) cat("\nLooking for MLE estimates...\n") fit <- try(qmle(yuima, start = start, ...), silent = TRUE) if (class(fit)[1] == "try-error"){ tmp <- list(mle = fail, sd.mle = NA, lasso = fail, sd.lasso = NA) class(tmp) <- "yuima.lasso" return(tmp) } theta.mle <- coef(fit) SIGMA <- try(sqrt(diag(vcov(fit))), silent = TRUE) if (class(SIGMA)[1] == "try-error"){ tmp <- list(mle = theta.mle, sd.mle = NA, lasso = fail, sd.lasso = NA) class(tmp) <- "yuima.lasso" return(tmp) } H <- try(solve(vcov(fit)), silent = TRUE) if (class(H)[1] == "try-error"){ tmp <- list(mle = theta.mle, sd.mle = SIGMA, lasso = fail, sd.lasso = NA) class(tmp) <- "yuima.lasso" return(tmp) } lambda <- unlist(lambda0[names(theta.mle)])/abs(theta.mle)^delta #lambda1 <- unlist(lambda0[names(theta.mle)])/abs(theta.mle) idx <- which(lambda > 10000) lambda[idx] <- 10000 f2 <- function(theta) as.numeric(t(theta - theta.mle) %*% H %*% (theta - theta.mle) + lambda %*% abs(theta)) cat("\nPerforming LASSO estimation...\n") args <- list(...) args$joint <- NULL args$par <- theta.mle args$fn <- f2 args$hessian <- TRUE args$delta <- NULL args$control <- list(maxit = 30000, temp = 2000, REPORT = 500) # fit2 <- try(optim(theta.mle, f2, hessian = TRUE, args, control = list(maxit = 30000, # temp = 2000, REPORT = 500)), silent = FALSE) fit2 <- try( do.call(optim, args = args), silent = TRUE) if (class(fit2)[1] == "try-error"){ tmp <- list(mle = theta.mle, sd.mle = SIGMA, lasso = fail, sd.lasso = NA) class(tmp) <- "yuima.lasso" return(tmp) } theta.lasso <- fit2$par SIGMA1 <- try(sqrt(diag(solve(fit2$hessian))), silent = TRUE) if (class(SIGMA1)[1] == "try-error"){ tmp <- list(mle = theta.mle, sd.mle = SIGMA, lasso = theta.lasso, sd.lasso = NA) class(tmp) <- "yuima.lasso" return(tmp) } tmp <- list(mle = theta.mle, sd.mle = SIGMA, lasso = theta.lasso, sd.lasso = SIGMA1, call = call, lambda0 = lambda0) class(tmp) <- "yuima.lasso" return(tmp) } print.yuima.lasso <- function(x,...){ cat("Adaptive Lasso estimation\n") cat("\nCall:\n") print(x$cal) if(!is.null(x$mle) & !is.null(x$sd.mle)){ qmle.tab <- rbind(x$mle, x$sd.mle) rownames(qmle.tab) <- c("Estimate", "Std. Error") cat("\nQMLE estimates\n") print(t(qmle.tab)) } if(!is.null(x$lasso) & !is.null(x$sd.lasso)){ lasso.tab <- rbind(x$lasso, x$sd.lasso) rownames(lasso.tab) <- c("Estimate", "Std. Error") cat("\nLASSO estimates\n") print(t(lasso.tab)) } }
/scratch/gouwar.j/cran-all/cranData/yuima/R/lasso.R
setGeneric("limiting.gamma", function(obj, theta, verbose=FALSE) standardGeneric("limiting.gamma") ) setMethod("limiting.gamma", "yuima", function(obj, theta, verbose=FALSE){ limiting.gamma(obj@model, theta, verbose=verbose) }) setMethod("limiting.gamma", "yuima.model", function(obj, theta, verbose=FALSE){ ## error check 1 if(missing(obj)){ stop("main object is missing.") } if(missing(theta)){ stop("theta is missing.") } if(is.list(theta)==FALSE){ stop("theta required list.\ntheta <- list(theta1, theta2)") } if(verbose){ yuima.warn("Initializing... ") } r.size <- [email protected] d.size <- [email protected] state <- [email protected] THETA.1 <- obj@parameter@diffusion THETA.2 <- obj@parameter@drift mi.size <- c(length(THETA.1), length(THETA.2)) ## error check 2 if(d.size!=1){ stop("this program is 1-dimention yuima limitation.") } if(mi.size[1]!=length(theta[[1]])){ stop("the length of m1 and theta1 is different.") } if(mi.size[2]!=length(theta[[2]])){ stop("the length of m2 and theta2 is different.") } Differentiation.vector <- function(myfunc, mystate, dim1, dim2){ tmp <- vector(dim1*dim2, mode="expression") for(i in 1:dim1){ for(j in 1:dim2){ tmp[(i-1)*dim2+j] <- parse(text=deparse(D(myfunc[i], mystate[j]))) } } return(tmp) } Differentiation.scalar <- function(myfunc, mystate, dim){ tmp <- vector(dim, mode="expression") for(i in 1:dim){ tmp[i] <- parse(text=deparse(D(myfunc[i], mystate))) } return(tmp) } ## assign theta for(i in 1:mi.size[1]){ assign(THETA.1[i], theta[[1]][i]) } for(i in 1:mi.size[2]){ assign(THETA.2[i], theta[[2]][i]) } if(verbose){ yuima.warn("Done") } ## p(x) if(verbose){ yuima.warn("get C ... ") } ## a part of p(x) function tmp.y <- function(x.arg){ assign([email protected], x.arg) a.eval <- eval(obj@drift) b.eval <- numeric(d.size) for(i in 1:d.size){ b.eval[i] <- eval(obj@diffusion[[1]][i]) } return(2*a.eval/as.double(t(b.eval)%*%b.eval)) } ## a part of p(x) function for integrate integrate.tmp.y <- function(x.arg){ tmp <- numeric(length(x.arg)) for(i in 1:length(x.arg)){ tmp[i]<-tmp.y(x.arg[i]) } return(tmp) } ## p(x) function without normalize const C p0.x <- function(x.arg){ assign([email protected], x.arg) b.eval <- numeric(d.size) for(i in 1:d.size){ b.eval[i] <- eval(obj@diffusion[[1]][i]) } return(exp(as.double(integrate(integrate.tmp.y, 0, x.arg)$value))/as.double(t(b.eval)%*%b.eval)) } ## p0.x function for integrate integrate.p0.x <- function(x.arg){ tmp <- numeric(length(x.arg)) for(i in 1:length(x.arg)){ tmp[i]<-p0.x(x.arg[i]) } return(tmp) } ## normalize const C <- 1/integrate(integrate.p0.x, -Inf, Inf)$value if(verbose){ yuima.warn("Done") } ## gamma1 if(verbose){ yuima.warn("Get gamma1 ... ") } counter.gamma1 <- 1 ## gamma1 function get.gamma1 <- function(x.arg){ assign([email protected], x.arg) b.eval <- numeric(d.size) for(i in 1:d.size){ b.eval[i] <- eval(obj@diffusion[[1]][i]) } Bi <- solve(t(b.eval)%*%b.eval) dTHETA.1.B <- array(0,c(d.size, d.size, mi.size[1])) tmp1.B <- array(0, c(d.size, d.size, mi.size[1])) tmp2.B <- numeric(mi.size[1]) for(k in 1:mi.size[1]){ dTHETA.1.b <- Differentiation.scalar(obj@diffusion[[1]], THETA.1[k], d.size) dTHETA.1.b.eval <- numeric(d.size) for(i in 1:d.size){ dTHETA.1.b.eval[i] <- eval(dTHETA.1.b[i]) } tmp <- b.eval%*%t(dTHETA.1.b.eval) dTHETA.1.B[, , k] <- tmp+t(tmp) tmp1.B[, , k] <- dTHETA.1.B[, , k]%*%Bi tmp2.B[k] <- tmp1.B[, , k] #sum(diag(tmp1.B[,,k])) 1-dimention limitation } tmp <- tmp2.B %*% t(tmp2.B) * p0.x(x.arg) return(tmp[((counter.gamma1-1)%%mi.size[1])+1, ((counter.gamma1-1)%/%mi.size[1])+1]) } ## gamma1 function for integrate integrate.get.gamma1 <- function(x.arg){ tmp <- numeric(length(x.arg)) for(i in 1:length(x.arg)){ tmp[i] <- get.gamma1(x.arg[i]) } return(tmp*C/2) } ## calculating gamma1 gamma1 <- matrix(0, mi.size[1], mi.size[1]) for(i in 1:(mi.size[1]*mi.size[1])){ gamma1[((i-1)%%mi.size[1])+1,((i-1)%/%mi.size[1])+1] <- integrate(integrate.get.gamma1, -Inf, Inf)$value counter.gamma1 <- counter.gamma1+1 } if(verbose){ yuima.warn("Done") } ## gamma2 if(verbose){ yuima.warn("Get gamma2 ... ") } counter.gamma2 <- 1 ## gamma2 function get.gamma2 <- function(x.arg){ assign([email protected], x.arg) if(mi.size[2]==1){ dTHETA.2.a <- Differentiation.scalar(obj@drift, THETA.2, d.size) }else{ dTHETA.2.a <- Differentiation.vector(obj@drift, THETA.2, d.size, mi.size[2]) } dTHETA.2.a.eval <- numeric(mi.size[2]) for(i in 1:mi.size[2]){ dTHETA.2.a.eval[i] <- eval(dTHETA.2.a[i]) } b.eval <- numeric(d.size) for(i in 1:d.size){ b.eval[i] <- eval(obj@diffusion[[1]][i]) } Bi <- solve(t(b.eval)%*%b.eval) tmp <- dTHETA.2.a.eval %*% Bi %*% t(dTHETA.2.a.eval) * p0.x(x.arg) return(tmp[((counter.gamma2-1)%%mi.size[2])+1, ((counter.gamma2-1)%/%mi.size[2])+1]) } ## gamma2 function for intefrate integrate.get.gamma2 <- function(x.arg){ tmp <- numeric(length(x.arg)) for(i in 1:length(x.arg)){ tmp[i]<-get.gamma2(x.arg[i]) } return(tmp*C) } ## calculating gamma2 gamma2 <- matrix(0, mi.size[2], mi.size[2]) for(i in 1:(mi.size[2]*mi.size[2])){ gamma2[((i-1)%%mi.size[2])+1, ((i-1)%/%mi.size[2])+1] <- integrate(integrate.get.gamma2, -Inf, Inf)$value counter.gamma2 <- counter.gamma2+1 } if(verbose){ yuima.warn("Done") } ## make list for return poi1 <- list(gamma1, gamma2) names(poi1) <- c("gamma1", "gamma2") poi2 <- append(gamma1, gamma2) ret <- list(poi1, poi2) names(ret) <- c("list", "vec") return(ret) })
/scratch/gouwar.j/cran-all/cranData/yuima/R/limiting.gamma.R
#lead-lag estimation #x:data #setGeneric( "llag", function(x,verbose=FALSE) standardGeneric("llag") ) #setMethod( "llag", "yuima", function(x,verbose=FALSE) llag(x@data,verbose=verbose )) #setMethod( "llag", "yuima.data", function(x,verbose=FALSE) { #setGeneric( "llag", # function(x,from=FALSE,to=FALSE,division=FALSE,verbose=FALSE) # standardGeneric("llag") ) #setMethod( "llag", "yuima", # function(x,from=FALSE,to=FALSE,division=FALSE,verbose=FALSE) # llag(x@data,from=FALSE,to=FALSE,division=FALSE,verbose=verbose )) #setMethod( "llag", "yuima.data", function(x,from=FALSE,to=FALSE,division=FALSE,verbose=FALSE) { ## function to make the grid if it is missing make.grid <- function(d, d.size, x, from, to, division){ out <- vector(d.size, mode = "list") if(length(from) != d.size){ from <- c(from,rep(-Inf,d.size - length(from))) } if(length(to) != d.size){ to <- c(to,rep(Inf,d.size - length(to))) } if(length(division) == 1){ division <- rep(division,d.size) } for(i in 1:(d-1)){ for(j in (i+1):d){ time1 <- as.numeric(time(x[[i]])) time2 <- as.numeric(time(x[[j]])) # calculate the maximum of correlation by substituting theta to lagcce #n:=2*length(data) num <- d*(i-1) - (i-1)*i/2 + (j-i) if(division[num]==FALSE){ n <- round(2*max(length(time1),length(time2)))+1 }else{ n <- division[num] } # maximum value of lagcce tmptheta <- time2[1]-time1[1] # time lag (sec) num1 <- time1[length(time1)]-time1[1] # elapsed time for series 1 num2 <- time2[length(time2)]-time2[1] # elapsed time for series 2 # modified if(is.numeric(from[num])==TRUE && is.numeric(to[num])==TRUE){ num2 <- min(-from[num],num2+tmptheta) num1 <- min(to[num],num1-tmptheta) tmptheta <- 0 if(-num2 >= num1){ print("llag:invalid range") return(NULL) } }else if(is.numeric(from[num])==TRUE){ num2 <- min(-from[num],num2+tmptheta) num1 <- num1-tmptheta tmptheta <- 0 if(-num2 >= num1){ print("llag:invalid range") return(NULL) } }else if(is.numeric(to[num])==TRUE){ num2 <- num2+tmptheta num1 <- min(to[num],num1-tmptheta) tmptheta <- 0 if(-num2 >= num1){ print("llag:invalid range") return(NULL) } } out[[num]] <- seq(-num2-tmptheta,num1-tmptheta,length=n)[2:(n-1)] } } return(out) } ## function to compute asymptotic variances llag.avar <- function(x, grid, bw, alpha, fisher, ser.diffX, ser.times, vol, cormat, ccor, idx, G, d, d.size, tol){ # treatment of the bandwidth if(missing(bw)){ bw <- matrix(0, d, d) for(i in 1:(d - 1)){ for(j in (i + 1):d){ Init <- min(ser.times[[i]][1], ser.times[[j]][1]) Term <- max(tail(ser.times[[i]], n = 1), tail(ser.times[[j]], n = 1)) bw[i, j] <- (Term - Init) * min(length(ser.times[[i]]), length(ser.times[[j]]))^(-0.45) bw[j, i] <- bw[i, j] } } }else{ bw <- bw/tol } bw <- matrix(bw, d, d) p <- diag(d) # p-values avar <- vector(d.size,mode="list") # asymptotic variances CI <- vector(d.size,mode="list") # confidence intervals names(avar) <- names(ccor) names(CI) <- names(ccor) vv <- (2/3) * sapply(ser.diffX, FUN = function(x) sum(x^4)) # AVAR for RV for(i in 1:(d-1)){ for(j in (i+1):d){ time1 <- ser.times[[i]] time2 <- ser.times[[j]] num <- d*(i-1) - (i-1)*i/2 + (j-i) ## computing conficence intervals N.max <- max(length(time1), length(time2)) tmp <- rev(as.numeric(ccor[[num]])) d1 <- -0.5 * tmp * sqrt(vol[j]/vol[i]) d2 <- -0.5 * tmp * sqrt(vol[i]/vol[j]) avar.tmp <- .C("hycrossavar", as.double(G[[num]]), as.double(time1), as.double(time2), as.integer(length(G[[num]])), as.integer(length(time1)), as.integer(length(time2)), as.double(x[[i]]), as.double(x[[j]]), as.integer(N.max), as.double(bw[i, j]), as.double(vv[i]), as.double(vv[j]), as.double(d1^2), as.double(d2^2), as.double(2 * d1), as.double(2 * d2), as.double(2 * d1 * d2), covar = double(length(G[[num]])), corr = double(length(G[[num]])), PACKAGE = "yuima")$corr / (vol[i] * vol[j]) #avar[[num]][avar[[num]] <= 0] <- NA if(fisher == TRUE){ z <- atanh(tmp) # the Fisher z transformation of the estimated correlation se.z <- sqrt(avar.tmp)/(1 - tmp^2) p[i,j] <- pchisq((atanh(cormat[i,j])/se.z[idx[num]])^2, df=1, lower.tail=FALSE) CI[[num]] <- zoo(tanh(qnorm(1 - alpha/2) * se.z), -grid[[num]]) }else{ p[i,j] <- pchisq(cormat[i,j]^2/avar.tmp[idx[num]], df=1, lower.tail=FALSE) c.alpha <- sqrt(qchisq(alpha, df=1, lower.tail = FALSE) * avar.tmp) CI[[num]] <- zoo(c.alpha, -grid[[num]]) } p[j,i] <- p[i,j] avar[[num]] <- zoo(avar.tmp, -grid[[num]]) } } return(list(p = p, avar = avar, CI = CI)) } ## main body setGeneric( "llag", function(x, from = -Inf, to = Inf, division = FALSE, verbose = (ci || ccor), grid, psd = TRUE, plot = ci, ccor = ci, ci = FALSE, alpha = 0.01, fisher = TRUE, bw, tol = 1e-6) standardGeneric("llag") ) ## yuima-method setMethod("llag", "yuima", function(x, from, to, division, verbose, grid, psd, plot, ccor, ci, alpha, fisher, bw, tol) llag(x@data, from, to, division, verbose, grid, psd, plot, ccor, ci, alpha, fisher, bw, tol)) ## yuima.data-method setMethod("llag", "yuima.data", function(x, from, to, division, verbose, grid, psd, plot, ccor, ci, alpha, fisher, bw, tol) llag([email protected], from, to, division, verbose, grid, psd, plot, ccor, ci, alpha, fisher, bw, tol)) ## list-method setMethod("llag", "list", function(x, from, to, division, verbose, grid, psd, plot, ccor, ci, alpha, fisher, bw, tol) { d <- length(x) d.size <- d*(d-1)/2 # allocate memory ser.times <- vector(d, mode="list") # time index in 'x' ser.diffX <- vector(d, mode="list") # difference of data vol <- double(d) # treatment of the grid (2016-07-04: we implement this before the NA treatment) if(missing(grid)) grid <- make.grid(d, d.size, x, from, to, division) # Set the tolerance to avoid numerical erros in comparison #tol <- 1e-6 for(i in 1:d){ # NA data must be skipped idt <- which(is.na(x[[i]])) if(length(idt>0)){ x[[i]] <- x[[i]][-idt] } if(length(x[[i]])<2) { stop("length of data (w/o NA) must be more than 1") } # set data and time index ser.times[[i]] <- as.numeric(time(x[[i]]))/tol # set difference of the data ser.diffX[[i]] <- diff( as.numeric(x[[i]]) ) vol[i] <- sum(ser.diffX[[i]]^2) } theta <- matrix(0,d,d) #d.size <- d*(d-1)/2 crosscor <- vector(d.size,mode="list") idx <- integer(d.size) # treatment of the grid #if(missing(grid)) # grid <- make.grid(d, d.size, x, from, to, division) if(is.list(grid)){ G <- relist(unlist(grid)/tol, grid) }else{ if(is.numeric(grid)){ G <- data.frame(matrix(grid/tol,length(grid),d.size)) grid <- data.frame(matrix(grid,length(grid),d.size)) }else{ print("llag:invalid grid") return(NULL) } } # core part if(psd){ # positive semidefinite correction is implemented cormat <- diag(d) LLR <- diag(d) for(i in 1:(d-1)){ for(j in (i+1):d){ time1 <- ser.times[[i]] time2 <- ser.times[[j]] num <- d*(i-1) - (i-1)*i/2 + (j-i) names(crosscor)[num] <- paste("(",i,",",j,")", sep = "") tmp <- .C("HYcrosscorr2", as.integer(length(G[[num]])), as.integer(length(time1)), as.integer(length(time2)), as.double(G[[num]]), as.double(time1), as.double(time2), #double(length(time2)), as.double(ser.diffX[[i]]), as.double(ser.diffX[[j]]), as.double(vol[i]), as.double(vol[j]), value=double(length(G[[num]])), PACKAGE = "yuima")$value idx[num] <- which.max(abs(tmp)) mlag <- -grid[[num]][idx[num]] # make the first timing of max or min cor <- tmp[idx[num]] theta[i,j] <- mlag cormat[i,j] <- cor theta[j,i] <- -mlag cormat[j,i] <- cormat[i,j] LLR[i,j] <- sum(tmp[grid[[num]] < 0]^2)/sum(tmp[grid[[num]] > 0]^2) LLR[j,i] <- 1/LLR[i,j] crosscor[[num]] <- zoo(tmp,-grid[[num]]) } } covmat <- diag(sqrt(vol))%*%cormat%*%diag(sqrt(vol)) }else{# non-psd covmat <- diag(vol) LLR <- diag(d) for(i in 1:(d-1)){ for(j in (i+1):d){ time1 <- ser.times[[i]] time2 <- ser.times[[j]] num <- d*(i-1) - (i-1)*i/2 + (j-i) names(crosscor)[num] <- paste("(",i,",",j,")", sep = "") tmp <- .C("HYcrosscov2", as.integer(length(G[[num]])), as.integer(length(time1)), as.integer(length(time2)), as.double(G[[num]]), as.double(time1), as.double(time2), #double(length(time2)), as.double(ser.diffX[[i]]), as.double(ser.diffX[[j]]), value=double(length(G[[num]])), PACKAGE = "yuima")$value idx[num] <- which.max(abs(tmp)) mlag <- -grid[[num]][idx[num]] # make the first timing of max or min cov <- tmp[idx[num]] theta[i,j] <- mlag covmat[i,j] <- cov theta[j,i] <- -mlag covmat[j,i] <- covmat[i,j] LLR[i,j] <- sum(tmp[grid[[num]] < 0]^2)/sum(tmp[grid[[num]] > 0]^2) LLR[j,i] <- 1/LLR[i,j] crosscor[[num]] <- zoo(tmp,-grid[[num]])/sqrt(vol[i]*vol[j]) } } cormat <- diag(1/sqrt(diag(covmat)))%*%covmat%*%diag(1/sqrt(diag(covmat))) } if(ci){ # computing confidence intervals out <- llag.avar(x = x, grid = grid, bw = bw, alpha = alpha, fisher = fisher, ser.diffX = ser.diffX, ser.times = ser.times, vol = vol, cormat = cormat, ccor = crosscor, idx = idx, G = G, d = d, d.size = d.size, tol = tol) p <- out$p CI <- out$CI avar <- out$avar colnames(theta) <- names(x) rownames(theta) <- names(x) colnames(p) <- names(x) rownames(p) <- names(x) if(plot){ for(i in 1:(d-1)){ for(j in (i+1):d){ num <- d*(i-1) - (i-1)*i/2 + (j-i) y.max <- max(abs(as.numeric(crosscor[[num]])),as.numeric(CI[[num]])) plot(crosscor[[num]], main=paste(i,"vs",j,"(positive",expression(theta),"means",i,"leads",j,")"), xlab=expression(theta),ylab=expression(U(theta)), ylim=c(-y.max,y.max)) lines(CI[[num]],lty=2,col="blue") lines(-CI[[num]],lty=2,col="blue") } } } if(verbose==TRUE){ colnames(covmat) <- names(x) rownames(covmat) <- names(x) colnames(cormat) <- names(x) rownames(cormat) <- names(x) colnames(LLR) <- names(x) rownames(LLR) <- names(x) if(ccor){ result <- list(lagcce=theta,p.values=p,covmat=covmat,cormat=cormat,LLR=LLR,ccor=crosscor,avar=avar) }else{ result <- list(lagcce=theta,p.values=p,covmat=covmat,cormat=cormat,LLR=LLR) } }else{ return(theta) } }else{ colnames(theta) <- names(x) rownames(theta) <- names(x) if(plot){ for(i in 1:(d-1)){ for(j in (i+1):d){ num <- d*(i-1) - (i-1)*i/2 + (j-i) plot(crosscor[[num]], main=paste(i,"vs",j,"(positive",expression(theta),"means",i,"leads",j,")"), xlab=expression(theta),ylab=expression(U(theta))) } } } if(verbose==TRUE){ colnames(covmat) <- names(x) rownames(covmat) <- names(x) colnames(cormat) <- names(x) rownames(cormat) <- names(x) colnames(LLR) <- names(x) rownames(LLR) <- names(x) if(ccor){ result <- list(lagcce=theta,covmat=covmat,cormat=cormat,LLR=LLR,ccor=crosscor) }else{ result <- list(lagcce=theta,covmat=covmat,cormat=cormat,LLR=LLR) } }else{ return(theta) } } class(result) <- "yuima.llag" return(result) }) # print method for yuima.llag-class print.yuima.llag <- function(x, ...){ if(is.null(x$p.values)){ cat("Estimated lead-lag parameters\n") print(x$lagcce, ...) cat("Corresponding covariance matrix\n") print(x$covmat, ...) cat("Corresponding correlation matrix\n") print(x$cormat, ...) cat("Lead-lag ratio\n") print(x$LLR, ...) }else{ cat("Estimated lead-lag parameters\n") print(x$lagcce, ...) cat("Corresponding p-values\n") print(x$p.values, ...) cat("Corresponding covariance matrix\n") print(x$covmat, ...) cat("Corresponding correlation matrix\n") print(x$cormat, ...) cat("Lead-lag ratio\n") print(x$LLR, ...) } } # plot method for yuima.llag-class plot.yuima.llag <- function(x, alpha = 0.01, fisher = TRUE, main = NULL, xlab = NULL, ylab = NULL, ...){ if(is.null(x$ccor)){ warning("cross-correlation functions were not returned by llag. Set verbose = TRUE and ccor = TRUE to return them.", call. = FALSE) return(NULL) }else{ if(is.null(xlab)) xlab <- expression(theta) if(is.null(ylab)) ylab <- expression(U(theta)) d <- nrow(x$LLR) if(is.null(x$avar)){ for(i in 1:(d-1)){ for(j in (i+1):d){ num <- d*(i-1) - (i-1)*i/2 + (j-i) if(is.null(main)){ plot(x$ccor[[num]], main=paste(i,"vs",j,"(positive",expression(theta),"means",i,"leads",j,")"), xlab=xlab,ylab=ylab) }else{ plot(x$ccor[[num]],main=main,xlab=xlab,ylab=ylab) } } } }else{ for(i in 1:(d-1)){ for(j in (i+1):d){ num <- d*(i-1) - (i-1)*i/2 + (j-i) G <- time(x$ccor[[num]]) if(fisher == TRUE){ z <- atanh(x$ccor[[num]]) # the Fisher z transformation of the estimated correlation se.z <- sqrt(x$avar[[num]])/(1 - x$ccor[[num]]^2) CI <- zoo(tanh(qnorm(1 - alpha/2) * se.z), G) }else{ c.alpha <- sqrt(qchisq(alpha, df=1, lower.tail = FALSE) * x$avar[[num]]) CI <- zoo(c.alpha, G) } y.max <- max(abs(as.numeric(x$ccor[[num]])),as.numeric(CI)) if(is.null(main)){ plot(x$ccor[[num]], main=paste(i,"vs",j,"(positive",expression(theta),"means",i,"leads",j,")"), xlab=xlab,ylab=ylab,ylim=c(-y.max,y.max)) }else{ plot(x$ccor[[num]],main = main,xlab=xlab,ylab=ylab, ylim=c(-y.max,y.max)) } lines(CI,lty=2,col="blue") lines(-CI,lty=2,col="blue") } } } } } ## Old version until Oct. 10, 2015 if(0){ setGeneric( "llag", function(x,from=-Inf,to=Inf,division=FALSE,verbose=FALSE,grid,psd=TRUE, plot=FALSE,ccor=FALSE) standardGeneric("llag") ) setMethod( "llag", "yuima", function(x,from=-Inf,to=Inf,division=FALSE,verbose=FALSE,grid,psd=TRUE, plot=FALSE,ccor=FALSE) llag(x@data,from=from,to=to,division=division,verbose=verbose,grid=grid, psd=psd,plot=plot)) setMethod( "llag", "yuima.data", function(x,from=-Inf,to=Inf,division=FALSE, verbose=FALSE,grid,psd=TRUE, plot=FALSE,ccor=FALSE) { if((is(x)=="yuima")||(is(x)=="yuima.data")){ zdata <- get.zoo.data(x) }else{ print("llag:invalid argument") return(NULL) } d <- length(zdata) # allocate memory ser.times <- vector(d, mode="list") # time index in 'x' ser.diffX <- vector(d, mode="list") # difference of data vol <- double(d) # Set the tolerance to avoid numerical erros in comparison tol <- 1e-6 for(i in 1:d){ # NA data must be skipped idt <- which(is.na(zdata[[i]])) if(length(idt>0)){ zdata[[i]] <- zdata[[i]][-idt] } if(length(zdata[[i]])<2) { stop("length of data (w/o NA) must be more than 1") } # set data and time index ser.times[[i]] <- as.numeric(time(zdata[[i]])) # set difference of the data ser.diffX[[i]] <- diff( as.numeric(zdata[[i]]) ) vol[i] <- sum(ser.diffX[[i]]^2) } theta <- matrix(0,d,d) d.size <- d*(d-1)/2 crosscor <- vector(d.size,mode="list") if(psd){ cormat <- diag(d) if(missing(grid)){ if(length(from) != d.size){ from <- c(from,rep(-Inf,d.size - length(from))) } if(length(to) != d.size){ to <- c(to,rep(Inf,d.size - length(to))) } if(length(division) == 1){ division <- rep(division,d.size) } for(i in 1:(d-1)){ for(j in (i+1):d){ time1 <- ser.times[[i]] time2 <- ser.times[[j]] # calculate the maximum of correlation by substituting theta to lagcce #n:=2*length(data) num <- d*(i-1) - (i-1)*i/2 + (j-i) if(division[num]==FALSE){ n <- round(2*max(length(time1),length(time2)))+1 }else{ n <- division[num] } # maximum value of lagcce tmptheta <- time2[1]-time1[1] # time lag (sec) num1 <- time1[length(time1)]-time1[1] # elapsed time for series 1 num2 <- time2[length(time2)]-time2[1] # elapsed time for series 2 # modified if(is.numeric(from[num])==TRUE && is.numeric(to[num])==TRUE){ num2 <- min(-from[num],num2+tmptheta) num1 <- min(to[num],num1-tmptheta) tmptheta <- 0 if(-num2 >= num1){ print("llag:invalid range") return(NULL) } }else if(is.numeric(from[num])==TRUE){ num2 <- min(-from[num],num2+tmptheta) num1 <- num1-tmptheta tmptheta <- 0 if(-num2 >= num1){ print("llag:invalid range") return(NULL) } }else if(is.numeric(to[num])==TRUE){ num2 <- num2+tmptheta num1 <- min(to[num],num1-tmptheta) tmptheta <- 0 if(-num2 >= num1){ print("llag:invalid range") return(NULL) } } y <- seq(-num2-tmptheta,num1-tmptheta,length=n)[2:(n-1)] tmp <- .C("HYcrosscorr", as.integer(n-2), as.integer(length(time1)), as.integer(length(time2)), as.double(y/tol), as.double(time1/tol), as.double(time2/tol), double(length(time2)), as.double(ser.diffX[[i]]), as.double(ser.diffX[[j]]), as.double(vol[i]), as.double(vol[j]), value=double(n-2), PACKAGE = "yuima")$value idx <- which.max(abs(tmp)) mlag <- -y[idx] # make the first timing of max or min corr <- tmp[idx] theta[i,j] <- mlag cormat[i,j] <- corr theta[j,i] <- -mlag cormat[j,i] <- cormat[i,j] crosscor[[num]] <- zoo(tmp,-y) } } }else{ if(!is.list(grid)){ if(is.numeric(grid)){ grid <- data.frame(matrix(grid,length(grid),d.size)) }else{ print("llag:invalid grid") return(NULL) } } for(i in 1:(d-1)){ for(j in (i+1):d){ time1 <- ser.times[[i]] time2 <- ser.times[[j]] num <- d*(i-1) - (i-1)*i/2 + (j-i) tmp <- .C("HYcrosscorr", as.integer(length(grid[[num]])), as.integer(length(time1)), as.integer(length(time2)), as.double(grid[[num]]/tol), as.double(time1/tol), as.double(time2/tol), double(length(time2)), as.double(ser.diffX[[i]]), as.double(ser.diffX[[j]]), as.double(vol[i]), as.double(vol[j]), value=double(length(grid[[num]])), PACKAGE = "yuima")$value idx <- which.max(abs(tmp)) mlag <- -grid[[num]][idx] # make the first timing of max or min cor <- tmp[idx] theta[i,j] <- mlag cormat[i,j] <- cor theta[j,i] <- -mlag cormat[j,i] <- cormat[i,j] crosscor[[num]] <- zoo(tmp,-grid[[num]]) } } } covmat <- diag(sqrt(vol))%*%cormat%*%diag(sqrt(vol)) }else{# non-psd covmat <- diag(vol) if(missing(grid)){ if(length(from) != d.size){ from <- c(from,rep(-Inf,d.size - length(from))) } if(length(to) != d.size){ to <- c(to,rep(Inf,d.size - length(to))) } if(length(division) == 1){ division <- rep(division,d.size) } for(i in 1:(d-1)){ for(j in (i+1):d){ time1 <- ser.times[[i]] time2 <- ser.times[[j]] # calculate the maximum of correlation by substituting theta to lagcce #n:=2*length(data) num <- d*(i-1) - (i-1)*i/2 + (j-i) if(division[num]==FALSE){ n <- round(2*max(length(time1),length(time2)))+1 }else{ n <- division[num] } # maximum value of lagcce tmptheta <- time2[1]-time1[1] # time lag (sec) num1 <- time1[length(time1)]-time1[1] # elapsed time for series 1 num2 <- time2[length(time2)]-time2[1] # elapsed time for series 2 # modified if(is.numeric(from[num])==TRUE && is.numeric(to[num])==TRUE){ num2 <- min(-from[num],num2+tmptheta) num1 <- min(to[num],num1-tmptheta) tmptheta <- 0 if(-num2 >= num1){ print("llag:invalid range") return(NULL) } }else if(is.numeric(from[num])==TRUE){ num2 <- min(-from[num],num2+tmptheta) num1 <- num1-tmptheta tmptheta <- 0 if(-num2 >= num1){ print("llag:invalid range") return(NULL) } }else if(is.numeric(to[num])==TRUE){ num2 <- num2+tmptheta num1 <- min(to[num],num1-tmptheta) tmptheta <- 0 if(-num2 >= num1){ print("llag:invalid range") return(NULL) } } y <- seq(-num2-tmptheta,num1-tmptheta,length=n)[2:(n-1)] tmp <- .C("HYcrosscov", as.integer(n-2), as.integer(length(time1)), as.integer(length(time2)), as.double(y/tol), as.double(time1/tol), as.double(time2/tol), double(length(time2)), as.double(ser.diffX[[i]]), as.double(ser.diffX[[j]]), value=double(n-2), PACKAGE = "yuima")$value idx <- which.max(abs(tmp)) mlag <- -y[idx] # make the first timing of max or min cov <- tmp[idx] theta[i,j] <- mlag covmat[i,j] <- cov theta[j,i] <- -mlag covmat[j,i] <- covmat[i,j] crosscor[[num]] <- zoo(tmp,-y)/sqrt(vol[i]*vol[j]) } } }else{ if(!is.list(grid)){ if(is.numeric(grid)){ grid <- data.frame(matrix(grid,length(grid),d.size)) }else{ print("llag:invalid grid") return(NULL) } } for(i in 1:(d-1)){ for(j in (i+1):d){ time1 <- ser.times[[i]] time2 <- ser.times[[j]] num <- d*(i-1) - (i-1)*i/2 + (j-i) tmp <- .C("HYcrosscov", as.integer(length(grid[[num]])), as.integer(length(time1)), as.integer(length(time2)), as.double(grid[[num]]/tol), as.double(time1/tol), as.double(time2/tol), double(length(time2)), as.double(ser.diffX[[i]]), as.double(ser.diffX[[j]]), value=double(length(grid[[num]])), PACKAGE = "yuima")$value idx <- which.max(abs(tmp)) mlag <- -grid[[num]][idx] # make the first timing of max or min cov <- tmp[idx] theta[i,j] <- mlag covmat[i,j] <- cov theta[j,i] <- -mlag covmat[j,i] <- covmat[i,j] crosscor[[num]] <- zoo(tmp,-grid[[num]])/sqrt(vol[i]*vol[j]) } } } cormat <- diag(1/sqrt(diag(covmat)))%*%covmat%*%diag(1/sqrt(diag(covmat))) } colnames(theta) <- names(zdata) rownames(theta) <- names(zdata) if(plot){ for(i in 1:(d-1)){ for(j in (i+1):d){ num <- d*(i-1) - (i-1)*i/2 + (j-i) plot(crosscor[[num]], main=paste(i,"vs",j,"(positive",expression(theta),"means",i,"leads",j,")"), xlab=expression(theta),ylab=expression(U(theta))) } } } if(verbose==TRUE){ colnames(covmat) <- names(zdata) rownames(covmat) <- names(zdata) colnames(cormat) <- names(zdata) rownames(cormat) <- names(zdata) if(ccor){ return(list(lagcce=theta,covmat=covmat,cormat=cormat,ccor=crosscor)) }else{ return(list(lagcce=theta,covmat=covmat,cormat=cormat)) } }else{ return(theta) } }) } ## Old version if(0){ setMethod( "llag", "yuima.data", function(x,from=-Inf,to=Inf,division=FALSE,verbose=FALSE) { if(!is(x)=="yuima.data"){ if(is(x)=="yuima"){ dat <- x@data }else{ print("llag:invalid argument") return(NULL) } }else{ dat <- x } d <- length([email protected]) lagccep <- function(datp,theta){ time(datp[[2]]) <- time(datp[[2]])+theta return(cce(setData(datp))$covmat[1,2]) } lagcce <- function(datzoo,theta){ d <- dim(theta)[1] lcmat <- cce(setData(datzoo))$covmat for(i in 1:(d-1)){ for(j in (i+1):d){ datp <- datzoo[c(i,j)] lcmat[i,j] <- lagccep(datp,theta[i,j]) lcmat[j,i] <- lcmat[i,j] } } return(lcmat) } d.size <- d*(d-1)/2 if(length(from) != d.size){ from <- c(from,rep(-Inf,d.size - length(from))) } if(length(to) != d.size){ to <- c(to,rep(Inf,d.size - length(to))) } if(length(division) != d.size){ division <- c(division,rep(FALSE,d.size - length(division))) } find_lag <- function(i,j){ datp <- [email protected][c(i,j)] time1 <- time(datp[[1]]) time2 <- time(datp[[2]]) # calculate the maximum of correlation by substituting theta to lagcce #n:=2*length(data) num <- d*(i-1) - (i-1)*i/2 + (j-i) if(division[num]==FALSE){ n <- round(2*max(length(datp[[1]]),length(datp[[2]])))+1 }else{ n <- division[num] } # maximum value of lagcce tmptheta <- as.numeric(time2[1])-as.numeric(time1[1]) # time lag (sec) num1 <- as.numeric(time1[length(time1)])-as.numeric(time1[1]) # elapsed time for series 1 num2 <- as.numeric(time2[length(time2)])-as.numeric(time2[1]) # elapsed time for series 2 # modified if(is.numeric(from[num])==TRUE && is.numeric(to[num])==TRUE){ num2 <- min(-from[num],num2+tmptheta) num1 <- min(to[num],num1-tmptheta) tmptheta <- 0 if(-num2 >= num1){ print("llag:invalid range") return(NULL) } }else if(is.numeric(from[num])==TRUE){ num2 <- min(-from[num],num2+tmptheta) num1 <- num1-tmptheta tmptheta <- 0 if(-num2 >= num1){ print("llag:invalid range") return(NULL) } }else if(is.numeric(to[num])==TRUE){ num2 <- num2+tmptheta num1 <- min(to[num],num1-tmptheta) tmptheta <- 0 if(-num2 >= num1){ print("llag:invalid range") return(NULL) } } y <- seq(-num2-tmptheta,num1-tmptheta,length=n) tmp <- double(n) for(i.tmp in 2:(n-1)){ tmp[i.tmp] <- lagccep(datp,y[i.tmp]) } mat <- cbind(y[2:(n-1)],tmp[2:(n-1)]) #idx <- abs(mat[,2])==max(abs(mat[,2])) #mlag <- mat[,1][idx][1] # make the first timing of max or min #cov <- mat[,2][idx][1] idx <- which.max(abs(mat[,2])) mlag <- mat[,1][idx] # make the first timing of max or min cov <- mat[,2][idx] return(list(lag=-mlag,cov=cov)) } theta <- matrix(numeric(d^2),ncol=d) covmat <- cce(dat)$covmat for(i in 1:(d-1)){ for(j in (i+1):d){ fl <- find_lag(i,j) theta[i,j] <- fl$lag covmat[i,j] <- fl$cov theta[j,i] <- -theta[i,j] covmat[j,i] <- covmat[i,j] } } # covmat <- lagcce([email protected],theta) cormat <- diag(1/sqrt(diag(covmat)))%*%covmat%*%diag(1/sqrt(diag(covmat))) if(verbose==TRUE){ return(list(lagcce=theta,covmat=covmat,cormat=cormat)) }else{ return(theta) } }) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/llag.R
llag.test <- function(x, from = -Inf, to = Inf, division = FALSE, grid, R = 999, parallel = "no", ncpus = getOption("boot.ncpus", 1L), cl = NULL, tol = 1e-6){ x <- get.zoo.data(x) d <- length(x) d.size <- d*(d-1)/2 # allocate memory ser.times <- vector(d, mode="list") # time index in 'x' ser.diffX <- vector(d, mode="list") # difference of data vol <- double(d) # treatment of the grid (2016-07-04: we implement this before the NA treatment) if(missing(grid)) grid <- make.grid(d, d.size, x, from, to, division) # Set the tolerance to avoid numerical erros in comparison #tol <- 1e-6 for(i in 1:d){ # NA data must be skipped idt <- which(is.na(x[[i]])) if(length(idt>0)){ x[[i]] <- x[[i]][-idt] } if(length(x[[i]])<2) { stop("length of data (w/o NA) must be more than 1") } # set data and time index ser.times[[i]] <- as.numeric(time(x[[i]]))/tol # set difference of the data ser.diffX[[i]] <- diff( as.numeric(x[[i]]) ) vol[i] <- sum(ser.diffX[[i]]^2) } pval <- matrix(0,d,d) mcov <- diag(vol) mcor <- diag(d) rownames(pval) <- names(x) rownames(mcov) <- names(x) rownames(mcor) <- names(x) colnames(pval) <- names(x) colnames(mcov) <- names(x) colnames(mcor) <- names(x) # treatment of the grid #if(missing(grid)) # grid <- make.grid(d, d.size, x, from, to, division) if(is.list(grid)){ G <- relist(unlist(grid)/tol, grid) }else{ if(is.numeric(grid)){ G <- data.frame(matrix(grid/tol,length(grid),d.size)) grid <- data.frame(matrix(grid,length(grid),d.size)) }else{ print("llag:invalid grid") return(NULL) } } # core part for(i in 1:(d-1)){ for(j in (i+1):d){ time1 <- ser.times[[i]] time2 <- ser.times[[j]] num <- d*(i-1) - (i-1)*i/2 + (j-i) hry <- function(data){ dx <- data$dx dy <- data$dy U <- .C("HYcrosscov2", as.integer(length(G[[num]])), as.integer(length(time1)), as.integer(length(time2)), as.double(G[[num]]), as.double(time1), as.double(time2), #double(length(time2)), as.double(dx), as.double(dy), value=double(length(G[[num]])), PACKAGE = "yuima")$value return(max(abs(U))) } ran.gen <- function(data, mle){ dx <- data$dx dy <- data$dy list(dx = (2*rbinom(length(dx),1,0.5)-1) * dx, dy = (2*rbinom(length(dy),1,0.5)-1) * dy) } out <- boot(list(dx = ser.diffX[[i]], dy = ser.diffX[[j]]), hry, R, sim = "parametric", ran.gen = ran.gen, parallel = parallel, ncpus = ncpus, cl = cl) pval[i,j] <- mean(out$t > out$t0) mcov[i,j] <- out$t0 mcor[i,j] <- out$t0/sqrt(vol[i]*vol[j]) pval[j,i] <- pval[i,j] mcov[j,i] <- mcov[i,j] mcor[j,i] <- mcor[i,j] } } return(list(p.values = pval, max.cov = mcov, max.corr = mcor)) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/llag.test.R
# Lee-Mykland's jump test lm.jumptest <- function(yuima, K){ data <- get.zoo.data(yuima) d.size <- length(data) n <- length(yuima) - 1 if(missing(K)) K <- pmin(floor(sqrt(252*n)), n) K <- rep(K, d.size) cn <- sqrt(2*log(n)) - (log(pi) + log(log(n)))/(2*sqrt(2*log(n))) sn <- 1/sqrt(2*log(n)) result <- vector(d.size,mode="list") for(d in 1:d.size){ x <- data[[d]] adx <- abs(diff(as.numeric(x))) v.hat <- (pi/2) * rollmeanr(adx[-n[d]] * adx[-1], k = K[d] - 2, fill = "e") v.hat <- append(v.hat, v.hat[1], after = 0) stat <- (max(adx/sqrt(v.hat)) - cn[d])/sn[d] p <- 1 - exp(-exp(-stat)) result[[d]] <- list(statistic = c(LM = stat), p.value = p, method = "Lee and Mykland jump test", data.names = paste("x",d,sep = "")) class(result[[d]]) <- "htest" } return(result) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/lm.jumptest.R
##estimate theta2 by LSE ##function name LSE1 lse <- function(yuima, start, lower, upper, method="BFGS", ...){ call <- match.call() if( missing(yuima)) yuima.stop("yuima object is missing.") ## param handling ## FIXME: maybe we should choose initial values at random within lower/upper ## at present, qmle stops if( missing(start) ) yuima.stop("Starting values for the parameters are missing.") diff.par <- yuima@model@parameter@diffusion drift.par <- yuima@model@parameter@drift jump.par <- yuima@model@parameter@jump measure.par <- yuima@model@parameter@measure common.par <- yuima@model@parameter@common fullcoef <- c(diff.par, drift.par) npar <- length(fullcoef) nm <- names(start) oo <- match(nm, fullcoef) if(any(is.na(oo))) yuima.stop("some named arguments in 'start' are not arguments to the supplied yuima model") start <- start[order(oo)] nm <- names(start) idx.diff <- match(diff.par, nm) idx.drift <- match(drift.par, nm) tmplower <- as.list( rep( -Inf, length(nm))) names(tmplower) <- nm if(!missing(lower)){ idx <- match(names(lower), names(tmplower)) if(any(is.na(idx))) yuima.stop("names in 'lower' do not match names fo parameters") tmplower[ idx ] <- lower } lower <- tmplower tmpupper <- as.list( rep( Inf, length(nm))) names(tmpupper) <- nm if(!missing(upper)){ idx <- match(names(upper), names(tmpupper)) if(any(is.na(idx))) yuima.stop("names in 'lower' do not match names fo parameters") tmpupper[ idx ] <- upper } upper <- tmpupper d.size <- yuima@[email protected] n <- length(yuima)[1] env <- new.env() assign("X", as.matrix(onezoo(yuima)), envir=env) assign("deltaX", matrix(0, n-1, d.size), envir=env) for(t in 1:(n-1)) env$deltaX[t,] <- env$X[t+1,] - env$X[t,] assign("h", deltat(yuima@[email protected][[1]]), envir=env) ##objective function f <-function(theta){ names(theta) <- drift.par tmp <- env$deltaX - env$h * drift.term(yuima, theta, env)[-n,] ret <- t(tmp) %*% tmp return(sum(ret)) } mydots <- as.list(call)[-(1:2)] mydots$fixed <- NULL mydots$fn <- as.name("f") mydots$start <- NULL mydots$par <- unlist(start) mydots$hessian <- FALSE mydots$upper <- unlist( upper[ nm[idx.diff] ]) mydots$lower <- unlist( lower[ nm[idx.diff] ]) if(length(start)>1){ #multidimensional optim oout <- do.call(optim, args=mydots) } else { ### one dimensional optim mydots$f <- mydots$fn mydots$fn <- NULL mydots$par <- NULL mydots$hessian <- NULL mydots$method <- NULL mydots$interval <- as.numeric(c(lower[drift.par],upper[drift.par])) mydots$lower <- NULL mydots$upper <- NULL opt1 <- do.call(optimize, args=mydots) #opt1 <- optimize(f, ...) ## an interval should be provided oout <- list(par = opt1$minimum, value = opt1$objective) } return(oout$par) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/lse.R
##::quasi-bayes function #new minusquasilogl "W1","W2" like lse function. setGeneric("lseBayes", function(yuima, start,prior,lower,upper, method="mcmc",mcmc=1000,rate=1.0,algorithm="randomwalk") standardGeneric("lseBayes") ) setMethod("lseBayes", "yuima", function(yuima, start,prior,lower,upper, method="mcmc",mcmc=1000,rate=1.0,algorithm="randomwalk") { rcpp <- TRUE joint <- FALSE fixed <- numeric(0) print <- FALSE call <- match.call() if( missing(yuima)) yuima.stop("yuima object is missing.") ## param handling ## FIXME: maybe we should choose initial values at random within lower/upper ## at present, qmle stops if(missing(lower) || missing(upper)){ yuima.stop("lower or upper is missing.") } diff.par <- yuima@model@parameter@diffusion drift.par <- yuima@model@parameter@drift jump.par <- yuima@model@parameter@jump measure.par <- yuima@model@parameter@measure common.par <- yuima@model@parameter@common ## BEGIN Prior construction if(!missing(prior)){ priorLower = numeric(0) priorUpper = numeric(0) pdlist <- numeric(length(yuima@model@parameter@all)) names(pdlist) <- yuima@model@parameter@all for(i in 1: length(pdlist)){ if(prior[[names(pdlist)[i]]]$measure.type=="code"){ expr <- prior[[names(pdlist)[i]]]$df code <- suppressWarnings(sub("^(.+?)\\(.+", "\\1", expr, perl=TRUE)) args <- unlist(strsplit(suppressWarnings(sub("^.+?\\((.+)\\)", "\\1", expr, perl=TRUE)), ",")) pdlist[i] <- switch(code, dunif=paste("function(z){return(dunif(z, ", args[2], ", ", args[3],"))}"), dnorm=paste("function(z){return(dnorm(z,", args[2], ", ", args[3], "))}"), dbeta=paste("function(z){return(dbeta(z, ", args[2], ", ", args[3], "))}"), dgamma=paste("function(z){return(dgamma(z, ", args[2], ", ", args[3], "))}"), dexp=paste("function(z){return(dexp(z, ", args[2], "))}") ) qf <- switch(code, dunif=paste("function(z){return(qunif(z, ", args[2], ", ", args[3],"))}"), dnorm=paste("function(z){return(qnorm(z,", args[2], ", ", args[3], "))}"), dbeta=paste("function(z){return(qbeta(z, ", args[2], ", ", args[3], "))}"), dgamma=paste("function(z){return(qgamma(z, ", args[2], ", ", args[3], "))}"), dexp=paste("function(z){return(qexp(z, ", args[2], "))}") ) priorLower = append(priorLower,eval(parse("text"=qf))(0.00)) priorUpper = append(priorUpper,eval(parse("text"=qf))(1.00)) } } if(sum(unlist(lower)<priorLower) + sum(unlist(upper)>priorUpper) > 0){ yuima.stop("lower&upper of prior are out of parameter space.") } names(lower) <- names(pdlist) names(upper) <- names(pdlist) pd <- function(param){ value <- 1 for(i in 1:length(pdlist)){ value <- value*eval(parse(text=pdlist[[i]]))(param[[i]]) } return(value) } }else{ pd <- function(param) return(1) } ## END Prior construction JointOptim <- joint if(length(common.par)>0){ JointOptim <- TRUE yuima.warn("Drift and diffusion parameters must be different. Doing joint estimation, asymptotic theory may not hold true.") } if(length(jump.par)+length(measure.par)>0) yuima.stop("Cannot estimate the jump models, yet") fullcoef <- NULL if(length(diff.par)>0) fullcoef <- diff.par if(length(drift.par)>0) fullcoef <- c(fullcoef, drift.par) npar <- length(fullcoef) fixed.par <- names(fixed) if (any(!(fixed.par %in% fullcoef))) yuima.stop("Some named arguments in 'fixed' are not arguments to the supplied yuima model") nm <- names(start) oo <- match(nm, fullcoef) if(any(is.na(oo))) yuima.stop("some named arguments in 'start' are not arguments to the supplied yuima model") start <- start[order(oo)] if(!missing(prior)){ pdlist <- pdlist[order(oo)] } nm <- names(start) idx.diff <- match(diff.par, nm) idx.drift <- match(drift.par, nm) idx.fixed <- match(fixed.par, nm) tmplower <- as.list( rep( -Inf, length(nm))) names(tmplower) <- nm if(!missing(lower)){ idx <- match(names(lower), names(tmplower)) if(any(is.na(idx))) yuima.stop("names in 'lower' do not match names fo parameters") tmplower[ idx ] <- lower } lower <- tmplower tmpupper <- as.list( rep( Inf, length(nm))) names(tmpupper) <- nm if(!missing(upper)){ idx <- match(names(upper), names(tmpupper)) if(any(is.na(idx))) yuima.stop("names in 'lower' do not match names fo parameters") tmpupper[ idx ] <- upper } upper <- tmpupper d.size <- yuima@[email protected] n <- length(yuima)[1] G <- rate if(G<=0 || G>1){ yuima.stop("rate G should be 0 < G <= 1") } n_0 <- floor(n^G) if(n_0 < 2) n_0 <- 2 #######data is reduced to n_0 before qmle(16/11/2016) env <- new.env() #assign("X", yuima@[email protected][1:n_0,], envir=env) assign("X", as.matrix(onezoo(yuima)[1:n_0,]), envir=env) assign("deltaX", matrix(0, n_0 - 1, d.size), envir=env) assign("crossdx",matrix(0,n_0 - 1,d.size*d.size),envir=env) ####(deltaX)%*%t(deltaX).this is used in W1. assign("time", as.numeric(index(yuima@[email protected][[1]])), envir=env) assign("Cn.r", rep(1,n_0 - 1), envir=env) for(t in 1:(n_0 - 1)){ env$deltaX[t,] <- env$X[t+1,] - env$X[t,] env$crossdx[t,] <- as.vector(tcrossprod(env$deltaX[t,])) } assign("h", deltat(yuima@[email protected][[1]]), envir=env) pp<-0 while(1){ if(n*env$h^pp < 0.1) break pp <- pp + 1 } qq <- max(pp,2/G) C.temper.diff <- n_0^(2/(qq*G)-1) #this is used in pg. C.temper.drift <- (n_0*env$h)^(2/(qq*G)-1) #this is used in pg. mle <- qmle(yuima, "start"=start, "lower"=lower,"upper"=upper, "method"="L-BFGS-B",rcpp=rcpp) start <- as.list(mle@coef) integ <- function(idx.fixed=NULL,f=f,start=start,par=NULL,hessian=FALSE,upper,lower){ if(length(idx.fixed)==0){ intf <- adaptIntegrate(f,lowerLimit=lower,upperLimit=upper,fDim=(length(upper)+1))$integral }else{ intf <- adaptIntegrate(f,lowerLimit=lower[-idx.fixed],upperLimit=upper[-idx.fixed],fDim=(length(upper[-idx.fixed])+1))$integral } return(intf[-1]/intf[1]) } mcinteg <- function(idx.fixed=NULL,f=f,p,start=start,par=NULL,hessian=FALSE,upper,lower,mean,vcov,mcmc){ if(length(idx.fixed)==0){ intf <- mcIntegrate(f,p,lowerLimit=lower,upperLimit=upper,mean,vcov,mcmc) }else{ intf <- mcIntegrate(f,p,lowerLimit=lower[-idx.fixed],upperLimit=upper[-idx.fixed],mean[-idx.fixed],vcov[-idx.fixed,-idx.fixed],mcmc) } return(intf) } mcIntegrate <- function(f,p, lowerLimit, upperLimit,mean,vcov,mcmc){ if(algorithm=="randomwalk"){ x_c <- mean p_c <- p(mean) val <- f(x_c) if(length(mean)>1){ x <- rmvnorm(mcmc-1,mean,vcov) q <- dmvnorm(x,mean,vcov) q_c <- dmvnorm(mean,mean,vcov) }else{ x <- rnorm(mcmc-1,mean,sqrt(vcov)) q <- dnorm(x,mean,sqrt(vcov)) q_c <- dnorm(mean,mean,sqrt(vcov)) } for(i in 1:(mcmc-1)){ if(length(mean)>1){x_n <- x[i,]}else{x_n <- x[i]} if(sum(x_n<lowerLimit)==0 & sum(x_n>upperLimit)==0){ q_n <- q[i] p_n <- p(x_n) #u <- runif(1) #a <- (p_n*q_c)/(p_c*q_n) u <- log(runif(1)) a <- p_n-p_c+log(q_c/q_n) if(u<a){ p_c <- p_n q_c <- q_n x_c <- x_n } } val <- val+f(x_c) } return(unlist(val/mcmc)) } else if(tolower(algorithm)=="mpcn"){ #MpCN x_n <- mean val <- mean logLik_old <- p(x_n)+0.5*length(mean)*log(sqnorm(x_n-mean)) for(i in 1:(mcmc-1)){ prop <- makeprop(mean,x_n,unlist(lowerLimit),unlist(upperLimit)) logLik_new <- p(prop)+0.5*length(mean)*log(sqnorm(prop-mean)) u <- log(runif(1)) if( logLik_new-logLik_old > u){ nx_ <- prop logLik_old <- logLik_new } val <- val+f(x_n) } return(unlist(val/mcmc)) } } #print(mle@coef) flagNotPosDif <- 0 for(i in 1:npar){ if(mle@vcov[i,i] <= 0) flagNotPosDif <- 1 #Check mle@vcov is positive difinite matrix } if(flagNotPosDif == 1){ mle@vcov <- diag(c(rep(1 / n_0,length(diff.par)),rep(1 / (n_0 * env$h),length(drift.par)))) # Redifine mle@vcov } tmpW1 <- minusquasilogl_W1(yuima=yuima, param=mle@coef, print=print, env,rcpp=rcpp) tmpW2 <- minusquasilogl_W2(yuima=yuima, param=mle@coef, print=print, env,rcpp=rcpp) g <- function(p,fixed,idx.fixed){ mycoef <- mle@coef if(length(idx.fixed)>0){ mycoef[-idx.fixed] <- p mycoef[idx.fixed] <- fixed }else{ names(mycoef) <- nm } if(sum(idx.diff==idx.fixed)>0){ return(c(1,p)*exp(-minusquasilogl_W1(yuima=yuima, param=mycoef, print=print, env,rcpp=rcpp)+tmpW1)*pd(param=mycoef)) }else{ return(c(1,p)*exp(-minusquasilogl_W2(yuima=yuima, param=mycoef, print=print, env,rcpp=rcpp)+tmpW2)*pd(param=mycoef)) } } pg <- function(p,fixed,idx.fixed){ mycoef <- start if(length(idx.fixed)>0){ mycoef[-idx.fixed] <- p mycoef[idx.fixed] <- fixed }else{ names(mycoef) <- nm } if(sum(idx.diff==idx.fixed)>0){ return(C.temper.diff*(-minusquasilogl_W1(yuima=yuima, param=mycoef, print=print, env,rcpp=rcpp)+tmpW1+log(pd(param=mycoef))))#log }else{ return(C.temper.drift*(-minusquasilogl_W2(yuima=yuima, param=mycoef, print=print, env,rcpp=rcpp)+tmpW2+log(pd(param=mycoef))))#log } } idf <- function(p){return(p)} # fj <- function(p) { # mycoef <- as.list(p) # names(mycoef) <- nm # mycoef[fixed.par] <- fixed # minusquasilogl(yuima=yuima, param=mycoef, print=print, env) # } oout <- NULL HESS <- matrix(0, length(nm), length(nm)) colnames(HESS) <- nm rownames(HESS) <- nm HaveDriftHess <- FALSE HaveDiffHess <- FALSE if(length(start)){ # if(JointOptim){ ### joint optimization # if(length(start)>1){ #multidimensional optim # oout <- optim(start, fj, method = method, hessian = TRUE, lower=lower, upper=upper) # HESS <- oout$hessian # HaveDriftHess <- TRUE # HaveDiffHess <- TRUE # } else { ### one dimensional optim # opt1 <- optimize(f, ...) ## an interval should be provided # opt1 <- list(par=integ(f=f,upper=upper,lower=lower,fDim=length(lower)+1),objective=0) # oout <- list(par = opt1$minimum, value = opt1$objective) # } ### endif( length(start)>1 ) # } else { ### first diffusion, then drift theta1 <- NULL old.fixed <- fixed old.start <- start if(length(idx.diff)>0){ ## DIFFUSION ESTIMATIOn first old.fixed <- fixed old.start <- start new.start <- start[idx.diff] # considering only initial guess for diffusion new.fixed <- fixed if(length(idx.drift)>0) new.fixed[nm[idx.drift]] <- start[idx.drift] fixed <- new.fixed fixed.par <- names(fixed) idx.fixed <- match(fixed.par, nm) names(new.start) <- nm[idx.diff] mydots <- as.list(call)[-(1:2)] mydots$fixed <- NULL mydots$fn <- as.name("f") mydots$start <- NULL mydots$par <- unlist(new.start) mydots$hessian <- FALSE mydots$upper <- unlist( upper[ nm[idx.diff] ]) mydots$lower <- unlist( lower[ nm[idx.diff] ]) f <- function(p){return(g(p,fixed,idx.fixed))} pf <- function(p){return(pg(p,fixed,idx.fixed))} if(length(mydots$par)>1){ # oout <- do.call(optim, args=mydots) if(method=="mcmc"){ oout <- list(par=mcinteg(idx.fixed=idx.fixed,f=idf,p=pf,upper=upper,lower=lower,mean=mle@coef,vcov=diag(diag(mle@vcov)),mcmc=mcmc)) }else{ oout <- list(par=integ(idx.fixed=idx.fixed,f=f,upper=upper,lower=lower,start=start)) } } else { mydots$f <- mydots$fn mydots$fn <- NULL mydots$par <- NULL mydots$hessian <- NULL mydots$method <- NULL mydots$interval <- as.numeric(c(unlist(lower[diff.par]),unlist(upper[diff.par]))) mydots$lower <- NULL mydots$upper <- NULL # opt1 <- do.call(optimize, args=mydots) if(method=="mcmc"){ opt1 <- list(minimum=mcinteg(idx.fixed=idx.fixed,f=idf,p=pf,upper=upper,lower=lower,mean=mle@coef,vcov=diag(diag(mle@vcov)),mcmc=mcmc)) }else{ opt1 <- list(minimum=integ(idx.fixed=idx.fixed,f=f,upper=upper,lower=lower)) } theta1 <- opt1$minimum names(theta1) <- diff.par # oout <- list(par = theta1, value = opt1$objective) oout <- list(par=theta1,value=0) } theta1 <- oout$par #names(theta1) <- nm[idx.diff] names(theta1) <- diff.par } ## endif(length(idx.diff)>0) theta2 <- NULL if(length(idx.drift)>0){ ## DRIFT estimation with first state diffusion estimates fixed <- old.fixed start <- old.start new.start <- start[idx.drift] # considering only initial guess for drift new.fixed <- fixed new.fixed[names(theta1)] <- theta1 fixed <- new.fixed fixed.par <- names(fixed) idx.fixed <- match(fixed.par, nm) names(new.start) <- nm[idx.drift] mydots <- as.list(call)[-(1:2)] mydots$fixed <- NULL mydots$fn <- as.name("f") mydots$start <- NULL mydots$par <- unlist(new.start) mydots$hessian <- FALSE mydots$upper <- unlist( upper[ nm[idx.drift] ]) mydots$lower <- unlist( lower[ nm[idx.drift] ]) f <- function(p){return(g(p,fixed,idx.fixed))} pf <- function(p){return(pg(p,fixed,idx.fixed))} if(length(mydots$par)>1){ # oout1 <- do.call(optim, args=mydots) if(method=="mcmc"){ oout1 <- list(par=mcinteg(idx.fixed=idx.fixed,f=idf,p=pf,upper=upper,lower=lower,mean=mle@coef,vcov=diag(diag(mle@vcov)),mcmc=mcmc)) }else{ oout1 <- list(par=integ(idx.fixed=idx.fixed,f=f,upper=upper,lower=lower)) } } else { mydots$f <- mydots$fn mydots$fn <- NULL mydots$par <- NULL mydots$hessian <- NULL mydots$method <- NULL mydots$interval <- as.numeric(c(lower[drift.par],upper[drift.par])) # opt1 <- do.call(optimize, args=mydots) if(method=="mcmc"){ opt1 <- list(minimum=mcinteg(idx.fixed=idx.fixed,f=idf,p=pf,upper=upper,lower=lower,mean=mle@coef,vcov=diag(diag(mle@vcov)),mcmc=mcmc)) }else{ opt1 <- list(minimum=integ(idx.fixed=idx.fixed,f=f,upper=upper,lower=lower)) } theta2 <- opt1$minimum names(theta2) <- drift.par oout1 <- list(par = theta2, value = as.numeric(opt1$objective)) } theta2 <- oout1$par } ## endif(length(idx.drift)>0) oout1 <- list(par= c(theta1, theta2)) names(oout1$par) <- c(diff.par,drift.par) oout <- oout1 # } ### endif JointOptim } else { list(par = numeric(0L), value = f(start)) } fDrift <- function(p) { mycoef <- as.list(p) names(mycoef) <- drift.par mycoef[diff.par] <- coef[diff.par] minusquasilogl(yuima=yuima, param=mycoef, print=print, env,rcpp=rcpp) } fDiff <- function(p) { mycoef <- as.list(p) names(mycoef) <- diff.par mycoef[drift.par] <- coef[drift.par] minusquasilogl(yuima=yuima, param=mycoef, print=print, env,rcpp=rcpp) } coef <- oout$par control=list() par <- coef names(par) <- c(diff.par, drift.par) nm <- c(diff.par, drift.par) # print(par) # print(coef) conDrift <- list(trace = 5, fnscale = 1, parscale = rep.int(5, length(drift.par)), ndeps = rep.int(0.001, length(drift.par)), maxit = 100L, abstol = -Inf, reltol = sqrt(.Machine$double.eps), alpha = 1, beta = 0.5, gamma = 2, REPORT = 10, type = 1, lmm = 5, factr = 1e+07, pgtol = 0, tmax = 10, temp = 10) conDiff <- list(trace = 5, fnscale = 1, parscale = rep.int(5, length(diff.par)), ndeps = rep.int(0.001, length(diff.par)), maxit = 100L, abstol = -Inf, reltol = sqrt(.Machine$double.eps), alpha = 1, beta = 0.5, gamma = 2, REPORT = 10, type = 1, lmm = 5, factr = 1e+07, pgtol = 0, tmax = 10, temp = 10) # nmsC <- names(con) # if (method == "Nelder-Mead") # con$maxit <- 500 # if (method == "SANN") { # con$maxit <- 10000 # con$REPORT <- 100 # } # con[(namc <- names(control))] <- control # if (length(noNms <- namc[!namc %in% nmsC])) # warning("unknown names in control: ", paste(noNms, collapse = ", ")) # if (con$trace < 0) # warning("read the documentation for 'trace' more carefully") # else if (method == "SANN" && con$trace && as.integer(con$REPORT) == # 0) # stop("'trace != 0' needs 'REPORT >= 1'") # if (method == "L-BFGS-B" && any(!is.na(match(c("reltol", # "abstol"), namc)))) # warning("method L-BFGS-B uses 'factr' (and 'pgtol') instead of 'reltol' and 'abstol'") # npar <- length(par) # if (npar == 1 && method == "Nelder-Mead") # warning("one-diml optimization by Nelder-Mead is unreliable: use optimize") # if(!HaveDriftHess & (length(drift.par)>0)){ #hess2 <- .Internal(optimhess(coef[drift.par], fDrift, NULL, conDrift)) hess2 <- optimHess(coef[drift.par], fDrift, NULL, control=conDrift) HESS[drift.par,drift.par] <- hess2 } if(!HaveDiffHess & (length(diff.par)>0)){ #hess1 <- .Internal(optimhess(coef[diff.par], fDiff, NULL, conDiff)) hess1 <- optimHess(coef[diff.par], fDiff, NULL, control=conDiff) HESS[diff.par,diff.par] <- hess1 } oout$hessian <- HESS vcov <- if (length(coef)) solve(oout$hessian) else matrix(numeric(0L), 0L, 0L) mycoef <- as.list(coef) names(mycoef) <- nm mycoef[fixed.par] <- fixed min <- minusquasilogl(yuima=yuima, param=mycoef, print=print, env,rcpp=rcpp) new("mle", call = call, coef = coef, fullcoef = unlist(mycoef), # vcov = vcov, min = min, details = oout, minuslogl = minusquasilogl, vcov = vcov, details = oout, method = method) } ) minusquasilogl_W1 <- function(yuima, param, print=FALSE, env,rcpp=T){ #new logl estimates volatility diff.par <- yuima@model@parameter@diffusion drift.par <- yuima@model@parameter@drift if(0){ if(length(yuima@model@[email protected])!=0){ xinit.par <- yuima@model@parameter@xinit } } if(0 && length(yuima@model@[email protected])==0 && length(yuima@model@parameter@jump)!=0){ diff.par<-yuima@model@parameter@jump # measure.par<-yuima@model@parameter@measure } if(0 && length(yuima@model@[email protected])==0 && length(yuima@model@parameter@measure)!=0){ measure.par<-yuima@model@parameter@measure } # 24/12 if(0 && length(yuima@model@[email protected])>0 ){ yuima.warn("carma(p,q): the case of lin.par will be implemented as soon as") return(NULL) } if(0){ xinit.par <- yuima@model@parameter@xinit } drift.par <- yuima@model@parameter@drift fullcoef <- NULL if(length(diff.par)>0) fullcoef <- diff.par if(length(drift.par)>0) fullcoef <- c(fullcoef, drift.par) if(0){ if(length(xinit.par)>0) fullcoef <- c(fullcoef, xinit.par) } if(0 && (length(yuima@model@parameter@measure)!=0)) fullcoef<-c(fullcoef, measure.par) if(0){ if("mean.noise" %in% names(param)){ mean.noise<-"mean.noise" fullcoef <- c(fullcoef, mean.noise) NoNeg.Noise<-TRUE } } npar <- length(fullcoef) nm <- names(param) oo <- match(nm, fullcoef) if(any(is.na(oo))) yuima.stop("some named arguments in 'param' are not arguments to the supplied yuima model") param <- param[order(oo)] nm <- names(param) idx.diff <- match(diff.par, nm) idx.drift <- match(drift.par, nm) if(0){ idx.xinit <-as.integer(na.omit(match(xinit.par, nm))) } h <- env$h Cn.r <- env$Cn.r theta1 <- unlist(param[idx.diff]) theta2 <- unlist(param[idx.drift]) n.theta1 <- length(theta1) n.theta2 <- length(theta2) n.theta <- n.theta1+n.theta2 if(0){ theta3 <- unlist(param[idx.xinit]) n.theta3 <- length(theta3) n.theta <- n.theta1+n.theta2+n.theta3 } d.size <- yuima@[email protected] n <- length(yuima)[1] if (0){ # 24/12 d.size <-1 # We build the two step procedure as described in # if(length(yuima@model@[email protected])!=0){ prova<-as.numeric(param) #names(prova)<-fullcoef[oo] names(prova)<-names(param) param<-prova[c(length(prova):1)] time.obs<-env$time.obs y<-as.numeric(env$X) u<-env$h p<-env$p q<-env$q # p<-yuima@model@info@p ar.par <- yuima@model@[email protected] name.ar<-paste0(ar.par, c(1:p)) # q <- yuima@model@info@q ma.par <- yuima@model@[email protected] name.ma<-paste0(ma.par, c(0:q)) if (length(yuima@model@[email protected])==0){ a<-param[name.ar] # a_names<-names(param[c(1:p)]) # names(a)<-a_names b<-param[name.ma] # b_names<-names(param[c((p+1):(length(param)-p+1))]) # names(b)<-b_names if(length(yuima@model@[email protected])!=0){ if(length(b)==1){ b<-1 } else{ indx_b0<-paste0(yuima@model@[email protected],"0",collapse="") b[indx_b0]<-1 } sigma<-tail(param,1) }else {sigma<-1} NoNeg.Noise<-FALSE if(0){ if("mean.noise" %in% names(param)){ NoNeg.Noise<-TRUE } } if(NoNeg.Noise==TRUE){ if (length(b)==p){ #mean.noise<-param[mean.noise] # Be useful for carma driven by a no negative levy process mean.y<-mean(y) #mean.y<-mean.noise*tail(b,n=1)/tail(a,n=1)*sigma #param[mean.noise]<-mean.y/(tail(b,n=1)/tail(a,n=1)*sigma) }else{ mean.y<-0 } y<-y-mean.y } # V_inf0<-matrix(diag(rep(1,p)),p,p) V_inf0<-env$V_inf0 p<-env$p q<-env$q strLog<-yuima.carma.loglik1(y, u, a, b, sigma,time.obs,V_inf0,p,q) }else if (!rcpp){ # 01/01 # ar.par <- yuima@model@[email protected] # name.ar<-paste0(ar.par, c(1:p)) a<-param[name.ar] # ma.par <- yuima@model@[email protected] # q <- yuima@model@info@q name.ma<-paste0(ma.par, c(0:q)) b<-param[name.ma] if(length(yuima@model@[email protected])!=0){ if(length(b)==1){ b<-1 } else{ indx_b0<-paste0(yuima@model@[email protected],"0",collapse="") b[indx_b0]<-1 } scale.par <- yuima@model@[email protected] sigma <- param[scale.par] } else{sigma <- 1} loc.par <- yuima@model@[email protected] mu <- param[loc.par] NoNeg.Noise<-FALSE if(0){ if("mean.noise" %in% names(param)){ NoNeg.Noise<-TRUE } } # Lines 883:840 work if we have a no negative noise if(0&&(NoNeg.Noise==TRUE)){ if (length(b)==p){ mean.noise<-param[mean.noise] # Be useful for carma driven by levy process # mean.y<-mean.noise*tail(b,n=1)/tail(a,n=1)*sigma mean.y<-mean(y-mu) }else{ mean.y<-0 } y<-y-mean.y } y.start <- y-mu #V_inf0<-matrix(diag(rep(1,p)),p,p) V_inf0<-env$V_inf0 p<-env$p q<-env$q strLog<-yuima.carma.loglik1(y.start, u, a, b, sigma,time.obs,V_inf0,p,q) } QL<-strLog$loglikCdiag # }else { # yuima.warn("carma(p,q): the scale parameter is equal to 1. We will implemented as soon as possible") # return(NULL) # } } else { drift_name <- yuima@model@drift diffusion_name <- yuima@model@diffusion ####data <- yuima@[email protected] data <- env$X thetadim <- length(yuima@model@parameter@all) noise_number <- yuima@[email protected] assign(yuima@[email protected],env$time[-length(env$time)]) for(i in 1:d.size) assign(yuima@[email protected][i], data[-length(data[,1]),i]) for(i in 1:thetadim) assign(names(param)[i], param[[i]]) d_b <- NULL for(i in 1:d.size){ if(length(eval(drift_name[[i]]))==(length(data[,1])-1)){ d_b[[i]] <- drift_name[[i]] #this part of model includes "x"(state.variable) } else{ if(is.na(c(drift_name[[i]][2]))){ #ex. yuima@model@drift=expression(0) (we hope "expression((0))") drift_name[[i]] <- parse(text=paste(sprintf("(%s)", drift_name[[i]])))[[1]] } d_b[[i]] <- parse(text=paste("(",drift_name[[i]][2],")*rep(1,length(data[,1])-1)",sep="")) #vectorization } } v_a<-matrix(list(NULL),d.size,noise_number) for(i in 1:d.size){ for(j in 1:noise_number){ if(length(eval(diffusion_name[[i]][[j]]))==(length(data[,1])-1)){ v_a[[i,j]] <- diffusion_name[[i]][[j]] #this part of model includes "x"(state.variable) } else{ if(is.na(c(diffusion_name[[i]][[j]][2]))){ diffusion_name[[i]][[j]] <- parse(text=paste(sprintf("(%s)", diffusion_name[[i]][[j]])))[[1]] } v_a[[i,j]] <- parse(text=paste("(",diffusion_name[[i]][[j]][2],")*rep(1,length(data[,1])-1)",sep="")) #vectorization } } } dx_set <- as.matrix((data-rbind(numeric(d.size),as.matrix(data[-length(data[,1]),])))[-1,]) crossdx_set <- env$crossdx drift_set <- diffusion_set <- NULL #for(i in 1:thetadim) assign(names(param)[i], param[[i]]) for(i in 1:d.size) drift_set <- cbind(drift_set,eval(d_b[[i]])) for(i in 1:noise_number){ for(j in 1:d.size) diffusion_set <- cbind(diffusion_set,eval(v_a[[j,i]])) } QL <- W1(crossdx_set,drift_set,diffusion_set,env$h)*(-0.5*env$h*env$h) } if(!is.finite(QL)){ yuima.warn("quasi likelihood is too small to calculate.") return(1e10) } if(print==TRUE){ yuima.warn(sprintf("NEG-QL: %f, %s", -QL, paste(names(param),param,sep="=",collapse=", "))) } if(is.infinite(QL)) return(1e10) return(as.numeric(-QL)) } minusquasilogl_W2 <- function(yuima, param, print=FALSE, env,rcpp=T){#new logl estimates drift diff.par <- yuima@model@parameter@diffusion drift.par <- yuima@model@parameter@drift if(0){ if(length(yuima@model@[email protected])!=0){ xinit.par <- yuima@model@parameter@xinit } } if(0 && length(yuima@model@[email protected])==0 && length(yuima@model@parameter@jump)!=0){ diff.par<-yuima@model@parameter@jump # measure.par<-yuima@model@parameter@measure } if(0 && length(yuima@model@[email protected])==0 && length(yuima@model@parameter@measure)!=0){ measure.par<-yuima@model@parameter@measure } # 24/12 if(0 && length(yuima@model@[email protected])>0 ){ yuima.warn("carma(p,q): the case of lin.par will be implemented as soon as") return(NULL) } if(0){ xinit.par <- yuima@model@parameter@xinit } drift.par <- yuima@model@parameter@drift fullcoef <- NULL if(length(diff.par)>0) fullcoef <- diff.par if(length(drift.par)>0) fullcoef <- c(fullcoef, drift.par) if(0){ if(length(xinit.par)>0) fullcoef <- c(fullcoef, xinit.par) } if(0 && (length(yuima@model@parameter@measure)!=0)) fullcoef<-c(fullcoef, measure.par) if(0){ if("mean.noise" %in% names(param)){ mean.noise<-"mean.noise" fullcoef <- c(fullcoef, mean.noise) NoNeg.Noise<-TRUE } } npar <- length(fullcoef) nm <- names(param) oo <- match(nm, fullcoef) if(any(is.na(oo))) yuima.stop("some named arguments in 'param' are not arguments to the supplied yuima model") param <- param[order(oo)] nm <- names(param) idx.diff <- match(diff.par, nm) idx.drift <- match(drift.par, nm) if(0){ idx.xinit <-as.integer(na.omit(match(xinit.par, nm))) } h <- env$h Cn.r <- env$Cn.r theta1 <- unlist(param[idx.diff]) theta2 <- unlist(param[idx.drift]) n.theta1 <- length(theta1) n.theta2 <- length(theta2) n.theta <- n.theta1+n.theta2 if(0){ theta3 <- unlist(param[idx.xinit]) n.theta3 <- length(theta3) n.theta <- n.theta1+n.theta2+n.theta3 } d.size <- yuima@[email protected] n <- length(yuima)[1] if (0){ # 24/12 d.size <-1 # We build the two step procedure as described in # if(length(yuima@model@[email protected])!=0){ prova<-as.numeric(param) #names(prova)<-fullcoef[oo] names(prova)<-names(param) param<-prova[c(length(prova):1)] time.obs<-env$time.obs y<-as.numeric(env$X) u<-env$h p<-env$p q<-env$q # p<-yuima@model@info@p ar.par <- yuima@model@[email protected] name.ar<-paste0(ar.par, c(1:p)) # q <- yuima@model@info@q ma.par <- yuima@model@[email protected] name.ma<-paste0(ma.par, c(0:q)) if (length(yuima@model@[email protected])==0){ a<-param[name.ar] # a_names<-names(param[c(1:p)]) # names(a)<-a_names b<-param[name.ma] # b_names<-names(param[c((p+1):(length(param)-p+1))]) # names(b)<-b_names if(length(yuima@model@[email protected])!=0){ if(length(b)==1){ b<-1 } else{ indx_b0<-paste0(yuima@model@[email protected],"0",collapse="") b[indx_b0]<-1 } sigma<-tail(param,1) }else {sigma<-1} NoNeg.Noise<-FALSE if(0){ if("mean.noise" %in% names(param)){ NoNeg.Noise<-TRUE } } if(NoNeg.Noise==TRUE){ if (length(b)==p){ #mean.noise<-param[mean.noise] # Be useful for carma driven by a no negative levy process mean.y<-mean(y) #mean.y<-mean.noise*tail(b,n=1)/tail(a,n=1)*sigma #param[mean.noise]<-mean.y/(tail(b,n=1)/tail(a,n=1)*sigma) }else{ mean.y<-0 } y<-y-mean.y } # V_inf0<-matrix(diag(rep(1,p)),p,p) V_inf0<-env$V_inf0 p<-env$p q<-env$q strLog<-yuima.carma.loglik1(y, u, a, b, sigma,time.obs,V_inf0,p,q) }else if (!rcpp){ # 01/01 # ar.par <- yuima@model@[email protected] # name.ar<-paste0(ar.par, c(1:p)) a<-param[name.ar] # ma.par <- yuima@model@[email protected] # q <- yuima@model@info@q name.ma<-paste0(ma.par, c(0:q)) b<-param[name.ma] if(length(yuima@model@[email protected])!=0){ if(length(b)==1){ b<-1 } else{ indx_b0<-paste0(yuima@model@[email protected],"0",collapse="") b[indx_b0]<-1 } scale.par <- yuima@model@[email protected] sigma <- param[scale.par] } else{sigma <- 1} loc.par <- yuima@model@[email protected] mu <- param[loc.par] NoNeg.Noise<-FALSE if(0){ if("mean.noise" %in% names(param)){ NoNeg.Noise<-TRUE } } # Lines 883:840 work if we have a no negative noise if(0&&(NoNeg.Noise==TRUE)){ if (length(b)==p){ mean.noise<-param[mean.noise] # Be useful for carma driven by levy process # mean.y<-mean.noise*tail(b,n=1)/tail(a,n=1)*sigma mean.y<-mean(y-mu) }else{ mean.y<-0 } y<-y-mean.y } y.start <- y-mu #V_inf0<-matrix(diag(rep(1,p)),p,p) V_inf0<-env$V_inf0 p<-env$p q<-env$q strLog<-yuima.carma.loglik1(y.start, u, a, b, sigma,time.obs,V_inf0,p,q) } QL<-strLog$loglikCdiag # }else { # yuima.warn("carma(p,q): the scale parameter is equal to 1. We will implemented as soon as possible") # return(NULL) # } } else { drift_name <- yuima@model@drift diffusion_name <- yuima@model@diffusion ####data <- yuima@[email protected] data <- env$X thetadim <- length(yuima@model@parameter@all) noise_number <- yuima@[email protected] assign(yuima@[email protected],env$time[-length(env$time)]) for(i in 1:d.size) assign(yuima@[email protected][i], data[-length(data[,1]),i]) for(i in 1:thetadim) assign(names(param)[i], param[[i]]) d_b <- NULL for(i in 1:d.size){ if(length(eval(drift_name[[i]]))==(length(data[,1])-1)){ d_b[[i]] <- drift_name[[i]] #this part of model includes "x"(state.variable) } else{ if(is.na(c(drift_name[[i]][2]))){ #ex. yuima@model@drift=expression(0) (we hope "expression((0))") drift_name[[i]] <- parse(text=paste(sprintf("(%s)", drift_name[[i]])))[[1]] } d_b[[i]] <- parse(text=paste("(",drift_name[[i]][2],")*rep(1,length(data[,1])-1)",sep="")) #vectorization } } dx_set <- as.matrix((data-rbind(numeric(d.size),as.matrix(data[-length(data[,1]),])))[-1,]) drift_set <- diffusion_set <- NULL for(i in 1:d.size) drift_set <- cbind(drift_set,eval(d_b[[i]])) QL <- W2(dx_set,drift_set,env$h)*(-0.5*env$h) } if(!is.finite(QL)){ yuima.warn("quasi likelihood is too small to calculate.") return(1e10) } if(print==TRUE){ yuima.warn(sprintf("NEG-QL: %f, %s", -QL, paste(names(param),param,sep="=",collapse=", "))) } if(is.infinite(QL)) return(1e10) return(as.numeric(-QL)) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/lseBayes.R
# multiple lead-lag detector mllag <- function(x, from = -Inf, to = Inf, division = FALSE, grid, psd = TRUE, plot = TRUE, alpha = 0.01, fisher = TRUE, bw) { if((is(x) == "yuima")||(is(x) == "yuima.data")||(is(x) == "list")){ x <- llag(x, from = from, to = to, division = division, grid = grid, psd = psd, plot = FALSE, ci = TRUE, alpha = alpha, fisher = fisher, bw = bw) }else if((is(x) != "yuima.llag") && (is(x) != "yuima.mllag")){ cat("mllag: invalid x") return(NULL) } d <- ncol(x$LLR) d.size <- length(x$ccor) CI <- vector(d.size,mode="list") # confidence intervals result <- vector(d.size,mode="list") names(CI) <- names(x$ccor) names(result) <- names(x$ccor) for(i in 1:(d-1)){ for(j in (i+1):d){ num <- d*(i-1) - (i-1)*i/2 + (j-i) G <- time(x$ccor[[num]]) tmp <- x$ccor[[num]] avar.tmp <- x$avar[[num]] if(fisher == TRUE){ z <- atanh(tmp) # the Fisher z transformation of the estimated correlation se.z <- sqrt(avar.tmp)/(1 - tmp^2) c.alpha <- tanh(qnorm(1 - alpha/2) * se.z) idx <- which(abs(tmp) > c.alpha) result[[num]] <- data.frame(lagcce = G[idx], p.values = pchisq(atanh(tmp[idx])^2/se.z[idx]^2, df=1, lower.tail=FALSE), correlation = tmp[idx]) }else{ c.alpha <- sqrt(qchisq(alpha, df=1, lower.tail=FALSE) * avar.tmp) idx <- which(abs(tmp) > c.alpha) result[[num]] <- data.frame(lagcce = G[idx], p.value = pchisq(tmp[idx]^2/avar.tmp[idx], df=1, lower.tail=FALSE), correlation = tmp[idx]) } CI[[num]] <- zoo(c.alpha, G) } } if(plot){ for(i in 1:(d-1)){ for(j in (i+1):d){ num <- d*(i-1) - (i-1)*i/2 + (j-i) y.max <- max(abs(as.numeric(x$ccor[[num]])),as.numeric(CI[[num]])) plot(x$ccor[[num]], main=paste(i,"vs",j,"(positive",expression(theta),"means",i,"leads",j,")"), xlab=expression(theta),ylab=expression(U(theta)), ylim=c(-y.max,y.max)) lines(CI[[num]],lty=2,col="blue") lines(-CI[[num]],lty=2,col="blue") points(result[[num]]$lagcce, result[[num]]$correlation, col = "red", pch = 19) } } } out <- list(mlagcce = result, LLR = x$LLR, ccor = x$ccor, avar = x$avar, CI = CI) class(out) <- "yuima.mllag" return(out) } # print method for yuima.mllag-class print.yuima.mllag <- function(x, ...){ cat("Estimated lead-lag parameters\n") print(x$mlagcce, ...) cat("Lead-lag ratio\n") print(x$LLR, ...) } # plot method for yuima.mllag-class plot.yuima.mllag <- function(x, alpha = 0.01, fisher = TRUE, ...){ d <- nrow(x$LLR) for(i in 1:(d-1)){ for(j in (i+1):d){ num <- d*(i-1) - (i-1)*i/2 + (j-i) G <- time(x$ccor[[num]]) if(fisher == TRUE){ z <- atanh(x$ccor[[num]]) # the Fisher z transformation of the estimated correlation se.z <- sqrt(x$avar[[num]])/(1 - x$ccor[[num]]^2) CI <- zoo(tanh(qnorm(1 - alpha/2) * se.z), G) }else{ c.alpha <- sqrt(qchisq(alpha, df=1, lower.tail = FALSE) * x$avar[[num]]) CI <- zoo(c.alpha, G) } y.max <- max(abs(as.numeric(x$ccor[[num]])),as.numeric(CI)) plot(x$ccor[[num]], main=paste(i,"vs",j,"(positive",expression(theta),"means",i,"leads",j,")"), xlab=expression(theta),ylab=expression(U(theta)), ylim=c(-y.max,y.max)) lines(CI,lty=2,col="blue") lines(-CI,lty=2,col="blue") points(x$result[[num]]$lagcce, x$result[[num]]$correlation, col = "red", pch = 19) } } }
/scratch/gouwar.j/cran-all/cranData/yuima/R/mllag.R
##estimate theta2 by LSE mmfrac <- function(yuima,...){ call <- match.call() if(missing(yuima)){ yuima.stop("yuima object is missing.") } #if(class(yuima)!="yuima"){ if(!inherits(yuima,"yuima")){ yuima.stop("an object of class yuima is needed.") } Ddiffx0 <- D(yuima@model@diffusion[[1]],yuima@[email protected]) == 0 Ddifft0 <- D(yuima@model@diffusion[[1]],yuima@[email protected]) == 0 bconst<-FALSE Hconst<-FALSE diffnoparam<-length(yuima@model@parameter@diffusion)==0 if (Ddiffx0 & Ddifft0 & diffnoparam){ if(eval(yuima@model@diffusion[[1]])==0){ yuima.stop("the model has no fractional part.") } } if (length(yuima@model@parameter@drift)!=1){ yuima.stop("the drift is malformed.") } dx <- D(yuima@model@drift,yuima@[email protected]) dbx <- D(yuima@model@diffusion[[1]],yuima@[email protected])==0 dbt <- D(yuima@model@diffusion[[1]],yuima@[email protected])==0 bxx <- D(dx,yuima@[email protected])==0 bmix <- D(dx,yuima@[email protected])==0 isfOU <- (bxx || bmix) && (dbx && dbt) if (!isfOU){yuima.stop("estimation not available for this model")} process<-yuima@[email protected][[1]] T<-yuima@sampling@Terminal est<-qgv(yuima,...) H<-est$coeff[1] sigma<-est$coeff[2] if ((!is.na(H))&(!is.na(sigma))){ theta<-(2*mean(process^2)/(sigma^2*gamma(2*H+1)))^(-1/2/H) sH<-sqrt((4*H-1)*(1+(gamma(1-4*H)*gamma(4*H-1))/(gamma(2-2*H)*gamma(2*H)))) sdtheta<- sqrt(theta)*(sH/(2*H))/sqrt(T) }else{ yuima.warn("Diffusion estimation not available, can not estimate the drift parameter") } x<-c(est$coeff,theta) names(x)<-c(names(est$coeff),yuima@model@parameter@drift) sdx<-matrix(,3,3) diag(sdx)<-c(diag(est$vcov),sdtheta) colnames(sdx)<-names(x) rownames(sdx)<-names(x) obj <- list(coefficients=x,vcov=sdx,call=call) class(obj) <- "mmfrac" return(obj) } print.mmfrac<-function(x,...){ tmp <- rbind(x$coefficients, diag(x$vcov)) rownames(tmp) <- c("Estimate", "Std. Error") cat("\nFractional OU estimation\n") print(tmp) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/mmfrac.R
######################################################################### # Realized multipower variation ######################################################################### setGeneric("mpv",function(yuima,r=2,normalize=TRUE)standardGeneric("mpv")) setMethod("mpv",signature(yuima="yuima"), function(yuima,r=2,normalize=TRUE)mpv(yuima@data,r,normalize)) setMethod("mpv",signature(yuima="yuima.data"), function(yuima,r=2,normalize=TRUE){ data <- get.zoo.data(yuima) d.size <- length(data) result <- double(d.size) if(is.numeric(r)){ for(d in 1:d.size){ X <- as.numeric(data[[d]]) idt <- which(is.na(X)) if(length(idt>0)){ X <- X[-idt] } if(length(X)<2) { stop("length of data (w/o NA) must be more than 1") } abs.diffX <- abs(diff(X)) tmp <- rollapplyr(abs.diffX,length(r),FUN=function(x)prod(x^r)) result[d] <- length(abs.diffX)^(sum(r)/2-1)*sum(tmp) } if(normalize){ result <- result/prod(2^(r/2)*gamma((r+1)/2)/gamma(1/2)) } }else{ for(d in 1:d.size){ X <- as.numeric(data[[d]]) idt <- which(is.na(X)) if(length(idt>0)){ X <- X[-idt] } if(length(X)<2) { stop("length of data (w/o NA) must be more than 1") } abs.diffX <- abs(diff(X)) tmp <- rollapplyr(abs.diffX,length(r[[d]]),FUN=function(x)prod(x^r[[d]])) result[d] <- length(abs.diffX)^(sum(r[[d]])/2-1)*sum(tmp) if(normalize){ result[d] <- result[d]/prod(2^(r[[d]]/2)*gamma((r[[d]]+1)/2)/gamma(1/2)) } } } return(result) })
/scratch/gouwar.j/cran-all/cranData/yuima/R/mpv.R
############################################################### # function for adding noise ############################################################### setGeneric("noisy.sampling", function(x,var.adj=0,rng="rnorm",mean.adj=0,...,end.coef=0,n,order.adj=0,znoise) standardGeneric("noisy.sampling")) setMethod("noisy.sampling",signature(x="yuima"), function(x,var.adj=0,rng="rnorm",mean.adj=0,...,end.coef=0,n,order.adj=0,znoise) noisy.sampling(x@data,var.adj=var.adj,rng=rng,mean.adj=mean.adj,..., end.coef=end.coef,n=n,order.adj=order.adj,znoise=znoise)) setMethod("noisy.sampling",signature(x="yuima.data"), function(x,var.adj=0,rng="rnorm",mean.adj=0,..., end.coef=0,n,order.adj=0,znoise){ data <- get.zoo.data(x) d.size <- length(data) ser.times <- lapply(data,"time") total.samp <- unique(sort(unlist(ser.times))) samp.size <- length(total.samp) if(missing(n)) n <- sapply(data,"length") n <- as.vector(matrix(n,d.size,1)) if(missing(znoise)) znoise <- as.list(double(d.size)) result <- vector(d.size,mode="list") if(any(var.adj!=0)){ # exogenous noise is present rn <- n^(order.adj/2)*(matrix(do.call(rng,list(d.size*samp.size,...)),d.size,samp.size)-mean.adj) if(is.list(var.adj)){ total.noise <- matrix(0,d.size,samp.size) for(d in 1:d.size){ idx <- is.element(time(var.adj[[d]]),total.samp) total.noise[d,] <- sqrt(var.adj[[d]][idx])*rn[d,] } }else{ if(d.size>1){ tmp <- svd(as.matrix(var.adj)) total.noise <- (tmp$u%*%diag(sqrt(tmp$d))%*%t(tmp$v))%*%rn }else{ total.noise <- sqrt(var.adj)*rn } } if(any(end.coef!=0)){ if(is.list(end.coef)){ n.tmp <- n^((1-order.adj)/2) for(d in 1:d.size){ noise <- subset(total.noise[d,],is.element(total.samp,ser.times[[d]])) result[[d]] <- data[[d]]+noise+znoise[[d]]+ n.tmp*c(0,end.coef[[d]]*diff(as.numeric(data[[d]]))) } }else{ psi <- n^((1-order.adj)/2)*end.coef for(d in 1:d.size){ noise <- subset(total.noise[d,],is.element(total.samp,ser.times[[d]])) result[[d]] <- data[[d]]+noise+znoise[[d]]+ psi[d]*c(0,diff(as.numeric(data[[d]]))) } } }else{ for(d in 1:d.size){ noise <- subset(total.noise[d,],is.element(total.samp,ser.times[[d]])) result[[d]] <- data[[d]]+noise+znoise[[d]] } } }else{ # exogenous noise is absent if(any(end.coef!=0)){ if(is.list(end.coef)){ n.tmp <- n^((1-order.adj)/2) for(d in 1:d.size){ result[[d]] <- data[[d]]+znoise[[d]]+ n.tmp*c(0,end.coef[[d]]*diff(as.numeric(data[[d]]))) } }else{ end.coef <- n^((1-order.adj)/2)*end.coef for(d in 1:d.size){ result[[d]] <- data[[d]]+znoise[[d]]+ end.coef[d]*c(0,diff(as.numeric(data[[d]]))) } } }else{ for(d in 1:d.size){ result[[d]] <- data[[d]]+znoise[[d]] } } } return(setData(result)) })
/scratch/gouwar.j/cran-all/cranData/yuima/R/noisy.sampling.R
###################################################### # Volatility estimation and jump test using # nearest neighbor truncation ###################################################### ######## Volatility estimation ######## ## MinRV minrv <- function(yuima){ x <- get.zoo.data(yuima) d <- length(x) out <- double(d) for(j in 1:d){ dx2 <- diff(as.numeric(x[[j]]))^2 out[j] <- length(dx2) * mean(pmin(dx2[-length(dx2)], dx2[-1])) } return((pi/(pi - 2)) * out) } ## MedRV medrv <- function(yuima){ x <- get.zoo.data(yuima) d <- length(x) out <- double(d) for(j in 1:d){ dx2 <- diff(as.numeric(x[[j]]))^2 out[j] <- length(dx2) * mean(rollmedian(dx2, k = 3)) } return((pi/(6 - 4*sqrt(3) + pi)) * out) } ######## Jump test ######## ## function to compute log-type test statistics logstat <- function(rv, iv, iq, n, theta, adj){ avar <- iq/iv^2 if(adj) avar[avar < 1] <- 1 return(log(rv/iv)/sqrt(theta * avar/n)) } ## function to compute ratio-type test statistics ratiostat <- function(rv, iv, iq, n, theta, adj){ avar <- iq/iv^2 if(adj) avar[avar < 1] <- 1 return((1 - iv/rv)/sqrt(theta * avar/n)) } ## Jump test based on minRV minrv.test <- function(yuima, type = "ratio", adj = TRUE){ data <- get.zoo.data(yuima) d.size <- length(data) rv <- double(d.size) iv <- double(d.size) iq <- double(d.size) n <- integer(d.size) for(d in 1:d.size){ dx2 <- diff(as.numeric(data[[d]]))^2 n[d] <- length(dx2) rv[d] <- sum(dx2) obj <- pmin(dx2[-n[d]], dx2[-1]) iv[d] <- (pi/(pi - 2)) * n[d] * mean(obj) iq[d] <- (pi/(3*pi - 8)) * n[d]^2 * mean(obj^2) } stat <- switch(type, "standard" = (rv - iv)/sqrt(1.81 * iq/n), "ratio" = ratiostat(rv, iv, iq, n, 1.81, adj), "log" = logstat(rv, iv, iq, n, 1.81, adj)) p <- pnorm(stat, lower.tail = FALSE) result <- vector(d.size,mode="list") for(d in 1:d.size){ result[[d]] <- list(statistic = c(ADS = stat[d]), p.value = p[d], method = "Andersen-Dobrev-Schaumburg jump test based on MinRV", data.names = paste("x",d,sep = "")) class(result[[d]]) <- "htest" } return(result) } ## Jump test based on medRV medrv.test <- function(yuima, type = "ratio", adj = TRUE){ data <- get.zoo.data(yuima) d.size <- length(data) rv <- double(d.size) iv <- double(d.size) iq <- double(d.size) n <- integer(d.size) for(d in 1:d.size){ dx2 <- diff(as.numeric(data[[d]]))^2 n[d] <- length(dx2) rv[d] <- sum(dx2) obj <- rollmedian(dx2, k = 3) iv[d] <- (pi/(6 - 4*sqrt(3) + pi)) * n[d] * mean(obj) iq[d] <- (3*pi/(9*pi + 72 - 52*sqrt(3))) * n[d]^2 * mean(obj^2) } stat <- switch(type, "standard" = (rv - iv)/sqrt(0.96 * iq/n), "ratio" = ratiostat(rv, iv, iq, n, 0.96, adj), "log" = logstat(rv, iv, iq, n, 0.96, adj)) p <- pnorm(stat, lower.tail = FALSE) result <- vector(d.size,mode="list") for(d in 1:d.size){ result[[d]] <- list(statistic = c(ADS = stat[d]), p.value = p[d], method = "Andersen-Dobrev-Schaumburg jump test based on MedRV", data.names = paste("x",d,sep = "")) class(result[[d]]) <- "htest" } return(result) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/ntv.R