code
stringlengths
1
13.8M
findend<-function(inde,left,right,low,upp,N){ lenn<-length(inde) current<-1 dep<-1 if ((left[current]==0) && (right[current]==0)){ exists<-FALSE } else{ exists<-TRUE } while ((exists) && ((left[current]>0) || (right[current]>0))){ mid<-(low[current]+upp[current])/2 direc<-depth2com(dep,N)$direc if (inde[direc]<=mid){ if (left[current]>0){ current<-left[current] dep<-dep+1 } else{ exists<-FALSE } } else{ if (right[current]>0){ current<-right[current] dep<-dep+1 } else{ exists<-FALSE } } } return(list(exists=exists,location=current,dep=dep)) }
NULL IM4E <- function(xx,yy,epsilon=0.01,sig=1,lambda=1,max_iter=10,removesmall=FALSE) { suppressWarnings( res<-(IM4ECpp(oneIM4E = one.IM4E,xx,yy,epsilon=0.01, sig=1, lambda=1,max_iter=10,removesmall=FALSE))) class(res)<-"IM4E" return(res) }
efs_eval <- function(data, efs_table, file_name, classnumber, NA_threshold, logreg = TRUE, rf = TRUE, permutation = TRUE, p_num = 100, variances = TRUE, jaccard = TRUE, bs_num =100, bs_percentage = 0.9){ if(missing(efs_table)) stop("efs_table argument missing") if(missing(file_name)) stop("file_name argument missing") if(missing(classnumber)) stop("classnumber argument missing") if(missing(NA_threshold)){ NA_threshold=0.2 print("default value for NA_threshold = 0.2")} if(!is.numeric(NA_threshold) | NA_threshold > 1 | NA_threshold < 0) stop("invalid argument: NA_threshold is required to be in [0,1]") if(missing(p_num)){ p_num=100 print("default value for p_num = 100")} if(missing(bs_num)){ bs_num = 100 print("default value for bs_num = 100")} if(missing(bs_percentage)){ bs_percentage=0.9 print("default value for bs_percentage = 0.9")} classname = colnames(data)[classnumber] NrNA= c() for(i in 1:length(data[1,])){ NrNA[i] = length(which(is.na(data[,i]))) } NmNA = which(NrNA/length(data[,1])>0.2) if(length(NmNA) != 0) data=data[,-NmNA] data = na.omit(data, row.names=F) data=data[,which(colSums(data,na.rm=F)!=0 & apply(data, 2, var)!=0)] clnr= which(colnames(data)==classname) logreg_test <- function(data, efs_table, file_name, classnumber){ e.features = which(colSums(efs_table)> mean(colSums(efs_table))) klasse = data[,classname] clnr= which(colnames(data)==classname) data = data[,-clnr] k=length(data[,1]) prob1=c() prob2=c() prob3=c() for(i in 1:k){ Train = seq(i,to=nrow(data),by=k) training <- data[-Train, ] training.cl <- klasse[-Train] testing <- data[ Train, ] testing.cl <- klasse[Train] logreg1 = glm(as.factor(training.cl)~., data = training, family = binomial,control = list(maxit = 50)) logreg3 = glm(as.factor(training.cl)~., data = training[,e.features], family = binomial,control = list(maxit = 50)) prob1= (c(prob1,predict(logreg1, newdata=testing))) prob3= (c(prob3,predict(logreg3, newdata=testing))) } prob1=prob1[order(as.numeric(names(prob1)))] roc1=roc(klasse, prob1, ci=T) ci1=roc1$ci ci1= gsub('95% CI:', '',ci1) ci1=round(as.numeric(ci1),1)*100 pred1 <- prediction(prob1, klasse) perf1 <- performance(pred1, measure = "tpr", x.measure = "fpr") auc1 <- performance(pred1, measure = "auc") auc1 <- [email protected][[1]] prob3=prob3[order(as.numeric(names(prob3)))] roc3=roc(klasse, prob3, ci=T) ci3=roc3$ci ci3= gsub('95% CI:', '',ci3) ci3=round(as.numeric(ci3),3)*100 pred3 <- prediction(prob3, klasse) perf3 <- performance(pred3, measure = "tpr", x.measure = "fpr") auc3 <- performance(pred3, measure = "auc") auc3 <- [email protected][[1]] r=roc.test(roc1,roc3) p = as.numeric(r$p.value) P = paste("p = ",round(p,3),sep ="") if(p<0.001){P = "p < 0.001"} d=c(0,1) pdf(paste(file_name,"_LG_ROC.pdf", sep="")) plot(perf1, avg="vertical", spread.estimate="boxplot", main="") plot(perf3, avg="vertical", spread.estimate="boxplot", main="",add=TRUE, col = 'blue') abline(d, lty=2) text(0.15, 0.9, cex=1, paste("All: ", round(mean(auc1),3)*100, "% (", format(ci1[1], nsmall=1), '...',format(ci1[3], nsmall=1), ")", sep="")) text(0.15, 1, cex=1, paste("EFS: ",round(mean(auc3),3)*100, "% (",format(ci3[1], nsmall=1), '...',format(ci3[3], nsmall=1), ")", sep=""), col='blue') text(0.8, 0.1, cex=1, paste("ROC-test: ",P,sep="")) dev.off() return(rbind(round(mean(auc1),3)*100,round(mean(auc3),3)*100,p)) } rf_test <- function(data, efs_table, file_name, classnumber){ e.features = which(colSums(efs_table)> mean(colSums(efs_table))) klasse = data[,classname] clnr= which(colnames(data)==classname) data = data[,-clnr] votes1 = c() real1 = c() votes3 = c() real3 = c() for(i in 1:1000) { rf1 = randomForest(as.factor(klasse)~., data= data) votes1 = cbind(votes1, rf1$votes[,2]) real1 = cbind(real1, klasse) rf3 = randomForest(as.factor(klasse)~., data = data[,e.features]) votes3 = cbind(votes3, rf3$votes[,2]) real3 = cbind(real3, klasse) } pred1 = prediction(votes1, real1) perf1 = performance(pred1, "auc") roc1=roc(klasse,rf1$votes[,2] , ci=T) pred3 = prediction(votes3, real3) perf3 = performance(pred3, "auc") roc3=roc(klasse, rf3$votes[,2], ci=T) ci1=roc1$ci ci1= gsub('95% CI:', '',ci1) ci1=round(as.numeric(ci1),1)*100 pred1 <- prediction(rf1$votes[,2], klasse) perf1 <- performance(pred1, measure = "tpr", x.measure = "fpr") auc1 <- performance(pred1, measure = "auc") auc1 <- [email protected][[1]] ci3=roc3$ci ci3= gsub('95% CI:', '',ci3) ci3=round(as.numeric(ci3),3)*100 pred3 <- prediction(rf3$votes[,2], klasse) perf3 <- performance(pred3, measure = "tpr", x.measure = "fpr") auc3 <- performance(pred3, measure = "auc") auc3 <- [email protected][[1]] r=roc.test(roc1,roc3) p = as.numeric(r$p.value) P = paste("p = ",round(p,3),sep ="") if(p<0.001){P = "p < 0.001"} d=c(0,1) pdf(paste(file_name,"_RF_ROC.pdf", sep="")) plot(perf1, avg="vertical", spread.estimate="boxplot", main="") plot(perf3, avg="vertical", spread.estimate="boxplot", main="",add=TRUE, col = 'blue') abline(d, lty=2) text(0.15, 0.9, cex=1, paste("All: ", round(mean(auc1),3)*100, "% (", format(ci1[1], nsmall=1), '...',format(ci1[3], nsmall=1), ")", sep="")) text(0.15, 1, cex=1, paste("EFS: ",round(mean(auc3),3)*100, "% (",format(ci3[1], nsmall=1), '...',format(ci3[3], nsmall=1), ")", sep=""), col='blue') text(0.8, 0.1, cex=1, paste("ROC-test: ",P,sep="")) dev.off() return(rbind(round(mean(auc1),3)*100,round(mean(auc3),3)*100,p)) } perm_logreg_test <- function(data, efs_table, file_name, classnumber, NA_threshold){ klasse = data[[1]] data = data.frame(data[,-1]) e.features = which(colSums(efs_table)> mean(colSums(efs_table))) k=length(data[,1]) prob1=c() prob2=c() prob3=c() for(i in 1:k){ Train = seq(i,to=nrow(data),by=k) training <- data[-Train, ] training.cl <- klasse[-Train] testing <- data[ Train, ] testing.cl <- klasse[Train] logreg1 = glm(as.factor(training.cl)~., data = training, family = binomial,control = list(maxit = 50)) logreg3 = glm(as.factor(training.cl)~., data = training[,e.features], family = binomial,control = list(maxit = 50)) prob1= (c(prob1,predict(logreg1, newdata=testing))) prob3= (c(prob3,predict(logreg3, newdata=testing))) } prob1=prob1[order(as.numeric(names(prob1)))] roc1=roc(klasse, prob1, ci=T) ci1=roc1$ci ci1= gsub('95% CI:', '',ci1) ci1=round(as.numeric(ci1),1)*100 pred1 <- prediction(prob1, klasse) perf1 <- performance(pred1, measure = "tpr", x.measure = "fpr") auc1 <- performance(pred1, measure = "auc") auc1 <- [email protected][[1]] prob3=prob3[order(as.numeric(names(prob3)))] roc3=roc(klasse, prob3, ci=T) ci3=roc3$ci ci3= gsub('95% CI:', '',ci3) ci3=round(as.numeric(ci3),3)*100 pred3 <- prediction(prob3, klasse) perf3 <- performance(pred3, measure = "tpr", x.measure = "fpr") auc3 <- performance(pred3, measure = "auc") auc3 <- [email protected][[1]] r=roc.test(roc1,roc3) p = as.numeric(r$p.value) P = paste("p = ",round(p,3),sep ="") if(p<0.001){P = "p < 0.001"} return(auc3) } permutation_test <- function(classnumber, NA_threshold, efs_table, p_num){ klasse = data[,clnr] data = data[,-clnr] dat.all = cbind(klasse,data) AUC1 = perm_logreg_test (dat.all, efs_table, file_name, classnumber, NA_threshold) AUC = c() for(i in 1:p_num){ klasse = sample(klasse,replace=FALSE) data.1 = cbind(klasse,data) AUC[i] = perm_logreg_test(data.1, efs_table, file_name, classnumber, NA_threshold) } ttest = t.test(AUC,alternative = "less", mu=AUC1) p.values = as.vector(ttest[["p.value"]]) return(p.values) } stability_test <- function(data, classnumber, bs_num, bs_percentage){ pos = which(data[,clnr]==1) neg = which(data[,clnr]==0) importances <- NULL print("Conducting boostrapping:") for(i in 1:bs_num){ print(i) pos_sam = sample(pos, bs_percentage*length(pos), replace = FALSE) neg_sam = sample(neg, bs_percentage*length(neg), replace = FALSE) df=0 df = rbind(data[pos_sam,], data[neg_sam,]) efs_table = ensemble_fs(df, clnr, NA_threshold=0.2, cor_threshold=0.7, runs=100, selection = c(T,T,T,T,T,T,T,T)) importances = cbind(importances, colSums(efs_table)) } return(importances) } feature_var <- function(importances){ m=NULL for(i in 1: length(importances[,1])){ m = c(m,mean(importances[i,],na.rm=TRUE)) } m = order(m,decreasing=TRUE)[1:5] vars=NULL for(i in 1:length(importances[m,1])){ vars = c(vars,var(importances[m,][i,],na.rm=TRUE)) } pdf(paste(file_name,'_Variances.pdf', sep="")) boxplot(t(importances[m,-1]),main = file_name, ylim = c(0,1)) dev.off() return(vars) } jaccard_index <- function(importances){ importances = importances[ , colSums(is.na(importances)) == 0] e.features = which(rowMeans(importances) > mean(rowMeans(importances))) l = length(e.features) x = apply(importances, 2 , order) y = tail(x,l) z = list(y) schnitt = Reduce(intersect, z) vereinigung = Reduce(union, z) index = length(schnitt)/length(vereinigung) return(index) } if(logreg == TRUE){ lg.efs = logreg_test(data, efs_table, file_name, classnumber) } else{lg.efs = rbind("Not conducted", "Not conducted","Not conducted")} if(rf == TRUE){ rf.efs = rf_test(data, efs_table, file_name, classnumber) } else{rf.efs = rbind("Not conducted", "Not conducted","Not conducted")} if(permutation == TRUE){ permutation.p.values = permutation_test(classnumber, NA_threshold, efs_table,p_num) } else{permutation.p.values = "Not conducted"} if(variances == TRUE| jaccard ==TRUE){ importances = stability_test(data, classnumber, bs_num, bs_percentage) } if(variances == TRUE){ vars = feature_var(importances) } else{vars = "Not conducted"} if(jaccard == TRUE){ jaccard_index = jaccard_index(importances) } else{jaccard_index = "Not conducted"} results = NULL results = list("AUC of LR of all parameters" = as.vector(lg.efs[1,1]), "AUC of LR of EFS parameters" = as.vector(lg.efs[2,1]), "P-value of LG-ROC test" = as.vector(lg.efs[3,1]), "AUC of RF of all parameters" = as.vector(rf.efs[1,1]), "AUC of RF of EFS parameters" = as.vector(rf.efs[2,1]), "P-value of RF-ROC test" = as.vector(rf.efs[3,1]), "P-value of permutation" = as.vector(permutation.p.values), "Variances of feature importances"= vars, "Jaccard-index"=jaccard_index) return(results) }
pvm <- function(theta, m, k, rads = FALSE) { if ( !rads ) { u <- u * pi / 180 m <- m * pi / 180 } theta <- theta %% (2 * pi) if ( k > 0 ) { theta <- theta %% (2 * pi) f <- 2 * pi * besselI(k, 0) funa <- function(u) exp(k * cos(u - m) ) prob <- as.numeric( integrate(funa, 0, theta)$value ) / f } else prob <- theta / ( 2 * pi ) prob }
library(testthat) library(synthACS) context("LOCAL -- synthetic new attribute creation") test_that("single synthetic dataset -- real df, fake ST (DF)", { levels <- c("A", "B", "C") ST <- data.frame(marital_status= rep(levels(test_micro$marital_status), each= 7), race= rep(levels(test_micro$race), 5)) ST <- do.call("rbind", replicate(3, ST, simplify=FALSE)) ST <- ST[order(ST$marital_status, ST$race),] ST$pct <- rep(c(0.33, 0.34, 0.33), 35) ST$levels <- rep(levels, 35) syn <- synthetic_new_attribute(df= test_micro, prob_name= "p", attr_name= "variable", conditional_vars= c("marital_status", "race"), sym_tbl= ST) expect_equal(sum(syn$p), 1) expect_equal(tapply(syn$p, syn$gender, sum), tapply(test_micro$p, test_micro$gender, sum)) expect_equal(tapply(syn$p, syn$marital_status, sum), tapply(test_micro$p, test_micro$marital_status, sum)) expect_equal(tapply(syn$p, syn$race, sum), tapply(test_micro$p, test_micro$race, sum)) expect_equal(nrow(test_micro) * length(levels), nrow(syn)) expect_equal(ncol(test_micro), ncol(syn) - 1) expect_true(all.equal(as.vector(tapply(syn$p, syn$variable, sum)), c(0.33, 0.34, 0.33), check.attributes=FALSE)) }) test_that("single synthetic dataset -- real df, fake ST (DT)", { levels <- c("A", "B", "C") ST <- data.frame(marital_status= rep(levels(test_micro$marital_status), each= 7), race= rep(levels(test_micro$race), 5)) ST <- do.call("rbind", replicate(3, ST, simplify=FALSE)) ST <- ST[order(ST$marital_status, ST$race),] ST$pct <- rep(c(0.33, 0.34, 0.33), 35) ST$levels <- rep(levels, 35) data.table::setDT(test_micro); data.table::setDT(ST) syn <- synthetic_new_attribute(df= test_micro, prob_name= "p", attr_name= "variable", conditional_vars= c("marital_status", "race"), sym_tbl= ST) expect_equal(sum(syn$p), 1) expect_equal(tapply(syn$p, syn$gender, sum), tapply(test_micro$p, test_micro$gender, sum)) expect_equal(tapply(syn$p, syn$marital_status, sum), tapply(test_micro$p, test_micro$marital_status, sum)) expect_equal(tapply(syn$p, syn$race, sum), tapply(test_micro$p, test_micro$race, sum)) expect_equal(nrow(test_micro) * length(levels), nrow(syn)) expect_equal(ncol(test_micro), ncol(syn) - 1) expect_true(all.equal(as.vector(tapply(syn$p, syn$variable, sum)), c(0.33, 0.34, 0.33), check.attributes=FALSE)) }) test_that("single synthetic dataset -- real DF, ST (DF)", { test_micro <- syn[[1]][[2]] work_ST <- towork[[1]] class(work_ST) <- "data.frame" syn <- synthetic_new_attribute(df= test_micro, prob_name= "p", attr_name= "transit", conditional_vars= c("emp_status", "age"), sym_tbl= work_ST) expect_equal(sum(syn$p), 1) expect_equal(tapply(syn$p, syn$emp_status, sum), tapply(test_micro$p, test_micro$emp_status, sum)) expect_equal(tapply(syn$p, syn$age, sum), tapply(test_micro$p, test_micro$age, sum)) expect_equal(tapply(syn$p, syn$race, sum), tapply(test_micro$p, test_micro$race, sum)) expect_equal(ncol(test_micro), ncol(syn) - 1) }) test_that("single synthetic dataset -- real DF, ST (DT)", { test_micro <- syn[[4]][[2]] work_ST <- towork[[4]] syn <- synthetic_new_attribute(df= test_micro, prob_name= "p", attr_name= "transit", conditional_vars= c("emp_status", "age"), sym_tbl= work_ST) expect_equal(sum(syn$p), 1) expect_equal(tapply(syn$p, syn$emp_status, sum), tapply(test_micro$p, test_micro$emp_status, sum)) expect_equal(tapply(syn$p, syn$age, sum), tapply(test_micro$p, test_micro$age, sum)) expect_equal(tapply(syn$p, syn$race, sum), tapply(test_micro$p, test_micro$race, sum)) expect_equal(ncol(test_micro), ncol(syn) - 1) }) test_that("parallel - real DF, fake ST", { levels <- c("A", "B", "C") ST <- data.frame(marital_status= rep(levels(syn[[1]][[2]]$marital_status), each= 7), race= rep(levels(syn[[2]][[2]]$race), 5)) ST <- do.call("rbind", replicate(3, ST, simplify=FALSE)) ST <- ST[order(ST$marital_status, ST$race),] ST$pct <- rep(c(0.33, 0.34, 0.33), 35) ST$levels <- rep(levels, 35) st_list <- replicate(4, ST, simplify= FALSE) syn2 <- all_geog_synthetic_new_attribute(syn, prob_name= "p", attr_name= "variable", conditional_vars= c("marital_status", "race"), st_list= st_list) expect_equal(class(syn2), c("synthACS", "list")) expect_true(is.synthACS(syn2)) expect_true(all(unlist(lapply(syn2, function(l) is.micro_synthetic(l[[2]]))))) expect_true(all.equal(unlist(lapply(syn2, function(l) sum(l[[2]]$p))), rep(1, 4), check.attributes = FALSE)) expect_equal(lapply(syn2, function(l) {tapply(l[[2]]$p, l[[2]]$marital_status, sum)}), lapply(syn, function(l) {tapply(l[[2]]$p, l[[2]]$marital_status, sum)}) ) expect_equal(lapply(syn2, function(l) {tapply(l[[2]]$p, l[[2]]$race, sum)}), lapply(syn, function(l) {tapply(l[[2]]$p, l[[2]]$race, sum)}) ) expect_true(all.equal(lapply(syn2, function(l) {as.vector(tapply(l[[2]]$p, l[[2]]$variable, sum))}), replicate(4, c(0.33, 0.34, 0.33), simplify = FALSE), check.attributes = FALSE)) })
weighted_quantile_type_selection <- function( type, pp, N, dfr, weights_NULL) { eps <- 1E-10 mm <- NULL set1 <- FALSE if ( ! weights_NULL ){ type <- -9 a1 <- dfr$w_cum <=pp if ( sum(a1) > 0 ){ ind <- which( a1 ) } else { ind <- 0 } jj <- max(ind) jj1 <- jj + 1 if (jj1 > N){ jj1 <- N} if (jj %in% c(0,-Inf)){ jj <- 1 set1 <- TRUE jj1 <- 1 } if ( jj !=jj1){ GAMMA0 <- ( pp - dfr[jj,"w_cum"] )/ ( eps + dfr[jj1,"w_cum"] - dfr[jj,"w_cum"] ) } else { GAMMA0 <- 0 } GAMMA <- GAMMA0 } if (type==6){ mm <- pp jj <- floor(N*pp + mm) gg <- N*pp + mm - jj GAMMA <- gg } if (type==7){ mm <- 1 - pp jj <- floor(N*pp + mm) gg <- N*pp + mm - jj GAMMA <- gg } if ( ! set1){ jj1 <- jj+1 } if (jj1 > N){ jj1 <- N} if (jj==0){ jj <- 1} res <- list(mm=mm, jj=jj, GAMMA=GAMMA, jj1=jj1) return(res) }
ffs_adp_outcomes_week <- function(scoring_history, pos_filter = c("QB", "RB", "WR", "TE")) { checkmate::assert_character(pos_filter) checkmate::assert_data_frame(scoring_history) assert_columns(scoring_history, c("gsis_id", "week", "season", "points")) gsis_id <- NULL fantasypros_id <- NULL pos <- NULL rank <- NULL points <- NULL week <- NULL week_outcomes <- NULL player_name <- NULL fantasypros_id <- NULL len <- NULL sh <- data.table::as.data.table(scoring_history)[!is.na(gsis_id) & week <= 16,c("gsis_id","week", "season", "points")] fp_rh <- data.table::as.data.table(ffsimulator::fp_rankings_history_week)[,-"page_pos"] dp_id <- data.table::as.data.table(ffscrapr::dp_playerids())[!is.na(gsis_id) & !is.na(fantasypros_id),c("fantasypros_id","gsis_id")] ao <- fp_rh[dp_id,on = "fantasypros_id", nomatch = 0 ][!is.na(gsis_id) & pos %in% pos_filter ][sh, on = c("season","week","gsis_id"),nomatch = 0 ][,list(week_outcomes = list(points), games_played = .N), by = c("season","pos","rank","fantasypros_id","player_name") ][,rank := lapply(rank, .ff_triplicate)] ao <- tidytable::unnest.(ao,"rank", .drop = FALSE) ao <- ao[ ,list(week_outcomes = list(c(unlist(week_outcomes))), player_name = list(player_name), fantasypros_id = list(fantasypros_id) ), by = c("pos","rank") ][,len := sapply(week_outcomes,length) ][,len := max(len)-len ][,`:=`(week_outcomes = mapply(.ff_rep_na,week_outcomes,len, SIMPLIFY = FALSE),len = NULL) ][order(pos,rank)] return(ao) } .ff_rep_na <- function(week_outcomes,len){ c(unlist(week_outcomes),rep(NA,times = len)) }
list.load <- function(file, type = tools::file_ext(file), ..., guess = c("json", "yaml", "rds", "rdata", "xml"), action = c("none", "merge", "ungroup"), progress = length(file) >= 5L) { if (length(file) == 0L) return(list()) nztype <- !is.na(type) & nzchar(type) fun <- paste("list.loadfile", tolower(type), sep = ".") fun[!nztype] <- NA_character_ guess <- tolower(guess) pb <- if (progress) txtProgressBar(min = 0L, max = length(file), style = 3L) else NULL res <- if (length(file) == 1L) list.loadfile(file, fun, guess, ..., pb = pb, index = 1L) else { items <- map(list.loadfile, list(file, fun, index = seq_along(file)), list(guess = guess, ..., pb = pb)) switch(match.arg(action), merge = do.call("list.merge", items), ungroup = list.ungroup(items), items) } if (!is.null(pb)) close(pb) res } list.loadfile <- function(file, fun, guess, ..., pb = NULL, index = NULL) { res <- NULL if (is.na(fun)) { if (!missing(guess) && length(guess) > 0L) { exprs <- lapply(paste("list.loadfile", guess, sep = "."), function(f) call(f, file)) res <- try_list(exprs, stop("Unrecognized type of file: ", file, call. = FALSE)) if (!is.null(pb)) pb$up(index) } else stop("Unrecognized type of file: ", file, call. = FALSE) } else if (exists(fun, mode = "function")) { fun <- get(fun, mode = "function") res <- fun(file, ...) if (!is.null(pb)) pb$up(index) } else { stop("Unrecognized type of file: ", file, call. = FALSE) } res } list.loadfile.json <- function(file, ...) { callwith(jsonlite::fromJSON, list(file, simplifyDataFrame = FALSE), list(...)) } list.loadfile.yaml <- function(file, ...) { yaml::yaml.load_file(file, ...) } list.loadfile.yml <- list.loadfile.yaml list.loadfile.xml <- function(file, ...) { xmlData <- XML::xmlParse(file, ...) XML::xmlToList(xmlData) } list.loadfile.rdata <- function(file, name = "x") { env <- new.env(parent = parent.frame(), size = 1L) load(file, env) env[[name]] } list.loadfile.rds <- function(file, ...) readRDS(file, ...)
idotplot <- function(x, y, indID=NULL, group=NULL, chartOpts=NULL, digits=5) { stopifnot(length(x) == length(y)) if(is.null(group)) group <- rep(1, length(x)) stopifnot(length(group) == length(x)) group <- group2numeric(group) if(is.null(indID)) indID <- get_indID(length(x), names(x), names(y), names(group)) stopifnot(length(indID) == length(x)) indID <- as.character(indID) if(is.factor(x)) x_levels <- levels(x) else x_levels <- sort(unique(x)) x <- group2numeric(x, preserveNA=TRUE) names(x) <- NULL names(y) <- NULL names(indID) <- NULL names(group) <- NULL chartOpts <- add2chartOpts(chartOpts, ylab="y", title="", xlab="group", xcategories=seq(along=x_levels), xcatlabels=x_levels) x <- list(data=list(x=x, y=y, indID=indID, group=group), chartOpts=chartOpts) if(!is.null(digits)) attr(x, "TOJSON_ARGS") <- list(digits=digits) defaultAspect <- 1 browsersize <- getPlotSize(defaultAspect) htmlwidgets::createWidget("idotplot", x, width=chartOpts$width, height=chartOpts$height, sizingPolicy=htmlwidgets::sizingPolicy( browser.defaultWidth=browsersize$width, browser.defaultHeight=browsersize$height, knitr.defaultWidth=1000, knitr.defaultHeight=1000/defaultAspect), package="qtlcharts") } idotplot_output <- function(outputId, width="100%", height="530") { htmlwidgets::shinyWidgetOutput(outputId, "idotplot", width, height, package="qtlcharts") } idotplot_render <- function(expr, env=parent.frame(), quoted=FALSE) { if(!quoted) { expr <- substitute(expr) } htmlwidgets::shinyRenderWidget(expr, idotplot_output, env, quoted=TRUE) }
print.nl <- function(x, ...) { util_print.nl(x) util_print.experiment(x@experiment) util_print.simdesign(x@simdesign) util_print.summary(x) } util_print.nl <- function(x, ...) { style_heading <- crayon::black$bold$bgWhite style_def <- crayon::green style_opt <- crayon::yellow style_na <- crayon::red cat(style_heading(paste0("\n", " NL OBJECT ", "\n"))) cat("NetLogo version = ") output <- paste0(x@nlversion, "\n") cat(ifelse(nchar(x@nlversion) > 0, style_def(output), style_na(output))) cat("NetLogo path = ") output <- paste0(x@nlpath, "\n") cat(ifelse(!identical(x@nlpath, character(0)), style_def(output), style_na(output))) cat("Model path = ") output <- paste0(x@modelpath, "\n") cat(ifelse(!identical(x@modelpath, character(0)), style_def(output), style_na(output))) cat("JVM memory = ") output <- paste0(x@jvmmem, "\n") cat(ifelse(!is.na(x@jvmmem), style_def(output), style_na(output))) } util_print.summary <- function(x, ...) { style_heading <- crayon::black$bold$bgWhite style_def <- crayon::green style_opt <- crayon::yellow style_na <- crayon::red cat(style_heading(paste0("\n", " SUMMARY ", "\n"))) cat("supported nlversion: ") output <- ifelse(x@nlversion %in% c("5.3.1", "6.0", "6.0.1", "6.0.2", "6.0.3", "6.0.4", "6.1.0", "6.1.1"), style_def("\u2713"), style_na("\u2717")) cat(paste0(output, "\n")) cat("nlpath exists on local system: ") output <- ifelse(dir.exists(x@nlpath), style_def("\u2713"), style_na("\u2717")) cat(paste0(output, "\n")) cat("modelpath exists on local system: ") output <- ifelse(file.exists(x@modelpath), style_def("\u2713"), style_na("\u2717")) cat(paste0(output, "\n")) cat("valid jvm memory: ") output <- ifelse(is.numeric(x@jvmmem), style_def("\u2713"), style_na("\u2717")) cat(paste0(output, "\n")) cat("valid experiment name: ") output <- ifelse(is.na(x@experiment@expname) | grepl("\\s", getexp(x, "expname")), style_na("\u2717"), style_def("\u2713")) cat(paste0(output, "\n")) cat("outpath exists on local system: ") output <- ifelse(dir.exists(x@experiment@outpath), style_def("\u2713"), style_na("\u2717")) cat(paste0(output, "\n")) cat("setup and go defined: ") output <- ifelse(!all(is.na(x@experiment@idsetup), is.na(x@experiment@idgo)), style_def("\u2713"), style_na("\u2717")) cat(paste0(output, "\n")) cat("variables defined: ") output <- ifelse(length(x@experiment@variables) > 0, style_def("\u2713"), style_na("\u2717")) cat(paste0(output, "\n")) if(!identical(x@modelpath, character(0))){ if(file.exists(x@modelpath)){ cat("variables present in model: ") output <- ifelse(length(x@experiment@variables) > 0 & all(names(x@experiment@variables) %in% names(report_model_parameters(x))), style_def("\u2713"), style_na("\u2717")) cat(paste0(output, "\n")) } } cat("constants defined: ") output <- ifelse(length(x@experiment@constants) > 0, style_def("\u2713"), style_na("\u2717")) cat(paste0(output, "\n")) if(!identical(x@modelpath, character(0))){ if(file.exists(x@modelpath)){ cat("constants present in model: ") output <- ifelse(length(x@experiment@constants) > 0 & all(names(x@experiment@constants) %in% names(report_model_parameters(x))), style_def("\u2713"), style_na("\u2717")) cat(paste0(output, "\n")) } } cat("metrics defined: ") output <- ifelse(length(x@experiment@metrics) > 0, style_def("\u2713"), style_na("\u2717")) cat(paste0(output, "\n")) cat("spatial Metrics defined: ") output <- ifelse(length(x@[email protected]) > 0 | length(x@[email protected]) > 0 | length(x@[email protected]) > 0, style_def("\u2713"), style_na("\u2717")) cat(paste0(output, "\n")) cat("simdesign attached: ") output <- ifelse(!is.na(x@simdesign@simmethod), style_def("\u2713"), style_na("\u2717")) cat(paste0(output, "\n")) cat("siminput parameter matrix: ") output <- ifelse(nrow(x@simdesign@siminput) > 0, style_def("\u2713"), style_na("\u2717")) cat(paste0(output, "\n")) cat("number of siminputrows: ") output <- ifelse(nrow(x@simdesign@siminput) > 0, style_def(nrow(x@simdesign@siminput)), style_na("\u2717")) cat(paste0(output, "\n")) cat("number of random seeds: ") output <- ifelse(!all(is.na(x@simdesign@simseeds)), style_def(length(x@simdesign@simseeds)), style_na("\u2717")) cat(paste0(output, "\n")) cat("estimated number of runs: ") output <- ifelse(!all(nrow(x@simdesign@siminput) == 0, is.na(x@simdesign@simseeds)), style_def(nrow(x@simdesign@siminput) * length(x@simdesign@simseeds)), style_na("\u2717")) cat(paste0(output, "\n")) cat("simoutput results attached: ") output <- ifelse(nrow(x@simdesign@simoutput) > 0, style_def("\u2713"), style_na("\u2717")) cat(paste0(output, "\n")) cat("number of runs calculated: ") output <- ifelse(nrow(x@simdesign@simoutput) > 0, style_def(length(unique(paste(x@simdesign@simoutput$'random-seed', x@simdesign@simoutput$siminputrow)))), style_na("\u2717")) cat(paste0(output, "\n")) } util_print.experiment <- function(x, ...) { style_heading <- crayon::black$bold$bgWhite style_def <- crayon::green style_opt <- crayon::yellow style_na <- crayon::red cat(style_heading(paste0("\n", " EXPERIMENT ", "\n"))) cat("Experiment name = ") output <- paste0(x@expname, "\n") cat(ifelse(!is.na(x@expname), style_def(output), style_na(output))) cat("Output path = ") output <- paste0(x@outpath, "\n") cat(ifelse(!is.na(x@outpath), style_def(output), style_na(output))) cat("NetLogo repetitions = ") output <- paste0(x@repetition, "\n") cat(ifelse(!is.na(x@repetition), style_def(output), style_na(output))) cat("Measure on each tick? = ") output <- paste0(x@tickmetrics, "\n") cat(ifelse(!is.na(x@tickmetrics), style_def(output), style_na(output))) cat("Setup procedure(s) = ") output <- paste0(paste(x@idsetup, collapse=", "), "\n") cat(ifelse(!all(is.na(x@idsetup)), style_def(output), style_na(output))) cat("Go procedure(s) = ") output <- paste0(paste(x@idgo, collapse=", "), "\n") cat(ifelse(!all(is.na(x@idgo)), style_def(output), style_na(output))) cat("Final procedure(s) = ") output <- paste0(paste(x@idfinal, collapse=", "), "\n") cat(ifelse(!all(is.na(x@idfinal)), style_def(output), style_opt(output))) cat("Run nr. widget name = ") output <- paste0(x@idrunnum, "\n") cat(ifelse(!is.na(x@idrunnum), style_def(output), style_opt(output))) cat("Runtime (ticks) = ") output <- paste0(x@runtime, "\n") cat(ifelse(!is.na(x@runtime), style_def(output), style_na(output))) cat("Report output on ticks = ") output <- paste0(paste(x@evalticks, collapse=", "), "\n") cat(ifelse(!all(is.na(x@evalticks)), style_def(output), style_opt(output))) cat("Stop condition = ") output <- paste0(x@stopcond, "\n") cat(ifelse(!is.na(x@stopcond), style_def(output), style_opt(output))) cat("Metrics (output) = ") output <- paste0(paste(x@metrics, collapse=", "), "\n") cat(ifelse(!all(is.na(x@metrics)), style_def(output), style_na(output))) cat(paste0("\n", "Turtle metrics (output)", "\n")) output <- paste0(paste(paste0(" ", names([email protected])), paste(unlist([email protected]), collapse = ", "), sep=" = "), "\n") cat(ifelse(!all(is.na([email protected])), style_def(output), style_opt(output))) cat(paste0("\n", "Patch metrics (output)", "\n")) output <- paste0(" ", paste(unlist([email protected]), collapse = ", "), "\n") cat(ifelse(!all(is.na([email protected])), style_def(output), style_opt(output))) cat(paste0("\n", "Link metrics (output)", "\n")) output <- paste0(paste(paste0(" ", names([email protected])), paste(unlist([email protected]), collapse = ", "), sep=" = "), "\n") cat(ifelse(!all(is.na([email protected])), style_def(output), style_opt(output))) cat(paste0("\n", "Variable parameters (input)", "\n")) output <- paste0(paste(paste0(" ", names(x@variables)), x@variables, collapse="\n", sep=" = "), "\n") cat(ifelse(!all(is.na(x@variables)), style_def(output), style_opt(output))) cat(paste0("\n", "Constant parameters (input)", "\n")) output <- paste0(paste(paste0(" ", names(x@constants)), x@constants, sep=" = ", collapse="\n"), "\n") cat(ifelse(!all(is.na(x@constants)), style_def(output), style_opt(output))) } util_print.simdesign <- function(x, ...) { style_heading <- crayon::black$bold$bgWhite style_def <- crayon::green style_opt <- crayon::yellow style_na <- crayon::red cat(style_heading(paste0("\n", " SIMDESIGN ", "\n"))) cat("Simulation method = ") output <- paste0(x@simmethod, "\n") cat(ifelse(!identical(x@simmethod, character(0)), style_def(output), style_na(output))) cat("Simulation object = ") output <- paste0(x@simobject, "\n") cat(ifelse(length(x@simmethod) > 0, style_def(output), style_opt(output))) cat("Generated random seeds = ") output <- paste0(paste(x@simseeds, collapse=", "), "\n") cat(ifelse(!all(is.na(x@simseeds)), style_def(output), style_opt(output))) cat(paste0("\n", "Parameter matrix (input)", "\n")) print(x@siminput, width = Inf) cat(paste0("\n", "Simulation results (output)", "\n")) print(x@simoutput, width = Inf) }
run_tuner <- function(app_title, soln_templates_dir, knit_wd, tabs = c("lint","html","correctness"), lint_list, corr_cols_to_drop = c(1,2,4,5), max_time = 120, summary_header = " permission_to_install = FALSE, ...) { soln_fnames <- list.files(soln_templates_dir, full.names = TRUE) soln_choices <- sapply(soln_fnames, function(x) rmarkdown::yaml_front_matter(x)$title, USE.NAMES = FALSE) if(anyDuplicated(soln_choices)){ stop("Duplicate titles found in solution templates. Please resolve.") } tabs <- match.arg(tabs,several.ok = TRUE) soln_out_all <- lapply(soln_fnames, populate_soln_env, knit_root_dir = knit_wd) names(soln_out_all) <- soln_choices chunk_out_all <- lapply(soln_fnames, get_summary_output) names(chunk_out_all) <- soln_choices if(missing(lint_list)) { lint_list <- c(lintr::T_and_F_symbol_linter, lintr::assignment_linter, lintr::closed_curly_linter, lintr::commas_linter, lintr::equals_na_linter, lintr::function_left_parentheses_linter, lintr::infix_spaces_linter, lintr::line_length_linter, lintr::no_tab_linter, lintr::open_curly_linter, lintr::paren_brace_linter, lintr::absolute_path_linter, lintr::pipe_continuation_linter, lintr::spaces_inside_linter, lintr::trailing_blank_lines_linter, lintr::trailing_whitespace_linter, lintr::unneeded_concatenation_linter) } full_tabs = c("lint","html","correctness") lint_tabs <- tabPanel("Lint Check",uiOutput(outputId = "lint_check")) html_tabs <- tabPanel("HTML Check",uiOutput(outputId = "html_check")) correctness_tabs <- tabPanel("Correctness check",tableOutput(outputId = "corr_check")) list1 <- list(lint_tabs,html_tabs,correctness_tabs) index_match = match(tabs , full_tabs) list_of_tabs <- list1[index_match] internalwrapper <- function(...){ tabsetPanel(..., id = NULL, selected = NULL, type ="tabs") } panelOutput <- do.call("internalwrapper",list_of_tabs) ui <- fluidPage( titlePanel(title = app_title), fluidRow( column(4, wellPanel( selectInput( inputId = "selectfileweek", label = h4("Select tutorial number:"), choices = soln_choices ), fileInput( inputId = "fileupload", label = h4("Upload your solution:"), width = '100%', multiple = FALSE ), actionButton("goButton", "Check solution!"), hr(), shiny::tags$small('autoharp solution checker, 2020.', br(), 'Found a bug? Report it', a(href='mailto:[email protected]','here.')) ) ), column(8, panelOutput) ) ) server <- function(input, output, session) { lint_df <- reactive({ input$goButton isolate({ if(is.null(input$fileupload)){ return(NULL) } else { file1 <- input$fileupload all_lints <- lintr::lint(file1$datapath, linters= lint_list) if(length(all_lints) > 0) { ll <- sapply(all_lints, function(x) x$line_number) mm <- sapply(all_lints, function(x) x$message) l_df <- data.frame(ll, mm, stringsAsFactors = FALSE) colnames(l_df) <- c("Line", "Message") l_df2 <- renderTable(l_df) } else { l_df2 <- h5(br(), "No lints found. Nice job!") } } }) l_df2 }) sess_tmp_dir <- tempfile("rmd_out") dir.create(sess_tmp_dir) session$onSessionEnded(function() { unlink(sess_tmp_dir, TRUE) }) output$lint_check <- renderUI({ fluidPage(lint_df()) }) htmlUI <- reactive({ input$goButton isolate({ if(is.null(input$fileupload)) { return(NULL) } else { file1 <- input$fileupload progress <- shiny::Progress$new(session, min=1, max=10) on.exit(progress$close()) progress$set(message="Checking libraries") lib_used <- get_libraries(file1$datapath) lib_used_msg <- paste('Libraries used: ', paste0(lib_used, collapse=", ")) lib_to_install <- 'Libraries to install: None' lib_error <- 'Installation logs: --' if(!is.null(lib_used)) { id <- !(sapply(lib_used, quietly=TRUE, requireNamespace)) lib_needed <- lib_used[id] if(length(lib_needed) > 0) { if(!permission_to_install) { lib_error <- paste('Installation logs: Do Not Install') lib_to_install <- paste('Need to install:', paste0(lib_needed, collapse=", ")) return(list(used=lib_used_msg, install=lib_to_install, error=lib_error, html=NULL, correctness=NULL)) } lib_to_install <- paste('Need to install:', paste0(lib_needed, collapse=", ")) showNotification("Installing packages, please wait a while..") progress$set(message="Installing libraries", value=2) try_install <- tryCatch(utils::install.packages(lib_needed, dependencies = TRUE), error = function(e) return(e)) if("error" %in% class(try_install)) { lib_error <- paste('Installation logs:', conditionMessage(try_install)) return(list(used=lib_used_msg, install=lib_to_install, error=lib_error, html=NULL, correctness=NULL)) } else { lib_error <- paste('Installation logs: All OK!') } } } soln_to_use <- input$selectfileweek progress$set(message="Rendering file", value=4) try_html <- tryCatch(render_one(file1$datapath, out_dir = sess_tmp_dir, knit_root_dir = knit_wd, max_time_per_run = max_time, soln_stuff = soln_out_all[[soln_to_use]]), error = function(e) return(e)) progress$set(message="Almost done.. ", value=8) return(list(used=lib_used_msg, install=lib_to_install, error=lib_error, html=try_html)) } }) }) output$html_check <- renderUI({ if(is.null(htmlUI()$html)){ return(p(h5(htmlUI()$used), h5(htmlUI()$install), h5(htmlUI()$error), hr())) } else { if(!("data.frame" %in% class(htmlUI()$html))) { log_out <- log_summary(file.path(sess_tmp_dir, "render_one.log")) render_error <- paste('Render logs:', utils::tail(log_out$error_message, 1)) return(p(h6(htmlUI()$used), h6(htmlUI()$install), h6(htmlUI()$error), hr(), h6(render_error))) } if(htmlUI()$html$run_status[1] == "FAIL") { log_out <- log_summary(file.path(sess_tmp_dir, "render_one.log")) render_error <- paste('Render logs:', utils::tail(log_out$error_message, 1)) return(p(h6(htmlUI()$used), h6(htmlUI()$install), h6(htmlUI()$error), hr(), h6(render_error))) } addResourcePath("test", sess_tmp_dir) return(p(h6(htmlUI()$used), h6(htmlUI()$install), h6(htmlUI()$error), hr(), shiny::tags$iframe(src="test/0.html", height="1000", width="800", frameborder="0"))) } }) summary_df <- reactive({ input$goButton isolate({ if(is.null(input$fileupload)){ return(NULL) } else { soln_to_use <- input$selectfileweek summary_df2 <- chunk_out_all[[soln_to_use]] } }) summary_df2 }) output$corr_check <- renderUI({ fluidPage( fluidRow( renderTable({ if(is.null(htmlUI())){ return(NULL) } if("data.frame" %in% class(htmlUI()$html)){ if(ncol(htmlUI()$html) == 3) { return( htmlUI()$html[,3]) } else { return(htmlUI()$html[,-corr_cols_to_drop]) } } }) ), fluidRow( fluidPage(summary_df()) ) ) }) } app <- shiny::shinyApp(ui, server) app } get_summary_output <- function (rmd_file, summary_header = " dir = tempdir()){ all_non_chunks <- extract_non_chunks(rmd_file) ind <- which(all_non_chunks == summary_header) if(length(ind) != 0) { display_chunks <- all_non_chunks[ind:length(all_non_chunks)] fp <- file.path(dir, 'summary_chunk_info.Rmd') writeLines(display_chunks, con = fp) summary_df <- shiny::withMathJax(shiny::includeMarkdown(fp)) unlink(fp) } else { summary_df <- h5(br(), "No summary found") } return(summary_df) }
DLtest <- function(y,p) { ym <- as.matrix(y-mean(y)) n <- nrow(ym); s2 <- sum(ym^2)/(n-p) sum3 <- numeric(n-p) sum2 <- 0 for(j in (p+1):n) { sum1 <- 0 for(i in (p+1):n){ indicate <- 0 zi <- ym[(i-1):(i-p),1] zj <- ym[(j-1):(j-p),1] tem1 <- as.numeric(zi <= zj) if( prod(tem1) == 1) indicate <- 1 sum1 <- sum1 + ym[i,1]*indicate } sum2 <- sum2 + sum1^2 sum3[j-p] <- abs(sum1/sqrt(n-p)) } Cp <- sum2/(s2*(n-p)^2) Kp <- max(sum3)/sqrt(s2) return(list(Cpstat=Cp,Kpstat=Kp)) }
fdepthv2<-function(m,pts=NA,plotit=TRUE){ m<-elimna(m) if(!is.na(pts[1]))remm<-m if(!is.matrix(m))dep<-unidepth(m) if(is.matrix(m)){ nm<-nrow(m) nt<-nm nm1<-nm+1 if(!is.na(pts[1])){ if(ncol(m)!=ncol(pts))stop("Number of columns of m is not equal to number of columns for pts") nt<-nm+nrow(pts) }} if(ncol(m)==1)depth<-unidepth(m) if(ncol(m)>1){ m<-elimna(m) nc<-(nrow(m)^2-nrow(m))/2 if(is.na(pts[1]))mdep <- matrix(0,nrow=nc,ncol=nrow(m)) if(!is.na(pts[1])){ mdep <- matrix(0,nrow=nc,ncol=nrow(pts)) } ic<-0 for (iall in 1:nm){ for (i in 1:nm){ if(iall < i){ ic<-ic+1 B<-m[i,]-m[iall,] dis<-NA BB<-B^2 bot<-sum(BB) if(bot!=0){ if(is.na(pts[1])){ for (j in 1:nrow(m)){ A<-m[j,]-m[iall,] temp<-sum(A*B)*B/bot dis[j]<-sign(sum(A*B))*sqrt(sum(temp^2)) }} if(!is.na(pts[1])){ m<-rbind(remm,pts) for (j in 1:nrow(m)){ A<-m[j,]-m[iall,] temp<-sum(A*B)*B/bot dis[j]<-sign(sum(A*B))*sqrt(sum(temp^2)) }} if(is.na(pts[1]))mdep[ic,]<-unidepth(dis) if(!is.na(pts[1])){ mdep[ic,]<-unidepth(dis[1:nm],dis[nm1:nrow(m)]) }} if(bot==0)mdep[ic,]<-rep(0,ncol(mdep)) }}} dep<-apply(mdep,2,min) } if(ncol(m)==2 &&is.na(pts[1])){ flag<-chull(m) dep[flag]<-min(dep) } if(ncol(m)==2){ if(is.na(pts[1]) && plotit){ plot(m) x<-m temp<-dep flag<-(temp>=median(temp)) xx<-x[flag,] xord<-order(xx[,1]) xx<-xx[xord,] temp<-chull(xx) xord<-order(xx[,1]) xx<-xx[xord,] temp<-chull(xx) lines(xx[temp,]) lines(xx[c(temp[1],temp[length(temp)]),]) }} dep }
Tensor$set("public", "__and__", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = '__and__', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "__iand__", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = '__iand__', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "__ilshift__", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = '__ilshift__', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "__ior__", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = '__ior__', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "__irshift__", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = '__irshift__', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "__ixor__", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = '__ixor__', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "__lshift__", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = '__lshift__', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "__or__", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = '__or__', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "__rshift__", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = '__rshift__', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "__xor__", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = '__xor__', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "__backward", function(inputs, gradient = list(), retain_graph = NULL, create_graph = FALSE) { args <- mget(x = c("inputs", "gradient", "retain_graph", "create_graph")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", inputs = "TensorList", gradient = "Tensor", retain_graph = "bool", create_graph = "bool") nd_args <- c("self", "inputs") return_types <- list(list("void")) call_c_function( fun_name = '_backward', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "_coalesced_", function(coalesced) { args <- mget(x = c("coalesced")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", coalesced = "bool") nd_args <- c("self", "coalesced") return_types <- list(list('Tensor')) call_c_function( fun_name = '_coalesced_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "_dimI", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('int64_t')) call_c_function( fun_name = '_dimI', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "_dimV", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('int64_t')) call_c_function( fun_name = '_dimV', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "_fw_primal", function(level) { args <- mget(x = c("level")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", level = "int64_t") nd_args <- c("self", "level") return_types <- list(list('Tensor')) call_c_function( fun_name = '_fw_primal', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "_indices", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = '_indices', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "_nnz", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('int64_t')) call_c_function( fun_name = '_nnz', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "_values", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = '_values', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "_version", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('int64_t')) call_c_function( fun_name = '_version', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "abs", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'abs', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "abs_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'abs_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "absolute", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'absolute', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "absolute_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'absolute_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "acos", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'acos', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "acos_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'acos_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "acosh", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'acosh', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "acosh_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'acosh_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "add", function(other, alpha = 1L) { args <- mget(x = c("other", "alpha")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Tensor", "Scalar"), alpha = "Scalar") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'add', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "add_", function(other, alpha = 1L) { args <- mget(x = c("other", "alpha")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Tensor", "Scalar"), alpha = "Scalar") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'add_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "addbmm", function(batch1, batch2, beta = 1L, alpha = 1L) { args <- mget(x = c("batch1", "batch2", "beta", "alpha")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", batch1 = "Tensor", batch2 = "Tensor", beta = "Scalar", alpha = "Scalar") nd_args <- c("self", "batch1", "batch2") return_types <- list(list('Tensor')) call_c_function( fun_name = 'addbmm', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "addbmm_", function(batch1, batch2, beta = 1L, alpha = 1L) { args <- mget(x = c("batch1", "batch2", "beta", "alpha")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", batch1 = "Tensor", batch2 = "Tensor", beta = "Scalar", alpha = "Scalar") nd_args <- c("self", "batch1", "batch2") return_types <- list(list('Tensor')) call_c_function( fun_name = 'addbmm_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "addcdiv", function(tensor1, tensor2, value = 1L) { args <- mget(x = c("tensor1", "tensor2", "value")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", tensor1 = "Tensor", tensor2 = "Tensor", value = "Scalar") nd_args <- c("self", "tensor1", "tensor2") return_types <- list(list('Tensor')) call_c_function( fun_name = 'addcdiv', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "addcdiv_", function(tensor1, tensor2, value = 1L) { args <- mget(x = c("tensor1", "tensor2", "value")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", tensor1 = "Tensor", tensor2 = "Tensor", value = "Scalar") nd_args <- c("self", "tensor1", "tensor2") return_types <- list(list('Tensor')) call_c_function( fun_name = 'addcdiv_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "addcmul", function(tensor1, tensor2, value = 1L) { args <- mget(x = c("tensor1", "tensor2", "value")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", tensor1 = "Tensor", tensor2 = "Tensor", value = "Scalar") nd_args <- c("self", "tensor1", "tensor2") return_types <- list(list('Tensor')) call_c_function( fun_name = 'addcmul', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "addcmul_", function(tensor1, tensor2, value = 1L) { args <- mget(x = c("tensor1", "tensor2", "value")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", tensor1 = "Tensor", tensor2 = "Tensor", value = "Scalar") nd_args <- c("self", "tensor1", "tensor2") return_types <- list(list('Tensor')) call_c_function( fun_name = 'addcmul_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "addmm", function(mat1, mat2, beta = 1L, alpha = 1L) { args <- mget(x = c("mat1", "mat2", "beta", "alpha")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", mat1 = "Tensor", mat2 = "Tensor", beta = "Scalar", alpha = "Scalar") nd_args <- c("self", "mat1", "mat2") return_types <- list(list('Tensor')) call_c_function( fun_name = 'addmm', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "addmm_", function(mat1, mat2, beta = 1L, alpha = 1L) { args <- mget(x = c("mat1", "mat2", "beta", "alpha")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", mat1 = "Tensor", mat2 = "Tensor", beta = "Scalar", alpha = "Scalar") nd_args <- c("self", "mat1", "mat2") return_types <- list(list('Tensor')) call_c_function( fun_name = 'addmm_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "addmv", function(mat, vec, beta = 1L, alpha = 1L) { args <- mget(x = c("mat", "vec", "beta", "alpha")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", mat = "Tensor", vec = "Tensor", beta = "Scalar", alpha = "Scalar") nd_args <- c("self", "mat", "vec") return_types <- list(list('Tensor')) call_c_function( fun_name = 'addmv', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "addmv_", function(mat, vec, beta = 1L, alpha = 1L) { args <- mget(x = c("mat", "vec", "beta", "alpha")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", mat = "Tensor", vec = "Tensor", beta = "Scalar", alpha = "Scalar") nd_args <- c("self", "mat", "vec") return_types <- list(list('Tensor')) call_c_function( fun_name = 'addmv_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "addr", function(vec1, vec2, beta = 1L, alpha = 1L) { args <- mget(x = c("vec1", "vec2", "beta", "alpha")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", vec1 = "Tensor", vec2 = "Tensor", beta = "Scalar", alpha = "Scalar") nd_args <- c("self", "vec1", "vec2") return_types <- list(list('Tensor')) call_c_function( fun_name = 'addr', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "addr_", function(vec1, vec2, beta = 1L, alpha = 1L) { args <- mget(x = c("vec1", "vec2", "beta", "alpha")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", vec1 = "Tensor", vec2 = "Tensor", beta = "Scalar", alpha = "Scalar") nd_args <- c("self", "vec1", "vec2") return_types <- list(list('Tensor')) call_c_function( fun_name = 'addr_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "alias", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'alias', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "align_as", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'align_as', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "align_to", function(names, order, ellipsis_idx) { args <- mget(x = c("names", "order", "ellipsis_idx")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", names = "DimnameList", order = "DimnameList", ellipsis_idx = "int64_t") nd_args <- c("self", "names", "order", "ellipsis_idx") return_types <- list(list('Tensor')) call_c_function( fun_name = 'align_to', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "all", function(dim, keepdim = FALSE) { args <- mget(x = c("dim", "keepdim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), keepdim = "bool") nd_args <- c("self", "dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'all', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "allclose", function(other, rtol = 0.000010, atol = 0.000000, equal_nan = FALSE) { args <- mget(x = c("other", "rtol", "atol", "equal_nan")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor", rtol = "double", atol = "double", equal_nan = "bool") nd_args <- c("self", "other") return_types <- list(list('bool')) call_c_function( fun_name = 'allclose', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "amax", function(dim = list(), keepdim = FALSE) { args <- mget(x = c("dim", "keepdim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = "IntArrayRef", keepdim = "bool") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'amax', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "amin", function(dim = list(), keepdim = FALSE) { args <- mget(x = c("dim", "keepdim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = "IntArrayRef", keepdim = "bool") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'amin', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "angle", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'angle', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "any", function(dim, keepdim = FALSE) { args <- mget(x = c("dim", "keepdim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), keepdim = "bool") nd_args <- c("self", "dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'any', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "arccos", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'arccos', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "arccos_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'arccos_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "arccosh", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'arccosh', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "arccosh_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'arccosh_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "arcsin", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'arcsin', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "arcsin_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'arcsin_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "arcsinh", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'arcsinh', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "arcsinh_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'arcsinh_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "arctan", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'arctan', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "arctan_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'arctan_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "arctanh", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'arctanh', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "arctanh_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'arctanh_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_argmax", function(dim = NULL, keepdim = FALSE) { args <- mget(x = c("dim", "keepdim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = "int64_t", keepdim = "bool") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'argmax', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_argmin", function(dim = NULL, keepdim = FALSE) { args <- mget(x = c("dim", "keepdim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = "int64_t", keepdim = "bool") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'argmin', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_argsort", function(dim = -1L, descending = FALSE) { args <- mget(x = c("dim", "descending")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), descending = "bool") nd_args <- c("self", "dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'argsort', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "as_strided", function(size, stride, storage_offset = NULL) { args <- mget(x = c("size", "stride", "storage_offset")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", size = "IntArrayRef", stride = "IntArrayRef", storage_offset = "int64_t") nd_args <- c("self", "size", "stride") return_types <- list(list('Tensor')) call_c_function( fun_name = 'as_strided', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "as_strided_", function(size, stride, storage_offset = NULL) { args <- mget(x = c("size", "stride", "storage_offset")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", size = "IntArrayRef", stride = "IntArrayRef", storage_offset = "int64_t") nd_args <- c("self", "size", "stride") return_types <- list(list('Tensor')) call_c_function( fun_name = 'as_strided_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "asin", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'asin', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "asin_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'asin_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "asinh", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'asinh', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "asinh_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'asinh_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "atan", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'atan', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "atan_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'atan_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "atan2", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'atan2', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "atan2_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'atan2_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "atanh", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'atanh', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "atanh_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'atanh_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "baddbmm", function(batch1, batch2, beta = 1L, alpha = 1L) { args <- mget(x = c("batch1", "batch2", "beta", "alpha")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", batch1 = "Tensor", batch2 = "Tensor", beta = "Scalar", alpha = "Scalar") nd_args <- c("self", "batch1", "batch2") return_types <- list(list('Tensor')) call_c_function( fun_name = 'baddbmm', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "baddbmm_", function(batch1, batch2, beta = 1L, alpha = 1L) { args <- mget(x = c("batch1", "batch2", "beta", "alpha")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", batch1 = "Tensor", batch2 = "Tensor", beta = "Scalar", alpha = "Scalar") nd_args <- c("self", "batch1", "batch2") return_types <- list(list('Tensor')) call_c_function( fun_name = 'baddbmm_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "bernoulli", function(p, generator = NULL) { args <- mget(x = c("p", "generator")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", p = "double", generator = "Generator") nd_args <- c("self", "p") return_types <- list(list('Tensor')) call_c_function( fun_name = 'bernoulli', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "bernoulli_", function(p = 0.500000, generator = NULL) { args <- mget(x = c("p", "generator")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", p = c("Tensor", "double"), generator = "Generator") nd_args <- c("self", "p") return_types <- list(list('Tensor')) call_c_function( fun_name = 'bernoulli_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "bincount", function(weights = list(), minlength = 0L) { args <- mget(x = c("weights", "minlength")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", weights = "Tensor", minlength = "int64_t") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'bincount', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "bitwise_and", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'bitwise_and', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "bitwise_and_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'bitwise_and_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "bitwise_not", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'bitwise_not', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "bitwise_not_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'bitwise_not_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "bitwise_or", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'bitwise_or', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "bitwise_or_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'bitwise_or_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "bitwise_xor", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'bitwise_xor', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "bitwise_xor_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'bitwise_xor_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "bmm", function(mat2) { args <- mget(x = c("mat2")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", mat2 = "Tensor") nd_args <- c("self", "mat2") return_types <- list(list('Tensor')) call_c_function( fun_name = 'bmm', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "broadcast_to", function(size) { args <- mget(x = c("size")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", size = "IntArrayRef") nd_args <- c("self", "size") return_types <- list(list('Tensor')) call_c_function( fun_name = 'broadcast_to', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "cauchy_", function(median = 0L, sigma = 1L, generator = NULL) { args <- mget(x = c("median", "sigma", "generator")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", median = "double", sigma = "double", generator = "Generator") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'cauchy_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "ceil", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'ceil', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "ceil_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'ceil_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "cholesky", function(upper = FALSE) { args <- mget(x = c("upper")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", upper = "bool") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'cholesky', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "cholesky_inverse", function(upper = FALSE) { args <- mget(x = c("upper")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", upper = "bool") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'cholesky_inverse', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "cholesky_solve", function(input2, upper = FALSE) { args <- mget(x = c("input2", "upper")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", input2 = "Tensor", upper = "bool") nd_args <- c("self", "input2") return_types <- list(list('Tensor')) call_c_function( fun_name = 'cholesky_solve', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "chunk", function(chunks, dim = 1L) { args <- mget(x = c("chunks", "dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", chunks = "int64_t", dim = "int64_t") nd_args <- c("self", "chunks") return_types <- list(list('TensorList')) call_c_function( fun_name = 'chunk', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "clamp", function(min = NULL, max = NULL) { args <- mget(x = c("min", "max")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", min = c("Scalar", "Tensor"), max = c("Scalar", "Tensor")) nd_args <- c("self", "min", "max") return_types <- list(list('Tensor')) call_c_function( fun_name = 'clamp', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "clamp_", function(min = NULL, max = NULL) { args <- mget(x = c("min", "max")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", min = c("Scalar", "Tensor"), max = c("Scalar", "Tensor")) nd_args <- c("self", "min", "max") return_types <- list(list('Tensor')) call_c_function( fun_name = 'clamp_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "clamp_max", function(max) { args <- mget(x = c("max")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", max = c("Scalar", "Tensor")) nd_args <- c("self", "max") return_types <- list(list('Tensor')) call_c_function( fun_name = 'clamp_max', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "clamp_max_", function(max) { args <- mget(x = c("max")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", max = c("Scalar", "Tensor")) nd_args <- c("self", "max") return_types <- list(list('Tensor')) call_c_function( fun_name = 'clamp_max_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "clamp_min", function(min) { args <- mget(x = c("min")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", min = c("Scalar", "Tensor")) nd_args <- c("self", "min") return_types <- list(list('Tensor')) call_c_function( fun_name = 'clamp_min', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "clamp_min_", function(min) { args <- mget(x = c("min")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", min = c("Scalar", "Tensor")) nd_args <- c("self", "min") return_types <- list(list('Tensor')) call_c_function( fun_name = 'clamp_min_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "clip", function(min = NULL, max = NULL) { args <- mget(x = c("min", "max")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", min = c("Scalar", "Tensor"), max = c("Scalar", "Tensor")) nd_args <- c("self", "min", "max") return_types <- list(list('Tensor')) call_c_function( fun_name = 'clip', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "clip_", function(min = NULL, max = NULL) { args <- mget(x = c("min", "max")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", min = c("Scalar", "Tensor"), max = c("Scalar", "Tensor")) nd_args <- c("self", "min", "max") return_types <- list(list('Tensor')) call_c_function( fun_name = 'clip_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "clone", function(memory_format = NULL) { args <- mget(x = c("memory_format")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", memory_format = "MemoryFormat") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'clone', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "coalesce", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'coalesce', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "col_indices", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'col_indices', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "conj", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'conj', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "contiguous", function(memory_format = torch_contiguous_format()) { args <- mget(x = c("memory_format")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", memory_format = "MemoryFormat") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'contiguous', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_copy_", function(src, non_blocking = FALSE) { args <- mget(x = c("src", "non_blocking")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", src = "Tensor", non_blocking = "bool") nd_args <- c("self", "src") return_types <- list(list('Tensor')) call_c_function( fun_name = 'copy_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "copysign", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Tensor", "Scalar")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'copysign', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "copysign_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Tensor", "Scalar")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'copysign_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "cos", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'cos', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "cos_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'cos_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "cosh", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'cosh', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "cosh_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'cosh_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "count_nonzero", function(dim = NULL) { args <- mget(x = c("dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("IntArrayRef", "int64_t")) nd_args <- c("self", "dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'count_nonzero', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "cross", function(other, dim = NULL) { args <- mget(x = c("other", "dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor", dim = "int64_t") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'cross', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "crow_indices", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'crow_indices', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "cummax", function(dim) { args <- mget(x = c("dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname")) nd_args <- c("self", "dim") return_types <- list(list("Tensor", "Tensor")) call_c_function( fun_name = 'cummax', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "cummin", function(dim) { args <- mget(x = c("dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname")) nd_args <- c("self", "dim") return_types <- list(list("Tensor", "Tensor")) call_c_function( fun_name = 'cummin', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "cumprod", function(dim, dtype = NULL) { args <- mget(x = c("dim", "dtype")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), dtype = "ScalarType") nd_args <- c("self", "dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'cumprod', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "cumprod_", function(dim, dtype = NULL) { args <- mget(x = c("dim", "dtype")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), dtype = "ScalarType") nd_args <- c("self", "dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'cumprod_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "cumsum", function(dim, dtype = NULL) { args <- mget(x = c("dim", "dtype")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), dtype = "ScalarType") nd_args <- c("self", "dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'cumsum', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "cumsum_", function(dim, dtype = NULL) { args <- mget(x = c("dim", "dtype")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), dtype = "ScalarType") nd_args <- c("self", "dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'cumsum_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "data", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'data', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "deg2rad", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'deg2rad', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "deg2rad_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'deg2rad_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "dense_dim", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('int64_t')) call_c_function( fun_name = 'dense_dim', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "dequantize", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'dequantize', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "det", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'det', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "detach", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'detach', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "detach_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'detach_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "diag", function(diagonal = 0L) { args <- mget(x = c("diagonal")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", diagonal = "int64_t") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'diag', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "diag_embed", function(offset = 0L, dim1 = -2L, dim2 = -1L) { args <- mget(x = c("offset", "dim1", "dim2")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", offset = "int64_t", dim1 = "int64_t", dim2 = "int64_t") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'diag_embed', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "diagflat", function(offset = 0L) { args <- mget(x = c("offset")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", offset = "int64_t") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'diagflat', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "diagonal", function(outdim, dim1 = 1L, dim2 = 2L, offset = 0L) { args <- mget(x = c("outdim", "dim1", "dim2", "offset")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", outdim = "Dimname", dim1 = c("int64_t", "Dimname"), dim2 = c("int64_t", "Dimname"), offset = "int64_t") nd_args <- c("self", "outdim", "dim1", "dim2") return_types <- list(list('Tensor')) call_c_function( fun_name = 'diagonal', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "diff", function(n = 1L, dim = -1L, prepend = list(), append = list()) { args <- mget(x = c("n", "dim", "prepend", "append")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", n = "int64_t", dim = "int64_t", prepend = "Tensor", append = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'diff', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "digamma", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'digamma', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "digamma_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'digamma_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "dist", function(other, p = 2L) { args <- mget(x = c("other", "p")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor", p = "Scalar") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'dist', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "div", function(other, rounding_mode) { args <- mget(x = c("other", "rounding_mode")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Tensor", "Scalar"), rounding_mode = "std::string") nd_args <- c("self", "other", "rounding_mode") return_types <- list(list('Tensor')) call_c_function( fun_name = 'div', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "div_", function(other, rounding_mode) { args <- mget(x = c("other", "rounding_mode")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Tensor", "Scalar"), rounding_mode = "std::string") nd_args <- c("self", "other", "rounding_mode") return_types <- list(list('Tensor')) call_c_function( fun_name = 'div_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "divide", function(other, rounding_mode) { args <- mget(x = c("other", "rounding_mode")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Tensor", "Scalar"), rounding_mode = "std::string") nd_args <- c("self", "other", "rounding_mode") return_types <- list(list('Tensor')) call_c_function( fun_name = 'divide', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "divide_", function(other, rounding_mode) { args <- mget(x = c("other", "rounding_mode")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Tensor", "Scalar"), rounding_mode = "std::string") nd_args <- c("self", "other", "rounding_mode") return_types <- list(list('Tensor')) call_c_function( fun_name = 'divide_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "dot", function(tensor) { args <- mget(x = c("tensor")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", tensor = "Tensor") nd_args <- c("self", "tensor") return_types <- list(list('Tensor')) call_c_function( fun_name = 'dot', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "dsplit", function(indices, sections) { args <- mget(x = c("indices", "sections")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", indices = "IntArrayRef", sections = "int64_t") nd_args <- c("self", "indices", "sections") return_types <- list(list('TensorList')) call_c_function( fun_name = 'dsplit', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "eig", function(eigenvectors = FALSE) { args <- mget(x = c("eigenvectors")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", eigenvectors = "bool") nd_args <- "self" return_types <- list(list("Tensor", "Tensor")) call_c_function( fun_name = 'eig', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "eq", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'eq', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "eq_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'eq_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "equal", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('bool')) call_c_function( fun_name = 'equal', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "erf", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'erf', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "erf_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'erf_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "erfc", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'erfc', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "erfc_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'erfc_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "erfinv", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'erfinv', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "erfinv_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'erfinv_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "exp", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'exp', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "exp_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'exp_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "exp2", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'exp2', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "exp2_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'exp2_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "expand", function(size, implicit = FALSE) { args <- mget(x = c("size", "implicit")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", size = "IntArrayRef", implicit = "bool") nd_args <- c("self", "size") return_types <- list(list('Tensor')) call_c_function( fun_name = 'expand', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "expand_as", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'expand_as', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "expm1", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'expm1', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "expm1_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'expm1_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "exponential_", function(lambd = 1L, generator = NULL) { args <- mget(x = c("lambd", "generator")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", lambd = "double", generator = "Generator") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'exponential_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "fill_", function(value) { args <- mget(x = c("value")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", value = c("Scalar", "Tensor")) nd_args <- c("self", "value") return_types <- list(list('Tensor')) call_c_function( fun_name = 'fill_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "fill_diagonal_", function(fill_value, wrap = FALSE) { args <- mget(x = c("fill_value", "wrap")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", fill_value = "Scalar", wrap = "bool") nd_args <- c("self", "fill_value") return_types <- list(list('Tensor')) call_c_function( fun_name = 'fill_diagonal_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "fix", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'fix', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "fix_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'fix_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "flatten", function(dims, start_dim = 1L, end_dim = -1L, out_dim) { args <- mget(x = c("dims", "start_dim", "end_dim", "out_dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dims = "DimnameList", start_dim = c("int64_t", "Dimname"), end_dim = c("int64_t", "Dimname"), out_dim = "Dimname") nd_args <- c("self", "dims", "start_dim", "end_dim", "out_dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'flatten', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "flip", function(dims) { args <- mget(x = c("dims")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dims = "IntArrayRef") nd_args <- c("self", "dims") return_types <- list(list('Tensor')) call_c_function( fun_name = 'flip', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "fliplr", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'fliplr', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "flipud", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'flipud', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "float_power", function(exponent) { args <- mget(x = c("exponent")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", exponent = c("Tensor", "Scalar")) nd_args <- c("self", "exponent") return_types <- list(list('Tensor')) call_c_function( fun_name = 'float_power', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "float_power_", function(exponent) { args <- mget(x = c("exponent")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", exponent = c("Scalar", "Tensor")) nd_args <- c("self", "exponent") return_types <- list(list('Tensor')) call_c_function( fun_name = 'float_power_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "floor", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'floor', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "floor_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'floor_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "floor_divide", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Tensor", "Scalar")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'floor_divide', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "floor_divide_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Tensor", "Scalar")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'floor_divide_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "fmax", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'fmax', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "fmin", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'fmin', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "fmod", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'fmod', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "fmod_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'fmod_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "frac", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'frac', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "frac_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'frac_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "frexp", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list("Tensor", "Tensor")) call_c_function( fun_name = 'frexp', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "gather", function(dim, index, sparse_grad = FALSE) { args <- mget(x = c("dim", "index", "sparse_grad")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), index = "Tensor", sparse_grad = "bool") nd_args <- c("self", "dim", "index") return_types <- list(list('Tensor')) call_c_function( fun_name = 'gather', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "gcd", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'gcd', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "gcd_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'gcd_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "ge", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'ge', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "ge_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'ge_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "geometric_", function(p, generator = NULL) { args <- mget(x = c("p", "generator")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", p = "double", generator = "Generator") nd_args <- c("self", "p") return_types <- list(list('Tensor')) call_c_function( fun_name = 'geometric_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "geqrf", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list("Tensor", "Tensor")) call_c_function( fun_name = 'geqrf', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "ger", function(vec2) { args <- mget(x = c("vec2")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", vec2 = "Tensor") nd_args <- c("self", "vec2") return_types <- list(list('Tensor')) call_c_function( fun_name = 'ger', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "greater", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'greater', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "greater_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'greater_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "greater_equal", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'greater_equal', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "greater_equal_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'greater_equal_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "gt", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'gt', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "gt_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'gt_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "hardshrink", function(lambd = 0.500000) { args <- mget(x = c("lambd")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", lambd = "Scalar") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'hardshrink', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "hardshrink_backward", function(grad_out, lambd) { args <- mget(x = c("grad_out", "lambd")) args <- append(list(self = self), args) expected_types <- list(grad_out = "Tensor", self = "Tensor", lambd = "Scalar") nd_args <- c("grad_out", "self", "lambd") return_types <- list(list('Tensor')) call_c_function( fun_name = 'hardshrink_backward', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "heaviside", function(values) { args <- mget(x = c("values")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", values = "Tensor") nd_args <- c("self", "values") return_types <- list(list('Tensor')) call_c_function( fun_name = 'heaviside', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "heaviside_", function(values) { args <- mget(x = c("values")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", values = "Tensor") nd_args <- c("self", "values") return_types <- list(list('Tensor')) call_c_function( fun_name = 'heaviside_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "histc", function(bins = 100L, min = 0L, max = 0L) { args <- mget(x = c("bins", "min", "max")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", bins = "int64_t", min = "Scalar", max = "Scalar") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'histc', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "hsplit", function(indices, sections) { args <- mget(x = c("indices", "sections")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", indices = "IntArrayRef", sections = "int64_t") nd_args <- c("self", "indices", "sections") return_types <- list(list('TensorList')) call_c_function( fun_name = 'hsplit', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "hypot", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'hypot', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "hypot_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'hypot_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "i0", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'i0', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "i0_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'i0_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "igamma", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'igamma', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "igamma_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'igamma_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "igammac", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'igammac', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "igammac_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'igammac_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "index", function(indices) { args <- mget(x = c("indices")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", indices = "const c10::List<c10::optional<Tensor>> &") nd_args <- c("self", "indices") return_types <- list(list('Tensor')) call_c_function( fun_name = 'index', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "index_add", function(dim, index, source, alpha = 1L) { args <- mget(x = c("dim", "index", "source", "alpha")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), index = "Tensor", source = "Tensor", alpha = "Scalar") nd_args <- c("self", "dim", "index", "source", "alpha") return_types <- list(list('Tensor')) call_c_function( fun_name = 'index_add', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "index_add_", function(dim, index, source, alpha) { args <- mget(x = c("dim", "index", "source", "alpha")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = "int64_t", index = "Tensor", source = "Tensor", alpha = "Scalar") nd_args <- c("self", "dim", "index", "source", "alpha") return_types <- list(list('Tensor')) call_c_function( fun_name = 'index_add_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "index_copy", function(dim, index, source) { args <- mget(x = c("dim", "index", "source")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), index = "Tensor", source = "Tensor") nd_args <- c("self", "dim", "index", "source") return_types <- list(list('Tensor')) call_c_function( fun_name = 'index_copy', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "index_copy_", function(dim, index, source) { args <- mget(x = c("dim", "index", "source")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), index = "Tensor", source = "Tensor") nd_args <- c("self", "dim", "index", "source") return_types <- list(list('Tensor')) call_c_function( fun_name = 'index_copy_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "index_fill", function(dim, index, value) { args <- mget(x = c("dim", "index", "value")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), index = "Tensor", value = c("Scalar", "Tensor")) nd_args <- c("self", "dim", "index", "value") return_types <- list(list('Tensor')) call_c_function( fun_name = 'index_fill', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "index_fill_", function(dim, index, value) { args <- mget(x = c("dim", "index", "value")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), index = "Tensor", value = c("Scalar", "Tensor")) nd_args <- c("self", "dim", "index", "value") return_types <- list(list('Tensor')) call_c_function( fun_name = 'index_fill_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "index_put", function(indices, values, accumulate = FALSE) { args <- mget(x = c("indices", "values", "accumulate")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", indices = "const c10::List<c10::optional<Tensor>> &", values = "Tensor", accumulate = "bool") nd_args <- c("self", "indices", "values") return_types <- list(list('Tensor')) call_c_function( fun_name = 'index_put', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "index_put_", function(indices, values, accumulate = FALSE) { args <- mget(x = c("indices", "values", "accumulate")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", indices = "const c10::List<c10::optional<Tensor>> &", values = "Tensor", accumulate = "bool") nd_args <- c("self", "indices", "values") return_types <- list(list('Tensor')) call_c_function( fun_name = 'index_put_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "index_select", function(dim, index) { args <- mget(x = c("dim", "index")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), index = "Tensor") nd_args <- c("self", "dim", "index") return_types <- list(list('Tensor')) call_c_function( fun_name = 'index_select', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "indices", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'indices', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "inner", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'inner', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "int_repr", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'int_repr', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "inverse", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'inverse', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "is_coalesced", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('bool')) call_c_function( fun_name = 'is_coalesced', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "is_complex", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('bool')) call_c_function( fun_name = 'is_complex', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "is_distributed", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('bool')) call_c_function( fun_name = 'is_distributed', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "is_floating_point", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('bool')) call_c_function( fun_name = 'is_floating_point', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_is_leaf", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('bool')) call_c_function( fun_name = 'is_leaf', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "is_nonzero", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('bool')) call_c_function( fun_name = 'is_nonzero', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "is_pinned", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('bool')) call_c_function( fun_name = 'is_pinned', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "is_same_size", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('bool')) call_c_function( fun_name = 'is_same_size', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "is_set_to", function(tensor) { args <- mget(x = c("tensor")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", tensor = "Tensor") nd_args <- c("self", "tensor") return_types <- list(list('bool')) call_c_function( fun_name = 'is_set_to', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "is_signed", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('bool')) call_c_function( fun_name = 'is_signed', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "isclose", function(other, rtol = 0.000010, atol = 0.000000, equal_nan = FALSE) { args <- mget(x = c("other", "rtol", "atol", "equal_nan")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor", rtol = "double", atol = "double", equal_nan = "bool") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'isclose', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "isfinite", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'isfinite', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "isinf", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'isinf', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "isnan", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'isnan', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "isneginf", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'isneginf', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "isposinf", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'isposinf', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "isreal", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'isreal', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "istft", function(n_fft, hop_length = NULL, win_length = NULL, window = list(), center = TRUE, normalized = FALSE, onesided = NULL, length = NULL, return_complex = FALSE) { args <- mget(x = c("n_fft", "hop_length", "win_length", "window", "center", "normalized", "onesided", "length", "return_complex")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", n_fft = "int64_t", hop_length = "int64_t", win_length = "int64_t", window = "Tensor", center = "bool", normalized = "bool", onesided = "bool", length = "int64_t", return_complex = "bool") nd_args <- c("self", "n_fft") return_types <- list(list('Tensor')) call_c_function( fun_name = 'istft', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "item", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Scalar')) call_c_function( fun_name = 'item', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "kron", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'kron', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "kthvalue", function(k, dim = -1L, keepdim = FALSE) { args <- mget(x = c("k", "dim", "keepdim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", k = "int64_t", dim = c("int64_t", "Dimname" ), keepdim = "bool") nd_args <- c("self", "k", "dim") return_types <- list(list("Tensor", "Tensor")) call_c_function( fun_name = 'kthvalue', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "lcm", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'lcm', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "lcm_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'lcm_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "ldexp", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'ldexp', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "ldexp_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'ldexp_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "le", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'le', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "le_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'le_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "lerp", function(end, weight) { args <- mget(x = c("end", "weight")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", end = "Tensor", weight = c("Scalar", "Tensor" )) nd_args <- c("self", "end", "weight") return_types <- list(list('Tensor')) call_c_function( fun_name = 'lerp', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "lerp_", function(end, weight) { args <- mget(x = c("end", "weight")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", end = "Tensor", weight = c("Scalar", "Tensor" )) nd_args <- c("self", "end", "weight") return_types <- list(list('Tensor')) call_c_function( fun_name = 'lerp_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "less", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'less', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "less_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'less_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "less_equal", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'less_equal', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "less_equal_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'less_equal_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "lgamma", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'lgamma', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "lgamma_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'lgamma_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "log", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'log', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "log_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'log_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "log_normal_", function(mean = 1L, std = 2L, generator = NULL) { args <- mget(x = c("mean", "std", "generator")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", mean = "double", std = "double", generator = "Generator") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'log_normal_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "log_softmax", function(dim, dtype = NULL) { args <- mget(x = c("dim", "dtype")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), dtype = "ScalarType") nd_args <- c("self", "dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'log_softmax', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "log10", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'log10', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "log10_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'log10_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "log1p", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'log1p', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "log1p_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'log1p_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "log2", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'log2', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "log2_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'log2_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "logaddexp", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'logaddexp', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "logaddexp2", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'logaddexp2', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "logcumsumexp", function(dim) { args <- mget(x = c("dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname")) nd_args <- c("self", "dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'logcumsumexp', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "logdet", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'logdet', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "logical_and", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'logical_and', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "logical_and_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'logical_and_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "logical_not", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'logical_not', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "logical_not_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'logical_not_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "logical_or", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'logical_or', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "logical_or_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'logical_or_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "logical_xor", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'logical_xor', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "logical_xor_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'logical_xor_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "logit", function(eps = NULL) { args <- mget(x = c("eps")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", eps = "double") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'logit', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "logit_", function(eps = NULL) { args <- mget(x = c("eps")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", eps = "double") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'logit_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "logsumexp", function(dim, keepdim = FALSE) { args <- mget(x = c("dim", "keepdim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("IntArrayRef", "DimnameList"), keepdim = "bool") nd_args <- c("self", "dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'logsumexp', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "lstsq", function(A) { args <- mget(x = c("A")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", A = "Tensor") nd_args <- c("self", "A") return_types <- list(list("Tensor", "Tensor")) call_c_function( fun_name = 'lstsq', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "lt", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'lt', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "lt_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'lt_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "lu_solve", function(LU_data, LU_pivots) { args <- mget(x = c("LU_data", "LU_pivots")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", LU_data = "Tensor", LU_pivots = "Tensor") nd_args <- c("self", "LU_data", "LU_pivots") return_types <- list(list('Tensor')) call_c_function( fun_name = 'lu_solve', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "masked_fill", function(mask, value) { args <- mget(x = c("mask", "value")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", mask = "Tensor", value = c("Scalar", "Tensor" )) nd_args <- c("self", "mask", "value") return_types <- list(list('Tensor')) call_c_function( fun_name = 'masked_fill', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "masked_fill_", function(mask, value) { args <- mget(x = c("mask", "value")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", mask = "Tensor", value = c("Scalar", "Tensor" )) nd_args <- c("self", "mask", "value") return_types <- list(list('Tensor')) call_c_function( fun_name = 'masked_fill_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "masked_scatter", function(mask, source) { args <- mget(x = c("mask", "source")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", mask = "Tensor", source = "Tensor") nd_args <- c("self", "mask", "source") return_types <- list(list('Tensor')) call_c_function( fun_name = 'masked_scatter', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "masked_scatter_", function(mask, source) { args <- mget(x = c("mask", "source")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", mask = "Tensor", source = "Tensor") nd_args <- c("self", "mask", "source") return_types <- list(list('Tensor')) call_c_function( fun_name = 'masked_scatter_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "masked_select", function(mask) { args <- mget(x = c("mask")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", mask = "Tensor") nd_args <- c("self", "mask") return_types <- list(list('Tensor')) call_c_function( fun_name = 'masked_select', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "matmul", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'matmul', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "matrix_exp", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'matrix_exp', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "matrix_power", function(n) { args <- mget(x = c("n")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", n = "int64_t") nd_args <- c("self", "n") return_types <- list(list('Tensor')) call_c_function( fun_name = 'matrix_power', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_max", function(dim, other, keepdim = FALSE) { args <- mget(x = c("dim", "other", "keepdim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), other = "Tensor", keepdim = "bool") nd_args <- c("self", "dim", "other") return_types <- list(list("Tensor", "Tensor"), list('Tensor')) call_c_function( fun_name = 'max', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "maximum", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'maximum', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "mean", function(dim, keepdim = FALSE, dtype = NULL) { args <- mget(x = c("dim", "keepdim", "dtype")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("IntArrayRef", "DimnameList"), keepdim = "bool", dtype = "ScalarType") nd_args <- c("self", "dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'mean', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "median", function(dim, keepdim = FALSE) { args <- mget(x = c("dim", "keepdim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), keepdim = "bool") nd_args <- c("self", "dim") return_types <- list(list('Tensor'), list("Tensor", "Tensor")) call_c_function( fun_name = 'median', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_min", function(dim, other, keepdim = FALSE) { args <- mget(x = c("dim", "other", "keepdim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), other = "Tensor", keepdim = "bool") nd_args <- c("self", "dim", "other") return_types <- list(list("Tensor", "Tensor"), list('Tensor')) call_c_function( fun_name = 'min', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "minimum", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'minimum', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "mm", function(mat2) { args <- mget(x = c("mat2")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", mat2 = "Tensor") nd_args <- c("self", "mat2") return_types <- list(list('Tensor')) call_c_function( fun_name = 'mm', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "mode", function(dim = -1L, keepdim = FALSE) { args <- mget(x = c("dim", "keepdim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), keepdim = "bool") nd_args <- c("self", "dim") return_types <- list(list("Tensor", "Tensor")) call_c_function( fun_name = 'mode', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "moveaxis", function(source, destination) { args <- mget(x = c("source", "destination")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", source = c("IntArrayRef", "int64_t"), destination = c("IntArrayRef", "int64_t")) nd_args <- c("self", "source", "destination") return_types <- list(list('Tensor')) call_c_function( fun_name = 'moveaxis', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "movedim", function(source, destination) { args <- mget(x = c("source", "destination")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", source = c("IntArrayRef", "int64_t"), destination = c("IntArrayRef", "int64_t")) nd_args <- c("self", "source", "destination") return_types <- list(list('Tensor')) call_c_function( fun_name = 'movedim', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "msort", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'msort', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "mul", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Tensor", "Scalar")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'mul', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "mul_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Tensor", "Scalar")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'mul_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "multinomial", function(num_samples, replacement = FALSE, generator = NULL) { args <- mget(x = c("num_samples", "replacement", "generator")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", num_samples = "int64_t", replacement = "bool", generator = "Generator") nd_args <- c("self", "num_samples") return_types <- list(list('Tensor')) call_c_function( fun_name = 'multinomial', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "multiply", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Tensor", "Scalar")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'multiply', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "multiply_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Tensor", "Scalar")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'multiply_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "mv", function(vec) { args <- mget(x = c("vec")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", vec = "Tensor") nd_args <- c("self", "vec") return_types <- list(list('Tensor')) call_c_function( fun_name = 'mv', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "mvlgamma", function(p) { args <- mget(x = c("p")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", p = "int64_t") nd_args <- c("self", "p") return_types <- list(list('Tensor')) call_c_function( fun_name = 'mvlgamma', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "mvlgamma_", function(p) { args <- mget(x = c("p")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", p = "int64_t") nd_args <- c("self", "p") return_types <- list(list('Tensor')) call_c_function( fun_name = 'mvlgamma_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "nan_to_num", function(nan = NULL, posinf = NULL, neginf = NULL) { args <- mget(x = c("nan", "posinf", "neginf")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", nan = "double", posinf = "double", neginf = "double") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'nan_to_num', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "nan_to_num_", function(nan = NULL, posinf = NULL, neginf = NULL) { args <- mget(x = c("nan", "posinf", "neginf")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", nan = "double", posinf = "double", neginf = "double") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'nan_to_num_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "nanmedian", function(dim, keepdim = FALSE) { args <- mget(x = c("dim", "keepdim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), keepdim = "bool") nd_args <- c("self", "dim") return_types <- list(list('Tensor'), list("Tensor", "Tensor")) call_c_function( fun_name = 'nanmedian', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "nanquantile", function(q, dim = NULL, keepdim = FALSE, interpolation) { args <- mget(x = c("q", "dim", "keepdim", "interpolation")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", q = c("double", "Tensor"), dim = "int64_t", keepdim = "bool", interpolation = "std::string") nd_args <- c("self", "q", "dim", "keepdim", "interpolation") return_types <- list(list('Tensor')) call_c_function( fun_name = 'nanquantile', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "nansum", function(dim, keepdim = FALSE, dtype = NULL) { args <- mget(x = c("dim", "keepdim", "dtype")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = "IntArrayRef", keepdim = "bool", dtype = "ScalarType") nd_args <- c("self", "dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'nansum', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_narrow", function(dim, start, length) { args <- mget(x = c("dim", "start", "length")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = "int64_t", start = c("int64_t", "Tensor" ), length = "int64_t") nd_args <- c("self", "dim", "start", "length") return_types <- list(list('Tensor')) call_c_function( fun_name = 'narrow', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_narrow_copy", function(dim, start, length) { args <- mget(x = c("dim", "start", "length")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = "int64_t", start = "int64_t", length = "int64_t") nd_args <- c("self", "dim", "start", "length") return_types <- list(list('Tensor')) call_c_function( fun_name = 'narrow_copy', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "ne", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'ne', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "ne_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'ne_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "neg", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'neg', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "neg_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'neg_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "negative", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'negative', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "negative_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'negative_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "new_empty", function(size, options = list()) { args <- mget(x = c("size", "options")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", size = "IntArrayRef", options = "TensorOptions") nd_args <- c("self", "size") return_types <- list(list('Tensor')) call_c_function( fun_name = 'new_empty', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "new_empty_strided", function(size, stride, options = list()) { args <- mget(x = c("size", "stride", "options")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", size = "IntArrayRef", stride = "IntArrayRef", options = "TensorOptions") nd_args <- c("self", "size", "stride") return_types <- list(list('Tensor')) call_c_function( fun_name = 'new_empty_strided', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "new_full", function(size, fill_value, options = list()) { args <- mget(x = c("size", "fill_value", "options")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", size = "IntArrayRef", fill_value = "Scalar", options = "TensorOptions") nd_args <- c("self", "size", "fill_value") return_types <- list(list('Tensor')) call_c_function( fun_name = 'new_full', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "new_zeros", function(size, options = list()) { args <- mget(x = c("size", "options")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", size = "IntArrayRef", options = "TensorOptions") nd_args <- c("self", "size") return_types <- list(list('Tensor')) call_c_function( fun_name = 'new_zeros', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "nextafter", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'nextafter', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "nextafter_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'nextafter_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_nonzero", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'nonzero', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_nonzero_numpy", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('TensorList')) call_c_function( fun_name = 'nonzero_numpy', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_norm", function(p = 2L, dim, keepdim = FALSE, dtype) { args <- mget(x = c("p", "dim", "keepdim", "dtype")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", p = "Scalar", dim = c("IntArrayRef", "DimnameList" ), keepdim = "bool", dtype = "ScalarType") nd_args <- c("self", "p", "dim", "keepdim", "dtype") return_types <- list(list('Tensor')) call_c_function( fun_name = 'norm', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "normal_", function(mean = 0L, std = 1L, generator = NULL) { args <- mget(x = c("mean", "std", "generator")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", mean = "double", std = "double", generator = "Generator") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'normal_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "not_equal", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'not_equal', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "not_equal_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'not_equal_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "numpy_T", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'numpy_T', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "orgqr", function(input2) { args <- mget(x = c("input2")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", input2 = "Tensor") nd_args <- c("self", "input2") return_types <- list(list('Tensor')) call_c_function( fun_name = 'orgqr', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "ormqr", function(input2, input3, left = TRUE, transpose = FALSE) { args <- mget(x = c("input2", "input3", "left", "transpose")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", input2 = "Tensor", input3 = "Tensor", left = "bool", transpose = "bool") nd_args <- c("self", "input2", "input3") return_types <- list(list('Tensor')) call_c_function( fun_name = 'ormqr', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "outer", function(vec2) { args <- mget(x = c("vec2")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", vec2 = "Tensor") nd_args <- c("self", "vec2") return_types <- list(list('Tensor')) call_c_function( fun_name = 'outer', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "output_nr", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('int64_t')) call_c_function( fun_name = 'output_nr', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "permute", function(dims) { args <- mget(x = c("dims")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dims = "IntArrayRef") nd_args <- c("self", "dims") return_types <- list(list('Tensor')) call_c_function( fun_name = 'permute', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "pin_memory", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'pin_memory', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "pinverse", function(rcond = 0.000000) { args <- mget(x = c("rcond")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", rcond = "double") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'pinverse', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "polygamma_", function(n) { args <- mget(x = c("n")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", n = "int64_t") nd_args <- c("self", "n") return_types <- list(list('Tensor')) call_c_function( fun_name = 'polygamma_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "positive", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'positive', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "pow", function(exponent) { args <- mget(x = c("exponent")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", exponent = c("Tensor", "Scalar")) nd_args <- c("self", "exponent") return_types <- list(list('Tensor')) call_c_function( fun_name = 'pow', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "pow_", function(exponent) { args <- mget(x = c("exponent")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", exponent = c("Scalar", "Tensor")) nd_args <- c("self", "exponent") return_types <- list(list('Tensor')) call_c_function( fun_name = 'pow_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "prelu", function(weight) { args <- mget(x = c("weight")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", weight = "Tensor") nd_args <- c("self", "weight") return_types <- list(list('Tensor')) call_c_function( fun_name = 'prelu', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "prelu_backward", function(grad_output, weight) { args <- mget(x = c("grad_output", "weight")) args <- append(list(self = self), args) expected_types <- list(grad_output = "Tensor", self = "Tensor", weight = "Tensor") nd_args <- c("grad_output", "self", "weight") return_types <- list(list("Tensor", "Tensor")) call_c_function( fun_name = 'prelu_backward', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "prod", function(dim, keepdim = FALSE, dtype = NULL) { args <- mget(x = c("dim", "keepdim", "dtype")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), keepdim = "bool", dtype = "ScalarType") nd_args <- c("self", "dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'prod', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "put", function(index, source, accumulate = FALSE) { args <- mget(x = c("index", "source", "accumulate")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", index = "Tensor", source = "Tensor", accumulate = "bool") nd_args <- c("self", "index", "source") return_types <- list(list('Tensor')) call_c_function( fun_name = 'put', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "put_", function(index, source, accumulate = FALSE) { args <- mget(x = c("index", "source", "accumulate")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", index = "Tensor", source = "Tensor", accumulate = "bool") nd_args <- c("self", "index", "source") return_types <- list(list('Tensor')) call_c_function( fun_name = 'put_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "q_per_channel_axis", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('int64_t')) call_c_function( fun_name = 'q_per_channel_axis', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "q_per_channel_scales", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'q_per_channel_scales', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "q_per_channel_zero_points", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'q_per_channel_zero_points', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "q_scale", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('double')) call_c_function( fun_name = 'q_scale', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "q_zero_point", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('int64_t')) call_c_function( fun_name = 'q_zero_point', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "qr", function(some = TRUE) { args <- mget(x = c("some")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", some = "bool") nd_args <- "self" return_types <- list(list("Tensor", "Tensor")) call_c_function( fun_name = 'qr', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "qscheme", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('QScheme')) call_c_function( fun_name = 'qscheme', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "quantile", function(q, dim = NULL, keepdim = FALSE, interpolation) { args <- mget(x = c("q", "dim", "keepdim", "interpolation")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", q = c("double", "Tensor"), dim = "int64_t", keepdim = "bool", interpolation = "std::string") nd_args <- c("self", "q", "dim", "keepdim", "interpolation") return_types <- list(list('Tensor')) call_c_function( fun_name = 'quantile', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "rad2deg", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'rad2deg', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "rad2deg_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'rad2deg_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "random_", function(from, to, generator = NULL) { args <- mget(x = c("from", "to", "generator")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", from = "int64_t", to = "int64_t", generator = "Generator") nd_args <- c("self", "from", "to") return_types <- list(list('Tensor')) call_c_function( fun_name = 'random_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "ravel", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'ravel', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "reciprocal", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'reciprocal', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "reciprocal_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'reciprocal_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "record_stream", function(s) { args <- mget(x = c("s")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", s = "Stream") nd_args <- c("self", "s") return_types <- list(list("void")) call_c_function( fun_name = 'record_stream', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "refine_names", function(names) { args <- mget(x = c("names")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", names = "DimnameList") nd_args <- c("self", "names") return_types <- list(list('Tensor')) call_c_function( fun_name = 'refine_names', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "relu", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'relu', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "relu_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'relu_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "remainder", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'remainder', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "remainder_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Scalar", "Tensor")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'remainder_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_rename", function(names) { args <- mget(x = c("names")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", names = "DimnameList") nd_args <- c("self", "names") return_types <- list(list('Tensor')) call_c_function( fun_name = 'rename', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_rename_", function(names) { args <- mget(x = c("names")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", names = "DimnameList") nd_args <- c("self", "names") return_types <- list(list('Tensor')) call_c_function( fun_name = 'rename_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "renorm", function(p, dim, maxnorm) { args <- mget(x = c("p", "dim", "maxnorm")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", p = "Scalar", dim = "int64_t", maxnorm = "Scalar") nd_args <- c("self", "p", "dim", "maxnorm") return_types <- list(list('Tensor')) call_c_function( fun_name = 'renorm', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "renorm_", function(p, dim, maxnorm) { args <- mget(x = c("p", "dim", "maxnorm")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", p = "Scalar", dim = "int64_t", maxnorm = "Scalar") nd_args <- c("self", "p", "dim", "maxnorm") return_types <- list(list('Tensor')) call_c_function( fun_name = 'renorm_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "repeat", function(repeats) { args <- mget(x = c("repeats")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", repeats = "IntArrayRef") nd_args <- c("self", "repeats") return_types <- list(list('Tensor')) call_c_function( fun_name = 'repeat', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "repeat_interleave", function(repeats, dim = NULL) { args <- mget(x = c("repeats", "dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", repeats = c("Tensor", "int64_t"), dim = "int64_t") nd_args <- c("self", "repeats") return_types <- list(list('Tensor')) call_c_function( fun_name = 'repeat_interleave', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "requires_grad_", function(requires_grad = TRUE) { args <- mget(x = c("requires_grad")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", requires_grad = "bool") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'requires_grad_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "reshape", function(shape) { args <- mget(x = c("shape")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", shape = "IntArrayRef") nd_args <- c("self", "shape") return_types <- list(list('Tensor')) call_c_function( fun_name = 'reshape', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "reshape_as", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'reshape_as', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "resize_", function(size, memory_format = NULL) { args <- mget(x = c("size", "memory_format")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", size = "IntArrayRef", memory_format = "MemoryFormat") nd_args <- c("self", "size") return_types <- list(list('Tensor')) call_c_function( fun_name = 'resize_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "resize_as_", function(the_template, memory_format = NULL) { args <- mget(x = c("the_template", "memory_format")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", the_template = "Tensor", memory_format = "MemoryFormat") nd_args <- c("self", "the_template") return_types <- list(list('Tensor')) call_c_function( fun_name = 'resize_as_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_retain_grad", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list("void")) call_c_function( fun_name = 'retain_grad', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "roll", function(shifts, dims = list()) { args <- mget(x = c("shifts", "dims")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", shifts = "IntArrayRef", dims = "IntArrayRef") nd_args <- c("self", "shifts") return_types <- list(list('Tensor')) call_c_function( fun_name = 'roll', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "rot90", function(k = 1L, dims = c(0,1)) { args <- mget(x = c("k", "dims")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", k = "int64_t", dims = "IntArrayRef") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'rot90', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "round", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'round', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "round_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'round_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "rsqrt", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'rsqrt', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "rsqrt_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'rsqrt_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_scatter", function(dim, index, src, value) { args <- mget(x = c("dim", "index", "src", "value")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), index = "Tensor", src = "Tensor", value = "Scalar") nd_args <- c("self", "dim", "index", "src", "value") return_types <- list(list('Tensor')) call_c_function( fun_name = 'scatter', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_scatter_", function(dim, index, src, value, reduce) { args <- mget(x = c("dim", "index", "src", "value", "reduce")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = "int64_t", index = "Tensor", src = "Tensor", value = "Scalar", reduce = "std::string") nd_args <- c("self", "dim", "index", "src", "value", "reduce") return_types <- list(list('Tensor')) call_c_function( fun_name = 'scatter_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "scatter_add", function(dim, index, src) { args <- mget(x = c("dim", "index", "src")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), index = "Tensor", src = "Tensor") nd_args <- c("self", "dim", "index", "src") return_types <- list(list('Tensor')) call_c_function( fun_name = 'scatter_add', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "scatter_add_", function(dim, index, src) { args <- mget(x = c("dim", "index", "src")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = "int64_t", index = "Tensor", src = "Tensor") nd_args <- c("self", "dim", "index", "src") return_types <- list(list('Tensor')) call_c_function( fun_name = 'scatter_add_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "select", function(dim, index) { args <- mget(x = c("dim", "index")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("Dimname", "int64_t"), index = "int64_t") nd_args <- c("self", "dim", "index") return_types <- list(list('Tensor')) call_c_function( fun_name = 'select', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "set_", function(source, storage_offset, size, stride = list()) { args <- mget(x = c("source", "storage_offset", "size", "stride")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", source = c("Storage", "Tensor"), storage_offset = "int64_t", size = "IntArrayRef", stride = "IntArrayRef") nd_args <- c("self", "source", "storage_offset", "size") return_types <- list(list('Tensor')) call_c_function( fun_name = 'set_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "set_data", function(new_data) { args <- mget(x = c("new_data")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", new_data = "Tensor") nd_args <- c("self", "new_data") return_types <- list(list("void")) call_c_function( fun_name = 'set_data', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sgn", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'sgn', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sgn_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'sgn_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sigmoid", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'sigmoid', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sigmoid_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'sigmoid_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sign", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'sign', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sign_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'sign_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "signbit", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'signbit', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sin", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'sin', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sin_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'sin_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sinc", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'sinc', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sinc_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'sinc_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sinh", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'sinh', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sinh_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'sinh_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_size", function(dim) { args <- mget(x = c("dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = "Dimname") nd_args <- c("self", "dim") return_types <- list(list('int64_t')) call_c_function( fun_name = 'size', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "slice", function(dim = 1L, start = NULL, end = NULL, step = 1L) { args <- mget(x = c("dim", "start", "end", "step")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = "int64_t", start = "int64_t", end = "int64_t", step = "int64_t") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'slice', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "slogdet", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list("Tensor", "Tensor")) call_c_function( fun_name = 'slogdet', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "smm", function(mat2) { args <- mget(x = c("mat2")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", mat2 = "Tensor") nd_args <- c("self", "mat2") return_types <- list(list('Tensor')) call_c_function( fun_name = 'smm', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "softmax", function(dim, dtype = NULL) { args <- mget(x = c("dim", "dtype")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), dtype = "ScalarType") nd_args <- c("self", "dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'softmax', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "solve", function(A) { args <- mget(x = c("A")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", A = "Tensor") nd_args <- c("self", "A") return_types <- list(list("Tensor", "Tensor")) call_c_function( fun_name = 'solve', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sort", function(dim = -1L, descending = FALSE, stable) { args <- mget(x = c("dim", "descending", "stable")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), descending = "bool", stable = "bool") nd_args <- c("self", "dim", "stable") return_types <- list(list("Tensor", "Tensor")) call_c_function( fun_name = 'sort', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sparse_dim", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('int64_t')) call_c_function( fun_name = 'sparse_dim', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sparse_mask", function(mask) { args <- mget(x = c("mask")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", mask = "Tensor") nd_args <- c("self", "mask") return_types <- list(list('Tensor')) call_c_function( fun_name = 'sparse_mask', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sparse_resize_", function(size, sparse_dim, dense_dim) { args <- mget(x = c("size", "sparse_dim", "dense_dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", size = "IntArrayRef", sparse_dim = "int64_t", dense_dim = "int64_t") nd_args <- c("self", "size", "sparse_dim", "dense_dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'sparse_resize_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sparse_resize_and_clear_", function(size, sparse_dim, dense_dim) { args <- mget(x = c("size", "sparse_dim", "dense_dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", size = "IntArrayRef", sparse_dim = "int64_t", dense_dim = "int64_t") nd_args <- c("self", "size", "sparse_dim", "dense_dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'sparse_resize_and_clear_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_split", function(split_size, dim = 1L) { args <- mget(x = c("split_size", "dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", split_size = "int64_t", dim = "int64_t") nd_args <- c("self", "split_size") return_types <- list(list('TensorList')) call_c_function( fun_name = 'split', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "split_with_sizes", function(split_sizes, dim = 1L) { args <- mget(x = c("split_sizes", "dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", split_sizes = "IntArrayRef", dim = "int64_t") nd_args <- c("self", "split_sizes") return_types <- list(list('TensorList')) call_c_function( fun_name = 'split_with_sizes', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sqrt", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'sqrt', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sqrt_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'sqrt_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "square", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'square', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "square_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'square_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "squeeze", function(dim) { args <- mget(x = c("dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname")) nd_args <- c("self", "dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'squeeze', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "squeeze_", function(dim) { args <- mget(x = c("dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname")) nd_args <- c("self", "dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'squeeze_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sspaddmm", function(mat1, mat2, beta = 1L, alpha = 1L) { args <- mget(x = c("mat1", "mat2", "beta", "alpha")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", mat1 = "Tensor", mat2 = "Tensor", beta = "Scalar", alpha = "Scalar") nd_args <- c("self", "mat1", "mat2") return_types <- list(list('Tensor')) call_c_function( fun_name = 'sspaddmm', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "std", function(dim, correction, unbiased = TRUE, keepdim = FALSE) { args <- mget(x = c("dim", "correction", "unbiased", "keepdim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("IntArrayRef", "DimnameList"), correction = "int64_t", unbiased = "bool", keepdim = "bool") nd_args <- c("self", "dim", "correction") return_types <- list(list('Tensor')) call_c_function( fun_name = 'std', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "stft", function(n_fft, hop_length = NULL, win_length = NULL, window = list(), normalized = FALSE, onesided = NULL, return_complex = NULL) { args <- mget(x = c("n_fft", "hop_length", "win_length", "window", "normalized", "onesided", "return_complex")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", n_fft = "int64_t", hop_length = "int64_t", win_length = "int64_t", window = "Tensor", normalized = "bool", onesided = "bool", return_complex = "bool") nd_args <- c("self", "n_fft") return_types <- list(list('Tensor')) call_c_function( fun_name = 'stft', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_stride", function(dim) { args <- mget(x = c("dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname")) nd_args <- c("self", "dim") return_types <- list(list('int64_t')) call_c_function( fun_name = 'stride', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sub", function(other, alpha = 1L) { args <- mget(x = c("other", "alpha")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Tensor", "Scalar"), alpha = "Scalar") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'sub', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sub_", function(other, alpha = 1L) { args <- mget(x = c("other", "alpha")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Tensor", "Scalar"), alpha = "Scalar") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'sub_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "subtract", function(other, alpha = 1L) { args <- mget(x = c("other", "alpha")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Tensor", "Scalar"), alpha = "Scalar") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'subtract', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "subtract_", function(other, alpha = 1L) { args <- mget(x = c("other", "alpha")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Tensor", "Scalar"), alpha = "Scalar") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'subtract_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sum", function(dim, keepdim = FALSE, dtype = NULL) { args <- mget(x = c("dim", "keepdim", "dtype")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("IntArrayRef", "DimnameList"), keepdim = "bool", dtype = "ScalarType") nd_args <- c("self", "dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'sum', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "sum_to_size", function(size) { args <- mget(x = c("size")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", size = "IntArrayRef") nd_args <- c("self", "size") return_types <- list(list('Tensor')) call_c_function( fun_name = 'sum_to_size', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "svd", function(some = TRUE, compute_uv = TRUE) { args <- mget(x = c("some", "compute_uv")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", some = "bool", compute_uv = "bool") nd_args <- "self" return_types <- list(list("Tensor", "Tensor", "Tensor")) call_c_function( fun_name = 'svd', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "swapaxes", function(axis0, axis1) { args <- mget(x = c("axis0", "axis1")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", axis0 = "int64_t", axis1 = "int64_t") nd_args <- c("self", "axis0", "axis1") return_types <- list(list('Tensor')) call_c_function( fun_name = 'swapaxes', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "swapaxes_", function(axis0, axis1) { args <- mget(x = c("axis0", "axis1")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", axis0 = "int64_t", axis1 = "int64_t") nd_args <- c("self", "axis0", "axis1") return_types <- list(list('Tensor')) call_c_function( fun_name = 'swapaxes_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "swapdims", function(dim0, dim1) { args <- mget(x = c("dim0", "dim1")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim0 = "int64_t", dim1 = "int64_t") nd_args <- c("self", "dim0", "dim1") return_types <- list(list('Tensor')) call_c_function( fun_name = 'swapdims', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "swapdims_", function(dim0, dim1) { args <- mget(x = c("dim0", "dim1")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim0 = "int64_t", dim1 = "int64_t") nd_args <- c("self", "dim0", "dim1") return_types <- list(list('Tensor')) call_c_function( fun_name = 'swapdims_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "symeig", function(eigenvectors = FALSE, upper = TRUE) { args <- mget(x = c("eigenvectors", "upper")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", eigenvectors = "bool", upper = "bool") nd_args <- "self" return_types <- list(list("Tensor", "Tensor")) call_c_function( fun_name = 'symeig', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "t", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 't', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "t_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 't_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "take", function(index) { args <- mget(x = c("index")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", index = "Tensor") nd_args <- c("self", "index") return_types <- list(list('Tensor')) call_c_function( fun_name = 'take', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "take_along_dim", function(indices, dim = NULL) { args <- mget(x = c("indices", "dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", indices = "Tensor", dim = "int64_t") nd_args <- c("self", "indices") return_types <- list(list('Tensor')) call_c_function( fun_name = 'take_along_dim', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "tan", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'tan', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "tan_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'tan_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "tanh", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'tanh', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "tanh_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'tanh_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "tensor_split", function(indices, sections, tensor_indices_or_sections, dim = 1L) { args <- mget(x = c("indices", "sections", "tensor_indices_or_sections", "dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", indices = "IntArrayRef", sections = "int64_t", tensor_indices_or_sections = "Tensor", dim = "int64_t") nd_args <- c("self", "indices", "sections", "tensor_indices_or_sections" ) return_types <- list(list('TensorList')) call_c_function( fun_name = 'tensor_split', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "tile", function(dims) { args <- mget(x = c("dims")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dims = "IntArrayRef") nd_args <- c("self", "dims") return_types <- list(list('Tensor')) call_c_function( fun_name = 'tile', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_to", function(device, options = list(), other, dtype, non_blocking = FALSE, copy = FALSE, memory_format = NULL) { args <- mget(x = c("device", "options", "other", "dtype", "non_blocking", "copy", "memory_format")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", device = "Device", options = "TensorOptions", other = "Tensor", dtype = "ScalarType", non_blocking = "bool", copy = "bool", memory_format = "MemoryFormat") nd_args <- c("self", "device", "other", "dtype") return_types <- list(list('Tensor')) call_c_function( fun_name = 'to', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "to_dense", function(dtype = NULL) { args <- mget(x = c("dtype")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dtype = "ScalarType") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'to_dense', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "to_mkldnn", function(dtype = NULL) { args <- mget(x = c("dtype")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dtype = "ScalarType") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'to_mkldnn', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "to_sparse", function(sparse_dim) { args <- mget(x = c("sparse_dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", sparse_dim = "int64_t") nd_args <- c("self", "sparse_dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'to_sparse', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_topk", function(k, dim = -1L, largest = TRUE, sorted = TRUE) { args <- mget(x = c("k", "dim", "largest", "sorted")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", k = "int64_t", dim = "int64_t", largest = "bool", sorted = "bool") nd_args <- c("self", "k") return_types <- list(list("Tensor", "Tensor")) call_c_function( fun_name = 'topk', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "trace", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'trace', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "transpose", function(dim0, dim1) { args <- mget(x = c("dim0", "dim1")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim0 = c("int64_t", "Dimname"), dim1 = c("int64_t", "Dimname")) nd_args <- c("self", "dim0", "dim1") return_types <- list(list('Tensor')) call_c_function( fun_name = 'transpose', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "transpose_", function(dim0, dim1) { args <- mget(x = c("dim0", "dim1")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim0 = "int64_t", dim1 = "int64_t") nd_args <- c("self", "dim0", "dim1") return_types <- list(list('Tensor')) call_c_function( fun_name = 'transpose_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "triangular_solve", function(A, upper = TRUE, transpose = FALSE, unitriangular = FALSE) { args <- mget(x = c("A", "upper", "transpose", "unitriangular")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", A = "Tensor", upper = "bool", transpose = "bool", unitriangular = "bool") nd_args <- c("self", "A") return_types <- list(list("Tensor", "Tensor")) call_c_function( fun_name = 'triangular_solve', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "tril", function(diagonal = 0L) { args <- mget(x = c("diagonal")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", diagonal = "int64_t") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'tril', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "tril_", function(diagonal = 0L) { args <- mget(x = c("diagonal")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", diagonal = "int64_t") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'tril_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "triu", function(diagonal = 0L) { args <- mget(x = c("diagonal")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", diagonal = "int64_t") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'triu', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "triu_", function(diagonal = 0L) { args <- mget(x = c("diagonal")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", diagonal = "int64_t") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'triu_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "true_divide", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Tensor", "Scalar")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'true_divide', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "true_divide_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Tensor", "Scalar")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'true_divide_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "trunc", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'trunc', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "trunc_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'trunc_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "type_as", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'type_as', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "unbind", function(dim = 1L) { args <- mget(x = c("dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname")) nd_args <- c("self", "dim") return_types <- list(list('TensorList')) call_c_function( fun_name = 'unbind', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "unflatten", function(dim, sizes, names = NULL) { args <- mget(x = c("dim", "sizes", "names")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("int64_t", "Dimname"), sizes = "IntArrayRef", names = "DimnameList") nd_args <- c("self", "dim", "sizes", "names") return_types <- list(list('Tensor')) call_c_function( fun_name = 'unflatten', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "unfold", function(dimension, size, step) { args <- mget(x = c("dimension", "size", "step")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dimension = "int64_t", size = "int64_t", step = "int64_t") nd_args <- c("self", "dimension", "size", "step") return_types <- list(list('Tensor')) call_c_function( fun_name = 'unfold', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "uniform_", function(from = 0L, to = 1L, generator = NULL) { args <- mget(x = c("from", "to", "generator")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", from = "double", to = "double", generator = "Generator") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'uniform_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "unsafe_chunk", function(chunks, dim = 1L) { args <- mget(x = c("chunks", "dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", chunks = "int64_t", dim = "int64_t") nd_args <- c("self", "chunks") return_types <- list(list('TensorList')) call_c_function( fun_name = 'unsafe_chunk', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "unsafe_split", function(split_size, dim = 1L) { args <- mget(x = c("split_size", "dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", split_size = "int64_t", dim = "int64_t") nd_args <- c("self", "split_size") return_types <- list(list('TensorList')) call_c_function( fun_name = 'unsafe_split', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "unsafe_split_with_sizes", function(split_sizes, dim = 1L) { args <- mget(x = c("split_sizes", "dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", split_sizes = "IntArrayRef", dim = "int64_t") nd_args <- c("self", "split_sizes") return_types <- list(list('TensorList')) call_c_function( fun_name = 'unsafe_split_with_sizes', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "unsqueeze", function(dim) { args <- mget(x = c("dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = "int64_t") nd_args <- c("self", "dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'unsqueeze', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "unsqueeze_", function(dim) { args <- mget(x = c("dim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = "int64_t") nd_args <- c("self", "dim") return_types <- list(list('Tensor')) call_c_function( fun_name = 'unsqueeze_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "values", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'values', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "var", function(dim, correction, unbiased = TRUE, keepdim = FALSE) { args <- mget(x = c("dim", "correction", "unbiased", "keepdim")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dim = c("IntArrayRef", "DimnameList"), correction = "int64_t", unbiased = "bool", keepdim = "bool") nd_args <- c("self", "dim", "correction") return_types <- list(list('Tensor')) call_c_function( fun_name = 'var', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "vdot", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'vdot', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("private", "_view", function(dtype, size) { args <- mget(x = c("dtype", "size")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", dtype = "ScalarType", size = "IntArrayRef") nd_args <- c("self", "dtype", "size") return_types <- list(list('Tensor')) call_c_function( fun_name = 'view', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "view_as", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = "Tensor") nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'view_as', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "vsplit", function(indices, sections) { args <- mget(x = c("indices", "sections")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", indices = "IntArrayRef", sections = "int64_t") nd_args <- c("self", "indices", "sections") return_types <- list(list('TensorList')) call_c_function( fun_name = 'vsplit', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "where", function(condition, other) { args <- mget(x = c("condition", "other")) args <- append(list(self = self), args) expected_types <- list(condition = "Tensor", self = "Tensor", other = "Tensor") nd_args <- c("condition", "self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'where', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "xlogy", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Tensor", "Scalar")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'xlogy', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "xlogy_", function(other) { args <- mget(x = c("other")) args <- append(list(self = self), args) expected_types <- list(self = "Tensor", other = c("Tensor", "Scalar")) nd_args <- c("self", "other") return_types <- list(list('Tensor')) call_c_function( fun_name = 'xlogy_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )}) Tensor$set("public", "zero_", function() { args <- list() args <- append(list(self = self), args) expected_types <- list(self = "Tensor") nd_args <- "self" return_types <- list(list('Tensor')) call_c_function( fun_name = 'zero_', args = args, expected_types = expected_types, nd_args = nd_args, return_types = return_types, fun_type = 'method' )})
fabric_text <- function(cid, cwidth = 800, cheight = 600, cfill = " textId, text, left = 100, top = 100, fill = " angle = 0, opacity = 1, fontFamily = 'Comic Sans', fontSize = 40, fontStyle = 'normal', strokecolor = " strokewidth = 1, fontWeight = "normal", underline = FALSE, linethrough = FALSE, overline = FALSE, selectable = TRUE, shadow = FALSE, shadowCol = " textAlign = "center", lineHeight = 1, textBackgroundColor = NULL, isDrawingMode = FALSE){ if (!fontStyle %in% c("normal", "italic")) { stop(paste0("fontStyle accepts two values: 'normal' or 'italic'")) } selectable <- ifelse(selectable == TRUE, "true", "false") isDrawingMode <- ifelse(isDrawingMode == TRUE, "true", "false") underline <- ifelse(underline == TRUE, "true", "false") linethrough <- ifelse(linethrough == TRUE, "true", "false") overline <- ifelse(overline == TRUE, "true", "false") shadow <- ifelse(shadow == TRUE, glue::glue("shadow:'{shadowCol} 5px 5px 5px'"), "") tBG <- ifelse(is.null(textBackgroundColor), character(0), glue::glue("textBackgroundColor: '{textBackgroundColor}',")) htmltools::tagList( htmltools::tags$canvas(id = cid, width = cwidth, height = cheight), fabric_dependency(), htmltools::tags$script(htmltools::HTML(glue::glue( " var {cid} = new fabric.Canvas('{cid}', {{ isDrawingMode: {isDrawingMode} }}); {cid}.backgroundColor = '{cfill}'; var {textId} = new fabric.Text(\"{text}\", {{ left: {left}, top: {top}, fontFamily: '{fontFamily}', fontSize: {fontSize}, fontStyle: '{fontStyle}', fontWeight: '{fontWeight}', underline: {underline}, linethrough: {linethrough}, overline: {overline}, fill: '{fill}', angle: {angle}, opacity: {opacity}, stroke: '{strokecolor}', strokeWidth: {strokewidth}, textAlign: '{textAlign}', lineHeight: {lineHeight}, {tBG} selectable: {selectable}, {shadow} }}); {cid}.add({textId}); " , .na = ""))) ) }
ABC_P2_norm <- function(n,ObsMean,M_Lo,M_Hi,SD_Lo,SD_Hi,delta,iter){ posterior<-c() discard<-c() Norm<-c() Avg<-c() Std<-c() i<-1 j<-1 k<-1 l<-1 m<-1 while(i <= iter){ avg<-runif(1,M_Lo,M_Hi) std<-runif(1,SD_Lo,SD_Hi) while(j<=n){ norm<-round(rnorm(1, mean=avg, sd=std)) if(norm>0){ Norm[j]<-norm j<-j+1} } P2<-runif(1,0,1) sire2<-rbinom(n,Norm,P2) meanP2<-mean(sire2) if(abs(meanP2 - ObsMean)>delta){ discard[k]<-P2 k<-k+1 }else if(abs(meanP2 - ObsMean)<=delta){ posterior[i]<-P2 Avg[l]<-avg Std[m]<-std i<-i+1 l<-l+1 m<-m+1 } } list(posterior = posterior, Avg = Avg, Std = Std) }
createSpecificRef <- function(currRefference, modelSize, neighborhoodSize, genePercents, chosenCells, chosenNeigCells){ specificRef = do.call(cbind,lapply(chosenCells,function(chosenCell){ currRefference[,chosenNeigCells[[chosenCell]]] })) colnames(specificRef) = unlist(lapply(chosenCells,function(cell){ rep(paste(colnames(currRefference)[cell],cell,sep="_"),neighborhoodSize) })) row.names(specificRef) = row.names(currRefference) specificRef = specificRef[sample(1:dim(currRefference)[1],round(genePercents*dim(currRefference)[1])),] list(ref = specificRef, chosenCells = chosenCells) } createNoCellDupeReference <- function(refference){ currCellNames = colnames(refference) refferenceNoDups = as.data.frame(matrix(0,nrow = dim(refference)[1], ncol=length(unique(currCellNames)))) for (i in 1:length(unique(currCellNames))){ if (length(which(currCellNames == unique(currCellNames)[i]))!=1){ refferenceNoDups[,i] = rowMeans(refference[,which(currCellNames == unique(currCellNames)[i])]) }else{ refferenceNoDups[,i] = refference[,which(currCellNames == unique(currCellNames)[i])] } } row.names(refferenceNoDups) = row.names(refference) colnames(refferenceNoDups) = unique(currCellNames) return(refferenceNoDups) } GeneBasedAnova <- function(specificRefference, nonZeroRatio = NULL){ cellNamesForAnova = colnames(specificRefference) genes_to_take = row.names(specificRefference) genes_to_take = names(which(rowMeans(specificRefference[genes_to_take,])!=0)) if(!is.null(nonZeroRatio)){ genes_to_take = unlist(apply(as.data.frame(genes_to_take),1,function(gene){ if((length(which(as.numeric(specificRefference[gene,which(cellNamesForAnova==1)])!=0))/length(as.numeric(specificRefference[gene,which(cellNamesForAnova==1)])))>nonZeroRatio){ gene }else{ NULL } })) } dat = cbind(rep(0,length(genes_to_take)),specificRefference[genes_to_take,]) group = c("",cellNamesForAnova) dmat <- stats::model.matrix(~ group) fit <- limma::lmFit(dat, dmat) fit = fit[,-1] fit <- limma::eBayes(fit) fitF = fit$F res = as.data.frame(cbind(gsub("group","",colnames(fit$coefficients)[apply(fit$coefficients,1,function(x){order(x,decreasing = T)[1]})]),fitF)) colnames(res) = c("group", "score") listOfGenes = apply(as.data.frame(unique(cellNamesForAnova)),1,function(cellGroup){ selectedIndexes = which(as.character(res$group)==as.character(cellGroup)) (genes_to_take[selectedIndexes])[order(res$score[selectedIndexes],decreasing = T)] }) return(listOfGenes) } selectGenesUsingKappa <- function(refferenceNoDups, allGenes){ bestKappa = Inf bestG = 0 mul = 1 maxNumberOfGenesPerCell = 50 bestGenes = c() indexRange = 2:maxNumberOfGenesPerCell for (i in indexRange){ selectedGenes = unique(as.character(unlist(lapply(1:length(allGenes), function(listIndex){ unlist(allGenes[listIndex])[which(!is.na(unlist(allGenes[listIndex])[1:as.numeric(i*mul)]))] })))) currRefferenceNoDups = refferenceNoDups[match(selectedGenes, row.names(refferenceNoDups)),] newKappa = kappa(currRefferenceNoDups) if (newKappa<bestKappa){ bestKappa = newKappa bestG = i bestGenes = unique(selectedGenes) } } finalRefference = refferenceNoDups[which(row.names(refferenceNoDups) %in% bestGenes),] return(list(reference = finalRefference, G = bestG, kappa = bestKappa)) } checkVariableGenes = function(a, ratio) { count_nonZeros = length(which(a > min(a))) if (count_nonZeros/length(a) > ratio) { var(a)/ mean(a) } else { 0 } } runLibLinear = function(ref_matrix, sample_matrix){ X <- data.matrix(ref_matrix) X <- X[apply(X,1,sd)!=0,] Y <- data.matrix(sample_matrix) Y = Y[match(row.names(X),row.names(Y)),] Y <- Y[row.names(Y) %in% row.names(X),] X <- X[row.names(X) %in% row.names(Y),] X <- t(apply(X,1,function(rowX){ (rowX - mean(rowX)) / sd(as.vector(rowX)) })) C = LiblineaR::heuristicC(X) predictionMatrix = do.call(rbind,lapply(1:dim(Y)[2],function(index){ y <- Y[,index] y <- (y - mean(y)) / sd(y) (LiblineaR::LiblineaR(data = X, target = y, type = 11, cost = C)$W)[1:dim(X)[2]] })) colnames(predictionMatrix) = colnames(X) row.names(predictionMatrix) = colnames(Y) predictionMatrix } choseCellsForRuns = function(XY, refNames, modelSize, minSelection, neighborhoodSize){ k = floor(modelSize/length(unique(refNames))) if(k==0){ k=1 } minValueToReduceTo = 10^-10 initialGrids = lapply(unique(refNames), function(currCluster){ clusterIndexes = which(refNames==currCluster) nbins = max(k,length(clusterIndexes)/neighborhoodSize) if(is.null(dim(XY))){ currXY = XY[clusterIndexes] breaks = seq(min(currXY)-10^-7,max(currXY)+10^-7, (max(currXY)-min(currXY)+2*10^-7)/ceiling(nbins)) grid <- rep(NA,ceiling(nbins)) cellLocationOnGrid = rep(NA,length(currXY)) for(currBreakIndex in 2:length(breaks)){ cellLocationOnGrid[which(currXY>breaks[currBreakIndex-1] & currXY<breaks[currBreakIndex])] = currBreakIndex-1 } tab <- table(cellLocationOnGrid) grid[as.numeric(names(tab))] <- tab }else{ currXY = XY[clusterIndexes,] ch <- grDevices::chull(currXY) coords <- currXY[c(ch, ch[1]), ] poly = sp::SpatialPolygons(list(sp::Polygons(list(sp::Polygon(coords)), "x"))) grid <- raster::raster(raster::extent(poly), nrows = ceiling(sqrt(nbins)), ncols= ceiling(sqrt(nbins))) sp::proj4string(grid)<-sp::proj4string(poly) cellLocationOnGrid = raster::cellFromXY(grid, currXY) tab <- table(cellLocationOnGrid) grid[as.numeric(names(tab))] <- tab } list(grid = grid, clusterIndexes = clusterIndexes, cellLocationOnGrid = cellLocationOnGrid, nFullbins = length(tab), maxBinSize = max(tab)) }) numOfRuns = ceiling(minSelection*max(unlist(lapply(initialGrids,function(clusterData){ clusterData$nFullbins * clusterData$maxBinSize }))) / k) meanDistMatrix = rep(1,length(refNames)) chosenCellList = lapply(1:numOfRuns, function(runNum){ chosenCells = as.numeric(unlist(lapply(unique(refNames),function(currCluster){ initialGrid = initialGrids[[which(unique(refNames)==currCluster)]] clusterIndexes = initialGrid$clusterIndexes grid = initialGrid$grid cellLocationOnGrid = initialGrid$cellLocationOnGrid kToUse = k if(k>length(which(!is.na(grid[])))){ kToUse = length(which(!is.na(grid[]))) } gridCellsToUse = sample(which(!is.na(grid[])),kToUse,replace = F) chosenCellsForCluster = clusterIndexes[unlist(lapply(gridCellsToUse, function(currCell){ chosenCell = which(cellLocationOnGrid==currCell) if(length(chosenCell)>1){ chosenCell = sample(chosenCell,1,prob = meanDistMatrix[clusterIndexes[chosenCell]]) } chosenCell }))] chosenCellsForCluster }))) cellsToReduce = chosenCells[which(meanDistMatrix[chosenCells]>minValueToReduceTo)] meanDistMatrix[cellsToReduce] <<- meanDistMatrix[cellsToReduce]/10 chosenCells }) chosenNeigList = lapply(1:length(refNames),function(cellIndex){ selectedCellType = refNames[cellIndex] selectedCellIndexes = which(refNames == selectedCellType) cellXY = XY[cellIndex,] cellDist = fields::rdist(t(as.matrix(cellXY)),XY[selectedCellIndexes,]) chosenRepeats = order(as.numeric(cellDist),decreasing = F)[1:neighborhoodSize] chosenRepeats = chosenRepeats[!is.na(chosenRepeats)] selectedCellIndexes[chosenRepeats] }) list(chosenCellList = chosenCellList, chosenNeigList = chosenNeigList, numOfRuns = numOfRuns) } CPMMain = function(refference,refferenceNames, Y, chosenCellList, chosenCellNeigList ,numOfRuns, modelSize, neighborhoodSize, no_cores, genePercents, quantifyTypes, typeTransformation, calculateCI){ YReduced = Y[row.names(Y) %in% row.names(refference), , drop = FALSE] geneVarianceRef = apply(refference,1,function(gene){checkVariableGenes(as.numeric(as.matrix(gene)),0.1)}) geneVarianceFinalRef = sort(geneVarianceRef[geneVarianceRef>0],decreasing = T) mutualGenes = names(geneVarianceFinalRef)[names(geneVarianceFinalRef) %in% row.names(YReduced)] YReduced = YReduced[mutualGenes, , drop = FALSE] refferenceSmaller = refference[mutualGenes,] if(is.null(no_cores)){ no_cores = max(1, parallel::detectCores() - 1) } cl<-parallel::makeCluster(no_cores) parallel::clusterExport(cl=cl, varlist=c("refferenceNames", "refferenceSmaller", "YReduced","neighborhoodSize","modelSize", "createSpecificRef","GeneBasedAnova", "chosenCellList", "chosenCellNeigList" ,"createNoCellDupeReference", "selectGenesUsingKappa", "runLibLinear", "genePercents"), envir=environment()) doSNOW::registerDoSNOW(cl) pb <- utils::txtProgressBar(min = 1, max = numOfRuns, style = 3) progress <- function(n) setTxtProgressBar(pb, n) opts <- list(progress = progress) `%dopar2%` <- foreach::`%dopar%` runNumber = NULL resultSmallMatrixes <- foreach::foreach(runNumber = 1:numOfRuns, .options.snow = opts) %dopar2% { print(runNumber) completeSpecificRefBefore = createSpecificRef(refferenceSmaller, modelSize, neighborhoodSize, genePercents, chosenCellList[[runNumber]], chosenCellNeigList) completeSpecificRef = completeSpecificRefBefore$ref clusterNamesVector = rep("", dim(completeSpecificRef)[2]) for(cluster in unique(refferenceNames)){ selectedCellsForCluster = completeSpecificRefBefore$chosenCells[which(refferenceNames[completeSpecificRefBefore$chosenCells] == cluster)] selectedNamesForCluster = paste(colnames(refferenceSmaller)[selectedCellsForCluster],selectedCellsForCluster,sep="_") clusterNamesVector[!is.na(match(colnames(completeSpecificRef),selectedNamesForCluster))] = cluster } allGenes = c() if(quantifyTypes){ allGenesList = GeneBasedAnova(completeSpecificRef) }else{ allGenesList = lapply(unique(refferenceNames), function(cluster){ specificClusterRef = completeSpecificRef[,which(clusterNamesVector == cluster)] colnames(specificClusterRef) = colnames(completeSpecificRef)[clusterNamesVector == cluster] GeneBasedAnova(specificClusterRef) }) } for (list in allGenesList){ allGenes = c(allGenes, list) } specificRefNoDupes = createNoCellDupeReference(completeSpecificRef) results = selectGenesUsingKappa(specificRefNoDupes, allGenes) X = results$reference X = refferenceSmaller[row.names(X),completeSpecificRefBefore$chosenCells] X = X[rowSums(X)!=0,] YRefinedReduced = YReduced[row.names(YReduced) %in% row.names(X),] PBSReductionData = YRefinedReduced setTxtProgressBar(pb, runNumber) resMatrix = t(runLibLinear(X, PBSReductionData)) row.names(resMatrix) = chosenCellList[[runNumber]] resMatrix } parallel::stopCluster(cl) close(pb) print("Combining CPM iterations") predictedCells = matrix(0, nrow = dim(YReduced)[2], ncol = dim(refferenceSmaller)[2]) predictedCellsCounts = matrix(0, nrow = dim(YReduced)[2], ncol = dim(refferenceSmaller)[2]) for(resultMatrix in resultSmallMatrixes){ completeResultMatrix = matrix(0, nrow = dim(resultMatrix)[2], ncol = dim(refferenceSmaller)[2]) completeResultMatrix[,as.numeric(as.matrix(row.names(resultMatrix)))] = t(resultMatrix) predictedCells = predictedCells + completeResultMatrix predictedCellsCounts = predictedCellsCounts + abs(sign(completeResultMatrix)) } predictedCellsFinal = predictedCells/predictedCellsCounts print("Smoothing") allClusterMeansMatrix = t(do.call(rbind,lapply(1:length(refferenceNames),function(cell){ rowMeans(predictedCellsFinal[,chosenCellNeigList[[cell]]]) }))) colnames(allClusterMeansMatrix) = colnames(refference) row.names(allClusterMeansMatrix) = colnames(Y) cellTypeRes = NULL seRes = NULL confMatrix = NULL if(quantifyTypes){ print("Calculating cell type quantities") allClusterMeansMatrixForCellTypes = allClusterMeansMatrix if(typeTransformation){ allClusterMeansMatrixForCellTypes = t(apply(t(allClusterMeansMatrixForCellTypes),2,function(x){ x-min(x) })) } cellTypeRes = do.call(cbind,lapply(unique(refferenceNames),function(currCluster){ rowMeans(allClusterMeansMatrixForCellTypes[,currCluster==refferenceNames]) })) colnames(cellTypeRes) = unique(refferenceNames) if(typeTransformation){ cellTypeRes = t(apply(t(cellTypeRes),2,function(x){ x/sum(x) }) ) } } if(calculateCI){ print("Calculating the confidence interval matrix") resultOriginalSizeMatrixes = lapply(resultSmallMatrixes, function(resultSmallMatrix){ completeResultMatrix = matrix(NA, nrow = dim(resultSmallMatrix)[2], ncol = dim(refferenceSmaller)[2]) completeResultMatrix[,match(colnames(allClusterMeansMatrix)[as.numeric(as.matrix(row.names(resultSmallMatrix)))],colnames(refferenceSmaller))] = t(resultSmallMatrix) completeResultMatrix }) seRes <- do.call(rbind,lapply(colnames(YReduced), function(sample){ sampleMatrix = do.call(rbind, lapply(resultOriginalSizeMatrixes,function(currRes){ currRes[which(colnames(YReduced)==sample),] })) apply(sampleMatrix,2,function(x){ sd(x[!is.na(x)])/sqrt(length(which(!is.na(x)))) }) })) seResNorm = t(do.call(rbind,lapply(1:length(refferenceNames),function(cell){ rowMeans(seRes[,chosenCellNeigList[[cell]]]) }))) confMatrix = matrix(paste(allClusterMeansMatrix-1.96*seResNorm,allClusterMeansMatrix+1.96*seResNorm,sep = " <-> "),ncol = dim(allClusterMeansMatrix)[2]) colnames(seRes) = colnames(confMatrix) = colnames(refference) row.names(seRes) = row.names(confMatrix) = colnames(Y) } print("Done") list(predictions = allClusterMeansMatrix, cellTypePredictions = cellTypeRes, sePredictions = seRes, confMatrix = confMatrix) } CPM = function(SCData, SCLabels, BulkData, cellSpace, no_cores = NULL, neighborhoodSize = 10, modelSize = 50, minSelection = 5, quantifyTypes = F, typeTransformation = F, calculateCI = F){ genePercents = 0.4 if(min(table(SCLabels))<neighborhoodSize){ neighborhoodSize = min(table(SCLabels)) print(paste("Neighborhood size was switched to:",neighborhoodSize,sep=" ")) } if(quantifyTypes){ modelSize = length(unique(SCLabels)) print(paste("Model size was switched to:",modelSize,sep=" ")) }else if(length(SCLabels)<modelSize){ modelSize = length(SCLabels) print(paste("Model size was switched to:",modelSize,sep=" ")) } if(!is.null(SCData) & !is.null(SCLabels) & !is.null(BulkData) & !is.null(cellSpace)){ print("Selecting cells for each iteration") } cellSelection = choseCellsForRuns(cellSpace, SCLabels, modelSize, minSelection,neighborhoodSize) numOfRunsToUse = cellSelection$numOfRuns print(paste("Number of iteration:",numOfRunsToUse,sep=" ")) cellSelectionList = cellSelection$chosenCellList cellNeigSelectionList = cellSelection$chosenNeigList print("Running CPM, this may take a few minutes") deconvolutionRes = CPMMain(SCData, SCLabels,BulkData, cellSelectionList, cellNeigSelectionList, numOfRunsToUse,modelSize, neighborhoodSize, no_cores, genePercents, quantifyTypes, typeTransformation, calculateCI) list(predicted = deconvolutionRes$predictions, cellTypePredictions = deconvolutionRes$cellTypePredictions, confIntervals = deconvolutionRes$confMatrix, numOfRuns = numOfRunsToUse) } "BulkFlu" "SCFlu" "SCLabels" "SCCellSpace"
scanoneboot <- function(cross, chr, pheno.col=1, model=c("normal","binary","2part","np"), method=c("em","imp","hk","ehk","mr","mr-imp","mr-argmax"), addcovar=NULL, intcovar=NULL, weights=NULL, use=c("all.obs", "complete.obs"), upper=FALSE, ties.random=FALSE, start=NULL, maxit=4000, tol=1e-4, n.boot=1000, verbose=FALSE) { if(!missing(chr)) cross <- subset(cross, chr) if(nchr(cross) != 1) { warning("Considering just the first chromosome (", names(cross$geno)[1], ").") cross <- subset(cross, names(cross$geno)[1]) } if(LikePheVector(pheno.col, nind(cross), nphe(cross))) { cross$pheno <- cbind(pheno.col, cross$pheno) pheno.col <- 1 } if(length(pheno.col) > 1) stop("pheno.col should indicate a single phenotype") if(is.character(pheno.col)) { num <- find.pheno(cross, pheno.col) if(is.na(num)) stop("Couldn't identify phenotype \"", pheno.col, "\"") pheno.col <- num } if(pheno.col < 1 || pheno.col > nphe(cross)) stop("pheno.col should be between 1 and ", nphe(cross)) out <- scanone(cross, pheno.col=pheno.col, model=model, method=method, addcovar=addcovar, intcovar=intcovar, weights=weights, use=use, upper=upper, ties.random=ties.random, start=start, maxit=maxit, tol=tol) maxlod <- max(out[,3],na.rm=TRUE) w <- which(!is.na(out[,3]) & out[,3] == maxlod) results <- rep(NA, n.boot) n.ind <- nind(cross) n.prnt <- floor(n.boot/20) for(i in 1:n.boot) { temp <- subset(cross, ind=sample(n.ind, replace=TRUE)) out <- scanone(temp, pheno.col=pheno.col, model=model, method=method, addcovar=addcovar, intcovar=intcovar, weights=weights, use=use, upper=upper, ties.random=ties.random, start=start, maxit=maxit, tol=tol) mx <- max(out[,3],na.rm=TRUE) w <- out[!is.na(out[,3]) & out[,3]==mx,2] if(length(w) > 1) w <- sample(w,1) results[i] <- w if(verbose && ((i-1) %% n.prnt) == 0) cat("replicate", i, "\n") } attr(results, "results") <- out class(results) <- "scanoneboot" results } summary.scanoneboot <- function(object, prob=0.95, expandtomarkers=FALSE, ...) { lo <- (1-prob)/2 results <- attr(object, "results") o <- max(results) qu <- quantile(object, c(lo, 1-lo)) wh1 <- which(results[,2] <= qu[1]) wh1 <- wh1[length(wh1)] wh2 <- which(results[,2] >= qu[2]) wh2 <- wh2[1] if(expandtomarkers) { markerpos <- (1:nrow(results))[-grep("^c.+\\.loc-*[0-9]+(\\.[0-9]+)*$", rownames(results))] if(any(markerpos <= wh1)) wh1 <- max(markerpos[markerpos <= wh1]) if(any(markerpos >= wh2)) wh2 <- min(markerpos[markerpos >= wh2]) } rbind(results[wh1,], o, results[wh2,]) } print.scanoneboot <- function(x, ...) { print(as.numeric(x)) }
context("AUC") set.seed(SEED) N <- 100 x0 <- rnorm(N, mean = runif(1)) x1 <- rnorm(N, mean = 2 * runif(1)) x <- c(x0, x1) y <- c(rep(0, N), rep(1, N)) auc.conf <- AUCBoot(x, y, seed = 1) auc.conf2 <- AUCBoot(x, y, seed = 1) test_that("Same results of AUC with seed", { expect_equal(auc.conf, auc.conf2) }) test_that("Same results of AUC in particular cases", { expect_equal(AUC(c(0, 0), 0:1), 0.5) expect_equal(AUC(c(0.2, 0.1, 1), c(0, 0, 1)), 1) expect_warning(auc1 <- AUCBoot(c(0, 0), 0:1)) expect_equivalent(auc1, c(rep(0.5, 3), 0)) expect_warning(auc2 <- AUCBoot(c(0.2, 0.1, 1), c(0, 0, 1))) expect_equivalent(auc2, c(rep(1, 3), 0)) }) test_that("Same as wilcox test", { expect_equivalent(AUC(x, y), wilcox.test(x1, x0)$statistic / N^2) }) test_that("Same as package ModelMetrics (AUC < 0.5)", { skip_if_not_installed("ModelMetrics") for (i in 1:5) { N <- 10^i x4 <- c(sample(10, size = N, replace = TRUE), sample(5, size = N, replace = TRUE)) y4 <- rep(0:1, each = N) expect_equivalent(AUC(x4, y4), ModelMetrics::auc(y4, x4)) } }) test_that("AUC() does not accept missing values", { expect_error(AUC(c(0, 1, NA), c(0, 1, 1)), "missing values") expect_error(AUC(c(0, 1, 0), c(0, 0, NA)), "composed of 0s and 1s") expect_error(AUC(c(0, 1, 0), c(0, 1, NA)), "composed of 0s and 1s") expect_error(AUCBoot(c(0, 1, NA), c(0, 1, 1)), "missing values") expect_error(AUCBoot(c(0, 1, 0), c(0, 0, NA)), "composed of 0s and 1s") expect_error(AUCBoot(c(0, 1, 0), c(0, 1, NA)), "composed of 0s and 1s") }) test_that("AUCBoot() seems okay", { aucs <- AUCBoot(sample(5, 1e4, replace = TRUE), sample(0:1, 1e4, replace = TRUE)) expect_gt(aucs[2], 0.47) expect_lt(aucs[3], 0.53) aucs <- AUCBoot(rnorm(1e4), sample(0:1, 1e4, replace = TRUE)) expect_gt(aucs[2], 0.47) expect_lt(aucs[3], 0.53) })
enspls.od <- function( x, y, maxcomp = 5L, cvfolds = 5L, alpha = seq(0.2, 0.8, 0.2), reptimes = 500L, method = c("mc", "boot"), ratio = 0.8, parallel = 1L) { if (missing(x) | missing(y)) stop("Please specify both x and y") method <- match.arg(method) x.row <- nrow(x) samp.idx <- vector("list", reptimes) samp.idx.remain <- vector("list", reptimes) if (method == "mc") { for (i in 1L:reptimes) { samp.idx[[i]] <- sample(1L:x.row, round(x.row * ratio)) samp.idx.remain[[i]] <- setdiff(1L:x.row, samp.idx[[i]]) } } if (method == "boot") { for (i in 1L:reptimes) { samp.idx[[i]] <- sample(1L:x.row, x.row, replace = TRUE) samp.idx.remain[[i]] <- setdiff(1L:x.row, unique(samp.idx[[i]])) } } if (parallel < 1.5) { errorlist <- vector("list", reptimes) for (i in 1L:reptimes) { x.sample <- x[samp.idx[[i]], ] x.remain <- x[samp.idx.remain[[i]], ] y.sample <- y[samp.idx[[i]]] y.remain <- y[samp.idx.remain[[i]]] errorlist[[i]] <- enspls.od.core( x.sample, y.sample, x.remain, y.remain, maxcomp, cvfolds, alpha ) } } else { registerDoParallel(parallel) errorlist <- foreach(i = 1L:reptimes) %dopar% { x.sample <- x[samp.idx[[i]], ] x.remain <- x[samp.idx.remain[[i]], ] y.sample <- y[samp.idx[[i]]] y.remain <- y[samp.idx.remain[[i]]] enspls.od.core( x.sample, y.sample, x.remain, y.remain, maxcomp, cvfolds, alpha ) } } prederrmat <- matrix(NA, ncol = x.row, nrow = reptimes) for (i in 1L:reptimes) { for (j in 1L:length(samp.idx.remain[[i]])) { prederrmat[i, samp.idx.remain[[i]][j]] <- errorlist[[i]][j] } } errmean <- abs(colMeans(prederrmat, na.rm = TRUE)) errmedian <- apply(prederrmat, 2L, median, na.rm = TRUE) errsd <- apply(prederrmat, 2L, sd, na.rm = TRUE) res <- list( "error.mean" = errmean, "error.median" = errmedian, "error.sd" = errsd, "predict.error.matrix" = prederrmat ) class(res) <- "enspls.od" res } enspls.od.core <- function( x.sample, y.sample, x.remain, y.remain, maxcomp, cvfolds, alpha) { invisible(capture.output( spls.cvfit <- cv.spls( x.sample, y.sample, fold = cvfolds, K = maxcomp, eta = alpha, scale.x = TRUE, scale.y = FALSE, plot.it = FALSE ) )) cv.bestcomp <- spls.cvfit$"K.opt" cv.bestalpha <- spls.cvfit$"eta.opt" spls.fit <- spls( x.sample, y.sample, K = cv.bestcomp, eta = cv.bestalpha, scale.x = TRUE, scale.y = FALSE ) pred <- predict(spls.fit, newx = x.remain) error <- y.remain - pred names(error) <- NULL error }
scRNAtools_DEGsA <- function(example,types_all,type1,type2,num) { edgeR::cpm n<-ncol(example) data1<-example[,-1] zcpm<-cpm(data1) keep<-rowSums(zcpm>1)>=((n-1)*num) zset<-example[keep,] subtype1<-types_all[which(types_all[,1]%in%type1),2] subtype2<-types_all[which(types_all[,1]%in%type2),2] type1_exp<-zset[,which(as.numeric(zset[1,])%in%subtype1)] type2_exp<-zset[,which(as.numeric(zset[1,])%in%subtype2)] group1<-apply(type1_exp[,-1],1, mean) group2<-apply(type2_exp[,-1],1, mean) group1<-as.matrix(group1) group2<-as.matrix(group2) FC1<-group2/group1 FC2<-cbind(as.matrix(zset[,1]),FC1) FC2<-FC2[-1,] FC2[which(FC2[,2]%in%"Inf"),2]<-5 colnames(FC2)<-c("Gene_symbol","Fold_change") up<-FC2[which(FC2[,2]>2),] down<-FC2[which(FC2[,2]<0.5),] no_diff1<-FC2[-which(FC2[,1]%in%up[,1]),] no_diff2<-no_diff1[-which(no_diff1[,1]%in%down[,1]),] main=paste("Differentially expressed genes between",type1,"and",type2) max_v<-as.numeric(max(FC2[,2])) max_n<-max(nrow(up),nrow(down),nrow(no_diff2)) p<-plot(1:nrow(up),up[,2],main=main,ylim=c(0,max_v),xlim=c(0,max_n),xlab = "Gene number",ylab=paste("log2 (",type1,"/",type2,")"),col="red",pch=19,lwd=2) lines(1:nrow(down),down[,2],type="p",ylim=c(0,max_v),xlab = "Gene number",ylab=paste("log2(",type1,"/",type2,")"),col="green",pch=19,lwd=2) lines(1:nrow(no_diff2),no_diff2[,2],type="p",ylim=c(0,max_v),xlab = "Gene number",ylab=paste("log2(",type1,"/",type2,")"),col="gray",pch=19,lwd=2) abline(h = c(0.5, 2),lwd=0.5,lty=3) text((max_n-5),0.2,"log2(FC)=0.5") text((max_n-5),2.2,"log2(FC)=2") legend((max_n-20),(max_v-0.2),c("Up-regulated genes","Not DEGs","Down-regulated genes"),col=c("red","gray","green"),text.col=c("red","gray","green"),pch=19,cex=0.7) return(FC2) }
createJSON <- function(repo, pkg_name, descr_df, scm_df, docdir, rev_deps, suffix = paste0("_", descr_df$Version, ".json")) { reponame <- paste0("GRAN", repo_name(repo)) descr_df$id <- encode_string(paste0(reponame, descr_df$Package, descr_df$Version)) descr_df$gran_repo <- reponame scm_info <- scm_df[scm_df$name == pkg_name, ] descr_df$scm_url <- scm_info$url descr_df$scm_type <- scm_info$type descr_df$scm_branch <- scm_info$branch descr_df$scm_subdir <- scm_info$subdir descr_df$r_version <- R.version$version.string bldresults <- repo_results(repo) bldresults <- bldresults[bldresults$name == pkg_name, ] descr_df$last_attempt_version <- bldresults$lastAttemptVersion descr_df$last_attempt_status <- bldresults$lastAttemptStatus descr_df$last_attempt_date <- bldresults$lastAttempt descr_df$last_built_version <- bldresults$lastbuiltversion descr_df$last_built_status <- bldresults$lastbuiltstatus descr_df$last_built_date <- bldresults$lastbuilt descr_df$is_suspended <- bldresults$suspended doc_url <- paste0(repo_url(repo), basename(pkg_doc_dir(repo)), pkg_name) descr_df$pkgdocs_url <- doc_url descr_df$pkg_sticker <- paste0(doc_url, "/", pkg_name, ".png") descr_list <- lapply(as.list(descr_df), as.vector) reverse_deps <- lapply(as.list(rev_deps), as.vector) combo_list <- append(descr_list, reverse_deps) if ("Imports" %in% names(combo_list)) combo_list$Imports <- .stringToVec(combo_list$Imports) if ("Depends" %in% names(combo_list)) combo_list$Depends <- .stringToVec(combo_list$Depends) if ("Suggests" %in% names(combo_list)) combo_list$Suggests <- .stringToVec(combo_list$Suggests) if ("Enhances" %in% names(combo_list)) combo_list$Enhances <- .stringToVec(combo_list$Enhances) if ("LinkingTo" %in% names(combo_list)) combo_list$LinkingTo <- .stringToVec(combo_list$LinkingTo) if ("ReverseImports" %in% names(combo_list)) combo_list$ReverseImports <- .stringToVec(combo_list$ReverseImports) if ("ReverseDependencies" %in% names(combo_list)) combo_list$ReverseDependencies <- .stringToVec(combo_list$ReverseDependencies) if ("ReverseLinkingTo" %in% names(combo_list)) combo_list$ReverseLinkingTo <- .stringToVec(combo_list$ReverseLinkingTo) if ("ReverseSuggests" %in% names(combo_list)) combo_list$ReverseSuggests <- .stringToVec(combo_list$ReverseSuggests) if ("ReverseEnhances" %in% names(combo_list)) combo_list$ReverseEnhances <- .stringToVec(combo_list$ReverseEnhances) desc_json <- toJSON(combo_list, pretty = TRUE) json_outfile <- file.path(docdir, paste0(pkg_name, suffix)) logfun(repo)(pkg_name, "Writing package metadata JSON file") write(desc_json, json_outfile) } .stringToVec <- function(x) { unlist(strsplit(gsub("[[:blank:]]", "",x), ",")) }
fec.power.limits <- function(meanepg=200, g.faeces=3, sensitivity=1/25, replicates=1, animals=10, coeffvarrep=0.4, coeffvarind=0.3, coeffvargroup=0.7, true.sample=FALSE, lower.limit=NA, upper.limit=NA, iterations=100000, power = 0.95, confidence = 0.99, feedback=FALSE, forcesim=FALSE){ if(power >= 1) stop("Required power must be < 1") if(confidence >= 1) stop("Confidence must be < 1") conf <- (1-confidence)/2 lci <- 0+conf uci <- 1-conf if(replicates < 1 | animals < 1) stop("Specified values for animals and replicates must be greater than 0") if(!is.na(lower.limit) & !is.na(upper.limit)) stop("One or both of lower.limit or upper.limit must be non-fixed (NA)") fix.lower <- !is.na(lower.limit) fix.upper <- !is.na(upper.limit) fixed.lower <- lower.limit fixed.upper <- upper.limit target <- power if(feedback){ if(any(.Platform$GUI == c("AQUA", "Rgui"))){ warning("Printing the progress of the function using the GUI versions of R may massively increase the time taken, I suggest setting feedback=FALSE or using a command line version of R instead") } } if(animals==1 & true.sample==TRUE) coeffvargroup <- 10^-10 if(coeffvargroup > (coeffvarrep+coeffvarind)/10) approximate <- FALSE else approximate <- TRUE if(forcesim) approximate <- FALSE if(animals==1 & true.sample==FALSE) warning("NOTE: The power calculated is for the population from which the animal is derived, to calculate the power for the true mean of this individual use true.sample=TRUE") lowerl <- lower.limit upperl <- upper.limit start <- Sys.time() if(!approximate){ if(true.sample){ out <- .C("poweranalysissamplefixed", as.numeric(meanepg), as.numeric(g.faeces), as.numeric(sensitivity), as.integer(replicates), as.integer(animals), as.numeric(coeffvarrep), as.numeric(coeffvarind), as.numeric(coeffvargroup), as.integer(iterations), as.integer(feedback), numeric(iterations), PACKAGE="bayescount") lo <- length(out) meancounts <- out[[lo]] }else{ out <- .C("poweranalysispopulationfixed", as.numeric(meanepg), as.numeric(g.faeces), as.numeric(sensitivity), as.integer(replicates), as.integer(animals), as.numeric(coeffvarrep), as.numeric(coeffvarind), as.numeric(coeffvargroup), as.integer(iterations), as.integer(feedback), numeric(iterations), PACKAGE="bayescount") lo <- length(out) meancounts <- out[[lo]] } mcs <- meancounts f <- function(limit){ prob <- limit limits <- quantile(mcs, probs=c(0+((1-prob)/2), 1-((1-prob)/2))) nin <- sum(mcs <= limits[2] & mcs >= limits[1]) nout <- length(mcs)-nin med <- qbeta(0.5, nin+1, nout+1) return(med) } if(fix.lower){ f <- function(limit){ nin <- sum(mcs <= limit & mcs >= fixed.lower) nout <- length(mcs)-nin med <- qbeta(0.5, nin+1, nout+1) return(med) } } if(fix.upper){ f <- function(limit){ nin <- sum(mcs <= fixed.upper & mcs >= -limit) nout <- length(mcs)-nin med <- qbeta(0.5, nin+1, nout+1) return(med) } } limits <- c(0,1) if(fix.upper) limits <- c(-Inf,0) if(fix.lower) limits <- c(0,Inf) bsres <- binary.search(f, target, limits) if(bsres$status!="OK"){ if(bsres$status!="Absolute value not possible but this is closest") stop(bsres$status) } if(fix.upper) limits <- c(-bsres$value, fixed.upper) if(fix.lower) limits <- c(fixed.lower, bsres$value) if(!fix.upper & !fix.lower) limits <- quantile(mcs, prob=c(0+((1-bsres$value)/2), 1-((1-bsres$value)/2))) nin <- sum(mcs <= limits[2] & mcs >= limits[1]) nout <- length(mcs)-nin power <- qbeta(c(lci,0.5,uci), nin+1, nout+1) names(limits) <- c("lower.limit", "upper.limit") names(power) <- c(paste("lower.", confidence*100, "%.estimate", sep=""), "median.estimate", paste("upper.", confidence*100, "%.estimate", sep="")) return(list(limits=limits, power=power)) }else{ if(true.sample==FALSE | animals > 1){ coeffvarind <- sqrt(coeffvarind^2 + coeffvargroup^2 + coeffvarind^2*coeffvargroup^2) replicates <- replicates*animals } coeff.var <- sqrt(coeffvarind^2 + (coeffvarrep^2)/g.faeces + (coeffvarind^2 * (coeffvarrep^2)/g.faeces)) eggs.counted <- replicates*meanepg*sensitivity shape <- replicates / coeff.var^2 f <- function(limit){ accuracy <- limit upper.tol <- replicates*sensitivity*(meanepg+meanepg*accuracy) lower.tol <- replicates*sensitivity*(meanepg-meanepg*accuracy) return(pnbinom(upper.tol, size=shape, mu=eggs.counted, lower.tail=TRUE) - pnbinom(lower.tol, size=shape, mu=eggs.counted, lower.tail=TRUE) + suppressWarnings(dnbinom(lower.tol, size=shape, mu=eggs.counted))) } if(fix.lower){ f <- function(limit){ upper.tol <- replicates*sensitivity*(limit) lower.tol <- replicates*sensitivity*(fixed.lower) return(pnbinom(upper.tol, size=shape, mu=eggs.counted, lower.tail=TRUE) - pnbinom(lower.tol, size=shape, mu=eggs.counted, lower.tail=TRUE) + suppressWarnings(dnbinom(lower.tol, size=shape, mu=eggs.counted))) } } if(fix.upper){ f <- function(limit){ upper.tol <- replicates*sensitivity*(fixed.upper) lower.tol <- replicates*sensitivity*(-limit) return(pnbinom(upper.tol, size=shape, mu=eggs.counted, lower.tail=TRUE) - pnbinom(lower.tol, size=shape, mu=eggs.counted, lower.tail=TRUE) + suppressWarnings(dnbinom(lower.tol, size=shape, mu=eggs.counted))) } } limits <- c(0,Inf) if(fix.upper) limits <- c(-Inf,0) if(fix.lower) limits <- c(0,Inf) bsres <- binary.search(f, target, limits) if(bsres$status!="OK"){ if(bsres$status!="Absolute value not possible but this is closest") stop(bsres$status) } if(fix.upper) limits <- c(-bsres$value, fixed.upper) if(fix.lower) limits <- c(fixed.lower, bsres$value) if(!fix.upper & !fix.lower) limits <- c((meanepg-meanepg*bsres$value), (meanepg+meanepg*bsres$value)) power <- replicate(3, bsres$objective) names(limits) <- c("lower.limit", "upper.limit") names(power) <- c("absolute.value", "absolute.value", "absolute.value") return(list(limits=limits, power=power)) } } fec.power <- function(meanepg=200, g.faeces=3, sensitivity=1/25, replicates=1, animals=10, coeffvarrep=0.4, coeffvarind=0.3, coeffvargroup=0.7, true.sample=FALSE, accuracy=0.1, lower.limit=meanepg*(1-accuracy), upper.limit=meanepg*(1+accuracy), maxiterations=1000000, precision=2, confidence = 0.99, feedback=FALSE, forcesim=FALSE){ if(confidence >= 1) stop("Confidence must be < 1") conf <- (1-confidence)/2 lci <- 0+conf uci <- 1-conf if(feedback){ if(any(.Platform$GUI == c("AQUA", "Rgui"))){ warning("Printing the progress of the function using the GUI versions of R may massively increase the time taken, I suggest setting feedback=FALSE or using a command line version of R instead") } } if(replicates < 1 | animals < 1) stop("Specified values for animals and replicates must be greater than 0") if(animals==1 & true.sample==TRUE) coeffvargroup <- 10^-10 if(coeffvargroup > (coeffvarrep+coeffvarind)/10) approximate <- FALSE else approximate <- TRUE if(forcesim) approximate <- FALSE if(animals==1 & true.sample==FALSE) warning("NOTE: The power calculated is for the population from which the animal is derived, to calculate the power for the true mean of this individual use true.sample=TRUE") lowerl <- lower.limit upperl <- upper.limit start <- Sys.time() if(approximate){ if(true.sample==FALSE){ coeffvarind <- sqrt(coeffvarind^2 + coeffvargroup^2 + coeffvarind^2*coeffvargroup^2) replicates <- replicates*animals } coeff.var <- sqrt(coeffvarind^2 + (coeffvarrep^2)/g.faeces + (coeffvarind^2 * (coeffvarrep^2)/g.faeces)) eggs.counted <- replicates*meanepg*sensitivity upper.tol <- replicates*sensitivity*(upperl) lower.tol <- replicates*sensitivity*(lowerl) shape <- replicates / coeff.var^2 nbpower <- pnbinom(upper.tol, size=shape, mu=eggs.counted, lower.tail=TRUE) - pnbinom(lower.tol, size=shape, mu=eggs.counted, lower.tail=TRUE) + suppressWarnings(dnbinom(lower.tol, size=shape, mu=eggs.counted)) time <- timestring(start, Sys.time(), units="s", show.units=FALSE) output = list(roundedci=replicate(3, round(nbpower, precision)), ci=replicate(3, nbpower)) }else{ if(true.sample){ if(is.na(precision)){ out <- .C("poweranalysissamplefixed", as.numeric(meanepg), as.numeric(g.faeces), as.numeric(sensitivity), as.integer(replicates), as.integer(animals), as.numeric(coeffvarrep), as.numeric(coeffvarind), as.numeric(coeffvargroup), as.integer(maxiterations), as.integer(feedback), numeric(maxiterations), PACKAGE="bayescount") lo <- length(out) meancounts <- out[[lo]] nin <- sum(meancounts >= lowerl & meancounts <= upperl) nout <- length(meancounts)-nin time <- timestring(start, Sys.time(), units="s", show.units=FALSE) output=list(roundedci=round(qbeta(c(lci, 0.5, uci), nin+1, nout+1), precision), ci=qbeta(c(lci, 0.5, uci), nin+1, nout+1), within=nin, without=nout, total=nin+nout) }else{ out <- .C("poweranalysissample", as.numeric(meanepg), as.numeric(g.faeces), as.numeric(sensitivity), as.integer(replicates), as.integer(animals), as.numeric(coeffvarrep), as.numeric(coeffvarind), as.numeric(coeffvargroup), as.numeric(lowerl), as.numeric(upperl), as.integer(maxiterations), as.integer(precision), as.numeric(lci), as.numeric(uci), as.integer(feedback), as.integer(0), as.integer(0), PACKAGE="bayescount") lo <- length(out) time <- timestring(start, Sys.time(), units="s", show.units=FALSE) output=list(roundedci = round(qbeta(c(lci, 0.5, uci), out[[lo-1]]+1, (out[[lo]]-out[[lo-1]])+1), precision), ci=qbeta(c(lci, 0.5, uci), out[[lo-1]]+1, (out[[lo]]-out[[lo-1]])+1), within=out[[lo-1]], without=out[[lo]]-out[[lo-1]], total=out[[lo]]) } }else{ if(is.na(precision)){ out <- .C("poweranalysispopulationfixed", as.numeric(meanepg), as.numeric(g.faeces), as.numeric(sensitivity), as.integer(replicates), as.integer(animals), as.numeric(coeffvarrep), as.numeric(coeffvarind), as.numeric(coeffvargroup), as.integer(maxiterations), as.integer(feedback), numeric(maxiterations), PACKAGE="bayescount") lo <- length(out) meancounts <- out[[lo]] nin <- sum(meancounts >= lowerl & meancounts <= upperl) nout <- length(meancounts)-nin time <- timestring(start, Sys.time(), units="s", show.units=FALSE) output=list(roundedci=round(qbeta(c(lci, 0.5, uci), nin+1, nout+1), precision), ci=qbeta(c(lci, 0.5, uci), nin+1, nout+1), within=nin, without=nout, total=nin+nout) }else{ out <- .C("poweranalysispopulation", as.numeric(meanepg), as.numeric(g.faeces), as.numeric(sensitivity), as.integer(replicates), as.integer(animals), as.numeric(coeffvarrep), as.numeric(coeffvarind), as.numeric(coeffvargroup), as.numeric(lowerl), as.numeric(upperl), as.integer(maxiterations), as.integer(precision), as.numeric(lci), as.numeric(uci), as.integer(feedback), as.integer(0), as.integer(0), PACKAGE="bayescount") lo <- length(out) time <- timestring(start, Sys.time(), units="s", show.units=FALSE) output=list(roundedci = round(qbeta(c(lci, 0.5, uci), out[[lo-1]]+1, (out[[lo]]-out[[lo-1]])+1), precision), ci=qbeta(c(lci, 0.5, uci), out[[lo-1]]+1, (out[[lo]]-out[[lo-1]])+1), within=out[[lo-1]], without=out[[lo]]-out[[lo-1]], total=out[[lo]]) } } } if(approximate){ names(output$roundedci) <- c("absolute.value", "absolute.value", "absolute.value") names(output$ci) <- c("absolute.value", "absolute.value", "absolute.value") }else{ names(output$roundedci) <- c(paste("lower.", confidence*100, "%", sep=""), "median", paste("upper.", confidence*100, "%", sep="")) names(output$ci) <- c(paste("lower.", confidence*100, "%", sep=""), "median", paste("upper.", confidence*100, "%", sep="")) } return(output) } FEC.power.limits <- fec.power.limits FEC.precision <- fec.power.limits fec.precision <- fec.power.limits count.precision <- fec.precision FEC.power <- fec.power count.power <- fec.power
sdp_multi <- function (Q, capacity, target, surface_area, max_depth, evap, R_max = 2 * target, spill_targ = 0.95, vol_targ = 0.75, Markov = FALSE, weights = c(0.7, 0.2, 0.1), S_disc = 1000, R_disc = 10, Q_disc = c(0.0, 0.2375, 0.4750, 0.7125, 0.95, 1.0), loss_exp = c(2,2,2), S_initial = 1, plot = TRUE, tol = 0.99, rep_rrv = FALSE){ frq <- frequency(Q) if (is.ts(Q)==FALSE) stop("Q must be seasonal time series object with frequency of 12 or 4") if (frq != 12 && frq != 4) stop("Q must have frequency of 4 or 12") if (missing(evap)) { evap <- ts(rep(0, length(Q)), start = start(Q), frequency = frq) } if(length(evap) == 1) { evap <- ts(rep(evap, length(Q)), start = start(Q), frequency = frq) } if (length(evap) != length(Q) && length(evap) != frq){ stop("Evaporation must be either a time series of length Q, a vector of length frequency(Q), or a single numeric constant") } if (start(Q)[2] != 1){ message("NOTE: First incomplete year of time series removed") Q <- window(Q, start = c(start(Q)[1] + 1, 1), frequency = frq) } if(end(Q)[2] != frq){ message("NOTE: Final incomplete year of time series removed") Q <- window(Q, end = c(end(Q)[1] - 1, frq), frequency = frq) } if (length(evap) == frq){ evap <- ts(rep(evap, length(Q) / frq), start = start(Q), frequency = frq) } else { if(is.ts(evap)==FALSE) stop("Evaporation must be either a time series of length Q or a vector of length frequency(Q) for a seasonal evaporation profile") evap <- window(evap, start = start(Q), end = end(Q), frequency = frq) } if (missing(surface_area)) { surface_area <- 0 } evap_seas <- as.vector(tapply(evap, cycle(evap), FUN = mean)) if (Markov == FALSE){ Q_month_mat <- matrix(Q, byrow = TRUE, ncol = frq) Q.probs <- diff(Q_disc) Q_class_med <- apply(Q_month_mat, 2, quantile, type = 8, probs = Q_disc[-1] - (Q.probs / 2)) S_states <- seq(from = 0, to = capacity, by = capacity / S_disc) R_disc_x <- seq(from = 0, to = R_max, by = R_max / R_disc) Shell.array <- array(0,dim=c(length(S_states),length(R_disc_x),length(Q.probs))) Cost_to_go <- vector("numeric",length=length(S_states)) Results_mat <- matrix(0,nrow=length(S_states),ncol=frq) R_policy <- matrix(0,nrow=length(S_states),ncol=frq) Bellman <- R_policy R_policy_test <- R_policy } else if (Markov == TRUE){ Q_month_mat <- matrix(Q, byrow = TRUE, ncol = frq) n_Qcl <- length(Q_disc) - 1 Q.probs <- diff(Q_disc) Q_class_med <- apply(Q_month_mat, 2, quantile, type = 8, probs = Q_disc[-1] - (Q.probs / 2)) S_states <- seq(from = 0, to = capacity, by = capacity / S_disc) R_disc_x <- seq(from = 0, to = R_max, by = R_max / R_disc) Shell.array <- array(0, dim = c(length(S_states), length(R_disc_x), length(Q.probs))) Q_class.mat <- matrix(nrow=length(Q_month_mat[,1]),ncol=frq) for (m in 1:frq){ Q_disc_x <- gtools::quantcut(Q_month_mat[,m], Q_disc) Q_class.mat[,m] <- as.numeric(as.vector(factor(Q_disc_x, labels = c(1:n_Qcl)))) } Q_trans_probs <- array(0, c(length(Q_disc) - 1, length(Q_disc) - 1, frq)) for (m in 1 : frq){ for (cl in 1 : n_Qcl){ if (m == frq){ Tr.count <- table(factor(Q_class.mat[which(Q_class.mat[1:(length(Q_month_mat[,1]) - 1), frq] == cl) + 1, 1], 1:n_Qcl)) }else{ Tr.count <- table(factor(Q_class.mat[which(Q_class.mat[,m] == cl), m + 1], 1:n_Qcl)) } Tr.freq <- Tr.count / sum(Tr.count) Q_trans_probs[cl,,m] <- Tr.freq }} Cost_to_go <- matrix(0, nrow = (length(S_states)), ncol = n_Qcl) R_policy <- array(0,dim = c(length(S_states), n_Qcl, frq)) Bellman <- R_policy R_policy_test <- R_policy } if (missing(max_depth)){ c <- sqrt(2) / 3 * (surface_area * 10 ^ 6) ^ (3/2) / (capacity * 10 ^ 6) GetLevel <- function(c, V){ y <- (6 * V / (c ^ 2)) ^ (1 / 3) return(y) } GetArea <- function(c, V){ Ay <- (((3 * c * V) / (sqrt(2))) ^ (2 / 3)) return(Ay) } } else { c <- 2 * capacity / (max_depth * surface_area) GetLevel <- function(c, V){ y <- max_depth * (V / (capacity * 10 ^ 6)) ^ (c / 2) return(y) } GetArea <- function(c, V){ Ay <- ((2 * (capacity * 10 ^ 6)) / (c * max_depth * (V / (capacity * 10 ^ 6)) ^ (c / 2))) * ((V / (capacity * 10 ^ 6)) ^ (c / 2)) ^ (2 / c) Ay[which(is.nan(Ay) == TRUE)] <- 0 return(Ay) } } GetEvap <- function(s, q, r, ev){ e <- GetArea(c, V = s * 10 ^ 6) * ev / 10 ^ 6 n <- 0 repeat{ n <- n + 1 s_plus_1 <- max(min(s + q - r - e, capacity), 0) e_x <- GetArea(c, V = ((s + s_plus_1) / 2) * 10 ^ 6) * ev / 10 ^ 6 if (abs(e_x - e) < 0.001 || n > 20){ break } else { e <- e_x } } return(e) } S_area_rel <- GetArea(c, V = S_states * 10 ^ 6) message(paste0("policy converging... (>", tol,")")) if (Markov == FALSE){ repeat{ for (t in frq:1){ R.cstr <- sweep(Shell.array, 3, Q_class_med[,t], "+") + sweep(Shell.array, 1, S_states, "+") - sweep(Shell.array, 1, evap_seas[t] * S_area_rel / 10 ^ 6, "+") R.star <- aperm(apply(Shell.array, c(1, 3), "+", R_disc_x), c(2, 1, 3)) R.star[,2:(R_disc + 1),][which(R.star[,2:(R_disc + 1),] > R.cstr[,2 : (R_disc + 1),])] <- NaN Deficit.arr <- (target - R.star) / target Deficit.arr[which(Deficit.arr < 0)] <- 0 Cost_arr <- ( (abs(Deficit.arr)) ^ loss_exp[1]) S.t_plus_1 <- R.cstr - R.star S.t_plus_1[which(S.t_plus_1 < 0)] <- 0 Spill_costs <- S.t_plus_1 - capacity Spill_costs[which(Spill_costs < 0)] <- 0 Spill_costs <- (Spill_costs / quantile(Q, spill_targ)) ^ loss_exp[2] S.t_plus_1[which(S.t_plus_1 > capacity)] <- capacity Vol_costs <- abs(((S.t_plus_1 - vol_targ * capacity) / (vol_targ * capacity))) ^ loss_exp[3] Implied_S_state <- round(1 + (S.t_plus_1 / capacity) * (length(S_states) - 1)) Cost_arr <- weights[1] * Cost_arr + weights[2] * Spill_costs + weights[3] * Vol_costs Cost_to_go.arr <- array(Cost_to_go[Implied_S_state], dim = c(length(S_states), length(R_disc_x) , length(Q.probs))) Min_cost_arr <- Cost_arr + Cost_to_go.arr Min_cost_arr_weighted <- sweep(Min_cost_arr, 3, Q.probs, "*") Min_cost_expected <- apply(Min_cost_arr_weighted, c(1, 2), sum) Bellman[,t] <- Cost_to_go Cost_to_go <- apply(Min_cost_expected, 1, min, na.rm = TRUE) Results_mat[,t] <- Cost_to_go R_policy[,t] <- apply(Min_cost_expected, 1, which.min) } message(sum(R_policy == R_policy_test) / (frq * length(S_states))) if (sum(R_policy == R_policy_test) / (frq * length(S_states)) > tol){ break } R_policy_test <- R_policy } } else if (Markov == TRUE){ repeat{ for (t in frq:1){ R.cstr <- sweep(Shell.array, 3, Q_class_med[,t], "+") + sweep(Shell.array, 1, S_states, "+") - sweep(Shell.array, 1, evap_seas[t] * S_area_rel / 10 ^ 6, "+") R.star <- aperm(apply(Shell.array, c(1, 3), "+", R_disc_x), c(2, 1, 3)) R.star[,2:(R_disc + 1),][which(R.star[,2:(R_disc + 1),] > R.cstr[,2 : (R_disc + 1),])] <- NaN Deficit.arr <- (target - R.star) / target Deficit.arr[which(Deficit.arr < 0)] <- 0 Cost_arr <- ( (abs(Deficit.arr)) ^ loss_exp[1]) S.t_plus_1 <- R.cstr - R.star S.t_plus_1[which(S.t_plus_1 < 0)] <- 0 Spill_costs <- S.t_plus_1 - capacity Spill_costs[which(Spill_costs < 0)] <- 0 Spill_costs <- (Spill_costs / quantile(Q, spill_targ)) ^ loss_exp[2] S.t_plus_1[which(S.t_plus_1 > capacity)] <- capacity Vol_costs <- abs(((S.t_plus_1 - vol_targ * capacity) / (vol_targ * capacity))) ^ loss_exp[3] Implied_S_state <- round(1 + (S.t_plus_1 / capacity) * (length(S_states) - 1)) Cost_arr <- weights[1] * Cost_arr + weights[2] * Spill_costs + weights[3] * Vol_costs Cost_to_go.arr <- array(Cost_to_go, dim = c(length(S_states), n_Qcl, n_Qcl)) Expectation <- apply(sweep(Cost_to_go.arr, c(2,3), t(Q_trans_probs[,,t]), "*"), c(1,3), sum) Exp.arr <- Shell.array for (Qt in 1:n_Qcl){ Exp.arr[,,Qt] <- matrix(Expectation[,Qt][Implied_S_state[,,Qt]], ncol = length(R_disc_x)) } R_policy[,,t] <- apply( (Cost_arr + Exp.arr), c(1,3), which.min) Cost_to_go <- apply( (Cost_arr + Exp.arr), c(1,3), min, na.rm = TRUE) Bellman[,,t] <- Cost_to_go } message(sum(R_policy == R_policy_test) / (frq * length(S_states) * n_Qcl)) if (sum(R_policy == R_policy_test) / (frq * length(S_states) * n_Qcl) > tol){ break } R_policy_test <- R_policy } } S <- vector("numeric",length(Q) + 1); S[1] <- S_initial * capacity R_rec <- vector("numeric",length(Q)) E <- vector("numeric", length(Q)) y <- vector("numeric", length(Q)) Spill <- vector("numeric",length(Q)) for (yr in 1:nrow(Q_month_mat)) { for (month in 1:frq) { t_index <- (frq * (yr - 1)) + month S_state <- which.min(abs(S_states - S[t_index])) Qx <- Q_month_mat[yr,month] if (Markov == FALSE){ R <- R_disc_x[R_policy[S_state,month]] } else if (Markov == TRUE){ Q_class <- which.min(abs(as.vector(Q_class_med[,month] - Qx))) R <- R_disc_x[R_policy[S_state,Q_class,month]] } R_rec[t_index] <- R E[t_index] <- GetEvap(s = S[t_index], q = Qx, r = R, ev = evap[t_index]) y[t_index] <- GetLevel(c, S[t_index] * 10 ^ 6) if ( (S[t_index] - R + Qx - E[t_index]) > capacity) { S[t_index + 1] <- capacity Spill[t_index] <- S[t_index] - R + Qx - capacity - E[t_index] }else{ if ( (S[t_index] - R + Qx) < 0) { S[t_index + 1] <- 0 R_rec[t_index] <- max(0, S[t_index] + Qx - E[t_index]) }else{ S[t_index + 1] <- S[t_index] - R + Qx - E[t_index] } } } } R_policy <- (R_policy - 1) / R_disc S <- ts(S[1:(length(S) - 1)],start = start(Q),frequency = frq) R_rec <- ts(R_rec, start = start(Q), frequency = frq) E <- ts(E, start = start(Q), frequency = frequency(Q)) y <- ts(y, start = start(Q), frequency = frequency(Q)) Spill <- ts(Spill, start = start(Q), frequency = frq) if(plot) { plot(R_rec, ylab = "Controlled release", ylim = c(0, R_max)); abline(h = target, lty = 2) plot(S, ylab = "Storage", ylim = c(0, capacity)); abline(h = vol_targ * capacity, lty = 2) plot(Spill, ylab = "Uncontrolled spill") } total_release_cost <- sum((1 - R_rec/target)[which((R_rec/target) < 1)] ^ loss_exp[1]) total_spill_cost <- sum((Spill / quantile(Q, spill_targ)) ^ loss_exp[2]) total_volume_cost <- sum(((S - vol_targ * capacity) / (vol_targ * capacity)) ^ loss_exp[3]) total_weighted_cost <- weights[1] * total_release_cost + weights[2] * total_spill_cost + weights[3] * total_volume_cost costs <- list(total_release_cost, total_spill_cost, total_volume_cost, total_weighted_cost) names(costs) <- c("total_release_cost", "total_spill_cost", "total_volume_cost", "total_weighted_cost") if (rep_rrv == TRUE){ deficit <- ts(round(1 - (R_rec / target),5), start = start(Q), frequency = frequency(Q)) rel_ann <- sum(aggregate(deficit, FUN = mean) == 0) / length(aggregate(deficit, FUN = mean)) rel_time <- sum(deficit == 0) / length(deficit) rel_vol <- sum(R_rec) / (target * length(deficit)) fail.periods <- which(deficit > 0) if (length(fail.periods) == 0) { resilience <- NA vulnerability <- NA } else { if (length(fail.periods) == 1) { resilience <- 1 vulnerability <- max(deficit) } else { resilience <- (sum(diff(which(deficit > 0)) > 1) + 1) / (length(which(deficit > 0))) fail.refs <- vector("numeric", length = length(fail.periods)) fail.refs[1] <- 1 for (j in 2:length(fail.periods)) { if (fail.periods[j] > (fail.periods[j - 1] + 1)) { fail.refs[j] <- fail.refs[j - 1] + 1 } else { fail.refs[j] <- fail.refs[j - 1] } } n.events <- max(fail.refs) event.starts <- by(fail.periods, fail.refs, FUN = min) event.ends <- by(fail.periods, fail.refs, FUN = max) max.deficits <- vector("numeric", length = n.events) for (k in 1:n.events) { max.deficits[k] <- max(deficit[event.starts[k]:event.ends[k]]) } vulnerability <- mean(max.deficits) } } results <- list(R_policy, Bellman, S, R_rec, E, y, Spill, rel_ann, rel_time, rel_vol, resilience, vulnerability, Q_disc, costs) names(results) <- c("release_policy", "Bellman", "storage", "releases", "evap_loss", "water_level", "spill", "annual_reliability", "time_based_reliability", "volumetric_reliability", "resilience", "vulnerability", "flow_disc", "costs") } else { results <- list(R_policy, Bellman, S, R_rec, E, y, Spill, Q_disc, costs) names(results) <- c("release_policy", "Bellman", "storage", "releases", "evap_loss", "water_level", "spill", "flow_disc", "total_costs") } return(results) }
dynsi <- function(formula, model, factors, cumul=FALSE, simulonly=FALSE, nb.outp=NULL, Name.File=NULL, ...) { if(is.null(dim(factors))){ multisensi.design=planfact.as d.args=factors }else{ multisensi.design=factors d.args=list() } result <- multisensi(design=multisensi.design, model=model, reduction=NULL, dimension=nb.outp, center=FALSE, scale=FALSE, analysis=analysis.anoasg, cumul=cumul, simulonly=simulonly, Name.File=Name.File, design.args=d.args, analysis.args=list(formula=formula,keep.ouputs=FALSE), ...) cat("Warning : dynsi function can now be replaced by a call to the multisensi function. It is kept for compatibility with Version 1 of the multisensi package.\n") cat("You may use multisensi function instead, like this :\n") print(result$call.info$call) return(result) }
rinvchisq <- function (n, df, scale = 1/df) { if ((length(scale) != 1) & (length(scale) != n)) stop("scale should have the same length as n") if (df <= 0) stop("df must be greater than zero") if (any(scale <= 0)) stop("scale must be greater than zero") (df * scale)/rchisq(n, df = df) }
loadThresholds <- function(cpmType, ARL0, desiredLength=5000,lambda=NA, startup=20) { if (!is.na(lambda)) { lambda <- gsub("\\.","",lambda) cpmType <- sprintf("%s%s",cpmType,lambda) } str <- sprintf("%sARL%s",cpmType,ARL0) thresholds <- c(rep(99999,19),cpmthresholds[[str]][,1]) thresholds <- thresholds[!is.na(thresholds)] len <- length(thresholds) if (len< desiredLength) { thresholds <- c(thresholds,rep(mean(thresholds[(len-100):len]), desiredLength-len)) } return(thresholds) }
data_dir <- file.path("..", "testdata") tempfile_nc <- function() { tempfile_helper("monvar_") } file_out <- tempfile_nc() monvar("SIS", file.path(data_dir, "ex_mon.nc"), file_out) file <- nc_open(file_out) test_that("data is correct", { actual <- ncvar_get(file, "SIS") expected_data <- c( 18600.0,18600.0,18600.0, 18600.0,18600.0,18600.0, 18600.0,18600.0,18600.0, 18600.0,18600.0,18600.0, 18600.0,18600.0,18600.0, 16312.5,16312.5,16312.5, 16312.5,16312.5,16312.5, 16312.5,16312.5,16312.5, 16312.5,16312.5,16312.5, 16312.5,16312.5,16312.5, 115245.164,115245.164,115245.164, 115245.164,104890.32,115245.164, 115245.164,115245.164,104890.32, 104890.32,115245.164,115245.164, 115245.164,104890.32,104890.32 ) expected <- array(expected_data, dim = c(5,3,3)) expect_equivalent(actual, expected, tolerance = 1e-8) }) test_that("attributes are correct", { actual <- ncatt_get(file, "lon", "units")$value expect_equal(actual, "degrees_east") actual <- ncatt_get(file, "lon", "long_name")$value expect_equal(actual, "longitude") actual <- ncatt_get(file, "lon", "standard_name")$value expect_equal(actual, "longitude") actual <- ncatt_get(file, "lon", "axis")$value expect_equal(actual, "X") actual <- ncatt_get(file, "lat", "units")$value expect_equal(actual, "degrees_north") actual <- ncatt_get(file, "lat", "long_name")$value expect_equal(actual, "latitude") actual <- ncatt_get(file, "lat", "standard_name")$value expect_equal(actual, "latitude") actual <- ncatt_get(file, "lat", "axis")$value expect_equal(actual, "Y") actual <- ncatt_get(file, "time", "units")$value expect_equal(actual, "hours since 1983-01-01 00:00:00") actual <- ncatt_get(file, "time", "long_name")$value expect_equal(actual, "time") actual <- ncatt_get(file, "time", "standard_name")$value expect_equal(actual, "time") actual <- ncatt_get(file, "time", "calendar")$value expect_equal(actual, "standard") actual <- ncatt_get(file, "SIS", "standard_name")$value expect_equal(actual, "SIS_standard") actual <- ncatt_get(file, "SIS", "long_name")$value expect_equal(actual, "Surface Incoming Shortwave Radiation") actual <- ncatt_get(file, "SIS", "units")$value expect_equal(actual, "W m-2") actual <- ncatt_get(file, "SIS", "_FillValue")$value expect_equal(actual, -999) actual <- ncatt_get(file, "SIS", "cmsaf_info")$value expect_equal(actual, "cmsafops::monvar for variable SIS") global_attr <- ncatt_get(file, 0) expect_equal(length(global_attr), 1) actual <- names(global_attr[1]) expect_equal(actual, "Info") actual <- global_attr[[1]] expect_equal(actual, "Created with the CM SAF R Toolbox.") }) test_that("coordinates are correct", { actual <- ncvar_get(file, "lon") expect_identical(actual, array(seq(5, 6, by = 0.5))) actual <- ncvar_get(file, "lat") expect_identical(actual, array(seq(45, 47, by = 0.5))) actual <- ncvar_get(file, "time") expect_equal(actual, array(c(149016, 149760, 150456))) }) nc_close(file) test_that("no error is thrown if var does not exist", { file_out <- tempfile_nc() expect_warning(monsd("someVariable", file.path(data_dir, "ex_mon.nc"), file_out), "Variable 'someVariable' not found. Variable 'SIS' will be used instead.") }) test_that("no error is thrown if var is empty", { file_out <- tempfile_nc() expect_warning(monsd("", file.path(data_dir, "ex_mon.nc"), file_out), "Variable '' not found. Variable 'SIS' will be used instead.") }) test_that("error is thrown if var is NULL", { file_out <- tempfile_nc() expect_error( monsd(NULL, file.path(data_dir, "ex_mon.nc"), file_out), "variable must not be NULL" ) }) test_that("error is thrown if input file does not exist", { file_out <- tempfile_nc() expect_error( monsd("SIS", file.path(data_dir, "ex_doesNotExist.nc"), file_out), "Input file does not exist") }) test_that("error is thrown if input file is empty", { file_out <- tempfile_nc() expect_error( monsd("SIS", "", file_out), "Input file does not exist") }) test_that("error is thrown if input file is NULL", { file_out <- tempfile_nc() expect_error( monsd("SIS", NULL, file_out), "Input filepath must be of length one and not NULL") }) test_that("no error is thrown if output file already exists", { file_out <- tempfile_nc() cat("test\n", file = file_out) expect_error( monsd("SIS", file.path(data_dir, "ex_mon.nc"), file_out), paste0("File '", file_out, "' already exists. Specify 'overwrite = TRUE' if you want to overwrite it."), fixed = TRUE ) expect_equal(readLines(con = file_out), "test") }) test_that("no error is thrown if overwrite = TRUE", { file_out <- tempfile_nc() cat("test\n", file = file_out) expect_error( monsd("SIS", file.path(data_dir, "ex_mon.nc"), file_out, overwrite = TRUE), NA ) }) test_that("no error is thrown if output file already exists", { expect_error( monsd("SIS", file.path(data_dir, "ex_mon.nc"), NULL), "Output filepath must be of length one and not NULL" ) })
library(testthat) library(d3r) test_check("d3r")
fit.gpd <- function(x,method="LM",na.rm=TRUE, record.cpu.time = TRUE,return.data=FALSE,LambdaZeroEpsilon=1e-15){ if(record.cpu.time) { time.1 <- as.numeric(proc.time()[3]) } else { time.1 <- "not timing" } if (method == "LM") {method.name="Method of L-Moments"} if (method == "SM") {method.name="Starship"} if (method == "starship") { method.name="Starship" method="SM" } if (method == "LM") { results <- fit.gpd.lmom(data=x,na.rm=na.rm,LambdaZeroEpsilon=LambdaZeroEpsilon) } if (method == "SM") { if (na.rm) { original.n = length(x) x = x[!is.na(x)] } starship.results <- starship(data=x,param="gpd",return.data=FALSE) region = gldGPDRegionID(pars=starship.results$lambda) if (region == "A"){ results = list(estA=starship.results$lambda,estB=NULL,param="gpd",starship=starship.results) } if (region == "B"){ results = list(estA=NULL,estB=starship.results$lambda,param="gpd",starship=starship.results) } } if (record.cpu.time) { time.2 <- as.numeric(proc.time()[3]); runtime <- round(time.2-time.1,2) results$cpu <- runtime } if (return.data) {results$data = x} class(results) <- "GldGPDFit" results } fit.gpd.lmom <- function(data,na.rm=TRUE,LambdaZeroEpsilon=1e-15){ if (na.rm){ dataNArm <- data[!is.na(data)] } else { if (any(is.na(data))) { stop(paste("NA values in ",deparse(substitute(data)),". use na.rm=TRUE to fit these data.",sep=""))} else {dataNArm <- data} } fit.gpd.lmom.given(lmoms=lmom::samlmu(dataNArm,nmom=4),n=length(dataNArm),LambdaZeroEpsilon=LambdaZeroEpsilon) } fit.gpd.lmom.given <- function(lmoms,n=NULL,LambdaZeroEpsilon=1e-15){ if (length(lmoms) < 4) {stop("4 L-Moments are required to fit the GLD gpd.\nArgument lmoms of fit.gpd.lmom.given is less than 4 long.")} t4 <- lmoms[4] t3 <- lmoms[3] l2 <- lmoms[2] l1 <- lmoms[1] el.1 <- (3+7*t4) if (abs(t3)>=1){problem=paste("No estimates possible, impossible sample Tau 3 value: Tau3=",t3,"outside (-1,1) range\n") warning(problem) res <- list(estA=NA,estB=NA,warn=problem,param="gpd") class(res) <- "GldGPDFit" return(res)} if ( (5*t3^2-1)/4 > t4 ){problem = paste("No estimates possible, impossible sample Tau3/Tau4 combination. (5*Tau3^2-1)/4 =",(5*t3^2-1)/4,"must be <= Tau4 =",t4,"\n") warning(problem) res <- list(estA=NA,estB=NA,warn=problem,param="gpd") class(res) <- "GldGPDFit" return(res)} if (t4 < -0.25){problem = paste("No estimates possible, impossible sample Tau 4 value: Tau4=",t4,"< -0.25\n") warning(problem) res <- list(estA=NA,estB=NA,warn=problem,param="gpd") class(res) <- "GldGPDFit" return(res)} if (t4>=1){problem = paste("No estimates possible, impossible sample Tau 4 value: Tau4=",t4,">= 1\n") warning(problem) res <- list(estA=NA,estB=NA,warn=problem,param="gpd") class(res) <- "GldGPDFit" return(res)} if ((t4^2+98*t4+1)<0) {problem = paste("No estimates possible, Tau4 too low (lowest possible value is approx -0.0102051). Tau4 here is ",t4,"\n") warning(problem) res <- list(estA=NA,estB=NA,warn=problem,param="gpd") class(res) <- "GldGPDFit" return(res)} el.2 <- sqrt(t4^2+98*t4+1) denom <- (2*(1-t4)) lambdahatA <- (el.1 - el.2 )/ denom lambdahatB <- (el.1 + el.2 )/ denom deltahatA <- 0.5*(1-(t3*(lambdahatA+3))/(lambdahatA-1)) deltahatB <- 0.5*(1-(t3*(lambdahatB+3))/(lambdahatB-1)) betahatA <- l2*(lambdahatA+1)*(lambdahatA+2) betahatB <- l2*(lambdahatB+1)*(lambdahatB+2) alphahatA <- l1+(betahatA*(1-2*deltahatA))/(lambdahatA+1) alphahatB <- l1+(betahatB*(1-2*deltahatB))/(lambdahatB+1) if (abs(lambdahatA)<LambdaZeroEpsilon) { AisSLD = TRUE lambdahatA = 0 } else {AisSLD = FALSE} lmomestA <- c(alphahatA,betahatA,deltahatA,lambdahatA) if (gl.check.lambda(lmomestA,param="gpd")) { names(lmomestA) <- c("alpha","beta","delta","lambda") RegionAest = TRUE} else {lmomestA <- NA RegionAest = FALSE} lmomestB <- c(alphahatB,betahatB,deltahatB,lambdahatB) if (gl.check.lambda(lmomestB,param="gpd")) { names(lmomestB) <- c("alpha","beta","delta","lambda") RegionBest = TRUE } else { lmomestB = NA RegionBest = FALSE} if (!is.null(n)){ if (RegionAest){ if (AisSLD){ warning("Since lambda estimate is zero, the estimated distribution\nis a special case, the Quantile Based Skew Logistic Distribution.\nNo standard errors are available for lambda, but SEs for the other\nparameters are given from the Quantile Based SLD.\n") omega = lmomestA[3]*(1-lmomestA[3]) se.alpha = lmomestA[2] * sqrt((57 + (125*pi^2-1308)*omega)/(15*n)) se.beta = lmomestA[2] * sqrt(4/(3*n) * (1 - (pi^2-8)*omega)) se.delta = sqrt((8-(397+160*omega-20*pi^2*(omega+2))*omega)/(15*n)) lmomestA <- cbind(lmomestA,c(se.alpha,se.beta,se.delta,NA)) dimnames(lmomestA) <- list(c("alpha","beta","delta","lambda"),c("Estimate","Std. Error")) } else { if (lambdahatA > -0.5) { alphahatA.se = se.alphahat(alphahatA,betahatA,deltahatA,lambdahatA,n) betahatA.se = se.betahat(alphahatA,betahatA,deltahatA,lambdahatA,n) deltahatA.se = se.deltahat(alphahatA,betahatA,deltahatA,lambdahatA,n) lambdahatA.se = se.lambdahat(alphahatA,betahatA,deltahatA,lambdahatA,n) SEs.A = c(alphahatA.se,betahatA.se,deltahatA.se,lambdahatA.se) lmomestA = cbind(lmomestA,SEs.A) dimnames(lmomestA)[[2]] = c("Estimate","Std. Error") } else { warning("Region A Standard Errors are undefined since lambda is estimated as <= -0.5\n")} } } if (RegionBest) { if (lmomestB[4] == 0){ warning("Since lambda estimate is zero, the estimate is a special case,\nthe Quantile Based Skew Logistic Distribution. No standard errors are available for lambda,\nbut SEs for the other parameters are given from the Quantile Based SLD.\n") omega = lmomestB$delta*(1-lmomestB$delta) se.alpha = lmomestB$beta * sqrt((57 + (125*pi^2-1308)*omega)/(15*n)) se.beta = lmomestB$beta * sqrt(4/(3*n) * (1 - (pi^2-8)*omega)) se.delta = sqrt((8-(397+160*omega-20*pi^2*(omega+2))*omega)/(15*n)) lmomestB <- cbind(lmomestB,c(se.alpha,se.beta,se.delta,NA)) dimnames(lmomestB) <- list(c("alpha","beta","delta","lambda"),c("Estimate","Std. Error")) } else { if (lambdahatB > -0.5) { alphahatB.se = se.alphahat(alphahatB,betahatB,deltahatB,lambdahatB,n) betahatB.se = se.betahat(alphahatB,betahatB,deltahatB,lambdahatB,n) deltahatB.se = se.deltahat(alphahatB,betahatB,deltahatB,lambdahatB,n) lambdahatB.se = se.lambdahat(alphahatB,betahatB,deltahatB,lambdahatB,n) SEs.B = c(alphahatB.se,betahatB.se,deltahatB.se,lambdahatB.se) lmomestB = cbind(lmomestB,SEs.B) dimnames(lmomestB)[[2]] = c("Estimate","Std. Error") } else { warning("Region B Standard Errors are undefined since lambda is estimated as <= -0.5\n") } } } ret <- list(estA=lmomestA,estB=lmomestB,param="gpd") } if (RegionAest){ ret <- list(estA=lmomestA,estB=lmomestB,param="gpd") } else { if (RegionBest) { ret <- list(estB=lmomestB,param="gpd") } else { ret <- list(param="gpd") } } class(ret) <- "GldGPDFit" ret }
skip_on_cran() test_that("no errors/warnings with standard use in tbl_summary() and add_p()", { tbl_summary_comp <- tbl_summary(mtcars, by = am) %>% add_p() expect_error(bold_p(tbl_summary_comp), NA) expect_warning(bold_p(tbl_summary_comp), NA) }) test_that("expect error with use in tbl_summary() but NO add_p()", { table1_without_comp <- tbl_summary(mtcars, by = am) expect_error(bold_p(table1_without_comp), NULL) }) test_that("no errors/warnings with q=TRUE and add_q() used in tbl_summary", { table1_comp_with_q <- tbl_summary(mtcars, by = am) %>% add_p() %>% add_q() expect_error(bold_p(table1_comp_with_q, q = TRUE), NA) expect_warning(bold_p(table1_comp_with_q, q = TRUE), NA) }) test_that("expect error with q=TRUE and add_q() NOT USED in tbl_summary", { table1_comp_without_q <- tbl_summary(mtcars, by = am) %>% add_p() expect_error(bold_p(table1_comp_without_q, q = TRUE), NULL) }) test_that("no errors/warnings with standard use in tbl_regression()", { fmt_reg <- lm(mpg ~ hp + am, mtcars) %>% tbl_regression() expect_error(bold_p(fmt_reg), NA) expect_warning(bold_p(fmt_reg), NA) }) test_that("no errors/warnings with standard use in tbl_uvregression()", { fmt_uni_reg <- trial %>% tbl_uvregression( method = lm, y = age ) expect_error(bold_p(fmt_uni_reg, t = 0.3), NA) expect_warning(bold_p(fmt_uni_reg, t = 0.3), NA) }) test_that("no errors/warnings with use in tbl_uvregression() with add_global_p()", { skip_if_not(requireNamespace("car")) fmt_uni_reg_global_p <- trial %>% tbl_uvregression( method = lm, y = age ) %>% add_global_p() expect_error(bold_p(fmt_uni_reg_global_p, t = 0.3), NA) expect_warning(bold_p(fmt_uni_reg_global_p, t = 0.3), NA) })
getSummary.polr <- function(obj, alpha=.05, ...){ smry <- summary(obj) N <- if(length(weights(obj))) sum(weights(obj)) else nobs(obj) coef <- smry$coef if (smry$df.residual) { pvals <- 2*pt(-abs(coef[,3]), smry$df.residual) } else { pvals <- 2*pnorm(-abs(coef[,3])) } lower <- qnorm(p=alpha/2,mean=coef[,1],sd=coef[,2]) upper <- qnorm(p=1-alpha/2,mean=coef[,1],sd=coef[,2]) coef <- cbind(coef,pvals,lower,upper) colnames(coef) <- c("est","se","stat","p","lwr","upr") null.model <- update(obj, .~1) LR <- deviance(null.model) - deviance(obj) df <- null.model$df.residual - smry$df.resid ll <- logLik(obj) dev <- deviance(obj) if(df > 0){ p <- pchisq(LR,df,lower.tail=FALSE) L0.pwr <- exp(-deviance(null.model)/N) Aldrich.Nelson <- LR/(LR+N) McFadden <- 1 - dev/deviance(null.model) Cox.Snell <- 1 - exp(-LR/N) Nagelkerke <- Cox.Snell/(1-L0.pwr) } else { LR <- NA df <- NA p <- NA Aldrich.Nelson <- NA McFadden <- NA Cox.Snell <- NA Nagelkerke <- NA } AIC <- AIC(obj) BIC <- AIC(obj,k=log(N)) sumstat <- c( LR = LR, df = df, p = p, logLik = ll, deviance = dev, Aldrich.Nelson = Aldrich.Nelson, McFadden = McFadden, Cox.Snell = Cox.Snell, Nagelkerke = Nagelkerke, AIC = AIC, BIC = BIC, N = N ) list(coef=coef,sumstat=sumstat,contrasts=obj$contrasts,xlevels=smry$xlevels,call=obj$call) } getSummary.simex <- function(obj, alpha=.05, ...){ smry <- summary(obj) modsmry <- summary(obj$model) N <- if(length(weights(obj$model))) sum(weights(obj$model)) else { if(length(modsmry$df) > 1) sum(modsmry$df[1:2]) else obj$model$nobs } coef <- smry$coef$jackknife lower <- qnorm(p=alpha/2,mean=coef[,1],sd=coef[,2]) upper <- qnorm(p=1-alpha/2,mean=coef[,1],sd=coef[,2]) coef <- cbind(coef,lower,upper) colnames(coef) <- c("est","se","stat","p","lwr","upr") sumstat <- c(N=N) list(coef=coef,sumstat=sumstat,contrasts=obj$contrasts,xlevels=smry$xlevels,call=obj$call) } setSummaryTemplate("simex" = c( "N" = "($N:d)" ))
apply_mistnet <- function(file, pvolfile_out, verbose = FALSE, mount = dirname(file), load = TRUE, mistnet_elevations = c(0.5, 1.5, 2.5, 3.5, 4.5)) { assert_that(file.exists(file)) if (!.pkgenv$mistnet) { stop("MistNet has not been installed, see update_docker() for install instructions") } assert_that(is.numeric(mistnet_elevations)) assert_that(length(mistnet_elevations) == 5) if (!missing(pvolfile_out)) { if (!file.exists(dirname(pvolfile_out))) { stop(paste("output directory", dirname(pvolfile_out), "not found")) } if (file.access(dirname(pvolfile_out), 2) == -1) { stop(paste("No write permission in directory", dirname(pvolfile_out))) } } opt.names <- c("USE_MISTNET", "MISTNET_ELEVS") opt.values <- c( "TRUE", paste("{", paste(as.character(mistnet_elevations), collapse = ", "), paste = "}", sep = "") ) opt <- data.frame( "option" = opt.names, "is" = rep("=", length(opt.values)), "value" = opt.values ) optfile <- paste(normalizePath(mount, winslash = "/"), "/options.conf", sep = "" ) if (file.exists(optfile)) { optfile_save <- paste(optfile, ".", format(Sys.time(), "%Y%m%d%H%M%S"), sep = "") warning(paste("options.conf file found in directory ", mount, ". Renamed to ", basename(optfile_save), " to prevent overwrite...", sep = "" )) file.rename(optfile, optfile_save) } write.table(opt, file = optfile, col.names = FALSE, row.names = FALSE, quote = FALSE ) pvol_tmp <- nexrad_to_odim_tempfile(file, verbose, mount) if (load) output <- read_pvolfile(pvol_tmp) else output <- TRUE if (missing(pvolfile_out)) { file.remove(pvol_tmp) } else { file.rename(pvol_tmp, pvolfile_out) } if (file.exists(optfile)) { file.remove(optfile) } return(output) }
context("Test pmx options") test_that("can get pmx options", { pmxOptions(template_dir = "/home/agstudy") default_options <- pmxOptions() expect_identical(default_options$template_dir, "/home/agstudy") }) test_that("can set option", { pmxOptions(myOption = 10L) expect_identical(getPmxOption("myOption"), 10L) })
cnd_signal <- function(cnd, ...) { check_dots_empty0(...) .__signal_frame__. <- TRUE if (is_null(cnd)) { return(invisible(NULL)) } switch( cnd_type(cnd), error = { if (is_environment(cnd$call)) { frame <- cnd$call cnd$call <- error_call(cnd$call) } else { frame <- caller_env() } if (is_null(cnd$trace)) { info <- abort_context(frame, cnd$parent) with_options( "rlang:::visible_bottom" = info$bottom_frame, { cnd$trace <- trace_back() } ) } signal_abort(cnd) }, warning = warning(cnd), message = message(cnd), interrupt = interrupt(), condition = invisible(withRestarts( rlang_muffle = function() NULL, signalCondition(cnd) )) ) } warn <- function(message = NULL, class = NULL, ..., body = NULL, footer = NULL, use_cli_format = NULL, .frequency = c("always", "regularly", "once"), .frequency_id = NULL, .subclass = deprecated()) { message <- validate_signal_args(message, class, NULL, .subclass, "warn") message_info <- cnd_message_info( message, body, footer, caller_env(), use_cli_format = use_cli_format ) message <- message_info$message extra_fields <- message_info$extra_fields use_cli_format <- message_info$use_cli_format .frequency <- arg_match0(.frequency, c("always", "regularly", "once")) if (!needs_signal(.frequency, .frequency_id, warning_freq_env, "rlib_warning_verbosity")) { return(invisible(NULL)) } cnd <- warning_cnd( class, message = message, !!!extra_fields, use_cli_format = use_cli_format, ... ) cnd$footer <- c(cnd$footer, message_freq(message, .frequency, "warning")) local_long_messages() warning(cnd) } inform <- function(message = NULL, class = NULL, ..., body = NULL, footer = NULL, use_cli_format = NULL, .file = NULL, .frequency = c("always", "regularly", "once"), .frequency_id = NULL, .subclass = deprecated()) { message <- message %||% "" validate_signal_args(message, class, NULL, .subclass, "inform") message_info <- cnd_message_info( message, body, footer, caller_env(), use_cli_format = use_cli_format ) message <- message_info$message extra_fields <- message_info$extra_fields use_cli_format <- message_info$use_cli_format .frequency <- arg_match0(.frequency, c("always", "regularly", "once")) if (!needs_signal(.frequency, .frequency_id, message_freq_env, "rlib_message_verbosity")) { return(invisible(NULL)) } cnd <- message_cnd( class, message = message, !!!extra_fields, use_cli_format = use_cli_format, ... ) cnd$footer <- c(cnd$footer, message_freq(message, .frequency, "message")) withRestarts(muffleMessage = function() NULL, { signalCondition(cnd) msg <- paste0(conditionMessage(cnd), "\n") cat(msg, file = .file %||% default_message_file()) }) invisible() } signal <- function(message, class, ..., .subclass = deprecated()) { validate_signal_args(message, class, NULL, .subclass, "signal") message <- .rlang_cli_format_fallback(message) cnd <- cnd(class, ..., message = message) cnd_signal(cnd) } local_long_messages <- function(..., frame = caller_env()) { if (peek_option("warning.length") == 1000) { local_options(warning.length = 8170, .frame = frame) } } default_message_file <- function() { opt <- peek_option("rlang:::message_file") if (!is_null(opt)) { return(opt) } if (is_interactive() && sink.number("output") == 0 && sink.number("message") == 2) { stdout() } else { stderr() } } deprecate_subclass <- function(subclass, fn, env = caller_env()) { msg <- sprintf( "The %s argument of %s has been renamed to %s.", format_arg(".subclass"), format_fn(fn), format_arg("class") ) if (is_true(peek_option("force_subclass_deprecation"))) { signal_soft_deprecated(msg) } env_bind(env, class = subclass) } interrupt <- function() { .Call(ffi_interrupt) } validate_signal_args <- function(message, class, call, subclass, fn, env = caller_env()) { local_error_call("caller") if (!is_missing(subclass)) { deprecate_subclass(subclass, fn, env) } check_required(class, call = env) if (!is_missing(call)) { if (!is_null(call) && !is_environment(call) && !is_call(call)) { stop_input_type(call, "a call or environment", arg = "call", call = env) } } if (is_null(message)) { if (is_null(class)) { abort("Either `message` or `class` must be supplied.", call = env) } message <- "" } check_character(message, call = env) if (!is_null(class)) { check_character(class, call = env) } message } warning_freq_env <- new.env(parent = emptyenv()) message_freq_env <- new.env(parent = emptyenv()) needs_signal <- function(frequency, id, env, opt) { local_error_call("caller") switch( peek_verbosity(opt), verbose = return(TRUE), quiet = return(FALSE), default = NULL ) if (is_string(frequency, "always")) { return(TRUE) } if (is_true(peek_option("rlang:::message_always"))) { return(TRUE) } if (is_null(id)) { abort(sprintf( "%s must be supplied with %s.", format_arg(".frequency_id"), format_arg(".frequency") )) } if (!is_string(id)) { abort(sprintf( "%s must be a string.", format_arg(".frequency") )) } sentinel <- env[[id]] if (is_null(sentinel)) { env_poke(env, id, Sys.time()) return(TRUE) } if (is_string(frequency, "once")) { return(FALSE) } if (!inherits(sentinel, "POSIXct")) { abort("Expected `POSIXct` value.", .internal = TRUE) } (Sys.time() - sentinel) > (8 * 60 * 60) } peek_verbosity <- function(opt, call = caller_env()) { arg_match0( peek_option(opt) %||% "default", c("default", "verbose", "quiet"), opt, error_call = call ) } message_freq <- function(message, frequency, type) { if (is_string(frequency, "always")) { return(chr()) } if (is_string(frequency, "regularly")) { info <- silver("This %s is displayed once every 8 hours.") } else { info <- silver("This %s is displayed once per session.") } sprintf(info, type) }
LLR.fun <- function(outcomes, mu, mu0, mu1, dfun, ...) { llr.res <- t(apply(outcomes,1, function(y) { llr <- dfun(y, mu=mu1, log=TRUE,...) - dfun(y, mu=mu0, log=TRUE, ...) p <- dfun(y, mu=mu, ...) return(c(llr=llr,p=p)) })) res <- cbind(outcomes,llr.res) colnames(res) <- c(paste("y",1:ncol(outcomes),sep=""),"llr","p") return(res) } outcomeFunStandard <- function(k,n) { args <- list() ; for (j in seq_len(k)) args[[j]] <- 0:n outcomes <- as.matrix(do.call("expand.grid", args)) if (!is.null(n)) { outcomes <- outcomes[apply(outcomes,1,sum) <= n,,drop=FALSE] } return(outcomes) } LRCUSUM.runlength <- function(mu,mu0,mu1,h,dfun, n, g=5,outcomeFun=NULL,...) { if ( ((ncol(mu) != ncol(mu0)) | (ncol(mu0) != ncol(mu1))) | ((nrow(mu) != nrow(mu0)) | (nrow(mu0) != nrow(mu1)))) { stop("Error: dimensions of mu, mu0 and mu1 have to match") } if (missing(h)) { stop("No threshold specified!") } if (is.null(outcomeFun)) { outcomeFun <- outcomeFunStandard } S <- c(-Inf,seq(0,h,length=g)) names <- c(levels(cut(1,S,right=TRUE)),">=h") t <- 1:ncol(mu) km1 <- nrow(mu) P <- array(0, dim=c(length(t),g+1,g+1),dimnames=list(t,names,names)) P[,g+1,g+1] <- 1 for (i in seq_len(length(t))) { cat("Looking at t=",i," out of ",length(t),"\n") outcomes <- outcomeFun(km1,n[i]) llr <- LLR.fun(outcomes,mu=mu[,i],mu0=mu0[,i],mu1=mu1[,i],dfun=dfun,size=n[i],...) F <- stepfun(sort(llr[,"llr"]),c(0,cumsum(llr[order(llr[,"llr"]),"p"]))) for (j in 1:g) { for (k in 1:g) { a <- S[k] ; b <- S[k+1] ; c <- S[j] ; d <- S[j+1] ; m <- (c+d)/2 if (j == 1) { P[i,j,k] <- F(b) - F(a) } else { P[i,j,k] <- (F(b-c) + 4*F(b-m) + F(b-d) - F(a-c) - 4*F(a-m) - F(a-d))/6 } } } P[i,-(g+1),(g+1)] <- pmax(0,1-apply(P[i,-(g+1),-(g+1)],1,sum)) } Ppower <- P[1,,] alarmUntilTime <- numeric(ncol(mu0)) alarmUntilTime[1] <- Ppower[1,ncol(P)] for (time in t[-1]) { Ppower <- Ppower %*% P[time,,] alarmUntilTime[time] <- Ppower[1,ncol(P)] } pRL <- c(alarmUntilTime[1],diff(alarmUntilTime)) mom <- NA if (length(t) == 1) { R <- P[,1:g,1:g] I <- diag(nrow=g) mom <- rowSums(solve(I-R)) } return(list(P=P,pmf=pRL,cdf=alarmUntilTime,arl=mom[1])) }
tidy_regression <- function(data, model, type = "ols", robust = FALSE, ...) { if (is_ols(type)) { call <- "ols_regression" } else if (is_log(type)) { call <- "logistic_regression" } else if (is_qlog(type)) { call <- "quasilogistic_regression" } else if (is_pois(type)) { call <- "poisson_regression" } else if (is_qpois(type)) { call <- "quasipoisson_regression" }else if (is_negbin(type)) { call <- "negbinom_regression" } else { stop("cannot recognized type", call. = FALSE) } args <- list(model, data = data, robust = robust, ...) m <- do.call(call, args) m } NULL ols_regression <- function(data, model, robust = FALSE, ...) { if (robust) { e <- rlang::expr(MASS::rlm(!!model, data, ...)) } else { e <- rlang::expr(lm(!!model, data = data, ...)) } m <- eval(e) attr(m, "tidycall") <- store_tidycall(m, e) m } logistic_regression <- function(data, model, robust = FALSE, ...) { if (robust) { e <- rlang::expr(robust::glmRob(!!model, data = data, family = binomial)) } else { e <- rlang::expr(glm(!!model, data = data, family = binomial)) } m <- eval(e) attr(m, "tidycall") <- store_tidycall(m, e) m } quasilogistic_regression <- function(data, model, robust = FALSE, ...) { if (robust) { e <- rlang::expr(robust::glmRob(!!model, data = data, family = quasibinomial)) } else { e <- rlang::expr(glm(!!model, data = data, family = quasibinomial)) } m <- eval(e) attr(m, "tidycall") <- store_tidycall(m, e) m } poisson_regression <- function(data, model, robust = FALSE, ...) { if (robust) { e <- rlang::expr(robust::glmRob(!!model, data = data, family = poisson)) } else { e <- rlang::expr(glm(!!model, data = data, family = poisson)) } m <- eval(e) attr(m, "tidycall") <- store_tidycall(m, e) m } quasipoisson_regression <- function(data, model, robust = FALSE, ...) { if (robust) { e <- rlang::expr(robust::glmRob(!!model, data = data, family = quasipoisson)) } else { e <- rlang::expr(glm(!!model, data = data, family = quasipoisson)) } m <- eval(e) attr(m, "tidycall") <- store_tidycall(m, e) m } negbinom_regression <- function(data, model, robust = FALSE, ...) { if (robust) { stop(paste0("Robust is not currently available for negative binomial models.\n", " If you know of a package that offers such a model, please file an\n", " issue at https://github.com/mkearney/tidyversity/issues. Otherwise,\n", " you can try the function found at the following link---though the\n", " output is rather limited: https://github.com/williamaeberhard/glmrob.nb"), call. = FALSE) } e <- rlang::expr(MASS::glm.nb(!!model, data = data, ...)) m <- eval(e) attr(m, "tidycall") <- store_tidycall(m, e) m }
mapdeck_style <- function( style = c("dark","light","outdoors","streets","satellite","satellite-streets") ) { style <- match.arg(style) return( switch( style , "dark" = "mapbox://styles/mapbox/dark-v10" , "light" = "mapbox://styles/mapbox/light-v10" , "outdoors" = "mapbox://styles/mapbox/outdoors-v11" , "streets" = "mapbox://styles/mapbox/streets-v11" , "satellite" = "mapbox://styles/mapbox/satellite-v9" , "satellite-streets" = "mapbox://styles/mapbox/satellite-streets-v11" ) ) }
`weibplot` <- function(x, plot.pos = "exp", shape = NULL, scale = NULL, labels = NULL, mono = TRUE, ...){ if (mono) { col1 <- "darkgray" } else { col <- col2rgb("SteelBlue3")/256 col1 <- rgb(col[1], col[2], col[3], 0.3) } xs <- sort(x) n <- length(x) if (!(plot.pos %in% c("exp", "med"))) stop("plot.pas must be either \"exp\" or \"med\"") if (plot.pos == "medrank") F <- ((1:n) - 0.3)/(n + 0.4) else F <- (1:n) / (n + 1) transF <- log(-log(1-F)) par(xlog = TRUE) plot(x = xs, y = transF, pch = 16, col = col1, yaxt = "n", ylab = "prob", log = "x", ...) probs <- c(0.01, 0.05, 0.10, 0.25, 0.50, 0.60, 0.70, 0.80, 0.90) abline(h = log(-log(probs)), lty = "dotted", col = "gray") abline(v = axTicks(side = 1), lty = "dotted", col = "gray") axis(side = 2, at = log(-log(probs)), labels = formatC(1 - probs, format = "f", digits = 2)) if (!is.null(shape)) { if (is.null(scale)) { warning("'scale' is NULL, hence no use of 'shape'") } else { x.g <- seq(from = min(x), to = max(x) , length = 50) nW <- max(c(length(shape), length(scale))) shape <- rep(shape, length.out = nW) scale <- rep(scale, length.out = nW) if (mono) { cols <- c("black", "darkgray") ltys <- c("solid", "dashed", "dotted") } else { ltys <- "solid" cols <- c("orangered", "DarkOliveGreen3", "purple", "pink") } ltys <- rep(ltys, length.out = nW) cols <- rep(cols, length.out = nW) for (i in 1:nW) { col1 <- col2rgb(cols[i]) / 256 cols[i] <- rgb(col1[1], col1[2], col1[3], 0.9) transF.g <- log(-log(1 - pweibull(x.g, shape[i], scale[i]))) lines(x = x.g, y = transF.g, col = cols[i], lty = ltys[i]) } coords <- par()$usr if (is.null(labels)) labels <- paste("shape = ", formatC(shape, format = "f", digits = 2), "scale = ", formatC(scale, format = "f", digits = 2)) else labels <- rep(labels, length.out = nW) legend(x = range(x)[2] * 0.9, y = 0.60 * coords[3] + 0.40 * coords[4], xjust = 1, yjust = 1, lty = ltys, lwd = rep(2, nW), col = cols, horiz = FALSE, legend = labels) } } }
validate.Gamma.arguments <- function(data,surv.times,m,gamma,strata,gamma.factor,DCO.time,Call){ is.valid.call(Call) if(nrow(data)==0){ stop("Empty data frame!") } if(any(c("impute.time","impute.event","internal_gamma_val","internalDCO.time") %in% colnames(data))){ stop("Cannot use a data frame with columns impute.time, impute.event", " internalDCO.time or internal_gamma_val") } if(!.internal.is.finite.number(m) ||!.internal.is.wholenumber(m) || m < 2){ stop("m must be an integer and at least 2") } if(!is.numeric(gamma.factor) || is.na(gamma.factor) || length(gamma.factor)>1){ stop("gamma.factor must be a single number that is multiplied by the values", " of the gamma argument in order to create subject specific jumps in the hazard rate.", " see help(gammaImpute) for examples") } if(length(strata) != nrow(data)){ stop("Invalid strata argument it must be a vector the same length as the number of rows in the dataset") } validateDCO.time(DCO.time=DCO.time,data=data,times=surv.times[,1]) if(!is.null(gamma)){ validateGammaVal(gamma,data) } if(any(surv.times[,1]<= 0)){ stop("Time on study must be positive") } } validateDCO.time <- function(DCO.time,data,times){ if(is.character(DCO.time)){ if(length(DCO.time) != 1 || !DCO.time %in% colnames(data)){ stop("Invalid DCO.time argument") } DCO.time <- data[,DCO.time] } else if(length(DCO.time)==1){ DCO.time <- rep(DCO.time,nrow(data)) } else if(length(DCO.time)!=nrow(data)){ stop("Invalid DCO.time length") } if(any(!is.numeric(DCO.time) | is.infinite(DCO.time))){ stop("DCO times must be numeric and finite") } if(any(DCO.time < times)){ stop("DCO.time must be >= time for all subjects ") } } validateGammaVal <- function(gamma,data){ if(is.character(gamma)){ if(length(gamma)!= 1 || !gamma %in% colnames(data)){ stop("Invalid gamma column name") } gamma <- data[,gamma] } if(length(gamma)!= nrow(data)){ stop("Invalid length of gamma its length must be the number of subjects in the", " the dataset. use the gamma.factor argument if you want to use a single number", " for each subject's jump in hazard. See help(gammaImpute) for futher details") } if(any(!is.na(gamma) & !is.numeric(gamma))){ stop("gamma must be numeric") } }
df_format_stdstyle <- c( "padding-top"="3px", "padding-bottom"="3px", "padding-left"="0.5ex", "padding-right"="0.5ex", "margin-top"="0px", "margin-bottom"="0px", "border-style"="none", "border-width"="0px" ) format_html.data.frame <- function(x, toprule=2,midrule=1,bottomrule=2, split.dec=TRUE, row.names=TRUE, digits=getOption("digits"), format="f", style=df_format_stdstyle, margin="2ex auto", ...){ firstcol <- c("padding-left"="0.3em") lastcol <- c("padding-right"="0.3em") toprule <- c("border-top"=paste0(midrule,"px solid")) bottomrule <- c("border-bottom"=paste0(midrule,"px solid")) midrule_above <- c("border-top"=paste0(midrule,"px solid")) midrule <- c("border-bottom"=paste0(midrule,"px solid")) align.right <- c("text-align"="right") align.left <- c("text-align"="left") align.center <- c("text-align"="center") row_style <- c("border-style"="none") table_style <- c("border-collapse"="collapse" ,"border-style"="none") colsep <- "" rowsep <- "\n" n <- nrow(x) m <- ncol(x) d <- digits is.int <- sapply(x,is.integer) is.num <- sapply(x,is.numeric) & !is.int m.num <- sum(is.num) digits <- integer(m.num) digits[] <- d fdigits <- integer(m) fdigits[is.num] <- digits fo <- format format <- character(m) format[is.num] <- fo colspan <- integer(0) body <- matrix(nrow=nrow(x),ncol=0) for(i in 1:m) { tmp <- x[[i]] dim.x.i <- dim(tmp) ncol.tmp <- if(length(dim.x.i)) ncol(tmp) else 1 if(is.int[i]){ tmp <- formatC(tmp,format="d") col <- html_td(tmp,vectorize=TRUE,style=css(style)) colspan <- c(colspan,ncol.tmp) } else if(is.num[i]){ tmp <- formatC(tmp,digits=fdigits[i],format=format[i]) if(split.dec){ tmp <- spltDec(tmp) col <- html_td_spltDec(tmp,style=css(style)) colspan <- c(colspan,3L*ncol.tmp) } else{ col <- html_td(tmp,vectorize=TRUE,style=css(style)) colspan <- c(colspan,ncol.tmp) } } else { tmp <- as.character(tmp) col <- html_td(tmp,vectorize=TRUE,style=css(style)) col <- setStyle(col,align.left) colspan <- c(colspan,ncol.tmp) } dim(col) <- dim.x.i body <- cbind(body,col) } if(row.names){ tmp <- rownames(x) ldr <- html_td(tmp,vectorize=TRUE,style=css(c(style,firstcol,align.right))) body <- cbind(ldr,body) } body[1,] <- lapply(body[1,],setStyle,toprule) body[n,] <- lapply(body[n,],setStyle,bottomrule) body <- apply(body,1,html_tr) hdr <- colnames(x) if(row.names) { hdr <- c("",hdr) colspan <- c(1L,colspan) } hdr <- html_td(hdr,vectorize=TRUE,style=css(style)) hdr[] <- mapply(setAttribs,hdr,colspan=colspan,SIMPLIFY=FALSE) hdr <- lapply(hdr,setStyle,df_format_stdstyle) hdr <- lapply(hdr,setStyle,align.center) hdr <- lapply(hdr,setStyle,toprule) hdr[[1]] <- setStyle(hdr[[1]],lastcol) hdr[[length(hdr)]] <- setStyle(hdr[[length(hdr)]],lastcol) hdr <- html_tr(hdr) if(length(margin)) table_style <- c(table_style,margin=margin) ans <- html_table(c(list(hdr),body),style=as.css(table_style)) ans <- as.character(ans) return(ans) }
download.database.all <- function(db, path = NULL) { db_chunks <- listNCBIDatabases(db = db) db_chunks <- db_chunks[-which(stringr::str_detect(db_chunks, "[.]json"))] message("Starting download of the files: ", paste0(db_chunks, collapse = ", "), " ...") message("This download process may take a while due to the large size of the individual data chunks ...") if (is.null(path)) { path <- db } dld_paths <- list(length(db_chunks)) for (i in seq_len(length(db_chunks))) { dld_paths[i] <- list(download.database(db = db_chunks[i], path = path)) } corrupt_md5 <- any(unlist(lapply(dld_paths, is.logical))) which_corrupter_md5 <- which(unlist(lapply(dld_paths, is.logical))) if (corrupt_md5) warning("The file(s) ", paste0(db_chunks[which_corrupter_md5], collapse = ", "), " had corrupted md5 check sum(s). You can simply re-run this function to re-download corrupted files.") message("Download process is finished and files are stored in '", path, "'.") if (corrupt_md5) return(unlist(dld_paths[-which_corrupter_md5])) if (!corrupt_md5) return(unlist(dld_paths)) }
generateSpFromBCA <- function(raster.stack.current, raster.stack.future, rescale = TRUE, niche.breadth = "any", means = NULL, sds = NULL, bca = NULL, sample.points = FALSE, nb.points = 10000, plot = TRUE) { if(!(is(raster.stack.current, "RasterStack"))){ stop("raster.stack.current must be a raster stack object") } if(!(is(raster.stack.future, "RasterStack"))){ stop("raster.stack.future must be a raster stack object") } if(!all((names(raster.stack.future) %in% names(raster.stack.current)))){ stop("The variables names in raster.stack.future must be the same as variables names in raster.stack.current") } if((calc(raster.stack.current, sum) == calc(raster.stack.future, sum))@data@min==1){ stop("Please provide two different rasters") } if(sample.points){ if(!is.numeric(nb.points)) {stop("nb.points must be a numeric value corresponding to the number of pixels to sample from raster.stack.current and from raster.stack.future")} env.df.current <- sampleRandom(raster.stack.current, size = nb.points, na.rm = TRUE) env.df.future <- sampleRandom(raster.stack.future , size = nb.points, na.rm = TRUE) } else { if(canProcessInMemory(raster.stack.current, n = 4)){ env.df.current <- getValues(raster.stack.current) env.df.future <- getValues(raster.stack.future) if(any(is.na(env.df.current))) { env.df.current <- env.df.current[-unique(which(is.na(env.df.current), arr.ind = T)[, 1]), ] } if(any(is.na(env.df.future))) { env.df.future <- env.df.future[-unique(which(is.na(env.df.future), arr.ind = T)[, 1]), ] } } else { stop("Your computer does not have enough memory to extract all the values from raster.stack.current. Use the argument sample.points = TRUE, and adjust the number of points to use with nb.points. More details in ?generateSpFromBCA") } } if(!is.null(bca)){ if(!all(class(bca) %in% c("between", "dudi"))) { stop("Please provide an appropriate bca object (output of bca()) to make the bca plot.") } if(any(!(names(bca$tab) %in% names(raster.stack.current)))){ stop("The variables used to make the bca must be the same as variables names in raster.stack.current") } if (is.null(bca$cent) | is.null(bca$norm) ){ stop("Please provide an appropriate bca object (output of generateSpFromBCA) to make the bca plot.") } between.object <- bca rm(bca) sel.vars <- names(raster.stack.current) } else { sel.vars <- names(raster.stack.current) xpoint <- sample(nrow(env.df.future), 1) env.df <- rbind(env.df.current, env.df.future, env.df.future[xpoint, ], deparse.level = 0) condition <- as.factor(c(rep('Current', nrow(env.df.current)), rep('Future' , nrow(env.df.future )), "X")) message(" - Perfoming the between component analysis\n") pca.object <- ade4::dudi.pca(env.df, scannf = F, nf = 2) between.object <- ade4::bca(pca.object, condition, scannf = F, nf = 2) between.object$xpoint <- xpoint between.object$cent <- pca.object$cent between.object$norm <- pca.object$norm if(!ncol(between.object$ls)==2){ stop("A two dimension BCA can not be performed with provided rasters stack") } } message(" - Defining the response of the species along the axis\n") if(!is.null(means)){ if(!is.numeric(means)) {stop("Please provide numeric means for the gaussian function to compute probabilities of presence")} if(!is.vector(means) | length(means) != 2) {stop("Please provide a vector with 2 means for the gaussian function (one for each of the two between axes)")} } else { means <- between.object$ls[sample(1:nrow(between.object$ls), 1), ] means <- c(mean1 = means[1, 1], mean2 = means[1, 2]) } if(!is.null(sds)){ if(!is.numeric(sds)) {stop("Please provide numeric standard deviations for the gaussian function to compute probabilities of presence")} if(!is.vector(sds) | length(sds) != 2) {stop("Please provide a vector with 2 standard deviations for the gaussian function (one for each of the two pca axes)")} if(any(sds < 0)) {stop("The standard deviations must have a positive value!")} message(" - You have provided standard deviations, so argument niche.breadth will be ignored.\n") } else { axis1 <- c(min = max(min(between.object$ls[, 1]), quantile(between.object$ls[, 1], probs = .25) - 5 * (quantile(between.object$ls[, 1], probs = .75) - quantile(between.object$ls[, 1], probs = .25))), max = min(max(between.object$ls[, 1]), quantile(between.object$ls[, 1], probs = .75) + 5 * (quantile(between.object$ls[, 1], probs = .75) - quantile(between.object$ls[, 1], probs = .25)))) axis2 <- c(min = max(min(between.object$ls[, 2]), quantile(between.object$ls[, 2], probs = .25) - 5 * (quantile(between.object$ls[, 2], probs = .75) - quantile(between.object$ls[, 2], probs = .25))), max = min(max(between.object$ls[, 2]), quantile(between.object$ls[, 2], probs = .75) + 5 * (quantile(between.object$ls[, 2], probs = .75) - quantile(between.object$ls[, 2], probs = .25)))) if(niche.breadth == "any") { sds <- c(sd1 = sample(seq((axis1[2] - axis1[1])/100, (axis1[2] - axis1[1])/2, length = 1000), 1), sd2 = sample(seq((axis2[2] - axis2[1])/100, (axis2[2] - axis2[1])/2, length = 1000), 1)) } else if (niche.breadth == "narrow") { sds <- c(sd1 = sample(seq((axis1[2] - axis1[1])/100, (axis1[2] - axis1[1])/10, length = 1000), 1), sd2 = sample(seq((axis2[2] - axis2[1])/100, (axis2[2] - axis2[1])/10, length = 1000), 1)) } else if (niche.breadth == "wide") { sds <- c(sd1 = sample(seq((axis1[2] - axis1[1])/10, (axis1[2] - axis1[1])/2, length = 1000), 1), sd2 = sample(seq((axis2[2] - axis2[1])/10, (axis2[2] - axis2[1])/2, length = 1000), 1)) } else { stop("niche.breadth must be one of these: 'any', 'narrow', 'wide") } } message(" - Calculating current suitability values\n") rasters.env.current <- calc(raster.stack.current[[sel.vars]], fun = function(x, ...) {.pca.coordinates(x, pca = between.object, na.rm = TRUE, axes = c(1, 2))}) suitab.raster.current <- calc(rasters.env.current, fun = function(x, ...){.prob.gaussian(x, means = means, sds = sds)}) message(" - Calculating future suitability values\n") rasters.env.future <- calc(raster.stack.future [[sel.vars]], fun = function(x, ...) {.pca.coordinates(x, pca = between.object, na.rm = TRUE, axes = c(1, 2))}) suitab.raster.future <- calc(rasters.env.future , fun = function(x, ...){.prob.gaussian(x, means = means, sds = sds)}) if(!is.null(bca)){ between.env.current <- .pca.coordinates(env.df.current, pca = between.object, na.rm = TRUE) between.env.future <- .pca.coordinates(env.df.future , pca = between.object, na.rm = TRUE) between.object$ls <- as.data.frame( rbind(between.env.current, between.env.future) ) } if(rescale){ suitab.raster.current <- (suitab.raster.current - suitab.raster.current@data@min) / (suitab.raster.current@data@max - suitab.raster.current@data@min) suitab.raster.future <- (suitab.raster.future - suitab.raster.future@data@min) / (suitab.raster.future@data@max - suitab.raster.future@data@min) } stack.lengths <- c(nrow(env.df.current), nrow(env.df.future)) if(plot){ message(" - Ploting response and suitability\n") op <- par(no.readonly = TRUE) par(mar = c(5.1, 4.1, 4.1, 2.1)) layout(matrix(nrow = 2, ncol = 2, c(1, 1, 2, 3 ))) plotResponse(x = raster.stack.current, approach = "bca", parameters = list(bca = between.object, means = means, sds = sds, stack.lengths = stack.lengths), no.plot.reset = T) image(suitab.raster.current, axes = T, ann = F, asp = 1, las = 1, col = rev(terrain.colors(12))) legend(title = "Pixel\nsuitability", "right", inset = c(-0.14, 0), legend = c(1, 0.8, 0.6, 0.4, 0.2, 0), fill = terrain.colors(6), bty = "n") title("Current environmental suitability of the virtual species") image(suitab.raster.future, axes = T, ann = F, asp = 1, las = 1, col = rev(terrain.colors(12))) legend(title = "Pixel\nsuitability", "right", inset = c(-0.14, 0), legend = c(1, 0.8, 0.6, 0.4, 0.2, 0), fill = terrain.colors(6), bty = "n") title("Future environmental suitability of the virtual species") par(op) } results <- list(approach = "bca", details = list(variables = sel.vars, bca = between.object, rescale = rescale, axes = c(1, 2), means = means, sds = sds, stack.lengths = stack.lengths), suitab.raster.current = suitab.raster.current, suitab.raster.future = suitab.raster.future) class(results) <- append("virtualspecies", class(results)) return(results) }
factor_detector <- function(y_column,x_column_nn,tabledata) { n_x<-length( x_column_nn) error1<-try({tabledata[y_column]},silent=TRUE) if('try-error' %in% class(error1)) { stop("undefined columns selected in data as parameter.") } for (num in 1: n_x) { x_column <- x_column_nn[num] error1<-try({tabledata[x_column]},silent=TRUE) if('try-error' %in% class(error1)) { stop("undefined columns selected in data as parameter.") } } if(is.character(y_column)) { y_colname<-y_column y_column<-which(names(tabledata) == y_colname) } y_colname<-names(tabledata)[y_column] x_column_n <- vector() for(num in 1:n_x) { x_column <- x_column_nn[num] if(is.character(x_column)) { x_colname<-x_column x_column<-which(names(tabledata) == x_colname) } x_column_n <- rbind(x_column_n,c(x_column)) if(x_column==y_column) { stop("Y variable and X variables should be the different data.") } } lgnull<-is.null(tabledata) num_null=sum(lgnull) if(num_null > 0) { stop("data hava some objects with value NULL") } long=length(tabledata[[y_column]]) Na_check <- vector() for(i in 1:long) { if(is.na(tabledata[[y_column]][i])) { Na_check <-rbind(Na_check,c(y_column,as.character(i))) } } for (num in 1: n_x) { x_column <- x_column_n[num] for(i in 1:long) { if(is.na(tabledata[[x_column]][i])) { Na_check <-rbind(Na_check,c(x_column,as.character(i))) } } } for (num in 1: n_x) { x_column <- x_column_n[num] if((class(tabledata[[x_column]])=="factor")|(class(tabledata[[x_column]])=="character") ) { for(i in 1:long){ if(tabledata[[x_column]][i]=="") { Na_check <-rbind(Na_check,c(x_column,as.character(i))) } } } } if(length(Na_check)!=0) { mes="" for(i in 1:length(Na_check[,1])){ mes=paste(mes,"data hava NA in column: ",Na_check[i,1]," ,at row: ",Na_check[i,2],"\n") } stop(mes) } for(i in 1:long) { if(class(tabledata[[y_column]][i])=="character") { stop("the data type of Y variable can not be character ,in column :",y_column) } } lginfi<-is.infinite(tabledata[[y_column]]) num_infi=sum(lginfi) if(num_infi > 0) { stop("Y variable data hava some objects with value Not finite") } for (num in 1: n_x) { x_column <- x_column_n[num] uni_x=unique(tabledata[x_column]) long2=long/2 if(length(uni_x[[1]])> long2) { stop("For column ",x_column,":data should be dispersed.") } if(length(uni_x[[1]]) < 2) { stop("For column ",x_column,":the number of types(or groups) in a x variable should be more than 1.") } } Result_factorDetector_n<-list() for (num in 1: n_x) { x_column <- x_column_n[num] x_colname<-names(tabledata)[x_column] vec <- tabledata[,x_column] vec.sort <- sort(vec) vec.unique <- unique(vec.sort) N_popu <- nrow(tabledata) N_stra <- length(vec.unique) N_var <- var(tabledata[,y_column]) strataVarSum <- 0 lamda_1st_sum <- 0 lamda_2nd_sum <- 0 for(i in vec.unique) { LenInter <- length(which(vec == i)) strataVar <- 0 lamda_1st <- 0 lamda_2nd <- 0 if(LenInter <= 1) { strataVar <- 0 lamda_1st <- (tabledata[which(vec == i),y_column])^2 lamda_2nd <- tabledata[which(vec == i),y_column] }else { strataVar <- (LenInter-1) * var(tabledata[which(vec == i),y_column]) lamda_1st <- (mean(tabledata[which(vec == i),y_column]))^2 lamda_2nd <- sqrt(LenInter) * mean(tabledata[which(vec == i),y_column]) } strataVarSum <- strataVarSum + strataVar; lamda_1st_sum <- lamda_1st_sum + lamda_1st lamda_2nd_sum <- lamda_2nd_sum + lamda_2nd } TotalVar <- (nrow(tabledata)-1)*N_var pd <- 1 - strataVarSum/TotalVar; lamda <- (lamda_1st_sum - lamda_2nd_sum^2 / N_popu) / N_var F_value <- (N_popu - N_stra)* pd / ((N_stra - 1)* (1 - pd)) p_value <- pf(F_value,df1= N_stra - 1, df2= N_popu - N_stra, ncp=lamda, lower.tail = F) Result_factorDetector <- data.frame(pd,p_value) colnames(Result_factorDetector) <- c("q-statistic","p-value") rownames(Result_factorDetector) <- c(x_colname) Result_factorDetector_n[num]<-list(Result_factorDetector) } return(Result_factorDetector_n) }
`SHradfoc` <- function(A , MEC, GU, pscale, col) { C = RPMG::circle() imageSH(MEC$az1, MEC$dip1, MEC$rake1, SCALE=FALSE, UP=MEC$UP, col=col ) lines(C$x, C$y, type='l', col=grey(.6)) }
fpca2s <- function(Y = NULL, ydata = NULL, argvals = NULL, npc = NA, center = TRUE, smooth = TRUE) { stopifnot(!is.null(Y)) if (any(is.na(Y))) stop("No missing values in <Y> allowed.") if (!is.null(ydata)) { stop(paste("<ydata> argument for irregular data is not supported,", "please use fpca.sc instead.")) } X <- Y data_dim <- dim(X) I <- data_dim[1] J <- data_dim[2] if (is.na(npc)) { npc <- getNPC.DonohoGavish(X) } irregular <- FALSE if (!is.null(argvals)) { stopifnot(is.numeric(argvals), length(argvals) == J, all(!is.na(argvals))) if (any(diff(argvals)/mean(diff(argvals)) > 1.05 | diff(argvals)/mean(diff(argvals)) < 0.95)) { warning(paste("non-equidistant <argvals>-grid detected:", "fpca2s will return orthonormal eigenvectors of the function evaluations", "not evaluations of the orthonormal eigenvectors.", "Use fpca.sc() for the latter instead.")) irregular <- TRUE } } else { argvals <- seq(0, 1, length = J) } meanX <- rep(0, J) if (center) { meanX <- apply(X, 2, function(x) mean(x, na.rm = TRUE)) meanX <- smooth.spline(argvals, meanX, all.knots = TRUE)$y X <- t(t(X) - meanX) } if (J > I) { VV <- X %*% t(X) Eigen <- eigen(VV) D <- Eigen$values sel <- (D > 0) V <- Eigen$vectors[, sel == 1] D <- D[sel == 1] D <- sqrt(D) U <- t(X) %*% V %*% diag(1/D) } if (J <= I) { UU <- t(X) %*% X Eigen <- eigen(UU) D <- Eigen$values U <- Eigen$vectors[, D > 0] D <- D[D > 0] D <- sqrt(D) } lambda <- D^2/(I - 1)/J if (!is.numeric(npc)) stop("Invalid <npc>.") if (npc < 1 | npc > min(I, J)) stop("Invalid <npc>.") message("Extracted ", npc, " smooth components.") if (smooth == TRUE) { for (j in 1:npc) { temp = smooth.spline(argvals, U[, j], all.knots = TRUE)$y U[, j] = temp } } if (!irregular) { scale <- sqrt(mean(diff(argvals))) } else { scale <- 1 } eigenvectors = U[, 1:npc, drop = FALSE]/scale scores = unname(t(lm.fit(x = eigenvectors, y = t(X))$coefficients)) eigenvalues = diag(var(scores)) Yhat = t(eigenvectors %*% t(scores) + meanX) ret = list(Yhat = Yhat, Y = Y, scores = scores, mu = meanX, efunctions = eigenvectors, evalues = eigenvalues, npc = npc, argvals = argvals) class(ret) = "fpca" return(ret) }
test_that("mpm_to_ functions work correctly", { xmax <- 20 lx <- mpm_to_lx(mat_u, start = 1, xmax = xmax, lx_crit = 0) expect_length(lx, xmax + 1) expect_true(all(lx >= 0)) expect_true(all(lx <= 1)) expect_true(all(lx == cummin(lx))) lx_zero <- suppressWarnings(mpm_to_lx(mat_u_zero, start = 1, xmax = xmax)) expect_equal(lx_zero[1], 1) expect_true(all(lx_zero[-1] == 0)) lx_a <- mpm_to_lx(mat_u, start = 2) lx_b <- mpm_to_lx(mat_u, start = c(0, 1, 0, 0)) expect_equal(lx_a, lx_b) px <- mpm_to_px(mat_u, start = 1, xmax = xmax, lx_crit = 0) expect_length(px, length(lx)) hx <- mpm_to_hx(mat_u, start = 1, xmax = xmax, lx_crit = 0) expect_length(hx, length(lx)) mx <- mpm_to_mx(mat_u, mat_f, start = 1, xmax = xmax,lx_crit = 0) expect_length(mx, length(lx)) expect_true(all(mx >= 0)) mx_zero <- suppressWarnings(mpm_to_mx(mat_u_zero, mat_f, start = 1, xmax = xmax)) expect_true(all(mx_zero == 0)) lx_named <- mpm_to_lx(mat_u_named, start = "sm", xmax = xmax, lx_crit = 0) px_named <- mpm_to_px(mat_u_named, start = 1, xmax = xmax, lx_crit = 0) hx_named <- mpm_to_hx(mat_u_named, start = 1, xmax = xmax,lx_crit = 0) mx_named <- mpm_to_mx(mat_u_named, mat_f_named, start = 1, xmax = xmax, lx_crit = 0) expect_equal(lx, lx_named) expect_equal(px, px_named) expect_equal(hx, hx_named) expect_equal(mx, mx_named) }) test_that("mpm_to_ functions warn and fail gracefully", { expect_error(mpm_to_lx(mat_u, start = 10)) expect_error(mpm_to_lx(mat_u_na)) expect_error(mpm_to_lx(mat_u, start = "stage name")) expect_error(mpm_to_px(mat_u, start = 10)) expect_error(mpm_to_px(mat_u_na)) expect_error(mpm_to_px(mat_u, start = "stage name")) expect_error(mpm_to_hx(mat_u, start = 10)) expect_error(mpm_to_hx(mat_u_na)) expect_error(mpm_to_hx(mat_u, start = "stage name")) expect_error(mpm_to_mx(mat_u, mat_f, start = 10)) expect_error(mpm_to_mx(mat_u_na, mat_f)) expect_error(mpm_to_mx(mat_u, mat_f_na)) expect_error(mpm_to_mx(mat_u, mat_f, start = "stage name")) })
betamfxest <- function(formula, data, atmean = TRUE, robust = FALSE, clustervar1 = NULL, clustervar2 = NULL, control = betareg.control(), link.phi = NULL, type = "ML"){ if(is.null(formula)){ stop("formula is missing") } if(!is.data.frame(data)){ stop("data arguement must contain data.frame object") } if(is.null(clustervar1) & !is.null(clustervar2)){ stop("use clustervar1 arguement before clustervar2 arguement") } if(!is.null(clustervar1)){ if(is.null(clustervar2)){ if(!(clustervar1 %in% names(data))){ stop("clustervar1 not in data.frame object") } data = data.frame(model.frame(formula, data, na.action=NULL),data[,clustervar1]) names(data)[dim(data)[2]] = clustervar1 data=na.omit(data) } if(!is.null(clustervar2)){ if(!(clustervar1 %in% names(data))){ stop("clustervar1 not in data.frame object") } if(!(clustervar2 %in% names(data))){ stop("clustervar2 not in data.frame object") } data = data.frame(model.frame(formula, data, na.action=NULL), data[,c(clustervar1,clustervar2)]) names(data)[c(dim(data)[2]-1):dim(data)[2]] = c(clustervar1,clustervar2) data=na.omit(data) } } fit = betareg(formula, data=data, x=T, control = control, link = "logit", link.phi = link.phi, type = type) x1 = model.matrix(fit) if (any(alias <- is.na(coef(fit)))) { x1 <- x1[, !alias, drop = FALSE] } xm = as.matrix(colMeans(x1)) be = as.matrix(na.omit(coef(fit)))[1:NROW(xm)] k1 = NROW(xm) xb = t(xm) %*% be fxb = ifelse(atmean==TRUE, plogis(xb)*(1-plogis(xb)), mean(plogis(x1 %*% be)*(1-plogis(x1 %*% be)))) vcv = vcov(fit)[1:NROW(xm),1:NROW(xm)] if(robust){ if(is.null(clustervar1)){ vcv = sandwich(fit, bread. = bread(fit), meat. = meatHCbeta(fit,"HC0"))[1:NROW(xm),1:NROW(xm)] } else { if(is.null(clustervar2)){ vcv = clusterVCV(data=data, fm=fit, cluster1=clustervar1,cluster2=NULL)[1:NROW(xm),1:NROW(xm)] } else { vcv = clusterVCV(data=data, fm=fit, cluster1=clustervar1,cluster2=clustervar2)[1:NROW(xm),1:NROW(xm)] } } } if(robust==FALSE & is.null(clustervar1)==FALSE){ if(is.null(clustervar2)){ vcv = clusterVCV(data=data, fm=fit, cluster1=clustervar1,cluster2=NULL)[1:NROW(xm),1:NROW(xm)] } else { vcv = clusterVCV(data=data, fm=fit, cluster1=clustervar1,cluster2=clustervar2)[1:NROW(xm),1:NROW(xm)] } } mfx = data.frame(mfx=fxb*be, se=NA) row.names(mfx) = colnames(x1) if(atmean){ gr = (as.numeric(fxb))*(diag(k1) + as.numeric(1 - 2*plogis(xb))*(be %*% t(xm))) mfx$se = sqrt(diag(gr %*% vcv %*% t(gr))) } else { gr = apply(x1, 1, function(x){ as.numeric(as.numeric(plogis(x %*% be)*(1-plogis(x %*% be)))* (diag(k1) - (1 - 2*as.numeric(plogis(x %*% be)))*(be %*% t(x)))) }) gr = matrix(apply(gr,1,mean),nrow=k1) mfx$se = sqrt(diag(gr %*% vcv %*% t(gr))) } temp1 = apply(x1,2,function(x)length(table(x))==1) const = names(temp1[temp1==TRUE]) mfx = mfx[row.names(mfx)!=const,] temp1 = apply(x1,2,function(x)length(table(x))==2) disch = names(temp1[temp1==TRUE]) if(length(disch)!=0){ for(i in 1:length(disch)){ if(atmean){ disx0 = disx1 = xm disx1[disch[i],] = max(x1[,disch[i]]) disx0[disch[i],] = min(x1[,disch[i]]) mfx[disch[i],1] = plogis(t(be) %*% disx1) - plogis(t(be) %*% disx0) gr = dlogis(t(be) %*% disx1) %*% t(disx1) - dlogis(t(be) %*% disx0) %*% t(disx0) mfx[disch[i],2] = sqrt(gr %*% vcv %*% t(gr)) } else { disx0 = disx1 = x1 disx1[,disch[i]] = max(x1[,disch[i]]) disx0[,disch[i]] = min(x1[,disch[i]]) mfx[disch[i],1] = mean(plogis(disx1 %*% be) - plogis(disx0 %*% be)) gr = as.numeric(dlogis(disx1 %*% be)) * disx1 - as.numeric(dlogis(disx0 %*% be)) * disx0 avegr = as.matrix(colMeans(gr)) mfx[disch[i],2] = sqrt(t(avegr) %*% vcv %*% avegr) } } } mfx$discretechgvar = ifelse(rownames(mfx) %in% disch, 1, 0) output = list(fit=fit, mfx=mfx) return(output) }
spip_exists <- function() { file.exists(spip_binary_path()) }
library(RXMCDA) tree <- xmlTreeParse(system.file("extdata","testFile.xml",package="RXMCDA"), useInternalNodes=TRUE) altIDs <- getAlternativesIDs(tree) perfTable <- getPerformanceTables(tree) comps <- getAlternativesComparisons(tree, perfTable[[1]]) stopifnot(all.equal(dim(comps[[1]]), c(13,11)))
library(OutliersO3) library(ggplot2) data(Election2005) data <- Election2005[, c(6, 10, 17, 28)] O3d <- O3prep(data, method=c("HDo", "PCS", "BAC", "adjOut", "DDC", "MCD"), tolHDo=0.05, tolPCS=0.5, tolBAC=0.95, toladj=0.25, tolDDC=0.01, tolMCD=0.5) O3d1 <- O3plotM(O3d) O3d1$nOut O3p <- O3prep(data, method=c("HDo", "PCS", "BAC", "adjOut", "DDC", "MCD")) O3p1 <- O3plotM(O3p) O3p1$nOut O3p1$gO3 data(etymology, package="languageR") data <- etymology[, c(2, 4, 5, 10, 13, 14)] O3q <- O3prep(data, method=c("HDo", "PCS", "BAC", "adjOut", "DDC", "MCD"), tolHDo=0.01, tolPCS=0.005, tolBAC=0.005, toladj=0.1, tolDDC=0.01, tolMCD=0.000001) O3q1 <- O3plotM(O3q) O3q1$nOut library(dplyr) outHD <- O3q1$outsTable %>% filter(Method=="HDo") %>% group_by(Combination) %>% summarise(num=n()) %>% filter(num>5) knitr::kable(outHD, row.names=FALSE) O3r <- O3prep(data, method=c("HDo", "PCS", "BAC", "adjOut", "DDC", "MCD"), k1=2, tolHDo=0.01, tolPCS=0.0025, tolBAC=0.005, toladj=0.1, tolDDC=0.005, tolMCD=0.000001) O3r1 <- O3plotM(O3r, caseNames=etymology$Verb) O3r1$nOut library(gridExtra) grid.arrange(O3r1$gO3 + theme(plot.margin = unit(c(0, 1, 0, 0), "cm")), O3r1$gpcp, ncol=1, heights=c(2,1))
gemMoney_3_2 <- function(dstl, supply.labor = 100, supply.money = 300, names.commodity = c("product", "labor", "money"), names.agent = c("firm", "household"), ...) { ge <- sdm2( A = dstl, B = matrix(c( 1, 0, 0, 0, 0, 0 ), 3, 2, TRUE, dimnames = list(names.commodity, names.agent) ), S0Exg = { tmp <- matrix(NA, 3, 2, dimnames = list(names.commodity, names.agent)) tmp[2, 2] <- supply.labor tmp[3, 2] <- supply.money tmp }, names.commodity = names.commodity, names.agent = names.agent, ... ) return(ge) }
test_aregImpute <- function(X_hat, list) { index <- lapply(list, is.na) aregImpute_imp <- function(X) { Xdf <- as.data.frame(X) Xcolnames <- colnames(Xdf) Xformula <- stats::as.formula(paste("~", paste(Xcolnames, collapse = "+"))) hmisc_algo <- Hmisc::aregImpute(formula = Xformula, data = Xdf, n.impute = 1, burnin = 5, nk = 3, type = "pmm", pmmtype = 2) completeData <- as.data.frame(Hmisc::impute.transcan(hmisc_algo, imputation = 1, data = Xdf, list.out = TRUE, pr = FALSE, check = FALSE)) imp_matrix <- as.matrix(completeData) list(Imputed = imp_matrix) } print("Hmisc aregImpute imputation - in progress") start_time <- Sys.time() log_output <- utils::capture.output(results <- lapply(list, aregImpute_imp)) end_time <- Sys.time() time <- as.numeric(end_time - start_time, units = "mins") orig_MCAR <- X_hat[index[[1]]] orig_MAR <- X_hat[index[[2]]] orig_MNAR <- X_hat[index[[3]]] if (length(index) == 4) orig_MAP <- X_hat[index[[4]]] imp_MCAR <- results$MCAR_matrix$Imputed[index[[1]]] imp_MAR <- results$MAR_matrix$Imputed[index[[2]]] imp_MNAR <- results$MNAR_matrix$Imputed[index[[3]]] if (length(index) == 4) imp_MAP <- results$MAP_matrix$Imputed[index[[4]]] rmse_MCAR <- sqrt(mean((orig_MCAR - imp_MCAR)^2)) rmse_MAR <- sqrt(mean((orig_MAR - imp_MAR)^2)) rmse_MNAR <- sqrt(mean((orig_MNAR - imp_MNAR)^2)) if (length(index) == 4) rmse_MAP <- sqrt(mean((orig_MAP - imp_MAP)^2)) mae_MCAR <- mean(abs(orig_MCAR - imp_MCAR)) mae_MAR <- mean(abs(orig_MAR - imp_MAR)) mae_MNAR <- mean(abs(orig_MNAR - imp_MNAR)) if (length(index) == 4) mae_MAP <- mean(abs(orig_MAP - imp_MAP)) ks_MCAR <- stats::ks.test(orig_MCAR, imp_MCAR, exact=TRUE)$statistic ks_MAR <- stats::ks.test(orig_MAR, imp_MAR, exact=TRUE)$statistic ks_MNAR <- stats::ks.test(orig_MNAR, imp_MNAR, exact=TRUE)$statistic if (length(index) == 4) ks_MAP <- stats::ks.test(orig_MAP, imp_MAP, exact=TRUE)$statistic if (length(index) == 4) list(Comp_time = time, MCAR_RMSE = rmse_MCAR, MAR_RMSE = rmse_MAR, MNAR_RMSE = rmse_MNAR, MAP_RMSE = rmse_MAP, MCAR_MAE = mae_MCAR, MAR_MAE = mae_MAR, MNAR_MAE = mae_MNAR, MAP_MAE = mae_MAP, MCAR_KS = ks_MCAR, MAR_KS = ks_MAR, MNAR_KS = ks_MNAR, MAP_KS = ks_MAP) else list(Comp_time = time, MCAR_RMSE = rmse_MCAR, MAR_RMSE = rmse_MAR, MNAR_RMSE = rmse_MNAR, MCAR_MAE = mae_MCAR, MAR_MAE = mae_MAR, MNAR_MAE = mae_MNAR, MCAR_KS = ks_MCAR, MAR_KS = ks_MAR, MNAR_KS = ks_MNAR) }
if(FALSE) { tools:::.install_packages(c("--preclean", "--no-multiarch", "tree")) status <- tryCatch( tools:::.install_packages(c("--no-clean-on-error", "--no-multiarch", "tree"), no.q = TRUE) , error = function(e) as.numeric(sub(".* exit status *", "", conditionMessage(e)))) debugonce(tools:::.install_packages) tools:::.install_packages(c("-c", "--debug", "--no-clean-on-error", "--no-multiarch", "tree")) debug(do_install) } .install_packages <- function(args = NULL, no.q = interactive(), warnOption = 1) { 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 R_runR_deps_only <- function(cmd, deps_only_env, multiarch = FALSE, ...) { deps_only <- config_val_to_logical(Sys.getenv("_R_CHECK_INSTALL_DEPENDS_", "FALSE")) env <- if (deps_only) deps_only_env else "" env <- paste(env, "R_TESTS=") opts <- "--no-save --no-restore --no-echo" if (deps_only) { opts <- paste(opts, "--no-init-file --no-site-file") if (!multiarch) opts <- paste(opts, "--no-environ") } R_runR(cmd = cmd, Ropts = opts, env = env, ...) } do_exit <- if(no.q) function(status) stop(".install_packages() exit status ", status) else function(status) q("no", status = status, runLast = FALSE) do_exit_on_error <- function(status = 1L) { 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) if(system(paste("mv -f", shQuote(lp), shQuote(pkgdir)))) message(" restoration failed\n") } } } do_cleanup() do_exit(status=status) } 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) } quote_path <- function(path, quote = "'") { path <- gsub("\\", "\\\\", path, fixed = TRUE) path <- gsub(quote, paste0("\\", quote), path, fixed = TRUE) paste0(quote, path, quote) } quote_replacement <- function(r) paste0(gsub("\\", "\\\\", r, fixed=TRUE)) on.exit(do_exit_on_error()) WINDOWS <- .Platform$OS.type == "windows" cross <- Sys.getenv("R_CROSS_BUILD") have_cross <- nzchar(cross) if(have_cross && !cross %in% c("i386", "x64")) stop("invalid value ", sQuote(cross), " for R_CROSS_BUILD") if (have_cross) { WINDOWS <- TRUE Sys.setenv(R_OSTYPE = "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) cross <- Sys.getenv("R_CROSS_BUILD") if(have_cross && !cross %in% c("i386", "x64")) stop("invalid value ", sQuote(cross), " for R_CROSS_BUILD") test_archs <- rarch if (have_cross) { WINDOWS <- TRUE r_arch <- paste0("/", cross) test_archs <- c() } 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)) } if(getOption("warn") < warnOption) { op <- options(warn = warnOption) on.exit(options(op), add = TRUE) } 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", " --with-keep.parse.data", " --without-keep.parse.data", " use (or not) 'keep.parse.data' for R code", " --byte-compile byte-compile R code", " --no-byte-compile do not byte-compile R code", " --staged-install install to a temporary directory and then move", " to the target directory (default)", " --no-staged-install install directly to the target directory", " --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)", " --use-vanilla do not read any Renviron or Rprofile files", " --use-LTO use Link-Time Optimization", " --no-use-LTO do not use Link-Time Optimization", "\nfor Unix", " --configure-args=ARGS", " set arguments for the configure scripts (if any)", " --configure-vars=VARS", " set variables for the configure scripts (if any)", " --strip strip shared object(s)", " --strip-lib strip static/dynamic libraries under lib/", " --dsym (macOS 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 <https://bugs.R-project.org>.", sep = "\n") } is_subdir <- function(dir, parent) { rl <- Sys.readlink(dir) (!is.na(rl) && nzchar(rl)) || normalizePath(parent) == normalizePath(file.path(dir, "..")) } fullpath <- function(dir) { owd <- setwd(dir) full <- getwd() setwd(owd) full } parse_description_field <- function(desc, field, default) str_parse_logic(desc[field], default = default, otherwise = quote( 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) errmsg(msg, " for package ", sQuote(pkg)) do_install <- function(pkg) { if (WINDOWS && endsWith(pkg, ".zip")) { pkg_name <- basename(pkg) pkg_name <- sub("\\.zip$", "", pkg_name) pkg_name <- sub("_[0-9.-]+$", "", pkg_name) reuse_lockdir <- lock && !pkglock if (pkglock) lock <- "pkglock" utils:::unpackPkgZip(pkg, pkg_name, lib, libs_only, lock, reuse_lockdir = reuse_lockdir) 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)) { unlink(instdir, recursive = FALSE) 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, ",")) for (i in cxx_standards) { pattern <- paste0("^[[:space:]]*C[+][+]",i,"[[:space:]]*$") if(any(grepl(pattern, sys_requires, ignore.case=TRUE))) { Sys.setenv("R_PKG_CXX_STD"=i) on.exit(Sys.unsetenv("R_PKG_CXX_STD")) break } } } } 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(C_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 -f", 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 <- paste0("src-", arch) .Call(C_dirchmod, ss, group.writable) unlink(ss, recursive = TRUE) } owd <- setwd("src") if (WINDOWS) { if (file.exists("Makefile.ucrt")) system(paste(MAKE, "-f Makefile.ucrt clean")) else 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.ucrt")) system("sh ./cleanup.ucrt") else 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) revert_install_time_patches() } 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((do_strip || config_val_to_logical(Sys.getenv("_R_SHLIB_STRIP_", "false"))) && nzchar(strip_cmd <- Sys.getenv("R_STRIP_SHARED_LIB"))) { system(paste(c(strip_cmd, shQuote(file.path(dest, files))), collapse = " ")) } if (!WINDOWS) Sys.chmod(file.path(dest, files), dmode) if (dsym && startsWith(R.version$os, "darwin")) { starsmsg(stars, gettextf("generating debug symbols (%s)", "dSYM")) dylib <- Sys.glob(paste0(dest, "/*", SHLIB_EXT)) for (d in dylib) system(paste0("dsymutil ", d)) } 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, use_LTO = NA) { args <- c(shargs, if(isTRUE(use_LTO)) "--use-LTO", if(isFALSE(use_LTO)) "--no-use-LTO", "-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) } patch_rpaths <- function() { slibs <- list.files(instdir, recursive = TRUE, all.files = TRUE, full.names = TRUE) slibs <- grep("(\\.sl$)|(\\.so$)|(\\.dylib$)|(\\.dll$)", slibs, value = TRUE) if (!length(slibs)) return() have_file <- nzchar(Sys.which("file")) if (have_file) { are_shared <- vapply(slibs, function(l) any(grepl("(shared|dynamically linked)", system(paste("file", shQuote(l)), intern = TRUE))), NA) slibs <- slibs[are_shared] if (!length(slibs)) return() } starsmsg(stars, "checking absolute paths in shared objects and dynamic libraries") uname <- system("uname -a", intern = TRUE) os <- sub(" .*", "", uname) have_chrpath <- nzchar(Sys.which("chrpath")) have_patchelf <- nzchar(Sys.which("patchelf")) have_readelf <- nzchar(Sys.which("readelf")) have_macos_clt <- identical(os, "Darwin") && nzchar(Sys.which("otool")) && nzchar(Sys.which("install_name_tool")) have_solaris_elfedit <- identical(os, "SunOS") && nzchar(Sys.which("elfedit")) hardcoded_paths <- FALSE failed_fix <- FALSE if (have_solaris_elfedit) { for (l in slibs) { out <- suppressWarnings( system(paste("elfedit -re dyn:value", shQuote(l)), intern = TRUE)) out <- grep("^[ \t]*\\[[0-9]+\\]", out, value = TRUE) re <- "^[ \t]*\\[([0-9]+)\\][ \t]+([^ \t]+)[ \t]+([^ \t]+)[ \t]*(.*)" paths <- gsub(re, "\\4", out) idxs <- gsub(re, "\\1", out) old_paths <- paths paths <- gsub(instdir, quote_replacement(final_instdir), paths, fixed = TRUE) changed <- paths != old_paths paths <- paths[changed] old_paths <- old_paths[changed] idxs <- idxs[changed] for (i in seq_along(paths)) { hardcoded_paths <- TRUE qp <- gsub('([" \\])', "\\\\\\1", paths[i]) qp <- gsub("'", "\\\\'", qp) cmd <- paste0("elfedit -e \"dyn:value -dynndx -s ", idxs[i], " ", qp, "\" ", shQuote(l)) message(cmd) ret <- suppressWarnings(system(cmd, intern = FALSE)) if (ret == 0) message("NOTE: fixed path ", sQuote(old_paths[i])) } out <- suppressWarnings( system(paste("elfedit -re dyn:value", shQuote(l)), intern = TRUE)) out <- grep("^[ \t]*\\[", out, value = TRUE) paths <- gsub(re, "\\4", out) if (any(grepl(instdir, paths, fixed = TRUE))) failed_fix <- TRUE } } else if (have_macos_clt) { for (l in slibs) { out <- suppressWarnings( system(paste("otool -D", shQuote(l)), intern = TRUE)) out <- out[-1L] oldid <- out if (length(oldid) == 1 && grepl(instdir, oldid, fixed = TRUE)) { hardcoded_paths <- TRUE newid <- gsub(instdir, quote_replacement(final_instdir), oldid, fixed = TRUE) cmd <- paste("install_name_tool -id", shQuote(newid), shQuote(l)) message(cmd) ret <- suppressWarnings(system(cmd, intern = FALSE)) if (ret == 0) message("NOTE: fixed library identification name ", sQuote(oldid)) } out <- suppressWarnings( system(paste("otool -L", shQuote(l)), intern = TRUE)) paths <- grep("\\(compatibility", out, value = TRUE) paths <- gsub("^[ \t]*(.*) \\(compatibility.*", "\\1", paths) old_paths <- paths paths <- gsub(instdir, quote_replacement(final_instdir), paths, fixed = TRUE) changed <- paths != old_paths paths <- paths[changed] old_paths <- old_paths[changed] for(i in seq_along(paths)) { hardcoded_paths <- TRUE cmd <- paste("install_name_tool -change", shQuote(old_paths[i]), shQuote(paths[i]), shQuote(l)) message(cmd) ret <- suppressWarnings(system(cmd, intern = FALSE)) if (ret == 0) message("NOTE: fixed library path ", sQuote(old_paths[i])) } out <- suppressWarnings( system(paste("otool -L", shQuote(l)), intern = TRUE)) out <- grep("\\(compatibility", out, value = TRUE) if (any(grepl(instdir, out, fixed = TRUE))) failed_fix <- TRUE out <- suppressWarnings( system(paste("otool -l", shQuote(l)), intern = TRUE)) out <- grep("(^[ \t]*cmd )|(^[ \t]*path )", out, value = TRUE) rpidx <- grep("cmd LC_RPATH$", out) if (length(rpidx)) { paths <- gsub("^[ \t]*path ", "", out[rpidx+1]) paths <- gsub("(.*) \\(offset .*", "\\1", paths) old_paths <- paths paths <- gsub(instdir, quote_replacement(final_instdir), paths, fixed = TRUE) changed <- paths != old_paths paths <- paths[changed] old_paths <- old_paths[changed] for(i in seq_along(paths)) { hardcoded_paths <- TRUE cmd <- paste("install_name_tool -rpath", shQuote(old_paths[i]), shQuote(paths[i]), shQuote(l)) message(cmd) ret <- suppressWarnings(system(cmd)) if (ret == 0) message("NOTE: fixed rpath ", sQuote(old_paths[i])) } } out <- suppressWarnings( system(paste("otool -l", shQuote(l)), intern = TRUE)) out <- out[-1L] if (any(grepl(instdir, out, fixed = TRUE))) failed_fix <- TRUE } } else if (have_patchelf) { for(l in slibs) { rpath <- suppressWarnings( system(paste("patchelf --print-rpath", shQuote(l)), intern = TRUE)) old_rpath <- rpath rpath <- gsub(instdir, quote_replacement(final_instdir), rpath, fixed = TRUE) if (length(rpath) && nzchar(rpath) && old_rpath != rpath) { hardcoded_paths <- TRUE cmd <- paste("patchelf", "--set-rpath", shQuote(rpath), shQuote(l)) message(cmd) ret <- suppressWarnings(system(cmd)) if (ret == 0) message("NOTE: fixed rpath ", sQuote(old_rpath)) rpath <- suppressWarnings( system(paste("patchelf --print-rpath", shQuote(l)), intern = TRUE)) if (any(grepl(instdir, rpath, fixed = TRUE))) failed_fix <- TRUE } if (have_readelf) { out <- suppressWarnings( system(paste("readelf -d", shQuote(l)), intern = TRUE)) re0 <- "0x.*\\(NEEDED\\).*Shared library:" out <- grep(re0, out, value = TRUE) re <- "^[ \t]*0x[0-9]+[ \t]+\\(NEEDED\\)[ \t]+Shared library:[ \t]*\\[(.*)\\]" paths <- gsub(re, "\\1", out) old_paths <- paths paths <- gsub(instdir, quote_replacement(final_instdir), paths, fixed = TRUE) changed <- paths != old_paths paths <- paths[changed] old_paths <- old_paths[changed] for(i in seq_along(paths)) { cmd <- paste("patchelf --replace-needed", shQuote(old_paths[i]), shQuote(paths[i]), shQuote(l)) message(cmd) ret <- suppressWarnings(system(cmd)) if (ret == 0) message("NOTE: fixed library path ", sQuote(old_paths[i])) } out <- suppressWarnings( system(paste("readelf -d", shQuote(l)), intern = TRUE)) out <- grep(re0, out, value = TRUE) if (any(grepl(instdir, out, fixed = TRUE))) failed_fix <- TRUE } } } else if (have_chrpath) { for(l in slibs) { out <- suppressWarnings( system(paste("chrpath", shQuote(l)), intern = TRUE)) rpath <- grep(".*PATH=", out, value=TRUE) rpath <- gsub(".*PATH=", "", rpath) old_rpath <- rpath rpath <- gsub(instdir, quote_replacement(final_instdir), rpath, fixed = TRUE) if (length(rpath) && nzchar(rpath) && old_rpath != rpath) { hardcoded_paths <- TRUE cmd <- paste("chrpath", "-r", shQuote(rpath), shQuote(l)) message(cmd) ret <- suppressWarnings(system(cmd)) if (ret == 0) message("NOTE: fixed rpath ", sQuote(old_rpath)) out <- suppressWarnings( system(paste("chrpath", shQuote(l)), intern = TRUE)) rpath <- grep(".*PATH=", out, value = TRUE) rpath <- gsub(".*PATH=", "", rpath) if (any(grepl(instdir, rpath, fixed = TRUE))) failed_fix <- TRUE } } } if (hardcoded_paths) message("WARNING: shared objects/dynamic libraries with hard-coded temporary installation paths") if (failed_fix) errmsg("some hard-coded temporary paths could not be fixed") if (have_readelf) { for(l in slibs) { out <- suppressWarnings( system(paste("readelf -d", shQuote(l)), intern = TRUE)) out <- grep("^[ \t]*0x", out, value = TRUE) if (any(grepl(instdir, out, fixed = TRUE))) { ll <- sub(file.path(instdir, ""), "", l, fixed = TRUE) errmsg("absolute paths in ", sQuote(ll), " include the temporary installation directory:", " please report to the package maintainer", " and use ", sQuote("--no-staged-install")) } } } } 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")) R_install_force_depends_imports <- config_val_to_logical(Sys.getenv( "_R_INSTALL_LIBS_ONLY_FORCE_DEPENDS_IMPORTS_", "TRUE")) if (libs_only && isFALSE(R_install_force_depends_imports)) pkgs <- unique(c(names(names(pkgInfo$LinkingTo)))) else 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 -f ", 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) if (more_than_libs && dir.exists(instdir)) errmsg("cannot remove earlier installation, is it in use?") dir.create(instdir, recursive = TRUE, showWarnings = FALSE) } pkg_staged_install <- SI <- parse_description_field(desc, "StagedInstall", default = NA) if (is.na(pkg_staged_install)) pkg_staged_install <- staged_install if (have_cross) pkg_staged_install <- FALSE if (pkg_staged_install && libs_only) { pkg_staged_install <- FALSE message("not using staged install with --libs-only") } if (pkg_staged_install && !lock) { pkg_staged_install <- FALSE message("staged installation is only possible with locking") } if (pkg_staged_install) { starsmsg(stars, "using staged installation") final_instdir <- instdir final_lib <- lib final_rpackagedir <- Sys.getenv("R_PACKAGE_DIR") final_rlibs <- Sys.getenv("R_LIBS") final_libpaths <- .libPaths() instdir <- file.path(lockdir, "00new", pkg_name) Sys.setenv(R_PACKAGE_DIR = instdir) dir.create(instdir, recursive = TRUE, showWarnings = FALSE) lib <- file.path(lockdir, "00new") rlibs <- if (nzchar(final_rlibs)) paste(lib, final_rlibs, sep = .Platform$path.sep) else lib Sys.setenv(R_LIBS = rlibs) .libPaths(c(lib, final_libpaths)) } else { if(isFALSE(SI)) starsmsg(stars, "using non-staged installation via StagedInstall field") else if (Sys.getenv("_R_INSTALL_SUPPRESS_NO_STAGED_MESSAGE_") != "yes") starsmsg(stars, "using non-staged installation") } if (preclean) run_clean() if (WINDOWS) { it_patches_base <- Sys.getenv("_R_INSTALL_TIME_PATCHES_", "https://www.r-project.org/nosvn/winutf8/ucrt3/") if (!it_patches_base %in% c("no", "disabled", "false", "FALSE")) { patches_idx <- tryCatch({ idxfile <- file(paste0(it_patches_base, "/", "patches_idx.rds")) patches_idx <- readRDS(idxfile) close(idxfile) patches_idx }, error = function(e) NULL) if (is.null(patches_idx)) message("WARNING: installation-time patches will not be applied, could not get the patches index") else { patches_msg <- FALSE for(p in patches_idx[[pkg_name]]) { if (!patches_msg) { patches_msg <- TRUE starsmsg(stars, "applying installation-time patches") } purl <- paste0(it_patches_base, "/", p) have_patch <- nzchar(Sys.which("patch")) if (!have_patch) stop("patch utility is needed for installation-time patching") dir.create("install_time_patches", recursive=TRUE) fname <- paste0("install_time_patches/", basename(p)) if (grepl("^http", purl)) utils::download.file(purl, destfile = fname, mode = "wb") else file.copy(purl, fname) if (system2("patch", args = c("--dry-run", "-p2", "--binary", "--force"), stdin = fname, stdout = NULL, stderr = NULL) != 0) { if (system2("patch", args = c("--dry-run", "-R", "-p2", "--binary", "--force"), stdin = fname) == 0) message("NOTE: Skipping installation-time patch ", purl, " which seems to be already applied.\n") else message("WARNING: failed to apply patch ", purl, "\n") } else { if (system2("patch", args = c("-p2", "--binary", "--force"), stdin = fname) != 0) message("WARNING: failed to apply patch ", p, "\n") else message("Applied installation-time patch ", purl, " and saved it as ", fname, " in package installation\n") } } } } } if (use_configure) { if (WINDOWS) { if (file.exists("configure.ucrt")) { res <- system("sh ./configure.ucrt") if (res) pkgerrmsg("configuration failed", pkg_name) } else 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.ucrt"))) 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(f <- "Makefile.ucrt") || file.exists(f <- "Makefile.win")) { makefiles <- c(f, makefiles) message(paste0(" running 'src/", f, "' ..."), domain = NA) res <- system(paste("make --no-print-directory", paste("-f", shQuote(makefiles), collapse = " "))) if (res == 0L) shlib_install(instdir, rarch) else has_error <- TRUE } else { srcs <- dir(pattern = "\\.([cfmM]|cc|cpp|f90|f95|mm)$", all.files = TRUE) archs <- if(have_cross) cross else 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 has_configure_ucrt <- file.exists("../configure.ucrt") if(!one_only && (has_configure_ucrt || file.exists("../configure.win"))) { if(pkg_name %notin% 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( if(has_configure_ucrt) "../configure.ucrt" else "../configure.win", warn = FALSE), "bytes")) > 0 if(one_only && !force_biarch) { if(parse_description_field(desc, "Biarch", FALSE)) force_biarch <- TRUE else if (has_configure_ucrt) warning("this package has a non-empty 'configure.ucrt' file,\nso building only the main architecture\n", call. = FALSE, domain = NA) 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, use_LTO) else { setwd(owd) test_archs <- archs for(arch in archs) { message("", domain = NA) starsmsg("***", "arch - ", arch) ss <- paste0("src-", arch) dir.create(ss, showWarnings = FALSE) file.copy(Sys.glob("src/*"), ss, recursive = TRUE) .Call(C_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, use_LTO) 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 == 0L) 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)) { use_LTO <- if (!is.na(use_LTO)) use_LTO else parse_description_field(desc, "UseLTO", default = NA) 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, use_LTO) } else { setwd(owd) test_archs <- archs for(arch in archs) { if (arch == "R") { has_error <- run_shlib(pkg_name, srcs, instdir, "", use_LTO) } else { starsmsg("***", "arch - ", arch) ss <- paste0("src-", arch) 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, use_LTO) 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 <- filtergrep("^Archs:", olddesc, useBytes = TRUE) newdesc <- c(olddesc, paste("Archs:", paste(dirs, collapse = ", ")) ) writeLines(newdesc, descfile, useBytes = TRUE) saveRDS(.split_description(.read_description(descfile)), file.path(instdir, "Meta", "package.rds")) } } 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 (have_cross) Sys.unsetenv("R_ARCH") if (WINDOWS && dir.exists("install_time_patches")) file.copy("install_time_patches", instdir, recursive = TRUE) 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 (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 <- filtergrep(.vc_dir_names_re, i_dirs) 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 <- filtergrep(e, i_dirs, perl = TRUE, ignore.case = TRUE) lapply(gsub("^inst", quote_replacement(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 <- filtergrep(.vc_dir_names_re, i_files) for(e in ignore) i_files <- filtergrep(e, i_files, perl = TRUE, ignore.case = TRUE) i_files <- i_files %w/o% c("inst/doc/Rplots.pdf", "inst/doc/Rplots.ps") i_files <- filtergrep("inst/doc/.*[.](log|aux|bbl|blg|dvi)$", i_files, perl = TRUE, ignore.case = TRUE) if (!dir.exists("vignettes") && pkgname %notin% c("RCurl")) i_files <- filtergrep("inst/doc/.*[.](png|jpg|jpeg|gif|ps|eps)$", i_files, perl = TRUE, ignore.case = TRUE) i_files <- i_files %w/o% "Makefile" i2_files <- gsub("^inst", quote_replacement(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, ]) } } rait <- Sys.getenv("R_ALWAYS_INSTALL_TESTS", "FALSE") install_tests <- install_tests || config_val_to_logical(rait) 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 = TRUE) rcps <- Sys.getenv("R_COMPILE_PKGS") rcp <- switch(rcps, "TRUE"=, "true"=, "True"=, "yes"=, "Yes"= 1, "FALSE"=,"false"=,"False"=, "no"=, "No" = 0, as.numeric(rcps)) if (!is.na(rcp)) BC <- (rcp > 0) if (BC) { starsmsg(stars, "byte-compile and prepare package for lazy loading") cmd <- c("Sys.setenv(R_ENABLE_JIT = 0L)", "invisible(compiler::enableJIT(0))", "invisible(compiler::compilePKGS(1L))", "compiler::setCompilerOptions(suppressAll = FALSE)", "compiler::setCompilerOptions(suppressUndefined = TRUE)", "compiler::setCompilerOptions(suppressNoSuperAssignVar = TRUE);") } else { starsmsg(stars, "preparing package for lazy loading") cmd <- "" } keep.source <- parse_description_field(desc, "KeepSource", default = keep.source) cmd <- append(cmd, paste0("setwd(", quote_path(getwd()), ")")) cmd <- append(cmd, paste0("if (isNamespaceLoaded(\"",pkg_name, "\"))", " unloadNamespace(\"", pkg_name, "\")")) cmd <- append(cmd, "suppressPackageStartupMessages(.getRequiredPackages(quietly = TRUE))") if (pkg_staged_install) set.install.dir <- paste0(", set.install.dir = ", quote_path(final_instdir)) else set.install.dir <- "" cmd <- append(cmd, paste0("tools:::makeLazyLoading(\"", pkg_name, "\", ", quote_path(lib), ", ", "keep.source = ", keep.source, ", ", "keep.parse.data = ", keep.parse.data, set.install.dir, ")")) cmd <- paste(cmd, collapse="\n") out <- R_runR_deps_only(cmd, setRlibs(LinkingTo = TRUE, quote = TRUE)) if(length(out)) cat(paste(c(out, ""), collapse = "\n")) if(length(attr(out, "status"))) pkgerrmsg("lazy loading failed", pkg_name) } 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") cmd <- c("tools:::.install_package_indices(\".\",", quote_path(instdir), ")") cmd <- paste(cmd, collapse="\n") out <- R_runR_deps_only(cmd, setRlibs(LinkingTo = TRUE, quote = TRUE)) if(length(out)) cat(paste(c(out, ""), collapse = "\n")) if (length(attr(out, "status"))) 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() do_test_load <- function(extra_cmd = NULL) { cmd <- paste0("tools:::.test_load_package('", pkg_name, "', ", quote_path(lib), ")") if (!is.null(extra_cmd)) cmd <- paste0(cmd, "\n", extra_cmd) tlim <- get_timeout(Sys.getenv("_R_INSTALL_TEST_LOAD_ELAPSED_TIMEOUT_")) if (length(test_archs) > 1L) { msgs <- character() for (arch in test_archs) { starsmsg("***", "arch - ", arch) out <- R_runR_deps_only(cmd, deps_only_env = setRlibs(lib0, self = TRUE, quote = TRUE), arch = arch, timeout = tlim, multiarch = TRUE) 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 { out <- R_runR_deps_only(cmd, deps_only_env = setRlibs(lib0, self = TRUE, quote = TRUE), timeout = tlim) if(length(out)) { cat(paste(c(out, ""), collapse = "\n")) } if(length(attr(out, "status"))) errmsg("loading failed") } } if (test_load && !have_cross) { if (pkg_staged_install) starsmsg(stars, "testing if installed package can be loaded from temporary location") else starsmsg(stars, "testing if installed package can be loaded") do_test_load() } if (pkg_staged_install) { if (WINDOWS) { unlink(final_instdir, recursive = TRUE) if (!file.rename(instdir, final_instdir)) { if (dir.exists(instdir) && !dir.exists(final_instdir)) { message("WARNING: moving package to final location failed, copying instead") ret <- file.copy(instdir, dirname(final_instdir), recursive = TRUE, copy.date = TRUE) if (any(!ret)) errmsg(" copying to final location failed") unlink(instdir, recursive = TRUE) } else errmsg(" moving to final location failed") } } else { patch_rpaths() unlink(final_instdir, recursive = TRUE) owd <- setwd(startdir) status <- system(paste("mv -f", shQuote(instdir), shQuote(dirname(final_instdir)))) if (status) errmsg(" moving to final location failed") setwd(owd) } instdir <- final_instdir lib <- final_lib Sys.setenv(R_PACKAGE_DIR = final_rpackagedir) Sys.setenv(R_LIBS = final_rlibs) .libPaths(final_libpaths) if (test_load) { starsmsg(stars, "testing if installed package can be loaded from final location") serf <- tempfile() cmd <- paste0("f <- base::file(", quote_path(serf), ", \"wb\")") cmd <- append(cmd, paste0("base::invisible(base::suppressWarnings(base::serialize(", "base::as.list(base::getNamespace(\"", pkg_name, "\"), all.names=TRUE), f)))")) cmd <- append(cmd, "base::close(f)") do_test_load(extra_cmd = paste(cmd, collapse = "\n")) starsmsg(stars, "testing if installed package keeps a record of temporary installation path") r <- readBin(serf, "raw", n=file.size(serf)) unlink(serf) if (length(grepRaw("00new", r, fixed = TRUE, all = FALSE, value = FALSE))) errmsg("hard-coded installation path: ", "please report to the package maintainer and use ", sQuote("--no-staged-install")) } } if (do_strip_lib && nzchar(strip_cmd <- Sys.getenv("R_STRIP_STATIC_LIB")) && length(a_s <- Sys.glob(file.path(file.path(lib, curPkg), "lib", "*.a")))) { if(length(a_s) > 1L) starsmsg(stars, "stripping static libraries under lib") else starsmsg(stars, "stripping static library under lib") system(paste(c(strip_cmd, shQuote(a_s)), collapse = " ")) } if (do_strip_lib && nzchar(strip_cmd <- Sys.getenv("R_STRIP_SHARED_LIB")) && length(so_s <- Sys.glob(file.path(file.path(lib, curPkg), "lib", paste0("*", SHLIB_EXT))))) { if(length(so_s) > 1L) starsmsg(stars, "stripping dynamic libraries under lib") else starsmsg(stars, "stripping dynamic library under lib") system(paste(c(strip_cmd, shQuote(so_s)), collapse = " ")) } } 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 staged_install <- 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") keep.parse.data <- getOption("keep.parse.data.pkgs") use_LTO <- NA 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 do_strip <- do_strip_lib <- FALSE while(length(args)) { a <- args[1L] if (a %in% c("-h", "--help")) { Usage() do_exit(0) } 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("", .R_copyright_msg(2000), "This is free software; see the GNU General Public License version 2", "or later for copying conditions. There is NO warranty.", sep = "\n") do_exit(0) } 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 == "--with-keep.parse.data") { keep.parse.data <- TRUE } else if (a == "--without-keep.parse.data") { keep.parse.data <- FALSE } else if (a == "--byte-compile") { byte_compile <- TRUE } else if (a == "--no-byte-compile") { byte_compile <- FALSE } else if (a == "--use-LTO") { use_LTO <- TRUE } else if (a == "--no-use-LTO") { use_LTO <- FALSE } else if (a == "--staged-install") { staged_install <- TRUE } else if (a == "--no-staged-install") { staged_install <- FALSE } else if (a == "--dsym") { dsym <- TRUE } else if (a == "--strip") { do_strip <- TRUE } else if (a == "--strip-lib") { do_strip_lib <- TRUE } else if (substr(a, 1, 18) == "--built-timestamp=") { built_stamp <- substr(a, 19, 1000) } else if (startsWith(a, "-")) { 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 %w/o% c("--merge-multiarch", "--build") Sys.setenv("_R_INSTALL_NO_DONE_" = "yes") for (arch in archs) { cmd <- c(shQuote(file.path(R.home(), "bin", arch, "Rcmd.exe")), "INSTALL", shQuote(args), "--no-multiarch") if (arch == "x64") { Sys.setenv("_R_INSTALL_SUPPRESS_NO_STAGED_MESSAGE_" = "yes") cmd <- c(cmd, "--libs-only --no-staged-install", 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 (arch == "x64") Sys.unsetenv("_R_INSTALL_SUPPRESS_NO_STAGED_MESSAGE_") if(res) break } } } else { archs <- dir(file.path(R.home("bin"), "exec")) if (length(archs) > 1L) { args <- args0 %w/o% c("--merge-multiarch", "--build") Sys.setenv("_R_INSTALL_NO_DONE_" = "yes") last <- archs[length(archs)] for (arch in archs) { cmd <- c(shQuote(file.path(R.home("bin"), "R")), "--arch", arch, "CMD", "INSTALL", shQuote(args), "--no-multiarch") if (arch != archs[1L]) { Sys.setenv("_R_INSTALL_SUPPRESS_NO_STAGED_MESSAGE_" = "yes") cmd <- c(cmd, "--libs-only --no-staged-install") } 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 (arch != archs[1L]) Sys.unsetenv("_R_INSTALL_SUPPRESS_NO_STAGED_MESSAGE_") 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 && endsWith(pkg, ".zip")) { 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 %w/o% 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(shQuote(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, paste0("_test_dir_", Sys.getpid())) 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) == 0L } 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() do_exit(status = 3) } dir.create(lockdir, recursive = TRUE) if (!dir.exists(lockdir)) { message("ERROR: failed to create lock directory ", sQuote(lockdir), domain = NA) do_cleanup_tmpdir() do_exit(status = 3) } 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 (is.na(staged_install)) { rsi <- Sys.getenv("R_INSTALL_STAGED") rsi <- switch(rsi, "TRUE"=, "true"=, "True"=, "yes"=, "Yes"= 1, "FALSE"=,"false"=,"False"=, "no"=, "No" = 0, as.numeric(rsi)) if (!is.na(rsi)) staged_install <- (rsi > 0) else staged_install <- TRUE } if ((tar_up || zip_up) && fake) stop("building a fake installation is disallowed") if (fake) { use_configure <- FALSE if("--html" %notin% args0) 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, paste0("00LOCK-", basename(pkg))) 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", " --use-LTO use Link-Time Optimization", " --no-use-LTO do not use Link-Time Optimization", "", "Windows only:", " -d, --debug build a debug DLL", "", "Report bugs at <https://bugs.R-project.org>.", sep = "\n") p1 <- function(...) paste(..., collapse = " ") WINDOWS <- .Platform$OS.type == "windows" cross <- Sys.getenv("R_CROSS_BUILD") if(nzchar(cross)) { if(!cross %in% c("i386", "x64")) stop("invalid value ", sQuote(cross), " for R_CROSS_BUILD") WINDOWS <- TRUE Sys.setenv(R_ARCH = paste0("/", cross)) } 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_cxxstd <- NULL use_fc_link <- FALSE use_lto <- NA 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("", .R_copyright_msg(2000), "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 == "--use-LTO") { use_lto <- TRUE } else if (a == "--no-use-LTO") { use_lto <- FALSE } 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.ucrt"))) 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(fn <- "Makevars.ucrt") || file.exists(fn <- "Makevars.win"))) { makefiles <- c(fn, makefiles) lines <- readLines(fn, 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)) == 1) { val <- gsub("^CXX_STD *= *CXX", "", ll) val <- gsub(" +$", "", val) if (val %in% cxx_standards) { use_cxxstd <- val with_cxx <- TRUE } } if (any(grepl("^USE_FC_TO_LINK", lines, perl=TRUE, useBytes = TRUE))) use_fc_link <- 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)) == 1) { val <- gsub("^CXX_STD *= *CXX", "", ll) val <- gsub(" +$", "", val) if (val %in% cxx_standards) { use_cxxstd <- val with_cxx <- TRUE } } if (any(grepl("^USE_FC_TO_LINK", lines, perl=TRUE, useBytes = TRUE))) use_fc_link <- TRUE } if (is.null(use_cxxstd)) { for (i in cxx_standards) { if (nzchar(Sys.getenv(paste0("USE_CXX", i)))) { use_cxxstd <- i break } } } if (is.null(use_cxxstd)) { val <- Sys.getenv("R_PKG_CXX_STD") if (val %in% cxx_standards) { use_cxxstd <- val } } if (with_cxx) { checkCXX <- function(cxxstd) { for (i in rev(seq_along(makefiles))) { lines <- readLines(makefiles[i], warn = FALSE) pattern <- paste0("^CXX", cxxstd, " *= *") ll <- grep(pattern, lines, perl = TRUE, value = TRUE, useBytes = TRUE) for (j in rev(seq_along(ll))) { cxx <- gsub(pattern, "", ll[j]) return(nzchar(cxx)) } } return(FALSE) } if (!is.null(use_cxxstd)) { if (use_cxxstd == "98") { stop("C++98 standard requested but unsupported", call. = FALSE, domain = NA) } if (!checkCXX(use_cxxstd)) { stop(paste0("C++", use_cxxstd, " standard requested but CXX", use_cxxstd, " is not defined"), call. = FALSE, domain = NA) } } } makeargs <- paste0("SHLIB=", shQuote(shlib)) if (with_cxx) { if (!is.null(use_cxxstd)) { cxx_makeargs <- sprintf(c("CXX='$(CXX%s) $(CXX%sSTD)'", "CXXFLAGS='$(CXX%sFLAGS)'", "CXXPICFLAGS='$(CXX%sPICFLAGS)'", "SHLIB_LDFLAGS='$(SHLIB_CXX%sLDFLAGS)'", "SHLIB_LD='$(SHLIB_CXX%sLD)'"), use_cxxstd, use_cxxstd) makeargs <- c(cxx_makeargs, makeargs) } else { makeargs <- c("SHLIB_LDFLAGS='$(SHLIB_CXXLDFLAGS)'", "SHLIB_LD='$(SHLIB_CXXLD)'", makeargs) } } else if (use_fc_link && (with_f77 || with_f9x)) makeargs <- c("SHLIB_LDFLAGS='$(SHLIB_FCLDFLAGS)'", "SHLIB_LD='$(SHLIB_FCLD)'", "ALL_LIBS='$(PKG_LIBS) $(SHLIB_LIBADD)'", makeargs) if (with_objc) shlib_libadd <- c(shlib_libadd, "$(OBJC_LIBS)") if (with_f77 || with_f9x) { if (use_fc_link) shlib_libadd <- c(shlib_libadd, "$(FCLIBS_XTRA)") else shlib_libadd <- c(shlib_libadd, "$(FLIBS) $(FCLIBS_XTRA)") } 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 (with_f9x && file.exists("Makevars") && length(grep("^\\s*PKG_FCFLAGS", lines, perl = TRUE, useBytes = TRUE))) makeargs <- c(makeargs, "P_FCFLAGS='$(PKG_FCFLAGS)'") if (WINDOWS && debug) makeargs <- c(makeargs, "DEBUG=T") if (WINDOWS && rarch == "/x64") makeargs <- c(makeargs, "WIN=64 TCLBIN=") build_objects_symbol_tables <- config_val_to_logical(Sys.getenv("_R_SHLIB_BUILD_OBJECTS_SYMBOL_TABLES_", "FALSE")) makeargs <- c(makeargs, if(isTRUE(use_lto)) c(paste0("LTO=", shQuote("$(LTO_OPT)")), paste0("LTO_FC=", shQuote("$(LTO_FC_OPT)"))) else if(isFALSE(use_lto)) c("LTO=", "LTO_FC=") ) 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.int(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[endsWith(x, "-package")] <- " " 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)) { list2DF(list(Topic = character(), File = character(), Title = character(), Internal = character())) } else { lens <- lengths(topics) files <- sub("\\.[Rr]d$", "", Rd$File) internal <- (vapply(Rd$Keywords, function(x) match("internal", x, 0L), 0L) > 0L) list2DF(list(Topic = unlist(topics), File = rep.int(files, lens), Title = rep.int(Rd$Title, lens), Internal = rep.int(internal, lens))) } 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) & endsWith(gen, "<-") 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('</div></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.int(" ", 40L - nc), sep = "") else cat(" ", bf, "\n", rep.int(" ", 44L), sep = "") shown <<- TRUE } cat(type, rep.int(" ", 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))) tryInvokeRestart("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), fixed=TRUE) drop <- have[have2 %notin% 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), fixed=TRUE) drop <- have[have2 %notin% 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), fixed=TRUE) drop <- have[have2 %notin% 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.ucrt"))) 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(paste0("~/.R/Makevars-", Sys.getenv("R_PLATFORM"))))) m <- f else if(file.exists(f <- path.expand("~/.R/Makevars"))) m <- f } m } revert_install_time_patches <- function() { WINDOWS <- .Platform$OS.type == "windows" if (WINDOWS && dir.exists("install_time_patches")) { patches <- sort(list.files("install_time_patches"), decreasing = TRUE) for(p in patches) { fname <- paste0("install_time_patches/", p) if (system2("patch", args = c("-p2", "--binary", "--force", "--reverse"), stdin = fname) != 0) message("WARNING: failed to revert patch ", p, "\n") else message("Reverted installation-time patch ", p, " in package installation\n") } unlink("install_time_patches", recursive = TRUE) } } 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 } cxx_standards <- c("20", "17", "14", "11", "98")
compute.threshold.AROC.kernel <- function(object, newcovariate, FPF = 0.5) { if(class(object)[2] != "AROC.kernel") { stop(paste0("This function can not be used for this object class: ", class(object)[2])) } ncov <- length(newcovariate) np <- length(FPF) thresholds <- matrix(0, nrow = np, ncol = ncov) rownames(thresholds) <- FPF colnames(thresholds) <- newcovariate fit.mean.new <- npreg(object$bw.mean, exdat = newcovariate, residuals = TRUE) fit.var.new <- npreg(object$bw.var, exdat = newcovariate, residuals = TRUE) h.residuals <- object$fit.mean$resid/sqrt(object$fit.var$mean) csf0 <- apply(outer(h.residuals, h.residuals, ">="), 2, mean) csf0_inv <- apply(outer(csf0, FPF, "<="), 2, function(x, z) { res <- min(c(z[x], max(z))) res }, z = h.residuals) csf0_inv <- replace(csf0_inv, is.infinite(csf0_inv), max(h.residuals)) for(i in 1:ncov) { thresholds[,i] <- fit.mean.new$mean[i] + sqrt(fit.var.new$mean[i])*csf0_inv } res <- list() res$thresholds <- thresholds res }
context("test-geom_parallel_slopes") library(ggplot2) set.seed(202) test_df <- dplyr::bind_rows( tibble::tibble(a = runif(10, 0, 0.1), gr = 1), tibble::tibble(a = runif(15, 0.1, 0.3), gr = 2), tibble::tibble(a = runif(20, 0.4, 1), gr = 3) ) %>% dplyr::mutate( pan = factor(sample(1:3, dplyr::n(), replace = TRUE)), gr = factor(gr), b = as.integer(pan) * a + as.integer(gr) + runif(dplyr::n(), max = 0.1), c = as.integer(pan) * a^2 + as.integer(gr) + runif(dplyr::n(), max = 0.1), ) viz <- ggplot(test_df, aes(a, b, colour = gr)) + geom_point() test_that("geom_parallel_slopes works", { expect_doppelganger( "geom_parallel_slopes-basic-1", viz + geom_parallel_slopes() + labs(title = "geom_parallel_slopes()") ) expect_doppelganger( "geom_parallel_slopes-basic-2", viz + geom_parallel_slopes(se = FALSE) + labs(title = "geom_parallel_slopes() with `se = FALSE`") ) expect_doppelganger( "geom_parallel_slopes-basic-3", viz + geom_parallel_slopes( mapping = aes(group = gr), color = "red", size = 3 ) + labs(title = "geom_parallel_slopes() with extra aesthetics") ) expect_doppelganger( "geom_parallel_slopes-basic-4", ggplot(test_df, aes(a, c, colour = gr)) + geom_point() + geom_parallel_slopes(formula = y ~ poly(x, 2)) + labs(title = "Quadratic geom_parallel_slopes()") ) expect_doppelganger( "geom_parallel_slopes-basic-5", viz + geom_parallel_slopes() + facet_wrap(~pan) + labs(title = "Faceted geom_parallel_slopes()") ) expect_doppelganger( "geom_parallel_slopes-basic-6", ggplot(test_df, aes(a, b)) + geom_point() + geom_parallel_slopes(aes(group = gr)) + labs(title = "geom_parallel_slopes() with `group` aesthetics grouping") ) expect_doppelganger( "geom_parallel_slopes-basic-7", ggplot(test_df, aes(a, b)) + geom_point() + geom_parallel_slopes(aes(fill = gr)) + labs(title = "geom_parallel_slopes() with `fill` aesthetics grouping") ) expect_doppelganger( "geom_parallel_slopes-fullrange", viz + geom_parallel_slopes(fullrange = TRUE) + xlim(c(-1, 2)) + labs(title = "geom_parallel_slopes() with fullrange=TRUE") ) expect_doppelganger( "geom_parallel_slopes-level", viz + geom_parallel_slopes(level = 0.25) + labs(title = "geom_parallel_slopes() with level=0.25") ) }) test_that("geom_parallel_slopes works in edge cases", { expect_doppelganger( "geom_parallel_slopes-edge-non-factor-grouping", test_df %>% dplyr::mutate(gr = as.integer(gr)) %>% ggplot(aes(a, b, colour = gr, group = gr)) + geom_point() + geom_parallel_slopes() + labs(title = "Works with non-factor grouping") ) expect_warning( expect_doppelganger( "geom_parallel_slopes-edge-no-grouping", ggplot(test_df, aes(a, b)) + geom_point() + geom_parallel_slopes() + labs(title = "Works without grouping") ), regexp = "grouping" ) expect_warning( expect_doppelganger( "geom_parallel_slopes-edge-unique-grouping", test_df %>% dplyr::mutate(gr = 1) %>% ggplot(aes(a, b, group = gr)) + geom_point() + geom_parallel_slopes() + labs(title = "Works with grouping variable with one value") ), regexp = "grouping.*unique" ) expect_warning( expect_doppelganger( "geom_parallel_slopes-edge-method-arg", viz + geom_parallel_slopes(method = "lm") + labs(title = "geom_parallel_slopes() with `method` supplied") ), regexp = "doesn't need a `method`" ) })
context("getFirstLast") test_that("getFirstLast", { expect_equal(getFirst(1:3), 1L) expect_equal(getLast(1:3), 3L) expect_equal(getFirst(list(iris, 1)), iris) expect_equal(getLast(list(iris, 1)), 1) expect_equal(getFirst(c(a=1, 2)), 1) expect_equal(names(getFirst(c(a=1, 2))), NULL) expect_equal(getLast(c(a=1, 2)), 2) expect_equal(names(getLast(c(a=1, 2))), NULL) })
setMethod( 'ConstantOutFluxRate_by_PoolIndex' ,signature=signature( sourceIndex='numeric' ,rate_constant='numeric' ) ,def=function(sourceIndex,rate_constant){ if (rate_constant<0){ stop( "Negative rate constant. A rate_constant defines a flux F with F = rate_constant*pool_content. Since fluxes have to be positive and pool contents are positive rate constants have to be positive too." ) } rate=new( 'ConstantOutFluxRate_by_PoolIndex' ,sourceIndex=PoolIndex(id=sourceIndex) ,rate_constant=rate_constant ) rate } ) setMethod( f="by_PoolName", signature=c(obj='ConstantOutFluxRate_by_PoolIndex'), def=function(obj,poolNames){ new( 'ConstantOutFluxRate_by_PoolName' ,sourceName=PoolName(id=obj@sourceIndex,poolNames) ,rate_constant=obj@rate_constant ) } )
path.rpart <- function(tree, nodes, pretty = 0, print.it = TRUE) { if (!inherits(tree, "rpart")) stop("Not a legitimate \"rpart\" object") splits <- labels.rpart(tree, pretty = pretty) frame <- tree$frame n <- row.names(frame) node <- as.numeric(n) which <- descendants(node) path <- list() if (missing(nodes)) { xy <- rpartco(tree) while(length(i <- identify(xy, n = 1L, plot = FALSE)) > 0L) { path[[n[i]]] <- path.i <- splits[which[, i]] if (print.it) { cat("\n", "node number:", n[i], "\n") cat(paste(" ", path.i), sep = "\n") } } } else { if (length(nodes <- node.match(nodes, node)) == 0L) return(invisible()) for (i in nodes) { path[[n[i]]] <- path.i <- splits[which[, i]] if (print.it) { cat("\n", "node number:", n[i], "\n") cat(paste(" ", path.i), sep = "\n") } } } invisible(path) }
plot.predMMSE <- function(x,legend.loc="topright",legend,add=FALSE,...) { if (!inherits(x, "predMMSE")) stop("use only with \"predMMSE\" objects") if(is.na(as.logical(add))) stop("add should be TRUE or FALSE") ng <- 1 ndistr <- grep("MMSEdistr",colnames(x)) if(length(ndistr)) { ng <- length(ndistr)/3 } else { if(ncol(x)>2) { ng <- ncol(x)-1 } } if(missing(legend)) legend <- paste("class",1:ng,sep="") dots <- list(...) if(length(list(...)$main)) { main1 <- as.character(eval(match.call()$main)) dots <- dots[setdiff(names(dots),"main")] } else main1 <- "Prediction of MMSE scores" if(length(list(...)$type)) { type1 <- eval(match.call()$type) dots <- dots[-which(names(dots)=="type")] } else type1 <- "l" if(length(list(...)$col)) { col1 <- eval(match.call()$col) col1 <- rep(col1,length.out=ng) dots <- dots[-which(names(dots)=="col")] } else col1 <- rainbow(ng) if(length(list(...)$ylim)) { ylim1 <- eval(match.call()$ylim) dots <- dots[setdiff(names(dots),"ylim")] } else ylim1 <- c(0,30) if(length(list(...)$xlab)) { xlab1 <- as.character(eval(match.call()$xlab)) dots <- dots[setdiff(names(dots),"xlab")] } else xlab1 <- "prediction time" if(length(list(...)$ylab)) { ylab1 <- as.character(eval(match.call()$ylab)) dots <- dots[setdiff(names(dots),"ylab")] } else ylab1 <- "MMSE" names.plot <- c("adj","ann","asp","axes","bg","bty","cex","cex.axis","cex.lab","cex.main","cex.sub","col","col.axis", "col.lab","col.main","col.sub","crt","err","family","fig","fin","font","font.axis","font.lab","font.main","font.sub", "frame.plot","lab","las","lend","lheight","ljoin","lmitre","lty","lwd","mai","main","mar","mex","mgp","mkh","oma", "omd","omi","pch","pin","plt","ps","pty","smo","srt","sub","tck","tcl","type","usr","xaxp","xaxs","xaxt","xlab", "xlim","xpd","yaxp","yaxs","yaxt","ylab","ylbias","ylim") dots.plot <- dots[intersect(names(dots),names.plot)] if(!isTRUE(add)) { do.call("matplot",c(dots.plot,list(x=x[,rep(1,ng),drop=FALSE],y=x[,1+1:ng,drop=FALSE],type=type1,ylab=ylab1,xlab=xlab1,main=main1,ylim=ylim1,col=col1))) } else { do.call("matlines",c(dots.plot,list(x=x[,rep(1,ng),drop=FALSE],y=x[,1+1:ng,drop=FALSE],type=type1,col=col1))) } if(length(ndistr)) { if(length(list(...)$lty)) dots.plot <- dots.plot[setdiff(names(dots),"lty")] do.call("matlines",c(dots.plot,list(x=x[,rep(1,ng),drop=FALSE],y=x[,1+ng+1:ng,drop=FALSE],col=col1,lty=2))) do.call("matlines",c(dots.plot,list(x=x[,rep(1,ng),drop=FALSE],y=x[,1+2*ng+1:ng,drop=FALSE],col=col1,lty=2))) } if(!is.null(legend)) { if(length(list(...)$box.lty)) { box.lty1 <- as.integer(eval(match.call()$box.lty)) dots <- dots[setdiff(names(dots),"box.lty")] } else box.lty1 <- 0 if(length(list(...)$inset)) { inset1 <- eval(match.call()$inset) dots <- dots[setdiff(names(dots),"inset")] } else inset1 <- c(0.02,0.02) if(length(list(...)$lty)) { lty1 <- eval(match.call()$lty) dots <- dots[setdiff(names(dots),"lty")] } else lty1 <- 1 names.legend <- c("fill","border","lty","lwd","pch","angle","density","bg","box.lwd", "box.lty","box.col","pt.bg","cex","pt.cex","pt.lwd","xjust","yjust","x.intersp","y.intersp","adj","text.width", "text.col","text.font","merge","trace","plot","ncol","horiz","title","xpd","title.col","title.adj","seg.len") dots.leg <- dots[intersect(names(dots),names.legend)] if(type1=="l" | type1=="b") dots.leg <- c(dots.leg,list(lty=lty1)) if(!(type1 %in% c("l","b"))) dots.leg <- dots.leg[setdiff(names(dots),"lwd")] do.call("legend",c(dots.leg,list(x=legend.loc, legend=legend, box.lty=box.lty1, inset=inset1,col=col1))) } return(invisible(NULL)) }
context('chapter 4') library(rethinking) expect_equiv_eps <- function( x , y , eps=0.01 ) { expect_equivalent( x , y , tolerance=eps ) } library(rethinking) data(Howell1) d <- Howell1 d2 <- d[ d$age >= 18 , ] flist <- alist( height ~ dnorm( mu , sigma ) , mu ~ dnorm( 178 , 20 ) , sigma ~ dunif( 0 , 50 ) ) m4.1 <- quap( flist , data=d2 ) test_that("R code 4.29", expect_equiv_eps( round(coef(m4.1),2) , c(154.61,7.73) ) ) m4.2 <- quap( alist( height ~ dnorm( mu , sigma ) , mu ~ dnorm( 178 , 0.1 ) , sigma ~ dunif( 0 , 50 ) ) , data=d2 ) test_that("R code 4.31", expect_equiv_eps( round(coef(m4.2),2) , c(177.86,24.52) ) ) library(rethinking) data(Howell1) d <- Howell1 d2 <- d[ d$age >= 18 , ] d2$xbar <- mean(d2$weight) m4.3 <- quap( alist( height ~ dnorm( mu , sigma ) , mu <- a + b*( weight - xbar ) , a ~ dnorm( 178 , 20 ) , b ~ dlnorm( 0 , 1 ) , sigma ~ dunif( 0 , 50 ) ) , data=d2 ) test_that("R code 4.42", expect_equiv_eps( round(coef(m4.3),2) , c(154.60 , 0.90 , 5.07) ) ) m4.3b <- quap( alist( height ~ dnorm( mu , sigma ) , mu <- a + exp(log_b)*( weight - xbar ), a ~ dnorm( 178 , 20 ) , log_b ~ dnorm( 0 , 1 ) , sigma ~ dunif( 0 , 50 ) ) , data=d2 ) test_that("R code 4.43", expect_equiv_eps( round(coef(m4.3b),2) , c(154.60 , -0.10 , 5.07) ) ) library(rethinking) data(Howell1) d <- Howell1 d$weight_s <- ( d$weight - mean(d$weight) )/sd(d$weight) d$weight_s2 <- d$weight_s^2 m4.5 <- quap( alist( height ~ dnorm( mu , sigma ) , mu <- a + b1*weight_s + b2*weight_s2 , a ~ dnorm( 178 , 20 ) , b1 ~ dlnorm( 0 , 1 ) , b2 ~ dnorm( 0 , 1 ) , sigma ~ dunif( 0 , 50 ) ) , data=d ) test_that("R code 4.65", expect_equiv_eps( round(coef(m4.5),2) , c(146.06 , 21.73 , -7.80 , 5.77) ) ) d$weight_s3 <- d$weight_s^3 m4.6 <- quap( alist( height ~ dnorm( mu , sigma ) , mu <- a + b1*weight_s + b2*weight_s2 + b3*weight_s3 , a ~ dnorm( 178 , 20 ) , b1 ~ dlnorm( 0 , 1 ) , b2 ~ dnorm( 0 , 10 ) , b3 ~ dnorm( 0 , 10 ) , sigma ~ dunif( 0 , 50 ) ) , data=d ) test_that("R code 4.69", expect_equiv_eps( round(coef(m4.6),2) , c(146.74 , 15.00 , -6.54 , 3.60 , 4.82) ) ) library(rethinking) data(cherry_blossoms) d <- cherry_blossoms d2 <- d[ complete.cases(d$temp) , ] num_knots <- 15 knot_list <- quantile( d2$year , probs=seq(0,1,length.out=num_knots) ) library(splines) B <- bs(d2$year, knots=knot_list[-c(1,num_knots)] , degree=3 , intercept=TRUE ) m4.7 <- quap( alist( T ~ dnorm( mu , sigma ) , mu <- a + B %*% w , a ~ dnorm(6,10), w ~ dnorm(0,1), sigma ~ dexp(1) ), data=list( T=d2$temp , B=B ) , start=list( w=rep( 0 , ncol(B) ) ) ) test_that("R code 4.76", expect_equiv_eps( round(coef(m4.7),2) , c(0.10 , 0.24 , 1.20, -0.82 , 0.10, -1.40 , 1.16, -1.92 , 2.35 ,-2.32 , 0.94, -1.61 , 0.18 , -1.24 , 0.03 , 1.00 , 2.04 , 6.32 , 0.34 ) ) ) m4.7alt <- quap( alist( T ~ dnorm( mu , sigma ) , mu <- a + sapply( 1:1124 , function(i) sum( B[i,]*w ) ) , a ~ dnorm(6,10), w ~ dnorm(0,1), sigma ~ dexp(1) ), data=list( T=d2$temp , B=B ) , start=list( w=rep( 0 , ncol(B) ) ) ) test_that("R code 4.76", expect_equiv_eps( round(coef(m4.7alt),2) , c(0.10 , 0.24 , 1.20, -0.82 , 0.10, -1.40 , 1.16, -1.92 , 2.35 ,-2.32 , 0.94, -1.61 , 0.18 , -1.24 , 0.03 , 1.00 , 2.04 , 6.32 , 0.34 ) ) )
test_that("is_running", { expect_false(is_running()) })
integration <- function(values, intervals){ n <- length(values) sum(0.5 * (values[1:n-1] + values[2:n]) * diff(intervals)) } getNC <- function(beta, subbetas, nvertex, ncolor, edges, neighbors=NULL, blocks=NULL, algorithm=c("SwendsenWang", "Gibbs", "Wolff"), n, burn){ if(length(subbetas) < 2) stop("There has to be at least 2 intermidiate betas.") if(max(subbetas) > beta) stop("The maxmimum of the intermidiate betas has to be less than or equal to beta") if(max(subbetas) < beta) subbetas <- c(subbetas, beta) if(is.null(edges)) stop("'edges' are needed to get the normalizing constant.") algorithm <- match.arg(algorithm) algorithm <- switch(algorithm, Gibbs = 1, SwendsenWang = 2, Wolff = 3) if(algorithm == 1 && (is.null(neighbors) || is.null(blocks))) stop("'neighbors' and 'blcoks' are needed to run Gibbs sampling.") if(algorithm == 3 && is.null(neighbors)) stop("'neighbors' are needed to run the Wolff algorithm.") if(algorithm ==1) p.body <- quote(BlocksGibbs(n, nvertex, ncolor, neighbors, blocks, beta=subbetas[i])) else if(algorithm == 2) p.body <- quote(SW(n, nvertex, ncolor, edges, beta=subbetas[i])) else p.body <- quote(Wolff(n, nvertex, ncolor, neighbors, beta=subbetas[i])) EUs <- rep(0, length(subbetas)) for (i in 1 : length(subbetas)){ colors <- eval(p.body) EUs[i] <- mean(apply(colors[,-(1:burn)], 2, function(x) sum(x[edges[,1]]==x[edges[,2]]))) } exp(integration(EUs, subbetas) + nvertex * log(ncolor)) }
tab_stackfrq <- function(items, weight.by = NULL, title = NULL, var.labels = NULL, value.labels = NULL, wrap.labels = 20, sort.frq = NULL, alternate.rows = FALSE, digits = 2, string.total = "N", string.na = "NA", show.n = FALSE, show.total = FALSE, show.na = FALSE, show.skew = FALSE, show.kurtosis = FALSE, digits.stats = 2, file = NULL, encoding = NULL, CSS = NULL, use.viewer = TRUE, remove.spaces = TRUE) { if (!is.null(sort.frq)) { if (sort.frq == "first.asc") { sort.frq <- "first" reverseOrder <- FALSE } else if (sort.frq == "first.desc") { sort.frq <- "first" reverseOrder <- TRUE } else if (sort.frq == "last.asc") { sort.frq <- "last" reverseOrder <- FALSE } else if (sort.frq == "last.desc") { sort.frq <- "last" reverseOrder <- TRUE } else { sort.frq <- NULL reverseOrder <- FALSE } } else { reverseOrder <- FALSE } encoding <- get.encoding(encoding, items) if (is.null(value.labels)) { value.labels <- sjlabelled::get_labels( items[[1]], attr.only = F, values = "n", non.labelled = T ) } if (is.null(var.labels)) { var.labels <- sjlabelled::get_label(items, def.value = colnames(items)) } minval <- as.numeric(min(apply(items, 2, function(x) min(x, na.rm = TRUE)))) maxval <- as.numeric(max(apply(items, 2, function(x) max(x, na.rm = TRUE)))) if (is.null(value.labels)) value.labels <- as.character(minval:maxval) if (show.na) value.labels <- c(value.labels, `NA` = string.na) catcount <- length(value.labels) value.labels <- sjmisc::word_wrap(value.labels, wrap.labels, "<br>") if (is.null(var.labels)) var.labels <- colnames(items) var.labels <- sjmisc::word_wrap(var.labels, wrap.labels, "<br>") if (show.skew) pstat_skewness <- datawizard::skewness(items) if (show.kurtosis) pstat_kurtosis <- datawizard::kurtosis(items) if (is.null(weight.by)) { dummy <- sjmisc::frq(items, show.strings = TRUE, show.na = show.na) } else { items$weights <- weight.by dummy <- sjmisc::frq(items, weights = items$weights, show.strings = TRUE, show.na = show.na) } mat.n <- .transform_data(dummy, col = "frq") mat <- .transform_data(dummy, col = ifelse(isTRUE(show.na), "raw.prc", "valid.prc")) facord <- seq_len(nrow(mat)) if (!is.null(sort.frq)) { if (sort.frq == "first") facord <- order(mat.n$V1) else facord <- order(mat.n[, ncol(mat.n)]) } if (reverseOrder) facord <- rev(facord) toWrite <- table.header <- sprintf("<html>\n<head>\n<meta http-equiv=\"Content-type\" content=\"text/html;charset=%s\">\n", encoding) tag.table <- "table" tag.caption <- "caption" tag.thead <- "thead" tag.tdata <- "tdata" tag.arc <- "arc" tag.centeralign <- "centeralign" tag.firsttablecol <- "firsttablecol" tag.ncol <- "ncol" tag.skewcol <- "skewcol" tag.kurtcol <- "kurtcol" tag.summary <- "summary" css.table <- "border-collapse:collapse; border:none; border-bottom:double black;" css.caption <- "font-weight: bold; text-align:left;" css.thead <- "border-top:double black; border-bottom:1px solid black; padding:0.2cm;" css.tdata <- "padding:0.2cm;" css.arc <- "background-color: css.centeralign <- "text-align:center;" css.firsttablecol <- "font-style:italic;" css.ncol <- "" css.summary <- "" css.skewcol <- "" css.kurtcol <- "" if (!is.null(CSS)) { if (!is.null(CSS[['css.table']])) css.table <- ifelse(substring(CSS[['css.table']],1,1) == '+', paste0(css.table, substring(CSS[['css.table']],2)), CSS[['css.table']]) if (!is.null(CSS[['css.thead']])) css.thead <- ifelse(substring(CSS[['css.thead']],1,1) == '+', paste0(css.thead, substring(CSS[['css.thead']],2)), CSS[['css.thead']]) if (!is.null(CSS[['css.caption']])) css.caption <- ifelse(substring(CSS[['css.caption']],1,1) == '+', paste0(css.caption, substring(CSS[['css.caption']],2)), CSS[['css.caption']]) if (!is.null(CSS[['css.summary']])) css.summary <- ifelse(substring(CSS[['css.summary']],1,1) == '+', paste0(css.summary, substring(CSS[['css.summary']],2)), CSS[['css.summary']]) if (!is.null(CSS[['css.arc']])) css.arc <- ifelse(substring(CSS[['css.arc']],1,1) == '+', paste0(css.arc, substring(CSS[['css.arc']],2)), CSS[['css.arc']]) if (!is.null(CSS[['css.tdata']])) css.tdata <- ifelse(substring(CSS[['css.tdata']],1,1) == '+', paste0(css.tdata, substring(CSS[['css.tdata']],2)), CSS[['css.tdata']]) if (!is.null(CSS[['css.centeralign']])) css.centeralign <- ifelse(substring(CSS[['css.centeralign']],1,1) == '+', paste0(css.centeralign, substring(CSS[['css.centeralign']],2)), CSS[['css.centeralign']]) if (!is.null(CSS[['css.firsttablecol']])) css.firsttablecol <- ifelse(substring(CSS[['css.firsttablecol']],1,1) == '+', paste0(css.firsttablecol, substring(CSS[['css.firsttablecol']],2)), CSS[['css.firsttablecol']]) if (!is.null(CSS[['css.ncol']])) css.ncol <- ifelse(substring(CSS[['css.ncol']],1,1) == '+', paste0(css.ncol, substring(CSS[['css.ncol']],2)), CSS[['css.ncol']]) if (!is.null(CSS[['css.skewcol']])) css.skewcol <- ifelse(substring(CSS[['css.skewcol']],1,1) == '+', paste0(css.skewcol, substring(CSS[['css.skewcol']],2)), CSS[['css.skewcol']]) if (!is.null(CSS[['css.kurtcol']])) css.kurtcol <- ifelse(substring(CSS[['css.kurtcol']],1,1) == '+', paste0(css.kurtcol, substring(CSS[['css.kurtcol']],2)), CSS[['css.kurtcol']]) } page.style <- sprintf("<style>\nhtml, body { background-color: white; }\n%s { %s }\n%s { %s }\n.%s { %s }\n.%s { %s }\n.%s { %s }\n.%s { %s }\n.%s { %s }\n.%s { %s }\n.%s { %s }\n.%s { %s }\n.%s { %s }\n</style>", tag.table, css.table, tag.caption, css.caption, tag.thead, css.thead, tag.tdata, css.tdata, tag.firsttablecol, css.firsttablecol, tag.arc, css.arc, tag.centeralign, css.centeralign, tag.ncol, css.ncol, tag.summary, css.summary, tag.kurtcol, css.kurtcol, tag.skewcol, css.skewcol) toWrite <- paste0(toWrite, page.style) toWrite = paste(toWrite, "\n</head>\n<body>", "\n") page.content <- "<table>\n" if (!is.null(title)) page.content <- paste(page.content, sprintf(" <caption>%s</caption>\n", title)) page.content <- paste0(page.content, " <tr>\n") page.content <- paste0(page.content, " <th class=\"thead\">&nbsp;</th>\n") for (i in 1:catcount) { page.content <- paste0(page.content, sprintf(" <th class=\"thead\">%s</th>\n", value.labels[i])) } if (show.total) page.content <- paste0(page.content, sprintf(" <th class=\"thead ncol summary\">%s</th>\n", string.total)) if (show.skew) page.content <- paste0(page.content, " <th class=\"thead skewcol summary\">Skew</th>\n") if (show.kurtosis) page.content <- paste0(page.content, " <th class=\"thead kurtcol summary\">Kurtosis</th>\n") page.content <- paste0(page.content, " </tr>\n") for (i in seq_len(nrow(mat))) { arcstring <- "" if (alternate.rows) arcstring <- ifelse(sjmisc::is_even(i), " arc", "") page.content <- paste0(page.content, " <tr>\n") page.content <- paste0(page.content, sprintf(" <td class=\"firsttablecol%s\">%s</td>\n", arcstring, var.labels[facord[i]])) for (j in seq_len(ncol(mat))) { if (show.n) { page.content <- paste0(page.content, sprintf(" <td class=\"tdata centeralign%s\">%i<br>(%.*f&nbsp;%%)</td>\n", arcstring, as.integer(mat.n[facord[i], j]), digits, mat[facord[i], j])) } else { page.content <- paste0(page.content, sprintf(" <td class=\"tdata centeralign%s\">%.*f&nbsp;%%</td>\n", arcstring, digits, mat[facord[i], j])) } } if (show.total) page.content <- paste0(page.content, sprintf(" <td class=\"tdata centeralign ncol summary%s\">%i</td>\n", arcstring, as.integer(sum(mat.n[facord[i], ])))) if (show.skew) page.content <- paste0(page.content, sprintf(" <td class=\"tdata centeralign skewcol summary%s\">%.*f</td>\n", arcstring, digits.stats, pstat_skewness[facord[i]])) if (show.kurtosis) page.content <- paste0(page.content, sprintf(" <td class=\"tdata centeralign kurtcol summary%s\">%.*f</td>\n", arcstring, digits.stats, pstat_kurtosis[facord[i]])) page.content <- paste0(page.content, " </tr>\n") } page.content <- paste(page.content, "\n</table>") toWrite <- paste(toWrite, page.content, "\n") toWrite <- paste0(toWrite, "</body></html>") knitr <- page.content knitr <- gsub("class=", "style=", knitr, fixed = TRUE, useBytes = TRUE) knitr <- gsub("<table", sprintf("<table style=\"%s\"", css.table), knitr, fixed = TRUE, useBytes = TRUE) knitr <- gsub("<caption", sprintf("<caption style=\"%s\"", css.caption), knitr, fixed = TRUE, useBytes = TRUE) knitr <- gsub(tag.tdata, css.tdata, knitr, fixed = TRUE, useBytes = TRUE) knitr <- gsub(tag.thead, css.thead, knitr, fixed = TRUE, useBytes = TRUE) knitr <- gsub(tag.centeralign, css.centeralign, knitr, fixed = TRUE, useBytes = TRUE) knitr <- gsub(tag.firsttablecol, css.firsttablecol, knitr, fixed = TRUE, useBytes = TRUE) knitr <- gsub(tag.ncol, css.ncol, knitr, fixed = TRUE, useBytes = TRUE) knitr <- gsub(tag.skewcol, css.skewcol, knitr, fixed = TRUE, useBytes = TRUE) knitr <- gsub(tag.kurtcol, css.kurtcol, knitr, fixed = TRUE, useBytes = TRUE) knitr <- gsub(tag.summary, css.summary, knitr, fixed = TRUE, useBytes = TRUE) knitr <- gsub(tag.arc, css.arc, knitr, fixed = TRUE, useBytes = TRUE) if (remove.spaces) { knitr <- sju.rmspc(knitr) toWrite <- sju.rmspc(toWrite) page.content <- sju.rmspc(page.content) } structure(class = c("sjTable", "sjtstackfrq"), list(page.style = page.style, page.content = page.content, page.complete = toWrite, header = table.header, knitr = knitr, file = file, viewer = use.viewer)) } .transform_data <- function(x, col) { dat <- suppressWarnings(Reduce(function(x, y) merge(x, y, all = TRUE, sort = FALSE, by = "val"), x)) if (is.factor(dat$val)) { reihe <- levels(dat$val) if (anyNA(dat$val)) reihe <- c(reihe, NA) dat <- dat[order(dat$val, reihe), ] } else { dat <- dat[order(dat$val), ] } colnames(dat) <- make.names(colnames(dat), unique = TRUE) keep <- (colnames(dat) == "val") | grepl(paste0("^", col), colnames(dat)) dat <- as.data.frame(t(dat[, keep, drop = FALSE])) dat <- as.data.frame(sapply(dat[-1, ], function(i) as.numeric(as.character(i)))) dat[is.na(dat)] <- 0 colnames(dat) <- sprintf("V%i", 1:ncol(dat)) dat }
if(require("suppdata") & require("testthat")){ context("bioRxiv") test_that("bioRxiv works", { skip_on_cran() expect_true(file.exists(suppdata("10.1101/016386", 1))) }) test_that("bioRxiv fails with character SI info", { skip_on_cran() expect_error(suppdata("10.1101/016386", si = "999"), "numeric SI info") }) }
plot.Meth <- function( x, which = NULL, col.LoA = "blue", col.pt = "black", cex.name = 2, var.range, diff.range, var.names = FALSE, pch = 16, cex = 0.7, Transform, ... ) { if( !missing(Transform) ) { if( is.character(Transform) ) Transform <- choose.trans(Transform)$trans if( !is.function(Transform) ) stop( "Transform= must be of mode character or function\n" ) x$y <- Transform( x$y ) } x <- x[,c("meth","item","repl","y")] data <- to.wide( x ) if( is.null(which) ) which <- match( levels(x$meth), names(data) ) if( is.logical( var.names ) ) { plot.names <- var.names if( is.character( which ) ) var.names <- which else var.names <- names( data )[which] } else plot.names <- TRUE pnl <- function( x, y, ... ) { abline( 0, 1, col="black" ) points( x, y, pch=pch, cex=cex, col=col.pt, ... ) } pnu <- function( x, y, ... ) { sdd <- sd( (y-x), na.rm=TRUE ) mnd <- mean( (y-x), na.rm=TRUE ) abline( h=mnd+(-1:1)*2.00*sdd, col=col.LoA ) abline( h=0,col="black" ) points( (x+y)/2, y-x, pch=pch, cex=cex, col=col.pt, ... ) } pldat <- data[,which] nvar <- ncol( pldat ) if( missing(var.range) ) rg <- range( pldat, na.rm=TRUE ) else rg <- var.range if( missing(diff.range) ) dif.rg <- c(-1,1)*diff(rg)/2 else if( length( diff.range )==1 ) dif.rg <- c(-1,1)*abs(diff.range) else dif.rg <- diff.range oma <- par("mar") oldpar <- par( mfrow=c(nvar,nvar), mar=c(0,0,0,0), oma=c(4,4,4,4), las=1 ) on.exit( par ( oldpar ) ) for( ir in 1:nvar ) for( ic in 1:nvar ) { if( ir == ic ) { plot( 0:1, 0:1, type="n", xlab="", ylab="", axes=FALSE ) text( 0.5, 0.5, names( pldat )[ir], font=2, cex=cex.name ) box() } if( ir < ic ) { plot( 0:1, 0:1, xlim=rg, ylim=dif.rg, type="n", xlab="", ylab="", axes=FALSE ) pnu( pldat[,ir], pldat[,ic], ... ) if( plot.names ) { text( rg[1], dif.rg[2], paste(var.names[ic],"-",var.names[ir]), adj=c(0,1) ) text( rg[2], dif.rg[1], paste("(",var.names[ic],"+",var.names[ir],")/2"), adj=c(1,0) ) } if( ir == nvar ) axis( side=1 ) if( ic == 1 ) axis( side=2 ) if( ir == 1 ) axis( side=3 ) if( ic == nvar ) axis( side=4 ) box() } if( ir > ic ) { plot( 0:1, 0:1, xlim=rg, ylim=rg, type="n", xlab="", ylab="", axes=FALSE ) pnl( pldat[,ic], pldat[,ir], ... ) if( plot.names ) { text( rg[1], rg[2], var.names[ir], adj=c(0,1) ) text( rg[2], rg[1], var.names[ic], adj=c(1,0) ) } if( ir == nvar ) axis( side=1 ) if( ic == 1 ) axis( side=2 ) if( ir == 1 ) axis( side=3 ) if( ic == nvar ) axis( side=4 ) box() } } }
library("freqdom") library(pcdpca) RES = c() for (run in 1:100){ d = 7 n = 100 A = t(t(matrix(rnorm(d*n),ncol=d,nrow=n))) B = t(t(matrix(rnorm(d*n),ncol=d,nrow=n))) A = t(t(A) * exp(-(1:d)/(d) )) B = t(t(B) * exp(-(1:d)/(d) )) ntotal = 3*n X = matrix(0,ncol=d,nrow=3*n) X[3*(1:n) - 1,] = A X[3*(1:n) - 2,] = B X[3*(1:n) ,] = 2*A - B train = 1:(ntotal/2) test = (1 + ntotal/2) : (ntotal) PR = prcomp(as.matrix(X[train,])) Y1 = as.matrix(X) %*% PR$rotation Y1[,-1] = 0 Xpca.est = Y1 %*% t(PR$rotation) XI.est = dpca(as.matrix(X[train,]),q=sqn,freq=pi*(-150:150/150),Ndpc = 1) Y.est = freqdom::filter.process(X, XI.est$filters ) Xdpca.est = freqdom::filter.process(Y.est, t(rev(XI.est$filters)) ) XI.est.pc = pcdpca(as.matrix(X[train,]),q=sqn,freq=pi*(-150:150/150),period=period) Y.est.pc = pcdpca.scores(X, XI.est.pc) Y.est.pc[,-1] = 0 Xpcdpca.est = pcdpca.inverse(Y.est.pc, XI.est.pc) r0 = MSE(X[test,],Xpca.est[test,]) / MSE(X[test,],0) r1 = MSE(X[test,],Xdpca.est[test,]) / MSE(X[test,],0) r2 = MSE(X[test,],Xpcdpca.est[test,]) / MSE(X[test,],0) row = c(r0,r1,r2) print(row) RES = rbind(RES,row) } colnames(RES) = c("PCA","DPCA","PC-DPCA") df1 = data.frame(RES,row.names = NULL) colMeans(df1) summary(df1) apply(df1, 2, sd) t.test(df1$DPCA - df1$PC.DPCA) par(mfrow=c(1,1),ps = 12, cex = 1.8, cex.main = 1.8) boxplot(df1, main="Simulation study 1", ylab="Normalized mean squared error",ylim=c(0.25,0.9))
init.theta.MSAR.VM <- function(data,...,M,order,regime_names=NULL,nh.emissions=NULL,nh.transitions=NULL,label=NULL,ncov.emis = 0,ncov.trans=0 ) { if (missing(M) || is.null(M) || M==0) {print("Need at least one regime : M=1"); M <- 1 } if (missing(order)) { order <- 0 } if (missing(label)) {label = 'HH'} d = dim(data)[3] if (is.null(d) ) {d=1} else if ( is.na(d)) {d=1} if (length(dim(data))<3) {d = 1} else {d = dim(data)[3]} mu <- matrix(6*runif(M*d),M,d) ; kappa = matrix(1+2*runif(M*(order+1)),M,order+1) if (M>1) { prior <- normalise(runif(M)) transmat <- mk_stochastic(diag(1,M)+matrix(runif(M*M),M)) } else { prior = 1 transmat = 1 } prior=matrix(prior,M,1) transmat=matrix(transmat,M,M) n_par=order*M+M+M^2 emis.linear = FALSE if (substr(label,2,2)=="N") { par.emis <- list() if (missing(nh.emissions)) {nh.emissions = 'linear'} if (!is.function(nh.emissions)){ if (nh.emissions == 'linear') { emis.linear = TRUE if (ncov.emis<1) {ncov.emis=1} nh.emissions <- function(covar,par.emis){ d <- dim(par.emis)[1] if(is.null(d) || is.na(d)){d <- 1} f <- matrix(0,d,dim(covar)[1]) for(i in 1:d){ f[i,] <- par.emis[i,1:dim(par.emis)[2]]%*%t(covar) } return(f) } } } for(i in 1:M){ par.emis[[i]] <- matrix(0,d,ncov.emis) } n_par <- n_par+ncov.emis } if (substr(label,1,1)=="N") { par.trans <- array(1,c(M,max(2,ncov.trans+1))) if (missing(nh.transitions)) { nh.transition = 'VM'} if (!is.function(nh.transitions)){ if (nh.transitions=='VM') { nh.transitions <- function(covar,par.trans,transmat){ T <- dim(covar)[1] N.samples = dim(covar)[2] ncov = dim(covar)[3] M = dim(transmat)[1] par.trans = repmat(t(par.trans[,2])*exp(1i*par.trans[,1]),M,1)%*%(matrix(1,M,M)-diag(1,nrow=M)) f <- array(0,c(M,M,T)) for (j in 1:M) { for (i in 1:M) { f[i,j,] = transmat[i,j]*abs(exp(par.trans[i,j]*exp(-1i*covar))) ; } } f.sum = apply(f , c(1,3), sum) for (i in 1:M) {f[i,,] = f[i,,]/t(matrix(f.sum[i,],T,M))} return(f) } } else if (nh.transitions=='gauss') { nh.transitions <- function(covar,par.trans,transmat){ T <- dim(covar)[1] N.samples = dim(covar)[2] ncov = dim(covar)[3] M = dim(transmat)[1] f <- array(0,c(M,M,T)) for (j in 1:M) { xx = (covar-array(par.trans[j,1:ncov],c(T,N.samples,ncov)))^2 sxx = apply(xx,1,sum) temp=exp( -sxx/par.trans[j,ncov+1]^2/2) for (i in 1:M) { f[i,j,] = transmat[i,j]*temp ; } } f.sum = apply(f , c(1,3), sum) for (i in 1:M) {f[i,,] = f[i,,]/t(matrix(f.sum[i,],T,M))} return(f) } } else if (nh.transitions=='logistic') { nh.transitions <- function(covar,par.trans,transmat){ eps = 1e-10 T <- dim(covar)[1] nc <- dim(covar)[3] covar = matrix(covar,T,nc) M = dim(transmat)[1] f <- array(0,c(M,M,T)) for (m in 1:M) { f[m,m,] = eps+(1-2*eps)/(1 + exp(par.trans[m,1] + par.trans[m,2:(nc+1)] %*% t(covar))) } f[1,2,] = 1-f[1,1,] f[2,1,] = 1-f[2,2,] return(f) } }} n_par <- n_par+max(2,ncov.trans+1) } if (label=='HH'){theta=list(mu,kappa,prior,transmat)} if (label=='HN'){theta=list(mu,kappa,prior,transmat,par.emis)} if (label=='NH'){theta=list(mu,kappa,prior,transmat,par.trans)} if (label=='NN'){theta=list(mu,kappa,prior,transmat,par.trans,par.emis)} attr(theta,'NbComp') <- d attr(theta,'NbRegimes') <- M attr(theta,'order') <- order attr(theta,'label') <- label attr(theta,'nh.emissions') <- nh.emissions attr(theta,'nh.transitions') <- nh.transitions attr(theta,'n_par') <- n_par attr(theta,'emis.linear') <- emis.linear theta=as.thetaMSAR.VM(theta,label=label,ncov.emis=ncov.emis,ncov.trans=ncov.trans) class(theta) <- "MSAR.VM" return(theta) }
context("`select_best()` and `show_best()`") rcv_results <- readRDS(test_path("rcv_results.rds")) knn_results <- readRDS(test_path("knn_results.rds")) source(test_path("../helper-objects.R")) test_that("select_best()", { expect_true( tibble::is_tibble(select_best(rcv_results, metric = "rmse")) ) best_rmse <- tibble::tribble( ~deg_free, ~degree, ~`wt df`, ~`wt degree`, 6L, 2L, 2L, 1L ) best_rsq <- tibble::tribble( ~deg_free, ~degree, ~`wt df`, ~`wt degree`, 10L, 2L, 2L, 2L ) expect_equal( select_best(rcv_results, metric = "rmse") %>% select(-.config), best_rmse ) expect_equal( select_best(rcv_results, metric = "rsq") %>% select(-.config), best_rsq ) expect_warning( select_best(rcv_results, metric = "rsq", maximize = TRUE), "The `maximize` argument is no longer" ) expect_error( select_best(rcv_results, metric = "random"), "Please check the value of `metric`" ) expect_error( select_best(rcv_results, metric = c("rmse", "rsq")), "Please specify a single character" ) expect_warning( expect_equal( select_best(rcv_results), select_best(rcv_results, metric = "rmse") ), "metric 'rmse' will be used" ) }) test_that("show_best()", { rcv_rmse <- rcv_results %>% collect_metrics() %>% dplyr::filter(.metric == "rmse") %>% dplyr::arrange(mean) expect_equal( show_best(rcv_results, metric = "rmse", n = 1), rcv_rmse %>% slice(1) ) expect_equal( show_best(rcv_results, metric = "rmse", n = nrow(rcv_rmse) + 1), rcv_rmse ) expect_equal( show_best(rcv_results, metric = "rmse", n = 1) %>% names(), rcv_rmse %>% names() ) expect_warning( expect_equal( show_best(rcv_results), show_best(rcv_results, metric = "rmse") ), "metric 'rmse' will be used" ) }) test_that("one-std error rule", { expect_true( tibble::is_tibble(select_by_one_std_err(knn_results, metric = "accuracy", K)) ) expect_equal( select_by_one_std_err(rcv_results, metric = "rmse", deg_free, `wt degree`)$mean, 2.94252798698909 ) expect_equal( select_by_one_std_err(knn_results, metric = "accuracy", K)$K, 25L ) expect_warning( select_by_one_std_err(knn_results, metric = "accuracy", K, maximize = TRUE), "The `maximize` argument is no longer" ) expect_error( select_by_one_std_err(rcv_results, metric = "random", deg_free), "Please check the value of `metric`" ) expect_error( select_by_one_std_err(rcv_results, metric = c("rmse", "rsq"), deg_free), "Please specify a single character" ) expect_warning( expect_equal( select_by_one_std_err(knn_results, K), select_by_one_std_err(knn_results, K, metric = "roc_auc") ), "metric 'roc_auc' will be used" ) expect_error( select_by_one_std_err(rcv_results, metric = "random"), "Please choose at least one tuning parameter to sort" ) }) test_that("percent loss", { expect_true( tibble::is_tibble(select_by_pct_loss(knn_results, metric = "accuracy", K)) ) expect_equal( select_by_pct_loss(rcv_results, metric = "rmse", deg_free, `wt degree`)$mean, 2.94252798698909 ) expect_equal( select_by_pct_loss(knn_results, metric = "accuracy", K)$K, 12L ) expect_warning( select_by_pct_loss(knn_results, metric = "accuracy", K, maximize = TRUE), "The `maximize` argument is no longer" ) expect_error( select_by_pct_loss(rcv_results, metric = "random", deg_free), "Please check the value of `metric`" ) expect_error( select_by_pct_loss(rcv_results, metric = c("rmse", "rsq"), deg_free), "Please specify a single character" ) expect_warning( expect_equal( select_by_pct_loss(knn_results, K), select_by_pct_loss(knn_results, K, metric = "roc_auc") ), "metric 'roc_auc' will be used" ) expect_error( select_by_pct_loss(rcv_results, metric = "random"), "Please choose at least one tuning parameter to sort" ) })
expected <- eval(parse(text="c(FALSE, FALSE)")); test(id=0, code={ argv <- eval(parse(text="list(structure(list(1L, 3L), class = structure(\"L\", package = \".GlobalEnv\")))")); do.call(`is.na`, argv); }, o=expected);
`codominant.snp` <- function(o) { o<-codominant.default(o) class(o)<-c("snp","factor") o }
test_that("tx_ml subsets only inactive clients within a period", { expect_identical( tx_ml( new_data = ndr_example, from = lubridate::ymd("2020-10-01"), to = lubridate::ymd("2021-01-31") ), ndr_example %>% dplyr::filter(dplyr::between( date_lost, lubridate::as_date("2020-10-01"), lubridate::as_date("2021-01-31") )) ) })
setSeasonLabel<-function(localAnnualResults){ paStart <- localAnnualResults$PeriodStart[1] paLong <- localAnnualResults$PeriodLong[1] index <- seq(paStart, paStart + paLong - 1) index <- ifelse(index > 12, index - 12, index) monthList <- sapply(index[1:paLong], function(x) { monthInfo[[x]]@monthAbbrev }) monthList <- paste(monthList, collapse = " ") temp1 <- c("Year Starting With", monthInfo[[paStart]]@monthFull) temp1 <- paste(temp1, collapse = " ") temp2 <- "Water Year" temp3 <- "Calendar Year" temp4 <- c("Season Consisting of", monthList) temp4 <- paste(temp4, collapse = " ") periodName <- temp4 periodName<-if(paLong==12) temp1 else periodName periodName<-if(paLong==12 & paStart==10) temp2 else periodName periodName<-if(paLong==12 & paStart==1) temp3 else periodName return(periodName) }
histGroup <- function(data,groups, main=paste("Histogram of" , dataname),xlab=dataname,ylab,col=NULL, alpha=0.5,breaks="Sturges",legend=TRUE,legend.x=80,legend.y=80,legend.pch=15,freq=TRUE) { out <- list() dataname <- paste(deparse(substitute(data), 500), collapse="\n") histo <- hist(data,plot=FALSE,breaks=breaks) if(!is.factor(groups)) { groups <- as.factor(groups) } lev <- levels(groups) nlev <- length(lev) if (is.null(col)) colo <- rainbow(nlev,alpha=alpha) else { if (length(col) != nlev) stop("length of 'col' must match number of groups") else if (is.character(col)) colo <- col else { rgbfun <- function(x) { alpha <- alpha*255 x <- rgb(x[1],x[2],x[3],maxColorValue = 255,alpha=alpha) return(x) } colo <- apply(col2rgb(col),2,rgbfun) } } testrun <- 0 for( i in 1:nlev) {if(freq) testrun[i] <- max(hist(data[groups==lev[i]],breaks=histo$breaks,plot=F)$counts) else testrun[i] <- max(hist(data[groups==lev[i]],breaks=histo$breaks,plot=F)$density) } ylim <- max(testrun) ylim <- ylim+0.15*ylim out[[1]] <- hist(data[groups==lev[1]],breaks=histo$breaks,col=colo[1],main=main,xlab=xlab,ylab=ylab,ylim=c(0,ylim),freq=freq) for (i in 2:nlev) { out[[i]] <- hist(data[groups==lev[i]],breaks=histo$breaks,col=colo[i],add=T,freq=freq) } if (legend) { tmp <- 0 tmp[1] <- grconvertX(legend.x, 'device') tmp[2] <- grconvertY(legend.y, 'device') legend(tmp[1],tmp[2],pch=legend.pch,col=colo,legend=lev,cex=1) } invisible(out) }
predictMA <- function(object, new.data){ z <- object c <- z$candidatmodels w <- z$optimresults$weights pmodels <- sapply(z$candidatmodels, predict, newdata = new.data) MApredict <- w%*%t(sapply(c, predict, newdata = new.data)) res <- list(prediction = MApredict, weights = w) return(res) }
library(sarima) context("Fitting Sarima models with estimated unit roots") test_that("Sarima and Arma models work ok", { expect_true(TRUE) sarima(log(AirPassengers) ~ 0 | ma(1, c(-0.3)) + sma(12,1, c(-0.1)) + i(1) + si(12,1), ss.method = "sarima") sarima(log(AirPassengers) ~ 0 | ma(1, c(-0.3)) + sma(12,1, c(-0.1)) + uar(13, c(rep(0,12), 1), fixed = 13, atanh.tr = TRUE), ss.method = "sarima") sarima(log(AirPassengers) ~ 0 | ma(1, c(-0.3)) + sma(12,1, c(-0.1)) + i(2) + uar(11, c(rep(0,10), 1), fixed = 11), ss.method = "sarima") })
segment.outside<-function(img,blobsize=1) { nimg<-img/max(img) dims<-dim(img) thresh<-c() XX<-dims[1] YY<-dims[1] ZZ<-dims[1] for (i in 1:5) { try({ Y<-round(dims[2]*stats::runif(1,.4,.6),0) Z<-round(dims[3]*stats::runif(1,.4,.6),0) m<-mean(nimg[1:3,Y,Z]) s<-stats::sd(nimg[1:3,Y,Z]) X<-4 while(((m+3*s)>nimg[X,Y,Z])|(s<1e-4)) { m<-mean(nimg[1:X,Y,Z]) s<-stats::sd(nimg[1:X,Y,Z]) X<-X+1 } thresh<-c(thresh,nimg[X+1,Y,Z]) }) try({ Y<-round(dims[2]*stats::runif(1,.4,.6),0) Z<-round(dims[3]*stats::runif(1,.4,.6),0) m<-mean(nimg[XX-(0:2),Y,Z]) s<-stats::sd(nimg[XX-(0:2),Y,Z]) X<-3 while(((m+3*s)>nimg[XX-X,Y,Z])|(s<1e-4)) { m<-mean(nimg[XX-(0:X),Y,Z]) s<-stats::sd(nimg[XX-(0:X),Y,Z]) X<-X+1 } thresh<-c(thresh,nimg[XX-X-1,Y,Z]) }) try({ X<-round(dims[1]*stats::runif(1,.4,.6),0) Z<-round(dims[3]*stats::runif(1,.4,.6),0) m<-mean(nimg[X,1:3,Z]) s<-stats::sd(nimg[X,1:3,Z]) Y<-4 while(((m+3*s)>nimg[X,Y,Z])|(s<1e-4)) { m<-mean(nimg[X,1:Y,Z]) s<-stats::sd(nimg[X,1:Y,Z]) Y<-Y+1 } thresh<-c(thresh,nimg[X,Y+1,Z]) }) try({ X<-round(dims[1]*stats::runif(1,.4,.6),0) Z<-round(dims[3]*stats::runif(1,.4,.6),0) m<-mean(nimg[X,YY-(0:2),Z]) s<-stats::sd(nimg[X,YY-(0:2),Z]) Y<-3 while(((m+3*s)>nimg[X,YY-Y,Z])|(s<1e-4)) { m<-mean(nimg[X,YY-(0:Y),Z]) s<-stats::sd(nimg[X,YY-(0:Y),Z]) Y<-Y+1 } thresh<-c(thresh,nimg[X,YY-Y-1,Z]) }) } thresh<-stats::quantile(thresh,.1) cat(paste("Threshold is ",round(thresh*100,1),"%\n",sep="")) nimg<-array(ifelse(nimg<thresh,0,1),dims) cat("Starting Segmentation.\n") return(outside(nimg,0,blobsize)) }
context("coord_matrix") test_that("guess_loncol/guess_latcol work as expected", { coord_cols <- c("lon", "lat") x <- matrix(c(1, 2, 3, 4, 5, 6), ncol = 2) expect_identical(guess_loncol(x), 1L) expect_identical(guess_latcol(x), 2L) colnames(x) <- c("lat", "longitude") expect_identical(guess_loncol(x), 2L) expect_identical(guess_latcol(x), 1L) colnames(x) <- c("lon", "long") expect_warning(guess_loncol(x), class = "multipleCandidateColumnsFoundWarning") expect_error(guess_latcol(x), class = "cannotGuessColumnError") colnames(x) <- c("lat", "lon") expect_identical(guess_loncol(as.data.frame(x)), 2L) expect_identical(guess_latcol(as.data.frame(x)), 1L) }) test_that("as_coord_matrix.numeric works as expected", { expect_identical( as_coord_matrix(c(16.422524, 48.185686)), as_coord_matrix(c(lon = 16.422524, lat = 48.185686)) ) expect_identical( as_coord_matrix(c(16.422524, 48.185686)), as_coord_matrix(c(LAT = 48.185686, LoNgItuDE = 16.422524)) ) }) test_that("as_coord_matrix.data.frame works as expected", { x <- matrix(c(1, 2, 3, 4, 5, 6), ncol = 2) y <- as.data.frame(x) expect_error(as_coord_matrix(y), class = "cannotGuessColumnError") colnames(x) <- c("lon", "lat") colnames(y) <- c("lat", "lon") y <- as_coord_matrix(y) expect_identical(colnames(y), c("lon", "lat")) expect_identical(x[, "lat"], y[, "lon"]) expect_identical(x[, "lon"], y[, "lat"]) expect_identical(colnames(x), colnames(y)) }) test_that("as_coord_matrix.default fails nicely on unspported objects", { expect_error(as_coord_matrix("blubb"), class = "objectNotSupportedError") })
.fit.param.fj.endcensoring <- function(counting, s, kmax, distr, cens.beg) { theta0 <- matrix(data = NA, nrow = 2, ncol = s) for (j in 1:s) { if (distr[j] == "dweibull") { theta0[, j] <- .fit.param.fj.dweibull(counting, j, kmax, cens.beg = FALSE) } else if (distr[j] == "geom") { theta0[, j] <- .fit.param.fj.geom(counting, j, kmax, cens.beg = FALSE) } else if (distr[j] == "nbinom") { theta0[, j] <- .fit.param.fj.nbinom(counting, j, kmax, cens.beg = FALSE) } else if (distr[j] == "pois") { theta0[, j] <- .fit.param.fj.pois(counting, j, kmax, cens.beg = FALSE) } } theta0 <- as.vector(theta0[!(is.na(theta0))]) if (s == 2) { ptrans <- matrix(c(0, 1, 1, 0), nrow = s, byrow = TRUE) param <- matrix(data = NA, nrow = s, ncol = 2) if ((distr[1] == "unif") & (distr[2] == "unif")) { for (j in 1:s) { param[j, ] <- .fit.param.fj.unif(counting, j, kmax) } } else if ("unif" %in% distr) { for (j in 1:s) { if (distr[j] == "unif") { param[j, ] <- .fit.param.fj.unif(counting, j, kmax) } else { if (cens.beg) { loglik <- function(par) { fv <- matrix(data = 0, nrow = s, ncol = kmax) Fv <- matrix(data = 0, nrow = s, ncol = kmax) skipindex <- 1 for (j in 1:s) { maskNjk <- counting$Njk[j, ] != 0 maskNeNb <- (counting$Nbjk[j, ] + counting$Neik[abs(j - 3), ]) != 0 if (distr[j] == "dweibull") { fv[j, maskNjk] <- log(ddweibull(x = (1:kmax)[maskNjk], q = par[skipindex], beta = par[skipindex + 1], zero = FALSE)) Fv[j, maskNeNb] <- log(1 - pdweibull(x = (1:kmax)[maskNeNb], q = par[skipindex], beta = par[skipindex + 1], zero = FALSE) + .Machine$double.xmin) skipindex <- skipindex + 2 } else if (distr[j] == "geom") { fv[j, maskNjk] <- dgeom(x = (0:(kmax - 1))[maskNjk], prob = par[skipindex], log = TRUE) Fv[j, maskNeNb] <- pgeom(q = (0:(kmax - 1))[maskNeNb], prob = par[skipindex], lower.tail = FALSE, log.p = TRUE) skipindex <- skipindex + 1 } else if (distr[j] == "nbinom") { fv[j, maskNjk] <- dnbinom(x = (0:(kmax - 1))[maskNjk], size = par[skipindex], prob = par[skipindex + 1], log = TRUE) Fv[j, maskNeNb] <- pnbinom(q = (0:(kmax - 1))[maskNeNb], size = par[skipindex], prob = par[skipindex + 1], lower.tail = FALSE, log.p = TRUE) skipindex <- skipindex + 2 } else if (distr[j] == "pois") { fv[j, maskNjk] <- dpois(x = (0:(kmax - 1))[maskNjk], lambda = par[skipindex], log = TRUE) Fv[j, maskNeNb] <- ppois(q = (0:(kmax - 1))[maskNeNb], lambda = par[skipindex], lower.tail = FALSE, log.p = TRUE) skipindex <- skipindex + 1 } } return( -(sum(counting$Njk[1, ] * fv[1, ]) + sum(counting$Njk[2, ] * fv[2, ]) + sum((counting$Nbjk[1, ] + counting$Neik[2, ]) * Fv[1, ]) + sum((counting$Nbjk[2, ] + counting$Neik[1, ]) * Fv[2, ])) ) } } else { loglik <- function(par) { fv <- matrix(data = 0, nrow = s, ncol = kmax) Fv <- matrix(data = 0, nrow = s, ncol = kmax) skipindex <- 1 for (j in 1:s) { maskNjk <- counting$Njk[j, ] != 0 maskNeik <- counting$Neik[abs(j - 3), ] != 0 if (distr[j] == "dweibull") { fv[j, maskNjk] <- log(ddweibull(x = (1:kmax)[maskNjk], q = par[skipindex], beta = par[skipindex + 1], zero = FALSE)) Fv[j, maskNeik] <- log(1 - pdweibull(x = (1:kmax)[maskNeik], q = par[skipindex], beta = par[skipindex + 1], zero = FALSE) + .Machine$double.xmin) skipindex <- skipindex + 2 } else if (distr[j] == "geom") { fv[j, maskNjk] <- dgeom(x = (0:(kmax - 1))[maskNjk], prob = par[skipindex], log = TRUE) Fv[j, maskNeik] <- pgeom(q = (0:(kmax - 1))[maskNeik], prob = par[skipindex], lower.tail = FALSE, log.p = TRUE) skipindex <- skipindex + 1 } else if (distr[j] == "nbinom") { fv[j, maskNjk] <- dnbinom(x = (0:(kmax - 1))[maskNjk], size = par[skipindex], prob = par[skipindex + 1], log = TRUE) Fv[j, maskNeik] <- pnbinom(q = (0:(kmax - 1))[maskNeik], size = par[skipindex], prob = par[skipindex + 1], lower.tail = FALSE, log.p = TRUE) skipindex <- skipindex + 2 } else if (distr[j] == "pois") { fv[j, maskNjk] <- dpois(x = (0:(kmax - 1))[maskNjk], lambda = par[skipindex], log = TRUE) Fv[j, maskNeik] <- ppois(q = (0:(kmax - 1))[maskNeik], lambda = par[skipindex], lower.tail = FALSE, log.p = TRUE) skipindex <- skipindex + 1 } } return( -(sum(counting$Njk[1, ] * fv[1, ]) + sum(counting$Njk[2, ] * fv[2, ]) + sum(counting$Neik[1, ] * Fv[2, ]) + sum(counting$Neik[2, ] * Fv[1, ])) ) } } if (distr[j] == "dweibull") { u0 <- diag(x = 1, nrow = 2) c0 <- c(0, 0) u1 <- matrix(data = c(-1, 0), nrow = 1, ncol = 2) c1 <- c(-1) mle <- constrOptim( theta = theta0, f = loglik, ui = rbind(u0, u1), ci = c(c0, c1), method = "Nelder-Mead" ) param[j, ] <- mle$par } else if (distr[j] == "geom") { mle <- optim(par = theta0, loglik, method = "Brent", lower = 0, upper = 1) param[j, ] <- mle$par } else if (distr[j] == "nbinom") { u0 <- diag(x = 1, nrow = 2) c0 <- c(0, 0) u1 <- matrix(data = c(0, -1), nrow = 1, ncol = 2) c1 <- c(-1) mle <- constrOptim( theta = theta0, f = loglik, ui = rbind(u0, u1), ci = c(c0, c1), method = "Nelder-Mead" ) param[j, ] <- mle$par } else if (distr[j] == "pois") { mle <- optim(par = theta0, loglik, method = "Brent", lower = 0, upper = kmax - 1) param[j, ] <- mle$par } } } } else { if (cens.beg) { loglik <- function(par) { fv <- matrix(data = 0, nrow = s, ncol = kmax) Fv <- matrix(data = 0, nrow = s, ncol = kmax) skipindex <- 1 for (j in 1:s) { maskNjk <- counting$Njk[j, ] != 0 maskNeNb <- (counting$Nbjk[j, ] + counting$Neik[abs(j - 3), ]) != 0 if (distr[j] == "dweibull") { fv[j, maskNjk] <- log(ddweibull(x = (1:kmax)[maskNjk], q = par[skipindex], beta = par[skipindex + 1], zero = FALSE)) Fv[j, maskNeNb] <- log(1 - pdweibull(x = (1:kmax)[maskNeNb], q = par[skipindex], beta = par[skipindex + 1], zero = FALSE) + .Machine$double.xmin) skipindex <- skipindex + 2 } else if (distr[j] == "geom") { fv[j, maskNjk] <- dgeom(x = (0:(kmax - 1))[maskNjk], prob = par[skipindex], log = TRUE) Fv[j, maskNeNb] <- pgeom(q = (0:(kmax - 1))[maskNeNb], prob = par[skipindex], lower.tail = FALSE, log.p = TRUE) skipindex <- skipindex + 1 } else if (distr[j] == "nbinom") { fv[j, maskNjk] <- dnbinom(x = (0:(kmax - 1))[maskNjk], size = par[skipindex], prob = par[skipindex + 1], log = TRUE) Fv[j, maskNeNb] <- pnbinom(q = (0:(kmax - 1))[maskNeNb], size = par[skipindex], prob = par[skipindex + 1], lower.tail = FALSE, log.p = TRUE) skipindex <- skipindex + 2 } else if (distr[j] == "pois") { fv[j, maskNjk] <- dpois(x = (0:(kmax - 1))[maskNjk], lambda = par[skipindex], log = TRUE) Fv[j, maskNeNb] <- ppois(q = (0:(kmax - 1))[maskNeNb], lambda = par[skipindex], lower.tail = FALSE, log.p = TRUE) skipindex <- skipindex + 1 } } return( -(sum(counting$Njk[1, ] * fv[1, ]) + sum(counting$Njk[2, ] * fv[2, ]) + sum((counting$Nbjk[1, ] + counting$Neik[2, ]) * Fv[1, ]) + sum((counting$Nbjk[2, ] + counting$Neik[1, ]) * Fv[2, ]) ) ) } } else { loglik <- function(par) { fv <- matrix(data = 0, nrow = s, ncol = kmax) Fv <- matrix(data = 0, nrow = s, ncol = kmax) skipindex <- 1 for (j in 1:s) { maskNjk <- counting$Njk[j, ] != 0 maskNeik <- counting$Neik[abs(j - 3), ] != 0 if (distr[j] == "dweibull") { fv[j, maskNjk] <- log(ddweibull(x = (1:kmax)[maskNjk], q = par[skipindex], beta = par[skipindex + 1], zero = FALSE)) Fv[j, maskNeik] <- log(1 - pdweibull(x = (1:kmax)[maskNeik], q = par[skipindex], beta = par[skipindex + 1], zero = FALSE) + .Machine$double.xmin) skipindex <- skipindex + 2 } else if (distr[j] == "geom") { fv[j, maskNjk] <- dgeom(x = (0:(kmax - 1))[maskNjk], prob = par[skipindex], log = TRUE) Fv[j, maskNeik] <- pgeom(q = (0:(kmax - 1))[maskNeik], prob = par[skipindex], lower.tail = FALSE, log.p = TRUE) skipindex <- skipindex + 1 } else if (distr[j] == "nbinom") { fv[j, maskNjk] <- dnbinom(x = (0:(kmax - 1))[maskNjk], size = par[skipindex], prob = par[skipindex + 1], log = TRUE) Fv[j, maskNeik] <- pnbinom(q = (0:(kmax - 1))[maskNeik], size = par[skipindex], prob = par[skipindex + 1], lower.tail = FALSE, log.p = TRUE) skipindex <- skipindex + 2 } else if (distr[j] == "pois") { fv[j, maskNjk] <- dpois(x = (0:(kmax - 1))[maskNjk], lambda = par[skipindex], log = TRUE) Fv[j, maskNeik] <- ppois(q = (0:(kmax - 1))[maskNeik], lambda = par[skipindex], lower.tail = FALSE, log.p = TRUE) skipindex <- skipindex + 1 } } return( -(sum(counting$Njk[1, ] * fv[1, ]) + sum(counting$Njk[2, ] * fv[2, ]) + sum(counting$Neik[1, ] * Fv[2, ]) + sum(counting$Neik[2, ] * Fv[1, ])) ) } } u0 <- diag(x = 1, nrow = length(theta0), ncol = length(theta0)) c0 <- rep(0, length(theta0)) u1 <- matrix(0, nrow = length(theta0), ncol = length(theta0)) skipindex <- 1 rowstoremove <- c() for (j in 1:s) { if (distr[j] == "dweibull") { u1[skipindex, skipindex] <- -1 rowstoremove <- c(rowstoremove, skipindex + 1) skipindex <- skipindex + 2 } else if (distr[j] == "geom") { u1[skipindex, skipindex] <- -1 skipindex <- skipindex + 1 } else if (distr[j] == "nbinom") { u1[skipindex + 1, skipindex + 1] <- -1 rowstoremove <- c(rowstoremove, skipindex) skipindex <- skipindex + 2 } else if (distr[j] == "pois") { rowstoremove <- c(rowstoremove, skipindex) skipindex <- skipindex + 1 } } if (!is.null(rowstoremove)) { u1 <- u1[-rowstoremove, ] } if (!is.null(nrow(u1))) { c1 <- rep(-1, nrow(u1)) } else { c1 <- c(-1) } if (length(u1) != 0) { u2 <- rbind(u0, u1) c2 <- c(c0, c1) } else { u2 <- u0 c2 <- c0 } mle <- constrOptim( theta = theta0, f = loglik, ui = u2, ci = c2, method = "Nelder-Mead" ) skipindex <- 1 for (j in 1:s) { if (distr[j] %in% c("dweibull", "nbinom")) { param[j, ] <- mle$par[skipindex:(skipindex + 1)] skipindex <- skipindex + 2 } else if (distr[j] %in% c("geom", "pois")) { param[j, 1] <- mle$par[skipindex] skipindex <- skipindex + 1 } else if (distr[j] == "unif") { param[j, ] <- .fit.param.fj.unif(counting, j, kmax) } } } } else { if (cens.beg) { loglik <- function(par) { parpuv <- matrix(par[1:(s * (s - 2))], nrow = s, ncol = s - 2, byrow = T) parpuv <- cbind(parpuv, 1 - apply(parpuv, 1, sum)) parp <- matrix(data = 0, nrow = s, ncol = s) parp[row(parp) != col(parp)] <- t(parpuv) parp <- t(parp) fv <- matrix(data = 0, nrow = s, ncol = kmax) Fv <- matrix(data = 0, nrow = s, ncol = kmax) Fv2 <- matrix(data = 0, nrow = s, ncol = kmax) skipindex <- s * (s - 2) + 1 for (j in 1:s) { maskNjk <- counting$Njk[j, ] != 0 maskNbjk <- counting$Nbjk[j, ] != 0 if (distr[j] == "dweibull") { fv[j, maskNjk] <- log(ddweibull(x = (1:kmax)[maskNjk], q = par[skipindex], beta = par[skipindex + 1], zero = FALSE)) Fv[j, maskNbjk] <- log(1 - pdweibull(x = (1:kmax)[maskNbjk], q = par[skipindex], beta = par[skipindex + 1], zero = FALSE) + .Machine$double.xmin) Fv2[j, ] <- 1 - pdweibull(x = (1:kmax), q = par[skipindex], beta = par[skipindex + 1], zero = FALSE) skipindex <- skipindex + 2 } else if (distr[j] == "geom") { fv[j, maskNjk] <- dgeom(x = (0:(kmax - 1))[maskNjk], prob = par[skipindex], log = TRUE) Fv[j, maskNbjk] <- pgeom(q = (0:(kmax - 1))[maskNbjk], prob = par[skipindex], lower.tail = FALSE, log.p = TRUE) Fv2[j, ] <- pgeom(q = 0:(kmax - 1), prob = par[skipindex], lower.tail = FALSE) skipindex <- skipindex + 1 } else if (distr[j] == "nbinom") { fv[j, maskNjk] <- dnbinom(x = (0:(kmax - 1))[maskNjk], size = par[skipindex], prob = par[skipindex + 1], log = TRUE) Fv[j, maskNbjk] <- pnbinom(q = (0:(kmax - 1))[maskNbjk], size = par[skipindex], prob = par[skipindex + 1], lower.tail = FALSE, log.p = TRUE) Fv2[j, ] <- pnbinom(q = 0:(kmax - 1), size = par[skipindex], prob = par[skipindex + 1], lower.tail = FALSE) skipindex <- skipindex + 2 } else if (distr[j] == "pois") { fv[j, maskNjk] <- dpois(x = (0:(kmax - 1))[maskNjk], lambda = par[skipindex], log = TRUE) Fv[j, maskNbjk] <- ppois(q = (0:(kmax - 1))[maskNbjk], lambda = par[skipindex], lower.tail = FALSE, log.p = TRUE) Fv2[j, ] <- ppois(q = 0:(kmax - 1), lambda = par[skipindex], lower.tail = FALSE) skipindex <- skipindex + 1 } } Fv2 <- parp %*% Fv2 Fv2[Fv2 != 0] <- log(Fv2[Fv2 != 0]) return(-( sum(counting$Nij[row(counting$Nij) != col(counting$Nij)] * log(parp[row(parp) != col(parp)])) + sum(counting$Njk * fv) + sum(counting$Nbjk * Fv) + sum(counting$Neik * Fv2) )) } } else { loglik <- function(par) { parpuv <- matrix(par[1:(s * (s - 2))], nrow = s, ncol = s - 2, byrow = T) parpuv <- cbind(parpuv, 1 - apply(parpuv, 1, sum)) parp <- matrix(data = 0, nrow = s, ncol = s) parp[row(parp) != col(parp)] <- t(parpuv) parp <- t(parp) fv <- matrix(data = 0, nrow = s, ncol = kmax) Fv2 <- matrix(data = 0, nrow = s, ncol = kmax) skipindex <- s * (s - 2) + 1 for (j in 1:s) { maskNjk <- counting$Njk[j, ] != 0 if (distr[j] == "dweibull") { fv[j, maskNjk] <- log(ddweibull(x = (1:kmax)[maskNjk], q = par[skipindex], beta = par[skipindex + 1], zero = FALSE)) Fv2[j, ] <- 1 - pdweibull(x = 1:kmax, q = par[skipindex], beta = par[skipindex + 1], zero = FALSE) skipindex <- skipindex + 2 } else if (distr[j] == "geom") { fv[j, maskNjk] <- dgeom(x = (0:(kmax - 1))[maskNjk], prob = par[skipindex], log = TRUE) Fv2[j, ] <- pgeom(q = 0:(kmax - 1), prob = par[skipindex], lower.tail = FALSE) skipindex <- skipindex + 1 } else if (distr[j] == "nbinom") { fv[j, maskNjk] <- dnbinom(x = (0:(kmax - 1))[maskNjk], size = par[skipindex], prob = par[skipindex + 1], log = TRUE) Fv2[j, ] <- pnbinom(q = 0:(kmax - 1), size = par[skipindex], prob = par[skipindex + 1], lower.tail = FALSE) skipindex <- skipindex + 2 } else if (distr[j] == "pois") { fv[j, maskNjk] <- dpois(x = (0:(kmax - 1))[maskNjk], lambda = par[skipindex], log = TRUE) Fv2[j, ] <- ppois(q = 0:(kmax - 1), lambda = par[skipindex], lower.tail = FALSE) skipindex <- skipindex + 1 } } Fv2 <- parp %*% Fv2 Fv2[Fv2 != 0] <- log(Fv2[Fv2 != 0]) return(-( sum(counting$Nij[row(counting$Nij) != col(counting$Nij)] * log(parp[row(parp) != col(parp)])) + sum(counting$Njk * fv) + sum(counting$Neik * Fv2) )) } } u0 <- diag(x = 1, nrow = s * (s - 2) + length(theta0), ncol = s * (s - 2) + length(theta0)) c0 <- rep(0, s * (s - 2) + length(theta0)) u1 <- matrix(0, nrow = s * (s - 2), ncol = s * (s - 2) + length(theta0)) diag(u1) <- -1 c1 <- rep(-1, s * (s - 2)) u2 <- matrix(0, nrow = s, ncol = s * (s - 2) + length(theta0)) u2[1, 1:(s - 2)] <- -1 for (l in 1:(s - 1)) { u2[l + 1, (l * (s - 2) + 1):(l * (s - 2) + (s - 2))] <- -1 } c2 <- rep(-1, s) u3 <- matrix(0, nrow = length(theta0), ncol = s * (s - 2) + length(theta0)) skipindex <- 1 rowstoremove <- c() for (j in 1:s) { if (distr[j] == "dweibull") { u3[skipindex, skipindex + s * (s - 2)] <- -1 rowstoremove <- c(rowstoremove, skipindex + 1) skipindex <- skipindex + 2 } else if (distr[j] == "geom") { u3[skipindex, skipindex + s * (s - 2)] <- -1 skipindex <- skipindex + 1 } else if (distr[j] == "nbinom") { u3[skipindex + 1, skipindex + 1 + s * (s - 2)] <- -1 rowstoremove <- c(rowstoremove, skipindex) skipindex <- skipindex + 2 } else if (distr[j] == "pois") { rowstoremove <- c(rowstoremove, skipindex) skipindex <- skipindex + 1 } } if (!is.null(rowstoremove)) { u3 <- u3[-rowstoremove, ] } if (!is.null(nrow(u3))) { c3 <- rep(-1, nrow(u3)) } else { c3 <- c(-1) } if (length(u3) != 0) { u4 <- rbind(u0, u1, u2, u3) c4 <- c(c0, c1, c2, c3) } else { u4 <- rbind(u0, u1, u2) c4 <- c(c0, c1, c2) } mle <- constrOptim( theta = c(rep(1 / (s - 1), s * (s - 2)), theta0), f = loglik, ui = u4, ci = c4, method = "Nelder-Mead" ) parpuv <- matrix(mle$par[1:(s * (s - 2))], nrow = s, ncol = s - 2, byrow = T) parpuv <- cbind(parpuv, 1 - apply(parpuv, 1, sum)) ptrans <- matrix(data = 0, nrow = s, ncol = s) ptrans[row(ptrans) != col(ptrans)] <- t(parpuv) ptrans <- t(ptrans) param <- matrix(data = NA, nrow = s, ncol = 2) skipindex <- s * (s - 2) + 1 for (j in 1:s) { if (distr[j] %in% c("dweibull", "nbinom")) { param[j, ] <- mle$par[skipindex:(skipindex + 1)] skipindex <- skipindex + 2 } else if (distr[j] %in% c("geom", "pois")) { param[j, 1] <- mle$par[skipindex] skipindex <- skipindex + 1 } else if (distr[j] == "unif") { param[j, ] <- .fit.param.fj.unif(counting, j, kmax) } } } return(list(ptrans = ptrans, param = param)) }
as.edgelist <- function(x, ...){ UseMethod("as.edgelist") } as.edgelist.rankings <- function(x, ...){ x <- unclass(x) maxRank <- max(x) nm <- colnames(x) res <- list() for (i in seq_len(maxRank)){ res[[i]] <- list() for(j in seq_len(nrow(x))){ if (!is.null(nm)) { res[[i]][[j]] <- nm[which(x[j, ] == i)] } else res[[i]][[j]] <- which(x[j, ] == i) } } res <- unlist(res, recursive = FALSE) rep <- lengths(res) n <- nrow(x) m <- length(res) cbind(from = unlist(rep(res[seq(m - n)], rep[-seq(n)])), to = unlist(rep(res[-seq(n)], rep[seq(m - n)]))) }
library("httr") world <- "https://raw.githubusercontent.com/johan/world.geo.json/master/countries.geo.json" %>% GET() %>% content() %>% jsonlite::fromJSON(simplifyVector = FALSE) marine <- "http://cedeusdata.geosteiniger.cl/geoserver/wfs?srsName=EPSG%3A4326&typename=geonode%3Amundo_corrientes_maritimas&outputFormat=json&version=1.0.0&service=WFS&request=GetFeature" %>% GET() %>% content() plates <- "http://cedeusdata.geosteiniger.cl/geoserver/wfs?srsName=EPSG%3A4326&typename=geonode%3Amundo_limites_placas&outputFormat=json&version=1.0.0&service=WFS&request=GetFeature" %>% GET() %>% content() volcano <- "http://cedeusdata.geosteiniger.cl/geoserver/wfs?srsName=EPSG%3A4326&typename=geonode%3Amundo_volcanes&outputFormat=json&version=1.0.0&service=WFS&request=GetFeature" %>% GET() %>% content() highchart(type = "map") %>% hc_title(text = "Marine Currents, Plates & Volcanos") %>% hc_chart(backgroundColor = " hc_add_series(mapData = world, showInLegend = FALSE, nullColor = " hc_add_series(data = marine, type = "mapline", lineWidth = 2, name = "Marine currents", color = 'rgba(0, 0, 80, 0.33)', states = list(hover = list(color = " tooltip = list(pointFormat = "{point.properties.NOMBRE}")) %>% hc_add_series(data = plates, type = "mapline", name = "Plates", color = 'rgba(5, 5, 5, 0.5)', tooltip = list(pointFormat = "{point.properties.TIPO}")) %>% hc_add_series(data = volcano, type = "mappoint", name = "Volcanos", color = 'rgba(200, 10, 80, 0.5)', tooltip = list(pointFormat = "{point.properties.NOMBRE}")) %>% hc_mapNavigation(enabled = TRUE)
print.rocTree <- function(x, digits = 5, tree = NULL, ...) { if (!is.rocTree(x)) stop("Response must be a \"rocTree\" object.") if (!x$ensemble) { printTree(x$Frame, x$vNames, digits) } else { if (!is.null(tree)) { if (!is.wholenumber(tree)) stop("Tree number must be an integer.") if (tree > length(x$trees)) stop("Tree number exceeded the number of trees in forest.") printTree(x$Frame[[tree]], vNames = x$vNames, digits = digits) } else { cat("ROC-guided ensembles\n\n") cat("Call:\n", deparse(x$call), "\n\n") cat("Sample size: ", ncol(x$xlist[[1]]), "\n") cat("Number of independent variables: ", length(unique(x$data$.id)),"\n") cat("Number of trees: ", x$control$numTree, "\n") cat("Split rule: ", x$splitBy, "\n") cat("Number of variables tried at each split: ", x$control$mtry, "\n") cat("Number of time points to evaluate CON: ", x$control$K, "\n") cat("Min. number of baseline obs. in a splittable node: ", x$control$minSplitNode, "\n") cat("Min. number of baseline obs. in a terminal node: ", x$control$minSplitTerm, "\n") } } } tree.split.names <- function(nd0, nd, p, cut, xname, digits = getOption("digits")) { if (nd0 == 1) return("root") ind <- which(nd == nd0 %/% 2) if (nd0 %% 2 == 0) { return(paste(xname[p[ind]], "<=", formatC(cut[ind], digits = digits, flag = " } else { return(paste(xname[p[ind]], ">", formatC(cut[ind], digits = digits, flag = " } } printTree <- function(Frame, vNames, digits) { root <- Node$new("Root", type = "root", decision = "", nd = 1) if (nrow(Frame) > 1) { for (i in 2:nrow(Frame)) { if (i <= 3) parent <- "root" if (i > 3) parent <- paste0("Node", Frame$nd[i] %/% 2) if (Frame$is.terminal[i] > 0) { type <- "terminal" display <- with(Frame, paste0(nd[i], ") ", tree.split.names(nd[i], nd, p, cutVal, vNames, digits), "*")) } else { type <- "interior" display <- with(Frame, paste0(nd[i], ") ", tree.split.names(nd[i], nd, p, cutVal, vNames, digits))) } eval(parse(text = paste0("Node", Frame$nd[i], "<-", parent, "$AddChild(display, type = type, nd = Frame$nd[i])"))) } } toPrint <- ToDataFrameTree(root)[[1]] cat(" ROC-guided survival tree\n") if (nrow(Frame) > 1) { cat("\n") cat(" node), split\n") cat(" * denotes terminal node\n") cat(" ", toPrint, sep = "\n") } else { cat(" Decision tree found no splits.") } cat("\n") } print.predict.rocTree <- function(x, ...) { if (!is.predict.rocTree(x)) stop("Response must be a 'predict.rocTree' object") if (names(x$pred)[[2]] == "Survival") { cat(" Fitted survival probabilities:\n") } if (names(x$pred)[[2]] == "hazard") { cat(" Fitted cumulative hazard:\n") } print(head(x$pred, 5)) cat("\n") }
test_that("normal print method works", { x <- as_sys_time(year_month_day(2019, 1:5, 1)) expect_snapshot(x) }) test_that("can limit with `max`", { x <- as_sys_time(year_month_day(2019, 1:5, 1)) expect_snapshot(print(x, max = 2)) expect_snapshot(print(x, max = 4)) expect_snapshot(print(x, max = 5)) expect_snapshot(print(x, max = 6)) }) test_that("`max` defaults to `getOption('max.print')` but can be overridden", { local_options(max.print = 3) x <- as_naive_time(year_month_day(2019, 1:5, 1)) expect_snapshot(x) expect_snapshot(print(x, max = 4)) expect_snapshot(print(x, max = 5)) }) test_that("can round to less precise precision", { x <- naive_seconds(c(-86401, -86400, -86399, 0, 86399, 86400, 86401)) floor <- naive_days(c(-2, -1, -1, 0, 0, 1, 1)) ceiling <- naive_days(c(-1, -1, 0, 0, 1, 1, 2)) round <- naive_days(c(-1, -1, -1, 0, 1, 1, 1)) expect_identical(time_point_floor(x, "day"), floor) expect_identical(time_point_ceiling(x, "day"), ceiling) expect_identical(time_point_round(x, "day"), round) floor <- naive_days(c(-2, -2, -2, 0, 0, 0, 0)) ceiling <- naive_days(c(0, 0, 0, 0, 2, 2, 2)) round <- naive_days(c(-2, 0, 0, 0, 0, 2, 2)) expect_identical(time_point_floor(x, "day", n = 2), floor) expect_identical(time_point_ceiling(x, "day", n = 2), ceiling) expect_identical(time_point_round(x, "day", n = 2), round) }) test_that("can round with `origin` altering starting point", { x <- sys_seconds(c(-86401, -86400, -86399, 0, 86399, 86400, 86401)) origin <- sys_days(-1) floor <- sys_days(c(-3, -1, -1, -1, -1, 1, 1)) ceiling <- sys_days(c(-1, -1, 1, 1, 1, 1, 3)) round <- sys_days(c(-1, -1, -1, 1, 1, 1, 1)) expect_identical(time_point_floor(x, "day", origin = origin, n = 2), floor) expect_identical(time_point_ceiling(x, "day", origin = origin, n = 2), ceiling) expect_identical(time_point_round(x, "day", origin = origin, n = 2), round) }) test_that("cannot floor to more precise precision", { expect_snapshot_error(time_point_floor(naive_days(), "second")) }) test_that("rounding with `origin` requires same clock", { origin <- sys_days(0) x <- naive_days(0) expect_snapshot_error(time_point_floor(x, "day", origin = origin)) }) test_that("`origin` can be cast to a more precise `precision`, but not to a less precise one", { origin1 <- as_naive_time(duration_days(1)) origin2 <- as_naive_time(duration_milliseconds(0)) x <- naive_seconds(0) expect_identical( time_point_floor(x, "hour", origin = origin1, n = 5), time_point_floor(x - as_duration(origin1), "hour", n = 5) + as_duration(origin1) ) expect_snapshot_error(time_point_floor(x, "hour", origin = origin2)) }) test_that("`origin` must be size 1", { origin <- naive_days(0:1) x <- naive_days(0) expect_snapshot_error(time_point_floor(x, "day", origin = origin)) }) test_that("`origin` must not be `NA`", { origin <- naive_days(NA) x <- naive_days(0) expect_snapshot_error(time_point_floor(x, "day", origin = origin)) }) test_that("`origin` can't be Date or POSIXt", { origin1 <- new_date(0) origin2 <- new_datetime(0, "America/New_York") x <- naive_days(0) expect_snapshot_error(time_point_floor(x, "day", origin = origin1)) expect_snapshot_error(time_point_floor(x, "day", origin = origin2)) }) test_that("can shift to next weekday", { expect_identical( time_point_shift( naive_days(0:1), weekday(clock_weekdays$sunday) ), naive_days(c(3, 3)) ) }) test_that("can shift to next if on the boundary", { naive_sunday <- naive_days(3) sunday <- weekday(clock_weekdays$sunday) expect_identical( time_point_shift(naive_sunday, sunday), naive_sunday ) expect_identical( time_point_shift(naive_sunday, sunday, boundary = "advance"), naive_sunday + 7 ) }) test_that("can shift to previous weekday", { expect_identical( time_point_shift( naive_days(0:1), weekday(clock_weekdays$sunday), which = "previous" ), naive_days(c(-4, -4)) ) }) test_that("can shift to previous weekday if on boundary", { naive_sunday <- naive_days(3) sunday <- weekday(clock_weekdays$sunday) expect_identical( time_point_shift(naive_sunday, sunday, which = "previous"), naive_sunday ) expect_identical( time_point_shift(naive_sunday, sunday, which = "previous", boundary = "advance"), naive_sunday - 7 ) }) test_that("`target` is recycled to size of `x`", { expect_identical( time_point_shift( sys_days(0:1), weekday(1:2) ), sys_days(3:4) ) expect_snapshot_error(time_point_shift(sys_days(0), weekday(1:2))) }) test_that("`x` is validated", { expect_snapshot_error(time_point_shift(1)) }) test_that("`target` is validated", { expect_snapshot_error(time_point_shift(sys_days(0), 1)) }) test_that("`which` is validated", { expect_snapshot_error(time_point_shift(sys_days(), weekday(), which = 1)) expect_snapshot_error(time_point_shift(sys_days(), weekday(), which = "foo")) expect_snapshot_error(time_point_shift(sys_days(), weekday(), which = c("next", "previous"))) }) test_that("`boundary` is validated", { expect_snapshot_error(time_point_shift(sys_days(), weekday(), boundary = 1)) expect_snapshot_error(time_point_shift(sys_days(), weekday(), boundary = "foo")) expect_snapshot_error(time_point_shift(sys_days(), weekday(), boundary = c("keep", "advance"))) }) test_that("can count units between", { x <- as_naive_time(year_month_day(1990, 02, 03, 04)) y <- as_naive_time(year_month_day(1995, 04, 05, 03)) expect_identical(time_point_count_between(x, y, "day"), 1886L) expect_identical(time_point_count_between(x, y, "hour"), 45287L) }) test_that("'week' is an allowed precision", { x <- sys_days(0) y <- sys_days(13:15) expect_identical(time_point_count_between(x, y, "week"), c(1L, 2L, 2L)) }) test_that("`n` affects the result", { x <- sys_days(0) y <- sys_days(10) expect_identical(time_point_count_between(x, y, "day", n = 2L), 5L) expect_identical(time_point_count_between(x, y, "day", n = 3L), 3L) }) test_that("negative vs positive differences are handled correctly", { one_hour <- duration_hours(1) x <- sys_days(0) y <- sys_days(1) z <- sys_days(-1) expect_identical(time_point_count_between(x, y - one_hour, "day"), 0L) expect_identical(time_point_count_between(x, y, "day"), 1L) expect_identical(time_point_count_between(x, y + one_hour, "day"), 1L) expect_identical(time_point_count_between(x, z - one_hour, "day"), -1L) expect_identical(time_point_count_between(x, z, "day"), -1L) expect_identical(time_point_count_between(x, z + one_hour, "day"), 0L) }) test_that("common precision of inputs and `precision` is taken", { expect_identical( time_point_count_between(sys_days(0), sys_days(2) + duration_hours(1), "second"), 176400L ) expect_identical( time_point_count_between(sys_seconds(0), sys_seconds(86401), "day"), 1L ) }) test_that("OOB results return a warning and NA", { expect_snapshot({ out <- time_point_count_between(sys_days(0), sys_days(1000), "nanosecond") }) expect_identical(out, NA_integer_) }) test_that("both inputs must be time points", { expect_snapshot({ (expect_error(time_point_count_between(sys_days(1), 1))) (expect_error(time_point_count_between(1, sys_days(1)))) }) }) test_that("both inputs must be compatible", { x <- sys_days(1) y <- naive_days(1) expect_snapshot((expect_error( time_point_count_between(x, y) ))) }) test_that("`n` is validated", { x <- sys_days(1) expect_snapshot({ (expect_error(time_point_count_between(x, x, "day", n = NA_integer_))) (expect_error(time_point_count_between(x, x, "day", n = -1))) (expect_error(time_point_count_between(x, x, "day", n = 1.5))) (expect_error(time_point_count_between(x, x, "day", n = "x"))) (expect_error(time_point_count_between(x, x, "day", n = c(1L, 2L)))) }) }) test_that("`precision` must be a time point precision", { x <- sys_days(1) expect_snapshot((expect_error( time_point_count_between(x, x, "year") ))) }) test_that("seq(to, by) works", { expect_identical(seq(sys_days(0L), to = sys_days(4L), by = 2), sys_days(c(0L, 2L, 4L))) expect_identical(seq(sys_days(0L), to = sys_days(5L), by = 2), sys_days(c(0L, 2L, 4L))) expect_identical(seq(sys_seconds(0L), to = sys_seconds(-4L), by = -2), sys_seconds(c(0L, -2L, -4L))) expect_identical(seq(sys_seconds(0L), to = sys_seconds(-5L), by = -2), sys_seconds(c(0L, -2L, -4L))) }) test_that("seq(to, length.out) works", { expect_identical(seq(naive_days(0L), to = naive_days(4L), length.out = 2), naive_days(c(0L, 4L))) expect_identical(seq(naive_days(0L), to = naive_days(4L), length.out = 1), naive_days(c(0L))) expect_identical(seq(naive_days(0L), to = naive_days(4L), length.out = 5), naive_days(c(0:4))) expect_identical(seq(naive_seconds(0L), to = naive_seconds(4L), along.with = 1:2), naive_seconds(c(0L, 4L))) }) test_that("seq(by, length.out) works", { expect_identical(seq(naive_seconds(0L), by = 2, length.out = 3), naive_seconds(c(0L, 2L, 4L))) expect_identical(seq(naive_seconds(0L), by = -2, length.out = 3), naive_seconds(c(0L, -2L, -4L))) expect_identical(seq(naive_seconds(0L), by = 2, along.with = 1:3), naive_seconds(c(0L, 2L, 4L))) }) test_that("`by` can be a duration", { expect_identical( seq(naive_seconds(0), to = naive_seconds(1000), by = duration_minutes(1)), seq(naive_seconds(0), to = naive_seconds(1000), by = 60) ) expect_identical( seq(as_naive_time(duration_nanoseconds(0)), to = as_naive_time(duration_nanoseconds(2e9)), by = duration_seconds(1)), seq(as_naive_time(duration_nanoseconds(0)), to = as_naive_time(duration_nanoseconds(2e9)), by = 1e9) ) }) test_that("can't mix chronological time points and calendrical durations", { expect_snapshot_error(seq(naive_seconds(0), by = duration_years(1), length.out = 2)) }) test_that("can't mix clocks in seq()", { expect_snapshot_error(seq(sys_seconds(0), to = naive_seconds(5), by = 1)) }) test_that("`to` is always cast to `from`", { expect_identical( seq(naive_seconds(0), to = naive_days(12), by = duration_days(2)), seq(naive_seconds(0), to = naive_seconds(12 * 86400), by = 86400 * 2) ) expect_snapshot_error(seq(naive_days(0), to = naive_seconds(5), by = 2)) }) test_that("can make nanosecond precision seqs", { x <- as_naive_time(duration_nanoseconds(0)) y <- as_naive_time(duration_nanoseconds(10)) expect_identical(seq(x, by = 2, length.out = 5), x + c(0, 2, 4, 6, 8)) expect_identical(seq(x, y, by = 3), x + c(0, 3, 6, 9)) }) test_that("duration to add to a time-point must have at least week precision ( expect_snapshot_error(naive_seconds(0) + duration_years(1)) }) test_that("precision: can get the precision", { expect_identical(time_point_precision(as_naive_time(duration_days(2:5))), "day") expect_identical(time_point_precision(as_naive_time(duration_nanoseconds(2:5))), "nanosecond") }) test_that("precision: can only be called on time points", { expect_snapshot_error(time_point_precision(duration_days())) })
renv_ci_dependencies <- function() { ensure_directory("ci") saveRDS(R.version, file = "ci/version.rds", version = 2L) records <- renv_project_remotes(project = getwd()) packages <- extract_chr(records, "Package") revdeps <- tools::package_dependencies(packages, recursive = TRUE) all <- sort(unique(unlist(revdeps))) db <- as.data.frame( available.packages(filters = c("OS_type", "duplicates")), stringsAsFactors = FALSE ) resolved <- db[db$Package %in% all, c("Package", "Version")] rownames(resolved) <- NULL envvar <- case( renv_platform_linux() ~ "RENV_CI_CACHE_VERSION_LINUX", renv_platform_macos() ~ "RENV_CI_CACHE_VERSION_MACOS", renv_platform_windows() ~ "RENV_CI_CACHE_VERSION_WINDOWS" ) version <- Sys.getenv(envvar, unset = NA) if (!is.na(version)) attr(resolved, "cache") <- version print(resolved) saveRDS(resolved, file = "ci/dependencies.rds", version = 2L) } renv_ci_repair <- function() { library <- renv_libpaths_default() db <- renv_installed_packages(lib.loc = library) packages <- db$Package names(packages) <- packages ok <- map_lgl(packages, requireNamespace, quietly = TRUE) broken <- packages[!ok] if (empty(broken)) { vwritef("* All installed packages can be successfully loaded.") return(broken) } renv_pretty_print( values = paste("-", packages), preamble = "The following package(s) could not be successfully loaded:", postamble = "These packages will be removed and later reinstalled.", wrap = FALSE ) paths <- file.path(library, broken) unlink(paths, recursive = TRUE) return(broken) }
expected <- c(1L, 2L, 3L, 0L, 1L, 4L, 5L) test(id=1, code={ argv <- structure(list(x = 1:5, values = 0:1, after = 3), .Names = c("x", "values", "after")) do.call('append', argv); }, o = expected);
Wald1 <- function(y,k) { y <- as.matrix(y) n <- nrow(y) m <- mean(y) vr1 <- sum( (y-m)^2 )/n flt = filter(y, rep(1,k), method = "convolution") flt = flt[!is.na(flt)] summ = sum((flt - k * m)^2) vr2 <- summ/(n*k) vr <- vr2/vr1 -1 return(vr) }
SUMIF <- function(range,criteria, sum_range) { if(is.na(as.numeric(criteria)) == FALSE){ c1 <- "==" } else if (str_detect(criteria,"^>") == TRUE){ c1 <- ">" criteria <- extract_numeric(criteria) } else if (str_detect(criteria,"^<") == TRUE){ c1 <- "<" criteria <- extract_numeric(criteria) } else if (str_detect(criteria,"^>=")){ c1 <- ">=" criteria <- extract_numeric(criteria) } else if (str_detect(criteria,"^<=")){ c1 <- "<=" criteria <- extract_numeric(criteria) } else if (is.character(criteria) == TRUE){ c1 <- "==" } ret <- sum(sum_range[get(c1)(range,criteria)]) ret }
simulate_clustered_phylogeny<-function(v_sizeclusts,joining_branchlengths=NULL,f_simclustphyl="sim.bd.taxa_Yule1",joiningphyl=NULL,b_change_joining_branches=FALSE,...){ if (is.null(v_sizeclusts)){stop("Size clusters not provided!")} numclusts<-length(v_sizeclusts) if ((inherits(joiningphyl,"phylo"))&&(numclusts!=(joiningphyl$Nnode+1))){stop("Number of tips of connecting phylogeny does not equal the number of clusters.")} if (numclusts==1){ if ((is.character(f_simclustphyl))&&(f_simclustphyl=="sim.bd.taxa_Yule1")){ p1<-TreeSim::sim.bd.taxa(n=v_sizeclusts[1],lambda=1,mu=0,numbsim=1)[[1]] p_joined<-p1;p_joined$root.edge<-joining_branchlengths[1];return(p_joined) } else if(is.function(f_simclustphyl)){ p1<-f_simclustphyl(n=v_sizeclusts[1],...) if (!inherits(p1,"phylo")){ stop("The simulation function passed through f_simclustphyl does not return a phylo object!") } p_joined<-p1;p_joined$root.edge<-joining_branchlengths[1];return(p_joined) }else{stop("Cannot simulate the phylogeny with the provided f_simclustphyl.")} } if (!is.null(joining_branchlengths)){ internal_joining_branchlength<-NA if (length(joining_branchlengths)==2){ internal_joining_branchlength<-joining_branchlengths[[2]] joining_branchlengths<-joining_branchlengths[[1]] }else{ if (length(joining_branchlengths)==1){internal_joining_branchlength<-joining_branchlengths} else{stop("At the moment joining_branchlengths cannot have length more than 2!")} } } if (is.null(joiningphyl)){ if (is.null(joining_branchlengths)){stop("If joining phylogeny is not provided, joining_branchlengths is required!")} joiningphyl<-list(Nnode=numclusts-1,edge=matrix(NA,nrow=2*numclusts-2,ncol=2),edge.length=rep(NA,2*numclusts-2),tip.label=paste(paste0("t",1:numclusts))) if (numclusts>2){ joiningphyl$edge[1,]<-c(numclusts+2,1) joiningphyl$edge.length[1]<-joining_branchlengths curredge<-2 currintnode<-numclusts+2 for (i in 2:(numclusts-1)){ joiningphyl$edge[curredge,]<-c(currintnode,i) joiningphyl$edge.length[curredge]<-joining_branchlengths joiningphyl$edge[(curredge+1),]<-c(currintnode+1,currintnode) if (is.na(internal_joining_branchlength)){ stop("The second element of joining_branchlengths cannot be NA if the joining phylogeny is NOT provided.") } joiningphyl$edge.length[curredge+1]<-internal_joining_branchlength curredge<-curredge+2 currintnode<-currintnode+1 } joiningphyl$edge[curredge,]<-c(numclusts+1,numclusts) joiningphyl$edge[which(joiningphyl$edge==(2*numclusts))]<-numclusts+1 joiningphyl$edge.length[curredge]<-joining_branchlengths }else{ joiningphyl$edge<-rbind(c(3,1),c(3,2)) joiningphyl$edge.length<-rep(joining_branchlengths,2) } class(joiningphyl)<-"phylo" }else{ if (!inherits(joiningphyl,"phylo")){ if((inherits(joiningphyl,"character")) && (joiningphyl=="sim.bd.taxa_Yule1")){ joiningphyl<-TreeSim::sim.bd.taxa(n=numclusts,lambda=1,mu=0,numbsim=1)[[1]] } else if(is.function(joiningphyl)){ joiningphyl<-joiningphyl(n=numclusts,...) if (!inherits(joiningphyl,"phylo")){ stop("The simulation function passed through joiningphyl does not return a phylo object!") } }else{stop("Cannot simulate the phylogeny with the provided joiningphyl.")} } joiningphyl$root.edge<-NULL if (b_change_joining_branches){ if ((!is.null(joining_branchlengths))&&(is.numeric(joining_branchlengths))){ v_tip_branches<-which(joiningphyl$edge[,2]<(numclusts+1)) joiningphyl$edge.length[v_tip_branches]<-joining_branchlengths[[1]] if (!is.na(internal_joining_branchlength)){ v_non_tip_branches<-setdiff(1:length(joiningphyl$edge.length),v_tip_branches) if (length(v_non_tip_branches)>0){ joiningphyl$edge.length[v_non_tip_branches]<-internal_joining_branchlength } } }else{message("Cannot change branches leading to clusters as joining_branchlengths not provided")} } } numtipscurr<-0 p_joined<-joiningphyl numalltips<-sum(v_sizeclusts) p_joined$edge[which(p_joined$edge>(numclusts+1))]<-p_joined$edge[which(p_joined$edge>(numclusts+1))]+numalltips p_joined$edge[which(p_joined$edge==(numclusts+1))]<-numalltips+1 p_joined$edge[which(p_joined$edge<=numclusts)]<-p_joined$edge[which(p_joined$edge<=numclusts)]+numalltips+1 labelfirstnodeinsubtree<-numalltips+2*numclusts p_joined$edges_clusters<-vector("list",numclusts+1) p_joined$tips_clusters<-vector("list",numclusts) names(p_joined$edges_clusters)<-c("joining_tree",paste0("cluster_",1:numclusts)) names(p_joined$tips_clusters)<-paste0("cluster_",1:numclusts) p_joined$edges_clusters$joining_tree<-1:nrow(p_joined$edge) for (i in 1:numclusts){ if ((is.character(f_simclustphyl))&&(f_simclustphyl=="sim.bd.taxa_Yule1")){ pnext<-TreeSim::sim.bd.taxa(n=v_sizeclusts[i],lambda=1,mu=0,numbsim=1)[[1]] } else if(is.function(f_simclustphyl)){ pnext<-f_simclustphyl(n=v_sizeclusts[i],...) if (!inherits(pnext,"phylo")){ stop("The simulation function passed through f_simclustphyl does not return a phylo object!") } }else{stop("Cannot simulate the phylogeny with the provided f_simclustphyl.")} pnext$root.edge<-NULL intnodes_torelabel<-which(pnext$edge>(v_sizeclusts[i]+1)) if (length(intnodes_torelabel)>0){ pnext$edge[intnodes_torelabel]<-pnext$edge[intnodes_torelabel]+labelfirstnodeinsubtree-(v_sizeclusts[i]+2) labelfirstnodeinsubtree<-labelfirstnodeinsubtree+v_sizeclusts[i]-2 } pnext$edge[which(pnext$edge==(v_sizeclusts[i]+1))]<-numalltips+i+1 p_joined$tips_clusters[[i]]<-sort(unique(pnext$edge[which(pnext$edge<=v_sizeclusts[i])]))+numtipscurr pnext$edge[which(pnext$edge<=v_sizeclusts[i])]<-pnext$edge[which(pnext$edge<=v_sizeclusts[i])]+numtipscurr numtipscurr<-numtipscurr+v_sizeclusts[i] start_edge_cluster<-nrow(p_joined$edge)+1 p_joined$edge<-rbind(p_joined$edge,pnext$edge) end_edge_cluster<-nrow(p_joined$edge) p_joined$edges_clusters[[i+1]]<-start_edge_cluster:end_edge_cluster p_joined$edge.length<-c(p_joined$edge.length,pnext$edge.length) } p_joined$Nnode<-numalltips-1 p_joined$tip.label<-paste0("t",1:numalltips) class(p_joined)<-c("clustered_phylo","phylo") p_joined } plot.clustered_phylo<-function(x,clust_cols=NULL,clust_edge.width=NULL,clust_edge.lty=NULL,clust_tip.color="black",joiningphylo_col="black",joiningphylo_edge.width=1,joiningphylo_edge.lty=1,...){ if (is.null(joiningphylo_col)){joiningphylo_col<-"black"} vedgecol<-rep(joiningphylo_col,length(x$edge.length)) if (!is.null(clust_cols)){ if (length(clust_cols)!=(length(x$edges_clusters)-1)){ opt_warn<-options("warn") options(warn=-1) new_clust_cols<-rep(NA,length(x$edges_clusters)-1) new_clust_cols[]<-clust_cols clust_cols<-new_clust_cols options(warn=opt_warn$warn) } for (i in 2:length(x$edges_clusters)){ vedgecol[x$edges_clusters[[i]]]<-clust_cols[i-1] } } if (is.null(joiningphylo_edge.width)){joiningphylo_edge.width<-1} vedgewidth<-rep(joiningphylo_edge.width,length(x$edge.length)) if (!is.null(clust_edge.width)){ if (length(clust_edge.width)!=(length(x$edges_clusters)-1)){ opt_warn<-options("warn") options(warn=-1) new_clust_edge.width<-rep(NA,length(x$edges_clusters)-1) new_clust_edge.width[]<-clust_edge.width clust_edge.width<-new_clust_edge.width options(warn=opt_warn$warn) } for (i in 2:length(x$edges_clusters)){ vedgewidth[x$edges_clusters[[i]]]<-clust_edge.width[i-1] } } if (is.null(joiningphylo_edge.lty)){joiningphylo_edge.lty<-1} vedgelty<-rep(joiningphylo_edge.lty,length(x$edge.length)) if (!is.null(clust_edge.lty)){ if (length(clust_edge.lty)!=(length(x$edges_clusters)-1)){ opt_warn<-options("warn") options(warn=-1) new_clust_edge.lty<-rep(NA,length(x$edges_clusters)-1) new_clust_edge.lty[]<-clust_edge.lty clust_edge.lty<-new_clust_edge.lty options(warn=opt_warn$warn) } for (i in 2:length(x$edges_clusters)){ vedgelty[x$edges_clusters[[i]]]<-clust_edge.lty[i-1] } } if (is.null(clust_tip.color)){clust_tip.color<-"black"} if (length(clust_tip.color)!=length(x$tips_clusters)){ opt_warn<-options("warn") options(warn=-1) new_clust_tip.color<-rep(NA,length(x$tips_clusters)) new_clust_tip.color[]<-clust_tip.color clust_tip.color<-new_clust_tip.color options(warn=opt_warn$warn) } vtipcolor<-rep(NA,length(x$tip.label)) for (i in 1:length(x$tips_clusters)){ vtipcolor[x$tips_clusters[[i]]]<-clust_tip.color[i] } class(x)<-"phylo" ape::plot.phylo(x,edge.color=vedgecol,edge.width=vedgewidth,edge.lty=vedgelty,tip.color=vtipcolor,...) }
WriteMCL <- function(mtrx, filename) { write.csv(mtrx, filename, quote = F, row.names = F) wd <- getwd() file <- paste(wd, filename, sep = "/") cat("wrote matrix to", file, "\n") }
iBMA.bicreg<- function(x, ...) UseMethod("iBMA.bicreg") iBMA.bicreg.data.frame<- function(x, Y, wt = rep(1, nrow(X)), thresProbne0 = 5, maxNvar = 30, nIter=100, verbose = FALSE, sorted = FALSE, ...) { printCGen<- function(printYN) { printYN<- printYN return(function(x) if (printYN) cat(paste(paste(x,sep="", collapse = " "),"\n", sep=""))) } sortX<- function(Y, X, wt) { r2vec<- rep(NA, times = ncol(X)) for (i in 1:ncol(X)) r2vec[i]<- summary(lm(Y~X[,i], weights = wt))$r.squared initial.order<- order(abs(r2vec),decreasing = TRUE) sortedX<- X[, initial.order] return(list(sortedX = sortedX, initial.order = initial.order)) } cl <- match.call() printC<- printCGen(verbose) X<- x if (!sorted) { printC("sorting X") sorted<- sortX(Y,X, wt = wt) sortedX<- sorted$sortedX initial.order<- sorted$initial.order } else { sortedX<- X initial.order<- 1:ncol(sortedX) } nVar<- ncol(sortedX) maxNvar <- min (maxNvar, nVar) stopVar <- 0 nextVar <- maxNvar + 1 current.probne0<- rep(0, maxNvar) maxProbne0<- rep(0, times = nVar) nTimes<- rep(0, times = nVar) currIter <- 0 first.in.model<- rep(NA, times = nVar) new.vars<- 1:maxNvar first.in.model[new.vars]<- currIter + 1 iter.dropped<- rep(NA, times = nVar) currentSet<- NULL current_state<- list(Y = Y, sortedX = sortedX, wt = wt, call = cl, initial.order = initial.order, thresProbne0 = thresProbne0, maxNvar = maxNvar, nIter = nIter, verbose = verbose, nVar = nVar, currentSet = currentSet, new.vars= new.vars, stopVar = stopVar, nextVar = nextVar, current.probne0 = current.probne0, maxProbne0 = maxProbne0, nTimes = nTimes, currIter = currIter, first.in.model = first.in.model, iter.dropped = iter.dropped) class(current_state)<- "iBMA.intermediate.bicreg" result<- iBMA.bicreg.iBMA.intermediate.bicreg(current_state, ...) result } iBMA.bicreg.iBMA.intermediate.bicreg<- function (x, nIter = NULL, verbose = NULL, ...) { printCGen<- function(printYN) { printYN<- printYN return(function(x) if (printYN) cat(paste(paste(x,sep="", collapse = " "),"\n", sep=""))) } cs<- x if (!is.null(nIter)) cs$nIter<- nIter if (!is.null(verbose)) cs$verbose<- verbose printC<- printCGen(cs$verbose) finalIter<- cs$currIter + cs$nIter while (cs$stopVar == 0 && cs$currIter < finalIter) { nextSet<- c(cs$currentSet, cs$new.vars) cs$currIter<- cs$currIter + 1 printC(paste("starting iteration ",cs$currIter," nextVar =",cs$nextVar)) printC("applying bicreg now") currentX<- cs$sortedX[,nextSet] colnames(currentX)<- colnames(cs$sortedX)[nextSet] ret.bicreg <- bicreg (x = currentX, y = cs$Y, wt = cs$wt, maxCol = cs$maxNvar + 1, ...) printC(ret.bicreg$probne0) cs$maxProbne0[nextSet]<- pmax(ret.bicreg$probne0, cs$maxProbne0[nextSet]) cs$nTimes[nextSet]<- cs$nTimes[nextSet] + 1 cs$rmVector <- ret.bicreg$probne0 < cs$thresProbne0 if (any(cs$rmVector) == FALSE) { currMin <- min (ret.bicreg$probne0) printC (paste("no var to swap! Min probne0 = ", currMin, sep="")) newThresProbne0 <- currMin + 1 printC(paste("new probne0 threshold = ", newThresProbne0, sep="")) cs$rmVector <- ret.bicreg$probne0 < newThresProbne0 if (all(cs$rmVector)) cs$rmVector<- c(rep(FALSE, times = length(cs$rmVector)-1), TRUE) } cs$iter.dropped[nextSet[cs$rmVector]]<- cs$currIter cs$currentSet<- nextSet[!cs$rmVector] if ( cs$nextVar <= cs$nVar) { printC ("generating next set of variables") lastVar<- sum(cs$rmVector) + cs$nextVar - 1 if (lastVar <= cs$nVar) { cs$new.vars<- cs$nextVar:lastVar cs$first.in.model[cs$new.vars]<- cs$currIter + 1 cs$nextVar <- lastVar + 1 } else { cs$new.vars<- NULL for (i in length(cs$rmVector):1) { if (cs$rmVector[i] == TRUE && cs$nextVar <= cs$nVar) { cs$new.vars<- c(cs$new.vars, cs$nextVar) cs$first.in.model[cs$nextVar]<- cs$currIter + 1 cs$nextVar <- cs$nextVar + 1 } } } } else { cs$stopVar <- 1 cs$new.vars = NULL } } if (cs$stopVar == 1) { printC("finished iterating") currentX<- cs$sortedX[,cs$currentSet] colnames(currentX)<- colnames(cs$sortedX)[cs$currentSet] ret.bicreg <- bicreg (x = currentX, y = cs$Y, wt = cs$wt, maxCol = cs$maxNvar + 1, ...) output<- cs output$bma<- ret.bicreg output$selected<- cs$currentSet output$nIterations<- cs$currIter class(output)<- "iBMA.bicreg" } else { output<- cs class(output)<- "iBMA.intermediate.bicreg" } output } iBMA.bicreg.matrix<- iBMA.bicreg.data.frame
NULL embedding_glove6b <- function(dir = NULL, dimensions = c(50, 100, 200, 300), delete = FALSE, return_path = FALSE, clean = FALSE, manual_download = FALSE) { this_glove <- "6b" available_dims <- c(50, 100, 200, 300) all_names <- construct_glove_name(this_glove, available_dims) dimensions <- as.character(dimensions) dimensions <- match.arg(dimensions, as.character(available_dims)) name <- construct_glove_name(this_glove, dimensions) load_dataset(data_name = "glove6b", name = name, dir = dir, delete = delete, return_path = return_path, clean = clean, clean_manual = all_names, manual_download = manual_download) } construct_glove_name <- function(tokens = c("6b", "27b"), dimensions = c(25, 50, 100, 200, 300)) { tokens <- match.arg(tokens) dimensions <- as.character(dimensions) dimensions <- match.arg( dimensions, choices = as.character(c(25, 50, 100, 200, 300)), several.ok = TRUE ) paste0( paste( "glove", tokens, dimensions, sep = "_" ), ".rds" ) } embedding_glove27b <- function(dir = NULL, dimensions = c(25, 50, 100, 200), delete = FALSE, return_path = FALSE, clean = FALSE, manual_download = FALSE) { this_glove <- "27b" available_dims <- c(25, 50, 100, 200) all_names <- construct_glove_name(this_glove, available_dims) dimensions <- as.character(dimensions) dimensions <- match.arg(dimensions, as.character(available_dims)) name <- construct_glove_name(this_glove, dimensions) load_dataset(data_name = "glove27b", name = name, dir = dir, delete = delete, return_path = return_path, clean = clean, clean_manual = all_names, manual_download = manual_download) } embedding_glove42b <- function(dir = NULL, delete = FALSE, return_path = FALSE, clean = FALSE, manual_download = FALSE) { name <- "glove_42b.rds" load_dataset(data_name = "glove42b", name = name, dir = dir, delete = delete, return_path = return_path, clean = clean, manual_download = manual_download) } embedding_glove840b <- function(dir = NULL, delete = FALSE, return_path = FALSE, clean = FALSE, manual_download = FALSE) { name <- "glove_840b.rds" load_dataset(data_name = "glove840b", name = name, dir = dir, delete = delete, return_path = return_path, clean = clean, manual_download = manual_download) } download_glove6b <- function(folder_path) { file_path <- path(folder_path, "glove.6B.zip") if (file_exists(file_path)) { return(invisible()) } download.file(url = "http://nlp.stanford.edu/data/glove.6B.zip", destfile = file_path) } download_glove42b <- function(folder_path) { file_path <- path(folder_path, "glove.42B.300d.zip") if (file_exists(file_path)) { return(invisible()) } download.file(url = "http://nlp.stanford.edu/data/glove.42B.300d.zip", destfile = file_path) } download_glove840b <- function(folder_path) { file_path <- path(folder_path, "glove.840B.300d.zip") if (file_exists(file_path)) { return(invisible()) } download.file(url = "http://nlp.stanford.edu/data/glove.840B.300d.zip", destfile = file_path) } download_glove27b <- function(folder_path) { file_path <- path(folder_path, "glove.twitter.27B.zip") if (file_exists(file_path)) { return(invisible()) } download.file(url = "http://nlp.stanford.edu/data/glove.twitter.27B.zip", destfile = file_path) } process_glove6b <- function(folder_path, name_path) { filename <- gsub(folder_path, "", name_path) dimensions <- unlist(strsplit(filename, "_|\\."))[[3]] raw_name <- paste0("glove.6B.", dimensions, "d.txt") file <- unz(path(folder_path, "glove.6B.zip"), raw_name) write_glove(file, name_path, dimensions) } process_glove42b <- function(folder_path, name_path) { dimensions <- 300 raw_name <- "glove.42B.300d.txt" file <- unz(path(folder_path, "glove.42B.300d.zip"), raw_name) write_glove(file, name_path, dimensions) } process_glove840b <- function(folder_path, name_path) { dimensions <- 300 raw_name <- "glove.840B.300d.txt" file <- unz(path(folder_path, "glove.840B.300d.zip"), raw_name) write_glove(file, name_path, dimensions) } process_glove27b <- function(folder_path, name_path) { filename <- gsub(folder_path, "", name_path) dimensions <- unlist(strsplit(filename, "_|\\."))[[3]] raw_name <- paste0("glove.twitter.27B.", dimensions, "d.txt") file <- unz(path(folder_path, "glove.twitter.27B.zip"), raw_name) write_glove(file, name_path, dimensions) } write_glove <- function(file, name_path, dimensions) { embeddings <- read_delim( file, delim = " ", quote = "", col_names = c( "token", paste0("d", seq_len(dimensions)) ), col_types = paste0( c( "c", rep("d", dimensions) ), collapse = "" ) ) write_rds(embeddings, name_path) }
emgm = function(X, init, maxiter=100,verb=0){ initialization = function(X, init){ d = nrow(X) ; n = ncol(X); if (is.list(init)) {R = expectation(X,init);} else { if (length(init) == 1) {k = init; idx = sample(1:n,k,replace=FALSE); m = X[,idx,drop=FALSE]; label = max.col(t(sweep(t(m)%*%X,1,colSums(m^2)/2,"-"))); u = sort(unique(label)); count=0; while (k != length(u) && count<20){ count=count+1; k=length(u); idx = sample(1:n,k,replace=FALSE); m = X[,idx]; m = as.matrix(m); label = max.col(t(sweep(t(m)%*%X,1,colSums(m^2)/2,"-"))); u = sort(unique(label)); } k=length(u); R = as.matrix(sparseMatrix(i=1:n,j=label,x=rep(1,n),dims=c(n,k))) } else { if (nrow(init) == n) {R = init;} else { if (nrow(init) == d) {k = ncol(init); m = init; m = as.matrix(m); label = max.col(t(sweep(t(m)%*%X,2,colSums(m^2)/2,"-"))); R = as.matrix(sparseMatrix(i=1:n,j=label,x=rep(1,n),dims=c(n,k))) ; } else {stop('ERROR: init is not valid.');} } } } return(R) } expectation = function(X, model){ mu = model$mu; Sigma = model$Sigma; w = model$weight; n = ncol(X); k = ncol(mu); logRho = matrix(0,n,k); for (i in 1:k){ logRho[,i] = loggausspdf(X,mu[,i,drop=FALSE],Sigma[,,i]); } logRho = sweep(logRho,2,log(w),"+") TT = logsumexp(logRho,2); llh = sum(TT)/n; logR= sweep(logRho,1,TT,"-") R = exp(logR); return(list(R=R, llh=llh)) } maximization = function(X, R){ d = nrow(X) ; n = ncol(X) k = ncol(R) ; nk = colSums(R); w = nk/n; mu = sweep(X%*%R,2,1/nk,"*") Sigma = array(0,dim=c(d,d,k)); sqrtR = sqrt(R); for (i in 1:k){ Xo = sweep(X,1,mu[,i],"-") Xo = sweep(Xo,2,sqrtR[,i],"*") Sigma[,,i] = tcrossprod(Xo)/nk[i]; Sigma[,,i] = Sigma[,,i]+diag(d)*(1e-08); } return(list(mu=mu,Sigma=Sigma,weight=w)) } if(verb>=1) print(' EM for Gaussian mixture: running ... '); R = initialization(X,init); label = max.col(R) R = R[,sort(unique(label))]; tol = 1e-14; llh = rep(-Inf, maxiter) converged = FALSE; t = 0; while (!converged & t < maxiter){ t = t+1; if(verb>=1) print(paste(' Step ',t,sep="")); model = maximization(X,as.matrix(R)); tmp = expectation(X,model); R=tmp$R; llh[t]=tmp$llh label = max.col(R) u = unique(label); if (ncol(R) != length(u)) { R = R[,u]; } else {converged = ((llh[t+1]-llh[t]) < tol*abs(llh[t+1]));} } if(verb>=1) { if (converged) {print(paste('Converged in ',t,' steps.',sep=""));} else {print(paste('Did not converge in ',maxiter,' steps.',sep=""));} } return(list(label= label, model= model, llh= llh[1:t], R=R)) }
context("alignTransect") data("sierraTransect") g <- subset(sierraTransect, transect == 'Granite') a <- subset(sierraTransect, transect == 'Andesite') test_that("alignTransect works as expected", { p <- alignTransect(g$elev, 1, length(g), fix = FALSE) expect_true(inherits(p, 'list')) expect_true(length(p) == 3) expect_true(all(p$order == 1:7)) }) test_that("more complex input", { p <- alignTransect(a$elev, 1, length(a), fix = FALSE) expect_true(inherits(p, 'list')) expect_true(length(p) == 3) expect_true(all(p$order == c(7, 6, 5, 4, 3, 2, 1))) })
plot.new_ezmmek_act_group <- function(x, ...) { columns <- rlang::enquos(...) if("act_raw_data_ibc" %in% colnames(x)) { df <- x %>% dplyr::rename(act_raw_data = act_raw_data_ibc) unnest_act_df <- tidyr::unnest(df, act_raw_data) act_plot <- ggplot2::ggplot(data = unnest_act_df, mapping = ggplot2::aes(x = substrate_conc, y = signal, color = as.factor(replicate))) + ggplot2::geom_point() + ggplot2::theme_bw() + ggplot2::scale_color_discrete(name = "replicate") + ggplot2::facet_wrap(columns) } if("act_raw_data_isc" %in% colnames(x)) { df <- x %>% dplyr::rename(act_raw_data = act_raw_data_isc) unnest_act_df <- tidyr::unnest(df, act_raw_data) act_plot <- ggplot2::ggplot(data = unnest_act_df, mapping = ggplot2::aes(x = time, y = signal, color = as.factor(replicate))) + ggplot2::geom_point() + ggplot2::geom_smooth(method = "lm") + ggplot2::theme_bw() + ggplot2::scale_color_discrete(name = "replicate") + ggplot2::facet_wrap(columns) } act_plot }
question_radio <- function( text, ..., correct = "Correct!", incorrect = "Incorrect", try_again = incorrect, allow_retry = FALSE, random_answer_order = FALSE ) { learnr::question( text = text, ..., type = "learnr_radio", correct = correct, incorrect = incorrect, allow_retry = allow_retry, random_answer_order = random_answer_order ) } question_ui_initialize.learnr_radio <- function(question, value, ...) { choice_names <- answer_labels(question) choice_values <- answer_values(question) radioButtons( question$ids$answer, label = question$question, choiceNames = choice_names, choiceValues = choice_values, selected = value %||% FALSE ) } question_is_correct.learnr_radio <- function(question, value, ...) { for (ans in question$answers) { if (as.character(ans$option) == value) { return(mark_as( ans$correct, ans$message )) } } mark_as(FALSE, NULL) } question_ui_completed.learnr_radio <- function(question, value, ...) { choice_values <- answer_values(question) choice_names_final <- lapply(question$answers, function(ans) { if (ans$correct) { tag <- " & tagClass <- "correct" } else { tag <- " & tagClass <- "incorrect" } tags$span(ans$label, HTML(tag), class = tagClass) }) disable_all_tags( radioButtons( question$ids$answer, label = question$question, choiceValues = choice_values, choiceNames = choice_names_final, selected = value ) ) }
gtm_api_request <- function( creds, request, scope = gtm_scopes["read_only"], base_url = "https://www.googleapis.com/tagmanager/v1", req_type = "GET", body_list = NULL, fields = NULL, max_results = NULL ) { stopifnot(scope %in% gtm_scopes) google_api_request( creds = creds, scope = scope, request = request, base_url = base_url, req_type = req_type, body_list = body_list, fields = fields ) } .gtmManagementApi <- R6Class( ".gtmManagementApi", inherit = .googleApi, private = list( scope = gtm_scopes['read_only'], write_scope = gtm_scopes["edit_containers"], api_req_func = gtm_api_request, base_url = "https://www.googleapis.com/tagmanager/v1" ) ) .gtmResource <- R6Class( ".gtmResource", inherit = .googleApiResource, private = c( get_privates(.gtmManagementApi), list(field_corrections = function(field_list) { names(field_list)[names(field_list) == paste0(private$resource_name, 'Id')] <- "id" super$field_corrections(field_list) }) ) ) .gtmCollection <- R6Class( ".gtmCollection", inherit = .googleApiCollection, private = c( get_privates(.gtmResource), list(collection_name = NULL) ) ) gtmAccount <- R6Class( "gtmAccount", inherit = .gtmResource, public = list( shareData = NA, fingerprint = NA ), active = list( containers = function() {self$.child_nodes(gtmContainers)}, permissions = function() { tryCatch( self$.child_nodes(gtmPermissions), error = function(e) { e$message } ) } ), private = list( parent_class_name = "NULL", request = "accounts", resource_name = "account" ) ) GtmAccount <- function(id = NULL, creds = get_creds()){ gtmAccount$new(id = id, creds = creds) } gtmAccounts <- R6Class( "gtmAccounts", inherit = .gtmCollection, private = list( entity_class = gtmAccount ) ) GtmAccounts <- function(creds = get_creds()){ gtmAccounts$new(creds = creds) } gtmPermission <- R6Class( "gtmPermission", inherit = .gtmResource, public = list( emailAddress = NA, accountAccess = NA, containerAccess = NA ), private = list( parent_class_name = "gtmAccount", request = "permissions", scope = gtm_scopes[c('read_only', 'manage_users')], resource_name = "permission" ) ) gtmPermissions <- R6Class( "gtmPermissions", inherit = .gtmCollection, private = list( entity_class = gtmPermission, collection_name = "userAccess", scope = gtmPermission$private_fields$scope ) ) gtmContainer <- R6Class( "gtmContainer", inherit = .gtmResource, public = list( domainName = NA, publicId = NA, timeZoneCountryId = NA, timeZoneId = NA, notes = NA, usageContext = NA, enabledBuiltInVariable = NA, fingerprint = NA ), active = list( tags = function() {self$.child_nodes(gtmTags)}, rules = function() {self$.child_nodes(gtmRules)}, macros = function() {self$.child_nodes(gtmMacros)}, versions = function() {self$.child_nodes(gtmContainerVersions)}, variables = function() {self$.child_nodes(gtmVariables)}, triggers = function() { tryCatch( self$.child_nodes(gtmTriggers), error = function(e) { e$message } ) } ), private = list( parent_class_name = "gtmAccount", request = "containers", resource_name = "container" ) ) gtmContainers <- R6Class( "gtmContainers", inherit = .gtmCollection, private = list( entity_class = gtmContainer ) ) gtmTag <- R6Class( "gtmTag", inherit = .gtmResource, public = list( type = NA, firingRuleId = NA, blockingRuleId = NA, firingTriggerId = NA, blockingTriggerId = NA, liveOnly = NA, priority = NA, notes = NA, scheduleStartMs = NA, scheduleEndMs = NA, parameter = NA, fingerprint = NA ), private = list( parent_class_name = "gtmContainer", request = "tags", resource_name = "tag" ) ) gtmTags <- R6Class( "gtmTags", inherit = .gtmCollection, private = list( entity_class = gtmTag ) ) gtmRule <- R6Class( "gtmRule", inherit = .gtmResource, public = list( notes = NA, condition = NA, fingerprint = NA ), private = list( parent_class_name = "gtmContainer", request = "rules", resource_name = "rule" ) ) gtmRules <- R6Class( "gtmRules", inherit = .gtmCollection, private = list( entity_class = gtmRule ) ) gtmTrigger <- R6Class( "gtmTrigger", inherit = .gtmResource, public = list( type = NA, customEventFilter = NA, filter = NA, autoEventFilter = NA, waitForTags = NA, checkValidation = NA, waitForTagsTimeout = NA, uniqueTriggerId = NA, eventName = NA, interval = NA, limit = NA, enableAllVideos = NA, videoPercentageList = NA, fingerprint = NA ), private = list( parent_class_name = "gtmContainer", request = "triggers", resource_name = "trigger" ) ) gtmTriggers <- R6Class( "gtmTriggers", inherit = .gtmCollection, private = list( entity_class = gtmTrigger ) ) gtmMacro <- R6Class( "gtmMacro", public = list( type = NA, notes = NA, scheduleStartMs = NA, scheduleEndMs = NA, parameter = NA, enablingRuleId = NA, disablingRuleId = NA, fingerprint = NA ), inherit = .gtmResource, private = list( parent_class_name = "gtmContainer", request = "macros", resource_name = "macro" ) ) gtmMacros <- R6Class( "gtmMacros", inherit = .gtmCollection, private = list( entity_class = gtmMacro ) ) gtmVariable <- R6Class( "gtmVariable", inherit = .gtmResource, public = list( type = NA, notes = NA, scheduleStartMs = NA, scheduleEndMs = NA, parameter = NA, enablingTriggerId = NA, disablingTriggerId = NA, fingerprint = NA ), private = list( parent_class_name = "gtmContainer", request = "variables", resource_name = "variable" ) ) gtmVariables <- R6Class( "gtmVariables", inherit = .gtmCollection, private = list( entity_class = gtmVariable ) ) gtmContainerVersion <- R6Class( "gtmContainerVersion", inherit = .gtmResource, public = list( deleted = NA, notes = NA, container = NA, macro = NA, rule = NA, tag = NA, trigger = NA, variable = NA, fingerprint = NA ), private = list( parent_class_name = "gtmContainer", request = "versions", resource_name = "containerVersion" ) ) gtmContainerVersions <- R6Class( "gtmContainerVersions", inherit = .gtmCollection, private = list( entity_class = gtmContainerVersion, collection_name = "containerVersion" ) )
load_nrrd <- function(filename, mask_filename = NULL, keep_mask_values = 1, switch_z = TRUE, crop_in = TRUE, replace_in = TRUE, center_in = FALSE, zero_value = NULL, min_to = -1024, verbose_in = TRUE, origin_in = NULL, ReadByteAsRaw_in = "unsigned", ... ) { if(verbose_in) {message(paste0("LOADING nrrd FILES FROM: ", filename, "\n"))} dcmImages <- nat::read.nrrd(filename, Verbose = verbose_in, origin = origin_in, ReadByteAsRaw = ReadByteAsRaw_in, AttachFullHeader = FALSE) data <- dcmImages RIA_image <- list(data = NULL, header = list(), log = list()) if(length(dim(data)) == 3 | length(dim(data)) == 2) {class(RIA_image) <- append(class(RIA_image), "RIA_image") } else {stop(paste0("nrrd LOADED IS ", length(dim(data)), " DIMENSIONAL. ONLY 2D AND 3D DATA ARE SUPPORTED!"))} if(is.null(zero_value)) zero_value <- min(data, na.rm = TRUE) if(!is.null(mask_filename)) { if(identical(filename, mask_filename)) { if(verbose_in) {message(paste0("CANCELING OUT VALUES OTHER THAN THOSE SPECIFIED IN 'keep_mask_values' PARAMETER \n"))} if(suppressWarnings(any(is.na(as.numeric(keep_mask_values))))) { data[!eval(parse(text = paste0("data", keep_mask_values)))] <- zero_value } else{ data[!data %in% keep_mask_values] <- zero_value } } else { for(i in 1:length(mask_filename)) { mask_filename_i <- mask_filename[i] if(verbose_in) {message(paste0("LOADING nrrd IMAGES OF MASK IMAGE FROM: ", mask_filename_i, "\n"))} dcmImages_mask <- nat::read.nrrd(mask_filename_i, Verbose = verbose_in, origin = origin_in, ReadByteAsRaw = ReadByteAsRaw_in, AttachFullHeader = FALSE) data_mask <- dcmImages_mask if(!all(dim(data) == dim(data_mask))) { stop(paste0("DIMENSIONS OF THE IMAGE AND THE MASK ARE NOT EQUAL!\n", "DIMENSION OF IMAGE: ", dim(data)[1], " ", dim(data)[2], " ", dim(data)[3], "\n", "DIMENSION OF MASK: ", dim(data_mask)[1], " ", dim(data_mask)[2], " ", dim(data_mask)[3], "\n")) } else { if(switch_z) {data_mask[,,dim(data_mask)[3]:1] <- data_mask message("MASK IMAGE WAS TRANSFORMED TO ACHIEVE PROPER ORIENTATION OF THE ORIGINAL AND THE MASK IMAGE.\n") } if(suppressWarnings(any(is.na(as.numeric(keep_mask_values))))) { data[!eval(parse(text = paste0("data_mask", keep_mask_values)))] <- zero_value } else{ data_mask[!(data_mask %in% keep_mask_values)] <- NA if(i == 1) { data_mask_all <- data_mask }else { data_mask_all[is.na(data_mask_all)] <- data_mask[is.na(data_mask_all)] } } } } if(suppressWarnings(!any(is.na(as.numeric(keep_mask_values))))) { data[!(data_mask_all %in% keep_mask_values)] <- zero_value } } } RIA_image$data$orig <- data RIA_image$data$modif <- NULL class(RIA_image$header) <- append(class(RIA_image$header), "RIA_header") class(RIA_image$data) <- append(class(RIA_image$data), "RIA_data") class(RIA_image$log) <- append(class(RIA_image$log), "RIA_log") RIA_image$log$events <- "Created" RIA_image$log$orig_dim <- dim(data) RIA_image$log$directory <- filename if(!is.null(mask_filename)) { if(identical(filename, mask_filename)) { RIA_image$log$events <- paste0("Filtered_using_values_", paste0(keep_mask_values, collapse = "_")) } else { RIA_image$log$events <- paste0("Filtered_using_mask_values_", paste0(keep_mask_values, collapse = "_")) } } if(crop_in) { if(verbose_in) {message(paste0("SMALLEST VALUES IS ", zero_value, ", AND WILL BE CONSIDERED AS REFERENCE POINT TO IDENTIFY VOXELS WITHOUT ANY SIGNAL\n"))} if(verbose_in & center_in == FALSE) message(paste0("MIGHT CONSIDER RESCALING, SINCE SMALLEST VALUE IS NOT -1024, AND THUS VOXEL VALUES MIGHT NOT BE CORRECT\n")) RIA_image <- crop(RIA_image, zero_value, write_orig = TRUE, verbose_in = verbose_in) } if(replace_in) { if(verbose_in) {message(paste0("SMALLEST VALUES IS ", zero_value, ", AND WILL CHANGE TO NA\n"))} RIA_image <- change_to(RIA_image, zero_value_in = zero_value, verbose_in = verbose_in) } if(center_in & (min(data, na.rm = T) != min_to)) { if(verbose_in) {message(paste0("SMALLEST VALUES IS not ", min_to, " THEREFORE SHIFTING VALUES TO ACHIVE THIS\n"))} RIA_image <- shift_to(RIA_image, to = min_to, min_value_in = zero_value, verbose_in = verbose_in) } header <- create_header_nrrd(filename) RIA_image$header <- header xy_dim <- as.numeric(RIA_image$header$PixelSpacing) z_dim <- as.numeric(RIA_image$header$SpacingBetweenSlices) RIA_image$log$orig_vol_mm <- volume(RIA_image$data$orig, xy_dim = xy_dim, z_dim = z_dim) RIA_image$log$orig_surf_mm <- surface(RIA_image$data$orig, xy_dim = xy_dim, z_dim = z_dim) RIA_image$log$surface_volume_r <- ifelse(RIA_image$log$orig_vol_mm != 0, RIA_image$log$orig_surf_mm/RIA_image$log$orig_vol_mm, 0) RIA_image$log$orig_xy_dim <- xy_dim RIA_image$log$orig_z_dim <- z_dim if(verbose_in) {message(paste0("SUCCESSFULLY LOADED ", RIA_image$header$PatientsName, "'s nrrd IMAGES TO RIA IMAGE CLASS\n"))} data_NA <- as.vector(RIA_image$data$orig) data_NA <- data_NA[!is.na(data_NA)] if(length(data_NA) == 0) {message("WARNING: RIA_image$data DOES NOT CONTAIN ANY DATA!!!\n")} return(RIA_image) }
cxr_competitive_response <- function(pair_matrix){ if(all(pair_matrix>=0)){ return(sqrt((pair_matrix[2,1]/pair_matrix[1,1]) * (pair_matrix[2,2]/pair_matrix[1,2]))) }else{ return(NA_real_) } }
plot_mir_new <- function(df, threshold = 1, start = NULL, end = NULL, colour = "steelblue3", col.mir = miRNA, col.year = Year, title = NULL) { if(!threshold >= 1) { stop("'threshold' must be >= 1.") } if(is.null(title)) { title <- "Number of new miRNAs per year" } if(is.null(start)) { start <- df %>% dplyr::select({{col.year}}) %>% dplyr::pull() %>% min() } if(is.null(end)) { end <- df %>% dplyr::select({{col.year}}) %>% dplyr::pull() %>% max() } df_ <- df %>% dplyr::add_count({{col.year}}, {{col.mir}}) %>% dplyr::filter(n >= threshold) %>% dplyr::group_by({{col.mir}}) %>% dplyr::summarise(first_mentioned = min({{col.year}})) %>% dplyr::add_count(first_mentioned, name = "new_miRNAs") %>% dplyr::select(first_mentioned, new_miRNAs) %>% dplyr::distinct() %>% dplyr::filter(dplyr::between(first_mentioned, start, end)) df_empty <- data.frame(first_mentioned = seq(start, end, by = 1), stringsAsFactors = FALSE) %>% dplyr::as_tibble() df_plot <- df_empty %>% dplyr::left_join(df_, by = "first_mentioned") %>% dplyr::mutate(new_miRNAs = ifelse(is.na(new_miRNAs), 0, new_miRNAs)) plot <- ggplot(df_plot, aes(x = factor(first_mentioned), y = new_miRNAs)) + geom_col(fill = colour) + theme_classic() + xlab("Year") + ylab(" labs(caption = paste("Threshold: ", threshold)) + ggtitle(title) plot <- pretty_breaks_miretrieve(plot, df_plot$new_miRNAs) return(plot) } plot_mir_development <- function(df, mir, start = NULL, end = NULL, linetype = "miRNA", alpha = 0.8, width = 0.3, col.mir = miRNA, col.year = Year, title = NULL) { if(is.null(start)) { start <- df %>% dplyr::select({{col.year}}) %>% dplyr::pull() %>% min() } if(is.null(end)) { end <- df %>% dplyr::select({{col.year}}) %>% dplyr::pull() %>% max() } if(!is.numeric(start) | !is.numeric(end)) { stop("'start' and 'end' must be numeric.") } if(is.null(title)) { title <- paste0("Development of ", paste(mir, collapse = ", "), " in PubMed abstracts") } df_empty <- expand.grid(mir, seq(start, end, by = 1), 0, stringsAsFactors = FALSE) %>% dplyr::as_tibble() %>% dplyr::rename({{col.mir}} := Var1, {{col.year}} := Var2) df_ <- df %>% dplyr::select({{col.mir}}, {{col.year}}) %>% dplyr::filter({{col.mir}} %in% mir) %>% dplyr::add_count({{col.mir}}, {{col.year}}, name = "n") df_plot <- dplyr::left_join(df_empty, df_) %>% dplyr::mutate(n = ifelse(is.na(n), 0, n)) plot <- ggplot(df_plot, aes(x = factor({{col.year}}), y = n, col = {{col.mir}}, group = {{col.mir}})) + theme_classic() + scale_y_continuous(limits = c(0, as.integer(max(df_$n) + 2)), expand = c(0.01,0.01), breaks = function(x) unique(floor(pretty(seq(0, (max(x) + 1) * 1.1))))) + xlab("Year") + ylab("Mentioned in labs(color = "microRNA") + ggtitle(title) if(linetype == "miRNA") { plot <- plot + geom_line(alpha = alpha, position=position_dodge(width=width), aes(linetype = {{col.mir}})) + scale_linetype(guide = FALSE) } else { plot <- plot + geom_line(alpha = alpha, position=position_dodge(width=width), linetype = linetype) } return(plot) }
context("test-other_helpers") set.seed(1234) x <- c(1, 5, -1, 2) G1 <- matrix(nrow = 1, ncol = 2) G2 <- matrix(nrow = 1, ncol = 1) G3 <- matrix(nrow = 3, ncol = 3) test_that("unif works", { expect_equal(unif(x), c(2/5, 4/5, 1/5, 3/5)) }) test_that("dim_Gamma works", { expect_error(dim_Gamma(G1)) expect_equal(dim_Gamma(G2), 1) expect_equal(dim_Gamma(G3), 3) }) test_that("select_edges works", { small_graph <- igraph::make_empty_graph(n = 4, directed = FALSE) small_graph <- igraph::add_edges(small_graph, c(1, 2, 2, 3, 2, 4)) expect_equal(select_edges(small_graph), rbind(c(1, 3), c(1, 4), c(3, 4))) })