\documentclass[article,shortnames,nojss]{jss}

%\VignetteIndexEntry{Restricted permutations; using the permute package}
%\VignettePackage{permute}

%% almost as usual
\author{Gavin L. Simpson\\University of Regina}
\title{Restricted permutations; using the \pkg{permute} package}

%% for pretty printing and a nice hypersummary also set:
\Plainauthor{Gavin L. Simpson} %% comma-separated
\Plaintitle{Restricted permutations; using the permute package} %% without formatting
\Shorttitle{Using the permute package} %% a short title (if necessary)

%% an abstract and keywords
\Abstract{
  TODO
}
\Keywords{permutations, restricted permutations, time series, transects, spatial grids, split-plot designs, Monte Carlo resampling, \proglang{R}}
\Plainkeywords{permutations, restricted permutations, time series, transects, spatial grids, split-plot designs, Monte Carlo resampling, R} %% without formatting
%% at least one keyword must be supplied

%% The address of (at least) one author should be given
%% in the following format:
% \Address{
%   Gavin L. Simpson\\
%   Environmental Change Research Centre\\
%   UCL Department of Geography\\
%   Pearson Building\\
%   Gower Street\\
%   London, UK, WC1E 6BT\\
%   E-mail: \email{gavin.simpson@ucl.ac.uk}\\
%   URL: \url{http://www.homepages.ucl.ac.uk/~ucfagls/}
% }
%% It is also possible to add a telephone and fax number
%% before the e-mail in the following format:
%% Telephone: +43/1/31336-5053
%% Fax: +43/1/31336-734

%% for those who use Sweave please include the following line (with % symbols):
%% need no \usepackage{Sweave.sty}

%% end of declarations %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{document}

%% include your article here, just as usual
%% Note that you should use the \pkg{}, \proglang{} and \code{} commands.
<<preliminary,results=hide,echo=false>>=
options("prompt" = "R> ", "continue" = "+  ")
options(useFancyQuotes="UTF-8")
@
\section{Introduction}
In classical frequentist statistics, the significance of a relationship or model is determined by reference to a null distribution for the test statistic. This distribution is derived mathematically and the probability of achieving a test statistic as large or larger if the null hypothesis were true is looked-up from this null distribution. In deriving this probability, some assumptions about the data or the errors are made. If these assumptions are violated, then the validity of the derived $p$-value may be questioned.

An alternative to deriving the null distribution from theory is to generate a null distribution of the test statistic by randomly shuffling the data in some manner, refitting the model and deriving values for the test statistic for the permuted data. The level of significance of the test can be computed as the proportion of values of the test statistic from the null distribution that are equal to or larger than the observed value.

In many data sets, simply shuffling the data at random is inappropriate; under the null hypothesis, that data are not freely exchangeable, for example if there is temporal or spatial correlation, or the samples are clustered in some way, such as multiple samples collected from each of a number of fields. The \pkg{permute} package was designed to provide facilities for generating these restricted permutations for use in randomisation tests. \pkg{permute} takes as its motivation the permutation schemes originally available in \proglang{Canoco} version 3.1 \citep{canoco31}, which employed the cyclic- or toroidal-shifts suggested by \citet{besagclifford}.

\section{Simple randomisation}\label{sec:simple}
As an illustration of both randomisation and simple usage of the \pkg{permute} package we consider a small data set of mandible length measurements on specimens of the golden jackal (\emph{Canis aureus}) from the British Museum of Natural History, London, UK. These data were collected as part of a study comparing prehistoric and modern canids \citep{higham80}, and were analysed by \citet{manly07}. There are ten measurements of mandible length on both male and female specimens. The data are available in the \code{jackal} data frame supplied with \pkg{permute}.

<<load_jackal>>=
library("permute")
data(jackal)
jackal
@

The interest is whether there is a difference in the mean mandible length between male and female golden jackals. The null hypothesis is that there is zero difference in mandible length between the two sexes or that females have larger mandibles. The alternative hypothesis is that males have larger mandibles. The usual statistical test of this hypothesis is a one-sided $t$ test, which can be applied using \code{t.test()}

<<ttest_jackal, keep.source=true>>=
jack.t <- t.test(Length ~ Sex, data = jackal, var.equal = TRUE,
                 alternative = "greater")
jack.t
@

The observed $t$ is \Sexpr{with(jack.t, round(statistic, 3))} with \Sexpr{with(jack.t, parameter)} df. The probability of observing a value this large or larger if the null hypothesis were true is \Sexpr{with(jack.t, round(p.value, 4))}. Several assumptions have been made in deriving this $p$-value, namely

\begin{enumerate}
  \item random sampling of individuals from the populations of interest,
  \item equal population standard deviations for males and females, and
  \item that the mandible lengths are normally distributed within the sexes.
\end{enumerate}

Assumption 1 is unlikely to be valid for museum specimens such as these, that have been collected in some unknown manner. Assumption 2 may be valid, Fisher's $F$-test and a Fligner-Killeen test both suggest that the standard deviations of the two populations do not differ significantly
<<ftest_jackal>>=
var.test(Length ~ Sex, data = jackal)
fligner.test(Length ~ Sex, data = jackal)
@
This assumption may be relaxed using \code{var.equal = FALSE} (the default) in the call to \code{t.test()}, to employ Welch's modification for unequal variances. Assumption 3 may be valid, but with such a small sample we are unable to reliably test this.

A randomisation test of the same hypothesis can be performed by randomly allocating ten of the mandible lengths to the male group and the remaining lengths to the female group. This randomisation is justified under the null hypothesis because the observed difference in mean mandible length between the two sexes is just a typical value for the difference in a sample if there were no difference in the population. An appropriate test statistic needs to be selected. We could use the $t$ statistic as derived in the $t$-test. Alternatively, we could base our randomisation test on the difference of means $D_i$ (male - female).

The main function in \pkg{permute} for providing random permutations is \code{shuffle()}. We can write our own randomisation test for the \code{jackal} data by first creating a function to compute the difference of means for two groups
<<meanFun>>=
meanDif <- function(x, grp) {
 mean(x[grp == "Male"]) - mean(x[grp == "Female"])
}
@
which can be used in a simple \code{for()} loop to generate the null distribution for the difference of means. First, we allocate some storage to hold the null difference of means; here we use 4999 random permutations so allocate a vector of length 5000. Then we iterate, randomly generating an ordering of the \code{Sex} vector and computing the difference of means for that permutation.
<<randJackal>>=
Djackal <- numeric(length = 5000)
N <- nrow(jackal)
set.seed(42)
for(i in seq_len(length(Djackal) - 1)) {
    perm <- shuffle(N)
    Djackal[i] <- with(jackal, meanDif(Length, Sex[perm]))
}
Djackal[5000] <- with(jackal, meanDif(Length, Sex))
@
The observed difference of means was added to the null distribution, because under the null hypothesis the observed allocation of mandible lengths to male and female jackals is just one of the possible random allocations.

The null distribution of $D_i$ can be visualised using a histogram, as shown in Figure~\ref{hist_jackal}. The observed difference of means (\Sexpr{round(Djackal[5000], 2)}) is indicated by the red tick mark.

<<hist_jackal, fig=false, echo=true, eval=false, keep.source=true>>=
hist(Djackal, main = "",
     xlab = expression("Mean difference (Male - Female) in mm"))
rug(Djackal[5000], col = "red", lwd = 2)
@
The number of values in the randomisation distribution equal to or larger than the observed difference is
<<>>=
(Dbig <- sum(Djackal >= Djackal[5000]))
@
giving a permutational $p$-value of
<<>>=
Dbig / length(Djackal)
@
which is comparable with that determined from the frequentist $t$-test, and indicates strong evidence against the null hypothesis of no difference.
\begin{figure}[t]
  \centering
<<draw_hist_jackal, fig=true, echo=false>>=
<<hist_jackal>>
@
\caption{\label{hist_jackal}Distribution of the difference of mean mandible length in random allocations, ten to each sex.}
\end{figure}

In total there $^{20}C_{10} = \Sexpr{formatC(choose(20,10), big.mark = ",", format = "f", digits = 0)}$ possible allocations of the 20 observations to two groups of ten
<<>>=
choose(20, 10)
@
so we have only evaluated a small proportion of these in the randomisation test.

The main workhorse function we used above was \code{shuffle()}. In this example, we could have used the base R function \code{sample()} to generate the randomised indices \code{perm} that were used to permute the \code{Sex} factor. Where \code{shuffle()} comes into it's own is for generating permutation indices from restricted permutation designs.

\section{The shuffle() and shuffleSet() functions}
In the previous section I introduced the \code{shuffle()} function to generate permutation indices for use in a randomisation test. Now we will take a closer look at \code{shuffle()} and explore the various restricted permutation designs from which it can generate permutation indices.

\code{shuffle()} has two arguments: i) \code{n}, the number of observations in the data set to be permuted, and ii) \code{control}, a list that defines the permutation design describing how the samples should be permuted.
<<show_args>>=
args(shuffle)
@
A series of convenience functions are provided that allow the user to set-up even quite complex permutation designs with little effort. The user only needs to specify the aspects of the design they require and the convenience functions ensure all configuration choices are set and passed on to \code{shuffle()}. The main convenience function is \code{how()}, which returns a list specifying all the options available for controlling the sorts of permutations returned by \code{shuffle()}.
<<show_str>>=
str(how())
@
The defaults describe a random permutation design where all objects are freely exchangeable. Using these defaults, \code{shuffle(10)} amounts to \code{sample(1:10, 10, replace = FALSE)}:
<<compare_shuffle_sample>>=
set.seed(2)
(r1 <- shuffle(10))
set.seed(2)
(r2 <- sample(1:10, 10, replace = FALSE))
all.equal(r1, r2)
@

