R/propagate.R

Defines functions .rCopT .covIntJCGM print.propagate propagate

Documented in propagate

propagate <- function(
    expr, 
    data, 
    type = c("stat", "raw", "sim"),
    cov = c("diag", "full"), 
    df.tot = NULL,
    k = NULL, 
    nsim = 1000000,
    alpha = 0.05,
    exp.uc = c("1st", "2nd"),
    mc.margins = c("S1", "mvt"),          ## v1.3-0
    ws.group = NULL,                      ## v1.3-0: Willink (2007), Result 1
    adaptive = FALSE,                     ## v1.3-0: adaptive Monte Carlo procedure, JCGM 101:2008, 7.9 (TRUE or "validation")
    ndig = 2,                             ## v1.3-0: significant digits of u(y) for 'adaptive'
    max.nsim = 1E7,                       ## v1.3-0: upper limit of trials for 'adaptive'
    ad.interval = c("symmetric", "shortest"),  ## v1.3-0: coverage interval used in the stopping rule of 'adaptive'
    check = TRUE,
    ...
)
{            
  ## v1.3-0: adaptive Monte Carlo procedure (JCGM 101:2008, 7.9.4). Blocks of M = max(100/alpha, 1E4)
  ## trials are added until twice the standard deviations of the block averages of y, u(y) and of the
  ## endpoints of the probabilistically symmetric coverage interval are not larger than the numerical
  ## tolerance delta of u(y) with 'ndig' significant digits (7.9.2); adaptive = "validation" uses delta/5,
  ## as recommended for the validation of the GUF (8.2). 'ad.interval' selects the coverage interval whose
  ## endpoints enter the stopping rule (the shortest interval is noisier and needs more trials).
  if (isTRUE(adaptive) || identical(adaptive, "validation")) {
    tolFac <- if (identical(adaptive, "validation")) 5 else 1
    ad.interval <- match.arg(ad.interval)
    type <- match.arg(type)
    BUD <- attr(data, "budget")
    if (type == "sim" && !is.data.frame(BUD))
      stop("propagate: 'adaptive' with type = \"sim\" needs samples from makeDat(..., output = \"sim\"), whose budget is used to draw new blocks.")
    Mb <- max(ceiling(100/alpha), 1E4)
    ARGS <- list(expr = expr, data = data, type = type, cov = cov, df.tot = df.tot, k = k, nsim = Mb, alpha = alpha,
                 exp.uc = exp.uc, mc.margins = mc.margins, ws.group = ws.group, adaptive = FALSE)
    runBlock <- function(chk) { out <- NULL
      if (type == "sim") { ARGS$data <- .sampleBudget(BUD, Mb); attr(ARGS$data, "budget") <- BUD }
      invisible(capture.output(out <- suppressMessages(do.call(propagate, c(ARGS, list(check = chk), list(...))))))
      out }
    FIRST <- runBlock(check)
    RES <- list(FIRST$resSIM); DS <- list(FIRST$datSIM); DS2 <- list(FIRST$datSIM2)
    blockStat <- function(y) { y <- y[is.finite(y)]
      c(y = mean(y), u = sd(y), .covIntJCGM(y, 1 - alpha), .covIntJCGM(y, 1 - alpha, shortest = TRUE)) }
    ST <- list(blockStat(FIRST$resSIM))
    h <- 1
    repeat {
      h <- h + 1
      B <- runBlock(FALSE)
      RES[[h]] <- B$resSIM; DS[[h]] <- B$datSIM; DS2[[h]] <- B$datSIM2; ST[[h]] <- blockStat(B$resSIM)
      sBlk <- apply(do.call(rbind, ST), 2, sd)/sqrt(h)
      uy <- sd(unlist(RES), na.rm = TRUE)
      delta <- if (is.finite(uy) && uy > 0) 0.5 * 10^(floor(log10(uy)) - (ndig - 1)) else NA
      crit <- if (ad.interval == "shortest") c(1, 2, 5, 6) else 1:4
      conv <- is.finite(delta) && all(2 * sBlk[crit] <= delta/tolFac)
      if (conv || h * Mb >= max.nsim) break
    }
    if (!conv) message("propagate: adaptive procedure stopped at max.nsim = ", max.nsim, " trials without reaching the numerical tolerance.")
    OUT <- FIRST
    resSIM <- unlist(RES)
    confSIM <- .covIntJCGM(resSIM, p = 1 - alpha); shortSIM <- .covIntJCGM(resSIM, p = 1 - alpha, shortest = TRUE)
    names(confSIM) <- names(shortSIM) <- paste(c(alpha/2, 1 - alpha/2) * 100, "%", sep = "")
    OUT$resSIM <- resSIM; OUT$datSIM <- do.call(rbind, DS)
    OUT$datSIM2 <- if (!is.null(DS2[[1]])) do.call(rbind, DS2) else NULL
    OUT$sim <- c(mean.MC = mean(resSIM, na.rm = TRUE), u.MC = sd(resSIM, na.rm = TRUE), median.MC = median(resSIM, na.rm = TRUE),
                 mad.MC = mad(resSIM, na.rm = TRUE), confSIM[1], confSIM[2])
    OUT$ci.short <- shortSIM
    OUT$nsim <- h * Mb
    names(sBlk) <- c("mean.MC", "u.MC", "sym.low", "sym.high", "short.low", "short.high")
    OUT$sim.se <- sBlk
    OUT$adaptive <- list(blocks = h, M.block = Mb, nsim = h * Mb, delta = delta, tolerance = delta/tolFac, ndig = ndig,
                         interval = ad.interval, converged = conv)
    return(OUT)
  }
  
  type <- match.arg(type)
  if (!is.matrix(cov)) cov <- match.arg(cov)
  exp.uc <- match.arg(exp.uc)
  ## v1.3-0: the variance-matched margins of <= 1.2-0 were removed
  if (identical(mc.margins, "GUF"))
    stop("propagate: mc.margins = \"GUF\" (t-margins rescaled to variance u^2, propagate <= 1.2-0) was removed in 1.3-0, because ",
         "it gives too narrow Monte Carlo coverage intervals for Type A inputs with few indications. Use \"S1\" ",
         "(JCGM 101:2008, 6.4.9) or \"mvt\" (JCGM 102:2011, 5.3.2), see ?propagate.")
  mc.margins <- match.arg(mc.margins)  ## v1.3-0
  
  ## version 1.0-4: convert function to expression
  if (is.function(expr)) {
    ARGS <- as.list(args(expr))
    ARGS <- ARGS[-length(ARGS)]
    VARS <- names(ARGS)    
    expr <- body(expr)
    class(expr) <- "expression"
    isFun <- TRUE
  } else isFun <- FALSE
  
  ## check for correct expression and number of simulations
  if (!is.expression(expr)) stop("propagate: 'expr' must be an expression")
  if (nsim < 10000) stop("propagate: 'nsim' should be >= 10000 !")
  
  ## v1.3-0: uncertainty budget from makeDat(..., output = "sim"), used for the GUF (see below)
  BUDGET <- attr(data, "budget")
  
  ## check for matching variable names
  if (!isFun) VARS <- all.vars(expr)  
  m <- match(VARS, colnames(data))
  
  ## version 1.0-8: if expr does not use all data columns, select
  if (length(m) != ncol(data)) data <- data[, m, drop = FALSE]
  
  if (any(is.na(m))) stop("propagate: variable names of input dataframe and expression do not match!")
  if (length(unique(m)) != length(m)) stop("propagate: some variable names are repetitive!")
  
  DATA <- data
  EXPR <- expr
  
  ## if covariance matrix is supplied, check for symmetry and matching names
  if (is.matrix(cov)) {
    if (NCOL(cov) != NROW(cov)) stop("propagate: 'cov' is not a symmetric matrix!")
    ## v1.3-0: like 'data', reduce 'cov' to the variables of 'expr'
    if (!is.null(colnames(cov)) && all(colnames(DATA) %in% colnames(cov)) && NCOL(cov) > NCOL(DATA))
      cov <- cov[colnames(DATA), colnames(DATA), drop = FALSE]
    m <- match(colnames(cov), colnames(DATA))            
    if (any(is.na(m))) stop("propagate: names of input dataframe and var-cov matrix do not match!")             
    if (length(unique(m)) != length(m)) stop("propagate: some names of the var-cov matrix are repetitive!")        
    if (NCOL(cov) != NCOL(DATA)) stop("propagate: 'cov' must have one row/column per variable in 'expr'!")
    ## bring an external covariance matrix into the column order of 'data'
    cov <- cov[colnames(DATA), colnames(DATA)]
  }
  
  ############## version 1.0-8: Create variables from input data, use the direct 'type's ##############
  ## 1) statistical summaries
  if (type == "stat") {
    meanVAL <- DATA[1, ]
    sdVAL <- DATA[2, ] 
    dfVAL <- if (nrow(DATA) == 3) DATA[3, ] else rep(Inf, ncol(DATA))
    
    if (nrow(DATA) == 2 | nrow(DATA) == 3) cat("I see data with 2 or 3 rows ... type = 'stat' seems correct!\n")
    else cat("I don't see data with 2 or 3 rows ... type = 'stat' probably correct!\n")
    
    if (is.matrix(cov)) SIGMA <- cov 
    else if (cov == "diag") {
      SIGMA <- diag(sdVAL^2, nrow = length(VARS), ncol = length(VARS))    
      colnames(SIGMA) <- rownames(SIGMA) <- colnames(DATA)
    } 
    else if (cov == "full") stop("Cannot use full covariance matrix with summary data. Please supply an external one...")
    COR <- suppressWarnings(cov2cor(SIGMA))   ## inputs with u = 0 give NaN, set to 0 below
  }
  
  ## 2) experimental samples
  if (type == "raw") {
    N <- apply(DATA, 2, function(x) sum(!is.na(x), na.rm = TRUE))
    meanVAL <- apply(DATA, 2, function(x) mean(x, na.rm = TRUE))
    sdVAL <- apply(DATA, 2, function(x) sd(x, na.rm = TRUE))/sqrt(N)
    dfVAL <- N - 1
    
    if (nrow(DATA) > 3 & nrow(DATA) < 1000) cat("I see data with 3 < rows < 1000 ... type = 'raw' seems correct!\n")
    else cat("I don't see data with 3 < rows < 1000 ... type = 'raw' probably correct!\n")
    
    if (is.matrix(cov)) {
      SIGMA <- cov
      COR <- suppressWarnings(cov2cor(SIGMA))   ## inputs with u = 0 give NaN, set to 0 below
    }
    else if (cov == "diag") {
      SIGMA <- diag(sdVAL^2, nrow = length(VARS), ncol = length(VARS))    
      colnames(SIGMA) <- rownames(SIGMA) <- colnames(DATA)
      COR <- suppressWarnings(cov2cor(SIGMA))   ## inputs with u = 0 give NaN, set to 0 below
    } 
    else if (cov == "full") {
      notNA <- !is.na(DATA)
      Npairs <- t(notNA) %*% notNA  
      SIGMA <- cov(DATA, use = "pairwise.complete.obs")/Npairs
      COR <- cor(DATA, use = "pairwise.complete.obs")
    }
  }
  
  ## 3) simulated distribution data
  if (type == "sim") {
    N <- nrow(DATA)
    meanVAL <- apply(DATA, 2, function(x) mean(x, na.rm = TRUE))
    sdVAL <- apply(DATA, 2, function(x) sd(x, na.rm = TRUE))
    dfVAL <- rep(N - 1, ncol(DATA))
    
    if (nrow(DATA) >= 1000) cat("I see data with 1000 <= rows ... type = 'sim' seems correct!\n")
    else cat("I don't see data with 1000 <= rows ... type = 'sim' probably correct!\n")
    
    ## v1.3-0: samples from makeDat(..., output = "sim") carry the uncertainty budget. The GUF then uses its
    ## estimates, standard uncertainties (u = scale for t-distributions, JCGM 101:2008, 6.4.9) and degrees of
    ## freedom instead of the sample moments; the sample variance of a t_nu sample is nu/(nu - 2) u^2.
    useBudget <- is.data.frame(BUDGET) && all(colnames(DATA) %in% BUDGET$name)
    if (useBudget) {
      mb <- match(colnames(DATA), BUDGET$name)
      meanVAL <- setNames(BUDGET$mean[mb], colnames(DATA))
      sdVAL <- setNames(BUDGET$u[mb], colnames(DATA))
      dfVAL <- BUDGET$df[mb]
      message("propagate: the GUF uses the estimates, standard uncertainties and degrees of freedom of the uncertainty budget (attribute 'budget').")
    }
    
    if (is.matrix(cov)) {
      SIGMA <- cov
      COR <- suppressWarnings(cov2cor(SIGMA))   ## inputs with u = 0 give NaN, set to 0 below
    }
    else if (cov == "diag") {
      SIGMA <- diag(sdVAL^2, nrow = length(VARS), ncol = length(VARS))    
      colnames(SIGMA) <- rownames(SIGMA) <- colnames(DATA)
      COR <- suppressWarnings(cov2cor(SIGMA))   ## inputs with u = 0 give NaN, set to 0 below
    }
    else if (cov == "full") {
      SIGMA <- cov(DATA, use = "pairwise.complete.obs")
      COR <- cor(DATA, use = "pairwise.complete.obs")
      if (useBudget) SIGMA <- COR * outer(sdVAL, sdVAL)        ## v1.3-0: sample correlation, budget u
    }
  }  
  
  ## version 1.0-5: replace possible NA's/NaN's in covariance/correlation matrix with 0's
  SIGMA[is.na(SIGMA)] <- 0; SIGMA[is.nan(SIGMA)] <- 0
  COR[is.na(COR)] <- 0
  
  ## version 1.0-5: No diagonals with 0, 
  if (any(diag(SIGMA) == 0)) {
    DIAG <- diag(SIGMA)
    DIAG[DIAG == 0] <- 1E-6
    diag(SIGMA) <- DIAG
  }
  
  ## This will bring the variables in 'data' and 'expr' in the same 
  ## order as in the covariance matrix
  m1 <- match(colnames(SIGMA), colnames(DATA))
  meanVAL <- meanVAL[m1]
  m2 <- match(colnames(SIGMA), VARS)
  
  ############ first- and second-order Taylor expansion-based error propagation ################
  MEAN1 <- try(eval(EXPR, envir = as.list(meanVAL)), silent = TRUE)
  if (!is.numeric(MEAN1)) {
    message("propagate: there was an error in calculating the first-order mean")
    MEAN1 <- NA
  }  
  
  GRAD <- try(makeGrad(EXPR, m2), silent = TRUE)  
  if (!inherits(GRAD, "try-error")) evalGRAD <- try(sapply(GRAD, eval, envir = as.list(meanVAL)), silent = TRUE)
  ## v1.3-0: numGrad() returns the derivatives in the order of all.vars(EXPR); reorder to the columns of SIGMA
  ## (bug in <= 1.2-0: wrong u(y) for non-differentiable expressions with a different variable order, e.g. atan2(X2, X1))
  if (inherits(GRAD, "try-error")) {
    message("propagate: symbolic differentiation failed (", sub("\n$", "", conditionMessage(attr(GRAD, "condition"))),
            "); numerical derivatives are used.")
    evalGRAD <- try(numGrad(EXPR, as.list(meanVAL))[m2], silent = TRUE)
  }
  if (!inherits(evalGRAD, "try-error")) evalGRAD <- as.vector(evalGRAD) else evalGRAD <- NA
  
  VAR1 <- try(as.numeric(t(evalGRAD) %*% SIGMA %*% matrix(evalGRAD)), silent = TRUE)  
  if (inherits(VAR1, "try-error")) {
    message("propagate: there was an error in calculating the first-order variance")
    VAR1 <- NA
  }
  
  HESS <- try(makeHess(EXPR, m2), silent = TRUE)
  if (!inherits(HESS, "try-error")) evalHESS <- try(sapply(HESS, eval, envir = as.list(meanVAL)), silent = TRUE)
  if (inherits(HESS, "try-error")) evalHESS <- try(numHess(EXPR, as.list(meanVAL))[m2, m2, drop = FALSE], silent = TRUE)  ## v1.3-0: order
  if (!inherits(evalHESS, "try-error")) evalHESS <- matrix(evalHESS, ncol = length(meanVAL), byrow = TRUE) else evalHESS <- NA  
  
  valMEAN2 <- try(0.5 * tr(evalHESS %*% SIGMA), silent = TRUE)
  if (!inherits(valMEAN2, "try-error")) {
    MEAN2 <- MEAN1 + valMEAN2
  } else {
    warning("propagate: there was an error in calculating the second-order mean")
    MEAN2 <- NA
  }
  
  valVAR2 <- try(0.5 * tr(evalHESS %*% SIGMA %*% evalHESS %*% SIGMA), silent = TRUE)
  if (!inherits(valVAR2, "try-error")) {
    VAR2 <- VAR1 + valVAR2
  } else {
    message("propagate: there was an error in calculating the second-order variance")
    VAR2 <- NA
  }
  
  ## v1.3-0: second-order variance with the input moments (u.2m). u.2 assumes Gaussian inputs
  ## (fourth moment 3 u^4, third moment 0). With the skewness g1 and excess kurtosis g2 of each input,
  ## Var(c'd + 1/2 d'Hd) for independent inputs adds 1/4 h_ii^2 g2_i u_i^4 + c_i h_ii g1_i u_i^3
  ## (Cox 1979; Mekid & Vaja 2008). Correlated pairs keep the Gaussian joint moments.
  MOMENTS <- tryCatch(.inputMoments(colnames(SIGMA), type, DATA, dfVAL,
                                    if (type == "sim" && is.data.frame(BUDGET)) BUDGET else NULL), error = function(e) NULL)
  VAR2m <- NA
  if (!is.null(MOMENTS) && is.finite(VAR2) && is.numeric(evalGRAD) && is.matrix(evalHESS) && all(is.finite(evalHESS))) {
    uIN <- sqrt(diag(SIGMA)); hII <- diag(evalHESS)
    VAR2m <- VAR2 + sum(0.25 * hII^2 * MOMENTS$exkurt * uIN^4 + evalGRAD * hII * MOMENTS$skewness * uIN^3)
    if (VAR2m < 0) VAR2m <- NA
  }
  
  if (exp.uc == "1st") {
    totalMEAN <- MEAN1
    totalVAR <- VAR1
  }
  if (exp.uc == "2nd") {
    totalMEAN <- MEAN2
    totalVAR <- VAR2 
  }
  errorPROP <- sqrt(totalVAR)  
  
  if (is.numeric(evalGRAD)) {
    sensitivity <- evalGRAD
    names(sensitivity) <- colnames(DATA)
    contribution <- outer(sensitivity, sensitivity, "*") * SIGMA
    rel.contribution <- abs(contribution)/sum(abs(contribution), na.rm = TRUE)
  } else sensitivity <- contribution <- rel.contribution <- NULL
  
  dfVAL[is.na(dfVAL)] <- Inf
  ## v1.3-0: Willink (2007), Result 1: raw data with full covariance = one jointly observed group
  wsGroup <- if (!is.null(ws.group)) ws.group else
             if (type == "raw" && identical(cov, "full") && !anyNA(DATA)) rep(1, ncol(DATA)) else NULL
  ws <- WelchSatter(ui = sqrt(diag(SIGMA)), ci = sensitivity, df = dfVAL, df.tot = df.tot, uc = errorPROP,
                    alpha = alpha, k = k, cov = SIGMA, group = wsGroup)
  
  if (exp.uc == "1st") confMEAN <- MEAN1 else confMEAN <- MEAN2
  confPROP <- confMEAN + c(-1, 1) * ws$u.exp
  names(confPROP) <- paste(c(alpha/2, 1 - alpha/2) * 100, "%", sep = "")
  
  ################# v1.3-0: Monte Carlo sampling of the inputs #####################
  ## mc.margins = "S1": Gaussian copula with per-input t-margins.
  ## mc.margins = "mvt"     : multivariate t-distribution (JCGM 102:2011, 5.3.2),
  ##                          one common DOF nu = n - N for all N jointly observed inputs.
  ## 'df.tot' is NOT used for sampling: it is an effective DOF of the output and only
  ## enters the coverage factor k.
  dfMC <- as.numeric(dfVAL)
  names(dfMC) <- colnames(DATA)
  NV <- ncol(DATA)
  
  ## v1.3-0: "mvt" for
  ##  type = "raw":  N quantities observed jointly n times, nu = n - N (JCGM 102:2011, 5.3.2);
  ##  type = "stat": all inputs with finite DOF share one nu and one chi-square variable, with
  ##                 scale matrix Sigma (e.g. regression coefficients and residual term, which
  ##                 share the estimated residual variance, see predictNLS); inputs with DOF = Inf
  ##                 are Gaussian and must be uncorrelated with the t-block.
  mvtIdx <- rep(TRUE, NV)
  if (mc.margins == "mvt") {
    if (type == "sim") stop("propagate: mc.margins = \"mvt\" is not available for type = \"sim\".")
    if (type == "raw") {
      if (!identical(cov, "full")) 
        stop("propagate: mc.margins = \"mvt\" requires cov = \"full\" (sample covariance of the joint indications).")
      if (anyNA(DATA)) 
        stop("propagate: mc.margins = \"mvt\" requires complete joint indications (no NA's).")
      nObs <- nrow(DATA)
      nuMVT <- nObs - NV
      if (nuMVT < 1) 
        stop("propagate: mc.margins = \"mvt\" needs n > N (n = ", nObs, " indications, N = ", NV, " quantities).")
      dfMC[] <- nuMVT
      scaleMVT <- SIGMA * (nObs - 1)/nuMVT
    } else {
      if (nrow(DATA) != 3) 
        stop("propagate: mc.margins = \"mvt\" with type = \"stat\" samples all inputs with finite DOF from ONE ",
             "multivariate t-distribution with a common DOF, which must be given in the 3rd row of 'data'. ",
             "This is meant for inputs whose uncertainties share one variance estimate (e.g. regression ",
             "coefficients, see predictNLS). For independent inputs, use mc.margins = \"S1\".")
      mvtIdx <- is.finite(dfMC)
      nuMVT <- unique(dfMC[mvtIdx])
      if (length(nuMVT) != 1) 
        stop("propagate: mc.margins = \"mvt\" with type = \"stat\" requires one common finite DOF ",
             "(other inputs: DOF = Inf).")
      if (any(SIGMA[mvtIdx, !mvtIdx] != 0)) 
        stop("propagate: inputs with finite and infinite DOF must be uncorrelated for mc.margins = \"mvt\".")
      scaleMVT <- SIGMA                                      ## scale = covariance given (S1 convention)
      nObs <- nuMVT + 1                                      ## => (nObs - 1)/nuMVT = 1 below
    }
    if (nuMVT <= 1)
      message("propagate: nu = ", nuMVT, " => neither expectation nor covariance of the ",
              "multivariate t exist (JCGM 102:2011, 5.3.2.3). 'mean.MC' and 'u.MC' are not ",
              "meaningful; use median.MC and the MC coverage interval.")
    else if (nuMVT <= 2)
      message("propagate: nu = ", nuMVT, " => the multivariate t has no finite covariance ",
              "(JCGM 102:2011, 5.3.2.3). 'u.MC' is not meaningful; use the MC coverage interval.")
  }
  
  ## variance of a standard t_nu; Inf DOF = Gaussian
  tVar <- ifelse(is.infinite(dfMC), 1, ifelse(dfMC > 2, dfMC/(dfMC - 2), Inf))
  
  if (type == "raw" | type == "stat") {
    CENTER <- as.numeric(meanVAL)
    
    if (mc.margins == "mvt") {
      ## Q = sum_r (x_r - xbar)(x_r - xbar)^T.  SIGMA (raw, full) = Q/((n-1) n).
      ## Posterior of the mean under the Jeffreys prior |Sigma|^-(N+1)/2:
      ##   X ~ t_nu(xbar, Q/(n (n-N))),  nu = n - N,  Cov(X) = Q/(n (n-N-2)).
      ## => scale matrix = SIGMA * (n-1)/(n-N).  For N = 1 this equals the S1 case.
      ## Identical to JCGM 102:2011, 5.3.2.1: t_nu(xbar, S/n) with S = Q/nu, nu = n - N;
      ## covariance nu/(nu-2) * S/n (5.3.2.3). Sampling as in 5.3.2.4: R's chol() returns
      ## the upper factor U = t(L), so row-vector draws z^T U equal (L z)^T.
      ## scaleMVT = SIGMA (n-1)/(n-N) for "raw", = SIGMA for "stat" (set above)
      L <- try(chol(scaleMVT[mvtIdx, mvtIdx, drop = FALSE]), silent = TRUE)
      if (inherits(L, "try-error")) 
        stop("propagate: scale matrix of the multivariate t is not positive definite.")
      if (any(!mvtIdx)) L0 <- chol(SIGMA[!mvtIdx, !mvtIdx, drop = FALSE])
      rmvtJCGM <- function(n) {
        X <- matrix(CENTER, nrow = n, ncol = NV, byrow = TRUE)
        Z <- matrix(rnorm(n * sum(mvtIdx)), ncol = sum(mvtIdx)) %*% L     ## rows ~ N(0, scale)
        W <- sqrt(nuMVT/rchisq(n, df = nuMVT))                            ## one mixing variable per draw
        X[, mvtIdx] <- X[, mvtIdx] + Z * W                                ## Z * W scales each row by its W
        if (any(!mvtIdx)) 
          X[, !mvtIdx] <- X[, !mvtIdx] + matrix(rnorm(n * sum(!mvtIdx)), ncol = sum(!mvtIdx)) %*% L0
        X
      }
      datSIM <- rmvtJCGM(nsim); datSIM2 <- rmvtJCGM(nsim)
      colnames(datSIM) <- colnames(datSIM2) <- colnames(DATA)
      inflate <- ifelse(mvtIdx, tVar * (nObs - 1)/nuMVT, 1)              ## raw: SIGMA (n-1)/(n-N-2)
    } else {
      if (any(dfMC <= 0)) stop("propagate: all degrees of freedom must be > 0.")
      if (mc.margins == "S1" && any(dfMC <= 2))
        message("propagate: input(s) ", paste(names(dfMC)[dfMC <= 2], collapse = ", "),
                " have DOF <= 2 => infinite variance (DOF = 1: also no expectation) of the ",
                "t-margin. 'u.MC' (and for DOF = 1 'mean.MC') is not meaningful; ",
                "use median.MC and the MC coverage interval (JCGM 101:2008, 6.4.9.4).")
      
      if (NV == 1) {
        datSIM  <- matrix(rt(nsim, df = dfMC), ncol = 1)
        datSIM2 <- matrix(rt(nsim, df = dfMC), ncol = 1)   ## independent draw for sobol()
      } else {
        datSIM <- .rCopT(nsim, COR, dfMC); datSIM2 <- .rCopT(nsim, COR, dfMC)
      }
      colnames(datSIM) <- colnames(datSIM2) <- colnames(DATA)
      
      ## "S1": scale parameter = u  => Var(X) = tVar * u^2
      SCALE <- as.numeric(sdVAL)
      datSIM  <- sweep(sweep(datSIM,  2, SCALE, "*"), 2, CENTER, "+")
      datSIM2 <- sweep(sweep(datSIM2, 2, SCALE, "*"), 2, CENTER, "+")
      
      inflate <- tVar
    }
  } else {
    datSIM <- DATA; datSIM2 <- NULL
    inflate <- rep(1, NV)
  }
  
  ## Covariance the MC input is *expected* to have under the chosen mode.
  ## "mvt": exact (elliptical distribution, correlation = that of the scale matrix).
  ## "S1": off-diagonals approximate, because the Pearson correlation of t-margins
  ## joined by a Gaussian copula is slightly smaller than the copula parameter for small
  ## DOF => frobCOV/frobCOR have a small DOF-dependent floor that does not vanish with nsim.
  SIGMA.MC <- SIGMA * sqrt(outer(inflate, inflate))
  
  covMC <- cov(datSIM, use = "pairwise.complete.obs")
  corMC <- suppressWarnings(cor(datSIM, use = "pairwise.complete.obs"))   ## constant inputs (u = 0): NA, set to 0 as in COR
  corMC[is.na(corMC)] <- 0
  frobCOV <- if (all(is.finite(SIGMA.MC))) norm(covMC - SIGMA.MC, "F")/norm(SIGMA.MC, "F") else NA
  frobCOR <- norm(corMC - COR, "F")/norm(COR, "F")
  
  ## Fit scaled/shifted t to the margins. Row 2 is reported so that it is directly
  ## comparable with the input uncertainty u (2nd row of 'data'); row 3 (fitted DOF)
  ## should be compared with 'df.MC' in the output, not with the 3rd row of 'data'.
  ##  "S1":  fitted scale parameter should equal u
  ##  "mvt": fitted scale = u * sqrt((n-1)/(n-N)), converted back to u
  ##  type = "sim": fitted scale converted to SD, should equal u
  if (check) {
    cat("Checking Copula margins with scaled/shifted t-distribution...\n")
    fitDIST <- apply(datSIM, 2, function(x) fitDistr(x, distsel = 5, nbin = 1000, verbose = FALSE, plot = "none")$bestpar)
    if (type == "sim") {
      conv <- ifelse(is.finite(tVar), sqrt(tVar), NA)
      fitDIST[2, ] <- fitDIST[2, ] * conv
    } else if (mc.margins == "mvt" && type == "raw") {
      fitDIST[2, ] <- fitDIST[2, ] / sqrt((nObs - 1)/nuMVT)
    }
  } else fitDIST <- NULL
  
  resSIM <- try(eval(EXPR, envir = as.data.frame(datSIM)), silent = TRUE) 
  if (inherits(resSIM, "try-error")) {
    message("propagate: using 'vectorized' evaluation gave an error. Switching to 'row-wise' evaluation...")
    resSIM <- apply(datSIM, 1, function(x) eval(EXPR, envir = as.list(x)))     
  }
  
  ## v1.3-0: coverage intervals from order statistics exactly as in JCGM 101:2008, 7.7
  ## (previously quantile(type = 7), which interpolates between order statistics)
  confSIM  <- .covIntJCGM(resSIM, p = 1 - alpha, shortest = FALSE)
  shortSIM <- .covIntJCGM(resSIM, p = 1 - alpha, shortest = TRUE)
  names(confSIM) <- names(shortSIM) <- paste(c(alpha/2, 1 - alpha/2) * 100, "%", sep = "")
  
  if (length(unique(resSIM)) == 1) message("propagate: Monte Carlo simulation gave unique repetitive values! Are all derivatives constants?")   
  
  outPROP <- c(mean.1 = MEAN1, mean.2 = MEAN2, u.1 = sqrt(VAR1), u.2 = sqrt(VAR2), u.2m = sqrt(VAR2m),    ## v1.3-0: u.2m
               confPROP[1], confPROP[2])   
  
  outSIM <- c(mean.MC = mean(resSIM, na.rm = TRUE), u.MC = sd(resSIM, na.rm = TRUE), 
              median.MC = median(resSIM, na.rm = TRUE), mad.MC = mad(resSIM, na.rm = TRUE),
              confSIM[1], confSIM[2])
  
  outDAT <- rbind(meanVAL, sdVAL, dfVAL)
  
  ## v1.3-0: numerical standard uncertainties of the MC results (cf. JCGM 101:2008, 7.9): standard
  ## deviation over h = 10 blocks of the M results, divided by sqrt(h)
  simSE <- NULL
  yF <- resSIM[is.finite(resSIM)]
  if (length(yF) >= 1E3) {
    grp <- rep_len(1:10, length(yF))
    BS <- sapply(split(yF, grp), function(y) c(mean(y), sd(y), .covIntJCGM(y, 1 - alpha), .covIntJCGM(y, 1 - alpha, shortest = TRUE)))
    simSE <- apply(BS, 1, sd)/sqrt(10)
    names(simSE) <- c("mean.MC", "u.MC", "sym.low", "sym.high", "short.low", "short.high")
  }
  
  OUT <- list(gradient = GRAD, evalGrad = evalGRAD,
              hessian = HESS, evalHess = evalHESS, 
              rel.contr  = rel.contribution, covMat = SIGMA, covMat.MC = covMC,
              covMat.target = SIGMA.MC,                                     ## v1.3-0
              corMat = COR, corMat.MC = corMC, frobCOV = frobCOV, frobCOR = frobCOR, 
              ws.df = floor(ws$ws.df), k = ws$k, u.exp = ws$u.exp, resSIM = resSIM, datSIM = datSIM, datSIM2 = datSIM2, 
              prop = outPROP, sim = outSIM, expr = EXPR, data = outDAT, alpha = alpha, nsim = nsim, check = fitDIST, type = type,
              mc.margins = if (type == "sim") NA else mc.margins,          ## v1.3-0
              df.MC = if (type == "sim") NULL else dfMC,                  ## v1.3-0: DOFs used for sampling
              input = list(data = if (type == "sim") NULL else DATA, type = type, cov = cov, df.tot = df.tot, k = k,   ## v1.3-0: for report()
                           exp.uc = exp.uc, ws.group = ws.group, ws.method = ws$method, budget = BUDGET),
              ci.short = shortSIM,                                        ## v1.3-0: shortest coverage interval
              moments = MOMENTS,                                          ## v1.3-0: input skewness/kurtosis for u.2m
              sim.se = simSE, 
              call = match.call())                                             ## v1.3-0: numerical standard uncertainties
  
  class(OUT) <- "propagate"
  OUT$call <- match.call()
  return(OUT)                                     
}

