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