\subsection{Generating restricted permutations}
Several types of permutation are available in \pkg{permute}:

\begin{itemize}
  \item Free permutation of objects
  \item Time series or line transect designs, where the temporal or spatial ordering is preserved.
  \item Spatial grid designs, where the spatial ordering is preserved in both coordinate directions
  \item Permutation of plots or groups of samples.
  \item Blocking factors which restrict permutations to within blocks. The preceding designs can be nested within blocks.
\end{itemize}

The first three of these can be nested within the levels of a factor or to the levels of that factor, or to both. Such flexibility allows the analysis of split-plot designs using permutation tests, especially when combined with blocks.

\code{how()} is used to set up the design from which \code{shuffle()} will draw a permutation. \code{how()} has two main arguments that specify how samples are permuted \emph{within} plots of samples or at the plot level itself. These are \code{within} and \code{plots}. Two convenience functions, \code{Within()} and \code{Plots()} can be used to set the various options for permutation. Blocks operate at the uppermost level of this hierarchy; blocks define groups of plots, each of which may contain groups of samples.

For example, to permute the observations \code{1:10} assuming a time series design for the entire set of observations, the following control object would be used

<<series1, keep.source=true>>=
set.seed(4)
x <- 1:10
CTRL <- how(within = Within(type = "series"))
perm <- shuffle(10, control = CTRL)
perm
x[perm] ## equivalent
@

