
\documentclass{article}
\usepackage{amsmath} %Never write a paper without using amsmath for its many new commands
\usepackage{amssymb} %Some extra symbols
\usepackage{makeidx} %If you want to generate an index, automatically
\usepackage{graphicx} %If you want to include postscript graphics
%%%  \usepackage{mystyle} 
%Create your own file, mystyle.sty where you put all your own \newcommand statements
%%%
%%%
\usepackage{amscd}

\usepackage{Sweave}


%%\VignetteIndexEntry{Examples from RSEIS}

%%% \usepackage{Sweave}

\begin{document}

%%%\renewcommand\floatpagefraction{.9}
%%%\renewcommand\topfraction{.9}
%%%\renewcommand\bottomfraction{.9}
%%%\renewcommand\textfraction{.1}
%%%\setcounter{totalnumber}{50}
%%%\setcounter{topnumber}{50}
%%%\setcounter{bottomnumber}{50}

\setkeys{Gin}{width=0.9\textwidth}



\numberwithin{equation}{section}

%%%   \SweaveOpts{prefix.string=rseis}
\SweaveOpts{prefix=TRUE,prefix.string=rseis,include=TRUE}


\author{Jonathan M. Lees\\
University of North Carolina, Chapel Hill\\
Department of Geological Sciences\\
CB \#3315, Mitchell Hall\\
Chapel Hill, NC  27599-3315\\
email: jonathan.lees@unc.edu\\
ph: (919) 962-0695
}
%%  \address{University of North Carolina, Chapel Hill}
%% \contact{Jonathan M. Lees}
%% \contactaddress{Department of Geological Sciences, CB #3315, Mitchell Hall, Chapel Hill, NC  27599-3315}
%% \contactemail{jonathan.lees@unc.edu}
%% \contactphone{(919) 962-0695}
\title{RSEIS: Seismic Time Series Analysis in R}
\date{\today}

\maketitle


\begin{abstract}
I present several new packages for analyzing seismic data for time
series analysis and earthquake focal mechanisms.  The packages
consists of modules that 1) read in seismic waveform data in various
common exchange formats, 2) display data as either event or continuous
recordings and 3) performs numerous standard analyses applied to
earthquake and volcano monitoring.  RSEIS is designed as a research
tool aimed at investigators who need to quickly assess large amounts
of time-series as they are related to the spatial distribution of
geologic structure and wave propagation.  In addition to time series
analysis, a spatial mapping program is included that ties waveforms
and radiation patterns to geographical data-base and mapping programs.
\end{abstract}


\section{Waveform Analysis}

The waveform module of RSEIS reads in seismic data in SEGY, SAC, AH,
UW and various ASCII formats.  The core of these modules are a set of
C programs that pass waveforms back to R and wrappers that create
lists of seismograms.  RSEIS was written primarily for use with
continuous data, so the R code is able to sort a large database
consisting of continuous data from several stations and numerous
components.  Each component of the waveform database may have a
different sample rate and may require very different handling in terms
of instrument de-convolution.  Time-windows provided by the user are
used to select off parts of the continuous data and rectify timing so
that all traces represent identical time slots.  Seismic data (binary
or ASCII format) are read into R and stored in structures that provide
a platform for object oriented manipulation of complex information
regarding earth dynamics.  In my case, I use this package to
investigate exploding volcanoes in Ecuador, Guatemala, Kamchatka and
Italy.

An initial, interactive display of the seismic records is presented to
the user and a large array of useful options are available for further
processing by buttons that surround the main display but are on the
same graphics device.  Some of the routines employed in the RSEIS
package are drawn from packages already available on the R
distribution, for example wavelet transforms - although these have
been modified to some extent to accommodate specific concerns of
seismologists. Other modules, like those dealing with focal mechanisms
and radiation patterns are original and will prove useful for
investigators searching for patterns of stress distribution in fault
regions.  


\section{Getting started}

Start by downloading packages and installing locally in the
machine being used.
The packages required by RSEIS include RPMG, and Rwave, 
and RFOC if focal mechanisms are going to be inspected.

<<fig=FALSE, echo=TRUE, results=hide>>=

library(RSEIS)
library(RPMG)

options(continue = " ")

@ 

\subsection{Example: Reventador Volcano Explosion }


