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