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