code
stringlengths
1
13.8M
tau2h_ml <- function(y, se, maxiter = 100) { tau2h <- tau2h_dl(y, se)$tau2h r <- 0 autoadj <- 0 stepadj <- 0.5 while(1) { wi <- (se^2 + tau2h)^-1 ti <- sum(wi^2 * ((y - sum(wi*y)/sum(wi))^2 - se^2)) / sum(wi^2) if (ti <= 0) { tau2h <- 0.0 break } else { if (abs(ti - tau2h)/(1.0 + tau2h) < 1e-5) { break } else if (r == maxiter && autoadj == 1) { stop("The heterogeneity variance (tau^2) could not be calculated.") break } else if (r == maxiter && autoadj == 0) { r <- 0 autoadj <- 1 } else if (autoadj == 1) { r <- r + 1 tau2h <- tau2h + (ti - tau2h)*stepadj } else { r <- r + 1 tau2h <- ti } } } return(list(tau2h = tau2h)) }
test_that("predict method works", { task = tsk("sonar") lrn = lrn("classif.featureless")$train(task) newdata = task$data(1:3) expect_factor(predict(lrn, newdata = newdata), len = 3) expect_factor(predict(lrn, newdata = newdata, predict_type = "response"), len = 3) expect_error(predict(lrn, newdata = newdata, predict_type = "prob"), "'prob'") lrn = lrn("classif.featureless", predict_type = "prob")$train(task) expect_factor(predict(lrn, newdata = newdata), len = 3) expect_factor(predict(lrn, newdata = newdata, predict_type = "response"), len = 3) expect_matrix(predict(lrn, newdata = newdata, predict_type = "prob"), nrows = 3, ncols = 2) expect_true(uniqueN(predict(lrn, newdata, method = "mode")) == 1L) }) test_that("missing predictions are handled gracefully / classif", { task = tsk("sonar") learner = lrn("classif.debug", predict_missing = 1, predict_missing_type = "na", predict_type = "prob") learner$train(task) p = learner$predict(task) expect_factor(p$response, levels = task$class_names) expect_true(all(is.na(p$response))) expect_true(all(is.na(p$prob))) expect_error(p$score(), "missing") learner = lrn("classif.debug", predict_missing = 0.5, predict_missing_type = "omit", predict_type = "prob") learner$train(task) expect_error(learner$predict(task), "observations") }) test_that("missing predictions are handled gracefully / regr", { task = tsk("mtcars") learner = lrn("regr.debug", predict_missing = 1, predict_missing_type = "na", predict_type = "se") learner$train(task) p = learner$predict(task) expect_numeric(p$response) expect_numeric(p$se) expect_true(all(is.na(p$response))) expect_true(all(is.na(p$se))) expect_error(p$score(), "missing") learner = lrn("regr.debug", predict_missing = 0.5, predict_missing_type = "omit", predict_type = "se") learner$train(task) expect_error(learner$predict(task), "observations") }) test_that("predict_newdata with weights ( task = tsk("boston_housing") task$set_col_roles("nox", "weight") learner = lrn("regr.featureless") learner$train(task) expect_prediction(learner$predict(task)) expect_prediction(learner$predict_newdata(task$data())) expect_prediction(learner$predict_newdata(task$data(cols = c(task$target_names, task$feature_names, "nox")))) }) test_that("parallel predict works", { skip_if_not_installed("future") task = tsk("sonar") lrn = lrn("classif.featureless")$train(task) lrn$parallel_predict = FALSE p1 = lrn$predict(task, row_ids = 20:1) lrn$parallel_predict = TRUE p2 = with_future(future::multisession, lrn$predict(task, row_ids = 20:1) ) expect_equal(as.data.table(p1), as.data.table(p2)) })
genwhisker<-function(x,y=NA,input="openair",method="mqm",pollutant=NA,distr="norm",by.years=FALSE,col=" quantile05<-function(x) { quantile(x, 0.05, names=FALSE, na.rm=TRUE) } quantile25<-function(x) { quantile(x, 0.25, names=FALSE, na.rm=TRUE) } quantile75<-function(x) { quantile(x, 0.75, names=FALSE, na.rm=TRUE) } quantile95<-function(x) { quantile(x, 0.95, names=FALSE, na.rm=TRUE) } trimean<-function(x) { (quantile25+2*median(x,na.rm=TRUE)+quantile75)/4 } if (class(x)=="data.frame"&input=="genasis") { compounds<-as.character(unique(x[,2])) initial<-as.numeric(substr(min(gendate(x[,3]),na.rm=TRUE)+(min(gendate(x[,4]),na.rm=TRUE)-min(gendate(x[,3]),na.rm=TRUE))/2,1,4)) final<-as.numeric(substr(max(gendate(x[,4]),na.rm=TRUE)-(max(gendate(x[,4]),na.rm=TRUE)-max(gendate(x[,3]),na.rm=TRUE))/2,1,4)) } if (class(x)=="data.frame"&input=="openair") { compounds<-colnames(x)[-which(is.element(colnames(x),c("date","date_end","temp","wind","note")))] x[,"date"]<-gendate(x[,"date"]) if (is.element("date_end",colnames(x))) { x[,"date_end"]<-gendate(x[,"date_end"]) initial<-as.numeric(substr(min(x[,"date"],na.rm=TRUE)+(min(x[,"date_end"],na.rm=TRUE)-min(x[,"date"],na.rm=TRUE))/2,1,4)) final<-as.numeric(substr(max(x[,"date_end"],na.rm=TRUE)-(max(x[,"date_end"],na.rm=TRUE)-max(x[,"date"],na.rm=TRUE))/2,1,4)) } else { initial<-min(as.numeric(substr(x[,"date"],1,4)),na.rm=TRUE) final<-max(as.numeric(substr(x[,"date"],1,4)),na.rm=TRUE) } } if (class(x)!="data.frame") { compounds<-NA initial<-min(as.numeric(substr(gendate(y),1,4)),na.rm=TRUE) final<-max(as.numeric(substr(gendate(y),1,4)),na.rm=TRUE) } if (length(pollutant)==1) { if(is.na(pollutant)|pollutant=="") { pollutant<-compounds } } if (class(x)=="data.frame") { compos<-pollutant[which(is.element(pollutant,compounds))] if (length(pollutant)>length(compos)) { warning(paste0("One or more pollutants (",pollutant[which(!is.element(pollutant,compos))],") was not recognized.")) } } else { compos<-pollutant } if (class(x)=="data.frame"&input=="genasis") { valu <-as.numeric(x[,1]) comp <-as.character(x[,2]) date_start<-gendate(x[,3]) date_end <-gendate(x[,4]) } if (class(x)=="data.frame"&input=="openair") { valu <-c() comp <-c() date_start<-c() date_end <-c() for (compound in compos) { valu <-c(valu,as.numeric(x[,compound])) comp <-c(comp,as.character(rep(compound,nrow(x)))) date_start<-as.Date(c(as.character(date_start),as.character(x[,"date"]))) if (is.element("date_end",colnames(x))) { date_end<-as.Date(c(as.character(date_end),as.character(x[,"date_end"])))} else { date_end<-as.Date(c(as.character(date_end),as.character(x[,"date"]))) } } } if (class(x)!="data.frame") { valu <-x comp <-rep(pollutant,length(x)) date_start<-gendate(y) date_end <-gendate(y) } date<-as.Date((as.numeric(date_start)+as.numeric(date_end))/2,origin="1970-01-01") if (distr=="lnorm") { valu<-log(valu) } highest<-max(valu,na.rm=TRUE) lowest<-min(valu,na.rm=TRUE) unit<-(highest-lowest)/100 if(method=="mqm") { f1<-"median" f2<-"quantile25" f3<-"quantile75" f4<-"min" f5<-"max" } if(method=="tqm") { f1<-"trimean" f2<-"quantile25" f3<-"quantile75" f4<-"min" f5<-"max" } if(method=="mqq") { f1<-"median" f2<-"quantile25" f3<-"quantile75" f4<-"quantile05" f5<-"quantile95" } par(mar=c(9,4,4,2),mfrow=c(1,1)) if (distr=="lnorm") { if (by.years==TRUE&legend==TRUE) { plot(c(1:(length(compos)+1)),c(rep(lowest,length(compos)),highest+0.2*(highest-lowest)),cex=0,xaxt="n",yaxt="n",xlab=xlab,ylab=ylab,main=main) } else { plot(c(1:(length(compos)+1)),c(rep(lowest,length(compos)),highest),cex=0,xaxt="n",yaxt="n",xlab=xlab,ylab=ylab,main=main) } axis(2,at=axis(2,labels=NA),round(exp(axis(2,labels=NA)),2)) } else { if (by.years==TRUE&legend==TRUE) { plot(c(1:(length(compos)+1)),c(rep(lowest,length(compos)),highest+0.2*(highest-lowest)),cex=0,xaxt="n",xlab=xlab,ylab=ylab,main=main) } else { plot(c(1:(length(compos)+1)),c(rep(lowest,length(compos)),highest),cex=0,xaxt="n",xlab=xlab,ylab=ylab,main=main) } } axis(1,at=c(1:length(compos)+0.5),labels=compos,las=2) for (compound in compos) { if (class(x)=="data.frame") { i<-which(compos==compound) } else { i<-1 } svalu<-valu[which(comp==compound)] scomp<-comp[which(comp==compound)] sdate<-date[which(comp==compound)] if (class(x)!="data.frame") { svalu<-valu scomp<-pollutant sdate<-y } valid<-which(!is.na(svalu)&!is.na(sdate)) svalu<-svalu[valid] scomp<-scomp[valid] sdate<-sdate[valid] if (by.years==FALSE) { rect(i-0.4+0.5,apply(as.matrix(svalu),2,FUN=f1)-0.5*unit,i+0.4+0.5,apply(as.matrix(svalu),2,FUN=f1)+0.5*unit,border=NA,col=paste0(rgb(t(col2rgb(col)/255)),"84")) rect(i-0.1+0.5,apply(as.matrix(svalu),2,FUN=f3),i+0.1+0.5,apply(as.matrix(svalu),2,FUN=f5)-0.5*unit,border=NA,col=paste0(rgb(t(col2rgb(col)/255)),"60")) rect(i-0.1+0.5,apply(as.matrix(svalu),2,FUN=f4)+0.5*unit,i+0.1+0.5,apply(as.matrix(svalu),2,FUN=f2),border=NA,col=paste0(rgb(t(col2rgb(col)/255)),"60")) rect(i-0.4+0.5,apply(as.matrix(svalu),2,FUN=f2),i+0.4+0.5,apply(as.matrix(svalu),2,FUN=f3),border=NA,col=paste0(rgb(t(col2rgb(col)/255)),"60")) rect(i-0.4+0.5,apply(as.matrix(svalu),2,FUN=f4)-0.5*unit,i+0.4+0.5,apply(as.matrix(svalu),2,FUN=f4)+0.5*unit,border=NA,col=paste0(rgb(t(col2rgb(col)/255)),"60")) rect(i-0.4+0.5,apply(as.matrix(svalu),2,FUN=f5)-0.5*unit,i+0.4+0.5,apply(as.matrix(svalu),2,FUN=f5)+0.5*unit,border=NA,col=paste0(rgb(t(col2rgb(col)/255)),"60")) } if (by.years==TRUE) { if (length(col)!=final-initial+1) { col<-hsv((1:(final-initial+1))/(final-initial+1),1,1) } for (j in initial:final) { ssvalu<-svalu[which(as.numeric(substr(sdate,1,4))==j)] if (length(ssvalu)>0) { rect(i-0.4+0.5,apply(as.matrix(ssvalu),2,FUN=f1)-0.5*unit,i+0.4+0.5,apply(as.matrix(ssvalu),2,FUN=f1)+0.5*unit,border=NA,col=paste0(rgb(t(col2rgb(col[j-initial+1])/255)),"84")) rect(i-0.1+0.5,apply(as.matrix(ssvalu),2,FUN=f3),i+0.1+0.5,apply(as.matrix(ssvalu),2,FUN=f5)-0.5*unit,border=NA,col=paste0(rgb(t(col2rgb(col[j-initial+1])/255)),"60")) rect(i-0.1+0.5,apply(as.matrix(ssvalu),2,FUN=f4)+0.5*unit,i+0.1+0.5,apply(as.matrix(ssvalu),2,FUN=f2),border=NA,col=paste0(rgb(t(col2rgb(col[j-initial+1])/255)),"60")) rect(i-0.4+0.5,apply(as.matrix(ssvalu),2,FUN=f2),i+0.4+0.5,apply(as.matrix(ssvalu),2,FUN=f3),border=NA,col=paste0(rgb(t(col2rgb(col[j-initial+1])/255)),"60")) rect(i-0.4+0.5,apply(as.matrix(ssvalu),2,FUN=f4)-0.5*unit,i+0.4+0.5,apply(as.matrix(ssvalu),2,FUN=f4)+0.5*unit,border=NA,col=paste0(rgb(t(col2rgb(col[j-initial+1])/255)),"60")) rect(i-0.4+0.5,apply(as.matrix(ssvalu),2,FUN=f5)-0.5*unit,i+0.4+0.5,apply(as.matrix(ssvalu),2,FUN=f5)+0.5*unit,border=NA,col=paste0(rgb(t(col2rgb(col[j-initial+1])/255)),"60")) } } if (legend==TRUE) { for (j in (initial:final-initial+1)) { legend((j-1)/(final-initial+1)*length(compos)*0.9+1,highest+0.3*(highest-lowest),(initial:final)[j],horiz=TRUE,text.col=paste0(rgb(t(col2rgb(col[j])/255)),"60"),bty="n") } } } } par(mar=c(5,4,4,2)) }
merge_sistec_rfept <- function(x){ x$sistec_rfept_linked <- dplyr::inner_join(x$sistec, x$rfept, by = c("S_NU_CPF" = "R_NU_CPF")) %>% link_courses() %>% link_ciclos() %>% remove_duplicated_courses() %>% remove_duplicated_link() x$sistec <- dplyr::anti_join(x$sistec, x$sistec_rfept_linked, by = c("S_NU_CPF", "S_CO_CICLO_MATRICULA")) x$rfept <- dplyr::anti_join(x$rfept, x$sistec_rfept_linked, by = c("R_NU_CPF" = "S_NU_CPF", "R_CO_MATRICULA")) x } link_courses <- function(x){ x <- x %>% dplyr::filter(!!sym("R_DT_INICIO_CURSO") == !!sym("S_DT_INICIO_CURSO")) x %>% dplyr::group_by(!!sym("R_NO_CURSO"), !!sym("S_NO_CURSO")) %>% dplyr::tally() %>% dplyr::filter(!!sym("n") > 10) %>% dplyr::rename(S_NO_CURSO_LINKED = !!sym("S_NO_CURSO"), S_QT_ALUNOS_LINKED = !!sym("n")) %>% dplyr::inner_join(x, by = "R_NO_CURSO") %>% dplyr::filter(!!sym("S_NO_CURSO_LINKED") == !!sym("S_NO_CURSO")) %>% dplyr::ungroup() } link_ciclos <- function(x){ ciclos <- x %>% dplyr::group_by(!!sym("S_CO_CICLO_MATRICULA"), !!sym("S_QT_ALUNOS_LINKED")) %>% dplyr::tally() %>% dplyr::arrange(!!sym("S_CO_CICLO_MATRICULA") , dplyr::desc(!!sym("n"))) %>% dplyr::distinct(!!sym("S_CO_CICLO_MATRICULA"), .keep_all = TRUE) dplyr::semi_join(x, ciclos, by = c("S_CO_CICLO_MATRICULA", "S_QT_ALUNOS_LINKED")) } remove_duplicated_courses <- function(x){ courses <- x %>% dplyr::group_by(!!sym("R_NO_CURSO"), !!sym("S_NO_CURSO")) %>% dplyr::tally() %>% dplyr::filter(!!sym("n") > 8) dplyr::semi_join(x, courses, by = c("R_NO_CURSO", "S_NO_CURSO")) } remove_duplicated_link <- function(x){ duplicated_link <- x %>% dplyr::group_by(!!sym("S_NU_CPF"), !!sym("R_CO_MATRICULA")) %>% dplyr::tally() %>% dplyr::filter(!!sym("n") > 1) dplyr::anti_join(x, duplicated_link, by = c("S_NU_CPF", "R_CO_MATRICULA")) } complete_campus <- function(x){ dplyr::mutate(x, R_NO_CAMPUS = ifelse(!!sym("R_NO_CAMPUS") == "SEM CAMPUS", !!sym("S_NO_CAMPUS"), !!sym("R_NO_CAMPUS"))) }
rmcol.folder <- function(object, name) { if (!is.folder(object)) stop("rmcol.folder applies to an object of class 'folder'.") xf <- lapply(object, function(x)x[!(colnames(x) %in% name)]) attributes(xf) <- attributes(object) return(xf) }
context("findvar") test_that("findvar_fun", { expect_that(findvar_fun(cars)("sp"), is_equivalent_to("speed")) expect_that(findvar_fun(iris)("petal"), is_equivalent_to(c("Petal.Length", "Petal.Width"))) }) test_that("findvar_in_df", { expect_that(findvar_in_df("sp", cars), is_equivalent_to("speed")) expect_that(findvar_in_df("petal", iris), is_equivalent_to(c("Petal.Length", "Petal.Width"))) }) suppressMessages( test_that("findvar_anywhere", { expect_that(findvar_anywhere("sp"), is_equivalent_to(NULL)) expect_that(findvar_anywhere("petal"), is_equivalent_to(NULL)) expect_that(findvar_anywhere("sp"), shows_message()) expect_that(findvar_anywhere("petal"), shows_message()) }) )
cpg.perm <- function(beta.values,indep,covariates=NULL,nperm,data=NULL,seed=NULL, logit.transform=FALSE,chip.id=NULL,subset=NULL,random=FALSE,fdr.cutoff=.05,fdr.method="BH",large.data=TRUE) { name.holder<-list(deparse(substitute(beta.values)),deparse(substitute(chip.id)),cpg.everything(deparse(substitute(indep)))) if(is.null(ncol(beta.values))) {beta.values<-as.matrix(beta.values)} beta.row<-nrow(beta.values) beta.col<-ncol(beta.values) if(class(covariates)=="formula") { variables<-gsub("[[:blank:]]","",strsplit(as.character(covariates)[2],"+",fixed=TRUE)[[1]]) covariates<-data.frame(eval(parse(text=variables[1]))) names(covariates)=variables[1] if(length(variables)>1) { for(i in 2:length(variables)) { covariates<-cbind(covariates,eval(parse(text=variables[i]))) names(covariates)=variables[1:i] } } } cpg.length(indep,beta.col,covariates, chip.id) if(is.character(indep)) {warnings("\nindep is a character class, converting to factor\n") indep<-as.factor(indep) } if(!is.null(data)){ nameofdata<-deparse(substitute(data)) thecheck<-nameofdata %in% search() if(!thecheck) stop("\nMust attach data before using data option in CpGassoc package", "\nPlease attach and resubmit command\n") } if(is.matrix(covariates)| length(covariates)==length(indep) ) { if(is.character(covariates) & is.matrix(covariates)) { stop("\nCan not analyze data with covariates given.\nNo characters allowed within", " a matrix") } else { covariates<-data.frame(covariates) }} levin<-is.factor(indep) Problems<-which(beta.values<0 |beta.values >1) ob.data<-cpg.assoc(beta.values,indep,covariates,data,logit.transform,chip.id,subset,random,fdr.cutoff,fdr.method=fdr.method,large.data=large.data) ob.data$info$Phenotype<-name.holder[[3]] Min.P.Observed<-ob.data$info[1,1] fdr <- beta.row>= 100 if(fdr.method=="qvalue" & !fdr) { fdr.method="BH" warning("\nCan not perform qvalue method with less than a 100 CpG sites\n") } if(nperm>=100) { perm.pval<-matrix(NA,beta.row,nperm) if(!levin) {perm.tstat<-matrix(NA,beta.row,nperm)} } cpg.everything(complex(1),first=TRUE,logit.transform,Problems,beta.values) if(logit.transform) { beta.values<-as.matrix(beta.values) if (length(Problems)!=0) { beta.values[Problems]<-NA } onevalues<-which(beta.values==1) zerovalues<-which(beta.values==0) if(length(onevalues)>0 | length(zerovalues)>0) { if(length(onevalues)>0) { beta.values[onevalues]<-NA beta.values[onevalues]<-max(beta.values,na.rm=T) } if(length(zerovalues)>0) { beta.values[zerovalues]<-NA beta.values[zerovalues]<-min(beta.values,na.rm=T) } } beta.values=log(beta.values/(1-beta.values)) beta.values<-data.frame(beta.values) } if(!is.null(subset)){ if(!is.null(chip.id)) { chip.id<-chip.id[subset] } beta.values<-beta.values[,subset] indep<-indep[subset] if(!is.null(covariates)) { covariates<-covariates[subset,] } subset=NULL } Permutation <- matrix(nrow = nperm,ncol = 3) compleval<-design(covariates,indep,chip.id,random)[[3]] gc.Permutation<-matrix(nrow=nperm,ncol=3) indep<-indep[compleval] covariates<-data.frame(covariates[compleval,]) if(ncol(covariates)==0 & nrow(covariates)==0) {covariates=NULL} beta.values<-beta.values[,compleval] if(is.null(dim(beta.values))) {beta.values<-as.matrix(beta.values)} chip.id<-chip.id[compleval] for(i in 1:nperm) { if (!is.null(seed)) { set.seed(i*22424-seed) } Perm.var <- sample(indep); answers<-cpg.assoc(beta.values,Perm.var,covariates,data,logit.transform=FALSE ,chip.id,subset,random,fdr.cutoff,fdr.method=fdr.method,logitperm=TRUE,large.data=large.data) if(random) { problems<-sum(is.na(answers$results$P.value)) if (problems>0){ cpg.everything(complex(1),first=FALSE,logit.transform,problems) } } if(nperm>=100 ) { perm.pval[,i]<-answers$results$P.value if(!levin) {perm.tstat[,i]<-answers$results$T.statistic} } Permutation[i,1:3] <- c(answers$info$Min.P.Observed,nrow(answers$Holm.sig),nrow(answers$FDR.sig)) if (fdr.method=="qvalue") { fdr.adj<-tryCatch(qvalue::qvalue(answers$results$gc.p.value), error = function(e) NULL) if(is.null(fdr.adj)) { fdr.adj <- tryCatch(qvalue::qvalue(answers$results$gc.p.value, pi0.method = "bootstrap"), error = function(e) NULL) if(is.null(fdr.adj)) { fdr.method="BH" }}} if(fdr.method!="qvalue") { fdr.adj<-p.adjust(answers$results$gc.p.value,fdr.method) } if(fdr.method=="qvalue"){ fdr.adj<-fdr.adj$qvalue } gc.Permutation[i,1:3]<-c(min(answers$results$gc.p.value,na.rm=TRUE), sum(p.adjust(answers$results$gc.p.value,"holm")<.05), sum(fdr.adj<.05)) rm(answers) gc() } Permutation<-data.frame(Permutation) p.value.p <- sum(Permutation[,1]<=Min.P.Observed)/nperm p.value.holm <- sum(Permutation[,2]>=nrow(ob.data$Holm.sig))/nperm p.value.FDR <- sum(Permutation[,3]>=nrow(ob.data$FDR.sig))/nperm if(is.null(seed)) {seed<-"NULL"} p.value.matrix <- data.frame(p.value.p,p.value.holm,p.value.FDR,nperm,seed) names(Permutation)<-cpg.everything(fdr,perm=TRUE) colnames(gc.Permutation)<-names(Permutation) perm.data<-list(permutation.matrix=Permutation,perm.p.values=p.value.matrix,gc.permutation.matrix=gc.Permutation) perm.data<-append(perm.data,ob.data) names(perm.data)<-c("permutation.matrix","perm.p.values","gc.permutation.matrix",names(ob.data)) if(nperm>=100) { perm.pval<-apply(perm.pval,2,sort) perm.pval<- -log(perm.pval,base=10) perm.data$perm.pval<-t(apply(perm.pval,1,quantile,probs=c(.025,.975))) if(!levin ) { perm.tstat<-apply(perm.tstat,2,sort) perm.data$perm.tstat<-t(apply(perm.tstat,1,quantile,probs=c(.025,.975))) }} perm.data$info$betainfo<-name.holder[[1]] rm(Permutation,ob.data,p.value.matrix) gc() class(perm.data)<-"cpg.perm" perm.data }
context("Testing random.estimate()") set.seed(100) n= 10000 tolerance=3/sqrt(n) test_that("3d - standard normal distribution (correlated) is generated correctly from the 0.05 and 0.95 quantiles", { profitEstimate<-estimate_read_csv("profit-4.csv") meanProductPrice <- mean(c(profitEstimate$marginal["productprice","lower"], profitEstimate$marginal["productprice","upper"]) ) meanCostPrice <- mean(c(profitEstimate$marginal["costprice","lower"], profitEstimate$marginal["costprice","upper"]) ) meanSales <- mean(c(profitEstimate$marginal["sales","lower"], profitEstimate$marginal["sales","upper"]) ) mean <- c(productprice=meanProductPrice, costprice=meanCostPrice, sales=meanSales) sdProductPrice <- 0.5 * (profitEstimate$marginal["productprice","upper"] - profitEstimate$marginal["productprice","lower"]) / qnorm(0.95) sdCostPrice <- 0.5 * (profitEstimate$marginal["costprice","upper"] - profitEstimate$marginal["costprice","lower"]) / qnorm(0.95) sdSales <- 0.5 * (profitEstimate$marginal["sales","upper"] - profitEstimate$marginal["sales","lower"]) / qnorm(0.95) sd <- c(productprice=sdProductPrice, costprice=sdCostPrice, sales=sdSales) cor<-corMat(profitEstimate) x<-random(rho=profitEstimate,n=n) expect_equal(colMeans(x), mean, tolerance=tolerance) expect_equal(apply(X=x, MARGIN=2, sd), sd, tolerance=tolerance) expect_equal(cor(x),cor, tolerance=0.05) })
chrom <- function(c){ p <- length(c) P <- matrix(0,p,p) I <- p*seq(from = 0, to = (p-1), by = 1)+c P[I] <- 1 return(P) }
context("Penalty matrices") test_that("Penalty matrix for Lasso", { expect_equal(.pen.mat.lasso(5), diag(5)) }) test_that("Penalty matrix for Group Lasso", { expect_equal(.pen.mat.grouplasso(6), diag(6)) }) test_that("Penalty matrix for Fused Lasso", { expect_equal(.pen.mat.flasso(4), rbind(c(1, 0, 0, 0), c(-1, 1, 0, 0), c(0, -1, 1, 0), c(0, 0, -1, 1))) expect_equal(.pen.mat.flasso(4, refcat = 3), rbind(c(-1, 1, 0, 0), c(0, -1, 0, 0), c(0, 0, 1, 0), c(0, 0, -1, 1))) }) test_that("Penalty matrix for Generalized Fused Lasso", { a <- .pen.mat.gflasso(4) dimnames(a) <- NULL expect_equal(a, rbind(c(1, 0, 0, 0), c(-1, 1, 0, 0), c(0, -1, 1, 0), c(0, 0, -1, 1), c(0, 1, 0, 0), c(-1, 0, 1, 0), c(0, -1, 0, 1), c(0, 0, 1, 0), c(-1, 0, 0, 1), c(0, 0, 0, 1))) b <- .pen.mat.gflasso(4, refcat = FALSE) dimnames(b) <- NULL expect_equal(b, rbind(c(-1, 1, 0, 0), c(0, -1, 1, 0), c(0, 0, -1, 1), c(-1, 0, 1, 0), c(0, -1, 0, 1), c(-1, 0, 0, 1))) }) test_that("Penalty matrix for 2D Fused Lasso", { expect_equal(.pen.mat.2dflasso(3, 2), rbind(c(1, 0, 0, 0, 0, 0), c(-1, 1, 0, 0, 0, 0), c(-1, 0, 0, 1, 0, 0), c(0, 1, 0, 0, 0, 0), c(0, -1, 1, 0, 0, 0), c(0, -1, 0, 0, 1, 0), c(0, 0, 1, 0, 0, 0), c(0, 0, -1, 0, 0, 1), c(0, 0, 0, 1, 0, 0), c(0, 0, 0, -1, 1, 0), c(0, 0, 0, 0, -1, 1))) }) test_that("Penalty matrix for Graph-Guided Fused Lasso", { adj <- matrix(0, 10, 10) adj[1, 2] <- adj[2, 1] <- 1 adj[2, 3] <- adj[3, 2] <- 1 adj[2, 5] <- adj[5, 2] <- 1 adj[1, 3] <- adj[3, 1] <- 1 adj[6, 7] <- adj[7, 6] <- 1 pen.exp <- matrix(0, 5, 9) pen.exp[1, 1] <- 1 pen.exp[2, 2] <- 1 pen.exp[3, 1] <- -1; pen.exp[3, 2] <- 1 pen.exp[4, 1] <- -1; pen.exp[4, 4] <- 1 pen.exp[5, 5] <- -1; pen.exp[5, 6] <- 1 expect_equal(.pen.mat.ggflasso(adj), pen.exp) pen.exp2 <- matrix(0, 5, 9) pen.exp2[1, 2] <- 1 pen.exp2[2, 1] <- -1; pen.exp2[2, 2] <- 1 pen.exp2[3, 1] <- -1; pen.exp2[3, 3] <- 1 pen.exp2[4, 2] <- -1; pen.exp2[4, 3] <- 1 pen.exp2[5, 5] <- -1; pen.exp2[5, 6] <- 1 expect_equal(.pen.mat.ggflasso(adj, refcat = 5), pen.exp2) })
Compute.Model<-function( tree, utilities, weights ) { model<-NULL criteria<-1:length( V(tree) ) index<-which( V(tree)$leaf == 1 ) with( utilities, { for ( i in criteria ) { nl<-unlist( neighborhood( tree, 100, V(tree)[i], mode = 'out' ) ) code<-V(tree)[ nl[ nl %in% index ] ]$code W<-weights[ code ] RW<-W / sum( W ) uname<-paste( 'u', code, sep = '' ) u<-utilities[ , list( utility = unlist( lapply( .SD * W, sum ) ), relative.utility = unlist( lapply( .SD * RW, sum ) ) ), by = cod, .SDcols = uname ] u<-u[ , list( utility = sum( utility ), relative.utility = sum( relative.utility ) ), by = cod ] u[ , id := V(tree)[i]$id ] u[ , index := ifelse( V(tree)[i]$code == 0, NA, V(tree)[i]$code ) ] u[ , deep := V(tree)[i]$deep ] u[ , weight := V(tree)[i]$weight ] u[ , relative.weight := V(tree)[i]$rweight ] u[ , name := V(tree)[i]$name ] u<-u[ , list( id, name, cod, index, deep, utility, relative.utility, weight, relative.weight ) ] model<-rbind( model, u ) } return( model ) }) }
httpget_session_tar <- function(sessionpath, requri){ setwd(sessionpath); tmptar <- tempfile(fileext=".tar.gz"); utils::tar(tmptar, files=".", compression="gzip"); res$setbody(file=tmptar); res$setheader("Content-Type", "application/x-gzip") res$setheader("Content-Disposition", paste('attachment; filename="', basename(sessionpath), '.tar.gz"', sep="")); res$finish(); }
find_course <- function(course){ file.path(find.package("swirl"), "Courses", gsub(" ", "_", course)) } display_swirl_file <- function(filename, course, lesson=""){ fname <- filename if(lesson != "")fname <- file.path(lesson, filename) loc <- gsub(" ", "_", file.path( find_course(course), fname)) toloc <- file.path("swirl_temp", filename) if(!file.exists("swirl_temp"))dir.create("swirl_temp") file.copy(loc, "swirl_temp", overwrite=TRUE) if(isTRUE(1 == grep("*[.]R$", filename))){ file.edit(toloc, title=filename) } else { file.show(toloc, title=filename) } message(paste("(Se ha copiado el archivo", filename, "a la ruta", file.path(getwd(), toloc), ").")) } display_swirl_file("distributions.txt", "programacion-estadistica-r", "Simulacion")
print.summary.Lifedata.MLE <- function(x,...){ cat("Call:\n") print(x$call) cat("\n") cat("Parameters:\n") print(x$coefmat) cat("\n") cat("Loglikelihod:\n") print(as.numeric(-x$min)) cat("\n") cat("Covariance matrix:\n") print(x$vcov) cat("\n") cat("Survival probability:\n") print(x$surv) }
ly_hexbin <- function( fig, x, y = NULL, data = figure_data(fig), xbins = 30, shape = 1, xbnds = NULL, ybnds = NULL, style = "colorscale", trans = NULL, inv = NULL, lname = NULL, palette = "RdYlGn11", line = FALSE, alpha = 1, hover = TRUE ) { args <- sub_names(fig, data, grab( x, y, xbins, shape, hover, line, alpha, dots = lazy_dots() ), process_data_and_names = FALSE ) minarea <- 0.04; maxarea <- 0.8; mincnt <- 1; maxcnt <- NULL if (!inherits(args$data$x, "hexbin")) { xy_names <- get_xy_names(args$data$x, args$data$y, deparse(substitute(x)), deparse(substitute(y)), NULL) xy <- get_xy_data(args$data$x, args$data$y) args$data$x <- xy$x args$data$y <- xy$y args$info$x_name <- xy_names$x args$info$y_name <- xy_names$y hbd <- get_hexbin_data(x = xy$x, y = xy$y, xbins = xbins, shape = shape, xbnds = xbnds, ybnds = ybnds) } else { args$info$x_name <- "x" args$info$y_name <- "y" hbd <- args$data$x } hbd <- get_from_hexbin(hbd, maxcnt = maxcnt, mincnt = mincnt, trans = trans, inv = inv, style = style, minarea = minarea, maxarea = maxarea) if (is.character(palette)) { if (valid_color(palette)) { col <- palette } else { if (!palette %in% bk_gradient_palette_names) stop( "'palette' specified in ly_hexbin is not a valid color name or palette ", "- see here: https://docs.bokeh.org/en/latest/docs/reference/palettes.html", call. = FALSE) palette <- colorRampPalette(bk_gradient_palettes[[palette]]) } } if (is.function(palette)) { colorcut <- seq(0, 1, length = 100) colgrp <- cut(hbd$rcnt, colorcut, labels = FALSE, include.lowest = TRUE) clrs <- palette(length(colorcut) - 1) col <- clrs[colgrp] } if (args$info$x_name == args$info$y_name) { args$info$x_name <- paste(args$info$x_name, "(x)") args$info$y_name <- paste(args$info$y_name, "(y)") } names(hbd$data)[1:2] <- c(args$info$x_name, args$info$y_name) if (!line) { line_color <- NA } else { line_color <- col } if (is.logical(hover) && !hover) hbd$data <- NULL fig %>% ly_polygons( xs = hbd$xs, ys = hbd$ys, color = NULL, fill_color = col, alpha = NULL, fill_alpha = args$params$alpha, line_color = line_color, hover = hbd$data, xlab = args$info$x_name, ylab = args$info$y_name, lname = lname ) } get_hexbin_data <- function(x, y, xbins = 30, shape = 1, xbnds = range(x, na.rm = TRUE), ybnds = range(y, na.rm = TRUE)) { if (is.null(xbnds)) xbnds <- range(x, na.rm = TRUE) if (is.null(ybnds)) ybnds <- range(y, na.rm = TRUE) ind <- stats::complete.cases(x, y) hexbin(x[ind], y[ind], shape = shape, xbins = xbins, xbnds = xbnds, ybnds = ybnds) } get_from_hexbin <- function(dat, maxcnt = NULL, mincnt = 1, trans = identity, inv = identity, maxarea = 0.8, minarea = 0.04, style = style) { cnt <- dat@count xbins <- dat@xbins shape <- dat@shape tmp <- hcell2xy(dat) if (is.null(maxcnt)) maxcnt <- max(dat@count) ok <- cnt >= mincnt & cnt <= maxcnt xnew <- tmp$x[ok] ynew <- tmp$y[ok] cnt <- cnt[ok] sx <- xbins / diff(dat@xbnds) sy <- (xbins * shape) / diff(dat@ybnds) if (is.null(trans)) { if (min(cnt, na.rm = TRUE) < 0) { pcnt <- cnt + min(cnt) rcnt <- { if (maxcnt == mincnt) rep.int(1, length(cnt)) else (pcnt - mincnt) / (maxcnt - mincnt) } } else rcnt <- { if (maxcnt == mincnt) rep.int(1, length(cnt)) else (cnt - mincnt) / (maxcnt - mincnt) } } else { rcnt <- (trans(cnt) - trans(mincnt)) / (trans(maxcnt) - trans(mincnt)) if (any(is.na(rcnt))) stop("bad count transformation") } if (style == "lattice") { area <- minarea + rcnt * (maxarea - minarea) area <- pmin(area, maxarea) radius <- sqrt(area) } else { radius <- rep(1, length(xnew)) } inner <- 0.5 outer <- (2 * inner) / sqrt(3) dx <- inner / sx dy <- outer / (2 * sy) hex_c <- hexcoords(dx, dy, sep = NULL) xs <- lapply(seq_along(xnew), function(i) hex_c$x * radius[i] + xnew[i]) ys <- lapply(seq_along(xnew), function(i) hex_c$y * radius[i] + ynew[i]) list(xs = xs, ys = ys, data = data.frame(x = xnew, y = ynew, count = cnt), rcnt = rcnt) }
pdb_make_proto_ipm <- function(pdb, ipm_id = NULL, det_stoch = "det", kern_param = "kern") { if(!is.null(ipm_id)) { pdb <- lapply(pdb, function(x, ipm_id) { out <- x[x$ipm_id %in% ipm_id, ] return(out) }, ipm_id = ipm_id) class(pdb) <- c("pdb", "list") } out <- list() unique_ids <- unique(pdb[[1]]$ipm_id) if(length(det_stoch) < length(unique_ids)) { det_stoch <- rep_len(det_stoch, length.out = length(unique_ids)) } if(length(kern_param) < length(det_stoch) && any(det_stoch == "stoch")) { kern_param <- rep_len(kern_param, length.out = length(det_stoch)) kern_param[det_stoch == "det"] <- NA_character_ } for(i in seq_along(unique_ids)) { out[[i]] <- .make_proto(pdb, id = unique_ids[i], det_stoch[i], kern_param[i]) attr(out[[i]], "species_accepted") <- pdb$Metadata$species_accepted[i] names(out)[i] <- unique_ids[i] out[[i]]$id <- unique_ids[i] } class(out) <- c("pdb_proto_ipm_list", "list") return(out) }
haplo.binomial <- function (link = "logit") { save <- binomial() save$initialize <- expression({ if (NCOL(y) == 1) { if (is.factor(y)) y <- y != levels(y)[1L] n <- rep.int(1, nobs) y[weights == 0] <- 0 mustart <- (weights * y + 0.5)/(weights + 1) m <- weights * y } else if (NCOL(y) == 2) { n <- y[, 1] + y[, 2] y <- ifelse(n == 0, 0, y[, 1]/n) weights <- weights * n mustart <- (n * y + 0.5)/(n + 1) } else stop("for the binomial family, y must be a vector of 0 and 1's\n", "or a 2 column matrix where col 1 is no. successes and col 2 is no. failures") }) return(save) }
library(vcfR) data(vcfR_example) my_genind <- vcfR2genind(vcf) class(my_genind) my_genind my_genclone <- poppr::as.genclone(my_genind) class(my_genclone) my_genclone vcf_file <- system.file("extdata", "pinf_sc50.vcf.gz", package = "pinfsc50") vcf <- read.vcfR(vcf_file, verbose = FALSE) x <- vcfR2genlight(vcf) x library(poppr) x <- as.snpclone(x) x vcf_file <- system.file("extdata", "pinf_sc50.vcf.gz", package = "pinfsc50") dna_file <- system.file("extdata", "pinf_sc50.fasta", package = "pinfsc50") gff_file <- system.file("extdata", "pinf_sc50.gff", package = "pinfsc50") vcf <- read.vcfR(vcf_file, verbose = FALSE) dna <- ape::read.dna(dna_file, format="fasta") gff <- read.table(gff_file, sep="\t", quote = "") record <- 130 my_dnabin1 <- vcfR2DNAbin(vcf, consensus = TRUE, extract.haps = FALSE, ref.seq=dna[,gff[record,4]:gff[record,5]], start.pos=gff[record,4], verbose=FALSE) my_dnabin1 par(mar=c(5,8,4,2)) ape::image.DNAbin(my_dnabin1[,ape::seg.sites(my_dnabin1)]) par(mar=c(5,4,4,2)) my_dnabin1 <- vcfR2DNAbin(vcf, consensus=FALSE, extract.haps=TRUE, ref.seq=dna[,gff[record,4]:gff[record,5]], start.pos=gff[record,4], verbose=FALSE) par(mar=c(5,8,4,2)) ape::image.DNAbin(my_dnabin1[,ape::seg.sites(my_dnabin1)]) par(mar=c(5,4,4,2))
scenarioGenerator <- function(n, type = c("none", "up", "updown", "rand1"), nbSeg = 20, jumpSize = 1) { type <- match.arg(type) if (type == "rand1") { set.seed(42) rand1CP <- rpois(nbSeg, lambda = 10) r1 <- pmax(round(rand1CP * n / sum(rand1CP)), 1) s <- sum(r1) if(s > n) { while(sum(r1) > n) { p <- sample(x = nbSeg, size = 1) if(r1[p]> 1){r1[p] <- r1[p] - 1} } } else if(s < n) { for(i in 1:(n-s)) { p <- sample(x = nbSeg, size = 1) r1[p] <- r1[p] + 1 } } set.seed(43) rand1Jump <- runif(nbSeg, min = 0.5, max = 1) * sample(c(-1,1), size = nbSeg, replace = TRUE) } switch( type, none = rep(0, n), up = unlist(lapply(0:(nbSeg-1), function (k) rep(k * jumpSize, n * 1 / nbSeg))), updown = unlist(lapply(0:(nbSeg-1), function(k) rep((k %% 2) * jumpSize, n * 1 / nbSeg))), rand1 = unlist(sapply(1:nbSeg, function(i) rep(rand1Jump[i] * jumpSize, r1[i]))) ) }
summary.test_dim <-function(object, ...){ out0 = object$out0 out1 = object$out1 out = object cat("\nCall:\n") print(out$call) cat("\nTesting dimension output:\n") table = c(round(out0$lk,3),round(out0$aic,3),round(out0$bic,3),round(out0$np,0), round(out1$lk,3),round(out1$aic,3),round(out1$bic,3),round(out1$np,0), round(out$dev,3),out$df,round(out$pv,3)) table = matrix(table,11,1) colnames(table) = "" rownames(table) = c("Log-likelihood of the constrained model","AIC of the constrained model", "BIC of the constrained model","N.parameters of the constrained model", "Log-likelihood of the unconstrained model","AIC of the unconstrained model", "BIC of the unconstrained model","N.parameters of the unconstrained model", "Deviance","Degrees of freedom","p-value") print(table) cat("\n") }
plot.riskRegression <- function(x, cause, newdata, xlab, ylab, xlim, ylim, lwd, col, lty, axes=TRUE, percent=TRUE, legend=TRUE, add=FALSE, ...){ if ("CauseSpecificCox"%in%class(x)) plot.times <- x$eventTimes else plot.times <- x$timeVaryingEffects$coef[,"time"] if (class(x)=="predictedRisk") Y <- split(x$risk,1:NROW(x$risk)) else{ if (missing(newdata)){ ff <- eval(x$call$formula) xdat <- unique(eval(x$call$data)[all.vars(update(ff,NULL~.))]) if (NROW(xdat)<5){ if ("CauseSpecificCox"%in%class(x)){ p1 <- predictRisk(x,newdata=xdat,times=plot.times,cause=cause) } else{ p1 <- stats::predict(x,newdata=xdat,times=plot.times)$risk} rownames(p1) <- paste("id",1:NROW(xdat)) } else{ if ("CauseSpecificCox"%in%class(x)){ P1 <- predictRisk(x,newdata=eval(x$call$data),times=plot.times,cause=cause) } else{ P1 <- stats::predict(x, newdata=eval(x$call$data), times=plot.times)$risk } medianP1 <- P1[,prodlim::sindex(plot.times,median(plot.times))] P1 <- P1[order(medianP1),] p1 <- P1[round(quantile(1:NROW(P1))),] rownames(p1) <- paste("Predicted risk",c("Min","q25","Median","q75","Max"),sep="=") warning("Argument newdata is missing.\n", "Shown are the cumulative incidence curves from the original data set.\nSelected are curves based on individual risk (min,q25,median,q75,max) at the median time:", median(plot.times)) } } else{ p1 <- stats::predict(x,newdata=newdata,time=plot.times)$risk } Y <- lapply(1:NROW(p1),function(i){p1[i,]}) if (!is.null(rownames(p1))) names(Y) <- rownames(p1) } nlines <- NROW(Y) if (missing(ylab)) ylab <- "Cumulative incidence" if (missing(xlab)) xlab <- "Time" if (missing(xlim)) xlim <- c(0, max(plot.times)) if (missing(ylim)) ylim <- c(0, 1) if (missing(lwd)) lwd <- rep(3,nlines) if (missing(col)) col <- 1:nlines if (missing(lty)) lty <- rep(1, nlines) if (length(lwd) < nlines) lwd <- rep(lwd, nlines) if (length(lty) < nlines) lty <- rep(lty, nlines) if (length(col) < nlines) col <- rep(col, nlines) plot.DefaultArgs <- list(x=0,y=0,type = "n",ylim = ylim,xlim = xlim,xlab = xlab,ylab = ylab) lines.DefaultArgs <- list(type="s") axis1.DefaultArgs <- list() axis2.DefaultArgs <- list(at=seq(0,1,.25),side=2) legend.DefaultArgs <- list(legend=names(Y), lwd=lwd, col=col, lty=lty, cex=1.5, bty="n", y.intersp=1.3, x="topleft", trimnames=TRUE) smartA <- prodlim::SmartControl(call= list(...), keys=c("plot","lines","legend","conf.int","marktime","axis1","axis2"), ignore=c("x","type","cause","newdata","add","col","lty","lwd","ylim","xlim","xlab","ylab","legend","marktime","conf.int","automar","atrisk","timeOrigin","percent","axes","atrisk.args","conf.int.args","legend.args"), ignore.case=TRUE, defaults=list("plot"=plot.DefaultArgs, "axis1"=axis1.DefaultArgs, "axis2"=axis2.DefaultArgs, "legend"=legend.DefaultArgs, "lines"=lines.DefaultArgs), forced=list("plot"=list(axes=FALSE), "axis1"=list(side=1)), verbose=TRUE) if (!add) { do.call("plot",smartA$plot) if (axes){ do.call("axis",smartA$axis1) if (percent & is.null(smartA$axis1$labels)) smartA$axis2$labels <- paste(100*smartA$axis2$at,"%") do.call("axis",smartA$axis2) } } lines.type <- smartA$lines$type nix <- lapply(1:nlines, function(s) { lines(x = plot.times, y = Y[[s]], type = lines.type, col = col[s], lty = lty[s], lwd = lwd[s]) }) if(legend[[1]]==TRUE && !add[[1]] && !is.null(names(Y))){ if (all(smartA$legend$trimnames==TRUE) && all(sapply((nlist <- strsplit(names(Y),"=")),function(x)length(x))==2)){ smartA$legend$legend <- sapply(nlist,function(x)x[[2]]) smartA$legend$title <- unique(sapply(nlist,function(x)x[[1]])) } smartA$legend <- smartA$legend[-match("trimnames",names(smartA$legend))] save.xpd <- par()$xpd par(xpd=TRUE) do.call("legend",smartA$legend) par(xpd=save.xpd) } }
"df_tmin"
s2_mask <- function(infiles, maskfiles, mask_type, smooth = 0, buffer = 0, max_mask = 100, outdir = "./masked", tmpdir = NA, rmtmp = TRUE, save_binary_mask = FALSE, format = NA, subdirs = NA, compress = "DEFLATE", bigtiff = FALSE, parallel = FALSE, overwrite = FALSE, .log_message = NA, .log_output = NA) { .s2_mask(infiles = infiles, maskfiles = maskfiles, mask_type = mask_type, smooth = smooth, buffer = buffer, max_mask = max_mask, outdir = outdir, tmpdir = tmpdir, rmtmp = rmtmp, save_binary_mask = save_binary_mask, format = format, subdirs = subdirs, compress = compress, bigtiff = bigtiff, parallel = parallel, overwrite = overwrite, output_type = "s2_mask", .log_message = .log_message, .log_output = .log_output) } .s2_mask <- function(infiles, maskfiles, mask_type = "cloud_medium_proba", smooth = 250, buffer = 250, max_mask = 80, outdir = "./masked", tmpdir = NA, rmtmp = TRUE, save_binary_mask = FALSE, format = NA, subdirs = NA, compress = "DEFLATE", bigtiff = FALSE, parallel = FALSE, overwrite = FALSE, output_type = "s2_mask", .log_message = NA, .log_output = NA) { . <- NULL if (!any(sapply(infiles, file.exists))) { print_message( type="error", if (!all(sapply(infiles, file.exists))) {"The "} else {"Some of the "}, "input files (\"", paste(infiles[!sapply(infiles, file.exists)], collapse="\", \""), "\") do not exists locally; please check file names and paths.") } gdal_formats <- fromJSON( system.file("extdata/settings/gdal_formats.json",package="sen2r") )$drivers if (!is.na(format)) { sel_driver <- gdal_formats[gdal_formats$name==format,] if (nrow(sel_driver)==0) { print_message( type="error", "Format \"",format,"\" is not recognised; ", "please use one of the formats supported by your GDAL installation.\n\n", "To list them, use the following command:\n", "\u00A0\u00A0gdalUtils::gdalinfo(formats=TRUE)\n\n", "To search for a specific format, use:\n", "\u00A0\u00A0gdalinfo(formats=TRUE)[grep(\"yourformat\", gdalinfo(formats=TRUE))]") } } if (is.na(tmpdir)) { tmpdir <- if (all(!is.na(format), format == "VRT")) { if (!missing(outdir)) { autotmpdir <- FALSE file.path(outdir, ".vrt") } else { autotmpdir <- TRUE tempfile(pattern="s2mask_") } } else { autotmpdir <- FALSE tempfile(pattern="s2mask_") } } else { if (dir.exists(tmpdir)) { tmpdir <- file.path(tmpdir, basename(tempfile(pattern="s2mask_"))) } autotmpdir <- FALSE } if (all(!is.na(format), format == "VRT")) { rmtmp <- FALSE } dir.create(tmpdir, recursive=FALSE, showWarnings=FALSE) infiles_meta_sen2r <- sen2r_getElements(infiles, format="data.table") infiles_meta_raster <- raster_metadata(infiles, c("res", "outformat", "unit"), format="data.table") maskfiles_meta_sen2r <- sen2r_getElements(maskfiles, format="data.table") suppressWarnings(outdir <- expand_path(outdir, parent=comsub(infiles,"/"), silent=TRUE)) if (!dir.exists(dirname(outdir))) { print_message( type = "error", "The parent folder of 'outdir' (",outdir,") does not exist; ", "please create it." ) } dir.create(outdir, recursive=FALSE, showWarnings=FALSE) prod_types <- unique(infiles_meta_sen2r$prod_type) if (is.na(subdirs)) { subdirs <- ifelse(length(prod_types)>1, TRUE, FALSE) } if (subdirs) { sapply(file.path(outdir,prod_types), dir.create, showWarnings=FALSE) } if (anyNA(smooth)) {smooth <- 0} if (anyNA(buffer)) {buffer <- 0} if (mask_type == "nomask") { req_masks <- list() } else if (mask_type == "nodata") { req_masks <- list("SCL"=c(0:1)) } else if (mask_type == "cloud_high_proba") { req_masks <- list("SCL"=c(0:1,9)) } else if (mask_type == "cloud_medium_proba") { req_masks <- list("SCL"=c(0:1,8:9)) } else if (mask_type == "cloud_low_proba") { req_masks <- list("SCL"=c(0:1,7:9)) } else if (mask_type == "cloud_and_shadow") { req_masks <- list("SCL"=c(0:1,3,8:9)) } else if (mask_type == "clear_sky") { req_masks <- list("SCL"=c(0:1,3,7:10)) } else if (mask_type == "land") { req_masks <- list("SCL"=c(0:3,6:11)) } else if (grepl("^scl\\_", mask_type)) { req_masks <- list("SCL"=strsplit(mask_type,"_")[[1]][-1]) } if (output_type == "s2_mask") { outfiles <- character(0) outfiles_toomasked <- character(0) } else if (output_type == "perc") { outpercs <- numeric(0) } for (i in seq_along(infiles)) {try({ sel_infile <- infiles[i] sel_infile_meta_sen2r <- c(infiles_meta_sen2r[i,]) sel_infile_meta_raster <- c(infiles_meta_raster[i,]) sel_format <- if (is.na(format)) { sel_infile_meta_raster$outformat } else { format } sel_rmtmp <- ifelse(sel_format == "VRT", FALSE, rmtmp) sel_out_ext <- gdal_formats[gdal_formats$name==sel_format,"ext"][1] sel_naflag <- s2_defNA(sel_infile_meta_sen2r$prod_type) sel_maskfiles <- sapply(names(req_masks), function(m) { sel1 <- maskfiles_meta_sen2r$prod_type==m & maskfiles_meta_sen2r$type==sel_infile_meta_sen2r$type & maskfiles_meta_sen2r$mission==sel_infile_meta_sen2r$mission & maskfiles_meta_sen2r$sensing_date==sel_infile_meta_sen2r$sensing_date & maskfiles_meta_sen2r$id_orbit==sel_infile_meta_sen2r$id_orbit if (!is.null(maskfiles_meta_sen2r$res) & !is.null(sel_infile_meta_sen2r$res)) { sel1 <- sel1 & maskfiles_meta_sen2r$res==sel_infile_meta_sen2r$res } maskfiles[which(sel1)][1] }) out_subdir <- ifelse(subdirs, file.path(outdir,infiles_meta_sen2r[i,"prod_type"]), outdir) sel_outfile <- file.path( out_subdir, gsub(paste0("\\.",infiles_meta_sen2r[i,"file_ext"],"$"), paste0(".",sel_out_ext), basename(sel_infile))) if (!file.exists(sel_outfile) | overwrite==TRUE) { print_message( type = "message", date = TRUE, paste0("Masking file ", basename(sel_outfile),"...") ) if (length(sel_maskfiles)==0) { gdalUtil( "translate", source = sel_infile, destination = sel_outfile, options = c( "-of", sel_format, if (sel_format == "GTiff") {c( "-co", paste0("COMPRESS=",toupper(compress)), "-co", "TILED=YES" )}, if (sel_format=="GTiff" & bigtiff==TRUE) {c("-co", "BIGTIFF=YES")} ), quiet = TRUE ) } else { inmask <- raster::stack(sel_maskfiles) if (Sys.info()["sysname"] == "Windows" & gsub(".*\\.([^\\.]+)$","\\1",sel_infile)=="vrt") { gdalUtil( "translate", source = sel_infile, destination = gsub("\\.vrt$",".tif",sel_infile), options = c( "-of", "GTiff", "-co", paste0("COMPRESS=",toupper(compress)), "-co", "TILED=YES", if (bigtiff == TRUE) {c("-co", "BIGTIFF=YES")} ), quiet = TRUE ) sel_infile <- gsub("\\.vrt$",".tif",sel_infile) } sel_tmpdir <- if (autotmpdir) { file.path(out_subdir, ".vrt") } else { tmpdir } dir.create(sel_tmpdir, showWarnings=FALSE) mask_tmpfiles <- character(0) naval_tmpfiles <- character(0) for (j in seq_along(inmask@layers)) { mask_tmpfiles <- c( mask_tmpfiles, file.path(sel_tmpdir, basename(tempfile(pattern = "mask_", fileext = ".tif"))) ) suppress_warnings( raster::calc( inmask[[j]], function(x){as.integer(!is.na(nn(x)) & !x %in% req_masks[[j]])}, filename = mask_tmpfiles[j], options = c( "COMPRESS=LZW", if (bigtiff==TRUE) {"BIGTIFF=YES"} ), datatype = "INT1U", overwrite = TRUE ), "NOT UPDATED FOR PROJ >\\= 6" ) naval_tmpfiles <- c( naval_tmpfiles, file.path(sel_tmpdir, basename(tempfile(pattern = "naval_", fileext = ".tif"))) ) suppress_warnings( raster::calc( inmask[[j]], function(x){as.integer(!is.na(nn(x)))}, filename = naval_tmpfiles[j], options = "COMPRESS=LZW", datatype = "INT1U" ), "NOT UPDATED FOR PROJ >\\= 6" ) } if(length(mask_tmpfiles)==1) { outmask <- mask_tmpfiles outnaval <- naval_tmpfiles } else { outmask <- file.path(sel_tmpdir, basename(tempfile(pattern = "mask_", fileext = ".tif"))) outnaval <- file.path(sel_tmpdir, basename(tempfile(pattern = "naval_", fileext = ".tif"))) raster::overlay(stack(mask_tmpfiles), fun = sum, filename = outmask, options = "COMPRESS=LZW", datatype = "INT1U") raster::overlay(stack(naval_tmpfiles), fun = sum, filename = outnaval, options = "COMPRESS=LZW", datatype = "INT1U") } mean_values_naval <- raster::cellStats(raster(outnaval), "mean", na.rm = TRUE) mean_values_mask <- raster::cellStats(raster(outmask), "mean", na.rm = TRUE) perc_mask <- 100 * (mean_values_naval - mean_values_mask) / mean_values_naval if (!is.finite(perc_mask)) {perc_mask <- 100} if (output_type == "perc") { names(perc_mask) <- sel_infile outpercs <- c(outpercs, perc_mask) } else if (output_type == "s2_mask") { if (is.na(max_mask) | perc_mask <= max_mask) { if (any( unlist(sel_infile_meta_raster[c("res.x","res.y")]) != unlist(raster_metadata(outmask, "res", format = "list")[[1]]$res) )) { gdal_warp( outmask, outmask_res <- file.path(sel_tmpdir, basename(tempfile(pattern = "mask_", fileext = ".tif"))), ref = sel_infile ) } else { outmask_res <- outmask } if (any( unlist(sel_infile_meta_raster[c("res.x","res.y")]) != unlist(raster_metadata(outnaval, "res", format = "list")[[1]]$res) )) { gdal_warp( outnaval, outnaval_res <- file.path(sel_tmpdir, basename(tempfile(pattern = "naval_", fileext = ".tif"))), ref = sel_infile ) } else { outnaval_res <- outnaval } outmask_smooth <- if (smooth > 0 | buffer != 0) { if (sel_infile_meta_raster$unit == "degree") { buffer <- buffer * 8.15e-6 smooth <- smooth * 8.15e-6 } min_values_naval <- raster::cellStats(raster(outnaval), "min", na.rm = TRUE) smooth_mask( outmask_res, radius = smooth, buffer = buffer, namask = if (min_values_naval==0) {outnaval_res} else {NULL}, tmpdir = sel_tmpdir, bigtiff = bigtiff ) } else { outmask_res } if (save_binary_mask == TRUE) { binmask <- file.path( ifelse(subdirs, file.path(outdir,"MSK"), outdir), gsub(paste0("\\.",infiles_meta_sen2r[i,"file_ext"],"$"), paste0(".",sel_out_ext), gsub(paste0("\\_",infiles_meta_sen2r[i,"prod_type"],"\\_"), "_MSK_", basename(sel_infile))) ) if (subdirs & !dir.exists(file.path(outdir,"MSK"))) { dir.create(file.path(outdir,"MSK")) } if (any(!file.exists(binmask), overwrite == TRUE)) { suppress_warnings( raster::mask( raster(outmask_smooth), raster(outnaval_res), filename = binmask, maskvalue = 0, updatevalue = sel_naflag, updateNA = TRUE, NAflag = 255, datatype = "INT1U", format = sel_format, options = if(sel_format == "GTiff") {paste0("COMPRESS=",compress)}, overwrite = overwrite ), "NOT UPDATED FOR PROJ >\\= 6" ) } } inraster <- raster::brick(sel_infile) maskapply_serial <- function( x, y, na, out_file = '', datatype, minrows = NULL, overwrite = overwrite ) { if (inherits(x, "RasterStackBrick")) { out <- brick(x, values = FALSE) } else { out <- raster(x) out@legend <- x@legend } if (grepl("\\.vrt$", out_file)) { out_file <- gsub("\\.vrt$", ".tif", out_file) } suppress_warnings( out <- writeStart( out, out_file, NAflag=na, datatype = datatype, format = ifelse(sel_format=="VRT","GTiff",sel_format), if (sel_format %in% c("GTiff","VRT")) { options = c( "COMPRESS=LZW", if (bigtiff==TRUE) {"BIGTIFF=YES"} ) }, overwrite = overwrite ), "NOT UPDATED FOR PROJ >\\= 6" ) bs <- blockSize(out, minblocks = 8) if (all(inherits(stdout(), "terminal"), interactive())) { pb <- txtProgressBar(0, bs$n, style = 3) } for (j in seq_len(bs$n)) { m <- raster::getValuesBlock(y, row = bs$row[j], nrows = bs$nrows[j]) v <- raster::getValuesBlock(x, row = bs$row[j], nrows = bs$nrows[j]) v[m == 0] <- NA out <- writeValues(out, v, bs$row[j]) gc() if (all(inherits(stdout(), "terminal"), interactive())) { setTxtProgressBar(pb, j) } } if (all(inherits(stdout(), "terminal"), interactive())) { message("") } out <- writeStop(out) } out <- maskapply_serial( x = inraster, y = raster(outmask_smooth), out_file = sel_outfile, na = sel_naflag, datatype = dataType(inraster), overwrite = TRUE ) if (grepl("\\.vrt$", sel_outfile)) { file.rename(gsub("\\.vrt$", ".tif", sel_outfile), sel_outfile) } if (sel_format=="ENVI") {fix_envi_format(sel_outfile)} } else { outfiles_toomasked <- c(outfiles_toomasked, sel_outfile) } } if (sel_rmtmp == TRUE) { unlink(sel_tmpdir, recursive=TRUE) } } } if (output_type == "s2_mask" & file.exists(sel_outfile)) { outfiles <- c(outfiles, sel_outfile) } })} if (rmtmp == TRUE) { unlink(tmpdir, recursive=TRUE) } if (output_type == "s2_mask") { attr(outfiles, "toomasked") <- outfiles_toomasked return(outfiles) } else if (output_type == "perc") { return(outpercs) } } s2_perc_masked <- function(infiles, maskfiles, mask_type = "cloud_medium_proba", tmpdir = NA, rmtmp = TRUE, parallel = FALSE) { .s2_mask(infiles = infiles, maskfiles = maskfiles, mask_type = mask_type, smooth = 0, buffer = 0, max_mask = 100, tmpdir = tmpdir, rmtmp = rmtmp, parallel = parallel, output_type = "perc") }
bootstrap.gain <- function(df1, df2, df3, opt.cov, n.rep, p1.beg, p1.end, p2.beg, p2.end, ratedPW, AEP, pw.freq, freq.id = 3, time.format = "%Y-%m-%d %H:%M:%S", k.fold = 5, col.time = 1, col.turb = 2, free.sec = NULL, neg.power = FALSE, pred.return = FALSE) { res <- rep(list(c()), n.rep) for (i in 1:n.rep) { message("Bootstrap Replication: ", i) data <- arrange.data(df1, df2, df3, p1.beg, p1.end, p2.beg, p2.end, time.format, k.fold, col.time, col.turb, bootstrap = i, free.sec, neg.power) if (is.na(data$train)[1]) { gain.res <- list(gainCurve = NA, gain = NA) res[[i]] <- gain.res } else { id.circ <- which(opt.cov %in% c("D", "hour")) message("Period 1 Prediction") message(" Period 1 Prediction - REF Model") n.dots <- floor(10/k.fold) pred.REF <- lapply(1:k.fold, function(x) { pred <- pred.akern(data$train[[x]]$yr, as.matrix(data$train[[x]][, opt.cov]), as.matrix(data$test[[x]][, opt.cov]), id.circ, k = "gcv", kernel = "gauss") return(cbind(data$test[[x]][, c(opt.cov, "yr")], pred = pred)) }) message(" Period 1 Prediction - CTR-b Model") pred.CTR <- lapply(1:k.fold, function(x) { pred <- pred.akern(data$train[[x]]$yb, as.matrix(data$train[[x]][, opt.cov]), as.matrix(data$test[[x]][, opt.cov]), id.circ, k = "gcv", kernel = "gauss") return(cbind(data$test[[x]][, c(opt.cov, "yb")], pred = pred)) }) bin.ref <- c(seq(0, ratedPW - 100, 100), ratedPW + 100) bins <- lapply(pred.CTR, function(df) .bincode(df$yb, bin.ref)) bin.biasREF <- t(sapply(1:k.fold, function(x) get.biasCurve(pred.REF[[x]], bins[[x]], bin.ref, "yr"))) bin.biasCTR <- t(sapply(1:k.fold, function(x) get.biasCurve(pred.CTR[[x]], bins[[x]], bin.ref, "yb"))) p1.res <- list(opt.cov = opt.cov, pred.REF = pred.REF, pred.CTR = pred.CTR, biasCurve.REF = bin.biasREF, biasCurve.CTR = bin.biasCTR) p2.res <- analyze.p2(data$per1, data$per2, p1.res$opt.cov) gain.res <- quantify.gain(p1.res, p2.res, ratedPW = ratedPW, AEP = AEP, pw.freq = pw.freq) p1.res <- p1.res[2:3] if (pred.return) res[[i]] <- list(gain.res = gain.res, p1.pred = p1.res, p2.pred = p2.res) else res[[i]] <- list(gain.res = gain.res) } } return(res) }
obsv <- function(A, C) { obsm <- t(ctrb (t(A), t(C))) return(obsm) }
spec_knit_hooks <- function( knit_hook_source = NULL, results_folding = c("none", "show", "hide") ) { results_folding = match.arg(results_folding) if (results_folding == "none") return(NULL) list( source = hook_start_results_folding(knit_hook_source), results.folding = hook_end_results_folding() ) }
gfac2<-function(covlevels){ nrows<-1 ncov<-length(covlevels) levmult <- cumprod(covlevels) totlev<-levmult[ncov] levmult<-c(1,levmult[-ncov]) cov<-NULL for (j in 1:ncov) { scov<-gl(covlevels[j],levmult[j],totlev*nrows) cov<-cbind(cov,scov) } cov }
defaultCorrectionParams<-function() { return(list( varmethods = list(MeanTemperature = "unbias", MinTemperature = "quantmap", MaxTemperature = "quantmap", Precipitation = "quantmap", MeanRelativeHumidity = "unbias", Radiation = "unbias", WindSpeed = "quantmap"), qstep = 0.01, fill_wind = TRUE, allow_saturated = FALSE, wind_height = 10 )) }
source(here::here("R/00_base_join.R")) y_extra <- bind_rows(y, tibble(id = 2, y = "y5")) anim_df <- tibble::tribble( ~.y, ~label, ~value, ~.x, ~.id, ~color, ~frame, ~obj, -1L, "id", "1", 1, "x", " -2L, "id", "2", 1, "x", " -2L, "id", "2", 1, "x", " -3L, "id", "3", 1, "x", " -1L, "x", "x1", 2, "x", " -2L, "x", "x2", 2, "x", " -3L, "x", "x3", 2, "x", " -2L, "x", "x2", 2, "x", " -1L, "id", "1", 4, "y", " -2L, "id", "2", 4, "y", " -3L, "id", "4", 4, "y", " -4L, "id", "2", 4, "y", " -1L, "y", "y1", 5, "y", " -2L, "y", "y2", 5, "y", " -3L, "y", "y4", 5, "y", " -4L, "y", "y5", 5, "y", " -1L, "id", "1", 2, "x", " -2L, "id", "2", 2, "x", " -3L, "id", "2", 2, "x", " -4L, "id", "3", 2, "x", " -1L, "x", "x1", 3, "x", " -2L, "x", "x2", 3, "x", " -3L, "x", "x2", 3, "x", " -4L, "x", "x3", 3, "x", " -1L, "y", "y1", 4, "x", " -2L, "y", "y2", 4, "x", " -3L, "y", "y5", 4, "x", " -1L, "id", "1", 2, "y", " -2L, "id", "2", 2, "y", " -3L, "id", "2", 2, "y", " ) lj_extra <- anim_df %>% arrange(obj, frame) %>% plot_data("left_join(x, y)") %>% animate_plot() lj_extra <- animate(lj_extra) anim_save(here::here("images", "left-join-extra.gif"), lj_extra) df_names <- tibble( .x = c(1.5, 4.5), .y = 0.25, value = c("x", "y"), size = 12, color = "black" ) g_input <- proc_data(y_extra) %>% mutate(.x = .x + 3) %>% bind_rows(proc_data(x)) %>% plot_data() + geom_text(data = df_names, family = "Fira Mono", size = 24) + annotate("text", label = "↑ duplicate keys in y", x = 4.5, y = -4.75, family = "Fira Sans", color = "grey45") save_static_plot(g_input, "left-join-extra-input") lj_g <- left_join(x, y_extra, by = "id") %>% proc_data() %>% mutate(.x = .x + 1) %>% plot_data_join("left_join(x, y)", ylims = ylim(-4.5, -0.5)) save_static_plot(lj_g, "left-join-extra")
print.ipcwsurvivalROC <- function(x,No.lines=5,digits=2,...){ if(x$iid==TRUE){ tab_ou_print<-round(cbind(x$Stats,x$AUC*100,x$inference$vect_sd_1*100),digits=digits) colnames(tab_ou_print)<-c("Cases","Survivors","Censored","AUC (%)","se") } else{ tab_ou_print<-round(cbind(x$Stats,x$AUC*100),digits=digits) colnames(tab_ou_print)<-c("Cases","Survivors","Censored","AUC (%)") } cat(paste("Time-dependent-Roc curve estimated using IPCW (n=",x$n, ", without competing risks). \n",sep="")) l<-length(x$times) if(l<=No.lines){ print(tab_ou_print) } else{print(tab_ou_print[unique(round(quantile(1:length(x$times),probs=seq(0,1,length.out=No.lines)),0)),])} cat("\n") cat("Method used for estimating IPCW:") cat(paste(x$weights$method,"\n")) cat("\n") cat("Total computation time :",round(x$computation_time,2)," secs.") cat("\n") }
NULL dev.curc <- function() { evalc(grDevices::dev.cur()) } dev.listc <- function() { evalc(grDevices::dev.list()) } dev.nextc <- function(which = grDevices::dev.cur()) { evalc(grDevices::dev.next(which = which)) } dev.prevc <- function(which = grDevices::dev.cur()) { evalc(grDevices::dev.prev(which = which)) } dev.offc <- function(which = grDevices::dev.cur()) { if(iam("local")) tryCatch(grDevices::dev.off(which = which)) } dev.setc <- function(which = grDevices::dev.cur()) { evalc(grDevices::dev.set(which = which)) } dev.newc <- function(..., noRstudioGD = FALSE) { if(iam("local")) tryCatch(grDevices::dev.new(..., noRstudioGD = noRstudioGD)) } dev.sizec <- function(units = c("in", "cm", "px")) { evalc(grDevices::dev.size(units = units)) }
library(gt) iris_tbl <- gt(iris) %>% tab_spanner_delim(delim = ".") %>% cols_move_to_start(columns = Species) %>% fmt_number( columns = c(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width), decimals = 1 ) %>% tab_header( title = md("The **iris** dataset"), subtitle = md("[All about *Iris setosa*, *versicolor*, and *virginica*]") ) %>% tab_source_note( source_note = md("The data were collected by *Anderson* (1935).") ) iris_tbl
context("Nonlinear mixed-effects models") test_that("Print methods work", { expect_known_output(print(fits[, 2:3], digits = 2), "print_mmkin_parent.txt") expect_known_output(print(mmkin_biphasic_mixed, digits = 2), "print_mmkin_biphasic_mixed.txt") expect_known_output(print(nlme_biphasic, digits = 1), "print_nlme_biphasic.txt") }) test_that("nlme results are reproducible to some degree", { test_summary <- summary(nlme_biphasic) test_summary$nlmeversion <- "Dummy 0.0 for testing" test_summary$mkinversion <- "Dummy 0.0 for testing" test_summary$Rversion <- "Dummy R version for testing" test_summary$date.fit <- "Dummy date for testing" test_summary$date.summary <- "Dummy date for testing" test_summary$time <- c(elapsed = "test time 0") expect_known_output(print(test_summary, digits = 1), "summary_nlme_biphasic_s.txt") dfop_sfo_pop <- as.numeric(dfop_sfo_pop) ci_dfop_sfo_n <- summary(nlme_biphasic)$confint_back expect_true(all(ci_dfop_sfo_n[, "upper"] > dfop_sfo_pop)) })
test.set.props <- function() { m <- parse.smiles("CCCC")[[1]] set.property(m, "foo", "bar") checkEquals(get.property(m,"foo"), "bar") } test.get.properties <- function() { m <- parse.smiles("CCCC")[[1]] set.property(m, "foo", "bar") set.property(m, "baz", 1.23) props <- get.properties(m) checkEquals(length(props), 3) checkTrue(all(sort(names(props)) == c('baz','cdk:Title','foo'))) checkEquals(props$foo,'bar') checkEquals(props$baz,1.23) }
context( "test Rank timePoints " ) seedFile <- system.file( "dataForTesting" , "seed.rds" , package = "microsamplingDesign" ) seed <- readRDS( seedFile ) rankTimePointsFile <- system.file( "dataForTesting" , "rankedTimePoints.rds" , package = "microsamplingDesign" ) rankTimePointsOrig <- readRDS( rankTimePointsFile ) suppressWarnings(RNGversion("3.5.0")) set.seed( seed , kind = "Mersenne-Twister", normal.kind = "Inversion") fullTimePoints <- 0:10 setOfTimePoints <- getExampleSetOfTimePoints( fullTimePoints) pkDataExample <- getPkData( getExamplePkModel() , getTimePoints( setOfTimePoints ) , nSubjectsPerScheme = 5 , nSamples = 17 ) suppressWarnings(RNGversion("3.5.0")) set.seed( seed , kind = "Mersenne-Twister", normal.kind = "Inversion") rankedTimePointsNew <- rankObject( object = setOfTimePoints , pkData = pkDataExample , nGrid = 75 , nSamplesAvCurve = 13) suppressWarnings(RNGversion("3.5.0")) set.seed( seed , kind = "Mersenne-Twister", normal.kind = "Inversion") rankedTimePointsNew2 <- rankObject( object = setOfTimePoints , pkData = pkDataExample , nGrid = 75 , nSamplesAvCurve = 13) suppressWarnings(RNGversion("3.5.0")) set.seed( seed , kind = "Mersenne-Twister", normal.kind = "Inversion") rankedTimePointsNewDiffGrid <- rankObject( object = setOfTimePoints , pkData = pkDataExample , nGrid = 10 , nSamplesAvCurve = 13) suppressWarnings(RNGversion("3.5.0")) set.seed( seed , kind = "Mersenne-Twister", normal.kind = "Inversion") rankedTimePointsNewDiffCurves <- rankObject( object = setOfTimePoints , pkData = pkDataExample , nGrid = 75 , nSamplesAvCurve = 20) test_that( "Equal ranking timePoints" , { expect_equal( rankTimePointsOrig@ranking , rankedTimePointsNew@ranking ) } ) test_that( "Different ranking timePoints with different number of grid poings" , { expect_false( identical( rankedTimePointsNew , rankedTimePointsNewDiffGrid ) ) } ) test_that( "Different ranking timePoints with different number of sample curves" , { expect_false( identical( rankedTimePointsNew , rankedTimePointsNewDiffCurves) ) } )
gemTwoCountryPureExchange_Bond <- function(...) sdm2(...)
listFromLong <- function(foo, unit.variable, time.variable, unit.names.variable=NULL,exclude.columns=NULL) { if(!is.data.frame(foo)) stop("foo must be a data.frame") DFtoList <- function(input,rowcol,colcol,colnamecol=NULL,exclude=NULL) { stopifnot(length(dim(input))==2) datcols <- setdiff(seq_len(ncol(input)), c(rowcol,colcol,colnamecol,exclude)) res <- vector("list",length(datcols)) names(res) <- if (!is.null(colnames(input))) colnames(input)[datcols] else as.character(datcols) if (!is.null(colnamecol)) { c2n <- na.omit(unique(input[,colnamecol])) names(c2n) <- na.omit(unique(input[,colcol])) } for (i in seq_along(res)) { idx <- !is.na(input[,datcols[i]]) rown <- unique(input[idx,rowcol]) coln <- unique(input[idx,colcol]) res[[i]] <- matrix(NA,nrow=length(rown),ncol=length(coln)) rownames(res[[i]]) <- rown colnames(res[[i]]) <- coln for (j in which(idx)) res[[i]][as.character(input[j,rowcol]),as.character(input[j,colcol])] <- input[j,datcols[i]] if (!is.null(colnamecol)) colnames(res[[i]]) <- c2n[as.character(coln)] res[[i]] <- res[[i]][order(rownames(res[[i]])),,drop=FALSE] } res } nam2idx <- function(...,id,type="numeric") { if (missing(id)) id <- as.character(match.call())[2] obj <- list(`...`)[[1]] if (length(obj)!=1) stop(paste0("\n Please specify only one ",id,"\n")) if (!(mode(foo[,obj]) %in% type)) stop("\n ",id," not found as ",type, " variable in foo.\n") if (mode(obj) == "character") which(names(foo)==obj) else obj } unit.variable <- nam2idx(unit.variable) time.variable <- nam2idx(time.variable,type=c("numeric","character")) if (!is.null(unit.names.variable)) { idx <- !(is.na(foo[,unit.variable])|is.na(foo[,unit.names.variable])) unit.names.variable <- nam2idx(unit.names.variable,type="character") if (length(unique(foo[idx,unit.names.variable])) != length(unique(foo[idx,unit.variable]))) stop("lengths of unit.names and unit.names.variable do not match") if (length(unique(paste(foo[idx,unit.variable],foo[idx,unit.names.variable], sep="----------"))) != length(unique(foo[idx,unit.variable]))) stop("unit.names and unit.names.variable do not match") } DFtoList(foo,rowcol=time.variable,colcol=unit.variable, colnamecol=unit.names.variable,exclude=exclude.columns) }
knitr::opts_chunk$set( collapse = TRUE, comment = " fig.width=6, fig.height=4 ) options(scipen = 9999) library(sf) library(dplyr) library(ncdfgeom) prcp_data <- readRDS(system.file("extdata/climdiv-pcpndv.rds", package = "ncdfgeom")) print(prcp_data, n_extra = 0) plot(prcp_data$date, prcp_data$`0101`, col = "red", xlab = "date", ylab = "monthly precip (inches)", main = "Sample Timeseries for 0101-'Northern Valley'") lines(prcp_data$date, prcp_data$`0101`) climdiv_poly <- read_sf(system.file("extdata/climdiv.gpkg", package = "ncdfgeom")) print(climdiv_poly) plot(st_geometry(climdiv_poly), main = "Climate Divisions with 0101-'Northern Valley' Highlighted") plot(st_geometry(filter(climdiv_poly, CLIMDIV == "0101")), col = "red", add = TRUE) climdiv_centroids <- climdiv_poly %>% st_transform(5070) %>% st_set_agr("constant") %>% st_centroid() %>% st_transform(4269) %>% st_coordinates() %>% as.data.frame() nc_file <- "climdiv_prcp.nc" prcp_dates <- prcp_data$date prcp_data <- select(prcp_data, -date) prcp_meta <- list(name = "climdiv_prcp_inches", long_name = "Estimated Monthly Precipitation (Inches)") write_timeseries_dsg(nc_file = nc_file, instance_names = climdiv_poly$CLIMDIV, lats = climdiv_centroids$Y, lons = climdiv_centroids$X, times = prcp_dates, data = prcp_data, data_unit = rep("inches", (ncol(prcp_data) - 1)), data_prec = "float", data_metadata = prcp_meta, attributes = list(title = "Demonstation of ncdfgeom"), add_to_existing = FALSE) climdiv_poly <- st_sf(st_cast(climdiv_poly, "MULTIPOLYGON")) write_geometry(nc_file = "climdiv_prcp.nc", geom_data = climdiv_poly, variables = "climdiv_prcp_inches") try({ncdump <- system(paste("ncdump -h", nc_file), intern = TRUE) cat(ncdump, sep = "\n")}, silent = TRUE) prcp_data <- read_timeseries_dsg("climdiv_prcp.nc") climdiv_poly <- read_geometry("climdiv_prcp.nc") names(prcp_data) class(prcp_data$time) names(prcp_data$varmeta$climdiv_prcp_inches) prcp_data$data_unit prcp_data$data_prec str(names(prcp_data$data_frames$climdiv_prcp_inches)) prcp_data$global_attributes names(climdiv_poly) p_colors <- function (n, name = c("precip_colors")) { p_rgb <- col2rgb(c(" " " " precip_colors = rgb(p_rgb[1,],p_rgb[2,],p_rgb[3,],maxColorValue = 255) name = match.arg(name) orig = eval(parse(text = name)) rgb = t(col2rgb(orig)) temp = matrix(NA, ncol = 3, nrow = n) x = seq(0, 1, , length(orig)) xg = seq(0, 1, , n) for (k in 1:3) { hold = spline(x, rgb[, k], n = n)$y hold[hold < 0] = 0 hold[hold > 255] = 255 temp[, k] = round(hold) } palette = rgb(temp[, 1], temp[, 2], temp[, 3], maxColorValue = 255) palette } climdiv_poly <- climdiv_poly %>% st_transform(3857) %>% st_simplify(dTolerance = 5000) title <- paste0("\n Sum of: ", prcp_data$varmeta$climdiv_prcp_inches$long_name, "\n", format(prcp_data$time[1], "%Y-%m", tz = "UTC"), " - ", format(prcp_data$time[length(prcp_data$time)], "%Y-%m", tz = "UTC")) prcp_sum <- apply(prcp_data$data_frames$climdiv_prcp_inches, 2, sum, na.rm = TRUE) prcp <- data.frame(CLIMDIV = names(prcp_sum), prcp = as.numeric(prcp_sum), stringsAsFactors = FALSE) %>% right_join(climdiv_poly, by = "CLIMDIV") %>% st_as_sf() plot(prcp["prcp"], lwd = 0.1, pal = p_colors, breaks = seq(0, 14000, 1000), main = title, key.pos = 3, key.length = lcm(20)) unlink("climdiv_prcp.nc")
separate_rows <- function(data, ..., sep = "[^[:alnum:].]+", convert = FALSE) { ellipsis::check_dots_unnamed() UseMethod("separate_rows") } separate_rows.data.frame <- function(data, ..., sep = "[^[:alnum:].]+", convert = FALSE) { vars <- tidyselect::eval_select(expr(c(...)), data) out <- purrr::modify_at(data, vars, str_split_n, pattern = sep) out <- unchop(as_tibble(out), any_of(vars)) if (convert) { out[vars] <- map(out[vars], type.convert, as.is = TRUE) } reconstruct_tibble(data, out, names(vars)) }
require(Rmpfr) require(DPQmpfr) stopifnot(all.equal(DPQ:::dntJKBf(mpfr(0, 64), 5,10), 3.66083172640611114864e-23, tol=1e-20)) dt(0, 5, 10) (dt5.10m <- dntJKBm(mpfr(-4:4, 256), 5, 10)) stopifnot(all.equal(dt5.10m, tolerance = 1e-7 , c(2.604112e-29, 1.40239e-28, 1.423497e-27, 5.449437e-26, 3.660832e-23, 1.035962e-16, 2.85854e-10, 3.656286e-06, 0.0006233252))) cbind(x = -4:4, dt.log = dt(-4:4, 5, 10, log=TRUE), log.dt.M = asNumeric(log(dt5.10m)))
setMethodS3("isZero", "default", function(x, neps=1, eps=.Machine$double.eps, ...) { if (is.character(eps)) { eps <- match.arg(eps, choices=c("double.eps", "single.eps")) if (eps == "double.eps") { eps <- .Machine$double.eps } else if (eps == "single.eps") { eps <- sqrt(.Machine$double.eps) } } (abs(x) < neps*eps) })
marginalize <- function(members, beta, weights) { w <- weights[members]/sum(weights[members]) pvec <- colSums(beta[members,,drop=FALSE]*w) words <- order(pvec, decreasing=TRUE) return(list(beta=pvec, indices=words)) }
VDJ_assemble_for_PnP <- function(VDJ.mixcr.matrix, id.column, species, manual_IgKC, manual_2A, manual_VDJLeader, write.to.disk, filename, verbose){ Nr_of_VDJ_chains <- NULL Nr_of_VJ_chains <- NULL platypus.version <- "v3" if(missing(verbose)) verbose <- F if(missing(species)) species <- "mouse" if(missing(manual_IgKC)) manual_IgKC <- "none" if(missing(manual_2A)) manual_2A <- "none" if(missing(manual_VDJLeader)) manual_VDJLeader <- "none" if(missing(write.to.disk)) write.to.disk <- T if(missing(id.column)) id.column <- "barcode" if(missing(filename)) filename <- "PnP_assembled_seqs" VDJ.matrix <- VDJ.mixcr.matrix if(all(c("Nr_of_VJ_chains", "Nr_of_VDJ_chains") %in% names(VDJ.matrix))){ if(verbose) message("\n Excluded cells with more or less than 1 VDJ 1 VJ chain") VDJ.matrix <- subset(VDJ.matrix, Nr_of_VDJ_chains == 1 & Nr_of_VJ_chains == 1) } if(any(!c("VDJ_nSeqFR1", "VDJ_nSeqFR2","VDJ_nSeqFR3","VDJ_nSeqFR4","VDJ_nSeqCDR1","VDJ_nSeqCDR2","VDJ_nSeqCDR3","VJ_nSeqFR1", "VJ_nSeqFR2","VJ_nSeqFR3","VJ_nSeqFR4","VJ_nSeqCDR1","VJ_nSeqCDR2","VJ_nSeqCDR3") %in% names(VDJ.matrix))){ stop(paste0("At least one of the neccessary columns in the input matrix are missing. Neccessary columns are: VDJ_nSeqFR1, VDJ_nSeqFR2,VDJ_nSeqFR3,VDJ_nSeqFR4,VDJ_nSeqCDR1,VDJ_nSeqCDR2,VDJ_nSeqCDR3,VJ_nSeqFR1, VJ_nSeqFR2,VJ_nSeqFR3,VJ_nSeqFR4,VJ_nSeqCDR1,VJ_nSeqCDR2,VJ_nSeqCDR3")) } if(!id.column %in% names(VDJ.matrix)) stop("id.column not found in input matrix") if(manual_IgKC == "none"){ if(species == "human"){ IgKC <- "CGAACTGTGGCTGCACCATCTGTCTTCATCTTCCCGCCATCTGATGAGCAGTTGAAATCTGGAACTGCCTCTGTTGTGTGCCTGCTGAATAACTTCTATCCCAGAGAGGCCAAAGTACAGTGGAAGGTGGATAACGCCCTCCAATCGGGTAACTCCCAGGAGAGTGTCACAGAGCAGGACAGCAAGGACAGCACCTACAGCCTCAGCAGCACCCTGACGCTGAGCAAAGCAGACTACGAGAAACACAAAGTCTACGCCTGCGAAGTCACCCATCAGGGCCTGAGCTCGCCCGTCACAAAGAGCTTCAACAGGGGAGAGTGT" } else if(species == "mouse") { IgKC <- "CGGGCCGACGCGGCCCCAACTGTATCCATCTTCCCACCATCCAGTGAGCAGTTAACATCTGGAGGTGCCTCAGTCGTGTGCTTCTTGAACAACTTCTACCCCAAAGACATCAATGTCAAGTGGAAGATTGATGGCAGTGAACGACAAAATGGCGTCCTGAACAGTTGGACTGATCAGGACAGCAAAGACAGCACCTACAGCATGAGCAGCACCCTCACGTTGACCAAGGACGAGTATGAACGACATAACAGCTATACCTGTGAGGCCACTCACAAGACATCAACTTCACCCATTGTCAAGAGCTTCAACAGGAATGAGTGT" } else { stop("Please enter either mouse or human as the species parameter") } } else{ IgKC <- manual_IgKC } if(manual_2A == "none"){ Fur_2A <- "AGGAAAAGACGACACAAACAGAAAATTGTGGCACCGGTGAAACAGACTTTGAATTTTGACCTTCTCAAGTTGGCGGGAGACGTCGAGTCCAACCCTGGGCCC" } else{ Fur_2A <- manual_2A } if(manual_VDJLeader == "none"){ VDJLeader <- "ATGATGGTGTTAAGTCTTCTGTACCTGTTGACAGCACTTCCGGGTGAGTGTTTCCATTTCATACATGTGCCATGAGGATTTTTCAAAATGTGTGATTGACAGATTTGATTCTTTTTGTCTAAAGGTATCCTGTCA" } else{ VDJLeader <- manual_VDJLeader } VJLeader <- "ATGGATTTTCAGGTGCAGATTTTCAGCTTCCTGCTAATCAGCGCTTCAGTTATAATGTCCCGGGGG" if(verbose) message("\n Got sequences; starting assembly...") seq_frame <- VDJ.matrix[,which(names(VDJ.matrix) %in% c(id.column, "VDJ_nSeqFR1", "VDJ_nSeqFR2","VDJ_nSeqFR3","VDJ_nSeqFR4","VDJ_nSeqCDR1","VDJ_nSeqCDR2","VDJ_nSeqCDR3","VJ_nSeqFR1", "VJ_nSeqFR2","VJ_nSeqFR3","VJ_nSeqFR4","VJ_nSeqCDR1","VJ_nSeqCDR2","VJ_nSeqCDR3"))] seq_length_check <- NULL seq_frame$seq_length_check <- "passed" for(i in 1:nrow(seq_frame)){ if(any(nchar(seq_frame[i,2:ncol(seq_frame)]) < 6)){ if(verbose) warning(paste0("At least one FR or CDR3 seq of cell id ",seq_frame[i,1]), " is less than 9 nt long. Please check for possible issues or missing sequences") seq_frame$seq_length_check[i] <- "FAILED" } } seq_codon_check <- NULL seq_frame$seq_codon_check <- "passed" for(i in 1:nrow(seq_frame)){ if(sum(nchar(seq_frame[i,2:ncol(seq_frame)]) %% 3 != 0) > 2){ if(verbose) warning(paste0("At least one FR or CDR3 seq of cell id ",seq_frame[i,1]), " does contain partial codons (i.e. sequence length not divisible by 3") seq_frame$seq_codon_check[i] <- "FAILED" } } VJ_nSeqFR4.lastnttrimmed <- NULL VDJ_nSeqFR4.lastnttrimmed <- NULL seq_frame$VJ_nSeqFR4.lastnttrimmed <- substr(seq_frame$VJ_nSeqFR4, start = 0, stop = nchar(seq_frame$VJ_nSeqFR4)-1) seq_frame$VDJ_nSeqFR4.lastnttrimmed <- substr(seq_frame$VDJ_nSeqFR4, start = 0, stop = nchar(seq_frame$VDJ_nSeqFR4)-1) pasted_seqs <- paste0(seq_frame$VJ_nSeqFR1,seq_frame$VJ_nSeqCDR1,seq_frame$VJ_nSeqFR2,seq_frame$VJ_nSeqCDR2,seq_frame$VJ_nSeqFR3,seq_frame$VJ_nSeqCDR3,seq_frame$VJ_nSeqFR4.lastnttrimmed,IgKC, Fur_2A,VDJLeader,seq_frame$VDJ_nSeqFR1,seq_frame$VDJ_nSeqCDR1,seq_frame$VDJ_nSeqFR2,seq_frame$VDJ_nSeqCDR2,seq_frame$VDJ_nSeqFR3,seq_frame$VDJ_nSeqCDR3,seq_frame$VDJ_nSeqFR4.lastnttrimmed) nchar_frame <- seq_frame nchar_frame$IgKC <- IgKC nchar_frame$Fur_2A <- Fur_2A nchar_frame$VDJLeader <- VDJLeader nchar_frame <- nchar_frame[,c("VJ_nSeqFR1","VJ_nSeqCDR1", "VJ_nSeqFR2","VJ_nSeqCDR2","VJ_nSeqFR3","VJ_nSeqCDR3","VJ_nSeqFR4.lastnttrimmed","IgKC","Fur_2A","VDJLeader","VDJ_nSeqFR1","VDJ_nSeqCDR1", "VDJ_nSeqFR2","VDJ_nSeqCDR2","VDJ_nSeqFR3","VDJ_nSeqCDR3","VDJ_nSeqFR4.lastnttrimmed")] for(i in 1:nrow(nchar_frame)){ nchar_frame[i,] <- cumsum(nchar(nchar_frame[i,])) } pasted_annotations <- paste0( "VJ_FR1 -> ",nchar_frame$VJ_nSeqFR1," | VJ_CDRL -> ",nchar_frame$VJ_nSeqCDR1, " | VJ_FR2 -> ",nchar_frame$VJ_nSeqFR2," | VJ_CDR2 -> ",nchar_frame$VJ_nSeqCDR2, " | VJ_FR3 -> ",nchar_frame$VJ_nSeqFR3," | VJ_CDR3 -> ",nchar_frame$VJ_nSeqCDR3, " | VJ_FRL4.lastnttrimmed -> ",nchar_frame$VJ_nSeqFR4.lastnttrimmed, " | IgKC -> ",nchar_frame$IgKC, " | Fur 2A -> ",nchar_frame$Fur_2A, " | VDJLeader -> ",nchar_frame$VDJLeader, " | VDJ_FRH1 -> ",nchar_frame$VDJ_nSeqFR1," | VDJ_CDR1 -> ",nchar_frame$VDJ_nSeqCDR1, " | VDJ_FR2 -> ",nchar_frame$VDJ_nSeqFR2," | VDJ_CDR2 -> ",nchar_frame$VDJ_nSeqCDR2, " | VDJ_FR3 -> ",nchar_frame$VDJ_nSeqFR3," | VDJ_CDR3 -> ",nchar_frame$VDJ_nSeqCDR3, " | VDJ_FR4.lastnttrimmed -> ",nchar_frame$VDJ_nSeqFR4.lastnttrimmed) PnP_assembled_seqs <- NULL PnP_assembled_annotations <- NULL seq_frame$PnP_assembled_seqs <- pasted_seqs seq_frame$PnP_assembled_annotations <- pasted_annotations leader_seqs_pasted <- paste0(VJLeader, seq_frame$PnP_assembled_seqs) trans_test <- as.character(Biostrings::translate(Biostrings::DNAStringSet(leader_seqs_pasted))) trans_VJ_CDR3s <- as.character(Biostrings::translate(Biostrings::DNAStringSet(seq_frame$VJ_nSeqCDR3))) trans_VDJ_CDR3s <- as.character(Biostrings::translate(Biostrings::DNAStringSet(seq_frame$VDJ_nSeqCDR3))) PnP_assembled_translations <- NULL seq_frame$PnP_assembled_translations <- trans_test if(verbose) message("\n Please note: the sequences in the PnP_assembled_translations column resulted from pasting the VJ leader sequence (contained in the PnP vector backbone) and the PnP_assembled_seqs (The insert itself)") seq_VJCDR3_check <- NULL seq_frame$seq_VJCDR3_check <- "passed" seq_Fur2A_check <- NULL seq_frame$seq_Fur2A_check <- "passed" seq_VDJCDR3_check <- NULL seq_frame$seq_VDJCDR3_check <- "passed" seq_splicesite_check <- NULL seq_frame$seq_splicesite_check <- "passed" for(i in 1:nrow(seq_frame)){ if(!stringr::str_detect(seq_frame$PnP_assembled_translations[i], pattern = trans_VJ_CDR3s[i])){ if(verbose) warning(paste0("Correct VJ CDR3 AA seq not found in the assembled sequence for cell id ", seq_frame[i,1]), "!") seq_frame$seq_VJCDR3_check[i] <- "FAILED" } if(!stringr::str_detect(seq_frame$PnP_assembled_translations[i], pattern = as.character(Biostrings::translate(Biostrings::DNAStringSet(Fur_2A))))){ if(verbose) warning(paste0("Correct Furine 2A AA seq not found in the assembled sequence for cell id ", seq_frame[i,1]), "!") seq_frame$seq_Fur2A_check[i] <- "FAILED" } if(!stringr::str_detect(seq_frame$PnP_assembled_translations[i], pattern = trans_VDJ_CDR3s[i])){ if(verbose) warning(paste0("Correct VDJ CDR3 AA seq not found in the assembled sequence for cell id ", seq_frame[i,1]), "!") seq_frame$seq_VDJCDR3_check[i] <- "FAILED" } if(!substr(seq_frame$PnP_assembled_seqs[i], start = nchar(seq_frame$PnP_assembled_seqs[i])-5, stop = 10000) %in% c("TCCTCA", "TCTTCA","TCGTCA","TCATCA")){ if(verbose) warning(paste0("Splicing site not found at end of VDJ FR4 in the assembled sequence for cell id ", seq_frame[i,1]), "! Valid splicing site requires a TCA at the sequence end") seq_frame$seq_splicesite_check[i] <- "FAILED" } } cat("\n Assembly and checks done") if(verbose) message("\n Adding additional columns to VDJ.mixcr.matrix input") VDJ.matrix <- cbind(VDJ.matrix, seq_frame) if(write.to.disk == F){ if(verbose) message("\n Done") return(VDJ.matrix) } else { if(verbose) message("\n Building .FASTA and .csv file") fasta_names <- paste0("Seq ID: ", seq_frame[,1], " | seq_length_check: ", seq_frame$seq_length_check," | seq_codon_check: ", seq_frame$seq_codon_check, " | seq_VJCDR3_check: ", seq_frame$seq_VJCDR3_check," | seq_Fur2A_check: ", seq_frame$seq_Fur2A_check," | seq_VDJCDR3_check: ", seq_frame$seq_VDJCDR3_check," | seq_splicesite_check: ", seq_frame$seq_splicesite_check, " Annotations: ", seq_frame$PnP_assembled_annotations) seqinr::write.fasta(as.list(unlist(seq_frame$PnP_assembled_seqs)), names = fasta_names, file.out = paste0(filename,".fasta")) utils::write.csv(seq_frame, file = paste0(filename,".csv")) if(verbose) message("\n Done \n") return(VDJ.matrix) } }
bag_o_words <- function(text.var, apostrophe.remove = FALSE, ...) { if (identical(list(), list(...))) { bag_o_words1(x = text.var, apostrophe.remove = apostrophe.remove, ...) } else { bag_o_words2(x = text.var, apostrophe.remove = apostrophe.remove) } } bag_o_words1 <- function(x, apostrophe.remove = FALSE) { x <- gsub("\\|", "", x[!is.na(x)]) x <- paste(x, collapse=" ") if(apostrophe.remove) { reg <- "[^[:alpha:]]" x <- gsub("'", "", x) } else { reg <- "[^[:alpha:]|\\']" } x <- strsplit(tolower(gsub(reg, " ", x)), "\\s+")[[1]] x[x != ""] } bag_o_words2 <- function(x, apostrophe.remove = FALSE, ...) { unblanker(words(strip(clean(x), apostrophe.remove = apostrophe.remove, ...))) } unbag <- function(text.var, na.rm = TRUE) { text.var <- unlist(text.var) if (na.rm) text.var <- text.var[!is.na(text.var)] paste(text.var, collapse=" ") } breaker <- function(text.var) { unblanker(unlist(strsplit(as.character(text.var), "[[:space:]]|(?=[|.!?*-])", perl=TRUE))) } word_split <- function (text.var) { x <- reducer(Trim(clean(text.var))) sapply(x, function(x) { unblanker(unlist(strsplit(x, "[[:space:]]|(?=[.!?*-])", perl = TRUE))) }, simplify = FALSE ) }
comment_out <- function(m, pattern = ".*") { m %>% gsub_ctl(paste0("(", pattern, ")"), "; \\1") } uncomment <- function(m, pattern = ".*") { m %>% gsub_ctl(paste0("^;+\\s*(", pattern, ")"), "\\1") } gsub_ctl <- function(m, pattern, replacement, ..., dollar = NA_character_) { UseMethod("gsub_ctl") } gsub_ctl.nm_generic <- function(m, pattern, replacement, ..., dollar = NA_character_) { text <- get_target_text(m) text <- gsub(pattern, replacement, text, ...) m <- m %>% set_target_text(text) m } gsub_ctl.nm_list <- Vectorize_nm_list(gsub_ctl.nm_generic, SIMPLIFY = FALSE) search_ctl_name <- function(r, models_dir = nm_dir("models")) { if (inherits(r, "nm")) ctl_name <- r$ctl if (inherits(r, "numeric") | inherits(r, "character")) { r <- as.character(r) rtemp <- normalizePath(r, mustWork = FALSE) if (file.exists2(rtemp)) { ctl_name <- rtemp } else { stop("cant find ctl_name") } } ctl_name } is_dollar_line <- function(l) grepl("^\\s*;*\\s*\\$", l) is_nm_comment_line <- function(l) grepl("^\\s*;", l) rem_dollars <- function(s) gsub("\\s*\\$\\S*\\s*", "", s) rem_comment <- function(s, char = ";") gsub(paste0("^([^", char, "]*)", char, "*.*$"), "\\1", s) get_comment <- function(s, char = ";") gsub(paste0("^[^", char, "]*", char, "*(.*)$"), "\\1", s) setup_dollar <- function(x, type, add_dollar_text = TRUE) { if (add_dollar_text) { if (!grepl(paste0("\\s*\\", type), x[1], ignore.case = TRUE)) { if (grepl("THETA|OMEGA|SIGMA|PK|PRED|ERROR|DES", type)) { x <- c(type, x) } else { x[1] <- paste(type, x[1]) } } } x <- strsplit(x, "\n") x <- sapply(x, function(i) { if (length(i) == 0) "" else i }) names(x) <- NULL class(x) <- c(paste0("nm.", tolower(gsub("^\\$", "", type))), "nm_subroutine") x } ctl_character <- function(r) { if (inherits(r, "ctl_character")) { return(r) } if (inherits(r, "nmexecute")) { ctl <- readLines(r$ctl) class(ctl) <- c("ctl_character", "character") attr(ctl, "file_name") <- r$ctl return(ctl) } if (inherits(r, "ctl_list")) { file_name <- attributes(r)$file_name ctl <- ctl_r2nm(r) attr(ctl, "file_name") <- file_name return(ctl) } if (inherits(r, "character")) { if (length(r) == 1) { ctl_name <- search_ctl_name(r) ctl <- readLines(ctl_name) class(ctl) <- c("ctl_character", "character") attr(ctl, "file_name") <- ctl_name return(ctl) } else { class(r) <- c("ctl_character", "character") return(r) } } stop("cannot coerce to ctl_character") } ctl_list <- function(r) { UseMethod("ctl_list") } ctl_list.ctl_character <- function(r) { ctl <- ctl_nm2r(r) attr(ctl, "file_name") <- attributes(r)$file_name ctl } ctl_list.ctl_list <- function(r) { r } ctl_list.character <- function(r) { if (length(r) == 1) { ctl <- ctl_character(r) file_name <- attributes(ctl)$file_name ctl <- ctl_nm2r(ctl) attr(ctl, "file_name") <- file_name return(ctl) } else { stop("cannot coerce to ctl_list") } } ctl_nm2r <- function(ctl) { ctl0 <- ctl dol <- grep("^\\s*\\$", ctl) dol <- which(is_dollar_line(ctl)) dol[1] <- 1 dol.type <- function(ctl) { sc <- paste(ctl, collapse = " ") type <- gsub("^[^\\$]*\\$([\\S]+).*$", "\\1", sc, perl = TRUE) type <- getOption("available_nm_types")[grep(substr(type, 1, 3), getOption("available_nm_types"))] if (length(type) == 0) type <- NA type } ctl2 <- list() start <- dol[1] finish <- dol[2] - 1 for (i in seq_along(dol)) { start <- dol[i] if (finish + 1 < start) start <- finish + 1 finish <- dol[i + 1] - 1 if (i == length(dol)) { finish <- length(ctl) } else { last.line <- ctl[finish] while (is_nm_comment_line(last.line) & !is_dollar_line(last.line)) { finish <- finish - 1 last.line <- ctl[finish] } } tmp <- ctl[start:finish] type <- dol.type(tmp) if (is.na(type)) type <- paste0("UNKNOWN", i) class(tmp) <- c(paste0("nm.", tolower(gsub("^\\$", "", type))), "nm_subroutine") ctl2[[i]] <- tmp } ctl <- ctl2 x <- lapply(ctl, function(s) class(s)) for (i in rev(seq_along(x))) { if (i == 1) break if (identical(x[i], x[i - 1])) { ctl[[i - 1]] <- c(ctl[[i - 1]], ctl[[i]]) class(ctl[[i - 1]]) <- class(ctl[[i]]) ctl[[i]] <- NULL } } names(ctl) <- sapply(ctl, function(s) gsub("NM\\.", "", toupper(class(s)[1]))) class(ctl) <- "ctl_list" ctl } ctl_r2nm <- function(x) { ctl <- unlist(x, use.names = FALSE) class(ctl) <- c("ctl_character") ctl } theta_nm2r <- function(x) { x <- rem_dollars(x) x <- gsub("FIX", "", x) x <- x[!grepl("^\\s*$", x)] x <- gsub("\\t", " ", x) x <- x[!grepl("^\\s*;.*", x)] x0 <- x x <- rem_comment(x, ";") x <- paste(x, collapse = " ") x <- gsub("\\(\\s*\\S*(\\s*)\\S*(\\s\\)S*\\s)\\)", "\\(~", x) x <- gsub("\\(", "\\(~", x) x <- strsplit(x, "\\(|\\)")[[1]] x <- x[!grepl("^\\s*$", x)] x <- lapply(x, function(x) { if (substr(x, 1, 1) != "~") { x <- strsplit(x, "[ ,]")[[1]] x <- x[!x %in% c("", "FIX")] x <- suppressWarnings(as.numeric(x)) x <- data.frame(lower = NA, init = x, upper = NA) } else { x <- gsub("~", "", x) x <- strsplit(x, "[ ,]")[[1]] x <- x[!x %in% c("", "FIX")] x <- suppressWarnings(as.numeric(x)) if (length(x) == 1) { x <- data.frame(lower = NA, init = x, upper = NA) } else if (length(x) == 2) { x <- data.frame(lower = x[1], init = x[2], upper = NA) } else if (length(x) == 3) x <- data.frame(lower = x[1], init = x[2], upper = x[3]) if (!length(x) %in% 1:3) stop("can't figure out bounds") } x }) x <- do.call(rbind, x) x$N <- 1:nrow(x) class(x) <- c(class(x), "r.theta") comments <- get_comment(x0, ";") if (length(comments) > max(x$N)) { warning("More comments than THETAs found. Something wrong") comments <- rep("", max(x$N)) } tmp <- strsplit(comments, ";") x$name <- sapply(tmp, "[", 1) x$name <- rem_trailing_spaces(x$name) x$unit <- sapply(tmp, "[", 2) x$unit <- rem_trailing_spaces(x$unit) x$trans <- sapply(tmp, "[", 3) x$trans <- rem_trailing_spaces(x$trans) x$trans[is.na(x$trans) & x$lower %in% 0] <- "RATIO" x$parameter <- paste0("THETA", x$N) x } rem_trailing_spaces <- function(x) { x <- gsub("\\s(?!\\S)", "", x, perl = TRUE) x <- gsub("^\\s*", "", x, perl = TRUE) x[grepl("^ *$", x)] <- NA x } param_info <- function(ctl) { UseMethod("param_info") } param_info.default <- function(ctl) { ctl <- ctl_list(ctl) if ("THETA" %in% names(ctl)) { return(theta_nm2r(ctl$THETA)) } else { return(data.frame()) } } param_info.nm_generic <- function(ctl) { ctl <- ctl_list2(ctl) if ("THETA" %in% names(ctl)) { return(theta_nm2r(ctl$THETA)) } else { return(data.frame()) } } param_info.nm_list <- function(ctl) param_info(as_nm_generic(ctl)) nonmem_code_to_r <- function(code, eta_to_0 = TRUE) { pk_block <- rem_comment(code) pk_block <- pk_block[!grepl("^\\s*\\$.*", pk_block)] if (eta_to_0) { pk_block <- gsub("\\bETA\\(([0-9]+)\\)", "0", pk_block) } pk_block <- gsub("ETA\\(([0-9]+)\\)", "ETA\\1", pk_block) pk_block <- gsub("\\bLOG\\b", "log", pk_block) pk_block <- gsub("\\bEXP\\b", "exp", pk_block) pk_block <- gsub("\\bIF\\b", "if", pk_block) pk_block <- gsub("\\bTHEN\\b", "{", pk_block) pk_block <- gsub("\\bENDIF\\b", "}", pk_block) pk_block <- gsub("\\bELSE\\b", "} else {", pk_block) pk_block <- gsub("\\.EQ\\.", "==", pk_block) pk_block <- gsub("\\.NE\\.", "!=", pk_block) pk_block <- gsub("\\.EQN\\.", "==", pk_block) pk_block <- gsub("\\.NEN\\.", "!=", pk_block) pk_block <- gsub("\\./E\\.", "!=", pk_block) pk_block <- gsub("\\.GT\\.", ">", pk_block) pk_block <- gsub("\\.LT\\.", "<", pk_block) pk_block <- gsub("\\.GE\\.", ">=", pk_block) pk_block <- gsub("\\.LE\\.", "<=", pk_block) pk_block } print.nm_subroutine <- function(x, ...) { cat(paste0(format(seq_along(x), width = 3), "| ", x), sep = "\n") } grab_variables0 <- function(text, pattern) { text_separated <- text %>% paste0(collapse = "\n") %>% stringr::str_split("(\n|\\s|\\+|\\-|\\=|\\*|\\/)") %>% unlist() text_separated <- text_separated[grepl(pattern, text_separated)] text_separated <- gsub(paste0(".*(", pattern, ").*"), "\\1", text_separated) unique(text_separated) } grab_variables <- function(m, pattern) { text <- m %>% text() grab_variables0(text, pattern) }
factory <- function (fun, debug=FALSE, errval="An error occurred in the factory function", types=c("message","warning","error")) { function(...) { errorOccurred <- FALSE warn <- err <- msg <- NULL res <- withCallingHandlers(tryCatch(fun(...), error = function(e) { if (debug) cat("error: ",conditionMessage(e),"\n") err <<- conditionMessage(e) errorOccurred <<- TRUE NULL }), warning = function(w) { if (!"warning" %in% types) { warning(conditionMessage(w)) } else { warn <<- append(warn, conditionMessage(w)) invokeRestart("muffleWarning") } }, message = function(m) { if (debug) cat("message: ",conditionMessage(m),"\n") if (!"message" %in% types) { message(conditionMessage(m)) } else { msg <<- append(msg, conditionMessage(m)) invokeRestart("muffleMessage") } }) if (errorOccurred) { if (!"error" %in% types) stop(err) res <- errval } setattr <- function(x, attrib, value) { attr(x,attrib) <- value x } attr_fun <- function(x,str,msg) { setattr(x,paste0("factory-",str), if(is.character(msg)) msg else NULL) } res <- attr_fun(res, "message", msg) res <- attr_fun(res, "warning", warn) res <- attr_fun(res, "error", err) return(res) } }
weighted_colSums <- function( mat, wgt=NULL) { wgt <- weighted_stats_extend_wgt( wgt=wgt, mat=mat ) mat1 <- colSums( mat * wgt, na.rm=TRUE) return(mat1) }
plot.mudens <- function (x, ...) { y <- x$haz.est if (x$pin$dens == 0) { plot(x$est.grid, y, type = "l", ylim = c(0, max(y)), xlab = "Follow-up Time", ylab = "Hazard Rate", ...) } else { plot(x$est.grid, y, type = "l", ylim = c(0, max(y)), xlab = "Follow-up Time", ylab = "Density", ...) } return(invisible()) }
makeRLearner.classif.__mlrmocklearners__1 = function() { makeRLearnerClassif( cl = "classif.__mlrmocklearners__1", package = character(0L), par.set = makeParamSet(), properties = c("twoclass", "multiclass", "missings", "numerics", "factors", "prob") ) } trainLearner.classif.__mlrmocklearners__1 = function(.learner, .task, .subset, .weights = NULL, ...) list() predictLearner.classif.__mlrmocklearners__1 = function(.learner, .model, .newdata, ...) stop("foo") registerS3method("makeRLearner", "classif.__mlrmocklearners__1", makeRLearner.classif.__mlrmocklearners__1) registerS3method("trainLearner", "classif.__mlrmocklearners__1", trainLearner.classif.__mlrmocklearners__1) registerS3method("predictLearner", "classif.__mlrmocklearners__1", predictLearner.classif.__mlrmocklearners__1) makeRLearner.classif.__mlrmocklearners__2 = function() { makeRLearnerClassif( cl = "classif.__mlrmocklearners__2", package = character(0L), par.set = makeParamSet( makeNumericLearnerParam("alpha", lower = 0, upper = 1) ), properties = c("twoclass", "multiclass", "missings", "numerics", "factors", "prob") ) } trainLearner.classif.__mlrmocklearners__2 = function(.learner, .task, .subset, .weights = NULL, alpha, ...) { if (alpha < 0.5) { stop("foo") } list() } predictLearner.classif.__mlrmocklearners__2 = function(.learner, .model, .newdata, ...) { as.factor(sample(.model$task.desc$class.levels, nrow(.newdata), replace = TRUE)) } registerS3method("makeRLearner", "classif.__mlrmocklearners__2", makeRLearner.classif.__mlrmocklearners__2) registerS3method("trainLearner", "classif.__mlrmocklearners__2", trainLearner.classif.__mlrmocklearners__2) registerS3method("predictLearner", "classif.__mlrmocklearners__2", predictLearner.classif.__mlrmocklearners__2) makeRLearner.classif.__mlrmocklearners__3 = function() { makeRLearnerClassif( cl = "classif.__mlrmocklearners__3", package = character(0L), par.set = makeParamSet(), properties = c("twoclass", "multiclass", "missings", "numerics", "factors", "prob") ) } trainLearner.classif.__mlrmocklearners__3 = function(.learner, .task, .subset, .weights = NULL, ...) stop("foo") predictLearner.classif.__mlrmocklearners__3 = function(.learner, .model, .newdata, ...) 1L registerS3method("makeRLearner", "classif.__mlrmocklearners__3", makeRLearner.classif.__mlrmocklearners__3) registerS3method("trainLearner", "classif.__mlrmocklearners__3", trainLearner.classif.__mlrmocklearners__3) registerS3method("predictLearner", "classif.__mlrmocklearners__3", predictLearner.classif.__mlrmocklearners__3) makeRLearner.regr.__mlrmocklearners__4 = function() { makeRLearnerRegr( cl = "regr.__mlrmocklearners__4", package = character(0L), par.set = makeParamSet( makeNumericLearnerParam("p1", when = "train"), makeNumericLearnerParam("p2", when = "predict"), makeNumericLearnerParam("p3", when = "both") ), properties = c("missings", "numerics", "factors") ) } trainLearner.regr.__mlrmocklearners__4 = function(.learner, .task, .subset, .weights = NULL, p1, p3, ...) { list(foo = p1 + p3) } predictLearner.regr.__mlrmocklearners__4 = function(.learner, .model, .newdata, p2, p3) { y = rep(1, nrow(.newdata)) y * .model$learner.model$foo + p2 + p3 } registerS3method("makeRLearner", "regr.__mlrmocklearners__4", makeRLearner.regr.__mlrmocklearners__4) registerS3method("trainLearner", "regr.__mlrmocklearners__4", trainLearner.regr.__mlrmocklearners__4) registerS3method("predictLearner", "regr.__mlrmocklearners__4", predictLearner.regr.__mlrmocklearners__4) makeRLearner.classif.__mlrmocklearners__5 = function() { makeRLearnerClassif( cl = "classif.__mlrmocklearners__5", package = "mlr", par.set = makeParamSet( makeDiscreteLearnerParam(id = "a", values = c("x", "y")), makeNumericLearnerParam(id = "b", lower = 0.0, upper = 1.0, requires = expression(a == "x")) ), properties = c("twoclass", "multiclass", "numerics", "factors", "prob") ) } trainLearner.classif.__mlrmocklearners__5 = function(.learner, .task, .subset, .weights = NULL, ...) { } predictLearner.classif.__mlrmocklearners__5 = function(.learner, .model, .newdata) { rep(factor(.model$factor.levels[[.model$task.desc$target]][1]), nrow(.newdata)) } registerS3method("makeRLearner", "classif.__mlrmocklearners__5", makeRLearner.classif.__mlrmocklearners__5) registerS3method("trainLearner", "classif.__mlrmocklearners__5", trainLearner.classif.__mlrmocklearners__5) registerS3method("predictLearner", "classif.__mlrmocklearners__5", predictLearner.classif.__mlrmocklearners__5) makeRLearner.regr.__mlrmocklearners__6 = function() { makeRLearnerRegr( cl = "regr.__mlrmocklearners__6", package = character(0L), par.set = makeParamSet(), properties = c("missings", "numerics", "factors", "weights") ) } trainLearner.regr.__mlrmocklearners__6 = function(.learner, .task, .subset, .weights = NULL, ...) { list(weights = .weights) } predictLearner.regr.__mlrmocklearners__6 = function(.learner, .model, .newdata) { rep(1, nrow(.newdata)) } registerS3method("makeRLearner", "regr.__mlrmocklearners__6", makeRLearner.regr.__mlrmocklearners__6) registerS3method("trainLearner", "regr.__mlrmocklearners__6", trainLearner.regr.__mlrmocklearners__6) registerS3method("predictLearner", "regr.__mlrmocklearners__6", predictLearner.regr.__mlrmocklearners__6) makeRLearner.classif.__mlrmocklearners__6 = function() { makeRLearnerClassif( cl = "classif.__mlrmocklearners__6", package = character(0L), par.set = makeParamSet(), properties = c("missings", "numerics", "factors", "weights", "twoclass", "multiclass") ) } trainLearner.classif.__mlrmocklearners__6 = function(.learner, .task, .subset, .weights = NULL, ...) { list(weights = .weights) } predictLearner.classif.__mlrmocklearners__6 = function(.learner, .model, .newdata) { rep(1, nrow(.newdata)) } registerS3method("makeRLearner", "classif.__mlrmocklearners__6", makeRLearner.classif.__mlrmocklearners__6) registerS3method("trainLearner", "classif.__mlrmocklearners__6", trainLearner.classif.__mlrmocklearners__6) registerS3method("predictLearner", "classif.__mlrmocklearners__6", predictLearner.classif.__mlrmocklearners__6)
"sse.bridges" <- function(sse, type="helix", hbond=TRUE, energy.cut=-1.0 ) { if(missing(sse)) stop("sse missing") if(is.null(sse$hbonds)) stop("sse$hbonds does not exists. run dssp with 'resno=FALSE' and 'full=TRUE'") natoms <- nrow(sse$hbonds) if(type=="helix") { sse2 <- sse$helix stype <- "H" lim <- 4 } if(type=="sheet") { sse2 <- sse$sheet stype <- "S" lim <- 2 } if(length(sse2$start)==0) return(NULL) simple.sse <- sse$sse simple.sse[ !(sse$sse %in% c("H", "E", "G", "I")) ] <- "L" simple.sse[ sse$sse %in% c("E") ] <- "S" simple.sse[ sse$sse %in% c("H", "I", "G") ] <- "H" inds <- NULL for ( i in 1:(natoms-lim) ) { if(simple.sse[i]!=stype) next; paired <- NULL if(type=="helix") { paired <- i+4 if(simple.sse[paired]!=stype) next; } if (type=="sheet") { paired <- sse$hbonds[i,c("BP1", "BP2")] paired <- paired[ !is.na(paired) ] if(length(paired)==0) next; } if(hbond) { resid <- sse$hbonds[i, c(3,5,7,9)] energ <- sse$hbonds[i, c(4,6,8,10)] energ <- energ[ !is.na(resid) ] resid <- resid[ !is.na(resid) ] inds.tmp <- which(resid %in% paired) resid <- resid[inds.tmp] energ <- energ[inds.tmp] dups <- duplicated(resid) resid <- resid[ !dups ] energ <- energ[ !dups ] if(length(resid)==0) next; for( j in 1:length(resid) ) { if(energ[j] < energy.cut) inds <- c(inds, i, resid[j]) } } else { for ( j in 1:length(paired) ) { inds <- c(inds, i, paired[j]) } } } if(length(inds)==0) return(NULL) mat <- matrix(inds, ncol=2, byrow=T) mat <- t(apply(mat, 1, sort)) pair.ids <- apply(mat, 1, function(x) paste(x, collapse="-")) mat <- matrix(mat[!duplicated(pair.ids), ], ncol=2) return(mat) }
snr_rms <- function(int, baseline, gauge) { SNR <- 0 int <- sort(int - baseline) Signal <- max(int) xN <- which(int/Signal < (1-gauge)) NVec <- int[xN] Noise <- sqrt(sum(NVec^2)/length(NVec)) if (is.na(Noise) == FALSE) { if (Noise != 0) { SNR <- Signal/Noise } else { SNR <- Inf } } return(SNR) }
tidy.lmRob <- function(x, ...) { co <- stats::coef(summary(x)) ret <- as_tibble(co, rownames = "term") names(ret) <- c("term", "estimate", "std.error", "statistic", "p.value") ret } augment.lmRob <- function(x, data = model.frame(x), newdata = NULL, ...) { passed_newdata <- !is.null(newdata) df <- if (passed_newdata) newdata else data df <- as_augment_tibble(df) rows <- split(df, 1:nrow(df)) preds <- purrr::map(rows, ~ predict(x, newdata = .x)) no_pred <- purrr::map_lgl(preds, ~ length(.x) == 0) preds[no_pred] <- NA df$.fitted <- as.numeric(preds) resp <- safe_response(x, df) if (!is.null(resp)) { df$.resid <- df$.fitted - resp } df } glance.lmRob <- function(x, ...) { as_glance_tibble( r.squared = x$r.squared, deviance = x$dev, sigma = summary(x)$sigma, df.residual = x$df.residual, nobs = stats::nobs(x), na_types = "rrrii" ) }
NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL
test_that("dictionary constructors fail if all elements unnamed: explicit", { expect_error(dictionary(list(c("a", "b"), "c")), "Dictionary elements must be named: a b c") expect_error(dictionary(list(first = c("a", "b"), "c")), "Unnamed dictionary entry: c") }) test_that("dictionary constructors fail if all elements unnamed: implicit", { expect_error(dictionary(list(c("a", "b"), "c")), "Dictionary elements must be named: a b c") expect_error(dictionary(list(first = c("a", "b"), "c")), "Unnamed dictionary entry: c") }) test_that("dictionary constructors fail if a value is numeric", { expect_error(dictionary(list(first = c("a", "b"), second = 2016)), "Non-character entries found in dictionary key 'second'") expect_error(dictionary(list(first = c("a", "b"), second = c("c", NA))), "Non-character entries found in dictionary key 'second'") }) test_that("dictionary constructor ignores extra arguments", { expect_error( dictionary(list(first = c("a", "b"), second = "c"), something = TRUE), "unused argument \\(something = TRUE\\)" ) }) marydict <- dictionary(list("A CATEGORY" = c("more", "lamb", "little"), "ANOTHER CATEGORY" = c("had", "mary"))) test_that("dictionary constructor works with wordstat format", { expect_equivalent(dictionary(file = "../data/dictionaries/mary.cat"), marydict) }) test_that("dictionary constructor works with Yoshikoder format", { expect_equivalent(dictionary(file = "../data/dictionaries/mary.ykd"), marydict) }) test_that("dictionary constructor works with YAML format", { expect_equivalent(dictionary(file = "../data/dictionaries/mary.yml"), marydict) }) test_that("dictionary constructor works with LIWC format", { expect_equivalent(dictionary(file = "../data/dictionaries/mary.dic"), dictionary(list(A_CATEGORY = c("lamb", "little", "more"), ANOTHER_CATEGORY = c("had", "mary")))) }) test_that("dictionary constructor works with Lexicoder format", { expect_equivalent(dictionary(file = "../data/dictionaries/mary.lcd"), marydict) }) test_that("read a dictionary with NA as a key", { testdict <- dictionary(file = "../data/dictionaries/issue-459.cat") expect_true("NA" %in% names(testdict$SOUTH)) }) test_that("as.yaml is working", { expect_equivalent(quanteda::as.yaml(marydict), "A CATEGORY:\n - more\n - lamb\n - little\nANOTHER CATEGORY:\n - had\n - mary\n") }) test_that("dictionary works with different encoding", { skip_on_os("windows") suppressWarnings({ expect_equivalent(dictionary(file = "../data/dictionaries/iso-8859-1.cat", tolower = FALSE), dictionary(list("LATIN" = c("B", "C", "D"), "NON-LATIN" = c("Bh", "Ch", "Dh")), tolower = FALSE)) expect_equivalent(dictionary(file = "../data/dictionaries/windows-1252.cat", tolower = FALSE, encoding = "windows-1252"), dictionary(list("LATIN" = c("S", "Z", "Y"), "NON-LATIN" = c("Š", "Ž", "Ÿ")), tolower = FALSE)) expect_equivalent(dictionary(file = "../data/dictionaries/iso-8859-2.cat", encoding = "iso-8859-2", tolower = FALSE), dictionary(list("LATIN" = c("C", "D", "E"), "NON-LATIN" = c("Č", "Ď", "Ě")), tolower = FALSE)) expect_equivalent(dictionary(file = "../data/dictionaries/iso-8859-14.cat", encoding = "iso-8859-14", tolower = FALSE), dictionary(list("LATIN" = c("B", "C", "D"), "NON-LATIN" = c("Ḃ", "Ċ", "Ḋ")), tolower = FALSE)) expect_equivalent(dictionary(file = "../data/dictionaries/shift-jis.cat", encoding = "shift-jis", tolower = FALSE), dictionary(list("LATIN" = c("A", "I", "U"), "NON-LATIN" = c("あ", "い", "う")), tolower = FALSE)) expect_equivalent(dictionary(file = "../data/dictionaries/euc-jp.cat", encoding = "euc-jp", tolower = FALSE), dictionary(list("LATIN" = c("A", "I", "U"), "NON-LATIN" = c("あ", "い", "う")), tolower = FALSE)) }) }) test_that("tolower is working", { list <- list(KEY1 = list(SUBKEY1 = c("A", "B"), SUBKEY2 = c("C", "D")), KEY2 = list(SUBKEY3 = c("E", "F"), SUBKEY4 = c("G", "F", "I")), KEY3 = list(SUBKEY5 = list(SUBKEY7 = c("J", "K")), SUBKEY6 = list(SUBKEY8 = c("L")))) dict <- dictionary(list, tolower = FALSE) dict_lower <- dictionary(list, tolower = TRUE) expect_equal(names(unlist(list)), names(unlist(dict))) expect_equal(names(unlist(dict_lower)), names(unlist(dict))) expect_equal(unlist(list, use.names = FALSE), unlist(dict, use.names = FALSE)) expect_equal(stringi::stri_trans_tolower(unlist(list, use.names = FALSE)), unlist(dict_lower, use.names = FALSE)) }) test_that("indexing for dictionary objects works", { testdict <- dictionary(file = "../data/dictionaries/laver-garry.cat") expect_true(is.dictionary(testdict[1:2])) expect_equal(names(testdict[1]), "CULTURE") expect_equal(names(testdict[[1]][1]), "CULTURE-HIGH") expect_equal(names(testdict[2]), "ECONOMY") expect_equal(names(testdict[[2]][1]), "+STATE+") expect_output( print(testdict), "Dictionary object with 9 primary key entries and 2 nested levels" ) expect_output( print(testdict[1]), "Dictionary object with 1 primary key entry and 2 nested levels" ) }) test_that("dictionary printing works", { dict <- dictionary(list(one = c("a", "b"), two = c("c", "d"))) expect_true(is.dictionary(dict[1])) expect_output( print(dict), paste0( "Dictionary object with 2 key entries.\n", "- [one]:\n", " - a, b\n", "- [two]:\n", " - c, d" ), fixed = TRUE ) expect_output( print(dict, max_nkey = 1), paste0( "Dictionary object with 2 key entries.\n", "- [one]:\n", " - a, b\n", "[ reached max_nkey ... 1 more key ]" ), fixed = TRUE ) expect_output( print(dict, max_nkey = -1, max_nval = -1), paste0( "Dictionary object with 2 key entries.\n", "- [one]:\n", " - a, b\n", "- [two]:\n", " - c, d" ), fixed = TRUE ) expect_output( print(dict, max_nkey = 1, max_nval = 1), paste0( "Dictionary object with 2 key entries.\n", "- [one]:\n", " - a [ ... and 1 more ]\n", "[ reached max_nkey ... 1 more key ]" ), fixed = TRUE ) expect_output( print(dict, max_nkey = 1, max_nval = 1, show_summary = FALSE), paste0( "- [one]:\n", " - a [ ... and 1 more ]\n", "[ reached max_nkey ... 1 more key ]" ), fixed = TRUE ) lis <- as.list(letters[1:10]) names(lis) <- LETTERS[1:10] dict2 <- dictionary(list("letters" = lis)) expect_output( print(dict2), "- [letters]:\n", fixed = TRUE ) expect_output( print(dict2, max_nkey = 5), "[ reached max_nkey ... 5 more keys ]", fixed = TRUE ) expect_output( print(dict2, max_nkey = -1), paste0( " - [J]:\n", " - j" ), fixed = TRUE ) expect_output( print(dict, 0, 0), "Dictionary object with 2 key entries.", fixed = TRUE ) }) test_that("dictionary_depth works correctly", { dict1 <- dictionary(list(one = c("a", "b"), two = c("c", "d"))) expect_equal(quanteda:::dictionary_depth(dict1), 1) dict2 <- dictionary(list(one = c("a", "b"), two = list(sub1 = c("c", "d"), sub2 = c("e", "f")))) expect_equal(quanteda:::dictionary_depth(dict2), 2) expect_output( print(dict2), "Dictionary object with 2 primary key entries and 2 nested levels\\." ) }) test_that("as.list is working", { lis <- list(top1 = c("a", "b"), top2 = c("c", "d"), top3 = list(sub1 = c("e", "f"), sub2 = c("f", "h"))) dict <- dictionary(lis) expect_equal( as.list(dict), lis ) expect_equal( as.list(dict, flatten = FALSE, levels = 1), lis ) expect_equal( as.list(dict, flatten = TRUE), list(top1 = c("a", "b"), top2 = c("c", "d"), top3.sub1 = c("e", "f"), top3.sub2 = c("f", "h")) ) expect_equal( as.list(dict, flatten = TRUE, levels = 1), list(top1 = c("a", "b"), top2 = c("c", "d"), top3 = c("e", "f", "f", "h")) ) expect_equal( as.list(dict, flatten = TRUE, levels = 2), list(sub1 = c("e", "f"), sub2 = c("f", "h")) ) }) test_that("error if empty separator is given", { expect_error(dictionary(list(one = c("a", "b"), two = c("c", "d")), separator = ""), "The value of separator must be between 1 and Inf character") expect_error(dictionary(list(one = c("a", "b"), two = c("c", "d")), separator = NULL), "The length of separator must be 1") expect_error(dictionary(file = "../data/dictionaries/mary.yml", separator = ""), "The value of separator must be between 1 and Inf character") expect_error(dictionary(file = "../data/dictionaries/mary.yml", separator = NULL), "The length of separator must be 1") }) test_that("dictionary woks with the Yoshicoder format", { testdict <- dictionary(file = "../data/dictionaries/laver-garry.ykd") expect_equal(names(testdict), "Laver and Garry") expect_equal(names(testdict[["Laver and Garry"]]), c("State in Economy", "Institutions", "Values", "Law and Order", "Environment", "Culture", "Groups", "Rural", "Urban")) }) test_that("dictionary constructor works with LIWC format w/doubled terms", { expect_equivalent( dictionary(file = "../data/dictionaries/mary_doubleterm.dic"), dictionary(list(A_CATEGORY = c("lamb", "little", "more"), ANOTHER_CATEGORY = c("had", "little", "mary"))) ) }) test_that("dictionary constructor works with LIWC format zero padding", { expect_equivalent( dictionary(file = "../data/dictionaries/mary_zeropadding.dic"), dictionary(list(A_CATEGORY = c("lamb", "little", "more"), ANOTHER_CATEGORY = c("had", "little", "mary"))) ) }) test_that("dictionary constructor reports mssing cateogries in LIWC format", { expect_message( dictionary(file = "../data/dictionaries/mary_missingcat.dic"), "note: ignoring undefined categories:" ) }) test_that("dictionary constructor works with LIWC format w/multiple tabs, spaces, etc", { expect_equivalent( dictionary(file = "../data/dictionaries/mary_multipletabs.dic"), dictionary(list(A_CATEGORY = c("lamb", "little", "more"), ANOTHER_CATEGORY = c("had", "little", "mary"))) ) }) test_that("dictionary constructor works with LIWC format w/extra codes", { expect_message( dictionary(file = "../data/dictionaries/liwc_extracodes.dic"), "note: 1 term ignored because contains unsupported <of> tag" ) expect_message( dictionary(file = "../data/dictionaries/liwc_extracodes.dic"), "note: ignoring parenthetical expressions in lines:" ) expect_message( dictionary(file = "../data/dictionaries/liwc_extracodes.dic"), "note: removing empty key: filler" ) expect_message( dictionary(file = "../data/dictionaries/liwc_extracodes.dic"), "note: removing empty key: discrep" ) expect_message( dictionary(file = "../data/dictionaries/liwc_extracodes.dic"), "note: removing empty key: cause" ) expect_message( dictionary(file = "../data/dictionaries/liwc_extracodes.dic"), "note: removing empty key: insight" ) expect_message( dictionary(file = "../data/dictionaries/liwc_extracodes.dic"), "note: removing empty key: humans" ) expect_message( dictionary(file = "../data/dictionaries/liwc_extracodes.dic"), "note: removing empty key: friend" ) dict <- dictionary(file = "../data/dictionaries/liwc_extracodes.dic") expect_equal( length(dict), 10 ) expect_true(setequal( names(dict), c("verb", "past", "whatever", "family", "affect", "posemo", "cogmech", "tentat", "whatever2", "time") )) }) test_that("dictionary constructor works with LIWC format w/extra codes and nesting", { expect_message( dictionary(file = "../data/dictionaries/liwc_hierarchical.dic"), "note: 1 term ignored because contains unsupported <of> tag" ) expect_message( dictionary(file = "../data/dictionaries/liwc_hierarchical.dic"), "note: ignoring parenthetical expressions in lines:" ) expect_message( dictionary(file = "../data/dictionaries/liwc_extracodes.dic"), "note: removing empty key: filler" ) expect_message( dictionary(file = "../data/dictionaries/liwc_extracodes.dic"), "note: removing empty key: discrep" ) expect_message( dictionary(file = "../data/dictionaries/liwc_extracodes.dic"), "note: removing empty key: cause" ) expect_message( dictionary(file = "../data/dictionaries/liwc_extracodes.dic"), "note: removing empty key: insight" ) expect_message( dictionary(file = "../data/dictionaries/liwc_extracodes.dic"), "note: removing empty key: humans" ) expect_message( dictionary(file = "../data/dictionaries/liwc_extracodes.dic"), "note: removing empty key: friend" ) dict <- dictionary(file = "../data/dictionaries/liwc_hierarchical.dic") expect_equal(length(dict), 4) expect_equal(length(dict[[1]]), 1) expect_equal(length(dict[[2]]), 4) expect_equal(length(dict[[3]]), 2) expect_equal(length(dict[[4]]), 2) }) test_that("dictionary works with yoshicoder, issue 819", { expect_equal( as.list(dictionary(file = "../data/dictionaries/issue-819.ykd")), list("Dictionary" = list("pos" = list("A" = "a word", "B" = "b word")))) }) test_that("dictionary constructor works on a dictionary", { dictlist <- list(one = LETTERS[1:2], Two = letters[1:3], three = c("E f", "g")) dict <- dictionary(dictlist, tolower = FALSE) expect_identical( dict, dictionary(dict, tolower = FALSE) ) dictlist2 <- list(one = LETTERS[1:2], Two = letters[1:3], three = c("E_f", "g")) dict2 <- dictionary(dictlist, tolower = FALSE) expect_equal( dictionary(dictlist, tolower = FALSE, separator = "_"), dictionary(dict2, tolower = FALSE, separator = "_") ) expect_equal( as.list(dictionary(dict2, separator = "_", tolower = FALSE)), dictlist ) }) test_that("combine method is working with dictionary objects", { dict1 <- dictionary(list(A = c("aa", "aaa")), separator = "+") dict2 <- dictionary(list(B = c("b", "bb")), separator = "-") dict3 <- dictionary(list(A = c("aaaa", "aaaaa"))) expect_equal(c(dict1, dict2), dictionary(list(A = c("aa", "aaa"), B = c("b", "bb")), separator = "+")) expect_equal(c(dict1, dict2, dict3), dictionary(list(A = c("aa", "aaa"), B = c("b", "bb"), A = c("aaaa", "aaaaa")), separator = "+")) }) test_that("dictionary constructor clean values", { dict1 <- dictionary(list(A = c("aa ", " aaa "))) dict2 <- dictionary(list(B = c("b", "bb", "bb"))) expect_equal(dict1, dictionary(list(A = c("aa", "aaa")))) expect_equal(dict2, dictionary(list(B = c("b", "bb")))) }) test_that("dictionary merge values in duplicate keys", { dict <- dictionary(list(A = "a", A = "aa", A = "aaa", B = list(BB = "bb"), B = list(BB = "bbb"), C = "c")) expect_equal(dict, dictionary(list(A = c("a", "aa", "aaa"), B = list(BB = c("bb", "bbb")), C = "c"))) }) test_that("dictionary allows empty keys", { dict <- dictionary(list(A = "a", B = list(), C = character())) expect_equal(names(dict), c("A", "B", "C")) }) test_that("object2id() preserves the order of keys and values", { type <- stopwords() dict1 <- dictionary(list(th = c("tho*", "the"), wh = "wh*", ng = "not *")) dict2 <- dictionary(list(ng = "not *", th = c("tho*", "the"), wh = "wh*")) dict3 <- dictionary(list(ng = "not *", wh = "wh* is", th = c("tho*", "the"))) dict4 <- dictionary(list(ng = "not *", th = c("tho*", "the"), wh = "wh* is")) ids1 <- quanteda:::object2id(dict1, type, "glob", FALSE) expect_identical(unique(names(ids1)), names(dict1)) ids2 <- quanteda:::object2id(dict2, type, "glob", FALSE) expect_identical(unique(names(ids2)), names(dict2)) ids3 <- quanteda:::object2id(dict3, type, "glob", FALSE) expect_identical(unique(names(ids3)), names(dict3)) ids4 <- quanteda:::object2id(dict4, type, "glob", FALSE) expect_identical(unique(names(ids4)), names(dict4)) }) test_that("split_values() handle concatenators correctly", { expect_identical( quanteda:::split_values(list(A = "a_a", "b_b"), "_", " "), list(A = c("a", "a"), A = "a a", c("b", "b"), "b b") ) expect_identical( quanteda:::split_values(list(A = "a_a", B = "b_b"), "_", " "), list(A = c("a", "a"), A = "a a", B = c("b", "b"), B = "b b") ) expect_identical( quanteda:::split_values(list(A = "a_a", "A_A"), "_", "-"), list(A = c("a", "a"), A = "a-a", c("A", "A"), "A-A") ) expect_identical( quanteda:::split_values(list(A = "a_a", "A_A"), " ", " "), list(A = "a_a", "A_A") ) })
dlms.bcn <- function(x, lambda = 1, mu = 0, sigma = 1, tol0 = 0.001, log = FALSE) { if (!is.logical(log.arg <- log) || length(log) != 1) stop("bad input for argument 'log'") rm(log) zedd <- ((x/mu)^lambda - 1) / (lambda * sigma) log.dz.dy <- (lambda - 1) * log(x/mu) - log(mu * sigma) is.eff.0 <- abs(lambda) < tol0 if (any(is.eff.0)) { zedd[is.eff.0] <- log(x[is.eff.0] / mu[is.eff.0]) / sigma[is.eff.0] log.dz.dy[is.eff.0] <- -log(x[is.eff.0] * sigma[is.eff.0]) } logden <- dnorm(zedd, log = TRUE) + log.dz.dy if (log.arg) logden else exp(logden) } qlms.bcn <- function(p, lambda = 1, mu = 0, sigma = 1) { answer <- mu * (1 + lambda * sigma * qnorm(p))^(1/lambda) answer } lms.bcn.control <- lms.bcg.control <- lms.yjn.control <- function(trace = TRUE, ...) list(trace = trace) lms.bcn <- function(percentiles = c(25, 50, 75), zero = c("lambda", "sigma"), llambda = "identitylink", lmu = "identitylink", lsigma = "loglink", idf.mu = 4, idf.sigma = 2, ilambda = 1, isigma = NULL, tol0 = 0.001) { llambda <- as.list(substitute(llambda)) elambda <- link2list(llambda) llambda <- attr(elambda, "function.name") lmu <- as.list(substitute(lmu)) emu <- link2list(lmu) lmu <- attr(emu, "function.name") lsigma <- as.list(substitute(lsigma)) esigma <- link2list(lsigma) lsigma <- attr(esigma, "function.name") if (!is.Numeric(tol0, positive = TRUE, length.arg = 1)) stop("bad input for argument 'tol0'") if (!is.Numeric(ilambda)) stop("bad input for argument 'ilambda'") if (length(isigma) && !is.Numeric(isigma, positive = TRUE)) stop("bad input for argument 'isigma'") new("vglmff", blurb = c("LMS ", "quantile", " regression (Box-Cox transformation to normality)\n", "Links: ", namesof("lambda", link = llambda, earg = elambda), ", ", namesof("mu", link = lmu, earg = emu), ", ", namesof("sigma", link = lsigma, earg = esigma)), constraints = eval(substitute(expression({ constraints <- cm.zero.VGAM(constraints, x = x, .zero , M = M, predictors.names = predictors.names, M1 = 3) }), list( .zero = zero))), infos = eval(substitute(function(...) { list(M1 = 3, Q1 = 1, expected = TRUE, multipleResponses = FALSE, parameters.names = c("lambda", "mu", "sigma"), llambda = .llambda , lmu = .lmu , lsigma = .lsigma , percentiles = .percentiles , true.mu = FALSE, zero = .zero ) }, list( .zero = zero, .percentiles = percentiles, .llambda = llambda, .lmu = lmu, .lsigma = lsigma ))), initialize = eval(substitute(expression({ w.y.check(w = w, y = y, Is.positive.y = TRUE, ncol.w.max = 1, ncol.y.max = 1) predictors.names <- c(namesof("lambda", .llambda, earg = .elambda, short= TRUE), namesof("mu", .lmu, earg = .emu, short= TRUE), namesof("sigma", .lsigma, earg = .esigma, short= TRUE)) extra$percentiles <- .percentiles if (!length(etastart)) { Fit5 <- vsmooth.spline(x = x[, min(ncol(x), 2)], y = y, w = w, df = .idf.mu ) fv.init <- c(predict(Fit5, x = x[, min(ncol(x), 2)])$y) lambda.init <- if (is.Numeric( .ilambda )) .ilambda else 1.0 sigma.init <- if (is.null(.isigma)) { myratio <- ((y/fv.init)^lambda.init - 1) / lambda.init if (is.Numeric( .idf.sigma )) { fit600 <- vsmooth.spline(x = x[, min(ncol(x), 2)], y = myratio^2, w = w, df = .idf.sigma) sqrt(c(abs(predict(fit600, x = x[, min(ncol(x), 2)])$y))) } else { sqrt(var(myratio)) } } else { .isigma } etastart <- cbind(theta2eta(lambda.init, .llambda , earg = .elambda ), theta2eta(fv.init, .lmu , earg = .emu ), theta2eta(sigma.init, .lsigma , earg = .esigma )) } }), list( .llambda = llambda, .lmu = lmu, .lsigma = lsigma, .elambda = elambda, .emu = emu, .esigma = esigma, .idf.mu = idf.mu, .idf.sigma = idf.sigma, .ilambda = ilambda, .isigma = isigma, .percentiles = percentiles ))), linkinv = eval(substitute(function(eta, extra = NULL) { pcent <- extra$percentiles eta[, 1] <- eta2theta(eta[, 1], .llambda , earg = .elambda ) eta[, 2] <- eta2theta(eta[, 2], .lmu , earg = .emu ) eta[, 3] <- eta2theta(eta[, 3], .lsigma , earg = .esigma ) qtplot.lms.bcn(percentiles = pcent, eta = eta) }, list( .llambda = llambda, .lmu = lmu, .lsigma = lsigma, .elambda = elambda, .emu = emu, .esigma = esigma ))), last = eval(substitute(expression({ misc$links <- c(lambda = .llambda , mu = .lmu , sigma = .lsigma ) misc$earg <- list(lambda = .elambda , mu = .emu , sigma = .esigma ) misc$tol0 <- .tol0 misc$percentiles <- .percentiles if (control$cdf) { post$cdf <- cdf.lms.bcn(y, eta0 = matrix(c(lambda, mymu, sigma), ncol = 3, dimnames = list(dimnames(x)[[1]], NULL))) } }), list( .llambda = llambda, .lmu = lmu, .lsigma = lsigma, .elambda = elambda, .emu = emu, .esigma = esigma, .percentiles = percentiles, .tol0 = tol0 ))), loglikelihood = eval(substitute( function(mu, y, w, residuals = FALSE, eta, extra = NULL, summation = TRUE) { lambda <- eta2theta(eta[, 1], .llambda , earg = .elambda ) muvec <- eta2theta(eta[, 2], .lmu , earg = .emu ) sigma <- eta2theta(eta[, 3], .lsigma , earg = .esigma ) if (residuals) { stop("loglikelihood residuals not implemented yet") } else { ll.elts <- dlms.bcn(x = y, lambda = lambda, mu = mu, sigma = sigma, tol0 = .tol0 , log = TRUE) if (summation) { sum(ll.elts) } else { ll.elts } } }, list( .llambda = llambda, .lmu = lmu, .lsigma = lsigma, .elambda = elambda, .emu = emu, .esigma = esigma, .tol0 = tol0 ))), vfamily = c("lms.bcn", "lmscreg"), validparams = eval(substitute(function(eta, y, extra = NULL) { lambda <- eta2theta(eta[, 1], .llambda , earg = .elambda ) mymu <- eta2theta(eta[, 2], .lmu , earg = .emu ) sigma <- eta2theta(eta[, 3], .lsigma , earg = .esigma ) okay1 <- all(is.finite(mymu )) && all(is.finite(sigma )) && all(0 < sigma) && all(is.finite(lambda)) okay1 }, list( .llambda = llambda, .lmu = lmu, .lsigma = lsigma, .elambda = elambda, .emu = emu, .esigma = esigma, .tol0 = tol0 ))), deriv = eval(substitute(expression({ lambda <- eta2theta(eta[, 1], .llambda , earg = .elambda ) mymu <- eta2theta(eta[, 2], .lmu , earg = .emu ) sigma <- eta2theta(eta[, 3], .lsigma , earg = .esigma ) zedd <- ((y / mymu)^lambda - 1) / (lambda * sigma) z2m1 <- zedd * zedd - 1 dl.dlambda <- zedd * (zedd - log(y/mymu) / sigma) / lambda - z2m1 * log(y/mymu) dl.dmu <- zedd / (mymu * sigma) + z2m1 * lambda / mymu dl.dsigma <- z2m1 / sigma dlambda.deta <- dtheta.deta(lambda, .llambda , earg = .elambda ) dmu.deta <- dtheta.deta(mymu, .lmu , earg = .emu ) dsigma.deta <- dtheta.deta(sigma, .lsigma , earg = .esigma ) c(w) * cbind(dl.dlambda * dlambda.deta, dl.dmu * dmu.deta, dl.dsigma * dsigma.deta) }), list( .llambda = llambda, .lmu = lmu, .lsigma = lsigma, .elambda = elambda, .emu = emu, .esigma = esigma ))), weight = eval(substitute(expression({ wz <- matrix(NA_real_, n, 6) wz[,iam(1, 1, M)] <- (7 * sigma^2 / 4) * dlambda.deta^2 wz[,iam(2, 2, M)] <- (1 + 2*(lambda*sigma)^2)/(mymu*sigma)^2 * dmu.deta^2 wz[,iam(3, 3, M)] <- (2 / sigma^2) * dsigma.deta^2 wz[,iam(1, 2, M)] <- (-1 / (2 * mymu)) * dlambda.deta * dmu.deta wz[,iam(1, 3, M)] <- (lambda * sigma) * dlambda.deta * dsigma.deta wz[,iam(2, 3, M)] <- (2*lambda/(mymu * sigma)) * dmu.deta * dsigma.deta c(w) * wz }), list( .llambda = llambda, .lmu = lmu, .lsigma = lsigma, .elambda = elambda, .emu = emu, .esigma = esigma )))) } lms.bcg <- function(percentiles = c(25, 50, 75), zero = c("lambda", "sigma"), llambda = "identitylink", lmu = "identitylink", lsigma = "loglink", idf.mu = 4, idf.sigma = 2, ilambda = 1, isigma = NULL) { llambda <- as.list(substitute(llambda)) elambda <- link2list(llambda) llambda <- attr(elambda, "function.name") lmu <- as.list(substitute(lmu)) emu <- link2list(lmu) lmu <- attr(emu, "function.name") lsigma <- as.list(substitute(lsigma)) esigma <- link2list(lsigma) lsigma <- attr(esigma, "function.name") if (!is.Numeric(ilambda)) stop("bad input for argument 'ilambda'") if (length(isigma) && !is.Numeric(isigma, positive = TRUE)) stop("bad input for argument 'isigma'") new("vglmff", blurb = c("LMS Quantile Regression ", "(Box-Cox transformation to a Gamma distribution)\n", "Links: ", namesof("lambda", link = llambda, earg = elambda), ", ", namesof("mu", link = lmu, earg = emu), ", ", namesof("sigma", link = lsigma, earg = esigma)), constraints = eval(substitute(expression({ constraints <- cm.zero.VGAM(constraints, x = x, .zero , M = M, predictors.names = predictors.names, M1 = 3) }), list(.zero = zero))), infos = eval(substitute(function(...) { list(M1 = 3, Q1 = 1, expected = TRUE, multipleResponses = FALSE, parameters.names = c("lambda", "mu", "sigma"), llambda = .llambda , lmu = .lmu , lsigma = .lsigma , percentiles = .percentiles , true.mu = FALSE, zero = .zero ) }, list( .zero = zero, .percentiles = percentiles, .llambda = llambda, .lmu = lmu, .lsigma = lsigma ))), initialize = eval(substitute(expression({ w.y.check(w = w, y = y, Is.positive.y = TRUE, ncol.w.max = 1, ncol.y.max = 1) predictors.names <- c( namesof("lambda", .llambda, earg = .elambda, short = TRUE), namesof("mu", .lmu, earg = .emu, short = TRUE), namesof("sigma", .lsigma, earg = .esigma, short = TRUE)) extra$percentiles <- .percentiles if (!length(etastart)) { Fit5 <- vsmooth.spline(x = x[, min(ncol(x), 2)], y = y, w = w, df = .idf.mu ) fv.init <- c(predict(Fit5, x = x[, min(ncol(x), 2)])$y) lambda.init <- if (is.Numeric( .ilambda )) .ilambda else 1.0 sigma.init <- if (is.null( .isigma )) { myratio <- ((y/fv.init)^lambda.init-1) / lambda.init if (is.numeric( .idf.sigma ) && is.finite( .idf.sigma )) { fit600 <- vsmooth.spline(x = x[, min(ncol(x), 2)], y = (myratio)^2, w = w, df = .idf.sigma ) sqrt(c(abs(predict(fit600, x = x[, min(ncol(x), 2)])$y))) } else { sqrt(var(myratio)) } } else .isigma etastart <- cbind(theta2eta(lambda.init, .llambda , earg = .elambda ), theta2eta(fv.init, .lmu , earg = .emu ), theta2eta(sigma.init, .lsigma , earg = .esigma )) } }), list( .llambda = llambda, .lmu = lmu, .lsigma = lsigma, .elambda = elambda, .emu = emu, .esigma = esigma, .idf.mu = idf.mu, .idf.sigma = idf.sigma, .ilambda = ilambda, .isigma = isigma, .percentiles = percentiles ))), linkinv = eval(substitute(function(eta, extra = NULL) { pcent <- extra$percentiles eta[, 1] <- eta2theta(eta[, 1], .llambda , earg = .elambda ) eta[, 2] <- eta2theta(eta[, 2], .lmu , earg = .emu ) eta[, 3] <- eta2theta(eta[, 3], .lsigma , earg = .esigma ) qtplot.lms.bcg(percentiles = pcent, eta = eta) }, list( .llambda = llambda, .lmu = lmu, .lsigma = lsigma, .elambda = elambda, .emu = emu, .esigma = esigma ))), last = eval(substitute(expression({ misc$link <- c(lambda = .llambda , mu = .lmu , sigma = .lsigma ) misc$earg <- list(lambda = .elambda , mu = .emu , sigma = .esigma ) misc$percentiles <- .percentiles if (control$cdf) { post$cdf <- cdf.lms.bcg(y, eta0 = matrix(c(lambda, mymu, sigma), ncol = 3, dimnames = list(dimnames(x)[[1]], NULL))) } }), list( .llambda = llambda, .lmu = lmu, .lsigma = lsigma, .elambda = elambda, .emu = emu, .esigma = esigma, .percentiles = percentiles ))), loglikelihood = eval(substitute( function(mu, y, w, residuals = FALSE, eta, extra = NULL, summation = TRUE) { lambda <- eta2theta(eta[, 1], .llambda , earg = .elambda ) mu <- eta2theta(eta[, 2], .lmu , earg = .emu ) sigma <- eta2theta(eta[, 3], .lsigma , earg = .esigma ) Gee <- (y / mu)^lambda theta <- 1 / (sigma * lambda)^2 if (residuals) { stop("loglikelihood residuals not implemented yet") } else { ll.elts <- c(w) * (log(abs(lambda)) + theta * (log(theta) + log(Gee)-Gee) - lgamma(theta) - log(y)) if (summation) { sum(ll.elts) } else { ll.elts } } }, list( .llambda = llambda, .lmu = lmu, .lsigma = lsigma, .elambda = elambda, .emu = emu, .esigma = esigma ))), vfamily = c("lms.bcg", "lmscreg"), validparams = eval(substitute(function(eta, y, extra = NULL) { lambda <- eta2theta(eta[, 1], .llambda , earg = .elambda ) mymu <- eta2theta(eta[, 2], .lmu , earg = .emu ) sigma <- eta2theta(eta[, 3], .lsigma , earg = .esigma ) okay1 <- all(is.finite(mymu )) && all(is.finite(sigma )) && all(0 < sigma) && all(is.finite(lambda)) okay1 }, list( .llambda = llambda, .lmu = lmu, .lsigma = lsigma, .elambda = elambda, .emu = emu, .esigma = esigma ))), deriv = eval(substitute(expression({ lambda <- eta2theta(eta[, 1], .llambda, earg = .elambda ) mymu <- eta2theta(eta[, 2], .lmu, earg = .emu ) sigma <- eta2theta(eta[, 3], .lsigma, earg = .esigma ) Gee <- (y / mymu)^lambda theta <- 1 / (sigma * lambda)^2 dd <- digamma(theta) dl.dlambda <- (1 + 2 * theta * (dd + Gee -1 -log(theta) - 0.5 * (Gee + 1) * log(Gee))) / lambda dl.dmu <- lambda * theta * (Gee-1) / mymu dl.dsigma <- 2*theta*(dd + Gee - log(theta * Gee)-1) / sigma dlambda.deta <- dtheta.deta(lambda, link = .llambda , earg = .elambda ) dmu.deta <- dtheta.deta(mymu, link = .lmu , earg = .emu ) dsigma.deta <- dtheta.deta(sigma, link = .lsigma , earg = .esigma ) cbind(dl.dlambda * dlambda.deta, dl.dmu * dmu.deta, dl.dsigma * dsigma.deta) * w }), list( .llambda = llambda, .lmu = lmu, .lsigma = lsigma, .elambda = elambda, .emu = emu, .esigma = esigma ))), weight = eval(substitute(expression({ tritheta <- trigamma(theta) wz <- matrix(0, n, 6) if (TRUE) { part2 <- dd + 2/theta - 2*log(theta) wz[,iam(1, 1, M)] <- ((1 + theta*(tritheta*(1+4*theta) - 4*(1+1/theta) - log(theta)*(2/theta - log(theta)) + dd*part2)) / lambda^2) * dlambda.deta^2 } else { temp <- mean( Gee*(log(Gee))^2 ) wz[,iam(1, 1, M)] <- ((4 * theta * (theta * tritheta-1) - 1 + theta*temp) / lambda^2) * dlambda.deta^2 } wz[,iam(2, 2, M)] <- dmu.deta^2 / (mymu * sigma)^2 wz[,iam(3, 3, M)] <- (4 * theta * (theta * tritheta - 1) / sigma^2) * dsigma.deta^2 wz[,iam(1, 2, M)] <- (-theta * (dd + 1 / theta - log(theta)) / mymu) * dlambda.deta * dmu.deta wz[,iam(1, 3, M)] <- 2 * theta^1.5 * (2 * theta * tritheta - 2 - 1 / theta) * dlambda.deta * dsigma.deta c(w) * wz }), list( .llambda = llambda, .lmu = lmu, .lsigma = lsigma, .elambda = elambda, .emu = emu, .esigma = esigma )))) } dy.dpsi.yeojohnson <- function(psi, lambda) { L <- max(length(psi), length(lambda)) if (length(psi) != L) psi <- rep_len(psi, L) if (length(lambda) != L) lambda <- rep_len(lambda, L) ifelse(psi > 0, (1 + psi * lambda)^(1/lambda - 1), (1 - (2-lambda) * psi)^((lambda - 1) / (2-lambda))) } dyj.dy.yeojohnson <- function(y, lambda) { L <- max(length(y), length(lambda)) if (length(y) != L) y <- rep_len(y, L) if (length(lambda) != L) lambda <- rep_len(lambda, L) ifelse(y>0, (1 + y)^(lambda - 1), (1 - y)^(1 - lambda)) } yeo.johnson <- function(y, lambda, derivative = 0, epsilon = sqrt(.Machine$double.eps), inverse = FALSE) { if (!is.Numeric(derivative, length.arg = 1, integer.valued = TRUE) || derivative < 0) stop("argument 'derivative' must be a non-negative integer") ans <- y if (!is.Numeric(epsilon, length.arg = 1, positive = TRUE)) stop("argument 'epsilon' must be a single positive number") L <- max(length(lambda), length(y)) if (length(y) != L) y <- rep_len(y, L) if (length(lambda) != L) lambda <- rep_len(lambda, L) if (inverse) { if (derivative != 0) stop("argument 'derivative' must 0 when inverse = TRUE") if (any(index <- y >= 0 & abs(lambda ) > epsilon)) ans[index] <- (y[index]*lambda[index] + 1)^(1/lambda[index]) - 1 if (any(index <- y >= 0 & abs(lambda ) <= epsilon)) ans[index] <- expm1(y[index]) if (any(index <- y < 0 & abs(lambda-2) > epsilon)) ans[index] <- 1 - (-(2-lambda[index]) * y[index]+1)^(1/(2-lambda[index])) if (any(index <- y < 0 & abs(lambda-2) <= epsilon)) ans[index] <- -expm1(-y[index]) return(ans) } if (derivative == 0) { if (any(index <- y >= 0 & abs(lambda ) > epsilon)) ans[index] <- ((y[index]+1)^(lambda[index]) - 1) / lambda[index] if (any(index <- y >= 0 & abs(lambda ) <= epsilon)) ans[index] <- log1p(y[index]) if (any(index <- y < 0 & abs(lambda-2) > epsilon)) ans[index] <- -((-y[index]+1)^(2-lambda[index]) - 1)/(2 - lambda[index]) if (any(index <- y < 0 & abs(lambda-2) <= epsilon)) ans[index] <- -log1p(-y[index]) } else { psi <- Recall(y = y, lambda = lambda, derivative = derivative - 1, epsilon = epsilon, inverse = inverse) if (any(index <- y >= 0 & abs(lambda ) > epsilon)) ans[index] <- ( (y[index]+1)^(lambda[index]) * (log1p(y[index]))^(derivative) - derivative * psi[index] ) / lambda[index] if (any(index <- y >= 0 & abs(lambda ) <= epsilon)) ans[index] <- (log1p(y[index]))^(derivative + 1) / (derivative + 1) if (any(index <- y < 0 & abs(lambda-2) > epsilon)) ans[index] <- -( (-y[index]+1)^(2-lambda[index]) * (-log1p(-y[index]))^(derivative) - derivative * psi[index] ) / (2-lambda[index]) if (any(index <- y < 0 & abs(lambda-2) <= epsilon)) ans[index] <- (-log1p(-y[index]))^(derivative + 1) / (derivative + 1) } ans } dpsi.dlambda.yjn <- function(psi, lambda, mymu, sigma, derivative = 0, smallno = 1.0e-8) { if (!is.Numeric(derivative, length.arg = 1, integer.valued = TRUE) || derivative < 0) stop("argument 'derivative' must be a non-negative integer") if (!is.Numeric(smallno, length.arg = 1, positive = TRUE)) stop("argument 'smallno' must be a single positive number") L <- max(length(psi), length(lambda), length(mymu), length(sigma)) if (length(psi) != L) psi <- rep_len(psi, L) if (length(lambda) != L) lambda <- rep_len(lambda, L) if (length(mymu) != L) mymu <- rep_len(mymu, L) if (length(sigma) != L) sigma <- rep_len(sigma, L) answer <- matrix(NA_real_, L, derivative+1) CC <- psi >= 0 BB <- ifelse(CC, lambda, -2+lambda) AA <- psi * BB temp8 <- if (derivative > 0) { answer[,1:derivative] <- Recall(psi = psi, lambda = lambda, mymu = mymu, sigma = sigma, derivative = derivative-1, smallno = smallno) answer[,derivative] * derivative } else { 0 } answer[, 1+derivative] <- ((AA+1) * (log1p(AA)/BB)^derivative - temp8) / BB pos <- (CC & abs(lambda) <= smallno) | (!CC & abs(lambda-2) <= smallno) if (any(pos)) answer[pos,1+derivative] = (answer[pos, 1]^(1+derivative))/(derivative+1) answer } gh.weight.yjn.11 <- function(z, lambda, mymu, sigma, derivmat = NULL) { if (length(derivmat)) { ((derivmat[, 2]/sigma)^2 + sqrt(2) * z * derivmat[, 3] / sigma) / sqrt(pi) } else { psi <- mymu + sqrt(2) * sigma * z (1 / sqrt(pi)) * (dpsi.dlambda.yjn(psi, lambda, mymu, sigma, derivative = 1)[, 2]^2 + (psi - mymu) * dpsi.dlambda.yjn(psi, lambda, mymu, sigma, derivative = 2)[, 3]) / sigma^2 } } gh.weight.yjn.12 <- function(z, lambda, mymu, sigma, derivmat = NULL) { if (length(derivmat)) { (-derivmat[, 2]) / (sqrt(pi) * sigma^2) } else { psi <- mymu + sqrt(2) * sigma * z (1 / sqrt(pi)) * (-dpsi.dlambda.yjn(psi, lambda, mymu, sigma, derivative = 1)[, 2]) / sigma^2 } } gh.weight.yjn.13 <- function(z, lambda, mymu, sigma, derivmat = NULL) { if (length(derivmat)) { sqrt(8 / pi) * (-derivmat[, 2]) * z / sigma^2 } else { psi <- mymu + sqrt(2) * sigma * z (1 / sqrt(pi)) * (-2 * dpsi.dlambda.yjn(psi, lambda, mymu, sigma, derivative = 1)[, 2]) * (psi - mymu) / sigma^3 } } glag.weight.yjn.11 <- function(z, lambda, mymu, sigma, derivmat = NULL) { if (length(derivmat)) { derivmat[, 4] * (derivmat[, 2]^2 + sqrt(2) * sigma * z * derivmat[, 3]) } else { psi <- mymu + sqrt(2) * sigma * z discontinuity <- -mymu / (sqrt(2) * sigma) (1 / (2 * sqrt((z-discontinuity^2)^2 + discontinuity^2))) * (1 / sqrt(pi)) * (dpsi.dlambda.yjn(psi, lambda, mymu, sigma, derivative = 1)[, 2]^2 + (psi - mymu) * dpsi.dlambda.yjn(psi, lambda, mymu, sigma, derivative = 2)[, 3]) / sigma^2 } } glag.weight.yjn.12 <- function(z, lambda, mymu, sigma, derivmat = NULL) { discontinuity <- -mymu / (sqrt(2) * sigma) if (length(derivmat)) { derivmat[, 4] * (-derivmat[, 2]) } else { psi <- mymu + sqrt(2) * sigma * z (1 / (2 * sqrt((z-discontinuity^2)^2 + discontinuity^2))) * (1 / sqrt(pi)) * (- dpsi.dlambda.yjn(psi, lambda, mymu, sigma, derivative = 1)[, 2]) / sigma^2 } } glag.weight.yjn.13 <- function(z, lambda, mymu, sigma, derivmat = NULL) { if (length(derivmat)) { derivmat[, 4] * (-derivmat[, 2]) * sqrt(8) * z } else { psi <- mymu + sqrt(2) * sigma * z discontinuity <- -mymu / (sqrt(2) * sigma) (1 / (2 * sqrt((z-discontinuity^2)^2 + discontinuity^2))) * (1 / sqrt(pi)) * (-2 * dpsi.dlambda.yjn(psi, lambda, mymu, sigma, derivative = 1)[, 2]) * (psi - mymu) / sigma^3 } } gleg.weight.yjn.11 <- function(z, lambda, mymu, sigma, derivmat = NULL) { if (length(derivmat)) { derivmat[, 4] * (derivmat[, 2]^2 + sqrt(2) * sigma*z* derivmat[, 3]) } else { psi <- mymu + sqrt(2) * sigma * z (exp(-z^2) / sqrt(pi)) * (dpsi.dlambda.yjn(psi, lambda, mymu, sigma, derivative = 1)[, 2]^2 + (psi - mymu) * dpsi.dlambda.yjn(psi, lambda, mymu, sigma, derivative = 2)[, 3]) / sigma^2 } } gleg.weight.yjn.12 <- function(z, lambda, mymu, sigma, derivmat = NULL) { if (length(derivmat)) { derivmat[, 4] * (- derivmat[, 2]) } else { psi <- mymu + sqrt(2) * sigma * z (exp(-z^2) / sqrt(pi)) * (- dpsi.dlambda.yjn(psi, lambda, mymu, sigma, derivative = 1)[, 2]) / sigma^2 } } gleg.weight.yjn.13 <- function(z, lambda, mymu, sigma, derivmat = NULL) { if (length(derivmat)) { derivmat[, 4] * (-derivmat[, 2]) * sqrt(8) * z } else { psi <- mymu + sqrt(2) * sigma * z (exp(-z^2) / sqrt(pi)) * (-2 * dpsi.dlambda.yjn(psi, lambda, mymu, sigma, derivative = 1)[, 2]) * (psi - mymu) / sigma^3 } } lms.yjn2.control <- function(save.weights = TRUE, ...) { list(save.weights = save.weights) } lms.yjn2 <- function(percentiles = c(25, 50, 75), zero = c("lambda", "sigma"), llambda = "identitylink", lmu = "identitylink", lsigma = "loglink", idf.mu = 4, idf.sigma = 2, ilambda = 1.0, isigma = NULL, yoffset = NULL, nsimEIM = 250) { llambda <- as.list(substitute(llambda)) elambda <- link2list(llambda) llambda <- attr(elambda, "function.name") lmu <- as.list(substitute(lmu)) emu <- link2list(lmu) lmu <- attr(emu, "function.name") lsigma <- as.list(substitute(lsigma)) esigma <- link2list(lsigma) lsigma <- attr(esigma, "function.name") if (!is.Numeric(ilambda)) stop("bad input for argument 'ilambda'") if (length(isigma) && !is.Numeric(isigma, positive = TRUE)) stop("bad input for argument 'isigma'") new("vglmff", blurb = c("LMS Quantile Regression (Yeo-Johnson transformation", " to normality)\n", "Links: ", namesof("lambda", link = llambda, earg = elambda), ", ", namesof("mu", link = lmu, earg = emu ), ", ", namesof("sigma", link = lsigma, earg = esigma )), constraints = eval(substitute(expression({ constraints <- cm.zero.VGAM(constraints, x = x, .zero , M = M, predictors.names = predictors.names, M1 = 3) }), list( .zero = zero ))), infos = eval(substitute(function(...) { list(M1 = 3, Q1 = 1, expected = TRUE, multipleResponses = FALSE, parameters.names = c("lambda", "mu", "sigma"), llambda = .llambda , lmu = .lmu , lsigma = .lsigma , percentiles = .percentiles , true.mu = FALSE, zero = .zero ) }, list( .zero = zero, .percentiles = percentiles, .llambda = llambda, .lmu = lmu, .lsigma = lsigma ))), initialize = eval(substitute(expression({ w.y.check(w = w, y = y, ncol.w.max = 1, ncol.y.max = 1) extra$percentiles <- .percentiles predictors.names <- c(namesof("lambda", .llambda, earg = .elambda, short= TRUE), namesof("mu", .lmu, earg = .emu, short= TRUE), namesof("sigma", .lsigma, earg = .esigma, short= TRUE)) y.save <- y yoff <- if (is.Numeric( .yoffset)) .yoffset else -median(y) extra$yoffset <- yoff y <- y + yoff if (!length(etastart)) { lambda.init <- if (is.Numeric( .ilambda )) .ilambda else 1. y.tx <- yeo.johnson(y, lambda.init) fv.init = if (smoothok <- (length(unique(sort(x[, min(ncol(x), 2)]))) > 7)) { fit700 <- vsmooth.spline(x = x[, min(ncol(x), 2)], y = y.tx, w = w, df = .idf.mu ) c(predict(fit700, x = x[, min(ncol(x), 2)])$y) } else { rep_len(weighted.mean(y, w), n) } sigma.init <- if (!is.Numeric(.isigma)) { if (is.Numeric( .idf.sigma) && smoothok) { fit710 = vsmooth.spline(x = x[, min(ncol(x), 2)], y = (y.tx - fv.init)^2, w = w, df = .idf.sigma) sqrt(c(abs(predict(fit710, x = x[, min(ncol(x), 2)])$y))) } else { sqrt( sum( w * (y.tx - fv.init)^2 ) / sum(w) ) } } else .isigma etastart <- matrix(0, n, 3) etastart[, 1] <- theta2eta(lambda.init, .llambda, earg = .elambda) etastart[, 2] <- theta2eta(fv.init, .lmu, earg = .emu) etastart[, 3] <- theta2eta(sigma.init, .lsigma, earg = .esigma) } }), list(.llambda = llambda, .lmu = lmu, .lsigma = lsigma, .elambda = elambda, .emu = emu, .esigma = esigma, .ilambda = ilambda, .isigma = isigma, .idf.mu = idf.mu, .idf.sigma = idf.sigma, .yoffset = yoffset, .percentiles = percentiles ))), linkinv = eval(substitute(function(eta, extra = NULL) { pcent <- extra$percentiles eta[, 1] <- eta2theta(eta[, 1], .llambda, earg = .elambda) eta[, 3] <- eta2theta(eta[, 3], .lsigma, earg = .esigma) qtplot.lms.yjn(percentiles = pcent, eta = eta, yoffset = extra$yoff) }, list( .esigma = esigma, .elambda = elambda, .llambda = llambda, .lsigma = lsigma ))), last = eval(substitute(expression({ misc$link <- c(lambda = .llambda, mu = .lmu, sigma = .lsigma) misc$earg <- list(lambda = .elambda, mu = .emu, sigma = .esigma) misc$nsimEIM <- .nsimEIM misc$percentiles <- .percentiles misc[["yoffset"]] <- extra$yoffset y <- y.save if (control$cdf) { post$cdf <- cdf.lms.yjn(y + misc$yoffset, eta0=matrix(c(lambda,mymu,sigma), ncol=3, dimnames = list(dimnames(x)[[1]], NULL))) } }), list(.percentiles = percentiles, .elambda = elambda, .emu = emu, .esigma = esigma, .nsimEIM=nsimEIM, .llambda = llambda, .lmu = lmu, .lsigma = lsigma ))), loglikelihood = eval(substitute( function(mu, y, w, residuals = FALSE, eta, extra = NULL, summation = TRUE) { lambda <- eta2theta(eta[, 1], .llambda , earg = .elambda ) mu <- eta2theta(eta[, 2], .lmu , earg = .emu ) sigma <- eta2theta(eta[, 3], .lsigma , earg = .esigma ) psi <- yeo.johnson(y, lambda) if (residuals) { stop("loglikelihood residuals not implemented yet") } else { ll.elts <- c(w) * (-log(sigma) - 0.5 * ((psi-mu)/sigma)^2 + (lambda-1) * sign(y) * log1p(abs(y))) if (summation) { sum(ll.elts) } else { ll.elts } } }, list( .elambda = elambda, .emu = emu, .esigma = esigma, .llambda = llambda, .lmu = lmu, .lsigma = lsigma ))), vfamily = c("lms.yjn2", "lmscreg"), validparams = eval(substitute(function(eta, y, extra = NULL) { lambda <- eta2theta(eta[, 1], .llambda , earg = .elambda ) mymu <- eta2theta(eta[, 2], .lmu , earg = .emu ) sigma <- eta2theta(eta[, 3], .lsigma , earg = .esigma ) okay1 <- all(is.finite(mymu )) && all(is.finite(sigma )) && all(0 < sigma) && all(is.finite(lambda)) okay1 }, list( .elambda = elambda, .emu = emu, .esigma = esigma, .llambda = llambda, .lmu = lmu, .lsigma = lsigma ))), deriv = eval(substitute(expression({ lambda <- eta2theta(eta[, 1], .llambda , earg = .elambda ) mymu <- eta2theta(eta[, 2], .lmu , earg = .emu ) sigma <- eta2theta(eta[, 3], .lsigma , earg = .esigma ) dlambda.deta <- dtheta.deta(lambda, link = .llambda, earg = .elambda) dmu.deta <- dtheta.deta(mymu, link = .lmu, earg = .emu) dsigma.deta <- dtheta.deta(sigma, link = .lsigma, earg = .esigma) psi <- yeo.johnson(y, lambda) d1 <- yeo.johnson(y, lambda, deriv = 1) AA <- (psi - mymu) / sigma dl.dlambda <- -AA * d1 /sigma + sign(y) * log1p(abs(y)) dl.dmu <- AA / sigma dl.dsigma <- (AA^2 -1) / sigma dthetas.detas <- cbind(dlambda.deta, dmu.deta, dsigma.deta) c(w) * cbind(dl.dlambda, dl.dmu, dl.dsigma) * dthetas.detas }), list( .elambda = elambda, .emu = emu, .esigma = esigma, .llambda = llambda, .lmu = lmu, .lsigma = lsigma ))), weight = eval(substitute(expression({ run.varcov <- 0 ind1 <- iam(NA, NA, M = M, both = TRUE, diag = TRUE) for (ii in 1:( .nsimEIM )) { psi <- rnorm(n, mymu, sigma) ysim <- yeo.johnson(y = psi, lam = lambda, inverse = TRUE) d1 <- yeo.johnson(ysim, lambda, deriv = 1) AA <- (psi - mymu) / sigma dl.dlambda <- -AA * d1 /sigma + sign(ysim) * log1p(abs(ysim)) dl.dmu <- AA / sigma dl.dsigma <- (AA^2 -1) / sigma rm(ysim) temp3 <- cbind(dl.dlambda, dl.dmu, dl.dsigma) run.varcov <- ((ii-1) * run.varcov + temp3[,ind1$row.index]*temp3[,ind1$col.index]) / ii } if (intercept.only) run.varcov <- matrix(colMeans(run.varcov), n, ncol(run.varcov), byrow = TRUE) wz <- run.varcov * dthetas.detas[,ind1$row] * dthetas.detas[,ind1$col] dimnames(wz) <- list(rownames(wz), NULL) c(w) * wz }), list(.lsigma = lsigma, .esigma = esigma, .elambda = elambda, .nsimEIM=nsimEIM, .llambda = llambda)))) } lms.yjn <- function(percentiles = c(25, 50, 75), zero = c("lambda", "sigma"), llambda = "identitylink", lsigma = "loglink", idf.mu = 4, idf.sigma = 2, ilambda = 1.0, isigma = NULL, rule = c(10, 5), yoffset = NULL, diagW = FALSE, iters.diagW = 6) { llambda <- as.list(substitute(llambda)) elambda <- link2list(llambda) llambda <- attr(elambda, "function.name") lsigma <- as.list(substitute(lsigma)) esigma <- link2list(lsigma) lsigma <- attr(esigma, "function.name") rule <- rule[1] if (rule != 5 && rule != 10) stop("only rule=5 or 10 is supported") new("vglmff", blurb = c("LMS Quantile Regression ", "(Yeo-Johnson transformation to normality)\n", "Links: ", namesof("lambda", link = llambda, earg = elambda), ", ", namesof("mu", link = "identitylink", earg = list()), ", ", namesof("sigma", link = lsigma, earg = esigma)), constraints = eval(substitute(expression({ constraints <- cm.zero.VGAM(constraints, x = x, .zero , M = M, predictors.names = predictors.names, M1 = 3) }), list(.zero = zero))), infos = eval(substitute(function(...) { list(M1 = 3, Q1 = 1, expected = TRUE, multipleResponses = FALSE, parameters.names = c("lambda", "mu", "sigma"), llambda = .llambda , lmu = "identitylink", lsigma = .lsigma , percentiles = .percentiles , true.mu = FALSE, zero = .zero ) }, list( .zero = zero, .percentiles = percentiles, .llambda = llambda, .lsigma = lsigma ))), initialize = eval(substitute(expression({ w.y.check(w = w, y = y, ncol.w.max = 1, ncol.y.max = 1) predictors.names <- c(namesof("lambda", .llambda, earg = .elambda , short = TRUE), "mu", namesof("sigma", .lsigma, earg = .esigma , short = TRUE)) extra$percentiles <- .percentiles y.save <- y yoff <- if (is.Numeric( .yoffset )) .yoffset else -median(y) extra$yoffset <- yoff y <- y + yoff if (!length(etastart)) { lambda.init <- if (is.Numeric( .ilambda )) .ilambda else 1.0 y.tx <- yeo.johnson(y, lambda.init) if (smoothok <- (length(unique(sort(x[, min(ncol(x), 2)]))) > 7)) { fit700 <- vsmooth.spline(x = x[, min(ncol(x), 2)], y = y.tx, w = w, df = .idf.mu ) fv.init <- c(predict(fit700, x = x[, min(ncol(x), 2)])$y) } else { fv.init <- rep_len(weighted.mean(y, w), n) } sigma.init <- if (!is.Numeric( .isigma )) { if (is.Numeric( .idf.sigma) && smoothok) { fit710 = vsmooth.spline(x = x[, min(ncol(x), 2)], y = (y.tx - fv.init)^2, w = w, df = .idf.sigma) sqrt(c(abs(predict(fit710, x = x[, min(ncol(x), 2)])$y))) } else { sqrt( sum( w * (y.tx - fv.init)^2 ) / sum(w) ) } } else .isigma etastart <- cbind(theta2eta(lambda.init, .llambda , earg = .elambda ), fv.init, theta2eta(sigma.init, .lsigma , earg = .esigma )) } }), list( .llambda = llambda, .lsigma = lsigma, .elambda = elambda, .esigma = esigma, .ilambda = ilambda, .isigma = isigma, .idf.mu = idf.mu, .idf.sigma = idf.sigma, .yoffset = yoffset, .percentiles = percentiles ))), linkinv = eval(substitute(function(eta, extra = NULL) { pcent <- extra$percentiles eta[, 1] <- eta2theta(eta[, 1], .llambda , earg = .elambda ) eta[, 3] <- eta2theta(eta[, 3], .lsigma , earg = .esigma ) qtplot.lms.yjn(percentiles = pcent, eta = eta, yoffset = extra$yoff) }, list(.percentiles = percentiles, .esigma = esigma, .elambda = elambda, .llambda = llambda, .lsigma = lsigma))), last = eval(substitute(expression({ misc$link <- c(lambda = .llambda , mu = "identitylink", sigma = .lsigma ) misc$earg <- list(lambda = .elambda , mu = list(theta = NULL), sigma = .esigma ) misc$percentiles <- .percentiles misc$true.mu <- FALSE misc[["yoffset"]] <- extra$yoff y <- y.save if (control$cdf) { post$cdf = cdf.lms.yjn(y + misc$yoffset, eta0 = matrix(c(lambda,mymu,sigma), ncol = 3, dimnames = list(dimnames(x)[[1]], NULL))) } }), list( .percentiles = percentiles, .elambda = elambda, .esigma = esigma, .llambda = llambda, .lsigma = lsigma))), loglikelihood = eval(substitute( function(mu, y, w, residuals = FALSE, eta, extra = NULL, summation = TRUE) { lambda <- eta2theta(eta[, 1], .llambda , earg = .elambda ) mu <- eta[, 2] sigma <- eta2theta(eta[, 3], .lsigma , earg = .esigma ) psi <- yeo.johnson(y, lambda) if (residuals) { stop("loglikelihood residuals not implemented yet") } else { ll.elts <- c(w) * (-log(sigma) - 0.5 * ((psi-mu)/sigma)^2 + (lambda-1) * sign(y) * log1p(abs(y))) if (summation) { sum(ll.elts) } else { ll.elts } } }, list( .esigma = esigma, .elambda = elambda, .lsigma = lsigma, .llambda = llambda))), vfamily = c("lms.yjn", "lmscreg"), validparams = eval(substitute(function(eta, y, extra = NULL) { lambda <- eta2theta(eta[, 1], .llambda , earg = .elambda ) mymu <- eta[, 2] sigma <- eta2theta(eta[, 3], .lsigma , earg = .esigma ) okay1 <- all(is.finite(mymu )) && all(is.finite(sigma )) && all(0 < sigma) && all(is.finite(lambda)) okay1 }, list( .esigma = esigma, .elambda = elambda, .lsigma = lsigma, .llambda = llambda))), deriv = eval(substitute(expression({ lambda <- eta2theta(eta[, 1], .llambda , earg = .elambda ) mymu <- eta[, 2] sigma <- eta2theta(eta[, 3], .lsigma , earg = .esigma ) psi <- yeo.johnson(y, lambda) d1 <- yeo.johnson(y, lambda, deriv = 1) AA <- (psi - mymu) / sigma dl.dlambda <- -AA * d1 /sigma + sign(y) * log1p(abs(y)) dl.dmu <- AA / sigma dl.dsigma <- (AA^2 -1) / sigma dlambda.deta <- dtheta.deta(lambda, link = .llambda, earg = .elambda ) dsigma.deta <- dtheta.deta(sigma, link = .lsigma, earg = .esigma ) cbind(dl.dlambda * dlambda.deta, dl.dmu, dl.dsigma * dsigma.deta) * c(w) }), list( .esigma = esigma, .elambda = elambda, .lsigma = lsigma, .llambda = llambda ))), weight = eval(substitute(expression({ wz <- matrix(0, n, 6) wz[,iam(2, 2, M)] <- 1 / sigma^2 wz[,iam(3, 3, M)] <- 2 * wz[,iam(2, 2, M)] if ( .rule == 10) { glag.abs = c(0.13779347054,0.729454549503, 1.80834290174,3.40143369785, 5.55249614006,8.33015274676, 11.8437858379,16.2792578314, 21.996585812, 29.9206970123) glag.wts = c(0.308441115765, 0.401119929155, 0.218068287612, 0.0620874560987, 0.00950151697517, 0.000753008388588, 2.82592334963e-5, 4.24931398502e-7, 1.83956482398e-9, 9.91182721958e-13) } else { glag.abs = c(0.2635603197180449, 1.4134030591060496, 3.5964257710396850, 7.0858100058570503, 12.6408008442729685) glag.wts = c(5.217556105826727e-01, 3.986668110832433e-01, 7.594244968176882e-02, 3.611758679927785e-03, 2.336997238583738e-05) } if ( .rule == 10) { sgh.abs = c(0.03873852801690856, 0.19823332465268367, 0.46520116404433082, 0.81686197962535023, 1.23454146277833154, 1.70679833036403172, 2.22994030591819214, 2.80910399394755972, 3.46387269067033854, 4.25536209637269280) sgh.wts = c(9.855210713854302e-02, 2.086780884700499e-01, 2.520517066468666e-01, 1.986843323208932e-01,9.719839905023238e-02, 2.702440190640464e-02, 3.804646170194185e-03, 2.288859354675587e-04, 4.345336765471935e-06, 1.247734096219375e-08) } else { sgh.abs = c(0.1002421519682381, 0.4828139660462573, 1.0609498215257607, 1.7797294185202606, 2.6697603560875995) sgh.wts = c(0.2484061520284881475,0.3923310666523834311, 0.2114181930760276606, 0.0332466603513424663, 0.0008248533445158026) } if ( .rule == 10) { gleg.abs = c(-0.973906528517, -0.865063366689, -0.679409568299, -0.433395394129, -0.148874338982) gleg.abs = c(gleg.abs, rev(-gleg.abs)) gleg.wts = c(0.0666713443087, 0.149451349151, 0.219086362516, 0.26926671931, 0.295524224715) gleg.wts = c(gleg.wts, rev(gleg.wts)) } else { gleg.abs = c(-0.9061798459386643,-0.5384693101056820, 0, 0.5384693101056828, 0.9061798459386635) gleg.wts = c(0.2369268850561853,0.4786286704993680, 0.5688888888888889, 0.4786286704993661, 0.2369268850561916) } discontinuity = -mymu/(sqrt(2)*sigma) LL <- pmin(discontinuity, 0) UU <- pmax(discontinuity, 0) if (FALSE) { AA <- (UU-LL)/2 for (kk in seq_along(gleg.wts)) { temp1 <- AA * gleg.wts[kk] abscissae <- (UU+LL)/2 + AA * gleg.abs[kk] psi <- mymu + sqrt(2) * sigma * abscissae temp9 <- dpsi.dlambda.yjn(psi, lambda, mymu, sigma, derivative = 2) temp9 <- cbind(temp9, exp(-abscissae^2) / (sqrt(pi) * sigma^2)) wz[,iam(1, 1, M)] <- wz[,iam(1, 1, M)] + temp1 * gleg.weight.yjn.11(abscissae, lambda, mymu, sigma, temp9) wz[,iam(1, 2, M)] <- wz[,iam(1, 2, M)] + temp1 * gleg.weight.yjn.12(abscissae, lambda, mymu, sigma, temp9) wz[,iam(1, 3, M)] <- wz[,iam(1, 3, M)] + temp1 * gleg.weight.yjn.13(abscissae, lambda, mymu, sigma, temp9) } } else { temp9 <- .Fortran("yjngintf", as.double(LL), as.double(UU), as.double(gleg.abs), as.double(gleg.wts), as.integer(n), as.integer(length(gleg.abs)), as.double(lambda), as.double(mymu), as.double(sigma), answer = double(3*n), eps = as.double(1.0e-5))$ans dim(temp9) <- c(3, n) wz[,iam(1, 1, M)] <- temp9[1,] wz[,iam(1, 2, M)] <- temp9[2,] wz[,iam(1, 3, M)] <- temp9[3,] } for (kk in seq_along(sgh.wts)) { abscissae <- sign(-discontinuity) * sgh.abs[kk] psi <- mymu + sqrt(2) * sigma * abscissae temp9 <- dpsi.dlambda.yjn(psi, lambda, mymu, sigma, derivative = 2) wz[,iam(1, 1, M)] <- wz[,iam(1, 1, M)] + sgh.wts[kk] * gh.weight.yjn.11(abscissae, lambda, mymu, sigma, temp9) wz[,iam(1, 2, M)] <- wz[,iam(1, 2, M)] + sgh.wts[kk] * gh.weight.yjn.12(abscissae, lambda, mymu, sigma, temp9) wz[,iam(1, 3, M)] <- wz[,iam(1, 3, M)] + sgh.wts[kk] * gh.weight.yjn.13(abscissae, lambda, mymu, sigma, temp9) } temp1 <- exp(-discontinuity^2) for (kk in seq_along(glag.wts)) { abscissae <- sign(discontinuity) * sqrt(glag.abs[kk]) + discontinuity^2 psi <- mymu + sqrt(2) * sigma * abscissae temp9 <- dpsi.dlambda.yjn(psi, lambda, mymu, sigma, derivative = 2) temp9 <- cbind(temp9, 1 / (2 * sqrt((abscissae-discontinuity^2)^2 + discontinuity^2) * sqrt(pi) * sigma^2)) temp7 <- temp1 * glag.wts[kk] wz[,iam(1, 1, M)] <- wz[,iam(1, 1, M)] + temp7 * glag.weight.yjn.11(abscissae, lambda, mymu, sigma, temp9) wz[,iam(1, 2, M)] <- wz[,iam(1, 2, M)] + temp7 * glag.weight.yjn.12(abscissae, lambda, mymu, sigma, temp9) wz[,iam(1, 3, M)] <- wz[,iam(1, 3, M)] + temp7 * glag.weight.yjn.13(abscissae, lambda, mymu, sigma, temp9) } wz[, iam(1, 1, M)] <- wz[, iam(1, 1, M)] * dlambda.deta^2 wz[, iam(1, 2, M)] <- wz[, iam(1, 2, M)] * dlambda.deta wz[, iam(1, 3, M)] <- wz[, iam(1, 3, M)] * dsigma.deta * dlambda.deta if ( .diagW && iter <= .iters.diagW) { wz[,iam(1, 2, M)] <- wz[, iam(1, 3, M)] <- 0 } wz[, iam(2, 3, M)] <- wz[, iam(2, 3, M)] * dsigma.deta wz[, iam(3, 3, M)] <- wz[, iam(3, 3, M)] * dsigma.deta^2 c(w) * wz }), list( .lsigma = lsigma, .llambda = llambda, .esigma = esigma, .elambda = elambda, .rule = rule, .diagW = diagW, .iters.diagW = iters.diagW )))) } lmscreg.control <- function(cdf = TRUE, at.arg = NULL, x0 = NULL, ...) { if (!is.logical(cdf)) { warning("'cdf' is not logical; using TRUE instead") cdf <- TRUE } list(cdf = cdf, at.arg = at.arg, x0 = x0) } Wr1 <- function(r, w) ifelse(r <= 0, 1, w) Wr2 <- function(r, w) (r <= 0) * 1 + (r > 0) * w amlnormal.deviance <- function(mu, y, w, residuals = FALSE, eta, extra = NULL) { M <- length(extra$w.aml) if (M > 1) y <- matrix(y, extra$n, extra$M) devi <- cbind((y - mu)^2) if (residuals) { stop("not sure here") wz <- VGAM.weights.function(w = w, M = extra$M, n = extra$n) return((y - mu) * sqrt(wz) * matrix(extra$w.aml,extra$n,extra$M)) } else { all.deviances <- numeric(M) myresid <- matrix(y,extra$n,extra$M) - cbind(mu) for (ii in 1:M) all.deviances[ii] <- sum(c(w) * devi[, ii] * Wr1(myresid[, ii], w = extra$w.aml[ii])) } if (is.logical(extra$individual) && extra$individual) all.deviances else sum(all.deviances) } amlnormal <- function(w.aml = 1, parallel = FALSE, lexpectile = "identitylink", iexpectile = NULL, imethod = 1, digw = 4) { if (!is.Numeric(w.aml, positive = TRUE)) stop("argument 'w.aml' must be a vector of positive values") if (!is.Numeric(imethod, length.arg = 1, integer.valued = TRUE, positive = TRUE) || imethod > 3) stop("argument 'imethod' must be 1, 2 or 3") lexpectile <- as.list(substitute(lexpectile)) eexpectile <- link2list(lexpectile) lexpectile <- attr(eexpectile, "function.name") if (length(iexpectile) && !is.Numeric(iexpectile)) stop("bad input for argument 'iexpectile'") new("vglmff", blurb = c("Asymmetric least squares quantile regression\n\n", "Links: ", namesof("expectile", link = lexpectile, earg = eexpectile)), constraints = eval(substitute(expression({ constraints <- cm.VGAM(matrix(1, M, 1), x = x, bool = .parallel , constraints = constraints) }), list( .parallel = parallel ))), deviance = function(mu, y, w, residuals = FALSE, eta, extra = NULL) { amlnormal.deviance(mu = mu, y = y, w = w, residuals = residuals, eta = eta, extra = extra) }, initialize = eval(substitute(expression({ extra$w.aml <- .w.aml temp5 <- w.y.check(w = w, y = y, ncol.w.max = 1, ncol.y.max = 1, out.wy = TRUE, maximize = TRUE) w <- temp5$w y <- temp5$y extra$M <- M <- length(extra$w.aml) extra$n <- n extra$y.names <- y.names <- paste("w.aml = ", round(extra$w.aml, digits = .digw ), sep = "") predictors.names <- c(namesof( paste("expectile(",y.names,")", sep = ""), .lexpectile , earg = .eexpectile, tag = FALSE)) if (!length(etastart)) { mean.init <- if ( .imethod == 1) rep_len(median(y), n) else if ( .imethod == 2 || .imethod == 3) rep_len(weighted.mean(y, w), n) else { junk <- lm.wfit(x = x, y = c(y), w = c(w)) junk$fitted } if ( .imethod == 3) mean.init <- abs(mean.init) + 0.01 if (length( .iexpectile)) mean.init <- matrix( .iexpectile, n, M, byrow = TRUE) etastart <- matrix(theta2eta(mean.init, .lexpectile, earg = .eexpectile), n, M) } }), list( .lexpectile = lexpectile, .eexpectile = eexpectile, .iexpectile = iexpectile, .imethod = imethod, .digw = digw, .w.aml = w.aml ))), linkinv = eval(substitute(function(eta, extra = NULL) { ans <- eta <- as.matrix(eta) for (ii in 1:ncol(eta)) ans[, ii] <- eta2theta(eta[, ii], .lexpectile , earg = .eexpectile ) dimnames(ans) <- list(dimnames(eta)[[1]], extra$y.names) ans }, list( .lexpectile = lexpectile, .eexpectile = eexpectile ))), last = eval(substitute(expression({ misc$link <- rep_len(.lexpectile , M) names(misc$link) <- extra$y.names misc$earg <- vector("list", M) for (ilocal in 1:M) misc$earg[[ilocal]] <- list(theta = NULL) names(misc$earg) <- names(misc$link) misc$parallel <- .parallel misc$expected <- TRUE extra$percentile <- numeric(M) misc$multipleResponses <- TRUE for (ii in 1:M) { use.w <- if (M > 1 && NCOL(w) == M) w[, ii] else w extra$percentile[ii] <- 100 * weighted.mean(myresid[, ii] <= 0, use.w) } names(extra$percentile) <- names(misc$link) extra$individual <- TRUE if (!(M > 1 && NCOL(w) == M)) { extra$deviance <- amlnormal.deviance(mu = mu, y = y, w = w, residuals = FALSE, eta = eta, extra = extra) names(extra$deviance) <- extra$y.names } }), list( .lexpectile = lexpectile, .eexpectile = eexpectile, .parallel = parallel ))), vfamily = c("amlnormal"), validparams = eval(substitute(function(eta, y, extra = NULL) { mymu <- eta2theta(eta, .lexpectile , earg = .eexpectile ) okay1 <- all(is.finite(mymu)) okay1 }, list( .lexpectile = lexpectile, .eexpectile = eexpectile ))), deriv = eval(substitute(expression({ mymu <- eta2theta(eta, .lexpectile , earg = .eexpectile ) dexpectile.deta <- dtheta.deta(mymu, .lexpectile , earg = .eexpectile ) myresid <- matrix(y,extra$n,extra$M) - cbind(mu) wor1 <- Wr2(myresid, w = matrix(extra$w.aml, extra$n, extra$M, byrow = TRUE)) c(w) * myresid * wor1 * dexpectile.deta }), list( .lexpectile = lexpectile, .eexpectile = eexpectile ))), weight = eval(substitute(expression({ wz <- c(w) * wor1 * dexpectile.deta^2 wz }), list( .lexpectile = lexpectile, .eexpectile = eexpectile )))) } amlpoisson.deviance <- function(mu, y, w, residuals = FALSE, eta, extra = NULL) { M <- length(extra$w.aml) if (M > 1) y <- matrix(y,extra$n,extra$M) nz <- y > 0 devi <- cbind(-(y - mu)) devi[nz] <- devi[nz] + y[nz] * log(y[nz]/mu[nz]) if (residuals) { stop("not sure here") return(sign(y - mu) * sqrt(2 * abs(devi) * w) * matrix(extra$w,extra$n,extra$M)) } else { all.deviances <- numeric(M) myresid <- matrix(y,extra$n,extra$M) - cbind(mu) for (ii in 1:M) all.deviances[ii] <- 2 * sum(c(w) * devi[, ii] * Wr1(myresid[, ii], w=extra$w.aml[ii])) } if (is.logical(extra$individual) && extra$individual) all.deviances else sum(all.deviances) } amlpoisson <- function(w.aml = 1, parallel = FALSE, imethod = 1, digw = 4, link = "loglink") { if (!is.Numeric(w.aml, positive = TRUE)) stop("'w.aml' must be a vector of positive values") link <- as.list(substitute(link)) earg <- link2list(link) link <- attr(earg, "function.name") new("vglmff", blurb = c("Poisson expectile regression by", " asymmetric maximum likelihood estimation\n\n", "Link: ", namesof("expectile", link, earg = earg)), constraints = eval(substitute(expression({ constraints <- cm.VGAM(matrix(1, M, 1), x = x, bool = .parallel , constraints = constraints) }), list( .parallel = parallel ))), deviance = function(mu, y, w, residuals = FALSE, eta, extra = NULL) { amlpoisson.deviance(mu = mu, y = y, w = w, residuals = residuals, eta = eta, extra = extra) }, initialize = eval(substitute(expression({ extra$w.aml <- .w.aml temp5 <- w.y.check(w = w, y = y, ncol.w.max = 1, ncol.y.max = 1, out.wy = TRUE, maximize = TRUE) w <- temp5$w y <- temp5$y extra$M <- M <- length(extra$w.aml) extra$n <- n extra$y.names <- y.names <- paste("w.aml = ", round(extra$w.aml, digits = .digw ), sep = "") extra$individual <- FALSE predictors.names <- c(namesof(paste("expectile(",y.names,")", sep = ""), .link , earg = .earg , tag = FALSE)) if (!length(etastart)) { mean.init <- if ( .imethod == 2) rep_len(median(y), n) else if ( .imethod == 1) rep_len(weighted.mean(y, w), n) else { junk = lm.wfit(x = x, y = c(y), w = c(w)) abs(junk$fitted) } etastart <- matrix(theta2eta(mean.init, .link , earg = .earg ), n, M) } }), list( .link = link, .earg = earg, .imethod = imethod, .digw = digw, .w.aml = w.aml ))), linkinv = eval(substitute(function(eta, extra = NULL) { mu.ans <- eta <- as.matrix(eta) for (ii in 1:ncol(eta)) mu.ans[, ii] <- eta2theta(eta[, ii], .link , earg = .earg ) dimnames(mu.ans) <- list(dimnames(eta)[[1]], extra$y.names) mu.ans }, list( .link = link, .earg = earg ))), last = eval(substitute(expression({ misc$multipleResponses <- TRUE misc$expected <- TRUE misc$parallel <- .parallel misc$link <- rep_len( .link , M) names(misc$link) <- extra$y.names misc$earg <- vector("list", M) for (ilocal in 1:M) misc$earg[[ilocal]] <- list(theta = NULL) names(misc$earg) <- names(misc$link) extra$percentile <- numeric(M) for (ii in 1:M) extra$percentile[ii] <- 100 * weighted.mean(myresid[, ii] <= 0, w) names(extra$percentile) <- names(misc$link) extra$individual <- TRUE extra$deviance <- amlpoisson.deviance(mu = mu, y = y, w = w, residuals = FALSE, eta = eta, extra = extra) names(extra$deviance) <- extra$y.names }), list( .link = link, .earg = earg, .parallel = parallel ))), linkfun = eval(substitute(function(mu, extra = NULL) { theta2eta(mu, link = .link , earg = .earg ) }, list( .link = link, .earg = earg ))), vfamily = c("amlpoisson"), validparams = eval(substitute(function(eta, y, extra = NULL) { mymu <- eta2theta(eta, .link , earg = .earg ) okay1 <- all(is.finite(mymu)) && all(0 < mymu) okay1 }, list( .link = link, .earg = earg ))), deriv = eval(substitute(expression({ mymu <- eta2theta(eta, .link , earg = .earg ) dexpectile.deta <- dtheta.deta(mymu, .link , earg = .earg ) myresid <- matrix(y,extra$n,extra$M) - cbind(mu) wor1 <- Wr2(myresid, w = matrix(extra$w.aml, extra$n, extra$M, byrow = TRUE)) c(w) * myresid * wor1 * (dexpectile.deta / mymu) }), list( .link = link, .earg = earg ))), weight = eval(substitute(expression({ use.mu <- mymu use.mu[use.mu < .Machine$double.eps^(3/4)] <- .Machine$double.eps^(3/4) wz <- c(w) * wor1 * use.mu * (dexpectile.deta / mymu)^2 wz }), list( .link = link, .earg = earg )))) } amlbinomial.deviance <- function(mu, y, w, residuals = FALSE, eta, extra = NULL) { M <- length(extra$w.aml) if (M > 1) y <- matrix(y,extra$n,extra$M) devy <- y nz <- y != 0 devy[nz] <- y[nz] * log(y[nz]) nz <- (1 - y) != 0 devy[nz] <- devy[nz] + (1 - y[nz]) * log1p(-y[nz]) devmu <- y * log(mu) + (1 - y) * log1p(-mu) if (any(small <- mu * (1 - mu) < .Machine$double.eps)) { warning("fitted values close to 0 or 1") smu <- mu[small] sy <- y[small] smu <- ifelse(smu < .Machine$double.eps, .Machine$double.eps, smu) onemsmu <- ifelse((1 - smu) < .Machine$double.eps, .Machine$double.eps, 1 - smu) devmu[small] <- sy * log(smu) + (1 - sy) * log(onemsmu) } devi <- 2 * (devy - devmu) if (residuals) { stop("not sure here") return(sign(y - mu) * sqrt(abs(devi) * w)) } else { all.deviances <- numeric(M) myresid <- matrix(y,extra$n,extra$M) - matrix(mu,extra$n,extra$M) for (ii in 1:M) all.deviances[ii] <- sum(c(w) * devi[, ii] * Wr1(myresid[, ii], w=extra$w.aml[ii])) } if (is.logical(extra$individual) && extra$individual) all.deviances else sum(all.deviances) } amlbinomial <- function(w.aml = 1, parallel = FALSE, digw = 4, link = "logitlink") { if (!is.Numeric(w.aml, positive = TRUE)) stop("'w.aml' must be a vector of positive values") link <- as.list(substitute(link)) earg <- link2list(link) link <- attr(earg, "function.name") new("vglmff", blurb = c("Logistic expectile regression by ", "asymmetric maximum likelihood estimation\n\n", "Link: ", namesof("expectile", link, earg = earg)), constraints = eval(substitute(expression({ constraints <- cm.VGAM(matrix(1, M, 1), x = x, bool = .parallel , constraints = constraints) }), list( .parallel = parallel ))), deviance = function(mu, y, w, residuals = FALSE, eta, extra = NULL) { amlbinomial.deviance(mu = mu, y = y, w = w, residuals = residuals, eta = eta, extra = extra) }, initialize = eval(substitute(expression({ { NCOL <- function (x) if (is.array(x) && length(dim(x)) > 1 || is.data.frame(x)) ncol(x) else as.integer(1) if (NCOL(y) == 1) { if (is.factor(y)) y <- y != levels(y)[1] nn <- rep_len(1, n) if (!all(y >= 0 & y <= 1)) stop("response values must be in [0, 1]") if (!length(mustart) && !length(etastart)) mustart <- (0.5 + w * y) / (1 + w) no.successes <- w * y if (any(abs(no.successes - round(no.successes)) > 0.001)) stop("Number of successes must be integer-valued") } else if (NCOL(y) == 2) { if (any(abs(y - round(y)) > 0.001)) stop("Count data must be integer-valued") nn <- y[, 1] + y[, 2] y <- ifelse(nn > 0, y[, 1]/nn, 0) w <- w * nn if (!length(mustart) && !length(etastart)) mustart <- (0.5 + nn * y) / (1 + nn) } else stop("Response not of the right form") } extra$w.aml <- .w.aml if (ncol(y <- cbind(y)) != 1) stop("response must be a vector or a one-column matrix") extra$M <- M <- length(extra$w.aml) extra$n <- n extra$y.names <- y.names <- paste("w.aml = ", round(extra$w.aml, digits = .digw ), sep = "") extra$individual <- FALSE predictors.names <- c(namesof(paste("expectile(", y.names, ")", sep = ""), .link , earg = .earg , tag = FALSE)) if (!length(etastart)) { etastart <- matrix(theta2eta(mustart, .link , earg = .earg ), n, M) mustart <- NULL } }), list( .link = link, .earg = earg, .digw = digw, .w.aml = w.aml ))), linkinv = eval(substitute(function(eta, extra = NULL) { mu.ans <- eta <- as.matrix(eta) for (ii in 1:ncol(eta)) mu.ans[, ii] <- eta2theta(eta[, ii], .link , earg = .earg ) dimnames(mu.ans) <- list(dimnames(eta)[[1]], extra$y.names) mu.ans }, list( .link = link, .earg = earg ))), last = eval(substitute(expression({ misc$link <- rep_len(.link , M) names(misc$link) <- extra$y.names misc$earg <- vector("list", M) for (ilocal in 1:M) misc$earg[[ilocal]] <- list(theta = NULL) names(misc$earg) <- names(misc$link) misc$parallel <- .parallel misc$expected <- TRUE extra$percentile <- numeric(M) for (ii in 1:M) extra$percentile[ii] <- 100 * weighted.mean(myresid[, ii] <= 0, w) names(extra$percentile) <- names(misc$link) extra$individual <- TRUE extra$deviance <- amlbinomial.deviance(mu = mu, y = y, w = w, residuals = FALSE, eta = eta, extra = extra) names(extra$deviance) <- extra$y.names }), list( .link = link, .earg = earg, .parallel = parallel ))), linkfun = eval(substitute(function(mu, extra = NULL) { theta2eta(mu, link = .link , earg = .earg ) }, list( .link = link, .earg = earg ))), vfamily = c("amlbinomial"), validparams = eval(substitute(function(eta, y, extra = NULL) { mymu <- eta2theta(eta, .link , earg = .earg ) okay1 <- all(is.finite(mymu)) && all(0 < mymu & mymu < 1) okay1 }, list( .link = link, .earg = earg ))), deriv = eval(substitute(expression({ mymu <- eta2theta(eta, .link , earg = .earg ) use.mu <- mymu use.mu[use.mu < .Machine$double.eps^(3/4)] = .Machine$double.eps^(3/4) dexpectile.deta <- dtheta.deta(use.mu, .link , earg = .earg ) myresid <- matrix(y,extra$n,extra$M) - cbind(mu) wor1 <- Wr2(myresid, w = matrix(extra$w.aml, extra$n, extra$M, byrow = TRUE)) c(w) * myresid * wor1 * (dexpectile.deta / (use.mu * (1-use.mu))) }), list( .link = link, .earg = earg ))), weight = eval(substitute(expression({ wz <- c(w) * wor1 * (dexpectile.deta^2 / (use.mu * (1 - use.mu))) wz }), list( .link = link, .earg = earg)))) } amlexponential.deviance <- function(mu, y, w, residuals = FALSE, eta, extra = NULL) { M <- length(extra$w.aml) if (M > 1) y <- matrix(y,extra$n,extra$M) devy <- cbind(-log(y) - 1) devi <- cbind(-log(mu) - y / mu) if (residuals) { stop("not sure here") return(sign(y - mu) * sqrt(2 * abs(devi) * w) * matrix(extra$w,extra$n,extra$M)) } else { all.deviances <- numeric(M) myresid <- matrix(y,extra$n,extra$M) - cbind(mu) for (ii in 1:M) all.deviances[ii] = 2 * sum(c(w) * (devy[, ii] - devi[, ii]) * Wr1(myresid[, ii], w=extra$w.aml[ii])) } if (is.logical(extra$individual) && extra$individual) all.deviances else sum(all.deviances) } amlexponential <- function(w.aml = 1, parallel = FALSE, imethod = 1, digw = 4, link = "loglink") { if (!is.Numeric(w.aml, positive = TRUE)) stop("'w.aml' must be a vector of positive values") if (!is.Numeric(imethod, length.arg = 1, integer.valued = TRUE, positive = TRUE) || imethod > 3) stop("argument 'imethod' must be 1, 2 or 3") link <- as.list(substitute(link)) earg <- link2list(link) link <- attr(earg, "function.name") y.names <- paste("w.aml = ", round(w.aml, digits = digw), sep = "") predictors.names <- c(namesof( paste("expectile(", y.names,")", sep = ""), link, earg = earg)) predictors.names <- paste(predictors.names, collapse = ", ") new("vglmff", blurb = c("Exponential expectile regression by", " asymmetric maximum likelihood estimation\n\n", "Link: ", predictors.names), constraints = eval(substitute(expression({ constraints <- cm.VGAM(matrix(1, M, 1), x = x, bool = .parallel , constraints = constraints) }), list( .parallel = parallel ))), deviance = function(mu, y, w, residuals = FALSE, eta, extra = NULL) { amlexponential.deviance(mu = mu, y = y, w = w, residuals = residuals, eta = eta, extra = extra) }, initialize = eval(substitute(expression({ extra$w.aml <- .w.aml temp5 <- w.y.check(w = w, y = y, Is.positive.y = TRUE, ncol.w.max = 1, ncol.y.max = 1, out.wy = TRUE, maximize = TRUE) w <- temp5$w y <- temp5$y extra$M <- M <- length(extra$w.aml) extra$n <- n extra$y.names <- y.names <- paste("w.aml = ", round(extra$w.aml, digits = .digw ), sep = "") extra$individual = FALSE predictors.names <- c(namesof( paste("expectile(", y.names, ")", sep = ""), .link , earg = .earg , tag = FALSE)) if (!length(etastart)) { mean.init <- if ( .imethod == 1) rep_len(median(y), n) else if ( .imethod == 2) rep_len(weighted.mean(y, w), n) else { 1 / (y + 1) } etastart <- matrix(theta2eta(mean.init, .link , earg = .earg ), n, M) } }), list( .link = link, .earg = earg, .imethod = imethod, .digw = digw, .w.aml = w.aml ))), linkinv = eval(substitute(function(eta, extra = NULL) { mu.ans <- eta <- as.matrix(eta) for (ii in 1:ncol(eta)) mu.ans[, ii] <- eta2theta(eta[, ii], .link , earg = .earg ) dimnames(mu.ans) <- list(dimnames(eta)[[1]], extra$y.names) mu.ans }, list( .link = link, .earg = earg ))), last = eval(substitute(expression({ misc$multipleResponses <- TRUE misc$expected <- TRUE misc$parallel <- .parallel misc$link <- rep_len( .link , M) names(misc$link) <- extra$y.names misc$earg <- vector("list", M) for (ilocal in 1:M) misc$earg[[ilocal]] <- list(theta = NULL) names(misc$earg) <- names(misc$link) extra$percentile <- numeric(M) for (ii in 1:M) extra$percentile[ii] <- 100 * weighted.mean(myresid[, ii] <= 0, w) names(extra$percentile) <- names(misc$link) extra$individual <- TRUE extra$deviance = amlexponential.deviance(mu = mu, y = y, w = w, residuals = FALSE, eta = eta, extra = extra) names(extra$deviance) <- extra$y.names }), list( .link = link, .earg = earg, .parallel = parallel ))), linkfun = eval(substitute(function(mu, extra = NULL) { theta2eta(mu, link = .link , earg = .earg ) }, list( .link = link, .earg = earg ))), vfamily = c("amlexponential"), validparams = eval(substitute(function(eta, y, extra = NULL) { mymu <- eta2theta(eta, .link , earg = .earg ) okay1 <- all(is.finite(mymu)) && all(0 < mymu) okay1 }, list( .link = link, .earg = earg ))), deriv = eval(substitute(expression({ mymu <- eta2theta(eta, .link , earg = .earg ) bigy <- matrix(y,extra$n,extra$M) dl.dmu <- (bigy - mymu) / mymu^2 dmu.deta <- dtheta.deta(mymu, .link , earg = .earg ) myresid <- bigy - cbind(mymu) wor1 <- Wr2(myresid, w = matrix(extra$w.aml, extra$n, extra$M, byrow = TRUE)) c(w) * wor1 * dl.dmu * dmu.deta }), list( .link = link, .earg = earg ))), weight = eval(substitute(expression({ ned2l.dmu2 <- 1 / mymu^2 wz <- c(w) * wor1 * ned2l.dmu2 * dmu.deta^2 wz }), list( .link = link, .earg = earg )))) } rho1check <- function(u, tau = 0.5) u * (tau - (u <= 0)) dalap <- function(x, location = 0, scale = 1, tau = 0.5, kappa = sqrt(tau/(1-tau)), log = FALSE) { if (!is.logical(log.arg <- log) || length(log) != 1) stop("bad input for argument 'log'") rm(log) NN <- max(length(x), length(location), length(scale), length(kappa), length(tau)) if (length(x) != NN) x <- rep_len(x, NN) if (length(location) != NN) location <- rep_len(location, NN) if (length(scale) != NN) scale <- rep_len(scale, NN) if (length(kappa) != NN) kappa <- rep_len(kappa, NN) if (length(tau) != NN) tau <- rep_len(tau, NN) logconst <- 0.5 * log(2) - log(scale) + log(kappa) - log1p(kappa^2) exponent <- -(sqrt(2) / scale) * abs(x - location) * ifelse(x >= location, kappa, 1/kappa) indexTF <- (scale > 0) & (tau > 0) & (tau < 1) & (kappa > 0) logconst[!indexTF] <- NaN if (log.arg) logconst + exponent else exp(logconst + exponent) } ralap <- function(n, location = 0, scale = 1, tau = 0.5, kappa = sqrt(tau/(1-tau))) { use.n <- if ((length.n <- length(n)) > 1) length.n else if (!is.Numeric(n, integer.valued = TRUE, length.arg = 1, positive = TRUE)) stop("bad input for argument 'n'") else n location <- rep_len(location, use.n) scale <- rep_len(scale, use.n) tau <- rep_len(tau, use.n) kappa <- rep_len(kappa, use.n) ans <- location + scale * log(runif(use.n)^kappa / runif(use.n)^(1/kappa)) / sqrt(2) indexTF <- (scale > 0) & (tau > 0) & (tau < 1) & (kappa > 0) ans[!indexTF] <- NaN ans } palap <- function(q, location = 0, scale = 1, tau = 0.5, kappa = sqrt(tau/(1-tau)), lower.tail = TRUE, log.p = FALSE) { if (!is.logical(lower.tail) || length(lower.tail ) != 1) stop("bad input for argument 'lower.tail'") if (!is.logical(log.p) || length(log.p) != 1) stop("bad input for argument 'log.p'") NN <- max(length(q), length(location), length(scale), length(kappa), length(tau)) if (length(q) != NN) q <- rep_len(q, NN) if (length(location) != NN) location <- rep_len(location, NN) if (length(scale) != NN) scale <- rep_len(scale, NN) if (length(kappa) != NN) kappa <- rep_len(kappa, NN) if (length(tau) != NN) tau <- rep_len(tau, NN) exponent <- -(sqrt(2) / scale) * abs(q - location) * ifelse(q >= location, kappa, 1/kappa) temp5 <- exp(exponent) / (1 + kappa^2) index1 <- (q < location) if (lower.tail) { if (log.p) { ans <- log1p(-exp(exponent) / (1 + kappa^2)) logtemp5 <- exponent - log1p(kappa^2) ans[index1] <- 2 * log(kappa[index1]) + logtemp5[index1] } else { ans <- (kappa^2 - expm1(exponent)) / (1 + kappa^2) ans[index1] <- (kappa[index1])^2 * temp5[index1] } } else { if (log.p) { ans <- exponent - log1p(kappa^2) ans[index1] <- log1p(-(kappa[index1])^2 * temp5[index1]) } else { ans <- temp5 ans[index1] <- (1 + (kappa[index1])^2 * (-expm1(exponent[index1]))) / (1+(kappa[index1])^2) } } indexTF <- (scale > 0) & (tau > 0) & (tau < 1) & (kappa > 0) ans[!indexTF] <- NaN ans } qalap <- function(p, location = 0, scale = 1, tau = 0.5, kappa = sqrt(tau / (1 - tau)), lower.tail = TRUE, log.p = FALSE) { if (!is.logical(lower.tail) || length(lower.tail ) != 1) stop("bad input for argument 'lower.tail'") if (!is.logical(log.p) || length(log.p) != 1) stop("bad input for argument 'log.p'") NN <- max(length(p), length(location), length(scale), length(kappa), length(tau)) if (length(p) != NN) p <- rep_len(p, NN) if (length(location) != NN) location <- rep_len(location, NN) if (length(scale) != NN) scale <- rep_len(scale, NN) if (length(kappa) != NN) kappa <- rep_len(kappa, NN) if (length(tau) != NN) tau <- rep_len(tau, NN) temp5 <- kappa^2 / (1 + kappa^2) if (lower.tail) { if (log.p) { ans <- exp(p) index1 <- (exp(p) <= temp5) exponent <- exp(p[index1]) / temp5[index1] ans[index1] <- location[index1] + (scale[index1] * kappa[index1]) * log(exponent) / sqrt(2) ans[!index1] <- location[!index1] - (scale[!index1] / kappa[!index1]) * (log1p((kappa[!index1])^2) + log(-expm1(p[!index1]))) / sqrt(2) } else { ans <- p index1 <- (p <= temp5) exponent <- p[index1] / temp5[index1] ans[index1] <- location[index1] + (scale[index1] * kappa[index1]) * log(exponent) / sqrt(2) ans[!index1] <- location[!index1] - (scale[!index1] / kappa[!index1]) * (log1p((kappa[!index1])^2) + log1p(-p[!index1])) / sqrt(2) } } else { if (log.p) { ans <- -expm1(p) index1 <- (-expm1(p) <= temp5) exponent <- -expm1(p[index1]) / temp5[index1] ans[index1] <- location[index1] + (scale[index1] * kappa[index1]) * log(exponent) / sqrt(2) ans[!index1] <- location[!index1] - (scale[!index1] / kappa[!index1]) * (log1p((kappa[!index1])^2) + p[!index1]) / sqrt(2) } else { ans <- exp(log1p(-p)) index1 <- (p >= (1 / (1+kappa^2))) exponent <- exp(log1p(-p[index1])) / temp5[index1] ans[index1] <- location[index1] + (scale[index1] * kappa[index1]) * log(exponent) / sqrt(2) ans[!index1] <- location[!index1] - (scale[!index1] / kappa[!index1]) * (log1p((kappa[!index1])^2) + log(p[!index1])) / sqrt(2) } } indexTF <- (scale > 0) & (tau > 0) & (tau < 1) & (kappa > 0) ans[!indexTF] <- NaN ans } rloglap <- function(n, location.ald = 0, scale.ald = 1, tau = 0.5, kappa = sqrt(tau/(1-tau))) { use.n <- if ((length.n <- length(n)) > 1) length.n else if (!is.Numeric(n, integer.valued = TRUE, length.arg = 1, positive = TRUE)) stop("bad input for argument 'n'") else n location.ald <- rep_len(location.ald, use.n) scale.ald <- rep_len(scale.ald, use.n) tau <- rep_len(tau, use.n) kappa <- rep_len(kappa, use.n) ans <- exp(location.ald) * (runif(use.n)^kappa / runif(use.n)^(1/kappa))^(scale.ald / sqrt(2)) indexTF <- (scale.ald > 0) & (tau > 0) & (tau < 1) & (kappa > 0) ans[!indexTF] <- NaN ans } dloglap <- function(x, location.ald = 0, scale.ald = 1, tau = 0.5, kappa = sqrt(tau/(1-tau)), log = FALSE) { if (!is.logical(log.arg <- log) || length(log) != 1) stop("bad input for argument 'log'") rm(log) scale <- scale.ald location <- location.ald NN <- max(length(x), length(location), length(scale), length(kappa), length(tau)) if (length(x) != NN) x <- rep_len(x, NN) if (length(location) != NN) location <- rep_len(location, NN) if (length(scale) != NN) scale <- rep_len(scale, NN) if (length(kappa) != NN) kappa <- rep_len(kappa, NN) if (length(tau) != NN) tau <- rep_len(tau, NN) Alpha <- sqrt(2) * kappa / scale.ald Beta <- sqrt(2) / (scale.ald * kappa) Delta <- exp(location.ald) exponent <- ifelse(x >= Delta, -(Alpha+1), (Beta-1)) * (log(x) - location.ald) logdensity <- -location.ald + log(Alpha) + log(Beta) - log(Alpha + Beta) + exponent indexTF <- (scale.ald > 0) & (tau > 0) & (tau < 1) & (kappa > 0) logdensity[!indexTF] <- NaN logdensity[x < 0 & indexTF] <- -Inf if (log.arg) logdensity else exp(logdensity) } qloglap <- function(p, location.ald = 0, scale.ald = 1, tau = 0.5, kappa = sqrt(tau/(1-tau)), lower.tail = TRUE, log.p = FALSE) { if (!is.logical(lower.tail) || length(lower.tail ) != 1) stop("bad input for argument 'lower.tail'") if (!is.logical(log.p) || length(log.p) != 1) stop("bad input for argument 'log.p'") NN <- max(length(p), length(location.ald), length(scale.ald), length(kappa)) p <- rep_len(p, NN) location <- rep_len(location.ald, NN) scale <- rep_len(scale.ald, NN) kappa <- rep_len(kappa, NN) tau <- rep_len(tau, NN) Alpha <- sqrt(2) * kappa / scale.ald Beta <- sqrt(2) / (scale.ald * kappa) Delta <- exp(location.ald) temp9 <- Alpha + Beta if (lower.tail) { if (log.p) { ln.p <- p ans <- ifelse((exp(ln.p) > Alpha / temp9), Delta * (-expm1(ln.p) * temp9 / Beta)^(-1/Alpha), Delta * (exp(ln.p) * temp9 / Alpha)^(1/Beta)) ans[ln.p > 0] <- NaN } else { ans <- ifelse((p > Alpha / temp9), Delta * exp((-1/Alpha) * (log1p(-p) + log(temp9/Beta))), Delta * (p * temp9 / Alpha)^(1/Beta)) ans[p < 0] <- NaN ans[p == 0] <- 0 ans[p == 1] <- Inf ans[p > 1] <- NaN } } else { if (log.p) { ln.p <- p ans <- ifelse((-expm1(ln.p) > Alpha / temp9), Delta * (exp(ln.p) * temp9 / Beta)^(-1/Alpha), Delta * (-expm1(ln.p) * temp9 / Alpha)^(1/Beta)) ans[ln.p > 0] <- NaN } else { ans <- ifelse((p < (temp9 - Alpha) / temp9), Delta * (p * temp9 / Beta)^(-1/Alpha), Delta * exp((1/Beta)*(log1p(-p) + log(temp9/Alpha)))) ans[p < 0] <- NaN ans[p == 0] <- Inf ans[p == 1] <- 0 ans[p > 1] <- NaN } } indexTF <- (scale.ald > 0) & (tau > 0) & (tau < 1) & (kappa > 0) ans[!indexTF] <- NaN ans } ploglap <- function(q, location.ald = 0, scale.ald = 1, tau = 0.5, kappa = sqrt(tau/(1-tau)), lower.tail = TRUE, log.p = FALSE) { if (!is.logical(lower.tail) || length(lower.tail ) != 1) stop("bad input for argument 'lower.tail'") if (!is.logical(log.p) || length(log.p) != 1) stop("bad input for argument 'log.p'") NN <- max(length(q), length(location.ald), length(scale.ald), length(kappa)) location <- rep_len(location.ald, NN) scale <- rep_len(scale.ald, NN) kappa <- rep_len(kappa, NN) q <- rep_len(q, NN) tau <- rep_len(tau, NN) Alpha <- sqrt(2) * kappa / scale.ald Beta <- sqrt(2) / (scale.ald * kappa) Delta <- exp(location.ald) temp9 <- Alpha + Beta index1 <- (Delta <= q) if (lower.tail) { if (log.p) { ans <- log((Alpha / temp9) * (q / Delta)^(Beta)) ans[index1] <- log1p((-(Beta/temp9) * (Delta/q)^(Alpha))[index1]) ans[q <= 0 ] <- -Inf ans[q == Inf] <- 0 } else { ans <- (Alpha / temp9) * (q / Delta)^(Beta) ans[index1] <- -expm1((log(Beta/temp9) + Alpha * log(Delta/q)))[index1] ans[q <= 0] <- 0 ans[q == Inf] <- 1 } } else { if (log.p) { ans <- log1p(-(Alpha / temp9) * (q / Delta)^(Beta)) ans[index1] <- log(((Beta/temp9) * (Delta/q)^(Alpha))[index1]) ans[q <= 0] <- 0 ans[q == Inf] <- -Inf } else { ans <- -expm1(log(Alpha/temp9) + Beta * log(q/Delta)) ans[index1] <- ((Beta/temp9) * (Delta/q)^(Alpha))[index1] ans[q <= 0] <- 1 ans[q == Inf] <- 0 } } indexTF <- (scale.ald > 0) & (tau > 0) & (tau < 1) & (kappa > 0) ans[!indexTF] <- NaN ans } rlogitlap <- function(n, location.ald = 0, scale.ald = 1, tau = 0.5, kappa = sqrt(tau/(1-tau))) { logitlink(ralap(n = n, location = location.ald, scale = scale.ald, tau = tau, kappa = kappa), inverse = TRUE) } dlogitlap <- function(x, location.ald = 0, scale.ald = 1, tau = 0.5, kappa = sqrt(tau/(1-tau)), log = FALSE) { if (!is.logical(log.arg <- log) || length(log) != 1) stop("bad input for argument 'log'") rm(log) NN <- max(length(x), length(location.ald), length(scale.ald), length(kappa)) location <- rep_len(location.ald, NN) scale <- rep_len(scale.ald, NN) kappa <- rep_len(kappa, NN) x <- rep_len(x, NN) tau <- rep_len(tau, NN) Alpha <- sqrt(2) * kappa / scale.ald Beta <- sqrt(2) / (scale.ald * kappa) Delta <- logitlink(location.ald, inverse = TRUE) exponent <- ifelse(x >= Delta, -Alpha, Beta) * (logitlink(x) - location.ald) logdensity <- log(Alpha) + log(Beta) - log(Alpha + Beta) - log(x) - log1p(-x) + exponent indexTF <- (scale.ald > 0) & (tau > 0) & (tau < 1) & (kappa > 0) logdensity[!indexTF] <- NaN logdensity[x < 0 & indexTF] <- -Inf logdensity[x > 1 & indexTF] <- -Inf if (log.arg) logdensity else exp(logdensity) } qlogitlap <- function(p, location.ald = 0, scale.ald = 1, tau = 0.5, kappa = sqrt(tau/(1-tau))) { qqq <- qalap(p = p, location = location.ald, scale = scale.ald, tau = tau, kappa = kappa) ans <- logitlink(qqq, inverse = TRUE) ans[(p < 0) | (p > 1)] <- NaN ans[p == 0] <- 0 ans[p == 1] <- 1 ans } plogitlap <- function(q, location.ald = 0, scale.ald = 1, tau = 0.5, kappa = sqrt(tau/(1-tau))) { NN <- max(length(q), length(location.ald), length(scale.ald), length(kappa)) location.ald <- rep_len(location.ald, NN) scale.ald <- rep_len(scale.ald, NN) kappa <- rep_len(kappa, NN) q <- rep_len(q, NN) tau <- rep_len(tau, NN) indexTF <- (q > 0) & (q < 1) qqq <- logitlink(q[indexTF]) ans <- q ans[indexTF] <- palap(q = qqq, location = location.ald[indexTF], scale = scale.ald[indexTF], tau = tau[indexTF], kappa = kappa[indexTF]) ans[q >= 1] <- 1 ans[q <= 0] <- 0 ans } rprobitlap <- function(n, location.ald = 0, scale.ald = 1, tau = 0.5, kappa = sqrt(tau/(1-tau))) { probitlink(ralap(n = n, location = location.ald, scale = scale.ald, tau = tau, kappa = kappa), inverse = TRUE) } dprobitlap <- function(x, location.ald = 0, scale.ald = 1, tau = 0.5, kappa = sqrt(tau/(1-tau)), log = FALSE, meth2 = TRUE) { if (!is.logical(log.arg <- log) || length(log) != 1) stop("bad input for argument 'log'") rm(log) NN <- max(length(x), length(location.ald), length(scale.ald), length(kappa)) location.ald <- rep_len(location.ald, NN) scale.ald <- rep_len(scale.ald, NN) kappa <- rep_len(kappa, NN) x <- rep_len(x, NN) tau <- rep_len(tau, NN) logdensity <- x * NaN index1 <- (x > 0) & (x < 1) indexTF <- (scale.ald > 0) & (tau > 0) & (tau < 1) & (kappa > 0) if (meth2) { dx.dy <- x use.x <- probitlink(x[index1]) logdensity[index1] <- dalap(x = use.x, location = location.ald[index1], scale = scale.ald[index1], tau = tau[index1], kappa = kappa[index1], log = TRUE) } else { Alpha <- sqrt(2) * kappa / scale.ald Beta <- sqrt(2) / (scale.ald * kappa) Delta <- pnorm(location.ald) use.x <- qnorm(x) log.dy.dw <- dnorm(use.x, log = TRUE) exponent <- ifelse(x >= Delta, -Alpha, Beta) * (use.x - location.ald) - log.dy.dw logdensity[index1] <- (log(Alpha) + log(Beta) - log(Alpha + Beta) + exponent)[index1] } logdensity[!indexTF] <- NaN logdensity[x < 0 & indexTF] <- -Inf logdensity[x > 1 & indexTF] <- -Inf if (meth2) { dx.dy[index1] <- probitlink(x[index1], inverse = TRUE, deriv = 1) dx.dy[!index1] <- 0 dx.dy[!indexTF] <- NaN if (log.arg) logdensity - log(abs(dx.dy)) else exp(logdensity) / abs(dx.dy) } else { if (log.arg) logdensity else exp(logdensity) } } qprobitlap <- function(p, location.ald = 0, scale.ald = 1, tau = 0.5, kappa = sqrt(tau/(1-tau))) { qqq <- qalap(p = p, location = location.ald, scale = scale.ald, tau = tau, kappa = kappa) ans <- probitlink(qqq, inverse = TRUE) ans[(p < 0) | (p > 1)] = NaN ans[p == 0] <- 0 ans[p == 1] <- 1 ans } pprobitlap <- function(q, location.ald = 0, scale.ald = 1, tau = 0.5, kappa = sqrt(tau/(1-tau))) { NN <- max(length(q), length(location.ald), length(scale.ald), length(kappa)) location.ald <- rep_len(location.ald, NN) scale.ald <- rep_len(scale.ald, NN) kappa <- rep_len(kappa, NN) q <- rep_len(q, NN) tau <- rep_len(tau, NN) indexTF <- (q > 0) & (q < 1) qqq <- probitlink(q[indexTF]) ans <- q ans[indexTF] <- palap(q = qqq, location = location.ald[indexTF], scale = scale.ald[indexTF], tau = tau[indexTF], kappa = kappa[indexTF]) ans[q >= 1] <- 1 ans[q <= 0] <- 0 ans } rclogloglap <- function(n, location.ald = 0, scale.ald = 1, tau = 0.5, kappa = sqrt(tau/(1-tau))) { clogloglink(ralap(n = n, location = location.ald, scale = scale.ald, tau = tau, kappa = kappa), inverse = TRUE) } dclogloglap <- function(x, location.ald = 0, scale.ald = 1, tau = 0.5, kappa = sqrt(tau/(1-tau)), log = FALSE, meth2 = TRUE) { if (!is.logical(log.arg <- log) || length(log) != 1) stop("bad input for argument 'log'") rm(log) NN <- max(length(x), length(location.ald), length(scale.ald), length(kappa)) location.ald <- rep_len(location.ald, NN) scale.ald <- rep_len(scale.ald, NN) kappa <- rep_len(kappa, NN) x <- rep_len(x, NN) tau <- rep_len(tau, NN) logdensity <- x * NaN index1 <- (x > 0) & (x < 1) indexTF <- (scale.ald > 0) & (tau > 0) & (tau < 1) & (kappa > 0) if (meth2) { dx.dy <- x use.w <- clogloglink(x[index1]) logdensity[index1] <- dalap(x = use.w, location = location.ald[index1], scale = scale.ald[index1], tau = tau[index1], kappa = kappa[index1], log = TRUE) } else { Alpha <- sqrt(2) * kappa / scale.ald Beta <- sqrt(2) / (scale.ald * kappa) Delta <- clogloglink(location.ald, inverse = TRUE) exponent <- ifelse(x >= Delta, -(Alpha+1), Beta-1) * log(-log1p(-x)) + ifelse(x >= Delta, Alpha, -Beta) * location.ald logdensity[index1] <- (log(Alpha) + log(Beta) - log(Alpha + Beta) - log1p(-x) + exponent)[index1] } logdensity[!indexTF] <- NaN logdensity[x < 0 & indexTF] <- -Inf logdensity[x > 1 & indexTF] <- -Inf if (meth2) { dx.dy[index1] <- clogloglink(x[index1], inverse = TRUE, deriv = 1) dx.dy[!index1] <- 0 dx.dy[!indexTF] <- NaN if (log.arg) logdensity - log(abs(dx.dy)) else exp(logdensity) / abs(dx.dy) } else { if (log.arg) logdensity else exp(logdensity) } } qclogloglap <- function(p, location.ald = 0, scale.ald = 1, tau = 0.5, kappa = sqrt(tau/(1-tau))) { qqq <- qalap(p = p, location = location.ald, scale = scale.ald, tau = tau, kappa = kappa) ans <- clogloglink(qqq, inverse = TRUE) ans[(p < 0) | (p > 1)] <- NaN ans[p == 0] <- 0 ans[p == 1] <- 1 ans } pclogloglap <- function(q, location.ald = 0, scale.ald = 1, tau = 0.5, kappa = sqrt(tau/(1-tau))) { NN <- max(length(q), length(location.ald), length(scale.ald), length(kappa)) location.ald <- rep_len(location.ald, NN) scale.ald <- rep_len(scale.ald, NN) kappa <- rep_len(kappa, NN) q <- rep_len(q, NN) tau <- rep_len(tau, NN) indexTF <- (q > 0) & (q < 1) qqq <- clogloglink(q[indexTF]) ans <- q ans[indexTF] <- palap(q = qqq, location = location.ald[indexTF], scale = scale.ald[indexTF], tau = tau[indexTF], kappa = kappa[indexTF]) ans[q >= 1] <- 1 ans[q <= 0] <- 0 ans } alaplace2.control <- function(maxit = 100, ...) { list(maxit = maxit) } alaplace2 <- function(tau = NULL, llocation = "identitylink", lscale = "loglink", ilocation = NULL, iscale = NULL, kappa = sqrt(tau / (1-tau)), ishrinkage = 0.95, parallel.locat = TRUE ~ 0, parallel.scale = FALSE ~ 0, digt = 4, idf.mu = 3, imethod = 1, zero = "scale") { apply.parint.locat <- FALSE apply.parint.scale <- TRUE llocat <- as.list(substitute(llocation)) elocat <- link2list(llocat) llocat <- attr(elocat, "function.name") lscale <- as.list(substitute(lscale)) escale <- link2list(lscale) lscale <- attr(escale, "function.name") ilocat <- ilocation if (!is.Numeric(kappa, positive = TRUE)) stop("bad input for argument 'kappa'") if (!is.Numeric(imethod, length.arg = 1, integer.valued = TRUE, positive = TRUE) || imethod > 4) stop("argument 'imethod' must be 1, 2 or ... 4") if (length(iscale) && !is.Numeric(iscale, positive = TRUE)) stop("bad input for argument 'iscale'") if (!is.Numeric(ishrinkage, length.arg = 1) || ishrinkage < 0 || ishrinkage > 1) stop("bad input for argument 'ishrinkage'") if (length(tau) && max(abs(kappa - sqrt(tau / (1 - tau)))) > 1.0e-6) stop("arguments 'kappa' and 'tau' do not match") fittedMean <- FALSE if (!is.logical(fittedMean) || length(fittedMean) != 1) stop("bad input for argument 'fittedMean'") new("vglmff", blurb = c("Two-parameter asymmetric Laplace distribution\n\n", "Links: ", namesof("location", llocat, earg = elocat), ", ", namesof("scale", lscale, earg = escale), "\n\n", "Mean: ", "location + scale * (1/kappa - kappa) / sqrt(2)", "\n", "Quantiles: location", "\n", "Variance: scale^2 * (1 + kappa^4) / (2 * kappa^2)"), constraints = eval(substitute(expression({ onemat <- matrix(1, Mdiv2, 1) constraints.orig <- constraints cm1.locat <- kronecker(diag(Mdiv2), rbind(1, 0)) cmk.locat <- kronecker(onemat, rbind(1, 0)) con.locat <- cm.VGAM(cmk.locat, x = x, bool = .parallel.locat , constraints = constraints.orig, apply.int = .apply.parint.locat , cm.default = cm1.locat, cm.intercept.default = cm1.locat) cm1.scale <- kronecker(diag(Mdiv2), rbind(0, 1)) cmk.scale <- kronecker(onemat, rbind(0, 1)) con.scale <- cm.VGAM(cmk.scale, x = x, bool = .parallel.scale , constraints = constraints.orig, apply.int = .apply.parint.scale , cm.default = cm1.scale, cm.intercept.default = cm1.scale) con.use <- con.scale for (klocal in seq_along(con.scale)) { con.use[[klocal]] <- cbind(con.locat[[klocal]], con.scale[[klocal]]) } constraints <- con.use constraints <- cm.zero.VGAM(constraints, x = x, .zero , M = M, predictors.names = predictors.names, M1 = M1) }), list( .parallel.locat = parallel.locat, .parallel.scale = parallel.scale, .zero = zero, .apply.parint.scale = apply.parint.scale, .apply.parint.locat = apply.parint.locat ))), infos = eval(substitute(function(...) { list(M1 = 2, Q1 = 1, summary.pvalues = FALSE, expected = TRUE, multipleResponses = TRUE, parameters.names = c("location", "scale"), true.mu = .fittedMean , zero = .zero , tau = .tau , kappa = .kappa ) }, list( .tau = tau, .kappa = kappa, .fittedMean = fittedMean, .zero = zero ))), initialize = eval(substitute(expression({ M1 <- 2 temp5 <- w.y.check(w = w, y = y, ncol.w.max = if (length( .kappa ) > 1) 1 else Inf, ncol.y.max = if (length( .kappa ) > 1) 1 else Inf, out.wy = TRUE, colsyperw = 1, maximize = TRUE) w <- temp5$w y <- temp5$y extra$ncoly <- ncoly <- ncol(y) if ((ncoly > 1) && (length( .kappa ) > 1)) stop("response must be a vector if 'kappa' or 'tau' ", "has a length greater than one") extra$kappa <- .kappa extra$tau <- extra$kappa^2 / (1 + extra$kappa^2) extra$Mdiv2 <- Mdiv2 <- max(ncoly, length( .kappa )) extra$M <- M <- M1 * Mdiv2 extra$n <- n extra$tau.names <- tau.names <- paste("(tau = ", round(extra$tau, digits = .digt), ")", sep = "") extra$Y.names <- Y.names <- if (ncoly > 1) dimnames(y)[[2]] else "y" if (is.null(Y.names) || any(Y.names == "")) extra$Y.names <- Y.names <- paste("y", 1:ncoly, sep = "") extra$y.names <- y.names <- if (ncoly > 1) paste(Y.names, tau.names, sep = "") else tau.names extra$individual <- FALSE mynames1 <- param.names("location", Mdiv2, skip1 = TRUE) mynames2 <- param.names("scale", Mdiv2, skip1 = TRUE) predictors.names <- c(namesof(mynames1, .llocat , earg = .elocat , tag = FALSE), namesof(mynames2, .lscale , earg = .escale , tag = FALSE)) predictors.names <- predictors.names[interleave.VGAM(M, M1 = M1)] locat.init <- scale.init <- matrix(0, n, Mdiv2) if (!length(etastart)) { for (jay in 1:Mdiv2) { y.use <- if (ncoly > 1) y[, jay] else y Jay <- if (ncoly > 1) jay else 1 if ( .imethod == 1) { locat.init[, jay] <- weighted.mean(y.use, w[, Jay]) scale.init[, jay] <- sqrt(var(y.use) / 2) } else if ( .imethod == 2) { locat.init[, jay] <- median(y.use) scale.init[, jay] <- sqrt(sum(c(w[, Jay]) * abs(y - median(y.use))) / (sum(w[, Jay]) * 2)) } else if ( .imethod == 3) { Fit5 <- vsmooth.spline(x = x[, min(ncol(x), 2)], y = y.use, w = w[, Jay], df = .idf.mu ) locat.init[, jay] <- predict(Fit5, x = x[, min(ncol(x), 2)])$y scale.init[, jay] <- sqrt(sum(c(w[, Jay]) * abs(y.use - median(y.use))) / ( sum(w[, Jay]) * 2)) } else { use.this <- weighted.mean(y.use, w[, Jay]) locat.init[, jay] <- (1 - .ishrinkage ) * y.use + .ishrinkage * use.this scale.init[, jay] <- sqrt(sum(c(w[, Jay]) * abs(y.use - median(y.use ))) / (sum(w[, Jay]) * 2)) } } if (length( .ilocat )) { locat.init <- matrix( .ilocat , n, Mdiv2, byrow = TRUE) } if (length( .iscale )) { scale.init <- matrix( .iscale , n, Mdiv2, byrow = TRUE) } etastart <- cbind(theta2eta(locat.init, .llocat , earg = .elocat ), theta2eta(scale.init, .lscale , earg = .escale )) etastart <- etastart[, interleave.VGAM(M, M1 = M1), drop = FALSE] } }), list( .imethod = imethod, .idf.mu = idf.mu, .ishrinkage = ishrinkage, .digt = digt, .elocat = elocat, .escale = escale, .llocat = llocat, .lscale = lscale, .kappa = kappa, .ilocat = ilocat, .iscale = iscale ))), linkinv = eval(substitute(function(eta, extra = NULL) { M1 <- 2 Mdiv2 <- ncol(eta) / M1 vTF <- c(TRUE, FALSE) locat <- eta2theta(eta[, vTF, drop = FALSE], .llocat , earg = .elocat ) dimnames(locat) <- list(dimnames(eta)[[1]], extra$y.names) myans <- if ( .fittedMean ) { kappamat <- matrix(extra$kappa, extra$n, extra$Mdiv2, byrow = TRUE) Scale <- eta2theta(eta[, !vTF, drop = FALSE], .lscale , earg = .escale ) locat + Scale * (1/kappamat - kappamat) } else { locat } dimnames(myans) <- list(dimnames(myans)[[1]], extra$y.names) myans }, list( .elocat = elocat, .llocat = llocat, .escale = escale, .lscale = lscale, .fittedMean = fittedMean, .kappa = kappa ))), last = eval(substitute(expression({ M1 <- 2 Mdiv2 <- ncol(eta) / M1 misc$link <- setNames(c(rep_len( .llocat , Mdiv2), rep_len( .lscale , Mdiv2)), c(mynames1, mynames2))[interleave.VGAM(M, M1 = M1)] misc$earg <- vector("list", M) for (ii in 1:Mdiv2) { misc$earg[[M1 * ii - 1]] <- .elocat misc$earg[[M1 * ii ]] <- .escale } names(misc$earg) <- names(misc$link) extra$kappa <- misc$kappa <- .kappa extra$tau <- misc$tau <- misc$kappa^2 / (1 + misc$kappa^2) extra$percentile <- numeric(Mdiv2) locat <- as.matrix(locat) for (ii in 1:Mdiv2) { y.use <- if (ncoly > 1) y[, ii] else y Jay <- if (ncoly > 1) ii else 1 extra$percentile[ii] <- 100 * weighted.mean(y.use <= locat[, ii], w[, Jay]) } names(extra$percentile) <- y.names }), list( .elocat = elocat, .llocat = llocat, .escale = escale, .lscale = lscale, .fittedMean = fittedMean, .kappa = kappa ))), loglikelihood = eval(substitute( function(mu, y, w, residuals = FALSE, eta, extra = NULL, summation = TRUE) { M1 <- 2 Mdiv2 <- ncol(eta) / M1 ymat <- matrix(y, extra$n, extra$Mdiv2) kappamat <- matrix(extra$kappa, extra$n, extra$Mdiv2, byrow = TRUE) vTF <- c(TRUE, FALSE) locat <- eta2theta(eta[, vTF, drop = FALSE], .llocat , earg = .elocat ) Scale <- eta2theta(eta[, !vTF, drop = FALSE], .lscale , earg = .escale ) if (residuals) { stop("loglikelihood residuals not implemented yet") } else { ll.elts <- c(w) * dalap(x = c(ymat), location = c(locat), scale = c(Scale), kappa = c(kappamat), log = TRUE) if (summation) { sum(ll.elts) } else { ll.elts } } }, list( .elocat = elocat, .llocat = llocat, .escale = escale, .lscale = lscale, .kappa = kappa ))), vfamily = c("alaplace2"), validparams = eval(substitute(function(eta, y, extra = NULL) { vTF <- c(TRUE, FALSE) locat <- eta2theta(eta[, vTF, drop = FALSE], .llocat , earg = .elocat ) Scale <- eta2theta(eta[, !vTF, drop = FALSE], .lscale , earg = .escale ) okay1 <- all(is.finite(locat)) && all(is.finite(Scale)) && all(0 < Scale) okay1 }, list( .elocat = elocat, .llocat = llocat, .escale = escale, .lscale = lscale, .kappa = kappa ))), simslot = eval(substitute( function(object, nsim) { pwts <- if (length(pwts <- [email protected]) > 0) pwts else weights(object, type = "prior") if (any(pwts != 1)) warning("ignoring prior weights") eta <- predict(object) extra <- object@extra vTF <- c(TRUE, FALSE) locat <- eta2theta(eta[, vTF, drop = FALSE], .llocat , earg = .elocat ) Scale <- eta2theta(eta[, !vTF, drop = FALSE], .lscale , earg = .escale ) kappamat <- matrix(extra$kappa, extra$n, extra$Mdiv2, byrow = TRUE) ralap(nsim * length(Scale), location = c(locat), scale = c(Scale), kappa = c(kappamat)) }, list( .elocat = elocat, .llocat = llocat, .escale = escale, .lscale = lscale, .kappa = kappa ))), deriv = eval(substitute(expression({ M1 <- 2 Mdiv2 <- ncol(eta) / M1 ymat <- matrix(y, n, Mdiv2) vTF <- c(TRUE, FALSE) locat <- eta2theta(eta[, vTF, drop = FALSE], .llocat , earg = .elocat ) Scale <- eta2theta(eta[, !vTF, drop = FALSE], .lscale , earg = .escale ) kappamat <- matrix(extra$kappa, n, Mdiv2, byrow = TRUE) zedd <- abs(ymat - locat) / Scale dl.dlocat <- sqrt(2) * ifelse(ymat >= locat, kappamat, 1/kappamat) * sign(ymat - locat) / Scale dl.dscale <- sqrt(2) * ifelse(ymat >= locat, kappamat, 1/kappamat) * zedd / Scale - 1 / Scale dlocat.deta <- dtheta.deta(locat, .llocat , earg = .elocat ) dscale.deta <- dtheta.deta(Scale, .lscale , earg = .escale ) ans <- c(w) * cbind(dl.dlocat * dlocat.deta, dl.dscale * dscale.deta) ans[, interleave.VGAM(ncol(ans), M1 = M1)] }), list( .escale = escale, .lscale = lscale, .elocat = elocat, .llocat = llocat, .kappa = kappa ))), weight = eval(substitute(expression({ wz <- matrix(NA_real_, n, M) d2l.dlocat2 <- 2 / Scale^2 d2l.dscale2 <- 1 / Scale^2 wz[, vTF] <- d2l.dlocat2 * dlocat.deta^2 wz[, !vTF] <- d2l.dscale2 * dscale.deta^2 c(w) * wz }), list( .escale = escale, .lscale = lscale, .elocat = elocat, .llocat = llocat )))) } alaplace1.control <- function(maxit = 100, ...) { list(maxit = maxit) } alaplace1 <- function(tau = NULL, llocation = "identitylink", ilocation = NULL, kappa = sqrt(tau/(1-tau)), Scale.arg = 1, ishrinkage = 0.95, parallel.locat = TRUE ~ 0, digt = 4, idf.mu = 3, zero = NULL, imethod = 1) { apply.parint.locat <- FALSE if (!is.Numeric(kappa, positive = TRUE)) stop("bad input for argument 'kappa'") if (length(tau) && max(abs(kappa - sqrt(tau/(1-tau)))) > 1.0e-6) stop("arguments 'kappa' and 'tau' do not match") if (!is.Numeric(imethod, length.arg = 1, integer.valued = TRUE, positive = TRUE) || imethod > 4) stop("argument 'imethod' must be 1, 2 or ... 4") llocation <- llocation llocat <- as.list(substitute(llocation)) elocat <- link2list(llocat) llocat <- attr(elocat, "function.name") ilocat <- ilocation if (!is.Numeric(ishrinkage, length.arg = 1) || ishrinkage < 0 || ishrinkage > 1) stop("bad input for argument 'ishrinkage'") if (!is.Numeric(Scale.arg, positive = TRUE)) stop("bad input for argument 'Scale.arg'") fittedMean <- FALSE if (!is.logical(fittedMean) || length(fittedMean) != 1) stop("bad input for argument 'fittedMean'") new("vglmff", blurb = c("One-parameter asymmetric Laplace distribution\n\n", "Links: ", namesof("location", llocat, earg = elocat), "\n", "\n", "Mean: location + scale * (1/kappa - kappa) / ", "sqrt(2)", "\n", "Quantiles: location", "\n", "Variance: scale^2 * (1 + kappa^4) / (2 * kappa^2)"), constraints = eval(substitute(expression({ onemat <- matrix(1, M, 1) constraints.orig <- constraints cm1.locat <- diag(M) cmk.locat <- onemat con.locat <- cm.VGAM(cmk.locat, x = x, bool = .parallel.locat , constraints = constraints.orig, apply.int = .apply.parint.locat , cm.default = cm1.locat, cm.intercept.default = cm1.locat) constraints <- con.locat constraints <- cm.zero.VGAM(constraints, x = x, .zero , M = M, predictors.names = predictors.names, M1 = 1) }), list( .parallel.locat = parallel.locat, .zero = zero, .apply.parint.locat = apply.parint.locat ))), infos = eval(substitute(function(...) { list(M1 = 1, Q1 = 1, summary.pvalues = FALSE, tau = .tau , multipleResponses = FALSE, parameters.names = c("location"), kappa = .kappa) }, list( .kappa = kappa, .tau = tau ))), initialize = eval(substitute(expression({ extra$M1 <- M1 <- 1 temp5 <- w.y.check(w = w, y = y, ncol.w.max = if (length( .kappa ) > 1) 1 else Inf, ncol.y.max = if (length( .kappa ) > 1) 1 else Inf, out.wy = TRUE, maximize = TRUE) w <- temp5$w y <- temp5$y extra$ncoly <- ncoly <- ncol(y) if ((ncoly > 1) && (length( .kappa ) > 1 || length( .Scale.arg ) > 1)) stop("response must be a vector if 'kappa' or 'Scale.arg' ", "has a length greater than one") extra$kappa <- .kappa extra$tau <- extra$kappa^2 / (1 + extra$kappa^2) extra$M <- M <- max(length( .Scale.arg ), ncoly, length( .kappa )) extra$Scale <- rep_len( .Scale.arg , M) extra$kappa <- rep_len( .kappa , M) extra$tau <- extra$kappa^2 / (1 + extra$kappa^2) extra$n <- n extra$tau.names <- tau.names <- paste("(tau = ", round(extra$tau, digits = .digt), ")", sep = "") extra$Y.names <- Y.names <- if (ncoly > 1) dimnames(y)[[2]] else "y" if (is.null(Y.names) || any(Y.names == "")) extra$Y.names <- Y.names <- paste("y", 1:ncoly, sep = "") extra$y.names <- y.names <- if (ncoly > 1) paste(Y.names, tau.names, sep = "") else tau.names extra$individual <- FALSE mynames1 <- param.names("location", M, skip1 = TRUE) predictors.names <- c(namesof(mynames1, .llocat , earg = .elocat , tag = FALSE)) locat.init <- matrix(0, n, M) if (!length(etastart)) { for (jay in 1:M) { y.use <- if (ncoly > 1) y[, jay] else y if ( .imethod == 1) { locat.init[, jay] <- weighted.mean(y.use, w[, min(jay, ncol(w))]) } else if ( .imethod == 2) { locat.init[, jay] <- median(y.use) } else if ( .imethod == 3) { Fit5 <- vsmooth.spline(x = x[, min(ncol(x), 2)], y = y.use, w = w, df = .idf.mu ) locat.init[, jay] <- c(predict(Fit5, x = x[, min(ncol(x), 2)])$y) } else { use.this <- weighted.mean(y.use, w[, min(jay, ncol(w))]) locat.init[, jay] <- (1- .ishrinkage ) * y.use + .ishrinkage * use.this } if (length( .ilocat )) { locat.init <- matrix( .ilocat , n, M, byrow = TRUE) } if ( .llocat == "loglink") locat.init <- abs(locat.init) etastart <- cbind(theta2eta(locat.init, .llocat , earg = .elocat )) } } }), list( .imethod = imethod, .idf.mu = idf.mu, .ishrinkage = ishrinkage, .digt = digt, .elocat = elocat, .Scale.arg = Scale.arg, .llocat = llocat, .kappa = kappa, .ilocat = ilocat ))), linkinv = eval(substitute(function(eta, extra = NULL) { if ( .fittedMean ) { kappamat <- matrix(extra$kappa, extra$n, extra$M, byrow = TRUE) locat <- eta2theta(eta, .llocat , earg = .elocat ) Scale <- matrix(extra$Scale, extra$n, extra$M, byrow = TRUE) locat + Scale * (1/kappamat - kappamat) } else { locat <- eta2theta(eta, .llocat , earg = .elocat ) if (length(locat) > extra$n) dimnames(locat) <- list(dimnames(eta)[[1]], extra$y.names) locat } }, list( .elocat = elocat, .llocat = llocat, .fittedMean = fittedMean, .Scale.arg = Scale.arg, .kappa = kappa ))), last = eval(substitute(expression({ M1 <- extra$M1 misc$M1 <- M1 misc$multipleResponses <- TRUE misc$link <- setNames(rep_len( .llocat , M), mynames1) misc$earg <- vector("list", M) names(misc$earg) <- names(misc$link) for (ii in 1:M) { misc$earg[[ii]] <- .elocat } misc$expected <- TRUE extra$kappa <- misc$kappa <- .kappa extra$tau <- misc$tau <- misc$kappa^2 / (1 + misc$kappa^2) misc$true.mu <- .fittedMean extra$percentile <- numeric(M) locat <- as.matrix(locat) for (ii in 1:M) { y.use <- if (ncoly > 1) y[, ii] else y extra$percentile[ii] <- 100 * weighted.mean(y.use <= locat[, ii], w[, min(ii, ncol(w))]) } names(extra$percentile) <- y.names extra$Scale.arg <- .Scale.arg }), list( .elocat = elocat, .llocat = llocat, .Scale.arg = Scale.arg, .fittedMean = fittedMean, .kappa = kappa ))), loglikelihood = eval(substitute( function(mu, y, w, residuals = FALSE, eta, extra = NULL, summation = TRUE) { ymat <- matrix(y, extra$n, extra$M) locat <- eta2theta(eta, .llocat , earg = .elocat ) kappamat <- matrix(extra$kappa, extra$n, extra$M, byrow = TRUE) Scale <- matrix(extra$Scale, extra$n, extra$M, byrow = TRUE) if (residuals) { stop("loglikelihood residuals not implemented yet") } else { ll.elts <- c(w) * dalap(x = c(ymat), locat = c(locat), scale = c(Scale), kappa = c(kappamat), log = TRUE) if (summation) { sum(ll.elts) } else { ll.elts } } }, list( .elocat = elocat, .llocat = llocat, .Scale.arg = Scale.arg, .kappa = kappa ))), vfamily = c("alaplace1"), validparams = eval(substitute(function(eta, y, extra = NULL) { locat <- eta2theta(eta, .llocat , earg = .elocat ) okay1 <- all(is.finite(locat)) okay1 }, list( .elocat = elocat, .llocat = llocat, .Scale.arg = Scale.arg, .kappa = kappa ))), simslot = eval(substitute( function(object, nsim) { pwts <- if (length(pwts <- [email protected]) > 0) pwts else weights(object, type = "prior") if (any(pwts != 1)) warning("ignoring prior weights") eta <- predict(object) extra <- object@extra locat <- eta2theta(eta, .llocat , .elocat ) Scale <- matrix(extra$Scale, extra$n, extra$M, byrow = TRUE) kappamat <- matrix(extra$kappa, extra$n, extra$M, byrow = TRUE) ralap(nsim * length(Scale), location = c(locat), scale = c(Scale), kappa = c(kappamat)) }, list( .elocat = elocat, .llocat = llocat, .Scale.arg = Scale.arg, .kappa = kappa ))), deriv = eval(substitute(expression({ ymat <- matrix(y, n, M) Scale <- matrix(extra$Scale, extra$n, extra$M, byrow = TRUE) locat <- eta2theta(eta, .llocat , earg = .elocat ) kappamat <- matrix(extra$kappa, n, M, byrow = TRUE) zedd <- abs(ymat-locat) / Scale dl.dlocat <- ifelse(ymat >= locat, kappamat, 1/kappamat) * sqrt(2) * sign(ymat - locat) / Scale dlocat.deta <- dtheta.deta(locat, .llocat , earg = .elocat ) c(w) * cbind(dl.dlocat * dlocat.deta) }), list( .Scale.arg = Scale.arg, .elocat = elocat, .llocat = llocat, .kappa = kappa ))), weight = eval(substitute(expression({ d2l.dlocat2 <- 2 / Scale^2 wz <- cbind(d2l.dlocat2 * dlocat.deta^2) c(w) * wz }), list( .Scale.arg = Scale.arg, .elocat = elocat, .llocat = llocat )))) } alaplace3.control <- function(maxit = 100, ...) { list(maxit = maxit) } alaplace3 <- function(llocation = "identitylink", lscale = "loglink", lkappa = "loglink", ilocation = NULL, iscale = NULL, ikappa = 1.0, imethod = 1, zero = c("scale", "kappa")) { llocat <- as.list(substitute(llocation)) elocat <- link2list(llocat) llocat <- attr(elocat, "function.name") ilocat <- ilocation lscale <- as.list(substitute(lscale)) escale <- link2list(lscale) lscale <- attr(escale, "function.name") lkappa <- as.list(substitute(lkappa)) ekappa <- link2list(lkappa) lkappa <- attr(ekappa, "function.name") if (!is.Numeric(imethod, length.arg = 1, integer.valued = TRUE, positive = TRUE) || imethod > 2) stop("argument 'imethod' must be 1 or 2") if (length(iscale) && !is.Numeric(iscale, positive = TRUE)) stop("bad input for argument 'iscale'") new("vglmff", blurb = c("Three-parameter asymmetric Laplace distribution\n\n", "Links: ", namesof("location", llocat, earg = elocat), ", ", namesof("scale", lscale, earg = escale), ", ", namesof("kappa", lkappa, earg = ekappa), "\n", "\n", "Mean: location + scale * (1/kappa - kappa) / sqrt(2)", "\n", "Variance: Scale^2 * (1 + kappa^4) / (2 * kappa^2)"), constraints = eval(substitute(expression({ constraints <- cm.zero.VGAM(constraints, x = x, .zero , M = M, predictors.names = predictors.names, M1 = 3) }), list( .zero = zero ))), infos = eval(substitute(function(...) { list(M1 = 3, Q1 = 1, multipleResponses = FALSE, parameters.names = c("location", "scale", "kappa"), summary.pvalues = FALSE, zero = .zero ) }, list( .zero = zero ))), initialize = eval(substitute(expression({ w.y.check(w = w, y = y, ncol.w.max = 1, ncol.y.max = 1) predictors.names <- c(namesof("location", .llocat , earg = .elocat, tag = FALSE), namesof("scale", .lscale , earg = .escale, tag = FALSE), namesof("kappa", .lkappa , earg = .ekappa, tag = FALSE)) if (!length(etastart)) { kappa.init <- if (length( .ikappa )) rep_len( .ikappa , n) else rep_len( 1.0 , n) if ( .imethod == 1) { locat.init <- median(y) scale.init <- sqrt(var(y) / 2) } else { locat.init <- y scale.init <- sqrt(sum(c(w)*abs(y-median(y ))) / (sum(w) *2)) } locat.init <- if (length( .ilocat )) rep_len( .ilocat , n) else rep_len(locat.init, n) scale.init <- if (length( .iscale )) rep_len( .iscale , n) else rep_len(scale.init, n) etastart <- cbind(theta2eta(locat.init, .llocat , earg = .elocat ), theta2eta(scale.init, .lscale , earg = .escale ), theta2eta(kappa.init, .lkappa, earg = .ekappa)) } }), list( .imethod = imethod, .elocat = elocat, .escale = escale, .ekappa = ekappa, .llocat = llocat, .lscale = lscale, .lkappa = lkappa, .ilocat = ilocat, .iscale = iscale, .ikappa = ikappa ))), linkinv = eval(substitute(function(eta, extra = NULL) { locat <- eta2theta(eta[, 1], .llocat , earg = .elocat ) Scale <- eta2theta(eta[, 2], .lscale , earg = .escale ) kappa <- eta2theta(eta[, 3], .lkappa, earg = .ekappa) locat + Scale * (1/kappa - kappa) / sqrt(2) }, list( .elocat = elocat, .llocat = llocat, .escale = escale, .lscale = lscale, .ekappa = ekappa, .lkappa = lkappa ))), last = eval(substitute(expression({ misc$link <- c(location = .llocat , scale = .lscale , kappa = .lkappa ) misc$earg <- list(location = .elocat, scale = .escale, kappa = .ekappa ) misc$expected = TRUE }), list( .elocat = elocat, .llocat = llocat, .escale = escale, .lscale = lscale, .ekappa = ekappa, .lkappa = lkappa ))), loglikelihood = eval(substitute( function(mu, y, w, residuals = FALSE, eta, extra = NULL, summation = TRUE) { locat <- eta2theta(eta[, 1], .llocat , earg = .elocat ) Scale <- eta2theta(eta[, 2], .lscale , earg = .escale ) kappa <- eta2theta(eta[, 3], .lkappa , earg = .ekappa ) if (residuals) { stop("loglikelihood residuals not implemented yet") } else { ll.elts <- c(w) * dalap(x = y, locat = locat, scale = Scale, kappa = kappa, log = TRUE) if (summation) { sum(ll.elts) } else { ll.elts } } }, list( .elocat = elocat, .llocat = llocat, .escale = escale, .lscale = lscale, .ekappa = ekappa, .lkappa = lkappa ))), vfamily = c("alaplace3"), validparams = eval(substitute(function(eta, y, extra = NULL) { locat <- eta2theta(eta[, 1], .llocat , earg = .elocat ) Scale <- eta2theta(eta[, 2], .lscale , earg = .escale ) kappa <- eta2theta(eta[, 3], .lkappa , earg = .ekappa ) okay1 <- all(is.finite(locat)) && all(is.finite(Scale)) && all(0 < Scale) && all(is.finite(kappa)) && all(0 < kappa) okay1 }, list( .elocat = elocat, .llocat = llocat, .escale = escale, .lscale = lscale, .ekappa = ekappa, .lkappa = lkappa ))), deriv = eval(substitute(expression({ locat <- eta2theta(eta[, 1], .llocat , earg = .elocat ) Scale <- eta2theta(eta[, 2], .lscale , earg = .escale ) kappa <- eta2theta(eta[, 3], .lkappa , earg = .ekappa ) zedd <- abs(y - locat) / Scale dl.dlocat <- sqrt(2) * ifelse(y >= locat, kappa, 1/kappa) * sign(y-locat) / Scale dl.dscale <- sqrt(2) * ifelse(y >= locat, kappa, 1/kappa) * zedd / Scale - 1 / Scale dl.dkappa <- 1 / kappa - 2 * kappa / (1+kappa^2) - (sqrt(2) / Scale) * ifelse(y > locat, 1, -1/kappa^2) * abs(y-locat) dlocat.deta <- dtheta.deta(locat, .llocat , earg = .elocat ) dscale.deta <- dtheta.deta(Scale, .lscale , earg = .escale ) dkappa.deta <- dtheta.deta(kappa, .lkappa, earg = .ekappa) c(w) * cbind(dl.dlocat * dlocat.deta, dl.dscale * dscale.deta, dl.dkappa * dkappa.deta) }), list( .escale = escale, .lscale = lscale, .elocat = elocat, .llocat = llocat, .ekappa = ekappa, .lkappa = lkappa ))), weight = eval(substitute(expression({ d2l.dlocat2 <- 2 / Scale^2 d2l.dscale2 <- 1 / Scale^2 d2l.dkappa2 <- 1 / kappa^2 + 4 / (1+kappa^2)^2 d2l.dkappadloc <- -sqrt(8) / ((1+kappa^2) * Scale) d2l.dkappadscale <- -(1-kappa^2) / ((1+kappa^2) * kappa * Scale) wz <- matrix(0, nrow = n, dimm(M)) wz[,iam(1, 1, M)] <- d2l.dlocat2 * dlocat.deta^2 wz[,iam(2, 2, M)] <- d2l.dscale2 * dscale.deta^2 wz[,iam(3, 3, M)] <- d2l.dkappa2 * dkappa.deta^2 wz[,iam(1, 3, M)] <- d2l.dkappadloc * dkappa.deta * dlocat.deta wz[,iam(2, 3, M)] <- d2l.dkappadscale * dkappa.deta * dscale.deta c(w) * wz }), list( .escale = escale, .lscale = lscale, .elocat = elocat, .llocat = llocat )))) } dlaplace <- function(x, location = 0, scale = 1, log = FALSE) { if (!is.logical(log.arg <- log) || length(log) != 1) stop("bad input for argument 'log'") rm(log) logdensity <- (-abs(x-location)/scale) - log(2*scale) if (log.arg) logdensity else exp(logdensity) } plaplace <- function(q, location = 0, scale = 1, lower.tail = TRUE, log.p =FALSE) { zedd <- (q - location) / scale if (!is.logical(lower.tail) || length(lower.tail ) != 1) stop("bad input for argument 'lower.tail'") if (!is.logical(log.p) || length(log.p) != 1) stop("bad input for argument 'log.p'") L <- max(length(q), length(location), length(scale)) if (length(q) != L) q <- rep_len(q, L) if (length(location) != L) location <- rep_len(location, L) if (length(scale) != L) scale <- rep_len(scale, L) if (lower.tail) { if (log.p) { ans <- ifelse(q < location, log(0.5) + zedd, log1p(- 0.5 * exp(-zedd))) } else { ans <- ifelse(q < location, 0.5 * exp(zedd), 1 - 0.5 * exp(-zedd)) } } else { if (log.p) { ans <- ifelse(q < location, log1p(- 0.5 * exp(zedd)), log(0.5) - zedd) } else { ans <- ifelse(q < location, 1 - 0.5 * exp(zedd), 0.5 * exp(-zedd)) } } ans[scale <= 0] <- NaN ans } qlaplace <- function(p, location = 0, scale = 1, lower.tail = TRUE, log.p = FALSE) { if (!is.logical(lower.tail) || length(lower.tail ) != 1) stop("bad input for argument 'lower.tail'") if (!is.logical(log.p) || length(log.p) != 1) stop("bad input for argument 'log.p'") L <- max(length(p), length(location), length(scale)) if (length(p) != L) p <- rep_len(p, L) if (length(location) != L) location <- rep_len(location, L) if (length(scale) != L) scale <- rep_len(scale, L) if (lower.tail) { if (log.p) { ln.p <- p ans <- location - sign(exp(ln.p)-0.5) * scale * log(2 * ifelse(exp(ln.p) < 0.5, exp(ln.p), -expm1(ln.p))) } else { ans <- location - sign(p-0.5) * scale * log(2 * ifelse(p < 0.5, p, 1-p)) } } else { if (log.p) { ln.p <- p ans <- location - sign(0.5 - exp(ln.p)) * scale * log(2 * ifelse(-expm1(ln.p) < 0.5, -expm1(ln.p), exp(ln.p))) } else { ans <- location - sign(0.5 - p) * scale * log(2 * ifelse(p > 0.5, 1 - p, p)) } } ans[scale <= 0] <- NaN ans } rlaplace <- function(n, location = 0, scale = 1) { use.n <- if ((length.n <- length(n)) > 1) length.n else if (!is.Numeric(n, integer.valued = TRUE, length.arg = 1, positive = TRUE)) stop("bad input for argument 'n'") else n if (!is.Numeric(scale, positive = TRUE)) stop("'scale' must be positive") location <- rep_len(location, use.n) scale <- rep_len(scale, use.n) rrrr <- runif(use.n) location - sign(rrrr - 0.5) * scale * (log(2) + ifelse(rrrr < 0.5, log(rrrr), log1p(-rrrr))) } laplace <- function(llocation = "identitylink", lscale = "loglink", ilocation = NULL, iscale = NULL, imethod = 1, zero = "scale") { llocat <- as.list(substitute(llocation)) elocat <- link2list(llocat) llocat <- attr(elocat, "function.name") ilocat <- ilocation lscale <- as.list(substitute(lscale)) escale <- link2list(lscale) lscale <- attr(escale, "function.name") if (!is.Numeric(imethod, length.arg = 1, integer.valued = TRUE, positive = TRUE) || imethod > 3) stop("argument 'imethod' must be 1 or 2 or 3") if (length(iscale) && !is.Numeric(iscale, positive = TRUE)) stop("bad input for argument 'iscale'") new("vglmff", blurb = c("Two-parameter Laplace distribution\n\n", "Links: ", namesof("location", llocat, earg = elocat), ", ", namesof("scale", lscale, earg = escale), "\n", "\n", "Mean: location", "\n", "Variance: 2*scale^2"), constraints = eval(substitute(expression({ constraints <- cm.zero.VGAM(constraints, x = x, .zero , M = M, predictors.names = predictors.names, M1 = 2) }), list( .zero = zero ))), infos = eval(substitute(function(...) { list(M1 = 2, Q1 = 1, multipleResponses = FALSE, parameters.names = c("location", "scale"), summary.pvalues = FALSE, zero = .zero ) }, list( .zero = zero ))), initialize = eval(substitute(expression({ w.y.check(w = w, y = y, ncol.w.max = 1, ncol.y.max = 1) predictors.names <- c(namesof("location", .llocat , earg = .elocat, tag = FALSE), namesof("scale", .lscale , earg = .escale, tag = FALSE)) if (!length(etastart)) { if ( .imethod == 1) { locat.init <- median(y) scale.init <- sqrt(var(y) / 2) } else if ( .imethod == 2) { locat.init <- weighted.mean(y, w) scale.init <- sqrt(var(y) / 2) } else { locat.init <- median(y) scale.init <- sqrt(sum(c(w)*abs(y-median(y ))) / (sum(w) *2)) } locat.init <- if (length( .ilocat )) rep_len( .ilocat , n) else rep_len(locat.init, n) scale.init <- if (length( .iscale )) rep_len( .iscale , n) else rep_len(scale.init, n) etastart <- cbind(theta2eta(locat.init, .llocat , earg = .elocat ), theta2eta(scale.init, .lscale , earg = .escale )) } }), list( .imethod = imethod, .elocat = elocat, .escale = escale, .llocat = llocat, .lscale = lscale, .ilocat = ilocat, .iscale = iscale ))), linkinv = eval(substitute(function(eta, extra = NULL) { eta2theta(eta[, 1], .llocat , earg = .elocat ) }, list( .elocat = elocat, .llocat = llocat ))), last = eval(substitute(expression({ misc$link <- c(location = .llocat , scale = .lscale ) misc$earg <- list(location = .elocat , scale = .escale ) misc$expected <- TRUE misc$RegCondOK <- FALSE }), list( .escale = escale, .lscale = lscale, .elocat = elocat, .llocat = llocat ))), loglikelihood = eval(substitute( function(mu, y, w, residuals = FALSE, eta, extra = NULL, summation = TRUE) { locat <- eta2theta(eta[, 1], .llocat , earg = .elocat ) Scale <- eta2theta(eta[, 2], .lscale , earg = .escale ) if (residuals) { stop("loglikelihood residuals not implemented yet") } else { ll.elts <- c(w) * dlaplace(x = y, locat = locat, scale = Scale, log = TRUE) if (summation) { sum(ll.elts) } else { ll.elts } } }, list( .escale = escale, .lscale = lscale, .elocat = elocat, .llocat = llocat ))), vfamily = c("laplace"), validparams = eval(substitute(function(eta, y, extra = NULL) { Locat <- eta2theta(eta[, 1], .llocat , earg = .elocat ) Scale <- eta2theta(eta[, 2], .lscale , earg = .escale ) okay1 <- all(is.finite(Locat)) && all(is.finite(Scale)) && all(0 < Scale) okay1 }, list( .escale = escale, .lscale = lscale, .elocat = elocat, .llocat = llocat ))), deriv = eval(substitute(expression({ Locat <- eta2theta(eta[, 1], .llocat , earg = .elocat ) Scale <- eta2theta(eta[, 2], .lscale , earg = .escale ) zedd <- abs(y-Locat) / Scale dl.dLocat <- sign(y - Locat) / Scale dl.dscale <- zedd / Scale - 1 / Scale dLocat.deta <- dtheta.deta(Locat, .llocat , earg = .elocat ) dscale.deta <- dtheta.deta(Scale, .lscale , earg = .escale ) c(w) * cbind(dl.dLocat * dLocat.deta, dl.dscale * dscale.deta) }), list( .escale = escale, .lscale = lscale, .elocat = elocat, .llocat = llocat ))), weight = eval(substitute(expression({ d2l.dLocat2 <- d2l.dscale2 <- 1 / Scale^2 wz <- matrix(0, nrow = n, ncol = M) wz[,iam(1, 1, M)] <- d2l.dLocat2 * dLocat.deta^2 wz[,iam(2, 2, M)] <- d2l.dscale2 * dscale.deta^2 c(w) * wz }), list( .escale = escale, .lscale = lscale, .elocat = elocat, .llocat = llocat )))) } fff.control <- function(save.weights = TRUE, ...) { list(save.weights = save.weights) } fff <- function(link = "loglink", idf1 = NULL, idf2 = NULL, nsimEIM = 100, imethod = 1, zero = NULL) { link <- as.list(substitute(link)) earg <- link2list(link) link <- attr(earg, "function.name") if (!is.Numeric(imethod, length.arg = 1, integer.valued = TRUE, positive = TRUE) || imethod > 2) stop("argument 'imethod' must be 1 or 2") if (!is.Numeric(nsimEIM, length.arg = 1, integer.valued = TRUE) || nsimEIM <= 10) stop("argument 'nsimEIM' should be an integer greater than 10") ncp <- 0 if (any(ncp != 0)) warning("not sure about ncp != 0 wrt dl/dtheta") new("vglmff", blurb = c("F-distribution\n\n", "Links: ", namesof("df1", link, earg = earg), ", ", namesof("df2", link, earg = earg), "\n", "\n", "Mean: df2/(df2-2) provided df2>2 and ncp = 0", "\n", "Variance: ", "2*df2^2*(df1+df2-2)/(df1*(df2-2)^2*(df2-4)) ", "provided df2>4 and ncp = 0"), constraints = eval(substitute(expression({ constraints <- cm.zero.VGAM(constraints, x = x, .zero , M = M, predictors.names = predictors.names, M1 = 2) }), list( .zero = zero ))), infos = eval(substitute(function(...) { list(M1 = 2, Q1 = 1, multipleResponses = FALSE, parameters.names = c("df1", "df2"), zero = .zero ) }, list( .zero = zero ))), initialize = eval(substitute(expression({ w.y.check(w = w, y = y, ncol.w.max = 1, ncol.y.max = 1) predictors.names <- c(namesof("df1", .link , earg = .earg , tag = FALSE), namesof("df2", .link , earg = .earg , tag = FALSE)) if (!length(etastart)) { if ( .imethod == 1) { df2.init <- b <- 2*mean(y) / (mean(y)-1) df1.init <- 2*b^2*(b-2)/(var(y)*(b-2)^2 * (b-4) - 2*b^2) if (df2.init < 4) df2.init <- 5 if (df1.init < 2) df1.init <- 3 } else { df2.init <- b <- 2*median(y) / (median(y)-1) summy <- summary(y) var.est <- summy[5] - summy[2] df1.init <- 2*b^2*(b-2)/(var.est*(b-2)^2 * (b-4) - 2*b^2) } df1.init <- if (length( .idf1 )) rep_len( .idf1 , n) else rep_len(df1.init, n) df2.init <- if (length( .idf2 )) rep_len( .idf2 , n) else rep_len(1, n) etastart <- cbind(theta2eta(df1.init, .link , earg = .earg ), theta2eta(df2.init, .link , earg = .earg )) } }), list( .imethod = imethod, .idf1 = idf1, .earg = earg, .idf2 = idf2, .link = link ))), linkinv = eval(substitute(function(eta, extra = NULL) { df2 <- eta2theta(eta[, 2], .link , earg = .earg ) ans <- df2 * NA ans[df2 > 2] <- df2[df2 > 2] / (df2[df2 > 2] - 2) ans }, list( .link = link, .earg = earg ))), last = eval(substitute(expression({ misc$link <- c(df1 = .link , df2 = .link ) misc$earg <- list(df1 = .earg , df2 = .earg ) misc$nsimEIM <- .nsimEIM misc$ncp <- .ncp }), list( .link = link, .earg = earg, .ncp = ncp, .nsimEIM = nsimEIM ))), loglikelihood = eval(substitute( function(mu, y, w, residuals = FALSE, eta, extra = NULL, summation = TRUE) { df1 <- eta2theta(eta[, 1], .link , earg = .earg ) df2 <- eta2theta(eta[, 2], .link , earg = .earg ) if (residuals) { stop("loglikelihood residuals not implemented yet") } else { ll.elts <- c(w) * df(x = y, df1 = df1, df2 = df2, ncp = .ncp , log = TRUE) if (summation) { sum(ll.elts) } else { ll.elts } } }, list( .link = link, .earg = earg, .ncp = ncp ))), vfamily = c("fff"), validparams = eval(substitute(function(eta, y, extra = NULL) { df1 <- eta2theta(eta[, 1], .link , earg = .earg ) df2 <- eta2theta(eta[, 2], .link , earg = .earg ) okay1 <- all(is.finite(df1)) && all(0 < df1) && all(is.finite(df2)) && all(0 < df2) okay1 }, list( .link = link, .earg = earg, .ncp = ncp ))), deriv = eval(substitute(expression({ df1 <- eta2theta(eta[, 1], .link , earg = .earg ) df2 <- eta2theta(eta[, 2], .link , earg = .earg ) dl.ddf1 <- 0.5*digamma(0.5*(df1+df2)) + 0.5 + 0.5*log(df1/df2) + 0.5*log(y) - 0.5*digamma(0.5*df1) - 0.5*(df1+df2)*(y/df2) / (1 + df1*y/df2) - 0.5*log1p(df1*y/df2) dl.ddf2 <- 0.5*digamma(0.5*(df1+df2)) - 0.5*df1/df2 - 0.5*digamma(0.5*df2) - 0.5*(df1+df2) * (-df1*y/df2^2) / (1 + df1*y/df2) - 0.5*log1p(df1*y/df2) ddf1.deta <- dtheta.deta(df1, .link , earg = .earg ) ddf2.deta <- dtheta.deta(df2, .link , earg = .earg ) dthetas.detas <- cbind(ddf1.deta, ddf2.deta) c(w) * dthetas.detas * cbind(dl.ddf1, dl.ddf2) }), list( .link = link, .earg = earg ))), weight = eval(substitute(expression({ run.varcov <- 0 ind1 <- iam(NA, NA, M = M, both = TRUE, diag = TRUE) for (ii in 1:( .nsimEIM )) { ysim <- rf(n = n, df1=df1, df2=df2) dl.ddf1 <- 0.5*digamma(0.5*(df1+df2)) + 0.5 + 0.5*log(df1/df2) + 0.5*log(ysim) - 0.5*digamma(0.5*df1) - 0.5*(df1+df2)*(ysim/df2) / (1 + df1*ysim/df2) - 0.5*log1p(df1*ysim/df2) dl.ddf2 <- 0.5*digamma(0.5*(df1+df2)) - 0.5*df1/df2 - 0.5*digamma(0.5*df2) - 0.5*(df1+df2) * (-df1*ysim/df2^2)/(1 + df1*ysim/df2) - 0.5*log1p(df1*ysim/df2) rm(ysim) temp3 <- cbind(dl.ddf1, dl.ddf2) run.varcov <- ((ii-1) * run.varcov + temp3[,ind1$row.index]*temp3[,ind1$col.index]) / ii } wz <- if (intercept.only) matrix(colMeans(run.varcov), n, ncol(run.varcov), byrow = TRUE) else run.varcov wz <- c(w) * wz * dthetas.detas[, ind1$row] * dthetas.detas[, ind1$col] wz }), list( .link = link, .earg = earg, .nsimEIM = nsimEIM, .ncp = ncp )))) } hyperg <- function(N = NULL, D = NULL, lprob = "logitlink", iprob = NULL) { inputN <- is.Numeric(N, positive = TRUE) inputD <- is.Numeric(D, positive = TRUE) if (inputD && inputN) stop("only one of 'N' and 'D' is to be inputted") if (!inputD && !inputN) stop("one of 'N' and 'D' needs to be inputted") lprob <- as.list(substitute(lprob)) earg <- link2list(lprob) lprob <- attr(earg, "function.name") new("vglmff", blurb = c("Hypergeometric distribution\n\n", "Link: ", namesof("prob", lprob, earg = earg), "\n", "Mean: D/N\n"), initialize = eval(substitute(expression({ NCOL <- function (x) if (is.array(x) && length(dim(x)) > 1 || is.data.frame(x)) ncol(x) else as.integer(1) if (NCOL(y) == 1) { if (is.factor(y)) y <- y != levels(y)[1] nn <- rep_len(1, n) if (!all(y >= 0 & y <= 1)) stop("response values must be in [0, 1]") mustart <- (0.5 + w * y) / (1 + w) no.successes <- w * y if (any(abs(no.successes - round(no.successes)) > 0.001)) stop("Number of successes must be integer-valued") } else if (NCOL(y) == 2) { if (any(abs(y - round(y)) > 0.001)) stop("Count data must be integer-valued") nn <- y[, 1] + y[, 2] y <- ifelse(nn > 0, y[, 1]/nn, 0) w <- w * nn mustart <- (0.5 + nn * y) / (1 + nn) mustart[mustart >= 1] <- 0.95 } else stop("Response not of the right form") predictors.names <- namesof("prob", .lprob , earg = .earg , tag = FALSE) extra$Nvector <- .N extra$Dvector <- .D extra$Nunknown <- length(extra$Nvector) == 0 if (!length(etastart)) { init.prob <- if (length( .iprob)) rep_len( .iprob, n) else mustart etastart <- matrix(init.prob, n, NCOL(y)) } }), list( .lprob = lprob, .earg = earg, .N = N, .D = D, .iprob = iprob ))), linkinv = eval(substitute(function(eta, extra = NULL) { eta2theta(eta, .lprob , earg = .earg ) }, list( .lprob = lprob, .earg = earg ))), last = eval(substitute(expression({ misc$link <- c("prob" = .lprob) misc$earg <- list("prob" = .earg ) misc$Dvector <- .D misc$Nvector <- .N }), list( .N = N, .D = D, .lprob = lprob, .earg = earg ))), linkfun = eval(substitute(function(mu, extra = NULL) { theta2eta(mu, .lprob, earg = .earg ) }, list( .lprob = lprob, .earg = earg ))), loglikelihood = eval(substitute( function(mu, y, w, residuals = FALSE, eta, extra = NULL, summation = TRUE) { N <- extra$Nvector Dvec <- extra$Dvector prob <- mu yvec <- w * y if (residuals) { stop("loglikelihood residuals not implemented yet") } else { ll.elts <- if (extra$Nunknown) { tmp12 <- Dvec * (1-prob) / prob (lgamma(1+tmp12) + lgamma(1+Dvec/prob-w) - lgamma(1+tmp12-w+yvec) - lgamma(1+Dvec/prob)) } else { (lgamma(1+N*prob) + lgamma(1+N*(1-prob)) - lgamma(1+N*prob-yvec) - lgamma(1+N*(1-prob) -w + yvec)) } if (summation) { sum(ll.elts) } else { ll.elts } } }, list( .lprob = lprob, .earg = earg ))), vfamily = c("hyperg"), validparams = eval(substitute(function(eta, y, extra = NULL) { prob <- eta2theta(eta, .lprob , earg = .earg ) okay1 <- all(is.finite(prob)) && all(0 < prob & prob < 1) okay1 }, list( .lprob = lprob, .earg = earg ))), deriv = eval(substitute(expression({ prob <- mu dprob.deta <- dtheta.deta(prob, .lprob, earg = .earg ) Dvec <- extra$Dvector Nvec <- extra$Nvector yvec <- w * y if (extra$Nunknown) { tmp72 <- -Dvec / prob^2 tmp12 <- Dvec * (1-prob) / prob dl.dprob <- tmp72 * (digamma(1 + tmp12) + digamma(1 + Dvec/prob -w) - digamma(1 + tmp12-w+yvec) - digamma(1 + Dvec/prob)) } else { dl.dprob <- Nvec * (digamma(1+Nvec*prob) - digamma(1+Nvec*(1-prob)) - digamma(1+Nvec*prob-yvec) + digamma(1+Nvec*(1-prob)-w+yvec)) } c(w) * dl.dprob * dprob.deta }), list( .lprob = lprob, .earg = earg ))), weight = eval(substitute(expression({ if (extra$Nunknown) { tmp722 <- tmp72^2 tmp13 <- 2*Dvec / prob^3 d2l.dprob2 <- tmp722 * (trigamma(1 + tmp12) + trigamma(1 + Dvec/prob - w) - trigamma(1 + tmp12 - w + yvec) - trigamma(1 + Dvec/prob)) + tmp13 * (digamma(1 + tmp12) + digamma(1 + Dvec/prob - w) - digamma(1 + tmp12 - w + yvec) - digamma(1 + Dvec/prob)) } else { d2l.dprob2 <- Nvec^2 * (trigamma(1+Nvec*prob) + trigamma(1+Nvec*(1-prob)) - trigamma(1+Nvec*prob-yvec) - trigamma(1+Nvec*(1-prob)-w+yvec)) } d2prob.deta2 <- d2theta.deta2(prob, .lprob , earg = .earg ) wz <- -(dprob.deta^2) * d2l.dprob2 wz <- c(w) * wz wz[wz < .Machine$double.eps] <- .Machine$double.eps wz }), list( .lprob = lprob, .earg = earg )))) } dbenini <- function(x, y0, shape, log = FALSE) { if (!is.logical(log.arg <- log) || length(log) != 1) stop("bad input for argument 'log'") rm(log) N <- max(length(x), length(shape), length(y0)) if (length(x) != N) x <- rep_len(x, N) if (length(shape) != N) shape <- rep_len(shape, N) if (length(y0) != N) y0 <- rep_len(y0, N) logdensity <- rep_len(log(0), N) xok <- (x > y0) tempxok <- log(x[xok]/y0[xok]) logdensity[xok] <- log(2*shape[xok]) - shape[xok] * tempxok^2 + log(tempxok) - log(x[xok]) logdensity[is.infinite(x)] <- log(0) if (log.arg) logdensity else exp(logdensity) } pbenini <- function(q, y0, shape, lower.tail = TRUE, log.p = FALSE) { if (!is.Numeric(q)) stop("bad input for argument 'q'") if (!is.Numeric(shape, positive = TRUE)) stop("bad input for argument 'shape'") if (!is.Numeric(y0, positive = TRUE)) stop("bad input for argument 'y0'") if (!is.logical(lower.tail) || length(lower.tail ) != 1) stop("bad input for argument 'lower.tail'") if (!is.logical(log.p) || length(log.p) != 1) stop("bad input for argument 'log.p'") N <- max(length(q), length(shape), length(y0)) if (length(q) != N) q <- rep_len(q, N) if (length(shape) != N) shape <- rep_len(shape, N) if (length(y0) != N) y0 <- rep_len(y0, N) ans <- y0 * 0 ok <- q > y0 if (lower.tail) { if (log.p) { ans[ok] <- log(-expm1(-shape[ok] * (log(q[ok]/y0[ok]))^2)) ans[q <= y0 ] <- -Inf } else { ans[ok] <- -expm1(-shape[ok] * (log(q[ok]/y0[ok]))^2) } } else { if (log.p) { ans[ok] <- -shape[ok] * (log(q[ok]/y0[ok]))^2 ans[q <= y0] <- 0 } else { ans[ok] <- exp(-shape[ok] * (log(q[ok]/y0[ok]))^2) ans[q <= y0] <- 1 } } ans } qbenini <- function(p, y0, shape, lower.tail = TRUE, log.p = FALSE) { if (!is.logical(lower.tail) || length(lower.tail ) != 1) stop("bad input for argument 'lower.tail'") if (!is.logical(log.p) || length(log.p) != 1) stop("bad input for argument 'log.p'") if (lower.tail) { if (log.p) { ln.p <- p ans <- y0 * exp(sqrt(-log(-expm1(ln.p)) / shape)) } else { ans <- y0 * exp(sqrt(-log1p(-p) / shape)) } } else { if (log.p) { ln.p <- p ans <- y0 * exp(sqrt(-ln.p / shape)) } else { ans <- y0 * exp(sqrt(-log(p) / shape)) } } ans[y0 <= 0] <- NaN ans } rbenini <- function(n, y0, shape) { y0 * exp(sqrt(-log(runif(n)) / shape)) } benini1 <- function(y0 = stop("argument 'y0' must be specified"), lshape = "loglink", ishape = NULL, imethod = 1, zero = NULL, parallel = FALSE, type.fitted = c("percentiles", "Qlink"), percentiles = 50) { type.fitted <- match.arg(type.fitted, c("percentiles", "Qlink"))[1] lshape <- as.list(substitute(lshape)) eshape <- link2list(lshape) lshape <- attr(eshape, "function.name") if (!is.Numeric(imethod, length.arg = 1, integer.valued = TRUE, positive = TRUE) || imethod > 2) stop("argument 'imethod' must be 1 or 2") if (!is.Numeric(y0, positive = TRUE, length.arg = 1)) stop("bad input for argument 'y0'") new("vglmff", blurb = c("1-parameter Benini distribution\n\n", "Link: ", namesof("shape", lshape, earg = eshape), "\n", "\n", "Median: qbenini(p = 0.5, y0, shape)"), constraints = eval(substitute(expression({ constraints <- cm.VGAM(matrix(1, M, 1), x = x, bool = .parallel , constraints, apply.int = FALSE) constraints <- cm.zero.VGAM(constraints, x = x, .zero , M = M, predictors.names = predictors.names, M1 = 1) }), list( .parallel = parallel, .zero = zero ))), infos = eval(substitute(function(...) { list(M1 = 1, Q1 = 1, expected = TRUE, multipleResponses = TRUE, parameters.names = c("shape"), parallel = .parallel , percentiles = .percentiles , type.fitted = .type.fitted , lshape = .lshape , eshape = .eshape , zero = .zero ) }, list( .parallel = parallel, .zero = zero, .percentiles = percentiles , .type.fitted = type.fitted, .eshape = eshape, .lshape = lshape))), initialize = eval(substitute(expression({ temp5 <- w.y.check(w = w, y = y, ncol.w.max = Inf, ncol.y.max = Inf, out.wy = TRUE, colsyperw = 1, maximize = TRUE) w <- temp5$w y <- temp5$y ncoly <- ncol(y) M1 <- 1 M <- M1 * ncoly extra$ncoly <- ncoly extra$type.fitted <- .type.fitted extra$colnames.y <- colnames(y) extra$percentiles <- .percentiles extra$M1 <- M1 mynames1 <- paste("shape", if (ncoly > 1) 1:ncoly else "", sep = "") predictors.names <- namesof(mynames1, .lshape , earg = .eshape , tag = FALSE) extra$y0 <- .y0 if (any(y <= extra$y0)) stop("some values of the response are > argument 'y0' values") if (!length(etastart)) { probs.y <- (1:3) / 4 qofy <- quantile(rep(y, times = w), probs = probs.y) if ( .imethod == 1) { shape.init <- mean(-log1p(-probs.y) / (log(qofy))^2) } else { shape.init <- median(-log1p(-probs.y) / (log(qofy))^2) } shape.init <- matrix(if (length( .ishape )) .ishape else shape.init, n, ncoly, byrow = TRUE) etastart <- cbind(theta2eta(shape.init, .lshape , earg = .eshape )) } }), list( .imethod = imethod, .ishape = ishape, .lshape = lshape, .eshape = eshape, .percentiles = percentiles, .type.fitted = type.fitted, .y0 = y0 ))), linkinv = eval(substitute(function(eta, extra = NULL) { type.fitted <- if (length(extra$type.fitted)) { extra$type.fitted } else { warning("cannot find 'type.fitted'. Returning the 'median'.") extra$percentiles <- 50 "percentiles" } type.fitted <- match.arg(type.fitted, c("percentiles", "Qlink"))[1] if (type.fitted == "Qlink") { eta2theta(eta, link = "loglink") } else { shape <- eta2theta(eta, .lshape , earg = .eshape ) pcent <- extra$percentiles perc.mat <- matrix(pcent, NROW(eta), length(pcent), byrow = TRUE) / 100 fv <- switch(type.fitted, "percentiles" = qbenini(perc.mat, y0 = extra$y0, shape = matrix(shape, nrow(perc.mat), ncol(perc.mat)))) if (type.fitted == "percentiles") fv <- label.cols.y(fv, colnames.y = extra$colnames.y, NOS = NCOL(eta), percentiles = pcent, one.on.one = FALSE) fv } }, list( .lshape = lshape, .eshape = eshape ))), last = eval(substitute(expression({ M1 <- extra$M1 misc$link <- c(rep_len( .lshape , ncoly)) names(misc$link) <- mynames1 misc$earg <- vector("list", M) names(misc$earg) <- mynames1 for (ii in 1:ncoly) { misc$earg[[ii]] <- .eshape } extra$y0 <- .y0 }), list( .lshape = lshape, .eshape = eshape, .y0 = y0 ))), loglikelihood = eval(substitute( function(mu, y, w, residuals = FALSE, eta, extra = NULL, summation = TRUE) { shape <- eta2theta(eta, .lshape , earg = .eshape ) y0 <- extra$y0 if (residuals) { stop("loglikelihood residuals not implemented yet") } else { ll.elts <- c(w) * dbenini(x = y, y0 = y0, shape = shape, log = TRUE) if (summation) { sum(ll.elts) } else { ll.elts } } }, list( .lshape = lshape, .eshape = eshape ))), vfamily = c("benini1"), validparams = eval(substitute(function(eta, y, extra = NULL) { shape <- eta2theta(eta, .lshape , earg = .eshape ) okay1 <- all(is.finite(shape)) && all(0 < shape) okay1 }, list( .lshape = lshape, .eshape = eshape ))), simslot = eval(substitute( function(object, nsim) { pwts <- if (length(pwts <- [email protected]) > 0) pwts else weights(object, type = "prior") if (any(pwts != 1)) warning("ignoring prior weights") eta <- predict(object) extra <- object@extra shape <- eta2theta(eta, .lshape , earg = .eshape ) y0 <- extra$y0 rbenini(nsim * length(shape), y0 = y0, shape = shape) }, list( .lshape = lshape, .eshape = eshape ))), deriv = eval(substitute(expression({ shape <- eta2theta(eta, .lshape , earg = .eshape ) y0 <- extra$y0 dl.dshape <- 1/shape - (log(y/y0))^2 dshape.deta <- dtheta.deta(shape, .lshape , earg = .eshape ) c(w) * dl.dshape * dshape.deta }), list( .lshape = lshape, .eshape = eshape ))), weight = eval(substitute(expression({ ned2l.dshape2 <- 1 / shape^2 wz <- ned2l.dshape2 * dshape.deta^2 c(w) * wz }), list( .lshape = lshape, .eshape = eshape )))) } dpolono <- function (x, meanlog = 0, sdlog = 1, bigx = 170, ...) { mapply(function(x, meanlog, sdlog, ...) { if (abs(x) > floor(x)) { 0 } else if (x == Inf) { 0 } else if (x > bigx) { z <- (log(x) - meanlog) / sdlog (1 + (z^2 + log(x) - meanlog - 1) / (2 * x * sdlog^2)) * exp(-0.5 * z^2) / (sqrt(2 * pi) * sdlog * x) } else integrate( function(t) exp(t * x - exp(t) - 0.5 * ((t - meanlog) / sdlog)^2), lower = -Inf, upper = Inf, ...)$value / (sqrt(2 * pi) * sdlog * exp(lgamma(x + 1.0))) }, x, meanlog, sdlog, ...) } ppolono <- function(q, meanlog = 0, sdlog = 1, isOne = 1 - sqrt( .Machine$double.eps ), ...) { .cumprob <- rep_len(0, length(q)) .cumprob[q == Inf] <- 1 q <- floor(q) ii <- -1 while (any(xActive <- ((.cumprob < isOne) & (q > ii)))) .cumprob[xActive] <- .cumprob[xActive] + dpolono(ii <- (ii+1), meanlog, sdlog, ...) .cumprob } rpolono <- function(n, meanlog = 0, sdlog = 1) { lambda <- rlnorm(n = n, meanlog = meanlog, sdlog = sdlog) rpois(n = n, lambda = lambda) } dtriangle <- function(x, theta, lower = 0, upper = 1, log = FALSE) { if (!is.logical(log.arg <- log) || length(log) != 1) stop("bad input for argument 'log'") rm(log) N <- max(length(x), length(theta), length(lower), length(upper)) if (length(x) != N) x <- rep_len(x, N) if (length(theta) != N) theta <- rep_len(theta, N) if (length(lower) != N) lower <- rep_len(lower, N) if (length(upper) != N) upper <- rep_len(upper, N) denom1 <- ((upper-lower)*(theta-lower)) denom2 <- ((upper-lower)*(upper-theta)) logdensity <- rep_len(log(0), N) xok.neg <- (lower < x) & (x <= theta) xok.pos <- (theta <= x) & (x < upper) logdensity[xok.neg] = log(2 * (x[xok.neg] - lower[xok.neg]) / denom1[xok.neg]) logdensity[xok.pos] = log(2 * (upper[xok.pos] - x[xok.pos]) / denom2[xok.pos]) logdensity[lower >= upper] <- NaN logdensity[lower > theta] <- NaN logdensity[upper < theta] <- NaN if (log.arg) logdensity else exp(logdensity) } rtriangle <- function(n, theta, lower = 0, upper = 1) { use.n <- if ((length.n <- length(n)) > 1) length.n else if (!is.Numeric(n, integer.valued = TRUE, length.arg = 1, positive = TRUE)) stop("bad input for argument 'n'") else n if (!is.Numeric(theta)) stop("bad input for argument 'theta'") if (!is.Numeric(lower)) stop("bad input for argument 'lower'") if (!is.Numeric(upper)) stop("bad input for argument 'upper'") if (!all(lower < theta & theta < upper)) stop("lower < theta < upper values are required") N <- use.n lower <- rep_len(lower, N) upper <- rep_len(upper, N) theta <- rep_len(theta, N) t1 <- sqrt(runif(n)) t2 <- sqrt(runif(n)) ifelse(runif(n) < (theta - lower) / (upper - lower), lower + (theta - lower) * t1, upper - (upper - theta) * t2) } qtriangle <- function(p, theta, lower = 0, upper = 1, lower.tail = TRUE, log.p = FALSE) { if (!is.logical(lower.tail) || length(lower.tail ) != 1) stop("bad input for argument 'lower.tail'") if (!is.logical(log.p) || length(log.p) != 1) stop("bad input for argument 'log.p'") N <- max(length(p), length(theta), length(lower), length(upper)) if (length(p) != N) p <- rep_len(p, N) if (length(theta) != N) theta <- rep_len(theta, N) if (length(lower) != N) lower <- rep_len(lower, N) if (length(upper) != N) upper <- rep_len(upper, N) ans <- NA_real_ * p if (lower.tail) { if (log.p) { Neg <- (exp(ln.p) <= (theta - lower) / (upper - lower)) temp1 <- exp(ln.p) * (upper - lower) * (theta - lower) Pos <- (exp(ln.p) >= (theta - lower) / (upper - lower)) pstar <- (exp(ln.p) - (theta - lower) / (upper - lower)) / ((upper - theta) / (upper - lower)) } else { Neg <- (p <= (theta - lower) / (upper - lower)) temp1 <- p * (upper - lower) * (theta - lower) Pos <- (p >= (theta - lower) / (upper - lower)) pstar <- (p - (theta - lower) / (upper - lower)) / ((upper - theta) / (upper - lower)) } } else { if (log.p) { ln.p <- p Neg <- (exp(ln.p) >= (upper- theta) / (upper - lower)) temp1 <- -expm1(ln.p) * (upper - lower) * (theta - lower) Pos <- (exp(ln.p) <= (upper- theta) / (upper - lower)) pstar <- (-expm1(ln.p) - (theta - lower) / (upper - lower)) / ((upper - theta) / (upper - lower)) } else { Neg <- (p >= (upper- theta) / (upper - lower)) temp1 <- (1 - p) * (upper - lower) * (theta - lower) Pos <- (p <= (upper- theta) / (upper - lower)) pstar <- ((upper- theta) / (upper - lower) - p) / ((upper - theta) / (upper - lower)) } } ans[ Neg] <- lower[ Neg] + sqrt(temp1[ Neg]) if (any(Pos)) { qstar <- cbind(1 - sqrt(1-pstar), 1 + sqrt(1-pstar)) qstar <- qstar[Pos,, drop = FALSE] qstar <- ifelse(qstar[, 1] >= 0 & qstar[, 1] <= 1, qstar[, 1], qstar[, 2]) ans[Pos] <- theta[Pos] + qstar * (upper - theta)[Pos] } ans[theta < lower | theta > upper] <- NaN ans } ptriangle <- function(q, theta, lower = 0, upper = 1, lower.tail = TRUE, log.p = FALSE) { N <- max(length(q), length(theta), length(lower), length(upper)) if (length(q) != N) q <- rep_len(q, N) if (length(theta) != N) theta <- rep_len(theta, N) if (length(lower) != N) lower <- rep_len(lower, N) if (length(upper) != N) upper <- rep_len(upper, N) if (!is.logical(lower.tail) || length(lower.tail ) != 1) stop("bad input for argument 'lower.tail'") if (!is.logical(log.p) || length(log.p) != 1) stop("bad input for argument 'log.p'") ans <- q * 0 qstar <- (q - lower)^2 / ((upper - lower) * (theta - lower)) Neg <- (lower <= q & q <= theta) ans[Neg] <- if (lower.tail) { if (log.p) { (log(qstar))[Neg] } else { qstar[Neg] } } else { if (log.p) { (log1p(-qstar))[Neg] } else { 1 - qstar[Neg] } } Pos <- (theta <= q & q <= upper) qstar <- (q - theta) / (upper-theta) if (lower.tail) { if (log.p) { ans[Pos] <- log(((theta-lower)/(upper-lower))[Pos] + (qstar * (2-qstar) * (upper-theta) / (upper - lower))[Pos]) ans[q <= lower] <- -Inf ans[q >= upper] <- 0 } else { ans[Pos] <- ((theta-lower)/(upper-lower))[Pos] + (qstar * (2-qstar) * (upper-theta) / (upper - lower))[Pos] ans[q <= lower] <- 0 ans[q >= upper] <- 1 } } else { if (log.p) { ans[Pos] <- log(((upper - theta)/(upper-lower))[Pos] + (qstar * (2-qstar) * (upper-theta) / (upper - lower))[Pos]) ans[q <= lower] <- 0 ans[q >= upper] <- -Inf } else { ans[Pos] <- ((upper - theta)/(upper-lower))[Pos] + (qstar * (2-qstar) * (upper-theta) / (upper - lower))[Pos] ans[q <= lower] <- 1 ans[q >= upper] <- 0 } } ans[theta < lower | theta > upper] <- NaN ans } triangle.control <- function(stepsize = 0.33, maxit = 100, ...) { list(stepsize = stepsize, maxit = maxit) } triangle <- function(lower = 0, upper = 1, link = extlogitlink(min = 0, max = 1), itheta = NULL) { if (!is.Numeric(lower)) stop("bad input for argument 'lower'") if (!is.Numeric(upper)) stop("bad input for argument 'upper'") if (!all(lower < upper)) stop("lower < upper values are required") if (length(itheta) && !is.Numeric(itheta)) stop("bad input for 'itheta'") link <- as.list(substitute(link)) earg <- link2list(link) link <- attr(earg, "function.name") if (length(earg$min) && any(earg$min != lower)) stop("argument 'lower' does not match the 'link'") if (length(earg$max) && any(earg$max != upper)) stop("argument 'upper' does not match the 'link'") new("vglmff", blurb = c("Triangle distribution\n\n", "Link: ", namesof("theta", link, earg = earg)), infos = eval(substitute(function(...) { list(M1 = 1, Q1 = 1, parameters.names = c("theta"), link = .link ) }, list( .link = link ))), initialize = eval(substitute(expression({ w.y.check(w = w, y = y, ncol.w.max = 1, ncol.y.max = 1) extra$lower <- rep_len( .lower , n) extra$upper <- rep_len( .upper , n) if (any(y <= extra$lower | y >= extra$upper)) stop("some y values in [lower,upper] detected") predictors.names <- namesof("theta", .link , earg = .earg , tag = FALSE) if (!length(etastart)) { Theta.init <- if (length( .itheta )) .itheta else { weighted.mean(y, w) } Theta.init <- rep_len(Theta.init, n) etastart <- theta2eta(Theta.init, .link , earg = .earg ) } }), list( .link = link, .earg = earg, .itheta=itheta, .upper = upper, .lower = lower ))), linkinv = eval(substitute(function(eta, extra = NULL) { Theta <- eta2theta(eta, .link , earg = .earg ) lower <- extra$lower upper <- extra$upper mu1 <- (lower + upper + Theta) / 3 mu1 }, list( .link = link, .earg = earg ))), last = eval(substitute(expression({ misc$link <- c(theta = .link ) misc$earg <- list(theta = .earg ) misc$expected <- TRUE }), list( .link = link, .earg = earg ))), loglikelihood = eval(substitute( function(mu, y, w, residuals = FALSE, eta, extra = NULL, summation = TRUE) { Theta <- eta2theta(eta, .link , earg = .earg ) lower <- extra$lower upper <- extra$upper if (residuals) { stop("loglikelihood residuals not implemented yet") } else { ll.elts <- c(w) * dtriangle(x = y, theta = Theta, lower = lower, upper = upper, log = TRUE) if (summation) { sum(ll.elts) } else { ll.elts } } }, list( .link = link, .earg = earg ))), vfamily = c("triangle"), validparams = eval(substitute(function(eta, y, extra = NULL) { Theta <- eta2theta(eta, .link , earg = .earg ) okay1 <- all(is.finite(Theta)) && all(extra$lower < Theta & Theta < extra$upper) okay1 }, list( .link = link, .earg = earg ))), simslot = eval(substitute( function(object, nsim) { pwts <- if (length(pwts <- [email protected]) > 0) pwts else weights(object, type = "prior") if (any(pwts != 1)) warning("ignoring prior weights") eta <- predict(object) extra <- object@extra Theta <- eta2theta(eta, .link , earg = .earg ) lower <- extra$lower upper <- extra$upper rtriangle(nsim * length(Theta), theta = Theta, lower = lower, upper = upper) }, list( .link = link, .earg = earg ))), deriv = eval(substitute(expression({ Theta <- eta2theta(eta, .link , earg = .earg ) dTheta.deta <- dtheta.deta(Theta, .link , earg = .earg ) pos <- y > Theta neg <- y < Theta lower <- extra$lower upper <- extra$upper dl.dTheta <- 0 * y dl.dTheta[neg] <- -1 / (Theta[neg]-lower[neg]) dl.dTheta[pos] <- 1 / (upper[pos]-Theta[pos]) c(w) * dl.dTheta * dTheta.deta }), list( .link = link, .earg = earg ))), weight = eval(substitute(expression({ var.dl.dTheta <- 1 / ((Theta - lower) * (upper - Theta)) wz <- var.dl.dTheta * dTheta.deta^2 c(w) * wz }), list( .link = link, .earg = earg )))) } adjust0.loglaplace1 <- function(ymat, y, w, rep0) { rangey0 <- range(y[y > 0]) ymat[ymat <= 0] <- min(rangey0[1] / 2, rep0) ymat } loglaplace1.control <- function(maxit = 300, ...) { list(maxit = maxit) } loglaplace1 <- function(tau = NULL, llocation = "loglink", ilocation = NULL, kappa = sqrt(tau/(1-tau)), Scale.arg = 1, ishrinkage = 0.95, parallel.locat = FALSE, digt = 4, idf.mu = 3, rep0 = 0.5, minquantile = 0, maxquantile = Inf, imethod = 1, zero = NULL) { if (length(minquantile) != 1) stop("bad input for argument 'minquantile'") if (length(maxquantile) != 1) stop("bad input for argument 'maxquantile'") if (!is.Numeric(rep0, positive = TRUE, length.arg = 1) || rep0 > 1) stop("bad input for argument 'rep0'") if (!is.Numeric(kappa, positive = TRUE)) stop("bad input for argument 'kappa'") if (length(tau) && max(abs(kappa - sqrt(tau/(1-tau)))) > 1.0e-6) stop("arguments 'kappa' and 'tau' do not match") llocat <- as.list(substitute(llocation)) elocat <- link2list(llocat) llocat <- attr(elocat, "function.name") ilocat <- ilocation llocat.identity <- as.list(substitute("identitylink")) elocat.identity <- link2list(llocat.identity) llocat.identity <- attr(elocat.identity, "function.name") if (!is.Numeric(imethod, length.arg = 1, integer.valued = TRUE, positive = TRUE) || imethod > 4) stop("argument 'imethod' must be 1, 2 or ... 4") if (!is.Numeric(ishrinkage, length.arg = 1) || ishrinkage < 0 || ishrinkage > 1) stop("bad input for argument 'ishrinkage'") if (!is.Numeric(Scale.arg, positive = TRUE)) stop("bad input for argument 'Scale.arg'") if (!is.logical(parallel.locat) || length(parallel.locat) != 1) stop("bad input for argument 'parallel.locat'") fittedMean <- FALSE if (!is.logical(fittedMean) || length(fittedMean) != 1) stop("bad input for argument 'fittedMean'") mystring0 <- namesof("location", llocat, earg = elocat) mychars <- substring(mystring0, first = 1:nchar(mystring0), last = 1:nchar(mystring0)) mychars[nchar(mystring0)] <- ", inverse = TRUE)" mystring1 <- paste(mychars, collapse = "") new("vglmff", blurb = c("One-parameter ", if (llocat == "loglink") "log-Laplace" else c(llocat, "-Laplace"), " distribution\n\n", "Links: ", mystring0, "\n", "\n", "Quantiles: ", mystring1), constraints = eval(substitute(expression({ constraints <- cm.VGAM(matrix(1, M, 1), x = x, bool = .parallel.locat , constraints = constraints, apply.int = FALSE) constraints <- cm.zero.VGAM(constraints, x = x, .zero , M = M, predictors.names = predictors.names, M1 = 1) }), list( .parallel.locat = parallel.locat, .Scale.arg = Scale.arg, .zero = zero ))), infos = eval(substitute(function(...) { list(M1 = 1, Q1 = 1, parameters.names = c("location"), llocation = .llocat ) }, list( .llocat = llocat, .zero = zero ))), initialize = eval(substitute(expression({ extra$M <- M <- max(length( .Scale.arg ), length( .kappa )) extra$Scale <- rep_len( .Scale.arg , M) extra$kappa <- rep_len( .kappa , M) extra$tau <- extra$kappa^2 / (1 + extra$kappa^2) temp5 <- w.y.check(w = w, y = y, ncol.w.max = 1, ncol.y.max = 1, out.wy = TRUE, maximize = TRUE) w <- temp5$w y <- temp5$y extra$n <- n extra$y.names <- y.names <- paste("tau = ", round(extra$tau, digits = .digt), sep = "") extra$individual <- FALSE predictors.names <- namesof(paste("quantile(", y.names, ")", sep = ""), .llocat , earg = .elocat , tag = FALSE) if (FALSE) { if (min(y) < 0) stop("negative response values detected") if ((prop.0. <- weighted.mean(1*(y == 0), w)) >= min(extra$tau)) stop("sample proportion of 0s == ", round(prop.0., digits = 4), " > minimum 'tau' value. Choose larger values for 'tau'.") if ( .rep0 == 0.5 && (ave.tau <- (weighted.mean(1*(y <= 0), w) + weighted.mean(1*(y <= 1), w))/2) >= min(extra$tau)) warning("the minimum 'tau' value should be greater than ", round(ave.tau, digits = 4)) } if (!length(etastart)) { if ( .imethod == 1) { locat.init <- quantile(rep(y, w), probs= extra$tau) + 1/16 } else if ( .imethod == 2) { locat.init <- weighted.mean(y, w) } else if ( .imethod == 3) { locat.init <- median(y) } else if ( .imethod == 4) { Fit5 <- vsmooth.spline(x = x[, min(ncol(x), 2)], y = y, w = w, df = .idf.mu ) locat.init <- c(predict(Fit5, x = x[, min(ncol(x), 2)])$y) } else { use.this <- weighted.mean(y, w) locat.init <- (1- .ishrinkage )*y + .ishrinkage * use.this } locat.init <- if (length( .ilocat )) rep_len( .ilocat , M) else rep_len(locat.init, M) locat.init <- matrix(locat.init, n, M, byrow = TRUE) if ( .llocat == "loglink") locat.init <- abs(locat.init) etastart <- cbind(theta2eta(locat.init, .llocat , earg = .elocat )) } }), list( .imethod = imethod, .idf.mu = idf.mu, .rep0 = rep0, .ishrinkage = ishrinkage, .digt = digt, .elocat = elocat, .Scale.arg = Scale.arg, .llocat = llocat, .kappa = kappa, .ilocat = ilocat ))), linkinv = eval(substitute(function(eta, extra = NULL) { locat.y = eta2theta(eta, .llocat , earg = .elocat ) if ( .fittedMean ) { stop("Yet to do: handle 'fittedMean = TRUE'") kappamat <- matrix(extra$kappa, extra$n, extra$M, byrow = TRUE) Scale <- matrix(extra$Scale, extra$n, extra$M, byrow = TRUE) locat.y + Scale * (1/kappamat - kappamat) } else { if (length(locat.y) > extra$n) dimnames(locat.y) <- list(dimnames(eta)[[1]], extra$y.names) locat.y } locat.y[locat.y < .minquantile] = .minquantile locat.y[locat.y > .maxquantile] = .maxquantile locat.y }, list( .elocat = elocat, .llocat = llocat, .minquantile = minquantile, .maxquantile = maxquantile, .fittedMean = fittedMean, .Scale.arg = Scale.arg, .kappa = kappa ))), last = eval(substitute(expression({ misc$link <- c(location = .llocat) misc$earg <- list(location = .elocat ) misc$expected <- TRUE extra$kappa <- misc$kappa <- .kappa extra$tau <- misc$tau <- misc$kappa^2 / (1 + misc$kappa^2) extra$Scale.arg <- .Scale.arg misc$true.mu <- .fittedMean misc$rep0 <- .rep0 misc$minquantile <- .minquantile misc$maxquantile <- .maxquantile extra$percentile <- numeric(length(misc$kappa)) locat.y <- as.matrix(locat.y) for (ii in seq_along(misc$kappa)) extra$percentile[ii] <- 100 * weighted.mean(y <= locat.y[, ii], w) }), list( .elocat = elocat, .llocat = llocat, .Scale.arg = Scale.arg, .fittedMean = fittedMean, .minquantile = minquantile, .maxquantile = maxquantile, .rep0 = rep0, .kappa = kappa ))), loglikelihood = eval(substitute( function(mu, y, w, residuals = FALSE, eta, extra = NULL, summation = TRUE) { kappamat <- matrix(extra$kappa, extra$n, extra$M, byrow = TRUE) Scale.w <- matrix(extra$Scale, extra$n, extra$M, byrow = TRUE) ymat <- matrix(y, extra$n, extra$M) if ( .llocat == "loglink") ymat <- adjust0.loglaplace1(ymat = ymat, y = y, w = w, rep0 = .rep0) w.mat <- theta2eta(ymat, .llocat , earg = .elocat ) if (residuals) { stop("loglikelihood residuals not implemented yet") } else { ll.elts <- c(w) * dalap(x = c(w.mat), locat = c(eta), scale = c(Scale.w), kappa = c(kappamat), log = TRUE) if (summation) { sum(ll.elts) } else { ll.elts } } }, list( .elocat = elocat, .llocat = llocat, .rep0 = rep0, .Scale.arg = Scale.arg, .kappa = kappa ))), vfamily = c("loglaplace1"), validparams = eval(substitute(function(eta, y, extra = NULL) { locat.w <- eta locat.y <- eta2theta(locat.w, .llocat , earg = .elocat ) okay1 <- all(is.finite(locat.y)) okay1 }, list( .elocat = elocat, .llocat = llocat, .rep0 = rep0, .Scale.arg = Scale.arg, .kappa = kappa ))), deriv = eval(substitute(expression({ ymat <- matrix(y, n, M) Scale.w <- matrix(extra$Scale, extra$n, extra$M, byrow = TRUE) locat.w <- eta locat.y <- eta2theta(locat.w, .llocat , earg = .elocat ) kappamat <- matrix(extra$kappa, n, M, byrow = TRUE) ymat <- adjust0.loglaplace1(ymat = ymat, y = y, w = w, rep0= .rep0) w.mat <- theta2eta(ymat, .llocat , earg = .elocat ) zedd <- abs(w.mat-locat.w) / Scale.w dl.dlocat <- ifelse(w.mat >= locat.w, kappamat, 1/kappamat) * sqrt(2) * sign(w.mat-locat.w) / Scale.w dlocat.deta <- dtheta.deta(locat.w, .llocat.identity , earg = .elocat.identity ) c(w) * cbind(dl.dlocat * dlocat.deta) }), list( .Scale.arg = Scale.arg, .rep0 = rep0, .llocat = llocat, .elocat = elocat, .elocat.identity = elocat.identity, .llocat.identity = llocat.identity, .kappa = kappa ))), weight = eval(substitute(expression({ ned2l.dlocat2 <- 2 / Scale.w^2 wz <- cbind(ned2l.dlocat2 * dlocat.deta^2) c(w) * wz }), list( .Scale.arg = Scale.arg, .elocat = elocat, .llocat = llocat, .elocat.identity = elocat.identity, .llocat.identity = llocat.identity )))) } loglaplace2.control <- function(save.weights = TRUE, ...) { list(save.weights = save.weights) } loglaplace2 <- function(tau = NULL, llocation = "loglink", lscale = "loglink", ilocation = NULL, iscale = NULL, kappa = sqrt(tau/(1-tau)), ishrinkage = 0.95, parallel.locat = FALSE, digt = 4, eq.scale = TRUE, idf.mu = 3, rep0 = 0.5, nsimEIM = NULL, imethod = 1, zero = "(1 + M/2):M") { warning("it is best to use loglaplace1()") if (length(nsimEIM) && (!is.Numeric(nsimEIM, length.arg = 1, integer.valued = TRUE) || nsimEIM <= 10)) stop("argument 'nsimEIM' should be an integer greater than 10") if (!is.Numeric(rep0, positive = TRUE, length.arg = 1) || rep0 > 1) stop("bad input for argument 'rep0'") if (!is.Numeric(kappa, positive = TRUE)) stop("bad input for argument 'kappa'") if (length(tau) && max(abs(kappa - sqrt(tau/(1-tau)))) > 1.0e-6) stop("arguments 'kappa' and 'tau' do not match") llocat <- as.list(substitute(llocation)) elocat <- link2list(llocat) llocat <- attr(elocat, "function.name") ilocat <- ilocation lscale <- as.list(substitute(lscale)) escale <- link2list(lscale) lscale <- attr(escale, "function.name") if (!is.Numeric(imethod, length.arg = 1, integer.valued = TRUE, positive = TRUE) || imethod > 4) stop("argument 'imethod' must be 1, 2 or ... 4") if (length(iscale) && !is.Numeric(iscale, positive = TRUE)) stop("bad input for argument 'iscale'") if (!is.Numeric(ishrinkage, length.arg = 1) || ishrinkage < 0 || ishrinkage > 1) stop("bad input for argument 'ishrinkage'") if (!is.logical(eq.scale) || length(eq.scale) != 1) stop("bad input for argument 'eq.scale'") if (!is.logical(parallel.locat) || length(parallel.locat) != 1) stop("bad input for argument 'parallel.locat'") fittedMean <- FALSE if (!is.logical(fittedMean) || length(fittedMean) != 1) stop("bad input for argument 'fittedMean'") if (llocat != "loglink") stop("argument 'llocat' must be \"loglink\"") new("vglmff", blurb = c("Two-parameter log-Laplace distribution\n\n", "Links: ", namesof("location", llocat, earg = elocat), ", ", namesof("scale", lscale, earg = escale), "\n", "\n", "Mean: zz location + scale * ", "(1/kappa - kappa) / sqrt(2)", "\n", "Quantiles: location", "\n", "Variance: zz scale^2 * (1 + kappa^4) / (2 * kappa^2)"), constraints = eval(substitute(expression({ .ZERO <- .zero if (is.character( .ZERO )) .ZERO <- eval(parse(text = .ZERO )) .PARALLEL <- .parallel.locat parelHmat <- if (is.logical( .PARALLEL ) && .PARALLEL ) matrix(1, M/2, 1) else diag(M/2) scaleHmat <- if (is.logical( .eq.scale ) && .eq.scale ) matrix(1, M/2, 1) else diag(M/2) mycmatrix <- cbind(rbind( parelHmat, 0*parelHmat), rbind(0*scaleHmat, scaleHmat)) constraints <- cm.VGAM(mycmatrix, x = x, bool = .PARALLEL , constraints = constraints, apply.int = FALSE) constraints <- cm.zero.VGAM(constraints, x = x, .ZERO , M = M, predictors.names = predictors.names, M1 = 2) if ( .PARALLEL && names(constraints)[1] == "(Intercept)") { parelHmat <- diag(M/2) mycmatrix <- cbind(rbind( parelHmat, 0*parelHmat), rbind(0*scaleHmat, scaleHmat)) constraints[["(Intercept)"]] <- mycmatrix } if (is.logical( .eq.scale) && .eq.scale && names(constraints)[1] == "(Intercept)") { temp3 <- constraints[["(Intercept)"]] temp3 <- cbind(temp3[,1:(M/2)], rbind(0*scaleHmat, scaleHmat)) constraints[["(Intercept)"]] = temp3 } }), list( .eq.scale = eq.scale, .parallel.locat = parallel.locat, .zero = zero ))), initialize = eval(substitute(expression({ extra$kappa <- .kappa extra$tau <- extra$kappa^2 / (1 + extra$kappa^2) temp5 <- w.y.check(w = w, y = y, ncol.w.max = 1, ncol.y.max = 1, out.wy = TRUE, maximize = TRUE) w <- temp5$w y <- temp5$y extra$M <- M <- 2 * length(extra$kappa) extra$n <- n extra$y.names <- y.names <- paste("tau = ", round(extra$tau, digits = .digt), sep = "") extra$individual = FALSE predictors.names <- c(namesof(paste("quantile(", y.names, ")", sep = ""), .llocat , earg = .elocat, tag = FALSE), namesof(if (M == 2) "scale" else paste("scale", 1:(M/2), sep = ""), .lscale , earg = .escale, tag = FALSE)) if (weighted.mean(1 * (y < 0.001), w) >= min(extra$tau)) stop("sample proportion of 0s > minimum 'tau' value. ", "Choose larger values for 'tau'.") if (!length(etastart)) { if ( .imethod == 1) { locat.init.y <- weighted.mean(y, w) scale.init <- sqrt(var(y) / 2) } else if ( .imethod == 2) { locat.init.y <- median(y) scale.init <- sqrt(sum(c(w)*abs(y-median(y))) / (sum(w) *2)) } else if ( .imethod == 3) { Fit5 <- vsmooth.spline(x = x[, min(ncol(x), 2)], y = y, w = w, df = .idf.mu ) locat.init.y <- c(predict(Fit5, x = x[, min(ncol(x), 2)])$y) scale.init <- sqrt(sum(c(w)*abs(y-median(y))) / (sum(w) *2)) } else { use.this <- weighted.mean(y, w) locat.init.y <- (1- .ishrinkage )*y + .ishrinkage * use.this scale.init <- sqrt(sum(c(w)*abs(y-median(y ))) / (sum(w) *2)) } locat.init.y <- if (length( .ilocat )) rep_len( .ilocat , n) else rep_len(locat.init.y, n) locat.init.y <- matrix(locat.init.y, n, M/2) scale.init <- if (length( .iscale )) rep_len( .iscale , n) else rep_len(scale.init, n) scale.init <- matrix(scale.init, n, M/2) etastart <- cbind(theta2eta(locat.init.y, .llocat , earg = .elocat ), theta2eta(scale.init, .lscale , earg = .escale )) } }), list( .imethod = imethod, .idf.mu = idf.mu, .kappa = kappa, .ishrinkage = ishrinkage, .digt = digt, .llocat = llocat, .lscale = lscale, .elocat = elocat, .escale = escale, .ilocat = ilocat, .iscale = iscale ))), linkinv = eval(substitute(function(eta, extra = NULL) { locat.y <- eta2theta(eta[, 1:(extra$M/2), drop = FALSE], .llocat , earg = .elocat ) if ( .fittedMean ) { kappamat <- matrix(extra$kappa, extra$n, extra$M/2, byrow = TRUE) Scale.y <- eta2theta(eta[,(1+extra$M/2):extra$M], .lscale , earg = .escale ) locat.y + Scale.y * (1/kappamat - kappamat) } else { dimnames(locat.y) = list(dimnames(eta)[[1]], extra$y.names) locat.y } }, list( .llocat = llocat, .lscale = lscale, .elocat = elocat, .escale = escale, .fittedMean = fittedMean, .kappa = kappa ))), last = eval(substitute(expression({ misc$link <- c(location = .llocat , scale = .lscale ) misc$earg <- list(location = .elocat , scale = .escale ) misc$expected <- TRUE extra$kappa <- misc$kappa <- .kappa extra$tau <- misc$tau <- misc$kappa^2 / (1 + misc$kappa^2) misc$true.mu <- .fittedMean misc$nsimEIM <- .nsimEIM misc$rep0 <- .rep0 extra$percentile <- numeric(length(misc$kappa)) locat <- as.matrix(locat.y) for (ii in seq_along(misc$kappa)) extra$percentile[ii] <- 100 * weighted.mean(y <= locat.y[, ii], w) }), list( .elocat = elocat, .llocat = llocat, .escale = escale, .lscale = lscale, .fittedMean = fittedMean, .nsimEIM = nsimEIM, .rep0 = rep0, .kappa = kappa ))), loglikelihood = eval(substitute( function(mu, y, w, residuals = FALSE, eta, extra = NULL, summation = TRUE) { kappamat <- matrix(extra$kappa, extra$n, extra$M/2, byrow = TRUE) Scale.w <- eta2theta(eta[, (1+extra$M/2):extra$M], .lscale , earg = .escale ) ymat <- matrix(y, extra$n, extra$M/2) ymat[ymat <= 0] <- min(min(y[y > 0]), .rep0 ) ell.mat <- matrix(c(dloglaplace(x = c(ymat), locat.ald = c(eta[, 1:(extra$M/2)]), scale.ald = c(Scale.w), kappa = c(kappamat), log = TRUE)), extra$n, extra$M/2) if (residuals) { stop("loglikelihood residuals not implemented yet") } else { ll.elts <- c(w) * ell.mat if (summation) { sum(ll.elts) } else { ll.elts } } }, list( .elocat = elocat, .llocat = llocat, .escale = escale, .lscale = lscale, .rep0 = rep0, .kappa = kappa ))), vfamily = c("loglaplace2"), validparams = eval(substitute(function(eta, y, extra = NULL) { Scale.w <- eta2theta(eta[, (1+extra$M/2):extra$M], .lscale , earg = .escale ) locat.w <- eta[, 1:(extra$M/2), drop = FALSE] locat.y <- eta2theta(locat.w, .llocat , earg = .elocat ) okay1 <- all(is.finite(locat.y)) && all(is.finite(Scale.w)) && all(0 < Scale.w) okay1 }, list( .elocat = elocat, .llocat = llocat, .escale = escale, .lscale = lscale, .rep0 = rep0, .kappa = kappa ))), deriv = eval(substitute(expression({ ymat <- matrix(y, n, M/2) Scale.w <- eta2theta(eta[, (1+extra$M/2):extra$M], .lscale , earg = .escale ) locat.w <- eta[, 1:(extra$M/2), drop = FALSE] locat.y <- eta2theta(locat.w, .llocat , earg = .elocat ) kappamat <- matrix(extra$kappa, n, M/2, byrow = TRUE) w.mat <- ymat w.mat[w.mat <= 0] <- min(min(w.mat[w.mat > 0]), .rep0) w.mat <- theta2eta(w.mat, .llocat , earg = .elocat ) zedd <- abs(w.mat-locat.w) / Scale.w dl.dlocat <- sqrt(2) * ifelse(w.mat >= locat.w, kappamat, 1/kappamat) * sign(w.mat-locat.w) / Scale.w dl.dscale <- sqrt(2) * ifelse(w.mat >= locat.w, kappamat, 1/kappamat) * zedd / Scale.w - 1 / Scale.w dlocat.deta <- dtheta.deta(locat.w, .llocat , earg = .elocat ) dscale.deta <- dtheta.deta(Scale.w, .lscale , earg = .escale ) c(w) * cbind(dl.dlocat * dlocat.deta, dl.dscale * dscale.deta) }), list( .escale = escale, .lscale = lscale, .elocat = elocat, .llocat = llocat, .rep0 = rep0, .kappa = kappa ))), weight = eval(substitute(expression({ run.varcov <- 0 ind1 <- iam(NA, NA, M = M, both = TRUE, diag = TRUE) dthetas.detas <- cbind(dlocat.deta, dscale.deta) if (length( .nsimEIM )) { for (ii in 1:( .nsimEIM )) { wsim <- matrix(rloglap(n*M/2, loc = c(locat.w), sca = c(Scale.w), kappa = c(kappamat)), n, M/2) zedd <- abs(wsim-locat.w) / Scale.w dl.dlocat <- sqrt(2) * ifelse(wsim >= locat.w, kappamat, 1/kappamat) * sign(wsim-locat.w) / Scale.w dl.dscale <- sqrt(2) * ifelse(wsim >= locat.w, kappamat, 1/kappamat) * zedd / Scale.w - 1 / Scale.w rm(wsim) temp3 <- cbind(dl.dlocat, dl.dscale) run.varcov <- ((ii-1) * run.varcov + temp3[,ind1$row.index]*temp3[,ind1$col.index]) / ii } wz <- if (intercept.only) matrix(colMeans(run.varcov), n, ncol(run.varcov), byrow = TRUE) else run.varcov wz <- wz * dthetas.detas[,ind1$row] * dthetas.detas[,ind1$col] wz <- c(w) * matrix(wz, n, dimm(M)) wz } else { d2l.dlocat2 <- 2 / (Scale.w * locat.w)^2 d2l.dscale2 <- 1 / Scale.w^2 wz <- cbind(d2l.dlocat2 * dlocat.deta^2, d2l.dscale2 * dscale.deta^2) c(w) * wz } }), list( .elocat = elocat, .escale = escale, .llocat = llocat, .lscale = lscale, .nsimEIM = nsimEIM) ))) } logitlaplace1.control <- function(maxit = 300, ...) { list(maxit = maxit) } adjust01.logitlaplace1 <- function(ymat, y, w, rep01) { rangey01 <- range(y[(y > 0) & (y < 1)]) ymat[ymat <= 0] <- min(rangey01[1] / 2, rep01 / w[y <= 0]) ymat[ymat >= 1] <- max((1 + rangey01[2]) / 2, 1 - rep01 / w[y >= 1]) ymat } logitlaplace1 <- function(tau = NULL, llocation = "logitlink", ilocation = NULL, kappa = sqrt(tau/(1-tau)), Scale.arg = 1, ishrinkage = 0.95, parallel.locat = FALSE, digt = 4, idf.mu = 3, rep01 = 0.5, imethod = 1, zero = NULL) { if (!is.Numeric(rep01, positive = TRUE, length.arg = 1) || rep01 > 0.5) stop("bad input for argument 'rep01'") if (!is.Numeric(kappa, positive = TRUE)) stop("bad input for argument 'kappa'") if (length(tau) && max(abs(kappa - sqrt(tau/(1-tau)))) > 1.0e-6) stop("arguments 'kappa' and 'tau' do not match") llocat <- as.list(substitute(llocation)) elocat <- link2list(llocat) llocat <- attr(elocat, "function.name") ilocat <- ilocation llocat.identity <- as.list(substitute("identitylink")) elocat.identity <- link2list(llocat.identity) llocat.identity <- attr(elocat.identity, "function.name") if (!is.Numeric(imethod, length.arg = 1, integer.valued = TRUE, positive = TRUE) || imethod > 4) stop("argument 'imethod' must be 1, 2 or ... 4") if (!is.Numeric(ishrinkage, length.arg = 1) || ishrinkage < 0 || ishrinkage > 1) stop("bad input for argument 'ishrinkage'") if (!is.Numeric(Scale.arg, positive = TRUE)) stop("bad input for argument 'Scale.arg'") if (!is.logical(parallel.locat) || length(parallel.locat) != 1) stop("bad input for argument 'parallel.locat'") fittedMean <- FALSE if (!is.logical(fittedMean) || length(fittedMean) != 1) stop("bad input for argument 'fittedMean'") mystring0 <- namesof("location", llocat, earg = elocat) mychars <- substring(mystring0, first = 1:nchar(mystring0), last = 1:nchar(mystring0)) mychars[nchar(mystring0)] = ", inverse = TRUE)" mystring1 <- paste(mychars, collapse = "") new("vglmff", blurb = c("One-parameter ", llocat, "-Laplace distribution\n\n", "Links: ", mystring0, "\n", "\n", "Quantiles: ", mystring1), constraints = eval(substitute(expression({ constraints <- cm.VGAM(matrix(1, M, 1), x = x, bool = .parallel.locat , constraints = constraints, apply.int = FALSE) constraints <- cm.zero.VGAM(constraints, x = x, .zero , M = M, predictors.names = predictors.names, M1 = 1) }), list( .parallel.locat = parallel.locat, .Scale.arg = Scale.arg, .zero = zero ))), infos = eval(substitute(function(...) { list(M1 = 1, Q1 = 1, multipleResponses = FALSE, parameters.names = c("location"), llocation = .llocat , zero = .zero ) }, list( .zero = zero, .llocat = llocat ))), initialize = eval(substitute(expression({ extra$M <- M <- max(length( .Scale.arg ), length( .kappa )) extra$Scale <- rep_len( .Scale.arg , M) extra$kappa <- rep_len( .kappa , M) extra$tau <- extra$kappa^2 / (1 + extra$kappa^2) temp5 <- w.y.check(w = w, y = y, ncol.w.max = 1, ncol.y.max = 1, out.wy = TRUE, maximize = TRUE) w <- temp5$w y <- temp5$y extra$n <- n extra$y.names <- y.names <- paste("tau = ", round(extra$tau, digits = .digt), sep = "") extra$individual <- FALSE predictors.names <- namesof(paste("quantile(", y.names, ")", sep = ""), .llocat , earg = .elocat, tag = FALSE) if (all(y == 0 | y == 1)) stop("response cannot be all 0s or 1s") if (min(y) < 0) stop("negative response values detected") if (max(y) > 1) stop("response values greater than 1 detected") if ((prop.0. <- weighted.mean(1*(y == 0), w)) >= min(extra$tau)) stop("sample proportion of 0s == ", round(prop.0., digits = 4), " > minimum 'tau' value. Choose larger values for 'tau'.") if ((prop.1. <- weighted.mean(1*(y == 1), w)) >= max(extra$tau)) stop("sample proportion of 1s == ", round(prop.1., digits = 4), " < maximum 'tau' value. Choose smaller values for 'tau'.") if (!length(etastart)) { if ( .imethod == 1) { locat.init <- quantile(rep(y, w), probs= extra$tau) } else if ( .imethod == 2) { locat.init <- weighted.mean(y, w) locat.init <- median(rep(y, w)) } else if ( .imethod == 3) { use.this <- weighted.mean(y, w) locat.init <- (1- .ishrinkage )*y + use.this * .ishrinkage } else { stop("this option not implemented") } locat.init <- if (length( .ilocat )) rep_len( .ilocat , M) else rep_len(locat.init, M) locat.init <- matrix(locat.init, n, M, byrow = TRUE) locat.init <- abs(locat.init) etastart <- cbind(theta2eta(locat.init, .llocat , earg = .elocat )) } }), list( .imethod = imethod, .idf.mu = idf.mu, .ishrinkage = ishrinkage, .digt = digt, .elocat = elocat, .Scale.arg = Scale.arg, .llocat = llocat, .kappa = kappa, .ilocat = ilocat ))), linkinv = eval(substitute(function(eta, extra = NULL) { locat.y <- eta2theta(eta, .llocat , earg = .elocat ) if ( .fittedMean ) { stop("Yet to do: handle 'fittedMean = TRUE'") kappamat <- matrix(extra$kappa, extra$n, extra$M, byrow = TRUE) Scale <- matrix(extra$Scale, extra$n, extra$M, byrow = TRUE) locat.y + Scale * (1/kappamat - kappamat) } else { if (length(locat.y) > extra$n) dimnames(locat.y) <- list(dimnames(eta)[[1]], extra$y.names) locat.y } }, list( .elocat = elocat, .llocat = llocat, .fittedMean = fittedMean, .Scale.arg = Scale.arg, .kappa = kappa ))), last = eval(substitute(expression({ misc$link <- c(location = .llocat ) misc$earg <- list(location = .elocat ) misc$expected <- TRUE extra$kappa <- misc$kappa <- .kappa extra$tau <- misc$tau <- misc$kappa^2 / (1 + misc$kappa^2) extra$Scale.arg <- .Scale.arg misc$true.mu <- .fittedMean misc$rep01 <- .rep01 extra$percentile <- numeric(length(misc$kappa)) locat.y <- eta2theta(eta, .llocat , earg = .elocat ) locat.y <- as.matrix(locat.y) for (ii in seq_along(misc$kappa)) extra$percentile[ii] <- 100 * weighted.mean(y <= locat.y[, ii], w) }), list( .elocat = elocat, .llocat = llocat, .Scale.arg = Scale.arg, .fittedMean = fittedMean, .rep01 = rep01, .kappa = kappa ))), loglikelihood = eval(substitute( function(mu, y, w, residuals = FALSE, eta, extra = NULL, summation = TRUE) { kappamat <- matrix(extra$kappa, extra$n, extra$M, byrow = TRUE) Scale.w <- matrix(extra$Scale, extra$n, extra$M, byrow = TRUE) ymat <- matrix(y, extra$n, extra$M) ymat <- adjust01.logitlaplace1(ymat = ymat, y = y, w = w, rep01 = .rep01) w.mat <- theta2eta(ymat, .llocat , earg = .elocat ) if (residuals) { stop("loglikelihood residuals not implemented yet") } else { ll.elts <- c(w) * dalap(x = c(w.mat), location = c(eta), scale = c(Scale.w), kappa = c(kappamat), log = TRUE) if (summation) { sum(ll.elts) } else { ll.elts } } }, list( .elocat = elocat, .llocat = llocat, .rep01 = rep01, .Scale.arg = Scale.arg, .kappa = kappa ))), vfamily = c("logitlaplace1"), validparams = eval(substitute(function(eta, y, extra = NULL) { locat.w <- eta okay1 <- all(is.finite(locat.w)) okay1 }, list( .Scale.arg = Scale.arg, .rep01 = rep01, .elocat = elocat, .llocat = llocat, .elocat.identity = elocat.identity, .llocat.identity = llocat.identity, .kappa = kappa ))), deriv = eval(substitute(expression({ ymat <- matrix(y, n, M) Scale.w <- matrix(extra$Scale, extra$n, extra$M, byrow = TRUE) locat.w <- eta kappamat <- matrix(extra$kappa, n, M, byrow = TRUE) ymat <- adjust01.logitlaplace1(ymat = ymat, y = y, w = w, rep01 = .rep01 ) w.mat <- theta2eta(ymat, .llocat , earg = .elocat ) zedd <- abs(w.mat - locat.w) / Scale.w dl.dlocat <- ifelse(w.mat >= locat.w, kappamat, 1/kappamat) * sqrt(2) * sign(w.mat-locat.w) / Scale.w dlocat.deta <- dtheta.deta(locat.w, "identitylink", earg = .elocat.identity ) c(w) * cbind(dl.dlocat * dlocat.deta) }), list( .Scale.arg = Scale.arg, .rep01 = rep01, .elocat = elocat, .llocat = llocat, .elocat.identity = elocat.identity, .llocat.identity = llocat.identity, .kappa = kappa ))), weight = eval(substitute(expression({ d2l.dlocat2 <- 2 / Scale.w^2 wz <- cbind(d2l.dlocat2 * dlocat.deta^2) c(w) * wz }), list( .Scale.arg = Scale.arg, .elocat = elocat, .llocat = llocat )))) }
as.party <- function(obj, ...) UseMethod("as.party") as.party.rpart <- function(obj, data = TRUE, ...) { ff <- obj$frame n <- nrow(ff) mf <- model_frame_rpart(obj) for(i in which(sapply(mf, function(x) class(x)[1L]) == "character")) mf[[i]] <- factor(mf[[i]]) rpart_fitted <- function() { ret <- as.data.frame(matrix(nrow = NROW(mf), ncol = 0)) ret[["(fitted)"]] <- obj$where ret[["(response)"]] <- model.response(mf) ret[["(weights)"]] <- model.weights(mf) ret } fitted <- rpart_fitted() if (n == 1) { node <- partynode(1L) } else { is.leaf <- (ff$var == "<leaf>") vnames <- ff$var[!is.leaf] index <- cumsum(c(1, ff$ncompete + ff$nsurrogate + 1*(!is.leaf))) splitindex <- list() splitindex$primary <- numeric(n) splitindex$primary[!is.leaf] <- index[c(!is.leaf, FALSE)] splitindex$surrogate <- lapply(1L:n, function(i) { prim <- splitindex$primary[i] if (prim < 1 || ff[i, "nsurrogate"] == 0) return(NULL) else return(prim + ff[i, "ncompete"] + 1L:ff[i, "nsurrogate"]) }) rpart_kids <- function(i) { if (is.leaf[i]) return(NULL) else return(c(i + 1L, which((cumsum(!is.leaf[-(1L:i)]) + 1L) == cumsum(is.leaf[-(1L:i)]))[1L] + 1L + i)) } rpart_onesplit <- function(j) { if (j < 1) return(NULL) idj <- which(rownames(obj$split)[j] == names(mf)) if (abs(obj$split[j, "ncat"]) == 1) { ret <- partysplit(varid = idj, breaks = as.double(obj$split[j, "index"]), right = FALSE, index = if(obj$split[j, "ncat"] > 0) 2L:1L) } else { index <- obj$csplit[obj$split[j, "index"],] mfj <- mf[, rownames(obj$split)[j]] index <- index[1L:nlevels(mfj)] index[index == 2L] <- NA index[index == 3L] <- 2L if(inherits(mfj, "ordered")) { ret <- partysplit(varid = idj, breaks = which(diff(index) != 0L) + 1L, right = FALSE, index = unique(index)) } else { ret <- partysplit(varid = idj, index = as.integer(index)) } } ret } rpart_split <- function(i) rpart_onesplit(splitindex$primary[i]) rpart_surrogates <- function(i) lapply(splitindex$surrogate[[i]], rpart_onesplit) rpart_node <- function(i) { if (is.null(rpart_kids(i))) return(partynode(as.integer(i))) nd <- partynode(as.integer(i), split = rpart_split(i), kids = lapply(rpart_kids(i), rpart_node), surrogates = rpart_surrogates(i)) left <- nodeids(kids_node(nd)[[1L]], terminal = TRUE) right <- nodeids(kids_node(nd)[[2L]], terminal = TRUE) nd$split$prob <- c(0, 0) nl <- sum(fitted[["(fitted)"]] %in% left) nr <- sum(fitted[["(fitted)"]] %in% right) nd$split$prob <- if (nl > nr) c(1, 0) else c(0, 1) nd$split$prob <- as.double(nd$split$prob) return(nd) } node <- rpart_node(1) } rval <- party(node = node, data = if(data) mf else mf[0L,], fitted = fitted, terms = obj$terms, info = list(method = "rpart")) class(rval) <- c("constparty", class(rval)) return(rval) } model_frame_rpart <- function(formula, ...) { if(!is.null(formula$model)) return(formula$model) mf <- formula$call mf <- mf[c(1L, match(c("formula", "data", "subset", "na.action", "weights"), names(mf), 0L))] if (is.null(mf$na.action)) mf$na.action <- rpart::na.rpart mf[[1L]] <- quote(stats::model.frame) mf$formula <- formula$terms env <- if(!is.null(environment(formula$terms))) environment(formula$terms) else parent.frame() mf <- eval(mf, env) return(mf) } as.party.Weka_tree <- function(obj, data = TRUE, ...) { stopifnot(requireNamespace("RWeka")) j48 <- inherits(obj, "J48") mf <- model.frame(obj) mf_class <- sapply(mf, function(x) class(x)[1L]) mf_levels <- lapply(mf, levels) x <- rJava::.jcall(obj$classifier, "S", "graph") if(j48) { info <- NULL } else { info <- RWeka::parse_Weka_digraph(x, plainleaf = FALSE)$nodes[, 2L] info <- strsplit(info, " (", fixed = TRUE) info <- lapply(info, function(x) if(length(x) == 1L) x else c(x[1L], paste("(", x[-1L], sep = ""))) } x <- RWeka::parse_Weka_digraph(x, plainleaf = TRUE) nodes <- x$nodes edges <- x$edges is.leaf <- x$nodes[, "splitvar"] == "" weka_tree_kids <- function(i) { if (is.leaf[i]) return(NULL) else return(which(nodes[,"name"] %in% edges[nodes[i,"name"] == edges[,"from"], "to"])) } weka_tree_split <- function(i) { if(is.leaf[i]) return(NULL) var_id <- which(nodes[i, "splitvar"] == names(mf)) edges <- edges[nodes[i,"name"] == edges[,"from"], "label"] split <- Map(c, sub("^([[:punct:]]+).*$", "\\1", edges), sub("^([[:punct:]]+) *", "", edges)) if(mf_class[var_id] %in% c("ordered", "factor")) { stopifnot(all(sapply(split, head, 1) == "=")) stopifnot(all(sapply(split, tail, 1) %in% mf_levels[[var_id]])) split <- partysplit(varid = as.integer(var_id), index = match(mf_levels[[var_id]], sapply(split, tail, 1))) } else { breaks <- unique(as.numeric(sapply(split, tail, 1))) breaks <- if(mf_class[var_id] == "integer") as.integer(breaks) else as.double(breaks) stopifnot(length(breaks) == 1 && !is.na(breaks)) stopifnot(all(sapply(split, head, 1) %in% c("<=", ">"))) split <- partysplit(varid = as.integer(var_id), breaks = breaks, right = TRUE, index = if(split[[1L]][1L] == ">") 2L:1L) } return(split) } weka_tree_node <- function(i) { if(is.null(weka_tree_kids(i))) return(partynode(as.integer(i), info = info[[i]])) partynode(as.integer(i), split = weka_tree_split(i), kids = lapply(weka_tree_kids(i), weka_tree_node)) } node <- weka_tree_node(1) if(j48) { pty <- party( node = node, data = if(data) mf else mf[0L,], fitted = data.frame("(fitted)" = fitted_node(node, mf), "(response)" = model.response(mf), check.names = FALSE), terms = obj$terms, info = list(method = "J4.8")) class(pty) <- c("constparty", class(pty)) } else { pty <- party( node = node, data = mf[0L,], fitted = data.frame("(fitted)" = fitted_node(node, mf), check.names = FALSE), terms = obj$terms, info = list(method = class(obj)[1L])) } return(pty) }
context("getFeatureNames") test_that("getFeatureNames", { g = getFeatureNames(testscenario1) })
context("test-read_iamc.R") test_that("Read the file that meets the specification", { iamc_file_path = system.file("mipplot", "ar5_db_sample_data.csv", package = "mipplot", mustWork = TRUE) loaded_data <- mipplot_read_iamc(iamc_file_path, sep = ",", interactive = FALSE) expect_gt(nrow(loaded_data), 0) })
EdMethod = function(x) { k <- 1 Len<- length(x) temp <-vector("list",Len) for (i in x) { temp[[k]]<- i k <- k + 1 } temp1 <- Reduce("+",temp) output <- temp1 return(output) }
eqs <- sfcr_set( TX_s ~ TX_d, YD ~ W * N_s - TX_s, C_d ~ alpha1 * YD + alpha2 * H_h[-1], H_h ~ YD - C_d + H_h[-1], N_s ~ N_d, N_d ~ Y / W, C_s ~ C_d, G_s ~ G_d, Y ~ C_s + G_s, TX_d ~ theta * W * N_s, H_s ~ G_d - TX_d + H_s[-1] ) external <- sfcr_set(G_d ~ 20, W ~ 1, alpha1 ~ 0.6, alpha2 ~ 0.4, theta ~ 0.2) baseline <- sfcr_baseline(eqs, external, periods = 10) expanded <- sfcr_expand(external, "alpha2", c(0.1, 0.2)) sfcr_many_baseline(eqs, expanded, periods = 10)
Normcol<-function(m){ nrows<-nrow(m) ncols<-ncol(m) m1<-matrix(1,nrow=nrows,ncol = ncols) for (i in 1:nrows){ if (m[i,1]==-1){ for (j in 1:ncols){ m1[i,j]=-m[i,j] } } else { for (j in 1:ncols){ m1[i,j]=m[i,j] } } } return(m1) }
HyperEstimate <- function(estimate, nuisance, family) { if(family=="gaussian") { mu <- mean(estimate) vv <- nuisance^2 fit <- nlminb( start=mean(vv) , objective=nnnll,gradient=nnnll.g,hessian=nnnll.hess, lower=0, x=(estimate-mu), sigma2=vv ) tau2 <- fit$par hypers <- c(mu,tau2) } else if(family=="binomial") { ok <- (nuisance>0) tmp1 <- mean( (estimate/nuisance)[ok] ) tmp2 <- var( (estimate/nuisance)[ok] ) den <- tmp1*(1-tmp1)/tmp2 a0 <- den*tmp1 b0 <- den - a0 fit <- nlminb( start=c(a0,b0), objective=bbnll, x=estimate[ok], n=nuisance[ok] , lower=c(1,1) ) hypers <- c(fit$par[1],fit$par[2]) } else if(family=="poisson") { a0 <- 2 b0 <- a0/( sum(estimate)/sum(nuisance) ) fit <- nlminb( start=c(a0,b0), objective=pgnll, gradient=pgnll.g, x=estimate, eta=nuisance , lower=c(.1,.1) ) hypers <- c(fit$par[1],fit$par[2]) } else if(family=="Gamma") { a0 <- 4 b0 <- mean(nuisance)/((a0 - 1)*mean(estimate)) b0 <- 3 fit <- nlminb( start=c(a0,b0), objective=ggnll, gradient=ggnll.g, x = estimate, shapes = nuisance, lower=c(.2,.2)) hypers <- c(fit$par[1], fit$par[2]) } return(hypers) } bbnll <- function(shapes, x, n) { a <- shapes[1] b <- shapes[2] tt <- lgamma(a+b) - lgamma(a+b+n)+lgamma(a+x)+lgamma(b+n-x)- lgamma(a) - lgamma(b) return( -sum(tt) ) } bbnll.g <- function(shapes,x,n) { a <- shapes[1] b <- shapes[2] tta <- digamma(a+b) - digamma(a+b+n)+digamma(a+x) -digamma(a) ttb <- digamma(a+b) - digamma(a+b+n)+digamma(b+n-x)-digamma(b) return(c(tta,ttb)) } pgnll <- function(shapes, x, eta) { a <- shapes[1] b <- shapes[2] u <- b/(b+eta) tt <- a*log(u) + x*log(1-u) + lgamma(a+x) -lgamma(x+1) -lgamma(a) return( -sum(tt) ) } pgnll.g <- function(shapes, x, eta) { a <- shapes[1] b <- shapes[2] u <- b/(b+eta) dudb <- eta/((eta + b)^2) tta <- log(u) + digamma(a+x) - digamma(a) ttb <- (a/u - x/(1-u))*dudb return( c(-sum(tta),-sum(ttb)) ) } nnnll <- function( tau2, x, sigma2 ) { ss <- tau2 + sigma2 tmp <- sum( log(ss) ) + sum( (x^2)/ss ) nll <- (1/2)*tmp nll } nnnll.g <- function(tau2,x,sigma2) { ss <- tau2 + sigma2 ans <- sum(1/ss) - sum((x/ss)^2) return(ans/2) } nnnll.hess <- function(tau2,x,sigma2) { ss <- tau2 + sigma2 ans <- -sum(1/(ss^2)) + 2*sum((x^2)/(ss^3)) return(as.matrix(ans/2)) } ggnll <- function(pars, x, shapes) { a <- pars[1] b <- pars[2] n <- length(x) ans <- sum((a + shapes)*log(b + x)) + n*lgamma(a) - n*a*log(b) - sum(lgamma(shapes + a)) return(ans) } ggnll.g <- function(pars, x, shapes) { a <- pars[1] b <- pars[2] n <- length(x) a.partial <- sum(log(b + x)) + n*digamma(a) - n*log(b) - sum(digamma(shapes + a)) b.partial <- sum((a + shapes)/(b + x)) - (n*a)/b return(c(a.partial, b.partial)) }
lmf = function(ws, hmin = 2, shape = c("circular", "square")) { shape <- match.arg(shape) circ <- shape == "circular" ws <- lazyeval::uq(ws) hmin <- lazyeval::uq(hmin) f = function(las) { assert_is_valid_context(LIDRCONTEXTITD, "lmf") if (is.function(ws)) { n <- nrow(las@data) ws <- ws(las@data$Z) b <- las$Z < hmin ws[b] <- ws(hmin) if (!is.numeric(ws)) stop("The function 'ws' did not return a correct output. ", call. = FALSE) if (any(ws <= 0)) stop("The function 'ws' returned negative or null values.", call. = FALSE) if (anyNA(ws)) stop("The function 'ws' returned NA values.", call. = FALSE) if (length(ws) != n) stop("The function 'ws' did not return a correct output.", call. = FALSE) } else if (!is.numeric(ws)) { stop("'ws' must be a number or a function", call. = FALSE) } force_autoindex(las) <- LIDRGRIDPARTITION return(C_lmf(las, ws, hmin, circ, getThread())) } class(f) <- c(LIDRALGORITHMITD, LIDRALGORITHMOPENMP, LIDRALGORITHMPOINTCLOUDBASED) return(f) } manual = function(detected = NULL, radius = 0.5, color = "red", button = "middle", ...) { f = function(las) { assert_is_valid_context(LIDRCONTEXTITD, "manual") . <- X <- Y <- Z <- treeID <- NULL stopifnotlas(las) crs = sp::CRS() if (!interactive()) stop("R is not being used interactively", call. = FALSE) if (is.null(detected)) { apice <- data.table::data.table(X = numeric(0), Y = numeric(0), Z = numeric(0)) } else if (is(detected, "SpatialPointsDataFrame")) { crs <- detected@proj4string apice <- data.table::data.table(detected@coords) apice$Z <- detected@data[["Z"]] names(apice) <- c("X","Y","Z") } else { stop("Input is not of the correct type.") } minx <- min(las$X) miny <- min(las$Y) las@data <- las@data[, .(X, Y, Z)] las@data[, X := X - minx] las@data[, Y := Y - miny] apice[, X := X - minx] apice[, Y := Y - miny] plot.LAS(las, ..., clear_artifacts = FALSE) id = numeric(nrow(apice)) for (i in 1:nrow(apice)) id[i] = rgl::spheres3d(apice$X[i], apice$Y[i], apice$Z[i], radius = radius, color = color) apice$id <- id repeat { f <- rgl::select3d(button = button) i <- if (nrow(apice) > 0) f(apice) else FALSE if (sum(i) > 0) { ii <- which(i == TRUE) rgl::rgl.pop(id = apice[ii]$id) apice <- apice[-ii] } else { i <- f(las@data) if (sum(i) == 0) break; pts <- las@data[i, .(X,Y,Z)] apex <- unique(pts[pts$Z == max(pts$Z)])[1] apex$id <- as.numeric(rgl::spheres3d(apex$X, apex$Y, apex$Z, radius = radius, color = color)) apice <- rbind(apice, apex) } } rgl::rgl.close() apice[, treeID := 1:.N] apice[, X := X + minx] apice[, Y := Y + miny] output <- sp::SpatialPointsDataFrame(apice[, .(X,Y)], apice[, .(treeID, Z)], proj4string = crs) return(output) } class(f) <- c(LIDRALGORITHMITD, LIDRALGORITHMPOINTCLOUDBASED) return(f) }
Progress <- R6Class( 'Progress', public = list( initialize = function(session = getDefaultReactiveDomain(), min = 0, max = 1, style = getShinyOption("progress.style", default = "notification")) { if (is.null(session)) rlang::abort("Can only use Progress$new() inside a Shiny app") if (is.null(session$progressStack)) rlang::abort("`session` is not a ShinySession object.") private$session <- session private$id <- createUniqueId(8) private$min <- min private$max <- max private$value <- NULL private$style <- match.arg(style, choices = c("notification", "old")) private$closed <- FALSE session$sendProgress('open', list(id = private$id, style = private$style)) }, set = function(value = NULL, message = NULL, detail = NULL) { if (private$closed) { warning("Attempting to set progress, but progress already closed.") return() } if (is.null(value) || is.na(value)) value <- NULL if (!is.null(value)) { private$value <- value value <- min(1, max(0, (value - private$min) / (private$max - private$min))) } data <- dropNulls(list( id = private$id, message = message, detail = detail, value = value, style = private$style )) private$session$sendProgress('update', data) }, inc = function(amount = 0.1, message = NULL, detail = NULL) { if (is.null(private$value)) private$value <- private$min value <- min(private$value + amount, private$max) self$set(value, message, detail) }, getMin = function() private$min, getMax = function() private$max, getValue = function() private$value, close = function() { if (private$closed) { warning("Attempting to close progress, but progress already closed.") return() } private$session$sendProgress('close', list(id = private$id, style = private$style) ) private$closed <- TRUE } ), private = list( session = 'ShinySession', id = character(0), min = numeric(0), max = numeric(0), style = character(0), value = numeric(0), closed = logical(0) ) ) withProgress <- function(expr, min = 0, max = 1, value = min + (max - min) * 0.1, message = NULL, detail = NULL, style = getShinyOption("progress.style", default = "notification"), session = getDefaultReactiveDomain(), env = parent.frame(), quoted = FALSE) { if (!quoted) expr <- substitute(expr) if (is.null(session$progressStack)) stop("'session' is not a ShinySession object.") style <- match.arg(style, c("notification", "old")) p <- Progress$new(session, min = min, max = max, style = style) session$progressStack$push(p) on.exit({ session$progressStack$pop() p$close() }) p$set(value, message, detail) eval(expr, env) } setProgress <- function(value = NULL, message = NULL, detail = NULL, session = getDefaultReactiveDomain()) { if (is.null(session$progressStack)) stop("'session' is not a ShinySession object.") if (session$progressStack$size() == 0) { warning('setProgress was called outside of withProgress; ignoring') return() } session$progressStack$peek()$set(value, message, detail) invisible() } incProgress <- function(amount = 0.1, message = NULL, detail = NULL, session = getDefaultReactiveDomain()) { if (is.null(session$progressStack)) stop("'session' is not a ShinySession object.") if (session$progressStack$size() == 0) { warning('incProgress was called outside of withProgress; ignoring') return() } p <- session$progressStack$peek() p$inc(amount, message, detail) invisible() }
is_filetype <- function(x, ext) { tools::file_ext(x) %in% ext } is_emptyish <- function(x) { length(x) == 0 || !nzchar(x) } is_whse_object_name <- function(x) { if (inherits(x, "bcdc_record")) { return(FALSE) } grepl("^[0-9A-Z_]+\\.[0-9A-Z_]+$", x) } is_record <- function(x) { class(x) == "bcdc_record" }
point_in_polygon <- function(x, polygon) { point <- grDevices::xy.coords(x) polygon <- grDevices::xy.coords(polygon) n <- length(polygon$x) j <- n inside <- FALSE for (i in seq_len(n)) { if (((polygon$y[i] >= point$y) != (polygon$y[j] >= point$y)) && (point$x <= (polygon$x[j] - polygon$x[i])*(point$y - polygon$y[i]) / (polygon$y[j] - polygon$y[i]) + polygon$x[i])) { inside <- !inside } j <- i } inside }
hergm.permutation.wrapper <- function(number) { number_permutations <- factorial(number) permutations <- vector(length=number_permutations*number) for (i in 1:number) permutations[i] = i output <- .C("Permutations", as.integer(number), as.integer(number_permutations), permutations = as.integer(permutations), PACKAGE="hergm") permutations <- matrix(output$permutations, nrow = number_permutations, ncol = number, byrow = TRUE) permutations }
optimal.portfolio.expected.shortfall <- function(model) { n_var <- 1 + model$assets + 2*model$scenarios ix_b <- 1 ix_x <- 2 ix_loss <- ix_x + model$assets ix_z <- ix_loss + model$scenarios Objective <- list() Objective$linear <- rep(0, n_var) Objective$linear[ix_b] <- 1 for (s in 0:(model$scenarios-1)) { Objective$linear[ix_z+s] <- -model$scenario.probabilities[s+1]/model$alpha } Constraints <- list(n=n_var, A=NULL, b=NULL, Aeq=NULL, beq=NULL) Constraints <- linear.constraint.eq(Constraints, c((ix_x):(ix_x+model$assets-1)), model$sum.portfolio) if(!is.null(model$min.mean)) { Constraints <- linear.constraint.iq(Constraints, c((ix_x):(ix_x+model$assets-1)), -model$min.mean, -1*model$asset.means) } if(!is.null(model$fix.mean)) { Constraints <- linear.constraint.eq(Constraints, c((ix_x):(ix_x+model$assets-1)), model$fix.mean, model$asset.means) } for (s in 0:(model$scenarios-1)) { Constraints <- linear.constraint.eq(Constraints, c((ix_x:(ix_x+model$assets-1)), ix_loss+s), 0, c(as.vector(model$data[(s+1),]), -1)) } for (s in 0:(model$scenarios-1)) { Constraints <- linear.constraint.iq(Constraints, c(ix_b, ix_loss+s, ix_z+s), 0, c(1,-1,-1)) } Bounds <- list() M <- 1e9 Bounds$lower <- rep(-M, n_var) Bounds$upper <- rep(M, n_var) Bounds$lower[(ix_x):(ix_x+model$assets-1)] <- model$asset.bound.lower Bounds$upper[(ix_x):(ix_x+model$assets-1)] <- model$asset.bound.upper Bounds$lower[(ix_z):(ix_z+model$scenarios-1)] <- 0 solution <- linprog(-Objective$linear, Constraints$A, Constraints$b, Constraints$Aeq, Constraints$beq, Bounds$lower, Bounds$upper) portfolio <- list() portfolio$x <- solution$x[ix_x:(ix_x+model$assets-1)] portfolio$x <- round(portfolio$x, model$precision) model$portfolio <- portfolio return(model) }
welchManyOneTTest <- function(x, ...) UseMethod("welchManyOneTTest") welchManyOneTTest.default <- function(x, g, alternative = c("two.sided", "greater", "less"), p.adjust.method = p.adjust.methods, ...) { if (is.list(x)) { if (length(x) < 2L) stop("'x' must be a list with at least 2 elements") DNAME <- deparse(substitute(x)) x <- lapply(x, function(u) u <- u[complete.cases(u)]) k <- length(x) l <- sapply(x, "length") if (any(l == 0)) stop("all groups must contain data") g <- factor(rep(1:k, l)) if (is.null(x$alternative)){ alternative <- "two.sided" } else { alternative <- x$alternative } if(is.null(x$p.adjust.method)){ p.adjust.method <- "holm" } else { p.adjust.method <- x$p.adjust.method } x <- unlist(x) } else { if (length(x) != length(g)) stop("'x' and 'g' must have the same length") DNAME <- paste(deparse(substitute(x)), "and", deparse(substitute(g))) OK <- complete.cases(x, g) x <- x[OK] g <- g[OK] if (!all(is.finite(g))) stop("all group levels must be finite") g <- factor(g) k <- nlevels(g) if (k < 2) stop("all observations are in the same group") } alternative <- match.arg(alternative) p.adjust.method <- match.arg(p.adjust.method) kk <- k - 1 levNames <- levels(g) statistic <- numeric(kk) p.value <- numeric(kk) x0 <- x[g == levNames[1]] for (i in 1:kk) { out <- t.test( y = x0, x = x[g == levNames[i + 1]], alternative = alternative, var.equal = FALSE ) statistic[i] <- out$statistic p.value[i] <- out$p.value } p.value <- p.adjust(p.value, method = p.adjust.method) METHOD <- "Welch's t-test" STAT <- cbind(statistic) colnames(STAT) <- levNames[1] rownames(STAT) <- levNames[2:k] PVAL <- cbind(p.value) colnames(PVAL) <- colnames(STAT) rownames(PVAL) <- rownames(STAT) MODEL <- data.frame(x, g) DIST <- "t" ans <- list( method = METHOD, data.name = DNAME, p.value = PVAL, statistic = STAT, p.adjust.method = p.adjust.method, model = MODEL, dist = DIST, alternative = alternative ) class(ans) <- "PMCMR" ans } welchManyOneTTest.formula <- function(formula, data, subset, na.action, alternative = c("two.sided", "greater", "less"), p.adjust.method = p.adjust.methods,...) { mf <- match.call(expand.dots = FALSE) m <- match(c("formula", "data", "subset", "na.action"), names(mf), 0L) mf <- mf[c(1L, m)] mf[[1L]] <- quote(stats::model.frame) if (missing(formula) || (length(formula) != 3L)) stop("'formula' missing or incorrect") mf <- eval(mf, parent.frame()) if (length(mf) > 2L) stop("'formula' should be of the form response ~ group") DNAME <- paste(names(mf), collapse = " by ") names(mf) <- NULL alternative <- match.arg(alternative) p.adjust.method <- match.arg(p.adjust.method) y <- do.call("welchManyOneTTest", c(as.list(mf), alternative = alternative, p.adjust.method = p.adjust.method)) y$data.name <- DNAME y } welchManyOneTTest.aov <- function(x, alternative = c("two.sided", "greater", "less"), p.adjust.method = p.adjust.methods, ...) { model <- x$model DNAME <- paste(names(model), collapse = " by ") names(model) <- c("x", "g") alternative <- match.arg(alternative) p.adjust.method <- match.arg(p.adjust.method) parms <- c(as.list(model), list(alternative = alternative, p.adjust.method = p.adjust.method)) y <- do.call("welchManyOneTTest", parms) y$data.name <- DNAME y }
f <- function(N) { for (i in 1:N) { for (j in 1:N) { for (k in 1:N) { i + j + k } } } }
.inline.hook = function(x) { if (is.numeric(x)) x = round_digits(x) paste(as.character(x), collapse = ', ') } .out.hook = function(x, options) x .plot.hook = function(x, options) paste(x, collapse = '.') .default.hooks = list( source = .out.hook, output = .out.hook, warning = .out.hook, message = .out.hook, error = .out.hook, plot = .plot.hook, inline = .inline.hook, chunk = .out.hook, text = identity, evaluate.inline = function(code, envir = knit_global()) { v = withVisible(eval(parse_only(code), envir = envir)) if (v$visible) knit_print(v$value, inline = TRUE, options = opts_chunk$get()) }, evaluate = function(...) evaluate::evaluate(...), document = identity ) knit_hooks = new_defaults(.default.hooks) render_brew = function() NULL hook_suppress = function(x, options) { n = options$out.lines if (length(n) == 0 || !is.numeric(n) || length(n) > 2) return(x) x = split_lines(x) m = length(x) if (length(n) == 1) { if (m > abs(n)) { x = if (n >= 0) c(head(x, n), '....') else c('....', tail(x, -n)) } } else { if (m > sum(n)) x = c(head(x, n[1]), '....', tail(x, n[2])) } one_string(x) } opts_hooks = new_defaults(list())
library(plotly) barly1 <- function(x_data = NULL, data = NULL, b_name = NULL, b_orientation = 'v', b_text = NULL, bar_col = 'blue', bar_l_col = 'black', bar_l_wid = 1, bar_gap = 1, bar_opacity = 1, plot_width = NULL, plot_height = NULL, axis_range = FALSE, y_min, y_max, auto_size = TRUE, title = NA, x_title = NA, y_title = NA, x_showgrid = TRUE, y_showgrid = TRUE, ax_title_font_family = 'Arial, sans-serif', ax_title_font_size = 18, ax_title_font_color = 'black', ax_tick_font_family = 'Arial, sans-serif', ax_tick_font_size = 18, ax_tick_font_color = 'black', x_autotick = TRUE, x_ticks = 'outside', x_tick0 = NULL, x_dtick = NULL, x_ticklen = 5, x_tickwidth = 1, x_tickcolor = ' x_tickangle = 'auto', x_zeroline = FALSE, x_showline = TRUE, x_gridcolor = "rgb(204, 204, 204)", x_gridwidth = 1, x_zerolinecol = " x_zerolinewidth = 1, x_linecol = ' x_linewidth = 1, y_autotick = TRUE, y_ticks = 'outside', y_tick0 = NULL, y_dtick = NULL, y_ticklen = 5, y_tickwidth = 1, y_tickcolor = ' y_showticklab = TRUE, y_tickangle = 'auto', y_zeroline = FALSE, y_showline = TRUE, y_gridcolor = "rgb(204, 204, 204)", y_gridwidth = 1, y_zerolinecol = " y_zerolinewidth = 1, y_linecol = ' y_linewidth = 1, left_margin = 80, right_margin = 80, top_margin = 100, bottom_margin = 80, padding = 0, add_annotate = FALSE, x_annotate, y_annotate, text_annotate, annotate_xanchor = 'auto', show_arrow, arrow_head = 1, ax_annotate = 20, ay_annotate = -40, annotate_family = 'sans-serif', annotate_size = 14, annotate_col = 'red') { x <- data %>% select(x_data) %>% unlist() %>% levels() y <- data %>% select(x_data) %>% table() %>% as.vector() data <- data.frame(x, y) f1 <- list( family = ax_title_font_family, size = ax_title_font_size, color = ax_title_font_color ) f2 <- list( family = ax_tick_font_family, size = ax_tick_font_size, color = ax_tick_font_color ) xaxis <- list( title = x_title, showgrid = x_showgrid, autotick = x_autotick, ticks = x_ticks, tick0 = x_tick0, dtick = x_dtick, ticklen = x_ticklen, tickwidth = x_tickwidth, tickcolor = x_tickcolor, titlefont = f1, showticklabels = x_showticklab, tickangle = x_tickangle, tickfont = f2, zeroline = x_zeroline, showline = x_showline, gridcolor = x_gridcolor, gridwidth = x_gridwidth, zerolinecolor = x_zerolinecol, zerolinewidth = x_zerolinewidth, linecolor = x_linecol, linewidth = x_linewidth ) yaxis <- list( title = y_title, showgrid = y_showgrid, autotick = y_autotick, ticks = y_ticks, tick0 = y_tick0, dtick = y_dtick, ticklen = y_ticklen, tickwidth = y_tickwidth, tickcolor = y_tickcolor, titlefont = f1, showticklabels = y_showticklab, tickangle = y_tickangle, tickfont = f2, zeroline = y_zeroline, showline = y_showline, mirror = 'ticks', gridcolor = y_gridcolor, gridwidth = y_gridwidth, zerolinecolor = y_zerolinecol, zerolinewidth = y_zerolinewidth, linecolor = y_linecol, linewidth = y_linewidth ) m <- list( l = left_margin, r = right_margin, t = top_margin, b = bottom_margin, pad = padding ) if(add_annotate) { a <- list( x = x_annotate, y = y_annotate, text = text_annotate, xref = 'x', yref = 'y', xanchor = annotate_xanchor, showarrow = show_arrow, arrowhead = arrow_head, ax = ax_annotate, ay = ay_annotate, font = list( family = annotate_family, size = annotate_size, color = annotate_col ) ) } p <- plot_ly(data, x = ~x, y = ~y, type = "bar", name = b_name, orientation = b_orientation, text = b_text, marker = list(color = bar_col, opacity = bar_opacity, line = list( color = bar_l_col, width = bar_l_wid, gap = bar_gap )), width = plot_width, height = plot_height) %>% layout( title = title, xaxis = xaxis, yaxis = yaxis, autosize = auto_size, margin = m ) if(add_annotate) { p <- p %>% layout(annotations = a) } if(axis_range) { p <- p %>% layout( yaxis = list( range = list(y_min, y_max) ) ) } p }
otp_get_times <- function(otpcon, fromPlace, toPlace, mode = "CAR", date = format(Sys.Date(), "%m-%d-%Y"), time = format(Sys.time(), "%H:%M:%S"), maxWalkDistance = NULL, walkReluctance = 2, waitReluctance = 1, arriveBy = FALSE, transferPenalty = 0, minTransferTime = 0, maxItineraries = 1, detail = FALSE, includeLegs = FALSE, extra.params = list()) { call <- sys.call() call[[1]] <- as.name('list') params <- eval.parent(call) params <- params[names(params) %in% c("mode", "detail", "includeLegs", "maxItineraries", "extra.params") == FALSE] if (missing(otpcon)) { stop("otpcon argument is required") } else if (missing(fromPlace)) { stop("fromPlace argument is required") } else if (missing(toPlace)) { stop("toPlace argument is required") } args.coll <- checkmate::makeAssertCollection() checkmate::assert_list(extra.params) checkmate::assert_logical(detail, add = args.coll) checkmate::assert_integerish(maxItineraries, lower = 1, add = args.coll) checkmate::reportAssertions(args.coll) mode <- otp_check_mode(mode) do.call(otp_check_params, params) routerUrl <- paste0(make_url(otpcon)$router, "/plan") fromPlace <- paste(fromPlace, collapse = ",") toPlace <- paste(toPlace, collapse = ",") query <- list( fromPlace = fromPlace, toPlace = toPlace, mode = mode, date = date, time = time, maxWalkDistance = maxWalkDistance, walkReluctance = walkReluctance, waitReluctance = waitReluctance, arriveBy = arriveBy, transferPenalty = transferPenalty, minTransferTime = minTransferTime ) if (length(extra.params) > 0) { msg <- paste("Unknown parameters were passed to the OTP API without checks:", paste(sapply(names(extra.params), paste), collapse=", ")) warning(paste(msg), call. = FALSE) query <- append(query, extra.params) } req <- httr::GET(routerUrl, query = query) url <- urltools::url_decode(req$url) text <- httr::content(req, as = "text", encoding = "UTF-8") asjson <- jsonlite::fromJSON(text, flatten = TRUE) if (!is.null(asjson$error$id)) { response <- list( "errorId" = asjson$error$id, "errorMessage" = ifelse( otpcon$version == 1, asjson$error$msg, asjson$error$message ), "query" = url ) return (response) } else { error.id <- "OK" } if (length(asjson$plan$itineraries) == 0) { response <- list( "errorId" = -9999, "errorMessage" = "No itinerary returned. If using OTPv2 the maxWalkDistance parameter (default 800m) might be too restrictive. It is applied by OTPv2 to BICYCLE and CAR modes in addition to WALK", "query" = url ) return (response) } if (detail == TRUE) { num_itin <- pmin(maxItineraries, nrow(asjson$plan[["itineraries"]])) df <- asjson$plan$itineraries[c(1:num_itin),] df$start <- otp_from_epoch(df$startTime, otpcon$tz) df$end <- otp_from_epoch(df$endTime, otpcon$tz) df$timeZone <- attributes(df$start)$tzone[1] if (isTRUE(includeLegs)) { legs <- rrapply::rrapply( df$legs, f = function(x) janitor::clean_names(x, case = "lower_camel"), classes = "data.frame" ) legs <- rrapply::rrapply( legs, condition = function(x, .xname) .xname %in% c("startTime", "endTime", "fromDeparture", "fromArrival"), f = function(x) otp_from_epoch(x, otpcon$tz) ) legs <- rrapply::rrapply( legs, f = function(x) if (nrow(x) > 1) dplyr::mutate(x, departureWait = round(abs((as.numeric( .data$fromArrival - .data$fromDeparture )) / 60 ), 2)) else dplyr::mutate(x, departureWait = 0) , classes = "data.frame" ) legs <- rrapply::rrapply( legs, condition = function(x, .xname) .xname == "departureWait", f = function(x) replace(x, is.na(x), 0) ) legs <- rrapply::rrapply( legs, condition = function(x, .xname) .xname == "duration", f = function(x) round(x / 60, 2) ) legs <- rrapply::rrapply( legs, f = function(x) dplyr::mutate(x, timeZone = attributes(x$startTime)$tzone[1]), classes = "data.frame" ) leg_columns <- c( 'startTime', 'endTime', 'timeZone', 'mode', 'departureWait', 'duration', 'distance', 'routeType', 'routeId', 'routeShortName', 'routeLongName', 'headsign', 'agencyName', 'agencyUrl', 'agencyId', 'fromName', 'fromLon', 'fromLat', 'fromStopId', 'fromStopCode', 'toName', 'toLon', 'toLat', 'toStopId', 'toStopCode' ) legs <- rrapply::rrapply( legs, f = function(x) dplyr::select(x, which(colnames(x) %in% leg_columns)), classes = "data.frame" ) legs <- rrapply::rrapply( legs, f = function(x) dplyr::relocate(x, any_of(leg_columns)), classes = "data.frame" ) } ret.df <- dplyr::select( df, c( 'start', 'end', 'timeZone', 'duration', 'walkTime', 'transitTime', 'waitingTime', 'transfers' ) ) if (isTRUE(includeLegs)) { ret.df$legs <- legs } ret.df[, 4:7] <- round(ret.df[, 4:7] / 60, digits = 2) if (mode == "CAR") { names(ret.df)[names(ret.df) == 'walkTime'] <- 'driveTime' } else if (mode == "BICYCLE") { names(ret.df)[names(ret.df) == 'walkTime'] <- 'cycleTime' } response <- list("errorId" = error.id, "itineraries" = ret.df, "query" = url) return (response) } else { response <- list( "errorId" = error.id, "duration" = round(asjson$plan$itineraries[1, "duration"] / 60, digits = 2), "query" = url ) return (response) } }
"draw.bplot" <- function (temp, width, xpos, outlier = TRUE, style = "tukey") { if (temp$N < 1) return() if (style == "quantile") { temp <- temp[!is.na(temp)] quant <- c(0.05, 0.25, 0.5, 0.75, 0.95) bb <- quantile(temp, quant) mid <- xpos low <- mid - width * 0.5 high <- mid + width * 0.5 if (length(temp) > 5) { y <- c(bb[1], bb[1], NA, bb[1], bb[2], NA, bb[2], bb[2], bb[4]) x <- c(high, low, NA, mid, mid, NA, high, low, low) y <- c(y, bb[4], bb[2], bb[3], bb[3], NA, bb[4], bb[5], bb[5], bb[5]) x <- c(x, high, high, high, low, NA, mid, mid, high, low) lines(x, y) } if (length(temp) > 5) { outs <- temp[(temp < bb[1]) | (temp > bb[5])] } else outs <- temp olen <- length(outs) if ((olen > 0) & outlier) points(rep(mid, olen), outs) } if (style == "tukey") { temp <- temp[!is.na(temp)] quant <- c(0.05, 0.25, 0.5, 0.75, 0.95) bb <- quantile(temp, quant) iqr <- bb[4] - bb[2] mid <- xpos low <- mid - width * 0.5 high <- mid + width * 0.5 bb[1] <- min(temp[temp >= bb[2] - 1.5 * iqr]) bb[5] <- max(temp[temp <= bb[4] + 1.5 * iqr]) if (length(temp) > 5) { y <- c(bb[1], bb[1], NA, bb[1], bb[2], NA, bb[2], bb[2], bb[4]) x <- c(high, low, NA, mid, mid, NA, high, low, low) y <- c(y, bb[4], bb[2], bb[3], bb[3], NA, bb[4], bb[5], bb[5], bb[5]) x <- c(x, high, high, high, low, NA, mid, mid, high, low) lines(x, y) } if (length(temp) > 5) { outs <- temp[(temp < bb[2] - 3 * iqr) | (temp > bb[4] + 3 * iqr)] } else outs <- temp olen <- length(outs) if ((olen > 0) & outlier) points(rep(mid, olen), outs) } }
check_several <- function(pattern,dmz,ppm=TRUE){ if(length(pattern[[1]]) < 2 || !all(colnames(pattern[[1]])[1:2] == c("m/z","abundance"))) stop("WARNING: pattern has invalid entries\n") if(ppm==TRUE & dmz < 0) stop("\n WARNING: ppm=TRUE -> dmz must be >0\n") if(ppm!=TRUE & ppm!=FALSE) stop("WARNING: ppm TRUE or FALSE") if(length(pattern) < 2) stop("WARNING: nothing to compare") getit1<-c(); getit2<-c(); getit3<-c(); for(i in 1:length(pattern)){ getit1<-c(getit1,rep(i,length(pattern[[i]][,1]))) getit2<-c(getit2,pattern[[i]][,1]); getit3<-c(getit3,seq(1,length(pattern[[i]][,1]),1)); } getit1<-getit1[order(getit2)]; getit3<-getit3[order(getit2)]; getit2<-getit2[order(getit2)]; get1<-rep("",length(pattern)) get2<-rep("",length(pattern)) get3<-rep("",length(pattern)) for(i in 2:length(getit1)){ if(ppm==FALSE){ if(getit1[i-1]!=getit1[i]){ if((getit2[i-1]+dmz)>=getit2[i]){ get1[getit1[i]]<-"TRUE"; get1[getit1[i-1]]<-"TRUE"; get2[getit1[i]]<-paste(get2[getit1[i]],getit1[i-1],"/",sep="") get2[getit1[i-1]]<-paste(get2[getit1[i-1]],getit1[i],"/",sep="") get3[getit1[i]]<-paste(get3[getit1[i]],getit3[i-1],"/",sep="") get3[getit1[i-1]]<-paste(get3[getit1[i-1]],getit3[i],"/",sep="") } } }else{ if(getit1[i=1]!=getit1[i]){ if((getit2[i-1]+(getit2[i-1]*dmz/1e6))>=getit2[i]){ get1[getit1[i]]<-"TRUE"; get1[getit1[i-1]]<-"TRUE"; get2[getit1[i]]<-paste(get2[getit1[i]],getit1[i-1],"/",sep="") get2[getit1[i-1]]<-paste(get2[getit1[i-1]],getit1[i],"/",sep="") get3[getit1[i]]<-paste(get3[getit1[i]],getit3[i-1],"/",sep="") get3[getit1[i-1]]<-paste(get3[getit1[i-1]],getit3[i],"/",sep="") } } } } if(any(get1!="")){cat("\n Overlaps detected!\n\n")} checked<-data.frame(names(pattern),get1,get2,get3) names(checked)<-c("compound","warning","to?","peak return(checked) }
require(mgcv);set.seed(9) dat <- gamSim(1,n=2000,dist="poisson",scale=.1) k <- 12;bs <- "cr";ctrl <- list(nthreads=2) system.time(b1<-gam(y~s(x0,bs=bs)+s(x1,bs=bs)+s(x2,bs=bs,k=k) ,family=poisson,data=dat,method="REML"))[3] system.time(b2<-gam(y~s(x0,bs=bs)+s(x1,bs=bs)+s(x2,bs=bs,k=k), family=poisson,data=dat,method="REML",control=ctrl))[3] k <- 13;set.seed(9) dat <- gamSim(1,n=6000,dist="poisson",scale=.1) require(parallel) nc <- 2 if (detectCores()>1) { cl <- makeCluster(nc) } else cl <- NULL system.time(b3 <- bam(y ~ s(x0,bs=bs,k=7)+s(x1,bs=bs,k=7)+s(x2,bs=bs,k=k) ,data=dat,family=poisson(),chunk.size=5000,cluster=cl)) fv <- predict(b3,cluster=cl) if (!is.null(cl)) stopCluster(cl) b3 system.time(b4 <- bam(y ~ s(x0,bs=bs,k=7)+s(x1,bs=bs,k=7)+s(x2,bs=bs,k=k) ,data=dat,family=poisson(),discrete=TRUE,nthreads=2))
summary.Jointlcmm <- function(object,...) { x <- object if (!inherits(x, "Jointlcmm")) stop("use only with \"Jointlcmm\" objects") cat("Joint latent class model for quantitative outcome and competing risks", "\n") cat(" fitted by maximum likelihood method", "\n") cl <- x$call cl$B <- NULL if(is.data.frame(cl$data)) { cl$data <- NULL x$call$data <- NULL } cat(" \n") dput(cl) cat(" \n") posfix <- eval(cl$posfix) cat("Statistical Model:", "\n") cat(paste(" Dataset:", as.character(as.expression(x$call$data))),"\n") cat(paste(" Number of subjects:", x$ns),"\n") cat(paste(" Number of observations:", x$N[9]),"\n") cat(paste(" Number of latent classes:", x$ng), "\n") cat(paste(" Number of parameters:", length(x$best))," \n") if(length(posfix)) cat(paste(" Number of estimated parameters:", length(x$best)-length(posfix))," \n") nbevt <- length(x$hazard[[1]]) nprisq <- rep(NA,nbevt) nrisq <- rep(NA,nbevt) typrisq <- x$hazard[[1]] hazardtype <- x$hazard[[2]] nz <- x$hazard[[4]] for(ke in 1:nbevt) { if(typrisq[ke]==1) nprisq[ke] <- nz[ke]-1 if(typrisq[ke]==2) nprisq[ke] <- 2 if(typrisq[ke]==3) nprisq[ke] <- nz[ke]+2 if(hazardtype[ke]=="Common") nrisq[ke] <- nprisq[ke] if(hazardtype[ke]=="PH") nrisq[ke] <- nprisq[ke]+x$ng-1 if(hazardtype[ke]=="Specific") nrisq[ke] <- nprisq[ke]*x$ng cat(paste(" Event ",ke,": \n",sep="")) cat(paste(" Number of events: ", x$N[9+ke],"\n",sep="")) if(x$ng>1) { if (hazardtype[ke]=="Specific") cat(" Class-specific hazards and \n") if (hazardtype[ke]=="PH") cat(" Proportional hazards over latent classes and \n") if (hazardtype[ke]=="Common") cat(" Common hazards over classes and \n") } if (typrisq[ke]==2) { cat(" Weibull baseline risk function \n") } if (typrisq[ke]==1) { cat(" Piecewise constant baseline risk function with nodes \n") cat(" ",x$hazard[[3]][1:nz[ke],ke]," \n") } if (typrisq[ke]==3) { cat(" M-splines constant baseline risk function with nodes \n") cat(" ",x$hazard[[3]][1:nz[ke],ke]," \n") } } ntrtot <- x$N[8] numSPL <- 0 if(x$linktype!=-1) { cat(paste(" Link function for ",x$Names$Yname,": ",sep="")) if (x$linktype==0) { cat("Linear \n") } if (x$linktype==1) { cat("Standardised Beta CdF \n") } if (x$linktype==2) { cat("Quadratic I-splines with nodes ", x$linknodes ,"\n") } } cat(" \n") cat("Iteration process:", "\n") if(x$conv==1) cat(" Convergence criteria satisfied") if(x$conv==2) cat(" Maximum number of iteration reached without convergence") if(x$conv==3) cat(" Convergence with restrained Hessian matrix") if(x$conv==4|x$conv==12) { cat(" The program stopped abnormally. No results can be displayed.\n") } else { cat(" \n") cat(" Number of iterations: ", x$niter, "\n") cat(" Convergence criteria: parameters=", signif(x$gconv[1],2), "\n") cat(" : likelihood=", signif(x$gconv[2],2), "\n") cat(" : second derivatives=", signif(x$gconv[3],2), "\n") cat(" \n") cat("Goodness-of-fit statistics:", "\n") cat(paste(" maximum log-likelihood:", round(x$loglik,2))," \n") cat(paste(" AIC:", round(x$AIC,2))," \n") cat(paste(" BIC:", round(x$BIC,2))," \n") if(!is.na(x$scoretest[1])&(length(x$hazard[[1]])==1)){ cat(paste(" Score test statistic for CI assumption: ", round(x$scoretest[1],3)," (p-value=",round((1-pchisq(x$scoretest[1],sum(x$idea))),4),")" ,sep="")) } if(!is.na(x$scoretest[1])&(length(x$hazard[[1]])>1)){ cat(paste(" Score test statistic for global CI assumption: ", round(x$scoretest[1],3)," (p-value=",round((1-pchisq(x$scoretest[1],sum(x$idea))),4),")" ,sep=""),"\n") } if(!is.na(x$scoretest[1])&(length(x$hazard[[1]])>1)){ cat(" Score test statistic for event-specific CI assumption: \n") for (ke in 1:length(x$hazard[[1]])){ if(!is.na(x$scoretest[1+ke])){ cat(paste(" event ",ke,":", round(x$scoretest[1+ke],3)," (p-value=",round((1-pchisq(x$scoretest[1+ke],sum(x$idea))),4),")" ,sep=""),"\n") } else{ cat(paste(" event ",ke,": problem in the computation", "\n")) } } } cat(" \n") cat(" \n") cat("Maximum Likelihood Estimates:", "\n") cat(" \n") nprob <- x$N[1] nrisqtot <- x$N[2] nvarxevt <- x$N[3] nef <- x$N[4] nvc <- x$N[5] nw <- x$N[6] ncor <- x$N[7] ntrtot <- x$N[8] NPM <- length(x$best) se <- rep(NA,NPM) if (x$conv==1 | x$conv==3) { id <- 1:NPM indice <- id*(id+1)/2 se <-sqrt(x$V[indice]) wald <- x$best/se pwald <- 1-pchisq(wald**2,1) coef <- x$best } else { se <- NA wald <- NA pwald <- NA coef <- x$best sech <- rep(NA,length(coef)) waldch <- rep(NA,length(coef)) pwaldch <- rep(NA,length(coef)) } if(nw>0) coef[nprob+nrisqtot+nvarxevt+nef+nvc+1:nw] <- abs(coef[nprob+nrisqtot+nvarxevt+nef+nvc+1:nw]) if(ncor>0) coef[nprob+nrisqtot+nvarxevt+nef+nvc+nw+ncor] <- abs(coef[nprob+nrisqtot+nvarxevt+nef+nvc+nw+ncor]) if(ntrtot==1) coef[nprob+nrisqtot+nvarxevt+nef+nvc+nw+ncor+1] <- abs(coef[nprob+nrisqtot+nvarxevt+nef+nvc+nw+ncor+1]) if(x$conv!=2) { coefch <- format(as.numeric(sprintf("%.5f",coef)),nsmall=5,scientific=FALSE) sech <- format(as.numeric(sprintf("%.5f",se)),nsmall=5,scientific=FALSE) waldch <- format(as.numeric(sprintf("%.3f",wald)),nsmall=3,scientific=FALSE) pwaldch <- format(as.numeric(sprintf("%.5f",pwald)),nsmall=5,scientific=FALSE) } else { coefch <- format(as.numeric(sprintf("%.5f",coef)),nsmall=5,scientific=FALSE) } if(length(posfix)) { coefch[posfix] <- paste(coefch[posfix],"*",sep="") sech[posfix] <- "" waldch[posfix] <- "" pwaldch[posfix] <- "" } maxchar <- function(x) { xx <- na.omit(x) if(length(xx)) { res <- max(nchar(xx)) } else { res <- 2 } return(res) } if(nprob>0) { cat("Fixed effects in the class-membership model:\n" ) cat("(the class of reference is the last class) \n") tmp <- cbind(coefch[1:nprob],sech[1:nprob],waldch[1:nprob],pwaldch[1:nprob]) maxch <- apply(tmp,2,maxchar) if(any(c(1:nprob) %in% posfix)) maxch[1] <- maxch[1]-1 dimnames(tmp) <- list(names(coef)[1:nprob], c(paste(paste(rep(" ",max(maxch[1]-4,0)),collapse=""),"coef",sep=""), paste(paste(rep(" ",max(maxch[2]-2,0)),collapse=""),"Se",sep=""), paste(paste(rep(" ",max(maxch[3]-4,0)),collapse=""),"Wald",sep=""), paste(paste(rep(" ",max(maxch[4]-7,0)),collapse=""),"p-value",sep=""))) cat("\n") print(tmp,quote=FALSE,na.print="") cat("\n") } cat("Parameters in the proportional hazard model:\n" ) tmp <- cbind(coefch[nprob+1:(nrisqtot+nvarxevt)], sech[nprob+1:(nrisqtot+nvarxevt)], waldch[nprob+1:(nrisqtot+nvarxevt)], pwaldch[nprob+1:(nrisqtot+nvarxevt)]) maxch <- apply(tmp,2,maxchar) if(any(c(nprob+1:(nrisqtot+nvarxevt)) %in% posfix)) maxch[1] <- maxch[1]-1 dimnames(tmp) <- list(names(coef)[nprob+1:(nrisqtot+nvarxevt)], c(paste(paste(rep(" ",max(maxch[1]-4,0)),collapse=""),"coef",sep=""), paste(paste(rep(" ",max(maxch[2]-2,0)),collapse=""),"Se",sep=""), paste(paste(rep(" ",max(maxch[3]-4,0)),collapse=""),"Wald",sep=""), paste(paste(rep(" ",max(maxch[4]-7,0)),collapse=""),"p-value",sep=""))) cat("\n") print(tmp,quote=FALSE,na.print="") cat("\n") cat("Fixed effects in the longitudinal model:\n" ) if(x$linktype!=-1) { tmp <- matrix(c(paste(c(rep(" ",maxchar(coefch[nprob+nrisqtot+nvarxevt+1:nef])-ifelse(any(c(nprob+nrisqtot+nvarxevt+1:nef) %in% posfix),2,1)),0),collapse=""),"","",""),nrow=1,ncol=4) tTable <- matrix(c(0,NA,NA,NA),nrow=1,ncol=4) } if(x$linktype==-1) { tmp <- NULL tTable <-NULL } if (nef>0) { tmp2 <- cbind(coefch[nprob+nrisqtot+nvarxevt+1:nef], sech[nprob+nrisqtot+nvarxevt+1:nef], waldch[nprob+nrisqtot+nvarxevt+1:nef], pwaldch[nprob+nrisqtot+nvarxevt+1:nef]) tmp <- rbind(tmp,tmp2) tTable <- rbind(tTable,cbind(round(coef[nprob+nrisqtot+nvarxevt+1:nef],5), round(se[nprob+nrisqtot+nvarxevt+1:nef],5), round(wald[nprob+nrisqtot+nvarxevt+1:nef],3), round(pwald[nprob+nrisqtot+nvarxevt+1:nef],5))) } interc <- "intercept" if (x$ng>1) { interc <- paste(interc,"class1") } if(x$linktype!=-1) interc <- paste(interc,"(not estimated)") if(x$linktype==-1) interc <- NULL if(nef>0) { maxch <- apply(tmp,2,maxchar) if(any(c(nprob+nrisqtot+nvarxevt+1:nef) %in% posfix)) maxch[1] <- maxch[1]-1 dimnames(tmp) <- list(c(interc,names(coef)[nprob+nrisqtot+nvarxevt+1:nef]), c(paste(paste(rep(" ",max(maxch[1]-4,0)),collapse=""),"coef",sep=""), paste(paste(rep(" ",max(maxch[2]-2,0)),collapse=""),"Se",sep=""), paste(paste(rep(" ",max(maxch[3]-4,0)),collapse=""),"Wald",sep=""), paste(paste(rep(" ",max(maxch[4]-7,0)),collapse=""),"p-value",sep=""))) } else { dimnames(tmp) <- list(interc, c("coef", "Se", "Wald", "p-value")) } rownames(tTable) <- rownames(tmp) colnames(tTable) <- c("coef", "Se", "Wald", "p-value") cat("\n") print(tmp,quote=FALSE,na.print="") cat("\n") if(nvc>0) { cat("\n") cat("Variance-covariance matrix of the random-effects:\n" ) if(x$idiag==1) { Mat.cov <- diag(coef[nprob+nrisqtot+nvarxevt+nef+1:nvc]) Mat.cov[lower.tri(Mat.cov)] <- 0 Mat.cov[upper.tri(Mat.cov)] <- NA if(nvc==1) Mat.cov <- matrix(coef[nprob+nrisqtot+nvarxevt+nef+1:nvc],1,1) } if(x$idiag==0) { Mat.cov<-matrix(0,ncol=sum(x$idea),nrow=sum(x$idea)) Mat.cov[upper.tri(Mat.cov,diag=TRUE)] <- coef[nprob+nrisqtot+nvarxevt+nef+1:nvc] Mat.cov <-t(Mat.cov) Mat.cov[upper.tri(Mat.cov)] <- NA } colnames(Mat.cov) <-x$Names$Xnames[x$idea==1] rownames(Mat.cov) <-x$Names$Xnames[x$idea==1] if(any(posfix %in% c(nprob+nrisqtot+nvarxevt+nef+1:nvc))) { Mat.cov <- apply(Mat.cov,2,format,digits=5,nsmall=5) Mat.cov[upper.tri(Mat.cov)] <- "" pf <- sort(intersect(c(nprob+nrisqtot+nvarxevt+nef+1:nvc),posfix)) p <- matrix(0,sum(x$idea),sum(x$idea)) if(x$idiag==FALSE) p[upper.tri(p,diag=TRUE)] <- c(nprob+nrisqtot+nvarxevt+nef+1:nvc) if(x$idiag==TRUE & nvc>1) diag(p) <- c(nprob+nrisqtot+nvarxevt+nef+1:nvc) if(x$idiag==TRUE & nvc==1) p <- matrix(c(nprob+nrisqtot+nvarxevt+nef+1),1,1) Mat.cov[which(t(p) %in% pf)] <- paste(Mat.cov[which(t(p) %in% pf)],"*",sep="") print(Mat.cov,quote=FALSE) } else { prmatrix(round(Mat.cov,5),na.print="") } cat("\n") } std <- NULL nom <- NULL if(nw>=1) { nom <- paste("Proportional coefficient class",c(1:(x$ng-1)),sep="") std <-cbind(coefch[nprob+nrisqtot+nvarxevt+nef+nvc+1:nw], sech[nprob+nrisqtot+nvarxevt+nef+nvc+1:nw]) } if(ncor==2) { nom <- c(nom,"AR correlation parameter:","AR standard error:") std <-rbind(std,c(coefch[nprob+nrisqtot+nvarxevt+nef+nvc+nw+1], sech[nprob+nrisqtot+nvarxevt+nef+nvc+nw+1]), c(coefch[nprob+nrisqtot+nvarxevt+nef+nvc+nw+2], sech[nprob+nrisqtot+nvarxevt+nef+nvc+nw+2])) } if(ncor==1) { nom <- c(nom,"BM standard error:") std <-rbind(std,c(coefch[nprob+nrisqtot+nvarxevt+nef+nvc+nw+1], sech[nprob+nrisqtot+nvarxevt+nef+nvc+nw+1])) } if (!is.null(std)) { rownames(std) <- nom maxch <- apply(std,2,maxchar) if(any(c(nprob+nrisqtot+nvarxevt+nef+nvc+1:(nw+ncor)) %in% posfix)) maxch[1] <- maxch[1]-1 colnames(std) <- c(paste(paste(rep(" ",max(maxch[1]-4,0)),collapse=""),"coef",sep=""), paste(paste(rep(" ",max(maxch[2]-2,0)),collapse=""),"Se",sep="")) print(std,quote=FALSE,na.print="") cat("\n") } if(x$linktype==-1) { tmp <- cbind(coefch[NPM],sech[NPM]) rownames(tmp) <- "Residual standard error" maxch <- apply(tmp,2,maxchar) if(c(NPM) %in% posfix) maxch[1] <- maxch[1]-1 colnames(tmp) <- c(paste(paste(rep(" ",max(maxch[1]-4,0)),collapse=""),"coef",sep=""), paste(paste(rep(" ",max(maxch[2]-2,0)),collapse=""),"Se",sep="")) print(tmp,quote=FALSE,na.print="") cat("\n") } else { cat("Residual standard error (not estimated) = 1\n") cat("\n") cat("Parameters of the link function:\n" ) tmp <- cbind(coefch[(nprob+nrisqtot+nvarxevt+nef+nvc+nw+ncor+1):NPM], sech[(nprob+nrisqtot+nvarxevt+nef+nvc+nw+ncor+1):NPM], waldch[(nprob+nrisqtot+nvarxevt+nef+nvc+nw+ncor+1):NPM], pwaldch[(nprob+nrisqtot+nvarxevt+nef+nvc+nw+ncor+1):NPM]) rownames(tmp) <- names(x$best[(nprob+nrisqtot+nvarxevt+nef+nvc+nw+ncor+1):NPM]) maxch <- apply(tmp,2, maxchar) if(any(c((nprob+nrisqtot+nvarxevt+nef+nvc+nw+ncor+1):NPM) %in% posfix)) maxch[1] <- maxch[1]-1 colnames(tmp) <- c(paste(paste(rep(" ",max(maxch[1]-4,0)),collapse=""),"coef",sep=""), paste(paste(rep(" ",max(maxch[2]-2,0)),collapse=""),"Se",sep=""), paste(paste(rep(" ",max(maxch[3]-4,0)),collapse=""),"Wald",sep=""), paste(paste(rep(" ",max(maxch[4]-7,0)),collapse=""),"p-value",sep="")) cat("\n") print(tmp,quote=FALSE,na.print="") cat("\n") } if(length(posfix)) { cat(" * coefficient fixed by the user \n \n") } return(invisible(tTable)) } }
exp_dec <- function(thermal_units, chill_days, b, m) { y_pred <- b * exp(m * chill_days) if(thermal_units >= y_pred) { return(1) } else { return(0) } }
google_scholar <- function(search_terms) { message("Opening Google Scholar search for \"", search_terms, "\" in browser") utils::browseURL(paste0("https://scholar.google.com/scholar?q=", URLencode(search_terms))) }
siaraddcross <- function(x = NULL, ex = NULL, y = NULL, ey = NULL, clr = "grey50", upch = 21) { points(x, y, col = clr, pch = upch) if (!is.null(ex)) { lines(c(x - ex, x + ex), c(y, y), col = clr) } if (!is.null(ey)) { lines(c(x, x), c(y - ey, y + ey), col = clr) } }
data("survdata") test_that("input checking works", { datatrunc <- survdata datatrunc[datatrunc$time > 360, "event"] <- 0 expect_error(with(datatrunc, cpsurv(time, event, intwd = 20, cpmax = 360)), "No events with 'time' > 'cpmax'") wrongevent <- survdata$event wrongevent[5] <- 0.5 expect_error(cpsurv(survdata$time, wrongevent, intwd = 20, cpmax = 360), "Argument 'event' has to be binary") expect_error(cpsurv(survdata$time, survdata$event[-1], intwd = 20, cpmax = 360), "Vectors 'time' and 'event' must be of equal length.") expect_error(with(survdata, cpsurv(time, event, intwd = "nonsense", cpmax = 360)), "Argument 'intwd' is not a single numeric value") expect_error(with(survdata, cpsurv(time, event, conf.level = 2, cpmax = 360)), "Value for argument 'conf.level' too high") })
NULL Conv1D <- function(filters, kernel_size, strides = 1, padding = 'valid', dilation_rate = 1, activation = NULL, use_bias = TRUE, kernel_initializer = 'glorot_uniform', bias_initializer = 'zeros', kernel_regularizer = NULL, bias_regularizer = NULL, activity_regularizer = NULL, kernel_constraint = NULL, bias_constraint = NULL, input_shape = NULL) { if (is.null(input_shape)) { res <- modules$keras.layers.convolutional$Conv1D( filters = int32(filters), kernel_size = int32(kernel_size), strides = int32(strides), padding = padding, dilation_rate = int32(dilation_rate), activation = activation, use_bias = use_bias, kernel_initializer = kernel_initializer, bias_initializer = bias_initializer, kernel_regularizer = kernel_regularizer, bias_regularizer = bias_regularizer, activity_regularizer = activity_regularizer, kernel_constraint = kernel_constraint, bias_constraint = bias_constraint) } else { input_shape <- as.list(input_shape) input_shape <- modules$builtin$tuple(int32(input_shape)) res <- modules$keras.layers.convolutional$Conv1D( filters = int32(filters), kernel_size = int32(kernel_size), strides = int32(strides), padding = padding, dilation_rate = int32(dilation_rate), activation = activation, use_bias = use_bias, kernel_initializer = kernel_initializer, bias_initializer = bias_initializer, kernel_regularizer = kernel_regularizer, bias_regularizer = bias_regularizer, activity_regularizer = activity_regularizer, kernel_constraint = kernel_constraint, bias_constraint = bias_constraint, input_shape = input_shape) } return(res) } Conv2D <- function(filters, kernel_size, strides = c(1, 1), padding = 'valid', data_format = NULL, dilation_rate = c(1, 1), activation = NULL, use_bias = TRUE, kernel_initializer = 'glorot_uniform', bias_initializer = 'zeros', kernel_regularizer = NULL, bias_regularizer = NULL, activity_regularizer = NULL, kernel_constraint = NULL, bias_constraint = NULL, input_shape = NULL) { if (is.null(input_shape)) { res <- modules$keras.layers.convolutional$Conv2D( filters = int32(filters), kernel_size = int32(kernel_size), strides = int32(strides), padding = padding, data_format = data_format, dilation_rate = int32(dilation_rate), activation = activation, use_bias = use_bias, kernel_initializer = kernel_initializer, bias_initializer = bias_initializer, kernel_regularizer = kernel_regularizer, bias_regularizer = bias_regularizer, activity_regularizer = activity_regularizer, kernel_constraint = kernel_constraint, bias_constraint = bias_constraint) } else { input_shape <- as.list(input_shape) input_shape <- modules$builtin$tuple(int32(input_shape)) res <- modules$keras.layers.convolutional$Conv2D( filters = int32(filters), kernel_size = int32(kernel_size), strides = int32(strides), padding = padding, data_format = data_format, dilation_rate = int32(dilation_rate), activation = activation, use_bias = use_bias, kernel_initializer = kernel_initializer, bias_initializer = bias_initializer, kernel_regularizer = kernel_regularizer, bias_regularizer = bias_regularizer, activity_regularizer = activity_regularizer, kernel_constraint = kernel_constraint, bias_constraint = bias_constraint, input_shape = input_shape) } return(res) } SeparableConv2D <- function(filters, kernel_size, strides = c(1, 1), padding = 'valid', data_format = NULL, depth_multiplier = 1, dilation_rate = c(1, 1), activation = NULL, use_bias = TRUE, kernel_initializer = 'glorot_uniform', bias_initializer = 'zeros', kernel_regularizer = NULL, bias_regularizer = NULL, activity_regularizer = NULL, kernel_constraint = NULL, bias_constraint = NULL, input_shape = NULL) { if (is.null(input_shape)) { res <- modules$keras.layers.convolutional$SeparableConv2D( filters = int32(filters), kernel_size = int32(kernel_size), strides = int32(strides), padding = padding, data_format = data_format, depth_multiplier = int32(depth_multiplier), dilation_rate = int32(dilation_rate), activation = activation, use_bias = use_bias, kernel_initializer = kernel_initializer, bias_initializer = bias_initializer, kernel_regularizer = kernel_regularizer, bias_regularizer = bias_regularizer, activity_regularizer = activity_regularizer, kernel_constraint = kernel_constraint, bias_constraint = bias_constraint) } else { input_shape <- as.list(input_shape) input_shape <- modules$builtin$tuple(int32(input_shape)) res <- modules$keras.layers.convolutional$SeparableConv2D( filters = int32(filters), kernel_size = int32(kernel_size), strides = int32(strides), padding = padding, data_format = data_format, depth_multiplier = int32(depth_multiplier), dilation_rate = int32(dilation_rate), activation = activation, use_bias = use_bias, kernel_initializer = kernel_initializer, bias_initializer = bias_initializer, kernel_regularizer = kernel_regularizer, bias_regularizer = bias_regularizer, activity_regularizer = activity_regularizer, kernel_constraint = kernel_constraint, bias_constraint = bias_constraint, input_shape = input_shape) } return(res) } Conv2DTranspose <- function(filters, kernel_size, strides = c(1, 1), padding = 'valid', data_format = NULL, dilation_rate = c(1, 1), activation = NULL, use_bias = TRUE, kernel_initializer = 'glorot_uniform', bias_initializer = 'zeros', kernel_regularizer = NULL, bias_regularizer = NULL, activity_regularizer = NULL, kernel_constraint = NULL, bias_constraint = NULL, input_shape = NULL) { if (is.null(input_shape)) { res <- modules$keras.layers.convolutional$Conv2DTranspose( filters = int32(filters), kernel_size = int32(kernel_size), strides = int32(strides), padding = padding, data_format = data_format, dilation_rate = int32(dilation_rate), activation = activation, use_bias = use_bias, kernel_initializer = kernel_initializer, bias_initializer = bias_initializer, kernel_regularizer = kernel_regularizer, bias_regularizer = bias_regularizer, activity_regularizer = activity_regularizer, kernel_constraint = kernel_constraint, bias_constraint = bias_constraint) } else { input_shape <- as.list(input_shape) input_shape <- modules$builtin$tuple(int32(input_shape)) res <- modules$keras.layers.convolutional$Conv2DTranspose( filters = int32(filters), kernel_size = int32(kernel_size), strides = int32(strides), padding = padding, data_format = data_format, dilation_rate = int32(dilation_rate), activation = activation, use_bias = use_bias, kernel_initializer = kernel_initializer, bias_initializer = bias_initializer, kernel_regularizer = kernel_regularizer, bias_regularizer = bias_regularizer, activity_regularizer = activity_regularizer, kernel_constraint = kernel_constraint, bias_constraint = bias_constraint, input_shape = input_shape) } return(res) } Conv3D <- function(filters, kernel_size, strides = c(1, 1, 1), padding = 'valid', data_format = NULL, dilation_rate = c(1, 1, 1), activation = NULL, use_bias = TRUE, kernel_initializer = 'glorot_uniform', bias_initializer = 'zeros', kernel_regularizer = NULL, bias_regularizer = NULL, activity_regularizer = NULL, kernel_constraint = NULL, bias_constraint = NULL, input_shape = NULL) { if (is.null(input_shape)) { res <- modules$keras.layers.convolutional$Conv3D( filters = int32(filters), kernel_size = int32(kernel_size), strides = int32(strides), padding = padding, data_format = data_format, dilation_rate = int32(dilation_rate), activation = activation, use_bias = use_bias, kernel_initializer = kernel_initializer, bias_initializer = bias_initializer, kernel_regularizer = kernel_regularizer, bias_regularizer = bias_regularizer, activity_regularizer = activity_regularizer, kernel_constraint = kernel_constraint, bias_constraint = bias_constraint) } else { input_shape <- as.list(input_shape) input_shape <- modules$builtin$tuple(int32(input_shape)) res <- modules$keras.layers.convolutional$Conv3D( filters = int32(filters), kernel_size = int32(kernel_size), strides = int32(strides), padding = padding, data_format = data_format, dilation_rate = int32(dilation_rate), activation = activation, use_bias = use_bias, kernel_initializer = kernel_initializer, bias_initializer = bias_initializer, kernel_regularizer = kernel_regularizer, bias_regularizer = bias_regularizer, activity_regularizer = activity_regularizer, kernel_constraint = kernel_constraint, bias_constraint = bias_constraint, input_shape = input_shape) } return(res) } NULL Cropping1D <- function(cropping = c(1,1), input_shape = NULL) { if (is.null(input_shape)) { res <- modules$keras.layers.convolutional$Cropping1D( cropping = int32(cropping)) } else { input_shape <- as.list(input_shape) input_shape <- modules$builtin$tuple(int32(input_shape)) res <- modules$keras.layers.convolutional$Cropping1D( cropping = int32(cropping), input_shape = input_shape) } return(res) } Cropping2D <- function(cropping = 0, data_format = NULL, input_shape = NULL) { if (is.null(input_shape)) { res <- modules$keras.layers.convolutional$Cropping2D( cropping = int32(cropping), data_format = data_format) } else { input_shape <- as.list(input_shape) input_shape <- modules$builtin$tuple(int32(input_shape)) res <- modules$keras.layers.convolutional$Cropping2D( cropping = int32(cropping), data_format = data_format, input_shape = input_shape) } return(res) } Cropping3D <- function(cropping = 0, data_format = NULL, input_shape = NULL) { if (is.null(input_shape)) { res <- modules$keras.layers.convolutional$Cropping3D( cropping = int32(cropping), data_format = data_format) } else { input_shape <- as.list(input_shape) input_shape <- modules$builtin$tuple(int32(input_shape)) res <- modules$keras.layers.convolutional$Cropping3D( cropping = int32(cropping), data_format = data_format, input_shape = input_shape) } return(res) } NULL UpSampling1D <- function(size = 2, input_shape = NULL) { if (is.null(input_shape)) { res <- modules$keras.layers.convolutional$UpSampling1D(size = int32(size)) } else { input_shape <- as.list(input_shape) input_shape <- modules$builtin$tuple(int32(input_shape)) res <- modules$keras.layers.convolutional$UpSampling1D(size = int32(size), input_shape = input_shape) } return(res) } UpSampling2D <- function(size = c(2, 2), data_format = NULL, input_shape = NULL) { if (is.null(input_shape)) { res <- modules$keras.layers.convolutional$UpSampling2D(size = int32(size)) } else { input_shape <- as.list(input_shape) input_shape <- modules$builtin$tuple(int32(input_shape)) res <- modules$keras.layers.convolutional$UpSampling2D(size = int32(size), input_shape = input_shape) } return(res) } UpSampling3D <- function(size = c(2, 2, 2), data_format = NULL, input_shape = NULL) { if (is.null(input_shape)) { res <- modules$keras.layers.convolutional$UpSampling3D(size = int32(size)) } else { input_shape <- as.list(input_shape) input_shape <- modules$builtin$tuple(int32(input_shape)) res <- modules$keras.layers.convolutional$UpSampling3D(size = int32(size), input_shape = input_shape) } return(res) } NULL ZeroPadding1D <- function(padding = 1, input_shape = NULL) { if (is.null(input_shape)) { res <- modules$keras.layers.convolutional$ZeroPadding1D( padding = int32(padding)) } else { input_shape <- as.list(input_shape) input_shape <- modules$builtin$tuple(int32(input_shape)) res <- modules$keras.layers.convolutional$ZeroPadding1D( padding = int32(padding), input_shape = input_shape) } return(res) } ZeroPadding2D <- function(padding = 1, data_format = NULL, input_shape = NULL) { if (is.null(input_shape)) { res <- modules$keras.layers.convolutional$ZeroPadding2D( padding = int32(padding), data_format = data_format) } else { input_shape <- as.list(input_shape) input_shape <- modules$builtin$tuple(int32(input_shape)) res <- modules$keras.layers.convolutional$ZeroPadding2D( padding = int32(padding), data_format = data_format, input_shape = input_shape) } return(res) } ZeroPadding3D <- function(padding = 1, data_format = NULL, input_shape = NULL) { if (is.null(input_shape)) { res <- modules$keras.layers.convolutional$ZeroPadding3D( padding = int32(padding), data_format = data_format) } else { input_shape <- as.list(input_shape) input_shape <- modules$builtin$tuple(int32(input_shape)) res <- modules$keras.layers.convolutional$ZeroPadding3D( padding = int32(padding), data_format = data_format, input_shape = input_shape) } return(res) }
.setup.formulae <- function(formula, npar, npar2, data, trace) { if (inherits(formula, "formula")) formula <- list(formula) if (npar == 1) { if (!(length(formula) %in% c(npar, 1))) stop("length(formula) for this family should be 1") } else { if (!(length(formula) %in% c(npar, 1))) stop(paste("length(formula) for this family should be", npar, "(or 1 if all parameters are to have the same formula)")) } pred.vars <- unique(unlist(lapply(formula, all.vars))) if (!all(pred.vars %in% names(data))) { missing.vars <- pred.vars[!(pred.vars %in% names(data))] stop(paste("Variable(s) '", paste(missing.vars, collapse=", "), "' not supplied to `data'.", sep="")) } terms.list <- lapply(formula, terms.formula, specials=c("s", "te", "ti")) got.specials <- sapply(lapply(terms.list, function(x) unlist(attr(x, "specials"))), any) termlabels.list <- lapply(terms.list, attr, "term.labels") got.intercept <- sapply(terms.list, attr, "intercept") == 1 for (i in seq_along(termlabels.list)) { if (length(termlabels.list[[i]]) == 0) { if (got.intercept[i]) { termlabels.list[[i]] <- "1" } else { stop(paste("formula element", i, "incorrectly specified")) } } } got.response <- sapply(terms.list, attr, "response") == 1 if (!got.response[1]) { stop("formula has no response") } else { response.name <- as.character(formula[[1]])[2] } if (any(!got.response)) { for (i in which(!got.response)) { formula[[i]] <- reformulate(termlabels=termlabels.list[[i]], response=response.name) } } stripped.formula <- lapply(termlabels.list, function(x) reformulate(termlabels=x)) censored <- FALSE if (substr(response.name, 1, 5) == "cens(") { response.name <- substr(response.name, 6, nchar(response.name) - 1) response.name <- gsub(" ", "", response.name) response.name <- strsplit(response.name, ",")[[1]] if (length(response.name) > 2) stop("Censored response can only contain two variables.") rr <- response.name[2] formula <- lapply(termlabels.list, function(x) reformulate(termlabels=x, response=rr)) censored <- TRUE } attr(formula, "response.name") <- response.name pred.vars <- pred.vars[!(pred.vars %in% response.name)] attr(formula, "predictor.names") <- pred.vars attr(formula, "stripped") <- stripped.formula attr(formula, "censored") <- censored attr(formula, "smooths") <- got.specials for (i in seq_along(formula)) { attr(formula[[i]], "intercept") <- got.intercept[i] attr(formula[[i]], "smooth") <- got.specials[i] } formula } .setup.family <- function(family, pp) { if (family == "gev") { lik.fns <- .gevfns npar <- 3 nms <- c("mu", "lpsi", "xi") } else { if (family == "gpd") { lik.fns <- .gpdfns npar <- 2 nms <- c("lpsi", "xi") } else { if (family == "modgpd") { stop("'family='modgpd'' will return; in the mean time use `family='gpd''") lik.fns <- NULL npar <- 2 nms <- c("lmodpsi", "xi") } else { if (family == "pp") { lik.fns <- .ppfns npar <- 3 nms <- c("mu", "lpsi", "xi") } else { if (family == "weibull") { lik.fns <- .weibfns npar <- 2 nms <- c("llambda", "lk") } else { if (family == "exi") { lik.fns <- .exifns npar <- 1 nms <- c("location") } else { if (family == "ald") { lik.fns <- .aldfns npar <- 2 nms <- c("mu", "lsigma") } else { if (family == "gamma") { lik.fns <- NULL npar <- 2 nms <- c("ltheta", "lk") } else { if (family == "orthoggpd") { stop("'family='orthoggpd'' may not return return") lik.fns <- NULL npar <- 2 nms <- c("lnu", "xi") } else { if (family == "transxigpd") { stop("'family='transxigpd'' may not return") lik.fns <- NULL npar <- 2 nms <- c("lpsi", "xi") } else { if (family == "transgev") { stop("'family='transgev'' may not return") lik.fns <- NULL npar <- 6 nms <- c("mu", "lpsi", "xi", "A", "lB", "C") } else { if (family == "exponential") { lik.fns <- .expfns npar <- 1 nms <- c("llambda") } else { if (family == "gauss") { lik.fns <- .gaussfns npar <- 2 nms <- c("mu", "logsigma") } } } } } } } } } } } } } out <- list(npar=npar, npar2=npar, lik.fns=lik.fns, nms=nms) } .predictable.gam <- function(G, formula) { keep <- c("dev.extra", "pterms", "nsdf", "X", "terms", "mf", "smooth", "sp") G <- G[keep] G$nb <- ncol(G$X) G$coefficients <- numeric(G$nb) old <- c("mf", "pP", "cl") new <- c("model", "paraPen", "call") is.in <- !is.na(match(old, names(G))) if (any(is.in)) names(G)[match(old[is.in], names(G))] <- new[is.in] G$formula <- formula class(G) <- "gamlist" G } .X.evgam <- function(object, newdata) { object <- object[sapply(object, inherits, what="gamlist")] if (missing(newdata)) { X <- lapply(object, function(x) x$X) } else { for (i in seq_along(object)) class(object[[i]]) <- "gam" X <- lapply(object, mgcv::predict.gam, newdata=newdata, type="lpmatrix") } names(X) <- names(object) X } .setup.data <- function(data, responsename, formula, family, nms, removeData, exiargs, aldargs, pp, knots, maxdata, maxspline, compact, sargs, outer, trace) { for (i in seq_along(responsename)) data <- data[!is.na(data[,responsename[i]]),] if (nrow(data) > maxdata) { id <- sort(sample(nrow(data), maxdata)) data <- data[id,] if (trace >= 0) message("`data' truncated to `maxdata' rows. Re-supply `data' to, e.g., `predict.evgam'") } if (compact) { data.undup <- as.list(data[,unique(unlist(lapply(formula, function(y) unlist(lapply(mgcv::interpret.gam(y)$smooth.spec, function(x) x$term))))), drop=FALSE]) data.undup <- lapply(data.undup, function(x) as.integer(as.factor(x))) if (length(data.undup) > 1) for (i in 2:length(data.undup)) data.undup[[1]] <- paste(data.undup[[1]], data.undup[[i]], sep=":") data.undup <- data.undup[[1]] gc() unq.id <- which(!duplicated(data.undup)) data.unq <- data.undup[unq.id] dup.id <- match(data.undup, data.unq) } subsampling <- FALSE gams <- list() if (family %in% c("pp", "ppexi")) data <- .setup.pp.data(data, responsename, pp) for (i in seq_along(formula)) { if (nrow(data) > maxspline) { id <- sample(nrow(data), maxspline) gams[[i]] <- mgcv::gam(formula[[i]], data=data[id,], fit=FALSE, knots=knots, method="REML") } else { gams[[i]] <- mgcv::gam(formula[[i]], data=data, fit=FALSE, knots=knots, method="REML") } gams[[i]] <- .predictable.gam(gams[[i]], formula[[i]]) } gc() lik.data <- list() lik.data$control <- list() lik.data$outer <- outer lik.data$control$outer <- list(steptol=1e-12, itlim=1e2, fntol=1e-8, gradtol=1e-2, stepmax=3) lik.data$control$inner <- list(steptol=1e-12, itlim=1e2, fntol=1e-8, gradtol=1e-4, stepmax=1e2) lik.data$y <- as.matrix(data[,responsename, drop=FALSE]) lik.data$Mp <- sum(unlist(sapply(gams, function(y) c(1, sapply(y$smooth, function(x) x$null.space.dim))))) lik.data$const <- .5 * lik.data$Mp * log(2 * pi) lik.data$nobs <- nrow(lik.data$y) if (attr(formula, "censored")) { lik.data$censored <- TRUE if (any(lik.data$y[,2] < lik.data$y[,1])) stop("For censored response need right >= left in `cens(left, right)'") lik.data$cens.id <- lik.data$y[,2] > lik.data$y[,1] if (trace >= 0 & sum(lik.data$cens.id) == 0) { message("No response data appear to be censored. Switching to uncensored likelihood.") lik.data$censored <- FALSE } } else { lik.data$censored <- FALSE } if (family == "weibull") { if (min(lik.data$y) <= 0) stop(expression("Weibull distribution has support (0, \U221E) in evgam.")) } if (family == "gpd") { if (min(lik.data$y) <= 0) stop(expression("GPD has support (0, \U221E) in evgam.")) } if (family == "exi") { if (is.null(exiargs$id)) stop("no `id' in `exi.args'.") if (is.null(exiargs$nexi)) { if (trace >= 0) message("`exiargs$nexi' assumed to be 2.") exiargs$nexi <- 2 } if (is.null(exiargs$link)) { if (trace >= 0) message("`exiargs$link' assumed to be `logistic'.") exiargs$link <- "logistic" } lik.data$exiname <- exiargs$id lik.data$y <- list(lik.data$y, data[,exiargs$id]) lik.data$nexi <- exiargs$nexi if (exiargs$link == "cloglog") { lik.data$exilink <- 2 lik.data$linkfn <- function(x) 1 - exp(-exp(x)) attr(lik.data$linkfn, "deriv") <- function(x) exp(-exp(x)) * exp(x) } if (exiargs$link == "logistic") { lik.data$exilink <- 1 lik.data$linkfn <- function(x) 1 / (1 + exp(-x)) attr(lik.data$linkfn, "deriv") <- function(x) exp(-x)/(1 + exp(-x))^2 } if (exiargs$link == "probit") { lik.data$exilink <- 0 lik.data$linkfn <- function(x) pnorm(x) attr(lik.data$linkfn, "deriv") <- function(x) dnorm(x) } attr(lik.data$linkfn, "name") <- exiargs$link } if (family %in% c("pp", "ppexi")) { lik.data$ppw <- attr(data, "weights") lik.data$y <- as.matrix(rbind(as.matrix(attr(data, "quad")[,responsename]), lik.data$y)) lik.data$ppq <- rep(as.logical(1:0), c(nrow(attr(data, "quad")), nrow(data))) lik.data$ppcens <- attr(data, "cens") lik.data$weights <- attr(data, "cweights") lik.data$exi <- attr(data, "exi") } if (family == "ald") { if (is.null(aldargs$tau)) aldargs$tau <- .5 if (is.null(aldargs$C)) aldargs$C <- .5 lik.data$tau <- aldargs$tau lik.data$C <- aldargs$C } lik.data$sandwich <- !is.null(sargs$id) if (lik.data$sandwich) lik.data$sandwich.split <- data[,sargs$id] if (!compact) { if (nrow(data) > maxspline) { lik.data$X <- .X.evgam(gams, data) } else { lik.data$X <- .X.evgam(gams) } if (family %in% c("pp", "ppexi")) { ppX <- .X.evgam(gams, attr(data, "quad")) lik.data$X <- lapply(seq_along(ppX), function(i) rbind(ppX[[i]], lik.data$X[[i]])) } lik.data$dupid <- 0 lik.data$duplicate <- 0 } else { if (family %in% c("pp", "ppexi")) stop("Option compact = TRUE not currently possible for pp model.") lik.data$X <- .X.evgam(gams, data[unq.id,]) lik.data$dupid <- dup.id - 1 lik.data$duplicate <- 1 } for (i in seq_along(gams)) { if (removeData) gams[[i]]$y <- NULL } if (length(lik.data$X) == 1 & length(nms) > 1) { for (i in 2:length(nms)) { lik.data$X[[i]] <- lik.data$X[[1]] gams[[i]] <- gams[[1]] } } nbk <- sapply(lik.data$X, ncol) lik.data$nb <- sum(nbk) lik.data$idpars <- rep(seq_along(lik.data$X), nbk) lik.data$LAid <- lik.data$idpars > 0 lik.data$subsampling <- subsampling gotsmooth <- which(sapply(gams, function(x) length(x$sp)) > 0) lik.data$k <- 1 if (is.null(sargs$id)) { lik.data$adjust <- 0 } else { if (is.null(sargs$method)) sargs$method <- "magnitude" if (sargs$method == "curvature") { if (trace > 0) message(paste("Sandwich adjustment method: curvature")) lik.data$adjust <- 2 } else { if (trace > 0) message(paste("Sandwich adjustment method: magnitude")) lik.data$adjust <- 1 } } if (is.null(sargs$force)) sargs$force <- FALSE lik.data$force <- sargs$force list(lik.data=lik.data, gotsmooth=gotsmooth, data=data, gams=gams, sandwich=lik.data$adjust > 0) } .setup.pp.data <- function(data, responsename, pp) { nodes <- pp$nodes ny <- pp$ny if (is.null(ny)) stop("Cannot have NULL pp.args$ny.") threshold <- pp$threshold r <- pp$r if (is.null(threshold) & is.null(r)) stop("Both pp$threshold and pp$r cannot be NULL") data$row <- seq_len(nrow(data)) ds <- split(data, data[,pp$id]) wts <- pp$ny if (length(wts) == 1) { wts <- rep(wts, length(ds)) } else { wts <- wts[match(names(ds), names(wts))] } nobs2 <- sapply(ds, nrow) data.quad <- do.call(rbind, lapply(ds, function(x) x[1,])) if (!is.null(pp$r)) { enough <- nobs2 >= pp$r if (any(!enough)) warning(paste(sum(!enough), "unique pp.args$id removed for having fewer than r observations.")) ds <- ds[enough] wts <- wts[enough] nid <- sum(enough) data.quad <- data.quad[enough,] if (pp$r != -1) { du <- sapply(ds, function(x) x[order(x[,responsename], decreasing=TRUE)[pp$r], responsename]) } else { du <- sapply(ds, function(x) min(x[, responsename])) } } else { du <- sapply(ds, function(x) x[1, pp$threshold]) nid <- length(du) } data.quad[,responsename] <- du ds <- lapply(seq_len(nid), function(i) subset(ds[[i]], ds[[i]][,responsename] >= du[i])) out <- dfbind(ds) attr(out, "weights") <- wts attr(out, "quad") <- data.quad if (is.null(pp$cens)) { attr(out, "cens") <- NULL } else { attr(out, "cens") <- data[out$row, pp$cens] } if (is.null(pp$weights)) { attr(out, "cweights") <-rep(1, length(out$row)) } else { attr(out, "cweights") <- pp$weights[out$row] } out } .sandwich.C <- function(H, J) { iJ <- pinv(J) HA <- crossprod(H, crossprod(iJ, H)) sH <- svd(H) M <- sqrt(sH$d) * t(sH$v) sHA <- svd(HA) MA <- sqrt(sHA$d) * t(sHA$v) solve(M, MA) } .setup.inner.inits <- function(inits, likdata, likfns, npar, family) { likdata0 <- likdata likdata0$X <- lapply(seq_along(likdata$X), function(i) matrix(1, nrow=nrow(likdata$X[[i]]), ncol=1)) likdata0$S <- diag(0, npar) likdata0$idpars <- seq_len(npar) if (is.null(inits)) { if (npar == 1) inits <- 2 if (npar == 2) { if (family == "ald") { inits <- c(quantile(likdata0$y[,1], likdata0$tau), log(sd(likdata0$y[,1]))) } else { inits <- c(log(mean(likdata$y[,1])), .05) if (family == "transxigpd") inits[2] <- .9 } } if (npar %in% 3:4) { inits <- c(sqrt(6) * sd(likdata0$y[,1]) / pi, .05) inits <- c(mean(likdata0$y[,1]) - .5772 * inits[1], log(inits[1]), inits[2]) if (npar == 4) inits <- c(inits, 1) } if (npar == 6) { inits <- c(sqrt(6) * sd(likdata0$y[,1]) / pi, .05) inits <- c(mean(likdata0$y[,1]) - .5772 * inits[1], log(inits[1]), inits[2]) inits <- c(inits, 0, 0, 1) } likdata0$CH <- diag(length(inits)) likdata0$compmode <- numeric(length(inits)) beta0 <- .newton_step_inner(inits, .nllh.nopen, .search.nopen, likdata=likdata0, likfns=likfns, control=likdata$control$inner)$par } else { if (is.list(inits)) { betamat <- expand.grid(inits) betanllh <- numeric(nrow(betamat)) for (i in seq_len(nrow(betamat))) { beta0 <- unlist(betamat[i,]) betanllh[i] <- likfns$nllh(beta0, likdata0) } beta0 <- betamat[which.min(betanllh),] print(beta0) } else { beta0 <- inits } } beta0 <- unlist(lapply(seq_len(npar), function(i) c(beta0[i], rep(0, ncol(likdata$X[[i]]) - 1)))) compmode <- 0 * beta0 CH <- diag(compmode + 1) k <- 1 likdata[c("k", "CH", "compmode")] <- list(k, CH, compmode) diagH <- diag(.gH.nopen(beta0, likdata=likdata, likfns=likfns)[[2]]) if (likdata$sandwich) { beta0 <- .newton_step(beta0, .nllh.nopen, .search.nopen, likdata=likdata, likfns=likfns, control=likdata$control$inner)$par H <- .gH.nopen(beta0, likdata=likdata, likfns=likfns, sandwich=TRUE) if (family == "pp") { J0 <- H[[1]] J <- J0[,!likdata$ppq] J0 <- rowSums(J0[,likdata$ppq]) J <- split(as.data.frame(t(J)), likdata$sandwich.split) wts <- sapply(J, nrow) wts <- wts / sum(wts) J <- sapply(J, colSums) J <- J + J0 %o% wts J <- tcrossprod(J) } else { J <- split(as.data.frame(t(H[[1]])), likdata$sandwich.split) J <- sapply(J, colSums) J <- tcrossprod(J) } H <- H[[2]] diagH <- diag(H) cholH <- try(chol(H), silent=TRUE) if (inherits(cholH, "try-error")) { if (!likdata$force) { stop("Hessian of unpenalised MLE not positive definite.\n Supply `force=TRUE' to `sandwich.args' to perturb it to be positive definite.") } else { if (trace >= 0) message("Hessian perturbed to be positive definite for sandwich adjustment.") iH <- pinv(H) } } else { iH <- chol2inv(cholH) } if (likdata$adjust == 2) { cholJ <- try(chol(J), silent=TRUE) if (inherits(cholJ, "try-error") & likdata$adjust == 2) { HA <- crossprod(backsolve(cholJ, H, transpose=TRUE)) } else { iHA <- tcrossprod(crossprod(iH, J), iH) choliHA <- try(chol(iHA), silent=TRUE) if (inherits(choliHA, "try-error")) { if (!likdata$force) { stop("Sandwich variance not positive definite.\n Supply `force=TRUE' to `sandwich.args' to perturb it to be positive definite.") } else { if (trace >= 0) message("Sandwich variance perturbed to be positive definite.") HA <- pinv(iHA) } } else { HA <- chol2inv(choliHA) } } sH <- svd(H) M <- sqrt(sH$d) * t(sH$v) sHA <- svd(HA) MA <- sqrt(sHA$d) * t(sHA$v) CH <- solve(M, MA) compmode <- beta0 } else { k <- 1 / mean(diag(crossprod(iH, J))) } } attr(beta0, "k") <- k attr(beta0, "CH") <- CH attr(beta0, "compmode") <- compmode attr(beta0, "diagH") <- diagH beta0 } .guess <- function(x, d, s) { okay <- s != 0 val <- d / (d + exp(x) * s) mean(val[okay]) - .4 } .sandwich <- function(likdata, beta) { likdata$k <- attr(beta, "k") likdata$CH <- attr(beta, "CH") likdata$compmode <- attr(beta, "compmode") bigX <- do.call(cbind, likdata$X) CHX <- bigX %*% likdata$CH CHX <- lapply(unique(likdata$idpars), function(i) CHX[,likdata$idpars == i]) likdata$CHX <- CHX likdata } .outer <- function(rho0, beta, likfns, likdata, Sdata, control, correctV, outer, trace) { attr(rho0, "beta") <- beta if (outer == "newton") { fit.reml <- .newton_step_inner(rho0, .reml0, .search.reml, likfns=likfns, likdata=likdata, Sdata=Sdata, control=likdata$control$outer, trace=trace > 1) } else { if (outer == "fd") { fit.reml <- .BFGS(rho0, .reml0, .reml1.fd, likfns=likfns, likdata=likdata, Sdata=Sdata, control=likdata$control$outer, trace=trace > 1) } else { fit.reml <- .BFGS(rho0, .reml0, .reml1, likfns=likfns, likdata=likdata, Sdata=Sdata, control=likdata$control$outer, trace=trace > 1) } rho1 <- fit.reml$par attr(rho1, "beta") <- fit.reml$beta fit.reml$Hessian <- try(.reml12(rho1, likfns=likfns, likdata=likdata, Sdata=Sdata)[[2]], silent=TRUE) if (inherits(fit.reml$Hessian, "try-error")) fit.reml$Hessian <- .reml2.fd(rho1, likfns=likfns, likdata=likdata, Sdata=Sdata) } fit.reml$invHessian <- .solve_evgam(fit.reml$Hessian) fit.reml$trace <- trace if (trace == 1) { report <- "\n Final max(|grad|))" likdata$S <- .makeS(Sdata, exp(fit.reml$par)) report <- c(report, paste(" Inner:", signif(max(abs(.gH.pen(fit.reml$beta, likdata, likfns)[[1]])), 3))) report <- c(report, paste(" Outer:", signif(max(abs(fit.reml$gradient)), 3))) report <- c(report, "", "") cat(paste(report, collapse="\n")) } fit.reml } .outer.nosmooth <- function(beta, likfns, likdata, control, trace) { fit.inner <- .newton_step(beta, .nllh.nopen, .search.nopen, likdata=likdata, likfns=likfns, control=likdata$control$inner) list(beta=fit.inner$par) } .VpVc <- function(fitreml, likfns, likdata, Sdata, correctV, sandwich, smooths, trace) { lsp <- fitreml$par H0 <- .gH.nopen(fitreml$beta, likdata, likfns)[[2]] if (smooths) { sp <- exp(lsp) H <- H0 + likdata$S } else { H <- H0 } cholH <- try(chol(H), silent=TRUE) if (inherits(cholH, "try-error") & trace >= 0) message("Final Hessian of negative penalized log-likelihood not numerically positive definite.") Vc <- Vp <- pinv(H) if (smooths) { if (correctV) { cholVp <- try(chol(Vp), silent=TRUE) if (inherits(cholVp, "try-error")) { cholVp <- attr(.perturb(Vp), "chol") } attr(lsp, "beta") <- fitreml$beta spSl <- Map("*", attr(Sdata, "Sl"), exp(lsp)) dbeta <- .d1beta(lsp, fitreml$beta, spSl, .Hdata(H))$d1 Vrho <- fitreml$invHessian Vbetarho <- tcrossprod(dbeta %*% Vrho, dbeta) VR <- matrix(0, nrow=likdata$nb, ncol=likdata$nb) Vc <- .perturb(Vp + Vbetarho + VR) } } else { Vrho <- 0 } list(Vp=Vp, Vc=Vc, Vlsp=Vrho, H0=H0, H=H) } .edf <- function(beta, likfns, likdata, VpVc, sandwich) { diag(crossprod(VpVc$Vp, VpVc$H0)) } .swap <- function(fitreml, gams, likdata, VpVc, gotsmooth, edf, smooths) { Vp <- VpVc$Vp Vc <- VpVc$Vc if (smooths) { spl <- split(exp(fitreml$par), unlist(sapply(seq_along(gams), function(x) rep(x, length(gams[[x]]$sp))))) sp <- replace(lapply(seq_along(gams), function(x) NULL), gotsmooth, spl) } for (i in seq_along(gams)) { idi <- likdata$idpars == i gams[[i]]$coefficients <- fitreml$beta[idi] names(gams[[i]]$coefficients) <- gams[[i]]$term.names gams[[i]]$Vp <- Vp[idi, idi, drop = FALSE] gams[[i]]$Vc <- Vc[idi, idi, drop = FALSE] if (i %in% gotsmooth) gams[[i]]$sp <- sp[[i]] gams[[i]]$edf <- edf[idi] } gams } .finalise <- function(gams, data, likfns, likdata, Sdata, fitreml, VpVc, family, gotsmooth, formula, responsenm, removeData, edf) { nms <- c("location", "logscale", "shape") if (length(gams) == 2) { if (family %in% c("ald", "gauss")) { nms <- nms[1:2] } else { nms <- nms[-1] }} if (length(gams) == 4) { if (is.null(likdata$agg)) { nms <- c(nms, "logitdep") } else { nms <- c(nms, "logdep") } } if (family == "exponential") nms <- "lograte" if (family == "weibull") nms[2] <- "logshape" if (family == "exi") nms <- paste(attr(likdata$linkfn, "name"), "exi", sep="") names(gams) <- nms smooths <- length(gotsmooth) > 0 Vp <- VpVc$Vp Vc <- VpVc$Vc if (smooths) gams$sp <- exp(fitreml$par) gams$nobs <- likdata$nobs gams$logLik <- -1e20 fit.lik <- list(convergence=0) if (fit.lik$convergence == 0) { gams$logLik <- -.nllh.nopen(fitreml$beta, likdata, likfns) gams$logLik <- gams$logLik - likdata$const } if (fit.lik$convergence != 0) gams$AIC <- gams$BIC <- 1e20 attr(gams, "df") <- sum(edf) gams$simulate <- list(mu=fitreml$beta, Sigma=Vp) gams$family <- family gams$idpars <- likdata$idpars nms <- names(gams)[seq_along(formula)] logits <- substr(nms, 1, 5) == "logit" if (any(logits)) nms[logits] <- gsub("logit", "", nms[logits]) logs <- substr(nms, 1, 3) == "log" if (any(logs)) nms[logs] <- gsub("log", "", nms[logs]) probits <- substr(nms, 1, 6) == "probit" if (any(probits)) nms[probits] <- gsub("probit", "", nms[probits]) gams$predictor.names <- attr(formula, "predictor.names") formula <- attr(formula, "stripped") names(formula) <- nms gams$call <- formula gams$response.name <- responsenm gams$gotsmooth <- gotsmooth if (!removeData) { if (family == "pp") { gams$data <- attr(data, "quad") } else { gams$data <- data } } gams$Vc <- Vc gams$Vp <- Vp gams$Vlsp <- VpVc$Vlsp gams$negREML <- fitreml$objective gams$coefficients <- fitreml$beta if (family == "ald") gams$tau <- likdata$tau if (family == "exi") { gams$linkfn <- likdata$linkfn gams$exi.name <- likdata$exiname } for (i in seq_along(likdata$X)) { gams[[i]]$X <- likdata$X[[i]] if (likdata$duplicate == 1) gams[[i]]$X <- gams[[i]]$X[likdata$dupid + 1,] gams[[i]]$fitted <- as.vector(likdata$X[[i]] %*% gams[[i]]$coefficients) } gams$likdata <- likdata gams$likfns <- likfns if (smooths) gams$Sdata <- Sdata gams$formula <- formula gams$compacted <- likdata$duplicate == 1 if (gams$compacted) gams$compactid <- likdata$dupid + 1 smooth.terms <- unique(lapply(lapply(gams[gotsmooth], function(x) x$smooth), function(y) lapply(y, function(z) z$term))) smooth.terms <- unique(unlist(smooth.terms, recursive=FALSE)) gams$plotdata <- lapply(smooth.terms, function(x) unique(data[,x, drop=FALSE])) if (family == "weibull") names(gams)[2] <- "logshape" if (family == "exponential") names(gams)[1] <- "lograte" gams$ngam <- length(formula) for (i in seq_along(gams[nms])[-gotsmooth]) gams[[i]]$smooth <- NULL class(gams) <- "evgam" return(gams) }
context("pnpp_experiment-calculate_neg_freq") test_that("calc_negative_freq_simple works", { expect_equal(calc_negative_freq_simple(5, 45), 10) expect_equal(calc_negative_freq_simple(5, 5), 50) expect_equal(calc_negative_freq_simple(13, 87), 13) }) test_that("calculate_neg_freq_single works", { file <- system.file("sample_data", "small", "analyzed_pnpp.rds", package = "ddpcr") plate <- load_plate(file) expect_equal(plate %>% calculate_neg_freq_single("A05"), list("negative_num" = 368, "positive_num" = 1224, "negative_freq" = calc_negative_freq_simple(368, 1224))) }) test_that("calculate_negative_freqs works", { file <- system.file("sample_data", "small", "analyzed_pnpp.rds", package = "ddpcr") plate <- load_plate(file) neg_freqs <- plate %>% calculate_negative_freqs %>% plate_meta %>% .[['negative_freq']] %>% .[!is.na(.)] expect_equal(neg_freqs, c(0.218, 23.1, 0.24, 19.8)) })
"greenrice"
EMVS.probit=function(y,x,epsilon=.0005,v0s=.025,nu.1=100,nu.gam=1,a=1,b=ncol(x),beta.initial=NULL, sigma.initial=1,theta.inital=.5,temp=1,p=ncol(x),n=nrow(x)){ if(length(beta.initial)==0){ beta.initial=rep(NaN,times=ncol(x)) while(sum(is.nan(beta.initial))>0) { beta.initial=CSDCD.logistic(p,n,x,ifelse(y==1,1,-1),rep(.0001,p),75) } } scrap=0 cat("\n") L=length(v0s) cat("\n","Running Probit across v0's","\n") cat(rep("",times=(L+1)),sep="|") cat("\n") intersects=numeric(L) log_post=numeric(L) sigma.Vec=numeric(L) theta.Vec=numeric(L) log_post=numeric(L) index.Vec=numeric(L) beta.Vec=matrix(0,L,p) p.Star.Vec=matrix(0,L,p) for (i in (1:L)){ bail.count=0 nu.0=v0s[i] beta.Current=beta.initial beta.new=beta.initial sigma.EM=sigma.initial theta.EM=theta.inital eps=epsilon+1 iter.index=1 while(eps>epsilon && iter.index<20){ if(bail.count>=3) { cat("\n","Iteration scrapped!","\n",sep="") list=list(betas=NULL,intersects=NULL,sigmas=NULL, niters=NULL,posts=NULL,thetas=NULL,v0s=NULL,scrap=1) return(list) } d.Star=rep(NA,p) p.Star=rep(NA,p) for(j in 1:p){ gam.one=dnorm(beta.Current[j],0,sqrt(nu.1))**temp*theta.EM**temp gam.zero=dnorm(beta.Current[j],0,sqrt(nu.0))**temp*(1-theta.EM)**temp p.Star[j]=gam.one/(gam.one+gam.zero) d.Star[j]=((1-p.Star[j])/nu.0)+(p.Star[j]/nu.1) } M=rep(NA,n) y.Star=rep(NA,n) for(j in 1:n){ M[j]=ifelse(y[j]==0,-dnorm(-x[j,]%*%beta.Current,0,1)/pnorm(-x[j,]%*%beta.Current,0,1), dnorm(-x[j,]%*%beta.Current,0,1)/(1-pnorm(-x[j,]%*%beta.Current,0,1))) y.Star[j]=x[j,]%*%beta.Current+M[j] } d.Star.Mat=diag(d.Star,p) beta.old=beta.new beta.Current=CSDCD.random(p,n,x,y.Star,d.Star) if(sum(is.nan(beta.Current))==0) { sigma.EM=1 theta.EM=(sum(p.Star)+a-1)/(a+b+p-2) eps=max(abs(beta.new-beta.Current)) beta.new=beta.Current iter.index=iter.index+1 } if(sum(is.nan(beta.Current))>0){ beta.Current=beta.old bail.count=bail.count+1 } } p.Star.Vec[i,]=p.Star beta.Vec[i,]=beta.new sigma.Vec[i]=sigma.EM theta.Vec[i]=theta.EM index.Vec[i]=iter.index index=p.Star>0.5 c=sqrt(nu.1/v0s[i]) w=(1-theta.Vec[i])/theta.Vec[i] if (w>0){ intersects[i]=sigma.Vec[i]*sqrt(v0s[i])*sqrt(2*log(w*c)*c^2/(c^2-1))}else{ intersects[i]=0} cat("|",sep="") } list=list(betas=beta.Vec,intersects=intersects,sigmas=sigma.Vec, niters=index.Vec,posts=p.Star.Vec,thetas=theta.Vec,v0s=v0s,scrap=0) return(list) }
NULL scale_xcolour_hue <- function(..., h = c(0, 360) + 15, c = 100, l = 65, h.start = 0, direction = 1, na.value = "grey50", aesthetics = "xcolour") { ggplot2::discrete_scale(aesthetics, "hue", scales::hue_pal(h, c, l, h.start, direction), na.value = na.value, ...) } scale_xcolour_manual <- function(..., values, aesthetics = "xcolour", breaks = waiver()) { manual_scale(aesthetics, values, breaks, ...) } scale_xcolor_manual <- function(..., values, aesthetics = "xcolour", breaks = waiver()) { manual_scale(aesthetics, values, breaks, ...) } scale_xcolour_gradient <- function (..., low = " space = "Lab",na.value = "grey50", guide = guide_colorbar(available_aes = "xcolour"), aesthetics = "xcolour") { continuous_scale(aesthetics, "gradient", scales::seq_gradient_pal(low, high, space), na.value = na.value, guide = guide, ...) } scale_xcolor_gradientn <- function (..., colours, values = NULL, space = "Lab", na.value = "grey50", guide = guide_colorbar(available_aes = "xcolour"), aesthetics = "xcolour", colors) { colours <- if (missing(colours)) colors else colours continuous_scale(aesthetics, "gradientn", scales::gradient_n_pal(colours,values, space), na.value = na.value, guide = guide, ...) } scale_xcolour_gradientn <- function (..., colours, values = NULL, space = "Lab", na.value = "grey50", guide = guide_colorbar(available_aes = "xcolour"), aesthetics = "xcolour", colors) { colours <- if (missing(colours)) colors else colours continuous_scale(aesthetics, "gradientn", scales::gradient_n_pal(colours,values, space), na.value = na.value, guide = guide, ...) } scale_xcolour_discrete <- scale_xcolour_hue scale_xcolor_discrete <- scale_xcolour_hue scale_xcolour_continuous <- scale_xcolour_gradient scale_xcolor_continuous <- scale_xcolour_gradient scale_ycolour_hue <- function(..., h = c(0, 360) + 15, c = 100, l = 65, h.start = 0, direction = 1, na.value = "grey50", aesthetics = "ycolour") { ggplot2::discrete_scale(aesthetics, "hue", scales::hue_pal(h, c, l, h.start, direction), na.value = na.value, ...) } scale_ycolour_manual <- function(..., values, aesthetics = "ycolour", breaks = waiver()) { manual_scale(aesthetics, values, breaks, ...) } scale_ycolor_manual <- function(..., values, aesthetics = "ycolour", breaks = waiver()) { manual_scale(aesthetics, values, breaks, ...) } scale_ycolour_gradient <- function (..., low = " space = "Lab",na.value = "grey50", guide = guide_colorbar(available_aes = "ycolour"), aesthetics = "ycolour") { continuous_scale(aesthetics, "gradient", scales::seq_gradient_pal(low, high, space), na.value = na.value, guide = guide, ...) } scale_ycolour_gradientn <- function (..., colours, values = NULL, space = "Lab", na.value = "grey50", guide = guide_colorbar(available_aes = "ycolour"), aesthetics = "ycolour", colors) { colours <- if (missing(colours)) colors else colours continuous_scale(aesthetics, "gradientn", scales::gradient_n_pal(colours,values, space), na.value = na.value, guide = guide, ...) } scale_ycolor_gradientn <- function (..., colours, values = NULL, space = "Lab", na.value = "grey50", guide = guide_colorbar(available_aes = "ycolour"), aesthetics = "ycolour", colors) { colours <- if (missing(colours)) colors else colours continuous_scale(aesthetics, "gradientn", scales::gradient_n_pal(colours,values, space), na.value = na.value, guide = guide, ...) } scale_ycolour_discrete <- scale_ycolour_hue scale_ycolor_discrete <- scale_ycolour_hue scale_ycolour_continuous <- scale_ycolour_gradient scale_ycolor_continuous <- scale_ycolour_gradient
getFormacaoDoutorado <- function(curriculo) { if (!any(class(curriculo) == 'xml_document')) { stop("The input file must be XML, imported from `xml2` package.", call. = FALSE) } doutorado <- xml2::xml_find_all(curriculo, ".//FORMACAO-ACADEMICA-TITULACAO/DOUTORADO") |> purrr::map(~ xml2::xml_attrs(.)) |> purrr::map(~ dplyr::bind_rows(.)) |> purrr::map(~ janitor::clean_names(.)) doutorado_area <- xml2::xml_find_all(curriculo, ".//FORMACAO-ACADEMICA-TITULACAO/DOUTORADO") |> purrr::map(~ xml2::xml_find_all(., ".//AREAS-DO-CONHECIMENTO")) |> purrr::map(~ xml2::xml_children(.)) |> purrr::map(~ xml2::xml_attrs(.)) |> purrr::map(~ dplyr::bind_rows(.)) |> purrr::map(~ janitor::clean_names(.)) if (nrow(doutorado_area[[1]]) == 0) doutorado_area <- tibble::tibble(nome_grande_area_do_conhecimento = NA, nome_da_area_do_conhecimento = NA, nome_da_sub_area_do_conhecimento = NA, nome_da_especialidade = NA) purrr::pmap(list(doutorado, doutorado_area), function(x, y) tibble::tibble(x, area = list(y))) |> dplyr::bind_rows() |> dplyr::mutate(id = getId(curriculo)) }
set_cartesian <- function(...) { if (nargs() < 2L) return(..1) l <- list(...) if (!all(len <- lengths(l))) return(set()) .make_set_of_tuples_from_list_of_lists(.cartesian_product(l)) } gset_cartesian <- function(...) { if (nargs() < 2L) return(..1) l <- lapply(list(...), as.list) if (isTRUE(all(sapply(l, gset_is_set)))) return(as.gset(set_cartesian(...))) if (any(sapply(l, gset_cardinality) == 0, na.rm = TRUE)) return(gset()) support <- .make_set_of_tuples_from_list_of_lists(.cartesian_product(l)) memberships <- lapply(l, .get_memberships) memberships <- do.call(Map, c("list", .cartesian_product(memberships))) memberships <- if (all(sapply(l, gset_is_crisp, na.rm = TRUE))) sapply(memberships, function(i) prod(unlist(i))) else if (all(sapply(l, gset_is_fuzzy_set, na.rm = TRUE))) { sapply(memberships, function(i) Reduce(.T., unlist(i))) } else { lapply(memberships, function(i) { maxlen <- max(sapply(i, gset_cardinality, na.rm = TRUE)) m <- lapply(i, .expand_membership, len = maxlen, rep = FALSE) mult <- unlist(do.call(Map, c(list(prod), lapply(m, .get_memberships) )) ) S <- Reduce(.T., m) .make_gset_from_support_and_memberships(as.list(S), mult) }) } .make_gset_from_support_and_memberships(support, memberships) } cset_cartesian <- function(...) gset_cartesian(...)
CIBinary <- function(kappa0, kappaL, kappaU=NA, props, raters=2, alpha=0.05) { if ( (raters != 1) && (raters !=2) && (raters !=3) && (raters != 4) && (raters != 5) && (raters != 6) ) stop("Sorry, this function is designed for between 2 to 6 raters.") if (length(props) == 1) { if ((props >= 1) || (props <= 0) ) stop("Sorry, the proportion, props must lie within (0,1).") } if (length(props) == 2) { if ( abs( sum(props) - 1) >= 0.001 ) stop("Sorry, the two proportions must sum to one.") for (i in 1:2) { if ((props[i] >= 1) || (props[i] <= 0) ) stop("Sorry, the proportion, props must lie within (0,1).") } props <- props[1]; } if ((kappa0 >= 1) || (kappa0 <= 0) || (kappaL <= 0) || (kappaL >= 1) ) stop("Sorry, the null and lower values of kappa must lie within (0,1).") if ((!is.na(kappaU)) && ( (kappaU <= 0) || (kappaU >= 1) ) ) stop("Sorry, the upper value of kappa must be either NA for a one-sided test or within (0,1)."); if ( (kappaL >= kappa0) || ( (!is.na(kappaU)) && (kappaU <= kappa0) ) ) stop("Remember, kappaL < kappa0 < kappaU...") if ( (is.na(kappaL)) && (is.na(kappaU)) ) stop("Sorry, at least one of kappaL or kappaU must be specified.") if ( (alpha >= 1) || (alpha <= 0) ) stop("Sorry, the alpha and power must lie within (0,1).") X <- NULL; X$kappa0 <- kappa0; X$kappaL <- kappaL; X$kappaU <- kappaU; X$props <- props; X$raters <- raters; X$alpha <- alpha; if (is.na(kappaU)) { X$ChiCrit <- qchisq((1-2*alpha),1); } if ( (!is.na(kappaL)) && (!is.na(kappaU)) ) { X$ChiCrit <- qchisq((1-alpha),1); } if (raters == 2) { .CalcIT <- function(rho0, rho1, Pi, n) { P0 <- function(r, p) { x <- (1- p)^2 + r*p*(1 - p) return(x) } P1 <- function(r, p) { x <- 2*(1 - r)*p*(1 - p) return(x) } P2 <- function(r, p) { x <- p^2 + r*p*(1 - p) return(x) } Results <- c(0,0,0) Results[1] <- ( (n*P0(r=rho0, p = Pi)) - (n*P0(r=rho1, p = Pi)) )^2/ (n*P0(r=rho1, p = Pi)) Results[2] <- ( (n*P1(r=rho0, p = Pi)) - (n*P1(r=rho1, p = Pi)) )^2/ (n*P1(r=rho1, p = Pi)) Results[3] <- ( (n*P2(r=rho0, p = Pi)) - (n*P2(r=rho1, p = Pi)) )^2/ (n*P2(r=rho1, p = Pi)) return(sum(Results,na.rm=TRUE)) } } if (raters == 3) { .CalcIT <- function(rho0, rho1, Pi, n) { P0 <- function(r, p) { x <- (1- p)^3 + p*r*( (1 - p)^2 + (1 - p) ) return(x) } P1 <- function(r, p) { x <- 3*p*(1 - r)*(1 - p)^2 return(x) } P2 <- function(r, p) { x <- 3*p^2*(1 - p)*(1 - r) return(x) } P3 <- function(r, p) { x <- p^3 + r*p*(1 - p^2) return(x) } Results <- c(0,0,0,0); Results[1] <- ( n*P0(r=rho0, p = Pi) - n*P0(r=rho1, p = Pi) )^2/ (n*P0(r=rho1, p = Pi)) Results[2] <- ( n*P1(r=rho0, p = Pi) - n*P1(r=rho1, p = Pi) )^2/ (n*P1(r=rho1, p = Pi)) Results[3] <- ( n*P2(r=rho0, p = Pi) - n*P2(r=rho1, p = Pi) )^2/ (n*P2(r=rho1, p = Pi)) Results[4] <- ( n*P3(r=rho0, p = Pi) - n*P3(r=rho1, p = Pi) )^2/ (n*P3(r=rho1, p = Pi)) return(sum(Results,na.rm=TRUE)) } } if (raters == 4) { .CalcIT <- function(rho0, rho1, Pi, n) { P0 <- function(r, p) { x <- p^4 -r*p^4 -4*p^3 +4*r*p^3 +6*p^2 -6*r*p^2 -4*p +3*r*p +1 return(x) } P1 <- function(r, p) { x <- (4*(1-3*p-r+3*r*p+3*p^2-3*r*p^2-p^3+r*p^3))*p return(x) } P2 <- function(r, p) { x <- -(6*(-1+r+2*p-2*r*p-p^2+r*p^2))*p^2 return(x) } P3 <- function(r, p) { x <- (4*(1-r-p+r*p))*p^3 return(x) } P4 <- function(r,p) { x <- -(-p^3-r+r*p^3)*p return(x) } Results <- c(0,0,0,0,0); Results[1] <- ( n*P0(r=rho0, p = Pi) - n*P0(r=rho1, p = Pi) )^2/ (n*P0(r=rho1, p = Pi)) Results[2] <- ( n*P1(r=rho0, p = Pi) - n*P1(r=rho1, p = Pi) )^2/ (n*P1(r=rho1, p = Pi)) Results[3] <- ( n*P2(r=rho0, p = Pi) - n*P2(r=rho1, p = Pi) )^2/ (n*P2(r=rho1, p = Pi)) Results[4] <- ( n*P3(r=rho0, p = Pi) - n*P3(r=rho1, p = Pi) )^2/ (n*P3(r=rho1, p = Pi)) Results[5] <- ( n*P4(r=rho0, p = Pi) - n*P4(r=rho1, p = Pi) )^2/ (n*P4(r=rho1, p = Pi)) return(sum(Results,na.rm=TRUE)) } } if (raters == 5) { .CalcIT <- function(rho0, rho1, Pi, n) { P0 <- function(r, p) { x <- -p^5+r*p^5+5*p^4-5*r*p^4+10*r*p^3-10*p^3-10*r*p^2+10*p^2+4*r*p-5*p+1 return(x) } P1 <- function(r, p) { x <- -(5*(-1+4*p+r-4*r*p-6*p^2+6*r*p^2+4*p^3-4*r*p^3-p^4+r*p^4))*p return(x) } P2 <- function(r, p) { x <- (10*(1-r-3*p+3*r*p+3*p^2-3*r*p^2-p^3+r*p^3))*p^2 return(x) } P3 <- function(r, p) { x <- -(10*(-1+r+2*p-2*r*p-p^2+r*p^2))*p^3 return(x) } P4 <- function(r,p) { x <- (5*(1-r-p+r*p))*p^4 return(x) } P5 <- function(r,p) { x <- -(-p^4-r+r*p^4)*p return(x) } Results <- c(0,0,0,0,0,0); Results[1] <- ( n*P0(r=rho0, p = Pi) - n*P0(r=rho1, p = Pi) )^2/ (n*P0(r=rho1, p = Pi)) Results[2] <- ( n*P1(r=rho0, p = Pi) - n*P1(r=rho1, p = Pi) )^2/ (n*P1(r=rho1, p = Pi)) Results[3] <- ( n*P2(r=rho0, p = Pi) - n*P2(r=rho1, p = Pi) )^2/ (n*P2(r=rho1, p = Pi)) Results[4] <- ( n*P3(r=rho0, p = Pi) - n*P3(r=rho1, p = Pi) )^2/ (n*P3(r=rho1, p = Pi)) Results[5] <- ( n*P4(r=rho0, p = Pi) - n*P4(r=rho1, p = Pi) )^2/ (n*P4(r=rho1, p = Pi)) Results[6] <- ( n*P5(r=rho0, p = Pi) - n*P5(r=rho1, p = Pi) )^2/ (n*P5(r=rho1, p = Pi)) return(sum(Results,na.rm=TRUE)) } } if (raters == 6) { .CalcIT <- function(rho0, rho1, Pi, n) { P0 <- function(r, p) { x <- p^6-r*p^6+6*r*p^5-6*p^5-15*r*p^4+15*p^4+20*r*p^3-20*p^3-15*r*p^2+15*p^2+5*r*p-6*p+1 return(x) } P1 <- function(r, p) { x <- (6*(1-5*p-r+5*r*p+10*p^2-10*r*p^2-10*p^3+10*r*p^3+5*p^4-5*r*p^4-p^5+r*p^5))*p return(x) } P2 <- function(r, p) { x <- -(15*(-1+r+4*p-4*r*p-6*p^2+6*r*p^2+4*p^3-4*r*p^3-p^4+r*p^4))*p^2 return(x) } P3 <- function(r, p) { x <- (20*(1-r-3*p+3*r*p+3*p^2-3*r*p^2-p^3+r*p^3))*p^3 return(x) } 0 P4 <- function(r,p) { x <- -(15*(-1+r+2*p-2*r*p-p^2+r*p^2))*p^4 return(x) } P5 <- function(r,p) { x <- (6*(1-r-p+r*p))*p^5 return(x) } P6 <- function(r,p) { x <- -(-p^5-r+r*p^5)*p return(x) } Results <- c(0,0,0,0,0,0,0); Results[1] <- ( n*P0(r=rho0, p = Pi) - n*P0(r=rho1, p = Pi) )^2/ (n*P0(r=rho1, p = Pi)) Results[2] <- ( n*P1(r=rho0, p = Pi) - n*P1(r=rho1, p = Pi) )^2/ (n*P1(r=rho1, p = Pi)) Results[3] <- ( n*P2(r=rho0, p = Pi) - n*P2(r=rho1, p = Pi) )^2/ (n*P2(r=rho1, p = Pi)) Results[4] <- ( n*P3(r=rho0, p = Pi) - n*P3(r=rho1, p = Pi) )^2/ (n*P3(r=rho1, p = Pi)) Results[5] <- ( n*P4(r=rho0, p = Pi) - n*P4(r=rho1, p = Pi) )^2/ (n*P4(r=rho1, p = Pi)) Results[6] <- ( n*P5(r=rho0, p = Pi) - n*P5(r=rho1, p = Pi) )^2/ (n*P5(r=rho1, p = Pi)) Results[7] <- ( n*P6(r=rho0, p = Pi) - n*P6(r=rho1, p = Pi) )^2/ (n*P6(r=rho1, p = Pi)) return(sum(Results,na.rm=TRUE)) } } n <- 10; if ( (!is.na(kappaL)) && (!is.na(kappaU)) ) { resultsl <- 0; resultsu <- 0; while ( (abs(resultsl - 0.001) < X$ChiCrit) || (abs(resultsu - 0.001) < X$ChiCrit) ) { n <- n + 1; resultsl <- .CalcIT(rho0=kappa0, rho1 = kappaL, Pi=props, n=n) resultsu <- .CalcIT(rho0=kappa0, rho1 = kappaU, Pi=props, n=n) if (is.infinite(resultsu)) { resultsu <- 0 } if (is.infinite(resultsl)) { resultsl <- 0 } } } if (is.na(kappaU)) { resultsl <- 0; while (abs(resultsl - 0.001) < X$ChiCrit) { n <- n + 1; resultsl <- .CalcIT(rho0=kappa0, rho1 = kappaL, Pi=props, n=n) if (is.infinite(resultsl)) { resultsl <- 0 } } } X$n <- n; class(X) <- "CIBinary"; return(X); } print.CIBinary <- function(x, ...) { cat("A minimum of", max(x$n, x$n), "subjects are required for this study of interobserver agreement. \n") for (i in 1:length(x$props)) { if (x$props[i] * x$n < 5) { cat("Warning: At least one expected cell count is less than five. \n") } } } summary.CIBinary <- function(object, ...) { cat("Confidence-Interval Based Sample Size Estimation for \n") cat("Studies of Interobserver Agreement with a Binary Outcome \n \n") cat("Assuming:", "\n") cat("Kappa0:", object$kappa0, "\n") cat("KappaL:", object$kappaL, "\n") cat("KappaU:", object$kappaU, "\n") cat("Event Proportion:", object$props, "\n") cat("Type I Error Rate (alpha) = ", object$alpha, "\n \n") if (is.na(object$kappaU)) { cat("A minimum of", ceiling(object$n), "subjects are required to ensure the lower \n") cat("confidence limit is at least ", object$kappaL, ". \n \n", sep="") for (i in 1:length(object$props)) { if (object$props[i] * object$n < 5) { cat("Warning: At least one expected cell count is less than five. \n") } } } if ( (!is.na(object$kappaL)) && (!is.na(object$kappaU)) ) { cat("A minimum of", ceiling(object$n), "subjects are required to ensure the lower \n") cat("confidence limit is at least", object$kappaL, "and the upper confidence \n") cat("limit does not exceed ", object$kappaU, ". \n \n", sep="") for (i in 1:length(object$props)) { if (object$props[i] * object$n < 5) { cat("Warning: At least one expected cell count is less than five. \n") } } } }
getCutoffNonNested <- function(dat1Mod1, dat1Mod2, dat2Mod1 = NULL, dat2Mod2 = NULL, alpha = 0.05, usedFit = NULL, onetailed = FALSE, nVal = NULL, pmMCARval = NULL, pmMARval = NULL, df = 0) { usedFit <- cleanUsedFit(usedFit, colnames(dat1Mod1@fit), colnames(dat1Mod2@fit)) mod1 <- clean(dat1Mod1, dat1Mod2) dat1Mod1 <- mod1[[1]] dat1Mod2 <- mod1[[2]] if (!isTRUE(all.equal(unique(dat1Mod1@paramValue), unique(dat1Mod2@paramValue)))) stop("'dat1Mod1' and 'dat1Mod2' are based on different data and cannot be compared, check your random seed") if (!is.null(dat2Mod1) & !is.null(dat2Mod2)) { mod2 <- clean(dat2Mod1, dat2Mod2) dat2Mod1 <- mod2[[1]] dat2Mod2 <- mod2[[2]] if (!isTRUE(all.equal(unique(dat2Mod1@paramValue), unique(dat2Mod2@paramValue)))) stop("'dat2Mod1' and 'dat2Mod2' are based on different data and cannot be compared, check your random seed") if (!multipleAllEqual(unique(dat1Mod1@n), unique(dat1Mod2@n), unique(dat2Mod1@n), unique(dat2Mod2@n))) stop("Models are based on different values of sample sizes") if (!multipleAllEqual(unique(dat1Mod1@pmMCAR), unique(dat1Mod2@pmMCAR), unique(dat2Mod1@pmMCAR), unique(dat2Mod2@pmMCAR))) stop("Models are based on different values of the percent completely missing at random") if (!multipleAllEqual(unique(dat1Mod1@pmMAR), unique(dat1Mod2@pmMAR), unique(dat2Mod1@pmMAR), unique(dat2Mod2@pmMAR))) stop("Models are based on different values of the percent missing at random") } else { if (!isTRUE(all.equal(unique(dat1Mod1@n), unique(dat1Mod2@n)))) stop("Models are based on different values of sample sizes") if (!isTRUE(all.equal(unique(dat1Mod1@pmMCAR), unique(dat1Mod2@pmMCAR)))) stop("Models are based on different values of the percent completely missing at random") if (!isTRUE(all.equal(unique(dat1Mod1@pmMAR), unique(dat1Mod2@pmMAR)))) stop("Models are based on different values of the percent missing at random") } if (is.null(nVal) || is.na(nVal)) nVal <- NULL if (is.null(pmMCARval) || is.na(pmMCARval)) pmMCARval <- NULL if (is.null(pmMARval) || is.na(pmMARval)) pmMARval <- NULL Data1 <- as.data.frame((dat1Mod1@fit - dat1Mod2@fit)) Data2 <- NULL if (!is.null(dat2Mod1) & !is.null(dat2Mod2)) Data2 <- as.data.frame((dat2Mod1@fit - dat2Mod2@fit)) condition <- c(length(unique(dat1Mod1@pmMCAR)) > 1, length(unique(dat1Mod1@pmMAR)) > 1, length(unique(dat1Mod1@n)) > 1) condValue <- cbind(dat1Mod1@pmMCAR, dat1Mod1@pmMAR, dat1Mod1@n) colnames(condValue) <- c("Percent MCAR", "Percent MAR", "N") condValue <- condValue[, condition] if (is.null(condValue) || length(condValue) == 0) condValue <- NULL predictorVal <- rep(NA, 3) if (condition[3]) { ifelse(is.null(nVal), stop("Please specify the sample size value, 'nVal', because the sample size in the result object is varying"), predictorVal[3] <- nVal) } if (condition[1]) { ifelse(is.null(pmMCARval), stop("Please specify the percent of completely missing at random, 'pmMCARval', because the percent of completely missing at random in the result object is varying"), predictorVal[1] <- pmMCARval) } if (condition[2]) { ifelse(is.null(pmMARval), stop("Please specify the percent of missing at random, 'pmMARval', because the percent of missing at random in the result object is varying"), predictorVal[2] <- pmMARval) } predictorVal <- predictorVal[condition] result <- list() if (onetailed) { cutoffDat1 <- getCutoffDataFrame(Data1, alpha, FALSE, usedFit, predictor = condValue, predictorVal = predictorVal, df = df) bound <- rep(-Inf, length(cutoffDat1)) bound[names(cutoffDat1) %in% getKeywords()$reversedFit] <- Inf resultModel1 <- rbind(bound, cutoffDat1) resultModel1 <- apply(resultModel1, 2, sort) rownames(resultModel1) <- c("lower", "upper") result$model1 <- resultModel1 if (!is.null(dat2Mod1) & !is.null(dat2Mod2)) { cutoffDat2 <- getCutoffDataFrame(Data2, 1 - alpha, FALSE, usedFit, predictor = condValue, predictorVal = predictorVal, df = df) bound <- rep(Inf, length(cutoffDat2)) bound[names(cutoffDat2) %in% getKeywords()$reversedFit] <- -Inf resultModel2 <- rbind(bound, cutoffDat2) resultModel2 <- apply(resultModel2, 2, sort) rownames(resultModel2) <- c("lower", "upper") result$model2 <- resultModel2 } } else { lower <- alpha/2 upper <- 1 - (alpha/2) cutoffDat1Low <- getCutoffDataFrame(Data1, lower, FALSE, usedFit, predictor = condValue, predictorVal = predictorVal, df = df) cutoffDat1High <- getCutoffDataFrame(Data1, upper, FALSE, usedFit, predictor = condValue, predictorVal = predictorVal, df = df) resultModel1 <- rbind(cutoffDat1Low, cutoffDat1High) resultModel1 <- apply(resultModel1, 2, sort) rownames(resultModel1) <- c("lower", "upper") result$model1 <- resultModel1 if (!is.null(dat2Mod1) & !is.null(dat2Mod2)) { cutoffDat2Low <- getCutoffDataFrame(Data2, lower, FALSE, usedFit, predictor = condValue, predictorVal = predictorVal, df = df) cutoffDat2High <- getCutoffDataFrame(Data2, upper, FALSE, usedFit, predictor = condValue, predictorVal = predictorVal, df = df) resultModel2 <- rbind(cutoffDat2Low, cutoffDat2High) resultModel2 <- apply(resultModel2, 2, sort) rownames(resultModel2) <- c("lower", "upper") result$model2 <- resultModel2 } } return(result) }
plot.dist.matrix <- function (x, y, labels=rownames(x), show.labels=TRUE, label.pos=3, selected=attr(x, "selected"), show.selected=TRUE, col="black", cex=1, pch=20, pt.cex=1.2, selected.cex=1.2, selected.col="red", show.edges=TRUE, edges.lwd=6, edges.col=" stopifnot(inherits(x, "dist.matrix")) if (!missing(y)) stop("plot.dist.matrix() doesn't take a second argument (y)") if (!isTRUE(attr(x, "symmetric"))) stop("only symmetric distance matrices can be plotted") if (isTRUE(attr(x, "similarity"))) stop("similarity matrices are not supported. Please provide a distance matrix for this plot.") method <- match.arg(method) if (is.null(labels)) { show.labels <- FALSE } else { if (length(labels) != nrow(x)) stop("wrong number of labels specified") } coords <- if (method == "isomds") isoMDS(x, k=2, trace=FALSE)$points else sammon(x, k=2, trace=FALSE)$points x.range <- extendrange(coords[, 1], f=expand) y.range <- extendrange(coords[, 2], f=expand) .asp <- diff(x.range) / diff(y.range) if (.asp < aspect) { x.range <- extendrange(x.range, f=(aspect/.asp-1)/2) } else if (.asp > aspect) { y.range <- extendrange(y.range, f=(.asp/aspect-1)/2) } plot(coords, type="n", xlim=x.range, ylim=y.range, xlab="", ylab="", xaxs="i", yaxs="i", xaxt="n", yaxt="n", ...) if (show.edges) { midx <- t(combn(1:nrow(x), 2)) P1 <- midx[, 1] P2 <- midx[, 2] len <- x[midx] lwd.vec <- edges.lwd * (1 - len / edges.threshold) idx <- lwd.vec > 0.1 segments(coords[P1[idx], 1], coords[P1[idx], 2], coords[P2[idx], 1], coords[P2[idx], 2], lwd=lwd.vec[idx], col=edges.col) } if (is.null(selected) || !show.selected) selected <- rep(FALSE, nrow(x)) col.vec <- ifelse(selected, selected.col, col) cex.vec <- cex * pt.cex * ifelse(selected, selected.cex, 1) points(coords, pch=pch, col=col.vec, cex=cex.vec) if (show.labels) { cex.vec <- cex * ifelse(selected, selected.cex, 1) text(coords[, 1], coords[, 2], labels=labels, pos=label.pos, font=2, cex=cex.vec, col=col.vec) } if (!is.null(labels)) rownames(coords) <- labels invisible(coords) }
addBackTile <- function(tileFilename, libForMosaic, libForMosaicFull) { lib <- rbind(libForMosaic, libForMosaicFull[which(libForMosaicFull[,1]==tileFilename),]) rownames(lib) <- NULL return(lib) }
test_that("Bad data results in error", { expect_error(cpp_edge_to_splits(matrix(1, 3, 3), 3)) expect_error(cpp_edge_to_splits(matrix(1, 10, 2), 0)) expect_error(cpp_edge_to_splits(matrix(1, 10, 2), -10)) expect_error(cpp_edge_to_splits(matrix(1, 2, 2), 6)) })
plot_dotbar_sd_sc <- function(data, xcol, ycol, colour = "ok_orange", dotsize = 1.5, dotthick = 1, bwid = 0.7, ewid = 0.2, b_alpha = 1, d_alpha = 1, TextXAngle = 0, fontsize = 20, ...){ ifelse(grepl(" a <- colour, a <- get_graf_colours({{ colour }})) ggplot2::ggplot(data, aes(x = factor({{ xcol }}), y = {{ ycol }}))+ stat_summary(geom = "bar", colour = "black", width = {{ bwid }}, fun = "mean", alpha = {{ b_alpha }}, size = 1, fill = a)+ geom_dotplot(dotsize = {{ dotsize }}, stroke = {{ dotthick }}, binaxis = 'y', alpha = {{ d_alpha }}, stackdir = 'center', fill = a, ...)+ stat_summary(geom = "errorbar", size = 1, fun.data = "mean_sdl", fun.args = list(mult = 1), width = {{ ewid }}) + labs(x = enquo(xcol))+ theme_classic(base_size = {{ fontsize }})+ theme(strip.background = element_blank())+ guides(x = guide_axis(angle = {{ TextXAngle }})) }
context("Check standarize call with formals") test_that("Standarize call with formals primitive function", { user <- rlang::get_expr(quote(mean(1:3, na.rm = TRUE))) user_stand <- call_standardise_formals(user) testthat::expect_equal(user_stand, call("mean", x = 1:3, na.rm = TRUE)) user <- quote(mean(1:3, 0, TRUE)) user_stand <- call_standardise_formals(user) testthat::expect_equal(user_stand, call("mean", x = 1:3, 0, TRUE)) }) test_that("Standarize call with formals user function", { my_func <- function(x, y, z=100, a = TRUE, b = 3.14, c = "s", ...) {x + y + z + b} user <- rlang::get_expr(quote(my_func(x = 1, 20))) user_stand <- gradethis:::call_standardise_formals(user, env = rlang::env(my_func = my_func)) testthat::expect_equal(user_stand, call("my_func", x = 1, y = 20, z = 100, a = TRUE, b = 3.14, c = "s")) }) test_that("Standarize call with ... and kwargs", { a <- quote(vapply(list(1:3, 4:6), mean, numeric(1), 0, TRUE)) b <- quote(vapply(list(1:3, 4:6), mean, numeric(1), trim = 0, TRUE)) c <- quote(vapply(list(1:3, 4:6), mean, numeric(1), 0, na.rm = TRUE)) d <- quote(vapply(list(1:3, 4:6), mean, numeric(1), trim = 0, na.rm = TRUE)) xa <- quote(vapply(X = list(1:3, 4:6), FUN = mean, FUN.VALUE = numeric(1), 0, TRUE, USE.NAMES = TRUE)) xb <- quote(vapply(X = list(1:3, 4:6), FUN = mean, FUN.VALUE = numeric(1), trim = 0, TRUE, USE.NAMES = TRUE)) xc <- quote(vapply(X = list(1:3, 4:6), FUN = mean, FUN.VALUE = numeric(1), 0, na.rm = TRUE, USE.NAMES = TRUE)) xd <- quote(vapply(X = list(1:3, 4:6), FUN = mean, FUN.VALUE = numeric(1), trim = 0, na.rm = TRUE, USE.NAMES = TRUE)) testthat::expect_equal(call_standardise_formals(a), xa) testthat::expect_equal(call_standardise_formals(b), xb) testthat::expect_equal(call_standardise_formals(c), xc) testthat::expect_equal(call_standardise_formals(d), xd) a <- quote(vapply(list(1:3, 4:6), mean, numeric(1), 0, USE.NAMES = TRUE, TRUE)) b <- quote(vapply(list(1:3, 4:6), mean, numeric(1), trim = 0, USE.NAMES = TRUE, TRUE)) c <- quote(vapply(list(1:3, 4:6), mean, numeric(1), 0, USE.NAMES = TRUE, na.rm = TRUE)) d <- quote(vapply(list(1:3, 4:6), mean, numeric(1), trim = 0, USE.NAMES = TRUE, na.rm = TRUE)) testthat::expect_equal(call_standardise_formals(a), xa) testthat::expect_equal(call_standardise_formals(b), xb) testthat::expect_equal(call_standardise_formals(c), xc) testthat::expect_equal(call_standardise_formals(d), xd) }) test_that("When an invalid function passed (i.e., corrupt language object)", { user <- quote(1(a(1))) testthat::expect_equal( call_standardise_formals(user), user) }) test_that("Standarize call with include_defaults = FALSE", { library(purrr) user <- rlang::get_expr(quote(insistently(mean,quiet = TRUE))) user_stand <- gradethis:::call_standardise_formals(user) user_stand_mini <- gradethis:::call_standardise_formals(user,include_defaults = FALSE) testthat::expect_equal( user_stand_mini, quote(insistently(f = mean, quiet = TRUE)) ) testthat::expect_equal( user_stand, quote(insistently(f = mean,rate = rate_backoff(), quiet = TRUE)) ) })
library(grid) HersheyLabel <- function(x, y=unit(.5, "npc")) { lines <- strsplit(x, "\n")[[1]] if (!is.unit(y)) y <- unit(y, "npc") n <- length(lines) if (n > 1) { y <- y + unit(rev(seq(n)) - mean(seq(n)), "lines") } grid.text(lines, y=y, gp=gpar(fontfamily="HersheySans")) } grid.newpage() pushViewport(viewport(clip=circleGrob())) grid.rect(gp=gpar(fill="grey")) HersheyLabel("push circle clipping path rect grey circle") grid.newpage() pushViewport(viewport(width=.5, height=.5, clip=TRUE)) grid.circle(r=.6, gp=gpar(fill="grey")) HersheyLabel("push clipping rect circle squared circle") grid.newpage() pushViewport(viewport(clip=circleGrob(1:2/3, r=unit(.5, "in")))) grid.rect(gp=gpar(fill="grey")) popViewport() HersheyLabel("push two circles clipping path rect two circles") grid.newpage() pushViewport(viewport(width=.5, height=.5, clip=polygonGrob(c(.2, .4, .6, .2), c(.2, .6, .4, .1)))) grid.rect(gp=gpar(fill="grey")) popViewport() HersheyLabel("push clipping path rect grey wedge") grid.newpage() pushViewport(viewport(width=.5, height=.6, angle=45, clip=rectGrob())) grid.circle(r=.6, gp=gpar(fill="grey")) HersheyLabel("push rotated viewport with clipping path circle square-sided circle") grid.newpage() pushViewport(viewport(clip=circleGrob(1:2/3, r=unit(.5, "in")), gp=gpar(fill=linearGradient()))) grid.rect() popViewport() HersheyLabel("push clipping path gradient on viewport two circles (one gradient)") grid.newpage() pushViewport(viewport(clip=circleGrob(1:2/3, r=unit(.5, "in")))) grid.rect(gp=gpar(fill=linearGradient())) popViewport() HersheyLabel("push clipping path rect with gradient two circles (one gradient)") grid.newpage() pushViewport(viewport(clip=circleGrob())) pushViewport(viewport()) grid.rect(gp=gpar(fill="grey")) HersheyLabel("push clipping path push again (inherit clip path) rect grey circle") grid.newpage() pushViewport(viewport(clip=circleGrob())) pushViewport(viewport()) pushViewport(viewport()) upViewport() grid.rect(gp=gpar(fill="grey")) HersheyLabel("push clipping path push again (inherit clip path) push again (inherit clip path) up (restore inherited clip path) rect grey circle") grid.newpage() pushViewport(viewport(clip=circleGrob())) grid.rect(gp=gpar(fill="grey")) upViewport() grid.rect(gp=gpar(fill=rgb(0,0,1,.2))) HersheyLabel("push clipping path grey circle upViewport page all (translucent) blue") grid.newpage() pushViewport(viewport(clip=circleGrob(), name="vp")) grid.rect(height=.5, gp=gpar(fill="grey")) upViewport() downViewport("vp") grid.rect(gp=gpar(fill=rgb(0,0,1,.2))) HersheyLabel("push clipping path rounded rect upViewport downViewport blue (translucent) circle") grid.newpage() pushViewport(viewport(width=.5, height=.5, clip=TRUE)) pushViewport(viewport(clip=circleGrob())) grid.rect(gp=gpar(fill="grey")) upViewport() grid.circle(r=.6, gp=gpar(fill=rgb(0,0,1,.2))) HersheyLabel("push clipping rect push clipping path grey circle upViewport squared (translucent) blue circle") grid.newpage() pushViewport(viewport(clip=circleGrob())) pushViewport(viewport(width=.5, height=.5, clip=TRUE)) grid.circle(r=.6, gp=gpar(fill="grey")) upViewport() grid.rect(gp=gpar(fill=rgb(0,0,1,.2))) HersheyLabel("push clipping path push clipping rect squared circle upViewport grey (translucent) blue circle") grid.newpage() pushViewport(viewport(width=.5, height=.5, clip=TRUE)) grid.rect() pushViewport(viewport(clip=circleGrob(r=.6))) grid.rect(width=1.2, height=1.2, gp=gpar(fill=rgb(0,0,1,.2))) HersheyLabel("push clip rect (small) rect push clip path (bigger) rect (big) blue (translucent) circle") grid.newpage() pushViewport(viewport(width=.5, height=.5, clip=TRUE)) grid.rect() pushViewport(viewport(clip=circleGrob(r=.6, vp=viewport()))) grid.rect(width=1.2, height=1.2, gp=gpar(fill=rgb(0,0,1,.2))) HersheyLabel("push clip rect (small) rect push clip path with viewport (bigger) rect (big) blue (translucent) circle") grid.newpage() pushViewport(viewport(clip=circleGrob())) grid.rect(gp=gpar(fill="grey")) HersheyLabel("push clip path rect grey circle (for resizing)") grid.newpage() pushViewport(viewport(clip=circleGrob())) grid.rect(gp=gpar(fill="grey")) x <- recordPlot() HersheyLabel("push clip path rect grey circle (for recording)") print(x) HersheyLabel("push clip path rect record plot replay plot grey circle") grid.newpage() pushViewport(viewport(clip=circleGrob())) grid.rect(gp=gpar(fill="grey")) HersheyLabel("push clip path rect grey circle (for grid.grab)") x <- grid.grab() grid.newpage() grid.draw(x) HersheyLabel("push clip path rect grey circle grid.grab grid.draw grey circle") grid.newpage() path <- circleGrob(r=.6, vp=viewport(width=.5, height=.5, clip=TRUE)) pushViewport(viewport(clip=path)) grid.rect(gp=gpar(fill="grey")) popViewport() HersheyLabel("clipping path is circle with viewport with clip=TRUE AND circle is larger than viewport BUT viewport clipping is ignored within clipping path SO clipping path is just circle draw rect result is grey circle") grid.newpage() path <- circleGrob(vp=viewport(clip=rectGrob(width=.8, height=.8))) pushViewport(viewport(clip=path)) grid.rect(gp=gpar(fill="grey")) popViewport() HersheyLabel("clip path is circle with viewport with clip path viewport clip path is rect that squares off the circle BUT clip paths are ignored within clipping path (with warning) SO clipping path is just circle draw rect result is grey circle") grid.newpage() path <- circleGrob(vp=viewport(mask=rectGrob(width=.8, height=.8, gp=gpar(fill="black")))) pushViewport(viewport(clip=path)) grid.rect(gp=gpar(fill="grey")) popViewport() HersheyLabel("clip path is circle with viewport with mask viewport mask is rect that squares off the circle BUT masks are ignored within clipping path (with warning) SO clipping path is just circle draw rect result is grey circle") grid.newpage() path <- circleGrob(vp=viewport(mask=rectGrob(width=.8, height=.8, gp=gpar(fill="black")))) pushViewport(viewport(clip=path, name="test")) upViewport() downViewport("test") grid.rect(gp=gpar(fill="grey")) popViewport() HersheyLabel("same as previous test EXCEPT that push viewport then pop then down (and only push should warn) draw rect result is grey circle") grid.newpage() g <- gTree(cl="test") makeContent.test <- function(x) { setChildren(x, gList(rectGrob(gp=gpar(fill="grey"), vp=viewport(clip=circleGrob())))) } grid.draw(g) HersheyLabel("custom grob class with makeContent() method makeContent() adds rectangle with viewport viewport has circle clip path result is grey circle") grid.newpage() path <- gTree(cl="test") makeContent.test <- function(x) { setChildren(x, gList(circleGrob())) } pushViewport(viewport(clip=path)) grid.rect(gp=gpar(fill="grey")) popViewport() HersheyLabel("push viewport with clip path clip path is grob with makeContent() method makeContent() adds circle draw rect result is grey circle") grid.newpage() pushViewport(viewport(clip=circleGrob())) grid.rect(gp=gpar(fill="grey")) x <- recordPlot() HersheyLabel("push circle clipping path rect grey circle (for save(recordPlot()))") f <- tempfile() saveRDS(x, file=f) grid.newpage() y <- readRDS(f) replayPlot(y) HersheyLabel("push circle clipping path rect grey circle saveRDS(recordPlot()) replayPlot(readRDS())") grid.newpage() tg <- textGrob("testing", gp=gpar(fontface="bold", cex=4)) pushViewport(viewport(clip=tg)) grid.rect(gp=gpar(fill="grey")) grid.rect(width=.1, gp=gpar(fill="2")) popViewport() HersheyLabel("clipping path from text grey rect clipped to text thin red rect (black border) also clipped to text", y=.9) grid.newpage() gt <- gTree(children=gList(circleGrob(), textGrob("testing", gp=gpar(fontface="bold", cex=4)), rectGrob(width=.8, height=.5))) pushViewport(viewport(clip=as.path(gt, rule="evenodd"))) grid.rect(gp=gpar(fill="grey")) grid.rect(width=.1, gp=gpar(fill="2")) popViewport() HersheyLabel("clipping path based on circle and text and rect with even-odd rule draw large grey rect and thin red rect both clipped to text and space between circle and rect (PDF will NOT include text in clipping path", y=.85) grid.newpage() gt <- gTree(children=gList(textGrob("testing", gp=gpar(fontface="bold", cex=4)), circleGrob(), rectGrob(width=.8, height=.5))) pushViewport(viewport(clip=as.path(gt, rule="evenodd"))) grid.rect(gp=gpar(fill="grey")) grid.rect(width=.1, gp=gpar(fill="2")) popViewport() HersheyLabel("clipping path based on text and circle and rect with even-odd rule draw large grey rect and thin red rect both clipped to text and space between circle and rect (PDF will ONLY include text in clipping path", y=.85) grid.newpage() for (i in 1:65) { pushViewport(viewport(clip=circleGrob())) grid.rect(gp=gpar(fill="grey")) HersheyLabel(paste0("viewport ", i, " with clip path result is grey circle")) upViewport() } grid.newpage() grid.text("testing", gp=gpar(col="grey", cex=3)) path <- circleGrob(r=.05, gp=gpar(fill=NA)) grid.draw(path) pushViewport(viewport(clip=path)) grid.text("testing", gp=gpar(cex=3)) popViewport() HersheyLabel("text clipped by circle", y=.8) grid.newpage() grid.raster(matrix(c(.5, 1, 1, .5), nrow=2), width=.2, height=.2, interpolate=FALSE) path <- circleGrob(r=.05, gp=gpar(fill=NA)) grid.draw(path) pushViewport(viewport(clip=path)) grid.raster(matrix(c(0:1, 1:0), nrow=2), width=.2, height=.2, interpolate=FALSE) popViewport() HersheyLabel("raster clipped by circle", y=.8)
permGamma = function(target, dataset, xIndex, csIndex, wei = NULL, univariateModels = NULL , hash = FALSE, stat_hash = NULL, pvalue_hash = NULL, threshold = 0.05, R = 999) { pvalue = log(1) stat = 0; csIndex[which(is.na(csIndex))] = 0; thres <- threshold * R + 1 if( hash ) { csIndex2 = csIndex[which(csIndex!=0)] csIndex2 = sort(csIndex2) xcs = c(xIndex,csIndex2) key = paste(as.character(xcs) , collapse=" "); if ( !is.null(stat_hash[key]) ) { stat = stat_hash[key]; pvalue = pvalue_hash[key]; results <- list(pvalue = pvalue, stat = stat, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); } } if ( !is.na( match(xIndex, csIndex) ) ) { if( hash ) { stat_hash[key] <- 0; pvalue_hash[key] <- 1; } results <- list(pvalue = 1, stat = 0, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); } if( any(xIndex < 0) || any(csIndex < 0) ) { message(paste("error in testIndPois : wrong input of xIndex or csIndex")) results <- list(pvalue = pvalue, stat = stat, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); } xIndex = unique(xIndex); csIndex = unique(csIndex); x = dataset[ , xIndex]; cs = dataset[ , csIndex]; if ( length(cs)!=0 ) { if ( is.null(dim(cs)[2]) ) { if ( identical(x, cs) ) { if ( hash ) { stat_hash[key] <- 0; pvalue_hash[key] <- 1; } results <- list(pvalue = 1, stat = 0, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); } } else { for (col in 1:dim(cs)[2]) { if ( identical(x, cs[, col]) ) { if ( hash ) { stat_hash[key] <- 0; pvalue_hash[key] <- 1; } results <- list(pvalue = 1, stat = 0, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); } } } } if (length(cs) == 0) { fit2 = glm(target ~ x, family = Gamma(link = log), weights = wei, model = FALSE) dev2 <- fit2$deviance stat <- fit2$null.deviance - dev2 if (stat > 0) { step <- 0 j <- 1 n <- length(target) while (j <= R & step < thres ) { xb <- sample(x, n) bit2 <- glm(target ~ xb, family = Gamma(link = log), weights = wei, model = FALSE) step <- step + ( bit2$deviance < dev2 ) j <- j + 1 } pvalue <- log( (step + 1) / (R + 1) ) } else pvalue <- log(1) } else { fit1 = glm(target ~ cs, family = Gamma(link = log), weights = wei, model = FALSE) fit2 = glm(target ~ cs + x, family = Gamma(link = log), weights = wei, model = FALSE) dev2 <- fit2$deviance stat = fit1$deviance - dev2 if ( stat > 0 ) { step <- 0 j <- 1 n <- length(target) while (j <= R & step < thres ) { xb <- sample(x, n) bit2 <- glm(target ~ cs + xb, family = Gamma(link = log), weights = wei, model = FALSE) step <- step + ( bit2$deviance < dev2 ) j <- j + 1 } pvalue <- log( (step + 1) / (R + 1) ) } else pvalue <- log(1) } if ( is.na(pvalue) || is.na(stat) ) { pvalue = log(1) stat = 0; } else { if ( hash ) { stat_hash[key] <- stat; pvalue_hash[key] <- pvalue; } } results <- list(pvalue = pvalue, stat = stat, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); }
phi.mult.it<-function(beta.0,y,Xk,M,u1,u2){ D=nrow(y) k=ncol(y) d=nrow(u1) t=D/d theta.ol=matrix(0,D,(k-1)) prmul=prmu.time(M,Xk,beta.0,u1,u2) theta=prmul[[3]] for (i in 1:(k-1)){ for (j in 1:D){ if ((y[j,i]==0) |(y[j,k]==0)) {theta.ol[j,i]=log(y[j,i]+1/(y[j,k]+1))} else {theta.ol[j,i]=log(y[j,i]/y[j,k])}}} dif=(theta-theta.ol)^2 phi1.new=colSums(dif)/(2*(D-1)) return(phi.0=phi1.new) } initial.values<-function(d,pp,datar,mod){ Xk=datar$Xk M=datar$n resp=datar$y k=ncol(resp) D=nrow(resp) beta=beta.new=list() for (i in 1:(k-1)){ dep=cbind(round(resp[,i]),round(rowSums(resp)-resp[,i])) mod1=glm(dep ~ (Xk[[i]])-1,family=binomial) tt=coef(mod1) beta[[i]]=as.matrix(tt) beta.new[[i]]=(beta[[i]]) } u=list() for (i in 1:(k-1)){ u[[i]]=as.matrix((1:(pp[i]+1))) rownames(beta.new[[i]])=u[[i]]} if (mod==1){ phi.new=phi.mult(beta.new,datar$y,datar$Xk,datar$n) phi.new=as.vector(phi.new) u.new=rep(0.5,((k-1)*D)) dim(u.new)=c(D,k-1) result=list(beta.0=beta.new,phi.0=phi.new,u.0=u.new)} if (mod==2){ u1.new=rep(0.01,((k-1)*d)) dim(u1.new)=c(d,k-1) u2.new=rep(0.01,((k-1)*D)) dim(u2.new)=c(D,k-1) phi1.new=phi.mult.it(beta.new,resp,Xk,M,u1.new,u2.new) phi2.new=phi1.new result=list(beta.0=beta.new,phi1.0=phi1.new,phi2.0=phi2.new,u1.0=u1.new,u2.0=u2.new)} if (mod==3) { u1.new=rep(0.01,((k-1)*d)) dim(u1.new)=c(d,k-1) u2.new=rep(0.01,((k-1)*D)) dim(u2.new)=c(D,k-1) resul=phi.mult.ct(beta.new,resp,Xk,M,u1.new,u2.new) phi1.new=resul[[1]] phi2.new=phi1.new rho=resul[[2]] result=list(beta.0=beta.new,phi1.0=phi1.new,phi2.0=phi2.new,u1.0=u1.new,u2.0=u2.new,rho.0=rho) } return(result) } prmu.time<-function(M,Xk,beta,u1,u2){ k=ncol(u1)+1 d=nrow(u1) D=nrow(u2) t=D/d pr=matrix(1,D,k) theta=matrix(0,D,(k-1)) mu=matrix(0,D,k) salida=list() u11=matrix(0,D,(k-1)) jj=1 for (i in 1:d){ for(j in 1:t){ u11[jj,]=u1[i,] jj=jj+1}} for (i in 1:(k-1)){ theta[,i]=Xk[[i]]%*%beta[[i]]+u2[,i]+u11[,i]} suma=rowSums(exp(theta)) pr[,k]=(1+suma)^(-1) for (i in 1:(k-1)){ pr[,i]=pr[,k]*exp(theta[,i])} for (j in 1:D){ mu[j,]=M[j]*pr[j,]} mu=mu[,1:k-1] est=list(estimated.probabilities=pr,mean=mu,eta=theta) return(est)} Fbetaf.it<- function(sigmap,X,Z,phi1,phi2,y,mu,u1,u2){ d=nrow(u1) D=nrow(u2) k=ncol(u1)+1 t=D/d A_d=list() B_d=list() B2_d=list() C_d=list() D_d=list() S_beta_d=list() S_u2_d=rep(0,D*(k-1)) dim(S_u2_d)=c(D,(k-1)) S_u1=matrix(0,d,(k-1)) salida=list() for(i in 1:D){ S_beta_d[[i]]=crossprod((X[[i]]),(y[i,]-mu[i,])) S_u2_d[i,]=(y[i,]-mu[i,]) } S_beta=add(S_beta_d) S_u2=S_u2_d-(u2/(matrix(rep(phi2,D),D,(k-1),byrow=TRUE))) j=1 for (i in 1:d){ S_u1[i,]=colSums(S_u2_d[j:(j+t-1),]) j=j+t} S_u1=S_u1-(u1/(matrix(rep(phi1,d),d,(k-1),byrow=TRUE))) for(i in 1:D){ A_d[[i]]=crossprod((X[[i]]),sigmap[[i]])%*%X[[i]] B_d[[i]]=crossprod((X[[i]]),sigmap[[i]]) D_d[[i]]=crossprod((Z[[i]]),(sigmap[[i]])) } A=as(add(A_d[1:D]),"sparseMatrix") B=as(do.call(cbind,B_d), "sparseMatrix") B2_d=addtolist(B_d,t,d) B2=as(do.call(cbind,B2_d),"sparseMatrix") DD=as(do.call(cbind,D_d),"sparseMatrix") D2_d=addtolist(D_d,t,d) D2=as(do.call(cbind,D2_d),"sparseMatrix") C2_d=addtolist(D_d,t,d) C2=do.call(cbind,C2_d) C22=addtomatrix(C2,d,t,k) F11=as(C22,"sparseMatrix")+as(diag(rep((1/phi1),d)),"sparseMatrix") F22=DD+as(diag(rep((1/phi2),D)),"sparseMatrix") Fuu=as(rbind(cbind(F11,as(t(as(D2,"matrix")),"sparseMatrix")),cbind(D2,F22)),"sparseMatrix") Fuui=as(solve(Fuu),"sparseMatrix") int=as(solve(F22),"sparseMatrix") Fuubb=rbind(as(t(as(B2,"matrix")),"sparseMatrix"),as(t(as(B,"matrix")),"sparseMatrix")) Fbb=as(solve(A-t(as(Fuubb,"matrix"))%*%Fuui%*%(Fuubb)),"sparseMatrix") Fub=-1*Fbb%*%t(as(Fuubb,"matrix"))%*%Fuui Fu1u1=solve(F11-t(as(D2,"matrix"))%*%int%*%D2) Fu1u2=-1*Fu1u1%*%t(as(D2,"matrix"))%*%int Fu2u2=int+int%*%D2%*%Fu1u1%*%t(as(D2,"matrix"))%*%int Fiuu=rbind(cbind(Fu1u1,Fu1u2),cbind(t(as(Fu1u2,"matrix")),Fu2u2)) Fuu=Fiuu+Fiuu%*%Fuubb%*%Fbb%*%t(as(Fuubb,"matrix"))%*%Fiuu F=rbind(cbind(Fbb,(Fub)),cbind(t(as(Fub,"matrix")),Fuu)) S_u11=matrix(t(S_u1),d*(k-1),1) S_u22=matrix(t(S_u2),D*(k-1),1) S=rbind(S_beta,rbind(S_u11,S_u22)) rm(A,B,B2_d,B2,DD,D2_d,D2,C2_d,C2,C22, A_d,B_d,F11,F22,Fuu,Fuui,int,Fbb,Fub,Fu1u1,Fu1u2,Fu2u2,Fiuu) F=as(F,"matrix") fisher=list(F=F,S=S) return(fisher) } phi.direct.it<- function(pp,sigmap,X,phi1,phi2,u1,u2){ d=nrow(u1) D=nrow(u2) t=D/d k=ncol(u1)+1 r=sum(pp+1) Vd=list() qq=matrix(0,r,r) Ld=list() sigmapt=list() u=rep(t,d) mdcum=cumsum(u) a=list() a[[1]]=1:t for(i in 2:d){ a[[i]] <- (mdcum[i-1]+1):mdcum[i]} Xd=list() for (i in 1:d){ Xd[[i]]=X[a[[i]]] Xd[[i]]=do.call(rbind,Xd[[i]]) } j=1 Iq1=matrix(rep(diag(rep(1,(k-1))),t),(t*(k-1)),(k-1),byrow=TRUE) for (i in 1:d){ phi22=diag(1/phi2) a=matrix(0,(k-1),(k-1)) for (l in 1:t){ sigmapt[[l]]=sigmap[[j]]-sigmap[[j]]%*%solve(sigmap[[j]]+phi22)%*%sigmap[[j]] a=a+sigmapt[[l]] j=j+1} Ld[[i]]=do.call("blockdiag",sigmapt) Vd[[i]]=Ld[[i]]-Ld[[i]]%*%Iq1%*%solve(diag(1/phi1)+a)%*%t(Iq1)%*%Ld[[i]] qq=qq+crossprod((Xd[[i]]),(Vd[[i]]))%*%Xd[[i]] } qq=as(solve(qq),"sparseMatrix") Xt=as(do.call(rbind,Xd),"sparseMatrix") W=bdiag(sigmap) V1=list() V2=list() AA=list() for(i in 1:D){ AA[[i]]=matrix(0,(k-1),(k-1)*D) for (j in 1:(k-1)){ AA[[i]][j,((j-1)*D+i)]=1} } Z2=as(do.call(rbind,AA),"sparseMatrix") AA=list() for(i in 1:d){ AA[[i]]=matrix(0,t*(k-1),(k-1)*d) kk=1 for (j in 1:(t*(k-1))){ AA[[i]][j,((kk-1)*d+i)]=1 kk=kk+1 if (kk>(k-1)) {kk=k-1}} } Z1=as(do.call(rbind,AA),"sparseMatrix") for (i in 1:(k-1)){ V1[[i]]=(1/phi1[i])*diag(1,d) V2[[i]]=(1/phi2[[i]])*diag(1,D)} T1=as(solve(t(as(Z1,"matrix"))%*%W%*%Z1+bdiag(V1)),"sparseMatrix") T2=as(solve(t(as(Z2,"matrix"))%*%W%*%Z2+bdiag(V2)),"sparseMatrix") Treml1=T1+as(T1%*%t(as(Z1,"matrix"))%*%W%*%Xt%*%qq%*%t(as(Xt,"matrix"))%*%W%*%Z1%*%T1,"sparseMatrix") Treml2=T2+as(T2%*%t(as(Z2,"matrix"))%*%W%*%Xt%*%qq%*%t(as(Xt,"matrix"))%*%W%*%Z2%*%T2,"sparseMatrix") j=1 Treml1=as(Treml1,"matrix") Treml2=as(Treml2,"matrix") tau=list() Trmll=list() nr=nrow(Treml1) for (i in 1:(k-1)){ Trmll[[i]]=Treml1[j:(j+(nr/(k-1))-1),j:(j+(nr/(k-1))-1)] tau[i]=sum(diag(Trmll[[i]]))/phi1[i] j=j+(nr/(k-1)) } tau=do.call(rbind,tau) tau=as.vector(tau) phi1.new=diag((t(u1)%*%u1)/diag(d-tau)) tau=list() Trmll=list() nr=nrow(Treml2) j=1 for (i in 1:(k-1)){ Trmll[[i]]=Treml2[j:(j+(nr/(k-1))-1),j:(j+(nr/(k-1))-1)] tau[i]=sum(diag(Trmll[[i]]))/phi2[i] j=j+(nr/(k-1)) } tau=do.call(rbind,tau) tau=as.vector(tau) phi2.new=diag((t(u2)%*%u2)/diag((d*t)-tau)) rm(Trmll,tau,Treml2,Treml1, T1, T2,V1,V2, Z1, Z2,Xt,W,Vd,Ld,qq) resul=list(phi1.new=phi1.new,phi2.new=phi2.new) } sPhikf.it<- function(d,t,pp,sigmap,X,eta,phi1,phi2){ k=ncol(eta)+1 r=sum(pp+1) Vd=list() F=matrix(0,(2*(k-1)),(2*(k-1))) qq=matrix(0,r,r) Ld=list() sigmapt=list() u=rep(t,d) mdcum=cumsum(u) a=list() a[[1]]=1:t for(i in 2:d){ a[[i]] <- (mdcum[i-1]+1):mdcum[i]} Xd=list() for (i in 1:d){ Xd[[i]]=X[a[[i]]] Xd[[i]]=do.call(rbind,Xd[[i]]) } thetaa=list() j=1 for (i in 1:d){ thetaa[[i]]=matrix(t(eta[(j:(j+t-1)),]),((k-1)*t),1,byrow=TRUE) j=j+t} j=1 Iq1=matrix(rep(diag(rep(1,(k-1))),t),(t*(k-1)),(k-1),byrow=TRUE) for (i in 1:d){ phi22=diag(1/phi2) a=matrix(0,(k-1),(k-1)) for (l in 1:t){ sigmapt[[l]]=sigmap[[j]]-sigmap[[j]]%*%solve(sigmap[[j]]+phi22)%*%sigmap[[j]] a=a+sigmapt[[l]] j=j+1} Ld[[i]]=do.call("blockdiag",sigmapt) Vd[[i]]=Ld[[i]]-Ld[[i]]%*%Iq1%*%solve(diag(1/phi1)+a)%*%t(Iq1)%*%Ld[[i]] qq=qq+crossprod((Xd[[i]]),(Vd[[i]]))%*%Xd[[i]]} qq=solve(qq) S1=rep(0,2*(k-1)) S2=rep(0,2*(k-1)) delta11=list() sum1=list() sum2=list() sum3=list() sum4=list() for (i in 1:(2*(k-1))){ sum1[[i]]=matrix(0,1,r) sum2[[i]]=matrix(0,r,1) sum3[[i]]=matrix(0,1,r) sum4[[i]]=matrix(0,r,r)} o=1 for(i in 1:2){ for (j in 1:(k-1)){ delta=matrix(0,(k-1),(k-1)) for (ll in 1:(k-1)){ if (ll==j) {delta[ll,ll]=1}} for (ll in 1:t){ delta11[[ll]]=delta } if (i==1) {Vakd=Iq1%*%delta%*%t(Iq1)} if (i==2) {Vakd=do.call("blockdiag",delta11)} for (l in 1:d){ S1[o]=S1[o]+sum(diag((Vd[[l]]-Vd[[l]]%*%Xd[[l]]%*%qq%*%t(Xd[[l]])%*%Vd[[l]])%*%Vakd)) S2[o]=S2[o]+t(thetaa[[l]])%*%Vd[[l]]%*%Vakd%*%(Vd[[l]])%*%thetaa[[l]] sum1[[o]]=sum1[[o]]+t(thetaa[[l]])%*%Vd[[l]]%*%Vakd%*%(Vd[[l]])%*%Xd[[l]] sum2[[o]]=sum2[[o]]+t(Xd[[l]])%*%Vd[[l]]%*%thetaa[[l]] sum3[[o]]=sum3[[o]]+t(thetaa[[l]])%*%Vd[[l]]%*%Xd[[l]] sum4[[o]]=sum4[[o]]+t(Xd[[l]])%*%Vd[[l]]%*%Vakd%*%(Vd[[l]])%*%Xd[[l]]} o=o+1}} tt=rep(0,(2*(k-1))) for(i in 1:(2*(k-1))){ tt[i]=-2*(sum1[[i]]%*%qq%*%sum2[[i]])+sum3[[i]]%*%qq%*%sum4[[i]]%*%qq%*%sum2[[i]]} S2=S2+tt S=-0.5*S1+0.5*S2 F1=rep(0,((k-1)*(k-1)*4)) F2=rep(0,((k-1)*(k-1)*4)) F3=rep(0,((k-1)*(k-1)*4)) aa=1 o=1 for (i in 1:2){ for(ii in 1:(k-1)){ for(j in 1:2){ for (jj in 1:(k-1)){ delta=matrix(0,(k-1),(k-1)) for (ll in 1:(k-1)){ if (ll==ii) {delta[ll,ll]=1}} for (ll in 1:t){ delta11[[ll]]=delta} if (i==1) {Vakd1=Iq1%*%delta%*%t(Iq1)} if (i==2) {Vakd1=do.call("blockdiag",delta11)} delta=matrix(0,(k-1),(k-1)) for (ll in 1:(k-1)){ if (ll==jj) {delta[ll,ll]=1}} for (ll in 1:t){ delta11[[ll]]=delta } if (j==1) {Vakd2=Iq1%*%delta%*%t(Iq1)} if (j==2) {Vakd2=do.call("blockdiag",delta11)} for (l in 1:d){ F1[aa]=F1[aa]+0.5*sum(diag(Vd[[l]]%*%Vakd1%*%Vd[[l]]%*%Vakd2)) F2[aa]=F2[aa]+0.5*sum(diag(Vd[[l]]%*%Vakd1%*%Vd[[l]]%*%Xd[[l]]%*%qq%*%t(Xd[[l]])%*%Vd[[l]]%*%Vakd2)) F3[aa]=F3[aa]+0.5*sum(diag(Vd[[l]]%*%Xd[[l]]%*%qq%*%sum4[[o]]%*%qq%*%t(Xd[[l]])%*%Vd[[l]]%*%Vakd2))} aa=aa+1 }} o=o+1}} F=F1+2*F2+F3 FF=list() FFF=list() o=1 for (i in 1:2){ for (j in 1:2){ FF[[j]]=matrix(F[o:(o+(k-1)*(k-1)-1)],(k-1),(k-1)) o=o+(k-1)*(k-1)} FFF[[i]]=do.call(cbind,FF)} F=do.call(rbind,FFF) F=solve(F) S=matrix(t(S),4,1) A=F%*%S rm(sum1,sum2,sum3,sum4, Vakd1,Vakd2, Vakd, S1,S2,Xd,Vd,Ld,sigmapt,thetaa, Iq1) score.F=list(S=S,F=F) return(score.F) } modelfit2<-function(d,t,pp,Xk,X,Z,initial,y,M,MM){ D=d*t beta.new=initial[[1]] phi1.new=initial[[2]] phi2.new=initial[[3]] u1.new=initial[[4]] u2.new=initial[[5]] k=ncol(u1.new)+1 maxiter1=100 maxiter2=100 iter1=0 eps=1e-3 phi1.prim=phi1.new phi2.prim=phi2.new p=sum(pp+1) cont=0 ii=1 ll=0 mm=1 aviso=0 Fk=matrix(0,(k-1),(k-1)) while (iter1<maxiter1) { phi1.old=phi1.new phi2.old=phi2.new iter2=0 p1=matrix(1,p,(k-1)) p2=matrix(1,D,(k-1)) while(iter2<maxiter2 & mm>eps){ beta.old=beta.new u1.old=u1.new u2.old=u2.new prmul=prmu.time(M,Xk,beta.old,u1.old,u2.old) theta=prmul[[3]] pr=prmul[[1]] mu=prmul[[2]] sigmap=wmatrix(M,pr) for (i in 1:D){ comp=det(sigmap[[i]]) if (is.na(comp)){cont=1} if (is.na(comp)==FALSE & (abs(comp))<0.000001 ) {cont=1}} if (cont==0){ inversaFbeta=Fbetaf.it(sigmap,X,Z,phi1.old,phi2.old,y,mu,u1.old,u2.old) F=inversaFbeta[[1]] S=inversaFbeta[[2]] rm(inversaFbeta) beta.u.old=rbind(do.call(rbind,beta.old),rbind(matrix(t(u1.old),d*(k-1),1),matrix(t(u2.old),D*(k-1),1))) beta.u.new=beta.u.old+F%*%S p1=(beta.u.new-beta.u.old)/beta.u.old mm=max(abs(p1)) if (mm<eps){iter2=maxiter2} else {iter2=iter2+1} ucum=cumsum(pp+1) beta_new=list() beta.new[[1]]=as.matrix(beta.u.new[(1:ucum[1]),1]) for (i in 2:(k-1)){ beta.new[[i]]=as.matrix(beta.u.new[((ucum[i-1]+1):ucum[i]),1]) } u1.new=matrix(beta.u.new[(ucum[k-1]+1):(ucum[k-1]+d*(k-1)),],d,k-1,byrow=TRUE) u2.new=matrix(beta.u.new[(ucum[k-1]+1+d*(k-1)):nrow(beta.u.new),],D,k-1,byrow=TRUE)} if (ii==1) { beta.prim=beta.new F.prim=F u1.prim=u1.new u2.prim=u2.new } if (cont==1){iter2=maxiter2} } if (cont==0){ prmul=prmu.time(M,Xk,beta.new,u1.new,u2.new) theta=prmul[[3]] pr=prmul[[1]] mu=prmul[[2]] rm(prmul) sigmap=wmatrix(M,pr) ii=ii+1 phi.old=rbind(data.matrix(phi1.old),data.matrix(phi2.old)) resul=phi.direct.it(pp,sigmap,X,phi1.old,phi2.old,u1.new,u2.new) phi1.new=resul[[1]] phi2.new=resul[[2]] phi.new=matrix(cbind(phi1.new,phi2.new),2*(k-1),1) phi.new=data.matrix(phi.new) p3=(phi.new-phi.old)/phi.old phi1.new=phi.new[1:(k-1),] phi2.new=phi.new[k:(2*(k-1)),] mmm=max(abs(c(p1,p3))) if (min(phi.new)<0.001){ aviso=1 ll=ll+1 phi1.new=phi1.prim phi2.new=phi2.prim u1.new=u1.prim u2.new=u2.prim if (ll>1) { phi1.new=phi1.prim phi2.new=phi2.prim iter1=maxiter1} iter1=iter1+1 } if (aviso==0) {mmm=max(abs(c(p1,p3))) mm=1} else {mmm=max(abs(p3)) mm=eps/10} if (mmm>eps){iter1=iter1+1} else {iter1=maxiter1}} if (cont==1) { iter1=maxiter1} } prmul=prmu.time(MM,Xk,beta.new,u1.new,u2.new) mu=prmul[[2]] pr=prmul[[1]] colnames(mu)=paste("Yest",1:(k-1),sep="") b2=do.call(rbind,beta.new) cii=ci(b2,F[1:(sum(pp+1)),1:(sum(pp+1))]) resulbeta=cbind(Beta=b2,Std.dev=cii[[1]],p.value=cii[[2]]) colnames(resulbeta)=c("Estimate","Std.Error","p.value") u=list() for (i in 1:(k-1)){ u[[i]]=as.matrix(colnames(Xk[[i]])) u[[i]][1]="Intercept"} u=do.call(rbind,u) rownames(resulbeta)=u resulbeta sk_F=sPhikf.it(d,t,pp,sigmap,X,theta,phi1.new,phi2.new) Fk=sk_F[[2]] phi.new=(rbind(as.matrix(phi1.new),as.matrix(phi2.new))) cii=ci(phi.new,Fk) resulphi=cbind(phi.est=phi.new,Std.dev=cii[[1]],p.value=cii[[2]]) colnames(resulphi)=c("Estimate","Std.Error","p.value") result=list() result=list(Estimated.probabilities=pr,u1=u1.new,u2=u2.new,mean=mu,warning1=cont,Fisher.information.matrix.beta=F,Fisher.information.matrix.phi=Fk,beta.Stddev.p.value=resulbeta,phi.Stddev.p.value=resulphi,warning2=aviso) class(result)="mme" return(result) } msef.it<-function(p,X,result,M,MM){ pr=result$Estimated.probabilities k=ncol(pr) phi1.old=(result[[9]][1:(k-1),1]) phi2.old=(result[[9]][k:(2*k-2),1]) F=result$Fisher.information.matrix.phi D=nrow(MM) d=nrow(result$u1) t=D/d r=sum(p+1) Vd=list() qq=matrix(0,(r),(r)) Ld=list() sigmap=wmatrix(MM,pr) sigmapMM=wmatrix(M,pr) sigmapt=list() u=rep(t,d) mdcum=cumsum(u) a=list() a[[1]]=1:t for(i in 2:d){ a[[i]] <- (mdcum[i-1]+1):mdcum[i]} Xd=list() Xaa=list() for (i in 1:d){ Xaa[[i]]=X[a[[i]]] Xd[[i]]=do.call(rbind,Xaa[[i]]) } j=1 Iq1=matrix(rep(diag(rep(1,(k-1))),t),(t*(k-1)),(k-1),byrow=TRUE) for (i in 1:d){ phi22=diag(1/phi2.old) a=matrix(0,(k-1),(k-1)) for (l in 1:t){ sigmapt[[l]]=sigmapMM[[j]]-sigmapMM[[j]]%*%solve(sigmapMM[[j]]+phi22)%*%sigmapMM[[j]] a=a+sigmapt[[l]] j=j+1} Ld[[i]]=do.call("blockdiag",sigmapt) Vd[[i]]=Ld[[i]]-Ld[[i]]%*%Iq1%*%solve(diag(1/phi1.old)+a)%*%t(Iq1)%*%Ld[[i]] qq=qq+crossprod((Xd[[i]]),(Vd[[i]]))%*%Xd[[i]] } qq=solve(qq) Xt=do.call(rbind,Xd) W=bdiag(sigmapMM) H=bdiag(sigmap) phi22=list() for (i in 1:t){ phi22[[i]]=diag(phi2.old)} phi22=bdiag(phi22) z2=diag(rep(1,(t*(k-1)))) T11=list() T22=list() T12=list() Z1i=list() TT=list() for (i in 1:d){ T11[[i]]=as(diag(phi1.old)-diag(phi1.old)%*%t(Iq1)%*%Vd[[i]]%*%Iq1%*%diag(phi1.old),"sparseMatrix") T12[[i]]=as(-diag(phi1.old)%*%t(Iq1)%*%Vd[[i]]%*%z2%*%phi22,"sparseMatrix") T22[[i]]=as(phi22-phi22%*%t(z2)%*%Vd[[i]]%*%z2%*%phi22,"sparseMatrix") TT[[i]]=as(Iq1%*%T11[[i]]%*%t(Iq1)+Iq1%*%T12[[i]]%*%t(as(z2,"matrix"))+z2%*%t(as(T12[[i]],"matrix"))%*%t(Iq1)+z2%*%t(as(T22[[i]],"matrix"))%*%t(as(z2,"matrix")),"sparseMatrix") Z1i[[i]]=as(Iq1,"sparseMatrix")} pro=list() prod=list() pro2=list() pro22=list() prod2=list() jj=1 for (i in 1:d){ for (j in 1:t){ pro[[jj]]=as(t(cbind(matrix(0,(k-1),(j-1)*(k-1)),sigmap[[jj]],matrix(0,(k-1),(t-j)*(k-1)))),"sparseMatrix") pro22[[j]]=as(sigmapMM[[jj]]%*%X[[jj]],"sparseMatrix") jj=jj+1} pro2[[i]]=do.call(rbind,pro22)} G1=list() G11=list() G12=list() G22=list() A21=list() A22=list() G2=list() jj=1 for (i in 1:d){ for (l in 1:t){ G11[[jj]]=as(sigmap[[jj]]%*%(diag(phi1.old)-diag(phi1.old)%*%t(Iq1)%*%Vd[[i]]%*%Iq1%*%diag(phi1.old))%*%t(as(sigmap[[jj]],"matrix")),"sparseMatrix") G12[[jj]]=as(-sigmap[[jj]]%*%diag(phi1.old)%*%t(Iq1)%*%Vd[[i]]%*%z2%*%phi22%*%(pro[[jj]]),"sparseMatrix") G22[[jj]]=as(t(as(pro[[jj]],"matrix"))%*%(phi22-phi22%*%t(as(z2,"matrix"))%*%Vd[[i]]%*%z2%*%phi22)%*%pro[[jj]],"sparseMatrix") A21[[jj]]=as(sigmap[[jj]]%*%X[[jj]],"sparseMatrix") A22[[jj]]=as(t(as(pro[[jj]],"matrix"))%*%TT[[i]]%*%(pro2[[i]]),"sparseMatrix") G2[[jj]]=as((A21[[jj]]-A22[[jj]])%*%qq%*%(t(as(A21[[jj]],"matrix"))-t(as(A22[[jj]],"matrix"))),"sparseMatrix") G1[[jj]]=G11[[jj]]+G12[[jj]]+t(as(G12[[jj]],"matrix"))+G22[[jj]] jj=jj+1 }} Vu1=diag(rep(phi1.old,d)) Vu2=diag(rep(phi2.old,(d*t))) V=bdiag(Vd) Z1=bdiag(Z1i) R2=Vu2%*%V R1=Z1%*%Vu1%*%t(as(Z1,"matrix"))%*%V aa=nrow(R1) bb=nrow(R2) delta11=list() Vakd=list() Va=list() Lk=list() o=1 for(i in 1:2){ for (j in 1:(k-1)){ delta=matrix(0,(k-1),(k-1)) for (ll in 1:(k-1)){ if (ll==j) {delta[ll,ll]=1}} for (ll in 1:t){ delta11[[ll]]=delta } if (i==1){Vakd =as(Iq1%*%delta%*%t(Iq1),"sparseMatrix")} if (i==2){Vakd=bdiag(delta11)} for(l in 1:d){ Va[[l]]=Vakd} if (i==1) {Lk[[o]]=(as(diag(rep(1,aa)),"sparseMatrix")-R1)%*%bdiag(Va)%*%V} if (i==2) {Lk[[o]]=(as(diag(rep(1,bb)),"sparseMatrix")-R2)%*%bdiag(Va)%*%V} o=o+1 }} A=list() for(i in 1:D){ n0=(k-1)*(D-i) if (n0<0) {n0=0} A[[i]]=cbind(matrix(0,nrow=k-1,ncol=(k-1)*(i-1)),diag(k-1),matrix(0,nrow=k-1,ncol=n0))} aa=2*(k-1) jj=1 gg3=list() g3=as(matrix(0,(d*t*(k-1)),(d*t*(k-1))),"sparseMatrix") for (i in 1:aa){ for (j in 1:aa){ g33=H%*%Lk[[i]]%*%V%*%t(as(Lk[[j]],"matrix"))%*%t(as(H,"matrix")) g3=g3+F[i,j]*g33 jj=jj+1 }} for (kk in 1:D){ gg3[[kk]]=A[[kk]]%*%g3%*%t(as(A[[kk]],"matrix"))} g=list() gg=list() for (i in 1:D){ g[[i]]=G1[[i]]+G2[[i]]+2*gg3[[i]] gg[[i]]=G1[[i]]+G2[[i]]} mse.analitic=matrix(0,D,(k-1)) for (i in 1:(k-1)){ for (j in 1:D){ mse.analitic[j,i]=g[[j]][i,i]}} colnames(mse.analitic)=paste("mse.",1:(k-1),sep="") mse=list(mse.analitic=mse.analitic) return(mse) }
`beals` <- function(x, species=NA, reference=x, type=0, include=TRUE) { refX <- reference mode <- as.numeric(match.arg(as.character(type), c("0","1","2","3"))) spIndex <- species incSp <- include refX <- as.matrix(refX) x <- as.matrix(x) if (!(is.numeric(x) || is.logical(x))) stop("input data must be numeric") if(mode==0 || mode ==2) refX <- ifelse(refX > 0, 1, 0) if(mode==0 || mode ==1) x <- ifelse(x > 0, 1, 0) if(is.na(spIndex)){ M <- crossprod(ifelse(refX > 0, 1, 0),refX) C <-diag(M) M <- sweep(M, 2, replace(C,C==0,1), "/") if(!incSp) for (i in 1:ncol(refX)) M[i,i] <- 0 } else { C <- colSums(refX) M <- crossprod(refX,ifelse(refX > 0, 1, 0)[,spIndex]) M <- M/replace(C,C==0,1) if(!incSp) M[spIndex] <- 0 } S <- rowSums(x) if(is.na(spIndex)) { b <-x for (i in 1:nrow(x)) { b[i, ] <- rowSums(sweep(M, 2, x[i, ], "*")) } SM <- rep(S,ncol(x)) if(!incSp) SM <- SM-x b <- b/replace(SM,SM==0,1) } else { b <-rowSums(sweep(x,2,M,"*")) if(!incSp) S <- S-x[,spIndex] b <- b/replace(S,S==0,1) } b }