code
stringlengths
1
13.8M
read_spectra = function(path, format = NULL, type = "target_reflectance", extract_metadata = FALSE, exclude_if_matches = NULL, ignore_extension = FALSE) { path_and_format = i_verify_path_and_format(path = path, format = format, exclude_if_matches = exclude_if_matches, ignore_extension = ignore_extension) path = path_and_format$i_path format = path_and_format$i_format if(format == "sig"){ if(type == "target_reflectance"){ refl_cols = 4 sample_type = "target" } else if (type == "target_radiance") { refl_cols = 3 sample_type = "target" } else if (type == "reference_radiance") { refl_cols = 2 sample_type = "reference" } else { stop("type must be either target_reflectance, target_radiance or reference_radiance") } result = i_read_ascii_spectra(path, skip_until_tag = "data=", sep_char = "", header = FALSE, wl_col = 1, refl_cols = refl_cols, divide_refl_by = 100) spec = lapply(result, function(x) { rf = sapply(x, `[`, "value") rf = do.call(rbind, rf) wl = x[[1]][ , "band" ] nm = basename(names(x)) spectra(rf, wl, nm) }) if(extract_metadata){ svc_meta_tags = c("name=", "instrument=", "integration=", "scan method=", "scan coadds=", "scan time=", "scan settings=", "optic=", "temp=", "battery=", "error=", "units=", "time=", "longitude=", "latitude=", "gpstime=", "memory slot=", "inclinometer x offset=", "inclinometer y offset=") metadata = lapply(result, function(x){ i_read_ascii_metadata(file_paths = names(x), sample_type = sample_type, sep_char = ",", max_lines = 40, meta_tags = svc_meta_tags, tag_sep = "=") }) for(i in seq_along(spec)){ meta(spec[[i]]) = metadata[[i]] } } } if(format == "sed"){ if(type == "target_reflectance"){ refl_cols = c("Reflect. %", "Reflect. [1.0]") divide_refl_by = c(100, 1) sample_type = "target" } else if (type == "target_radiance") { refl_cols = "Rad. (Target)" divide_refl_by = 1 sample_type = "target" } else if (type == "reference_radiance") { refl_cols = "Rad. (Ref.)" divide_refl_by = 1 sample_type = "reference" } else { stop("type must be either target_reflectance, target_radiance or reference_radiance") } result = i_read_ascii_spectra(path, skip_until_tag = "Data:", sep_char = "\t", header = TRUE, wl_col = "Wvl", refl_cols = refl_cols, divide_refl_by = divide_refl_by, check.names = FALSE) spec = lapply(result, function(x) { rf = sapply(x, `[`, "value") rf = do.call(rbind, rf) wl = x[[1]][ , "band" ] nm = basename(names(x)) spectra(rf, wl, nm) }) if(extract_metadata){ psr_meta_tags = c("Version:", "File Name:", "Instrument:", "Detectors:", "Measurement:", "Date:","Time:", "Temperature (C):", "Battery Voltage:", "Averages:", "Integration:", "Dark Mode:", "Foreoptic:", "Radiometric Calibration:", "Units:", "band Range:", "Latitude:", "Longitude:", "Altitude:", "GPS Time:", "Satellites:", "Calibrated Reference Correction File:", "Channels:") metadata = lapply(result, function(x){ i_read_ascii_metadata(file_paths = names(x), sample_type = sample_type, sep_char = ",", max_lines = 40, meta_tags = psr_meta_tags, tag_sep = ":") }) for(i in seq_along(spec)){ meta(spec[[i]]) = metadata[[i]] } } } if(format == "asd"){ spec = i_read_asd_spectra(path, type = type, divide_refl_by = 1) } if(length(spec) > 1){ message("Returning a list of `spectra` because some files had different number of bands or band values. If you want to make those data compatible, consider resampling (with resample) and then combining them (with combine)") return(spec) } else { return(spec[[1]]) } } i_verify_path_and_format = function(path, format = NULL, exclude_if_matches = NULL, ignore_extension = FALSE) { i_path = path f_exists = file.exists(i_path) if(!all(f_exists)){ stop("Path(s) not found ", i_path[!f_exists]) } is_dir = dir.exists(i_path) if(any(is_dir)){ if(any(!is_dir)){ stop("Cannot mix directory and file paths.") } if(length(is_dir) > 1 ){ stop("Cannot read multiple directories at once. Please use a single directory as your path.") } i_path = dir(path = i_path, full.names = TRUE) if(length(i_path) == 0){ stop("The directory is empty.") } i_path = i_path[ ! dir.exists(i_path) ] if(length(i_path) == 0){ stop("The directory only includes other directories. `path` should be the directory that includes the spectral files themselves.") } } file_extensions = tolower(tools::file_ext(i_path)) format_lookup = c("sig", "sed", "asd") if( ! is.null(format) ){ format_match = pmatch(tolower(format), format_lookup) if(length(format_match) == 0){ stop("Files did not match any known format") } format = format_lookup[format_match] } else { extensions = file_extensions[file_extensions %in% format_lookup] extensions = names(sort(table(extensions), decreasing = TRUE)) if(length(extensions) > 1){ stop("Multiple file formats found. Spectrolab can only read one file format at a time.") } if(length(extensions) == 0){ stop("Files did not match any known format") } format = extensions[1] } if(! ignore_extension ){ i_path = i_path[ grepl(format, file_extensions) ] if(length(i_path) == 0){ stop("No files have the extension ", format) } } if(!is.null(exclude_if_matches)){ bad_tag = exclude_if_matches m = grepl(paste(bad_tag,collapse = "|"), i_path) i_path = i_path[!m] } if(length(i_path) == 0){ stop("No paths left after removing bad spectra. Check your `exclude_if_matches` parameter") } list(i_path = i_path, i_format = format) } i_read_ascii_spectra = function(file_paths, skip_until_tag = NULL, sep_char, header, wl_col, refl_cols, divide_refl_by, ...){ parse = function(x, tag = skip_until_tag) { max_l = 40 skip = grep(tag, trimws(readLines(x, n = max_l)), fixed = TRUE) if(length(skip) == 1){ return(utils::read.delim(x, skip = skip, sep = sep_char, header = header, check.names = FALSE)) } else if (length(skip) == 0){ stop(paste0("No match found for skip_until_tag in the first ", max_l, " lines")) } else { stop(paste0("More than one match found for skip_until_tag in the first ", max_l, " lines")) } } if(length(refl_cols) > 1 && any(i_is_whole(refl_cols)) ){ stop("refl_cols cannot be a vector of indices.") } if(length(refl_cols) < length(divide_refl_by)) { warning("Length of divide_refl_by should be either 1 or equals to the length of refl_cols. divide_refl_by has been prunned to length", length(refl_cols), ".") divide_refl_by = rep(divide_refl_by, length.out = length(refl_cols)) } data = lapply(file_paths, parse) names(data) = file_paths if(length(refl_cols) > 1) { d = data[[1]] m = colnames(d) %in% refl_cols n = which(refl_cols %in% colnames(d)) if(all( !m )){ stop("refl_cols did not match any columns.") } if( sum(m) > 1 ){ stop("refl_cols matched more than one column.") } refl_cols = which(m) divide_refl_by = divide_refl_by[n] } data = lapply(data, function(x){ data.frame("band" = x[ , wl_col], "value" = x[ , refl_cols] / divide_refl_by ) }) wl_factor = unlist( lapply(data, function(x){ paste0(x[ , "band"], collapse = "") }) ) data = unname(split(data, wl_factor)) return(data) } i_read_ascii_metadata = function(file_paths, sample_type, max_lines, sep_char, meta_tags, tag_sep){ message("reading metadata may take a while...") mat = sapply(file_paths, function(x){ f_lines = trimws(readLines(x, n = max_lines)) pick = ifelse(test = sample_type == "target", yes = 2, no = 1) meta_tags = setNames(meta_tags, meta_tags) data = lapply(meta_tags, function(x){ y = f_lines[grep(paste0("^", x), f_lines)] if(length(y) == 0){ return(NULL) } y = strsplit(gsub(x, "", y), sep_char)[[1]] s = sort(rep( c(1,2) , length.out = length(y))) if(length(s) == 1){ return(trimws(y)) } else { return(trimws(split(y, s)[[pick]])) } }) names(data) = gsub(tag_sep, "", names(data)) unlist(data) }, USE.NAMES = FALSE) mat = as.data.frame( t(mat), stringsAsFactors = FALSE, row.names = FALSE, check.names = FALSE) mat = lapply(mat, type.convert, as.is = TRUE) as.data.frame(mat, stringsAsFactors = FALSE, check.names = FALSE) } i_read_asd_spectra = function(file_paths, type = "target_reflectance", divide_refl_by){ ENDIAN = "little" TYPES = c("raw", "reflectance", "radiance", "no_units", "irradiance", "qi", "transmittance", "unknown", "absorbance") DATA_FORMAT = c("numeric", "integer", "double", "unknown") result = lapply(file_paths, FUN = function(f){ con = file(f, open = "rb") seek(con, 186) data_type = readBin(con, integer(), size = 1) data_type = TYPES[data_type + 1L] seek(con, 191) band_start = readBin(con, numeric(), size = 4, endian = ENDIAN) seek(con, 195) band_step = readBin(con, numeric(), size = 4, endian = ENDIAN) seek(con, 204) n_bands = readBin(con, integer(), size = 2, endian = ENDIAN) bands = seq(from = band_start, to = band_start + n_bands * band_step - 1L, by = band_step) seek(con, 199) data_format = readBin(con, integer(), size = 1) data_format = DATA_FORMAT[data_format + 1L] seek(con, 390) integration_time = readBin(con, integer(), size = 4, endian = ENDIAN) seek(con, 436) swir1_gain = readBin(con, integer(), size = 2, endian = ENDIAN) seek(con, 438) swir2_gain = readBin(con, integer(), size = 2, endian = ENDIAN) seek(con, 444) splice1 = readBin(con, numeric(), size = 4, endian = ENDIAN) seek(con, 448) splice2 = readBin(con, numeric(), size = 4, endian = ENDIAN) seek(con, where = 484) spectrum = readBin(con, what = data_format, n = n_bands, endian = ENDIAN) seek(con, 17710) comment_nchar = readBin(con, integer(), size = 2, endian = ENDIAN) seek(con, 17712 + comment_nchar) white_ref = readBin(con, what = data_format, n = n_bands, endian = ENDIAN) close(con) if(data_type == "raw"){ s1 = bands <= splice1 s2 = bands > splice1 & bands <= splice2 s3 = bands > splice2 spectrum[s1] = spectrum[s1] / integration_time spectrum[s2] = spectrum[s2] * swir1_gain / 2048 spectrum[s3] = spectrum[s3] * swir2_gain / 2048 white_ref[s1] = white_ref[s1] / integration_time white_ref[s2] = white_ref[s2] * swir1_gain / 2048 white_ref[s3] = white_ref[s3] * swir2_gain / 2048 } relative_reflectance = spectrum / white_ref spec_name = gsub(pattern = ".asd$", replacement = "", x = basename(f), ignore.case = TRUE) if(type == "target_reflectance"){ result = cbind(bands, relative_reflectance, spec_name) } else if (type == "target_radiance") { result = spectra(bands, spectrum, spec_name) } else if (type == "reference_radiance") { result = spectra(bands, white_ref, spec_name) } else { stop("type must be either target_reflectance, target_radiance or reference_radiance") } }) wl = lapply(result, function(x){ x[ , 1] }) wl_factor = unlist( lapply(wl, function(x){ paste0(x, collapse = "") }) ) data = unname(split(result, wl_factor)) spec = lapply(data, function(x) { rf = lapply(x, function(y){ y[ , 2 ] }) rf = do.call(rbind, rf) wl = x[[1]][ , 1 ] nm = sapply(x, function(y){ y[1 , 3 ] }) spectra(rf, wl, nm) }) if(length(spec) > 1){ warning("Returning a list of `spectra` because some files had different number of bands or band values. If you want to make those data compatible, consider resampling (with resample) and then combining them (with combine)") return(spec) } else { return(spec[[1]]) } }
gap_cases <- function(alignment) { m <- remove_align_mat_class(alignment) any_gaps <- any(m[, 2] == '-') if(!any_gaps) return('case 1') is_again_gapped <- again_gapped(m) if(!is_again_gapped) return('case 2') else return('case 3') }
context("test-plot_egor.R") pdf(NULL) test_that("plot plots egor objects", { expect_error({ e <- make_egor(5, 5) plot( x = e, x_dim = 2, y_dim = 2, ego_no = 1, vertex_size_var = "age.years", vertex_color_var = "age.years", vertex_color_palette = "Greys", vertex_color_legend_label = "Age", edge_width_var = "weight", edge_color_var = "weight", edge_color_palette = "Greys", highlight_box_col_var = "sex", res_disp_vars = c("sex", "age") ) plot( x = e, x_dim = 2, y_dim = 2, ego_no = 1, vertex_size_var = "age.years", vertex_color_var = "age.years", vertex_color_palette = "Greys", vertex_color_legend_label = "Mushi", edge_width_var = "weight", edge_color_var = "weight", edge_color_palette = "Greys", highlight_box_col_var = "sex", res_disp_vars = c("sex", "age") ) plot( x = e, ego_no = 1, venn_var = "age", pie_var = "country", venn_colors = c("blue", "lightblue", "mistyrose", "lightcyan"), show_venn_labels = TRUE, type = "egogram" ) }, NA) }) test_that("plot_egograms works with minimal arguments", { expect_error({ e <- make_egor(net.count = 5, max.alters = 12) plot_egograms( x = e, ego_no = 2, venn_var = "sex", pie_var = "country", vertex_size_var = "age" ) plot_egograms( x = e, ego_no = 2, venn_var = "sex", pie_var = "country" ) }, NA) }) test_that("plot_ego_graphs works with minmal arguments", { expect_error({ e <- make_egor(5, 15) plot_ego_graphs(e) }, NA) }) test_that("plot_ego_graphs works with vertex_color_var", { expect_error({ e <- make_egor(15, 15) plot_ego_graphs(e, vertex_color_var = "sex") plot_ego_graphs(e, vertex_color_var = "sex", vertex_color_legend_label = "Sex") }, NA) }) test_that("plot_egograms doesn't fail on empty alters or aaties", { e <- make_egor(5, 5) e$aatie <- e$aatie %>% filter(.egoID != 1) expect_error(plot_egograms( x = e, venn_var = "sex", pie_var = "country", show_venn_labels = TRUE ), NA) e <- make_egor(5, 5) e$alter <- e$alter %>% filter(.egoID != 1) expect_error(plot_egograms( x = e, venn_var = "sex", pie_var = "country", show_venn_labels = TRUE ), NA) }) test_that("plot_egograms plots with and without venn labels", { expect_error({ e <- make_egor(5, 5) plot_egograms( e, venn_var = "sex", pie_var = "country", show_venn_labels = FALSE ) plot_egograms( e, venn_var = "sex", pie_var = "country", show_venn_labels = TRUE ) }, NA) }) test_that("plotting works when active data level is not ego", { expect_error({ e <- make_egor(5, 15) %>% activate(alter) plot_egograms( e, 1, x_dim = 1, y_dim = 1, "sex", "country", show_venn_labels = FALSE ) plot_ego_graphs(e, 1) e <- make_egor(5, 15) %>% activate(aatie) plot_egograms( e, 1, x_dim = 1, y_dim = 1, "sex", "country", show_venn_labels = FALSE ) plot_ego_graphs(e, 1) }, NA) }) test_that("plot_ego_graphs is fast", { expect_error({ plot_ego_graphs(make_egor(12, 16)) plot_ego_graphs(make_egor(120, 16)) }, NA) }) test_that("plot_ego_gram adjusts node size according to venn count", { expect_error({ e <- make_egor(5, 5) plot_egograms( x = e, ego_no = 2, venn_var = "sex", pie_var = "country" ) plot_egograms( x = e, ego_no = 2, venn_var = "country", pie_var = "age" ) plot_egograms( x = e, ego_no = 2, venn_var = "age", pie_var = "age" ) plot_egograms( x = e, ego_no = 2, venn_var = "age", pie_var = "age", vertex_zoom = 2, edge_zoom = 2 ) }, NA) }) test_that("plot_ego_gram works with edge arguments", { expect_error({ e <- make_egor(5, 32) plot_egograms( e, ego_no = 1, venn_var = "sex", pie_var = "country", vertex_color_var = "sex", edge_color_var = "weight", edge_width_var = "weight", edge_zoom = 3 ) plot_ego_graphs( x = e, ego_no = 1, edge_color_var = "weight", edge_width_var = "weight", edge_zoom = 2 ) }, NA) }) test_that("plot_ego_gram works without pie_var/venn_var", { expect_error({ e <- make_egor(5, 32) plot_egograms( e, ego_no = 1, venn_var = "sex", pie_var = NULL, vertex_color_var = "sex", edge_color_var = "weight", edge_width_var = "weight", edge_zoom = 3 ) plot_egograms( e, ego_no = 1, venn_var = NULL, pie_var = "sex", vertex_color_var = "sex", edge_color_var = "weight", edge_width_var = "weight", edge_zoom = 3 ) }, NA) expect_warning({ plot_egograms( e, ego_no = 1, venn_var = NULL, pie_var = NULL, vertex_color_var = "sex", edge_color_var = "weight", edge_width_var = "weight", edge_zoom = 3 ) }) }) test_that("plot_ego_gram plots empty levels of a factor variables for pies and venns", { expect_error({ e <- make_egor(50, 12) e <- e %>% activate(alter) %>% mutate(age2 = as.character(age), rating = sample(1:5, n(), replace = TRUE)) e <- e %>% mutate(rating.f = factor(rating, levels = 1:5)) plot_egograms( e, ego_no = 4, venn_var = "rating", pie_var = "age2", vertex_color_var = "sex", edge_color_var = "weight", edge_width_var = "weight", edge_zoom = 3, venn_gradient_reverse = FALSE ) plot_egograms( e, ego_no = 1, venn_var = "rating", pie_var = "sex", vertex_color_var = "sex", edge_color_var = "weight", edge_width_var = "weight", edge_zoom = 3, ) plot_egograms( e, ego_no = 1, venn_var = "rating", pie_var = "sex", vertex_color_var = "sex", edge_color_var = "weight", edge_width_var = "weight", edge_zoom = 3, vertex_label_var = NULL ) }, NA) layout_egogram(e$alter$.altID, e$alter$age, e$alter$rating.f) expect_warning({ plot_egograms( e, ego_no = 1, venn_var = NULL, pie_var = NULL, vertex_color_var = "sex", edge_color_var = "weight", edge_width_var = "weight", edge_zoom = 3 ) }) }) test_that("ego-alter weights are plotted", { e <- make_egor(5, 12) e$alter$weight <- sample(1:5 / 5, nrow(e$alter), replace = TRUE) expect_error({ plot_ego_graphs(e, include_ego = TRUE) plot_ego_graphs(x = e, edge_width_var = "weight", include_ego = TRUE) }, NA) expect_error({ plot_ego_graphs(e, include_ego = TRUE) plot_ego_graphs(e, edge_color_var = "weight", include_ego = TRUE) }, NA) }) test_that("egograms with many venns produce adequatly sized nodes", { data("transnat") transnat <- transnat %>% activate(alter) %>% mutate(test_var = sample(1:12, nrow(.$alter), replace = TRUE)) expect_error( plot_egograms( transnat, venn_var = "test_var", pie_var = "sex", vertex_zoom = 1, vertex_label_var = NULL ), NA ) }) test_that("egograms with `include_ego = TRUE` work properly", { expect_error(plot_egograms(x = egor32, venn_var = "age", pie_var = "country", include_ego = TRUE), NA) expect_error(plot_egograms(x = egor32, venn_var = "age", pie_var = "country", include_ego = FALSE), NA) }) test_that("egograms with reverse ordered alters plot correctly", { plot_egograms(egor32, venn_var = "age", pie_var = "country") egor32 %>% activate(alter) %>% arrange(.egoID, desc(.altID)) %>% plot_egograms(venn_var = "age", pie_var = "country") ego <- tibble(egoID = c("Hans", "Peter", "Klaus"), var = c(1, 2, 3)) alter <- tibble( egoID = c(rep("Hans", 3), rep("Peter", 3), rep("Klaus", 3)), alterID = c( "Mary", "Paul", "Susana", "Irna", "Laser3000", "Pferd", "Ross", "Ricky", "Herald" ), var1 = sample(1:3, 9, replace = TRUE), var2 = sample(1:3, 9, replace = TRUE) ) e1 <- egor(alter, ego) plot_egograms(e1, venn_var = "var1", pie_var = "var2", ego_no = 2) expect_error(e1 %>% activate(alter) %>% arrange(.egoID, desc(.altID)) %>% plot_egograms(venn_var = "var1", pie_var = "var2", ego_no = 2), NA) }) test_that("plot_egograms removes and warns for alters with missing data in pie/venn_var", { t1 <- make_egor(5, 5) %>% activate(alter) %>% mutate(test = c(NA, sample(c("test", "test2"), nrow(.$alter)-1, replace = TRUE))) expect_warning(plot_egograms(t1, 1, venn_var = "country", pie_var = "test")) expect_warning(plot_egograms(x = t1, ego_no = 1, venn_var = "test", pie_var = "country")) }) test_that("plot_egograms() argument ascending_inwards works", { e1 <- make_egor(15, 15) expect_error(plot_egograms(e1, 1, venn_var = "age", pie_var = "sex", ascending_inwards = FALSE), NA) expect_error(plot_egograms(e1, 1, venn_var = "age", pie_var = "sex", ascending_inwards = TRUE), NA) }) dev.off()
bedr.setup <- function(datasets = "all", data.dir = paste0(Sys.getenv("HOME"),"/bedr/data")) { config.file <- paste0(Sys.getenv("HOME"),"/bedr/config.txt"); if (!file.exists(data.dir)) dir.create(data.dir, recursive = TRUE); if (!file.exists(config.file)) file.create(config.file); config.bedr$data.dir <- data.dir; cat(as.yaml(config.bedr), file = config.file, append = TRUE); download.datasets(datasets, data.dir); return(); }
expected <- eval(parse(text="structure(\"range specified by \", Rd_tag = \"TEXT\")")); test(id=0, code={ argv <- eval(parse(text="list(\"\\\\\", \"\\\\bsl\", structure(\"range specified by \", Rd_tag = \"TEXT\"), FALSE, FALSE, TRUE, TRUE)")); .Internal(gsub(argv[[1]], argv[[2]], argv[[3]], argv[[4]], argv[[5]], argv[[6]], argv[[7]])); }, o=expected);
library(knotR) filename <- "8_15.svg" a <- reader(filename) Mver <- matrix(c( 04,16, 15,05, 09,11, 06,14, 08,12, 03,01, 07,13 ),ncol=2,byrow=TRUE) sym815 <- symmetry_object(a,Mver=Mver,xver=c(2,10)) ou815 <- matrix(c( 16,05, 12,01, 02,14, 07,03, 04,09, 06,15, 10,07, 14,11 ),ncol=2,byrow=TRUE) jj <- knotoptim(filename, symobj = sym815, ou = ou815, prob = 0, iterlim=1000,print.level=2,hessian=FALSE ) write_svg(jj, filename,safe=FALSE) dput(jj,file=sub('.svg','.S',filename))
kRp_corp_freq <- setClass("kRp.corp.freq", representation=representation( meta="data.frame", words="data.frame", desc="data.frame", bigrams="data.frame", cooccur="data.frame", caseSens="logical" ), prototype( ) ) setMethod("initialize", "kRp.corp.freq", function( .Object, meta=data.frame( meta=character(), value=character() ), words=data.frame( num=numeric(), word=character(), lemma=character(), tag=character(), wclass=character(), lttr=numeric(), freq=numeric(), pct=numeric(), pmio=numeric(), log10=numeric(), rank.avg=numeric(), rank.min=numeric(), rank.rel.avg=numeric(), rank.rel.min=numeric(), inDocs=numeric(), idf=numeric() ), desc=data.frame( tokens=character(), types=character(), words.p.sntc=numeric(), chars.p.sntc=numeric(), chars.p.wform=numeric(), chars.p.word=numeric() ), bigrams=data.frame( token1=character(), token2=character(), freq=numeric(), sig=numeric() ), cooccur=data.frame( token1=character(), token2=character(), freq=numeric(), sig=numeric() ), caseSens=FALSE ){ slot(.Object, "meta") <- meta slot(.Object, "words") <- words slot(.Object, "desc") <- desc slot(.Object, "bigrams") <- bigrams slot(.Object, "cooccur") <- cooccur slot(.Object, "caseSens") <- caseSens validObject(.Object) return(.Object) } ) setValidity("kRp.corp.freq", function(object){ meta <- slot(object, "meta") words <- slot(object, "words") desc <- slot(object, "desc") bigrams <- slot(object, "bigrams") cooccur <- slot(object, "cooccur") meta.names <- dimnames(meta)[[2]] words.names <- dimnames(words)[[2]] desc.names <- dimnames(desc)[[2]] bigrams.names <- dimnames(bigrams)[[2]] cooccur.names <- dimnames(cooccur)[[2]] if(!identical(meta.names, c("meta", "value"))){ stop(simpleError("Invalid object: Wrong column names in slot \"meta\".")) } else {} if(!identical(words.names, c( "num", "word", "lemma", "tag", "wclass", "lttr", "freq", "pct", "pmio", "log10", "rank.avg", "rank.min", "rank.rel.avg", "rank.rel.min", "inDocs", "idf"))){ stop(simpleError("Invalid object: Wrong column names in slot \"words\".")) } else {} if(!identical(desc.names, c("tokens", "types", "words.p.sntc", "chars.p.sntc", "chars.p.wform", "chars.p.word"))){ stop(simpleError("Invalid object: Wrong column names in slot \"desc\".")) } else {} if(!identical(bigrams.names, c("token1", "token2", "freq", "sig"))){ stop(simpleError("Invalid object: Wrong column names in slot \"bigrams\".")) } else {} if(!identical(cooccur.names, c("token1", "token2", "freq", "sig"))){ stop(simpleError("Invalid object: Wrong column names in slot \"cooccur\".")) } else {} return(TRUE) })
probs.l1mstate = function(object, longdt, tmat, predt, direction=c("forward","fixedhorizon")){ transit = tmat2(tmat) numtrans = nrow(transit) x1 = object$Haz unt = sort(unique(x1$time)) K = unique(x1$trans) k=min(K) xk = x1[x1$trans==k,] xk_new = matrix(rep(0,3*length(unt)), nrow = length(unt)) xk_new[,1] = unt xk_new[,2] = ifelse(xk_new[,1] %in% xk$time, xk$Haz, 0) xk_new[,2] = cumsum(xk_new[,2]) xk_new[,3] = rep(k, length(unt)) x1_new = xk_new for(k in K){ if(k!=min(K)){ xk = x1[x1$trans==k,] xk_new = matrix(rep(0,3*length(unt)), nrow = length(unt)) xk_new[,1] = unt xk_new[,2] = ifelse(xk_new[,1] %in% xk$time, xk$Haz, 0) xk_new[,2] = cumsum(xk_new[,2]) xk_new[,3] = rep(k, length(unt)) x1_new = rbind(x1_new, xk_new) } } x1_new = data.frame(x1_new) names(x1_new)=c("time", "cumHaz", "trans") stackhaz = x1_new for (i in 1:numtrans) stackhaz$dhaz[stackhaz$trans==i] = diff(c(0,stackhaz$cumHaz[stackhaz$trans==i])) if (direction=="forward"){ stackhaz = stackhaz[stackhaz$time > predt,] }else{ stackhaz = stackhaz[stackhaz$time <= predt,] } untimes = sort(unique(stackhaz$time)) TT = length(untimes) S = nrow(tmat) if (direction=="forward") { res = array(0,c(TT+1,S+1,S)) res[1,1,] = predt for (j in 1:S) res[1, 1+j,] = rep(c(0,1,0), c(j-1,1,S-j)) }else{ if (predt %in% untimes) { res = array(0,c(TT+1,S+1,S)) res[TT+1,1,] = predt for (j in 1:S) res[TT+1, 1+j,] = rep(c(0,1,0), c(j-1,1,S-j)) }else{ res = array(0,c(TT+2,S+1,S)) res[TT+1,1,] = max(untimes) for (j in 1:S) res[TT+1, 1+j,] = rep(c(0,1,0), c(j-1,1,S-j)) res[TT+2,1,] = predt for (j in 1:S) res[TT+2, 1+j,] = rep(c(0,1,0), c(j-1,1,S-j)) } } P = diag(S) for (i in 1:TT) { idx = ifelse(direction=="forward",i,TT+1-i) tt = untimes[idx] Haztt = stackhaz[stackhaz$time==tt,] lHaztt = nrow(Haztt) IplusdA = diag(S) for (j in 1:lHaztt){ from = transit$from[transit$transno==Haztt$trans[j]] to = transit$to[transit$transno==Haztt$trans[j]] IplusdA[from, to] = Haztt$dhaz[j] IplusdA[from, from] = IplusdA[from, from] - Haztt$dhaz[j] } if (any(diag(IplusdA)<0)) warning("Warning! Negative diagonal elements of (I+dA); the estimate may not be meaningful. \n") if (direction=="forward") { P = P %*% IplusdA }else{ P = IplusdA %*% P } if (direction=="forward") { res[idx+1,1,] = tt res[idx+1,2:(S+1),] = t(P) }else{ res[idx,1,] = ifelse(i==TT,0,untimes[TT-i]) res[idx,2:(S+1),] = t(P) } } res2 = vector("list", S) for (s in 1:S) { tmp = as.data.frame(res[,,s]) if (min(dim(tmp))==1) tmp = res[,,s] names(tmp) = c("time",paste("pstate",1:S,sep="")) res2[[s]] = tmp } res2$trans = x1$trans res2$tmat = tmat return(res2) } tmat2 = function(tmat) { dm = dim(tmat) mx = max(tmat,na.rm=TRUE) res = matrix(NA,mx,3) res[,1] = 1:mx transvec = as.vector(tmat) for (i in 1:mx) { idx = which(transvec==i) res[i,2:3] = c(idx %% dm[2],idx %/% dm[2] + 1) } res = data.frame(res) names(res) = c("transno","from","to") if (!is.null(dimnames(tmat))) { states = dimnames(tmat)[[1]] res$fromname = states[res$from] res$toname = states[res$to] } return(res) }
print.boot.two <- function(x, ...) { test <- !is.null(x$Null) hist(x$Boot.values,breaks=20,xlab=paste("bootstrap",x$Statistic), main=paste("Histogram of bootstrap ",x$Statistic,"s",sep="")) abline(v=x$Observed,col="2") abline(v=x$Mean,col="3") abline(v=c(x$Confidence.limits),col="4") if (test) abline(v=x$Null,col="5") leg.text <- if (test) expression(Observed,Mean.boots,Confidence.interval,Null.value) else expression(Observed,Mean.boots,Confidence.interval) legend("topright",leg.text,col=2:5,lwd=2,cex=.6) cat("\n\n",x$Header,"\n\n") if (x$Stacked || !is.null(x$Variable)) {if (identical("proportion",x$Parameter)) print(data.frame(SUMMARY="STATISTICS",Variable=x$Variable, Pop.1=x$Pop.1,Pop.2=x$Pop.2,n.1=x$n.1, x.1=x$Observed.1*x$n.1,n.2=x$n.2,x.2=x$Observed.2*x$n.2, Statistic=x$Statistic,Observed=x$Observed),row.names=FALSE) else print(data.frame(SUMMARY="STATISTICS",Variable=x$Variable, Pop.1=x$Pop.1,Pop.2=x$Pop.2,n.1=x$n.1, n.2=x$n.2,Statistic=x$Statistic,Observed=x$Observed),row.names=FALSE)} else {if (identical("proportion",x$Parameter)) print(data.frame(SUMMARY="STATISTICS",Pop.1=x$Pop.1, Pop.2=x$Pop.2,n.1=x$n.1, x.1=x$Observed.1*x$n.1, n.2=x$n.2,x.2=x$Observed.2*x$n.2,Statistic=x$Statistic, Observed=x$Observed),row.names=FALSE) else print(data.frame(SUMMARY="STATISTICS",Pop.1=x$Pop.1, Pop.2=x$Pop.2,n.1=x$n.1,n.2=x$n.2,Statistic=x$Statistic, Observed=x$Observed),row.names=FALSE)} cat("\n") print(data.frame(BOOTSTRAP="SUMMARY",Replications=x$Replications,Mean=x$Mean, SE=x$SE,Bias=x$Bias,Percent.bias=x$Percent.bias),row.names=FALSE) cat("\n") if (test) print(data.frame(HYPOTHESIS="TEST",Null=x$Null, Alternative=x$Alternative,P.value=x$P.value),row.names=FALSE) if (test) cat("\n") print(data.frame(CONFIDENCE="INTERVAL",Level=x$Level,Type=x$Type, Confidence.interval=x$Confidence.interval),row.names=FALSE) cat("\n\n") }
HMR.fit <- function (t, C, A = 1, V, serie = "", k = log(1.5), verbose = TRUE, plot = FALSE, maxiter = 100, ...) { tryCatch({ stopifnot(length(t) > 3) fit <- withWarnings(nls(C ~ cbind(1, exp(-exp(k)*t)/(-exp(k)*V/A)), start= list(k=k), algorithm = "plinear", control=nls.control(maxiter=maxiter, minFactor=1e-10))) w <- if (is.null(fit$warnings)) "" else fit$warnings[[1]]$message fit <- fit$value fitsum <- withWarnings(summary(fit)) if (w == "") w <- if (is.null(fitsum$warnings)) "" else fitsum$warnings[[1]]$message fitsum <- fitsum$value fitsumCoef <- fitsum$coef try({ if (plot) { curve(predict(fit, newdata = data.frame(t = x)), from = min(t), to = max(t), add = TRUE, col = "red") }}, silent = TRUE) res <- list( f0 = fitsumCoef[".lin2", "Estimate"], f0.se = fitsumCoef[".lin2", "Std. Error"], f0.p = fitsumCoef[".lin2", "Pr(>|t|)"], kappa=exp(fitsumCoef["k", "Estimate"]), phi=fitsumCoef[".lin1", "Estimate"], AIC=AIC(fit), AICc=AICc(fit), RSE=fitsum$sigma, diagnostics = w) if (verbose) message(serie, if (w == "") ": HMR fit successful" else ": HMR fit warning") res }, error = function(cond) { if (verbose) message(serie, ": HMR fit failed") list( f0 = NA_real_, f0.se = NA_real_, f0.p = NA_real_, kappa=NA_real_, phi=NA_real_, AIC=NA_real_, AICc=NA_real_, RSE=NA_real_, diagnostics=cond$message) } ) } utils::globalVariables("x")
impute.MinDet = function(dataSet.mvs,q = 0.01){ nSamples = dim(dataSet.mvs)[2] dataSet.imputed = dataSet.mvs lowQuantile.samples = apply(dataSet.imputed,2,quantile,prob = q,na.rm = T) for (i in 1:(nSamples)){ dataSet.imputed[which(is.na(dataSet.mvs[,i])),i] = lowQuantile.samples[i] } return(dataSet.imputed) }
data(dataEP05A2_1) data(dataEP05A2_2) data(dataEP05A2_3) cat("\n\n***********************************************************************") cat("\nVariance Component Analysis (VCA) - test cases defined in runit.misc.R.") cat("\n***********************************************************************\n\n") TF001.CovarianceMatrix <- function() { data(VCAdata1) sample1 <- VCAdata1[which(VCAdata1$sample==1),] sample1$device <- gl(3,28,252) set.seed(505) sample1$y <- sample1$y + rep(rep(rnorm(3,,.25), c(28,28,28)),3) res1 <- anovaVCA(y~(lot+device)/day/run, sample1) inf1 <- VCAinference(res1, VarVC=TRUE, constrainCI=FALSE) checkEquals(round(inf1$VCAobj$aov.tab[2, "Var(VC)"], 6), 0.000301) checkEquals(round(inf1$VCAobj$aov.tab[3, "Var(VC)"], 6), 0.004091) checkEquals(round(inf1$VCAobj$aov.tab[4, "Var(VC)"], 6), 0.000071) checkEquals(round(inf1$VCAobj$aov.tab[5, "Var(VC)"], 6), 0.000084) checkEquals(round(inf1$VCAobj$aov.tab[6, "Var(VC)"], 11), 2.108e-8) } TF002.marginal_residuals <- function() { data(Orthodont) Ortho <- Orthodont Ortho$age2 <- Ortho$age - 11 fit.R <- anovaMM(distance~Sex+Sex:age2+(Subject)+(Subject):age2, Ortho, order.data=FALSE) sas.raw <- c(3.384375,0.815625,3.246875,3.678125,-1.115625,-1.684375,-2.753125,-0.821875,0.384375,-1.684375,-1.753125,0.178125,2.884375,3.315625,0.746875,-0.321875,-2.615625,-0.684375,-3.253125,-1.321875,1.884375,1.315625,1.246875,1.178125,-0.615625,-2.184375,-1.253125,-0.821875,1.384375,-2.684375,-1.253125,-1.821875,0.384375,-3.684375,5.246875,-1.321875,4.884375,3.815625,5.246875,4.178125,0.384375,-1.184375,-2.253125,-2.321875,-1.115625,-0.684375,-1.753125,0.678125,-5.615625,0.315625,0.246875,2.178125,-0.115625,1.315625,-0.253125,-1.321875,0.384375,0.315625,0.246875,2.678125,-0.615625,-2.684375,-2.253125,-2.321875,-0.209090909,-2.168181818,-1.627272727,-1.086363636,-0.209090909,-0.668181818,0.8727272727,1.4136363636,-0.709090909,1.8318181818,1.3727272727,1.9136363636,2.2909090909,2.3318181818,1.8727272727,2.4136363636,0.2909090909,0.8318181818,-0.627272727,-0.586363636,-1.209090909,-1.168181818,-2.127272727,-1.586363636,0.2909090909,0.3318181818,-0.127272727,0.9136363636,1.7909090909,0.8318181818,0.3727272727,-0.086363636,-1.209090909,-1.168181818,-1.127272727,-2.586363636,-4.709090909,-3.168181818,-4.127272727,-4.586363636,3.2909090909,2.8318181818,4.8727272727,3.9136363636) sas.stu <- c(1.5050944191,0.37015662,1.473535357,1.6357304998,-0.496139158,-0.764423058,-1.249455871,-0.365503077,0.1709387013,-0.764423058,-0.795623999,0.0792154957,1.2827351328,1.5047362981,0.3389556788,-0.143143791,-1.163217016,-0.310591187,-1.476371806,-0.587862363,0.8380165602,0.5970725556,0.5658716145,0.5239340683,-0.273779871,-0.991338994,-0.568708064,-0.365503077,0.6156572739,-1.218254929,-0.568708064,-0.810221649,0.1709387013,-1.672086801,2.3811990995,-0.587862363,2.1721722779,1.7316522338,2.3811990995,1.858089786,0.1709387013,-0.537507123,-1.022539935,-1.032580936,-0.496139158,-0.310591187,-0.795623999,0.301574782,-2.497372734,0.1432406844,0.1120397432,0.9686526409,-0.051420585,0.5970725556,-0.114876192,-0.587862363,0.1709387013,0.1432406844,0.1120397432,1.1910119272,-0.273779871,-1.218254929,-1.022539935,-1.032580936,-0.094278468,-0.99540562,-0.747075916,-0.489838127,-0.094278468,-0.306760222,0.400666413,0.6374044247,-0.319726978,0.8409821065,0.6302148788,0.8628529351,1.0329640838,1.0705305723,0.8597633446,1.0883014454,0.1311700424,0.3818851749,-0.287978984,-0.264389617,-0.545175489,-0.536308688,-0.976624382,-0.715286637,0.1311700424,0.1523367091,-0.058430519,0.4119559144,0.8075155734,0.3818851749,0.1711179472,-0.038941106,-0.545175489,-0.536308688,-0.51752745,-1.166183658,-2.123315061,-1.454502551,-1.894818245,-2.067977699,1.4838611045,1.3000790381,2.2370541394,1.7646469765) sas.pea <- c(1.4619609019,0.3612064332,1.4379060694,1.5888531685,-0.48192063,-0.745939722,-1.219244704,-0.355028363,0.1660398808,-0.745939722,-0.776386242,0.0769453106,1.245974065,1.4683525887,0.3307599139,-0.139041526,-1.12988114,-0.30308126,-1.440673935,-0.5710152,0.8140003914,0.5826356643,0.552189145,0.5089189843,-0.265933793,-0.967368953,-0.55495701,-0.355028363,0.5980135545,-1.188798184,-0.55495701,-0.787002037,0.1660398808,-1.631656647,2.3236229938,-0.5710152,2.1099214124,1.6897818198,2.3236229938,1.8048400054,0.1660398808,-0.524510491,-0.997815473,-1.002988874,-0.48192063,-0.30308126,-0.776386242,0.2929321475,-2.425802161,0.1397772021,0.1093306829,0.940892658,-0.049946956,0.5826356643,-0.112098548,-0.5710152,0.1660398808,0.1397772021,0.1093306829,1.1568794948,-0.265933793,-1.188798184,-0.997815473,-1.002988874,-0.090321768,-0.960197666,-0.720651498,-0.469280491,-0.090321768,-0.295909972,0.3864946579,0.6106536933,-0.306308605,0.811236183,0.607923889,0.8266405301,0.9896124161,1.0326654141,0.8293531201,1.0426273669,0.1256650687,0.3683777208,-0.277793035,-0.253293654,-0.522295442,-0.517339204,-0.942080729,-0.685267328,0.1256650687,0.1469484897,-0.056363804,0.3946668564,0.7736255792,0.3683777208,0.1650654268,-0.037306817,-0.522295442,-0.517339204,-0.499222266,-1.117241001,-2.0342033,-1.403056128,-1.827797653,-1.981188349,1.4215860898,1.2540946452,2.1579285066,1.6905878775) checkEquals(round(as.numeric(resid(fit.R, "marginal", "raw")), 6), round(sas.raw, 6)) checkEquals(round(as.numeric(resid(fit.R, "marginal", "stud")), 10), sas.stu) checkEquals(round(as.numeric(resid(fit.R, "marginal", "pear")), 10), sas.pea) } TF003.conditional_residuals <- function() { data(Orthodont) Ortho <- Orthodont Ortho$age2 <- Ortho$age - 11 Ortho$Subject <- factor(as.character(Ortho$Subject)) fit.R <- anovaMM(distance~Sex+Sex:age2+(Subject)+(Subject):age2, Ortho, order.data=FALSE) sas.raw <- c(1.0554503692,-1.604344233,0.7358611644,1.0760665621,0.2894545536,-0.274141978,-1.33773851,0.5986649577,0.9931804233,-1.056673527,-1.106527478,0.843618572,0.9136978046,1.6799232283,-0.553851348,-1.287625924,-0.816278005,1.0788977187,-1.525926558,0.3692491659,0.5475924658,0.0389662598,0.0303400538,0.0217138478,0.4776426009,-1.099696512,-0.177035626,0.2456252606,2.0163981647,-1.827317063,-0.171032292,-0.51474752,0.4030450154,-3.770492168,5.0559706477,-1.617566536,0.8392188753,-0.210635075,1.2395109744,0.1896570239,1.1967876368,-0.119442428,-0.935672494,-0.751902559,-0.300680854,0.0120393803,-1.175240385,1.1374798497,-4.01735371,1.2731484286,0.5636505667,1.8541527049,-0.246387468,1.3274418148,-0.098728902,-1.024899619,-0.138123401,-0.394116074,-0.650108746,1.5938985808,0.9363555284,-1.00355777,-0.443471069,-0.383384367,0.8329387278,-1.068683204,-0.470305136,0.1280729319,-0.257137352,-0.892383169,0.4723710135,0.8371251962,-1.380761257,0.9565077625,0.2937767823,0.6310458021,0.3127531847,0.3561609268,-0.100431331,0.4429764109,0.142397156,0.79574555,-0.550906056,-0.397557662,0.0545559443,0.1529340124,-0.74868792,-0.150309852,0.0367239257,0.0389039233,-0.458916079,0.5432639185,0.8950900173,0.1034087373,-0.188272543,-0.479953823,-0.027899545,0.1254488494,0.2787972434,-1.067854363,-1.056621665,0.5005286586,-0.442321018,-0.885170694,0.1479608631,-0.418572047,1.5148950435,0.4483621337) sas.stu <- c(1.0130072422,-1.40421926,0.6440702679,1.0327943903,0.277814635,-0.239945666,-1.170869781,0.5745906729,0.9532413755,-0.924864682,-0.968499879,0.8096938975,0.876955014,1.4703705752,-0.484764251,-1.235846255,-0.783452784,0.9443166405,-1.33558336,0.3544004438,0.5255719736,0.034105631,0.026555453,0.0208406626,0.4584350227,-0.962521005,-0.154952304,0.2357478619,1.9353121698,-1.599378588,-0.149697822,-0.494047831,0.3868372511,-3.300163153,4.4252917896,-1.552518871,0.8054711271,-0.184360578,1.0848950914,0.1820302919,1.148660874,-0.104543249,-0.818957247,-0.721666086,-0.288589489,0.010537595,-1.028641578,1.0917380478,-3.855802718,1.114336629,0.4933411206,1.7795911329,-0.236479419,1.1618574896,-0.086413516,-0.983685038,-0.132569005,-0.344954262,-0.569014557,1.5298026822,0.8987015962,-0.878374554,-0.388152744,-0.367967222,0.8058885013,-0.936507499,-0.412137372,0.1239136802,-0.248786649,-0.782012412,0.4139477394,0.8099390114,-1.335920138,0.8382060174,0.2574422042,0.6105521795,0.3025963217,0.3121106213,-0.088009893,0.4285904641,0.1377727158,0.6973270207,-0.482769497,-0.384646719,0.0527842046,0.1340189954,-0.656089521,-0.145428441,0.0355312923,0.0340922509,-0.402156923,0.5256210697,0.8660213873,0.0906190511,-0.164986824,-0.464367011,-0.026993489,0.1099332223,0.2443153482,-1.033175098,-1.02230719,0.4386228215,-0.387614354,-0.856424201,0.1431557379,-0.366802677,1.3275314545,0.433801282) sas.pea <- c(0.805662962,-1.224653252,0.561709108,0.8214000384,0.2209509986,-0.209262363,-1.021143582,0.4569823435,0.7581300884,-0.806596642,-0.844651943,0.6439641857,0.6974581668,1.2823453984,-0.422774515,-0.982890855,-0.623094154,0.8235611613,-1.16479424,0.281861076,0.4179968863,0.0297443378,0.0231596466,0.0165749555,0.3646016562,-0.839437623,-0.135137616,0.1874945339,1.5391887345,-1.394856377,-0.130555057,-0.392925166,0.3076586549,-2.878151335,3.8594029686,-1.234746308,0.6406057401,-0.160785276,0.9461629957,0.1447719799,0.9135507463,-0.091174671,-0.714232232,-0.573954077,-0.229520435,0.009190089,-0.897102959,0.8682789942,-3.066589566,0.9718396658,0.4302546083,1.4153409804,-0.188076354,1.0132837466,-0.075363297,-0.782342484,-0.105434525,-0.300842875,-0.496251225,1.2166797125,0.7147536166,-0.766051488,-0.338517305,-0.29265098,0.6358118792,-0.815764058,-0.359000707,0.097762643,-0.196282124,-0.681187944,0.3605776652,0.6390075601,-1.053984381,0.7301365366,0.2242503101,0.4816997984,0.2387356758,0.2718703556,-0.076662822,0.3381397153,0.1086968349,0.6074209982,-0.420526268,-0.303469962,0.0416445008,0.1167399937,-0.571500228,-0.114736878,0.028032684,0.0296967541,-0.350307033,0.4146927516,0.6832541782,0.0789355824,-0.143715156,-0.366365894,-0.021296719,0.0957595871,0.2128158931,-0.815131373,-0.806557054,0.3820714014,-0.33763943,-0.675682405,0.1129438112,-0.319510993,1.1563734909,0.3422508298) checkEquals(round(as.numeric(resid(fit.R, "conditional", "raw")), 10), sas.raw) checkEquals(round(as.numeric(resid(fit.R, "conditional", "stud")), 10), sas.stu) checkEquals(round(as.numeric(resid(fit.R, "conditional", "pear")), 10), sas.pea) } TF004.ddfm.LMM.unbalanced <- function() { data(dataEP05A2_2) dat2ub <- dataEP05A2_2[-c(11,12,23,32,40,41,42),] fit2ub <- anovaMM(y~day/(run), dat2ub, VarVC.method="scm") L <- getL(fit2ub, c("day1-day2", "day2-day3", "day3-day6", "day14-day20"), "fixef") tst.con <- test.fixef(fit2ub, L=L, ddfm="contain") checkEquals(as.numeric(tst.con[,"DF"]), c(18, 18, 18, 18)) tst.res <- test.fixef(fit2ub, L=L, ddfm="residual") checkEquals(as.numeric(tst.res[,"DF"]), c(53, 53, 53, 53)) tst.satt <- test.fixef(fit2ub, L=L, ddfm="satt") checkEquals(as.numeric(tst.satt[,"DF"]), c(17.83, 17.83, 19.6, 17.83), tolerance=1) } TF005.ddfm.LMM.unbalanced <- function() { data(VCAdata1) datS2 <- VCAdata1[VCAdata1$sample == 2, ] datS2ub <- datS2[-c(15, 32, 33, 60, 62, 63, 64, 65, 74),] fitS2ub <- anovaMM(y~(lot+device)/(day)/(run), datS2ub) L <- getL(fitS2ub, c("lot1-lot2", "device1-device2"), "fixef") tst.con <- test.fixef(fitS2ub, L=L, ddfm="contain") checkEquals(as.numeric(tst.con[,"DF"]), c(58, 58)) tst.res <- test.fixef(fitS2ub, L=L, ddfm="residual") checkEquals(as.numeric(tst.res[,"DF"]), c(238, 238)) fit <- fitS2ub fit$VarCov <- matrix(c(0.004773, -0.00009, -5.14E-6, -0.00009, 0.000211, -0.00002, -5.14E-6, -0.00002, 0.000035), 3, 3) tst.satt <- test.fixef(fit, L=L, ddfm="satt") checkEquals(as.numeric(round(tst.satt[,"DF"], c(1,1))), c(56.4, 55.9), tolerance=0.1) } TF006.stepwiseVCA.fully_nested <- function() { data(VCAdata1) datS7L1 <- VCAdata1[VCAdata1$sample == 7 & VCAdata1$lot == 1, ] fit0 <- anovaVCA(y~device/day/run, datS7L1) Ci <- getMat(fit0, "Ci.MS") tab <- fit0$aov.tab sw.res <- stepwiseVCA(fit0) nr <- nrow(fit0$aov.tab) for(i in 1:length(sw.res)) { checkEquals(sum(fit0$aov.tab[(nr-i):nr, "VC"]), sw.res[[i]]$aov.tab[1,"VC"]) tmpTotDF <- VCA:::SattDF(tab[(nr-i):nr, "MS"], Ci[(nr-i-1):(nr-1), (nr-i-1):(nr-1)], tab[(nr-i):nr, "DF"], "total") checkEquals(tmpTotDF, sw.res[[i]]$aov.tab[1,"DF"]) } } TF007.getL.simple_contrasts <- function() { data(VCAdata1) dat1 <- VCAdata1[VCAdata1$sample==1,] fit <- anovaMM(y~(lot+device)/day/(run), dat1) L <- getL(fit, c("lot1-lot2", "1lot1-1*lot2")) checkEquals(L[1,], L[2,]) tmp <- rep(0,70) tmp[2:3] <- c(1,-1) checkEquals(as.numeric(L[1,]), tmp) } TF008.getL.complex_contrasts <- function() { data(VCAdata1) dat1 <- VCAdata1[VCAdata1$sample==1,] fit <- anovaMM(y~(lot+device)/day/run, dat1) L <- getL(fit, c("lot1:device1:day1-lot1:device1:day2", "lot2:device1:day2-lot3:device1:day4")) L0 <- matrix(0, nrow=2, ncol=ncol(L)) colnames(L0) <- colnames(L) rownames(L0) <- rownames(L) L0[1,c("lot1:device1:day1", "lot1:device1:day2")] <- c(1, -1) L0[2,c("lot2:device1:day2", "lot3:device1:day4")] <- c(1, -1) checkEquals(L, L0) } TF009.getL.complex_contrasts <- function() { data(VCAdata1) dat1 <- VCAdata1[VCAdata1$sample==1,] fit <- anovaMM(y~(lot+device)/day/run, dat1) L <- getL(fit, c("Custom Linear Hypothesis"="0.25lot1-.75*lot2")) checkEquals(as.numeric(L[2:3]), c(.25, -.75)) } TF010.ranef.balanced.nested <- function() { old.opt <- options("scipen" = 21) SASre <- c(0.000201,0.002605,-0.00054,-0.00182,-0.00119,0.000152,0.001162,-0.00122, 0.000293,-0.00087,-0.00009,0.000457,-0.00079,-0.00031,0.001124,0.00062,0.00058,0.000421,-0.00096,0.000188,0.23,1.7866,0.4298,-2.2927,-0.5359,0.3628,0.1836,-1.8719,0.7564,-1.6238,-0.6192,0.7676,-0.3797,-0.7438,-0.09473,0.6637,0.1288,0.5929,-1.4274,0.5381,0.01714,1.4101,-1.0957,0.05366,-0.9255,-0.1757,1.242,0.3798,-0.3971,0.5512,0.5044,-0.2064,-0.5919,0.3678,1.4737,0.09764,0.5825,-0.07603,0.245,-0.3075) digits <- nchar(gsub(".*\\.", "", as.character(SASre))) fit <- anovaVCA(y~day/run, dataEP05A2_1) fit <- solveMME(fit) checkEquals(as.numeric(round(ranef(fit)[,1], digits)), SASre) options(old.opt) } TF011.ranef.balanced.nested <- function() { old.opt <- options("scipen" = 21) SASre <- c(-1.3614,0.9946,-0.3492,2.2449,-1.0212,-0.2419,-0.09628,-1.1657,1.4828,-0.08096,-0.4642,-0.473,-0.2088,0.4715,1.0583,-0.17,-0.07924,-0.1185,0.4657,-0.8874,-1.536,-0.3423,-0.06817,0.5967,0.7873,-0.3391,-0.3554,0.1041,0.07095,-0.03257,-2.3438,1.1429,-0.4562,0.2562,1.6627,-0.9192,-1.2352,-0.6738,0.7737,-0.4168,-0.5393,1.8585,-0.4641,2.8256,-2.3442,-0.02973,0.2087,-1.8812,2.1895,-0.09085,1.6362,-1.864,0.1378,0.4626,-0.04928,0.6601,1.1144,0.4931,-0.06373,-0.9361) digits <- nchar(gsub(".*\\.", "", as.character(SASre))) fit <- anovaVCA(y~day/run, dataEP05A2_2) fit <- solveMME(fit) checkEquals(as.numeric(round(ranef(fit)[,1], digits)), SASre) options(old.opt) } TF012.ranef.balanced.nested <- function() { old.opt <- options("scipen" = 21) SASre <- c(0.6753,-2.1525,0.595,4.8068,1.9164,1.6353,-2.7515,-3.2263,0.2208,1.6819,0.005058,4.8909,0.9292,3.971,-0.2123,-5.0957,-3.8365,-1.7749,-1.7071,-0.5711,0.5098,-0.07488,1.0364,3.7443,0.2138,-1.9382,-2.065,-2.4335,-0.3697,0.008577,0.4418,2.8435,-1.7807,2.4792,2.1879,-0.1801,-1.2571,-0.6198,0.1537,-0.6488,-0.1216,-1.1625,-0.6944,-0.981,0.8879,2.8783,0.4832,0.5788,0.4966,0.9583,-0.4389,-0.03192,2.3149,-0.1964,-2.31,-2.7492,-0.9484,-0.4006,-1.1351,0.3206) digits <- nchar(gsub(".*\\.", "", as.character(SASre))) fit <- anovaVCA(y~day/run, dataEP05A2_3) fit <- solveMME(fit) checkEquals(as.numeric(round(ranef(fit)[,1], digits)), SASre) options(old.opt) } f <- function(x) { nam <- unlist(strsplit(as.character(x[1]), "\\*")) if(x[3] == "_") nam <- paste(nam, sub(" ", "", x[2]), sep="") else nam <- paste(nam, gsub(" ", "", x[2:3]), sep="") nam <- paste(nam, collapse=":") return(nam) } TF013.ranef.unbalanced.nested <- function() { old.opt <- options("scipen" = 21) SASre <- c(-0.04937,-0.6243,0.1375,0.3915,0.2943,0.03382,-0.275,0.3004,-0.06473,0.2177,0.02878,-0.1045,0.07342,0.08029,-0.2658,-0.144,-0.1341,-0.09579,0.2393,-0.03934,0.2539,2.2287,0.3491,-2.3509,-0.7547,0.3425,-2.1535,0.813,-1.8442,-0.6803,0.8489,0.2013,-0.8418,0.04628,0.7644,0.1997,0.6611,-1.6523,0.5696,0.06753,1.8355,-1.244,-0.1982,-1.1615,-0.2202,1.4478,0.198,-0.3916,0.4271,0.493,-0.1683,-0.6793,0.3191,1.6842,0.1732,0.6735,-0.03746,0.09424,-0.3134) digits <- nchar(gsub(".*\\.", "", as.character(SASre))) fit <- anovaVCA(y~day/run, dataEP05A2_1[-c(3,13,21,22,50), ], NegVC=TRUE) fit <- solveMME(fit) checkEquals(as.numeric(round(ranef(fit)[,1], digits)), SASre) options(old.opt) } TF014.ranef.unbalanced.nested <- function() { old.opt <- options("scipen" = 21) SASre <- c(-1.1456,0.6634,0.463,1.9848,-0.8504,-0.1739,-0.04745,-0.9272,0.9797,-0.03415,-0.3668,-0.3744,-0.2066,0.329,0.9548,-0.1114,-0.4822,-0.06678,0.1464,-0.7342,-1.6664,-0.08874,1.0566,0.8392,0.7674,-0.3348,-0.3397,0.01771,0.4464,-0.00412,-2.4289,1.1808,-0.4149,0.03393,1.8452,-0.9296,-0.9685,-0.6712,0.1018,-0.4684,-0.6344,1.4211,-0.1266,3.1471,-2.4752,-0.01445,0.2444,-1.8798,1.5212,-0.06447,1.6922,-1.9328,0.6268,0.07245,0.7058,0.5371,0.1922,-1.0062) digits <- nchar(gsub(".*\\.", "", as.character(SASre))) fit <- anovaVCA(y~day/run, dataEP05A2_2[-c(8, 9, 12, 32, 35, 51, 52, 53, 67, 68, 73), ], NegVC=TRUE) fit <- solveMME(fit) checkEquals(as.numeric(round(ranef(fit)[,1], digits)), SASre) options(old.opt) } TF015.ranef.unbalanced.nested <- function() { old.opt <- options("scipen" = 21) SASre <- c(0.6958,-2.1514,0.3809,4.7516,1.8846,1.4953,-2.7456,-3.3254,0.2027,1.652,0.1019,4.8351,0.9999,3.9225,-0.2269,-5.2604,-3.8218,-1.0984,-1.7096,-0.5828,0.5248,-0.08342,1.068,3.5725,0.2055,-1.9519,-1.9777,-2.2817,-0.3553,0.009593,0.5286,2.7164,-1.7359,2.3667,2.0749,-0.3834,-1.2134,-0.899,0.1355,-0.6235,-0.1364,-1.1175,-0.8554,-0.9202,0.8465,2.7865,0.4451,0.4255,0.4684,0.9125,-0.4717,-0.01747,2.2941,-0.1771,-2.2015,-2.553,-0.9199,0.2859,-1.0898,0.2982) digits <- nchar(gsub(".*\\.", "", as.character(SASre))) fit <- anovaVCA(y~day/run, dataEP05A2_3[-c(1, 11, 21, 31, 41, 51, 61, 71 ), ], NegVC=TRUE) fit <- solveMME(fit) checkEquals(as.numeric(round(ranef(fit)[,1], digits)), SASre) options(old.opt) } TF016.as.matrix.anovaVCA <- function() { data(dataEP05A2_2) fit <- anovaVCA(y~day/run, dataEP05A2_2) checkEquals(c(as.matrix(fit)), c(fit$aov.tab)) } TF017.as.matrix.anovaMM <- function() { data(dataEP05A2_2) fit <- anovaMM(y~day/(run), dataEP05A2_2) checkEquals(c(as.matrix(fit)), c(fit$aov.tab)) } NWformula <- function(input=NULL) { if( is.null(input) ) stop("'input' is NULL, cannot compute Satterthwaite approximation of total degrees of freedom!") out <- input out$DF <- NA out$M <- NA out$a <- NA term1 <- 1 for(i in 1:nrow(out)) { out$DF[i] <- out$N[i]-1 for(j in (i+1):nrow(out)) { if(j > nrow(out)) break else out$DF[i] <- out$DF[i] * out$N[j] } if(i == 1) out$M[i] <- out$VC[i] else { n <- 1 for(j in 1:(i-1)) n <- n * out$N[j] out$M[i] <- out$VC[i]*n + out$M[i-1] } if(i < nrow(out)) { out$a[i] <- term1 * (1-1/out$N[i]) term1 <- term1*(1/out$N[i]) } else out$a[i] <- term1 } DFtotal <- eval(parse(text=paste(paste(out$N, collapse="*"), "-1", sep=""))) numer <- 0 denom <- 0 for(i in 1:nrow(out)) { numer <- numer + out$a[i] * out$M[i] denom <- denom + (out$a[i] * out$M[i])^2 / out$DF[i] } DFsatt <- numer^2 / denom return(DFsatt) } data(VCAdata1) datS1 <- VCAdata1[VCAdata1$sample==1,] TF018.SattDF_total_vs_Neter_Wasserman <- function() { fit <- anovaVCA(y~day/run, datS1) input <- data.frame(VC=rev(fit$aov.tab[-1,"VC"]), N=c(6,2,21)) NWdf <- NWformula(input) checkEquals(NWdf, fit$aov.tab[1,"DF"]) } TF019.SattDF_total_vs_Neter_Wasserman <- function() { fit <- anovaVCA(y~device/day/run, datS1) input <- data.frame(VC=rev(fit$aov.tab[-1,"VC"]), N=c(6,2,7,3)) NWdf <- NWformula(input) checkEquals(NWdf, fit$aov.tab[1,"DF"]) } TF020.SattDF_total_vs_Neter_Wasserman <- function() { fit <- anovaVCA(y~lot/device/day/run, datS1) input <- data.frame(VC=rev(fit$aov.tab[-1,"VC"]), N=c(2,2,7,3,3)) NWdf <- NWformula(input) checkEquals(NWdf, fit$aov.tab[1,"DF"], tol=1e-7) } TF021.lsmeans.balanced <- function() { data(VCAdata1) datS1 <- VCAdata1[VCAdata1$sample == 1, ] fit <- anovaMM(y~(lot+device)/(day)/(run), datS1) lsm <- lsmeans(fit, type="c", ddfm="cont") checkEquals(round(as.numeric(lsm[,"Estimate"]), 4), c(2.8138, 2.5507, 2.6719, 2.7887, 2.7136, 2.5341)) checkEquals(round(as.numeric(lsm[,"SE"]), 5), rep(0.04266, 6)) checkEquals(round(as.numeric(lsm[,"DF"]), 5), rep(58, 6)) checkEquals(round(as.numeric(lsm[,"t Value"]), 2), c(65.96, 59.79, 62.64, 65.37, 63.61, 59.41)) } TF022.lsmeans.unbalanced <- function() { data(VCAdata1) datS1 <- VCAdata1[VCAdata1$sample == 1, ] datS1ub <- datS1[-c(1,11,12,20,55,56,57,103,121,122,179),] fit <- anovaMM(y~(lot+device)/(day)/(run), datS1ub) lsm <- lsmeans(fit) checkEquals(round(as.numeric(lsm[,"Estimate"]), 4), c(2.8062, 2.5549, 2.6718, 2.7778, 2.7207, 2.5343)) checkEquals(round(as.numeric(lsm[,"SE"]), 5), c(0.04106, 0.04062, 0.04019, 0.04063, 0.04105, 0.04019)) } TF023.ddfm_fixef.all_methods.Orthodont.balanced <- function() { data(Orthodont) Ortho <- Orthodont Ortho$age2 <- Ortho$age - 11 fit.Ortho <- anovaMM(distance~Sex+Sex:age2+(Subject)+(Subject):age2-1, Ortho) L <- getL(fit.Ortho, "SexMale-SexFemale", "fixef") tst.con <- test.fixef(fit.Ortho, L=L, ddfm="contain") checkEquals(as.numeric(tst.con[,"DF"]), 54) tst.res <- test.fixef(fit.Ortho, L=L, ddfm="residual") checkEquals(as.numeric(tst.res[,"DF"]), 104) fit <- fit.Ortho fit$VarCov <- matrix(c(1.1494, 0.001364, -0.02727, 0.001364, 0.001393, -0.00545, -0.02727, -0.00545, 0.1091), 3, 3) tst.satt <- test.fixef(fit, L=L, ddfm="satt") checkEquals(as.numeric(tst.satt[,"DF"]), 25, tolerance=0.1) } TF024.ddfm_lsmeans.all_methods.Orthodont.unbalanced <- function() { data(Orthodont) Ortho <- Orthodont Ortho$age2 <- Ortho$age - 11 Ortho.ub <- Ortho[-c(5,7,23,33,51,72,73,74,90),] fit.Ortho <- anovaMM(distance~Sex+Sex:age2+(Subject)+(Subject):age2-1, Ortho.ub) L <- getL(fit.Ortho, "SexMale-SexFemale", "lsmeans") tst.con <- test.lsmeans(fit.Ortho, L=L, ddfm="contain") checkEquals(as.numeric(tst.con[,"DF"]), 45) tst.res <- test.lsmeans(fit.Ortho, L=L, ddfm="residual") checkEquals(as.numeric(tst.res[,"DF"]), 95) fit <- fit.Ortho fit$VarCov <- matrix(c(1.4381, 0.002238, -0.05008, 0.002238, 0.001532, -0.00800, -0.05008, -0.00800, 0.1572), 3, 3) tst.satt <- test.lsmeans(fit, L=L, ddfm="satt") checkEquals(round(as.numeric(tst.satt[,"DF"]),2), 23.35, tolerance=0.1) } TF025.lsmeans.including_covariate <- function() { data(VCAdata1) datS1 <- VCAdata1[VCAdata1$sample == 1, ] set.seed(20140608) datS1$cov <- 20 + rnorm(252) fit <- anovaMM(y~device+day:cov+device:(run), datS1) lsm <- lsmeans(fit, "device") checkEquals( round(as.numeric(lsm[,"Estimate"]), 4), c(2.8773, 1.8635, 3.2976) ) } TF026.lsmeans.complex_model.including_covariate <- function() { data(VCAdata1) datS1 <- VCAdata1[VCAdata1$sample == 1, ] set.seed(20140608) datS1$cov <- 20 + rnorm(252) fit <- anovaMM(y~lot+device+day:cov+lot:device:day+lot:device:day:(run), datS1) lsm <- lsmeans(fit, c("lot", "device")) checkEquals( round(as.numeric(lsm[,"Estimate"]), 4), c(2.8143, 2.5496, 2.6720, 2.7762, 2.7380, 2.5217) ) } TF027.anovaVCA.by_processing <- function() { data(CA19_9) fit.lst <- anovaVCA(result~site/day, CA19_9, by="sample") samples <- gsub("sample\\.", "",names(fit.lst)) for(i in 1:length(fit.lst)) { tmp.fit <- anovaVCA(result~site/day, CA19_9[CA19_9$sample == samples[i],]) checkEquals(fit.lst[[i]]$aov.tab, tmp.fit$aov.tab) } } TF028.anovaMM.by_processing <- function() { data(CA19_9) fit.lst <- anovaMM(result~site/(day), CA19_9, by="sample") samples <- gsub("sample\\.", "",names(fit.lst)) for(i in 1:length(fit.lst)) { tmp.fit <- anovaMM(result~site/(day), CA19_9[CA19_9$sample == samples[i],]) print(checkEquals(fit.lst[[i]]$aov.tab, tmp.fit$aov.tab)) } } TF029.anovaVCA.by_processing <- function() { data(CA19_9) fit.lst <- anovaVCA(result~site/day, CA19_9, by="sample") samples <- gsub("sample\\.", "",names(fit.lst)) inf.lst <- VCAinference(fit.lst) for(i in 1:length(fit.lst)) { tmp.fit <- anovaVCA(result~site/day, CA19_9[CA19_9$sample == samples[i],]) tmp.inf <- VCAinference(tmp.fit) checkEquals(inf.lst[[i]]$VCAobj$aov.tab, tmp.inf$VCAobj$aov.tab) checkEquals(inf.lst[[i]]$ConfInt, tmp.inf$ConfInt) } } TF030.anovaVCA.by_processing <- function() { data(CA19_9) fit.lst <- anovaVCA(result~site/day, CA19_9, by="sample") samples <- gsub("sample\\.", "",names(fit.lst)) total.specs <- c(1, 3, 5, 30, 80, 200) error.specs <- c(.5, 2, 2, 5, 50, 75) inf.lst <- VCAinference(fit.lst, total.claim=total.specs, error.claim=error.specs) for(i in 1:length(fit.lst)) { tmp.fit <- anovaVCA(result~site/day, CA19_9[CA19_9$sample == samples[i],]) tmp.inf <- VCAinference(tmp.fit, total.claim=total.specs[i], error.claim=error.specs[i]) checkEquals(inf.lst[[i]]$VCAobj$aov.tab, tmp.inf$VCAobj$aov.tab) } } TF031.test.lsmeans <- function() { data(dataEP05A2_1) fit <- anovaMM(y~day/(run), dataEP05A2_1) lc.mat <- getL(fit, "day19-day20", "lsm") res <- test.lsmeans(fit, lc.mat) checkEquals(as.numeric(round(res, 6)), c(-1.220903, 20, 1.523546, -0.801356, 0.432343)) } TF032.ANOVA_vs_REML.residuals.raw <- function() { data(dataEP05A2_1) fit1.aov <- anovaVCA(y~day/run, dataEP05A2_1) fit1.reml <- remlVCA(y~day/run, dataEP05A2_1) checkEquals(round(resid(fit1.aov), 4), round(resid(fit1.reml), 4)) data(dataEP05A2_2) fit2.aov <- anovaVCA(y~day/run, dataEP05A2_2) fit2.reml <- remlVCA(y~day/run, dataEP05A2_2) checkEquals(round(resid(fit2.aov), 6), round(resid(fit2.reml), 6)) data(dataEP05A2_3) fit3.aov <- anovaVCA(y~day/run, dataEP05A2_3) fit3.reml <- remlVCA(y~day/run, dataEP05A2_3) checkEquals(round(resid(fit3.aov), 4), round(resid(fit3.reml), 4)) data(Orthodont) Ortho <- Orthodont Ortho$age2 <- Ortho$age - 11 Ortho$Subject <- factor(as.character(Ortho$Subject)) fit.anovaMM <- anovaMM(distance~Sex+Sex:age2+(Subject)+(Subject):age2, Ortho) fit.remlMM <- remlMM(distance~Sex+Sex:age2+(Subject)+(Subject):age2, Ortho, cov=FALSE) checkEquals(round(resid(fit.anovaMM), 4), round(resid(fit.remlMM), 4)) } TF033.ANOVA_vs_REML.residuals.studentized <- function() { data(dataEP05A2_1) fit1.aov <- anovaVCA(y~day/run, dataEP05A2_1) fit1.reml <- remlVCA(y~day/run, dataEP05A2_1) checkEquals(round(resid(fit1.aov, mode="student"), 4), round(resid(fit1.reml, mode="student"), 4)) data(dataEP05A2_2) fit2.aov <- anovaVCA(y~day/run, dataEP05A2_2) fit2.reml <- remlVCA(y~day/run, dataEP05A2_2) checkEquals(round(resid(fit2.aov, mode="student"), 5), round(resid(fit2.reml, mode="student"), 5)) data(dataEP05A2_3) fit3.aov <- anovaVCA(y~day/run, dataEP05A2_3) fit3.reml <- remlVCA(y~day/run, dataEP05A2_3) checkEquals(round(resid(fit3.aov, mode="student"), 4), round(resid(fit3.reml, mode="student"), 4)) data(Orthodont) Ortho <- Orthodont Ortho$age2 <- Ortho$age - 11 Ortho$Subject <- factor(as.character(Ortho$Subject)) fit.anovaMM <- anovaMM(distance~Sex+Sex:age2+(Subject)+(Subject):age2, Ortho) fit.remlMM <- remlMM(distance~Sex+Sex:age2+(Subject)+(Subject):age2, Ortho, cov=FALSE) checkEquals(round(resid(fit.anovaMM, mode="student"), 4), round(resid(fit.remlMM, mode="student"), 4)) } TF034.ANOVA_vs_REML.residuals.pearson <- function() { data(dataEP05A2_1) fit1.aov <- anovaVCA(y~day/run, dataEP05A2_1) fit1.reml <- remlVCA(y~day/run, dataEP05A2_1) checkEquals(round(resid(fit1.aov, mode="pearson"), 4), round(resid(fit1.reml, mode="pearson"), 4)) data(dataEP05A2_2) fit2.aov <- anovaVCA(y~day/run, dataEP05A2_2) fit2.reml <- remlVCA(y~day/run, dataEP05A2_2) checkEquals(round(resid(fit2.aov, mode="pearson"), 6), round(resid(fit2.reml, mode="pearson"), 6)) data(dataEP05A2_3) fit3.aov <- anovaVCA(y~day/run, dataEP05A2_3) fit3.reml <- remlVCA(y~day/run, dataEP05A2_3) checkEquals(round(resid(fit3.aov, mode="pearson"), 4), round(resid(fit3.reml, mode="pearson"), 4)) data(Orthodont) Ortho <- Orthodont Ortho$age2 <- Ortho$age - 11 Ortho$Subject <- factor(as.character(Ortho$Subject)) fit.anovaMM <- anovaMM(distance~Sex+Sex:age2+(Subject)+(Subject):age2, Ortho) fit.remlMM <- remlMM(distance~Sex+Sex:age2+(Subject)+(Subject):age2, Ortho, cov=FALSE) checkEquals(round(resid(fit.anovaMM, mode="pearson"), 4), round(resid(fit.remlMM, mode="pearson"), 4)) } TF035.ANOVA_vs_REML.residuals.standardized <- function() { data(dataEP05A2_1) fit1.aov <- anovaVCA(y~day/run, dataEP05A2_1) fit1.reml <- remlVCA(y~day/run, dataEP05A2_1) checkEquals(round(resid(fit1.aov, mode="standard"), 4), round(resid(fit1.reml, mode="standard"), 4)) data(dataEP05A2_2) fit2.aov <- anovaVCA(y~day/run, dataEP05A2_2) fit2.reml <- remlVCA(y~day/run, dataEP05A2_2) checkEquals(round(resid(fit2.aov, mode="standard"), 6), round(resid(fit2.reml, mode="standard"), 6)) data(dataEP05A2_3) fit3.aov <- anovaVCA(y~day/run, dataEP05A2_3) fit3.reml <- remlVCA(y~day/run, dataEP05A2_3) checkEquals(round(resid(fit3.aov, mode="standard"), 4), round(resid(fit3.reml, mode="standard"), 4)) data(Orthodont) Ortho <- Orthodont Ortho$age2 <- Ortho$age - 11 Ortho$Subject <- factor(as.character(Ortho$Subject)) fit.anovaMM <- anovaMM(distance~Sex+Sex:age2+(Subject)+(Subject):age2, Ortho) fit.remlMM <- remlMM(distance~Sex+Sex:age2+(Subject)+(Subject):age2, Ortho, cov=FALSE) checkEquals(round(resid(fit.anovaMM, mode="standard"), 4), round(resid(fit.remlMM, mode="standard"), 4)) } TF036.ANOVA_vs_REML.ranef.raw <- function() { data(dataEP05A2_1) fit1.aov <- anovaVCA(y~day/run, dataEP05A2_1) fit1.reml <- remlVCA(y~day/run, dataEP05A2_1) re.aov <- ranef(fit1.aov, mode="raw") re.reml <- ranef(fit1.reml, mode="raw") re.reml <- re.reml[rownames(re.aov),,drop=FALSE] checkEquals(round(re.aov[,1], 4), round(re.reml[,1], 4)) data(dataEP05A2_2) fit2.aov <- anovaVCA(y~day/run, dataEP05A2_2) fit2.reml <- remlVCA(y~day/run, dataEP05A2_2) re.aov <- ranef(fit2.aov, mode="raw") re.reml <- ranef(fit2.reml, mode="raw") re.reml <- re.reml[rownames(re.aov),,drop=FALSE] checkEquals(round(re.aov[,1], 4), round(re.reml[,1], 4)) data(dataEP05A2_3) fit3.aov <- anovaVCA(y~day/run, dataEP05A2_3) fit3.reml <- remlVCA(y~day/run, dataEP05A2_3) re.aov <- ranef(fit3.aov, mode="raw") re.reml <- ranef(fit3.reml, mode="raw") re.reml <- re.reml[rownames(re.aov),,drop=FALSE] checkEquals(round(re.aov[,1], 4), round(re.reml[,1], 4)) data(Orthodont) Ortho <- Orthodont Ortho$age2 <- Ortho$age - 11 Ortho$Subject <- factor(as.character(Ortho$Subject)) fit.anovaMM <- anovaMM(distance~Sex+Sex:age2+(Subject)+(Subject):age2, Ortho) fit.remlMM <- remlMM(distance~Sex+Sex:age2+(Subject)+(Subject):age2, Ortho, cov=FALSE) re.aov <- ranef(fit.anovaMM, mode="raw") re.reml <- ranef(fit.remlMM, mode="raw") re.reml <- re.reml[rownames(re.aov),,drop=FALSE] checkEquals(round(re.aov[,1], 4), round(re.reml[,1], 4)) } TF037.ANOVA_vs_REML.ranef.studentized <- function() { data(dataEP05A2_1) fit1.aov <- anovaVCA(y~day/run, dataEP05A2_1) fit1.reml <- remlVCA(y~day/run, dataEP05A2_1) re.aov <- ranef(fit1.aov, mode="student") re.reml <- ranef(fit1.reml, mode="student") re.reml <- re.reml[rownames(re.aov),,drop=FALSE] checkEquals(round(re.aov[,1], 4), round(re.reml[,1], 4)) data(dataEP05A2_2) fit2.aov <- anovaVCA(y~day/run, dataEP05A2_2) fit2.reml <- remlVCA(y~day/run, dataEP05A2_2) re.aov <- ranef(fit2.aov, mode="student") re.reml <- ranef(fit2.reml, mode="student") re.reml <- re.reml[rownames(re.aov),,drop=FALSE] checkEquals(round(re.aov[,1], 4), round(re.reml[,1], 4)) data(dataEP05A2_3) fit3.aov <- anovaVCA(y~day/run, dataEP05A2_3) fit3.reml <- remlVCA(y~day/run, dataEP05A2_3) re.aov <- ranef(fit3.aov, mode="student") re.reml <- ranef(fit3.reml, mode="student") re.reml <- re.reml[rownames(re.aov),,drop=FALSE] checkEquals(round(re.aov[,1], 4), round(re.reml[,1], 4)) data(Orthodont) Ortho <- Orthodont Ortho$age2 <- Ortho$age - 11 Ortho$Subject <- factor(as.character(Ortho$Subject)) fit.anovaMM <- anovaMM(distance~Sex+Sex:age2+(Subject)+(Subject):age2, Ortho) fit.remlMM <- remlMM(distance~Sex+Sex:age2+(Subject)+(Subject):age2, Ortho, cov=FALSE) re.aov <- ranef(fit.anovaMM, mode="student") re.reml <- ranef(fit.remlMM, mode="student") re.reml <- re.reml[rownames(re.aov),,drop=FALSE] checkEquals(round(re.aov[,1], 4), round(re.reml[,1], 4)) } TF038.ANOVA_vs_REML.ranef.standardized <- function() { data(dataEP05A2_1) fit1.aov <- anovaVCA(y~day/run, dataEP05A2_1) fit1.reml <- remlVCA(y~day/run, dataEP05A2_1) re.aov <- ranef(fit1.aov, mode="standard") re.reml <- ranef(fit1.reml, mode="standard") re.reml <- re.reml[rownames(re.aov),,drop=FALSE] checkEquals(round(re.aov[,1], 4), round(re.reml[,1], 4)) data(dataEP05A2_2) fit2.aov <- anovaVCA(y~day/run, dataEP05A2_2) fit2.reml <- remlVCA(y~day/run, dataEP05A2_2) re.aov <- ranef(fit2.aov, mode="standard") re.reml <- ranef(fit2.reml, mode="standard") re.reml <- re.reml[rownames(re.aov),,drop=FALSE] checkEquals(round(re.aov[,1], 4), round(re.reml[,1], 4)) data(dataEP05A2_3) fit3.aov <- anovaVCA(y~day/run, dataEP05A2_3) fit3.reml <- remlVCA(y~day/run, dataEP05A2_3) re.aov <- ranef(fit3.aov, mode="standard") re.reml <- ranef(fit3.reml, mode="standard") re.reml <- re.reml[rownames(re.aov),,drop=FALSE] checkEquals(round(re.aov[,1], 4), round(re.reml[,1], 4)) data(Orthodont) Ortho <- Orthodont Ortho$age2 <- Ortho$age - 11 Ortho$Subject <- factor(as.character(Ortho$Subject)) fit.anovaMM <- anovaMM(distance~Sex+Sex:age2+(Subject)+(Subject):age2, Ortho) fit.remlMM <- remlMM(distance~Sex+Sex:age2+(Subject)+(Subject):age2, Ortho, cov=FALSE) re.aov <- ranef(fit.anovaMM, mode="standard") re.reml <- ranef(fit.remlMM, mode="standard") re.reml <- re.reml[rownames(re.aov),,drop=FALSE] checkEquals(round(re.aov[,1], 4), round(re.reml[,1], 4)) } TF039.remlVCA.by_processing <- function() { data(CA19_9) fit.lst <- remlVCA(result~site/day, CA19_9, by="sample") samples <- gsub("sample\\.", "",names(fit.lst)) total.specs <- c(1, 3, 5, 30, 80, 200) error.specs <- c(.5, 2, 2, 5, 50, 75) inf.lst <- VCAinference(fit.lst, total.claim=total.specs, error.claim=error.specs) for(i in 1:length(fit.lst)) { tmp.fit <- remlVCA(result~site/day, CA19_9[CA19_9$sample == samples[i],]) tmp.inf <- VCAinference(tmp.fit, total.claim=total.specs[i], error.claim=error.specs[i]) checkEquals(inf.lst[[i]]$VCAobj$aov.tab, tmp.inf$VCAobj$aov.tab) checkEquals(inf.lst[[i]]$ConfInt, tmp.inf$ConfInt) } } TF040.remlMM.by_processing <- function() { data(CA19_9) fit.lst <- remlMM(result~(site)/day, CA19_9, by="sample") samples <- gsub("sample\\.", "",names(fit.lst)) total.specs <- c(1, 3, 5, 30, 80, 200) error.specs <- c(.5, 2, 2, 5, 50, 75) inf.lst <- VCAinference(fit.lst, total.claim=total.specs, error.claim=error.specs) for(i in 1:length(fit.lst)) { tmp.fit <- remlMM(result~(site)/day, CA19_9[CA19_9$sample == samples[i],]) tmp.inf <- VCAinference(tmp.fit, total.claim=total.specs[i], error.claim=error.specs[i]) print(checkEquals(inf.lst[[i]]$VCAobj$aov.tab, tmp.inf$VCAobj$aov.tab)) checkEquals(inf.lst[[i]]$ConfInt, tmp.inf$ConfInt) } } TF041.REML.test.lsmeans <- function() { data(dataEP05A2_1) fit <- remlMM(y~day/(run), dataEP05A2_1) lc.mat <- getL(fit, "day19-day20", "lsm") res <- test.lsmeans(fit, lc.mat) checkEquals(round(as.numeric(res),7), c( -1.2209032, 20, 1.5235456, -0.8013565, 0.4323434)) } TF042.balancedness.ordered_vs_unordered <- function() { data(dataEP05A2_1) dat <- dataEP05A2_1 dat <- dat[sample(1:nrow(dat)),] fit1 <- anovaVCA(y~day/run, dat) fit2 <- remlVCA(y~day/run, dat) fit3 <- anovaMM(y~day/(run), dat) fit4 <- remlMM(y~day/(run), dat) checkEquals(fit1$balanced, "balanced") checkEquals(fit2$balanced, "balanced") checkEquals(fit3$balanced, "balanced") checkEquals(fit4$balanced, "balanced") } load(file=file.path(R.home(), "library/VCA/UnitTests/LSMeans_Data.RData")) fit.vca <- remlMM(y~snp+time+snp:time+sex+(id)+(id):time, dat,VarVC=F) TF043.LSMeans.atCovarLevel <- function() { lsm <- lsmeans(fit.vca, var="snp", at=list(time=1:4)) checkEquals(as.numeric(round(lsm[-c(1,2),"Estimate"],2)), c(4.89, 5.01, 5.80, 5.92, 6.71, 6.83, 7.62, 7.75)) } TF044.LSMeans.atCovarLevel <- function() { lsm <- lsmeans(fit.vca, var="snp", at=list(tim=1:4)) checkEquals(nrow(lsm), 2) } TF045.LSMeans.atCovarLevel <- function() { lsm1 <- lsmeans(fit.vca, var="snp", at=list(sex=c(Male=.3, Female=.6))) checkEquals(nrow(lsm1), 2) lsm2 <- lsmeans(fit.vca, var="snp", at=list(sex=c(Male=.5, Female=.6))) checkEquals(nrow(lsm2), 2) } TF046.model.terms <- function() { data(dataEP05A2_1) checkException(anovaMM(y~(a)+.b:y, dataEP05A2_1)) checkException(remlMM(y~(a)+.b:y, dataEP05A2_1)) fit0 <- anovaVCA(y~day/run, dataEP05A2_1) dat <- dataEP05A2_1 dat$day.var <- dat$day checkEquals(as.numeric(anovaVCA(y~day.var/run, dat)$aov.tab[,"VC"]), as.numeric(fit0$aov.tab[,"VC"]), tolerance=1e-8) checkEquals(as.numeric(anovaMM(y~(day.var)/(run), dat)$aov.tab[,"VC"]), as.numeric(fit0$aov.tab[,"VC"]), tolerance=1e-8) checkEquals(as.numeric(remlMM(y~(day.var)/(run), dat)$aov.tab[,"VC"]), as.numeric(fit0$aov.tab[,"VC"]), tolerance=1e-7) checkEquals(as.numeric(remlVCA(y~day.var/run, dat)$aov.tab[,"VC"]), as.numeric(fit0$aov.tab[,"VC"]), tolerance=1e-7) } TF047.as.matrix.VCA.REML <- function() { data(dataEP05A2_1) fit1 <- remlVCA(y~day/run, dataEP05A2_1) mat1 <- as.matrix(fit1) checkEquals( fit1$aov.tab[,"DF"], as.numeric(mat1[,"DF"])) checkEquals( fit1$aov.tab[,"VC"], as.numeric(mat1[,"VC"])) checkEquals( fit1$aov.tab[,"%Total"], as.numeric(mat1[,"%Total"])) checkEquals( fit1$aov.tab[,"SD"], as.numeric(mat1[,"SD"])) checkEquals( fit1$aov.tab[,"CV[%]"], as.numeric(mat1[,"CV[%]"])) checkEquals( fit1$aov.tab[,"Var(VC)"], as.numeric(mat1[,"Var(VC)"])) fit2 <- remlMM(y~day/(run), dataEP05A2_1) mat2 <- as.matrix(fit2) checkEquals( fit2$aov.tab[,"DF"], as.numeric(mat2[,"DF"])) checkEquals( fit2$aov.tab[,"VC"], as.numeric(mat2[,"VC"])) checkEquals( fit2$aov.tab[,"%Total"], as.numeric(mat2[,"%Total"])) checkEquals( fit2$aov.tab[,"SD"], as.numeric(mat2[,"SD"])) checkEquals( fit2$aov.tab[,"CV[%]"], as.numeric(mat2[,"CV[%]"])) checkEquals( fit2$aov.tab[,"Var(VC)"], as.numeric(mat2[,"Var(VC)"])) } TF048.as.matrix.VCAinference.REML <- function() { data(dataEP05A2_2) fit.reml <- remlVCA(y~day/run, dataEP05A2_2) inf.reml <- VCAinference(fit.reml) VC.mat <- as.matrix(inf.reml, what="VC", digits=12) SD.mat <- as.matrix(inf.reml, what="SD", digits=12) CV.mat <- as.matrix(inf.reml, what="CV", digits=12) checkEquals(as.numeric(fit.reml$aov.tab[,"VC"]), as.numeric(VC.mat[,"Estimate"])) checkEquals(as.numeric(inf.reml$ConfInt$VC$OneSided[,"LCL"]), as.numeric(VC.mat[,"One-Sided LCL"])) checkEquals(as.numeric(inf.reml$ConfInt$VC$OneSided[,"UCL"]), as.numeric(VC.mat[,"One-Sided UCL"])) checkEquals(as.numeric(inf.reml$ConfInt$VC$TwoSided[,"LCL"]), as.numeric(VC.mat[,"CI LCL"])) checkEquals(as.numeric(inf.reml$ConfInt$VC$TwoSided[,"UCL"]), as.numeric(VC.mat[,"CI UCL"])) checkEquals(as.numeric(fit.reml$aov.tab[,"SD"]), as.numeric(SD.mat[,"Estimate"])) checkEquals(as.numeric(inf.reml$ConfInt$SD$OneSided[,"LCL"]), as.numeric(SD.mat[,"One-Sided LCL"])) checkEquals(as.numeric(inf.reml$ConfInt$SD$OneSided[,"UCL"]), as.numeric(SD.mat[,"One-Sided UCL"])) checkEquals(as.numeric(inf.reml$ConfInt$SD$TwoSided[,"LCL"]), as.numeric(SD.mat[,"CI LCL"])) checkEquals(as.numeric(inf.reml$ConfInt$SD$TwoSided[,"UCL"]), as.numeric(SD.mat[,"CI UCL"])) checkEquals(as.numeric(fit.reml$aov.tab[,"CV[%]"]), as.numeric(CV.mat[,"Estimate"])) checkEquals(as.numeric(inf.reml$ConfInt$CV$OneSided[,"LCL"]), as.numeric(CV.mat[,"One-Sided LCL"])) checkEquals(as.numeric(inf.reml$ConfInt$CV$OneSided[,"UCL"]), as.numeric(CV.mat[,"One-Sided UCL"])) checkEquals(as.numeric(inf.reml$ConfInt$CV$TwoSided[,"LCL"]), as.numeric(CV.mat[,"CI LCL"])) checkEquals(as.numeric(inf.reml$ConfInt$CV$TwoSided[,"UCL"]), as.numeric(CV.mat[,"CI UCL"])) mat.list <- as.matrix(inf.reml, digits=12) checkEquals(VC.mat, mat.list[[1]]) checkEquals(SD.mat, mat.list[[2]]) checkEquals(CV.mat, mat.list[[3]]) } TF049.as.matrix.VCAinference.ANOVA <- function() { data(dataEP05A2_3) fit.anova <- anovaVCA(y~day/run, dataEP05A2_3) inf.anova <- VCAinference(fit.anova, VarVC=FALSE) VC.mat <- as.matrix(inf.anova, what="VC", digits=12) SD.mat <- as.matrix(inf.anova, what="SD", digits=12) CV.mat <- as.matrix(inf.anova, what="CV", digits=12) checkEquals(as.numeric(fit.anova$aov.tab[,"VC"]), as.numeric(VC.mat[,"Estimate"])) checkEquals(as.numeric(inf.anova$ConfInt$VC$OneSided[,"LCL"]), as.numeric(VC.mat[,"One-Sided LCL"])) checkEquals(as.numeric(inf.anova$ConfInt$VC$OneSided[,"UCL"]), as.numeric(VC.mat[,"One-Sided UCL"])) checkEquals(as.numeric(inf.anova$ConfInt$VC$TwoSided[,"LCL"]), as.numeric(VC.mat[,"CI LCL"])) checkEquals(as.numeric(inf.anova$ConfInt$VC$TwoSided[,"LCL"]), as.numeric(VC.mat[,"CI LCL"])) checkEquals(as.numeric(fit.anova$aov.tab[,"SD"]), as.numeric(SD.mat[,"Estimate"])) checkEquals(as.numeric(inf.anova$ConfInt$SD$OneSided[,"LCL"]), as.numeric(SD.mat[,"One-Sided LCL"])) checkEquals(as.numeric(inf.anova$ConfInt$SD$OneSided[,"UCL"]), as.numeric(SD.mat[,"One-Sided UCL"])) checkEquals(as.numeric(inf.anova$ConfInt$SD$TwoSided[,"LCL"]), as.numeric(SD.mat[,"CI LCL"])) checkEquals(as.numeric(inf.anova$ConfInt$SD$TwoSided[,"LCL"]), as.numeric(SD.mat[,"CI LCL"])) checkEquals(as.numeric(fit.anova$aov.tab[,"CV[%]"]), as.numeric(CV.mat[,"Estimate"])) checkEquals(as.numeric(inf.anova$ConfInt$CV$OneSided[,"LCL"]), as.numeric(CV.mat[,"One-Sided LCL"])) checkEquals(as.numeric(inf.anova$ConfInt$CV$OneSided[,"UCL"]), as.numeric(CV.mat[,"One-Sided UCL"])) checkEquals(as.numeric(inf.anova$ConfInt$CV$TwoSided[,"LCL"]), as.numeric(CV.mat[,"CI LCL"])) checkEquals(as.numeric(inf.anova$ConfInt$CV$TwoSided[,"LCL"]), as.numeric(CV.mat[,"CI LCL"])) inf.anova <- VCAinference(fit.anova, VarVC=TRUE) VC.mat <- as.matrix(inf.anova, what="VC", digits=12) SD.mat <- as.matrix(inf.anova, what="SD", digits=12) CV.mat <- as.matrix(inf.anova, what="CV", digits=12) checkEquals(as.numeric(fit.anova$aov.tab[,"VC"]), as.numeric(VC.mat[,"Estimate"])) checkEquals(as.numeric(inf.anova$ConfInt$VC$OneSided[,"LCL"]), as.numeric(VC.mat[,"One-Sided LCL"])) checkEquals(as.numeric(inf.anova$ConfInt$VC$OneSided[,"UCL"]), as.numeric(VC.mat[,"One-Sided UCL"])) checkEquals(as.numeric(inf.anova$ConfInt$VC$TwoSided[,"LCL"]), as.numeric(VC.mat[,"CI LCL"])) checkEquals(as.numeric(inf.anova$ConfInt$VC$TwoSided[,"LCL"]), as.numeric(VC.mat[,"CI LCL"])) checkEquals(as.numeric(fit.anova$aov.tab[,"SD"]), as.numeric(SD.mat[,"Estimate"])) checkEquals(as.numeric(inf.anova$ConfInt$SD$OneSided[,"LCL"]), as.numeric(SD.mat[,"One-Sided LCL"])) checkEquals(as.numeric(inf.anova$ConfInt$SD$OneSided[,"UCL"]), as.numeric(SD.mat[,"One-Sided UCL"])) checkEquals(as.numeric(inf.anova$ConfInt$SD$TwoSided[,"LCL"]), as.numeric(SD.mat[,"CI LCL"])) checkEquals(as.numeric(inf.anova$ConfInt$SD$TwoSided[,"LCL"]), as.numeric(SD.mat[,"CI LCL"])) checkEquals(as.numeric(fit.anova$aov.tab[,"CV[%]"]), as.numeric(CV.mat[,"Estimate"])) checkEquals(as.numeric(inf.anova$ConfInt$CV$OneSided[,"LCL"]), as.numeric(CV.mat[,"One-Sided LCL"])) checkEquals(as.numeric(inf.anova$ConfInt$CV$OneSided[,"UCL"]), as.numeric(CV.mat[,"One-Sided UCL"])) checkEquals(as.numeric(inf.anova$ConfInt$CV$TwoSided[,"LCL"]), as.numeric(CV.mat[,"CI LCL"])) checkEquals(as.numeric(inf.anova$ConfInt$CV$TwoSided[,"LCL"]), as.numeric(CV.mat[,"CI LCL"])) } TF050.lmerSummary <- function() { data(VCAdata1) fit0 <- remlVCA(y~(device+lot)/day/run, subset(VCAdata1, sample==5)) fit1 <- lme4:::lmer(y~(1|device)+(1|lot)+(1|device:lot:day)+(1|device:lot:day:run), subset(VCAdata1, sample==5), control=lme4:::lmerControl(optimizer="bobyqa")) sum1 <- lmerSummary(fit1, tab.only=TRUE) sum1 <- sum1[rownames(fit0$aov.tab),] checkEquals(as.numeric(fit0$aov.tab[,"VC"]), as.numeric(sum1[,"VC"]), tolerance=1e-5) checkEquals(as.numeric(fit0$aov.tab[,"%Total"]), as.numeric(sum1[,"%Total"]), tolerance=1e-5) checkEquals(as.numeric(fit0$aov.tab[,"SD"]), as.numeric(sum1[,"SD"]), tolerance=1e-6) checkEquals(as.numeric(fit0$aov.tab[,"CV[%]"]), as.numeric(sum1[,"CV[%]"]), tolerance=1e-6) } TF051.Scale.reScale.anovaVCA <- function() { data(VCAdata1) scaled.fits <- Scale("anovaVCA", y~(device+lot)/day/run, VCAdata1, by="sample") reference.fits <- anovaVCA(y~(device+lot)/day/run, VCAdata1, by="sample") scaled.infs <- VCAinference(scaled.fits, VarVC=TRUE) reference.infs <- VCAinference(reference.fits, VarVC=TRUE) rescaled.infs <- reScale(scaled.infs) for(i in 1:length(scaled.infs)) { scl <- rescaled.infs[[i]] ref <- reference.infs[[i]] sfac <- 1e12/scl$VCAobj$scale tol <- 1/sfac checkEquals(ref$VCAobj$aov.tab[,"VC"], scl$VCAobj$aov.tab[,"VC"], tolerance=tol) checkEquals(diag(ref$vcovVC), diag(scl$vcovVC), tolerance=tol) } } TF052.Scale.reScale.anovaMM <- function() { data(VCAdata1) scaled.fits <- Scale("anovaMM", y~((device)+(lot))/(day)/(run), VCAdata1, by="sample") reference.fits <- anovaMM( y~((device)+(lot))/(day)/(run), VCAdata1, by="sample") scaled.infs <- VCAinference(scaled.fits, VarVC=TRUE) reference.infs <- VCAinference(reference.fits, VarVC=TRUE) rescaled.infs <- reScale(scaled.infs) for(i in 1:length(scaled.infs)) { scl <- rescaled.infs[[i]] ref <- reference.infs[[i]] tol <- 1e-10 checkEquals(ref$VCAobj$aov.tab[,"SD"], scl$VCAobj$aov.tab[,"SD"], tolerance=tol) checkEquals(diag(ref$vcovVC), diag(scl$vcovVC), tolerance=tol) } } TF053.Scale.reScale.remlVCA <- function() { data(VCAdata1) scaled.fits <- Scale("remlVCA", y~(device+lot)/day/run, VCAdata1, by="sample") reference.fits <- remlVCA(y~(device+lot)/day/run, VCAdata1, by="sample") scaled.infs <- VCAinference(scaled.fits, VarVC=TRUE) reference.infs <- VCAinference(reference.fits, VarVC=TRUE) rescaled.infs <- reScale(scaled.infs) for(i in 1:length(scaled.infs)) { scl <- rescaled.infs[[i]] ref <- reference.infs[[i]] tol <- 1e-5 checkEquals(ref$VCAobj$aov.tab[,"SD"], scl$VCAobj$aov.tab[,"SD"], tolerance=tol) checkEquals(diag(ref$vcovVC), diag(scl$vcovVC), tolerance=tol) } } TF054.Scale.reScale.remlMM <- function() { data(VCAdata1) scaled.fits <- Scale("remlMM", y~((device)+(lot))/(day)/(run), VCAdata1, by="sample") reference.fits <- remlMM( y~((device)+(lot))/(day)/(run), VCAdata1, by="sample") scaled.infs <- VCAinference(scaled.fits, VarVC=TRUE) reference.infs <- VCAinference(reference.fits, VarVC=TRUE) rescaled.infs <- reScale(scaled.infs) for(i in 1:length(scaled.infs)) { scl <- rescaled.infs[[i]] ref <- reference.infs[[i]] tol <- 1e-5 checkEquals(ref$VCAobj$aov.tab[,"SD"], scl$VCAobj$aov.tab[,"SD"], tolerance=tol) checkEquals(diag(ref$vcovVC), diag(scl$vcovVC), tolerance=tol) } } TF055.fitVCA.anovaVCA.remlVCA <- function() { data(VCAdata1) sgnf <- 5 for(i in 1:10) { tmpData <- subset(VCAdata1, sample==i) fit0.anova <- anovaVCA(y~(device+lot)/day/run, tmpData) fit0.reml <- remlVCA( y~(device+lot)/day/run, tmpData) fit1.anova <- fitVCA( y~(device+lot)/day/run, tmpData, method="anova", scale=(i%%2==0)) fit1.reml <- fitVCA( y~(device+lot)/day/run, tmpData, method="reml", scale=(i%%2!=0)) cat("\nsample",i,":\n") print(checkEquals(round(fit0.anova$aov.tab[,"VC"], sgnf), round(fit1.anova$aov.tab[,"VC"], sgnf))) print(checkEquals(round(fit0.reml$aov.tab[ ,"VC"], sgnf), round(fit1.reml$aov.tab[, "VC"], sgnf))) } } TF056.orderData.remlVCA <- function() { data(MLrepro) MLrepro.ord <- with(MLrepro, MLrepro[order(Lab, Lot, Day, Run),]) opt.new <- options(scipen=12) M1.ref <- remlVCA(Result ~ (Lab + Lot)/Day/Run, MLrepro.ord, VarVC = TRUE) M1 <- remlVCA(Result ~ (Lab + Lot)/Day/Run, MLrepro, VarVC = TRUE) checkEquals(M1$aov.tab, M1.ref$aov.tab) options(opt.new) } TF057.orderData.remlMM <- function() { data(MLrepro) MLrepro.ord <- with(MLrepro, MLrepro[order(Lab, Lot, Day, Run),]) opt.new <- options(scipen=12) M1.ref <- remlMM(Result ~ ((Lab) + (Lot))/(Day)/(Run), MLrepro.ord, VarVC = TRUE, order.data = FALSE) M1 <- remlMM(Result ~ ((Lab) + (Lot))/(Day)/(Run), MLrepro, VarVC = TRUE, order.data = TRUE) checkEquals(M1$aov.tab, M1.ref$aov.tab) options(opt.new) } TF058.predict.anovaMM <- function() { data(VCAdata1) VCAdata1_sample5 <- subset(VCAdata1, sample==5) fitS5 <- fitLMM(y~(device+lot)/(day)/(run), VCAdata1_sample5, "anova") pred <- predict(fitS5) SASref <- c(17.899050479, 17.899050479, 18.019161777, 18.019161777, 17.851799074, 17.851799074, 17.844764076, 17.844764076, 16.814900319, 16.814900319, 18.099103148, 18.099103148, 18.323024006, 18.323024006, 18.402690956, 18.402690956, 18.02856588, 18.02856588, 17.414336609, 17.414336609, 18.01615201, 18.01615201, 18.150495477, 18.150495477, 17.810710437, 17.810710437, 17.541187839, 17.541187839, 17.891970672, 17.891970672, 17.477222676, 17.477222676, 16.936743521, 16.936743521, 17.009863088, 17.009863088, 16.996838687, 16.996838687, 17.742573591, 17.742573591, 17.181168314, 17.181168314, 17.913059433, 17.913059433, 17.886696332, 17.886696332, 17.920933794, 17.920933794, 17.453001574, 17.453001574, 17.908328271, 17.908328271, 17.168513101, 17.168513101, 17.208107861, 17.208107861, 18.350257975, 18.350257975, 18.454610947, 18.454610947, 18.05353796, 18.05353796, 18.148658917, 18.148658917, 17.782646776, 17.782646776, 18.191321439, 18.191321439, 17.747847363, 17.747847363, 18.160575146, 18.160575146, 17.854959068, 17.854959068, 17.94836637, 17.94836637, 17.778571123, 17.778571123, 17.981690354, 17.981690354, 17.721834759, 17.721834759, 18.210214242, 18.210214242, 17.426262307, 17.426262307, 17.516597821, 17.516597821, 17.995705373, 17.995705373, 17.839060278, 17.839060278, 17.870866129, 17.870866129, 17.455708536, 17.455708536, 17.484376436, 17.484376436, 17.633759632, 17.633759632, 18.059467054, 18.059467054, 18.109651477, 18.109651477, 17.763661497, 17.763661497, 17.678617607, 17.678617607, 17.649497267, 17.649497267, 17.671977329, 17.671977329, 16.844471453, 16.844471453, 16.304322063, 16.304322063, 17.155502328, 17.155502328, 16.959623965, 16.959623965, 17.248848449, 17.248848449, 17.203171369, 17.203171369, 16.377849768, 16.377849768, 16.840993943, 16.840993943, 17.598257565, 17.598257565, 16.993849474, 16.993849474, 15.847775522, 15.847775522, 16.139327587, 16.139327587, 17.235607942, 17.235607942, 17.194286781, 17.194286781, 18.151865586, 18.151865586, 18.006728937, 18.006728937, 17.932605325, 17.932605325, 17.993503934, 17.993503934, 17.972653873, 17.972653873, 17.938784406, 17.938784406, 17.656457414, 17.656457414, 18.171206871, 18.171206871, 18.056473288, 18.056473288, 18.12599667, 18.12599667, 18.195670704, 18.195670704, 18.531011728, 18.531011728, 18.067735776, 18.067735776, 18.445249298, 18.445249298, 17.374363044, 17.374363044, 17.467161232, 17.467161232, 17.095178243, 17.095178243, 17.74331252, 17.74331252, 17.470110835, 17.470110835, 17.734284011, 17.734284011, 17.575357936, 17.575357936, 18.042970992, 18.042970992, 17.151979443, 17.151979443, 17.175104385, 17.175104385, 17.442102655, 17.442102655, 16.823553712, 16.823553712, 17.519946213, 17.519946213, 17.338524873, 17.338524873, 17.147467912, 17.147467912, 16.713978566, 16.713978566, 16.472854882, 16.472854882, 16.65792692, 16.65792692, 15.675853935, 15.675853935, 16.380109642, 16.380109642, 16.915108884, 16.915108884, 17.599223625, 17.599223625, 16.92119403, 16.92119403, 16.700892957, 16.700892957, 15.747910906, 15.747910906, 15.559174464, 15.559174464, 17.193351366, 17.193351366, 17.602150973, 17.602150973, 17.502256685, 17.502256685, 17.701333304, 17.701333304, 17.407119593, 17.407119593, 17.591792282, 17.591792282, 17.188676031, 17.188676031, 17.659079358, 17.659079358, 17.552768564, 17.552768564, 17.347926526, 17.347926526, 16.295013278, 16.295013278, 16.52279957, 16.52279957, 16.232855875, 16.232855875, 15.900764272, 15.900764272, 16.411652347, 16.411652347, 17.135995502, 17.135995502) checkEqualsNumeric(as.vector(pred), SASref) } TF059.predict.remlMM.newdata <- function() { data(VCAdata1) datS5 <- subset(VCAdata1, sample==5) set.seed(1) datS5$cov <- round(rnorm(nrow(datS5), 65, 8),1) fitS5 <- fitLMM(y~cov+device+lot+(day)+(run), datS5, "reml") newdata <- datS5[c(1,62),] newdata$cov <- newdata$cov + 3.5 pred <- predict(fitS5, newdata) SASref <- c(18.12473221,17.28640975) checkEqualsNumeric(as.vector(pred), SASref, tolerance=1e-6) } TF060.predict.remlMM.newdata <- function() { data(Orthodont) Ortho <- Orthodont Ortho$age2 <- Ortho$age-11 fit.fitLMM <- fitLMM(distance~Sex*age2+(Subject)*age2, Ortho, "reml") newdata <- Ortho[c(45,75),] newdata$age2 <- newdata$age2 + 5 pred <- predict(fit.fitLMM, newdata) SASref <- c(26.0117,27.2067) checkEqualsNumeric(as.vector(pred), SASref, tolerance=1e-4) } TF061.predict.remlMM.restriction <- function() { data(Orthodont) Ortho <- Orthodont Ortho$age2 <- Ortho$age-11 fit.fitLMM <- fitLMM(distance~Sex*age2+(Subject)*age2, Ortho, "reml") pred <- predict(fit.fitLMM, re=NA) SASref <- c(21.209090909, 22.168181818, 23.127272727, 24.086363636, 21.209090909, 22.168181818, 23.127272727, 24.086363636, 21.209090909, 22.168181818, 23.127272727, 24.086363636, 21.209090909, 22.168181818, 23.127272727, 24.086363636, 21.209090909, 22.168181818, 23.127272727, 24.086363636, 21.209090909, 22.168181818, 23.127272727, 24.086363636, 21.209090909, 22.168181818, 23.127272727, 24.086363636, 21.209090909, 22.168181818, 23.127272727, 24.086363636, 21.209090909, 22.168181818, 23.127272727, 24.086363636, 21.209090909, 22.168181818, 23.127272727, 24.086363636, 21.209090909, 22.168181818, 23.127272727, 24.086363636, 22.615625, 24.184375, 25.753125, 27.321875, 22.615625, 24.184375, 25.753125, 27.321875, 22.615625, 24.184375, 25.753125, 27.321875, 22.615625, 24.184375, 25.753125, 27.321875, 22.615625, 24.184375, 25.753125, 27.321875, 22.615625, 24.184375, 25.753125, 27.321875, 22.615625, 24.184375, 25.753125, 27.321875, 22.615625, 24.184375, 25.753125, 27.321875, 22.615625, 24.184375, 25.753125, 27.321875, 22.615625, 24.184375, 25.753125, 27.321875, 22.615625, 24.184375, 25.753125, 27.321875, 22.615625, 24.184375, 25.753125, 27.321875, 22.615625, 24.184375, 25.753125, 27.321875, 22.615625, 24.184375, 25.753125, 27.321875, 22.615625, 24.184375, 25.753125, 27.321875, 22.615625, 24.184375, 25.753125, 27.321875) checkEqualsNumeric(as.vector(pred), SASref, tolerance=1e-6) } TF062.comparison.fitLMM.REML <- function() { data(Orthodont) Ortho <- Orthodont Ortho$age2 <- Ortho$age-11 fit.fitLMM <- fitLMM(distance~Sex*age2+(Subject)*age2, Ortho, "reml") fit.remlMM <- remlMM(distance~Sex*age2+(Subject)*age2, Ortho) checkEqualsNumeric(fit.fitLMM$aov.tab, fit.remlMM$aov.tab, tolerance=1e-7) } TF063.comparison.fitLMM.ANOVA <- function() { data(Orthodont) Ortho <- Orthodont Ortho$age2 <- Ortho$age-11 fit.fitLMM <- fitLMM(distance~Sex*age2+(Subject)*age2, Ortho) fit.anovaMM <- anovaMM(distance~Sex*age2+(Subject)*age2, Ortho) checkEqualsNumeric(fit.fitLMM$aov.tab, fit.anovaMM$aov.tab, tolerance=1e-8) } TF064.Scale.reScale.response <- function() { data(VCAdata1) sample1 <- VCAdata1[VCAdata1$sample==1,] scaled.fit <- Scale("remlMM", y~((device)+(lot))/(day)/(run), sample1) scaled.inf <- VCAinference(scaled.fit, VarVC=TRUE) rescaled.inf <- reScale(scaled.inf) ref.response <- orderData(sample1 , y~((device)+(lot))/(day)/(run))$y checkEqualsNumeric(rescaled.inf$VCAobj$data$y, ref.response, tolerance=1e-10) } TF065.comparison.fitVCA.REML <- function() { data(dataEP05A2_2) fit.fitVCA <- fitVCA(y~day/run, dataEP05A2_2, "reml") fit.remlVCA <- remlVCA(y~day/run, dataEP05A2_2) checkEqualsNumeric(fit.fitVCA$aov.tab, fit.remlVCA$aov.tab, tolerance=1e-8) } TF066.comparison.fitVCA.ANOVA <- function() { data(dataEP05A2_2) fit.fitVCA <- fitVCA(y~day/run, dataEP05A2_2, "anova") fit.anovaVCA <- anovaVCA(y~day/run, dataEP05A2_2) checkEqualsNumeric(fit.fitVCA$aov.tab, fit.anovaVCA$aov.tab, tolerance=1e-8) } TF067.checkException.NoReScaling <- function() { data(VCAdata1) datS511 <- subset(VCAdata1, sample==5 & lot == 1 & device == 1) fit <- Scale("anovaVCA", y~day/run, datS511) options(warn=2) checkException(ranef(fit)) checkException(resid(fit)) options(warn=0) } TF068.check.Scale.reScale.anovaVCA <- function() { data(VCAdata1) datS5 <- subset(VCAdata1, sample == 5) datHV <- datS5 datHV$y <- datHV$y * 1e7 fit.anovaVCA <- Scale("anovaVCA", y~(device+lot)/day/run, datHV) fit.anovaVCA <- reScale(fit.anovaVCA) fit0 <- anovaVCA(y~((device)+(lot))/day/run, datS5) VarCov0 <- vcovVC(fit0) fit1 <- Scale("anovaVCA", y~((device)+(lot))/day/run, datS5) fit1 <- reScale(fit1, VarVC=TRUE) VarCov1 <- vcovVC(fit1) tol <- 1e-6 digits <- log10(1/tol) checkEquals(round(VarCov0, digits=digits), round(VarCov1, digits=digits), tolerance=tol) checkEquals(round(ranef(fit0),digits=digits), round(ranef(fit1),digits=digits), tolerance=tol) checkEquals(round(ranef(fit0, mode="student"),digits=digits), round(ranef(fit1, mode="student"),digits=digits), tolerance=tol) checkEquals(round(ranef(fit0, mode="standard"),digits=digits), round(ranef(fit1, mode="standard"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="cond"),digits=digits), round(resid(fit1, term="cond"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="cond", mode="student"),digits=digits), round(resid(fit1, term="cond", mode="student"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="cond", mode="pearson"),digits=digits), round(resid(fit1,term="cond", mode="pearson"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="marginal"),digits=digits), round(resid(fit1, term="marginal"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="marginal", mode="student"),digits=digits), round(resid(fit1, term="marginal", mode="student"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="marginal", mode="pearson"),digits=digits), round(resid(fit1,term="marginal", mode="pearson"),digits=digits), tolerance=tol) } TF069.check.Scale.reScale.remlVCA <- function() { data(VCAdata1) datS5 <- subset(VCAdata1, sample == 5) datHV <- datS5 datHV$y <- datHV$y * 1e7 fit.remlVCA <- Scale("remlVCA", y~(device+lot)/day/run, datHV) fit.remlVCA <- reScale(fit.remlVCA) fit0 <- remlVCA(y~((device)+(lot))/day/run, datS5) VarCov0 <- vcovVC(fit0) fit1 <- Scale("remlVCA", y~((device)+(lot))/day/run, datS5) fit1 <- reScale(fit1, VarVC=TRUE) VarCov1 <- vcovVC(fit1) tol <- 1e-4 digits <- log10(1/tol) checkEquals(round(VarCov0, 6), round(VarCov1, 6), tolerance=1e-6) checkEquals(round(ranef(fit0),digits=digits), round(ranef(fit1),digits=digits), tolerance=tol) checkEquals(round(ranef(fit0, mode="student"),digits=digits), round(ranef(fit1, mode="student"),digits=digits), tolerance=tol) checkEquals(round(ranef(fit0, mode="standard"),digits=digits), round(ranef(fit1, mode="standard"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="cond"),digits=digits), round(resid(fit1, term="cond"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="cond", mode="student"),digits=digits), round(resid(fit1, term="cond", mode="student"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="cond", mode="pearson"),digits=digits), round(resid(fit1,term="cond", mode="pearson"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="marginal"),digits=digits), round(resid(fit1, term="marginal"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="marginal", mode="student"),digits=digits), round(resid(fit1, term="marginal", mode="student"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="marginal", mode="pearson"),digits=digits), round(resid(fit1,term="marginal", mode="pearson"),digits=digits), tolerance=tol) } TF070.check.Scale.reScale.anovaMM <- function() { data(VCAdata1) datS5 <- subset(VCAdata1, sample == 5) datHV <- datS5 datHV$y <- datHV$y * 1e7 fit.anovaMM <- Scale("anovaMM", y~(device+lot)/(day)/(run), datHV) fit.anovaMM <- reScale(fit.anovaMM) fit0 <- anovaMM(y~(device+lot)/(day)/(run), datS5) VarCov0 <- vcovVC(fit0) fit1 <- Scale("anovaMM", y~(device+lot)/(day)/(run), datS5) fit1 <- reScale(fit1, VarVC=TRUE) VarCov1 <- vcovVC(fit1) tol <- 1e-6 digits <- log10(1/tol) checkEquals(round(VarCov0, 6), round(VarCov1, 6), tolerance=1e-6) checkEquals(round(ranef(fit0),digits=digits), round(ranef(fit1),digits=digits), tolerance=tol) checkEquals(round(ranef(fit0, mode="student"),digits=digits), round(ranef(fit1, mode="student"),digits=digits), tolerance=tol) checkEquals(round(ranef(fit0, mode="standard"),digits=digits), round(ranef(fit1, mode="standard"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="cond"),digits=digits), round(resid(fit1, term="cond"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="cond", mode="student"),digits=digits), round(resid(fit1, term="cond", mode="student"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="cond", mode="pearson"),digits=digits), round(resid(fit1,term="cond", mode="pearson"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="marginal"),digits=digits), round(resid(fit1, term="marginal"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="marginal", mode="student"),digits=digits), round(resid(fit1, term="marginal", mode="student"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="marginal", mode="pearson"),digits=digits), round(resid(fit1,term="marginal", mode="pearson"),digits=digits), tolerance=tol) } TF071.check.Scale.reScale.remlMM <- function() { data(VCAdata1) datS5 <- subset(VCAdata1, sample == 5) datHV <- datS5 datHV$y <- datHV$y * 1e7 fit.remlMM <- Scale("remlMM", y~(device+lot)/(day)/(run), datHV) fit.remlMM <- reScale(fit.remlMM) fit0 <- remlMM(y~(device+lot)/(day)/(run), datS5) VarCov0 <- vcovVC(fit0) fit1 <- Scale("remlMM", y~(device+lot)/(day)/(run), datS5) fit1 <- reScale(fit1, VarVC=TRUE) VarCov1 <- vcovVC(fit1) tol <- 1e-5 digits <- log10(1/tol) checkEquals(round(VarCov0, 6), round(VarCov1, 6), tolerance=1e-6) checkEquals(round(ranef(fit0),digits=digits), round(ranef(fit1),digits=digits), tolerance=tol) checkEquals(round(ranef(fit0, mode="student"),digits=digits), round(ranef(fit1, mode="student"),digits=digits), tolerance=tol) checkEquals(round(ranef(fit0, mode="standard"),digits=digits), round(ranef(fit1, mode="standard"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="cond"),digits=digits), round(resid(fit1, term="cond"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="cond", mode="student"),digits=digits), round(resid(fit1, term="cond", mode="student"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="cond", mode="pearson"),digits=digits), round(resid(fit1,term="cond", mode="pearson"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="marginal"),digits=digits), round(resid(fit1, term="marginal"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="marginal", mode="student"),digits=digits), round(resid(fit1, term="marginal", mode="student"),digits=digits), tolerance=tol) checkEquals(round(resid(fit0, term="marginal", mode="pearson"),digits=digits), round(resid(fit1,term="marginal", mode="pearson"),digits=digits), tolerance=tol) } TF072.getMM.multi.covariables <- function() { data <- as.data.frame(matrix(rnorm(40), nrow=10)) colnames(data) <- c('V.1', 'V.2', 'V.3', 'V.4') form <- as.formula('V.1 ~ V.2 + V.3 + V.4 + V.2 * V.3 + V.2 * V.4 + V.3 * V.4 + V.2 * V.3 * V.4') X0 <- model.matrix(form, data = data) X1 <- getMM(form, Data = data) checkEquals(c(X0), c(as.matrix(X1))) data2 <- data data2$subject <- gl(5, 2) form2 <- as.formula('V.1 ~ V.2 + subject*V.2 * V.3') X3 <- model.matrix(form2, data2) X4 <- getMM(form2, data2) checkEquals(c(X3[,c(1:6, 8:11, 7, 12:20)]), c(as.matrix(X4)[,-c(3,8,14,20)])) } TF073.fitVCA_ANOVA_VarVC_TRUE <- function() { data(dataEP05A2_3) fit0 <- anovaVCA(y~day/run, dataEP05A2_3) fit1 <- fitVCA( y~day/run, dataEP05A2_3) inf0 <- VCAinference(fit0, VarVC=TRUE) inf1 <- VCAinference(fit1, VarVC=TRUE) checkEquals(unlist(inf0$ConfInt), unlist(inf1$ConfInt)) } TF074.fitVCA_REML_VarVC_TRUE <- function() { fit0 <- remlVCA(y~day/run, dataEP05A2_3) fit1 <- fitVCA( y~day/run, dataEP05A2_3, "REML") inf0 <- VCAinference(fit0, VarVC=TRUE) inf1 <- VCAinference(fit1, VarVC=TRUE) checkEquals(unlist(inf0$ConfInt), unlist(inf1$ConfInt), tol=1e-6) }
print.mlgarch <- function(x, varma=FALSE, ...) { pars <- coef.mlgarch(x, varma=varma) vcovmat <- vcov.mlgarch(x, varma=varma) out1 <- rbind(pars, sqrt(diag(vcovmat))) rownames(out1) <- c("Estimate:", "Std. Error:") out2 <- as.data.frame(matrix(NA,4,1)) out2[1,1] <- as.character(round(logLik.mlgarch(x, varma=FALSE), digits=3)) out2[2,1] <- as.character(round(logLik.mlgarch(x, varma=TRUE), digits=3)) out2[3,1] <- as.character(round(x$aux$ynonzerorowsn, digits=0)) out2[4,1] <- as.character(round(x$aux$yanyrowiszeron, digits=0)) rownames(out2) <- c("Log-likelihood (log-mgarch):", "Log-likelihood (varma):", "No. of obs. without zeros:", "No. of obs. with zeros:") colnames(out2) <- "" cat("\n") cat("Date:", x$date, "\n") cat("Method: Multivariate ML \n") cat("Message (nlminb):", x$message, "\n") cat("No. of observations:", x$aux$n, "\n") cat("Sample:", as.character(x$aux$y.index[1]), "to", as.character(x$aux$y.index[x$aux$n]), "\n") cat("\n") cat("Coefficients:\n") cat("\n") print(out1) print(out2) cat("\n") }
fetchVegdata <- function(SS=TRUE, stringsAsFactors = default.stringsAsFactors(), dsn = NULL) { if (!local_NASIS_defined(dsn)) stop('Local NASIS ODBC connection has not been setup. Please see `http://ncss-tech.github.io/AQP/soilDB/setup_local_nasis.html`.') vegplot <- get_vegplot_from_NASIS_db(SS = SS, stringsAsFactors = stringsAsFactors, dsn = dsn) vegplotlocation <-get_vegplot_location_from_NASIS_db(SS = SS, stringsAsFactors = stringsAsFactors, dsn = dsn) vegplotrhi <- get_vegplot_trhi_from_NASIS_db(SS = SS, stringsAsFactors = stringsAsFactors, dsn = dsn) vegplotspecies <- get_vegplot_species_from_NASIS_db(SS = SS, stringsAsFactors = stringsAsFactors, dsn = dsn) vegtransect <- get_vegplot_transect_from_NASIS_db(SS = SS, stringsAsFactors = stringsAsFactors, dsn = dsn) vegtransplantsum <- get_vegplot_transpecies_from_NASIS_db(SS = SS, stringsAsFactors = stringsAsFactors, dsn = dsn) vegsiteindexsum <- get_vegplot_tree_si_summary_from_NASIS_db(SS = SS, stringsAsFactors = stringsAsFactors, dsn = dsn) vegsiteindexdet <- get_vegplot_tree_si_details_from_NASIS_db(SS = SS, stringsAsFactors = stringsAsFactors, dsn = dsn) vegplottext <- get_vegplot_textnote_from_NASIS_db(SS = SS, fixLineEndings = TRUE, stringsAsFactors = stringsAsFactors, dsn = dsn) if (nrow(vegplot) == 0) message('your selected set is missing either the vegplot, pedon or site table, please load and try again :)') return(list( vegplot = vegplot, vegplotlocation = vegplotlocation, vegplotrhi = vegplotrhi, vegplotspecies = vegplotspecies, vegtransect = vegtransect, vegtransplantsum = vegtransplantsum, vegsiteindexsum = vegsiteindexsum, vegsiteindexdet = vegsiteindexdet, vegplottext = vegplottext )) }
summary.dbv.cartogramR <- function(object, ...) { L3 <- dbv <- NULL if (!inherits(object, "dbv.cartogramR")) stop(paste(deparse(substitute(object)), "must be a dbv.cartogramR object")) object2 <- copy(object) return(setorder(object2, -dbv)[1:10,]) }
library(ptm) context("GO-related") test_that("search.go() works properly", { skip_on_cran() skip_on_travis() a <- search.go(query = 'oxidative stress') b <- search.go(query = 'methionine') c <- search.go(query = 'xxxxxx') if (!is.null(a)){ expect_is(a, 'data.frame') expect_gte(nrow(a), 300) expect_equal(ncol(a), 5) expect_true('GO:0070994' %in% a$GO_id) } if (!is.null(b)){ expect_is(b, 'data.frame') expect_gte(nrow(b), 100) expect_equal(ncol(b), 5) expect_true('GO:0015821' %in% b$GO_id) } expect_is(c, 'NULL') }) test_that("term.go() works properly", { skip_on_cran() skip_on_travis() a <- term.go('GO:0034599') b <- term.go('GO:0005886', children = TRUE) c <- term.go('xxxxxxx') if (!is.null(a)){ expect_is(a, 'data.frame') expect_equal(nrow(a), 1) expect_equal(ncol(a), 7) expect_equal(a$term_name, "cellular response to oxidative stress") } if (!is.null(b)){ expect_is(b, 'list') expect_is(b[[1]], 'data.frame') expect_equal(nrow(b[[1]]), 1) expect_equal(ncol(b[[1]]), 7) expect_equal(b[[1]]$term_name, "plasma membrane") expect_is(b[[2]], 'data.frame') expect_equal(ncol(b[[2]]), 2) } expect_is(c, 'NULL') }) test_that("get.go() works properly", { skip_on_cran() skip_on_travis() a <- get.go(id = "P01009") b <- get.go(id = 'P01009', filter = FALSE) c <- get.go(id = 'P04406', format = 'string') d <- get.go(id = 'P04406', filter = FALSE, format = 'string') e <- get.go(id = 'P00367') f <- get.go(id = 'Q14687') g <- get.go(id = "P010091") h <- get.go("AAA58698", filter = FALSE) i <- get.go("AAA58698") if (!is.null(a)){ expect_is(a, 'data.frame') expect_gte(nrow(a), 20) expect_equal(ncol(a), 5) } if (!is.null(b)){ expect_is(b, 'data.frame') expect_gte(nrow(b), 70) expect_equal(ncol(b), 8) } if (!is.null(c)){ expect_is(c, 'character') expect_gte(nchar(c), 400) } if (!is.null(d)){ expect_is(d, "character") expect_gte(nchar(d), 1100) } if (!is.null(e)){ expect_is(e, 'data.frame') expect_gte(nrow(e), 15) expect_equal(ncol(e), 5) } expect_is(f, 'NULL') expect_is(g, 'NULL') expect_is(h, 'NULL') expect_is(i, 'NULL') }) test_that("bg.go() works properly", { skip_on_cran() skip_on_travis() a <- bg.go(ids = "./go/id_set.txt") b <- bg.go(ids = c("Q13015", "Q14667", "P08575", "Q5JSZ5", "P13196", "H7C4H7")) if (!is.null(a)){ expect_is(a, 'data.frame') expect_equal(nrow(a), 6) expect_equal(ncol(a), 2) } if (!is.null(b)){ expect_is(b, 'data.frame') expect_equal(nrow(b), 6) expect_equal(ncol(b), 2) expect_equal(a, b) } }) test_that(" hdfisher.go() works properly", { skip_on_cran() skip_on_travis() backg <- bg.go(c("Q13015", "Q14667", "P08575", "Q5JSZ5", "P13196")) if (!is.null(backg)){ a <- hdfisher.go(target = c('Q14667', 'Q5JSZ5'), background = backg, query = 'extracellular') } else { a <- NULL } if (!is.null(backg)){ b <- hdfisher.go(target = c('Q14667', 'Q5JSZ5'), background = backg, query = 'xxxxxxx') } else { b <- NULL } if (!is.null(a)){ expect_is(a, 'list') expect_is(a[[1]], 'matrix') expect_is(a[[2]], 'numeric') expect_true(attributes(a)$query == 'extracellular') } expect_is(b, 'NULL') }) test_that("net.go() works properly", { skip_on_cran() skip_on_travis() a <- net.go(data = "./go/id_set.txt", threshold = 0.1) b <- net.go(data = "./go/id_set.Rda", threshold = 0.1) c <- net.go(data = "./go/id_set_dummy.txt", threshold = 0.1) expect_is(a, 'list') expect_is(a[[1]], 'matrix') expect_equal(dim(a[[1]]), c(6,6)) expect_true(!isSymmetric(a[[1]])) expect_is(a[[2]], 'matrix') expect_equal(dim(a[[2]]), c(6,6)) expect_true(isSymmetric(a[[2]])) expect_is(a[[3]], 'character') expect_equal(length(a[[3]]), 6) expect_is(a[[4]], 'matrix') expect_equal(ncol(a[[4]]), 2) expect_is(b, 'list') expect_is(b[[1]], 'matrix') expect_equal(dim(b[[1]]), c(6,6)) expect_true(!isSymmetric(b[[1]])) expect_is(b[[2]], 'matrix') expect_equal(dim(b[[2]]), c(6,6)) expect_true(isSymmetric(b[[2]])) expect_is(b[[3]], 'character') expect_equal(length(b[[3]]), 6) expect_is(b[[4]], 'matrix') expect_equal(ncol(b[[4]]), 2) expect_is(c, 'list') expect_is(c[[1]], 'matrix') expect_equal(dim(c[[1]]), c(5,5)) expect_true(!isSymmetric(c[[1]])) expect_is(c[[2]], 'matrix') expect_equal(dim(c[[2]]), c(5,5)) expect_true(isSymmetric(c[[2]])) expect_is(c[[3]], 'character') expect_equal(length(c[[3]]), 6) expect_is(c[[4]], 'matrix') expect_equal(ncol(c[[4]]), 2) })
map <- function(.x, .f, ...) { lapply(.x, .f, ...) } map_mold <- function(...) { out <- vapply(..., USE.NAMES = FALSE) names(out) <- names(..1) out } map_lgl <- function(.x, .f, ...) { map_mold(.x, .f, logical(1), ...) } map_int <- function(.x, .f, ...) { map_mold(.x, .f, integer(1), ...) } map_dbl <- function(.x, .f, ...) { map_mold(.x, .f, double(1), ...) } map_chr <- function(.x, .f, ...) { map_mold(.x, .f, character(1), ...) } map_cpl <- function(.x, .f, ...) { map_mold(.x, .f, complex(1), ...) } pluck <- function(.x, .f) { map(.x, `[[`, .f) } pluck_lgl <- function(.x, .f) { map_lgl(.x, `[[`, .f) } pluck_int <- function(.x, .f) { map_int(.x, `[[`, .f) } pluck_dbl <- function(.x, .f) { map_dbl(.x, `[[`, .f) } pluck_chr <- function(.x, .f) { map_chr(.x, `[[`, .f) } pluck_cpl <- function(.x, .f) { map_cpl(.x, `[[`, .f) } map2 <- function(.x, .y, .f, ...) { mapply(.f, .x, .y, MoreArgs = list(...), SIMPLIFY = FALSE) } map2_lgl <- function(.x, .y, .f, ...) { as.vector(map2(.x, .y, .f, ...), "logical") } map2_int <- function(.x, .y, .f, ...) { as.vector(map2(.x, .y, .f, ...), "integer") } map2_dbl <- function(.x, .y, .f, ...) { as.vector(map2(.x, .y, .f, ...), "double") } map2_chr <- function(.x, .y, .f, ...) { as.vector(map2(.x, .y, .f, ...), "character") } map2_cpl <- function(.x, .y, .f, ...) { as.vector(map2(.x, .y, .f, ...), "complex") } args_recycle <- function(args) { lengths <- map_int(args, length) n <- max(lengths) stopifnot(all(lengths == 1L | lengths == n)) to_recycle <- lengths == 1L args[to_recycle] <- map(args[to_recycle], function(x) rep.int(x, n)) args } pmap <- function(.l, .f, ...) { args <- args_recycle(.l) do.call("mapply", c( FUN = list(quote(.f)), args, MoreArgs = quote(list(...)), SIMPLIFY = FALSE, USE.NAMES = FALSE )) } probe <- function(.x, .p, ...) { if (is_logical(.p)) { stopifnot(length(.p) == length(.x)) .p } else { map_lgl(.x, .p, ...) } } keep <- function(.x, .f, ...) { .x[probe(.x, .f, ...)] } discard <- function(.x, .p, ...) { sel <- probe(.x, .p, ...) .x[is.na(sel) | !sel] } map_if <- function(.x, .p, .f, ...) { matches <- probe(.x, .p) .x[matches] <- map(.x[matches], .f, ...) .x } compact <- function(.x) { Filter(length, .x) } transpose <- function(.l) { inner_names <- names(.l[[1]]) result <- map(seq_along(.l[[1]]), function(i) { map(.l, .subset2, i) }) set_names(result, inner_names) } every <- function(.x, .p, ...) { for (i in seq_along(.x)) { if (!rlang::is_true(.p(.x[[i]], ...))) return(FALSE) } TRUE } some <- function(.x, .p, ...) { for (i in seq_along(.x)) { if (rlang::is_true(.p(.x[[i]], ...))) return(TRUE) } FALSE } negate <- function(.p) { function(...) !.p(...) } reduce <- function(.x, .f, ..., .init) { f <- function(x, y) .f(x, y, ...) Reduce(f, .x, init = .init) } reduce_right <- function(.x, .f, ..., .init) { f <- function(x, y) .f(y, x, ...) Reduce(f, .x, init = .init, right = TRUE) } accumulate <- function(.x, .f, ..., .init) { f <- function(x, y) .f(x, y, ...) Reduce(f, .x, init = .init, accumulate = TRUE) } accumulate_right <- function(.x, .f, ..., .init) { f <- function(x, y) .f(y, x, ...) Reduce(f, .x, init = .init, right = TRUE, accumulate = TRUE) } invoke <- function(.f, .x, ..., .env = NULL){ .env <- .env %||% parent.frame() args <- c(as.list(.x), list(...)) do.call(.f, args, envir = .env) } imap <- function(.x, .f, ...){ map2(.x, names(.x) %||% seq_along(.x), .f, ...) } capture_error <- function (code, otherwise = NULL, quiet = TRUE) { tryCatch(list(result = code, error = NULL), error = function(e) { if (!quiet) message("Error: ", e$message) list(result = otherwise, error = e) }, interrupt = function(e) { stop("Terminated by user", call. = FALSE) }) } safely <- function (.f, otherwise = NULL, quiet = TRUE) { function(...) capture_error(.f(...), otherwise, quiet) } possibly <- function (.f, otherwise, quiet = TRUE) { force(otherwise) function(...) capture_error(.f(...), otherwise, quiet)$result } compose <- function (...) { fs <- lapply(list(...), match.fun) n <- length(fs) last <- fs[[n]] rest <- fs[-n] function(...) { out <- last(...) for (f in rev(rest)) { out <- f(out) } out } }
Ehrenfest <- function(n) { States <- c(0, seq(1,2*n)) TPM <- matrix(0,nrow=length(States),ncol=length(States),dimnames= list(seq(0,2*n),seq(0,2*n))) tran_prob <- function(i,n) { tranRow <- rep(0,2*n+1) if(i==0) tranRow[2] <- 1 if(i==2*n) tranRow[(2*n+1)-1] <- 1 if(i!=0 & i!=2*n) { j=i+1 tranRow[j-1] <- i/(2*n) tranRow[j+1] <- 1-i/(2*n) } return(tranRow) } for(j in 0:(2*n))TPM[j+1,] <- tran_prob(j,n) return(TPM) }
kin.coef <- function(n.parents, n.sibs) { n.person <- n.parents+n.sibs kin.coef <- matrix(0.25, ncol=n.person, nrow=n.person) diag(kin.coef) <- 0.5 if (n.parents == 2) kin.coef[1,2] <- kin.coef[2,1] <- 0 kin.coef } vec <- function(A) A[upper.tri(A,diag=FALSE)] score.core <- function(b1, b2, r) { S1 <- max(b1, 0)^2 S2 <- NULL if ((b1 > r*b2) & (b2 >= r*b1)) S2 <- (b1^2-2*r*b1*b2+b2^2)/(1-r^2) else if ((b1 >= 0) & (b2 < r*b1)) S2 <- b1^2 else if ((b1 <= r*b2) & (b2 > 0)) S2 <- b2^2 else S2 <- 0 k <- acos(r)/(2*pi) p1 <- 0.5-0.5*pchisq(S1, df = 1) p2 <- 1-((0.5-k)+0.5*pchisq(S2, df=1)+k*pchisq(S2,df=2)) c(round(S1,3), round(S2,3), round(p1,4), round(p2,4)) } reorder <- function(familyID, pair.id) { pairs <- do.call("rbind", strsplit(as.character(pair.id), ",")) p1 <- as.numeric(pairs[,1]) p2 <- as.numeric(pairs[,2]) ttt1 <- paste(familyID, pmin(p1, p2), sep=".") ttt2 <- paste(familyID, pmax(p1, p2), sep=".") paste(ttt1, ttt2, sep=",") } pair.data <- function(pheno,mean,h2,var) { pheno <- pheno[!is.na(pheno$phenotype),] pheno <- pheno[order(pheno$family, pheno$father, pheno$mother),] pairID <- allv <- NULL for (family in unique(pheno$family)) { target <- (pheno$family == family) ttt <- pheno[target,] n.parents <- sum(ttt$father == 0 & ttt$mother == 0) n.sibs <- sum(ttt$father!=0 | ttt$mother !=0) if (n.sibs < 2) next Sigma0 <- 2*h2*kin.coef(n.parents,n.sibs)+(1-h2)*diag(n.parents+n.sibs) Sigma0 <- var*Sigma0 Sigma0.1 <- solve(Sigma0) w <- as.vector(Sigma0.1 %*% (ttt$phenotype-mean)) Wanted <- (n.parents+1):(n.parents+n.sibs) v <- vec((outer(w,w)-Sigma0.1)[Wanted,Wanted]) names <- as.character(ttt$person) pair.id <- vec(outer(names,names, FUN=paste, sep=",")[Wanted,Wanted]) n.pairs <- length(v) pairID <- c(pairID, reorder(family,pair.id)) allv <- c(allv, v) } data.frame(pairID=pairID, v=allv) } score <- function(chrom.pos, pair.data, ibd) { ibddata <- ibd[ibd$pos == chrom.pos & ibd$prior.Z0 == 0.25 & ibd$prior.Z1 == 0.5 & ibd$prior.Z2 == 0.25, c("pedigree", "pair", "Z1", "Z2")] newdata <- data.frame(pairID=reorder(ibddata$pedigree, ibddata$pair), epi=ibddata$Z1/2+ibddata$Z2, pi2=ibddata$Z2) joint.data <- merge(pair.data, newdata, by="pairID", all=FALSE) b1 <- sum((joint.data$epi - 0.5) * joint.data$v) b2 <- sum((joint.data$pi2 - 0.25) * joint.data$v) Vepi <- var(cbind(joint.data$epi, joint.data$pi2)) Vb <- Vepi*sum(joint.data$v^2) b1 <- b1/sqrt(Vb[1,1]) b2 <- b2/sqrt(Vb[2,2]) r <- Vb[1,2]/sqrt(Vb[1,1]*Vb[2,2]) c(chrom.pos, score.core(b1, b2, r)) } comp.score <- function(ibddata="ibd_dist.out", phenotype="pheno.dat", mean=0, var=1, h2=0.3) { ibd <- read.table(ibddata, skip = 1, col.names = c("pos", "pedigree", "pair", "prior.Z0", "prior.Z1", "prior.Z2", "Z0", "Z1", "Z2"), colClasses=c("numeric", "integer", "character", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric"), comment.char = "") pheno <- read.table(phenotype, col.names = c("family", "person", "father", "mother", "gender", "phenotype")) paired <- pair.data(pheno,mean,h2,var) result <- NULL for (i in unique(ibd$pos)) result <- rbind(result, score(i, paired, ibd)) dimnames(result) <- list(NULL, c("pos", "stat.S1", "stat.S2", "p.value.S1", "p.value.S2")) result }
p <- c(1, -2, 1, -1) prior4.4 <- uniform(p -1.5, p + 1.5) formula4.4 <- ~exp(b0+b1*x1+b2*x2+b3*x1*x2)/(1+exp(b0+b1*x1+b2*x2+b3*x1*x2)) prob4.4 <- ~1-1/(1+exp(b0 + b1 * x1 + b2 * x2 + b3 * x1 * x2)) predvars4.4 <- c("x1", "x2") parvars4.4 <- c("b0", "b1", "b2", "b3") lb <- c(-1, -1) ub <- c(1, 1) xopt <- c(-1, -0.389, 1, 0.802, -1, 1, -1, 1) wopt <- c(0.198, 0.618, 0.084, 0.1) senslocallycomp(formula = formula4.4, predvars = predvars4.4, parvars = parvars4.4, family = binomial(), prob = prob4.4, lx = lb, ux = ub, alpha = .25, inipars = p, x = xopt, w = wopt) \dontrun{ senslocallycomp(formula = formula4.4, predvars = predvars4.4, parvars = parvars4.4, family = binomial(), prob = prob4.4, lx = lb, ux = ub, alpha = .3, inipars = p, x = xopt, w = wopt) senslocallycomp(formula = formula4.4, predvars = predvars4.4, parvars = parvars4.4, family = binomial(), prob = prob4.4, lx = lb, ux = ub, alpha = .5, inipars = p, x = xopt, w = wopt) senslocallycomp(formula = formula4.4, predvars = predvars4.4, parvars = parvars4.4, family = binomial(), prob = prob4.4, lx = lb, ux = ub, alpha = .8, inipars = p, x = xopt, w = wopt) senslocallycomp(formula = formula4.4, predvars = predvars4.4, parvars = parvars4.4, family = binomial(), prob = prob4.4, lx = lb, ux = ub, alpha = .9, inipars = p, x = xopt, w = wopt) }
sim.rateshift.taxa <-function(n,numbsim,lambda,mu,frac,times,complete=TRUE,K=0,norm=TRUE){ out<-lapply(1:numbsim,sim.rateshift.taxa.help,n=n,lambda=lambda,mu=mu,frac=frac,times=times,complete=complete,K=K,norm=norm) out1<-lapply(out,function(x){ x[[1]][[1]]}) out2<-sapply(out,function(x){ x[[2]]}) for (i in 1:length(out1)){ out1[[i]]$root.edge<-out2[i]-max(getx(out1[[i]],sersampling=1)[,1]) } out1 }
test.efdr <- function(Z,wf = "la8",J=2, alpha=0.05,n.hyp=100,b=11,iteration = 200, parallel = 1L) { .check_args(Z = Z,wf = wf,J = J,alpha = alpha,n.hyp = n.hyp,b = b,iteration = iteration,parallel = parallel) cat("Starting EFDR ...",sep="\n") cat("... Finding neighbours ...",sep="\n") nei <- nei.efdr(Z,wf = wf,J=J,b=b, parallel = parallel) cat("... Estimating the EFDR optimal number of tests ...",sep="\n") if(length(n.hyp)>1) { nhat <- .gdf(Z,n.hyp=n.hyp,iteration=iteration,nei=nei,parallel = parallel)$nhat } else { nhat = n.hyp } test.efdr.base(Z, wf=wf,J=J, alpha = alpha, n.hyp = nhat, b=b, nei=nei) } test.efdr.base <- function(Z,wf = "la8",J=2, alpha=0.05,n.hyp=100,b=11,nei = NULL, parallel = 1L) { .check_args(Z = Z,wf = wf,J = J,alpha = alpha,n.hyp = n.hyp,b = b,nei = nei, parallel = parallel) dwt.z <- dwt.2d(x=Z,wf=wf,J=J) std.dwt.z <- .std.wav.coeff(dwt.z) pvalue <- .p.values(std.dwt.z) if(is.null(nei)) nei <- nei.efdr(std.dwt.z,b=b, parallel = parallel) weight <- .weights.efdr3(std.dwt.z,nei,b=b) weight_unlist <- unlist(weight) index <- rev(order(weight_unlist))[1:n.hyp] pvalue_unlist <- unlist(pvalue) pvalue_order1 <- order(pvalue_unlist) pvalue_order2 <- intersect(pvalue_order1,index) pvalue_ordered2 <- pvalue_unlist[pvalue_order2] below_th <- as.vector(which(pvalue_ordered2 <= alpha*(1:n.hyp)/n.hyp)) if(length(below_th > 0)) { reject <- 1:max(below_th) } else { reject <- NULL } keep_coeff <- pvalue_order2[reject] test <- list() test$filtered <- .reconstruct.wt(dwt.z,keep = keep_coeff) test$Z <- idwt.2d(test$filtered) test$reject_coeff <- keep_coeff test$pvalue_ordered <- pvalue_ordered2 test$n.hyp <- n.hyp test } test.fdr <- function(Z,wf = "la8",J=2,alpha=0.05) { .check_args(Z = Z,wf = wf,J = J,alpha = alpha) dwt.z <- dwt.2d(x=Z,wf=wf,J=J) std.dwt.z <- .std.wav.coeff(dwt.z) pvalue <- .p.values(std.dwt.z) pvalue_unlist <- unlist(pvalue) pvalue_order1 <- order(pvalue_unlist) pvalue_ordered1 <- pvalue_unlist[pvalue_order1] n <- length(pvalue_ordered1) below_th <- which(pvalue_ordered1 <= alpha*(1:n)/n) if(length(below_th > 0)) { reject <- 1:max(below_th) } else { reject <- NULL } keep_coeff <- pvalue_order1[reject] test <- list() test$filtered <- .reconstruct.wt(dwt.z,keep = keep_coeff) test$Z <- idwt.2d(test$filtered) test$reject_coeff <- keep_coeff test$pvalue_ordered <- pvalue_ordered1 test$n.hyp <- n test } test.bonferroni <- function(Z,wf="la8",J=2,alpha=0.05) { .check_args(Z = Z,wf = wf,J = J,alpha = alpha) dwt.z <- dwt.2d(x=Z,wf=wf,J=J) std.dwt.z <- .std.wav.coeff(dwt.z) pvalue <- .p.values(std.dwt.z) pvalue_unlist <- unlist(pvalue) pvalue_order1 <- order(pvalue_unlist) pvalue_ordered1 <- pvalue_unlist[pvalue_order1] n <- length(pvalue_ordered1) reject <- as.vector(which(pvalue_ordered1 <= alpha/n)) keep_coeff <- pvalue_order1[reject] test <- list() test$filtered <- .reconstruct.wt(dwt.z,keep = keep_coeff) test$Z <- idwt.2d(test$filtered) test$reject_coeff <- keep_coeff test$pvalue_ordered <- pvalue_ordered1 test$n.hyp <- n test } test.los <- function(Z,wf="la8",J=2,alpha=0.05) { .check_args(Z = Z,wf = wf,J = J,alpha = alpha) dwt.z <- dwt.2d(x=Z,wf=wf,J=J) std.dwt.z <- .std.wav.coeff(dwt.z) pvalue <- .p.values(std.dwt.z) pvalue_unlist <- unlist(pvalue) pvalue_order1 <- order(pvalue_unlist) pvalue_ordered1 <- pvalue_unlist[pvalue_order1] n <- length(pvalue_ordered1) reject <- sum(pvalue_ordered1[1] < (1 - (1-alpha)^(1/n))) keep_coeff <- pvalue_order1[reject] test <- list() test$filtered <- .reconstruct.wt(dwt.z,keep = keep_coeff) test$Z <- idwt.2d(test$filtered) test$reject_coeff <- keep_coeff test$n.hyp <- n test } test_image <- function(h=1,r=10,n1 = 64, n2=64) { stopifnot(is.numeric(h)) stopifnot(is.numeric(r)) stopifnot(is.numeric(n1)) stopifnot(is.numeric(n2)) stopifnot(r > 0 & r < min(n1,n2)) stopifnot(n1 > 0) stopifnot(n2 > 0) stopifnot(.IsPowerOfTwo(n1)) stopifnot(.IsPowerOfTwo(n2)) signal=matrix(0,n1,n2) cutoff1 <- (n1/2) - 0.5 cutoff2 <- (n2/2) - 0.5 signal.grid <- expand.grid(-cutoff1:cutoff1,-cutoff2:cutoff2) distances <- matrix(apply(signal.grid,1,function(x) sqrt(x[1]^2 + x[2]^2)),n1,n2) signal[distances < r] <- h return(list(z = signal, grid = as.matrix(signal.grid))) } wav_th <- function(Z, wf = "la8", J = 2, th = 1) { stopifnot(is.numeric(th)) .check_args(Z = Z,wf = wf,J = J) zcoeff <- dwt.2d(x=Z,wf=wf,J=J) %>% unlist() as.numeric(which(abs(zcoeff) >= th)) } df.to.mat <- function(df) { stopifnot(is.data.frame(df)) stopifnot(ncol(df) == 3) stopifnot("x" %in% names(df)) stopifnot("y" %in% names(df)) stopifnot("z" %in% names(df)) x <- y <- z <- NULL if(!(length(unique(df$x)) * length(unique(df$y)) == nrow(df))) stop("Data frame needs to be in long format x-y-z with x and y being the output of expand.grid(x0,y0), where x0 and y0 are the x and y grid points") x0 = unique(df$x) y0 = unique(df$y) df_check <- expand.grid(x0,y0) names(df_check) <- c("x","y") if(nrow(merge(df,df_check)) < nrow(df)) stop("Data frame needs to be in long format x-y-z with x and y being the output of expand.grid(x0,y0), where x0 and y0 are the x and y grid points") spread(df,key = x,value=z) %>% select(-y) %>% as.matrix() %>% t() } regrid <- function(df,n1 = 128, n2 = n1, method="idw", idp = 0.5, nmax = 7,model="Exp") { stopifnot(is.data.frame(df)) stopifnot("x" %in% names(df)) stopifnot("y" %in% names(df)) stopifnot("z" %in% names(df)) stopifnot(is.numeric(n1)) stopifnot(is.numeric(n2)) stopifnot((n1 %% 1 == 0) & n1 > 0 ) stopifnot((n2 %% 1 == 0) & n2 > 0 ) stopifnot(is.numeric(idp)) stopifnot(idp > 0) stopifnot(is.numeric(nmax)) stopifnot((nmax %% 1 == 0) & nmax > 0 ) stopifnot(method %in% c("idw","median_polish","cond_sim")) stopifnot(model %in% vgm()$short) x <- y <- z <- box_x <- box_y <- z.pred <- NULL xlim=range(df$x) ylim=range(df$y) x0 <- seq(xlim[1],xlim[2],,n1+1) y0 <- seq(ylim[1],ylim[2],,n2+1) xd <- mean(diff(x0))/2 yd <- mean(diff(y0))/2 df.regrid <- expand.grid(x0[-1] - xd,y0[-1] - yd) names(df.regrid) <- c("x","y") if(method == "idw") { df.regrid <- gstat(id = "z", formula = z ~ 1, locations = ~ x + y, data = df, nmax = nmax, set = list(idp = idp)) %>% predict(df.regrid) %>% mutate(z = z.pred) %>% select(x,y,z) } else if(method == "cond_sim") { df.spat <- df coordinates(df.spat) = ~x+y df.regrid.spat <- df.regrid coordinates(df.regrid.spat) = ~x+y start_range <- max(diff(range(df$y)),diff(range(df$x)))/3 image.vgm = variogram(z~1, data=df.spat) fit = fit.variogram(image.vgm, model = vgm(var(df$z),"Exp",start_range,var(df$z)/10)) df.regrid$z = krige(z~1, df.spat, df.regrid.spat, model = fit,nmax = nmax, nsim = 1)$sim1 } else if(method == "median_polish") { x02 <- seq(xlim[1] - diff(xlim)/n1/2,xlim[2] + diff(xlim)/n1/2,,n1+1) y02 <- seq(ylim[1] - diff(ylim)/n1/2,ylim[2] + diff(ylim)/n2/2,,n2+1) df.boxed <- df %>% mutate(box_x = cut(x,x02,labels=F), box_y = cut(y,y02,labels=F)) %>% group_by(box_x,box_y) %>% summarise(z = mean(z)) %>% data.frame() Z <- df.regrid %>% mutate(box_x = cut(x,x02,labels=F), box_y = cut(y,y02,labels=F)) %>% left_join(df.boxed,by=c("box_x","box_y")) %>% select(x,y,z) %>% df.to.mat() med_Z <- medpolish(Z,na.rm=T) if (any(is.na(med_Z$row)) | any(is.na(med_Z$col))) stop("Grid with chosen size has rows or columns with no observations. Use method='idw' or a lower resolution.") med_Z$residuals[which(is.na(Z),arr.ind=T)] <- 0 df.regrid$z <- c(med_Z$overall + outer(med_Z$row,med_Z$col, "+") + med_Z$residuals) } df.regrid } fdrpower <- function(reject.true,reject) { length(intersect(reject.true,reject)) / length(reject.true) } diagnostic.table <- function(reject.true,reject, n) { TP = length(intersect(reject.true,reject)) FP = length(setdiff(reject.true,reject)) accept.true <- setdiff(1:n,reject.true) accept <- setdiff(1:n,reject) TN = length(intersect(accept.true,accept)) FN = length(setdiff(accept.true,accept)) d.table <- matrix(c(TN,FP,FN,TP),2,2) row.names(d.table) <- c("Diagnostic Negative","Diagnostic Positive") colnames(d.table) <- c("Real Negative","Real Positive") d.table } nei.efdr <- function(Z,wf="la8",J=2,b=11,parallel=1L) { .check_args(Z=Z,wf=wf,J=J,b=b,parallel=parallel) parallel <- 1L dwt.z <- dwt.2d(x=Z,wf=wf,J=J) layers <- .flat.pack(dwt.z,b=b) i <- s1 <-s2 <- j <- NULL if(parallel > 1L) { cl <- makeCluster(parallel) registerDoParallel(cl) nei <- foreach(i=1 : nrow(layers),.combine = rbind) %dopar% { x <- layers[i,] L <- subset(layers, abs(x$s1-s1) < 2.5 & abs(x$s2-s2) < 2.5 & abs(x$j - j) < 2) L$D1 <- .jmk.dist(x$j,x$m,x$s1,x$s2,L$j,L$m,L$s1,L$s2) max.set <- L[order(L$D1),][2:(b+1),] as.numeric(rownames(max.set)) } row.names(nei) <- NULL stopCluster(cl) } else { nei <- t( apply(layers,1,function(x) { L <- subset(layers, abs(x['s1']-s1) < 2.5 & abs(x['s2']-s2) < 2.5 & abs(x['j'] - j) < 2) L$D1 <- .jmk.dist(x['j'],x['m'],x['s1'],x['s2'],L$j,L$m,L$s1,L$s2) max.set <- L[order(L$D1),][2:(b+1),] matrix(as.numeric(rownames(max.set)),b,1) })) } nei } .IsPowerOfTwo <- function(x) { (sum(as.integer(intToBits(x))) == 1) } .check_args <- function(Z,wf="la8",J=2,alpha = 0.05,n.hyp = 1L,b = 11L,nei = NULL,iteration = 1L,parallel=1L) { if(!is.matrix(Z)) stop("Z needs to be a matrix") if(!(.IsPowerOfTwo(ncol(Z))) | !(.IsPowerOfTwo(nrow(Z)))) stop("Z needs to have rows and columns a power of two") temp <- tryCatch({ wave.filter(wf) }, error = function(e) { stop("Invalid filter specification. Refer to waveslim::wave.filter for filter names") }) if(!((J %% 1 == 0) & J > 0 )) stop("J needs to be an integer greater than zero") if(!((iteration %% 1 == 0) & iteration > 0 )) stop("iteration needs to be an integer greater than zero") if(!(alpha > 0 & alpha < 1)) stop("alpha needs to be less than 1 and greater than 0") if(!(all(n.hyp > 0) & all(n.hyp %% 1 == 0))) stop("n.hyp needs to be an integer vector with all elements greater than zero") if(any(n.hyp > length(unlist(dwt.2d(Z,wf=wf))))) stop("Every element in n.hyp needs to be smaller than the number of wavelet coefficients (i.e. smaller than the number of tests available)") if(!((b %% 1 == 0) & b > 0 )) stop("b needs to be an integer greater than zero") if(!((parallel %% 1 == 0) & parallel > 0 )) stop("parallel needs to be a positive integer") if(parallel > detectCores()) stop("parallel needs to be less than the number of available cores") } .gdf <- function(Z, wf = "la8", J = 2, alpha = 0.05, n.hyp=c(100,150,200),iteration=200,b=11,nei=NULL,parallel=1L) { stopifnot(is.numeric(iteration)) stopifnot(iteration > 1); iteration <- round(iteration) .check_args(Z = Z, wf = wf, J = J, n.hyp = n.hyp, b =b, nei = nei, parallel = parallel) dwt.z <- dwt.2d(x=Z,wf=wf,J=J) if (is.null(nei)) nei <- nei.efdr(dwt.z,b=b,parallel = parallel) dwt.z <- .std.wav.coeff(dwt.z) loss <- n.hyp*0 nz <- length(unlist(dwt.z)) sigma <- 1 tau <- 0.5*sigma find_loss <- function(i) { g <- 0 for(j in 1:iteration){ delta <- tau*rnorm(nz) dwt_unlist <- unlist(dwt.z) + delta dwt.z.MC <- .relist.dwt(vec = dwt_unlist,x = dwt.z) dwt.z.MC.cleaned <- test.efdr.base(idwt.2d(dwt.z.MC),wf = wf, J = J, alpha = alpha, n.hyp = n.hyp[i],b=b,nei=nei, parallel=parallel)$filtered g <- g+sum(unlist(dwt.z.MC.cleaned)*delta) } g <- g/iteration/tau^2 dwt.zhat <- test.efdr.base(idwt.2d(dwt.z),wf = wf, J = J,alpha = alpha,n.hyp = n.hyp[i],b=b,nei=nei)$filtered sum((unlist(dwt.z)-unlist(dwt.zhat))^2)+2*g*sigma^2 } if(parallel > 1L) { cl <- makeCluster(parallel) registerDoParallel(cl) loss <- foreach(i = seq_along(n.hyp), .combine=c) %dopar% { find_loss(i) } stopCluster(cl) } else { for(i in seq_along(n.hyp)){ loss[i] <- find_loss(i) } } nhat <- n.hyp[order(loss)[1]] list(nhat=nhat,loss=loss) } .lapply.dwt <- function(x,f) { x2 <- lapply(x, f) attr(x2, "J") <- attributes(x)$J attr(x2, "wavelet") <- attributes(x)$wavelet attr(x2, "boundary") <- attributes(x)$boundary attr(x2, "class") <- c("dwt.2d") x2 } .relist.dwt <- function(vec,x) { x2 <- relist(vec,as(x,"list")) attr(x2, "names") <- names(x) attr(x2, "J") <- attributes(x)$J attr(x2, "wavelet") <- attributes(x)$wavelet attr(x2, "boundary") <- attributes(x)$boundary attr(x2, "class") <- c("dwt.2d") x2 } .std.wav.coeff <- function(dwt) { .lapply.dwt(dwt,function(x) { std <- mad(x) x/std }) } .p.values <- function(dwt) { .lapply.dwt(dwt,function(x) { 2*(1-pnorm(abs(x))) } ) } .jmk.dist <- function(j,m,k1,k2,j_,m_,s1,s2) { d1 <- (j > j_) + sqrt((k1 - s1)^2 + (k2 - s2)^2) + 1 - (m == m_) } .jmk.sys <- function(dwt) { M <- 3 J <- (length(dwt)-1)/M K1 <- nrow(dwt[[1]]) K2 <- ncol(dwt[[1]]) dwt.t <- array(NA,dim=c(J,M+1,K1,K2)) for (j in 1:J) for(m in 1:M){ dwt.partial <- dwt[[(j-1)*M + m]] n1 <- K1*2^{-(j-1)} n2 <- K2*2^{-(j-1)} dwt.t[j,m,1:n1,1:n2] <- dwt.partial } dwt.t[J,M+1,1:n1,1:n2] <- dwt[[J*M + 1]] dwt.t } .flat.pack <- function(dwt,b=11) { M <- 3 J <- (length(dwt)-1)/M K1 <- nrow(dwt[[1]]) K2 <- ncol(dwt[[1]]) min_n1 <- K1*2^{-(J-1)} min_n2 <- K2*2^{-(J-1)} layers <- list() for (j in J:1) { n1 <- K1*2^{-(j-1)} n2 <- K2*2^{-(j-1)} s1 <- seq(0,(min_n1+1),,n1+2)[-c(1,(n1+2))] s2 <- seq(0,(min_n2+1),,n2+2)[-c(1,(n2+2))] grid_points <- expand.grid(s1,s2) k_points <- expand.grid(1:n1,1:n2) layers[[j]] <- data.frame(k1 = k_points[,1], k2 = k_points[,2], s1 = grid_points[,1], s2 = grid_points[,2],m = 1,j=j) layers_temp <- layers[[j]] for( m in 2:M) { layers_temp$m <- m layers[[j]] <- rbind(layers[[j]],layers_temp) } if (j == J) { layers[[j]] <- rbind(layers[[j]],data.frame(k1 = k_points[,1], k2 = k_points[,2], s1 = grid_points[,1], s2 = grid_points[,2],m = 4,j=j)) } } layers <- Reduce("rbind",layers) } .weights.efdr3 <- function(dwt,nei,b=11) { M <- 3 J <- (length(dwt)-1)/M K1 <- nrow(dwt[[1]]) K2 <- ncol(dwt[[1]]) dwt.t <- .jmk.sys(dwt) weight <- dwt.t * 0 layers <- .flat.pack(dwt,b=b) layers$z <- dwt.t[as.matrix(subset(layers,select=c("j","m","k1","k2")))]^2 weight_mat <- matrix(layers$z[c(nei)],nrow = nrow(layers)) layers$weight <- do.call(pmax, data.frame(weight_mat)) weight[cbind(layers$j,layers$m,layers$k1,layers$k2)] <- layers$weight weight[J,M+1,,] <- 1e10 weight.list <- dwt for (j in 1:J) for(m in 1:M){ n1 <- K1*2^{-(j-1)} n2 <- K2*2^{-(j-1)} weight.list[[(j-1)*M + m]] <- weight[j,m,1:n1,1:n2] } weight.list[[J*M + 1]] <- weight[J,M+1,1:n1,1:n2] weight.list } .reconstruct.wt <- function(dwt,keep) { z_unlist <- unlist(dwt) if (length(keep) == 0 ) { z_unlist <- z_unlist * 0 } else { z_unlist[-keep] <- 0 } .relist.dwt(z_unlist,dwt) }
context("test idig_view_records") rec_uuid = "d4f6974f-a7d6-4bfb-b70c-4c815b516a0b" test_that("viewing a record returns right information", { testthat::skip_on_cran() rec <- idig_view_records(rec_uuid) expect_that(rec, is_a("list")) expect_that(rec$uuid, equals(rec_uuid)) expect_that(rec$data, is_a("list")) expect_that(length(rec$data$id) > 0, is_true()) expect_that(rec$indexTerms, is_a("list")) expect_that(rec$indexTerms$uuid, equals(rec_uuid)) expect_that(rec$attribution, is_a("list")) expect_that(length(rec$attribution$data_rights) > 0, is_true()) })
pi.dosage<-function(dos,L=NULL){ if(!is.matrix(dos)){ if(class(dos)[[1]]=="bed.matrix") dos<-gaston::as.matrix(dos) else dos <- as.matrix(dos) } lims <- range(dos, na.rm = TRUE) if ((lims[2] > 2) | (lims[1] < 0)) stop("input dosage matrix should contains only 0, 1 and 2s") nis<-nrow(dos) p<-colMeans(dos,na.rm=TRUE)/2 nas<-colSums(is.na(dos)) pis<-2*p*(1-p)*(2*(nis-nas))/(2*(nis-nas)-1) if(is.null(L)) sum(pis,na.rm=TRUE) else sum(pis,na.rm=TRUE)/L } theta.Watt.dosage<-function(dos,L=NULL){ if(!is.matrix(dos)){ if(class(dos)[[1]]=="bed.matrix") dos<-gaston::as.matrix(dos) else dos <- as.matrix(dos) } lims <- range(dos, na.rm = TRUE) if ((lims[2] > 2) | (lims[1] < 0)) stop("input dosage matrix should contains only 0, 1 and 2s") nis<-nrow(dos) p<-colMeans(dos,na.rm=TRUE)/2 SegSites<-sum(p!=0.0 & p!=1.0,na.rm=TRUE) a<-sum(1/(1:(nis*2-1))) if(is.null(L)) SegSites/a else 1/L*SegSites/a } TajimaD.dosage<-function(dos){ if(!is.matrix(dos)){ if(class(dos)[[1]]=="bed.matrix") dos<-gaston::as.matrix(dos) else dos <- as.matrix(dos) } lims <- range(dos, na.rm = TRUE) if ((lims[2] > 2) | (lims[1] < 0)) stop("input dosage matrix should contains only 0, 1 and 2s") nis<-2*nrow(dos) p<-colMeans(dos,na.rm=TRUE)/2 Ss<-sum(p>0.0 & p<1.0,na.rm=TRUE) a<-sum(1/(1:(nis-1))) a2<-sum(1/((1:(nis-1))^2)) tW<-Ss/a pis<-pi.dosage(dos) tmp1<- ((nis+1)/(3*(nis-1))-1/a)/a num.tmp2<-2*(nis^2+nis+3)/(9*nis*(nis-1))-(nis+2)/(nis*a)+a2/(a^2) den.tmp2<-a^2+a2 VTD<-tmp1*Ss+num.tmp2/den.tmp2*Ss*(Ss-1) (pis-tW)/sqrt(VTD) }
context("train") test_that("train + knn + predict() works", { skip_on_cran() skip_if_not_installed("caret") library(caret) train_data <- iris[, 1:4] train_classes <- iris[, 5] train_fit <- caret::train(train_data, train_classes, method = "knn", preProcess = c("center", "scale"), tuneLength = 10, trControl = caret::trainControl(method = "cv")) x <- axe_call(train_fit) expect_equal(x$call, rlang::expr(dummy_call())) expect_equal(x$dots, train_fit$dots) x <- axe_ctrl(train_fit) expect_equal(x$control$method, train_fit$control$method) x <- axe_data(train_fit) expect_equal(x$trainingData, data.frame(NA)) x <- axe_fitted(train_fit) expect_equal(x$pred, train_fit$pred) expect_equal(x, train_fit) x <- axe_env(train_fit) expect_null(attr(x$modelInfo$prob, "srcref")) expect_null(attr(x$modelInfo$sort, "srcref")) x <- butcher(train_fit) expect_equal(attr(x, "butcher_disabled"), c("summary()", "update()")) test_data <- iris[1:3, 1:4] expect_equal(predict(x, newdata = test_data), structure( c(1L, 1L, 1L), .Label = c("setosa", "versicolor", "virginica"), class = "factor")) }) test_that("train + rda + predict() works", { skip_on_cran() skip_if_not_installed("caret") library(caret) data(cars) set.seed(123) train_fit <- suppressWarnings({ train(Price ~ ., data = cars, method = "rpart", trControl = trainControl(method = "cv")) }) x <- axe_call(train_fit) expect_equal(x$call, rlang::expr(dummy_call())) expect_equal(x$dots, train_fit$dots) x <- axe_ctrl(train_fit) expect_equal(x$control$method, train_fit$control$method) x <- axe_data(train_fit) expect_equal(x$trainingData, data.frame(NA)) x <- axe_fitted(train_fit) expect_equal(x$pred, train_fit$pred) expect_equal(x, train_fit) x <- axe_env(train_fit) expect_null(attr(x$modelInfo$prob, "srcref")) expect_null(attr(x$modelInfo$sort, "srcref")) x <- butcher(train_fit) expect_equal(attr(x, "butcher_disabled"), c("summary()", "update()")) expect_equal(predict(x, cars[1:3, ]), predict(train_fit, cars[1:3, ])) })
list_channels <- function(token = Sys.getenv("SLACK_TOKEN"), types = "public_channel", exclude_archived = TRUE, ...) { with_pagination( function(cursor) { call_slack_api( "/api/conversations.list", .method = GET, token = token, types = types, exclude_archived = exclude_archived, limit = 1000, ..., .next_cursor = cursor ) }, extract = "channels" ) } list_users <- function(token = Sys.getenv("SLACK_TOKEN"), ...) { with_pagination( function(cursor) { call_slack_api( "/api/users.list", .method = GET, token = token, ..., .next_cursor = cursor ) }, extract = "members" ) } post_message <- function(txt, channel, emoji = "", username = Sys.getenv("SLACK_USERNAME"), token = Sys.getenv("SLACK_TOKEN"), ...) { r <- call_slack_api( "/api/chat.postMessage", .method = POST, token = token, body = list( text = txt, channel = channel, username = username, link_names = 1, icon_emoji = emoji, ... ) ) invisible(content(r)) } files_upload <- function(file, channels, initial_comment = NULL, token = Sys.getenv("SLACK_TOKEN"), ...) { r <- call_slack_api( "/api/files.upload", .method = POST, token = token, body = list( file = upload_file(file), initial_comment = initial_comment, channels = paste(channels, collapse = ","), ... ) ) invisible(content(r)) } list_scopes <- function(token = Sys.getenv("SLACK_TOKEN")) { r <- call_slack_api( "/api/apps.permissions.scopes.list", .method = GET, token = token ) invisible(content(r)) }
knownComp_to_uniform <- function(data, comp.dist, comp.param) { stopifnot( (length(comp.dist) == 2) & (length(comp.param) == 2) ) if (is.null(comp.dist[[2]]) | is.null(comp.param[[2]])) stop("Known component must be specified.") comp.dist.inv <- paste0("p", comp.dist[[2]]) comp.inv <- sapply(X = comp.dist.inv, FUN = get, pos = "package:stats", mode = "function") assign(x = names(comp.inv)[1], value = comp.inv[[1]]) arg.names <- sapply(X = comp.inv, FUN = methods::formalArgs) n.arg.user <- length(comp.param[[2]]) if (inherits(arg.names, what = "matrix")) { arg.names.supplied <- names(comp.param[[2]]) if (is.character(arg.names.supplied)) { common.args <- match(x = arg.names.supplied, table = arg.names) } else { common.args <- apply(sapply(comp.param, names), 2, match, table = arg.names) } if (any(is.na(common.args))) stop("Parameters of the mixture components were not correctly specified") } else { common.args <- vector(mode = "list", length = length(comp.dist)) for (i in 1:length(comp.dist)) { if (class(sapply(comp.param, names))[1] != "matrix") { common.args[[i]] <- sapply(sapply(comp.param, names)[[i]], match, arg.names[[i]]) } else { common.args[[i]] <- match(sapply(comp.param, names)[, i], arg.names[[i]]) } if (any(is.na(common.args[[i]]))) stop("Parameters of the mixture components were not correctly specified") } } make.expr.inv <- function(z) paste(names(comp.inv)[1],"(q=", z, ",", paste(names(comp.param[[2]]), "=", comp.param[[2]], sep="", collapse=","), ")", sep="") expr.inv <- parse(text = make.expr.inv(data)) data.transformed <- sapply(expr.inv, eval) return(data.transformed) }
pn.modselect.step <- structure(function (x, y, grp, pn.options, forcemod = 0, existing = FALSE, penaliz = "1/sqrt(n)", taper.ends = 0.45, Envir = .GlobalEnv, ... ) { pcklib<- FPCEnv if( anyNA(data.frame(x, y, grp)) == TRUE ) stop ("This function does not handle missing data values for x, y, or grp. Please subset the data, e.g. mydataframe[!is.na(mydataframe),], to remove them prior to function call") options( warn = -1) if(existing == FALSE) { rm(list = ls(pattern = "richardsR", envir=FPCEnv), envir=FPCEnv) rm(list = ls(pattern = "richardsR", envir=Envir), envir=Envir) } else { rm(list = ls(pattern = "richardsR", envir=FPCEnv), envir=FPCEnv) get.mod(modelname = ls(Envir,pattern="richardsR"), from.envir = Envir, to.envir = FPCEnv, write.mod = TRUE, silent = TRUE) print(" print(paste("NOTE: existing is not set to false, existing models in the working environment ",substitute(Envir)," will be used during fits. To remove models manually, remove all files prefixed richardsR from working environment before running",sep="")) print(" } pnoptm=NULL pnoptnm <- as.character(pn.options) checkpen <- try(unlist(strsplit(penaliz, "(n)")), silent = TRUE) if (length(checkpen) != 2 | class(checkpen)[1] == "try-error") { stop("penaliz parameter is ill defined: see ?pn.mod.compare") } else { checkpen <- try(eval(parse(text = sprintf("%s", paste(checkpen[1], "1", checkpen[2], sep = ""))))) if (class(checkpen)[1] == "try-error") stop("penaliz parameter is ill defined: see ?pn.mod.compare") } datamerg <- data.frame(x, y, grp) userdata <- groupedData(y ~ x | grp, outer = ~grp, data = datamerg) assign("userdata", userdata, envir = Envir) if(as.character(list(Envir)) != "<environment>") stop ("No such environment") if(exists("Envir", mode = "environment") == FALSE) stop ("No such environment") FPCEnv$env <- Envir testbounds <- 1 testpar <- 1 is.na(testbounds) <- TRUE is.na(testpar) <- TRUE testbounds <- try(get(pnoptnm, envir = Envir)[16:32], silent = T) testpar <- try(get(pnoptnm, envir = Envir)[1:15], silent = T) if (class(testbounds)[1] == "try-error" | class(testpar)[1] == "try-error" | is.na(testbounds[1]) == TRUE | is.na(testpar[1]) == TRUE) try({ FPCEnv$mod.sel <- TRUE modpar(datamerg[,1], datamerg[,2], pn.options = pnoptnm, taper.ends = taper.ends, verbose=FALSE, Envir = Envir, ...) options(warn=-1) try(rm("mod.sel", envir = FPCEnv), silent =T) options(warn=0) }, silent = FALSE) extraF <- try(get("extraF", pos = 1), silent = TRUE) if (class(extraF)[1] == "try-error") { stop("cannot find function: extraF - please reload FlexParamCurve") } mostreducedmod<-1 print("checking fit of positive section of the curve for variable M*************************************") richardsR12.lis <- try(FPCEnv$richardsR12.lis, silent = TRUE) if (class(richardsR12.lis)[1] == "try-error" | existing == FALSE) richardsR12.lis <- eval(parse(text=sprintf("%s",paste("try(nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, modno = 12, pn.options = ",pnoptnm, "), data = userdata), silent = TRUE)",sep="")))) print("checking fit of positive section of the curve for fixed M*************************************") pnmodelparams <- get(pnoptnm, envir = Envir)[1:15] change.pnparameters <- try(get("change.pnparameters", pos = 1), silent = TRUE) chk <- try(unlist(summary(richardsR12.lis))["RSE"], silent = TRUE) richardsR20.lis <- try(FPCEnv$richardsR20.lis, silent = TRUE) if (class(richardsR20.lis)[1] == "try-error" | existing == FALSE) richardsR20.lis <- eval(parse(text=sprintf("%s",paste("try(nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, modno = 20, pn.options = ",pnoptnm,"), data = userdata), silent = TRUE)",sep="")))) chk1 <- try(unlist(summary(richardsR20.lis))["RSE"], silent = TRUE) if ((class(richardsR20.lis)[1]) == "try-error" | class(richardsR20.lis)[[1]] != "nlsList" | class(chk1)[1] == "try-error") { print("3 parameter positive richards model failed/not fitted*************************************") if(forcemod != 3) forcemod = 4 richardsR20.lis <- 1 } else { FPCEnv$richardsR20.lis <- richardsR20.lis } if ((class(richardsR12.lis)[1]) == "try-error" | class(richardsR12.lis)[[1]] != "nlsList" | class(chk)[1] == "try-error") { print("4 parameter positive richards model failed/not fitted*************************************") if(forcemod != 4) forcemod = 3 richardsR12.lis <- 1 } else { FPCEnv$richardsR12.lis <- richardsR12.lis } currentmodel <- 1 testmod <- try(extraF(richardsR20.lis, richardsR12.lis, warn = F)) if (forcemod == 0) { if (class(testmod)[1] == "try-error") { modelsig = 0.1 } else { modelsig = testmod[4] if ((testmod[4]) > 0.05 & sqrt(testmod[5]/(testmod[3]-testmod[2])) > sqrt(testmod[6]/testmod[3])) { currentmodel <- richardsR20.lis mostreducednm <- substr("richardsR20.lis", 10, 11) } else { currentmodel <- richardsR12.lis mostreducednm <- substr("richardsR12.lis", 10, 11) } } } mostreducedmod <- currentmodel if (class(testmod)[1] != "try-error") { mostreducednm <- substr("richardsR20.lis", 10, 11) mostreducedmod <- richardsR20.lis } else { mostreducednm <- "NONE" } if (forcemod == 3) { modelsig = 0.1 } if (forcemod == 4) { modelsig = 0.04 } if (modelsig < 0.05) { print("Variable M models most appropriate*************************************") } else { print("Fixed M models most appropriate*************************************") } options(warn = 0) options(warn = -1) rankmod <- function(model1 = 1, model2 = 1, model3 = 1, model4 = 1) { nm <- rep(0, 4) nm[1] <- (as.character(substitute(model1))) nm[2] <- (as.character(substitute(model2))) nm[3] <- (as.character(substitute(model3))) nm[4] <- (as.character(substitute(model4))) if (class(model1)[[1]] == "nlsList" & class(model1)[1] != "try-error") { if (is.null(nrow(coef(model1))) == TRUE) { model1 <- 1 } } if (class(model2)[[1]] == "nlsList" & class(model2)[1] != "try-error") { if (is.null(nrow(coef(model2))) == TRUE) { model2 <- 1 } } if (class(model3)[[1]] == "nlsList" & class(model3)[1] != "try-error") { if (is.null(nrow(coef(model3))) == TRUE) { model3 <- 1 } } if (class(model4)[[1]] == "nlsList" & class(model4)[1] != "try-error") { if (is.null(nrow(coef(model4))) == TRUE) { model4 <- 1 } } modrank <- data.frame(modno = c(1, 2, 3, 4), rank = rep(-999, 4)) nomods <- 4 RSEstr <- "RSE" dfstr <- "df" usefun <- unlist(strsplit(penaliz, "(n)")) if (class(model1)[[1]] == "nlsList" & class(model1)[1] != "try-error") { evfun <- parse(text = sprintf("%s", paste("summary(model1)[['", RSEstr, "']]*(", usefun[1], "(1+sum( summary(model1)[['", dfstr, "']],na.rm=TRUE)))", usefun[2], sep = ""))) modrank[1, 2] <- eval(evfun) } else { nomods = nomods - 1 } if (class(model2)[[1]] == "nlsList" & class(model2)[1] != "try-error") { evfun <- parse(text = sprintf("%s", paste("summary(model2)[['", RSEstr, "']]*(", usefun[1], "(1+sum( summary(model2)[['", dfstr, "']],na.rm=TRUE)))", usefun[2], sep = ""))) modrank[2, 2] <- eval(evfun) } else { nomods = nomods - 1 } if (class(model3)[[1]] == "nlsList" & class(model3)[1] != "try-error") { evfun <- parse(text = sprintf("%s", paste("summary(model3)[['", RSEstr, "']]*(", usefun[1], "(1+sum( summary(model3)[['", dfstr, "']],na.rm=TRUE)))", usefun[2], sep = ""))) } else { nomods = nomods - 1 } if (class(model4)[[1]] == "nlsList" & class(model4)[1] != "try-error") { evfun <- parse(text = sprintf("%s", paste("summary(model4)[['", RSEstr, "']]*(", usefun[1], "(1+sum( summary(model4)[['", dfstr, "']],na.rm=TRUE)))", usefun[2], sep = ""))) modrank[4, 2] <- eval(evfun) } else { nomods = nomods - 1 } if (nomods == 0) { for (j in 1:4) { if (modrank[j, 2] == -999 & nm[j] != 1) print(paste("Model", nm[j], "failed to converge for all individuals", sep = " ")) } return(print("*************************************no models to evaluate*************************************")) } else { modnmsav = "" for (j in 1:4) { if (modrank[j, 2] == -999 & nm[j] != 1) print(paste("Model", nm[j], "failed to converge for all individuals", sep = " ")) if (j == 1) if (modrank[j, 2] != -999) modnmsav <- nm[j] if (j > 1) if (modrank[j, 2] != -999) modnmsav <- paste(modnmsav, nm[j], sep = " vs. ") } print(paste("**************Ranking this step's models (all have same modnmsav, sep = "")) modrank <- modrank[modrank[, 2] > -999, ] modrank <- modrank[order(modrank[, 2], modrank[, 1]), ] if (modrank[1, 1] == 1) { model <- model1 submod <- as.character(substitute(model1)) } if (modrank[1, 1] == 2) { model <- model2 submod <- as.character(substitute(model2)) } if (modrank[1, 1] == 3) { model <- model3 submod <- as.character(substitute(model3)) } if (modrank[1, 1] == 4) { model <- model4 submod <- as.character(substitute(model4)) } submod <- substr(submod, 10, 11) FPCEnv$tempparam.select <- submod return(model) } } rncheck <- function(modname, existing = FALSE) { modname <- as.character(substitute(modname)) FPCEnv$tempmodnm <- modname modobj <- try(get(as.character(substitute(modname)),envir = pcklib) , silent = TRUE) if (class(modobj)[1] == "try-error" | existing == FALSE | class(modobj)[1] == "NULL") { outp <- TRUE } else { outp <- FALSE } return(outp) } rncheckfirst <- function(modname, existing = FALSE) { modname <- as.character(substitute(modname)) modobj <- try(get(as.character(substitute(modname)),envir = pcklib) , silent = TRUE) if (class(modobj)[1] == "try-error" | existing == FALSE) { } else { return(modobj) } } rnassign <- function() { modname <- parse(text = sprintf("%s", FPCEnv$tempmodnm)) if (class(eval(modname)[1]) != "try-error") { chk <- try(unlist(summary(eval(modname)))["RSE"], silent = TRUE) if (class(chk)[1] == "try-error") { return(1) } else { modnm <- sprintf("%s", FPCEnv$tempmodnm) FPCEnv$tempparam.select <- substr(modnm, 10, 11) assign(modnm,eval(modname), pcklib) return(eval(modname)) } } else { return(1) } } tstmod <- function(modelsub, modelcurrent) { extraF <- try(get("extraF", pos = 1), silent = TRUE) if (is.na(extraF(modelsub, modelcurrent, warn = F)[4]) == FALSE) { if ((extraF(modelsub, modelcurrent, warn = F)[4]) > 0.05 & sign(extraF(modelsub, modelcurrent, warn = F)[1]) != -1 & FPCEnv$legitmodel[1] == "legitmodelreset") { currentmodel <- modelsub return(currentmodel) } else { if(sign(extraF(modelsub, modelcurrent, warn = F)[1]) != -1 & FPCEnv$legitmodel[1] == "legitmodelreset") { currentmodel <- modelcurrent return(currentmodel) }else{ if (FPCEnv$legitmodel[1] == "legitmodelreset" ) { currentmodel <- modelsub return(currentmodel) } else { currentmodel <- FPCEnv$legitmodel return(currentmodel) } } } } else { if (FPCEnv$legitmodel[1] == "legitmodelreset") { currentmodel <- modelcurrent return(currentmodel) } else { currentmodel <- FPCEnv$legitmodel return(currentmodel) } } } cnt <- 1 step1submod <- FALSE step5submod <- FALSE FPCEnv$tempparam.select <- "NONE" while (cnt < 6) { if (modelsig < 0.05) { if (cnt == 1) { print("Step 1 of a maximum of 6*********************************************************************") print("--ASSESSING MODEL: richardsR1.lis --") richardsR1.lis <- rncheckfirst(richardsR1.lis, existing = existing) if (rncheck(richardsR1.lis, existing = existing) == TRUE) richardsR1.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = RAsym, Rk = Rk, Ri = Ri, RM = RM, modno = 1, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) currentmodel <- rnassign() if (class(currentmodel)[1] != "numeric") step1submod <- TRUE } if (cnt == 2) { print("Step 2 of a maximum of 6*********************************************************************") print("--ASSESSING MODEL: richardsR2.lis --") richardsR2.lis <- rncheckfirst(richardsR2.lis, existing = existing) if (rncheck(richardsR2.lis, existing = existing) == TRUE) richardsR2.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = RAsym, Rk = Rk, Ri = Ri, RM = 1, modno = 2, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR7.lis --") richardsR7.lis <- rncheckfirst(richardsR7.lis, existing = existing) if (rncheck(richardsR7.lis, existing = existing) == TRUE) richardsR7.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = Rk, Ri = Ri, RM = RM, modno = 7, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR6.lis --") richardsR6.lis <- rncheckfirst(richardsR6.lis, existing = existing) if (rncheck(richardsR6.lis, existing = existing) == TRUE) richardsR6.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = RAsym, Rk = 1, Ri = Ri, RM = RM, modno = 6, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR8.lis --") richardsR8.lis <- rncheckfirst(richardsR8.lis, existing = existing) if (rncheck(richardsR8.lis, existing = existing) == TRUE) richardsR8.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = RAsym, Rk = Rk, Ri = 1, RM = RM, modno = 8, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR2.lis, richardsR7.lis, richardsR6.lis, richardsR8.lis) step2stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (cnt == 3) { print("Step 3 of a maximum of 6*********************************************************************") currentmodID3 <- FPCEnv$tempparam.select if (currentmodID3 == "NONE") currentmodID3 = "2." if (currentmodID3 == "2.") { print("--ASSESSING MODEL: richardsR14.lis --") richardsR14.lis <- rncheckfirst(richardsR14.lis, existing = existing) if (rncheck(richardsR14.lis, existing = existing) == TRUE) richardsR14.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = Rk, Ri = Ri, RM = 1, modno = 14, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR13.lis --") richardsR13.lis <- rncheckfirst(richardsR13.lis, existing = existing) if (rncheck(richardsR13.lis, existing = existing) == TRUE) richardsR13.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = RAsym, Rk = 1, Ri = Ri, RM = 1, modno = 13, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR15.lis --") richardsR15.lis <- rncheckfirst(richardsR15.lis, existing = existing) if (rncheck(richardsR15.lis, existing = existing) == TRUE) richardsR15.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = RAsym, Rk = Rk, Ri = 1, RM = 1, modno = 15, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR14.lis, richardsR13.lis, richardsR15.lis) step3stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE") currentmodID3 = "7." if (currentmodID3 == "7.") { print("--ASSESSING MODEL: richardsR14.lis --") richardsR14.lis <- rncheckfirst(richardsR14.lis, existing = existing) if (rncheck(richardsR14.lis, existing = existing) == TRUE) richardsR14.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = Rk, Ri = Ri, RM = 1, modno = 14, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR3.lis --") richardsR3.lis <- rncheckfirst(richardsR3.lis, existing = existing) if (rncheck(richardsR3.lis, existing = existing) == TRUE) richardsR3.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = 1, Ri = Ri, RM = RM, modno = 3, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR9.lis --") richardsR9.lis <- rncheckfirst(richardsR9.lis, existing = existing) if (rncheck(richardsR9.lis, existing = existing) == TRUE) richardsR9.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = Rk, Ri = 1, RM = RM, modno = 9, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR14.lis, richardsR3.lis, richardsR9.lis) step3stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE") currentmodID3 = "6." if (currentmodID3 == "6.") { print("--ASSESSING MODEL: richardsR13.lis --") richardsR13.lis <- rncheckfirst(richardsR13.lis, existing = existing) if (rncheck(richardsR13.lis, existing = existing) == TRUE) richardsR13.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = RAsym, Rk = 1, Ri = Ri, RM = 1, modno = 13, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR3.lis --") richardsR3.lis <- rncheckfirst(richardsR3.lis, existing = existing) if (rncheck(richardsR3.lis, existing = existing) == TRUE) richardsR3.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = 1, Ri = Ri, RM = RM, modno = 3, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR4.lis --") richardsR4.lis <- rncheckfirst(richardsR4.lis, existing = existing) if (rncheck(richardsR4.lis, existing = existing) == TRUE) richardsR4.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = RAsym, Rk = 1, Ri = 1, RM = RM, modno = 4, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR13.lis, richardsR3.lis, richardsR4.lis) step3stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE") currentmodID3 = "8." if (currentmodID3 == "8.") { print("--ASSESSING MODEL: richardsR15.lis --") richardsR15.lis <- rncheckfirst(richardsR15.lis, existing = existing) if (rncheck(richardsR15.lis, existing = existing) == TRUE) richardsR15.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = RAsym, Rk = Rk, Ri = 1, RM = 1, modno = 15, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR9.lis --") richardsR9.lis <- rncheckfirst(richardsR9.lis, existing = existing) if (rncheck(richardsR9.lis, existing = existing) == TRUE) richardsR9.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = Rk, Ri = 1, RM = RM, modno = 9, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR4.lis --") richardsR4.lis <- rncheckfirst(richardsR4.lis, existing = existing) if (rncheck(richardsR4.lis, existing = existing) == TRUE) richardsR4.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = RAsym, Rk = 1, Ri = 1, RM = RM, modno = 4, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR15.lis, richardsR9.lis, richardsR4.lis) step3stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } } if (cnt == 4) { print("Step 4 of a maximum of 6*********************************************************************") currentmodID2 <- FPCEnv$tempparam.select if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "2." currentmodID2 = "14" } if (currentmodID3 == "2." & currentmodID2 == "14") { print("--ASSESSING MODEL: richardsR10.lis --") richardsR10.lis <- rncheckfirst(richardsR10.lis, existing = existing) if (rncheck(richardsR10.lis, existing = existing) == TRUE) richardsR10.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = 1, Ri = Ri, RM = 1, modno = 10, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR16.lis --") richardsR16.lis <- rncheckfirst(richardsR16.lis, existing = existing) if (rncheck(richardsR16.lis, existing = existing) == TRUE) richardsR16.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = Rk, Ri = 1, RM = 1, modno = 16, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR10.lis, richardsR16.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "2." currentmodID2 = "13" } if (currentmodID3 == "2." & currentmodID2 == "13") { print("--ASSESSING MODEL: richardsR10.lis --") richardsR10.lis <- rncheckfirst(richardsR10.lis, existing = existing) if (rncheck(richardsR10.lis, existing = existing) == TRUE) richardsR10.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = 1, Ri = Ri, RM = 1, modno = 10, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR11.lis --") richardsR11.lis <- rncheckfirst(richardsR11.lis, existing = existing) if (rncheck(richardsR11.lis, existing = existing) == TRUE) richardsR11.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = RAsym, Rk = 1, Ri = 1, RM = 1, modno = 11, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR10.lis, richardsR11.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "2." currentmodID2 = "15" } if (currentmodID3 == "2." & currentmodID2 == "15") { print("--ASSESSING MODEL: richardsR16.lis --") richardsR16.lis <- rncheckfirst(richardsR16.lis, existing = existing) if (rncheck(richardsR16.lis, existing = existing) == TRUE) richardsR16.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = Rk, Ri = 1, RM = 1, modno = 16, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR11.lis --") richardsR11.lis <- rncheckfirst(richardsR11.lis, existing = existing) if (rncheck(richardsR11.lis, existing = existing) == TRUE) richardsR11.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = RAsym, Rk = 1, Ri = 1, RM = 1, modno = 11, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR16.lis, richardsR11.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "7." currentmodID2 = "14" } if (currentmodID3 == "7." & currentmodID2 == "14") { print("--ASSESSING MODEL: richardsR10.lis --") richardsR10.lis <- rncheckfirst(richardsR10.lis, existing = existing) if (rncheck(richardsR10.lis, existing = existing) == TRUE) richardsR10.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = 1, Ri = Ri, RM = 1, modno = 10, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR16.lis --") richardsR16.lis <- rncheckfirst(richardsR16.lis, existing = existing) if (rncheck(richardsR16.lis, existing = existing) == TRUE) richardsR16.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = Rk, Ri = 1, RM = 1, modno = 16, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR10.lis, richardsR16.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "7." currentmodID2 = "3." } if (currentmodID3 == "7." & currentmodID2 == "3.") { print("--ASSESSING MODEL: richardsR10.lis --") richardsR10.lis <- rncheckfirst(richardsR10.lis, existing = existing) if (rncheck(richardsR10.lis, existing = existing) == TRUE) richardsR10.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = 1, Ri = Ri, RM = 1, modno = 10, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR5.lis --") richardsR5.lis <- rncheckfirst(richardsR5.lis, existing = existing) if (rncheck(richardsR5.lis, existing = existing) == TRUE) richardsR5.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = 1, Ri = 1, RM = RM, modno = 5, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR10.lis, richardsR5.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "7." currentmodID2 = "9." } if (currentmodID3 == "7." & currentmodID2 == "9.") { print("--ASSESSING MODEL: richardsR16.lis --") richardsR16.lis <- rncheckfirst(richardsR16.lis, existing = existing) if (rncheck(richardsR16.lis, existing = existing) == TRUE) richardsR16.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = Rk, Ri = 1, RM = 1, modno = 16, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR5.lis --") richardsR5.lis <- rncheckfirst(richardsR5.lis, existing = existing) if (rncheck(richardsR5.lis, existing = existing) == TRUE) richardsR5.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = 1, Ri = 1, RM = RM, modno = 5, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR16.lis, richardsR5.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "6." currentmodID2 = "13" } if (currentmodID3 == "6." & currentmodID2 == "13") { print("--ASSESSING MODEL: richardsR10.lis --") richardsR10.lis <- rncheckfirst(richardsR10.lis, existing = existing) if (rncheck(richardsR10.lis, existing = existing) == TRUE) richardsR10.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = 1, Ri = Ri, RM = 1, modno = 10, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR11.lis --") richardsR11.lis <- rncheckfirst(richardsR11.lis, existing = existing) if (rncheck(richardsR11.lis, existing = existing) == TRUE) richardsR11.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = RAsym, Rk = 1, Ri = 1, RM = 1, modno = 11, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR10.lis, richardsR11.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "6." currentmodID2 = "3." } if (currentmodID3 == "6." & currentmodID2 == "3.") { print("--ASSESSING MODEL: richardsR10.lis --") richardsR10.lis <- rncheckfirst(richardsR10.lis, existing = existing) if (rncheck(richardsR10.lis, existing = existing) == TRUE) richardsR10.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = 1, Ri = Ri, RM = 1, modno = 10, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR5.lis --") richardsR5.lis <- rncheckfirst(richardsR5.lis, existing = existing) if (rncheck(richardsR5.lis, existing = existing) == TRUE) richardsR5.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = 1, Ri = 1, RM = RM, modno = 5, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR10.lis, richardsR5.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "6." currentmodID2 = "4." } if (currentmodID3 == "6." & currentmodID2 == "4.") { print("--ASSESSING MODEL: richardsR11.lis --") richardsR11.lis <- rncheckfirst(richardsR11.lis, existing = existing) if (rncheck(richardsR11.lis, existing = existing) == TRUE) richardsR11.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = RAsym, Rk = 1, Ri = 1, RM = 1, modno = 11, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR5.lis --") richardsR5.lis <- rncheckfirst(richardsR5.lis, existing = existing) if (rncheck(richardsR5.lis, existing = existing) == TRUE) richardsR5.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = 1, Ri = 1, RM = RM, modno = 5, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR11.lis, richardsR5.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "8." currentmodID2 = "15" } if (currentmodID3 == "8." & currentmodID2 == "15") { print("--ASSESSING MODEL: richardsR16.lis --") richardsR16.lis <- rncheckfirst(richardsR16.lis, existing = existing) if (rncheck(richardsR16.lis, existing = existing) == TRUE) richardsR16.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = Rk, Ri = 1, RM = 1, modno = 16, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR11.lis --") richardsR11.lis <- rncheckfirst(richardsR11.lis, existing = existing) if (rncheck(richardsR11.lis, existing = existing) == TRUE) richardsR11.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = RAsym, Rk = 1, Ri = 1, RM = 1, modno = 11, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR16.lis, richardsR11.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "8." currentmodID2 = "9." } if (currentmodID3 == "8." & currentmodID2 == "9.") { print("--ASSESSING MODEL: richardsR16.lis --") richardsR16.lis <- rncheckfirst(richardsR16.lis, existing = existing) if (rncheck(richardsR16.lis, existing = existing) == TRUE) richardsR16.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = Rk, Ri = 1, RM = 1, modno = 16, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR5.lis --") richardsR5.lis <- rncheckfirst(richardsR5.lis, existing = existing) if (rncheck(richardsR5.lis, existing = existing) == TRUE) richardsR5.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = 1, Ri = 1, RM = RM, modno = 5, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR16.lis, richardsR5.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "8." currentmodID2 = "4." } if (currentmodID3 == "8." & currentmodID2 == "4.") { print("--ASSESSING MODEL: richardsR11.lis --") richardsR11.lis <- rncheckfirst(richardsR11.lis, existing = existing) if (rncheck(richardsR11.lis, existing = existing) == TRUE) richardsR11.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = RAsym, Rk = 1, Ri = 1, RM = 1, modno = 11, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR5.lis --") richardsR5.lis <- rncheckfirst(richardsR5.lis, existing = existing) if (rncheck(richardsR5.lis, existing = existing) == TRUE) richardsR5.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = 1, Ri = 1, RM = RM, modno = 5, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR11.lis, richardsR5.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } } if (cnt == 5) { print("Step 5 of 6*********************************************************************") currentmodID1 <- FPCEnv$tempparam.select print("--ASSESSING MODEL: richardsR12.lis --") richardsR12.lis <- rncheckfirst(richardsR12.lis, existing = existing) if (rncheck(richardsR12.lis, existing = existing) == TRUE) richardsR12.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = M, RAsym = 1, Rk = 1, Ri = 1, RM = 1, modno = 12, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() step5stat <- extraF(richardsR12.lis, currentmodel, warn = F) step5submod <- TRUE currentmodel <- tstmod(richardsR12.lis, currentmodel) } cnt <- cnt + 1 print("4 param") print(cnt) } else { if (cnt == 1) { print("Step 1 of a maximum of 6*********************************************************************") print("--ASSESSING MODEL: richardsR21.lis --") richardsR21.lis <- rncheckfirst(richardsR21.lis, existing = existing) if (rncheck(richardsR21.lis, existing = existing) == TRUE) richardsR21.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = RAsym, Rk = Rk, Ri = Ri, RM = RM, modno = 21, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) currentmodel <- rnassign() if (class(currentmodel)[1] != "numeric") step1submod <- TRUE } if (cnt == 2) { print("Step 2 of a maximum of 6*********************************************************************") print("--ASSESSING MODEL: richardsR22.lis --") richardsR22.lis <- rncheckfirst(richardsR22.lis, existing = existing) if (rncheck(richardsR22.lis, existing = existing) == TRUE) richardsR22.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = RAsym, Rk = Rk, Ri = Ri, RM = 1, modno = 22, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR27.lis --") richardsR27.lis <- rncheckfirst(richardsR27.lis, existing = existing) if (rncheck(richardsR27.lis, existing = existing) == TRUE) richardsR27.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = Rk, Ri = Ri, RM = RM, modno = 27, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR26.lis --") richardsR26.lis <- rncheckfirst(richardsR26.lis, existing = existing) if (rncheck(richardsR26.lis, existing = existing) == TRUE) richardsR26.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = RAsym, Rk = 1, Ri = Ri, RM = RM, modno = 26, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR28.lis --") richardsR28.lis <- rncheckfirst(richardsR28.lis, existing = existing) if (rncheck(richardsR28.lis, existing = existing) == TRUE) richardsR28.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = RAsym, Rk = Rk, Ri = 1, RM = RM, modno = 28, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR22.lis, richardsR27.lis, richardsR26.lis, richardsR28.lis) step2stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (cnt == 3) { print("Step 3 of a maximum of 6*********************************************************************") currentmodID3 <- FPCEnv$tempparam.select if (currentmodID3 == "NONE") currentmodID3 = "22" if (currentmodID3 == "22") { print("--ASSESSING MODEL: richardsR34.lis --") richardsR34.lis <- rncheckfirst(richardsR34.lis, existing = existing) if (rncheck(richardsR34.lis, existing = existing) == TRUE) richardsR34.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = Rk, Ri = Ri, RM = 1, modno = 34, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR33.lis --") richardsR33.lis <- rncheckfirst(richardsR33.lis, existing = existing) if (rncheck(richardsR33.lis, existing = existing) == TRUE) richardsR33.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = RAsym, Rk = 1, Ri = Ri, RM = 1, modno = 33, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR35.lis --") richardsR35.lis <- rncheckfirst(richardsR35.lis, existing = existing) if (rncheck(richardsR35.lis, existing = existing) == TRUE) richardsR35.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = RAsym, Rk = Rk, Ri = 1, RM = 1, modno = 35, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR34.lis, richardsR33.lis, richardsR35.lis) step3stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE") currentmodID3 = "27" if (currentmodID3 == "27") { print("--ASSESSING MODEL: richardsR34.lis --") richardsR34.lis <- rncheckfirst(richardsR34.lis, existing = existing) if (rncheck(richardsR34.lis, existing = existing) == TRUE) richardsR34.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = Rk, Ri = Ri, RM = 1, modno = 34, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR23.lis --") richardsR23.lis <- rncheckfirst(richardsR23.lis, existing = existing) if (rncheck(richardsR23.lis, existing = existing) == TRUE) richardsR23.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = 1, Ri = Ri, RM = RM, modno = 23, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR29.lis --") richardsR29.lis <- rncheckfirst(richardsR29.lis, existing = existing) if (rncheck(richardsR29.lis, existing = existing) == TRUE) richardsR29.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = Rk, Ri = 1, RM = RM, modno = 29, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR34.lis, richardsR23.lis, richardsR29.lis) step3stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE") currentmodID3 = "26" if (currentmodID3 == "26") { print("--ASSESSING MODEL: richardsR33.lis --") richardsR33.lis <- rncheckfirst(richardsR33.lis, existing = existing) if (rncheck(richardsR33.lis, existing = existing) == TRUE) richardsR33.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = RAsym, Rk = 1, Ri = Ri, RM = 1, modno = 33, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR23.lis --") richardsR23.lis <- rncheckfirst(richardsR23.lis, existing = existing) if (rncheck(richardsR23.lis, existing = existing) == TRUE) richardsR23.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = 1, Ri = Ri, RM = RM, modno = 23, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR24.lis --") richardsR24.lis <- rncheckfirst(richardsR24.lis, existing = existing) if (rncheck(richardsR24.lis, existing = existing) == TRUE) richardsR24.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = RAsym, Rk = 1, Ri = 1, RM = RM, modno = 24, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR33.lis, richardsR23.lis, richardsR24.lis) step3stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE") currentmodID3 = "28" if (currentmodID3 == "28") { print("--ASSESSING MODEL: richardsR35.lis --") richardsR35.lis <- rncheckfirst(richardsR35.lis, existing = existing) if (rncheck(richardsR35.lis, existing = existing) == TRUE) richardsR35.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = RAsym, Rk = Rk, Ri = 1, RM = 1, modno = 35, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR29.lis --") richardsR29.lis <- rncheckfirst(richardsR29.lis, existing = existing) if (rncheck(richardsR29.lis, existing = existing) == TRUE) richardsR29.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = Rk, Ri = 1, RM = RM, modno = 29, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR24.lis --") richardsR24.lis <- rncheckfirst(richardsR24.lis, existing = existing) if (rncheck(richardsR24.lis, existing = existing) == TRUE) richardsR24.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = RAsym, Rk = 1, Ri = 1, RM = RM, modno = 24, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR35.lis, richardsR29.lis, richardsR24.lis) step3stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } } if (cnt == 4) { print("Step 4 of a maximum of 6*********************************************************************") currentmodID2 <- FPCEnv$tempparam.select if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "22" currentmodID2 = "34" } if (currentmodID3 == "22" & currentmodID2 == "34") { print("--ASSESSING MODEL: richardsR30.lis --") richardsR30.lis <- rncheckfirst(richardsR30.lis, existing = existing) if (rncheck(richardsR30.lis, existing = existing) == TRUE) richardsR30.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = 1, Ri = Ri, RM = 1, modno = 30, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR36.lis --") richardsR36.lis <- rncheckfirst(richardsR36.lis, existing = existing) if (rncheck(richardsR36.lis, existing = existing) == TRUE) richardsR36.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = Rk, Ri = 1, RM = 1, modno = 36, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR30.lis, richardsR36.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "22" currentmodID2 = "33" } if (currentmodID3 == "22" & currentmodID2 == "33") { print("--ASSESSING MODEL: richardsR33.lis --") richardsR30.lis <- rncheckfirst(richardsR30.lis, existing = existing) if (rncheck(richardsR30.lis, existing = existing) == TRUE) richardsR30.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = 1, Ri = Ri, RM = 1, modno = 30, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR31.lis --") richardsR31.lis <- rncheckfirst(richardsR31.lis, existing = existing) if (rncheck(richardsR31.lis, existing = existing) == TRUE) richardsR31.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = RAsym, Rk = 1, Ri = 1, RM = 1, modno = 31, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR30.lis, richardsR31.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "22" currentmodID2 = "35" } if (currentmodID3 == "22" & currentmodID2 == "35") { print("--ASSESSING MODEL: richardsR36.lis --") richardsR36.lis <- rncheckfirst(richardsR36.lis, existing = existing) if (rncheck(richardsR36.lis, existing = existing) == TRUE) richardsR36.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = Rk, Ri = 1, RM = 1, modno = 36, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR31.lis --") richardsR31.lis <- rncheckfirst(richardsR31.lis, existing = existing) if (rncheck(richardsR31.lis, existing = existing) == TRUE) richardsR31.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = RAsym, Rk = 1, Ri = 1, RM = 1, modno = 31, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR36.lis, richardsR31.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "27" currentmodID2 = "34" } if (currentmodID3 == "27" & currentmodID2 == "34") { print("--ASSESSING MODEL: richardsR30.lis --") richardsR30.lis <- rncheckfirst(richardsR30.lis, existing = existing) if (rncheck(richardsR30.lis, existing = existing) == TRUE) richardsR30.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = 1, Ri = Ri, RM = 1, modno = 30, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR36.lis --") richardsR36.lis <- rncheckfirst(richardsR36.lis, existing = existing) if (rncheck(richardsR36.lis, existing = existing) == TRUE) richardsR36.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = Rk, Ri = 1, RM = 1, modno = 36, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR30.lis, richardsR36.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "27" currentmodID2 = "23" } if (currentmodID3 == "27" & currentmodID2 == "23") { print("--ASSESSING MODEL: richardsR30.lis --") richardsR30.lis <- rncheckfirst(richardsR30.lis, existing = existing) if (rncheck(richardsR30.lis, existing = existing) == TRUE) richardsR30.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = 1, Ri = Ri, RM = 1, modno = 30, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR25.lis --") richardsR25.lis <- rncheckfirst(richardsR25.lis, existing = existing) if (rncheck(richardsR25.lis, existing = existing) == TRUE) richardsR25.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = 1, Ri = 1, RM = RM, modno = 25, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR30.lis, richardsR25.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "27" currentmodID2 = "29" } if (currentmodID3 == "27" & currentmodID2 == "29") { print("--ASSESSING MODEL: richardsR36.lis --") richardsR36.lis <- rncheckfirst(richardsR36.lis, existing = existing) if (rncheck(richardsR36.lis, existing = existing) == TRUE) richardsR36.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = Rk, Ri = 1, RM = 1, modno = 36, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR25.lis --") richardsR25.lis <- rncheckfirst(richardsR25.lis, existing = existing) if (rncheck(richardsR25.lis, existing = existing) == TRUE) richardsR25.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = 1, Ri = 1, RM = RM, modno = 25, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR36.lis, richardsR25.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "26" currentmodID2 = "33" } if (currentmodID3 == "26" & currentmodID2 == "33") { print("--ASSESSING MODEL: richardsR33.lis --") richardsR30.lis <- rncheckfirst(richardsR30.lis, existing = existing) if (rncheck(richardsR30.lis, existing = existing) == TRUE) richardsR30.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = 1, Ri = Ri, RM = 1, modno = 30, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR31.lis --") richardsR31.lis <- rncheckfirst(richardsR31.lis, existing = existing) if (rncheck(richardsR31.lis, existing = existing) == TRUE) richardsR31.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = RAsym, Rk = 1, Ri = 1, RM = 1, modno = 31, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR30.lis, richardsR31.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "26" currentmodID2 = "23" } if (currentmodID3 == "26" & currentmodID2 == "23") { print("--ASSESSING MODEL: richardsR30.lis --") richardsR30.lis <- rncheckfirst(richardsR30.lis, existing = existing) if (rncheck(richardsR30.lis, existing = existing) == TRUE) richardsR30.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = 1, Ri = Ri, RM = 1, modno = 30, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR25.lis --") richardsR25.lis <- rncheckfirst(richardsR25.lis, existing = existing) if (rncheck(richardsR25.lis, existing = existing) == TRUE) richardsR25.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = 1, Ri = 1, RM = RM, modno = 25, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR30.lis, richardsR25.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "26" currentmodID2 = "24" } if (currentmodID3 == "26" & currentmodID2 == "24") { print("--ASSESSING MODEL: richardsR31.lis --") richardsR31.lis <- rncheckfirst(richardsR31.lis, existing = existing) if (rncheck(richardsR31.lis, existing = existing) == TRUE) richardsR31.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = RAsym, Rk = 1, Ri = 1, RM = 1, modno = 31, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR25.lis --") richardsR25.lis <- rncheckfirst(richardsR25.lis, existing = existing) if (rncheck(richardsR25.lis, existing = existing) == TRUE) richardsR25.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = 1, Ri = 1, RM = RM, modno = 25, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR31.lis, richardsR25.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "28" currentmodID2 = "35" } if (currentmodID3 == "28" & currentmodID2 == "35") { print("--ASSESSING MODEL: richardsR36.lis --") richardsR36.lis <- rncheckfirst(richardsR36.lis, existing = existing) if (rncheck(richardsR36.lis, existing = existing) == TRUE) richardsR36.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = Rk, Ri = 1, RM = 1, modno = 36, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR31.lis --") richardsR31.lis <- rncheckfirst(richardsR31.lis, existing = existing) if (rncheck(richardsR31.lis, existing = existing) == TRUE) richardsR31.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = RAsym, Rk = 1, Ri = 1, RM = 1, modno = 31, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR36.lis, richardsR31.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "28" currentmodID2 = "29" } if (currentmodID3 == "28" & currentmodID2 == "29") { print("--ASSESSING MODEL: richardsR36.lis --") richardsR36.lis <- rncheckfirst(richardsR36.lis, existing = existing) if (rncheck(richardsR36.lis, existing = existing) == TRUE) richardsR36.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = Rk, Ri = 1, RM = 1, modno = 36, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR25.lis --") richardsR25.lis <- rncheckfirst(richardsR25.lis, existing = existing) if (rncheck(richardsR25.lis, existing = existing) == TRUE) richardsR25.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = 1, Ri = 1, RM = RM, modno = 25, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR36.lis, richardsR25.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } if (currentmodID3 == "NONE" & currentmodID2 == "NONE") { currentmodID3 = "28" currentmodID2 = "24" } if (currentmodID3 == "28" & currentmodID2 == "24") { print("--ASSESSING MODEL: richardsR31.lis --") richardsR31.lis <- rncheckfirst(richardsR31.lis, existing = existing) if (rncheck(richardsR31.lis, existing = existing) == TRUE) richardsR31.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = RAsym, Rk = 1, Ri = 1, RM = 1, modno = 31, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() print("--ASSESSING MODEL: richardsR25.lis --") richardsR25.lis <- rncheckfirst(richardsR25.lis, existing = existing) if (rncheck(richardsR25.lis, existing = existing) == TRUE) richardsR25.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = 1, Ri = 1, RM = RM, modno = 25, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() submodel <- rankmod(richardsR31.lis, richardsR25.lis) step4stat <- extraF(submodel, currentmodel, warn = F) currentmodel <- tstmod(submodel, currentmodel) } } if (cnt == 5) { print("Step 5 of 6*********************************************************************") currentmodID1 <- FPCEnv$tempparam.select print("--ASSESSING MODEL: richardsR32.lis --") richardsR32.lis <- rncheckfirst(richardsR32.lis, existing = existing) if (rncheck(richardsR32.lis, existing = existing) == TRUE) richardsR32.lis <- eval(parse(text=sprintf("%s",paste("try({ nlsList(y ~ SSposnegRichards(x, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = 1, Rk = 1, Ri = 1, RM = 1, modno = 32, pn.options = ",pnoptnm,"), data = userdata, ...) }, silent = TRUE)",sep="")))) dump <- rnassign() step5stat <- extraF(richardsR32.lis, currentmodel) step5submod <- TRUE currentmodel <- tstmod(richardsR32.lis, currentmodel) } cnt <- cnt + 1 } } if (modelsig < 0.05) { mod1 <- "1." mod4 <- "12" } else { mod1 <- "21" mod4 <- "32" } if (step5submod == FALSE) { step5submod <- NA step5stat <- NA mod4 <- NA mod5 <- NA step6stat <- NA } else { print("Step 6 of 6*********************************************************************") if (class (mostreducedmod)[1] != "numeric"){ mod5 <- mostreducednm step6stat <- extraF(mostreducedmod, currentmodel, warn = F) currentmodel <- tstmod(mostreducedmod, currentmodel) } else { step6stat <- NA mod5 <- NA } } options(warn = -1) currentmodID3 <- as.numeric(currentmodID3) currentmodID2 <- as.numeric(currentmodID2) currentmodID1 <- as.numeric(currentmodID1) options(warn = 0) if(mod1 == "1.") mod1 <- "1" modnames <- c(paste("richardsR", mod1, ".lis", sep = ""), paste("richardsR", currentmodID3, ".lis", sep = ""), paste("richardsR", currentmodID2, ".lis", sep = ""), paste("richardsR", currentmodID1, ".lis", sep = ""), paste("richardsR", mod4, ".lis", sep = ""), paste("richardsR", mod5, ".lis", sep = "")) modnames[modnames == "richardsRNA.lis"] <- "" modnames[modnames == "richardsRNONE.lis"] <- "" stepwisetable <- data.frame(` Best Submodel at Step` = modnames) testof <- rep("", 6) xf <- rep(NA, 6) dfn <- rep(NA, 6) dfd <- rep(NA, 6) pval <- rep(NA, 6) RSSgen <- rep(NA, 6) RSSsub <- rep(NA, 6) countfit <- 0 for (i in 1:6) { if (i > 1) { if (modnames[i] == "" & modnames[i - 1] == "") { testof[i] <- "No models converged at this step" } else { testof[i] <- paste("| ", modnames[i], " vs ", modnames[i - 1], " |", sep = "") } options(warn = -1) assessfits <- try( eval(parse(text = sprintf("%s", paste("step", i, "stat", sep = "")))),silent = TRUE) if (class(assessfits)[1] != "try-error") countfit <- countfit + 1 if (i == 6 & countfit == 0) stop("No models were successfully fitted. Aborting..... Please check your data or change argument options.") currstat <- eval(parse(text = sprintf("%s", (paste("step", i, "stat", sep = ""))))) options(warn = 0) xf[i] <- round(as.numeric(currstat[1]), 4) dfn[i] <- as.numeric(currstat[2]) dfd[i] <- as.numeric(currstat[3]) pval[i] <- round(as.numeric(currstat[4]), 8) RSSgen[i] <- as.numeric(currstat[5]) RSSsub[i] <- as.numeric(currstat[6]) } else { testof[i] <- "| Reduced model More complex model |" } } modnames1 <- modnames for (i in 2:6) { if (is.na(pval[i]) == FALSE) { if (pval[i] > 0.05 & sign(xf[i]) != -1) { modnames1[i] <- modnames1[i] } else { if (sign(xf[i]) != -1) { modnames1[i] <- modnames1[i - 1] } else { modnames1[i] <- modnames1[i] } } } else { modnames1[i] <- modnames1[i] } } for (i in 2:6) { if (modnames[i] == "" & modnames[i - 1] == "") { testof[i] <- "No models converged at this step" } else { if (modnames[i - 1] != modnames1[i - 1]) testof[i] <- paste("| ", modnames[i], " vs ", modnames1[i - 1], " |", sep = "") } } testof <- unlist(testof) xf <- data.frame(sprintf("%.4f", as.numeric(unlist(xf)))) dfn <- data.frame(as.numeric(unlist(dfn))) dfd <- data.frame(as.numeric(unlist(dfd))) pval <- data.frame(sprintf("%.8f", as.numeric(unlist(pval)))) RSSgen <- data.frame(signif( as.numeric(unlist(RSSgen)),4)) RSSsub <- data.frame(signif( as.numeric(unlist(RSSsub)),4)) stepwisetable <- data.frame(` Best Submodel at Step` = modnames1, Test = testof, `F-stat` = xf, df_n = dfn, df_d = dfd, P = pval, RSS_sub = RSSsub, RSS_gen = RSSgen) names(stepwisetable) <- c(" Best Submodel at Step", "Test ", "F-stat", "df_n", "df_d", "P", "RSS_sub", "RSS_gen") row.names(stepwisetable) <- c("Step 1", "Step 2", "Step 3", "Step 4", "Step 5", "Step 6") stepwisetable[is.na(stepwisetable)] <- "" print(" assign("pn.bestmodel.lis", currentmodel, envir = Envir) print("writing output to environment:") print(Envir) get.mod(to.envir = Envir, write.mod = TRUE) assign("userdata",userdata, envir = Envir) options(warn=-1) try(rm("model1",envir = FPCEnv),silent=T) try(rm("tempparam.select",envir = FPCEnv),silent=T) try(rm("tempmodnm",envir = FPCEnv),silent=T) try(rm("legitmodel",envir = FPCEnv),silent=T) options( warn = 0) return(stepwisetable) } , ex = function(){ subdata<-subset(posneg.data, as.numeric(row.names (posneg.data) ) < 40) modseltable <- pn.modselect.step(subdata$age, subdata$mass, subdata$id, existing = FALSE) subdata<-subset(posneg.data, as.numeric(row.names (posneg.data) ) < 40) richardsR22.lis <- nlsList(mass ~ SSposnegRichards(age, Asym = Asym, K = K, Infl = Infl, M = 1, RAsym = RAsym, Rk = Rk, Ri = Ri, RM = 1 , modno = 22) ,data = subdata) modseltable <- pn.modselect.step(subdata$age, subdata$mass, subdata$id, forcemod = 3, existing = TRUE) modseltable <- pn.modselect.step(subdata$age, subdata$mass, subdata$id, penaliz='1*(n)', existing = TRUE) } )
library(rigr) data(fev) descrip(fev) descrip(fev$fev, fev$height) descrip(fev$fev, fev$height, strata = fev$smoke) greater_10 <- ifelse(fev$age > 10, 1, 0) descrip(fev$fev, fev$height, subset = greater_10) descrip(fev$fev, strata = fev$smoke, above = 2)
"investor" "marketprices" "portfolio_results" "portfolio_results_ts" "DEanalysis"
profoundProFound=function(image=NULL, segim=NULL, objects=NULL, mask=NULL, skycut=1, pixcut=3, tolerance=4, ext=2, reltol=0, cliptol=Inf, sigma=1, smooth=TRUE, SBlim=NULL, SBdilate=NULL, SBN100=100, size=5, shape='disc', iters=6, threshold=1.05, magzero=0, gain=NULL, pixscale=1, sky=NULL, skyRMS=NULL, redosegim=FALSE, redosky=TRUE, redoskysize=21, box=c(100,100), grid=box, skygrid_type = 'new', type='bicubic', skytype='median', skyRMStype='quanlo', roughpedestal=FALSE, sigmasel=1, skypixmin=prod(box)/2, boxadd=box/2, boxiters=0, conviters=100, iterskyloc=TRUE, deblend=FALSE, df=3, radtrunc=2, iterative=FALSE, doclip=TRUE, shiftloc = FALSE, paddim = TRUE, header=NULL, verbose=FALSE, plot=FALSE, stats=TRUE, rotstats=FALSE, boundstats=FALSE, nearstats=boundstats, groupstats=boundstats, group=NULL, groupby='segim_orig', offset=1, haralickstats=FALSE, sortcol="segID", decreasing=FALSE, lowmemory=FALSE, keepim=TRUE, watershed='ProFound', pixelcov=FALSE, deblendtype='fit', psf=NULL, fluxweight='sum', convtype = 'brute', convmode = 'extended', fluxtype='Raw', app_diam=1, Ndeblendlim=Inf, ...){ if(verbose){message('Running ProFound:')} timestart=proc.time()[3] call=match.call() if(length(box)==1){ box=rep(box,2) if(missing(grid)){grid=box} if(missing(boxadd)){boxadd=box/2} if(missing(skypixmin)){skypixmin=prod(box)/2} } if(length(grid)==1){ grid=rep(grid,2) } if(length(boxadd)==1){ boxadd=rep(boxadd,2) } fluxtype=tolower(fluxtype) if(skytype == 'mode' | skytype == 'converge'){ skygrid_type = 'old' } if(fluxtype=='raw' | fluxtype=='adu' | fluxtype=='adus'){ if(verbose){message('Using raw flux units')} fluxscale=1 }else if (fluxtype=='jansky'){ if(verbose){message('Using Jansky flux units (WARNING: magzero must take system to AB)')} fluxscale=10^(-0.4*(magzero-8.9)) }else if (fluxtype=='microjansky'){ if(verbose){message('Using Micro-Jansky flux units (WARNING: magzero must take system to AB)')} fluxscale=10^(-0.4*(magzero-23.9)) }else{ stop('fluxtype must be Jansky / Microjansky / Raw!') } if(!is.null(image)){ if(any(names(image)=='imDat') & is.null(header)){ if(verbose){message('Supplied image contains image and header components')} header=image$hdr image=image$imDat }else if(any(names(image)=='imDat') & !is.null(header)){ if(verbose){message('Supplied image contains image and header but using specified header')} image=image$imDat } if(any(names(image)=='dat') & is.null(header)){ if(verbose){message('Supplied image contains image and header components')} header=image$hdr[[1]] header=data.frame(key=header[,1],value=header[,2], stringsAsFactors = FALSE) image=image$dat[[1]] }else if(any(names(image)=='dat') & !is.null(header)){ if(verbose){message('Supplied image contains image and header but using specified header')} image=image$dat[[1]] } if(any(names(image)=='image') & is.null(header)){ if(verbose){message('Supplied image contains image and header components')} header=image$header image=image$image }else if(any(names(image)=='image') & !is.null(header)){ if(verbose){message('Supplied image contains image and header but using specified header')} image=image$image } }else{ stop('Missing image - this is a required input!') } if(box[1] > ceiling(dim(image)[1]/3)){ box[1] = ceiling(dim(image)[1]/3) message('dim(image)[1]/box[1] must be >=3, box[1] modified to ',box[1]) } if(box[2] > ceiling(dim(image)[1]/3)){ box[2] = ceiling(dim(image)[2]/3) message('dim(image)[2]/box[2] must be >=3, box[2] modified to ',box[2]) } if(grid[1] > ceiling(dim(image)[1]/3)){ grid[1] = ceiling(dim(image)[1]/3) message('dim(image)[1]/grid[1] must be >=3, grid[1] modified to ',grid[1]) } if(grid[2] > ceiling(dim(image)[1]/3)){ grid[2] = ceiling(dim(image)[2]/3) message('dim(image)[2]/grid[2] must be >=3, grid[2] modified to ',grid[2]) } if(verbose){message(paste('Supplied image is',dim(image)[1],'x',dim(image)[2],'pixels'))} badpix=NULL if(!is.null(mask)){ mask=mask*1L if(length(mask)==1 & !is.na(mask[1])){ maskflag=mask mask=matrix(0L,dim(image)[1],dim(image)[2]) mask[image==maskflag]=1L } if(anyNA(image)){ badpix=which(is.na(image)) mask[badpix]=1L image[badpix]=0 } if(is.numeric(mask)){ mask=as.integer(mask) attributes(mask)$dim = dim(image) } }else{ if(anyNA(image)){ mask=matrix(0L,dim(image)[1],dim(image)[2]) badpix=which(is.na(image)) mask[badpix]=1L image[badpix]=0 } } if(missing(pixscale) & !is.null(header)){ pixscale=getpixscale(header) if(verbose){message(paste('Extracted pixel scale from header provided:',signif(pixscale,4),'asec/pixel'))} }else{ if(verbose){message(paste('Using suggested pixel scale:',signif(pixscale,4),'asec/pixel'))} } imarea=prod(dim(image))*pixscale^2/(3600^2) if(verbose){message(paste('Supplied image is',signif(dim(image)[1]*pixscale/60,4),'x',signif(dim(image)[2]*pixscale/60,4),'amin, ', signif(imarea,4),'deg-sq'))} if(is.null(objects)){ if(!is.null(segim)){ objects=matrix(0L,dim(segim)[1],dim(segim)[2]) objects[]=as.logical(segim) } }else{ objects=objects*1L } hassky=!is.null(sky) hasskyRMS=!is.null(skyRMS) if((hassky==FALSE | hasskyRMS==FALSE) & is.null(segim)){ if(verbose){message(paste('Making initial sky map -',round(proc.time()[3]-timestart,3),'sec'))} roughsky=profoundMakeSkyGrid(image=image, objects=objects, mask=mask, box=box, grid=grid, skygrid_type=skygrid_type, type=type, skytype=skytype, skyRMStype=skyRMStype, sigmasel=sigmasel, skypixmin=skypixmin, boxadd=boxadd, boxiters=0, conviters=conviters, doclip=doclip, shiftloc=shiftloc, paddim=paddim) if(roughpedestal){ roughsky$sky=median(roughsky$sky,na.rm=TRUE) roughsky$skyRMS=median(roughsky$skyRMS,na.rm=TRUE) } if(hassky==FALSE){ sky=roughsky$sky if(verbose){message(' - Sky statistics :')} if(verbose){print(summary(as.numeric(sky)))} } if(hasskyRMS==FALSE){ skyRMS=roughsky$skyRMS if(verbose){message(' - Sky-RMS statistics :')} if(verbose){print(summary(as.numeric(skyRMS)))} } rm(roughsky) }else{ if(verbose){message("Skipping making initial sky map - User provided sky and sky RMS, or user provided segim")} } if(is.null(segim)){ if(verbose){message(paste('Making initial segmentation image -',round(proc.time()[3]-timestart,3),'sec'))} segim=profoundMakeSegim(image=image, objects=objects, mask=mask, tolerance=tolerance, ext=ext, reltol=reltol, cliptol=cliptol, sigma=sigma, smooth=smooth, pixcut=pixcut, skycut=skycut, SBlim=SBlim, sky=sky, skyRMS=skyRMS, magzero=magzero, pixscale=pixscale, verbose=verbose, watershed=watershed, plot=FALSE, stats=FALSE) objects=segim$objects segim=segim$segim }else{ redosegim=FALSE if(verbose){message("Skipping making an initial segmentation image - User provided segim")} } if(any(segim>0)){ if((hassky==FALSE | hasskyRMS==FALSE)){ if(redosky){ if(verbose){message(paste('Doing initial aggressive dilation -',round(proc.time()[3]-timestart,3),'sec'))} objects_redo=profoundMakeSegimDilate(segim=objects, size=redoskysize, shape=shape, sky=sky, verbose=verbose, plot=FALSE, stats=FALSE, rotstats=FALSE)$objects }else{ objects_redo=objects } if(verbose){message(paste('Making better sky map -',round(proc.time()[3]-timestart,3),'sec'))} if(hassky==FALSE){rm(sky)} if(hasskyRMS==FALSE){rm(skyRMS)} bettersky=profoundMakeSkyGrid(image=image, objects=objects_redo, mask=mask, box=box, skygrid_type=skygrid_type, grid=grid, type=type, skytype=skytype, skyRMStype=skyRMStype, sigmasel=sigmasel, skypixmin=skypixmin, boxadd=boxadd, boxiters=boxiters, conviters=conviters, doclip=doclip, shiftloc=shiftloc, paddim=paddim) if(hassky==FALSE){ sky=bettersky$sky if(verbose){message(' - Sky statistics :')} if(verbose){print(summary(as.numeric(sky)))} } if(hasskyRMS==FALSE){ skyRMS=bettersky$skyRMS if(verbose){message(' - Sky-RMS statistics :')} if(verbose){print(summary(as.numeric(skyRMS)))} } rm(bettersky) if(redosegim){ if(verbose){message(paste('Making better segmentation image -',round(proc.time()[3]-timestart,3),'sec'))} imagescale=(image-sky)/skyRMS imagescale[!is.finite(imagescale)]=0 if(!is.null(SBlim) & !missing(magzero)){ imagescale[imagescale<skycut | sky<profoundSB2Flux(SBlim, magzero, pixscale)]=0 }else{ imagescale[imagescale<skycut]=0 } if(!is.null(mask)){ imagescale[mask!=0]=0 } segim[imagescale==0]=0 objects[segim==0]=0 } }else{ if(verbose){message("Skipping making better sky map - User provided sky and sky RMS")} } if(iters>0 | iterskyloc){ if(verbose){message(paste('Calculating initial segstats -',round(proc.time()[3]-timestart,3),'sec'))} if(length(sky)>1){ skystats=.profoundFluxCalcMin(image=sky, segim=segim, mask=mask) skystats=skystats$flux/skystats$N100 skymed=median(skystats, na.rm=TRUE) }else{ skystats=sky skymed=sky } segstats=.profoundFluxCalcMin(image=image, segim=segim, mask=mask) segstats$flux = segstats$flux - (skystats * segstats$N100) origfrac = segstats$flux segim_orig=segim expand_segID=segstats[,'segID'] SBlast=rep(Inf,length(expand_segID)) selseg=rep(0,length(expand_segID)) if(is.null(SBdilate)){ SBdilate=Inf }else{ skyRMSstats = .profoundFluxCalcMin(image=skyRMS, segim=segim, mask=mask) skyRMSstats = skyRMSstats$flux/skyRMSstats$N100 SBdilate = skyRMSstats * 10^(-0.4*SBdilate) SBdilate[!is.finite(SBdilate)]=Inf } if(verbose){message('Doing dilations:')} if(iters>0){ for(i in 1:(iters)){ if(verbose){message(paste('Iteration',i,'of',iters,'-',round(proc.time()[3]-timestart,3),'sec'))} segim_new=profoundMakeSegimDilate(segim=segim, expand=expand_segID, size=size, shape=shape, verbose=verbose, plot=FALSE, stats=FALSE, rotstats=FALSE)$segim segstats_new=.profoundFluxCalcMin(image=image, segim=segim_new, mask=mask) segstats_new$flux = segstats_new$flux - (skystats * segstats_new$N100) N100diff = (segstats_new$N100-segstats$N100) SBnew=(segstats_new$flux - segstats$flux) / N100diff fluxgrowthratio = segstats_new$flux / segstats$flux skyfrac = abs(((skystats-skymed) * N100diff) / (segstats_new$flux - segstats$flux)) expand_segID=segstats[which((fluxgrowthratio > threshold | (SBnew > SBdilate & N100diff>SBN100)) & segstats_new$flux>0 & SBnew < SBlast & skyfrac < 0.5 & selseg==(i-1)),'segID'] expand_segID=expand_segID[is.finite(expand_segID)] if(length(expand_segID)==0){break} updateID=which(segstats$segID %in% expand_segID) selseg[updateID] = i segstats[updateID,] = segstats_new[updateID,] SBlast = SBnew if('fastmatch' %in% .packages()){ selpix = which(fastmatch::fmatch(segim_new, expand_segID, nomatch = 0L) > 0) }else{ selpix = which(segim_new %in% expand_segID) } segim[selpix]=segim_new[selpix] } } if(iterskyloc){ segim_skyloc = profoundMakeSegimDilate(segim=segim, size=size, shape=shape, verbose=verbose, plot=FALSE, stats=FALSE, rotstats=FALSE)$segim segstats_new = .profoundFluxCalcMin(image=image, segim=segim_skyloc, mask=mask) segstats$flux = segstats$flux + (skystats * segstats$N100) skyseg_mean=(segstats_new$flux-segstats$flux)/(segstats_new$N100-segstats$N100) skyseg_mean[!is.finite(skyseg_mean)]=0 } objects=matrix(0L,dim(segim)[1],dim(segim)[2]) objects[]=as.logical(segim) origfrac = origfrac / (segstats$flux - (skystats * segstats$N100)) }else{ if(verbose){message('Iters set to 0 - keeping segim un-dilated')} segim_orig=segim selseg=0 origfrac=1 skyseg_mean=NA } if(redosky){ if(redoskysize %% 2 == 0){redoskysize=redoskysize+1} if(verbose){message(paste('Doing final aggressive dilation -',round(proc.time()[3]-timestart,3),'sec'))} objects_redo=profoundMakeSegimDilate(segim=objects, mask=mask, size=redoskysize, shape=shape, sky=sky, verbose=verbose, plot=FALSE, stats=FALSE, rotstats=FALSE)$objects if(verbose){message(paste('Making final sky map -',round(proc.time()[3]-timestart,3),'sec'))} rm(skyRMS) sky = profoundMakeSkyGrid(image=image, objects=objects_redo, mask=mask, sky=sky, box=box, skygrid_type=skygrid_type, grid=grid, type=type, skytype=skytype, skyRMStype=skyRMStype, sigmasel=sigmasel, skypixmin=skypixmin, boxadd=boxadd, boxiters=boxiters, conviters=conviters, doclip=doclip, shiftloc=shiftloc, paddim=paddim)$sky if(verbose){message(paste('Making final sky RMS map -',round(proc.time()[3]-timestart,3),'sec'))} skyRMS = profoundMakeSkyGrid(image=image, objects=objects_redo, mask=mask, sky=sky, box=box, skygrid_type=skygrid_type, grid=grid, type=type, skytype=skytype, skyRMStype=skyRMStype, sigmasel=sigmasel, skypixmin=skypixmin, boxadd=boxadd, boxiters=boxiters, conviters=conviters, doclip=doclip, shiftloc=shiftloc, paddim=paddim)$skyRMS if(verbose){message(' - Sky statistics :')} if(verbose){print(summary(as.numeric(sky)))} if(verbose){message(' - Sky-RMS statistics :')} if(verbose){print(summary(as.numeric(skyRMS)))} }else{ if(verbose){message("Skipping making final sky map - redosky set to FALSE")} objects_redo=NULL } Norig=tabulate(segim_orig) if(is.function(pixelcov)){ cor_err_func=pixelcov }else{ if(pixelcov){ if(verbose){message(paste('Calculating pixel covariance -',round(proc.time()[3]-timestart,3),'sec'))} cor_err_func=profoundPixelCorrelation(image=image, objects=objects, mask=mask, sky=sky, skyRMS=skyRMS, fft=FALSE, lag=apply(expand.grid(c(1,2,4),c(1,10,100,1000,1e4)),MARGIN=1,FUN=prod))$cor_err_func }else{ cor_err_func=NULL } } if(lowmemory){ image=image-sky sky=0 skyRMS=0 segim_orig=NULL objects=NULL objects_redo=NULL } if(stats & !is.null(image)){ if(verbose){message(paste('Calculating final segstats for',length(which(tabulate(segim)>0)),'objects -',round(proc.time()[3]-timestart,3),'sec'))} if(verbose){message(paste(' - magzero =', signif(magzero,4)))} if(verbose){ if(is.null(gain)){ message(paste(' - gain = NULL (ignored)')) }else{ message(paste(' - gain =', signif(gain,4))) } } if(verbose){message(paste(' - pixscale =', signif(pixscale,4)))} if(verbose){message(paste(' - rotstats =', rotstats))} if(verbose){message(paste(' - boundstats =', boundstats))} segstats=profoundSegimStats(image=image, segim=segim, mask=mask, sky=sky, skyRMS=skyRMS, magzero=magzero, gain=gain, pixscale=pixscale, header=header, sortcol=sortcol, decreasing=decreasing, rotstats=rotstats, boundstats=boundstats, offset=offset, cor_err_func=cor_err_func, app_diam=app_diam) segstats=cbind(segstats, iter=selseg, origfrac=origfrac, Norig=Norig[segstats$segID], skyseg_mean=skyseg_mean) segstats=cbind(segstats, flag_keep=segstats$origfrac>= median(segstats$origfrac[segstats$iter==iters]) | segstats$iter<iters) }else{ if(verbose){message("Skipping segmentation statistics - segstats set to FALSE")} segstats=NULL } if(nearstats){ near=profoundSegimNear(segim=segim, offset=offset) }else{ near=NULL } if(deblend){ groupstats=TRUE } if(groupstats){ if(verbose){message(paste(' - groupstats = TRUE - ',round(proc.time()[3]-timestart,3),'sec'))} if(groupby=='segim'){ if(is.null(group)){ group=profoundSegimGroup(segim) } }else if(groupby=='segim_orig'){ if(is.null(group)){ group=profoundSegimGroup(segim_orig) if(any(group$groupsegID$Ngroup>1)){ group$groupim=profoundSegimKeep(segim=segim, segID_merge=group$groupsegID[group$groupsegID$Ngroup>1,'segID']) group$groupsegID$Npix=tabulate(group$groupim)[group$groupsegID$groupID] } } }else{ stop('Non legal groupby option, must be segim or segim_orig!') } if(stats & !is.null(image) & !is.null(group)){ groupstats=profoundSegimStats(image=image, segim=group$groupim, mask=mask, sky=sky, skyRMS=skyRMS, magzero=magzero, gain=gain, pixscale=pixscale, header=header, sortcol=sortcol, decreasing=decreasing, rotstats=rotstats, boundstats=boundstats, offset=offset, cor_err_func=cor_err_func, app_diam=app_diam) colnames(groupstats)[1]='groupID' }else{ groupstats=NULL } }else{ if(verbose){message(' - groupstats = FALSE')} group=NULL groupstats=NULL } if(deblend & stats & !is.null(image) & any(group$groupsegID$Ngroup>1)){ if(verbose){message(paste(' - deblend = TRUE - ',round(proc.time()[3]-timestart,3),'sec'))} tempblend=profoundFluxDeblend(image=image-sky, segim=segim, segstats=segstats, groupim=group$groupim, groupsegID=group$groupsegID, magzero=magzero, df=df, radtrunc=radtrunc, iterative=iterative, doallstats=TRUE, deblendtype=deblendtype, psf=psf, fluxweight=fluxweight, convtype=convtype, convmode=convmode, Ndeblendlim = Ndeblendlim) if(!is.null(tempblend)){ segstats=cbind(segstats,tempblend[,-2]) } }else{ if(verbose){message(' - deblend = FALSE')} } if(haralickstats){ if(requireNamespace("EBImage", quietly = TRUE)){ scale=10^(0.4*(30-magzero)) temphara=(image-sky)*scale if(!is.null(mask)){ temphara[mask!=0]=0 } temphara[!is.finite(temphara)]=0 haralick=as.data.frame(EBImage::computeFeatures.haralick(segim,temphara)) haralick=haralick[segstats$segID,] }else{ if(verbose){ message('The EBImage package is needed to compute Haralick statistics.') haralick=NULL } } }else{ haralick=NULL } if(plot){ if(verbose){message(paste('Plotting segments -',round(proc.time()[3]-timestart,3),'sec'))} if(any(is.finite(sky))){ profoundSegimPlot(image=image-sky, segim=segim, mask=mask, header=header, ...) }else{ profoundSegimPlot(image=image, segim=segim, mask=mask, header=header, ...) } }else{ if(verbose){message("Skipping segmentation plot - plot = FALSE")} } if(is.null(SBlim)){ SBlim=NULL }else if(is.numeric(SBlim)){ SBlimtemp=profoundFlux2SB(flux=skyRMS*skycut, magzero=magzero, pixscale=pixscale) SBlimtemp=matrix(SBlimtemp,dim(skyRMS)[1],dim(skyRMS)[2]) SBlimtemp[which(SBlimtemp>SBlim)]=SBlim SBlim=SBlimtemp }else if(SBlim[1]=='get' & skycut> -Inf){ SBlim=profoundFlux2SB(flux=skyRMS*skycut, magzero=magzero, pixscale=pixscale) } if(is.null(header)){header=NULL} if(keepim==FALSE){image=NULL; mask=NULL} if(is.null(mask)){mask=NULL} if(!is.null(badpix)){image[badpix]=NA} row.names(segstats)=NULL segstats[,grep('flux',colnames(segstats))] = fluxscale*segstats[,grep('flux',colnames(segstats))] if(stats){ cutsky = (image - sky) / skyRMS cutsky[!is.finite(cutsky)] = NA if(!is.null(mask)){ cutsky[mask==1] = NA } if(!is.null(objects_redo)){ cutsky[objects_redo == 1] = NA }else{ cutsky[objects == 1] = NA } cutsky = cutsky[which(cutsky<=0)] if(length(cutsky) > 0){ skyLL = dchisq(sum(cutsky^2, na.rm =TRUE), df=length(cutsky)-1, log=TRUE) }else{ skyLL = NA } }else{ skyLL = NULL } if(verbose){message(paste('ProFound is finished! -',round(proc.time()[3]-timestart,3),'sec'))} output=list(segim=segim, segim_orig=segim_orig, objects=objects, objects_redo=objects_redo, sky=sky, skyRMS=skyRMS, image=image, mask=mask, segstats=segstats, Nseg=dim(segstats)[1], near=near, group=group, groupstats=groupstats, haralick=haralick, header=header, SBlim=SBlim, magzero=magzero, dim=dim(segim), pixscale=pixscale, imarea=imarea, skyLL=skyLL, gain=gain, call=call, date=date(), time=proc.time()[3]-timestart, ProFound.version=packageVersion('ProFound'), R.version=R.version) }else{ if(is.null(header)){header=NULL} if(keepim==FALSE){image=NULL; mask=NULL} if(is.null(mask)){mask=NULL} if(!is.null(badpix)){image[badpix]=NA} if(verbose){message('No objects in segmentation map - skipping dilations and CoG')} if(verbose){message(paste('ProFound is finished! -',round(proc.time()[3]-timestart,3),'sec'))} output=list(segim=NULL, segim_orig=NULL, objects=NULL, objects_redo=NULL, sky=sky, skyRMS=skyRMS, image=image, mask=mask, segstats=NULL, Nseg=0, near=NULL, group=NULL, groupstats=NULL, haralick=NULL, header=header, SBlim=NULL, magzero=magzero, dim=dim(segim), pixscale=pixscale, imarea=imarea, skyLL=skyLL, gain=gain, call=call, date=date(), time=proc.time()[3]-timestart, ProFound.version=packageVersion('ProFound'), R.version=R.version) } class(output)='profound' return(invisible(output)) } plot.profound=function(x, logR50=TRUE, dmag=0.5, hist='sky', ...){ if(class(x)!='profound'){ stop('Object class is not of type profound!') } if(is.null(x$image)){ stop('Missing image!') } if(is.null(x$segim)){ stop('Missing segmentation map!') } if(is.null(x$sky)){ x$sky=matrix(0, x$dim[1], x$dim[2]) } if(length(x$sky)==1){ x$sky=matrix(x$sky, x$dim[1], x$dim[2]) } if(is.null(x$skyRMS)){ x$skyRMS=matrix(1, x$dim[1], x$dim[2]) } if(length(x$skyRMS)==1){ x$skyRMS=matrix(x$skyRMS, x$dim[1], x$dim[2]) } segdiff=x$segim-x$segim_orig segdiff[segdiff<0]=0 if(all(x$skyRMS>0, na.rm=TRUE)){ image = (x$image-x$sky)/x$skyRMS }else{ image = (x$image-x$sky) } if(!is.null(x$mask)){ image[x$mask==1]=NA } cmap = rev(colorRampPalette(brewer.pal(9,'RdYlBu'))(100)) maximg = quantile(abs(image[is.finite(image)]), 0.995, na.rm=TRUE) stretchscale = 1/median(abs(image), na.rm=TRUE) layout(matrix(1:9, 3, byrow=TRUE)) if(!is.null(x$header)){ par(mar=c(3.5,3.5,0.5,0.5)) magimageWCS(image, x$header, stretchscale=stretchscale, locut=-maximg, hicut=maximg, range=c(-1,1), type='num', zlim=c(-1,1), col=cmap) if(!is.null(x$mask)){magimage(x$mask!=0, col=c(NA,hsv(alpha=0.2)), add=TRUE, magmap=FALSE, zlim=c(0,1))} par(mar=c(3.5,3.5,0.5,0.5)) magimageWCS(x$segim, x$header, col=c(NA, rainbow(max(x$segim,na.rm=TRUE), end=2/3)), magmap=FALSE) if(!is.null(x$mask)){magimage(x$mask!=0, col=c(NA,hsv(alpha=0.2)), add=TRUE, magmap=FALSE, zlim=c(0,1))} abline(v=c(0,dim(x$image)[1])) abline(h=c(0,dim(x$image)[2])) par(mar=c(3.5,3.5,0.5,0.5)) magimageWCS(image, x$header) magimage(segdiff, col=c(NA, rainbow(max(x$segim,na.rm=TRUE), end=2/3)), magmap=FALSE, add=TRUE) if(!is.null(x$mask)){magimage(x$mask!=0, col=c(NA,hsv(alpha=0.2)), add=TRUE, magmap=FALSE, zlim=c(0,1))} par(mar=c(3.5,3.5,0.5,0.5)) if(is.null(x$imarea)){ imarea=prod(x$dim)*x$pixscale^2/(3600^2) }else{ imarea=x$imarea } temphist=maghist(x$segstats$mag, log='y', scale=(2*dmag)/x$imarea, breaks=seq(floor(min(x$segstats$mag, na.rm = TRUE)), ceiling(max(x$segstats$mag, na.rm = TRUE)),by=0.5), xlab='mag', ylab=paste(' ymax=log10(max(temphist$counts,na.rm = T)) xmax=temphist$mids[which.max(temphist$counts)] abline(ymax - xmax*0.4, 0.4, col='red') abline(v=xmax+0.25, col='red') axis(side=1, at=xmax+0.25, labels=xmax+0.25, tick=FALSE, line=-1, col.axis='red') legend('topleft', legend=paste('N:',length(x$segstats$mag))) par(mar=c(3.5,3.5,0.5,0.5)) magimageWCS(x$sky-median(x$sky,na.rm=TRUE), x$header, qdiff=TRUE) if(!is.null(x$mask)){ magimage(x$mask!=0, col=c(NA,hsv(alpha=0.2)), add=TRUE, magmap=FALSE, zlim=c(0,1)) stat_mean = signif(mean(x$sky[x$mask==0], na.rm=TRUE),4) stat_sd = signif(sd(x$sky[x$mask==0], na.rm=TRUE),4) stat_cor = signif(cor(as.numeric(x$sky[x$mask==0]), as.numeric(x$skyRMS[x$mask==0])^2, use="pairwise.complete.obs"),4) }else{ stat_mean = signif(mean(x$sky, na.rm=TRUE),4) stat_sd = signif(sd(x$sky, na.rm=TRUE),4) stat_cor = signif(cor(as.numeric(x$sky), as.numeric(x$skyRMS)^2, use="pairwise.complete.obs"),4) } legend('topleft',legend=c('Sky',paste0('Mean: ',stat_mean),paste0('SD: ',stat_sd)),bg='white') par(mar=c(3.5,3.5,0.5,0.5)) magimageWCS(x$skyRMS, x$header) if(!is.null(x$mask)){ magimage(x$mask!=0, col=c(NA,hsv(alpha=0.2)), add=TRUE, magmap=FALSE, zlim=c(0,1)) stat_mean = signif(mean(x$skyRMS[x$mask==0], na.rm=TRUE),4) stat_sd = signif(sd(x$skyRMS[x$mask==0], na.rm=TRUE),4) }else{ stat_mean = signif(mean(x$skyRMS, na.rm=TRUE),4) stat_sd = signif(sd(x$skyRMS, na.rm=TRUE),4) } legend('topleft',legend=c('Sky RMS',paste0('Mean: ',stat_mean),paste0('SD: ',stat_sd)),bg='white') if(hist=='iters'){ maghist(x$segstats$iter, breaks=seq(-0.5,max(x$segstats$iter, na.rm=TRUE)+0.5,by=1), majorn=max(x$segstats$iter, na.rm=TRUE)+1, xlab='Number of Dilations', ylab=' }else if(hist=='sky'){ try({ if(!is.null(x$objects_redo)){ tempsky=image[x$objects_redo==0] }else{ tempsky=image[x$objects==0] } tempsky=tempsky[tempsky > -8 & tempsky < 8 & !is.na(tempsky)] stat_LL = signif(x$skyLL,4) magplot(density(tempsky[is.finite(tempsky)], bw=0.1), grid=TRUE, xlim=c(-6,6), xlab='(image - sky) / skyRMS', ylab='PDF', log='y', ylim=c(1e-8,0.5)) curve(dnorm(x, mean=0, sd=1), add=TRUE, col='red', lty=2) legend('topleft',legend=c('Sky Pixels',paste0('Cor: ',stat_cor), paste0('sky LL: ',stat_LL)), bg='white') }) }else{stop('Not a recognised hist type! Must be iters / sky.')} par(mar=c(3.5,3.5,0.5,0.5)) if(logR50){ magplot(x$segstats$mag, x$segstats$R50, pch='.', col=hsv(alpha=0.5), ylim=c(min(x$segstats$R50, 0.1, na.rm = TRUE), max(x$segstats$R50, 1, na.rm = TRUE)), cex=3, xlab='mag', ylab='R50 / asec', grid=TRUE, log='y') }else{ magplot(x$segstats$mag, x$segstats$R50, pch='.', col=hsv(alpha=0.5), ylim=c(0, max(x$segstats$R50, 1, na.rm = TRUE)), cex=3, xlab='mag', ylab='R50 / asec', grid=TRUE) } par(mar=c(3.5,3.5,0.5,0.5)) fluxrat=x$segstats$flux/x$segstats$flux_err magplot(x$segstats$SB_N90, fluxrat, pch='.', col=hsv(alpha=0.5), ylim=c(0.5,max(fluxrat, 1, na.rm=TRUE)), cex=3, xlab='SB90 / mag/asec-sq', ylab='Flux/Flux-Error', grid=TRUE, log='y') }else{ par(mar=c(3.5,3.5,0.5,0.5)) magimage(image, stretchscale=stretchscale, locut=-maximg, hicut=maximg, range=c(-1,1), type='num', zlim=c(-1,1), col=cmap) if(!is.null(x$mask)){magimage(x$mask!=0, col=c(NA,hsv(alpha=0.2)), add=TRUE, magmap=FALSE, zlim=c(0,1))} par(mar=c(3.5,3.5,0.5,0.5)) magimage(x$segim, col=c(NA, rainbow(max(x$segim,na.rm=TRUE), end=2/3)), magmap=FALSE) if(!is.null(x$mask)){magimage(x$mask!=0, col=c(NA,hsv(alpha=0.2)), add=TRUE, magmap=FALSE, zlim=c(0,1))} abline(v=c(0,dim(image)[1])) abline(h=c(0,dim(image)[2])) par(mar=c(3.5,3.5,0.5,0.5)) magimage(image) magimage(segdiff, col=c(NA, rainbow(max(x$segim,na.rm=TRUE), end=2/3)), magmap=FALSE, add=TRUE) if(!is.null(x$mask)){magimage(x$mask!=0, col=c(NA,hsv(alpha=0.2)), add=TRUE, magmap=FALSE, zlim=c(0,1))} par(mar=c(3.5,3.5,0.5,0.5)) temphist=maghist(x$segstats$mag, log='y', scale=(2*dmag), breaks=seq(floor(min(x$segstats$mag, na.rm = TRUE)), ceiling(max(x$segstats$mag, na.rm = TRUE)),by=0.5), xlab='mag', ylab=paste(' ymax=log10(max(temphist$counts,na.rm = T)) xmax=temphist$mids[which.max(temphist$counts)] abline(ymax - xmax*0.4, 0.4, col='red') abline(v=xmax+0.25, col='red') axis(side=1, at=xmax+0.25, labels=xmax+0.25, tick=FALSE, line=-1, col.axis='red') legend('topleft', legend=paste('N:',length(x$segstats$mag))) par(mar=c(3.5,3.5,0.5,0.5)) magimage(x$sky-median(x$sky,na.rm=TRUE), qdiff=TRUE) if(!is.null(x$mask)){ magimage(x$mask!=0, col=c(NA,hsv(alpha=0.2)), add=TRUE, magmap=FALSE, zlim=c(0,1)) stat_mean = signif(mean(x$sky[x$mask==0], na.rm=TRUE),4) stat_sd = signif(sd(x$sky[x$mask==0], na.rm=TRUE),4) stat_cor = signif(cor(as.numeric(x$sky[x$mask==0]), as.numeric(x$skyRMS[x$mask==0])^2, use="pairwise.complete.obs"),4) }else{ stat_mean = signif(mean(x$sky, na.rm=TRUE),4) stat_sd = signif(sd(x$sky, na.rm=TRUE),4) stat_cor = signif(cor(as.numeric(x$sky), as.numeric(x$skyRMS)^2, use="pairwise.complete.obs"),4) } legend('topleft',legend=c('Sky',paste0('Mean: ',stat_mean),paste0('SD: ',stat_sd)),bg='white') par(mar=c(3.5,3.5,0.5,0.5)) magimage(x$skyRMS) if(!is.null(x$mask)){ magimage(x$mask!=0, col=c(NA,hsv(alpha=0.2)), add=TRUE, magmap=FALSE, zlim=c(0,1)) stat_mean = signif(mean(x$skyRMS[x$mask==0], na.rm=TRUE),4) stat_sd = signif(sd(x$skyRMS[x$mask==0], na.rm=TRUE),4) }else{ stat_mean = signif(mean(x$skyRMS, na.rm=TRUE),4) stat_sd = signif(sd(x$skyRMS, na.rm=TRUE),4) } legend('topleft',legend=c('Sky RMS',paste0('Mean: ',stat_mean),paste0('SD: ',stat_sd)),bg='white') if(hist=='iters'){ maghist(x$segstats$iter, breaks=seq(-0.5,max(x$segstats$iter, na.rm=TRUE)+0.5,by=1), majorn=max(x$segstats$iter, na.rm=TRUE)+1, xlab='Number of Dilations', ylab=' }else if(hist=='sky'){ try({ if(!is.null(x$objects_redo)){ tempsky=image[x$objects_redo==0] }else{ tempsky=image[x$objects==0] } tempsky=tempsky[tempsky > -8 & tempsky < 8 & !is.na(tempsky)] stat_LL = signif(x$skyLL,4) magplot(density(tempsky[is.finite(tempsky)], bw=0.1), grid=TRUE, xlim=c(-6,6), xlab='(image - sky) / skyRMS', ylab='PDF', log='y', ylim=c(1e-8,0.5)) curve(dnorm(x, mean=0, sd=1), add=TRUE, col='red', lty=2) legend('topleft',legend=c('Sky Pixels',paste0('Cor: ',stat_cor), paste0('sky LL: ',stat_LL)), bg='white') }) }else{stop('Not a recognised hist type! Must be iters / sky.')} par(mar=c(3.5,3.5,0.5,0.5)) if(logR50){ magplot(x$segstats$mag, x$segstats$R50, pch='.', col=hsv(alpha=0.5), ylim=c(min(x$segstats$R50, 0.1, na.rm = TRUE), max(x$segstats$R50, 1, na.rm = TRUE)), cex=3, xlab='mag', ylab='R50 / asec', grid=TRUE, log='y') }else{ magplot(x$segstats$mag, x$segstats$R50, pch='.', col=hsv(alpha=0.5), ylim=c(0, max(x$segstats$R50, 1, na.rm = TRUE)), cex=3, xlab='mag', ylab='R50 / asec', grid=TRUE) } par(mar=c(3.5,3.5,0.5,0.5)) fluxrat=x$segstats$flux/x$segstats$flux_err magplot(x$segstats$SB_N90, fluxrat, pch='.', col=hsv(alpha=0.5), ylim=c(0.5,max(fluxrat, 1, na.rm=TRUE)), cex=3, xlab='SB90 / mag/pix-sq', ylab='Flux/Flux-Error', grid=TRUE, log='y') } } .selectCoG=function(diffmat, threshold=1.05){ IDmat=matrix(rep(1:dim(diffmat)[2],each=dim(diffmat)[1]),nrow=dim(diffmat)[1]) logmat=diffmat>1 & diffmat<threshold IDfin=IDmat IDfin[logmat==FALSE]=NA NegFlux=which(diffmat<threshold^0.2,arr.ind=TRUE) if(length(NegFlux)>0){ NegFlux[,2]=NegFlux[,2]-1 IDfin[NegFlux]=IDmat[NegFlux] IDfin[NegFlux[NegFlux[,2]==0,1],1]=0 } tempout=suppressWarnings(apply(IDfin,1,min,na.rm=TRUE)) tempout[is.infinite(tempout)]=dim(diffmat)[2] tempout+1 }
context("sim_generate") test_that("sim_generate for smstp_fe", code={ test_out <- sim_base(base_id(nDomains = 2, nUnits = c(3, 5))) %>% sim_gen_x() %>% as.data.frame expect_is(test_out, "data.frame") expect_equal(length(test_out), 3) expect_equal(nrow(test_out), 8) expect_equal(max(test_out$idU), 5) expect_equal(max(test_out$idD), 2) }) test_that("sim_gen", code={ setup1 <- sim_base() %>% sim_gen(gen_norm(0, 4, name = "x")) %>% sim_gen(gen_norm(0, 4, "e")) %>% sim_gen_cont(gen_norm(0, 150, "e"), nCont = 0.05, type = "unit", areaVar = "idD", fixed = TRUE) setup2 <- sim_base() %>% sim_gen_x() %>% sim_gen_e() %>% sim_gen_ec() set.seed(1) result1 <- sim(setup1, R = 1) set.seed(1) result2 <- sim(setup2, R = 1) expect_equal(result2, result1) }) test_that("gen_generic", { set.seed(1) dat1 <- gen_generic(runif, groupVars = "idD", name = "x")(base_id(5, 2)) set.seed(1) dat2 <- gen_generic(runif, name = "x")(base_id(5, 2)) expect_is(dat1, "data.frame") expect_equal(nrow(dat1), 10) expect_equal(dat1[1, "x"], dat1[2, "x"]) expect_equal(unique(dat2["x"]), dat2["x"]) expect_error(gen_generic(runif, level = "")(5, 2, "x")) set.seed(1) dat1 <- sim(sim_base() %>% sim_gen(gen_generic(rnorm, mean = 0, sd = 4, name="e")) %>% sim_gen(gen_generic(rnorm, mean = 0, sd = 1, groupVars = "idD", name="v"))) set.seed(1) dat2 <- sim(sim_base() %>% sim_gen_e() %>% sim_gen_v()) expect_equal(dat1, dat2) }) test_that("sim_gen_generic", { set.seed(1) dat1 <- base_id(5, 5) %>% sim_gen_generic(rnorm, mean = 0, sd = 4, name="e") %>% sim_gen_generic(rnorm, mean = 0, sd = 1, groupVars = "idD", name="v") %>% as.data.frame set.seed(1) dat2 <- base_id(5, 5) %>% sim_gen_e() %>% sim_gen_v() %>% as.data.frame expect_equal(dat1, dat2) }) test_that("gen_v_ar1", { set.seed(1) dat <- base_id_temporal(3, 1, 3) %>% sim_gen(gen_v_ar1( 1.2, sd = 5, rho = 0.6, groupVar = "idD", timeVar = "idT", name = "v")) %>% as.data.frame testthat::expect_equal(length(unique(dat$v)), 9) dat <- base_id_temporal(3, 1:3, 3) %>% sim_gen(gen_v_ar1( 1.2, sd = 5, rho = 0.6, groupVar = "idD", timeVar = "idT", name = "v")) %>% as.data.frame testthat::expect_equal(length(unique(dat$v)), 9) dat <- base_id_temporal(3, 1:3, 3) %>% sim_gen(gen_v_ar1( 1.2, sd = 5, rho = 0.6, groupVar = c("idD", "idU"), timeVar = "idT", name = "v")) %>% as.data.frame testthat::expect_equal(length(unique(dat$v)), 18) })
GLMSmoothIndex<- function(R = NULL, ...) { columns = 1 columnnames = NULL if(!is.null(R)){ x = checkData(R) columns = ncol(x) n = nrow(x) count = q columns = ncol(x) columnnames = colnames(x) for(column in 1:columns) { y = checkData(x[,column], method="vector", na.rm = TRUE) sum = sum(abs(acf(y,plot=FALSE,lag.max=6)[[1]][2:7])); acflag6 = acf(y,plot=FALSE,lag.max=6)[[1]][2:7]/sum; values = sum(acflag6*acflag6) if(column == 1) { result.df = data.frame(Value = values) colnames(result.df) = columnnames[column] } else { nextcol = data.frame(Value = values) colnames(nextcol) = columnnames[column] result.df = cbind(result.df, nextcol) } } rownames(result.df)= paste("GLM Smooth Index") return(result.df) } edhec=NULL }
aa.VLF.count.pos <- function(freq, p, seqlength){ count <- mat.or.vec(nr = 1, nc = seqlength) for(i in 1:seqlength){ count[i] <- length(which(freq[,i] < p)) } return(count) }
biblioNetwork <- function(M, analysis = "coupling", network = "authors", n = NULL, sep = ";", short = FALSE, shortlabel = TRUE) { crossprod <- Matrix::crossprod NetMatrix <- NA if (analysis == "coupling") { switch( network, authors = { WA <- cocMatrix(M, Field = "AU", type = "sparse", n,sep,short=short) WCR <- cocMatrix(M, Field = "CR", type = "sparse", n,sep,short=short) CRA <- crossprod(WCR, WA) NetMatrix <- crossprod(CRA, CRA) }, references = { WCR <- Matrix::t(cocMatrix(M, Field = "CR", type = "sparse", n,sep,short=short)) NetMatrix <- crossprod(WCR, WCR) }, sources = { WSO <- cocMatrix(M, Field = "SO", type = "sparse", n, sep,short=short) WCR <- cocMatrix(M, Field = "CR", type = "sparse", n, sep,short=short) CRSO <- crossprod(WCR, WSO) NetMatrix <- crossprod(CRSO, CRSO) }, countries = { WCO <- cocMatrix(M, Field = "AU_CO", type = "sparse", n, sep,short=short) WCR <- cocMatrix(M, Field = "CR", type = "sparse", n, sep,short=short) CRCO <- crossprod(WCR, WCO) NetMatrix <- crossprod(CRCO, CRCO) } ) } if (analysis == "co-occurrences") { switch( network, authors = { WA <- cocMatrix(M, Field = "AU", type = "sparse", n, sep,short=short) }, keywords = { WA <- cocMatrix(M, Field = "ID", type = "sparse", n, sep,short=short) }, author_keywords = { WA <- cocMatrix(M, Field = "DE", type = "sparse", n, sep,short=short) }, titles = { WA <- cocMatrix(M, Field = "TI_TM", type = "sparse", n, sep,short=short) }, abstracts = { WA <- cocMatrix(M, Field = "AB_TM", type = "sparse", n, sep,short=short) }, sources = { WA <- cocMatrix(M, Field = "SO", type = "sparse", n, sep,short=short) } ) NetMatrix <- crossprod(WA, WA) } if (analysis == "co-citation") { switch( network, authors = { WA <- cocMatrix(M, Field = "CR_AU", type = "sparse", n, sep,short=short) }, references = { WA <- cocMatrix(M, Field = "CR", type = "sparse", n, sep,short=short) }, sources = { WA <- cocMatrix(M, Field = "CR_SO", type = "sparse", n, sep,short=short) } ) NetMatrix <- crossprod(WA, WA) } if (analysis == "collaboration") { switch( network, authors = { WA <- cocMatrix(M, Field = "AU", type = "sparse", n, sep,short=short) }, universities = { WA <- cocMatrix(M, Field = "AU_UN", type = "sparse", n, sep,short=short) }, countries = { WA <- cocMatrix(M, Field = "AU_CO", type = "sparse", n, sep,short=short) } ) NetMatrix <- crossprod(WA, WA) } NetMatrix <- NetMatrix[nchar(colnames(NetMatrix)) != 0, nchar(colnames(NetMatrix)) != 0] if (network == "references") { ind <- which(regexpr("[A-Za-z]", substr(colnames(NetMatrix), 1, 1)) == 1) NetMatrix <- NetMatrix[ind, ind] if (isTRUE(shortlabel)) { LABEL <- labelShort(NetMatrix, db = tolower(M$DB[1])) LABEL <- removeDuplicatedlabels(LABEL) colnames(NetMatrix) <- rownames(NetMatrix) <- LABEL } } return(NetMatrix) } labelShort <- function(NET,db="isi"){ LABEL <- colnames(NET) YEAR <- suppressWarnings(as.numeric(sub('.*(\\d{4}).*', '\\1', LABEL))) YEAR[is.na(YEAR)] <- "" switch(db, isi={ AU <- strsplit(LABEL," ") AU <- unlist(lapply(AU, function(l){paste(l[1]," ",l[2],sep="")})) LABEL <- paste0(AU, " ", YEAR, sep="") }, scopus={ AU <- strsplit(LABEL,"\\. ") AU <- unlist(lapply(AU, function(l){l[1]})) LABEL <- paste0(AU, ". ", YEAR, sep="") }) return(LABEL) } removeDuplicatedlabels <- function(LABEL){ tab <- sort(table(LABEL),decreasing=T) dup <- names(tab[tab>1]) for (i in 1:length(dup)){ ind <- which(LABEL %in% dup[i]) if (length(ind)>0){ LABEL[ind] <- paste0(LABEL[ind],"-",as.character(1:length(ind)),sep="") } } return(LABEL) }
"auto.noise" "feedlot" "fiber" "MOats" "neuralgia" "nutrition" "oranges" "pigs" "ubds"
lvTransformer.default<-function(delta, mat, lib.size=NULL) { if(is.null(lib.size)) { lib.size=colSums(mat) } tt <- t(mat + 0.5)/(lib.size + 1) * 1e+06 mat2 <- t(log2(tt+1/delta)) vec = c(mat2) res=(mean(vec, na.rm=TRUE)-median(vec, na.rm=TRUE))^2 return(res) } lvTransformer=function(mat, lib.size=NULL, low=0.001, upp=1000) { res.delta=optimize(lvTransformer.default, mat=mat, lib.size=lib.size, lower=low, upper=upp) delta = res.delta$minimum if(is.null(lib.size)) { lib.size=colSums(mat) } tt <- t(mat + 0.5)/(lib.size + 1) * 1e+06 mat2 <- t(log2(tt+1/delta)) res=list(res.delta=res.delta, delta=delta, mat2=mat2) invisible(res) }
ran.genf <- function(data, n, ran.args) { if (length(ran.args$ar)==0) { x <- as.numeric(arima.sim(model=list(ma=ran.args$ma), n=n, innov=rnorm(n, ran.args$intercept, sqrt(ran.args$var)))) } if (length(ran.args$ma)==0) { x <- as.numeric(arima.sim(model=list(ar=ran.args$ar), n=n, innov=rnorm(n, ran.args$intercept, sqrt(ran.args$var)))) } if (length(ran.args$ar)!=0 & length(ran.args$ma)!=0) { x <- as.numeric(arima.sim(model=list(ar=ran.args$ar, ma=ran.args$ma), n=n, innov=rnorm(n, ran.args$intercept, sqrt(ran.args$var)))) } y <- ifelse(ran.args$z==0, x, x*ran.args$q) return(y) }
estimate_pls_mga <- function(pls_model, condition, nboot = 2000, ...) { pls_data <- pls_model$rawdata path_estimate <- function(path, path_coef) { path_coef[path["source"], path["target"]] } boot_paths <- function(path_coef, beta_df) { betas <- apply(beta_df, MARGIN=1, FUN=path_estimate, path_coef = path_coef) } group1_data <- pls_data[condition, ] group2_data <- pls_data[!condition, ] message("Estimating and bootstrapping groups...") group1_model <- rerun(pls_model, data = group1_data) group2_model <- rerun(pls_model, data = group2_data) group1_boot <- bootstrap_model(seminr_model = group1_model, nboot = nboot, ...) group2_boot <- bootstrap_model(seminr_model = group2_model, nboot = nboot, ...) message("Computing similarity of groups") beta <- as.data.frame(pls_model$smMatrix[,c("source", "target")]) path_names <- do.call(paste0, cbind(beta["source"], " -> ", beta["target"])) rownames(beta) <- path_names beta$estimate <- apply(beta, MARGIN = 1, FUN=path_estimate, path_coef = pls_model$path_coef) beta$group1_beta <- apply(beta, MARGIN = 1, FUN=path_estimate, path_coef = group1_model$path_coef) beta$group2_beta <- apply(beta, MARGIN = 1, FUN=path_estimate, path_coef = group2_model$path_coef) beta_diff <- group1_model$path_coef - group2_model$path_coef beta$diff <- apply(beta, MARGIN = 1, FUN=path_estimate, path_coef = beta_diff) boot1_betas <- t(apply(group1_boot$boot_paths, MARGIN=3, FUN=boot_paths, beta_df=beta)) colnames(boot1_betas) <- path_names boot2_betas <- t(apply(group2_boot$boot_paths, MARGIN=3, FUN=boot_paths, beta_df=beta)) colnames(boot2_betas) <- path_names J <- min(dim(boot1_betas)[1], dim(boot2_betas)[1]) if (J < nboot) { message(paste("NOTE: Using", J, "bootstrapped results of each group after removing inadmissible runs")) } boot1_betas <- boot1_betas[1:J,] boot2_betas <- boot2_betas[1:J,] beta$group1_beta_mean <- apply(boot1_betas, MARGIN=2, FUN=mean) beta$group2_beta_mean <- apply(boot2_betas, MARGIN=2, FUN=mean) Theta <- function(s) { ifelse(s > 0, 1, 0) } beta_comparison <- function(i, beta, beta1_boots, beta2_boots) { for_all <- expand.grid(beta1_boots[,i], beta2_boots[,i]) 2*beta$group1_beta_mean[i] - for_all[,1] - 2*beta$group2_beta_mean[i] + for_all[,2] } pls_mga_p <- function(i, beta, beta1_boots, beta2_boots) { 1 - (sum(Theta(beta_comparison(i, beta, beta1_boots, beta2_boots))) / J^2) } beta$pls_mga_p <- sapply(1:nrow(beta), FUN=pls_mga_p, beta=beta, beta1_boots=boot1_betas, beta2_boots=boot2_betas) class(beta) <- c("seminr_pls_mga", class(beta)) beta }
cacoord <- function(obj, type = c("standard", "principal", "symmetric", "rowprincipal", "colprincipal", "symbiplot", "rowgab", "colgab", "rowgreen", "colgreen"), dim = NA, rows = NA, cols = NA, ...){ if (!inherits(obj, c("ca", "mjca"))){ stop("'obj' must be a 'ca' or 'mjca' object") } map <- match.arg(type) if (is.na(rows) & is.na(cols)){ rows <- TRUE cols <- TRUE } else{ if (is.na(rows) | !rows){ rows <- FALSE cols <- TRUE obj$rowcoord <- matrix(rep(0, ncol(obj$colcoord)), nrow = 1) obj$rowmass <- 1 } if (is.na(cols) | !cols){ cols <- FALSE rows <- TRUE obj$colcoord <- matrix(rep(0, ncol(obj$rowcoord)), nrow = 1) obj$colmass <- 1 } } if (is.null(rownames(obj$rowcoord))){ x.rnames <- 1:nrow(obj$rowcoord) rownames(obj$rowcoord) <- x.rnames } else { x.rnames <- rownames(obj$rowcoord) } if (is.null(colnames(obj$rowcoord))){ x.cnames <- paste("Dim", 1:ncol(obj$rowcoord), sep = "") colnames(obj$rowcoord) <- x.cnames } else { x.cnames <- colnames(obj$rowcoord) } if (is.null(rownames(obj$colcoord))){ y.rnames <- 1:nrow(obj$colcoord) rownames(obj$colcoord) <- y.rnames } else { y.rnames <- rownames(obj$colcoord) } if (is.null(colnames(obj$colcoord))){ y.cnames <- paste("Dim", 1:ncol(obj$colcoord), sep = "") colnames(obj$colcoord) <- y.cnames } else { y.cnames <- colnames(obj$colcoord) } if (is.na(dim)[1]){ sv <- obj$sv rsc <- obj$rowcoord csc <- obj$colcoord } else { sv <- obj$sv[dim] rsc <- matrix(obj$rowcoord[,dim], ncol = length(dim)) csc <- matrix(obj$colcoord[,dim], ncol = length(dim)) rownames(rsc) <- x.rnames colnames(rsc) <- x.cnames[dim] rownames(csc) <- y.rnames colnames(csc) <- y.cnames[dim] } if (map == "standard"){ x <- rsc y <- csc } else { I <- nrow(rsc) J <- nrow(csc) K <- ncol(rsc) rpc <- rsc %*% diag(sv) cpc <- csc %*% diag(sv) if (map == "principal"){ x <- rpc y <- cpc } else { symrpc <- rsc %*% diag(sqrt(sv)) symcpc <- csc %*% diag(sqrt(sv)) rgab <- rsc * matrix(obj$rowmass, ncol = ncol(rsc), nrow = nrow(rsc)) cgab <- csc * matrix(obj$colmass, ncol = ncol(csc), nrow = nrow(csc)) rgreen <- rsc * matrix(sqrt(obj$rowmass), ncol = ncol(rsc), nrow = nrow(rsc)) cgreen <- csc * matrix(sqrt(obj$colmass), ncol = ncol(csc), nrow = nrow(csc)) mt <- c("symmetric", "rowprincipal", "colprincipal", "symbiplot", "rowgab", "colgab", "rowgreen", "colgreen") mti <- 1:length(mt) mtlut <- list(symmetric = list(x = rpc, y = cpc), rowprincipal = list(x = rpc, y = csc), colprincipal = list(x = rsc, y = cpc), symbiplot = list(x = symrpc, y = symcpc), rowgab = list(x = rpc, y = cgab), colgab = list(x = rgab, y = cpc), rowgreen = list(x = rpc, y = cgreen), rowgreen = list(x = rgreen, y = cpc) ) x <- mtlut[[mti[mt == map]]][[1]] y <- mtlut[[mti[mt == map]]][[2]] } } rownames(x) <- rownames(rsc) colnames(x) <- colnames(rsc) rownames(y) <- rownames(csc) colnames(y) <- colnames(csc) if (rows & cols){ out <- list(rows = x, columns = y) } else { if (rows){ out <- x } else { out <- y } } return(out) }
NULL mortalityTable.observed = setClass( "mortalityTable.observed", slots = list( deathProbs = "data.frame", years = "numeric", ages = "numeric" ), prototype = list( deathProbs = data.frame(), years = c(), ages = c() ), contains = "mortalityTable" ) setMethod("ages", "mortalityTable.observed", function(object, ...) { object@ages; }) setMethod("getOmega", "mortalityTable.observed", function(object) { max(object@ages, na.rm = TRUE); }) setMethod("mT.round", "mortalityTable.observed", function(object, digits = 8) { o = callNextMethod() o@data = round(o@data, digits = digits) o }) findIntRuns <- function(run) { rundiff <- c(1, diff(run)) difflist <- split(run, cumsum(rundiff != 1)) runs = unlist(lapply(difflist, function(x) { if (length(x) %in% 1:2) as.character(x) else paste0(x[1], "-", x[length(x)]) }), use.names = FALSE) paste0(runs, collapse = ",") } setMethod("periodDeathProbabilities", "mortalityTable.observed", function(object, ..., ages = NULL, Period = 1975) { if (is.null(ages)) { ages = ages(object) } col = which.min(abs(object@years - Period)) if (object@years[col] != Period) { warning("periodDeathProbabilities: Desired Period ", Period, " of observed mortalityTable not available, using closest period ", object@years[[col]], ".\nAvailable periods: ", findIntRuns(object@years)) } fillAges( object@modification(object@deathProbs[,col] * (1 + object@loading)), givenAges = ages(object), neededAges = ages) }) setMethod("deathProbabilities","mortalityTable.observed", function(object, ..., ages = NULL, YOB = 1975) { if (is.null(ages)) { ages = ages(object); } years = YOB + ages; yearcols = sapply(years, function(y) which.min(abs(object@years - y))) agerows = match(ages, object@ages) if (sum(abs(object@years[yearcols] - years)) > 0) { warning("deathProbabilities: Not all observation years ", findIntRuns(years), " of observed mortalityTable are available, using closest observations.\nAvailable periods: ", findIntRuns(object@years)) } qx = object@deathProbs[cbind(agerows, yearcols)] * (1 + object@loading); fillAges(object@modification(qx), givenAges = ages(object), neededAges = ages) }) setMethod("mT.cleanup", "mortalityTable.observed", function(object) { o = callNextMethod() o@ages = unname(o@ages) o@deathProbs = unname(o@deathProbs) o@years = unname(o@years) o })
test_not_seen_level <- function() { d <- wrapr::build_frame( "ID" , "OP", "DATE" , "rank" | 1 , "A" , "2001-01-02 00:00:00", 1 | 1 , "B" , "2015-04-25 00:00:00", 2 | 2 , "A" , "2000-04-01 00:00:00", 1 | 3 , "C" , "2014-04-07 00:00:00", 1 | 4 , "A" , "2005-06-16 00:00:00", 1 | 4 , "D" , "2009-01-20 00:00:00", 2 | 4 , "C" , "2012-12-01 00:00:00", 3 | 5 , "B" , "2003-11-09 00:00:00", 1 | 5 , "A" , "2010-10-10 00:00:00", 2 | 6 , "B" , "2004-01-09 00:00:00", 1 ) diagram <- wrapr::build_frame( "rank", "DATE", "OP" | "1", "DATE1", "OP1" | "2", "DATE2", "OP2" | "3", "DATE3", "OP3" | "4", "DATE4", "OP4" | "5", "DATE5", "OP5" ) res <- blocks_to_rowrecs(d, keyColumns = "ID", controlTable = diagram) expect <- wrapr::build_frame( "ID" , "DATE1" , "OP1", "DATE2" , "OP2" , "DATE3" , "OP3" , "DATE4" , "OP4" , "DATE5" , "OP5" | 1 , "2001-01-02 00:00:00", "A" , "2015-04-25 00:00:00", "B" , NA_character_ , NA_character_, NA_character_, NA_character_, NA_character_, NA_character_ | 2 , "2000-04-01 00:00:00", "A" , NA_character_ , NA_character_, NA_character_ , NA_character_, NA_character_, NA_character_, NA_character_, NA_character_ | 3 , "2014-04-07 00:00:00", "C" , NA_character_ , NA_character_, NA_character_ , NA_character_, NA_character_, NA_character_, NA_character_, NA_character_ | 4 , "2005-06-16 00:00:00", "A" , "2009-01-20 00:00:00", "D" , "2012-12-01 00:00:00", "C" , NA_character_, NA_character_, NA_character_, NA_character_ | 5 , "2003-11-09 00:00:00", "B" , "2010-10-10 00:00:00", "A" , NA_character_ , NA_character_, NA_character_, NA_character_, NA_character_, NA_character_ | 6 , "2004-01-09 00:00:00", "B" , NA_character_ , NA_character_, NA_character_ , NA_character_, NA_character_, NA_character_, NA_character_, NA_character_ ) expect_true(wrapr::check_equiv_frames(res, expect)) invisible(NULL) } test_not_seen_level()
format.default <- function(x, ...){ res <- get("format.default", pos = "package:base")(x, ...) attributes(res) <- attributes(x) res }
context ("avisContributorsSummary") test_that("avisContributorsSummary returns expected header",{ response <- avisContributorsSummary() expectedNames <- c("UserId", "Observations","Species","Provinces","UTMs","Periods") expect_equal (colnames (response), expectedNames) })
NULL setClass( Class = "Weight", representation=representation( descr = "character" ) ) setMethod(f = "getDescr", signature = "Weight", definition = function(object) { return(object@descr) } )
sparsePC <- function(...) { sparsePC.spikeslab(...) } sparsePC.spikeslab <- function(x=NULL, y=NULL, n.rep=10, n.iter1=150, n.iter2=100, n.prcmp=5, max.genes=100, ntree=1000, nodesize=1, verbose=TRUE, ... ) { permute.rows <-function(x) { dd <- dim(x) n <- dd[1] p <- dd[2] mm <- runif(length(x)) + rep(seq(n) * 10, rep(p, n)) matrix(t(x)[order(mm)], n, p, byrow = TRUE) } balanced.folds <- function(y, nfolds = min(min(table(y)), 10)) { totals <- table(y) fmax <- max(totals) nfolds <- min(nfolds, fmax) nfolds= max(nfolds, 2) folds <- as.list(seq(nfolds)) yids <- split(seq(y), y) bigmat <- matrix(NA, ceiling(fmax/nfolds) * nfolds, length(totals)) for(i in seq(totals)) { if(length(yids[[i]])>1){bigmat[seq(totals[i]), i] <- sample(yids[[i]])} if(length(yids[[i]])==1){bigmat[seq(totals[i]), i] <- yids[[i]]} } smallmat <- matrix(bigmat, nrow = nfolds) smallmat <- permute.rows(t(smallmat)) res <-vector("list", nfolds) for(j in 1:nfolds) { jj <- !is.na(smallmat[, j]) res[[j]] <- smallmat[jj, j] } return(res) } class.error <- function(y, ytest, pred) { cl <- sort(unique(y)) err <- rep(NA, length(cl)) for (k in 1:length(cl)) { cl.pt <- (ytest == cl[k]) if (sum(cl.pt) > 0) { err[k] <- mean(ytest[cl.pt] != pred[cl.pt]) } } err } get.pc <- function(X, Y, n.prcmp) { cat("Getting prcmp...\n") nclass <- length(unique(Y)) n <- nrow(X) p <- ncol(X) o.r <- order(Y) Y <- Y[o.r] Y.freq <- tapply(Y, Y, length) X <- X[o.r, ] X.mean <- as.double(c(apply(X, 2, mean.center, center = TRUE))) X.sd <- as.double(c(apply(X, 2, sd.center, center = TRUE))) ss.X <- scale(X, center = X.mean, scale = X.sd) pc.out <- svd(ss.X) U <- pc.out$u D <- pc.out$d UD <- t(t(U)*D) imp <- apply(UD, 2, function(p){ rf.out <- randomForest(cbind(Y), p, importance = TRUE) rf.out$importance[1,1]}) o.r <- order(imp, decreasing = TRUE) tot.var <- cumsum(D[o.r]/sum(D)) cat("total variation for top prcmp(s):", round(100 * tot.var[n.prcmp]), "%", "\n") Y.prcmp <- as.matrix(UD[, o.r[1:n.prcmp]]) Y.prcmp <- as.matrix(apply(Y.prcmp, 2, function(p) { p.mean <- rep(tapply(p, Y, mean), Y.freq) p.sd <- rep(tapply(p, Y, sd), Y.freq) rnorm(n, p.mean, 0.1 * p.sd) } )) colnames(ss.X) <- paste("X.", 1:p, sep="") return(list(Y.prcmp=Y.prcmp, ss.X=ss.X, tot.var=tot.var)) } gene.signature <- NULL X <- as.matrix(x) Y <- y if (!is.factor(y)) Y <- factor(y) n.genes <- ncol(X) n.data <- nrow(X) if (any(is.na(Y))) stop("Missing values not allowed in y") if (n.data != length(Y)) stop("number of rows of x should match length of y") n.class <- length(unique(Y)) dim.results <- pred.results <- rep(0, n.rep) pred.class.results <- matrix(NA, n.rep, n.class) X <- scale(X, center = TRUE, scale = TRUE) for (k in 1:n.rep) { if (verbose) cat("\n ---> Monte Carlo Replication:", k, "\n") if (n.rep > 1) { cv.sample <- balanced.folds(Y, 3) train.pt <- c(cv.sample[[1]], cv.sample[[2]]) test.pt <- cv.sample[[3]] } else { train.pt <- test.pt <- 1:n.data } n.prcmp <- min(n.prcmp, length(train.pt)) pc.out <- get.pc(X[train.pt, ], Y[train.pt], n.prcmp = n.prcmp) sig.genes <- NULL signal <- rep(0, n.genes) for (p in 1:n.prcmp) { if (verbose) cat("fitting principal component:", p, "(", round(100*pc.out$tot.var[p]), "%)", "\n") ss.out <- spikeslab(x = pc.out$ss.X, y = pc.out$Y.prcmp[, p], n.iter1 = n.iter1, n.iter2 = n.iter2, max.var = max.genes, bigp.smalln.factor = max(1, round(max.genes/nrow(pc.out$ss.X))), bigp.smalln = (nrow(pc.out$ss.X) < ncol(pc.out$ss.X))) sig.genes.p <- as.double(which(abs(ss.out$gnet) > .Machine$double.eps)) if (length(sig.genes.p) > 0) { sig.genes <- c(sig.genes, sig.genes.p) signal[sig.genes.p] <- signal[sig.genes.p] + abs(ss.out$gnet)[sig.genes.p] } } if (length(sig.genes) == 0) { sig.genes <- as.double(which(signal == max(signal, na.rm = TRUE)))[1] } sig.genes <- sort(unique(sig.genes)) P <- min(max.genes, length(sig.genes)) o.r <- order(signal[sig.genes], decreasing = TRUE) sig.genes.k <- sig.genes[o.r][1:P] rf.data.x <- as.matrix(X[, sig.genes.k]) colnames(rf.data.x) <- paste("x.", 1:length(sig.genes.k)) Y.train <- Y[train.pt] Y.test <- Y[test.pt] rf.out <- randomForest(x=as.matrix(rf.data.x[train.pt, ]), y=Y.train, importance = TRUE, ntree=ntree, nodesize=nodesize) gene.signature <- c(gene.signature, sig.genes.k) dim.results[k] <- length(sig.genes.k) if (n.rep > 1) { rf.pred <- predict(rf.out, newdata = as.matrix(rf.data.x[test.pt, ])) pred.results[k] <- mean(as.character(Y.test) != rf.pred) pred.class.results[k, ] <- class.error(as.character(Y), as.character(Y.test), rf.pred) } if (verbose & (n.rep > 1)) { cat("\n", "PE:", round(pred.results[k], 3), "dimension:", dim.results[k], "\n") } } gene.signature.all <- gene.signature gene.signature.freq <- tapply(gene.signature, gene.signature, length) gene.signature <- as.double(names(gene.signature.freq)[rev(order(gene.signature.freq))][1:mean(dim.results)]) if (verbose) cat("growing the forest classifier...\n") rf.data.x <- as.matrix(X[, gene.signature]) colnames(rf.data.x) <- paste("x.", gene.signature) rf.out <- randomForest(x=rf.data.x, y=Y, importance = TRUE, ntree=ntree, nodesize=nodesize) cat("\n\n") cat("-----------------------------------------------------------\n") cat("no. prcmps :", n.prcmp, "\n") cat("no. genes :", n.genes, "\n") cat("max genes :", max.genes, "\n") cat("no. samples :", nrow(X), "\n") cat("no. classes :", n.class, "\n") cat("class freq :", as.double(tapply(Y, Y, length)), "\n") cat("class names :", levels(Y), "\n") cat("replicates :", n.rep, "\n") cat("model size :", round(mean(dim.results), 4), "+/-", round(sd(dim.results), 4), "\n") if (n.rep > 1) { cat("misclass :", round(mean(100*pred.results), 4), "+/-", round(sd(100*pred.results), 4), "\n") for (j in 1:n.class) { cat(paste(" class } } cat("\n") cat("Gene Signature:\n") print(gene.signature) cat("-----------------------------------------------------------\n") invisible(list(gene.signature=gene.signature, gene.signature.all=gene.signature.all, rf.object=rf.out)) }
context("ebirdregion") test_that("ebirdregion works correctly", { skip_on_cran() out <- ebirdregion(loc = 'US', species = 'btbwar', max = 50) expect_is(out, "data.frame") expect_equal(ncol(out), 13) expect_is(out$comName, "character") expect_is(out$howMany, "integer") expect_equal(dim(ebirdregion('US-OH', max=10, provisional=TRUE, hotspot=TRUE)), c(10,13)) res <- ebirdregion(loc = 'US-CA', max = 10) expect_equal(ncol(res), 13) expect_equal(ncol(ebirdregion(loc = 'US', species = 'coohaw')), 13) expect_gte(ncol(ebirdregion(loc = 'L109339', species = 'amecro', simple = FALSE)), 26) })
fun.Rjudge <- function(A,B,symbol) { size <- length(A); Output <- matrix(1, nrow=size, ncol=1) for(i in 1:size){ if(symbol=='<'){ if(A[i] >= B){Output[i] <- 0} } else if(symbol=='>='){ if(A[i] < B){Output[i] <- 0} } } return(Output) }
`confint.cusp` <- function (object, parm, level = 0.95, ...) { cf <- coef(object) pnames <- names(cf) v <- vcov(object) pnames <- colnames(v) if (missing(parm)) parm <- seq_along(pnames) else if (is.character(parm)) parm <- match(parm, pnames, nomatch = 0) a <- (1 - level)/2 a <- c(a, 1 - a) pct <- format.perc(a, 3) fac <- qnorm(a) ci <- array(NA, dim = c(length(parm), 2), dimnames = list(pnames[parm], pct)) ses <- sqrt(diag(v))[parm] ci[] <- cf[pnames[parm]] + ses %o% fac ci }
assertthat::on_failure(is_valid_bdc) <- function (call, env) { paste0(deparse(call$bdc), " contains invalid business day convention.") } assertthat::on_failure(is_valid_day_basis) <- function(call, env) { paste0(deparse(call$bdc), " contains invalid business day convention.") } assertthat::on_failure(is_list_of) <- function(call, env) { paste0("All elements of ", deparse(call$object), " are not objects of class ", deparse(call$class), ".") }
.readComment <- function(fileName, commentChar = "*", metaChar = " comment <- NULL if (!is.null(commentChar)) { if (commentChar != "") { zz <- file(fileName) open(zz) readRepeat <- TRUE while (readRepeat) { tmp <- readLines(zz, 1) if (length(grep(paste("^", escapeRegex(commentChar), sep = ""), tmp)) & !grepl(metaChar, substr(tmp, 3, 3), fixed = TRUE)) { comment <- c(comment, tmp) } else { readRepeat <- FALSE } } close(zz) } } return(substring(comment, 2)) }
library(uwot) context("API output") set.seed(1337) res <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, min_dist = 0.001, init = "normlaplacian", verbose = FALSE, n_threads = 0 ) expect_ok_matrix(res) set.seed(1337) res2 <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, min_dist = 0.001, init = "normlaplacian", verbose = FALSE, n_threads = 0 ) expect_equal(res2, res) res <- umap(dist(iris10), n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, min_dist = 0.001, init = "laplacian", verbose = FALSE, n_threads = 0 ) expect_ok_matrix(res) res <- tumap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, metric = "cosine", init = "spectral", verbose = FALSE, n_threads = 0 ) expect_ok_matrix(res) res <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, metric = "cosine", init = "spectral", verbose = FALSE, n_threads = 1 ) expect_ok_matrix(res) res <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, metric = "manhattan", init = "rand", verbose = FALSE, n_threads = 0 ) expect_ok_matrix(res) res <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, metric = "manhattan", init = "spca", verbose = FALSE, n_threads = 1 ) expect_ok_matrix(res) iris10_pca <- prcomp(iris10, retx = TRUE, center = TRUE, scale. = FALSE )$x[, 1:2] res <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, min_dist = 0.001, init = iris10_pca, verbose = FALSE, n_threads = 0 ) expect_ok_matrix(res) expect_equal(iris10_pca, prcomp(iris10, retx = TRUE, center = TRUE, scale. = FALSE )$x[, 1:2]) set.seed(1337) res <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, min_dist = 0.001, init = "spca", verbose = FALSE, n_threads = 0, ret_nn = TRUE ) expect_is(res, "list") expect_ok_matrix(res$embedding) expect_is(res$nn, "list") expect_is(res$nn$euclidean, "list") expect_ok_matrix(res$nn$euclidean$idx, nc = 4) expect_ok_matrix(res$nn$euclidean$dist, nc = 4) set.seed(1337) res_nn <- umap(iris10, nn_method = res$nn[[1]], n_epochs = 2, learning_rate = 0.5, min_dist = 0.001, init = "spca", verbose = FALSE, n_threads = 0 ) expect_ok_matrix(res_nn) expect_equal(res_nn, res$embedding) set.seed(1337) res_nnxn <- umap( X = NULL, nn_method = nn, n_epochs = 2, learning_rate = 0.5, min_dist = 0.001, init = "rand", verbose = FALSE, n_threads = 0 ) set.seed(1337) res_nnl <- umap(iris10, nn_method = res$nn, n_epochs = 2, learning_rate = 0.5, min_dist = 0.001, init = "rand", verbose = FALSE, n_threads = 0, ret_nn = TRUE ) expect_ok_matrix(res_nnl$embedding) expect_equal(res_nnl$nn[[1]], res$nn[[1]]) expect_equal(names(res_nnl$nn), "precomputed") expect_equal(res_nnxn, res_nnl$embedding) res_nn2 <- umap(iris10, nn_method = list(nn, nn), n_epochs = 2, learning_rate = 0.5, min_dist = 0.001, init = "spca", verbose = FALSE, n_threads = 0, ret_nn = TRUE ) expect_ok_matrix(res_nn2$embedding) expect_equal(names(res_nn2$nn), c("precomputed", "precomputed")) res <- lvish(iris10, perplexity = 4, n_epochs = 2, learning_rate = 0.5, nn_method = "annoy", init = "lvrand", verbose = FALSE, n_threads = 1, ret_extra = c("sigma") ) expect_ok_matrix(res$embedding) expect_equal(res$sigma, c(0.3039, 0.2063, 0.09489, 0.08811, 0.3091, 0.6789, 0.1743, 0.1686, 0.3445, 0.1671), tol = 1e-4) res <- lvish(iris10, kernel = "knn", perplexity = 4, n_epochs = 2, learning_rate = 0.5, init = "lvrand", verbose = FALSE, n_threads = 1 ) expect_ok_matrix(res) res <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, min_dist = 0.001, init = "rand", verbose = FALSE, n_threads = 1, ret_model = TRUE ) expect_is(res, "list") expect_ok_matrix(res$embedding) res_test <- umap_transform(iris10, res, n_threads = 1, verbose = FALSE) expect_ok_matrix(res_test) res_test0 <- umap_transform(iris10, res, n_epochs = 0, n_threads = 1, verbose = FALSE) expect_ok_matrix(res_test) expect_equal(dim(res_test0), c(10, 2)) res <- tumap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, init = "rand", verbose = FALSE, n_threads = 1, ret_model = TRUE, ret_nn = TRUE ) expect_is(res, "list") expect_ok_matrix(res$embedding) expect_is(res$nn, "list") expect_is_nn(res$nn[[1]], k = 4) expect_equal(names(res$nn), "euclidean") res_test <- umap_transform(iris10, res, n_threads = 0, verbose = FALSE) expect_ok_matrix(res_test) res <- umap(iris10, n_components = 1, n_neighbors = 4, n_epochs = 2, n_threads = 1, verbose = FALSE ) expect_ok_matrix(res, nc = 1) res <- umap(iris10, n_components = 1, n_neighbors = 4, n_epochs = 2, n_threads = 1, verbose = FALSE, init = "irlba_spectral" ) expect_ok_matrix(res, nc = 1) set.seed(1337) res_y <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, min_dist = 0.001, init = "spca", verbose = FALSE, n_threads = 0, y = 1 / (1:10)^2, target_n_neighbors = 2 ) expect_ok_matrix(res_y) y_nn <- list( idx = matrix(c( 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 9 ), ncol = 2, byrow = TRUE), dist = matrix(c( 0, 0.750000000, 0, 0.138888896, 0, 0.048611112, 0, 0.022500001, 0, 0.012222221, 0, 0.007369615, 0, 0.004783163, 0, 0.003279321, 0, 0.002345679, 0, 0.002345679 ), ncol = 2, byrow = TRUE) ) set.seed(1337) res_ynn <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, min_dist = 0.001, init = "spca", verbose = FALSE, n_threads = 0, y = y_nn ) expect_ok_matrix(res_ynn) expect_equal(res_ynn, res_y) bin10 <- structure(c( 0L, 0L, 1L, 0L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 0L, 1L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 1L, 0L, 0L, 1L, 1L, 0L, 0L, 1L, 1L, 0L ), .Dim = c(10L, 4L)) res <- umap(bin10, n_neighbors = 4, metric = "hamming", verbose = FALSE, n_threads = 1 ) expect_ok_matrix(res) set.seed(1337) res <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, init = "spca", verbose = FALSE, n_threads = 0, metric = list(euclidean = c(1, 2), euclidean = c(3, 4)), ret_model = TRUE ) res_trans <- umap_transform(iris10, model = res, verbose = FALSE, n_threads = 0, n_epochs = 2 ) expect_ok_matrix(res_trans) res <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, init = "spca", verbose = FALSE, n_threads = 0, pca = 2, ret_model = TRUE ) expect_ok_matrix(res$embedding) expect_is(res$pca_models, "list") expect_equal(length(res$pca_models), 1) expect_ok_matrix(res$pca_models[["1"]]$rotation, nr = 4, nc = 2) expect_equal(res$pca_models[["1"]]$center, c(4.86, 3.31, 1.45, 0.22), check.attributes = FALSE ) res <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, init = "spca", verbose = FALSE, n_threads = 0, pca = 2, pca_center = FALSE, ret_model = TRUE ) expect_ok_matrix(res$embedding) expect_is(res$pca_models, "list") expect_equal(length(res$pca_models), 1) expect_ok_matrix(res$pca_models[["1"]]$rotation, nr = 4, nc = 2) expect_null(res$pca_models[["1"]]$center) res <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, metric = list("euclidean" = 1:2, "euclidean" = 3:4), init = "spca", verbose = FALSE, n_threads = 0, pca = 2 ) expect_ok_matrix(res) set.seed(1337) ib10 <- cbind(iris10, bin10, bin10) res <- umap(ib10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, init = "spca", verbose = FALSE, n_threads = 0, metric = list( euclidean = c(1, 2), hamming = 5:12, euclidean = c(3, 4) ), pca = 2, ret_model = TRUE ) expect_ok_matrix(res$embedding) expect_is(res$pca_models, "list") expect_equal(length(res$pca_models), 2) expect_equal(names(res$pca_models), c("1", "3")) expect_ok_matrix(res$pca_models[["1"]]$rotation, nr = 2, nc = 2) expect_equal(res$pca_models[["1"]]$center, c(4.86, 3.31), check.attributes = FALSE ) expect_ok_matrix(res$pca_models[["3"]]$rotation, nr = 2, nc = 2) expect_equal(res$pca_models[["3"]]$center, c(1.45, 0.22), check.attributes = FALSE ) res_trans <- umap_transform(ib10, model = res, verbose = FALSE, n_threads = 0, n_epochs = 2 ) expect_ok_matrix(res_trans) set.seed(1337) res <- umap(ib10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, init = "spca", verbose = FALSE, n_threads = 0, metric = list( euclidean = c(1, 2), hamming = 5:8, euclidean = list(c(3, 4), pca = NULL) ), pca = 2, ret_model = TRUE ) expect_ok_matrix(res$embedding) expect_is(res$pca_models, "list") expect_equal(length(res$pca_models), 1) expect_equal(names(res$pca_models), "1") expect_ok_matrix(res$pca_models[["1"]]$rotation, nr = 2, nc = 2) expect_equal(res$pca_models[["1"]]$center, c(4.86, 3.31), check.attributes = FALSE ) res_trans <- umap_transform(ib10, model = res, verbose = FALSE, n_threads = 0, n_epochs = 2 ) expect_ok_matrix(res_trans) set.seed(1337) res <- umap(bin10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, init = "spca", verbose = FALSE, n_threads = 0, metric = "manhattan", pca = 2, pca_center = FALSE, ret_model = TRUE ) expect_ok_matrix(res$embedding) expect_is(res$pca_models, "list") expect_equal(length(res$pca_models), 1) expect_equal(names(res$pca_models), "1") expect_ok_matrix(res$pca_models[["1"]]$rotation, nr = 4, nc = 2) expect_null(res$pca_models[["1"]]$center) res_trans <- umap_transform(bin10, model = res, verbose = FALSE, n_threads = 0, n_epochs = 2 ) expect_ok_matrix(res_trans) res <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, init = "pca", verbose = FALSE, n_threads = 0, init_sdev = 2 ) expect_ok_matrix(res) res <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, init = "laplacian", verbose = FALSE, n_threads = 0, init_sdev = 0.1 ) expect_ok_matrix(res) res <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, init = "spectral", verbose = FALSE, n_threads = 0, init_sdev = 5 ) expect_ok_matrix(res) res_sd <- apply(res, 2, sd) res2 <- umap(iris10, n_neighbors = 4, n_epochs = 0, learning_rate = 0.5, init = res, verbose = FALSE, n_threads = 0, init_sdev = 5 ) expect_ok_matrix(res2) expect_equal(apply(res2, 2, sd), rep(5, ncol(res2))) expect_equal(apply(res, 2, sd), res_sd) set.seed(1337) res <- umap(iris10[1:4, ], n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, min_dist = 0.001, init = "rand", verbose = FALSE, ret_model = TRUE ) expect_is(res, "list") expect_ok_matrix(res$embedding, nr = 4) res_test <- umap_transform(iris10[5:10, ], res, verbose = FALSE, n_epochs = 10) expect_ok_matrix(res_test, nr = 6) expect_equal(res$metric$euclidean$ndim, 4) res <- umap(iris10, pcg_rand = FALSE, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, init = "spectral", verbose = FALSE, n_threads = 0, init_sdev = 5 ) expect_ok_matrix(res) res <- umap(iris10, n_neighbors = 4, n_threads = 0.5) expect_ok_matrix(res) res <- umap(iris10, n_neighbors = 4, n_threads = 1.5) expect_ok_matrix(res) res <- umap(iris10, n_neighbors = 4, n_sgd_threads = 0.5) expect_ok_matrix(res) res <- umap(iris10, n_neighbors = 4, n_sgd_threads = 1.5) expect_ok_matrix(res) res <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, min_dist = 0.001, init = "spca", verbose = FALSE, n_threads = 0, ret_extra = c("fgraph") ) expect_is(res, "list") expect_ok_matrix(res$embedding) expect_is(res$fgraph, "Matrix") res <- tumap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, init = "spca", verbose = FALSE, n_threads = 0, ret_extra = c("fgraph") ) expect_is(res, "list") expect_ok_matrix(res$embedding) expect_is(res$fgraph, "Matrix") res <- lvish(iris10, perplexity = 4, n_epochs = 2, learning_rate = 0.5, init = "spca", verbose = FALSE, n_threads = 0, ret_extra = c("P") ) expect_is(res, "list") expect_ok_matrix(res$embedding) expect_is(res$P, "Matrix") set.seed(42) res_cor <- tumap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, metric = "correlation", init = "spectral", verbose = FALSE, n_threads = 0, ret_model = TRUE) expect_ok_matrix(res_cor$embedding) set.seed(42) res_cos <- tumap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, metric = "cosine", init = "spectral", verbose = FALSE, n_threads = 0, ret_model = TRUE) expect_gt(sum((res_cor$embedding - res_cos$embedding) ^ 2), 1e-3) set.seed(42) res_trans_cor <- umap_transform(x2m(iris[11:20, ]), res_cor, n_threads = 0, verbose = FALSE) expect_ok_matrix(res_trans_cor) res_cor$nn_index$metric <- "cosine" set.seed(42) res_trans_cor2 <- umap_transform(x2m(iris[11:20, ]), res_cor, n_threads = 0, verbose = FALSE) expect_ok_matrix(res_trans_cor2) expect_gt(sum((res_trans_cor - res_trans_cor2) ^ 2), 1e-3) set.seed(42) xnames <- data.frame(matrix(rnorm(10 * 4), nrow = 10), row.names = letters[1:10]) xumap <- umap( xnames, n_neighbors = 4, verbose = FALSE, n_threads = 0, ret_model = TRUE, ret_nn = TRUE ) expect_equal(row.names(xumap$embedding), row.names(xnames)) expect_equal(row.names(xumap$nn$euclidean$idx), row.names(xnames)) expect_equal(row.names(xumap$nn$euclidean$dist), row.names(xnames)) first_coords <- c() test_callback <- function(epochs, n_epochs, coords) { first_coords <<- c(first_coords, coords[1, 1]) } set.seed(42) ibatch <- tumap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, init = "spca", verbose = FALSE, batch = TRUE, n_threads = 0, n_sgd_threads = 0, ret_model = TRUE, epoch_callback = test_callback) expect_equal(length(first_coords), 2) set.seed(42) ibatch2 <- tumap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, init = "spca", verbose = FALSE, batch = TRUE, n_threads = 0, n_sgd_threads = 2, ret_model = TRUE) expect_equal(ibatch$embedding, ibatch2$embedding) itest <- x2m(iris[11:20, ]) first_coords <- c() fixed_first_coords <- c() test_transform_callback <- function(epochs, n_epochs, coords, fixed_coords) { first_coords <<- c(first_coords, coords[1, 1]) fixed_first_coords <<- c(fixed_first_coords, fixed_coords[1, 1]) } set.seed(42) ibatchtest <- umap_transform(itest, ibatch, epoch_callback = test_transform_callback, n_epochs = 5) expect_equal(length(first_coords), 5) expect_equal(length(fixed_first_coords), 5) expect_equal(length(unique(first_coords)), 4) expect_equal(length(unique(fixed_first_coords)), 1) set.seed(42) ibatchtest2 <- umap_transform(itest, ibatch, n_sgd_threads = 2, n_epochs = 5) expect_equal(ibatchtest, ibatchtest2) oargs_umap <- tumap(iris10, n_neighbors = 4, n_epochs = 0, learning_rate = 0.5, init = "spca", verbose = FALSE, batch = TRUE, n_threads = 0, n_sgd_threads = 0, ret_model = TRUE, opt_args = list(alpha = 0.4, beta1 = 0.1, beta2 = 0.2, eps = 1e-3)) expect_equal(length(oargs_umap$opt_args), 5) expect_equal(oargs_umap$opt_args$method, "adam") expect_equal(oargs_umap$opt_args$alpha, 0.4) expect_equal(oargs_umap$opt_args$beta1, 0.1) expect_equal(oargs_umap$opt_args$beta2, 0.2) expect_equal(oargs_umap$opt_args$eps, 1e-3) oargs_umap <- tumap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, init = "spca", verbose = FALSE, batch = TRUE, n_threads = 0, n_sgd_threads = 0, ret_model = TRUE, opt_args = list(method = "sgd", alpha = 0.4)) expect_equal(length(oargs_umap$opt_args), 2) expect_equal(oargs_umap$opt_args$method, "sgd") expect_equal(oargs_umap$opt_args$alpha, 0.4) res <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, min_dist = 0.001, init = "spca", verbose = FALSE, n_threads = 0, ret_extra = c("sigma") ) expect_is(res, "list") expect_ok_matrix(res$embedding) expected_sigma <- c( 0.1799, 0.2049, 0.04938, 0.0906, 0.2494, 0.003906, 0.1537, 0.1355, 0.2454, 0.2063 ) sigma <- res$sigma expect_equal(sigma, expected_sigma, tolerance = 1e-4) expected_rho <- c( 0.1414, 0.1732, 0.2449, 0.2449, 0.1414, 0.6164, 0.2646, 0.1732, 0.3, 0.1732 ) rho <- res$rho expect_equal(rho, expected_rho, 1e-4) res <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, min_dist = 0.001, init = "normlaplacian", verbose = FALSE, n_threads = 0, dens_scale = 1 ) expect_ok_matrix(res) res <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, min_dist = 0.001, init = "normlaplacian", verbose = FALSE, n_threads = 0, dens_scale = 1, ret_extra = c("sigma", "localr") ) expect_is(res, "list") expect_ok_matrix(res$embedding) sigma <- res$sigma expect_equal(sigma, expected_sigma, tolerance = 1e-4) rho <- res$rho expect_equal(rho, expected_rho, tolerance = 1e-4) expected_localr <- c( 0.3214, 0.3781, 0.2943, 0.3356, 0.3908, 0.6203, 0.4182, 0.3087, 0.5454, 0.3795 ) localr <- res$localr expect_equal(localr, expected_localr, tolerance = 1e-4) res <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, min_dist = 0.001, init = "normlaplacian", verbose = FALSE, n_threads = 0, dens_scale = 1, ret_model = TRUE ) expect_is(res, "list") expect_ok_matrix(res$embedding) expected_ai <- c( 8.072, 2.957, 13.89, 6.181, 2.41, 0.1389, 1.585, 10.34, 0.3076, 2.888 ) ai <- res$ai expect_equal(ai, expected_ai, tolerance = 1e-4) expect_equal(res$dens_scale, 1.0) expect_equal(res$method, "leopold") res <- umap(iris10, n_neighbors = 4, n_epochs = 2, learning_rate = 0.5, min_dist = 0.001, init = "normlaplacian", verbose = FALSE, n_threads = 0, dens_scale = 0.5, ret_model = TRUE ) expected_ai05 <- c( 3.348, 2.027, 4.392, 2.93, 1.83, 0.4392, 1.484, 3.79, 0.6536, 2.003 ) expect_equal(res$ai, expected_ai05, tolerance = 1e-3) expect_equal(res$dens_scale, 0.5) ret_trans <- umap_transform(iris10, res) expect_ok_matrix(res$embedding)
library(qrmtools) n <- 10^c(1,3,5) pmExp <- 2 pmG <- c(2, 2) pmN <- c(1, 2) pmLN <- c(1, 2) x <- seq(-3, 10, length.out = 257) pFun <- list(function(q, ...) pexp(q, rate = pmExp, ...), function(q, ...) pgamma(q, shape = pmG[1], rate = pmG[2], ...), function(q, ...) pnorm(q, mean = pmN[1], sd = pmN[2], ...), function(q, ...) plnorm(q, meanlog = pmLN[1], sdlog = pmLN[2], ...)) ndf <- length(pFun) dfs <- as.expression(c(paste0("Exp(",pmExp,")"), substitute(Gamma(a,b), list(a = pmG[1], b = pmG[2])), paste0("N(",pmN[1],", ",pmN[2],")"), paste0("LN(",pmLN[1],", ",pmLN[2],")"))) dFun <- list(function(x, ...) dexp(x, rate = pmExp, ...), function(x, ...) dgamma(x, shape = pmG[1], rate = pmG[2], ...), function(x, ...) dnorm(x, mean = pmN[1], sd = pmN[2], ...), function(x, ...) dlnorm(x, meanlog = pmLN[1], sdlog = pmLN[2], ...)) qFun <- list(function(p, ...) qexp(p, rate = pmExp, ...), function(p, ...) qgamma(p, shape = pmG[1], rate = pmG[2], ...), function(p, ...) qnorm(p, mean = pmN[1], sd = pmN[2], ...), function(p, ...) qlnorm(p, meanlog = pmLN[1], sdlog = pmLN[2], ...)) d_n <- function(n, k) switch(k, { log(n)/pmExp }, { (log(n) + (pmG[1] - 1) * log(log(n)) - lgamma(pmG[1])) / pmG[2] }, { pmN[1] + pmN[2] * (sqrt(2*log(n)) - (log(4*pi) + log(log(n))) / (2*sqrt(2*log(n)))) }, { exp(pmLN[1] + pmLN[2] * (sqrt(2*log(n)) - (log(4*pi) + log(log(n))) / (2*sqrt(2*log(n))))) }, stop("Wrong case")) c_n <- function(n, k) switch(k, { 1/pmExp }, { 1/pmG[2] }, { pmN[2] / sqrt(2*log(n)) }, { pmLN[2] * d_n(n, k = k) / sqrt(2*log(n)) }, stop("Wrong case")) res.p <- vector("list", length = ndf) for(k in seq_len(ndf)) { res.p[[k]] <- lapply(seq_along(n), function(i) { c.n <- c_n(n[i], k = k) d.n <- d_n(n[i], k = k) ly <- log(n[i]) + log(c.n) + dFun[[k]](d.n + c.n * x, log = TRUE) + (n[i]-1) * pFun[[k]](d.n + c.n * x, log.p = TRUE) cbind(x = x, y = exp(ly)) }) } dLambda <- exp(-exp(-x)-x) xlim <- range(x) ylim <- range(dLambda, unlist(lapply(res.p, function(x) lapply(x, function(x.) x.[,"y"])))) opar <- par(mar = c(5, 4, 4, 2) + 0.1 - c(1, 1, 3, 0)) layout(matrix(1:4, nrow = 2, ncol = 2, byrow = TRUE)) k <- 1 for(i in 1:2) { for(j in 1:2) { r <- res.p[[k]] plot(x, dLambda, type = "l", xlim = xlim, ylim = ylim, xlab = "x", ylab = "") lines(r[[1]][,"x"], r[[1]][,"y"], col = "royalblue3") lines(r[[2]][,"x"], r[[2]][,"y"], col = "maroon3") lines(r[[3]][,"x"], r[[3]][,"y"], col = "darkorange2") legend("topright", bty = "n", lty = rep(1, 4), col = c("black", "royalblue3", "maroon3", "darkorange2"), legend = as.expression(c("Gumbel", lapply(1:3, function(i) substitute(n == n., list(n. = n[i])))))) mtext(dfs[k], side = 4, adj = 0, line = 0.75) k <- k+1 } } layout(1) par(opar) m <- 100 ns <- n * m ns.max <- max(ns) set.seed(271) U <- runif(ns.max) system.time(dat <- lapply(qFun, function(qF) qF(U))) res.np <- vector("list", length = ndf) for(k in seq_len(ndf)) { res.np[[k]] <- lapply(seq_along(n), function(i) { c.n <- c_n(n[i], k = k) d.n <- d_n(n[i], k = k) dat. <- head(dat[[k]], n = ns[i]) dat.blocks <- split(dat., f = rep(1:m, each = n[i])) M <- sapply(dat.blocks, function(x) (max(x) - d.n) / c.n) fit.dens <- density(M) cbind(x = fit.dens$x, y = fit.dens$y) }) } ylim <- range(dLambda, unlist(lapply(res.np, function(x) lapply(x, function(x.) x.[,"y"])))) opar <- par(mar = c(5, 4, 4, 2) + 0.1 - c(1, 1, 3, 0)) layout(matrix(1:4, nrow = 2, ncol = 2, byrow = TRUE)) k <- 1 for(i in 1:2) { for(j in 1:2) { r <- res.np[[k]] plot(x, dLambda, type = "l", xlim = xlim, ylim = ylim, xlab = "x", ylab = "") lines(r[[1]][,"x"], r[[1]][,"y"], col = "royalblue3") lines(r[[2]][,"x"], r[[2]][,"y"], col = "maroon3") lines(r[[3]][,"x"], r[[3]][,"y"], col = "darkorange2") legend("topright", bty = "n", lty = rep(1, 4), col = c("black", "royalblue3", "maroon3", "darkorange2"), legend = as.expression(c("Gumbel", lapply(1:3, function(i) substitute(n == n., list(n. = n[i])))))) mtext(dfs[k], side = 4, adj = 0, line = 0.75) k <- k+1 } } layout(1) par(opar)
data2platonic <- function(datamatrix,shape=Rvcg::vcgSphere(),col="red",scale=FALSE,scalefactor=1) { myplatonic <- shape myplatonic <- Morpho::scalemesh(myplatonic,center="none",size=scalefactor) if(scale) matrix <- scale(matrix) col1mesh <- rgb(t(col2rgb(col)), maxColorValue = 255) matmesh <- lapply(1:nrow(datamatrix), function(x) x <- myplatonic) matmesh <- lapply(1:nrow(datamatrix), function(x) x <- translate3d(matmesh[[x]], x = datamatrix[x, 1], y = datamatrix[x, 2], z = datamatrix[x,3])) matmesh <- Morpho::mergeMeshes(matmesh) matmesh$material$color <- rep(col1mesh, ncol(matmesh$vb)) matmesh$normals <- NULL return(matmesh) }
ldata <- vcdExtra::datasets("Lahman") ldata <- ldata[-which(ldata$Item=="LahmanData"),] ldata <- ldata[-grep("Labels", ldata$Item),] ldata dims <- t(matrix(as.numeric(unlist(strsplit(ldata$dim, "x"))), 2, nrow(ldata))) title <- sub(" -.*", "", ldata$Title) ldata <- data.frame(file=ldata$Item, class=ldata$class, nobs=dims[,1], nvar=dims[,2], title=title, stringsAsFactors = FALSE ) LahmanData <- ldata save(LahmanData, file="data/LahmanData.RData")
denominator <- function(x, numerator = 1, quarter = TRUE, ...) { if (!length(x)) return(character(0)) if (!is.numeric(x)) stop("`x` must be numeric") if (!is.numeric(numerator)) stop("`numerator` must be numeric") if (length(numerator) != 1 & length(numerator) != length(x)) stop("`numerator` must be either length one or the same length as `x`") if (length(quarter) != 1) stop("`quarter` must be length one") if (!is.logical(quarter) | is.na(quarter)) stop("`quarter` must be either `TRUE` or `FALSE`") numeric <- x denom <- ordinal(x, ...) plural <- abs(numerator) != 1 denom[abs(x) == 1] <- gsub("1st$|first$", "whole", denom[abs(x) == 1]) denom[abs(x) == 2 & !plural] <- gsub( "2nd$|second$", "half", denom[abs(x) == 2 & !plural] ) denom[abs(x) == 2 & plural] <- gsub( "2nd$|second$", "halves", denom[abs(x) == 2 & plural] ) if (quarter) { denom[abs(x) == 4] <- gsub("fourth$", "quarter", denom[abs(x) == 4]) } denom[plural & abs(x) != 2] <- paste0(denom[plural & abs(x) != 2], "s") denom <- gsub("^one-", "", denom) args <- as.list(match.call()[-1]) args[["x"]] <- NULL structure( denom, numeric = numeric, nombre = "denominator", args = args, class = c("nombre", "character") ) } nom_denom <- denominator
"ecld.sged_const" <- function(object) { ecld.validate(object, sged.only=TRUE) one <- if([email protected]) ecd.mp1 else 1 lambda <- object@lambda s <- object@sigma b <- object@beta mu <- object@mu d <- ecd(lambda=lambda, sigma=s, mu=mu, bare.bone=TRUE) e_y <- function(x) exp(ecld.solve(object, x)) i1 <- ecd.integrate(d, e_y, mu, Inf) i2 <- ecd.integrate(d, e_y, -Inf, mu) C <- i1$value + i2$value return(C) } "ecld.sged_cdf" <- function(object, x) { ecld.validate(object, sged.only=TRUE) d <- ecd(lambda=object@lambda, sigma=object@sigma, bare.bone=TRUE) e_y <- function(x) exp(ecld.solve(object, x)) C <- ecld.const(object) cdf <- function(x) { if (x < object@mu) { c2 <- ecd.integrate(d, e_y, -Inf, x) return(c2$value/C) } else { c1 <- ecd.integrate(d, e_y, x, Inf) return(1-c1$value/C) } } return(ecld.sapply(object, x, cdf)) } "ecld.sged_moment" <- function(object, order) { ecld.validate(object, sged.only=TRUE) if (length(order)>1) { return(ecld.sapply(object, order, function(n) ecld.sged_moment(object,n) )) } d <- ecd(lambda=object@lambda, sigma=object@sigma, bare.bone=TRUE) e_y <- function(x) exp(ecld.solve(object, x)) * (x-object@mu)^order C <- ecld.const(object) c1 <- ecd.integrate(d, e_y, object@mu, Inf) c2 <- ecd.integrate(d, e_y, -Inf, object@mu) return((c1$value + c2$value)/C) } "ecld.sged_mgf" <- function(object, t=1) { ecld.validate(object, sged.only=TRUE) sigma <- object@sigma d <- ecd(lambda=object@lambda, sigma=sigma, bare.bone=TRUE) e_y <- function(x) exp(ecld.solve(object, x) + t*x) C <- ecld.const(object) xmax <- ecld.y_slope_trunc(object) if (is.na(xmax)) { stop("Failed to locate y_slope truncation point") } xmax2 <- .ecd.mpfr.N.sigma * sigma + object@mu if (xmax > xmax2) xmax <- xmax2 c1 <- ecd.integrate(d, e_y, object@mu, xmax) c2 <- ecd.integrate(d, e_y, -Inf, object@mu) return(c1$value/C + c2$value/C) } "ecld.sged_imgf" <- function(object, k, t=1, otype="c") { if (length(k)>1) { f <- function(k) ecld.sged_imgf(object, k, t=t, otype=otype) return(ecld.sapply(object, k, f)) } if (!(otype %in% c("c","p"))) { stop(paste("Unknown option type:", otype)) } ecld.validate(object, sged.only=TRUE) d <- ecd(lambda=object@lambda, sigma=object@sigma, bare.bone=TRUE) e_y <- function(x) exp(ecld.solve(object, x) + t*x) C <- ecld.const(object) if (otype=="c") { if (k >= object@mu) { xmax <- ecld.y_slope_trunc(object) if (is.na(xmax)) { stop("Failed to locate y_slope truncation point") } xmax2 <- .ecd.mpfr.N.sigma * object@sigma + object@mu if (xmax > xmax2) xmax <- xmax2 c1 <- ecd.integrate(d, e_y, k, xmax) return(c1$value/C) } else { Mp <- ecld.sged_imgf(object, k, otype="p") M1 <- ecld.sged_mgf(object) return(M1-Mp) } } if (otype=="p") { if (k < object@mu) { c2 <- ecd.integrate(d, e_y, -Inf, k) return(c2$value/C) } else { Mc <- ecld.sged_imgf(object, k, otype="c") M1 <- ecld.sged_mgf(object) return(M1-Mc) } } stop(paste("Unknown option type:", otype)) } "ecld.sged_ogf" <- function(object, k, otype="c") { if (length(k)>1) { f <- function(k) ecld.sged_ogf(object, k, otype=otype) return(ecld.mclapply(object, k, f)) } if (!(otype %in% c("c","p"))) { stop(paste("Unknown option type:", otype)) } ecld.validate(object, sged.only=TRUE) if (otype=="c") { Mc <- ecld.imgf(object, k, otype="c") ccdf <- 1-ecld.cdf(object, k) return(Mc-exp(k)*ccdf) } if (otype=="p") { Mp <- ecld.imgf(object, k, otype="p") cdf <- ecld.cdf(object, k) return(-Mp+exp(k)*cdf) } stop(paste("Unknown option type:", otype)) }
getWDI = function(indicator = "SP.POP.TOTL", name = NULL, startDate = 1960, endDate = format(Sys.Date(), "%Y"), printURL = FALSE, outputFormat = "wide"){ if(is.null(name)) name = indicator url = paste("https://api.worldbank.org/v2/countries/all/indicators/", indicator, "?date=", startDate, ":", endDate, "&format=json&per_page=30000", sep = "") if(printURL) print(url) wbData = fromJSON(url)[[2]] wbData = data.frame(Country = sapply(wbData, function(x) x[["country"]]["value"]), ISO2_WB_CODE= sapply(wbData, function(x) x[["country"]]["id"]), Year = as.integer(sapply(wbData, "[[", "date")), Value = as.numeric(sapply(wbData, function(x) ifelse(is.null(x[["value"]]), NA, x[["value"]]))), stringsAsFactors = FALSE) if(outputFormat == "long"){ wbData$name = name } else if(outputFormat == "wide"){ names(wbData)[4] = name } return(wbData) }
uniroot.all <- function (f, interval, lower= min(interval), upper= max(interval), tol= .Machine$double.eps^0.2, maxiter= 1000, trace = 0, n = 100, ... ) { if (!missing(interval) && length(interval) != 2) stop("'interval' must be a vector of length 2") if (!is.numeric(lower) || !is.numeric(upper) || lower >= upper) stop("lower < upper is not fulfilled") xseq <- seq(lower,upper,len=n+1) mod <- f(xseq,...) Equi <- xseq[which(mod==0)] ss <- mod[1:n]*mod[2:(n+1)] ii <- which(ss<0) for (i in ii) Equi <- c(Equi, uniroot(f,lower=xseq[i],upper=xseq[i+1], maxiter = maxiter, tol = tol, trace = trace, ...)$root) return(Equi) }
h_boot <- function (x, n.ahead, runs, ortho, cumulative, impulse, response, ci, seed, y.names) { if (!(is.null(seed))) set.seed(abs(as.integer(seed))) if (inherits(x, "varest")) { VAR <- eval.parent(x) } else if (inherits(x, "svarest")) { VAR <- eval.parent(x$var) } else { stop("Bootstrap not implemented for this class.\n") } p <- VAR$p K <- VAR$K obs <- VAR$obs total <- VAR$totobs type <- VAR$type B <- Bcoef_sh(VAR) BOOT <- vector("list", runs) ysampled <- matrix(0, nrow = total, ncol = K) colnames(ysampled) <- names(VAR$varresult) Zdet <- NULL if (ncol(VAR$datamat) > (K * (p + 1))) { Zdet <- as.matrix(VAR$datamat[, (K * (p + 1) + 1):ncol(VAR$datamat)]) } resorig <- scale(resid(VAR), scale = FALSE) B <- Bcoef_sh(VAR) for (i in 1:runs) { booted <- sample(c(1:obs), replace = TRUE) resid <- resorig[booted, ] lasty <- c(t(VAR$y[p:1, ])) ysampled[c(1:p), ] <- VAR$y[c(1:p), ] for (j in 1:obs) { lasty <- lasty[1:(K * p)] Z <- c(lasty, Zdet[j, ]) ysampled[j + p, ] <- B %*% Z + resid[j, ] lasty <- c(ysampled[j + p, ], lasty) } varboot <- update(VAR, y = ysampled) if (inherits(x, "svarest")) { varboot <- update(x, x = varboot) } BOOT[[i]] <- h_irf(x = varboot, n.ahead = n.ahead, ortho = ortho, cumulative = cumulative, impulse = impulse, response = response, y.names = y.names) } lower <- ci/2 upper <- 1 - ci/2 mat.l <- matrix(NA, nrow = n.ahead + 1, ncol = length(response)) mat.u <- matrix(NA, nrow = n.ahead + 1, ncol = length(response)) Lower <- list() Upper <- list() idx1 <- length(impulse) idx2 <- length(response) idx3 <- n.ahead + 1 temp <- rep(NA, runs) for (j in 1:idx1) { for (m in 1:idx2) { for (l in 1:idx3) { for (i in 1:runs) { if (idx2 > 1) { temp[i] <- BOOT[[i]][[j]][l, m] } else { temp[i] <- matrix(BOOT[[i]][[j]])[l, m] } } mat.l[l, m] <- quantile(temp, lower, na.rm = TRUE) mat.u[l, m] <- quantile(temp, upper, na.rm = TRUE) } } colnames(mat.l) <- response colnames(mat.u) <- response Lower[[j]] <- mat.l Upper[[j]] <- mat.u } names(Lower) <- impulse names(Upper) <- impulse result <- list(Lower = Lower, Upper = Upper) return(result) }
int_est1 <- function(x, lev) { ec <- 0.57721566490153286 zeta3 <- 1.202056903159594285399 dum<-point_est1(x) n<-length(x) ah<-dum[1] sh<-dum[2] zcv <- qnorm(1 - (1 - lev)/2, 0, 1) sah <- sqrt((-1 - (ah^4 - 11)/(10 * ah^2))/n) ssh <- sqrt((((sh^2) * (-(-1 + ah^2) * (pi^2) * (3 * (11 + ah^2) *ec^2 + 5 * (ah^2) * (pi^2)) + 360 * ah * (-1 + ah^3) * ec *(zeta3)))/(30 * (ah^2) * (pi^2)))/n) return( rbind( c('alpha:', ah - zcv * sah, ah + zcv * sah), c('rho:', sh - zcv * ssh, sh + zcv * ssh) ) ) }
NULL dim.blockmatrix <- function (x) { return(dim(as.matrix(x$value))) }
context("test Reaction as app") source(paste(system.file("examples", package = "rODE"), "Reaction.R", sep ="/")) X <- 1; Y <- 5; dt <- 0.1 reaction <- Reaction(c(X, Y, 0)) solver <- RK4(reaction) expect_equal(solver@estimated_state, c(0, 0, 0)) expect_equal(solver@numEqn, 3) test_that("rates are zero before step", { expect_equal(solver@rate1, c(0, 0, 0)) expect_equal(solver@rate2, c(0, 0, 0)) expect_equal(solver@rate3, c(0, 0, 0)) expect_equal(solver@rate4, c(0, 0, 0)) }) solver <- step(solver) test_that("get these values after one step", { expect_equal(solver@ode@state, c(1.342695, 4.641994, 0.1), tolerance = 0.000001) expect_equal(solver@estimated_state, c(1.345462, 4.638375, 0.100000), tolerance = 0.000001) expect_equal(solver@numEqn, 3) expect_equal(solver@rate1, c(2.5, -2.5, 1.0)) expect_equal(solver@rate2, c(3.232422, -3.357422, 1.000000), tolerance = 0.0000001) expect_equal(solver@rate3, c(3.454625, -3.616246, 1.000000), tolerance = 0.0000001) expect_equal(solver@rate4, c(4.687590, -5.033052, 1.000000), tolerance = 0.0000001) }) while (solver@ode@state[3] <= 100.0) { solver <- step(solver) } test_that("get this vector at the end of the loop", { expect_equal(c(solver@ode@state[1], solver@ode@state[2], solver@ode@state[3]), c(1.987618, 1.143675, 100.1)) })
distance <- function(box1, box2, type = c("vertical", "horizontal", "euclidean"), half = FALSE, center = FALSE) { assert_input <- function(v) { assert( checkClass(v, "box"), checkClass(v, "coords"), checkNumeric(v), checkTRUE(is.unit(v)) ) } type <- match.arg(type) if (missing(box2) && is.list(box1) && length(box1) == 2) { box2 <- box1[[2]] box1 <- box1[[1]] } assert_input(box1) assert_input(box2) box_coords1 <- prConvert2Coords(box1) box_coords2 <- prConvert2Coords(box2) type = match.arg(type) converter_fn <- ifelse(type == "horizontal", prCnvrtX, prCnvrtY) from = NA to = NA if (type == "vertical") { if (converter_fn(box_coords1$y) > converter_fn(box_coords2$y)) { if (center) { from <- box_coords1$y to <- box_coords2$y } else { from <- box_coords1$bottom to <- box_coords2$top } } else { if (center) { from <- box_coords1$y to <- box_coords2$y } else { from <- box_coords1$top to <- box_coords2$bottom } } ret <- converter_fn(to) - converter_fn(from) } else if (type == "horizontal") { if (prCnvrtX(box_coords1$x) < prCnvrtX(box_coords2$x)) { if (center) { from <- box_coords1$x to <- box_coords2$x } else { from <- box_coords1$right to <- box_coords2$left } } else { if (center) { from <- box_coords1$x to <- box_coords2$x } else { from <- box_coords1$left to <- box_coords2$right } } ret <- converter_fn(to) - converter_fn(from) } else if (type == "euclidean") { ydist <- distance(box1 = box1, box2 = box2, type = "vertical", center = center) xdist <- distance(box1 = box1, box2 = box2, type = "horizontal", center = center) ret <- sqrt(prCnvrtY(ydist)^2 + prCnvrtX(xdist)^2) } else { stop("Unreachable code") } if (ret < 0) { positive <- FALSE ret <- -1 * ret } else { positive <- TRUE } if (half) { ret <- ret / 2 } ret <- unit(ret, "mm") structure( ret, class = c("Gmisc_unit", class(ret)), positive = positive, from = from, to = to, type = type, box_coords1 = box_coords1, box_coords2 = box_coords2, center = center) } print.Gmisc_unit <- function(x, ...) { base_txt <- as.character(x) repr <- paste( base_txt, paste0(" - positive = ", as.character(attr(x, "positive"))), paste0(" - from ", as.character(attr(x, "from"))), paste0(" - to ", as.character(attr(x, "to"))), paste0(" - type: ", as.character(attr(x, "type"))), paste0(" - center: ", as.character(attr(x, "center"))), "", sep = "\n") cat(repr) invisible(x) }
nlsR2 <- function(nlsAns, y, p) { n <- length(y) rsds <- residuals(nlsAns) rr <- sum(rsds^2) / var(y) / (length(y) - 1) R2 <- 1 - rr adjR2 <- 1 - rr * (n - 1) / (n - p) return(list(R2 = R2, adjR2 = adjR2)) }
context("Pretreatment functions of mixtCompLearn's parameters") Sys.setenv(MC_DETERMINISTIC = 42) test_that("imputModelIntern returns Gaussian when a numeric is given", { data <- rnorm(100) outModel <- imputModelIntern(data, name = "var") expect_equal(outModel, "Gaussian") }) test_that("imputModelIntern returns Poisson when an integer vector is given", { data <- 1:100 outModel <- imputModelIntern(data, name = "var") expect_equal(outModel, "Poisson") }) test_that("imputModelIntern returns Multinomial when a character/factor is given", { data <- letters outModel <- imputModelIntern(data, name = "var") expect_equal(outModel, "Multinomial") data <- as.factor(letters) outModel <- imputModelIntern(data, name = "var") expect_equal(outModel, "Multinomial") }) test_that("imputModelIntern returns LatentClass when the variable is named z_class", { data <- 1:100 outModel <- imputModelIntern(data, name = "z_class") expect_equal(outModel, "LatentClass") }) test_that("imputModelIntern returns an error when a bad type is given", { data <- list() expect_error(outModel <- imputModelIntern(data, name = "var")) }) test_that("imputModel works with data.frame", { data <- data.frame(a = 1:3, b = rnorm(3), c = letters[1:3], z_class = 1:3) expectedModel <- list(a = list(type = "Poisson", paramStr = ""), b = list(type = "Gaussian", paramStr = ""), c = list(type = "Multinomial", paramStr = ""), z_class = list(type = "LatentClass", paramStr = "")) outModel <- imputModel(data) expect_equal(outModel, expectedModel) }) test_that("imputModel works with list", { data <- list(a = 1:3, b = rnorm(3), c = letters[1:3], z_class = 1:3) expectedModel <- list(a = list(type = "Poisson", paramStr = ""), b = list(type = "Gaussian", paramStr = ""), c = list(type = "Multinomial", paramStr = ""), z_class = list(type = "LatentClass", paramStr = "")) outModel <- imputModel(data) expect_equal(outModel, expectedModel) }) test_that("imputModel returns an error with a matrix", { data <- matrix(rnorm(50), ncol = 5, dimnames = list(NULL, letters[1:5])) expect_error(outModel <- imputModel(data)) }) test_that("completeModel adds hyperparameters for functional data", { model <- list(gauss = list(type = "Gaussian", paramStr = ""), func1 = list(type = "Func_CS", paramStr = "nSub: 3, nCoeff: 3"), func2 = list(type = "Func_SharedAlpha_CS", paramStr = "nSub: 3, nCoeff: 3"), func3 = list(type = "Func_CS", paramStr = ""), func4 = list(type = "Func_SharedAlpha_CS", paramStr = "")) nInd <- 200 ratioPresent <- 0.95 var <- list() var$z_class <- RMixtCompIO:::zParam() var$func1 <- RMixtCompIO:::functionalInterPolyParam("func1") var$func2 <- RMixtCompIO:::functionalInterPolyParam("func2") var$func3 <- RMixtCompIO:::functionalInterPolyParam("func3") var$func4 <- RMixtCompIO:::functionalInterPolyParam("func4") data <- RMixtCompIO:::dataGeneratorNewIO(nInd, ratioPresent, var)$data expect_warning(out <- completeModel(model, data)) expect_equal(out, list(gauss = list(type = "Gaussian", paramStr = ""), func1 = list(type = "Func_CS", paramStr = "nSub: 3, nCoeff: 3"), func2 = list(type = "Func_SharedAlpha_CS", paramStr = "nSub: 3, nCoeff: 3"), func3 = list(type = "Func_CS", paramStr = "nSub: 2, nCoeff: 2"), func4 = list(type = "Func_SharedAlpha_CS", paramStr = "nSub: 2, nCoeff: 2"))) }) test_that("formatDataBasicMode works with data.frame", { dat <- data.frame(a = rnorm(20), b = as.character(rep(letters[1:2], 10)), c = as.factor(rep(letters[2:1], 10)), d = 1:20, z_class = letters[1:20]) dat[1,] = NA model <- list(a = list(type = "Gaussian"), b = list(type = "Multinomial"), c = list(type = "Multinomial"), d = list(type = "Poisson"), z_class = list(type = "LatentClass")) out <- formatDataBasicMode(dat, model) expect_length(out, 2) expect_named(out, c("data", "dictionary")) expect_type(out$data, "list") expect_named(out$data, c("a", "b", "c", "d", "z_class")) expect_equal(out$data$a, c("?", as.character(dat$a[-1]))) expect_equal(out$data$b, c("?", rep(2:1, 9), 2)) expect_equal(out$data$c, c("?", rep(1:2, 9), 1)) expect_equal(out$data$d, c("?", as.character(dat$d[-1]))) expect_equal(out$data$z_class, c("?", 1:19)) expect_type(out$dictionary, "list") expect_length(out$dictionary, 3) expect_named(out$dictionary, c("b", "c", "z_class")) expect_equal(out$dictionary$b, list(old = sort(letters[2:1]), new = c("1", "2"))) expect_equal(out$dictionary$c, list(old = sort(letters[2:1]), new = c("1", "2"))) expect_equal(out$dictionary$z_class, list(old = sort(letters[2:20]), new = as.character(1:19))) }) test_that("formatDataBasicMode works with list", { dat <- list(a = rnorm(20), b = as.character(rep(letters[1:2], 10)), c = as.factor(rep(letters[2:1], 10)), d = 1:20, z_class = letters[1:20]) dat$a[1] = NA dat$b[1] = NA dat$c[1] = NA dat$d[1] = NA dat$z_class[1] = NA model <- list(a = list(type = "Gaussian"), b = list(type = "Multinomial"), c = list(type = "Multinomial"), d = list(type = "Poisson"), z_class = list(type = "LatentClass")) out <- formatDataBasicMode(dat, model) expect_length(out, 2) expect_named(out, c("data", "dictionary")) expect_type(out$data, "list") expect_named(out$data, c("a", "b", "c", "d", "z_class")) expect_equal(out$data$a, c("?", as.character(dat$a[-1]))) expect_equal(out$data$b, c("?", rep(2:1, 9), 2)) expect_equal(out$data$c, c("?", rep(1:2, 9), 1)) expect_equal(out$data$d, c("?", as.character(dat$d[-1]))) expect_equal(out$data$z_class, c("?", 1:19)) expect_type(out$dictionary, "list") expect_length(out$dictionary, 3) expect_named(out$dictionary, c("b", "c", "z_class")) expect_equal(out$dictionary$b, list(old = sort(letters[2:1]), new = c("1", "2"))) expect_equal(out$dictionary$c, list(old = sort(letters[2:1]), new = c("1", "2"))) expect_equal(out$dictionary$z_class, list(old = sort(letters[2:20]), new = as.character(1:19))) }) test_that("formatDataBasicMode works with a dictionary", { dat <- list(a = rnorm(20), b = as.character(rep(letters[1:2], 10)), c = as.factor(rep(letters[2:1], 10)), d = 1:20, z_class = 1:20) dat$a[1] = NA dat$b[1] = NA dat$c[1] = NA dat$d[1] = NA dat$z_class[1] = NA model <- list(a = list(type = "Gaussian"), b = list(type = "Multinomial"), c = list(type = "Multinomial"), d = list(type = "Poisson"), z_class = list(type = "LatentClass")) dictionary <- list(b = list(old = c("a", "b"), new = c("1", "2")), c = list(old = c("a", "b"), new = c("1", "2"))) out <- formatDataBasicMode(dat, model, dictionary) expect_length(out, 2) expect_named(out, c("data", "dictionary")) expect_type(out$data, "list") expect_named(out$data, c("a", "b", "c", "d", "z_class")) expect_equal(out$data$a, c("?", as.character(dat$a[-1]))) expect_equal(out$data$b, c("?", "2", rep(c("1", "2"), 9))) expect_equal(out$data$c, c("?", "1", rep(c("2", "1"), 9))) expect_equal(out$data$d, c("?", as.character(dat$d[-1]))) expect_equal(out$data$z_class, c("?", as.character(dat$z_class[-1]))) expect_equal(out$dictionary, dictionary) dictionary$b = NULL expect_error(out <- formatDataBasicMode(dat, model, dictionary)) }) test_that("checkNClass works with mixtComp object", { resLearn <- list(algo = list(nClass = 2)) class(resLearn) = "MixtComp" nClass <- NULL expect_warning(out <- checkNClass(nClass, resLearn), regexp = NA) expect_equal(out, 2) nClass <- 3 expect_warning(out <- checkNClass(nClass, resLearn)) expect_equal(out, 2) nClass <- 2:4 expect_warning(out <- checkNClass(nClass, resLearn)) expect_equal(out, 2) nClass <- 3:4 expect_warning(out <- checkNClass(nClass, resLearn)) expect_equal(out, 2) }) test_that("checkNClass works with mixtCompLearn object", { resLearn <- list(algo = list(nClass = 2), nClass = 2:5) class(resLearn) = c("MixtCompLearn", "MixtComp") nClass <- NULL expect_warning(out <- checkNClass(nClass, resLearn), regexp = NA) expect_equal(out, 2) nClass <- 3 expect_warning(out <- checkNClass(nClass, resLearn), regexp = NA) expect_equal(out, 3) nClass <- 3:4 expect_warning(out <- checkNClass(nClass, resLearn)) expect_equal(out, 3) nClass <- 6:8 expect_warning(out <- checkNClass(nClass, resLearn)) expect_equal(out, 2) }) test_that("performHierarchical works", { model <- list("a" = list(type = "Gaussian")) mode <- "basic" for(hierarchicalMode in c("yes", "no", "auto")) { out <- performHierarchical(hierarchicalMode, mode, model) expect_false(out) } mode = "expert" out <- performHierarchical(hierarchicalMode = "yes", mode, model) expect_true(out) for(hierarchicalMode in c("no", "auto")) { out <- performHierarchical(hierarchicalMode, mode, model) expect_false(out) } model$b = list(type = "Func_CS") out <- performHierarchical(hierarchicalMode = "no", mode, model) expect_false(out) for(hierarchicalMode in c("yes", "auto")) { out <- performHierarchical(hierarchicalMode, mode, model) expect_true(out) } }) test_that("changeClassNames works", { rowNames <- c("k: 1, lambda", "k: 2, mean", "k: 2, sd", "k: 3, modality: 1", "k: 3, modality: 2", "k: 4, n", "k: 4, p", "k: 5, k", "k: 6, s: 0, alpha0", "k: 7, s: 0, alpha1", "k: 8, s: 0, c: 0", "k: 9, s: 0", "k: 10, pi") dictionary <- list(z_class = list(old = paste0("G", 1:10), new = 1:10)) out <- changeClassName(rowNames, dictionary) expect_equal(out, c("k: G1, lambda", "k: G2, mean", "k: G2, sd", "k: G3, modality: 1", "k: G3, modality: 2", "k: G4, n", "k: G4, p", "k: G5, k", "k: G6, s: 0, alpha0", "k: G7, s: 0, alpha1", "k: G8, s: 0, c: 0", "k: G9, s: 0", "k: G10, pi")) }) test_that("formatOutputBasicMode works", { dictionary <- list(z_class = list(old = c("setosa", "versicolor", "virginica"), new = c("1", "2", "3")), categ1 = list(old = c("a", "b"), new = c("1", "2"))) res0 <- list(algo = list(), variable = list(type = list(z_class = "LatentClass", categ1 = "Multinomial"), data = list(z_class = list(completed = c(3, 3, 1, 2), stat = matrix(NA, nrow = 1, ncol = 3, dimnames = list(NULL, c("k: 1", "k: 2", "k: 3")))), categ1 = list(completed = c(2, 1, 2))), param = list(z_class = list(stat = matrix(NA, nrow = 3, ncol = 3, dimnames = list(c("k: 1", "k: 2", "k: 3"), NULL)), log = matrix(NA, nrow = 3, ncol = 2, dimnames = list(c("k: 1", "k: 2", "k: 3"), NULL))), categ1 = list(stat = matrix(NA, nrow = 6, ncol = 3, dimnames = list(c("k: 1, modality: 1", "k: 1, modality: 2", "k: 2, modality: 1", "k: 2, modality: 2", "k: 3, modality: 1", "k: 3, modality: 2"), NULL)), log = matrix(NA, nrow = 6, ncol = 2, dimnames = list(c("k: 1, modality: 1", "k: 1, modality: 2", "k: 2, modality: 1", "k: 2, modality: 2", "k: 3, modality: 1", "k: 3, modality: 2"), NULL))) ))) res <- formatOutputBasicMode(res0, dictionary) expect_equal(res$algo$dictionary, dictionary) expect_equal(res$variable$data$z_class$completed, c("virginica", "virginica", "setosa", "versicolor")) expect_equal(colnames(res$variable$data$z_class$stat), c("k: setosa", "k: versicolor", "k: virginica")) expect_equal(res$variable$data$categ1$completed, c("b", "a", "b")) expect_equal(rownames(res$variable$param$z_class$stat), c("k: setosa", "k: versicolor", "k: virginica")) expect_equal(rownames(res$variable$param$z_class$log), c("k: setosa", "k: versicolor", "k: virginica")) expect_equal(rownames(res$variable$param$categ1$stat), c("k: setosa, modality: a", "k: setosa, modality: b", "k: versicolor, modality: a", "k: versicolor, modality: b", "k: virginica, modality: a", "k: virginica, modality: b")) expect_equal(rownames(res$variable$param$categ1$log), c("k: setosa, modality: a", "k: setosa, modality: b", "k: versicolor, modality: a", "k: versicolor, modality: b", "k: virginica, modality: a", "k: virginica, modality: b")) }) Sys.unsetenv("MC_DETERMINISTIC")
minimal_model_MRMC <- function() { m <-c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3 ,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5 ,5,5,5,5,5,5,5,5,5,5,5,5) q <-c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,1,1,1,1 ,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,1,1,1,1,1,2,2,2 ,2,2,3,3,3,3,3,4,4,4,4,4) c<-c(5,4,3,2,1,5,4,3,2,1,5,4,3,2,1,5,4,3,2,1,5,4,3,2,1,5,4,3,2,1,5,4,3,2,1,5,4,3,2,1,5,4,3,2 ,1,5,4,3,2,1,5,4,3,2,1,5,4,3,2,1,5,4,3,2,1,5,4,3,2,1,5,4,3,2,1,5,4,3,2,1,5,4,3,2,1,5,4,3 ,2,1,5,4,3,2,1,5,4,3,2,1) f<-c( 0,4,20,29,21,0,0,6,15,22,1,15,18,31,19,1,2,4,16,17,1,1,21,24,23,1,1,5,30 ,40,2,19,31,56,42,2,0,2,30,32,1,7,13,28,19,0,1,7,7,31,7,15,28,41,9,0,2,5 ,24,31,1,4,18,21,23,1,1,0,11,35,6,14,37,36,18,0,2,4,18,25,0,2,19,23,18,0,2 ,6,10,30,2,25,40,29,24,1,1,4,24,32 ) h<-c( 50,30,11,5,1,15,29,29,1,0,39,31,8,10,3,10,8,25,45,14,52,25,13,4,1,27,28,29,1 ,0,53,29,13,2,4,9,16,22,43,14,43,29,11,6,0,18,29,21,0,0,43,29,6,7,1,10,14,19 ,32,23,61,19,12,9,3,16,29,34,1,0,52,29,10,4,3,10,16,23,43,15,35,29,18,9,0,17,27 ,24,0,0,34,33,7,13,2,12,16,21,35,15 ) C<-5 M<-5 Q<-4 NI<-199 NL<-142 N <-C*M*Q ff <- numeric(N) harray<-array(0,dim=c(C,M,Q)); for(md in 1:M) { for(cd in 1:C) { for(qd in 1 : Q){ for(n in 1:cd){ ff[cd+(md-1)*C*Q+(qd-1)*C]<-ff[cd+(md-1)*C*Q+(qd-1)*C]+f[n+(md-1)*C*Q+(qd-1)*C] } harray[cd,md,qd] <- h[cd+(md-1)*C*Q+(qd-1)*C] }}} data <- list(N=N,Q=Q, M=M,m=m ,C=C , NL=NL,NI=NI ,c=c,q=q, h=h, f=f, ff=ff, harray=harray,ModifiedPoisson=FALSE ) Stan.model <- rstan::stan_model( model_code=" data{ int <lower=0>N; int <lower=0>M; int <lower=0>C; int <lower=0>Q; int <lower=0>h[N]; int <lower=0>f[N]; int <lower=0>q[N]; int <lower=0>c[N]; int <lower=0>m[N]; int <lower=0>NL; int <lower=0>NI; int <lower=0>ff[N]; int <lower=0>harray[C,M,Q]; int ModifiedPoisson;//////Logical } transformed data { int <lower=0> NX; if(ModifiedPoisson==0) NX = NI; if(ModifiedPoisson==1) NX =NL; print(\" 2019 Dec 25 Non hierarchical MRMC model \") print(\" 2019 Dec 25 Non hierarchical MRMC model \") print(\" 2019 Dec 25 Non hierarchical MRMC model \") print(\" 2019 Dec 25 Non hierarchical MRMC model \") print(\" 2019 Dec 25 Non hierarchical MRMC model \") print(\" 2019 Dec 25 Non hierarchical MRMC model \") print(\" 2019 Dec 25 Non hierarchical MRMC model \") print(\" 2019 Dec 25 Non hierarchical MRMC model \") print(\" 2019 Dec 25 Non hierarchical MRMC model \") print(\" 2019 Dec 25 Non hierarchical MRMC model \") print(\" 2019 Dec 25 Non hierarchical MRMC model \") print(\" 2019 Dec 25 Non hierarchical MRMC model \") } parameters{ real w; real <lower =0 > dz[C-1]; real mu[M,Q]; real <lower=0> v[M,Q]; } transformed parameters { real <lower =0> dl[C]; real <lower=0,upper=1> ppp[C,M,Q]; real <lower =0> l[C]; real z[C]; real aa[M,Q]; real <lower =0> bb[M,Q]; real <lower=0,upper=1> AA[M,Q]; real deno[C-1,M,Q]; real hit_rate[C,M,Q]; real <lower=0,upper=1>A[M]; z[1]=w; for(md in 1 : M) { for(qd in 1 : Q) { aa[md,qd]=mu[md,qd]/v[md,qd]; bb[md,qd]=1/v[md,qd]; for(cd in 1 : C-1) z[cd+1] = z[cd] + dz[cd]; ppp[C,md,qd] = 1- Phi((z[C] -mu[md,qd])/v[md,qd]); for(cd in 1 : C-1) ppp[cd,md,qd] = Phi((z[cd+1] -mu[md,qd])/v[md,qd]) - Phi((z[cd ] -mu[md,qd])/v[md,qd]); for(cd in 1 : C) l[cd] = (-1)*log(Phi(z[cd])); dl[C] = fabs(l[C]-0); for(cd in 1:C-1) dl[cd]= fabs(l[cd]-l[cd+1]); } } for(md in 1 : M) { for(qd in 1 : Q) { AA[md,qd]=Phi( (mu[md,qd]/v[md,qd])/sqrt((1/v[md,qd])^2+1) );//////Measures of modality performance }} for(md in 1 : M) { A[md] = 0; for(qd in 1 : Q) { A[md] = A[md] + AA[md,qd]; } A[md]= A[md]/Q; } for(md in 1 : M) { for(qd in 1 : Q) { deno[C-1,md,qd]=1-ppp[C,md,qd]; for(cd in 3:C){ deno[c[cd],md,qd]=deno[c[cd-1],md,qd]-ppp[c[cd-1],md,qd]; } }} for(md in 1 : M) { for(qd in 1 : Q) { for(cd in 1:C-1){ hit_rate[cd,md,qd]=ppp[cd,md,qd]/deno[cd,md,qd]; } hit_rate[C,md,qd]=ppp[C,md,qd]; }} } model{ int s=0; for(n in 1:N) { target += poisson_lpmf(ff[n]|l[c[n]]*NX); } for(qd in 1 : Q) { for(md in 1 : M) { s=0; for(cd in 1 : C){ target += binomial_lpmf(harray[cd,md,qd] | NL-s, hit_rate[c[cd],md,qd] ); s = s + harray[cd,md,qd]; } }} w ~ uniform(-3,3); for(cd in 1:C-1) dz[cd] ~ uniform(0.001,7); for(md in 1 : M) { for(qd in 1 : Q) { mu[md,qd] ~ uniform(-11,11); v[md,qd] ~ uniform(0.01,11); }} } ") fit <- rstan::sampling( object= Stan.model, data=data, verbose = FALSE, seed=1, chains=1, warmup=11, iter=111, sample_file =paste0(file.path(Sys.getenv("USERPROFILE"),"Desktop"),"\\samples"), control = list(adapt_delta = 0.9999999, max_treedepth = 15) ) rstan::traceplot(fit,pars=c("w")) rstan::check_hmc_diagnostics(fit) }
termExtraction <- function(M, Field="TI", ngrams = 1, stemming=FALSE, language="english",remove.numbers=TRUE, remove.terms=NULL, keep.terms=NULL, synonyms=NULL, verbose=TRUE){ if (Field %in% c("ID","DE")){ngrams <- 1} data("stopwords",envir=environment()) data("stop_words", envir=environment(), package = "tidytext") stop_words <- stop_words %>% as.data.frame() if (ngrams == 2){remove.terms <- c(remove.terms,stopwords$bigrams)} switch(language, english={stopwords=(stop_words$word)}, italian={stopwords=stopwords$it}, german={stopwords=stopwords$de}, french={stopwords=stopwords$fr}, spanish={stopwords=stopwords$es} ) stopwords <- tolower(stopwords) TERMS <- M %>% select(.data$SR,!!Field) names(TERMS) <- c("SR","text") if (Field %in% c("ID","DE")){ listTerms <- strsplit(TERMS$text,";") TERMS$text <- unlist(lapply(listTerms, function(l){ l <- tolower(paste(gsub(" ","_",trimES(trimws(l))), sep="", collapse=";")) })) } else { TERMS <- TERMS %>% mutate(text = tolower(gsub("[^[:alnum:][:blank:]\\-]", "", .data$text)), text = gsub("-", "_",.data$text)) } if (remove.numbers==TRUE){ TERMS <- TERMS %>% mutate(text = gsub("[[:digit:]]","",.data$text)) } if (length(keep.terms)>0 & class(keep.terms)=="character"){ keep.terms <- tolower(keep.terms) if (Field %in% c("DE","ID")){ kt <- gsub(" |-","_",keep.terms) } else { kt <- gsub("-","_",keep.terms) } for (i in 1:length(keep.terms)){ TERMS <- TERMS %>% mutate(text = gsub(keep.terms[i],kt[i],.data$text)) } } if (Field %in% c("ID","DE")){ TERMS <- TERMS %>% mutate(text = gsub("_|-", " ", .data$text)) } if (is.null(remove.terms)) remove.terms <- "" TERMS <- extractNgrams(text=TERMS, Var="text", nword=ngrams, stopwords=stopwords, custom_stopwords=tolower(remove.terms), stemming=stemming, language=language, synonyms = synonyms) TERMS <- TERMS %>% dplyr::filter(!(.data$ngram %in% paste(rep("NA",ngrams),sep="",collapse=" "))) %>% group_by(.data$SR) %>% summarize(text = paste(.data$ngram, collapse=";")) if (Field %in% c("ID","DE")){ TERMS <- TERMS %>% mutate(text = gsub("_", " ", .data$text)) } col_name <- paste(Field,"_TM",sep="") M <- M[!names(M) %in% col_name] M <- TERMS %>% right_join(M, by = "SR") names(M)[which(names(M) %in% "text")] <- col_name if (verbose==TRUE){ s <- tableTag(M,col_name) if (length(s>25)){print(s[1:25])}else{print(s)} } class(M) <- c("bibliometrixDB", "data.frame") row.names(M) <- M$SR return(M) } extractNgrams <- function(text, Var, nword, stopwords, custom_stopwords, stemming, language, synonyms){ stopwords <- c(stopwords,"elsevier", "springer", "wiley", "mdpi", "emerald") custom_stopngrams <- c(custom_stopwords,"rights reserved", "john wiley", "john wiley sons", "science bv", "mdpi basel", "mdpi licensee", "emerald publishing", "taylor francis", "paper proposes", "we proposes", "paper aims", "articles published", "study aims") ngram <- NULL ngrams <- text %>% drop_na(any_of(Var)) %>% unnest_tokens(ngram, !!Var, token = "ngrams", n = nword) %>% separate(.data$ngram, paste("word",1:nword,sep=""), sep = " ") %>% dplyr::filter(if_all(starts_with("word"), ~ !.x %in% stopwords)) if (isTRUE(stemming)){ ngrams <- ngrams %>% mutate(across(paste("word",1:nword,sep=""), ~SnowballC::wordStem(.x,language=language))) } ngrams <- ngrams %>% unite(ngram, paste("word",1:nword,sep=""), sep = " ") %>% dplyr::filter(!.data$ngram %in% custom_stopngrams) %>% mutate(ngram = toupper(.data$ngram)) if (length(synonyms)>0 & class(synonyms)=="character"){ s <- strsplit(toupper(synonyms),";") snew <- trimws(unlist(lapply(s,function(l) l[1]))) sold <- (lapply(s,function(l) trimws(l[-1]))) for (i in 1:length(s)){ ngrams <- ngrams %>% mutate( ngram = str_replace_all(.data$ngram, paste(sold[[i]], collapse="|",sep=""),snew[i]) ) } } return(ngrams) }
bestset.noise <- function (m = 100, n = 40, method = "exhaustive", nvmax = 3, X = NULL, y=NULL, intercept=TRUE, print.summary = TRUE, really.big = FALSE, ...) { leaps.out <- try(requireNamespace("leaps", quietly=TRUE), silent = TRUE) if ((is.logical(leaps.out) == TRUE) & (leaps.out == TRUE)) { if (is.null(X)) { X <- matrix(rnorm(m * n), ncol = n) colnames(X) <- paste("V", 1:n, sep = "") } else { if(is.data.frame(X)){ if(intercept) X <- model.matrix(~., data=X)[,-1] else X <- model.matrix(~-1+., data=X) } m <- dim(X)[1] n <- dim(X)[2] } if (is.null(colnames(X))) colnames(X) <- paste("V", 1:n, sep = "") if(is.null(y))y <- rnorm(m) u <- leaps::regsubsets(X, y, method = method, nvmax = nvmax, nbest = 1, intercept=intercept, really.big = really.big, ...) if(is.null(intercept))intercept <- TRUE if(intercept){ x <- X[, summary(u)$which[nvmax, -1]] u1 <- lm(y ~ x)} else { x <- X[, summary(u)$which[nvmax, ]] u1 <- lm(y ~ -1+x)} if (print.summary) print(summary(u1, corr = FALSE)) invisible(list(best=u1, regsubsets_obj=u)) } else { print("Error: package leaps is not installed properly") } }
rand_profile <- function(df, grouping = "pop", population = NULL, n = FALSE, keep_pop = FALSE){ meta <- NULL pop <- NULL x0 <- NULL X0 <- NULL x1 <- NULL locus <- NULL p <- NULL p0 <- NULL p1 <- NULL p2 <- NULL . <- NULL stopifnot(length(population) <= 1) grouping <- match.arg(grouping, c("pop", "meta")) grouping_ <- quo(!!sym(grouping)) df <- df %>% select(starts_with(grouping)) %>% distinct(!!grouping_, .keep_all = TRUE) %>% unnest(cols = ends_with("data")) %>% ungroup() if(grouping == "meta") df <- df %>% rename(pop = meta) if(!is.null(population)){ if(any(population %in% df$pop)) df <- filter_(df, .dots = paste0("pop == '", population,"'")) else cat(paste0("Population: '",population,"' is not in database with grouping '",grouping,"'")) } else{ pops_n <- df %>% select(pop, n) %>% distinct() if(!n) pops_n <- mutate(pops_n, n = 1) pops_n <- pops_n %>% sample_n(size = 1, replace = FALSE, weight = n) %>% select(pop) df <- right_join(df, pops_n, by = "pop") } x0_profile <- df %>% filter(x0 == 0, X0 == 0) %>% mutate(p = x1/n) %>% select(pop, locus, p) %>% mutate(x0 = rbinom(n = nrow(.), size = 2, prob = p)) %>% select(pop, locus, x0) df <- inner_join(df, x0_profile, by = c("pop", "locus", "x0")) x0_x_profile <- df %>% filter(X0 == 0) %>% bind_cols(dist_x0_cond_x_(n = .$n, x = .$x0 + .$x1)) %>% rowwise() %>% mutate(X0 = sample(0:2, size = 1, prob = c(p0, p1, p2))) %>% select(pop, locus, x0, X0) %>% ungroup() if(keep_pop) return(x0_x_profile) x0_x_profile %>% select(-pop) } random_AIMs_profile <- function(df, grouping = "pop", population = NULL, n = FALSE, keep_pop = FALSE){ rand_profile(df = df, grouping = grouping, population = population, n = n, keep_pop = keep_pop) }
globalVariables('priors') GQD.mcmc <- function(X,time,mesh=10,theta,sds,updates,burns=min(round(updates/2),25000),Dtype='Saddle',Trunc=c(4,4),RK.order=4,P=200,alpha=0,lower=min(na.omit(X))/2,upper=max(na.omit(X))*2,exclude=NULL,plot.chain=TRUE,Tag=NA,wrt=FALSE,print.output=TRUE,palette='mono') { solver =function(Xs, Xt, theta, N , delt , N2, tt , P , alpha, lower , upper, tro ){} rm(list =c('solver')) theta = theta+runif(length(theta),0.01,0.02)*sign(theta) adapt=0 check_for_model=function() { txt='' namess=c('G0','G1','G2','Q0','Q1','Q2') func.list=rep(0,length(namess)) obs=objects(pos=1) for(i in 1:length(namess)) { if(sum(obs==namess[i])){func.list[i]=1} } check=F if(sum(func.list)==0) { txt=' -------------------------------------------------------------------------------- No model has been defined yet! Try for example: -------------------------------------------------------------------------------- GQD.remove() G0=function(t){theta[1]*theta[2]} G1=function(t){-theta[1]} Q1=function(t){theta[3]*theta[3]} model=GQD.mcmc(X,time,10,theta =rep(1,3),sds=rep(0.1,3),updates=10000) -------------------------------------------------------------------------------- ' check=T } if((sum(func.list)>0)&&(sum(func.list[-c(1:3)])==0)) { txt=' -------------------------------------------------------------------------------- At least one diffusion coefficient has to be defined! Try for example: -------------------------------------------------------------------------------- GQD.remove() G0=function(t){theta[1]*theta[1]} model=GQD.mcmc(X,time,10,theta =c(0.1),sds=0.1,updates=10000) -------------------------------------------------------------------------------- ' check=T } return(list(check=check,txt=txt)) } check_for=check_for_model() if(check_for[[1]]){stop(check_for[[2]])} theta = theta+runif(length(theta),0.001,0.002)*sign(theta) pow=function(x,p) { x^p } prod=function(a,b){a*b} T.seq=time TR.order=Trunc[1] DTR.order=Trunc[2] Dtypes =c('Saddle','Normal','Gamma','InvGamma','Beta') Dindex = which(Dtypes==Dtype) IntRange = c(lower,upper) IntDelta =1/100 Xtr = min(IntRange) b1 = '\n==============================================================================\n' b2 = '==============================================================================\n' warn=c( '1. Missing input: Argument {X} is missing.\n' ,'2. Missing input: Argument {time} is missing.\n' ,'3. Missing input: Argument {theta} is missing.\n' ,'4. Missing input: Argument {sds} is missing.\n' ,'5. Input type: Argument {X} must be of type vector!.\n' ,'6. Input type: Argument {time} must be of type vector!.\n' ,'7. Input: Less starting parameters than model parameters.\n' ,'8. Input: More starting parameters than model parameters.\n' ,'9. Input: length(X) must be > 10.\n' ,'10. Input: length(time) must be > 10.\n' ,'11. Input: length(lower)!=1.\n' ,'12. Input: length(upper)!=1.\n' ,'13. Input: length(P)!=1.\n' ,'14. Input: length(mesh)!=1.\n' ,'15. Input: length(alpha)!=1.\n' ,'16. Input: length(Trunc)!=1.\n' ,'17. Input: length(RK.order)!=1.\n' ,'18. Density: Dtype has to be one of Saddle, Normal, Gamma, InvGamma or Beta.\n' ,'19. Density: Range [lower,upper] must be strictly positive for Dtype Gamma or InvGamma.\n' ,'20. Density: Dtype cannot be Beta for observations not in (0,1).\n' ,'21. Density: Argument {upper} must be > {lower}.\n' ,'22. Density: P must be >= 10.\n' ,'23. Density: Trunc[2] must be <= Trunc[1].\n' ,'24. ODEs : Large max(diff(time))/mesh may result in poor approximations. Try larger mesh.\n' ,'25. ODEs : max(diff(time))/mesh must be <1.\n' ,'26. ODEs : Runge Kutta scheme must be of order 4 or 10.\n' ,'27. ODEs : Argument {mesh} must be >= 5.\n' ,'28. Input: length(X)!=length(time).\n' ,'29. MCMC : Argument {burns} must be < {updates}.\n' ,'30. MCMC : Argument {updates} must be > 2.\n' ,'31. MCMC : length(theta)!=length(sds).\n' ,'32. Model: There has to be at least one model coefficient.\n' ,'33. Input: length(updates)!=1.\n' ,'34. Input: length(burns)!=1.\n' ,'35. Prior: priors(theta) must return a single value.\n' ,'36. Input: NAs not allowed.\n' ,'37. Input: length(Dtype)!=1.\n' ,'38. Input: NAs not allowed.\n' ,'39. Input: Time series contains values of small magnitude.\n This may result in numerical instabilities.\n It may be advisable to scale the data by a constant factor.\n' ) warntrue = rep(F,40) check.thetas = function(theta,tt) { t=tt theta = theta+runif(length(theta),0.001,0.002)*sign(theta) namess=c('G0','G1','G2','Q0','Q1','Q2') func.list=rep(0,length(namess)) obs=objects(pos=1) for(i in 1:length(namess)) { if(sum(obs==namess[i])){func.list[i]=1} } pers.represented = rep(0,length(theta)) for(i in which(func.list==1)) { for(j in 1:length(theta)) { dresult1=eval(body(namess[i])) theta[j] = theta[j]+runif(1,0.1,0.2) dresult2=eval(body(namess[i])) dff = abs(dresult1-dresult2) if(any(round(dff,6)!=0)){pers.represented[j]=pers.represented[j]+1} } } return(pers.represented) } check.thetas2 = function(theta) { namess=c('G0','G1','G2','Q0','Q1','Q2') func.list=rep(0,length(namess)) obs=objects(pos=1) for(i in 1:length(namess)) { if(sum(obs==namess[i])){func.list[i]=1} } l=0 for(k in which(func.list==1)) { str=body(namess[k])[2] for(i in 1:length(theta)) { for(j in 1:20) { str=sub(paste0('theta\\[',i,'\\]'),'clear',str) } } l=l+length(grep('theta',str)) l } return(l) } if(missing(X)) {warntrue[1]=T} if(missing(time)) {warntrue[2]=T} if(missing(theta)) {warntrue[3]=T} if(missing(sds)) {warntrue[4]=T} if(!is.vector(X)) {warntrue[5]=T} if(!is.vector(time)) {warntrue[6]=T} if(check.thetas2(theta)!=0) {warntrue[7]=T} if(!warntrue[7]){if(any(check.thetas(theta,T.seq)==0)) {warntrue[8]=T}} if(length(X)<10) {warntrue[9]=T} if(length(time)<10) {warntrue[10]=T} if(length(lower)>1) {warntrue[11]=T} if(length(upper)>1) {warntrue[12]=T} if(length(P)!=1) {warntrue[13]=T} if(length(mesh)!=1) {warntrue[14]=T} if(length(alpha)!=1) {warntrue[15]=T} if(length(Trunc)!=2) {warntrue[16]=T} if(length(RK.order)!=1) {warntrue[17]=T} if(length(updates)!=1) {warntrue[33]=T} if(length(burns)!=1) {warntrue[34]=T} if(length(Dtype)!=1) {warntrue[37]=T} if(sum(Dindex)==0) {warntrue[18] =T} if(!warntrue[18]) { if((Dindex==3)|(Dindex==4)){if(lower[1]<=0) {warntrue[19] =T}} if(Dindex==5){if(any(X<=0)|any(X>=1)) {warntrue[20] =T}} } if(!any(warntrue[c(11,12)])){if(upper<=lower) {warntrue[21] =T}} if(!warntrue[13]){if(P<10) {warntrue[22] =T}} if(!warntrue[16]){if(Trunc[2]>Trunc[1]) {warntrue[23] =T}} excl=0 if(is.null(exclude)){excl=length(T.seq)-1+200} if(!is.null(exclude)){excl=exclude} test.this =max(diff(T.seq)[-excl])/mesh if(test.this>0.1) {warntrue[24]=T} if(test.this>=1) {warntrue[25]=T} if(!warntrue[17]){if(!((RK.order==4)|(RK.order==10))) {warntrue[26]=T}} if(!warntrue[14]){if(mesh<5) {warntrue[27]=T}} if(length(X)!=length(time)) {warntrue[28]=T} if(!any(warntrue[c(33,34)])){if(burns>updates) {warntrue[29]=T}} if(!warntrue[33]){if(updates<2) {warntrue[30]=T}} if(length(theta)!=length(sds)) {warntrue[31]=T} if(any(is.na(X))||any(is.na(time))) {warntrue[36]=T} if(any(warntrue)) { prnt = b1 for(i in which(warntrue)) { prnt = paste0(prnt,warn[i]) } prnt = paste0(prnt,b2) stop(prnt) } if(any(X<10^-2)){warntrue[39]=T} if(any(warntrue)) { prnt = b1 for(i in which(warntrue)) { prnt = paste0(prnt,warn[i]) } prnt = paste0(prnt,b2) warning(prnt) } nnn=length(X) homo=T homo.res=T delt=(diff(T.seq)/mesh)[1] t=T.seq if(is.null(exclude)) { if(sum(round(diff(T.seq)-diff(T.seq)[1],10)==0)!=length(T.seq)-1){homo.res=F} } if(!is.null(exclude)) { if(sum(round(diff(T.seq)[-excl]-c(diff(T.seq)[-excl])[1],10)==0)!=length(T.seq)-1-length(excl)){homo.res=F} } if(sum(objects(pos=1)=='priors')==1) { pp=function(theta){} body(pp)=parse(text =body(priors)[2]) prior.list=paste0('d(theta)',':',paste0(body(priors)[2])) if(length(priors(theta))!=1){stop(" ============================================================================== Incorrect input: Prior distribution must return a single value only! ==============================================================================");} } if(sum(objects(pos=1)=='priors')==0) { prior.list=paste0('d(theta)',':',' None.') pp=function(theta){1} } namess=c('G0','G1','G2','Q0','Q1','Q2') func.list=rep(0,6) obs=objects(pos=1) for(i in 1:6) { if(sum(obs==namess[i])){func.list[i]=1} } state1=(sum(func.list[c(3,5,6)]==1)==0) if(state1){DTR.order=2;TR.order=2;sol.state='Normally distributed diffusion.';} if((state1&(Dtype!='Saddle'))){TR.order=2;DTR.order=2;sol.state='2nd Ord. Truncation + Std Normal Dist.';} state2=!state1 if(state2) { state2.types=c('Saddlepoint Appr. ', ' Ext. Normal Appr. ', ' Ext. Gamma Appr. ', ' Ext. Inv. Gamma Appr.') sol.state=paste0(TR.order,' Ord. Truncation +',DTR.order,'th Ord. ',state2.types[Dindex]) } if(TR.order==2) { fpart= ' using namespace arma; using namespace Rcpp; using namespace R; // [[Rcpp::depends("RcppArmadillo")]] // [[Rcpp::export]] vec prod(vec a,vec b) { return(a%b); } mat f(mat a,vec theta,vec t,int N2) { mat atemp(N2,2);' } if(TR.order==4) { fpart= ' using namespace arma; using namespace Rcpp; using namespace R; // [[Rcpp::depends("RcppArmadillo")]] // [[Rcpp::export]] vec prod(vec a,vec b) { return(a%b); } mat f(mat a,vec theta,vec t,int N2) { mat atemp(N2,4);' } if(TR.order==6) { fpart= ' using namespace arma; using namespace Rcpp; using namespace R; // [[Rcpp::depends("RcppArmadillo")]] // [[Rcpp::export]] vec prod(vec a,vec b) { return(a%b); } mat f(mat a,vec theta,vec t,int N2) { mat atemp(N2,6);' } if(TR.order==8) { fpart= ' using namespace arma; using namespace Rcpp; using namespace R; // [[Rcpp::depends("RcppArmadillo")]] // [[Rcpp::export]] vec prod(vec a,vec b) { return(a%b); } mat f(mat a,vec theta,vec t,int N2) { mat atemp(N2,8);' } if(RK.order==10) { if(homo.res) { ODEpart= ' return atemp; } // [[Rcpp::export]] List solver(vec Xs,vec Xt,vec theta,int N,double delt,int N2,vec tt,int P,double alpha,double lower,double upper,int tro) { mat x0(N2,tro); mat xa(N2,tro); mat xe(N2,tro); mat fx0(N2,tro); mat fx1(N2,tro); mat fx2(N2,tro); mat fx3(N2,tro); mat fx4(N2,tro); mat fx5(N2,tro); mat fx6(N2,tro); mat fx7(N2,tro); mat fx8(N2,tro); mat fx9(N2,tro); mat fx10(N2,tro); mat fx11(N2,tro); mat fx12(N2,tro); mat fx13(N2,tro); mat fx14(N2,tro); mat fx15(N2,tro); mat fx16(N2,tro); double whch =0; x0.fill(0); x0.col(0)=Xs; vec d=tt; for (int i = 1; i < N+1; i++) { fx0=f(x0,theta,d,N2)*delt; fx1=f(x0+0.1*fx0,theta,d+0.100000000000000000000000000000000000000000000000000000000000*delt,N2)*delt; fx2=f(x0+-0.915176561375291*fx0+1.45453440217827*fx1,theta,d+0.539357840802981787532485197881302436857273449701009015505500*delt,N2)*delt; fx3=f(x0+0.202259190301118*fx0+0.606777570903354*fx2,theta,d+0.809036761204472681298727796821953655285910174551513523258250*delt,N2)*delt; fx4=f(x0+0.184024714708644*fx0+0.197966831227192*fx2-0.0729547847313633*fx3,theta,d+0.309036761204472681298727796821953655285910174551513523258250*delt,N2)*delt; fx5=f(x0+0.0879007340206681*fx0+0.410459702520261*fx3+0.482713753678866*fx4,theta,d+0.981074190219795268254879548310562080489056746118724882027805*delt,N2)*delt; fx6=f(x0+0.085970050490246*fx0+0.330885963040722*fx3+0.48966295730945*fx4-0.0731856375070851*fx5,theta,d+0.833333333333333333333333333333333333333333333333333333333333*delt,N2)*delt; fx7=f(x0+0.120930449125334*fx0+0.260124675758296*fx4+0.0325402621549091*fx5-0.0595780211817361*fx6,theta,d+0.354017365856802376329264185948796742115824053807373968324184*delt,N2)*delt; fx8=f(x0+0.110854379580391*fx0-0.0605761488255006*fx5+0.321763705601778*fx6+0.510485725608063*fx7,theta,d+0.882527661964732346425501486979669075182867844268052119663791*delt,N2)*delt; fx9=f(x0+0.112054414752879*fx0-0.144942775902866*fx5-0.333269719096257*fx6+0.49926922955688*fx7+0.509504608929686*fx8,theta,d+0.642615758240322548157075497020439535959501736363212695909875*delt,N2)*delt; fx10=f(x0+0.113976783964186*fx0-0.0768813364203357*fx5+0.239527360324391*fx6+0.397774662368095*fx7+0.0107558956873607*fx8-0.327769124164019*fx9,theta,d+0.357384241759677451842924502979560464040498263636787304090125*delt,N2)*delt; fx11=f(x0+0.0798314528280196*fx0-0.0520329686800603*fx5-0.0576954146168549*fx6+0.194781915712104*fx7+0.145384923188325*fx8-0.0782942710351671*fx9-0.114503299361099*fx10,theta,d+0.117472338035267653574498513020330924817132155731947880336209*delt,N2)*delt; fx12=f(x0+0.985115610164857*fx0+0.330885963040722*fx3+0.48966295730945*fx4-1.37896486574844*fx5-0.861164195027636*fx6+5.78428813637537*fx7+3.28807761985104*fx8-2.38633905093136*fx9-3.25479342483644*fx10-2.16343541686423*fx11,theta,d+0.833333333333333333333333333333333333333333333333333333333333*delt,N2)*delt; fx13=f(x0+0.895080295771633*fx0+0.197966831227192*fx2-0.0729547847313633*fx3-0.851236239662008*fx5+0.398320112318533*fx6+3.63937263181036*fx7+1.5482287703983*fx8-2.12221714704054*fx9-1.58350398545326*fx10-1.71561608285936*fx11-0.0244036405750127*fx12,theta,d+0.309036761204472681298727796821953655285910174551513523258250*delt,N2)*delt; fx14=f(x0+-0.915176561375291*fx0+1.45453440217827*fx1+0*fx2+0*fx3-0.777333643644968*fx4+0*fx5-0.0910895662155176*fx6+0.0910895662155176*fx12+0.777333643644968*fx13,theta,d+0.539357840802981787532485197881302436857273449701009015505500*delt,N2)*delt; fx15=f(x0+0.1*fx0-0.157178665799771*fx2+0.157178665799771*fx14,theta,d+0.100000000000000000000000000000000000000000000000000000000000*delt,N2)*delt; fx16=f(x0+0.181781300700095*fx0+0.675*fx1+0.34275815984719*fx2+0*fx3+0.259111214548323*fx4-0.358278966717952*fx5-1.04594895940883*fx6+0.930327845415627*fx7+1.77950959431708*fx8+0.1*fx9-0.282547569539044*fx10-0.159327350119973*fx11-0.145515894647002*fx12-0.259111214548323*fx13-0.34275815984719*fx14-0.675*fx15,theta,d+delt,N2)*delt; x0=x0+(0.0333333333333333333333333333333333333333333333333333333333333*fx0 +0.0250000000000000000000000000000000000000000000000000000000000*fx1 +0.0333333333333333333333333333333333333333333333333333333333333*fx2 +0.000000000000000000000000000000000000000000000000000000000000*fx3 +0.0500000000000000000000000000000000000000000000000000000000000*fx4 +0.000000000000000000000000000000000000000000000000000000000000*fx5 +0.0400000000000000000000000000000000000000000000000000000000000*fx6 +0.000000000000000000000000000000000000000000000000000000000000*fx7 +0.189237478148923490158306404106012326238162346948625830327194*fx8 +0.277429188517743176508360262560654340428504319718040836339472*fx9 +0.277429188517743176508360262560654340428504319718040836339472*fx10 +0.189237478148923490158306404106012326238162346948625830327194*fx11 -0.0400000000000000000000000000000000000000000000000000000000000*fx12 -0.0500000000000000000000000000000000000000000000000000000000000*fx13 -0.0333333333333333333333333333333333333333333333333333333333333*fx14 -0.0250000000000000000000000000000000000000000000000000000000000*fx15 +0.0333333333333333333333333333333333333333333333333333333333333*fx16); xe = abs(fx1.col(1)-fx15.col(1))/360.0; if(xe.max()>whch) { whch = xe.max(); } d=d+delt; } ' } if(!homo.res) { ODEpart= ' return atemp; } // [[Rcpp::export]] List solver(vec Xs,vec Xt,vec theta,int N,double delt,int N2,vec tt,int P,double alpha,double lower,double upper,int tro) { mat x0(N2,tro); mat xa(N2,tro); mat xe(N2,tro); mat fx0(N2,tro); mat fx1(N2,tro); mat fx2(N2,tro); mat fx3(N2,tro); mat fx4(N2,tro); mat fx5(N2,tro); mat fx6(N2,tro); mat fx7(N2,tro); mat fx8(N2,tro); mat fx9(N2,tro); mat fx10(N2,tro); mat fx11(N2,tro); mat fx12(N2,tro); mat fx13(N2,tro); mat fx14(N2,tro); mat fx15(N2,tro); mat fx16(N2,tro); double whch =0; x0.fill(0); x0.col(0)=Xs; vec d=tt; for (int i = 1; i < N+1; i++) { fx0=f(x0,theta,d,N2)%delt; fx1=f(x0+0.1*fx0,theta,d+0.100000000000000000000000000000000000000000000000000000000000*delt.col(0),N2)%delt; fx2=f(x0+-0.915176561375291*fx0+1.45453440217827*fx1,theta,d+0.539357840802981787532485197881302436857273449701009015505500*delt.col(0),N2)%delt; fx3=f(x0+0.202259190301118*fx0+0.606777570903354*fx2,theta,d+0.809036761204472681298727796821953655285910174551513523258250*delt.col(0),N2)%delt; fx4=f(x0+0.184024714708644*fx0+0.197966831227192*fx2-0.0729547847313633*fx3,theta,d+0.309036761204472681298727796821953655285910174551513523258250*delt.col(0),N2)%delt; fx5=f(x0+0.0879007340206681*fx0+0.410459702520261*fx3+0.482713753678866*fx4,theta,d+0.981074190219795268254879548310562080489056746118724882027805*delt.col(0),N2)%delt; fx6=f(x0+0.085970050490246*fx0+0.330885963040722*fx3+0.48966295730945*fx4-0.0731856375070851*fx5,theta,d+0.833333333333333333333333333333333333333333333333333333333333*delt.col(0),N2)%delt; fx7=f(x0+0.120930449125334*fx0+0.260124675758296*fx4+0.0325402621549091*fx5-0.0595780211817361*fx6,theta,d+0.354017365856802376329264185948796742115824053807373968324184*delt.col(0),N2)%delt; fx8=f(x0+0.110854379580391*fx0-0.0605761488255006*fx5+0.321763705601778*fx6+0.510485725608063*fx7,theta,d+0.882527661964732346425501486979669075182867844268052119663791*delt.col(0),N2)%delt; fx9=f(x0+0.112054414752879*fx0-0.144942775902866*fx5-0.333269719096257*fx6+0.49926922955688*fx7+0.509504608929686*fx8,theta,d+0.642615758240322548157075497020439535959501736363212695909875*delt.col(0),N2)%delt; fx10=f(x0+0.113976783964186*fx0-0.0768813364203357*fx5+0.239527360324391*fx6+0.397774662368095*fx7+0.0107558956873607*fx8-0.327769124164019*fx9,theta,d+0.357384241759677451842924502979560464040498263636787304090125*delt.col(0),N2)%delt; fx11=f(x0+0.0798314528280196*fx0-0.0520329686800603*fx5-0.0576954146168549*fx6+0.194781915712104*fx7+0.145384923188325*fx8-0.0782942710351671*fx9-0.114503299361099*fx10,theta,d+0.117472338035267653574498513020330924817132155731947880336209*delt.col(0),N2)%delt; fx12=f(x0+0.985115610164857*fx0+0.330885963040722*fx3+0.48966295730945*fx4-1.37896486574844*fx5-0.861164195027636*fx6+5.78428813637537*fx7+3.28807761985104*fx8-2.38633905093136*fx9-3.25479342483644*fx10-2.16343541686423*fx11,theta,d+0.833333333333333333333333333333333333333333333333333333333333*delt.col(0),N2)%delt; fx13=f(x0+0.895080295771633*fx0+0.197966831227192*fx2-0.0729547847313633*fx3-0.851236239662008*fx5+0.398320112318533*fx6+3.63937263181036*fx7+1.5482287703983*fx8-2.12221714704054*fx9-1.58350398545326*fx10-1.71561608285936*fx11-0.0244036405750127*fx12,theta,d+0.309036761204472681298727796821953655285910174551513523258250*delt.col(0),N2)%delt; fx14=f(x0+-0.915176561375291*fx0+1.45453440217827*fx1+0*fx2+0*fx3-0.777333643644968*fx4+0*fx5-0.0910895662155176*fx6+0.0910895662155176*fx12+0.777333643644968*fx13,theta,d+0.539357840802981787532485197881302436857273449701009015505500*delt.col(0),N2)%delt; fx15=f(x0+0.1*fx0-0.157178665799771*fx2+0.157178665799771*fx14,theta,d+0.100000000000000000000000000000000000000000000000000000000000*delt.col(0),N2)%delt; fx16=f(x0+0.181781300700095*fx0+0.675*fx1+0.34275815984719*fx2+0*fx3+0.259111214548323*fx4-0.358278966717952*fx5-1.04594895940883*fx6+0.930327845415627*fx7+1.77950959431708*fx8+0.1*fx9-0.282547569539044*fx10-0.159327350119973*fx11-0.145515894647002*fx12-0.259111214548323*fx13-0.34275815984719*fx14-0.675*fx15,theta,d+delt.col(0),N2)%delt; x0=x0+(0.0333333333333333333333333333333333333333333333333333333333333*fx0 +0.0250000000000000000000000000000000000000000000000000000000000*fx1 +0.0333333333333333333333333333333333333333333333333333333333333*fx2 +0.000000000000000000000000000000000000000000000000000000000000*fx3 +0.0500000000000000000000000000000000000000000000000000000000000*fx4 +0.000000000000000000000000000000000000000000000000000000000000*fx5 +0.0400000000000000000000000000000000000000000000000000000000000*fx6 +0.000000000000000000000000000000000000000000000000000000000000*fx7 +0.189237478148923490158306404106012326238162346948625830327194*fx8 +0.277429188517743176508360262560654340428504319718040836339472*fx9 +0.277429188517743176508360262560654340428504319718040836339472*fx10 +0.189237478148923490158306404106012326238162346948625830327194*fx11 -0.0400000000000000000000000000000000000000000000000000000000000*fx12 -0.0500000000000000000000000000000000000000000000000000000000000*fx13 -0.0333333333333333333333333333333333333333333333333333333333333*fx14 -0.0250000000000000000000000000000000000000000000000000000000000*fx15 +0.0333333333333333333333333333333333333333333333333333333333333*fx16); xe = abs(fx1.col(1)-fx15.col(1))/360.0; if(xe.max()>whch) { whch = xe.max(); } d=d+delt.col(0); } ' } } if(RK.order==4) { if(homo.res) { ODEpart= ' return atemp; } // [[Rcpp::export]] List solver(vec Xs,vec Xt,vec theta,int N,double delt,int N2,vec tt,int P,double alpha,double lower,double upper,int tro) { mat x0(N2,tro); mat xa(N2,tro); mat xe(N2,tro); mat fx1(N2,tro); mat fx2(N2,tro); mat fx3(N2,tro); mat fx4(N2,tro); mat fx5(N2,tro); mat fx6(N2,tro); double whch =0; x0.fill(0); x0.col(0)=Xs; vec d=tt; for (int i = 1; i < N+1; i++) { fx1 = f(x0,theta,d,N2)*delt; fx2 = f(x0+0.25*fx1,theta,d+0.25*delt,N2)*delt; fx3 = f(x0+0.09375*fx1+0.28125*fx2,theta,d+0.375*delt,N2)*delt; fx4 = f(x0+0.879381*fx1-3.277196*fx2+ 3.320892*fx3,theta,d+0.9230769*delt,N2)*delt; fx5 = f(x0+2.032407*fx1-8*fx2+7.173489*fx3-0.2058967*fx4,theta,d+delt,N2)*delt; fx6 = f(x0-0.2962963*fx1+2*fx2-1.381676*fx3+0.4529727*fx4-0.275*fx5,theta,d+0.5*delt,N2)*delt; xa = x0+0.1185185*fx1+0.5189864*fx3+0.5061315*fx4-0.18*fx5+0.03636364*fx6; x0 = x0+0.1157407*fx1+0.5489279*fx3+0.5353314*fx4-0.2*fx5; xe = abs(x0.col(1)-xa.col(1)); if(xe.max()>whch) { whch = xe.max(); } d=d+delt; } ' } if(!homo.res) { ODEpart= ' return atemp; } // [[Rcpp::export]] List solver(vec Xs,vec Xt,vec theta,int N, mat delt,int N2,vec tt,int P,double alpha,double lower,double upper,int tro) { mat x0(N2,tro); mat xa(N2,tro); mat xe(N2,tro); mat fx1(N2,tro); mat fx2(N2,tro); mat fx3(N2,tro); mat fx4(N2,tro); mat fx5(N2,tro); mat fx6(N2,tro); double whch =0; vec d=tt; x0.fill(0); x0.col(0)=Xs; for (int i = 1; i < N+1; i++) { fx1 = f(x0,theta,d,N2)%delt; fx2 = f(x0+0.25*fx1,theta,d+0.25*delt.col(0),N2)%delt; fx3 = f(x0+0.09375*fx1+0.28125*fx2,theta,d+0.375*delt.col(0),N2)%delt; fx4 = f(x0+0.879381*fx1-3.277196*fx2+ 3.320892*fx3,theta,d+0.9230769*delt.col(0),N2)%delt; fx5 = f(x0+2.032407*fx1-8*fx2+7.173489*fx3-0.2058967*fx4,theta,d+delt.col(0),N2)%delt; fx6 = f(x0-0.2962963*fx1+2*fx2-1.381676*fx3+0.4529727*fx4-0.275*fx5,theta,d+0.5*delt.col(0),N2)%delt; xa = x0+0.1185185*fx1+0.5189864*fx3+0.5061315*fx4-0.18*fx5+0.03636364*fx6; x0 = x0+0.1157407*fx1+0.5489279*fx3+0.5353314*fx4-0.2*fx5; xe = abs(x0.col(1)-xa.col(1)); if(xe.max()>whch) { whch = xe.max(); } d=d+delt.col(0); } ' } } if(DTR.order==2) { Inv= ' mat u(N2,2); u.col(0)=x0.col(0); u.col(1)=x0.col(1)+x0.col(0)%u.col(0); vec det=u.col(1)-u.col(0)%u.col(0); vec b11=(u.col(1))/det; vec b12=-u.col(0)/det; vec b21=-u.col(0)/det; vec b22=(1.0)/det; ' switch(Dindex, { Dpart=' vec val = -0.5*log(2*3.141592653589793)-0.5*log(x0.col(1))-0.5*((Xt-x0.col(0))%(Xt-x0.col(0))/x0.col(1)); List ret; ret["like"] = val; ret["max"] = whch; return(ret); } ' }) } if(DTR.order==4) { Inv= ' mat u(N2,4); u.col(0)=x0.col(0); u.col(1)=x0.col(1)+x0.col(0)%u.col(0); u.col(2)=x0.col(2)+x0.col(0)%u.col(1)+2*x0.col(1)%u.col(0); u.col(3)=x0.col(3)+x0.col(0)%u.col(2)+3*x0.col(1)%u.col(1)+3*x0.col(2)%u.col(0); vec det=u.col(1)%u.col(3)+u.col(0)%u.col(2)%u.col(1)+u.col(1)%u.col(0)%u.col(2)-u.col(2)%u.col(2)-u.col(1)%u.col(1)%u.col(1)-u.col(0)%u.col(0)%u.col(3); vec b11=(u.col(1)%u.col(3)-u.col(2)%u.col(2))/det; vec b12=(u.col(1)%u.col(2)-u.col(0)%u.col(3))/det; vec b13=(u.col(0)%u.col(2)-u.col(1)%u.col(1))/det; vec b21=(u.col(2)%u.col(1)-u.col(0)%u.col(3))/det; vec b22=(u.col(3)-u.col(1)%u.col(1))/det; vec b23=(u.col(1)%u.col(0)-u.col(2))/det; vec b31=(u.col(0)%u.col(2)-u.col(1)%u.col(1))/det; vec b32=(u.col(0)%u.col(1)-u.col(2))/det; vec b33=(u.col(1)-u.col(0)%u.col(0))/det; ' switch(Dindex, { Dpart=' vec p=(1.0/3.0) *(3*(x0.col(3)/6.0)%x0.col(1) - pow(x0.col(2)/2.0,2))/pow(x0.col(3)/6.0,2); vec q=(1.0/27.0)*(27*pow(x0.col(3)/6.0,2)%(x0.col(0)-Xt) - 9*(x0.col(3)/6.0)%(x0.col(2)/2.0)%x0.col(1) + 2*pow(x0.col(2)/2.0,3))/pow(x0.col(3)/6.0,3); vec chk=pow(q,2)/4.0 + pow(p,3)/27.0; vec th=-(x0.col(2)/2.0)/(3*(x0.col(3)/6.0))+pow(-q/2.0+sqrt(chk),(1.0/3.0))-pow(q/2.0+sqrt(chk),(1.0/3.0)); vec K =x0.col(0)%th+(x0.col(1)%th%th)/2.0+(x0.col(2)%th%th%th)/6.0 +(x0.col(3)%th%th%th%th)/24.0; vec K1=x0.col(0) +(x0.col(1)%th) +(x0.col(2)%th%th)/2.0 +(x0.col(3)%th%th%th)/6.0; vec K2=x0.col(1) +(x0.col(2)%th) +(x0.col(3)%th%th)/2.0; vec val=-0.5*log(2*3.141592653589793*K2)+(K-th%K1); List ret; ret["like"] = val; ret["max"] = whch; return(ret); } ' }, { Dpart= ' vec betas1 =+b12+2*b13%u.col(0); vec betas2 =+b22+2*b23%u.col(0); vec betas3 =+b32+2*b33%u.col(0); vec K=exp(-betas1*pow(Xtr,1)-0.5*betas2*pow(Xtr,2)-0.333333333333333333*betas3*pow(Xtr,3)); vec lo =-(0.5/(u.col(0)-lower))%(sqrt(exp(2*alpha)+4*pow((u.col(0)-lower),2))-exp(alpha)); vec up =-(0.5/(u.col(0)-upper))%(sqrt(exp(2*alpha)+4*pow((u.col(0)-upper),2))-exp(alpha)); vec DT = (up-lo)/(1.00*P); vec tau = exp(alpha)*lo/(1-pow(lo,2))+u.col(0); vec rho = exp(alpha)*(1+pow(lo,2))/pow((1-pow(lo,2)),2); vec K=exp(-betas1%pow(tau,1)-0.5*betas2%pow(tau,2)-0.333333333333333333*betas3%pow(tau,3))%rho%DT; for (int i = 1; i <= P; i++) { lo=lo+DT; tau = exp(alpha)*lo/(1-pow(lo,2))+u.col(0); rho = exp(alpha)*(1+pow(lo,2))/pow((1-pow(lo,2)),2); K=K+exp(-betas1%pow(tau,1)-0.5*betas2%pow(tau,2)-0.333333333333333333*betas3%pow(tau,3))%rho%DT; } vec val = ((-betas1%pow(Xt,1)-0.5*betas2%pow(Xt,2)-0.333333333333333333*betas3%pow(Xt,3))-log(K)); List ret; ret["like"] = val; ret["max"] = whch; return(ret); } ' }, { Dpart=' vec betas1 =+b11+2*b12%u.col(0)+3*b13%u.col(1); vec betas2 =+b21+2*b22%u.col(0)+3*b23%u.col(1); vec betas3 =+b31+2*b32%u.col(0)+3*b33%u.col(1); vec lo =-(0.5/(u.col(0)-lower))%(sqrt(exp(2*alpha)+4*pow((u.col(0)-lower),2))-exp(alpha)); vec up =-(0.5/(u.col(0)-upper))%(sqrt(exp(2*alpha)+4*pow((u.col(0)-upper),2))-exp(alpha)); vec DT = (up-lo)/(1.00*P); vec tau = exp(alpha)*lo/(1-pow(lo,2))+u.col(0); vec rho = exp(alpha)*(1+pow(lo,2))/pow((1-pow(lo,2)),2); vec K=exp(-betas1%log(tau)+(-betas2%tau-0.5*betas3%pow(tau,2)))%rho%DT; for (int i = 1; i <= P; i++) { lo=lo+DT; tau = exp(alpha)*lo/(1-pow(lo,2))+u.col(0); rho = exp(alpha)*(1+pow(lo,2))/pow((1-pow(lo,2)),2); K=K+exp(-betas1%log(tau)+(-betas2%tau-0.5*betas3%pow(tau,2)))%rho%DT; } vec val =((-betas1%log(Xt)+(-betas2%Xt-0.5*betas3%pow(Xt,2)))-log(K)); List ret; ret["like"] = val; ret["max"] = whch; return(ret); } ' }, { Dpart=' vec betas1 =+2*b11%u.col(0)+3*b12%u.col(1)+4*b13%u.col(2); vec betas2 =+2*b21%u.col(0)+3*b22%u.col(1)+4*b23%u.col(2); vec betas3 =+2*b31%u.col(0)+3*b32%u.col(1)+4*b33%u.col(2); vec lo =-(0.5/(u.col(0)-lower))%(sqrt(exp(2*alpha)+4*pow((u.col(0)-lower),2))-exp(alpha)); vec up =-(0.5/(u.col(0)-upper))%(sqrt(exp(2*alpha)+4*pow((u.col(0)-upper),2))-exp(alpha)); vec DT = (up-lo)/(1.00*P); vec tau = exp(alpha)*lo/(1-pow(lo,2))+u.col(0); vec rho = exp(alpha)*(1+pow(lo,2))/pow((1-pow(lo,2)),2); vec K=exp(-betas2%log(tau)+(betas1/tau-betas3%tau))%rho%DT; for (int i = 1; i <= P; i++) { lo=lo+DT; tau = exp(alpha)*lo/(1-pow(lo,2))+u.col(0); rho = exp(alpha)*(1+pow(lo,2))/pow((1-pow(lo,2)),2); K=K+exp(-betas2%log(tau)+(betas1/tau-betas3%tau))%rho%DT; } vec val((-betas2%log(Xt)+(betas1/Xt-betas3%Xt))-log(K)); List ret; ret["like"] = val; ret["max"] = whch; return(ret); } ' }, { Dpart=' vec betas1 =+b11%(1-2*u.col(0))+b12%(2*u.col(0)-3*u.col(1))+b13%(3*u.col(1)-4*u.col(2)); vec betas2 =+b21%(1-2*u.col(0))+b22%(2*u.col(0)-3*u.col(1))+b23%(3*u.col(1)-4*u.col(2)); vec betas3 =+b31%(1-2*u.col(0))+b32%(2*u.col(0)-3*u.col(1))+b33%(3*u.col(1)-4*u.col(2)); vec lo =-(0.5/(u.col(0)-lower))%(sqrt(exp(2*alpha)+4*pow((u.col(0)-lower),2))-exp(alpha)); vec up =-(0.5/(u.col(0)-upper))%(sqrt(exp(2*alpha)+4*pow((u.col(0)-upper),2))-exp(alpha)); vec DT = (up-lo)/(1.00*P); vec tau = exp(alpha)*lo/(1-pow(lo,2))+u.col(0); vec rho = exp(alpha)*(1+pow(lo,2))/pow((1-pow(lo,2)),2); vec K=exp(-betas2%log(tau)+(betas1/tau-betas3%tau))%rho%DT; for (int i = 1; i <= P; i++) { lo=lo+DT; tau = exp(alpha)*lo/(1-pow(lo,2))+u.col(0); rho = exp(alpha)*(1+pow(lo,2))/pow((1-pow(lo,2)),2); K=K+exp(-betas2%log(tau)+(betas1/tau-betas3%tau))%rho%DT; } vec val = ((-betas2%log(Xt)+(betas1/Xt-betas3%Xt))-log(K)); List ret; ret["like"] = val; ret["max"] = whch; return(ret); }' }) if(Dindex!=1) { Dpart=paste(Inv,Dpart) } } if(DTR.order==6) { Inv= ' vec u1 = x0.col(0); vec u2 = x0.col(1)+x0.col(0)%u1; vec u3 = x0.col(2)+x0.col(0)%u2+2*x0.col(1)%u1; vec u4 = x0.col(3)+x0.col(0)%u3+3*x0.col(1)%u2+3*x0.col(2)%u1 ; vec u5 = x0.col(4)+x0.col(0)%u4+4*x0.col(1)%u3+6*x0.col(2)%u2+4*x0.col(3)%u1 ; vec u6 = x0.col(5)+x0.col(0)%u5+5*x0.col(1)%u4+10*x0.col(2)%u3+10*x0.col(3)%u2+5*x0.col(4)%u1 ; vec det=-u1%(u1%(u4%u6-u5%u5)-u3%(u2%u6-u3%u5)+u4%(u2%u5-u3%u4))+u2%(u1%(u3%u6-u4%u5)-u2%(u2%u6-u3%u5)+u4%(u2%u4-u3%u3))+u2%(u4%u6-u5%u5)-u3%(u3%u6-u4%u5)-u3%(u1%(u3%u5-u4%u4)-u2%(u2%u5-u3%u4)+u3%(u2%u4-u3%u3))+u4%(u3%u5-u4%u4); vec b11 = (u2%(u4%u6-u5%u5)-u3%(u3%u6-u4%u5)+u4%(u3%u5-u4%u4))/det ; vec b12 = (-u1%(u4%u6-u5%u5)+u2%(u3%u6-u4%u5)-u3%(u3%u5-u4%u4))/det ; vec b13 = (u1%(u3%u6-u4%u5)-u2%(u2%u6-u4%u4)+u3%(u2%u5-u3%u4))/det ; vec b14 = (-u1%(u3%u5-u4%u4)+u2%(u2%u5-u3%u4)-u3%(u2%u4-u3%u3))/det ; vec b21 = (-u1%(u4%u6-u5%u5)+u3%(u2%u6-u3%u5)-u4%(u2%u5-u3%u4))/det; vec b22 = (-u2%(u2%u6-u3%u5)+u4%u6-u5%u5+u3%(u2%u5-u3%u4))/det ; vec b23 = (u2%(u1%u6-u3%u4)-u3%u6-u3%(u1%u5-u3%u3)+u4%u5)/det ; vec b24 = (-u2%(u1%u5-u2%u4)+u3%u5-u4%u4+u3%(u1%u4-u2%u3))/det ; vec b31 = (u1%(u3%u6-u4%u5)-u2%(u2%u6-u3%u5)+u4%(u2%u4-u3%u3))/det; vec b32 = (u1%(u2%u6-u3%u5)-u3%u6+u4%u5-u3%(u2%u4-u3%u3))/det ; vec b33 = (-u1%(u1%u6-u3%u4)+u2%u6-u4%u4+u3%(u1%u4-u2%u3))/det; vec b34 = (u1%(u1%u5-u2%u4)-u2%u5+u3%u4-u3%(u1%u3-u2%u2))/det ; vec b41 = (-u1%(u3%u5-u4%u4)+u2%(u2%u5-u3%u4)-u3%(u2%u4-u3%u3))/det; vec b42 = (-u1%(u2%u5-u3%u4)+u3%u5-u4%u4+u2%(u2%u4-u3%u3))/det; vec b43 = (u1%(u1%u5-u3%u3)-u2%u5-u2%(u1%u4-u2%u3)+u3%u4)/det ; vec b44 = (-u1%(u1%u4-u2%u3)+u2%u4-u3%u3+u2%(u1%u3-u2%u2))/det ; ' switch(Dindex, { Dpart=' vec p=(1.0/3.0) *(3*(x0.col(3)/6.0)%x0.col(1) - pow(x0.col(2)/2.0,2))/pow(x0.col(3)/6.0,2); vec q=(1.0/27.0)*(27*pow(x0.col(3)/6.0,2)%(x0.col(0)-Xt) - 9*(x0.col(3)/6.0)%(x0.col(2)/2.0)%x0.col(1) + 2*pow(x0.col(2)/2.0,3))/pow(x0.col(3)/6.0,3); vec chk=pow(q,2)/4.0 + pow(p,3)/27.0; vec th=-(x0.col(2)/2.0)/(3*(x0.col(3)/6.0))+pow(-q/2.0+sqrt(chk),(1.0/3.0))-pow(q/2.0+sqrt(chk),(1.0/3.0)); vec K =x0.col(0)%th+(x0.col(1)%th%th)/2.0+(x0.col(2)%th%th%th)/6.0 +(x0.col(3)%th%th%th%th)/24.0; vec K1=x0.col(0) +(x0.col(1)%th) +(x0.col(2)%th%th)/2.0 +(x0.col(3)%th%th%th)/6.0; vec K2=x0.col(1) +(x0.col(2)%th) +(x0.col(3)%th%th)/2.0; vec val=-0.5*log(2*3.141592653589793*K2)+(K-th%K1); List ret; ret["like"] = val; ret["max"] = whch; return(ret); } ' }, { Dpart= ' vec betas1 =+b12+2*b13%u1+3*b14%u2; vec betas2 =+b22+2*b23%u1+3*b24%u2; vec betas3 =+b32+2*b33%u1+3*b34%u2; vec betas4 =+b42+2*b43%u1+3*b44%u2; vec lo =-(0.5/(u1-lower))%(sqrt(exp(2*alpha)+4*pow((u1-lower),2))-exp(alpha)); vec up =-(0.5/(u1-upper))%(sqrt(exp(2*alpha)+4*pow((u1-upper),2))-exp(alpha)); vec DT = (up-lo)/(1.00*P); vec tau = exp(alpha)*lo/(1-pow(lo,2))+u1; vec rho = exp(alpha)*(1+pow(lo,2))/pow((1-pow(lo,2)),2); vec K=exp(-betas1%pow(tau,1)-0.5*betas2%pow(tau,2)-0.333333333333333333*betas3%pow(tau,3)-0.25*betas4%pow(tau,4))%rho%DT; for (int i = 1; i <= P; i++) { lo=lo+DT; tau = exp(alpha)*lo/(1-pow(lo,2))+u1; rho = exp(alpha)*(1+pow(lo,2))/pow((1-pow(lo,2)),2); K=K+exp(-betas1%pow(tau,1)-0.5*betas2%pow(tau,2)-0.333333333333333333*betas3%pow(tau,3)-0.25*betas4%pow(tau,4))%rho%DT; } vec val=((-betas1%pow(Xt,1)-0.5*betas2%pow(Xt,2)-0.333333333333333333*betas3%pow(Xt,3)-0.25*betas4%pow(Xt,4))-log(K)); List ret; ret["like"] = val; ret["max"] = whch; return(ret); } ' }, { Dpart=' vec betas1 =+b11+2*b12%u1+3*b13%u2+4*b14%u3; vec betas2 =+b21+2*b22%u1+3*b23%u2+4*b24%u3; vec betas3 =+b31+2*b32%u1+3*b33%u2+4*b34%u3; vec betas4 =+b41+2*b42%u1+3*b43%u2+4*b44%u3; vec lo =-(0.5/(u1-lower))%(sqrt(exp(2*alpha)+4*pow((u1-lower),2))-exp(alpha)); vec up =-(0.5/(u1-upper))%(sqrt(exp(2*alpha)+4*pow((u1-upper),2))-exp(alpha)); vec DT = (up-lo)/(1.00*P); vec tau = exp(alpha)*lo/(1-pow(lo,2))+u1; vec rho = exp(alpha)*(1+pow(lo,2))/pow((1-pow(lo,2)),2); vec K=exp(-betas1%log(tau)+(-betas2%tau-0.5*betas3%pow(tau,2)-0.33333333333333333333333*betas4%pow(tau,3)))%rho%DT; for (int i = 1; i <= P; i++) { lo=lo+DT; tau = exp(alpha)*lo/(1-pow(lo,2))+u1; rho = exp(alpha)*(1+pow(lo,2))/pow((1-pow(lo,2)),2); K=K+exp(-betas1%log(tau)+(-betas2%tau-0.5*betas3%pow(tau,2)-0.33333333333333333333333*betas4%pow(tau,3)))%rho%DT; } vec val = ((-betas1%log(Xt)+(-betas2%Xt-0.5*betas3%pow(Xt,2)-0.33333333333333333333333*betas4%pow(Xt,3)))-log(K)); List ret; ret["like"] = val; ret["max"] = whch; return(ret); } ' }, { Dpart=' vec betas1 =+2*b11%u1+3*b12%u2+4*b13%u3+5*b14%u4; vec betas2 =+2*b21%u1+3*b22%u2+4*b23%u3+5*b24%u4; vec betas3 =+2*b31%u1+3*b32%u2+4*b33%u3+5*b34%u4; vec betas4 =+2*b41%u1+3*b42%u2+4*b43%u3+5*b44%u4; vec lo =-(0.5/(u1-lower))%(sqrt(exp(2*alpha)+4*pow((u1-lower),2))-exp(alpha)); vec up =-(0.5/(u1-upper))%(sqrt(exp(2*alpha)+4*pow((u1-upper),2))-exp(alpha)); vec DT = (up-lo)/(1.00*P); vec tau = exp(alpha)*lo/(1-pow(lo,2))+u1; vec rho = exp(alpha)*(1+pow(lo,2))/pow((1-pow(lo,2)),2); vec K=exp(-betas2%log(tau)+(betas1/tau-betas3%tau-0.5*betas4%pow(tau,2)))%rho%DT; for (int i = 1; i <= P; i++) { lo=lo+DT; tau = exp(alpha)*lo/(1-pow(lo,2))+u1; rho = exp(alpha)*(1+pow(lo,2))/pow((1-pow(lo,2)),2); K=K+exp(-betas2%log(tau)+(betas1/tau-betas3%tau-0.5*betas4%pow(tau,2)))%rho%DT; } vec val = ((-betas2%log(Xt)+(betas1/Xt-betas3%Xt-0.5*betas4%pow(Xt,2)))-log(K)); List ret; ret["like"] = val; ret["max"] = whch; return(ret); } ' }, { Dpart=' vec betas1 =+b11%(1-2*u1)+b12%(2*u1-3*u2)+b13%(3*u2-4*u3)+b14%(4*u3-5*u4); vec betas2 =+b21%(1-2*u1)+b22%(2*u1-3*u2)+b23%(3*u2-4*u3)+b24%(4*u3-5*u4); vec betas3 =+b31%(1-2*u1)+b32%(2*u1-3*u2)+b33%(3*u2-4*u3)+b34%(4*u3-5*u4); vec betas4 =+b41%(1-2*u1)+b42%(2*u1-3*u2)+b43%(3*u2-4*u3)+b44%(4*u3-5*u4); vec K=exp(-betas1*log(Xtr)+(betas1+betas2+betas3+betas4)*log(1-Xtr)+(betas3+betas4)*Xtr+0.5*betas4*pow(Xtr,2)); for (int i = 1; i <= lim; i++) { Xtr=Xtr+delt2; K=K+exp(-betas1*log(Xtr)+(betas1+betas2+betas3+betas4)*log(1-Xtr)+(betas3+betas4)*Xtr+0.5*betas4*pow(Xtr,2))*delt2; } vec val =((-betas1%log(Xt)+(betas1+betas2+betas3+betas4)%log(1-Xt)+(betas3+betas4)%Xt+0.5*betas4%pow(Xt,2))-log(K)); List ret; ret["like"] = val; ret["max"] = whch; return(ret); } ' }) if(Dindex!=1) { Dpart=paste(Inv,Dpart) } } if(DTR.order==8) { Inv=' vec u1= x0.col(0); vec u2= x0.col(1)+1*x0.col(0)%u1; vec u3= x0.col(2)+1*x0.col(0)%u2+2*x0.col(1)%u1; vec u4= x0.col(3)+1*x0.col(0)%u3+3*x0.col(1)%u2+3*x0.col(2)%u1; vec u5= x0.col(4)+1*x0.col(0)%u4+4*x0.col(1)%u3+6*x0.col(2)%u2+4*x0.col(3)%u1; vec u6= x0.col(5)+1*x0.col(0)%u5+5*x0.col(1)%u4+10*x0.col(2)%u3+10*x0.col(3)%u2+5*x0.col(4)%u1; vec u7= x0.col(6)+1*x0.col(0)%u6+6*x0.col(1)%u5+15*x0.col(2)%u4+20*x0.col(3)%u3+15*x0.col(4)%u2+6*x0.col(5)%u1; vec u8= x0.col(7)+1*x0.col(0)%u7+7*x0.col(1)%u6+21*x0.col(2)%u5+35*x0.col(3)%u4+35*x0.col(4)%u3+21*x0.col(5)%u2+7*x0.col(6)%u1; vec det=-u1%(u1%(u4%(u6%u8-u7%u7)-u5%(u5%u8-u6%u7)+u6%(u5%u7-u6%u6))-u3%(u2%(u6%u8-u7%u7)-u5%(u3%u8-u4%u7)+u6%(u3%u7-u4%u6))+u4% (u2%(u5%u8-u6%u7)-u4%(u3%u8-u4%u7)+u6%(u3%u6-u4%u5))-u5%(u2%(u5%u7-u6%u6)-u4%(u3%u7-u4%u6)+u5%(u3%u6-u4%u5)))+u2%(u1% (u3%(u6%u8-u7%u7)-u5%(u4%u8-u5%u7)+u6%(u4%u7-u5%u6))-u2%(u2%(u6%u8-u7%u7)-u5%(u3%u8-u4%u7)+u6%(u3%u7-u4%u6))+u4% (u2%(u4%u8-u5%u7)-u3%(u3%u8-u4%u7)+(u3%u5-u4%u4)%u6)-u5%(u2%(u4%u7-u5%u6)-u3%(u3%u7-u4%u6)+u5%(u3%u5-u4%u4)))-u3%(u1% (u3%(u5%u8-u6%u7)-u4%(u4%u8-u5%u7)+u6%(u4%u6-u5%u5))-u2%(u2%(u5%u8-u6%u7)-u4%(u3%u8-u4%u7)+u6%(u3%u6-u4%u5))+u3% (u2%(u4%u8-u5%u7)-u3%(u3%u8-u4%u7)+(u3%u5-u4%u4)%u6)-u5%(u2%(u4%u6-u5%u5)-u3%(u3%u6-u4%u5)+u4%(u3%u5-u4%u4)))+u2% (u4%(u6%u8-u7%u7)-u5%(u5%u8-u6%u7)+u6%(u5%u7-u6%u6))-u3%(u3%(u6%u8-u7%u7)-u5%(u4%u8-u5%u7)+u6%(u4%u7-u5%u6))+u4% (u3%(u5%u8-u6%u7)-u4%(u4%u8-u5%u7)+u6%(u4%u6-u5%u5))+u4%(u1%(u3%(u5%u7-u6%u6)-u4%(u4%u7-u5%u6)+u5%(u4%u6-u5%u5))-u2% (u2%(u5%u7-u6%u6)-u4%(u3%u7-u4%u6)+u5%(u3%u6-u4%u5))+u3%(u2%(u4%u7-u5%u6)-u3%(u3%u7-u4%u6)+u5%(u3%u5-u4%u4))-u4% (u2%(u4%u6-u5%u5)-u3%(u3%u6-u4%u5)+u4%(u3%u5-u4%u4)))-u5%(u3%(u5%u7-u6%u6)-u4%(u4%u7-u5%u6)+u5%(u4%u6-u5%u5)); vec b11= (u2%(u4%(u6%u8-u7%u7)-u5%(u5%u8-u6%u7)+u6%(u5%u7-u6%u6))-u3%(u3%(u6%u8-u7%u7)-u5%(u4%u8-u5%u7)+u6%(u4%u7-u5%u6))+u4%(u3%(u5%u8-u6%u7)-u4%(u4%u8-u5%u7)+u6%(u4%u6-u5%u5))-u5%(u3%(u5%u7-u6%u6)-u4%(u4%u7-u5%u6)+u5%(u4%u6-u5%u5)))/det; vec b12= (-u1%(u4%(u6%u8-u7%u7)-u5%(u5%u8-u6%u7)+u6%(u5%u7-u6%u6))+u2%(u3%(u6%u8-u7%u7)-u5%(u4%u8-u5%u7)+u6%(u4%u7-u5%u6))-u3%(u3%(u5%u8-u6%u7)-u4%(u4%u8-u5%u7)+u6%(u4%u6-u5%u5))+u4%(u3%(u5%u7-u6%u6)-u4%(u4%u7-u5%u6)+u5%(u4%u6-u5%u5)))/det; vec b13= (u1%(u3%(u6%u8-u7%u7)-u4%(u5%u8-u6%u7)+u5%(u5%u7-u6%u6))-u2%(u2%(u6%u8-u7%u7)-u4%(u4%u8-u5%u7)+u5%(u4%u7-u5%u6))+u3%(u2%(u5%u8-u6%u7)-u3%(u4%u8-u5%u7)+u5%(u4%u6-u5%u5))-u4%(u2%(u5%u7-u6%u6)-u3%(u4%u7-u5%u6)+u4%(u4%u6-u5%u5)))/det; vec b14= (-u1%(u3%(u5%u8-u6%u7)-u4%(u4%u8-u6%u6)+u5%(u4%u7-u5%u6))+u2%(u2%(u5%u8-u6%u7)-u4%(u3%u8-u5%u6)+u5%(u3%u7-u5%u5))-u3%(u2%(u4%u8-u6%u6)-u3%(u3%u8-u5%u6)+u5%(u3%u6-u4%u5))+u4%(u2%(u4%u7-u5%u6)-u3%(u3%u7-u5%u5)+u4%(u3%u6-u4%u5)))/det; vec b15= (u1%(u3%(u5%u7-u6%u6)-u4%(u4%u7-u5%u6)+u5%(u4%u6-u5%u5))-u2%(u2%(u5%u7-u6%u6)-u4%(u3%u7-u4%u6)+u5%(u3%u6-u4%u5))+u3%(u2%(u4%u7-u5%u6)-u3%(u3%u7-u4%u6)+u5%(u3%u5-u4%u4))-u4%(u2%(u4%u6-u5%u5)-u3%(u3%u6-u4%u5)+u4%(u3%u5-u4%u4)))/det; vec b21= (-u1%(u4%(u6%u8-u7%u7)-u5%(u5%u8-u6%u7)+u6%(u5%u7-u6%u6))+u3%(u2%(u6%u8-u7%u7)-u5%(u3%u8-u4%u7)+u6%(u3%u7-u4%u6))-u4%(u2%(u5%u8-u6%u7)-u4%(u3%u8-u4%u7)+u6%(u3%u6-u4%u5))+u5%(u2%(u5%u7-u6%u6)-u4%(u3%u7-u4%u6)+u5%(u3%u6-u4%u5)))/det; vec b22= (-u2%(u2%(u6%u8-u7%u7)-u5%(u3%u8-u4%u7)+u6%(u3%u7-u4%u6))+u3%(u2%(u5%u8-u6%u7)-u4%(u3%u8-u4%u7)+u6%(u3%u6-u4%u5))+u4%(u6%u8-u7%u7)-u5%(u5%u8-u6%u7)-u4%(u2%(u5%u7-u6%u6)-u4%(u3%u7-u4%u6)+u5%(u3%u6-u4%u5))+u6%(u5%u7-u6%u6))/det; vec b23= (u2%(u1%(u6%u8-u7%u7)-u4%(u3%u8-u4%u7)+u5%(u3%u7-u4%u6))-u3%(u1%(u5%u8-u6%u7)-u3%(u3%u8-u4%u7)+u5%(u3%u6-u4%u5))-u3%(u6%u8-u7%u7)+u4%(u5%u8-u6%u7)+u4%(u1%(u5%u7-u6%u6)-u3%(u3%u7-u4%u6)+u4%(u3%u6-u4%u5))-u5%(u5%u7-u6%u6))/det; vec b24= (-u2%(u1%(u5%u8-u6%u7)-u4%(u2%u8-u4%u6)+u5%(u2%u7-u4%u5))+u3%(u1%(u4%u8-u6%u6)-u3%(u2%u8-u4%u6)+u5%(u2%u6-u4%u4))+u3%(u5%u8-u6%u7)-u4%(u4%u8-u6%u6)-u4%(u1%(u4%u7-u5%u6)-u3%(u2%u7-u4%u5)+u4%(u2%u6-u4%u4))+u5%(u4%u7-u5%u6))/det; vec b25= (u2%(u1%(u5%u7-u6%u6)-u4%(u2%u7-u3%u6)+u5%(u2%u6-u3%u5))-u3%(u1%(u4%u7-u5%u6)-u3%(u2%u7-u3%u6)+u5%(u2%u5-u3%u4))-u3%(u5%u7-u6%u6)+u4%(u4%u7-u5%u6)+u4%(u1%(u4%u6-u5%u5)-u3%(u2%u6-u3%u5)+u4%(u2%u5-u3%u4))-u5%(u4%u6-u5%u5))/det; vec b31= (u1%(u3%(u6%u8-u7%u7)-u5%(u4%u8-u5%u7)+u6%(u4%u7-u5%u6))-u2%(u2%(u6%u8-u7%u7)-u5%(u3%u8-u4%u7)+u6%(u3%u7-u4%u6))+u4%(u2%(u4%u8-u5%u7)-u3%(u3%u8-u4%u7)+(u3%u5-u4%u4)%u6)-u5%(u2%(u4%u7-u5%u6)-u3%(u3%u7-u4%u6)+u5%(u3%u5-u4%u4)))/det; vec b32= (u1%(u2%(u6%u8-u7%u7)-u5%(u3%u8-u4%u7)+u6%(u3%u7-u4%u6))-u3%(u2%(u4%u8-u5%u7)-u3%(u3%u8-u4%u7)+(u3%u5-u4%u4)%u6)-u3%(u6%u8-u7%u7)+u5%(u4%u8-u5%u7)+u4%(u2%(u4%u7-u5%u6)-u3%(u3%u7-u4%u6)+u5%(u3%u5-u4%u4))-u6%(u4%u7-u5%u6))/det; vec b33= (-u1%(u1%(u6%u8-u7%u7)-u4%(u3%u8-u4%u7)+u5%(u3%u7-u4%u6))+u3%(u1%(u4%u8-u5%u7)-u2%(u3%u8-u4%u7)+u5%(u3%u5-u4%u4))+u2%(u6%u8-u7%u7)-u4%(u4%u8-u5%u7)-u4%(u1%(u4%u7-u5%u6)-u2%(u3%u7-u4%u6)+u4%(u3%u5-u4%u4))+u5%(u4%u7-u5%u6))/det; vec b34= (u1%(u1%(u5%u8-u6%u7)-u4%(u2%u8-u4%u6)+u5%(u2%u7-u4%u5))-u3%(u1%(u3%u8-u5%u6)-u2%(u2%u8-u4%u6)+u5%(u2%u5-u3%u4))-u2%(u5%u8-u6%u7)+u4%(u3%u8-u5%u6)+u4%(u1%(u3%u7-u5%u5)-u2%(u2%u7-u4%u5)+u4%(u2%u5-u3%u4))-u5%(u3%u7-u5%u5))/det; vec b35= (-u1%(u1%(u5%u7-u6%u6)-u4%(u2%u7-u3%u6)+u5%(u2%u6-u3%u5))+u3%(u1%(u3%u7-u4%u6)-u2%(u2%u7-u3%u6)+(u2%u4-u3%u3)%u5)+u2%(u5%u7-u6%u6)-u4%(u3%u7-u4%u6)-u4%(u1%(u3%u6-u4%u5)-u2%(u2%u6-u3%u5)+u4%(u2%u4-u3%u3))+u5%(u3%u6-u4%u5))/det; vec b41= (-u1%(u3%(u5%u8-u6%u7)-u4%(u4%u8-u5%u7)+u6%(u4%u6-u5%u5))+u2%(u2%(u5%u8-u6%u7)-u4%(u3%u8-u4%u7)+u6%(u3%u6-u4%u5))-u3%(u2%(u4%u8-u5%u7)-u3%(u3%u8-u4%u7)+(u3%u5-u4%u4)%u6)+u5%(u2%(u4%u6-u5%u5)-u3%(u3%u6-u4%u5)+u4%(u3%u5-u4%u4)))/det; vec b42= (-u1%(u2%(u5%u8-u6%u7)-u4%(u3%u8-u4%u7)+u6%(u3%u6-u4%u5))+u2%(u2%(u4%u8-u5%u7)-u3%(u3%u8-u4%u7)+(u3%u5-u4%u4)%u6)+u3%(u5%u8-u6%u7)-u4%(u4%u8-u5%u7)-u4%(u2%(u4%u6-u5%u5)-u3%(u3%u6-u4%u5)+u4%(u3%u5-u4%u4))+u6%(u4%u6-u5%u5))/det; vec b43= (u1%(u1%(u5%u8-u6%u7)-u3%(u3%u8-u4%u7)+u5%(u3%u6-u4%u5))-u2%(u1%(u4%u8-u5%u7)-u2%(u3%u8-u4%u7)+u5%(u3%u5-u4%u4))-u2%(u5%u8-u6%u7)+u3%(u4%u8-u5%u7)+u4%(u1%(u4%u6-u5%u5)-u2%(u3%u6-u4%u5)+u3%(u3%u5-u4%u4))-u5%(u4%u6-u5%u5))/det; vec b44= (-u1%(u1%(u4%u8-u6%u6)-u3%(u2%u8-u4%u6)+u5%(u2%u6-u4%u4))+u2%(u1%(u3%u8-u5%u6)-u2%(u2%u8-u4%u6)+u5%(u2%u5-u3%u4))+u2%(u4%u8-u6%u6)-u3%(u3%u8-u5%u6)-u4%(u1%(u3%u6-u4%u5)-u2%(u2%u6-u4%u4)+u3%(u2%u5-u3%u4))+u5%(u3%u6-u4%u5))/det; vec b45= (u1%(u1%(u4%u7-u5%u6)-u3%(u2%u7-u3%u6)+u5%(u2%u5-u3%u4))-u2%(u1%(u3%u7-u4%u6)-u2%(u2%u7-u3%u6)+(u2%u4-u3%u3)%u5)-u2%(u4%u7-u5%u6)+u3%(u3%u7-u4%u6)+u4%(u1%(u3%u5-u4%u4)-u2%(u2%u5-u3%u4)+u3%(u2%u4-u3%u3))-u5%(u3%u5-u4%u4))/det; vec b51= (u1%(u3%(u5%u7-u6%u6)-u4%(u4%u7-u5%u6)+u5%(u4%u6-u5%u5))-u2%(u2%(u5%u7-u6%u6)-u4%(u3%u7-u4%u6)+u5%(u3%u6-u4%u5))+u3%(u2%(u4%u7-u5%u6)-u3%(u3%u7-u4%u6)+u5%(u3%u5-u4%u4))-u4%(u2%(u4%u6-u5%u5)-u3%(u3%u6-u4%u5)+u4%(u3%u5-u4%u4)))/det; vec b52= (u1%(u2%(u5%u7-u6%u6)-u4%(u3%u7-u4%u6)+u5%(u3%u6-u4%u5))-u2%(u2%(u4%u7-u5%u6)-u3%(u3%u7-u4%u6)+u5%(u3%u5-u4%u4))-u3%(u5%u7-u6%u6)+u4%(u4%u7-u5%u6)+u3%(u2%(u4%u6-u5%u5)-u3%(u3%u6-u4%u5)+u4%(u3%u5-u4%u4))-u5%(u4%u6-u5%u5))/det; vec b53= (-u1%(u1%(u5%u7-u6%u6)-u3%(u3%u7-u4%u6)+u4%(u3%u6-u4%u5))+u2%(u1%(u4%u7-u5%u6)-u2%(u3%u7-u4%u6)+u4%(u3%u5-u4%u4))+u2%(u5%u7-u6%u6)-u3%(u4%u7-u5%u6)-u3%(u1%(u4%u6-u5%u5)-u2%(u3%u6-u4%u5)+u3%(u3%u5-u4%u4))+u4%(u4%u6-u5%u5))/det; vec b54= (u1%(u1%(u4%u7-u5%u6)-u3%(u2%u7-u4%u5)+u4%(u2%u6-u4%u4))-u2%(u1%(u3%u7-u5%u5)-u2%(u2%u7-u4%u5)+u4%(u2%u5-u3%u4))-u2%(u4%u7-u5%u6)+u3%(u3%u7-u5%u5)+u3%(u1%(u3%u6-u4%u5)-u2%(u2%u6-u4%u4)+u3%(u2%u5-u3%u4))-u4%(u3%u6-u4%u5))/det; vec b55= (-u1%(u1%(u4%u6-u5%u5)-u3%(u2%u6-u3%u5)+u4%(u2%u5-u3%u4))+u2%(u1%(u3%u6-u4%u5)-u2%(u2%u6-u3%u5)+u4%(u2%u4-u3%u3))+u2%(u4%u6-u5%u5)-u3%(u3%u6-u4%u5)-u3%(u1%(u3%u5-u4%u4)-u2%(u2%u5-u3%u4)+u3%(u2%u4-u3%u3))+u4%(u3%u5-u4%u4))/det; ' switch(Dindex, { Dpart=' vec p=(1.0/3.0) *(3*(x0.col(3)/6.0)%x0.col(1) - pow(x0.col(2)/2.0,2))/pow(x0.col(3)/6.0,2); vec q=(1.0/27.0)*(27*pow(x0.col(3)/6.0,2)%(x0.col(0)-Xt) - 9*(x0.col(3)/6.0)%(x0.col(2)/2.0)%x0.col(1) + 2*pow(x0.col(2)/2.0,3))/pow(x0.col(3)/6.0,3); vec chk=pow(q,2)/4.0 + pow(p,3)/27.0; vec th=-(x0.col(2)/2.0)/(3*(x0.col(3)/6.0))+pow(-q/2.0+sqrt(chk),(1.0/3.0))-pow(q/2.0+sqrt(chk),(1.0/3.0)); vec K =x0.col(0)%th+(x0.col(1)%th%th)/2.0+(x0.col(2)%th%th%th)/6.0 +(x0.col(3)%th%th%th%th)/24.0; vec K1=x0.col(0) +(x0.col(1)%th) +(x0.col(2)%th%th)/2.0 +(x0.col(3)%th%th%th)/6.0; vec K2=x0.col(1) +(x0.col(2)%th) +(x0.col(3)%th%th)/2.0; vec val=-0.5*log(2*3.141592653589793*K2)+(K-th%K1); List ret; ret["like"] = val; ret["max"] = whch; return(ret); } ' }, { Dpart= ' vec betas1 =+b12+2*b13%u1+3*b14%u2+4*b15%u3; vec betas2 =+b22+2*b23%u1+3*b24%u2+4*b25%u3; vec betas3 =+b32+2*b33%u1+3*b34%u2+4*b35%u3; vec betas4 =+b42+2*b43%u1+3*b44%u2+4*b45%u3; vec betas5 =+b52+2*b53%u1+3*b54%u2+4*b55%u3; vec lo =-(0.5/(u1-lower))%(sqrt(exp(2*alpha)+4*pow((u1-lower),2))-exp(alpha)); vec up =-(0.5/(u1-upper))%(sqrt(exp(2*alpha)+4*pow((u1-upper),2))-exp(alpha)); vec DT = (up-lo)/(1.00*P); vec tau = exp(alpha)*lo/(1-pow(lo,2))+u1; vec rho = exp(alpha)*(1+pow(lo,2))/pow((1-pow(lo,2)),2); vec K=exp(-betas1%pow(tau,1)-0.5*betas2%pow(tau,2)-0.333333333333333333*betas3%pow(tau,3)-0.25*betas4%pow(tau,4)-0.2*betas5%pow(tau,5))%rho%DT; for (int i = 1; i <= P; i++) { lo=lo+DT; tau = exp(alpha)*lo/(1-pow(lo,2))+u1; rho = exp(alpha)*(1+pow(lo,2))/pow((1-pow(lo,2)),2); K=K+exp(-betas1%pow(tau,1)-0.5*betas2%pow(tau,2)-0.333333333333333333*betas3%pow(tau,3)-0.25*betas4%pow(tau,4)-0.2*betas5%pow(tau,5))%rho%DT; } vec val =((-betas1%pow(Xt,1)-0.5*betas2%pow(Xt,2)-0.333333333333333333*betas3%pow(Xt,3)-0.25*betas4%pow(Xt,4)-0.2*betas5%pow(Xt,5))-log(K)); List ret; ret["like"] = val; ret["max"] = whch; return(ret); } ' }, { Dpart=' vec betas1 =+b11+2*b12%u1+3*b13%u2+4*b14%u3+4*b15%u4; vec betas2 =+b21+2*b22%u1+3*b23%u2+4*b24%u3+4*b25%u4; vec betas3 =+b31+2*b32%u1+3*b33%u2+4*b34%u3+4*b35%u4; vec betas4 =+b41+2*b42%u1+3*b43%u2+4*b44%u3+4*b45%u4; vec betas5 =+b51+2*b52%u1+3*b53%u2+4*b54%u3+4*b55%u4; vec lo =-(0.5/(u1-lower))%(sqrt(exp(2*alpha)+4*pow((u1-lower),2))-exp(alpha)); vec up =-(0.5/(u1-upper))%(sqrt(exp(2*alpha)+4*pow((u1-upper),2))-exp(alpha)); vec DT = (up-lo)/(1.00*P); vec tau = exp(alpha)*lo/(1-pow(lo,2))+u1; vec rho = exp(alpha)*(1+pow(lo,2))/pow((1-pow(lo,2)),2); vec K=exp(-betas1%log(tau)+(-betas2%tau-0.5*betas3%pow(tau,2)-0.33333333333333333333333*betas4%pow(tau,3)-0.25*betas5%pow(tau,4)))%rho%DT; for (int i = 1; i <= P; i++) { lo=lo+DT; tau = exp(alpha)*lo/(1-pow(lo,2))+u1; rho = exp(alpha)*(1+pow(lo,2))/pow((1-pow(lo,2)),2); K=K+exp(-betas1%log(tau)+(-betas2%tau-0.5*betas3%pow(tau,2)-0.33333333333333333333333*betas4%pow(tau,3)-0.25*betas5%pow(tau,4)))%rho%DT; } vec val =((-betas1%log(Xt)+(-betas2%Xt-0.5*betas3%pow(Xt,2)-0.33333333333333333333333*betas4%pow(Xt,3)-0.25*betas5%pow(Xt,4)))-log(K)); List ret; ret["like"] = val; ret["max"] = whch; return(ret); } ' }, { Dpart=' vec betas1 =+2*b11%u1+3*b12%u2+4*b13%u3+5*b14%u4+6*b15%u5; vec betas2 =+2*b21%u1+3*b22%u2+4*b23%u3+5*b24%u4+6*b25%u5; vec betas3 =+2*b31%u1+3*b32%u2+4*b33%u3+5*b34%u4+6*b35%u5; vec betas4 =+2*b41%u1+3*b42%u2+4*b43%u3+5*b44%u4+6*b45%u5; vec betas5 =+2*b51%u1+3*b52%u2+4*b53%u3+5*b54%u4+6*b55%u5; vec lo =-(0.5/(u1-lower))%(sqrt(exp(2*alpha)+4*pow((u1-lower),2))-exp(alpha)); vec up =-(0.5/(u1-upper))%(sqrt(exp(2*alpha)+4*pow((u1-upper),2))-exp(alpha)); vec DT = (up-lo)/(1.00*P); vec tau = exp(alpha)*lo/(1-pow(lo,2))+u1; vec rho = exp(alpha)*(1+pow(lo,2))/pow((1-pow(lo,2)),2); vec K=exp(-betas2%log(tau)+(betas1/tau-betas3%tau-0.5*betas4%pow(tau,2)-0.3333333333333333*betas5%pow(tau,3)))%rho%DT; for (int i = 1; i <= P; i++) { lo=lo+DT; tau = exp(alpha)*lo/(1-pow(lo,2))+u1; rho = exp(alpha)*(1+pow(lo,2))/pow((1-pow(lo,2)),2); K=K+exp(-betas2%log(tau)+(betas1/tau-betas3%tau-0.5*betas4%pow(tau,2)-0.3333333333333333*betas5%pow(tau,3)))%rho%DT; } vec val =((-betas2%log(Xt)+(betas1/Xt-betas3%Xt-0.5*betas4%pow(Xt,2)-0.3333333333333333*betas5%pow(Xt,3)))-log(K)); List ret; ret["like"] = val; ret["max"] = whch; return(ret); } ' }, { Dpart=' vec betas1 =+b11%(1-2*u1)+b12%(2*u1-3*u2)+b13%(3*u2-4*u3)+b14%(4*u3-5*u4)+b15%(5*u4-6*u5); vec betas2 =+b21%(1-2*u1)+b22%(2*u1-3*u2)+b23%(3*u2-4*u3)+b24%(4*u3-5*u4)+b25%(5*u4-6*u5); vec betas3 =+b31%(1-2*u1)+b32%(2*u1-3*u2)+b33%(3*u2-4*u3)+b34%(4*u3-5*u4)+b35%(5*u4-6*u5); vec betas4 =+b41%(1-2*u1)+b42%(2*u1-3*u2)+b43%(3*u2-4*u3)+b44%(4*u3-5*u4)+b45%(5*u4-6*u5); vec betas5 =+b51%(1-2*u1)+b52%(2*u1-3*u2)+b53%(3*u2-4*u3)+b54%(4*u3-5*u4)+b55%(5*u4-6*u5); vec lo =-(0.5/(u1-lower))%(sqrt(exp(2*alpha)+4*pow((u1-lower),2))-exp(alpha)); vec up =-(0.5/(u1-upper))%(sqrt(exp(2*alpha)+4*pow((u1-upper),2))-exp(alpha)); vec DT = (up-lo)/(1.00*P); vec tau = exp(alpha)*lo/(1-pow(lo,2))+u1; vec rho = exp(alpha)*(1+pow(lo,2))/pow((1-pow(lo,2)),2); vec K=exp(-betas2%log(tau)+(betas1/tau-betas3%tau-0.5*betas4%pow(tau,2)-0.3333333333333333*betas5%pow(tau,3)))%rho%DT; for (int i = 1; i <= P; i++) { lo=lo+DT; tau = exp(alpha)*lo/(1-pow(lo,2))+u1; rho = exp(alpha)*(1+pow(lo,2))/pow((1-pow(lo,2)),2); K=K+exp(-betas2%log(tau)+(betas1/tau-betas3%tau-0.5*betas4%pow(tau,2)-0.3333333333333333*betas5%pow(tau,3)))%rho%DT; } vec val = ((-betas2%log(Xt)+(betas1/Xt-betas3%Xt-0.5*betas4%pow(Xt,2)-0.3333333333333333*betas5%pow(Xt,3)))-log(K)); List ret; ret["like"] = val; ret["max"] = whch; return(ret); } ' }) if(Dindex!=1) { Dpart=paste(Inv,Dpart) } } strcheck=function(str) { k=0 if(length(grep('/',str))!=0) { warning('C++ uses integer division when denominators are of type int. Use decimal values if possible (e.g. 0.5 i.s.o. 1/2).',call. = F) k=k+1 } if(length(grep('\\^',str))!=0) { stop('^-Operator not defined in C++: Use pow(x,p) instead (e.g. pow(x,2) i.s.o. x^2).',call. = F) k=k+1 } return(k) } for(i in which(func.list==1)) { strcheck(body(namess[i])[2]) } if(state1) { if(!homo.res) { delt=cbind(diff(T.seq)/mesh,diff(T.seq)/mesh) if(!is.null(exclude)) { diffs=diff(T.seq)/mesh diffs[excl]=1/20/mesh delt=cbind(diffs,diffs) } } MAT=rbind( c('(1+0*a.col(0))','a.col(0)' ,''), c('','2*a.col(1)','(1+0*a.col(0))'), c('','3*a.col(2)',''), c('','4*a.col(3)','')) namess2=c('G0','G1','Q0') func.list2=rep(0,3) obs=objects(pos=1) for(i in 1:3) { if(sum(obs==namess2[i])){func.list2[i]=1} } func.list.timehomo=func.list2*0 for(i in which(func.list2==1)) { result=eval(body(namess2[i])) func.list.timehomo[i]=2-(sum(diff(result)==0)==(length(result)-1)) } if(any(func.list.timehomo==2)){homo=F} dims=rep('(',2) for(i in 1:2) { for(j in which(func.list2==1)) { if(MAT[i,j]!='') { dims[i]=paste0(dims[i],'+(',body(namess2[j])[2],')',c('*','%')[func.list.timehomo[j]],MAT[i,j]) } } dims[i]=paste0(dims[i],')') } if(any(dims=='()')){dims[which(dims=='()')]='0*a.col(0)'} for(i in 1:2) { dims[i]=paste0(paste0(paste0(' atemp.col(',i-1,')='),dims[i]),';') } txt.full=paste(fpart,'\n',dims[1],'\n',dims[2],ODEpart,Dpart) type.sol =" Generalized Ornstein-Uhlenbeck " if(wrt){write(txt.full,file='GQD.mcmc.cpp')} stre="Compiling C++ code. Please wait." cat(stre, " \r") flush.console() sourceCpp(code=txt.full) cat(' ','\r') } if(state2) { if((!homo.res)&(TR.order==4)) { delt=cbind(diff(T.seq)/mesh,diff(T.seq)/mesh,diff(T.seq)/mesh,diff(T.seq)/mesh) if(!is.null(exclude)) { diffs=diff(T.seq)/mesh diffs[excl]=1/20/mesh delt=cbind(diffs,diffs,diffs,diffs) } } if((!homo.res)&(TR.order==6)) { delt=cbind(diff(T.seq)/mesh,diff(T.seq)/mesh,diff(T.seq)/mesh,diff(T.seq)/mesh,diff(T.seq)/mesh,diff(T.seq)/mesh) if(!is.null(exclude)) { diffs=diff(T.seq)/mesh diffs[excl]=1/20/mesh delt=cbind(diffs,diffs,diffs,diffs,diffs,diffs) } } if((!homo.res)&(TR.order==8)) { delt=cbind(diff(T.seq)/mesh,diff(T.seq)/mesh,diff(T.seq)/mesh,diff(T.seq)/mesh,diff(T.seq)/mesh,diff(T.seq)/mesh,diff(T.seq)/mesh,diff(T.seq)/mesh) if(!is.null(exclude)) { diffs=diff(T.seq)/mesh diffs[excl]=1/20/mesh delt=cbind(diffs,diffs,diffs,diffs,diffs,diffs,diffs,diffs) } } if(TR.order==4) { MAT=rbind( c('(1+0*a.col(0))','a.col(0)','(a.col(1)+a.col(0)%a.col(0))','','',''), c('','(2*a.col(1))','(2*a.col(2)+4*a.col(0)%a.col(1))','(1+0*a.col(0))','a.col(0)','(a.col(1)+a.col(0)%a.col(0))'), c('','(3*a.col(2))','(3*a.col(3)+6*a.col(0)%a.col(2)+6*a.col(1)%a.col(1))','','(3*a.col(1))','(3*a.col(2)+6*a.col(0)%a.col(1))'), c('','(4*a.col(3))','(8*a.col(0)%a.col(3)+24*a.col(1)%a.col(2))','','(6*a.col(2))','(6*a.col(3)+12*a.col(0)%a.col(2)+12*a.col(1)%a.col(1))')) } if(TR.order==6) { MAT = rbind( c('(1+0*a.col(0))','(a.col(0))' ,'(1*a.col(1)+1*a.col(0)%a.col(0))' ,'','',''), c('','(2*a.col(1))','(2*a.col(2)+4*a.col(0)%a.col(1))' ,'(1+0*a.col(0))','( a.col(0))','(a.col(1)+a.col(0)%a.col(0))'), c('','(3*a.col(2))','(3*a.col(3)+6*a.col(0)%a.col(2)+6*a.col(1)%a.col(1))' ,'','( 3*a.col(1))','(3*a.col(2)+6*a.col(0)%a.col(1))'), c('','(4*a.col(3))','(4*a.col(4)+8*a.col(0)%a.col(3)+24*a.col(1)%a.col(2))' ,'','( 6*a.col(2))','(6*a.col(3)+12*a.col(0)%a.col(2)+12*a.col(1)%a.col(1))'), c('','(5*a.col(4))','(5*a.col(5)+10*a.col(0)%a.col(4)+40*a.col(1)%a.col(3)+30*a.col(2)%a.col(2))' ,'','(10*a.col(3))','(10*a.col(4)+20*a.col(0)%a.col(3)+60*a.col(1)%a.col(2))'), c('','(6*a.col(5))','( +12*a.col(0)%a.col(5)+60*a.col(1)%a.col(4)+120*a.col(2)%a.col(3))','','(15*a.col(4))','(15*a.col(5)+30*a.col(0)%a.col(4)+120*a.col(1)%a.col(3)+90*a.col(2)%a.col(2))')) } if(TR.order==8) { MAT = rbind( c('(1+0*a.col(0))',' (a.col(0))','(1*a.col(1) +1*a.col(0)%a.col(0))' ,'','',''), c('','(2*a.col(1))','(2*a.col(2) +4*a.col(0)%a.col(1))' ,'(1+0*a.col(0))','( a.col(0))','(a.col(1)+a.col(0)%a.col(0))'), c('','(3*a.col(2))','(3*a.col(3) +6*a.col(0)%a.col(2) +6*a.col(1)%a.col(1))' ,'','( 3*a.col(1))','( 3*a.col(2) +6*a.col(0)%a.col(1))'), c('','(4*a.col(3))','(4*a.col(4) +8*a.col(0)%a.col(3) +24*a.col(1)%a.col(2))' ,'','( 6*a.col(2))','( 6*a.col(3)+12*a.col(0)%a.col(2) +12*a.col(1)%a.col(1))'), c('','(5*a.col(4))','(5*a.col(5)+10*a.col(0)%a.col(4) +40*a.col(1)%a.col(3) +30*a.col(2)%a.col(2))' ,'','(10*a.col(3))','(10*a.col(4)+20*a.col(0)%a.col(3) +60*a.col(1)%a.col(2))'), c('','(6*a.col(5))','(6*a.col(6)+12*a.col(0)%a.col(5) +60*a.col(1)%a.col(4) +120*a.col(2)%a.col(3))' ,'','(15*a.col(4))','(15*a.col(5)+30*a.col(0)%a.col(4)+120*a.col(1)%a.col(3) +90*a.col(2)%a.col(2))'), c('','(7*a.col(6))','(7*a.col(7)+14*a.col(0)%a.col(6) +84*a.col(1)%a.col(5) +210*a.col(2)%a.col(4)+140*a.col(3)%a.col(3))','','(21*a.col(5))','(21*a.col(6)+42*a.col(0)%a.col(5)+210*a.col(1)%a.col(4)+420*a.col(2)%a.col(3))'), c('','(8*a.col(7))','( +16*a.col(0)%a.col(7)+112*a.col(1)%a.col(6) +336*a.col(2)%a.col(5)+560*a.col(4)%a.col(3))','','(28*a.col(6))','(28*a.col(7)+56*a.col(0)%a.col(6)+336*a.col(1)%a.col(5)+840*a.col(2)%a.col(4)+560*a.col(3)%a.col(3))')) } namess2=c('G0','G1','G2','Q0','Q1','Q2') func.list2=rep(0,6) obs=objects(pos=1) for(i in 1:6) { if(sum(obs==namess[i])){func.list2[i]=1} } func.list.timehomo=func.list2*0 for(i in which(func.list2==1)) { result=eval(body(namess2[i])) func.list.timehomo[i]=2-(sum(diff(result)==0)==(length(result)-1)) } if(any(func.list.timehomo==2)){homo=F} dims=rep('(',TR.order) for(i in 1:TR.order) { for(j in which(func.list2==1)) { if(MAT[i,j]!='') { dims[i]=paste0(dims[i],'+(',body(namess2[j])[2],')',c('*','%')[func.list.timehomo[j]],MAT[i,j]) } } dims[i]=paste0(dims[i],')') } if(any(dims=='()')){dims[which(dims=='()')]='0*a.col(0)'} for(i in 1:TR.order) { dims[i]=paste0(paste0(paste0(' atemp.col(',i-1,')='),dims[i]),';') } if(TR.order==4) { txt.full=paste(fpart,'\n',dims[1],'\n',dims[2],'\n',dims[3],'\n',dims[4],ODEpart,Dpart) } if(TR.order==6) { txt.full=paste(fpart,'\n',dims[1],'\n',dims[2],'\n',dims[3],'\n',dims[4],'\n',dims[5],'\n',dims[6],ODEpart,Dpart) } if(TR.order==8) { txt.full=paste(fpart,'\n',dims[1],'\n',dims[2],'\n',dims[3],'\n',dims[4],'\n',dims[5],'\n',dims[6],'\n',dims[7],'\n',dims[8],ODEpart,Dpart) } type.sol =" Generalized Quadratic Diffusion (GQD) " if(wrt){write(txt.full,file='GQD.mcmc.cpp')} stre="Compiling C++ code. Please wait." cat(stre, " \r") flush.console() sourceCpp(code=txt.full) cat(' ','\r') } if(sum(objects(pos=1)=='priors')==1) { pp=function(theta){} body(pp)=parse(text =body(priors)[2]) prior.list=paste0('d(theta)',':',paste0(body(priors)[2])) } if(sum(objects(pos=1)=='priors')==0) { prior.list=paste0('d(theta)',':',' None.') pp=function(theta){1} } if(length(pp(theta))!=1){stop("Prior density must return only a single value!")} namess4=namess trim <- function (x) gsub("([[:space:]])", "", x) for(i in 1:6) { if(sum(obs==namess4[i])) { namess4[i]=paste0(namess4[i],' : ',trim(body(namess4[i])[2])) } } namess4=matrix(namess4,length(namess4),1) prior.list = trim(prior.list) buffer0=c('================================================================') buffer1=c('----------------------------------------------------------------') buffer2=c('................................................................') buffer3=c('... ... ... ... ... ... ... ... ... ... ... ') buffer4=c('_____________________ Drift Coefficients _______________________') buffer5=c('___________________ Diffusion Coefficients _____________________') buffer6=c('_____________________ Prior Distributions ______________________') buffer7=c('_______________________ Model/Chain Info _______________________') Info=c(buffer0,type.sol,buffer0,buffer4,namess4[1:3],buffer5,namess4[4:6],buffer6,'',prior.list) Info=data.frame(matrix(Info,length(Info),1)) colnames(Info)='' if(print.output) { print(Info,row.names = FALSE,right=F) } tme=Sys.time() par.matrix=matrix(0,length(theta),updates) muvec = theta covvec = diag(sds^2) errs = rep(0,updates) ll = rep(0,updates) acc=ll kk=0 par.matrix[,1]=theta prop.matrix = par.matrix retries = 0 max.retries = 0 retry.count = 0 retry.indexes = c() success = TRUE rs=solver(X[-nnn],X[-1],c(0,theta),mesh,delt,nnn-1,T.seq[-nnn],P,alpha,lower,upper,TR.order) if(is.na(sum(rs$like))) { retry.count =1 while(is.na(sum(rs$like))&&(retry.count<=10)) { theta.start=theta+rnorm(length(theta),sd=sds) rs = solver(X[-nnn],X[-1],c(0,theta.start),mesh,delt,nnn-1,T.seq[-nnn],P,alpha,lower,upper,TR.order) if(is.na(sum(rs$like[-excl]))){retry.count=retry.count+1} } } lold=sum(rs$like) if(rs$max>0.1){warning('Probable that starting values were chosen poorly.')} errs[1] =rs$max ll[1]=lold if(adapt==0) { pb <- txtProgressBar(1,updates,1,style = 1,width = 65) failed.chain=F i=2 while(i<=updates) { theta.temp=theta theta=theta+rnorm(length(theta),sd=sds) prop.matrix[,i] = theta rs = solver(X[-nnn],X[-1],c(0,theta),mesh,delt,nnn-1,T.seq[-nnn],P,alpha,lower,upper,TR.order) lnew=sum(rs$like[-excl]) rat=min(exp(lnew-lold)*pp(theta)/pp(theta.temp),1) if(is.na(rat)) { retry.count =1 retries=retries+1 retry.indexes[retries] = i max.retries=max.retries+1 while(is.na(rat)&&(retry.count<=10)) { i = max(i-10,2) theta = par.matrix[,i] theta=theta+rnorm(length(theta),sd=sds) prop.matrix[,i] = theta rs = solver(X[-nnn],X[-1],c(0,theta),mesh,delt,nnn-1,T.seq[-nnn],P,alpha,lower,upper,TR.order) lnew=sum(rs$like[-excl]) rat=min(exp(lnew-lold)*pp(theta)/pp(theta.temp),1) if(is.na(rat)){retry.count=retry.count+1} } } u=runif(1) is.true =(rat>u) is.false=!is.true theta=theta*is.true+theta.temp*is.false lold=lnew*is.true +lold*is.false errs[i]=rs$max*is.true+errs[i-1]*is.false par.matrix[,i]=theta ll[i]=lold kk=kk+is.true acc[i]=is.true if(max.retries>2000){print('Fail: Failed evaluation limit exceeded!');failed.chain=T;break;} if(any(is.na(theta))){print('Fail: Samples were NA! ');failed.chain=T;break;} setTxtProgressBar(pb, i) i = i+1 } close(pb) acc = cumsum(acc)/(1:updates) } if(adapt!=0) { pb <- txtProgressBar(1,updates,1,style = 1,width = 65) failed.chain=F for(i in 2:updates) { theta.temp=theta if(i>min(5000,round(burns/2))) { theta=theta+(1-adapt)*rnorm(length(theta),sd=sqrt(2.38^2/length(theta)*diag(covvec)))+adapt*rnorm(length(theta),sd=sqrt(0.1^2/length(theta)*diag(covvec))) }else { theta=theta+rnorm(length(theta),sd=sds) } prop.matrix[,i] = theta rs =solver(X[-nnn],X[-1],c(0,theta),mesh,delt,nnn-1,T.seq[-nnn],P,alpha,lower,upper,TR.order) lnew=sum(rs$like[-excl]) rat=min(exp(lnew-lold)*pp(theta)/pp(theta.temp),1) u=runif(1) is.true =(rat>u) is.false=!is.true theta=theta*is.true+theta.temp*is.false lold=lnew*is.true +lold*is.false errs[i]=rs$max*is.true+errs[i-1]*is.false par.matrix[,i]=theta ll[i]=lold kk=kk+is.true acc[i]=kk/i muvec=muvec +1/(i)*(theta-muvec) covvec = covvec+1/(i)*((theta-muvec)%*%t(theta-muvec)-covvec) if(any(is.na(theta))){print('Fail');failed.chain=T;break;} setTxtProgressBar(pb, i) } close(pb) } tme.eval = function(start_time) { start_time = as.POSIXct(start_time) dt = difftime(Sys.time(), start_time, units="secs") format(.POSIXct(dt,tz="GMT"), "%H:%M:%S") } tme=tme.eval(tme) if(dim(par.matrix)[1]>1) { theta =apply(par.matrix[,-c(1:burns)],1,mean) } if(dim(par.matrix)[1]==1) { theta=mean(par.matrix[,-c(1:burns)]) } meanD=mean(-2*ll[-c(1:burns)]) rs=solver(X[-nnn],X[-1],c(0,theta),mesh,delt,nnn-1,T.seq[-nnn],P,alpha,lower,upper,TR.order) pd=meanD-(-2*sum(rs$like[-excl])) DIC=meanD+pd actual.p=length(theta) model.inf=list(elapsed.time=tme,time.homogeneous=c('Yes','No')[2-homo],p=actual.p,DIC=DIC,pd=pd,N=length(X)-length(excl)+1,Tag=Tag,burns=burns) Info2=c( buffer7, paste0("Chain Updates : ",updates), paste0("Burned Updates : ",burns), paste0("Time Homogeneous : ",c('Yes','No')[2-homo]), paste0("Data Resolution : ",c(paste0('Homogeneous: dt=',round(max(diff(T.seq)[-excl]),4)),paste0('Variable: min(dt)=',round(min(diff(T.seq)[-excl]),4),', max(dt)=',round(max(diff(T.seq)[-excl]),4)))[2-homo.res]), paste0(" paste0("Density approx. : ",sol.state), paste0('Elapsed time : ',tme), buffer3, paste0("dim(theta) : ",round(actual.p,3)), paste0("DIC : ",round(DIC,3)), paste0("pd (eff. dim(theta)): ",round(pd,3)), buffer1) Info2=data.frame(matrix(Info2,length(Info2),1)) colnames(Info2)='' if(print.output) { print(Info2,row.names = FALSE,right=F) } if(plot.chain) { nper=length(theta) if(nper==1){par(mfrow=c(1,2))} if(nper==2){par(mfrow=c(2,2))} if(nper==3){par(mfrow=c(2,2))} if(nper>3) { d1=1:((nper)+1) d2=d1 O=outer(d1,d2) test=O-((nper)+1) test[test<0]=100 test=test[1:4,1:4] test wh=which(test==min(test)) d1=d1[col(test)[wh[1]]] d2=d2[row(test)[wh[1]]] par(mfrow=c(d1,d2)) } if(palette=='mono') { cols =rep(' }else{ cols=rainbow_hcl(nper, start = 10, end = 275,c=100,l=70) } ylabs=paste0('theta[',1:nper,']') for(i in 1:nper) { plot(prop.matrix[i,],col='gray90',type='s',main=ylabs[i],xlab='Iteration',ylab='') lines(par.matrix[i,],col=cols[i],type='s') abline(v=burns,lty='dotdash') if(adapt!=0){abline(v=min(5000,round(burns/2)),lty='dotted',col='red')} } plot(acc,type='l',ylim=c(0,1),col='darkblue',main='Accept. Rate',xlab='Iteration',ylab='%/100') abline(h=seq(0,1,1/10),lty='dotted') abline(v=burns,lty='dotdash') abline(h=0.4,lty='solid',col='red',lwd=1.2) abline(h=0.2,lty='solid',col='red',lwd=1.2) box() } ret=list(par.matrix=t(par.matrix),acceptance.rate=acc,elapsed.time=tme,model.info=model.inf,failed.chain=failed.chain,covvec=covvec,prop.matrix=t(prop.matrix),errors = errs) class(ret) = 'GQD.mcmc' return(ret) }
abs_units = c("cm", "inches", "mm", "points", "picas", "bigpts", "dida", "cicero", "scaledpts", "lines", "char", "strwidth", "strheight", "grobwidth", "grobheight", "strascent", "strdescent", "mylines", "mychar", "mystrwidth", "mystrheight", "centimetre", "centimetres", "centimeter", "centimeters", "in", "inch", "line", "millimetre", "millimetres", "millimeter", "millimeters", "point", "pt") .is_abs_unit.unit = function(x) { unit = unitType(x) if(all(unit %in% abs_units)) { return(TRUE) } else { return(FALSE) } } .is_abs_unit.unit.list = function(x) { all(sapply(x, function(y) { if(inherits(y, "unit.arithmetic")) .is_abs_unit.unit.arithmetic(y) else if(inherits(y, "unit.list")) .is_abs_unit.unit.list(y) else if(inherits(y, "unit")) .is_abs_unit.unit(y) else FALSE })) } .is_abs_unit.unit.arithmetic = function(x) { all(sapply(x, function(y) { if(inherits(y, "unit.arithmetic")) .is_abs_unit.unit.arithmetic(y) else if(inherits(y, "unit.list")) .is_abs_unit.unit.list(y) else if(inherits(y, "unit")) .is_abs_unit.unit(y) else TRUE })) } .is_abs_unit.default = function(x) { FALSE } is_abs_unit = function(u) { NULL } is_abs_unit_v3 = function(u) { if(inherits(u, "unit.arithmetic")) .is_abs_unit.unit.arithmetic(u) else if(inherits(u, "unit.list")) .is_abs_unit.unit.list(u) else if(inherits(u, "unit")) .is_abs_unit.unit(u) else FALSE } is_abs_unit_v4 = function(u) { u = unitType(u, recurse = TRUE) u = unlist(u) all(u %in% abs_units) } rv = R.Version() if(getRversion() >= "4.0.0" && as.numeric(rv$`svn rev`) >= 77889) { is_abs_unit = is_abs_unit_v4 } else { is_abs_unit = is_abs_unit_v3 }
testIndQBinom = function(target, dataset, xIndex, csIndex, wei = NULL, univariateModels = NULL , hash = FALSE, stat_hash = NULL, pvalue_hash = NULL) { pvalue = log(1); stat = 0; csIndex[which(is.na(csIndex))] = 0; if( hash ) { csIndex2 = csIndex[which(csIndex!=0)] csIndex2 = sort(csIndex2) xcs = c(xIndex,csIndex2) key = paste(as.character(xcs) , collapse=" "); if( !is.null(stat_hash[key]) ){ stat = stat_hash[key]; pvalue = pvalue_hash[key]; results <- list(pvalue = pvalue, stat = stat, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); } } if ( !is.na( match(xIndex, csIndex) ) ) { if( hash ) { stat_hash[key] <- 0; pvalue_hash[key] <- log(1); } results <- list(pvalue = log(1), stat = 0, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); } if( any(xIndex < 0) || any(csIndex < 0) ) { message(paste("error in testIndPois : wrong input of xIndex or csIndex")) results <- list(pvalue = pvalue, stat = stat, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); } xIndex = unique(xIndex); csIndex = unique(csIndex); x = dataset[ , xIndex]; cs = dataset[ , csIndex]; if ( length(cs)!=0 ) { if ( is.null(dim(cs)[2]) ) { if ( identical(x, cs) ) { if ( hash ) { stat_hash[key] <- 0; pvalue_hash[key] <- log(1); } results <- list(pvalue = log(1), stat = 0, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results) } } else { for ( col in 1:dim(cs)[2] ) { if (identical(x, cs[, col]) ) { if( hash ) { stat_hash[key] <- 0 pvalue_hash[key] <- log(1) } results <- list(pvalue = log(1), stat = 0, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); } } } } if (length(cs) == 0) { fit1 <- glm(target ~ 1, family = quasibinomial(link = logit), weights = wei ,model = FALSE) fit2 <- glm(target ~ x, family = quasibinomial(link = logit), weights = wei ,model = FALSE) } else { fit1 = glm(target ~., data = as.data.frame( cs ), family = quasibinomial(link = logit), weights = wei, model = FALSE) fit2 = glm(target ~., data = as.data.frame( dataset[, c(csIndex, xIndex)] ), family = quasibinomial(link = logit), weights = wei, model = FALSE) } mod <- anova(fit1, fit2, test = "F") stat <- mod[2, 5] df1 <- mod[2, 3] df2 <- mod[2, 1] pvalue = pf( stat, df1, df2, lower.tail = FALSE, log.p = TRUE ) if ( is.na(pvalue) || is.na(stat) ) { pvalue = log(1); stat = 0; } else { if ( hash ) { stat_hash[key] <- stat; pvalue_hash[key] <- pvalue; } } results <- list(pvalue = pvalue, stat = stat, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results) }
cutoffSensitivityPlot <- function(predTest,depTest,metric=c("accuracy","expMisclassCost","misclassCost"),costType=c("costRatio","costMatrix","costVector"),costs=NULL,resolution=1/50) { checkDepVector(depTest) if (metric=="expMisclassCost" && costType=="costVector") stop("Cost vectors are not supported for the misclassification cost. Use expMisclassCost.") tmp <- unique(depTest) depvalues <- tmp[order(tmp)] yp = cbind(as.factor(depTest),predTest) perc_list <- seq(0,1,resolution)[-1] perf = mat.or.vec(length(perc_list),1) for (perc_idx in 1:length(perc_list)) { if (metric=="accuracy") { perf[perc_idx]<-dynAccuracy(predTest,depTest,dyn.cutoff=FALSE,cutoff=perc_list[perc_idx])[[1]] multiplier<-1 } else if (metric=="expMisclassCost") { perf[perc_idx]<-expMisclassCost(predTest,depTest,costType=costType, costs=costs,cutoff=perc_list[perc_idx])[[1]] multiplier<- -1 } else if (metric=="misclassCost") { perf[perc_idx]<-misclassCost(predTest,depTest,costType=costType, costs=costs,cutoff=perc_list[perc_idx])[[1]] multiplier<- -1 } } plot(perc_list,perf,type="b",xlab="Cutoff",ylab=metric, main="Cutoff sensitivity Chart") perf2<-multiplier*perf lines(perc_list[which(perf2==max(perf2))],rep(max(perf2),length(perc_list[which(perf2==max(perf2))])),type="b",col=34) lines(perc_list[which(perf2==max(perf2))],rep(max(perf2),length(perc_list[which(perf2==max(perf2))])),type="h",col=34) text(perc_list[which(perf2==max(perf2))][1],abs(min(perf)), paste("optimal cutoff =",perc_list[which(perf2==max(perf2))][1]), cex=1) }
nobs.tvgarch <- function (object, ...) { return(length(object$sigma2)) }
set.genomic.region.subregion <- function(x, regions, subregions, split = TRUE) { if(!is.factor(regions$Name) | !is.factor(subregions$Name)) stop("regions$Name and subregions$Name should be factors with levels ordered in the genome order") if(typeof(x@snps$chr) != "integer") stop("x@snps$chr should be either a vector of integers, or a factor with same levels as regions$Chr") regions$Start <- regions$Start + 1 w <- duplicated(regions$Name) if(any(w)) { regions <- regions[!w,] } n <- nrow(regions) chr1 <- regions$Chr[1:(n-1)] chr2 <- regions$Chr[2:n] b <- (chr1 < chr2) | (chr1 == chr2 & regions$Start[1:(n-1)] <= regions$Start[2:n]) if(!all(b)) { regions <- regions[ order(regions$Chr, regions$Start), ] } n <- nrow(subregions) chr1 <- subregions$Chr[1:(n-1)] chr2 <- subregions$Chr[2:n] b <- (chr1 < chr2) | (chr1 == chr2 & subregions$Start[1:(n-1)] <= subregions$Start[2:n]) if(!all(b)) { subregions <- subregions[ order(subregions$Chr, subregions$Start), ] } R <- .Call("label_multiple_genes", PACKAGE = "Ravages", regions$Chr, regions$Start, regions$End, x@snps$chr, x@snps$pos) R.genename <- unlist(lapply(R, function(z) paste(levels(regions$Name)[unlist(z)], collapse=","))) R.genename[which(R.genename=="")] <- NA x@snps$genomic.region <- R.genename x@snps$genomic.region <- factor(x@snps$genomic.region, levels = unique(x@snps$genomic.region)) if(any(grepl(x@snps$genomic.region, pattern = ","))){ x <- bed.matrix.split.genomic.region(x, genomic.region = x@snps$genomic.region, split.pattern = ",") } Rsub <- .Call("label_multiple_genes", PACKAGE = "Ravages", subregions$Chr, subregions$Start, subregions$End, x@snps$chr, x@snps$pos) Rsub.genename <- unlist(lapply(Rsub, function(z) paste(subregions$Name[unlist(z)], collapse=","))) Rsub.genename[which(Rsub.genename=="")] <- NA x@snps$SubRegion <- Rsub.genename x@snps$SubRegion <- factor(x@snps$SubRegion, levels = unique(x@snps$SubRegion)) x }
context("ui slider") test_that("test slider_input", { expect_is(slider_input("slider_input", 10, 0, 20), "shiny.tag") expect_error(slider_input()) si_str <- as.character(slider_input("slider_input", 10, 0, 20)) expect_true(grepl( paste("<div id=\"slider_input\" class=\"ui slider ss-slider labeled\" data-min=\"0\"", "data-max=\"20\" data-step=\"1\" data-start=\"10\">"), si_str )) }) test_that("test sliderInput", { expect_error(sliderInput("slider_input"), "\"value\" is missing") si_str <- as.character(sliderInput("slider_input", "Label", 10, 0, 20)) expect_true(grepl( "<form class=\"ui form \">\n <label>Label</label>\n", si_str )) expect_true(grepl( "data-max=\"0\" data-step=\"1\" data-start=\"20\"></div>", si_str )) }) test_that("test range_input", { expect_is(range_input("range_input", 10, 15, 0, 20), "shiny.tag") expect_error(range_input()) si_str <- as.character(range_input("range_input", 10, 15, 0, 20)) expect_true(grepl(paste( "<div id=\"range_input\" class=\"ui range slider ss-slider \" data-min=\"0\" data-max=\"20\"", "data-step=\"1\" data-start=\"10\" data-end=\"15\">" ), si_str)) })
ZAP <- function (mu.link = "log", sigma.link = "logit") { mstats <- checklink("mu.link", "ZAP", substitute(mu.link), c("1/mu^2", "log", "identity")) dstats <- checklink("sigma.link", "ZAP", substitute(sigma.link), c("logit", "probit", "cloglog", "cauchit", "log", "own")) structure( list(family = c("ZAP", "Zero Adjusted Poisson"), parameters = list(mu=TRUE, sigma=TRUE), nopar = 2, type = "Discrete", mu.link = as.character(substitute(mu.link)), sigma.link = as.character(substitute(sigma.link)), mu.linkfun = mstats$linkfun, sigma.linkfun = dstats$linkfun, mu.linkinv = mstats$linkinv, sigma.linkinv = dstats$linkinv, mu.dr = mstats$mu.eta, sigma.dr = dstats$mu.eta, dldm = function(y,mu,sigma) {dldm0 <- PO()$dldm(y,mu) + dPO(0,mu)*PO()$dldm(0,mu)/(1-dPO(0,mu)) dldm <- ifelse(y==0, 0 , dldm0) dldm}, d2ldm2 = function(y,mu,sigma) {dldm0 <- PO()$dldm(y,mu) + dPO(0,mu)*PO()$dldm(0,mu)/(1-dPO(0,mu)) dldm <- ifelse(y==0, 0 , dldm0) d2ldm2 <- -dldm*dldm d2ldm2}, dldd = function(y,mu,sigma) {dldd <- ifelse(y==0, 1/sigma, -1/(1-sigma)) dldd}, d2ldd2 = function(y,mu,sigma) {d2ldd2 <- -1/(sigma*(1-sigma)) d2ldd2}, d2ldmdd = function(y,mu,sigma) {d2ldmdd <- 0 d2ldmdd }, G.dev.incr = function(y,mu,sigma,...) -2*dZAP(y,mu,sigma,log=TRUE), rqres = expression(rqres(pfun="pZAP", type="Discrete", ymin=0, y=y, mu=mu, sigma=sigma)) , mu.initial = expression(mu <- (y+mean(y))/2), sigma.initial = expression(sigma <-rep(0.3, length(y))), mu.valid = function(mu) all(mu > 0) , sigma.valid = function(sigma) all(sigma > 0 & sigma < 1), y.valid = function(y) all(y >= 0), mean = function(mu, sigma) { c <- (1 - sigma) / (1- exp(-mu)) return( c * mu ) }, variance = function(mu, sigma, nu) { c <- (1 - sigma) / (1- exp(-mu)) return(c * mu + c * mu^2 - c^2 * mu^2 ) } ), class = c("gamlss.family","family")) } dZAP<-function(x, mu = 5, sigma = 0.1, log = FALSE) { if (any(mu <= 0) ) stop(paste("mu must be greater than 0", "\n", "")) if (any(sigma <= 0) | any(sigma >= 1) ) stop(paste("sigma must be between 0 and 1", "\n", "")) if (any(x < 0) ) stop(paste("x must be 0 or greater than 0", "\n", "")) ly <- max(length(x),length(mu),length(sigma)) x <- rep(x, length = ly) sigma <- rep(sigma, length = ly) mu <- rep(mu, length = ly) logfy <- rep(0, ly) logfy <- ifelse((x==0), log(sigma), log(1-sigma) + dPO(x,mu,log=T) - log(1-dPO(0,mu)) ) if(log == FALSE) fy <- exp(logfy) else fy <- logfy fy } pZAP <- function(q, mu = 5, sigma = 0.1, lower.tail = TRUE, log.p = FALSE) { if (any(mu <= 0) ) stop(paste("mu must be greater than 0", "\n", "")) if (any(sigma <= 0) | any(sigma >= 1) ) stop(paste("sigma must be between 0 and 1", "\n", "")) if (any(q < 0) ) stop(paste("y must be 0 or greater than 0", "\n", "")) ly <- max(length(q),length(mu),length(sigma)) q <- rep(q, length = ly) sigma <- rep(sigma, length = ly) mu <- rep(mu, length = ly) cdf <- rep(0,ly) cdf1 <- ppois(q, lambda = mu, lower.tail = TRUE, log.p = FALSE) cdf2 <- ppois(0, lambda = mu, lower.tail = TRUE, log.p = FALSE) cdf3 <- sigma+((1-sigma)*(cdf1-cdf2)/(1-cdf2)) cdf <- ifelse((q==0),sigma, cdf3) if(lower.tail == TRUE) cdf <- cdf else cdf <-1-cdf if(log.p==FALSE) cdf <- cdf else cdf <- log(cdf) cdf } qZAP <- function(p, mu = 5, sigma = 0.1, lower.tail = TRUE, log.p = FALSE) { if (any(mu <= 0) ) stop(paste("mu must be greater than 0", "\n", "")) if (any(sigma <= 0) ) stop(paste("sigma must be greater than 0", "\n", "")) if (any(p <= 0) | any(p >= 1)) stop(paste("p must be between 0 and 1", "\n", "")) if (log.p == TRUE) p <- exp(p) else p <- p if (lower.tail == TRUE) p <- p else p <- 1 - p ly <- max(length(p),length(mu),length(sigma)) p <- rep(p, length = ly) sigma <- rep(sigma, length = ly) mu <- rep(mu, length = ly) pnew <- (p-sigma)/(1-sigma) pnew2 <- ppois(0, lambda = mu, lower.tail = TRUE, log.p = FALSE)*(1-pnew) + pnew suppressWarnings(q <- ifelse((pnew > 0 ), qpois(pnew2, lambda = mu, ), 0)) q } rZAP <- function(n, mu=5, sigma=0.1) { if (any(mu <= 0) ) stop(paste("mu must greated than 0", "\n", "")) if (any(sigma <= 0) ) stop(paste("sigma must greated than 0", "\n", "")) if (any(n <= 0)) stop(paste("n must be a positive integer", "\n", "")) n <- ceiling(n) p <- runif(n) r <- qZAP(p, mu = mu, sigma = sigma) as.integer(r) }
semLme <- function(formula, data, classes, burnin = 40, samples = 200, trafo = "None", adjust = 2, bootstrap.se = FALSE, b = 100) { call <- match.call() o.classes <- classes o.data <- data o.formula <- formula lambda <- result_lambda <- b.lambda <- m.lambda <- se <- ci <- NULL if (trafo == "log") { classes <- log.est(y = classes) } if (trafo == "bc") { suppressWarnings(lambda.est <- lambda.lme.est( formula = formula, data = data, classes = classes, burnin = burnin, samples = samples, adjust = adjust )) lambda <- lambda.est$lambda result_lambda <- lambda.est$it.lambda b.lambda <- lambda.est$b.lambda m.lambda <- lambda.est$m.lambda BoxCoxClasses <- boxcox.lme.est(dat = classes, lambda = lambda, inverse = FALSE) classes <- BoxCoxClasses[[1]] } data <- midpoints.est(formula = formula, data = data, classes = classes) formula <- as.formula(gsub(".*~", "pseudoy~", formula)) regclass <- lmer(formula, data = data) resulty <- matrix(ncol = c(burnin + samples), nrow = nrow(data)) resultcoef <- matrix(ncol = c(burnin + samples), nrow = length(regclass@beta)) result_ranef <- vector("list", burnin + samples) result_sigmae <- vector(mode = "numeric", length = burnin + samples) result_r2c <- vector(mode = "numeric", length = burnin + samples) result_r2m <- vector(mode = "numeric", length = burnin + samples) result_icc <- vector(mode = "numeric", length = burnin + samples) VaCovMa <- vector("list", burnin + samples) for (j in 1:(burnin + samples)) { data$predict <- predict(regclass, data) sigmahat <- sigma(regclass) for (i in 1:(length(classes) - 1)) { if (nrow(data[data$yclassl == i, ]) != 0) { mean <- data$predict[data$yclassl == i] pseudoy <- rtruncnorm(length(mean), a = classes[i], b = classes[i + 1], mean = mean, sd = sigmahat) data$pseudoy[data$yclassl == i] <- pseudoy } } regclass <- lmer(formula, data = data) resultcoef[, j] <- regclass@beta result_ranef[[j]] <- as.matrix(ranef(regclass)[[1]]) result_sigmae[j] <- sigmahat r_squared <- r.squaredGLMM(regclass) if (is.matrix(r_squared)) { result_r2m[j] <- unname(r_squared[1, 1]) result_r2c[j] <- unname(r_squared[1, 2]) } else { result_r2m[j] <- unname(r_squared[1]) result_r2c[j] <- unname(r_squared[2]) } result_icc[j] <- icc.est(model = regclass) resulty[, j] <- data$pseudoy VaCovMa[[j]] <- as.matrix(unclass(VarCorr(regclass))[[1]][1:ncol(ranef(regclass)[[1]]), ]) } parameter.ma <- list(ranef = result_ranef, VaCov = VaCovMa) parameter.final.ma <- parameters.est.ma(parameter = parameter.ma, burnin = burnin) colnames(parameter.final.ma$VaCov) <- colnames(VaCovMa[[1]]) rownames(parameter.final.ma$VaCov) <- rownames(VaCovMa[[1]]) colnames(parameter.final.ma$ranef) <- colnames(result_ranef[[1]]) parameter <- list( coef = resultcoef, sigmae = result_sigmae, r2m = result_r2m, r2c = result_r2c, icc = result_icc ) parameter.final <- parameters.est(parameter = parameter, burnin = burnin) names(parameter.final$coef) <- rownames(summary(regclass)$coefficients) if (bootstrap.se == TRUE) { result_se <- standardErrorLME.est( formula = o.formula, data = o.data, classes = o.classes, burnin = burnin, samples = samples, trafo = trafo, adjust = adjust, b = b, coef = parameter.final$coef, sigmae = parameter.final$sigmae, VaCov = parameter.final.ma$VaCov, nameRI = names(ranef(regclass)), nameRS = names(ranef(regclass)[[1]])[2], regmodell = regclass, lambda = m.lambda ) se <- result_se$se ci <- result_se$ci rownames(ci) <- names(parameter.final$coef) } est <- list( pseudo.y = resulty, coef = parameter.final$coef, ranef = parameter.final.ma$ranef, sigmae = parameter.final$sigmae, VaCov = parameter.final.ma$VaCov, se = se, ci = ci, lambda = lambda, bootstraps = b, r2m = parameter.final$r2m, r2c = parameter.final$r2c, icc = parameter.final$icc, formula = o.formula, transformation = trafo, n.classes = length(classes) - 1, conv.coef = resultcoef, conv.sigmae = result_sigmae, conv.lambda = result_lambda, conv.VaCov = VaCovMa, b.lambda = b.lambda, m.lambda = m.lambda, burnin = burnin, samples = samples, classes = o.classes, original.y = data$y, call = call ) class(est) <- c("sem", "lme") return(est) }
mc_link_function <- function(beta, X, offset, link) { assert_that(noNA(beta)) assert_that(noNA(X)) if (!is.null(offset)) assert_that(noNA(offset)) link_name <- c("logit", "probit", "cauchit", "cloglog", "loglog", "identity", "log", "sqrt", "1/mu^2", "inverse") link_func <- c("mc_logit", "mc_probit", "mc_cauchit", "mc_cloglog", "mc_loglog", "mc_identity", "mc_log", "mc_sqrt", "mc_invmu2", "mc_inverse") names(link_func) <- link_name if (!link %in% link_name) { if (!exists(link, envir = -1, mode = "function")) { stop(gettextf(paste0( "%s link function not recognised or found. ", "Available links are: ", paste(link_name, collapse = ", "), "."), sQuote(link)), domain = NA) } else { match_args <- sort(names(formals(link))) %in% sort(c("beta", "X", "offset")) if (length(match_args) != 3L || !all(match_args)) { stop(gettextf(paste( "Provided link function must have %s, %s and %s", "as arguments to be valid."), sQuote("beta"), sQuote("X"), sQuote("offset")), domain = NA) } } output <- do.call(link, args = list(beta = beta, X = X, offset = offset)) if (!is.list(output)) { stop("Provided link funtion doesn't return a list.") } if (!identical(sort(names(output)), c("D","mu"))) { stop(paste0("Provided link funtion isn't return ", "a list with names ", sQuote("mu"), " and ", sQuote("D"), ".")) } if (!(identical(dim(output$D), dim(X)) && is.matrix(output$D))) { stop(paste0("Returned ", sQuote("D"), " object by user defined link function ", "isn't a matrix of correct dimensions.")) } print(is.vector(output$mu, mode = "vector")) print(class(output$mu)) if (!(length(output$mu) == nrow(X) && is.vector(output$mu, mode = "numeric"))) { stop(paste0("Returned ", sQuote("mu"), " object by user defined link function ", "isn't a vector of correct length.")) is.vector(output$mu, mode = "vector") } } else { link <- link_func[link] output <- do.call(link, args = list(beta = beta, X = X, offset = offset)) } return(output) } mc_logit <- function(beta, X, offset) { eta <- as.numeric(X %*% beta) if (!is.null(offset)) { eta <- eta + offset } mu <- make.link("logit")$linkinv(eta = eta) return(list(mu = mu, D = X * (mu * (1 - mu)))) } mc_probit <- function(beta, X, offset) { eta <- as.numeric(X %*% beta) if (!is.null(offset)) { eta <- eta + offset } mu <- make.link("probit")$linkinv(eta = eta) Deri <- make.link("probit")$mu.eta(eta = eta) return(list(mu = mu, D = X * Deri)) } mc_cauchit <- function(beta, X, offset) { eta <- as.numeric(X %*% beta) if (!is.null(offset)) { eta <- eta + offset } mu = make.link("cauchit")$linkinv(eta = eta) Deri <- make.link("cauchit")$mu.eta(eta = eta) return(list(mu = mu, D = X * Deri)) } mc_cloglog <- function(beta, X, offset) { eta <- as.numeric(X %*% beta) if (!is.null(offset)) { eta <- eta + offset } mu = make.link("cloglog")$linkinv(eta = eta) Deri <- make.link("cloglog")$mu.eta(eta = eta) return(list(mu = mu, D = X * Deri)) } mc_loglog <- function(beta, X, offset) { eta <- as.numeric(X %*% beta) if (!is.null(offset)) { eta <- eta + offset } mu <- exp(-exp(-eta)) Deri <- exp(-exp(-eta) - eta) return(list(mu = mu, D = X * Deri)) } mc_identity <- function(beta, X, offset) { eta <- X %*% beta if (!is.null(offset)) { eta <- eta + offset } return(list(mu = as.numeric(eta), D = X)) } mc_log <- function(beta, X, offset) { eta <- as.numeric(X %*% beta) if (!is.null(offset)) { eta <- eta + offset } mu = make.link("log")$linkinv(eta = eta) return(list(mu = mu, D = X * mu)) } mc_sqrt <- function(beta, X, offset) { eta <- as.numeric(X %*% beta) if (!is.null(offset)) { eta <- eta + offset } mu = make.link("sqrt")$linkinv(eta = eta) return(list(mu = mu, D = X * (2 * as.numeric(eta)))) } mc_invmu2 <- function(beta, X, offset) { eta <- as.numeric(X %*% beta) if (!is.null(offset)) { eta <- eta + offset } mu <- make.link("1/mu^2")$linkinv(eta = eta) Deri <- make.link("1/mu^2")$mu.eta(eta = eta) return(list(mu = mu, D = X * Deri)) } mc_inverse <- function(beta, X, offset) { eta <- as.numeric(X %*% beta) if (!is.null(offset)) { eta <- eta + offset } mu <- make.link("inverse")$linkinv(eta = eta) Deri <- make.link("inverse")$mu.eta(eta = eta) return(list(mu = mu, D = X * Deri)) }
ps.model <- function(dat, form.ps) { fm <- glm( formula = as.formula( form.ps ), data = dat, family = binomial(link = "logit")); ps.hat <- as.numeric(predict(fm, newdata = dat, type = "response")); ps.hat <- pmin(pmax(0.000001, ps.hat), 0.999999); return( list( ps.hat = ps.hat, fm = fm ) ); } psw.balance.core <- function( Xmat, Xname, weight, W, Z ) { out1 <- NULL ; for ( j in 1 : length( Xname ) ) { this.name <- Xname[j]; this.var <- as.numeric( Xmat[ , this.name ] ); tmp <- calc.std.diff( var.value = this.var, wt = rep(1, length = nrow( Xmat ) ), Z = Z ); out1 <- rbind(out1, tmp ); } rownames(out1) <- Xname; colnames(out1) <- c("treated.mean","treated.sd","control.mean","control.sd","std.diff.pct"); std.diff.before <- out1; out1 <- NULL; for ( j in 1 : length( Xname ) ) { this.name <- Xname[j]; this.var <- as.numeric( Xmat[ , this.name ] ); tmp <- calc.std.diff( var.value = this.var, wt = W, Z = Z); out1 <- rbind(out1, tmp); } rownames(out1) <- Xname; colnames(out1) <- c("treated.mean","treated.sd","control.mean","control.sd","std.diff.pct"); std.diff.after <- out1; diff.plot( diff.before = std.diff.before[ , "std.diff.pct" ], diff.after = std.diff.after[ , "std.diff.pct" ], name = Xname, weight = weight ); return( list( std.diff.before = std.diff.before, std.diff.after = std.diff.after ) ); } psw.wt.core <- function( dat, beta.hat, omega, Q, trt.var, out.var, family, Xname, weight, delta=0.002, K=4 ) { n <- nrow(dat); mu1.hat <- sum( ( omega / Q ) * dat[ , trt.var ] * dat[ , out.var ] ) / sum( ( omega / Q ) * dat[ , trt.var ] ); mu0.hat <- sum( ( omega / Q ) * ( 1 - dat[ , trt.var ]) * dat[ , out.var ] ) / sum( ( omega / Q ) * ( 1 - dat[ , trt.var ] ) ); if ( family == "gaussian" ) { est <- mu1.hat - mu0.hat; } if ( family == "binomial" ) { est.risk <- mu1.hat - mu0.hat; est.rr <- mu1.hat / mu0.hat; est.or <- ( mu1.hat / ( 1 - mu1.hat ) ) / ( mu0.hat / ( 1 - mu0.hat ) ); est.lor <- log( est.or ); } Amat <- Bmat <- 0; for (i in 1 : n) { Xi <- as.numeric( c( 1, dat[ i, Xname ] ) ); Zi <- dat[ i, trt.var ]; Yi <- dat[ i, out.var ]; ei <- calc.ps.Xbeta( Xmat = Xi, beta = beta.hat ); ei.deriv1 <- calc.ps.deriv1( Xmat = Xi, beta = beta.hat ); ei.deriv2 <- calc.ps.deriv2( Xi = Xi, beta = beta.hat ); omega.ei <- omega[ i ]; omegaei.deriv <- omega.derive.ei( ps = ei, weight = weight, delta = delta, K=K ); Qi <- Q[i]; Qi.deriv <- 2*Zi - 1; phi <- c( Zi * ( Yi - mu1.hat ) * omega.ei / Qi, ( 1 - Zi ) * ( Yi - mu0.hat ) * omega.ei / Qi, ( Zi -ei ) / ( ei * ( 1 - ei ) ) * ei.deriv1 ); Bmat <- Bmat + outer( phi, phi ); first.row <- c( - Zi * omega.ei / Qi, 0, Zi * ( Yi - mu1.hat ) * ei.deriv1 * ( Qi * omegaei.deriv - omega.ei * Qi.deriv ) / Qi^2 ); second.row <- c( 0, - ( 1 - Zi ) * omega.ei / Qi, ( 1 - Zi ) * ( Yi - mu0.hat ) * ei.deriv1 * ( Qi * omegaei.deriv - omega.ei * Qi.deriv ) / Qi^2 ); tmp0 <- matrix( 0, nrow = length( beta.hat ), ncol = 2 ); tmp1 <- - ei * ( 1 - ei ) * colVec( Xi ) %*% Xi; third.row <- cbind( tmp0, tmp1 ); phi.deriv <- rbind( first.row, second.row, third.row ); Amat <- Amat + phi.deriv; } Amat <- Amat/n; Bmat <- Bmat/n; Amat.inv <- solve( Amat ); var.mat <- ( Amat.inv %*% Bmat %*% t( Amat.inv ) ) / n; var.mat <- var.mat[ c( 1 : 2 ), c( 1 : 2 ) ]; if ( family == "gaussian" ) { tmp1 <- c( 1, -1 ); var.est <- rowVec( tmp1 ) %*% var.mat %*% colVec( tmp1 ); std <- sqrt( as.numeric( var.est ) ); ans <- list( est = est, std = std ); } if ( family == "binomial" ) { tmp.risk <- c( 1, -1 ); var.risk <- rowVec( tmp.risk ) %*% var.mat %*% colVec( tmp.risk ); std.risk <- sqrt( as.numeric( var.risk ) ); tmp.rr <- c( 1 / mu1.hat, - mu1.hat / ( mu0.hat^2 ) ); var.rr <- rowVec( tmp.rr ) %*% var.mat %*% colVec( tmp.rr ); std.rr <- sqrt( as.numeric( var.rr ) ); tmp1 <- ( 1 - mu0.hat ) / ( mu0.hat * ( 1 - mu1.hat )^2 ); tmp0 <- - mu1.hat / ( ( 1 - mu1.hat ) * mu0.hat^2 ); tmp.or <- c( tmp1, tmp0 ); var.or <- rowVec( tmp.or ) %*% var.mat %*% colVec( tmp.or ); std.or <- sqrt( as.numeric( var.or ) ); tmp1 <- 1/( mu1.hat * ( 1 - mu1.hat ) ); tmp0 <- - 1/( mu0.hat * ( 1 - mu0.hat ) ); tmp.lor <- c( tmp1, tmp0 ); var.lor <- rowVec( tmp.lor ) %*% var.mat %*% colVec( tmp.lor ); std.lor <- sqrt( as.numeric( var.lor ) ); ans <- list( est.risk = est.risk, std.risk = std.risk, est.rr = est.rr, std.rr = std.rr, est.or = est.or, std.or = std.or, est.lor = est.lor, std.lor = std.lor ); } return( ans ); } psw.aug.core <- function(dat, beta.hat, omega, Q, out.ps, out.outcome, trt.var, out.var, weight, family, K, delta=0.002){ n <- nrow( dat ); W <- omega/Q; tmp1 <- W*dat[ , trt.var ]; mu1.hat <- sum( tmp1*(dat[ , out.var ] - out.outcome$Y.hat.m1) )/sum( tmp1 ); mu2.hat <- sum( omega*out.outcome$Y.hat.m1 )/sum( omega ); tmp0 <- W*( 1 - dat[ , trt.var ] ); mu3.hat <- sum( tmp0*(dat[ , out.var ] - out.outcome$Y.hat.m0) )/sum( tmp0 ); mu4.hat <- sum( omega*out.outcome$Y.hat.m0 )/sum( omega ); if ( family == "gaussian" ) { est <- mu1.hat + mu2.hat - mu3.hat - mu4.hat; } if ( family == "binomial" ) { p1.hat <- mu1.hat + mu2.hat; p0.hat <- mu3.hat + mu4.hat; est.risk <- p1.hat - p0.hat; est.rr <- p1.hat/p0.hat; est.or <- (p1.hat/(1-p1.hat)) / (p0.hat/(1-p0.hat)); est.lor <- log( est.or ); } alpha1.hat <- as.numeric( coef(out.outcome$fm1) ); alpha0.hat <- as.numeric( coef(out.outcome$fm0) ); beta.hat <- as.numeric( coef(out.ps$fm) ); n.alpha1 <- length( alpha1.hat ); n.alpha0 <- length( alpha0.hat ); n.beta <- length( beta.hat ); n <- nrow(dat); Amat <- Bmat <- 0; for (i in 1:n) { Xi <- as.numeric( c(1, dat[i, names(coef(out.ps$fm))[-1] ] ) ); Vi <- as.numeric( c(1, dat[i, names(coef(out.outcome$fm1))[-1] ] ) ); Zi <- dat[ i, trt.var ] ; Yi <- dat[ i, out.var ] ; Wi <- W[i]; Qi <- Q[i]; omegai <- omega[i]; ei <- calc.ps.Xbeta(Xmat=Xi, beta=beta.hat); ei.deriv1 <- calc.ps.deriv1(Xmat=Xi, beta=beta.hat); ei.deriv2 <- calc.ps.deriv2( Xi=Xi, beta=beta.hat); Wi.deriv.beta <- calc.W.derive.beta( Zi=Zi, Xi=Xi, omega.ei=omegai, beta.hat=beta.hat, ei=ei, Qi=Qi, weight=weight, delta=delta, K=K ); omegai.deriv.beta <- calc.omega.derive.beta( Xi=Xi, beta.hat=beta.hat, ei=ei, weight=weight, delta=delta, K=K ); if ( family == "gaussian" ) { m1.hat <- sum(Vi*alpha1.hat); m0.hat <- sum(Vi*alpha0.hat); m1.deriv.alpha1 <- Vi; m0.deriv.alpha0 <- Vi; s1.deriv.alpha1 <- -outer(Vi, Vi); s0.deriv.alpha0 <- -outer(Vi, Vi); } if ( family == "binomial" ) { tmp1 <- sum(Vi*alpha1.hat); tmp0 <- sum(Vi*alpha0.hat); m1.hat <- exp(tmp1)/(1+exp(tmp1)); m0.hat <- exp(tmp0)/(1+exp(tmp0)); m1.deriv.alpha1 <- m1.hat*(1-m1.hat)*Vi; m0.deriv.alpha0 <- m0.hat*(1-m0.hat)*Vi; s1.deriv.alpha1 <- -m1.hat*(1-m1.hat)*outer(Vi, Vi); s0.deriv.alpha0 <- -m0.hat*(1-m0.hat)*outer(Vi, Vi); } this.phi.row1 <- Wi*Zi*( Yi - m1.hat - mu1.hat ); this.phi.row2 <- omegai*( m1.hat - mu2.hat ); this.phi.row3 <- Wi*(1-Zi)*( Yi - m0.hat - mu3.hat ); this.phi.row4 <- omegai*( m0.hat - mu4.hat ); this.phi.row5 <- Zi*( Yi - m1.hat )*Vi; this.phi.row6 <- (1-Zi)*( Yi - m0.hat )*Vi; this.phi.row7 <- (Zi-ei)/ei/(1-ei)*ei.deriv1; this.phi <- c( this.phi.row1, this.phi.row2, this.phi.row3, this.phi.row4, this.phi.row5, this.phi.row6, this.phi.row7 ); Bmat <- Bmat + outer( this.phi, this.phi ); quad1 <- diag( c( -Wi*Zi, -omegai, -Wi*(1-Zi), -omegai ) ); quad2 <- matrix(0, nrow=n.alpha1+n.alpha0+n.beta, ncol=4); tmp <- c( -Wi*Zi*m1.deriv.alpha1, rep(0, n.alpha0), Zi*( Yi - m1.hat - mu1.hat )*Wi.deriv.beta, omegai*m1.deriv.alpha1, rep(0, n.alpha0), ( m1.hat - mu2.hat )*omegai.deriv.beta, rep(0, n.alpha1), -Wi*(1-Zi)*m0.deriv.alpha0, (1-Zi)*( Yi - m0.hat - mu3.hat )*Wi.deriv.beta, rep(0, n.alpha1), omegai*m0.deriv.alpha0, ( m0.hat - mu4.hat )*omegai.deriv.beta ); quad3 <- matrix( tmp, byrow = TRUE, nrow = 4, ncol = n.alpha1 + n.alpha0 + n.beta ); quad4.blk1 <- cbind( Zi*s1.deriv.alpha1, matrix(0, nrow=n.alpha1, ncol=n.alpha0 + n.beta) ); quad4.blk2 <- cbind( matrix(0, nrow=n.alpha0, ncol=n.alpha1 ), (1-Zi)*s0.deriv.alpha0, matrix(0, nrow=n.alpha0, ncol=n.beta) ); quad4.blk3 <- cbind( matrix(0, nrow=n.beta, ncol=n.alpha1+n.alpha0), -ei*(1-ei)*outer(Xi, Xi) ); quad4 <- rbind( quad4.blk1, quad4.blk2, quad4.blk3 ); this.phi.deriv <- rbind( cbind(quad1, quad3) , cbind(quad2, quad4) ); Amat <- Amat + this.phi.deriv; } Amat <- Amat/n; Bmat <- Bmat/n; Amat.inv <- solve(Amat) ; var.mat <- ( Amat.inv %*% Bmat %*% t(Amat.inv) )/n; var.mat <- var.mat[ c(1:4), c(1:4) ]; if ( family == "gaussian" ) { tmp <- c( 1, 1, -1, -1 ); var.est <- rowVec(tmp) %*% var.mat %*% colVec(tmp); std <- sqrt( as.numeric(var.est) ); ans <- list( est = est, std = std ); } if ( family == "binomial" ) { tmp.risk <- c( 1, 1, -1, -1 ); var.risk <- rowVec( tmp.risk ) %*% var.mat %*% colVec( tmp.risk ); std.risk <- sqrt( as.numeric( var.risk ) ); ans <- list( est.risk = est.risk, std.risk = std.risk ); } return( ans ); } psw.spec.test.core <- function( X.mat, V.mat, V.name, trt, beta.hat, omega, Q, trans.type, weight, K, delta=0.002 ) { n <- nrow( X.mat ); W <- omega/Q; mu.B1.hat <- as.numeric( t(V.mat) %*% colVec( W * trt ) ) / sum( W * trt ) ; mu.B0.hat <- as.numeric( t(V.mat) %*% colVec( W * ( 1 - trt ) ) ) / sum( W * ( 1 - trt ) ) ; eta.B1.hat <- g.fun( x=mu.B1.hat, fun.type = trans.type ) ; eta.B0.hat <- g.fun( x=mu.B0.hat, fun.type = trans.type ) ; theta.hat <- c( eta.B1.hat, eta.B0.hat, beta.hat ) ; B.hat <- eta.B1.hat - eta.B0.hat ; n.mu.B1 <- length( mu.B1.hat ) ; n.mu.B0 <- length( mu.B0.hat ) ; n.beta <- length( beta.hat ) ; n.theta <- length(theta.hat) ; D.mat <- cbind( diag(n.mu.B1), -diag(n.mu.B0), matrix(0, nrow=n.mu.B1, ncol=n.beta) ) ; Meat.mat <- Bread.mat <- 0 ; for ( i in 1 : n ) { Vi <- as.numeric( V.mat[i, ] ); Xi <- as.numeric( X.mat[i, ] ); Zi <- trt[i]; Wi <- W[i]; omegai <- omega[i]; Qi <- Q[i]; ei <- calc.ps.Xbeta(Xmat=Xi, beta=beta.hat); ei.deriv <- calc.ps.deriv1( Xmat = Xi, beta = beta.hat ); omegai.deriv <- omega.derive.ei( ps = ei, weight = weight, delta = delta, K = K ); Qi.deriv <- 2 * Zi - 1; Wi.deriv.beta <- ei.deriv * ( Qi*omegai.deriv - omegai*Qi.deriv ) / Qi^2; tmp1 <- Wi * Zi * ( Vi - g.inv( x = eta.B1.hat, fun.type = trans.type ) ); tmp2 <- Wi * ( 1 - Zi ) * ( Vi - g.inv( x = eta.B0.hat, fun.type = trans.type ) ); tmp3 <- ( Zi - ei ) * Xi; this.phi <- c( tmp1, tmp2, tmp3 ); Meat.mat <- Meat.mat + outer( this.phi, this.phi ); Block.11 <- - Wi * Zi *( diag( g.inv.deriv( x = eta.B1.hat, fun.type = trans.type ) ) ); Block.12 <- matrix( 0, nrow = n.mu.B1, ncol = n.mu.B0 ); Block.13 <- Zi * ( colVec( Vi - g.inv( x = eta.B1.hat, fun.type = trans.type ) ) %*% rowVec( Wi.deriv.beta ) ); Block.21 <- matrix( 0, nrow = n.mu.B0, ncol = n.mu.B1 ) ; Block.22 <- - Wi * ( 1 - Zi ) * ( diag( g.inv.deriv( x = eta.B0.hat, fun.type = trans.type ) ) ); Block.23 <- (1-Zi)*( colVec( Vi - g.inv( x = eta.B0.hat, fun.type = trans.type ) ) %*% rowVec( Wi.deriv.beta ) ); Block.31 <- matrix( 0, nrow = n.beta, ncol = n.mu.B1 ); Block.32 <- matrix( 0, nrow = n.beta, ncol = n.mu.B0 ); Block.33 <- -ei * ( 1 - ei ) * outer( Xi, Xi ) ; Bread.mat <- Bread.mat + rbind( cbind( Block.11, Block.12, Block.13 ) , cbind( Block.21, Block.22, Block.23 ) , cbind( Block.31, Block.32, Block.33 ) ); } B.mat <- Meat.mat/n; A.mat <- Bread.mat/n; A.mat.inv <- solve( A.mat ); Sigma.theta.hat <- ( A.mat.inv %*% B.mat %*% t( A.mat.inv ) )/n; Sigma.B.hat <- D.mat %*% Sigma.theta.hat %*% t( D.mat ); df <- qr(Sigma.B.hat)$rank; test.stat <- as.numeric( t(B.hat) %*% solve(Sigma.B.hat) %*% B.hat ); pvalue <- pchisq( test.stat, df = df, lower.tail = FALSE ); names(eta.B1.hat) <- paste("eta.B1.", V.name, sep=""); names(eta.B0.hat) <- paste("eta.B0.", V.name, sep=""); names(B.hat) <- c( paste("B.hat.", V.name, sep="") ) rownames(Sigma.B.hat) <- colnames(Sigma.B.hat) <- names(B.hat); return( list( weight = weight, V.name = V.name, g.B1.hat = eta.B1.hat, g.B0.hat = eta.B0.hat, B.hat = B.hat, var.B.hat = Sigma.B.hat, test.stat = test.stat, df = df, pvalue = pvalue ) ); } mirror.hist.core <- function( ps.above, ps.below, wt.above, wt.below, add.weight, label.above, label.below, nclass = 50 ) { x0 <- ps.above ; wt0 <- wt.above ; x1 <- ps.below ; wt1 <- wt.below ; if ( is.null(nclass) ) { breaks <- hist( c(x0, x1), nclass=nclass, plot=F )$breaks ; } else { breaks <- hist( c(x0, x1), nclass=nclass, plot=F )$breaks ; } fm.x0 <- hist( x0, breaks=breaks, plot = F ) ; fm.x1 <- hist( x1, breaks=breaks, plot = F ) ; x.range <- range( c(x0, x1) ) ; y.range <- c( -max( fm.x1$counts ), max( fm.x0$counts ) ) ; par( las=1, lwd = 2, mar=c(5, 5, 4, 2), bty="n" ); plot( x=x.range, y=y.range, xaxt="n", yaxt="n", type="n" , xlim=x.range, ylim=y.range, ylab="", xlab="", cex.lab=1 ) ; axis( side=1, at=pretty( x.range ), cex.axis=1 ) ; axis( side=2, at=pretty( y.range ) , labels=abs( pretty( y.range ) ), cex.axis=1 ) ; title( xlab="Propensity score", cex.lab=1 ) title( ylab="Frequency", cex.lab=1 ); abline( h=0, lty=1 ); fm <- fm.x0 ; for (i in 1:(length(breaks)-1)) { x <- c( fm$breaks[i], fm$breaks[i], fm$breaks[i+1], fm$breaks[i+1] ) ; y <- c(0, fm$counts[i], fm$counts[i], 0) ; polygon(x, y) ; if ( add.weight ) { tmp <- ( breaks[i] <= x0 & x0 <= breaks[i+1] ) ; y2 <- c(0, sum(wt0[tmp]), sum(wt0[tmp]), 0) ; polygon(x, y2, col="light green", border="black") ; } } fm <- fm.x1 ; for (i in 1:(length(breaks)-1)) { x <- c( fm$breaks[i], fm$breaks[i], fm$breaks[i+1], fm$breaks[i+1] ) ; y <- c(0, -fm$counts[i], -fm$counts[i], 0) ; polygon(x, y) ; if ( add.weight ) { tmp <- ( breaks[i] <= x1 & x1 <= breaks[i+1] ) ; y2 <- c(0, -sum(wt1[tmp]), -sum(wt1[tmp]), 0) ; polygon(x, y2, col="dark green", border="black") ; } } } rowVec <- function(x) { return( t(x) ); } colVec <- function(x) { return( t(t(x)) ); } outcome.model <- function(dat, form, trt.var, family) { fm1 <- glm( as.formula( form ), data = dat[ dat[ , trt.var ] == 1, ] ); fm0 <- glm( as.formula( form ), data = dat[ dat[ , trt.var ] == 0, ] ); Y.hat.m1 <- as.numeric( predict( fm1, newdata = dat ) ); Y.hat.m0 <- as.numeric( predict( fm0, newdata = dat ) ); return( list( Y.hat.m1 = Y.hat.m1 , Y.hat.m0 = Y.hat.m0 , fm1 = fm1 , fm0 = fm0 ) ); } calc.omega <- function(ps, weight, delta=0.002, K=4) { ans <- 0; if (weight == "ATE") { ans <- 1; } else if (weight == "MW") { ans <- calc.omega.MW( ps = ps, delta = delta ); } else if (weight == "ATT") { ans <- ps; } else if (weight == "ATC") { ans <- 1-ps; } else if (weight == "OVERLAP") { ans <- 4*ps*(1-ps); } else if (weight == "TRAPEZOIDAL") { ans <- calc.omega.trapzd(ps=ps, delta=delta, K=K); } else { stop("Error in calc.omega: weight method does not exist!"); } return( ans ); } calc.ps.Xbeta <- function( Xmat, beta ) { Xmat <- as.matrix(Xmat); tmp <- as.numeric(rowVec(beta) %*% Xmat); tmp <- exp(tmp); names(tmp) <- NULL; return( tmp/(1 + tmp) ); } calc.ps.deriv1 <- function(Xmat, beta) { Xmat <- as.matrix(Xmat); tmp.ps <- calc.ps.Xbeta( Xmat=Xmat, beta=beta ); ans <- tmp.ps*(1 - tmp.ps)*t(Xmat); names(ans) <- rownames(ans) <- NULL; return( t(ans) ); } calc.ps.deriv2 <- function( Xi, beta ) { Xi <- colVec(Xi); tmp.ps <- calc.ps.Xbeta( Xmat=Xi, beta=beta ); tmp.deriv1 <- calc.ps.deriv1( Xmat=Xi, beta=beta ); ans <- Xi %*% rowVec(tmp.deriv1); names(ans) <- rownames(ans) <- NULL; ans <- (1 - 2*tmp.ps)*ans; return( ans ); } calc.omega.MW <- function (ps, delta) { ans <- 0; if (ps <= 0.5 - delta) { ans <- 2*ps; } else if (ps >= 0.5 + delta) { ans <- 2*(1 - ps); } else { ans <- approx.omega.MW(ps, delta); } return( ans ); } approx.omega.MW <- function (ps, delta) { A <- solve.A.MW(delta); ans <- rowVec(A) %*% c(1, ps, ps^2, ps^3); ans; } solve.A.MW <- function(delta) { if ( delta < 0.00001 ) { stop("*** ERROR in solve.a: delta too small ***"); } tmp1 <- 0.5 - delta; tmp2 <- 0.5 + delta; D <- matrix(c(1, tmp1, tmp1^2, tmp1^3, 0, 1, 2*tmp1, 3*tmp1^2, 1, tmp2, tmp2^2, tmp2^3, 0, 1, 2*tmp2, 3*tmp2^2), ncol = 4, nrow = 4, byrow = TRUE); C <- 2*c(tmp1, 1, tmp1, -1); A <- solve(D) %*% C; A; } calc.omega.trapzd <- function (ps, delta, K) { ans <- 0; if ( (0 < ps) & (ps <= 1/K - delta) ) { ans <- K*ps; } else if ( (1/K + delta <= ps) & (ps <= 1 - 1/K - delta) ) { ans <- 1; } else if ( (1 - 1/K + delta <= ps) & (ps < 1) ) { ans <- K*(1 - ps); } else { ans <- approx.omega.trapzd(ps, delta, K); } ans; } approx.omega.trapzd <- function (ps, delta, K) { A <- 0; if ( (1/K - delta < ps) & (ps < 1/K + delta) ) { A <- solve.A.trapzd1st(delta=delta, K=K); } else { A <- solve.A.trapzd2nd(delta=delta, K=K); } ans <- rowVec(A) %*% c(1, ps, ps^2, ps^3); ans; } solve.A.trapzd1st <- function (delta, K) { if ( delta < 0.00001 ) { stop("*** ERROR in solve.a: delta too small ***"); } tmp1 <- 1/K - delta; tmp2 <- 1/K + delta; D <- matrix(c(1, tmp1, tmp1^2, tmp1^3, 0, 1, 2*tmp1, 3*tmp1^2, 1, tmp2, tmp2^2, tmp2^3, 0, 1, 2*tmp2, 3*tmp2^2), ncol = 4, nrow = 4, byrow = TRUE); C <- 2*c(K*tmp1, K, 1, 0); A <- solve(D) %*% C; A; } solve.A.trapzd2nd <- function (delta, K) { if ( delta < 0.00001 ) { stop("*** ERROR in solve.a: delta too small ***"); } tmp1 <- 1 - 1/K - delta; tmp2 <- 1 - 1/K + delta; D <- matrix(c(1, tmp1, tmp1^2, tmp1^3, 0, 1, 2*tmp1, 3*tmp1^2, 1, tmp2, tmp2^2, tmp2^3, 0, 1, 2*tmp2, 3*tmp2^2), ncol = 4, nrow = 4, byrow = TRUE); C <- 2*c(1, 0, K*(1/K - delta), -K); A <- solve(D) %*% C; A; } omega.derive.ei <- function(ps, weight, delta=0.002, K=4) { if (weight == "ATE") { ans <- 0; } else if (weight == "ATT") { ans <- 1; } else if (weight == "ATC") { ans <- -1; } else if (weight == "OVERLAP") { ans <- 4*(1 - 2*ps); } else if (weight == "MW") { ans <- omega.derive.ei.MW(ps, delta); } else if (weight == "TRAPEZOIDAL") { ans <- omega.derive.ei.trapzd(ps, delta, K); } else { stop( "User defined first-order derivative of omega function is not provided!" ); } ans; } omega.derive.ei.MW <- function (ps, delta) { if ( (0 < ps) & (ps <= 0.5 - delta) ) { ans <- 2; } else if ( (0.5 + delta <= ps) & (ps <1) ) { ans <- -2; } else { A <- solve.A.MW(delta); ans <- A[2] + 2*A[3]*ps + 3*A[4]*ps^2; } ans; } omega.derive.ei.trapzd <- function (ps, delta, K) { if ( (0 < ps) & (ps <= 1/K - delta) ) { ans <- K; } else if ( (1/K - delta < ps) & (ps < 1/K + delta) ) { A <- solve.A.trapzd1st(delta = delta, K = K); ans <- A[2] + 2*A[3]*ps + 3*A[4]*ps^2; } else if ( (1/K + delta <= ps) & (ps <= 1 - 1/K - delta) ) { ans <- 0; } else if ( (1 - 1/K + delta <= ps) & (ps < 1) ) { ans <- -K; } else { A <- solve.A.trapzd2nd(delta = delta, K = K); ans <- A[2] + 2*A[3]*ps + 3*A[4]*ps^2; } ans; } calc.W.derive.beta <- function(Zi, Xi, omega.ei, beta.hat, ei, Qi, weight, delta, K ) { ei.deriv1 <- calc.ps.deriv1( Xmat=Xi, beta=beta.hat ); omegaei.deriv <- omega.derive.ei( ps = ei, weight = weight, delta = delta, K = K ); Qi.deriv.ei <- 2*Zi - 1; ans <- ei.deriv1*(Qi*omegaei.deriv - omega.ei*Qi.deriv.ei)/Qi^2; return( ans ); } calc.omega.derive.beta <- function(Xi, beta.hat, ei, weight, delta=0.002, K=4 ) { ei.deriv1 <- calc.ps.deriv1( Xmat=Xi, beta=beta.hat ); omegaei.deriv <- omega.derive.ei( ps=ei, weight=weight, delta=delta, K=K ); ans <- omegaei.deriv * ei.deriv1; return( ans ); } calc.std.diff <- function(var.value, wt, Z) { Z1.mean <- wtd.mean( x = var.value[Z==1], weights = wt[Z==1] ); Z1.var <- wtd.var( x = var.value[Z==1], weights = wt[Z==1] ); Z0.mean <- wtd.mean( x = var.value[Z==0], weights = wt[Z==0] ); Z0.var <- wtd.var( x = var.value[Z==0], weights = wt[Z==0] ); std.diff <- 100 * ( Z1.mean - Z0.mean ) / sqrt( ( Z1.var + Z0.var ) / 2 ) ; ans <- c( Z1.mean, sqrt(Z1.var), Z0.mean, sqrt(Z0.var), std.diff ); return( ans ); } diff.plot <- function( diff.before, diff.after, name, weight ) { par( las=1, lwd = 2, mar=c(5, max( nchar(name) ) + 4, 4, 2), bty="n" ); x.range <- range( c(diff.before, diff.after) ); y.range <- c(1, length(name)); ord <- order( diff.before, decreasing = T ); plot( x=x.range, y=y.range, xaxt="n", yaxt="n", type="n", xlim=x.range, ylim=y.range, ylab="", xlab="Standardized mean difference" ); axis( side=1, at=pretty( x.range ) ); axis( side=2, at=length(name):1, labels=name[ord], tick=F ); abline( v=0, lty=1, col="gray" ); points( y = length(name):1, x = diff.before[ord], pch=4 ); points( y = length(name):1, x = diff.after[ord], pch=21 ); legend("topleft", legend=c("Unadjusted", weight), pch=c(4, 21) ); } g.fun <- function( x, fun.type ) { if ( length(x) != length(fun.type) ) { print("*** ERROR in g.fun() ***"); return( rep(NA, length(x)) ); } else { m <- length(x); ans <- rep(0, m); for (j in 1:m) { if ( fun.type[j] == "log" ) { ans[j] <- log( max( 1e-6, x[j] ) ); } else if ( fun.type[j] == "logit" ) { ans[j] <- logit( min( max( 1e-6, x[j]), 1-1e-6 ) ); } else if ( fun.type[j] == "Fisher" ) { ans[j] <- 0.5*( log( 1 + x[j] ) - log( 1 - x[j] ) ); } else if (fun.type[j] == "sqrt") { ans[j] <- sqrt( x[j] ); } else { ans[j] <- x[j] ; } } return( ans ) ; } } g.inv <- function( x, fun.type ) { if ( length(x) != length(fun.type) ) { print("*** ERROR in g.inv() ***") ; return( rep(NA, length(x)) ) ; } else { m <- length(x) ; ans <- rep(0, m) ; for (j in 1:m) { if ( fun.type[j] == "log" ) { ans[j] <- exp( x[j] ) ; } else if ( fun.type[j] == "logit" ) { ans[j] <- inv.logit( x[j] ) ; } else if ( fun.type[j] == "Fisher" ) { ans[j] <- ( (exp(2*x[j])-1)/(exp(2*x)+1) ); } else if ( fun.type[j] == "sqrt") { ans[j] <- x[j]^2; } else { ans[j] <- x[j] ; } } return( ans ) ; } } g.inv.deriv <- function( x, fun.type ) { if ( length(x) != length(fun.type) ) { print("*** ERROR in g.inv.deriv() ***") ; return( rep(NA, length(x)) ) ; } else { m <- length(x) ; ans <- rep(0, m) ; for (j in 1:m) { if ( fun.type[j] == "log" ) { ans[j] <- exp( x[j] ) ; } else if ( fun.type[j] == "logit" ) { tmp <- inv.logit( x[j] ) ; ans[j] <- tmp*(1-tmp) ; } else if ( fun.type[j] == "Fisher" ) { tmp <- 2*exp( 2*x[j] ); ans[j] <- tmp^2; } else if ( fun.type[j] == "sqrt" ) { ans[j] <- 2*x[j]; } else { ans[j] <- 1 ; } } return( ans ) ; } }
bootCRCumInc <- function (df, exit, event, exposure, entry = NULL, weights = NULL, ipwvars=NULL, rep = 0, print.attr=T, seed=54321) { df$exit <- df[[deparse(substitute(exit))]] df$event <- df[[deparse(substitute(event))]] if(is.factor(df$event)) df$event <- as.numeric(df$event)-1 df$exposure <- df[[deparse(substitute(exposure))]] if(is.factor(df$exposure)) df$exposure <- as.numeric(df$exposure)-1 df$entry <- df[[deparse(substitute(entry))]] df$weights <- df[[deparse(substitute(weights))]] set.seed(seed) e3 <- any(df$event==3) e4 <- any(df$event==4) if (rep == 0) { stop("\n", "`n` boostrapping repetitions missing", call. = FALSE) } else { nboot <- rep bI1o.all <- NULL bI1x.all <- NULL bI2o.all <- NULL bI2x.all <- NULL R1.all <- NULL R2.all <- NULL bI3o.all <- NULL bI3x.all <- NULL R3.all <- NULL bI4o.all <- NULL bI4x.all <- NULL R4.all <- NULL ttx.all <- NULL datx <- df[which(df$exposure == 1), ] dato <- df[which(df$exposure == 0), ] for (b in 1:nboot) { b.data <- rbind(datx[sample(1:nrow(datx),replace=T),],dato[sample(1:nrow(dato),replace=T),]) b.data$exit <- jitter(b.data$exit) dat_boot <- do.call(CRCumInc,list(b.data,substitute(exit), substitute(event), substitute(exposure), substitute(entry), substitute(weights), substitute(ipwvars), F)) ttx.all[[b]] <- dat_boot$time R1.all[[b]] <- dat_boot$R1 R2.all[[b]] <- dat_boot$R2 if(e3) R3.all[[b]] <- dat_boot$R3 if(e4) R4.all[[b]] <- dat_boot$R4 rm(dat_boot) } ttx <- sort(c(0, df$exit[df$event > 0])) R1.lower <- NULL R1.upper <- NULL R2.lower <- NULL R2.upper <- NULL if(e3){ R3.lower <- NULL R3.upper <- NULL } if(e4){ R4.lower <- NULL R4.upper <- NULL } for (i in 1:length(ttx)) { tty1 <- NULL tty2 <- NULL tty3 <- NULL tty4 <- NULL for (b in 1:nboot) { tty1[b] <- approx(ttx.all[[b]], R1.all[[b]], xout = ttx[i], method = "constant", f = 0)$y tty2[b] <- approx(ttx.all[[b]], R2.all[[b]], xout = ttx[i], method = "constant", f = 0)$y if(e3) tty3[b] <- approx(ttx.all[[b]], R3.all[[b]], xout = ttx[i], method = "constant", f = 0)$y if(e4) tty4[b] <- approx(ttx.all[[b]], R4.all[[b]], xout = ttx[i], method = "constant", f = 0)$y } ttq <- quantile(tty1, probs = c(0.025, 0.975), na.rm = T) R1.lower[i] <- ttq[1] R1.upper[i] <- ttq[2] ttq <- quantile(tty2, probs = c(0.025, 0.975), na.rm = T) R2.lower[i] <- ttq[1] R2.upper[i] <- ttq[2] if(e3){ ttq <- quantile(tty3, probs = c(0.025, 0.975), na.rm = T) R3.lower[i] <- ttq[1] R3.upper[i] <- ttq[2] } if(e4){ ttq <- quantile(tty4, probs = c(0.025, 0.975), na.rm = T) R4.lower[i] <- ttq[1] R4.upper[i] <- ttq[2] } } CRCumInc_boot <- as.data.frame(cbind(R1.lower, R1.upper, R2.lower, R2.upper)) if(e3) CRCumInc_boot <- as.data.frame(cbind(CRCumInc_boot,R3.lower,R3.upper)) if(e4) CRCumInc_boot <- as.data.frame(cbind(CRCumInc_boot,R4.lower,R4.upper)) if(print.attr) print(attributes(CRCumInc_boot)[1:2]) invisible(CRCumInc_boot) } }
library(tidyverse) library(data.table) library(lubridate) library(countrycode) options(scipen=999) inspect <- FALSE df <- pred_frame <- data.frame(readRDS("output-data/country_daily_excess_deaths_with_covariates.RDS")) df <- df[order(df$date), ] pred_frame <- pred_frame[order(pred_frame$date), ] dv <- "daily_excess_deaths_per_100k" exclude <- c("daily_total_deaths", "daily_total_deaths_per_100k", "daily_expected_deaths", "daily_expected_deaths_per_100k", "daily_excess_deaths", "daily_tests", "daily_covid_cases", "daily_covid_deaths", "daily_vaccinations", "iso3c", "country", "continent", "imf_economy", "wdi_life_expectancy_at_birth_dist_average", "wdi_life_expectancy_at_birth_contiguous_country_average") predictors <- setdiff(colnames(df), c(dv, exclude)) saveRDS(predictors, "output-data/model-objects/predictors.RDS") source("scripts/shared-functions/expand_categorical.R") temp <- expand_categorical(df, predictors) df <- temp[[1]] predictors <- temp[[2]] X <- df Y <- df[, dv] if(inspect){ library(ggplot2) pdat <- df ggplot(pdat[pdat$date >= as.Date('2021-10-01'), ], aes(x=as.Date(date, origin = '1970-01-01'), y=daily_excess_deaths_per_100k, col = iso3c))+ geom_line()+ theme(legend.pos = 'none')+ geom_vline(aes(xintercept = as.Date('2021-12-01')))+ geom_vline(aes(xintercept = as.Date('2021-12-31')))+ geom_line(data = pdat[pdat$date >= as.Date('2021-10-01') & pdat$iso3c == 'USA', ], size = 2)+ geom_vline(aes(xintercept = Sys.Date()-28), size = 2) } Y <- Y[!X$date > Sys.Date()-21] X <- X[!X$date > Sys.Date()-21, ] Y <- Y[!(X$iso3c == "IND_Mumbai_City" & X$date > 18744)] X <- X[!(X$iso3c == "IND_Mumbai_City" & X$date > 18744),] Y <- Y[!X$iso3c %in% c("PER", "ECU")] X <- X[!X$iso3c %in% c("PER", "ECU"), ] ids <- paste0(X$iso3c, "_", round(X$date/7, 0)) for(i in setdiff(colnames(X), c("iso3c", "region"))){ X[, i] <- ave(X[, i], ids, FUN = function(x){mean(x, na.rm = T)}) } X <- X[!duplicated(ids), ] Y <- Y[!duplicated(ids)] export <- pred_frame[!duplicated(ids), c("iso3c", "country", "date", "region", "subregion", "population", "median_age", "aged_65_older", "life_expectancy", "daily_covid_deaths_per_100k", "daily_covid_cases_per_100k", "daily_tests_per_100k", "cumulative_daily_covid_cases_per_100k", "cumulative_daily_covid_deaths_per_100k", "cumulative_daily_tests_per_100k", "demography_adjusted_ifr", "daily_covid_cases", "daily_tests", "daily_covid_deaths", "daily_excess_deaths", dv)] source("scripts/shared-functions/impute_missing.R") X <- impute_missing(X[, c(predictors, "iso3c")]) ncol(X) for(i in colnames(X)){ if(is.numeric(X[, i])){ if(is.nan(sd(X[, i]))){ print(i) X[,i] <- NULL } else if(sd(X[, i]) == 0){ print(i) X[,i] <- NULL } } } ncol(X) NAm <- X[, grep("NA_matrix", colnames(X))] library(DescTools) NA_dimension_reduction <- FindCorr(cor(NAm), cutoff = 0.99) for(i in grep("NA_matrix", colnames(X))){ X[X[, i] != 1, i] <- 0 } source('scripts/aux_generate_model_loop.R') main_estimate_models <- 10 saveRDS(main_estimate_models, "output-data/model-objects/main_estimate_models_n.RDS") set.seed(112358) generate_model_loop( X_full = X[!is.na(Y), ], Y_full = Y[!is.na(Y)], B = 200, include_main_estimate = T, main_estimate_model_n = main_estimate_models, main_estimate_learning_rate = 0.001, bootstrap_learning_rate = 0.003) calibration = F if(calibration){ X_cv <- X[!is.na(Y), ] Y_cv <- Y[!is.na(Y)] weights <- log(X_cv$population) iso3c <- X_cv$iso3c cv_folds <- function(x, n = 10){ x <- sample(x) split(x, cut(seq_along(x), n, labels = FALSE))} folds <- cv_folds(unique(iso3c), n = 10) saveRDS(folds, "output-data/model-objects/folds.RDS") results <- data.frame(target = Y_cv, preds = rep(NA, length(Y_cv)), weights = weights, iso3c = iso3c) vars <- list() for(i in 1:length(folds)){ train_x <- X_cv[!iso3c %in% folds[[i]], ] train_y <- Y_cv[!iso3c %in% folds[[i]]] train_w <- weights[!iso3c %in% folds[[i]]] test_x <- X_cv[iso3c %in% folds[[i]], ] test_y <- Y_cv[iso3c %in% folds[[i]]] test_w <- weights[iso3c %in% folds[[i]]] library(agtboost) gbt_fit <- gbt.train(train_y, as.matrix(train_x[, setdiff(colnames(X_cv), c("iso3c", "region"))]), learning_rate = 0.01, nrounds = 1500, verbose = 10, algorithm = "vanilla", weights = train_w/mean(train_w)) print(i) print("cross-validation round completed.") results$preds[results$iso3c %in% folds[[i]]] <- predict(gbt_fit, newdata = as.matrix(test_x[, setdiff(colnames(X_cv), c("iso3c", "region"))])) } mean((abs(results$target - results$preds)^2)*results$weights/mean(results$weights)) write_csv(results, "output-data/results_gradient_booster.csv") pdat <- cbind.data.frame(pred = results$preds, truth = results$target, country = X_cv$iso3c, region = X_cv$region, w = results$weights) write_csv(pdat, "output-data/calibration_plot_gradient_booster.csv") ggplot(pdat, aes(x=pred, y=truth, col=region))+ geom_point()+ geom_abline(aes(slope = 1, intercept = 0))+ geom_smooth(aes(group = "1"), method = 'lm')+theme_minimal()+facet_wrap(.~region) ggplot(pdat, aes(x=pred, y=truth, col=region))+ geom_point()+ geom_abline(aes(slope = 1, intercept = 0))+ geom_smooth(mapping = aes(weight = weights, group = "1"), method = 'lm')+theme_minimal() }
mean_token_length <- function(topic_model, top_n_tokens = 10){ UseMethod("mean_token_length") } mean_token_length.TopicModel <- function(topic_model, top_n_tokens = 10){ top_terms <- terms(topic_model, top_n_tokens) nchar_mat <- apply(top_terms, 2, nchar) unname(colMeans(nchar_mat)) }
wfs_api <- function(base_url = "http://geo.stat.fi/geoserver/wfs", queries) { if (!grepl("^http", base_url)) stop("Invalid base URL") ua <- httr::user_agent("https://github.com/rOpenGov/geofi") url <- httr::modify_url(base_url, query = queries) message("Requesting response from: ", url) resp <- httpcache::GET(url, ua) content <- xml2::read_xml(resp$content) if (httr::http_error(resp)) { status_code <- httr::status_code(resp) exception_texts <- "" if (status_code == 400) { exception_texts <- xml2::xml_text(xml2::xml_find_all(content, "//ExceptionText")) exception_texts <- exception_texts[!grepl("^(URI)", exception_texts)] exception_texts <- c(exception_texts, paste("URL: ", url)) } stop( sprintf( "WFS API %s request failed [%s]\n %s", paste(url), httr::http_status(status_code)$message, paste0(exception_texts, collapse = "\n ") ), call. = FALSE ) } api_obj <- structure( list( url = url, response = resp ), class = "wfs_api" ) api_obj$content <- content api_obj$content <- content return(api_obj) }
reshape_grouplevel <- function(x, indices = "all", ...) { UseMethod("reshape_grouplevel") } reshape_grouplevel.estimate_grouplevel <- function(x, indices = "all", ...) { if (any(indices == "all")) { indices <- names(x)[!names(x) %in% c("Group", "Level", "Parameter", "CI")] } if ("Coefficient" %in% indices) { indices <- c(indices, "Median", "Mean", "MAP") } if ("SE" %in% indices) { indices <- c(indices, "SD") } indices <- names(x)[names(x) %in% unique(indices)] data <- attributes(x)$data groups <- unique(x$Group) for (group in groups) { data_group <- x[x$Group == group, ] if (nrow(data_group) == 0) next data_group[[group]] <- data_group$Level newvars <- paste0(group, "_", indices) names(data_group)[names(data_group) %in% indices] <- newvars data_group$Parameter <- ifelse(data_group$Parameter == "(Intercept)", "Intercept", data_group$Parameter ) data_wide <- datawizard::data_to_wide( data_group[c(group, newvars, "Parameter")], rows_from = group, values_from = newvars, colnames_from = "Parameter", sep = "_" ) if (grepl(":", group)) { groups <- as.data.frame(t(sapply(strsplit(data_wide[[group]], ":"), function(x) as.data.frame(t(x))))) names(groups) <- unlist(strsplit(group, ":")) data_wide <- cbind(groups, data_wide) data_wide[group] <- NULL group <- names(groups) } data[["__sort_id"]] <- 1:nrow(data) data <- merge(data, data_wide, by = group, sort = FALSE) data <- data[order(data[["__sort_id"]]), ] data[["__sort_id"]] <- NULL } row.names(data) <- NULL class(data) <- c("reshape_grouplevel", class(data)) data } summary.reshape_grouplevel <- function(object, ...) { x <- object[!duplicated(object), ] row.names(x) <- NULL x }
xts2ts <- function(series, freq=NULL) { if (is.null(freq)) {freq = freq_xts(series)} newTS <- series if (freq==365) { newTS[format(zoo::index(series), "%m-%d")=="02-29"] <- NA} time <- sum(as.numeric(format(zoo::index(series), "%Y")==format(xts::first(zoo::index(series)), "%Y"))) if (.is.leapyear(format(xts::first(zoo::index(series)), "%Y")) && as.Date(xts::first(zoo::index(series))) < as.Date(paste0(format(xts::first(zoo::index(series)), "%Y"), "-02-29"))) {time <- time-1} newstart <- c(as.numeric(format(xts::first(zoo::index(series)), "%Y")), freq-time+1) newseries <- as.numeric(newTS[!is.na(newTS)]) outTS <- stats::ts(newseries, start=newstart, frequency=freq) outTS }
blus <- function(mainlm, omit = c("first", "last", "random"), keepNA = TRUE, exhaust = NA, seed = 1234) { processmainlm(m = mainlm, needy = FALSE) n <- nrow(X) if (!is.na(seed)) set.seed(seed) omitfunc <- do_omit(omit, n, p, seed) Xmats <- do_Xmats(X, n, p, omitfunc$omit_ind) singular_matrix <- FALSE if (is.singular.mat(Xmats$X_ord_sq) || is.singular.mat(Xmats$X0)) { singular_matrix <- TRUE message("Passed `omit` argument resulted in singular matrix; BLUS residuals could not be computed. Randomly chosen combinations of indices to omit will be attempted according to `exhaust` argument passed.") ncombn <- choose(n, p) if ((is.na(exhaust) || is.null(exhaust))) { dosample <- (ncombn > 1e4) numsample <- 1e4 } else if (exhaust <= 0) { stop("`exhaust` is not positive; no attempts will be made to find subset to omit") } else { dosample <- (ncombn > exhaust) numsample <- min(ncombn, exhaust) } if (dosample) { subsetstotry <- unique(t(replicate(numsample, sort(sample(x = n, size = p))))) rowstodo <- 1:nrow(subsetstotry) } else { subsetstotry <- t(utils::combn(n, p)) maxrow <- min(exhaust, nrow(subsetstotry), na.rm = TRUE) rowstodo <- sample(1:nrow(subsetstotry), maxrow, replace = FALSE) } for (r in rowstodo) { omitfunc <- do_omit(subsetstotry[rowstodo[r], , drop = FALSE], n, p) Xmats <- do_Xmats(X, n, p, omitfunc$omit_ind) if (!is.singular.mat(Xmats$X_ord_sq) && !is.singular.mat(Xmats$X0)) { singular_matrix <- FALSE message(paste0("Success! Subset of indices found that does not yield singular matrix: ", paste(omitfunc$omit_ind, collapse = ","))) break } } } if (singular_matrix) stop("No subset of indices to omit was found that avoided a singular matrix.") keep_ind <- setdiff(1:n, omitfunc$omit_ind) G <- Xmats$X0 %*% solve(Xmats$X_ord_sq) %*% t(Xmats$X0) Geig <- eigen(G, symmetric = TRUE) lambda <- sqrt(Geig$values) q <- as.data.frame(Geig$vectors) Z <- Reduce(`+`, mapply(`*`, lambda / (1 + lambda), lapply(q, function(x) tcrossprod(x)), SIMPLIFY = FALSE)) e0 <- e[omitfunc$omit_ind] e1 <- e[keep_ind] e_tilde <- c(e1 - Xmats$X1 %*% solve(Xmats$X0) %*% Z %*% e0) if (keepNA) { rval <- rep(NA_real_, n) rval[keep_ind] <- e_tilde } else { rval <- e_tilde } rval }
`dsminmeanmax` <- function(intervalnumber,min,mean,max){ p=seq(0,1,1/(intervalnumber-1)); lo=max-(max-mean)/p;lo[lo<min]=min; hi=(p*min-mean)/(p-1);hi[hi>max]=max;hi[hi==-Inf]=max erg=dsstruct(cbind(lo,hi,1/intervalnumber)) }
l_cget <- function(target, state) { UseMethod("l_cget", target) } l_cget.loon <- function(target, state) { obj_eval <- .loonobject(target, as.character) if(substr(state,1,1) != "-") { dash_state <- paste("-", state, sep='') } else { dash_state <- state state <- substring(state, 2) } type <- obj_eval('info', 'stateType', state) if (type %in% c("double", "positive_double", "integer", "positive_integer", "tempcoords", "in_unit_interval")) { environment(obj_eval)$convert <- function(x) {as.numeric(as.character(x))} } else if (type == "boolean") { environment(obj_eval)$convert <- function(x) {as.logical(as.character(x))} } else if (type == "data") { environment(obj_eval)$convert <- function(result) { vars <- tcl('dict', 'keys', result) l <- sapply(as.character(tcl('dict','keys',result)), FUN=function(var){ as.character(tcl('dict','get', result, var)) }, simplify=FALSE, USE.NAMES=TRUE) l[['stringsAsFactors']] <- FALSE do.call(data.frame, l) } } else if (type == "nested_double") { environment(obj_eval)$convert <- function(result) { dim <- as.numeric(tcl('llength', result)) out <- vector(mode='list', length=dim) for (i in 1:dim) { out[[i]] <- as.numeric(tcl('lindex', result, i-1)) } out } } else if (state %in% c("n","p")) { environment(obj_eval)$convert <- function(x) {as.numeric(as.character(x))} } else if (type == "nested_double") { environment(obj_eval)$convert <- l_nestedTclList2Rlist } else { dim <- obj_eval('info', 'stateDimension', state) if (dim == "1") { environment(obj_eval)$convert <- function(x) { paste(rawToChar(as.raw(x)), collapse=' ') } } } obj_eval('cget', dash_state) } l_cget.character <- function(target, state) { widget <- try(l_create_handle(target), silent = TRUE) if ("try-error" %in% class(widget)) { stop(paste0(state, " is not accessible from", target, "via l_cget")) } else { l_cget(widget, state) } }
generate.lm <- function(baseline, X=NULL, N=1000, type="none", beta=NULL, xvars=3, mu=0, sd=1, censor=.1){ T <- max(baseline$time) if(type=="none"){ if(is.null(X)) X <- cbind(matrix(rnorm(N*xvars, mean=mu, sd=sd), N, xvars)) if(!is.null(X)) X <- as.matrix(X) if(is.null(beta)) beta <- as.matrix(rnorm(ncol(X), mean=0, sd=.1)) if(!is.null(beta)) beta <- as.matrix(beta) XB <- X%*%beta survival <- t(sapply(XB, FUN=function(x){baseline$survivor^exp(x)}, simplify=TRUE)) survival <- cbind(1, survival) y <- apply(survival, 1, FUN=function(x){ z <- diff(x < runif(1)) r <- ifelse(all(z==0), T, which.max(z)) return(r) }) data <- data.frame(X) data$y <- y tvc <- FALSE } else if(type=="tvc"){ if(!is.null(X)) warning("User-supplied X matrices are not implemented when type='tvc'. Generating random X data") if(is.null(beta)) beta <- as.matrix(rnorm(xvars, mean=0, sd=.1)) if(!is.null(beta)) beta <- as.matrix(beta) Xmat1 <- expand.grid(N = 1:N, T=1:T) Xmat1$X1 <- rnorm(N*T) Xmat2 <- data.frame(matrix(rnorm(xvars*N), N, xvars)) Xmat2$N <- 1:N Xmat2 <- Xmat2[,-1] X <- as.matrix(merge(Xmat1, Xmat2, by="N")[,-c(1,2)]) XB <- matrix(X%*%beta, N, T, byrow=TRUE) survival <- t(apply(XB, 1, FUN=function(x){baseline$survivor^exp(x)})) survival <- cbind(1, survival) lifetimes <- apply(survival, 1, FUN=function(x){ z <- diff(x < runif(1)) r <- ifelse(all(z==0), T, which.max(z)) return(r) }) cen <- quantile(lifetimes, 1-censor) m <- (2*cen + 1)/T data <- PermAlgo::permalgorithm(N, T, X, XmatNames = colnames(X), eventRandom = lifetimes, censorRandom = round(runif(N, 1, m*T),0), betas = beta, groupByD = FALSE) data <- dplyr::rename(data, id=Id, failed=Event, start=Start, end=Stop) data <- dplyr::select(data, -Fup) rownames(data) <- NULL tvc <- TRUE } else if(type=="tvbeta"){ X <- cbind(matrix(rnorm(N*xvars, mean=mu, sd=sd), N, xvars)) if(is.null(beta)) beta <- as.matrix(rnorm(ncol(X), mean=0, sd=.1)) if(!is.null(beta) & ncol(beta) == 1){ beta.mat1 <- data.frame(time = 1:T, one=1) beta.mat2 <- data.frame(t(beta), one=1) beta.mat <- merge(beta.mat1, beta.mat2, by="one") beta.mat <- dplyr::select(beta.mat, -one) colnames(beta.mat) <- gsub(pattern="X", replacement="beta", colnames(beta.mat)) beta.mat <- dplyr::mutate(beta.mat, beta1 = beta1*log(time)) beta.mat2 <- dplyr::select(beta.mat, -time) XB <- apply(as.matrix(beta.mat2), 1, FUN=function(b){ as.matrix(X)%*%b }) } if(!is.null(beta) & ncol(beta) > 1){ XB <- apply(as.matrix(beta), 1, FUN=function(b){ as.matrix(X)%*%b }) beta.mat <- cbind(time=1:nrow(beta), beta) } survival <- t(apply(XB, 1, FUN=function(x){baseline$survivor^exp(x)})) survival <- cbind(1, survival) lifetimes <- apply(survival, 1, FUN=function(x){ z <- diff(x < runif(1)) r <- ifelse(all(z==0), T, which.max(z)) return(r) }) data <- data.frame(X) data <- dplyr::mutate(data, y = lifetimes) beta <- beta.mat tvc <- FALSE } else {stop("type must be one of 'none', 'tvc', or 'tvbeta'")} return(list(data=data, beta=beta, XB=XB, exp.XB = exp(XB), survmat=survival, tvc=tvc)) }
wth.param <- function(dly, llim = 0, method = "poisson", year.col = "YEAR", month.col = "MONTH", day.col = "DAY", prcp.col = "PRCP.VALUE", tmin.col = "TMIN.VALUE", tmax.col = "TMAX.VALUE") { results <- NA yearlist <- table(dly[[year.col]]) yearlist <- as.numeric(names(yearlist)[yearlist >= 365]) nyears <- length(yearlist) dly <- dly[ dly[[year.col]] %in% yearlist, ] dly <- dly[!(dly[[month.col]] == 2 & dly[[day.col]] == 29), ] dly <- dly[seq(min(which(dly$MONTH == 1 & dly$DAY == 1)), max(which(dly$MONTH == 12 & dly$DAY == 31))), ] tmin <- dly[[tmin.col]] tmax <- dly[[tmax.col]] tave <- (tmin + tmax)/2 A <- mean(tave, na.rm = TRUE) B <- diff(range(tave, na.rm = TRUE))/4 C <- which.min(apply(matrix(tave, nrow = 365, byrow = FALSE), 1, mean, na.rm = TRUE)) if(method == "poisson") { dly <- dly[!(dly[[month.col]] == 2 & dly[[day.col]] == 29), ] dly <- dly[seq(min(which(dly[[month.col]] == 1 & dly[[day.col]] == 1)), max(which(dly[[month.col]] == 12 & dly[[day.col]] == 31))), ] prcp <- dly[[prcp.col]] prun <- rle(ifelse(prcp > llim, 1, 0)) lambda <- 1/mean(prun$lengths[prun$values == 0], na.rm = TRUE) d <- mean(prcp[prcp > 0], na.rm = TRUE) results <- list(lambda = lambda, depth = d) } if(method == "markov") { mindex <- dly[[month.col]] mindex <- factor(mindex, levels=1:12) mnames <- paste0("m", sprintf("%02d", 1:12)) dayT.max <- split(dly[[tmax.col]], mindex) dayT.min <- split(dly[[tmin.col]], mindex) dayT.mean <- split((dly[[tmax.col]] + dly[[tmin.col]]) / 2, mindex) dayP.sum <- split(dly[[prcp.col]], mindex) monthP.sum <- sapply(dayP.sum, sum, na.rm=TRUE) / nyears prcpmean <- sapply(dayP.sum, function(x)mean(x[x > 0], na.rm=TRUE)) monthP.max <- sapply(dayP.sum, max, na.rm=TRUE) monthT.mmin <- sapply(dayT.min, mean, na.rm=TRUE) monthT.mmax <- sapply(dayT.max, mean, na.rm=TRUE) tsdmin <- sapply(dayT.min, sd, na.rm=TRUE) tsdmax <- sapply(dayT.max, sd, na.rm=TRUE) prsd <- sapply(dayP.sum, function(x)sd(x[x > 0], na.rm=TRUE)) prskew <- sapply(dayP.sum, function(x)e1071::skewness(x[x > 0], na.rm=TRUE)) prskew[is.nan(prskew)] <- 0 dayP.wetv <- ifelse(dly[[prcp.col]] > llim, 1, 0) dayP.wetv[is.na(dayP.wetv)] <- 0 dayP.wet <- split(dayP.wetv, mindex) prdays <- sapply(dayP.wet, sum) / sapply(dayP.wet, length) Ptoday <- c(dayP.wetv, 0) Pyest <- c(0, dayP.wetv) Pyt <- paste0(Pyest, Ptoday) Pyt <- Pyt[-length(Pyt)] Pyt <- split(Pyt, mindex) prww <- sapply(Pyt, function(x)sum(x == "11")) / sapply(Pyt, function(x)sum(x == "11" | x == "10")) prdw <- sapply(Pyt, function(x)sum(x == "01")) / sapply(Pyt, function(x)sum(x == "01" | x == "00")) results <- data.frame( tmin = monthT.mmin, tminsd = tsdmin, tmax = monthT.mmax, tmaxsd = tsdmax, prcp = monthP.sum, prcpmean = prcpmean, prcpmax = monthP.max, prcpsd = prsd, prcpskew = prskew, prcpwet = prdays, prcpww = prww, prcpdw = prdw) } list(params = results, temperature = list(A = A, B = B, C = C), llim = llim, start = min(yearlist), end = max(yearlist)) }
opt.TPO <- function (x, k.max = ncol (x), n.lambda = 30, lambda.max, ...) { store.opt = TRUE ret <- .sPCAgrid.opt.ind (x = x, k.max = k.max, n.lambda = n.lambda, lambda.max = lambda.max, store.PCs = store.opt, f.eval = .TPO, ...) class (ret) <- c (class (ret), "opt.TPO") return (ret) } opt.BIC <- function (x, k.max = ncol (x), n.lambda = 30, lambda.max, ...) { store.opt = TRUE ret <- .sPCAgrid.opt.tot (x = x, k.max = k.max, n.lambda = n.lambda, lambda.max = lambda.max, store.PCs = store.opt, f.eval = .BIC.RSS, ...) class (ret) <- c (class (ret), "opt.BIC") return (ret) } .flexapply <- function (X, f, NAME, args) { args[[NAME]] <- X do.call (f, args) } .sPCAgrid.ml <- function (..., lambda, f.pca = .sPCAgrid.ini, f.apply = lapply) { args <- list (...) args$store.call <- FALSE f.apply (X = lambda, FUN = .flexapply, f = f.pca, NAME = "lambda", args = args) } .sPCAgrid.opt.tot <- function (x, n.lambda = 101, k.max = 2, lambda, lambda.ini, lambda.max, trace = 0, store.PCs = TRUE, f.apply = lapply, f.eval = .TPO, ...) { pc.ini <- NULL f.pca <- .sPCAgrid.ini if (!missing (lambda.ini) && !is.null (lambda.ini)) { k.ini <- length (lambda.ini) pc.ini <- f.pca (x = x, lambda = lambda.ini, k = k.ini, cut.pc = FALSE, ...) if (!missing (pc.ini) && !is.null (pc.ini)) warning ("argumens \x22pc.ini\x22 AND \x22lambda.ini\x22 were specified. Ignoring \x22pc.ini\x22.") } else if (!missing (pc.ini) && !is.null (pc.ini)) { k.ini = pc.ini$k lambda.ini <- rep (NA, k.ini) } else { pc.ini <- NULL lambda.ini <- NULL k.ini <- 0 } p <- ncol (x) if (k.ini == p) stop ("all components have already been computed") if (k.ini + k.max > p) { warning (paste ("reducing k.max to", p - k.ini)) k.max <- p - k.ini } if (missing (lambda)) { if (missing (lambda.max) || is.na (lambda.max)) max.fs <- .FSgetLambda (x = x, k = k.max, pc.ini = pc.ini, f.pca = f.pca, scores = FALSE, trace = trace, ...) else max.fs <- lambda.max[1] lambda <- seq (0, max.fs, len = n.lambda) } PCs <- .sPCAgrid.ml (x = x, pc.ini = pc.ini, k = k.max, scores = FALSE, cut.pc = TRUE, trace = trace, f.pca = f.pca, lambda = lambda, f.apply = f.apply, ...) opt <- .SPCAgrid.opt (x, PCs, f.eval, store.PCs, k = k.ini + 1:k.max, singlePC = FALSE, ...) if (!store.PCs) return (opt) ret <- list (pc = list (), pc.noord = list (), x = x, k.ini = k.ini, opt = opt) for (i in 1:length (opt$pc)) { pc <- .cut.pc (opt$pc[[i]], k.ini + k.max) ret$pc.noord[[i]] <- pc ret$pc[[i]] <- .orderPCs (pc, k.max, k.ini, TRUE) } class (ret) <- "sPCAgrid.opt.tot" return (ret) } .sPCAgrid.opt.eval <- function (x, f.eval = .BIC.RSS, k = 1, ...) { if (all (class (x) != "sPCAgrid.opt.tot")) stop ("x must be of type \"sPCAgrid.opt.tot\"") .SPCAgrid.opt (x$x, x$opt$PCs, f.eval, storePCs = FALSE, k = 1:k, ...) } .SPCAgrid.opt <- function (x, PCs, k, f.eval, store.PCs, f.apply = sapply, singlePC = TRUE, ...) { ret <- list () if (store.PCs) ret$PCs <- PCs if (missing (f.eval) || !is.function (f.eval)) { if (!store.PCs) stop ("either store.PCs must be TRUE, or f.eval must be a valid model evaluation function") return (ret) } ret$pc <- ret$k <- list () ret$mode <- .GetFunctionName (f.eval, ...) for (i in 1:length (k)) { if (singlePC) K <- k[i] else K <- k[1:i] obj.pc.0 <- f.eval (x = x, pc = PCs[[1]], k = K, ...) obj.pc.1 <- f.eval (x = x, pc = PCs[[length (PCs)]], k = K, obj.pc.0 = obj.pc.0, ...) obj <- f.apply (X = PCs, FUN = .flexapply, f = f.eval, NAME = "pc", args = list (x = x, k = K, obj.pc.0 = obj.pc.0, obj.pc.1 = obj.pc.1, ...)) ret$obj <- cbind (ret$obj, obj) idx.best <- which.min (obj) ret$idx.best <- cbind (ret$idx.best, idx.best) ret$pc[[i]] <- PCs[[idx.best]] ret$k[[i]] <- K } if (!store.PCs) return (ret$pc) return (ret) } .sPCAgrid.opt.ind <- function (x, n.lambda = 101, k.max = ncol (x), lambda.ini, lambda.max, trace = 0, store.PCs = TRUE, f.eval = .TPO, ...) { pc.ini <- NULL f.pca <- .sPCAgrid.ini if (!missing (lambda.ini) && !is.null (lambda.ini)) { k.ini <- length (lambda.ini) pc.ini <- f.pca (x = x, lambda = lambda.ini, k = k.ini, cut.pc = FALSE, ...) if (!missing (pc.ini)) stop ("either store.PCs must be TRUE, or f.eval must be a valid model evaluation function") } else if (!missing (pc.ini) && !is.null (pc.ini)) { k.ini = pc.ini$k lambda.ini <- rep (NA, k.ini) } else { pc.ini <- NULL lambda.ini <- NULL k.ini <- 0 } if (!missing (lambda.max)) lambda.max <- rep (lambda.max, len = k.max) p <- ncol (x) if (k.ini == p) stop ("all components have already been computed") if (k.ini + k.max > p) { warning (paste ("reducing k.max to", p - k.ini)) k.max <- p - k.ini } if (store.PCs) opt <- list () for (i in 1:k.max) { if (missing (lambda.max) || is.na (lambda.max[i])) max.fs <- .FSgetLambda (x = x, k = 1, pc.ini = pc.ini, f.pca = f.pca, scores = FALSE, trace = trace, ...) else max.fs <- lambda.max[i] lambda <- seq (0, max.fs, len = n.lambda) cur.pcs <- .sPCAgrid.ml (x = x, pc.ini = pc.ini, k = 1, scores = FALSE, cut.pc = FALSE, trace = trace, lambda = lambda, f.pca = f.pca, ...) cur.opt <- .SPCAgrid.opt (x, cur.pcs, f.eval, store.PCs, k = k.ini + i, ...) if (store.PCs) opt[[i]] <- cur.opt pc.ini <- cur.opt$pc[[1]] } pc.ini <- .cut.pc (pc.ini, k.ini + k.max) pc <- .orderPCs (pc.ini, k.max, k.ini, TRUE) if (!store.PCs) return (pc) ret <- list (pc = pc, pc.noord = pc.ini, x = x, k.ini = k.ini, opt = opt) class (ret) <- "sPCAgrid.opt.ind" return (ret) } .GFSL.calc.sPCA <- function (k.check, lambda = 1, f.pca = sPCAgrid, zero.tol = 1e-10, trace = 0, check.all = TRUE, ...) { if (trace >= 5) .flush.cat ("checking lambda: ", lambda, "\r\n", sep = "") if (check.all) return (f.pca (lambda = lambda, k = k.check, ...)$loadings[, 1:k.check]) return (f.pca (lambda = lambda, ...)$loadings[, k.check, drop = FALSE]) } .GFSL.is.sparse <- function (k.check, zero.tol = 1e-10, ...) { load <- .GFSL.calc.sPCA (k.check = k.check, zero.tol = zero.tol, ...) return ((sum (abs (load)> zero.tol) ) == ncol (load)) } .GFSL.is.same <- function (sparse.load, zero.tol = 1e-10, ...) { load <- .GFSL.calc.sPCA (zero.tol = zero.tol, ...) return (sum (abs (sparse.load - load)) <= zero.tol) } .GFSL.find.max <- function (lambda = 1, ...) { for (i in 1:16) { if (.GFSL.is.sparse (lambda = lambda, ...)) return (lambda) lambda = lambda * 2 } return (NULL) } .GFSL.find.range <- function (lbL , ubL, niter = 6, f.sparse = .GFSL.is.sparse, ...) { for (i in 1:niter) { mbL <- mean (c(ubL, lbL)) if (f.sparse (lambda = mbL, ...)) ubL <- mbL else lbL <- mbL } return (ubL) } .getFullSparseLambda.all <- function (uBound, ...) { if (missing (uBound)) uBound <- .GFSL.find.max (lambda = 1, check.all = TRUE, ...) if (is.null (uBound)) stop ("cannot find full sparse model") lBound <- ifelse (uBound > 1, uBound / 2, 0) .GFSL.find.range (lbL = lBound, ubL = uBound, f.sparse = .GFSL.is.sparse, ...) } .getFullSparseLambda.indiv <- function (niter = 15, ...) { uBound <- .GFSL.find.max (lambda = 1, check.all = FALSE, ...) if (!is.null (uBound)) { lBound <- ifelse (uBound > 1, uBound / 2, 0) return (.GFSL.find.range (lbL = lBound, ubL = uBound, f.sparse = .GFSL.is.sparse, check.all = FALSE, ...)) } lambda.max <- 1e6 load <- .GFSL.calc.sPCA (lambda = lambda.max, check.all = FALSE, ...) .GFSL.find.range (lbL = 0, ubL = lambda.max, niter = 25, f.sparse = .GFSL.is.same, sparse.load = load, check.all = FALSE, ...) } .FSgetLambda <- function (...) { kc <- .FSgetK.check (...) if (.FSpossible (...)) .FSgetLambdaFS (..., k.check = kc) else .FSgetLambdaC (..., k.check = kc) } .FSgetK.check <- function (pc.ini = NULL, k.ini, k, ...) { if (is.null (pc.ini)) return (1:k) if (missing (k.ini)) k.ini <- pc.ini$k return (k.ini + 1 : k) } .FSpossible <- function (pc.ini = NULL, k.ini, k, zero.tol = 1e-16, ...) { if (is.null (pc.ini)) return (TRUE) if (missing (k.ini)) k.ini <- pc.ini$k l0 <- abs (pc.ini$loadings[, 1:k.ini, drop = FALSE]) > zero.tol return (any (rowSums (l0) == 0)) } .FSgetLambdaFS <-function (iter = 15, ...) { .FSiter (..., f.test = .FSisFullSparse) } .FSgetLambdaC <- function (zero.tol, ...) { pc0 <- .FScalc (..., lambda = 2^20)[[1]] .FSiter (..., pc0 = pc0, f.test = .FScompL) } .FSiter <- function (niter = 8, testL = testE^-2, testU = testE^5, testE = 16, ...) { L <- testL U <- testU for (i in 1:2) { lambda.test <- testE^seq (log (L) / log (testE), log (U) / log (testE), len = niter) sparse <- .FStest (..., lambda = lambda.test) if (sparse[1]) return (lambda.test[1]) if (!sparse[niter]) return (lambda.test[niter]) idx <- which (sparse)[1] L <- lambda.test[idx-1] U <- lambda.test[idx] } return (lambda.test[idx]) } .FStest <- function (..., f.test) { PCs <- .FScalc (...) sapply (PCs, f.test, ...) } .FScompL <- function (pc, pc0, k.check, zero.tol = 1e-16, ...) { sum (abs (.loadSgnU (pc$load [, k.check, drop = FALSE]) - .loadSgnU (pc0$load [, k.check, drop = FALSE])) > sqrt (zero.tol)) == 0 } .FScalc <- function (...) { .sPCAgrid.ml (...) } .FSisFullSparse <- function (pc, k.check, zero.tol = 1e-16, ...) { n.k <- length(k.check) sum (abs (pc$load [, k.check]) > sqrt (zero.tol)) == n.k } .loadSgnU <- function (x) { idx.max <- apply (abs (x), 2, which.max) sgn <- sign (x[cbind (idx.max, 1:ncol (x))]) if (length (sgn) == 1) return (x * sgn) return (x %*% diag (sgn)) }
Hox02 <- matrix( c(-0.264, 0.086, 3, -0.230, 0.106, 1, 0.166, 0.055, 2, 0.173, 0.084, 4, 0.225, 0.071, 3, 0.291, 0.078, 6, 0.309, 0.051, 7, 0.435, 0.093, 9, 0.476, 0.149, 3, 0.617, 0.095, 6, 0.651, 0.110, 6, 0.718, 0.054, 7, 0.740, 0.081, 9, 0.745, 0.084, 5, 0.758, 0.087, 6, 0.922, 0.103, 5, 0.938, 0.113, 5, 0.962, 0.083, 7, 1.522, 0.100, 9, 1.844, 0.141, 9), ncol=3, byrow=TRUE) Hox02 <- cbind(1:nrow(Hox02), Hox02) dimnames(Hox02) <- list(NULL, c("study", "yi","vi","weeks")) Hox02 <- data.frame(Hox02)
context("bs4CardLabel") test_that("is shiny tag?", { golem::expect_shinytag(bs4CardLabel(text = 1, status = "warning")) }) test_that("Long text warning", { expect_warning(bs4CardLabel(text = "jssjjsjssjsjsj", status = "danger")) }) test_that("basis", { expect_error(bs4CardLabel(text = 1)) }) test_that("status", { labelCl <- bs4CardLabel(text = 1, status = "danger")$attribs$class expect_match(labelCl, "badge bg-danger") }) test_that("Is wrapper tag span?", { wrapperType <- bs4CardLabel(text = 1, status = "primary")$name expect_match(wrapperType, "span") }) test_that("no tooltip", { labelTagChildren <- bs4CardLabel(text = 1, status = "primary")$children expect_length(labelTagChildren, 1) }) test_that("tooltip", { labelTagProps <- bs4CardLabel(text = 1, tooltip = "prout", status = "primary")$attribs expect_length(labelTagProps, 3) })
ReconstructedCountSet <- R6Class("ReconstructedCountSet", inherit = ReconstructedFeatureSet, public = list( KR = NULL, initialize = function(fs=NULL, ro=NULL) { if (!is.null(fs)) { super$initialize(fs, ro) if (!is.null(fs$data) & (length(fs$data) > 0)) { for (name in names(fs$data)) { self$data[[name]] <- cbind(self$data[[name]], C=fs$data[[name]][,"C"]) } } } }, getKR = function() { if (is.null(self$KR)) { yhat <- function(r, mu, kappa) { kr.yhat(r, mu[,1:2], mu[,3], kappa) } compute.conc <- function(mu) { kr.compute.concentration(mu[,1:2], mu[,3]) } Gss <- list() for (id in self$getIDs()) { Gss[[id]] <- self$getFeature(id) } for (n in names(Gss)) { if (sum(Gss[[n]][,"C"]) <= 2) { Gss[[n]] <- NULL } } return(compute.kernel.estimate(Gss, self$ro$phi0, yhat, compute.conc)) } return(self$KR) } ) ) projection.ReconstructedCountSet <- function(r, phi0, transform=identity.transform, ids=r$getIDs(), axisdir=cbind(phi=90, lambda=0), projection=azimuthal.equalarea, proj.centre=cbind(phi=0, lambda=0), markup=NULL, max.proj.dim=NULL, ...) { for (id in ids) { if (!is.null(r$getFeature(id))) { if (nrow(r$getFeature(id)) > 0) { rc <- projection(rotate.axis(transform(r$getFeature(id)[,c("phi", "lambda")], phi0=r$phi0), axisdir*pi/180), proj.centre=pi/180*proj.centre) text(rc[,"x"], rc[,"y"], r$getFeature(id)[,"C"], col=r$cols[[id]], ...) } } } }
"pois.daly" <- function(x, pt = 1, conf.level = 0.95){ xc <- cbind(x,conf.level,pt) pt2 <- xc[,3] results <- matrix(NA,nrow(xc),6) cipois <- function(x, conf.level = 0.95){ if(x!=0){ LL <- qgamma((1 - conf.level)/2, x) UL <- qgamma((1 + conf.level)/2, x + 1) } else { if(x==0){ LL <- 0 UL <- -log(1 - conf.level) } } data.frame(x = x, lower = LL, upper = UL) } for(i in 1:nrow(xc)){ alp <- 1-xc[i,2] daly <- cipois(x = xc[i, 1], conf.level = xc[i, 2]) LCL <- daly$lower/pt2[i] UCL <- daly$upper/pt2[i] results[i,] <- c(xc[i,1],pt2[i],xc[i,1]/pt2[i],LCL,UCL,xc[i,2]) } coln <- c("x","pt","rate","lower","upper","conf.level") colnames(results) <- coln data.frame(results) }
library(statpsych) test_that("ci.prop1 returns valid matrix", { colnames_expected <- c( "Estimate", "SE", "LL", "UL" ) res <- ci.prop1(.05, 12, 100) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(2, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) }) test_that("ci.pairs.prop1 returns valid matrix", { colnames_expected <- c( "", "", "Estimate", "SE", "LL", "UL" ) f <- c(125, 82, 92) res <- ci.pairs.prop1(.05, f) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(3, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) }) test_that("ci.prop2 returns valid matrix", { colnames_expected <- c( "Estimate", "SE", "LL", "UL" ) res <- ci.prop2(.05, 35, 21, 150, 150) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(1, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) }) test_that("ci.ratio.prop2 returns valid matrix", { colnames_expected <- c( "Estimate", "LL", "UL" ) res <- ci.ratio.prop2(.05, 35, 21, 150, 150) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(1, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) }) test_that("ci.lc.prop.bs returns valid matrix", { colnames_expected <- c( "Estimate", "SE", "z", "p", "LL", "UL" ) f <- c(26, 24, 38) n <- c(60, 60, 60) c <- c(-.5, -.5, 1) res <- ci.lc.prop.bs(.05, f, n, c) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(1, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) }) test_that("ci.pairs.prop.bs returns valid matrix", { colnames_expected <- c( "", "", "Estimate", "SE", "z", "p", "LL", "UL" ) f <- c(111, 161, 132) n <- c(200, 200, 200) res <- ci.pairs.prop.bs(.05, f, n) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(3, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) }) test_that("ci.slope.prop.bs returns valid matrix", { colnames_expected <- c( "Estimate", "SE", "z", "p", "LL", "UL" ) f <- c(14, 27, 38) n <- c(100, 100, 100) x <- c(10, 20, 40) res <- ci.slope.prop.bs(.05, f, n, x) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(1, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) }) test_that("ci.prop.ps returns valid matrix", { colnames_expected <- c( "Estimate", "SE", "LL", "UL" ) res <- ci.prop.ps(.05, 12, 26, 4, 6) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(1, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) }) test_that("ci.ratio.prop.ps returns valid matrix", { colnames_expected <- c( "Estimate", "LL", "UL" ) res <- ci.ratio.prop.ps(.05, 12, 26, 4, 6) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(1, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) }) test_that("ci.condslope.log returns valid matrix", { colnames_expected <- c( "Estimate", "exp(Estimate)", "z", "p", "LL", "UL" ) res <- ci.condslope.log(.05, .132, .154, .031, .021, .015, 5.2, 10.6) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(2, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) }) test_that("ci.oddsratio returns valid matrix", { colnames_expected <- c( "Estimate", "LL", "UL" ) res <- ci.oddsratio(.05, 229, 28, 96, 24) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(1, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) }) test_that("ci.yule returns valid matrix", { colnames_expected <- c( "Estimate", "LL", "UL" ) res <- ci.yule(.05, 229, 28, 96, 24) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(1, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) }) test_that("ci.phi returns valid matrix", { colnames_expected <- c( "Estimate", "SE", "LL", "UL" ) res <- ci.phi(.05, 229, 28, 96, 24) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(1, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) }) test_that("ci.biphi returns valid matrix", { colnames_expected <- c( "Estimate", "SE", "LL", "UL" ) res <- ci.biphi(.05, 46, 15, 100, 100) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(1, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) }) test_that("ci.tetra returns valid matrix", { colnames_expected <- c( "Estimate", "LL", "UL" ) res <- ci.tetra(.05, 46, 15, 54, 85) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(1, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) }) test_that("ci.kappa returns valid matrix", { colnames_expected <- c( "Estimate", "SE", "LL", "UL" ) res <- ci.kappa(.05, 31, 12, 4, 58) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(2, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) }) test_that("ci.agree returns valid matrix", { colnames_expected <- c( "Estimate", "SE", "LL", "UL" ) res <- ci.agree(.05, 100, 80, 4) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(1, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) }) test_that("ci.popsize returns valid matrix", { colnames_expected <- c( "Estimate", "LL", "UL" ) res <- ci.popsize(.05, 794, 710, 741) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(1, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) }) test_that("test.prop1 returns valid matrix", { colnames_expected <- c( "Estimate", "z", "p" ) res <- test.prop1(9, 20, .2) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(1, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) }) test_that("test.prop2 returns valid matrix", { colnames_expected <- c( "Estimate", "z", "p" ) res <- test.prop2(11, 26, 50, 50) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(1, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) }) test_that("test.prop.bs returns valid matrix", { colnames_expected <- c( "Chi-square", "df", "p" ) f <- c(35, 30, 15) n <- c(50, 50, 50) res <- test.prop.bs (f, n) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(1, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) }) test_that("test.prop.ps returns valid matrix", { colnames_expected <- c( "Estimate", "z", "p" ) res <- test.prop.ps(156, 96, 68, 80) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(1, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) }) test_that("size.ci.prop1 returns valid numeric", { res <- size.ci.prop1(.05, .4, .2) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(res[[1,1]], 93) }) test_that("size.ci.prop2 returns valid numeric", { res <- size.ci.prop2(.05, .4, .2, .15) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(res[[1,1]], 274) }) test_that("size.ci.ratio.prop2 returns valid numeric", { res <- size.ci.ratio.prop2(.05, .2, .1, 2) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(res[[1,1]], 416) }) test_that("size.ci.lc.prop.bs returns valid numeric", { p <- c(.25, .30, .50, .50) v <- c(.5, .5, -.5, -.5) res <- size.ci.lc.prop.bs(.05, p, .2, v) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(res[[1,1]], 87) }) test_that("size.ci.prop.ps returns valid numeric", { p <- c(.25, .30, .50, .50) v <- c(.5, .5, -.5, -.5) res <- size.ci.prop.ps(.05, .2, .3, .8, .1) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(res[[1,1]], 118) }) test_that("size.ci.ratio.prop.ps returns valid numeric", { res <- size.ci.ratio.prop.ps(.05, .4, .2, .7, 2) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(res[[1,1]], 67) }) test_that("size.ci.agree returns valid numeric", { res <- size.ci.agree(.05, .8, .2) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(res[[1,1]], 139) }) test_that("size.test.prop1 returns valid numeric", { res <- size.test.prop1(.05, .9, .5, .2) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(res[[1,1]], 66) }) test_that("size.test.prop2 returns valid numeric", { res <- size.test.prop2(.05, .8, .2, .4, .2) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(res[[1,1]], 79) }) test_that("size.test.lc.prop.bs returns valid numeric", { p <- c(.25, .30, .50, .50) v <- c(.5, .5, -.5, -.5) res <- size.test.lc.prop.bs(.05, .9, p, .15, v) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(res[[1,1]], 105) }) test_that("size.equiv.prop2 returns valid numeric", { res <- size.equiv.prop2(.1, .8, .30, .35, .15) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(res[[1,1]], 288) }) test_that("size.supinf.prop2 returns valid numeric", { res <- size.supinf.prop2(.05, .9, .35, .20, .05) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(res[[1,1]], 408) }) test_that("size.test.prop.ps returns valid numeric", { res <- size.test.prop.ps(.05, .80, .4, .3, .5, .1) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(res[[1,1]], 177) }) test_that("size.equiv.prop.ps returns valid numeric", { res <- size.equiv.prop.ps(.1, .8, .30, .35, .40, .15) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(res[[1,1]], 173) }) test_that("size.supinf.prop.ps returns valid numeric", { res <- size.supinf.prop.ps(.05, .9, .35, .20, .45, .05) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(res[[1,1]], 227) }) test_that("iqv returns valid matrix", { colnames_expected <- c( "Simpson", "Berger", "Shannon" ) f <- c(10, 46, 15, 3) res <- iqv(f) testthat::expect_equal(class(res), c("matrix", "array")) testthat::expect_equal(dim(res), c(1, length(colnames_expected))) testthat::expect_equal(colnames(res), colnames_expected) })
utils::globalVariables(c("rawdata", "stratum")) roundR <- function(roundin, level = 2, smooth = FALSE, textout = TRUE, drop0 = FALSE, .german = FALSE, .bigmark = FALSE) { if (.german) { textout <- TRUE } decimalmark <- ifelse(.german, ",", ".") bigmark <- ifelse(.german, ".", ",") if (!.bigmark) { bigmark <- "" } if (!is.matrix(roundin)) { roundin <- matrix(roundin) } roundin <- as.numeric(roundin) roundout <- roundin roundlevel <- 0 roundlevel <- max( 0, level - floor( log10( max(abs(roundin), na.rm = TRUE) ) + 1 ) ) roundout[which(!is.na(roundout))] <- round(roundin[which(!is.na(roundin))], roundlevel) if (smooth & max(abs(roundout), na.rm = TRUE) != 0) { roundout[which(!is.na(roundout))] <- round( roundin[which(!is.na(roundin))] / 10^ceiling(log10(max(abs(roundin), na.rm = TRUE)) - level) ) * 10^ceiling(log10(max(abs(roundin), na.rm = TRUE)) - level) } if (textout) { roundout[which(!is.na(roundout))] <- formatC(roundout[which(!is.na(roundout))], format = "f", digits = roundlevel, drop0trailing = drop0, big.mark = bigmark, decimal.mark = decimalmark ) } return(roundout) } markSign <- function(SignIn, plabel = c("n.s.", "+", "*", "**", "***")) { SignIn <- as.numeric(SignIn) SignOut <- cut(SignIn, breaks = c(-Inf, .001, .01, .05, .1, 1), labels = rev(plabel) ) return(SignOut) } formatP <- function(pIn, ndigits = 3, textout = TRUE, pretext = FALSE, mark = FALSE, german_num = FALSE) { decimal.mark <- ifelse(german_num, ",", ".") pIn_is_matrix <- is.matrix(pIn) if(pIn_is_matrix){ pIn <- apply(pIn,c(1,2),as.numeric) } else{ pIn <- as.numeric(pIn) } formatp <- NA_character_ if (length(na.omit(pIn))>0) { if (!pIn_is_matrix) { pIn <- matrix(pIn) } formatp <- apply( X = pIn, MARGIN = c(1, 2), max, 10**(-ndigits), na.rm = FALSE ) %>% apply(MARGIN = c(1, 2), round, ndigits) %>% apply( MARGIN = c(1, 2), formatC, format = "f", digits = ndigits, drop0trailing = FALSE, decimal.mark = decimal.mark ) if (pretext) { for (row_i in 1:nrow(pIn)) { for (col_i in 1:ncol(pIn)) { formatp[row_i, col_i] <- paste( ifelse(pIn[row_i, col_i] < 10**(-ndigits), "<", "=" ), formatp[row_i, col_i] ) } } } if (mark) { formatp <- matrix( paste( formatp, apply(gsub("[\\<\\=]", "", formatp), c(1, 2), markSign) ), ncol = ncol(pIn) ) } if (textout == FALSE & pretext == FALSE) { formatp <- apply(formatp, MARGIN = c(1, 2), as.numeric) } if(!pIn_is_matrix){ formatp <- as.vector(formatp) } } return(formatp) } FindVars <- function(varnames, allnames = NULL, exact = FALSE, exclude = NA, casesensitive = TRUE, fixed = FALSE) { if (is.null(allnames)) { allnames <- colnames(get("rawdata")) } if (fixed) { exact <- FALSE } allnames_tmp <- allnames if (!casesensitive) { varnames <- tolower(varnames) allnames_tmp <- tolower(allnames) exclude <- tolower(exclude) } vars <- numeric() evars <- numeric() if (exact) { for (i in 1:length(varnames)) { vars <- c(vars, grep(paste0("^", varnames[i], "$"), allnames_tmp)) } vars <- unique(vars) } else { for (i in 1:length(varnames)) { vars <- c(vars, grep(varnames[i], allnames_tmp, fixed = fixed )) } vars <- sort(unique(vars)) if (any(!is.na(exclude))) { for (i in 1:length(exclude)) { evars <- c(evars, grep(exclude[i], allnames_tmp)) } evars <- unique(na.omit(match( sort(unique(evars)), vars ))) if (length(evars) > 0) { vars <- vars[-evars] } } vars <- unique(vars) } return(list( index = vars, names = allnames[vars], bticked = bt(allnames[vars]), symbols = rlang::syms(allnames[vars]), count = length(vars) )) } print_kable <- function(t, nrows = 30, caption = "", ncols = 100, ...) { for (block_i in 1:ceiling(nrow(t) / nrows)) { for (col_i in 1:ceiling((ncol(t) - 1) / ncols)) { if (block_i + col_i > 2) { cat("\\newpage\n\n") } print( knitr::kable( t[ (1 + (block_i - 1) * nrows): min(nrow(t), block_i * nrows), c(1, (2 + (col_i - 1) * ncols):min((1 + col_i * ncols), ncol(t))) ], row.names = FALSE, caption = paste0( ifelse(block_i + col_i > 2, "continued: ", ""), caption, " \n \n " ) ) ) cat(" \n \n") } } } pdf_kable <- function(.input, width1 = 6, twidth = 14, tposition = "left", innercaption = NULL, caption = "", foot = NULL, escape = TRUE) { ncols <- ncol(.input) out <- knitr::kable(.input, format = "latex", booktabs = TRUE, linesep = "", escape = escape, caption = caption, align = c("l", rep("c", ncols - 1)) ) %>% kableExtra::kable_styling( position = tposition, latex_options = c( "striped", "hold_position" ) ) %>% kableExtra::column_spec(-1, width = paste0((twidth - width1) / (ncols - 1), "cm"), ) %>% kableExtra::column_spec(1, bold = TRUE, width = paste0(width1, "cm")) %>% kableExtra::row_spec(0, bold = TRUE) if (!is.null(innercaption)) { caption1 <- c(caption = ncols) names(caption1) <- caption out <- out %>% kableExtra::add_header_above(caption1, bold = TRUE) } if (!is.null(foot)) { out <- out %>% kableExtra::footnote(general = foot) } return(out) } cn <- function(data = rawdata) { colnames(data) } bt <- function(x, remove = FALSE) { if (remove) { return(gsub("`", "", x)) } else { return(paste0("`", x, "`")) } } tab.search <- function(searchdata = rawdata, pattern, find.all = T, names.only = FALSE) { if (!is.character(pattern)) { pattern <- as.character(pattern) } positions <- purrr::map(searchdata, str_which, pattern = pattern) %>% purrr::compact() if (!find.all) { positions <- purrr::map(positions, nth, n = 1) } if (names.only) { positions <- names(positions) } return(positions) }
toString.XMLNode <- function(x, ...) { .tempXMLOutput = "" con <- textConnection(".tempXMLOutput", "w", local = TRUE) sink(con) print(x) sink() close(con) paste(.tempXMLOutput, collapse="\n") }