1 naive_f <- function(link, M1,M2,M3, p,β,b)
5 λ <- sqrt(colSums(β^2))
7 # Compute β x2,3 (self) tensorial products
8 β2 <- array(0, dim=c(d,d,K))
9 β3 <- array(0, dim=c(d,d,d,K))
16 β2[i,j,k] = β[i,k]*β[j,k]
18 β3[i,j,l,k] = β[i,k]*β[j,k]*β[l,k]
28 term <- term + p[k]*.G(link,1,λ[k],b[k])*β[i,k]
29 res <- res + (term - M1[i])^2
34 term <- term + p[k]*.G(link,2,λ[k],b[k])*β2[i,j,k]
35 res <- res + (term - M2[i,j])^2
40 term <- term + p[k]*.G(link,3,λ[k],b[k])*β3[i,j,l,k]
41 res <- res + (term - M3[i,j,l])^2
48 # TODO: understand why delta is so large (should be 10^-6 10^-7 ...)
49 test_that("naive computation provides the same result as vectorized computations",
51 h <- 1e-7 #for finite-difference tests
53 for (dK in list( c(2,2), c(5,3)))
59 M2 <- matrix(runif(d^2, -1, 1), ncol=d)
60 M3 <- array(runif(d^3, -1, 1), dim=c(d,d,d))
62 for (link in c("logit","probit"))
64 # X and Y are unused here (W not re-computed)
65 op <- optimParams(X=matrix(runif(n*d),ncol=d), Y=rbinom(n,1,.5),
66 K, link, M=list(M1,M2,M3))
67 op$W <- diag(d + d^2 + d^3)
69 for (var in seq_len((2+d)*K-1))
73 β <- matrix(runif(d*K,-5,5),ncol=K)
75 x <- c(p[1:(K-1)],as.double(β),b)
77 # Test functions values (TODO: 1 is way too high)
78 expect_equal( op$f(x)[1], naive_f(link,M1,M2,M3, p,β,b), tolerance=1 )
80 # Test finite differences ~= gradient values
81 dir_h <- rep(0, (2+d)*K-1)
83 expect_equal( op$grad_f(x)[var], ((op$f(x+dir_h) - op$f(x)) / h)[1], tolerance=0.5 )
89 test_that("W computed in C and in R are the same",
93 for (dK in list( c(2,2))) #, c(5,3)))
97 link <- ifelse(d==2, "logit", "probit")
100 β=matrix(runif(d*K),ncol=K),
102 io <- generateSampleIO(n, θ$p, θ$β, θ$b, link)
108 λ <- sqrt(colSums(β^2))
110 β2 <- apply(β, 2, function(col) col %o% col)
111 β3 <- apply(β, 2, function(col) col %o% col %o% col)
113 β %*% (p * .G(link,1,λ,b)),
114 β2 %*% (p * .G(link,2,λ,b)),
115 β3 %*% (p * .G(link,3,λ,b)))
116 Id <- as.double(diag(d))
119 v2 <- Y * t( apply(X, 1, function(Xi) Xi %o% Xi - Id) )
120 v3 <- Y * t( apply(X, 1, function(Xi) { return (Xi %o% Xi %o% Xi
121 - Reduce('+', lapply(1:d, function(j)
122 as.double(Xi %o% E[j,] %o% E[j,])), rep(0, d*d*d))
123 - Reduce('+', lapply(1:d, function(j)
124 as.double(E[j,] %o% Xi %o% E[j,])), rep(0, d*d*d))
125 - Reduce('+', lapply(1:d, function(j)
126 as.double(E[j,] %o% E[j,] %o% Xi)), rep(0, d*d*d))) } ) )
127 Omega1 <- matrix(0, nrow=dd, ncol=dd)
130 gi <- t(as.matrix(c(v1[i,], v2[i,], v3[i,]) - M))
131 Omega1 <- Omega1 + t(gi) %*% gi / n
133 W <- matrix(0, nrow=dd, ncol=dd)
134 Omega2 <- matrix( .C("Compute_Omega",
135 X=as.double(X), Y=as.integer(Y), M=as.double(M),
136 pnc=as.integer(1), pn=as.integer(n), pd=as.integer(d),
137 W=as.double(W), PACKAGE="morpheus")$W, nrow=dd, ncol=dd )
138 rg <- range(Omega1 - Omega2)
139 expect_equal(rg[1], rg[2], tolerance=tol)