before computeSynchrones
[epclust.git] / epclust / R / main.R
CommitLineData
7f0781b7
BA
1#' @title Cluster power curves with PAM in parallel
2#'
3#' @description Groups electricity power curves (or any series of similar nature) by applying PAM
cea14f3a 4#' algorithm in parallel to chunks of size \code{nb_series_per_chunk}
7f0781b7
BA
5#'
6#' @param data Access to the data, which can be of one of the three following types:
7#' \itemize{
8#' \item data.frame: each line contains its ID in the first cell, and all values after
9#' \item connection: any R connection object (e.g. a file) providing lines as described above
c33af7e4
BA
10#' \item function: a custom way to retrieve the curves; it has two arguments: the ranks to be
11#' retrieved, and the IDs - at least one of them must be present (priority: ranks).
7f0781b7 12#' }
1c6f223e
BA
13#' @param K1 Number of super-consumers to be found after stage 1 (K1 << N)
14#' @param K2 Number of clusters to be found after stage 2 (K2 << K1)
15#' @param ntasks Number of tasks (parallel iterations to obtain K1 medoids); default: 1.
16#' Note: ntasks << N, so that N is "roughly divisible" by N (number of series)
17#' @param nb_series_per_chunk (Maximum) number of series in each group, inside a task
cea14f3a 18#' @param min_series_per_chunk Minimum number of series in each group
3465b246 19#' @param wf Wavelet transform filter; see ?wt.filter. Default: haar
7f0781b7
BA
20#' @param WER "end" to apply stage 2 after stage 1 has iterated and finished, or "mix"
21#' to apply it after every stage 1
5c652979
BA
22#' @param ncores_tasks "MPI" number of parallel tasks (1 to disable: sequential tasks)
23#' @param ncores_clust "OpenMP" number of parallel clusterings in one task
24#' @param random Randomize chunks repartition
0e2dce80 25#' @param ... Other arguments to be passed to \code{data} function
7f0781b7
BA
26#'
27#' @return A data.frame of the final medoids curves (identifiers + values)
1c6f223e
BA
28#'
29#' @examples
30#' getData = function(start, n) {
31#' con = dbConnect(drv = RSQLite::SQLite(), dbname = "mydata.sqlite")
32#' df = dbGetQuery(con, paste(
33#' "SELECT * FROM times_values GROUP BY id OFFSET ",start,
34#' "LIMIT ", n, " ORDER BY date", sep=""))
35#' return (df)
36#' }
e205f218 37#' #####TODO: if DB, array rank --> ID at first retrieval, when computing coeffs; so:: NO use of IDs !
5c652979
BA
38#' #TODO: 3 examples, data.frame / binary file / DB sqLite
39#' + sampleCurves : wavBootstrap de package wmtsa
1c6f223e
BA
40#' cl = epclust(getData, K1=200, K2=15, ntasks=1000, nb_series_per_chunk=5000, WER="mix")
41#' @export
0e2dce80
BA
42epclust = function(series,K1,K2,ntasks=1,nb_series_per_chunk=50*K1,min_series_per_chunk=5*K1,
43 wf="haar",WER="end",ncores_tasks=1,ncores_clust=4,random=TRUE,...)
ac1d4231 44{
0e2dce80
BA
45 # Check/transform arguments
46 bin_dir = "epclust.bin/"
47 dir.create(bin_dir, showWarnings=FALSE, mode="0755")
48 if (!is.function(series))
49 {
50 series_file = paste(bin_dir,"data",sep="")
51 unlink(series_file)
52 }
53 if (is.matrix(series))
54 serialize(series, series_file)
55 else if (!is.function(series))
5c652979 56 {
6ecf5c2d
BA
57 tryCatch(
58 {
0e2dce80
BA
59 if (is.character(series))
60 series_con = file(series, open="r")
61 else if (!isOpen(series))
6ecf5c2d 62 {
0e2dce80
BA
63 open(series)
64 series_con = series
6ecf5c2d 65 }
0e2dce80
BA
66 serialize(series_con, series_file)
67 close(series_con)
6ecf5c2d 68 },
0e2dce80 69 error=function(e) "series should be a data.frame, a function or a valid connection"
5c652979
BA
70 )
71 }
0e2dce80
BA
72 if (!is.function(series))
73 series = function(indices) getDataInFile(indices, series_file)
74 getSeries = series
75
5c652979
BA
76 K1 = toInteger(K1, function(x) x>=2)
77 K2 = toInteger(K2, function(x) x>=2)
c33af7e4 78 ntasks = toInteger(ntasks, function(x) x>=1)
5c652979
BA
79 nb_series_per_chunk = toInteger(nb_series_per_chunk, function(x) x>=K1)
80 min_series_per_chunk = toInteger(K1, function(x) x>=K1 && x<=nb_series_per_chunk)
81 ncores_tasks = toInteger(ncores_tasks, function(x) x>=1)
82 ncores_clust = toInteger(ncores_clust, function(x) x>=1)
7f0781b7
BA
83 if (WER!="end" && WER!="mix")
84 stop("WER takes values in {'end','mix'}")
ac1d4231 85
7b13d0c2 86 # Serialize all wavelets coefficients (+ IDs) onto a file
0e2dce80
BA
87 coefs_file = paste(bin_dir,"coefs",sep="")
88 unlink(coefs_file)
7f0781b7 89 index = 1
cea14f3a 90 nb_curves = 0
6ecf5c2d 91 repeat
ac1d4231 92 {
0e2dce80
BA
93 series = getSeries((index-1)+seq_len(nb_series_per_chunk))
94 if (is.null(series))
cea14f3a 95 break
0e2dce80
BA
96 coeffs_chunk = curvesToCoeffs(series, wf)
97 serialize(coeffs_chunk, coefs_file)
cea14f3a 98 index = index + nb_series_per_chunk
5c652979 99 nb_curves = nb_curves + nrow(coeffs_chunk)
8e6accca 100 }
0e2dce80 101 getCoefs = function(indices) getDataInFile(indices, coefs_file)
8e6accca 102
5c652979
BA
103 if (nb_curves < min_series_per_chunk)
104 stop("Not enough data: less rows than min_series_per_chunk!")
105 nb_series_per_task = round(nb_curves / ntasks)
106 if (nb_series_per_task < min_series_per_chunk)
107 stop("Too many tasks: less series in one task than min_series_per_chunk!")
ac1d4231 108
7b13d0c2 109 # Cluster coefficients in parallel (by nb_series_per_chunk)
48108c39
BA
110 indices = if (random) sample(nb_curves) else seq_len(nb_curves)
111 indices_tasks = lapply(seq_len(ntasks), function(i) {
5c652979 112 upper_bound = ifelse( i<ntasks, min(nb_series_per_task*i,nb_curves), nb_curves )
48108c39
BA
113 indices[((i-1)*nb_series_per_task+1):upper_bound]
114 })
e205f218 115 cl = parallel::makeCluster(ncores_tasks)
0e2dce80 116 #1000*K1 (or K2) indices (or NOTHING--> series on file)
e205f218
BA
117 indices = unlist( parallel::parLapply(cl, indices_tasks, function(inds) {
118 clusteringTask(inds, getSeries, getSeries, getCoefs, K1, K2*(WER=="mix"),
119 nb_series_per_chunk,ncores_clust,to_file=TRUE)
120 }) )
121 parallel::stopCluster(cl)
3465b246 122
e205f218
BA
123 getSeriesForSynchrones = getSeries
124 synchrones_file = paste(bin_dir,"synchrones",sep="")
125 if (WER=="mix")
126 {
127 indices = seq_len(ntasks*K2)
128 #Now series must be retrieved from synchrones_file
129 getSeries = function(inds) getDataInFile(inds, synchrones_file)
130 #Coefs must be re-computed
131 unlink(coefs_file)
132 index = 1
133 repeat
134 {
135 series = getSeries((index-1)+seq_len(nb_series_per_chunk))
136 if (is.null(series))
137 break
138 coeffs_chunk = curvesToCoeffs(series, wf)
139 serialize(coeffs_chunk, coefs_file)
140 index = index + nb_series_per_chunk
141 }
142 }
0e2dce80
BA
143
144 # Run step2 on resulting indices or series (from file)
e205f218
BA
145 clusteringTask(indices, getSeries, getSeriesForSynchrones, getCoefs, K1, K2,
146 nb_series_per_chunk, ncores_tasks*ncores_clust, to_file=FALSE)
cea14f3a 147}