'update'
[epclust.git] / pkg / tests / testthat / test-clustering.R
CommitLineData
b7cd987d
BA
1context("clustering")
2
3test_that("clusteringTask1 behave as expected",
4{
5 # Generate 60 reference sinusoïdal series (medoids to be found),
6 # and sample 900 series around them (add a small noise)
7 n <- 900
8 x <- seq(0,9.5,0.1)
9 L <- length(x) #96 1/4h
10 K1 <- 60
11 s <- lapply( seq_len(K1), function(i) x^(1+i/30)*cos(x+i) )
12 series <- matrix(nrow=L, ncol=n)
13 for (i in seq_len(n))
14 series[,i] <- s[[I(i,K1)]] + rnorm(L,sd=0.01)
15
16 getSeries <- function(indices) {
17 indices <- indices[indices <= n]
18 if (length(indices)>0) as.matrix(series[,indices]) else NULL
19 }
20
21 wf <- "haar"
22 ctype <- "absolute"
23 getContribs <- function(indices) curvesToContribs(as.matrix(series[,indices]),wf,ctype)
24
25 require("cluster", quietly=TRUE)
26 algoClust1 <- function(contribs,K) cluster::pam(t(contribs),K,diss=FALSE)$id.med
27 indices1 <- clusteringTask1(1:n, getContribs, K1, algoClust1, 140, verbose=TRUE)
28 medoids_K1 <- getSeries(indices1)
29
30 expect_equal(dim(medoids_K1), c(L,K1))
31 # Not easy to evaluate result: at least we expect it to be better than random selection of
32 # medoids within initial series
33 distor_good <- computeDistortion(series, medoids_K1)
34 for (i in 1:3)
35 expect_lte( distor_good, computeDistortion(series,series[,sample(1:n, K1)]) )
36})
37
38test_that("clusteringTask2 behave as expected",
39{
40 # Same 60 reference sinusoïdal series than in clusteringTask1 test,
41 # but this time we consider them as medoids - skipping stage 1
42 # Here also we sample 900 series around the 60 "medoids"
43 n <- 900
44 x <- seq(0,9.5,0.1)
45 L <- length(x) #96 1/4h
46 K1 <- 60
47 K2 <- 3
48 #for (i in 1:60) {plot(x^(1+i/30)*cos(x+i),type="l",col=i,ylim=c(-50,50)); par(new=TRUE)}
49 s <- lapply( seq_len(K1), function(i) x^(1+i/30)*cos(x+i) )
50 series <- matrix(nrow=L, ncol=n)
51 for (i in seq_len(n))
52 series[,i] <- s[[I(i,K1)]] + rnorm(L,sd=0.01)
53
54 getSeries <- function(indices) {
55 indices <- indices[indices <= n]
56 if (length(indices)>0) as.matrix(series[,indices]) else NULL
57 }
58
59 # Perfect situation: all medoids "after stage 1" are ~good
60 algoClust2 <- function(dists,K) cluster::pam(dists,K,diss=TRUE)$id.med
61 indices2 <- clusteringTask2(1:K1, getSeries, K2, algoClust2, 210, 3, 4, 8, "little",
62 verbose=TRUE)
63 medoids_K2 <- getSeries(indices2)
64
65 expect_equal(dim(medoids_K2), c(L,K2))
66 # Not easy to evaluate result: at least we expect it to be better than random selection of
67 # synchrones within 1...K1 (from where distances computations + clustering was run)
68 distor_good <- computeDistortion(series, medoids_K2)
69#TODO: This fails; why?
70# for (i in 1:3)
71# expect_lte( distor_good, computeDistortion(series, series[,sample(1:K1,3)]) )
72})