improvements
[epclust.git] / epclust / R / clustering.R
CommitLineData
4bcfdbee
BA
1#' @name clustering
2#' @rdname clustering
492cd9e7 3#' @aliases clusteringTask1 computeClusters1 computeClusters2
4bcfdbee 4#'
492cd9e7 5#' @title Two-stage clustering, withing one task (see \code{claws()})
4bcfdbee 6#'
492cd9e7
BA
7#' @description \code{clusteringTask1()} runs one full stage-1 task, which consists in
8#' iterated stage 1 clustering (on nb_curves / ntasks energy contributions, computed
bf5c0844
BA
9#' through discrete wavelets coefficients).
10#' \code{clusteringTask2()} runs a full stage-2 task, which consists in synchrones
11#' and then WER distances computations, before applying the clustering algorithm.
12#' \code{computeClusters1()} and \code{computeClusters2()} correspond to the atomic
13#' clustering procedures respectively for stage 1 and 2. The former applies the
14#' clustering algorithm (PAM) on a contributions matrix, while the latter clusters
15#' a chunk of series inside one task (~max nb_series_per_chunk)
4bcfdbee
BA
16#'
17#' @param indices Range of series indices to cluster in parallel (initial data)
18#' @param getContribs Function to retrieve contributions from initial series indices:
19#' \code{getContribs(indices)} outpus a contributions matrix
20#' @param contribs matrix of contributions (e.g. output of \code{curvesToContribs()})
21#' @inheritParams computeSynchrones
22#' @inheritParams claws
23#'
492cd9e7 24#' @return For \code{clusteringTask1()} and \code{computeClusters1()}, the indices of the
4bcfdbee 25#' computed (K1) medoids. Indices are irrelevant for stage 2 clustering, thus
24ed5d83 26#' \code{computeClusters2()} outputs a big.matrix of medoids
4bcfdbee
BA
27#' (of size limited by nb_series_per_chunk)
28NULL
29
30#' @rdname clustering
31#' @export
492cd9e7
BA
32clusteringTask1 = function(
33 indices, getContribs, K1, nb_series_per_chunk, ncores_clust=1, verbose=FALSE, parll=TRUE)
5c652979 34{
492cd9e7 35 if (verbose)
e161499b 36 cat(paste("*** Clustering task 1 on ",length(indices)," lines\n", sep=""))
4bcfdbee 37
492cd9e7 38 if (parll)
7b13d0c2 39 {
492cd9e7
BA
40 cl = parallel::makeCluster(ncores_clust)
41 parallel::clusterExport(cl, varlist=c("getContribs","K1","verbose"), envir=environment())
7b13d0c2 42 }
492cd9e7
BA
43 while (length(indices) > K1)
44 {
45 indices_workers = .spreadIndices(indices, nb_series_per_chunk)
e161499b
BA
46 indices <-
47 if (parll)
48 {
49 unlist( parallel::parLapply(cl, indices_workers, function(inds) {
50 require("epclust", quietly=TRUE)
51 inds[ computeClusters1(getContribs(inds), K1, verbose) ]
52 }) )
53 }
54 else
55 {
56 unlist( lapply(indices_workers, function(inds)
57 inds[ computeClusters1(getContribs(inds), K1, verbose) ]
58 ) )
59 }
492cd9e7
BA
60 }
61 if (parll)
62 parallel::stopCluster(cl)
63
56857861 64 indices #medoids
5c652979
BA
65}
66
4bcfdbee
BA
67#' @rdname clustering
68#' @export
bf5c0844 69clusteringTask2 = function(medoids, K2,
492cd9e7 70 getRefSeries, nb_ref_curves, nb_series_per_chunk, ncores_clust=1,verbose=FALSE,parll=TRUE)
5c652979 71{
e161499b
BA
72 if (verbose)
73 cat(paste("*** Clustering task 2 on ",nrow(medoids)," lines\n", sep=""))
74
bf5c0844
BA
75 if (nrow(medoids) <= K2)
76 return (medoids)
492cd9e7
BA
77 synchrones = computeSynchrones(medoids,
78 getRefSeries, nb_ref_curves, nb_series_per_chunk, ncores_clust, verbose, parll)
79 distances = computeWerDists(synchrones, ncores_clust, verbose, parll)
bf5c0844 80 # PAM in package 'cluster' cannot take big.matrix in input: need to cast it
e161499b 81 medoids[ computeClusters2(distances[,],K2,verbose), ]
5c652979
BA
82}
83
bf5c0844
BA
84#' @rdname clustering
85#' @export
e161499b
BA
86computeClusters1 = function(contribs, K1, verbose=FALSE)
87{
88 if (verbose)
89 cat(paste(" computeClusters1() on ",nrow(contribs)," lines\n", sep=""))
bf5c0844 90 cluster::pam(contribs, K1, diss=FALSE)$id.med
e161499b 91}
bf5c0844
BA
92
93#' @rdname clustering
94#' @export
e161499b
BA
95computeClusters2 = function(distances, K2, verbose=FALSE)
96{
97 if (verbose)
98 cat(paste(" computeClusters2() on ",nrow(distances)," lines\n", sep=""))
bf5c0844 99 cluster::pam(distances, K2, diss=TRUE)$id.med
e161499b 100}
bf5c0844 101
4bcfdbee
BA
102#' computeSynchrones
103#'
104#' Compute the synchrones curves (sum of clusters elements) from a matrix of medoids,
105#' using L2 distances.
106#'
24ed5d83 107#' @param medoids big.matrix of medoids (curves of same length as initial series)
4bcfdbee
BA
108#' @param getRefSeries Function to retrieve initial series (e.g. in stage 2 after series
109#' have been replaced by stage-1 medoids)
492cd9e7 110#' @param nb_ref_curves How many reference series? (This number is known at this stage)
4bcfdbee
BA
111#' @inheritParams claws
112#'
24ed5d83
BA
113#' @return A big.matrix of size K1 x L where L = data_length
114#'
4bcfdbee 115#' @export
492cd9e7
BA
116computeSynchrones = function(medoids, getRefSeries,
117 nb_ref_curves, nb_series_per_chunk, ncores_clust=1,verbose=FALSE,parll=TRUE)
e205f218 118{
e161499b
BA
119 if (verbose)
120 cat(paste("--- Compute synchrones\n", sep=""))
121
492cd9e7 122 computeSynchronesChunk = function(indices)
3eef8d3d 123 {
492cd9e7 124 ref_series = getRefSeries(indices)
e161499b 125 nb_series = nrow(ref_series)
3eef8d3d 126 #get medoids indices for this chunk of series
e161499b
BA
127
128 #TODO: debug this (address is OK but values are garbage: why?)
129# mi = .Call("computeMedoidsIndices", medoids@address, ref_series, PACKAGE="epclust")
130
131 #R-equivalent, requiring a matrix (thus potentially breaking "fit-in-memory" hope)
132 mat_meds = medoids[,]
133 mi = rep(NA,nb_series)
134 for (i in 1:nb_series)
135 mi[i] <- which.min( rowSums( sweep(mat_meds, 2, ref_series[i,], '-')^2 ) )
136 rm(mat_meds); gc()
137
138 for (i in seq_len(nb_series))
56857861 139 {
492cd9e7
BA
140 if (parll)
141 synchronicity::lock(m)
e161499b
BA
142 synchrones[mi[i],] = synchrones[mi[i],] + ref_series[i,]
143 counts[mi[i],1] = counts[mi[i],1] + 1
492cd9e7
BA
144 if (parll)
145 synchronicity::unlock(m)
146 }
147 }
148
e161499b 149 K = nrow(medoids) ; L = ncol(medoids)
492cd9e7 150 # Use bigmemory (shared==TRUE by default) + synchronicity to fill synchrones in //
24ed5d83 151 # TODO: if size > RAM (not our case), use file-backed big.matrix
e161499b
BA
152 synchrones = bigmemory::big.matrix(nrow=K, ncol=L, type="double", init=0.)
153 counts = bigmemory::big.matrix(nrow=K, ncol=1, type="double", init=0)
24ed5d83 154 # synchronicity is only for Linux & MacOS; on Windows: run sequentially
492cd9e7
BA
155 parll = (requireNamespace("synchronicity",quietly=TRUE)
156 && parll && Sys.info()['sysname'] != "Windows")
157 if (parll)
158 m <- synchronicity::boost.mutex()
159
24ed5d83
BA
160 if (parll)
161 {
162 cl = parallel::makeCluster(ncores_clust)
163 parallel::clusterExport(cl,
164 varlist=c("synchrones","counts","verbose","medoids","getRefSeries"),
165 envir=environment())
166 }
167
492cd9e7 168 indices_workers = .spreadIndices(seq_len(nb_ref_curves), nb_series_per_chunk)
e161499b 169 browser()
c45fd663 170 ignored <-
492cd9e7 171 if (parll)
e161499b 172 parallel::parLapply(cl, indices_workers, computeSynchronesChunk)
492cd9e7 173 else
c45fd663 174 lapply(indices_workers, computeSynchronesChunk)
492cd9e7 175
24ed5d83
BA
176 if (parll)
177 parallel::stopCluster(cl)
178
179 #TODO: can we avoid this loop? ( synchrones = sweep(synchrones, 1, counts, '/') )
492cd9e7 180 for (i in seq_len(K))
24ed5d83 181 synchrones[i,] = synchrones[i,] / counts[i,1]
3eef8d3d 182 #NOTE: odds for some clusters to be empty? (when series already come from stage 2)
8702eb86 183 # ...maybe; but let's hope resulting K1' be still quite bigger than K2
24ed5d83
BA
184 noNA_rows = sapply(seq_len(K), function(i) all(!is.nan(synchrones[i,])))
185 if (all(noNA_rows))
186 return (synchrones)
187 # Else: some clusters are empty, need to slice synchrones
188 synchrones[noNA_rows,]
e205f218 189}
1c6f223e 190
4bcfdbee
BA
191#' computeWerDists
192#'
193#' Compute the WER distances between the synchrones curves (in rows), which are
194#' returned (e.g.) by \code{computeSynchrones()}
195#'
24ed5d83
BA
196#' @param synchrones A big.matrix of synchrones, in rows. The series have same length
197#' as the series in the initial dataset
492cd9e7 198#' @inheritParams claws
4bcfdbee 199#'
24ed5d83
BA
200#' @return A big.matrix of size K1 x K1
201#'
4bcfdbee 202#' @export
492cd9e7 203computeWerDists = function(synchrones, ncores_clust=1,verbose=FALSE,parll=TRUE)
d03c0621 204{
e161499b
BA
205 if (verbose)
206 cat(paste("--- Compute WER dists\n", sep=""))
24ed5d83 207
4bcfdbee
BA
208 n <- nrow(synchrones)
209 delta <- ncol(synchrones)
db6fc17d 210 #TODO: automatic tune of all these parameters ? (for other users)
d03c0621 211 nvoice <- 4
4bcfdbee 212 # noctave = 2^13 = 8192 half hours ~ 180 days ; ~log2(ncol(synchrones))
d7d55bc1
BA
213 noctave = 13
214 # 4 here represent 2^5 = 32 half-hours ~ 1 day
db6fc17d 215 #NOTE: default scalevector == 2^(0:(noctave * nvoice) / nvoice) * s0 (?)
24ed5d83 216 scalevector <- 2^(4:(noctave * nvoice) / nvoice + 1)
db6fc17d
BA
217 #condition: ( log2(s0*w0/(2*pi)) - 1 ) * nvoice + 1.5 >= 1
218 s0=2
219 w0=2*pi
220 scaled=FALSE
221 s0log = as.integer( (log2( s0*w0/(2*pi) ) - 1) * nvoice + 1.5 )
222 totnoct = noctave + as.integer(s0log/nvoice) + 1
223
e161499b
BA
224 Xwer_dist <- bigmemory::big.matrix(nrow=n, ncol=n, type="double")
225 fcoefs = rep(1/3, 3) #moving average on 3 values
226
227 # Generate n(n-1)/2 pairs for WER distances computations
228 pairs = list()
229 V = seq_len(n)
230 for (i in 1:n)
231 {
232 V = V[-1]
233 pairs = c(pairs, lapply(V, function(v) c(i,v)))
234 }
235
492cd9e7
BA
236 computeCWT = function(i)
237 {
4bcfdbee 238 ts <- scale(ts(synchrones[i,]), center=TRUE, scale=scaled)
24ed5d83 239 totts.cwt = Rwave::cwt(ts, totnoct, nvoice, w0, plot=FALSE)
db6fc17d
BA
240 ts.cwt = totts.cwt[,s0log:(s0log+noctave*nvoice)]
241 #Normalization
242 sqs <- sqrt(2^(0:(noctave*nvoice)/nvoice)*s0)
af3ea947 243 sqres <- sweep(ts.cwt,2,sqs,'*')
db6fc17d 244 sqres / max(Mod(sqres))
492cd9e7 245 }
3ccd1e39 246
e161499b
BA
247 computeDistancesIJ = function(pair)
248 {
249 i = pair[1] ; j = pair[2]
250 if (verbose && j==i+1)
251 cat(paste(" Distances (",i,",",j,"), (",i,",",j+1,") ...\n", sep=""))
252 cwt_i = computeCWT(i)
253 cwt_j = computeCWT(j)
254 num <- .Call("filter", Mod(cwt_i * Conj(cwt_j)), PACKAGE="epclust")
255 WX <- .Call("filter", Mod(cwt_i * Conj(cwt_i)), PACKAGE="epclust")
256 WY <- .Call("filter", Mod(cwt_j * Conj(cwt_j)), PACKAGE="epclust")
257 wer2 <- sum(colSums(num)^2) / sum(colSums(WX) * colSums(WY))
258 Xwer_dist[i,j] <- sqrt(delta * ncol(cwt_i) * (1 - wer2))
259 Xwer_dist[j,i] <- Xwer_dist[i,j]
260 Xwer_dist[i,i] = 0.
261 }
262
492cd9e7
BA
263 if (parll)
264 {
265 cl = parallel::makeCluster(ncores_clust)
af3ea947
BA
266 parallel::clusterExport(cl,
267 varlist=c("synchrones","totnoct","nvoice","w0","s0log","noctave","s0","verbose"),
268 envir=environment())
492cd9e7
BA
269 }
270
e161499b 271 ignored <-
492cd9e7 272 if (parll)
e161499b 273 parallel::parLapply(cl, pairs, computeDistancesIJ)
492cd9e7 274 else
e161499b 275 lapply(pairs, computeDistancesIJ)
492cd9e7
BA
276
277 if (parll)
278 parallel::stopCluster(cl)
279
492cd9e7 280 Xwer_dist[n,n] = 0.
24ed5d83 281 Xwer_dist
492cd9e7
BA
282}
283
284# Helper function to divide indices into balanced sets
285.spreadIndices = function(indices, nb_per_chunk)
286{
287 L = length(indices)
288 nb_workers = floor( L / nb_per_chunk )
289 if (nb_workers == 0)
290 {
291 # L < nb_series_per_chunk, simple case
292 indices_workers = list(indices)
293 }
294 else
295 {
296 indices_workers = lapply( seq_len(nb_workers), function(i)
297 indices[(nb_per_chunk*(i-1)+1):(nb_per_chunk*i)] )
298 # Spread the remaining load among the workers
299 rem = L %% nb_per_chunk
300 while (rem > 0)
301 {
302 index = rem%%nb_workers + 1
303 indices_workers[[index]] = c(indices_workers[[index]], indices[L-rem+1])
304 rem = rem - 1
d03c0621 305 }
1c6f223e 306 }
492cd9e7 307 indices_workers
1c6f223e 308}