'update'
[epclust.git] / epclust / R / main.R
1 #' CLAWS: CLustering with wAvelets and Wer distanceS
2 #'
3 #' Groups electricity power curves (or any series of similar nature) by applying PAM
4 #' algorithm in parallel to chunks of size \code{nb_series_per_chunk}. Input series
5 #' must be sampled on the same time grid, no missing values.
6 #'
7 #' @param getSeries Access to the (time-)series, which can be of one of the three
8 #' following types:
9 #' \itemize{
10 #' \item matrix: each line contains all the values for one time-serie, ordered by time
11 #' \item connection: any R connection object (e.g. a file) providing lines as described above
12 #' \item function: a custom way to retrieve the curves; it has only one argument:
13 #' the indices of the series to be retrieved. See examples
14 #' }
15 #' @inheritParams clustering
16 #' @param K1 Number of super-consumers to be found after stage 1 (K1 << N)
17 #' @param K2 Number of clusters to be found after stage 2 (K2 << K1)
18 #' @param wf Wavelet transform filter; see ?wavelets::wt.filter
19 #' @param ctype Type of contribution: "relative" or "absolute" (or any prefix)
20 #' @param WER "end" to apply stage 2 after stage 1 has fully iterated, or "mix" to apply stage 2
21 #' at the end of each task
22 #' @param random TRUE (default) for random chunks repartition
23 #' @param ntasks Number of tasks (parallel iterations to obtain K1 medoids); default: 1.
24 #' Note: ntasks << N, so that N is "roughly divisible" by N (number of series)
25 #' @param ncores_tasks "MPI" number of parallel tasks (1 to disable: sequential tasks)
26 #' @param ncores_clust "OpenMP" number of parallel clusterings in one task
27 #' @param nb_series_per_chunk (~Maximum) number of series in each group, inside a task
28 #' @param min_series_per_chunk Minimum number of series in each group
29 #' @param sep Separator in CSV input file (if any provided)
30 #' @param nbytes Number of bytes to serialize a floating-point number; 4 or 8
31 #' @param endian Endianness to use for (de)serialization. Use "little" or "big" for portability
32 #' @param verbose Level of verbosity (0/FALSE for nothing or 1/TRUE for all; devel stage)
33 #' @param parll TRUE to fully parallelize; otherwise run sequentially (debug, comparison)
34 #'
35 #' @return A matrix of the final medoids curves (K2) in rows
36 #'
37 #' @examples
38 #' \dontrun{
39 #' # WER distances computations are a bit too long for CRAN (for now)
40 #'
41 #' # Random series around cos(x,2x,3x)/sin(x,2x,3x)
42 #' x = seq(0,500,0.05)
43 #' L = length(x) #10001
44 #' ref_series = matrix( c(cos(x), cos(2*x), cos(3*x), sin(x), sin(2*x), sin(3*x)),
45 #' byrow=TRUE, ncol=L )
46 #' library(wmtsa)
47 #' series = do.call( rbind, lapply( 1:6, function(i)
48 #' do.call(rbind, wmtsa::wavBootstrap(ref_series[i,], n.realization=400)) ) )
49 #' #dim(series) #c(2400,10001)
50 #' medoids_ascii = claws(series, K1=60, K2=6, "d8", "rel", nb_series_per_chunk=500)
51 #'
52 #' # Same example, from CSV file
53 #' csv_file = "/tmp/epclust_series.csv"
54 #' write.table(series, csv_file, sep=",", row.names=FALSE, col.names=FALSE)
55 #' medoids_csv = claws(csv_file, K1=60, K2=6, "d8", "rel", nb_series_per_chunk=500)
56 #'
57 #' # Same example, from binary file
58 #' bin_file = "/tmp/epclust_series.bin"
59 #' nbytes = 8
60 #' endian = "little"
61 #' epclust::binarize(csv_file, bin_file, 500, nbytes, endian)
62 #' getSeries = function(indices) getDataInFile(indices, bin_file, nbytes, endian)
63 #' medoids_bin = claws(getSeries, K1=60, K2=6, "d8", "rel", nb_series_per_chunk=500)
64 #' unlink(csv_file)
65 #' unlink(bin_file)
66 #'
67 #' # Same example, from SQLite database
68 #' library(DBI)
69 #' series_db <- dbConnect(RSQLite::SQLite(), "file::memory:")
70 #' # Prepare data.frame in DB-format
71 #' n = nrow(series)
72 #' time_values = data.frame(
73 #' id = rep(1:n,each=L),
74 #' time = rep( as.POSIXct(1800*(0:n),"GMT",origin="2001-01-01"), L ),
75 #' value = as.double(t(series)) )
76 #' dbWriteTable(series_db, "times_values", times_values)
77 #' # Fill associative array, map index to identifier
78 #' indexToID_inDB <- as.character(
79 #' dbGetQuery(series_db, 'SELECT DISTINCT id FROM time_values')[,"id"] )
80 #' getSeries = function(indices) {
81 #' request = "SELECT id,value FROM times_values WHERE id in ("
82 #' for (i in indices)
83 #' request = paste(request, i, ",", sep="")
84 #' request = paste(request, ")", sep="")
85 #' df_series = dbGetQuery(series_db, request)
86 #' # Assume that all series share same length at this stage
87 #' ts_length = sum(df_series[,"id"] == df_series[1,"id"])
88 #' t( as.matrix(df_series[,"value"], nrow=ts_length) )
89 #' }
90 #' medoids_db = claws(getSeries, K1=60, K2=6, "d8", "rel", nb_series_per_chunk=500)
91 #' dbDisconnect(series_db)
92 #'
93 #' # All computed medoids should be the same:
94 #' digest::sha1(medoids_ascii)
95 #' digest::sha1(medoids_csv)
96 #' digest::sha1(medoids_bin)
97 #' digest::sha1(medoids_db)
98 #' }
99 #' @export
100 claws = function(getSeries, K1, K2,
101 wf,ctype, #stage 1
102 WER="end", #stage 2
103 random=TRUE, #randomize series order?
104 ntasks=1, ncores_tasks=1, ncores_clust=4, #control parallelism
105 nb_series_per_chunk=50*K1, min_series_per_chunk=5*K1, #chunk size
106 sep=",", #ASCII input separator
107 nbytes=4, endian=.Platform$endian, #serialization (write,read)
108 verbose=FALSE, parll=TRUE)
109 {
110 # Check/transform arguments
111 if (!is.matrix(getSeries) && !bigmemory::is.big.matrix(getSeries)
112 && !is.function(getSeries)
113 && !methods::is(getSeries,"connection") && !is.character(getSeries))
114 {
115 stop("'getSeries': [big]matrix, function, file or valid connection (no NA)")
116 }
117 K1 = .toInteger(K1, function(x) x>=2)
118 K2 = .toInteger(K2, function(x) x>=2)
119 if (!is.logical(random))
120 stop("'random': logical")
121 tryCatch(
122 {ignored <- wavelets::wt.filter(wf)},
123 error = function(e) stop("Invalid wavelet filter; see ?wavelets::wt.filter"))
124 if (WER!="end" && WER!="mix")
125 stop("WER takes values in {'end','mix'}")
126 ntasks = .toInteger(ntasks, function(x) x>=1)
127 ncores_tasks = .toInteger(ncores_tasks, function(x) x>=1)
128 ncores_clust = .toInteger(ncores_clust, function(x) x>=1)
129 nb_series_per_chunk = .toInteger(nb_series_per_chunk, function(x) x>=K1)
130 min_series_per_chunk = .toInteger(K1, function(x) x>=K1 && x<=nb_series_per_chunk)
131 if (!is.character(sep))
132 stop("'sep': character")
133 nbytes = .toInteger(nbytes, function(x) x==4 || x==8)
134
135 # Serialize series if required, to always use a function
136 bin_dir = ".epclust_bin/"
137 dir.create(bin_dir, showWarnings=FALSE, mode="0755")
138 if (!is.function(getSeries))
139 {
140 if (verbose)
141 cat("...Serialize time-series\n")
142 series_file = paste(bin_dir,"data",sep="") ; unlink(series_file)
143 binarize(getSeries, series_file, nb_series_per_chunk, sep, nbytes, endian)
144 getSeries = function(inds) getDataInFile(inds, series_file, nbytes, endian)
145 }
146
147 # Serialize all computed wavelets contributions into a file
148 contribs_file = paste(bin_dir,"contribs",sep="") ; unlink(contribs_file)
149 index = 1
150 nb_curves = 0
151 if (verbose)
152 cat("...Compute contributions and serialize them\n")
153 nb_curves = binarizeTransform(getSeries,
154 function(series) curvesToContribs(series, wf, ctype),
155 contribs_file, nb_series_per_chunk, nbytes, endian)
156 getContribs = function(indices) getDataInFile(indices, contribs_file, nbytes, endian)
157
158 if (nb_curves < min_series_per_chunk)
159 stop("Not enough data: less rows than min_series_per_chunk!")
160 nb_series_per_task = round(nb_curves / ntasks)
161 if (nb_series_per_task < min_series_per_chunk)
162 stop("Too many tasks: less series in one task than min_series_per_chunk!")
163
164 runTwoStepClustering = function(inds)
165 {
166 if (parll)
167 require("epclust", quietly=TRUE)
168 indices_medoids = clusteringTask1(
169 inds, getContribs, K1, nb_series_per_chunk, ncores_clust, verbose, parll)
170 if (WER=="mix")
171 {
172
173
174
175
176 #TODO: getSeries(indices_medoids) BAD ; il faudrait une big.matrix de medoids en entree
177 #OK en RAM il y en aura 1000 (donc 1000*K1*17519... OK)
178 #...mais du coup chaque process ne re-dupliquera pas medoids
179
180
181 medoids2 = computeClusters2(getSeries(indices_medoids),
182 K2, getSeries, nb_curves, nb_series_per_chunk, ncores_clust, verbose, parll)
183 binarize(medoids2, synchrones_file, nb_series_per_chunk, sep, nbytes, endian)
184 return (vector("integer",0))
185 }
186 indices_medoids
187 }
188
189 # Cluster contributions in parallel (by nb_series_per_chunk)
190 indices_all = if (random) sample(nb_curves) else seq_len(nb_curves)
191 indices_tasks = lapply(seq_len(ntasks), function(i) {
192 upper_bound = ifelse( i<ntasks, min(nb_series_per_task*i,nb_curves), nb_curves )
193 indices_all[((i-1)*nb_series_per_task+1):upper_bound]
194 })
195 if (verbose)
196 cat(paste("...Run ",ntasks," x stage 1 in parallel\n",sep=""))
197 if (WER=="mix")
198 {synchrones_file = paste(bin_dir,"synchrones",sep="") ; unlink(synchrones_file)}
199 if (parll)
200 {
201 cl = parallel::makeCluster(ncores_tasks)
202 varlist = c("getSeries","getContribs","K1","K2","verbose","parll",
203 "nb_series_per_chunk","ncores_clust","sep","nbytes","endian")
204 if (WER=="mix")
205 varlist = c(varlist, "synchrones_file")
206 parallel::clusterExport(cl, varlist=varlist, envir = environment())
207 }
208
209 # 1000*K1 indices [if WER=="end"], or empty vector [if WER=="mix"] --> series on file
210 if (parll)
211 indices = unlist( parallel::parLapply(cl, indices_tasks, runTwoStepClustering) )
212 else
213 indices = unlist( lapply(indices_tasks, runTwoStepClustering) )
214 if (parll)
215 parallel::stopCluster(cl)
216
217 getRefSeries = getSeries
218 if (WER=="mix")
219 {
220 indices = seq_len(ntasks*K2)
221 #Now series must be retrieved from synchrones_file
222 getSeries = function(inds) getDataInFile(inds, synchrones_file, nbytes, endian)
223 #Contributions must be re-computed
224 unlink(contribs_file)
225 index = 1
226 if (verbose)
227 cat("...Serialize contributions computed on synchrones\n")
228 ignored = binarizeTransform(getSeries,
229 function(series) curvesToContribs(series, wf, ctype),
230 contribs_file, nb_series_per_chunk, nbytes, endian)
231 }
232
233
234
235 #TODO: if ntasks==1, c'est deja terminé
236
237 # Run step2 on resulting indices or series (from file)
238 if (verbose)
239 cat("...Run final // stage 1 + stage 2\n")
240 indices_medoids = clusteringTask1(
241 indices, getContribs, K1, nb_series_per_chunk, ncores_tasks*ncores_clust, verbose, parll)
242 medoids = computeClusters2(getSeries(indices_medoids), K2,
243 getRefSeries, nb_curves, nb_series_per_chunk, ncores_tasks*ncores_clust, verbose, parll)
244
245 # Cleanup
246 unlink(bin_dir, recursive=TRUE)
247
248 medoids
249 }
250
251 #' curvesToContribs
252 #'
253 #' Compute the discrete wavelet coefficients for each series, and aggregate them in
254 #' energy contribution across scales as described in https://arxiv.org/abs/1101.4744v2
255 #'
256 #' @param series Matrix of series (in rows), of size n x L
257 #' @inheritParams claws
258 #'
259 #' @return A matrix of size n x log(L) containing contributions in rows
260 #'
261 #' @export
262 curvesToContribs = function(series, wf, ctype)
263 {
264 L = length(series[1,])
265 D = ceiling( log2(L) )
266 nb_sample_points = 2^D
267 cont_types = c("relative","absolute")
268 ctype = cont_types[ pmatch(ctype,cont_types) ]
269 t( apply(series, 1, function(x) {
270 interpolated_curve = spline(1:L, x, n=nb_sample_points)$y
271 W = wavelets::dwt(interpolated_curve, filter=wf, D)@W
272 nrj = rev( sapply( W, function(v) ( sqrt( sum(v^2) ) ) ) )
273 if (ctype=="relative") nrj / sum(nrj) else nrj
274 }) )
275 }
276
277 # Check integer arguments with functional conditions
278 .toInteger <- function(x, condition)
279 {
280 if (!is.integer(x))
281 tryCatch(
282 {x = as.integer(x)[1]},
283 error = function(e) paste("Cannot convert argument",substitute(x),"to integer")
284 )
285 if (!condition(x))
286 stop(paste("Argument",substitute(x),"does not verify condition",body(condition)))
287 x
288 }