Debian Codegraph @

R/integratexy.R

raw
1 ## This is also sym.linked into
2 ## Martin's WpDensity package /u/maechler/R/Pkgs/WpDensity/
3
4 integrate.xy <- function(x,fx, a,b, use.spline = TRUE, xtol = 2e-8)
5 {
6 if(is.list(x)) {
7 fx <- x$y; x <- x$x
8 if(length(x) == 0)
9 stop("list 'x' has no valid $x component")
10 }
11 if((n <- length(x)) != length(fx))
12 stop("'fx' must have same length as 'x'")
13
14 if(is.unsorted(x)) { i <- sort.list(x); x <- x[i]; fx <- fx[i] }
15 if(any(i <- duplicated(x))) {
16 n <- length(x <- x[!i])
17 ## we might have to check that the same fx[] are duplicated
18 ## otherwise either give an error or take the mean() of those...
19 fx <- fx[!i]
20 }
21 if(any(diff(x) == 0))
22 stop("bug in 'duplicated()' killed me: have still multiple x[]!")
23
24 if(missing(a)) a <- x[1]
25 else if(any(a < x[1])) stop("'a' must NOT be smaller than min(x)")
26 if(missing(b)) b <- x[n]
27 else if(any(b > x[n])) stop("'b' must NOT be larger than max(x)")
28 if(length(a) != 1 && length(b) != 1 && length(a) != length(b))
29 stop("'a' and 'b' must have length 1 or same length !")
30 else {
31 k <- max(length(a),length(b))
32 if(any(b < a)) stop("'b' must be elementwise >= 'a'")
33 }
34
35 if(use.spline) {
36 xy <- spline(x,fx, n = max(1024, 3*n))
37 ##-- Work around spline(.) BUG: (ex.: range(spline(1:20,1:20,n=95)))
38 if(xy$x[length(xy$x)] < x[n]) {
39 if(TRUE) cat("working around spline(.) BUG --- hmm, really?\n\n")
40 xy$x <- c(xy$x, x[n])
41 xy$y <- c(xy$y, fx[n])
42 }
43 ## END if work around ----
44 x <- xy$x; fx <- xy$y
45 n <- length(x)
46 }
47
48 ab <- unique(c(a,b))
49 BB <- abs(outer(x,ab,"-")) < (xtol * max(b - a))
50 if(any(j <- 0 == colSums(BB))) { # the j-th element(s) of ab are not in x[]
51 y <- approx(x,fx, xout = ab[j])$y
52 x <- c(ab[j],x)
53 i <- sort.list(x)
54 x <- x[i]; fx <- c(y,fx)[i]; n <- length(x)
55 }
56
57 ##--- now we could use 'Simpson's formula IFF the x[i] are equispaced... --
58 ##--- Since this may well be wrong, just use 'trapezoid formula':
59
60 dig0 <- floor(-log10(xtol)) #
61 f.match <- function(x,table,dig) match(signif(x,dig), signif(table,dig))
62 ## was (S+) f.match <- function(x,table) match(as.single(x), as.single(table))
63
64 d <- dig0; while(anyNA(ai <- f.match(a,x, d))) d <- d - 1/8 ; ai <- rep_len(ai, k)
65 d <- dig0; while(anyNA(bi <- f.match(b,x, d))) d <- d - 1/8 ; bi <- rep_len(bi, k)
66 dfx <- fx[-c(1,n)] * diff(x,lag = 2)
67 r <- numeric(k)
68 for (i in 1:k) {
69 a <- ai[i]; b <- bi[i]
70 r[i] <- (x[a+1] - x[a])*fx[a] + (x[b] - x[b-1])*fx[b] +
71 sum(dfx[seq(a, length = max(0,b-a-1))])
72 }
73 r/2
74 }