update
[morpheus.git] / pkg / tests / testthat / test-alignMatrices.R
1 # Helper to generate a random series of matrices to align
2 .generateMatrices = function(d, K, N, noise)
3 {
4 matrices = list( matrix(runif(d*K, min=-1, max=1),ncol=K) ) #reference
5 for (i in 2:(N+1))
6 {
7 matrices[[i]] <- matrices[[1]][,sample(1:K)]
8 if (noise)
9 matrices[[i]] = matrices[[i]] + matrix(rnorm(d*K, sd=0.05), ncol=K)
10 }
11 matrices
12 }
13
14 test_that("labelSwitchingAlign correctly aligns de-noised parameters",
15 {
16 N <- 30 #number of matrices
17 d_K_list <- list(c(2,2), c(5,3))
18 for (i in 1:2)
19 {
20 d <- d_K_list[[i]][1]
21 K <- d_K_list[[i]][2]
22
23 # 1] Generate matrix series
24 Ms <- .generateMatrices(d, K, N, noise=FALSE)
25
26 # 2] Call align function with mode=approx1
27 aligned <- alignMatrices(Ms[2:(N+1)], ref=Ms[[1]], ls_mode="approx1")
28
29 # 3] Check alignment
30 for (j in 1:N)
31 expect_equal(aligned[[j]], Ms[[1]])
32
33 # 2bis] Call align function with mode=approx2
34 aligned <- alignMatrices(Ms[2:(N+1)], ref=Ms[[1]], ls_mode="approx2")
35
36 # 3bis] Check alignment
37 for (j in 1:N)
38 expect_equal(aligned[[j]], Ms[[1]])
39 }
40 })
41
42 test_that("labelSwitchingAlign correctly aligns noisy parameters",
43 {
44 N <- 30 #number of matrices
45 d_K_list <- list(c(2,2), c(5,3))
46 for (i in 1:2)
47 {
48 d <- d_K_list[[i]][1]
49 K <- d_K_list[[i]][2]
50 max_error <- d * 0.2 #TODO: what value to choose ?
51
52 # 1] Generate matrix series
53 Ms <- .generateMatrices(d, K, N, noise=TRUE)
54
55 # 2] Call align function
56 aligned <- alignMatrices(Ms[2:(N+1)], ref=Ms[[1]], ls_mode="exact")
57
58 # 3] Check alignment
59 for (j in 2:N)
60 expect_lt( norm(aligned[[j]] - Ms[[1]]), max_error )
61 }
62 })