4d43b2b3801daa880ce004c7a2eb9f73f0894a9b
[epclust.git] / epclust / R / clustering.R
1 #' @name clustering
2 #' @rdname clustering
3 #' @aliases clusteringTask1 computeClusters1 computeClusters2
4 #'
5 #' @title Two-stage clustering, withing one task (see \code{claws()})
6 #'
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
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)
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 #' @param distances matrix of K1 x K1 (WER) distances between synchrones
22 #' @inheritParams computeSynchrones
23 #' @inheritParams claws
24 #'
25 #' @return For \code{clusteringTask1()} and \code{computeClusters1()}, the indices of the
26 #' computed (K1) medoids. Indices are irrelevant for stage 2 clustering, thus
27 #' \code{computeClusters2()} outputs a big.matrix of medoids
28 #' (of size limited by nb_series_per_chunk)
29 NULL
30
31 #' @rdname clustering
32 #' @export
33 clusteringTask1 = function(
34 indices, getContribs, K1, nb_series_per_chunk, ncores_clust=1, verbose=FALSE, parll=TRUE)
35 {
36 if (verbose)
37 cat(paste("*** Clustering task 1 on ",length(indices)," lines\n", sep=""))
38
39 if (parll)
40 {
41 cl = parallel::makeCluster(ncores_clust)
42 parallel::clusterExport(cl, varlist=c("getContribs","K1","verbose"), envir=environment())
43 }
44 while (length(indices) > K1)
45 {
46 indices_workers = .spreadIndices(indices, nb_series_per_chunk)
47 indices <-
48 if (parll)
49 {
50 unlist( parallel::parLapply(cl, indices_workers, function(inds) {
51 require("epclust", quietly=TRUE)
52 inds[ computeClusters1(getContribs(inds), K1, verbose) ]
53 }) )
54 }
55 else
56 {
57 unlist( lapply(indices_workers, function(inds)
58 inds[ computeClusters1(getContribs(inds), K1, verbose) ]
59 ) )
60 }
61 }
62 if (parll)
63 parallel::stopCluster(cl)
64
65 indices #medoids
66 }
67
68 #' @rdname clustering
69 #' @export
70 clusteringTask2 = function(medoids, K2,
71 getRefSeries, nb_ref_curves, nb_series_per_chunk, ncores_clust=1,verbose=FALSE,parll=TRUE)
72 {
73 if (verbose)
74 cat(paste("*** Clustering task 2 on ",nrow(medoids)," lines\n", sep=""))
75
76 if (nrow(medoids) <= K2)
77 return (medoids)
78 synchrones = computeSynchrones(medoids,
79 getRefSeries, nb_ref_curves, nb_series_per_chunk, ncores_clust, verbose, parll)
80 distances = computeWerDists(synchrones, ncores_clust, verbose, parll)
81 medoids[ computeClusters2(distances,K2,verbose), ]
82 }
83
84 #' @rdname clustering
85 #' @export
86 computeClusters1 = function(contribs, K1, verbose=FALSE)
87 {
88 if (verbose)
89 cat(paste(" computeClusters1() on ",nrow(contribs)," lines\n", sep=""))
90 cluster::pam(contribs, K1, diss=FALSE)$id.med
91 }
92
93 #' @rdname clustering
94 #' @export
95 computeClusters2 = function(distances, K2, verbose=FALSE)
96 {
97 if (verbose)
98 cat(paste(" computeClusters2() on ",nrow(distances)," lines\n", sep=""))
99 cluster::pam(distances, K2, diss=TRUE)$id.med
100 }
101
102 #' computeSynchrones
103 #'
104 #' Compute the synchrones curves (sum of clusters elements) from a matrix of medoids,
105 #' using L2 distances.
106 #'
107 #' @param medoids big.matrix of medoids (curves of same length as initial series)
108 #' @param getRefSeries Function to retrieve initial series (e.g. in stage 2 after series
109 #' have been replaced by stage-1 medoids)
110 #' @param nb_ref_curves How many reference series? (This number is known at this stage)
111 #' @inheritParams claws
112 #'
113 #' @return A big.matrix of size K1 x L where L = data_length
114 #'
115 #' @export
116 computeSynchrones = function(medoids, getRefSeries,
117 nb_ref_curves, nb_series_per_chunk, ncores_clust=1,verbose=FALSE,parll=TRUE)
118 {
119 if (verbose)
120 cat(paste("--- Compute synchrones\n", sep=""))
121
122 computeSynchronesChunk = function(indices)
123 {
124 ref_series = getRefSeries(indices)
125 nb_series = nrow(ref_series)
126
127 if (parll)
128 {
129 require("bigmemory", quietly=TRUE)
130 require("synchronicity", quietly=TRUE)
131 require("epclust", quietly=TRUE)
132 synchrones <- bigmemory::attach.big.matrix(synchrones_desc)
133 medoids <- bigmemory::attach.big.matrix(medoids_desc)
134 m <- synchronicity::attach.mutex(m_desc)
135 }
136
137
138
139 #TODO: use dbs(),
140 #https://www.r-bloggers.com/debugging-parallel-code-with-dbs/
141 #http://gforge.se/2015/02/how-to-go-parallel-in-r-basics-tips/
142
143 #OK ::
144 #write(length(indices), file="TOTO")
145 #write( computeMedoidsIndices(medoids@address, getRefSeries(indices[1:600])), file="TOTO")
146 #stop()
147
148 # write(indices, file="TOTO", ncolumns=10, append=TRUE)
149 #write("medoids", file = "TOTO", ncolumns=1, append=TRUE)
150 #write(medoids[1,1:3], file = "TOTO", ncolumns=1, append=TRUE)
151 #write("synchrones", file = "TOTO", ncolumns=1, append=TRUE)
152 #write(synchrones[1,1:3], file = "TOTO", ncolumns=1, append=TRUE)
153
154 #NOT OK :: (should just be "ref_series") ...or yes ? race problems mutex then ? ?!
155 #get medoids indices for this chunk of series
156 mi = computeMedoidsIndices(medoids@address, getRefSeries(indices[1:600])) #ref_series)
157 write("MI ::::", file = "TOTO", ncolumns=1, append=TRUE)
158 write(mi[1:3], file = "TOTO", ncolumns=1, append=TRUE)
159
160 # #R-equivalent, requiring a matrix (thus potentially breaking "fit-in-memory" hope)
161 # mat_meds = medoids[,]
162 # mi = rep(NA,nb_series)
163 # for (i in 1:nb_series)
164 # mi[i] <- which.min( rowSums( sweep(mat_meds, 2, ref_series[i,], '-')^2 ) )
165 # rm(mat_meds); gc()
166
167 for (i in seq_len(nb_series))
168 {
169 if (parll)
170 synchronicity::lock(m)
171 synchrones[mi[i],] = synchrones[mi[i],] + ref_series[i,]
172 counts[mi[i],1] = counts[mi[i],1] + 1
173 if (parll)
174 synchronicity::unlock(m)
175 }
176 }
177
178 K = nrow(medoids) ; L = ncol(medoids)
179 # Use bigmemory (shared==TRUE by default) + synchronicity to fill synchrones in //
180 # TODO: if size > RAM (not our case), use file-backed big.matrix
181 synchrones = bigmemory::big.matrix(nrow=K, ncol=L, type="double", init=0.)
182 counts = bigmemory::big.matrix(nrow=K, ncol=1, type="double", init=0)
183 # synchronicity is only for Linux & MacOS; on Windows: run sequentially
184 parll = (requireNamespace("synchronicity",quietly=TRUE)
185 && parll && Sys.info()['sysname'] != "Windows")
186 if (parll)
187 {
188 m <- synchronicity::boost.mutex()
189 m_desc <- synchronicity::describe(m)
190 synchrones_desc = bigmemory::describe(synchrones)
191 medoids_desc = bigmemory::describe(medoids)
192
193 cl = parallel::makeCluster(ncores_clust)
194 parallel::clusterExport(cl,
195 varlist=c("synchrones_desc","counts","verbose","m_desc","medoids_desc","getRefSeries"),
196 envir=environment())
197 }
198
199 indices_workers = .spreadIndices(seq_len(nb_ref_curves), nb_series_per_chunk)
200 ignored <-
201 if (parll)
202 parallel::parLapply(cl, indices_workers, computeSynchronesChunk)
203 else
204 lapply(indices_workers, computeSynchronesChunk)
205
206 if (parll)
207 parallel::stopCluster(cl)
208
209 #TODO: can we avoid this loop? ( synchrones = sweep(synchrones, 1, counts, '/') )
210 for (i in seq_len(K))
211 synchrones[i,] = synchrones[i,] / counts[i,1]
212 #NOTE: odds for some clusters to be empty? (when series already come from stage 2)
213 # ...maybe; but let's hope resulting K1' be still quite bigger than K2
214 noNA_rows = sapply(seq_len(K), function(i) all(!is.nan(synchrones[i,])))
215 if (all(noNA_rows))
216 return (synchrones)
217 # Else: some clusters are empty, need to slice synchrones
218 synchrones[noNA_rows,]
219 }
220
221 #' computeWerDists
222 #'
223 #' Compute the WER distances between the synchrones curves (in rows), which are
224 #' returned (e.g.) by \code{computeSynchrones()}
225 #'
226 #' @param synchrones A big.matrix of synchrones, in rows. The series have same length
227 #' as the series in the initial dataset
228 #' @inheritParams claws
229 #'
230 #' @return A matrix of size K1 x K1
231 #'
232 #' @export
233 computeWerDists = function(synchrones, ncores_clust=1,verbose=FALSE,parll=TRUE)
234 {
235 if (verbose)
236 cat(paste("--- Compute WER dists\n", sep=""))
237
238 n <- nrow(synchrones)
239 delta <- ncol(synchrones)
240 #TODO: automatic tune of all these parameters ? (for other users)
241 nvoice <- 4
242 # noctave = 2^13 = 8192 half hours ~ 180 days ; ~log2(ncol(synchrones))
243 noctave = 13
244 # 4 here represent 2^5 = 32 half-hours ~ 1 day
245 #NOTE: default scalevector == 2^(0:(noctave * nvoice) / nvoice) * s0 (?)
246 scalevector <- 2^(4:(noctave * nvoice) / nvoice + 1)
247 #condition: ( log2(s0*w0/(2*pi)) - 1 ) * nvoice + 1.5 >= 1
248 s0=2
249 w0=2*pi
250 scaled=FALSE
251 s0log = as.integer( (log2( s0*w0/(2*pi) ) - 1) * nvoice + 1.5 )
252 totnoct = noctave + as.integer(s0log/nvoice) + 1
253
254 Xwer_dist <- bigmemory::big.matrix(nrow=n, ncol=n, type="double")
255 fcoefs = rep(1/3, 3) #moving average on 3 values
256
257 # Generate n(n-1)/2 pairs for WER distances computations
258 pairs = list()
259 V = seq_len(n)
260 for (i in 1:n)
261 {
262 V = V[-1]
263 pairs = c(pairs, lapply(V, function(v) c(i,v)))
264 }
265
266 # Distance between rows i and j
267 computeDistancesIJ = function(pair)
268 {
269 require("bigmemory", quietly=TRUE)
270 require("epclust", quietly=TRUE)
271 synchrones <- bigmemory::attach.big.matrix(synchrones_desc)
272 Xwer_dist <- bigmemory::attach.big.matrix(Xwer_dist_desc)
273
274 computeCWT = function(i)
275 {
276 ts <- scale(ts(synchrones[i,]), center=TRUE, scale=scaled)
277 totts.cwt = Rwave::cwt(ts, totnoct, nvoice, w0, plot=FALSE)
278 ts.cwt = totts.cwt[,s0log:(s0log+noctave*nvoice)]
279 #Normalization
280 sqs <- sqrt(2^(0:(noctave*nvoice)/nvoice)*s0)
281 sqres <- sweep(ts.cwt,2,sqs,'*')
282 sqres / max(Mod(sqres))
283 }
284
285 i = pair[1] ; j = pair[2]
286 if (verbose && j==i+1)
287 cat(paste(" Distances (",i,",",j,"), (",i,",",j+1,") ...\n", sep=""))
288 cwt_i = computeCWT(i)
289 cwt_j = computeCWT(j)
290 num <- epclustFilter(Mod(cwt_i * Conj(cwt_j)))
291 WX <- epclustFilter(Mod(cwt_i * Conj(cwt_i)))
292 WY <- epclustFilter(Mod(cwt_j * Conj(cwt_j)))
293 wer2 <- sum(colSums(num)^2) / sum(colSums(WX) * colSums(WY))
294 Xwer_dist[i,j] <- sqrt(delta * ncol(cwt_i) * (1 - wer2))
295 Xwer_dist[j,i] <- Xwer_dist[i,j]
296 Xwer_dist[i,i] = 0.
297 }
298
299 if (parll)
300 {
301 cl = parallel::makeCluster(ncores_clust)
302 synchrones_desc <- bigmemory::describe(synchrones)
303 Xwer_dist_desc_desc <- bigmemory::describe(Xwer_dist)
304
305 parallel::clusterExport(cl, varlist=c("synchrones_desc","Xwer_dist_desc","totnoct",
306 "nvoice","w0","s0log","noctave","s0","verbose"), envir=environment())
307 }
308
309 ignored <-
310 if (parll)
311 parallel::parLapply(cl, pairs, computeDistancesIJ)
312 else
313 lapply(pairs, computeDistancesIJ)
314
315 if (parll)
316 parallel::stopCluster(cl)
317
318 Xwer_dist[n,n] = 0.
319 distances <- Xwer_dist[,]
320 rm(Xwer_dist) ; gc()
321 distances #~small matrix K1 x K1
322 }
323
324 # Helper function to divide indices into balanced sets
325 .spreadIndices = function(indices, nb_per_chunk)
326 {
327 L = length(indices)
328 nb_workers = floor( L / nb_per_chunk )
329 if (nb_workers == 0)
330 {
331 # L < nb_series_per_chunk, simple case
332 indices_workers = list(indices)
333 }
334 else
335 {
336 indices_workers = lapply( seq_len(nb_workers), function(i)
337 indices[(nb_per_chunk*(i-1)+1):(nb_per_chunk*i)] )
338 # Spread the remaining load among the workers
339 rem = L %% nb_per_chunk
340 while (rem > 0)
341 {
342 index = rem%%nb_workers + 1
343 indices_workers[[index]] = c(indices_workers[[index]], indices[L-rem+1])
344 rem = rem - 1
345 }
346 }
347 indices_workers
348 }