It is assumed that the observations are in temporal or transect order. We only specified the type of permutation within plots, the remaining options were set to their defaults via \code{Within()}.

A more complex design, with three plots, and a 3 by 3 spatial grid arrangement within each plot can be created as follows

<<grid1, keep.source=true>>=
set.seed(4)
plt <- gl(3, 9)
CTRL <- how(within = Within(type = "grid", ncol = 3, nrow = 3),
            plots = Plots(strata = plt))
perm <- shuffle(length(plt), control = CTRL)
perm
@

Visualising the permutation as the 3 matrices may help illustrate how the data have been shuffled

<<vis_grid1, keep.source=true>>=
## Original
lapply(split(seq_along(plt), plt), matrix, ncol = 3)
## Shuffled
lapply(split(perm, plt), matrix, ncol = 3)
@

In the first grid, the lower-left corner of the grid was set to row 2 and column 2 of the original, to row 1 and column 2 in the second grid, and to row 3 column 2 in the third grid.

To have the same permutation within each level of \code{plt}, use the \code{constant} argument of the \code{Within()} function, setting it to \code{TRUE}
<<grid_2, keep.source=TRUE>>=
set.seed(4)
CTRL <- how(within = Within(type = "grid", ncol = 3, nrow = 3,
                            constant = TRUE),
            plots = Plots(strata = plt))
perm2 <- shuffle(length(plt), control = CTRL)
lapply(split(perm2, plt), matrix, ncol = 3)
@

\subsection{Generating sets of permutations with shuffleSet()}
There are several reasons why one might wish to generate a set of $n$ permutations instead of repeatedly generating permutations one at a time. Interpreting the permutation design happens each time \code{shuffle()} is called. This is an unnecessary computational burden, especially if you want to perform tests with large numbers of permutations. Furthermore, having the set of permutations available allows for expedited use with other functions, they can be iterated over using \code{for} loops or the \code{apply} family of functions, and the set of permutations can be exported for use outside of R.

The \code{shuffleSet()} function allows the generation of sets of permutations from any of the designs available in \pkg{permute}. \code{shuffleSet()} takes an additional argument to that of \code{shuffle()}, \code{nset}, which is the number of permutations required for the set. \code{nset} can be missing, in which case the number of permutations in the set is looked for in the object passed to \code{control}; using this, the desired number of permutations can be set at the time the design is created via the \code{nperm} argument of \code{how()}. For example,

