fix comment on initialize.sh
[epclust.git] / epclust / R / main.R
CommitLineData
7f0781b7 1#' @include defaults.R
3dcbfeef 2
7f0781b7
BA
3#' @title Cluster power curves with PAM in parallel
4#'
5#' @description Groups electricity power curves (or any series of similar nature) by applying PAM
cea14f3a 6#' algorithm in parallel to chunks of size \code{nb_series_per_chunk}
7f0781b7
BA
7#'
8#' @param data Access to the data, which can be of one of the three following types:
9#' \itemize{
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.
14#' }
15#' @param K Number of clusters
cea14f3a
BA
16#' @param nb_series_per_chunk (Maximum) number of series in each group
17#' @param min_series_per_chunk Minimum number of series in each group
7f0781b7
BA
18#' @param writeTmp Function to write temporary wavelets coefficients (+ identifiers);
19#' see defaults in defaults.R
20#' @param readTmp Function to read temporary wavelets coefficients (see defaults.R)
3465b246 21#' @param wf Wavelet transform filter; see ?wt.filter. Default: haar
7f0781b7
BA
22#' @param WER "end" to apply stage 2 after stage 1 has iterated and finished, or "mix"
23#' to apply it after every stage 1
24#' @param ncores number of parallel processes; if NULL, use parallel::detectCores()
25#'
26#' @return A data.frame of the final medoids curves (identifiers + values)
cea14f3a 27epclust = function(data, K, nb_series_per_chunk, min_series_per_chunk=10*K,
3465b246 28 writeTmp=defaultWriteTmp, readTmp=defaultReadTmp, wf="haar", WER="end", ncores=NULL)
ac1d4231 29{
7f0781b7
BA
30 #TODO: setRefClass(...) to avoid copy data:
31 #http://stackoverflow.com/questions/2603184/r-pass-by-reference
ac1d4231 32
7f0781b7
BA
33 #0) check arguments
34 if (!is.data.frame(data) && !is.function(data))
6ecf5c2d
BA
35 tryCatch(
36 {
37 if (is.character(data))
38 {
cea14f3a 39 data_con = file(data, open="r")
6ecf5c2d
BA
40 } else if (!isOpen(data))
41 {
42 open(data)
cea14f3a 43 data_con = data
6ecf5c2d
BA
44 }
45 },
7f0781b7
BA
46 error="data should be a data.frame, a function or a valid connection")
47 if (!is.integer(K) || K < 2)
48 stop("K should be an integer greater or equal to 2")
cea14f3a
BA
49 if (!is.integer(nb_series_per_chunk) || nb_series_per_chunk < K)
50 stop("nb_series_per_chunk should be an integer greater or equal to K")
7f0781b7
BA
51 if (!is.function(writeTmp) || !is.function(readTmp))
52 stop("read/writeTmp should be functional (see defaults.R)")
53 if (WER!="end" && WER!="mix")
54 stop("WER takes values in {'end','mix'}")
55 #concerning ncores, any non-integer type will be treated as "use parallel:detectCores()"
ac1d4231 56
3d061515 57 #1) acquire data (process curves, get as coeffs)
aa7daeaa 58 #TODO: for data.frame and custom function, run in parallel (connections are sequential[?!])
7f0781b7 59 index = 1
cea14f3a 60 nb_curves = 0
6ecf5c2d 61 repeat
ac1d4231 62 {
cea14f3a 63 coeffs_chunk = NULL
7f0781b7 64 if (is.data.frame(data))
3dcbfeef 65 {
7f0781b7 66 #full data matrix
b9f1c0c7
BA
67 if (index < nrow(data))
68 {
cea14f3a 69 coeffs_chunk = curvesToCoeffs(
3465b246 70 data[index:(min(index+nb_series_per_chunk-1,nrow(data))),], wf)
b9f1c0c7 71 }
7f0781b7
BA
72 } else if (is.function(data))
73 {
74 #custom user function to retrieve next n curves, probably to read from DB
3465b246 75 coeffs_chunk = curvesToCoeffs( data(index, nb_series_per_chunk), wf )
7f0781b7
BA
76 } else
77 {
78 #incremental connection
79 #TODO: find a better way to parse than using a temp file
cea14f3a 80 ascii_lines = readLines(data_con, nb_series_per_chunk)
b9f1c0c7
BA
81 if (length(ascii_lines > 0))
82 {
cea14f3a
BA
83 series_chunk_file = ".tmp/series_chunk"
84 writeLines(ascii_lines, series_chunk_file)
3465b246 85 coeffs_chunk = curvesToCoeffs( read.csv(series_chunk_file), wf )
b9f1c0c7 86 }
3dcbfeef 87 }
cea14f3a
BA
88 if (is.null(coeffs_chunk))
89 break
90 writeTmp(coeffs_chunk)
91 nb_curves = nb_curves + nrow(coeffs_chunk)
92 index = index + nb_series_per_chunk
8e6accca 93 }
cea14f3a
BA
94 if (exists(data_con))
95 close(data_con)
96 if (nb_curves < min_series_per_chunk)
97 stop("Not enough data: less rows than min_series_per_chunk!")
8e6accca 98
cea14f3a 99 #2) process coeffs (by nb_series_per_chunk) and cluster them in parallel
8e6accca 100 library(parallel)
7f0781b7 101 ncores = ifelse(is.integer(ncores), ncores, parallel::detectCores())
8e6accca 102 cl = parallel::makeCluster(ncores)
aa7daeaa 103 parallel::clusterExport(cl=cl, varlist=c("TODO:", "what", "to", "export?"), envir=environment())
6ecf5c2d 104 #TODO: be careful of writing to a new temp file, then flush initial one, then re-use it...
8e6accca
BA
105 repeat
106 {
cea14f3a
BA
107 #while there is jobs to do (i.e. size of tmp "file" is greater than nb_series_per_chunk)
108 nb_workers = nb_curves %/% nb_series_per_chunk
109 indices = list()
3465b246 110 #indices[[i]] == (start_index,number_of_elements)
cea14f3a
BA
111 for (i in 1:nb_workers)
112 indices[[i]] = c(nb_series_per_chunk*(i-1)+1, nb_series_per_chunk)
113 remainder = nb_curves %% nb_series_per_chunk
114 if (remainder >= min_series_per_chunk)
115 {
116 nb_workers = nb_workers + 1
117 indices[[nb_workers]] = c(nb_curves-remainder+1, nb_curves)
118 } else if (remainder > 0)
119 {
120 #spread the load among other workers
aa7daeaa 121 #...
cea14f3a 122 }
3465b246 123 li = parallel::parLapply(cl, indices, processChunk, K, WER=="mix")
8e6accca 124 #C) flush tmp file (current parallel processes will write in it)
8e6accca 125 }
7f0781b7 126 parallel::stopCluster(cl)
3d061515 127
8e6accca 128 #3) readTmp last results, apply PAM on it, and return medoids + identifiers
cea14f3a
BA
129 final_coeffs = readTmp(1, nb_series_per_chunk)
130 if (nrow(final_coeffs) == K)
131 {
132 return ( list( medoids=coeffsToCurves(final_coeffs[,2:ncol(final_coeffs)]),
133 ids=final_coeffs[,1] ) )
134 }
135 pam_output = getClusters(as.matrix(final_coeffs[,2:ncol(final_coeffs)]), K)
3465b246 136 medoids = coeffsToCurves(pam_output$medoids, wf)
cea14f3a 137 ids = final_coeffs[,1] [pam_output$ranks]
ac1d4231 138
8e6accca
BA
139 #4) apply stage 2 (in parallel ? inside task 2) ?)
140 if (WER == "end")
141 {
142 #from center curves, apply stage 2...
3465b246 143 #TODO:
8e6accca 144 }
3465b246
BA
145
146 return (list(medoids=medoids, ids=ids))
ac1d4231 147}
cea14f3a 148
3465b246 149processChunk = function(indice, K, WER)
cea14f3a
BA
150{
151 #1) retrieve data
3465b246 152 coeffs = readTmp(indice[1], indice[2])
cea14f3a 153 #2) cluster
3465b246 154 cl = getClusters(as.matrix(coeffs[,2:ncol(coeffs)]), K)
cea14f3a 155 #3) WER (optional)
3465b246 156 #TODO:
cea14f3a 157}
3465b246
BA
158
159#TODO: difficulté : retrouver courbe à partir de l'identifiant (DB ok mais le reste ?)
160#aussi : que passe-t-on aux noeuds ? curvesToCoeffs en // ?
161#enfin : WER ?!