Commit | Line | Data |
---|---|---|
3d69ff21 BA |
1 | #' @title dateIndexToInteger |
2 | #' | |
3 | #' @description Transform a (potential) date index into an integer (relative to data) | |
4 | #' | |
5 | #' @param index Date (or integer) index | |
6 | #' @param data Object of class \code{Data} | |
7 | #' | |
8 | #' @export | |
9 | dateIndexToInteger = function(index, data) | |
10 | { | |
11 | if (is.numeric(index)) | |
12 | index = as.integer(index) | |
13 | #Undocumented "private" method to translate index --> date (is needed) | |
14 | if (is.integer(index)) | |
15 | return (index[1]) | |
16 | if (is.character(index)) | |
17 | { | |
18 | tryCatch(dt <- as.POSIXct(index[1]), finally=print("Unrecognized index format")) | |
19 | #TODO: tz arg to difftime ? | |
20 | integerIndex <- as.integer( difftime(dt, data$getTime(1)) ) + 1 | |
21 | if (integerIndex > 0 && integerIndex <= data$getSize()) | |
22 | return (integerIndex) | |
23 | stop("Date outside data range") | |
24 | } | |
25 | stop("Unrecognized index format") | |
26 | } | |
27 | ||
28 | #' @title getSimilarDaysIndices | |
29 | #' | |
30 | #' @description Find similar days indices in the past | |
31 | #' | |
32 | #' @param index Day index (numeric or date) | |
33 | #' @param limit Maximum number of indices to return | |
34 | #' @param same_seaon Should the indices correspond to day in same season? | |
35 | #' | |
36 | #' @export | |
37 | getSimilarDaysIndices = function(index, limit, same_season) | |
38 | { | |
39 | index = dateIndexToInteger(index) | |
40 | ||
41 | #TODO: mardi similaire à lundi mercredi jeudi aussi ...etc | |
42 | if (!same_season) | |
43 | { | |
44 | #take all similar days in recent past | |
45 | nb_days = min( (index-1) %/% 7, limit) | |
46 | return ( rep(index,nb_days) - 7*seq_len(nb_days) ) | |
47 | } | |
48 | ||
49 | #Look for similar days in similar season (+/- 30 days) | |
50 | days = c() | |
51 | i = index | |
52 | while (i >= 1 && length(days) < limit) | |
53 | { | |
54 | if (i < index) | |
55 | { | |
56 | days = c(days, i) | |
57 | #look in the "future of the past" | |
58 | for (j in 1:4) | |
59 | days = c(days, i+7*j) | |
60 | } | |
61 | #...and in the "past of the past" | |
62 | for (j in 1:4) | |
63 | { | |
64 | if (i - 7*j >= 1) | |
65 | days = c(days, i-7*j) | |
66 | } | |
67 | # TODO: exact computation instead of -364 | |
68 | # 364 = closest multiple of 7 to 365 - drift along the years... but not so many years so OK | |
69 | i = i - 364 | |
70 | } | |
71 | ||
72 | return ( days[1:min(limit,length(days))] ) | |
73 | } |