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