improvements
[epclust.git] / epclust / R / clustering.R
index 077becf..92adda2 100644 (file)
-# Cluster one full task (nb_curves / ntasks series)
-clusteringTask = function(K1, K2, WER, nb_series_per_chunk, indices_tasks, ncores_clust)
+#' @name clustering
+#' @rdname clustering
+#' @aliases clusteringTask1 computeClusters1 computeClusters2
+#'
+#' @title Two-stage clustering, withing one task (see \code{claws()})
+#'
+#' @description \code{clusteringTask1()} runs one full stage-1 task, which consists in
+#'   iterated stage 1 clustering (on nb_curves / ntasks energy contributions, computed
+#'   through discrete wavelets coefficients).
+#'   \code{clusteringTask2()} runs a full stage-2 task, which consists in synchrones
+#'   and then WER distances computations, before applying the clustering algorithm.
+#'   \code{computeClusters1()} and \code{computeClusters2()} correspond to the atomic
+#'   clustering procedures respectively for stage 1 and 2. The former applies the
+#'   clustering algorithm (PAM) on a contributions matrix, while the latter clusters
+#'   a chunk of series inside one task (~max nb_series_per_chunk)
+#'
+#' @param indices Range of series indices to cluster in parallel (initial data)
+#' @param getContribs Function to retrieve contributions from initial series indices:
+#'   \code{getContribs(indices)} outpus a contributions matrix
+#' @param contribs matrix of contributions (e.g. output of \code{curvesToContribs()})
+#' @inheritParams computeSynchrones
+#' @inheritParams claws
+#'
+#' @return For \code{clusteringTask1()} and \code{computeClusters1()}, the indices of the
+#'   computed (K1) medoids. Indices are irrelevant for stage 2 clustering, thus
+#'   \code{computeClusters2()} outputs a big.matrix of medoids
+#'   (of size limited by nb_series_per_chunk)
+NULL
+
+#' @rdname clustering
+#' @export
+clusteringTask1 = function(
+       indices, getContribs, K1, nb_series_per_chunk, ncores_clust=1, verbose=FALSE, parll=TRUE)
 {
-       cl_clust = parallel::makeCluster(ncores_clust)
-       #parallel::clusterExport(cl=cl_clust, varlist=c("fonctions_du_package"), envir=environment())
-       indices_clust = indices_task[[i]]
-       repeat
+       if (verbose)
+               cat(paste("*** Clustering task 1 on ",length(indices)," lines\n", sep=""))
+
+       if (parll)
        {
-               nb_workers = max( 1, round( length(indices_clust) / nb_series_per_chunk ) )
-               indices_workers = list()
-               for (i in 1:nb_workers)
-               {
-                       upper_bound = ifelse( i<nb_workers,
-                               min(nb_series_per_chunk*i,length(indices_clust)), length(indices_clust) )
-                       indices_workers[[i]] = indices_clust[(nb_series_per_chunk*(i-1)+1):upper_bound]
-               }
-               indices_clust = parallel::parLapply(cl, indices_workers, clusterChunk, K1, K2*(WER=="mix"))
-               if ((WER=="end" && length(indices_clust)==K1) || (WER=="mix" && length(indices_clust)==K2))
-                       break
+               cl = parallel::makeCluster(ncores_clust)
+               parallel::clusterExport(cl, varlist=c("getContribs","K1","verbose"), envir=environment())
        }
-       parallel::stopCluster(cl_clust)
-       unlist(indices_clust)
+       while (length(indices) > K1)
+       {
+               indices_workers = .spreadIndices(indices, nb_series_per_chunk)
+               indices <-
+                       if (parll)
+                       {
+                               unlist( parallel::parLapply(cl, indices_workers, function(inds) {
+                                       require("epclust", quietly=TRUE)
+                                       inds[ computeClusters1(getContribs(inds), K1, verbose) ]
+                               }) )
+                       }
+                       else
+                       {
+                               unlist( lapply(indices_workers, function(inds)
+                                       inds[ computeClusters1(getContribs(inds), K1, verbose) ]
+                               ) )
+                       }
+       }
+       if (parll)
+               parallel::stopCluster(cl)
+
+       indices #medoids
 }
 
