f5e497fa0784078768e9ab7bf9d530817510a661
[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 #' @inheritParams computeSynchrones
22 #' @inheritParams claws
23 #'
24 #' @return For \code{clusteringTask1()} and \code{computeClusters1()}, the indices of the
25 #' computed (K1) medoids. Indices are irrelevant for stage 2 clustering, thus
26 #' \code{computeClusters2()} outputs a big.matrix of medoids
27 #' (of size limited by nb_series_per_chunk)
28 NULL
29
30 #' @rdname clustering
31 #' @export
32 clusteringTask1 = function(
33 indices, getContribs, K1, nb_series_per_chunk, ncores_clust=1, verbose=FALSE, parll=TRUE)
34 {
35 if (verbose)
36 cat(paste("*** Clustering task on ",length(indices)," lines\n", sep=""))
37
38 wrapComputeClusters1 = function(inds) {
39 if (parll)
40 require("epclust", quietly=TRUE)
41 if (verbose)
42 cat(paste(" computeClusters1() on ",length(inds)," lines\n", sep=""))
43 inds[ computeClusters1(getContribs(inds), K1) ]
44 }
45
46 if (parll)
47 {
48 cl = parallel::makeCluster(ncores_clust)
49 parallel::clusterExport(cl, varlist=c("getContribs","K1","verbose"), envir=environment())
50 }
51 while (length(indices) > K1)
52 {
53 indices_workers = .spreadIndices(indices, nb_series_per_chunk)
54 if (parll)
55 indices = unlist( parallel::parLapply(cl, indices_workers, wrapComputeClusters1) )
56 else
57 indices = unlist( lapply(indices_workers, wrapComputeClusters1) )
58 }
59 if (parll)
60 parallel::stopCluster(cl)
61
62 indices #medoids
63 }
64
65 #' @rdname clustering
66 #' @export
67 clusteringTask2 = function(medoids, K2,
68 getRefSeries, nb_ref_curves, nb_series_per_chunk, ncores_clust=1,verbose=FALSE,parll=TRUE)
69 {
70 if (nrow(medoids) <= K2)
71 return (medoids)
72 synchrones = computeSynchrones(medoids,
73 getRefSeries, nb_ref_curves, nb_series_per_chunk, ncores_clust, verbose, parll)
74 distances = computeWerDists(synchrones, ncores_clust, verbose, parll)
75 # PAM in package 'cluster' cannot take big.matrix in input: need to cast it
76 mat_dists = matrix(nrow=K1, ncol=K1)
77 for (i in seq_len(K1))
78 mat_dists[i,] = distances[i,]
79 medoids[ computeClusters2(mat_dists,K2), ]
80 }
81
82 #' @rdname clustering
83 #' @export
84 computeClusters1 = function(contribs, K1)
85 cluster::pam(contribs, K1, diss=FALSE)$id.med
86
87 #' @rdname clustering
88 #' @export
89 computeClusters2 = function(distances, K2)
90 cluster::pam(distances, K2, diss=TRUE)$id.med
91
92 #' computeSynchrones
93 #'
94 #' Compute the synchrones curves (sum of clusters elements) from a matrix of medoids,
95 #' using L2 distances.
96 #'
97 #' @param medoids big.matrix of medoids (curves of same length as initial series)
98 #' @param getRefSeries Function to retrieve initial series (e.g. in stage 2 after series
99 #' have been replaced by stage-1 medoids)
100 #' @param nb_ref_curves How many reference series? (This number is known at this stage)
101 #' @inheritParams claws
102 #'
103 #' @return A big.matrix of size K1 x L where L = data_length
104 #'
105 #' @export
106 computeSynchrones = function(medoids, getRefSeries,
107 nb_ref_curves, nb_series_per_chunk, ncores_clust=1,verbose=FALSE,parll=TRUE)
108 {
109
110
111
112 #TODO: si parll, getMedoids + serialization, pass only getMedoids to nodes
113 # --> BOF... chaque node chargera tous les medoids (efficacité) :/ ==> faut que ça tienne en RAM
114 #au pire :: C-ifier et charger medoids 1 by 1...
115
116 #MIEUX :: medoids DOIT etre une big.matrix partagée !
117
118 computeSynchronesChunk = function(indices)
119 {
120 if (verbose)
121 cat(paste("--- Compute synchrones for ",length(indices)," lines\n", sep=""))
122 ref_series = getRefSeries(indices)
123 #get medoids indices for this chunk of series
124 for (i in seq_len(nrow(ref_series)))
125 {
126 j = which.min( rowSums( sweep(medoids, 2, ref_series[i,], '-')^2 ) )
127 if (parll)
128 synchronicity::lock(m)
129 synchrones[j,] = synchrones[j,] + ref_series[i,]
130 counts[j,1] = counts[j,1] + 1
131 if (parll)
132 synchronicity::unlock(m)
133 }
134 }
135
136 K = nrow(medoids)
137 # Use bigmemory (shared==TRUE by default) + synchronicity to fill synchrones in //
138 # TODO: if size > RAM (not our case), use file-backed big.matrix
139 synchrones = bigmemory::big.matrix(nrow=K,ncol=ncol(medoids),type="double",init=0.)
140 counts = bigmemory::big.matrix(nrow=K,ncol=1,type="double",init=0)
141 # synchronicity is only for Linux & MacOS; on Windows: run sequentially
142 parll = (requireNamespace("synchronicity",quietly=TRUE)
143 && parll && Sys.info()['sysname'] != "Windows")
144 if (parll)
145 m <- synchronicity::boost.mutex()
146
147 if (parll)
148 {
149 cl = parallel::makeCluster(ncores_clust)
150 parallel::clusterExport(cl,
151 varlist=c("synchrones","counts","verbose","medoids","getRefSeries"),
152 envir=environment())
153 }
154
155 indices_workers = .spreadIndices(seq_len(nb_ref_curves), nb_series_per_chunk)
156 ignored <-
157 if (parll)
158 parallel::parLapply(indices_workers, computeSynchronesChunk)
159 else
160 lapply(indices_workers, computeSynchronesChunk)
161
162 if (parll)
163 parallel::stopCluster(cl)
164
165 #TODO: can we avoid this loop? ( synchrones = sweep(synchrones, 1, counts, '/') )
166 for (i in seq_len(K))
167 synchrones[i,] = synchrones[i,] / counts[i,1]
168 #NOTE: odds for some clusters to be empty? (when series already come from stage 2)
169 # ...maybe; but let's hope resulting K1' be still quite bigger than K2
170 noNA_rows = sapply(seq_len(K), function(i) all(!is.nan(synchrones[i,])))
171 if (all(noNA_rows))
172 return (synchrones)
173 # Else: some clusters are empty, need to slice synchrones
174 synchrones[noNA_rows,]
175 }
176
177 #' computeWerDists
178 #'
179 #' Compute the WER distances between the synchrones curves (in rows), which are
180 #' returned (e.g.) by \code{computeSynchrones()}
181 #'
182 #' @param synchrones A big.matrix of synchrones, in rows. The series have same length
183 #' as the series in the initial dataset
184 #' @inheritParams claws
185 #'
186 #' @return A big.matrix of size K1 x K1
187 #'
188 #' @export
189 computeWerDists = function(synchrones, ncores_clust=1,verbose=FALSE,parll=TRUE)
190 {
191
192
193
194 #TODO: re-organize to call computeWerDist(x,y) [C] (in //?) from two indices + big.matrix
195
196
197 n <- nrow(synchrones)
198 delta <- ncol(synchrones)
199 #TODO: automatic tune of all these parameters ? (for other users)
200 nvoice <- 4
201 # noctave = 2^13 = 8192 half hours ~ 180 days ; ~log2(ncol(synchrones))
202 noctave = 13
203 # 4 here represent 2^5 = 32 half-hours ~ 1 day
204 #NOTE: default scalevector == 2^(0:(noctave * nvoice) / nvoice) * s0 (?)
205 scalevector <- 2^(4:(noctave * nvoice) / nvoice + 1)
206 #condition: ( log2(s0*w0/(2*pi)) - 1 ) * nvoice + 1.5 >= 1
207 s0=2
208 w0=2*pi
209 scaled=FALSE
210 s0log = as.integer( (log2( s0*w0/(2*pi) ) - 1) * nvoice + 1.5 )
211 totnoct = noctave + as.integer(s0log/nvoice) + 1
212
213 computeCWT = function(i)
214 {
215 if (verbose)
216 cat(paste("+++ Compute Rwave::cwt() on serie ",i,"\n", sep=""))
217 ts <- scale(ts(synchrones[i,]), center=TRUE, scale=scaled)
218 totts.cwt = Rwave::cwt(ts, totnoct, nvoice, w0, plot=FALSE)
219 ts.cwt = totts.cwt[,s0log:(s0log+noctave*nvoice)]
220 #Normalization
221 sqs <- sqrt(2^(0:(noctave*nvoice)/nvoice)*s0)
222 sqres <- sweep(ts.cwt,2,sqs,'*')
223 sqres / max(Mod(sqres))
224 }
225
226 if (parll)
227 {
228 cl = parallel::makeCluster(ncores_clust)
229 parallel::clusterExport(cl,
230 varlist=c("synchrones","totnoct","nvoice","w0","s0log","noctave","s0","verbose"),
231 envir=environment())
232 }
233
234 # list of CWT from synchrones
235 # TODO: fit in RAM, OK? If not, 2 options: serialize, compute individual distances
236 Xcwt4 <-
237 if (parll)
238 parallel::parLapply(cl, seq_len(n), computeCWT)
239 else
240 lapply(seq_len(n), computeCWT)
241
242 if (parll)
243 parallel::stopCluster(cl)
244
245 Xwer_dist <- bigmemory::big.matrix(nrow=n, ncol=n, type="double")
246 fcoefs = rep(1/3, 3) #moving average on 3 values (TODO: very slow! correct?!)
247 if (verbose)
248 cat("*** Compute WER distances from CWT\n")
249
250 #TODO: computeDistances(i,j), et répartir les n(n-1)/2 couples d'indices
251 #là c'est trop déséquilibré
252
253 computeDistancesLineI = function(i)
254 {
255 if (verbose)
256 cat(paste(" Line ",i,"\n", sep=""))
257 for (j in (i+1):n)
258 {
259 #TODO: 'circular=TRUE' is wrong, should just take values on the sides; to rewrite in C
260 num <- filter(Mod(Xcwt4[[i]] * Conj(Xcwt4[[j]])), fcoefs, circular=TRUE)
261 WX <- filter(Mod(Xcwt4[[i]] * Conj(Xcwt4[[i]])), fcoefs, circular=TRUE)
262 WY <- filter(Mod(Xcwt4[[j]] * Conj(Xcwt4[[j]])), fcoefs, circular=TRUE)
263 wer2 <- sum(colSums(num)^2) / sum( sum(colSums(WX) * colSums(WY)) )
264 if (parll)
265 synchronicity::lock(m)
266 Xwer_dist[i,j] <- sqrt(delta * ncol(Xcwt4[[1]]) * (1 - wer2))
267 Xwer_dist[j,i] <- Xwer_dist[i,j]
268 if (parll)
269 synchronicity::unlock(m)
270 }
271 Xwer_dist[i,i] = 0.
272 }
273
274 parll = (requireNamespace("synchronicity",quietly=TRUE)
275 && parll && Sys.info()['sysname'] != "Windows")
276 if (parll)
277 m <- synchronicity::boost.mutex()
278
279 ignored <-
280 if (parll)
281 {
282 parallel::mclapply(seq_len(n-1), computeDistancesLineI,
283 mc.cores=ncores_clust, mc.allow.recursive=FALSE)
284 }
285 else
286 lapply(seq_len(n-1), computeDistancesLineI)
287 Xwer_dist[n,n] = 0.
288 Xwer_dist
289 }
290
291 # Helper function to divide indices into balanced sets
292 .spreadIndices = function(indices, nb_per_chunk)
293 {
294 L = length(indices)
295 nb_workers = floor( L / nb_per_chunk )
296 if (nb_workers == 0)
297 {
298 # L < nb_series_per_chunk, simple case
299 indices_workers = list(indices)
300 }
301 else
302 {
303 indices_workers = lapply( seq_len(nb_workers), function(i)
304 indices[(nb_per_chunk*(i-1)+1):(nb_per_chunk*i)] )
305 # Spread the remaining load among the workers
306 rem = L %% nb_per_chunk
307 while (rem > 0)
308 {
309 index = rem%%nb_workers + 1
310 indices_workers[[index]] = c(indices_workers[[index]], indices[L-rem+1])
311 rem = rem - 1
312 }
313 }
314 indices_workers
315 }