# Copyright (c) 2015 Microsoft Corporation All Rights Reserved

session <- RevoIOQ:::saveRUnitSession()

"d.p.q.r.tests.stress" <- function()
{
    
    ####	d|ensity
    ####	p|robability (cumulative)
    ####	q|uantile
    ####	r|andom number generation
    ####
    ####	Functions for  ``d/p/q/r''
    
    .ptime <- proc.time()
    F <- FALSE
    T <- TRUE
    
    ###-- these are identical in ./arith-true.R ["fixme": use source(..)]
    opt.conformance <- 0
    Meps <- .Machine $ double.eps
    xMax <- .Machine $ double.xmax
    options(rErr.eps = 1e-30)
    rErr <- function(approx, true, eps = .Options$rErr.eps)
    {
        if(is.null(eps)) { eps <- 1e-30; options(rErr.eps = eps) }
        ifelse(Mod(true) >= eps,
                1 - approx / true, # relative error
                true - approx)     # absolute error (e.g. when true=0)
    }
    ## Numerical equality: Here want "rel.error" almost always:
    All.eq <- function(x,y) {
        all.equal.numeric(x,y, tolerance= 64*.Machine$double.eps,
                scale = max(0, mean(abs(x), na.rm=TRUE)))
    }
    if(!interactive()) set.seed(123)
    
    ## The prefixes of ALL the PDQ & R functions
    PDQRinteg <- c("binom", "geom", "hyper", "nbinom", "pois","signrank","wilcox")
    PDQR <- c(PDQRinteg, "beta", "cauchy", "chisq", "exp", "f", "gamma",
            "lnorm", "logis", "norm", "t","unif","weibull")
    PQonly <- c("tukey")
    
    ###--- Discrete Distributions --- Consistency Checks  pZZ = cumsum(dZZ)
    
    ##for(pre in PDQRinteg) { n <- paste("d",pre,sep=""); cat(n,": "); str(get(n))}
    
    ##__ 1. Binomial __
    
    ## Cumulative Binomial '==' Cumulative F :
    ## Abramowitz & Stegun, p.945-6;  26.5.24  AND	26.5.28 :
    n0 <- 50; n1 <- 16; n2 <- 20; n3 <- 8
    for(n in rbinom(n1, size = 2*n0, p = .4)) {
        cat("n=",n,": ")
        for(p in c(0,1,rbeta(n2, 2,4))) {
            cat(".")
            for(k in rbinom(n3, size = n,  prob = runif(1))) {
                ## For X ~ Bin(n,p), compute 1 - P[X > k] = P[X <= k] in three ways:
                tst1 <- all.equal(	     pbinom(0:k, size = n, prob = p),
                        cumsum(dbinom(0:k, size = n, prob = p)))
                tst <- all.equal(if(k==n || p==0) 1 else
                                    pf((k+1)/(n-k)*(1-p)/p, df1=2*(n-k), df2=2*(k+1)),
                        sum(dbinom(0:k, size = n, prob = p)))
                if(!isTRUE(tst1) || !isTRUE(tst)) {
                    cat("n=", n,"; p =",format(p),".  k =",k)
                    if(!isTRUE(tst1)) cat("; tst1=",tst1)
                    if(!isTRUE(tst )) cat("; tst=", tst)
                    cat("\n")
                }
            }
        }
        cat("\n")
    }
    
    ##__ 2. Geometric __
    for(pr in seq(1e-10,1,len=15)) { # p=0 is not a distribution
        print(All.eq((dg <- dgeom(0:10, pr)),
                        pr * (1-pr)^(0:10)))
        print(All.eq(cumsum(dg), pgeom(0:10, pr)))
    }
    
    ##__ 3. Hypergeometric __
    
    m <- 10; n <- 7
    for(k in 2:m) {
        x <- 0:(k+1)
        print(All.eq(phyper(x, m, n, k), cumsum(dhyper(x, m, n, k))))
    }
    
    ##__ 4. Negative Binomial __
    
    ## PR #842
    for(size in seq(0.8,2, by=.1))
        print(all.equal(cumsum(dnbinom(0:7, size, .5)),
                        pnbinom(0:7, size, .5)))
    All.eq(pnbinom(c(1,3), .9, .5), c(0.777035760338812, 0.946945347071519))
    
    ##__ 5. Poisson __
    
    all(dpois(0:5,0)	   == c(1, rep(0,5)))
    all(dpois(0:5,0, log=TRUE) == c(0, rep(-Inf, 5)))
    
    ## Cumulative Poisson '==' Cumulative Chi^2 :
    ## Abramowitz & Stegun, p.941 :	 26.4.21 (26.4.2)
    n1 <- 20; n2 <- 16
    for(lambda in rexp(n1))
        for(k in rpois(n2, lambda)) {
            tst <- all.equal(1 - pchisq(2*lambda, 2*(1+ 0:k)),
                    pp <- cumsum(dpois(0:k, lambda=lambda)), tol= 100*Meps)
            if(!isTRUE(tst))
                cat("lambda=", format(lambda),".  k =",k, " --> tst=", tst,"\n")
            tst2 <- all.equal(pp, ppois(0:k, lambda=lambda), tol = 100*Meps)
            if(!isTRUE(tst2))
                cat("lambda=", format(lambda),".  k =",k, " --> tst2=", tst2,"\n")
            tst3 <- all.equal(1 - pp, ppois(0:k, lambda=lambda, lower.tail=FALSE))
            if(!isTRUE(tst3))
                cat("lambda=", format(lambda),".  k =",k, " --> tst3=", tst3,"\n")
        }
    
    
    ##__ 6. SignRank __
    for(n in rpois(32, lam=8)) {
        x <- -1:(n + 4)
        if(!isTRUE(eq <- All.eq(psignrank(x, n), cumsum(dsignrank(x, n)))))
            print(eq)
    }
    
    ##__ 7. Wilcoxon (symmetry & cumulative) __
    is.sym <- TRUE
    for(n in rpois(5, lam=6))
        for(m in rpois(15, lam=8)) {
            x <- -1:(n*m + 1)
            fx <- dwilcox(x, n, m)
            Fx <- pwilcox(x, n, m)
            is.sym <- is.sym & all(fx == dwilcox(x, m, n))
            if(!isTRUE(eq <- All.eq(Fx, cumsum(fx))))
                print(eq)
        }
    is.sym
    
    
    ###-------- Continuous Distributions ----------
    
    ##---  Gamma (incl. central chi^2) Density :
    x <- round(rgamma(100, shape = 2),2)
    for(sh in round(rlnorm(30),2)) {
        Ga <- gamma(sh)
        for(sig in round(rlnorm(30),2)) {
            tst <- all.equal((d1 <- dgamma(	 x,   shape = sh, scale = sig)),
                    (d2 <- dgamma(x/sig, shape = sh, scale = 1) / sig),
                    tol = 1e-14)## __ad interim__ was 1e-15
            if(!isTRUE(tst))
                cat("ERROR: dgamma() doesn't scale:",tst,"\n",
                        "  x =", formatC(x),"\n	 shape,scale=",formatC(c(sh, sig)),"\n")
            tst <- All.eq(d1, (d3 <- 1/(Ga * sig^sh) * x^(sh-1) * exp(-x/sig)))
            if(!isTRUE(tst))
                cat("NOT Equal:",tst,"\n x =", formatC(x),
                        "\n  shape,scale=",formatC(c(sh, sig)),"\n")
        }
    }
    pgamma(1,Inf,scale=Inf) == 0
    ## Also pgamma(Inf,Inf) == 1 for which NaN was slightly more appropriate
    all(is.nan(c(pgamma(Inf,  1,scale=Inf),
                            pgamma(Inf,Inf,scale=Inf))))
    scLrg <- c(2,100, 1e300*c(.1, 1,10,100), 1e307, xMax, Inf)
    stopifnot(pgamma(Inf, 1, scale=xMax) == 1,
            pgamma(xMax,1, scale=Inf) == 0,
            all.equal(pgamma(1e300, 2, scale= scLrg, log=TRUE),
                    c(0, 0, -0.000499523968713701, -1.33089326820406,
                            -5.36470502873211, -9.91015144019122,
                            -32.9293385491433, -38.707517174609, -Inf), tol=2e-15)
    )
    
    p <- 7e-4; df <- 0.9
    abs(1-c(pchisq(qchisq(p, df),df)/p, # was 2.31e-8 for R <= 1.8.1
                    pchisq(qchisq(1-p, df,lower=FALSE),df,lower=FALSE)/(1-p),# was 1.618e-11
                    pchisq(qchisq(log(p), df,log=TRUE),df, log=TRUE)/log(p), # was 3.181e-9
                    pchisq(qchisq(log(1-p),df,log=T,lower=F),df, log=T,lower=F)/log(1-p)
            )# 32b-i386: (2.2e-16, 0,0, 3.3e-16); Opteron: (2.2e-16, 0,0, 2.2e-15)
    ) < 1e-14
    
    ##-- non central Chi^2 :
    xB <- c(2000,1e6,1e50,Inf)
    for(df in c(0.1, 1, 10))
        for(ncp in c(0, 1, 10, 100)) stopifnot(pchisq(xB, df=df, ncp=ncp) == 1)
    all.equal(qchisq(0.025,31,ncp=1,lower.tail=FALSE),# inf.loop PR#875
            49.7766246561514, tol= 1e-11)
    for(df in c(0.1, 0.5, 1.5, 4.7, 10, 20,50,100)) {
        cat("df =", formatC(df, wid=3))
        xx <- c(10^-(5:1), .9, 1.2, df + c(3,7,20,30,35,38))
        pp <- pchisq(xx, df=df, ncp = 1) #print(pp)
        dtol <- 1e-12 *(if(2 < df && df <= 50) 64 else if(df > 50) 20000 else 501)
        print(all.equal(xx, qchisq(pp, df=df, ncp=1), tol = dtol))# TRUE
        ##or print(mapply(rErr, xx, qchisq(pp, df=df,ncp=1)), digits = 3)
    }
    
    ## p ~= 1 (<==> 1-p ~= 0) -- gave infinite loop in R <= 1.8.1 -- PR#6421
    options(warn=-1) # ignore warnings from R's version of log1p
    psml <- 2^-(10:54)
    q0 <- qchisq(psml,    df=1.2, ncp=10, lower.tail=FALSE)
    q1 <- qchisq(1-psml, df=1.2, ncp=10) # inaccurate in the tail
    p0 <- pchisq(q0, df=1.2, ncp=10, lower.tail=FALSE)
    p1 <- pchisq(q1, df=1.2, ncp=10, lower.tail=FALSE)
    iO <- 1:30
    all.equal(q0[iO], q1[iO], 1e-5)
    all.equal(p0[iO], psml[iO])
    options(warn=0)
    
    ##--- Beta (need more):
    
    ## big a & b (PR #643)
    summary(a <- rlnorm(20, 5.5))
    summary(b <- rlnorm(20, 6.5))
    pab <- expand.grid(seq(0,1,by=.1), a, b)
    p <- pab[,1]; a <- pab[,2]; b <- pab[,3]
    all.equal(dbeta(p,a,b), exp(pab <- dbeta(p,a,b, log = TRUE)), tol = 1e-11)
    sample(pab, 50)
    
    
    ##--- Normal (& Lognormal) :
    
    qnorm(0) == -Inf && qnorm(-Inf, log = TRUE) == -Inf
    qnorm(1) ==  Inf && qnorm(0, log = TRUE) == Inf
    
    is.nan(qnorm(1.1)) &&
            is.nan(qnorm(-.1)) # + warn
    
    x <- c(-Inf, -1e100, 1:6, 1e200, Inf)
    rbind(d.s0 =dnorm(x,3,s=0),   p.s0 = pnorm(x,3,s=0),
            d.sI =dnorm(x,3,s=Inf), p.sI = pnorm(x,3,s=Inf))
    
    ## 3 Test data from Wichura (1988) :
    all.equal(qnorm(c( 0.25,  .001,	 1e-20)),
            c(-0.6744897501960817, -3.090232306167814, -9.262340089798408),
            tol = 1e-15)
# extreme tail -- available on log scale only:
    all.equal(qnorm(-1e5, log = TRUE), -447.1974945)
    
    z <- rnorm(1000); all.equal(pnorm(z),  1 - pnorm(-z), tol= 1e-15)
    z <- c(-Inf,Inf,NA,NaN, rt(1000, df=2))
    z.ok <- z > -37.5 | !is.finite(z)
    for(df in 1:10) if(!isTRUE(all.equal(pt(z, df), 1 - pt(-z,df), tol= 1e-15)))
            cat("ERROR -- df = ", df, "\n")
    All.eq(pz <- pnorm(z), 1 - pnorm(z, lower=FALSE))
    All.eq(pz,		 pnorm(-z, lower=FALSE))
    All.eq(log(pz[z.ok]),  pnorm(z[z.ok], log=TRUE))
    y <- seq(-70,0, by = 10)
    cbind(y, "log(pnorm(y))"= log(pnorm(y)), "pnorm(y, log=T)"= pnorm(y, log=TRUE))
    y <- c(1:15, seq(20,40, by=5))
    cbind(y, "log(pnorm(y))"= log(pnorm(y)), "pnorm(y, log=T)"= pnorm(y, log=TRUE),
            "log(pnorm(-y))"= log(pnorm(-y)), "pnorm(-y, log=T)"= pnorm(-y, log=TRUE))
    ## Symmetry:
    y <- c(1:50,10^c(3:10,20,50,150,250))
    y <- c(-y,0,y)
    for(L in c(FALSE,TRUE))
        stopifnot(identical(pnorm(-y, log= L),
                        pnorm(+y, log= L, lower=FALSE)))
    
    ## Log norm
    All.eq(pz, plnorm(exp(z)))
    