-# Cluster a chunk of series inside one task (~max nb_series_per_chunk)
-clusterChunk = function(indices, K1, K2)
+#' @rdname clustering
+#' @export
+clusteringTask2 = function(medoids, K2,
+       getRefSeries, nb_ref_curves, nb_series_per_chunk, ncores_clust=1,verbose=FALSE,parll=TRUE)
 {
-       coeffs = getCoeffs(indices)
-       cl = computeClusters(as.matrix(coeffs[,2:ncol(coeffs)]), K1, diss=FALSE)
-       if (K2 > 0)
-       {
-               curves = computeSynchrones(cl)
-               dists = computeWerDists(curves)
-               cl = computeClusters(dists, K2, diss=TRUE)
-       }
-       indices[cl]
+       if (verbose)
+               cat(paste("*** Clustering task 2 on ",nrow(medoids)," lines\n", sep=""))
+
+       if (nrow(medoids) <= K2)
+               return (medoids)
+       synchrones = computeSynchrones(medoids,
+               getRefSeries, nb_ref_curves, nb_series_per_chunk, ncores_clust, verbose, parll)
+       distances = computeWerDists(synchrones, ncores_clust, verbose, parll)
+       # PAM in package 'cluster' cannot take big.matrix in input: need to cast it
+       medoids[ computeClusters2(distances[,],K2,verbose), ]
+}
+
+#' @rdname clustering
+#' @export
+computeClusters1 = function(contribs, K1, verbose=FALSE)
+{
+       if (verbose)
+               cat(paste("   computeClusters1() on ",nrow(contribs)," lines\n", sep=""))
+       cluster::pam(contribs, K1, diss=FALSE)$id.med
 }
 
-# Apply the clustering algorithm (PAM) on a coeffs or distances matrix
-computeClusters = function(md, K, diss)
+#' @rdname clustering
+#' @export
+computeClusters2 = function(distances, K2, verbose=FALSE)
 {
-       if (!require(cluster, quietly=TRUE))
-               stop("Unable to load cluster library")
-       cluster::pam(md, K, diss=diss)$id.med
+       if (verbose)
+               cat(paste("   computeClusters2() on ",nrow(distances)," lines\n", sep=""))
+       cluster::pam(distances, K2, diss=TRUE)$id.med
 }
 
-# Compute the synchrones curves (sum of clusters elements) from a clustering result
-computeSynchrones = function(indices)
+#' computeSynchrones
+#'
+#' Compute the synchrones curves (sum of clusters elements) from a matrix of medoids,
+#' using L2 distances.
+#'
+#' @param medoids big.matrix of medoids (curves of same length as initial series)
+#' @param getRefSeries Function to retrieve initial series (e.g. in stage 2 after series
+#'   have been replaced by stage-1 medoids)
+#' @param nb_ref_curves How many reference series? (This number is known at this stage)
+#' @inheritParams claws
+#'
+#' @return A big.matrix of size K1 x L where L = data_length
+#'
+#' @export
+computeSynchrones = function(medoids, getRefSeries,
+       nb_ref_curves, nb_series_per_chunk, ncores_clust=1,verbose=FALSE,parll=TRUE)
 {
-       colSums( getData(indices) )
+       if (verbose)
+               cat(paste("--- Compute synchrones\n", sep=""))
+
+       computeSynchronesChunk = function(indices)
+       {
+               ref_series = getRefSeries(indices)
+               nb_series = nrow(ref_series)
+               #get medoids indices for this chunk of series
+
+               #TODO: debug this (address is OK but values are garbage: why?)
+#               mi = .Call("computeMedoidsIndices", medoids@address, ref_series, PACKAGE="epclust")
+
+               #R-equivalent, requiring a matrix (thus potentially breaking "fit-in-memory" hope)
+               mat_meds = medoids[,]
+               mi = rep(NA,nb_series)
+               for (i in 1:nb_series)
+                       mi[i] <- which.min( rowSums( sweep(mat_meds, 2, ref_series[i,], '-')^2 ) )
+               rm(mat_meds); gc()
+
+               for (i in seq_len(nb_series))
+               {
+                       if (parll)
+                               synchronicity::lock(m)
+                       synchrones[mi[i],] = synchrones[mi[i],] + ref_series[i,]
+                       counts[mi[i],1] = counts[mi[i],1] + 1
+                       if (parll)
+                               synchronicity::unlock(m)
+               }
+       }
+
+       K = nrow(medoids) ; L = ncol(medoids)
+       # Use bigmemory (shared==TRUE by default) + synchronicity to fill synchrones in //
+       # TODO: if size > RAM (not our case), use file-backed big.matrix
+       synchrones = bigmemory::big.matrix(nrow=K, ncol=L, type="double", init=0.)
+       counts = bigmemory::big.matrix(nrow=K, ncol=1, type="double", init=0)
+       # synchronicity is only for Linux & MacOS; on Windows: run sequentially
+       parll = (requireNamespace("synchronicity",quietly=TRUE)
+               && parll && Sys.info()['sysname'] != "Windows")
+       if (parll)
+               m <- synchronicity::boost.mutex()
+
+       if (parll)
+       {
+               cl = parallel::makeCluster(ncores_clust)
+               parallel::clusterExport(cl,
+                       varlist=c("synchrones","counts","verbose","medoids","getRefSeries"),
+                       envir=environment())
+       }
+
+       indices_workers = .spreadIndices(seq_len(nb_ref_curves), nb_series_per_chunk)
+               browser()
+       ignored <-
+               if (parll)
+                       parallel::parLapply(cl, indices_workers, computeSynchronesChunk)
+               else
+                       lapply(indices_workers, computeSynchronesChunk)
+
+       if (parll)
+               parallel::stopCluster(cl)
+
+       #TODO: can we avoid this loop? ( synchrones = sweep(synchrones, 1, counts, '/') )
+       for (i in seq_len(K))
+               synchrones[i,] = synchrones[i,] / counts[i,1]
+       #NOTE: odds for some clusters to be empty? (when series already come from stage 2)
+       #      ...maybe; but let's hope resulting K1' be still quite bigger than K2
+       noNA_rows = sapply(seq_len(K), function(i) all(!is.nan(synchrones[i,])))
+       if (all(noNA_rows))
+               return (synchrones)
+       # Else: some clusters are empty, need to slice synchrones
+       synchrones[noNA_rows,]
 }
 
