Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
use env for perl in this script
[simgrid.git] / contrib / benchmarking_code_block / Rdhist.R
1 #-------------------------------------------------------------------------------
2 # Copyright (c) 2012 University of Illinois, NCSA.
3 # All rights reserved. This program and the accompanying materials
4 # are made available under the terms of the
5 # University of Illinois/NCSA Open Source License
6 # which accompanies this distribution, and is available at
7 # http://opensource.ncsa.illinois.edu/license.html
8 ##' Variable-width (dagonally cut) histogram
9 ##'
10 ##' When constructing a histogram, it is common to make all bars the same width.
11 ##' One could also choose to make them all have the same area.
12 ##' These two options have complementary strengths and weaknesses; the equal-width histogram oversmooths in regions of high density, and is poor at identifying sharp peaks; the equal-area histogram oversmooths in regions of low density, and so does not identify outliers.
13 ##' We describe a compromise approach which avoids both of these defects. We regard the histogram as an exploratory device, rather than as an estimate of a density.
14 ##' @name dhist
15 ##' @title Diagonally Cut Histogram
16 ##' @param x is a numeric vector (the data)
17 ##' @param a is the scaling factor, default is 5 * IQR
18 ##' @param nbins is the number of bins, default is assigned by the Stuges method
19 ##' @param rx is the range used for the left of the left-most bin to the right of the right-most bin
20 ##' @param eps used to set artificial bound on min width / max height of bins as described in Denby and Mallows (2009) on page 24.
21 ##' @param xlab is label for the x axis
22 ##' @param plot = TRUE produces the plot, FALSE returns the heights, breaks and counts
23 ##' @param lab.spikes = TRUE labels the \% of data in the spikes
24 ##' @return list with two elements, heights of length n and breaks of length n+1 indicating the heights and break points of the histogram bars.
25 ##' @author Lorraine Denby, Colin Mallows
26 ##' @references Lorraine Denby, Colin Mallows. Journal of Computational and Graphical Statistics. March 1, 2009, 18(1): 21-31. doi:10.1198/jcgs.2009.0002.
27 dhist <- function(x, a=5*iqr(x), nbins=nclass.Sturges(x),
28                   rx = range(x,na.rm = TRUE), eps=.15, xlab = "x", plot = TRUE,lab.spikes = TRUE){
29   if(is.character(nbins))
30     nbins <- switch(casefold(nbins), sturges = nclass.Sturges(x), fd = nclass.FD(x), scott = nclass.scott(x),
31                     stop("Nclass method not recognized"))
32   else if(is.function(nbins))
33     nbins <- nbins(x)
34
35   x <- sort(x[!is.na(x)])
36   if(a == 0)
37     a <- diff(range(x))/100000000
38   if(a != 0 & a != Inf) {
39     n <- length(x)
40     h <- (rx[2] + a - rx[1])/nbins
41     ybr <- rx[1] + h * (0:nbins)
42     yupper <- x + (a * (1:n))/n
43                                         # upper and lower corners in the ecdf
44     ylower <- yupper - a/n
45
46     cmtx <- cbind(cut(yupper, breaks = ybr), cut(yupper, breaks = ybr, left.include = TRUE), cut(ylower, breaks = ybr),
47                   cut(ylower, breaks = ybr, left.include = TRUE))
48     cmtx[1, 3] <- cmtx[1, 4] <- 1
49                                         # to replace NAs when default r is used
50     cmtx[n, 1] <- cmtx[n, 2] <- nbins
51                                         #checksum <- apply(cmtx, 1, sum) %% 4
52     checksum <- (cmtx[, 1] + cmtx[, 2] + cmtx[, 3] + cmtx[, 4]) %% 4
53                                         # will be 2 for obs. that straddle two bins
54     straddlers <- (1:n)[checksum == 2]
55                                         # to allow for zero counts
56     if(length(straddlers) > 0) {
57       counts <- table(c(1:nbins, cmtx[ - straddlers, 1]))
58     } else {
59       counts <- table(c(1:nbins, cmtx[, 1]))
60     }
61     counts <- counts - 1
62
63     if(length(straddlers) > 0) {
64       for(i in straddlers) {
65         binno <- cmtx[i, 1]
66         theta <- ((yupper[i] - ybr[binno]) * n)/a
67         counts[binno - 1] <- counts[binno - 1] + (1 - theta)
68         counts[binno] <- counts[binno] + theta
69       }
70     }
71     xbr <- ybr
72     xbr[-1] <- ybr[-1] - (a * cumsum(counts))/n
73     spike<-eps*diff(rx)/nbins
74     flag.vec<-c(diff(xbr)<spike,F)
75     if ( sum(abs(diff(xbr))<=spike) >1) {
76       xbr.new<-xbr
77       counts.new<-counts
78       diff.xbr<-abs(diff(xbr))
79       amt.spike<-diff.xbr[length(diff.xbr)]
80       for (i in rev(2:length(diff.xbr))) {
81         if (diff.xbr[i-1] <= spike&diff.xbr[i] <= spike & !is.na(diff.xbr[i])) {
82           amt.spike <- amt.spike+diff.xbr[i-1]
83           counts.new[i-1] <- counts.new[i-1]+counts.new[i]
84           xbr.new[i] <- NA
85           counts.new[i] <- NA
86           flag.vec[i-1] <- T
87         }
88         else amt.spike<-diff.xbr[i-1]
89       }
90       flag.vec<-flag.vec[!is.na(xbr.new)]
91       flag.vec<-flag.vec[-length(flag.vec)]
92       counts<-counts.new[!is.na(counts.new)]
93       xbr<-xbr.new[!is.na(xbr.new)]
94
95     }
96     else flag.vec<-flag.vec[-length(flag.vec)]
97     widths <- abs(diff(xbr))
98     ## N.B. argument "widths" in barplot must be xbr
99     heights <- counts/widths
100   }
101   bin.size <- length(x)/nbins
102   cut.pt <- unique(c(min(x) - abs(min(x))/1000, approx(seq(length(x)), x,
103                                                        (1:(nbins - 1)) * bin.size, rule = 2)$y, max(x)))
104   aa <- hist(x, breaks = cut.pt, plot = FALSE, probability = TRUE)
105   if(a == Inf) {
106     heights <- aa$counts
107     xbr <- aa$breaks
108   }
109   amt.height<-3
110   q75<-quantile(heights,.75)
111   if (sum(flag.vec)!=0) {
112     amt<-max(heights[!flag.vec])
113     ylim.height<-amt*amt.height
114     ind.h<-flag.vec&heights> ylim.height
115     flag.vec[heights<ylim.height*(amt.height-1)/amt.height]<-F
116     heights[ind.h] <- ylim.height
117   }
118   amt.txt<-0
119   end.y<-(-10000)
120   if(plot) {
121     barplot(heights, abs(diff(xbr)), space = 0, density = -1, xlab = xlab, plot = TRUE, xaxt = "n",yaxt='n')
122     at <- pretty(xbr)
123     axis(1, at = at - xbr[1], labels = as.character(at))
124     if (lab.spikes) {
125       if (sum(flag.vec)>=1) {
126         usr<-par('usr')
127         for ( i in seq(length(xbr)-1)) {
128           if (!flag.vec[i]) {
129             amt.txt<-0
130             if (xbr[i]-xbr[1]<end.y) amt.txt<-1
131           }
132           else {
133             amt.txt<-amt.txt+1
134             end.y<-xbr[i]-xbr[1]+3*par('cxy')[1]
135           }
136           if (flag.vec[i]) {
137             txt<-paste(' ',format(round(counts[i]/
138                                         sum(counts)*100)),'%',sep='')
139             par(xpd = TRUE)
140             text(xbr[i+1]-xbr[1],ylim.height-par('cxy')[2]*(amt.txt-1),txt, adj=0)
141           }
142         }
143       } else print('no spikes or more than one spike')
144     }
145     invisible(list(heights = heights, xbr = xbr))
146   } else {return(list(heights = heights, xbr = xbr,counts=counts))}
147 }
148 #==================================================================================================#
149 ##' Calculate interquartile range
150 ##'
151 ##' Calculates the 25th and 75th quantiles given a vector x; used in function \link{dhist}.
152 ##' @name iqr
153 ##' @title Interquartile range
154 ##' @param x vector
155 ##' @return numeric vector of length 2, with the 25th and 75th quantiles of input vector x.
156 iqr <- function(x){
157   return(diff(quantile(x, c(0.25, 0.75), na.rm = TRUE)))
158 }
159 ##==================================================================================================#
160 ##' Creates empty ggplot object
161 ##'
162 ##' An empty base plot to which layers created by other functions
163 ##' (\code{\link{plot.data}}, \code{\link{plot.prior.density}},
164 ##' \code{\link{plot.posterior.density}}) can be added.
165 ##' @name create.base.plot
166 ##' @title Create Base Plot
167 ##' @return empty ggplot object
168 ##' @export
169 ##' @author David LeBauer
170 create.base.plot <- function() {
171   base.plot <- ggplot()
172   return(base.plot)
173 }
174 #==================================================================================================#
175 ##' Add data to an existing plot or create a new one from \code{\link{create.base.plot}}
176 ##'
177 ##' Used to add raw data or summary statistics to the plot of a distribution.
178 ##' The height of Y is arbitrary, and can be set to optimize visualization.
179 ##' If SE estimates are available, tehse wil be plotted
180 ##' @name plot.data
181 ##' @title Add data to plot
182 ##' @param trait.data data to be plotted
183 ##' @param base.plot a ggplot object (grob),
184 ##' created by \code{\link{create.base.plot}} if none provided
185 ##' @param ymax maximum height of y
186 ##' @seealso \code{\link{create.base.plot}}
187 ##' @return updated plot object
188 ##' @author David LeBauer
189 ##' @export
190 ##' @examples
191 ##' \dontrun{plot.data(data.frame(Y = c(1, 2), se = c(1,2)), base.plot = NULL, ymax = 10)}
192 plot.data <- function(trait.data, base.plot = NULL, ymax, color = 'black') {
193   if(is.null(base.plot)) base.plot <- create.base.plot()
194   n.pts <- nrow(trait.data)
195   if(n.pts == 1){
196     ymax <- ymax/8
197   } else if (n.pts < 5) {
198     ymax <- ymax / 4
199   } else {
200     ymax <- ymax / 2
201   }
202   y.pts <- seq(0, ymax, length.out = 1 + n.pts)[-1]
203   plot.data <- data.frame(x = trait.data$Y, y = y.pts, se = trait.data$se,
204                           control = !trait.data$trt == 1 & trait.data$ghs == 1)
205   new.plot <- base.plot + geom_point(data = plot.data, aes(x = x, y = y, color = control)) +
206                  geom_segment(data = plot.data, aes(x = x - se, y = y, xend = x + se, yend = y, color = control)) +
207                      scale_color_manual(values = c('black', 'grey')) + opts(legend_position = "none")
208   return(new.plot)
209 }
210 ##==================================================================================================#
211 ##' Add borders to .. content for \description{} (no empty lines) ..
212 ##'
213 ##' Has ggplot2 display only specified borders, e.g. ("L"-shaped) borders, rather than a rectangle or no border. Note that the order can be significant; for example, if you specify the L border option and then a theme, the theme settings will override the border option, so you need to specify the theme (if any) before the border option, as above.
214 ##' @name theme_border
215 ##' @title Theme border for plot
216 ##' @param type
217 ##' @param colour
218 ##' @param size
219 ##' @param linetype
220 ##' @return adds borders to ggplot as a side effect
221 ##' @author Rudolf Cardinal
222 ##' @author \url{ggplot2 google group}{https://groups.google.com/forum/?fromgroups#!topic/ggplot2/-ZjRE2OL8lE}
223 ##' @examples
224 ##' \dontrun{
225 ##' df = data.frame( x=c(1,2,3), y=c(4,5,6) )
226 ##' ggplot(data=df, aes(x=x, y=y)) + geom_point() + theme_bw() +
227 ##' opts(panel.border = theme_border(c("bottom","left")) )
228 ##' ggplot(data=df, aes(x=x, y=y)) + geom_point() + theme_bw() +
229 ##' opts(panel.border = theme_border(c("b","l")) )
230 ##' }
231 theme_border <- function(type = c("left", "right", "bottom", "top", "none"), colour = "black", size = 1, linetype = 1){
232   type <- match.arg(type, several.ok=TRUE)
233   structure(function(x = 0, y = 0, width = 1, height = 1, ...) {
234       xlist <- c()
235       ylist <- c()
236       idlist <- c()
237       if ("bottom" %in% type) { # bottom
238           xlist <- append(xlist, c(x, x+width))
239           ylist <- append(ylist, c(y, y))
240           idlist <- append(idlist, c(1,1))
241       }
242       if ("top" %in% type) { # top
243           xlist <- append(xlist, c(x, x+width))
244           ylist <- append(ylist, c(y+height, y+height))
245           idlist <- append(idlist, c(2,2))
246       }
247       if ("left" %in% type) { # left
248           xlist <- append(xlist, c(x, x))
249           ylist <- append(ylist, c(y, y+height))
250           idlist <- append(idlist, c(3,3))
251       }
252       if ("right" %in% type) { # right
253           xlist <- append(xlist, c(x+width, x+width))
254           ylist <- append(ylist, c(y, y+height))
255           idlist <- append(idlist, c(4,4))
256       }
257       polylineGrob(x=xlist, y=ylist, id=idlist, ..., default.units = "npc",
258                    gp=gpar(lwd=size, col=colour, lty=linetype),
259                    )
260   },
261             class = "theme",
262             type = "box",
263             call = match.call()
264             )
265 }
266 #==================================================================================================#