code
stringlengths
1
13.8M
require(OpenMx) A <- mxMatrix(nrow = 2, ncol = 2, values = c(1:4), free = TRUE, name = 'A') squared <- function(x) { x ^ 2 } objFunction <- function(model, state) { return(mxEval(squared(A[1,1] - 4) + squared(A[1,2] - 3) + squared(A[2,1] - 2) + squared(A[2,2] - 1), model)) } objective <- mxFitFunctionR(objFunction) model <- mxModel('model', A, objective) modelOut <- mxRun(model) omxCheckCloseEnough(mxEval(A, modelOut), rbind(c(4, 3), c(2, 1)), epsilon = 0.001) omxCheckCloseEnough(modelOut$output$hessian, diag(2, 4), 1e-9)
context("Unit tests feistest and bsfeistest") data("mwp", package = "feisr") wages.feis <- feis(lnw ~ marry + enrol + yeduc | exp, data = mwp[mwp$id <= 50, ], id = "id") art0 <- feistest(wages.feis, robust = TRUE) art <- feistest(wages.feis, robust = TRUE, terms = c("marry", "enrol")) bsht0 <- bsfeistest(wages.feis, rep = 10, seed = 133213, prog = FALSE) bsht <- bsfeistest(wages.feis, rep = 10, seed = 133213, prog = FALSE, terms = c("marry", "enrol")) test_that("Terms in feistest", { expect_equal(length(art0$wald_feis$Terms), 3, tolerance = 1e-10) expect_equal(length(art0$wald_fe$Terms), 4, tolerance = 1e-10) expect_equal(length(art$wald_feis$Terms), 2, tolerance = 1e-10) expect_equal(length(art$wald_fe$Terms), 3, tolerance = 1e-10) }) test_that("Terms in bsfeistest", { expect_equal(length(bsht0$wald_feis$Terms), 3, tolerance = 1e-10) expect_equal(length(bsht0$wald_fe$Terms), 4, tolerance = 1e-10) expect_equal(length(bsht$wald_feis$Terms), 2, tolerance = 1e-10) expect_equal(length(bsht$wald_fe$Terms), 3, tolerance = 1e-10) }) art0_1 <- 0.93 art1_1 <- 0.89 art0_2 <- 14.34 art1_2 <- 8.70 art0_3 <- 1.54 art1_3 <- 1.05 test_that("Unit test for feistest", { expect_equal(art0$wald_feis$result$chi2[1], art0_1, tolerance = 2e-2, check.attributes = FALSE) expect_equal(art0$wald_fe$result$chi2[1], art0_2, tolerance = 2e-2, check.attributes = FALSE) expect_equal(art0$wald_re$result$chi2[1], art0_3, tolerance = 2e-2, check.attributes = FALSE) expect_equal(art$wald_feis$result$chi2[1], art1_1, tolerance = 2e-2, check.attributes = FALSE) expect_equal(art$wald_fe$result$chi2[1], art1_2, tolerance = 2e-2, check.attributes = FALSE) expect_equal(art$wald_re$result$chi2[1], art1_3, tolerance = 2e-2, check.attributes = FALSE) }) bsht0_1 <- 1.03 bsht1_1 <- 0.99 bsht0_2 <- 5.01 bsht1_2 <- 4.05 bsht0_3 <- 1.69 bsht1_3 <- 0.94 test_that("Unit test for feistest", { expect_equal(bsht0$wald_feis$result$chi2[1], bsht0_1, tolerance = 2e-1, check.attributes = FALSE) expect_equal(bsht0$wald_fe$result$chi2[1], bsht0_2, tolerance = 2e-1, check.attributes = FALSE) expect_equal(bsht0$wald_re$result$chi2[1], bsht0_3, tolerance = 2e-1, check.attributes = FALSE) expect_equal(bsht$wald_feis$result$chi2[1], bsht1_1, tolerance = 5e-1, check.attributes = FALSE) expect_equal(bsht$wald_fe$result$chi2[1], bsht1_2, tolerance = 5e-1, check.attributes = FALSE) expect_equal(bsht$wald_re$result$chi2[1], bsht1_3, tolerance = 5e-1, check.attributes = FALSE) }) test_that("P value for feistest and bsfeistest", { expect_equal(art$wald_feis$result$chi2[3], 0.64, tolerance = 2e-2, check.attributes = FALSE) expect_equal(art0$wald_feis$result$chi2[3], 0.82, tolerance = 2e-2, check.attributes = FALSE) expect_equal(bsht$wald_feis$result$chi2[3], 0.61, tolerance = 2e-2, check.attributes = FALSE) expect_equal(bsht0$wald_re$result$chi2[3], 0.64, tolerance = 1e-1, check.attributes = FALSE) })
anovaRMOptions <- if (requireNamespace("jmvcore", quietly=TRUE)) R6::R6Class( "anovaRMOptions", inherit = jmvcore::Options, public = list( initialize = function( rm = list( list(label="RM Factor 1", levels=list( "Level 1", "Level 2"))), rmCells = NULL, bs = NULL, cov = NULL, effectSize = NULL, depLabel = "Dependent", rmTerms = NULL, bsTerms = NULL, ss = "3", spherTests = FALSE, spherCorr = list( "none"), leveneTest = FALSE, qq = FALSE, contrasts = NULL, postHoc = NULL, postHocCorr = list( "tukey"), emMeans = list( list()), emmPlots = TRUE, emmTables = FALSE, emmWeights = TRUE, ciWidthEmm = 95, emmPlotData = FALSE, emmPlotError = "ci", groupSumm = FALSE, ...) { super$initialize( package="jmv", name="anovaRM", requiresData=TRUE, ...) private$..rm <- jmvcore::OptionArray$new( "rm", rm, default=list( list(label="RM Factor 1", levels=list( "Level 1", "Level 2"))), template=jmvcore::OptionGroup$new( "rm", NULL, elements=list( jmvcore::OptionString$new( "label", NULL), jmvcore::OptionArray$new( "levels", NULL, template=jmvcore::OptionString$new( "levels", NULL))))) private$..rmCells <- jmvcore::OptionArray$new( "rmCells", rmCells, default=NULL, template=jmvcore::OptionGroup$new( "rmCells", NULL, elements=list( jmvcore::OptionVariable$new( "measure", NULL), jmvcore::OptionArray$new( "cell", NULL, template=jmvcore::OptionString$new( "cell", NULL))))) private$..bs <- jmvcore::OptionVariables$new( "bs", bs, rejectUnusedLevels=TRUE, suggested=list( "nominal", "ordinal"), permitted=list( "factor"), default=NULL) private$..cov <- jmvcore::OptionVariables$new( "cov", cov, suggested=list( "continuous"), permitted=list( "numeric"), default=NULL) private$..effectSize <- jmvcore::OptionNMXList$new( "effectSize", effectSize, options=list( "eta", "partEta", "ges", "omega"), default=NULL) private$..depLabel <- jmvcore::OptionString$new( "depLabel", depLabel, default="Dependent") private$..rmTerms <- jmvcore::OptionTerms$new( "rmTerms", rmTerms, default=NULL) private$..bsTerms <- jmvcore::OptionTerms$new( "bsTerms", bsTerms, default=NULL) private$..ss <- jmvcore::OptionList$new( "ss", ss, options=list( "2", "3"), default="3") private$..spherTests <- jmvcore::OptionBool$new( "spherTests", spherTests, default=FALSE) private$..spherCorr <- jmvcore::OptionNMXList$new( "spherCorr", spherCorr, options=list( "none", "GG", "HF"), default=list( "none")) private$..leveneTest <- jmvcore::OptionBool$new( "leveneTest", leveneTest, default=FALSE) private$..qq <- jmvcore::OptionBool$new( "qq", qq, default=FALSE) private$..contrasts <- jmvcore::OptionArray$new( "contrasts", contrasts, hidden=TRUE, items="(bs)", default=NULL, template=jmvcore::OptionGroup$new( "contrasts", NULL, elements=list( jmvcore::OptionString$new( "var", NULL, content="$key"), jmvcore::OptionList$new( "type", NULL, options=list( "none", "deviation", "simple", "difference", "helmert", "repeated", "polynomial"))))) private$..postHoc <- jmvcore::OptionArray$new( "postHoc", postHoc, template=jmvcore::OptionArray$new( "postHoc", NULL, template=jmvcore::OptionString$new( "postHoc", NULL)), default=NULL) private$..postHocCorr <- jmvcore::OptionNMXList$new( "postHocCorr", postHocCorr, options=list( "none", "tukey", "scheffe", "bonf", "holm"), default=list( "tukey")) private$..emMeans <- jmvcore::OptionArray$new( "emMeans", emMeans, default=list( list()), template=jmvcore::OptionVariables$new( "emMeans", NULL)) private$..emmPlots <- jmvcore::OptionBool$new( "emmPlots", emmPlots, default=TRUE) private$..emmTables <- jmvcore::OptionBool$new( "emmTables", emmTables, default=FALSE) private$..emmWeights <- jmvcore::OptionBool$new( "emmWeights", emmWeights, default=TRUE) private$..ciWidthEmm <- jmvcore::OptionNumber$new( "ciWidthEmm", ciWidthEmm, min=50, max=99.9, default=95) private$..emmPlotData <- jmvcore::OptionBool$new( "emmPlotData", emmPlotData, default=FALSE) private$..emmPlotError <- jmvcore::OptionList$new( "emmPlotError", emmPlotError, options=list( "none", "ci", "se"), default="ci") private$..groupSumm <- jmvcore::OptionBool$new( "groupSumm", groupSumm, default=FALSE) self$.addOption(private$..rm) self$.addOption(private$..rmCells) self$.addOption(private$..bs) self$.addOption(private$..cov) self$.addOption(private$..effectSize) self$.addOption(private$..depLabel) self$.addOption(private$..rmTerms) self$.addOption(private$..bsTerms) self$.addOption(private$..ss) self$.addOption(private$..spherTests) self$.addOption(private$..spherCorr) self$.addOption(private$..leveneTest) self$.addOption(private$..qq) self$.addOption(private$..contrasts) self$.addOption(private$..postHoc) self$.addOption(private$..postHocCorr) self$.addOption(private$..emMeans) self$.addOption(private$..emmPlots) self$.addOption(private$..emmTables) self$.addOption(private$..emmWeights) self$.addOption(private$..ciWidthEmm) self$.addOption(private$..emmPlotData) self$.addOption(private$..emmPlotError) self$.addOption(private$..groupSumm) }), active = list( rm = function() private$..rm$value, rmCells = function() private$..rmCells$value, bs = function() private$..bs$value, cov = function() private$..cov$value, effectSize = function() private$..effectSize$value, depLabel = function() private$..depLabel$value, rmTerms = function() private$..rmTerms$value, bsTerms = function() private$..bsTerms$value, ss = function() private$..ss$value, spherTests = function() private$..spherTests$value, spherCorr = function() private$..spherCorr$value, leveneTest = function() private$..leveneTest$value, qq = function() private$..qq$value, contrasts = function() private$..contrasts$value, postHoc = function() private$..postHoc$value, postHocCorr = function() private$..postHocCorr$value, emMeans = function() private$..emMeans$value, emmPlots = function() private$..emmPlots$value, emmTables = function() private$..emmTables$value, emmWeights = function() private$..emmWeights$value, ciWidthEmm = function() private$..ciWidthEmm$value, emmPlotData = function() private$..emmPlotData$value, emmPlotError = function() private$..emmPlotError$value, groupSumm = function() private$..groupSumm$value), private = list( ..rm = NA, ..rmCells = NA, ..bs = NA, ..cov = NA, ..effectSize = NA, ..depLabel = NA, ..rmTerms = NA, ..bsTerms = NA, ..ss = NA, ..spherTests = NA, ..spherCorr = NA, ..leveneTest = NA, ..qq = NA, ..contrasts = NA, ..postHoc = NA, ..postHocCorr = NA, ..emMeans = NA, ..emmPlots = NA, ..emmTables = NA, ..emmWeights = NA, ..ciWidthEmm = NA, ..emmPlotData = NA, ..emmPlotError = NA, ..groupSumm = NA) ) anovaRMResults <- if (requireNamespace("jmvcore", quietly=TRUE)) R6::R6Class( "anovaRMResults", inherit = jmvcore::Group, active = list( rmTable = function() private$.items[["rmTable"]], bsTable = function() private$.items[["bsTable"]], assump = function() private$.items[["assump"]], contrasts = function() private$.items[["contrasts"]], postHoc = function() private$.items[["postHoc"]], emm = function() private$.items[["emm"]], groupSummary = function() private$.items[["groupSummary"]]), private = list(), public=list( initialize=function(options) { super$initialize( options=options, name="", title="Repeated Measures ANOVA") self$add(jmvcore::Table$new( options=options, name="rmTable", title="Within Subjects Effects", refs="afex", clearWith=list( "dependent", "ss", "rmCells", "rmcModelTerms", "bscModelTerms", "bs", "rm", "cov", "rmTerms", "bsTerms"), columns=list( list( `name`="name[none]", `title`="", `type`="text", `combineBelow`=TRUE, `visible`="(spherCorr:none)"), list( `name`="correction[none]", `title`="Sphericity Correction", `type`="text", `content`="None", `visible`="(spherCorr:none && (spherCorr:GG || spherCorr:HF))"), list( `name`="ss[none]", `title`="Sum of Squares", `type`="number", `visible`="(spherCorr:none)"), list( `name`="df[none]", `title`="df", `type`="integer", `visible`="(spherCorr:none)"), list( `name`="ms[none]", `title`="Mean Square", `type`="number", `visible`="(spherCorr:none)"), list( `name`="F[none]", `title`="F", `type`="number", `visible`="(spherCorr:none)"), list( `name`="p[none]", `title`="p", `type`="number", `format`="zto,pvalue", `visible`="(spherCorr:none)"), list( `name`="ges[none]", `title`="\u03B7\u00B2<sub>G</sub>", `type`="number", `format`="zto", `visible`="(effectSize:ges && spherCorr:none)"), list( `name`="eta[none]", `title`="\u03B7\u00B2", `type`="number", `format`="zto", `visible`="(effectSize:eta && spherCorr:none)"), list( `name`="partEta[none]", `title`="\u03B7\u00B2<sub>p</sub>", `type`="number", `format`="zto", `visible`="(effectSize:partEta && spherCorr:none)"), list( `name`="omega[none]", `title`="\u03C9\u00B2", `type`="number", `format`="zto", `visible`="(effectSize:omega && spherCorr:none)"), list( `name`="name[GG]", `title`="", `type`="text", `combineBelow`=TRUE, `visible`="(spherCorr:GG)"), list( `name`="correction[GG]", `title`="Sphericity Correction", `type`="text", `content`="Greenhouse-Geisser", `visible`="(spherCorr:GG)"), list( `name`="ss[GG]", `title`="Sum of Squares", `type`="number", `visible`="(spherCorr:GG)"), list( `name`="df[GG]", `title`="df", `type`="number", `visible`="(spherCorr:GG)"), list( `name`="ms[GG]", `title`="Mean Square", `type`="number", `visible`="(spherCorr:GG)"), list( `name`="F[GG]", `title`="F", `type`="number", `visible`="(spherCorr:GG)"), list( `name`="p[GG]", `title`="p", `type`="number", `format`="zto,pvalue", `visible`="(spherCorr:GG)"), list( `name`="ges[GG]", `title`="\u03B7\u00B2<sub>G</sub>", `type`="number", `format`="zto", `visible`="(effectSize:ges && spherCorr:GG)"), list( `name`="eta[GG]", `title`="\u03B7\u00B2", `type`="number", `format`="zto", `visible`="(effectSize:eta && spherCorr:GG)"), list( `name`="partEta[GG]", `title`="\u03B7\u00B2<sub>p</sub>", `type`="number", `format`="zto", `visible`="(effectSize:partEta && spherCorr:GG)"), list( `name`="omega[GG]", `title`="\u03C9\u00B2", `type`="number", `format`="zto", `visible`="(effectSize:omega && spherCorr:GG)"), list( `name`="name[HF]", `title`="", `type`="text", `combineBelow`=TRUE, `visible`="(spherCorr:HF)"), list( `name`="correction[HF]", `title`="Sphericity Correction", `type`="text", `content`="Huynh-Feldt", `visible`="(spherCorr:HF)"), list( `name`="ss[HF]", `title`="Sum of Squares", `type`="number", `visible`="(spherCorr:HF)"), list( `name`="df[HF]", `title`="df", `type`="number", `visible`="(spherCorr:HF)"), list( `name`="ms[HF]", `title`="Mean Square", `type`="number", `visible`="(spherCorr:HF)"), list( `name`="F[HF]", `title`="F", `type`="number", `visible`="(spherCorr:HF)"), list( `name`="p[HF]", `title`="p", `type`="number", `format`="zto,pvalue", `visible`="(spherCorr:HF)"), list( `name`="ges[HF]", `title`="\u03B7\u00B2<sub>G</sub>", `type`="number", `format`="zto", `visible`="(effectSize:ges && spherCorr:HF)"), list( `name`="eta[HF]", `title`="\u03B7\u00B2", `type`="number", `format`="zto", `visible`="(effectSize:eta && spherCorr:HF)"), list( `name`="partEta[HF]", `title`="\u03B7\u00B2<sub>p</sub>", `type`="number", `format`="zto", `visible`="(effectSize:partEta && spherCorr:HF)"), list( `name`="omega[HF]", `title`="\u03C9\u00B2", `type`="number", `format`="zto", `visible`="(effectSize:omega && spherCorr:HF)")))) self$add(jmvcore::Table$new( options=options, name="bsTable", title="Between Subjects Effects", clearWith=list( "dependent", "ss", "rmCells", "rmcModelTerms", "bscModelTerms", "bs", "rm", "cov", "rmTerms", "bsTerms"), columns=list( list( `name`="name", `title`="", `content`=".", `type`="text"), list( `name`="ss", `title`="Sum of Squares", `type`="number"), list( `name`="df", `title`="df", `type`="integer"), list( `name`="ms", `title`="Mean Square", `type`="number"), list( `name`="F", `title`="F", `type`="number"), list( `name`="p", `title`="p", `type`="number", `format`="zto,pvalue"), list( `name`="ges", `title`="\u03B7\u00B2<sub>G</sub>", `type`="number", `format`="zto", `visible`="(effectSize:ges)"), list( `name`="eta", `title`="\u03B7\u00B2", `type`="number", `format`="zto", `visible`="(effectSize:eta)"), list( `name`="partEta", `title`="\u03B7\u00B2<sub>p</sub>", `type`="number", `format`="zto", `visible`="(effectSize:partEta)"), list( `name`="omega", `title`="\u03C9\u00B2", `type`="number", `format`="zto", `visible`="(effectSize:omega)")))) self$add(R6::R6Class( inherit = jmvcore::Group, active = list( spherTable = function() private$.items[["spherTable"]], leveneTable = function() private$.items[["leveneTable"]], qq = function() private$.items[["qq"]]), private = list(), public=list( initialize=function(options) { super$initialize( options=options, name="assump", title="Assumptions") self$add(jmvcore::Table$new( options=options, name="spherTable", title="Tests of Sphericity", visible="(spherTests)", clearWith=list( "dependent", "ss", "rmCells", "rmcModelTerms", "bscModelTerms", "bs", "rm", "cov", "rmTerms", "bsTerms"), columns=list( list( `name`="name", `title`="", `type`="text"), list( `name`="mauch", `title`="Mauchly's W", `type`="number"), list( `name`="p", `title`="p", `type`="number", `format`="zto,pvalue"), list( `name`="gg", `title`="Greenhouse-Geisser \u03B5", `type`="number"), list( `name`="hf", `title`="Huynh-Feldt \u03B5", `type`="number")))) self$add(jmvcore::Table$new( options=options, name="leveneTable", title="Homogeneity of Variances Test (Levene's)", visible="(leveneTest)", clearWith=list( "bs", "rmCells", "cov"), columns=list( list( `name`="name", `title`="", `type`="text"), list( `name`="F", `type`="number"), list( `name`="df1", `type`="integer"), list( `name`="df2", `type`="integer"), list( `name`="p", `type`="number", `format`="zto,pvalue")))) self$add(jmvcore::Image$new( options=options, name="qq", title="Q-Q Plot", visible="(qq)", width=450, height=400, renderFun=".qqPlot", clearWith=list( "dependent", "ss", "rmCells", "rmcModelTerms", "bscModelTerms", "bs", "rm", "cov", "rmTerms", "bsTerms")))}))$new(options=options)) self$add(jmvcore::Array$new( options=options, name="contrasts", title="Contrasts", items=0, visible="(contrasts)", template=jmvcore::Table$new( options=options, title="Contrasts - $key", rows=0, columns=list( list( `name`="contrast", `title`="", `type`="text"), list( `name`="est", `title`="Estimate", `type`="number"), list( `name`="se", `title`="SE", `type`="number"), list( `name`="t", `type`="number"), list( `name`="p", `title`="p", `type`="number", `format`="zto,pvalue"))))) self$add(jmvcore::Array$new( options=options, name="postHoc", title="Post Hoc Tests", items="(postHoc)", refs="emmeans", template=jmvcore::Table$new( options=options, title="", columns=list(), clearWith=list( "dependent", "ss", "rmCells", "rmcModelTerms", "bscModelTerms", "bs", "rm", "cov", "rmTerms", "bsTerms")))) self$add(jmvcore::Array$new( options=options, name="emm", title="Estimated Marginal Means", refs="emmeans", clearWith=list( "emMeans"), template=R6::R6Class( inherit = jmvcore::Group, active = list( emmPlot = function() private$.items[["emmPlot"]], emmTable = function() private$.items[["emmTable"]]), private = list(), public=list( initialize=function(options) { super$initialize( options=options, name="undefined", title="") self$add(jmvcore::Image$new( options=options, name="emmPlot", title="", width=450, height=400, renderFun=".emmPlot", visible="(emmPlots)", clearWith=list( "ciWidthEmm", "emmWeights", "rmCells", "rmcModelTerms", "bscModelTerms", "bs", "rm", "cov", "rmTerms", "bsTerms", "emmPlotData", "emmPlotError", "depLabel"))) self$add(jmvcore::Table$new( options=options, name="emmTable", title="", visible="(emmTables)", columns=list(), clearWith=list( "ciWidthEmm", "emmWeights", "rmCells", "rmcModelTerms", "bscModelTerms", "bs", "rm", "cov", "rmTerms", "bsTerms")))}))$new(options=options))) self$add(jmvcore::Table$new( options=options, name="groupSummary", title="Group Summary", visible="(groupSumm)", clearWith=list( "dep", "factors", "covs"), columns=list( list( `name`="n", `title`="N", `type`="integer"), list( `name`="ex", `title`="Excluded", `type`="integer"))))})) anovaRMBase <- if (requireNamespace("jmvcore", quietly=TRUE)) R6::R6Class( "anovaRMBase", inherit = jmvcore::Analysis, public = list( initialize = function(options, data=NULL, datasetId="", analysisId="", revision=0) { super$initialize( package = "jmv", name = "anovaRM", version = c(2,0,0), options = options, results = anovaRMResults$new(options=options), data = data, datasetId = datasetId, analysisId = analysisId, revision = revision, pause = NULL, completeWhenFilled = TRUE, requiresMissings = FALSE) })) anovaRM <- function( data, rm = list( list(label="RM Factor 1", levels=list( "Level 1", "Level 2"))), rmCells = NULL, bs = NULL, cov = NULL, effectSize = NULL, depLabel = "Dependent", rmTerms = NULL, bsTerms = NULL, ss = "3", spherTests = FALSE, spherCorr = list( "none"), leveneTest = FALSE, qq = FALSE, contrasts = NULL, postHoc = NULL, postHocCorr = list( "tukey"), emMeans = list( list()), emmPlots = TRUE, emmTables = FALSE, emmWeights = TRUE, ciWidthEmm = 95, emmPlotData = FALSE, emmPlotError = "ci", groupSumm = FALSE) { if ( ! requireNamespace("jmvcore", quietly=TRUE)) stop("anovaRM requires jmvcore to be installed (restart may be required)") if ( ! missing(bs)) bs <- jmvcore::resolveQuo(jmvcore::enquo(bs)) if ( ! missing(cov)) cov <- jmvcore::resolveQuo(jmvcore::enquo(cov)) if (missing(data)) data <- jmvcore::marshalData( parent.frame(), `if`( ! missing(bs), bs, NULL), `if`( ! missing(cov), cov, NULL)) for (v in bs) if (v %in% names(data)) data[[v]] <- as.factor(data[[v]]) if (inherits(rmTerms, "formula")) rmTerms <- jmvcore::decomposeFormula(rmTerms) if (inherits(bsTerms, "formula")) bsTerms <- jmvcore::decomposeFormula(bsTerms) if (inherits(emMeans, "formula")) emMeans <- jmvcore::decomposeFormula(emMeans) options <- anovaRMOptions$new( rm = rm, rmCells = rmCells, bs = bs, cov = cov, effectSize = effectSize, depLabel = depLabel, rmTerms = rmTerms, bsTerms = bsTerms, ss = ss, spherTests = spherTests, spherCorr = spherCorr, leveneTest = leveneTest, qq = qq, contrasts = contrasts, postHoc = postHoc, postHocCorr = postHocCorr, emMeans = emMeans, emmPlots = emmPlots, emmTables = emmTables, emmWeights = emmWeights, ciWidthEmm = ciWidthEmm, emmPlotData = emmPlotData, emmPlotError = emmPlotError, groupSumm = groupSumm) analysis <- anovaRMClass$new( options = options, data = data) analysis$run() analysis$results }
if (Sys.getenv("_R_CHECK_FULL_") != "") { library("PSCBS") data <- PSCBS::exampleData("paired.chr01") str(data) data <- data.frame(chromosome=data$chromosome, x=data$x, y=data$CT) dataS <- dropSegmentationOutliers(data) dataS <- dataS[seq(from=1, to=nrow(data), by=5),] str(dataS) gaps <- findLargeGaps(dataS, minLength=2e6) knownSegments <- gapsToSegments(gaps) fit <- segmentByCBS(dataS, knownSegments=knownSegments, seed=0xBEEF, verbose=-10) signalType(fit) <- "ratio" fit1 <- fit fit2 <- renameChromosomes(fit, from=1, to=2) fit <- c(fit1, fit2) report(fit, sampleName="CBS", studyName="CBS-Ex", verbose=-10) }
if(!requireNamespace("purrr", quietly = TRUE)) stop("purrr package required.") library(purrr) cmuarctic_df <- torchaudio::cmuarctic_dataset(system.file("", package = "torchaudio")) spectrogram_spec <- torchaudio::transform_spectrogram(n_fft = 255) spectrograms = map(seq.int(cmuarctic_df), ~{ s <-spectrogram_spec(cmuarctic_df[.x][[1]]) s <- s[..,1:100] s <- torch::torch_mean(s, 1) }) spectrograms = torch::torch_stack(spectrograms) test_that("model_resblock", { resblock = model_resblock() expect_no_error(x <- resblock(spectrograms)) expect_tensor(x) expect_true(x$requires_grad) }) test_that("model_melresnet", { melresnet <- model_melresnet() expect_no_error(x <- melresnet(spectrograms)) expect_tensor(x) expect_true(x$requires_grad) }) test_that("model_stretch2d", { stretch2d <- model_stretch2d(freq_scale = 1L, time_scale = 1L) expect_no_error(x <- stretch2d(spectrograms)) expect_tensor(x) expect_false(x$requires_grad) }) test_that("model_upsample_network", { upsamplenetwork = model_upsample_network(upsample_scales=c(4, 4, 16)) input = torch::torch_rand (3, 128, 10) output = upsamplenetwork (input) expect_equal(dim(output[[1]]), c(3, 128, (10 - 5 + 1)*(4*4*16))) expect_equal(dim(output[[2]]), c(3, 128, (10 - 5 + 1)*(4*4*16))) }) test_that("model_wavernn", { wavernn = model_wavernn(upsample_scales=c(2,2,3), n_classes=5, hop_length=12) waveform = torch::torch_rand(3,1,(10 - 5 + 1)*12) spectrogram = torch::torch_rand(3,1,128,10) expect_no_error(output <- wavernn (waveform, spectrogram)) expect_tensor(output) expect_equal(dim(output), c(3, 1, (10 - 5 + 1) * 12, 5)) })
simulate_modelvariants_ode <- function(U = 1e5, I = 0, V = 10, F=0, A=0, n = 0, dU = 0, dI = 1, dV = 4, b = 1e-5, p = 100, pF=1, dF=1, f1 = 1e-4, f2 = 0, f3 = 0, Fmax = 1e3, sV = 1e-10, k1 = 1e-3, k2 = 0, k3 = 0, a1 = 1e3, a2 = 0, a3 = 0, hV = 1e-10, k4 = 1e-3, k5 = 0, k6 = 0, sA = 1e-10, dA = 0.1, tstart = 0, tfinal = 20, dt = 0.01) { modelvariantode <- function(t, y, parms) { with( as.list(c(y,parms)), { dUdt = n - dU*U - b*V*U - k1*F*U dIdt = b*V*U - dI*I - k2*F*I - k4*A*I - k5*A*I/(A+sA) dVdt = p*I/(1+k3*F) - dV*V - b*V*U - k6*A*V dFdt = pF - dF*F + f1 *V*(Fmax - F) + f2 * V / (V+sV)*F + f3 *V*I / (V*I+sV)*F dAdt = a1*F*A + a2*V/(V+hV)*F + a3 * F * V / (F * V + hV) * A - dA * A list(c(dUdt, dIdt, dVdt, dFdt, dAdt)) } ) } Y0 = c(U = U, I = I, V = V, F = F, A = A); timevec = seq(tstart, tfinal, dt); pars = c(n=n,dU=dU,dI=dI,dV=dV,b=b,p=p,pF=pF,dF=dF,f1=f1,f2=f2,f3=f3,Fmax=Fmax,sV=sV,k1=k1,k2=k2,k3=k3,a1=a1,a2=a2,a3=a3,hV=hV,k4=k4,k5=k5,k6=k6,sA=sA, dA = dA); odeoutput = deSolve::ode(y = Y0, times = timevec, func = modelvariantode, parms=pars, atol=1e-12, rtol=1e-12); result = list() result$ts = as.data.frame(odeoutput) return(result) }
data{ n <- length(distance) n.papers <- max(paper) n.angles <- max(angle) n.designs <- max(design) } model{ for (i in 1:n) { distance[i] ~ dnorm(b0, tau) } for (j in 2:n.papers) { b1[j] <- paper[j] } for (k in 2:n.angles) { b2[k] <- angle[k] } for (m in 2:n.designs) { b3[m] <- design[m] } tau ~ dgamma(0.001, 0.001) b0 ~ dnorm(0, 1e-09) }
sgee.control <- function(maxIt = 200 , epsilon = 0.05, stoppingThreshold = NULL, undoThreshold = 0.005, interceptLimit = NULL, stochastic = 1, sampleProb = NULL, reSample = 1, withReplacement = FALSE){ if(epsilon <= 0){ stop("epsilon must be >0") } if(epsilon >=1){ warning("It is advised that epsilon be sufficiently small") } if(maxIt <= 0){ stop("maxIt must be >0") } if(!is.null(stoppingThreshold)){ if(stoppingThreshold<1){ stop("stoppingThreshold must be >1") } } if(!is.null(interceptLimit)){ if(interceptLimit<=0){ stop("interceptLimit must be >0") } } if(stochastic>1 | stochastic<=0){ stop("paramter 'stochastic' indicates percentage of data being subsample and must be greater than 0 and less than or equal to 1") } if(reSample <0 | reSample %% 1 != 0){ stop("parameter 'reSample' indicates how frequently a subsample is collected (i.e. reSample == 1 implies every iteration, reSample == 2 implies every other iteration). Therefore, reSample must be a non-negative integer") } list(maxIt = maxIt, epsilon = epsilon, stoppingThreshold = stoppingThreshold, undoThreshold = undoThreshold, stochastic = stochastic, sampleProb = sampleProb, reSample = reSample, withReplacement = withReplacement) }
library(stringr) library(tableschema.r) library(testthat) library(foreach) library(lubridate) library(config) context("types.castTime") Time <- function(hour, minute=0, second=0) { value <- lubridate::as_datetime(lubridate::make_datetime(0, 0, 1, hour, minute, second,tz = "UTC")) unlist(strsplit(as.character(value), " "))[[2]] } TESTS <- list( list('default', Time(6), Time(6)), list('default', '06:00:00', Time(6)), list('default', '09:00', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))), list('default', '3 am', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))), list('default', '3.00', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))), list('default', 'invalid', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))), list('default', TRUE, config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))), list('default', '', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))), list('any', Time(6), Time(6)), list('any', 'some night', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))), list('any', 'invalid', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))), list('any', TRUE, config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))), list('any', '', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))), list('%H:%M', Time(6), Time(6)), list('%H:%M', 'some night', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))), list('%H:%M', 'invalid', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))), list('%H:%M', TRUE, config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))), list('%H:%M', '', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))), list('invalid', '', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))), list('fmt:%M:%H', '06:50', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))), list('fmt:%H:%M', 'some night', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))), list('fmt:%H:%M', 'invalid', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))), list('fmt:%H:%M', TRUE, config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))), list('fmt:%H:%M', '', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))) ) foreach(j = seq_along(TESTS) ) %do% { TESTS[[j]] <- setNames(TESTS[[j]], c("format", "value", "result")) test_that(str_interp('format "${TESTS[[j]]$format}" should check "${TESTS[[j]]$value}" as "${TESTS[[j]]$result}"'), { expect_equal(types.castTime(TESTS[[j]]$format, TESTS[[j]]$value), TESTS[[j]]$result) }) }
utility.endnode.cond.create <- function(name.node, attrib.levels, nodes, utility = TRUE, required = FALSE, col = "black", shift.levels = 0) { check.ok <- T if ( !is.data.frame(attrib.levels) ) { cat("*** Warning: attrib.levels must be a data frame","\n") check.ok <- F } if ( length(names(attrib.levels)) != length(unique(names(attrib.levels))) ) { cat("*** Warning: Column names of attrib.levels must be different","\n") check.ok <- F } if ( nrow(attrib.levels) != length(nodes) ) { cat("*** Warning: Number of rows of attrib.levels not equal to", "number of nodes provided:",nrow(attrib.levels),length(nodes),"\n") check.ok <- F } if ( length(nodes) < 1 ) { cat("*** Warning: No nodes provided","\n") check.ok <- F } for ( i in 1:length(nodes) ) { if ( nodes[[i]]$utility != utility ) { funtype <- "utility"; if ( !utility ) funtype <- "value" funtype.i <- "utility"; if ( !nodes[[i]]$utility ) funtype.i <- "value" cat("***Warning: incompatible function types: new node is of type", funtype,"node",nodes[[i]]$name," is of type",funtype.i,"\n") check.ok <- F } } if ( ! check.ok ) { cat("*** Warning: Node \"",name.node,"\" could not be constructed","\n", sep="") return(NA) } node <- list() node$name <- name.node node$description <- "utility/value conditional combination end node" node$type <- "endnode" node$attrib.levels <- attrib.levels for ( i in 1:ncol(attrib.levels) ) { node$attrib.levels[,i] <- as.character(node$attrib.levels[,i]) } node$attrib <- names(attrib.levels) for ( i in 1:length(nodes) ) { node$attrib <- c(node$attrib,nodes[[i]]$attrib) } node$attrib <- unique(node$attrib) node$nodes <- nodes node$required <- required node$utility <- utility node$col <- col node$shift.levels <- shift.levels class(node) <- "utility.endnode.cond" return(node) } updatepar.utility.endnode.cond <- function(x,par=NA,...) { node <- x if ( length(names(par)) == 0 ) return(node) n <- node for ( i in 1:length(n$nodes) ) { n$nodes[[i]] <- updatepar(n$nodes[[i]],par) } return(n) } evaluate.utility.endnode.cond <- function(x, attrib, par=NA, ...) { as.character.na <- function(x,...) { return(ifelse(is.na(x),"",as.character(x,...))) } node <- x if ( ! is.data.frame(attrib) ) { warning("Node \"",node$name,"\": attrib must be a data frame",sep="") return(NA) } ind <- match(node$attrib,names(attrib)) if(sum(is.na(ind))>0) { ind.na <- is.na(ind) warning("Node \"",node$name,"\": attribute(s) \"", paste(node$attrib[ind.na],collapse=","),"\" not found",sep="") return(rep(NA,nrow(attrib))) } n <- updatepar(node,par) u <- rep(NA,nrow(attrib)) calc <- rep(FALSE,nrow(attrib)) while( TRUE ) { startind <- match(FALSE,calc) if ( is.na(startind) ) break ind.attrib <- as.character.na(attrib[startind,names(n$attrib.levels)[1]]) == as.character.na(attrib[,names(n$attrib.levels)[1]]) if ( ncol(n$attrib.levels) > 1 ) { for ( i in 2:ncol(n$attrib.levels) ) { ind.attrib <- ind.attrib & ( as.character.na(attrib[startind,names(n$attrib.levels)[i]]) == as.character.na(attrib[,names(n$attrib.levels)[i]]) ) } } ind.attrib <- which(ind.attrib) ind.node <- as.character.na(attrib[startind,names(n$attrib.levels)[1]]) == as.character.na(n$attrib.levels[,names(n$attrib.levels)[1]]) if ( ncol(n$attrib.levels) > 1 ) { for ( i in 2:ncol(n$attrib.levels) ) { ind.node <- ind.node & ( as.character.na(n$attrib.levels[,names(n$attrib.levels)[i]]) == as.character.na(attrib[startind,names(n$attrib.levels)[i]]) ) } } ind.node <- which(ind.node) if ( length(ind.node) > 0 ) { u[ind.attrib] <- evaluate(n$nodes[[ind.node[1]]],attrib[ind.attrib,]) if ( length(ind.node) > 1 ) { cat("*** Warning: multiple combinations of the same", "attribute levels in node",n$name,"\n") } } calc[ind.attrib] <- T } return(u) } print.utility.endnode.cond <- function(x,...) { cat(paste(rep("-",50),collapse=""),"\n") summary(x,...) cat(paste(rep("-",50),collapse=""),"\n") } summary.utility.endnode.cond <- function(object,...) { node <- object cat(node$name,"\n") cat(paste(rep("-",nchar(node$name)),collapse=""),"\n") cat(node$description,"\n") funtype <- "utility"; if ( !node$utility ) funtype <- "value" cat("function type: ",funtype,"\n") cat("required: ",node$required,"\n") cat("attribute/node combinations:","\n") nodes.names <- character(0) for ( i in 1:length(node$nodes) ) nodes.names[i] <- node$nodes[[i]]$name print(cbind(node$attrib.levels,node=nodes.names)) for ( i in 1:length(node$nodes) ) { cat("**","\n") summary(node$nodes[[i]]) } } plot.utility.endnode.cond <- function(x, par = NA, col = utility.calc.colors(), gridlines = c(0.2,0.4,0.6,0.8), main = "", cex.main = 1, nodes = x$name, ...) { node <- x if ( is.na(nodes[1]) | ! is.na(match(node$name,nodes)) ) { nrow <- floor(sqrt(length(node$nodes))) ncol <- floor(length(node$nodes)/nrow+0.999) par.def <- par(no.readonly=T) par(mfrow=c(nrow,ncol),mar=c(4.3,3.8,2.8,0.8),oma=c(0,0,2,0)) for ( i in 1:length(node$nodes) ) { title <- main for ( j in 1:ncol(node$attrib.levels) ) { title <- paste(title," ",colnames(node$attrib.levels)[j],"=", as.character(node$attrib.levels[i,j]),sep="") } plot(node$nodes[[i]],par=par,col=col,gridlines=gridlines,main=title,cex.main=cex.main,...) } mtext(node$name,outer=TRUE,cex=cex.main) par(par.def) } if ( length(node$nodes) > 0 ) { for ( i in 1:length(node$nodes) ) { if ( is.na(nodes[1]) | !is.na(match(node$nodes[[i]]$name,nodes)) ) { plot(node$nodes[[i]], par=par, col=col, gridlines=gridlines, cex.main=cex.main, ...) } } } }
dfa_fitted <- function(modelfit, conf_level = 0.95, names = NULL) { pred <- predicted(modelfit) n_mcmc <- dim(pred)[1] n_chains <- dim(pred)[2] n_years <- dim(pred)[3] n_ts <- dim(pred)[4] df_pred <- data.frame( "ID" = rep(seq_len(n_ts), n_years), "time" = sort(rep(seq_len(n_years), n_ts)), "estimate" = c(t(apply(pred, c(3, 4), mean))), "lower" = c(t(apply(pred, c(3, 4), quantile, 1 - (1 - conf_level) / 2))), "upper" = c(t(apply(pred, c(3, 4), quantile, (1 - conf_level) / 2))) ) if (modelfit$shape == "wide") { df_obs <- data.frame( "ID" = rep(seq_len(n_ts), n_years), "time" = sort(rep(seq_len(n_years), n_ts)), "y" = c(modelfit$orig_data) ) } else { df_obs <- data.frame( "ID" = modelfit$orig_data[["ts"]], "time" = modelfit$orig_data[["time"]], "y" = modelfit$orig_data[["obs"]] ) } df_obs$time <- df_obs$time - min(df_obs$time) + 1 for (i in seq_len(n_ts)) { indx <- which(df_obs[["ID"]] == i) df_obs[indx, "y"] <- scale(df_obs[indx, "y"], center = TRUE, scale = TRUE) } df_obs <- df_obs[order(df_obs$ID, df_obs$time), ] df_pred <- df_pred[order(df_pred$ID, df_pred$time), ] if (!is.null(names)) { if (length(names) != n_ts) { warning("bayesdfa: Length of 'names' should match number of time series. Ignoring 'names'.") } else { df_pred$ID <- names[df_pred$ID] df_obs$ID <- names[df_obs$ID] } } df <- merge(df_obs, df_pred, by = c("ID", "time"), sort = FALSE) return(df) }
NULL qqplotprecWGEN <- function (measured,simulated,xlab="simulated[mm]",ylab="measured[mm]",title="daily precipitation",station=NULL,diff=FALSE,quantile=0) { ncols=1 name <- names(as.data.frame(simulated)) if (is.null(station)) { nrows=ncol(measured) istation=1:ncols } else { istation=which(name %in% station) nrows=length(istation) } par(mfrow=c(nrows,ncols)) xlim <- c(min(simulated,na.rm=TRUE),max(simulated,na.rm=TRUE)) ylim <- c(min(measured,na.rm=TRUE),max(measured,na.rm=TRUE)) for (r in 1:nrows) { for (c in 1:ncols) { main=paste(title,name[r],sep=" ") qqplotWGEN(val=cbind(simulated[,r],measured[,r]),ylab=ylab,xlab=xlab,xlim=xlim,ylim=ylim,main=main,diff=diff,quantile=quantile) } } return(0) }
evaluate_model <- function(seminr_model) { rel <- reliability(seminr_model) val <- validity(seminr_model) out <- list(rel,val) names(out) <- c("reliability", "validity") return(out) } reliability <- function(seminr_model) { alpha <- cronbachs_alpha(seminr_model) mat1 <- rhoC_AVE(seminr_model) mat2 <- rho_A(seminr_model) table <- cbind(alpha, mat1, mat2) comment(table) <- "Alpha, rhoC, and rhoA should exceed 0.7 while AVE should exceed 0.5" class(table) <- append(class(table), c("table_output","reliability_table")) return(table) } validity <- function(seminr_model) { list( htmt = HTMT(seminr_model), cross_loadings = cross_loadings(seminr_model), item_vifs = item_vifs(seminr_model), antecedent_vifs = antecedent_vifs(seminr_model$smMatrix, stats::cor(seminr_model$construct_scores)), fl_criteria = fl_criteria_table(seminr_model) ) } cross_loadings <- function(seminr_model) { ret <- stats::cor(seminr_model$data[, seminr_model$mmVariables], seminr_model$construct_scores) convert_to_table_output(ret) } evaluate_measurement_model <- function(object, na.print=".", digits=3, ...) { stopifnot(inherits(object, "seminr_model")) factors <- get_factors(object) composites <- get_composites(object) factor_items <- unlist(sapply(factors, items_of_construct, object)) composite_items <- unlist(sapply(composites, items_of_construct, object)) metrics <- evaluate_model(object) if (length(factors) == 1) { factor_reliability <- as.matrix(t(metrics$reliability[factors, c("AVE", "rhoA")])) rownames(factor_reliability) <- factors factor_indicator_reliability <- as.matrix(object$outer_loadings[factor_items, factors]) colnames(factor_indicator_reliability) <- factors discriminant_validity <- HTMT(object) } else if (length(factors) > 1) { factor_reliability <- metrics$reliability[factors, c("AVE", "rhoA")] factor_indicator_reliability <- object$outer_loadings[factor_items, factors] discriminant_validity <- HTMT(object) } else { factor_reliability <- NA factor_indicator_reliability <- NA discriminant_validity <- NA } if (length(composites) == 1) { composite_indicator_reliability <- as.matrix(object$outer_weights[composite_items, composites]) colnames(composite_indicator_reliability) <- composites } else if (length(composites) > 1) { composite_indicator_reliability <- object$outer_weights[composite_items, composites] } else { composite_indicator_reliability <- NA } message("Measurement Model Evaluation:") message("------------------Factors:------------------") message("1. Indicator Reliability:\nLoadings:") message(factor_indicator_reliability) message("\n2. Factor Reliability and Convergent Validity:") message(factor_reliability) message("\n3. Discriminant Validity") message("HTMT") message(discriminant_validity) message("\n------------------Composites:---------------") message("1. Indicator Reliability:\nWeights:") message(composite_indicator_reliability) message("\n2. Collinearity:\nItem VIFs per Construct:") message(metrics$validity$item_vifs[composites]) measurement_model_evaluation <- list(factor_reliability = factor_reliability, factor_indicator_reliability = factor_indicator_reliability, factor_discriminant_validity = discriminant_validity, composite_indicator_reliability = composite_indicator_reliability, composite_collinearity = metrics$validity$item_vifs[composites]) class(measurement_model_evaluation) <- "measurement_model_evaluation.seminr_model" return(measurement_model_evaluation) } boot_evaluate_measurement_model <- function(object, na.print=".", digits=3, ...) { stopifnot(inherits(object, "boot_seminr_model")) factors <- get_factors(object) composites <- get_composites(object) factor_items <- unlist(sapply(factors, items_of_construct, object)) composite_items <- unlist(sapply(composites, items_of_construct, object)) metrics <- evaluate_model(object) weights_boot_matrix <- object$weights_descriptives num_composites <- ncol(weights_boot_matrix) / 3 column_names <- colnames(weights_boot_matrix)[1:num_composites] weights_boot_mean <- as.matrix(weights_boot_matrix[, c((1*num_composites+1):(2*num_composites))]) weights_boot_SE <- as.matrix(weights_boot_matrix[, c((2*num_composites+1):(3*num_composites))]) weights_boot_t <- abs(weights_boot_mean / weights_boot_SE) weights_boot_p <- 2*stats::pt(weights_boot_t, df = object$boots-1, lower.tail = FALSE) colnames(weights_boot_t) <- object$constructs colnames(weights_boot_p) <- object$constructs HTMT_boot_matrix <- object$HTMT_descriptives num_factors <- ncol(HTMT_boot_matrix) / 3 factor_names <- colnames(HTMT_boot_matrix)[1:num_factors] HTMT_boot_mean <- as.matrix(HTMT_boot_matrix[, c((1*num_factors+1):(2*num_factors))]) HTMT_boot_SE <- as.matrix(HTMT_boot_matrix[, c((2*num_factors+1):(3*num_factors))]) HTMT_boot_t <- abs((HTMT_boot_mean-1) / HTMT_boot_SE) HTMT_boot_p <- 2*stats::pt(HTMT_boot_t, df = object$boots-1, lower.tail = FALSE) colnames(HTMT_boot_t) <- colnames(HTMT(object)) colnames(HTMT_boot_p) <- colnames(HTMT(object)) discriminant_validity <- HTMT(object) discriminant_validity_t <- HTMT_boot_t discriminant_validity_p <- HTMT_boot_p if (length(factors) == 1) { factor_reliability <- as.matrix(t(metrics$reliability[factors, c("AVE", "rhoA")])) rownames(factor_reliability) <- factors factor_indicator_reliability <- as.matrix(object$outer_loadings[factor_items, factors]) colnames(factor_indicator_reliability) <- factors } else if (length(factors) > 1) { factor_reliability <- metrics$reliability[factors, c("AVE", "rhoA")] factor_indicator_reliability <- object$outer_loadings[factor_items, factors] } else { factor_reliability <- NA factor_indicator_reliability <- NA discriminant_validity <- NA discriminant_validity_t <- NA discriminant_validity_p <- NA } if (length(composites) == 1) { composite_indicator_reliability <- as.matrix(object$outer_weights[composite_items, composites]) composite_indicator_weights_t <- as.matrix(weights_boot_t[composite_items, composites]) composite_indicator_weights_p <- as.matrix(weights_boot_p[composite_items, composites]) colnames(composite_indicator_reliability) <- composites } else if (length(composites) > 1) { composite_indicator_reliability <- object$outer_weights[composite_items, composites] composite_indicator_weights_t <- weights_boot_t[composite_items, composites] composite_indicator_weights_p <- weights_boot_p[composite_items, composites] } else { composite_indicator_reliability <- NA composite_indicator_weights_t <- NA composite_indicator_weights_p <- NA } composite_indicator_weights_t[is.nan(composite_indicator_weights_t)] <- NA composite_indicator_weights_p[is.nan(composite_indicator_weights_p)] <- NA message("Boot Measurement Model Evaluation:") message("\n------------------Factors:------------------") message("1. Indicator Reliability:\nLoadings:") message(factor_indicator_reliability) message("\n2. Factor Reliability and Convergent Validity:") message(factor_reliability) message("\n3. Discriminant Validity") message("HTMT") message(discriminant_validity) message("HTMT t-values:") message(discriminant_validity_t) message("HTMT p-values:") message(discriminant_validity_p) message("\n------------------Composites:---------------") message("1. Indicator Reliability:\nWeights:") message(composite_indicator_reliability) message("\n Weights t-values:") message(composite_indicator_weights_t) message("\n Weights p-values:") message(composite_indicator_weights_p) message("\n2. Collinearity:\nItem VIFs per Construct:") message(metrics$validity$item_vifs[composites]) boot_measurement_model_evaluation <- list(factor_reliability = factor_reliability, factor_indicator_reliability = factor_indicator_reliability, factor_discriminant_validity = discriminant_validity, factor_discriminant_validity_t_values = discriminant_validity_t, factor_discriminant_validity_p_values = discriminant_validity_p, composite_indicator_reliability = composite_indicator_reliability, composite_indicator_weights_t_values = composite_indicator_weights_t, composite_indicator_weights_p_values = composite_indicator_weights_p, composite_collinearity = metrics$validity$item_vifs[composites]) class(boot_measurement_model_evaluation) <- "measurement_model_evaluation.boot_seminr_model" return(boot_measurement_model_evaluation) }
svc <- paws::lightsail()
context("ml feature bucketizer") skip_databricks_connect() test_that("ft_bucketizer() default params", { test_requires_latest_spark() sc <- testthat_spark_connection() test_default_args(sc, ft_bucketizer) }) test_that("ft_bucketizer() param setting", { test_requires_latest_spark() sc <- testthat_spark_connection() test_args <- list( input_col = "x", output_col = "y", splits = c(-1, 34, 100), handle_invalid = "keep" ) test_param_setting(sc, ft_bucketizer, test_args) test_args2 <- list( input_cols = c("x1", "x2"), output_cols = c("y1", "y2"), splits_array = list(c(-1, 34, 100), c(-5, 0, 2)), handle_invalid = "keep" ) test_param_setting(sc, ft_bucketizer, test_args2) }) test_that("ft_bucketizer() works properly", { mtcars_tbl <- testthat_tbl("mtcars") expect_identical( mtcars_tbl %>% select(drat) %>% ft_bucketizer( "drat", "drat_out", splits = c(-Inf, 2, 4, Inf) ) %>% colnames(), c("drat", "drat_out") ) }) test_that("ft_bucketizer() can mutate multiple columns", { test_requires_version("2.3.0", "multiple column support requires 2.3+") mtcars_tbl <- testthat_tbl("mtcars") expect_identical( mtcars_tbl %>% select(drat, hp) %>% ft_bucketizer( input_cols = c("drat", "hp"), output_cols = c("drat_out", "hp_out"), splits_array = list(c(-Inf, 2, 4, Inf), c(-Inf, 90, 120, Inf)) ) %>% colnames(), c("drat", "hp", "drat_out", "hp_out") ) })
field_caps <- function(conn, fields, index = NULL, ...) { is_conn(conn) conn$stop_es_version(540, "field_caps") fields <- paste(fields, collapse = ",") tt <- es_GET(conn, "_field_caps", index = index, fields = fields, callopts = list(...)) jsonlite::fromJSON(tt) }
T10 <- function(time, nger) { N <- max(nger) ni <- max(nger) ti <- max(time) nj <- min(nger) tj <- min(time) for (i in length(time):1) { if (ni > ((N)/(100/10))) { ni = nger[i] ti = time[i] } } for (j in 1:length(time)) { if (nj < ((N)/(100/10))) { nj = nger[j] tj = time[j] } } result <- ti + (((N)/(100/10) - ni)*(tj - ti))/(nj-ni) return(result) }
aqs_qa_blanks_by_MA <- function(parameter, bdate, edate, MA_code, cbdate = NA_Date_, cedate = NA_Date_, return_header = FALSE ) { checkaqsparams(parameter, bdate, edate, MA_code, cbdate, cedate, return_header) params <- aqsmultiyearparams(parameter = parameter, bdate = bdate, edate = edate, MA_code = MA_code, service = "qaBlanks", cbdate = cbdate, cedate = cedate ) blanks <- purrr::pmap(.l = params, .f = aqs_services_by_MA) if (!return_header) blanks %<>% aqs_removeheader return(blanks) } aqs_qa_collocated_assessments_by_MA <- function(parameter, bdate, edate, MA_code, cbdate = NA_Date_, cedate = NA_Date_, return_header = FALSE ) { checkaqsparams(parameter, bdate, edate, MA_code, cbdate, cedate, return_header) params <- aqsmultiyearparams(parameter = parameter, bdate = bdate, edate = edate, MA_code = MA_code, service = "qaCollocatedAssessments", cbdate = cbdate, cedate = cedate ) colocatedsummary <- purrr::pmap(.l = params, .f = aqs_services_by_MA) if (!return_header) colocatedsummary %<>% aqs_removeheader return(colocatedsummary) } aqs_qa_flowrateverification_by_MA <- function(parameter, bdate, edate, MA_code, cbdate = NA_Date_, cedate = NA_Date_, return_header = FALSE) { checkaqsparams(parameter, bdate, edate, MA_code, cbdate, cedate, return_header) params <- aqsmultiyearparams(parameter = parameter, bdate = bdate, edate = edate, MA_code = MA_code, service = "qaFlowRateVerifications", cbdate = cbdate, cedate = cedate ) frv <- purrr::pmap(.l = params, .f = aqs_services_by_MA) if (!return_header) frv %<>% aqs_removeheader return(frv) } aqs_qa_flowrateaudit_by_MA <- function(parameter, bdate, edate, MA_code, cbdate = NA_Date_, cedate = NA_Date_, return_header = FALSE ) { checkaqsparams(parameter, bdate, edate, MA_code, cbdate, cedate, return_header) params <- aqsmultiyearparams(parameter = parameter, bdate = bdate, edate = edate, MA_code = MA_code, service = "qaFlowRateAudits", cbdate = cbdate, cedate = cedate ) fra <- purrr::pmap(.l = params, .f = aqs_services_by_MA) if (!return_header) fra %<>% aqs_removeheader return(fra) } aqs_qa_one_point_qc_by_MA <- function(parameter, bdate, edate, MA_code, cbdate = NA_Date_, cedate = NA_Date_, return_header = FALSE ) { checkaqsparams(parameter, bdate, edate, MA_code, cbdate, cedate, return_header) params <- aqsmultiyearparams(parameter = parameter, bdate = bdate, edate = edate, MA_code = MA_code, service = "qaOnePointQcRawData", cbdate = cbdate, cedate = cedate ) opqcc <- purrr::pmap(.l = params, .f = aqs_services_by_MA) if (!return_header) opqcc %<>% aqs_removeheader return(opqcc) } aqs_qa_pep_audit_by_MA <- function(parameter, bdate, edate, MA_code, cbdate = NA_Date_, cedate = NA_Date_, return_header = FALSE) { checkaqsparams(parameter, bdate, edate, MA_code, cbdate, cedate, return_header) params <- aqsmultiyearparams(parameter = parameter, bdate = bdate, edate = edate, MA_code = MA_code, service = "qaPepAudits", cbdate = cbdate, cedate = cedate ) pepaudit <- purrr::pmap(.l = params, .f = aqs_services_by_MA) if (!return_header) pepaudit %<>% aqs_removeheader return(pepaudit) } aqs_transactionsample_by_MA <- function(parameter, bdate, edate, MA_code, cbdate = NA_Date_, cedate = NA_Date_, return_header = FALSE ) { checkaqsparams(parameter, bdate, edate, MA_code, cbdate, cedate, return_header) params <- aqsmultiyearparams(parameter = parameter, bdate = bdate, edate = edate, MA_code = MA_code, service = "transactionsSample" ) transactionsample <- purrr::pmap(.l = params, .f = aqs_services_by_MA) if (!return_header) transactionsample %<>% aqs_removeheader return(transactionsample) } aqs_qa_annualpeferomanceeval_by_MA <- function(parameter, bdate, edate, MA_code, return_header = FALSE) { checkaqsparams(parameter, bdate, edate, MA_code, return_header) params <- aqsmultiyearparams(parameter = parameter, bdate = bdate, edate = edate, MA_code = MA_code, service = "qaAnnualPerformanceEvaluations" ) qaape <- purrr::pmap(.l = params, .f = aqs_services_by_MA) if (!return_header) qaape %<>% aqs_removeheader return(qaape) } aqs_qa_annualperformanceevaltransaction_by_MA <- function(parameter, bdate, edate, MA_code, return_header = FALSE) { checkaqsparams(parameter, bdate, edate, MA_code, return_header) params <- aqsmultiyearparams(parameter = parameter, bdate = bdate, edate = edate, MA_code = MA_code, service = "transactionsQaAnnualPerformanceEvaluations" ) tqaape <- purrr::pmap(.l = params, .f = aqs_services_by_MA) if (!return_header) tqaape %<>% aqs_removeheader return(tqaape) }
emit_message <- function(..., .format = NULL, .f_name = TRUE, .issue = TRUE) { calling_fcn <- deparse(sys.call(-1)) if (.issue) { input_components <- list(...) named_numeric_input_components <- get_named_numeric_input_components( input_components = input_components) named_nonnumeric_input_components <- get_named_nonnumeric_input_components( input_components = input_components) unnamed_input_components <- get_unnamed_input_components( input_components = input_components) numeric_refs <- names(named_numeric_input_components) nonnumeric_refs <- names(named_nonnumeric_input_components) text <- squash_all_text(unnamed_input_components) format_str <- process_format_str(.format = .format) .f_name <- process_function_name( .f_name = .f_name, calling_fcn = calling_fcn) format_str <- glue::glue(format_str) %>% as.character() format_str <- format_str %>% reprocess_grammar( named_numeric_input_components = named_numeric_input_components, named_nonnumeric_input_components = named_nonnumeric_input_components) format_str %>% as.character() %>% message() } }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) Sys.setenv(LANGUAGE="en") library(robust2sls) p <- generate_param(dx1 = 3, dx2 = 2, dz2 = 3, intercept = TRUE, seed = 10) library(parallel) ncores <- 2 cl <- makeCluster(ncores) invisible(clusterCall(cl = cl, function(x) .libPaths(x), .libPaths())) library(doParallel) registerDoParallel(cl) sim1 <- mc_grid(M = 100, n = c(100, 1000), seed = 42, parameters = p, formula = p$setting$formula, ref_dist = "normal", sign_level = 0.05, initial_est = "robustified", iterations = 0, shuffle = FALSE, shuffle_seed = 42, split = 0.5) library(doFuture) registerDoFuture() plan(cluster, workers = cl) sim2 <- mc_grid(M = 100, n = c(100, 1000), seed = 42, parameters = p, formula = p$setting$formula, ref_dist = "normal", sign_level = 0.05, initial_est = "robustified", iterations = 0, shuffle = FALSE, shuffle_seed = 42, split = 0.5) stopCluster(cl) identical(sim1, sim2) library(doFuture) registerDoFuture() plan(sequential) sim3 <- mc_grid(M = 100, n = c(100, 1000), seed = 42, parameters = p, formula = p$setting$formula, ref_dist = "normal", sign_level = 0.05, initial_est = "robustified", iterations = 0, shuffle = FALSE, shuffle_seed = 42, split = 0.5) identical(sim1, sim3)
test_that("auto item value", { out <- autoItemValuesMinMaxConstraint(nForms = 2, itemValues = c(1, 1, 1, 1), allowedDeviation = 0, verbose = FALSE, itemIDs = 1:4) expect_equal(out$A_binary[1, ], c(1, 1, 1, 1, 0, 0, 0, 0)) expect_equal(out$A_binary[4, ], c(0, 0, 0, 0, 1, 1, 1, 1)) expect_equal(out$d, c(min = 2 , min = 2, max = 2, max = 2)) out <- autoItemValuesMinMaxConstraint(nForms = 2, itemValues = c(1, 1, 1, 1), allowedDeviation = .5, verbose = FALSE, itemIDs = 1:4) expect_equal(out$d, c(min = 1.5, min = 1.5, max = 2.5, max = 2.5)) expect_equal(out$operators, c(">=", ">=", "<=", "<=")) out <- autoItemValuesMinMaxConstraint(nForms = 2, itemValues = c(1, 1, 1, 1), verbose = FALSE, itemIDs = 1:4) expect_equal(out$d, c(2, 2)) expect_equal(out$operators, c("=", "=")) out <- autoItemValuesMinMaxConstraint(nForms = 2, itemValues = c(1, 1, 1, 1, 1), allowedDeviation = .5, verbose = FALSE, itemIDs = 1:5) expect_equal(out$A_binary[1, ], c(1, 1, 1, 1, 1, 0, 0, 0, 0, 0)) expect_equal(out$d, c(min = 2, min = 2, max = 3, max = 3)) expect_equal(out$operators, c(">=", ">=", "<=", "<=")) expect_equal(autoItemValuesMinMaxConstraint(nForms = 2, itemValues = c(1, 1, 1, 1), allowedDeviation = 1, verbose = FALSE, itemIDs = 1:4), autoItemValuesMinMaxConstraint(nForms = 2, itemValues = c(1, 1, 1, 1), allowedDeviation = .5, relative = TRUE, verbose = FALSE, itemIDs = 1:4)) }) test_that("auto item value with specific testlength", { out <- autoItemValuesMinMaxConstraint(nForms = 2, itemValues = c(1, 1, 1, 1), testLength = 1, allowedDeviation = 0, verbose = FALSE, itemIDs = 1:4) expect_equal(out$A_binary[1, ], c(1, 1, 1, 1, 0, 0, 0, 0)) expect_equal(out$A_binary[4, ], c(0, 0, 0, 0, 1, 1, 1, 1)) expect_equal(out$d, c(min = 1 , min = 1, max = 1, max = 1)) }) test_that("auto item value gives the correct messages + warnings", { expect_message(out <- autoItemValuesMinMaxConstraint(nForms = 2, itemValues = c(1, 1, 1, 1, 1), itemIDs = 1:5), "The target value per test form is: 2.5") expect_message(out <- autoItemValuesMinMaxConstraint(nForms = 2, itemValues = c(1, 1, 1, 1, 1), allowedDeviation = .5, itemIDs = 1:5), "The minimum and maximum values per test form are: min = 2 - max = 3") out <- capture_output(expect_message(out <- autoItemValuesMinMaxConstraint(nForms = 2, itemValues = factor(rep(1:2, 5)), itemIDs = 1:10), "The minimum and maximum frequences per test form for each item category are")) expect_warning(out <- autoItemValuesMinMaxConstraint(nForms = 2, itemValues = c(1, 1, 1, 1), allowedDeviation = 0, verbose = FALSE), "Argument 'itemIDs' is missing. 'itemIDs' will be generated automatically.") })
knitr::opts_chunk$set( message = FALSE, warning = FALSE, error = FALSE, tidy = FALSE, cache = FALSE ) library(sortable) library(htmltools) sortable_js(css_id = "example01") library(htmltools) tagList( tags$ul( id = "example02", tags$li("drag me"), tags$li("sort me"), tags$li("any way you like") ), sortable_js("example02") ) library(base64) library(withr) pngfile_1 <- tempfile(fileext = ".png") with_png(pngfile_1, width = 300, height = 200,{ plot(1:100, rnorm(100), pch = 21, bg = "red") title(main = "Moves Like Jagger") }) pngfile_2 <- tempfile(fileext = ".png") with_png(pngfile_2, width = 300, height = 200,{ barplot(1:9, col = blues9) title(main = "I Like the Way You Move") }) tagList( tags$div( id = "example03", HTML(base64::img(pngfile_1)), HTML(base64::img(pngfile_2)) ), sortable_js(css_id = "example03") ) knitr::read_chunk( system.file("shiny-examples/shiny_tabset/app.R", package = "sortable") )
betasecond=function(x,n=20){ library(BioFTF) for (i in 1:ncol(x)) colnames(x)=paste("species",c(1:ncol(x)),sep=" n.") for (i in 1:nrow(x)) rownames(x)=paste("community",c(1:nrow(x)),sep=" n.") class(x) x=as.matrix(x) nsiti=nrow(x) nspecie=ncol(x) xrel=prop.table(x,1) k=(n-1)/2 b=seq(-1,1,1/k) b[b==0]=0.001 b[1]=-0.9999 appo.beta=matrix(rep(b),length(b),nsiti) appo.profile=matrix(NA,length(b),nsiti) appo.siti=matrix(rep((xrel),each=length(b)),nsiti*length(b),nspecie) all=length(b)*nsiti for(i in 1:all) {appo.profile[i]=(1-sum(appo.siti[i,]^(appo.beta[i]+1)))/(appo.beta[i])} appo.profile[1,]=round(appo.profile[1,]) appo.siti2=log(appo.siti) appo.siti2[appo.siti2==-Inf]=0 appo.second=matrix(NA,length(b),nsiti) for (i in 1:all) appo.second[i]=(sum((appo.siti[i,]^(appo.beta[i]+1))*(-(appo.beta[i])^2*((appo.siti2[i,])^2)-2+2*appo.beta[i]*appo.siti2[i,]))+2)/((appo.beta[i])^3) appo.second }
context("Other error messages") test_that("Error messages on NosoiSim", { t_incub_fct <- function(x){rnorm(x,mean = 5,sd=1)} p_max_fct <- function(x){rbeta(x,shape1 = 5,shape2=2)} p_exit_param1 <- function(x){rnorm(x,mean = 10,sd=2)} p_Exit_fct <- function(t,pExit.param1){plogis(t,pExit.param1,2)} proba <- function(t,p_max,t_incub){ if(t <= t_incub){p=0} if(t >= t_incub){p=p_max} return(p) } time_contact = function(t){round(rnorm(1, 3, 1), 0)} expect_error( test.nosoiC <- nosoiSim(type="triple", popStructure="none", length=40, max.infected=100, init.individuals=3, nContact=time_contact, param.nContact=NA, pTrans = proba, param.pTrans = list(p_max=p_max_fct, t_incub=t_incub_fct), pExit=p_Exit_fct, param.pExit = list(pExit.param1=p_exit_param1) ), "Type of transmission should be 'single' or 'dual'-host." ) expect_error( test.nosoiC <- nosoiSim(type="single", popStructure="multiple", length=40, max.infected=100, init.individuals=3, nContact=time_contact, param.nContact=NA, pTrans = proba, param.pTrans = list(p_max=p_max_fct, t_incub=t_incub_fct), pExit=p_Exit_fct, param.pExit = list(pExit.param1=p_exit_param1) ), "Unrecognized parameters for population structure, should be 'none,'discrete' or 'continuous'." ) }) test_that("Error messages on SanityCheck", { t_incub_fct <- function(x){rnorm(x,mean = 5,sd=1)} p_max_fct <- function(x){rbeta(x,shape1 = 5,shape2=2)} p_exit_param1 <- function(x){rnorm(x,mean = 10,sd=2)} p_Exit_fct <- function(t,pExit.param1){plogis(t,pExit.param1,2)} proba <- function(t,p_max,t_incub){ if(t <= t_incub){p=0} if(t >= t_incub){p=p_max} return(p) } time_contact = function(t){round(rnorm(1, 3, 1), 0)} expect_error( nosoiSim(type="single", popStructure="none", length=1, max.infected=100, init.individuals=3, nContact=time_contact, param.nContact=NA, pTrans = proba, param.pTrans = list(p_max=p_max_fct, t_incub=t_incub_fct), pExit=p_Exit_fct, param.pExit = list(pExit.param1=p_exit_param1) ), "You must specify a length (in time units) for your simulation (bigger than 1).",fixed=TRUE ) expect_error( test.nosoiC <- nosoiSim(type="single", popStructure="none", length=100, max.infected=NA, init.individuals=3, nContact=time_contact, param.nContact=NA, pTrans = proba, param.pTrans = list(p_max=p_max_fct, t_incub=t_incub_fct), pExit=p_Exit_fct, param.pExit = list(pExit.param1=p_exit_param1) ), "You must specify a maximum number of infected hosts (bigger than 1).",fixed=TRUE ) expect_error( test.nosoiC <- nosoiSim(type="single", popStructure="none", length=100, max.infected=100, init.individuals=NA, nContact=time_contact, param.nContact=NA, pTrans = proba, param.pTrans = list(p_max=p_max_fct, t_incub=t_incub_fct), pExit=p_Exit_fct, param.pExit = list(pExit.param1=p_exit_param1) ), "The transmission chain should be started by 1 or more (integer) individuals.",fixed=TRUE ) }) test_that("Error messages on MatrixSanityCheck", { t_incub_fct <- function(x){rnorm(x,mean = 5,sd=1)} p_max_fct <- function(x){rbeta(x,shape1 = 5,shape2=2)} p_Move_fct <- function(t){return(0.1)} p_Exit_fct <- function(t,current.in){ if(current.in=="A"){return(0)} if(current.in=="B"){return(0.5)} if(current.in=="C"){return(1)}} proba <- function(t,p_max,t_incub){ if(t <= t_incub){p=0} if(t >= t_incub){p=p_max} return(p) } time_contact = function(t){round(rnorm(1, 3, 1), 0)} transition.matrix = matrix(c(0,0.2,0.4,0.5,0,0.6,0.5,0.8,0),nrow = 3, ncol = 3,dimnames=list(c("A","B","C"),c("A","B","C"))) set.seed(805) expect_error( test.nosoiA <- nosoiSim(type="dual", popStructure="discrete", length.sim=20, max.infected.A=1000, max.infected.B=1000, init.individuals.A=1, init.individuals.B=0, init.structure.A="D", init.structure.B=NA, structure.matrix.A=transition.matrix, structure.matrix.B=transition.matrix, pExit.A=p_Exit_fct, param.pExit.A=NA, timeDep.pExit.A=FALSE, diff.pExit.A=TRUE, pMove.A=p_Move_fct, param.pMove.A=NA, timeDep.pMove.A=FALSE, diff.pMove.A=FALSE, nContact.A=time_contact, param.nContact.A=NA, timeDep.nContact.A=FALSE, diff.nContact.A=FALSE, pTrans.A=proba, param.pTrans.A=list(p_max=p_max_fct, t_incub=t_incub_fct), timeDep.pTrans.A=FALSE, diff.pTrans.A=FALSE, prefix.host.A="H", pExit.B=p_Exit_fct, param.pExit.B=NA, timeDep.pExit.B=FALSE, diff.pExit.B=TRUE, pMove.B=p_Move_fct, param.pMove.B=NA, timeDep.pMove.B=FALSE, diff.pMove.B=FALSE, nContact.B=time_contact, param.nContact.B=NA, timeDep.nContact.B=FALSE, diff.nContact.B=FALSE, pTrans.B=proba, param.pTrans.B=list(p_max=p_max_fct, t_incub=t_incub_fct), timeDep.pTrans.B=FALSE, diff.pTrans.B=FALSE, prefix.host.B="V"), "init.structure should be a state present in structure.matrix.") }) test_that("Error messages on RasterSanityCheck", { library(raster) set.seed(860) test.raster <- raster(nrows=100, ncols=100, xmn=-50, xmx=50, ymn=-50,ymx=50) test.raster[] <- runif(10000, -80, 180) test.raster <- focal(focal(test.raster, w=matrix(1, 5, 5), mean), w=matrix(1, 5, 5), mean) bad.raster <- "raster" t_incub_fct <- function(x){rnorm(x,mean = 5,sd=1)} p_max_fct <- function(x){rbeta(x,shape1 = 5,shape2=2)} p_Move_fct <- function(t){return(0.1)} sdMove_fct = function(t,current.env.value){return(100/(current.env.value+1))} p_Exit_fct <- function(t){return(0.08)} proba <- function(t,p_max,t_incub){ if(t <= t_incub){p=0} if(t >= t_incub){p=p_max} return(p) } time_contact = function(t){round(rnorm(1, 3, 1), 0)} start.pos <- c(0,0) bad.start.pos <- c(100,100) expect_error(nosoiSim(type="single", popStructure="continuous", length=200, max.infected=500, init.individuals=1, init.structure=start.pos, structure.raster=bad.raster, pMove=p_Move_fct, param.pMove=NA, diff.sdMove=TRUE, sdMove=sdMove_fct, param.sdMove=NA, attracted.by.raster=TRUE, nContact=time_contact, param.nContact=NA, pTrans = proba, param.pTrans = list(p_max=p_max_fct, t_incub=t_incub_fct), pExit=p_Exit_fct, param.pExit=NA), "structure.raster must be a raster (class RasterLayer).", fixed=TRUE) expect_error(nosoiSim(type="single", popStructure="continuous", length=200, max.infected=500, init.individuals=1, init.structure=bad.start.pos, structure.raster=test.raster, pMove=p_Move_fct, param.pMove=NA, diff.sdMove=TRUE, sdMove=sdMove_fct, param.sdMove=NA, attracted.by.raster=TRUE, nContact=time_contact, param.nContact=NA, pTrans = proba, param.pTrans = list(p_max=p_max_fct, t_incub=t_incub_fct), pExit=p_Exit_fct, param.pExit=NA), "Your starting position (init.structure) should be on the raster.", fixed=TRUE) set.seed(805) expect_error( nosoiSim(type="dual", popStructure="continuous", length.sim=200, max.infected.A=500, max.infected.B=500, init.individuals.A=1, init.individuals.B=0, init.structure.A=bad.start.pos, init.structure.B=NA, structure.raster.A=test.raster, structure.raster.B=test.raster, pExit.A=p_Exit_fct, param.pExit.A=NA, timeDep.pExit.A=FALSE, diff.pExit.A=FALSE, pMove.A=p_Move_fct, param.pMove.A=NA, timeDep.pMove.A=FALSE, diff.pMove.A=FALSE, diff.sdMove.A=TRUE, sdMove.A=sdMove_fct, param.sdMove.A=NA, attracted.by.raster.A=TRUE, nContact.A=time_contact, param.nContact.A=NA, timeDep.nContact.A=FALSE, diff.nContact.A=FALSE, pTrans.A=proba, param.pTrans.A=list(p_max=p_max_fct, t_incub=t_incub_fct), timeDep.pTrans.A=FALSE, diff.pTrans.A=FALSE, prefix.host.A="H", pExit.B=p_Exit_fct, param.pExit.B=NA, timeDep.pExit.B=FALSE, diff.pExit.B=FALSE, pMove.B=NA, param.pMove.B=NA, timeDep.pMove.B=FALSE, diff.pMove.B=FALSE, diff.sdMove.B=FALSE, sdMove.B=NA, param.sdMove.B=NA, attracted.by.raster.B=FALSE, nContact.B=time_contact, param.nContact.B=NA, timeDep.nContact.B=FALSE, diff.nContact.B=FALSE, pTrans.B=proba, param.pTrans.B=list(p_max=p_max_fct, t_incub=t_incub_fct), timeDep.pTrans.B=FALSE, diff.pTrans.B=FALSE, prefix.host.B="V"), "Your starting position (init.structure) should be on the raster.",fixed=TRUE) expect_error( test.nosoiA <- nosoiSim(type="single", popStructure="discrete", length=100, max.infected=200, init.individuals=1, init.structure="A", structure.matrix=transition.matrix, pMove=p_Move_fct, param.pMove=NA, diff.nContact=FALSE, hostCount.nContact=TRUE, nContact=time_contact, param.nContact=NA, pTrans = proba, param.pTrans = list(p_max=p_max_fct, t_incub=t_incub_fct), pExit=p_Exit_fct, param.pExit=NA ), "diff.nContact should be TRUE to use hostCount.nContact.") }) test_that("Error messages on drawBernouilli", { test = data.frame(A=0.5,B=0.6,C=0.1) expect_error(drawBernouilli(test), "Function 'drawBernouilli' should be applied to a vector.") })
sanity_check <- function(pkg = get_golem_wd()) { all_R_files <- list.files( path = pkg, pattern = "\\.R$", recursive = TRUE ) to_find <- c("browser()", " source_markers <- data.frame() for (file_name in all_R_files) { file <- readLines(file_name, warn = FALSE) for (word in to_find) { line_number <- grep(word, file, fixed = TRUE) if (length(line_number) > 0) { df <- data.frame( type = "warning", file = file_name, line = line_number, message = paste("Found", word, sep = " "), column = 1 ) source_markers <- rbind.data.frame(source_markers, df) } } } if (length(source_markers) > 0) { if (rstudioapi::isAvailable() & rstudioapi::hasFun("sourceMarkers")) { rstudioapi::sourceMarkers("sanity_check", markers = source_markers) } return(source_markers) } else { cat_green_tick("Sanity check passed successfully.") } }
`getKnotsBoundaries` <- function(sgp.iter, state, sgp.iter.type="sgp.percentiles", sgp.year.baseline=NULL) { kb <- list() getContent_Areas <- function(sgp.iter, type) { if (!is.null(my.tmp <- SGP::SGPstateData[[state]][["SGP_Configuration"]][["content_area.projection.sequence"]])) { tmp.content_areas <- unique(sgp.iter[[type]]) tmp.content_areas <- unique(unlist(my.tmp[unlist(lapply(my.tmp, function(x) any(tmp.content_areas %in% x)))])) if (is.null(tmp.content_areas)) { messageSGP(paste0("\n\tNOTE: Content Areas ", paste(unique(sgp.iter[[type]]), collapse=", "), " not in SGPstateData[['",state,"']][['SGP_Configuration']][['content_area.projection.sequence']].\n\t\t Knots and boundaries for only those Content Areas will be used.")) tmp.content_areas <- unique(sgp.iter[[type]]) } return(tmp.content_areas) } else { return(unique(sgp.iter[[type]])) } } if (sgp.iter.type=="sgp.percentiles") { tmp.content_areas <- getContent_Areas(sgp.iter, 'sgp.content.areas') } if (sgp.iter.type=="sgp.percentiles.baseline") { tmp.content_areas <- getContent_Areas(sgp.iter, 'sgp.baseline.content.areas') } if (sgp.iter.type=="sgp.projections") { tmp.content_areas <- getContent_Areas(sgp.iter, 'sgp.projection.content.areas') } if (sgp.iter.type=="sgp.projections.lagged") { tmp.content_areas <- getContent_Areas(sgp.iter, 'sgp.projection.content.areas') } if (sgp.iter.type=="sgp.projections.baseline") { tmp.content_areas <- getContent_Areas(sgp.iter, 'sgp.projection.baseline.content.areas') } if (sgp.iter.type=="sgp.projections.lagged.baseline") { tmp.content_areas <- getContent_Areas(sgp.iter, 'sgp.projection.baseline.content.areas') } if (sgp.iter.type=="sgp.percentiles") { content_area.label <- tail(sgp.iter[["sgp.content.areas"]], 1) if (!is.null(sgp.year.baseline)) tmp.year <- sgp.year.baseline else tmp.year <- tail(sgp.iter[["sgp.panel.years"]], 1) } if (sgp.iter.type=="sgp.percentiles.baseline") { content_area.label <- tail(sgp.iter[["sgp.baseline.content.areas"]], 1) if (!is.null(sgp.year.baseline)) tmp.year <- sgp.year.baseline else tmp.year <- tail(sgp.iter[["sgp.panel.years"]], 1) } if (sgp.iter.type=="sgp.projections") { content_area.label <- tail(sgp.iter[["sgp.projection.content.areas"]], 1) if (!is.null(sgp.year.baseline)) tmp.year <- sgp.year.baseline else tmp.year <- tail(sgp.iter[["sgp.projection.panel.years"]], 1) } if (sgp.iter.type=="sgp.projections.baseline") { content_area.label <- tail(sgp.iter[["sgp.projection.baseline.content.areas"]], 1) if (!is.null(sgp.year.baseline)) tmp.year <- sgp.year.baseline else tmp.year <- tail(sgp.iter[["sgp.projection.baseline.panel.years"]], 1) } if (sgp.iter.type=="sgp.projections.lagged") { content_area.label <- tail(sgp.iter[["sgp.content.areas"]], 1) if (!is.null(sgp.year.baseline)) tmp.year <- sgp.year.baseline else tmp.year <- tail(sgp.iter[["sgp.panel.years"]], 1) } if (sgp.iter.type=="sgp.projections.lagged.baseline") { content_area.label <- tail(sgp.iter[["sgp.baseline.content.areas"]], 1) if (!is.null(sgp.year.baseline)) tmp.year <- sgp.year.baseline else tmp.year <- tail(sgp.iter[["sgp.panel.years"]], 1) } for (j in tmp.content_areas) { for (i in grep(j, names(SGP::SGPstateData[[state]][["Achievement"]][["Knots_Boundaries"]]), value=TRUE)) { kb[["Knots_Boundaries"]][[paste(content_area.label, tmp.year, sep=".")]][[i]] <- SGP::SGPstateData[[state]][["Achievement"]][["Knots_Boundaries"]][[i]] } } return(kb[["Knots_Boundaries"]]) }
sym <- function(x) { if (is_symbol(x)) { return(x) } if (identical(x, "")) { return(missing_arg()) } if (!is_string(x)) { abort_coercion(x, "a symbol") } .Call(ffi_symbol, x) } syms <- function(x) { map(x, sym) } data_sym <- function(x) { call("$", quote(.data), sym(x)) } data_syms <- function(x) { map(x, data_sym) } is_symbol <- function(x, name = NULL) { if (typeof(x) != "symbol") { return(FALSE) } if (is_null(name)) { return(TRUE) } as_string(x) %in% name } as_string <- function(x) { if (is_string(x)) { attributes(x) <- NULL return(x) } if (is_symbol(x)) { return(.Call(ffi_sym_as_character, x)) } abort_coercion(x, "a string") } namespace_sym <- quote(`::`) namespace2_sym <- quote(`:::`) dollar_sym <- quote(`$`) dot_data_sym <- quote(.data) dots_sym <- quote(...) at_sym <- quote(`@`) tilde_sym <- quote(`~`) colon_equals_sym <- quote(`:=`) brace_sym <- quote(`{`) dots_sym <- quote(...) function_sym <- quote(`function`) dot_sym <- quote(.) pipe_sym <- quote(`%>%`)
getStatus = function(ids = NULL, reg = getDefaultRegistry()) { assertRegistry(reg, sync = TRUE) stats = getStatusTable(convertIds(reg, ids), reg = reg) setClasses(stats, c("Status", class(stats))) } getStatusTable = function(ids = NULL, batch.ids = getBatchIds(reg = reg), reg = getDefaultRegistry()) { submitted = started = done = error = status = NULL stats = merge(filter(reg$status, ids), batch.ids, by = "batch.id", all.x = TRUE, all.y = FALSE, sort = FALSE)[, list( defined = .N, submitted = count(submitted), started = sum(!is.na(started) | !is.na(status) & status == "running"), done = count(done), error = count(error), queued = sum(status == "queued", na.rm = TRUE), running = sum(status == "running", na.rm = TRUE), expired = sum(!is.na(submitted) & is.na(done) & is.na(status)) )] stats$done = stats$done - stats$error stats$system = stats$queued + stats$running return(stats) } print.Status = function(x, ...) { fmt = sprintf(" %%-13s: %%%ii (%%5.1f%%%%)", stri_width(x$defined)) pr = function(label, h) catf(fmt, label, h, h / x$defined * 100) catf("Status for %i jobs at %s:", x$defined, strftime(Sys.time())) pr("Submitted", x$submitted) pr("-- Queued", x$queued) pr("-- Started", x$started) pr("---- Running", x$running) pr("---- Done", x$done) pr("---- Error", x$error) pr("---- Expired", x$expired) }
compIdent <- function(x, genome, target=NULL, debug=FALSE, mainLayer=NULL, covLayer=NULL, out="plot") { if(is.null(target)) { memo <- paste0("Argument not supplied to target, defaulting to", " predefined identity SNPs from hg19 assembly!") message(memo) } if(isTRUE(debug)) { bams <- list(normal=GenVisR::HCC1395_N, tumor=GenVisR::HCC1395_T) samplenames <- c('normal','tumor') count_tables <- lapply(bams, compIdent_bamRcnt, genome=genome, debug=debug, target=target) } else { bams <- as.character(x$bamfile) samplenames <- as.character(x$sample_name) names(bams) <- samplenames count_tables <- lapply(bams, compIdent_bamRcnt, genome=genome, target=target) } count_tables <- compIdent_format(count_tables) plot <- compIdent_buildMain(count_tables, mainLayer=mainLayer, covLayer=covLayer) output <- multi_selectOut(data=count_tables, plot=plot, draw=TRUE, out=out) return(output) }
Enders_Siklos_2001 <- function(y,x,case=2,max_lags){ y = as.vector(y) x = as.vector(x) res = residuals(lm(y~x)) z=diff(res) if(case==1){ gfz=embed(res,1)[,1] } if(case==2){ gfz=embed(res,2)[,2] } if(case==3){ gfz=embed(res,4)[,4] } say=99999999999999999999999999999 for(i in 1:max_lags){ model = setar(gfz,m=max_lags,model="MTAR",th=0,type="ADF",common="both", include = "none") if (AIC(model)<say){ uygun_lag=i say=AIC(model) } model = setar(gfz,m=uygun_lag,model="MTAR",th=0,type="ADF",common="both", include = "none") } p1 = linearHypothesis(model, c("phiL.1=0", "phiH.1=0"), test="F") p2 = linearHypothesis(model, c("phiL.1=phiH.1"), test="F") tval=p1[,"Chisq"][2] tval2=p2[,"Chisq"][2] my_list <- list("Model"=summary(model), "Selected Lag"=uygun_lag, "p1=p2=0 Statistic"=tval/2, "p1=p2 Statistic"=tval2, "p value"=p2[,"Pr(>Chisq)"][2]) return(my_list) }
magrittr::`%>%` sjmisc::typical_value performance::mse performance::rmse bayestestR::ci bayestestR::equivalence_test insight::link_inverse
context("Test toolCountryFill") test_that("toolCountryFill works as expected", { x <- new.magpie("DEU",1994,"bla",0) expect_message(y <- toolCountryFill(x,99), "toolCountryFill set missing values for IMPORTANT") expect_equal(dim(y)[1], 249) expect_true(y["DEU",,] == 0) expect_true(all(y["DEU",,,invert=TRUE] == 99)) x2 <- new.magpie(c("DEU","XYZ"),1994,"bla",0) expect_warning(y2 <- toolCountryFill(x2,99), "unknown country codes removed: XYZ") expect_identical(y2,y) expect_error(toolCountryFill(x,99, HKG="CHN"), "Try to fill a country") expect_silent(suppressMessages(y3 <- toolCountryFill(x,99, FRA="DEU", verbosity = 2))) expect_true(all(y3[c("DEU","FRA"),,] == 0)) y4 <- toolCountryFill(x,99, map = c(FRA = "DEU"), verbosity = 2) expect_identical(y3,y4) x3 <- new.magpie(c("DEU","FRA"),1994,"bla",0) x3["FRA",,] <- 42 expect_true(toolCountryFill(x3,99, FRA = "DEU")["FRA",,] == 42) expect_message(y5 <- toolCountryFill(x3,99, FRA="DEU", overwrite = TRUE), "data overwritten") expect_true(y5["FRA",,] == 0) })
PandocAll = function(intype="docx", outtype="html"){ FileList=list.files(pattern=paste0(".",intype)) for(i in FileList){ Outfile = sub(paste0(".", intype), paste0(".", outtype), i) if(file.mtime(i) > file.mtime(Outfile)| !file.exists(Outfile)) { shell(paste0('pandoc -s "', i, '" -o "', Outfile, '"')) message(paste("File", i, "converted to", Outfile)) } } return(invisible(TRUE)) }
horizFPCA <- function(warp_data,no,ci=c(-1,0,1),showplot = TRUE){ gam <- warp_data$gam tmp = SqrtMean(gam) vec = tmp$vec mu = tmp$mu no_pca = 1:no K = cov(t(vec)) out = svd(K) s = out$d U = out$u TT = nrow(vec) + 1 vm = rowMeans(vec) gam_pca = array(0,dim=c(length(ci),length(mu)+1,no)) psi_pca = array(0,dim=c(length(ci),length(mu),no)) for (j in no_pca){ cnt = 1 for (k in ci){ v = ci*sqrt(s[j])*U[,j] vn = pvecnorm(v,2)/sqrt(TT) if (vn < 0.0001){ psi_pca[cnt,,j] = mu }else{ psi_pca[cnt,,j] = cos(vn)*mu+sin(vn)*v/vn } tmp = rep(0,TT) tmp[2:TT] = cumsum(psi_pca[cnt,,j]*psi_pca[cnt,,j]) gam_pca[cnt,,j] = (tmp-tmp[1]) / (tmp[length(tmp)] - tmp[1]) cnt = cnt + 1 } } N2 = dim(gam)[2] c = matrix(0,N2,no) for (k in no_pca){ for (i in 1:N2){ c[i,k] = sum((vec[,i]-vm)*U[,k]) } } hfpca = list() hfpca$gam_pca = gam_pca hfpca$psi_pca = psi_pca hfpca$latent = s[no_pca] hfpca$U = U[,no_pca] hfpca$coef = c[,no_pca] hfpca$vec = vec hfpca$mu = mu class(hfpca) <- "hfpca" if (showplot){ plot(hfpca) } return(hfpca) }
options(width=140) options(prompt=" ", continue=" ") options(digits=4)
context("add_mandatory_allocation_constraints") test_that("compile (compressed formulation, multiple zones)", { data(sim_pu_zones_stack, sim_features_zones) p <- problem(sim_pu_zones_stack, sim_features_zones) %>% add_min_set_objective() %>% add_mandatory_allocation_constraints() %>% add_manual_targets(tibble::tibble(feature = c("feature_1", "feature_2", "feature_3"), zone = list("zone_1", "zone_2", c("zone_1", "zone_3")), sense = c("<=", ">=", "="), type = rep("absolute", 3), target = c(4, 5, 6))) %>% add_binary_decisions() o <- compile(p) n_pu <- length(sim_pu_raster[[1]][!is.na(sim_pu_raster)]) n_zone <- number_of_zones(sim_features_zones) expect_equal(o$modelsense(), "min") expect_equal(o$obj(), c(p$planning_unit_costs())) expect_equal(o$sense(), c("<=", ">=", "=", rep("=", n_pu))) expect_equal(o$rhs(), c(4, 5, 6, rep(1, n_pu))) expect_equal(o$row_ids(), c(rep("spp_target", 3), rep("pu_zone", n_pu))) expect_equal(o$col_ids(), rep("pu", n_pu * n_zone)) expect_true(all(o$lb() == 0)) expect_true(all(o$ub() == 1)) m <- matrix(0, nrow = 3 + n_pu, ncol = n_pu * n_zone) m[1, seq_len(n_pu)] <- p$data$rij_matrix[[1]][1, ] m[2, n_pu + seq_len(n_pu)] <- p$data$rij_matrix[[2]][2, ] m[3, seq_len(n_pu)] <- p$data$rij_matrix[[1]][3, ] m[3, (n_pu * 2) + seq_len(n_pu)] <- p$data$rij_matrix[[3]][3, ] for (i in seq_len(n_pu)) m[3 + i, c(i, n_pu + i, n_pu + n_pu + i) ] <- 1 m <- as(m, "dgCMatrix") expect_true(all(m == o$A())) }) test_that("compile (expanded formulation, multiple zones)", { data(sim_pu_zones_stack, sim_features_zones) p <- problem(sim_pu_zones_stack, sim_features_zones) %>% add_min_set_objective() %>% add_mandatory_allocation_constraints() %>% add_manual_targets(tibble::tibble(feature = c("feature_1", "feature_2", "feature_3"), zone = list("zone_1", "zone_2", c("zone_1", "zone_3")), sense = c("<=", ">=", "="), type = rep("absolute", 3), target = c(4, 5, 6))) %>% add_binary_decisions() o <- compile(p, FALSE) n_pu <- length(sim_pu_raster[[1]][!is.na(sim_pu_raster)]) n_zone <- number_of_zones(sim_features_zones) n_feature <- number_of_features(sim_features_zones) expect_equal(o$modelsense(), "min") expect_equal(o$obj(), c(c(p$planning_unit_costs()), rep(0, n_pu * n_zone * n_feature))) expect_equal(o$sense(), c(rep("<=", n_pu * n_zone * n_feature), "<=", ">=", "=", rep("=", n_pu))) expect_equal(o$rhs(), c(rep(0, n_pu * n_zone * n_feature), 4, 5, 6, rep(1, n_pu))) expect_equal(o$row_ids(), c(rep("pu_ijz", n_pu * n_zone * n_feature), rep("spp_target", 3), rep("pu_zone", n_pu))) expect_equal(o$col_ids(), c(rep("pu", n_pu * n_zone), rep("pu_ijz", n_pu * n_zone * n_feature))) expect_true(all(o$lb() == 0)) expect_true(all(o$ub() == 1)) m <- matrix(0, nrow = n_pu * n_feature * n_zone + 3 + n_pu, ncol = (n_pu * n_zone) + (n_pu * n_zone * n_feature)) r <- 0 for (z in seq_len(n_zone)) { for (i in seq_len(n_feature)) { for (j in seq_len(n_pu)) { r <- r + 1 m[r, ((z - 1) * n_pu) + j] <- -1 m[r, (n_pu * n_zone) + ((z - 1) * n_pu * n_feature) + ((i - 1) * n_pu) + j] <- 1 } } } r <- r + 1 m[r, (n_pu * n_zone) + seq_len(n_pu)] <- p$data$rij_matrix[[1]][1, ] r <- r + 1 m[r, (n_pu * n_zone) + (1 * n_pu * n_feature) + (1 * n_pu) + seq_len(n_pu)] <- p$data$rij_matrix[[2]][2, ] r <- r + 1 m[r, (n_pu * n_zone) + (0 * n_pu * n_feature) + (2 * n_pu) + seq_len(n_pu)] <- p$data$rij_matrix[[1]][3, ] m[r, (n_pu * n_zone) + (2 * n_pu * n_feature) + (2 * n_pu) + seq_len(n_pu)] <- p$data$rij_matrix[[3]][3, ] for (i in seq_len(n_pu)) m[r + i, c(i, n_pu + i, n_pu + n_pu + i)] <- 1 m <- as(m, "dgCMatrix") expect_true(all(m == o$A())) }) test_that("solve (compressed formulation, multiple zones)", { skip_on_cran() skip_if_no_fast_solvers_installed() costs <- raster::stack( raster::raster(matrix(c(1, 2, NA, 3, 100, 100, NA), ncol = 7)), raster::raster(matrix(c(10, 10, 10, 10, 4, 1, NA), ncol = 7))) spp <- raster::stack( raster::raster(matrix(c(1, 2, 0, 0, 0, 0, 0), ncol = 7)), raster::raster(matrix(c(NA, 0, 1, 1, 0, 0, 0), ncol = 7)), raster::raster(matrix(c(1, 0, 0, 0, 1, 0, 0), ncol = 7)), raster::raster(matrix(c(0, 0, 0, 0, 0, 10, 0), ncol = 7))) p <- problem(costs, zones(spp[[1:2]], spp[[3:4]])) %>% add_min_set_objective() %>% add_mandatory_allocation_constraints() %>% add_absolute_targets(matrix(c(1, 1, 1, 0), nrow = 2, ncol = 2)) %>% add_binary_decisions() %>% add_default_solver(gap = 0, verbose = FALSE) s <- p %>% solve() expect_is(s, "RasterStack") expect_equal(raster::values(s[[1]]), c(1, 1, NA, 1, 0, 0, NA)) expect_equal(raster::values(s[[2]]), c(0, 0, 1, 0, 1, 1, NA)) }) test_that("solve (expanded formulation, multiple zones)", { skip_on_cran() skip_if_no_fast_solvers_installed() costs <- raster::stack( raster::raster(matrix(c(1, 2, NA, 3, 100, 100, NA), ncol = 7)), raster::raster(matrix(c(10, 10, 10, 10, 4, 1, NA), ncol = 7))) spp <- raster::stack( raster::raster(matrix(c(1, 2, 0, 0, 0, 0, 0), ncol = 7)), raster::raster(matrix(c(NA, 0, 1, 1, 0, 0, 0), ncol = 7)), raster::raster(matrix(c(1, 0, 0, 0, 1, 0, 0), ncol = 7)), raster::raster(matrix(c(0, 0, 0, 0, 0, 10, 0), ncol = 7))) p <- problem(costs, zones(spp[[1:2]], spp[[3:4]])) %>% add_min_set_objective() %>% add_mandatory_allocation_constraints() %>% add_absolute_targets(matrix(c(1, 1, 1, 0), nrow = 2, ncol = 2)) %>% add_binary_decisions() %>% add_default_solver(gap = 0, verbose = FALSE) s <- p %>% solve(compressed_formulation = FALSE) expect_is(s, "RasterStack") expect_equal(raster::values(s[[1]]), c(1, 1, NA, 1, 0, 0, NA)) expect_equal(raster::values(s[[2]]), c(0, 0, 1, 0, 1, 1, NA)) }) test_that("throws error for problem with single zone", { data(sim_pu_raster, sim_features) expect_error(problem(sim_pu_raster, sim_features) %>% add_mandatory_allocation_constraints()) })
add_meta <- function(meta, nexml=new("nexml"), level=c("nexml", "otus", "trees", "characters"), namespaces = NULL, i = 1, at_id = NULL){ level <- match.arg(level) if (is.null(meta)) stop("meta object to add is null, with no default") if(!is.list(meta)) meta <- list(meta) if(!all(sapply(meta, is, "meta"))) stop("All elements in list must be of class 'meta' or a subclass") if(!is.null(at_id)){ stop("function does not yet handle at_id assignments") } else if(level =="nexml"){ nexml@meta <- c(nexml@meta, meta) } else if(level =="otus"){ nexml@otus[[i]]@meta <- c(nexml@otus[[i]]@meta, meta) } else if(level == "trees"){ nexml@trees[[i]]@meta <- c(nexml@trees[[i]]@meta, meta) } else if(level == "characters"){ nexml@characters[[i]]@meta <- c(nexml@characters[[i]]@meta, meta) } nexml <- add_namespaces(namespaces, nexml) nexml }
rm(list = ls()) s <- search()[-1] s <- s[-match(c("package:base", "package:stats", "package:graphics", "package:grDevices", "package:utils", "package:datasets", "package:methods", "Autoloads"), s)] if (length(s) > 0) sapply(s, detach, character.only = TRUE) if (!file.exists("tables")) dir.create("tables") if (!file.exists("figures")) dir.create("figures") set.seed(290875) options(prompt = "R> ", continue = "+ ", width = 63, show.signif.stars = FALSE, SweaveHooks = list(leftpar = function() par(mai = par("mai") * c(1, 1.05, 1, 1)), bigleftpar = function() par(mai = par("mai") * c(1, 1.7, 1, 1)))) HSAURpkg <- require("HSAUR3") if (!HSAURpkg) stop("cannot load package ", sQuote("HSAUR3")) rm(HSAURpkg) a <- Sys.setlocale("LC_ALL", "C") book <- TRUE refs <- cbind(c("AItR", "DAGD", "SI", "CI", "ANOVA", "MLR", "GLM", "DE", "RP", "GAM", "SA", "ALDI", "ALDII", "SIMC", "MA", "PCA", "MDS", "CA"), 1:18) ch <- function(x) { ch <- refs[which(refs[,1] == x),] if (book) { return(paste("Chapter~\\\\ref{", ch[1], "}", sep = "")) } else { return(paste("Chapter~", ch[2], sep = "")) } } if (file.exists("deparse.R")) source("deparse.R") setHook(packageEvent("lattice", "attach"), function(...) { lattice.options(default.theme = function() standard.theme("pdf", color = FALSE)) }) book <- FALSE library("wordcloud") data("weightgain", package = "HSAUR3") tapply(weightgain$weightgain, list(weightgain$source, weightgain$type), mean) tapply(weightgain$weightgain, list(weightgain$source, weightgain$type), sd) plot.design(weightgain) wg_aov <- aov(weightgain ~ source * type, data = weightgain) summary(wg_aov) interaction.plot(weightgain$type, weightgain$source, weightgain$weightgain, legend = FALSE) legend(1.5, 95, legend = levels(weightgain$source), title = "weightgain$source", lty = c(2,1), bty = "n") coef(wg_aov) options("contrasts") coef(aov(weightgain ~ source + type + source:type, data = weightgain, contrasts = list(source = contr.sum))) data("foster", package = "HSAUR3") plot.design(foster) summary(aov(weight ~ litgen * motgen, data = foster)) summary(aov(weight ~ motgen * litgen, data = foster)) foster_aov <- aov(weight ~ litgen * motgen, data = foster) foster_hsd <- TukeyHSD(foster_aov, "motgen") foster_hsd plot(foster_hsd) data("water", package = "HSAUR3") summary(manova(cbind(hardness, mortality) ~ location, data = water), test = "Hotelling-Lawley") tapply(water$hardness, water$location, mean) tapply(water$mortality, water$location, mean) data("skulls", package = "HSAUR3") means <- aggregate(skulls[,c("mb", "bh", "bl", "nh")], list(epoch = skulls$epoch), mean) means pairs(means[,-1], panel = function(x, y) { textplot(x, y, levels(skulls$epoch), new = FALSE, cex = 0.8) }) skulls_manova <- manova(cbind(mb, bh, bl, nh) ~ epoch, data = skulls) summary(skulls_manova, test = "Pillai") summary(skulls_manova, test = "Wilks") summary(skulls_manova, test = "Hotelling-Lawley") summary(skulls_manova, test = "Roy") summary.aov(skulls_manova) summary(manova(cbind(mb, bh, bl, nh) ~ epoch, data = skulls, subset = epoch %in% c("c4000BC", "c3300BC"))) summary(manova(cbind(mb, bh, bl, nh) ~ epoch, data = skulls, subset = epoch %in% c("c4000BC", "c1850BC"))) summary(manova(cbind(mb, bh, bl, nh) ~ epoch, data = skulls, subset = epoch %in% c("c4000BC", "c200BC"))) summary(manova(cbind(mb, bh, bl, nh) ~ epoch, data = skulls, subset = epoch %in% c("c4000BC", "cAD150")))
test_that("plot", { x <- rnorm(10) x2 <- cbind(x, x) expect_error(plotx(x), NA) expect_error(plotx(x2), NA) expect_error(plotx(x, main ="rnorm"), NA) expect_error(plotx(x2, main ="rnorm"), NA) expect_error(plotx(x, xlab ="nx"), "xlab is not available") expect_error(plotx(x2, xlab ="nx"), "xlab is not available") expect_error(plotx(x, ylab ="nx"), "ylab is not available") expect_error(plotx(x2, ylab ="nx"), "ylab is not available") })
fusePairs <- function(datPair,refDatNames=NULL,inclRepLst=FALSE,maxFuse=NULL,debug=FALSE,silent=TRUE,callFrom=NULL) { fxNa <- .composeCallName(callFrom,newNa="fusePairs") msg <- " 'datPair' should be matrix of 2 cols with paired rownames" if(length(dim(datPair)) !=2) stop(msg) else if(ncol(datPair) <2) stop(msg) if(!is.matrix(datPair)) datPair <- if(nrow(datPair) >1) as.matrix(datPair) else matrix(datPair,nrow=1,dimnames=dimnames(datPair)) if(is.null(maxFuse)) maxFuse <- nrow(datPair)+1 else { if(!silent) message(fxNa," use of 'maxFuse' at ",maxFuse," may increase 'artificially' the number of groups/clusters")} if(!is.null(refDatNames)) { chRef <- unique(as.character(datPair[,1:2])) %in% as.character(refDatNames) if(sum(!chRef,na.rm=TRUE) >0) { if(!silent) message(fxNa,sum(!chRef,na.rm=TRUE)," names from 'datPair' missing in 'refDatNames', ignore") refDatNames <- refDatNames } } refDatNa <- if(is.null(refDatNames)) unique(as.character(datPair[,1:2])) else refDatNames if(is.null(rownames(datPair))) rownames(datPair) <- 1:nrow(datPair) nPt <- length(unique(as.character(datPair[,1:2]))) similDat <- list(which(refDatNa %in% datPair[1,1:2])) if(nrow(datPair) >1) for(i in 2:nrow(datPair)) { basTest <- datPair[i,1:2] %in% as.character(datPair[1:(i-1),1:2]) chPr <- sapply(similDat,function(x) sum(datPair[i,1:2] %in% refDatNa[x])) if(debug) message(fxNa," basTest ",pasteC(basTest)) if(any(chPr >0) & length(similDat[[which.max(chPr)]]) < maxFuse) { if(sum(basTest)==1){ similDat[[which.max(chPr)]] <- unique(sort(c(similDat[[which.max(chPr)]], which(refDatNa %in% datPair[i,1:2])))) } else { isMax <- which(chPr==max(chPr)) if(length(isMax) >1) { if(debug) message(fxNa," iter no ",i," fuse clusters : max ",pasteC(isMax)) similDat[[isMax[1]]] <- unique(unlist(similDat[which(chPr==max(chPr))])) similDat <- similDat[-isMax[2]] } else if(debug) message(fxNa," iter no ",i," : loop, already fused")} } else { if(debug) message(fxNa," create new cluster no ",length(similDat)+1," for ",pasteC(which(refDatNa %in% datPair[i,1:2]))) similDat[[length(similDat)+1]] <- which(refDatNa %in% datPair[i,1:2]) } } msg <- " trouble ahead, some elements are indexed more than 1x in 'similDat' !!!" if(any(table(unlist(similDat)) >1) & maxFuse < nrow(datPair) & !silent) message(fxNa,msg) out <- rep(1:length(similDat),sapply(similDat,length)) names(out) <- unlist(lapply(similDat,function(x) refDatNa[x])) if(length(refDatNa) > length(unlist(similDat))) { tmp <- refDatNa[which(!(refDatNa %in% as.character(as.matrix(datPair[,1:2]))))] out2 <- (1:length(tmp)) +length(out) names(out2) <- tmp out <- c(out,out2) } out <- out[order(convToNum(.trimFromStart(names(out)),remove=NULL,sciIncl=TRUE))] if(inclRepLst) list(clu=out, repLst=similDat) else out } .neigbDis <- function(x,asSum=TRUE) { if(nrow(x) ==2) sqrt(sum(abs(x[1,]-x[2,]))) else { x <- x[order(rowMeans(x)),] out <- sqrt(rowSums((x[-nrow(x),]-x[-1,])^2,na.rm=TRUE)) if(asSum) sum(out,na.rm=TRUE) else out } } .addDatCol <- function(mainDf,addVect,idCol=c("iniID","uniqID"),newNa=NULL,callFrom=NULL){ fxNa <- .composeCallName(callFrom,newNa=".addDatCol") namesXY <- c(deparse(substitute(mainDf)),deparse(substitute(addVect))) iniColNa <- colnames(mainDf) naAddV <- if(length(dim(addVect)) >1) rownames(addVect) else names(addVect) if(is.null(naAddV)) { out <- cbind(mainDf,addVect) } else { if(identical(names(mainDf),naAddV)) out <- cbind(mainDf,addVect) else { out <- merge(mainDf,data.frame(iniID=naAddV,addVect,stringsAsFactors=FALSE),by.x=idCol[1],by.y="iniID",all.x=TRUE) if(all(is.na(out[,ncol(out)]),idCol[2] %in% colnames(mainDf))) { out <- merge(mainDf,data.frame(uniqID=naAddV,addVect,stringsAsFactors=FALSE),by=idCol[2],all.x=TRUE)} if(nrow(out) > nrow(mainDf) | all(is.na(out[,ncol(out)]))) if(length(addVect)==nrow(mainDf)) { out <- cbind(mainDf,addVect) out[,ncol(out)] <- as.character(out[,ncol(out)]) message(fxNa,"problem comparing names of '",namesXY[2],"' and '",namesXY[1],"', treat as if no names") } else { message(fxNa," found no matches !!")}} } if(is.null(newNa))newNa <- namesXY[2] if(length(dim(addVect)) >1) if(length(dim(addVect)) >1) newNa <- paste(newNa,1:ncol(addVect),sep=".") if(any(newNa %in% colnames(mainDf))) message(fxNa,"NOTE : ",pasteC(newNa[which(newNa %in% colnames(mainDf))])," colnames will be repeated") colnames(out)[(length(iniColNa)+1):ncol(out)] <- newNa out }
NULL methods::setClass("RapReliableOpts", methods::representation(failure.multiplier = "numeric", max.r.level = "integer"), prototype = list(failure.multiplier = 1.1, max.r.level = 5L), contains = "RapOpts", validity = function(object) { assertthat::assert_that( assertthat::is.scalar([email protected]), msg = "argument to failure.multiplier is not a scalar") assertthat::assert_that( is.finite([email protected]), msg = "argument to failure.multiplier is NA or non-finite value") assertthat::assert_that( assertthat::is.scalar(object@BLM), msg = "argument to BLM is not a scalar") assertthat::assert_that( is.finite(object@BLM), msg = "argument to BLM is NA or non-finite value") assertthat::assert_that( is.integer([email protected]), length([email protected]) == 1, msg = "argument to max.r.level is not a scalar integer") assertthat::assert_that( is.finite([email protected]), msg = "argument to max.r.level is NA or non-finite value") return(TRUE) } ) RapReliableOpts <- function(BLM = 0, failure.multiplier = 1.1, max.r.level = 5L) { ro <- methods::new("RapReliableOpts", BLM = BLM, failure.multiplier = failure.multiplier, max.r.level = max.r.level) methods::validObject(ro, test= FALSE) return(ro) } print.RapReliableOpts <- function(x, ..., header=TRUE) { assertthat::assert_that(assertthat::is.flag(header)) if (header) message("RapReliableOpts object.") message(" BLM: ", x@BLM) message(" failure.multiplier: ", [email protected]) message(" max.r.level: ", [email protected]) } methods::setMethod("show", "RapReliableOpts", function(object) print.RapReliableOpts(object)) update.RapReliableOpts <- function(object, BLM = NULL, failure.multiplier = NULL, max.r.level = NULL, ...) { if (!is.null(BLM)) object@BLM <- BLM if (!is.null(failure.multiplier)) [email protected] <- failure.multiplier if (!is.null(max.r.level)) [email protected] <- max.r.level methods::validObject(object, test = FALSE) return(object) }
run.diff.exp <- function (x = NULL, data.type = "main", pval.test = "t.test", p.adjust.method = "hochberg", de.by = "clusters", cond.1 = "array", cond.2 = "array", base.cond = 0) { if ("iCellR" != class(x)[1]) { stop("x should be an object of class iCellR") } if (data.type == "main") { dat <- [email protected] } if (data.type == "imputed") { dat <- [email protected] } DATA <- [email protected] CondA = cond.1 CondB = cond.2 CondAnames = paste(CondA, collapse="_") CondBnames = paste(CondB, collapse="_") if (de.by == "clustBase.condComp") { CondAnames = paste(CondA, collapse="_") CondAnames = paste(CondAnames,"inClust",base.cond,sep=".") CondBnames = paste(CondB, collapse="_") CondBnames = paste(CondBnames,"inClust",base.cond,sep=".") } if (de.by == "condBase.clustComp") { CondAnames = paste(CondA, collapse="_") CondAnames = paste(CondAnames,"inCond",base.cond,sep=".") CondBnames = paste(CondB, collapse="_") CondBnames = paste(CondBnames,"inCond",base.cond,sep=".") } if (de.by == "conditions") { col.legend <- data.frame(do.call('rbind', strsplit(as.character(rownames(DATA)),'_',fixed=TRUE)))[1] conditions <- as.character(as.matrix(col.legend)) Table <- as.data.frame(cbind(DATA, conditions = conditions)) Cluster0 <- row.names(subset(Table, Table$conditions %in% CondA)) Cluster1 <- row.names(subset(Table, Table$conditions %in% CondB)) } if (de.by == "clusters") { if (is.null(DATA$clusters)) { stop("Clusters are not assigend yet, please run assign.clust fisrt.") } else { Table=DATA Cluster0 <- row.names(subset(Table, Table$clusters %in% CondA)) Cluster1 <- row.names(subset(Table, Table$clusters %in% CondB)) } } if (de.by == "clustBase.condComp") { if (base.cond == 0) { stop("You should choose a base cluster/clusters to compare the conditions in it/them") } my.base.cond = base.cond col.legend <- data.frame(do.call('rbind', strsplit(as.character(rownames(DATA)),'_',fixed=TRUE)))[1] conditions <- as.character(as.matrix(col.legend)) Table <- as.data.frame(cbind(DATA, conditions = conditions)) Table <- subset(Table, Table$clusters %in% my.base.cond) Cluster0 <- row.names(subset(Table, Table$conditions %in% CondA)) Cluster1 <- row.names(subset(Table, Table$conditions %in% CondB)) } if (de.by == "condBase.clustComp") { if (base.cond == 0) { stop("You should choose a base condition/conditions to compare the clusters in it/them") } my.base.cond = base.cond col.legend <- data.frame(do.call('rbind', strsplit(as.character(rownames(DATA)),'_',fixed=TRUE)))[1] conditions <- as.character(as.matrix(col.legend)) Table <- as.data.frame(cbind(DATA, conditions = conditions)) Table <- subset(Table, Table$conditions %in% my.base.cond) Cluster0 <- row.names(subset(Table, Table$clusters %in% CondA)) Cluster1 <- row.names(subset(Table, Table$clusters %in% CondB)) } cond1 <- dat[ , which(names(dat) %in% Cluster0)] cond2 <- dat[ , which(names(dat) %in% Cluster1)] mrgd <- cbind(cond1,cond2) mrgd <- data.matrix(mrgd) meansCond1 <- apply(cond1, 1, function(cond1) {mean(cond1)}) meansCond2 <- apply(cond2, 1, function(cond2) {mean(cond2)}) baseMean <- apply(mrgd, 1, function(mrgd) {mean(mrgd)}) FC <- meansCond2/meansCond1 FC.log2 <- log2(FC) Cond1_Start <- 1 Cond1_End <- dim(cond1)[2] Cond2_Start <- dim(cond1)[2] + 1 Cond2_End <- dim(cond1)[2] + dim(cond2)[2] FiltData <- subset(FC.log2,FC.log2!="NaN") mrgd <- subset(mrgd, row.names(mrgd) %in% row.names(as.data.frame(FiltData))) if (pval.test == "t.test") { Pval <- apply(mrgd, 1, function(mrgd) { t.test(x = mrgd[Cond1_Start:Cond1_End], y = mrgd[Cond2_Start:Cond2_End])$p.value }) } if (pval.test == "wilcox.test") { Pval <- apply(mrgd, 1, function(mrgd) { wilcox.test(x = mrgd[Cond1_Start:Cond1_End], y = mrgd[Cond2_Start:Cond2_End])$p.value }) } FDR <- p.adjust(Pval, method = p.adjust.method) Stats <- cbind( baseMean = baseMean, MeanCond1 = meansCond1, MeanCond2 = meansCond2, FC=FC, FC.log2=FC.log2) Stats1 <- cbind( pval = Pval, padj = FDR) Stats <- as.data.frame(Stats) Stats1 <- as.data.frame(Stats1) mrgdall <- merge(Stats, Stats1, by="row.names") row.names(mrgdall) <- mrgdall$Row.names mrgdall <- mrgdall[,-1] colnames(mrgdall) <- c("baseMean",CondAnames, CondBnames,"foldChange","log2FoldChange","pval","padj") return(mrgdall) }
F23Fun<-function(df,model,m_nf){ data<-sapply(df,as.character) dF23<-data[-1,which(data[1,]=="F23")];F23<-as.numeric(dF23[which(is.na(as.numeric(dF23))==FALSE)]);df<-as.data.frame(F23) F3colname <- c("Model","Log_Max_likelihood_Value","AIC","mean[1]","mean[2]","mean[3]","mean[4]","mean[5]","mean[6]","mean[7]","mean[8]","mean[9]", "Var[1]","Var[2]","Var[3]","Var[4]","Var[5]","Var[6]","Var[7]","Var[8]","Var[9]","Proportion[1]","Proportion[2]","Proportion[3]","Proportion[4]","Proportion[5]","Proportion[6]", "Proportion[7]","Proportion[8]","Proportion[9]","m","da(d)","db","ha(h)","hb","i","jab","jba","l","Major-Gene Var","Heritability(Major-Gene)(%)", "U1 square","P(U1 square)","U2 square","P(U2 square)","U3 square","P(U3 square)","nW square","P(nW square)","Dn","P(Dn)") F3ModelFun<-list(NA) F3ModelFun[[1]] <-function(K1,logL,df,m_nf){ data <- as.matrix(as.numeric(df[,1])) m_sam <- dim(data)[1]; mean0 <- mean(data); sigma0 <- var(data) m<-mean0 sigma<-sigma0 mix_pi <- 1 lp<-matrix(0,m_sam,1) for(j in 1:m_sam){lp[j]<-log(dnorm(data[j],m,sqrt(sigma)))} abc<-sum(lp) AIC<--2*abc+2*2 data<-sort(data) w1<-1/(12*m_sam) bmw <- matrix(0,m_sam,1) gg <- (data - m)/sqrt(as.vector(sigma)) bmw[which(gg>=0)] <- pnorm(gg[gg>=0]) bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0])) nn <- dim(as.matrix(unique(bmw)))[1] if(nn < m_sam){bmw <- bmw+runif(m_sam)/1e4} dd<-c((sum(bmw)),(sum(bmw^2)),sum((bmw-0.5)^2)) w<-w1+sum((bmw - (as.matrix(c(1:m_sam)) - 0.5)/m_sam)^2) u<- as.matrix(c(12*m_sam*((dd[1]/m_sam-0.5)^2),((45*m_sam)/4)*((dd[2]/m_sam-1/3)^2),180*m_sam*((dd[3]/m_sam-1/12)^2))) D<-as.numeric(ks.test(bmw,"punif")[[1]][1]) tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(w),(1-pkolm(D,m_sam)))) tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4) output <- data.frame("0MG",round(abc,4),round(AIC,4),round(m,4)," "," "," "," "," "," "," "," ",round(sigma,4)," "," "," "," "," "," "," "," ",round(mix_pi,4)," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(u[1],4),tt[1],round(u[2],4),tt[2],round(u[3],4),tt[3],round(w,4),tt[4],round(D,4),tt[5]) output<-as.matrix(output) OUTPUT<-list(output) return(OUTPUT) } F3ModelFun[[2]] <-function(K1,logL,df,m_nf){ data <- as.matrix(as.numeric(df[,1])) m_sam <- dim(data)[1]; d2<- 3; m_esp <- 0.0001 mean0 <- mean(data);sigma0 <- var(data) a1 <- sqrt(sigma0/m_sam) m <- as.matrix(c((mean0+2*a1),mean0,(mean0-2*a1))) mi <- as.matrix(c(0.25,0.5,0.25)) sigma <- matrix((sigma0/2),3,1) L0 <- sum(log(dmixnorm(data,m,sqrt(sigma),mi))) iteration <- 0; stopa <- 1000 WW <- matrix(0,3,m_sam); swx <- matrix(0,3,1); s0 <- matrix(0,2,1) while(stopa > m_esp && iteration <= 1000){ iteration <- iteration + 1 for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(data,m[i],sqrt(sigma[i]))/dmixnorm(data,m,sqrt(sigma),mi) } mix_pi <- as.matrix(rowSums(WW)/m_sam) sumwx <- WW%*%data n0 <- m_sam*mix_pi n0[abs(n0)<0.000001] <- 0.000001 m <- sumwx/n0 hh1 <- matrix(c(1,1,1,1,0,-1,0,0.5,0),3,3) b_line1 <- m; B1 <- solve(hh1,b_line1) aa3<-(0.5*B1[2]^2+0.25*B1[3]^2)/m_nf for(i in 1:d2) { swx[i] <- WW[i,]%*%(data-m[i])^2 } s0[1]<-swx[1]+swx[3] s0[2]<-n0[1]+n0[3] aaa0<-sigma[1] n_iter<-0 aa5<-1000 while(aa5>0.0001){ n_iter<-n_iter+1.0 aa4<-sigma[1]/(sigma[1]+aa3) sigma[1]<-(s0[1]+aa4^2*swx[2])/(s0[2]+aa4*n0[2]) aa5<-abs(sigma[1]-aaa0) aaa0<-sigma[1] if(n_iter>20)break } sigma[2]<-sigma[1]+aa3 sigma[3]<-sigma[1] L1 <- sum(log(dmixnorm(data,m,sqrt(sigma),mix_pi))) stopa <- L1 - L0 L0 <- L1 if(stopa < 0) {stopa <- -stopa} } abc<-L0 AIC<--2*abc+2*5 jj <- sigma0 - sigma[1] if(jj < 0) {jj <- 0} ll <- jj/sigma0 data <- sort(data) w1<-1/(12*m_sam) bmw <- matrix(0,m_sam,1); bmwsl <- matrix(0,m_sam,d2) for(i in 1:d2){ gg <- (data - m[i])/sqrt(sigma[i]) bmw[which(gg>=0)] <- pnorm(gg[gg>=0]) bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0])) bmwsl[,i] <- bmw*mix_pi[i] } P2 <- rowSums(bmwsl) nn <- dim(as.matrix(unique(P2)))[1] if(nn < m_sam){P2 <- P2+runif(m_sam)/1e4} dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2))) WW2 <- 1/(12*m_sam) + sum((P2 - (as.matrix(c(1:m_sam)) - 0.5)/m_sam)^2) u <- as.matrix(c(12*m_sam*((dd[1]/m_sam-0.5)^2),((45*m_sam)/4)*((dd[2]/m_sam-1/3)^2),180*m_sam*((dd[3]/m_sam-1/12)^2))) D <- as.numeric(ks.test(P2,"punif")[[1]][1]) tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,m_sam)))) tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4) output <- data.frame("1MG-AD",round(abc,4),round(AIC,4),round(t(m),4)," "," "," "," "," "," ",round(t(sigma),4)," "," "," "," "," "," ",round(t(mix_pi),4)," "," "," "," "," "," ",round(B1[1],4),round(B1[2],4)," ",round(B1[3],4)," "," "," "," "," ",round(jj,4),round(ll*100,4),round(u[1],4),tt[1],round(u[2],4),tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5]) output<-as.matrix(output) OUTPUT<-list(output,mi) return(OUTPUT) } F3ModelFun[[3]] <-function(K1,logL,df,m_nf) { data <- as.matrix(as.numeric(as.numeric(df[,1]))) m_sam <- dim(data)[1]; d2 <- 3; m_esp <- 0.0001 mean0 <- mean(data);sigma0 <- var(data) a1 <- sqrt(sigma0) m <- as.matrix(c((mean0+2*a1),mean0,(mean0-2*a1))) mi <- as.matrix(c(0.25,0.5,0.25)) sigma <- matrix((sigma0/2),3,1) L0 <- sum(log(dmixnorm(data,m,sqrt(sigma),mi))) iteration <- 0; stopa <- 1000 WW <- matrix(0,3,m_sam); swx <- matrix(0,3,1);s0 <- matrix(0,2,1) while(stopa > m_esp && iteration <= 1000){ iteration <- iteration + 1 for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(data,m[i],sqrt(sigma[i]))/dmixnorm(data,m,sqrt(sigma),mi) } mix_pi <- as.matrix(rowSums(WW)/m_sam) sumwx <- WW%*%data n0 <- m_sam*mix_pi n0[abs(n0)<0.000001] <- 0.000001 aa1<-sigma[1]/n0[1]+4*sigma[2]/n0[2]+sigma[3]/n0[3] aa2<-sumwx[1]/n0[1]-2.0*sumwx[2]/n0[2]+sumwx[3]/n0[3] aa3<-aa2/aa1 m[1]<-(sumwx[1]-sigma[1]*aa3)/n0[1] m[2]<-(sumwx[2]+sigma[1]*2*aa3)/n0[2] m[3]<-(sumwx[3]-sigma[1]*aa3)/n0[3] hh1 <- matrix(c(1,1,1,1,0,-1),3,2) B1<-solve(crossprod(hh1,hh1))%*%crossprod(hh1,m) aa3<-0.5*B1[2]^2/m_nf for(i in 1:d2) { swx[i] <- WW[i,]%*%(data-m[i])^2 } s0[1]<-swx[1]+swx[3] s0[2]<-n0[1]+n0[3] aaa0<-sigma[1] n_iter<-0 aa5<-1000 while(aa5>0.0001){ n_iter<-n_iter+1.0 aa4<-sigma[1]/(sigma[1]+aa3) sigma[1]<-(s0[1]+aa4^2*swx[2])/(s0[2]+aa4*n0[2]) aa5<-abs(sigma[1]-aaa0) aaa0<-sigma[1] if(n_iter>20)break } sigma[2]<-sigma[1]+aa3 sigma[3]<-sigma[1] L1 <- sum(log(dmixnorm(data,m,sqrt(sigma),mix_pi))) stopa <- L1 - L0 L0 <- L1 if(stopa < 0) {stopa <- -stopa} } abc<-L0 AIC<--2*abc+2*3 jj <- sigma0 - sigma[1] if(jj < 0) {jj <- 0} ll <- jj/sigma0 data <- sort(data) w1<-1/(12*m_sam) bmw <- matrix(0,m_sam,1); bmwsl <- matrix(0,m_sam,d2) for(i in 1:d2){ gg <- (data - m[i])/sqrt(sigma[i]) bmw[which(gg>=0)] <- pnorm(gg[gg>=0]) bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0])) bmwsl[,i] <- bmw*mix_pi[i] } P2 <- rowSums(bmwsl) nn <- dim(as.matrix(unique(P2)))[1] if(nn < m_sam){P2 <- P2+runif(m_sam)/1e4} dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2))) WW2 <- 1/(12*m_sam) + sum((P2 - (as.matrix(c(1:m_sam)) - 0.5)/m_sam)^2) u <- as.matrix(c(12*m_sam*((dd[1]/m_sam-0.5)^2),((45*m_sam)/4)*((dd[2]/m_sam-1/3)^2),180*m_sam*((dd[3]/m_sam-1/12)^2))) D <- as.numeric(ks.test(P2,"punif")[[1]][1]) tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,m_sam)))) tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4) output <- data.frame("1MG-A",round(abc,4),round(AIC,4),round(t(m),4)," "," "," "," "," "," ",round(t(sigma),4)," "," "," "," "," "," ",round(t(mix_pi),4)," "," "," "," "," "," ",round(B1[1],4),round(B1[2],4)," "," "," "," "," "," "," ",round(jj,4),round(ll*100,4),round(u[1],4),tt[1],round(u[2],4),tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5]) output<-as.matrix(output) OUTPUT<-list(output,mi) return(OUTPUT) } F3ModelFun[[4]] <-function(K1,logL,df,m_nf){ data <- as.matrix(as.numeric(as.numeric(df[,1]))) m_sam <- dim(data)[1]; d2 <- 3; m_esp <- 0.0001 mean0 <- mean(data);sigma0 <- var(data) a1 <- sqrt(sigma0/m_sam) m <- as.matrix(c((mean0+2*a1),mean0,(mean0-2*a1))) mi <- as.matrix(c(0.25,0.5,0.25)) sigma <- matrix((sigma0/2),3,1) L0 <- sum(log(dmixnorm(data,m,sqrt(sigma),mi))) iteration <- 0; stopa <- 1000 WW <- matrix(0,3,m_sam); swx <- matrix(0,3,1);s0 <- matrix(0,2,1) while(stopa > m_esp && iteration <= 1000){ iteration <- iteration + 1 for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(data,m[i],sqrt(sigma[i]))/dmixnorm(data,m,sqrt(sigma),mi) } mix_pi <- as.matrix(rowSums(WW)/m_sam) sumwx <- WW%*%data n0 <- m_sam*mix_pi n0[abs(n0)<0.000001] <- 0.000001 aa1<-3*sumwx[1]/n0[1]-4*sumwx[2]/n0[2]+sumwx[3]/n0[3] aa2<-9*sigma[1]/n0[1]+16*sigma[2]/n0[2]+sigma[3]/n0[3] aa3<-aa1/aa2 m[1]<-(sumwx[1]-sigma[1]*3*aa3)/n0[1] m[2]<-(sumwx[2]+sigma[2]*4*aa3)/n0[2] m[3]<-(sumwx[3]-sigma[3]*aa3)/n0[3] hh1 <- matrix(c(1,1,1,1,0.5,-1),3,2) B1<-solve(crossprod(hh1,hh1))%*%crossprod(hh1,m) aa3<-0.75*B1[2]^2/m_nf for(i in 1:d2) { swx[i] <- WW[i,]%*%(data-m[i])^2 } s0[1]<-swx[1]+swx[3] s0[2]<-n0[1]+n0[3] aaa0<-sigma[1] n_iter<-0 aa5<-1000 while(aa5>0.0001){ n_iter<-n_iter+1.0 aa4<-sigma[1]/(sigma[1]+aa3) sigma[1]<-(s0[1]+aa4^2*swx[2])/(s0[2]+aa4*n0[2]) aa5<-abs(sigma[1]-aaa0) aaa0<-sigma[1] if(n_iter>20)break } sigma[2]<-sigma[1]+aa3 sigma[3]<-sigma[1] L1 <- sum(log(dmixnorm(data,m,sqrt(sigma),mix_pi))) stopa <- L1 - L0 L0 <- L1 if(stopa < 0) {stopa <- -stopa} } abc<-L0 AIC<--2*abc+2*4 jj <- sigma0 - sigma[1] if(jj < 0) {jj <- 0} ll <- jj/sigma0 data <- sort(data); w1<-1/(12*m_sam) bmw <- matrix(0,m_sam,1); bmwsl <- matrix(0,m_sam,d2) for(i in 1:d2){ gg <- (data - m[i])/sqrt(sigma[i]) bmw[which(gg>=0)] <- pnorm(gg[gg>=0]) bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0])) bmwsl[,i] <- bmw*mix_pi[i] } P2 <- rowSums(bmwsl) nn <- dim(as.matrix(unique(P2)))[1] if(nn < m_sam){P2 <- P2+runif(m_sam)/1e4} dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2))) WW2 <- 1/(12*m_sam) + sum((P2 - (as.matrix(c(1:m_sam)) - 0.5)/m_sam)^2) u <- as.matrix(c(12*m_sam*((dd[1]/m_sam-0.5)^2),((45*m_sam)/4)*((dd[2]/m_sam-1/3)^2),180*m_sam*((dd[3]/m_sam-1/12)^2))) D <- as.numeric(ks.test(P2,"punif")[[1]][1]) tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,m_sam)))) tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4) output <- data.frame("1MG-EAD",round(abc,4),round(AIC,4),round(t(m),4)," "," "," "," "," "," ",round(t(sigma),4)," "," "," "," "," "," ",round(t(mix_pi),4)," "," "," "," "," "," ",round(B1[1],4),round(B1[2],4)," "," "," "," "," "," "," ",round(jj,4),round(ll*100,4),round(u[1],4),tt[1],round(u[2],4),tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5]) output<-as.matrix(output) OUTPUT<-list(output,mi) return(OUTPUT) } F3ModelFun[[5]] <-function(K1,logL,df,m_nf){ data <- as.matrix(as.numeric(as.numeric(df[,1]))) m_sam <- dim(data)[1]; d2 <- 3; m_esp <- 0.0001 mean0 <- mean(data);sigma0 <- var(data) a1 <- sqrt(sigma0/m_sam) m <- as.matrix(c((mean0+2*a1),mean0,(mean0-2*a1))) mi <- as.matrix(c(0.25,0.5,0.25)) sigma <- matrix((sigma0/2),3,1) L0 <- sum(log(dmixnorm(data,m,sqrt(sigma),mi))) iteration <- 0; stopa <- 1000 WW <- matrix(0,3,m_sam); swx <- matrix(0,3,1); s0 <- matrix(0,2,1) while(stopa > m_esp && iteration <= 1000){ iteration <- iteration + 1 for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(data,m[i],sqrt(sigma[i]))/dmixnorm(data,m,sqrt(sigma),mi) } mix_pi <- as.matrix(rowSums(WW)/m_sam) sumwx <- WW%*%data n0 <- m_sam*mix_pi n0[abs(n0)<0.000001] <- 0.000001 aa1<-sumwx[1]/n0[1]-4.0*sumwx[2]/n0[2]+3.0*sumwx[3]/n0[3] aa2<-sigma[1]/n0[1]+16.0*sigma[2]/n0[2]+9.0*sigma[3]/n0[3] aa3<-aa1/aa2 m[1]<-(sumwx[1]-sigma[1]*aa3)/n0[1] m[2]<-(sumwx[2]+sigma[2]*aa3*4.0)/n0[2] m[3]<-(sumwx[3]-sigma[3]*aa3*3.0)/n0[3] hh1 <- matrix(c(1,1,1,1,-0.5,-1),3,2) B1<-solve(crossprod(hh1,hh1))%*%crossprod(hh1,m) aa3<-0.75*B1[2]^2/m_nf for(i in 1:d2) { swx[i] <- WW[i,]%*%(data-m[i])^2 } s0[1]<-swx[1]+swx[3] s0[2]<-n0[1]+n0[3] aaa0<-sigma[1] n_iter<-0 aa5<-1000 while(aa5>0.0001){ n_iter<-n_iter+1.0 aa4<-sigma[1]/(sigma[1]+aa3) sigma[1]<-(s0[1]+aa4^2*swx[2])/(s0[2]+aa4*n0[2]) aa5<-abs(sigma[1]-aaa0) aaa0<-sigma[1] if(n_iter>20)break } sigma[2]<-sigma[1]+aa3 sigma[3]<-sigma[1] L1 <- sum(log(dmixnorm(data,m,sqrt(sigma),mix_pi))) stopa <- L1 - L0 L0 <- L1 if(stopa < 0) {stopa <- -stopa} } abc<-L0 AIC<--2*abc+2*4 jj <- sigma0 - sigma[1] if(jj < 0) {jj <- 0} ll <- jj/sigma0 data <- sort(data) w1<-1/(12*m_sam) bmw <- matrix(0,m_sam,1); bmwsl <- matrix(0,m_sam,d2) for(i in 1:d2){ gg <- (data - m[i])/sqrt(sigma[i]) bmw[which(gg>=0)] <- pnorm(gg[gg>=0]) bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0])) bmwsl[,i] <- bmw*mix_pi[i] } P2 <- rowSums(bmwsl) nn <- dim(as.matrix(unique(P2)))[1] if(nn < m_sam){P2 <- P2+runif(m_sam)/1e4} dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2))) WW2 <- 1/(12*m_sam) + sum((P2 - (as.matrix(c(1:m_sam)) - 0.5)/m_sam)^2) u <- as.matrix(c(12*m_sam*((dd[1]/m_sam-0.5)^2),((45*m_sam)/4)*((dd[2]/m_sam-1/3)^2),180*m_sam*((dd[3]/m_sam-1/12)^2))) D <- as.numeric(ks.test(P2,"punif")[[1]][1]) tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,m_sam)))) tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4) output <- data.frame("1MG-NCD",round(abc,4),round(AIC,4),round(t(m),4)," "," "," "," "," "," ",round(t(sigma),4)," "," "," "," "," "," ",round(t(mix_pi),4)," "," "," "," "," "," ",round(B1[1],4),round(B1[2],4)," "," "," "," "," "," "," ",round(jj,4),round(ll*100,4),round(u[1],4),tt[1],round(u[2],4),tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5]) output<-as.matrix(output) OUTPUT<-list(output,mi) return(OUTPUT) } F3ModelFun[[6]] <-function(K1,logL,df,m_nf){ data <- as.matrix(as.numeric(as.numeric(df[,1]))) m_sam <- dim(data)[1]; d4 <- 9; m_esp <- 0.0001 mean0 <- mean(data);sigma0 <- var(data) a1 <- sqrt(sigma0) sigma <- matrix((sigma0/2),9,1) m <- as.matrix(c((mean0+3.2*a1),(mean0+2.4*a1),(mean0+1.6*a1),(mean0+0.8*a1),mean0, (mean0-0.8*a1),(mean0-1.6*a1),(mean0-2.4*a1),(mean0-3.2*a1))) mi <- as.matrix(c(0.0625,0.125,0.0625,0.125,0.25,0.125,0.0625,0.125,0.0625)) L0 <- sum(log(dmixnorm(data,m,sqrt(sigma),mi))) iteration <- 0; stopa <- 1000 WW <- matrix(0,9,m_sam); swx <- matrix(0,9,1);g_a<-matrix(0,5,1);s0 <- matrix(0,2,1) while(stopa > m_esp && iteration <= 1000){ iteration <- iteration + 1 for(i in 1:d4) { WW[i,] <- mi[i]*dnorm(data,m[i],sqrt(sigma[i]))/dmixnorm(data,m,sqrt(sigma),mi) } mix_pi <- as.matrix(rowSums(WW)/m_sam) sumwx <- WW%*%data n0 <- m_sam*mix_pi n0[abs(n0)<0.000001] <- 0.000001 m<-sumwx/n0 hh5 <- matrix(c(1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,-1,-1,-1,1,0,-1,1,0,-1,1,0,-1,0,0,0,0.5,0.5,0.5,0,0,0, 0,0.5,0,0,0.5,0,0,0.5,0,1,0,-1,0,0,0,-1,0,1,0,0.5,0,0,0,0,0,-0.5,0,0,0,0,0.5,0,-0.5,0, 0,0,0,0,0,0,0.25,0,0,0,0),9,9) b_line5 <- m; B5 <- solve(hh5,b_line5) g_a[1]<-(0.5*(B5[3]+B5[6])^2+0.25*(B5[5]+B5[7])^2)/m_nf g_a[2]<-(0.5*(B5[2]+B5[6])^2+0.25*(B5[4]+B5[8])^2)/m_nf g_a[3]<-(0.5*(B5[2]-B5[6])^2+0.25*(B5[4]-B5[8])^2)/m_nf g_a[4]<-(0.5*(B5[3]-B5[6])^2+0.25*(B5[5]-B5[7])^2)/m_nf g_a[5]<-0.25*(B5[2]^2+B5[3]^2+B5[6]^2+(B5[2]+B5[7])^2+(B5[3]+B5[8])^2+(B5[4]+0.5*B5[9])^2+(B5[5]+0.5*B5[9])^2+0.25*B5[9]^2)/m_nf for(i in 1:d4) { swx[i] <- WW[i,]%*%(data-m[i])^2 } s0[1]<-swx[1]+swx[3]+swx[7]+swx[9] s0[2]<-n0[1]+n0[3]+n0[7]+n0[9] aaa0<-sigma[1] n_iter<-0 aa6<-1000 while(aa6>0.0001){ n_iter<-n_iter+1 aa1<-sigma[1]/(sigma[1]+g_a[1]);aa2<-sigma[1]/(sigma[1]+g_a[2]) aa3<-sigma[1]/(sigma[1]+g_a[3]);aa4<-sigma[1]/(sigma[1]+g_a[4]) aa5<-sigma[1]/(sigma[1]+g_a[5]) sigma[1]<-(s0[1]+aa1^2*swx[2]+aa2^2*swx[4]+aa5^2*swx[5]+aa3^2*swx[6]+aa4^2*swx[8])/(s0[2]+aa1*n0[2]+aa2*n0[4]+aa5*n0[5]+aa3*n0[6]+aa4*n0[8]) aa6<-abs(sigma[1]-aaa0) aaa0<-sigma[1] if(n_iter>20)break } sigma[3]<-sigma[1];sigma[7]<-sigma[1];sigma[9]<-sigma[1] sigma[2]<-sigma[1]+g_a[1];sigma[4]<-sigma[1]+g_a[2];sigma[5]<-sigma[1]+g_a[5] sigma[6]<-sigma[1]+g_a[3];sigma[8]<-sigma[1]+g_a[4] L1 <- sum(log(dmixnorm(data,m,sqrt(sigma),mix_pi))) stopa <- L1 - L0 L0 <- L1 if(stopa < 0) {stopa <- -stopa} if(iteration>1000)break } abc<-L0 AIC<--2*abc+2*10 jj <- sigma0 - sigma[1] if(jj < 0) {jj <- 0} ll <- jj/sigma0 data <- sort(data) w1<-1/(12*m_sam) bmw <- matrix(0,m_sam,1); bmwsl <- matrix(0,m_sam,d4) for(i in 1:d4){ gg <- (data - m[i])/sqrt(sigma[i]) bmw[which(gg>=0)] <- pnorm(gg[gg>=0]) bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0])) bmwsl[,i] <- bmw*mix_pi[i] } P2 <- rowSums(bmwsl) nn <- dim(as.matrix(unique(P2)))[1] if(nn < m_sam){P2 <- P2+runif(m_sam)/1e4} dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2))) WW2 <- 1/(12*m_sam) + sum((P2 - (as.matrix(c(1:m_sam)) - 0.5)/m_sam)^2) u <- as.matrix(c(12*m_sam*((dd[1]/m_sam-0.5)^2),((45*m_sam)/4)*((dd[2]/m_sam-1/3)^2),180*m_sam*((dd[3]/m_sam-1/12)^2))) D <- as.numeric(ks.test(P2,"punif")[[1]][1]) tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,m_sam)))) tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4) output <- data.frame("2MG-ADI",round(abc,4),round(AIC,4),round(t(m),4),round(t(sigma),4),round(t(mix_pi),4),round(t(B5),4),round(jj,4),round(ll*100,4),round(u[1],4),tt[1],round(u[2],4),tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5]) output<-as.matrix(output) OUTPUT<-list(output,mi) return(OUTPUT) } F3ModelFun[[7]] <-function(K1,logL,df,m_nf){ data <- as.matrix(as.numeric(as.numeric(df[,1]))) m_sam <- dim(data)[1]; d4 <- 9; m_esp <- 0.0001 mean0 <- mean(data);sigma0 <- var(data) a1 <- sqrt(sigma0) sigma <- matrix((sigma0/2),9,1) m <- as.matrix(c((mean0+3.2*a1),(mean0+2.4*a1),(mean0+1.6*a1),(mean0+0.8*a1),mean0,(mean0-0.8*a1),(mean0-1.6*a1),(mean0-2.4*a1),(mean0-3.2*a1))) mi <- as.matrix(c(0.0625,0.125,0.0625,0.125,0.25,0.125,0.0625,0.125,0.0625)) L0 <- sum(log(dmixnorm(data,m,sqrt(sigma),mi))) iteration <- 0; stopa <- 1000 WW <- matrix(0,9,m_sam); swx <- matrix(0,9,1); hh <- matrix(0,4,4); b_line <- matrix(0,4,1) g_a<-matrix(0,3,1);s0 <- matrix(0,2,1) while(stopa > m_esp && iteration <= 1000){ iteration <- iteration + 1 for(i in 1:d4) { WW[i,] <- mi[i]*dnorm(data,m[i],sqrt(sigma[i]))/dmixnorm(data,m,sqrt(sigma),mi) } mix_pi <- as.matrix(rowSums(WW)/m_sam) sumwx <- WW%*%data n0 <- m_sam*mix_pi n0[abs(n0)<0.000001] <- 0.000001 hh[1,1]<-sigma[1]/n0[1]+sigma[3]/n0[3]+sigma[7]/n0[7]+sigma[9]/n0[9] hh[1,2]<-sigma[1]/n0[1]+sigma[7]/n0[7] hh[1,3]<-sigma[1]/n0[1]+sigma[3]/n0[3] hh[1,4]<-sigma[7]/n0[7]-sigma[9]/n0[9] hh[2,2]<-sigma[1]/n0[1]+sigma[2]/n0[2]+sigma[7]/n0[7]+sigma[8]/n0[8] hh[2,3]<-sigma[1]/n0[1] hh[2,4]<-sigma[7]/n0[7]+2.0*sigma[8]/n0[8] hh[3,3]<-sigma[1]/n0[1]+sigma[3]/n0[3]+sigma[4]/n0[4]+sigma[6]/n0[6] hh[3,4]<--sigma[4]/n0[4]+sigma[6]/n0[6] hh[4,4]<-sigma[4]/n0[4]+4.0*sigma[5]/n0[5]+sigma[6]/n0[6]+sigma[7]/n0[7]+4.0*sigma[8]/n0[8]+sigma[9]/n0[9] for(i in 2:4) { for(j in 1:(i-1)) { hh[i,j]<-hh[j,i] } } b_line[1]<-sumwx[1]/n0[1]-sumwx[3]/n0[3]-sumwx[7]/n0[7]+sumwx[9]/n0[9] b_line[2]<-sumwx[1]/n0[1]-sumwx[2]/n0[2]-sumwx[7]/n0[7]+sumwx[8]/n0[8] b_line[3]<-sumwx[1]/n0[1]-sumwx[3]/n0[3]-sumwx[4]/n0[4]+sumwx[6]/n0[6] b_line[4]<-sumwx[4]/n0[4]-2.0*sumwx[5]/n0[5]+sumwx[6]/n0[6]-sumwx[7]/n0[7]+2.0*sumwx[8]/n0[8]-sumwx[9]/n0[9] B6<- solve(hh,b_line) m[1]<-(sumwx[1]-sigma[1]*(B6[1]+B6[2]+B6[3]))/n0[1] m[2]<-(sumwx[2]+sigma[2]*B6[2])/n0[2] m[3]<-(sumwx[3]+sigma[3]*(B6[1]+B6[3]))/n0[3] m[4]<-(sumwx[4]+sigma[4]*(B6[3]-B6[4]))/n0[4] m[5]<-(sumwx[5]+sigma[5]*2*B6[4])/n0[5] m[6]<-(sumwx[6]-sigma[6]*(B6[3]+B6[4]))/n0[6] m[7]<-(sumwx[7]+sigma[7]*(B6[1]+B6[2]+B6[4]))/n0[7] m[8]<-(sumwx[8]-sigma[8]*(B6[2]+2*B6[4]))/n0[8] m[9]<-(sumwx[9]-sigma[9]*(B6[1]-B6[4]))/n0[9] hh61 <- matrix(c(1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,-1,-1,-1,1,0,-1,1,0,-1,1,0,-1, 0,0,0,0.5,0.5,0.5,0,0,0,0,0.5,0,0,0.5,0,0,0.5,0),9,5) B61<-solve(crossprod(hh61,hh61))%*%crossprod(hh61,m) g_a[1]<-(0.5*B61[3]^2+0.25*B61[5]^2)/m_nf g_a[2]<-(0.5*B61[2]^2+0.25*B61[4]^2)/m_nf g_a[3]<-(0.5*(B61[2]^2+B61[3]^2)+0.25*(B61[4]^2+B61[5]^2))/m_nf for(i in 1:d4) { swx[i] <- WW[i,]%*%(data-m[i])^2 } s0[1]<-swx[1]+swx[3]+swx[7]+swx[9] s0[2]<-n0[1]+n0[3]+n0[7]+n0[9] aaa0<-sigma[1] n_iter<-0 aa6<-1000 while(aa6>0.0001){ n_iter<-n_iter+1 aa1<-sigma[1]/(sigma[1]+g_a[1]) aa2<-sigma[1]/(sigma[1]+g_a[2]) aa3<-sigma[1]/(sigma[1]+g_a[3]) sigma[1]<-(s0[1]+aa1^2*(swx[2]+swx[8])+aa2^2*(swx[4]+swx[6])+aa3^2*swx[5])/(s0[2]+aa1*(n0[2]+n0[8])+aa2*(n0[4]+n0[6])+aa3*n0[5]) aa6<-abs(sigma[1]-aaa0) aaa0<-sigma[1] if(n_iter>20)break } sigma[3]<-sigma[1];sigma[7]<-sigma[1];sigma[9]<-sigma[1] sigma[2]<-sigma[1]+g_a[1];sigma[4]<-sigma[1]+g_a[2] sigma[5]<-sigma[1]+g_a[3];sigma[6]<-sigma[1]+g_a[2];sigma[8]<-sigma[1]+g_a[1] L1 <- sum(log(dmixnorm(data,m,sqrt(sigma),mix_pi))) stopa <- L1 - L0 L0 <- L1 if(stopa < 0) {stopa <- -stopa} } abc<-L0 AIC<--2*abc+2*6 jj <- sigma0 - sigma[1] if(jj < 0) {jj <- 0} ll <- jj/sigma0 data <- sort(data) w1<-1/(12*m_sam) bmw <- matrix(0,m_sam,1); bmwsl <- matrix(0,m_sam,d4) for(i in 1:d4){ gg <- (data - m[i])/sqrt(sigma[i]) bmw[which(gg>=0)] <- pnorm(gg[gg>=0]) bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0])) bmwsl[,i] <- bmw*mix_pi[i] } P2 <- rowSums(bmwsl) nn <- dim(as.matrix(unique(P2)))[1] if(nn < m_sam){P2 <- P2+runif(m_sam)/1e4} dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2))) WW2 <- 1/(12*m_sam) + sum((P2 - (as.matrix(c(1:m_sam)) - 0.5)/m_sam)^2) u <- as.matrix(c(12*m_sam*((dd[1]/m_sam-0.5)^2),((45*m_sam)/4)*((dd[2]/m_sam-1/3)^2),180*m_sam*((dd[3]/m_sam-1/12)^2))) D <- as.numeric(ks.test(P2,"punif")[[1]][1]) tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,m_sam)))) tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4) output <- data.frame("2MG-AD",round(abc,4),round(AIC,4),round(t(m),4),round(t(sigma),4),round(t(mix_pi),4),round(t(B61),4)," "," "," "," ",round(jj,4),round(ll*100,4),round(u[1],4),tt[1],round(u[2],4),tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5]) output<-as.matrix(output) OUTPUT<-list(output,mi) return(OUTPUT) } F3ModelFun[[8]] <-function(K1,logL,df,m_nf){ data <- as.matrix(as.numeric(as.numeric(df[,1]))) m_sam <- dim(data)[1]; d4 <- 9; m_esp <- 0.0001 mean0 <- mean(data);sigma0 <- var(data) a1 <- sqrt(sigma0) sigma <- matrix((sigma0/2),9,1) m <- as.matrix(c((mean0+3.2*a1),(mean0+2.4*a1),(mean0+1.6*a1),(mean0+0.8*a1),mean0,(mean0-0.8*a1),(mean0-1.6*a1),(mean0-2.4*a1),(mean0-3.2*a1))) mi <- as.matrix(c(0.0625,0.125,0.0625,0.125,0.25,0.125,0.0625,0.125,0.0625)) L0 <- sum(log(dmixnorm(data,m,sqrt(sigma),mi))) iteration <- 0; stopa <- 1000 WW <- matrix(0,9,m_sam); swx <- matrix(0,9,1); hh <- matrix(0,6,6); b_line <- matrix(0,6,1) g_a<-matrix(0,3,1); s0 <- matrix(0,2,1) while(stopa > m_esp && iteration <= 1000){ iteration <- iteration + 1 for(i in 1:d4) { WW[i,] <- mi[i]*dnorm(data,m[i],sqrt(sigma[i]))/dmixnorm(data,m,sqrt(sigma),mi) } mix_pi <- as.matrix(rowSums(WW)/m_sam) sumwx <- WW%*%data n0 <- m_sam*mix_pi n0[abs(n0)<0.000001] <- 0.000001 hh[1,1]<-sigma[1]/n0[1]+sigma[3]/n0[3]+sigma[7]/n0[7]+sigma[9]/n0[9] hh[1,2]<-sigma[1]/n0[1]+sigma[7]/n0[7] hh[1,3]<--sigma[3]/n0[3]-sigma[7]/n0[7] hh[1,4]<-2.0*sigma[3]/n0[3] hh[1,5]<--sigma[7]/n0[7]+sigma[9]/n0[9] hh[1,6]<-sigma[1]/n0[1]-sigma[7]/n0[7] hh[2,2]<-sigma[1]/n0[1]+sigma[2]/n0[2]+sigma[7]/n0[7]+sigma[8]/n0[8] hh[2,3]<--sigma[7]/n0[7] hh[2,4]<--2.0*sigma[2]/n0[2] hh[2,5]<--sigma[7]/n0[7]-2.0*sigma[8]/n0[8] hh[2,6]<-hh[1,6] hh[3,3]<-sigma[3]/n0[3]+4.0*sigma[5]/n0[5]+sigma[7]/n0[7] hh[3,4]<--2.0*sigma[3]/n0[3] hh[3,5]<-sigma[7]/n0[7] hh[3,6]<-hh[3,5] hh[4,4]<-4.0*sigma[2]/n0[2]+4.0*sigma[3]/n0[3]+sigma[4]/n0[4]+sigma[6]/n0[6] hh[4,5]<-0 hh[4,6]<-2.0*sigma[4]/n0[4] hh[5,5]<-sigma[7]/n0[7]+4.0*sigma[8]/n0[8]+sigma[9]/n0[9] hh[5,6]<-hh[3,5] hh[6,6]<-sigma[1]/n0[1]+4.0*sigma[4]/n0[4]+sigma[7]/n0[7] for(i in 2:6) { for(j in 1:(i-1)) { hh[i,j]<-hh[j,i] } } b_line[1]<-sumwx[1]/n0[1]-sumwx[3]/n0[3]-sumwx[7]/n0[7]+sumwx[9]/n0[9] b_line[2]<-sumwx[1]/n0[1]-sumwx[2]/n0[2]-sumwx[7]/n0[7]+sumwx[8]/n0[8] b_line[3]<-sumwx[3]/n0[3]-2*sumwx[5]/n0[5]+sumwx[7]/n0[7] b_line[4]<-2*sumwx[2]/n0[2]-2*sumwx[3]/n0[3]-sumwx[4]/n0[4]+sumwx[6]/n0[6] b_line[5]<-sumwx[7]/n0[7]-2*sumwx[8]/n0[8]+sumwx[9]/n0[9] b_line[6]<-sumwx[1]/n0[1]-2*sumwx[4]/n0[4]+sumwx[7]/n0[7] B7<- solve(hh,b_line) m[1]<-(sumwx[1]-sigma[1]*(B7[1]+B7[2]+B7[6]))/n0[1] m[2]<-(sumwx[2]+sigma[2]*(B7[2]-2*B7[4]))/n0[2] m[3]<-(sumwx[3]+sigma[3]*(B7[1]-B7[3]+2*B7[4]))/n0[3] m[4]<-(sumwx[4]+sigma[4]*(-B7[4]+2*B7[6]))/n0[4] m[5]<-(sumwx[5]+sigma[5]*(2*B7[3]))/n0[5] m[6]<-(sumwx[6]-sigma[6]*B7[4])/n0[6] m[7]<-(sumwx[7]+sigma[7]*(B7[1]+B7[2]-B7[3]-B7[5]-B7[6]))/n0[7] m[8]<-(sumwx[8]+sigma[8]*(-B7[2]+2*B7[5]))/n0[8] m[9]<-(sumwx[9]-sigma[9]*(B7[1]+B7[5]))/n0[9] hh71 <- matrix(c(1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,-1,-1,-1,1,0,-1,1,0,-1,1,0,-1),9,3) B71<-solve(crossprod(hh71,hh71))%*%crossprod(hh71,m) g_a[1]<-(0.5*B71[3]^2)/m_nf g_a[2]<-(0.5*B71[2]^2)/m_nf g_a[3]<-g_a[1]+g_a[2] for(i in 1:d4) { swx[i] <- WW[i,]%*%(data-m[i])^2 } s0[1]<-swx[1]+swx[3]+swx[7]+swx[9] s0[2]<-n0[1]+n0[3]+n0[7]+n0[9] aaa0<-sigma[1] n_iter<-0 aa6<-1000 while(aa6>0.0001){ n_iter<-n_iter+1 aa1<-sigma[1]/(sigma[1]+g_a[1]) aa2<-sigma[1]/(sigma[1]+g_a[2]) aa3<-sigma[1]/(sigma[1]+g_a[3]) sigma[1]<-(s0[1]+aa1^2*(swx[2]+swx[8])+aa2^2*(swx[4]+swx[6])+aa3^2*swx[5])/(s0[2]+aa1*(n0[2]+n0[8])+aa2*(n0[4]+n0[6])+aa3*n0[5]) aa6<-abs(sigma[1]-aaa0) aaa0<-sigma[1] if(n_iter>20)break } sigma[3]<-sigma[1];sigma[7]<-sigma[1];sigma[9]<-sigma[1] sigma[2]<-sigma[1]+g_a[1];sigma[4]<-sigma[1]+g_a[2] sigma[5]<-sigma[1]+g_a[3];sigma[6]<-sigma[1]+g_a[2];sigma[8]<-sigma[1]+g_a[1] L1 <- sum(log(dmixnorm(data,m,sqrt(sigma),mix_pi))) stopa <- L1 - L0 L0 <- L1 if(stopa < 0) {stopa <- -stopa} if(iteration>60)break } abc<-L0 AIC<--2*abc+2*4 jj <- sigma0 - sigma[1] if(jj < 0) {jj <- 0} ll <- jj/sigma0 data <- sort(data) w1<-1/(12*m_sam) bmw <- matrix(0,m_sam,1); bmwsl <- matrix(0,m_sam,d4) for(i in 1:d4){ gg <- (data - m[i])/sqrt(sigma[i]) bmw[which(gg>=0)] <- pnorm(gg[gg>=0]) bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0])) bmwsl[,i] <- bmw*mix_pi[i] } P2 <- rowSums(bmwsl) nn <- dim(as.matrix(unique(P2)))[1] if(nn < m_sam){P2 <- P2+runif(m_sam)/1e4} dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2))) WW2 <- 1/(12*m_sam) + sum((P2 - (as.matrix(c(1:m_sam)) - 0.5)/m_sam)^2) u <- as.matrix(c(12*m_sam*((dd[1]/m_sam-0.5)^2),((45*m_sam)/4)*((dd[2]/m_sam-1/3)^2),180*m_sam*((dd[3]/m_sam-1/12)^2))) D <- as.numeric(ks.test(P2,"punif")[[1]][1]) tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,m_sam)))) tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4) output <- data.frame("2MG-A",round(abc,4),round(AIC,4),round(t(m),4),round(t(sigma),4),round(t(mix_pi),4),round(t(B71),4)," "," "," "," "," "," ",round(jj,4),round(ll*100,4),round(u[1],4),tt[1],round(u[2],4),tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5]) output<-as.matrix(output) OUTPUT<-list(output,mi) return(OUTPUT) } F3ModelFun[[9]] <-function(K1,logL,df,m_nf){ data <- as.matrix(as.numeric(as.numeric(df[,1]))) m_sam <- dim(data)[1]; d5 <- 6; m_esp <- 0.0001 mean0 <- mean(data);sigma0 <- var(data) a1 <- sqrt(sigma0) sigma <- matrix((sigma0/2),6,1) m <- as.matrix(c((mean0+3*a1),(mean0+2.4*a1),mean0, (mean0+1.7*a1),(mean0-0.7*a1),(mean0-3*a1))) mi <- as.matrix(c(0.0625,0.25,0.125,0.25,0.25,0.0625)) L0 <- sum(log(dmixnorm(data,m,sqrt(sigma),mi))) iteration <- 0; stopa <- 1000 WW <- matrix(0,6,m_sam); swx <- matrix(0,6,1); hh <- matrix(0,3,3); b_line <- matrix(0,3,1) g_a<-matrix(0,2,1); s0 <- matrix(0,2,1) while(stopa > m_esp && iteration <= 1000){ iteration <- iteration + 1 for(i in 1:d5) { WW[i,] <- mi[i]*dnorm(data,m[i],sqrt(sigma[i]))/dmixnorm(data,m,sqrt(sigma),mi) } mix_pi <- as.matrix(rowSums(WW)/m_sam) sumwx <- WW%*%data n0 <- m_sam*mix_pi n0[abs(n0)<0.000001] <- 0.000001 hh[1,1]<-sigma[1]/n0[1]+4.0*sigma[2]/n0[2]+sigma[3]/n0[3] hh[1,2]<--2.0*sigma[2]/n0[2]-2.0*sigma[3]/n0[3] hh[1,3]<-sigma[3]/n0[3] hh[2,2]<-sigma[2]/n0[2]+4.0*sigma[3]/n0[3]+sigma[5]/n0[5] hh[2,3]<--2.0*sigma[3]/n0[3]-2.0*sigma[5]/n0[5] hh[3,3]<-sigma[3]/n0[3]+4.0*sigma[5]/n0[5]+sigma[6]/n0[6] for(i in 2:3) { for(j in 1:(i-1)) { hh[i,j]<-hh[j,i] } } b_line[1]<-sumwx[1]/n0[1]-2.0*sumwx[2]/n0[2]+sumwx[3]/n0[3] b_line[2]<-sumwx[2]/n0[2]-2.0*sumwx[3]/n0[3]+sumwx[5]/n0[5] b_line[3]<-sumwx[3]/n0[3]-2.0*sumwx[5]/n0[5]+sumwx[6]/n0[6] B8<- solve(hh,b_line) m[1]<-(sumwx[1]-sigma[1]*B8[1])/n0[1] m[2]<-(sumwx[2]+sigma[2]*(2.0*B8[1]-B8[2]))/n0[2] m[3]<-(sumwx[3]+(sigma[3]/sigma[4])*sumwx[4]+sigma[3]*(-B8[1]+2.0*B8[2]-B8[3]))/(n0[3]+(sigma[3]/sigma[4])*n0[4]) m[4]<-m[3] m[5]<-(sumwx[5]-sigma[5]*(B8[2]-2.0*B8[3]))/n0[5] m[6]<-(sumwx[6]-sigma[6]*B8[3])/n0[6] hh81 <- matrix(c(1,1,1,1,1,2,1,0,-1,-2),5,2) B81<-solve(crossprod(hh81,hh81))%*%crossprod(hh81,m[-4]) g_a[1]<-0.5*B81[2]^2/m_nf g_a[2]<-B81[2]^2/m_nf for(i in 1:d5) { swx[i] <- WW[i,]%*%(data-m[i])^2 } s0[1]<-swx[1]+swx[6] s0[2]<-n0[1]+n0[6] aaa0<-sigma[1] n_iter<-0 aa6<-1000 while(aa6>0.0001){ n_iter<-n_iter+1 aa1<-sigma[1]/(sigma[1]+g_a[1]) aa2<-sigma[1]/(sigma[1]+g_a[2]) sigma[1]<-(s0[1]+aa1^2*(swx[2]+swx[4]+swx[5])+aa2^2*swx[3])/(s0[2]+aa1*(n0[2]+n0[4]+n0[5])+aa2*n0[3]) aa6<-abs(sigma[1]-aaa0) aaa0<-sigma[1] if(n_iter>20)break } sigma[6]<-sigma[1];sigma[2]<-sigma[1]+g_a[1];sigma[4]<-sigma[1]+g_a[1] sigma[5]<-sigma[1]+g_a[1];sigma[3]<-sigma[1]+g_a[2] L1 <- sum(log(dmixnorm(data,m,sqrt(sigma),mix_pi))) stopa <- L1 - L0 L0 <- L1 if(stopa < 0) {stopa <- -stopa} if(iteration>600)break } abc<-L0 AIC<--2*abc+2*3 jj <- sigma0 - sigma[1] if(jj < 0) {jj <- 0} ll <- jj/sigma0 data <- sort(data); w1<-1/(12*m_sam) bmw <- matrix(0,m_sam,1); bmwsl <- matrix(0,m_sam,d5) for(i in 1:d5){ gg <- (data - m[i])/sqrt(sigma[i]) bmw[which(gg>=0)] <- pnorm(gg[gg>=0]) bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0])) bmwsl[,i] <- bmw*mix_pi[i] } P2 <- rowSums(bmwsl) nn <- dim(as.matrix(unique(P2)))[1] if(nn < m_sam){P2 <- P2+runif(m_sam)/1e4} dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2))) WW2 <- 1/(12*m_sam) + sum((P2 - (as.matrix(c(1:m_sam)) - 0.5)/m_sam)^2) u <- as.matrix(c(12*m_sam*((dd[1]/m_sam-0.5)^2),((45*m_sam)/4)*((dd[2]/m_sam-1/3)^2),180*m_sam*((dd[3]/m_sam-1/12)^2))) D <- as.numeric(ks.test(P2,"punif")[[1]][1]) tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,m_sam)))) tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4) output <- data.frame("2MG-EA",round(abc,4),round(AIC,4),round(t(m),4)," "," "," ",round(t(sigma),4)," "," "," ",round(t(mix_pi),4)," "," "," ",round(t(B81),4)," "," "," "," "," "," "," ",round(jj,4),round(ll*100,4),round(u[1],4),tt[1],round(u[2],4),tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5]) output<-as.matrix(output) OUTPUT<-list(output,mi) return(OUTPUT) } F3ModelFun[[10]] <-function(K1,logL,df,m_nf){ data <- as.matrix(as.numeric(as.numeric(df[,1]))) m_sam <- dim(data)[1]; d4 <- 9; m_esp <- 0.0001 mean0 <- mean(data);sigma0 <- var(data) a1 <- sqrt(sigma0) sigma <- matrix((sigma0/2),9,1) m <- as.matrix(c((mean0+3.2*a1),(mean0+2.4*a1),(mean0+1.6*a1),(mean0+0.8*a1),mean0,(mean0-0.8*a1),(mean0-1.6*a1),(mean0-2.4*a1),(mean0-3.2*a1))) mi <- as.matrix(c(0.0625,0.125,0.0625,0.125,0.25,0.125,0.0625,0.125,0.0625)) L0 <- sum(log(dmixnorm(data,m,sqrt(sigma),mi))) iteration <- 0; stopa <- 1000 WW <- matrix(0,9,m_sam); swx <- matrix(0,9,1); hh <- matrix(0,6,6); b_line <- matrix(0,6,1) g_a<-matrix(0,3,1);s0 <- matrix(0,2,1) while(stopa > m_esp && iteration <= 1000){ iteration <- iteration + 1 for(i in 1:d4) { WW[i,] <- mi[i]*dnorm(data,m[i],sqrt(sigma[i]))/dmixnorm(data,m,sqrt(sigma),mi) } mix_pi <- as.matrix(rowSums(WW)/m_sam) sumwx <- WW%*%data n0 <- m_sam*mix_pi n0[abs(n0)<0.000001] <- 0.000001 hh[1,1]<-9.0*sigma[1]/n0[1]+16.0*sigma[2]/n0[2]+sigma[3]/n0[3] hh[1,2]<-0.0 hh[1,3]<--12.0*sigma[2]/n0[2] hh[1,4]<-3.0*sigma[1]/n0[1]+4.0*sigma[2]/n0[2] hh[1,5]<-3.0*sigma[1]/n0[1]-sigma[3]/n0[3] hh[1,6]<-0.0 hh[2,2]<-9.0*sigma[4]/n0[4]+16.0*sigma[5]/n0[5]+sigma[6]/n0[6] hh[2,3]<-16.0*sigma[5]/n0[5] hh[2,4]<-0.0 hh[2,5]<--3.0*sigma[4]/n0[4]+sigma[6]/n0[6] hh[2,6]<--4.0*sigma[5]/n0[5]-sigma[6]/n0[6] hh[3,3]<-9.0*sigma[2]/n0[2]+16.0*sigma[5]/n0[5]+sigma[8]/n0[8] hh[3,4]<--3.0*sigma[2]/n0[2]+sigma[8]/n0[8] hh[3,5]<-0 hh[3,6]<--4.0*sigma[5]/n0[5]-sigma[8]/n0[8] hh[4,4]<-sigma[1]/n0[1]+sigma[2]/n0[2]+sigma[7]/n0[7]+sigma[8]/n0[8] hh[4,5]<-sigma[1]/n0[1] hh[4,6]<--sigma[8]/n0[8] hh[5,5]<-sigma[1]/n0[1]+sigma[3]/n0[3]+sigma[4]/n0[4]+sigma[6]/n0[6] hh[5,6]<--sigma[6]/n0[6] hh[6,6]<-sigma[5]/n0[5]+sigma[6]/n0[6]+sigma[8]/n0[8]+sigma[9]/n0[9] for(i in 2:6) { for(j in 1:(i-1)) { hh[i,j]<-hh[j,i] } } b_line[1]<-3*sumwx[1]/n0[1]-4*sumwx[2]/n0[2]+sumwx[3]/n0[3] b_line[2]<-3*sumwx[4]/n0[4]-4*sumwx[5]/n0[5]+sumwx[6]/n0[6] b_line[3]<-3*sumwx[2]/n0[2]-4*sumwx[5]/n0[5]+sumwx[8]/n0[8] b_line[4]<-sumwx[1]/n0[1]-sumwx[2]/n0[2]-sumwx[7]/n0[7]+sumwx[8]/n0[8] b_line[5]<-sumwx[1]/n0[1]-sumwx[3]/n0[3]-sumwx[4]/n0[4]+sumwx[6]/n0[6] b_line[6]<-sumwx[5]/n0[5]-sumwx[6]/n0[6]-sumwx[8]/n0[8]+sumwx[9]/n0[9] B9<- solve(hh,b_line) m[1]<-(sumwx[1]-sigma[1]*(3.0*B9[1]+B9[4]+B9[5]))/n0[1] m[2]<-(sumwx[2]+sigma[2]*(4.0*B9[1]-3.0*B9[3]+B9[4]))/n0[2] m[3]<-(sumwx[3]-sigma[3]*(B9[1]-B9[5]))/n0[3] m[4]<-(sumwx[4]+sigma[4]*(-3.0*B9[2]+B9[5]))/n0[4] m[5]<-(sumwx[5]+sigma[5]*(4.0*B9[2]+4.0*B9[3]-B9[6]))/n0[5] m[6]<-(sumwx[6]+sigma[6]*(-B9[2]-B9[5]+B9[6]))/n0[6] m[7]<-(sumwx[7]+sigma[7]*B9[4])/n0[7] m[8]<-(sumwx[8]+sigma[8]*(-B9[3]-B9[4]+B9[6]))/n0[8] m[9]<-(sumwx[9]-sigma[9]*B9[6])/n0[9] hh91 <- matrix(c(1,1,1,1,1,1,1,1,1,1,1,1,0.5,0.5,0.5,-1,-1,-1,1,0.5,-1,1,0.5,-1,1,0.5,-1),9,3) B91<-solve(crossprod(hh91,hh91))%*%crossprod(hh91,m) g_a[1]<-0.75*B91[3]^2/m_nf g_a[2]<-0.75*B91[2]^2/m_nf g_a[3]<-g_a[1]+g_a[2] for(i in 1:d4) { swx[i] <- WW[i,]%*%(data-m[i])^2 } s0[1]<-swx[1]+swx[3]+swx[7]+swx[9] s0[2]<-n0[1]+n0[3]+n0[7]+n0[9] aaa0<-sigma[1] n_iter<-0 aa6<-1000 while(aa6>0.0001){ n_iter<-n_iter+1 aa1<-sigma[1]/(sigma[1]+g_a[1]) aa2<-sigma[1]/(sigma[1]+g_a[2]) aa3<-sigma[1]/(sigma[1]+g_a[3]) sigma[1]<-(s0[1]+aa1^2*(swx[2]+swx[8])+aa2^2*(swx[4]+swx[6])+aa3^2*swx[5])/(s0[2]+aa1*(n0[2]+n0[8])+aa2*(n0[4]+n0[6])+aa3*n0[5]) aa6<-abs(sigma[1]-aaa0) aaa0<-sigma[1] if(n_iter>20)break } sigma[3]<-sigma[1];sigma[7]<-sigma[1];sigma[9]<-sigma[1] sigma[2]<-sigma[1]+g_a[1];sigma[4]<-sigma[1]+g_a[2] sigma[5]<-sigma[1]+g_a[3];sigma[6]<-sigma[1]+g_a[2];sigma[8]<-sigma[1]+g_a[1] L1 <- sum(log(dmixnorm(data,m,sqrt(sigma),mix_pi))) stopa <- L1 - L0 L0 <- L1 if(stopa < 0) {stopa <- -stopa} } abc<-L0 AIC<--2*abc+2*4 jj <- sigma0 - sigma[1] if(jj < 0) {jj <- 0} ll <- jj/sigma0 data <- sort(data) w1<-1/(12*m_sam) bmw <- matrix(0,m_sam,1); bmwsl <- matrix(0,m_sam,d4) for(i in 1:d4){ gg <- (data - m[i])/sqrt(sigma[i]) bmw[which(gg>=0)] <- pnorm(gg[gg>=0]) bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0])) bmwsl[,i] <- bmw*mix_pi[i] } P2 <- rowSums(bmwsl) nn <- dim(as.matrix(unique(P2)))[1] if(nn < m_sam){P2 <- P2+runif(m_sam)/1e4} dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2))) WW2 <- 1/(12*m_sam) + sum((P2 - (as.matrix(c(1:m_sam)) - 0.5)/m_sam)^2) u <- as.matrix(c(12*m_sam*((dd[1]/m_sam-0.5)^2),((45*m_sam)/4)*((dd[2]/m_sam-1/3)^2),180*m_sam*((dd[3]/m_sam-1/12)^2))) D <- as.numeric(ks.test(P2,"punif")[[1]][1]) tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,m_sam)))) tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4) output <- data.frame("2MG-CD",round(abc,4),round(AIC,4),round(t(m),4),round(t(sigma),4),round(t(mix_pi),4),round(t(B91),4)," "," "," "," "," "," ",round(jj,4),round(ll*100,4),round(u[1],4),tt[1],round(u[2],4),tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5]) output<-as.matrix(output) OUTPUT<-list(output,mi) return(OUTPUT) } F3ModelFun[[11]] <-function(K1,logL,df,m_nf){ data <- as.matrix(as.numeric(as.numeric(df[,1]))) m_sam <- dim(data)[1]; d5 <- 6; m_esp <- 0.0001 mean0 <- mean(data);sigma0 <- var(data) a1 <- sqrt(sigma0/m_sam) sigma <- matrix((sigma0/2),6,1) m <- as.matrix(c((mean0+3*a1),(mean0+2.4*a1),(mean0+1.7*a1),mean0,(mean0-0.7*a1),(mean0-3*a1))) mi <- as.matrix(c(0.0625,0.25,0.25,0.125,0.25,0.0625)) L0 <- sum(log(dmixnorm(data,m,sqrt(sigma),mi))) iteration <- 0; stopa <- 1000 WW <- matrix(0,6,m_sam); swx <- matrix(0,6,1); hh <- matrix(0,4,4); b_line <- matrix(0,4,1) g_a<-matrix(0,2,1);s0 <- matrix(0,2,1) while(stopa > m_esp && iteration <= 1000){ iteration <- iteration + 1 for(i in 1:d5) { WW[i,] <- mi[i]*dnorm(data,m[i],sqrt(sigma[i]))/dmixnorm(data,m,sqrt(sigma),mi) } mix_pi <- as.matrix(rowSums(WW)/m_sam) sumwx <- WW%*%data n0 <- m_sam*mix_pi n0[abs(n0)<0.000001] <- 0.000001 hh[1,1]<-sigma[1]/n0[1]+4.0*sigma[2]/n0[2]+sigma[3]/n0[3] hh[1,2]<-sigma[1]/n0[1] hh[1,3]<--2.0*sigma[2]/n0[2]-sigma[3]/n0[3] hh[1,4]<-2.0*sigma[3]/n0[3] hh[2,2]<-sigma[1]/n0[1]+4.0*sigma[4]/n0[4]+sigma[6]/n0[6] hh[2,3]<-2.0*sigma[4]/n0[4] hh[2,4]<-6.0*sigma[4]/n0[4]+sigma[6]/n0[6] hh[3,3]<-sigma[2]/n0[2]+sigma[3]/n0[3]+sigma[4]/n0[4]+sigma[5]/n0[5] hh[3,4]<--2.0*sigma[3]/n0[3]+3.0*sigma[4]/n0[4] hh[4,4]<-4.0*sigma[3]/n0[3]+9.0*sigma[4]/n0[4]+sigma[6]/n0[6] for(i in 2:4) { for(j in 1:(i-1)) { hh[i,j]<-hh[j,i] } } b_line[1]<-sumwx[1]/n0[1]-2.0*sumwx[2]/n0[2]+sumwx[3]/n0[3] b_line[2]<-sumwx[1]/n0[1]-2.0*sumwx[4]/n0[4]+sumwx[6]/n0[6] b_line[3]<-sumwx[2]/n0[2]-sumwx[3]/n0[3]-sumwx[4]/n0[4]+sumwx[5]/n0[5] b_line[4]<-2.0*sumwx[3]/n0[3]-3.0*sumwx[4]/n0[4]+sumwx[6]/n0[6] B10<- solve(hh,b_line) m[1]<-(sumwx[1]-sigma[1]*(B10[1]+B10[2]))/n0[1] m[2]<-(sumwx[2]+sigma[2]*(2.0*B10[1]-B10[3]))/n0[2] m[3]<-(sumwx[3]-sigma[3]*(B10[1]-B10[3]+2.0*B10[4]))/n0[3] m[4]<-(sumwx[4]+sigma[4]*(2.0*B10[2]+B10[3]+3.0*B10[4]))/n0[4] m[5]<-(sumwx[5]-sigma[5]*B10[3])/n0[5] m[6]<-(sumwx[6]-sigma[6]*(B10[2]+B10[4]))/n0[6] hh101 <- matrix(c(1,1,1,1,1,1,2,1.5,1,0,-0.5,-2),6,2) B101<-solve(crossprod(hh101,hh101))%*%crossprod(hh101,m) g_a[1]<-0.75*B101[2]^2/m_nf g_a[2]<-1.5*B101[2]^2/m_nf for(i in 1:d5) { swx[i] <- WW[i,]%*%(data-m[i])^2 } s0[1]<-swx[1]+swx[4]+swx[6] s0[2]<-n0[1]+n0[4]+n0[6] aaa0<-sigma[1] n_iter<-0 aa6<-1000 while(aa6>0.0001){ n_iter<-n_iter+1 aa1<-sigma[1]/(sigma[1]+g_a[1]) aa2<-sigma[1]/(sigma[1]+g_a[2]) sigma[1]<-(s0[1]+aa1^2*(swx[2]+swx[5])+aa2^2*swx[3])/(s0[2]+aa1*(n0[2]+n0[5])+aa2*n0[3]) aa6<-abs(sigma[1]-aaa0) aaa0<-sigma[1] if(n_iter>20)break } sigma[4]<-sigma[1];sigma[6]<-sigma[1] sigma[2]<-sigma[1]+g_a[1];sigma[5]<-sigma[1]+g_a[1] sigma[3]<-sigma[1]+g_a[2] L1 <- sum(log(dmixnorm(data,m,sqrt(sigma),mix_pi))) stopa <- L1 - L0 L0 <- L1 if(stopa < 0) {stopa <- -stopa} } abc<-L0 AIC<--2*abc+2*3 jj <- sigma0 - sigma[1] if(jj < 0) {jj <- 0} ll <- jj/sigma0 data <- sort(data) w1<-1/(12*m_sam) bmw <- matrix(0,m_sam,1); bmwsl <- matrix(0,m_sam,d5) for(i in 1:d5){ gg <- (data - m[i])/sqrt(sigma[i]) bmw[which(gg>=0)] <- pnorm(gg[gg>=0]) bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0])) bmwsl[,i] <- bmw*mix_pi[i] } P2 <- rowSums(bmwsl) nn <- dim(as.matrix(unique(P2)))[1] if(nn < m_sam){P2 <- P2+runif(m_sam)/1e4} dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2))) WW2 <- 1/(12*m_sam) + sum((P2 - (as.matrix(c(1:m_sam)) - 0.5)/m_sam)^2) u <- as.matrix(c(12*m_sam*((dd[1]/m_sam-0.5)^2),((45*m_sam)/4)*((dd[2]/m_sam-1/3)^2),180*m_sam*((dd[3]/m_sam-1/12)^2))) D <- as.numeric(ks.test(P2,"punif")[[1]][1]) tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,m_sam)))) tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4) output <- data.frame("2MG-EAD",round(abc,4),round(AIC,4),round(t(m),4)," "," "," ",round(t(sigma),4)," "," "," ",round(t(mix_pi),4)," "," "," ",round(t(B101),4)," "," "," "," "," "," "," ",round(jj,4),round(ll*100,4),round(u[1],4),tt[1],round(u[2],4),tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5]) output<-as.matrix(output) OUTPUT<-list(output,mi) return(OUTPUT) } K1F23 <- function(x){ V0 <- 0 for(j in 0:2) {I1 <- 0;I2 <- 0 for(k in 0:8) {I1 <- I1 + (((4*j+1)^2/(32*x))^(-0.25+2*k))/(gamma(k+1)*gamma(0.75+k)) I2 <- I2 + ((4*j+1)^2/(32*x))^(0.25+2*k)/(gamma(k+1)*gamma(1.25+k))} V0 <- V0 + (gamma(j+0.5)*sqrt(4*j+1)/(gamma(0.5)*gamma(j+1)))*exp(-(4*j+1)^2/(16*x))*(I1-I2)} V <- (1/sqrt(2*x))*V0 return (1-V) } logLF23 <- function(nm,nng,mi,mn,s,d1) { sum2 <- sum(log(dmixnorm(d1,mn,sqrt(s),mi)));return (sum2) } if(model=="All models"){ cl.cores <- detectCores() if(cl.cores<=2){ cl.cores<-1 }else if(cl.cores>2){ if(cl.cores>10){ cl.cores<-10 }else { cl.cores <- detectCores()-1 } } cl <- makeCluster(cl.cores) registerDoParallel(cl) i<-NULL allresult=foreach(i=1:11,.combine = 'rbind')%dopar%{ requireNamespace("KScorrect") requireNamespace("kolmim") F3ModelFun[[i]](K1F23,logLF23,df,m_nf)[[1]] } stopCluster(cl) mi<-NULL }else{ allresultq<-switch(model,"0MG" = F3ModelFun[[1]](K1F23,logLF23,df,m_nf),"1MG-AD"=F3ModelFun[[2]](K1F23,logLF23,df,m_nf),"1MG-A"=F3ModelFun[[3]](K1F23,logLF23,df,m_nf), "1MG-EAD"=F3ModelFun[[4]](K1F23,logLF23,df,m_nf),"1MG-NCD"=F3ModelFun[[5]](K1F23,logLF23,df,m_nf),"2MG-ADI"=F3ModelFun[[6]](K1F23,logLF23,df,m_nf), "2MG-AD"=F3ModelFun[[7]](K1F23,logLF23,df,m_nf),"2MG-A"=F3ModelFun[[8]](K1F23,logLF23,df,m_nf),"2MG-EA"=F3ModelFun[[9]](K1F23,logLF23,df,m_nf), "2MG-CD"=F3ModelFun[[10]](K1F23,logLF23,df,m_nf),"2MG-EAD"=F3ModelFun[[11]](K1F23,logLF23,df,m_nf)) allresult<-allresultq[[1]] if(model!="0MG"){ mi<-allresultq[[2]] }else{ mi<-NULL } } colnames(allresult) <- F3colname out<-list(allresult,mi) return(out) }
one2one_fizz <- function(data, hrvar = "Organization", mingroup = 5, return = "plot"){ cleaned_data <- data %>% mutate(`Scheduled 1:1 meeting minutes with manager` = Meeting_hours_with_manager_1_on_1 * 60) create_fizz(data = cleaned_data, metric = "Scheduled 1:1 meeting minutes with manager", hrvar = hrvar, mingroup = mingroup, return = return) }
getSyncModel <- function(inp_sync, silent=TRUE, fine_tune=FALSE, max_iter=100, tmb_smartsearch=TRUE){ inp_sync$inp_params$tmb_smartsearch <- tmb_smartsearch inp_sync$inp_params$max_iter <- max_iter dat_tmb <- inp_sync$dat_tmb_sync params <- inp_sync$params_tmb_sync random <- inp_sync$random_tmb_sync inits <- inp_sync$inits_tmb_sync inp_params <- inp_sync$inp_params cat(paste0(Sys.time(), " \n")) cat(". Running optimization of the sync model. Please be patient - this can take a long time. \n") if(fine_tune){cat(".... fine tuning is enabled, but is getting deprecated in future version. Consider to use the function fineTuneSyncModel() instead. See ?fineTuneSyncModel for info. \n")} tictoc::tic("Fitting sync model: ") opt <- c() pl <- c() plsd <- c() obj <- c() tictoc::tic() obj <- c() opt <- c() report <- c() gc() obj <- TMB::MakeADFun(data = dat_tmb, parameters = params, random = random, DLL = "yaps", inner.control = list(maxit = max_iter), silent=silent) obj$fn(obj$par) if(!tmb_smartsearch){ TMB::newtonOption(obj, smartsearch=FALSE) } if(silent){ opt <- suppressWarnings(stats::nlminb(inits,obj$fn,obj$gr, lower=c(-10), upper=c(-2))) } else { opt <- stats::nlminb(inits,obj$fn,obj$gr, lower=c(-10), upper=c(-2)) } pl <- obj$env$parList() obj_val <- opt$objective cat(paste0(".. ", Sys.time()), " \n") cat(".... obj = ", obj_val, " \n") report <- obj$report() crazy_outliers <- which(abs(report$eps_toa)*1450 > 10000) fine_outliers <- which(abs(report$eps_toa)*1450 > 1000) if(length(crazy_outliers > 0)){ cat(".... some extreme outliers potentially affecting the model where identified \n Consider to run fineTuneSyncModel(sync_model, eps_threshold=10000). See ?fineTuneSyncModel for more info. \n") } else if(fine_tune){ cat(".... fine tuning is enabled, but is deprecated. Use the function fineTuneSyncModel() instead. See ?fineTuneSyncModel for info. \n") } tictoc::toc() jointrep <- try(TMB::sdreport(obj, getJointPrecision=TRUE), silent=silent) param_names <- rownames(summary(jointrep)) sds <- summary(jointrep)[,2] summ <- data.frame(param=param_names, sd=sds) plsd <- split(summ[,2], f=summ$param) pl$TRUE_H[,1] <- pl$TRUE_H[,1] + inp_params$Hx0 pl$TRUE_H[,2] <- pl$TRUE_H[,2] + inp_params$Hy0 eps_long <- getEpsLong(report, pl, inp_sync) offset_nas <- which(pl$OFFSET == 0) pl$OFFSET[offset_nas] <- NA pl$SLOPE1[offset_nas] <- NA pl$SLOPE2[offset_nas] <- NA cat("Sync model done \n") cat("Consider saving the sync model for later use - e.g. save(sync_model, file='path_to_sync_save'). \n") return(list(pl=pl, plsd=plsd, report=report, obj_val=obj_val, eps_long=eps_long, inp_synced=inp_sync)) }
AirP <- AirP %>% mutate( x1 = (loc == 1) + 0.5 * (loc == 3), x2 = (loc == 2) + 0.5 * (loc == 3)) model3 <- lm(pollution ~ -1 + x1 + x2, data = AirP) anova(model3, model)
binom.test(16, 50, 1/6)
context("Test compile.data") test_that("Compile genetic and non-genetic data",{ expect_output(str(compile.data(read.Genepop("testData/GenepopEx1.txt"), "testData/varDummy1.csv", skipQ = T)),"List of 5") expect_output(str(compile.data(read.Structure("testData/StructureEx1.txt"), "testData/varDummy2.csv", skipQ = T)),"List of 5") })
pred.int.norm.k.of.m.on.r.integrand <- function (v.weird, n.weird, df.weird = n.weird - 1, n.mean = 1, K.weird, delta.over.sigma, k.weird, m.weird, r.weird) { term.1 <- pT(q = sqrt(n.weird) * K.weird, df = df.weird, ncp = sqrt(n.weird/n.mean) * (qnorm(v.weird) + sqrt(n.mean) * delta.over.sigma)) term.2 <- r.weird * pbeta(q = v.weird, shape1 = k.weird, shape2 = m.weird + 1 - k.weird)^(r.weird - 1) term.3 <- (v.weird^(k.weird - 1) * (1 - v.weird)^(m.weird - k.weird))/beta(k.weird, m.weird + 1 - k.weird) term.1 * term.2 * term.3 }
knitr::opts_chunk$set(echo = TRUE) library(ALUES) y <- MarinduqueLT banana_suit <- suit("banana", terrain=y) banana_ovsuit <- overall_suit(banana_suit[["soil"]], method="average") knitr::include_graphics("../vignettes/img/scores1.jpg") knitr::include_graphics("../vignettes/img/classes1.jpg")
context("tas data") test_that("tas_pu", { expect_is(tas_pu, "SpatialPolygonsDataFrame") expect_true(rgeos::gIsValid(tas_pu)) expect_is(tas_pu$id, "integer") expect_is(tas_pu$cost, "numeric") expect_is(tas_pu$status, "integer") expect_is(tas_pu$locked_in, "logical") expect_is(tas_pu$locked_out, "logical") }) test_that("tas_features", { expect_is(tas_features, "RasterStack") })
proxfun <- function(graph, ...){ UseMethod("proxfun") } proxfun.igraph <- function(graph, method, v1 = NULL, v2 = v1, value =c("matrix", "edgelist", "graph"), ...){ if (igraph::is.directed(graph) | !igraph::is.connected(graph)) stop("graph has to be undirected and connected") value <- match.arg(value) method <- match_method(method) v1 <- check_vertices(graph, v1) v2 <- check_vertices(graph, v2) result <- do.call(method, list(graph = graph, v1 = v1, v2 = v2, ...)) rownames(result) <- v1 colnames(result) <- v2 result <- coerce_result(result, value, graph) result } proxfun.network <- function(graph, method, v1 = NULL, v2 = v1, value =c("matrix", "edgelist", "graph"), ...){ graph <- intergraph::asIgraph(graph) proxfun.igraph(graph, method = method , v1 = v1, v2 = v2, value = value, ...) }
shape_text <- function(strings, id = NULL, family = '', italic = FALSE, bold = FALSE, size = 12, res = 72, lineheight = 1, align = 'left', hjust = 0, vjust = 0, width = NA, tracking = 0, indent = 0, hanging = 0, space_before = 0, space_after = 0, path = NULL, index = 0) { n_strings = length(strings) if (is.null(id)) id <- seq_len(n_strings) id <- rep_len(id, n_strings) id <- match(id, unique(id)) if (anyNA(id)) { stop('id must be a vector of valid integers', call. = FALSE) } ido <- order(id) id <- id[ido] strings <- as.character(strings)[ido] if (is.null(path)) { if (all(c(length(family), length(italic), length(bold)) == 1)) { loc <- systemfonts::match_font(family, italic, bold) path <- loc$path index <- loc$index } else { family <- rep_len(family, n_strings) italic <- rep_len(italic, n_strings) bold <- rep_len(bold, n_strings) loc <- Map(systemfonts::match_font, family = family, italic = italic, bold = bold) path <- vapply(loc, `[[`, character(1L), 1, USE.NAMES = FALSE)[ido] index <- vapply(loc, `[[`, integer(1L), 2, USE.NAMES = FALSE)[ido] } } else { if (!all(c(length(path), length(index)) == 1)) { path <- rep_len(path, n_strings)[ido] index <- rep_len(index, n_strings)[ido] } } if (length(size) != 1) size <- rep_len(size, n_strings)[ido] if (length(res) != 1) res <- rep_len(res, n_strings)[ido] if (length(lineheight) != 1) lineheight <- rep_len(lineheight, n_strings)[ido] align <- match.arg(align, c('left', 'center', 'right'), TRUE) align <- match(align, c('left', 'center', 'right')) if (length(align) != 1) align <- rep_len(align, n_strings)[ido] if (length(hjust) != 1) hjust <- rep_len(hjust, n_strings)[ido] if (length(vjust) != 1) vjust <- rep_len(vjust, n_strings)[ido] if (length(width) != 1) width <- rep_len(width, n_strings)[ido] width[is.na(width)] <- -1 if (length(tracking) != 1) tracking <- rep_len(tracking, n_strings)[ido] if (length(indent) != 1) indent <- rep_len(indent, n_strings)[ido] if (length(hanging) != 1) hanging <- rep_len(hanging, n_strings)[ido] if (length(space_before) != 1) space_before <- rep_len(space_before, n_strings)[ido] if (length(space_after) != 1) space_after <- rep_len(space_after, n_strings)[ido] width <- width * res indent <- indent * res hanging <- hanging * res if (!all(file.exists(path))) stop("path must point to a valid file", call. = FALSE) shape <- get_string_shape_c( strings, id, path, as.integer(index), as.numeric(size), as.numeric(res), as.numeric(lineheight), as.integer(align) - 1L, as.numeric(hjust), as.numeric(vjust), as.numeric(width), as.numeric(tracking), as.numeric(indent), as.numeric(hanging), as.numeric(space_before), as.numeric(space_after) ) if (nrow(shape$shape) == 0) return(shape) shape$metrics$string <- vapply(split(strings, id), paste, character(1), collapse = '') shape$shape$string_id <- ido[shape$shape$string_id] shape$shape <- shape$shape[order(shape$shape$string_id), , drop = FALSE] shape$shape$x_offset <- shape$shape$x_offset * (72 / res) shape$shape$y_offset <- shape$shape$y_offset * (72 / res) shape$shape$x_midpoint <- shape$shape$x_midpoint * (72 / res) shape } text_width <- function(strings, family = '', italic = FALSE, bold = FALSE, size = 12, res = 72, include_bearing = TRUE, path = NULL, index = 0) { n_strings <- length(strings) if (is.null(path)) { if (all(c(length(family), length(italic), length(bold)) == 1)) { loc <- systemfonts::match_font(family, italic, bold) path <- loc$path index <- loc$index } else { family <- rep_len(family, n_strings) italic <- rep_len(italic, n_strings) bold <- rep_len(bold, n_strings) loc <- Map(systemfonts::match_font, family = family, italic = italic, bold = bold) path <- vapply(loc, `[[`, character(1L), 1, USE.NAMES = FALSE) index <- vapply(loc, `[[`, integer(1L), 2, USE.NAMES = FALSE) } } else { if (!all(c(length(path), length(index)) == 1)) { path <- rep_len(path, n_strings) index <- rep_len(index, n_strings) } } if (length(size) != 1) size <- rep_len(size, n_strings) if (length(res) != 1) res <- rep_len(res, n_strings) if (length(include_bearing) != 1) include_bearing <- rep_len(include_bearing, n_strings) if (!all(file.exists(path))) stop("path must point to a valid file", call. = FALSE) get_line_width_c( as.character(strings), path, as.integer(index), as.numeric(size), as.numeric(res), as.logical(include_bearing) ) }
predict_MS.rcalibration_MS<-function(object, testing_input, X_testing=as.list(rep(0,object@num_sources)), testing_output_weights=NULL, n_thinning=10, interval_est=NULL,interval_data=rep(F,length(testing_input)),math_model=NULL,...){ if(object@measurement_bias==T){ if(length(testing_input)!=(object@num_sources+1) ){ stop("please specified the testing input for the model discrepancy. \n") } }else{ if(length(testing_input)!=object@num_sources){ stop("The number of sources in the testing input should match the number of sources in the object. \n") } } for(i_source in 1:object@num_sources){ testing_input[[i_source]]=as.matrix(testing_input[[i_source]]) testing_input[[i_source]]=matrix(as.numeric(testing_input[[i_source]]), ncol = ncol(testing_input[[i_source]])) } if(object@measurement_bias==T){ testing_input[[i_source+1]]=as.matrix( testing_input[[i_source+1]]) testing_input[[i_source+1]]=matrix(as.numeric(testing_input[[i_source+1]]), ncol = ncol(testing_input[[i_source+1]])) } if(is.null(testing_output_weights)){ testing_output_weights=list() for(i_source in 1: object@num_sources){ testing_output_weights[[i_source]]=rep(1,dim(testing_input[[i_source]])[1]) } } if(object@measurement_bias==F){ predict_obj=predict_MS_no_measurement_bias(object,testing_input,X_testing,testing_output_weights,interval_est,interval_data,math_model,n_thinning) }else{ predict_obj=predict_MS_with_measurement_bias(object,testing_input,X_testing,testing_output_weights,interval_est,interval_data,math_model,n_thinning) } return(predict_obj) } predict_MS_no_measurement_bias<-function(object, testing_input, X_testing=as.list(rep(0,object@num_sources)), testing_output_weights=NULL, interval_est=NULL,interval_data=rep(F,length(testing_input)),math_model=NULL,n_thinning=10){ predictobj <- new("predictobj.rcalibration_MS") emulator=as.list(rep(NA,object@num_sources)) for(i_source in 1:object@num_sources){ if(object@simul_type[[i_source]]==0){ if(length(object@emulator_ppgasp[[i_source]]@p>0)){ emulator=object@emulator_ppgasp[[i_source]] }else{ emulator=object@emulator_rgasp[[i_source]] } } } for(i_source in 1:object@num_sources){ if(object@discrepancy_type[i_source]=='no-discrepancy'){ record_cm_pred=0 record_cm_pred_no_mean=0 c_prop=1/4 for(i_S in (1: SS)*n_thinning ){ if(i_S==floor(SS*n_thinning*c_prop)){ cat(c_prop*100, 'percent is completed \n') c_prop=c_prop+1/4 } theta=object@post_theta[i_S,] sigma_2_delta=object@post_individual_par[[i_source]][i_S,1] mean_cm_test=mathematical_model_eval(testing_input[[i_source]],theta,object@simul_type[i_source],object@emulator[[i_source]], object@emulator_type[i_source],object@loc_index_emulator[[i_source]], math_model[[i_source]]); mean_cm_test_no_mean=mean_cm_test if(object@have_trend[i_source]){ theta_m=as.matrix(object@post_individual_par[[i_source]][i_S,2:(1+object@q[i_source]) ]) mean_cm_test=mean_cm_test+X_testing[[i_source]]%*%theta_m } record_cm_pred=record_cm_pred+mean_cm_test record_cm_pred_no_mean=record_cm_pred_no_mean+mean_cm_test_no_mean if(!is.null(interval_est)){ qnorm_all=qnorm(interval_est[[i_source]]); for(i_int in 1:length(interval_est[[i_source]]) ){ record_interval[,i_int]=record_interval[,i_int]+mean_cm_test+qnorm_all[i_int]*sqrt(sigma_2_delta/testing_output_weights[[i_source]]) } } } record_cm_pred=record_cm_pred/SS record_cm_pred_no_mean=record_cm_pred_no_mean/SS predictobj@math_model_mean[[i_source]]=record_cm_pred predictobj@math_model_mean_no_trend[[i_source]]=record_cm_pred_no_mean if(!is.null(interval_est)){ record_interval=record_interval/SS predictobj@interval[[i_source]]=record_interval } cat('Source',i_source, 'is completed \n') }else{ if(!is.null(interval_est)){ c_star_record=rep(0,dim(testing_input[[i_source]])[1]) } N_testing=dim(testing_input[[i_source]])[1] r0=as.list(1:object@p_x[i_source]) for(i in 1:object@p_x[i_source]){ r0[[i]]=abs(outer(object@input[[i_source]][,i],testing_input[[i_source]][,i],'-')) } record_cm_pred=0 record_cm_pred_no_mean=0 record_pred_mean=0 SS=floor(dim(object@post_theta)[1]/n_thinning) c_prop=1/4 for(i_S in (1: SS)*n_thinning ){ if(i_S==floor(SS*n_thinning*c_prop)){ cat(c_prop*100, 'percent is completed \n') c_prop=c_prop+1/4 } theta=object@post_theta[i_S,] beta_delta=exp(object@post_individual_par[[i_source]][i_S,1:object@p_x[i_source]]) eta_delta=exp(object@post_individual_par[[i_source]][i_S,object@p_x[i_source]+1]) sigma_2_delta=object@post_individual_par[[i_source]][i_S,object@p_x[i_source]+2] if(object@have_trend[i_source]){ theta_m=as.matrix(object@post_individual_par[[i_source]][i_S,(object@p_x[i_source]+3):(object@p_x[i_source]+2+object@q[i_source])]) } mean_cm=mathematical_model_eval(object@input[[i_source]],theta,object@simul_type[[i_source]],object@emulator[[i_source]], object@emulator_type[i_source],object@loc_index_emulator[[i_source]],math_model[[i_source]]); output_minus_cm=object@output[[i_source]]- mean_cm if(object@have_trend[i_source]){ output_minus_cm=output_minus_cm-object@X[[i_source]]%*%theta_m } if(object@discrepancy_type[i_source]=="GaSP"){ L=Get_R_new( beta_delta, eta_delta, object@R0[[i_source]], object@kernel_type[[i_source]],object@alpha[[i_source]], 1/object@output_weights[[i_source]]) }else if(object@discrepancy_type[i_source]=="S-GaSP"){ L=Get_R_z_new( beta_delta, eta_delta, object@lambda_z[[i_source]][i_S], object@R0[[i_source]], object@kernel_type[[i_source]],object@alpha[[i_source]], 1/object@output_weights[[i_source]]) } R_inv_y=backsolve(t(L),forwardsolve(L,output_minus_cm )) if(object@discrepancy_type[i_source]=="S-GaSP"){ R_inv_y=Update_R_inv_y(R_inv_y,object@R0[[i_source]],beta_delta,object@kernel_type[i_source],object@alpha[[i_source]], object@lambda_z[[i_source]][i_S],object@num_obs[i_source]) } r=separable_kernel(r0,beta_delta,kernel_type=object@kernel_type[i_source],object@alpha[[i_source]]) rt_R_inv_y=t(r)%*%R_inv_y mean_cm_test=mathematical_model_eval(testing_input[[i_source]],theta,object@simul_type[i_source],object@emulator[[i_source]], object@emulator_type[i_source],object@loc_index_emulator[[i_source]],math_model[[i_source]]); mean_cm_test_no_mean=mean_cm_test if(object@have_trend[i_source]){ mean_cm_test=mean_cm_test+X_testing[[i_source]]%*%theta_m } pred_mean=mean_cm_test+rt_R_inv_y record_cm_pred=record_cm_pred+mean_cm_test record_cm_pred_no_mean=record_cm_pred_no_mean+mean_cm_test_no_mean record_pred_mean=record_pred_mean+pred_mean if(!is.null(interval_est)){ if(object@discrepancy_type[i_source]=="GaSP"){ R_tilde_inv_r=(backsolve(t(L),forwardsolve(L, r ))) for(i_testing in 1:N_testing){ c_star_record[i_testing]=1-r[,i_testing]%*%R_tilde_inv_r[,i_testing] } var_gasp_f=sigma_2_delta*c_star_record if(interval_data[i_source]==T){ var_gasp_f=var_gasp_f+sigma_2_delta*eta_delta/testing_output_weights[[i_source]] } qnorm_all=qnorm(interval_est[[i_source]]); for(i_int in 1:length(interval_est[[i_source]]) ){ record_interval[,i_int]=record_interval[,i_int]+pred_mean+qnorm_all[i_int]*sqrt(var_gasp_f) } }else if(object@discrepancy_type[i_source]=="S-GaSP"){ R=separable_kernel(object@R0[[i_source]], beta_delta, object@kernel_type[i_source], object@alpha[[i_source]]) R_tilde=R+1/object@lambda_z[[i_source]][i_S]*diag(object@num_obs[i_source]); L_R_tilde=Chol_Eigen(R_tilde) I_minus_R_R_tilde=diag(object@num_obs[i_source])-t(backsolve(t(L_R_tilde),forwardsolve(L_R_tilde,R ))) R_tilde_inv_r=(backsolve(t(L_R_tilde),forwardsolve(L_R_tilde, r ))) r_z=I_minus_R_R_tilde%*%r R_z_tilde_inv_r_z=(backsolve(t(L),forwardsolve(L, r_z ))) for(i_testing in 1:N_testing){ c_star_record[i_testing]=1-t(r[,i_testing])%*%R_tilde_inv_r[,i_testing]-r_z[,i_testing]%*%R_z_tilde_inv_r_z[,i_testing] } var_gasp_f=sigma_2_delta*c_star_record if(interval_data[i_source]==T){ var_gasp_f=var_gasp_f+sigma_2_delta*eta_delta/testing_output_weights[[i_source]] } qnorm_all=qnorm(interval_est[[i_source]]); for(i_int in 1:length(interval_est[[i_source]]) ){ record_interval[,i_int]=record_interval[,i_int]+pred_mean+qnorm_all[i_int]*sqrt(var_gasp_f) } } } } record_cm_pred=record_cm_pred/SS record_cm_pred_no_mean=record_cm_pred_no_mean/SS record_pred_mean=record_pred_mean/SS predictobj@math_model_mean[[i_source]]=record_cm_pred predictobj@math_model_mean_no_trend[[i_source]]=record_cm_pred_no_mean predictobj@mean[[i_source]]=record_pred_mean if(!is.null(interval_est)){ record_interval=record_interval/SS predictobj@interval[[i_source]]=record_interval } } } return(predictobj) } predict_MS_with_measurement_bias<-function(object, testing_input, X_testing=as.list(rep(0,object@num_sources)), testing_output_weights=NULL, interval_est=NULL,interval_data=rep(F,length(testing_input)), math_model=NULL, n_thinning=10){ emulator=as.list(rep(NA,object@num_sources)) for(i_source in 1:object@num_sources){ if(object@simul_type[[i_source]]==0){ if(length(object@emulator_ppgasp[[i_source]]@p>0)){ emulator=object@emulator_ppgasp[[i_source]] }else{ emulator=object@emulator_rgasp[[i_source]] } } } predictobj <- new("predictobj.rcalibration_MS") if(!is.null(interval_est)){ c_star_record_delta=rep(0,dim(testing_input[[object@num_sources+1]])[1]) } SS=dim(object@post_individual_par[[1]])[1]/n_thinning num_sources_1=object@num_sources+1 num_obs=object@num_obs[1] for(i_source in 1:object@num_sources){ record_cm_pred=0 record_cm_pred_no_mean=0 N_testing=dim(testing_input[[i_source]])[1] for(i_S in (1: SS)*n_thinning ){ theta=object@post_theta[i_S,] mean_cm_test=mathematical_model_eval(testing_input[[i_source]],theta,object@simul_type[i_source],object@emulator[[i_source]], object@emulator_type[i_source],object@loc_index_emulator[[i_source]],math_model[[i_source]]); mean_cm_test_no_mean=mean_cm_test if(object@have_trend[i_source]){ theta_m=as.matrix(object@post_individual_par[[i_source]][i_S,(object@p_x[i_source]+3):(object@p_x[i_source]+2+object@q[i_source])]) mean_cm_test=mean_cm_test+X_testing[[i_source]]%*%theta_m } record_cm_pred=record_cm_pred+mean_cm_test record_cm_pred_no_mean=record_cm_pred_no_mean+mean_cm_test_no_mean } record_cm_pred=record_cm_pred/SS record_cm_pred_no_mean=record_cm_pred_no_mean/SS predictobj@math_model_mean[[i_source]]=record_cm_pred predictobj@math_model_mean_no_trend[[i_source]]=record_cm_pred_no_mean } cat('Complete the mathematical model prediction \n') r0=list() for(i in 1:object@p_x[num_sources_1]){ r0[[i]]=abs(outer(object@input[[num_sources_1]][,i],testing_input[[num_sources_1]][,i],'-')) } delta_mean=0 var_delta=0; for(i_S in (1: SS) ){ par_cur=object@post_individual_par[[num_sources_1]][i_S,] sigma_2_delta=par_cur[object@p_x[num_sources_1]+1] L_delta=Get_R_new(exp(par_cur[1:object@p_x[num_sources_1]]),0, object@R0[[num_sources_1]],object@kernel_type[num_sources_1],object@alpha[[num_sources_1]], rep(1,num_obs)); Sigma_inv_delta=(backsolve(t(L_delta),forwardsolve(L_delta, object@post_delta[i_S,] ))) r=separable_kernel(r0,exp(par_cur[1:object@p_x[num_sources_1]]),kernel_type=object@kernel_type[num_sources_1],object@alpha[[num_sources_1]]) pred_mean= t(r)%*%Sigma_inv_delta delta_mean=delta_mean+ pred_mean if(!is.null(interval_est)){ R_tilde_inv_r=(backsolve(t(L_delta),forwardsolve(L_delta, r ))) for(i_testing in 1:N_testing){ c_star_record_delta[i_testing]=1-r[,i_testing]%*%R_tilde_inv_r[,i_testing] } var_delta=var_delta+sigma_2_delta*c_star_record_delta } } delta_mean=delta_mean/SS var_delta=var_delta/SS predictobj@delta_mean=delta_mean cat('Complete the model discrepancy \n') for(i_source in 1: object@num_sources){ measurement_bias_no_mean=0 for(i in 1:object@p_x[i_source]){ r0[[i]]=abs(outer(object@input[[i_source]][,i],testing_input[[i_source]][,i],'-')) } N_testing=dim(testing_input[[i_source]])[1] if(!is.null(interval_est)){ record_interval=matrix(0,dim(testing_input[[i_source]])[1],length(interval_est[[i_source]])); c_star_record=rep(0,dim(testing_input[[i_source]])[1]) } var_meaurement=0; for(i_S in 1: SS ){ theta=object@post_theta[i_S,] beta_delta=exp(object@post_individual_par[[i_source]][i_S,1:object@p_x[i_source]]) eta_delta=exp(object@post_individual_par[[i_source]][i_S,object@p_x[i_source]+1]) sigma_2_delta=object@post_individual_par[[i_source]][i_S,object@p_x[i_source]+2] mean_cm=mathematical_model_eval(object@input[[i_source]],theta,object@simul_type[[i_source]],object@emulator[[i_source]], object@emulator_type[i_source],object@loc_index_emulator[[i_source]],math_model[[i_source]]); output_minus_cm=object@output[[i_source]]- mean_cm if(object@have_trend[i_source]){ theta_m=as.matrix(object@post_individual_par[[i_source]][i_S,(object@p_x[i_source]+3):(object@p_x[i_source]+2+object@q[i_source])]) output_minus_cm=output_minus_cm-object@X[[i_source]]%*%theta_m } output_minus_cm_minus_delta=output_minus_cm-object@post_delta[i_S,] if(object@discrepancy_type[i_source]=="GaSP"){ L=Get_R_new( beta_delta, eta_delta, object@R0[[i_source]], object@kernel_type[[i_source]],object@alpha[[i_source]], 1/object@output_weights[[i_source]]) }else if(object@discrepancy_type[i_source]=="S-GaSP"){ L=Get_R_z_new( beta_delta, eta_delta, object@lambda_z[[i_source]][i_S], object@R0[[i_source]], object@kernel_type[[i_source]],object@alpha[[i_source]], 1/object@output_weights[[i_source]]) } R_inv_y=backsolve(t(L),forwardsolve(L,output_minus_cm_minus_delta )) if(object@discrepancy_type[i_source]=="S-GaSP"){ R_inv_y=Update_R_inv_y(R_inv_y,object@R0[[i_source]],beta_delta,object@kernel_type[i_source],object@alpha[[i_source]], object@lambda_z[[i_source]][i_S],object@num_obs[i_source]) } r=separable_kernel(r0,beta_delta,kernel_type=object@kernel_type[i_source],object@alpha[[i_source]]) rt_R_inv_y=t(r)%*%R_inv_y measurement_bias_no_mean=measurement_bias_no_mean+rt_R_inv_y if(!is.null(interval_est)){ if(object@discrepancy_type[i_source]=="GaSP"){ R_tilde_inv_r=(backsolve(t(L),forwardsolve(L, r ))) for(i_testing in 1:N_testing){ c_star_record[i_testing]=1-r[,i_testing]%*%R_tilde_inv_r[,i_testing] } var_meaurement=sigma_2_delta*c_star_record if(interval_data[i_source]==T){ var_meaurement=var_meaurement+sigma_2_delta*eta_delta/testing_output_weights[[i_source]] } }else if(object@discrepancy_type[i_source]=="S-GaSP"){ R=separable_kernel(object@R0[[i_source]], beta_delta, object@kernel_type[i_source], object@alpha[[i_source]]) R_tilde=R+1/object@lambda_z[[i_source]][i_S]*diag(object@num_obs[i_source]); L_R_tilde=Chol_Eigen(R_tilde) I_minus_R_R_tilde=diag(object@num_obs[i_source])-t(backsolve(t(L_R_tilde),forwardsolve(L_R_tilde,R ))) R_tilde_inv_r=(backsolve(t(L_R_tilde),forwardsolve(L_R_tilde, r ))) r_z=I_minus_R_R_tilde%*%r R_z_tilde_inv_r_z=(backsolve(t(L),forwardsolve(L, r_z ))) for(i_testing in 1:N_testing){ c_star_record[i_testing]=1-t(r[,i_testing])%*%R_tilde_inv_r[,i_testing]-r_z[,i_testing]%*%R_z_tilde_inv_r_z[,i_testing] } var_meaurement=sigma_2_delta*c_star_record if(interval_data[i_source]==T){ var_meaurement=var_meaurement+sigma_2_delta*eta_delta/testing_output_weights[[i_source]] } } } } measurement_bias_no_mean=measurement_bias_no_mean/SS var_meaurement=var_meaurement/SS predictobj@measurement_bias_mean[[i_source]]=measurement_bias_no_mean if(!is.null(interval_est)){ qnorm_all=qnorm(interval_est[[i_source]]); for(i_int in 1:length(interval_est[[i_source]]) ){ record_interval[,i_int]=record_interval[,i_int]+measurement_bias_no_mean+qnorm_all[i_int]*sqrt(var_meaurement+var_delta) } predictobj@interval[[i_source]]=record_interval } predictobj@mean[[i_source]]=predictobj@delta_mean+predictobj@measurement_bias_mean[[i_source]]+predictobj@math_model_mean[[i_source]] } return(predictobj) }
a() b
"xsy" <- function(x,y,s) { if (missing(x)) messagena("x") if (missing(y)) messagena("y") if (missing(s)) messagena("s") n <- length(x) nn <- length(s) result <- single(1) f.res <- .Fortran("xsyz", x=to.single(x), y=to.single(y), s=to.single(s), n=to.integer(n), nn=to.integer(nn), result=to.single(result)) list(result=f.res$result) }
sgcca <- function (A, C = 1-diag(length(A)), c1 = rep(1, length(A)), ncomp = rep(1, length(A)), scheme = "centroid", scale = TRUE, init = "svd", bias = TRUE, tol = .Machine$double.eps, verbose = FALSE){ ndefl <- ncomp-1 N <- max(ndefl) J <- length(A) pjs <- sapply(A,NCOL) nb_ind <- NROW(A[[1]]) AVE_X = list() AVE_outer <- rep(NA,max(ncomp)) if ( any(ncomp < 1) ) stop("One must compute at least one component per block!") if (any(ncomp-pjs > 0)) stop("For each block, choose a number of components smaller than the number of variables!") if (is.vector(c1)){ if (any(c1 < 1/sqrt(pjs) | c1 > 1 )) stop("L1 constraints (c1) must vary between 1/sqrt(p_j) and 1.") } if (is.matrix(c1)){ if (any(apply(c1, 1, function(x) any(x < 1/sqrt(pjs))))) stop("L1 constraints (c1) must vary between 1/sqrt(p_j) and 1.") } if (mode(scheme) != "function") { if ((scheme != "horst" ) & (scheme != "factorial") & (scheme != "centroid")) { stop("Choose one of the three following schemes: horst, centroid, factorial or design the g function") } if (verbose) cat("Computation of the SGCCA block components based on the", scheme, "scheme \n") } if (mode(scheme) == "function" & verbose) { cat("Computation of the SGCCA block components based on the g scheme \n") } if (scale == TRUE) { A = lapply(A, function(x) scale2(x, bias = bias)) A = lapply(A, function(x) x/sqrt(NCOL(x))) } ndefl <- ncomp-1 N <- max(ndefl) J <- length(A) pjs <- sapply(A,NCOL) nb_ind <- NROW(A[[1]]) AVE_X = list() AVE_outer <- rep(NA,max(ncomp)) if (N == 0) { result <- sgccak(A, C, c1, scheme, init = init, bias = bias, tol = tol, verbose = verbose) Y <- NULL for (b in 1:J) Y[[b]] <- result$Y[,b, drop = FALSE] for (j in 1:J) AVE_X[[j]] = mean(cor(A[[j]], Y[[j]])^2) AVE_outer <- sum(pjs * unlist(AVE_X))/sum(pjs) AVE <- list(AVE_X = AVE_X, AVE_outer = AVE_outer, AVE_inner = result$AVE_inner) a <- lapply(result$a, cbind) for (b in 1:J) { rownames(a[[b]]) = colnames(A[[b]]) rownames(Y[[b]]) = rownames(A[[b]]) colnames(Y[[b]]) = "comp1" } out <- list(Y=Y, a=a, astar=a, C=C, scheme=scheme, c1=c1, ncomp=ncomp, crit = result$crit[length(result$crit)], AVE = AVE) class(out) <- "sgcca" return(out) } Y <- NULL R <- A P <- a <- astar <- NULL crit <- list() AVE_inner <- rep(NA,max(ncomp)) for (b in 1:J) P[[b]] <- a[[b]] <- astar[[b]] <- matrix(NA,pjs[[b]],N+1) for (b in 1:J) Y[[b]] <- matrix(NA,nb_ind,N+1) for (n in 1:N) { if (verbose) cat(paste0("Computation of the SGCCA block components if(is.vector(c1)){ sgcca.result <- sgccak(R, C, c1 = c1 , scheme=scheme, init = init, bias = bias, tol = tol, verbose=verbose) } else{ sgcca.result <- sgccak(R, C, c1 = c1[n, ] , scheme=scheme, init = init, bias = bias, tol = tol, verbose=verbose) } AVE_inner[n] <- sgcca.result$AVE_inner crit[[n]] <- sgcca.result$crit for (b in 1:J) Y[[b]][,n] <- sgcca.result$Y[ ,b] for (q in which(n <ndefl)) if(sum(sgcca.result$a[[q]]!=0) <= 1) warning(sprintf("Deflation failed because only one variable was selected for block defla.result <- defl.select(sgcca.result$Y, R, ndefl, n, nbloc = J) R <- defla.result$resdefl for (b in 1:J) { P[[b]][,n] <- defla.result$pdefl[[b]] a[[b]][,n] <- sgcca.result$a[[b]] } if (n==1) { for (b in 1:J) astar[[b]][,n] <- sgcca.result$a[[b]] } else { for (b in 1:J) astar[[b]][,n] <- sgcca.result$a[[b]] - astar[[b]][,(1:n-1),drop=F] %*% drop( t(a[[b]][,n]) %*% P[[b]][,1:(n-1),drop=F] ) } } if (verbose) cat(paste0("Computation of the SGCCA block components if(is.vector(c1)) { sgcca.result <- sgccak(R, C, c1 = c1, scheme=scheme, init = init, bias = bias, tol = tol, verbose=verbose) } else{ sgcca.result <- sgccak(R, C, c1 = c1[N+1, ], scheme=scheme, init = init, bias = bias, tol = tol, verbose=verbose) } AVE_inner[max(ncomp)] <- sgcca.result$AVE_inner crit[[N+1]] <- sgcca.result$crit for (b in 1:J) { Y[[b]][,N+1] <- sgcca.result$Y[, b] a[[b]][,N+1] <- sgcca.result$a[[b]] astar[[b]][,N+1] <- sgcca.result$a[[b]] - astar[[b]][,(1:N),drop=F] %*% drop( t(a[[b]][,(N+1)]) %*% P[[b]][,1:(N),drop=F] ) rownames(a[[b]]) = rownames(astar[[b]]) = colnames(A[[b]]) rownames(Y[[b]]) = rownames(A[[b]]) colnames(Y[[b]]) = paste0("comp", 1:max(ncomp)) } shave.matlist <- function(mat_list, nb_cols) mapply(function(m, nbcomp) m[, 1:nbcomp, drop = FALSE], mat_list, nb_cols, SIMPLIFY=FALSE) shave.veclist <- function(vec_list, nb_elts) mapply(function(m, nbcomp) m[1:nbcomp], vec_list, nb_elts, SIMPLIFY=FALSE) for (j in 1:J) AVE_X[[j]] = apply(cor(A[[j]], Y[[j]])^2, 2, mean) outer = matrix(unlist(AVE_X), nrow = max(ncomp)) for (j in 1:max(ncomp)) AVE_outer[j] <- sum(pjs * outer[j, ])/sum(pjs) Y = shave.matlist(Y, ncomp) AVE_X = shave.veclist(AVE_X, ncomp) AVE <- list(AVE_X = AVE_X, AVE_outer = AVE_outer, AVE_inner = AVE_inner) out <- list(Y = shave.matlist(Y, ncomp), a = shave.matlist(a, ncomp), astar = shave.matlist(astar, ncomp), C = C, c1 = c1, scheme = scheme, ncomp = ncomp, crit = crit, AVE = AVE ) class(out) <- "sgcca" return(out) }
.packageName <- 'mousetrack' sampenc <- function(y, M, r){ n = length(y) run = lastrun = vector(mode = "numeric", length = n) A = B = vector(mode = "numeric", length = M) for (i in 1:(n-1)){ nj = n-i y1 = y[i] for (jj in 1:nj){ j = jj+i if (abs(y[j] - y1) < r){ run[jj] = lastrun[jj] + 1 M1 = min(M, run[jj]) for (m in 1:M1){ A[m] = A[m] + 1 if (j < n){ B[m] = B[m] + 1 } } } else { run[jj] = 0 } } for (j in 1:nj){ lastrun[j] = run[j] } } N = n*(n-1)/2; B = c(N, B[1:(M-1)]) p = A/B; e = -log(p); return ( cbind(e, A, B) ) }
`sinlogr` <- function (t) { y<-sinlog(t) y <- c(y, rev(y)) n <- length(y) y[seq(from=1, to=n, by=2)] }
dLRT <- function(MPRMobj){ eprm <- EPRM_red(MPRMobj$data) emp_Chi2 <- -2*(eprm$logLikelihood-MPRMobj$logLikelihood) df <- length(MPRMobj$estpar)-length(eprm$estpar) pvalue <- 1-pchisq(emp_Chi2,df) res <- list(emp_Chi2=emp_Chi2, df=df, pvalue=pvalue) class(res) <- "dLR" res }
setMethod( f="missingValues", signature=c("ClusterMixedDataModel"), function(x) { nbData <- length(x@lcomponent) res <- vector("list", nbData) if(nbData>0) { for (l in 1:nbData) { res[[l]] <- cbind(x@lcomponent[[l]]@missing, (x@lcomponent[[l]]@data)[x@lcomponent[[l]]@missing]); colnames(res[[l]])[3] <- "value"; } } return(res) } ) setMethod( f="missingValues", signature=c("ClusterDiagGaussianComponent"), function(x) { res = cbind(x@missing, x@data[x@missing]); colnames(res)[3] <- "value"; nmiss <- nrow(x@missing) if (nmiss > 0) { rownames(res) <- 1:nmiss} return(res) } ) setMethod( f="missingValues", signature=c("ClusterDiagGaussian"), function(x) { return(missingValues(x@component));} ) setMethod( f="missingValues", signature=c("ClusterGammaComponent"), function(x) { res = cbind(x@missing, x@data[x@missing]); colnames(res)[3] <- "value"; nmiss <- nrow(x@missing) if (nmiss > 0) { rownames(res) <- 1:nmiss} return(res) } ) setMethod( f="missingValues", signature=c("ClusterGamma"), function(x) { return(missingValues(x@component));} ) setMethod( f="missingValues", signature=c("ClusterCategoricalComponent"), function(x) { res = cbind(x@missing, x@data[x@missing]); colnames(res)[3] <- "value"; nmiss <- nrow(x@missing) if (nmiss > 0) { rownames(res) <- 1:nmiss} return(res) } ) setMethod( f="missingValues", signature=c("ClusterCategorical"), function(x) { return(missingValues(x@component));} ) setMethod( f="missingValues", signature=c("ClusterPoissonComponent"), function(x) { res = cbind(x@missing, x@data[x@missing]); colnames(res)[3] <- "value"; nmiss <- nrow(x@missing) if (nmiss > 0) { rownames(res) <- 1:nmiss} return(res) } ) setMethod( f="missingValues", signature=c("ClusterPoisson"), function(x) { return(missingValues(x@component));} ) setMethod( f="missingValues", signature=c("ClusterPredict"), function(x) { res = cbind(x@missing, x@data[x@missing]) colnames(res)[3] <- "value" nmiss <- nrow(x@missing) if (nmiss > 0) { rownames(res) <- 1:nmiss} return(res) } ) setMethod( f="missingValues", signature=c("ClusterPredictMixedData"), function(x) { nbData <- length(x@ldata) res <- vector("list", nbData) if(nbData>0) { for (l in 1:nbData) { res[[l]] <- cbind(x@lmissing[[l]], (x@ldata[[l]])[x@lmissing[[l]]]); colnames(res[[l]])[3] <- "value"; } } return(res) } ) setMethod( f="missingValues", signature=c("KmmComponent"), function(x) { return(NULL)} ) setMethod( f="missingValues", signature=c("KmmModel"), function(x) { return(NULL)} )
context("Parameteric Bootstrap Sampling") set.seed(1234) n <- 10 p <- 30 Niter <- 10 group <- rep(1:(p/10), each = 10) Weights <- rep(1, p/10) X <- matrix(rnorm(n*p), n) Y <- X%*%rep(1,p) + rnorm(n) test_that("lasso", { expect_error(PBsampler(X=X, PE_1=rep(0,p),sig2_1=1, lbd_1 = .5, weights=rep(1,p), group=1:p, niter=10, type="lasso", PEtype="coeff", parallel=TRUE), NA) }) test_that("PE length under two types, \"mu\" and \"coeff\"", { expect_error(PBsampler(X = X, PE_1 = rep(0, p-1), sig2_1 = 1, lbd_1 = .5, weights = Weights, group = group, niter = Niter, type = "grlasso", PEtype = "coeff", parallel = FALSE), "PE must have a same length") expect_error(PBsampler(X = X, PE_1 = rep(0, p), sig2_1 = 1, lbd_1 = .5, weights = Weights, group = group, niter = Niter, type = "grlasso", PEtype = "coeff", parallel = FALSE) , NA) expect_error(PBsampler(X = X, PE_1 = rep(0, p), sig2_1 = 1, lbd_1 = 1, weights = Weights, group = group, niter = Niter, type = "sgrlasso", PEtype = "coeff", parallel = FALSE) , NA) expect_error(PBsampler(X = X, PE_1 = rep(0, p), sig2_1 = 1, lbd_1 = 1, niter = Niter, type = "slasso", PEtype = "coeff", parallel = FALSE) , NA) expect_error(PBsampler(X = X, PE_1 = rep(0, n-1), sig2_1 = 1, lbd_1 = .5, weights = Weights, group = group, niter = Niter, type = "grlasso", PEtype = "mu", parallel = FALSE), "PE must have a same length") expect_error(PBsampler(X = X, PE_1 = rep(0, n), sig2_1 = 1, lbd_1 = .5, weights = Weights, group = group, niter = Niter, type = "grlasso", PEtype = "mu", parallel = FALSE) , NA) expect_error(PBsampler(X = X, PE_1 = rep(0, n), sig2_1 = 1, lbd_1 = .5, PE_2 = rep(0, n), sig2_2 = 1, lbd_2 = .5, weights = Weights, group = group, niter = Niter, type = "grlasso", PEtype = "mu", parallel = FALSE) , NA) }) test_that("missing parameter", { expect_error(PBsampler(X = X, PE_1 = rep(0, p), sig2_1 = 1, weights = Weights, group = group, niter = Niter, type = "grlasso", PEtype = "coeff", parallel = FALSE) , "provide all the parameters") expect_error(PBsampler(X = X, PE_1 = rep(0, n), sig2_1 = 1, lbd_1 = .5, PE_2 = rep(0, n), sig2_2 = 1, weights = Weights, group = group, niter = Niter, type = "grlasso", PEtype = "mu", parallel = FALSE) , "provide all the parameters") }) test_that("Improper value of parameter, sig2/lbd/weights", { expect_error(PBsampler(X = X, PE_1 = rep(0, p), sig2_1 = -1, lbd_1 = .5, weights = Weights, group = group, niter = Niter, type = "grlasso", parallel = FALSE), "sig2 should be positive") expect_error(PBsampler(X = X, PE_1 = rep(0, p), sig2_1 = 1, lbd_1 = -1, weights = Weights, group = group, niter = Niter, type = "grlasso", parallel = FALSE), "lbd should be non-negative") expect_error(PBsampler(X = X, PE_1 = rep(0, p), sig2_1 = c(1,2), lbd_1 = .5, weights = Weights, group = group, niter = Niter, type = "grlasso", parallel = FALSE), "sig2/lbd should be a scalar") expect_error(PBsampler(X = X, PE_1 = rep(0, p), sig2_1 = 1, lbd_1 = .5, weights = c(-1, rep(1, p / 10 - 1)), group = group, niter = Niter, type = "grlasso", parallel = FALSE), "weights should be positive") }) test_that("group argument",{ Group <- rep(1:(p/10), each = 10); Weights <- rep(1, p/10) Group1 <- rep(1,p); Weights1 <- 1 Group2 <- rep(1,p-1); Weights2 <- 1 Group3 <- rep(c(1,2,4),each=10); Weights3 <- rep(1, 3) Group4 <- rep(-1,p); Weights4 <- 1 expect_error(PBsampler(X = X, PE_1 = rep(0, p), sig2_1 = 1, lbd_1 = .5, weights = Weights, group = Group, niter = Niter, type = "grlasso", PEtype = "coeff", parallel = FALSE) , NA) expect_error(PBsampler(X = X, PE_1 = rep(0, p), sig2_1 = 1, lbd_1 = .5, weights = Weights1, group = Group1, niter = Niter, type = "grlasso", PEtype = "coeff", parallel = FALSE) , NA) expect_error(PBsampler(X = X, PE_1 = rep(0, p), sig2_1 = 1, lbd_1 = .5, weights = Weights2, group = Group2, niter = Niter, type = "grlasso", PEtype = "coeff", parallel = FALSE) , "group must have a same length with the number of X columns") expect_error(PBsampler(X = X, PE_1 = rep(0, p), sig2_1 = 1, lbd_1 = .5, weights = Weights3, group = Group3, niter = Niter, type = "grlasso", PEtype = "coeff", parallel = FALSE) , "group index has to be a consecutive integer starting from 1" ) expect_error(PBsampler(X = X, PE_1 = rep(0, p), sig2_1 = 1, lbd_1 = .5, weights = Weights4, group = Group4, niter = Niter, type = "grlasso", PEtype = "coeff", parallel = FALSE) , "group index has to be a consecutive integer starting from 1" ) }) set.seed(1234) n <- 40 p <- 50 Niter <- 10 group <- rep(1:(p/10), each = 10) weights <- rep(1, p/10) parallel <- (.Platform$OS.type != "windows") X <- matrix(rnorm(n*p), n) Y <- X %*% c(rep(1,5),rep(0,p-5)) + rnorm(n) test_that("confidence interval", { object <- PBsampler(X = X,PE_1 = c(1,1,rep(0,p-2)),sig2_1 = 1,lbd_1 = .5, weights = rep(1,p), group = 1:p, niter = 100,type="lasso", PEtype = "coeff", parallel=parallel) expect_error(PB.CI(object = object, alpha = .05, method = "debias", parallel=parallel) , NA) expect_error(PB.CI(object = object, alpha = .05, method = "none", parallel=parallel) , NA) object <- PBsampler(X = X,PE_1 = c(1,1,rep(0,p-2)),sig2_1 = 1,lbd_1 = 1, niter=100,type="slasso",parallel=parallel) expect_error(PB.CI(object = object, alpha = .05, method = "debias", parallel=parallel) , NA) expect_error(PB.CI(object = object, alpha = .05, method = "none") , NA) object <- PBsampler(X = X,PE_1 = c(1,1,rep(0,p-2)),sig2_1 = 1,lbd_1 = .5, group=group,niter=100,type="grlasso",parallel=parallel) expect_error(PB.CI(object = object, alpha = .05, method = "debias", parallel=parallel) , NA) expect_error(PB.CI(object = object, alpha = .05, method = "none") , NA) object <- PBsampler(X = X,PE_1 = c(1,1,rep(0,p-2)),sig2_1 = 1,lbd_1 = 1, group=group,niter=100,type="sgrlasso",parallel=parallel) expect_error(PB.CI(object = object, alpha = .05, method = "debias", parallel=parallel) , NA) expect_error(PB.CI(object = object, alpha = .05, method = "none") , NA) }) if(.Platform$OS.type != "windows"){ test_that("parallel", { expect_warning(PBsampler(X = X, PE_1 = rep(0, p), sig2_1 = 1, lbd_1 = .5, weights = weights, group = group, niter = Niter, type = "grlasso", PEtype = "coeff", parallel = TRUE, ncores = 1) , "set ncores to 2") expect_warning(PBsampler(X = X, PE_1 = rep(0, p), sig2_1 = 1, lbd_1 = .5, weights = weights, group = group, niter = Niter, type = "grlasso", PEtype = "coeff", parallel = TRUE, ncores = 2) , NA) }) } else { test_that("parallel", { expect_warning(PBsampler(X = X, PE_1 = rep(0, p), sig2_1 = 1, lbd_1 = .5, weights = weights, group = group, niter = Niter, type = "grlasso", PEtype = "coeff", parallel = TRUE, ncores = 1) , "Under Windows platform") expect_warning(PBsampler(X = X, PE_1 = rep(0, p), sig2_1 = 1, lbd_1 = .5, weights = weights, group = group, niter = Niter, type = "grlasso", PEtype = "coeff", parallel = TRUE, ncores = 2) , "Under Windows platform") }) }
library(survival) test1 <- list(time=c(4,3,1,1,2,2,3), status=c(1,1,1,0,1,1,0), x=c(0,2,1,1,1,0,0), sex=c(0,0,0,0,1,1,1)) fit <- coxph(Surv(time, status) ~ x + strata(sex), test1) out <- BF(fit, "x > .5") test_that("BF.coxph returns correct results,", { expect_true(out$PHP_confirmatory[1] > .5 & out$PHP_confirmatory[2] < .5) }) test2 <- list(start=c(1,2,5,2,1,7,3,4,8,8), stop=c(2,3,6,7,8,9,9,9,14,17), event=c(1,1,1,1,1,1,1,0,0,0), pred=c(1,0,0,1,0,1,1,1,0,0)) fit <- coxph(Surv(start, stop, event) ~ pred, test2) out <- BF(fit, hypothesis = "pred > .5; pred = .5") test_that("BF.coxph returns correct results,", { expect_true(out$PHP_confirmatory[1] < .5 & out$PHP_confirmatory[2] > .5) }) out <- BF(fit, hypothesis = "pred > .5; pred = .5",complement = FALSE) test_that("BF.coxph returns correct results,", { expect_equivalent( out$PHP_confirmatory, c(0.194,0.806), tol = .1 ) })
"cdfemu" <- function(x, para, paracheck=TRUE, yacoubsintegral=TRUE) { if(paracheck == TRUE) { if(! are.paremu.valid(para)) return() } ETA.SMALL <- 1E-3 SMALL <- 1E-10 ONEminusSMALL <- 1 - SMALL LARGE <- sqrt(.Machine$double.xmax) names(para$para) <- NULL E <- para$para[1] M <- para$para[2] b <- sqrt( 2*M / (1-E^2) ) Ymuleft <- sqrt(pi)*2^(3/2 - M)*(1 - E^2)^M Ymuleft <- Ymuleft / (gamma(M) * E^(M-1/2)) if(E >= 1 - ETA.SMALL) { yacoubsintegral <- FALSE } if(E <= ETA.SMALL) { yacoubsintegral <- FALSE } "Ymu" <- function(x=NULL, y=NULL) { if(y < 0) return(NA) "afunc" <- function(t) { B <- vector(mode="numeric", length=length(t)) for(i in 1:length(B)) { toI <- t[i]^2*x b <- NULL try(b <- besselI(toI, nu=M-1/2, expon.scaled=TRUE)/exp(-toI), silent=TRUE) if(is.null(b) | is.nan(b) | ! is.finite(b)) b <- LARGE B[i] <- b } B[! is.finite(B)] <- LARGE z <- exp(-t^2)*t^(2*M) * B z[! is.finite(z)] <- LARGE return( z ) } int1 <- NULL try( int1 <- integrate(afunc, lower=y, upper=Inf), silent=TRUE ) if(is.null(int1)) return(NA) val <- int1$value if(val == 0) return(0) return(Ymuleft * int1$value) } f <- sapply(1:length(x), function(i) { xi <- x[i] if(xi == 0) return(0) if(is.na(xi) || xi < 0) return(NA) if(yacoubsintegral) { Y <- Ymu(x=E, y=b*xi) if(is.na(Y)) { return(ONEminusSMALL) } else { return(1 - Y) } } else { int1 <- NULL try( int1 <- integrate(pdfemu, 0, xi, para=para, paracheck=FALSE) ) if(is.null(int1)) return(NA) val <- int1$value ifelse(val >= ONEminusSMALL, return(ONEminusSMALL), return(val)) } }) names(f) <- NULL return(f) }
NULL .ggroup.guiWidgetsToolkittcltk <- function(toolkit, horizontal=TRUE, spacing=5, use.scrollwindow=FALSE, container=NULL, ...) { GGroup$new(toolkit, horizontal, spacing=spacing, use.scrollwindow=use.scrollwindow, container, ...) } GGroup <- setRefClass("GGroup", contains="GBoxContainer", fields=list( use_scrollwindow="character" ), methods=list( initialize=function(toolkit=NULL, horizontal=TRUE, spacing=5, use.scrollwindow=FALSE, container=NULL, ...) { initFields(horizontal=horizontal, use_scrollwindow=as.character(use.scrollwindow)) if(use_scrollwindow != FALSE) { init_scrollwindow(container) tkconfigure(block, width=400, height=400) tkgrid.propagate(block, "FALSE") } else { widget <<- ttkframe(getWidget(container)) block <<- widget } set_spacing(spacing) add_to_parent(container, .self, ...) callSuper(toolkit) }, init_scrollwindow=function(container) { block <<- ttkframe(container$get_widget()) cnv <- tkcanvas(block) xscr <- ttkscrollbar(block, orient="horizontal", command=function(...)tkxview(cnv,...)) yscr <- ttkscrollbar(block, command=function(...)tkyview(cnv,...)) do_x <- horizontal do_y <- !horizontal tkconfigure(cnv, xscrollcommand = function(...) tkset(xscr,...)) tkconfigure(cnv, yscrollcommand = function(...) tkset(yscr,...)) tkgrid(cnv,row=0,column=0, sticky="news") if(do_x) tkgrid(xscr,row=1,column=0, sticky="ew") if(do_y) tkgrid(yscr,row=0,column=1, sticky="ns") tkgrid.columnconfigure(cnv, 0, weight=1) tkgrid.rowconfigure(cnv, 0, weight=1) widget <<- ttkframe(cnv) widgetID <- tcl(cnv,"create","window",0,0,anchor="nw",window=widget) tkbind(block, "<Map>", function() { width <- tkwinfo("width", block) height <- tkwinfo("height", block) if(do_x) tkconfigure(cnv, width=width) if(do_y) tkconfigure(cnv, height=height) }) tkbind(block, "<Configure>", function(W) { width <- as.numeric(tkwinfo("width", W)) height <- as.numeric(tkwinfo("height", W)) if(do_x) { scroll_size <- as.numeric(tkwinfo("height", xscr)) tkconfigure(cnv, height=height - scroll_size, width=width) tkitemconfigure(cnv, widgetID, height=height - scroll_size - 2) } if(do_y) { scroll_size <- as.numeric(tkwinfo("width", yscr)) tkconfigure(cnv, height=height, width=width - scroll_size) tkitemconfigure(cnv, widgetID, width=width - scroll_size - 2) } }) tkbind(widget,"<Configure>",function() { bbox <- tcl(cnv,"bbox","all") tcl(cnv,"config",scrollregion=bbox) }) } ))
dmsparsefmt <- function (x, fmt) { z <- { } for (i in 1:length(x)) { z1 <- dmsabs(x[i], fmt) mm <- ifelse(is.na(z1$mm), 0, z1$mm) ss <- ifelse(is.na(z1$ss), 0, z1$ss) decdeg <- dms2dd(z1$dd, mm, ss, z1$L) z2 <- data.frame(z1, decdeg, stringsAsFactors = F) z <- rbind(z, z2) } z <- data.frame(coord = x, z, stringsAsFactors = F) return(z) }
plotpar <- function(qp, x = NULL, panel = NULL, xpanel = NULL, ypanel = NULL, color = NULL, geom = 'bar', ci = T) { if (!missing(x)) x <- deparse(substitute(x)) if (!missing(panel)) panel <- deparse(substitute(panel)) if (!missing(xpanel)) xpanel <- deparse(substitute(xpanel)) if (!missing(ypanel)) ypanel <- deparse(substitute(ypanel)) if (!missing(color)) color <- deparse(substitute(color)) plotpar_(qp, x, panel, xpanel, ypanel, color, geom) }
EqRSintra <- function(comm, dis = NULL, structures = NULL, option=c("eq", "normed1", "normed2"), formula = c("QE", "EDI"), tol = 1e-8, metmean = c("harmonic", "arithmetic")){ df <- comm metmean <- metmean[1] if(!option[1]%in%c("eq", "normed1", "normed2")) stop("unavailable option, please modify; option can be eq, normed1, or normed2") if(!(is.data.frame(df) | is.matrix(df))) stop("df must be a matrix or a data frame") if(!(is.data.frame(df))) df <- as.data.frame(df) if(is.null(colnames(df)) | is.null(rownames(df))) stop("df must have both row names and column names") if(length(colnames(df)[colSums(df)>0])==1) stop("df must contain at least two species with positive occurrence in at least one site") if (is.null(dis)){ dis <- as.dist((matrix(1, ncol(df), ncol(df)) - diag(rep(1, ncol(df))))) attributes(dis)$Labels <- colnames(df) formula <- "QE" } if(!inherits(dis, "dist")) stop("dis must be of class dist") if(!formula[1]%in%c("QE","EDI")) stop("formula can be either QE or EDI") if(any(!colnames(df)%in%attributes(dis)$Labels)) stop("column names in df are missing in dis") else{ d <- as.matrix(dis)[colnames(df), colnames(df)] if(formula[1]=="EDI"){ op <- options()$warn options(warn=-1) if(!is.euclid(as.dist(d))) stop("dis should be Euclidean") options(warn=op) d <- d^2/2 } else{ op <- options()$warn options(warn=-1) if(!is.euclid(sqrt(as.dist(d)))) stop("dis should be squared Euclidean") options(warn=op) } if(any(d>1)) d <- d/max(d) } nsp <- ncol(df) if(any(rowSums(df)<tol)) warnings("empty sites have been removed") if(sum(df)<tol) stop("df must contain nonnegative values and the sum of its values must be positive") dfold <- df df <- df[rowSums(df)>tol, ] ncomm <- nrow(df) if(nrow(df)==1) stop("df must contain at least two non-empty sites") if(!is.null(structures)){ if(!inherits(structures, "data.frame")) stop("structures should be a data frame or NULL") if(!nrow(structures)==nrow(dfold)) stop("incorrect number of rows in structures") structures <- structures[rowSums(dfold)>0, , drop=FALSE] for(i in 1:ncol(structures)) structures[,i] <-factor(structures[,i]) if(!is.null(rownames(structures)) & !is.null(rownames(df))){ e <- sum(abs(match(rownames(df), rownames(structures))-(1:ncomm))) if(e>1e-8) warning("be careful that rownames in df should be in the same order as rownames in structures") } checknested <- function(forstru){ n <- ncol(forstru) for (i in 1:(n - 1)) { tf <- table(forstru[, c(i, i + 1)]) niv <- apply(tf, 1, function(x) sum(x != 0)) if (any(niv != 1)) { stop(paste("non hierarchical design for structures, column", i, "is not nested in column", i + 1)) } } } if(ncol(structures)> 1) checknested(structures) } P <- as.data.frame(sweep(df, 1, rowSums(df), "/")) if(is.null(structures)) w <- rep(1/nrow(df), nrow(df)) else{ nc <- ncol(structures) fun <- function(i){ x <- table(structures[, i], structures[, i-1]) x[x>0] <- 1 x <- rowSums(x) v <- x[structures[, i]] v <- 1/v return(v) } if(ncol(structures)==1){ firstw <- table(structures[, 1]) w <- 1/firstw[structures[, 1]]/length(unique(structures[, 1])) } else { listw <- lapply(2:nc, fun) firstw <- table(structures[, 1]) firstw <- 1/firstw[structures[, 1]] finalw <- 1/length(unique(structures[, ncol(structures)])) forw <- cbind.data.frame(as.vector(firstw), as.vector(listw), as.vector(rep(finalw, nrow(structures)))) w <- apply(forw, 1, prod) } } df <- P * w if(!is.null(structures)){ if(length(levels(factor(structures[, 1])))==1) stop("All sites belong to a unique level in the first column of structures, remove this first column in structures") if(length(levels(factor(structures[, 1])))==nrow(df)) stop("Each site belongs to a distinct level in the first column of structures, this first column is useless, remove it and re-run") } diversity <- function(x){ if(sum(x)==0) return(0) else return(t(x)%*%d%*%x) } op <- options()$warn options(warn=-1) a <- apqe(as.data.frame(t(df)), sqrt(2*as.dist(d)), structures) options(warn=op) dfprop <- sweep(df, 1, rowSums(df), "/") divsites <- sapply(as.data.frame(t(dfprop)), diversity) if(metmean=="arithmetic") alphaEQ <- sum(w*(1/(1-divsites))) else alphaEQ <- 1/(1-sum(w*divsites)) nlev <- nrow(a$results) beta1 <- (1-sum(a$results[-c(1, nlev), 1]))/(1-a$results[nlev ,1]) if(nlev==3){ gamma <- beta1*alphaEQ if(option[1]=="eq"){ res <- cbind.data.frame(c(beta1, alphaEQ, gamma)) rownames(res) <- c("Inter-sites", "Intra-sites", "Gamma") colnames(res) <- "Equivalent numbers" } else if(option[1]=="normed1"){ beta1 <- (1-1/beta1)/(1-1/ncomm) res <- cbind.data.frame(beta1) rownames(res) <- c("Inter-sites") colnames(res) <- "Normed inter-site diversity" } else if(option[1]=="normed2"){ beta1 <- (beta1-1)/(ncomm-1) res <- cbind.data.frame(beta1) rownames(res) <- c("Inter-sites") colnames(res) <- "Normed inter-site diversity" } return(res) } else{ nc <- ncol(structures) funnc <- function(i){ dfilist <- split(df, as.factor(structures[, i])) if(i > 1){ strulist <- split(structures, as.factor(structures[, i])) strulist <- lapply(strulist, function(x) x[, -(i:nc), drop=FALSE]) } wi <- tapply(w, as.factor(structures[, i]), sum) fun <- function(j){ tab <- dfilist[[j]] if(i > 1) thestru <- strulist[[j]] else thestru <- NULL op <- options()$warn options(warn=-1) ai <- apqe(as.data.frame(t(tab)), sqrt(2*as.dist(d)), thestru) nlev <- nrow(ai$results) numi <- ai$results[nlev, 1] - ai$results[1, 1] gammai <- ai$results[nlev, 1] options(warn=op) ratioi <- (1-numi)/(1-gammai) if(option[1]=="eq"){ return(ratioi) } else if(option[1]=="normed1"){ if(!is.null(thestru)) len <- length(levels(factor(thestru[, ncol(thestru)]))) else len <- nrow(tab) if((ratioi-1)<1e-10) res <-0 else res <- (1 - 1/ratioi)/(1 - 1/len) return(res) } else if(option[1]=="normed2"){ if(!is.null(thestru)) len <- length(levels(factor(thestru[, ncol(thestru)]))) else len <- nrow(tab) if((ratioi-1)<1e-10) res <-0 else res <- (ratioi - 1)/(len - 1) return(res) } } resi <- unlist(lapply(1:length(dfilist), fun)) if(metmean=="arithmetic") res <- sum(wi*resi) else res <- 1/sum(wi*(1/resi)) return(res) } resbeta <- sapply(nc:1, funnc) if(option[1]=="eq"){ gamma <- beta1*prod(resbeta)*alphaEQ res <- cbind.data.frame(c(beta1, resbeta, alphaEQ, gamma)) inter <- c("Inter-sites", paste("Inter-", colnames(structures), sep="")) intra <- c("Intra-sites", paste("Intra-", colnames(structures), sep="")) intrainter <- paste(inter[-(nc+1)], intra[-1]) rownames(res) <- c(inter[nc+1], rev(intrainter), intra[1], "Gamma") colnames(res) <- "Equivalent numbers" } else if(option[1]=="normed1"){ beta1N <- (1 - 1/beta1) / (1 - 1/length(unique(structures[, nc]))) res <- cbind.data.frame(c(beta1N, resbeta)) inter <- c("Inter-sites", paste("Inter-", colnames(structures), sep="")) intra <- c("Intra-sites", paste("Intra-", colnames(structures), sep="")) intrainter <- paste(inter[-(nc+1)], intra[-1]) rownames(res) <- c(inter[nc+1], rev(intrainter)) colnames(res) <- "Normed contributions to beta diversity" } else if(option[1]=="normed2"){ beta1N <- (beta1 - 1) / (length(unique(structures[, nc])) - 1) res <- cbind.data.frame(c(beta1N, resbeta)) inter <- c("Inter-sites", paste("Inter-", colnames(structures), sep="")) intra <- c("Intra-sites", paste("Intra-", colnames(structures), sep="")) intrainter <- paste(inter[-(nc+1)], intra[-1]) rownames(res) <- c(inter[nc+1], rev(intrainter)) colnames(res) <- "Normed contributions to beta diversity" } return(res) } }
Nam03 <- structure(list(ID = c(3, 4, 6, 8, 10, 11, 14, 16, 17, 19, 20, 22, 24, 25, 26, 28, 29, 32, 36, 37, 38, 40, 43, 44, 49, 50, 51, 52, 54, 56, 57, 59, 61, 63, 65, 69, 71, 75, 76, 78, 79, 80, 81, 82, 83, 84, 85, 88, 89, 93, 105, 109, 111, 113, 114, 122, 601, 603, 603), Size = c(1285, 470, 1077, 550, 850, 892, 1232, 3048, 2216, 535, 5953, 159, 9678, 318, 343, 11534, 10106, 443, 12727, 257, 511, 253, 1503, 7677, 1001, 961, 1138, 5412, 925, 2554, 4665, 1501, 1143, 483, 8154, 2077, 8585, 301, 153, 3072, 4331, 1215, 708, 620, 126, 228, 914, 16562, 15712, 3482, 192, 726, 372, 684, 207, 700, 9653, 3769, 2540), Age = c(1.1, 9, 6.7, 1.7, 9.4, 10.9, 9.5, 1, 8.6, 6.5, 0.5, 1, 5, 8.2, 9.5, 9.5, 7.5, 3.8, 2.5, 7.5, 2.5, 1, 13, 14, 7, 13.5, 9, 9.2, 7, 9.5, 13.5, 9.5, 1, 1, 4.6, 0.5, 7, 1, 10.9, 8.5, 2.5, 2, 10.5, 10, 9, 8.5, 3.5, 8, 5, 8.4, 0.8, 16.3, 7, 9, 9.3, 7.9, 9, 9, 9), Year = c(1987, 1994, 1995, 1995, 1996, 1996, 1996, 1997, 1997, 1995, 1987, 1986, 1989, 1995, 1995, 1996, 1984, 1992, 1987, 1989, 1995, 1995, 1997, 1995, 1988, 1995, 1983, 1997, 1997, 1995, 1997, 1991, 1981, 1989, 1995, 1974, 1993, 1988, 1989, 1982, 1990, 1993, 1994, 1995, 1991, 1992, 1993, 1991, 1995, 1986, 1992, 1996, 1980, 1988, 1992, 1992, 1997, 1997, 1997), Country = c("English or Scotland", "Scandanavia or Netherlands", "English or Scotland", "Scandanavia or Netherlands", "Other (Israel, Turkey, South Africa, Mexico or U. Arab Emirates", "USA or Canada", "Japan, Hong Kong or Malaysia", "Scandanavia or Netherlands", "English or Scotland", "Japan, Hong Kong or Malaysia", "Scandanavia or Netherlands", "USA or Canada", "English or Scotland", "Other (Israel, Turkey, South Africa, Mexico or U. Arab Emirates", "USA or Canada", "USA or Canada", "USA or Canada", "New Zealand or Australia", "English or Scotland", "English or Scotland", "Scandanavia or Netherlands", "New Zealand or Australia", "English or Scotland", "Other (Israel, Turkey, South Africa, Mexico or U. Arab Emirates", "English or Scotland", "English or Scotland", "USA or Canada", "Other (Israel, Turkey, South Africa, Mexico or U. Arab Emirates", "USA or Canada", "Scandanavia or Netherlands", "Japan, Hong Kong or Malaysia", "Japan, Hong Kong or Malaysia", "New Zealand or Australia", "English or Scotland", "New Zealand or Australia", "English or Scotland", "New Zealand or Australia", "USA or Canada", "USA or Canada", "USA or Canada", "USA or Canada", "English or Scotland", "New Zealand or Australia", "Scandanavia or Netherlands", "Scandanavia or Netherlands", "USA or Canada", "USA or Canada", "English or Scotland", "English or Scotland", "USA or Canada", "Scandanavia or Netherlands", "Other (Israel, Turkey, South Africa, Mexico or U. Arab Emirates", "USA or Canada", "Scandanavia or Netherlands", "USA or Canada", "USA or Canada", "Scandanavia or Netherlands", "Scandanavia or Netherlands", "Scandanavia or Netherlands"), Smoke = c("Parental exposure", "Parental exposure", "Parental exposure", "Parental exposure", "Parental exposure", "Parental exposure", "Parental exposure", "Parental exposure", "Household exposure", "Parental exposure", "Parental exposure", "Parental exposure", "Parental exposure", "Parental exposure", "Parental exposure", "Household exposure", "Parental exposure", "Parental exposure", "Parental exposure", "Household exposure", "Parental exposure", "Parental exposure", "Parental exposure", "Parental exposure", "Household exposure", "Parental exposure", "Parental exposure", "Household exposure", "Household exposure", "Household exposure", "Household exposure", "Household exposure", "Parental exposure", "Parental exposure", "Parental exposure", "Parental exposure", "Parental exposure", "Household exposure", "Parental exposure", "Parental exposure", "Parental exposure", "Household exposure", "Household exposure", "Parental exposure", "Parental exposure", "Household exposure", "Parental exposure", "Parental exposure", "Parental exposure", "Parental exposure", "Parental exposure", "Parental exposure", "Parental exposure", "Household exposure", "Household exposure", "Parental exposure", "Household exposure", "Household exposure", "Household exposure"), Adj = c(0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1), Asthma_logOR = c(0.385262400790645, NA, 0.350656871613169, NA, 0.246860077931526, -0.0202027073175195, -0.0943106794712413, NA, -0.27443684570176, 0.300104592450338, NA, NA, -0.0408219945202552, 0.336472236621213, NA, -0.0202027073175195, NA, NA, NA, NA, 0.524728528934982, NA, NA, 0.157003748809665, NA, NA, NA, 0.300104592450338, 0.470003629245736, -0.562118918153541, NA, 0.0953101798043249, NA, NA, NA, NA, 0.19062035960865, NA, NA, 0.398776119957368, 0.741937344729377, 0.78845736036427, 0.336472236621213, 1.02961941718116, 0.940007258491471, 0.693147180559945, 0.357674444271816, NA, NA, 0.139761942375159, NA, NA, NA, -0.0725706928348354, 0.357674444271816, 0.350656871613169, 0.444685821261446, 0.0953101798043249, -0.356674943938732 ), LRD_logOR = c(NA, 0.0392207131532813, NA, 0.609765571620894, NA, NA, NA, 0.418710334858185, NA, NA, 0.993251773010283, 0.693147180559945, 0.048790164169432, NA, 0.85015092936961, 0.122217632724249, -0.0202027073175195, 1.93296963777958, 0.378436435720245, 0.993251773010283, NA, -0.328504066972036, 0.122217632724249, 0.139761942375159, 0.0392207131532813, 0.0198026272961797, 0.00995033085316809, 0.22314355131421, 0.53062825106217, NA, 0.0392207131532813, 0.182321556793955, 0.0392207131532813, 0.476234178996372, 0.198850858745165, 0.500775287912489, NA, 0.688134638736401, 0.924258901523332, NA, NA, NA, NA, NA, NA, NA, NA, 0.300104592450338, 0.285178942233662, 0.215111379616945, 1.18784342239605, 1.47247205736094, 1.7732559976635, 0.22314355131421, NA, NA, NA, NA, NA), Asthma_v = c(0.0729, NA, 0.0225, NA, 0.0529, 0.0484, 0.0729, NA, 0.0225, 0.36, NA, NA, 0.0144, 0.1296, NA, 0.0121, NA, NA, NA, NA, 0.0289, NA, NA, 0.0036, NA, NA, NA, 0.0081, 0.0784, 0.1089, NA, 0.0121, NA, NA, NA, NA, 0.0016, NA, NA, 0.0256, 0.0529, 0.0441, 0.0361, 0.1521, 0.1369, 0.0841, 0.0324, NA, NA, 0.0169, NA, NA, NA, 0.0016, 0.1089, 0.0361, 0.0196, 0.0529, 0.1849), AsthmaLRD_cov_05 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 0.0054, NA, NA, 0.0033, NA, NA, NA, NA, NA, NA, NA, 6e-04, NA, NA, NA, 0.00405, 0.0448, NA, NA, 0.00825, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 0.0052, NA, NA, NA, 0.0022, NA, NA, NA, NA, NA), LRD_v = c(NA, 0.04, NA, 0.0324, NA, NA, NA, 0.0144, NA, NA, 0.04, 0.0576, 0.0081, NA, 0.0784, 0.0036, 0.0036, 0.2116, 0.01, 0.1369, NA, 0.2601, 0.0196, 4e-04, 0.0361, 0.0169, 0.0121, 0.0081, 0.1024, NA, 0.0049, 0.0225, 1e-04, 0.0529, 0.0016, 0.0441, NA, 0.1225, 0.1521, NA, NA, NA, NA, NA, NA, NA, NA, 0.09, 0.0361, 0.0064, 0.25, 0.2209, 1.0609, 0.0121, NA, NA, NA, NA, NA)), .Names = c("ID", "Size", "Age", "Year", "Country", "Smoke", "Adj", "Asthma_logOR", "LRD_logOR", "Asthma_v", "AsthmaLRD_cov_05", "LRD_v"), class = "data.frame", row.names = c(NA, -59L))
partial_bundle <- function(p, type = "auto", local = TRUE, minified = TRUE) { if (!is.plotly(p)) stop("The first argument to `partial_bundle()` must be a plotly object", call. = FALSE) idx <- plotlyjsBundleIDX(p) p$dependencies[[idx]]$local <- local p$dependencies[[idx]]$minified <- minified p$dependencies[[idx]]$partial_bundle <- match.arg(type, c("auto", "main", names(bundleTraceMap))) plotly_build(p) } verify_partial_bundle <- function(p) { currentBundle <- plotlyjsBundle(p) bundleType <- currentBundle$partial_bundle %||% "main" if (identical(bundleType, "main")) return(p) types <- unique(vapply(p$x$data, function(x) x[["type"]] %||% "scatter", character(1))) if (identical(bundleType, "auto")) { for (i in seq_along(bundleTraceMap)) { if (all(types %in% bundleTraceMap[[i]])) { bundleType <- names(bundleTraceMap)[[i]] break } } if (identical(bundleType, "auto")) { warning( "Couldn't find a single partial bundle that would support this plotly ", "visualization. Using the main (full) bundle instead." ) p$dependencies[[plotlyjsBundleIDX(p)]] <- plotlyMainBundle() return(p) } } missingTypes <- setdiff(types, bundleTraceMap[[bundleType]]) if (length(missingTypes)) { msg <- sprintf( "The '%s' bundle supports the following trace types: '%s'.\n\n This plotly visualization contains the following trace types: '%s'", bundleType, paste(bundleTraceMap[[bundleType]], collapse = "', '"), paste(missingTypes, collapse = "', '") ) stop(msg, call. = FALSE) } idx <- plotlyjsBundleIDX(p) bundle_name <- sprintf("plotly-%s", bundleType) bundle_script <- sprintf( "plotly-%s-%s.%sjs", bundleType, currentBundle$version, if (isTRUE(currentBundle$minified)) "min." else "" ) p$dependencies[[idx]]$name <- bundle_name p$dependencies[[idx]]$script <- bundle_script p$dependencies[[idx]]$src <- list(href = "https://cdn.plot.ly") if (isTRUE(p$dependencies[[idx]]$local)) { try_library("curl", "partial_bundle") tmpfile <- file.path(tempdir(), bundle_script) p$dependencies[[idx]]$src$file <- dirname(tmpfile) if (!file.exists(tmpfile)) { curl::curl_download(paste0("https://cdn.plot.ly/", bundle_script), tmpfile) } p$dependencies[[idx]]$package <- NULL } p } plotlyjsBundleIDX <- function(p) { depNames <- sapply(p$dependencies, "[[", "name") bundleNames <- paste0("plotly-", c("main", "auto", names(bundleTraceMap))) idx <- which(depNames %in% bundleNames) if (length(idx) != 1) stop("Couldn't find the plotlyjs bundle") idx } plotlyjsBundle <- function(p) { p$dependencies[[plotlyjsBundleIDX(p)]] } bundleTraceMap <- list( basic = c( "scatter", "bar", "pie" ), cartesian = c( "scatter", "bar", "pie", "box", "heatmap", "histogram", "histogram2d", "histogram2dcontour", "contour", "scatterternary", "violin" ), geo = c( "scatter", "scattergeo", "choropleth" ), gl3d = c( "scatter", "scatter3d", "surface", "mesh3d", "cone" ), gl2d = c( "scatter", "scattergl", "splom", "pointcloud", "heatmapgl", "contourgl", "parcoords" ), mapbox = c( "scatter", "scattermapbox" ), finance = c( "scatter", "bar", "pie", "histogram", "ohlc", "candlestick", "waterfall" ) )
spec_all <- c( spec_getting_started, spec_driver, spec_connection, spec_result, spec_sql, spec_meta, spec_transaction, spec_compliance, spec_stress )
indexMatrix<-function(dimension,symmetrical=FALSE,upper=FALSE,lowerTriangular=FALSE, sep=NULL,starttext=NULL,endtext=NULL, unique=FALSE,rowoffset=0,coloffset=0,indices=FALSE,diagonal=TRUE,namesvector=NULL,shortdiag=FALSE){ if(is.null(namesvector)) namesvector=1:9999 if(indices==TRUE) sep<-c(",") tempmatrix<-matrix(paste0(starttext,rep(namesvector[1:dimension+coloffset],dimension)),nrow=dimension,ncol=dimension) for(i in 1:nrow(tempmatrix)){ for(j in 1:ncol(tempmatrix)){ if(i!=j || !shortdiag) tempmatrix[i,j] <- paste0(tempmatrix[i,j],sep,namesvector[1:dimension+rowoffset][j]) } } tempmatrix[,]<-paste0(tempmatrix[,],endtext) if(upper==TRUE) tempmatrix<-t(tempmatrix) if(symmetrical==TRUE) tempmatrix[col(tempmatrix)>row(tempmatrix)] <-t(tempmatrix)[col(tempmatrix)>row(tempmatrix)] if(unique==TRUE && symmetrical==TRUE) tempmatrix<-tempmatrix[lower.tri(tempmatrix,diag=diagonal)] if(lowerTriangular==TRUE) tempmatrix[col(tempmatrix) > row(tempmatrix)] <- 0 if(indices==TRUE){ tempmatrix<-matrix(c(unlist(strsplit(tempmatrix,","))[seq(1,length(tempmatrix)*2,2)], unlist(strsplit(tempmatrix,","))[seq(2,length(tempmatrix)*2,2)]),ncol=2) } return(tempmatrix) } rl<-function(x) { x[is.na(x)] <- FALSE return(x) } cseq <- function(from, to, by){ temp<-c() for(i in from){ temp<-c(temp,seq(i,to,by)) } temp<-sort(temp) return(temp) }
extractS3ObjectInformation <- function(object_o_1) { on <- getObjectClassKind(object_o_1) stopifnot(on == 'S3') getFields <- function() { l <- ls(object_o_1) if (length(l) == 0) return(NULL) f <- sapply(l, function(e) !typeof(object_o_1[[e]]) %in% c('closure')) fields <- l[f] generatePublicFieldParagraph(object_o_1, fields) } getMethods <- function() { methods <- getObjectFunctionNames(object_o_1) if (is.null(methods) || length(methods) == 0) return(NULL) generatePublicMethodParagraph(object_o_1, methods) } l <- list( 'S3 fields' = getFields(), 'S3 methods' = getMethods() ) Filter(Negate(is.null), l) }
Harvey_Mills_2002_unit_root<-function(x,model,max_lags,lsm){ res<-Harvey_Mills_2002_unit_root_first_step(x,model,max_lags)$res ADF_unit_root(res,max_lags,lsm) } Harvey_Mills_2002_unit_root_first_step <- function(x,model,max_lags){ if (model==1){ try({ n=length(x) trend<-seq(0,length(x)-1,1) nonlin_model=nlsLM(x ~ a1 + a2*(1/(1+exp(-a3*(trend-(a4*n))))) + a5*(1/(1+exp(-a6*(trend-(a7*n))))),start=list(a1=0,a2=0,a3=1,a4=0.3,a5=0,a6=1,a7=0.7),control = nls.control(maxiter = 500)) res=residuals(nonlin_model) },silent = T) } if (model==2){ try({ n=length(x) trend<-seq(0,length(x)-1,1) nonlin_model=nlsLM(x ~ a1 + a2*(1/(1+exp(-a3*(trend-(a4*n))))) + a5*(1/(1+exp(-a6*(trend-(a7*n))))) + a8*trend ,start=list(a1=0,a2=0,a3=1,a4=0.3,a5=0,a6=1,a7=0.7,a8=0),control = nls.control(maxiter = 500)) res=residuals(nonlin_model) },silent = T) } if (model==3){ try({ n=length(x) trend<-seq(0,length(x)-1,1) nonlin_model=nlsLM(x ~ a1 + a2*(1/(1+exp(-a3*(trend-(a4*n))))) + a5*trend + a6*trend*(1/(1+exp(-a3*(trend-(a4*n))))) + a7*(1/(1+exp(-a8*(trend-(a9*n))))) + a10*trend*(1/(1+exp(-a8*(trend-(a9*n))))), start=list(a1=0,a2=0,a3=1,a4=0.3,a5=0,a6=0,a7=0,a8=1,a9=0.7,a10=0),control = nls.control(maxiter = 500)) res=residuals(nonlin_model) },silent = T) } my_list = list("res"=res) return(my_list) } ADF_unit_root<-function(x,max_lags,lsm){ AICs = NULL BICs = NULL for(i in 1:max_lags){ z=diff(x) n=length(z) z.diff=embed(z, i+1)[,1] z.lag.1=x[(i+1):n] k=i+1 z.diff.lag = embed(z, i+1)[, 2:k] model<-lm(z.diff~z.lag.1+0+z.diff.lag ) son<-summary(lm(z.diff~z.lag.1+0+z.diff.lag ))$coefficients[1,3] AICs[i+1] = AIC(model) BICs[i+1] = BIC(model) z.diffzero=embed(z, 2)[,1] z.lag.zero.1=x[2:n] model0<-lm(z.diffzero~z.lag.zero.1+0) AICs[1] = AIC(model0) BICs[1] = BIC(model0) if(lsm == 1){ uygun_lag=which.min(AICs)-1 } else { uygun_lag=which.min(BICs)-1 } z.diff=embed(z, uygun_lag+1)[,1] z.lag.1=x[(uygun_lag+1):n] if(uygun_lag == 0){ model = lm(z.diff~z.lag.1+0) son<-summary(lm(z.diff~z.lag.1+0 ))$coefficients[1,3] } else { z.diff.lag = embed(z, uygun_lag+1)[, 2:k] model = lm(z.diff~z.lag.1+0+z.diff.lag) son<-summary(lm(z.diff~z.lag.1+0+z.diff.lag ))$coefficients[1,3] } } my_list <- list("Model" = summary(model),"Selected Lag"=uygun_lag, "Test Statistic"=son) return(my_list) }
clikcorr_n <- function(data, lower1, upper1, lower2, upper2, cp=.95, starVal=NA, nlm=FALSE, ...) { F <- prepare_data(data, lower1, upper1, lower2, upper2) m <- suppressWarnings(estimate(F, starVal=starVal, nlm=nlm, ...)) r_est <- m$C[1,2] / sqrt(m$C[1,1]*m$C[2,2]) ci <- suppressWarnings(profile_ci(data, lower1, upper1, lower2, upper2, cp, starVal=starVal, nlm=nlm, ...)) p0 <- suppressWarnings(correlation_lrt(F, 0, starVal=starVal, ...)) result <- list(Cor=r_est, Cov=m$C, Mean=m$Mu, P0=p0, LCL=ci$lcl, UCL=ci$ucl, Loglike=m$loglike) return(result) }
get_cor_grouping <- function(mod, levels = NULL) { if (!is.null(mod$groups)) { struct <- mod$modelStruct$corStruct if (is.null(struct)) struct <- mod mod_formula <- nlme::getGroupsFormula(struct) dat <- nlme::getData(mod) if (inherits(na.action(mod), "exclude")) dat <- dat[-as.integer(na.action(mod)),,drop=FALSE] grps <- stats::model.frame(mod_formula, data = dat) grps <- apply(grps, 1, paste, collapse = "/") if (is.null(levels)) levels <- unique(grps) grps <- factor(grps, levels = levels) } else if (!is.null(mod$modelStruct$corStruct)) { grps <- factor(rep("A",mod$dims$N)) } else { grps <- factor(1:mod$dims$N) } grps } build_corr_mats <- function(mod) { if (is.null(mod$modelStruct$corStruct)) { return(NULL) } else { R_list <- nlme::corMatrix(mod$modelStruct$corStruct) grps <- get_cor_grouping(mod, levels = names(R_list)) if (!is.list(R_list)) R_list <- list(A = R_list) attr(R_list, "groups") <- grps return(R_list) } } get_sort_order <- function(mod) { groups <- mod$groups if (is.data.frame(groups)) { order(do.call(order, groups)) } else if (!is.null(groups)) { order(order(groups)) } else { 1:mod$dims$N } } build_var_cor_mats <- function(mod, R_list = build_corr_mats(mod), sigma_scale = FALSE) { sigma <- if (sigma_scale) mod$sigma else 1 if (is.null(R_list)) { if (is.null(mod$groups)) { if (is.null(mod$modelStruct$varStruct)) { V_list <- as.list(rep(sigma^2, mod$dims$N)) } else { sd_vec <- sigma / as.numeric(nlme::varWeights(mod$modelStruct$varStruct)) V_list <- as.list(sd_vec^2) } grps <- factor(1:mod$dims$N) attr(V_list, "groups") <- grps names(V_list) <- levels(grps) } else { if (is.null(mod$modelStruct$varStruct)) { grps <- mod$groups[[1]] V_list <- tapply(rep(sigma^2, length(grps)), grps, function(x) diag(x, nrow = length(x))) } else { sort_order <- get_sort_order(mod) sd_vec <- sigma / as.numeric(nlme::varWeights(mod$modelStruct$varStruct))[sort_order] V_list <- tapply(sd_vec^2, mod$groups[[1]], function(x) diag(x, nrow = length(x))) } attr(V_list, "groups") <- mod$groups[[1]] } } else { if (is.null(mod$modelStruct$varStruct)) { V_list <- if (sigma_scale) lapply(R_list, function(x) x * mod$sigma^2) else R_list } else { sort_order <- get_sort_order(mod) sd_vec <- sigma / as.numeric(nlme::varWeights(mod$modelStruct$varStruct))[sort_order] sd_list <- split(sd_vec, attr(R_list, "groups")) V_list <- Map(function(R, s) tcrossprod(s) * R, R = R_list, s = sd_list) } attr(V_list, "groups") <- attr(R_list, "groups") } return(V_list) } ZDZt <- function(D, Z_list) { lapply(Z_list, function(z) z %*% D %*% t(z)) } build_RE_mats <- function(mod, sigma_scale = FALSE) { all_groups <- rev(mod$groups) if (length(all_groups) == 1) { D_mat <- as.matrix(mod$modelStruct$reStruct[[1]]) if (sigma_scale) D_mat <- mod$sigma^2 * D_mat data <- nlme::getData(mod) Z_mat <- model.matrix(mod$modelStruct$reStruc, data[complete.cases(data), ]) row.names(Z_mat) <- NULL Z_list <- matrix_list(Z_mat, all_groups[[1]], "row") ZDZ_list <- ZDZt(D_mat, Z_list) attr(ZDZ_list, "groups") <- all_groups[[1]] } else { if (sigma_scale) { D_list <- lapply(mod$modelStruct$reStruct, function(x) mod$sigma^2 * as.matrix(x)) } else { D_list <- lapply(mod$modelStruct$reStruct, as.matrix) } data <- nlme::getData(mod) Z_mat <- model.matrix(mod$modelStruct$reStruc, data[complete.cases(data), ]) Z_names <- sapply(strsplit(colnames(Z_mat), ".", fixed=TRUE), function(x) x[1]) row.names(Z_mat) <- NULL Z_levels <- lapply(names(all_groups), function(x) Z_mat[,x==Z_names,drop=FALSE]) Z_levels <- Map(matrix_list, x = Z_levels, fac = all_groups, dim = "row") ZDZ_lists <- Map(ZDZt, D = D_list, Z_list = Z_levels) for (i in 2:length(all_groups)) { ZDZ_lists[[i]] <- add_bdiag(small_mats = ZDZ_lists[[i-1]], big_mats = ZDZ_lists[[i]], crosswalk = all_groups[c(i-1,i)]) } ZDZ_list <- ZDZ_lists[[i]] attr(ZDZ_list, "groups") <- all_groups[[i]] } ZDZ_list } build_Sigma_mats <- function(mod, invert = FALSE, sigma_scale = FALSE) UseMethod("build_Sigma_mats") build_Sigma_mats.default <- function(mod, invert = FALSE, sigma_scale = FALSE) { mod_class <- paste(class(mod), collapse = "-") stop(paste0("Sigma matrices not available for models of class ", mod_class, ".")) } build_Sigma_mats.gls <- function(mod, invert = FALSE, sigma_scale = FALSE) { V_list <- build_var_cor_mats(mod, sigma_scale = sigma_scale) V_grps <- attr(V_list, "groups") if (invert) { V_list <- lapply(V_list, function(x) chol2inv(chol(x))) attr(V_list, "groups") <- V_grps } return(V_list) } build_Sigma_mats.lme <- function(mod, invert = FALSE, sigma_scale = FALSE) { if (inherits(mod, "nlme")) stop("not implemented for \"nlme\" objects") V_list <- build_var_cor_mats(mod, sigma_scale = sigma_scale) ZDZ_list <- build_RE_mats(mod, sigma_scale = sigma_scale) V_grps <- attr(V_list, "groups") ZDZ_grps <- attr(ZDZ_list, "groups") group_mapping <- tapply(ZDZ_grps, V_grps, function(x) length(unique(x))) nested <- all(group_mapping == 1L) if (nested) { Sigma_list <- add_bdiag(V_list, ZDZ_list, data.frame(V_grps, ZDZ_grps)) Sigma_grps <- attr(ZDZ_list, "groups") } else { V_mat <- unblock(V_list, block = V_grps) ZDZ_mat <- unblock(ZDZ_list, block = ZDZ_grps) Sigma_list <- V_mat + ZDZ_mat Sigma_grps <- factor(rep("A", nrow(Sigma_list))) } if (invert) { Sigma_list <- lapply(Sigma_list, function(x) chol2inv(chol(x))) } attr(Sigma_list, "groups") <- Sigma_grps return(Sigma_list) }
as.binary.hypergraph <- function(h) { M <- incidence_matrix(h) M[M!=0] <- 1 hypergraph_from_incidence_matrix(M) } equivalent.hypergraphs <- function(h1,h2,vertex.names=FALSE,edge.names=FALSE, strip.names=FALSE, method=c('any','exact','binary')) { m <- from_igraph.match.arg(method) if(is.null(m)) stop("invalid method") if(m != "any"){ M1 <- incidence_matrix(h1) M2 <- incidence_matrix(h2) if(strip.names){ if(!is.null(colnames(M1))){ if(vertex.names){ M1 <- M1[,order(colnames(M1))] } colnames(M1) <- 1:ncol(M1) } if(!is.null(colnames(M2))){ if(vertex.names){ M2 <- M2[,order(colnames(M2))] } colnames(M2) <- 1:ncol(M2) } if(!is.null(rownames(M1))){ if(edge.names){ M1 <- M1[order(rownames(M1)),] } rownames(M1) <- 1:nrow(M1) } if(!is.null(rownames(M2))){ if(edge.names){ M2 <- M2[order(rownames(M2)),] } rownames(M2) <- 1:nrow(M2) } } else { if(vertex.names){ v1 <- colnames(M1) v2 <- colnames(M2) if(!all(sort(v1) == sort(v2))) return(FALSE) M1 <- M1[,order(v1)] M2 <- M2[,order(v2)] } if(edge.names){ e1 <- rownames(M1) e2 <- rownames(M2) if(!all(sort(e1) == sort(e2))) return(FALSE) M1 <- M1[order(e1),] M2 <- M2[order(e2),] } } if(m != "exact"){ h1 <- hypergraph_from_incidence_matrix(M1) h2 <- hypergraph_from_incidence_matrix(M1) } } switch(m, exact=all(M1==M2), any=equivalent.hypergraphs(h1,h2,method='binary',strip.names=TRUE) || equivalent.hypergraphs(h1,h2,method='binary',strip.names=TRUE, vertex.names=TRUE) || equivalent.hypergraphs(h1,h2,method='binary',strip.names=TRUE, edge.names=TRUE) || equivalent.hypergraphs(h1,h2,method='binary',strip.names=TRUE, vertex.names=TRUE, edge.names=TRUE), binary=all(incidence_matrix(as.binary.hypergraph(h1))== incidence_matrix(as.binary.hypergraph(h2))) ) }
function(){ }
spatial_distance <- function( stations, dem, topography = TRUE, cores = 1, dmap = TRUE, dstation = TRUE, aoi ) { if(dmap == TRUE) { if(cores == 1) { maps <- vector(mode = "list", length = nrow(stations)) dem <- methods::as(dem, "SpatialGridDataFrame") mean_cell_size <- mean(dem@grid@cellsize, na.rm = TRUE) xy <- sp::SpatialPoints(coords = stations[,1:2], proj4string = sp::CRS(raster::projection(dem))) z <- as.numeric(sp::over(x = xy, y = dem)[,1]) if(missing(aoi) == TRUE) { map_coords <- sp::coordinates(obj = dem) aoi <- c(min(map_coords[,1]), max(map_coords[,1]), min(map_coords[,2]), max(map_coords[,2])) } aoi_flag <- dem aoi_flag@data <- aoi_flag@data * 0 aoi_xy <- sp::coordinates(aoi_flag) aoi_flag@data[[1]][aoi_xy[,1] >= aoi[1] & aoi_xy[,1] <= aoi[2] & aoi_xy[,2] >= aoi[3] & aoi_xy[,2] <= aoi[4]] <- 1 map_i <- dem for(i in 1:length(xy)) { print(paste("Processing station", i)) dem_x <- sp::coordinates(dem)[,1] dem_y <- sp::coordinates(dem)[,2] dx <- dem_x - sp::coordinates(xy)[i,1] dy <- dem_y - sp::coordinates(xy)[i,2] dt <- sqrt(dx^2 + dy^2) for(j in 1:length(dt)) { if(aoi_flag@data[[1]][j] == 1) { n_i <- round(x = dt[j] / (0.1 * mean_cell_size), digits = 0) n_i <- ifelse(n_i == 0, 1, n_i) x_i <- seq(from = sp::coordinates(xy)[i,1], to = sp::coordinates(dem)[j,1], length.out = n_i) y_i <- seq(from = sp::coordinates(xy)[i,2], to = sp::coordinates(dem)[j,2], length.out = n_i) xy_i <- sp::SpatialPoints( coords = cbind(x_i, y_i), proj4string = sp::CRS(raster::projection(dem))) z_i <- sp::over(x = xy_i, y = dem)[,1] z_d <- seq(from = z[i], to = dem@data[[1]][j], length.out = length(z_i)) d_e <- z_d - z_i if(topography == TRUE) { z_e <- ifelse(d_e < 0, z_i, z_d) } else { z_e <- z_d } l <- sqrt((x_i[length(x_i)] - x_i[1])^2 + (y_i[length(x_i)] - y_i[1])^2 + sum(diff(z_e))^2) map_i@data[[1]][j] <- l } else { map_i@data[[1]][j] <- NA } } maps[[i]] <- map_i } } else { n_cores <- parallel::detectCores() n_cores <- ifelse(n_cores < cores, n_cores, cores) cl <- parallel::makeCluster(getOption("mc.cores", n_cores)) maps <- vector(mode = "list", length = nrow(stations)) dem <- as(dem, "SpatialGridDataFrame") xy <- sp::SpatialPoints(coords = stations[,1:2], proj4string = sp::CRS(raster::projection(dem))) z <- as.numeric(sp::over(x = xy, y = dem)[,1]) map_i <- dem work_parallel <- function(x, dem) { x_sep <- strsplit(x = x, split = "__", fixed = TRUE) topo_option <- as.numeric(x_sep[[1]][1]) dt <- as.numeric(x_sep[[1]][2]) dem_cellsize <- as.numeric(x_sep[[1]][3]) dem_projection <- as.character(x_sep[[1]][4]) x_station <- as.numeric(x_sep[[1]][5]) y_station <- as.numeric(x_sep[[1]][6]) z_station <- as.numeric(x_sep[[1]][7]) x_dem <- as.numeric(x_sep[[1]][8]) y_dem <- as.numeric(x_sep[[1]][9]) z_dem <- as.numeric(x_sep[[1]][10]) n_i <- round(x = dt / (0.1 * dem_cellsize), digits = 0) n_i <- ifelse(n_i == 0, 1, n_i) x_i <- seq(from = x_station, to = x_dem, length.out = n_i) y_i <- seq(from = y_station, to = y_dem, length.out = n_i) xy_i <- sp::SpatialPoints(coords = cbind(x_i, y_i), proj4string = sp::CRS(dem_projection)) z_i <- sp::over(x = xy_i, y = dem)[,1] z_d <- seq(from = z_station, to = z_dem, length.out = length(z_i)) d_e <- z_d - z_i if(topo_option == 1) { z_e <- ifelse(d_e < 0, z_i, z_d) } else { z_e <- z_d } l <- sqrt((x_i[length(x_i)] - x_i[1])^2 + (y_i[length(x_i)] - y_i[1])^2 + sum(diff(z_e))^2) return(l) } for(i in 1:length(xy)) { print(paste("Processing map for station", i)) dx <- sp::coordinates(dem)[,1] - sp::coordinates(xy)[i,1] dy <- sp::coordinates(dem)[,2] - sp::coordinates(xy)[i,2] n_data <- nrow(dem) topo_option <- rep(x = as.numeric(topography), times = n_data) dt <- sqrt(dx^2 + dy^2) dem_cellsize <- rep(x = mean(dem@grid@cellsize, na.rm = TRUE), times = n_data) dem_projection <- rep(x = as.character( sp::CRS(raster::projection(dem))), times = n_data) x_station <- rep(x = as.numeric(sp::coordinates(xy)[i,1]), times = n_data) y_station <- rep(x = as.numeric(sp::coordinates(xy)[i,2]), times = n_data) z_station <- rep(x = z[i], times = n_data) x_dem <- as.numeric(sp::coordinates(dem)[,1]) y_dem <- as.numeric(sp::coordinates(dem)[,2]) z_dem <- as.numeric(dem@data[[1]]) input_parallel <- paste(topo_option, dt, dem_cellsize, dem_projection, x_station, y_station, z_station, x_dem, y_dem, z_dem, sep = "__") l <- parallel::parLapply(cl, X = input_parallel, fun = work_parallel, dem = dem) map_i@data[[1]] <- unlist(l) maps[[i]] <- map_i } parallel::stopCluster(cl) } } else { maps <- vector(mode = "list", length = nrow(stations)) } if(dstation == TRUE) { print("Processing station distances") distances <- matrix(nrow = nrow(stations), ncol = nrow(stations)) rownames(distances) <- rownames(stations) colnames(distances) <- rownames(stations) xy <- sp::SpatialPoints(coords = stations[,1:2], proj4string = sp::CRS(raster::projection(dem))) dem <- methods::as(dem, "SpatialGridDataFrame") for(i in 1:length(xy)) { dx_stations <- sp::coordinates(xy)[,1] - sp::coordinates(xy)[i,1] dy_stations <- sp::coordinates(xy)[,2] - sp::coordinates(xy)[i,2] dt_stations <- sqrt(dx_stations^2 + dy_stations^2) z <- sp::over(x = xy, y = dem) for(j in 1:length(dt_stations)) { n_i <- round(x = dt_stations[j] / (0.1 * mean( dem@grid@cellsize, na.rm = TRUE)), digits = 0) n_i <- ifelse(n_i == 0, 1, n_i) x_i <- seq(from = sp::coordinates(xy)[i,1], to = sp::coordinates(xy)[j,1], length.out = n_i) y_i <- seq(from = sp::coordinates(xy)[i,2], to = sp::coordinates(xy)[j,2], length.out = length(x_i)) xy_i <- sp::SpatialPoints(coords = cbind(x_i, y_i), proj4string = sp::CRS(raster::projection(dem))) z_i <- as.numeric(unlist(sp::over(x = xy_i, y = dem))) z_d <- seq(from = z[i,], to = z[j,], length.out = length(z_i)) d_e <- z_d - z_i z_e <- ifelse(d_e < 0, z_i, z_d) distances[i,j] <- sum(sqrt(diff(x_i)^2 + diff(y_i)^2 + diff(z_e)^2)) } } } else { distances <- matrix(nrow = nrow(stations), ncol = nrow(stations)) rownames(distances) <- rownames(stations) colnames(distances) <- rownames(stations) } return(list(maps = maps, stations = distances)) }
"diagCOP" <- function(cop=NULL, para=NULL, secondary=FALSE, ploton=TRUE, lines=TRUE, delt=0.005, ...) { if(ploton) { plot(c(0,1), c(0,1), type="n", xlab="U=V, NONEXCEEDANCE PROBABILITY", ylab="H, NONEXCEEDANCE PROBABILITY") } T <- seq(0+delt,1-delt,delt) C <- sapply(T, function(x) { y <- x if(secondary) y <- 1 - y return( cop(x,y, para=para, ...)) } ) if(lines & ! is.null(dev.list())) lines(T,C, ...) txt <- "primary" if(secondary) txt <- "secondary" return(list(t=T, diagcop=C, diagtype=txt)) }
penhdfeppml_int <- function(y, x, fes, lambda, tol = 1e-8, hdfetol = 1e-4, glmnettol = 1e-12, penalty = "lasso", penweights = NULL, saveX = TRUE, mu = NULL, colcheck = TRUE, init_z = NULL, post = FALSE, verbose = FALSE, standardize = TRUE, method = "placeholder", cluster = NULL, debug = FALSE) { if (method == "plugin") { penreg <- penhdfeppml_cluster_int(y = y, x = x, fes = fes, cluster = cluster, tol = tol, hdfetol = hdfetol, glmnettol = glmnettol, penalty = penalty, penweights = penweights, saveX = saveX, mu = mu, colcheck = colcheck, K = 15, init_z = init_z, post = FALSE, verbose = verbose, lambda = NULL) } else { b <- matrix(NA, nrow = ncol(x), ncol = 1) rownames(b) <- colnames(x) include_x <- 1:ncol(x) if (is.null(penweights)) { penweights <- rep(1, length(include_x)) } if (length(penweights) > length(include_x)){ print("penweights needs to be same length as number of x variables") stop() } if (colcheck == TRUE) { include_x <- collinearity_check(y, x, fes, 1e-6) x <- x[, include_x] if (!is.null(penweights)) { penweights = penweights[include_x] } } n <- length(y) crit <- 1 old_deviance <-0 iter <-0 while (crit > tol) { iter <- iter + 1 if (iter == 1) { if (is.null(mu)) mu <- (y + mean(y))/2 z <- (y - mu)/mu + log(mu) eta <- log(mu) last_z <- z if (is.null(init_z)) { reg_z <- matrix(z) } else { reg_z <- init_z } reg_x <- x } else { last_z <- z z <- (y - mu)/mu + log(mu) reg_z <- matrix(z - last_z + z_resid) reg_x <- x_resid } z_resid <- collapse::fhdwithin(reg_z, fes, w = mu) x_resid <- collapse::fhdwithin(reg_x, fes, w = mu) if (is.null(penweights)) { } else{ if(debug) { print(sum(penweights)) } if(debug) { print(penweights) } penweights = penweights * length(include_x) / sum(penweights) if(debug) { print(sum(penweights)) } } if (penalty == "ridge") { penreg <- fastridge(x = x_resid, y = z_resid, weights = mu/sum(mu), lambda = n * lambda, standardize = standardize) } else { if (penalty != "lasso" & iter == 1) { warning(penalty, " penalty is not supported. Lasso is used by default.") } if (debug) { penreg <- glmnet::glmnet(x = x_resid, y = z_resid, weights = mu/sum(mu), lambda = lambda, thresh = glmnettol, standardize = standardize) print((penreg$beta)) print(penweights) } if (debug) { penreg <- glmnet::glmnet(x = x_resid, y = z_resid, weights = mu/sum(mu), lambda = lambda, thresh = glmnettol, standardize = standardize) print((penreg$beta)) print(penweights) } penreg <- glmnet::glmnet(x = x_resid, y = z_resid, weights = mu/sum(mu), lambda = lambda, thresh = glmnettol, penalty.factor = penweights, standardize = standardize) if (debug) { print((penreg$beta)) stop() } } b[include_x] <- penreg$beta residuals <- z_resid - x_resid %*% b[include_x] mu <- as.numeric(exp(z - residuals)) temp <- -(y * log(y/mu) - (y-mu)) temp[which(y == 0)] <- -mu[which(y == 0)] deviance <- -2 * sum(temp)/n if(deviance<0) deviance = 0 delta_deviance <- old_deviance - deviance if (!is.na(delta_deviance) & (deviance < 0.1 * delta_deviance)) { delta_deviance = deviance } denom_crit = max(c( min(c(deviance, old_deviance)) , 0.1 )) crit = abs(delta_deviance) / denom_crit if (verbose == TRUE) { print(crit) } old_deviance <- deviance } k <- ncol(matrix(x)) n <- length(y) select_x <- which(b != 0) k <- length(select_x) bic <- deviance + k * log(n)/n if (post) { x_select <- x_resid[, as.numeric(penreg$beta) != 0] if (length(x_select) != 0){ ppml_temp <- hdfeppml_int(y = y, x = x_select, fes = fes, tol = tol, hdfetol = hdfetol, mu = penreg$mu, colcheck = FALSE) penreg$pencoefs <- penreg$beta penreg$beta[which(penreg$beta != 0), 1] <- ppml_temp$coefficients b[include_x] <- penreg$beta mu <- ppml_temp$mu bic <- ppml_temp$bic deviance <- ppml_temp$deviance } else{ print("no covariates selected!") } } penreg[["beta"]] <- b penreg[["mu"]] <- mu penreg[["bic"]] <- bic penreg[["deviance"]] <- deviance if (saveX == TRUE) { penreg[["x_resid"]] <- x_resid penreg[["z_resid"]] <- z_resid } } return(penreg) }
summarizeExperiments = function(reg, ids, show = c("prob", "algo")) { checkExperimentRegistry(reg, strict = TRUE, writeable = FALSE) syncRegistry(reg) assertCharacter(show, min.len = 1, any.missing = FALSE) dbSummarizeExperiments(reg, ids, show) }
get_api = function(api = NULL) { if (is.null(api)) api = Sys.getenv("typeform_api2") if (inherits(api, "Token2.0")) api = api$credentials$access_token if (is.character(api) && nchar(api) != 0) return(api) if (nchar(Sys.getenv("typeform_api")) > 0) stop("Old key") stop("Invalid api key.", call. = FALSE) }
del.miss <- function (x) { deleteMissing <- function(x) { i <- which(x %in% as.raw(c(240, 2, 4))) if (length(i)) x[-i] else x } if (!inherits(x, "DNAbin")) x <- as.DNAbin(x) if (is.matrix(x)) { n <- dim(x)[1] y <- vector("list", n) for (i in 1:n) y[[i]] <- x[i, ] names(y) <- rownames(x) x <- y rm(y) } if (!is.list(x)) return(deleteMissing(x)) x <- lapply(x, deleteMissing) class(x) <- "DNAbin" x }
model_basic <- function(datadea, dmu_eval = NULL, dmu_ref = NULL, orientation = c("io", "oo", "dir"), dir_input = NULL, dir_output = NULL, rts = c("crs", "vrs", "nirs", "ndrs", "grs"), L = 1, U = 1, maxslack = TRUE, weight_slack_i = 1, weight_slack_o = 1, vtrans_i = NULL, vtrans_o = NULL, compute_target = TRUE, compute_multiplier = FALSE, returnlp = FALSE, ...) { if (!is.deadata(datadea)) { stop("Data should be of class deadata. Run read_data function first!") } orientation <- tolower(orientation) orientation <- match.arg(orientation) rts <- tolower(rts) rts <- match.arg(rts) if (!is.null(datadea$ud_inputs) || !is.null(datadea$ud_outputs)) { if (orientation == "dir") { warning("Model proposed by Fare and Grosskopf (2004) is applied for undesirable inputs/outputs.") } else { warning("Model proposed by Seiford and Zhu (2002) is applied for undesirable inputs/outputs.") datadea_old <- datadea res_und <- undesirable_basic(datadea = datadea, vtrans_i = vtrans_i, vtrans_o = vtrans_o) datadea <- res_und$u_datadea if (orientation == "oo") { vtrans_i <- res_und$vtrans_o vtrans_o <- res_und$vtrans_i } else { vtrans_i <- res_und$vtrans_i vtrans_o <- res_und$vtrans_o } if (!is.null(datadea$ud_inputs) && (orientation != "io")) { warning("Undesirable (good) inputs with no input-oriented model.") } if (!is.null(datadea$ud_outputs) && (orientation != "oo")) { warning("Undesirable (bad) outputs with no output-oriented model.") } if (rts != "vrs") { rts <- "vrs" warning("Returns to scale changed to variable (vrs) because there are data with undesirable inputs/outputs.") } } } if (rts == "grs") { if (L > 1) { stop("L must be <= 1.") } if (U < 1) { stop("U must be >= 1.") } } dmunames <- datadea$dmunames nd <- length(dmunames) if (is.null(dmu_eval)) { dmu_eval <- 1:nd } else if (!all(dmu_eval %in% (1:nd))) { stop("Invalid set of DMUs to be evaluated (dmu_eval).") } names(dmu_eval) <- dmunames[dmu_eval] nde <- length(dmu_eval) if (is.null(dmu_ref)) { dmu_ref <- 1:nd } else if (!all(dmu_ref %in% (1:nd))) { stop("Invalid set of reference DMUs (dmu_ref).") } names(dmu_ref) <- dmunames[dmu_ref] ndr <- length(dmu_ref) if (orientation == "dir") { input <- datadea$input output <- datadea$output nc_inputs <- datadea$nc_inputs nc_outputs <- datadea$nc_outputs nd_inputs <- datadea$nd_inputs nd_outputs <- datadea$nd_outputs ud_inputs <- datadea$ud_inputs ud_outputs <- datadea$ud_outputs inputnames <- rownames(input) outputnames <- rownames(output) ni <- nrow(input) no <- nrow(output) obj <- "max" if (is.null(dir_input)) { dir_input <- matrix(input[, dmu_eval], nrow = ni) } else { if (is.matrix(dir_input)) { if ((nrow(dir_input) != ni) || (ncol(dir_input) != nde)) { stop("Invalid input direction matrix (number of inputs x number of evaluated DMUs).") } } else if ((length(dir_input) == 1) || (length(dir_input) == ni)) { dir_input <- matrix(dir_input, nrow = ni, ncol = nde) } else { stop("Invalid input direction vector.") } } rownames(dir_input) <- inputnames colnames(dir_input) <- dmunames[dmu_eval] if (is.null(dir_output)) { dir_output <- matrix(output[, dmu_eval], nrow = no) } else { if (is.matrix(dir_output)) { if ((nrow(dir_output) != no) || (ncol(dir_output) != nde)) { stop("Invalid output direction matrix (number of outputs x number of evaluated DMUs).") } } else if ((length(dir_output) == 1) || (length(dir_output) == no)) { dir_output <- matrix(dir_output, nrow = no, ncol = nde) } else { stop("Invalid output direction vector.") } } rownames(dir_output) <- outputnames colnames(dir_output) <- dmunames[dmu_eval] } else { if (orientation == "io") { input <- datadea$input output <- datadea$output nc_inputs <- datadea$nc_inputs nc_outputs <- datadea$nc_outputs nd_inputs <- datadea$nd_inputs nd_outputs <- datadea$nd_outputs ud_inputs <- datadea$ud_inputs ud_outputs <- datadea$ud_outputs obj <- "min" orient <- 1 } else { input <- -datadea$output output <- -datadea$input nc_inputs <- datadea$nc_outputs nc_outputs <- datadea$nc_inputs nd_inputs <- datadea$nd_outputs nd_outputs <- datadea$nd_inputs ud_inputs <- datadea$ud_outputs ud_outputs <- datadea$ud_inputs aux <- weight_slack_i weight_slack_i <- weight_slack_o weight_slack_o <- aux obj <- "max" orient <- -1 } inputnames <- rownames(input) outputnames <- rownames(output) ni <- nrow(input) no <- nrow(output) } inputref <- matrix(input[, dmu_ref], nrow = ni) outputref <- matrix(output[, dmu_ref], nrow = no) ncd_inputs <- c(nc_inputs, nd_inputs) target_input <- NULL target_output <- NULL multiplier_input <- NULL multiplier_output <- NULL multiplier_rts <- NULL orientation_param <- NULL DMU <- vector(mode = "list", length = nde) names(DMU) <- dmunames[dmu_eval] f.obj <- c(1, rep(0, ndr)) if (rts == "crs") { f.con.rs <- NULL f.con2.rs <- NULL f.dir.rs <- NULL f.rhs.rs <- NULL } else { f.con.rs <- cbind(0, matrix(1, nrow = 1, ncol = ndr)) f.con2.rs <- cbind(matrix(1, nrow = 1, ncol = ndr), matrix(0, nrow = 1, ncol = ni + no)) f.rhs.rs <- 1 if (rts == "vrs") { f.dir.rs <- "=" } else if (rts == "nirs") { f.dir.rs <- "<=" } else if (rts == "ndrs") { f.dir.rs <- ">=" } else { f.con.rs <- rbind(f.con.rs, f.con.rs) f.con2.rs <- rbind(f.con2.rs, f.con2.rs) f.dir.rs <- c(">=", "<=") f.rhs.rs <- c(L, U) } } f.dir <- c(rep("<=", ni), rep(">=", no), f.dir.rs) f.dir[c(nc_inputs, ni + nc_outputs)] <- "=" if (maxslack && (!returnlp)) { if (is.matrix(weight_slack_i)) { if ((nrow(weight_slack_i) != ni) || (ncol(weight_slack_i) != nde)) { stop("Invalid weight input matrix (number of inputs x number of evaluated DMUs).") } } else if ((length(weight_slack_i) == 1) || (length(weight_slack_i) == ni)) { weight_slack_i <- matrix(weight_slack_i, nrow = ni, ncol = nde) } else { stop("Invalid weight input vector (number of inputs).") } rownames(weight_slack_i) <- inputnames colnames(weight_slack_i) <- dmunames[dmu_eval] weight_slack_i[nd_inputs, ] <- 0 if (is.matrix(weight_slack_o)) { if ((nrow(weight_slack_o) != no) || (ncol(weight_slack_o) != nde)) { stop("Invalid weight output matrix (number of outputs x number of evaluated DMUs).") } } else if ((length(weight_slack_o) == 1) || (length(weight_slack_o) == no)) { weight_slack_o <- matrix(weight_slack_o, nrow = no, ncol = nde) } else { stop("Invalid weight output vector (number of outputs).") } rownames(weight_slack_o) <- outputnames colnames(weight_slack_o) <- dmunames[dmu_eval] weight_slack_o[nd_outputs, ] <- 0 nnci <- length(nc_inputs) nnco <- length(nc_outputs) f.con2.1 <- cbind(inputref, diag(ni), matrix(0, nrow = ni, ncol = no)) f.con2.1[nc_inputs, (ndr + 1) : (ndr + ni)] <- 0 f.con2.2 <- cbind(outputref, matrix(0, nrow = no, ncol = ni), -diag(no)) f.con2.2[nc_outputs, (ndr + ni + 1) : (ndr + ni + no)] <- 0 f.con2.nc <- matrix(0, nrow = (nnci + nnco), ncol = (ndr + ni + no)) f.con2.nc[, ndr + c(nc_inputs, ni + nc_outputs)] <- diag(nnci + nnco) f.con2 <- rbind(f.con2.1, f.con2.2, f.con2.nc, f.con2.rs) f.dir2 <- c(rep("=", ni + no + nnci + nnco), f.dir.rs) if (orientation == "dir") { nudi <- length(ud_inputs) nudo <- length(ud_outputs) if ((nudi + nudo) > 0) { f.con2.s0.1 <- cbind(matrix(0, nrow = nudi, ncol = ndr), matrix(diag(ni)[ud_inputs, ], nrow = nudi, ncol = ni), matrix(0, nrow = nudi, ncol = no)) f.con2.s0.2 <- cbind(matrix(0, nrow = nudo, ncol = ndr + ni), matrix(diag(no)[ud_outputs, ], nrow = nudo, ncol = no)) f.con2 <- rbind(f.con2, f.con2.s0.1, f.con2.s0.2) f.dir2 <- c(f.dir2, rep("=", nudi + nudo)) } } } if (orientation != "dir") { f.con.2 <- cbind(matrix(0, nrow = no, ncol = 1), outputref) for (i in 1:nde) { ii <- dmu_eval[i] f.con.1 <- cbind(-input[, ii], inputref) f.con.1[ncd_inputs, 1] <- 0 f.con <- rbind(f.con.1, f.con.2, f.con.rs) f.rhs <- c(rep(0, ni), output[, ii], f.rhs.rs) f.rhs[ncd_inputs] <- input[ncd_inputs, ii] if (returnlp) { lambda <- rep(0, ndr) names(lambda) <- dmunames[dmu_ref] var <- list(efficiency = 0, lambda = lambda) DMU[[i]] <- list(direction = obj, objective.in = f.obj, const.mat = f.con, const.dir = f.dir, const.rhs = f.rhs, var = var) } else { if (compute_multiplier) { res <- lp(obj, f.obj, f.con, f.dir, f.rhs, compute.sens = TRUE) if (res$status == 0) { multiplier_input <- -orient * res$duals[1 : ni] names(multiplier_input) <- inputnames multiplier_output <- orient * res$duals[(ni + 1) : (ni + no)] names(multiplier_output) <- outputnames if (rts == "grs") { multiplier_rts <- res$duals[(ni + no + 1):(ni + no + 2)] names(multiplier_rts) <- c("grs_L", "grs_U") } else if (rts != "crs") { multiplier_rts <- res$duals[ni + no + 1] names(multiplier_rts) <- rts } } else { multiplier_input <- NA multiplier_output <- NA multiplier_rts <- NA } } else { res <- lp(obj, f.obj, f.con, f.dir, f.rhs) } if(res$status == 0) { res <- res$solution efficiency <- res[1] if (maxslack) { f.obj2 <- c(rep(0, ndr), weight_slack_i[, i], weight_slack_o[, i]) f.rhs2 <- c(efficiency * input[, ii], output[, ii], rep(0, nnci + nnco), f.rhs.rs) f.rhs2[ncd_inputs] <- input[ncd_inputs, ii] res <- lp("max", f.obj2, f.con2, f.dir2, f.rhs2)$solution lambda <- res[1 : ndr] names(lambda) <- dmunames[dmu_ref] slack_input <- res[(ndr + 1) : (ndr + ni)] names(slack_input) <- inputnames slack_output <- res[(ndr + ni + 1) : (ndr + ni + no)] names(slack_output) <- outputnames if (compute_target) { target_input <- orient * as.vector(inputref %*% lambda) target_output <- orient * as.vector(outputref %*% lambda) names(target_input) <- inputnames names(target_output) <- outputnames target_input[ud_inputs] <- vtrans_i - target_input[ud_inputs] target_output[ud_outputs] <- vtrans_o - target_output[ud_outputs] } } else { lambda <- res[2 : (ndr + 1)] names(lambda) <- dmunames[dmu_ref] target_input <- orient * as.vector(inputref %*% lambda) names(target_input) <- inputnames target_output <- orient * as.vector(outputref %*% lambda) names(target_output) <- outputnames slack_input <- efficiency * input[, ii] - orient * target_input slack_input[ncd_inputs] <- input[ncd_inputs, ii] - orient * target_input[ncd_inputs] names(slack_input) <- inputnames slack_output <- orient * target_output - output[, ii] names(slack_output) <- outputnames target_input[ud_inputs] <- vtrans_i - target_input[ud_inputs] target_output[ud_outputs] <- vtrans_o - target_output[ud_outputs] } } else { efficiency <- NA lambda <- NA slack_input <- NA slack_output <- NA if (compute_target) { target_input <- NA target_output <- NA } } if (orientation == "io") { if (rts == "crs") { DMU[[i]] <- list(efficiency = efficiency, lambda = lambda, slack_input = slack_input, slack_output = slack_output, target_input = target_input, target_output = target_output, multiplier_input = multiplier_input, multiplier_output = multiplier_output) } else { DMU[[i]] <- list(efficiency = efficiency, lambda = lambda, slack_input = slack_input, slack_output = slack_output, target_input = target_input, target_output = target_output, multiplier_input = multiplier_input, multiplier_output = multiplier_output, multiplier_rts = multiplier_rts) } } else { aux <- weight_slack_i weight_slack_i <- weight_slack_o weight_slack_o <- aux if (rts == "crs") { DMU[[i]] <- list(efficiency = efficiency, lambda = lambda, slack_input = slack_output, slack_output = slack_input, target_input = target_output, target_output = target_input, multiplier_input = multiplier_output, multiplier_output = multiplier_input) } else { DMU[[i]] <- list(efficiency = efficiency, lambda = lambda, slack_input = slack_output, slack_output = slack_input, target_input = target_output, target_output = target_input, multiplier_input = multiplier_output, multiplier_output = multiplier_input, multiplier_rts = multiplier_rts) } } } } } else { ncd_outputs <- c(nc_outputs, nd_outputs) for (i in 1:nde) { ii <- dmu_eval[i] f.con.1 <- cbind(dir_input[, i], inputref) f.con.1[ud_inputs, 1] <- -dir_input[ud_inputs, i] f.con.1[ncd_inputs, 1] <- 0 f.con.2 <- cbind(-dir_output[, i], outputref) f.con.2[ud_outputs, 1] <- dir_output[ud_outputs, i] f.con.2[ncd_outputs, 1] <- 0 f.con <- rbind(f.con.1, f.con.2, f.con.rs) f.dir[c(ud_inputs, ni + ud_outputs)] <- "=" f.rhs <- c(input[, ii], output[, ii], f.rhs.rs) if (returnlp) { lambda <- rep(0, ndr) names(lambda) <- dmunames[dmu_ref] var <- list(efficiency = 0, lambda = lambda) DMU[[i]] <- list(direction = obj, objective.in = f.obj, const.mat = f.con, const.dir = f.dir, const.rhs = f.rhs, var = var) } else { res <- lp(obj, f.obj, f.con, f.dir, f.rhs) if (res$status == 0) { res <- res$solution beta <- res[1] if (maxslack) { f.obj2 <- c(rep(0, ndr), weight_slack_i[, i], weight_slack_o[, i]) f.rhs2 <- c(input[, ii] - beta * dir_input[, i], output[, ii] + beta * dir_output[, i], rep(0, nnci + nnco), f.rhs.rs, rep(0, nudi + nudo)) f.rhs2[ud_inputs] <- input[ud_inputs, ii] + beta * dir_input[ud_inputs, i] f.rhs2[ni + ud_outputs] <- output[ud_outputs, ii] - beta * dir_output[ud_outputs, i] f.rhs2[ncd_inputs] <- input[ncd_inputs, ii] f.rhs2[ni + ncd_outputs] <- output[ncd_outputs, ii] res <- lp("max", f.obj2, f.con2, f.dir2, f.rhs2)$solution lambda <- res[1 : ndr] names(lambda) <- dmunames[dmu_ref] slack_input <- res[(ndr + 1) : (ndr + ni)] names(slack_input) <- inputnames slack_output <- res[(ndr + ni + 1) : (ndr + ni + no)] names(slack_output) <- outputnames if (compute_target) { target_input <- as.vector(inputref %*% lambda) target_output <- as.vector(outputref %*% lambda) names(target_input) <- inputnames names(target_output) <- outputnames } } else { lambda <- res[2 : (ndr + 1)] names(lambda) <- dmunames[dmu_ref] target_input <- as.vector(inputref %*% lambda) names(target_input) <- inputnames target_output <- as.vector(outputref %*% lambda) names(target_output) <- outputnames slack_input <- input[, ii] - beta * dir_input[, i] - target_input slack_input[ud_inputs] <- input[ud_inputs, ii] + beta * dir_input[ud_inputs, i] - target_input[ud_inputs] slack_input[ncd_inputs] <- input[ncd_inputs, ii] - target_input[ncd_inputs] names(slack_input) <- inputnames slack_output <- target_output - output[, ii] - beta * dir_output[, i] slack_output[ud_outputs] <- target_output[ud_outputs] - output[ud_outputs, ii] + beta * dir_output[ud_outputs, i] slack_output[ncd_outputs] <- target_output[ncd_outputs] - output[ncd_outputs, ii] names(slack_output) <- outputnames } } else { beta <- NA lambda <- NA slack_input <- NA slack_output <- NA if (compute_target) { target_input <- NA target_output <- NA } } DMU[[i]] <- list(beta = beta, lambda = lambda, slack_input = slack_input, slack_output = slack_output, target_input = target_input, target_output = target_output ) } } orientation_param <- list( dir_input = dir_input, dir_output = dir_output) } if ((!is.null(datadea$ud_inputs) || !is.null(datadea$ud_outputs)) && (orientation != "dir")) { datadea <- datadea_old vtrans_i <- res_und$vtrans_i vtrans_o <- res_und$vtrans_o } if (rts == "grs") { eps <- 1e-6 for (i in 1:nde) { j <- which(dmu_ref == dmu_eval[i]) if (length(j) == 1) { kk <- DMU[[i]]$lambda[j] kk2 <- sum(DMU[[i]]$lambda[-j]) if ((kk > eps) && (kk2 > eps)) { warning(paste("Under generalized returns to scale,", dmunames[dmu_eval[i]], "appears in its own reference set.")) } } } } deaOutput <- list(modelname = "basic", orientation = orientation, orientation_param = orientation_param, rts = rts, L = L, U = U, DMU = DMU, data = datadea, dmu_eval = dmu_eval, dmu_ref = dmu_ref, vtrans_i = vtrans_i, vtrans_o = vtrans_o, maxslack = maxslack, weight_slack_i = weight_slack_i, weight_slack_o = weight_slack_o) return(structure(deaOutput, class = "dea")) }
"openintro_palettes"
"SPtimeline"
rm(list = ls()) testthat::context("Miscellaneous") library("gamlss") library("distreg.vis") library("bamlss") library("testthat") cssfile <- system.file("srcjs/solarized-dark.css", package = "distreg.vis") jsfile <- system.file("srcjs/highlight.pack.js", package = "distreg.vis") expect_true(file.exists(cssfile)) expect_true(file.exists(jsfile)) DF <- structure( list( race = structure( c(1L, 1L, 1L, 1L, 1L), .Label = c("1. White", "2. Black", "3. Asian", "4. Other"), class = c("ordered", "factor") ), year = c(2006L, 2006L, 2006L, 2006L, 2006L), education = structure( 1:5, .Label = c( "1. < HS Grad", "2. HS Grad", "3. Some College", "4. College Grad", "5. Advanced Degree" ), class = c("ordered", "factor") ), health = structure( c(1L, 1L, 1L, 1L, 1L), .Label = c("1. <=Good", "2. >=Very Good"), class = c("ordered", "factor") ), age = c(42L, 42L, 42L, 42L, 42L), intercept = c(TRUE, TRUE, TRUE, TRUE, TRUE) ), .Names = c("race", "year", "education", "health", "age", "intercept"), row.names = c("P1", "P2", "P3", "P4", "P5"), class = "data.frame" ) DF <- distreg.vis:::fac_check(DF) expect_false("ordered" %in% unlist(sapply(DF, class))) fam_name <- "GA" art_data <- model_fam_data(fam_name = fam_name) ndata <- art_data[sample(seq_len(nrow(art_data)), 5), !colnames(art_data) %in% fam_name] form <- as.formula(paste0(fam_name, "~ norm2 + binomial1")) ga <- gamlss(form, sigma.formula = ~ ., data = art_data, family = fam_name, trace = FALSE) ba <- bamlss(list(GA ~ s(norm2) + binomial1, sigma ~ s(norm2) + binomial1), data = art_data, family = gamma_bamlss(), verbose = FALSE) ba_pred_samples_5 <- preds(ba, newdata = ndata, what = "samples") ba_pred_samples_1 <- preds(ba, newdata = ndata[1, , drop = FALSE], what = "samples") ba_pred_mean_5 <- preds(ba, newdata = ndata, what = "mean") ba_pred_mean_1 <- preds(ba, newdata = ndata[1, , drop = FALSE], what = "mean") ga_pred_mean_5 <- preds(ga, newdata = ndata, what = "mean") ba_mom_samples_5_mean <- moments(ba_pred_samples_5, fam_name = "gaussian", what = "mean") ba_mom_samples_5_ll <- moments(ba_pred_samples_5, fam_name = "gaussian", what = "lowerlimit") ba_mom_samples_5_ul <- moments(ba_pred_samples_5, fam_name = "gaussian", what = "upperlimit") ba_mom_samples_1_ul <- moments(ba_pred_samples_1, fam_name = "gaussian", what = "upperlimit") ba_mom_mean_5_ul <- moments(ba_pred_mean_5, fam_name = "gaussian", what = "mean") dat <- model_fam_data(fam_name = "GA") dat$norma <- dat$norm2 - min(dat$norm2) + 0.01 dat$lognorma <- log(dat$norma) m1 <- gamlss( GA ~ factor(binomial1) + log(norma), sigma.fo = ~ factor(binomial1), nu.fo = ~ log(norma), tau.fo = ~ factor(binomial1) + log(norma), data = dat, family = GA ) m2 <- gamlss( GA ~ factor(binomial1) + lognorma, sigma.fo = ~ factor(binomial1), nu.fo = ~ lognorma, tau.fo = ~ factor(binomial1) + lognorma, data = dat, family = GA ) expect_error(preds(m1, newdata = data.frame(binomial1 = "yes", norma = 50))) expect_error(preds(m2, newdata = data.frame(binomial1 = "yes", lognorma = log(50))))
test_that("Epw Header", { expect_is(idd <- get_epw_idd(), "Idd") expect_error(parse_epw_header("Wrong\n"), class = "eplusr_error_parse_epw_header_name") expect_error(parse_epw_header("LOCATION,;;\n"), class = "eplusr_error_parse_epw_header_line") expect_error(parse_epw_header(paste0("LOCATION", strrep(",", 11), "\n")), class = "eplusr_error_parse_epw_header_field") expect_is(err <- catch_cnd(parse_epw_header("LOCATION\n")), "eplusr_error_validity_check") expect_equal(err$data$missing_object, c( "DESIGN CONDITIONS", "TYPICAL/EXTREME PERIODS", "GROUND TEMPERATURES", "HOLIDAYS/DAYLIGHT SAVINGS", "COMMENTS 1", "COMMENTS 2", "DATA PERIODS" )) expect_is(err <- catch_cnd(parse_epw_header("DESIGN CONDITIONS,a\n")), "eplusr_error_validity_check") expect_equal(err$data$invalid_numeric$class_name, "DESIGN CONDITIONS") expect_equal(err$data$invalid_numeric$field_index, 1L) expect_is(class = "list", h <- parse_epw_header( " LOCATION,city,state,country,type,wmo,1,2,3,4 DESIGN CONDITIONS TYPICAL/EXTREME PERIODS GROUND TEMPERATURES HOLIDAYS/DAYLIGHT SAVINGS,yes,0,0,0 COMMENTS 1 COMMENTS 2 DATA PERIODS,1,1, Data, Friday, 2016/01/01, 2016/12/31 " ) ) expect_equal(h$value[object_id %in% c(2, 3, 4), value_num], rep(0, 3)) expect_equal(h$value[object_id %in% c(6, 7), value_chr], rep(NA_character_, 2)) get_idf_value(get_epw_idd_env(), h, EPW_CLASS[[paste0("comment", 1)]]) expect_warning( { DC <- function (n = 1, m = n) { htg <- c("heating", 1:15) clg <- c("cooling", 1:32) ext <- c("extremes", 1:16) grp <- paste0(rep(c(htg, clg, ext), m), collapse = ",") paste("DESIGN CONDITIONS", n, "src", "", grp, sep = ",", collapse = ",") } h <- parse_epw_header(paste0( " LOCATION,city,state,country,type,wmo,1,2,3,4 ", DC(0, 1), " TYPICAL/EXTREME PERIODS,0,period,typical,1/1,1/2 GROUND TEMPERATURES,0,0.5,,,,", paste0(1:12, collapse = ","), " HOLIDAYS/DAYLIGHT SAVINGS,yes,0,0,0,New year,1/1 COMMENTS 1 COMMENTS 2 DATA PERIODS,1,1,Data,Friday,2016/01/01,2016/12/31,Data1,Friday,2017/01/01,2017/12/31 " )) }, "Number of Design Conditions" ) expect_equal(h$value[object_id == 2, value_num][1], 1L) expect_equal(h$value[object_id == 3, value_num][1], 1L) expect_equal(h$value[object_id == 4, value_num][1], 1L) expect_equal(h$value[object_id == 5, value_num][4], 1L) expect_equal(h$value[object_id == 8, value_num][1], 2L) expect_error( parse_epw_header(paste0( " LOCATION,city,state,country,type,wmo,1,2,3,4 DESIGN CONDITIONS TYPICAL/EXTREME PERIODS,1,period,typical,a,1/2 GROUND TEMPERATURES HOLIDAYS/DAYLIGHT SAVINGS,yes,0,0,0 COMMENTS 1 COMMENTS 2 DATA PERIODS,1,1,Data,Friday,2016/01/01,2016/12/31 " )), class = "eplusr_error_parse_epw" ) expect_error( parse_epw_header(paste0( " LOCATION,city,state,country,type,wmo,1,2,3,4 DESIGN CONDITIONS TYPICAL/EXTREME PERIODS,1,period,typical,1/1,a GROUND TEMPERATURES HOLIDAYS/DAYLIGHT SAVINGS,yes,0,0,0 COMMENTS 1 COMMENTS 2 DATA PERIODS,1,1,Data,Friday,2016/01/01,2016/12/31 " )), class = "eplusr_error_parse_epw" ) expect_error( parse_epw_header(paste0( " LOCATION,city,state,country,type,wmo,1,2,3,4 DESIGN CONDITIONS TYPICAL/EXTREME PERIODS GROUND TEMPERATURES HOLIDAYS/DAYLIGHT SAVINGS,yes,1/1,0,0 COMMENTS 1 COMMENTS 2 DATA PERIODS,1,1,Data,Friday,2016/01/01,2016/12/31 " )), class = "eplusr_error_parse_epw" ) expect_error( parse_epw_header(paste0( " LOCATION,city,state,country,type,wmo,1,2,3,4 DESIGN CONDITIONS TYPICAL/EXTREME PERIODS GROUND TEMPERATURES HOLIDAYS/DAYLIGHT SAVINGS,yes,0,0,1,new year, 2020/01/01 COMMENTS 1 COMMENTS 2 DATA PERIODS,1,1,Data,Friday,2016/01/01,2016/12/31 " )), class = "eplusr_error_parse_epw" ) expect_error( parse_epw_header(paste0( " LOCATION,city,state,country,type,wmo,1,2,3,4 DESIGN CONDITIONS TYPICAL/EXTREME PERIODS GROUND TEMPERATURES HOLIDAYS/DAYLIGHT SAVINGS,yes,0,0,0 COMMENTS 1 COMMENTS 2 DATA PERIODS,1,7,Data,Friday,2016/01/01,2016/12/31 " )), class = "eplusr_error_parse_epw" ) expect_error( parse_epw_header(paste0( " LOCATION,city,state,country,type,wmo,1,2,3,4 DESIGN CONDITIONS TYPICAL/EXTREME PERIODS GROUND TEMPERATURES HOLIDAYS/DAYLIGHT SAVINGS,yes,0,0,0 COMMENTS 1 COMMENTS 2 DATA PERIODS,2,1,Data,Friday,2016/01/01,2016/1/31,Data,Friday,2016/2/01,2016/12/31 " )), class = "eplusr_error_parse_epw" ) expect_error( parse_epw_header(paste0( " LOCATION,city,state,country,type,wmo,1,2,3,4 DESIGN CONDITIONS TYPICAL/EXTREME PERIODS GROUND TEMPERATURES HOLIDAYS/DAYLIGHT SAVINGS,yes,0,0,0 COMMENTS 1 COMMENTS 2 DATA PERIODS,1,1,Data,Friday,2nd Mon in December,2016/12/31 " )), class = "eplusr_error_parse_epw" ) expect_error( parse_epw_header(paste0( " LOCATION,city,state,country,type,wmo,1,2,3,4 DESIGN CONDITIONS TYPICAL/EXTREME PERIODS GROUND TEMPERATURES HOLIDAYS/DAYLIGHT SAVINGS,yes,0,0,0 COMMENTS 1 COMMENTS 2 DATA PERIODS,1,1,Data,Friday,12/1,0 " )), class = "eplusr_error_parse_epw" ) expect_warning( h <- parse_epw_header(paste0( " LOCATION,city,state,country,type,wmo,1,2,3,4 DESIGN CONDITIONS TYPICAL/EXTREME PERIODS GROUND TEMPERATURES HOLIDAYS/DAYLIGHT SAVINGS,yes,0,0,0 COMMENTS 1 COMMENTS 2 DATA PERIODS,1,1,Data,Friday,2016/01/01,12/31 " )) ) expect_equal(h$value[object_id == 8L, value_chr][6], "2016/12/31") expect_error( parse_epw_header(paste0( " LOCATION,city,state,country,type,wmo,1,2,3,4 DESIGN CONDITIONS TYPICAL/EXTREME PERIODS GROUND TEMPERATURES HOLIDAYS/DAYLIGHT SAVINGS,yes,0,0,0 COMMENTS 1 COMMENTS 2 DATA PERIODS,1,1,Data,Friday,2017/01/01,2/29 " )), class = "eplusr_error_parse_epw" ) expect_warning( h <- parse_epw_header(paste0( " LOCATION,city,state,country,type,wmo,1,2,3,4 DESIGN CONDITIONS TYPICAL/EXTREME PERIODS GROUND TEMPERATURES HOLIDAYS/DAYLIGHT SAVINGS,yes,0,0,0 COMMENTS 1 COMMENTS 2 DATA PERIODS,1,1,Data,Friday,01/29,2016/3/21 " )), class = "eplusr_error_parse_epw" ) expect_equal(h$value[object_id == 8L, value_chr][6], " 3/21") expect_warning( h <- parse_epw_header(paste0( " LOCATION,city,state,country,type,wmo,1,2,3,4 DESIGN CONDITIONS TYPICAL/EXTREME PERIODS GROUND TEMPERATURES HOLIDAYS/DAYLIGHT SAVINGS,yes,0,0,0 COMMENTS 1 COMMENTS 2 DATA PERIODS,1,1,Data,Friday,2015/01/29,2015/3/21 " )) ) expect_error( h <- parse_epw_header(paste0( " LOCATION,city,state,country,type,wmo,1,2,3,4 DESIGN CONDITIONS TYPICAL/EXTREME PERIODS GROUND TEMPERATURES HOLIDAYS/DAYLIGHT SAVINGS,yes,0,0,0 COMMENTS 1 COMMENTS 2 DATA PERIODS,1,1,Data,Friday,1/2,1/1 " )), class = "eplusr_error_parse_epw" ) expect_error( suppressWarnings(h <- parse_epw_header(paste0( " LOCATION,city,state,country,type,wmo,1,2,3,4 DESIGN CONDITIONS TYPICAL/EXTREME PERIODS GROUND TEMPERATURES HOLIDAYS/DAYLIGHT SAVINGS,no,0,0,0 COMMENTS 1 COMMENTS 2 DATA PERIODS,1,1,Data,Friday,2016/2/29,2016/3/1 " ))), class = "eplusr_error_parse_epw" ) expect_error( parse_epw_header(paste0( " LOCATION,city,state,country,type,wmo,1,2,3,4 DESIGN CONDITIONS TYPICAL/EXTREME PERIODS GROUND TEMPERATURES HOLIDAYS/DAYLIGHT SAVINGS,yes,0,0,0 COMMENTS 1 COMMENTS 2 DATA PERIODS,2,1,Data,Friday,2016/01/01,2016/1/31,Data1,Friday,2016/1/1,2016/12/31 " )), class = "eplusr_error_parse_epw" ) idd <- get_epw_idd() idd_env <- get_priv_env(idd)$idd_env() idf_env <- parse_epw_header( " LOCATION,city,state,country,type,wmo,1,2,3,4 DESIGN CONDITIONS TYPICAL/EXTREME PERIODS GROUND TEMPERATURES HOLIDAYS/DAYLIGHT SAVINGS,no,0,0,0 COMMENTS 1 COMMENTS 2 DATA PERIODS,1,1, Data, Friday, 01/01, 12/31 " ) idd_env <- get_priv_env(idd)$idd_env() expect_is(class = "list", h <- parse_epw_header( " LOCATION,city,state,country,type,wmo,1,2,3,4 DESIGN CONDITIONS TYPICAL/EXTREME PERIODS GROUND TEMPERATURES HOLIDAYS/DAYLIGHT SAVINGS,no,0,0,0 COMMENTS 1 COMMENTS 2 DATA PERIODS,1,1, Data, Friday, 01/01, 12/31 " ) ) expect_equal(format_epw_header(h), c("LOCATION,city,state,country,type,wmo,1.00,2.00,3.0,4.0", "DESIGN CONDITIONS,0", "TYPICAL/EXTREME PERIODS,0", "GROUND TEMPERATURES,0", "HOLIDAYS/DAYLIGHT SAVINGS,No,0,0,0", "COMMENTS 1,", "COMMENTS 2,", "DATA PERIODS,1,1,Data,Friday, 1/ 1,12/31" ) ) expect_equal(format_epw_meta(h), c("[Location ]: city, state, country", " {N 1\u00B00'}, {E 2\u00B00'}, {UTC+03:00}", "[Elevation]: 4m above see level", "[Data Src ]: type", "[WMO Stat ]: wmo", "[Leap Year]: No", "[Interval ]: 60 mins" ) ) }) test_that("Epw Data", { idd <- get_epw_idd() idd_env <- get_priv_env(idd)$idd_env() idf_env <- parse_epw_header( " LOCATION,city,state,country,type,wmo,1,2,3,4 DESIGN CONDITIONS TYPICAL/EXTREME PERIODS GROUND TEMPERATURES HOLIDAYS/DAYLIGHT SAVINGS,no,0,0,0 COMMENTS 1 COMMENTS 2 DATA PERIODS,1,1, Data, Friday, 01/01, 12/31 " ) expect_error(parse_epw_data("\n\n\n\n\n\n\n\n,,,"), class = "eplusr_error_parse_epw_data_column") hd <- "1\n2\n3\n4\n5\n6\n7\n8" dh <- paste0(rep("a", 35), collapse = ",") rw <- init_idf_value(idd_env, idf_env, "WEATHER DATA", property = "type") val <- paste0(copy(rw)[type == "integer", value_chr := "a"]$value_chr, collapse = ",") expect_error(parse_epw_data(paste(hd, dh, val, sep = "\n")), class = "eplusr_error_parse_epw_data_type") val <- paste0(copy(rw)[type == "real", value_chr := "a"]$value_chr, collapse = ",") expect_error(parse_epw_data(paste(hd, dh, val, sep = "\n")), class = "eplusr_error_parse_epw_data_type") skip_on_cran() path_epw <- file.path(eplus_config(8.8)$dir, "WeatherData", "USA_CA_San.Francisco.Intl.AP.724940_TMY3.epw") expect_is(parsed <- parse_epw_file(path_epw), "list") expect_equal(names(parsed), c("header", "data", "matched")) expect_equal(ncol(parsed$data), 36L) expect_equal(parsed$matched, data.table(index = 1L, row = 1L, num = 8760L)) expect_equal(find_nearst_wday_year(make_date(2019, 1, 14), 1, 2019), 2019) expect_equal(find_nearst_wday_year(make_date(2019, 1, 14), 2, 2019), 2014) }) test_that("EpwDate Class", { expect_equal(get_epw_wday(1), 1) expect_equal(get_epw_wday(1, label = TRUE), "Monday") expect_equal(get_epw_wday(1, label = TRUE, abbr = TRUE), "Mon") expect_equal(get_epw_wday("mon"), 1) expect_equal(get_epw_wday("mon", label = TRUE), "Monday") expect_equal(get_epw_wday("mon", label = TRUE, abbr = TRUE), "Mon") expect_error(epw_date(list()), "Missing method to convert") expect_equal(epw_date(""), init_epwdate_vctr(1)) expect_equal(format(epw_date("")), NA_character_) expect_output(print(epw_date("")), "NA") expect_equal(epw_date(0L), init_epwdate_vctr(1, "0-01-01")) expect_equal(epw_date("0"), init_epwdate_vctr(1, "0-01-01")) expect_equal(epw_date(367), init_epwdate_vctr(1)) expect_equal(format(epw_date(367)), NA_character_) expect_output(print(epw_date(367)), "NA") expect_equal(epw_date(366), init_epwdate_vctr(1, "4-12-31")) expect_equal(format(epw_date(366)), "366") expect_output(print(epw_date(366)), "366th day") expect_equal(epw_date(3), init_epwdate_vctr(1, "4-01-03")) expect_equal(format(epw_date(3)), "3") expect_output(print(epw_date(3)), "3rd day") expect_equal(epw_date("3.10"), init_epwdate_vctr(1, "8-03-10")) expect_equal(epw_date("01/03"), init_epwdate_vctr(1, "8-01-03")) expect_equal(format(epw_date("Apr-01")), " 4/ 1") expect_output(print(epw_date("Apr-01")), "Apr 01") expect_equal(epw_date("01-Apr"), init_epwdate_vctr(1, "8-04-01")) expect_equal(format(epw_date("01-Apr")), " 4/ 1") expect_output(print(epw_date("01-Apr")), "Apr 01") expect_equal(epw_date("2019-01-Apr"), init_epwdate_vctr(1)) expect_equal(format(epw_date("2019-01-Apr")), NA_character_) expect_output(print(epw_date("2019-01-Apr")), "NA") expect_equal(epw_date("2019-Apr-01"), init_epwdate_vctr(1)) expect_equal(format(epw_date("2019-Apr-01")), NA_character_) expect_output(print(epw_date("2019-Apr-01")), "NA") expect_equal(epw_date("4-01-2019"), init_epwdate_vctr(1, "2019-04-01")) expect_equal(format(epw_date("4-01-2019")), "2019/ 4/ 1") expect_output(print(epw_date("4-01-2019")), "2019-04-01") expect_equal(epw_date("last Mon in Jan"), init_epwdate_vctr(1, "16-01-25")) expect_equal(format(epw_date("last Mon in Jan")), "Last Monday in January") expect_output(print(epw_date("last Mon in Jan")), "Last Monday in January") expect_equal(epw_date("1st Mon in Jan"), init_epwdate_vctr(1, "12-01-02")) expect_equal(format(epw_date("1st Mon in Jan")), "1st Monday in January") expect_output(print(epw_date("1st Mon in Jan")), "1st Monday in January") expect_equal(format(epw_date(c("2nd Sunday in March", "1st Sunday in November"))), c("2nd Sunday in March", "1st Sunday in November") ) expect_equal(epw_date("6 Mon in Jan"), init_epwdate_vctr(1)) expect_equal(format(epw_date("6 Mon in Jan")), NA_character_) expect_output(print(epw_date("6 Mon in Jan")), "NA") expect_equal(c(epw_date("1/3"), epw_date("3")), epw_date(c("1/3", "3"))) d <- epw_date(c("1/3", "4")) expect_equal(c(d[2], d[1], epw_date(1.1)), epw_date(c("4", "1/3", "1.1"))) expect_true(is_EpwDate(epw_date("1"))) expect_false(is_EpwDate(Sys.Date())) expect_equal(epw_date(1), as_EpwDate("1")) expect_true(is.na(epw_date(""))) expect_false(is.na(epw_date(1))) expect_equal(length(epw_date(1:5)), 5L) expect_equal(epw_date(1:5)[2L], epw_date(2)) expect_equal(epw_date(1:5)[[3L]], epw_date(3)) expect_equal({d <- epw_date(1:2);d[1] <- epw_date(3);d}, epw_date(c(3, 2))) expect_equal({d <- epw_date(1:2);d[[1]] <- epw_date(3);d}, epw_date(c(3, 2))) })
simulate_data <- function(N, t_data, covariates = c(), names = NULL, relevances = c(1, 1, rep(1, length(covariates))), n_categs = rep(2, sum(covariates %in% c(2, 3))), t_jitter = 0, lengthscales = rep(12, 2 + sum(covariates %in% c(0, 1, 2))), f_var = 1, noise_type = "gaussian", snr = 3, phi = 1, gamma = 0.2, N_affected = round(N / 2), t_effect_range = "auto", t_observed = "after_0", c_hat = 0, dis_fun = "gp_warp_vm", bin_kernel = FALSE, steepness = 0.5, vm_params = c(0.025, 1), continuous_info = list( mu = c(pi / 8, pi, -0.5), lambda = c(pi / 8, pi, 1) ), N_trials = 1, force_zeromean = TRUE) { noise_type <- tolower(noise_type) check_length_geq(t_data, 3) names <- sim.check_covariates(covariates, relevances, names, n_categs) bad <- N_affected > round(N / 2) if (bad) stop("N_affected cannot be greater than round(N/2)!") bad <- is.unsorted(covariates) if (bad) stop("The covariates vector must be increasing!") IN <- sim.create_x( N = N, covariates = covariates, names = names, n_categs = n_categs, t_data = t_data, t_jitter = t_jitter, t_effect_range = t_effect_range, continuous_info = continuous_info ) k <- length(t_data) X_affected <- c(rep(1, N_affected * k), rep(0, (N - N_affected) * k)) COMP <- sim.create_f( dollar(IN, "X"), covariates, relevances, lengthscales, X_affected, dis_fun, bin_kernel, steepness, vm_params, force_zeromean ) FFF <- dollar(COMP, "FFF") f <- rowSums(FFF) SD <- stats::sd(f) f <- if (SD > 0) sqrt(f_var) / SD * f else stats::rnorm(n = length(f)) f <- f + c_hat NOISY <- sim.create_y(noise_type, f, snr = snr, phi = phi, gamma = gamma, N_trials = N_trials ) h <- dollar(NOISY, "h") y <- dollar(NOISY, "y") noise <- y - h dat <- cbind(dollar(IN, "X"), y) rownames(dat) <- 1:(N * k) comp <- cbind(FFF, f, h, noise, y) OBSERVED <- sim.data_to_observed(dat, t_observed) SSR <- sum((h - mean(h))^2) SSE <- sum(noise^2) teff_true <- dollar(IN, "onsets") teff_obs <- dollar(OBSERVED, "onsets_observed") teff <- list(true = teff_true, observed = teff_obs) info <- list( par_ell = lengthscales, par_cont = dollar(IN, "par_cont"), p_signal = SSR / (SSR + SSE), msg = dollar(IN, "info"), noise_type = noise_type ) new("lgpsim", data = dollar(OBSERVED, "dat"), response = "y", components = comp, kernel_matrices = dollar(COMP, "KKK"), effect_times = teff, info = info ) } sim.create_y <- function(noise_type, f, snr, phi, gamma, N_trials) { L <- length(f) y <- rep(0, L) h <- link_inv(f, noise_type) if (noise_type == "gaussian") { sf <- stats::var(f) sigma_n <- 1 / sqrt(snr) * sqrt(sf) y_n <- stats::rnorm(n = L, mean = 0, sd = 1) y_n <- sigma_n * (y_n - mean(y_n)) / stats::sd(y_n) y <- h + y_n } else if (noise_type == "poisson") { y <- stats::rpois(n = L, lambda = h) } else if (noise_type == "nb") { y <- stats::rnbinom(n = L, mu = h, size = phi) } else if (noise_type == "binomial") { y <- stats::rbinom(n = L, size = N_trials, prob = h) h <- N_trials * h } else if (noise_type == "bb") { check_interval(gamma, 0, 1) gam_t <- (1 - gamma) / gamma alpha <- gam_t * h beta <- gam_t * (1.0 - h) prob <- stats::rbeta(n = L, alpha, beta) y <- stats::rbinom(n = L, size = N_trials, prob = prob) h <- N_trials * h } else { stop("Unknown noise_type! Please report a bug.") } NOISY <- list(h = h, y = y) return(NOISY) } sim.create_x <- function(N, covariates, names, n_categs, t_data, t_jitter, t_effect_range, continuous_info) { D <- sim.create_x_D(covariates) checked <- sim.create_x_check(n_categs, D, t_data, t_effect_range) k <- length(t_data) id <- rep(1:N, each = k) id <- as.factor(id) age <- sim.draw_measurement_times(N, t_data, t_jitter) X <- data.frame(id, age) et_range <- dollar(checked, "t_effect_range") parsed_dis <- sim.create_x_dis_age(X, k, N, D, age, et_range) dis_age <- parsed_dis$dis_age X <- parsed_dis$X cinfo <- continuous_info parsed_x <- sim.create_x_other(X, k, N, D, n_categs, dis_age, cinfo) X <- dollar(parsed_x, "X") colnames(X) <- names list( info = dollar(checked, "info"), onsets = dollar(parsed_dis, "teff"), N_cases = dollar(parsed_dis, "N_cases"), par_cont = dollar(parsed_x, "par_cont"), X = X ) } sim.create_f <- function(X, covariates, relevances, lengthscales, X_affected, dis_fun, bin_kernel, steepness, vm_params, force_zeromean) { i4 <- which(covariates == 4) covariates[i4] <- 3 D <- c(1, 2, covariates + 3) useMaskedVarianceKernel <- TRUE if (is.character(dis_fun)) { if (dis_fun == "gp_warp_vm") { useMaskedVarianceKernel <- TRUE } else if (dis_fun == "gp_warp") { useMaskedVarianceKernel <- FALSE } else { msg <- paste0("dis_fun must be gp_warp or gp_warp_vm! found = ", dis_fun) stop(msg) } } KK <- sim.kernels( X, D, lengthscales, X_affected, bin_kernel, useMaskedVarianceKernel, steepness, vm_params ) labs <- sim.name_components(D, colnames(X)) FFF <- sim.draw_components(KK) if (sum(D == 3) == 1) { i_dis <- which(labs == "diseaseAge") } else { i_dis <- -1 } if (i_dis > 0 && is.function(dis_fun)) { FFF[, i_dis] <- sim.disease_effect(X[, 1], X[, 3], dis_fun) } else { } if (!bin_kernel) { i_zm <- c(which(D == 1), which(D == 5)) i_skip <- c(i_dis, i_zm) } else { i_skip <- c(i_dis) } FFF <- sim.scale_relevances(FFF, relevances, force_zeromean = force_zeromean, i_skip ) colnames(FFF) <- labs ret <- list(FFF = data.frame(FFF), KKK = KK) return(ret) } sim.kernels <- function(X, types, lengthscales, X_affected, bin_kernel, useMaskedVarianceKernel, steepness, vm_params) { pos_class <- 1 n <- dim(X)[1] d <- length(types) KK <- array(0, c(n, n, d)) t <- X[, which(types == 2)] id <- X[, which(types == 1)] n_ell <- sum(types != 6) d_ell <- length(lengthscales) if (d_ell != n_ell) { stop("lengthscales has length ", d_ell, ", should be ", n_ell) } j_ell <- 0 ell <- lengthscales for (j in 1:d) { xj <- X[, j] if (types[j] == 1) { j_ell <- j_ell + 1 N_tot <- length(unique(xj)) Kj <- kernel_zerosum(id, id, N_tot) * kernel_eq(t, t, ell = ell[j_ell]) } else if (types[j] == 2) { j_ell <- j_ell + 1 Kj <- kernel_eq(t, t, ell = ell[j_ell]) } else if (types[j] == 3) { j_ell <- j_ell + 1 ell_ns <- ell[j_ell] Kj <- kernel_bin(X_affected, X_affected, pos_class) * kernel_ns(xj, xj, ell = ell_ns, a = steepness) if (useMaskedVarianceKernel) { M <- kernel_varmask(xj, xj, steepness, vm_params) Kj <- Kj * M } } else if (types[j] == 4) { j_ell <- j_ell + 1 Kj <- kernel_eq(xj, xj, ell = ell[j_ell]) } else if (types[j] == 5) { j_ell <- j_ell + 1 if (bin_kernel) { Kj <- kernel_bin(xj, xj, pos_class) * kernel_eq(t, t, ell = ell[j_ell]) } else { N_cat <- length(unique(xj)) Kj <- kernel_zerosum(xj, xj, N_cat) * kernel_eq(t, t, ell = ell[j_ell]) } } else if (types[j] == 6) { if (bin_kernel) { Kj <- kernel_bin(xj, xj, pos_class) } else { N_cat <- length(unique(xj)) Kj <- kernel_zerosum(xj, xj, N_cat) } } else { stop("types contains invalid values") } KK[, , j] <- Kj } return(KK) } sim.check_covariates <- function(covariates, relevances, names, n_cat) { d0 <- sum(covariates == 0) if (d0 > 1) stop("There can be only one diseaseAge component!") L1 <- length(covariates) L2 <- length(relevances) L3 <- sum(covariates %in% c(2, 3)) if ((L1 + 2) != L2) stop("length(relevances) must be length(covariates) + 2") if (L3 != length(n_cat)) stop("The argument n_cat has invalid length!") if (!is.null(names)) { check_lengths(names, covariates) names <- c("id", "age", names) } else { names <- sim.generate_names(covariates) } check_non_negative_all(relevances) return(names) } sim.generate_names <- function(covariates) { names <- c("id", "age") def <- c("x", "z", "offset", "group") D <- sim.create_x_D(covariates) if (D[1] == 1) { names <- c(names, "diseaseAge") } if (D[2] > 0) { str <- paste0(def[1], 1:D[2]) names <- if (D[2] > 1) c(names, str) else c(names, def[1]) } if (D[3] > 0) { str <- paste0(def[2], 1:D[3]) names <- if (D[3] > 1) c(names, str) else c(names, def[2]) } if (D[4] > 0) { str <- paste0(def[3], 1:D[4]) names <- if (D[4] > 1) c(names, str) else c(names, def[3]) } if (D[5] > 0) { names <- c(names, "group") } return(names) } sim.data_to_observed <- function(dat, t_observed) { flag <- !("diseaseAge" %in% colnames(dat)) id <- dollar(dat, "id") uid <- unique(id) N <- length(uid) onsets_observed <- rep(NaN, N) names(onsets_observed) <- c(1:N) if (flag) { ret <- list(dat = dat, onsets_observed = onsets_observed) return(ret) } else { age <- dollar(dat, "age") dis_age <- dollar(dat, "diseaseAge") j <- 0 for (ID in uid) { j <- j + 1 inds <- which(id == ID) age_i <- age[inds] dag_i <- dis_age[inds] if (is.nan(dag_i[1])) { } else { irem <- which(dag_i > 0) rem <- age_i[irem] t0_real <- -dag_i[1] + age_i[1] if (is.function(t_observed)) { oo <- sim.apply_obs_onset_fun(t_observed, t0_real, rem) t0 <- dollar(oo, "t0") idx0 <- dollar(oo, "idx0") } else { parsed <- sim.parse_t_obs(t_observed) typ <- dollar(parsed, "type") val <- dollar(parsed, "value") if (typ == "random") { idx0 <- sim.rtgeom(length(irem), val) sim.check_too_far(idx0, rem) t0 <- rem[idx0] } else if (typ == "after") { idx0 <- val + 1 sim.check_too_far(idx0, rem) t0 <- rem[idx0] } else { t0 <- t0_real } } onsets_observed[j] <- t0 dat$diseaseAge[inds] <- age_i - t0 } } ret <- list(dat = dat, onsets_observed = onsets_observed) return(ret) } } sim.apply_obs_onset_fun <- function(fun_obs, t0_real, rem) { t_possible <- fun_obs(t0_real) inds0 <- which(rem > t_possible) if (length(inds0) < 1) { stop("There are no data points after t = ", t_possible, "!") } else { idx0 <- inds0[1] t0 <- rem[idx0] } list(idx0 = idx0, t0 = t0) } sim.check_too_far <- function(idx, rem) { check_length(idx, 1) if (idx > length(rem)) { stop("Not enough data points to go that far!") } TRUE } sim.rtgeom <- function(s, p, n = 1) { s_seq <- 0:(s - 1) prob <- p^s_seq r <- sample.int(n = s, size = n, prob = prob, replace = TRUE) return(r) } sim.parse_t_obs <- function(t_observed) { parts <- strsplit(t_observed, "_")[[1]] if (parts[1] == "after") { type <- "after" } else if (parts[1] == "random") { type <- "random" } else if (parts[1] == "exact") { type <- "exact" } else { stop("unknown keyword ", parts[1]) } value <- as.numeric(parts[2]) return(list(type = type, value = value)) } sim.name_components <- function(types, names) { d <- length(types) componentNames <- rep("foo", d) for (j in 1:d) { if (types[j] == 1) { lab <- "id*age" } else if (types[j] == 5) { lab <- paste(names[j], "*age", sep = "") } else { lab <- names[j] } componentNames[j] <- lab } return(componentNames) } sim.scale_relevances <- function(FFF, relevances, force_zeromean, i_skip) { d <- dim(FFF)[2] check_non_negative_all(relevances) for (j in 1:d) { std <- stats::sd(FFF[, j]) if (std > 0) { FFF[, j] <- sqrt(relevances[j]) / std * FFF[, j] if (force_zeromean && !(j %in% i_skip)) { FFF[, j] <- FFF[, j] - mean(FFF[, j]) } } } return(FFF) } sim.draw_components <- function(KK) { n <- dim(KK)[1] d <- dim(KK)[3] mu0 <- rep(0, n) FFF <- matrix(0, n, d) for (j in 1:d) { K <- KK[, , j] fj <- MASS::mvrnorm(1, mu0, K) FFF[, j] <- fj } return(FFF) } sim.disease_effect <- function(X_id, X_disAge, dis_fun) { n <- length(X_id) uid <- unique(X_id) F_disAge <- rep(0, n) for (id in uid) { inds <- which(X_id == id) da <- X_disAge[inds] if (!is.nan(da[1])) { F_disAge[inds] <- dis_fun(da) } } return(F_disAge) } sim.create_x_D <- function(covariates) { D <- rep(0, 5) D[1] <- sum(covariates == 0) D[2] <- sum(covariates == 1) D[3] <- sum(covariates == 2) D[4] <- sum(covariates == 3) D[5] <- sum(covariates == 4) return(D) } sim.create_x_check <- function(n_categs, D, t_data, t_effect_range) { L1 <- length(n_categs) L2 <- sum(D[3:4]) msg <- paste0( "Length of <n_categs> must be same as the number of 2's", " and 3's in the <covariates> vector!", " Found = ", L1, ", should be = ", L2, "." ) if (L1 != L2) { stop(msg) } n_invalid <- sum(n_categs <= 1) if (n_invalid > 0) { stop("<n_categs> must only contain integers larger than 1!") } info <- "" if (is.character(t_effect_range)) { if (t_effect_range == "auto") { ran <- range(t_data) mrn <- mean(ran) t_effect_range <- c(mrn, mrn) if (D[1] == 1) { info <- paste0( "Disease effect time range set to [", t_effect_range[1], ", ", t_effect_range[2], "].\n" ) } } else { stop("invalid t_effect_range!") } } list( t_effect_range = t_effect_range, info = info ) } sim.create_x_dis_age <- function(X, k, N, D, age, t_effect_range) { if (D[1] > 0) { N_cases <- round(N / 2) if (is.function(t_effect_range)) { teff <- rep(0, N_cases) for (j in 1:N_cases) { teff[j] <- t_effect_range() } } else { teff <- stats::runif(N_cases, min = t_effect_range[1], max = t_effect_range[2] ) } teff <- c(teff, rep(NaN, N - N_cases)) dis_age <- sim.onsets_to_dis_age(teff, age, k) X <- cbind(X, dis_age) } else { dis_age <- NULL teff <- rep(NaN, N) N_cases <- NaN } lt <- length(teff) names(teff) <- seq_len(lt) list( X = X, teff = teff, N_cases = N_cases, dis_age = dis_age ) } sim.create_x_other <- function(X, k, N, D, n_categs, dis_age, continuous_info) { if (D[2] > 0) { mu <- dollar(continuous_info, "mu") lambda <- dollar(continuous_info, "lambda") CONT <- sim.draw_continuous(N, k, D[2], mu, lambda) cont <- dollar(CONT, "C") par_cont <- list( a = dollar(CONT, "A"), b = dollar(CONT, "B"), offset = dollar(CONT, "OFS") ) X <- cbind(X, cont) } else { par_cont <- list(a = NULL, b = NULL, offset = NULL) } if ((D[3] + D[4]) > 0) { categ <- sim.draw_categorical(N, k, n_categs) X <- cbind(X, categ) } if (D[5] > 0) { if (D[1] == 0) { stop("cannot include a 4 in covariates if 0 is not included!") } if (D[5] == 1) { group <- as.factor(as.numeric(!is.nan(dis_age))) X <- cbind(X, group) } else { stop("only one 4 can be included in the covariates vector") } } list(X = X, par_cont = par_cont) } sim.draw_measurement_times <- function(N, t_data, t_jitter) { k <- length(t_data) age <- rep(0, N * k) check_non_negative(t_jitter) for (i in 1:N) { idx <- (1 + (i - 1) * k):(i * k) t <- t_data + stats::rnorm(k, mean = 0, sd = t_jitter) age[idx] <- sort(t) } return(age) } sim.onsets_to_dis_age <- function(onsets, age, k) { N <- length(onsets) n <- N * k diseaseAge <- rep(0, n) for (i in 1:N) { inds <- ((i - 1) * k + 1):(i * k) if (!is.nan(onsets[i])) { diseaseAge[inds] <- age[inds] - onsets[i] } else { diseaseAge[inds] <- NaN } } return(diseaseAge) } sim.draw_continuous <- function(N, k, D, mu, lambda) { C <- matrix(0, N * k, D) A <- matrix(0, N, D) B <- matrix(0, N, D) OFS <- matrix(0, N, D) for (j in 1:D) { for (i in c(1:N)) { inds <- ((i - 1) * k + 1):(i * k) ttt <- seq(0, 2 * pi, length.out = k) a <- mu[1] + lambda[1] * stats::runif(1) b <- mu[2] + lambda[2] * stats::runif(1) ofs <- mu[3] + lambda[3] * stats::runif(1) A[i, j] <- a B[i, j] <- b OFS[i, j] <- ofs C[inds, j] <- sin(a * ttt + b) + ofs } } return(list(A = A, B = B, OFS = OFS, C = C)) } sim.draw_categorical <- function(N, k, v) { D <- length(v) C <- matrix(0, N, D) for (i in seq_len(D)) { C[, i] <- sample.int(v[i], N, replace = TRUE) } C_seq <- seq_len(nrow(C)) rows <- rep(C_seq, each = k) C <- data.frame(C[rows, ]) for (i in seq_len(D)) { C[, i] <- as.factor(C[, i]) } return(C) }
\donttest{ data( 'ticks' ) strategy_source = system.file( package = 'QuantTools', 'examples/bbands.cpp' ) Rcpp::sourceCpp( strategy_source ) parameters = data.table( n = 100, k = 0.5, timeframe = 60 ) options = list( cost = list( tradeAbs = -0.01 ), latency = 0.1 ) test_summary = bbands( ticks, parameters, options, fast = TRUE ) print( test_summary ) test = bbands( ticks, parameters, options, fast = FALSE ) indicators = plot_dts( test$indicators, test$orders[ side == 'buy' , .( time_processed, buy = price_exec ) ], test$orders[ side == 'sell', .( time_processed, sell = price_exec ) ] )$ lines( c( 'lower', 'sma', 'upper' ) )$ lines( c( 'buy', 'sell' ), type = 'p', pch = c( 24, 25 ), col = c( 'blue', 'red' ) ) performance = plot_dts( test$indicators[, .( time, pnl = pnl * 100, drawdown = drawdown * 100 ) ] )$ lines( c( 'pnl', 'drawdown' ), c( '% pnl', '% drawdown' ), col = c( 'darkolivegreen', 'darkred' ) ) interval = '2016-01-19 12/13' par( mfrow = c( 2, 1 ), oma = c( 5, 4, 2, 4 ) + 0.1, mar = c( 0, 0, 0, 0 ) ) indicators $limits( tlim = interval )$style( time = list( visible = FALSE ) ) performance$limits( tlim = interval ) title( 'Bollinger Bands', outer = TRUE ) par( mfrow = c( 1, 1 ), oma = c( 0, 0, 0, 0 ), mar = c( 5, 4, 4, 2 ) + 0.1 ) }
el.test.wt2 <- function(x, wt, mu, maxit=25, gradtol=1e-7, Hessian = FALSE, svdtol = 1e-9, itertrace=FALSE ){ x <- as.matrix(x) n <- nrow(x) p <- ncol(x) mu <- as.vector(mu) if( length(mu) !=p ) stop("mu must have same dimension as observation vectors.") if( n <= p ) stop("Need more observations than length(mu) in el.test.wt2().") z <- t( t(x) -mu ) wt <- as.vector(wt) if( length(wt) != n ) stop("length of wt must be n=nrow(x)") if( any(wt < 0) ) stop("wt must be >= 0") allw <- sum(wt) TINY <- sqrt( .Machine$double.xmin ) scale <- mean( abs(z) ) + TINY z <- z/scale lam <- rep(0,p) if(svdtol < TINY ) svdtol <- TINY if(gradtol < TINY) gradtol <- TINY nwts <- c( 3^-c(0:3), rep(0,12) ) gwts <- 2^( -c(0:(length(nwts)-1))) gwts <- (gwts^2 - nwts^2)^.5 gwts[12:16] <- gwts[12:16] * 10^-c(1:5) nits <- 0 gsize <- gradtol + 1 while( nits<maxit && gsize > gradtol ){ arg <- allw + z %*% lam wts2 <- as.vector( -llogpp(arg, 1/n) )^.5 grad <- gradf(z, wt, lam) gsize <- mean( abs(grad) ) wtwts2 <- sqrt(wt)*wts2 hess <- z*wtwts2 svdh <- svd( hess, nu=0 ) if( min(svdh$d) < max(svdh$d)*svdtol ) svdh$d <- svdh$d + max(svdh$d)*svdtol nstep <- as.vector( svdh$v %*% (t(svdh$v)/(svdh$d)^2) %*% grad ) gstep <- grad if( sum(nstep^2) < sum(gstep^2) ) gstep <- gstep*(sum(nstep^2)^.5/sum(gstep^2)^.5) ninner <- 0 for( i in 1:length(nwts) ){ ngrad <- gradf(z,wt, lam+nwts[i]*nstep+gwts[i]*gstep ) ngsize <- mean( abs(ngrad) ) if( ngsize < gsize ){ lam <- lam+nwts[i]*nstep+gwts[i]*gstep ninner <- i break } } nits <- nits+1 if( ninner==0 )nits <- maxit if( itertrace ) print( c(lam, ngrad, gsize, ninner) ) } Hess <- NA if( Hessian ) Hess <- t(hess)%*%hess*scale^2 list( prob= as.vector(wt/as.vector(allw + z %*% lam)), lambda = lam/scale, grad=grad*scale, hess=Hess, nits=nits ) } gradf <- function(z,wt,lam) { allw <- sum(wt) arg <- allw + z %*% lam n <- length(wt) wts1 <- as.vector( llogp(arg, 1/n) ) wtwts1<- wt*wts1 grad <- as.matrix(z*wtwts1) colSums(grad) }
context("text and number input") test_that("id argument", { expect_silent(textInput(id = "id")) expect_silent(textInput(id = NULL)) expect_silent(numberInput(id = "id")) expect_silent(numberInput(id = NULL)) expect_error(textInput(id = NA)) expect_error(numberInput(id = NA)) }) test_that("min, max, step added to <input> child element", { element <- numberInput(id = "ID", min = 1, max = 10, step = 2) expect_equal(element$children[[1]]$attribs$min, 1) expect_equal(element$children[[1]]$attribs$max, 10) expect_equal(element$children[[1]]$attribs$step, 2) expect_match(as.character(element), 'min="1" max="10" step="2"') }) test_that("has dependencies", { expect_dependencies(textInput(id = "ID")) })
set.seed(1234) n = 1000 p = 1000 k = 60 amplitude = 4.5 mu = rep(0,p) rho = 0.25 Sigma = toeplitz(rho^(0:(p-1))) X = matrix(rnorm(n*p),n) %*% chol(Sigma) nonzero = sample(p, k) beta = amplitude * (1:p %in% nonzero) / sqrt(n) y.sample = function(X) X %*% beta + rnorm(n) y = y.sample(X) library(knockoff) result = knockoff.filter(X, y) print(result) fdp = function(selected) sum(beta[selected] == 0) / max(1, length(selected)) fdp(result$selected) gaussian_knockoffs = function(X) create.gaussian(X, mu, Sigma) result = knockoff.filter(X, y, knockoffs=gaussian_knockoffs) print(result) fdp(result$selected) result = knockoff.filter(X, y, knockoffs = gaussian_knockoffs, statistic = stat.random_forest, fdr=0.2) print(result) fdp(result$selected) my_knockoff_stat = function(X, X_k, y) { abs(t(X) %*% y) - abs(t(X_k) %*% y) } result = knockoff.filter(X, y, knockoffs = gaussian_knockoffs, statistic = my_knockoff_stat) print(result) fdp(result$selected) my_lasso_stat = function(...) stat.glmnet_coefdiff(..., nlambda=100) result = knockoff.filter(X, y, knockoffs = gaussian_knockoffs, statistic = my_lasso_stat) print(result) fdp(result$selected) create_knockoffs = function(X) { create.second_order(X, shrink=T) } result = knockoff.filter(X, y, knockoffs=create_knockoffs) print(result) fdp(result$selected) gaussian_knockoffs = function(X) create.second_order(X, method='sdp', shrink=T) result = knockoff.filter(X, y, knockoffs = gaussian_knockoffs) print(result) fdp(result$selected) gaussian_knockoffs = function(X) create.second_order(X, method='equi', shrink=T) result = knockoff.filter(X, y, knockoffs = gaussian_knockoffs) print(result) fdp(result$selected)
context("Compiled") test_that("Compiled code coverage is reported including code in headers", { skip_on_cran() cov <- as.data.frame(package_coverage("TestCompiled", relative_path = TRUE)) simple_cc <- cov[cov$filename == "src/simple.cc", ] expect_equal(simple_cc[simple_cc$first_line == "10", "value"], 4) expect_equal(simple_cc[simple_cc$first_line == "16", "value"], 3) expect_equal(simple_cc[simple_cc$first_line == "19", "value"], 0) expect_equal(simple_cc[simple_cc$first_line == "21", "value"], 1) expect_equal(simple_cc[simple_cc$first_line == "23", "value"], 4) simple_h <- cov[cov$filename == "src/simple-header.h", ] expect_equal(simple_h[simple_h$first_line == "12", "value"], 4) expect_equal(simple_h[simple_h$first_line == "18", "value"], 3) expect_equal(simple_h[simple_h$first_line == "21", "value"], 0) expect_equal(simple_h[simple_h$first_line == "23", "value"], 1) expect_equal(simple_h[simple_h$first_line == "25", "value"], 4) expect_true(all(unique(cov$filename) %in% c("R/TestCompiled.R", "src/simple-header.h", "src/simple.cc", "src/simple4.cc"))) }) test_that("Source code subdirectories are found", { skip_on_cran() cov <- as.data.frame(package_coverage("TestCompiledSubdir", relative_path = TRUE)) expect_equal(cov[cov$first_line == "9", "value"], 4) expect_equal(cov[cov$first_line == "15", "value"], 3) expect_equal(cov[cov$first_line == "18", "value"], 0) expect_equal(cov[cov$first_line == "20", "value"], 1) expect_equal(cov[cov$first_line == "22", "value"], 4) })
library(RXMCDA) tree = newXMLDoc() newXMLNode("xmcda:XMCDA", namespace = c("xsi" = "http://www.w3.org/2001/XMLSchema-instance", "xmcda" = "http://www.decision-deck.org/2009/XMCDA-2.0.0"), parent=tree) root<-getNodeSet(tree, "/xmcda:XMCDA") criteria<-newXMLNode("criteria", parent=root[[1]], namespace=c()) newXMLNode("criterion",attrs = c(id="g1"), parent=criteria, namespace=c()) newXMLNode("criterion",attrs = c(id="g2"), parent=criteria, namespace=c()) y<-getNodeSet(tree,"//criteria") stopifnot(getCriteriaIDs(y[[1]])[[1]] == c("g1","g2"))
ordinal_ppmx <- function(y, co, X=NULL,Xpred=NULL, meanModel=1, cohesion=1, M=1, PPM = FALSE, similarity_function=1, consim=1, calibrate=0, simParms=c(0.0, 1.0, 0.1, 1.0, 2.0, 0.1, 1), modelPriors=c(0, 10, 1, 1), mh=c(0.5, 0.5), draws=1100,burn=100,thin=1, verbose=FALSE){ out <- NULL if(!is.data.frame(X) & !is.null(X)) X <- data.frame(X) if(!is.data.frame(Xpred) & !is.null(Xpred)){ Xpred <- data.frame(Xpred); colnames(Xpred) <- colnames(X) } cnames <- colnames(X) if(is.null(X) & meanModel != 1){ stop("No training covariates are provided and a regression is included in the mean model") } nout <- (draws-burn)/thin nobs <- length(y) Xcon <- cbind(rep(0,1)); Xconp <- cbind(rep(0,1)); ncon <- 0 Mcon <- cbind(rep(0,1)) Mconp <- cbind(rep(0,1)); Xcat <- cbind(rep(0,1)); Xcatp <- cbind(rep(0,1)); Cvec <- 0 ncat <- 0 Mcat <- cbind(rep(0,1)) Mcatp <- cbind(rep(0,1)) nmissing <- 0 npred <- 0 if(!(is.null(X) & is.null(Xpred))){ nxobs <- ifelse(is.null(X), 0, nrow(X)) npred <- ifelse(is.null(Xpred), 0, nrow(Xpred)) Xall <- rbind(X, Xpred) nmissing <- sum(is.na(Xall)) if(nmissing > 0){ Mall <- 1*is.na(Xall) } relab <- function(x) as.numeric(as.factor(as.character(x))) - 1 classes <- sapply(Xall, class) catvars <- classes %in% c("factor","character") if(nxobs > 0){ if(sum(!catvars) > 0){ mn <- apply(Xall[,!catvars, drop=FALSE],2,mean, na.rm=TRUE) sd <- apply(Xall[,!catvars, drop=FALSE],2,sd, na.rm=TRUE) if(sum(round(mn + sd,10) == 1) != length(mn)){ message("Continuous covariates are not standardized.") } Xconstd <- apply(Xall[,!catvars, drop=FALSE], 2, scale) Xcon <- Xconstd[1:nobs,,drop=FALSE]; ncon <- ncol(Xcon) if(nmissing > 0) Mcon <- Mall[1:nobs, !catvars, drop=FALSE] }else{ Xcon <- cbind(rep(0,nobs)); ncon <- 0 if(nmissing > 0) Mcon <- cbind(rep(0,nobs)) } if(sum(catvars) > 0){ Xcatall <- apply(Xall[, catvars,drop=FALSE], 2, relab) if(nmissing > 0) Mcat <- Mall[1:nobs, catvars, drop=FALSE] Xcat <- Xcatall[1:nobs,,drop=FALSE]; Cvec <- apply(Xcat,2,function(x)length(unique(x))) ncat <- ncol(Xcat) }else{ Xcat <- cbind(rep(0,nobs)); if(nmissing > 0) Mcat <- cbind(rep(0,nobs)) Cvec <- 0 ncat <- 0 } } if(npred > 0){ if(sum(!catvars) > 0){ Xconstd <- apply(Xall[,!catvars, drop=FALSE], 2, scale) Xconp <- Xconstd[(nrow(Xall)-npred+1):nrow(Xall),,drop=FALSE]; if(nmissing > 0) Mconp <- Mall[(nrow(Xall)-npred+1):nrow(Xall), !catvars, drop=FALSE] ncon <- ncol(Xconp) } else { Xconp <- cbind(rep(0,npred)); if(nmissing > 0) Mconp <- cbind(rep(0,npred)); ncon <- 0 } if(sum(catvars) > 0){ Xcatall <- apply(Xall[, catvars,drop=FALSE], 2, relab) Xcatp <- Xcatall[(nrow(Xall)-npred+1):nrow(Xall),,drop=FALSE]; if(nmissing > 0) Mcatp <- Mall[(nrow(Xall)-npred+1):nrow(Xall), catvars, drop=FALSE] ncat <- ncol(Xcatp) Cvec <- apply(Xcatall,2,function(x)length(unique(x))) } else { Xcatp <- cbind(rep(0,npred)); ncat <- 0 Cvec <- 0 if(nmissing > 0) Mcatp <- cbind(rep(0,npred)); } } } if(nmissing > 0 & similarity_function == 4){ stop("Gower's dissimilarity similarity function cannot be used with missing covariates") } if(nmissing == 0 & similarity_function == 4){ dissim <- as.matrix(cluster::daisy(Xall, metric="gower")) dissimtn <- dissim[1:nobs, 1:nobs] dissimtt <- dissim[-c(1:nobs), 1:nobs] }else{ dissimtn <- 0 dissimtt <- 0 } mu <- sig2 <- Si <- like <- ispred <- zi <- isordpred <- matrix(1,nrow=nout,ncol=nobs) mu0 <- sig20 <- nclus <- rep(1,nout) ppred <- predclass <- ordppred <- rbpred <- rbordpred <- matrix(1, nrow=nout, ncol=npred) predclass_prob <- matrix(1, nrow=nout, ncol=npred*nobs) WAIC <- lpml <- rep(1,1) beta <- matrix(0, nrow=nout, ncol=ncon+ncat) nordcat <- length(co) if(nmissing > 0){ Xcon[is.na(Xcon)] <- 999;Xconp[is.na(Xconp)] <- 999; Xcat[is.na(Xcat)] <- 999;Xcatp[is.na(Xcatp)] <- 999; message(" There are a total of ", nmissing, " missing covariate values. \n They will be accommodated using extentions to the ppmx model detailed in Page et. al (2020).") run <- .Call("ORDINAL_PPMX_MISSING", as.integer(y), as.double(co), as.integer(nobs), as.integer(nordcat), as.double(t(Xcon)), as.integer(t(Mcon)), as.integer(ncon), as.integer(t(Xcat)), as.integer(t(Mcat)), as.integer(ncat), as.integer(Cvec), as.integer(npred), as.double(t(Xconp)), as.integer(t(Mconp)), as.integer(t(Xcatp)), as.integer(t(Mcatp)), as.double(M), as.integer(meanModel), as.double(modelPriors), as.double(simParms), as.integer(PPM), as.integer(cohesion), as.integer(similarity_function), as.integer(consim), as.double(dissimtn), as.double(dissimtt), as.integer(calibrate), as.double(mh), as.integer(verbose), as.integer(draws), as.integer(burn), as.integer(thin)) } else { run <- .Call("ORDINAL_PPMX", as.integer(y), as.double(co), as.integer(nobs), as.integer(nordcat), as.double(t(Xcon)), as.integer(ncon), as.integer(t(Xcat)), as.integer(ncat), as.integer(Cvec), as.integer(npred), as.double(t(Xconp)), as.integer(t(Xcatp)), as.double(M), as.integer(meanModel), as.double(modelPriors), as.double(simParms), as.integer(PPM), as.integer(cohesion), as.integer(similarity_function), as.integer(consim), as.double(dissimtn), as.double(dissimtt), as.integer(calibrate), as.double(mh), as.integer(verbose), as.integer(draws), as.integer(burn), as.integer(thin)) } if(meanModel == 2) colnames(run$beta) <- c(cnames[!catvars], cnames[catvars]) if(meanModel == 1) run <- run[-3] out <- run if(nmissing > 0) out$Missmat <- Mall out }
balances <- function(x, y) { validate <- function(y) { if (any(dim(y) != c(dim(x)[2],dim(x)[2] - 1)) || any(abs(y) > 1)) stop("Size of partition matrix does not match or invalid entry!") act <- 1:nrow(y) for (i in 1:ncol(y)) { if (any(y[act,i] == 0)) { tmp <- which(apply(y[act,], 2,function(x) all(x != 0))) tmp <- tmp[tmp > i] if (length(tmp) != 1) stop("Binary Partition not valid!") y[, c(i, tmp)] <- y[, c(tmp, i)] } if (length(unique((y[act, i]))) == 1 || any(y[-act, i] != 0)) stop("Binary Partition not valid!") y[act,] <- y[act[order(y[act, i], decreasing = TRUE)],] count <- 0 act <- 1 for (j in 2:nrow(y)) { if (all(y[(j - 1), 1:i] == y[j, 1:i])) { count <- count + 1 act <- c(act, j) } else if (count == 0) act <- j else break } } return(TRUE) } createv <- function(x) { for (i in 1:ncol(x)) { p_ind <- which(x[,i] > 0) m_ind <- which(x[,i] < 0) p <- length(p_ind) m <- length(m_ind) x[p_ind, i] <- 1 / p * sqrt((m * p) / (m + p)) x[m_ind, i] <- (-1 / m * sqrt((m * p) / (m + p))) } colnames(x) <- paste("v", 1:ncol(x)) return(x) } if (validate(y)) { V <- as.matrix(createv(y)) balance <- as.matrix(cenLR(x)$x.clr) %*% V colnames(balance) <- paste("z", 2:ncol(x) - 1) } res <- list(balances = balance, V = as.matrix(V)) return(res) }
emcljgl = function(Y, p, ncluster, lambda1, lambda2, threshold, MAX_iter, tau, graph,seed){ L=ncluster n=nrow(Y) set.seed(seed) memship_ini = sample(seq(1,ncluster),n, replace =T) clust_size = as.numeric(table(memship_ini)) center_ini = matrix(0,nrow =ncluster, ncol=p) for(l in 1:L){ center_ini[l,] = apply(Y[memship_ini==l,], 2, mean) } pie = clust_size/n dat1 = list() temp_num_cluster = length(unique(memship_ini)) for(l in 1:temp_num_cluster){ dat1[[l]] = Y[memship_ini == l,] } mu = center_ini sol_path <- JGL(dat1 , penalty = "fused", lambda1, lambda2, 0.1, return.whole.theta=T) covinv_est = matrix(0, nrow = p, ncol = temp_num_cluster*p) S_bar = matrix(0, p, L*p) for (l in 1:temp_num_cluster){ covinv_est[,((l-1)*p+1):(l*p)] = sol_path$theta[[l]] temp_Y = dat1[[l]] mu_temp = apply(temp_Y, 2, mean) stemp = t(t(temp_Y)-mu_temp) S_bar[,((l-1)*p+1):(l*p)] <- (t(stemp) %*% stemp) / clust_size[l] } npie = pie nmu = mu ncovinv_est = covinv_est z = 1 diff = 100 nplog = obj_L12(Y, mu, p, L, covinv_est, S_bar, graph, lambda1, lambda2, pie) rho = matrix(0, L, n) while(diff>threshold && z<MAX_iter){ for(j in 1:n){ sm = rep(0, n) for(l in 1:L){ sm[j] = sm[j] + pie[l] * exp(fmvnorm(p, covinv_est[,((l-1)*p+1):(l*p)], Y[j,], mu[l,])) } for(l in 1:L){ rho[l,j] = pie[l] * exp(fmvnorm(p, covinv_est[,((l-1)*p+1):(l*p)], Y[j,], mu[l,])) / sm[j] } } pie = apply(rho, 1, mean) mu = rho %*% Y/ (pie * n) temp_memship = apply(rho, 2, which.max) dat1 = list() temp_num_cluster = length(unique(temp_memship)) for(l in 1:temp_num_cluster){ dat1[[l]] = Y[temp_memship==l,] } sol_path <- JGL(dat1, penalty = "fused", lambda1, lambda2, 0.1, return.whole.theta=T) covinv_est = matrix(0, nrow = p, ncol = temp_num_cluster*p) S_bar = matrix(0, p, L*p) for (l in 1:L){ covinv_est[,((l-1)*p+1):(l*p)] = sol_path$theta[[l]] S = matrix(0,p,p) for(j in 1:n){ S = S + rho[l,j] * outer((Y[j,]-mu[l,]), (Y[j,]-mu[l,]), "*") } S_bar[,((l-1)*p+1):(l*p)] <- S/(pie[l]*n) } plog = obj_L12(Y, mu, p, L, covinv_est, S_bar, graph, lambda1, lambda2, pie) diff = plog-nplog nplog = plog z = z+1 } class_memship = apply(rho, 2, which.max) output = list(pie = pie, mu = mu, covinv = covinv_est, membership = class_memship, par=c(lambda1, lambda2, ncluster)) }
targets::tar_test("tar_render_rep() manifest", { skip_pandoc() lines <- c( "---", "title: report", "output_format: html_document", "params:", " par: \"default value\"", "---", "", "```{r}", "print(params$par)", "print(targets::tar_read(x))", "```" ) writeLines(lines, "report.Rmd") targets::tar_script({ library(tarchetypes) list( tar_target(x, "value_of_x"), tar_render_rep( report, "report.Rmd", params = data.frame( par = c("parval1", "parval2", "parval3", "parval4"), stringsAsFactors = FALSE ), batches = 2 ) ) }) out <- targets::tar_manifest(callr_function = NULL) expect_equal(nrow(out), 3L) expect_equal(sort(out$name), sort(c("x", "report_params", "report"))) expect_equal(sum(is.na(out$pattern)), 2L) expect_equal(out$pattern[out$name == "report"], "map(report_params)") }) targets::tar_test("tar_render_rep() graph", { skip_pandoc() lines <- c( "---", "title: report", "output_format: html_document", "params:", " par: \"default value\"", "---", "", "```{r}", "print(params$par)", "print(targets::tar_read(x))", "```" ) writeLines(lines, "report.Rmd") targets::tar_script({ library(tarchetypes) list( tar_target(x, "value_of_x"), tar_render_rep( report, "report.Rmd", params = data.frame( par = c("parval1", "parval2", "parval3", "parval4"), stringsAsFactors = FALSE ), batches = 2 ) ) }) out <- targets::tar_network(callr_function = NULL)$edges expect_equal(nrow(out), 2L) expect_true(any(out$from == "report_params" & out$to == "report")) expect_true(any(out$from == "x" & out$to == "report")) }) targets::tar_test("tar_render_rep() run", { skip_on_cran() skip_pandoc() lines <- c( "---", "title: report", "output_format: html_document", "params:", " par: \"default value\"", "---", "", "```{r}", "print(params$par)", "print(targets::tar_read(x))", "```" ) writeLines(lines, "report.Rmd") targets::tar_script({ library(tarchetypes) list( tar_target(x, "value_of_x"), tar_render_rep( report, "report.Rmd", params = data.frame( par = c("parval1", "parval2", "parval3", "parval4"), stringsAsFactors = FALSE ), batches = 2 ) ) }) targets::tar_make(callr_function = NULL) out <- targets::tar_read(report_params) exp <- data.frame( par = c("parval1", "parval2", "parval3", "parval4"), tar_group = c(1L, 1L, 2L, 2L), stringsAsFactors = FALSE ) expect_equal(out, exp) out <- targets::tar_read(report, branches = 1) out <- grep(pattern = "\\.html$", x = out, value = TRUE) expect_equal(length(out), 2L) expect_true(all(file.exists(out))) skip_if_not_installed("xml2") read_code <- function(path) { file <- xml2::read_html(path) out <- xml2::xml_find_all(file, xpath = ".//code") as.character(unlist(xml2::as_list(out))) } out_file <- read_code(out[1]) expect_true(any(grepl("value_of_x", out_file))) expect_true(any(grepl("parval1", out_file))) expect_false(any(grepl("parval2", out_file))) expect_false(any(grepl("parval3", out_file))) expect_false(any(grepl("parval4", out_file))) out_file <- read_code(out[2]) expect_true(any(grepl("value_of_x", out_file))) expect_false(any(grepl("parval1", out_file))) expect_true(any(grepl("parval2", out_file))) expect_false(any(grepl("parval3", out_file))) expect_false(any(grepl("parval4", out_file))) out <- targets::tar_read(report, branches = 2) out <- grep(pattern = "\\.html$", x = out, value = TRUE) expect_equal(length(out), 2L) expect_true(all(file.exists(out))) out_file <- read_code(out[1]) expect_true(any(grepl("value_of_x", out_file))) expect_false(any(grepl("parval1", out_file))) expect_false(any(grepl("parval2", out_file))) expect_true(any(grepl("parval3", out_file))) expect_false(any(grepl("parval4", out_file))) out_file <- read_code(out[2]) expect_true(any(grepl("value_of_x", out_file))) expect_false(any(grepl("parval1", out_file))) expect_false(any(grepl("parval2", out_file))) expect_false(any(grepl("parval3", out_file))) expect_true(any(grepl("parval4", out_file))) out <- targets::tar_outdated(callr_function = NULL) expect_equal(out, character(0)) targets::tar_script({ library(tarchetypes) list( tar_target(x, "value_of_x"), tar_render_rep( report, "report.Rmd", params = data.frame( par = c("parval1", "parval2", "parval3-modified", "parval4"), stringsAsFactors = FALSE ), batches = 2 ) ) }) targets::tar_make(callr_function = NULL) out <- targets::tar_progress() out <- out[out$progress != "skipped", ] out <- out[grepl("^report", out$name), ] expect_equal(nrow(out), 3) out <- out$progress[!(out$name %in% c("report", "report_params"))] expect_equal(out, "built") }) targets::tar_test("tar_render_rep() run with output_file specified", { skip_on_cran() skip_pandoc() lines <- c( "---", "title: report", "output_format: html_document", "params:", " par: \"default value\"", "---", "", "```{r}", "print(params$par)", "print(targets::tar_read(x))", "```" ) writeLines(lines, "report.Rmd") targets::tar_script({ library(tarchetypes) list( tar_target(x, "value_of_x"), tar_render_rep( report, "report.Rmd", params = data.frame( par = c("parval1", "parval2", "parval3", "parval4"), output_file = c("f1.html", "f2.html", "f3.html", "f4.html"), stringsAsFactors = FALSE ) ) ) }) expect_false(any(file.exists(c("f1.html", "f2.html", "f3.html", "f4.html")))) targets::tar_make(callr_function = NULL) expect_true(all(file.exists(c("f1.html", "f2.html", "f3.html", "f4.html")))) out <- unlist(targets::tar_meta(report, children)$children) expect_equal(length(out), 4L) expect_equal(length(unique(out)), 4L) }) targets::tar_test("tar_render_rep() with output_file and _files", { skip_on_cran() skip_pandoc() lines <- c( "---", "title: report", "output_format: html_document", "params:", " par: \"default value\"", "---", "", "```{r}", "print(params$par)", "print(targets::tar_read(x))", "plot(sample.int(1e9, 4))", "```" ) writeLines(lines, "report.Rmd") targets::tar_script({ library(tarchetypes) list( tar_target(x, "value_of_x"), tar_render_rep( report, "report.Rmd", params = data.frame( par = c("parval1", "parval2", "parval3", "parval4"), output_file = c("f1.html", "f2.html", "f3.html", "f4.html"), stringsAsFactors = FALSE ), clean = FALSE ) ) }) targets::tar_make(callr_function = NULL) for (branch in seq_len(4)) { out <- basename(targets::tar_read_raw("report", branches = branch)) base <- paste0("f", branch) report <- fs::path_ext_set(base, "html") exp <- c(report, "report.Rmd", paste0(base, "_files")) expect_equal(out, exp) } })