print.propagate <- function(x, ...)
{
  object <- x
  
  ## print error propagation results
  cat(red("Results from uncertainty propagation:\n"))
  print(object$prop)
  
  ## print simulation results
  cat(red("Results from Monte Carlo simulation:\n"))
  print(object$sim)
}

## v1.3-0: Monte Carlo coverage interval, JCGM 101:2008, 7.7.1 (symmetric) and 7.7.2 (shortest).
## y(1) <= ... <= y(M) sorted results; q = pM if integer, else integer part of pM + 1/2;
## interval [y(r), y(r+q)] for r in 1..(M - q).
##  - probabilistically symmetric: r = (M - q)/2 if integer, else integer part of (M - q + 1)/2
##  - shortest: r* minimising y(r+q) - y(r)
.covIntJCGM <- function(y, p = 0.95, shortest = FALSE) {
  y <- sort(y[is.finite(y)])
  M <- length(y)
  if (M < 2) return(c(NA_real_, NA_real_))
  pM <- p * M
  q <- if (abs(pM - round(pM)) < 1e-8) round(pM) else floor(pM + 0.5)
  if (q >= M) return(c(y[1], y[M]))
  if (shortest) {
    r <- which.min(y[(q + 1):M] - y[1:(M - q)])
  } else {
    r <- if ((M - q) %% 2 == 0) (M - q) / 2 else floor((M - q + 1) / 2)
  }
  c(y[r], y[r + q])
}

## Gaussian copula with t-margins (replaces copula::rMvdc for normalCopula + "t" margins):
## Z ~ N(0, R) via the symmetric square root of R, X_j = qt(pnorm(Z_j), df_j)
.rCopT <- function(n, R, df) {
  e <- eigen(R, symmetric = TRUE)
  S <- e$vectors %*% (t(e$vectors) * sqrt(pmax(e$values, 0)))
  Z <- matrix(rnorm(n * ncol(R)), n, byrow = TRUE) %*% S
  qt(pnorm(Z), rep(df, each = n))
}

Try the propagate package in your browser

Any scripts or data that you put into this service are public.

propagate documentation built on Nov. 10, 2026, 9:07 a.m.