There several data set that accompany RSEIS,
and these can be loaded with simple calls to data().
For example,
<<fig=FALSE, echo=TRUE, results=hide>>=
data(KH)
names(KH)

@ 
loads a structure that includes wave forms and other important
meta-data about the earthquake.  To see a view of this data
we call the main program and display the earthquake records as they are stored
in memory,

<<fig=FALSE, echo=FALSE, results=hide>>=

pdark=c("tomato3","royalblue","forestgreen","blueviolet","tan3",
"lightseagreen","deeppink","cyan3",
"bisque3","magenta1","lightsalmon3","darkcyan", "gold4" ,      
"darkorange1", "goldenrod4" , "seagreen3" ,  "lightpink3")

palette(pdark )


@ 

<<fig=TRUE, echo=TRUE, results=hide>>=


STDLAB = c("DONE",  "zoom in", "zoom out", "refresh", "restore",
 "XTR", "SPEC", "SGRAM" ,"WLET", "FILT",  "Pinfo")


swig(KH, SHOWONLY=FALSE, WIN = c(90, 200) , STDLAB=STDLAB)

@ 
In this example we are showing the vertical component of an explosion 
of Reventador Volcano.  The buttons at the top
are defaults chosen from a large selection of 
buttons designed to be useful for analyzing seismic data.
To zoom in on the trace, click twice on the trace with the left mouse button,
and then terminate by clicking the middle mouse.
(Clicking with the middle mouse with now left mouse clicks terminates the interactive session).
When your are finished with RSEIS windows click the ``Done'' 
button to close the window.  Avoid using the small
``x'' in the corner of the window to terminate because
R does not know you have finished yet.

You can view spectra of the signal (SPEC) , spectrograms (SGRAM) 
and wavelet transforms (WLET). To illustrate,
left click on this trace around t=1200 and t=2000, which 
windows the harmonic tremor part of this explosion.
Click middle mouse to zoom in, or
select one of the buttons at
the top to analyze the time series in the (selected) sub-window.
Choose  \emph{WLET} to show the wavelet transform of
the harmonic tremor and important time variations of the
volcano during eruption.

The swig program is normally run in interactive mode.
In that case, once it is started R is waiting for
the user to select traces and buttons for
activating a variety of programs and analysis 
routines.
Selection of traces is accomplished by clicking on the traces,
one or more times depending 
on what is desired.
The program needs to know what to do with the 
selections once that process is over, 
usually by clicking on a button around the perimeter 
of the screen.  In the next example we will restrict the analysis
to just the vertical motion seismic data, at least for now.
If you expand the screen, you can re-arrange the buttons by
clicking on the refresh button.

