| 1 | context("Moments_M2") |
| 2 | |
| 3 | # (Slower, but trusted) R version of Moments_M2 |
| 4 | .Moments_M2_R = function(X,Y) |
| 5 | { |
| 6 | library(tensor) |
| 7 | n = nrow(X) |
| 8 | d = ncol(X) |
| 9 | v = rep(0,d) |
| 10 | e = diag(rep(1,d)) |
| 11 | |
| 12 | M21 = M2_1 = tensor(v,v) |
| 13 | for (i in 1:n) |
| 14 | M21 = M21 + Y[i] * tensor(X[i,],X[i,]) |
| 15 | M21 = (1/n) * M21 |
| 16 | |
| 17 | for (j in 1:d) |
| 18 | { |
| 19 | L = tensor(v,v) |
| 20 | for (i in 1:n) |
| 21 | L = L + Y[i]*tensor(e[,j],e[,j]) |
| 22 | L = (1/n) * L |
| 23 | M2_1 = M2_1 + L |
| 24 | } |
| 25 | |
| 26 | M2 = M21 - M2_1 |
| 27 | return (M2) |
| 28 | } |
| 29 | |
| 30 | test_that("both versions of Moments_M2 agree on various inputs", |
| 31 | { |
| 32 | for (n in c(20,200)) |
| 33 | { |
| 34 | for (d in c(2,10,20)) |
| 35 | { |
| 36 | X = matrix( runif(n*d,min=-1,max=1), nrow=n ) |
| 37 | Y = runif(n,min=-1,max=1) |
| 38 | M2 = .Moments_M2(X,Y) |
| 39 | M2_R = .Moments_M2_R(X,Y) |
| 40 | expect_equal(max(abs(M2 - M2_R)), 0) |
| 41 | } |
| 42 | } |
| 43 | }) |