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