swig is a general analysis program designed for earthquake studies.
It uses the {\emph Really Poor Man's GUI} to 
navigate between seismic traces and 
various analysis procedures.
Once the program is started it waits for the user to
select on the screen a variety of operations, determined
by the user via the button selection, STDLAB.
In the main event loop, 
the user may click on the screen with the left mouse 
button to hi-light specific traces or windows in the panel.
The right mouse click terminates the clicking sequence and
a decision is made on what to do, unless a button has been clicked.
Generally, one click selects a specific trace,
two clicks specify a trace and window in that trace.
If the clicking is terminated immediately, 
before a left mouse is clicked, the program stops and returns
NULL.
If it terminates after 1 click, a refresh screen 
command is produced. If there are two or more clicks,
and no button is pressed, the last two clicks are
used to zoom in the window.

If a button is clicked, however, 
the program
uses the number of clicks to determine
which traces to process and what to do.
For example, if the ``PickWin'' button is selected,
a new swig is spawned where the program 
gathers all the components for that station, Usually Vertical, North and East,
although in the presence of acoustic channels they will also be displayed.
The new window is called with a new set of Buttons
set up specifically for picking the P, S and Acoustic arrivals.
Once that window is finished, focus reverts to the main 
window and the new picks are registered.
Selecting the ``SavePF'' button will save the
new picks to a file for later use.

As another example, if the user clicks twice in a trace panel,
and then selects the WLet Button, a wavelet transform
of the selected time window is calculated and 
a special new screen is exposed where the 
user is now focused until that session is finished by
clicking ``Done''.

Each Button has different properties based on the 
requirements for that process.  Some buttons 
expect more than one click to operate properly, others 
are simple buttons that control the look and feel of the 
panel. For example, the ``restore'' button
reverts the panel to its original time window.
It can be pressed any time and the 
window will redraw and resize.
Each button includes a small set of instructions
designed to accomplish a specific task.
There are many buttons currently defined, some described below, and 
there is mechanism for users to  make their own
on the fly.


\subsection{Example: Coso Geothermal Event }

<<fig=FALSE, echo=TRUE, results=hide>>=

data(GH)
numstas = length(GH$STNS)


@ 

In this example, taken from the geothermal field 
at Coso, California, there are \Sexpr{numstas} stations,
most of which have three components (Vertical, North and East),
although there are a couple of stations that are missing
some of the components.  This situation is not 
atypical of earthquake seismic data recorded in the field.
If we show only the vertical component traces,
The plot is more manageable and easier to view:
<<fig=TRUE, echo=TRUE, results=hide>>=


verts = which(GH$COMPS == "V")

STDLAB = c("DONE", "QUIT",  "NEXT","PREV",  "zoom in", "zoom out", "refresh", "restore", "SavePF", 
"PickWin", "XTR", "SPEC", "SGRAM" ,"WLET", "FILT", "Pinfo", "WINFO", "PTS", "YPIX", "WPIX")


swig(GH,  sel=verts[c(1,2,3,4,6) ] ,STDLAB =STDLAB, WIN=c(4,15),  SHOWONLY=TRUE)


@ 




We see that the stations here are 'mixed up', i.e. arriving at different times.
<<fig=TRUE, echo=TRUE, results=hide>>=

vertord = getvertsorder(GH$pickfile, GH)

swig(GH,  sel=vertord$sel[1:5] ,      STDLAB =STDLAB,  WIN=c(4, 15), SHOWONLY=FALSE)

@ 

A seismic event is usually stored as a combination
of waveform information and meta-date associated with
the phase arrivals.  Phase arrivals are
commonly called ``picks'' since and analyst 
had to pick the arrival times from a representation
of the seismic signals, either on a computer or on a paper
record.
The picks are stored in RSEIS 
in a list structure called pickfile
which is an optional  component of the name waveform structure.
The pickfile structure is a list comprising several
sub-lists with important information associated with
stations and the event (earthquake) source.
<<>>=
names(GH$pickfile)
@ 
For now we consider the most relevant 
meta-data, 
<<>>=
names(GH$pickfile$STAS)
@ 
which is a list of vectors, 
one for each meta-datum and one element
each for each station that has meta-data.
We see in this example there are a couple of picks per station,
some picks are on the vertical components and some
are on the North component or East, there
are P and S-wave phase picks.
<<>>=
data.frame(cbind(name=GH$pickfile$STAS$name, comp=GH$pickfile$STAS$comp, phase=GH$pickfile$STAS$phase, time=GH$pickfile$STAS$sec, lat=GH$pickfile$STAS$lat, lon=GH$pickfile$STAS$lon))
@ 
We also store event information:
<<>>=
names(GH$pickfile$LOC)
@ 

Using this information we can associate the 
p-pick with the waveforms, match the timing information
and plot together.
finally we add the picks to the section:
<<fig=TRUE, echo=TRUE, results=hide>>=

apx = uwpfile2ypx(GH$pickfile)
swig(GH,  sel=vertord$sel[1:5] , APIX=apx, STDLAB =STDLAB,  WIN=c(4, 15), SHOWONLY=FALSE, velfile=VELMOD1D, )


@ 

Brief documentation for buttons in the swig
program can be seen by calling the documentation function,
either for a specific button 

<<>>=
PICK.DOC('WLET')

@ 
or for 
all possible buttons.
<<>>=
PICK.DOC()

@ 


\subsection{Example: SunSpots}

One standard data set included in the R
Distribution is the 
sunspot data.  As an example of RSEIS we can read this time series in and plot it using the
same code introduced above.
<<fig=TRUE, echo=TRUE, results=hide>>=
data(sunspots)

AA = attributes(sunspots)
starttime=list(yr=AA$tsp[1], jd=1,mo=1,dom=1,hr=0,mi=0,sec=0)
ES = prep1wig(wig=sunspots, dt=1/12, sta="STA", comp="CMP", units="UNITS", starttime=starttime    )

EH=prepSEIS(ES)

STDLAB = c("DONE",  "zoom in", "zoom out", "refresh", "restore",
 "XTR", "SPEC", "SGRAM" ,"WLET", "FILT",  "Pinfo")

xx =  swig( EH, STDLAB = STDLAB,  SHOWONLY=TRUE)

@ 


<<>>=
a = list(y=EH$JSTR[[1]], dt=EH$dt[1])
 Mspec = mtapspec(a$y, a$dt, klen =1024 , MTP = list(kind = 1,
        nwin = 5, npi = 3, inorm = 0))
    f = Mspec$freq
    amp = Mspec$spec[1:length(f)]
    ma = amp
displ = ma
f1 = 0.01
f2 = 1/(2*EH$dt[1])

    flag = f >= f1 & f <= f2
plxy = "xy"

 plot(range(f[flag]),range(displ[flag]),type='n',log=plxy,axes=FALSE, xlab="Hz", ylab="Spec")
      lines(f[flag], displ[flag], col=1, lty=1)       
      axis(2, las=2)
      axis(1)
      box()
  ##     L = locator()
 ## rDUMPLOC(L)
  
L=list()
L$x=c(0.0939105803154482,0.183351679178275,0.350333785192083)
L$y=c(31166.8951116052,7536.36156151748,2370.29538151056)

abline(v=L$x, lty=2, col=grey(0.8) )
text(L$x, rep(max(range(displ[flag])), length(L$x)),  labels=round((1/L$x)), xpd=TRUE, srt=45, adj=c(0,0) )



@ 


\subsection{Example: Climate Change}

As a final example showing how RSEIS might be used for 
arbitrary time series, unrelated to 
seismic data, consider the famous 
Delta-O18 time series.  By windowing the 
time sereis and looking at the 
spectrum one can immediately see the 
Milankovitch cycles at (approximately) 100K, 41K and 20K periods.

<<fig=TRUE, echo=TRUE, results=hide>>=
data(OH)
xx =  swig( OH, sel=which(OH$COMPS == "V"), STDLAB = STDLAB,  SHOWONLY=TRUE)

@ 

<<fig=TRUE, echo=TRUE, results=hide>>=
a = list(y=OH$JSTR[[1]], dt=OH$dt[1])
 Mspec = mtapspec(a$y, a$dt, klen =1024 , MTP = list(kind = 1,
        nwin = 5, npi = 3, inorm = 0))
    f = Mspec$freq
    amp = Mspec$spec[1:length(f)]
    ma = amp
displ = ma
f1 = 0.01
f2 = 1/(2*EH$dt[1])

    flag = f >= f1 & f <= f2
plxy = "xy"

 plot(range(f[flag]),range(displ[flag]),type='n',log=plxy,axes=FALSE, xlab="Hz", ylab="Spec")
      lines(f[flag], displ[flag], col=1, lty=1)       
      axis(2, las=2)
      axis(1)
      box()
      
##   L = locator()
##   rDUMPLOC(L)

u = par("usr")
L=list()
L$x=c(0.242745864538716,0.423063797271721,0.447439169221329,0.529320129815409,0.100457805181183)
L$y=c(37.4392793655756,19.0231348719557,15.6564640841027,15.0862607475168,40.6986171075992)

abline(v=L$x, lty=2, col=grey(0.8) )
text(L$x, rep(max(range(displ[flag])), length(L$x)),  labels=round(10000*(1/L$x)), xpd=TRUE, srt=45, adj=c(0,0) )




@ 



To illustrate the effects of comparing numerous filters to 
a specific volcanic explosions event,


<<fig=TRUE, echo=TRUE, results=hide>>=
 data(KH)
     dt = KH$dt[1]


     y =  KH$JSTR[[1]]
     y = y[1:50000]
y = y-mean(y)
     x =  seq(from=0, by=dt, length=length(y))




     fl=rep(1/100, 5)
     fh=1/c(4,3,2,1, .5)

     FILT.spread(x, y, dt, fl = fl, fh = fh, sfact = 1, WIN = NULL, PLOT = TRUE, TIT = NULL, TAPER = 0.05, POSTTAPER = 0.1)


@ 




\end{document}



