update documention, fix package to compete with 'method Bruno'
[talweg.git] / pkg / R / plot.R
CommitLineData
98e958ca 1#' Plot curves
e030a6e3 2#'
102bcfda 3#' Plot a range of curves in data.
e030a6e3 4#'
102bcfda 5#' @inheritParams computeError
e030a6e3
BA
6#' @param indices Range of indices (integers or dates)
7#'
8#' @export
1e20780e 9plotCurves <- function(data, indices=seq_len(data$getSize()))
e030a6e3 10{
98e958ca 11 series = data$getSeries(indices)
a5a3a294 12 yrange = quantile(series, probs=c(0.025,0.975), na.rm=TRUE)
e030a6e3 13 par(mar=c(4.7,5,1,1), cex.axis=1.5, cex.lab=1.5)
4f3fdbb8 14 matplot(series, type="l", ylim=yrange, xlab="Time (hours)", ylab="PM10")
e030a6e3
BA
15}
16
af3b84f4 17#' Plot error
3d69ff21 18#'
102bcfda 19#' Draw error graphs, potentially from several runs of \code{computeForecast()}.
3d69ff21 20#'
102bcfda 21#' @param err Error as returned by \code{computeError()}
09cf9c19 22#' @param cols Colors for each error (default: 1,2,3,...)
3d69ff21 23#'
98e958ca 24#' @seealso \code{\link{plotCurves}}, \code{\link{plotPredReal}},
72b9c501
BA
25#' \code{\link{plotSimils}}, \code{\link{plotFbox}}, \code{\link{computeFilaments}},
26#' \code{\link{plotFilamentsBox}}, \code{\link{plotRelVar}}
3d69ff21
BA
27#'
28#' @export
09cf9c19 29plotError <- function(err, cols=seq_along(err))
3d69ff21 30{
09cf9c19
BA
31 if (!is.null(err$abs))
32 err = list(err)
4e95ec8f 33 par(mfrow=c(2,2), mar=c(4.7,5,1,1), cex.axis=1.5, cex.lab=1.5, lwd=2)
3d69ff21 34 L = length(err)
98e958ca 35 yrange = range( sapply(1:L, function(i) ( err[[i]]$abs$day ) ), na.rm=TRUE )
3d69ff21
BA
36 for (i in seq_len(L))
37 {
4e25de2c
BA
38 plot(err[[i]]$abs$day, type="l", xlab=ifelse(i==1,"Time (hours)",""),
39 ylab=ifelse(i==1,"Mean |y - y_hat|",""), ylim=yrange, col=cols[i])
3d69ff21
BA
40 if (i < L)
41 par(new=TRUE)
42 }
98e958ca 43 yrange = range( sapply(1:L, function(i) ( err[[i]]$abs$indices ) ), na.rm=TRUE )
3d69ff21
BA
44 for (i in seq_len(L))
45 {
4e25de2c
BA
46 plot(err[[i]]$abs$indices, type="l", xlab=ifelse(i==1,"Time (days)",""),
47 ylab=ifelse(i==1,"Mean |y - y_hat|",""), ylim=yrange, col=cols[i])
3d69ff21
BA
48 if (i < L)
49 par(new=TRUE)
50 }
98e958ca 51 yrange = range( sapply(1:L, function(i) ( err[[i]]$MAPE$day ) ), na.rm=TRUE )
3d69ff21
BA
52 for (i in seq_len(L))
53 {
4e25de2c
BA
54 plot(err[[i]]$MAPE$day, type="l", xlab=ifelse(i==1,"Time (hours)",""),
55 ylab=ifelse(i==1,"Mean MAPE",""), ylim=yrange, col=cols[i])
3d69ff21
BA
56 if (i < L)
57 par(new=TRUE)
58 }
98e958ca 59 yrange = range( sapply(1:L, function(i) ( err[[i]]$MAPE$indices ) ), na.rm=TRUE )
3d69ff21
BA
60 for (i in seq_len(L))
61 {
4e25de2c
BA
62 plot(err[[i]]$MAPE$indices, type="l", xlab=ifelse(i==1,"Time (days)",""),
63 ylab=ifelse(i==1,"Mean MAPE",""), ylim=yrange, col=cols[i])
3d69ff21
BA
64 if (i < L)
65 par(new=TRUE)
66 }
67}
68
98e958ca
BA
69#' Plot measured / predicted
70#'
102bcfda 71#' Plot measured curve (in black) and predicted curve (in blue).
98e958ca 72#'
102bcfda 73#' @inheritParams computeError
98e958ca
BA
74#' @param index Index in forecasts (integer or date)
75#'
76#' @export
77plotPredReal <- function(data, pred, index)
78{
72b9c501 79 prediction = pred$getForecast(index)
e7bc2af6 80 measure = data$getSerie( pred$getIndexInData(index) )[1:length(prediction)]
98e958ca
BA
81 yrange = range(measure, prediction)
82 par(mar=c(4.7,5,1,1), cex.axis=1.5, cex.lab=1.5, lwd=3)
4e25de2c 83 plot(measure, type="l", ylim=yrange, xlab="Time (hours)", ylab="PM10")
98e958ca
BA
84 par(new=TRUE)
85 plot(prediction, type="l", col="#0000FF", ylim=yrange, xlab="", ylab="")
86}
87
88#' Plot similarities
89#'
102bcfda 90#' Plot histogram of similarities (weights), for 'Neighbors' method.
98e958ca 91#'
102bcfda 92#' @inheritParams computeError
98e958ca
BA
93#' @param index Index in forecasts (integer or date)
94#'
95#' @export
96plotSimils <- function(pred, index)
97{
98 weights = pred$getParams(index)$weights
99 if (is.null(weights))
100 stop("plotSimils only works on 'Neighbors' forecasts")
101 par(mar=c(4.7,5,1,1), cex.axis=1.5, cex.lab=1.5)
4e25de2c 102 hist(pred$getParams(index)$weights, nclass=20, main="", xlab="Weight", ylab="Count")
98e958ca
BA
103}
104
af3b84f4 105#' Functional boxplot
3d69ff21 106#'
102bcfda 107#' Draw the functional boxplot on the left, and bivariate plot on the right.
3d69ff21 108#'
102bcfda
BA
109#' @inheritParams computeError
110#' @inheritParams plotCurves
3d69ff21
BA
111#'
112#' @export
98e958ca 113plotFbox <- function(data, indices=seq_len(data$getSize()))
3d69ff21
BA
114{
115 if (!requireNamespace("rainbow", quietly=TRUE))
116 stop("Functional boxplot requires the rainbow package")
117
98e958ca
BA
118 series_matrix = data$getSeries(indices)
119 # Remove series with NAs
af3b84f4
BA
120 no_NAs_indices = sapply( 1:ncol(series_matrix),
121 function(i) all(!is.na(series_matrix[,i])) )
99f83c9a 122 series_matrix = series_matrix[,no_NAs_indices]
3d69ff21
BA
123
124 series_fds = rainbow::fds(seq_len(nrow(series_matrix)), series_matrix)
fa8078f9 125 par(mar=c(4.7,5,1,1), cex.axis=1.5, cex.lab=1.5)
4e25de2c 126 rainbow::fboxplot(series_fds, "functional", "hdr", xlab="Time (hours)", ylab="PM10",
3d69ff21 127 plotlegend=FALSE, lwd=2)
98e958ca
BA
128 rainbow::fboxplot(series_fds, "bivariate", "hdr", plotlegend=FALSE)
129}
130
131#' Compute filaments
132#'
102bcfda
BA
133#' Obtain similar days in the past, and (optionally) plot them -- as black as distances
134#' are small.
98e958ca 135#'
102bcfda 136#' @inheritParams computeError
8f84543c 137#' @param index Index in forecast (integer or date)
98e958ca
BA
138#' @param limit Number of neighbors to consider
139#' @param plot Should the result be plotted?
d2ab47a7 140#' @param predict_from First prediction instant
98e958ca
BA
141#'
142#' @return A list with
143#' \itemize{
144#' \item index : index of the current serie ('today')
145#' \item neighb_indices : indices of its neighbors
146#' \item colors : colors of neighbors curves (shades of gray)
147#' }
148#'
149#' @export
d2ab47a7 150computeFilaments <- function(data, pred, index, predict_from, limit=60, plot=TRUE)
98e958ca 151{
d2ab47a7 152 if (is.null(pred$getParams(index)$weights) || is.na(pred$getParams(index)$weights[1]))
98e958ca
BA
153 stop("computeFilaments requires a serie without NAs")
154
98e958ca 155 # Compute colors for each neighbor (from darkest to lightest)
8f84543c
BA
156 sorted_dists = sort(-log(pred$getParams(index)$weights), index.return=TRUE)
157 nn = min(limit, length(sorted_dists$x))
158 min_dist = min(sorted_dists$x[1:nn])
159 max_dist = max(sorted_dists$x[1:nn])
160 color_values = floor(19.5*(sorted_dists$x[1:nn]-min_dist)/(max_dist-min_dist)) + 1
98e958ca
BA
161 colors = gray.colors(20,0.1,0.9)[color_values] #TODO: 20 == magic number
162
163 if (plot)
164 {
165 # Complete series with (past and present) tomorrows
d2ab47a7
BA
166 ref_serie = c( data$getCenteredSerie( pred$getIndexInData(index)-1 ),
167 data$getCenteredSerie( pred$getIndexInData(index) ) )
8f84543c 168 centered_series = rbind(
9e0f25f6
BA
169 data$getCenteredSeries( pred$getParams(index)$indices-1 ),
170 data$getCenteredSeries( pred$getParams(index)$indices ) )
72b9c501
BA
171 yrange = range( ref_serie,
172 quantile(centered_series, probs=c(0.025,0.975), na.rm=TRUE) )
98e958ca
BA
173 par(mar=c(4.7,5,1,1), cex.axis=1.5, cex.lab=1.5, lwd=2)
174 for (i in nn:1)
175 {
8f84543c 176 plot(centered_series[,sorted_dists$ix[i]], ylim=yrange, type="l", col=colors[i],
4e25de2c 177 xlab=ifelse(i==1,"Time (hours)",""), ylab=ifelse(i==1,"Centered PM10",""))
98e958ca
BA
178 par(new=TRUE)
179 }
180 # Also plot ref curve, in red
181 plot(ref_serie, ylim=yrange, type="l", col="#FF0000", xlab="", ylab="")
d2ab47a7 182 abline(v=24+predict_from-0.5, lty=2, col=colors()[56], lwd=1)
98e958ca
BA
183 }
184
8f84543c
BA
185 list(
186 "index"=pred$getIndexInData(index),
187 "neighb_indices"=pred$getParams(index)$indices[sorted_dists$ix[1:nn]],
188 "colors"=colors)
fa8078f9
BA
189}
190
af3b84f4 191#' Functional boxplot on filaments
fa8078f9 192#'
102bcfda 193#' Draw the functional boxplot on filaments obtained by \code{computeFilaments()}.
fa8078f9 194#'
102bcfda 195#' @inheritParams computeError
98e958ca 196#' @param fil Output of \code{computeFilaments}
fa8078f9
BA
197#'
198#' @export
d2ab47a7 199plotFilamentsBox = function(data, fil, predict_from)
fa8078f9 200{
98e958ca
BA
201 if (!requireNamespace("rainbow", quietly=TRUE))
202 stop("Functional boxplot requires the rainbow package")
203
204 series_matrix = rbind(
3fd7377d 205 data$getSeries(fil$neighb_indices-1), data$getSeries(fil$neighb_indices) )
98e958ca 206 series_fds = rainbow::fds(seq_len(nrow(series_matrix)), series_matrix)
3fd7377d 207
98e958ca 208 par(mar=c(4.7,5,1,1), cex.axis=1.5, cex.lab=1.5)
4e25de2c 209 rainbow::fboxplot(series_fds, "functional", "hdr", xlab="Time (hours)", ylab="PM10",
98e958ca
BA
210 plotlegend=FALSE, lwd=2)
211
72b9c501 212 # "Magic": http://stackoverflow.com/questions/13842560/get-xlim-from-a-plot-in-r
fa8078f9
BA
213 usr <- par("usr")
214 yr <- (usr[4] - usr[3]) / 27
98e958ca 215 par(new=TRUE)
a5a3a294 216 plot(c(data$getSerie(fil$index),data$getSerie(fil$index+1)), type="l", lwd=2, lty=2,
fa8078f9 217 ylim=c(usr[3] + yr, usr[4] - yr), xlab="", ylab="")
d2ab47a7 218 abline(v=24+predict_from-0.5, lty=2, col=colors()[56])
3d69ff21 219}
16b1c049 220
af3b84f4 221#' Plot relative conditional variability / absolute variability
16b1c049 222#'
af3b84f4 223#' Draw the relative conditional variability / absolute variability based on filaments
102bcfda 224#' obtained by \code{computeFilaments()}.
16b1c049 225#'
102bcfda
BA
226#' @inheritParams computeError
227#' @inheritParams plotFilamentsBox
16b1c049
BA
228#'
229#' @export
d2ab47a7 230plotRelVar = function(data, fil, predict_from)
16b1c049 231{
3fd7377d
BA
232 ref_var = c( apply(data$getSeries(fil$neighb_indices-1),1,sd),
233 apply(data$getSeries(fil$neighb_indices),1,sd) )
cf3bb001 234 tdays = .getNoNA2(data, 2, fil$index)
72b9c501 235 global_var = c(
cf3bb001
BA
236 apply(data$getSeries(tdays-1),1,sd),
237 apply(data$getSeries(tdays),1,sd) )
16b1c049 238
af3b84f4 239 yrange = range(ref_var, global_var)
16b1c049 240 par(mar=c(4.7,5,1,1), cex.axis=1.5, cex.lab=1.5)
af3b84f4 241 plot(ref_var, type="l", col=1, lwd=3, ylim=yrange,
4e25de2c 242 xlab="Time (hours)", ylab="Standard deviation")
16b1c049 243 par(new=TRUE)
98e958ca 244 plot(global_var, type="l", col=2, lwd=3, ylim=yrange, xlab="", ylab="")
d2ab47a7 245 abline(v=24+predict_from-0.5, lty=2, col=colors()[56])
16b1c049 246}