<<series_2, results=hide>>=
how(nperm = 10, within = Within(type = "series"))
@

Internally, \code{shuffle()} and \code{shuffleSet()} are very similar, with the major difference being that \code{shuffleSet()} arranges repeated calls to the workhorse permutation-generating functions, only incurring the overhead associated with interpreting the permutation design once. \code{shuffleSet()} returns a matrix where the rows represent different permutations in the set.

As an illustration, consider again the simple time series example from earlier. Here I generate a set of 5 permutations from the design, with the results returned as a matrix

<<shuffleSet_1, keep.source=true>>=
set.seed(4)
CTRL <- how(within = Within(type = "series"))
pset <- shuffleSet(10, nset = 5, control = CTRL)
pset
@

It is worth taking a moment to explain what has happened here, behind the scenes. There are only \Sexpr{numPerms(10, CTRL)} unique orderings (including the observed) in the set of permutations for this design. Such a small set of permutations triggers\footnote{The trigger is via the utility function \code{check()}, which calls another utility function, \code{allPerms()}, to generate the set of permutations for the stated design. The trigger for complete enumeration is set via \code{how()} using argument \code{minperm}; below this value, by default \code{check()} will generate the entire set of permutations.} the generation of the entire set of permutations. From this set, \code{shuffleSet()} samples at random \code{nset} permutations. Hence the same number of random values has been generated via the pseudo-random number generator in \proglang{R} but we ensure a set of unique permutations is drawn, rather than randomly sample from a small set.

\section{Defining permutation designs}
In this section I give examples how various permutation designs can be specified using \code{how()}. It is not the intention to provide exhaustive coverage of all possible designs that can be produced; such a list would be tedious to both write \emph{and} read. Instead, the main features and options will be described through a series of examples. The reader should then be able to put together the various options to create the exact structure required.

\subsection{Set the number of permutations}
It may be useful to specify the number of permutations required in a permutation test alongside the permutation design. This is done via the \code{nperm} argument, as seen earlier. If nothing else is specified
<<results=hide>>=
how(nperm = 999)
@
would indicate 999 random permutations where the samples are all freely exchangeable.

One advantage of using \code{nperm} is that \code{shuffleSet()} will use this if the \code{nset} argument is not specified. Additionally, \code{shuffleSet()} will check to see if the desired number of permutations is possible given the data and the requested design. This is done via the function \code{check()}, which is discussed later.

\subsection{The levels of the permutation hierarchy}
There are three levels at which permutations can be controlled in \pkg{permute}. The highest level of the hierarchy is the \emph{block} level. Blocks are defined by a factor variable. Blocks restrict permutation of samples to within the levels of this factor; samples are never swapped between blocks.

The \emph{plot} level sits below blocks. Plots are defined by a factor and group samples in the same way as blocks. As such, some permutation designs can be initiated using a factor at the plot level or the same factor at the block level. The major difference between blocks and plots is that plots can also be permuted, whereas blocks are never permuted.

The lowest level of a permutation design in the \pkg{permute} hierarchy is known as \emph{within}, and refers to samples nested \emph{within} plots. If there are no plots or blocks, how samples are permuted at the \emph{within} level applies to the entire data set.

\subsubsection{Permuting samples at the lowest level}
How samples at the \emph{within} level are permuted is configured using the \code{Within()} function. It takes the following arguments
<<withinArgs, echo=false>>=
args(Within)
@

\begin{description}
  \item[\code{type}]
    controls how the samples at the lowest level are permuted. The default is to form unrestricted permutations via option \code{"type"}. Options \code{"series"} and \code{"grid"} form restricted permutations via cyclic or toroidal shifts, respectively. The former is useful for samples that are a time series or line-transect, whilst the latter is used for samples on a regular spatial grid. The final option, \code{"none"}, will result in the samples at the lowest level not being permuted at all. This option is only of practical use when there are plots within the permutation/experimental design\footnote{As blocks are never permuted, using \code{type = "none"} at the \emph{within} level is also of no practical use.}.
  \item[\code{constant}]
    this argument only has an effect when there are plots in the design\footnote{Owing to the current implementation, whilst this option could also be useful when blocks to define groups of samples, it will not have any influence over how permutations are generated. As such, only use blocks for simple blocking structures and use plots if you require greater control of the permutations at the group (i.e. plot) level.}. \code{constant = TRUE} stipulates that each plot should have the same \emph{within-plot} permutation. This is useful for example when you have time series of observations from several plots. If all plots were sampled at the same time points, it can be argued that at the plot level, the samples experienced the same \emph{time} and hence the same permutation should be used within each plot.
  \item[\code{mirror}]
    when \code{type} is \code{"series"} or \code{"grid"}, argument \code{"mirror"} controls whether permutations are taken from the mirror image of the observed ordering in space or time. Consider the sequence \code{1, 2, 3, 4}. The relationship between observations is also preserved if we reverse the original ordering to \code{4, 3, 2, 1} and generate permutations from both these orderings. This is what happens when \code{mirror = TRUE}. For time series, the reversed ordering \code{4, 3, 2, 1} would imply an influence of observation 4 on observation 3, which is implausible. For spatial grids or line transects, however, this is a sensible option, and can significantly increase the number of possible permutations\footnote{Setting \code{mirror = TRUE} will double or quadruple the set of permutations for \code{"series"} or \code{"grid"} permutations, respectively, as long as there are more than two time points or columns in the grid.}.
  \item[\code{ncol}, \code{nrow}]
    define the dimensions of the spatial grid.
