~ubuntu-branches/ubuntu/oneiric/latticeextra/oneiric

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
##
## Copyright (c) 2008 Felix Andrews <felix@nfrac.org>
## GPL version 2 or newer

as.layer <- function(x, ...)
    UseMethod("as.layer")

as.layer.layer <- function(x, ...)
    x

layer <-
    function(..., data = NULL,
             magicdots = TRUE, exclude = NULL,
             packets = NULL, 
             rows = NULL, columns = NULL,
             groups = NULL,
             style = NULL, force = FALSE,
             theme = if (force) trellis.par.get() else NULL,
             under = FALSE, superpose = FALSE)
{
    ## set layer to quoted expressions in `...`
    foo <- eval(substitute(expression(...)))
    if (magicdots) {
        ## The dots `...` are magic:
        ## pass on only those arguments not named in each call
        foo <- as.expression(lapply(foo, magicDots, exclude = exclude))
    }
    mostattributes(foo) <-
        list(data = data,
             under = under,
             packets = packets,
             rows = rows,
             columns = columns,
             groups = groups,
             superpose = superpose,
             style = style,
             theme = theme)
    lay <- list(foo)
    class(lay) <- c("layer", "trellis")
    lay
}

## convert a call containing `...` to only pass on arguments
## not named in the call
magicDots <- function(ocall, exclude = NULL, assume.xy = TRUE)
{
    if (!is.call(ocall)) stop("arguments to layer() should be calls")
    ## call recursively with any calls inside this one
    for (i in seq_along(ocall)[-1]) {
        thisArg <- ocall[[i]]
        if (missing(thisArg)) ## eg x[,1]
            next
        if (is.call(thisArg)) {
            ## skip function definitions
            if (identical(thisArg[[1]], as.symbol("function")))
                next
            ocall[[i]] <- Recall(thisArg, exclude = exclude, assume.xy = assume.xy)
        }
    }
    Args <- as.list(ocall)[-1]
    ## nothing to do if there are no dots in the call
    idots <- sapply(Args, identical, as.symbol("..."))
    if (!any(idots))
        return(ocall)
    Args <- Args[!idots]
    ## nothing to do if there are only dots in the call (unless exclude)
    if ((length(Args) == 0) && (length(exclude) == 0))
        return(ocall)
    ## assume first argument is 'x' if is un-named, and second 'y'
    if (assume.xy && (length(Args) > 0)) {
        if (is.null(names(Args)))
            names(Args) <- rep("", length = length(Args))
        if (identical(names(Args)[1], ""))
            names(Args)[1] <- "x"
        if (identical(names(Args)[2], ""))
            names(Args)[2] <- "y"
    }
    if (length(exclude) == 0) {
        ## simple case
        mcall <-
            substitute(do.call(FUN,
                               modifyList(list(...), Args)),
                       list(FUN = ocall[[1]], Args = Args))
    } else {
        ## exclude named arguments from dots
        mcall <-
            substitute(do.call(FUN,
                               modifyList(list(...)[!(names(list(...)) %in% exclude)],
                                          Args)),
                       list(FUN = ocall[[1]], Args = Args, exclude = exclude))
    }
    mcall
}

layer_ <- function(...)
{
    ccall <- match.call()
    ccall$under <- TRUE
    ccall[[1]] <- quote(layer)
    eval.parent(ccall)
}

glayer <- function(...)
{
    ccall <- match.call()
    ccall$superpose <- TRUE
    ccall[[1]] <- quote(layer)
    eval.parent(ccall)
}

glayer_ <- function(...)
{
    ccall <- match.call()
    ccall$superpose <- TRUE
    ccall$under <- TRUE
    ccall[[1]] <- quote(layer)
    eval.parent(ccall)
}

## to avoid print.trellis
print.layer <- print.default

## to avoid [.trellis and to keep the class attribute
"[.layer" <- function (x, i, ...)
    structure(unclass(x)[i], class = class(x))

"+.trellis" <- function(object, lay)
{
    ocall <- sys.call(sys.parent()); ocall[[1]] <- quote(`+`)
    stopifnot(inherits(object, "trellis"))
    lay <- as.layer(lay)
    if (inherits(object, "layer")) {
        ## just concatenate lists
        return(structure(c(unclass(object), unclass(lay)),
                         class = c("layer", "trellis")))
    }
    panel <- if ("panel" %in% names(object$panel.args.common))
        object$panel.args.common$panel
    else object$panel
    panel <- if (is.function(panel)) panel
    else if (is.character(panel)) {
        ## could be just get(panel), but for flattenPanel:
        ## do not expand original panel function eg panel.xyplot(...)
        tmp <- function(...) NA
        body(tmp) <- call(panel, quote(...))
        environment(tmp) <- globalenv()
        tmp
    } else eval(panel)
    ## a flag to indicate this panel function has layers
    ## (used by flattenPanel and undoLayer)
    .is.a.layer <- TRUE
    newpanel <- function(...) {
        .UNDER <- unlist(lapply(lay, attr, "under"))
        ## underlaying items only
        drawLayer(lay[.UNDER], list(...))
        ## original panel function:
        panel(...)
        ## overlaying items only
        drawLayer(lay[.UNDER == FALSE], list(...))
    }
    if ("panel" %in% names(object$panel.args.common))
        object$panel.args.common$panel <- newpanel
    else object$panel <- newpanel
    ## need this to allow further calls to update() to insert arguments:
    object$call <- call("update", ocall)
    object
}

