code
stringlengths
1
13.8M
AIC.ssym <- function(object, ...){ gle <- sum(object$gle.mu) + sum(object$gle.phi) AIC <- round(-2*sum(object$lpdf) + 2*(gle), digits=3) y <- object$z_es*sqrt(object$phi.fitted) + object$mu.fitted if(object$censored==FALSE) attr(AIC,"log") <- round(-2*sum(object$lpdf) + 2*(gle) + 2*sum(y), digits=3) else attr(AIC,"log") <- round(-2*sum(object$lpdf) + 2*(gle) + 2*sum(y[object$event==0]), digits=3) AIC }
fieldsmissing <- function (dat, fields) { ck <- checkdatastr(dat) if (any(ck$Present == FALSE)==TRUE) { fa <- ck[ck$Present == FALSE,1] fd<-as.character(fa) msg<-paste(fd,collapse=", ") stop(paste("Fields missing: ", msg)) } }
context("CRPS for gpd distribution") FF <- function(shape) { if (shape == 0) { function(x) { x <- exp(-x) x[x > 1] <- 1 1 - x } } else { function(x) { x <- 1 + shape * x x[x < 0] <- 0 x <- x^(-1/shape) x[x > 1] <- 1 1 - x } } } test_that("computed values are correct", { const <- 0.281636441 expect_equal(crps_gpd(.3, 0), const) expect_equal(crps_gpd(.3 + .1, 0, location = .1), const) expect_equal(crps_gpd(.3 * .9, 0, scale = .9), const * .9) const <- 0.546254141 expect_equal(crps_gpd(.3, .7), const) expect_equal(crps_gpd(.3 + .1, .7, location = .1), const) expect_equal(crps_gpd(.3 * .9, .7, scale = .9), const * .9) const <- 0.157583485 expect_equal(crps_gpd(.3, -.7), const) expect_equal(crps_gpd(.3 + .1, -.7, location = .1), const) expect_equal(crps_gpd(.3 * .9, -.7, scale = .9), const * .9) })
infl_result <- eventReactive(input$submit_infl, { if (input$infl_use_prev) { k <- model() } else { data <- final_split$train k <- glm(input$infl_fmla, data = data, family = binomial(link = "logit")) } return(k) }) output$infl_out <- renderPlot({ blorr::blr_plot_diag_influence(infl_result()) }) lev_result <- eventReactive(input$submit_lev, { if (input$lev_use_prev) { k <- model() } else { data <- final_split$train k <- glm(input$lev_fmla, data = data, family = binomial(link = "logit")) } return(k) }) output$lev_out <- renderPlot({ blorr::blr_plot_diag_leverage(lev_result()) }) fit_result <- eventReactive(input$submit_fit, { if (input$fit_use_prev) { k <- model() } else { data <- final_split$train k <- glm(input$fit_fmla, data = data, family = binomial(link = "logit")) } return(k) }) output$fit_out <- renderPlot({ blorr::blr_plot_diag_fit(fit_result()) }) dfbetas_result <- eventReactive(input$submit_dfbetas, { if (input$dfbetas_use_prev) { k <- model() } else { data <- final_split$train k <- glm(input$dfbetas_fmla, data = data, family = binomial(link = "logit")) } return(k) }) output$dfbetas_out <- renderPlot({ blorr::blr_plot_dfbetas_panel(dfbetas_result()) })
context("Check that NCA calculations are working") test_that("Extravascular single dose data is computed corectly",{ exvas_sd_dat <- readr::read_table("data_exvas_sd.txt",skip = 1) exvas_sd_true_result <- readr::read_csv("results_exvas_sd_true.csv") exvas_sd_true_result <- exvas_sd_true_result %>% tidyr::gather(var, val, 2:ncol(.)) %>% tidyr::spread_(names(.)[1], "val") out <- ncappc(obsFile=exvas_sd_dat, psnOut=TRUE, method="linear", evid = FALSE, onlyNCA = T, extrapolate = T, printOut = F, noPlot = T) calc_vals <- out$ncaOutput %>% tibble::as_tibble() %>% dplyr::mutate_all(dplyr::funs(as.numeric(as.character(.)))) true_vals <- exvas_sd_true_result %>% dplyr::filter(var=="Linear_trapezoidal_WinNonlin") %>% dplyr::rename("ID"=var) %>% dplyr::mutate(ID=1) expect_length(names(true_vals)[!(names(true_vals) %in% names(calc_vals))],0) calc_vals_sub <- calc_vals %>% dplyr::select(names(calc_vals)[(names(calc_vals) %in% names(true_vals))]) %>% dplyr::select(names(true_vals)) expect_equal(data.frame(calc_vals_sub),data.frame(true_vals),tolerance=0.005) out <- ncappc(obsFile=exvas_sd_dat, psnOut=TRUE, method="linearup-logdown", evid = FALSE, onlyNCA = T, extrapolate = T, printOut = F, noPlot = T) calc_vals <- out$ncaOutput %>% tibble::as_tibble() %>% dplyr::mutate_all(dplyr::funs(as.numeric(as.character(.)))) true_vals <- exvas_sd_true_result %>% dplyr::filter(var=="Linear_log_trapezoidal_WinNonlin") %>% dplyr::rename("ID"=var) %>% dplyr::mutate(ID=1) expect_length(names(true_vals)[!(names(true_vals) %in% names(calc_vals))],0) calc_vals_sub <- calc_vals %>% dplyr::select(names(calc_vals)[(names(calc_vals) %in% names(true_vals))]) %>% dplyr::select(names(true_vals)) expect_equal(data.frame(calc_vals_sub),data.frame(true_vals),tolerance=0.005) }) test_that("Extravascular multiple dose data is computed corectly",{ exvas_md_dat <- readr::read_table("data_exvas_md.txt",skip = 1) exvas_md_dat[9,"TIME"] <- 96 exvas_md_true_result <- readr::read_csv("results_exvas_md_true.csv") exvas_md_true_result <- exvas_md_true_result %>% tidyr::gather(var, val, 2:ncol(.)) %>% tidyr::spread_(names(.)[1], "val") out <- ncappc(obsFile=exvas_md_dat, psnOut=TRUE, method="linear", doseType = "ss", doseTime = 96, Tau = 12, evid = TRUE, onlyNCA = T, extrapolate = T, printOut = F, noPlot = T) calc_vals <- out$ncaOutput %>% tibble::as_tibble() %>% dplyr::mutate_all(dplyr::funs(as.numeric(as.character(.)))) true_vals <- exvas_md_true_result %>% dplyr::filter(var=="Linear_trapezoidal_WinNonlin") %>% dplyr::rename("ID"=var) %>% dplyr::mutate(ID=1) expect_length(names(true_vals)[!(names(true_vals) %in% names(calc_vals))],0) calc_vals_sub <- calc_vals %>% dplyr::select(names(calc_vals)[(names(calc_vals) %in% names(true_vals))]) %>% dplyr::select(names(true_vals)) expect_equal(data.frame(calc_vals_sub),data.frame(true_vals),tolerance=0.005) out <- ncappc(obsFile=exvas_md_dat, psnOut=TRUE, method="linearup-logdown", doseType = "ss", doseTime = 96, Tau = 12, evid = TRUE, onlyNCA = T, extrapolate = T, printOut = F, noPlot = T) calc_vals <- out$ncaOutput %>% tibble::as_tibble() %>% dplyr::mutate_all(dplyr::funs(as.numeric(as.character(.)))) true_vals <- exvas_md_true_result %>% dplyr::filter(var=="Linear_log_trapezoidal_WinNonlin") %>% dplyr::rename("ID"=var) %>% dplyr::mutate(ID=1) expect_length(names(true_vals)[!(names(true_vals) %in% names(calc_vals))],0) calc_vals_sub <- calc_vals %>% dplyr::select(names(calc_vals)[(names(calc_vals) %in% names(true_vals))]) %>% dplyr::select(names(true_vals)) expect_equal(data.frame(calc_vals_sub),data.frame(true_vals),tolerance=0.005) }) test_that("IV single dose data is computed corectly",{ iv_sd_dat <- readr::read_table("data_iv_sd.txt",skip = 1) iv_sd_true_result <- readr::read_csv("results_iv_sd_true.csv") iv_sd_true_result <- iv_sd_true_result %>% tidyr::gather(var, val, 2:ncol(.)) %>% tidyr::spread_(names(.)[1], "val") out <- ncappc(obsFile=iv_sd_dat, psnOut=TRUE, method="linear", adminType = "iv-bolus", evid = FALSE, onlyNCA = T, extrapolate = T, printOut = F, noPlot = T) calc_vals <- out$ncaOutput %>% tibble::as_tibble() %>% dplyr::mutate_all(dplyr::funs(as.numeric(as.character(.)))) true_vals <- iv_sd_true_result %>% dplyr::filter(var=="Linear_trapezoidal_WinNonlin") %>% dplyr::rename("ID"=var) %>% dplyr::mutate(ID=1) expect_length(names(true_vals)[!(names(true_vals) %in% names(calc_vals))],0) calc_vals_sub <- calc_vals %>% dplyr::select(names(calc_vals)[(names(calc_vals) %in% names(true_vals))]) %>% dplyr::select(names(true_vals)) expect_equal(data.frame(calc_vals_sub),data.frame(true_vals),tolerance=0.005) out <- ncappc(obsFile=iv_sd_dat, psnOut=TRUE, method="linearup-logdown", adminType = "iv-bolus", evid = FALSE, onlyNCA = T, extrapolate = T, printOut = F, noPlot = T) calc_vals <- out$ncaOutput %>% tibble::as_tibble() %>% dplyr::mutate_all(dplyr::funs(as.numeric(as.character(.)))) true_vals <- iv_sd_true_result %>% dplyr::filter(var=="Linear_log_trapezoidal_WinNonlin") %>% dplyr::rename("ID"=var) %>% dplyr::mutate(ID=1) expect_length(names(true_vals)[!(names(true_vals) %in% names(calc_vals))],0) calc_vals_sub <- calc_vals %>% dplyr::select(names(calc_vals)[(names(calc_vals) %in% names(true_vals))]) %>% dplyr::select(names(true_vals)) expect_equal(data.frame(calc_vals_sub),data.frame(true_vals),tolerance=0.005) }) test_that("IV multiple dose data is computed corectly",{ iv_md_dat <- readr::read_table("data_iv_md.txt",skip = 1) iv_md_dat[9,"TIME"] <- 96 iv_md_true_result <- readr::read_csv("results_iv_md_true.csv") iv_md_true_result <- iv_md_true_result %>% tidyr::gather(var, val, 2:ncol(.)) %>% tidyr::spread_(names(.)[1], "val") out <- ncappc(obsFile=iv_md_dat, psnOut=TRUE, method="linear", adminType = "iv-bolus", doseType = "ss", doseTime = 96, backExtrp = T, Tau = 12, onlyNCA = T, extrapolate = T, printOut = F, noPlot = T) calc_vals <- out$ncaOutput %>% tibble::as_tibble() %>% dplyr::mutate_all(dplyr::funs(as.numeric(as.character(.)))) true_vals <- iv_md_true_result %>% dplyr::filter(var=="Linear_trapezoidal_WinNonlin") %>% dplyr::rename("ID"=var) %>% dplyr::mutate(ID=1) expect_length(names(true_vals)[!(names(true_vals) %in% names(calc_vals))],0) calc_vals_sub <- calc_vals %>% dplyr::select(names(calc_vals)[(names(calc_vals) %in% names(true_vals))]) %>% dplyr::select(names(true_vals)) expect_equal(data.frame(calc_vals_sub),data.frame(true_vals),tolerance=0.005) out <- ncappc(obsFile=iv_md_dat, psnOut=TRUE, method="linearup-logdown", adminType = "iv-bolus", doseType = "ss", doseTime = 96, backExtrp = T, Tau = 12, onlyNCA = T, extrapolate = T, printOut = F, noPlot = T) calc_vals <- out$ncaOutput %>% tibble::as_tibble() %>% dplyr::mutate_all(dplyr::funs(as.numeric(as.character(.)))) true_vals <- iv_md_true_result %>% dplyr::filter(var=="Linear_log_trapezoidal_WinNonlin") %>% dplyr::rename("ID"=var) %>% dplyr::mutate(ID=1) expect_length(names(true_vals)[!(names(true_vals) %in% names(calc_vals))],0) calc_vals_sub <- calc_vals %>% dplyr::select(names(calc_vals)[(names(calc_vals) %in% names(true_vals))]) %>% dplyr::select(names(true_vals)) expect_equal(data.frame(calc_vals_sub),data.frame(true_vals),tolerance=0.005) }) test_that("IV infusion single dose data is computed corectly",{ iv_inf_sd_dat <- readr::read_table("data_iv_inf_sd.txt",skip = 1) iv_inf_sd_true_result <- readr::read_csv("results_iv_inf_sd_true.csv") iv_inf_sd_true_result <- iv_inf_sd_true_result %>% tidyr::gather(var, val, 2:ncol(.)) %>% tidyr::spread_(names(.)[1], "val") out <- ncappc(obsFile=iv_inf_sd_dat, psnOut=TRUE, method="linear", adminType = "iv-infusion", evid = FALSE, onlyNCA = T, extrapolate = T, printOut = F, noPlot = T) calc_vals <- out$ncaOutput %>% tibble::as_tibble() %>% dplyr::mutate_all(dplyr::funs(as.numeric(as.character(.)))) true_vals <- iv_inf_sd_true_result %>% dplyr::filter(var=="Linear_trapezoidal_WinNonlin") %>% dplyr::rename("ID"=var) %>% dplyr::mutate(ID=1) expect_length(names(true_vals)[!(names(true_vals) %in% names(calc_vals))],0) calc_vals_sub <- calc_vals %>% dplyr::select(names(calc_vals)[(names(calc_vals) %in% names(true_vals))]) %>% dplyr::select(names(true_vals)) expect_equal(data.frame(calc_vals_sub),data.frame(true_vals),tolerance=0.005) out <- ncappc(obsFile=iv_inf_sd_dat, psnOut=TRUE, method="linearup-logdown", adminType = "iv-infusion", evid = FALSE, onlyNCA = T, extrapolate = T, printOut = F, noPlot = T) calc_vals <- out$ncaOutput %>% tibble::as_tibble() %>% dplyr::mutate_all(dplyr::funs(as.numeric(as.character(.)))) true_vals <- iv_inf_sd_true_result %>% dplyr::filter(var=="Linear_log_trapezoidal_WinNonlin") %>% dplyr::rename("ID"=var) %>% dplyr::mutate(ID=1) expect_length(names(true_vals)[!(names(true_vals) %in% names(calc_vals))],0) calc_vals_sub <- calc_vals %>% dplyr::select(names(calc_vals)[(names(calc_vals) %in% names(true_vals))]) %>% dplyr::select(names(true_vals)) expect_equal(data.frame(calc_vals_sub),data.frame(true_vals),tolerance=0.005) }) test_that("IV infusion multiple dose data is computed corectly",{ iv_inf_md_dat <- readr::read_table("data_iv_inf_md.txt",skip = 1) iv_inf_md_dat[9,"TIME"] <- 96 iv_inf_md_true_result <- readr::read_csv("results_iv_inf_md_true.csv") iv_inf_md_true_result <- iv_inf_md_true_result %>% tidyr::gather(var, val, 2:ncol(.)) %>% tidyr::spread_(names(.)[1], "val") out <- ncappc(obsFile=iv_inf_md_dat, psnOut=TRUE, method="linear", adminType = "iv-infusion", doseType = "ss", doseTime = 96, backExtrp = T, Tau = 12, TI=2, onlyNCA = T, extrapolate = T, printOut = F, noPlot = T) calc_vals <- out$ncaOutput %>% tibble::as_tibble() %>% dplyr::mutate_all(dplyr::funs(as.numeric(as.character(.)))) true_vals <- iv_inf_md_true_result %>% dplyr::filter(var=="Linear_trapezoidal_WinNonlin") %>% dplyr::rename("ID"=var) %>% dplyr::mutate(ID=1) expect_length(names(true_vals)[!(names(true_vals) %in% names(calc_vals))],0) calc_vals_sub <- calc_vals %>% dplyr::select(names(calc_vals)[(names(calc_vals) %in% names(true_vals))]) %>% dplyr::select(names(true_vals)) expect_equal(data.frame(calc_vals_sub),data.frame(true_vals),tolerance=0.005) out <- ncappc(obsFile=iv_inf_md_dat, psnOut=TRUE, method="linearup-logdown", adminType = "iv-infusion", doseType = "ss", doseTime = 96, backExtrp = T, Tau = 12, TI=2, onlyNCA = T, extrapolate = T, printOut = F, noPlot = T) calc_vals <- out$ncaOutput %>% tibble::as_tibble() %>% dplyr::mutate_all(dplyr::funs(as.numeric(as.character(.)))) true_vals <- iv_inf_md_true_result %>% dplyr::filter(var=="Linear_log_trapezoidal_WinNonlin") %>% dplyr::rename("ID"=var) %>% dplyr::mutate(ID=1) expect_length(names(true_vals)[!(names(true_vals) %in% names(calc_vals))],0) calc_vals_sub <- calc_vals %>% dplyr::select(names(calc_vals)[(names(calc_vals) %in% names(true_vals))]) %>% dplyr::select(names(true_vals)) expect_equal(data.frame(calc_vals_sub),data.frame(true_vals),tolerance=0.005) }) test_that("force_extrapolate works corectly",{ data_1 <- tibble::tibble( ID=1, TIME = c(0,0.25,0.5,1,1.5,2,3,4,6,8,12,16,24), DV=c(0, 0.07, 0.14, 0.21, 0.24, 0.27, 0.26, 0.25, 0.22, 0.19, 0.13, 0.081, 0.033) ) out_1 <- ncappc(obsFile=data_1, onlyNCA = T, extrapolate = T, printOut = F, evid = FALSE, noPlot = T) out_2 <- ncappc(obsFile=data_1, onlyNCA = T, extrapolate = T, printOut = F, evid = FALSE, noPlot = T, force_extrapolate=T) expect_true(all(out_1$ncaOutput==out_2$ncaOutput,na.rm = T)) data_2 <- data_1 %>% dplyr::filter(TIME<3) expect_message(out_2 <- ncappc(obsFile=data_2, onlyNCA = T, extrapolate = T, printOut = F, evid = FALSE, noPlot = T, force_extrapolate=T)) expect_true(is.na(out_2$ncaOutput$AUCINF_obs)) data_3 <- data_1 %>% dplyr::filter(TIME>17|TIME<3) out_3 <- ncappc(obsFile=data_3, onlyNCA = T, extrapolate = T, printOut = F, evid = FALSE, noPlot = T, force_extrapolate=T) expect_true(!is.na(out_3$ncaOutput$AUCINF_obs)) data_4 <- data_1 %>% dplyr::filter(TIME>15|TIME<3) out_4 <- ncappc(obsFile=data_4, onlyNCA = T, extrapolate = T, printOut = F, evid = FALSE, noPlot = T, force_extrapolate=T) expect_true(!is.na(out_4$ncaOutput$AUCINF_obs)) })
multiverse.plot <- function(multiverse, title = "", vline = "none", heights = c(4,5), SE = FALSE) { if(SE == TRUE & length(heights) != 3) { stop("heights must be length 3 is SE = TRUE") } if(class(multiverse) == "list") { x <- length(multiverse) for(i in 1:x){ if(class(multiverse[[i]]) != "multiverse") stop("not all list objects are of class multiverse") } estimate <- 0 low <- 0 high <- 0 ns <- 0 time <- 0 Bigdecision <- 0 Decision <- 0 final <- NULL final2 <- NULL ord <- order(multiverse[[1]]$estimates[,"estimate"]) for(x in 1:length(multiverse)) { final <- multiverse[[x]]$estimates final$time <- toString(x) final <- final[ord,] final$ns <- 1:nrow(final) final2 <- rbind(final2, final) } } if(class(multiverse) == "multiverse"){ final2 <- multiverse$estimates final2 <- final2[order(final2[,"estimate"]),] final2$SE <- multiverse$SE } suppressWarnings({ if(class(multiverse) == "multiverse"){ final2$ns <- 1:multiverse$nS reliability_plot <- ggplot(data = final2, aes(x = 1:multiverse$nS, y = estimate)) + geom_ribbon(aes(ymin = low, ymax = high), fill = "grey80", alpha = .8) + {if(vline!="none")geom_vline(aes(), xintercept = round(multiverse$nS * vline), linetype = "dashed", colour = "black")} + geom_point() + scale_color_manual(values = c(" labs(x = " ") + theme(legend.position = "none", strip.text.x = element_blank(), strip.text.y = element_blank(), strip.background = element_blank(), text = element_text(size=10)) + geom_hline(yintercept = 0) if(SE == FALSE) reliability_plot <- reliability_plot + ggtitle(title) + theme(plot.title = element_text(hjust = 0.5, face = "bold")) } if(class(multiverse) == "list"){ reliability_plot <- ggplot(data = final2, aes(x = ns, y = estimate, fill = time)) + geom_ribbon(aes(ymin = low, ymax = high, fill = time), alpha = .1) + {if(vline!="none")geom_vline(aes(), xintercept = round(multiverse[[1]]$nS * vline), linetype = "dashed", colour = "black")} + geom_point(aes(colour = time)) + labs(x = " ") + theme(legend.position = "top", legend.title = element_blank(), strip.text.x = element_blank(), strip.text.y = element_blank(), strip.background = element_blank(), text = element_text(size=10)) + geom_hline(yintercept = 0) + ggtitle(title) + theme(plot.title = element_text(hjust = 0.5, face = "bold")) } }) suppressWarnings({ if(class(multiverse) == "multiverse"){ final2$ns <- 1:multiverse$nS final3 <- final2 %>% gather(key = "Bigdecision", value = "Decision", -ns, -estimate, -low, -high) } if(class(multiverse) == "list"){ final3 <- final2 %>% dplyr::filter(time == 1) %>% tidyr::gather(key = "Bigdecision", value = "Decision", -ns, -estimate, -low, -high) } }) final3$Bigdecision <- factor(final3$Bigdecision, levels = c("ACC_cutoff", "RT_min", "RT_max", "RT_sd_cutoff", "split_by", "averaging_method")) suppressWarnings({ if(class(multiverse) == "multiverse"){ dashboard <- ggplot(data = subset(final3, Bigdecision %in% multiverse$cols), aes(x = ns, y = Decision, colour = Bigdecision)) + facet_grid(Bigdecision ~ ., scales = "free", space = "free", drop = ) + {if(vline!="none")geom_vline(aes(), xintercept = round(multiverse$nS*vline), linetype = "dashed", colour = "black")} + geom_point(aes(colour = Bigdecision), shape = 108, size = 6) + labs(x = "specification number") + theme_minimal() + theme(legend.position = "none", strip.text.x = element_blank(), strip.text.y = element_blank(), strip.background = element_blank(), text = element_text(size=10)) } if(class(multiverse) == "list"){ dashboard <- ggplot(data = subset(final3, Bigdecision %in% multiverse[[1]]$cols), aes(x = ns, y = Decision, colour = Bigdecision)) + facet_grid(Bigdecision ~ ., scales = "free", space = "free", drop = ) + {if(vline!="none")geom_vline(aes(), xintercept = round(multiverse[[1]]$nS*vline), linetype = "dashed", colour = "black")} + geom_point(aes(colour = Bigdecision), shape = 108, size = 6) + labs(x = "specification number") + theme_minimal() + theme(legend.position = "none", strip.text.x = element_blank(), strip.text.y = element_blank(), strip.background = element_blank(), text = element_text(size=10)) } }) if(SE == TRUE) { SE_plot <- ggplot(data = final2, aes(x = 1:multiverse$nS, y = SE)) + geom_point() + scale_color_manual(values = c(" labs(x = " ") + theme(legend.position = "none", strip.text.x = element_blank(), strip.text.y = element_blank(), strip.background = element_blank(), text = element_text(size=10)) + geom_hline(yintercept = 0) + ggtitle(title) + theme(plot.title = element_text(hjust = 0.5, face = "bold")) } if(SE == FALSE) { final_plot <- reliability_plot / dashboard + plot_layout(heights = heights) } if(SE == TRUE) { final_plot <- SE_plot / reliability_plot / dashboard + plot_layout(heights = heights) } return(final_plot) }
get_javascripts <- function(deck){ make_path <- function(asset, url){ html_file = file.path(url, asset, sprintf("%s.html", asset)) file_there = file.exists(html_file) return(html_file[file_there]) } asset_js = dir(file.path(deck$url$assets, 'js'), full.names = T, pattern = '.js$') widget_js = with(deck, make_path(widgets, url$widgets)) hilite_js = with(deck, make_path(highlighter, url$highlighters)) javascripts = lapply(c(widget_js, hilite_js), read_file) paste(paste(javascripts, collapse = '\n'), "\n") } add_stylesheets <- function(deck){ asset_css = dir(file.path(deck$url$assets, 'css'), full.names = T) widget_css = lapply(file.path(deck$url$widgets, deck$widgets, 'css'), dir, full = T) css = c(unlist(widget_css), asset_css) tpl = '{{ deck$stylesheets = whisker.render(tpl) return(deck) } get_stylesheets <- function(deck){ asset_css = dir(file.path(deck$url$assets, 'css'), full.names = T) widget_css = lapply(file.path(deck$url$widgets, deck$widgets, 'css'), dir, full = T) c(unlist(widget_css), asset_css) }
ideoView_buildMain <- function(data_frame, chromosome, chr_txt_angle=chr_txt_angle, chr_txt_size=chr_txt_size, layers=NULL) { theme <- theme(axis.text.x=element_blank(), axis.text.y=element_blank(), axis.title.x=element_blank(), axis.ticks.x=element_blank(), axis.ticks.y=element_blank(), legend.position='right') legend <- scale_fill_manual("Giemsa stain", values=c('gneg'='grey100', 'stalk'='brown3', 'acen'='brown4', 'gpos'='grey0', 'gvar'='grey0', 'gpos1'=' 'gpos2'=' 'gpos4'=' 'gpos6'=' 'gpos8'=' 'gpos10'=' 'gpos12'=' 'gpos14'=' 'gpos16'=' 'gpos18'=' 'gpos20'=' 'gpos22'=' 'gpos24'=' 'gpos26'=' 'gpos28'=' 'gpos30'=' 'gpos32'=' 'gpos34'=' 'gpos36'=' 'gpos38'=' 'gpos40'=' 'gpos42'=' 'gpos44'=' 'gpos46'=' 'gpos48'=' 'gpos50'=' 'gpos52'=' 'gpos54'=' 'gpos56'=' 'gpos58'=' 'gpos60'=' 'gpos62'=' 'gpos64'=' 'gpos66'=' 'gpos68'=' 'gpos70'=' 'gpos72'=' 'gpos74'=' 'gpos76'=' 'gpos78'=' 'gpos80'=' 'gpos82'=' 'gpos84'=' 'gpos86'=' 'gpos88'=' 'gpos90'=' 'gpos92'=' 'gpos94'=' 'gpos96'=' 'gpos98'=' 'gpos100'=' P_arm_text <- geom_text(data=subset(data_frame, data_frame$alternate == 'top'), mapping=aes_string(x='band_center', y='text_y', label='name'), angle=chr_txt_angle, hjust=0, size=chr_txt_size) Q_arm_text <- geom_text(data=subset(data_frame, data_frame$alternate == 'bottom'), mapping=aes_string(x='band_center', y='text_y', label='name'), angle=chr_txt_angle, hjust=1, size=chr_txt_size) text_line_seg_p <- geom_segment(data=subset(data_frame, data_frame$alternate == 'top'), mapping=aes_string(x='band_center', y='text_y', xend='band_center', yend='height_max')) text_line_seg_q <- geom_segment(data=subset(data_frame, data_frame$alternate == 'bottom'), mapping=aes_string(x='band_center', y='text_y', xend='band_center', yend='height_min')) ylabel <- ylab(chromosome) if(!is.null(layers)) { layers <- layers } else { layers <- geom_blank() } chr <- ggplot(data_frame, aes_string(xmin='chromStart', xmax='chromEnd', ymin='height_min', ymax='height_max')) + geom_rect(aes_string(fill='gieStain'), colour='black') + ylim(-1.2, 1.2) chr <- chr + P_arm_text + Q_arm_text + text_line_seg_p + text_line_seg_q + theme_bw() + theme + ylabel + legend + layers return(chr) }
library(captioner) table_nums <- captioner(prefix = "Table") table_nums(name = "iris", caption = "Edgar Anderson's iris data. All measurements are in centimetres.") table_nums("iris") iris_cap <- table_nums("iris") table_nums("peony", display = FALSE) fig_nums <- captioner() fig_nums("apple", "Relationship between the number of apple seeds and the size of the apple.") fig_nums("milk_fat", "Average percentage of fat in milk from various animals.") fig_nums("tree_height", "Distribution of heights in common restinga tree species.") table_nums("world_pop", "World populations ordered from greatest to least.") table_nums("dolphins", "List of dolphin species and their brain sizes.") fig_nums("milk_fat", display = "cite") fig_nums("snuff", display = "cite") fig_nums("bounce", "Bounce height (cm) of balls made of various types of rubber.") fig_nums("snuff", "Average size of snuff boxes used from 1808 to 1908.") fig_nums("bounce", display = "cite") figs_2 <- captioner(levels = 3, type = c("n", "n", "n"), infix = "-") figs_2("A", "The letter A in several typefaces.") figs_2("B", display = "cite", level = 2) bump(figs_2, level = 1) figs_2("C", "The letter C shown in fixed-width fonts.")
lkLCCRcon <- function(th,np1,np2,model,H,J,S,L,M,X,nv,n,Y1,A,B,sc=FALSE){ be = th[1:np2] la = th[np2+(1:np1)] if(H>1){ Piv = matrix(0,S,H) for(s in 1:S){ Ls = as.matrix(L[s,,]) tmp = exp(Ls%*%be) Piv[s,] = tmp/sum(tmp) } } Q = array(0,c(S,2^J,H)) Pm = matrix(0,S,2^J) for(s in 1:S){ for(h in 1:H){ if(is.null(X)) Msh = as.matrix(M[,,h,1]) else Msh = as.matrix(M[,,h,s]) if(model=="loglin"){ tmp = exp(c(Msh%*%la)) Q[s,,h] = tmp/sum(tmp) } if(model=="logit") Q[s,,h] = exp(A%*%Msh%*%la-B%*%log(1+exp(Msh%*%la))) } if(H>1) Pm[s,] = Q[s,,]%*%Piv[s,] } if(H==1) Pm = Q[,,1] phiv = Pm[,1] Pm1 = Pm[,-1] Qm1 = (1/(1-phiv))*Pm1 lk = sum(Y1*log(Qm1)) out = lk if(sc){ if(H>1){ dPiv = array(0,c(S,H,np1+np2)) for(s in 1:S){ Ls = as.matrix(L[s,,]) dPiv[s,,1:np2] = (diag(Piv[s,])-Piv[s,]%o%Piv[s,])%*%Ls } } dQ = array(0,c(S,2^J,H,np1+np2)) dPm = array(0,c(S,2^J,np1+np2)) for(s in 1:S){ for(h in 1:H){ if(is.null(X)) Msh = as.matrix(M[,,h,1]) else Msh = as.matrix(M[,,h,s]) if(model=="loglin") dQ[s,,h,np2+(1:np1)] = (diag(Q[s,,h])-Q[s,,h]%o%Q[s,,h])%*%Msh if(model=="logit"){ tmp = c(exp(Msh%*%la)/(1+exp(Msh%*%la))) dQ[s,,h,np2+(1:np1)] = Q[s,,h]*(A%*%Msh-B%*%(tmp*Msh)) } } if(H>1) for(j in 1:(np1+np2)) dPm[s,,j] = dQ[s,,,j]%*%Piv[s,]+Q[s,,]%*%dPiv[s,,j] } if(H==1) dPm = array(dQ[,,1,],c(S,2^J,np1+np2)) dphiv = dPm[,1,] dPm1 = array(dPm[,-1,],c(S,2^J-1,np1+np2)) dQm1 = array(0,c(S,2^J-1,np1+np2)) for(s in 1:S) for(j in 1:(2^J-1)){ dQm1[s,j,] = (1/(1-phiv[s])^2)*dphiv[s,]*Pm1[s,j]+(1/(1-phiv[s]))*dPm1[s,j,] } Dyb = 0 for(s in 1:S) Dyb = Dyb+t(dQm1[s,,])%*%(Y1[s,]/Qm1[s,]) out = list(lk=lk,st=Dyb,dphiv=dphiv) } return(out) }
sampler_RW_PF <- nimbleFunction( name = 'sampler_RW_PF', contains = sampler_BASE, setup = function(model, mvSaved, target, control) { adaptive <- extractControlElement(control, 'adaptive', TRUE) adaptInterval <- extractControlElement(control, 'adaptInterval', 200) scale <- extractControlElement(control, 'scale', 1) m <- extractControlElement(control, 'pfNparticles', 1000) existingPF <- extractControlElement(control, 'pf', NULL) filterType <- extractControlElement(control, 'pfType', 'bootstrap') filterControl <- extractControlElement(control, 'pfControl', list()) optimizeM <- extractControlElement(control, 'pfOptimizeNparticles', FALSE) latents <- extractControlElement(control, 'latents', error = 'RW_PF sampler missing required control argument: latents') if('pfLookahead' %in% names(control)) { warning("The `pfLookahead` control list argument is deprecated and will not be supported in future versions of `nimbleSMC`. Please specify the lookahead function via the pfControl argument instead.") filterControl$lookahead <- control[['pfLookahead']] } else if(!('lookahead' %in% names(filterControl))) { filterControl$lookahead <- 'simulate' } targetAsScalar <- model$expandNodeNames(target, returnScalarComponents = TRUE) calcNodes <- model$getDependencies(target) latentSamp <- FALSE MCMCmonitors <- tryCatch(parent.frame(2)$conf$monitors, error = function(e) e) if(identical(MCMCmonitors, TRUE)) latentSamp <- TRUE else if(any(model$expandNodeNames(latents) %in% model$expandNodeNames(MCMCmonitors))) latentSamp <- TRUE latentDep <- model$getDependencies(latents) topParams <- model$getNodeNames(stochOnly=TRUE, includeData=FALSE, topOnly=TRUE) optimizeM <- as.integer(optimizeM) scaleOriginal <- scale timesRan <- 0 timesAccepted <- 0 timesAdapted <- 0 prevLL <- 0 nVarEsts <- 0 itCount <- 0 optimalAR <- 0.44 gamma1 <- 0 storeParticleLP <- -Inf storeLLVar <- 0 nVarReps <- 7 mBurnIn <- 15 d <- length(targetAsScalar) if(optimizeM) m <- 3000 my_setAndCalculate <- setAndCalculateOne(model, target) my_decideAndJump <- decideAndJump(model, mvSaved, target, calcNodes) if(!is.null(existingPF)) { my_particleFilter <- existingPF } else { if(latentSamp == TRUE) { filterControl$saveAll <- TRUE filterControl$smoothing <- TRUE } else { filterControl$saveAll <- FALSE filterControl$smoothing <- FALSE } filterControl$initModel <- FALSE if(is.character(filterType) && filterType == 'auxiliary') { my_particleFilter <- buildAuxiliaryFilter(model, latents, control = filterControl) } else if(is.character(filterType) && filterType == 'bootstrap') { my_particleFilter <- buildBootstrapFilter(model, latents, control = filterControl) } else if(is.nfGenerator(filterType)){ my_particleFilter <- filterType(model, latents, control = filterControl) } else stop('filter type must be either "bootstrap", "auxiliary", or a user defined filtering algorithm created by a call to nimbleFunction(...).') } particleMV <- my_particleFilter$mvEWSamples if(any(target%in%model$expandNodeNames(latents))) stop('PMCMC \'target\' argument cannot include latent states') if(length(targetAsScalar) > 1) stop('more than one top-level target; cannot use RW_PF sampler, try RW_PF_block sampler') }, run = function() { storeParticleLP <<- my_particleFilter$getLastLogLik() modelLP0 <- storeParticleLP + getLogProb(model, target) propValue <- rnorm(1, mean = model[[target]], sd = scale) my_setAndCalculate$run(propValue) particleLP <- my_particleFilter$run(m) modelLP1 <- particleLP + getLogProb(model, target) jump <- my_decideAndJump$run(modelLP1, modelLP0, 0, 0) if(!jump) { my_particleFilter$setLastLogLik(storeParticleLP) } if(jump & latentSamp){ index <- ceiling(runif(1, 0, m)) copy(particleMV, model, latents, latents, index) calculate(model, latentDep) copy(from = model, to = mvSaved, nodes = latentDep, row = 1, logProb = TRUE) } else if(!jump & latentSamp){ copy(from = mvSaved, to = model, nodes = latentDep, row = 1, logProb = TRUE) } if(jump & optimizeM) optimM() if(adaptive) adaptiveProcedure(jump) }, methods = list( optimM = function() { tempM <- 15000 declare(LLEst, double(1, nVarReps)) if(nVarEsts < mBurnIn) { for(i in 1:nVarReps) LLEst[i] <- my_particleFilter$run(tempM) if(nVarEsts == 1) storeLLVar <<- var(LLEst)/mBurnIn else { LLVar <- storeLLVar LLVar <- LLVar + var(LLEst)/mBurnIn storeLLVar<<- LLVar } nVarEsts <<- nVarEsts + 1 } else { m <<- m*storeLLVar/(0.92^2) m <<- ceiling(m) storeParticleLP <<- my_particleFilter$run(m) optimizeM <<- 0 } }, adaptiveProcedure = function(jump = logical()) { timesRan <<- timesRan + 1 if(jump) timesAccepted <<- timesAccepted + 1 if(timesRan %% adaptInterval == 0) { acceptanceRate <- timesAccepted / timesRan timesAdapted <<- timesAdapted + 1 gamma1 <<- 1/((timesAdapted + 3)^0.8) gamma2 <- 10 * gamma1 adaptFactor <- exp(gamma2 * (acceptanceRate - optimalAR)) scale <<- scale * adaptFactor timesRan <<- 0 timesAccepted <<- 0 } }, reset = function() { scale <<- scaleOriginal timesRan <<- 0 timesAccepted <<- 0 timesAdapted <<- 0 storeParticleLP <<- -Inf gamma1 <<- 0 } ) ) sampler_RW_PF_block <- nimbleFunction( name = 'sampler_RW_PF_block', contains = sampler_BASE, setup = function(model, mvSaved, target, control) { adaptive <- extractControlElement(control, 'adaptive', TRUE) adaptScaleOnly <- extractControlElement(control, 'adaptScaleOnly', FALSE) adaptInterval <- extractControlElement(control, 'adaptInterval', 200) adaptFactorExponent <- extractControlElement(control, 'adaptFactorExponent', 0.8) scale <- extractControlElement(control, 'scale', 1) propCov <- extractControlElement(control, 'propCov', 'identity') existingPF <- extractControlElement(control, 'pf', NULL) m <- extractControlElement(control, 'pfNparticles', 1000) filterType <- extractControlElement(control, 'pfType', 'bootstrap') filterControl <- extractControlElement(control, 'pfControl', list()) optimizeM <- extractControlElement(control, 'pfOptimizeNparticles', FALSE) latents <- extractControlElement(control, 'latents', error = 'RW_PF sampler missing required control argument: latents') if('pfLookahead' %in% names(control)) { warning("The `pfLookahead` control list argument is deprecated and will not be supported in future versions of `nimbleSMC`. Please specify the lookahead function via the pfControl argument instead.") filterControl$lookahead <- control[['pfLookahead']] } else if(!('lookahead' %in% names(filterControl))) { filterControl$lookahead <- 'simulate' } targetAsScalar <- model$expandNodeNames(target, returnScalarComponents = TRUE) calcNodes <- model$getDependencies(target) latentSamp <- FALSE MCMCmonitors <- tryCatch(parent.frame(2)$conf$monitors, error = function(e) e) if(identical(MCMCmonitors, TRUE)) latentSamp <- TRUE else if(any(model$expandNodeNames(latents) %in% model$expandNodeNames(MCMCmonitors))) latentSamp <- TRUE latentDep <- model$getDependencies(latents) topParams <- model$getNodeNames(stochOnly=TRUE, includeData=FALSE, topOnly=TRUE) target <- model$expandNodeNames(target) optimizeM <- as.integer(optimizeM) scaleOriginal <- scale timesRan <- 0 timesAccepted <- 0 timesAdapted <- 0 prevLL <- 0 nVarEsts <- 0 itCount <- 0 d <- length(targetAsScalar) if(is.character(propCov) && propCov == 'identity') propCov <- diag(d) propCovOriginal <- propCov chol_propCov <- chol(propCov) chol_propCov_scale <- scale * chol_propCov empirSamp <- matrix(0, nrow=adaptInterval, ncol=d) storeParticleLP <- -Inf storeLLVar <- 0 nVarReps <- 7 mBurnIn <- 15 if(optimizeM) m <- 3000 my_setAndCalculate <- setAndCalculate(model, target) my_decideAndJump <- decideAndJump(model, mvSaved, target, calcNodes) my_calcAdaptationFactor <- calcAdaptationFactor(d, adaptFactorExponent) if(!is.null(existingPF)) { my_particleFilter <- existingPF } else { if(latentSamp == TRUE) { filterControl$saveAll <- TRUE filterControl$smoothing <- TRUE } else { filterControl$saveAll <- FALSE filterControl$smoothing <- FALSE } filterControl$initModel <- FALSE if(is.character(filterType) && filterType == 'auxiliary') { my_particleFilter <- buildAuxiliaryFilter(model, latents, control = filterControl) } else if(is.character(filterType) && filterType == 'bootstrap') { my_particleFilter <- buildBootstrapFilter(model, latents, control = filterControl) } else if(is.nfGenerator(filterType)){ my_particleFilter <- filterType(model, latents, control = filterControl) } else stop('filter type must be either "bootstrap", "auxiliary", or a user defined filtering algorithm created by a call to nimbleFunction(...).') } particleMV <- my_particleFilter$mvEWSamples if(!inherits(propCov, 'matrix')) stop('propCov must be a matrix\n') if(!inherits(propCov[1,1], 'numeric')) stop('propCov matrix must be numeric\n') if(!all(dim(propCov) == d)) stop('propCov matrix must have dimension ', d, 'x', d, '\n') if(!isSymmetric(propCov)) stop('propCov matrix must be symmetric') if(length(targetAsScalar) < 2) stop('less than two top-level targets; cannot use RW_PF_block sampler, try RW_PF sampler') if(any(target%in%model$expandNodeNames(latents))) stop('PMCMC \'target\' argument cannot include latent states') }, run = function() { storeParticleLP <<- my_particleFilter$getLastLogLik() modelLP0 <- storeParticleLP + getLogProb(model, target) propValueVector <- generateProposalVector() my_setAndCalculate$run(propValueVector) particleLP <- my_particleFilter$run(m) modelLP1 <- particleLP + getLogProb(model, target) jump <- my_decideAndJump$run(modelLP1, modelLP0, 0, 0) if(!jump) { my_particleFilter$setLastLogLik(storeParticleLP) } if(jump & latentSamp) { index <- ceiling(runif(1, 0, m)) copy(particleMV, model, latents, latents, index) calculate(model, latentDep) copy(from = model, to = mvSaved, nodes = latentDep, row = 1, logProb = TRUE) } else if(!jump & latentSamp) { copy(from = mvSaved, to = model, nodes = latentDep, row = 1, logProb = TRUE) } if(jump & optimizeM) optimM() if(adaptive) adaptiveProcedure(jump) }, methods = list( optimM = function() { tempM <- 15000 declare(LLEst, double(1, nVarReps)) if(nVarEsts < mBurnIn) { for(i in 1:nVarReps) LLEst[i] <- my_particleFilter$run(tempM) if(nVarEsts == 1) storeLLVar <<- var(LLEst)/mBurnIn else { LLVar <- storeLLVar LLVar <- LLVar + var(LLEst)/mBurnIn storeLLVar <<- LLVar } nVarEsts <<- nVarEsts + 1 } else { m <<- m*storeLLVar/(0.92^2) m <<- ceiling(m) storeParticleLP <<- my_particleFilter$run(m) optimizeM <<- 0 } }, generateProposalVector = function() { propValueVector <- rmnorm_chol(1, values(model,target), chol_propCov_scale, 0) returnType(double(1)) return(propValueVector) }, adaptiveProcedure = function(jump = logical()) { timesRan <<- timesRan + 1 if(jump) timesAccepted <<- timesAccepted + 1 if(!adaptScaleOnly) empirSamp[timesRan, 1:d] <<- values(model, target) if(timesRan %% adaptInterval == 0) { acceptanceRate <- timesAccepted / timesRan timesAdapted <<- timesAdapted + 1 adaptFactor <- my_calcAdaptationFactor$run(acceptanceRate) scale <<- scale * adaptFactor if(!adaptScaleOnly) { gamma1 <- my_calcAdaptationFactor$getGamma1() for(i in 1:d) empirSamp[, i] <<- empirSamp[, i] - mean(empirSamp[, i]) empirCov <- (t(empirSamp) %*% empirSamp) / (timesRan-1) propCov <<- propCov + gamma1 * (empirCov - propCov) chol_propCov <<- chol(propCov) } chol_propCov_scale <<- chol_propCov * scale timesRan <<- 0 timesAccepted <<- 0 } }, reset = function() { scale <<- scaleOriginal propCov <<- propCovOriginal chol_propCov <<- chol(propCov) chol_propCov_scale <<- chol_propCov * scale storeParticleLP <<- -Inf timesRan <<- 0 timesAccepted <<- 0 timesAdapted <<- 0 my_calcAdaptationFactor$reset() } ) )
is.ggedit <- function(x) inherits(x, 'ggedit') as.ggedit <- function(plot) { UseMethod('as.ggedit') } as.ggedit.ggedit <- function(plot) { plot } as.ggedit.list <- function(plot) { structure(plot, class = c("ggedit", "gglist")) } as.ggedit.ggplot <- function(plot) { plot <- list(plot) structure(plot, class = c("ggedit", "gglist","gg","ggplot")) }
impute.wrapper.KNN = function(dataSet.mvs,K){ resultKNN = impute.knn(dataSet.mvs ,k = K, rowmax = 0.99, colmax = 0.99, maxp = 1500, rng.seed = sample(1:1000,1)) dataSet.imputed = resultKNN[[1]] return(dataSet.imputed) }
navbarPage("Multiple [R] Terminals Demo", tabPanel("Terminal 1", editorUI("termone") ), tabPanel("Terminal 2", editorUI("termtwo") ), tabPanel("Terminal 3", editorUI("termthree") ) )
`initPCA` <- function(Y, scale = FALSE) { Y <- as.matrix(Y) Y <- scale(Y, scale = scale) if (scale && any(is.nan(Y))) Y[is.nan(Y)] <- 0 Y <- Y / sqrt(nrow(Y) - 1) attr(Y, "METHOD") <- "PCA" Y } `initCAP` <- function(Y) { Y <- as.matrix(Y) Y <- scale(Y, scale = FALSE) attr(Y, "METHOD") <- "CAPSCALE" Y } `initCA` <- function(Y) { Y <- as.matrix(Y) tot <- sum(Y) Y <- Y/tot rw <- rowSums(Y) cw <- colSums(Y) rc <- outer(rw, cw) Y <- (Y - rc)/sqrt(rc) attr(Y, "tot") <- tot attr(Y, "RW") <- rw attr(Y, "CW") <- cw attr(Y, "METHOD") <- "CA" Y } `initDBRDA` <- function(Y) { Y <- as.matrix(Y) dims <- dim(Y) if (dims[1] != dims[2] || !isSymmetric(unname(Y))) stop("input Y must be distances or a symmetric square matrix") Y <- -0.5 * GowerDblcen(Y^2) attr(Y, "METHOD") <- "DISTBASED" Y } `ordHead`<- function(Y) { method <- attr(Y, "METHOD") headmethod <- switch(method, "CA" = "cca", "PCA" = "rda", "CAPSCALE" = "capscale", "DISTBASED" = "dbrda") if (method == "DISTBASED") totvar <- sum(diag(Y)) else totvar <- sum(Y^2) head <- list("tot.chi" = totvar, "Ybar" = Y, "method" = headmethod) if (method == "CA") head <- c(list("grand.total" = attr(Y, "tot"), "rowsum" = attr(Y, "RW"), "colsum" = attr(Y, "CW")), head) else if (method == "PCA") head <- c(list("colsum" = sqrt(colSums(Y^2))), head) head } `ordPartial` <- function(Y, Z) { ZERO <- sqrt(.Machine$double.eps) DISTBASED <- attr(Y, "METHOD") == "DISTBASED" RW <- attr(Y, "RW") if (!is.null(RW)) { envcentre <- apply(Z, 2, weighted.mean, w = RW) Z <- scale(Z, center = envcentre, scale = FALSE) Z <- sweep(Z, 1, sqrt(RW), "*") } else { envcentre <- colMeans(Z) Z <- scale(Z, center = envcentre, scale = FALSE) } Q <- qr(Z) if (Q$rank == 0) return(list(Y = Y, result = NULL)) Yfit <- qr.fitted(Q, Y) if (DISTBASED) { Yfit <- qr.fitted(Q, t(Yfit)) totvar <- sum(diag(Yfit)) } else { totvar <- sum(Yfit^2) } if (totvar < ZERO) totvar <- 0 Y <- qr.resid(Q, Y) if (DISTBASED) Y <- qr.resid(Q, t(Y)) result <- list( rank = if (totvar > 0) Q$rank else 0, tot.chi = totvar, QR = Q, envcentre = envcentre) list(Y = Y, result = result) } `ordConstrain` <- function(Y, X, Z) { DISTBASED <- attr(Y, "METHOD") == "DISTBASED" RW <- attr(Y, "RW") CW <- attr(Y, "CW") ZERO <- sqrt(.Machine$double.eps) if (!is.null(Z)) { X <- cbind(Z, X) zcol <- ncol(Z) } else { zcol <- 0 } if (!is.null(RW)) { envcentre <- apply(X, 2, weighted.mean, w = RW) X <- scale(X, center = envcentre, scale = FALSE) X <- sweep(X, 1, sqrt(RW), "*") } else { envcentre <- colMeans(X) X <- scale(X, center = envcentre, scale = FALSE) } Q <- qr(X) rank <- sum(Q$pivot[seq_len(Q$rank)] > zcol) if (rank == 0) return(list(Y = Y, result = NULL)) if (length(Q$pivot) > Q$rank) alias <- colnames(Q$qr)[-seq_len(Q$rank)] else alias <- NULL kept <- seq_along(Q$pivot) <= Q$rank & Q$pivot > zcol if (zcol > 0) envcentre <- envcentre[-seq_len(zcol)] Yfit <- qr.fitted(Q, Y) if (DISTBASED) { Yfit <- qr.fitted(Q, t(Yfit)) sol <- eigen(Yfit, symmetric = TRUE) lambda <- sol$values u <- sol$vectors } else { sol <- svd(Yfit) lambda <- sol$d^2 u <- sol$u v <- sol$v } zeroev <- abs(lambda) < max(ZERO, ZERO * lambda[1L]) if (any(zeroev)) { lambda <- lambda[!zeroev] u <- u[, !zeroev, drop = FALSE] if (!DISTBASED) v <- v[, !zeroev, drop = FALSE] } posev <- lambda > 0 if (DISTBASED) { wa <- Y %*% u[, posev, drop = FALSE] %*% diag(1/lambda[posev], sum(posev)) v <- matrix(NA, 0, sum(posev)) } else { wa <- Y %*% v %*% diag(1/sqrt(lambda), sum(posev)) } xx <- X[, Q$pivot[kept], drop = FALSE] bp <- (1/sqrt(colSums(xx^2))) * crossprod(xx, u[, posev, drop=FALSE]) if (!is.null(RW)) { u <- sweep(u, 1, sqrt(RW), "/") if (all(!is.na(wa))) wa <- sweep(wa, 1, sqrt(RW), "/") } if (!is.null(CW) && nrow(v)) { v <- sweep(v, 1, sqrt(CW), "/") } axnam <- paste0(switch(attr(Y, "METHOD"), "PCA" = "RDA", "CA" = "CCA", "CAPSCALE" = "CAP", "DISTBASED" = "dbRDA"), seq_len(sum(posev))) if (DISTBASED && any(!posev)) negnam <- paste0("idbRDA", seq_len(sum(!posev))) else negnam <- NULL dnam <- dimnames(Y) if (any(posev)) names(lambda) <- c(axnam, negnam) if (ncol(u)) dimnames(u) <- list(dnam[[1]], c(axnam, negnam)) if (nrow(v) && ncol(v)) dimnames(v) <- list(dnam[[2]], axnam) if (ncol(wa)) colnames(wa) <- axnam if (ncol(bp)) colnames(bp) <- axnam result <- list( eig = lambda, poseig = if (DISTBASED) sum(posev) else NULL, u = u, v = v, wa = wa, alias = alias, biplot = bp, rank = length(lambda), qrank = rank, tot.chi = sum(lambda), QR = Q, envcentre = envcentre) Y <- qr.resid(Q, Y) if (DISTBASED) Y <- qr.resid(Q, t(Y)) list(Y = Y, result = result) } `ordResid` <- function(Y) { DISTBASED <- attr(Y, "METHOD") == "DISTBASED" RW <- attr(Y, "RW") CW <- attr(Y, "CW") ZERO <- sqrt(.Machine$double.eps) if (DISTBASED) { sol <- eigen(Y, symmetric = TRUE) lambda <- sol$values u <- sol$vectors } else { sol <- svd(Y) lambda <- sol$d^2 u <- sol$u v <- sol$v } zeroev <- abs(lambda) < max(ZERO, ZERO * lambda[1L]) if (any(zeroev)) { lambda <- lambda[!zeroev] u <- u[, !zeroev, drop = FALSE] if (!DISTBASED) v <- v[, !zeroev, drop = FALSE] } posev <- lambda > 0 if (DISTBASED) v <- matrix(NA, 0, sum(posev)) if (!is.null(RW)) { u <- sweep(u, 1, sqrt(RW), "/") } if (!is.null(CW) && nrow(v)) { v <- sweep(v, 1, sqrt(CW), "/") } axnam <- paste0(switch(attr(Y, "METHOD"), "PCA" = "PC", "CA" = "CA", "CAPSCALE" = "MDS", "DISTBASED" = "MDS"), seq_len(sum(posev))) if (DISTBASED && any(!posev)) negnam <- paste0("iMDS", seq_len(sum(!posev))) else negnam <- NULL dnam <- dimnames(Y) if (any(posev)) names(lambda) <- c(axnam, negnam) if (ncol(u)) dimnames(u) <- list(dnam[[1]], c(axnam, negnam)) if (nrow(v) && ncol(v)) dimnames(v) <- list(dnam[[2]], axnam) out <- list( "eig" = lambda, "poseig" = if (DISTBASED) sum(posev) else NULL, "u" = u, "v" = v, "rank" = length(lambda), "tot.chi" = sum(lambda)) out } `ordConstrained` <- function(Y, X = NULL, Z = NULL, method = c("cca", "rda", "capscale", "dbrda", "pass"), arg = FALSE) { method = match.arg(method) partial <- constraint <- resid <- NULL Y <- switch(method, "cca" = initCA(Y), "rda" = initPCA(Y, scale = arg), "capscale" = initCAP(Y), "dbrda" = initDBRDA(Y), "pass" = Y) if (!is.numeric(Y)) stop("dependent data (community) must be numeric") if (!is.null(X)) { if (!is.numeric(X)) stop("constraints must be numeric or factors") if (nrow(Y) != nrow(X)) stop("dependent data and constraints must have the same number of rows") } if (!is.null(Z)) { if (!is.numeric(Z)) stop("conditions must be numeric or factors") if (nrow(Y) != nrow(Z)) stop("dependent data and conditions must have the same number of rows") } head <- ordHead(Y) if (!is.null(Z) && ncol(Z)) { out <- ordPartial(Y, Z) Y <- out$Y partial <- out$result } if (!is.null(X) && ncol(X)) { out <- ordConstrain(Y, X, Z) Y <- out$Y constraint <- out$result } resid <- ordResid(Y) out <- c(head, call = match.call(), list("pCCA" = partial, "CCA" = constraint, "CA" = resid)) class(out) <- switch(attr(Y, "METHOD"), "CA" = "cca", "PCA" = c("rda", "cca"), "CAPSCALE" = c("capscale", "rda", "cca"), "DISTBASED" = c("dbrda", "rda", "cca")) out }
pcf.boundary<-function(dendat,N=rep(10,dim(dendat)[2]-1), rho=0,m=dim(dendat)[1],seed=1) { n<-dim(dendat)[1] d<-dim(dendat)[2] set.seed(seed) mc<-max(1,round(m/n)) M<-n*mc data<-matrix(0,M,d-1) distat<-matrix(0,M,1) dendat.mc<-matrix(0,M,d) for (i in 1:n){ obs<-dendat[i,] for (j in 1:mc){ diro<-2*pi*runif(1) riro<-rho*runif(1) newobs<-obs+riro*sphere.map(diro) len<-sqrt(sum(newobs^2)) ii<-mc*(i-1)+j data[ii,]<-sphere.para(newobs/len) distat[ii]<-len dendat.mc[ii,]<-newobs } } support<-matrix(0,2*(d-1),1) for (i in 1:(d-1)){ support[2*i-1]<-min(data[,i]) support[2*i]<-max(data[,i]) } step<-matrix(0,d-1,1) for (i in 1:(d-1)) step[i]<-(support[2*i]-support[2*i-1])/N[i] recnum<-prod(N) rowpointer<-matrix(0,recnum,1) value<-matrix(0,recnum,1) index<-matrix(0,recnum,d-1) inde<-matrix(0,d-1,1) numpositive<-0 for (i in 1:M){ point<-data[i,] for (k in 1:(d-1)) inde[k]<-min(floor((point[k]-support[2*k-1])/step[k]),N[k]-1) recnum<-0 for (kk in 1:(d-1)){ if (kk==1) tulo<-1 else tulo<-prod(N[1:(kk-1)]) recnum<-recnum+inde[kk]*tulo } recnum<-recnum+1 row<-rowpointer[recnum] if (row>0) value[row]<-max(value[row],distat[i]) else{ numpositive<-numpositive+1 rowpointer[recnum]<-numpositive value[numpositive]<-distat[i] index[numpositive,]<-inde } } value<-value[1:numpositive] index<-index[1:numpositive,] if (d==2) index<-matrix(index,length(index),1) down<-index high<-index+1 pcf<-list( value=value,index=NULL, down=down,high=high, support=support,N=N,data=data,dendat.mc=dendat.mc) return(pcf) }
expected <- eval(parse(text="FALSE")); test(id=0, code={ argv <- eval(parse(text="list(list(structure(c(0, 1, 1, 2, 2, 4, NA), .Names = c(\"ddiMatrix\", \"diagonalMatrix\", \"dMatrix\", \"sparseMatrix\", \"Matrix\", \"mMatrix\", \"ANY\")), structure(c(0, 1, 1, 1, 2, 2, 2, 3, 4, NA), .Names = c(\"dgCMatrix\", \"CsparseMatrix\", \"dsparseMatrix\", \"generalMatrix\", \"dMatrix\", \"sparseMatrix\", \"compMatrix\", \"Matrix\", \"mMatrix\", \"ANY\"))), TRUE)")); .Internal(islistfactor(argv[[1]], argv[[2]])); }, o=expected);
library(knitr) opts_chunk$set(fig.align = "center", fig.width = 6, fig.height = 5, dev.args = list(pointsize=10), par = TRUE, message = FALSE, warning = FALSE) knit_hooks$set(par = function(before, options, envir) { if(before && options$fig.show != "none") par(mar=c(4.1,4.1,1.1,1.1), mgp=c(3,1,0), tcl=-0.5) }) library(qcc) data(pistonrings) diameter = with(pistonrings, qcc.groups(diameter, sample)) head(diameter) q1 = qcc(diameter[1:25,], type="xbar", newdata=diameter[26:40,]) plot(q1, chart.all=FALSE) plot(q1, add.stats=FALSE) q1 = qcc(diameter[1:25,], type="xbar", newdata=diameter[26:40,], confidence.level=0.99) q1 = qcc(diameter[1:25,], type="xbar", newdata=diameter[26:40,], plot=FALSE) (warn.limits = limits.xbar(q1$center, q1$std.dev, q1$sizes, 2)) plot(q1, restore.par = FALSE) abline(h = warn.limits, lty = 3, col = "chocolate") q2 = qcc(diameter[1:25,], type="R") summary(q2) q3 = qcc(diameter[1:25,], type="R", newdata=diameter[26:40,]) summary(q3) q4 = qcc(diameter[1:25,], type="S") summary(q4) q5 = qcc(diameter[1:25,], type="S", newdata=diameter[26:40,]) summary(q5) out = c(9, 10, 30, 35, 45, 64, 65, 74, 75, 85, 99, 100) diameter2 = with(pistonrings, qcc.groups(diameter[-out], sample[-out])) summary(qcc(diameter2[1:25,], type="xbar")) summary(qcc(diameter2[1:25,], type="R")) data(orangejuice) q1 = with(orangejuice, qcc(D[trial], sizes=size[trial], type="p")) summary(q1) q2 = with(orangejuice, qcc(D[trial], sizes=size[trial], type="np")) summary(q2) inc = setdiff(which(orangejuice$trial), c(15,23)) q2 = with(orangejuice, qcc(D[inc], sizes=size[inc], type="p", newdata=D[!trial], newsizes=size[!trial])) data(orangejuice2) q1 = with(orangejuice2, qcc(D[trial], sizes=size[trial], type="p", newdata=D[!trial], newsizes=size[!trial])) summary(q1) data(circuit) q1 = with(circuit, qcc(x[trial], sizes=size[trial], type="c")) summary(q1) inc = setdiff(which(circuit$trial), c(6,20)) q2 = with(circuit, qcc(x[inc], sizes=size[inc], type="c", labels=inc, newdata=x[!trial], newsizes=size[!trial], newlabels=which(!trial))) summary(q2) q3 = with(circuit, qcc(x[inc], sizes=size[inc], type="u", labels=inc, newdata=x[!trial], newsizes=size[!trial], newlabels=which(!trial))) summary(q3) data(pcmanufact) q1 = with(pcmanufact, qcc(x, sizes=size, type="u")) summary(q1) x = c(33.75, 33.05, 34, 33.81, 33.46, 34.02, 33.68, 33.27, 33.49, 33.20, 33.62, 33.00, 33.54, 33.12, 33.84) q1 = qcc(x, type="xbar.one") summary(q1) q2 = qcc(x, type="xbar.one", std.dev = "SD") summary(q2) stats.p.std = function(data, sizes) { data = as.vector(data) sizes = as.vector(sizes) pbar = sum(data)/sum(sizes) z = (data/sizes - pbar)/sqrt(pbar*(1-pbar)/sizes) list(statistics = z, center = 0) } sd.p.std = function(data, sizes, ...) { return(1) } limits.p.std = function(center, std.dev, sizes, conf) { if(conf >= 1) { lcl = -conf ucl = +conf } else { if(conf > 0 & conf < 1) { nsigmas = qnorm(1 - (1 - conf)/2) lcl = -nsigmas ucl = +nsigmas } else stop("invalid 'conf' argument.") } limits = matrix(c(lcl, ucl), ncol = 2) rownames(limits) = rep("", length = nrow(limits)) colnames(limits) = c("LCL", "UCL") return(limits) } n = c(rep(50,5), rep(100,5), rep(25, 5)) x = rbinom(length(n), n, 0.2) summary(qcc(x, type="p", size=n)) summary(qcc(x, type="p.std", size=n)) data(pistonrings) diameter = with(pistonrings, qcc.groups(diameter, sample)) q = qcc(diameter, type="xbar", nsigmas=3, plot=FALSE) beta = oc.curves.xbar(q) print(round(beta, digits=4)) data(orangejuice) q = with(orangejuice, qcc(D[trial], sizes=size[trial], type="p", plot=FALSE)) beta = oc.curves(q) print(round(beta, digits=4)) data(circuit) q = with(circuit, qcc(x[trial], sizes=size[trial], type="c", plot=FALSE)) beta = oc.curves(q) print(round(beta, digits=4)) data(pistonrings) diameter = with(pistonrings, qcc.groups(diameter, sample)) q1 = cusum(diameter[1:25,], decision.interval = 4, se.shift = 1) summary(q1) q2 = cusum(diameter[1:25,], newdata=diameter[26:40,]) summary(q2) plot(q2, chart.all=FALSE) data(pistonrings) diameter = with(pistonrings, qcc.groups(diameter, sample)) q1 = ewma(diameter[1:25,], lambda=0.2, nsigmas=3) summary(q1) q2 = ewma(diameter[1:25,], lambda=0.2, nsigmas=2.7, newdata=diameter[26:40,]) summary(q2) x = c(33.75, 33.05, 34, 33.81, 33.46, 34.02, 33.68, 33.27, 33.49, 33.20, 33.62, 33.00, 33.54, 33.12, 33.84) q3 = ewma(x, lambda=0.2, nsigmas=2.7) summary(q3) data(pistonrings) diameter = with(pistonrings, qcc.groups(diameter, sample)) q1 = qcc(diameter[1:25,], type="xbar", nsigmas=3, plot=FALSE) process.capability(q1, spec.limits=c(73.95,74.05)) process.capability(q1, spec.limits=c(73.95,74.05), target=74.02) process.capability(q1, spec.limits=c(73.99,74.01)) process.capability(q1, spec.limits = c(73.99, 74.1)) X1 = matrix(c(72, 56, 55, 44, 97, 83, 47, 88, 57, 26, 46, 49, 71, 71, 67, 55, 49, 72, 61, 35, 84, 87, 73, 80, 26, 89, 66, 50, 47, 39, 27, 62, 63, 58, 69, 63, 51, 80, 74, 38, 79, 33, 22, 54, 48, 91, 53, 84, 41, 52, 63, 78, 82, 69, 70, 72, 55, 61, 62, 41, 49, 42, 60, 74, 58, 62, 58, 69, 46, 48, 34, 87, 55, 70, 94, 49, 76, 59, 57, 46), ncol = 4) X2 = matrix(c(23, 14, 13, 9, 36, 30, 12, 31, 14, 7, 10, 11, 22, 21, 18, 15, 13, 22, 19, 10, 30, 31, 22, 28, 10, 35, 18, 11, 10, 11, 8, 20, 16, 19, 19, 16, 14, 28, 20, 11, 28, 8, 6, 15, 14, 36, 14, 30, 8, 35, 19, 27, 31, 17, 18, 20, 16, 18, 16, 13, 10, 9, 16, 25, 15, 18, 16, 19, 10, 30, 9, 31, 15, 20, 35, 12, 26, 17, 14, 16), ncol = 4) X = list(X1 = X1, X2 = X2) q = mqcc(X, type = "T2") summary(q) ellipseChart(q) ellipseChart(q, show.id = TRUE) q = mqcc(X, type = "T2", pred.limits = TRUE) q1 = qcc(X1, type = "xbar", confidence.level = q$confidence.level^(1/2)) summary(q1) q2 = qcc(X2, type = "xbar", confidence.level = q$confidence.level^(1/2)) summary(q2) Xnew = list(X1 = matrix(NA, 10, 4), X2 = matrix(NA, 10, 4)) for(i in 1:4) { x = MASS::mvrnorm(10, mu = q$center, Sigma = q$cov) Xnew$X1[,i] = x[,1] Xnew$X2[,i] = x[,2] } qq = mqcc(X, type = "T2", newdata = Xnew, pred.limits = TRUE) summary(qq) ellipseChart(qq, show.id = TRUE) Xnew = list(X1 = matrix(NA, 10, 4), X2 = matrix(NA, 10, 4)) for(i in 1:4) { x = MASS::mvrnorm(10, mu = 1.2*q$center, Sigma = q$cov) Xnew$X1[,i] = x[,1] Xnew$X2[,i] = x[,2] } qq = mqcc(X, type = "T2", newdata = Xnew, pred.limits = TRUE) summary(qq) ellipseChart(qq, show.id = TRUE) data(boiler) q1 = mqcc(boiler, type = "T2.single", confidence.level = 0.999) summary(q1) boilerNew = MASS::mvrnorm(10, mu = q1$center, Sigma = q1$cov) q2 = mqcc(boiler, type = "T2.single", confidence.level = 0.999, newdata = boilerNew, pred.limits = TRUE) summary(q2) boilerNew = MASS::mvrnorm(10, mu = 1.01*q1$center, Sigma = q1$cov) q3 = mqcc(boiler, type = "T2.single", confidence.level = 0.999, newdata = boilerNew, pred.limits = TRUE) summary(q3) rob = MASS::cov.rob(boiler) q4 = mqcc(boiler, type = "T2.single", center = rob$center, cov = rob$cov) summary(q4) defect = c(80, 27, 66, 94, 33) names(defect) = c("price code", "schedule date", "supplier code", "contact num.", "part num.") pareto.chart(defect, ylab = "Error frequency") cause.and.effect(cause = list(Measurements = c("Micrometers", "Microscopes", "Inspectors"), Materials = c("Alloys", "Lubricants", "Suppliers"), Personnel = c("Shifts", "Supervisors", "Training", "Operators"), Environment = c("Condensation", "Moisture"), Methods = c("Brake", "Engager", "Angle"), Machines = c("Speed", "Lathes", "Bits", "Sockets")), effect = "Surface Flaws") set.seed(123) mu = 100 sigma_W = 10 epsilon = rnorm(500) x = matrix(mu + sigma_W*epsilon, ncol=10, byrow=TRUE) q = qcc(x, type="xbar") q = qcc(x, type="R") q = qcc(x, type="S") mu = 100 sigma_W = 10 sigma_B = 5 epsilon = rnorm(500) u = as.vector(sapply(rnorm(50), rep, 10)) x = mu + sigma_B*u + sigma_W*epsilon x = matrix(x, ncol=10, byrow=TRUE) q = qcc(x, type="xbar") q = qcc(x, type="R") q = qcc(x, type="S") mu = 100 rho = 0.8 sigma_W = 10 sigma_B = 5 epsilon = rnorm(500) u = rnorm(500) W = rep(0,100) for(i in 2:length(W)) W[i] = rho*W[i-1] + sigma_B*u[i] x = mu + sigma_B*u + sigma_W*epsilon x = matrix(x, ncol=10, byrow=TRUE) q = qcc(x, type="xbar") q = qcc(x, type="R") q = qcc(x, type="S") mu = 100 sigma_W = 10 epsilon = rnorm(120, sd=0.3) W = c(-4, 0, 1, 2, 4, 2, 0, -2) W = rep(rep(W, rep(5,8)), 3) x = mu + W + sigma_W*epsilon x = matrix(x, ncol=5, byrow=TRUE) q = qcc(x, type="xbar") q = qcc(x, type="R") q = qcc(x, type="S") mu = 100 sigma_W = 10 epsilon = rnorm(500) W = rep(0.2*1:100, rep(5,100)) x = mu + W + sigma_W*epsilon x = matrix(x, ncol=10, byrow=TRUE) q = qcc(x, type="xbar") q = qcc(x, type="R") q = qcc(x, type="S") mu1 = 90 mu2 = 110 sigma_W = 10 epsilon = rnorm(500) p = rbinom(50, 1, 0.5) mu = mu1*p + mu2*(1-p) x = rep(mu, rep(10, length(mu))) + sigma_W*epsilon x = matrix(x, ncol=10, byrow=TRUE) q = qcc(x, type="xbar") q = qcc(x, type="R") q = qcc(x, type="S") mu = rep(c(95,110,100,90), c(20,35,25,20)) sigma_W = 10 epsilon = rnorm(500) x = rep(mu, rep(5, length(mu))) + sigma_W*epsilon x = matrix(x, ncol=10, byrow=TRUE) q = qcc(x, type="xbar") q = qcc(x, type="R") q = qcc(x, type="S")
StatSf <- ggproto("StatSf", Stat, compute_layer = function(self, data, params, layout) { params$coord <- layout$coord ggproto_parent(Stat, self)$compute_layer(data, params, layout) }, compute_group = function(data, scales, coord) { geometry_data <- data[[ geom_column(data) ]] geometry_crs <- sf::st_crs(geometry_data) bbox <- sf::st_bbox(geometry_data) if (inherits(coord, "CoordSf")) { coord$record_bbox( xmin = bbox[["xmin"]], xmax = bbox[["xmax"]], ymin = bbox[["ymin"]], ymax = bbox[["ymax"]] ) bbox_trans <- sf_transform_xy( list( x = c(rep(0.5*(bbox[["xmin"]] + bbox[["xmax"]]), 2), bbox[["xmin"]], bbox[["xmax"]]), y = c(bbox[["ymin"]], bbox[["ymax"]], rep(0.5*(bbox[["ymin"]] + bbox[["ymax"]]), 2)) ), coord$get_default_crs(), geometry_crs ) data$xmin <- min(bbox_trans$x) data$xmax <- max(bbox_trans$x) data$ymin <- min(bbox_trans$y) data$ymax <- max(bbox_trans$y) } else { data$xmin <- bbox[["xmin"]] data$xmax <- bbox[["xmax"]] data$ymin <- bbox[["ymin"]] data$ymax <- bbox[["ymax"]] } data }, required_aes = c("geometry") ) stat_sf <- function(mapping = NULL, data = NULL, geom = "rect", position = "identity", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ...) { layer_sf( stat = StatSf, data = data, mapping = mapping, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list( na.rm = na.rm, ... ) ) }
gbmokgbmidwpred <- function (longlat, trainx, trainy, longlatpredx, predx, var.monotone = rep(0, ncol(trainx)), family = "gaussian", n.trees = 3000, learning.rate = 0.001, interaction.depth = 2, bag.fraction = 0.5, train.fraction = 1.0, n.minobsinnode = 10, cv.fold = 0, weights = rep(1, nrow(trainx)), keep.data = FALSE, verbose = TRUE, idp = 2, nmaxidw = 12, nmaxok = 12, vgm.args = ("Sph"), block = 0, n.cores = 6, ...) { names(longlat) <- c("LON", "LAT") names(longlatpredx) <- c("LON", "LAT") gbm1 <- gbm::gbm(trainy ~ ., data=trainx, var.monotone = var.monotone, distribution = as.character(family), n.trees = n.trees, shrinkage = learning.rate, interaction.depth = interaction.depth, bag.fraction = bag.fraction, train.fraction = train.fraction, n.minobsinnode = n.minobsinnode, weights = weights, cv.folds = cv.fold, n.cores = n.cores) best.iter <- gbm::gbm.perf(gbm1, method = "cv") print(best.iter) pred.gbm1 <- gbm::predict.gbm(gbm1, predx, n.trees = best.iter, type = "response") data.dev <- longlat data.pred <- longlatpredx data.dev$var1 <- trainy - gbm::predict.gbm(gbm1, trainx, n.trees = best.iter, type = "response") gstat1 <- gstat::gstat(id = "var1", formula = var1 ~ 1, locations = ~ LON + LAT, data = data.dev, set = list(idp = idp), nmax = nmaxidw) idw.pred <- stats::predict(gstat1, data.pred)$var1.pred sp::coordinates(data.dev) = ~ LON + LAT vgm1 <- gstat::variogram(var1 ~ 1, data.dev) model.1 <- gstat::fit.variogram(vgm1, gstat::vgm(vgm.args)) if (model.1$range[2] <= 0) (cat("A zero or negative range was fitted to variogram. To allow gstat running, the range was set to be positive by using min(vgm1$dist). ", "\n")) if (model.1$range[2] <= 0) (model.1$range[2] <- min(vgm1$dist)) sp::coordinates(data.pred) = ~ LON + LAT ok.pred <- gstat::krige(var1 ~ 1, data.dev, data.pred, model = model.1, nmax = nmaxok, block = block) gbmokgbmidw.pred1 <- pred.gbm1 + (idw.pred + ok.pred$var1.pred) / 2 gbmokgbmidw.pred <- cbind(longlatpredx, gbmokgbmidw.pred1, ok.pred$var1.var) names(gbmokgbmidw.pred) <- c("LON", "LAT", "Predictions", "Variances") gbmokgbmidw.pred }
dbgumbel <- function(x, mu, sigma, delta) { gama = .5772156649015328606065120900824024310421593359399235988057672348848677267776646709369470632917467495146 z_delta = 1 + (delta * sigma * pi)^2 / 6 + (delta * mu + delta * sigma * gama - 1)^2 y = (z_delta^-1) * ( (1 - delta * x)^2 + 1 ) * (sigma^-1) * exp( -(x - mu) / sigma - exp( -(x - mu) / sigma ) ) return(y) } dbgumbel <- Vectorize(dbgumbel, 'x')
"SMBassWB1"
getfolderstructure = function(datadir=c(),referencefnames=c()) { filelist = isfilelist(datadir) if (filelist == FALSE) { fnamesfull = dir(datadir, recursive = TRUE, pattern = "[.](csv|bin|Rda|wav|cw|gt3)") } else { fnamesfull = datadir } fullfilenames = foldername = rep("",length(referencefnames)) if (length(fnamesfull) > 0) { fnamesshort = apply(X=as.matrix(fnamesfull),MARGIN=1,FUN=function(X) basename(X)) foldername_new = apply(X=as.matrix(fnamesfull),MARGIN=1,FUN=function(X) basename(dirname(X))) for (i in 1:length(referencefnames)) { index_match = which(fnamesshort == referencefnames[i] & referencefnames[i] %in% c("", " ",NA) == FALSE) if (length(index_match) > 0) { fullfilenames[i] = fnamesfull[index_match] foldername[i] = foldername_new[index_match] } } } invisible(list(fullfilenames=fullfilenames,foldername=foldername)) }
test_that("captures error before first test", { skip_on_covr() skip_if(is.null(attr(rlang::eval_bare, "srcref"))) local_output_override() expect_snapshot_reporter( ProgressReporter$new(update_interval = 0, min_time = Inf), test_path("reporters/error-setup.R") ) }) test_that("gracefully handles multiple contexts", { expect_snapshot_reporter( ProgressReporter$new(update_interval = 0, min_time = Inf), test_path("reporters/context.R") ) }) test_that("can control max fails with env var or option", { withr::local_envvar(TESTTHAT_MAX_FAILS = 11) expect_equal(testthat_max_fails(), 11) withr::local_options(testthat.progress.max_fails = 12) expect_equal(testthat_max_fails(), 12) }) test_that("fails after max_fail tests", { withr::local_options(testthat.progress.max_fails = 10) expect_snapshot_reporter( ProgressReporter$new(update_interval = 0, min_time = Inf), test_path(c("reporters/fail-many.R", "reporters/fail.R")) ) }) test_that("can fully suppress incremental updates", { expect_snapshot_reporter( ProgressReporter$new(update_interval = 0, min_time = Inf), test_path("reporters/successes.R") ) expect_snapshot_reporter( ProgressReporter$new(update_interval = Inf, min_time = Inf), test_path("reporters/successes.R") ) }) test_that("reports backtraces", { skip_on_covr() skip_if(is.null(attr(rlang::eval_bare, "srcref"))) expect_snapshot_reporter( ProgressReporter$new(update_interval = 0, min_time = Inf), test_path("reporters/backtraces.R") ) }) test_that("records skips", { expect_snapshot_reporter( ProgressReporter$new(update_interval = 0, min_time = Inf), test_path("reporters/skips.R") ) }) test_that("compact display is informative", { expect_snapshot_reporter( CompactProgressReporter$new(), test_path("reporters/tests.R") ) }) test_that("display of successes only is compact", { expect_snapshot_reporter( CompactProgressReporter$new(), test_path("reporters/successes.R") ) expect_snapshot_reporter( CompactProgressReporter$new(rstudio = TRUE), test_path("reporters/successes.R") ) })
readBinTemplates <- function( files=NULL, dir='.', ext='bt', parallel=FALSE ) { if(parallel) { lapplyfun <- function(X, FUN) parallel::mclapply(X, FUN, mc.cores=parallel::detectCores()) } else lapplyfun <- lapply if(is.null(files)) { filesfull <- list.files(path=dir, full.names=TRUE, pattern=paste('\\.', ext, '$', sep='')) files <- list.files(path=dir, pattern=paste('\\.', ext, '$', sep='')) names(filesfull) <- gsub("\\.[^.]*$", "", files) } else { filesfull <- paste(dir, '/', files, sep='') names(filesfull) <- if(is.null(names(files))) gsub("\\.[^.]*$", "", files) else names(files) } template.L <- lapplyfun(filesfull, function(x) readOneBinTemplate(file=x)) templates <- new('binTemplateList', templates=template.L) return(templates) }
"england_club_data"
parse_netstat <- function(netstat_output) { os <- Sys.info()['sysname'] switch(os, Windows = { ActiveConnections <- netstat_output[-c(1:3)] temp <- paste0(gsub("\\s+", ",", ActiveConnections), collapse="\n") read.table(text = temp, sep=",", stringsAsFactors = FALSE, header=TRUE, fill = TRUE) }, { ActiveConnections <- netstat_output[3: (which(netstat_output == "Active Multipath Internet connections") - 1)] temp <- paste0(gsub("\\s+", ",", ActiveConnections), collapse="\n") read.table(text = temp, sep=",", stringsAsFactors = FALSE, header=FALSE, fill = TRUE) } ) }
knitr::opts_chunk$set(echo = TRUE) library(CB2) library(dplyr) library(readr) data("Evers_CRISPRn_RT112") head(Evers_CRISPRn_RT112$count) Evers_CRISPRn_RT112$design sgrna_stats <- measure_sgrna_stats(Evers_CRISPRn_RT112$count, Evers_CRISPRn_RT112$design, "before", "after") gene_stats <- measure_gene_stats(sgrna_stats) head(gene_stats) df <- read_csv("https://raw.githubusercontent.com/hyunhwaj/CB2-Experiments/master/01_gene-level-analysis/data/Evers/CRISPRn-RT112.csv") df head(measure_sgrna_stats(df, Evers_CRISPRn_RT112$design, "before", "after", ge_id = 'gene', sg_id = 'sgRNA'))
sunterpi2 <- function(x,n) { xo<-sort(x,decreasing=TRUE) if(xo[1]*n/sum(xo)>1) stop("There are some units with inclusion probability >1") N<-length(xo) t<-rev(cumsum(rev(xo))) xbar<-t/(N:1) kk0<-n*xo/t k0<-which(kk0>=1,arr.ind = FALSE)[1] kstar<-min(k0,N-n+1) g<-numeric(kstar) g[1]<-1/t[2] for(i in 2:kstar) { g[i]<-prod(1-xo[1:(i-1)]/t[2:i])/t[i+1] } piij<-matrix(0,N,N) for(k in 1:(N-1)) { for(l in (k+1):N) { if(k<l & l<kstar) { piij[k,l]<-n*(n-1)/t[1]*g[k]*xo[k]*xo[l] } else if(k<kstar & kstar<=l) { piij[k,l]<-n*(n-1)/t[1]*g[k]*xo[k]*xbar[kstar] } else if(kstar<=k & k<l) { piij[k,l]<-n*(n-1)/t[1]*g[kstar-1]*(t[kstar]-xo[kstar-1])/(t[kstar]-xbar[kstar])*xbar[kstar]^2 } piij[l,k]<-piij[k,l] } } ord<-N+1-rank(x,ties.method="random") piij<-piij[ord,ord] diag(piij)<-apply(piij,1,sum)/(n-1) piij }
itriplot <- function(p, indID=NULL, group=NULL, chartOpts=NULL, digits=5) { if(!is.matrix(p)) p <- as.matrix(p) stopifnot(ncol(p) == 3) n <- nrow(p) if(is.null(indID)) indID <- get_indID(n, rownames(p), names(group)) stopifnot(length(indID) == n) indID <- as.character(indID) if(!is.null(colnames(p))) { chartOpts <- add2chartOpts(chartOpts, labels=colnames(p)) } if(is.null(group)) group <- rep(1, n) group_levels <- sort(unique(group)) group <- group2numeric(group) dimnames(p) <- NULL names(group) <- NULL names(indID) <- NULL x <- list(data=list(p=p, indID=indID, group=group), chartOpts=chartOpts) if(!is.null(digits)) attr(x, "TOJSON_ARGS") <- list(digits=digits) defaultAspect <- 2/sqrt(3) browsersize <- getPlotSize(defaultAspect) htmlwidgets::createWidget("itriplot", x, width=chartOpts$width, height=chartOpts$height, sizingPolicy=htmlwidgets::sizingPolicy( browser.defaultWidth=browsersize$width, browser.defaultHeight=browsersize$height, knitr.defaultWidth=1000, knitr.defaultHeight=1000/defaultAspect), package="qtlcharts") } itriplot_output <- function(outputId, width="100%", height="530") { htmlwidgets::shinyWidgetOutput(outputId, "itriplot", width, height, package="qtlcharts") } itriplot_render <- function(expr, env=parent.frame(), quoted=FALSE) { if(!quoted) { expr <- substitute(expr) } htmlwidgets::shinyRenderWidget(expr, itriplot_output, env, quoted=TRUE) }
attribute.prob.bin<- function(x, ...){ res <- attribute.default(x$y.i, obar.i=x$obar.i, prob.y=x$prob.y, obar=x$obar, class="prob.bin", obs=x$obs, pred=x$pred, thres=x$thres, bins=x$bins, ...) return(res) }
add_p <- function(x, ...) { UseMethod("add_p") } add_p.tbl_summary <- function(x, test = NULL, pvalue_fun = NULL, group = NULL, include = everything(), test.args = NULL, exclude = NULL, ...) { updated_call_list <- c(x$call_list, list(add_p = match.call())) if (!rlang::quo_is_null(rlang::enquo(exclude))) { lifecycle::deprecate_stop( "1.2.5", "gtsummary::add_p(exclude = )", "add_p(include = )", details = paste0( "The `include` argument accepts quoted and unquoted expressions similar\n", "to `dplyr::select()`. To exclude variable, use the minus sign.\n", "For example, `include = -c(age, stage)`" ) ) } test <- test %||% get_theme_element("add_p.tbl_summary-arg:test") pvalue_fun <- pvalue_fun %||% get_theme_element("add_p.tbl_summary-arg:pvalue_fun") %||% get_theme_element("pkgwide-fn:pvalue_fun") %||% getOption("gtsummary.pvalue_fun", default = style_pvalue) %>% gts_mapper("add_p(pvalue_fun=)") group <- .select_to_varnames( select = {{ group }}, data = x$inputs$data, var_info = x$table_body, arg_name = "group", select_single = TRUE ) include <- .select_to_varnames( select = {{ include }}, data = select(x$inputs$data, any_of(x$meta_data$variable)), var_info = x$table_body, arg_name = "include" ) if (!is.null(group) && group %in% x$meta_data$variable) { glue::glue( "The `group=` variable is no longer auto-removed from the summary table as of v1.3.1.\n", "The following syntax is now preferred:\n", "tbl_summary(..., include = -{group}) %>% add_p(..., group = {group})" ) %>% rlang::inform() } if (is.null(x$df_by)) { paste( "Cannot add a p-value when no 'by' variable", "in original `tbl_summary(by=)` call." ) %>% stop(call. = FALSE) } if ("add_difference" %in% names(x$call_list) && "p.value" %in% names(x$table_body)) { paste("`add_p()` cannot be run after `add_difference()` when a", "'p.value' column is already present.") %>% stop(call. = FALSE) } test <- .formula_list_to_named_list( x = test, data = select(x$inputs$data, any_of(include)), var_info = x$table_body, arg_name = "test", type_check = chuck(type_check, "is_function_or_string", "fn"), type_check_msg = chuck(type_check, "is_function_or_string", "msg") ) if (!is.function(pvalue_fun)) { stop("Input 'pvalue_fun' must be a function.", call. = FALSE) } caller_env <- rlang::caller_env() meta_data <- x$meta_data %>% select(.data$variable, .data$summary_type) %>% filter(.data$variable %in% include) %>% mutate( test = map2( .data$variable, .data$summary_type, function(variable, summary_type) { .assign_test_tbl_summary( data = x$inputs$data, variable = variable, summary_type = summary_type, by = x$by, group = group, test = test ) } ), test_info = map( .data$test, function(test) .get_add_p_test_fun("tbl_summary", test = test, env = caller_env) ), test_name = map_chr(.data$test_info, ~ pluck(.x, "test_name")) ) x$table_body <- x$table_body %>% select(-any_of(c("test_name", "test_result"))) %>% left_join(meta_data[c("variable", "test_name")], by = "variable") %>% select(.data$variable, .data$test_name, everything()) test.args <- .formula_list_to_named_list( x = test.args, data = select(x$inputs$data, any_of(include)), var_info = x$table_body, arg_name = "test.args", type_check = chuck(type_check, "is_named", "fn"), type_check_msg = chuck(type_check, "is_named", "msg") ) x$meta_data <- meta_data %>% mutate( test_result = pmap( list(.data$test_info, .data$variable, .data$summary_type), function(test_info, variable, summary_type) { .run_add_p_test_fun( x = test_info, data = .env$x$inputs$data, by = .env$x$by, variable = variable, group = group, type = summary_type, test.args = test.args[[variable]], tbl = x ) } ), p.value = map_dbl(.data$test_result, ~ pluck(.x, "df_result", "p.value")), stat_test_lbl = map_chr(.data$test_result, ~ pluck(.x, "df_result", "method")) ) %>% select(.data$variable, .data$test_result, .data$p.value, .data$stat_test_lbl) %>% { left_join( x$meta_data %>% select(-any_of(c("test_result", "p.value", "stat_test_lbl"))), ., by = "variable") } x$call_list <- updated_call_list add_p_merge_p_values(x, meta_data = x$meta_data, pvalue_fun = pvalue_fun) } footnote_add_p <- function(meta_data) { if (!"test_result" %in% names(meta_data)) { return(NA_character_) } footnotes <- meta_data$test_result %>% map_chr(~ pluck(., "df_result", "method") %||% NA_character_) %>% stats::na.omit() %>% unique() if (length(footnotes) > 0) { language <- get_theme_element("pkgwide-str:language", default = "en") return(paste(map_chr(footnotes, ~ translate_text(.x, language)), collapse = "; ")) } else { return(NA_character_) } } add_p_merge_p_values <- function(x, lgl_add_p = TRUE, meta_data, pvalue_fun, estimate_fun = NULL, conf.level = 0.95, adj.vars = NULL) { x <- modify_table_body( x, left_join, meta_data %>% select(.data$variable, .data$test_result) %>% mutate( df_result = map(.data$test_result, ~pluck(.x, "df_result")), row_type = "label" ) %>% unnest(.data$df_result) %>% select( -any_of("method"), -any_of(names(x$table_body) %>% setdiff(c("variable", "row_type"))) ), by = c("variable", "row_type") ) %>% modify_table_styling( columns = any_of("p.value"), label = paste0("**", translate_text("p-value"), "**"), hide = FALSE, fmt_fun = pvalue_fun, footnote = footnote_add_p(meta_data) ) if (lgl_add_p == FALSE) { x <- x %>% modify_table_styling( columns = any_of("estimate"), label = ifelse(is.null(adj.vars), paste0("**", translate_text("Difference"), "**"), paste0("**", translate_text("Adjusted Difference"), "**") ), hide = FALSE, fmt_fun = switch(is_function(estimate_fun), estimate_fun ), footnote = footnote_add_p(meta_data) ) if (is.list(estimate_fun)) { x$table_styling$fmt_fun <- x$table_styling$fmt_fun %>% bind_rows( estimate_fun %>% tibble::enframe("variable", "fmt_fun") %>% rowwise() %>% mutate( column = c("estimate", "conf.low", "conf.high") %>% intersect(names(x$table_body)) %>% list(), rows = glue(".data$variable == '{variable}'") %>% rlang::parse_expr() %>% list() ) %>% ungroup() %>% select(.data$column, .data$rows, .data$fmt_fun) %>% unnest(cols = .data$column) ) } if (all(c("conf.low", "conf.high") %in% names(x$table_body)) && !"ci" %in% names(x$table_body)) { ci.sep <- get_theme_element("pkgwide-str:ci.sep", default = ", ") x <- x %>% modify_table_body( ~ .x %>% mutate( ci = pmap_chr( list(variable, conf.low, conf.high), ~ case_when( !is.na(..2) | !is.na(..3) ~ paste(do.call(estimate_fun[[..1]], list(..2)), do.call(estimate_fun[[..1]], list(..3)), sep = ci.sep ) ) ) ) ) %>% modify_table_body(dplyr::relocate, .data$ci, .before = "conf.low") %>% modify_table_styling( any_of("ci"), label = paste0("**", conf.level * 100, "% ", translate_text("CI"), "**"), hide = FALSE, footnote = footnote_add_p(meta_data), footnote_abbrev = translate_text("CI = Confidence Interval") ) } } x } add_p.tbl_cross <- function(x, test = NULL, pvalue_fun = NULL, source_note = NULL, test.args = NULL, ...) { updated_call_list <- c(x$call_list, list(add_p = match.call())) test <- test %||% get_theme_element("add_p.tbl_cross-arg:test") source_note <- source_note %||% get_theme_element("add_p.tbl_cross-arg:source_note", default = FALSE) if (source_note == FALSE) { pvalue_fun <- pvalue_fun %||% get_theme_element("add_p.tbl_cross-arg:pvalue_fun") %||% get_theme_element("pkgwide-fn:pvalue_fun") %||% getOption("gtsummary.pvalue_fun", default = style_pvalue) %>% gts_mapper("add_p(pvalue_fun=)") } else { pvalue_fun <- pvalue_fun %||% get_theme_element("pkgwide-fn:prependpvalue_fun") %||% (function(x) style_pvalue(x, prepend_p = TRUE)) %>% gts_mapper("add_p(pvalue_fun=)") } input_test <- switch(!is.null(test), rlang::expr(everything() ~ !!test) ) input_test.args <- switch(!is.null(test.args), rlang::expr(everything() ~ !!test.args) ) x_copy <- x x$inputs$data <- x$tbl_data x <- expr( add_p.tbl_summary(x, test = !!input_test, test.args = !!input_test.args, pvalue_fun = !!pvalue_fun, include = -any_of("..total..")) ) %>% eval() x$inputs$data <- x_copy$inputs$data if (source_note == TRUE) { test_name <- x$meta_data$stat_test_lbl %>% discard(is.na) %>% translate_text() x <- modify_table_styling( x, columns = "p.value", footnote = NA_character_, hide = TRUE ) x$table_styling$source_note <- paste(test_name, pvalue_fun(discard(x$meta_data$p.value, is.na)), sep = ", ") attr(x$table_styling$source_note, "text_interpret") <- "md" } x$call_list <- updated_call_list x } add_p.tbl_survfit <- function(x, test = "logrank", test.args = NULL, pvalue_fun = style_pvalue, include = everything(), quiet = NULL, ...) { updated_call_list <- c(x$call_list, list(add_p = match.call())) quiet <- quiet %||% get_theme_element("pkgwide-lgl:quiet") %||% FALSE pvalue_fun <- pvalue_fun %||% get_theme_element("pkgwide-fn:pvalue_fun") %||% getOption("gtsummary.pvalue_fun", default = style_pvalue) %>% gts_mapper("add_p(pvalue_fun=)") include <- .select_to_varnames(select = {{ include }}, var_info = x$meta_data) if (rlang::is_string(test)) { test <- expr(everything() ~ !!test) %>% eval() if (!is.null(test.args)) { test.args <- expr(everything() ~ !!test.args) %>% eval() } } test <- .formula_list_to_named_list( x = test, var_info = x$table_body, arg_name = "test", type_check = chuck(type_check, "is_function_or_string", "fn"), type_check_msg = chuck(type_check, "is_function_or_string", "msg") ) caller_env <- rlang::caller_env() meta_data <- x$meta_data %>% filter(.data$stratified == TRUE & .data$variable %in% include) %>% select(.data$variable, .data$survfit) %>% mutate( test = map(.data$variable, ~ test[[.x]] %||% "logrank"), test_info = map( .data$test, function(test) .get_add_p_test_fun("tbl_survfit", test = test, env = caller_env) ), test_name = map_chr(.data$test_info, ~ pluck(.x, "test_name")) ) x$table_body <- left_join(x$table_body, meta_data[c("variable", "test_name")], by = "variable") %>% select(.data$variable, .data$test_name, everything()) test.args <- .formula_list_to_named_list( x = test.args, var_info = x$table_body, arg_name = "test.args", type_check = chuck(type_check, "is_named", "fn"), type_check_msg = chuck(type_check, "is_named", "msg") ) purrr::walk( x$meta_data$survfit, function(suvfit) { survfit_call <- suvfit$call %>% as.list() call_index <- names(survfit_call) %in% c("formula", "data") %>% which() rlang::call2(rlang::expr(stats::model.frame), !!!survfit_call[call_index]) %>% safe_survfit_eval() } ) x$meta_data <- meta_data %>% mutate( test_result = pmap( list(.data$test_info, .data$variable, .data$survfit), function(test_info, variable, survfit) { .run_add_p_test_fun( x = test_info, data = survfit, variable = variable, test.args = test.args[[variable]] ) } ), p.value = map_dbl(.data$test_result, ~ pluck(.x, "df_result", "p.value")), stat_test_lbl = map_chr(.data$test_result, ~ pluck(.x, "df_result", "method")) ) %>% select(.data$variable, .data$test_result, .data$p.value, .data$stat_test_lbl) %>% { left_join(x$meta_data, ., by = "variable") } x$call_list <- updated_call_list add_p_merge_p_values(x, meta_data = x$meta_data, pvalue_fun = pvalue_fun) } add_p.tbl_svysummary <- function(x, test = NULL, pvalue_fun = NULL, include = everything(), test.args = NULL, ...) { updated_call_list <- c(x$call_list, list(add_p = match.call())) assert_package("survey", "add_p.tbl_svysummary()") test <- test %||% get_theme_element("add_p.tbl_svysummary-arg:test") %||% get_theme_element("add_p.tbl_summary-arg:test") pvalue_fun <- pvalue_fun %||% get_theme_element("add_p.tbl_svysummary-arg:pvalue_fun") %||% get_theme_element("add_p.tbl_summary-arg:pvalue_fun") %||% get_theme_element("pkgwide-fn:pvalue_fun") %||% getOption("gtsummary.pvalue_fun", default = style_pvalue) %>% gts_mapper("add_p(pvalue_fun=)") include <- .select_to_varnames( select = {{ include }}, data = select(x$inputs$data$variables, any_of(x$meta_data$variable)), var_info = x$table_body, arg_name = "include" ) if (is.null(x$df_by)) { stop(paste0( "Cannot add comparison when no 'by' variable ", "in original `tbl_svysummary()` call" ), call. = FALSE) } test <- .formula_list_to_named_list( x = test, data = select(x$inputs$data$variables, any_of(x$meta_data$variable)), var_info = x$table_body, arg_name = "test", type_check = chuck(type_check, "is_function_or_string", "fn"), type_check_msg = chuck(type_check, "is_function_or_string", "msg") ) if (!is.function(pvalue_fun)) { stop("Input 'pvalue_fun' must be a function.", call. = FALSE) } caller_env <- rlang::caller_env() meta_data <- x$meta_data %>% select(.data$variable, .data$summary_type) %>% filter(.data$variable %in% include) %>% mutate( test = map2( .data$variable, .data$summary_type, function(variable, summary_type) { .assign_test_tbl_svysummary( data = x$inputs$data, variable = variable, summary_type = summary_type, by = x$by, test = test ) } ), test_info = map( .data$test, function(test) .get_add_p_test_fun("tbl_svysummary", test = test, env = caller_env) ), test_name = map_chr(.data$test_info, ~ pluck(.x, "test_name")) ) x$table_body <- left_join(x$table_body, meta_data[c("variable", "test_name")], by = "variable") %>% select(.data$variable, .data$test_name, everything()) test.args <- .formula_list_to_named_list( x = test.args, data = select(x$inputs$data, any_of(include)), var_info = x$table_body, arg_name = "test.args", type_check = chuck(type_check, "is_named", "fn"), type_check_msg = chuck(type_check, "is_named", "msg") ) x$meta_data <- meta_data %>% mutate( test_result = pmap( list(.data$test_info, .data$variable, .data$summary_type), function(test_info, variable, summary_type) { .run_add_p_test_fun( x = test_info, data = .env$x$inputs$data, by = .env$x$inputs$by, variable = variable, type = summary_type, test.args = test.args[[variable]] ) } ), p.value = map_dbl(.data$test_result, ~ pluck(.x, "df_result", "p.value")), stat_test_lbl = map_chr(.data$test_result, ~ pluck(.x, "df_result", "method")) ) %>% select(.data$variable, .data$test_result, .data$p.value, .data$stat_test_lbl) %>% { left_join(x$meta_data, ., by = "variable") } x$call_list <- updated_call_list add_p_merge_p_values(x, meta_data = x$meta_data, pvalue_fun = pvalue_fun) } add_p.tbl_continuous <- function(x, test = NULL, pvalue_fun = NULL, include = everything(), test.args = NULL, group = NULL, ...) { updated_call_list <- c(x$call_list, list(add_p = match.call())) pvalue_fun <- pvalue_fun %||% get_theme_element("pkgwide-fn:pvalue_fun", default = style_pvalue) %>% gts_mapper("add_p(pvalue_fun=)") include <- .select_to_varnames( select = {{ include }}, data = select(x$inputs$data, any_of(x$meta_data$variable)), var_info = x$table_body, arg_name = "include" ) group <- .select_to_varnames( select = {{ group }}, data = x$inputs$data, arg_name = "group" ) test <- .formula_list_to_named_list( x = test, data = select(x$inputs$data, any_of(x$meta_data$variable)), var_info = x$table_body, arg_name = "test", type_check = chuck(type_check, "is_function_or_string", "fn"), type_check_msg = chuck(type_check, "is_function_or_string", "msg") ) if (!is.function(pvalue_fun)) { stop("Input 'pvalue_fun' must be a function.", call. = FALSE) } caller_env <- rlang::caller_env() meta_data <- x$meta_data %>% select(.data$variable, .data$summary_type) %>% filter(.data$variable %in% .env$include) %>% mutate( test = map( .data$variable, function(variable) { .assign_test_tbl_continuous( data = x$inputs$data, continuous_variable = x$inputs$variable, variable = variable, by = x$inputs$by, group = group, test = test ) } ), test_info = map( .data$test, function(test) .get_add_p_test_fun("tbl_continuous", test = test, env = caller_env) ), test_name = map_chr(.data$test_info, ~ pluck(.x, "test_name")) ) x$table_body <- x$table_body %>% select(-any_of(c("test_name", "test_result"))) %>% left_join(meta_data[c("variable", "test_name")], by = "variable") %>% select(.data$variable, .data$test_name, everything()) test.args <- .formula_list_to_named_list( x = test.args, data = select(x$inputs$data, any_of(include)), var_info = x$table_body, arg_name = "test.args", type_check = chuck(type_check, "is_named", "fn"), type_check_msg = chuck(type_check, "is_named", "msg") ) x$meta_data <- meta_data %>% mutate( test_result = pmap( list(.data$test_info, .data$variable, .data$summary_type), function(test_info, variable, summary_type) { .run_add_p_test_fun( x = test_info, data = .env$x$inputs$data, by = .env$x$inputs$by, variable = variable, group = group, type = summary_type, test.args = test.args[[variable]], tbl = x, continuous_variable = x$inputs$variable ) } ), p.value = map_dbl(.data$test_result, ~ pluck(.x, "df_result", "p.value")), stat_test_lbl = map_chr(.data$test_result, ~ pluck(.x, "df_result", "method")) ) %>% select(.data$variable, .data$test_result, .data$p.value, .data$stat_test_lbl) %>% { left_join( x$meta_data %>% select(-any_of(c("test_result", "p.value", "stat_test_lbl"))), ., by = "variable") } x$call_list <- updated_call_list add_p_merge_p_values(x, meta_data = x$meta_data, pvalue_fun = pvalue_fun) }
hyper_tibble <- function(x, ..., na.rm = TRUE) { UseMethod("hyper_tibble") } hyper_tibble.character <- function(x, ..., na.rm = TRUE) { tidync(x) %>% hyper_filter(...) %>% hyper_tibble() } hyper_tibble.tidync<- function(x, ..., na.rm = TRUE) { slabs <- hyper_array(x, ...) if (na.rm) all_na <- Reduce(`&`, lapply(slabs, function(a) is.na(as.vector(a)))) total_prod <- prod(dim(slabs[[1]])) out <- tibble::as_tibble(lapply(slabs, as.vector)) prod_dims <- 1 trans <- attr(slabs, "transforms") for (i in seq_along(trans)) { nm <- names(trans)[i] nr <- sum(trans[[i]]$selected) out[[nm]] <- rep(dplyr::filter(trans[[nm]], .data$selected)[[nm]], each = prod_dims, length.out = total_prod) prod_dims <- prod_dims * nr } if (na.rm) out <- dplyr::filter(out, !all_na) out }
test_that("XY plot and Cat groups works", { g1 <- plot_xy_CatGroup(mtcars, disp, hp, cyl, TextXAngle = 45) expect_s3_class(g1, "ggplot") expect_equal(g1$theme$text$size, 20) expect_equal(g1$labels$x[1], "disp") expect_equal(g1$labels$y[1], "hp") expect_equal(g1$guides$x$angle, 45) })
bootstrapHet <- function(datafile,ndigit=3, nrepet=1000) { input=read.table(file=datafile, sep='\t', colClasses='character') noext= gsub("[.].*$","",datafile) nloci=ncol(input)-2 whereNbSamples=grep('NbSamples',input[,1]) npops=gsub( "[^0123456789]", "", input[whereNbSamples,1]) npops=as.numeric(npops) whereSampleSize =grep('SampleSize',input[,1]) popsizes=as.numeric(c(gsub('[^0123456789]', "", input[whereSampleSize,1]))) whereSampleName =grep('SampleName',input[,1]) popnames=(c(gsub('SampleName=', "", input[whereSampleName,1]))) matinput=input[,3:ncol(input)] xsums=rep(NA,times=nrow(matinput)) for (i in 1:nrow(matinput)){ xsums[i]=sum(nchar(matinput[i,])) } emptyrows=which(xsums==0) matinput=matinput[-emptyrows,] kvec=vector(mode='numeric',nloci) for (i in 1:nloci) { alleles=matinput[,i] vec=unique(alleles) vec=paste(vec,collapse='') vec=gsub( "[^[:alnum:]]", "", vec) k=nchar(vec)/ndigit kvec[i]=k } MAX=max(kvec) results=matrix(NA,2*nloci,MAX) missing=rep(NA, times=nloci) nbk=rep(NA, times=nloci) n.alleles=rep(NA, times=nloci) for (j in 1:nloci) { alleles=matinput[,j] totaln=length(alleles) vec=unique(alleles) vec=paste(vec,collapse='') vec=gsub( "[^[:alnum:]]", "", vec) k=nchar(vec)/ndigit sampsize=paste(alleles,collapse='') sampsize=gsub( "[^[:alnum:]]", "", sampsize) sampsize=(nchar(sampsize)/ndigit) missingABS=length(grep('[?]',alleles)) missing[j]=round((100*(missingABS/totaln)),2) nbk[j]=k n.alleles[j]=sampsize/2 for (m in 1:k) { alleleID=substr(vec,(m*ndigit)-(ndigit-1),m*ndigit) results[(2*j)-1,m]=alleleID count=0 for (z in 1:length(alleles)) { if (alleles[z]==alleleID) count=count+1 } results[2*j,m]=round(count/sampsize,3) } } for (j in 1:nloci) { ordre=order(results[(2*j)-1,]) results[(2*j)-1,]=results[(2*j)-1,ordre] results[(2*j),]=results[(2*j),ordre] } loc.col=NULL missing.col=NULL k.col=NULL n.alleles.col=NULL for (i in 1:nloci) { loc.col=c(loc.col,i,NA) missing.col=c(missing.col,missing[i],NA) k.col=c(k.col,nbk[i],NA) n.alleles.col=c(n.alleles.col,n.alleles[i],NA) } allpopresults=NULL matpopresults=NULL matpopcounts=NULL popsizes2=2*popsizes for (v in 1:npops) { popmissing=rep(NA,times=nloci) popnbk=rep(NA,times=nloci) pop.n.alleles=rep(NA,times=nloci) popresults=matrix(NA,2*nloci,MAX) popcounts=matrix(NA,2*nloci,MAX) popno=v if (v==1) first=1 if (v>1) first=sum(popsizes2[1:(popno-1)])+1 last=sum(popsizes2[1:popno]) popdata=matinput[first:last,] for (j in 1:nloci) { alleles=popdata[,j] vecalleles=results[(2*j)-1,] k=nbk[j] sampsize=paste(alleles,collapse='') sampsize=gsub( "[^0123456789]", "", sampsize) sampsize=(nchar(sampsize)/ndigit) missingABS=length(grep('[?]',alleles)) popmissing[j]=round((100*(missingABS/popsizes2[v])),2) pop.n.alleles[j]=sampsize/2 for (m in 1:k) { alleleID=vecalleles[m] count=0 for (z in 1:length(alleles)) { if (alleles[z]==alleleID) count=count+1 } popresults[(2*j),m]= round(count/sampsize,3) popresults[(2*j)-1,]=vecalleles popcounts[(2*j),m]= count popcounts[(2*j)-1,]=vecalleles if (popresults[2*j,m]=='NaN') popresults[2*j,m]=0 } popnbk[j]= length(which(popresults[2*j,]>0)) } pop.missing.col=NULL pop.k.col=NULL pop.n.alleles.col=NULL for (i in 1:nloci) { pop.missing.col=c(pop.missing.col,popmissing[i],NA) pop.k.col=c(pop.k.col,popnbk[i],NA) pop.n.alleles.col=c(pop.n.alleles.col,pop.n.alleles[i],NA) } table.popresults=cbind(loc.col,pop.n.alleles.col,pop.missing.col, pop.k.col, popresults) blank.row=rep(NA,times=ncol(table.popresults)) blank.row[1]=popnames[v] allpopresults=rbind(allpopresults,blank.row,table.popresults) matpopresults=rbind(matpopresults,popresults) matpopcounts=rbind(matpopcounts,popcounts) } NAallpopresults=allpopresults allpopn=NAallpopresults[,2] allpopn=allpopn[!is.na(allpopn)] allpopk=NAallpopresults[,4] allpopk=allpopk[!is.na(allpopk)] first.col=NAallpopresults[,1] first.col=first.col[!is.na(first.col)] allpopHo=NULL allpopSampN=NULL for (v in 1:npops) { popHo=rep(NA,times=nloci) popSampN=rep(NA, times=nloci) popno=v if (v==1) first=1 if (v>1) first=sum(popsizes2[1:(popno-1)])+1 last=sum(popsizes2[1:popno]) popdata=matinput[first:last,] for (j in 1:nloci) { if (allpopk[((v-1)*nloci)+j]>0) { alleles=popdata[,j] vec.missing=(which(alleles[]=='?')) if (sum(vec.missing)==0) alleles2=alleles else alleles2=alleles[-vec.missing] true.n=length(alleles2)/2 count=0 for (n in 1:(true.n)) { second.allele= alleles2[(2*n)] if (alleles2[(2*n)-1]!=second.allele) count=count+1 } popHo[j]= round(count/true.n, 3) popSampN[j]=true.n }} allpopHo=cbind(allpopHo,popHo) allpopSampN=cbind(allpopSampN, popSampN) } allpopHe=NULL for (v in 1:npops) { popHe=rep(NA,times=nloci) popno=v first=(((2*popno)-2)*nloci)+1 last=2*popno*nloci freqdata=matpopresults[first:last,] for (j in 1:nloci) { if (allpopk[((v-1)*nloci)+j]>0) { popHe[j]=round(1-sum(as.numeric(freqdata[2*j,])^2, na.rm=T),3) }} allpopHe=cbind(allpopHe,popHe) } table.Ho=as.matrix(as.vector(allpopHo), ncol=1) table.He=as.matrix(as.vector(allpopHe), ncol=1) MeanHo=rep(NA,times=npops) MeanHe=rep(NA,times=npops) for (v in 1:npops) { MeanHo[v]=round(sum(allpopHo[,v]*(allpopSampN[,v]/sum(allpopSampN[,v]))),3) MeanHe[v]=round(sum(allpopHe[,v]*(allpopSampN[,v]/sum(allpopSampN[,v]))),3) } table.stats=cbind(table.Ho,table.He) if (npops>1) { for (p in 2:npops) { table.stats=rbind(table.stats[1:(((p-1)*nloci)+p-2),], NA, table.stats[(((p-1)*nloci)+p-1):nrow(table.stats),]) } } table.stats=rbind(NA,table.stats) table.stats=cbind(first.col,table.stats) col.name=rep('',times=ncol(table.stats)) col.name[1]= 'Locus col.name[2]= 'Ho' col.name[3]= 'He' colnames(table.stats)=col.name filename3=paste(noext,'_bootHe.txt',sep='') for (r in 1:nrow(table.stats)) { for (c in 1:ncol(table.stats)) { if (is.na(table.stats[r,c])==T) table.stats[r,c]='' } } write.table(table.stats, file=filename3, quote=F, row.names=F, col.names=T, sep='\t') simHo=matrix(NA, nrow=npops, ncol=nrepet) simHe=matrix(NA, nrow=npops, ncol=nrepet) for (repn in 1:nrepet) { allpopresults=NULL matpopresults=NULL matpopcounts=NULL popsizes2=2*popsizes for (v in 1:npops) { popmissing=rep(NA,times=nloci) popnbk=rep(NA,times=nloci) pop.n.alleles=rep(NA,times=nloci) popresults=matrix(NA,2*nloci,MAX) popcounts=matrix(NA,2*nloci,MAX) popno=v if (v==1) first=1 if (v>1) first=sum(popsizes2[1:(popno-1)])+1 last=sum(popsizes2[1:popno]) popdata=matinput[first:last,] popdatacopy=popdata ech=sample(1:(nrow(popdata)/2), (nrow(popdata)/2), replace=T) for (x in 1:length(ech)) { popdata[((2*x)-1),]=popdatacopy[((ech[x]*2)-1),] popdata[(2*x),]=popdatacopy[(ech[x]*2),] } locsimHo=rep(NA,times=nloci) for (j in 1:nloci) { if (allpopk[((v-1)*nloci)+j]>0) { alleles=popdata[,j] vec.missing=(which(alleles[]=='?')) if (sum(vec.missing)==0) alleles2=alleles else alleles2=alleles[-vec.missing] true.n=length(alleles2)/2 count=0 for (n in 1:(true.n)) { second.allele= alleles2[(2*n)] if (alleles2[(2*n)-1]!=second.allele) count=count+1 } locsimHo[j]= round(count/true.n, 3) } alleles=popdata[,j] vecalleles=results[(2*j)-1,] k=nbk[j] sampsize=paste(alleles,collapse='') sampsize=gsub( "[^0123456789]", "", sampsize) sampsize=(nchar(sampsize)/ndigit) missingABS=length(grep('[?]',alleles)) popmissing[j]=round((100*(missingABS/popsizes2[v])),2) pop.n.alleles[j]=sampsize/2 for (m in 1:k) { alleleID=vecalleles[m] count=0 for (z in 1:length(alleles)) { if (alleles[z]==alleleID) count=count+1 } popresults[(2*j),m]= round(count/sampsize,3) popresults[(2*j)-1,]=vecalleles popcounts[(2*j),m]= count popcounts[(2*j)-1,]=vecalleles if (popresults[2*j,m]=='NaN') popresults[2*j,m]=0 } popnbk[j]= length(which(popresults[2*j,]>0)) } matpopresults=rbind(matpopresults,popresults) matpopcounts=rbind(matpopcounts,popcounts) simHo[v,repn]=mean(locsimHo) } for (v in 1:npops) { locsimHe=rep(NA, times=nloci) popno=v first=(((2*popno)-2)*nloci)+1 last=2*popno*nloci freqdata=matpopresults[first:last,] for (j in 1:nloci) { if (allpopk[((v-1)*nloci)+j]>0) { locsimHe[j]=round(1-sum(as.numeric(freqdata[2*j,])^2, na.rm=T),3) }} simHe[v,repn]=mean(locsimHe) } } CIs=matrix(NA, nrow=npops, ncol=7) for (j in 1:nrow(CIs)) { CIs[j,1]=j CIs[j,2]=MeanHo[j] CIs[j,3]=round(quantile(simHo[j,], probs=0.025, type=8),3) CIs[j,4]=round(quantile(simHo[j,], probs=0.975, type=8),3) CIs[j,5]=MeanHe[j] CIs[j,6]=round(quantile(simHe[j,], probs=0.025, type=8),3) CIs[j,7]=round(quantile(simHe[j,], probs=0.975, type=8),3) } colnames(CIs)=c('Pop write.table(CIs, file=filename3, quote=F, row.names=F, col.names=T, sep='\t', append=T) }
knitr::opts_chunk$set(echo = TRUE) suppressPackageStartupMessages(library(deSolve)) suppressPackageStartupMessages(library(hisse)) load("cladeSamplingVariables.Rsave") GetProbs <- function(yini, times){ times=times prob.subtree.cal.full <- lsoda(yini, times, func = "maddison_DE_bisse", padded.pars, initfunc="initmod_bisse", dllname = "hisse", rtol=1e-8, atol=1e-8) probs.out <- prob.subtree.cal.full[-1,-1] return(probs.out) } times=c(0, 20) yini <-c(E0=1-0.5, E1=1-0.5, D0=0.5, D1=0) left.branch.probs <- GetProbs(yini, times) left.branch.probs[1:2] times=c(0, 10) yini <-c(E0=1-0.5, E1=1-0.5, D0=0.5, D1=0) right.subA.probs <- GetProbs(yini, times) right.subB.probs <- GetProbs(yini, times) nodeR <- c(right.subA.probs[3:4] * right.subB.probs[3:4] * c(0.1, 0.2)) phi_A <- right.subA.probs[1:2] times=c(10, 20) yini <-c(E0=phi_A[1], E1=phi_A[2], D0=nodeR[1], D1=nodeR[2]) right.branch.probs <- GetProbs(yini, times) right.branch.probs[1:2] round(left.branch.probs[1:2],4) == round(right.branch.probs[1:2],4) times=c(0, 10) yini <-c(E0=1-0.25, E1=1-0.25, D0=0.25, D1=0) right.subA.probs <- GetProbs(yini, times) right.subB.probs <- GetProbs(yini, times) nodeR <- c(right.subA.probs[3:4] * right.subB.probs[3:4] * c(0.1, 0.2)) phi_A <- right.subA.probs[1:2] times=c(10, 20) yini <-c(E0=phi_A[1], E1=phi_A[2], D0=nodeR[1], D1=nodeR[2]) right.branch.probs <- GetProbs(yini, times) right.branch.probs[1:2] left.branch.probs[1:2] round(left.branch.probs[1:2],4) == round(right.branch.probs[1:2],4)
context('efa') test_that('efa works', { set.seed(100) y <- rnorm(100) z <- rnorm(100) data <- list() data[["y1"]] <- y + .2 * rnorm(100) data[["y2"]] <- y + .2 * rnorm(100) data[["y3 plus"]] <- y + .2 * rnorm(100) data[["z1"]] <- z + .2 * rnorm(100) data[["z2"]] <- z + .2 * rnorm(100) attr(data, 'row.names') <- seq_len(length(data[[1]])) attr(data, 'class') <- 'data.frame' efa <- jmv::efa(data = data, vars = c("y1","y2","y3 plus","z1","z2"), nFactorMethod = 'fixed', nFactors = 2, hideLoadings = .3, rotation = 'varimax') expect_equal("", efa$loadings$getCell(rowNo=2, "pc2")$value) expect_equal(0.969985600224343, efa$loadings$getCell(rowNo=2, "pc1")$value) expect_equal(0.00443466058941522, efa$loadings$getCell(rowNo=4, "uniq")$value) expect_equal("y3 plus", efa$loadings$getCell(rowNo=3, "name")$value) expect_error(jmv::efa(data = data, vars = c("y1","y2","y3 plus","z1","z2"), nFactorMethod = "fixed", nFactors = 6), 'Number of factors cannot be bigger than number of variables', fixed=TRUE) data('ToothGrowth') efa2 <- jmv::efa(data = ToothGrowth, vars = c("len","dose"), factorSummary = TRUE, rotation = 'varimax') })
model_parameters.MixMod <- model_parameters.glmmTMB ci.MixMod <- function(x, ci = .95, component = c("all", "conditional", "zi", "zero_inflated"), robust = FALSE, verbose = TRUE, ...) { component <- match.arg(component) if (is.null(.check_component(x, component, verbose = verbose))) { return(NULL) } .ci_generic( model = x, ci = ci, dof = Inf, component = component, robust = robust ) } standard_error.MixMod <- function(model, effects = c("fixed", "random"), component = c("all", "conditional", "zi", "zero_inflated"), robust = FALSE, verbose = TRUE, ...) { component <- match.arg(component) effects <- match.arg(effects) if (effects == "random") { insight::check_if_installed("lme4") rand.se <- lme4::ranef(model, post_vars = TRUE) vars.m <- attr(rand.se, "post_vars") all_names <- attributes(rand.se)$dimnames if (dim(vars.m[[1]])[1] == 1) { rand.se <- sqrt(unlist(vars.m)) } else { rand.se <- do.call( rbind, lapply(vars.m, function(.x) t(as.data.frame(sqrt(diag(.x))))) ) rownames(rand.se) <- all_names[[1]] colnames(rand.se) <- all_names[[2]] rand.se <- list(rand.se) names(rand.se) <- insight::find_random(model, flatten = TRUE) } rand.se } else { if (is.null(.check_component(model, component, verbose = verbose))) { return(NULL) } vc <- insight::get_varcov(model, effects = "fixed", component = "all", robust = robust) se <- sqrt(diag(vc)) x <- .data_frame( Parameter = names(se), SE = as.vector(se), Component = "conditional" ) zi_parms <- grepl("^zi_", x$Parameter) if (any(zi_parms)) { x$Component[zi_parms] <- "zero_inflated" x$Parameter[zi_parms] <- gsub("^zi_(.*)", "\\1", x$Parameter[zi_parms]) } .filter_component(x, component) } } simulate_model.MixMod <- simulate_model.glmmTMB
test_that("Simulating 2 dim symmetric BEKK based on estimated ts object", { obj_spec <- bekk_spec() x1 <- bekk_fit(obj_spec, StocksBonds, QML_t_ratios = FALSE, max_iter = 50, crit = 1e-9) x2 <- bekk_sim(x1, nobs = 100) expect_equal(nrow(x2), 100) expect_equal(ncol(x2), 2) }) test_that("Simulating 2 dim symmetric BEKK based on bekk_spec", { obj_spec <- bekk_spec(model = list(type = "bekk", asymmetric = FALSE), N = 2, init_values = as.matrix(c(0.019783677, -0.014962718, 0.085265736, 0.178859630, -0.007691659, -0.037152006, 0.298147337, 0.981184605, 0.001337367, 0.013260377, 0.951431611))) x2 <- bekk_sim(obj_spec, nobs = 100) expect_equal(nrow(x2), 100) expect_equal(ncol(x2), 2) }) test_that("Simulating 3 dim symmetric BEKK based on estimated xts object", { obj_spec <- bekk_spec() x1 <- bekk_fit(obj_spec, GoldStocksBonds, QML_t_ratios = FALSE, max_iter = 50, crit = 1e-9) x2 <- bekk_sim(x1, nobs = 100) expect_equal(nrow(x2), 100) expect_equal(ncol(x2), 3) }) test_that("Simulating 3 dim symmetric BEKK based on bekk_spec", { obj_spec <- bekk_spec(model = list(type = "bekk", asymmetric = FALSE), N = 3, init_values = as.matrix(c(0.0010122220, -0.0002678085, 0.0001905036, 0.0008937830, 0.0003111280, 0.0003893194, 0.2453276126, 0.0222127631, -0.0434456548, -0.0366629406, 0.2637613982, -0.0248105673, 0.0624407934, -0.0016446789, 0.1733957064, 0.9651528236, -0.0060973318, 0.0155928988, 0.0125157899, 0.9606411455, 0.0008724460, -0.0196494968, -0.0009070321, 0.9801993180))) x2 <- bekk_sim(obj_spec, nobs = 100) expect_equal(nrow(x2), 100) expect_equal(ncol(x2), 3) }) test_that("Simulating 2 dim asymmetric BEKK based on estimated ts object", { obj_spec <- bekk_spec(model = list(type = 'bekk', asymmetric = TRUE)) x1 <- bekk_fit(obj_spec, StocksBonds, QML_t_ratios = FALSE, max_iter = 50, crit = 1e-9) x2 <- bekk_sim(x1, nobs = 100) expect_equal(nrow(x2), 100) expect_equal(ncol(x2), 2) }) test_that("Simulating 2 dim asymmetric BEKK based on bekk_spec", { obj_spec <- bekk_spec(model = list(type = "bekk", asymmetric = TRUE), N = 2, init_values = as.matrix(c(0.019783677, -0.014962718, 0.085265736, 0.178859630, -0.007691659, -0.037152006, 0.298147337, 0.05234,-0.02,0.032,0.1032, 0.981184605, 0.001337367, 0.013260377, 0.951431611))) x2 <- bekk_sim(obj_spec, nobs = 100) expect_equal(nrow(x2), 100) expect_equal(ncol(x2), 2) })
source("common.r") png(file="game_monthly_revenue_extra_rate.png", width=1000, height=400, res=120) op <- par(mar=c(2.5, 2, 2, 6), lwd=2) res <- dbGetQuery(con, " select date_trunc('month',created_at) as month, count(case when price > min_price then true else null end)::numeric / count(*)::numeric as p from purchases where status = 1 and object_type = 1 and min_price is not null and min_price > 0 group by month order by month ") res$month <- as.Date(res$month) res$p <- res$p * 100 res <- truncate_dates(res, "month") plot(res$p, type="b", main="Percent of payments to paid games giving extra money", col=primary_color, ylim=c(0,50), axes=FALSE) months_axis(res$month, skip=FALSE) stops <- axis_stops(50, 5, 10) labels <- format(floor(stops), trim=TRUE, big.mark=",", scientific=FALSE) labels <- paste(labels, "%", sep="") axis(4, col=axis_color, at=stops, labels=labels, las=2)
`extractAIC.cca` <- function (fit, scale = 0, k = 2, ...) { n <- nobs(fit) edf <- 1 if (!is.null(fit$CCA$rank)) edf <- edf + fit$CCA$qrank if (!is.null(fit$pCCA$QR)) edf <- edf + fit$pCCA$QR$rank RSS <- deviance(fit) dev <- if(scale > 0) RSS/scale - n else n * log(RSS/n) c(edf, dev + k*edf) }
context("get_titles") test_that("get titles", { df <- data.frame(x = 1:3, y = 1:3) p <- ggplot(df, aes(x, y)) + geom_point() expect_s3_class(get_title(p), "zeroGrob") expect_s3_class(get_subtitle(p), "zeroGrob") p <- p + labs(title = "Title", subtitle = "Subtitle") expect_s3_class(get_title(p), "titleGrob") expect_s3_class(get_subtitle(p), "titleGrob") })
library(textrecipes) library(recipes) library(tibble) text <- tibble(text = c( "I would not eat them here or there.", "I would not eat them anywhere.", "I would not eat green eggs and ham.", "I do not like them, Sam-I-am." )) test_that("lemmatization works", { skip_on_cran() skip_if_no_python_or_no_spacy() rec <- recipe(~text, data = text) %>% step_tokenize(all_predictors(), engine = "spacyr") %>% step_lemma(all_predictors()) prepped_data <- rec %>% prep() %>% bake(new_data = NULL) expect_s3_class(prepped_data$text, "textrecipes_tokenlist") expect_equal( vctrs::field(prepped_data$text, "tokens"), list( c("I", "would", "not", "eat", "they", "here", "or", "there", "."), c("I", "would", "not", "eat", "they", "anywhere", "."), c("I", "would", "not", "eat", "green", "egg", "and", "ham", "."), c("I", "do", "not", "like", "they", ",", "Sam", "-", "I", "-", "am", ".") ) ) expect_null( attr(prepped_data$text, "lemma") ) }) test_that("lemmatization errors if lemma attribute doesn't exists", { rec <- recipe(~text, data = text) %>% step_tokenize(all_predictors()) %>% step_lemma(all_predictors()) expect_error( prep(rec) ) }) test_that("printing", { skip_on_cran() skip_if_no_python_or_no_spacy() rec <- recipe(~text, data = text) %>% step_tokenize(all_predictors(), engine = "spacyr") %>% step_lemma(all_predictors()) expect_output(print(rec)) expect_output(prep(rec, verbose = TRUE)) }) test_that("empty selection prep/bake is a no-op", { rec1 <- recipe(mpg ~ ., mtcars) rec2 <- step_lemma(rec1) rec1 <- prep(rec1, mtcars) rec2 <- prep(rec2, mtcars) baked1 <- bake(rec1, mtcars) baked2 <- bake(rec2, mtcars) expect_identical(baked1, baked1) }) test_that("empty selection tidy method works", { rec <- recipe(mpg ~ ., mtcars) rec <- step_lemma(rec) expect_identical( tidy(rec, number = 1), tibble(terms = character(), id = character()) ) rec <- prep(rec, mtcars) expect_identical( tidy(rec, number = 1), tibble(terms = character(), id = character()) ) }) test_that("empty printing", { rec <- recipe(mpg ~ ., mtcars) rec <- step_lemma(rec) expect_snapshot(rec) rec <- prep(rec, mtcars) expect_snapshot(rec) })
`bootstrap.wa` <- function(object, n.boot = 1000, verbose = TRUE, ...) { retval <- predict(object, object$orig.x, CV = "bootstrap", n.boot = n.boot, verbose = verbose) .call <- match.call() .call[[1]] <- as.name("bootstrap") retval$call = .call class(retval) <- "bootstrap.wa" return(retval) }
estimateb <- function(data, times, preb, lag, theta, gFunc, v, dObj) { n <- nrow(x = data) m <- length(x = theta) nTimes <- length(x = times) tEl <- -outer(X = data[,dObj$E] + lag, Y = times, FUN = "-") gFuncE <- gFunction(gFunc = gFunc, u = tEl, theta = theta, knts = v) expgE <- exp(x = theta[1L] + gFuncE$gu) Ybt <- preb$Y * {preb$wt0 + preb$wt1*expgE} dNbt <- preb$dNtTilde Yb.sum <- colSums(x = Ybt) dLambdaHat = colSums(x = dNbt) / Yb.sum YdLambdaHat = sweep(x = Ybt, MARGIN = 2L, STATS = dLambdaHat, FUN = "*") dNmYdLambdaHat <- dNbt - YdLambdaHat estb <- rep(x = 0.0, times = m) influmat <- matrix(data = 0.0, nrow = n, ncol = m) ZbmZbar <- list() for (d in 1L:m) { Z <- gFuncE$gutheta[[ d ]] Z[data[,dObj$A] == 0L,] <- 0.0 Zbar <- colSums(x = Ybt*Z) / Yb.sum ZbmZbar[[ d ]] <- t(x = t(x = Z) - Zbar) estb[d] <- sum( ZbmZbar[[ d ]]*dNbt ) influmat[,d] <- rowSums(x = ZbmZbar[[ d ]] * {dNmYdLambdaHat}) } meatb <- crossprod(x = influmat) dNbt <- t(x = dNbt) gradb <- matrix(data = 0.0, nrow = m, ncol = m) for (d1 in 1L:m) { for (d2 in d1:m) { res <- colSums(x = ZbmZbar[[ d1 ]]*ZbmZbar[[ d2 ]]*Ybt) / Yb.sum gradb[d1,d2] <- sum(dNbt*res) gradb[d2,d1] <- gradb[d1,d2] } } return( list("estb" = estb, "gradb" = gradb, "meatb" = meatb) ) }
library(tidyverse) library(ggforce) rule30 <- read_csv(here::here("genuary", "2021", "2021-2", "data", "rule30.csv"), col_names = FALSE) rule30_xy <- rule30 %>% mutate(y = row_number()) %>% pivot_longer(`X1`:`X101`, names_to = "x") %>% filter(value == 1) %>% mutate( x = as.numeric(str_remove(x, "X")), color1 = x %% y, color2 = x %% 2 ) ggplot(rule30_xy) + geom_voronoi_tile(aes(x, y, fill = color1), color = "grey20", size = 0.1) + scale_y_reverse() + scale_fill_viridis_c(option = "magma") + coord_cartesian(expand = FALSE) + theme_void() + theme( legend.position = "none", plot.background = element_rect(fill = "grey10", color = NA), plot.margin = margin(2, 2, 2, 2) ) ggsave(here::here("genuary", "2021", "2021-2", "2021-2.png"), dpi = 320, width = 7, height = 3.7)
esComplete <- function(dfList, lastItemList) { dfCheck <- sapply(dfList, FUN = is.data.frame) if(any(dfCheck == FALSE)) { stop("Error in first argument 'dfList': All elements in the list must be of type 'data.frame'.") } listCheck <- sapply(lastItemList, FUN = is.list) & !sapply(lastItemList, FUN = is.data.frame) if(any(listCheck == FALSE)) { stop("Error in second argument 'lastItemList'. Make sure each list element is again a list, containing exactly 4 entries (for detailed information enter ?esComplete).") } svyNamesFromDfList <- names(dfList) if(any(is.null(svyNamesFromDfList))){ stop("The argument 'dfList' contains at least one data.frame without a name. Prior to this function apply functions 'listES' and 'removeInvalidDf' (in this order).") } svyNamesFromLastItemList <- c() for(m in 1:length(lastItemList)) { svyNamesFromLastItemList <- c(svyNamesFromLastItemList, sapply(lastItemList[[m]][1], FUN = as.character)) } idxOrderComplete <- match(svyNamesFromLastItemList, svyNamesFromDfList) if(any(is.na(idxOrderComplete))) { isNA <- which(is.na(idxOrderComplete)) cat("Prior to this function apply function 'rmInvalid'.\n") stop(paste0(svyNamesFromLastItemList[isNA], " can't be found in the list that contains the raw event sampling data frames.")) } if(any(duplicated(idxOrderComplete))) { idxDupl <- which(duplicated(idxOrderComplete)) maxOccurrence <- 1 for(o in idxDupl) { maxOccurrence_n <- length(which(idxOrderComplete == idxOrderComplete[o])) maxOccurrence <- ifelse(maxOccurrence_n > maxOccurrence, maxOccurrence_n, maxOccurrence) } } checkStructureOfLastItemList <- list() for(n in 1:length(lastItemList)) { checkClass <- sapply(lastItemList[[n]], FUN = class) checkNA <- sapply(lastItemList[[n]], FUN = is.na) colNames <- sapply(lastItemList[[n]][c(2,4)], FUN = as.character) colNameDontExist <- any(is.na(match(colNames[!is.na(colNames)], names(dfList[[idxOrderComplete[n]]])))) if(colNameDontExist) { stop("At least one of the column names in the 2nd argument can't be found in their respective data frame.") } else { checkStructureOfLastItemList[[n]] <- TRUE } if(length(which(is.na(colNames))) == 0) { if(!is.numeric( unlist(dfList[[idxOrderComplete[n]]][colNames[1]]))) { stop("If there is a condition in the questionnaire that must be met in order to determine which item is the last one to contain data, the condition must be numeric, i.e. at least one value (of type integer), according to which the last item is expected to contain data.") } else { checkStructureOfLastItemList[[n]] <- c(checkStructureOfLastItemList[[n]], TRUE) } } } if(any(sapply(checkStructureOfLastItemList, function(x) any(x == FALSE)))) { stop("Error in argument 'lastItemList'. It must be a list of lists, each inner list containing exactly 4 entries (for more detailed information enter ?esComplete).") } lastItemList_elemNo3_list <- sapply(lastItemList, function(x) x[[3]]) lastItemList_elemNo3 <- unlist(lastItemList_elemNo3_list)[!is.na(unlist(lastItemList_elemNo3_list))] true_lastItemList_elemNo3 <- lastItemList_elemNo3 < 0 | lastItemList_elemNo3%%1 != 0 if(any(true_lastItemList_elemNo3)) { stop(paste0("Error in argument 'lastItemList': Only integers > 0 are permitted as values upon which it depends which item of the event sampling questionnaire is the last one expected to contain data. You entered: ", lastItemList_elemNo3[true_lastItemList_elemNo3], ".\n\n")) } svyNamesFromLastItemList <- c() svyNameOccurrence <- c() for(i in 1:length(lastItemList)) { svyName_i <- unlist(lastItemList[[i]][1]) svyNamesFromLastItemList <- c(svyNamesFromLastItemList, svyName_i) svyNameOccurrence <- c(svyNameOccurrence, length(which(svyNamesFromLastItemList%in%svyName_i))) } maxOccurrence <- max(svyNameOccurrence) dfListCompleteQuestionnaires <- list() counter <- 1 for(k in idxOrderComplete) { esVersion_k <- esCompleteSingleVersion( dfList[[k]], unlist(lastItemList[[counter]][1]), unlist(lastItemList[[counter]][2]), unlist(lastItemList[[counter]][3]), unlist(lastItemList[[counter]][4])) if(maxOccurrence > 1) { idxIncomplete <- which(names(esVersion_k) == "INCOMPLETE") colnames(esVersion_k)[idxIncomplete] <- paste0("INCOMPLETE_", svyNameOccurrence[counter]) outListName <- paste0(as.character(svyNamesFromLastItemList[counter]), "_", svyNameOccurrence[counter]) dfListCompleteQuestionnaires[[outListName]] <- esVersion_k counter <- counter + 1 } else { outListName <- as.character(svyNamesFromLastItemList[counter]) dfListCompleteQuestionnaires[[outListName]] <- esVersion_k counter <- counter + 1 } } dfListCompleteQuestionnaires }
knitr::opts_chunk$set(echo = TRUE, fig.width = 7, fig.height = 5) library(qtl2pattern) dirpath <- "https://raw.githubusercontent.com/rqtl/qtl2data/master/DOex" DOex <- subset( qtl2::read_cross2(file.path(dirpath, "DOex.zip")), chr = "2") tmpfile <- tempfile() download.file(file.path(dirpath, "DOex_genoprobs_2.rds"), tmpfile, quiet=TRUE) pr <- readRDS(tmpfile) unlink(tmpfile) tmpfile <- tempfile() download.file(file.path(dirpath, "c2_snpinfo.rds"), tmpfile, quiet=TRUE) snpinfo <- readRDS(tmpfile) unlink(tmpfile) snpinfo <- dplyr::rename(snpinfo, pos = pos_Mbp) snpinfo <- qtl2::index_snps(DOex$pmap, snpinfo) apr <- qtl2::genoprob_to_alleleprob(pr) snpapr <- qtl2::genoprob_to_snpprob(apr, snpinfo) dim(snpapr[["2"]]) dimnames(snpapr[["2"]])[[2]] snppr <- qtl2::genoprob_to_snpprob(pr, snpinfo) dim(snppr[["2"]]) dimnames(snppr[["2"]])[[2]] rm(snpapr) scan_snppr <- qtl2::scan1(snppr, DOex$pheno) qtl2::find_peaks(scan_snppr, snpinfo) top_snps_tbl <- top_snps_pattern(scan_snppr, snpinfo) (patterns <- summary(top_snps_tbl)) head(summary(top_snps_tbl, "best")) scan_pat <- scan1pattern(pr, DOex$pheno, map = DOex$pmap, patterns = patterns) summary(scan_pat, DOex$pmap) pat_names <- paste(c(52,43,16,20), colnames(scan_pat$scan), sep = "_") plot(scan_pat$scan, DOex$pmap, lodcolumn = 2, col = "red", xlim = c(90,110), type = "b") abline(v = c(96.5, 98.5), col = "darkgray", lwd = 2, lty = 2) plot(scan_pat$scan, DOex$pmap, lodcolumn = 1, add = TRUE, col = "blue", type = "b") plot(scan_pat$scan, DOex$pmap, lodcolumn = 3, add = TRUE, col = "purple", type = "b") plot(scan_pat$scan, DOex$pmap, lodcolumn = 4, add = TRUE, col = "green", type = "b") title("Scans for SDP 52 (blue), 43 (red), 16 (purple), 20 (green)") plot(scan_pat$scan, DOex$pmap, lodcolumn = 2, col = "red") abline(v = c(96.5, 98.5), col = "darkgray", lwd = 2, lty = 2) plot(scan_pat$scan, DOex$pmap, lodcolumn = 1, add = TRUE, col = "blue") plot(scan_pat$scan, DOex$pmap, lodcolumn = 3, add = TRUE, col = "purple") plot(scan_pat$scan, DOex$pmap, lodcolumn = 4, add = TRUE, col = "green") title("Scans for SDP 52 (blue), 43 (red), 16 (purple), 20 (green)") oldpar <- par(mfrow = c(2,2)) cols <- c("blue","purple","red") for(i in 1:4) { plot(scan_pat$coef[[i]], DOex$pmap, columns = 1:3, col = cols, xlim = c(90,110), type = "b") title(paste("Coefficients for", pat_names[i])) if(i == 3) { abline(v = c(96.5, 98.5), col = "darkgray", lwd = 2, lty = 2) legend(104, -3, legend = c("ref","het","alt"), col = cols, lty = 1, lwd = 2) } } par(oldpar) par(mfrow = c(2,2)) cols <- c("blue","purple","red") for(i in 1:4) { plot(scan_pat$coef[[i]], DOex$pmap, columns = 1:3, col = cols) title(paste("Coefficients for", pat_names[i])) if(i == 3) { abline(v = c(96.5, 98.5), col = "darkgray", lwd = 2, lty = 2) legend(125, -3, legend = c("ref","het","alt"), col = cols, lty = 1, lwd = 2) } } coefs2 <- qtl2::scan1coef(pr, DOex$pheno[,"OF_immobile_pct"], zerosum = FALSE) x <- LETTERS[1:8] ref <- outer(x,x,paste0) ref <- ref[upper.tri(ref, diag=TRUE)] ss <- 2 - sapply(stringr::str_split(ref, ""), function(x) x[1] == x[2]) alt <- ref[!stringr::str_detect(ref, c("A|B|C|D|G|H"))] het <- ref[stringr::str_detect(ref, c("A|B|C|D|G|H")) & stringr::str_detect(ref, c("E|F"))] altw <- ss[match(alt, ref, nomatch = 0)] hetw <- ss[match(het, ref, nomatch = 0)] refw <- ss[!stringr::str_detect(ref, c("E|F"))] ref <- ref[!stringr::str_detect(ref, c("E|F"))] coefsum <- coefs2 coefsum[,"AA"] <- apply(coefsum[,ref], 1, weighted.mean, w = refw) coefsum[,"AB"] <- apply(coefsum[,het], 1, weighted.mean, w = hetw) coefsum[,"BB"] <- apply(coefsum[,alt], 1, weighted.mean, w = altw) colnames(coefsum)[1:3] <- c("ref","het","alt") plot(coefsum, DOex$pmap, c("ref", "het", "alt", alt), xlim = c(90,110), ylim = c(-500, 500), col = c(1,8,7,2:4), type = "b") abline(h = mean(DOex$pheno[,"OF_immobile_pct"]), lwd = 2, col = "darkgrey", lty = 2) abline(v = c(96.5, 98.5), col = "darkgray", lwd = 2, lty = 2) title("Allele Coefficients for OF_immobile_pct") legend(105, 80, legend = c("ref", "het", "alt", alt), col = c(1,8,7,2:4), lty = 1, lwd = 2) plot(coefsum, DOex$pmap, c("ref", "het", alt[-1]), xlim = c(90,110), ylim = c(55,90), col = c(1,8,3:4), type = "b") abline(h = mean(DOex$pheno[,"OF_immobile_pct"]), lwd = 2, col = "darkgrey", lty = 2) abline(v = c(96.5, 98.5), col = "darkgray", lwd = 2, lty = 2) title("Allele Pair Coefficients for OF_immobile_pct") legend(107, 75, legend = c("ref", "het", alt[-1]), col = c(1,8,3:4), lty = 1, lwd = 2) scan_apr <- qtl2::scan1(apr, DOex$pheno) coefs <- qtl2::scan1coef(apr, DOex$pheno) coefs2 <- qtl2::scan1coef(pr, DOex$pheno) alleles <- allele1(probD = pr, scanH = scan_apr, coefH = coefs, coefD = coefs2, scan_pat = scan_pat, map = DOex$pmap, alt = "E") ggplot2::autoplot(alleles, scan_apr, DOex$pmap, frame = FALSE) aa <- subset(alleles, sources = levels(alleles$source)[c(1,4:6)]) ggplot2::autoplot(aa, scan_apr, DOex$pmap, frame = FALSE) pos = patterns$max_pos[patterns$sdp == 48] wh <- which.min(abs(pos - DOex$pmap[[1]])) geno <- apply(snppr[[1]][,,wh], 1, function(x) which.max(x)) geno <- factor(c("ref","het","alt")[geno], c("ref","het","alt")) dat <- data.frame(DOex$pheno, geno = geno) dat$x <- jitter(rep(1, nrow(dat))) ggplot2::ggplot(dat) + ggplot2::aes(x = x, y = OF_immobile_pct, col = geno, label = geno) + ggplot2::geom_boxplot() + ggplot2::geom_point() + ggplot2::facet_wrap(~ geno) tmpfile <- tempfile() download.file(file.path(dirpath, "c2_genes.rds"), tmpfile, quiet=TRUE) gene_tbl <- readRDS(tmpfile) unlink(tmpfile) class(gene_tbl) <- c("feature_tbl", class(gene_tbl)) out <- merge_feature(top_snps_tbl, snpinfo, scan_snppr, exons = gene_tbl) summary(out, "pattern") out$snp_type <- sample(c(rep("intron", 40), rep("exon", nrow(out) - 40))) ggplot2::autoplot(out, "OF_immobile_pct") ggplot2::autoplot(out, "OF_immobile_pct", "consequence") qtl2::plot_genes(gene_tbl, xlim = c(96,99)) ggplot2::autoplot(gene_tbl) ggplot2::autoplot(gene_tbl, top_snps_tbl = top_snps_tbl) out <- gene_exon(top_snps_tbl, gene_tbl) summary(out, gene = out$gene[1]) ggplot2::autoplot(out, top_snps_tbl) query_variants <- qtl2::create_variant_query_func( file.path("qtl2shinyData", "CCmouse", "cc_variants.sqlite")) query_genes <- qtl2::create_gene_query_func( file.path("qtl2shinyData", "CCmouse", "mouse_genes.sqlite")) objects(envir = environment(query_variants)) get("dbfile", envir = environment(query_variants))
dist <- function(x, method = "euclidean", diag = FALSE, upper = FALSE, p = 2) { if(!is.na(pmatch(method, "euclidian"))) method <- "euclidean" METHODS <- c("euclidean", "maximum", "manhattan", "canberra", "binary", "minkowski") method <- pmatch(method, METHODS) if(is.na(method)) stop("invalid distance method") if(method == -1) stop("ambiguous distance method") x <- as.matrix(x) N <- nrow(x) attrs <- if(method == 6L) list(Size = N, Labels = dimnames(x)[[1L]], Diag = diag, Upper = upper, method = METHODS[method], p = p, call = match.call(), class = "dist") else list(Size = N, Labels = dimnames(x)[[1L]], Diag = diag, Upper = upper, method = METHODS[method], call = match.call(), class = "dist") .Call(C_Cdist, x, method, attrs, p) } format.dist <- function(x, ...) format(as.vector(x), ...) as.matrix.dist <- function(x, ...) { size <- attr(x, "Size") df <- matrix(0, size, size) df[row(df) > col(df)] <- x df <- df + t(df) labels <- attr(x, "Labels") dimnames(df) <- if(is.null(labels)) list(seq_len(size), seq_len(size)) else list(labels,labels) df } as.dist <- function(m, diag = FALSE, upper = FALSE) UseMethod("as.dist") as.dist.default <- function(m, diag = FALSE, upper = FALSE) { if (inherits(m,"dist")) ans <- m else { m <- as.matrix(m) if(!is.numeric(m)) storage.mode(m) <- "numeric" p <- nrow(m) if(ncol(m) != p) warning("non-square matrix") ans <- m[row(m) > col(m)] attributes(ans) <- NULL if(!is.null(rownames(m))) attr(ans,"Labels") <- rownames(m) else if(!is.null(colnames(m))) attr(ans,"Labels") <- colnames(m) attr(ans,"Size") <- p attr(ans, "call") <- match.call() class(ans) <- "dist" } if(is.null(attr(ans,"Diag")) || !missing(diag)) attr(ans,"Diag") <- diag if(is.null(attr(ans,"Upper")) || !missing(upper)) attr(ans,"Upper") <- upper ans } print.dist <- function(x, diag = NULL, upper = NULL, digits = getOption("digits"), justify = "none", right = TRUE, ...) { if(length(x)) { if(is.null(diag)) diag <- attr(x, "Diag") %||% FALSE if(is.null(upper)) upper <- attr(x,"Upper") %||% FALSE m <- as.matrix(x) cf <- format(m, digits = digits, justify = justify) if(!upper) cf[row(cf) < col(cf)] <- "" if(!diag) cf[row(cf) == col(cf)] <- "" print(if(diag || upper) cf else cf[-1, -attr(x, "Size"), drop = FALSE], quote = FALSE, right = right, ...) } else { cat(data.class(x),"(0)\n", sep = "") } invisible(x) } labels.dist <- function (object, ...) attr(object,"Labels")
def_sXaug_Matrix_QRP_CHM_scaled <- function(Xaug,weight_X,w.ranef,H_global_scale) { n_u_h <- length(w.ranef) Xrows <- n_u_h+seq(length(weight_X)) Xaug <- .Dvec_times_Matrix_lower_block(weight_X,Xaug,n_u_h) attr(Xaug, "get_from") <- "get_from_MME.sXaug_Matrix_QRP_CHM_scaled" attr(Xaug, "BLOB") <- list2env(list(), parent=environment(.sXaug_Matrix_QRP_CHM_scaled)) attr(Xaug, "w.ranef") <- w.ranef attr(Xaug, "n_u_h") <- n_u_h attr(Xaug, "pforpv") <- ncol(Xaug)-n_u_h attr(Xaug, "weight_X") <- weight_X attr(Xaug, "H_global_scale") <- H_global_scale return( Xaug ) } .calc_t_Q_scaled <- function(BLOB, sXaug) { if (eval(.spaMM.data$options$presolve_cond) && .calc_denseness(sXaug,relative = TRUE)>0.004 ) { Matrix::tcrossprod(t(BLOB$solve_R_scaled), sXaug[,BLOB$perm]) } else { solve(t(BLOB$R_scaled),t(sXaug[,BLOB$perm])) } } .calc_hatval_Z_u_h_cols_on_left <- function(BLOB, sXaug) { n_u_h <- attr(sXaug,"n_u_h") tmp_t_Qq_scaled <- BLOB$t_Q_scaled[BLOB$seq_n_u_h,] tmp_t_Qq_scaled@x <- tmp_t_Qq_scaled@x*tmp_t_Qq_scaled@x tmp <- colSums(tmp_t_Qq_scaled) phipos <- n_u_h+seq_len(nrow(sXaug)-n_u_h) hatval_Z_ <- list(lev_lambda=tmp[-phipos],lev_phi=tmp[phipos]) } .calc_Z_lev_lambda <- function(BLOB) { lev_lambda <- BLOB$inv_factor_wd2hdv2w lev_lambda@x <- lev_lambda@x*lev_lambda@x lev_lambda <- colSums(lev_lambda) } .calc_Z_lev_phi <- function(BLOB, sXaug) { n_u_h <- attr(sXaug,"n_u_h") phipos <- (n_u_h+1L):nrow(sXaug) lev_phi <- .tcrossprod(BLOB$inv_factor_wd2hdv2w, sXaug[phipos, BLOB$seq_n_u_h ], chk_sparse2mat = FALSE) lev_phi@x <- lev_phi@x*lev_phi@x lev_phi <- colSums(lev_phi) } .sXaug_Matrix_QRP_CHM_scaled <- function(sXaug,which="",szAug=NULL,B=NULL) { BLOB <- attr(sXaug,"BLOB") if (is.null(BLOB$blob)) { BLOB$blob <- qr(sXaug) BLOB$perm <- BLOB$blob@q + 1L BLOB$R_scaled <- qrR(BLOB$blob,backPermute = FALSE) delayedAssign("sortPerm", sort.list(BLOB$perm), assign.env = BLOB ) delayedAssign("seq_n_u_h", seq(attr(sXaug,"n_u_h")), assign.env = BLOB ) delayedAssign("sortPerm_u_h", BLOB$sortPerm[ BLOB$seq_n_u_h], assign.env = BLOB ) delayedAssign("u_h_cols_on_left", (max(BLOB$sortPerm_u_h)==attr(sXaug,"n_u_h")), assign.env = BLOB ) delayedAssign("use_R_block", (BLOB$u_h_cols_on_left && FALSE) , assign.env = BLOB ) delayedAssign("invsqrtwranef", 1/sqrt(attr(sXaug,"w.ranef")), assign.env = BLOB ) delayedAssign("solve_R_scaled", as(.rawsolve(BLOB$R_scaled),"dtCMatrix"), assign.env = BLOB ) delayedAssign("t_Q_scaled", .calc_t_Q_scaled(BLOB, sXaug), assign.env = BLOB ) delayedAssign("CHMfactor_wd2hdv2w", { wd2hdv2w <- .crossprod(BLOB$R_scaled[,BLOB$sortPerm_u_h, drop=FALSE], allow_as_mat = FALSE ) Cholesky(wd2hdv2w,LDL=FALSE, perm=FALSE ) }, assign.env = BLOB ) delayedAssign("inv_factor_wd2hdv2w", { if (BLOB$use_R_block) { sortPerm_u_h <- BLOB$sortPerm_u_h t(BLOB$solve_R_scaled)[sortPerm_u_h,sortPerm_u_h, drop=FALSE] } else Matrix::solve(BLOB$CHMfactor_wd2hdv2w,system="L") } , assign.env = BLOB ) delayedAssign("inv_d2hdv2", { if (.is_evaluated("inv_factor_wd2hdv2w",BLOB)) { inv_d2hdv2 <- .Matrix_times_Dvec(.crossprod(BLOB$inv_factor_wd2hdv2w), BLOB$invsqrtwranef) } else inv_d2hdv2 <- Matrix::solve(BLOB$CHMfactor_wd2hdv2w, Diagonal(x=BLOB$invsqrtwranef), system="A") inv_d2hdv2 <- .Dvec_times_Matrix( - BLOB$invsqrtwranef,inv_d2hdv2) }, assign.env = BLOB ) delayedAssign("logdet_R_scaled_b_v", sum(log(abs(diag(x=BLOB$R_scaled)))), assign.env = BLOB ) delayedAssign("logdet_R_scaled_v", { if (BLOB$use_R_block) { sum(log(abs(diag(x=BLOB$R_scaled)[BLOB$seq_n_u_h]))) } else Matrix::determinant(BLOB$CHMfactor_wd2hdv2w)$modulus[1] }, assign.env = BLOB ) delayedAssign("logdet_r22", { if (BLOB$u_h_cols_on_left) { sum(log(abs(diag(x=BLOB$R_scaled)[-BLOB$seq_n_u_h]))) - attr(sXaug,"pforpv")*log(attr(sXaug,"H_global_scale"))/2 } else { BLOB$logdet_R_scaled_b_v - BLOB$logdet_R_scaled_v - attr(sXaug,"pforpv")*log(attr(sXaug,"H_global_scale"))/2 } } , assign.env = BLOB ) delayedAssign("logdet_sqrt_d2hdv2", { sum(log(attr(sXaug,"w.ranef")))/2 + BLOB$logdet_R_scaled_v }, assign.env = BLOB ) delayedAssign("hatval", { tmp <- BLOB$t_Q_scaled tmp@x <- tmp@x*tmp@x colSums(tmp) } , assign.env = BLOB ) delayedAssign("hatval_Z_u_h_cols_on_left", .calc_hatval_Z_u_h_cols_on_left(BLOB, sXaug), assign.env = BLOB ) delayedAssign("Z_lev_lambda", .calc_Z_lev_lambda(BLOB), assign.env = BLOB ) delayedAssign("Z_lev_phi", .calc_Z_lev_phi(BLOB, sXaug), assign.env = BLOB ) if ( ! is.null(szAug)) return(qr.coef(BLOB$blob,szAug)) } if ( ! is.null(szAug)) { return(qr.coef(BLOB$blob,szAug)) } if (which=="Qt_leftcols*B") { if (.is_evaluated("solve_R_scaled", BLOB)) { return(.crossprod(BLOB$solve_R_scaled, .crossprod(sXaug[-BLOB$seq_n_u_h,BLOB$perm], B))) } else return(solve(t(BLOB$R_scaled), .crossprod(sXaug[-BLOB$seq_n_u_h,BLOB$perm], B))) } if (which=="Mg_solve_g") { seq_n_u_h <- BLOB$seq_n_u_h rhs <- B rhs[seq_n_u_h] <- BLOB$invsqrtwranef * rhs[seq_n_u_h] if (.is_evaluated("solve_R_scaled", BLOB)) { rhs <- BLOB$solve_R_scaled %*% rhs[BLOB$perm] } else rhs <- Matrix::solve(BLOB$R_scaled,rhs[BLOB$perm]) return(sum(rhs^2)) } if (which=="Mg_invH_g") { rhs <- BLOB$invsqrtwranef * B if (.is_evaluated("inv_factor_wd2hdv2w",BLOB)) { rhs <- BLOB$inv_factor_wd2hdv2w %*% rhs } else rhs <- Matrix::solve(BLOB$CHMfactor_wd2hdv2w,rhs,system="L") return(sum(rhs^2)) } if (which=="Mg_invXtWX_g") { seq_n_u_h <- BLOB$seq_n_u_h if (is.null(BLOB$XtWX)) BLOB$XtWX <- .crossprod(sXaug[-seq_n_u_h,-seq_n_u_h]) Mg_invXtWX_g <- crossprod(B,solve(BLOB$XtWX,B))[1L] return(Mg_invXtWX_g) } if (which=="hatval_Z") { if (BLOB$u_h_cols_on_left) { return(BLOB$hatval_Z_u_h_cols_on_left) } else if (FALSE) { if (is.null(BLOB$hatval_Z_)) { tq <- drop0(.lmwithQR(as.matrix(BLOB$R_scaled[,BLOB$sortPerm][,BLOB$seq_n_u_h]) ,yy=NULL,returntQ=TRUE,returnR=FALSE)$t_Q_scaled, tol=1e-16) tmp_t_Qq_scaled <- tq %*% BLOB$t_Q_scaled tmp_t_Qq_scaled@x <- tmp_t_Qq_scaled@x*tmp_t_Qq_scaled@x tmp <- colSums(tmp_t_Qq_scaled) n_u_h <- attr(sXaug,"n_u_h") phipos <- n_u_h+seq_len(nrow(sXaug)-n_u_h) BLOB$hatval_Z_ <- list(lev_lambda=tmp[-phipos],lev_phi=tmp[phipos]) } return(BLOB$hatval_Z_) } else { hatval_Z_ <- list() if ("lambda" %in% B) hatval_Z_$lev_lambda <- BLOB$Z_lev_lambda if ("phi" %in% B) hatval_Z_$lev_phi <- BLOB$Z_lev_phi return(hatval_Z_) } } if (which=="solve_d2hdv2") { if (is.null(B)) { return(BLOB$inv_d2hdv2) } else { if (.is_evaluated("inv_d2hdv2", BLOB)) { return(BLOB$inv_d2hdv2 %*% B) } else { not_vector <- (( ! is.null(dimB <- dim(B))) && length(dimB)==2L && dimB[2L]>1L) if (not_vector) { rhs <- .Dvec_times_m_Matrix(BLOB$invsqrtwranef,B) } else rhs <- BLOB$invsqrtwranef * B if ( BLOB$use_R_block || .is_evaluated("inv_factor_wd2hdv2w",BLOB)) { rhs <- .crossprod(BLOB$inv_factor_wd2hdv2w, drop(BLOB$inv_factor_wd2hdv2w %*% rhs)) } else rhs <- Matrix::solve(BLOB$CHMfactor_wd2hdv2w,rhs,system="A") if (not_vector) { rhs <- .Dvec_times_m_Matrix(BLOB$invsqrtwranef,rhs) } else rhs <- BLOB$invsqrtwranef * rhs return( - rhs) } } } if (which=="hatval") {return(BLOB$hatval) } if (which=="R_scaled_blob") { if (is.null(BLOB$R_scaled_blob)) { tmp <- X <- BLOB$R_scaled[ , BLOB$sortPerm] tmp@x <- tmp@x*tmp@x BLOB$R_scaled_blob <- list(X=X, diag_pRtRp=colSums(tmp), XDtemplate=structure(.XDtemplate(X),upperTri=FALSE)) } return(BLOB$R_scaled_blob) } if (which=="R_scaled_v_h_blob") { if (is.null(BLOB$R_scaled_v_h_blob)) { if (BLOB$use_R_block) { R_scaled_v_h <- t(BLOB$R_scaled[BLOB$sortPerm_u_h,BLOB$sortPerm_u_h, drop=FALSE]) } else { R_scaled_v_h <- t( as(BLOB$CHMfactor_wd2hdv2w,"sparseMatrix") ) } tmp <- R_scaled_v_h tmp@x <- tmp@x*tmp@x diag_pRtRp_scaled_v_h <- colSums(tmp) BLOB$R_scaled_v_h_blob <- list(R_scaled_v_h=R_scaled_v_h,diag_pRtRp_scaled_v_h=diag_pRtRp_scaled_v_h, XDtemplate=structure(.XDtemplate(R_scaled_v_h), upperTri=NA)) } return(BLOB$R_scaled_v_h_blob) } if (which=="R_beta_blob") { if (is.null(BLOB$R_beta_blob)) { n_u_h <- attr(sXaug,"n_u_h") seq_n_u_h <- BLOB$seq_n_u_h X <- as.matrix(sXaug[-seq_n_u_h,-seq_n_u_h]) R_beta <- .lmwithQR(X,yy=NULL,returntQ=FALSE,returnR=TRUE)$R_scaled diag_pRtRp_beta <- colSums(R_beta^2) BLOB$R_beta_blob <- list(R_beta=R_beta,diag_pRtRp_beta=diag_pRtRp_beta, XDtemplate=structure(.XDtemplate(R_beta), upperTri=TRUE)) } return(BLOB$R_beta_blob) } if (which=="logdet_sqrt_d2hdv2") { return(BLOB$logdet_sqrt_d2hdv2)} if (which=="logdet_r22") { return(BLOB$logdet_r22) } if (which=="t_Q_scaled") { return(BLOB$t_Q_scaled) } if (which=="logdet_R_scaled_b_v") { return(BLOB$logdet_R_scaled_b_v)} if (which=="beta_cov_info_from_sXaug") { return(.calc_beta_cov_info_from_sXaug(BLOB=BLOB, sXaug=sXaug, tcrossfac=BLOB$solve_R_scaled)) } if (which=="beta_cov_info_from_wAugX") { tPmat <- sparseMatrix(seq_along(BLOB$sortPerm), BLOB$sortPerm, x=1) tcrossfac_beta_v_cov <- as.matrix(tPmat %*% BLOB$solve_R_scaled) rownames(tcrossfac_beta_v_cov) <- colnames(sXaug) pforpv <- attr(sXaug,"pforpv") seqp <- seq_len(pforpv) beta_cov <- .tcrossprod(tcrossfac_beta_v_cov[seqp,,drop=FALSE]) return( list(beta_cov=beta_cov, tcrossfac_beta_v_cov=tcrossfac_beta_v_cov) ) } if (which=="d2hdv2") { stop("d2hdv2 requested ") } stop("invalid 'which' value.") } get_from_MME.sXaug_Matrix_QRP_CHM_scaled <- function(sXaug,which="",szAug=NULL,B=NULL, damping, LMrhs, ...) { resu <- switch(which, "LevMar_step" = { R_scaled_blob <- .sXaug_Matrix_QRP_CHM_scaled(sXaug,which="R_scaled_blob") dampDpD <- damping*R_scaled_blob$diag_pRtRp list(dVscaled_beta=.damping_to_solve(XDtemplate=R_scaled_blob$XDtemplate, dampDpD=dampDpD, rhs=LMrhs), dampDpD = dampDpD) }, "LevMar_step_v_h" = { R_scaled_v_h_blob <- .sXaug_Matrix_QRP_CHM_scaled(sXaug,which="R_scaled_v_h_blob") dampDpD <- damping*R_scaled_v_h_blob$diag_pRtRp_scaled_v_h list(dVscaled = .damping_to_solve(XDtemplate=R_scaled_v_h_blob$XDtemplate, dampDpD=dampDpD, rhs=LMrhs), dampDpD = dampDpD) }, "LevMar_step_beta" = { if ( ! length(LMrhs)) stop("LevMar_step_beta called with 0-length LMrhs: pforpv=0?") R_beta_blob <- .sXaug_Matrix_QRP_CHM_scaled(sXaug,which="R_beta_blob") dampDpD <- damping*R_beta_blob$diag_pRtRp_beta list(dbeta = .damping_to_solve(XDtemplate=R_beta_blob$XDtemplate, dampDpD=dampDpD, rhs=LMrhs), dampDpD = dampDpD) } , .sXaug_Matrix_QRP_CHM_scaled(sXaug,which=which,szAug=szAug,B=B) ) return(resu) }
searchPair <- function(signaling = c(), pairLR.use, key = c("pathway_name","ligand"), matching.exact = FALSE, pair.only = TRUE) { key <- match.arg(key) pairLR = future.apply::future_sapply( X = 1:length(signaling), FUN = function(x) { if (!matching.exact) { index <- grep(signaling[x], pairLR.use[[key]]) } else { index <- which(pairLR.use[[key]] %in% signaling[x]) } if (length(index) > 0) { if (pair.only) { pairLR <- dplyr::select(pairLR.use[index, ], interaction_name, pathway_name, ligand, receptor) } else { pairLR <- pairLR.use[index, ] } return(pairLR) } else { stop(cat(paste("Cannot find ", signaling[x], ".", "Please input a correct name!"),'\n')) } } ) if (pair.only) { pairLR0 <- vector("list", length(signaling)) for (i in 1:length(signaling)) { pairLR0[[i]] <- matrix(unlist(pairLR[c(4*i-3, 4*i-2, 4*i-1, 4*i)]), ncol=4, byrow=F) } pairLR <- do.call(rbind, pairLR0) dimnames(pairLR)[[2]] <- dimnames(pairLR.use)[[2]][1:4] rownames(pairLR) <- pairLR[,1] } else { pairLR0 <- vector("list", length(signaling)) for (i in 1:length(signaling)) { pairLR0[[i]] <- matrix(unlist(pairLR[(i*ncol(pairLR.use)-(ncol(pairLR.use)-1)):(i*ncol(pairLR.use))]), ncol=ncol(pairLR.use), byrow=F) } pairLR <- do.call(rbind, pairLR0) dimnames(pairLR)[[2]] <- dimnames(pairLR.use)[[2]] rownames(pairLR) <- pairLR[,1] } return(as.data.frame(pairLR, stringsAsFactors = FALSE)) } subsetDB <- function(CellChatDB, search = c(), key = "annotation") { interaction_input <- CellChatDB$interaction interaction_input <- interaction_input[interaction_input[[key]] %in% search, ] CellChatDB$interaction <- interaction_input return(CellChatDB) } extractGene <- function(CellChatDB) { interaction_input <- CellChatDB$interaction complex_input <- CellChatDB$complex cofactor_input <- CellChatDB$cofactor geneIfo <- CellChatDB$geneInfo checkGeneSymbol(geneSet = unlist(complex_input), geneIfo) checkGeneSymbol(geneSet = unlist(cofactor_input), geneIfo) geneL <- unique(interaction_input$ligand) geneR <- unique(interaction_input$receptor) geneLR <- c(geneL, geneR) checkGeneSymbol(geneSet = geneLR[geneLR %in% rownames(complex_input) == "FALSE"], geneIfo) geneL <- extractGeneSubset(geneL, complex_input, geneIfo) geneR <- extractGeneSubset(geneR, complex_input, geneIfo) geneLR <- c(geneL, geneR) cofactor <- c(interaction_input$agonist, interaction_input$antagonist, interaction_input$co_A_receptor, interaction_input$co_I_receptor) cofactor <- unique(cofactor[cofactor != ""]) cofactorsubunits <- select(cofactor_input[match(cofactor, rownames(cofactor_input), nomatch=0),], starts_with("cofactor")) cofactorsubunitsV <- unlist(cofactorsubunits) geneCofactor <- unique(cofactorsubunitsV[cofactorsubunitsV != ""]) gene.use <- unique(c(geneLR, geneCofactor)) return(gene.use) } extractGeneSubset <- function(geneSet, complex_input, geneIfo) { complex <- geneSet[which(geneSet %in% geneIfo$Symbol == "FALSE")] geneSet <- intersect(geneSet, geneIfo$Symbol) complexsubunits <- dplyr::select(complex_input[match(complex, rownames(complex_input), nomatch=0),], starts_with("subunit")) complex <- intersect(complex, rownames(complexsubunits)) complexsubunitsV <- unlist(complexsubunits) complexsubunitsV <- unique(complexsubunitsV[complexsubunitsV != ""]) geneSet <- unique(c(geneSet, complexsubunitsV)) return(geneSet) } extractGeneSubsetFromPair <- function(pairLR, object = NULL, complex_input = NULL, geneInfo = NULL, combined = TRUE) { if (!all(c("ligand", "receptor") %in% colnames(pairLR))) { stop("The input data frame must contain columns named `ligand` and `receptor`") } if (is.null(object)) { if (is.null(complex_input) | is.null(geneInfo)) { stop("Either `object` or `complex_input` and `geneInfo` should be provided!") } else { complex <- complex_input } } else { complex <- object@DB$complex geneInfo <- object@DB$geneInfo } geneL <- unique(pairLR$ligand) geneR <- unique(pairLR$receptor) geneL <- extractGeneSubset(geneL, complex, geneInfo) geneR <- extractGeneSubset(geneR, complex, geneInfo) geneLR <- c(geneL, geneR) if (combined) { return(geneLR) } else { return(list(geneL = geneL, geneR = geneR)) } } checkGeneSymbol <- function(geneSet, geneIfo) { geneSet <- unique(geneSet[geneSet != ""]) genes_notOfficial <- geneSet[geneSet %in% geneIfo$Symbol == "FALSE"] if (length(genes_notOfficial) > 0) { cat("Issue identified!! Please check the official Gene Symbol of the following genes: ", "\n", genes_notOfficial, "\n") } return(FALSE) }
CalcResD.fun <- function(mlePP, h=NULL, nint=NULL,lint=NULL, typeRes=NULL,modSim='FALSE') { n<-length(mlePP@lambdafit) inddat<-mlePP@inddat inddat[inddat==0]<-NA posE<-mlePP@posE if (is.null(h)) { h<-1/mlePP@lambdafit**0.5 typeRes<-'Pearson' } if (is.null(typeRes)) stop('Please indicate argument typeRes') if (!is.null(nint)& !is.null(lint)) stop('Error: only one of nint and lint must be supplied') if (is.null(nint)& is.null(lint)) stop('Error: one of nint and lint must be supplied') if (is.null(lint)) lint<-ceiling(n/nint) if (is.null(nint)) nint<-ceiling(n/(lint)) indice<-rep(0,n) indice[posE]<-1*h[posE] indice<-indice*inddat indiceR<-rep(0,n) indiceR[posE]<-1 indiceR<-indiceR*inddat lambdafit<-mlePP@lambdafit*h*inddat lambdafitR<-mlePP@lambdafit*inddat int<-floor(c(0:(n-1))/lint) emplambda<-tapply(indice, INDEX=int, FUN=mean, na.rm = TRUE) emplambdaR<-tapply(indiceR, INDEX=int, FUN=mean, na.rm = TRUE) sumalfit<-tapply(lambdafit, INDEX=int, FUN=mean, na.rm = TRUE) sumalfitR<-tapply(lambdafitR, INDEX=int, FUN=mean, na.rm = TRUE) lintV<-tapply(inddat, INDEX=int, FUN=sum, na.rm=TRUE) ultlint<-n-(nint-1)*lint pm1<-floor(lint/2) pm<-pm1+c(0,cumsum(rep(lint,(nint-2))) ) pm<-c(pm, pm[length(pm)]+ceiling(ultlint/2)) if (modSim==FALSE) { cat(fill=T) cat('Number of intervals to calculate the disjoint residuals: ', nint, ' of length: ',lint, fill=T) if(lint*nint!=n) cat(' except the las one of length ',ultlint, fill=T) cat(fill=T) } ScaRes<-emplambda-sumalfit RawRes<-emplambdaR-sumalfitR return(list(RawRes=RawRes,ScaRes=list(ScaRes=ScaRes,typeRes=typeRes), emplambda=emplambdaR,fittedlambda=sumalfitR, lintV=lintV,nint=nint, lint=lint,pm=pm,typeI='Disjoint',h=h,mlePP=mlePP)) }
qat_plot_lim_rule_dynamic_2d <- function(flagvector, filename, measurement_vector=NULL, min_vector=NULL, max_vector=NULL, min_vector_name=NULL, max_vector_name=NULL, measurement_name="", directoryname="", plotstyle=NULL) { if (is.null(plotstyle)) { plotstyle<-qat_style_plot() } path <- paste(directoryname,filename,".png", sep="") png(filename=path,width=800,height=600, pointsize=12, bg=plotstyle$basecolor) par(font.lab=2,oma=c(0,0,2,0), mar=c(5.1,5.1,5.1,8), font=2) image(1:dim(flagvector)[1], 1:dim(flagvector)[2], flagvector, col=c(plotstyle$plotcolormain,plotstyle$plotcolorbackground,plotstyle$plotcolorminor), xlab="", ylab="", col.lab=plotstyle$fontcolor, col.main=plotstyle$fontcolor, col.sub=plotstyle$fontcolor,fg=plotstyle$frontcolor, col.axis=plotstyle$fontcolor, font.axis=2, zlim=c(-1,1)) title(main=list("LIM-Rule dynamic", col=plotstyle$fontcolor), outer=TRUE) if (length(min_vector_name) != 0) { bordertext <- paste("Minimum vector: ", min_vector_name, " ") } else { bordertext<- "" } bordertext2<- paste("Minimum errors: ",length(which(flagvector==-1)), " ") bordertext2<- paste(bordertext2,"Maximum errors: ",length(which(flagvector==1))) if (length(max_vector_name) != 0) { bordertext <- paste(bordertext,"Maximum vector: ", max_vector_name) } else { bordertext<- paste(bordertext,"") } if (bordertext != "") { mtext(bordertext, side=3, line=2, font=2, col=plotstyle$fontcolor) mtext(bordertext2, side=3, line=1, font=2, col=plotstyle$fontcolor) } if(measurement_name != "") { bordertext3<-paste("Data: ",measurement_name, sep="") mtext(bordertext3, side=3, line=3, font=2, col=plotstyle$fontcolor) } image.plot(1:dim(flagvector)[1], 1:dim(flagvector)[2], flagvector, col=c(plotstyle$plotcolormain,plotstyle$plotcolorbackground,plotstyle$plotcolorminor), xlab="", ylab="", col.lab=plotstyle$fontcolor, col.main=plotstyle$fontcolor, col.sub=plotstyle$fontcolor,fg=plotstyle$frontcolor, col.axis=plotstyle$fontcolor, font.axis=2, legend.only=T, axis.args=list(at=c(-1,0,1), labels=c("min", "ok", "max"), font=2), zlim=c(-1,1)) dev.off() }
solve_system <- function (mpolyList) { pointer <- solve_system.(mpolyList) m2_structure( m2_name = m2_name(pointer), m2_class = "m2_solutions", m2_meta = list( sols = m2_pts_str_to_list(m2_meta(pointer, "ext_str")) ) ) } solve_system. <- function (mpolyList) { poly_str <- mpolyList_to_m2_str(mpolyList) var_str <- suppressMessages(paste0(vars(mpolyList), collapse=",")) m2_code <- sprintf(' needsPackage "PHCpack" R := CC[%s]; pts := solveSystem %s; for i in 0..( ', var_str, listify(poly_str)) m2.(m2_code) } mixed_volume <- function (mpolyList) { poly_str <- mpolyList_to_m2_str(mpolyList) var_str <- suppressMessages(paste0(vars(mpolyList), collapse=",")) m2_code <- sprintf(' needsPackage "PHCpack" R := CC[%s]; mixedVolume( %s ) ', var_str, listify(poly_str)) m2_meta(m2.(m2_code), "ext_str") } m2_pts_str_to_list <-function(m2_out) { m2_out <- str_sub(m2_out,2,-2) m2_out <- str_replace_all(m2_out, "p53", "") m2_out <- str_replace_all(m2_out, "\"", "") m2_out <- str_replace_all(m2_out, "toCC\\(", "complex(real=") m2_out <- str_replace_all(m2_out, ",complex", "Dcomplex") m2_out <- str_replace_all(m2_out, "\\},", "\\}") m2_out <- str_replace_all(m2_out, ",",",imaginary=") m2_out <- str_replace_all(m2_out, "Dcomplex", ",complex") m2_out <- str_replace_all(m2_out, "\\{", "c\\(") m2_out <- str_replace_all(m2_out, "\\}", "\\),") m2_out <- paste0("list(",str_sub(m2_out,0,-2),")") m2_out <- eval(parse(text=m2_out)) m2_out }
`num.Terms.tsm` <- function(object, ...)sum(object$model$AR, object$model$MA, object$seasonal$model$AR, object$seasonal$model$MA)
times_to_netcdf <- function(times, timeunit, outdir, filename) { dims <- list(time = ncdf4::ncdim_def( name = "time", units = timeunit, vals = times)) vars <- list(Y = ncdf4::ncvar_def( name = "Y", units = "kg", dim = dims, missval = NA)) nc <- ncdf4::nc_create( filename = file.path(outdir, filename), vars = vars) ncdf4::ncatt_put(nc, 0, "description", "strictly for testing") ncdf4::ncvar_put(nc, varid = vars[["Y"]], vals = rnorm(length(times))) ncdf4::nc_close(nc) } example_netcdf <- function(varnames, file_path) { n <- 365 dims <- list(x = ncdf4::ncdim_def( name = "time", units = "days since 2001-01-01", vals = seq_len(n) - 1 )) vars <- lapply(varnames, ncdf4::ncvar_def, units = "kg", dim = dims, missval = NA) names(vars) <- varnames nc <- ncdf4::nc_create(filename = file_path, vars = vars) on.exit(ncdf4::nc_close(nc), add = TRUE) ncdf4::ncatt_put(nc, 0, "description", "strictly for testing") for (v in varnames) { ncdf4::ncvar_put(nc, varid = vars[[v]], vals = rnorm(n)) } invisible(file_path) }
buildHeap <- function(heap, D, l) { for (ii in floor(l/2) : 1) { heap <- .Call("percDown", heap, D, as.integer(l), as.integer(ii), PACKAGE = "adjclust") } return(heap) }
glimem <- function(simData, sim0, sim1, family = binomial, link = "logit", nAGQ, control = glmerControl(optimizer = "bobyqa")){ m <- NULL n <- NULL simData$predMu = NULL simData$r = NULL coefficients = NULL rows = NULL for (i in sim0:sim1){ Datarows = which(simData$simulation == i) NewData <- simData[Datarows,] NewData <- within(NewData,{ dose <- factor(dose) Trial <- as.integer(Trial) n <- as.numeric(n) x <- as.numeric(x) }) m <- glmer(x/n ~ dose + (1|Trial), data = NewData, family = family, na.action = "na.fail", nAGQ = nAGQ, control = control, weights = n) coefficients <- coef(m) pred <- predict(m, type = "response") resid <- residuals(m, type = "pearson") simData[Datarows, "PredMu"] = pred simData[Datarows, "r"] = resid rows = c(rows, Datarows) } res <- list(m = m, coeff = coefficients, simData = simData[rows, ]) return(res) }
require(geometa, quietly = TRUE) require(sf) require(testthat) context("GMLRectifiedGrid") test_that("GMLRectifiedGrid",{ testthat::skip_on_cran() md <- GMLRectifiedGrid$new() m <- matrix(c(-180,180,-90, 90), nrow = 2, ncol = 2, byrow = TRUE, dimnames = list(c("x", "y"), c("min","max"))) md$setGridEnvelope(m = m) md$setAxisLabels(c("E", "N")) md$setOrigin(15,15) md$addOffsetVector(c(0,15)) xml <- md$encode() expect_is(xml, "XMLInternalNode") md2 <- GMLRectifiedGrid$new(xml = xml) xml2 <- md2$encode() expect_true(ISOAbstractObject$compare(md, md2)) })
calcAD <- function(ta,tr,vel,rh,clo,met,vAnkle){ tsv = calcPMV(ta=ta, tr=tr, vel=vel, rh=rh, clo=clo, met=met) ppdval = (exp(-2.58 + 3.05 * vAnkle - 1.06 * tsv)/(1 + exp(-2.58 + 3.05 * vAnkle -1.06 * tsv))) * 100 ppdval = round(ppdval,1) acceptability = ppdval <= 20 print(paste0("PMV value: ", round(tsv,3))) print(paste0("Ankle_draft_ppd: ", ppdval)) print(paste0("Acceptability: ", acceptability)) if (vel > 0.2) { warning('Velocity(vel) should be less than or equal to 0.2') } }
a <- function(x) { if (x <= 1) { 1 } else { 2 } } TestS4 <- setClass("TestS4", slots = list(name = "character", enabled = "logical")) setGeneric("print2", function(x, y) { }) setMethod("print2", c(x = "TestS4"), function(x) { 1 + 1 }) setMethod("print2", c(x = "TestS4", y = "character"), function(x, y) { 1 + 2 }) setMethod("show", c(object = "TestS4"), function(object) { 1 + 3 })
xgb.DMatrix.save <- function(dmatrix, fname) { if (typeof(fname) != "character") stop("fname must be character") if (!inherits(dmatrix, "xgb.DMatrix")) stop("dmatrix must be xgb.DMatrix") fname <- path.expand(fname) .Call(XGDMatrixSaveBinary_R, dmatrix, fname[1], 0L) return(TRUE) }
data_processing_mst <- function(dat, mstdesign, weights, precondition, cumulative){ cumulative_i <- probabilities_i <- y_i <- na_p <- items_i <- items_l <- minSolved_i <- minSolved_stage_i <- maxSolved_i <- maxSolved_stage_i <- cs_i <- rs_i <- rf_i <- vector("list", nrow(mstdesign)) preconpar <- preconnum <- NULL preconsize <- 0 if (!is.null(precondition)) { preconpar <- t(precondition[,grep("precondition",colnames(precondition)),drop=FALSE]) preconnum <- t(precondition[,grep("value",colnames(precondition)), drop = FALSE]) preconsize <- nrow(preconpar) } for (mst in seq_len(nrow(mstdesign))) { items_m <- as.list(strsplit(mstdesign[mst, "items"],";")[[1]]) cumulative_i[[mst]] <- rep(cumulative,length(items_m)) items_i[[mst]] <- match(unlist(strsplit(unlist(items_m),",")),colnames(dat)) - preconsize items_l[[mst]] <- lapply(strsplit(unlist(items_m),","),FUN = function(x){ match(x,colnames(dat)) - preconsize }) minSolved_i[[mst]] <- as.numeric(strsplit(mstdesign[mst, "minSolved"],";")[[1]]) minSolved_stage_i[[mst]] <- as.numeric(strsplit(mstdesign[mst, "minSolved_stage"],";")[[1]]) maxSolved_i[[mst]] <- as.numeric(strsplit(mstdesign[mst, "maxSolved"],";")[[1]]) maxSolved_stage_i[[mst]] <- as.numeric(strsplit(mstdesign[mst, "maxSolved_stage"],";")[[1]]) probabilities_i[[mst]] <- unlist(lapply(strsplit(mstdesign[mst, "probability"],";")[[1]],FUN = function(x) as.numeric(strsplit(x,",")[[1]]))) na_p[[mst]] <- rowSums(!is.na(dat[,items_i[[mst]] + preconsize]))==length(items_i[[mst]]) if (!is.null(precondition)) { preconsub <- paste0("dat[,'", preconpar[,mst],"']", "==", preconnum[,mst], collapse="&") na_p[[mst]] <- na_p[[mst]] & eval(parse(text = preconsub)) } y_i[[mst]] <- dat[na_p[[mst]], items_i[[mst]] + preconsize, drop = FALSE] weights_i <- weights[na_p[[mst]]] cs_i[[mst]] <- colSums(y_i[[mst]] * weights_i) rs_i[[mst]] <- rowSums(y_i[[mst]]) rf_i[[mst]] <- as.vector(tapply(weights_i, factor(rs_i[[mst]], levels = 0:ncol(y_i[[mst]])), sum)) rf_i[[mst]][is.na(rf_i[[mst]])] <- 0 } res <- list( y_i = y_i, na_p = na_p, items_i = items_i, items_l = items_l, minSolved_i = minSolved_i, minSolved_stage_i = minSolved_stage_i, maxSolved_i = maxSolved_i, maxSolved_stage_i = maxSolved_stage_i, cs_i = cs_i, rs_i = rs_i, rf_i = rf_i, probabilities_i = probabilities_i, cumulative_i = cumulative_i ) return(res) }
context("Check multinomial TS functions") data(rodents) lda_data <- rodents$document_term_table lda <- LDA_set(lda_data, c(4), nseeds = 1, list(quiet = TRUE)) dct <- rodents$document_covariate_table mts_data <- data.frame(dct) mts_data$gamma <- lda[[1]]@gamma timename <- "newmoon" test_that("check packaging of chunk fits", { TS_chunk_memo <- memoise_fun(multinom_TS_chunk, TRUE) chunks <- prep_chunks(data = mts_data, changepoints = c(20,50), timename = timename) nchunks <- nrow(chunks) fits <- vector("list", length = nchunks) for (i in 1:nchunks){ fits[[i]] <- TS_chunk_memo(data = mts_data, formula = gamma ~ 1, chunk = chunks[i, ], timename = timename, weights = NULL) } packaged <- package_chunk_fits(chunks, fits) expect_is(packaged, "multinom_TS_fit") expect_equal(round(packaged$logLik, 2), -516.58) }) test_that("check logLik for multinom_TS_fit", { mts <- multinom_TS(data = mts_data, formula = gamma~1, changepoints = c(20,50), timename = "newmoon", weights = NULL) expect_is(logLik(mts), "logLik") expect_equal(round(as.numeric(logLik(mts))), -517) }) test_that("check good output from multinom_TS", { mts <- multinom_TS(data = mts_data, formula = gamma~1, changepoints = c(20,50), timename = "newmoon", weights = NULL) expect_is(mts, "list") expect_is(mts, "multinom_TS_fit") expect_equal(length(mts), 3) expect_equal(names(mts), c("chunk models", "logLik", "chunks")) expect_equal(length(mts$"chunk models"), 3) expect_is(mts$logLik, "numeric") }) test_that("check check_changepoints", { expect_silent(check_changepoints()) expect_silent(check_changepoints(1)) expect_error(check_changepoints("ok")) expect_error(check_changepoints(0.3)) }) test_that("check failed output from multinom_TS", { mts <- multinom_TS(data = mts_data, formula = gamma~1, changepoints = c(50,40), timename = "newmoon", weights = NULL) expect_is(mts, "list") expect_equal(length(mts), 3) expect_equal(names(mts), c("chunk models", "logLik", "chunks")) expect_equal(mts$"chunk models", NA) expect_equal(mts$logLik, -Inf) }) test_that("check bad change point location catching of verify_changepoint_locations", { expect_equal(verify_changepoint_locations(mts_data, -1, "newmoon"), FALSE) expect_equal(verify_changepoint_locations(mts_data, 1e5, "newmoon"), FALSE) expect_equal(verify_changepoint_locations(mts_data, NULL, "newmoon"), TRUE) expect_equal(verify_changepoint_locations(mts_data, 100, "newmoon"), TRUE) expect_equal(verify_changepoint_locations( mts_data, c(10, 50, 100), "newmoon"), TRUE) }) test_that("check memoization of multinom_TS_chunk", { expect_is(memoise_fun(multinom_TS_chunk, TRUE), "memoised") }) chunk <- data.frame(start = 0, end = 40) test_that("check multinom_TS_chunk", { expect_is(multinom_TS_chunk(mts_data, "gamma ~ 1", chunk, timename, NULL), "multinom") }) test_that("check memoised multinom_TS_chunk", { multinom_TS_chunk_memo <- memoise_fun(multinom_TS_chunk, TRUE) expect_is( multinom_TS_chunk_memo(mts_data, "gamma ~ 1", chunk, timename), "multinom") }) test_that("check prepping of chunks", { expect_is(prep_chunks(mts_data, NULL, "newmoon"), "data.frame") expect_equal(prep_chunks(mts_data, NULL, "newmoon")$start, 1) expect_equal(prep_chunks(mts_data, NULL, "newmoon")$end, 467) expect_equal(prep_chunks(mts_data, c(10), "newmoon")$start, c(1, 11)) expect_equal(prep_chunks(mts_data, c(10), "newmoon")$end, c(10, 467)) })
MODIStsp_addindex <- function( new_indexbandname = "", new_indexfullname = "", new_indexformula = "", new_indexnodata_out = "32767") { indexes_file <- (system.file("ExtData", "MODIStsp_indexes.json", package = "MODIStsp")) prod_opt_list <- load_prodopts() n_products <- length(prod_opt_list) refbands_names <- c("b1_Red", "b2_NIR", "b3_Blue", "b4_Green", "b5_SWIR", "b6_SWIR", "b7_SWIR") avail_refbands <- refbands_names catch_err <- check_formula_errors(new_indexbandname, new_indexfullname, new_indexformula, prod_opt_list, refbands_names, avail_refbands) if (catch_err == 0) { save_formula(refbands_names, req_bands = attr(catch_err, "req_bands"), new_indexbandname, new_indexfullname, new_indexformula, new_indexnodata_out, prod_opt_list) message("The new Index was correctly added!\n It will be available at ", "the next execution of MODIStsp().") } else if (catch_err == 1) { stop("The formula of the new index is wrong or not computable. ", "Please check it.\n", "(Valid band names are: ", paste(avail_refbands, collapse = ", "), ".") } else if (catch_err == 2) { stop("The index acronym and/or full name are already present;\n", "Please specify different ones.") } else if (catch_err == 3) { stop("Some parameters are still blank; please provide valid values for\n", "the index name, the index fullname and the formula.") } } save_formula <- function(refbands_names, req_bands, new_indexbandname, new_indexfullname, new_indexformula, new_indexnodata_out, prod_opt_list) { indexes_file <- system.file("ExtData", "MODIStsp_indexes.json", package = "MODIStsp") if (file.exists(indexes_file)) { custom_indexes <- jsonlite::read_json(indexes_file) } if (length(custom_indexes) == 1) { custom_indexes <- NULL } if (is.null(custom_indexes)) { custom_indexes <- list() for (prod in names(prod_opt_list)) { custom_indexes[[prod]] <- list() for (vers in names(prod_opt_list[[prod]])) { custom_indexes[[prod]][[vers]] <- list( "indexes_bandnames" = character(0), "indexes_fullnames" = character(0), "indexes_formulas" = character(0), "indexes_nodata_out" = character(0) ) } } } for (prod in names(prod_opt_list)) { for (vers in names(prod_opt_list[[prod]])) { check <- 0 current_custindexes <- as.list(custom_indexes[[prod]][[vers]]) for (reqband in refbands_names[req_bands]) { if (reqband %in% prod_opt_list[[prod]][[vers]]$bandnames) { check <- check + 1 } } n_req_bands <- sum(req_bands) if (n_req_bands == check) { tmp_indexes_bandnames <- c(current_custindexes$indexes_bandnames, new_indexbandname) tmp_indexes_fullnames <- c(current_custindexes$indexes_fullnames, new_indexfullname) tmp_indexes_formulas <- c(current_custindexes$indexes_formulas, new_indexformula) tmp_indexes_nodata_out <- c(current_custindexes$indexes_nodata_out, new_indexnodata_out) custom_indexes[[prod]][[vers]] <- list( "indexes_bandnames" = tmp_indexes_bandnames, "indexes_fullnames" = tmp_indexes_fullnames, "indexes_formulas" = tmp_indexes_formulas, "indexes_nodata_out" = tmp_indexes_nodata_out ) rm(tmp_indexes_bandnames, tmp_indexes_fullnames, tmp_indexes_formulas, tmp_indexes_nodata_out) } else { } } } jsonlite::write_json(custom_indexes, indexes_file, pretty = TRUE, auto_unbox = TRUE) return(custom_indexes) }
html_name <- function(x) { xml_name(x) } html_attr <- function(x, name, default = NA_character_) { xml_attr(x, name, default = default) } html_attrs <- function(x) { xml_attrs(x) } html_children <- function(x) { xml_children(x) }
dev.off.crop <- function(file=NULL, warn=TRUE, ...) { dev.off(...) if(!is.null(file)) { if(.Platform$OS.type != "unix") { if(warn) warning("dev.off.crop() only works on Unix(-like) systems; no cropping is done.") } else { f <- file.path(getwd(), file) file.ext <- file_ext(file) file.ext.low <- tolower(file.ext) switch(file.ext.low, "ps" =, "eps" = { if(!command.exists("epstool")) { if(warn) warning("Command 'epstool' for cropping PS files not found; no cropping is done.") } else { f. <- add_to_name(f, s="_crop") system(paste("epstool --copy --bbox --quiet", f, f., "1>/dev/null 2>&1; mv", f., f)) } }, "pdf" = { if(!command.exists("pdfcrop")) { if(warn) warning("Command 'pdfcrop' for cropping PDF files not found; no cropping is done.") } else { system(paste("pdfcrop --pdftexcmd pdftex", f, f, "1>/dev/null 2>&1")) } }, "png" = { if(!command.exists("mogrify")) { if(warn) warning("Command 'mogrify' for cropping PNG files not found; no cropping is done.") } else { system(paste("mogrify -trim", f, f, "1>/dev/null 2>&1")) } }, stop("Non-supported file extension.")) } } invisible() }
lr.twosigma_custom<-function(count_matrix,mean_form_alt,zi_form_alt,mean_form_null,zi_form_null ,id,lr.df,return_full_fits=TRUE, disp_covar=NULL ,weights=rep(1,ncol(count_matrix)) ,control = glmmTMBControl(),ncores=1,cluster_type="Fork",chunk_size=10,lb=FALSE,internal_call=FALSE) { passed_args <- names(as.list(match.call())[-1]) required_args<-c("count_matrix","mean_form_alt","zi_form_alt","mean_form_null","zi_form_null","id","lr.df") if (any(!required_args %in% passed_args)) { stop(paste("Argument(s)",paste(setdiff(required_args, passed_args), collapse=", "),"missing and must be specified.")) } if(!is.matrix(count_matrix)){stop("Please ensure the input count_matrix is of class matrix.")} if(length(id)!=ncol(count_matrix)){stop("Argument id should be a numeric vector with length equal to the number of columns of count_matrix (i.e. the number of cells).")} ngenes<-nrow(count_matrix) genes<-rownames(count_matrix) if(is.null(genes)){genes<-1:ngenes} sum_fit_alt<-vector('list',length=ngenes) sum_fit_null<-vector('list',length=ngenes) if(return_full_fits==TRUE){ fits_all_null<-vector('list',length=ngenes) fits_all_alt<-vector('list',length=ngenes) } fit_lr<-function(chunk,id){ k<-0 num_err=0 f_n<-vector('list',length=length(chunk)) f_a<-vector('list',length=length(chunk)) gene_err<-rep(NA,length(chunk)) logLik<-rep(NA,length(chunk)) LR_stat<-rep(NA,length=length(chunk)) p.val<-rep(NA,length=length(chunk)) for(l in unlist(chunk)){ k<-k+1 count<-count_matrix[l,,drop=FALSE] check_twosigma_custom_input(count,mean_form_alt,zi_form_alt,id,disp_covar) check_twosigma_custom_input(count,mean_form_null,zi_form_null,id,disp_covar) count<-as.numeric(count) if(is.null(disp_covar)){ disp_form<- ~1 }else{ if(is.atomic(disp_covar)&length(disp_covar)==1){ if(disp_covar==0){stop("Invalid dispersion covariate option")}else{ if(disp_covar==1){ disp_form<-~1 }else{ stop("Invalid dispersion covariate option") } } } } if(is.null(disp_form)){ disp_form<- ~ disp_covar} formulas_alt<-list(mean_form=mean_form_alt,zi_form=zi_form_alt,disp_form=disp_form) formulas_null<-list(mean_form=mean_form_null,zi_form=zi_form_null,disp_form=disp_form) tryCatch({ fit_alt<-glmmTMB(formula=formulas_alt$mean_form ,ziformula=formulas_alt$zi_form ,weights=weights ,dispformula = formulas_alt$disp_form ,family=nbinom2,verbose = F ,control = control) fit_null<-glmmTMB(formula=formulas_null$mean_form ,ziformula=formulas_null$zi_form ,weights=weights ,dispformula = formulas_null$disp_form ,family=nbinom2,verbose = F ,control = control) tryCatch({ LR_stat[k]<- as.numeric(-2*(summary(fit_null)$logLik-summary(fit_alt)$logLik)) if(!is.na(LR_stat[k])& (LR_stat[k]<0 | (!fit_alt$sdr$pdHess) | (!fit_null$sdr$pdHess) |is.na(fit_alt$logLik)|is.na(fit_null$logLik))){ LR_stat[k]<-NA}},error=function(e){}) p.val[k]<-1-pchisq(LR_stat[k],df=lr.df) if(return_full_fits==TRUE){ f_n[[k]]<-fit_null f_a[[k]]<-fit_alt }else{ tryCatch({ f_n[[k]]<-summary(fit_null) f_a[[k]]<-summary(fit_alt) }) }},error=function(e){}) } return(list(fit_null=f_n,fit_alt=f_a,p.val=p.val,LR_stat=LR_stat)) } size=chunk_size chunks<-split(1:ngenes,ceiling(seq_along(genes)/size)) nchunks<-length(chunks) cl=NULL if(cluster_type=="Sock" & ncores>1){ cl<-parallel::makeCluster(ncores) registerDoParallel(cl) vars<-unique(c(all.vars(mean_form_alt)[-1],all.vars(zi_form_alt) ,all.vars(mean_form_null)[-1],all.vars(zi_form_null))) clusterExport(cl,varlist=vars,envir=environment()) } if(cluster_type=="Fork"&ncores>1){ cl<-parallel::makeForkCluster(ncores,outfile="") registerDoParallel(cl) } if(internal_call==FALSE){ print("Running Gene-Level Models") pboptions(type="timer") if(lb==TRUE){pboptions(use_lb=TRUE)} a<-pblapply(chunks,FUN=fit_lr,id=id,cl=cl) if(ncores>1){parallel::stopCluster(cl)} }else{ a<-lapply(chunks,FUN=fit_lr,id=id) } fit_null<-do.call(c,sapply(a,'[',1)) fit_alt<-do.call(c,sapply(a,'[',2)) p.val<-unlist(sapply(a,'[',3)) LR_stat<-unlist(sapply(a,'[',4)) names(p.val)<-genes names(LR_stat)<-genes names(fit_null)<-genes names(fit_alt)<-genes return(list(fit_null=fit_null,fit_alt=fit_alt,LR_stat=LR_stat,LR_p.val=p.val)) }
test.gsq <- function(observed,expected){ gsq <- 0 obs <- as.matrix(observed,rownames.force=T) exp <- as.matrix(expected,rownames.force=T) r <- nrow(obs) count <- 1 while(count <= r){ for(s in count:r){ if((exp[s,count] == 0) || (obs[s,count] == 0)){ gsq <- gsq } if((exp[s,count] != 0) && (obs[s,count] != 0)){ gsq <- gsq + 2*obs[s,count]*log(obs[s,count]/exp[s,count]) } } count <- count + 1 } return(gsq) }
NULL Surv <- survival::Surv ns <- splines::ns bs <- splines::bs .onLoad <- function(libname, pkgname) { rjags::load.module("glm", quiet = TRUE) } .onAttach <- function(libname, pkgname) { packageStartupMessage( "Please report any bugs to the package maintainer (https://github.com/NErler/JointAI/issues)." ) } utils::globalVariables(c("i", "value", "chain", "iteration")) NULL
getWall <- function(owner_id='', domain='', offset='', count='', filter='owner', extended='', fields='', v=getAPIVersion()) { .Deprecated("getWallExecute()") query <- queryBuilder('wall.get', owner_id = owner_id, domain = domain, offset = offset, count = count, filter = filter, extended = extended, fields = fields, v = v) request_delay() response <- jsonlite::fromJSON(query) if (has_error(response)) return(try_handle_error(response)) response$response } getWallExecute <- function(owner_id='', domain='', offset=0, count=10, filter='owner', extended='', fields='', use_db=FALSE, db_params=list(), progress_bar=FALSE, v=getAPIVersion()) { get_posts2500 <- function(owner_id='', domain='', offset=0, max_count='', filter='owner', extended='', fields='', v=getAPIVersion()) { if (max_count > 2500) max_count <- 2500 if (max_count <= 100) { execute(paste0('return API.wall.get({"owner_id":"', owner_id, '", "domain":"', domain, '", "offset":"', offset, '", "count":"', max_count, '", "filter":"', filter, '", "extended":"', extended, '", "v":"', v, '"}).items;')) } else { code <- 'var wall_records = [];' code <- paste0(code, 'wall_records = wall_records + API.wall.get({"owner_id":"', owner_id, '", "domain":"', domain, '", "offset":"', offset, '", "count":"', 100, '", "filter":"', filter, '", "extended":"', extended, '", "v":"', v, '"}).items;') code <- paste0(code, 'var offset = 100 + ', offset, '; var count = 100; var max_offset = offset + ', max_count, '; while (offset < max_offset && wall_records.length <= offset && offset-', offset, '<', max_count, ') { if (', max_count, ' - wall_records.length < 100) { count = ', max_count, ' - wall_records.length; }; wall_records = wall_records + API.wall.get({"owner_id":"', owner_id, '", "domain":"', domain, '", "offset":offset, "count":count, "filter":"', filter, '", "extended":"', extended, '", "v":"', v, '"}).items; offset = offset + 100; }; return wall_records;') execute(code) } } code <- paste0('return API.wall.get({"owner_id":"', owner_id, '", "domain":"', domain, '", "offset":"', offset, '", "count":"', 1, '", "filter":"', filter, '", "extended":"', extended, '", "v":"', v, '"});') response <- execute(code) posts <- response$items max_count <- ifelse((response$count - offset) > count & count != 0, count, response$count - offset) if (max_count == 0) return(list(posts = response$items, count = response$count)) if (use_db) { collection <- or(db_params[['collection']], or(domain, owner_id)) suffix <- or(db_params[['suffix']], 'wall') key <- or(db_params[['key']], 'id') if (collection_exists(collection, suffix)) db_update(object = posts, key = key, collection = collection, suffix = suffix, upsert = TRUE) else db_save(object = posts, collection = collection, suffix = suffix) } if (progress_bar) { pb <- txtProgressBar(min = 0, max = max_count, style = 3) setTxtProgressBar(pb, nrow(posts)) } num_records <- max_count - nrow(posts) while (nrow(posts) < max_count) { tryCatch({ posts2500 <- get_posts2500(owner_id = owner_id, domain = domain, filter = filter, extended = extended, fields = fields, max_count = num_records, offset = offset + nrow(posts), v = v) if (use_db) db_update(object = posts2500, key = key, collection = collection, suffix = suffix, upsert = TRUE) posts <- jsonlite::rbind_pages(list(posts, posts2500)) num_records <- ifelse((max_count - nrow(posts)) > num_records, num_records, max_count - nrow(posts)) }, vk_error13 = function(e) { num_records <<- as.integer(num_records / 2) warning(simpleWarning(paste0('Parameter "count" was tuned: ', num_records, ' per request.'))) }) if (progress_bar) setTxtProgressBar(pb, nrow(posts)) } if (progress_bar) close(pb) wall <- list(posts = posts, count = response$count) class(wall) <- c(class(wall), "posts.list") return(wall) } wallSearch <- function(owner_id='', domain='', query='', owners_only='', count='20', offset='0', extended='', fields='', v=getAPIVersion()) { query <- queryBuilder('wall.search', owner_id = owner_id, domain = domain, query = query, owners_only = owners_only, count = count, offset = offset, extended = extended, fields = fields, v = v) request_delay() response <- jsonlite::fromJSON(query) if (has_error(response)) return(try_handle_error(response)) response$response } wallGetById <- function(posts='', extended='', copy_history_depth='', fields='', v=getAPIVersion()) { query <- queryBuilder('wall.getById', posts = posts, extended = extended, copy_history_depth = copy_history_depth, fields = fields, v = v) request_delay() response <- jsonlite::fromJSON(query) if (has_error(response)) return(try_handle_error(response)) response$response } wallGetReposts <- function(owner_id='', post_id='', offset='', count='20', v=getAPIVersion()) { query <- queryBuilder('wall.getReposts', owner_id = owner_id, post_id = post_id, offset = offset, count = count, v = v) request_delay() response <- jsonlite::fromJSON(query) if (has_error(response)) return(try_handle_error(response)) response$response } wallGetComments <- function(owner_id='', post_id='', need_likes='', start_comment_id='', offset='', count='10', sort='', preview_length='0', extended='', v=getAPIVersion()) { query <- queryBuilder('wall.getComments', owner_id = owner_id, post_id = post_id, need_likes = need_likes, start_comment_id = start_comment_id, offset = offset, count = count, sort = sort, preview_length = preview_length, extended = extended, v = v) request_delay() response <- jsonlite::fromJSON(query) if (has_error(response)) return(try_handle_error(response)) response$response } postGetComments <- function(owner_id='', post_id='', need_likes=1, start_comment_id='', offset=0, count=10, sort='', preview_length=0, extended='', progress_bar = FALSE, v=getAPIVersion()) { get_comments2500 <- function(owner_id='', post_id='', need_likes=1, start_comment_id='', offset=0, max_count='', sort='', preview_length=0, extended='', v=getAPIVersion()) { if (max_count > 2500) max_count <- 2500 if (max_count <= 100) { execute(paste0('return API.wall.getComments({ "owner_id":"', owner_id, '", "post_id":"', post_id, '", "count":"', max_count, '", "offset":"', offset, '", "need_likes":"', need_likes, '", "start_comment_id":"', start_comment_id, '", "sort":"', sort, '", "preview_length":"', preview_length, '", "extended":"', extended, '", "v":"', v, '"}).items;')) } else { code <- 'var comments = [];' code <- paste0(code, 'comments = comments + API.wall.getComments({ "owner_id":"', owner_id, '", "post_id":"', post_id, '", "count":"', 100, '", "offset":"', offset, '", "need_likes":"', need_likes, '", "start_comment_id":"', start_comment_id, '", "sort":"', sort, '", "preview_length":"', preview_length, '", "extended":"', extended, '", "v":"', v, '"}).items;') code <- paste0(code, 'var offset = 100 + ', offset, '; var count = 100; var max_offset = offset + ', max_count, '; while (offset < max_offset && comments.length <= offset && offset-', offset, '<', max_count, ') { if (', max_count, ' - comments.length < 100) { count = ', max_count, ' - comments.length; }; comments = comments + API.wall.getComments({ "owner_id":"', owner_id, '", "post_id":"', post_id, '", "offset":offset, "count":count, "need_likes":"', need_likes, '", "start_comment_id":"', start_comment_id, '", "sort":"', sort, '", "preview_length":"', preview_length, '", "extended":"', extended, '", "v":"', v, '"}).items; offset = offset + 100; }; return comments;') execute(code) } } code <- paste0('return API.wall.getComments({ "owner_id":"', owner_id, '", "post_id":"', post_id, '", "count":"', 1, '", "offset":"', offset, '", "need_likes":"', need_likes, '", "start_comment_id":"', start_comment_id, '", "sort":"', sort, '", "preview_length":"', preview_length, '", "extended":"', extended, '", "v":"', v, '"});') response <- execute(code) comments <- response$items max_count <- ifelse((response$count - offset) > count & count != 0, count, response$count - offset) if (max_count == 0) return(list(comments = response$items, count = response$count)) offset_counter <- 0 if (progress_bar) { pb <- txtProgressBar(min = 0, max = max_count, style = 3) setTxtProgressBar(pb, nrow(comments)) } while (nrow(comments) < max_count) { tryCatch({ comments2500 <- get_comments2500(owner_id = owner_id, post_id = post_id, need_likes = need_likes, extended = extended, sort = sort, preview_length = preview_length, start_comment_id = start_comment_id, max_count = (max_count - nrow(comments)), offset = (1 + offset + offset_counter * 2500), v = v) comments <- jsonlite::rbind_pages(list(comments, comments2500)) offset_counter <- offset_counter + 1 }, error = function(e) { warning(e) }) if (progress_bar) setTxtProgressBar(pb, nrow(comments)) } if (progress_bar) close(pb) list(comments = comments, count = response$count) } wallGetCommentsList <- function(posts, progress_bar = FALSE, v = getAPIVersion()) { get_comments <- function(posts, v = getAPIVersion()) { num_requests <- ceiling(nrow(posts) / 25) from <- 1 to <- 25 comments <- list() for (i in 1:num_requests) { code <- 'var comments_per_post = {}; var comments;' if (to > nrow(posts)) to <- nrow(posts) for (index in from:to) { code <- paste0(code, 'comments = API.wall.getComments({ "owner_id":"', posts[index, ]$owner_id, '", "post_id":"', posts[index, ]$id, '", "need_likes":"', 1, '", "count":"', 100, '", "v":"', v, '"}).items; comments_per_post.post', posts[index, ]$id, "=comments;", sep = "") } code <- paste0(code, 'return comments_per_post;') comments <- append(comments, execute(code)) from <- from + 25 to <- to + 25 } obj_ids <- unlist(strsplit(names(comments), "post", fixed = T)) obj_ids <- as.integer(obj_ids[obj_ids != ""]) names(comments) <- obj_ids comments } if ("posts.list" %in% class(posts)) posts <- posts$posts cmt_groups <- split(posts, posts$comments$count > 100) posts_le100 <- cmt_groups[['FALSE']] posts_gt100 <- cmt_groups[['TRUE']] comments <- list() from <- 1 max_count <- nrow(posts_le100) to <- ifelse(max_count >= 75, 75, max_count) if (progress_bar) { pb <- txtProgressBar(min = 0, max = nrow(posts), style = 3) setTxtProgressBar(pb, 0) } repeat { comments75 <- get_comments(posts_le100[from:to, ], v) comments <- append(comments, comments75) if (progress_bar) setTxtProgressBar(pb, length(comments)) if (to >= max_count) break from <- to + 1 to <- ifelse(to + 75 >= max_count, max_count, to + 75) } if (!is.null(posts_gt100)) { for (i in 1:nrow(posts_gt100)) { owner_id <- posts_gt100$owner_id[i] post_id <- posts_gt100$id[i] comments[[paste0(post_id)]] <- postGetComments(owner_id = owner_id, post_id = post_id, count = 0, v = v)$comments if (progress_bar) setTxtProgressBar(pb, length(comments)) } } if (progress_bar) close(pb) comments_ordered <- list() for (i in 1:nrow(posts)) { comments_ordered[[paste0(posts$id[i])]] <- comments[[paste0(posts$id[i])]] } class(comments_ordered) <- c(class(comments_ordered), "vk.comments") comments_ordered } filterAttachments <- function(attachments, type) { if (!requireNamespace("plyr", quietly = TRUE)) { stop("plyr package needed for this function to work. Please install it.", .call = FALSE) } if (!is.character(type)) stop('type must be a character') filtered_attachments <- data.frame() for (i in 1:length(attachments)) { if (!is.null(attachments[[i]])) { for (j in 1:nrow(attachments[[i]])) { if (attachments[[i]][j, ]$type == type) { filtered_attachments <- plyr::rbind.fill(filtered_attachments, attachments[[i]][j, ][[type]]) } } } } filtered_attachments }
model_parameters.htest <- function(model, cramers_v = NULL, phi = NULL, standardized_d = NULL, hedges_g = NULL, omega_squared = NULL, eta_squared = NULL, epsilon_squared = NULL, cohens_g = NULL, rank_biserial = NULL, rank_epsilon_squared = NULL, kendalls_w = NULL, ci = .95, alternative = NULL, bootstrap = FALSE, verbose = TRUE, ...) { if (bootstrap) { stop("Bootstrapped h-tests are not yet implemented.") } else { parameters <- .extract_parameters_htest( model, cramers_v = cramers_v, phi = phi, standardized_d = standardized_d, hedges_g = hedges_g, omega_squared = omega_squared, eta_squared = eta_squared, epsilon_squared = epsilon_squared, cohens_g = cohens_g, rank_biserial = rank_biserial, rank_epsilon_squared = rank_epsilon_squared, kendalls_w = kendalls_w, ci = ci, alternative = alternative, verbose = verbose, ... ) } if (!is.null(parameters$Method)) { parameters$Method <- trimws(gsub("with continuity correction", "", parameters$Method)) } parameters$Alternative <- model$alternative parameters <- .add_htest_parameters_attributes(parameters, model, ci, ...) class(parameters) <- c("parameters_model", "see_parameters_model", class(parameters)) parameters } standard_error.htest <- function(model, ...) { NULL } p_value.htest <- function(model, ...) { model$p.value } model_parameters.pairwise.htest <- function(model, verbose = TRUE, ...) { m <- model$p.value parameters <- data.frame( Group1 = rep(rownames(m), each = ncol(m)), Group2 = rep(colnames(m), times = nrow(m)), p = as.numeric(t(m)), stringsAsFactors = FALSE ) parameters <- stats::na.omit(parameters) parameters <- .add_htest_attributes(parameters, model, p_adjust = model$p.adjust.method) class(parameters) <- c("parameters_model", "see_parameters_model", class(parameters)) parameters } .extract_parameters_htest <- function(model, cramers_v = NULL, phi = NULL, standardized_d = NULL, hedges_g = NULL, omega_squared = NULL, eta_squared = NULL, epsilon_squared = NULL, cohens_g = NULL, rank_biserial = NULL, rank_epsilon_squared = NULL, kendalls_w = NULL, ci = 0.95, alternative = NULL, verbose = TRUE, ...) { m_info <- insight::model_info(model, verbose = FALSE) if (m_info$is_correlation) { out <- .extract_htest_correlation(model) } else if (.is_levenetest(model)) { out <- .extract_htest_levenetest(model) } else if (m_info$is_ttest) { out <- .extract_htest_ttest(model) out <- .add_effectsize_ttest(model, out, standardized_d, hedges_g, ci = ci, alternative = alternative, verbose = verbose, ... ) } else if (m_info$is_ranktest) { out <- .extract_htest_ranktest(model) if (grepl("^Wilcox", model$method)) { out <- .add_effectsize_rankbiserial(model, out, rank_biserial, ci = ci, verbose = verbose, ... ) } if (grepl("^Kruskal", model$method)) { out <- .add_effectsize_rankepsilon(model, out, rank_epsilon_squared, ci = ci, verbose = verbose, ... ) } if (grepl("^Friedman", model$method)) { out <- .add_effectsize_kendalls_w(model, out, kendalls_w, ci = ci, verbose = verbose, ... ) } } else if (m_info$is_onewaytest) { out <- .extract_htest_oneway(model) out <- .add_effectsize_oneway( model, out, omega_squared, eta_squared, epsilon_squared, ci = ci, verbose = verbose ) } else if (m_info$is_chi2test) { out <- .extract_htest_chi2(model) if (grepl("^McNemar", model$method)) { out <- .add_effectsize_mcnemar(model, out, cohens_g = cohens_g, ci = ci, verbose = verbose ) } else { out <- .add_effectsize_chi2( model, out, cramers_v = cramers_v, phi = phi, ci = ci, alternative = alternative, verbose = verbose ) } } else if (m_info$is_proptest) { out <- .extract_htest_prop(model) } else if (m_info$is_binomtest) { out <- .extract_htest_binom(model) } else { stop("model_parameters not implemented for such h-tests yet.") } row.names(out) <- NULL out } .extract_htest_correlation <- function(model) { names <- unlist(strsplit(model$data.name, " (and|by) ")) out <- data.frame( "Parameter1" = names[1], "Parameter2" = names[2], stringsAsFactors = FALSE ) if (model$method == "Pearson's Chi-squared test") { out$Chi2 <- model$statistic out$df_error <- model$parameter out$p <- model$p.value } else if (grepl("Pearson", model$method, fixed = TRUE)) { out$r <- model$estimate out$t <- model$statistic out$df_error <- model$parameter out$p <- model$p.value out$CI_low <- model$conf.int[1] out$CI_high <- model$conf.int[2] } else if (grepl("Spearman", model$method, fixed = TRUE)) { out$rho <- model$estimate out$S <- model$statistic out$df_error <- model$parameter out$p <- model$p.value } else { out$tau <- model$estimate out$z <- model$statistic out$df_error <- model$parameter out$p <- model$p.value } out$Method <- model$method col_order <- c( "Parameter1", "Parameter2", "Parameter", "r", "rho", "tau", "CI_low", "CI_high", "t", "z", "S", "df_error", "p", "Method", "method" ) out <- out[col_order[col_order %in% names(out)]] out } .extract_htest_ranktest <- function(model) { if (grepl("design-based", tolower(model$method), fixed = TRUE)) { names <- gsub("~", "", unlist(strsplit(model$data.name, " + ", fixed = TRUE)), fixed = TRUE) out <- data.frame( "Parameter1" = names[1], "Parameter2" = names[2], "Statistic" = model$statistic[[1]], "df_error" = model$parameter[[1]], "Method" = model$method, "p" = model$p.value[[1]], stringsAsFactors = FALSE ) out$Method <- gsub("KruskalWallis", "Kruskal-Wallis", out$Method, fixed = TRUE) colnames(out)[colnames(out) == "Statistic"] <- names(model$statistic)[1] } else { if (grepl(" (and|by) ", model$data.name)) { names <- unlist(strsplit(model$data.name, " (and|by) ")) out <- data.frame( "Parameter1" = names[1], "Parameter2" = names[2], stringsAsFactors = FALSE ) } else { out <- data.frame( "Parameter" = model$data.name, stringsAsFactors = FALSE ) } if (grepl("Wilcoxon", model$method, fixed = TRUE)) { out$W <- model$statistic[[1]] out$df_error <- model$parameter[[1]] out$p <- model$p.value[[1]] } else if (grepl("Kruskal-Wallis", model$method, fixed = TRUE) || grepl("Friedman", model$method, fixed = TRUE)) { out$Chi2 <- model$statistic[[1]] out$df_error <- model$parameter[[1]] out$p <- model$p.value[[1]] } out$Method <- model$method } out } .extract_htest_levenetest <- function(model) { data.frame( "df" = model$Df[1], "df_error" = model$Df[2], `F` = model$`F value`[1], p = model$`Pr(>F)`[1], Method = "Levene's Test for Homogeneity of Variance", stringsAsFactors = FALSE ) } .extract_htest_ttest <- function(model, standardized_d = NULL, hedges_g = NULL) { if (grepl("design-based", tolower(model$method), fixed = TRUE)) { names <- unlist(strsplit(model$data.name, " ~ ")) out <- data.frame( "Parameter1" = names[1], "Parameter2" = names[2], "Difference" = model$estimate[[1]], "t" = model$statistic[[1]], "df_error" = model$parameter[[1]], "Method" = model$method, "p" = model$p.value[[1]], stringsAsFactors = FALSE ) out$Method <- gsub("KruskalWallis", "Kruskal-Wallis", out$Method, fixed = TRUE) colnames(out)[colnames(out) == "Statistic"] <- names(model$statistic)[1] } else { paired_test <- grepl("^Paired", model$method) && length(model$estimate) == 1 if (grepl(" and ", model$data.name) && isFALSE(paired_test)) { names <- unlist(strsplit(model$data.name, " and ", fixed = TRUE)) out <- data.frame( "Parameter1" = names[1], "Parameter2" = names[2], "Mean_Parameter1" = model$estimate[1], "Mean_Parameter2" = model$estimate[2], "Difference" = model$estimate[1] - model$estimate[2], "CI_low" = model$conf.int[1], "CI_high" = model$conf.int[2], "t" = model$statistic, "df_error" = model$parameter, "p" = model$p.value, "Method" = model$method, stringsAsFactors = FALSE ) attr(out, "mean_group_values") <- gsub("mean in group ", "", names(model$estimate), fixed = TRUE) } else if (isTRUE(paired_test)) { names <- unlist(strsplit(model$data.name, " (and|by) ")) out <- data.frame( "Parameter" = names[1], "Group" = names[2], "Difference" = model$estimate, "t" = model$statistic, "df_error" = model$parameter, "p" = model$p.value, "CI_low" = model$conf.int[1], "CI_high" = model$conf.int[2], "Method" = model$method, stringsAsFactors = FALSE ) } else if (grepl(" by ", model$data.name, fixed = TRUE)) { if (length(model$estimate) == 1) { names <- unlist(strsplit(model$data.name, " by ", fixed = TRUE)) out <- data.frame( "Parameter" = names[1], "Group" = names[2], "Difference" = model$estimate, "CI" = .95, "CI_low" = as.vector(model$conf.int[, 1]), "CI_high" = as.vector(model$conf.int[, 2]), "t" = model$statistic, "df_error" = model$parameter, "p" = model$p.value, "CI_low" = model$conf.int[1], "CI_high" = model$conf.int[2], "Method" = model$method, stringsAsFactors = FALSE ) } else { names <- unlist(strsplit(model$data.name, " by ", fixed = TRUE)) out <- data.frame( "Parameter" = names[1], "Group" = names[2], "Mean_Group1" = model$estimate[1], "Mean_Group2" = model$estimate[2], "Difference" = model$estimate[1] - model$estimate[2], "CI_low" = model$conf.int[1], "CI_high" = model$conf.int[2], "t" = model$statistic, "df_error" = model$parameter, "p" = model$p.value, "Method" = model$method, stringsAsFactors = FALSE ) attr(out, "mean_group_values") <- gsub("mean in group ", "", names(model$estimate), fixed = TRUE) } } else { out <- data.frame( "Parameter" = model$data.name, "Mean" = model$estimate, "mu" = model$null.value, "Difference" = model$estimate - model$null.value, "CI_low" = model$conf.int[1], "CI_high" = model$conf.int[2], "t" = model$statistic, "df_error" = model$parameter, "p" = model$p.value, "Method" = model$method, stringsAsFactors = FALSE ) } } attr(out, "htest_type") <- "ttest" out } .extract_htest_oneway <- function(model) { data.frame( "F" = model$statistic, "df" = model$parameter[1], "df_error" = model$parameter[2], "p" = model$p.value, "Method" = model$method, stringsAsFactors = FALSE ) } .extract_htest_chi2 <- function(model) { if (("observed" %in% names(model) && inherits(model$observed, "svytable")) || grepl("^svychisq", model$data.name)) { if (grepl("Pearson's X", model$method, fixed = TRUE)) { model$method <- gsub("(Pearson's X\\^2: )(.*)", "Pearson's Chi2 \\(\\2\\)", model$method) } if (names(model$statistic) == "F") { data.frame( "F" = model$statistic, "df" = model$parameter[1], "df_error" = model$parameter[2], "p" = model$p.value, "Method" = model$method, stringsAsFactors = FALSE ) } else { data.frame( "Chi2" = model$statistic, "df" = model$parameter, "p" = model$p.value, "Method" = model$method, stringsAsFactors = FALSE ) } } else { if (!is.null(model$estimate) && identical(names(model$estimate), "odds ratio")) { data.frame( "Odds Ratio" = model$estimate, "CI_low" = model$conf.int[1], "CI_high" = model$conf.int[2], "p" = model$p.value, "Method" = model$method, stringsAsFactors = FALSE, check.names = FALSE ) } else { data.frame( "Chi2" = model$statistic, "df" = model$parameter, "p" = model$p.value, "Method" = model$method, stringsAsFactors = FALSE ) } } } .extract_htest_prop <- function(model) { out <- data.frame( Proportion = paste0(insight::format_value(model$estimate, as_percent = TRUE), collapse = " / "), stringsAsFactors = FALSE ) if (length(model$estimate) == 2) { out$Difference <- insight::format_value( abs(model$estimate[1] - model$estimate[2]), as_percent = TRUE ) } if (!is.null(model$conf.int)) { out$CI_low <- model$conf.int[1] out$CI_high <- model$conf.int[2] } out$Chi2 <- model$statistic out$df <- model$parameter[1] out$Null_value <- model$null.value out$p <- model$p.value out$Method <- model$method out } .extract_htest_binom <- function(model) { out <- data.frame( "Probability" = model$estimate, "CI_low" = model$conf.int[1], "CI_high" = model$conf.int[2], "Success" = model$statistic, "Trials" = model$parameter, stringsAsFactors = FALSE ) out$Null_value <- model$null.value out$p <- model$p.value out$Method <- model$method out } .add_effectsize_chi2 <- function(model, out, cramers_v = NULL, phi = NULL, ci = .95, alternative = NULL, verbose = TRUE) { if (!requireNamespace("effectsize", quietly = TRUE) || (is.null(cramers_v) && is.null(phi))) { return(out) } if (!is.null(cramers_v)) { es <- effectsize::effectsize( model, type = "cramers_v", ci = ci, alternative = alternative, adjust = identical(cramers_v, "adjusted"), verbose = verbose ) es$CI <- NULL ci_cols <- grepl("^CI", names(es)) names(es)[ci_cols] <- paste0("Cramers_", names(es)[ci_cols]) out <- cbind(out, es) } if (!is.null(phi)) { es <- effectsize::effectsize( model, type = "phi", ci = ci, alternative = alternative, adjust = identical(phi, "adjusted"), verbose = verbose ) es$CI <- NULL ci_cols <- grepl("^CI", names(es)) names(es)[ci_cols] <- paste0("phi_", names(es)[ci_cols]) out <- cbind(out, es) } col_order <- c( "Chi2", "df", "df_error", "Cramers_v", "Cramers_v_adjusted", "Cramers_CI_low", "Cramers_CI_high", "phi", "phi_adjusted", "phi_CI_low", "phi_CI_high", "p", "Method", "method" ) out <- out[col_order[col_order %in% names(out)]] out } .add_effectsize_mcnemar <- function(model, out, cohens_g = NULL, ci = .95, verbose = TRUE) { if (is.null(cohens_g)) { return(out) } if (requireNamespace("effectsize", quietly = TRUE)) { es <- effectsize::effectsize(model, type = "cohens_g", ci = ci, verbose = verbose) es$CI <- NULL ci_cols <- grepl("^CI", names(es)) names(es)[ci_cols] <- paste0("Cohens_", names(es)[ci_cols]) out <- cbind(out, es) } col_order <- c( "Chi2", "df", "df_error", "Cohens_g", "g", "Cohens_CI_low", "Cohens_CI_high", "p", "Method", "method" ) out <- out[col_order[col_order %in% names(out)]] out } .add_effectsize_ttest <- function(model, out, standardized_d = NULL, hedges_g = NULL, ci = .95, alternative = NULL, verbose = TRUE, ...) { if (is.null(standardized_d) && is.null(hedges_g)) { return(out) } if (requireNamespace("effectsize", quietly = TRUE)) { if (!is.null(standardized_d)) { es <- effectsize::effectsize( model, type = "cohens_d", ci = ci, alternative = alternative, verbose = verbose, ... ) es$CI <- NULL ci_cols <- grepl("^CI", names(es)) names(es)[ci_cols] <- paste0("d_", names(es)[ci_cols]) out <- cbind(out, es) } if (!is.null(hedges_g)) { es <- effectsize::effectsize( model, type = "hedges_g", ci = ci, alternative = alternative, verbose = verbose, ... ) es$CI <- NULL ci_cols <- grepl("^CI", names(es)) names(es)[ci_cols] <- paste0("g_", names(es)[ci_cols]) out <- cbind(out, es) } } col_order <- c( "Parameter1", "Parameter2", "Parameter", "Group", "Mean_Parameter1", "Mean_Parameter2", "Mean_Group1", "Mean_Group2", "mu", "Difference", "CI_low", "CI_high", "t", "df_error", "d", "Cohens_d", "d_CI_low", "d_CI_high", "g", "Hedges_g", "g_CI_low", "g_CI_high", "p", "Method", "method" ) out <- out[col_order[col_order %in% names(out)]] out } .add_effectsize_rankbiserial <- function(model, out, rank_biserial = NULL, ci = .95, verbose = TRUE, ...) { if (is.null(rank_biserial)) { return(out) } if (requireNamespace("effectsize", quietly = TRUE)) { es <- effectsize::effectsize(model, type = "rank_biserial", ci = ci, verbose = verbose, ... ) es$CI <- NULL ci_cols <- grepl("^CI", names(es)) names(es)[ci_cols] <- paste0("rank_biserial_", names(es)[ci_cols]) out <- cbind(out, es) } col_order <- c( "Parameter1", "Parameter2", "Parameter", "W", "r_rank_biserial", "CI", "rank_biserial_CI_low", "rank_biserial_CI_high", "p", "Method", "method" ) out <- out[col_order[col_order %in% names(out)]] out } .add_effectsize_rankepsilon <- function(model, out, rank_epsilon_squared = NULL, ci = .95, verbose = TRUE, ...) { if (is.null(rank_epsilon_squared)) { return(out) } if (requireNamespace("effectsize", quietly = TRUE)) { es <- effectsize::effectsize(model, type = "rank_epsilon_squared", ci = ci, verbose = verbose, ... ) es$CI <- NULL ci_cols <- grepl("^CI", names(es)) names(es)[ci_cols] <- paste0("rank_epsilon_squared_", names(es)[ci_cols]) out <- cbind(out, es) } col_order <- c( "Parameter1", "Parameter2", "Parameter", "Chi2", "df_error", "rank_epsilon_squared", "CI", "rank_epsilon_squared_CI_low", "rank_epsilon_squared_CI_high", "p", "Method", "method" ) out <- out[col_order[col_order %in% names(out)]] out } .add_effectsize_kendalls_w <- function(model, out, kendalls_w = NULL, ci = .95, verbose = TRUE, ...) { if (is.null(kendalls_w)) { return(out) } if (requireNamespace("effectsize", quietly = TRUE)) { es <- effectsize::effectsize(model, type = "kendalls_w", ci = ci, verbose = verbose, ... ) es$CI <- NULL ci_cols <- grepl("^CI", names(es)) names(es)[ci_cols] <- paste0("Kendalls_W_", names(es)[ci_cols]) out <- cbind(out, es) } col_order <- c( "Parameter1", "Parameter2", "Parameter", "Chi2", "df_error", "Kendalls_W", "CI", "Kendalls_W_CI_low", "Kendalls_W_CI_high", "p", "Method", "method" ) out <- out[col_order[col_order %in% names(out)]] out } .add_effectsize_oneway <- function(model, out, omega_squared = NULL, eta_squared = NULL, epsilon_squared = NULL, ci = .95, verbose = TRUE) { if (is.null(omega_squared) && is.null(eta_squared) && is.null(epsilon_squared)) { return(out) } if (requireNamespace("effectsize", quietly = TRUE)) { if (!is.null(omega_squared)) { es <- effectsize::effectsize(model, ci = ci, type = "omega", partial = TRUE, verbose = verbose) es$CI <- NULL ci_cols <- grepl("^CI", names(es)) names(es)[ci_cols] <- paste0("Omega2_", names(es)[ci_cols]) out <- cbind(out, es) } if (!is.null(eta_squared)) { es <- effectsize::effectsize(model, ci = ci, type = "eta", partial = TRUE, verbose = verbose) es$CI <- NULL ci_cols <- grepl("^CI", names(es)) names(es)[ci_cols] <- paste0("Eta2_", names(es)[ci_cols]) out <- cbind(out, es) } if (!is.null(epsilon_squared)) { es <- effectsize::effectsize(model, ci = ci, type = "epsilon", partial = TRUE, verbose = verbose) es$CI <- NULL ci_cols <- grepl("^CI", names(es)) names(es)[ci_cols] <- paste0("Epsilon2_", names(es)[ci_cols]) out <- cbind(out, es) } } col_order <- c( "F", "df", "df_error", "Eta2", "Eta2_CI_low", "Eta2_CI_high", "Omega2", "Omega2_CI_low", "Omega2_CI_high", "Epsilon2", "Epsilon2_CI_low", "Epsilon2_CI_high", "p", "Method", "method" ) out <- out[col_order[col_order %in% names(out)]] out } .add_htest_parameters_attributes <- function(params, model, ci = 0.95, ...) { attr(params, "title") <- unique(params$Method) attr(params, "model_class") <- class(model) attr(params, "alternative") <- model$alternative if (!is.null(model$alternative)) { h1_text <- "Alternative hypothesis: " if (!is.null(model$null.value)) { if (length(model$null.value) == 1L) { alt.char <- switch(model$alternative, two.sided = "not equal to", less = "less than", greater = "greater than" ) h1_text <- paste0(h1_text, "true ", names(model$null.value), " is ", alt.char, " ", model$null.value) } else { h1_text <- paste0(h1_text, model$alternative) } } else { h1_text <- paste0(h1_text, model$alternative) } attr(params, "text_alternative") <- h1_text } dot.arguments <- lapply(match.call(expand.dots = FALSE)$`...`, function(x) x) if ("digits" %in% names(dot.arguments)) { attr(params, "digits") <- eval(dot.arguments[["digits"]]) } else { attr(params, "digits") <- 2 } if ("ci_digits" %in% names(dot.arguments)) { attr(params, "ci_digits") <- eval(dot.arguments[["ci_digits"]]) } else { attr(params, "ci_digits") <- 2 } if ("p_digits" %in% names(dot.arguments)) { attr(params, "p_digits") <- eval(dot.arguments[["p_digits"]]) } else { attr(params, "p_digits") <- 3 } attr(params, "ci") <- ci attr(params, "ci_test") <- attributes(model$conf.int)$conf.level if (!"CI" %in% colnames(params) && length(ci) == 1) { ci_pos <- grep("CI_low", colnames(params), fixed = TRUE) if (length(ci_pos)) { if (length(ci_pos) > 1) { ci_pos <- ci_pos[1] } params$CI <- ci a <- attributes(params) params <- params[c(1:(ci_pos - 1), ncol(params), ci_pos:(ncol(params) - 1))] attributes(params) <- utils::modifyList(a, attributes(params)) } } params } .add_htest_attributes <- function(params, model, p_adjust = NULL, verbose = TRUE, ...) { dot.arguments <- lapply(match.call(expand.dots = FALSE)$`...`, function(x) x) attr(params, "p_adjust") <- p_adjust attr(params, "model_class") <- class(model) attr(params, "title") <- params$Method if ("digits" %in% names(dot.arguments)) { attr(params, "digits") <- eval(dot.arguments[["digits"]]) } else { attr(params, "digits") <- 2 } if ("ci_digits" %in% names(dot.arguments)) { attr(params, "ci_digits") <- eval(dot.arguments[["ci_digits"]]) } else { attr(params, "ci_digits") <- 2 } if ("p_digits" %in% names(dot.arguments)) { attr(params, "p_digits") <- eval(dot.arguments[["p_digits"]]) } else { attr(params, "p_digits") <- 3 } if ("s_value" %in% names(dot.arguments)) { attr(params, "s_value") <- eval(dot.arguments[["s_value"]]) } params }
OptSpace <- function(A,ropt=NA,niter=50,tol=1e-6,showprogress=TRUE){ if (!is.matrix(A)){ stop("* OptSpace : an input A should be a matrix.") } if (any(is.infinite(A))){ stop("* OptSpace : no infinite value in A is allowed.") } if (!any(is.na(A))){ stop("* OptSpace : there is no unobserved values as NA.") } idxna = (is.na(A)) M_E = array(0,c(nrow(A),ncol(A))) M_E[!idxna] = A[!idxna] n = nrow(A) m = ncol(A) nnZ.E = sum(!idxna) E = array(0,c(nrow(A),ncol(A))); E[!idxna] = 1 eps = nnZ.E/sqrt(m*n) if (is.na(ropt)){ if (showprogress){ print("* OptSpace: Guessing an implicit rank.") } r = min(max(round(guess_rank(M_E,nnZ.E)), 2), m-1) if (showprogress){ print(paste0('* OptSpace: Guessing an implicit rank: Estimated rank : ',r)) } } else { r = round(ropt) if ((!is.numeric(r))||(r<1)||(r>m)||(r>n)){ stop("* OptSpace: ropt should be an integer in [1,min(nrow(A),ncol(A))].") } } if ((is.infinite(niter))||(niter<=1)||(!is.numeric(niter))){ stop("* OptSpace: invalid niter number.") } niter = round(niter) m0 = 10000 rho = 0 rescal_param = sqrt(nnZ.E*r/(norm(M_E,'f')^2)) M_E = M_E*rescal_param if (showprogress){ print("* OptSpace: Step 1: Trimming ...") } M_Et = M_E d = colSums(E) d_ = mean(d) for (col in 1:m){ if (sum(E[,col])>(2*d_)){ listed = which(E[,col]>0) p = sample(1:length(listed),length(listed)) M_Et[listed[p[ceiling(2*d_)]]:n,col] = 0 } } d = rowSums(E) d_ = mean(d) for (row in 1:n){ if (sum(E[row,])>2*d_){ listed = which(E[row,]>0) p = sample(1:length(listed),length(listed)) M_Et[row,listed[p[ceiling(2*d_)]]:m] = 0 } } if (showprogress){ print("* OptSpace: Step 2: SVD ...") } svdEt = svd(M_Et) X0 = svdEt$u[,1:r] S0 = diag(svdEt$d[1:r]) Y0 = svdEt$v[,1:r] if (showprogress){ print("* OptSpace: Step 3: Initial Guess ...") } X0 = X0*sqrt(n) Y0 = Y0*sqrt(m) S0 = S0/eps if (showprogress){ print("* OptSpace: Step 4: Gradient Descent ...") } X = X0 Y = Y0 S = aux_getoptS(X,Y,M_E,E) dist = array(0,c(1,(niter+1))) dist[1] = norm((M_E - (X%*%S%*%t(Y)))*E,'f')/sqrt(nnZ.E) for (i in 1:niter){ tmpgrad = aux_gradF_t(X,Y,S,M_E,E,m0,rho) W = tmpgrad$W Z = tmpgrad$Z t = aux_getoptT(X,W,Y,Z,S,M_E,E,m0,rho) X = X+t*W; Y = Y+t*Z; S = aux_getoptS(X,Y,M_E,E) dist[i+1] = norm(((M_E - X%*%S%*%t(Y))*E),'f')/sqrt(nnZ.E) if (showprogress){ pmsg=sprintf('* OptSpace: Step 4: Iteration %d: distortion: %e',i,dist[i+1]) } if (dist[i+1]<tol){ dist = dist[1:(i+1)] break } } S = S/rescal_param out = list() out$X = X out$S = S out$Y = Y out$dist = dist if (showprogress){ print('* OptSpace: estimation finished.') } return(out) }
vec_inc <- c(1:10) vec_dec<- c(10:1) vec_ran <- c(sample(1:10)) vec_flat <- rep.int(1,10) test_that("increasing correctly guesses", { expect_true(increasing(vec_inc)) expect_false(increasing(vec_dec)) expect_false(increasing(vec_ran)) expect_false(increasing(vec_flat)) expect_false(increasing(1)) }) test_that("decreasing correctly guesses", { expect_false(decreasing(vec_inc)) expect_true(decreasing(vec_dec)) expect_false(decreasing(vec_ran)) expect_false(decreasing(vec_flat)) expect_false(decreasing(1)) }) test_that("unvarying correctly guesses", { expect_false(unvarying(vec_inc)) expect_false(unvarying(vec_dec)) expect_false(unvarying(vec_ran)) expect_true(unvarying(vec_flat)) expect_false(unvarying(1)) }) test_that("monotonic correctly guesses", { expect_true(monotonic(vec_inc)) expect_true(monotonic(vec_dec)) expect_false(monotonic(vec_ran)) expect_false(monotonic(vec_flat)) expect_false(monotonic(1)) }) wages_monotonic <- wages %>% features(ln_wages, feat_monotonic) test_that("wages_monotonic produces output 0 or 1",{ expect_equal(max(rowSums(wages_monotonic[ , 2:4])), 1) expect_false(any(rowSums(wages_monotonic[ , 2:4]) > 1)) })
HierHe=function(x, nreg, r, ncode) { read.genepop1 <- function(file, ncode, quiet = FALSE) { adegenet::.readExt adegenet::.genlab adegenet::df2genind adegenet::is.genind adegenet::pop adegenet::repool adegenet::Hs adegenet::seppop adegenet::popNames if (toupper(.readExt(file)) != "GEN") stop("File extension .gen expected") if (!quiet) cat("\n Converting data from a Genepop .gen file to a genind object... \n\n") prevcall <- match.call() txt <- scan(file, sep = "\n", what = "character", quiet = TRUE) if (!quiet) cat("\nFile description: ", txt[1], "\n") txt <- txt[-1] txt <- gsub("\t", " ", txt) NA.char <- paste(rep("0", ncode), collapse = "") locinfo.idx <- 1:(min(grep("POP", toupper(txt))) - 1) locinfo <- txt[locinfo.idx] locinfo <- paste(locinfo, collapse = ",") loc.names <- unlist(strsplit(locinfo, "([,]|[\n])+")) loc.names <- trimws(loc.names) nloc <- length(loc.names) txt <- txt[-locinfo.idx] pop.idx <- grep("^([[:space:]]*)POP([[:space:]]*)$", toupper(txt)) npop <- length(pop.idx) nocomma <- which(!(1:length(txt)) %in% grep(",", txt)) splited <- nocomma[which(!nocomma %in% pop.idx)] if (length(splited) > 0) { for (i in sort(splited, decreasing = TRUE)) { txt[i - 1] <- paste(txt[i - 1], txt[i], sep = " ") } txt <- txt[-splited] } pop.idx <- grep("^([[:space:]]*)POP([[:space:]]*)$", toupper(txt)) txt[length(txt) + 1] <- "POP" nind.bypop <- diff(grep("^([[:space:]]*)POP([[:space:]]*)$", toupper(txt))) - 1 pop <- factor(rep(1:npop, nind.bypop)) txt <- txt[-c(pop.idx, length(txt))] temp <- sapply(1:length(txt), function(i) strsplit(txt[i], ",")) ind.names <- vapply(temp, function(e) e[1], character(1)) ind.names <- trimws(ind.names) vec.genot <- vapply(temp, function(e) e[2], character(1)) vec.genot <- trimws(vec.genot) X <- matrix(unlist(strsplit(vec.genot, "[[:space:]]+")), ncol = nloc, byrow = TRUE) if (any(duplicated(ind.names))) { rownames(X) <- .genlab("", nrow(X)) } else { rownames(X) <- ind.names } colnames(X) <- loc.names pop.names.idx <- cumsum(table(pop)) pop.names <- ind.names[pop.names.idx] levels(pop) <- pop.names if (!all(unique(nchar(X)) == (ncode * 2))) stop(paste("some alleles are not encoded with", ncode, "characters\nCheck 'ncode' argument")) res <- df2genind(X = X, pop = as.character(pop), ploidy = 2, ncode = ncode, NA.char = NA.char) res@call <- prevcall if (!quiet) cat("\n...done.\n\n") return(res) } genfiles = read.genepop1(x, ncode, quiet = TRUE) hierfstat::genind2hierfstat hfiles <- genind2hierfstat(genfiles) npops = length(levels(genfiles$pop)) nloci = length(levels(genfiles$loc.fac)) sampsize = summary(genfiles$pop) if (length(r) != nreg) stop("Number of regions should be equal to the number defined in the level") if (sum(r) != npops) stop("Number of pops should be equal to the number defined in level") rsample = list() for (i in 1:nreg) { rsample[[i]] = sum(sampsize[(sum(head(r, i - 1)) + 1):(sum(head(r, i)))]) } rsample = as.data.frame(rsample) rsample = as.numeric(unlist(rsample)) region = list() hierHr = list() hierHrperloc = list() for (i in seq_along(r)) { region[[i]] = list() region[[i]] = hfiles[(sum(head(rsample, i - 1)) + 1):(sum(head(rsample, i))), ] region[[i]]$pop = factor(region[[i]]$pop) hierHr[[i]] = list() hierHrperloc[[i]] = list() hierHr[[i]] = t(basic.stats(region[[i]], diploid = TRUE, digits = 4)$overall) hierHrperloc[[i]] = basic.stats(region[[i]], diploid = TRUE, digits = 4)$perloc } Hrperloc = matrix(data = 0, ncol = nreg, nrow = nloci) for (j in seq(hierHrperloc)) { Hrperloc[, j] = hierHrperloc[[j]]$Ht } HierHr_T = t(basic.stats(hfiles, diploid = TRUE, digits = 4)$overall) HierHr_Tperloc = basic.stats(hfiles, diploid = TRUE, digits = 4)$perloc Hallperloc = cbind(HierHr_Tperloc$Ht, Hrperloc, HierHr_Tperloc$Hs) colnames(Hallperloc) = c("Ht", paste("Hr", 1:nreg), "Hp") rownames(Hallperloc) = c(paste("Locus", 1:nloci)) hierHr = do.call(rbind, lapply(hierHr, data.frame)) Hr = colMeans(hierHr) Hr = as.array(Hr) HierHr_T = as.data.frame(HierHr_T) HieHr = cbind(HierHr_T$Ht, Hr[3], HierHr_T$Hs) colnames(HieHr) = c("Ht", "Hr", "Hp") rownames(HieHr) = NULL return(list(HierHe_perloc = Hallperloc,HierHr=hierHr, Hrperloc=Hrperloc,HieHr_overall = HieHr)) }
context("Testing input_fn") source("helper-utils.R") fake_canned_estimator <- structure(list(a=1), class = "tf_estimator") fake_custom_estimator <- structure(list(a=1), class = "tf_custom_estimator") test_succeeds("input_fn can be constructed through formula interface", { features <- c("drat", "cyl") input_fn1 <- input_fn(mtcars, response = mpg, features = one_of(features))(TRUE) expect_equal(length(input_fn1()), 2) expect_equal(length(input_fn1()[[1]]), length(features)) input_fn2 <- input_fn(mpg ~ drat + cyl, data = mtcars)(TRUE) expect_equal(length(input_fn2()), 2) expect_equal(length(input_fn2()[[1]]), length(features)) expect_equal(input_fn1, input_fn2) }) test_succeeds("input_fn can be constructed correctly from data.frame objects", { features <- c("drat", "cyl") input_fn1 <- input_fn(mtcars, response = mpg, features = one_of(features))(TRUE) expect_equal(length(input_fn1()), 2) expect_length(setdiff(names(input_fn1()[[1]]), features), 0) expect_true(is.tensor(input_fn1()[[1]][[1]])) expect_true(is.tensor(input_fn1()[[2]])) }) test_succeeds("input_fn can be constructed correctly from matrix objects", { features <- c("drat", "cyl") input_fn1 <- input_fn( as.matrix(mtcars), response = mpg, features = one_of(features) )(fake_canned_estimator)() expect_equal(length(input_fn1), 2) expect_length(setdiff(names(input_fn1[[1]]), features), 0) expect_true(is.tensor(input_fn1[[1]][[1]])) expect_true(is.tensor(input_fn1[[2]])) input_fn2 <- input_fn( as.matrix(mtcars), response = mpg, features = one_of(features) )(fake_custom_estimator)() expect_equal(length(input_fn2), 2) expect_equal(names(input_fn2), NULL) expect_true(is.tensor(input_fn2[[1]][[1]])) expect_true(is.tensor(input_fn2[[2]])) }) test_succeeds("input_fn can be constructed correctly from list objects", { fake_sequence_input_fn <- input_fn( object = list( features = list( list(list(1), list(2), list(3)), list(list(4), list(5), list(6))), response = list( list(1, 2, 3), list(4, 5, 6))), features = c(features), response = response)(fake_canned_estimator)() expect_equal(length(fake_sequence_input_fn), 2) expect_true(is.tensor(fake_sequence_input_fn[[1]][[1]])) expect_true(is.tensor(fake_sequence_input_fn[[2]])) list_data <- list( featureA = list( list(list(1), list(2), list(3)), list(list(4), list(5), list(6))), featureB = list( list(list(7), list(8), list(9)), list(list(10), list(11), list(12))), response = list( list(1, 2, 3), list(4, 5, 6)) ) fake_sequence_input_fn <- input_fn( object = list_data, features = c("featureA", "featureB"), response = "response", batch_size = 10L)(fake_canned_estimator)() expect_equal(length(fake_sequence_input_fn), 2) expect_true(is.tensor(fake_sequence_input_fn[[1]][[1]])) expect_true(is.tensor(fake_sequence_input_fn[[2]])) }) test_succeeds("R factors are coerced appropriately", { RESPONSE <- "Species" FEATURES <- setdiff(names(iris), RESPONSE) classifier <- dnn_classifier( feature_columns = lapply(FEATURES, column_numeric), hidden_units = list(10, 20, 10), n_classes = 3 ) train( classifier, input_fn = input_fn( iris, features = one_of(FEATURES), response = one_of(RESPONSE) ) ) expect_message( train( classifier, input_fn = input_fn( iris, features = one_of(FEATURES), response = one_of(RESPONSE) ) ), "The following factor levels of 'Species' have been encoded:\n- 'setosa' => 0\n- 'versicolor' => 1\n- 'virginica' => 2") })
plotConfidence <- function(x, y.at, lower, upper, pch=16, cex=1, lwd=1, col=4, xlim, xlab, labels, title.labels, values, title.values, section.pos, section.sep, section.title=NULL, section.title.x, section.title.offset, order, leftmargin=0.025, rightmargin=0.025, stripes, factor.reference.pos, factor.reference.label="Reference", factor.reference.pch=16, refline=1, title.line=TRUE, xratio, y.offset=0, y.title.offset, digits=2, format, extremearrows.length=0.05, extremearrows.angle=30, add=FALSE, layout=TRUE, xaxis=TRUE, ...){ if (!is.list(x)) x <- list(x=x) m <- x[[1]] names(x) <- tolower(names(x)) if (missing(lower)) { lower <- x$lower } if (missing(upper)) upper <- x$upper if (missing(xlim)) xlim <- c(min(lower)-0.1*min(lower),max(upper)+0.1*min(upper)) if (missing(xlab)) xlab <- "" NR <- length(x[[1]]) if (length(lower)!=NR) stop(paste0("lower has wrong dimension. There are ",NR," contrasts but ",length(upper)," upper limits")) if (length(upper)!=NR) stop(paste0("upper has wrong dimension. There are ",NR," contrasts but ",length(upper)," upper limits")) if (!missing(labels) && (is.logical(labels) && labels[[1]]==FALSE)) do.labels <- FALSE else do.labels <- TRUE if (!do.labels || (!missing(title.labels) && (is.logical(title.labels) && title.labels[[1]]==FALSE))) do.title.labels <- FALSE else do.title.labels <- TRUE if (do.labels && missing(labels)) { labels <- x$labels if (is.null(labels)) do.labels <- FALSE } if (missing(labels)) labels <- NULL if (!is.data.frame(labels) && is.list(labels)){ section.rows <- sapply(labels,NROW) nsections <- length(labels) if (sum(section.rows)!=NR) stop(paste0("Label list has wrong dimension. There are ",NR," confidence intervals but ",sum(section.rows)," labels")) }else{ nsections <- 0 section.rows <- NULL } if (missing(y.at)) {at <- 1:NR } else{ if(length(y.at)!=NR) stop(paste0("Number of y positions must match number of confidence intervals which is ",NR)) at <- y.at } if (nsections>0){ if (!missing(section.title) && length(section.title)>0){ names(labels) <- section.title } do.sections <- TRUE section.title <- rev(names(labels)) if (!is.data.frame(labels[[1]]) && is.list(labels[[1]])){ sublevels <- names(labels) labels <- lapply(1:length(labels),function(l){ cbind(sublevels[[l]],data.table::data.table(labels[[l]])) }) } labels <- data.table::rbindlist(lapply(labels,data.table::data.table),use.names=TRUE) section.pos <- cumsum(rev(section.rows)) }else{ if (!missing(section.title) && length(section.title)>0){ if (missing(section.pos)) stop("Need y-positions for section.titles") do.sections <- TRUE }else{ do.sections <- FALSE } } oneM <- .5 if (do.sections){ if (missing(section.title.offset)) section.title.offset <- 1.5*oneM if (missing(section.sep)) section.sep <- 2*oneM section.shift <- rep(cumsum(c(0,section.sep+rep(section.sep,nsections-1))), c(section.pos[1],diff(section.pos))) section.pos+section.shift[section.pos] if ((sub.diff <- (length(at)-length(section.shift)))>0) section.shift <- c(section.shift,rep(section.title.offset+section.shift[length(section.shift)],sub.diff)) }else{ section.shift <- 0 } at <- at+section.shift if (length(y.offset)!=NR) y.offset <- rep(y.offset,length.out=NR) at <- at+y.offset if (do.sections){ section.y <- at[section.pos] section.title.y <- section.y+section.title.offset }else{ section.title.y <- 0 } if (missing(y.title.offset)) { if (do.sections){ y.title.offset <- 1.5*oneM + section.title.offset } else{ y.title.offset <- 1.5*oneM } } title.y <- max(at)+y.title.offset rat <- rev(at) ylim <- c(0,at[length(at)]+1) dimensions <- list("NumberRows"=NR,xlim=xlim,ylim=ylim,y.at=at) if (!missing(values) && (is.logical(values) && values[[1]]==FALSE)) do.values <- FALSE else do.values <- TRUE if (do.values==TRUE){ if (!missing(title.values) && (is.logical(title.values) && title.values[[1]]==FALSE)) do.title.values <- FALSE else do.title.values <- TRUE }else{ do.title.values <- FALSE } if (do.values){ if (missing(values)){ if (missing(format)) if (all(!is.na(upper)) && any(upper<0)) format <- "(u;l)" else format <- "(u-l)" values.defaults <- paste(pubformat(x[[1]],digits=digits), apply(cbind(lower,upper), 1, function(x)formatCI(lower=x[1],upper=x[2],format=format,digits=digits))) if (!missing(factor.reference.pos) && is.numeric(factor.reference.pos) && all(factor.reference.pos<length(values.defaults))) values.defaults[factor.reference.pos] <- factor.reference.label if (do.title.values && (missing(title.values)) || (!is.expression(title.values) && !is.character(title.values))) title.values <- expression(paste(bold(Estimate)," (",bold(CI[95]),")")) }else{ values.defaults <- values if (missing(title.values)) title.values <- NULL } } else{ values.defaults <- NULL title.values <- NULL } if (add==TRUE) do.values <- do.title.values <- do.labels <- do.title.labels <- FALSE dist <- (at[2]-at[1])/2 if (missing(stripes) || is.null(stripes)) do.stripes <- FALSE else do.stripes <- stripes stripes.DefaultArgs <- list(col=c(prodlim::dimColor("orange"),"white"), horizontal=seq(min(at)-dist,max(at)+dist,1), xlim=xlim, border=NA) if (xaxis) do.xaxis <- TRUE xaxis.DefaultArgs <- list(side=1,las=1,pos=0,cex=cex) xlab.DefaultArgs <- list(text=xlab,side=1,line=1.5,xpd=NA,cex=cex) plot.DefaultArgs <- list(0,0,type="n",ylim=ylim,xlim=xlim,axes=FALSE,ylab="",xlab=xlab) points.DefaultArgs <- list(x=m,y=rat,pch=16,cex=cex,col=col,xpd=NA) arrows.DefaultArgs <- list(x0=lower,y0=rat,x1=upper,y1=rat,lwd=lwd,col=col,xpd=NA,length=0,code=3,angle=90) refline.DefaultArgs <- list(x0=refline,y0=0,x1=refline,y1=max(at),lwd=lwd,col="gray71",xpd=NA) if (missing(title.labels)) title.labels <- NULL labels.DefaultArgs <- list(x=0,y=rat,cex=cex,labels=labels,xpd=NA,pos=4) title.labels.DefaultArgs <- list(x=0, y=at[length(at)]+y.title.offset, cex=NULL, labels=title.labels, xpd=NA, font=2, pos=NULL) values.DefaultArgs <- list(x=0,y=rat,labels=values.defaults,cex=cex,xpd=NA,pos=4) title.y <- at[length(at)]+y.title.offset title.values.DefaultArgs <- list(x=0, y=title.y, labels=title.values, cex=NULL, xpd=NA, font=2, pos=NULL) if (do.sections) title.line.y <- (title.y+max(section.title.y))/2 else title.line.y <- title.y-.25 title.line.DefaultArgs <- list(x0=-Inf, y0=title.line.y, x1=Inf, y1=title.line.y, lwd=lwd, col="gray71", xpd=TRUE) section.title.DefaultArgs <- list(x=0,y=section.title.y,labels=section.title,cex=NULL,xpd=NA,font=4,pos=4) smartA <- prodlim::SmartControl(call= list(...), keys=c("plot","points","arrows","refline","title.line","labels","values","title.labels","section.title","title.values","xaxis","stripes","xlab"), ignore=c("formula","data","add","col","lty","lwd","ylim","xlim","xlab","ylab","axes","factor.reference.pos","factor.reference.label","extremearrows.angle","extremearrows.length"), defaults=list("plot"=plot.DefaultArgs, "points"=points.DefaultArgs, "refline"=refline.DefaultArgs, "title.line"=title.line.DefaultArgs, "labels"=labels.DefaultArgs, "title.labels"=title.labels.DefaultArgs, "section.title"=section.title.DefaultArgs, "stripes"=stripes.DefaultArgs, "values"=values.DefaultArgs, "title.values"=title.values.DefaultArgs, "arrows"=arrows.DefaultArgs, "xaxis"=xaxis.DefaultArgs, "xlab"=xlab.DefaultArgs), forced=list("plot"=list(axes=FALSE,xlab=""),"xaxis"=list(side=1)), verbose=TRUE) if (is.null(smartA$title.labels$pos)) smartA$title.labels$pos <- smartA$labels$pos if (is.null(smartA$title.values$pos)) smartA$title.values$pos <- smartA$values$pos if (is.null(smartA$title.labels$cex)) smartA$title.labels$cex <- smartA$labels$cex if (is.null(smartA$section.title$cex)) smartA$section.title$cex <- smartA$labels$cex if (is.null(smartA$title.values$cex)) smartA$title.values$cex <- smartA$values$cex if (!missing(factor.reference.pos) && is.numeric(factor.reference.pos) && all(factor.reference.pos<length(values.defaults))){ if (length(smartA$points$pch)<NR) smartA$points$pch <- rep(smartA$points$pch,length.out=NR) smartA$points$pch[factor.reference.pos] <- factor.reference.pch } if (add==FALSE){ oldmar <- par()$mar on.exit(par(mar=oldmar)) on.exit(par(mfrow=c(1,1))) par(mar=c(0,0,0,0)) dsize <- dev.size(units="cm") leftmarginwidth <- leftmargin*dsize[1] rightmarginwidth <- rightmargin*dsize[1] plotwidth <- dsize[1]-leftmarginwidth-rightmarginwidth if (do.labels){ preplabels <- prepareLabels(labels=smartA$labels, titles=smartA$title.labels) } if (do.values){ prepvalues <- prepareLabels(labels=smartA$values, titles=smartA$title.values) } if (do.labels){ if (do.values){ do.stripes <- rep(do.stripes,length.out=3) names(do.stripes) <- c("labels","ci","values") if (missing(xratio)) { lwidth <- sum(preplabels$columnwidth) vwidth <- sum(prepvalues$columnwidth) xratio <- c(lwidth/(lwidth+vwidth)*0.7,vwidth/(lwidth+vwidth)*0.7) } labelswidth <- plotwidth * xratio[1] valueswidth <- plotwidth * xratio[2] ciwidth <- plotwidth - labelswidth - valueswidth mat <- matrix(c(0,c(1,3,2)[order],0),ncol=5) if (!missing(order) && length(order)!=3) order <- rep(order,length.out=3) if (layout) layout(mat,width=c(leftmarginwidth,c(labelswidth,ciwidth,valueswidth)[order],rightmarginwidth)) } else{ do.stripes <- rep(do.stripes,length.out=2) names(do.stripes) <- c("labels","ci") if (missing(xratio)) xratio <- 0.618 labelswidth <- plotwidth * xratio[1] ciwidth <- plotwidth - labelswidth valueswidth <- 0 if (!missing(order) && length(order)!=2) order <- rep(order,length.out=2) mat <- matrix(c(0,c(1,2)[order],0),ncol=4) if (layout) layout(mat,width=c(leftmarginwidth,c(labelswidth,ciwidth)[order],rightmarginwidth)) } } else{ if (do.values){ do.stripes <- rep(do.stripes,length.out=2) names(do.stripes) <- c("ci","values") if (missing(xratio)) xratio <- 0.618 valueswidth <- plotwidth * (1-xratio[1]) ciwidth <- plotwidth - valueswidth labelswidth <- 0 mat <- matrix(c(0,c(2,1)[order],0),ncol=4) if (!missing(order) && length(order)!=2) order <- rep(order,length.out=2) if (layout) layout(mat,width=c(leftmarginwidth,c(ciwidth,valueswidth)[order],rightmarginwidth)) }else{ xratio <- 1 ciwidth <- plotwidth do.stripes <- do.stripes[1] names(do.stripes) <- "ci" labelswidth <- 0 valueswidth <- 0 mat <- matrix(c(0,1,0),ncol=3) if (layout) layout(mat,width=c(leftmarginwidth,ciwidth,rightmarginwidth)) } } dimensions <- c(dimensions,list(xratio=xratio, labelswidth=labelswidth, valueswidth=valueswidth, ciwidth=ciwidth,layout=mat)) } if (add==FALSE) par(mar=oldmar*c(1,0,1,0)) if (do.labels){ if (do.stripes[["labels"]]) preplabels <- c(preplabels,list(width=labelswidth,ylim=ylim,stripes=smartA$stripes)) else preplabels <- c(preplabels,list(width=labelswidth,ylim=ylim)) do.call("plotLabels",preplabels) if ((missing(title.line) || !is.null(title.line)) && ((add==FALSE) & is.infinite(smartA$title.line$x0))){ smartA$title.line$x0 <- par()$usr[1] smartA$title.line$x1 <- par()$usr[2] do.call("segments",smartA$title.line) smartA$title.line$x0 <- -Inf } } if (do.sections){ do.call("text",smartA$section.title) } if (do.values){ if (do.stripes[["values"]]) prepvalues <- c(prepvalues,list(width=valueswidth,ylim=ylim,stripes=smartA$stripes)) else prepvalues <- c(prepvalues,list(width=valueswidth,ylim=ylim)) do.call("plotLabels",prepvalues) if ((missing(title.line) || !is.null(title.line)) && ((add==FALSE) & is.infinite(smartA$title.line$x0))){ smartA$title.line$x0 <- par()$usr[1] smartA$title.line$x1 <- par()$usr[2] do.call("segments",smartA$title.line) smartA$title.line$x0 <- -Inf } } if (add==FALSE){ do.call("plot",smartA$plot) if (do.stripes[["ci"]]) do.call("stripes",smartA$stripes) if (do.xaxis==TRUE){ oldcexaxis <- par()$cex.axis on.exit(par(cex.axis=oldcexaxis)) par(cex.axis=smartA$xaxis$cex) if (is.null(smartA$xaxis$labels)) do.call("axis",smartA$xaxis) } do.call("mtext",smartA$xlab) } if (add==FALSE){ if (missing(refline) || !is.null(refline)) do.call("segments",smartA$refline) } if (add==FALSE){ if (missing(title.line) || !is.null(title.line)){ if (is.infinite(smartA$title.line$x0)){ smartA$title.line$x0 <- par()$usr[1] smartA$title.line$x1 <- par()$usr[2] } do.call("segments",smartA$title.line) } } do.call("points",smartA$points) if (any(smartA$arrows$x0>xlim[2],na.rm=TRUE)||any(smartA$arrows$x1<xlim[1],na.rm=TRUE)) warning("One or several confidence intervals are completely outside xlim. You should adjust xlim.") tooHigh <- smartA$arrows$x1>xlim[2] tooHigh[is.na(tooHigh)] <- FALSE tooLow <- smartA$arrows$x0<xlim[1] tooLow[is.na(tooLow)] <- FALSE if (any(c(tooHigh,tooLow))){ if (length(smartA$arrows$angle)<NR) smartA$arrows$angle <- rep(smartA$arrows$angle,length.out=NR) if (length(smartA$arrows$length)<NR) smartA$arrows$length <- rep(smartA$arrows$length,length.out=NR) if (length(smartA$arrows$code)<NR) smartA$arrows$code <- rep(smartA$arrows$code,length.out=NR) if (length(smartA$arrows$col)<NR) smartA$arrows$col <- rep(smartA$arrows$col,length.out=NR) smartA$arrows$x0 <- pmax(xlim[1],smartA$arrows$x0) smartA$arrows$x1 <- pmin(xlim[2],smartA$arrows$x1) smartA$arrows$code[tooLow & tooHigh] <- 3 smartA$arrows$code[tooLow & !tooHigh] <- 1 smartA$arrows$code[!tooLow & tooHigh] <- 2 smartA$arrows$angle[tooLow | tooHigh] <- extremearrows.angle smartA$arrows$length[tooLow | tooHigh] <- extremearrows.length aargs <- smartA$arrows for (r in 1:NR){ aargs$x0 <- smartA$arrows$x0[r] aargs$x1 <- smartA$arrows$x1[r] aargs$y0 <- smartA$arrows$y0[r] aargs$y1 <- smartA$arrows$y1[r] aargs$code <- smartA$arrows$code[r] aargs$col <- smartA$arrows$col[r] aargs$length <- smartA$arrows$length[r] aargs$angle <- smartA$arrows$angle[r] suppressWarnings(do.call("arrows",aargs)) } } else{ suppressWarnings(do.call("arrows",smartA$arrows)) } dimensions <- c(smartA,dimensions) invisible(dimensions) }
heqb.SGB <- function(x,d,u,bound,shape1,index,...){ h <- x[index] return(h) }
DyS <- function(p.score, n.score, test, measure="topsoe", bins=seq(2,20,2), err=1e-5){ b_sizes <- bins result <- c(1:length(b_sizes)) for(hi in 1:length(b_sizes)){ Sty_1 <- getHist(p.score, b_sizes[hi]) Sty_2 <- getHist(n.score, b_sizes[hi]) Uy <- getHist(test, b_sizes[hi]) f <- function(x){ return(DyS_distance(rbind((Sty_1*x)+ (Sty_2*(1-x)), Uy), method = measure)) } result[hi] <- TernarySearch(0, 1, f, err) } result <- stats::median(result) if(result < 0 ) result <- 0 if(result > 1 ) result <- 1 result <- c(result, 1 - result) names(result) <- c("+", "-") return(result) }
context("case_insensitive") test_that( "case_insensitive wraps in case insensitivity tokens", { expected <- as.regex("(?i)foo(?-i)") actual <- case_insensitive("foo") expect_equal(actual, expected) } ) context("free_spacing") test_that( "free_spacing wraps in free spacing tokens", { expected <- as.regex("(?x)foo(?-x)") actual <- free_spacing("foo") expect_equal(actual, expected) } ) context("single_line") test_that( "single_line wraps in single line tokens", { expected <- as.regex("(?s)foo(?-s)") actual <- single_line("foo") expect_equal(actual, expected) } ) context("multi_line") test_that( "multi_line wraps in multi-line tokens", { expected <- as.regex("(?m)foo(?-m)") actual <- multi_line("foo") expect_equal(actual, expected) } ) context("duplicate_group_names") test_that( "duplicate_group_names wraps in duplicate group name tokens", { expected <- as.regex("(?J)foo(?-J)") actual <- duplicate_group_names("foo") expect_equal(actual, expected) } ) context("no_backslash_escaping") test_that( "no_backslash_escaping wraps in no backslash escaping tokens", { expected <- as.regex("(?X)foo(?-X)") actual <- no_backslash_escaping("foo") expect_equal(actual, expected) } )
tokenWindowOccurence <- function(tc, feature, context_level=c('document','sentence'), window.size=10, direction='<>', distance_as_value=F, batch_rows=NULL, drop_empty_terms=T){ is_tcorpus(tc) context_level = match.arg(context_level) feature = match.arg(feature, tc$feature_names) if (direction == '<') shifts = -window.size:0 if (direction == '<>') shifts = -window.size:window.size if (direction == '>') shifts = 0:window.size feature = tc$get(feature) if (!is.factor(feature)) feature = fast_factor(feature) if (drop_empty_terms) feature = base::droplevels(feature) term_index = as.numeric(feature) position = get_global_i(tc, context_level, window.size) rows = if (!is.null(batch_rows)) batch_rows[!is.na(feature[batch_rows])] else !is.na(feature) position.mat = position_matrix(position, term_index, shifts = 0, rows=rows) window.mat = position_matrix(position, term_index, shifts, distance_as_value=distance_as_value, rows=rows) colnames(position.mat) = colnames(window.mat) = levels(feature) rownames(position.mat) = rownames(window.mat) = position list(position.mat=position.mat, window.mat=window.mat) } transform_count <- function(m, count_mode=c('normal','dicho','prob'), alpha=2){ count_mode = match.arg(count_mode) m = methods::as(methods::as(m, 'dgCMatrix'), 'dgTMatrix') if (count_mode == 'normal') NULL if (count_mode == 'dicho') m@x[m@x > 0] = 1 if (count_mode == 'prob') { get_prob <- function(x, alpha) 1 - ((1/alpha) ^ x) m@x[m@x > 0] = get_prob(m@x[m@x > 0], alpha) } m } feature_cooccurrence <- function(tc, feature, matrix_mode=c('dtm', 'windowXwindow', 'positionXwindow'), count_mode=c('normal','dicho','prob'), mat_stats=c('sum.x','sum.y','magnitude.x','magnitude.y', 'nrow'), context_level=c('document','sentence'), direction='<>', window.size=10, n.batches=1, alpha=2){ is_tcorpus(tc) matrix_mode = match.arg(matrix_mode) count_mode = match.arg(count_mode) context_level = match.arg(context_level) if (matrix_mode == 'dtm') { ml = cooccurrence_matrix(tc, feature, count_mode=count_mode, mat_stats=mat_stats, context_level=context_level, n.batches=n.batches, alpha=alpha) } if (matrix_mode %in% c('positionXwindow', 'windowXwindow')) { ml = cooccurrence_matrix_window(tc, feature, matrix_mode=matrix_mode, count_mode=count_mode, mat_stats=mat_stats, context_level=context_level, direction=direction, window.size=window.size, n.batches=n.batches, alpha=alpha) } ml$mat = methods::as(methods::as(ml$mat, 'dgCMatrix'), 'dgTMatrix') ml } cooccurrence_crossprod <- function(m1, m2=NULL, count_mode, mat_stats, alpha){ m1 = transform_count(methods::as(m1, 'dgTMatrix'), count_mode=count_mode, alpha=alpha) if (is.null(m2)){ mat = Matrix::crossprod(m1) mat_stats = get_matrix_stats(m1, mat_stats=mat_stats) } else { m2 = transform_count(methods::as(m2, 'dgTMatrix'), count_mode=count_mode, alpha=alpha) mat = Matrix::crossprod(m1,m2) mat_stats = get_matrix_stats(m1, m2=m2, mat_stats=mat_stats) } c(list(mat=mat), mat_stats) } get_matrix_stats <- function(m1, m2=NULL, mat_stats = c('sum.x','sum.y','magnitude.x','magnitude.y', 'nrow')){ r = list() if ('nrow' %in% mat_stats) r[['nrow']] = nrow(m1) if ('sum.x' %in% mat_stats) r[['sum.x']] = Matrix::colSums(m1) if ('magnitude.x' %in% mat_stats) r[['magnitude.x']] = sqrt(Matrix::colSums(m1^2)) if(!is.null(m2)){ if ('sum.y' %in% mat_stats) r[['sum.y']] = Matrix::colSums(m2) if ('magnitude.y' %in% mat_stats) r[['magnitude.y']] = sqrt(Matrix::colSums(m2^2)) } else { if ('sum.y' %in% mat_stats) { r[['sum.y']] = if ('sum.x' %in% names(r)) r[['sum.x']] else Matrix::colSums(m2) } if ('magnitude.y' %in% mat_stats) { r[['magnitude.y']] = if ('magnitude.x' %in% names(r)) r[['magnitude.x']] else sqrt(Matrix::colSums(m2^2)) } } r } cooccurrence_matrix <- function(tc, feature, count_mode, mat_stats, context_level, n.batches, alpha, drop_empty_terms=T){ m = get_dtm(tc, feature=feature, context_level = context_level, drop_empty_terms=drop_empty_terms, context_labels = F) if (is.na(n.batches)){ ml = cooccurrence_crossprod(m, count_mode=count_mode, mat_stats=mat_stats, alpha=alpha) } else { batch_i = get_batch_i(tc, n.batches=n.batches) ml = list() for(i in 1:nrow(batch_i)){ batch_rows = batch_i$start[i]:batch_i$end[i] cooc = cooccurrence_crossprod(m[batch_rows,,drop=F], count_mode=count_mode, mat_stats=mat_stats, alpha=alpha) for(n in names(cooc)) ml[[n]] = if (n %in% names(ml)) ml[[n]] + cooc[[n]] else cooc[[n]] } } ml$freq = Matrix::colSums(m) ml$doc_freq = Matrix::colSums(m) ml } cooccurrence_matrix_window <- function(tc, feature, matrix_mode='position_to_window', count_mode='dicho', mat_stats=c('sum.x','sum.y','magnitude.x','magnitude.y'), context_level='document', direction='<>', window.size=10, n.batches=window.size, alpha=2, drop_empty_terms=T){ if (is.na(n.batches)){ wwo = tokenWindowOccurence(tc, feature, context_level, window.size, direction, drop_empty_terms=drop_empty_terms) if (matrix_mode == 'windowXwindow') ml = cooccurrence_crossprod(wwo$window.mat, wwo$window.mat, count_mode=count_mode, alpha=alpha, mat_stats=mat_stats) if (matrix_mode == 'positionXwindow') ml = cooccurrence_crossprod(wwo$position.mat, wwo$window.mat, count_mode=count_mode, alpha=alpha, mat_stats=mat_stats) ml[['freq']] = Matrix::colSums(wwo$position.mat) } else { batch_i = data_batch(tc, context_level, n.batches) ml = list() for(i in 1:nrow(batch_i)){ batch_rows = batch_i$start[i]:batch_i$end[i] wwo = tokenWindowOccurence(tc, feature, context_level, window.size, direction, batch_rows=batch_rows) if (matrix_mode == 'windowXwindow') cooc = cooccurrence_crossprod(wwo$window.mat, wwo$window.mat, count_mode=count_mode, alpha=alpha, mat_stats=mat_stats) if (matrix_mode == 'positionXwindow') cooc = cooccurrence_crossprod(wwo$position.mat, wwo$window.mat, count_mode=count_mode, alpha=alpha, mat_stats=mat_stats) for(n in names(cooc)) ml[[n]] = if (n %in% names(ml)) ml[[n]] + cooc[[n]] else cooc[[n]] ml[['freq']] = if ('freq' %in% names(ml)) ml[['freq']] + Matrix::colSums(wwo$position.mat) else Matrix::colSums(wwo$position.mat) } } ml } cooccurrence_graph_freq <- function(g, m1, m2){ if (is.null(m2)) { igraph::V(g)$sum = Matrix::colSums(m1) igraph::V(g)$doc_freq = Matrix::colSums(m1 > 0) } else { m1freq = data.frame(name=colnames(m1), sum=Matrix::colSums(m1), doc_freq=Matrix::colSums(m1 > 0)) m2freq = data.frame(name=colnames(m2), sum=Matrix::colSums(m2), doc_freq=Matrix::colSums(m2 > 0)) freq = unique(rbind(m1freq,m2freq)) i = match(igraph::V(g)$name, freq$name) igraph::V(g)$sum = freq$sum[i] igraph::V(g)$doc_freq = freq$doc_freq[i] } g } is_symmetrical <- function(mat) identical(colnames(mat), rownames(mat)) squarify_matrix <- function(mat){ if (!is_symmetrical(mat)){ mat = methods::as(mat, 'dgTMatrix') rnames = rownames(mat) cnames = colnames(mat) dnames = unique(c(rnames,cnames)) mat = summary(mat) conv_i = match(rnames, dnames) conv_j = match(cnames, dnames) mat = spMatrix(length(dnames), length(dnames), conv_i[mat$i], conv_j[mat$j], mat$x) dimnames(mat) = list(dnames, dnames) } mat } cooc_chi2 <- function(g, x_sum, y_sum=x_sum, autocorrect=T){ cooc = igraph::get.edgelist(g, names = F) cooc = data.frame(x = cooc[,1], y = cooc[,2], cooc = igraph::E(g)$weight) cooc$chi2 = calc_chi2(a = cooc$cooc, b = y_sum[cooc$y] - cooc$cooc, c = x_sum[cooc$x] - cooc$cooc, d = igraph::ecount(g) - ((x_sum[cooc$x] + y_sum[cooc$y]) - cooc$cooc), cochrans_criteria = autocorrect) cooc }
logthresh_2_thresh <- function(x) { cumsum( exp(x) ) }
`scores.metaMDS` <- function(x, display = c("sites", "species"), shrink = FALSE, choices, tidy = FALSE, ...) { display <- match.arg(display, c("sites","species"), several.ok = TRUE) if (missing(choices)) choices <- seq_len(x$ndim) else choices <- choices[choices <= x$ndim] out <- list() if ("sites" %in% display) { sites <- x$points[, choices, drop=FALSE] colnames(sites) <- paste0("NMDS", choices) out$sites <- sites } if ("species" %in% display && !is.null(x$species)) { species <- x$species[, choices, drop=FALSE] colnames(species) <- paste0("NMDS", choices) if (shrink) { mul <- sqrt(attr(X, "shrinkage")) if (is.null(mul)) warning("species cannot be shrunken, because they were not expanded") else { mul <- mul[choices] cnt <- attr(X, "centre") X <- sweep(X, 2, cnt, "-") X <- sweep(X, 2, mul, "*") X <- sweep(X, 2, cnt, "+") } } out$species <- species } if (tidy) { if (length(out) == 0) return(NULL) group <- sapply(out, nrow) group <- rep(names(group), group) out <- do.call(rbind, out) label <- rownames(out) out <- as.data.frame(out) out$score <- group out$label <- label } switch(length(out), out[[1]], out) }
context("Testing acv_arma") test_that("bogus arguments throw error",{ expect_error(acv_arma(Inf,1,10)) }) test_that("output of acv_arma is correct",{ n <- 0:9 answer <- 2^(-n) * (32/3 + 8 * n) /(32/3) acv <- acv_arma(c(1.0, -0.25), 1.0, 10) expect_equal(acv/acv[1], answer) })
get_invitroPK_param <- function( param, species, chem.name=NULL, chem.cas=NULL, dtxsid=NULL) { chem.physical_and_invitro.data <- chem.physical_and_invitro.data if (is.null(chem.cas) & is.null(chem.name) & is.null(dtxsid) ) stop('Chem.name, chem.cas, or dtxsid must be specified.') if (any(is.null(chem.cas),is.null(chem.name),is.null(dtxsid))) { out <- get_chem_id( chem.cas=chem.cas, chem.name=chem.name, dtxsid=dtxsid) chem.cas <- out$chem.cas chem.name <- out$chem.name dtxsid <- out$dtxsid } if (length(dtxsid)!=0) chem.physical_and_invitro.data.index <- which(chem.physical_and_invitro.data$DTXSID == dtxsid) else if (length(chem.cas)!=0) chem.physical_and_invitro.data.index <- which(chem.physical_and_invitro.data$CAS == chem.cas) else chem.physical_and_invitro.data.index <- which(chem.physical_and_invitro.data$Compound == chem.name) this.col.name <- tolower(paste(species,param,sep=".")) if (!(this.col.name %in% tolower(colnames(chem.physical_and_invitro.data)))) { warning(paste("No in vitro ",param," data for ",chem.name," in ",species,".",sep="")) for (alternate.species in c("Human","Rat","Mouse","Dog","Monkey","Rabbit")) { this.col.name <- tolower(paste(alternate.species,param,sep=".")) if (this.col.name %in% tolower(colnames(chem.physical_and_invitro.data))) { warning(paste("Substituting ",alternate.species," in vitro ", param," data for ",chem.name," ",species,".",sep="")) break() } } } if (this.col.name %in% tolower(colnames(chem.physical_and_invitro.data))) { this.col.index <- which(tolower(colnames(chem.physical_and_invitro.data))==this.col.name) param.val <- chem.physical_and_invitro.data[chem.physical_and_invitro.data.index,this.col.index] if (param=="Clint" & (nchar(param.val) - nchar(gsub(",","",param.val)))==3) return(param.val) else if (param=="Funbound.plasma" & (nchar(param.val) - nchar(gsub(",","",param.val)))==2) return(param.val) else if (param=="Clint.pValue") return(param.val) else if (!is.na(as.numeric(param.val))) return(as.numeric(param.val)) } stop(paste("Incomplete in vitro PK data for ",chem.name, " in ",species," -- missing ",param,".",sep="")) }
library(MendelianRandomization) MRInputObject <- mr_input(bx = ldlc, bxse = ldlcse, by = chdlodds, byse = chdloddsse) MRInputObject MRInputObject.cor <- mr_input(bx = calcium, bxse = calciumse, by = fastgluc, byse = fastglucse, corr = calc.rho) MRInputObject.cor IVWObject <- mr_ivw(MRInputObject, model = "default", robust = FALSE, penalized = FALSE, correl = FALSE, weights = "simple", psi = 0, distribution = "normal", alpha = 0.05) IVWObject <- mr_ivw(mr_input(bx = ldlc, bxse = ldlcse, by = chdlodds, byse = chdloddsse)) IVWObject IVWObject.correl <- mr_ivw(MRInputObject.cor, model = "default", correl = TRUE, distribution = "normal", alpha = 0.05) IVWObject.correl <- mr_ivw(mr_input(bx = calcium, bxse = calciumse, by = fastgluc, byse = fastglucse, corr = calc.rho)) IVWObject.correl WeightedMedianObject <- mr_median(MRInputObject, weighting = "weighted", distribution = "normal", alpha = 0.05, iterations = 10000, seed = 314159265) WeightedMedianObject <- mr_median(mr_input(bx = ldlc, bxse = ldlcse, by = chdlodds, byse = chdloddsse)) WeightedMedianObject SimpleMedianObject <- mr_median(mr_input(bx = ldlc, bxse = ldlcse, by = chdlodds, byse = chdloddsse), weighting = "simple") SimpleMedianObject EggerObject <- mr_egger(MRInputObject, robust = FALSE, penalized = FALSE, correl = FALSE, distribution = "normal", alpha = 0.05) EggerObject <- mr_egger(mr_input(bx = ldlc, bxse = ldlcse, by = chdlodds, byse = chdloddsse)) EggerObject EggerObject.corr <- mr_egger(MRInputObject.cor, correl = TRUE, distribution = "normal", alpha = 0.05) EggerObject.corr <- mr_egger(mr_input(bx = calcium, bxse = calciumse, by = fastgluc, byse = fastglucse, corr = calc.rho)) EggerObject.corr MaxLikObject <- mr_maxlik(MRInputObject, model = "default", correl = FALSE, psi = 0, distribution = "normal", alpha = 0.05) MaxLikObject <- mr_maxlik(mr_input(bx = ldlc, bxse = ldlcse, by = chdlodds, byse = chdloddsse)) MaxLikObject MaxLikObject.corr <- mr_maxlik(mr_input(bx = calcium, bxse = calciumse, by = fastgluc, byse = fastglucse, corr = calc.rho)) MaxLikObject.corr MRMVInputObject <- mr_mvinput(bx = cbind(ldlc, hdlc, trig), bxse = cbind(ldlcse, hdlcse, trigse), by = chdlodds, byse = chdloddsse) MRMVInputObject MRMVObject <- mr_mvivw(MRMVInputObject, model = "default", correl = FALSE, distribution = "normal", alpha = 0.05) MRMVObject <- mr_mvivw(MRMVInputObject) MRMVObject MBEObject <- mr_mbe(MRInputObject, weighting = "weighted", stderror = "delta", phi = 1, seed = 314159265, iterations = 10000, distribution = "normal", alpha = 0.05) MBEObject <- mr_mbe(mr_input(bx = ldlc, bxse = ldlcse, by = chdlodds, byse = chdloddsse)) MBEObject HetPenObject <- mr_hetpen(mr_input(bx = ldlc[1:10], bxse = ldlcse[1:10], by = chdlodds[1:10], byse = chdloddsse[1:10]), CIMin = -1, CIMax = 5, CIStep = 0.01) HetPenObject bcrp =c(0.160, 0.236, 0.149, 0.09, 0.079, 0.072, 0.047, 0.069) bcrpse =c(0.006, 0.009, 0.006, 0.005, 0.005, 0.005, 0.006, 0.011) bchd =c(0.0237903, -0.1121942, -0.0711906, -0.030848, 0.0479207, 0.0238895, 0.005528, 0.0214852) bchdse =c(0.0149064, 0.0303084, 0.0150552, 0.0148339, 0.0143077, 0.0145478, 0.0160765, 0.0255237) HetPenObject.multimode <- mr_hetpen(mr_input(bx = bcrp, bxse = bcrpse, by = bchd, byse = bchdse)) HetPenObject.multimode MRInputObject <- mr_input(bx = ldlc, bxse = ldlcse, by = chdlodds, byse = chdloddsse) MRAllObject_all <- mr_allmethods(MRInputObject, method = "all") MRAllObject_all MRAllObject_egger <- mr_allmethods(MRInputObject, method = "egger") MRAllObject_egger MRAllObject_main <- mr_allmethods(MRInputObject, method = "main") MRAllObject_main mr_plot(mr_input(bx = ldlc, bxse = ldlcse, by = chdlodds, byse = chdloddsse), error = TRUE, orientate = FALSE, line = "ivw", interactive = FALSE) mr_plot(mr_input(bx = ldlc, bxse = ldlcse, by = chdlodds, byse = chdloddsse), error = TRUE, orientate = FALSE, line = "ivw", interactive = FALSE, labels = TRUE) mr_plot(MRAllObject_all) mr_plot(MRAllObject_egger) mr_plot(mr_allmethods(mr_input(bx = hdlc, bxse = hdlcse, by = chdlodds, byse = chdloddsse))) path.noproxy <- system.file("extdata", "vitD_snps_PhenoScanner.csv", package = "MendelianRandomization") path.proxies <- system.file("extdata", "vitD_snps_PhenoScanner_proxies.csv", package = "MendelianRandomization") extract.pheno.csv( exposure = "log(eGFR creatinine)", pmidE = 26831199, ancestryE = "European", outcome = "Tanner stage", pmidO = 24770850, ancestryO = "European", file = path.noproxy) extract.pheno.csv( exposure = "log(eGFR creatinine)", pmidE = 26831199, ancestryE = "European", outcome = "Tanner stage", pmidO = 24770850, ancestryO = "European", rsq.proxy = 0.6, file = path.proxies) extract.pheno.csv( exposure = "log(eGFR creatinine)", pmidE = 26831199, ancestryE = "European", outcome = "Asthma", pmidO = 20860503, ancestryO = "European", rsq.proxy = 0.6, file = path.proxies)
bekk_mc_eval <- function(object, spec, sample_sizes, iter, nc = 1) { xx <- process_object(object) theta <- xx$theta mse <- rep(NA, length(sample_sizes)) index <- 1 for(j in sample_sizes) { print(paste('Sample size: ', j)) sim_dat <- vector(mode = "list", iter) sim_dat <- future_lapply(1:iter, function(x){bekk_sim(object, nobs = j)}, future.seed=TRUE) dd <- future_lapply(sim_dat, function(x){bekk_fit(spec = spec, data = x, max_iter = 200)},future.seed=TRUE) mse[index] <- sum(unlist(lapply(dd, RMSE, theta_true = theta)))/iter print(mse[index]) index <- index +1 } result <- data.frame(Sample_size = sample_sizes, MSE = mse) colnames(result) <- c('Sample', 'MSE') result <- list(result) class(result) <- 'bekkMC' return(result) } RMSE <- function(x, theta_true) { theta_est <- x$theta return(mean(sqrt(((theta_true - theta_est) / theta_true)^2))) } plot.bekkMC <- function(x, ...) { Sample <- NULL MSE <- NULL msep <- x[[1]] ggplot(msep) + geom_line(aes(x = Sample, y = MSE)) + theme_bw() }
popprojLow <- read.delim(file='popprojLow.txt', comment.char='
library("testthat") test_package("rDEA")
update.formula.svisit <- function (old, new) { oldsta <- . ~ . olddet <- ~. oldsta[[2]] <- old[[2]] oldsta[[3]] <- old[[3]][[2]] olddet[[3]] <- old[[3]][[3]] olddet[[2]] <- NULL newsta <- . ~ . newdet <- ~. newsta[[2]] <- new[[2]] newsta[[3]] <- new[[3]][[2]] newdet[[3]] <- new[[3]][[3]] newdet[[2]] <- NULL tmpsta <- update.formula(as.formula(oldsta), as.formula(newsta)) tmpdet <- update.formula(as.formula(olddet), as.formula(newdet)) tmp <- . ~ . | . tmp[[2]] <- tmpsta[[2]] tmp[[3]][[2]] <- tmpsta[[3]] tmp[[3]][[3]] <- tmpdet[[2]] out <- formula(terms.formula(tmp, simplify = FALSE)) return(out) }
isd <- function(usaf, wban, year, overwrite = TRUE, cleanup = TRUE, additional = TRUE, parallel = FALSE, cores = getOption("cl.cores", 2), progress = FALSE, force = FALSE, ...) { rds_path <- isd_GET(usaf, wban, year, overwrite, force, ...) df <- read_isd(x = rds_path, cleanup, force, additional, parallel, cores, progress) attr(df, "source") <- rds_path df } isd_GET <- function(usaf, wban, year, overwrite, force, ...) { isd_cache$mkdir() rds <- isd_local(usaf, wban, year, isd_cache$cache_path_get(), ".rds") if (!is_isd(rds) || force) { fp <- isd_local(usaf, wban, year, isd_cache$cache_path_get(), ".gz") cli <- crul::HttpClient$new(isd_remote(usaf, wban, year), opts = list(...)) tryget <- tryCatch( suppressWarnings(cli$get(disk = fp)), error = function(e) e ) if (inherits(tryget, "error") || !tryget$success()) { unlink(fp) stop("download failed for\n ", isd_remote(usaf, wban, year), call. = FALSE) } } return(rds) } isd_remote <- function(usaf, wban, year) { file.path(isdbase(), year, sprintf("%s-%s-%s%s", usaf, wban, year, ".gz")) } isd_local <- function(usaf, wban, year, path, ext) { file.path(path, sprintf("%s-%s-%s%s", usaf, wban, year, ext)) } is_isd <- function(x) { if (file.exists(x)) TRUE else FALSE } isdbase <- function() 'https://www1.ncdc.noaa.gov/pub/data/noaa' read_isd <- function(x, cleanup, force, additional, parallel, cores, progress) { path_rds <- x if (file.exists(path_rds) && !force) { cache_mssg(path_rds) df <- readRDS(path_rds) } else { df <- isdparser::isd_parse( sub("rds", "gz", x), additional = additional, parallel = parallel, cores = cores, progress = progress ) cache_rds(path_rds, df) if (cleanup) { unlink(sub("rds", "gz", x)) } } return(df) } cache_rds <- function(x, y) { if (!file.exists(x)) { saveRDS(y, file = x) } }
update_designinlist <- function(designsin,groupsize,ni,xt,x,a,it,iGroup){ design$xt = xt design$a = a design$x = x design$groupsize = groupsize design$ni = ni if((it==-1) ){ design$num = length(designsin)+1 } else { design$num = it } design$iGroup = iGroup designsin=matrix(c(designsin, design),nrow=1,byrow=T) return( designsin ) }
p_path <- function(package="R"){ if(!object_check(package) || !is.character(package)){ package <- as.character(substitute(package)) } if (package == "R"){ return(.libPaths()) } else { return(find.package(package)) } }
require("DEoptimR") c.time <- function(...) cat('Time elapsed: ', ..., '\n') S.time <- function(expr) c.time(system.time(expr)) source(system.file("xtraR/opt-test-funs.R", package = "DEoptimR")) (doExtras <- DEoptimR:::doExtras()) set.seed(2345) S.time(sf1. <- JDEoptim(c(-100, -100), c(100, 100), sf1, NP = 50, tol = 1e-7, maxiter = 800)) S.time(swf. <- JDEoptim(rep(-500, 10), rep(500, 10), swf, tol = 1e-7)) S.time(g11. <- JDEoptim(-c(1, 1), c(1, 1), fn = g11$obj, constr = g11$con, meq = g11$eq, eps = 1e-3, tol = 1e-7, trace = TRUE)) S.time(RND. <- JDEoptim(c(1e-5, 1e-5), c(16, 16), RND$obj, RND$con, NP = 40, tol = 1e-7)) if (doExtras) { S.time(HEND. <- JDEoptim(c( 100, 1000, 1000 , 10, 10), c(10000, 10000, 10000, 1000, 1000), fn = HEND$obj, constr = HEND$con, tol = 1e-4, trace = TRUE)) S.time(alkylation. <- JDEoptim(c(1500, 1, 3000, 85, 90, 3, 145), c(2000, 120, 3500, 93, 95, 12, 162), fn = alkylation$obj, constr = alkylation$con, tol = 0.1, trace = TRUE)) } bare.p.v <- function(r) unlist(unname(r[c("par", "value")])) stopifnot( all.equal( bare.p.v(sf1.), c(0, 0, 0), tolerance = 1e-4 ), all.equal( bare.p.v(swf.), c(rep(420.97, 10), -418.9829*10), tolerance = 1e-4 ), all.equal( bare.p.v(RND.), c(3.036504, 5.096052, -0.388812), tolerance = 1e-2 ), all.equal( unname(c(abs(g11.$par[1]), g11.$par[2], g11.$value)), c(1/sqrt(2), 0.5, 0.75), tolerance = 1e-2 ) ) if (doExtras) { stopifnot( all.equal( bare.p.v(HEND.), c(579.19, 1360.13, 5109.92, 182.01, 295.60, 7049.25), tolerance = 1e-3 ), all.equal( bare.p.v(alkylation.), c(1698.256922, 54.274463, 3031.357313, 90.190233, 95.0, 10.504119, 153.535355, -1766.36), tolerance = 1e-2 ) ) } c.time(proc.time())
chisqtestClust <- function(x, y=NULL, id, p = NULL, variance = c("MoM", "sand.null", "sand.est", "emp")) { variance <- match.arg(variance) if (is.null(y)) { DNAME <- deparse(substitute(x)) if (is.table(x)|is.data.frame(x)) { if (ncol(x) < 2L) stop("'x' must have at least 2 columns") x <- x[stats::complete.cases(x),] if (!(all(rowSums(x)>0))) stop("all clusters must have counts > 0") if (!(all(x)>=0)) stop("elements of x must be nonnegative ") if (is.null(p)) p <- rep(1/ncol(x), ncol(x)) if (ncol(x)!=length(p)) stop("length of p must equal the number of columns of x") tmpdat <- x } else { if (length(x) != length(id)) stop("'id' and 'x' must have the same length") OK <- stats::complete.cases(x, id) x <- factor(x[OK]) id <- factor(id[OK]) if (length(unique(x)) == 1L) stop("'x' must at least have 2 categories") if (is.null(p)) p = rep(1/length(unique(x)), length(unique(x))) if (length(unique(x)) != length(p)) stop("length of p must must equal number of categories of x") tmpdat <- table(id, x) } if (any(p < 0)) stop("probabilities must be non-negative.") if (abs(sum(p) - 1) > sqrt(.Machine$double.eps)) stop("probabilities must sum to 1.") M <- as.integer(nrow(tmpdat)) cl.n <- apply(tmpdat, 1, sum) phat <- tmpdat/cl.n pbar <- apply(phat,2,mean) dmat <- phat - matrix(rep(p,M), nrow=M, byrow=T) dhat <- colMeans(dmat) if (variance=="emp") { var.hat <- stats::var(dmat) } else { U <- switch(variance, MoM = t(t(dmat)/dhat), sand.null = t(t(phat)/p), sand.est = t(t(phat)/pbar)) Vtmp <- apply(U, 1, function(x) x%*%t(x)) V <- matrix(apply(Vtmp, 1, mean), nrow=length(p)) Hinv <- switch(variance, MoM = MASS::ginv(diag(-1/dhat)), sand.null = MASS::ginv(diag(-pbar/p^2)), sand.est = MASS::ginv(diag(-1/pbar))) var.hat <- Hinv%*%V%*%Hinv } OBSERVED <- pbar EXPECTED <- p names(EXPECTED) <- names(pbar) PARAMETER <- ncol(tmpdat) - 1 STATISTIC <- M*t(dhat)%*%MASS::ginv(var.hat)%*%(dhat) PVAL <- stats::pchisq(STATISTIC, df=PARAMETER, lower.tail=F) DNAME <- paste0(paste0(DNAME, ", M = "), as.character(M)) names(STATISTIC) <- "X-squared" names(PARAMETER) <- "df" METHOD <- paste0("Cluster-weighted chi-squared test for given probabilities with variance est: ", variance) if (any(M*p < 5) && is.finite(PARAMETER)) warning("M*p < 5: Chi-squared approximation may be incorrect") RVAL <- list(statistic = STATISTIC, parameter = PARAMETER, p.value = PVAL, method = METHOD, data.name = DNAME, observed = OBSERVED, expected = EXPECTED, M=M) } else { DNAME <- paste(deparse(substitute(x)), "and", deparse(substitute(y))) if (length(x) != length(y)) stop("'x' and 'y' must have the same length") if (length(x) != length(id)) stop("'id' must have the same length as x and y") OK <- stats::complete.cases(id,x,y) METHOD <- paste0("Cluster-weighted Chi-squared test of independence with variance est: ", variance) x <- factor(x[OK]) y <- factor(y[OK]) id <- factor(id[OK]) M <- length(unique(id)) if ((nlevels(x) < 2L) || (nlevels(y) < 2L)) stop("'x' and 'y' must have at least 2 levels") tmp <- table(x, y, id) o <- prop.table(tmp,3) e <- apply(tmp,3,function(x) { outer(rowSums(x)/sum(x), colSums(x)/sum(x)) }) dim(e) <- dim(o) o.mat <- matrix(as.vector(o), nrow=M, byrow=T) e.mat <- matrix(as.vector(e), nrow=M, byrow=T) d.mat <- o.mat-e.mat o.hat <- colMeans(o.mat) e.hat <- colMeans(e.mat) d.hat <- colMeans(d.mat) OBSERVED <- matrix(o.hat, nrow=nlevels(x), byrow=F) EXPECTED <- matrix(e.hat, nrow=nlevels(x), byrow=F) rownames(OBSERVED) <- rownames(EXPECTED) <- levels(x) colnames(OBSERVED) <- colnames(EXPECTED) <- levels(y) if (variance=="emp") { var.hat <- stats::var(d.mat) } else { U <- switch(variance, MoM = t(t(d.mat)/d.hat), sand.null = t(t(o.mat)/e.hat), sand.est = t(t(o.mat)/o.hat)) Vtmp <- apply(U, 1, function(x) x%*%t(x)) V <- matrix(apply(Vtmp, 1, mean), nrow=(nlevels(y)*nlevels(x))) Hinv <- switch(variance, MoM = MASS::ginv(diag(-1/d.hat)), sand.null = MASS::ginv(diag(-o.hat/e.hat^2)), sand.est = MASS::ginv(diag(-1/o.hat))) var.hat <- Hinv%*%V%*%Hinv } STATISTIC <- M*(t(d.hat) %*% MASS::ginv(var.hat) %*% d.hat) PARAMETER <- (nlevels(x)-1)*(nlevels(y)-1) PVAL <- stats::pchisq(STATISTIC, df=PARAMETER, lower=F) DNAME <- paste0(paste0(DNAME, ", M = "), as.character(M)) names(STATISTIC) <- "X-squared" names(PARAMETER) <- "df" RVAL <- list(statistic = STATISTIC, parameter = PARAMETER, p.value = PVAL, method = METHOD, data.name = DNAME, M = M, observed = OBSERVED, expected = EXPECTED) } DNAME <- paste0(paste0(DNAME, "M = "), as.character(M)) class(RVAL) <- "htest" if (M < 30) warning('Number of clusters < 30. Chi-squared approximation may be incorrect') return(RVAL) }
.powellTestNLP <- function() { start <- c(-2, 2, 2, -1, -1) fun <- function(x) { exp(x[1]*x[2]*x[3]*x[4]*x[5]) } eqFun <- list( function(x) x[1]*x[1]+x[2]*x[2]+x[3]*x[3]+x[4]*x[4]+x[5]*x[5], function(x) x[2]*x[3]-5*x[4]*x[5], function(x) x[1]*x[1]*x[1]+x[2]*x[2]*x[2]) eqFun.bound <- c(10, 0, -1) ans.donlp = donlp2NLP(start, fun, eqFun = eqFun, eqFun.bound = eqFun.bound) ans.solnp = solnpNLP(start, fun, eqFun = eqFun, eqFun.bound = eqFun.bound) ans.nlminb = nlminb2NLP(start, fun, eqFun = eqFun, eqFun.bound = eqFun.bound) result.par = round(rbind( ans.donlp$solution, ans.solnp$solution, ans.nlminb$solution), 3) result.fun = c( fun(ans.donlp$solution), fun(ans.solnp$solution), fun(ans.nlminb$solution)) cbind(result.par, result.fun) } .wright4TestNLP <- function() { start <- c(1, 1, 1, 1, 1) fun <- function(x){ (x[1]-1)^2+(x[1]-x[2])^2+(x[2]-x[3])^3+(x[3]-x[4])^4+(x[4]-x[5])^4} eqFun = list( function(x) x[1]+x[2]*x[2]+x[3]*x[3]*x[3], function(x) x[2]-x[3]*x[3]+x[4], function(x) x[1]*x[5] ) eqFun.bound = c(2+3*sqrt(2), -2+2*sqrt(2), 2) ans.donlp = donlp2NLP(start, fun, eqFun = eqFun, eqFun.bound = eqFun.bound) ans.solnp = solnpNLP(start, fun, eqFun = eqFun, eqFun.bound = eqFun.bound) ans.nlminb = nlminb2NLP(start, fun, eqFun = eqFun, eqFun.bound = eqFun.bound) result.par = round(rbind( ans.donlp$solution, ans.solnp$solution, ans.nlminb$solution), 3) result.fun = c( fun(ans.donlp$solution), fun(ans.solnp$solution), fun(ans.nlminb$solution)) cbind(result.par, result.fun) } .boxTestNLP <- function() { start <- c(1.1, 1.1, 9) fun <- function(x) { -x[1]*x[2]*x[3] } par.lower = rep(1, 3) par.upper = rep(10, 3) eqFun <- list( function(x) 4*x[1]*x[2]+2*x[2]*x[3]+2*x[3]*x[1] ) eqFun.bound = 100 ans.donlp = donlp2NLP(start, fun, par.lower = par.lower, par.upper = par.upper, eqFun = eqFun, eqFun.bound = eqFun.bound) ans.solnp = solnpNLP(start, fun, par.lower = par.lower, par.upper = par.upper, eqFun = eqFun, eqFun.bound = eqFun.bound) ans.nlminb = nlminb2NLP(start, fun, par.lower = par.lower, par.upper = par.upper, eqFun = eqFun, eqFun.bound = eqFun.bound) result.par = round(rbind( ans.donlp$solution, ans.solnp$solution, ans.nlminb$solution), 3) result.fun = c( fun(ans.donlp$solution), fun(ans.solnp$solution), fun(ans.nlminb$solution)) cbind(result.par, result.fun) } .wright9TestNLP <- function() { start <- c(1, 1, 1, 1, 1) fun <- function(x){ 10*x[1]*x[4]-6*x[3]*x[2]*x[2]+x[2]*(x[1]*x[1]*x[1])+ 9*sin(x[5]-x[3])+x[5]^4*x[4]*x[4]*x[2]*x[2]*x[2] } ineqFun <- list( function(x) x[1]*x[1]+x[2]*x[2]+x[3]*x[3]+x[4]*x[4]+x[5]*x[5], function(x) x[1]*x[1]*x[3]-x[4]*x[5], function(x) x[2]*x[2]*x[4]+10*x[1]*x[5]) ineqFun.lower = c(-100, -2, 5) ineqFun.upper = c( 20, 100, 100) ans.donlp = donlp2NLP(start, fun, ineqFun = ineqFun, ineqFun.lower = ineqFun.lower, ineqFun.upper = ineqFun.upper) ans.solnp = solnpNLP(start, fun, ineqFun = ineqFun, ineqFun.lower = ineqFun.lower, ineqFun.upper = ineqFun.upper) ans.nlminb = nlminb2NLP(start, fun, ineqFun = ineqFun, ineqFun.lower = ineqFun.lower, ineqFun.upper = ineqFun.upper) result.par = round(rbind( ans.donlp$solution, ans.solnp$solution, ans.nlminb$solution), 3) result.fun = c( fun(ans.donlp$solution), fun(ans.solnp$solution), fun(ans.nlminb$solution)) cbind(result.par, result.fun) } .alkylationTestNLP <- function() { start <- c(17.45, 12, 110, 30.5, 19.74, 89.2, 92.8, 8, 3.6, 145.2) fun <- function(x) { -0.63*x[4]*x[7]+50.4*x[1]+3.5*x[2]+x[3]+33.6*x[5] } par.lower <- c( 0, 0, 0, 10, 0, 85, 10, 3, 1, 145) par.upper <- c(20, 16, 120, 50, 20, 93, 95,12, 4, 162) eqFun <- list( function(x) 98*x[3]-0.1*x[4]*x[6]*x[9]-x[3]*x[6], function(x) 1000*x[2]+100*x[5]-100*x[1]*x[8], function(x) 122*x[4]-100*x[1]-100*x[5]) eqFun.bound = c(0, 0, 0) ineqFun <- list( function(x) (1.12*x[1]+0.13167*x[1]*x[8]-0.00667*x[1]*x[8]*x[8])/x[4], function(x) (1.098*x[8]-0.038*x[8]*x[8]+0.325*x[6]+57.25)/x[7], function(x) (-0.222*x[10]+35.82)/x[9], function(x) (3*x[7]-133)/x[10]) ineqFun.lower = c( 0.99, 0.99, 0.9, 0.99) ineqFun.upper = c(100/99, 100/99, 10/9, 100/99) ans.donlp = donlp2NLP(start, fun, par.lower = par.lower, par.upper = par.upper, eqFun = eqFun, eqFun.bound = eqFun.bound, ineqFun = ineqFun, ineqFun.lower = ineqFun.lower, ineqFun.upper = ineqFun.upper) ans.solnp = solnpNLP(start, fun, par.lower = par.lower, par.upper = par.upper, eqFun = eqFun, eqFun.bound = eqFun.bound, ineqFun = ineqFun, ineqFun.lower = ineqFun.lower, ineqFun.upper = ineqFun.upper) ans.nlminb = nlminb2NLP(start, fun, par.lower = par.lower, par.upper = par.upper, eqFun = eqFun, eqFun.bound = eqFun.bound, ineqFun = ineqFun, ineqFun.lower = ineqFun.lower, ineqFun.upper = ineqFun.upper) result.par = round(rbind( ans.donlp$solution, ans.solnp$solution, ans.nlminb$solution), 3) result.fun = c( fun(ans.donlp$solution), fun(ans.solnp$solution), fun(ans.nlminb$solution)) cbind(result.par, result.fun) } .entropyTestNLP <- function() { set.seed(1953) start <- runif(10, 0, 1) fun <- function(x) { m = length(x) f = -sum(log(x)) vnorm = sum((x-1)^2)^(1/2) f - log(vnorm + 0.1) } par.lower <- rep(0, 10) eqFun <- list( function(x) sum(x) ) eqFun.bound <- 10 ans.donlp = donlp2NLP(start, fun, par.lower = par.lower, eqFun = eqFun, eqFun.bound = eqFun.bound) ans.solnp = solnpNLP(start, fun, par.lower = par.lower, eqFun = eqFun, eqFun.bound = eqFun.bound) ans.nlminb = nlminb2NLP(start, fun, par.lower = par.lower, eqFun = eqFun, eqFun.bound = eqFun.bound) result.par = round(rbind( ans.donlp$solution, ans.solnp$solution, ans.nlminb$solution), 3) result.fun = c( fun(ans.donlp$solution), fun(ans.solnp$solution), fun(ans.nlminb$solution)) cbind(result.par, result.fun) } .rosensuzukiTestNLP <- function() { start <- c(1, 1, 1, 1) fun <- function(x) x[1]*x[1]+x[2]*x[2]+2*x[3]*x[3]+x[4]*x[4]-5*x[1]-5*x[2]-21*x[3]+7*x[4] ineqFun <- list( function(x) 8-x[1]*x[1]-x[2]*x[2]-x[3]*x[3]-x[4]*x[4]-x[1]+x[2]-x[3]+x[4], function(x) 10-x[1]*x[1]-2*x[2]*x[2]-x[3]*x[3]-2*x[4]*x[4]+x[1]+x[4], function(x) 5-2*x[1]*x[1]-x[2]*x[2]-x[3]*x[3]-2*x[1]+x[2]+x[4] ) ineqFun.lower <- rep( 0, 3) ineqFun.upper <- rep(10, 3) ans.donlp = donlp2NLP(start, fun, ineqFun = ineqFun, ineqFun.lower = ineqFun.lower, ineqFun.upper = ineqFun.upper) ans.solnp = solnpNLP(start, fun, ineqFun = ineqFun, ineqFun.lower = ineqFun.lower, ineqFun.upper = ineqFun.upper) ans.nlminb = nlminb2NLP(start, fun, ineqFun = ineqFun, ineqFun.lower = ineqFun.lower, ineqFun.upper = ineqFun.upper) result.par = round(rbind( ans.donlp$solution, ans.solnp$solution, ans.nlminb$solution), 3) result.fun = c( fun(ans.donlp$solution), fun(ans.solnp$solution), fun(ans.nlminb$solution)) cbind(result.par, result.fun) } .sharperatioTestNLP <- function() { dataSet <- data("LPP2005REC", package="timeSeries", envir=environment()) LPP2005REC <- get(dataSet, envir=environment()) ret <- as.matrix(LPP2005REC[,2:7]) Mean <- colMeans(ret) Cov <- cov(ret) start <- rep(1/6, times = 6) fun <- function(x) { return = (Mean %*% x)[[1]] risk = sqrt ( (t(x) %*% Cov %*% x)[[1]] ) -return/risk } par.lower <- rep(0, 6) par.upper <- rep(1, 6) eqFun <- list( function(x) sum(x) ) eqFun.bound = 1 ans.donlp <- donlp2NLP(start, fun, par.lower = par.lower, par.upper = par.upper, eqFun = eqFun, eqFun.bound = eqFun.bound ) ans.solnp <- solnpNLP(start, fun, par.lower = par.lower, par.upper = par.upper, eqFun = eqFun, eqFun.bound = eqFun.bound) ans.nlminb <- Rnlminb2::nlminb2NLP(start, fun, par.lower = par.lower, par.upper = par.upper, eqFun = eqFun, eqFun.bound = eqFun.bound) result.par = round(rbind( ans.donlp$solution, ans.solnp$solution, ans.nlminb$solution), 3) result.fun = c( fun(ans.donlp$solution), fun(ans.solnp$solution), fun(ans.nlminb$solution)) cbind(result.par, result.fun) result.par <- 100*round(rbind( ans.donlp$solution, ans.solnp$solution, ans.nlminb$solution), 4) result.fun <- c( fun(ans.donlp$solution), fun(ans.solnp$solution), fun(ans.nlminb$solution)) cbind(result.par, result.fun) } .rachevratioTestNLP <- function() { dataSet <- data("LPP2005REC", package="timeSeries", envir=environment()) LPP2005REC <- get(dataSet, envir=environment()) ret = as.matrix(LPP2005REC[, 2:7]) Mean = colMeans(ret) Cov = cov(ret) set.seed(1953) r = runif(6) start <- r/sum(r) start <- rep(1/6, times = 6) .VaR <- function(x) { quantile(x, probs = 0.05, type = 1) } .CVaR <- function(x) { VaR = .VaR(x) VaR - 0.5 * mean(((VaR-ret) + abs(VaR-ret))) / 0.05 } fun <- function(x) { port = as.vector(ret %*% x) ans = (-.CVaR(-port) / .CVaR(port))[[1]] ans} par.lower = rep(0, 6) par.upper = rep(1, 6) eqFun <- list( function(x) sum(x) ) eqFun.bound = 1 ans.donlp = donlp2NLP(start, fun, par.lower = par.lower, par.upper = par.upper, eqFun = eqFun, eqFun.bound = eqFun.bound) ans.solnp = solnpNLP(start, fun, par.lower = par.lower, par.upper = par.upper, eqFun = eqFun, eqFun.bound = eqFun.bound) ans.nlminb = nlminb2NLP(start, fun, par.lower = par.lower, par.upper = par.upper, eqFun = eqFun, eqFun.bound = eqFun.bound) result.par = 100*round(rbind( ans.donlp$solution, ans.solnp$solution, ans.nlminb$solution), 4) result.fun = c( fun(ans.donlp$solution), fun(ans.solnp$solution), fun(ans.nlminb$solution)) cbind(result.par, result.fun) } .boxmarkowitzTestNLP <- function() { dataSet <- data("LPP2005REC", package="timeSeries", envir=environment()) LPP2005REC <- get(dataSet, envir=environment()) ret <- 100 * as.matrix(LPP2005REC[, 2:7]) Mean <- colMeans(ret) Cov <- cov(ret) targetReturn <- mean(Mean) start <- rep(1/6, times = 6) objective <- function(x) { risk <- (t(x) %*% Cov %*% x)[[1]] risk } fun <- objective par.lower <- rep(0, 6) par.upper <- rep(1, 6) eqFun <- list( function(x) sum(x), function(x) (Mean %*% x)[[1]] ) eqFun.bound = c(1, targetReturn) ans.donlp = donlp2NLP(start, objective, par.lower = par.lower, par.upper = par.upper, eqFun = eqFun, eqFun.bound = eqFun.bound) ans.solnp = solnpNLP(start, objective, par.lower = par.lower, par.upper = par.upper, eqFun = eqFun, eqFun.bound = eqFun.bound) ans.nlminb = nlminb2NLP(start, objective, par.lower = par.lower, par.upper = par.upper, eqFun = eqFun, eqFun.bound = eqFun.bound) result.par <- 100*round(rbind( ans.donlp$solution, ans.solnp$solution, ans.nlminb$solution), 4) result.fun <- c( fun(ans.donlp$solution), fun(ans.solnp$solution), fun(ans.nlminb$solution)) cbind(result.par, result.fun) } .groupmarkowitzTestNLP <- function() { dataSet <- data("LPP2005REC", package="timeSeries", envir=environment()) LPP2005REC <- get(dataSet, envir=environment()) ret <- 100 * as.matrix(LPP2005REC[, 2:7]) Mean <- colMeans(ret) Cov <- cov(ret) targetReturn <- mean(Mean) start <- rep(1/6, times = 6) start[1]+start[4] start[2]+start[5]+start[6] start2 <- c(0, 0, 0.3, 0.3, 0, 0.4) start2 <- start/sum(start2) sum(start2) start2[1]+start2[4] start2[2]+start2[5]+start2[6] fun <- function(x) { risk = (t(x) %*% Cov %*% x)[[1]] risk } par.lower <- rep(0, 6) par.upper <- rep(1, 6) eqFun <- list( function(x) sum(x), function(x) (Mean %*% x)[[1]] ) eqFun.bound = c(1, targetReturn) ineqFun <- list( function(x) x[1]+x[4], function(x) x[2]+x[5]+x[6]) ineqFun.lower <- c( 0.3, 0.0) ineqFun.upper <- c( 1.0, 0.6) ans.donlp = donlp2NLP(start, fun, par.lower = par.lower, par.upper = par.upper, eqFun = eqFun, eqFun.bound = eqFun.bound, ineqFun = ineqFun, ineqFun.lower = ineqFun.lower, ineqFun.upper = ineqFun.upper) ans.solnp = solnpNLP(start, fun, par.lower = par.lower, par.upper = par.upper, eqFun = eqFun, eqFun.bound = eqFun.bound, ineqFun = ineqFun, ineqFun.lower = ineqFun.lower, ineqFun.upper = ineqFun.upper) ans.nlminb = nlminb2NLP(start, fun, par.lower = par.lower, par.upper = par.upper, eqFun = eqFun, eqFun.bound = eqFun.bound, ineqFun = ineqFun, ineqFun.lower = ineqFun.lower, ineqFun.upper = ineqFun.upper) result.par = 100*round(rbind( ans.donlp$solution, ans.solnp$solution, ans.nlminb$solution), 4) result.fun = c( fun(ans.donlp$solution), fun(ans.solnp$solution), fun(ans.nlminb$solution)) cbind(result.par, result.fun) }
source("ESEUR_config.r") library("chngpt") pal_col=rainbow(4) comp_recalls=read.csv(paste0(ESEUR_dir, "regression/Alemzadeh-Computer_Related_Recalls.csv.xz"), as.is=TRUE) comp_recalls$Date=as.Date(comp_recalls$Date, format="%b-%d-%Y") t1=cut(comp_recalls$Date, breaks=72) t2=table(t1) x_axis=1:length(t2) y_axis=as.vector(t2) y_bounds=range(y_axis) l_mod=glm(y_axis ~ x_axis) orig_pred=predict(l_mod) t2[33]=round(mean(y_axis)) t2[67]=round(mean(y_axis)) y_axis=as.vector(t2) y_bounds=range(y_axis) plot(t2, type="p", col=pal_col[3], ylim=y_bounds, xlab="Fortnights", ylab="Recalls") recall_subset=subset(comp_recalls, Date <= as.Date("2010-12-31")) t1=cut(comp_recalls$Date, breaks=60) t2=table(t1) bined_recalls=data.frame(fortnight=1:length(t2), recalls=as.vector(t2)) fit=chngptm(recalls ~ 1, ~fortnight, family="gaussian", data=bined_recalls, type="segmented", var.type="bootstrap", save.boot=TRUE) plot(fit, which=1)
wrap_old_cache <- function(x) { if (!is_old_cache(x)) { stop("`x` must be an old-style cache.", call. = FALSE) } list( digest = x$digest, reset = x$reset, set = x$set, get = function(key) { if (!x$has_key(key)) { return(key_missing()) } x$get(key) }, exists = x$has_key, remove = x$drop_key, keys = x$keys ) } is_old_cache <- function(x) { is.function(x$digest) && is.function(x$set) && is.function(x$get) && is.function(x$has_key) }
STAT2 <- function() { rmarkdown::run(system.file("img", "STAT2.Rmd", package = "STAT2")) Sys.setenv("R_TESTS" = "") }
context("COR") set.seed(SEED) N <- 101 M <- 43 x <- matrix(rnorm(N * M, 100, 5), N) test_that("equality with cor", { for (t in TEST.TYPES) { X <- `if`(t == "raw", asFBMcode(x), big_copy(x, type = t)) K <- big_cor(X, block.size = 10) expect_equal(K[], cor(X[])) } }) test_that("equality with cor with half of the data", { ind <- sample(M, M / 2) for (t in TEST.TYPES) { X <- `if`(t == "raw", asFBMcode(x), big_copy(x, type = t)) K <- big_cor(X, ind.col = ind, block.size = 10) expect_equal(K[], cor(X[, ind])) } }) test_that("equality with cor with half of the data", { ind <- sample(N, N / 2) for (t in TEST.TYPES) { X <- `if`(t == "raw", asFBMcode(x), big_copy(x, type = t)) K <- big_cor(X, ind.row = ind, block.size = 10) expect_equal(K[], cor(X[ind, ])) } })