\end{description}

How \code{Within()} is used has already been encountered in earlier sections of this vignette; the function is used to supply a value to the \code{within} argument of \code{how()}. You may have noticed that all the arguments of \code{Within()} have default values? This means that the user need only supply a modified value for the arguments they wish to change. Also, arguments that are not relevant for the type of permutation stated are simply ignored; \code{nrow} and \code{ncol}, for example, could be set to any value without affecting the permutation design if \code{type != "grid"}\footnote{No warnings are currently given if incompatible arguments are specified; they are ignored, but may show up in the printed output. This infelicity will be removed prior to \pkg{permute} version 1.0-0 being released.}.

\subsubsection{Permuting samples at the Plot level}
Permutation of samples at the \emph{plot} level is configured via the \code{Plots()} function. As with \code{Within()}, \code{Plots()} is supplied to the \code{plots} argument of \code{how()}. \code{Plots()} takes many of the same arguments as \code{Within()}, the two differences being \code{strata}, a factor variable that describes the grouping of samples at the \emph{plot} level, and the absence of a \code{constant} argument. As the majority of arguments are similar between \code{Within()} and \code{Plots()}, I will not repeat the details again, and only describe the \code{strata} argument

\begin{description}
  \item[\code{strata}]
    a factor variable. \code{strata} describes the grouping of samples at the \emph{plot} level, where samples from the same \emph{plot} are take the same \emph{level} of the factor.
\end{description}

When a \emph{plot}-level design is specified, samples are never permuted between \emph{plots}, only within plots if they are permuted at all. Hence, the type of permutation \emph{within} the \emph{plots} is controlled by \code{Within()}. Note also that with \code{Plots()}, the way the individual \emph{plots} are permuted can be from any one of the four basic permutation types; \code{"none"}, \code{"free"}, \code{"series"}, and \code{"grid"}, as described above. To permute the \emph{plots} only (i.e. retain the ordering of the samples \emph{within} plots), you also need to specify \code{Within(type = "none", ...)} as the default in \code{Within()} is \code{type = "free"}. The ability to permute the plots whilst preserving the within-plot ordering is an impotant feature in testing explanatory factors at the whole-plot level in split-plot designs and in multifactorial analysis of variance \citep{canoco5manual}.

\subsubsection[Specifying blocks; the top of the permute hierarchy]{Specifying blocks; the top of the \pkg{permute} hierarchy}
In constrast to the \emph{within} and \emph{plots} levels, the \emph{blocks} level is simple to specify; all that is required is an indicator variable the same length as the data. Usually this is a factor, but \code{how()} will take anything that can be coerced to a factor via \code{as.factor()}.

It is worth repeating what the role of the block-level structure is; blocks simply restrict permutation to \emph{within}, and never between, blocks, and blocks are never permuted. This is reflected in the implementation; the \emph{split}-\emph{apply}-\code{combine} paradigm is used to split on the blocking factor, the plot- and within-level permutation design is applied separately to each block, and finally the sets of permutations for each block are recombined.

\subsection{Examples}
To do.

\section[Using permute in R functions]{Using \pkg{permute} in \proglang{R} functions}
\pkg{permute} originally started life as a set of functions contained within the \pkg{vegan} package \citep{vegan} designed to provide a replacement for the \code{permuted.index()} function. From these humble origins, I realised other users and package authors might want to make use of the code I was writing and so Jari oksanen, the maintainer of \pkg{vegan}, and I decided to spin off the code into the \pkg{permute} package. Hence from the very beginning, \pkg{permute} was intended for use both by users, to defining permutation designs, and by package authors, with which to implement permutation tests within their packages.

