Commit | Line | Data |
---|---|---|
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()}) | |
777c4b02 | 21 | #' @param distances matrix of K1 x K1 (WER) distances between synchrones |
4bcfdbee BA |
22 | #' @inheritParams computeSynchrones |
23 | #' @inheritParams claws | |
24 | #' | |
492cd9e7 | 25 | #' @return For \code{clusteringTask1()} and \code{computeClusters1()}, the indices of the |
4bcfdbee | 26 | #' computed (K1) medoids. Indices are irrelevant for stage 2 clustering, thus |
24ed5d83 | 27 | #' \code{computeClusters2()} outputs a big.matrix of medoids |
4bcfdbee BA |
28 | #' (of size limited by nb_series_per_chunk) |
29 | NULL | |
30 | ||
31 | #' @rdname clustering | |
32 | #' @export | |
492cd9e7 BA |
33 | clusteringTask1 = function( |
34 | indices, getContribs, K1, nb_series_per_chunk, ncores_clust=1, verbose=FALSE, parll=TRUE) | |
5c652979 | 35 | { |
492cd9e7 | 36 | if (verbose) |
e161499b | 37 | cat(paste("*** Clustering task 1 on ",length(indices)," lines\n", sep="")) |
4bcfdbee | 38 | |
492cd9e7 | 39 | if (parll) |
7b13d0c2 | 40 | { |
492cd9e7 BA |
41 | cl = parallel::makeCluster(ncores_clust) |
42 | parallel::clusterExport(cl, varlist=c("getContribs","K1","verbose"), envir=environment()) | |
7b13d0c2 | 43 | } |
492cd9e7 BA |
44 | while (length(indices) > K1) |
45 | { | |
46 | indices_workers = .spreadIndices(indices, nb_series_per_chunk) | |
e161499b BA |
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 | } | |
492cd9e7 BA |
61 | } |
62 | if (parll) | |
63 | parallel::stopCluster(cl) | |
64 | ||
56857861 | 65 | indices #medoids |
5c652979 BA |
66 | } |
67 | ||
4bcfdbee BA |
68 | #' @rdname clustering |
69 | #' @export | |
bf5c0844 | 70 | clusteringTask2 = function(medoids, K2, |
492cd9e7 | 71 | getRefSeries, nb_ref_curves, nb_series_per_chunk, ncores_clust=1,verbose=FALSE,parll=TRUE) |
5c652979 | 72 | { |
e161499b BA |
73 | if (verbose) |
74 | cat(paste("*** Clustering task 2 on ",nrow(medoids)," lines\n", sep="")) | |
75 | ||
bf5c0844 BA |
76 | if (nrow(medoids) <= K2) |
77 | return (medoids) | |
492cd9e7 BA |
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) | |
777c4b02 | 81 | medoids[ computeClusters2(distances,K2,verbose), ] |
5c652979 BA |
82 | } |
83 | ||
bf5c0844 BA |
84 | #' @rdname clustering |
85 | #' @export | |
e161499b BA |
86 | computeClusters1 = 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 |
95 | computeClusters2 = 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 |
116 | computeSynchrones = 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) |
e161499b | 126 | |
363ae134 BA |
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 | ||
363ae134 | 137 | #get medoids indices for this chunk of series |
2c14dbea | 138 | mi = computeMedoidsIndices(medoids@address, ref_series) |
363ae134 BA |
139 | # #R-equivalent, requiring a matrix (thus potentially breaking "fit-in-memory" hope) |
140 | # mat_meds = medoids[,] | |
141 | # mi = rep(NA,nb_series) | |
142 | # for (i in 1:nb_series) | |
143 | # mi[i] <- which.min( rowSums( sweep(mat_meds, 2, ref_series[i,], '-')^2 ) ) | |
144 | # rm(mat_meds); gc() | |
e161499b BA |
145 | |
146 | for (i in seq_len(nb_series)) | |
56857861 | 147 | { |
492cd9e7 BA |
148 | if (parll) |
149 | synchronicity::lock(m) | |
e161499b | 150 | synchrones[mi[i],] = synchrones[mi[i],] + ref_series[i,] |
2c14dbea | 151 | #TODO: remove counts |
e161499b | 152 | counts[mi[i],1] = counts[mi[i],1] + 1 |
492cd9e7 BA |
153 | if (parll) |
154 | synchronicity::unlock(m) | |
155 | } | |
156 | } | |
157 | ||
e161499b | 158 | K = nrow(medoids) ; L = ncol(medoids) |
492cd9e7 | 159 | # Use bigmemory (shared==TRUE by default) + synchronicity to fill synchrones in // |
24ed5d83 | 160 | # TODO: if size > RAM (not our case), use file-backed big.matrix |
e161499b BA |
161 | synchrones = bigmemory::big.matrix(nrow=K, ncol=L, type="double", init=0.) |
162 | counts = bigmemory::big.matrix(nrow=K, ncol=1, type="double", init=0) | |
24ed5d83 | 163 | # synchronicity is only for Linux & MacOS; on Windows: run sequentially |
492cd9e7 BA |
164 | parll = (requireNamespace("synchronicity",quietly=TRUE) |
165 | && parll && Sys.info()['sysname'] != "Windows") | |
166 | if (parll) | |
363ae134 | 167 | { |
492cd9e7 | 168 | m <- synchronicity::boost.mutex() |
363ae134 BA |
169 | m_desc <- synchronicity::describe(m) |
170 | synchrones_desc = bigmemory::describe(synchrones) | |
171 | medoids_desc = bigmemory::describe(medoids) | |
492cd9e7 | 172 | |
24ed5d83 BA |
173 | cl = parallel::makeCluster(ncores_clust) |
174 | parallel::clusterExport(cl, | |
363ae134 | 175 | varlist=c("synchrones_desc","counts","verbose","m_desc","medoids_desc","getRefSeries"), |
24ed5d83 BA |
176 | envir=environment()) |
177 | } | |
178 | ||
492cd9e7 | 179 | indices_workers = .spreadIndices(seq_len(nb_ref_curves), nb_series_per_chunk) |
c45fd663 | 180 | ignored <- |
492cd9e7 | 181 | if (parll) |
e161499b | 182 | parallel::parLapply(cl, indices_workers, computeSynchronesChunk) |
492cd9e7 | 183 | else |
c45fd663 | 184 | lapply(indices_workers, computeSynchronesChunk) |
492cd9e7 | 185 | |
24ed5d83 BA |
186 | if (parll) |
187 | parallel::stopCluster(cl) | |
188 | ||
189 | #TODO: can we avoid this loop? ( synchrones = sweep(synchrones, 1, counts, '/') ) | |
492cd9e7 | 190 | for (i in seq_len(K)) |
24ed5d83 | 191 | synchrones[i,] = synchrones[i,] / counts[i,1] |
3eef8d3d | 192 | #NOTE: odds for some clusters to be empty? (when series already come from stage 2) |
8702eb86 | 193 | # ...maybe; but let's hope resulting K1' be still quite bigger than K2 |
24ed5d83 BA |
194 | noNA_rows = sapply(seq_len(K), function(i) all(!is.nan(synchrones[i,]))) |
195 | if (all(noNA_rows)) | |
196 | return (synchrones) | |
197 | # Else: some clusters are empty, need to slice synchrones | |
198 | synchrones[noNA_rows,] | |
e205f218 | 199 | } |
1c6f223e | 200 | |
4bcfdbee BA |
201 | #' computeWerDists |
202 | #' | |
203 | #' Compute the WER distances between the synchrones curves (in rows), which are | |
204 | #' returned (e.g.) by \code{computeSynchrones()} | |
205 | #' | |
24ed5d83 BA |
206 | #' @param synchrones A big.matrix of synchrones, in rows. The series have same length |
207 | #' as the series in the initial dataset | |
492cd9e7 | 208 | #' @inheritParams claws |
4bcfdbee | 209 | #' |
777c4b02 | 210 | #' @return A matrix of size K1 x K1 |
24ed5d83 | 211 | #' |
4bcfdbee | 212 | #' @export |
492cd9e7 | 213 | computeWerDists = function(synchrones, ncores_clust=1,verbose=FALSE,parll=TRUE) |
d03c0621 | 214 | { |
e161499b BA |
215 | if (verbose) |
216 | cat(paste("--- Compute WER dists\n", sep="")) | |
24ed5d83 | 217 | |
4bcfdbee BA |
218 | n <- nrow(synchrones) |
219 | delta <- ncol(synchrones) | |
db6fc17d | 220 | #TODO: automatic tune of all these parameters ? (for other users) |
d03c0621 | 221 | nvoice <- 4 |
4bcfdbee | 222 | # noctave = 2^13 = 8192 half hours ~ 180 days ; ~log2(ncol(synchrones)) |
d7d55bc1 BA |
223 | noctave = 13 |
224 | # 4 here represent 2^5 = 32 half-hours ~ 1 day | |
db6fc17d | 225 | #NOTE: default scalevector == 2^(0:(noctave * nvoice) / nvoice) * s0 (?) |
24ed5d83 | 226 | scalevector <- 2^(4:(noctave * nvoice) / nvoice + 1) |
db6fc17d BA |
227 | #condition: ( log2(s0*w0/(2*pi)) - 1 ) * nvoice + 1.5 >= 1 |
228 | s0=2 | |
229 | w0=2*pi | |
230 | scaled=FALSE | |
231 | s0log = as.integer( (log2( s0*w0/(2*pi) ) - 1) * nvoice + 1.5 ) | |
232 | totnoct = noctave + as.integer(s0log/nvoice) + 1 | |
233 | ||
e161499b BA |
234 | Xwer_dist <- bigmemory::big.matrix(nrow=n, ncol=n, type="double") |
235 | fcoefs = rep(1/3, 3) #moving average on 3 values | |
236 | ||
237 | # Generate n(n-1)/2 pairs for WER distances computations | |
238 | pairs = list() | |
239 | V = seq_len(n) | |
240 | for (i in 1:n) | |
241 | { | |
242 | V = V[-1] | |
243 | pairs = c(pairs, lapply(V, function(v) c(i,v))) | |
244 | } | |
245 | ||
777c4b02 | 246 | # Distance between rows i and j |
e161499b BA |
247 | computeDistancesIJ = function(pair) |
248 | { | |
2c14dbea | 249 | if (parll) |
363ae134 | 250 | { |
2c14dbea BA |
251 | require("bigmemory", quietly=TRUE) |
252 | require("epclust", quietly=TRUE) | |
253 | synchrones <- bigmemory::attach.big.matrix(synchrones_desc) | |
254 | Xwer_dist <- bigmemory::attach.big.matrix(Xwer_dist_desc) | |
255 | } | |
256 | ||
257 | computeCWT = function(index) | |
258 | { | |
259 | ts <- scale(ts(synchrones[index,]), center=TRUE, scale=scaled) | |
363ae134 BA |
260 | totts.cwt = Rwave::cwt(ts, totnoct, nvoice, w0, plot=FALSE) |
261 | ts.cwt = totts.cwt[,s0log:(s0log+noctave*nvoice)] | |
262 | #Normalization | |
263 | sqs <- sqrt(2^(0:(noctave*nvoice)/nvoice)*s0) | |
264 | sqres <- sweep(ts.cwt,2,sqs,'*') | |
265 | sqres / max(Mod(sqres)) | |
266 | } | |
2c14dbea | 267 | #browser() |
e161499b BA |
268 | i = pair[1] ; j = pair[2] |
269 | if (verbose && j==i+1) | |
270 | cat(paste(" Distances (",i,",",j,"), (",i,",",j+1,") ...\n", sep="")) | |
2c14dbea BA |
271 | print(system.time( { cwt_i <- computeCWT(i) |
272 | cwt_j <- computeCWT(j) } )) | |
273 | ||
274 | print(system.time( { | |
363ae134 BA |
275 | num <- epclustFilter(Mod(cwt_i * Conj(cwt_j))) |
276 | WX <- epclustFilter(Mod(cwt_i * Conj(cwt_i))) | |
277 | WY <- epclustFilter(Mod(cwt_j * Conj(cwt_j))) | |
e161499b | 278 | wer2 <- sum(colSums(num)^2) / sum(colSums(WX) * colSums(WY)) |
2c14dbea | 279 | Xwer_dist[i,j] <- sqrt(delta * ncol(cwt_i) * max(1 - wer2, 0.)) #FIXME: wer2 should be < 1 |
e161499b | 280 | Xwer_dist[j,i] <- Xwer_dist[i,j] |
2c14dbea | 281 | } ) ) |
e161499b BA |
282 | Xwer_dist[i,i] = 0. |
283 | } | |
284 | ||
492cd9e7 BA |
285 | if (parll) |
286 | { | |
287 | cl = parallel::makeCluster(ncores_clust) | |
363ae134 | 288 | synchrones_desc <- bigmemory::describe(synchrones) |
2c14dbea | 289 | Xwer_dist_desc <- bigmemory::describe(Xwer_dist) |
363ae134 BA |
290 | |
291 | parallel::clusterExport(cl, varlist=c("synchrones_desc","Xwer_dist_desc","totnoct", | |
292 | "nvoice","w0","s0log","noctave","s0","verbose"), envir=environment()) | |
492cd9e7 | 293 | } |
2c14dbea | 294 | browser() |
e161499b | 295 | ignored <- |
492cd9e7 | 296 | if (parll) |
e161499b | 297 | parallel::parLapply(cl, pairs, computeDistancesIJ) |
492cd9e7 | 298 | else |
e161499b | 299 | lapply(pairs, computeDistancesIJ) |
492cd9e7 BA |
300 | |
301 | if (parll) | |
302 | parallel::stopCluster(cl) | |
2c14dbea | 303 | #browser() |
492cd9e7 | 304 | Xwer_dist[n,n] = 0. |
777c4b02 BA |
305 | distances <- Xwer_dist[,] |
306 | rm(Xwer_dist) ; gc() | |
307 | distances #~small matrix K1 x K1 | |
492cd9e7 BA |
308 | } |
309 | ||
310 | # Helper function to divide indices into balanced sets | |
311 | .spreadIndices = function(indices, nb_per_chunk) | |
312 | { | |
313 | L = length(indices) | |
314 | nb_workers = floor( L / nb_per_chunk ) | |
315 | if (nb_workers == 0) | |
316 | { | |
317 | # L < nb_series_per_chunk, simple case | |
318 | indices_workers = list(indices) | |
319 | } | |
320 | else | |
321 | { | |
322 | indices_workers = lapply( seq_len(nb_workers), function(i) | |
323 | indices[(nb_per_chunk*(i-1)+1):(nb_per_chunk*i)] ) | |
324 | # Spread the remaining load among the workers | |
325 | rem = L %% nb_per_chunk | |
326 | while (rem > 0) | |
327 | { | |
328 | index = rem%%nb_workers + 1 | |
329 | indices_workers[[index]] = c(indices_workers[[index]], indices[L-rem+1]) | |
330 | rem = rem - 1 | |
d03c0621 | 331 | } |
1c6f223e | 332 | } |
492cd9e7 | 333 | indices_workers |
1c6f223e | 334 | } |