%\VignetteIndexEntry{sjemea}
%\VignetteKeywords{MEA}
%\VignettePackage{sjemea}
%\VignetteEngine{knitr::knitr}
\documentclass{article}
\usepackage{mathpazo}
\renewcommand{\sfdefault}{lmss}
\renewcommand{\ttdefault}{lmtt}
\usepackage[T1]{fontenc}
\usepackage[a4paper,left=2cm,right=4cm,top=2cm,bottom=2cm]{geometry}
\usepackage{setspace}
\usepackage{listings}
\usepackage{verbatim}

\usepackage{xspace,amsmath}
\newcommand{\um}{\ensuremath{\mu \text{m}}\xspace}
\usepackage{url}
\usepackage[authoryear]{natbib}
\newcommand{\dynamic}{(Dynamic)}
\newcommand{\static}{(Static)}
\newcommand{\hdfgroup}[1]{\texttt{#1}}
%% Place all figures at end of paper?
%%\usepackage[noheads,nomarkers]{endfloat}

\begin{document}

\onehalfspacing
\title{An introduction to the sjemea package}

\author{S. J. Eglen}
\date{\today}

\maketitle


\section*{Installation}
To install this package, and then view this introductory vignette, do:

<<install-sjemea,eval=FALSE,echo=TRUE>>=
install.packages(c("sjemea"), type="source",
                 contriburl="http://damtp.cam.ac.uk/user/eglen/r/")
vignette('sjemea-intro', package='sjemea')
@

\section*{Setup}
This file is a vignette, written in R, as a reproducible research
document.

<<setup,message=FALSE>>=
require(sjemea)
require(knitr)
opts_chunk$set(cache=TRUE)
opts_chunk$set(dev='pdf')
@

\section*{Introduction}

This is a short introduction to the abilities of the sjemea package
for analysis of multielectrode array data.  It is not a comprehensive
guide, but simply gives examples of what can be done with the package.
The package contains some example data sets which are used here to
demonstrate various routines.

\subsection*{Help pages}
A list of help pages associated with the package is given by
\verb+help(package='sjemea')+ command:
<<help,echo=FALSE>>=
cat(format(help(package='sjemea')), sep = '\n') #need to grab output.
@


\section*{Fourplot}

The fourplot gives a quick overview for a data file, showing (a) the
positions of recorded neurons (b) the array-wide firing rate,
estimated by default every 1 s (c) the spike raster for the entire
recording (d) the correlation index plot \citep{Wong1993}.

<<>>=
data.file <- system.file("examples", "P9_CTRL_MY1_1A.txt",
                         package = "sjemea")
s <- jay.read.spikes( data.file)
fourplot(s)
@

A convention of the program is that all data referring to a recording
is stored within an object of class \texttt{mm.s}, which is actually a
list.  So, when new data/results are collected for a recording, I tend
to add the new information into that object (e.g. see how burst
analysis results are stored).

\section*{Burst analysis}

We have several routines implemented for burst analysis:

\begin{enumerate}
\item Max Interval method, as described by Neuroexplorer \citep{neuroexplorer}
\item Poisson surprise \citep{Legendy1985}
\item Rank suprise \citep{Gourevitch2007}
\end{enumerate}

Out of these, the most tested has been the MaxInterval method.
<<bursts>>=
data.file <- system.file("examples", "TC89_DIV15_A.nexTimestamps",
package = "sjemea")
s <- sanger.read.spikes(data.file)
s$allb <- spikes.to.bursts.surprise(s)
@

So, for example, for electrode 2, we see the following bursts (just
taking the head as there are many of them.  We can also easily plot
the number of bursts on each electrode.

<<show-burst-info>>=
head(s$allb[[2]])
nbursts <- sapply(s$allb, nrow)
plot(nbursts, xlab='Electrode number', ylab='Number of bursts',
     bty='n', las=1)
@


Once bursts are computed the resulting burst information can be
visualized on a raster assuming that the burst information is stored
in the \verb+s$allb+ component of the object.  Here we ask to see the
burst information for twenty seconds of data from just the first five trains.

<<burst-raster>>=
plot(s, beg=100, end=200, show.bursts=TRUE, whichcells=1:5)
@

Bursts are indicated with a red horizontal line, and the blue number
indicates the number of spikes in the burst.


Note: a Hidden-Markov Model (HMM) for burst analysis in R \citep{Tokdar2010}
is available in the following package:
\url{http://www.stat.duke.edu/~st118/Software/}.

can be used within this package, but in principle (computation time
aside as I expect an HMM to be slow) there should be no issue.  There
is also a generic ``bursts'' package:
\url{http://cran.r-project.org/web/packages/bursts/bursts.pdf}.


\subsection*{Log interspike intervals}

To help determine burst parameters, it is often helpful to look at a
histogram of the interspike interval, plotted on a log scale.  

TODO: add this code from
\url{~/proj/sangermea/pdn/logisi_condtable.R}.

\section*{Network spikes}

Network spikes are periodic elevations in activity across the whole
array \citep{Eytan2006}.  The following example shows how they are computed.
In the resulting graph, the population ``firing rate'' (the number of
active electrodes here) is shown on the y axis, time (in seconds) on
the x axis.  The horizontal red line is a threshold set for the
minimum number of active electrodes to determine a ``network spike''.
The blue dots are the peak of each network spikes.

The mean network spike is also shown, averaged across all the network
spikes in the recording.

<<>>=
example(compute.ns)
@

\section*{Correlation index}

The correlation index plot was devised by \citet{Wong1993} as a method to
estimate how correlation between any pair of neurons on the array
depends (if at all) upon the distance separating the pair.  For
retinal waves, the correlation index usually has an
exponentially-decaying profile.  For other recordings,
(e.g. hippocampal cultures), the profile tends to be flatter.

<<>>=
jay.data.file <- system.file("examples", "P9_CTRL_MY1_1A.txt",
                         package = "sjemea")
jay.s <- jay.read.spikes( jay.data.file)
plot.corr.index(jay.s)

@

\section*{Batch analysis}

As this code is all written in the R progamming language, it scales
itself well to the notion that the analysis can be automated to run
over many data files in batch, rather than running one at a time.  To
this end, for the Genes to Cognition project, we devised a system
where data files were expected in one directory, and output files
would be written to a particular directory.  See the R function
\texttt{sanger.init} and in particular the variables
\texttt{mea.data.dir, mea.table.dir, mea.op.dir}.  A spreadsheet
containing the files to be analysed is passed to a script that
analyses each row of the spreadsheet independently.  This system was
used to analyse several hundreds of files simultaneously.


\section*{Data readers}
\label{sec:input}

The examples above have used example data stored within the package to
read in data.  Here are the names of some (not all) other readsers
that are available in the package.
 
\begin{description}
\item[ncl.read.spikes]  -- Multi-Channel system MCS output of spike
  times and cut outs.  (Named ``ncl'', as the data came from Newcastle.)
\item[jay.read.spikes] -- Used for Demas et al. (2003)  (Named ``jay''
  as the data was recorded by Jay Demas.)
\item[h5.read.spikes] -- HDF5 format, as described in the current
  ``waverepo'' project.
\item[sql.read.spikes] -- Prototype using SQL to store data.
\item[sanger.read.spikes] -- Multi-channel system from the Sanger
  Genes to Cognition project.
\item[nex.read.spikes] -- Neuroexplorer timestamp files can be read
  in.  I have adapted the matlab code from
  \url{http://www.neuroexplorer.com/code.html} to work in R.

\end{description}

\subsection*{Handling new data}

Although these old readers still work, where possible, we should use
the HDF5 format for data storage.  The preferred approach (as taken
with the ``waverepo'' project), is to convert data as soon as possible
into HDF5.

Some older routines exist for reading in binary format
(e.g. \texttt{mm.read.spikes}) but these are quite old now and
cumbersome to maintain.  Whenever possible, data collected from
laboratories should either be text or HDF5.

\subsection*{Multi-well arrays}

Through a collaboration with Dr Tim Shafer's group at EPA, we are
developing code for handling multi-well data.  (For example, so that
each well can be analysed independently in an efficient manner.)  This
introduces an extra layer of abstraction into the geometry of the
array, in that an electrode is part of a well, and there are many
wells on one array (or ``plate'').


\subsection*{Other features}

Interactive facilities for viewing spike times were in earlier
versions of the code, but Tk() widgets conflicted with the use of
parallel() code.  I think this has now been fixed, so we might be able to
return to adding interactive features.

\subsection*{History}

This package was originally written for research that was published in
\citep{Demas2003}.  Since then it has been used by several other
research groups.

\subsection*{Acknowledgements}
This work has been financially supported by grants from the Wellcome
Trust, BBSRC and EPSRC.  Zhengzheng Zhang provided the \texttt{logisi}
function.  I thank Paul Charlesworth for many discussions about
electrophysiological analysis.



\bibliographystyle{jneurosci}
\bibliography{sjemea}

\subsection*{Compiling this document}

<<eval=FALSE,include=TRUE>>=
require(knitr); knit2pdf('sjemea-intro.Rnw')
@




\end{document}