In the previous sections, I described the various user-facing functions that are employed to set up permutation designs and generate permutations from these. Here I will outline how package authors can use functionality in the \pkg{permute} package to implement permutation tests.

In Section~\ref{sec:simple} I showed how a permutation test function could be written using the \code{shuffle()} function and allowing the user to pass into the test function an object created with \code{how()}. As mentioned earlier, it is more efficient to generate a set of permutations via a call to \code{shuffleSet()} than to repeatedly call \code{shuffle()} and large number of times. Another advantage of using \code{shuffleSet()} is that once the set of permutations has been created, parallel processing can be used to break the set of permutations down into smaller chunks, each of which can be worked on simultaneously. As a result, package authors are encouraged to use \code{shuffleSet()} instead of the simpler \code{shuffle()}.

To illustrate how to use \pkg{permute} in \proglang{R} functions, I'll rework the permutation test I used for the \code{jackal} data earlier in Section~\ref{sec:simple}.

<<change-continuation,results=hide,echo=false>>=
options("prompt" = " ", "continue" = " ")
@
<<ptest-fun, keep.source=true>>=
pt.test <- function(x, group, nperm = 199) {
    ## mean difference function
    meanDif <- function(i, x, grp) {
        grp <- grp[i]
        mean(x[grp == "Male"]) - mean(x[grp == "Female"])
    }
    ## check x and group are of same length
    stopifnot(all.equal(length(x), length(group)))
    ## number of observations
    N <- nobs(x)
    ## generate the required set of permutations
    pset <- shuffleSet(N, nset = nperm)
    ## iterate over the set of permutations applying meanDif
    D <- apply(pset, 1, meanDif, x = x, grp = group)
    ## add on the observed mean difference
    D <- c(meanDif(seq_len(N), x, group), D)
    ## compute & return the p-value
    Ds <- sum(D >= D[1]) # how many >= to the observed diff?
    Ds / (nperm + 1)     # what proportion of perms is this (the pval)?
}
@
<<reset-continuation,results=hide,echo=false>>=
options("prompt" = "R> ", "continue" = "+  ")
@

The commented function should be reasonably self explanatory. I've altered the in-line version of the \code{meanDif()} function to take a vector of permutation indices \code{i} as the first argument, and internally the \code{grp} vector is permuted according to \code{i}. The other major change is that \code{shuffleSet()} is used to generate a set of permutations, which are then iterated over using \code{apply()}.

In use we see
<<run-ptest>>=
set.seed(42) ## same seed as earlier
pval <- with(jackal, pt.test(Length, Sex, nperm = 4999))
pval
@
which nicely agrees with the test we did earlier by hand.

Iterating over a set of permutation indices also means that adding parallel processing of the permutations requires only trivial changes to the main function code. As an illustration, below I show a parallel version of \code{pt.test()}

<<change-continuation,results=hide,echo=false>>=
options("prompt" = " ", "continue" = " ")
@
<<parallel-ptest-fun, keep.source=true>>=
ppt.test <- function(x, group, nperm = 199, cores = 2) {
    ## mean difference function
    meanDif <- function(i, .x, .grp) {
        .grp <- .grp[i]
        mean(.x[.grp == "Male"]) - mean(.x[.grp == "Female"])
    }
    ## check x and group are of same length
    stopifnot(all.equal(length(x), length(group)))
    ## number of observations
    N <- nobs(x)
    ## generate the required set of permutations
    pset <- shuffleSet(N, nset = nperm)
    if (cores > 1) {
        ## initiate a cluster
        cl <- makeCluster(cores)
        on.exit(stopCluster(cl = cl))
        ## iterate over the set of permutations applying meanDif
        D <- parRapply(cl, pset, meanDif, .x = x, .grp = group)
    } else {
        D <- apply(pset, 1, meanDif, .x = x, .grp = group)
    }
    ## add on the observed mean difference
    D <- c(meanDif(seq_len(N), x, group), D)
    ## compute & return the p-value
    Ds <- sum(D >= D[1]) # how many >= to the observed diff?
    Ds / (nperm + 1)     # what proportion of perms is this (the pval)?
}
@
<<reset-continuation,results=hide,echo=false>>=
options("prompt" = "R> ", "continue" = "+  ")
@
In use we observe
<<run-pptest>>=
require("parallel")
set.seed(42)
system.time(ppval <- ppt.test(jackal$Length, jackal$Sex, nperm = 9999,
                              cores = 2))