-# Compute the WER distance between the synchrones curves
-computeWerDist = function(curves)
+#' computeWerDists
+#'
+#' Compute the WER distances between the synchrones curves (in rows), which are
+#' returned (e.g.) by \code{computeSynchrones()}
+#'
+#' @param synchrones A big.matrix of synchrones, in rows. The series have same length
+#'   as the series in the initial dataset
+#' @inheritParams claws
+#'
+#' @return A big.matrix of size K1 x K1
+#'
+#' @export
+computeWerDists = function(synchrones, ncores_clust=1,verbose=FALSE,parll=TRUE)
 {
-       if (!require("Rwave", quietly=TRUE))
-               stop("Unable to load Rwave library")
-       n <- nrow(curves)
-       delta <- ncol(curves)
+       if (verbose)
+               cat(paste("--- Compute WER dists\n", sep=""))
+
+       n <- nrow(synchrones)
+       delta <- ncol(synchrones)
        #TODO: automatic tune of all these parameters ? (for other users)
        nvoice   <- 4
-       # noctave = 2^13 = 8192 half hours ~ 180 days ; ~log2(ncol(curves))
+       # noctave = 2^13 = 8192 half hours ~ 180 days ; ~log2(ncol(synchrones))
        noctave = 13
        # 4 here represent 2^5 = 32 half-hours ~ 1 day
        #NOTE: default scalevector == 2^(0:(noctave * nvoice) / nvoice) * s0 (?)
-       scalevector  <- 2^(4:(noctave * nvoice) / nvoice) * 2
+       scalevector  <- 2^(4:(noctave * nvoice) / nvoice + 1)
        #condition: ( log2(s0*w0/(2*pi)) - 1 ) * nvoice + 1.5 >= 1
        s0=2
        w0=2*pi
@@ -71,33 +221,88 @@ computeWerDist = function(curves)
        s0log = as.integer( (log2( s0*w0/(2*pi) ) - 1) * nvoice + 1.5 )
        totnoct = noctave + as.integer(s0log/nvoice) + 1
 
-       # (normalized) observations node with CWT
-       Xcwt4 <- lapply(seq_len(n), function(i) {
-               ts <- scale(ts(curves[i,]), center=TRUE, scale=scaled)
-               totts.cwt = Rwave::cwt(ts,totnoct,nvoice,w0,plot=0)
+       Xwer_dist <- bigmemory::big.matrix(nrow=n, ncol=n, type="double")
+       fcoefs = rep(1/3, 3) #moving average on 3 values
+
+       # Generate n(n-1)/2 pairs for WER distances computations
+       pairs = list()
+       V = seq_len(n)
+       for (i in 1:n)
+       {
+               V = V[-1]
+               pairs = c(pairs, lapply(V, function(v) c(i,v)))
+       }
+
+       computeCWT = function(i)
+       {
+               ts <- scale(ts(synchrones[i,]), center=TRUE, scale=scaled)
+               totts.cwt = Rwave::cwt(ts, totnoct, nvoice, w0, plot=FALSE)
                ts.cwt = totts.cwt[,s0log:(s0log+noctave*nvoice)]
                #Normalization
                sqs <- sqrt(2^(0:(noctave*nvoice)/nvoice)*s0)
-               sqres <- sweep(ts.cwt,MARGIN=2,sqs,'*')
+               sqres <- sweep(ts.cwt,2,sqs,'*')
                sqres / max(Mod(sqres))
-       })
+       }
+
+       computeDistancesIJ = function(pair)
+       {
+               i = pair[1] ; j = pair[2]
+               if (verbose && j==i+1)
+                       cat(paste("   Distances (",i,",",j,"), (",i,",",j+1,") ...\n", sep=""))
+               cwt_i = computeCWT(i)
+               cwt_j = computeCWT(j)
+               num <- .Call("filter", Mod(cwt_i * Conj(cwt_j)), PACKAGE="epclust")
+               WX  <- .Call("filter", Mod(cwt_i * Conj(cwt_i)), PACKAGE="epclust")
+               WY  <- .Call("filter", Mod(cwt_j * Conj(cwt_j)), PACKAGE="epclust")
+               wer2 <- sum(colSums(num)^2) / sum(colSums(WX) * colSums(WY))
+               Xwer_dist[i,j] <- sqrt(delta * ncol(cwt_i) * (1 - wer2))
+               Xwer_dist[j,i] <- Xwer_dist[i,j]
+               Xwer_dist[i,i] = 0.
+       }
 
-       Xwer_dist <- matrix(0., n, n)
-       fcoefs = rep(1/3, 3) #moving average on 3 values (TODO: very slow! correct?!)
-       for (i in 1:(n-1))
+       if (parll)
        {
-               for (j in (i+1):n)
+               cl = parallel::makeCluster(ncores_clust)
+               parallel::clusterExport(cl,
+                       varlist=c("synchrones","totnoct","nvoice","w0","s0log","noctave","s0","verbose"),
+                       envir=environment())
+       }
+
+       ignored <-
+               if (parll)
+                       parallel::parLapply(cl, pairs, computeDistancesIJ)
+               else
+                       lapply(pairs, computeDistancesIJ)
+
+       if (parll)
+               parallel::stopCluster(cl)
+
+       Xwer_dist[n,n] = 0.
+       Xwer_dist
+}
+
+# Helper function to divide indices into balanced sets
+.spreadIndices = function(indices, nb_per_chunk)
+{
+       L = length(indices)
+       nb_workers = floor( L / nb_per_chunk )
+       if (nb_workers == 0)
+       {
+               # L < nb_series_per_chunk, simple case
+               indices_workers = list(indices)
+       }
+       else
+       {
+               indices_workers = lapply( seq_len(nb_workers), function(i)
+                       indices[(nb_per_chunk*(i-1)+1):(nb_per_chunk*i)] )
+               # Spread the remaining load among the workers
+               rem = L %% nb_per_chunk
+               while (rem > 0)
                {
-                       #TODO: later, compute CWT here (because not enough storage space for 32M series)
-                       #      'circular=TRUE' is wrong, should just take values on the sides; to rewrite in C
-                       num <- filter(Mod(Xcwt4[[i]] * Conj(Xcwt4[[j]])), fcoefs, circular=TRUE)
-                       WX <- filter(Mod(Xcwt4[[i]] * Conj(Xcwt4[[i]])), fcoefs, circular=TRUE)
-                       WY <- filter(Mod(Xcwt4[[j]] * Conj(Xcwt4[[j]])), fcoefs, circular=TRUE)
-                       wer2    <- sum(colSums(num)^2) / sum( sum(colSums(WX) * colSums(WY)) )
-                       Xwer_dist[i,j] <- sqrt(delta * ncol(Xcwt4[[1]]) * (1 - wer2))
-                       Xwer_dist[j,i] <- Xwer_dist[i,j]
+                       index = rem%%nb_workers + 1
+                       indices_workers[[index]] = c(indices_workers[[index]], indices[L-rem+1])
+                       rem = rem - 1
                }
        }
-       diag(Xwer_dist) <- numeric(n)
-       Xwer_dist
+       indices_workers
 }