drawLayer <- function(lay, panelArgs = trellis.panelArgs())
{
    lay <- as.layer(lay)
    .UNDER <- unlist(lapply(lay, attr, "under"))
    ## underlayers, in reverse order
    for (.ITEM in rev(lay[.UNDER]))
        drawLayerItem(.ITEM, panelArgs)
    ## overlayers
    for (.ITEM in lay[.UNDER == FALSE])
        drawLayerItem(.ITEM, panelArgs)
    invisible()
}

drawLayerItem <- function(layer.item, panelArgs)
{
    stopifnot(is.expression(layer.item))
    ## check that any restrictions on packets/rows/columns are met
    matchesok <- function(spec, value) {
        if (is.null(spec)) return(TRUE)
        if (is.numeric(spec) && all(spec <= 0))
            ## negative indexes exclude items
            return(value %in% -spec == FALSE)
        else
            return(value %in% spec)
    }
    matchesallok <-
        with(list(a = attributes(layer.item)),
             matchesok(a$packets, packet.number()) &&
             matchesok(a$rows, current.row()) &&
             matchesok(a$columns, current.column()))
    if (!matchesallok) return()
    ## set given theme for duration of this function
    if (!is.null(attr(layer.item, "theme"))) {
        .TRELLISPAR <- trellis.par.get()
        trellis.par.set(attr(layer.item, "theme"))
        on.exit(trellis.par.set(.TRELLISPAR))
    }
    ## define a layer drawing function, which may be per group
    drawLayerItemPerGroup <- function(...)
    {
        ## Note: layer.item is found in this function's environment
        dots <- list(...)
        ## restrict to specified group numbers
        groupok <- (matchesok(attr(layer.item, "groups"), dots$group.number) ||
                    matchesok(attr(layer.item, "groups"), as.character(dots$group.value)))
        if (!groupok)
            return()
        if (!is.null(attr(layer.item, "style"))) {
            ## extract plot style attributes from given index into superpose.*
            .TRELLISPAR <- trellis.par.get()
            local({
                i <- attr(layer.item, "style")
                line <- Rows(trellis.par.get("superpose.line"), i)
                symbol <- Rows(trellis.par.get("superpose.symbol"), i)
                polygon <- Rows(trellis.par.get("superpose.polygon"), i)
                trellis.par.set(plot.line = line,
                                superpose.line = line,
                                add.line = line,
                                add.text = line,
                                plot.symbol = symbol,
                                superpose.symbol = symbol,
                                plot.polygon = polygon,
                                superpose.polygon = polygon,
                                axis.text = line,
                                axis.line = line
                                )
            })
            on.exit(trellis.par.set(.TRELLISPAR))
        }
        with(dots,
             eval(layer.item, attr(layer.item, "data"),
                  environment()))
    }
    ## call panel.superpose for group layers
    if (isTRUE(attr(layer.item, "superpose"))) {
        do.call("panel.superpose",
                modifyList(panelArgs,
                  list(panel.groups = drawLayerItemPerGroup)))
    } else {
        do.call("drawLayerItemPerGroup", panelArgs)
    }
}

flattenPanel <- function(object)
{
    flattenFun <- function(fun)
    {
        env <- environment(fun)
        ## check if this panel function is simple or has layers
        if (is.null(env) ||
            !exists(".is.a.layer", env, inherits = FALSE))
            return(as.expression(body(fun)))
        ## merge: under layers, existing panel, over layers
        .UNDER <- sapply(env$lay, attr, "under")
        c(do.call("c", rev(env$lay[.UNDER])),
          flattenFun(env$panel),
          do.call("c", env$lay[.UNDER == FALSE]))
    }
    flat <- flattenFun(object$panel)
    ## wrap in braces, as in a function body
    as.call(c(quote(`{`), flat))
}

## not exported -- I do not think this is really useful
undoLayer <- function(x)
{
    stopifnot(is.function(x$panel))
    env <- environment(x$panel)
    if (!exists(".is.a.layer", env, inherits=FALSE))
        stop("does not look like a layer")
    update(x, panel=env$panel)
}