3 #' @title Cluster power curves with PAM in parallel
5 #' @description Groups electricity power curves (or any series of similar nature) by applying PAM
6 #' algorithm in parallel to chunks of size \code{nb_series_per_chunk}
8 #' @param data Access to the data, which can be of one of the three following types:
10 #' \item data.frame: each line contains its ID in the first cell, and all values after
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 two arguments: the start index
13 #' (start) and number of curves (n); see example in package vignette.
15 #' @param K1 Number of super-consumers to be found after stage 1 (K1 << N)
16 #' @param K2 Number of clusters to be found after stage 2 (K2 << K1)
17 #' @param ntasks Number of tasks (parallel iterations to obtain K1 medoids); default: 1.
18 #' Note: ntasks << N, so that N is "roughly divisible" by N (number of series)
19 #' @param nb_series_per_chunk (Maximum) number of series in each group, inside a task
20 #' @param min_series_per_chunk Minimum number of series in each group
21 #' @param writeTmp Function to write temporary wavelets coefficients (+ identifiers);
22 #' see defaults in defaults.R
23 #' @param readTmp Function to read temporary wavelets coefficients (see defaults.R)
24 #' @param wf Wavelet transform filter; see ?wt.filter. Default: haar
25 #' @param WER "end" to apply stage 2 after stage 1 has iterated and finished, or "mix"
26 #' to apply it after every stage 1
27 #' @param ncores_tasks number of parallel tasks (1 to disable: sequential tasks)
28 #' @param ncores_clust number of parallel clusterings in one task
30 #' @return A data.frame of the final medoids curves (identifiers + values)
33 #' getData = function(start, n) {
34 #' con = dbConnect(drv = RSQLite::SQLite(), dbname = "mydata.sqlite")
35 #' df = dbGetQuery(con, paste(
36 #' "SELECT * FROM times_values GROUP BY id OFFSET ",start,
37 #' "LIMIT ", n, " ORDER BY date", sep=""))
40 #' cl = epclust(getData, K1=200, K2=15, ntasks=1000, nb_series_per_chunk=5000, WER="mix")
42 epclust = function(data, K1, K2,
43 ntasks=1, nb_series_per_chunk=50*K1, min_series_per_chunk=5*K1,
44 writeTmp=defaultWriteTmp, readTmp=defaultReadTmp, wf="haar", WER="end",
45 ncores_tasks=1, ncores_clust=4)
47 #TODO: setRefClass(...) to avoid copy data:
48 #http://stackoverflow.com/questions/2603184/r-pass-by-reference
51 if (!is.data.frame(data) && !is.function(data))
54 if (is.character(data))
56 data_con = file(data, open="r")
57 } else if (!isOpen(data))
63 error="data should be a data.frame, a function or a valid connection")
64 if (!is.integer(K) || K < 2)
65 stop("K should be an integer greater or equal to 2")
66 if (!is.integer(nb_series_per_chunk) || nb_series_per_chunk < K)
67 stop("nb_series_per_chunk should be an integer greater or equal to K")
68 if (!is.function(writeTmp) || !is.function(readTmp))
69 stop("read/writeTmp should be functional (see defaults.R)")
70 if (WER!="end" && WER!="mix")
71 stop("WER takes values in {'end','mix'}")
72 #concerning ncores, any non-integer type will be treated as "use parallel:detectCores()/4"
74 #1) acquire data (process curves, get as coeffs)
75 #TODO: for data.frame and custom function, run in parallel (connections are sequential[?!])
81 if (is.data.frame(data))
84 if (index < nrow(data))
86 coeffs_chunk = curvesToCoeffs(
87 data[index:(min(index+nb_series_per_chunk-1,nrow(data))),], wf)
89 } else if (is.function(data))
91 #custom user function to retrieve next n curves, probably to read from DB
92 coeffs_chunk = curvesToCoeffs( data(index, nb_series_per_chunk), wf )
95 #incremental connection
96 #TODO: find a better way to parse than using a temp file
97 ascii_lines = readLines(data_con, nb_series_per_chunk)
98 if (length(ascii_lines > 0))
100 series_chunk_file = ".tmp/series_chunk"
101 writeLines(ascii_lines, series_chunk_file)
102 coeffs_chunk = curvesToCoeffs( read.csv(series_chunk_file), wf )
105 if (is.null(coeffs_chunk))
107 writeTmp(coeffs_chunk)
108 nb_curves = nb_curves + nrow(coeffs_chunk)
109 index = index + nb_series_per_chunk
111 if (exists(data_con))
113 if (nb_curves < min_series_per_chunk)
114 stop("Not enough data: less rows than min_series_per_chunk!")
116 #2) process coeffs (by nb_series_per_chunk) and cluster them in parallel
118 cl_tasks = parallel::makeCluster(ncores_tasks)
119 #Nothing to export because each worker retrieve and put data from/on files (or DB)
120 #parallel::clusterExport(cl=cl, varlist=c("nothing","to","export"), envir=environment())
121 #TODO: be careful of writing to a new temp file, then flush initial one, then re-use it...
122 res_tasks = parallel::parSapply(cl_tasks, 1:ntasks, function() {
123 cl_clust = parallel::makeCluster(ncores_clust)
126 #while there are jobs to do
127 #(i.e. size of tmp "file" is greater than ntasks * nb_series_per_chunk)
128 nb_workers = nb_curves %/% nb_series_per_chunk
130 #indices[[i]] == (start_index,number_of_elements)
131 for (i in 1:nb_workers)
132 indices[[i]] = c(nb_series_per_chunk*(i-1)+1, nb_series_per_chunk)
133 remainder = nb_curves %% nb_series_per_chunk
134 if (remainder >= min_series_per_chunk)
136 nb_workers = nb_workers + 1
137 indices[[nb_workers]] = c(nb_curves-remainder+1, nb_curves)
138 } else if (remainder > 0)
140 #spread the load among other workers
143 res_clust = parallel::parSapply(cl, indices, processChunk, K, WER=="mix")
144 #C) flush tmp file (current parallel processes will write in it)
146 parallel:stopCluster(cl_clust)
148 parallel::stopCluster(cl_tasks)
150 #3) readTmp last results, apply PAM on it, and return medoids + identifiers
151 final_coeffs = readTmp(1, nb_series_per_chunk)
152 if (nrow(final_coeffs) == K)
154 return ( list( medoids=coeffsToCurves(final_coeffs[,2:ncol(final_coeffs)]),
155 ids=final_coeffs[,1] ) )
157 pam_output = getClusters(as.matrix(final_coeffs[,2:ncol(final_coeffs)]), K)
158 medoids = coeffsToCurves(pam_output$medoids, wf)
159 ids = final_coeffs[,1] [pam_output$ranks]
161 #4) apply stage 2 (in parallel ? inside task 2) ?)
164 #from center curves, apply stage 2...
168 return (list(medoids=medoids, ids=ids))
171 processChunk = function(indice, K, WER)
174 coeffs = readTmp(indice[1], indice[2])
176 cl = getClusters(as.matrix(coeffs[,2:ncol(coeffs)]), K)
181 #TODO: difficulté : retrouver courbe à partir de l'identifiant (DB ok mais le reste ?)
182 #aussi : que passe-t-on aux noeuds ? curvesToCoeffs en // ?