ppval
@
In this case there is little to be gained by splitting the computations over two CPU cores
<<run-pptest2>>=
set.seed(42)
system.time(ppval2 <- ppt.test(jackal$Length, jackal$Sex, nperm = 9999,
                               cores = 1))
ppval2
@
The cost of setting up and managing the parallel processes, and recombining the separate sets of results almost negates the gain in running the permutations in parallel. Here, the computations involved in \code{meanDif()} are trivial and we would expect greater efficiencies from running the permutations in parallel for more complex analyses.

\subsection{Accesing and changing permutation designs}
Th object created by \code{how()} is a relatively simple list containing the settings for the specified permutation design. As such one could use the standard subsetting and replacement functions in base \proglang{R} to alter components of the list. This is not recommended, however, as the internal structure of the list returned by \code{how()} may change in a later version of \pkg{permute}. Furthermore, to facilitate the use of \code{update()} at the user-level to alter the permutation design in a user-friendly way, the matched \code{how()} call is stored within the list along with the matched calls for any \code{Within()} or \code{Plots()} components. These matched calls need to be updated too if the list describing the permutation design is altered. To allow function writers to access and alter permutation designs, \pkg{permute} provides a series of extractor and replacement functions that have the forms \code{getFoo()} and \code{setFoo<-()}, respectively,where \code{Foo} is replaced by a particular component to be extracted or replaced.

The \code{getFoo()} functions provided by \pkg{permute} are

\begin{description}
  \item[\code{getWithin()}, \code{getPlots()}, \code{getBlocks()}]
    these extract the details of the \emph{within}-, \emph{plots}-, and \emph{blocks}-level components of the design. Given the current design (as of \pkg{permute} version 0.8-0), the first two of these return lists with classes \code{"Within"} and \code{"Plots"}, respectively, whilst \code{getBlocks()} returns the block-level factor.
\item[\code{getStrata()}]
  returns the factor describing the grouping of samples at the \emph{plots} or \emph{blocks} levels, as determined by the value of argument \code{which}.
  \item[\code{getType()}]
    returns the type of permutation of samples at the \emph{within} or \emph{plots} levels, as determined by the value of argument \code{which}.
  \item[\code{getMirror()}]
    returns a logical, indicating whether permutations are drawn from the mirror image of the observed ordering at the \emph{within} or \emph{plots} levels, as determined by the value of argument \code{which}.
  \item[\code{getConstant()}]
    returns a logical, indicating whether the same permutation of samples, or a different permutation, is used within each of the plots.
  \item[\code{getRow()}, \code{getCol()}, \code{getDim()}]
    return dimensions of the spatial grid of samples at the \emph{plots} or \emph{blocks} levels, as determined by the value of argument \code{which}.
  \item[\code{getNperm()}, \code{getMaxperm()}, \code{getMinperm()}]
    return numerics for the stored number of permutations requested plus two triggers used when checking permutation designs via \code{check()}.
  \item[\code{getComplete()}]
    returns a logical, indicating whether complete enumeration of the set of permutations was requested.
  \item[\code{getMake()}]
    returns a logical, indicating whether the entire set of permutations should be produced or not.
  \item[\code{getObserved()}]
    returns a logical, which indicates whether the observed permutation (ordering of samples) is included in the entire set of permutation generated by \code{allPerms()}.
  \item[\code{getAllperms()}]
    extracts the complete set of permutations if present. Returns \code{NULL} if the set has not been generated.
\end{description}

The available \code{setFoo()<-} functions are

