code
stringlengths
1
13.8M
binary_fun <- function(beta,rho,x,id, corstr){ response=c() N=length(unique(id)) for(i in 1:N){ mu_i <- 1/(1+exp(-(x[which(id==i),]%*%beta))) if(corstr=="independence"){ R_i=diag(1,length(mu_i)) } else if (corstr=="exchangeable"){ R_i=diag(1,length(mu_i))+matrix(rho,ncol=length(mu_i),nrow=length(mu_i))-diag(rho,length(mu_i)) } else { H <- abs(outer(1:length(mu_i),1:length(mu_i), "-")) R_i=rho^H } response <- c(response, rmvbin(1, margprob = as.vector(mu_i), bincorr = R_i)) } data=cbind(id,x,response) data=data.frame(data) return(data) }
library(knotR) filename <- "9_44.svg" a <- reader(filename) ou944 <- matrix(c( 8,2, 20,10, 11,17, 16,21, 3,15, 22,14, 13,5, 23,7, 4,21 ), byrow=TRUE,ncol=2) sym944 <- symmetry_object(a,xver=18) a <- symmetrize(a,sym944) jj <- knotoptim(filename, symobj=sym944, ou = ou944, prob=0, control=list(trace=100,maxit=100000), useNLM=FALSE ) write_svg(jj,filename,safe=FALSE) dput(jj,file=sub('.svg','.S',filename))
xpData <- local(get(load("xp_data.rda")))
MakeSnapshots <- function(info, outputdir = './anim', prefix = 'snapshot', nums = 1:info$N, dt = 0.1, makesec1 = TRUE, makesec2 = TRUE, makesurf = TRUE, res = 96, fn_topomap = 'topomap.png', width = 480, height = NaN, asp = 1, pointsize = 12){ prettytitle = function(x, m1, m2){ digits = getOption('digits') options(digits = 22) nd2 = floor(log(m2, 10)) + 1 nd1 = nchar(as.character(m1)) - regexpr('\\.', m1) start = 7 - (nd2-1) end = 7 + nd1 + (m1 < 1) y=substr(as.character(x+1e6+1e-6), start, end) if(nd2 >= 2){ for(i in 1:(nd2-1)){ if(x < 10^(nd2-i)){ substr(y, i, i) = ' ' } } } options(digits = digits) y } N = info$N topo = info$topo coords_sec1 = info$coords_sec1 coords_sec2 = info$coords_sec2 coords_surf = info$coords_surf surfline_sec1 = info$surfline_sec1 surfline_sec2 = info$surfline_sec2 mai=c(0.8,0.8,0.2,0.2) zz_sec1 = unique(coords_sec1[,3]) zz_sec2 = unique(coords_sec2[,3]) dist_sec2 = surfline_sec2$h if(is.na(height)){ width_plot = width - res * (mai[2]+mai[4]) if(makesec1){ height_sec1 = diff(range(zz_sec1))/max(surfline_sec1$h) * width_plot + res * (mai[1]+mai[3]) } if(makesec2){ height_sec2 = diff(range(zz_sec2))/max(dist_sec2) * width_plot + res * (mai[1]+mai[3]) } height_surf = diff(range(topo$y))/diff(range(topo$x)) * width_plot + res * (mai[1]+mai[3]) } mycols = colorRampPalette(c('darkblue','blue', 'white', 'orange', 'red'),bias=1,space=c('rgb')) png(filename=fn_topomap,width=4,height=length(topo$y)/length(topo$x)*4,units='in',res=200) par(omi=c(0,0,0,0),mai=mai,mgp=c(2,0.5,0),tck=-0.01) par(font.lab=2,font.axis=2,cex.lab=1.5,cex.axis=1.2) image(topo,col=topo.colors(50),xlab='X (m)',ylab='Y (m)', useRaster = TRUE) contour(topo,nlevels=10,lwd=1,add=TRUE) dev.off() for(j in nums){ ndigits_fn = 1 + floor(log(N, 10)) png_num = formatC(j, flag = 0, width = ndigits_fn) main = prettytitle(j*dt, dt, N*dt) print(paste(j, 'of', N, ': t =', main)) fn_sec1 = info$fn_sec1list[j] fn_sec2 = info$fn_sec2list[j] fn_sur = info$fn_surlist[j] if(makesec1){ con=file(fn_sec1,"rb") PP0=readBin(con,what=numeric(),n=dim(coords_sec1)[1],size=4) close(con) PP=matrix(PP0,ncol=length(zz_sec1))/info$MASKsec1 png(filename=paste(outputdir, '/', prefix, '_sec1_', png_num, '.png',sep=''),width=width, height=height_sec1, res=res, pointsize = pointsize) par(omi=c(0,0,0,0),mai=mai,mgp=c(2,0.5,0),tck=-0.01) par(font.lab=2,font.axis=2,cex.lab=1.5,cex.axis=1.2) image(surfline_sec1$h,sort(zz_sec1),PP[,order(zz_sec1)],xlab='Distance (m)',ylab='Elevation (m)',col=mycols(100), breaks = info$breaks_sec1, main = main, useRaster = TRUE, asp = asp) lines(surfline_sec1$h,surfline_sec1$z,col='black',lwd=2) dev.off() } if(makesec2){ con=file(fn_sec2,"rb") PP0=readBin(con,what=numeric(),n=dim(coords_sec2)[1],size=4) close(con) PP=matrix(PP0,ncol=length(zz_sec2))/info$MASKsec2 mai=c(0.8,0.8,0.2,0.2) png(filename=paste(outputdir, '/', prefix, '_sec2_', png_num, '.png',sep=''),width=width, height=height_sec2, res=res, pointsize = pointsize) par(omi=c(0,0,0,0),mai=mai,mgp=c(2,0.5,0),tck=-0.01) par(font.lab=2,font.axis=2,cex.lab=1.5,cex.axis=1.2) image(surfline_sec2$h, sort(zz_sec2),PP[,order(zz_sec2)],xlab='Distance (m)',ylab='Elevation (m)',col=mycols(100), breaks = info$breaks_sec2, main = main, useRaster = TRUE, asp = asp) lines(surfline_sec2$h, surfline_sec2$z,col='black',lwd=2) dev.off() } if(makesurf){ con=file(fn_sur,"rb") PP0=readBin(con,what=numeric(),n=nrow(coords_surf),size=4) close(con) PP=matrix(PP0,ncol=ncol(info$MASKsurf))/info$MASKsurf mai=c(0.8,0.8,0.2,0.2) png(filename=paste(outputdir, '/', prefix, '_surf_', png_num, '.png',sep=''),width=width, height=height_surf, res=res, pointsize = pointsize) par(omi=c(0,0,0,0),mai=mai,mgp=c(2,0.5,0),tck=-0.01) par(font.lab=2,font.axis=2,cex.lab=1.5,cex.axis=1.2) image(topo$x,topo$y,PP,xlab='X (m)',ylab='Y (m)',col=mycols(100), breaks = info$breaks_surf, main = main, useRaster = TRUE, asp = asp) contour(topo,nlevels=10,lwd=1,add=TRUE) dev.off() } } }
tk_tbl <- function(data, preserve_index = TRUE, rename_index = "index", timetk_idx = FALSE, silent = FALSE, ...) { UseMethod("tk_tbl", data) } tk_tbl.data.frame <- function(data, preserve_index = TRUE, rename_index = "index", timetk_idx = FALSE, silent = FALSE, ...) { if (preserve_index == TRUE) { idx <- rownames(data) if (!is.null(idx) && !identical(as.character(idx), as.character(1:nrow(as.data.frame(data)))) ) { ret <- data %>% as.data.frame() %>% tibble::rownames_to_column(var = rename_index) %>% tibble::as_tibble(...) if (any(vapply(ret, is.character, logical(1)))) { ret <- suppressMessages(readr::type_convert(ret)) } } else { if (!silent) warning("Warning: No index to preserve. Object otherwise converted to tibble successfully.") ret <- tibble::as_tibble(data, ...) } } else { ret <- tibble::as_tibble(data, ...) } return(ret) } tk_tbl.xts <- function(data, preserve_index = TRUE, rename_index = "index", timetk_idx = FALSE, silent = FALSE, ...) { ret <- tk_tbl(zoo::as.zoo(data), preserve_index, rename_index, timetk_idx, silent, ...) return(ret) } tk_tbl.matrix <- function(data, preserve_index = TRUE, rename_index = "index", timetk_idx = FALSE, silent = FALSE, ...) { ret <- tk_tbl(as.data.frame(data), preserve_index, rename_index, timetk_idx, silent, ...) return(ret) } tk_tbl.zoo <- function(data, preserve_index = TRUE, rename_index = "index", timetk_idx = FALSE, silent = FALSE, ...) { if (preserve_index == TRUE) { if (!is.null(zoo::index(data))) { idx <- zoo::index(data) } else { idx = NULL } if (!is.null(idx) && !identical(as.character(idx), as.character(1:nrow(as.data.frame(data)))) ) { ret <- tibble::as_tibble(data, ...) %>% tibble::add_column(idx, .before = 1) if (!is.null(rename_index)) colnames(ret)[[1]] <- rename_index if (any(vapply(ret, is.character, logical(1)))) { ret <- suppressMessages(readr::type_convert(ret)) } } else { if (!silent) warning(paste0("Warning: No index to preserve. ", "Object otherwise converted to tibble successfully.")) ret <- tibble::as_tibble(data, ...) } } else { ret <- tibble::as_tibble(data, ...) } return(ret) } tk_tbl.zooreg <- function(data, preserve_index = TRUE, rename_index = "index", timetk_idx = FALSE, silent = FALSE, ...) { if (timetk_idx && preserve_index) { first_val <- rownames(data)[[1]] if (!is.null(first_val)) { index <- tk_index(data, timetk_idx = TRUE) ret <- tk_xts(data, order.by = index) %>% tk_tbl(preserve_index = preserve_index, rename_index = rename_index, timetk_idx = timetk_idx, silent = silent, ... = ...) } else { if (!silent) warning("No `timetk index` attribute found. Using regularized index.") ret <- tk_tbl(zoo::as.zoo(data), preserve_index, rename_index, timetk_idx, silent, ...) } } else { ret <- tk_tbl(zoo::as.zoo(data), preserve_index, rename_index, timetk_idx, silent, ...) } return(ret) } tk_tbl.ts <- function(data, preserve_index = TRUE, rename_index = "index", timetk_idx = FALSE, silent = FALSE, ...) { if (timetk_idx && preserve_index) { index_attr <- attr(data, "index") if (!is.null(index_attr)) { index <- tk_index(data, timetk_idx = TRUE) ret <- tk_xts(data, order.by = index) %>% tk_tbl(preserve_index = preserve_index, rename_index = rename_index, timetk_idx = timetk_idx, silent = silent, ... = ...) } else { ret <- tk_tbl(zoo::as.zoo(data), preserve_index, rename_index, timetk_idx, silent, ...) } } else { ret <- tk_tbl(zoo::as.zoo(data), preserve_index, rename_index, timetk_idx, silent, ...) } return(ret) } tk_tbl.msts <- function(data, preserve_index = TRUE, rename_index = "index", timetk_idx = FALSE, silent = FALSE, ...) { ret <- tk_tbl(zoo::as.zoo(data), preserve_index, rename_index, timetk_idx, silent, ...) return(ret) } tk_tbl.timeSeries <- function(data, preserve_index = TRUE, rename_index = "index", timetk_idx = FALSE, silent = FALSE, ...) { ret <- tk_tbl(as.data.frame(data), preserve_index, rename_index, timetk_idx, silent, ...) return(ret) } tk_tbl.irts <- function(data, preserve_index = TRUE, rename_index = "index", timetk_idx = FALSE, silent = FALSE, ...) { ret <- tk_tbl(zoo::as.zoo(data), preserve_index, rename_index, timetk_idx, silent, ...) return(ret) } tk_tbl.default <- function(data, preserve_index = TRUE, rename_index = "index", timetk_idx = FALSE, silent = FALSE, ...) { ret <- tk_tbl(as.data.frame(data), preserve_index, rename_index, timetk_idx, silent, ...) return(ret) }
context("Performance optimizations") test_that("Optimized version of wt.bases.dog is equal to original", { for (param in 1:10) { expect_equal( biwavelet:::wt.bases.dog(1:10, 2, param), biwavelet:::rcpp_wt_bases_dog(1:10, 2, param) ) expect_equal( biwavelet:::wt.bases.dog(1:10, 1 / 3, param), biwavelet:::rcpp_wt_bases_dog(1:10, 1 / 3, param) ) } }) test_that("Optimized version of wt.bases.paul is equal to original", { for (param in 1:10) { expect_equal( biwavelet:::wt.bases.paul(1:10, 2, param), biwavelet:::rcpp_wt_bases_paul(1:10, 2, param) ) expect_equal( biwavelet:::wt.bases.paul(1:10, 1 / 3, param), biwavelet:::rcpp_wt_bases_paul(1:10, 1 / 3, param) ) } }) test_that("Optimized version of wt.bases.morlet is equal to original", { for (param in 1:10) { expect_equal( biwavelet:::wt.bases.morlet(1:10, 2, param), biwavelet:::rcpp_wt_bases_morlet(1:10, 2, param) ) expect_equal( biwavelet:::wt.bases.morlet(1:10, 1 / 3, param), biwavelet:::rcpp_wt_bases_morlet(1:10, 1 / 3, param) ) } }) test_that("Parameter m outside supported interval should fail", { FMIN <- -2 FMAX <- 11 ERRMSG <- "must be within" expect_error(biwavelet:::rcpp_wt_bases_dog(1:10, 2, FMIN), regexp = ERRMSG) expect_error(biwavelet:::rcpp_wt_bases_dog(1:10, 2, FMAX), regexp = ERRMSG) expect_error(biwavelet:::rcpp_wt_bases_morlet(1:10, 2, FMIN), regexp = ERRMSG) expect_error(biwavelet:::rcpp_wt_bases_morlet(1:10, 2, FMAX), regexp = ERRMSG) expect_error(biwavelet:::rcpp_wt_bases_paul(1:10, 2, FMIN), regexp = ERRMSG) expect_error(biwavelet:::rcpp_wt_bases_paul(1:10, 2, FMAX), regexp = ERRMSG) }) test_that("Default 'param' values for rcpp_wt_bases", { expect_equal( biwavelet:::rcpp_wt_bases_dog(1:10, 2, -1), biwavelet:::rcpp_wt_bases_dog(1:10, 2, 2)) expect_equal( biwavelet:::rcpp_wt_bases_morlet(1:10, 2, -1), biwavelet:::rcpp_wt_bases_morlet(1:10, 2, 6)) expect_equal( biwavelet:::rcpp_wt_bases_paul(1:10, 2, -1), biwavelet:::rcpp_wt_bases_paul(1:10, 2, 4)) }) test_that("replacing seq(1,N,1) with 1:N", { m <- J1 <- npad <- n.obs <- num_waves <- 17 expect_equal( 2:(2 * m - 1), seq(2, 2 * m - 1, 1) ) expect_equal( 1:(J1 + 1), seq(1, J1 + 1, 1) ) expect_equal( 1:as.integer(npad / 2), seq(1, as.integer(npad / 2), 1) ) expect_equal( as.integer((npad - 1) / 2):1, seq(as.integer((npad - 1) / 2), 1, -1) ) expect_equal( 1:((n.obs + 1) / 2 - 1), seq(1, (n.obs + 1) / 2 - 1) ) expect_equal( floor(n.obs / 2 - 1):1, seq(floor(n.obs / 2 - 1), 1, -1) ) expect_equal( 1:num_waves, seq(from = 1, to = num_waves, by = 1) ) })
context("test-form_tails") expect_self_x_tbl <- function(pdqr_f) { for (method in methods_tails) { for (dir in c("both", "left", "right")) { expect_equal_x_tbl(form_tails(pdqr_f, 0, method, dir), pdqr_f) } } } expect_dirac <- function(pdqr_f, x_vec) { max_levels <- c("both" = 0.5, "left" = 1, "right" = 1) for (method in methods_tails) { for (dir in c("both", "left", "right")) { expect_equal_x_tbl( form_tails(pdqr_f, max_levels[dir], method, dir), new_pdqr_by_ref(pdqr_f)(x_vec[dir], meta_type(pdqr_f)) ) } } } expect_error_negative_level <- function(pdqr_f) { for (method in methods_tails) { for (dir in c("both", "left", "right")) { expect_error( form_tails(pdqr_f, -0.1, method = method, direction = dir), "`level`.*negative" ) } } } cur_dis <- new_d(data.frame(x = 1:4, prob = (1:4) / 10), "discrete") cur_con <- new_d(data.frame(x = 0:1, y = c(1, 1)), "continuous") test_that("form_tails works with `method='trim'` and 'discrete' type", { expect_ref_x_tbl( form_tails(cur_dis, 0.1, "trim", "both"), data.frame(x = 2:4, prob = c(0.2, 0.3, 0.3) / 0.8) ) expect_ref_x_tbl( form_tails(cur_dis, 0.15, "trim", "both"), data.frame(x = 2:4, prob = c(0.15, 0.3, 0.25) / 0.7) ) expect_ref_x_tbl( form_tails(cur_dis, 0.1, "trim", "left"), data.frame(x = 2:4, prob = c(0.2, 0.3, 0.4) / 0.9) ) expect_ref_x_tbl( form_tails(cur_dis, 0.15, "trim", "left"), data.frame(x = 2:4, prob = c(0.15, 0.3, 0.4) / 0.85) ) expect_ref_x_tbl( form_tails(cur_dis, 0.8, "trim", "left"), data.frame(x = 4, prob = 1) ) expect_ref_x_tbl( form_tails(cur_dis, 0.4, "trim", "right"), data.frame(x = 1:3, prob = c(0.1, 0.2, 0.3) / 0.6) ) expect_ref_x_tbl( form_tails(cur_dis, 0.45, "trim", "right"), data.frame(x = 1:3, prob = c(0.1, 0.2, 0.25) / 0.55) ) expect_ref_x_tbl( form_tails(cur_dis, 0.8, "trim", "right"), data.frame(x = 1:2, prob = c(0.5, 0.5)) ) }) test_that("form_tails works with `method='trim'` and 'continuous' type", { expect_ref_x_tbl( form_tails(cur_con, 0.05, "trim", "both"), data.frame(x = c(0.05, 0.95), y = c(1, 1) / 0.9) ) expect_ref_x_tbl( form_tails(cur_con, 0.4, "trim", "both"), data.frame(x = c(0.4, 0.6), y = c(1, 1) / 0.2) ) expect_ref_x_tbl( form_tails(cur_con, 0.05, "trim", "left"), data.frame(x = c(0.05, 1), y = c(1, 1) / 0.95) ) expect_ref_x_tbl( form_tails(cur_con, 0.8, "trim", "left"), data.frame(x = c(0.8, 1), y = c(1, 1) / 0.2) ) expect_ref_x_tbl( form_tails(cur_con, 0.05, "trim", "right"), data.frame(x = c(0, 0.95), y = c(1, 1) / 0.95) ) expect_ref_x_tbl( form_tails(cur_con, 0.8, "trim", "right"), data.frame(x = c(0, 0.2), y = c(1, 1) / 0.2) ) }) test_that("form_tails works with `method='winsor'` and 'discrete' type", { expect_ref_x_tbl( form_tails(cur_dis, 0.1, "winsor", "both"), data.frame(x = 1:4, prob = (1:4) / 10) ) expect_ref_x_tbl( form_tails(cur_dis, 0.11, "winsor", "both"), data.frame(x = 2:4, prob = c(0.3, 0.3, 0.4)) ) expect_ref_x_tbl( form_tails(cur_dis, 0.1, "winsor", "left"), data.frame(x = 1:4, prob = (1:4) / 10) ) expect_ref_x_tbl( form_tails(cur_dis, 0.11, "winsor", "left"), data.frame(x = 2:4, prob = c(0.3, 0.3, 0.4)) ) expect_ref_x_tbl( form_tails(cur_dis, 0.4, "winsor", "right"), data.frame(x = 1:3, prob = c(0.1, 0.2, 0.7)) ) expect_ref_x_tbl( form_tails(cur_dis, 0.41, "winsor", "right"), data.frame(x = 1:3, prob = c(0.1, 0.2, 0.7)) ) }) test_that("form_tails works with `method='winsor'` and 'continuous' type", { expect_ref_x_tbl( form_tails(cur_con, 0.1, "winsor", "both"), data.frame( x = c(0.1, 0.1 + 1e-8, 0.9 - 1e-8, 0.9), y = c(2e7 + 1, 1, 1, 2e7 + 1) ) ) expect_ref_x_tbl( form_tails(cur_con, 0.1, "winsor", "left"), data.frame( x = c(0.1, 0.1 + 1e-8, 1), y = c(2e7 + 1, 1, 1) ) ) expect_ref_x_tbl( form_tails(cur_con, 0.1, "winsor", "right"), data.frame( x = c(0, 0.9 - 1e-8, 0.9), y = c(1, 1, 2e7 + 1) ) ) }) test_that("form_tails returns self when `level = 0`", { expect_self_x_tbl(cur_dis) expect_self_x_tbl(cur_con) }) test_that("form_tails returns dirac-like distribution at maximum level", { expect_dirac(cur_dis, c("both" = 3, "left" = 4, "right" = 1)) expect_dirac(cur_con, c("both" = 0.5, "left" = 1, "right" = 0)) }) test_that("form_tails validates input", { expect_error(form_tails("a", 0.1), "`f`.*not pdqr-function") expect_error(form_tails(cur_dis), "`level`.*missing.*tail level to modify") expect_error(form_tails(cur_dis, "a"), "`level`.*single number") expect_error(form_tails(cur_dis, 0.1, method = 1), "`method`.*string") expect_error(form_tails(cur_dis, 0.1, method = "a"), "`method`.*one of") expect_error(form_tails(cur_dis, 0.1, direction = 1), "`direction`.*string") expect_error(form_tails(cur_dis, 0.1, direction = "a"), "`direction`.*one of") expect_error_negative_level(cur_dis) expect_error(form_tails(cur_dis, 0.6, "trim", "both"), "`level`.*0.5") expect_error(form_tails(cur_dis, 0.6, "winsor", "both"), "`level`.*0.5") expect_error(form_tails(cur_dis, 1.2, "trim", "left"), "`level`.*1") expect_error(form_tails(cur_dis, 1.2, "winsor", "left"), "`level`.*1") expect_error(form_tails(cur_dis, 1.2, "trim", "right"), "`level`.*1") expect_error(form_tails(cur_dis, 1.2, "winsor", "right"), "`level`.*1") }) test_that("assert_form_tails_args respects global options", { op <- options(pdqr.assert_args = FALSE) on.exit(options(op)) expect_silent(assert_form_tails_args("a", "b", "c", "d")) })
lslx$set("public", "extract_specification", function() { specification <- private$model$specification return(specification) }) lslx$set("public", "extract_saturated_cov", function() { saturated_cov <- private$fitting$reduced_data$saturated_cov return(saturated_cov) }) lslx$set("public", "extract_saturated_mean", function() { saturated_mean <- private$fitting$reduced_data$saturated_mean return(saturated_mean) }) lslx$set("public", "extract_saturated_moment_acov", function() { saturated_moment_acov <- private$fitting$reduced_data$saturated_moment_acov return(saturated_moment_acov) }) lslx$set("public", "extract_lambda_grid", function() { lambda_grid <- private$fitting$control$lambda_grid return(lambda_grid) }) lslx$set("public", "extract_delta_grid", function() { delta_grid <- private$fitting$control$delta_grid return(delta_grid) }) lslx$set("public", "extract_weight_matrix", function() { if (!(private$fitting$control$loss %in% c("uls", "dwls", "wls"))) { stop("Weight matrix can be only extracted when 'loss' = 'uls', 'dwls', or 'wls'.") } else { weight_matrix <- private$fitting$control$weight_matrix } return(weight_matrix) }) lslx$set("public", "extract_penalty_level", function(selector, lambda, delta, step, include_faulty = FALSE) { if (!include_faulty) { idx_convergent <- which(private$fitting$fitted_result$is_convergent) if (length(idx_convergent) == 0) { stop( "PL estimate under EACH penalty level is derived under nonconverged result. \n", " To include faulty results, please set 'include_faulty = TRUE'. \n" ) } idx_convex <- which(private$fitting$fitted_result$is_convex) if (length(idx_convex) == 0) { stop( "PL estimate under EACH penalty level is derived under nonconvex approximated hessian. \n", " To include faulty results, please set 'include_faulty = TRUE'. \n" ) } } else { idx_convergent <- seq_len(length(private$fitting$fitted_result$numerical_condition)) idx_convex <- seq_len(length(private$fitting$fitted_result$numerical_condition)) } idx_used <- intersect(x = idx_convergent, y = idx_convex) if (length(idx_used) == 0) { stop( "PL estimate under EACH penalty/convex level is derive under problematic optimization.\n", " To include faulty results, please set 'include_faulty = TRUE'. \n" ) } if (length(private$fitting$fitted_result$numerical_condition) == 1) { penalty_level <- names(private$fitting$fitted_result$numerical_condition[idx_used]) } else { if (private$fitting$control$regularizer) { if (missing(selector) & missing(lambda) & missing(delta)) { if (length(private$fitting$fitted_result$numerical_condition) > 1) { stop( "Argument 'selector', 'lambda', and 'delta' cannot be all empty if there are many regularization levels." ) } } } else {} if (private$fitting$control$searcher) { if (missing(selector) & missing(step)) { if (length(private$fitting$fitted_result$numerical_condition) > 1) { stop( "Argument 'selector' and 'step' cannot be all empty if there are many searching steps." ) } } } else {} if (!missing(selector)) { if (length(selector) > 1) { stop("The length of argument 'selector' can be only one.\n") } if (!(selector %in% names(private$fitting$fitted_result$information_criterion[[1]]))) { stop( "Argument 'selector' is unrecognized.\n", " Selector currently recognized by 'lslx' is \n ", do.call(paste, as.list( names( private$fitting$fitted_result$information_criterion[[1]] ) )), "." ) } if ((selector %in% c("raic", "raic3", "rcaic", "rbic", "rabic", "rhbic")) & (!private$fitting$control$response)) { stop( "When lslx object is initialized via moments,", " 'raic', 'raic3', 'rcaic', 'rbic', 'rabic', and 'rhbic' are not available." ) } if (private$fitting$control$regularizer) { if ((!missing(lambda)) | (!missing(delta))) { stop("When 'selector' is specified, 'lambda' or 'delta' will not be used.\n") } } else {} if (private$fitting$control$searcher) { if ((!missing(step))) { stop("When 'selector' is specified, 'step' will not be used.\n") } } else {} penalty_level <- sapply( X = selector, FUN = function(selector_i) { information_criterion_i <- sapply( X = private$fitting$fitted_result$information_criterion, FUN = function(information_criterion_j) { getElement(object = information_criterion_j, name = selector_i) } ) penalty_level_i <- names(which.min(information_criterion_i[idx_used])) return(penalty_level_i) } ) } else { if (private$fitting$control$regularizer) { if (missing(lambda)) { stop("When 'selector' is not specified, 'lambda' cannot be empty.") } else { if (!private$fitting$control$double_regularizer) { if (length(lambda) != 1) { stop("When only one regularizer is implemented, length of 'lambda' must be 1.") } else { lambda <- list(lambda[[1]], 0) } } else { if ((!is.list(lambda))|(length(lambda) != 2)) { stop("When two regularizers are implemented, 'lambda' must be a list with length 2.") } if (!is.numeric(lambda[[1]])|!is.numeric(lambda[[2]])) { stop("Element in 'lambda' must be a numeric with length 1.") } } } if (missing(delta)) { if (private$fitting$control$penalty_method %in% c("elastic_net", "mcp")) { stop( "When 'selector' is not specified, 'delta' cannot be empty." ) } else if (private$fitting$control$penalty_method == "lasso") { delta <- c(1, 1) } else if (private$fitting$control$penalty_method == "ridge") { delta <- c(0, 0) } else{} } else { if (!private$fitting$control$double_regularizer) { if (length(delta) != 1) { stop("When only one regularizer is implemented, length of 'delta' must be 1.") } else { if (private$fitting$control$penalty_method == "ridge") { delta <- list(delta[[1]], 0) } else if (private$fitting$control$penalty_method == "lasso") { delta <- list(delta[[1]], 1) } else if (private$fitting$control$penalty_method == "elastic_net") { delta <- list(delta[[1]], .5) } else if (private$fitting$control$penalty_method == "mcp") { delta <- list(delta[[1]], Inf) } else {} } } else { if ((!is.list(delta))|(length(delta) != 2)) { stop("When two regularizers are implemented, 'delta' must be a list with length 2.") } if (!is.numeric(delta[[1]])|!is.numeric(delta[[2]])) { stop("Element in 'delta' must be a numeric with length 1.") } } } penalty_used_split <- strsplit( x = names(private$fitting$fitted_result$numerical_condition), split = "=|\\,|\\(|\\)" ) penalty_used <- sapply( X = penalty_used_split, FUN = function(penalty_used_split_i) { penalty_used_i <- as.numeric(c(penalty_used_split_i[3], penalty_used_split_i[4], penalty_used_split_i[8], penalty_used_split_i[9])) return(penalty_used_i) } ) lambda_1st_used <- penalty_used[1, ] if (lambda[[1]] %in% lambda_1st_used) { lambda_1st_nearest <- lambda[[1]] } else { if (lambda[[1]] == Inf) { lambda_1st_nearest <- max(lambda_1st_used) } else { lambda_1st_nearest <- max(abs(unique(lambda_1st_used)[which.min(abs(unique(lambda_1st_used) - lambda[[1]]))])) } } lambda_2nd_used <- penalty_used[2, ] if (lambda[[2]] %in% lambda_2nd_used) { lambda_2nd_nearest <- lambda[[2]] } else { if (lambda[[2]] == Inf) { lambda_2nd_nearest <- max(lambda_2nd_used) } else { lambda_2nd_nearest <- max(abs(unique(lambda_2nd_used)[which.min(abs(unique(lambda_2nd_used) - lambda[[2]]))])) } } delta_1st_used <- penalty_used[3, ] if (delta[[1]] %in% delta_1st_used) { delta_1st_nearest <- delta[[1]] } else { if (delta[[1]] == Inf) { delta_1st_nearest <- max(delta_1st_used) } else { delta_1st_nearest <- max(abs(unique(delta_1st_used)[which.min(abs(unique(delta_1st_used) - delta[[1]]))])) } } delta_2nd_used <- penalty_used[4, ] if (delta[[2]] %in% delta_2nd_used) { delta_2nd_nearest <- delta[[2]] } else { if (delta[[2]] == Inf) { delta_2nd_nearest <- max(delta_2nd_used) } else { delta_2nd_nearest <- max(abs(unique(delta_2nd_used)[which.min(abs(unique(delta_2nd_used) - delta[[2]]))])) } } penalty_level <- paste0("lambda", "=c(", lambda_1st_nearest, ",", lambda_2nd_nearest, ")", ",", "delta", "=c(", delta_1st_nearest, ",", delta_2nd_nearest, ")") } else {} if (private$fitting$control$searcher) { if (missing(step)) { stop("When 'selector' is not specified, 'step' cannot be empty.") } if (private$fitting$control$penalty_method == "forward") { step_nearest <- min(abs(unique(private$fitting$control$step_grid)[ which.min(abs(unique(private$fitting$control$step_grid) - step))])) } else if (private$fitting$control$penalty_method == "backward") { step_nearest <- max(abs(unique(private$fitting$control$step_grid)[ which.min(abs(unique(private$fitting$control$step_grid) - step))])) } else {} penalty_level <- paste0("step=", step_nearest) } else {} } } return(penalty_level) }) lslx$set("public", "extract_coefficient_indicator", function(selector, lambda, delta, step, type = "default", include_faulty = FALSE) { penalty_level <- self$extract_penalty_level( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) coefficient <- private$fitting$fitted_result$coefficient[[penalty_level]] if (!(type %in% c( "default", "all", "fixed", "free", "pen", "effective", "selected" ))) { stop( "Argument 'type' can be only either 'default', 'all', 'fixed', 'free', 'pen', 'active', or 'selected'." ) } if (type == "default") { type <- "all" } if (type == "all") { coefficient_indicator <- rep(T, length(coefficient)) } else if (type == "fixed") { coefficient_indicator <- !( private$fitting$reduced_model$theta_is_free | private$fitting$reduced_model$theta_is_pen ) } else if (type == "free") { coefficient_indicator <- private$fitting$reduced_model$theta_is_free } else if (type == "pen") { coefficient_indicator <- private$fitting$reduced_model$theta_is_pen } else if (type == "effective") { coefficient_indicator <- private$fitting$reduced_model$theta_is_free | (private$fitting$reduced_model$theta_is_pen & coefficient != 0) } else if (type == "selected") { coefficient_indicator <- private$fitting$reduced_model$theta_is_pen & coefficient != 0 } else {} return(coefficient_indicator) }) lslx$set("public", "extract_numerical_condition", function(selector, lambda, delta, step, include_faulty = FALSE) { penalty_level <- self$extract_penalty_level( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) numerical_condition <- private$fitting$fitted_result$numerical_condition[[penalty_level]] return(numerical_condition) }) lslx$set("public", "extract_information_criterion", function(selector, lambda, delta, step, include_faulty = FALSE) { penalty_level <- self$extract_penalty_level( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) information_criterion <- private$fitting$fitted_result$information_criterion[[penalty_level]] return(information_criterion) }) lslx$set("public", "extract_fit_index", function(selector, lambda, delta, step, include_faulty = FALSE) { penalty_level <- self$extract_penalty_level( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) fit_index <- private$fitting$fitted_result$fit_index[[penalty_level]] return(fit_index) }) lslx$set("public", "extract_cv_error", function(selector, lambda, delta, step, include_faulty = FALSE) { penalty_level <- self$extract_penalty_level( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) cv_error <- private$fitting$fitted_result$cv_error[[penalty_level]] return(cv_error) }) lslx$set("public", "extract_coefficient", function(selector, lambda, delta, step, type = "default", include_faulty = FALSE) { penalty_level <- self$extract_penalty_level( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) coefficient <- private$fitting$fitted_result$coefficient[[penalty_level]] coefficient_indicator <- self$extract_coefficient_indicator( selector = selector, lambda = lambda, delta = delta, step = step, type = type, include_faulty = include_faulty ) if (!(all(coefficient_indicator))) { coefficient <- coefficient[coefficient_indicator] } return(coefficient) }) lslx$set("public", "extract_debiased_coefficient", function(selector, lambda, delta, step, type = "default", include_faulty = FALSE) { coefficient <- self$extract_coefficient( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) debiased_coefficient <- coefficient if (private$fitting$control$regularizer) { is_effective <- self$extract_coefficient_indicator( selector = selector, lambda = lambda, delta = delta, step = step, type = "effective", include_faulty = include_faulty ) is_selected <- self$extract_coefficient_indicator( selector = selector, lambda = lambda, delta = delta, step = step, type = "selected", include_faulty = include_faulty ) if (any(is_selected)) { penalty_level <- self$extract_penalty_level( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) lambda_1st <- as.numeric(strsplit(x = penalty_level, split = "=|\\,|\\(|\\)")[[1]][3]) lambda_2nd <- as.numeric(strsplit(x = penalty_level, split = "=|\\,|\\(|\\)")[[1]][4]) delta_1st <- as.numeric(strsplit(x = penalty_level, split = "=|\\,|\\(|\\)")[[1]][8]) delta_2nd <- as.numeric(strsplit(x = penalty_level, split = "=|\\,|\\(|\\)")[[1]][9]) regularizer_gradient <- compute_regularizer_gradient_cpp( theta_value = coefficient, lambda_1st = lambda_1st, lambda_2nd = lambda_2nd, delta_1st = delta_1st, delta_2nd = delta_2nd, reduced_data = private$fitting$reduced_data, reduced_model = private$fitting$reduced_model, control = private$fitting$control, supplied_result = private$fitting$supplied_result ) observed_information <- 2 * self$extract_observed_information( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) observed_information_inv <- matrix(0, length(coefficient), length(coefficient)) observed_information_inv[is_effective, is_effective] <- solve(observed_information[is_effective, is_effective]) debiased_coefficient[is_effective] <- coefficient[is_effective] + observed_information_inv[is_effective, is_effective, drop = FALSE] %*% (regularizer_gradient[is_effective, 1, drop = FALSE]) } } else {} coefficient_indicator <- self$extract_coefficient_indicator( selector = selector, lambda = lambda, delta = delta, step = step, type = type, include_faulty = include_faulty ) if (!(all(coefficient_indicator))) { debiased_coefficient <- debiased_coefficient[coefficient_indicator] } return(debiased_coefficient) }) lslx$set("public", "extract_implied_cov", function(selector, lambda, delta, step, include_faulty = FALSE) { penalty_level <- self$extract_penalty_level( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) coefficient <- private$fitting$fitted_result$coefficient[[penalty_level]] implied_cov <- compute_implied_cov_cpp( theta_value = coefficient, reduced_data = private$fitting$reduced_data, reduced_model = private$fitting$reduced_model, control = private$fitting$control, supplied_result = private$fitting$supplied_result ) implied_cov <- lapply( X = implied_cov, FUN = function(implied_cov_i) { rownames(implied_cov_i) <- private$model$name_response colnames(implied_cov_i) <- private$model$name_response return(implied_cov_i) } ) names(implied_cov) <- private$model$level_group return(implied_cov) }) lslx$set("public", "extract_implied_mean", function(selector, lambda, delta, step, include_faulty = FALSE) { penalty_level <- self$extract_penalty_level( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) coefficient <- private$fitting$fitted_result$coefficient[[penalty_level]] implied_mean <- compute_implied_mean_cpp( theta_value = coefficient, reduced_data = private$fitting$reduced_data, reduced_model = private$fitting$reduced_model, control = private$fitting$control, supplied_result = private$fitting$supplied_result ) implied_mean <- lapply( X = implied_mean, FUN = function(implied_mean_i) { rownames(implied_mean_i) <- private$model$name_response return(implied_mean_i) } ) names(implied_mean) <- private$model$level_group return(implied_mean) }) lslx$set("public", "extract_residual_cov", function(selector, lambda, delta, step, include_faulty = FALSE) { implied_cov <- self$extract_implied_cov( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) residual_cov <- mapply( FUN = function(implied_cov_i, saturated_cov_i) { residual_cov_i <- implied_cov_i - saturated_cov_i return(residual_cov_i) }, implied_cov, private$fitting$reduced_data$saturated_cov, SIMPLIFY = FALSE, USE.NAMES = TRUE ) return(residual_cov) }) lslx$set("public", "extract_residual_mean", function(selector, lambda, delta, step, include_faulty = FALSE) { implied_mean <- self$extract_implied_mean( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) residual_mean <- mapply( FUN = function(implied_mean_i, saturated_mean_i) { residual_mean_i <- implied_mean_i - saturated_mean_i return(residual_mean_i) }, implied_mean, private$fitting$reduced_data$saturated_mean, SIMPLIFY = FALSE, USE.NAMES = TRUE ) return(residual_mean) }) lslx$set("public", "extract_coefficient_matrix", function(selector, lambda, delta, step, block, include_faulty = FALSE) { if (missing(block)) { stop("Argument 'block' is missing.") } if (length(block) > 1) { stop("The length of argument 'block' can be only one.") } penalty_level <- self$extract_penalty_level( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) coefficient <- private$fitting$fitted_result$coefficient[[penalty_level]] coefficient_matrix <- compute_coefficient_matrix_cpp( theta_value = coefficient, reduced_data = private$fitting$reduced_data, reduced_model = private$fitting$reduced_model, control = private$fitting$control, supplied_result = private$fitting$supplied_result ) if (block %in% c("f<-1", "y<-1")) { selected_matrix <- coefficient_matrix$alpha col_names <- "1" } else { if (block %in% c("f<-f", "f<-y", "y<-f", "y<-y")) { selected_matrix <- coefficient_matrix$beta } else if (block %in% c("f<->f", "f<->y", "y<->f", "y<->y")) { selected_matrix <- coefficient_matrix$phi } else { stop( "Argument 'block' is unrecognized. It must be one of the following:\n", " 'f<-1', 'y<-1', 'f<-f', 'f<-y', 'y<-f', 'f<-f', 'f<->f', 'f<->y', 'y<->f', 'f<->f'." ) } col_names <- private$model$name_eta } row_select <- strsplit(block, split = "<-|<->|->")[[1]][1] col_select <- strsplit(block, split = "<-|<->|->")[[1]][2] if (row_select == "f") { row_select <- private$model$name_factor } else if (row_select == "y") { row_select <- private$model$name_response } if (col_select == "f") { col_select <- private$model$name_factor } else if (col_select == "y") { col_select <- private$model$name_response } selected_matrix <- lapply( X = selected_matrix, FUN = function(selected_matrix_i) { rownames(selected_matrix_i) <- private$model$name_eta colnames(selected_matrix_i) <- col_names return(selected_matrix_i) } ) coefficient_matrix_block <- lapply( X = selected_matrix, FUN = function(selected_matrix_i) { coefficient_matrix_block_i <- selected_matrix_i[row_select, col_select, drop = FALSE] return(coefficient_matrix_block_i) } ) names(coefficient_matrix_block) <- private$model$level_group return(coefficient_matrix_block) }) lslx$set("public", "extract_moment_jacobian", function(selector, lambda, delta, step, type = "default", include_faulty = FALSE) { penalty_level <- self$extract_penalty_level( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) coefficient <- private$fitting$fitted_result$coefficient[[penalty_level]] moment_jacobian <- compute_model_jacobian_cpp( theta_value = coefficient, reduced_data = private$fitting$reduced_data, reduced_model = private$fitting$reduced_model, control = private$fitting$control, supplied_result = private$fitting$supplied_result ) colnames(moment_jacobian) <- rownames(private$model$specification) coefficient_indicator <- self$extract_coefficient_indicator( selector = selector, lambda = lambda, delta = delta, step = step, type = type, include_faulty = include_faulty ) if (!(all(coefficient_indicator))) { moment_jacobian <- moment_jacobian[, coefficient_indicator, drop = FALSE] } return(moment_jacobian) }) lslx$set("public", "extract_expected_information", function(selector, lambda, delta, step, type = "default", include_faulty = FALSE) { penalty_level <- self$extract_penalty_level( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) coefficient <- private$fitting$fitted_result$coefficient[[penalty_level]] expected_information <- compute_expected_information_cpp( theta_value = coefficient, reduced_data = private$fitting$reduced_data, reduced_model = private$fitting$reduced_model, control = private$fitting$control, supplied_result = private$fitting$supplied_result ) colnames(expected_information) <- rownames(private$model$specification) rownames(expected_information) <- rownames(private$model$specification) coefficient_indicator <- self$extract_coefficient_indicator( selector = selector, lambda = lambda, delta = delta, step = step, type = type, include_faulty = include_faulty ) if (!(all(coefficient_indicator))) { expected_information <- expected_information[coefficient_indicator, coefficient_indicator, drop = FALSE] } return(expected_information) }) lslx$set("public", "extract_observed_information", function(selector, lambda, delta, step, type = "default", include_faulty = FALSE) { penalty_level <- self$extract_penalty_level( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) coefficient <- private$fitting$fitted_result$coefficient[[penalty_level]] observed_information <- compute_observed_information_cpp( theta_value = coefficient, reduced_data = private$fitting$reduced_data, reduced_model = private$fitting$reduced_model, control = private$fitting$control, supplied_result = private$fitting$supplied_result ) colnames(observed_information) <- rownames(private$model$specification) rownames(observed_information) <- rownames(private$model$specification) coefficient_indicator <- self$extract_coefficient_indicator( selector = selector, lambda = lambda, delta = delta, step = step, type = type, include_faulty = include_faulty ) if (!(all(coefficient_indicator))) { observed_information <- observed_information[coefficient_indicator, coefficient_indicator, drop = FALSE] } return(observed_information) }) lslx$set("public", "extract_score_acov", function(selector, lambda, delta, step, type = "default", include_faulty = FALSE) { penalty_level <- self$extract_penalty_level( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) coefficient <- private$fitting$fitted_result$coefficient[[penalty_level]] score_acov <- compute_score_acov_cpp( theta_value = coefficient, reduced_data = private$fitting$reduced_data, reduced_model = private$fitting$reduced_model, control = private$fitting$control, supplied_result = private$fitting$supplied_result ) colnames(score_acov) <- rownames(private$model$specification) rownames(score_acov) <- rownames(private$model$specification) coefficient_indicator <- self$extract_coefficient_indicator( selector = selector, lambda = lambda, delta = delta, step = step, type = type, include_faulty = include_faulty ) if (!(all(coefficient_indicator))) { score_acov <- score_acov[coefficient_indicator, coefficient_indicator, drop = FALSE] } return(score_acov) }) lslx$set("public", "extract_coefficient_acov", function(selector, lambda, delta, step, standard_error = "default", ridge_penalty = "default", type = "default", include_faulty = FALSE) { if (!( standard_error %in% c( "default", "sandwich", "observed_information", "expected_information" ) )) { stop( "Argument 'standard_error' can be only either 'default', 'sandwich', 'observed_information', or 'expected_information'." ) } if (standard_error == "default") { if (private$fitting$control$response) { standard_error <- "sandwich" } else { standard_error <- "observed_information" } } if (ridge_penalty == "default") { if (private$fitting$control$penalty_method %in% c("ridge", "elastic_net")) { ridge_penalty <- TRUE } else { ridge_penalty <- FALSE } } penalty_level <- self$extract_penalty_level( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) coefficient <- self$extract_coefficient( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) is_effective <- self$extract_coefficient_indicator( selector = selector, lambda = lambda, delta = delta, step = step, type = "effective", include_faulty = include_faulty ) coefficient_acov <- matrix(NA, length(coefficient), length(coefficient)) if (standard_error == "sandwich") { score_acov <- self$extract_score_acov( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) observed_information <- self$extract_observed_information( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) if (ridge_penalty) { penalty_level_split <- strsplit(penalty_level, ",|\\(|\\)") lambda_1st <- as.numeric(penalty_level_split[[1]][2]) lambda_2nd <- as.numeric(penalty_level_split[[1]][3]) delta_1st <- as.numeric(penalty_level_split[[1]][6]) delta_2nd <- as.numeric(penalty_level_split[[1]][7]) if (private$fitting$control$penalty_method == "ridge") { observed_information <- observed_information + diag(private$fitting$reduced_model$theta_weight * (private$fitting$reduced_model$theta_set == 1) * lambda_1st + private$fitting$reduced_model$theta_weight * (private$fitting$reduced_model$theta_set == 2) * lambda_2nd) } else if (private$fitting$control$penalty_method == "elastic_net") { observed_information <- observed_information + diag(private$fitting$reduced_model$theta_weight * (private$fitting$reduced_model$theta_set == 1) * lambda_1st * (1 - delta_1st) + private$fitting$reduced_model$theta_weight * (private$fitting$reduced_model$theta_set == 2) * lambda_2nd * (1 - delta_2nd)) } else if (private$fitting$control$penalty_method == "mcp") { observed_information <- observed_information - diag(private$fitting$reduced_model$theta_weight * (abs(coefficient) <= (lambda_1st * delta_1st)) * (private$fitting$reduced_model$theta_set == 1) * (.5 / delta_1st) + private$fitting$reduced_model$theta_weight * (abs(coefficient) <= (lambda_2nd * delta_2nd)) * (private$fitting$reduced_model$theta_set == 2) * (.5 / delta_2nd)) } else {} } observed_information_pinv <- solve(observed_information[is_effective, is_effective]) coefficient_acov[is_effective, is_effective] <- (observed_information_pinv %*% score_acov[is_effective, is_effective] %*% observed_information_pinv) } else if (standard_error == "expected_information") { expected_information <- self$extract_expected_information( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) if (ridge_penalty) { penalty_level_split <- strsplit(penalty_level, ",|\\(|\\)") lambda_1st <- as.numeric(penalty_level_split[[1]][2]) lambda_2nd <- as.numeric(penalty_level_split[[1]][3]) delta_1st <- as.numeric(penalty_level_split[[1]][6]) delta_2nd <- as.numeric(penalty_level_split[[1]][7]) if (private$fitting$control$penalty_method == "ridge") { expected_information <- expected_information + diag(private$fitting$reduced_model$theta_weight * (private$fitting$reduced_model$theta_set == 1) * lambda_1st + private$fitting$reduced_model$theta_weight * (private$fitting$reduced_model$theta_set == 2) * lambda_2nd) } else if (private$fitting$control$penalty_method == "elastic_net") { expected_information <- expected_information + diag(private$fitting$reduced_model$theta_weight * (private$fitting$reduced_model$theta_set == 1) * lambda_1st * (1 - delta_1st) + private$fitting$reduced_model$theta_weight * (private$fitting$reduced_model$theta_set == 2) * lambda_2nd * (1 - delta_2nd)) } else if (private$fitting$control$penalty_method == "mcp") { expected_information <- expected_information - diag(private$fitting$reduced_model$theta_weight * (abs(coefficient) <= (lambda_1st * delta_1st)) * (private$fitting$reduced_model$theta_set == 1) * (.5 / delta_1st) + private$fitting$reduced_model$theta_weight * (abs(coefficient) <= (lambda_2nd * delta_2nd)) * (private$fitting$reduced_model$theta_set == 2) * (.5 / delta_2nd)) } else {} } coefficient_acov[is_effective, is_effective] <- solve(expected_information[is_effective, is_effective]) / private$fitting$reduced_data$n_observation } else if (standard_error == "observed_information") { observed_information <- self$extract_observed_information( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) if (ridge_penalty) { penalty_level_split <- strsplit(penalty_level, ",|\\(|\\)") lambda_1st <- as.numeric(penalty_level_split[[1]][2]) lambda_2nd <- as.numeric(penalty_level_split[[1]][3]) delta_1st <- as.numeric(penalty_level_split[[1]][6]) delta_2nd <- as.numeric(penalty_level_split[[1]][7]) if (private$fitting$control$penalty_method == "ridge") { observed_information <- observed_information + diag(private$fitting$reduced_model$theta_weight * (private$fitting$reduced_model$theta_set == 1) * lambda_1st + private$fitting$reduced_model$theta_weight * (private$fitting$reduced_model$theta_set == 2) * lambda_2nd) } else if (private$fitting$control$penalty_method == "elastic_net") { observed_information <- observed_information + diag(private$fitting$reduced_model$theta_weight * (private$fitting$reduced_model$theta_set == 1) * lambda_1st * (1 - delta_1st) + private$fitting$reduced_model$theta_weight * (private$fitting$reduced_model$theta_set == 2) * lambda_2nd * (1 - delta_2nd)) } else if (private$fitting$control$penalty_method == "mcp") { observed_information <- observed_information - diag(private$fitting$reduced_model$theta_weight * (abs(coefficient) <= (lambda_1st * delta_1st)) * (private$fitting$reduced_model$theta_set == 1) * (.5 / delta_1st) + private$fitting$reduced_model$theta_weight * (abs(coefficient) <= (lambda_2nd * delta_2nd)) * (private$fitting$reduced_model$theta_set == 2) * (.5 / delta_2nd)) } else {} } coefficient_acov[is_effective, is_effective] <- solve(observed_information[is_effective, is_effective]) / private$fitting$reduced_data$n_observation } else {} colnames(coefficient_acov) <- rownames(private$model$specification) rownames(coefficient_acov) <- rownames(private$model$specification) coefficient_indicator <- self$extract_coefficient_indicator( selector = selector, lambda = lambda, delta = delta, step = step, type = type, include_faulty = include_faulty ) if (!(all(coefficient_indicator))) { coefficient_acov <- coefficient_acov[coefficient_indicator, coefficient_indicator, drop = FALSE] } attr(coefficient_acov, "standard_error") <- standard_error return(coefficient_acov) }) lslx$set("public", "extract_loss_gradient", function(selector, lambda, delta, step, type = "default", include_faulty = FALSE) { penalty_level <- self$extract_penalty_level( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) coefficient <- private$fitting$fitted_result$coefficient[[penalty_level]] loss_gradient <- compute_loss_gradient_cpp( theta_value = coefficient, reduced_data = private$fitting$reduced_data, reduced_model = private$fitting$reduced_model, control = private$fitting$control, supplied_result = private$fitting$supplied_result ) rownames(loss_gradient) <- rownames(private$model$specification) coefficient_indicator <- self$extract_coefficient_indicator( selector = selector, lambda = lambda, delta = delta, step = step, type = type, include_faulty = include_faulty ) if (!(all(coefficient_indicator))) { loss_gradient <- loss_gradient[coefficient_indicator, , drop = FALSE] } return(loss_gradient) }) lslx$set("public", "extract_regularizer_gradient", function(selector, lambda, delta, step, type = "default", include_faulty = FALSE) { if (private$fitting$control$regularizer) { penalty_level <- self$extract_penalty_level( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) coefficient <- private$fitting$fitted_result$coefficient[[penalty_level]] lambda_1st <- as.numeric(strsplit(x = penalty_level, split = "=|\\,|\\(|\\)")[[1]][3]) lambda_2nd <- as.numeric(strsplit(x = penalty_level, split = "=|\\,|\\(|\\)")[[1]][4]) delta_1st <- as.numeric(strsplit(x = penalty_level, split = "=|\\,|\\(|\\)")[[1]][8]) delta_2nd <- as.numeric(strsplit(x = penalty_level, split = "=|\\,|\\(|\\)")[[1]][9]) regularizer_gradient <- compute_regularizer_gradient_cpp( theta_value = coefficient, lambda_1st = lambda_1st, lambda_2nd = lambda_2nd, delta_1st = delta_1st, delta_2nd = delta_2nd, reduced_data = private$fitting$reduced_data, reduced_model = private$fitting$reduced_model, control = private$fitting$control, supplied_result = private$fitting$supplied_result ) } else { regularizer_gradient <- matrix(0, nrow = private$fitting$reduced_model$n_theta, ncol = 1) } rownames(regularizer_gradient) <- rownames(private$model$specification) coefficient_indicator <- self$extract_coefficient_indicator( selector = selector, lambda = lambda, delta = delta, step = step, type = type, include_faulty = include_faulty ) if (!(all(coefficient_indicator))) { regularizer_gradient <- regularizer_gradient[coefficient_indicator, , drop = FALSE] } return(regularizer_gradient) }) lslx$set("public", "extract_objective_gradient", function(selector, lambda, delta, step, type = "default", include_faulty = FALSE) { penalty_level <- self$extract_penalty_level( selector = selector, lambda = lambda, delta = delta, step = step, include_faulty = include_faulty ) coefficient <- private$fitting$fitted_result$coefficient[[penalty_level]] if (private$fitting$control$regularizer) { lambda_1st <- as.numeric(strsplit(x = penalty_level, split = "=|\\,|\\(|\\)")[[1]][3]) lambda_2nd <- as.numeric(strsplit(x = penalty_level, split = "=|\\,|\\(|\\)")[[1]][4]) delta_1st <- as.numeric(strsplit(x = penalty_level, split = "=|\\,|\\(|\\)")[[1]][8]) delta_2nd <- as.numeric(strsplit(x = penalty_level, split = "=|\\,|\\(|\\)")[[1]][9]) objective_gradient <- compute_objective_gradient_cpp( theta_value = coefficient, lambda_1st = lambda_1st, lambda_2nd = lambda_2nd, delta_1st = delta_1st, delta_2nd = delta_2nd, reduced_data = private$fitting$reduced_data, reduced_model = private$fitting$reduced_model, control = private$fitting$control, supplied_result = private$fitting$supplied_result ) } else { objective_gradient <- compute_loss_gradient_cpp( theta_value = coefficient, reduced_data = private$fitting$reduced_data, reduced_model = private$fitting$reduced_model, control = private$fitting$control, supplied_result = private$fitting$supplied_result ) } rownames(objective_gradient) <- rownames(private$model$specification) coefficient_indicator <- self$extract_coefficient_indicator( selector = selector, lambda = lambda, delta = delta, step = step, type = type, include_faulty = include_faulty ) if (!(all(coefficient_indicator))) { objective_gradient <- objective_gradient[coefficient_indicator, , drop = FALSE] } return(objective_gradient) })
set_secrets <- function(keyvault, secrets) { keyvault$set_secrets(secrets) invisible(NULL) } get_secrets <- function(keyvault, secrets) { keyvault$get_secrets(secrets) } delete_secrets <- function(keyvault, secrets) { keyvault$delete_secrets(secrets) invisible(NULL) } list_secrets <- function(keyvault) { keyvault$list_secrets() }
rpcauchy = function(n, lambda = 1, mu= 0, sigma = 1){ n = runif(n) x = qpcauchy(n, lambda, mu, sigma) return(x) }
options(stringsAsFactors = FALSE) expect_equal( data.frame(x = 1) %>% mutate(across()), data.frame(x = 1), info = "across() works on one column data.frame" ) expect_equivalent( mtcars %>% group_by(cyl) %>% summarise(across(starts_with("c"), mean)) %>% ungroup(), data.frame(cyl = c(4, 6, 8), carb_1 = c(1.54545455, 3.42857, 3.5)), tolerance = 0.00001, info = "across() does not select grouping variables" ) gf <- data.frame(x = 1, y = 2, z = 3, s = "") %>% group_by(x) expect_named <- function(x, y, info = NA_character_) expect_equal(colnames(x), y, info = info) expect_named( summarise(gf, across()), c("x", "y", "z", "s"), "across() correctly names output columns" ) expect_named( summarise(gf, across(where(is.numeric), mean)), c("x", "y", "z"), "across() correctly names output for non-named functions" ) expect_named( summarise(gf, across(where(is.numeric), list(mean = mean, sum = sum))), c("x", "y_mean", "y_sum", "z_mean", "z_sum"), info = "across() correctly names output columns for named lists of functions" ) expect_named( summarise(gf, across(where(is.numeric), list(mean = mean, sum))), c("x", "y_mean", "y_2", "z_mean", "z_2"), info = "across() correctly names output columns for partially named lists of functions" ) expect_named( summarise(gf, across(where(is.numeric), list(mean, sum = sum))), c("x", "y_1", "y_sum", "z_1", "z_sum"), info = "across() correctly names output columns for partially named lists of functions" ) expect_named( summarise(gf, across(where(is.numeric), list(mean, sum))), c("x", "y_1", "y_2", "z_1", "z_2"), info = "across() correctly names output columns for non-named lists of functions" ) expect_identical( data.frame(x = 1:2, y = c("a", "b")) %>% summarise(across(everything(), list(cls = class, type = is.numeric))), data.frame(x_cls = "integer", x_type = TRUE, y_cls = "character", y_type = FALSE), info = "across() result locations are aligned with column names" ) expect_equal( summarise(data.frame(x = c(1, NA)), across(everything(), mean, na.rm = TRUE)), data.frame(x = 1), info = "across() passes ... to functions" ) expect_equal( summarise(data.frame(x = c(1, NA)), across(everything(), list(mean = mean, median = median), na.rm = TRUE)), data.frame(x_mean = 1, x_median = 1), info = "across() passes ... to functions" ) df <- data.frame(x = 1) expect_equal( mutate(df, across(x, `+`, 1)), data.frame(x = 2), info = "across() passes unnamed arguments following .fns as ..." ) expect_equal( summarize(data.frame(x = c(1, 2)), across(x, tail, n = 1)), data.frame(x = 2), info = "across() avoids simple argument name collisions with ..." ) df <- data.frame(a = 1) expect_equal( mutate(df, x = ncol(across(where(is.numeric))), y = ncol(across(where(is.numeric)))), data.frame(a = 1, x = 1L, y = 2L), info = "across() works sequentially" ) expect_equal( mutate(df, a = "x", y = ncol(across(where(is.numeric)))), data.frame(a = "x", y = 0L), info = "across() works sequentially" ) expect_equal( mutate(df, x = 1, y = ncol(across(where(is.numeric)))), data.frame(a = 1, x = 1, y = 2L), info = "across() works sequentially" ) expect_named( mutate(data.frame(a = 1, b = 2), a = 2, x = across())$x, c("a", "b"), info = "across() retains original ordering" ) expect_equal( mutate(data.frame(a = 1, b = 2), x = ncol(across(where(is.numeric))) + ncol(across(a))), data.frame(a = 1, b = 2, x = 3), info = "across() can be used twice in the same expression" ) expect_equal( mutate(data.frame(a = 1, b = 2), x = ncol(across(where(is.numeric))), y = ncol(across(a))), data.frame(a = 1, b = 2, x = 2, y = 1), info = "across() can be used in separate expressions" ) df <- data.frame(g = 1:2, a = 1:2, b = 3:4) %>% group_by(g) expect_equal( mutate(df, x = if_else(cur_group_id() == 1L, across(a)$a, across(b)$b)), structure( list(g = 1:2, a = 1:2, b = 3:4, x = c(1L, 4L)), groups = structure(list(g = 1:2, .rows = list(1L, 2L)), row.names = 1:2, class = "data.frame", .drop = TRUE ), row.names = 1:2, class = c("grouped_df", "data.frame") ), info = "across() usage can depend on the group id" ) df <- data.frame(g = rep(1:2, each = 2), a = 1:4) %>% group_by(g) expect_identical( mutate(df, data.frame(x = across(where(is.numeric), mean)$a, y = across(where(is.numeric), max)$a)), mutate(df, x = mean(a), y = max(a)), info = "across() internal cache key depends on all inputs" ) expect_error( data.frame(x = 1) %>% summarise(across(everything(), "foo")), info = "across() fails on non-function" ) expect_equal( mutate(data.frame(), across()), data.frame(), info = "across() works with empty data.frames" ) expect_equal( data.frame(x = 1, y = 2) %>% summarise(across(everything(), ~rep(42, .))), data.frame(x = rep(42, 2), y = rep(42, 2)), info = "across() uses tidy recycling rules" ) expect_error( data.frame(x = 2, y = 3) %>% summarise(across(everything(), ~rep(42, .))), info = "across() uses tidy recycling rules ) expect_equal( iris %>% group_by(Species) %>% summarise(across(starts_with("Sepal"), ~mean(., na.rm = TRUE))) %>% ungroup(), data.frame( Species = structure(1:3, .Label = c("setosa", "versicolor", "virginica"), class = "factor"), Sepal.Length = c(5.006, 5.936, 6.588), Sepal.Width = c(3.428, 2.77, 2.974) ), info = "purrr style formulas work" ) expect_equal( mtcars %>% summarise(across(starts_with("m"), list(~mean(.x), ~sd(.x)))), data.frame(mpg_1 = mean(mtcars$mpg), mpg_2 = sd(mtcars$mpg)), info = "list of purrr style formulas works" ) expect_equal( mtcars %>% summarise(across(starts_with("m"), list("mean", "sd"))), data.frame(mpg_1 = mean(mtcars$mpg), mpg_2 = sd(mtcars$mpg)), info = "character vector style functions work" ) d <- data.frame(x = 10, y = 10) expect_error(filter(d, if_all(x:y, identity)), info = "if_all() enforces logical in filter") expect_error(filter(d, if_any(x:y, identity)), info = "if_any() enforces logical in filter") expect_error(mutate(d, ok = if_all(x:y, identity)), info = "if_all() enforces logical in mutate") expect_error(mutate(d, ok = if_any(x:y, identity)), info = "if_any() enforces logical in mutate") d <- data.frame(x = c(1, 5, 10, 10), y = c(0, 0, 0, 10), z = c(10, 5, 1, 10)) res <- mutate(.data = d, any = if_any(x:z, ~ . > 8), all = if_all(x:z, ~ . > 8)) expect_equal(res$any, c(TRUE, FALSE, TRUE, TRUE), info = "if_any() can be used in mutate") expect_equal(res$all, c(FALSE, FALSE, FALSE, TRUE), info = "if_all() can be used in mutate") df <- expand.grid( x = c(TRUE, FALSE, NA), y = c(TRUE, FALSE, NA) ) expect_identical( filter(df, x & y), filter(df, if_all(c(x, y), identity)), info = "if_all() respects filter()-like NA handling" ) expect_identical( filter(df, x | y), filter(df, if_any(c(x, y), identity)), info = "if_any() respects filter()-like NA handling" ) expect_equal( mtcars %>% filter(if_any(contains("Width"), ~ . > 4)), mtcars[mtcars$mpg > 100, ], info = "if_any() conditions that return empty data.frames do not fail." ) expect_equal( mtcars %>% filter(if_all(contains("Width"), ~ . > 4)), mtcars[mtcars$mpg > 100, ], info = "if_all() conditions that return empty data.frames do not fail." )
genre.table <- read.table(text = " genre, genre.id unset, unset Alternative, 48 Gothic, 38 Grunge, 103 Metal - Extreme, 37 Metal (general), 36 Punk, 35 Chiptune, 54 Demo Style, 55 One Hour Compo, 53 Chillout, 106 Electronic - Ambient, 2 Electronic - Breakbeat, 9 Electronic - Dance, 3 Electronic - Drum and Bass, 6 Electronic - Gabber, 40 Electronic - Hardcore, 39 Electronic - House, 10 Electronic - IDM, 99 Electronic - Industrial, 34 Electronic - Jungle, 60 Electronic - Minimal, 101 Electronic - Other, 100 Electronic - Progressive, 11 Electronic - Rave, 65 Electronic - Techno, 7 Electronic (general), 1 Trance - Acid, 63 Trance - Dream, 67 Trance - Goa, 66 Trance - Hard, 64 Trance - Progressive, 85 Trance - Tribal, 70 Trance (general), 71 Big Band, 74 Blues, 19 Jazz - Acid, 30 Jazz - Modern, 31 Jazz (general), 29 Swing, 75 Bluegrass, 105 Classical, 20 Comedy, 45 Country, 18 Experimental, 46 Fantasy, 52 Folk, 21 Fusion, 102 Medieval, 28 New Ages, 44 Orchestral, 50 Other, 41 Piano, 59 Religious, 49 Soundtrack, 43 Spiritual, 47 Video Game, 8 Vocal Montage, 76 World, 42 Ballad, 56 Disco, 58 Easy Listening, 107 Funk, 32 Pop - Soft, 62 Pop - Synth, 61 Pop (general), 12 Rock - Hard, 14 Rock - Soft, 15 Rock (general), 13 Christmas, 72 Halloween, 82 Hip-Hop, 22 R and B, 26 Reggae, 27 Ska, 24 Soul, 25", header = T, sep = ",", stringsAsFactors = F, strip.white = T) htmlcodes <- read.table(text = " char, code 8364, 'euro' 32, 'nbsp' 34, 'quot' 38, 'amp' 60, 'lt' 62, 'gt' 160, 'nbsp' 161, 'iexcl' 162, 'cent' 163, 'pound' 164, 'curren' 165, 'yen' 166, 'brvbar' 167, 'sect' 168, 'uml' 169, 'copy' 170, 'ordf' 172, 'not' 173, 'shy' 174, 'reg' 175, 'macr' 176, 'deg' 177, 'plusmn' 178, 'sup2' 179, 'sup3' 180, 'acute' 181, 'micro' 182, 'para' 183, 'middot' 184, 'cedil' 185, 'sup1' 186, 'ordm' 187, 'raquo' 188, 'frac14' 189, 'frac12' 190, 'frac34' 191, 'iquest' 192, 'Agrave' 193, 'Aacute' 194, 'Acirc' 195, 'Atilde' 196, 'Auml' 197, 'Aring' 198, 'AElig' 199, 'Ccedil' 200, 'Egrave' 201, 'Eacute' 202, 'Ecirc' 203, 'Euml' 204, 'Igrave' 205, 'Iacute' 206, 'Icirc' 207, 'Iuml' 208, 'ETH' 209, 'Ntilde' 210, 'Ograve' 211, 'Oacute' 212, 'Ocirc' 213, 'Otilde' 214, 'Ouml' 215, 'times' 216, 'Oslash' 217, 'Ugrave' 218, 'Uacute' 219, 'Ucirc' 220, 'Uuml' 221, 'Yacute' 222, 'THORN' 223, 'szlig' 224, 'agrave' 225, 'aacute' 226, 'acirc' 227, 'atilde' 228, 'auml' 229, 'aring' 230, 'aelig' 231, 'ccedil' 232, 'egrave' 233, 'eacute' 234, 'ecirc' 235, 'euml' 236, 'igrave' 237, 'iacute' 238, 'icirc' 239, 'iuml' 240, 'eth' 241, 'ntilde' 242, 'ograve' 243, 'oacute' 244, 'ocirc' 245, 'otilde' 246, 'ouml' 247, 'divide' 248, 'oslash' 249, 'ugrave' 250, 'uacute' 251, 'ucirc' 252, 'uuml' 253, 'yacute' 254, 'thorn' ", sep = ",", header = T, quote = "'", strip.white = T) htmlcodes$char <- intToUtf8(htmlcodes$char, T) htmlcodes$code <- paste0("&", htmlcodes$code, ";") htmlcodes <- rbind(htmlcodes, data.frame( char = intToUtf8(32:383, T), code = sprintf("& )) .htmlUnescape <- function(text) { for (i in 1:nrow(htmlcodes)) text <- gsub(htmlcodes$code[i], htmlcodes$char[i], text, fixed = T) Encoding(text) <- "UTF-8" return(text) } modArchive.info <- function(mod.id, api.key) { mod.id <- as.integer(mod.id[[1]]) api.key <- as.character(api.key[[1]]) request.mod <- paste0("http://api.modarchive.org/xml-tools.php?key=", api.key, "&request=view_by_moduleid&query=",mod.id) result <- .get.module.table(request.mod, "module") return(result) } .get.module.table <- function(xmlcode, what) { xmlcode <- XML::xmlParse(xmlcode, options = XML::NOCDATA) result <- XML::xmlToList(xmlcode) if (any("error" %in% names(result))) stop (as.character(result$error)) totalpages <- as.numeric(result$totalpages) results <- as.numeric(result$results) if (what == "item") result <- result$items result <- lapply(result[names(result) == what], function(x) { lapply(x, function(x) { if (length(x) > 1) { x <- lapply(x, function(x) { x[is.null(x)] <- "NULL" x }) x <- unlist(x) paste(apply(cbind(names(x), paste0("<", x, ">")), 1, paste, collapse = "="), collapse = ";") } else { x[is.null(x)] <- "" x } }) }) result <- lapply(result, function(x) { x <- lapply(x, function(x) if (length(x) == 0) return("") else return(x)) data.frame(t(unlist(x))) }) result <- do.call(rbind, result) row.names(result) <- NULL if (what == "module") result <- .fix.module.table(result) if (what == "item") result <- .fix.artist.table(result) attr(result, "results") <- results attr(result, "totalpages") <- totalpages return(result) } .fix.module.table <- function(result) { result <- as.data.frame(as.matrix(result), stringsAsFactors = F) result$songtitle <- .htmlUnescape(result$songtitle) result$instruments <- .htmlUnescape(result$instruments) result$comment <- .htmlUnescape(result$comment) result$timestamp <- as.POSIXct(as.numeric(result$timestamp), origin = "1970-01-01 00:00", tz = "CET") numeric_sel <- c("bytes", "hits", "genreid", "id", "channels") result[,numeric_sel] <- as.data.frame(lapply(result[,numeric_sel], as.numeric)) return(result) } .fix.artist.table <- function(result) { result <- as.data.frame(as.matrix(result), stringsAsFactors = F) result$timestamp <- as.POSIXct(as.numeric(result$timestamp), origin = "1970-01-01 00:00", tz = "CET") numeric_sel <- c("id", "isartist") result[,numeric_sel] <- as.data.frame(lapply(result[,numeric_sel], as.numeric)) return(result) } modArchive.download <- function(mod.id, ...) { mod.id <- as.integer(mod.id[[1]]) con <- url(paste("http://api.modarchive.org/downloads.php?moduleid=", mod.id, sep = ""), "rb") mod <- read.module(con, ...) close(con) return (mod) } modArchive.search.mod <- function(search.text, search.where = c("filename_or_songtitle", "filename_and_songtitle", "filename", "songtitle", "module_instruments", "module_comments"), format.filter = c("unset", "669", "AHX", "DMF", "HVL", "IT", "MED", "MO3", "MOD", "MTM", "OCT", "OKT", "S3M", "STM", "XM"), size.filter = c("unset", "0-99", "100-299", "300-599", "600-1025", "1025-2999", "3072-6999", "7168-100000"), genre.filter = "deprecated", page, api.key) { search.text <- utils::URLencode(as.character(search.text[[1]])) search.where <- match.arg(search.where) format.filter <- match.arg(format.filter) size.filter <- match.arg(size.filter) api.key <- as.character(api.key[[1]]) if (!missing(genre.filter)) warning("Argument 'genre.filter' is deprecated in this function and not used since ProTrackR version 0.3.4. Use 'modArchive.view.by' to browse modules by genre.") xmlcode <- paste0("http://api.modarchive.org/xml-tools.php?key=", api.key, "&request=search&query=", search.text, "&type=", search.where) if (format.filter != "unset") xmlcode <- paste0(xmlcode, "&format=", format.filter) if (genre.filter != "unset") xmlcode <- paste0(xmlcode, "&genreid=", genre.filter) if (size.filter != "unset") xmlcode <- paste0(xmlcode, "&size=", size.filter) if (!missing(page)) xmlcode <- paste0(xmlcode, "&page=", as.integer(page[[1]])) result <- .get.module.table(xmlcode, "module") return(result) } modArchive.request.count <- function(api.key) { return(.requests("current", api.key)) } modArchive.max.requests <- function(api.key) { return(.requests("maximum", api.key)) } .requests <- function(index, api.key) { request.count <- XML::xmlTreeParse(paste0("http://api.modarchive.org/xml-tools.php?key=", api.key, "&request=view_requests")) count.root <- XML::xmlRoot(request.count) count.values <- XML::xmlSApply(count.root, function(x) XML::xmlSApply(x, XML::xmlValue)) return(as.integer(count.values$requests[[index]])) } modArchive.view.by <- function(view.query, view.by = c("view_by_list", "view_by_rating_comments", "view_by_rating_reviews", "view_modules_by_artistid", "view_modules_by_guessed_artist"), format.filter = c("unset", "669", "AHX", "DMF", "HVL", "IT", "MED", "MO3", "MOD", "MTM", "OCT", "OKT", "S3M", "STM", "XM"), size.filter = c("unset", "0-99", "100-299", "300-599", "600-1025", "1025-2999", "3072-6999", "7168-100000"), page, api.key) { view.query <- as.character(view.query[[1]]) format.filter <- match.arg(format.filter) size.filter <- match.arg(size.filter) api.key <- as.character(api.key[[1]]) xmlcode <- paste0("http://api.modarchive.org/xml-tools.php?key=", api.key, "&request=", view.by, "&query=", view.query) if (format.filter != "unset") xmlcode <- paste0(xmlcode, "&format=", format.filter) if (size.filter != "unset") xmlcode <- paste0(xmlcode, "&size=", size.filter) if (!missing(page)) xmlcode <- paste0(xmlcode, "&page=", as.integer(page[[1]])) result <- .get.module.table(xmlcode, "module") return(result) } modArchive.search.genre <- function(genre.filter = c("unset", "Alternative", "Gothic", "Grunge", "Metal - Extreme", "Metal (general)", "Punk", "Chiptune", "Demo Style", "One Hour Compo", "Chillout", "Electronic - Ambient", "Electronic - Breakbeat", "Electronic - Dance", "Electronic - Drum and Bass", "Electronic - Gabber", "Electronic - Hardcore", "Electronic - House", "Electronic - IDM", "Electronic - Industrial", "Electronic - Jungle", "Electronic - Minimal", "Electronic - Other", "Electronic - Progressive", "Electronic - Rave", "Electronic - Techno", "Electronic (general)", "Trance - Acid", "Trance - Dream", "Trance - Goa", "Trance - Hard", "Trance - Progressive", "Trance - Tribal", "Trance (general)", "Big Band", "Blues", "Jazz - Acid", "Jazz - Modern", "Jazz (general)", "Swing", "Bluegrass", "Classical", "Comedy", "Country", "Experimental", "Fantasy", "Folk", "Fusion", "Medieval", "New Ages", "Orchestral", "Other", "Piano", "Religious", "Soundtrack", "Spiritual", "Video Game", "Vocal Montage", "World", "Ballad", "Disco", "Easy Listening", "Funk", "Pop - Soft", "Pop - Synth", "Pop (general)", "Rock - Hard", "Rock - Soft", "Rock (general)", "Christmas", "Halloween", "Hip-Hop", "R and B", "Reggae", "Ska", "Soul"), format.filter = c("unset", "669", "AHX", "DMF", "HVL", "IT", "MED", "MO3", "MOD", "MTM", "OCT", "OKT", "S3M", "STM", "XM"), size.filter = c("unset", "0-99", "100-299", "300-599", "600-1025", "1025-2999", "3072-6999", "7168-100000"), page, api.key) { genre.filter <- match.arg(genre.filter) genre.filter <- genre.table$genre.id[genre.table$genre == genre.filter] format.filter <- match.arg(format.filter) size.filter <- match.arg(size.filter) api.key <- as.character(api.key[[1]]) xmlcode <- paste0("http://api.modarchive.org/xml-tools.php?key=", api.key, "&request=search&type=genre&query=", genre.filter) if (format.filter != "unset") xmlcode <- paste0(xmlcode, "&format=", format.filter) if (size.filter != "unset") xmlcode <- paste0(xmlcode, "&size=", size.filter) if (!missing(page)) xmlcode <- paste0(xmlcode, "&page=", as.integer(page[[1]])) result <- .get.module.table(xmlcode, "module") return(result) } modArchive.search.artist <- function(search.artist, page, api.key) { api.key <- as.character(api.key[[1]]) search.artist <- as.character(search.artist[[1]]) api.key <- as.character(api.key[[1]]) xmlcode <- paste0("http://api.modarchive.org/xml-tools.php?key=", api.key, "&request=search_artist&query=", search.artist) if (!missing(page)) xmlcode <- paste0(xmlcode, "&page=", as.integer(page[[1]])) result <- .get.module.table(xmlcode, "item") return(result) } modArchive.search.hash <- function(search.hash, api.key) { search.hash <- as.character(search.hash[[1]]) api.key <- as.character(api.key[[1]]) xmlcode <- paste0("http://api.modarchive.org/xml-tools.php?key=", api.key, "&request=search&type=hash&query=", search.hash) result <- .get.module.table(xmlcode, "module") return(result) } modArchive.random.pick <- function(genre.filter = c("Alternative", "Gothic", "Grunge", "Metal - Extreme", "Metal (general)", "Punk", "Chiptune", "Demo Style", "One Hour Compo", "Chillout", "Electronic - Ambient", "Electronic - Breakbeat", "Electronic - Dance", "Electronic - Drum and Bass", "Electronic - Gabber", "Electronic - Hardcore", "Electronic - House", "Electronic - IDM", "Electronic - Industrial", "Electronic - Jungle", "Electronic - Minimal", "Electronic - Other", "Electronic - Progressive", "Electronic - Rave", "Electronic - Techno", "Electronic (general)", "Trance - Acid", "Trance - Dream", "Trance - Goa", "Trance - Hard", "Trance - Progressive", "Trance - Tribal", "Trance (general)", "Big Band", "Blues", "Jazz - Acid", "Jazz - Modern", "Jazz (general)", "Swing", "Bluegrass", "Classical", "Comedy", "Country", "Experimental", "Fantasy", "Folk", "Fusion", "Medieval", "New Ages", "Orchestral", "Other", "Piano", "Religious", "Soundtrack", "Spiritual", "Video Game", "Vocal Montage", "World", "Ballad", "Disco", "Easy Listening", "Funk", "Pop - Soft", "Pop - Synth", "Pop (general)", "Rock - Hard", "Rock - Soft", "Rock (general)", "Christmas", "Halloween", "Hip-Hop", "R and B", "Reggae", "Ska", "Soul"), format.filter = c("unset", "669", "AHX", "DMF", "HVL", "IT", "MED", "MO3", "MOD", "MTM", "OCT", "OKT", "S3M", "STM", "XM"), size.filter = c("unset", "0-99", "100-299", "300-599", "600-1025", "1025-2999", "3072-6999", "7168-100000"), api.key) { genre.filter <- match.arg(genre.filter) genre.filter <- genre.table$genre.id[genre.table$genre == genre.filter] format.filter <- match.arg(format.filter) size.filter <- match.arg(size.filter) api.key <- as.character(api.key[[1]]) xmlcode <- paste0("http://api.modarchive.org/xml-tools.php?key=", api.key, "&request=random") if (format.filter != "unset") xmlcode <- paste0(xmlcode, "&format=", format.filter) if (size.filter != "unset") xmlcode <- paste0(xmlcode, "&size=", size.filter) if (genre.filter != "unset") xmlcode <- paste0(xmlcode, "&genreid=", genre.filter) result <- .get.module.table(xmlcode, "module") return(result) }
facet_wrap_paginate <- function(facets, nrow = NULL, ncol = NULL, scales = "fixed", shrink = TRUE, labeller = "label_value", as.table = TRUE, switch = NULL, drop = TRUE, dir = "h", strip.position = "top", page = 1) { facet <- ggplot2::facet_wrap( facets, nrow = nrow, ncol = ncol, scales = scales, shrink = shrink, labeller = labeller, as.table = as.table, switch = switch, drop = drop, dir = dir, strip.position = strip.position ) if (is.null(nrow) || is.null(ncol)) { facet } else { ggplot2::ggproto( NULL, FacetWrapPaginate, shrink = shrink, params = c(facet$params, list(page = page)) ) } } `%||%` <- function(x, y) { if (is.null(x)) y else x } FacetWrapPaginate <- ggplot2::ggproto( "FacetWrapPaginate", ggplot2::FacetWrap, setup_params = function(data, params) { if (!is.null(params$nrow)) { modifyList( params, list( max_rows = params$nrow, nrow = NULL ) ) } else { params } }, compute_layout = function(data, params) { layout <- FacetWrap$compute_layout(data, params) layout$page <- ceiling(layout$ROW / params$max_rows) layout }, draw_panels = function(panels, layout, x_scales, y_scales, ranges, coord, data, theme, params) { include <- which(layout$page == params$page) panels <- panels[include] ranges <- ranges[include] layout <- layout[include, , drop = FALSE] layout$ROW <- layout$ROW - min(layout$ROW) + 1 x_scale_ind <- unique(layout$SCALE_X) x_scales <- x_scales[x_scale_ind] layout$SCALE_X <- match(layout$SCALE_X, x_scale_ind) y_scale_ind <- unique(layout$SCALE_Y) y_scales <- y_scales[y_scale_ind] layout$SCALE_Y <- match(layout$SCALE_Y, y_scale_ind) table <- FacetWrap$draw_panels( panels, layout, x_scales, y_scales, ranges, coord, data, theme, params ) if (max(layout$ROW) != params$max_rows) { spacing <- theme$panel.spacing.y %||% theme$panel.spacing missing_rows <- params$max_rows - max(layout$ROW) strip_rows <- unique( table$layout$t[grepl("strip", table$layout$name) & table$layout$l %in% panel_cols(table)$l] ) strip_rows <- strip_rows[as.numeric(table$heights[strip_rows]) != 0] axis_b_rows <- unique(table$layout$t[grepl("axis-b", table$layout$name)]) axis_b_rows <- axis_b_rows[as.numeric(table$heights[axis_b_rows]) != 0] axis_t_rows <- unique(table$layout$t[grepl("axis-t", table$layout$name)]) axis_t_rows <- axis_t_rows[as.numeric(table$heights[axis_t_rows]) != 0] table <- gtable_add_rows(table, unit(missing_rows, "null")) table <- gtable_add_rows(table, spacing * missing_rows) if (length(strip_rows) != 0) { table <- gtable_add_rows( table, min(table$heights[strip_rows]) * missing_rows ) } if (params$free$x) { if (length(axis_b_rows) != 0) { table <- gtable_add_rows( table, min(table$heights[axis_b_rows]) * missing_rows ) } if (length(axis_t_rows) != 0) { table <- gtable_add_rows( table, min(table$heights[axis_t_rows]) * missing_rows ) } } } if (max(layout$COL) != params$ncol) { spacing <- theme$panel.spacing.x %||% theme$panel.spacing missing_cols <- params$ncol - max(layout$COL) strip_cols <- unique( table$layout$t[ grepl("strip", table$layout$name) & table$layout$t %in% panel_rows(table)$t ] ) strip_cols <- strip_cols[as.numeric(table$widths[strip_cols]) != 0] axis_l_cols <- unique(table$layout$l[grepl("axis-l", table$layout$name)]) axis_l_cols <- axis_l_cols[as.numeric(table$widths[axis_l_cols]) != 0] axis_r_cols <- unique(table$layout$l[grepl("axis-r", table$layout$name)]) axis_r_cols <- axis_r_cols[as.numeric(table$widths[axis_r_cols]) != 0] table <- gtable_add_cols(table, unit(missing_cols, "null")) table <- gtable_add_cols(table, spacing * missing_cols) if (length(strip_cols) != 0) { table <- gtable_add_cols( table, min(table$widths[strip_cols]) * missing_cols ) } if (params$free$y) { if (length(axis_l_cols) != 0) { table <- gtable_add_cols( table, min(table$widths[axis_l_cols]) * missing_cols ) } if (length(axis_r_cols) != 0) { table <- gtable_add_cols( table, min(table$widths[axis_r_cols]) * missing_cols ) } } } table } ) n_pages <- function(plot) { page <- ggplot_build(plot)$layout$panel_layout$page if (!is.null(page)) { max(page) } else { NULL } }
library(testthat) library(parsnip) library(rlang) context("poly SVM") source(test_path("helpers.R")) source(test_path("helper-objects.R")) hpc <- hpc_data[1:150, c(2:5, 8)] test_that('primary arguments', { basic <- svm_rbf(mode = "regression") basic_kernlab <- translate(basic %>% set_engine("kernlab")) expect_equal( object = basic_kernlab$method$fit$args, expected = list( x = expr(missing_arg()), data = expr(missing_arg()), kernel = "rbfdot" ) ) rbf_sigma <- svm_rbf(mode = "regression", rbf_sigma = .2) rbf_sigma_kernlab <- translate(rbf_sigma %>% set_engine("kernlab")) rbf_sigma_obj <- expr(list()) rbf_sigma_obj$sigma <- new_empty_quosure(.2) expect_equal( object = rbf_sigma_kernlab$method$fit$args, expected = list( x = expr(missing_arg()), data = expr(missing_arg()), kernel = "rbfdot", kpar = rbf_sigma_obj ) ) }) test_that('engine arguments', { kernlab_cv <- svm_rbf(mode = "regression") %>% set_engine("kernlab", cross = 10) expect_equal( object = translate(kernlab_cv, "kernlab")$method$fit$args, expected = list( x = expr(missing_arg()), data = expr(missing_arg()), cross = new_empty_quosure(10), kernel = "rbfdot" ) ) }) test_that('updating', { expr1 <- svm_rbf(mode = "regression") %>% set_engine("kernlab", cross = 10) expr1_exp <- svm_rbf(mode = "regression", rbf_sigma = .1) %>% set_engine("kernlab", cross = 10) expr2 <- svm_rbf(mode = "regression") %>% set_engine("kernlab", cross = varying()) expr2_exp <- svm_rbf(mode = "regression") %>% set_engine("kernlab", cross = 10) expr3 <- svm_rbf(mode = "regression", rbf_sigma = .2) %>% set_engine("kernlab") expr3_exp <- svm_rbf(mode = "regression", rbf_sigma = .3) %>% set_engine("kernlab") expect_equal(update(expr1, rbf_sigma = .1), expr1_exp) expect_equal(update(expr2, cross = 10), expr2_exp) expect_equal(update(expr3, rbf_sigma = .3, fresh = TRUE), expr3_exp) param_tibb <- tibble::tibble(rbf_sigma = 3, cost = 10) param_list <- as.list(param_tibb) expr1_updated <- update(expr1, param_tibb) expect_equal(expr1_updated$args$rbf_sigma, 3) expect_equal(expr1_updated$args$cost, 10) expect_equal(expr1_updated$eng_args$cross, rlang::quo(10)) expr1_updated_lst <- update(expr1, param_list) expect_equal(expr1_updated_lst$args$rbf_sigma, 3) expect_equal(expr1_updated_lst$args$cost, 10) expect_equal(expr1_updated_lst$eng_args$cross, rlang::quo(10)) }) test_that('bad input', { expect_error(svm_rbf(mode = "reallyunknown")) expect_error(translate(svm_rbf(mode = "regression") %>% set_engine( NULL))) }) reg_mod <- svm_rbf(mode = "regression", rbf_sigma = .1, cost = 1/4) %>% set_engine("kernlab") %>% set_mode("regression") cls_mod <- svm_rbf(mode = "classification", rbf_sigma = .1, cost = 1/8) %>% set_engine("kernlab") %>% set_mode("classification") ctrl <- control_parsnip(verbosity = 0, catch = FALSE) test_that('svm poly regression', { skip_if_not_installed("kernlab") expect_error( res <- fit_xy( reg_mod, control = ctrl, x = hpc[,2:4], y = hpc$input_fields ), regexp = NA ) expect_false(has_multi_predict(res)) expect_equal(multi_predict_args(res), NA_character_) expect_output(print(res), "parsnip model object") expect_error( fit( reg_mod, input_fields ~ ., data = hpc[, -5], control = ctrl ), regexp = NA ) }) test_that('svm rbf regression prediction', { skip_if_not_installed("kernlab") hpc_no_m <- hpc[-c(84, 85, 86, 87, 88, 109, 128),] %>% droplevels() ind <- c(2, 1, 143) reg_form <- fit( reg_mod, input_fields ~ ., data = hpc[, -5], control = ctrl ) kern_pred <- structure( list(.pred = c(131.7743, 372.0932, 902.0633)), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame")) parsnip_pred <- predict(reg_form, hpc[ind, -c(2, 5)]) expect_equal(as.data.frame(kern_pred), as.data.frame(parsnip_pred), tolerance = .0001) reg_xy_form <- fit_xy( reg_mod, x = hpc[, c(1, 3, 4)], y = hpc$input_fields, control = ctrl ) expect_equal(reg_form$fit@alphaindex, reg_xy_form$fit@alphaindex) parsnip_xy_pred <- predict(reg_xy_form, hpc[ind, -c(2, 5)]) expect_equal(as.data.frame(kern_pred), as.data.frame(parsnip_xy_pred), tolerance = .0001) }) test_that('svm rbf classification', { skip_if_not_installed("kernlab") hpc_no_m <- hpc[-c(84, 85, 86, 87, 88, 109, 128),] %>% droplevels() ind <- c(2, 1, 143) expect_error( fit_xy( cls_mod, control = ctrl, x = hpc_no_m[, -5], y = hpc_no_m$class ), regexp = NA ) expect_error( fit( cls_mod, class ~ ., data = hpc_no_m, control = ctrl ), regexp = NA ) }) test_that('svm rbf classification probabilities', { skip_if_not_installed("kernlab") hpc_no_m <- hpc[-c(84, 85, 86, 87, 88, 109, 128),] %>% droplevels() ind <- c(4, 55, 143) set.seed(34562) cls_form <- fit( cls_mod, class ~ ., data = hpc_no_m, control = ctrl ) kern_class <- structure(list( .pred_class = structure( c(1L, 1L, 3L), .Label = c("VF", "F", "L"), class = "factor")), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame")) parsnip_class <- predict(cls_form, hpc_no_m[ind, -5]) expect_equal(kern_class, parsnip_class) set.seed(34562) cls_xy_form <- fit_xy( cls_mod, x = hpc_no_m[, 1:4], y = hpc_no_m$class, control = ctrl ) expect_equal(cls_form$fit@alphaindex, cls_xy_form$fit@alphaindex) library(kernlab) kern_probs <- kernlab::predict(cls_form$fit, hpc_no_m[ind, -5], type = "probabilities") %>% as_tibble() %>% setNames(c('.pred_VF', '.pred_F', '.pred_L')) parsnip_probs <- predict(cls_form, hpc_no_m[ind, -5], type = "prob") expect_equal(as.data.frame(kern_probs), as.data.frame(parsnip_probs)) parsnip_xy_probs <- predict(cls_xy_form, hpc_no_m[ind, -5], type = "prob") expect_equal(as.data.frame(kern_probs), as.data.frame(parsnip_xy_probs)) })
.install_packages <- function(args = NULL) { curPkg <- character() lockdir <- "" is_first_package <- TRUE stars <- "*" user.tmpdir <- Sys.getenv("PKG_BUILD_DIR") keep.tmpdir <- nzchar(user.tmpdir) tmpdir <- "" clean_on_error <- TRUE do_exit_on_error <- function() { if(clean_on_error && length(curPkg)) { pkgdir <- file.path(lib, curPkg) if (nzchar(pkgdir) && dir.exists(pkgdir) && is_subdir(pkgdir, lib)) { starsmsg(stars, "removing ", sQuote(pkgdir)) unlink(pkgdir, recursive = TRUE) } if (nzchar(lockdir) && dir.exists(lp <- file.path(lockdir, curPkg)) && is_subdir(lp, lockdir)) { starsmsg(stars, "restoring previous ", sQuote(pkgdir)) if (WINDOWS) { file.copy(lp, dirname(pkgdir), recursive = TRUE, copy.date = TRUE) unlink(lp, recursive = TRUE) } else { setwd(startdir) system(paste("mv", shQuote(lp), shQuote(pkgdir))) } } } do_cleanup() q("no", status = 1, runLast = FALSE) } do_cleanup <- function() { if(!keep.tmpdir && nzchar(tmpdir)) do_cleanup_tmpdir() if (!is_first_package) { if (lib == .Library && "html" %in% build_help_types) utils::make.packages.html(.Library, docdir = R.home("doc")) } if (nzchar(lockdir)) unlink(lockdir, recursive = TRUE) } do_cleanup_tmpdir <- function() { setwd(startdir) if (!keep.tmpdir && dir.exists(tmpdir)) unlink(tmpdir, recursive=TRUE) } on.exit(do_exit_on_error()) WINDOWS <- .Platform$OS.type == "windows" if (WINDOWS) MAKE <- "make" else MAKE <- Sys.getenv("MAKE") rarch <- Sys.getenv("R_ARCH") if (WINDOWS && nzchar(.Platform$r_arch)) rarch <- paste0("/", .Platform$r_arch) test_archs <- rarch SHLIB_EXT <- if (WINDOWS) ".dll" else { mconf <- file.path(R.home(), paste0("etc", rarch), "Makeconf") sub(".*= ", "", grep("^SHLIB_EXT", readLines(mconf), value = TRUE, perl = TRUE)) } options(warn = 1) invisible(Sys.setlocale("LC_COLLATE", "C")) if (WINDOWS) { rhome <- chartr("\\", "/", R.home()) Sys.setenv(R_HOME = rhome) if (nzchar(rarch)) Sys.setenv(R_ARCH = rarch, R_ARCH_BIN = rarch) } Usage <- function() { cat("Usage: R CMD INSTALL [options] pkgs", "", "Install the add-on packages specified by pkgs. The elements of pkgs can", "be relative or absolute paths to directories with the package", "sources, or to gzipped package 'tar' archives. The library tree", "to install to can be specified via '--library'. By default, packages are", "installed in the library tree rooted at the first directory in", ".libPaths() for an R session run in the current environment", "", "Options:", " -h, --help print short help message and exit", " -v, --version print INSTALL version info and exit", " -c, --clean remove files created during installation", " --preclean remove files created during a previous run", " -d, --debug turn on debugging messages", if(WINDOWS) " and build a debug DLL", " -l, --library=LIB install packages to library tree LIB", " --no-configure do not use the package's configure script", " --no-docs do not install HTML, LaTeX or examples help", " --html build HTML help", " --no-html do not build HTML help", " --latex install LaTeX help", " --example install R code for help examples", " --fake do minimal install for testing purposes", " --no-lock install on top of any existing installation", " without using a lock directory", " --lock use a per-library lock directory (default)", " --pkglock use a per-package lock directory", " (default for a single package)", " --build build binaries of the installed package(s)", " --install-tests install package-specific tests (if any)", " --no-R, --no-libs, --no-data, --no-help, --no-demo, --no-exec,", " --no-inst", " suppress installation of the specified part of the", " package for testing or other special purposes", " --no-multiarch build only the main architecture", " --libs-only only install the libs directory", " --data-compress= none, gzip (default), bzip2 or xz compression", " to be used for lazy-loading of data", " --resave-data re-save data files as compactly as possible", " --compact-docs re-compress PDF files under inst/doc", " --with-keep.source", " --without-keep.source", " use (or not) 'keep.source' for R code", " --byte-compile byte-compile R code", " --no-byte-compile do not byte-compile R code", " --no-test-load skip test of loading installed package", " --no-clean-on-error do not remove installed package on error", " --merge-multiarch multi-arch by merging (from a single tarball only)", "\nfor Unix", " --configure-args=ARGS", " set arguments for the configure scripts (if any)", " --configure-vars=VARS", " set variables for the configure scripts (if any)", " --dsym (OS X only) generate dSYM directory", " --built-timestamp=STAMP", " set timestamp for Built: entry in DESCRIPTION", "\nand on Windows only", " --force-biarch attempt to build both architectures", " even if there is a non-empty configure.win", " --compile-both compile both architectures on 32-bit Windows", "", "Which of --html or --no-html is the default depends on the build of R:", paste0("for this one it is ", if(static_html) "--html" else "--no-html", "."), "", "Report bugs at bugs.r-project.org .", sep = "\n") } is_subdir <- function(dir, parent) normalizePath(parent) == normalizePath(file.path(dir, "..")) fullpath <- function(dir) { owd <- setwd(dir) full <- getwd() setwd(owd) full } parse_description_field <- function(desc, field, default = TRUE) { tmp <- desc[field] if (is.na(tmp)) default else switch(tmp, "yes"=, "Yes" =, "true" =, "True" =, "TRUE" = TRUE, "no" =, "No" =, "false" =, "False" =, "FALSE" = FALSE, errmsg("invalid value of ", field, " field in DESCRIPTION") ) } starsmsg <- function(stars, ...) message(stars, " ", ..., domain = NA) errmsg <- function(...) { message("ERROR: ", ..., domain = NA) do_exit_on_error() } pkgerrmsg <- function(msg, pkg) { message("ERROR: ", msg, " for package ", sQuote(pkg), domain = NA) do_exit_on_error() } do_install <- function(pkg) { if (WINDOWS && grepl("\\.zip$", pkg)) { pkg_name <- basename(pkg) pkg_name <- sub("\\.zip$", "", pkg_name) pkg_name <- sub("_[0-9.-]+$", "", pkg_name) utils:::unpackPkgZip(pkg, pkg_name, lib, libs_only) return() } setwd(pkg) desc <- tryCatch(read.dcf(fd <- file.path(pkg, "DESCRIPTION")), error = identity) if(inherits(desc, "error") || !length(desc)) stop(gettextf("error reading file '%s'", fd), domain = NA, call. = FALSE) desc <- desc[1L,] if (!is.na(desc["Bundle"])) { stop("this seems to be a bundle -- and they are defunct") } else { pkg_name <- desc["Package"] if (is.na(pkg_name)) errmsg("no 'Package' field in 'DESCRIPTION'") curPkg <<- pkg_name } instdir <- file.path(lib, pkg_name) Sys.setenv(R_PACKAGE_NAME = pkg_name, R_PACKAGE_DIR = instdir) status <- .Rtest_package_depends_R_version() if (status) do_exit_on_error() dir.create(instdir, recursive = TRUE, showWarnings = FALSE) if (!dir.exists(instdir)) { message("ERROR: unable to create ", sQuote(instdir), domain = NA) do_exit_on_error() } if (!is_subdir(instdir, lib)) { message("ERROR: ", sQuote(pkg_name), " is not a legal package name", domain = NA) do_exit_on_error() } owd <- setwd(instdir) if (owd == getwd()) pkgerrmsg("cannot install to srcdir", pkg_name) setwd(owd) is_source_package <- is.na(desc["Built"]) if (is_source_package) { sys_requires <- desc["SystemRequirements"] if (!is.na(sys_requires)) { sys_requires <- unlist(strsplit(sys_requires, ",")) if(any(grepl("^[[:space:]]*C[+][+]11[[:space:]]*$", sys_requires, ignore.case=TRUE))) { Sys.setenv("R_PKG_CXX_STD"="CXX11") on.exit(Sys.unsetenv("R_PKG_CXX_STD")) } } } if (!is_first_package) cat("\n") if (is_source_package) do_install_source(pkg_name, instdir, pkg, desc) else do_install_binary(pkg_name, instdir, desc) .Call(dirchmod, instdir, group.writable) is_first_package <<- FALSE if (tar_up) { starsmsg(stars, "creating tarball") version <- desc["Version"] filename <- if (!grepl("darwin", R.version$os)) { paste0(pkg_name, "_", version, "_R_", Sys.getenv("R_PLATFORM"), ".tar.gz") } else { paste0(pkg_name, "_", version,".tgz") } filepath <- file.path(startdir, filename) owd <- setwd(lib) res <- utils::tar(filepath, curPkg, compression = "gzip", compression_level = 9L, tar = Sys.getenv("R_INSTALL_TAR")) if (res) errmsg(sprintf("packaging into %s failed", sQuote(filename))) message("packaged installation of ", sQuote(pkg_name), " as ", sQuote(filename), domain = NA) setwd(owd) } if (zip_up) { starsmsg(stars, "MD5 sums") .installMD5sums(instdir) ZIP <- "zip" version <- desc["Version"] filename <- paste0(pkg_name, "_", version, ".zip") filepath <- shQuote(file.path(startdir, filename)) unlink(filepath) owd <- setwd(lib) res <- system(paste(shQuote(ZIP), "-r9Xq", filepath, paste(curPkg, collapse = " "))) setwd(owd) if (res) message("running 'zip' failed", domain = NA) else message("packaged installation of ", sQuote(pkg_name), " as ", filename, domain = NA) } if (Sys.getenv("_R_INSTALL_NO_DONE_") != "yes") { starsmsg(stars, "DONE (", pkg_name, ")") } curPkg <<- character() } do_install_binary <- function(pkg, instdir, desc) { starsmsg(stars, "installing *binary* package ", sQuote(pkg), " ...") if (file.exists(file.path(instdir, "DESCRIPTION"))) { if (nzchar(lockdir)) system(paste("mv", shQuote(instdir), shQuote(file.path(lockdir, pkg)))) dir.create(instdir, recursive = TRUE, showWarnings = FALSE) } TAR <- Sys.getenv("TAR", 'tar') res <- system(paste("cp -R .", shQuote(instdir), "|| (", TAR, "cd - .| (cd", shQuote(instdir), "&&", TAR, "-xf -))" )) if (res) errmsg("installing binary package failed") if (tar_up) { starsmsg(stars, sQuote(pkg), " was already a binary package and will not be rebuilt") tar_up <- FALSE } } run_clean <- function() { if (dir.exists("src") && length(dir("src", all.files = TRUE) > 2L)) { if (WINDOWS) archs <- c("i386", "x64") else { wd2 <- setwd(file.path(R.home("bin"), "exec")) archs <- Sys.glob("*") setwd(wd2) } if(length(archs)) for(arch in archs) { ss <- paste("src", arch, sep = "-") .Call(dirchmod, ss, group.writable) unlink(ss, recursive = TRUE) } owd <- setwd("src") if (WINDOWS) { if (file.exists("Makefile.win")) system(paste(MAKE, "-f Makefile.win clean")) else unlink(c("Makedeps", Sys.glob("*_res.rc"), Sys.glob("*.[do]"))) } else { if (file.exists("Makefile")) system(paste(MAKE, "clean")) else unlink(Sys.glob(paste0("*", SHLIB_EXT))) } setwd(owd) } if (WINDOWS) { if (file.exists("cleanup.win")) system("sh ./cleanup.win") } else if (file_test("-x", "cleanup")) system("./cleanup") else if (file.exists("cleanup")) warning("'cleanup' exists but is not executable -- see the 'R Installation and Administration Manual'", call. = FALSE) } do_install_source <- function(pkg_name, instdir, pkg_dir, desc) { Sys.setenv("R_INSTALL_PKG" = pkg_name) on.exit(Sys.unsetenv("R_INSTALL_PKG")) shlib_install <- function(instdir, arch) { if (file.exists("install.libs.R")) { message("installing via 'install.libs.R' to ", instdir, domain = NA) local.env <- local({ SHLIB_EXT <- SHLIB_EXT R_PACKAGE_DIR <- instdir R_PACKAGE_NAME <- pkg_name R_PACKAGE_SOURCE <- pkg_dir R_ARCH <- arch WINDOWS <- WINDOWS environment()}) parent.env(local.env) <- .GlobalEnv source("install.libs.R", local = local.env) return(TRUE) } files <- Sys.glob(paste0("*", SHLIB_EXT)) if (length(files)) { libarch <- if (nzchar(arch)) paste0("libs", arch) else "libs" dest <- file.path(instdir, libarch) message('installing to ', dest, domain = NA) dir.create(dest, recursive = TRUE, showWarnings = FALSE) file.copy(files, dest, overwrite = TRUE) if (!WINDOWS) Sys.chmod(file.path(dest, files), dmode) if (dsym && startsWith(R.version$os, "darwin")) { message(gettextf("generating debug symbols (%s)", "dSYM"), domain = NA) dylib <- Sys.glob(paste0(dest, "/*", SHLIB_EXT)) for (file in dylib) system(paste0("dsymutil ", file)) } if(config_val_to_logical(Sys.getenv("_R_SHLIB_BUILD_OBJECTS_SYMBOL_TABLES_", "TRUE")) && file_test("-f", "symbols.rds")) { file.copy("symbols.rds", dest) } } } run_shlib <- function(pkg_name, srcs, instdir, arch) { args <- c(shargs, "-o", paste0(pkg_name, SHLIB_EXT), srcs) if (WINDOWS && debug) args <- c(args, "--debug") if (debug) message("about to run ", "R CMD SHLIB ", paste(args, collapse = " "), domain = NA) if (.shlib_internal(args) == 0L) { if(WINDOWS && !file.exists("install.libs.R") && !length(Sys.glob("*.dll"))) { message("no DLL was created") return(TRUE) } shlib_install(instdir, arch) return(FALSE) } else return(TRUE) } Sys.setenv(R_LIBRARY_DIR = lib) if (nzchar(lib0)) { rlibs <- Sys.getenv("R_LIBS") rlibs <- if (nzchar(rlibs)) paste(lib, rlibs, sep = .Platform$path.sep) else lib Sys.setenv(R_LIBS = rlibs) .libPaths(c(lib, .libPaths())) } Type <- desc["Type"] if (!is.na(Type) && Type == "Frontend") { if (WINDOWS) errmsg("'Frontend' packages are Unix-only") starsmsg(stars, "installing *Frontend* package ", sQuote(pkg_name), " ...") if (preclean) system(paste(MAKE, "clean")) if (use_configure) { if (file_test("-x", "configure")) { res <- system(paste(paste(configure_vars, collapse = " "), "./configure", paste(configure_args, collapse = " "))) if (res) pkgerrmsg("configuration failed", pkg_name) } else if (file.exists("configure")) errmsg("'configure' exists but is not executable -- see the 'R Installation and Administration Manual'") } if (file.exists("Makefile")) if (system(MAKE)) pkgerrmsg("make failed", pkg_name) if (clean) system(paste(MAKE, "clean")) return() } if (!is.na(Type) && Type == "Translation") errmsg("'Translation' packages are defunct") OS_type <- desc["OS_type"] if (WINDOWS) { if ((!is.na(OS_type) && OS_type == "unix") && !fake) errmsg(" Unix-only package") } else { if ((!is.na(OS_type) && OS_type == "windows") && !fake) errmsg(" Windows-only package") } if(group.writable) { fmode <- "664" dmode <- "775" } else { fmode <- "644" dmode <- "755" } pkgInfo <- .split_description(.read_description("DESCRIPTION")) pkgs <- unique(c(names(pkgInfo$Depends), names(pkgInfo$Imports), names(pkgInfo$LinkingTo))) if (length(pkgs)) { miss <- character() for (pkg in pkgs) { if(!length(find.package(pkg, quiet = TRUE))) miss <- c(miss, pkg) } if (length(miss) > 1) pkgerrmsg(sprintf("dependencies %s are not available", paste(sQuote(miss), collapse = ", ")), pkg_name) else if (length(miss)) pkgerrmsg(sprintf("dependency %s is not available", sQuote(miss)), pkg_name) } starsmsg(stars, "installing *source* package ", sQuote(pkg_name), " ...") stars <- "**" res <- checkMD5sums(pkg_name, getwd()) if(!is.na(res) && res) { starsmsg(stars, gettextf("package %s successfully unpacked and MD5 sums checked", sQuote(pkg_name))) } if (file.exists(file.path(instdir, "DESCRIPTION"))) { if (nzchar(lockdir)) { if (debug) starsmsg(stars, "backing up earlier installation") if(WINDOWS) { file.copy(instdir, lockdir, recursive = TRUE, copy.date = TRUE) if (more_than_libs) unlink(instdir, recursive = TRUE) } else if (more_than_libs) system(paste("mv", shQuote(instdir), shQuote(file.path(lockdir, pkg_name)))) else file.copy(instdir, lockdir, recursive = TRUE, copy.date = TRUE) } else if (more_than_libs) unlink(instdir, recursive = TRUE) dir.create(instdir, recursive = TRUE, showWarnings = FALSE) } if (preclean) run_clean() if (use_configure) { if (WINDOWS) { if (file.exists("configure.win")) { res <- system("sh ./configure.win") if (res) pkgerrmsg("configuration failed", pkg_name) } else if (file.exists("configure")) message("\n", " **********************************************\n", " WARNING: this package has a configure script\n", " It probably needs manual configuration\n", " **********************************************\n\n", domain = NA) } else { if (file_test("-x", "configure")) { cmd <- paste(paste(configure_vars, collapse = " "), "./configure", paste(configure_args, collapse = " ")) if (debug) message("configure command: ", sQuote(cmd), domain = NA) cmd <- paste("_R_SHLIB_BUILD_OBJECTS_SYMBOL_TABLES_=false", cmd) res <- system(cmd) if (res) pkgerrmsg("configuration failed", pkg_name) } else if (file.exists("configure")) errmsg("'configure' exists but is not executable -- see the 'R Installation and Administration Manual'") } } if (more_than_libs) { for (f in c("NAMESPACE", "LICENSE", "LICENCE", "NEWS", "NEWS.md")) if (file.exists(f)) { file.copy(f, instdir, TRUE) Sys.chmod(file.path(instdir, f), fmode) } res <- try(.install_package_description('.', instdir, built_stamp)) if (inherits(res, "try-error")) pkgerrmsg("installing package DESCRIPTION failed", pkg_name) if (!file.exists(namespace <- file.path(instdir, "NAMESPACE")) ) { if(dir.exists("R")) errmsg("a 'NAMESPACE' file is required") else writeLines(" } } if (install_libs && dir.exists("src") && length(dir("src", all.files = TRUE) > 2L)) { starsmsg(stars, "libs") if (!file.exists(file.path(R.home("include"), "R.h"))) warning("R include directory is empty -- perhaps need to install R-devel.rpm or similar", call. = FALSE) has_error <- FALSE linkTo <- pkgInfo$LinkingTo if (!is.null(linkTo)) { lpkgs <- sapply(linkTo, function(x) x[[1L]]) paths <- find.package(lpkgs, quiet = TRUE) bpaths <- basename(paths) if (length(paths)) { have_vers <- (lengths(linkTo) > 1L) & lpkgs %in% bpaths for (z in linkTo[have_vers]) { p <- z[[1L]] path <- paths[bpaths %in% p] current <- readRDS(file.path(path, "Meta", "package.rds"))$DESCRIPTION["Version"] target <- as.numeric_version(z$version) if (!do.call(z$op, list(as.numeric_version(current), target))) stop(gettextf("package %s %s was found, but %s %s is required by %s", sQuote(p), current, z$op, target, sQuote(pkgname)), call. = FALSE, domain = NA) } clink_cppflags <- paste(paste0('-I"', paths, '/include"'), collapse = " ") Sys.setenv(CLINK_CPPFLAGS = clink_cppflags) } } else clink_cppflags <- "" libdir <- file.path(instdir, paste0("libs", rarch)) dir.create(libdir, showWarnings = FALSE) if (WINDOWS) { owd <- setwd("src") makefiles <- character() if (!is.na(f <- Sys.getenv("R_MAKEVARS_USER", NA_character_))) { if (file.exists(f)) makefiles <- f } else if (file.exists(f <- path.expand("~/.R/Makevars.win"))) makefiles <- f else if (file.exists(f <- path.expand("~/.R/Makevars"))) makefiles <- f if (file.exists("Makefile.win")) { makefiles <- c("Makefile.win", makefiles) message(" running 'src/Makefile.win' ...", domain = NA) res <- system(paste("make --no-print-directory", paste("-f", shQuote(makefiles), collapse = " "))) if (res == 0) shlib_install(instdir, rarch) else has_error <- TRUE } else { srcs <- dir(pattern = "\\.([cfmM]|cc|cpp|f90|f95|mm)$", all.files = TRUE) archs <- if (!force_both && !grepl(" x64 ", utils::win.version())) "i386" else { f <- dir(file.path(R.home(), "bin")) f[f %in% c("i386", "x64")] } one_only <- !multiarch if(!one_only && file.exists("../configure.win")) { if(!pkg_name %in% c("AnalyzeFMRI", "CORElearn", "PearsonDS", "PKI", "RGtk2", "RNetCDF", "RODBC", "RSclient", "Rcpp", "Runuran", "SQLiteMap", "XML", "arulesSequences", "cairoDevice", "diversitree", "foreign", "fastICA", "glmnet", "gstat", "igraph", "jpeg", "png", "proj4", "randtoolbox", "rgdal", "rngWELL", "rphast", "rtfbs", "sparsenet", "tcltk2", "tiff", "udunits2")) one_only <- sum(nchar(readLines("../configure.win", warn = FALSE), "bytes")) > 0 if(one_only && !force_biarch) { if(parse_description_field(desc, "Biarch", FALSE)) force_biarch <- TRUE else warning("this package has a non-empty 'configure.win' file,\nso building only the main architecture\n", call. = FALSE, domain = NA) } } if(force_biarch) one_only <- FALSE if(one_only || length(archs) < 2L) has_error <- run_shlib(pkg_name, srcs, instdir, rarch) else { setwd(owd) test_archs <- archs for(arch in archs) { message("", domain = NA) starsmsg("***", "arch - ", arch) ss <- paste("src", arch, sep = "-") dir.create(ss, showWarnings = FALSE) file.copy(Sys.glob("src/*"), ss, recursive = TRUE) .Call(dirchmod, ss, group.writable) setwd(ss) ra <- paste0("/", arch) Sys.setenv(R_ARCH = ra, R_ARCH_BIN = ra) has_error <- run_shlib(pkg_name, srcs, instdir, ra) setwd(owd) if (has_error) break } } } setwd(owd) } else { if (file.exists("src/Makefile")) { arch <- substr(rarch, 2, 1000) starsmsg(stars, "arch - ", arch) owd <- setwd("src") system_makefile <- file.path(R.home(), paste0("etc", rarch), "Makeconf") makefiles <- c(system_makefile, makevars_site(), "Makefile", makevars_user()) res <- system(paste(MAKE, paste("-f", shQuote(makefiles), collapse = " "))) if (res == 0) shlib_install(instdir, rarch) else has_error <- TRUE setwd(owd) } else { owd <- setwd("src") srcs <- dir(pattern = "\\.([cfmM]|cc|cpp|f90|f95|mm)$", all.files = TRUE) allfiles <- if (file.exists("Makevars")) c("Makevars", srcs) else srcs wd2 <- setwd(file.path(R.home("bin"), "exec")) archs <- Sys.glob("*") setwd(wd2) if (length(allfiles)) { if (!multiarch || length(archs) <= 1 || file_test("-x", "../configure")) { if (nzchar(rarch)) starsmsg("***", "arch - ", substr(rarch, 2, 1000)) has_error <- run_shlib(pkg_name, srcs, instdir, rarch) } else { setwd(owd) test_archs <- archs for(arch in archs) { if (arch == "R") { has_error <- run_shlib(pkg_name, srcs, instdir, "") } else { starsmsg("***", "arch - ", arch) ss <- paste("src", arch, sep = "-") dir.create(ss, showWarnings = FALSE) file.copy(Sys.glob("src/*"), ss, recursive = TRUE) setwd(ss) ra <- paste0("/", arch) Sys.setenv(R_ARCH = ra) has_error <- run_shlib(pkg_name, srcs, instdir, ra) Sys.setenv(R_ARCH = rarch) setwd(owd) if (has_error) break } } } } else warning("no source files found", call. = FALSE) } setwd(owd) } if (has_error) pkgerrmsg("compilation failed", pkg_name) fi <- file.info(Sys.glob(file.path(instdir, "libs", "*"))) dirs <- basename(row.names(fi[fi$isdir %in% TRUE, ])) if(WINDOWS) dirs <- dirs[dirs %in% c("i386", "x64")] if (length(dirs)) { descfile <- file.path(instdir, "DESCRIPTION") olddesc <- readLines(descfile, warn = FALSE) olddesc <- grep("^Archs:", olddesc, invert = TRUE, value = TRUE, useBytes = TRUE) newdesc <- c(olddesc, paste("Archs:", paste(dirs, collapse = ", ")) ) writeLines(newdesc, descfile, useBytes = TRUE) } } else if (multiarch) { if (WINDOWS) { wd2 <- setwd(file.path(R.home(), "bin")) archs <- Sys.glob("*") setwd(wd2) test_archs <- archs[archs %in% c("i386", "x64")] } else { wd2 <- setwd(file.path(R.home("bin"), "exec")) test_archs <- Sys.glob("*") setwd(wd2) } } if (WINDOWS && "x64" %in% test_archs) { if (!grepl(" x64 ", utils::win.version())) test_archs <- "i386" } if (install_R && dir.exists("R") && length(dir("R"))) { starsmsg(stars, "R") dir.create(file.path(instdir, "R"), recursive = TRUE, showWarnings = FALSE) res <- try(.install_package_code_files(".", instdir)) if (inherits(res, "try-error")) pkgerrmsg("unable to collate and parse R files", pkg_name) if (file.exists(f <- file.path("R", "sysdata.rda"))) { comp <- TRUE if(!is.na(lazycompress <- desc["SysDataCompression"])) { comp <- switch(lazycompress, "none" = FALSE, "gzip" = TRUE, "bzip2" = 2L, "xz" = 3L, TRUE) } else if(file.size(f) > 1e6) comp <- 3L res <- try(sysdata2LazyLoadDB(f, file.path(instdir, "R"), compress = comp)) if (inherits(res, "try-error")) pkgerrmsg("unable to build sysdata DB", pkg_name) } if (fake) { if (file.exists("NAMESPACE")) { cat("", '.onLoad <- .onAttach <- function(lib, pkg) NULL', '.onUnload <- function(libpaths) NULL', sep = "\n", file = file.path(instdir, "R", pkg_name), append = TRUE) writeLines(sub("useDynLib.*", 'useDynLib("")', readLines("NAMESPACE", warn = FALSE), perl = TRUE, useBytes = TRUE), file.path(instdir, "NAMESPACE")) } else { cat("", '.onLoad <- function (libname, pkgname) NULL', '.onAttach <- function (libname, pkgname) NULL', '.onDetach <- function(libpath) NULL', '.onUnload <- function(libpath) NULL', '.Last.lib <- function(libpath) NULL', sep = "\n", file = file.path(instdir, "R", pkg_name), append = TRUE) } } } if (install_data && dir.exists("data") && length(dir("data"))) { starsmsg(stars, "data") files <- Sys.glob(file.path("data", "*")) if (length(files)) { is <- file.path(instdir, "data") dir.create(is, recursive = TRUE, showWarnings = FALSE) file.remove(Sys.glob(file.path(instdir, "data", "*"))) file.copy(files, is, TRUE) thislazy <- parse_description_field(desc, "LazyData", default = lazy_data) if (!thislazy && resave_data) { paths <- Sys.glob(c(file.path(is, "*.rda"), file.path(is, "*.RData"))) if (pkg_name == "cyclones") paths <- c(paths, Sys.glob(file.path(is, "*.Rdata"))) if (length(paths)) { starsmsg(paste0(stars, "*"), "resaving rda files") resaveRdaFiles(paths, compress = "auto") } } Sys.chmod(Sys.glob(file.path(instdir, "data", "*")), fmode) if (thislazy) { starsmsg(paste0(stars, "*"), "moving datasets to lazyload DB") lazycompress <- desc["LazyDataCompression"] if(!is.na(lazycompress)) data_compress <- switch(lazycompress, "none" = FALSE, "gzip" = TRUE, "bzip2" = 2L, "xz" = 3L, TRUE) res <- try(data2LazyLoadDB(pkg_name, lib, compress = data_compress)) if (inherits(res, "try-error")) pkgerrmsg("lazydata failed", pkg_name) } } else warning("empty 'data' directory", call. = FALSE) } if (install_demo && dir.exists("demo") && length(dir("demo"))) { starsmsg(stars, "demo") dir.create(file.path(instdir, "demo"), recursive = TRUE, showWarnings = FALSE) file.remove(Sys.glob(file.path(instdir, "demo", "*"))) res <- try(.install_package_demos(".", instdir)) if (inherits(res, "try-error")) pkgerrmsg("ERROR: installing demos failed") Sys.chmod(Sys.glob(file.path(instdir, "demo", "*")), fmode) } if (install_exec && dir.exists("exec") && length(dir("exec"))) { starsmsg(stars, "exec") dir.create(file.path(instdir, "exec"), recursive = TRUE, showWarnings = FALSE) file.remove(Sys.glob(file.path(instdir, "exec", "*"))) files <- Sys.glob(file.path("exec", "*")) if (length(files)) { file.copy(files, file.path(instdir, "exec"), TRUE) if (!WINDOWS) Sys.chmod(Sys.glob(file.path(instdir, "exec", "*")), dmode) } } if (install_inst && dir.exists("inst") && length(dir("inst", all.files = TRUE)) > 2L) { starsmsg(stars, "inst") i_dirs <- list.dirs("inst")[-1L] i_dirs <- grep(.vc_dir_names_re, i_dirs, invert = TRUE, value = TRUE) ignore_file <- ".Rinstignore" ignore <- if (file.exists(ignore_file)) { ignore <- readLines(ignore_file, warn = FALSE) ignore[nzchar(ignore)] } else character() for(e in ignore) i_dirs <- grep(e, i_dirs, perl = TRUE, invert = TRUE, value = TRUE, ignore.case = TRUE) lapply(gsub("^inst", instdir, i_dirs), function(p) dir.create(p, FALSE, TRUE)) i_files <- list.files("inst", all.files = TRUE, full.names = TRUE, recursive = TRUE) i_files <- grep(.vc_dir_names_re, i_files, invert = TRUE, value = TRUE) for(e in ignore) i_files <- grep(e, i_files, perl = TRUE, invert = TRUE, value = TRUE, ignore.case = TRUE) i_files <- i_files[!i_files %in% c("inst/doc/Rplots.pdf", "inst/doc/Rplots.ps")] i_files <- grep("inst/doc/.*[.](log|aux|bbl|blg|dvi)$", i_files, perl = TRUE, invert = TRUE, value = TRUE, ignore.case = TRUE) if (!dir.exists("vignettes") && ! pkgname %in% c("RCurl")) i_files <- grep("inst/doc/.*[.](png|jpg|jpeg|gif|ps|eps)$", i_files, perl = TRUE, invert = TRUE, value = TRUE, ignore.case = TRUE) i_files <- i_files[! i_files %in% "Makefile"] i2_files <- gsub("^inst", instdir, i_files) file.copy(i_files, i2_files) if (!WINDOWS) { modes <- file.mode(i_files) execs <- as.logical(modes & as.octmode("100")) Sys.chmod(i2_files[execs], dmode) } if (compact_docs) { pdfs <- dir(file.path(instdir, "doc"), pattern="\\.pdf", recursive = TRUE, full.names = TRUE, all.files = TRUE) res <- compactPDF(pdfs, gs_quality = "none") print(res[res$old > 1e5, ]) } } if (install_tests && dir.exists("tests") && length(dir("tests", all.files = TRUE) > 2L)) { starsmsg(stars, "tests") file.copy("tests", instdir, recursive = TRUE) } if (install_R && dir.exists("R") && length(dir("R"))) { BC <- if (!is.na(byte_compile)) byte_compile else parse_description_field(desc, "ByteCompile", default = FALSE) rcps <- Sys.getenv("R_COMPILE_PKGS") rcp <- switch(rcps, "TRUE"=, "true"=, "True"=, "yes"=, "Yes"= 1, "FALSE"=,"false"=,"False"=, "no"=, "No" = 0, as.numeric(rcps) ) BC <- BC || (!is.na(rcp) && rcp > 0) if (BC) { starsmsg(stars, "byte-compile and prepare package for lazy loading") Sys.setenv(R_ENABLE_JIT = 0L) compiler::compilePKGS(1L) compiler::setCompilerOptions(suppressUndefined = TRUE) } else starsmsg(stars, "preparing package for lazy loading") keep.source <- parse_description_field(desc, "KeepSource", default = keep.source) if (isNamespaceLoaded(pkg_name)) unloadNamespace(pkg_name) deps_only <- config_val_to_logical(Sys.getenv("_R_CHECK_INSTALL_DEPENDS_", "FALSE")) if(deps_only) { env <- setRlibs(LinkingTo = TRUE) libs0 <- .libPaths() env <- sub("^.*=", "", env[1L]) .libPaths(c(lib0, env)) } else libs0 <- NULL res <- try({ suppressPackageStartupMessages(.getRequiredPackages(quietly = TRUE)) makeLazyLoading(pkg_name, lib, keep.source = keep.source) }) if (BC) compiler::compilePKGS(0L) if (inherits(res, "try-error")) pkgerrmsg("lazy loading failed", pkg_name) if (!is.null(libs0)) .libPaths(libs0) } if (install_help) { starsmsg(stars, "help") if (!dir.exists("man") || !length(list_files_with_type("man", "docs"))) cat("No man pages found in package ", sQuote(pkg_name), "\n") encoding <- desc["Encoding"] if (is.na(encoding)) encoding <- "unknown" res <- try(.install_package_Rd_objects(".", instdir, encoding)) if (inherits(res, "try-error")) pkgerrmsg("installing Rd objects failed", pkg_name) starsmsg(paste0(stars, "*"), "installing help indices") .writePkgIndices(pkg_dir, instdir) if (build_help) { outenc <- desc["Encoding"] if (is.na(outenc)) outenc <- "latin1" .convertRdfiles(pkg_dir, instdir, types = build_help_types, outenc = outenc) } if (dir.exists(figdir <- file.path(pkg_dir, "man", "figures"))) { starsmsg(paste0(stars, "*"), "copying figures") dir.create(destdir <- file.path(instdir, "help", "figures")) file.copy(Sys.glob(c(file.path(figdir, "*.png"), file.path(figdir, "*.jpg"), file.path(figdir, "*.jpeg"), file.path(figdir, "*.svg"), file.path(figdir, "*.pdf"))), destdir) } } if (install_inst || install_demo || install_help) { starsmsg(stars, "building package indices") res <- try(.install_package_indices(".", instdir)) if (inherits(res, "try-error")) errmsg("installing package indices failed") if(dir.exists("vignettes")) { starsmsg(stars, "installing vignettes") enc <- desc["Encoding"] if (is.na(enc)) enc <- "" if (!fake && file_test("-f", file.path("build", "vignette.rds"))) installer <- .install_package_vignettes3 else installer <- .install_package_vignettes2 res <- try(installer(".", instdir, enc)) if (inherits(res, "try-error")) errmsg("installing vignettes failed") } } if (install_R && file.exists("NAMESPACE")) { res <- try(.install_package_namespace_info(if(fake) instdir else ".", instdir)) if (inherits(res, "try-error")) errmsg("installing namespace metadata failed") } if (clean) run_clean() if (test_load) { starsmsg(stars, "testing if installed package can be loaded") cmd <- paste0("tools:::.test_load_package('", pkg_name, "', '", lib, "')") deps_only <- config_val_to_logical(Sys.getenv("_R_CHECK_INSTALL_DEPENDS_", "FALSE")) env <- if (deps_only) setRlibs(lib0, self = TRUE, quote = TRUE) else "" if (length(test_archs) > 1L) { msgs <- character() opts <- "--no-save --slave" for (arch in test_archs) { starsmsg("***", "arch - ", arch) out <- R_runR(cmd, opts, env = env, arch = arch) if(length(attr(out, "status"))) msgs <- c(msgs, arch) if(length(out)) cat(paste(c(out, ""), collapse = "\n")) } if (length(msgs)) { msg <- paste("loading failed for", paste(sQuote(msgs), collapse = ", ")) errmsg(msg) } } else { opts <- if (deps_only) "--vanilla --slave" else "--no-save --slave" out <- R_runR(cmd, opts, env = env) if(length(out)) cat(paste(c(out, ""), collapse = "\n")) if(length(attr(out, "status"))) errmsg("loading failed") } } } options(showErrorCalls=FALSE) pkgs <- character() if (is.null(args)) { args <- commandArgs(TRUE) args <- paste(args, collapse = " ") args <- strsplit(args,'nextArg', fixed = TRUE)[[1L]][-1L] } args0 <- args startdir <- getwd() if (is.null(startdir)) stop("current working directory cannot be ascertained") lib <- lib0 <- "" clean <- FALSE preclean <- FALSE debug <- FALSE static_html <- nzchar(system.file("html", "mean.html", package="base")) build_html <- static_html build_latex <- FALSE build_example <- FALSE use_configure <- TRUE configure_args <- character() configure_vars <- character() fake <- FALSE lazy_data <- FALSE byte_compile <- NA lock <- getOption("install.lock", NA) pkglock <- FALSE libs_only <- FALSE tar_up <- zip_up <- FALSE shargs <- character() multiarch <- TRUE force_biarch <- FALSE force_both <- FALSE test_load <- TRUE merge <- FALSE dsym <- nzchar(Sys.getenv("PKG_MAKE_DSYM")) get_user_libPaths <- FALSE data_compress <- TRUE resave_data <- FALSE compact_docs <- FALSE keep.source <- getOption("keep.source.pkgs") built_stamp <- character() install_libs <- TRUE install_R <- TRUE install_data <- TRUE install_demo <- TRUE install_exec <- TRUE install_inst <- TRUE install_help <- TRUE install_tests <- FALSE while(length(args)) { a <- args[1L] if (a %in% c("-h", "--help")) { Usage() q("no", runLast = FALSE) } else if (a %in% c("-v", "--version")) { cat("R add-on package installer: ", R.version[["major"]], ".", R.version[["minor"]], " (r", R.version[["svn rev"]], ")\n", sep = "") cat("", "Copyright (C) 2000-2013 The R Core Team.", "This is free software; see the GNU General Public License version 2", "or later for copying conditions. There is NO warranty.", sep = "\n") q("no", runLast = FALSE) } else if (a %in% c("-c", "--clean")) { clean <- TRUE shargs <- c(shargs, "--clean") } else if (a == "--preclean") { preclean <- TRUE shargs <- c(shargs, "--preclean") } else if (a %in% c("-d", "--debug")) { debug <- TRUE } else if (a == "--no-configure") { use_configure <- FALSE } else if (a == "--no-docs") { build_html <- build_latex <- build_example <- FALSE } else if (a == "--no-html") { build_html <- FALSE } else if (a == "--html") { build_html <- TRUE } else if (a == "--latex") { build_latex <- TRUE } else if (a == "--example") { build_example <- TRUE } else if (a == "--use-zip-data") { warning("use of '--use-zip-data' is defunct", call. = FALSE, domain = NA) warning("use of '--use-zip-data' is deprecated", call. = FALSE, domain = NA) } else if (a == "--auto-zip") { warning("'--auto-zip' is defunct", call. = FALSE, domain = NA) } else if (a == "-l") { if (length(args) >= 2L) {lib <- args[2L]; args <- args[-1L]} else stop("-l option without value", call. = FALSE) } else if (substr(a, 1, 10) == "--library=") { lib <- substr(a, 11, 1000) } else if (substr(a, 1, 17) == "--configure-args=") { configure_args <- c(configure_args, substr(a, 18, 1000)) } else if (substr(a, 1, 17) == "--configure-vars=") { configure_vars <- c(configure_vars, substr(a, 18, 1000)) } else if (a == "--fake") { fake <- TRUE } else if (a == "--no-lock") { lock <- pkglock <- FALSE } else if (a == "--lock") { lock <- TRUE; pkglock <- FALSE } else if (a == "--pkglock") { lock <- pkglock <- TRUE } else if (a == "--libs-only") { libs_only <- TRUE } else if (a == "--no-multiarch") { multiarch <- FALSE } else if (a == "--force-biarch") { force_biarch <- TRUE } else if (a == "--compile-both") { force_both <- TRUE } else if (a == "--maybe-get-user-libPaths") { get_user_libPaths <- TRUE } else if (a == "--build") { if (WINDOWS) zip_up <- TRUE else tar_up <- TRUE } else if (substr(a, 1, 16) == "--data-compress=") { dc <- substr(a, 17, 1000) dc <- match.arg(dc, c("none", "gzip", "bzip2", "xz")) data_compress <- switch(dc, "none" = FALSE, "gzip" = TRUE, "bzip2" = 2, "xz" = 3) } else if (a == "--resave-data") { resave_data <- TRUE } else if (a == "--install-tests") { install_tests <- TRUE } else if (a == "--no-inst") { install_inst <- FALSE } else if (a == "--no-R") { install_R <- FALSE } else if (a == "--no-libs") { install_libs <- FALSE } else if (a == "--no-data") { install_data <- FALSE } else if (a == "--no-demo") { install_demo <- FALSE } else if (a == "--no-exec") { install_exec <- FALSE } else if (a == "--no-help") { install_help <- FALSE } else if (a == "--no-test-load") { test_load <- FALSE } else if (a == "--no-clean-on-error") { clean_on_error <- FALSE } else if (a == "--merge-multiarch") { merge <- TRUE } else if (a == "--compact-docs") { compact_docs <- TRUE } else if (a == "--with-keep.source") { keep.source <- TRUE } else if (a == "--without-keep.source") { keep.source <- FALSE } else if (a == "--byte-compile") { byte_compile <- TRUE } else if (a == "--no-byte-compile") { byte_compile <- FALSE } else if (a == "--dsym") { dsym <- TRUE } else if (substr(a, 1, 18) == "--built-timestamp=") { built_stamp <- substr(a, 19, 1000) } else if (substr(a, 1, 1) == "-") { message("Warning: unknown option ", sQuote(a), domain = NA) } else pkgs <- c(pkgs, a) args <- args[-1L] } if (keep.tmpdir) { make_tmpdir <- function(prefix, nchars = 8, ntries = 100) { for(i in 1:ntries) { name = paste(sample(c(0:9, letters, LETTERS), nchars, replace=TRUE), collapse="") path = paste(prefix, name, sep = "/") if (dir.create(path, showWarnings = FALSE, recursive = T)) { return(path) } } stop("cannot create unique directory for build") } tmpdir <- make_tmpdir(user.tmpdir) } else { tmpdir <- tempfile("R.INSTALL") if (!dir.create(tmpdir)) stop("cannot create temporary directory") } if (merge) { if (length(pkgs) != 1L || !file_test("-f", pkgs)) stop("ERROR: '--merge-multiarch' applies only to a single tarball", call. = FALSE) if (WINDOWS) { f <- dir(file.path(R.home(), "bin")) archs <- f[f %in% c("i386", "x64")] if (length(archs) > 1L) { args <- args0[! args0 %in% c("--merge-multiarch", "--build")] Sys.setenv("_R_INSTALL_NO_DONE_" = "yes") for (arch in archs) { cmd <- c(file.path(R.home(), "bin", arch, "Rcmd.exe"), "INSTALL", args, "--no-multiarch") if (arch == "x64") { cmd <- c(cmd, "--libs-only", if(zip_up) "--build") Sys.unsetenv("_R_INSTALL_NO_DONE_") } cmd <- paste(cmd, collapse = " ") if (debug) message("about to run ", cmd, domain = NA) message("\n", "install for ", arch, "\n", domain = NA) res <- system(cmd) if(res) break } } } else { archs <- dir(file.path(R.home("bin"), "exec")) if (length(archs) > 1L) { args <- args0[! args0 %in% c("--merge-multiarch", "--build")] Sys.setenv("_R_INSTALL_NO_DONE_" = "yes") last <- archs[length(archs)] for (arch in archs) { cmd <- c(file.path(R.home("bin"), "R"), "--arch", arch, "CMD", "INSTALL", args, "--no-multiarch") if (arch != archs[1L]) cmd <- c(cmd, "--libs-only") if (arch == last) { Sys.unsetenv("_R_INSTALL_NO_DONE_") if(tar_up) cmd <- c(cmd, "--build") } cmd <- paste(cmd, collapse = " ") if (debug) message("about to run ", cmd, domain = NA) message("\n", "install for ", arch, "\n", domain = NA) res <- system(cmd) if(res) break } } } if (length(archs) > 1L) { if (res) do_exit_on_error() do_cleanup() on.exit() return(invisible()) } message("only one architecture so ignoring '--merge-multiarch'", domain = NA) } allpkgs <- character() for(pkg in pkgs) { if (debug) message("processing ", sQuote(pkg), domain = NA) if (file_test("-f", pkg)) { if (WINDOWS && grepl("\\.zip$", pkg)) { if (debug) message("a zip file", domain = NA) pkgname <- basename(pkg) pkgname <- sub("\\.zip$", "", pkgname) pkgname <- sub("_[0-9.-]+$", "", pkgname) allpkgs <- c(allpkgs, pkg) next } if (debug) message("a file", domain = NA) of <- dir(tmpdir, full.names = TRUE) if (utils::untar(pkg, exdir = tmpdir, tar = Sys.getenv("R_INSTALL_TAR", "internal"))) errmsg("error unpacking tarball") nf <- dir(tmpdir, full.names = TRUE) new <- nf[!nf %in% of] if (!length(new)) errmsg("cannot extract package from ", sQuote(pkg)) if (length(new) > 1L) errmsg("extracted multiple files from ", sQuote(pkg)) if (dir.exists(new)) pkgname <- basename(new) else errmsg("cannot extract package from ", sQuote(pkg)) if (file.exists(file.path(tmpdir, pkgname, "DESCRIPTION"))) { allpkgs <- c(allpkgs, file.path(tmpdir, pkgname)) } else errmsg("cannot extract package from ", sQuote(pkg)) } else if (file.exists(file.path(pkg, "DESCRIPTION"))) { if (debug) message("a directory", domain = NA) pkgname <- basename(pkg) allpkgs <- c(allpkgs, fullpath(pkg)) } else { warning("invalid package ", sQuote(pkg), call. = FALSE) next } } if (!length(allpkgs)) stop("ERROR: no packages specified", call.=FALSE) if (!nzchar(lib)) { lib <- if (get_user_libPaths) { system(paste(file.path(R.home("bin"), "Rscript"), "-e 'cat(.libPaths()[1L])'"), intern = TRUE) } else .libPaths()[1L] starsmsg(stars, "installing to library ", sQuote(lib)) } else { lib0 <- lib <- path.expand(lib) cwd <- tryCatch(setwd(lib), error = function(e) stop(gettextf("ERROR: cannot cd to directory %s", sQuote(lib)), call. = FALSE, domain = NA)) lib <- getwd() setwd(cwd) } ok <- dir.exists(lib) if (ok) { if (WINDOWS) { fn <- file.path(lib, paste("_test_dir", Sys.getpid(), sep = "_")) unlink(fn, recursive = TRUE) res <- try(dir.create(fn, showWarnings = FALSE)) if (inherits(res, "try-error") || !res) ok <- FALSE else unlink(fn, recursive = TRUE) } else ok <- file.access(lib, 2L) == 0 } if (!ok) stop("ERROR: no permission to install to directory ", sQuote(lib), call. = FALSE) group.writable <- if(WINDOWS) FALSE else { d <- as.octmode("020") (file.mode(lib) & d) == d } if (libs_only) { install_R <- FALSE install_data <- FALSE install_demo <- FALSE install_exec <- FALSE install_inst <- FALSE install_help <- FALSE } more_than_libs <- !libs_only mk_lockdir <- function(lockdir) { if (file.exists(lockdir)) { message("ERROR: failed to lock directory ", sQuote(lib), " for modifying\nTry removing ", sQuote(lockdir), domain = NA) do_cleanup_tmpdir() q("no", status = 3, runLast = FALSE) } dir.create(lockdir, recursive = TRUE) if (!dir.exists(lockdir)) { message("ERROR: failed to create lock directory ", sQuote(lockdir), domain = NA) do_cleanup_tmpdir() q("no", status = 3, runLast = FALSE) } if (debug) starsmsg(stars, "created lock directory ", sQuote(lockdir)) } if (is.na(lock)) { lock <- TRUE pkglock <- length(allpkgs) == 1L } if (lock && !pkglock) { lockdir <- file.path(lib, "00LOCK") mk_lockdir(lockdir) } if ((tar_up || zip_up) && fake) stop("building a fake installation is disallowed") if (fake) { use_configure <- FALSE build_html <- FALSE build_latex <- FALSE build_example <- FALSE install_libs <- FALSE install_demo <- FALSE install_exec <- FALSE } build_help_types <- character() if (build_html) build_help_types <- c(build_help_types, "html") if (build_latex) build_help_types <- c(build_help_types, "latex") if (build_example) build_help_types <- c(build_help_types, "example") build_help <- length(build_help_types) > 0L if (debug) starsmsg(stars, "build_help_types=", paste(build_help_types, collapse = " ")) if (debug) starsmsg(stars, "DBG: 'R CMD INSTALL' now doing do_install()") for(pkg in allpkgs) { if (pkglock) { lockdir <- file.path(lib, paste("00LOCK", basename(pkg), sep = "-")) mk_lockdir(lockdir) } do_install(pkg) } do_cleanup() on.exit() invisible() } .SHLIB <- function() { status <- .shlib_internal(commandArgs(TRUE)) q("no", status = (status != 0), runLast=FALSE) } .shlib_internal <- function(args) { Usage <- function() cat("Usage: R CMD SHLIB [options] files | linker options", "", "Build a shared object for dynamic loading from the specified source or", "object files (which are automagically made from their sources) or", "linker options. If not given via '--output', the name for the shared", "object is determined from the first source or object file.", "", "Options:", " -h, --help print short help message and exit", " -v, --version print version info and exit", " -o, --output=LIB use LIB as (full) name for the built library", " -c, --clean remove files created during compilation", " --preclean remove files created during a previous run", " -n, --dry-run dry run, showing commands that would be used", "", "Windows only:", " -d, --debug build a debug DLL", "", "Report bugs at [email protected] .", sep = "\n") p1 <- function(...) paste(..., collapse = " ") WINDOWS <- .Platform$OS.type == "windows" if (!WINDOWS) { mconf <- readLines(file.path(R.home(), paste0("etc", Sys.getenv("R_ARCH")), "Makeconf")) SHLIB_EXT <- sub(".*= ", "", grep("^SHLIB_EXT", mconf, value = TRUE, perl = TRUE)) SHLIB_LIBADD <- sub(".*= ", "", grep("^SHLIB_LIBADD", mconf, value = TRUE, perl = TRUE)) MAKE <- Sys.getenv("MAKE") rarch <- Sys.getenv("R_ARCH") } else { rhome <- chartr("\\", "/", R.home()) Sys.setenv(R_HOME = rhome) SHLIB_EXT <- ".dll" SHLIB_LIBADD <- "" MAKE <- "make" rarch <- Sys.getenv("R_ARCH", NA_character_) if(is.na(rarch)) { if (nzchar(.Platform$r_arch)) { rarch <- paste0("/", .Platform$r_arch) Sys.setenv(R_ARCH = rarch) } else rarch <- "" } } OBJ_EXT <- ".o" objs <- character() shlib <- "" site <- Sys.getenv("R_MAKEVARS_SITE", NA_character_) if (is.na(site)) site <- file.path(paste0(R.home("etc"), rarch), "Makevars.site") makefiles <- c(file.path(paste0(R.home("etc"), rarch), "Makeconf"), if(file.exists(site)) site, file.path(R.home("share"), "make", if (WINDOWS) "winshlib.mk" else "shlib.mk")) shlib_libadd <- if (nzchar(SHLIB_LIBADD)) SHLIB_LIBADD else character() with_cxx <- FALSE with_f77 <- FALSE with_f9x <- FALSE with_objc <- FALSE use_cxx1x <- FALSE pkg_libs <- character() clean <- FALSE preclean <- FALSE dry_run <- FALSE debug <- FALSE while(length(args)) { a <- args[1L] if (a %in% c("-h", "--help")) { Usage() return(0L) } else if (a %in% c("-v", "--version")) { cat("R shared object builder: ", R.version[["major"]], ".", R.version[["minor"]], " (r", R.version[["svn rev"]], ")\n", sep = "") cat("", "Copyright (C) 2000-2013 The R Core Team.", "This is free software; see the GNU General Public License version 2", "or later for copying conditions. There is NO warranty.", sep = "\n") return(0L) } else if (a %in% c("-n", "--dry-run")) { dry_run <- TRUE } else if (a %in% c("-d", "--debug")) { debug <- TRUE } else if (a %in% c("-c", "--clean")) { clean <- TRUE } else if (a == "--preclean") { preclean <- TRUE } else if (a == "-o") { if (length(args) >= 2L) {shlib <- args[2L]; args <- args[-1L]} else stop("-o option without value", call. = FALSE) } else if (substr(a, 1, 9) == "--output=") { shlib <- substr(a, 10, 1000) } else { base <- sub("\\.[[:alnum:]]*$", "", a) ext <- sub(paste0(base, "."), "", a, fixed = TRUE) nobj <- "" if (nzchar(ext)) { if (ext %in% c("cc", "cpp")) { with_cxx <- TRUE nobj <- base } else if (ext == "m") { with_objc <- TRUE nobj <- base } else if (ext %in% c("mm", "M")) { with_objc <- with_cxx <- TRUE nobj <- base } else if (ext == "f") { with_f77 <- TRUE nobj <- base } else if (ext %in% c("f90", "f95")) { with_f9x <- TRUE nobj <- base } else if (ext == "c") { nobj <- base } else if (ext == "o") { nobj <- base } if (nzchar(nobj) && !nzchar(shlib)) shlib <- paste0(nobj, SHLIB_EXT) } if (nzchar(nobj)) objs <- c(objs, nobj) else pkg_libs <- c(pkg_libs, a) } args <- args[-1L] } if (length(objs)) objs <- paste0(objs, OBJ_EXT, collapse = " ") if (WINDOWS) { if (!is.na(f <- Sys.getenv("R_MAKEVARS_USER", NA_character_))) { if (file.exists(f)) makefiles <- c(makefiles, f) } else if (rarch == "/x64" && file.exists(f <- path.expand("~/.R/Makevars.win64"))) makefiles <- c(makefiles, f) else if (file.exists(f <- path.expand("~/.R/Makevars.win"))) makefiles <- c(makefiles, f) else if (file.exists(f <- path.expand("~/.R/Makevars"))) makefiles <- c(makefiles, f) } else { makefiles <- c(makefiles, makevars_user()) } makeobjs <- paste0("OBJECTS=", shQuote(objs)) if (WINDOWS && file.exists("Makevars.win")) { makefiles <- c("Makevars.win", makefiles) lines <- readLines("Makevars.win", warn = FALSE) if (length(grep("^OBJECTS *=", lines, perl=TRUE, useBytes = TRUE))) makeobjs <- "" if (length(ll <- grep("^CXX_STD *=", lines, perl = TRUE, value = TRUE, useBytes = TRUE))) { cxxstd <- gsub("^CXX_STD *=", "", ll) cxxstd <- gsub(" *", "", cxxstd) if (cxxstd == "CXX11") { use_cxx1x <- TRUE } } } else if (file.exists("Makevars")) { makefiles <- c("Makevars", makefiles) lines <- readLines("Makevars", warn = FALSE) if (length(grep("^OBJECTS *=", lines, perl = TRUE, useBytes = TRUE))) makeobjs <- "" if (length(ll <- grep("^CXX_STD *=", lines, perl = TRUE, value = TRUE, useBytes = TRUE))) { cxxstd <- gsub("^CXX_STD *=", "", ll) cxxstd <- gsub(" *", "", cxxstd) if (cxxstd == "CXX11") { use_cxx1x <- TRUE } } } if (!use_cxx1x) { val <- Sys.getenv("USE_CXX1X", NA_character_) if(!is.na(val)) { use_cxx1x <- TRUE } else { val <- Sys.getenv("R_PKG_CXX_STD") if (val == "CXX11") { use_cxx1x <- TRUE } } } makeargs <- paste0("SHLIB=", shQuote(shlib)) if (with_f9x) { makeargs <- c("SHLIB_LDFLAGS='$(SHLIB_FCLDFLAGS)'", "SHLIB_LD='$(SHLIB_FCLD)'", makeargs) } else if (with_cxx) { makeargs <- if (use_cxx1x) c("CXX='$(CXX1X) $(CXX1XSTD)'", "CXXFLAGS='$(CXX1XFLAGS)'", "CXXPICFLAGS='$(CXX1XPICFLAGS)'", "SHLIB_LDFLAGS='$(SHLIB_CXX1XLDFLAGS)'", "SHLIB_LD='$(SHLIB_CXX1XLD)'", makeargs) else c("SHLIB_LDFLAGS='$(SHLIB_CXXLDFLAGS)'", "SHLIB_LD='$(SHLIB_CXXLD)'", makeargs) } if (with_objc) shlib_libadd <- c(shlib_libadd, "$(OBJC_LIBS)") if (with_f77) shlib_libadd <- c(shlib_libadd, "$(FLIBS)") if (with_f9x) shlib_libadd <- c(shlib_libadd, "$(FCLIBS)") if (length(pkg_libs)) makeargs <- c(makeargs, paste0("PKG_LIBS='", p1(pkg_libs), "'")) if (length(shlib_libadd)) makeargs <- c(makeargs, paste0("SHLIB_LIBADD='", p1(shlib_libadd), "'")) if (WINDOWS && debug) makeargs <- c(makeargs, "DEBUG=T") if (WINDOWS && rarch == "/x64") makeargs <- c(makeargs, "WIN=64 TCLBIN=64") build_objects_symbol_tables <- config_val_to_logical(Sys.getenv("_R_SHLIB_BUILD_OBJECTS_SYMBOL_TABLES_", "FALSE")) cmd <- paste(MAKE, p1(paste("-f", shQuote(makefiles))), p1(makeargs), p1(makeobjs)) if (dry_run) { cat("make cmd is\n ", cmd, "\n\nmake would use\n", sep = "") system(paste(cmd, "-n")) res <- 0 } else { if (preclean) system(paste(cmd, "shlib-clean")) res <- system(cmd) if((res == 0L) && build_objects_symbol_tables) { system(paste(cmd, "symbols.rds")) } if (clean) system(paste(cmd, "shlib-clean")) } res } .writePkgIndices <- function(dir, outDir, OS = .Platform$OS.type, html = TRUE) { re <- function(x) { xx <- rep(TRUE, length(x)) xx[grep("-package", x, fixed = TRUE)] <- FALSE order(xx, toupper(x), x) } html_header <- function(pkg, title, version, conn) { cat(paste(HTMLheader(title, Rhome="../../..", up="../../../doc/html/packages.html", css = "R.css"), collapse = "\n"), '<h2>Documentation for package &lsquo;', pkg, '&rsquo; version ', version, '</h2>\n\n', sep = "", file = conn) cat('<ul><li><a href="../DESCRIPTION">DESCRIPTION file</a>.</li>\n', file=conn) if (file.exists(file.path(outDir, "doc"))) cat('<li><a href="../doc/index.html">User guides, package vignettes and other documentation.</a></li>\n', file=conn) if (file.exists(file.path(outDir, "demo"))) cat('<li><a href="../demo">Code demos</a>. Use <a href="../../utils/help/demo">demo()</a> to run them.</li>\n', sep = "", file=conn) if (any(file.exists(c(file.path(outDir, "NEWS"), file.path(outDir, "NEWS.Rd"))))) cat('<li><a href="../NEWS">Package NEWS</a>.</li>\n', sep = "", file=conn) cat('</ul>\n\n<h2>Help Pages</h2>\n\n\n', sep ="", file = conn) } firstLetterCategory <- function(x) { x[grep("-package$", x)] <- " " x <- toupper(substr(x, 1, 1)) x[x > "Z"] <- "misc" x[x < "A" & x != " "] <- "misc" x } Rd <- if (file.exists(f <- file.path(outDir, "Meta", "Rd.rds"))) readRDS(f) else { db <- tryCatch(Rd_db(basename(outDir), lib.loc = dirname(outDir)), error = function(e) NULL) if (is.null(db)) db <- Rd_db(dir = dir) Rd <- Rd_contents(db) saveRDS(Rd, file.path(outDir, "Meta", "Rd.rds")) Rd } topics <- Rd$Aliases M <- if (!length(topics)) { data.frame(Topic = character(), File = character(), Title = character(), Internal = character(), stringsAsFactors = FALSE) } else { lens <- lengths(topics) files <- sub("\\.[Rr]d$", "", Rd$File) internal <- sapply(Rd$Keywords, function(x) "internal" %in% x) data.frame(Topic = unlist(topics), File = rep.int(files, lens), Title = rep.int(Rd$Title, lens), Internal = rep.int(internal, lens), stringsAsFactors = FALSE) } outman <- file.path(outDir, "help") dir.create(outman, showWarnings = FALSE) MM <- M[re(M[, 1L]), 1:2] utils::write.table(MM, file.path(outman, "AnIndex"), quote = FALSE, row.names = FALSE, col.names = FALSE, sep = "\t") a <- structure(MM[, 2L], names=MM[, 1L]) saveRDS(a, file.path(outman, "aliases.rds")) outman <- file.path(outDir, "html") dir.create(outman, showWarnings = FALSE) outcon <- file(file.path(outman, "00Index.html"), "wt") on.exit(close(outcon)) desc <- read.dcf(file.path(outDir, "DESCRIPTION"))[1L, ] if(!is.na(enc <- desc["Encoding"])) { desc <- iconv(desc, enc, "UTF-8", sub = "byte") } M <- M[!M[, 4L], ] if (desc["Package"] %in% c("base", "graphics", "stats", "utils")) { for(pass in 1:2) { gen <- gsub("\\.data\\.frame", ".data_frame", M$Topic) gen <- sub("\\.model\\.matrix$", ".modelmatrix", gen) gen <- sub("^(all|as|is|file|Sys|row|na|model)\\.", "\\1_", gen) gen <- sub("^(.*)\\.test", "\\1_test", gen) gen <- sub("([-[:alnum:]]+)\\.[^.]+$", "\\1", gen) last <- nrow(M) nongen <- gen %in% c("ar", "bw", "contr", "dyn", "lm", "qr", "ts", "which", ".Call", ".External", ".Library", ".First", ".Last") nc <- nchar(gen) asg <- (nc > 3) & substr(gen, nc-1, nc) == "<-" skip <- (gen == c("", gen[-last])) & (M$File == c("", M$File[-last])) & !nongen skip <- skip | asg M <- M[!skip, ] } } M$Topic <- sub("^([^,]*),.*-method$", "\\1-method", M$Topic) M <- M[!duplicated(M[, c("Topic", "File")]),] M <- M[re(M[, 1L]), ] htmlize <- function(x, backtick) { x <- gsub("&", "&amp;", x, fixed = TRUE) x <- gsub("<", "&lt;", x, fixed = TRUE) x <- gsub(">", "&gt;", x, fixed = TRUE) if (backtick) { x <- gsub("---", "-", x, fixed = TRUE) x <- gsub("--", "-", x, fixed = TRUE) } x } M$HTopic <- htmlize(M$Topic, FALSE) M$Title <- htmlize(M$Title, TRUE) html_header(desc["Package"], htmlize(desc["Title"], TRUE), desc["Version"], outcon) use_alpha <- (nrow(M) > 100) if (use_alpha) { first <- firstLetterCategory(M$Topic) nm <- sort(names(table(first))) m <- match(" ", nm, 0L) if (m) nm <- c(" ", nm[-m]) m <- match("misc", nm, 0L) if (m) nm <- c(nm[-m], "misc") writeLines(c('<p style="text-align: center;">', paste0("<a href=\" "</p>\n"), outcon) for (f in nm) { MM <- M[first == f, ] if (f != " ") cat("\n<h2><a name=\"", f, "\">-- ", f, " --</a></h2>\n\n", sep = "", file = outcon) writeLines(c('<table width="100%">', paste0('<tr><td style="width: 25%;"><a href="', MM[, 2L], '.html">', MM$HTopic, '</a></td>\n<td>', MM[, 3L],'</td></tr>'), "</table>"), outcon) } } else if (nrow(M)) { writeLines(c('<table width="100%">', paste0('<tr><td style="width: 25%;"><a href="', M[, 2L], '.html">', M$HTopic, '</a></td>\n<td>', M[, 3L],'</td></tr>'), "</table>"), outcon) } else { writeLines("There are no help pages in this package", outcon) } writeLines('</body></html>', outcon) file.copy(file.path(R.home("doc"), "html", "R.css"), outman) invisible(NULL) } .convertRdfiles <- function(dir, outDir, types = "html", silent = FALSE, outenc = "UTF-8") { showtype <- function(type) { if (!shown) { nc <- nchar(bf) if (nc < 38L) cat(" ", bf, rep(" ", 40L - nc), sep = "") else cat(" ", bf, "\n", rep(" ", 44L), sep = "") shown <<- TRUE } cat(type, rep(" ", max(0L, 6L - nchar(type))), sep = "") } dirname <- c("html", "latex", "R-ex") ext <- c(".html", ".tex", ".R") names(dirname) <- names(ext) <- c("html", "latex", "example") mandir <- file.path(dir, "man") if (!dir.exists(mandir)) return() desc <- readRDS(file.path(outDir, "Meta", "package.rds"))$DESCRIPTION pkg <- desc["Package"] ver <- desc["Version"] for(type in types) dir.create(file.path(outDir, dirname[type]), showWarnings = FALSE) cat(" converting help for package ", sQuote(pkg), "\n", sep = "") if ("html" %in% types) { if (!silent) message(" finding HTML links ...", appendLF = FALSE, domain = NA) Links <- findHTMLlinks(outDir, level = 0:1) if (!silent) message(" done") .Links2 <- function() { message("\n finding level-2 HTML links ...", appendLF = FALSE, domain = NA) Links2 <- findHTMLlinks(level = 2) message(" done", domain = NA) Links2 } delayedAssign("Links2", .Links2()) } db <- tryCatch(Rd_db(basename(outDir), lib.loc = dirname(outDir)), error = function(e) NULL) if (is.null(db)) db <- Rd_db(dir = dir) if (!length(db)) return() .whandler <- function(e) { .messages <<- c(.messages, paste("Rd warning:", conditionMessage(e))) invokeRestart("muffleWarning") } .ehandler <- function(e) { message("", domain = NA) unlink(ff) stop(conditionMessage(e), domain = NA, call. = FALSE) } .convert <- function(expr) withCallingHandlers(tryCatch(expr, error = .ehandler), warning = .whandler) files <- names(db) for(nf in files) { .messages <- character() Rd <- db[[nf]] attr(Rd, "source") <- NULL bf <- sub("\\.[Rr]d$", "", basename(nf)) f <- attr(Rd, "Rdfile") shown <- FALSE if ("html" %in% types) { type <- "html" ff <- file.path(outDir, dirname[type], paste0(bf, ext[type])) if (!file_test("-f", ff) || file_test("-nt", f, ff)) { showtype(type) .convert(Rd2HTML(Rd, ff, package = c(pkg, ver), defines = NULL, Links = Links, Links2 = Links2)) } } if ("latex" %in% types) { type <- "latex" ff <- file.path(outDir, dirname[type], paste0(bf, ext[type])) if (!file_test("-f", ff) || file_test("-nt", f, ff)) { showtype(type) .convert(Rd2latex(Rd, ff, defines = NULL, outputEncoding = outenc)) } } if ("example" %in% types) { type <- "example" ff <- file.path(outDir, dirname[type], paste0(bf, ext[type])) if (!file_test("-f", ff) || file_test("-nt", f, ff)) { .convert(Rd2ex(Rd, ff, defines = NULL)) if (file_test("-f", ff)) showtype(type) } } if (shown) { cat("\n") if (length(.messages)) writeLines(unique(.messages)) } } bfs <- sub("\\.[Rr]d$", "", basename(files)) if ("html" %in% types) { type <- "html" have <- list.files(file.path(outDir, dirname[type])) have2 <- sub("\\.html", "", basename(have)) drop <- have[! have2 %in% c(bfs, "00Index", "R.css")] unlink(file.path(outDir, dirname[type], drop)) } if ("latex" %in% types) { type <- "latex" have <- list.files(file.path(outDir, dirname[type])) have2 <- sub("\\.tex", "", basename(have)) drop <- have[! have2 %in% bfs] unlink(file.path(outDir, dirname[type], drop)) } if ("example" %in% types) { type <- "example" have <- list.files(file.path(outDir, dirname[type])) have2 <- sub("\\.R", "", basename(have)) drop <- have[! have2 %in% bfs] unlink(file.path(outDir, dirname[type], drop)) } } .makeDllRes <- function(name="", version = "0.0") { if (file.exists(f <- "../DESCRIPTION") || file.exists(f <- "../../DESCRIPTION")) { desc <- read.dcf(f)[[1L]] if (!is.na(f <- desc["Package"])) name <- f if (!is.na(f <- desc["Version"])) version <- f } writeLines(c(' ' '', 'VS_VERSION_INFO VERSIONINFO', 'FILEVERSION R_FILEVERSION', 'PRODUCTVERSION 3,0,0,0', 'FILEFLAGSMASK 0x3L', 'FILEOS VOS__WINDOWS32', 'FILETYPE VFT_APP', 'BEGIN', ' BLOCK "StringFileInfo"', ' BEGIN', ' BLOCK "040904E4"', ' BEGIN')) cat(" VALUE \"FileDescription\", \"DLL for R package `", name,"'\\0\"\n", " VALUE \"FileVersion\", \"", version, "\\0\"\n", sep = "") writeLines(c( ' VALUE "Compiled under R Version", R_MAJOR "." R_MINOR " (" R_YEAR "-" R_MONTH "-" R_DAY ")\\0"', ' VALUE "Project info", "https://www.r-project.org\\0"', ' END', ' END', ' BLOCK "VarFileInfo"', ' BEGIN', ' VALUE "Translation", 0x409, 1252', ' END', 'END')) } makevars_user <- function() { m <- character() if(.Platform$OS.type == "windows") { if(!is.na(f <- Sys.getenv("R_MAKEVARS_USER", NA_character_))) { if(file.exists(f)) m <- f } else if((Sys.getenv("R_ARCH") == "/x64") && file.exists(f <- path.expand("~/.R/Makevars.win64"))) m <- f else if(file.exists(f <- path.expand("~/.R/Makevars.win"))) m <- f else if(file.exists(f <- path.expand("~/.R/Makevars"))) m <- f } else { if(!is.na(f <- Sys.getenv("R_MAKEVARS_USER", NA_character_))) { if(file.exists(f)) m <- f } else if(file.exists(f <- path.expand(paste("~/.R/Makevars", Sys.getenv("R_PLATFORM"), sep = "-")))) m <- f else if(file.exists(f <- path.expand("~/.R/Makevars"))) m <- f } m } makevars_site <- function() { m <- character() if(is.na(f <- Sys.getenv("R_MAKEVARS_SITE", NA_character_))) f <- file.path(paste0(R.home("etc"), Sys.getenv("R_ARCH")), "Makevars.site") if(file.exists(f)) m <- f m }
context("iso") test_all <- (identical (Sys.getenv ("MPADGE_LOCAL"), "true") | identical (Sys.getenv ("GITHUB_WORKFLOW"), "test-coverage")) if (!test_all) RcppParallel::setThreadOptions (numThreads = 2) source ("../sc-conversion-fns.R") test_that("isodists", { expect_silent (hsc <- sf_to_sc (hampi)) requireNamespace ("geodist") requireNamespace ("dplyr") expect_silent (net <- weight_streetnet (hsc, wt_profile = "bicycle")) npts <- 100 set.seed (1) from <- sample (net$.vx0, size = npts) dlim <- c (1, 2, 5, 10, 20) * 100 expect_silent (d <- dodgr_isodists (net, from = from, dlim)) expect_is (d, "data.frame") expect_equal (ncol (d), 5) expect_identical (names (d), c ("from", "dlim", "id", "x", "y")) expect_true (nrow (d) > 0) expect_true ((npts - length (unique (d$from))) >= 0) expect_true (length (unique (d$dlim)) <= length (dlim)) }) skip_on_cran () skip_if (!test_all) test_that ("turn penalty", { hsc <- sf_to_sc (hampi) net0 <- weight_streetnet (hsc, wt_profile = "bicycle") npts <- 100 set.seed (1) from <- sample (net0$.vx0, size = npts) dlim <- c (1, 2, 5, 10, 20) * 100 d0 <- dodgr_isodists (net0, from = from, dlim) net <- weight_streetnet (hsc, wt_profile = "bicycle", turn_penalty = TRUE) expect_true (nrow (net) > nrow (net0)) d <- dodgr_isodists (net, from = from, dlim) expect_false (identical (d0, d)) }) test_that ("errors", { expect_silent (hsc <- sf_to_sc (hampi)) expect_silent (net <- weight_streetnet (hsc, wt_profile = "bicycle")) npts <- 100 set.seed (1) from <- sample (net$.vx0, size = npts) dlim <- c (1, 2, 5, 10, 20) * 100 expect_error (d <- dodgr_isodists (net, from = from), "dlim must be specified") expect_error (d <- dodgr_isodists (net, from = from, dlim = "a"), "dlim must be numeric") expect_error (d <- dodgr_isoverts (net, from = from, dlim = dlim, tlim = 500), "Only one of dlim or tlim can be provided") net <- weight_streetnet (hampi) expect_error (d <- dodgr_isochrones (net, from = from, tlim = 500), "isochrones can only be calculated from SC-class networks") expect_error (d <- dodgr_isoverts (net, from = from, tlim = 500), "isoverts can only be calculated from SC-class networks") }) test_that("isochrones", { expect_silent (hsc <- sf_to_sc (hampi)) expect_silent (net <- weight_streetnet (hsc, wt_profile = "bicycle")) npts <- 100 set.seed (1) from <- sample (net$.vx0, size = npts) tlim <- c (5, 10, 20, 30, 60) * 60 expect_silent (x <- dodgr_isochrones (net, from = from, tlim)) expect_is (x, "data.frame") expect_equal (ncol (x), 5) expect_identical (names (x), c ("from", "tlim", "id", "x", "y")) expect_true (nrow (x) > 0) expect_true ((npts - length (unique (x$from))) >= 0) expect_true (length (unique (x$tlim)) <= length (tlim)) }) test_that("isoverts", { expect_silent (hsc <- sf_to_sc (hampi)) expect_silent (net <- weight_streetnet (hsc, wt_profile = "bicycle")) npts <- 100 set.seed (1) from <- sample (net$.vx0, size = npts) dlim <- c (1, 2, 5, 10, 20) * 100 expect_silent (dd <- dodgr_isodists (net, from = from, dlim)) expect_silent (d <- dodgr_isoverts (net, from = from, dlim)) expect_identical (names (dd), names (d)) expect_true (nrow (d) > nrow (dd)) tlim <- c (60, 120, 300) expect_silent (v <- dodgr_isoverts (net, from = from, tlim = tlim)) expect_true ("tlim" %in% names (v)) expect_true ("dlim" %in% names (d)) expect_true (all (paste0 (tlim) %in% unique (v$tlim))) })
is_valid_package <- function(file) { if (!file.exists(file)) { FALSE } else if (grepl("\\.zip$", file)) { is_valid_package_zip(file) } else if (grepl("\\.tgz$|\\.tar\\.gz$", file)) { is_valid_package_targz(file) } else { FALSE } } is_valid_package_zip <- function(file) { if (file.info(file)$size == 0) return(FALSE) tryCatch( is_package_file_list(file, suppressWarnings(zip_list(file))), error = function(e) FALSE ) } is_valid_package_targz <- function(file) { if (file.info(file)$size == 0) return(FALSE) con <- gzfile(file, open = "rb") on.exit(close(con), add = TRUE) tryCatch( is_package_file_list(file, untar(con, list = TRUE)), error = function(e) FALSE ) } is_package_file_list <- function(file, list) { pkgname <- pkg_name_from_file(file) if (any(! grepl(paste0("^", pkgname, "\\b"), list))) return(FALSE) if (! paste0(pkgname, "/DESCRIPTION") %in% list) return(FALSE) return(TRUE) } pkg_name_from_file <- function(x) { sub("^([a-zA-Z0-9\\.]+)_.*$", "\\1", basename(x)) }
test_that("latch", { testthat::expect_error(latch.e()) testthat::expect_error(latch.w()) x <- 1 testthat::expect_error(latch.e(x)) testthat::expect_error(latch.w(x)) testthat::expect_error(latch.e(x, "error")) testthat::expect_error(latch.w(x, "warning")) le <- latch.e(x, e("Probematic")) lw <- latch.w(x, w("Suspicious")) testthat::expect_snapshot_output(le) testthat::expect_snapshot_output(lw) testthat::expect_true(is.e(le)) testthat::expect_true(is.w(lw)) testthat::expect_error(resolve(le)) testthat::expect_warning(resolve(lw)) unlatch(le) unlatch(lw) })
library(poweRlaw) library(plyr) library(ggplot2) context('Test the fitting of distributions') test_that("dtpl handles the log argument correctly", { testpoints <- 10^(seq(0, 5, length.out = 64)) expect_equal(exp(dtpl(testpoints, 2, 1.0, 1, log = TRUE)), dtpl(testpoints, 2, 1.0, 1, log = FALSE), tol = 1e-8) }) if ( exists("EXTENDED_TESTS") && EXTENDED_TESTS ) { test_that('PL fitting works', { if ( file.exists('./tests/testthat') ) { library(testthat) setwd('./tests/testthat') } for ( s in dir('./pli-R-v0.0.3-2007-07-25', full.names = TRUE, pattern = '*.R') ) { source(s) } system("cd ./pli-R-v0.0.3-2007-07-25/zeta-function/ && make") system("cd ./pli-R-v0.0.3-2007-07-25/exponential-integral/ && make") system("cd ./pli-R-v0.0.3-2007-07-25/ && \ gcc discpowerexp.c -lm -o discpowerexp && \ chmod +x discpowerexp") expos <- c(1.2, 2.5) xmins <- c(1, 10) for ( expo in expos ) { for ( xmin in xmins ) { dat <- unique(round(seq.int(1, 1000, length.out = 100))) pldat <- poweRlaw::rpldis(1000, xmin = xmin, alpha = expo) pldat <- pldat[pldat < 1e5] expect_equal(dzeta(dat,, exponent = expo, threshold = xmin), dpl(dat, expo, xmin = xmin)) expect_equal(pzeta(dat, exponent = expo, threshold = xmin, lower.tail = FALSE), ippl(dat, expo, xmin = xmin)) expect_equal(zeta.loglike(pldat, exponent = expo, threshold = xmin), pl_ll(pldat, expo, xmin = xmin)) our_expo <- pl_fit(pldat, xmin = xmin)[['plexpo']] clauset_expo <- zeta.fit(pldat, threshold = xmin)[['exponent']] powerlaw_expo <- estimate_pars( poweRlaw::displ$new(pldat) )[["pars"]] expect_equal(clauset_expo, our_expo, tol = 1e-3) plot(log10(cumpsd(pldat[pldat>=xmin]))) xs <- c(min(pldat[pldat>=xmin]), max(pldat[pldat>=xmin])) lines(log10(xs), log10(ippl(xs, clauset_expo, xmin = xmin)), lwd = 2, col = 'blue') lines(log10(xs), log10(ippl(xs, powerlaw_expo, xmin = xmin)), lwd = 2, col = 'green') lines(log10(xs), log10(ippl(xs, our_expo, xmin = xmin)), col = 'red') title('PLFIT') } } }) test_that('EXP fitting works', { rates <- c(1.1, 1.5) xmins <- c(1, 3) for (xmin in xmins) { for ( rate in rates ) { dat <- seq.int(1000) expdat <- ceiling(rexp(1000, rate = rate)) expect_equal(ddiscexp(dat, rate, threshold = xmin), ddisexp(dat, rate, xmin = xmin)) ipdisexp(dat, rate, xmin = xmin) fit <- exp_fit(expdat, xmin = xmin) expect_equal(fit[['cutoff']], discexp.fit(expdat, threshold = xmin)[["lambda"]], tol = 1e-3) plot(log10(cumpsd(expdat[expdat >= xmin]))) xs <- seq(min(expdat), max(expdat), length.out = 100) lines(log10(xs), log10(ipdisexp(xs, fit[["cutoff"]], xmin = xmin)), col = 'red') title('EXPFIT') } } }) test_that('LNORM fitting works', { meanlogs <- c(1, 10) sdlogs <- c(1, 3) xmins <- c(1, 30) for (xmin in xmins) { for ( meanlog in meanlogs ) { for ( sdlog in sdlogs ) { xmax <- 1000 dat <- seq.int(xmax) lnormdat <- ceiling(rlnorm(xmax, meanlog, sdlog)) expect_equal(ddislnorm(dat, meanlog, sdlog, xmin), dlnorm.tail.disc(dat, meanlog, sdlog, threshold = xmin)) our_dlnorm <- ddislnorm(dat, meanlog, sdlog, xmin = 0) clauset_dlnorm <- dlnorm.disc(dat, meanlog, sdlog) expect_equal(our_dlnorm, clauset_dlnorm) our_fit <- suppressWarnings( lnorm_fit(lnormdat, xmin = xmin) ) clauset_fit <- suppressWarnings( fit.lnorm.disc(lnormdat, threshold = xmin) ) plot(log10(cumpsd(lnormdat[lnormdat >= xmin]))) xs <- seq(min(lnormdat), max(lnormdat), length.out = 10000) suppressWarnings( lines(log10(xs), log10(ipdislnorm(xs, our_fit[['meanlog']], our_fit[['sdlog']], xmin = xmin)), col = 'red') ) suppressWarnings( lines(log10(xs), log10(ipdislnorm(xs, fit.lnorm.disc(lnormdat, threshold = xmin)[["meanlog"]], fit.lnorm.disc(lnormdat, threshold = xmin)[["sdlog"]], xmin = xmin)), col = "blue") ) title('LNORMFIT') } } } }) test_that('TPL fitting works', { rates <- c(0.05, 1.1) expos <- c(1.1, 1.3) xmins <- c(1, 10) for (xmin in xmins) { for ( rate in rates ) { for ( expo in expos ) { tpldat <- round(rpowerexp(1000, 1, expo, rate)) tpldat <- tpldat[tpldat < 1e5] dat <- seq(0, 1000) clauset_result <- suppressWarnings({ discpowerexp.norm(xmin, expo, rate) }) if ( length(clauset_result) > 0 ) { expect_equal(clauset_result, tplnorm(expo, rate, xmin), tolerance = 1e-4) } dtpl_result <- dtpl(dat, expo, rate, xmin) ddpxp_result <- suppressWarnings ( as.numeric( ddiscpowerexp(dat, expo, rate, threshold = xmin) ) ) if ( ! all( is.na(dtpl_result) ) ) { expect_equal(dtpl_result, ddpxp_result, tolerance = 1e-4) } clauset_result <- suppressWarnings( discpowerexp.loglike(tpldat, expo, rate, threshold = xmin) ) if (length(clauset_result) > 0) { expect_equal(tpl_ll(tpldat, expo, rate, xmin), clauset_result, tolerance = 1e-4) } our_fit <- tpl_fit(tpldat, xmin = xmin) clauset_fit <- tryNULL(discpowerexp.fit(tpldat, threshold = xmin)) if ( !is.null(clauset_fit) && abs(clauset_fit$exponent - (-1)) > 1e-4 && !is.na(our_fit$ll) ) { if ( our_fit$ll < clauset_fit$loglike ) { if ( abs(our_fit$ll - clauset_fit$loglike) > 1e-3 ) { message("We found a better fit than the reference code") } } else { if ( abs(our_fit$ll - clauset_fit$loglike) > 1e-3 ) { message("Reference code found a better fit") browser() fail() } } } if ( !is.null(clauset_fit) ) { plot(log10(cumpsd(tpldat[tpldat >= xmin]))) xs <- unique( round( seq(min(tpldat), max(tpldat), length.out = 100) )) lines(log10(xs), log10(iptpl(xs, clauset_fit[["exponent"]], clauset_fit[["rate"]], xmin)), col = 'blue', lwd = 2) lines(log10(xs), log10(iptpl(xs, our_fit[["plexpo"]], our_fit[["cutoff"]], xmin)), col = 'red') title('TPLFIT') } } } } }) test_that("PL estimations work with xmins", { expos <- c(1.5, 2) for (expo in expos) { for (xmin in c(1, 5)) { x <- seq.int(1000) pldat <- poweRlaw::rpldis(1000, xmin, expo) pldat <- pldat[pldat < 1e5] expect_equal(dzeta(x, xmin, expo), dpl(x, expo, xmin)) expect_equal(pzeta(x, xmin, expo, lower.tail = FALSE), ippl(x, expo, xmin)) expect_equal(zeta.loglike(pldat, xmin, expo), pl_ll(pldat, expo, xmin)) expect_equal(pl_fit(pldat, xmin = xmin)[["plexpo"]], zeta.fit(pldat, xmin)[["exponent"]], tol = 1e-3) expect_is(xmin_estim(pldat), "numeric") } } }) system("cd ./pli-R-v0.0.3-2007-07-25/zeta-function/ && rm zeta_func zeta_func.o") system("cd ./pli-R-v0.0.3-2007-07-25/exponential-integral/ && rm exp_int exp_int.o") system("cd ./pli-R-v0.0.3-2007-07-25/ && rm discpowerexp") }
make_seeds <- function(seed, n) { if (is.list(seed)) { seed <- validate_supplied_seeds(seed, n) return(seed) } if (is_true(seed)) { seed <- as_lecyer_cmrg_seed_from_base_r_seed() } else if (is.integer(seed)) { seed <- as_lecyer_cmrg_seed_from_integer(seed) } else { abort("Internal error: Unknown type of `seed` encountered.") } oseed <- next_random_seed() on.exit(set_random_seed(oseed), add = TRUE) out <- vector("list", length = n) for (i in seq_len(n)) { out[[i]] <- nextRNGSubStream(seed) seed <- nextRNGStream(seed) } out } validate_supplied_seeds <- function(seeds, n) { if (length(seeds) != n) { abort(paste0( "If `furrr_options(seed = )` is a list, it must have length equal ", "to the common length of the inputs, ", n, ", ", "not length ", length(seeds), "." )) } seeds } is_valid_random_seed <- function(seed) { oseed <- get_random_seed() on.exit(set_random_seed(oseed), add = TRUE) env <- globalenv() env$.Random.seed <- seed res <- tryCatch( simpleWarning = function(cnd) cnd, sample.int(n = 1L, size = 1L, replace = FALSE) ) ok <- !inherits(res, "simpleWarning") ok } next_random_seed <- function(seed = get_random_seed()) { sample.int(n = 1L, size = 1L, replace = FALSE) seed_next <- get_random_seed() stopifnot(!any(seed_next != seed)) invisible(seed_next) } get_random_seed <- function() { env <- globalenv() env$.Random.seed } set_random_seed <- function(seed) { env <- globalenv() if (is.null(seed)) { rm(list = ".Random.seed", envir = env, inherits = FALSE) } else { env$.Random.seed <- seed } } as_lecyer_cmrg_seed_from_base_r_seed <- function() { oseed <- get_random_seed() if (is_lecyer_cmrg_seed(oseed)) { return(oseed) } on.exit(set_random_seed(oseed), add = TRUE) RNGkind("L'Ecuyer-CMRG") return(get_random_seed()) } as_lecyer_cmrg_seed_from_integer <- function(seed) { if (is_lecyer_cmrg_seed(seed)) { return(seed) } if (length(seed) == 1L) { oseed <- get_random_seed() on.exit(set_random_seed(oseed), add = TRUE) RNGkind("L'Ecuyer-CMRG") set.seed(seed) return(get_random_seed()) } abort(paste0( "Integer `seed` must be L'Ecuyer-CMRG RNG seed as returned by ", "`parallel::nextRNGStream()` or a single integer." )) } is_lecyer_cmrg_seed <- function(seed) { is.numeric(seed) && length(seed) == 7L && all(is.finite(seed)) && (seed[[1]] %% 10000L == 407L) }
global_exhaustive2p_cluster <- function(formula, data, phase_id, cluster, boundary_weights, exhaustive){ n2<- sum(data[[phase_id[["phase.col"]]]] == phase_id[["terrgrid.id"]]) n1<- Inf model.object_plot_level <- lm(formula, data=data[data[[phase_id[["phase.col"]]]]%in%phase_id[["terrgrid.id"]],], x=TRUE, y=TRUE) data_ext <- as.data.frame(cbind(model.object_plot_level$y, model.object_plot_level$x)) names(data_ext)[1] <- all.vars(formula)[1] data_ext[, cluster] <- data[,cluster][match(rownames(data_ext),rownames(data))] if(!is.na(boundary_weights)){ data_ext[,boundary_weights]<- data [data[[phase_id[["phase.col"]]]]%in%phase_id[["terrgrid.id"]],boundary_weights] } cluster_weights <- aggregate(data_ext[,all.vars(formula)[1]], list(data_ext[,cluster]), length) cluster_means <- aggregate(data_ext[,-which(names(data_ext)==cluster)], list(cluster = data_ext[,cluster]), mean) if(!is.na(boundary_weights)){ clustmeans.temp<- ddply(data_ext[,-which(names(data_ext) == all.vars(formula)[1])], .(cluster), function(x) colwise(weighted.mean, w = x[[boundary_weights]]) (x)) clustmeans.temp<- clustmeans.temp[, -which(names(clustmeans.temp) == boundary_weights)] cluster_means<- merge(clustmeans.temp, cluster_means[,c(cluster, all.vars(formula)[1])], by=cluster) } names(cluster_weights)[1] <- cluster names(cluster_means)[1] <- cluster data_clust_s2 <- merge(cluster_means, cluster_weights, by=cluster) Yc_x <- data_clust_s2[, all.vars(formula)[1]] design_matrix.s2 <- as.matrix(data_clust_s2[, -1*c(which(names(data_clust_s2) %in% c(cluster,all.vars(formula)[1])), ncol(data_clust_s2))]) M_x.s2 <- data_clust_s2[, ncol(data_clust_s2)] n1_clusters <- Inf n2_clusters <- length(Yc_x) As2inv <- solve( (t(design_matrix.s2) %*% (M_x.s2*design_matrix.s2)) / n2_clusters ) beta_s2 <- As2inv %*% t(t(M_x.s2*Yc_x) %*% design_matrix.s2 / n2_clusters) Yc_x_hat <- design_matrix.s2 %*% beta_s2 Rc_x_hat <- Yc_x - Yc_x_hat MR_square <- as.vector((M_x.s2^2)*(Rc_x_hat^2)) middle_term <- ((t(as.matrix(design_matrix.s2)) %*% ( MR_square*(as.matrix(design_matrix.s2)))) / n2_clusters^2) cov_beta_s2 <- As2inv %*% middle_term %*% As2inv w <- (M_x.s2 / mean(M_x.s2)) weighted_mean_Yc_x <- sum(M_x.s2*Yc_x)/sum(M_x.s2) weighted_mean_Rc_x_hat <- sum(M_x.s2*Rc_x_hat)/sum(M_x.s2) estimate <- exhaustive %*% beta_s2 ext_variance <- (1/n2_clusters)*(1/(n2_clusters-1))*sum((w^2)*(Rc_x_hat - weighted_mean_Rc_x_hat)^2) g_variance <- (t(exhaustive) %*% cov_beta_s2 %*% exhaustive) samplesizes<- data.frame(cbind (n1_clusters, n2_clusters, n1, n2)) colnames(samplesizes)<- c("n1_clust", "n2_clust", "n1", "n2") rownames(samplesizes)<- "plots" estimation<- data.frame(estimate=estimate, ext_variance=ext_variance, g_variance=g_variance, n1=samplesizes$n1, n2=samplesizes$n2, n1_clust=samplesizes$n1_clust, n2_clust=samplesizes$n2_clust, r.squared=summary(model.object_plot_level)$r.squared) inputs<- list() inputs[["data"]]<- data inputs[["formula"]]<- formula inputs[["boundary_weights"]]<- boundary_weights inputs[["method"]]<- "exhaustive" inputs[["cluster"]]<- TRUE inputs[["exhaustive"]]<- TRUE warn.messages<- NA result<- list(input=inputs, estimation=estimation, samplesizes=samplesizes, coefficients=t(beta_s2), cov_coef=cov_beta_s2, Rc_x_hat=Rc_x_hat, mean_Rc_x_hat=weighted_mean_Rc_x_hat, warn.messages=warn.messages) class(result)<- c("global", "twophase") return(result) }
p2r = function(subcircle = 0, na.fill = NULL) { assert_is_a_number(subcircle) assert_all_are_non_negative(subcircle) subcircle <- lazyeval::uq(subcircle) na.fill <- lazyeval::uq(na.fill) if (!is.null(na.fill) && !is(na.fill, "SpatialInterpolation")) stop("'na.fill' is not an algorithm for spatial interpolation") f = function(las, layout) { assert_is_valid_context(LIDRCONTEXTDSM, "p2r") dsm <- fasterize(las, layout, subcircle, "max") if (!is.null(na.fill)) { verbose("Interpolating empty cells...") layout[[1]][] <- NA_real_ layout[[1]][] <- dsm hull <- st_convex_hull(las) hull <- sf::st_buffer(hull, dist = raster_res(layout)[1]) where <- raster_as_dataframe(layout, xy = FALSE, na.rm = FALSE) where <- where[is.na(where$Z)] where <- sf::st_multipoint(as.matrix(where[,1:2])) where <- sf::st_geometry(where) where <- sf::st_set_crs(where, sf::st_crs(hull)) where <- sf::st_intersection(where, hull) where <- sf::st_coordinates(where)[,-3] where <- as.data.frame(where) data.table::setnames(where, c("X", "Y")) grid <- raster_as_las(layout) lidR.context <- "p2r" cells <- raster_cell_from_xy(layout, where$X, where$Y) layout[[1]][cells] <- na.fill(grid, where) dsm <- as.numeric(layout[[1]]) } return(dsm) } f <- plugin_dsm(f) return(f) } dsmtin = function(max_edge = 0) { max_edge <- lazyeval::uq(max_edge) return(pitfree(0, c(max_edge, 0), 0)) } pitfree <- function(thresholds = c(0, 2, 5, 10, 15), max_edge = c(0, 1), subcircle = 0) { assert_is_numeric(thresholds) assert_all_are_non_negative(thresholds) assert_is_numeric(max_edge) assert_all_are_non_negative(max_edge) assert_is_a_number(subcircle) assert_all_are_non_negative(subcircle) if (length(thresholds) > 1L & length(max_edge) < 2L) { stop("'max_edge' should contain 2 numbers") } thresholds <- lazyeval::uq(thresholds) max_edge <- lazyeval::uq(max_edge) subcircle <- lazyeval::uq(subcircle) f <- function(las, layout) { assert_is_valid_context(LIDRCONTEXTDSM, "pitfree") if (!"ReturnNumber" %in% names(las)) stop("No attribute 'ReturnNumber' found. This attribute is needed to extract first returns", call. = FALSE) if (fast_countequal(las$ReturnNumber, 1L) == 0) stop("No first returns found. Operation aborted.", call. = FALSE) . <- .N <- X <- Y <- Z <- ReturnNumber <- NULL xscale <- las[["X scale factor"]] yscale <- las[["Y scale factor"]] xoffset <- las[["X offset"]] yoffset <- las[["Y offset"]] scales <- c(xscale, yscale) offsets <- c(xoffset, yoffset) verbose("Selecting first returns...") cloud <- las@data[ReturnNumber == 1L, .(X, Y, Z)] cloud <- LAS(cloud, las@header, st_crs(las), check = FALSE, index = las@index) if (subcircle > 0) { verbose("Subcircling points...") cloud <- subcircle(cloud, subcircle, 8L) } verbose("Selecting only the highest points within the grid cells...") template <- raster_template(layout) i <- C_highest(cloud, template) cloud <- cloud[i] if (nrow(cloud) < 3) stop("There are not enought points to triangulate.", call. = FALSE) grid <- raster_as_dataframe(layout, na.rm = FALSE) z <- rep(NA_real_, nrow(grid)) thresholds <- sort(thresholds) for (i in seq_along(thresholds)) { verbose(glue::glue("Triangulation pass {i} of {length(thresholds)}...")) th <- thresholds[i] edge <- if (th == 0) max_edge[1] else max_edge[2] if (fast_countover(cloud$Z, th) > 3) { b <- cloud$Z >= th cloud <- cloud[b] Ztemp <- interpolate_delaunay(cloud@data, grid, edge, scales, offsets) if (i == 1 && all(is.na(Ztemp))) { stop("Interpolation failed in the first layer (NAs everywhere). Maybe there are too few points.", call. = FALSE) } z <- pmax(z, Ztemp, na.rm = T) } } if (all(is.na(z))) stop("Interpolation failed (NAs everywhere). Input parameters might be wrong.", call. = FALSE) return(z) } f <- plugin_dsm(f, omp = TRUE) return(f) } subcircle = function(las, r, n) { xscale <- las[["X scale factor"]] yscale <- las[["Y scale factor"]] xoffset <- las[["X offset"]] yoffset <- las[["Y offset"]] bbox <- st_bbox(las) dt <- las@data X <- Y <- Z <- NULL f = function(x, y, z, px, py) { x = x + px y = y + py z = rep(z, length(px)) list(X = x, Y = y, Z = z) } n = n + 1 alpha = seq(0, 2*pi, length.out = n)[-n] px = r*cos(alpha) py = r*sin(alpha) dt <- dt[, f(X, Y, Z, px, py), by = 1:nrow(dt)][, nrow := NULL][] dt <- dt[data.table::between(X, bbox$xmin, bbox$xmax) & data.table::between(Y, bbox$ymin, bbox$ymax)] dt[1:.N, `:=`(X = round_any(X - xoffset, xscale) + xoffset, Y = round_any(Y - yoffset, yscale) + yoffset)] return(LAS(dt, las@header, st_crs(las), check = FALSE, index = las@index)) }
setAs("ddenseMatrix", "dgeMatrix", ..2dge) setAs("ddenseMatrix", "matrix", function(from) as(..2dge(from), "matrix")) setAs("dgeMatrix", "lgeMatrix", function(from) d2l_Matrix(from, "dgeMatrix")) setAs("dsyMatrix", "lsyMatrix", function(from) d2l_Matrix(from, "dsyMatrix")) setAs("dspMatrix", "lspMatrix", function(from) d2l_Matrix(from, "dspMatrix")) setAs("dtrMatrix", "ltrMatrix", function(from) d2l_Matrix(from, "dtrMatrix")) setAs("dtpMatrix", "ltpMatrix", function(from) d2l_Matrix(from, "dtpMatrix")) if(FALSE) setAs("ddenseMatrix", "CsparseMatrix", function(from) { if (class(from) != "dgeMatrix") as_Csparse(from) else .Call(dense_to_Csparse, from) }) setAs("dgeMatrix", "dgCMatrix", function(from) .Call(dense_to_Csparse, from)) setMethod("as.numeric", "ddenseMatrix", function(x, ...) ..2dge(x)@x) setMethod("norm", signature(x = "ddenseMatrix", type = "missing"), function(x, type, ...) norm(..2dge(x))) setMethod("norm", signature(x = "ddenseMatrix", type = "character"), function(x, type, ...) norm(..2dge(x), type)) setMethod("rcond", signature(x = "ddenseMatrix", norm = "missing"), function(x, norm, ...) rcond(..2dge(x), ...)) setMethod("rcond", signature(x = "ddenseMatrix", norm = "character"), function(x, norm, ...) rcond(..2dge(x), norm, ...)) setMethod("solve", signature(a = "ddenseMatrix", b = "missing"), function(a, b, ...) solve(..2dge(a))) for(.b in c("Matrix","ANY")) setMethod("solve", signature(a = "ddenseMatrix", b = .b), function(a, b, ...) solve(..2dge(a), b)) for(.b in c("matrix","numeric")) setMethod("solve", signature(a = "ddenseMatrix", b = .b), function(a, b, ...) solve(..2dge(a), Matrix(b))) rm(.b) setMethod("lu", signature(x = "ddenseMatrix"), function(x, ...) .set.factors(x, "LU", lu(..2dge(x), ...))) setMethod("chol", signature(x = "ddenseMatrix"), cholMat) setMethod("determinant", signature(x = "ddenseMatrix", logarithm = "missing"), function(x, logarithm, ...) determinant(..2dge(x))) setMethod("determinant", signature(x = "ddenseMatrix", logarithm = "logical"), function(x, logarithm, ...) determinant(..2dge(x), logarithm)) .trilDense <- function(x, k = 0, ...) { k <- as.integer(k[1]) d <- dim(x) stopifnot(-d[1] <= k, k <= d[1]) .Call(dense_band, x, -d[1], k) } setMethod("tril", "denseMatrix", .trilDense) setMethod("tril", "matrix", .trilDense) .triuDense <- function(x, k = 0, ...) { k <- as.integer(k[1]) d <- dim(x) stopifnot(-d[1] <= k, k <= d[1]) .Call(dense_band, x, k, d[2]) } setMethod("triu", "denseMatrix", .triuDense) setMethod("triu", "matrix", .triuDense) .bandDense <- function(x, k1, k2, ...) { k1 <- as.integer(k1[1]) k2 <- as.integer(k2[1]) dd <- dim(x) sqr <- dd[1] == dd[2] stopifnot(-dd[1] <= k1, k1 <= k2, k2 <= dd[2]) r <- .Call(dense_band, x, k1, k2) if (sqr && k1 < 0 && k1 == -k2 && isSymmetric(x)) forceSymmetric(r) else r } setMethod("band", "denseMatrix", .bandDense) setMethod("band", "matrix", .bandDense) setMethod("symmpart", signature(x = "ddenseMatrix"), function(x) .Call(ddense_symmpart, x)) setMethod("skewpart", signature(x = "ddenseMatrix"), function(x) .Call(ddense_skewpart, x)) setMethod("is.finite", signature(x = "dgeMatrix"), function(x) { if(all(ifin <- is.finite(x@x))) allTrueMat(x) else if(any(ifin)) { r <- as(x, "lMatrix") r@x <- ifin as(r, "nMatrix") } else is.na_nsp(x) }) setMethod("is.finite", signature(x = "ddenseMatrix"), function(x) { if(all(ifin <- is.finite(x@x))) return(allTrueMat(x)) cdx <- getClassDef(class(x)) r <- new(if(extends(cdx,"symmetricMatrix"))"nsyMatrix" else "ngeMatrix") r@Dim <- (d <- x@Dim) r@Dimnames <- x@Dimnames isPacked <- (le <- prod(d)) > length(ifin) r@x <- rep.int(TRUE, le) iTr <- indTri(d[1], upper= x@uplo == "U", diag= TRUE) if(isPacked) { r@x[iTr] <- ifin } else { r@x[iTr] <- ifin[iTr] } r }) setMethod("is.infinite", signature(x = "ddenseMatrix"), function(x) { if(any((isInf <- is.infinite(x@x)))) { r <- as(x, "lMatrix") r@x <- isInf as(r, "nMatrix") } else is.na_nsp(x) })
acrossFormsConstraint <- function(nForms, nItems = NULL, operator = c("<=", "=", ">="), targetValue, whichForms = seq_len(nForms), whichItems = NULL, itemIDs = NULL, itemValues = NULL, info_text = NULL){ check_out <- do_checks_eatATA( nItems = nItems, itemIDs = itemIDs, itemValues = itemValues, operator = operator, nForms = nForms, targetValue = targetValue, info_text = info_text, whichItems = whichItems, itemValuesName = deparse(substitute(itemValues))) nItems <- check_out$nItems itemIDs <- check_out$itemIDs itemValues <- check_out$itemValues operator <- check_out$operator info_text <- check_out$info_text whichItems <- check_out$whichItems makeItemFormConstraint(nForms = nForms, nItems = nItems, values = rep(itemValues, times = nForms), realVar = NULL, operator = operator, targetValue = targetValue, whichForms = whichForms, whichItems = whichItems, sense = NULL, info_text = info_text, itemIDs = itemIDs) }
context("miss_var_summary tidiers") dat <- tibble::tribble( ~air, ~wind, ~water, ~month, -99, NA, 23, 1, -98, NA, NA, 1, 25, 30, 21, 2, NA, 99, NA, 2, 23, 40, NA, 2 ) test_that("miss_var_summary errors when a non-dataframe given",{ expect_error(miss_var_summary(NULL)) expect_error(miss_var_summary(matrix(0))) }) test_that("miss_var_summary produces a tibble", { expect_is(miss_var_summary(dat), "tbl_df") }) aq_group <- dplyr::group_by(dat, month) test_that("miss_var_summary grouped_df returns a tibble", { expect_is(miss_var_summary(aq_group), "tbl_df") }) test_that("miss_var_summary returns the right number of columns", { expect_equal(ncol(miss_var_summary(dat)), 3) }) test_that("miss_var_summary group returns the right number of columns", { expect_equal(ncol(miss_var_summary(aq_group)), 4) }) test_that("grouped_df returns 1 more column than regular miss_var_summary", { expect_equal(ncol(miss_var_summary(aq_group)), ncol(miss_var_summary(dat)) + 1) }) test_that("grouped_df returns a column named 'Month'", { expect_identical(names(miss_var_summary(aq_group)), c("month", "variable", "n_miss","pct_miss")) }) test_that("grouped_df returns a dataframe with more rows than regular", { expect_gt(nrow(miss_var_summary(aq_group)), nrow(miss_var_summary(dat))) }) test_that("grouped_df returns a column named 'Month' with the right levels", { expect_identical(unique(miss_var_summary(aq_group)$month), c(1,2)) }) test_that("miss_var_summary adds cumsum when add_cumsum = TRUE", { expect_equal(names(miss_var_summary(dat, add_cumsum = TRUE)), c("variable", "n_miss", "pct_miss", "n_miss_cumsum")) }) test_that("miss_var_summary grouped adds cumsum when add_cumsum = TRUE", { expect_equal(names(miss_var_summary(aq_group, add_cumsum = TRUE)), c("month", "variable", "n_miss", "pct_miss", "n_miss_cumsum")) })
src <- function(x) { if(!missing(x)) { y <- paste(as.character(substitute(x)),".s",sep="") options(last.source=y, TEMPORARY=FALSE) } else y <- options()$last.source if(is.null(y)) stop("src not called with file name earlier") source(y) cat(y, "loaded\n") invisible() }
download.MACA <- function(outfolder, start_date, end_date, site_id, lat.in, lon.in, model='IPSL-CM5A-LR', scenario='rcp85', ensemble_member='r1i1p1', overwrite=FALSE, verbose=FALSE, ...){ start_date <- as.POSIXlt(start_date, tz = "UTC") end_date <- as.POSIXlt(end_date, tz = "UTC") start_year <- lubridate::year(start_date) end_year <- lubridate::year(end_date) site_id <- as.numeric(site_id) model <- paste0(model) scenario <- paste0(scenario) ensemble_member <- paste0(ensemble_member) outfolder <- paste0(outfolder,"_site_",paste0(site_id %/% 1000000000, "-", site_id %% 1000000000)) if (model == 'CCSM4'){ ensemble_member <- 'r6i1p1' } lat.in <- as.numeric(lat.in) lat <- lat.in - 25.063077926635742 lat_MACA <- round(lat*24) lon.in <- as.numeric(lon.in) if (lon.in < 0){ lon.in <- 180 - lon.in} lon <- lon.in - 235.22784423828125 lon_MACA <- round(lon*24) dap_base <-'http://thredds.northwestknowledge.net:8080/thredds/dodsC/MACAV2' ylist <- seq(start_year,end_year,by=1) rows <- length(ylist) results <- data.frame(file=character(rows), host=character(rows), mimetype=character(rows), formatname=character(rows), startdate=character(rows), enddate=character(rows), dbfile.name = paste("MACA",model,scenario,ensemble_member,sep="."), stringsAsFactors = FALSE) var <- data.frame(DAP.name <- c("tasmax","tasmin","rsds","uas","vas","huss","pr","none","none","none"), long_DAP.name <- c("air_temperature","air_temperature","surface_downwelling_shortwave_flux_in_air", "eastward_wind","northward_wind","specific_humidity","precipitation","air_pressure", "surface_downwelling_longwave_flux_in_air","air_temp"), CF.name <- c("air_temperature_max","air_temperature_min","surface_downwelling_shortwave_flux_in_air", "eastward_wind","northward_wind","specific_humidity","precipitation_flux","air_pressure", "surface_downwelling_longwave_flux_in_air","air_temperature"), units <- c('Kelvin','Kelvin',"W/m2","m/s","m/s","g/g","kg/m2/s", "Pascal", "W/m2","Kelvin") ) for (i in 1:rows){ year <- ylist[i] ntime <- (1825) met_start <- 2006 met_block <- 5 url_year <- met_start + floor((year-met_start)/met_block)*met_block start_url <- paste0(url_year) end_url <- paste0(url_year+met_block-1) dir.create(outfolder, showWarnings=FALSE, recursive=TRUE) loc.file <- file.path(outfolder,paste("MACA",model,scenario,ensemble_member,year,"nc",sep=".")) lat <- ncdf4::ncdim_def(name='latitude', units='degree_north', vals=lat.in, create_dimvar=TRUE) lon <- ncdf4::ncdim_def(name='longitude', units='degree_east', vals=lon.in, create_dimvar=TRUE) time <- ncdf4::ncdim_def(name='time', units="sec", vals=(1:365)*86400, create_dimvar=TRUE, unlim=TRUE) dim<-list(lat,lon,time) var.list <- list() dat.list <- list() for(j in 1:length(var$CF.name)){ dap_end <- paste0('/', model,'/macav2metdata_', var$DAP.name[j],'_', model,'_', ensemble_member,'_', scenario,'_', start_url,'_', end_url,'_CONUS_daily.nc') dap_file <- paste0(dap_base,dap_end) if(j < 8){ dap <- ncdf4::nc_open(dap_file) dat.list[[j]] <- ncdf4::ncvar_get(dap,as.character(var$long_DAP.name[j]),c(lon_MACA,lat_MACA,1),c(1,1,ntime)) var.list[[j]] <- ncdf4::ncvar_def(name=as.character(var$CF.name[j]), units=as.character(var$units[j]), dim=dim, missval=-9999.0, verbose=verbose) ncdf4::nc_close(dap) } else { dat.list[[j]] <- NA var.list[[j]] <- ncdf4::ncvar_def(name=as.character(var$CF.name[j]), units=as.character(var$units[j]), dim=dim, missval=-9999.0, verbose=verbose)} } dat.list <- as.data.frame(dat.list) colnames(dat.list) <- c("air_temperature_max","air_temperature_min","surface_downwelling_shortwave_flux_in_air","eastward_wind","northward_wind","specific_humidity","precipitation_flux","air_pressure", "surface_downwelling_longwave_flux_in_air","air_temperature") dat.list[["air_temperature"]] <- (dat.list[["air_temperature_max"]]+dat.list[["air_temperature_min"]])/2 dat.list[["precipitation_flux"]] <- (dat.list[["precipitation_flux"]]/(24*3600)) if (year%%5 == 1){ dat.list = dat.list[1:365,] } if (year%%5 == 2){ dat.list = dat.list[366:730,] } if (year%%5 == 3){ dat.list = dat.list[731:1095,] } if (year%%5 == 4){ dat.list = dat.list[1096:1460,] } if (year%%5 == 0){ dat.list = dat.list[1461:1825,] } loc <- ncdf4::nc_create(filename=loc.file, vars=var.list, verbose=verbose) for(j in seq_along(var$CF.name)){ ncdf4::ncvar_put(nc=loc, varid=as.character(var$CF.name[j]), vals=dat.list[[j]]) } ncdf4::nc_close(loc) results$file[i] <- loc.file results$host[i] <- PEcAn.remote::fqdn() results$startdate[i] <- paste0(year,"-01-01 00:00:00") results$enddate[i] <- paste0(year,"-12-31 23:59:59") results$mimetype[i] <- 'application/x-netcdf' results$formatname[i] <- 'CF Meteorology' } return(invisible(results)) }
rlaptrans <- function(n, ltpdf, ..., tol=1e-7, x0=1, xinc=2, m=11, L=1, A=19, nburn=38) { maxiter = 500 nterms = nburn + m*L seqbtL = seq(nburn,nterms,L) y = pi * (1i) * seq(1:nterms) / L expy = exp(y) A2L = 0.5 * A / L expxt = exp(A2L) / L coef = choose(m,c(0:m)) / 2^m u = sort(runif(n), method="qu") xrand = u t = x0/xinc cdf = 0 kount0 = 0 set1st = FALSE while (kount0 < maxiter & cdf < u[n]) { t = xinc * t kount0 = kount0 + 1 x = A2L / t z = x + y/t ltx = ltpdf(x, ...) ltzexpy = ltpdf(z, ...) * expy par.sum = 0.5*Re(ltx) + cumsum( Re(ltzexpy) ) par.sum2 = 0.5*Re(ltx/x) + cumsum( Re(ltzexpy/z) ) pdf = expxt * sum(coef * par.sum[seqbtL]) / t cdf = expxt * sum(coef * par.sum2[seqbtL]) / t if (!set1st & cdf > u[1]) { cdf1 = cdf pdf1 = pdf t1 = t set1st = TRUE } } if (kount0 >= maxiter) { stop('Cannot locate upper quantile') } upplim = t lower = 0 t = t1 cdf = cdf1 pdf = pdf1 kount = numeric(n) maxiter = 1000 for (j in 1:n) { upper = upplim kount[j] = 0 while (kount[j] < maxiter & abs(u[j]-cdf) > tol) { kount[j] = kount[j] + 1 t = t - (cdf-u[j])/pdf if (t < lower | t > upper) { t = 0.5 * (lower + upper) } x = A2L / t z = x + y/t ltx = ltpdf(x, ...) ltzexpy = ltpdf(z, ...) * expy par.sum = 0.5*Re(ltx) + cumsum( Re(ltzexpy) ) par.sum2 = 0.5*Re(ltx/x) + cumsum( Re(ltzexpy/z) ) pdf = expxt * sum(coef * par.sum[seqbtL]) / t cdf = expxt * sum(coef * par.sum2[seqbtL]) / t if (cdf <= u[j]) { lower = t} else { upper = t} } if (kount[j] >= maxiter) { warning('Desired accuracy not achieved for F(x)=u') } xrand[j] = t lower = t } if (n > 1) { rsample <- sample(xrand) } else { rsample <- xrand} rsample }
bhl_getpartnames <- function(...) { .Defunct(new = "bhl_getpartmetadata", package = "rbhl", msg = "see ?bhl_getpartmetadata") }
expected <- eval(parse(text="\"The following object is masked from ‘package:base’:\\n\\n det\\n\"")); test(id=0, code={ argv <- eval(parse(text="list(NULL, \"The following object is masked from ‘package:base’:\\n\\n det\\n\")")); .Internal(gettext(argv[[1]], argv[[2]])); }, o=expected);
data_collection_program <- function(interactive = TRUE, ...) { interactive <- check_interactive(interactive) observation <- if (interactive) { interactive_data_collection_program(...) } else { manual_data_collection_program(...) } return(observation) } compendium_reference <- function(obs_data, interactive = TRUE, ...){ interactive <- check_interactive(interactive) obs_data <- if (interactive) { interactive_compendium_reference(obs_data, ...) } else { manual_compendium_reference(obs_data, ...) } return(obs_data) }
test_that("check_packages_installed", { expect_equal(check_packages_installed("mlr3misc"), setNames(TRUE, "mlr3misc")) expect_warning(check_packages_installed("this_is_not_a_package999"), "required but not installed") expect_warning(check_packages_installed("this_is_not_a_package999", msg = "foobar %s"), "foobar") expect_logical(check_packages_installed("this_is_not_a_package999", warn = FALSE)) expect_true(tryCatch(check_packages_installed("this_is_not_a_package999"), packageNotFoundWarning = function(e) TRUE)) })
PERC <- function (Sigma, par = NULL, percentage = TRUE, optctrl = ctrl(), ...){ if(!isSymmetric(Sigma)){ stop("Matrix provided for Sigma is not symmetric.\n") } N <- ncol(Sigma) mrc <- rep(1/N, N) if(is.null(par)){ par <- mrc } else { if(length(par) != N){ stop("Length of 'par' not comformable with dimension of 'Sigma'.\n") } } call <- match.call() opt <- rp(x0 = par, P = Sigma, mrc = mrc, optctrl = optctrl) w <- drop(getx(opt)) w <- w / sum(w) if(percentage) w <- w * 100 if(is.null(dimnames(Sigma))){ names(w) <- paste("Asset", 1:N, sep = "") } else { names(w) <- colnames(Sigma) } new("PortSol", weights = w, opt = list(opt), type = "Equal Risk Contribution", call = call) }
context("local_style()") test_that("can be empty", { f <- function() { local_style() div(.style %>% background("red")) } f() %>% expect_html_class("cas-bg-red") }) test_that("rename prefix", { f <- function() { local_style(background = "bg") div(.style %>% background("indigo")) } f() %>% expect_html_class("bg-indigo") }) test_that("modifies passed .style", { f <- function(...) { local_style(margin = "margin") div( "hello, world!", ... ) } f(.style %>% margin(5)) %>% expect_s3_class("shiny.tag") %>% expect_html_class("margin-5") })
"simple_ts"
complete.mids.nmi <- function( x, action=c(1,1) ) { if ( x$type=="mice" ){ x1 <- x$imp data <- mice::complete( x1[[ action[1] ]], action=action[2] ) } if ( x$type=="mice.1chain" ){ data <- complete.mids.1chain( x$imp[[ action[1] ]], action=action[2] ) } return(data) } complete.mids.1chain <- function( x, action=1 ) { mice::complete( x$midsobj, action=action ) }
library(testthat) library(distill) test_check("distill")
library(ggplot2) library(ggiraph) dataset <- structure(list(qsec = c(16.46, 17.02, 18.61, 19.44, 17.02, 20.22 ), disp = c(160, 160, 108, 258, 360, 225), carname = c("Mazda RX4", "Mazda RX4 Wag", "Datsun 710", "Hornet 4 Drive", "Hornet Sportabout", "Valiant"), wt = c(2.62, 2.875, 2.32, 3.215, 3.44, 3.46)), row.names = c("Mazda RX4", "Mazda RX4 Wag", "Datsun 710", "Hornet 4 Drive", "Hornet Sportabout", "Valiant"), class = "data.frame") dataset gg_point = ggplot(data = dataset) + geom_point_interactive(aes(x = wt, y = qsec, color = disp, tooltip = carname, data_id = carname)) + theme_minimal() x <- girafe(ggobj = gg_point) if( interactive() ) print(x)
process_target_command <- function(name, dat, file_extensions) { core <- c("command", "rule", "args", "depends", "is_target") invalid <- c("rule", "target_argument", "quoted") if (any(invalid %in% names(dat))) { stop("Invalid keys: ", paste(intersect(invalid, names(dat)), collapse=", ")) } if (length(dat$depends) > 0) { dat$depends <- unlist(from_yaml_map_list(dat$depends)) } else { dat$depends <- character(0) } if (!is.null(dat$command)) { cmd <- parse_target_command(name, dat$command) if (length(dat$depends > 0)) { cmd$depends <- c(cmd$depends, dat$depends) } rewrite <- intersect(names(cmd), core) dat[rewrite] <- cmd[rewrite] } type <- target_infer_type(name, dat, file_extensions) is_command <- names(dat) %in% core list(command=dat[is_command], opts=dat[!is_command], type=type) } parse_target_command <- function(target_name, command, file_extensions) { if (is.character(command) && length(command) > 1L) { stop("commands must be scalar") } dat <- parse_command(command) if (length(dat$depends) > 0L) { depends <- dat$depends is_dot <- depends == "." if (sum(is_dot) > 1L) { stop("Only a single dot argument allowed") } else if (sum(is_dot) == 1L) { i <- which(is_dot) if (is.character(dat$args[[i]])) { stop("Dot argument must not be quoted (it's like a variable)") } } pos <- c(target_name, "target_name") i <- sapply(pos, function(x) depends == x) if (length(depends) == 1) { i <- rbind(i, deparse.level=0) } if (sum(i) == 1L) { j <- unname(which(rowSums(i) == 1L)) v <- dat$args[[j]] if (is.character(v) && v == "target_name") { stop("target_name must not be quoted (it's like a variable)") } else if (is.name(v) && v != quote(target_name)) { stop("target name must be quoted (it must be a file name)") } dat$args[[j]] <- target_name dat$depends <- dat$depends[-j] dat$command[[j + 1L]] <- target_name dat$is_target[[j]] <- FALSE } else if (sum(i) > 1L) { n <- colSums(i) n <- n[n > 0] stop(sprintf("target name matched multiple times in command for '%s': %s", dat$rule, paste(sprintf("%s (%d)", names(n), n), collapse=", "))) } } dat } parse_command <- function(str) { command <- check_command(str) rule <- check_command_rule(command[[1]]) is_target <- unname(vlapply(command[-1], is_target_like)) if (any(!is_target)) { i <- c(FALSE, !is_target) command[i] <- lapply(command[i], check_literal_arg) } args <- as.list(command[-1]) depends <- vcapply(args[is_target], as.character) list(rule=rule, args=args, depends=depends, is_target=is_target, command=command) } check_command <- function(str) { if (is.language(str)) { command <- str } else { assert_scalar_character(str) command <- parse(text=as.character(str), keep.source=FALSE) if (length(command) != 1L) { stop("Expected single expression") } command <- command[[1]] } if (length(command) == 0) { stop("I don't think this is possible") } if (!is.call(command)) { stop("Expected a function call (even with no arguments)") } command } check_command_rule <- function(x) { if (is.name(x)) { x <- as.character(x) } else if (!is.character(x)) { stop("Rule must be a character or name") } x } check_literal_arg <- function(x) { if (is.atomic(x)) { x } else if (is.call(x)) { if (identical(x[[1]], quote(I))) { x[[2]] } else { stop("Unknown special function ", as.character(x[[1]])) } } else { stop("Unknown type in argument list") } } is_target_like <- function(x) { is.character(x) || is.name(x) } target_infer_type <- function(name, dat, file_extensions) { type <- dat$type if (is.null(type)) { type <- if (target_is_file(name, file_extensions)) "file" else "object" if ("knitr" %in% names(dat)) { type <- "knitr" } else if ("download" %in% names(dat)) { type <- "download" } else if ("plot" %in% names(dat)) { type <- "plot" } else if (type == "object" && is.null(dat$command)) { type <- "fake" } } else { assert_scalar_character(type) } type } target_is_file <- function(x, file_extensions) { is_file <- grepl("/", x, fixed=TRUE) check <- !is_file if (any(check)) { if (is.null(file_extensions)) { file_extensions <- file_extensions() } is_file[check] <- tolower(file_extension(x[check])) %in% file_extensions } is_file }
itis_downstream <- function(id, downto, intermediate = FALSE, tsns = NULL, ...) { pchk(tsns, "id") if (!is.null(tsns)) id <- tsns downto <- tolower(downto) downto2 <- taxize_ds$rank_ref[which_rank(downto), "rankid"] torank_ids <- taxize_ds$rank_ref[ which_rank(downto):NROW(taxize_ds$rank_ref), "rankid"] stop_ <- "not" notout <- data.frame(rankname = "") out <- list() if (intermediate) intermed <- list() iter <- 0 while (stop_ == "not") { iter <- iter + 1 if (!nchar(as.character(notout$rankname[[1]])) > 0) { temp <- dt2df(lapply(as.character(id), ritis::rank_name), idcol = FALSE) } else { temp <- notout } tt <- dt2df(lapply(as.character(temp$tsn), ritis::hierarchy_down), idcol = FALSE) names_ <- dt2df(lapply(split(tt, row.names(tt)), function(x) { ritis::rank_name(as.character(x$tsn))[,c("rankid","rankname","tsn")] }), idcol = FALSE) if (nrow(names_) == 0) { out[[iter]] <- data.frame(tsn = "No data", parentname = "No data", parenttsn = "No data", taxonname = "No data", rankid = "No data", rankname = "No data") stop_ <- "nodata" } else { tt <- merge(tt, names_[,-2], by = "tsn") if (intermediate) intermed[[iter]] <- tt if (nrow(tt[tt$rankid == downto2, ]) > 0) out[[iter]] <- tt[tt$rankid == downto2, ] if (nrow(tt[!tt$rankid == downto2, ]) > 0) { notout <- tt[!tt$rankid %in% torank_ids, ] } else { notout <- data.frame(rankname = downto) } if (length(notout$rankname) > 0) notout$rankname <- tolower(notout$rankname) if (all(notout$rankname == downto)) { stop_ <- "fam" } else { id <- notout$tsn stop_ <- "not" } } if (intermediate) { intermed[[iter]] <- stats::setNames(intermed[[iter]], tolower(names(intermed[[iter]]))) intermed[[iter]]$rankname <- tolower(intermed[[iter]]$rankname) } } tmp <- dt2df(out, idcol = FALSE) tmp$rankname <- tolower(tmp$rankname) if (intermediate) { list(target = stats::setNames(tmp, tolower(names(tmp))), intermediate = intermed) } else { stats::setNames(tmp, tolower(names(tmp))) } }
test.dayOfWeek <- function() { old <- setRmetricsOptions(myFinCenter = "Zurich") on.exit(setRmetricsOptions(old)) td <- timeDate("2010-01-01") check <- c("2010-01-01" = "Fri") checkIdentical(dayOfWeek(td), check) setRmetricsOptions(myFinCenter = "GMT") td <- timeDate("2010-01-01") check <- c("2010-01-01" = "Fri") checkIdentical(dayOfWeek(td), check) }
FreeMatches <- function(Competitions){ print("Whilst we are keen to share data and facilitate research, we also urge you to be responsible with the data. Please register your details on https://www.statsbomb.com/resource-centre and read our User Agreement carefully.") Matches.df <- tibble() for(i in 1:nrow(Competitions)){ Matches.url <- paste0("https://raw.githubusercontent.com/statsbomb/open-data/master/data/matches/", Competitions$competition_id[i], "/", Competitions$season_id[i], ".json") raw.matches <- GET(url = Matches.url) matches.string <- rawToChar(raw.matches$content) matches <- fromJSON(matches.string, flatten = T) Matches.df <- bind_rows(Matches.df, matches) } return(Matches.df) }
mjs_plot <- function(data, x, y, show_rollover_text = TRUE, linked = FALSE, decimals=2, format="count", missing_is_hidden=FALSE, left = 80, right = 10, top = 40, bottom = 60, buffer = 8, width = NULL, height = NULL, title=NULL, description=NULL) { if (!format %in% c("percentage", "count")) { stop("'format' must be either 'percentage' or 'count'") } if (inherits(data, "data.frame")) data <- data.frame(data, stringsAsFactors=FALSE) eid <- sprintf("mjs-%s", paste(sample(c(letters[1:6], 0:9), 30, replace=TRUE), collapse="")) if (!missing(x)) { x <- substitute(x) res <- try(eval(x, data, parent.frame()), silent = TRUE) if (!inherits(res, "try-error") && inherits(res, "character")) { if (length(res) != 1) { x <- as.character(substitute(x)) } else { x <- res } } else if (inherits(x, "name")) { x <- as.character(x) } } else { x <- as.character(substitute(x)) } if (!missing(y)) { y <- substitute(y) res <- try(eval(y, data, parent.frame()), silent = TRUE) if (!inherits(res, "try-error") && inherits(res, "character")) { if (length(res) != 1) { y <- as.character(substitute(y)) } else { y <- res } } else if (inherits(y, "name")) { y <- as.character(y) } } else { y <- as.character(substitute(y)) } is_datetime <- function(x) { inherits(x, c('Date', 'POSIXct', 'POSIXlt')) } is_posix <- function(x) { inherits(x, c('POSIXct', 'POSIXlt')) } orig_posix <- FALSE if (is.null(dim(data))) { if (is_posix(data)) orig_posix <- TRUE } else if (is_posix(data[, x])) { orig_posix <- TRUE } if (is.null(dim(data))) { if (is_datetime(data)) data <- as.numeric(data) } else if (is_datetime(data[, x])) { data[, x] <- as.numeric(data[, x]) } params = list( forCSS=NULL, regions=NULL, orig_posix=orig_posix, data=data, x_axis=TRUE, y_axis=TRUE, baseline_accessor=NULL, predictor_accessor=NULL, show_confidence_band=NULL, show_secondary_x_label=NULL, chart_type="line", xax_format="plain", x_label=NULL, y_label=NULL, markers=NULL, baselines=NULL, linked=linked, title=title, description=description, left=left, right=right, bottom=bottom, buffer=buffer, format=format, y_scale_type="linear", yax_count=5, xax_count=6, x_rug=FALSE, y_rug=FALSE, area=FALSE, missing_is_hidden=missing_is_hidden, size_accessor=NULL, color_accessor=NULL, color_type="number", color_range=c("blue", "red"), size_range=c(1, 5), bar_height=20, min_x=NULL, max_x=NULL, min_y=NULL, max_y=NULL, bar_margin=1, binned=FALSE, bins=NULL, least_squares=FALSE, interpolate="cardinal", decimals=decimals, show_rollover_text=show_rollover_text, x_accessor=x, y_accessor=y, multi_line=NULL, geom="line", yax_units="", legend=NULL, legend_target=NULL, y_extended_ticks=FALSE, x_extended_ticks=FALSE, target=sprintf(" ) if (is.null(width)) params$full_width <- TRUE if (is.null(height)) params$full_height <- TRUE htmlwidgets::createWidget( name = 'metricsgraphics', x = params, width = width, height = height, package = 'metricsgraphics', elementId = eid ) } metricsgraphicsOutput <- function(outputId, width = '100%', height = '400px'){ htmlwidgets::shinyWidgetOutput(outputId, 'metricsgraphics', width, height, package = 'metricsgraphics') } renderMetricsgraphics <- function(expr, env = parent.frame(), quoted = FALSE) { if (!quoted) { expr <- substitute(expr) } htmlwidgets::shinyRenderWidget(expr, metricsgraphicsOutput, env, quoted = TRUE) } metricsgraphics_html <- function(id, style, class, ...) { list(tags$div(id = id, class = class, style = style), tags$div(id = sprintf("%s-legend", id), class = sprintf("%s-legend", class))) }
MNP <- function(level){ x <- NULL if(level==1){ x <- github.nytimes.covid19data(fips = "69", level = 2) } return(x) }
bootEff <- function(mod, R, seed = NULL, type = c("nonparametric", "parametric", "semiparametric"), ran.eff = NULL, cor.err = NULL, catch.err = TRUE, parallel = c("snow", "multicore", "no"), ncpus = NULL, cl = NULL, bM.arg = NULL, ...) { if (missing(R)) stop("Number of bootstrap resamples (R) must be specified.") m <- mod; type <- match.arg(type); re <- ran.eff; ce <- cor.err; parallel <- match.arg(parallel); nc <- ncpus; if (class(m)[1] == "psem") { m <- m[sapply(m, isMod)] ce <- do.call(c, m[sapply(m, class) == "formula.cerror"]) } if (isList(m) && is.null(names(m))) { names(m) <- sapply(m, function(i) { if (isList(i)) i <- i[[1]] names(model.frame(i, data = getData(i)))[1] }) } a <- list(...) w <- a$weights; a$weights <- NULL if (isList(m) && (is.null(w) || all(w == "equal"))) { if (is.null(w) && any(sapply(m, isList))) stop("'weights' must be supplied for model averaging (or specify 'equal').") w <- lapply(m, function(i) w) } upd <- function(m, d) { upd <- function(m) { eval(update(m, data = d, evaluate = FALSE)) } rMapply(upd, m, SIMPLIFY = FALSE) } d <- a$data; a$data <- NULL if (!is.null(d)) m <- upd(m, d) main.env <- environment() env <- a$env; a$env <- NULL if (is.null(env)) env <- parent.frame() if (!is.null(d)) env <- main.env mer <- unlist(rMapply(isMer, m)) if (any(mer) && !all(mer)) warning("Mixed and non-mixed models together in list. Resampling will treat all models as mixed.") mer <- any(mer) mer2 <- isTRUE(if (mer) { pb <- type %in% c("parametric", "semiparametric") if (!pb && is.null(re)) stop("Name of random effect to resample must be specified to 'ran.eff' (or use parametric bootstrapping).") mer && pb }) if (mer2) { bootMer2 <- function(...) { C <- match.call() n <- length(C) a <- c(list(FUN = s, nsim = R, seed = NULL, type = type, parallel = parallel, ncpus = nc, cl = cl), bM.arg) for (i in 1:length(a)) { C[n + i] <- a[i] names(C)[n + i] <- names(a)[i] } C[[1]] <- as.name("bootMer") set.seed(seed) eval.parent(C) } s <- NULL } any.ce <- isList(m) && !is.null(ce) if (any.ce) { cv <- sapply(ce, function(i) { gsub(" ", "", unlist(strsplit(i, "~~"))) }, simplify = FALSE) cv <- cv[sapply(cv, function(i) { all(i %in% names(m)) && all(i %in% names(w)) })] if (length(cv) < 1) stop("Names of variable(s) with correlated errors missing from list of models and/or weights.") } if (parallel != "no") { if (is.null(nc)) nc <- parallel::detectCores() if (parallel == "snow") { if (is.null(cl)) { cl <- parallel::makeCluster(getOption("cl.cores", nc)) } P <- function(...) { paste(..., collapse = " ") } mc <- P(unlist(rMapply(function(i) P(getCall(i)), m))) o <- unlist(lapply(search(), ls)) o <- o[sapply(o, function(i) grepl(i, mc, fixed = TRUE))] o <- c(o, ls("package:semEff")) parallel::clusterExport(cl, o) } } if (is.null(seed)) { set.seed(NULL) seed <- sample(10000:99999, 1) } bootEff <- function(m, w) { d <- getData(m, subset = TRUE, merge = TRUE, env = env) if (!mer2) x <- if (mer) unique(d[re]) else d stat <- function(x, i) { xi <- if (mer) { do.call(rbind, lapply(x[i, ], function(j) { d[d[, re] == j, ] })) } else x[i, ] do.call(stdEff, c(list(m, w, xi), a)) } stat2 <- function(x) { do.call(stdEff, c(list(x), a)) } s <- if (mer2) stat <- stat2 else stat if (catch.err) { s <- function(...) { tryCatch(stat(...), error = function(e) NA) } } if (mer2) assign("s", s, main.env) B <- if (!mer2) { set.seed(seed) boot::boot(x, s, R, parallel = parallel, ncpus = nc, cl = cl) } else { if (isList(m)) { B <- lapply(m, bootMer2) bn <- a$term.names b <- lapply(B, "[[", 1) b <- avgEst(b, w, bn) bb <- t(sapply(1:R, function(i) { bb <- lapply(B, function(j) j$t[i, ]) avgEst(bb, w, bn) })) if (ncol(bb) == R) bb <- t(bb) B <- B[[1]] B$t0 <- b; B$t <- bb B$call <- NULL; B$statistic <- NULL; B$mle <- NULL B } else bootMer2(m) } n.err <- sum(apply(rbind(B$t0, B$t), 1, function(i) any(is.na(i)))) if (n.err > 0) warning(paste(n.err, "model fit(s) or parameter estimation(s) failed. NAs reported/generated.")) colnames(B$t) <- names(B$t0) attributes(B$t)[c("sim", "seed", "n")] <- c(B$sim, seed, nrow(B$data)) B } BE <- rMapply(bootEff, m, w, SIMPLIFY = FALSE) if (any.ce) { if (is.null(d)) d <- getData(m, merge = TRUE, env = env) obs <- rownames(d) res <- function(x, w = NULL) { f <- function(m) { if (!isGls(m) && !isGlm(m)) { resid(m, type = "deviance") } else resid(m) } if (isList(x)) { if (all(sapply(x, isBoot))) { r <- lapply(x, "[[", 1) r <- avgEst(r, w) rb <- t(sapply(1:R, function(i) { rb <- lapply(x, function(j) j$t[i, ]) avgEst(rb, w) })) list(r, rb) } else { r <- lapply(x, f) avgEst(r, w) } } else { if (isBoot(x)) list(x$t0, x$t) else f(x) } } BCE <- Map(function(i, j) { m1 <- m[[i[1]]]; w1 <- w[[i[1]]] d1 <- getData(m1, subset = TRUE, merge = TRUE, env = env) m2 <- m[[i[2]]]; w2 <- w[[i[2]]] d2 <- getData(m2, subset = TRUE, merge = TRUE, env = env) o <- obs %in% rownames(d1) & obs %in% rownames(d2) if (!all(o)) d <- d[o, ] if (!mer2) { x <- if (mer) unique(d[re]) else d } else { if (!all(o)) {m1 <- upd(m1, d); m2 <- upd(m2, d)} } stat <- function(x, i) { xi <- if (mer) { do.call(rbind, lapply(x[i, ], function(j) { d[d[, re] == j, ] })) } else x[i, ] r1 <- res(upd(m1, xi), w1) r2 <- res(upd(m2, xi), w2) cor(r1, r2) } s <- if (mer2) stat <- res else stat if (catch.err) { na <- if (mer2) rep(NA, nrow(d)) else NA s <- function(...) { tryCatch(stat(...), error = function(e) na) } } if (mer2) assign("s", s, main.env) B <- if (!mer2) { set.seed(seed) boot::boot(x, s, R, parallel = parallel, ncpus = nc, cl = cl) } else { B1 <- rMapply(bootMer2, m1, SIMPLIFY = FALSE) R1 <- res(B1) r1 <- R1[[1]]; rb1 <- R1[[2]] B2 <- rMapply(bootMer2, m2, SIMPLIFY = FALSE) R2 <- res(B2) r2 <- R2[[1]]; rb2 <- R2[[2]] B <- if (isList(B1)) B1[[1]] else B1 B$t0 <- cor(r1, r2) B$t <- matrix(sapply(1:R, function(i) cor(rb1[i, ], rb2[i, ]))) B$call <- NULL; B$statistic <- NULL; B$mle <- NULL B } n.err <- sum(apply(rbind(B$t0, B$t), 1, function(i) any(is.na(i)))) if (n.err > 0) warning(paste(n.err, "model fit(s) or parameter estimation(s) failed. NAs reported/generated.")) names(B$t0) <- j; colnames(B$t) <- j attributes(B$t)[c("sim", "seed", "n")] <- c(B$sim, seed, nrow(B$data)) B }, cv, names(cv)) if (!isList(BE)) BE <- list(BE) BE <- c(BE, BCE) } if (parallel == "snow") parallel::stopCluster(cl) set.seed(NULL) BE } bootCI <- function(mod, conf = 0.95, type = "bca", digits = 3, bci.arg = NULL, ...) { m <- mod is.B <- all(unlist(rMapply(isBoot, m))) B <- if (!is.B) bootEff(m, ...) else m bootCI <- function(B) { if (B$sim == "parametric" && type[1] == "bca") { message("Percentile confidence intervals used for parametric bootstrap samples.") type <- "perc" } e <- B$t0 bi <- colMeans(B$t, na.rm = TRUE) - e se <- apply(B$t, 2, sd, na.rm = TRUE) se[is.na(e)] <- NA ci <- sapply(1:length(e), function(i) { if (!is.na(e[i])) { if (e[i] != 0) { ci <- suppressWarnings( do.call( boot::boot.ci, c(list(B, conf, type, i), bci.arg) ) ) tail(as.vector(ci[[4]]), 2) } else rep(0, 2) } else rep(NA, 2) }) e <- data.frame("Effect" = e, "Bias" = bi, "Std. Err." = se, "Lower CI" = ci[1, ], "Upper CI" = ci[2, ], check.names = FALSE) e <- round(e, digits) stars <- apply(e, 1, function(i) { if (!any(is.na(i))) { i <- c(i[1], tail(i, 2)) if (all(i > 0) || all(i < 0)) "*" else "" } else "" }) e <- cbind(e, " " = stars) e <- format(e, nsmall = digits) e <- cbind(" " = rownames(e), "|", e[1], "|", e[2], "|", e[3], "|", e[4:5], "|", e[6], fix.empty.names = FALSE) b <- mapply(function(i, j) { n1 <- nchar(j) n2 <- max(sapply(i, nchar), n1, 3) b <- if (n1 > 1) rep("-", n2) else "" paste(b, collapse = "") }, e, names(e)) e <- rbind(b, e) e[1] <- format(e[1], justify = "left") rownames(e) <- 1:nrow(e) class(e) <- c("bootCI", class(e)) attr(e, "ci.conf") <- conf attr(e, "ci.type") <- type e } rMapply(bootCI, B, SIMPLIFY = FALSE) } print.bootCI <- function(x, ...) { print.data.frame(x, row.names = FALSE) }
check_netmhc2pan_data_url <- function( netmhc2pan_data_url = get_netmhc2pan_data_url(), verbose = FALSE, temp_local_file = tempfile(pattern = "check_netmhc2pan_data_url_") ) { if (verbose) { message( "netmhc2pan_data_url: ", netmhc2pan_data_url, " \n", "temp_local_file: ", temp_local_file, " \n" ) } netmhc2pan::check_can_create_file( filename = temp_local_file, overwrite = FALSE ) tryCatch({ suppressWarnings( utils::download.file( url = netmhc2pan_data_url, destfile = temp_local_file, quiet = !verbose ) ) }, error = function(e) { stop( "'netmhc2pan_data_url' is invalid.\n", "netmhc2pan_data_url: ", netmhc2pan_data_url, "\n", "\n", "Full error message: \n", "\n", e ) }) file.remove(temp_local_file) }
sql_render <- function (query) { dplyr::check_dbplyr() dbplyr::sql_render(query = query) }
carpools.waterfall.pval = function(type=NULL,dataset=NULL, pval=0.05, mageck.type="pos", log=TRUE) { pval.old=pval if(is.null(type)) {stop("No analysis type selected. Please use either type='deseq2', type='mageck' or type='wilcox'.")} else if(type=="wilcox") { plot.data = dataset$p.value } else if (type=="deseq2") { plot.data = dataset$genes[,"padj"] } else if(type=="mageck") { plot.data = dataset$genes[,mageck.type] } if(identical(log,TRUE)) { plot.data = sapply(plot.data, function(x) { if(is.finite(-log10(as.numeric(x)))) { return(-log10(as.numeric(x)))} else return(1) }) pval = -log10(pval) plot.data = sort(plot.data, decreasing=TRUE) plot.col = sapply(plot.data, function(x) { if(as.numeric(x) >= pval) {return("red")} else { return("black")} }) ylab = "-log10 adjusted p-value" } else { plot.data = sort(plot.data, decreasing=FALSE) plot.col = sapply(plot.data, function(x) { if(as.numeric(x) <= pval) {return("red")} else { return("black")} }) ylab = "adjusted p-value" } plot(1:length(plot.data), plot.data, main="p-value Distribution", ylab = ylab, xlab="Gene", col= plot.col, pch = 16 ) lines(1:length(plot.data), rep(pval, length(plot.data)), col="black", lty="dashed", lwd=2) legend("topright", legend=paste("p-value:",pval.old, sep=" ")) }
"ecld.mu_D" <- function(object, validate=TRUE) { ecld.validate(object, sged.allowed=TRUE) one <- if([email protected]) ecd.mp1 else 1 lambda <- object@lambda * one s <- object@sigma * one b <- object@beta pass <- function(x) { if (validate) { if (is.na(x)) { stop(paste("mu_D is NaN:", "lambda=", ecd.mp2f(lambda), "beta=", ecd.mp2f(b), "sigma=", ecd.mp2f(s))) } if (abs(x)==Inf) { stop(paste("mu_D is infinite:", "lambda=", ecd.mp2f(lambda), "beta=", ecd.mp2f(b), "sigma=", ecd.mp2f(s))) } } return(x) } if ([email protected]) { d0 <- ecd(lambda=ecd.mp2f(lambda), sigma=one, bare.bone=TRUE) sn <- s*(1-b) sp <- s*(1+b) e_y1 <- function(xi) exp(-xi^(2/lambda))*(exp(sp*xi)-1) xt <- ecld.y_slope_trunc(object)/sp if (xt > .ecd.mpfr.N.sigma) xt <- .ecd.mpfr.N.sigma M1 <- ecd.integrate(d0, e_y1, 0, xt) e_y2 <- function(xi) exp(-xi^(2/lambda))*(exp(-sn*xi)-1) M2 <- ecd.integrate(d0, e_y2, 0, Inf) if (M1$message != "OK") { stop("Failed to integrate right tail from unit distribution") } if (M2$message != "OK") { stop("Failed to integrate left tail from unit distribution") } C <- ecld.const(object) return(pass(ecd.mpnum(object, -log(1 + (sp*M1$value + sn*M2$value)/C)))) } if (lambda==1) { if (b != 0) { stop("lambda=1: beta must be zero") } return(pass(-s^2/4)) } if (lambda==2) { return(pass(log(1-b*s-s^2))) } if (lambda==4 & b==0) { object@mu <- 0 return(ecld.mu_D_by_sum(object)) } if (TRUE) { return(ecld.mu_D_integrate(object, validate=validate)) } stop("Unknown analytic formula for mu_D") } "ecld.mu_D_quartic" <- function(object) { s <- object@sigma z = 1/2/sqrt(s) dz = z^2*exp(-z^2) Mz <- z^3*(ecd.erfq(z,-1) -ecd.erfq(z,1)) return(-log(Mz + dz)) } "ecld.mu_D_by_sum" <- function(object) { return(-log(ecld.mgf_by_sum(object))+object@mu) } "ecld.mu_D_integrate" <- function(object, validate=TRUE) { ecld.validate(object, sged.allowed=TRUE) one <- if([email protected]) ecd.mp1 else 1 lambda <- object@lambda * one s <- object@sigma * one b <- object@beta pass <- function(x) { if (validate) { if (is.na(x)) { stop(paste("mu_D is NaN:", "lambda=", ecd.mp2f(lambda), "beta=", ecd.mp2f(b), "sigma=", ecd.mp2f(s))) } if (abs(x)==Inf) { stop(paste("mu_D is infinite:", "lambda=", ecd.mp2f(lambda), "beta=", ecd.mp2f(b), "sigma=", ecd.mp2f(s))) } } return(x) } ld0 <- ecld(lambda=ecd.mp2f(lambda), beta=ecd.mp2f(b), sigma=one) d0 <- ecd(lambda=ecd.mp2f(lambda), beta=ecd.mp2f(b), sigma=one, bare.bone=TRUE) e_y1 <- function(xi) exp(ecld.solve(ld0,xi))*(exp(s*xi)-1) xt <- ecld.y_slope_trunc(object)/s if (xt > .ecd.mpfr.N.sigma) xt <- .ecd.mpfr.N.sigma M1 <- ecd.integrate(d0, e_y1, 0, xt) e_y2 <- function(xi) exp(ecld.solve(ld0,-xi))*(exp(-s*xi)-1) M2 <- ecd.integrate(d0, e_y2, 0, Inf) if (M1$message != "OK") { stop("Failed to integrate right tail from unit distribution") } if (M2$message != "OK") { stop("Failed to integrate left tail from unit distribution") } C <- ecld.const(object)/s return(pass(ecd.mpnum(object, -log(1+(M1$value+M2$value)/C)))) }
context("survival-coxph") skip_if_not_installed("modeltests") library(modeltests) skip_if_not_installed("survival") library(survival) fit <- coxph(Surv(time, status) ~ age + sex, lung) fit2 <- coxph(Surv(time, status) ~ age + sex, lung, robust = TRUE) fit3 <- coxph(Surv(time, status) ~ age + sex + frailty(inst), lung) bladder1 <- bladder[bladder$enum < 5, ] fit4 <- coxph(Surv(stop, event) ~ (rx + size + number) * strata(enum) + cluster(id), bladder1) fit5 <- coxph(Surv(time, status) ~ age + pspline(nodes), data = colon) test_that("coxph tidier arguments", { check_arguments(tidy.coxph) check_arguments(glance.coxph) check_arguments(augment.coxph) }) test_that("tidy.coxph", { td <- tidy(fit) td2 <- tidy(fit, exponentiate = TRUE) td3 <- tidy(fit2) td4 <- tidy(fit3) td5 <- tidy(fit3, exponentiate = TRUE) td6 <- tidy(fit3, conf.int = TRUE) td7 <- tidy(fit4) td8 <- tidy(fit4, exponentiate = TRUE) td9 <- tidy(fit4, conf.int = TRUE) td10 <- tidy(fit5) td11 <- tidy(fit5, conf.int = TRUE) check_tidy_output(td) check_tidy_output(td2) check_tidy_output(td3) check_tidy_output(td4) check_tidy_output(td5) check_tidy_output(td6) check_tidy_output(td7) check_tidy_output(td8) check_tidy_output(td9) check_tidy_output(td10) check_tidy_output(td11) }) test_that("glance.coxph", { gl <- glance(fit) gl2 <- glance(fit2) gl3 <- glance(fit3) gl4 <- glance(fit4) check_glance_outputs(gl, gl2, gl3, gl4, strict = FALSE) }) test_that("augment.coxph", { expect_error( augment(fit), regexp = "Must specify either `data` or `newdata` argument." ) check_augment_function( aug = augment.coxph, model = fit, data = lung, newdata = lung ) check_augment_function( aug = augment.coxph, model = fit2, data = lung, newdata = lung ) })
test_that("Testing log-likelihood function", { discrete_data = readRDS("discrete_data.RData") m = displ$new(discrete_data) m$setPars(2.58); m$setXmin(2) expect_equal(dist_ll(m), -9155.62809, tol = 1e-4) x = c(1, 1) m = dislnorm$new(x) m$setPars(c(1, 1)) l = (plnorm(1.5, 1, 1) - plnorm(0.5, 1, 1)) / (1 - plnorm(0.5, 1, 1)) ll1 = 2 * log(l) expect_equal(dist_ll(m), ll1, tol = 1e-4) x = c(1, 1, 3, 4) m$setDat(x); m$setXmin(2) ll3 = (plnorm(3.5, 1, 1) - plnorm(2.5, 1, 1)) / (1 - plnorm(1.5, 1, 1)) ll4 = (plnorm(4.5, 1, 1) - plnorm(3.5, 1, 1)) / (1 - plnorm(1.5, 1, 1)) ll = log(ll3) + log(ll4) expect_equal(dist_ll(m), ll, tol = 1e-4) x = c(1, 1, 3, 4) m = dispois$new(x); m$setPars(2) ll = log(prod(dpois(x, 2) / (1 - sum(dpois(0, 2))))) expect_equal(dist_ll(m), ll, tol = 1e-4) m$setXmin(2) ll = log(prod(dpois(3:4, 2) / (1 - sum(dpois(0:1, 2))))) expect_equal(dist_ll(m), ll, tol = 1e-4) x = c(1, 1) m = disexp$new(x) m$setPars(1) l = (pexp(1.5, 1, 1) - pexp(0.5, 1, 1)) / (1 - pexp(0.5, 1, 1)) ll1 = 2 * log(l) expect_equal(dist_ll(m), ll1, tol = 1e-4) x = c(1, 1, 3, 4) m$setDat(x); m$setXmin(2) ll3 = (pexp(3.5, 1, 1) - pexp(2.5, 1, 1)) / (1 - pexp(1.5, 1, 1)) ll4 = (pexp(4.5, 1, 1) - pexp(3.5, 1, 1)) / (1 - pexp(1.5, 1, 1)) ll = log(ll3) + log(ll4) expect_equal(dist_ll(m), ll, tol = 1e-4) ctn_data = readRDS("ctn_data.RData") m = conpl$new(ctn_data) m$setPars(2.53282); m$setXmin(1.43628) expect_equal(dist_ll(m), -9276.4, tolerance = 0.00001); x = c(1, 1) m = conlnorm$new(x); m$setPars(c(1, 1)) ll1 = sum(log(dlnorm(x, 1, 1) / (1 - plnorm(1, 1, 1)))) expect_equal(dist_ll(m), ll1, tol = 1e-4) x = c(1, 1, 3, 4) m$setDat(x) ll2 = sum(log(dlnorm(3:4, 1, 1) / (1 - plnorm(1, 1, 1)))) expect_equal(dist_ll(m), ll1 + ll2, tol = 1e-4) m$setXmin(2) ll3 = sum(log(dlnorm(3:4, 1, 1) / (1 - plnorm(2, 1, 1)))) expect_equal(dist_ll(m), ll3, tol = 1e-4) x = c(1, 1) m = conexp$new(x); m$setPars(1) ll1 = sum(log(dexp(x, 1) / (1 - pexp(1, 1)))) expect_equal(dist_ll(m), ll1, tol = 1e-4) x = c(1, 1, 3, 4) m$setDat(x) ll2 = sum(log(dexp(3:4, 1) / (1 - pexp(1, 1)))) expect_equal(dist_ll(m), ll1 + ll2, tol = 1e-4) m$setXmin(2) ll3 = sum(log(dexp(3:4, 1) / (1 - pexp(2, 1)))) expect_equal(dist_ll(m), ll3, tol = 1e-4) } )
homog.test <- function(resmca,var,dim=c(1,2)) { type <- attr(resmca,'class')[1] if(type %in% c("MCA","stMCA","multiMCA")) eigen <- resmca$eig[,"eigenvalue"] if(type %in% c("speMCA","csMCA")) eigen <- resmca$eig$eigen vs <- varsup(resmca,var) N <- sum(vs$weight) a <- sqrt(1/outer(1/vs$weight,1/vs$weight,"+")) res <- vector("list",length(dim)) for(i in 1:length(dim)) { temp <- abs(outer(vs$coord[,dim[i]],vs$coord[,dim[i]],"-"))/sqrt(eigen[dim[i]]) test.stat <- a*sqrt((N-1)/N)*temp res[[i]]$test.stat <- test.stat res[[i]]$p.values <- 2*(1 -pnorm(test.stat)) } names(res) <- paste('dim',dim,sep='.') return(res) }
weibreg <- function (formula = formula(data), data = parent.frame(), na.action = getOption("na.action"), init, shape = 0, control = list(eps = 1e-4, maxiter = 10, trace = FALSE), singular.ok = TRUE, model = FALSE, x = FALSE, y = TRUE, center = TRUE) { pfixed <- (shape > 0) call <- match.call() m <- match.call(expand.dots = FALSE) temp <- c("", "formula", "data", "na.action") m <- m[match(temp, names(m), nomatch = 0)] special <- "strata" Terms <- if (missing(data)) terms(formula, special) else terms(formula, special, data = data) m$formula <- Terms m[[1]] <- as.name("model.frame") m <- eval(m, parent.frame()) Y <- model.extract(m, "response") if (!inherits(Y, "Surv")) stop("Response must be a survival object") weights <- model.extract(m, "weights") offset <- attr(Terms, "offset") tt <- length(offset) offset <- if (tt == 0) rep(0, nrow(Y)) else if (tt == 1) m[[offset]] else { ff <- m[[offset[1]]] for (i in 2:tt) ff <- ff + m[[offset[i]]] ff } attr(Terms, "intercept") <- 1 strats <- attr(Terms, "specials")$strata dropx <- NULL if (length(strats)) { temp <- survival::untangle.specials(Terms, "strata", 1) dropx <- c(dropx, temp$terms) if (length(temp$vars) == 1) strata.keep <- m[[temp$vars]] else strata.keep <- survival::strata(m[, temp$vars], shortlabel = TRUE) strats <- as.numeric(strata.keep) } if (length(dropx)) newTerms <- Terms[-dropx] else newTerms <- Terms X <- model.matrix(newTerms, m) assign <- lapply(survival::attrassign(X, newTerms)[-1], function(x) x - 1) X <- X[, -1, drop = FALSE] ncov <- NCOL(X) if (ncov){ if (length(dropx)){ covars <- names(m)[-c(1, (dropx + 1))] }else{ covars <- names(m)[-1] } isF <- logical(length(covars)) for (i in 1:length(covars)){ if (length(dropx)){ isF[i] <- ( is.factor(m[, -(dropx + 1)][, (i + 1)]) || is.logical(m[, -(dropx + 1)][, (i + 1)]) ) }else{ isF[i] <- ( is.factor(m[, (i + 1)]) || is.logical(m[, (i + 1)]) ) } } if (ant.fak <- sum(isF)){ levels <- list() index <- 0 for ( i in 1:length(covars) ){ if (isF[i]){ index <- index + 1 if (length(dropx)){ levels[[i]] <- levels(m[, -(dropx + 1)][, (i + 1)]) }else{ levels[[i]] <- levels(m[, (i + 1)]) } }else{ levels[[i]] <- NULL } } }else{ levels <- NULL } } type <- attr(Y, "type") if (type != "right" && type != "counting") stop(paste("This model doesn't support \"", type, "\" survival data", sep = "")) if (NCOL(Y) == 2){ Y <- cbind(numeric(NROW(Y)), Y) } n.events <- sum(Y[, 3] != 0) if (n.events == 0) stop("No events; no sense in continuing!") if (missing(init)) init <- NULL if (is.list(control)){ if (is.null(control$eps)) control$eps <- 1e-4 if (is.null(control$maxiter)) control$maxiter <- 10 if (is.null(control$trace)) control$trace <- FALSE }else{ stop("control must be a list") } fit <- weibreg.fit(X, Y, strats, offset, init, shape, control, center) if (ncov){ fit$linear.predictors <- offset + X %*% fit$coefficients[1:ncov] fit$means <- apply(X, 2, mean) }else{ fit$linear.predictors <- NULL fit$means <- NULL } if (!fit$fail){ fit$fail <- NULL }else{ out <- paste("Singular hessian; suspicious variable No. ", as.character(fit$fail), ":\n", names(coefficients)[fit$fail], " = ", as.character(fit$value), "\nTry running with fixed shape", sep = "") stop(out) } fit$convergence <- as.logical(fit$conver) fit$conver <- NULL if (is.character(fit)) { fit <- list(fail = fit) class(fit) <- "mlreg" } else if (is.null(fit$fail)){ if (!is.null(fit$coef) && any(is.na(fit$coef))) { vars <- (1:length(fit$coef))[is.na(fit$coef)] msg <- paste("X matrix deemed to be singular; variable", paste(vars, collapse = " ")) if (singular.ok) warning(msg) else stop(msg) } fit$n <- nrow(Y) fit$terms <- Terms fit$assign <- assign if (FALSE){ if (length(fit$coef) && is.null(fit$wald.test)) { nabeta <- !is.na(fit$coef) if (is.null(init)) temp <- fit$coef[nabeta] else temp <- (fit$coef - init)[nabeta] } } na.action <- attr(m, "na.action") if (length(na.action)) fit$na.action <- na.action if (model) fit$model <- m if (x) { fit$x <- X if (length(strats)) fit$strata <- strata.keep } if (y) fit$y <- Y } s.wght <- (Y[, 2] - Y[, 1]) fit$ttr <- sum(s.wght) if (ncov){ fit$isF <- isF fit$covars <- covars fit$w.means <- list() for (i in 1:length(fit$covars)){ nam <- fit$covars[i] col.m <- which(nam == names(m)) if (isF[i]){ n.lev <- length(levels[[i]]) fit$w.means[[i]] <- numeric(n.lev) for (j in 1:n.lev){ who <- m[, col.m] == levels[[i]][j] fit$w.means[[i]][j] <- sum( s.wght[who] ) / fit$ttr } }else{ fit$w.means[[i]] <- sum(s.wght * m[, col.m]) / fit$ttr } } fit$means <- colMeans(X) } fit$ttr <- sum(s.wght) fit$levels <- levels fit$formula <- formula(Terms) fit$call <- call fit$n.events <- n.events class(fit) <- c("weibreg", "phreg") fit$pfixed <- pfixed fit }
EmpEst <- function( lst, alpha, NEst, m, K ) { tab1 <- lst[[1]] p1 <- aggregate( f ~ y1, data=tab1, sum) samp <- sample( p1[,"y1"], size=NEst, prob = p1[,"f"], replace = TRUE) samp <- data.frame( y1 = samp ) Mout <- matrix(NA, nrow=2, ncol=K+2) Mout[1,1:3] <- c(alpha,1,mean(samp[,"y1"])) Mout[2,1:3] <- c(alpha,2,mean(samp[,"y1"])) cSum <- samp[,"y1"] for ( j in 2:K ) { st <- max(1,j-m) nt <- min(m,j-1) nm <- paste("y",j,sep="") nml <- paste("y",st:(j-1),sep="") tab <- lst[[j]] tab <- tab[ tab[,nm] == 1, ] stmp <- seq( nt-1, 0, by=-1 ) pow <- 2^stmp loc <- as.matrix(samp[, nml, drop=FALSE ]) %*% matrix(pow,ncol=1) + 1 p <- tab[ loc, "cf" ] y <- as.numeric( runif(NEst) <= p ) samp[,nm] <- y if (j > m) samp <- samp[,-1] Mout[1,j+2] <- mean(y) cSum <- cSum + y Mout[2,j+2] <- mean(cSum) } colnames(Mout) <- c("alpha","type",paste("t",1:K,sep="")) return(Mout) }
nzffdr_razzle_dazzle <- function(){ dat <- nzffdr::nzffdr_import() dat <- nzffdr::nzffdr_clean(dat) dat <- nzffdr::nzffdr_add_dates(dat) dat <- nzffdr::nzffdr_taxon_threat(dat) dat <- nzffdr::nzffdr_widen_habitat(dat) return(dat) }
ggplot_global <- new.env(parent = emptyenv()) ggplot_global$theme_current <- list() ggplot_global$element_tree <- list() .all_aesthetics <- c( "adj", "alpha", "angle", "bg", "cex", "col", "color", "colour", "fg", "fill", "group", "hjust", "label", "linetype", "lower", "lty", "lwd", "max", "middle", "min", "pch", "radius", "sample", "shape", "size", "srt", "upper", "vjust", "weight", "width", "x", "xend", "xmax", "xmin", "xintercept", "y", "yend", "ymax", "ymin", "yintercept", "z" ) ggplot_global$all_aesthetics <- .all_aesthetics .base_to_ggplot <- c( "col" = "colour", "color" = "colour", "pch" = "shape", "cex" = "size", "lty" = "linetype", "lwd" = "size", "srt" = "angle", "adj" = "hjust", "bg" = "fill", "fg" = "colour", "min" = "ymin", "max" = "ymax" ) ggplot_global$base_to_ggplot <- .base_to_ggplot ggplot_global$x_aes <- c("x", "xmin", "xmax", "xend", "xintercept", "xmin_final", "xmax_final", "xlower", "xmiddle", "xupper", "x0") ggplot_global$y_aes <- c("y", "ymin", "ymax", "yend", "yintercept", "ymin_final", "ymax_final", "lower", "middle", "upper", "y0")
createReservoir.base <- function(type,name,priority,downstream,netEvaporation, seepageFraction,seepageObject,geometry,plant, penstock,initialStorage) { reservoir<-list(type=type, name=name, label=runif(1), priority=priority, downstream=downstream, netEvaporation=netEvaporation, seepageFraction=seepageFraction, seepageObject=seepageObject, geometry=geometry, plant=plant, penstock=penstock, initialStorage=initialStorage) return(reservoir) }
extract_formula <- function(formula, data, wanted = "both") { data_matrix_formula <- model.frame(formula, data, na.action = NULL) x <- data_matrix_formula[, 1] if (formula[[3]] == 1) { y <- 1 } else{ y <- data_matrix_formula[, 2] x_values <- x[y == levels(y)[1]] y_values <- x[y == levels(y)[2]] x <- x_values y <- y_values } if (wanted == "x") { x } else if (wanted == "y") { y } else { list(x, y) } }
plot.pred.density <- function (x, predict_index = NULL, addons = "eslz", realized.y = NULL, addons.lwd = 1.5, ...) { if (!is(x, "pred.density")) stop("x must be of class 'pred.density'!") x$plot(predict_index, realized.y = realized.y, addons = addons, addons.lwd = addons.lwd, ...) }
sample_wav <- torchaudio:::audiofile_read_wav(system.file("ARCTIC/cmu_us_aew_arctic/wav/arctic_a0001.wav", package = "torchaudio")) test_that("audiofile_loader", { audiofile_obj <- audiofile_loader(system.file("ARCTIC/cmu_us_aew_arctic/wav/arctic_a0001.wav", package = "torchaudio")) expect_equal(class(audiofile_obj)[1], "audiofile") waveform_and_sample_rate <- transform_to_tensor(audiofile_obj) expect_equal(waveform_and_sample_rate[[2]], sample_wav$sample_rate) expect_tensor(waveform_and_sample_rate[[1]]) expect_equal(length(waveform_and_sample_rate[[1]]), length(sample_wav$waveform[[1]])) expect_equal(dim(waveform_and_sample_rate[[1]]), c(1, length(sample_wav$waveform[[1]]))) })
req_suggested_packages <- c("rtdists", "microbenchmark", "reshape2", "ggplot2", "ggforce") pcheck <- lapply(req_suggested_packages, requireNamespace, quietly = TRUE) if (any(!unlist(pcheck))) { message("Required package(s) for this vignette are not available/installed and code will not be executed.") knitr::opts_chunk$set(eval = FALSE) } knitr::opts_chunk$set( collapse = TRUE, error = TRUE, comment = " ) RT <- seq(0.1, 2, by = 0.1) A <- seq(0.5, 3.5, by = 0.5) V <- c(-5, -2, 0, 2, 5) t0 <- 0 W <- seq(0.3, 0.7, by = 0.1) SV <- c(0, 1, 2, 3.5) err_tol <- 1e-6 library("fddm") source(system.file("extdata", "Blurton_et_al_distribution.R", package = "fddm", mustWork = TRUE)) library("rtdists") library("microbenchmark") library("reshape2") library("ggplot2") library("ggforce") rt_benchmark_vec <- function(RT, resp, V, A, t0 = 1e-4, W = 0.5, SV = 0.0, err_tol = 1e-6, times = 1000) { fnames <- c("Mills", "NCDF", "Blurton", "rtdists") nf <- length(fnames) nV <- length(V) nA <- length(A) nW <- length(W) nSV <- length(SV) resp <- rep(resp, length(RT)) mbm_res <- data.frame(matrix(ncol = 4+nf, nrow = nV*nA*nW*nSV)) colnames(mbm_res) <- c('V', 'A', 'W', 'SV', fnames) row_idx <- 1 for (v in 1:nV) { for (a in 1:nA) { for (w in 1:nW) { for (sv in 1:nSV) { mbm <- microbenchmark( Mills = pfddm(rt = RT, response = resp, a = A[a], v = V[v], t0 = t0, w = W[w], sv = SV[sv], log = FALSE, method = "Mills", err_tol = err_tol), NCDF = pfddm(rt = RT, response = resp, a = A[a], v = V[v], t0 = t0, w = W[w], sv = SV[sv], log = FALSE, method = "NCDF", err_tol = err_tol), Blurton = G_0(t = RT-t0, a = A[a], nu = V[v], w = W[w], eta2 = SV[sv]*SV[sv], sigma2 = 1, eps = err_tol), rtdists = pdiffusion(RT, resp, a = A[a], v = V[v], t0 = t0, z = W[w]*A[a], sv = SV[sv], precision = 3), times = times) mbm_res[row_idx, 1] <- V[v] mbm_res[row_idx, 2] <- A[a] mbm_res[row_idx, 3] <- W[w] mbm_res[row_idx, 4] <- SV[sv] for (i in 1:nf) { mbm_res[row_idx, 4+i] <- median(mbm[mbm[,1] == fnames[i],2]) } row_idx = row_idx + 1 } } } } return(mbm_res) } load(system.file("extdata", "pfddm_distribution", "bm_vec_0-2.Rds", package = "fddm", mustWork = TRUE)) t_idx <- match("SV", colnames(bm_vec)) bm_vec[, -seq_len(t_idx)] <- bm_vec[, -seq_len(t_idx)]/1000 mbm_vec <- melt(bm_vec, measure.vars = -seq_len(t_idx), variable.name = "FuncName", value.name = "time") Names_vec <- c("Mills", "NCDF", "Blurton", "rtdists") Color_vec <- c(" Outline_vec <- c(" mi <- min(bm_vec[, (t_idx+1):(ncol(bm_vec)-2)]) ma <- max(bm_vec[, (t_idx+1):(ncol(bm_vec)-2)]) ggplot(mbm_vec, aes(x = factor(FuncName, levels = Names_vec), y = time, color = factor(FuncName, levels = Names_vec), fill = factor(FuncName, levels = Names_vec))) + geom_violin(trim = TRUE, alpha = 0.5) + scale_color_manual(values = Outline_vec, guide = FALSE) + scale_fill_manual(values = Color_vec, guide = FALSE) + geom_boxplot(width = 0.15, fill = "white", alpha = 0.5) + stat_summary(fun = mean, geom = "errorbar", aes(ymax = ..y.., ymin = ..y..), width = .35, linetype = "dashed") + scale_x_discrete(labels = c( bquote(F[s] ~ Mills), bquote(F[s] ~ NCDF), "Blurton (Mills)", "rtdists")) + facet_zoom(ylim = c(mi, ma)) + labs(x = "Implementation", y = "Time (microseconds)") + theme_bw() + theme(panel.border = element_blank(), axis.text.x = element_text(size = 16, angle = 90, vjust = 0.5, hjust = 1), axis.text.y = element_text(size = 16), axis.title.x = element_text(size = 20, margin = margin(10, 0, 0, 0)), axis.title.y = element_text(size = 20, margin = margin(0, 10, 0, 0)), legend.position = "none") rt_benchmark_ind <- function(RT, resp, V, A, t0 = 1e-4, W = 0.5, SV = 0.0, err_tol = 1e-6, times = 100) { fnames <- c("Mills", "NCDF", "Blurton", "rtdists") nf <- length(fnames) nRT <- length(RT) nV <- length(V) nA <- length(A) nW <- length(W) nSV <- length(SV) mbm_res <- data.frame(matrix(ncol = 5+nf, nrow = nRT*nV*nA*nW*nSV)) colnames(mbm_res) <- c('RT', 'V', 'A', 'W', 'SV', fnames) row_idx <- 1 for (rt in 1:nRT) { for (v in 1:nV) { for (a in 1:nA) { for (w in 1:nW) { for (sv in 1:nSV) { mbm <- microbenchmark( Mills = pfddm(rt = RT[rt], response = resp, a = A[a], v = V[v], t0 = t0, w = W[w], sv = SV[sv], log = FALSE, method = "Mills", err_tol = err_tol), NCDF = pfddm(rt = RT[rt], response = resp, a = A[a], v = V[v], t0 = t0, w = W[w], sv = SV[sv], log = FALSE, method = "NCDF", err_tol = err_tol), Blurton = G_0(t = RT[rt]-t0, a = A[a], nu = V[v], w = W[w], eta2 = SV[sv]*SV[sv], sigma2 = 1, eps = err_tol), rtdists = pdiffusion(RT[rt], resp, a = A[a], v = V[v], t0 = t0, z = W[w]*A[a], sv = SV[sv], precision = 3), times = times) mbm_res[row_idx, 1] <- RT[rt] mbm_res[row_idx, 2] <- V[v] mbm_res[row_idx, 3] <- A[a] mbm_res[row_idx, 4] <- W[w] mbm_res[row_idx, 5] <- SV[sv] for (i in 1:nf) { mbm_res[row_idx, 5+i] <- median(mbm[mbm[,1] == fnames[i],2]) } row_idx = row_idx + 1 } } } } } return(mbm_res) } load(system.file("extdata", "pfddm_distribution", "bm_ind_0-2.Rds", package = "fddm", mustWork = TRUE)) t_idx <- match("SV", colnames(bm_ind)) bm_ind[,-seq_len(t_idx)] <- bm_ind[, -seq_len(t_idx)]/1000 mbm_ind <- melt(bm_ind, measure.vars = -seq_len(t_idx), variable.name = "FuncName", value.name = "time") Names_meq <- c("Mills", "NCDF", "Blurton", "rtdists") Color_meq <- c(" my_labeller <- as_labeller(c(Mills = "F[s] ~ Mills", NCDF = "F[s] ~ NCDF", fl_Nav_09 = "f[l] ~ Nav", Blurton = "Blurton (Mills)", rtdists = "rtdists"), default = label_parsed) ggplot(mbm_ind, aes(x = RT, y = time, color = factor(FuncName, levels = Names_meq), fill = factor(FuncName, levels = Names_meq))) + stat_summary(fun.min = min, fun.max = max, geom = "ribbon", color = NA, alpha = 0.1) + stat_summary(fun.min = function(z) { quantile(z, 0.1) }, fun.max = function(z) { quantile(z, 0.9) }, geom = "ribbon", color = NA, alpha = 0.2) + stat_summary(fun = mean, geom = "line") + scale_x_log10(breaks = c(0.1, 0.25, 0.5, 1, 2), labels = as.character(c(0.1, 0.25, 0.5, 1, 2))) + scale_color_manual(values = Color_meq) + scale_fill_manual(values = Color_meq) + labs(subtitle = paste( "The darker shaded regions represent the 10% and 90% quantiles", "The lighter shaded regions represent the min and max times", sep = ";\n"), x = bquote(t ~ ", response time"), y = "Time (microseconds)") + theme_bw() + theme(panel.grid.minor = element_blank(), panel.border = element_blank(), plot.subtitle = element_text(size = 16, margin = margin(0, 0, 15, 0)), axis.text.x = element_text(size = 16, angle = 90, vjust = 0.5, hjust = 1), axis.text.y = element_text(size = 16), axis.title.x = element_text(size = 20, margin = margin(10, 0, 0, 0)), axis.title.y = element_text(size = 20, margin = margin(0, 10, 0, 0)), strip.text = element_text(size = 16), strip.background = element_rect(fill = "white"), legend.position = "none") + facet_wrap(~ factor(FuncName, levels = Names_meq), scales = "free_y", labeller = my_labeller) sessionInfo()
pCart <- function (L) { pCartAB <- function (v1, v2) { v12<-list(); p12<-0; for (i in 1:length(v1) ) { for (j in 1:length(v2) ){ p12<-p12+1; if (typeof(v1[[i]])=="list") { v12[[p12]]<-list(); for (k in 1:length(v1[[i]])) v12[[p12]][k] <- v1[[i]][k]; v12[[p12]][k+1] <- v2[j] ; } else { v12[[p12]] <- c( c(v1[i]), c(v2[j]) ); } }} return(v12); } vL<-list(); pL<-0; if (length(L)==1) return(L); vL<-pCartAB(L[[1]],L[[2]]); if (length(L) < 3) return(vL); for (i in 3:length(L) ) { vL<-pCartAB(vL, L[[i]]); } return(vL); }
designTwophaseAnatomies <- function(formulae, data, which.designs = "all", printAnatomies = TRUE, titles, orthogonalize = "hybrid", marginality = NULL, which.criteria = c("aefficiency", "eefficiency", "order"), ...) { ntiers <- length(formulae) if (ntiers != 3 || !all(unlist(lapply(formulae, plyr::is.formula)))) stop("must supply a list with three formulas") if (length(orthogonalize) == 1) orthogonalize <- rep(orthogonalize, ntiers) else if (length(orthogonalize) != ntiers) { warning("Length of orthogonalize is not equal to 1 or the number of formulae - only using first value") orthogonalize <- rep(orthogonalize[1], ntiers) } anat.titls <- c("Anatomy for the full two-phase design", "Anatomy for the first-phase design", "Anatomy for the cross-phase, treatments design", "Anatomy for the combined-units design") if (!missing(titles)) { if (length(titles) != 4 | !is.character(titles)) stop("titles must be a character of length fours") anat.titls <- mapply(FUN = function(titl, anat.titl) { if (is.na(titl)) titl <- anat.titl invisible(titl) }, titles, anat.titls, USE.NAMES = FALSE) } designs <- c("two-phase", "first-phase", "cross-phase", "combined-units") options <- c(designs, "all") kdesigns <- options[unlist(lapply(which.designs, check.arg.values, options=options))] if ("all" %in% which.designs) kdesigns <- designs if (!is.null(marginality)) { if (!is.list(marginality)) stop("marginality must be a list") if (!all(unlist(lapply(marginality, inherits, what="matrix")) || unlist(lapply(marginality, is.null)))) stop("marginality must contain a list of matrices or NULL components") if (length(marginality) != ntiers) if (is.null(names(marginality)) | is.null(names(formulae))) { stop(paste("if the marginality list is not the same length as the formulae list, ", "these two lists must be named", sep = "")) } else { tmp <- vector(mode = "list", length = ntiers) names(tmp) <- names(formulae) for (f in names(formulae)) tmp[f] <- marginality[f] marginality <- tmp } } twoph.lay.canon <- twoph1.lay.canon <- ph12.lay.canon <- twoph2.lay.canon <- NULL if ("two-phase" %in% kdesigns) { twoph.lay.canon <- designAnatomy(formulae = formulae, data = data, orthogonalize = orthogonalize, marginality = marginality, which.criteria = which.criteria, ...) if (printAnatomies) { cat("\n print(summary(twoph.lay.canon, which.criteria = which.criteria)) } } if ("first-phase" %in% kdesigns) { twoph1.lay.canon <- designAnatomy(formulae = c(formulae[2], formulae[3]), data = data, orthogonalize = orthogonalize[c(2,3)], marginality = c(marginality[2],marginality[3]), which.criteria = which.criteria, ...) if (printAnatomies) { cat("\n print(summary(twoph1.lay.canon, which.criteria = which.criteria)) } } if ("cross-phase" %in% kdesigns) { ph12.lay.canon <- designAnatomy(formulae = c(formulae[1], formulae[3]), data = data, orthogonalize = orthogonalize[c(1,3)], marginality = c(marginality[1],marginality[3]), which.criteria = which.criteria, ...) if (printAnatomies) { cat("\n print(summary(ph12.lay.canon, which.criteria = which.criteria)) } } if ("combined-units" %in% kdesigns) { twoph2.lay.canon <- designAnatomy(formulae = c(formulae[1], formulae[2]), data = data, orthogonalize = orthogonalize[c(1,2)], marginality = c(marginality[1],marginality[2]), which.criteria = which.criteria, ...) if (printAnatomies) { cat("\n print(summary(twoph2.lay.canon, which.criteria = which.criteria)) } } anats <- list(twophase = twoph.lay.canon, first = twoph1.lay.canon, cross = ph12.lay.canon, units = twoph2.lay.canon) attr(anats, which = "titles") <- anat.titls invisible(anats) }
quoted_list <- function(x) { paste(shQuote(x, type = "csh"), collapse = ", ") } add_expr_after <- function(calls, add_after, expr, new_name = NULL) { if (!rlang::is_string(add_after) || !add_after %in% names(calls)) { stop(glue("`add_after=` must be one of {quoted_list(names(calls))}")) } index <- which(names(calls) == add_after) new_name <- new_name %||% "user_added" new_list <- list(expr) %>% set_names(new_name) append(calls, new_list, after = index) } gts_mapper <- function(x, context) { if (!rlang::is_function(x) && !rlang::is_formula(x)) { paste( "Expecting a function in argument `{context}`,\n", "e.g. `fun = function(x) style_pvalue(x, digits = 2)`, or\n", "`fun = ~style_pvalue(., digits = 2)`" ) %>% stringr::str_glue() %>% rlang::abort() } purrr::as_mapper(x) } type_check <- list( is_string = list(msg = "Expecting a string as the passed value.", fn = function(x) is_string(x)), is_character = list(msg = "Expecting a character as the passed value.", fn = function(x) is.character(x)), is_function = list(msg = "Expecting a function as the passed value.", fn = function(x) is.function(x)), is_function_or_string = list(msg = "Expecting a function or a string of a function name.", fn = function(x) is_string(x) || is.function(x)), is_string_or_na = list(msg = "Expecting a string or NA as the passed value.", fn = function(x) is_string(x) || is.na(x)), is_named = list(msg = "Expecting a named vector or list as the passed value.", fn = function(x) is_named(x)), digits = list(msg = "Expecting an integer, function, or a vector/list of intergers/functions as the passed value.", fn = function(x) rlang::is_integerish(x) || is.function(x) || purrr::every(x, ~rlang::is_integerish(.x) || is.function(.x))) )
test_that("repo_string_as_named_list() works", { expect_equal( repo_string_as_named_list('ropensci|https://ropensci.r-universe.dev|ddsjoberg|https://ddsjoberg.r-universe.dev'), list(ropensci = "https://ropensci.r-universe.dev", ddsjoberg = "https://ddsjoberg.r-universe.dev") ) expect_equal( repo_string_as_named_list(NULL), list() ) })
RW <- function(X) { if (!is.numeric((X)) && !is.logical((X))) { warning("Argument is not numeric or logical: returning NA") return(NA) } RW_Cpp(X); }
test_that("resp_condition_fun1 has expected output when age is out of range", { expect_equal(resp_condition_fun1(-1, 1, 1), "NA(b)") }) test_that("resp_condition_fun1 has expected output when COPD/Emphs is out of range", { expect_equal(resp_condition_fun1(40, 0, 1), 1) }) test_that("resp_condition_fun1 has expected output when Asthma is out of range", { expect_equal(resp_condition_fun1(40, 1, 0), 1) }) test_that("resp_condition_fun1 has expected output when age is NA", { expect_equal(resp_condition_fun1(NA, 1, 1), "NA(b)") }) test_that("resp_condition_fun1 has expected output when COPD/Emphs is NA", { expect_equal(resp_condition_fun1(40, NA, 1), 1) }) test_that("resp_condition_fun1 has expected output when Asthma is NA", { expect_equal(resp_condition_fun1(40, 1, NA), 1) }) test_that("resp_condition_fun1 has expected output when all arguments are NA", { expect_equal(resp_condition_fun1(NA, NA, NA), "NA(b)") }) test_that("resp_condition_fun1 has expected output when all arguments are in range", { expect_equal(resp_condition_fun1(40, 1, 1), 1) }) test_that("resp_condition_fun2 has expected output when age is out of range", { expect_equal(resp_condition_fun2(-1, 1, 1, 1, 1), "NA(b)") }) test_that("resp_condition_fun2 has expected output when emphysema is out of range", { expect_warning(out <- resp_condition_fun2(40, 3, 1, 1, 1)) expect_equal(out, 1) }) test_that("resp_condition_fun2 has expected output when COPD is out of range", { expect_warning(out <- resp_condition_fun2(40, 1, 3, 1, 1)) expect_equal(out, 1) }) test_that("resp_condition_fun2 has expected output when chronic bronchitis is out of range", { expect_warning(out <- resp_condition_fun2(40, 1, 1, 3, 1)) expect_equal(out, 1) }) test_that("resp_condition_fun2 has expected output when Age is out of range", { expect_warning(out <- resp_condition_fun2(40, 1, 3, 1, -1)) expect_equal(out, 1) }) test_that("resp_condition_fun2 has expected output when all parameters are in range", { expect_equal(resp_condition_fun2(40, 1, 1, 1, 1), 1) }) test_that("resp_condition_fun2 has expected output when COPD, bronchitis, and asthma are negative but emphysema is positive", { expect_equal(resp_condition_fun2(40, 1, 2, 2, 2), 1) }) test_that("resp_condition_fun2 has expected output when emphysema, bronchitis, and asthma are negative but COPD is positive", { expect_equal(resp_condition_fun2(40, 2, 1, 2, 2), 1) }) test_that("resp_condition_fun2 has expected output when emphysema, COPD, and asthma are negative but bronchitis is positive", { expect_equal(resp_condition_fun2(40, 2, 2, 1, 2), 1) }) test_that("resp_condition_fun2 has expected output when emphysema, COPD, and bronchitis are negative but asthma is positive", { expect_equal(resp_condition_fun2(40, 2, 2, 2, 1), 1) }) test_that("resp_condition_fun2 has expected output when all parameters are negative", { expect_equal(resp_condition_fun2(40, 2, 2, 2, 2), 3) }) test_that("resp_condition_fun2 has expected output when age is less than 35 and condition positive", { expect_equal(resp_condition_fun2(34, 1, 2, 2, 2), 2) }) test_that("resp_condition_fun3 has expected output when age is out of range", { expect_equal(resp_condition_fun3(-1, 1, 1, 1), "NA(b)") }) test_that("resp_condition_fun3 has expected output when COPD/Emphys is out of range", { expect_warning(out <- resp_condition_fun3(35, 4, 1, 1)) expect_equal(out, 1) }) test_that("resp_condition_fun3 has expected output when bronchitis is out of range", { expect_warning(out <- resp_condition_fun3(35, 1, 4, 1)) expect_equal(out, 1) }) test_that("resp_condition_fun3 has expected output when age is out of range", { expect_warning(out <- resp_condition_fun3(35, 1, 1, 4)) expect_equal(out, 1) }) test_that("resp_condition_fun3 has expected output when all parameters are in range", { expect_equal(resp_condition_fun3(35, 1, 1, 1), 1) }) test_that("resp_condition_fun3 has expected output when COPD/Emphys & asthma are negative but bronchitis is positive", { expect_equal(resp_condition_fun3(40, 2, 1, 2), 1) }) test_that("resp_condition_fun3 has expected output when bronchitis & asthma are negative but COPD/Emphys is positive", { expect_equal(resp_condition_fun3(40, 1, 2, 2), 1) }) test_that("resp_condition_fun3 has expected output when bronchitis & COPD/Emphys are negative but asthma is positive", { expect_equal(resp_condition_fun3(40, 2, 2, 1), 1) }) test_that("resp_condition_fun3 has expected output when all parameters are negative", { expect_equal(resp_condition_fun3(40, 2, 2, 2), 3) }) test_that("resp_condition_fun3 has expected output when age is less than 35 and condition positive", { expect_equal(resp_condition_fun3(34, 1, 2, 1), 2) }) test_that("COPD_Emph_der_fun1 has expected output when age is out of range", { expect_equal(COPD_Emph_der_fun1(-1, 1, 1), "NA(b)") }) test_that("COPD_Emph_der_fun1 has expected output when CCC_91E is out of range", { expect_warning(out <- COPD_Emph_der_fun1(20, -1, 1)) expect_equal(out, 2) }) test_that("COPD_Emph_der_fun1 has expected output when CCC_91F is out of range", { expect_warning(out <- COPD_Emph_der_fun1(20, 1, -1)) expect_equal(out, 2) }) test_that("COPD_Emph_der_fun1 has expected output when all parameters are in range", { expect_equal(COPD_Emph_der_fun1(20, 1, 1), 2) }) test_that("COPD_Emph_der_fun2 has expected output when age is out of range", { expect_equal(COPD_Emph_der_fun2(-1, 1), "NA(b)") }) test_that("COPD_Emph_der_fun2 has expected output when CCC_91E is out of range", { expect_equal(COPD_Emph_der_fun2(20, -1), "NA(b)") }) test_that("COPD_Emph_der_fun2 has expected output when all parameters are in range", { expect_equal(COPD_Emph_der_fun2(20, 1), 2) })
if (Sys.getenv("RunAllRcppTests") != "yes") exit_file("Set 'RunAllRcppTests' to 'yes' to run.") Rcpp::sourceCpp("cpp/rcppversion.cpp") pv <- packageVersion("Rcpp") pvstr <- as.character(pv) v <- as.integer(unlist(strsplit(pvstr, "\\."))) relstr <- as.character(as.package_version(paste(v[1:3], collapse="."))) res <- checkVersion(v) expect_equal(res$cur_ver, res$def_ver, info="current computed version equal defined version") expect_equal(relstr, res$def_str, info="current computed version equal defined dev string") if (length(v) >= 4) { expect_equal(res$cur_dev_ver, res$def_dev_ver, info="current computed dev version greater equal defined dev version") } if (length(v) <= 4) { expect_equal(pvstr, res$def_dev_str, info="current computed version equal defined dev string") }
NULL is.wholenumber <- function(x, tol = .Machine$double.eps^0.5) { (length(x)==1) && (abs(x - round(x)) < tol) } is.pos_wholenumber <- function(x, tol = .Machine$double.eps^0.5) { is.wholenumber(x) && (x>0) } scaled_binomial_difference_table <- function(nA, multA, nB, multB, probi) { if(!is.pos_wholenumber(nA)) { stop("sigr::scaled_binomial_difference_table nA must be a positive integer") } if(!is.pos_wholenumber(multA)) { stop("sigr::scaled_binomial_difference_table multA must be a positive integer") } if(!is.pos_wholenumber(nB)) { stop("sigr::scaled_binomial_difference_table nB must be a positive integer") } if(!is.pos_wholenumber(multB)) { stop("sigr::scaled_binomial_difference_table multB must be a positive integer") } if((probi<0)||(probi>1)) { stop("sigr::scaled_binomial_difference_table probi must in the interval [0,1]") } if(abs(nA*multA - nB*multB)>1.e-3) { stop("scaled_binomial_difference_table: (nA*multA - nB*multB) must be zero") } vA <- dbinom(0:nA, prob = probi, size = nA) if(multA>1) { pad <- numeric(multA-1) vA <- unlist(lapply(vA, function(vi) c(vi, pad)))[1:(nA*multA+1)] } if(length(vA)!=(nA*multA+1)) { stop("sigr::scaled_binomial_difference_table bad vA length") } vB <- dbinom(0:nB, prob = probi, size = nB) if(multB>1) { pad <- numeric(multB-1) vB <- unlist(lapply(vB, function(vi) c(vi, pad)))[1:(nB*multB+1)] } if(length(vB)!=(nB*multB+1)) { stop("sigr::scaled_binomial_difference_table bad vA length") } probs <- convolve(vA, vB, type = "open") probs <- pmax(probs, 0) probs <- probs/sum(probs) d <- data.frame( diff = (-nA*multA):(nA*multA), prob = probs) d$prob_le <- cumsum(d$prob) d$prob_lt <- d$prob_le - d$prob d$prob_ge <- rev(cumsum(rev(d$prob))) d$prob_gt <- d$prob_ge - d$prob d } calc_probs <- function(d, nA, multA, nB, multB, test_rate_difference) { if(!is.pos_wholenumber(nA)) { stop("sigr::scaled_binomial_difference_table nA must be a positive integer") } if(!is.pos_wholenumber(multA)) { stop("sigr::scaled_binomial_difference_table multA must be a positive integer") } if(!is.pos_wholenumber(nB)) { stop("sigr::scaled_binomial_difference_table nB must be a positive integer") } if(!is.pos_wholenumber(multB)) { stop("sigr::scaled_binomial_difference_table multB must be a positive integer") } if((test_rate_difference<0)||(test_rate_difference>1)) { stop("sigr::scaled_binomial_difference_table test_rate_difference must in the interval [0,1]") } if(abs(nA*multA - nB*multB)>1.e-3) { stop("scaled_binomial_difference_table: (nA*multA - nB*multB) must be zero") } en <- round(max(nA, nB)*test_rate_difference, digits = 7) i1 <- match(ceiling(-en), d$diff) if(is.na(i1)) { i1 <- 1 } else { if((i1>1)&&(d$diff[[i1]] > (-en))) { i1 <- i1 - 1 } } i2 <- match(floor(en), d$diff) if(is.na(i2)) { i2 <- nrow(d) } else { if((i2<nrow(d))&&(d$diff[[i2]]<en)) { i2 <- i2 + 1 } } test_sig <- d$prob_le[[i1]] + d$prob_ge[[i2]] test_sig }
NULL personalizeevents <- function(config = list()) { svc <- .personalizeevents$operations svc <- set_config(svc, config) return(svc) } .personalizeevents <- list() .personalizeevents$operations <- list() .personalizeevents$metadata <- list( service_name = "personalizeevents", endpoints = list("*" = list(endpoint = "personalize-events.{region}.amazonaws.com", global = FALSE), "cn-*" = list(endpoint = "personalize-events.{region}.amazonaws.com.cn", global = FALSE), "us-iso-*" = list(endpoint = "personalize-events.{region}.c2s.ic.gov", global = FALSE), "us-isob-*" = list(endpoint = "personalize-events.{region}.sc2s.sgov.gov", global = FALSE)), service_id = "Personalize Events", api_version = "2018-03-22", signing_name = "personalize", json_version = "1.1", target_prefix = "" ) .personalizeevents$service <- function(config = list()) { handlers <- new_handlers("restjson", "v4") new_service(.personalizeevents$metadata, handlers, config) }
step_tf <- function(recipe, ..., role = "predictor", trained = FALSE, columns = NULL, weight_scheme = "raw count", weight = 0.5, vocabulary = NULL, res = NULL, prefix = "tf", skip = FALSE, id = rand_id("tf")) { if (!(weight_scheme %in% tf_funs) | length(weight_scheme) != 1) { rlang::abort(paste0( "`weight_scheme` should be one of: ", "'", tf_funs, "'", collapse = ", " )) } add_step( recipe, step_tf_new( terms = enquos(...), role = role, trained = trained, res = res, columns = columns, weight_scheme = weight_scheme, weight = weight, vocabulary = vocabulary, prefix = prefix, skip = skip, id = id ) ) } tf_funs <- c( "binary", "raw count", "term frequency", "log normalization", "double normalization" ) step_tf_new <- function(terms, role, trained, columns, weight_scheme, weight, vocabulary, res, prefix, skip, id) { step( subclass = "tf", terms = terms, role = role, trained = trained, columns = columns, weight_scheme = weight_scheme, weight = weight, vocabulary = vocabulary, res = res, prefix = prefix, skip = skip, id = id ) } prep.step_tf <- function(x, training, info = NULL, ...) { col_names <- recipes_eval_select(x$terms, training, info) check_list(training[, col_names]) token_list <- list() for (i in seq_along(col_names)) { token_list[[i]] <- x$vocabulary %||% sort(get_unique_tokens(training[, col_names[i], drop = TRUE])) } step_tf_new( terms = x$terms, role = x$role, trained = TRUE, columns = col_names, weight_scheme = x$weight_scheme, weight = x$weight, vocabulary = x$vocabulary, res = token_list, prefix = x$prefix, skip = x$skip, id = x$id ) } bake.step_tf <- function(object, new_data, ...) { col_names <- object$columns for (i in seq_along(col_names)) { tf_text <- tf_function( new_data[, col_names[i], drop = TRUE], object$res[[i]], paste0(object$prefix, "_", col_names[i]), object$weight_scheme, object$weight ) new_data <- new_data[, !(colnames(new_data) %in% col_names[i]), drop = FALSE] new_data <- vctrs::vec_cbind(new_data, tf_text) } as_tibble(new_data) } print.step_tf <- function(x, width = max(20, options()$width - 30), ...) { cat("Term frequency with ", sep = "") printer(x$columns, x$terms, x$trained, width = width) invisible(x) } tidy.step_tf <- function(x, ...) { if (is_trained(x)) { res <- tibble( terms = unname(x$columns), value = x$weight_scheme ) } else { term_names <- sel2char(x$terms) res <- tibble( terms = term_names, value = na_chr ) } res$id <- x$id res } tf_function <- function(data, names, labels, weights, weight) { counts <- as.matrix(tokenlist_to_dtm(data, names)) tf <- tf_weight(counts, weights, weight) colnames(tf) <- paste0(labels, "_", names) as_tibble(tf) } tf_weight <- function(x, scheme, weight) { if (scheme == "binary") { return(x > 0) } if (scheme == "raw count") { return(x) } if (scheme == "term frequency") { rowsums_x <- rowSums(x) res <- x / rowsums_x res[rowsums_x == 0, ] <- 0 return(res) } if (scheme == "log normalization") { return(log(1 + x)) } if (scheme == "double normalization") { max_ftd <- apply(x, 1, max) return(weight + weight * x / max_ftd) } } required_pkgs.step_tf <- function(x, ...) { c("textrecipes") } tunable.step_tf <- function(x, ...) { tibble::tibble( name = c("weight_scheme", "num_terms"), call_info = list( list(pkg = "dials", fun = "weight_scheme"), list(pkg = "dials", fun = "weight") ), source = "recipe", component = "step_tf", component_id = x$id ) }
ral_vector <- function(..., .data = NULL, .subclass = NULL, .meta = NULL) { val <- if (is.null(.data)) { list(...) } else { stopifnot(is.list(`.data`)) `.data` } class(val) <- c(.subclass, "ral_vector") ral_meta_data <- if (!is.null(.meta) && inherits(.meta, "ral_map")) { .meta } new_vctr(val, ral_meta_data = ral_meta_data, class = class(val), inherit_base_type = TRUE) } set_meta_data.ral_vector <- function(x, val, envir = NULL) { attr(x, "ral_meta_data") <- val x } meta_data.ral_vector <- function(x) { attr(x, "ral_meta_data", exact = TRUE) } format.ral_vector <- function(x, ...) { paste0( "[", paste0(vapply(x, function(x) llr_format(x), character(1)), collapse = " "), "]" ) } print.ral_vector <- default_print vec_ptype2.ral_vector.list <- function(x, y, ...) { ral_vector() } vec_ptype2.list.ral_vector <- function(x, y, ...) { ral_vector() } vec_cast.character.llr_boolean <- function(x, to, ...) { format(x) }
NULL .efetch <- setRefClass( Class = "efetch", contains = "eutil", methods = list( initialize = function(method, ...) { callSuper() perform_query("efetch", method = method, ...) if (errors$all_empty() && retmode() == "xml") { errors$check_errors(.self) } }, show = function() { cat("Object of class", sQuote(eutil()), "\n") nhead <- getOption("reutils.show.headlines") if (no_errors()) { if (retmode() == "xml") { methods::show(get_content("xml")) } else { con <- get_content("textConnection") on.exit(close(con)) headlines <- readLines(con, n = nhead %||% -1L) cat(headlines, "...", sep="\n") } } else { methods::show(get_error()) } tail <- sprintf("EFetch query using the %s database.\nQuery url: %s\nRetrieval type: %s, retrieval mode: %s\n", sQuote(database()), sQuote(ellipsize(get_url(), offset=15)), sQuote(rettype()), sQuote(retmode())) cat(tail, sep="\n") } ) ) setMethod("content", "efetch", function(x, as = NULL) { as <- as %||% retmode(x) if (as == "asn.1") { as <- "text" } if (as == "parsed") { as <- retmode(x) } callNextMethod(x = x, as = as) }) efetch <- function(uid, db = NULL, rettype = NULL, retmode = NULL, outfile = NULL, retstart = NULL, retmax = NULL, querykey = NULL, webenv = NULL, strand = NULL, seqstart = NULL, seqstop = NULL, complexity = NULL) { params <- parse_params(uid, db, querykey, webenv) r <- ncbi_retrieval_type(params$db, rettype %||% "", retmode) if (is.null(retmax)) { retmax <- Inf } if (retmax > 500 && (is.finite(params$count) && (params$count > 500))) { if (is.null(outfile)) { stop("You are attempting to download more than 500 records.\n", " efetch() will download them iteratively in batches.\n", " Specify an 'outfile' where they can be saved to.", call. = FALSE) } if (is.na(webenv(uid))) { stop("You are attempting to download more than 500 records.\n", " Use the NCBI history server to store the UIDs and\n", " specify an 'outfile' where the data can be saved to.", call. = FALSE) } retstart <- 0 retmax <- 500 out <- file(outfile, open = "w+") on.exit(close(out)) while (retstart < params$count) { message("Retrieving UIDs ", retstart + 1, " to ", retstart + retmax) ans <- .efetch("GET", db = params$db, id = NULL, query_key = params$querykey, WebEnv = params$webenv, retmode = r$retmode, rettype = r$rettype, retstart = retstart, retmax = retmax, strand = strand, seq_start = seqstart, seq_stop = seqstop, complexity = complexity) writeLines(ans$get_content("text"), con = out) retstart <- retstart + retmax Sys.sleep(0.33) } invisible(outfile) } else { if (!is.null(outfile)) { out <- file(outfile, open = "wt") on.exit(close(out)) ans <- .efetch(method = if (length(params$uid) < 100) "GET" else "POST", db = params$db, id = .collapse(params$uid), query_key = params$querykey, WebEnv = params$webenv, retmode = r$retmode, rettype = r$rettype, retstart = retstart, retmax = retmax, strand = strand, seq_start = seqstart, seq_stop = seqstop, complexity = complexity) writeLines(ans$get_content("text"), con = out) invisible(outfile) } else { .efetch(method = if (length(params$uid) < 100) "GET" else "POST", db = params$db, id = .collapse(params$uid), query_key = params$querykey, WebEnv = params$webenv, retmode = r$retmode, rettype = r$rettype, retstart = retstart, retmax = retmax, strand = strand, seq_start = seqstart, seq_stop = seqstop, complexity = complexity) } } } setMethod("[", c(x = "efetch", i = "character", j = "missing"), function(x, i, j) { if (retmode(x) != "xml") { stop("This document does not contain XML data", call.=FALSE) } x$xmlSet(i) }) setMethod("[[", c(x = "efetch", i = "character"), function(x, i) { ans <- x[i] if (length(ans) > 1) { warning(length(ans), " elements in node set. Returning just the first!") } ans[[1]] })
get_district_counts <- function( path = "https://api.covid19india.org/csv/latest/districts.csv", raw = FALSE ) { d <- data.table::fread(path, showProgress = FALSE) if (raw == FALSE) { setnames(d, names(d), janitor::make_clean_names(names(d))) setnames(d, c("confirmed", "recovered", "deceased"), c("total_cases", "total_recovered", "total_deaths")) d <- data.table::melt(d[, !c("other")], id.vars = c("date", "state", "district"))[value >= 0] d <- data.table::dcast.data.table(d, date + state + district ~ variable)[order(date)][ , `:=` ( daily_cases = total_cases - data.table::shift(total_cases), daily_recovered = total_recovered - data.table::shift(total_recovered), daily_deaths = total_deaths - data.table::shift(total_deaths) ), by = c("state", "district") ][!is.na(daily_cases) & !is.na(daily_recovered) & !is.na(daily_deaths)][ , date := as.Date(date) ][ , .(state, district, date, daily_cases, daily_recovered, daily_deaths, total_cases, total_recovered, total_deaths) ] d <- na.omit(d, c("daily_cases", "daily_recovered", "daily_deaths")) setkeyv(d, cols = c("state", "district", "date")) } return(d) }
mice.impute.passive <- function(data, func) { model.frame(func, data) }
cor.folder <- function(x, use = "everything", method = "pearson") { if (!is.folder(x)) stop("x must be an object of class 'folder'.") fold <- x x <- fold[[1]] jnum <- logical(ncol(x)) for (j in 1:ncol(x)) { jnum[j] <- is.numeric(x[, j]) } notnum <- colnames(x)[!jnum] if (length(notnum) > 0) warning(paste("There are omitted variables (non numeric): ", paste(notnum, collapse = " "), sep = ""), immediate. = TRUE) fold.num <- vector("list", length(fold)) for (n in 1:length(fold.num)) fold.num[[n]] <- fold[[n]][jnum] names(fold.num) <- names(fold) return(lapply(fold.num, cor, use = use, method = method)) }
context("Unit tests for parameter passing for PLIV, partial_z") lgr::get_logger("mlr3")$set_threshold("warn") skip_on_cran() test_cases = expand.grid( learner = "regr.rpart", dml_procedure = c("dml1", "dml2"), score = "partialling out", stringsAsFactors = FALSE) test_cases_nocf = expand.grid( learner = "regr.rpart", dml_procedure = "dml1", score = "partialling out", stringsAsFactors = FALSE) test_cases[".test_name"] = apply(test_cases, 1, paste, collapse = "_") test_cases_nocf[".test_name"] = apply(test_cases_nocf, 1, paste, collapse = "_") patrick::with_parameters_test_that("Unit tests for parameter passing of PLIV.partialZ (oop vs fun):", .cases = test_cases, { n_rep_boot = 498 n_folds = 2 n_rep = 3 learner_pars = get_default_mlmethod_pliv(learner) df = data_pliv$df set.seed(3141) pliv_hat = dml_pliv_partial_z(df, y = "y", d = "d", z = c("z", "z2"), n_folds = n_folds, n_rep = n_rep, ml_r = mlr3::lrn(learner_pars$mlmethod$mlmethod_r), params_r = learner_pars$params$params_r, dml_procedure = dml_procedure, score = score) theta = pliv_hat$coef se = pliv_hat$se boot_theta = bootstrap_pliv_partial_z(pliv_hat$thetas, pliv_hat$ses, df, y = "y", d = "d", z = c("z", "z2"), n_folds = n_folds, n_rep = n_rep, smpls = pliv_hat$smpls, all_preds = pliv_hat$all_preds, bootstrap = "normal", n_rep_boot = n_rep_boot)$boot_coef set.seed(3141) Xnames = names(df)[names(df) %in% c("y", "d", "z", "z2") == FALSE] dml_data = double_ml_data_from_data_frame(df, y_col = "y", d_cols = "d", x_cols = Xnames, z_cols = c("z", "z2")) dml_pliv_obj = DoubleMLPLIV.partialZ( data = dml_data, n_folds = n_folds, n_rep = n_rep, ml_r = mlr3::lrn(learner_pars$mlmethod$mlmethod_r), dml_procedure = dml_procedure, score = score) dml_pliv_obj$set_ml_nuisance_params( treat_var = "d", learner = "ml_r", params = learner_pars$params$params_r) dml_pliv_obj$fit() theta_obj = dml_pliv_obj$coef se_obj = dml_pliv_obj$se dml_pliv_obj$bootstrap(method = "normal", n_rep = n_rep_boot) boot_theta_obj = dml_pliv_obj$boot_coef expect_equal(theta, theta_obj, tolerance = 1e-8) expect_equal(se, se_obj, tolerance = 1e-8) expect_equal(as.vector(boot_theta), as.vector(boot_theta_obj), tolerance = 1e-8) } ) patrick::with_parameters_test_that("Unit tests for parameter passing of PLIV.partialZ (no cross-fitting)", .cases = test_cases_nocf, { n_folds = 2 learner_pars = get_default_mlmethod_pliv(learner) df = data_pliv$df set.seed(3141) my_task = Task$new("help task", "regr", data_pliv$df) my_sampling = rsmp("holdout", ratio = 0.5)$instantiate(my_task) train_ids = list(my_sampling$train_set(1)) test_ids = list(my_sampling$test_set(1)) smpls = list(list(train_ids = train_ids, test_ids = test_ids)) pliv_hat = dml_pliv_partial_z(df, y = "y", d = "d", z = c("z", "z2"), n_folds = 1, ml_r = mlr3::lrn(learner_pars$mlmethod$mlmethod_r), params_r = learner_pars$params$params_r, dml_procedure = dml_procedure, score = score, smpls = smpls) theta = pliv_hat$coef se = pliv_hat$se set.seed(3141) Xnames = names(df)[names(df) %in% c("y", "d", "z", "z2") == FALSE] dml_data = double_ml_data_from_data_frame(df, y_col = "y", d_cols = "d", x_cols = Xnames, z_cols = c("z", "z2")) dml_pliv_nocf = DoubleMLPLIV.partialZ( data = dml_data, n_folds = n_folds, ml_r = mlr3::lrn(learner_pars$mlmethod$mlmethod_r), dml_procedure = dml_procedure, score = score, apply_cross_fitting = FALSE) dml_pliv_nocf$set_ml_nuisance_params( treat_var = "d", learner = "ml_r", params = learner_pars$params$params_r) dml_pliv_nocf$fit() theta_obj = dml_pliv_nocf$coef se_obj = dml_pliv_nocf$se expect_equal(theta, theta_obj, tolerance = 1e-8) expect_equal(se, se_obj, tolerance = 1e-8) } ) patrick::with_parameters_test_that("Unit tests for parameter passing of PLIV.partialZ (fold-wise vs global)", .cases = test_cases, { n_folds = 2 n_rep = 3 learner_pars = get_default_mlmethod_pliv(learner) df = data_pliv$df Xnames = names(df)[names(df) %in% c("y", "d", "z", "z2") == FALSE] dml_data = double_ml_data_from_data_frame(df, y_col = "y", d_cols = "d", x_cols = Xnames, z_cols = c("z", "z2")) set.seed(3141) dml_pliv_obj = DoubleMLPLIV.partialZ(dml_data, n_folds = n_folds, n_rep = n_rep, ml_r = mlr3::lrn(learner_pars$mlmethod$mlmethod_r), dml_procedure = dml_procedure, score = score) dml_pliv_obj$set_ml_nuisance_params( treat_var = "d", learner = "ml_r", params = learner_pars$params$params_r) dml_pliv_obj$fit() theta = dml_pliv_obj$coef se = dml_pliv_obj$se params_r_fold_wise = rep(list(rep(list(learner_pars$params$params_r), n_folds)), n_rep) set.seed(3141) dml_pliv_obj_fold_wise = DoubleMLPLIV.partialZ(dml_data, n_folds = n_folds, n_rep = n_rep, ml_r = mlr3::lrn(learner_pars$mlmethod$mlmethod_r), dml_procedure = dml_procedure, score = score) dml_pliv_obj_fold_wise$set_ml_nuisance_params( treat_var = "d", learner = "ml_r", params = params_r_fold_wise, set_fold_specific = TRUE) dml_pliv_obj_fold_wise$fit() theta_fold_wise = dml_pliv_obj_fold_wise$coef se_fold_wise = dml_pliv_obj_fold_wise$se expect_equal(theta, theta_fold_wise, tolerance = 1e-8) expect_equal(se, se_fold_wise, tolerance = 1e-8) } ) patrick::with_parameters_test_that("Unit tests for parameter passing of PLIV.partialXZ (default vs explicit)", .cases = test_cases, { n_folds = 2 n_rep = 3 params_r = list(cp = 0.01, minsplit = 20) df = data_pliv$df Xnames = names(df)[names(df) %in% c("y", "d", "z", "z2") == FALSE] dml_data = double_ml_data_from_data_frame(df, y_col = "y", d_cols = "d", x_cols = Xnames, z_cols = c("z", "z2")) set.seed(3141) dml_pliv_default = DoubleMLPLIV.partialZ(dml_data, n_folds = n_folds, n_rep = n_rep, ml_r = lrn("regr.rpart"), dml_procedure = dml_procedure, score = score) dml_pliv_default$fit() theta_default = dml_pliv_default$coef se_default = dml_pliv_default$se set.seed(3141) dml_pliv_obj = DoubleMLPLIV.partialZ(dml_data, n_folds = n_folds, n_rep = n_rep, ml_r = lrn("regr.rpart"), dml_procedure = dml_procedure, score = score) dml_pliv_obj$set_ml_nuisance_params( treat_var = "d", learner = "ml_r", params = params_r) dml_pliv_obj$fit() theta = dml_pliv_obj$coef se = dml_pliv_obj$se expect_equal(theta, theta_default, tolerance = 1e-8) expect_equal(se, se_default, tolerance = 1e-8) } )
NULL ycfunc <- function(Q = NULL, d = NULL, g = NULL) { thetafull <- 2 * acos(1 - (2 * (0.99))) Qcfull <- sqrt(g * d^5 * ((thetafull - sin(thetafull))^3)/(8^3 * sin(thetafull/2.0))) if ( Q >= Qcfull ) { yc <- d } else { thetafun <- function(theta) {Q^2 / ( g * d^5 ) - ((theta - sin(theta))^3)/(8^3 * sin(theta/2.0))} theta <- uniroot(thetafun, interval = c(0.00001, 2*pi))$root yc <- (d / 2) * (1 - cos(theta / 2)) } return(yc) } Qfull <- function(d = NULL, Sf = NULL, n = NULL, k = NULL) { Vf <- (k / n) * ((d / 4.0) ^ (2.0/3.0)) * sqrt( Sf ) Qf <- Vf * (0.25 * pi * d^2) return(Qf) } units::units_options(allow_mixed = TRUE) return_fcn2 <- function(x = NULL, units = NULL, ret_units = FALSE) { if (units == "SI") { out_units <- c("m^3/s","m/s","m^2","m","m","m","m",1,1,"m",1,1,"m^3/s") } else { out_units <- c("ft^3/s","ft/s","ft^2","ft","ft","ft","ft",1,1,"ft",1,1,"ft^3/s") } if( ret_units ) { a <- units::mixed_units(unlist(x), out_units) x <- a } return(x) } manningc <- function (Q = NULL, n = NULL, Sf = NULL, y = NULL, d = NULL, y_d = NULL, units = c("SI", "Eng"), ret_units = FALSE ) { units <- units for( i in c("Q", "n", "Sf", "y", "d", "y_d") ) { v <- get(i) if(class(v) == "units" ) assign(i, units::drop_units(v)) } if(missing(y_d)) { if (length(c(Q, n, Sf, y, d)) != 4) { stop("There must be exactly one unknown variable among Q, n, Sf, y, d") } if (any(c(Q, n, Sf, y, d) <= 0)) { stop("Either Q, n, Sf, y, d is <= 0. All of these variables must be positive") } if ( ( ! missing(d) ) & ( ! missing(y) ) ) { if ( y > d ) stop("depth y cannot exceed diameter d.") } case <- 1 } else { if ( (length(c(Q, Sf, n)) != 3) & (! missing(d)) & (! missing(y)) ) { stop("d, y must be missing when given y_d.") } if (any(c(Q, Sf, n, y_d) <= 0)) { stop("Either Q, n, Sf, y_d is <= 0. All of these variables must be positive") } if ( y_d > 1.0 ) { stop("y_d cannot exceed 1.0") } case <- 2 } if (units == "SI") { g <- 9.80665 k <- 1.0 mu <- dvisc(T = 20, units = 'SI') rho <- dens(T = 20, units = 'SI') dmax <- 3.5 } else if (units == "Eng") { g <- 32.2 k <- 1.4859 mu <- dvisc(T = 68, units = 'Eng') rho <- dens(T = 68, units = 'Eng') dmax <- 12 } else if (all(c("SI", "Eng") %in% units == FALSE) == FALSE) { stop("Incorrect unit system. Must be SI or Eng") } if (case == 1) { if (missing(Q)) { Qf <- Qfull(d = d, Sf = Sf, n = n, k = k) theta <- 2 * acos(1 - (2 * (y / d))) A <- (theta - sin(theta)) * (d ^ 2 / 8) P <- ((theta * d) / 2) B <- d * sin(theta / 2) R <- A / P D <- A / B Qfun <- function(Q) {Q - ((((theta - sin(theta)) * (d ^ 2 / 8)) ^ (5 / 3) * sqrt(Sf)) * (k / n) / ((theta * d) / 2) ^ (2 / 3))} Quse <- uniroot(Qfun, interval = c(0.0000001, 200), extendInt = "yes") Q <- Quse$root V <- Q / A Re <- (rho * R * V) / mu if (Re < 2000) { message(sprintf("Low Reynolds number: %.0f indicates not rough turbulent, Manning eq. not valid\n",Re)) } Fr <- V / (sqrt(g * D)) yc <- ycfunc(Q = Q, d = d, g = g) out <- list(Q = Q, V = V, A = A, P = P, R = R, y = y, d = d, Sf = Sf, n = n, yc = yc, Fr = Fr, Re = Re, Qf = Qf) return(return_fcn2(x = out, units = units, ret_units = ret_units)) } else if (missing(n)) { theta <- 2 * acos(1 - (2 * (y / d))) A <- (theta - sin(theta)) * (d ^ 2 / 8) P <- ((theta * d) / 2) B <- d * sin(theta / 2) R <- A / P D <- A / B nfun <- function(n) {Q - ((((theta - sin(theta)) * (d ^ 2 / 8)) ^ (5 / 3) * sqrt(Sf)) * (k / n) / ((theta * d) / 2) ^ (2 / 3))} nuse <- uniroot(nfun, interval = c(0.0000001, 200), extendInt = "yes") n <- nuse$root Qf <- Qfull(d = d, Sf = Sf, n = n, k = k) V <- Q / A Re <- (rho * R * V) / mu if (Re < 2000) { message(sprintf("Low Reynolds number: %.0f indicates not rough turbulent, Manning eq. not valid\n",Re)) } Fr <- V / (sqrt(g * D)) yc <- ycfunc(Q = Q, d = d, g = g) out <- list(Q = Q, V = V, A = A, P = P, R = R, y = y, d = d, Sf = Sf, n = n, yc = yc, Fr = Fr, Re = Re, Qf = Qf) return(return_fcn2(x = out, units = units, ret_units = ret_units)) } else if (missing(Sf)) { theta <- 2 * acos(1 - (2 * (y / d))) A <- (theta - sin(theta)) * (d ^ 2 / 8) P <- ((theta * d) / 2) B <- d * sin(theta / 2) R <- A / P D <- A / B Sffun <- function(Sf) {Q - ((((theta - sin(theta)) * (d ^ 2 / 8)) ^ (5 / 3) * sqrt(Sf)) * (k / n) / ((theta * d) / 2) ^ (2 / 3))} Sfuse <- uniroot(Sffun, interval = c(0.0000001, 200), extendInt = "yes") Sf <- Sfuse$root Qf <- Qfull(d = d, Sf = Sf, n = n, k = k) V <- Q / A Re <- (rho * R * V) / mu if (Re < 2000) { message(sprintf("Low Reynolds number: %.0f indicates not rough turbulent, Manning eq. not valid\n",Re)) } Fr <- V / (sqrt(g * D)) yc <- ycfunc(Q = Q, d = d, g = g) out <- list(Q = Q, V = V, A = A, P = P, R = R, y = y, d = d, Sf = Sf, n = n, yc = yc, Fr = Fr, Re = Re, Qf = Qf) return(return_fcn2(x = out, units = units, ret_units = ret_units)) } else if (missing(y)) { Qf <- Qfull(d = d, Sf = Sf, n = n, k = k) if ( Q > Qf ) { stop("Flow Q exceeds full flow for the pipe.") } rh <- (n * Q) / (k * sqrt(Sf)) thetafun <- function (theta) ((theta - sin(theta)) * (d ^ 2 / 8)) * (((theta - sin(theta)) * (d ^ 2 / 8) / ((theta * d) / 2)) ^ (2 / 3)) - rh thetause <- uniroot(thetafun, c(-1000, 1000), extendInt = "yes") theta <- thetause$root y <- (d / 2) * (1 - cos(theta / 2)) A <- (theta - sin(theta)) * (d ^ 2 / 8) P <- ((theta * d) / 2) B <- d * sin(theta / 2) R <- A / P D <- A / B V <- Q / A Re <- (rho * R * V) / mu if (Re < 2000) { message(sprintf("Low Reynolds number: %.0f indicates not rough turbulent, Manning eq. not valid\n",Re)) } Fr <- V / (sqrt(g * D)) yc <- ycfunc(Q = Q, d = d, g = g) out <- list(Q = Q, V = V, A = A, P = P, R = R, y = y, d = d, Sf = Sf, n = n, yc = yc, Fr = Fr, Re = Re, Qf = Qf) return(return_fcn2(x = out, units = units, ret_units = ret_units)) } } if (case == 2) { theta <- 2 * acos(1 - (2 * (y_d))) rh <- (n * Q) / (k * sqrt(Sf)) dfun <- function (d) ((theta - sin(theta)) * (d ^ 2 / 8)) * (((theta - sin(theta)) * (d ^ 2 / 8) / ((theta * d) / 2)) ^ (2 / 3)) - rh duse <- uniroot(dfun, interval = c(0.001, dmax), extendInt = "yes") d <- duse$root Qf <- Qfull(d = d, Sf = Sf, n = n, k = k) y <- y_d * d A <- (theta - sin(theta)) * (d ^ 2 / 8) P <- ((theta * d) / 2) B <- d * sin(theta / 2) R <- A / P D <- A / B V <- Q / A Re <- (rho * R * V) / mu if (Re < 2000) { message(sprintf("Low Reynolds number: %.0f indicates not rough turbulent, Manning eq. not valid\n",Re)) } Fr <- V / (sqrt(g * D)) yc <- ycfunc(Q = Q, d = d, g = g) out <- list(Q = Q, V = V, A = A, P = P, R = R, y = y, d = d, Sf = Sf, n = n, yc = yc, Fr = Fr, Re = Re, Qf = Qf) return(return_fcn2(x = out, units = units, ret_units = ret_units)) } }
SegSeqResProcess <- function(filename) { segseqRaw = read.delim(filename) chrs = sort(unique(segseqRaw[,1])) segseqRes = vector("list", length(chrs)) for(j in 1:length(chrs)) { segseqRes[[j]] = as.matrix(segseqRaw[segseqRaw[,1]==chrs[j],-1]) } names(segseqRes) = as.character(chrs) nChrs = length(segseqRes) tauHat = vector("list", nChrs) for(j in 1:nChrs) { tauHat[[j]] = unique(c(segseqRes[[j]][1,1],segseqRes[[j]][,2])) } names(tauHat) = names(segseqRes) return(tauHat) }
get_current_forecast <- function(latitude, longitude, units="us", language="en", exclude=NULL, extend=NULL, add_json=FALSE, add_headers=FALSE, ...) { url <- sprintf("https://api.darksky.net/forecast/%s/%s,%s", darksky_api_key(), latitude, longitude) params <- list(units=units, language=language) if (!is.null(exclude)) params$exclude <- exclude if (!is.null(extend)) params$extend <- extend resp <- httr::GET(url=url, query=params, ...) httr::stop_for_status(resp) tmp <- httr::content(resp, as="parsed") lys <- c("hourly", "minutely", "daily") lapply( lys[which(lys %in% names(tmp))], function(x) { dat <- plyr::rbind.fill(lapply(tmp[[x]]$data, as.data.frame, stringsAsFactors=FALSE)) ftimes <- c("time", "sunriseTime", "sunsetTime", "temperatureMinTime", "temperatureMaxTime", "apparentTemperatureMinTime", "apparentTemperatureMaxTime", "precipIntensityMaxTime") cols <- ftimes[which(ftimes %in% colnames(dat))] for (col in cols) { dat[,col] <- convert_time(dat[,col]) } dat } ) -> fio_data fio_data <- setNames(fio_data, lys[which(lys %in% names(tmp))]) if ("currently" %in% names(tmp)) { currently <- as.data.frame(tmp$currently, stringsAsFactors=FALSE) if ("time" %in% colnames(currently)) { currently$time <- convert_time(currently$time) } fio_data$currently <- currently } if (add_json) fio_data$json <- tmp ret_val <- fio_data if (add_headers) { dev_heads <- c("cache-control", "expires", "x-forecast-api-calls", "x-response-time") ret_heads <- httr::headers(resp) ret_val <- c(fio_data, ret_heads[dev_heads[which(dev_heads %in% names(ret_heads))]]) } class(ret_val) <- c("darksky", "current", class(ret_val)) return(ret_val) }
logit.spls.cv <- function(X, Y, lambda.ridge.range, lambda.l1.range, ncomp.range, adapt=TRUE, maxIter=100, svd.decompose=TRUE, return.grid=FALSE, ncores=1, nfolds=10, nrun=1, center.X=TRUE, scale.X=FALSE, weighted.center=TRUE, seed=NULL, verbose=TRUE) { X <- as.matrix(X) n <- nrow(X) p <- ncol(X) index.p <- c(1:p) if(is.factor(Y)) { Y <- as.numeric(levels(Y))[Y] } Y <- as.integer(Y) Y <- as.matrix(Y) q <- ncol(Y) one <- matrix(1,nrow=1,ncol=n) if(!is.null(seed)) { set.seed(seed) } if(length(table(Y)) > 2) { warning("message from logit.spls.cv: multicategorical response") results = multinom.spls.cv(X=X, Y=Y, lambda.ridge.range=lambda.ridge.range, lambda.l1.range=lambda.l1.range, ncomp.range=ncomp.range, adapt=adapt, maxIter=maxIter, svd.decompose=svd.decompose, return.grid=return.grid, ncores=ncores, nfolds=nfolds, nrun=nrun, center.X=center.X, scale.X=scale.X, weighted.center=weighted.center, seed=seed, verbose=verbose) return(results) } if ((!is.matrix(X)) || (!is.numeric(X))) { stop("Message from logit.spls.cv: X is not of valid type") } if (p==1) { warning("Message from logit.spls.cv: p=1 is not valid, ncomp.range is set to 0") ncomp.range <- 0 } if ((!is.matrix(Y)) || (!is.numeric(Y))) { stop("Message from logit.spls.cv: Y is not of valid type") } if (q != 1) { stop("Message from logit.spls.cv: Y must be univariate") } if (nrow(Y)!=n) { stop("Message from logit.spls.cv: the number of observations in Y is not equal to the number of row in X") } if (sum(is.na(Y))!=0) { stop("Message from logit.spls.cv: NA values in Ytrain") } if (sum(!(Y %in% c(0,1)))!=0) { stop("Message from logit.spls.cv: Y is not of valid type") } if (sum(as.numeric(table(Y))==0)!=0) { stop("Message from logit.spls.cv: there are empty classes") } if (any(!is.numeric(lambda.ridge.range)) || any(lambda.ridge.range<0) || any(!is.numeric(lambda.l1.range)) || any(lambda.l1.range<0) || any(lambda.l1.range>1)) { stop("Message from logit.spls.cv: lambda is not of valid type") } if (any(!is.numeric(ncomp.range)) || any(round(ncomp.range)-ncomp.range!=0) || any(ncomp.range<0) || any(ncomp.range>p)) { stop("Message from logit.spls.cv: ncomp is not of valid type") } if ((!is.numeric(maxIter)) || (round(maxIter)-maxIter!=0) || (maxIter<1)) { stop("Message from logit.spls.cv: maxIter is not of valid type") } if ((!is.numeric(ncores)) || (round(ncores)-ncores!=0) || (ncores<1)) { stop("Message from logit.spls.cv: ncores is not of valid type") } if ((!is.numeric(nfolds)) || (round(nfolds)-nfolds!=0) || (nfolds<1)) { stop("Message from logit.spls.cv: nfolds is not of valid type") } if ((!is.numeric(nrun)) || (round(nrun)-nrun!=0) || (nrun<1)) { stop("Message from logit.spls.cv: nrun is not of valid type") } if( any(as.vector(table(Y))<nfolds)) { stop("Message from logit.spls.cv: there is a class defined by Y that has less members than the number of folds nfold") } fold.size = n %/% nfolds folds.obs = sapply(1:nrun, function(run) { index0 = (1:n)[Y==0] index1 = (1:n)[Y==1] folds0 = c(1:nfolds, rep(0, length(index0) - nfolds))[sample(x=1:length(index0), size=length(index0), replace=FALSE)] folds1 = c(1:nfolds, rep(0, length(index1) - nfolds))[sample(x=1:length(index1), size=length(index1), replace=FALSE)] ind.folds0 = index0[folds0!=0] ind.folds1 = index1[folds1!=0] rest = c(index0[folds0==0], index1[folds1==0]) folds.rest = rep(1:nfolds, length.out = length(rest))[sample(x=1:length(rest), size=length(rest), replace=FALSE)] folds.res = rep(NA, n) folds.res[ind.folds0] = folds0[folds0!=0] folds.res[ind.folds1] = folds1[folds1!=0] folds.res[rest] = folds.rest return(folds.res) }) folds.grid = expand.grid(k=1:nfolds, run=1:nrun, KEEP.OUT.ATTRS=FALSE) ntrain_values <- matrix(NA, nrow=nfolds, ncol=nrun) ntest_values <- matrix(NA, nrow=nfolds, ncol=nrun) meanXtrain_values <- list() sigma2train_values <- list() for(index in 1:nrow(folds.grid)) { k = folds.grid$k[index] run = folds.grid$run[index] Xtrain <- subset(X, folds.obs[,run] != k) Ytrain <- subset(Y, folds.obs[,run] != k) ntrain <- nrow(Xtrain) Xtest <- subset(X, folds.obs[,run] == k) Ytest <- subset(Y, folds.obs[,run] == k) ntest <- nrow(Xtest) r <- p DeletedCol <- NULL sigma2train <- apply(Xtrain, 2, var) * (ntrain-1)/(ntrain) if (sum(sigma2train < .Machine$double.eps)!=0){ if (sum(sigma2train < .Machine$double.eps)>(p-2)){ stop("Message from logit.spls.cv: the procedure stops because number of predictor variables with no null variance is less than 1.") } warning("Message from logit.spls.cv: There are covariables with null variance in the current sub-sampling, they will be ignored.") Xtrain <- Xtrain[,which(sigma2train >= .Machine$double.eps)] if (!is.null(Xtest)) { Xtest <- Xtest[,which(sigma2train>= .Machine$double.eps)] } DeletedCol <- index.p[which(sigma2train < .Machine$double.eps)] sigma2train <- sigma2train[which(sigma2train >= .Machine$double.eps)] p <- ncol(Xtrain) r <- p } meanXtrain <- apply(Xtrain,2,mean) if(center.X && scale.X) { sXtrain <- scale(Xtrain, center=meanXtrain, scale=sqrt(sigma2train)) } else if(center.X && !scale.X) { sXtrain <- scale(Xtrain, center=meanXtrain, scale=FALSE) } else { sXtrain <- Xtrain } sXtrain.nosvd = sXtrain if ((p > ntrain) && (svd.decompose) && (p>1)) { svd.sXtrain <- svd(t(sXtrain)) r <- length(svd.sXtrain$d[abs(svd.sXtrain$d)>10^(-13)]) V <- svd.sXtrain$u[,1:r] D <- diag(c(svd.sXtrain$d[1:r])) U <- svd.sXtrain$v[,1:r] sXtrain <- U %*% D rm(D) rm(U) rm(svd.sXtrain) } meanXtest <- apply(Xtest,2,mean) sigma2test <- apply(Xtest,2,var) if(center.X && scale.X) { sXtest <- scale(Xtest, center=meanXtrain, scale=sqrt(sigma2train)) } else if(center.X && !scale.X) { sXtest <- scale(Xtest, center=meanXtrain, scale=FALSE) } else { sXtest <- Xtest } sXtest.nosvd <- sXtest if ((p > ntrain) && (svd.decompose)) { sXtest <- sXtest%*%V } assign(paste0("sXtrain_", k, "_", run), sXtrain) assign(paste0("sXtest_", k, "_", run), sXtest) assign(paste0("sXtrain.nosvd_", k, "_", run), sXtrain.nosvd) assign(paste0("sXtest.nosvd_", k, "_", run), sXtest.nosvd) ntrain_values[k,run] <- ntrain ntest_values[k,run] <- ntest meanXtrain_values[[k + (run-1)*nfolds]] <- meanXtrain sigma2train_values[[k + (run-1)*nfolds]] <- sigma2train } paramGrid <- expand.grid(fold=1:nfolds, run=1:nrun, lambdaL1=lambda.l1.range, lambdaL2=lambda.ridge.range, ncomp=ncomp.range, KEEP.OUT.ATTRS=FALSE) res_cv <- Reduce("rbind", mclapply(split(paramGrid, f=row.names(paramGrid)), function(gridRow) { k <- gridRow$fold run <- gridRow$run ntrain <- ntrain_values[k,run] ntest <- ntest_values[k,run] Ytrain <- subset(Y, folds.obs[,run] != k) Ytest <- subset(Y, folds.obs[,run] == k) model <- tryCatch( logit.spls.aux(sXtrain=get(paste0("sXtrain_", k, "_", run)), sXtrain.nosvd=get(paste0("sXtrain.nosvd_", k, "_", run)), Ytrain=Ytrain, lambda.ridge=gridRow$lambdaL2, lambda.l1=gridRow$lambdaL1, ncomp=gridRow$ncomp, sXtest=get(paste0("sXtest_", k, "_", run)), sXtest.nosvd=get(paste0("sXtest.nosvd_", k, "_", run)), adapt=adapt, maxIter=maxIter, svd.decompose=svd.decompose, meanXtrain=meanXtrain_values[[k + (run-1)*nfolds]], sigma2train=sigma2train_values[[k + (run-1)*nfolds]], center.X=center.X, scale.X=scale.X, weighted.center=weighted.center), error = function(e) { print(e); warnings("Message from logit.spls.cv: error when fitting a model in crossvalidation"); return(NULL);} ) res = numeric(8) if(!is.null(model)) { res = c(gridRow$fold, gridRow$run, gridRow$lambdaL1, gridRow$lambdaL2, gridRow$ncomp, model$lenA, model$converged, sum(model$hatYtest != Ytest) / ntest) } else { res = c(gridRow$fold, gridRow$run, gridRow$lambdaL1, gridRow$lambdaL2, gridRow$ncomp, 0, NA, NA) } return(res) }, mc.cores=ncores, mc.silent=!verbose)) rownames(res_cv) <- paste(1:nrow(res_cv)) res_cv = data.frame(res_cv) colnames(res_cv) = c("nfold", "nrun", "lambda.l1", "lambda.ridge", "ncomp", "lenA", "converged", "error") cv.grid.fails <- data.frame( as.matrix( with( res_cv, aggregate(error, list(lambda.ridge, lambda.l1, ncomp), function(x) {sum(is.na(x))})))) colnames(cv.grid.fails) <- c("lambda.ridge", "lambda.l1", "ncomp", "nb.fail") if(sum(cv.grid.fails$nb.fail>0.8*nrun*nfolds) > (0.8*nrow(paramGrid))) { warnings("Message from logit.spls.cv: too many errors during the cross-validation process, the grid is not enough filled") } cv.grid.error <- data.frame( as.matrix( with( res_cv, aggregate(error, list(lambda.ridge, lambda.l1, ncomp), function(x) c(mean(x, na.rm=TRUE), sd(x, na.rm=TRUE)) )))) colnames(cv.grid.error) <- c("lambda.ridge", "lambda.l1", "ncomp", "error", "error.sd") cv.grid.conv <- data.frame( as.matrix( with( res_cv, aggregate(converged, list(lambda.ridge, lambda.l1, ncomp), mean, na.rm=TRUE)))) colnames(cv.grid.conv) <- c("lambda.ridge", "lambda.l1", "ncomp", "converged") conv.per <- mean(cv.grid.conv$converged) cv.grid1 <- merge(cv.grid.error, cv.grid.conv, by = c("lambda.ridge", "lambda.l1", "ncomp")) cv.grid <- merge(cv.grid1, cv.grid.fails, by = c("lambda.ridge", "lambda.l1", "ncomp")) index_min <- which.min(cv.grid$error) lambdaL1.opt <- cv.grid$lambda.l1[index_min] lambdaL2.opt <- cv.grid$lambda.ridge[index_min] ncomp.opt <- cv.grid$ncomp[index_min] if(return.grid) { return( list(lambda.ridge.opt=lambdaL2.opt, lambda.l1.opt=lambdaL1.opt, ncomp.opt=ncomp.opt, conv.per=conv.per, cv.grid=cv.grid) ) } else { return( list(lambda.ridge.opt=lambdaL2.opt, lambda.l1.opt=lambdaL1.opt, ncomp.opt=ncomp.opt, conv.per=conv.per, cv.grid=NULL) ) } }
context("test-unname_all_chunks") test_that("unname_all_chunks works in case is.null(chunk_name_prefix) == TRUE", { R_version <- paste(R.version$major, R.version$minor, sep = ".") skip_if_not(R_version >= "3.5.0") skip_if_not(rmarkdown::pandoc_available("1.12.3")) temp_file_path <- file.path(tempdir(check = TRUE), "example4.Rmd") file.copy(system.file("examples", "example4.Rmd", package = "namer"), temp_file_path) unname_all_chunks(temp_file_path) lines <- readLines(temp_file_path) chunk_info <- get_chunk_info(lines) testthat::expect_identical(chunk_info$name[1],'setup') testthat::expect_true(all(is.na(chunk_info$name[-1]))) rendering <- rmarkdown::render(temp_file_path) testthat::expect_is(rendering, "character") file.remove(temp_file_path) basename <- fs::path_ext_remove(temp_file_path) file.remove(paste0(basename, ".html")) }) test_that("unname_all_chunks works in case is.null(chunk_name_prefix) == FALSE", { R_version <- paste(R.version$major, R.version$minor, sep = ".") skip_if_not(R_version >= "3.5.0") skip_if_not(rmarkdown::pandoc_available("1.12.3")) temp_file_path <- file.path(tempdir(check = TRUE), "example4.Rmd") file.copy(system.file("examples", "example4.Rmd", package = "namer"), temp_file_path) unname_all_chunks(temp_file_path,chunk_name_prefix='example4') lines <- readLines(temp_file_path) chunk_info <- get_chunk_info(lines) testthat::expect_identical(chunk_info$name[1],'setup') testthat::expect_identical(chunk_info$name[6],'sessioninfo') testthat::expect_true(all(is.na(chunk_info$name[2:5]))) rendering <- rmarkdown::render(temp_file_path) testthat::expect_is(rendering, "character") file.remove(temp_file_path) basename <- fs::path_ext_remove(temp_file_path) file.remove(paste0(basename, ".html")) }) test_that("unname_all_chunks works in case chunk_name_prefix == 'setup' ", { R_version <- paste(R.version$major, R.version$minor, sep = ".") skip_if_not(R_version >= "3.5.0") skip_if_not(rmarkdown::pandoc_available("1.12.3")) temp_file_path <- file.path(tempdir(check = TRUE), "example4.Rmd") file.copy(system.file("examples", "example4.Rmd", package = "namer"), temp_file_path) unname_all_chunks(temp_file_path,chunk_name_prefix='setup') lines <- readLines(temp_file_path) chunk_info <- get_chunk_info(lines) testthat::expect_identical(chunk_info$name[1],'setup') testthat::expect_identical(chunk_info$name[3],'example4-1') testthat::expect_identical(chunk_info$name[4],'example4-1-bis') testthat::expect_identical(chunk_info$name[6],'sessioninfo') testthat::expect_true(all(is.na(chunk_info$name[c(2,5)]))) rendering <- rmarkdown::render(temp_file_path) testthat::expect_is(rendering, "character") file.remove(temp_file_path) basename <- fs::path_ext_remove(temp_file_path) file.remove(paste0(basename, ".html")) })
library(data.table) load("BENCHMARK/DATA/base_all_simulations.Rdata") library(MASS) library(lfe) library(glmmML) library(alpaca) library(plm) library(fixest) getime = function(x) (proc.time() - x)[[3]] getime_errcheck = function(x, y) ifelse("try-error" %in% class(y), NA, (proc.time() - x)[[3]]) all_n = 1000 * 10**(0:3) all_rep = 1:10 results_all = data.frame(family = NA, method = NA, n_obs = NA, G = NA, rep = NA, time = NA) all_fixef = c("dum_1", "dum_2", "dum_3") all_families = c("poisson", "gaussian", "negbin", "logit") setFixest_notes(FALSE) for(fam in all_families){ cat("-------\nFAMILY: ", fam, "\n-------\n") for(i in 1:length(all_n)){ cat("---- i =", i, "\n") n_obs = all_n[i] for(g in 1:3){ cat("g =", g) for(r in all_rep){ cat(".") base = base_all[i, r][[1]] if(fam == "negbin"){ pt = proc.time() res_fixest = fenegbin(y ~ X1, base, fixef = all_fixef[1:g]) results_all = rbind(results_all, data.frame(family=fam, method="fenegbin", n_obs=n_obs, G=g, rep=r, time=getime(pt))) if(i <= 2){ pt = proc.time() fml_glmnb = switch(g, "1"=y~X1+factor(dum_1), "2"=y~X1+factor(dum_1)+factor(dum_2), "3"=y~X1+factor(dum_1)+factor(dum_2)+factor(dum_3)) res_glmnb = try(glm.nb(fml_glmnb, base), silent = TRUE) results_all = rbind(results_all, data.frame(family=fam, method="glmnb", n_obs=n_obs, G=g, rep=r, time=getime_errcheck(pt, res_glmnb))) } } if(fam == "gaussian"){ pt = proc.time() res_fixest = feols(ln_y ~ X1, base, fixef = all_fixef[1:g]) results_all = rbind(results_all, data.frame(family=fam, method="feols", n_obs=n_obs, G=g, rep=r, time=getime(pt))) pt = proc.time() fml_lfe = switch(g, "1"=ln_y~X1|dum_1, "2"=ln_y~X1|dum_1+dum_2, "3"=ln_y~X1|dum_1+dum_2+dum_3) res_lfe = try(felm(fml_lfe, base), silent = TRUE) results_all = rbind(results_all, data.frame(family=fam, method="lfe", n_obs=n_obs, G=g, rep=r, time=getime_errcheck(pt, res_lfe))) if(FALSE && g == 1){ pt = proc.time() res_plm = try(plm(ln_y~X1, base, index = "dum_1", model = "within"), silent = TRUE) results_all = rbind(results_all, data.frame(family=fam, method="plm", n_obs=n_obs, G=g, rep=r, time=getime_errcheck(pt, res_plm))) } } if(fam == "logit"){ pt = proc.time() res_fixest = fixest::feglm(sign(y) ~ X1, base, fixef = all_fixef[1:g], family = binomial()) results_all = rbind(results_all, data.frame(family=fam, method="feglm (fixest)", n_obs=n_obs, G=g, rep=r, time=getime(pt))) if(g == 1){ pt = proc.time() res_glmmML = try(glmmboot(sign(y)~X1, base, family=binomial, cluster = base$dum_1), silent = FALSE) results_all = rbind(results_all, data.frame(family=fam, method="glmmboot", n_obs=n_obs, G=g, rep=r, time=getime_errcheck(pt, res_glmmML))) } base$sy = sign(base$y) pt = proc.time() fml_alpaca = switch(g, "1"=sy~X1|dum_1, "2"=sy~X1|dum_1+dum_2, "3"=sy~X1|dum_1+dum_2+dum_3) res_alpaca = try(alpaca::feglm(fml_alpaca, base), silent = TRUE) results_all = rbind(results_all, data.frame(family=fam, method="feglm (alpaca)", n_obs=n_obs, G=g, rep=r, time=getime_errcheck(pt, res_alpaca))) } if(fam == "poisson") { pt = proc.time() res_fixest = fepois(y ~ X1, base, fixef = all_fixef[1:g]) results_all = rbind(results_all, data.frame(family=fam, method="fepois", n_obs=n_obs, G=g, rep=r, time=getime(pt))) if(g == 1){ pt = proc.time() res_glmmML = try(glmmboot(y~X1, base, family=poisson, cluster = base$dum_1), silent = FALSE) results_all = rbind(results_all, data.frame(family=fam, method="glmmboot", n_obs=n_obs, G=g, rep=r, time=getime_errcheck(pt, res_glmmML))) } pt = proc.time() fml_alpaca = switch(g, "1"=y~X1|dum_1, "2"=y~X1|dum_1+dum_2, "3"=y~X1|dum_1+dum_2+dum_3) res_alpaca = try(alpaca::feglm(fml_alpaca, base, family = poisson()), silent = TRUE) results_all = rbind(results_all, data.frame(family=fam, method="feglm (alpaca)", n_obs=n_obs, G=g, rep=r, time=getime_errcheck(pt, res_alpaca))) } } cat("\n") } } } results_all = results_all[-1, ] library(data.table) base = fread("BENCHMARK/DATA/base_10M.csv") for(g in 1:3){ cat("g =", g) for(r in 1:10){ cat("|") pt = proc.time() res_fixest = feols(ln_y ~ X1, base, fixef = all_fixef[1:g]) results_all = rbind(results_all, data.frame(family="gaussian", method="feols", n_obs=1e7, G=g, rep=r, time=getime(pt))) cat(".") pt = proc.time() fml_lfe = switch(g, "1"=ln_y ~ X1|dum_1, "2"=ln_y~X1|dum_1+dum_2, "3"=ln_y~X1|dum_1+dum_2+dum_3) res_lfe = felm(fml_lfe, base) results_all = rbind(results_all, data.frame(family="gaussian", method="lfe", n_obs=1e7, G=g, rep=r, time=getime_errcheck(pt, res_lfe))) } cat("\n") } data.table::fwrite(results_all, file = "BENCHMARK/DATA/results_bench_R.txt") library(fixest) library(lfe) load("BENCHMARK/DATA/base_all_diff.Rdata") results_all_diff = data.frame(family = NA, method = NA, n_obs = NA, G = NA, rep = NA, time = NA) for(i in 1:4){ cat("------\nOBS = ", 10**(3+i), "\n------\n") base = base_all_diff[[i]] for(g in 1:3){ cat("g =", g) for(r in 1:10){ fml = switch(g, "1"=y ~ x1+x2|id_indiv, "2"=y ~ x1+x2|id_indiv+id_firm, "3"=y ~ x1+x2|id_indiv+id_firm+id_year) cat("|") pt = proc.time() res_fixest = feols(fml, base) results_all_diff = rbind(results_all_diff, data.frame(family="gaussian", method="feols", n_obs=10**(3+i), G=g, rep=r, time=getime(pt))) cat(".") if(i < 4){ pt = proc.time() res_lfe = felm(fml, base) results_all_diff = rbind(results_all_diff, data.frame(family="gaussian", method="lfe", n_obs=10**(3+i), G=g, rep=r, time=getime_errcheck(pt, res_lfe))) } } cat("\n") } } results_all_diff = results_all_diff[-1, ] data.table::fwrite(results_all_diff, file = "BENCHMARK/DATA/results_diff_bench_R.txt")
NULL translate_create_parallel_data <- function(Name, Description = NULL, ParallelDataConfig, EncryptionKey = NULL, ClientToken) { op <- new_operation( name = "CreateParallelData", http_method = "POST", http_path = "/", paginator = list() ) input <- .translate$create_parallel_data_input(Name = Name, Description = Description, ParallelDataConfig = ParallelDataConfig, EncryptionKey = EncryptionKey, ClientToken = ClientToken) output <- .translate$create_parallel_data_output() config <- get_config() svc <- .translate$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .translate$operations$create_parallel_data <- translate_create_parallel_data translate_delete_parallel_data <- function(Name) { op <- new_operation( name = "DeleteParallelData", http_method = "POST", http_path = "/", paginator = list() ) input <- .translate$delete_parallel_data_input(Name = Name) output <- .translate$delete_parallel_data_output() config <- get_config() svc <- .translate$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .translate$operations$delete_parallel_data <- translate_delete_parallel_data translate_delete_terminology <- function(Name) { op <- new_operation( name = "DeleteTerminology", http_method = "POST", http_path = "/", paginator = list() ) input <- .translate$delete_terminology_input(Name = Name) output <- .translate$delete_terminology_output() config <- get_config() svc <- .translate$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .translate$operations$delete_terminology <- translate_delete_terminology translate_describe_text_translation_job <- function(JobId) { op <- new_operation( name = "DescribeTextTranslationJob", http_method = "POST", http_path = "/", paginator = list() ) input <- .translate$describe_text_translation_job_input(JobId = JobId) output <- .translate$describe_text_translation_job_output() config <- get_config() svc <- .translate$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .translate$operations$describe_text_translation_job <- translate_describe_text_translation_job translate_get_parallel_data <- function(Name) { op <- new_operation( name = "GetParallelData", http_method = "POST", http_path = "/", paginator = list() ) input <- .translate$get_parallel_data_input(Name = Name) output <- .translate$get_parallel_data_output() config <- get_config() svc <- .translate$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .translate$operations$get_parallel_data <- translate_get_parallel_data translate_get_terminology <- function(Name, TerminologyDataFormat) { op <- new_operation( name = "GetTerminology", http_method = "POST", http_path = "/", paginator = list() ) input <- .translate$get_terminology_input(Name = Name, TerminologyDataFormat = TerminologyDataFormat) output <- .translate$get_terminology_output() config <- get_config() svc <- .translate$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .translate$operations$get_terminology <- translate_get_terminology translate_import_terminology <- function(Name, MergeStrategy, Description = NULL, TerminologyData, EncryptionKey = NULL) { op <- new_operation( name = "ImportTerminology", http_method = "POST", http_path = "/", paginator = list() ) input <- .translate$import_terminology_input(Name = Name, MergeStrategy = MergeStrategy, Description = Description, TerminologyData = TerminologyData, EncryptionKey = EncryptionKey) output <- .translate$import_terminology_output() config <- get_config() svc <- .translate$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .translate$operations$import_terminology <- translate_import_terminology translate_list_parallel_data <- function(NextToken = NULL, MaxResults = NULL) { op <- new_operation( name = "ListParallelData", http_method = "POST", http_path = "/", paginator = list() ) input <- .translate$list_parallel_data_input(NextToken = NextToken, MaxResults = MaxResults) output <- .translate$list_parallel_data_output() config <- get_config() svc <- .translate$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .translate$operations$list_parallel_data <- translate_list_parallel_data translate_list_terminologies <- function(NextToken = NULL, MaxResults = NULL) { op <- new_operation( name = "ListTerminologies", http_method = "POST", http_path = "/", paginator = list() ) input <- .translate$list_terminologies_input(NextToken = NextToken, MaxResults = MaxResults) output <- .translate$list_terminologies_output() config <- get_config() svc <- .translate$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .translate$operations$list_terminologies <- translate_list_terminologies translate_list_text_translation_jobs <- function(Filter = NULL, NextToken = NULL, MaxResults = NULL) { op <- new_operation( name = "ListTextTranslationJobs", http_method = "POST", http_path = "/", paginator = list() ) input <- .translate$list_text_translation_jobs_input(Filter = Filter, NextToken = NextToken, MaxResults = MaxResults) output <- .translate$list_text_translation_jobs_output() config <- get_config() svc <- .translate$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .translate$operations$list_text_translation_jobs <- translate_list_text_translation_jobs translate_start_text_translation_job <- function(JobName = NULL, InputDataConfig, OutputDataConfig, DataAccessRoleArn, SourceLanguageCode, TargetLanguageCodes, TerminologyNames = NULL, ParallelDataNames = NULL, ClientToken) { op <- new_operation( name = "StartTextTranslationJob", http_method = "POST", http_path = "/", paginator = list() ) input <- .translate$start_text_translation_job_input(JobName = JobName, InputDataConfig = InputDataConfig, OutputDataConfig = OutputDataConfig, DataAccessRoleArn = DataAccessRoleArn, SourceLanguageCode = SourceLanguageCode, TargetLanguageCodes = TargetLanguageCodes, TerminologyNames = TerminologyNames, ParallelDataNames = ParallelDataNames, ClientToken = ClientToken) output <- .translate$start_text_translation_job_output() config <- get_config() svc <- .translate$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .translate$operations$start_text_translation_job <- translate_start_text_translation_job translate_stop_text_translation_job <- function(JobId) { op <- new_operation( name = "StopTextTranslationJob", http_method = "POST", http_path = "/", paginator = list() ) input <- .translate$stop_text_translation_job_input(JobId = JobId) output <- .translate$stop_text_translation_job_output() config <- get_config() svc <- .translate$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .translate$operations$stop_text_translation_job <- translate_stop_text_translation_job translate_translate_text <- function(Text, TerminologyNames = NULL, SourceLanguageCode, TargetLanguageCode) { op <- new_operation( name = "TranslateText", http_method = "POST", http_path = "/", paginator = list() ) input <- .translate$translate_text_input(Text = Text, TerminologyNames = TerminologyNames, SourceLanguageCode = SourceLanguageCode, TargetLanguageCode = TargetLanguageCode) output <- .translate$translate_text_output() config <- get_config() svc <- .translate$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .translate$operations$translate_text <- translate_translate_text translate_update_parallel_data <- function(Name, Description = NULL, ParallelDataConfig, ClientToken) { op <- new_operation( name = "UpdateParallelData", http_method = "POST", http_path = "/", paginator = list() ) input <- .translate$update_parallel_data_input(Name = Name, Description = Description, ParallelDataConfig = ParallelDataConfig, ClientToken = ClientToken) output <- .translate$update_parallel_data_output() config <- get_config() svc <- .translate$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .translate$operations$update_parallel_data <- translate_update_parallel_data
context("tests of supporting functions") test_that("load the demo data", { result <- data(PolyHaplotyper_demo) expect_equal(dim(snpdos), c(30, 663)) expect_equal(dim(ped), c(661, 4)) expect_equal(names(ped), c("genotype", "mother", "father", "sample_nr")) }) test_that("test several functions", { result <- allHaplotypes(mrknames=letters[1:4]) expect_equal(dim(result), c(16, 4)) expect_equal(colnames(result), letters[1:4]) expect_true(all(result[nrow(result),] == 1)) expect_equal(result[1:2, ncol(result)], c(0, 1)) result <- mrkdos2mrkdid( mrkDosage=matrix(c(1,2,3,4,4,3,2,1), ncol=2, dimnames=list(letters[1:4], c("ind1", "ind2"))), ploidy=4) expect_equal(result, setNames(c(195, 587), c("ind1", "ind2"))) parhac <- matrix(c(1,1,2,2,5,6,1,1,1,1,1,3), ncol=2, dimnames=list(NULL, c("P1", "P2"))) result <- getFSfreqs(parhac=parhac, DRrate=0.1) expect_equal(names(result), c("FShac", "freq")) expect_equal(dim(result$FShac), c(6, 54)) expect_equal(sum(result$freq), 1, tolerance=1e-6) })
multitest_evaluation <- function(evaluations, iterations, cross_validation, preserve_distribution, name, method, problem){ structure(class="multitest_evaluation", list( evaluations = evaluations, iterations = iterations, cross_validation = cross_validation, preserve_distribution = preserve_distribution, name = name, method = method, problem = problem )) } summary.multitest_evaluation <- function(object,...){ measures <- data.frame( t(sapply(object$evaluations, function(x){ unlist(x$measures) })) ) test_attributes <- data.frame( t(sapply(object$evaluations, function(x){ x$test_attributes })) ) overall_measures <- t( sapply(measures, function(x){ summary(na.omit(x)) } ) ) numeric_attrs <- plyr::ldply(test_attributes, function(x){ unlisted_x <- unlist(x) if(is.numeric(unlisted_x)){ summary(unlisted_x) } } ) row.names(numeric_attrs) <- numeric_attrs[,1] numeric_attrs <- numeric_attrs[,-1] other_attrs <- unlist( sapply(test_attributes, function(x){ x <- unlist(x) if(is.character(x) || is.factor(x)){ unique(x) } }, simplify = FALSE) ) structure( list(evaluations = object$evaluations, overall_test_attributes = list(numeric = numeric_attrs, other = other_attrs ), overall_measures = overall_measures, test_attributes = test_attributes, measures = measures, iterations = object$iterations, cross_validation = object$cross_validation, preserve_distribution = object$preserve_distribution, name = object$name, method = object$method, problem = object$problem ), class = "multitest_evaluation.summary" ) } print.multitest_evaluation.summary <- function(x, digits = max(3, getOption("digits")-4), ...){ overall_measures <- replace_names(x$overall_measures, replace_colnames = FALSE) if(x$problem == "classification"){ row.names(overall_measures)<- c("Accuracy", "Lower bound of 95% CI", "Upper bound of 95% CI", "No information rate", "P-value (accuracy > NIR)", "McNemar's test P-value") } overall_attributes <- replace_names(x$overall_test_attributes$numeric, replace_colnames = FALSE) test_problem <- capitalize_first(x$problem) test_name <- x$name cat(paste(test_problem, "Multiple Test Evaluation:", test_name, "\n\n")) cat("Test attributes:\n\n") cat("General:\n") sample_method <- "" if(x$cross_validation){ sample_method <- paste0(x$iterations, "-fold cross validation") } else{ sample_method <- paste(x$iterations, "random samples") } if(x$problem == "classification"){ if(x$preserve_distribution){ sample_method <- paste(sample_method, "with") } else { sample_method <- paste(sample_method, "without") } sample_method <- paste(sample_method, "preservation of class distribution") sample_method <- strwrap(sample_method, width = getOption("width") * .4) names(sample_method) <- rep("", length(sample_method)) names(sample_method)[1] <- "Sampling method" } if(length(sample_method)==1){ gen_attrs <- c(x$overall_test_attributes$other, "Sampling method" = sample_method) } else { gen_attrs <- c(x$overall_test_attributes$other, sample_method) } allnames <- c( row.names(overall_attributes), names(gen_attrs), row.names(x$overall_measures) ) width = max(stringr::str_length(allnames)) gen_attrs <- replace_names(gen_attrs) gen_attr_names <- paste0( format( names(gen_attrs), justify = "right", width = width ), ":" ) gen_attr_names[grep("\\s:", gen_attr_names)] <- "" gen_attrs_matrix <- cbind( gen_attr_names, gen_attrs ) print( remove_names( gen_attrs_matrix ), quote = FALSE ) cat("\nSummary of attributes per test iteration:\n\n") row.names(overall_attributes) <- format(row.names(overall_attributes), width = width + 2, justify = "right") print(overall_attributes, quote=FALSE, digits = digits) cat("\nPerformance measures:\n\n") row.names(overall_measures) <- format(row.names(overall_measures), width = width + 2, justify = "right") print(overall_measures, quote = FALSE, digits = digits) invisible(x) } print.multitest_evaluation <- function(x, ...){ summary_x <- summary(x) print(summary_x$measures) invisible(x) }
source("ESEUR_config.r") pal_col=rainbow(3) fit_and_summary=function(kind_bsd) { kind_bsd$date=as.POSIXct(kind_bsd$date, format="%Y-%m-%d") start_date=kind_bsd$date[1] kind_bsd$Number_days=as.integer(difftime(kind_bsd$date, start_date, units="days")) rad_per_day=(2*pi)/365 kind_bsd$rad_Number_days=rad_per_day*kind_bsd$Number_days season_mod=glm(sloc ~ Number_days+ sin(rad_Number_days)+cos(rad_Number_days), data=kind_bsd) print(summary(season_mod)) } freebsd=read.csv(paste0(ESEUR_dir, "regression/Herraiz-freebsd.txt.xz"), as.is=TRUE) fit_and_summary(freebsd)
pearson.dist <- function (x) { x <- as.matrix (x) x <- x - rowMeans (x) x <- x / sqrt (rowSums (x^2)) if (hy.getOption("gc")) gc () x <- tcrossprod (x) if (hy.getOption("gc")) gc () x <- as.dist (x) if (hy.getOption("gc")) gc () 0.5 - x / 2 } .test (pearson.dist) <- function (){ context ("pearson.dist") test_that("pearson.dist against manual calculation", { expect_equivalent ( pearson.dist (flu), as.dist (0.5 - cor (t (as.matrix (flu))) / 2)) }) }
library(ggplot2) library(ggtikz) plus1 <- function(x) x + 1 plus2 <- function(x) x + 2 test_that("numeric coordinate components are transformed", { expect_equal(try_transform("1", plus1), 2) expect_equal(try_transform("1", plus2), 3) }) test_that("transformation to infinite and NA values raise an errors", { expect_error(try_transform("-1", log), "value -1 could not be transformed") expect_error(try_transform("0", log), "value 0 could not be transformed") }) test_that("non-numeric coordinate components are not transformed", { expect_equal(try_transform("1in", plus1), "1in") expect_equal(try_transform("2 cm", plus2), "2 cm") }) test_that("explicitly input infinite coordinate components are not transformed", { expect_equal(try_transform("inf", plus1), "inf") expect_equal(try_transform("-inf", plus1), "-inf") expect_equal(try_transform("Inf", plus1), "Inf") expect_equal(try_transform("-Inf", plus1), "-Inf") }) test_that("a single coordinate can be transformed", { expect_equal(transform_coord("(0,0)", plus1, plus1), "(1,1)") expect_equal(transform_coord("(0,0)", plus1, plus2), "(1,2)") expect_equal(transform_coord("(0,0)", plus2, plus1), "(2,1)") expect_equal(transform_coord("(0 , 0 )", plus1, plus1), "(1,1)") expect_equal(transform_coord("( 0, 0 )", plus1, plus1), "(1,1)") }) test_that("multiple coordinates can be transformed", { coords <- "(0,0) -- (1,1) -- (2,2)" expect_equal(transform_tikz(coords, plus1, plus1), "(1,1) -- (2,2) -- (3,3)") }) test_that("multi-line tikz code can be transformed", { tikz_code <- " \\draw (0,0) -- (50,50) -- cycle; \\node at (5,5) {Text}; " expect <- " \\draw (1,2) -- (51,52) -- cycle; \\node at (6,7) {Text}; " expect_equal(transform_tikz(tikz_code, plus1, plus2), expect) }) test_that("coordinates intermixed with radii can be transformed", { input <- "\\draw (0,20) circle (20mm) node at (30,40) to (2,3)(4,5) (3mm) to (3,4)" expect <- "\\draw (1,21) circle (20mm) node at (31,41) to (3,4)(5,6) (3mm) to (4,5)" result <- transform_tikz(input, plus1, plus1) expect_equal(result, expect) }) expect_transformed_equal <- function(canvas, annotation, expect) { transformed <- ggtikzTransform(canvas, annotation) expect_equal(transformed$tikz_code, expect) } test_that("tikz_code in annotations is transformed for data reference frames", { canvas <- canvas_y_log10() annotation <- ggtikzAnnotation("\\draw (10,10) -- (100,100);", xy="data", panelx=1, panely=1) expect_transformed_equal(canvas, annotation, "\\draw (10,1) -- (100,2);") }) test_that("tikz_code in annotations is transformed correctly for discrete scales", { canvas <- canvas_x_discrete() annotation <- ggtikzAnnotation("\\draw (1,1) -- (2,2);", xy="data", panelx=1, panely=1) expect_transformed_equal(canvas, annotation, "\\draw (1,1) -- (2,2);") }) test_that("tikz_code in annotations is not transformed for panel reference frames", { canvas <- canvas_y_log10() annotation <- ggtikzAnnotation("\\draw (0.5,0.5) -- (0.5,0.5);", xy="panel", panelx=1, panely=1) expect_transformed_equal(canvas, annotation, "\\draw (0.5,0.5) -- (0.5,0.5);") }) test_that("tikz_code in annotations is not transformed for plot reference frames", { canvas <- canvas_y_log10() annotation <- ggtikzAnnotation("\\draw (0.5,0.5) -- (0.5,0.5);", xy="plot") expect_transformed_equal(canvas, annotation, "\\draw (0.5,0.5) -- (0.5,0.5);") }) test_that("tikz_code in annotations is transformed correctly for mixed references", { canvas <- canvas_y_log10() annotation <- ggtikzAnnotation("\\draw (0.5,10) -- (0.5,100);", x="panel", y="data", panelx=1, panely=1) expect_transformed_equal(canvas, annotation, "\\draw (0.5,1) -- (0.5,2);") }) test_that("tikz_code in annotations is transformed only once", { canvas <- canvas_y_log10() annotation <- ggtikzAnnotation("\\draw (10,10) -- (100,100);", xy="data", panelx=1, panely=1) expect_false(annotation$.transformed) canvas <- canvas + annotation annotation_tf <- canvas$.annotations[[1]] expect_true(annotation_tf$.transformed) expect_equal(annotation_tf$tikz_code, "\\draw (10,1) -- (100,2);") annotation_tf2 <- ggtikzTransform(canvas, annotation_tf) expect_equal(annotation_tf2$tikz_code, "\\draw (10,1) -- (100,2);") }) test_that("get_stringr_required raises an error when transforms are necessary and stringr is missing", { need_tfs <- list(x=function(){}, y=function(){}) with_mock_requireNamespace(FALSE, expect_error(get_stringr_required(need_tfs), "requires the `stringr` package") ) }) test_that("get_stringr_required raises no error when transforms are necessary and stringr is available", { need_tfs <- list(x=function(){}, y=function(){}) with_mock_requireNamespace(TRUE, expect_error(get_stringr_required(need_tfs), NA) ) }) test_that("get_stringr_required raises no error when no transforms are necessary", { noneed_tfs <- list(x=identity, y=identity) with_mock_requireNamespace(TRUE, expect_error(get_stringr_required(noneed_tfs), NA) ) with_mock_requireNamespace(FALSE, expect_error(get_stringr_required(noneed_tfs), NA) ) })
library(plm) data("Hedonic", package = "plm") pHed <- pdata.frame(Hedonic, index = "townid") plm:::pos.index(pHed) pHed_new_plm.data <- plm.data(Hedonic, indexes = "townid") Hedonic_const <- Hedonic Hedonic_const$constantNr <- 1 Hedonic_const$constantStr <- "constant" Hedonic_const <- Hedonic_const[ , c("constantNr", setdiff(names(Hedonic), c("constantNr", "constantStr")), "constantStr")] pHed_const_new_plm.data <- plm.data(Hedonic_const, indexes = "townid") class(pHed_const_new_plm.data) names(pHed_const_new_plm.data) lapply(pHed_const_new_plm.data, class)
EFT_clust <- function(obj2clust = NULL, n_clust = 20, standardise_vars = TRUE, filename = "", ...){ if(is.null(obj2clust)) stop("Please provide objects of classe Raster* (or file names to read in some)") if(is.character(obj2clust)){ obj2clust <- stack(obj2clust) }else if(!class(obj2clust) %in% c("RasterLayer", "RasterStack", "RasterBrick")){ stop("Please provide objects of classe Raster* (or a file name to read in from)") } if(!is.numeric(n_clust) | is.na(n_clust) | is.null(n_clust)) stop("Please provide a number of clusters") obj2clust_ini <- as.data.frame(obj2clust) obj2clust_ini$rn <- 1:nrow(obj2clust_ini) setDT(obj2clust_ini) clstr <- NULL obj2clust_ini_NA <- obj2clust_ini[!complete.cases(obj2clust_ini), ] obj2clust_ini_NA[, clstr := NA] obj2clust_ini_NA[, clstr := as.integer(clstr)] obj2clust_ini_NA <- obj2clust_ini_NA[, .SD, .SDcols = c("clstr", "rn")] obj2clust_ini <- na.omit(obj2clust_ini) if(standardise_vars == TRUE){ cols2scale <- colnames(obj2clust_ini) cols2scale <- cols2scale[!cols2scale %in% c("rn")] cols2keep <- paste0(cols2scale, "_scld") obj2clust_ini[, (cols2keep) := lapply(.SD, function(x) as.vector(scale(x))), .SDcols = cols2scale] obj2clust_ini <- obj2clust_ini[, .SD, .SDcols = c(cols2keep, "rn")] } dts <- list(...) if(is.null(dts$nstart)) dts$nstart <- 1 if(is.null(dts$iter.max)) dts$iter.max <- 500 if(is.null(dts$algorithm)) dts$algorithm <- "MacQueen" kmeans_clustring <- kmeans(obj2clust_ini[, - c("rn")], centers = n_clust, nstart = dts$nstart, iter.max = dts$iter.max, algorithm = dts$algorithm ) clust_eval <- kmeans_clustring$betweenss / kmeans_clustring$totss * 100 obj2clust_ini[, clstr := kmeans_clustring$cluster] obj2clust_ini <- obj2clust_ini[, .SD, .SDcols = c("clstr", "rn")] all_data <- bind_rows(obj2clust_ini, obj2clust_ini_NA) setorder(all_data, rn) EFTs_raster <- raster(nrows = obj2clust@nrows, ncols = obj2clust@ncols, crs = crs(obj2clust), ext = extent(obj2clust), vals = all_data$clstr) names(EFTs_raster) <- "clusterNum" if (filename != "") writeRaster(EFTs_raster, filename = filename, overwrite = TRUE) return(list(EFTs_raster, clust_eval)) }
library("knitr") Rscript_executable <- paste(file.path(R.home(), "bin", "Rscript"), "--vanilla") opts_knit$set(root.dir = system.file("exec", package="optparse")) opts_chunk$set(comment=NA, echo=FALSE) list_file_command <- "ls" chmod_command <- "chmod ug+x display_file.R example.R" path_command <- "export PATH=$PATH:`pwd`" run_command <- function(string) { suppressWarnings(cat(system(string, intern=TRUE), sep="\n")) } run_command(sprintf("%s", list_file_command)) command <- "display_file.R example.R" run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "example.R --help" run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "example.R" run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "example.R --mean=10 --sd=10 --count=3" run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "example.R --quiet -c 4 --generator=\"runif\"" run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "example.R --silent -m 5" run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "example.R -c 100 -c 2 -c 1000 -c 7" run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "display_file.R --help" run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "display_file.R --add_numbers display_file.R" run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "display_file.R non_existent_file.txt" run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "display_file.R" run_command(sprintf("%s %s 2>&1", Rscript_executable, command))
rings_segmentation <- function(z, angle_width, return_angle = FALSE) { stopifnot(class(z) == "RasterLayer") stopifnot(class(return_angle) == "logical") stopifnot(length(angle_width) == 1) if (!.is_whole(90 / angle_width)) { stop( paste("angle_width should divide the,", "0 to 90 range into a whole number of segments.") ) } intervals <- seq(0, 90, angle_width) c1 <- intervals[1:(length(intervals) - 1)] c2 <- intervals[2:length(intervals)] if (return_angle) { c3 <- (c1 + c2) / 2 } else { c3 <- 1:(length(intervals) - 1) } rcl <- matrix(c(c1, c2, c3), ncol = 3) reclassify(z, rcl) }
with_mock_api({ test_that("get_user_profile: expected behaviour", { skip_if(!dir.exists("api.twitter.com")) ori_test <- "../testdata/commtwitter/" user_ids <- unique(bind_tweets(ori_test, verbose = FALSE)$author_id)[c(1,2,3)] res <- get_user_profile(x = user_ids) expect_equal(readRDS("../testdata/user_profiles.RDS"), res) }) }) with_mock_api({ test_that("get_user_following: expected behaviour", { skip_if(!dir.exists("api.twitter.com")) ori_test <- "../testdata/commtwitter/" user_ids <- unique(bind_tweets(ori_test, verbose = FALSE)$author_id)[c(1,2,3)] res <- get_user_following(x = user_ids) expect_equal(nrow(readRDS("../testdata/user_following.RDS")), nrow(res)) }) }) with_mock_api({ test_that("get_user_following: expected behaviour", { skip_if(!dir.exists("api.twitter.com")) ori_test <- "../testdata/commtwitter/" user_ids <- unique(bind_tweets(ori_test, verbose = FALSE)$author_id)[c(1,2,3)] res <- get_user_followers(x = user_ids) expect_equal(nrow(readRDS("../testdata/user_followers.RDS")), nrow(res)) }) })
estimateActivations <- function(cuesOutcomes, weightMatrix, unique=FALSE,...) { cues = rownames(weightMatrix) outcomes = colnames(weightMatrix) NA.cue_strings <- grep("(^NA_)|(_NA_)|(_NA$)",cuesOutcomes$Cues) NA.outcome_strings <- grep("(^NA)|(_NA_)|(_NA$)",cuesOutcomes$Outcomes) if(length(NA.cue_strings)>0) warning(paste("Potential NA's in ",length(NA.cue_strings)," 'Cues'.",sep="")) if(length(NA.outcome_strings)>0) warning(paste("Potential NA's in ",length(NA.outcome_strings)," 'Outcomes'.",sep="")) NA.cues <- which(is.na(cuesOutcomes$Cues)) if("Outcomes" %in% names(cuesOutcomes)) NA.outcomes <- which(is.na(cuesOutcomes$Outcomes)) else { NA.outcomes = NULL warning("No 'Outcomes' column specified in 'cuesOutcomes'.") } if(length(NA.cues)>0) stop(paste("NA's in 'Cues': ",length(NA.cues)," cases.",sep="")) if(length(NA.outcomes)>0) stop(paste("NA's in 'Outcomes': ",length(NA.outcomes)," cases.",sep="")) obsCues = strsplit(as.character(cuesOutcomes$Cues), "_") uniqueObsCues = unique(unlist(obsCues)) newCues = uniqueObsCues[!is.element(uniqueObsCues, cues)] if(length(newCues) > 0) { wnew = matrix(0, length(newCues), ncol(weightMatrix)) rownames(wnew)=newCues colnames(wnew)=colnames(weightMatrix) w = rbind(weightMatrix, wnew) cues = c(cues, newCues) } else { w = weightMatrix } obsOutcomes = strsplit(as.character(cuesOutcomes$Outcomes), "_") uniqueObsOutcomes = unique(unlist(obsOutcomes)) newOutcomes = uniqueObsOutcomes[!is.element(uniqueObsOutcomes, outcomes)] m = matrix(0, length(cues), nrow(cuesOutcomes)) rownames(m) = cues v = rep(0, length(cues)) names(v) = cues for(i in 1:nrow(cuesOutcomes)) { v[obsCues[[i]]]=1 m[,i] = v v[obsCues[[i]]]=0 } a = t(w) %*% m if (unique) { activationMatrix <- unique(t(a)) } else { activationMatrix <- t(a) } if (length(newCues)>0) warning(paste("There were ", length(newCues), " cues not present in 'weightMatrix'.",sep="")) if (length(newOutcomes)>0) { warning(paste("There were ", length(newOutcomes), " outcomes not present in 'weightMatrix'.",sep="")) } result <- list(activationMatrix = activationMatrix, newCues = newCues, newOutcomes = newOutcomes) return(result) }
em.fil.interaction <- function(parameter, X, full.missing.data, observed.data, full.data, k, family = family) { p1 <- ncol(X) beta <- parameter[1:p1] alpha <- parameter[(p1 + 1):length(parameter)] linear.pred.y <- X %*% beta linear.pred.r <- cbind(X, X[, k + 1] * full.missing.data[, 1], full.missing.data[, 1]) %*% alpha likelihood.y <- exp(full.missing.data[, 1]*linear.pred.y)/(1 + exp(linear.pred.y)) likelihood.r <- exp(full.missing.data[, (p1 + 1)]*linear.pred.r)/(1 + exp(linear.pred.r)) likelihood.0 <- exp(0 * linear.pred.y)/(1 + exp(linear.pred.y)) likelihood.1 <- exp(1 * linear.pred.y)/(1 + exp(linear.pred.y)) weight.missing <- (likelihood.y*likelihood.r)/(likelihood.0*likelihood.r + likelihood.1*likelihood.r) weight.observed <- rep(1, nrow(observed.data)) weight <- c(weight.observed, weight.missing) full.x1 <- full.data[, -c(1, p1 + 1)] full.y <- full.data[, 1] full.r <- full.data[, p1 + 1] brglm.fit.y <- brglm::brglm(formula = full.y ~ full.x1, family = family, weights = weight) temp.y <- full.y * full.x1[, k] glm.fit.r <- brglm::brglm(formula = full.r ~ full.x1 + temp.y + full.y, family = family) alpha.hat <- stats::coef(glm.fit.r) beta.hat.firth <- stats::coef(brglm.fit.y) Fisher <- brglm.fit.y$FisherInfo weights <- brglm.fit.y$weights current.Q.firth <- brglm.fit.y$deviance/(-2) + glm.fit.r$deviance/(-2) parameter.hat.firth <- c(beta.hat.firth, alpha.hat) Fisher.alpha <- glm.fit.r$FisherInfo result <- list(Q.firth = current.Q.firth, parameter.firth = parameter.hat.firth, Fisher.firth = Fisher, weights = weights, Fisher.firth.alpha = Fisher.alpha) return(result) }
.year <- 1947:1962 longley <- data.frame( GNP.deflator = c(83, 88.5, 88.2, 89.5, 96.2, 98.1, 99, 100, 101.2, 104.6, 108.4, 110.8, 112.6, 114.2, 115.7, 116.9), GNP = c(234.289, 259.426, 258.054, 284.599, 328.975, 346.999, 365.385, 363.112, 397.469, 419.18, 442.769, 444.546, 482.704, 502.601, 518.173, 554.894), Unemployed = c(235.6, 232.5, 368.2, 335.1, 209.9, 193.2, 187, 357.8, 290.4, 282.2, 293.6, 468.1, 381.3, 393.1, 480.6, 400.7), Armed.Forces = c(159, 145.6, 161.6, 165, 309.9, 359.4, 354.7, 335, 304.8, 285.7, 279.8, 263.7, 255.2, 251.4, 257.2, 282.7), Population = c(107.608, 108.632, 109.773, 110.929, 112.075, 113.27, 115.094, 116.219, 117.388, 118.734, 120.445, 121.95, 123.366, 125.368, 127.852, 130.081), Year = .year, Employed = c(60.323, 61.122, 60.171, 61.187, 63.221, 63.639, 64.989, 63.761, 66.019, 67.857, 68.169, 66.513, 68.655, 69.564, 69.331, 70.551), row.names = .year) rm(.year)
test_that("download_checkpoint works", { new_cpdir <- download_BERT_checkpoint( model = "bert_base_uncased", dir = checkpoint_main_dir ) expect_identical(new_cpdir, cpdir) testthat::expect_true( file.exists(file.path(cpdir, "vocab.txt")) ) testthat::expect_true( file.exists(file.path(cpdir, "bert_config.json")) ) testthat::expect_true( file.exists(file.path(cpdir, "bert_model.ckpt.index")) ) testthat::expect_true( file.exists(file.path(cpdir, "bert_model.ckpt.meta")) ) testthat::expect_true( file.exists(file.path(cpdir, "bert_model.ckpt.data-00000-of-00001")) ) }) test_that("dir chooser works.", { expect_identical( .choose_BERT_dir("fake"), "fake" ) temp_dir <- tempdir() testing_dir <- paste0(temp_dir, "/testing") old_dir <- set_BERT_dir(testing_dir) expect_identical( normalizePath(getOption("BERT.dir"), mustWork = FALSE), normalizePath(testing_dir, mustWork = FALSE) ) expect_identical( .choose_BERT_dir(NULL), normalizePath(testing_dir, mustWork = FALSE) ) options(BERT.dir = NULL) default_dir <- rappdirs::user_cache_dir("RBERT") expect_identical( .choose_BERT_dir(NULL), default_dir ) options(BERT.dir = old_dir$BERT.dir) unlink(normalizePath(testing_dir), recursive = TRUE) }) test_that("Can download a cp by url.", { target_dir <- file.path( checkpoint_main_dir, "uncased_L-12_H-768_A-12" ) dir.create(target_dir) file.copy( cpdir, target_dir, recursive = TRUE ) google_base_url <- "https://storage.googleapis.com/bert_models/" bert_base_uncased_url <- paste0( google_base_url, "2018_10_18/uncased_L-12_H-768_A-12.zip" ) expect_warning( expect_identical( download_BERT_checkpoint( url = bert_base_uncased_url ), normalizePath(target_dir) ), NA ) unlink(target_dir, recursive = TRUE) scibert_url <- paste0( "https://s3-us-west-2.amazonaws.com/ai2-s2-research/scibert/", "tensorflow_models/scibert_scivocab_uncased.tar.gz" ) expect_warning( scibert_path <- download_BERT_checkpoint( url = scibert_url, dir = checkpoint_main_dir ), NA ) unlink(scibert_path, recursive = TRUE) }) test_that(".has_checkpoint works as expected.", { expect_error( expect_true(.has_checkpoint(model = "bert_base_uncased")), NA ) })
nose.rr <- function(nos,cc) { tcol=ncol(nos) trow=nrow(nos) nature=matrix(0,trow,1,byrow=FALSE) e=cc f=1/e for(m in 1:trow) { a=nos[m,1] b=nos[m,2] c=nos[m,3] d=nos[m,4] if(a>=0 && b>=0 && c>=0 && d>=0 && e>=0) { if(a>0 && b>0 && c>0 && d>0) {nature[m]='atleast one of the four arguments must be zero'} n=a+b p=c+d if(a==0 && b>0 && c>0 && d>0) { if(d>(b+c)) {cl1= (c * n) / (d - c - b) clr1=round(cl1,3) if(e>clr1) {nature[m]='SEVERE SPARSE'} else {nature[m]='MILD SPARSE'} } else {nature[m]='MILD SPARSE'} } if(c==0 && a>0 && b>0 && d>0) { if(b<=(d+a)) {nature[m]='MILD SPARSE'} else {cl2 = (a * p) / (b - a - d) clr2=round(cl2,3) if(e>clr2) {nature[m]='SEVERE SPARSE'} else {nature[m]='MILD SPARSE'} } } if(b==0 && a>0 && c>0 && d>0) {nature[m]='MILD SPARSE'} if(d==0 && a>0 && b>0 && c>0) {nature[m]='MILD SPARSE'} if(a==0 && b==0 && c>0 && d>0) {nature[m]='MILD SPARSE'} if(a==0 && c==0 && b>0 && d>0) {nature[m]='MILD SPARSE'} if(a==0 && d==0 && b>0 && c>0) {nature[m]='MILD SPARSE'} if(b==0 && c==0 && a>0 && d>0) {nature[m]='MILD SPARSE'} if(b==0 && d==0 && a>0 && c>0) { if(a==c) {nature[m]='MILD SPARSE'} else {nature[m]='SEVERE SPARSE'} } if(c==0 && d==0 && a>0 && b>0) {nature[m]='MILD SPARSE'} if(a==0 && b==0 && c==0 && d>0) {nature[m]='MILD SPARSE'} if(a==0 && b==0 && d==0 && c>0) {nature[m]='MILD SPARSE'} if(a==0 && c==0 && d==0 && b>0) {nature[m]='MILD SPARSE'} if(b==0 && c==0 && d==0 && a>0) {nature[m]='MILD SPARSE'} if(a==0 &&b==0 && c==0 && d==0 ) {nature[m]='MILD SPARSE'} } else { nature[m]='arguments must be non negative numbers' } } nosrr=cbind(nos,nature) nosrr }
test_that("error when wrong template", { a <- data.frame(letters[1:3], 1:3) expect_error(pie_bake_pro(a, template = "abbassomilan"), "exist") expect_error(pie_bake_pro(a, template = "basic3"), "pie_bake") }) test_that("data_check is properly linked", { a <- data.frame(1:3, letters[1:3]) expect_error(pie_bake_pro(a, template = "eye1"), "second variable") expect_error(pie_bake_pro(a, template = "eye2"), "second variable") }) test_that("output has 'list' type", { a <- data.frame(letters[1:3], 1:3) expect_type(pie_bake_pro(a, template = "dart1"), "list") expect_type(pie_bake_pro(a, template = "dart3", title = "tt"), "list") }) test_that("output is a 'ggplot' object", { a <- data.frame(letters[1:3], 1:3) expect_match(class(pie_bake_pro(a, template = "eaten3")), "gg") expect_match(class(pie_bake_pro(a, template = "eaten1", title = "gg")), "gg") expect_match(class(pie_bake_pro(a, template = "cirbar1", title = "prova")), "gg") expect_match(class(pie_bake_pro(a, template = "cirbar2")), "gg") expect_match(class(pie_bake_pro(a, template = "cirbar3", title = "ciao")), "gg") expect_match(class(pie_bake_pro(a, template = "cirbar4", title = "nop")), "gg") expect_match(class(pie_bake_pro(a, template = "cirbar5")), "gg") }) test_that("output is NULL when the template is a spider chart", { a <- data.frame(letters[1:3], 1:3) expect_match(class(pie_bake_pro(a, template = "spider1")), "NULL") expect_match(class(pie_bake_pro(a, template = "spider2")), "NULL") expect_match(class(pie_bake_pro(a, template = "spider3")), "NULL") expect_match(class(pie_bake_pro(a, template = "spider4")), "NULL") expect_match(class(pie_bake_pro(a, template = "spider5")), "NULL") }) test_that("title specification works", { a <- data.frame(letters[1:3], 1:3) out1 <- pie_bake_pro(a, template = "watermelon1") out2 <- pie_bake_pro(a, template = "watermelon3", title = "ciaociao") expect_match(out1$labels$title, "") expect_match(out2$labels$title, "ciaociao") }) test_that("percentages are properly computed", { a <- data.frame(letters[1:3], 1:3) b <- data.frame(letters[1:5], sample(1:100,5)) out1 <- pie_bake_pro(a, template = "watermelon4") out2 <- pie_bake_pro(b, template = "eye1", title = "ciaociao") expect_equal(sum(out1$data[,2]), 100, tolerance = 3) expect_equal(sum(out2$data[,2]), 100, tolerance = 3) }) test_that("also tibbles can be baked", { a <- data.frame(letters[1:3], 1:3) b <- tibble::tibble(letters[1:5], 1:5) c <- tibble::tibble(letters[1:5], c(4.3, 2.2, 1, 2, 3.0)) expect_match(class(pie_bake_pro(tibble::as_tibble(a), template = "dart2")), "gg") expect_match(class(pie_bake_pro(b, template = "dart4")), "gg") expect_match(class(pie_bake_pro(c, template = "dart5")), "gg") })