add comments, fix some things. TODO: comment tests, finish computeWerDists, test it
[epclust.git] / epclust / R / main.R
1 #' CLAWS: CLustering with wAvelets and Wer distanceS
2 #'
3 #' Cluster electricity power curves (or any series of similar nature) by applying a
4 #' two stage procedure in parallel (see details).
5 #' Input series must be sampled on the same time grid, no missing values.
6 #'
7 #' Summary of the function execution flow:
8 #' \enumerate{
9 #' \item Compute and serialize all contributions, obtained through discrete wavelet
10 #' decomposition (see Antoniadis & al. [2013])
11 #' \item Divide series into \code{ntasks} groups to process in parallel. In each task:
12 #' \enumerate{
13 #' \item iterate the first clustering algorithm on its aggregated outputs,
14 #' on inputs of size \code{nb_items_clust1}
15 #' \item optionally, if WER=="mix":
16 #' a) compute the K1 synchrones curves,
17 #' b) compute WER distances (K1xK1 matrix) between synchrones and
18 #' c) apply the second clustering algorithm
19 #' }
20 #' \item Launch a final task on the aggregated outputs of all previous tasks:
21 #' in the case WER=="end" this task takes indices in input, otherwise
22 #' (medoid) curves
23 #' }
24 #' \cr
25 #' The main argument -- \code{getSeries} -- has a quite misleading name, since it can be
26 #' either a [big.]matrix, a CSV file, a connection or a user function to retrieve
27 #' series; the name was chosen because all types of arguments are converted to a function.
28 #' When \code{getSeries} is given as a function, it must take a single argument,
29 #' 'indices', integer vector equal to the indices of the curves to retrieve;
30 #' see SQLite example. The nature and role of other arguments should be clear
31 #' \cr
32 #' Note: Since we don't make assumptions on initial data, there is a possibility that
33 #' even when serialized, contributions or synchrones do not fit in RAM. For example,
34 #' 30e6 series of length 100,000 would lead to a +4Go contribution matrix. Therefore,
35 #' it's safer to place these in (binary) files; that's what we do.
36 #'
37 #' @param getSeries Access to the (time-)series, which can be of one of the three
38 #' following types:
39 #' \itemize{
40 #' \item [big.]matrix: each column contains the (time-ordered) values of one time-serie
41 #' \item connection: any R connection object providing lines as described above
42 #' \item character: name of a CSV file containing series in rows (no header)
43 #' \item function: a custom way to retrieve the curves; it has only one argument:
44 #' the indices of the series to be retrieved. See SQLite example
45 #' }
46 #' @param K1 Number of clusters to be found after stage 1 (K1 << N [number of series])
47 #' @param K2 Number of clusters to be found after stage 2 (K2 << K1)
48 #' @param nb_series_per_chunk (Maximum) number of series to retrieve in one batch
49 #' @param algoClust1 Clustering algorithm for stage 1. A function which takes (data, K)
50 #' as argument where data is a matrix in columns and K the desired number of clusters,
51 #' and outputs K medoids ranks. Default: PAM. In our method, this function is called
52 #' on iterated medoids during stage 1
53 #' @param algoClust2 Clustering algorithm for stage 2. A function which takes (dists, K)
54 #' as argument where dists is a matrix of distances and K the desired number of clusters,
55 #' and outputs K medoids ranks. Default: PAM. In our method, this function is called
56 #' on a matrix of K1 x K1 (WER) distances computed between synchrones
57 #' @param nb_items_clust1 (~Maximum) number of items in input of the clustering algorithm
58 #' for stage 1. At worst, a clustering algorithm might be called with ~2*nb_items_clust1
59 #' items; but this could only happen at the last few iterations.
60 #' @param wav_filt Wavelet transform filter; see ?wavelets::wt.filter
61 #' @param contrib_type Type of contribution: "relative", "logit" or "absolute" (any prefix)
62 #' @param WER "end" to apply stage 2 after stage 1 has fully iterated, or "mix" to apply
63 #' stage 2 at the end of each task
64 #' @param random TRUE (default) for random chunks repartition
65 #' @param ntasks Number of tasks (parallel iterations to obtain K1 [if WER=="end"]
66 #' or K2 [if WER=="mix"] medoids); default: 1.
67 #' Note: ntasks << N (number of series), so that N is "roughly divisible" by ntasks
68 #' @param ncores_tasks Number of parallel tasks (1 to disable: sequential tasks)
69 #' @param ncores_clust Number of parallel clusterings in one task (4 should be a minimum)
70 #' @param sep Separator in CSV input file (if any provided)
71 #' @param nbytes Number of bytes to serialize a floating-point number; 4 or 8
72 #' @param endian Endianness for (de)serialization ("little" or "big")
73 #' @param verbose Level of verbosity (0/FALSE for nothing or 1/TRUE for all; devel stage)
74 #' @param parll TRUE to fully parallelize; otherwise run sequentially (debug, comparison)
75 #'
76 #' @return A matrix of the final K2 medoids curves, in columns
77 #'
78 #' @references Clustering functional data using Wavelets [2013];
79 #' A. Antoniadis, X. Brossat, J. Cugliari & J.-M. Poggi.
80 #' Inter. J. of Wavelets, Multiresolution and Information Procesing,
81 #' vol. 11, No 1, pp.1-30. doi:10.1142/S0219691313500033
82 #'
83 #' @examples
84 #' \dontrun{
85 #' # WER distances computations are too long for CRAN (for now)
86 #'
87 #' # Random series around cos(x,2x,3x)/sin(x,2x,3x)
88 #' x = seq(0,500,0.05)
89 #' L = length(x) #10001
90 #' ref_series = matrix( c(cos(x),cos(2*x),cos(3*x),sin(x),sin(2*x),sin(3*x)), ncol=6 )
91 #' library(wmtsa)
92 #' series = do.call( cbind, lapply( 1:6, function(i)
93 #' do.call(cbind, wmtsa::wavBootstrap(ref_series[i,], n.realization=400)) ) )
94 #' #dim(series) #c(2400,10001)
95 #' medoids_ascii = claws(series, K1=60, K2=6, 200, verbose=TRUE)
96 #'
97 #' # Same example, from CSV file
98 #' csv_file = "/tmp/epclust_series.csv"
99 #' write.table(series, csv_file, sep=",", row.names=FALSE, col.names=FALSE)
100 #' medoids_csv = claws(csv_file, K1=60, K2=6, 200)
101 #'
102 #' # Same example, from binary file
103 #' bin_file <- "/tmp/epclust_series.bin"
104 #' nbytes <- 8
105 #' endian <- "little"
106 #' binarize(csv_file, bin_file, 500, nbytes, endian)
107 #' getSeries <- function(indices) getDataInFile(indices, bin_file, nbytes, endian)
108 #' medoids_bin <- claws(getSeries, K1=60, K2=6, 200)
109 #' unlink(csv_file)
110 #' unlink(bin_file)
111 #'
112 #' # Same example, from SQLite database
113 #' library(DBI)
114 #' series_db <- dbConnect(RSQLite::SQLite(), "file::memory:")
115 #' # Prepare data.frame in DB-format
116 #' n <- nrow(series)
117 #' time_values <- data.frame(
118 #' id = rep(1:n,each=L),
119 #' time = rep( as.POSIXct(1800*(0:n),"GMT",origin="2001-01-01"), L ),
120 #' value = as.double(t(series)) )
121 #' dbWriteTable(series_db, "times_values", times_values)
122 #' # Fill associative array, map index to identifier
123 #' indexToID_inDB <- as.character(
124 #' dbGetQuery(series_db, 'SELECT DISTINCT id FROM time_values')[,"id"] )
125 #' serie_length <- as.integer( dbGetQuery(series_db,
126 #' paste("SELECT COUNT * FROM time_values WHERE id == ",indexToID_inDB[1],sep="")) )
127 #' getSeries <- function(indices) {
128 #' request <- "SELECT id,value FROM times_values WHERE id in ("
129 #' for (i in indices)
130 #' request <- paste(request, indexToID_inDB[i], ",", sep="")
131 #' request <- paste(request, ")", sep="")
132 #' df_series <- dbGetQuery(series_db, request)
133 #' as.matrix(df_series[,"value"], nrow=serie_length)
134 #' }
135 #' medoids_db = claws(getSeries, K1=60, K2=6, 200))
136 #' dbDisconnect(series_db)
137 #'
138 #' # All computed medoids should be the same:
139 #' digest::sha1(medoids_ascii)
140 #' digest::sha1(medoids_csv)
141 #' digest::sha1(medoids_bin)
142 #' digest::sha1(medoids_db)
143 #' }
144 #' @export
145 claws <- function(getSeries, K1, K2, nb_series_per_chunk, nb_items_clust1=7*K1,
146 algoClust1=function(data,K) cluster::pam(t(data),K,diss=FALSE)$id.med,
147 algoClust2=function(dists,K) cluster::pam(dists,K,diss=TRUE)$id.med,
148 wav_filt="d8", contrib_type="absolute", WER="end", random=TRUE,
149 ntasks=1, ncores_tasks=1, ncores_clust=4, sep=",", nbytes=4,
150 endian=.Platform$endian, verbose=FALSE, parll=TRUE)
151 {
152 # Check/transform arguments
153 if (!is.matrix(getSeries) && !bigmemory::is.big.matrix(getSeries)
154 && !is.function(getSeries)
155 && !methods::is(getSeries,"connection") && !is.character(getSeries))
156 {
157 stop("'getSeries': [big]matrix, function, file or valid connection (no NA)")
158 }
159 K1 <- .toInteger(K1, function(x) x>=2)
160 K2 <- .toInteger(K2, function(x) x>=2)
161 nb_series_per_chunk <- .toInteger(nb_series_per_chunk, function(x) x>=1)
162 # K1 (number of clusters at step 1) cannot exceed nb_series_per_chunk, because we will need
163 # to load K1 series in memory for clustering stage 2.
164 if (K1 > nb_series_per_chunk)
165 stop("'K1' cannot exceed 'nb_series_per_chunk'")
166 nb_items_clust1 <- .toInteger(nb_items_clust1, function(x) x>K1)
167 random <- .toLogical(random)
168 tryCatch( {ignored <- wavelets::wt.filter(wav_filt)},
169 error = function(e) stop("Invalid wavelet filter; see ?wavelets::wt.filter") )
170 ctypes = c("relative","absolute","logit")
171 contrib_type = ctypes[ pmatch(contrib_type,ctypes) ]
172 if (is.na(contrib_type))
173 stop("'contrib_type' in {'relative','absolute','logit'}")
174 if (WER!="end" && WER!="mix")
175 stop("'WER': in {'end','mix'}")
176 random <- .toLogical(random)
177 ntasks <- .toInteger(ntasks, function(x) x>=1)
178 ncores_tasks <- .toInteger(ncores_tasks, function(x) x>=1)
179 ncores_clust <- .toInteger(ncores_clust, function(x) x>=1)
180 if (!is.character(sep))
181 stop("'sep': character")
182 nbytes <- .toInteger(nbytes, function(x) x==4 || x==8)
183 verbose <- .toLogical(verbose)
184 parll <- .toLogical(parll)
185
186 # Binarize series if getSeries is not a function; the aim is to always use a function,
187 # to uniformize treatments. An equally good alternative would be to use a file-backed
188 # bigmemory::big.matrix, but it would break the "all-is-function" pattern.
189 if (!is.function(getSeries))
190 {
191 if (verbose)
192 cat("...Serialize time-series\n")
193 series_file = ".series.bin" ; unlink(series_file)
194 binarize(getSeries, series_file, nb_series_per_chunk, sep, nbytes, endian)
195 getSeries = function(inds) getDataInFile(inds, series_file, nbytes, endian)
196 }
197
198 # Serialize all computed wavelets contributions into a file
199 contribs_file = ".contribs.bin" ; unlink(contribs_file)
200 index = 1
201 nb_curves = 0
202 if (verbose)
203 cat("...Compute contributions and serialize them\n")
204 nb_curves = binarizeTransform(getSeries,
205 function(series) curvesToContribs(series, wav_filt, contrib_type),
206 contribs_file, nb_series_per_chunk, nbytes, endian)
207 getContribs = function(indices) getDataInFile(indices, contribs_file, nbytes, endian)
208
209 # A few sanity checks: do not continue if too few data available.
210 if (nb_curves < K2)
211 stop("Not enough data: less series than final number of clusters")
212 nb_series_per_task = round(nb_curves / ntasks)
213 if (nb_series_per_task < K2)
214 stop("Too many tasks: less series in one task than final number of clusters")
215
216 # Generate a random permutation of 1:N (if random==TRUE);
217 # otherwise just use arrival (storage) order.
218 indices_all = if (random) sample(nb_curves) else seq_len(nb_curves)
219 # Split (all) indices into ntasks groups of ~same size
220 indices_tasks = lapply(seq_len(ntasks), function(i) {
221 upper_bound = ifelse( i<ntasks, min(nb_series_per_task*i,nb_curves), nb_curves )
222 indices_all[((i-1)*nb_series_per_task+1):upper_bound]
223 })
224
225 if (parll && ntasks>1)
226 {
227 # Initialize parallel runs: outfile="" allow to output verbose traces in the console
228 # under Linux. All necessary variables are passed to the workers.
229 cl = parallel::makeCluster(ncores_tasks, outfile="")
230 varlist = c("getSeries","getContribs","K1","K2","algoClust1","algoClust2",
231 "nb_series_per_chunk","nb_items_clust1","ncores_clust",
232 "sep","nbytes","endian","verbose","parll")
233 if (WER=="mix" && ntasks>1)
234 varlist = c(varlist, "medoids_file")
235 parallel::clusterExport(cl, varlist, envir = environment())
236 }
237
238 # This function achieves one complete clustering task, divided in stage 1 + stage 2.
239 # stage 1: n indices --> clusteringTask1(...) --> K1 medoids
240 # stage 2: K1 medoids --> clusteringTask2(...) --> K2 medoids,
241 # where n = N / ntasks, N being the total number of curves.
242 runTwoStepClustering = function(inds)
243 {
244 # When running in parallel, the environment is blank: we need to load the required
245 # packages, and pass useful variables.
246 if (parll && ntasks>1)
247 require("epclust", quietly=TRUE)
248 indices_medoids = clusteringTask1(
249 inds, getContribs, K1, algoClust1, nb_series_per_chunk, ncores_clust, verbose, parll)
250 if (WER=="mix" && ntasks>1)
251 {
252 if (parll)
253 require("bigmemory", quietly=TRUE)
254 medoids1 = bigmemory::as.big.matrix( getSeries(indices_medoids) )
255 medoids2 = clusteringTask2(medoids1, K2, algoClust2, getSeries, nb_curves,
256 nb_series_per_chunk, nbytes, endian, ncores_clust, verbose, parll)
257 binarize(medoids2, medoids_file, nb_series_per_chunk, sep, nbytes, endian)
258 return (vector("integer",0))
259 }
260 indices_medoids
261 }
262
263 # Synchrones (medoids) need to be stored only if WER=="mix"; indeed in this case, every
264 # task output is a set of new (medoids) curves. If WER=="end" however, output is just a
265 # set of indices, representing some initial series.
266 if (WER=="mix" && ntasks>1)
267 {medoids_file = ".medoids.bin" ; unlink(medoids_file)}
268
269 if (verbose)
270 {
271 message = paste("...Run ",ntasks," x stage 1", sep="")
272 if (WER=="mix")
273 message = paste(message," + stage 2", sep="")
274 cat(paste(message,"\n", sep=""))
275 }
276
277 # As explained above, indices will be assigned to ntasks*K1 medoids indices [if WER=="end"],
278 # or nothing (empty vector) if WER=="mix"; in this case, synchrones are stored in a file.
279 indices <-
280 if (parll && ntasks>1)
281 unlist( parallel::parLapply(cl, indices_tasks, runTwoStepClustering) )
282 else
283 unlist( lapply(indices_tasks, runTwoStepClustering) )
284 if (parll && ntasks>1)
285 parallel::stopCluster(cl)
286
287 # Right before the final stage, two situations are possible:
288 # a. data to be processed now sit in a binary format in medoids_file (if WER=="mix")
289 # b. data still is the initial set of curves, referenced by the ntasks*K1 indices
290 # So, the function getSeries() will potentially change. However, computeSynchrones()
291 # requires a function retrieving the initial series. Thus, the next line saves future
292 # conditional instructions.
293 getRefSeries = getSeries
294
295 if (WER=="mix" && ntasks>1)
296 {
297 indices = seq_len(ntasks*K2)
298 # Now series (synchrones) must be retrieved from medoids_file
299 getSeries = function(inds) getDataInFile(inds, medoids_file, nbytes, endian)
300 # Contributions must be re-computed
301 unlink(contribs_file)
302 index = 1
303 if (verbose)
304 cat("...Serialize contributions computed on synchrones\n")
305 ignored = binarizeTransform(getSeries,
306 function(series) curvesToContribs(series, wav_filt, contrib_type),
307 contribs_file, nb_series_per_chunk, nbytes, endian)
308 }
309
310 # Run step2 on resulting indices or series (from file)
311 if (verbose)
312 cat("...Run final // stage 1 + stage 2\n")
313 indices_medoids = clusteringTask1(indices, getContribs, K1, algoClust1,
314 nb_series_per_chunk, ncores_tasks*ncores_clust, verbose, parll)
315 medoids1 = bigmemory::as.big.matrix( getSeries(indices_medoids) )
316 medoids2 = clusteringTask2(medoids1, K2, algoClust2, getRefSeries, nb_curves,
317 nb_series_per_chunk, nbytes, endian, ncores_tasks*ncores_clust, verbose, parll)
318
319 # Cleanup: remove temporary binary files
320 tryCatch(
321 {unlink(series_file); unlink(contribs_file); unlink(medoids_file)},
322 error = function(e) {})
323
324 # Return medoids as a standard matrix, since K2 series have to fit in RAM
325 # (clustering algorithm 1 takes K1 > K2 of them as input)
326 medoids2[,]
327 }
328
329 #' curvesToContribs
330 #'
331 #' Compute the discrete wavelet coefficients for each series, and aggregate them in
332 #' energy contribution across scales as described in https://arxiv.org/abs/1101.4744v2
333 #'
334 #' @param series [big.]matrix of series (in columns), of size L x n
335 #' @inheritParams claws
336 #'
337 #' @return A [big.]matrix of size log(L) x n containing contributions in columns
338 #'
339 #' @export
340 curvesToContribs = function(series, wav_filt, contrib_type, coin=FALSE)
341 {
342 series = as.matrix(series) #1D serie could occur
343 L = nrow(series)
344 D = ceiling( log2(L) )
345 # Series are interpolated to all have length 2^D
346 nb_sample_points = 2^D
347 apply(series, 2, function(x) {
348 interpolated_curve = spline(1:L, x, n=nb_sample_points)$y
349 W = wavelets::dwt(interpolated_curve, filter=wav_filt, D)@W
350 # Compute the sum of squared discrete wavelet coefficients, for each scale
351 nrj = rev( sapply( W, function(v) ( sqrt( sum(v^2) ) ) ) )
352 if (contrib_type!="absolute")
353 nrj = nrj / sum(nrj)
354 if (contrib_type=="logit")
355 nrj = - log(1 - nrj)
356 nrj
357 })
358 }
359
360 # Check integer arguments with functional conditions
361 .toInteger <- function(x, condition)
362 {
363 errWarn <- function(ignored)
364 paste("Cannot convert argument' ",substitute(x),"' to integer", sep="")
365 if (!is.integer(x))
366 tryCatch({x = as.integer(x)[1]; if (is.na(x)) stop()},
367 warning = errWarn, error = errWarn)
368 if (!condition(x))
369 {
370 stop(paste("Argument '",substitute(x),
371 "' does not verify condition ",body(condition), sep=""))
372 }
373 x
374 }
375
376 # Check logical arguments
377 .toLogical <- function(x)
378 {
379 errWarn <- function(ignored)
380 paste("Cannot convert argument' ",substitute(x),"' to logical", sep="")
381 if (!is.logical(x))
382 tryCatch({x = as.logical(x)[1]; if (is.na(x)) stop()},
383 warning = errWarn, error = errWarn)
384 x
385 }