\begin{description}
  \item[\code{setPlots<-()}, \code{setWithin<-()};]
    replaces the details of the \emph{within}-, and \emph{plots}-, components of the design. The replacement object must be of class \code{"Plots"} or \code{"Within"}, respectively, and hence is most usefully used in combination with the \code{Plots()} or \code{Within()} constructor functions.
  \item[\code{setBlocks<-()};]
    replaces the factor that partitions the observations into blocks. \code{value} can be any \proglang{R} object that can be coerced to a factor vector via \code{as.factor()}.
  \item[\code{setStrata<-()};]
    replaces either the \code{blocks} or \code{strata} components of the design, depending on what class of object \code{setStrata<-()} is applied to. When used on an object of class \code{"how"}, \code{setStrata<-()} replaces the \code{blocks} component of that object. When used on an object of class \code{"Plots"}, \code{setStrata<-()} replaces the \code{strata} component of that object. In both cases a factor variable is required and the replacement object will be coerced to a factor via \code{as.factor()} if possible.
  \item[\code{setType<-()};]
    replaces the \code{type} component of an object of class \code{"Plots"} or \code{"Within"} with a character vector of length one. Must be one of the available types: \code{"none"}, \code{"free"}, \code{"series"}, or \code{"grid"}.
  \item[\code{setMirror<-()};]
    replaces the \code{mirror} component of an object of class \code{"Plots"} or \code{"Within"} with a logical vector of length one.
  \item[\code{setConstant<-()};]
    replaces the \code{constant} component of an object of class \code{"Within"} with a logical vector of length one.
  \item[\code{setRow<-()}, \code{setCol<-()}, \code{setDim<-()};]
    replace one or both of the spatial grid dimensions of an object of class \code{"Plots"} or \code{"Within"} with am integer vector of length one, or, in the case of \code{setDim<-()}, of length 2.
  \item[\code{setNperm<-()}, \code{setMinperm<-()}, \code{setMaxperm<-()};]
    update the stored values for the requested number of permutations and the minimum and maximum permutation thresholds that control whether the entire set of permutations is generated instead of \code{nperm} permutations.
  \item[\code{setAllperms<-()};]
    assigns a matrix of permutation indices to the \code{all.perms} component of the design list object.
  \item[\code{setComplete<-()};]
    updates the status of the \code{complete} setting. Takes a logical vector of length 1 or any object coercible to such.
  \item[\code{setMake<-()};]
    sets the indicator controlling whether the entrie set of permutations is generated during checking of the design via \code{check()}. Takes a logical vector of length 1 or any object coercible to such.
  \item[\code{setObserved<-()};]
    updates the indicator of whether the observed ordering is included in the set of all permutations should they be generated. Takes a logical vector of length 1 or any object coercible to such.
\end{description}

\subsubsection{Examples}
I illustrate the behaviour of the \code{getFoo()} and \code{setFoo<-()} functions through a couple of simple examples. Firstly, generate a design object
<<get-set-eg0>>=
hh <- how()
@
This design is one of complete randomization, so all of the settings in the object take their default values. The default number of permutations is currently \Sexpr{getNperm(hh)}, and can be extracted using \code{getNperm()}
<<get-set-eg1>>=
getNperm(hh)
@
The corresponding replacement function can be use to alter the number of permutations after the design has been generated. To illustrate a finer point of the behaviour of these replacement functions, compare the matched call stored in \code{hh} before and after the number of permutations is changed
<<<get-set-eg2>>=
getCall(hh)
setNperm(hh) <- 999
getNperm(hh)
getCall(hh)
@
Note how the \code{call} component has been altered to include the argument pair \code{nperm = 999}, hence if this call were evaluated, the resulting object would be a copy of \code{hh}.

As a more complex example, consider the following design consisting of 5 blocks, each containing 2 plots of 5 samples each. Hence there are a total of 10 plots. Both the plots and within-plot sample are time series. This design can be created using
<<get-set-eg3>>=
hh <- how(within = Within(type = "series"),
          plots = Plots(type = "series", strata = gl(10, 5)),
          blocks = gl(5, 10))
@

To alter the design at the plot or within-plot levels, it is convenient to extract the relevant component using \code{getPlots()} or \code{getWithin()}, update the extracted object, and finally use the updated object to update \code{hh}. This process is illustrated below in order to change the plot-level permutation type to \code{"free"}
<<get-set-eg4>>=
pl <- getPlots(hh)
setType(pl) <- "free"
setPlots(hh) <- pl
@
We can confirm this has been changed by extracting the permutation type for the plot level
<<get-set-eg5>>=
getType(hh, which = "plots")
@
Notice too how the call has been expanded from \code{gl(10, 5)} to an integer vector. This expansion is to avoid the obvious problem of locating the objects referred to in the call should the call be re-evaluated later.
<<get-set-eg6>>=
getCall(getPlots(hh))
@

At the top level, a user can update the design using \code{update()}. Hence the equivalent of the above update is (this time resetting the original type; \code{type = "series"})
<<get-set-eg7>>=
hh <- update(hh, plots = update(getPlots(hh), type = "series"))
getType(hh, which = "plots")
@
However, this approach is not assured of working within a function because we do not guarantee that components of the call used to create \code{hh} can be found from the execution frame where \code{update()} is called. To be safe, always use the \code{setFoo<-()} replacement functions to update design objects from within your functions.

\section*{Computational details}
This vignette was built within the following environment:
<<seesionInfo, results=tex, echo=false>>=
toLatex(sessionInfo(), locale = FALSE)
@
\bibliography{permute}
\end{document}
