\name{COn0E65N}
\alias{COn0E65N}
\alias{lat}
\alias{lon}
\title{Convert long-lat to km-km}
\description{The function returns the distance in km from 0E 65N given
  the longitude and latitude. See also \code{\link{km2lon}} and \code{\link{km2lat}}.}
\usage{COn0E65N(lon, lat)}
\arguments{
 \item{lon}{longitude}
 \item{lat}{latitude}
}
\value{list(y=latitudes distance,x= longitudes distance)}
\author{R.E. Benestad}}
\examples{
library(clim.pact)
data(oslo.t2m)
print(c(oslo.t2m$lon,oslo.t2m$lat))
#[1] 10.71667 59.95000
xy<-COn0E65N(oslo.t2m$lon,oslo.t2m$lat)
oslo.t2m$lon<-xy$x
oslo.t2m$lat<-xy$y
print(c(oslo.t2m$lon,oslo.t2m$lat))
#[1]  595.4086 -560.3004
lon<-km2lon(oslo.t2m$lon,oslo.t2m$lat,x.centre=0,y.centre=65)
lat<-km2lat(oslo.t2m$lon,oslo.t2m$lat,x.centre=0,y.centre=65)
print(c(lon,lat))
#[1] 10.71667 59.95000
}
\keyword{manip}

\eof
\name{DNMI.t2m}
\alias{DNMI.t2m}
\alias{DNMI.slp}
\alias{DNMI.sst}
\title{Gridded monthly mean climate data}
\description{Gridded monthly mean 2-meter temperature [T(2m)], sea
level pressure (SLP), and sea surface temperature (SST) analysis for the North
Atlantic region covering the period 1873 -- 1998. The actual data is
filtered though 20 EOFs (see \code{\link{EOF2field}}), and stored as eof products in order to save
space. The lines listed in the example shows how these data have been
generated (NB. old objects with the name \code{eof}, \code{xxx}, \code{climxxx}, and \code{i} 
may be overwritten).}
\usage{data(DNMI.t2m)
       data(DNMI.slp)
       data(DNMI.sst)}
\format{The data is a 'field' object (see \code{\link{retrieve.nc}}).}
\examples{
\dontrun{
library(clim.pact)
t2m <- retrieve.nc("~/data/analysis/DNMI_t2m.nc")
eof <- EOF(t2m)
save(file="clim.pact/data/eof_DNMI_t2m.Rdata",eof)
t2m.eof <- EOF2field(eof)

# Check if the EOF reconstruction reproduces the original field:
newFig()
plotField(t2m,lat=60,lon=10)
plotField(t2m.eof,lat=60,lon=10,add=TRUE,lty=2,col="red")  # Very similar time series

newFig()
mapField(t2m.eof)
mapField(t2m,add=TRUE,col="red",lty=2,lwd=1)  # Very similar spatial pattern/contours

sst <- retrieve.nc("~/data/analysis/DNMI_sst.nc")
eof <- EOF(sst)
save(file="clim.pact/data/eof_DNMI_sst.Rdata",eof)

slp <- retrieve.nc("~/data/analysis/DNMI_slp.nc")
eof <- EOF(slp)
save(file="clim.pact/data/eof_DNMI_slp.Rdata",eof)
}
}
\source{The data is also avaialble from \url{http://noserc.met.no}.}
\references{
Benestad, R.E. and Melsom, A. (2002) Is there a link between the
unusually wet autumns autumns in southeastern Norway and SST
anomalies?, Climate Research Vol 23, 67-79.
\\
Melsom E. and Benestad, R.E. :  Is there a link between the unusually
wet autumns in southeastern Norway and SST anomalies?  PDF-version available
on-line from \url{http://www.dams.dk/nmm2002/Melsom\%20and\%20Benestad.pdf}
\\
Benestad, R.E.: Analysis of gridded sea level pressure and 2-meter temperature for 1873-1998 based on UEA and NCEP re-analysis II (RegClim), DNMI KLIMA Report 03/00
  PDF-version available on-line from
  \url{http://noserc.met.no/DS/klima0300.html}. For SST, see
  \url{http://noserc.met.no/DS/dnmisst.html}. The analysis of the SST
  was the same as the T(2m) and SLP.}
\keyword{datasets}

\eof
\name{DS}
\alias{DS}
\title{Downscaling of monthly or daily means}
\description{Identifies statistical relationships between large-scale
  spatial climate patterns and local climate variations for monthly and
  daily data series. Calibrates a linear regression model using
  step-wise screening and common EOFs (\code{\link{EOF}}) as basis
  functions. Evaluates the statistical relationship. Predicts local
  climate parameter from predictor fields. Works with ordinary EOFs,
  common EOFs (\code{\link{catFields}}) and mixed-common EOFs
  (\code{\link{mixFields}}).
  The rationale for using mixed-common EOFs is that the coupled
  structures described by the mixed-field EOFs may have a more physical
  meaning than EOFs of single fields [Benestad et al. (2002),
  "Empirically downscaled temperature scenarios for Svalbard",
  \emph{Atm. Sci. Lett.}, doi.10.1006/asle.2002.0051].

  The downscaling analysis returns a time series representing the local
  climate, patterns of large-scale anomalies associated with this,
  ANOVA, and analysis of residuals. Care must be taken when using this
  routine to infer local scenarios: check the R2 and p-values to check
  wether the calibration yielded an appropriate model. It is also
  important to examine the spatial structures of the large-scale
  anomalies assocaiated with the variations in the local climate: do
  these patterns make physical sense? Experiment with both single and
  mixed fields. It is also a good idea to check
  whether there are any structure in the residuals: if so, then a linear
  model for the relationship between the large and small-scale
  structures may not be appropriate. It is furthermore important to
  experiment with predictors covering different regions [ref: Benestad
  (2001), "A comparison between two empirical downscaling strategies",
  \emph{Int. J. Climatology}, \bold{vol 21}, Issue 13, pp.1645--1668. DOI
  10.1002/joc.703]. There is a cautionary tale for how the results can
  be misleading if the predictor domain in not appropriate: domain for
  northern Europe used for sites in Greenland [ref: Benestad (2002),
  "Empirically downscaled temperature scenarios for northern Europe
  based on a multi-model ensemble", \emph{Climate Research}, \bold{vol
  21 (2)}, pp.105--125. \url{http://www.int-res.com/abstracts/cr/v21/n2/index.html}]

  The function \code{ds()} is a generic routine which in principle works for
  when there is any real statistical relationship between the predictor
  and predictand. The predictand is therefore not limited to a climate
  variable, but may also be any quantity affected by the regional
  climate. \emph{It is important to stress that the downscaling model
  must reflect a well-understood (physical) relationship.} 

  The trend-estimation uses regression to fit a 5th-order polynomial (in
  time) to fit the observed time series. The rate-of-change is estimated
  by taking the time-derivative of this equation. If \deqn{y= c_0 + c_1
  x + c_2 x^2 + c_3 x^3 + c_4 x^4 + c_5 x^5,}{y= c0 + c1 x + c2 x^2 + c3
  x^3 + c4 x^4 + c5 x^5,} where x is the time, then the rate-of-change
is: \deqn{y= c_1 + 2 c_2 x + 3 c_3 x^2 +  4 c_4 x^3 + 5 c_5 x^4.}{y= c1
  + 2 c2 x + 3 c3 x^2 + 4 c4 x^3 + 5 c5 x^5.} [ref: Benestad
  (2002), What can present climate models tell us about climate
  change?, \emph{Climatic Change}, accepted.] 
  
  The routine uses a step-wise regression (step) using the leading
  EOFs. The calibration is by default carried out on de-trended data
  [ref: Benestad (2001), "The cause of warming over Norway in the
  ECHAM4/OPYC3 GHG integration", \emph{Int. J. Clim.}, 15 March,
  \bold{vol 21}, p.371-387.].

  The downscaled scenario is saved in a text file in the output
  directory (default: 'output').

  The course notes from Environmental statistics for climate researchers
  \url{http://www.gfi.uib.no/~nilsg/kurs/notes/course.html} is a useful
  reference to statistical modelling and regression.

  DS provides the basis for an 'objective' downscaling though \code{\link{objDS}}.
}
\usage{DS(dat,preds,mon=NULL,direc="output/",cal.id=NULL,
              ldetrnd=TRUE,i.eofs=seq(1,8,by=1),ex.tag="",
              method="lm",plot=TRUE,leps=FALSE,param="t2m",
              plot.res=FALSE,plot.rate=FALSE,xtr.args="",
              swsm="step",predm="predict",lsave=FALSE,rmac=TRUE,
               silent=FALSE)}

\arguments{
    \item{dat}{ A climate.station object (\code{\link{station.obj}} or 
        \code{\link{station.obj.dm}}). 
        [e.g. from \code{getnacd}, \code{getnordklim} or \code{station.obj}].}
    \item{preds}{ The predictor \code{\link{EOF}}.}
    \item{mon}{ month or season to downscale, this is automatically 
        changes if predictor only contains a different
	month (this is normally a redundant feature).}
    \item{direc}{ name of directory inwhich the output is dumped
          (e.g. figures, tables).}
    \item{cal.id}{ID tag used for calibration. By default use the 
	first field (\code{\link{catFields}}) for calibration.}
    \item{ldetrnd}{ F for no detrending; T for removing linear trends
	before model calibration.}
    \item{i.eofs}{ select which EOFs to include in the setp-wise screening.}
    \item{ex.tag}{Extra labelling tag for file names for experiments.}
    \item{method}{Sets the method to use for regression. Method is set
      to "lm" by default, but "anm" allows the incorporation of an
      analog model, see \code{\link[anm]{anm}}. "anm.weight" weights the
    principal components according to the eigenvalues, whereas "anm"
    uses unweighted series.}
    \item{plot}{'TRUE' produces figures.}
    \item{leps}{'TRUE' produces EPS figures (files).}
    \item{param}{Name of parameter (for plot labels).}
    \item{plot.res}{'TRUE' shows statistics for residuals.}
    \item{plot.rate}{'TRUE' shows analysis of rate-of-change.}
    \item{xtr.args}{Extra/additional arguments in the formula.}
    \item{swsm}{Step-wise screening method, default=='step'; 'none'
      skips stepwise sceeening.}
    \item{predm}{Prediction method, default is "predict"}.
    \item{lsave}{TRUE -> saves the result on disc}.
    \item{rmac}{TRUE -> subtracts (removes) the annual cycle in station
      data.}
    \item{silent}{TRUE -> no output to screen.}.
}

\value{A 'ds' object -  a list of following elements:
  \tabular{rl}{
    X.1 .. X.n \tab 1..nth predictor pattern for n fields
    (\link{mixFields}). \cr
    lon.1 .. \tab Longitude coordinate of spatial fields (a vector). \cr
    lat.1 .. \tab Latitude coordinate of spatial fields (a vector). \cr
    n.fld \tab Number of fields (different types of predictors,
    \link{mixFields}). \cr
    unit \tab Unit of quantity in station series. \cr
    pred.name \tab Name of predictor. \cr
    lon.loc \tab Longitude of predictand location. \cr
    lat.loc \tab Latitude of predictand location  \cr
    yy.gcm \tab Years corresponding to scenario (GCM). \cr
    mm.gcm \tab Months corresponding to scenario (GCM). \cr
    dd.gcm \tab Days corresponding to scenario (GCM). \cr
    yy.cal \tab Years corresponding to observation (Calibration). \cr
    mm.cal \tab Months corresponding to observation (Calibration). \cr
    dd.cal \tab Days corresponding to observation (Calibration). \cr
    yy.o \tab Years corresponding to station series (obs.). \cr
    mm.o \tab Months corresponding to station series (obs.). \cr
    dd.o \tab Days corresponding to station series (obs.). \cr
    rate.ds \tab Estimated linear rate of change of downscaled scenario. \cr
    rate.err \tab Error estimate for rate.ds. \cr
    gcm.trnd.p \tab P-value of linear trend in downscaled scenario.\cr
    fit.p \tab ANOVA p-value for fit between large-scale and small-scale \cr
          \tab variability(from regression analysis). \cr
    fit.r2 \tab ANOVA R2 for fit between large-scale and small-scale \cr
           \tab variability (from regression analysis). \cr
    pre.gcm \tab The downscaled scenario (a vector). \cr
    pre.y \tab The downscaled results using the calibration data. \cr
    location \tab Nsme of location of predictor. \cr
    gcm.stat \tab ANOVA of linear trend fit to scrnario. \cr
    month \tab Month of study (0-> all months).\cr
    v.name \tab Name of downscaled element. \cr
    region \tab Region used for downscaling. \cr 
    pre.fit \tab Linear fit to prediction (downscaled scenario) (a vector). \cr
    pre.p.fit \tab Polynomial fit to the downscaled scenario.\cr  
    tr.est.p.fit \tab Rate of change derived from a fifth-order
    polynomial  \cr
    \tab trend-fit to prediction (downscaled scenario) (a vector).\cr
    id.1, id.2 \tab IDs labelling which data was used for calibration (id.1).
  }
}
\author{R.E. Benestad}}
\examples{
library(clim.pact)
data("oslo.t2m")
data("eof.mc")
a<-DS(dat=oslo.t2m,preds=eof.mc,plot=FALSE)
\dontrun{
# Example 1: for computing common EOFs and using these as a basis for DS.
slp.obs <- retrieve.nc("ncep_slp.nc",x.rng=c(-20,40),y.rng=c(50,70))
                                              # Get gridded observations/analysis from NCEP
slp.gcm <- retrieve.nc("EH4OPYC_B2_slp.nc")   # Get results from climate models
slp <- catFields(slp.obs,slp.gcm)             # combine the fields.
eof <- EOF(slp,mon=1)
obs <- getnordklim("Stockholm")
ds <- DS(preds=eof,obs)



# Example 2:
# A demonstration for the linear regression model: monthly values
library(clim.pact)

# Read the gridded netCDF data:

t2m<-retrieve.nc("DNMI_t2m.nc")

# Manipulate the data: assign one part as calibration and one part as independent data
nt<-length(t2m$tim)
t2m$id.t[1:floor(nt/2)]<-"calibrate"
t2m$id.t[ceiling(nt/2):nt]<-"independent"

# Compute EOFs
eof<-EOF(t2m,mon=1,neofs=3)
plotEOF(eof)

# Get the predictand: a local station series
obs<-getnordklim("Goeteborg",ele=101)

# Apply the downscaling
DS(preds=eof,obs)
plotStation(obs,mon=1,add=TRUE,col="darkgreen",lwd=1,lty=2)



# Example 3: A demonstration for the linear regression model: daily values
# These files are not distributed with the clim.pact package, but
# nevertheless demonstrate how the downscaling can be done with a few
# clim.pact functions.

library(clim.pact)
data(eof.dc)
list<-read.table("data/daily/station.list.good",header=TRUE)
print(list)

i<-as.numeric(readline("Which number? (1-37)"))
obs1<-read.table(paste("data/daily/",list$file.name[i],sep=""))

obs<-station.obj.dm(t2m=obs1$V5,precip=obs1$V6,yy=obs1$V4,mm=obs1$V3,dd=obs1$V2,
                    station=obs1$V1[1],location=as.character(list$location[i]),
                    lon=list$lon[i],lat=list$lat[i],alt=list$alt[i],
                    obs.name<-c("t2m","precipitation"))

plotStation(obs)
DS(preds=eof.dc,obs)



Example 4: A demonstration for the analog model: daily values

library(clim.pact)
library(anm)
source("clim.R")
data(eof.dc)
list<-read.table("data/daily/station.list.good",header=TRUE)
print(list)

i<-as.numeric(readline("Which number? (1-37)"))
obs1<-read.table(paste("data/daily/",list$file.name[i],sep=""))

obs<-station.obj.dm(t2m=obs1$V5,precip=obs1$V6,yy=obs1$V4,mm=obs1$V3,dd=obs1$V2,
                    station=obs1$V1[1],location=as.character(list$location[i]),
                    lon=list$lon[i],lat=list$lat[i],alt=list$alt[i],
                    obs.name<-c("t2m","precipitation"))

plotStation(obs)

print("Please be patient - this takes a while...")
ds-anm<-DS(preds=eof.dc,obs,method="anm.weight",swsm="none",
           predm="predict.anm",param="precip",
           lsave=FALSE,ldetrnd=FALSE)

}
}
\keyword{models}
\keyword{multivariate}
\keyword{ts}
\keyword{spatial}

\eof
\name{EOF}
\alias{eof}
\alias{EOF}
\alias{Empirical orthogonal Functions}
\alias{PCA}
\alias{principal component analysis}
\title{Empirical Orthogonal Functions (EOFs).}
\description{Computes EOFs (a type of principal component
  analysis) for combinations of data sets, typically from
  the NCEP reanalysis and corresponding data from climate models.
  Preprocessing by \code{\link{catFields}} allows for common EOF analysis
  [ref: Benestad (2001), "A comparison between two empirical downscaling
  strategies", \emph{Int. J. Climatology}, \bold{vol 21}, Issue 13,
  pp.1645-1668. DOI 10.1002/joc.703]. and  \code{\link{mixFields}} prepares for
  mixed-field EOF analysis [ref. Bretherton et al. (1992) "An
  Intercomparison of Methods for finding Coupled Patterns in Climate
  Data", \emph{J. Climate}, \bold{vol 5}, 541-560;
  Benestad et al. (2002), "Empirically downscaled temperature scenarios
  for Svalbard", \emph{Atm. Sci. Lett.}, doi.10.1006/asle.2002.0051]. 

  Uncertainty estimates are computed according to North et al. (1982),
  "Sampling Errors in the Estimation of Empirical Orthogonal Functions",
  \emph{Mon. Weather Rev.}, \bold{vol 110}, 699-706. 
  
  NB: This routine may be computer-intensive!
  The computation of the EOFs tends to take some time, especially on
  computers/PCs with little memory (less than 128Mb) and slow processors
  less than 800MHz. 

  See the course notes from Environmental statistics for climate
  researchers \url{http://www.gfi.uib.no/~nilsg/kurs/notes/course.html}
  for a discussion on EOF analysis.
}

  \usage{EOF(fields,l.wght=TRUE,lc180e=FALSE,direc="data/",
              lon=NULL,lat=NULL,l.stndrd=TRUE,las=1,
              mon=NULL,plot=TRUE,neofs=20,l.rm.ac=TRUE,lsave=TRUE,
              LINPACK=TRUE)}
\arguments{
    \item{fields}{A field object (eg from \link{retrieve.nc}).}
    \item{l.wght}{'TRUE' applies a geographical weighting.}
    \item{lc180e}{'TRUE' centers the maps on date line (180 deg E).}
    \item{direc}{Directory for the output.}
    \item{lon}{longitudinal region of interest.}
    \item{lat}{latitudinal region of interest.}
    \item{l.stndrd}{Not yet used.}
    \item{las}{Used by \link{filled.contour}, see \link{par}.}
    \item{mon}{Month (1-12) [season (1-4) for daily data] to extract.}
    \item{plot}{'TRUE' plots the results.}
    \item{neofs}{Number of leading EOFs to retain.}
    \item{l.rm.ac}{'TRUE' removes the annual cycle.}
    \item{lsave}{'TRUE' dumps the results to file.}
    \item{LINPACK}{'TRUE': svd; 'FALSE':La.svd}
}
\value{File containing an 'eof.c' object:
  \tabular{ll}{
    EOF \tab EOF patterns. \cr
    W  \tab Eigen values. \cr
    PC \tab Principal components of common PCA. \cr
    n.fld \tab Number of different predictors (see
    \link{mixFields}). \cr
    tot.var \tab Sum of all W squared. \cr
    id.t \tab Time labels for the fields (see
    \link{catFields}) - used in \link{DS}. \cr
    id.x \tab Spatial labels for the fields (see
    \link{mixFields}) - used in \link{plotEOF}. \cr
    id.lon \tab Spatial labels for the fields (see
    \link{mixFields}) - used in \link{plotEOF}. \cr
    id.lat \tab Spatial labels for the fields (see
    \link{mixFields}) - used in \link{plotEOF}. \cr
    region \tab Describes the region analysed. \cr
    tim \tab Time information (usually redundant). \cr
    lon \tab Longitudes associated with EOF patterns. \cr
    lat \tab Latitudes associated with EOF patterns. \cr
    var.eof \tab Fractional variances associated with EOF patterns. \cr
    yy \tab years. \cr
    mm \tab months. \cr
    dd \tab days. \cr
    v.name \tab Name of element. \cr
    c.mon \tab Month-season information. \cr
    f.name \tab File name of original data. \cr
    clim \tab mean values (climatology) \cr
    attributes \tab Attributes \cr
}
  The data is also saved as files.
}
\author{R.E. Benestad}
\examples{
# Computes a set of mixed-common EOFs (overnight work..). This takes a while...
\dontrun{
library(clim.pact)
x.1 <- retrieve.nc("/home/kareb/data/ncep/ncep_t2m.nc",
                   x.rng=c(-60,40),y.rng=c(50,75))
x.2 <- retrieve.nc("/home/kareb/data/ncep/ncep_slp.nc",
                   x.rng=c(-60,40),y.rng=c(50,75))
print(x.1$v.name)

print("Read GCM predictor data.")
X.1 <- retrieve.nc("data/mpi-gsdio_t2m.nc",
                   x.rng=c(-60,40),y.rng=c(50,75))
X.2 <- retrieve.nc("data/mpi-gsdio_slp.nc",
                   x.rng=c(-60,40),y.rng=c(50,75))
print(X.1$v.name)
print("Cat fields.")
xX.1 <- cat.fields(x.1,X.1,interval.1=c(1958,1998),interval.2=c(1958,2050))
xX.2 <- cat.fields(x.2,X.2,interval.1=c(1958,1998),interval.2=c(1958,2050))
xX <- mix.fields(xX.1,xX.2,mon=1,
                 interval=c(1900,2050))
print("EOF")
eof.c <- eof(xX.1,mon=1)
eof.mc <- eof(xX,mon=1)
}
}

}
\keyword{spatial}
\keyword{ts}
\keyword{multivariate}


\eof
\name{EOF2field}
\alias{EOF2field}
\title{Reconstructs a field from EOF products}
\description{Reconstructs a field from \code{\link{EOF} products}.
}
\usage{EOF2field(eof,anomalies=FALSE)}

\arguments{
    \item{eof}{An 'EOF' object from \code{\link{EOF}}.}
    \item{anomalies}{True if only anomalies are to be shown.}
}

\value{A 'field' object (see \code{\link{retrieve.nc}}).}
}
\author{R.E. Benestad}}
\examples{
\dontrun{
load("data/ceof.Rdata")   # loads the object 'eof'
field <- EOF2field(eof)
}
}
\keyword{models}
\keyword{multivariate}
\keyword{ts}
\keyword{spatial}

\eof
\name{addland}
\alias{addland}
\title{Add land contours to map.}
\description{The function superimposes land contours on a map.}
\usage{addland(col="grey50",lwd=1) }
\arguments{
 \item{col}{colour}
 \item{lwd}{line width}
}
\author{R.E. Benestad}}
\examples{
plot(c(-90,90),c(0,80),type="n")
addland()
grid()
}
\keyword{hplot}

\eof
\name{addland}
\alias{continental coast line}
\alias{lat.cont}
\alias{lon.cont}
\alias{addland2}
\title{Coordinates of coast line.}
\description{Coordinates of coast line: \code{lat.cont} and
  \code{lon.cont} give the latitude and longitude coordinates of the
  coasts (continents).}
\usage{
data(addland)
data(addland2)}
\format{Two vectors, lat.cont and lon.cont, of length 124622.}
\source{Ferret web site}
\references{URL \url{http://ferret.wrc.noaa.gov/Ferret/}}
\examples{
library(clim.pact)
data(addland)
ls()                 # [1] "lat.cont" "lon.cont"
}
\keyword{datasets}

\eof
\name{adjust.eof}
\alias{adjust.eof}
\title{Adjust common EOFs}
\description{Forces same std and mean in the subsegments of common PCs.} 
\usage{adjust.eof(x)}
\arguments{
    \item{x}{a 'eof' object (see \code{\link{EOF}}).}
 
  }
\value{an 'eof' object}
\author{R.E. Benestad}}
\examples{
data(eof.c)
eof <- adjust.eof(eof.c)
plotEOF(eof)
}
\keyword{manip}

\eof
\name{anomaly.field}
\alias{anomaly.field}
\title{Anomalies of a field object.}
\description{Estimates the anomalies of a field object.  Also see \code{\link{anomaly.field}}.}
\usage{anomaly.field(x,period=NULL)}
\arguments{
  \item{x}{A field object.}
  \item{period}{Period to use as climatology 
           NULL -> the entire series as reference clim.}
 }
\value{A field object.}
\author{R.E. Benestad}}
\examples{
\dontrun{
slp<-retrieve.nc("ncep_slp.nc")
slp.a<-anomaly.field(slp)
}
}
\keyword{hplot}

\eof
\name{anomaly.station}
\alias{anomaly.station}
\title{Anomaly.station}
\description{Computes anomalies of a station series by subtracting the
  climatology. The climatology is estimated either by taking the average
  of the respective months over a given reference period or a least
  squares fit to the 6 leading harmonics, depending on the
  appropriateness. Also see \code{\link{anomaly.field}}.}
\usage{
anomaly.station(obs,period=c(1961,1990))
}
\arguments{
    \item{obs}{Monthly station series}
    \item{period}{Period to use as climatology 
           NULL -> the entire series as reference clim.}
  }
\value{Station series object.}
\author{R.E. Benestad}}
\examples{
library(clim.pact)
data(oslo.t2m)
oslo.t2ma<-anomaly.station(oslo.t2m)
}
\keyword{manip}

\eof
\name{avail.elem}
\alias{avail.elem}
\alias{avail.locs}
\alias{avail.preds}
\alias{avail.eofs}
\alias{avail.ds}
\title{Available elements}
\description{The function \code{avail.preds} searches for available predictors
  and returns a list of file names. \code{avail.elem} returns a list of
  available elements and \code{avail.locs} a list of available locations. These
  functions are support functions for \code{\link{getnacd}} and \code{\link{getnordklim}}.}
\usage{
avail.ds(direc="output")
avail.eofs(direc="data")
avail.preds(direc="data")
avail.elem()
avail.locs(ele) }
\arguments{
    \item{direc}{String containing the data directory.} 
    \item{ele}{Integer code for element in the Nordklim dataset:}
    \tabular{ll}{
      101 \tab mean T(2m) \cr
      111 \tab mean maximum T(2m) \cr
      112 \tab highest maximum T(2m) [Th] \cr
      113 \tab day of Th date Thd \cr
      121 \tab mean minimum T(2m) \cr
      122 \tab lowest minimum T(2m) [Tl] \cr
      123 \tab day of Tl date Tld \cr
      401 \tab mean SLP \cr
      601 \tab monthly accum. precip. \cr
      602 \tab maximum precip. \cr
      701 \tab Number of days with snow cover (> 50\% covered) days dsc \cr
      801 \tab Mean cloud cover \% N  \cr
      911 \tab mean snow depth \cr}
}
\value{
    
    \tabular{ll}{
      avail.preds \tab vector of characters \cr
      avail.locs \tab a list with name, lons, lats,
      country, ident \cr
      avail.elem \tab a list with data.set, ele, name \cr}}
\author{R.E. Benestad}}
\examples{
library(clim.pact)
avail.elem()$name
# [1] "mean T(2m)"                                             
# [2] "mean maximum T(2m)"                                     
# [3] "highest maximum T(2m)"                                  
# [4] "day of Th date Thd"                                     
# [5] "mean minimum T(2m)"                                     
# [6] "lowest minimum T(2m)"                                   
# [7] "day of Tl date Tld"                                     
# [8] "mean SLP"                                               
# [9] "monthly accum. precip."                                 
#[10] "maximum precip."                                        
#[11] "Number of days with snow cover (> 50% covered) days dsc"
#[12] "Mean cloud cover % N"                                   
#[13] "mean snow depth"

# The following assumes that the subdirectory 'data' exists
\dontrun{
avail.locs()$name[avail.locs()$country=="FIN"]
# [1] "HELSINKI"      "TURKU"         "TAMPERE"       "LAPPEENRANTA" 
# [5] "JYVASKYLA"     "KUOPIO"        "KAJAANI"       "OULU"         
# [9] "KUUSAMO"       "SODANKYLA"     "Maarianhamina" "Helsinki"     
#[13] "Turku"         "Huittinen"     "Tampere"       "Hattula"      
#[17] "Heinola"       "Virolahti"     "Lappeenranta"  "Lavia"        
#[21] "Virrat"        "Orivesi"       "Jyvaeskylae"   "Vaasa"        
#[25] "Ylistaro"      "Aehtaeri"      "Kuopio"        "Maaninka"     
#[29] "Joensuu"       "Kestilä"       "Kajaani"       "Oulu"         
#[33] "Yli-Ii"        "Pudasjärvi"    "Kuusamo"       "Sodankylae"

avail.preds()
# [1] "eof.dc.Rdata"                                                 
# [2] "eof.dmc.Rdata"                                                
# [3] "eof.mc2.Rdata"                                                
# [4] "eof.nn.dc.Rdata"                                              
# [5] "eof.nn.dmc.Rdata"
# ...
}
}
\keyword{file}

\eof
\name{bergen.dm}
\alias{bergen.dm}
\title{Daily Bergen record.}
\description{A station record of daily mean temperature and daily
  precipitation from Bergen-Florida.}
\usage{data(bergen.dm)}
\format{a "daily.station.record"-class object.
  \tabular{ll}{
  t2m \tab a vector holding daily mean temperature. \cr
  precip \tab a vector holding daily precipitation. \cr
  dd \tab a vector holding day of month.\cr
  mm \tab a vector holding the month.\cr
  yy \tab a vector holding the year.\cr
  obs.name \tab the name of observation: \cr
  \tab eg c("Daily mean temperature","Daily precipitation"). \cr
  unit \tab the unite of observation: eg c("deg C","mm/day").\cr
  ele \tab element code: eg c("tam","rr").\cr
  station \tab local (national) station number.\cr
  lat \tab latitude.\cr
  lon \tab longitude.\cr
  alt \tab altitude.\cr
  location \tab name of location. \cr
  wmo.no \tab WMO number of station.\cr
  start \tab start of measurements.\cr
  yy0 \tab first year of record.\cr
  country \tab name of country.\cr
  ref \tab reference to the data.\cr}}
\source{The Norwegian Meteorological Institute, Climatology deivision.}
\references{The Norwegian Meteorological Institute, P.O. Box 43, 0313
Oslo, Norway (http://www.met.no).}
\examples{
}
\keyword{datasets}

\eof
\name{bergen.t2m}
\alias{bergen.t2m}
\title{Monthly mean temperature in Bergen.}
\description{A station record of monthly mean temperature from Bergen-Florida.}
\usage{data(bergen.t2m)}
\format{a <- list of "monthly.station.record" class:
    \tabular{ll}{
    val \tab The monthly values (a 12-column matrix with one
    column for each year). \cr
    station \tab station number. \cr
    yy \tab The years of observation (vector). \cr
    lat,lon \tab Latitude and longitude of the location. \cr
    x.0E65N,y.0E65N \tab Distance in km from 0E, 65N. \cr
    location \tab Name of location . \cr
    wmo.no \tab WMO number. \cr
    start \tab Start of observatins from this location. \cr
    yy0 \tab First year in current record. \cr
    ele \tab Code of theelement. \cr
    obs.name \tab Name of the element. \cr
    unit \tab Unit of the element. \cr
    country \tab The country in which the location is
    located. \cr
    quality \tab Code/description for data quality. \cr
    found \tab Flag: T - the data requested was found. \cr
    ref \tab Reference for the data set. \cr
  }}
\source{The Nordklim data set: \url{http://www.smhi.se/hfa_coord/nordklim/}}
\references{Tuomenvirta et al. (2001), "Nordklim data set 1.0", DNMI
  KLIMA 08/01, pp. 26; \cr
  The Norwegian Meteorological Institute, P.O. Box 43, 0313
Oslo, Norway (http://www.met.no).}
\examples{
}
\keyword{datasets}

\eof
\name{caldat}
\alias{caldat}
\title{Converts Julian days to month, day, and year}
\description{The function computes month, day, and year from Julian
  days. The code is based on the algortithm from Press et al. (1989), "Numerical Recipes 
  in Pascal", Cambridge, p. 13. See also \code{chron} and \code{date}
for similar functions. This function was included to avoid the
dependency to the \code{chron} and \code{date} packages. See also \code{\link{julday}}.}
\usage{caldat(julian)}
\arguments{
    \item{julian}{The Julian day from 1-1-1.}
 }
\value{real}
\author{R.E. Benestad}}
\examples{
caldat(1)        # month=1, day=2, year=-4713
caldat(1721424)  #       1,     1,          1
caldat(2440588)  #       1,     1,       1970
caldat(2452887)  #       9,     4,       2003
}
\keyword{manip}

\eof
\name{catFields}
\alias{catFields}
\title{catFields}
\description{Concatinates fields two different gridded sets of
  observation. The two fields must be stored on the same spatial grid,
  and the routine performs a bilinear spatial interpolation to place the
  data on the same grid. Observations/data for representing values at n
  different locations at a given time (t) can be described in terms of a
  vector
  \deqn{\vec{x}(t) = [x_1, x_2, ... x_n].}{x(t)=[x_1, x_2,
    ... x_n].}
  The data set consists of a time series of vectors which can be
  represented by the means of matrices
  \deqn{X = [\vec{x}(t_1), \vec{x}(t_2), ... \vec{x}(t_n)].}{
    X=[x(t_1), x(t_2), ... x(t_n)].}
  Two different sets of observations can be represented by two matrices
  Y and Z with dimensions k x n and k x m respectively (k is the number
  of spatial points, whereas n and mIindicate the number of observations
  in time). The information in these two data sets are combined
  combining  the two matrices using rbind. The major difference between
  this routine and rbind is that this routine takes care of all the
  'house keeping' in terms of grid, time and variable information. 

  cat.field can be used to process single fields by setting
  'field.2=NULL'. This option allows for interpolation and extraction of
  sub-regions or sub-intervals, removing the mean values, and selecting
  a paricular month or season.

  The output from cat.fields can by further analysed in  \code{\link{EOF}}. By
  using a concatination of two fields of similar data, eg observed and
  simulated sea level pressure (SLP), it is possible to carry out a
  common EOF analysis. The application of \code{\link{DS}} to the EOFs of
  concatinated fields provides an analysis similar to the common EOH
  method described in Benestad (2001), "A comparison between two
  empirical downscaling strategies", \emph{Int. J. Climatology}, \bold{vol 21},
  1645-1668, DOI 10.1002/joc.703. 
}  
\usage{
catFields(field.1,field.2=NULL,lat=NULL,lon=NULL,plot.interp=FALSE,
           interval.1=NULL,interval.2=NULL,mon=NULL,demean=TRUE) 
}
\arguments{
    \item{field.1}{A 'field.object'. }
    \item{field.2}{A 'field.object'. A 'field.2=NULL' processes single fields.}
    \item{lat}{Latitudes to extract. If NULL, use the latitudes from
      the first field. Otherwise interpolate both fields to latitudes.  }
    \item{lon}{Longitudes to extract. See 'lat'. }
    \item{plot.interp}{Flag: 'TRUE' plots the interploation results - 
    Used for checking interpolation. }
    \item{interval.1}{Extract the time interval for the 1st field. }
    \item{interval.2}{Extract the time interval for the 2nd field. }
    \item{mon}{Calendar month or season to extract. eg January or DJF. }
    \item{demean}{Flag: 'TRUE' subtracts the mean values. This flag
      should be set to 'FALSE' if for instance two time slices are
      concatinated and the object is to investigate the mean change
      between these periods (see examples in \code{\link{eof.dc}} or
      \code{\link{eof.dmc}}).} 
  }
\value{A 'field.object'.}
\author{R.E. Benestad}
\examples{
\dontrun{
library(clim.pact)
x.1 <- retrieve.nc("/home/kareb/data/ncep/ncep_t2m.nc",
                   x.rng=c(-60,40),y.rng=c(50,75))
x.2 <- retrieve.nc("/home/kareb/data/ncep/ncep_slp.nc",
                   x.rng=c(-60,40),y.rng=c(50,75))
print(x.1$v.name)

print("Read GCM predictor data.")
X.1 <- retrieve.nc("data/mpi-gsdio_t2m.nc",
                   x.rng=c(-60,40),y.rng=c(50,75))
X.2 <- retrieve.nc("data/mpi-gsdio_slp.nc",
                   x.rng=c(-60,40),y.rng=c(50,75))
print(X.1$v.name)
print("Cat fields.")
xX.1 <- catFields(x.1,X.1,interval.1=c(1958,1998),interval.2=c(1958,2050))
xX.2 <- catFields(x.2,X.2,interval.1=c(1958,1998),interval.2=c(1958,2050))
xX <- mixFields(xX.1,xX.2,mon=1,
                 interval=c(1900,2050))
print("EOF")
eof.c <- eof(xX.1,mon=1)
eof.mc <- eof(xX,mon=1)
}
}
\keyword{manip}
\keyword{ts}

\eof
\name{cdfcont}
\alias{cdfcont}
\title{netCDF names and dimensions.}
\description{Obtains the variable names and dimension names from a
  netCDF file. This routine provides some of the information returned by
  \code{\link[netCDF]{names.netCDF}}, however this function does not depend on
  the \code{netCDF} package. If it doesn't work, make sure to set the
  path to include the location of \code{ncdump} and \code{ncgen} (two
  netCDF executables, usually under a netcdf direcory). Alternatively,
  set the \code{path}.}
\usage{cdfcont(filename,path="")}
\arguments{
    \item{filename}{name of netCDF file.}
    \item{path}{Path to the location where \code{ncdump} and \code{ncgen} are located.}
 }
\value{a list object containing two character vectors: \code{vars} and
  \code{dims} holding the names of the variables and
  dimensions. \code{dims} gives the dimensions for each of the variable,
  and may contain several names within the same string, separated by a
  comma, eg. "LONS","LATS",and "LATS, LONS" (\code{strsplit("TIME, LATS,
  LONS",", ")} can be used to split up these variables into seperate
  names).
  'time.origin' returns the time\_origin, 'add.offset' gives the 'add\_offset'
  attribute, and 'scale.factor' gives the scale\_factor.}

\author{R.E. Benestad}}
\examples{
}
\keyword{file}

\eof
\name{cdfextract}
\alias{cdfextract}
\title{Extract a subfield from a netCDF file.}
\description{A slow routine that extraxcts a subfield. This routine is
  suitable for reading subsections of large data files that are too big
  for \code{\link{retrieve.nc}}. 

This version uses \code{\link{cdfcont}} to obtain vital meta data for
handling the data in the netCDF file and constructing a 'field' object.}
\usage{cdfextract(filename,varname,x.rng=NULL,y.rng=NULL,t.rng=NULL,
                       greenwich=TRUE,x.nam="lon",y.nam="lat",t.nam="tim",
                       plot=TRUE,l.scale=TRUE)}
\arguments{
    \item{filename}{name of netCDF file.}
    \item{varname}{name ov variable.}
    \item{x.rng}{X-range (in degrees East): c(min,max).}
    \item{y.rng}{Y-range (in degrees North): c(min,max).}
    \item{t.rng}{T-range (in units stored in 'tim'): c(min,max).}
    \item{greenwich}{TRUE: longitude runs from -180E to 180E.}
    \item{x.nam}{name of X-dimension.}
    \item{y.nam}{name of Y-dimension.}
    \item{t.nam}{name of T-dimension.}
    \item{plot}{TRUE for plotting.}
    \item{l.scale}{scale field by offset and scaling-factor.}
 }
\value{a field object. Also see \code{\link{retrieve.nc}}. Saves the
  extracted data in a netCDF file called "cdfextract.nc" under current
  working directory (see \code{\link{r2cdf}}).}
\author{R.E. Benestad}}
\examples{
\dontrun{
slp <- cdfextract("data/nmc_slp.nc","slp",x.rng=c(-80,40),y.rng=c(20,75),
                  t.rng=c(times[is],times[is]+499),plot=FALSE)
}
}
\keyword{file}

\eof
\name{composite.field}
\alias{composite.field}
\alias{compositeField}
\title{Composite maps}
\description{Produce composites of maps based on station observations,
  weights, or years. For a station object, assign +/- 1 weights
  according to whether the values stored in \code{val} (monthly station
  objects)  are greater than mean + sd or less than
  mean - sd.}
\usage{
composite.field(x,y,lsig.mask=TRUE,sig.lev=0.05,s=0.42,mon=NULL,
                      lty=1,col="black",lwd=1,main=NULL,sub=NULL)
compositeField(x,y,lsig.mask=TRUE,sig.lev=0.05,s=0.42,mon=NULL,
                      lty=1,col="black",lwd=1,main=NULL,sub=NULL)
}
\arguments{
    \item{x}{A field object.}
    \item{y}{A station object, a vector consisting of [-1,0,+1] or a
      vector consisting of the years (negative values are used for
      negative phase, eg. c(1991,1993,1998,-1961,-1963,-1994).}
    \item{lsig.mask}{FLAG: mask the regions not statistically significant.}
    \item{sig.lev}{Level of significance.}
    \item{s}{Threshold for defining whether \code{y} is high or low = s *
      sd(y).}
    \item{mon}{Month to analyse.}
    \item{lty}{Contour line type.}
    \item{col}{Contour line colour.}
    \item{lwd}{Contour line width.}
    \item{main}{Main title.}
    \item{sub}{subtitle.}
 }
\value{A map object.}
\author{R.E. Benestad}}
\examples{
\dontrun{
slp <- retrieve.nc("ncep_slp.nc")
data(oslo.t2m)
composite.field(slp,oslo.t2m)
}
}
\keyword{manip}

\eof
\name{corEOF}
\alias{field correlation, PCA}
\alias{corEOF}
\title{Field correlation}
\description{Produces maps of spatial correlation patterns from the EOF
  products \deqn{X = {\bf UWV}^T}{X = UWt(V)} according to following formula:
  \deqn{r({\bf X}_{r,t}, \vec{y})=  \frac{
      \sum_k {\bf W}_k {\bf U}_{r,k}{\bf W}_k \sum_t [{\bf V}_{k,t}^T y'_t]}
 {\sqrt{\sum_k{\bf W}_k {\bf U}_{r,k}{\bf W}_k \sum_t({\bf V}_{k,t}^T)^2 
       \times \sum_t(y'_t)^2}}.}{.}

  Reference: Environmental statistics for climate researchers
  \url{http://www.gfi.uib.no/~nilsg/kurs/notes/course.html}

  \bold{NOTE: This routine is not finished yet - still contains some
    bugs, sometimes resulting in absolute correlation values greater
    than unity.} 
}
\usage{corEOF(x,y,lsig.mask=TRUE,sig.lev=0.05,neofs=20,
                 lty=1,col="black",lwd=1)}
\arguments{
    \item{x}{An EOF.}
    \item{y}{A station series.}
    \item{lsig.mask}{Mask out values that are not statistically significant.}
    \item{sig.lev}{Level of significanse.}
    \item{neofs}{Number of modes to include.}
    \item{lty}{Contour line type.}
    \item{col}{Contour line colour.}
    \item{lwd}{Contour line width.}
 }
\value{A map object.}
\author{R.E. Benestad}}
\examples{
data(oslo.t2m)
data(eof.slp)
corEOF(eof.slp,oslo.t2m)
}
\keyword{manip}

\eof
\name{corField}
\alias{field correlation}
\alias{corField}
\title{Field correlation}
\description{Produces maps of spatial correlation patterns.}
\usage{corField(x,y,lsig.mask=TRUE,sig.lev=0.05,mon=NULL,
                 lty=1,col="black",lwd=1,main=NULL,z.levs=NULL,my.col=NULL)}
\arguments{
    \item{x}{A field object.}
    \item{y}{A station series or a field object.}
    \item{lsig.mask}{Mask out values that are not statistically significant.}
    \item{sig.lev}{Level of significanse.}
    \item{mon}{Month to analyse.}
    \item{lty}{Contour line type.}
    \item{col}{Contour line colour.}
    \item{lwd}{Contour line width.}
    \item{main}{Title of plot, same as 'main' in plot().}
    \item{z.levs}{contour levels.}
    \item{my.col}{colour template (see \code{link{rgb}}).}
 }
\value{A map object.}
\author{R.E. Benestad}}
\examples{
\dontrun{
slp <- retrieve.nc("ncep_slp.nc")
data(oslo.t2m)
corField(slp,oslo.t2m)
}
}
\keyword{manip}

\eof
\name{datestr2num}
\alias{datestr2num}
\title{datestr2num}
\description{Converts a date string to number.}
\usage{datestr2num(datestr,vec=TRUE)}
\arguments{
    \item{datestr}{A date string (character). Types of stings may be "01-Jan-1980","1-1-1980", "01-01-1980", "1980-1-1", "1980-Jan-1"}
    \item{vec}{TRUE returns a vector \code{c(year,month,day)}; FALSE returns \code{year + month/12 + day/31}.}
 }
\value{A number or a vector}
\author{R.E. Benestad}}
\examples{
datestr2num("01-Jan-1980")
datestr2num("1-1-1980")
datestr2num("01-01-1980")
datestr2num("1980-1-1")
datestr2num("1980-Jan-1")
}
\keyword{manip}

\eof
\name{delta}
\alias{delta}
\alias{delta function}
\title{Delta function}
\description{The dirac delta function: delta (i,j) returns 1 if i==j, 0
  otherwise.}
\usage{delta(i,j)}
\arguments{
    \item{i}{first index.}
    \item{j}{second index.}
 }
\value{0 or 1}
\author{R.E. Benestad}}
\examples{
}
\keyword{manip}

\eof
\name{dist2norm}
\alias{dist2norm}
\alias{norm2dist}
\title{Transform a series to a normally distributed series.}
\description{Used for DS on non-Gaussian data. Tailored for the use with
  daily precipitation. \code{dist2norm} transforms (maps) data to normal
distribution and \code{norm2dist} carries out the reverse operation. The
mapping/transformation is done through one-to-one matching of the
empirical distribution functions (e.d.f.) of the data and a Gaussian
distribution.}
\usage{
  dist2norm(x,plot=FALSE,exclude=NULL,sd=1,mean=0,force.zero=TRUE)
  norm2dist(x,plot=FALSE,exclude=NULL,sd=1,mean=0,force.zero=TRUE)
}
\arguments{
    \item{x}{vector.}
    \item{plot}{T -> plot for illustrating the mapping.}
    \item{exclude}{Values (e.g. 0) to exclude for the transform.}
    \item{sd}{The standard deviation of the transformed quantities.}
    \item{mean}{The mean value of the transformed quantities.}
    \item{force.zero}{Force the e.d.f. to start from 0.}
 }
\value{a list object of class 'dist2norm' containing a vector and the empirical transform functions.}
\author{R.E. Benestad}}
\examples{
}
\keyword{manip}



\eof
\name{distAB}
\alias{distAB}
\title{Distance between two points on Earth}
\description{The function returns the distance between two points on
  Earth given by the lon-lat coordinates. The distance is computed using
the formula: d = a * theta, and |x1|*|x2| * cos(theta) = inner-product(x1,x2).}
\usage{distAB(lon,lat,lons,lats,a=6.378e06)}
\arguments{
    \item{lon}{Longitude of reference point (degrees East).}
    \item{lat}{Latitude of reference point (degrees North).}
    \item{lons}{Longitude of points of interest (vector) (degrees East).}
    \item{lats}{Latitude of points of interest (vector) (degrees
      North).}
    \item{a}{Radius of the Earth.}
 }
\value{A real value: units=meters.}
\author{R.E. Benestad}}
\examples{
distAB(10,60,5,58)    # [1] 362802.3
distAB(0,0,180,0)     # [1] 20037078
distAB(0,90,0,-90)    # [1] 20037078
}
\keyword{math}

\eof
\name{ds2station}
\alias{ds2station}
\title{Convert ds to station object}
\description{Convert 'ds' object to 'station' object so that
downscaled scenarios can be handled like station series.} 
\usage{ds2station(x,what="scenario")}
\arguments{
    \item{x}{a 'ds' object (see \code{\link{DS}}).}
    \item{what}{either 'scenario' or 'calibration'}
  }
\value{a station object}
\author{R.E. Benestad}}
\examples{
data(eof.c)
data(oslo.t2m)
ds <- DS(preds=eof.c, oslo.t2m,plot=FALSE)
oslo.dm <- ds2station(ds)
plotStation(oslo.dm)
}
\keyword{manip}

\eof
\name{eof.c}
\alias{eof.c}
\alias{eof.c_data}
\title{Monthly common EOF.}
\description{Common EOFs for January mean 2-meter temperature
  (T(2m)). 
}
\usage{data(eof.c)}
\format{
  \tabular{ll}{
    EOF \tab EOF patterns. \cr
    W  \tab Eigen values. \cr
    PC \tab Principal components of common PCA. \cr
    n.fld \tab Number of different predictors (see
    \link{mixFields}). \cr
    tot.var \tab Sum of all W squared. \cr
    id.t \tab Time labels for the fields (see
    \link{catFields}) - used in \link{DS}. \cr
    id.x \tab Spatial labels for the fields (see
    \link{mixFields}) - used in \link{plotEOF}. \cr
    id.lon \tab Spatial labels for the fields (see
    \link{mixFields}) - used in \link{plotEOF}. \cr
    id.lat \tab Spatial labels for the fields (see
    \link{mixFields}) - used in \link{plotEOF}. \cr
    region \tab Describes the region analysed. \cr
    tim \tab Time information (usually redundant). \cr
    lon \tab Longitudes associated with EOF patterns. \cr
    lat \tab Latitudes associated with EOF patterns. \cr
    var.eof \tab Fractional variances associated with EOF patterns. \cr
    yy \tab years. \cr
    mm \tab months. \cr
    dd \tab days. \cr
    v.name \tab Name of element. \cr
    c.mon \tab Month-season information. \cr
    f.name \tab File name of original data. \cr
  }
  }
\source{
The common EOF was produced using  \code{\link{EOF}}, with the combined January
2-meter air temperature data field from National Center for
Environmental Prediction (NCEP; USA) reanalysis (Kalnay et al., (1996) "The NCEP/NCAR 40-Year Reanalysis Project",  \emph{Bul. Am. Met. Soc.}, \bold{vol 77}, no 3, 437-471; e.g. see URL: \url{http://www.cdc.noaa.gov/index.html}) and the ECHAM4-GSDIO scenario (Max-Planck Institute for Meteorology, Hamburg, Germany; URL: \url{http://www.mpimet.mpg.de/}). The region is 60W - 40E, 50N - 75N.
}
\references{Reference to methodology: R.E. Benestad (2001), "A comparison
  between two empirical downscaling strategies",
  \emph{Int. J. Climatology}, \bold{vol 210}, pp.1645-1668. [DOI
  10.1002/joc.703].
  }
\examples{
library(clim.pact)
data(eof.c)
}
\keyword{datasets}

\eof
\name{eof.dc}
\alias{eof.dc}
\alias{eof.dc_data}
\title{Daily common EOF.}
\description{Common EOFs for daily December-February 2-meter temperature
  (T(2m)). 
}
\usage{data(eof.dc)}
\format{
  \tabular{ll}{
    EOF \tab EOF patterns. \cr
    W  \tab Eigen values. \cr
    PC \tab Principal components of common PCA. \cr
    n.fld \tab Number of different predictors (see
    \link{mixFields}). \cr
    tot.var \tab Sum of all W squared. \cr
    id.t \tab Time labels for the fields (see
    \link{catFields}) - used in \link{DS}. \cr
    id.x \tab Spatial labels for the fields (see
    \link{mixFields}) - used in \link{plotEOF}. \cr
    id.lon \tab Spatial labels for the fields (see
    \link{mixFields}) - used in \link{plotEOF}. \cr
    id.lat \tab Spatial labels for the fields (see
    \link{mixFields}) - used in \link{plotEOF}. \cr
    region \tab Describes the region analysed. \cr
    tim \tab Time information (usually redundant). \cr
    lon \tab Longitudes associated with EOF patterns. \cr
    lat \tab Latitudes associated with EOF patterns. \cr
    var.eof \tab Fractional variances associated with EOF patterns. \cr
    yy \tab years. \cr
    mm \tab months. \cr
    dd \tab days. \cr
    v.name \tab Name of element. \cr
    c.mon \tab Month-season information. \cr
    f.name \tab File name of original data. \cr
  }
  }
\source{
The common EOF was produced using  \code{\link{EOF}}, with the combined
December-February (DJF) 2-meter air temperature data field from European
Centre for Medium-Range Weather Forecasts (ECMWF; UK) reanalysis ( see URL:
\url{http://www.ecmwf.int/}) and HIRHAM dynamically dowwnscaled
scenarios from the ECHAM4-GSDIO scenario (Max-Planck Institute for Meteorology, Hamburg, Germany; URL: \url{http://www.mpimet.mpg.de/}). The region is 5E - 25E, 58N - 65N.
}
\references{Reference to methodology: R.E. Benestad (2001), "A comparison
  between two empirical downscaling strategies", \emph{Int. J. Climatology}, \bold{vol 210}, pp.1645-1668. [DOI 10.1002/joc.703].}
\examples{
#The EOFs were produced using the following code:
library(clim.pact)
\dontrun{
x.1.dm<-retrieve.nc("/data1/era15/ERA-15_t2m.nc",x.rng=c(5,25),y.rng=c(58,65))
X.1.dm<-retrieve.nc("/data1/hirham/T2M_198001-199912.nc",x.rng=c(5,25),
                    y.rng=c(58,65))
Y.1.dm<-retrieve.nc("/data1/hirham/T2M_203001-204912.nc",x.rng=c(5,25),
                    y.rng=c(58,65))
Y.1.dm$yy <- Y.1.dm$yy + 50
# It is important that demean=FALSE when concatinating the two time slices
# from the model simulations, if a study of climate change is the objective.
xX.1.dm <- catFields(X.1.dm,Y.1.dm,demean=FALSE)
xX.1.dm <- catFields(x.1.dm,xX.1.dm)
eof.dc <- eof(xX.1.dm,mon=1)
}
# To read the data:
data(eof.dc)
}
\keyword{datasets}

\eof
\name{eof.dmc}
\alias{eof.dmc}
\alias{eof.dmc_data}
\title{Daily common EOF.}
\description{Common EOFs for daily December-February 2-meter temperature
  (T(2m)) and sea level pressure (SLP). 
}
\usage{data(eof.dmc)}
\format{
  \tabular{ll}{
    EOF \tab EOF patterns. \cr
    W  \tab Eigen values. \cr
    PC \tab Principal components of common PCA. \cr
    n.fld \tab Number of different predictors (see
    \link{mixFields}). \cr
    tot.var \tab Sum of all W squared. \cr
    id.t \tab Time labels for the fields (see
    \link{catFields}) - used in \link{DS}. \cr
    id.x \tab Spatial labels for the fields (see
    \link{mixFields}) - used in \link{plotEOF}. \cr
    id.lon \tab Spatial labels for the fields (see
    \link{mixFields}) - used in \link{plotEOF}. \cr
    id.lat \tab Spatial labels for the fields (see
    \link{mixFields}) - used in \link{plotEOF}. \cr
    region \tab Describes the region analysed. \cr
    tim \tab Time information (usually redundant). \cr
    lon \tab Longitudes associated with EOF patterns. \cr
    lat \tab Latitudes associated with EOF patterns. \cr
    var.eof \tab Fractional variances associated with EOF patterns. \cr
    yy \tab years. \cr
    mm \tab months. \cr
    dd \tab days. \cr
    v.name \tab Name of element. \cr
    c.mon \tab Month-season information. \cr
    f.name \tab File name of original data. \cr
  }
  }
\source{
The common EOF was produced using  \code{\link{EOF}}, with the combined
December-February (DJF) 2-meter air temperature data field from European
Centre for Medium-Range Weather Forecasts (ECMWF; UK) reanalysis ( see URL:
\url{http://www.ecmwf.int/}) and HIRHAM dynamically dowwnscaled
scenarios from the ECHAM4-GSDIO scenario (Max-Planck Institute for Meteorology, Hamburg, Germany; URL: \url{http://www.mpimet.mpg.de/}). The region is 5E - 25E, 58N - 65N.
}
\references{Reference to methodology: R.E. Benestad (2001), "A comparison
  between two empirical downscaling strategies", \emph{Int. J. Climatology}, \bold{vol 210}, pp.1645-1668. [DOI 10.1002/joc.703].}
\examples{
library(clim.pact)
\dontrun{
x.1.dm<-retrieve.nc("/data1/era15/ERA-15_t2m.nc",x.rng=c(5,25),y.rng=c(58,65))
X.1.dm<-retrieve.nc("/data1/hirham/T2M_198001-199912.nc",x.rng=c(5,25),
                    y.rng=c(58,65))
Y.1.dm<-retrieve.nc("/data1/hirham/T2M_203001-204912.nc",x.rng=c(5,25),
                    y.rng=c(58,65))
Y.1.dm$yy <- Y.1.dm$yy + 50
# It is important that demean=FALSE when concatinating the two time slices
# from the model simulations, if a study of climate change is the objective.
xX.1.dm <- catFields(X.1.dm,Y.1.dm,demean=FALSE)
xX.1.dm <- catFields(x.1.dm,xX.1.dm)
x.2.dm<-retrieve.nc("/data1/era15/ERA-15_slp.nc",x.rng=c(5,25),y.rng=c(58,65))
X.2.dm<-retrieve.nc("/data1/hirham/PSL_198001-199912.nc",x.rng=c(5,25),
                    y.rng=c(58,65))
Y.2.dm<-retrieve.nc("/data1/hirham/PSL_203001-204912.nc",x.rng=c(5,25),
                    y.rng=c(58,65))
Y.2.dm$yy <- Y.2.dm$yy + 50
# It is important that demean=FALSE when concatinating the two time slices
# from the model simulations, if a study of climate change is the objective.
xX.2.dm <- catFields(X.2.dm,Y.2.dm,demean=FALSE)
xX.2.dm <- catFields(x.2.dm,xX.2.dm)

xX.dm <- mix.fields(xX.1.dm,xX.2.dm,mon=1)
eof.dmc <- eof(xX.dm,mon=1)
}
# To read the data:
data(eof.dmc)
}
\keyword{datasets}

\eof
\name{eof.mc}
\alias{eof.mc}
\alias{eof.mc_data}
\title{Monthly mixed-common EOF.}
\description{Monthly mixed-common EOFs for January mean 2-meter temperature
  (T(2m)) and sea-level-Pressure (SLP). 
}
\usage{data(eof.mc)}
\format{
  \tabular{ll}{
    EOF \tab EOF patterns. \cr
    W  \tab Eigen values. \cr
    PC \tab Principal components of common PCA. \cr
    n.fld \tab Number of different predictors (see
    \link{mixFields}). \cr
    tot.var \tab Sum of all W squared. \cr
    id.t \tab Time labels for the fields (see
    \link{catFields}) - used in \link{DS}. \cr
    id.x \tab Spatial labels for the fields (see
    \link{mixFields}) - used in \link{plotEOF}. \cr
    id.lon \tab Spatial labels for the fields (see
    \link{mixFields}) - used in \link{plotEOF}. \cr
    id.lat \tab Spatial labels for the fields (see
    \link{mixFields}) - used in \link{plotEOF}. \cr
    region \tab Describes the region analysed. \cr
    tim \tab Time information (usually redundant). \cr
    lon \tab Longitudes associated with EOF patterns. \cr
    lat \tab Latitudes associated with EOF patterns. \cr
    var.eof \tab Fractional variances associated with EOF patterns. \cr
    yy \tab years. \cr
    mm \tab months. \cr
    dd \tab days. \cr
    v.name \tab Name of element. \cr
    c.mon \tab Month-season information. \cr
    f.name \tab File name of original data. \cr
  }
  }
\source{
The common EOF was produced using  \code{\link{EOF}}, with the combined January
2-meter air temperature and sea level pressure data field from National
Center for Environmental Prediction (NCEP; USA) reanalysis (Kalnay et al., (1996) "The NCEP/NCAR 40-Year Reanalysis Project",  \emph{Bul. Am. Met. Soc.}, \bold{vol 77}, no 3, 437-471; e.g. see URL: \url{http://www.cdc.noaa.gov/index.html}) and the ECHAM4-GSDIO scenario (Max-Planck Institute for Meteorology, Hamburg, Germany; URL: \url{http://www.mpimet.mpg.de/}). The region is 60W - 40E, 50N - 75N.
}
\references{Reference to methodology: R.E. Benestad (2001), "A comparison
  between two empirical downscaling strategies", \emph{Int. J. Climatology}, \bold{vol 210}, pp.1645-1668. [DOI 10.1002/joc.703].}
\examples{
library(clim.pact)
data(eof.mc)
}
\keyword{datasets}

\eof
\name{eof.slp}
\alias{eof.slp}
\title{EOF of NCEP reanalysis SLP.}
\description{EOF of NCEP reanalysis January mean sea level pressure
}
\usage{data(eof.slp)}
\format{
  \tabular{ll}{
    EOF \tab EOF patterns. \cr
    W  \tab Eigen values. \cr
    PC \tab Principal components of common PCA. \cr
    n.fld \tab Number of different predictors (see
    \link{mixFields}). \cr
    tot.var \tab Sum of all W squared. \cr
    id.t \tab Time labels for the fields (see
    \link{catFields}) - used in \link{DS}. \cr
    id.x \tab Spatial labels for the fields (see
    \link{mixFields}) - used in \link{plotEOF}. \cr
    id.lon \tab Spatial labels for the fields (see
    \link{mixFields}) - used in \link{plotEOF}. \cr
    id.lat \tab Spatial labels for the fields (see
    \link{mixFields}) - used in \link{plotEOF}. \cr
    region \tab Describes the region analysed. \cr
    tim \tab Time information (usually redundant). \cr
    lon \tab Longitudes associated with EOF patterns. \cr
    lat \tab Latitudes associated with EOF patterns. \cr
    var.eof \tab Fractional variances associated with EOF patterns. \cr
    yy \tab years. \cr
    mm \tab months. \cr
    dd \tab days. \cr
    v.name \tab Name of element. \cr
    c.mon \tab Month-season information. \cr
    f.name \tab File name of original data. \cr
  }
  }
\source{
The common EOF was produced using  \code{\link{EOF}}, with the combined January
2-meter air temperature data field from National Center for
Environmental Prediction (NCEP; USA) reanalysis (Kalnay et al., (1996) "The NCEP/NCAR 40-Year Reanalysis Project",  \emph{Bul. Am. Met. Soc.}, \bold{vol 77}, no 3, 437-471; e.g. see URL: \url{http://www.cdc.noaa.gov/index.html}).
}
\references{Reference to methodology: R.E. Benestad (2001), "A comparison
  between two empirical downscaling strategies",
  \emph{Int. J. Climatology}, \bold{vol 210}, pp.1645-1668. [DOI
  10.1002/joc.703].
  }
\examples{
library(clim.pact)
data(eof.slp)
}
\keyword{datasets}

\eof
\name{getdnmi}
\alias{getdnmi}
\title{Retrieve station record from DNMI database filed.}
\description{Retrieve station record from DNMI (The Norwegian
  Meteorological Institute, met.no) database filed. URL
  \url{http://www.met.no}. Also see \code{\link{getnacd}} and
  \code{\link{getnordklim}}.
}
\usage{getdnmi(location,ele.c='101',silent = FALSE,direc="data/stations/")}

\arguments{
  \item{location}{name of climate station location.}
  \item{ele.c}{name of element [e.g. avail.elem(), or 't2m', 'rr',
    'slp'].}
  \item{silent}{TRUE: no printing}
  \item{direc}{name of directory in which the data are stored.}
 }
\value{a list of "monthly.station.record" class:
  \tabular{ll}{
    val \tab The monthly values (a 12-column matrix with one
    column for each year). \cr
    station \tab station number. \cr
    yy \tab The years of observation (vector). \cr
    lat,lon \tab Latitude and longitude of the location. \cr
    x.0E65N,y.0E65N \tab Distance in km from 0E, 65N. \cr
    location \tab Name of location . \cr
    wmo.no \tab WMO number. \cr
    start \tab Start of observatins from this location. \cr
    yy0 \tab First year in current record. \cr
    ele \tab Code of theelement. \cr
    obs.name \tab Name of the element. \cr
    unit \tab Unit of the element. \cr
    country \tab The country in which the location is
    located. \cr
    quality \tab Code/description for data quality. \cr
    found \tab Flag: T - the data requested was found. \cr
    ref \tab Reference for the data set. \cr
  }}
\author{R.E. Benestad}}
\examples{
\dontrun{
oslo.t2m.dnmi <- getdnmi("oslo")
ferder.t2m.dnmi <- getdnmi("ferder")
}
}
\keyword{file}

\eof
\name{getgiss}
\alias{getgiss}
\title{Retrieve station record from the GISS data set from URL.}
\description{Reads the data from GISS available at URL:
  \url{http://www.smhi.se/hfa_coord/nordklim/}.  Also see
  \code{\link{getdnmi}} and \code{\link{getnacd}}.

Use eg \code{options(timeout=120)} if problems with retreaving the
data. Some times, the code doesn't manage to read the data, and
returns with the message: "cannot open: HTTP status was '404 Not
Found'". Try again, since slow connections cause this problem.
One trick that often helps is to use the function to get the name of
the station (\code{stations <- getgiss()}), then use a browser
(Mozilla) to open the data file from
\url{http://www.giss.nasa.gov/data/update/gistemp/station_data/}, and
then call \code{getgiss} again with the station details.
}
\usage{getgiss(stnr=NULL,location=NULL,lon=NULL,lat=NULL,stations=NULL,silent=FALSE)}

\arguments{
  \item{stnr}{Station number.}
  \item{location}{Name of locvation.}
  \item{lon}{longitude. If both \code{lon} and \code{lat} are
  specified and the other arguments are not, then find the closest station.}
  \item{lat}{latitude.}
  \item{stations}{a list object with details of GISS stations
  (Prescribing this saves time).}
  \item{silent}{For verbose use.}
}
  \value{a <- list of "monthly.station.record" class:
    \tabular{ll}{
    val \tab The monthly values (a 12-column matrix with one
    column for each year). \cr
    station \tab station number. \cr
    yy \tab The years of observation (vector). \cr
    lat,lon \tab Latitude and longitude of the location. \cr
    x.0E65N,y.0E65N \tab Distance in km from 0E, 65N. \cr
    location \tab Name of location . \cr
    wmo.no \tab WMO number. \cr
    start \tab Start of observatins from this location. \cr
    yy0 \tab First year in current record. \cr
    ele \tab Code of theelement. \cr
    obs.name \tab Name of the element. \cr
    unit \tab Unit of the element. \cr
    country \tab The country in which the location is
    located. \cr
    quality \tab Code/description for data quality. \cr
    found \tab Flag: T - the data requested was found. \cr
    ref \tab Reference for the data set. \cr
  }
or a list of station details if the requested station was not found.
}
\author{R.E. Benestad}}
\examples{
\dontrun{
obs.oxford <- getgiss(location="Oxford")  # Takes longer time
stations <- getgiss()
obs.oxford <- getgiss(location="Oxford",stations=stations) #Quicker
plotStation(obs.oxford)
obs.broome <- getgiss(stnr="501942030004",stations=stations)
obs.120E.40S <- getgiss(lon=120,lat=-40,stations=stations)
}
}
\keyword{file}

\eof
\name{getnacd}
\alias{getnacd}
\alias{nacd.meta}
\alias{meta.nacd}
\title{Retreave station record from the NACD set.}
\description{Retrieve station record from the North Atlantic Climate
  Data (NACD) set: URL \url{http://www.dmi.dk/}. Also see
  \code{\link{getdnmi}} and \code{\link{getnordklim}}.
}
\usage{
getnacd(location="prompt",ele.c='101',ascii=FALSE,silent=FALSE,direc="data")
}

\arguments{
  \item{location}{name of climate station location or NACD station number.}
  \item{ele.c}{name of element [e.g. avail.elem(), or 't2m', 'rr', 'slp'].}
  \item{ascii}{Flag. T -> force ascii read, otherwise look for
    R-formatted verion (faster).}
  \item{silent}{Flag. F -> print error messages.}
  \item{direc}{name of directory in which the data are stored.}
 }
\value{a <- list of "monthly.station.record" class:
  \tabular{ll}{
    val \tab The monthly values (a 12-column matrix with one
    column for each year). \cr
    station \tab station number. \cr
    yy \tab The years of observation (vector). \cr
    lat,lon \tab Latitude and longitude of the location. \cr
    x.0E65N,y.0E65N \tab Distance in km from 0E, 65N. \cr
    location \tab Name of location . \cr
    wmo.no \tab WMO number. \cr
    start \tab Start of observatins from this location. \cr
    yy0 \tab First year in current record. \cr
    ele \tab Code of theelement. \cr
    obs.name \tab Name of the element. \cr
    unit \tab Unit of the element. \cr
    country \tab The country in which the location is
    located. \cr
    quality \tab Code/description for data quality. \cr
    found \tab Flag: T - the data requested was found. \cr
    ref \tab Reference for the data set. \cr
  }}
\author{R.E. Benestad}}
\examples{
\dontrun{
helsinki.rr <- getnacd("helsinki",ele=601)
obs.t2m <- getnacd()
}
}
\keyword{file}

\eof
\name{getnordklim}
\alias{getnordklim}
\alias{meta}
\title{Retrieve station record from the Nordklima set.}
\description{Reads the data from Nordklim available at URL:
  \url{http://www.smhi.se/hfa_coord/nordklim/}.  Also see
  \code{\link{getdnmi}} and \code{\link{getnacd}}.
}
\usage{getnordklim(location="prompt",ele.c='101',ascii=FALSE,silent=FALSE,direc="data")}

\arguments{
  \item{location}{ name of climate station location.}
  \item{ele.c}{ name of element [e.g. avail.elem(), or 't2m', 'rr', 'slp'].}
  \item{ascii}{ Flag. T -> force ascii read, otherwise look for
    R-formatted verion (faster).}
  \item{silent}{ Flag. F -> print error messages.}
  \item{direc}{ name of directory in which the data are stored.}
}
  \value{a <- list of "monthly.station.record" class:
    \tabular{ll}{
    val \tab The monthly values (a 12-column matrix with one
    column for each year). \cr
    station \tab station number. \cr
    yy \tab The years of observation (vector). \cr
    lat,lon \tab Latitude and longitude of the location. \cr
    x.0E65N,y.0E65N \tab Distance in km from 0E, 65N. \cr
    location \tab Name of location . \cr
    wmo.no \tab WMO number. \cr
    start \tab Start of observatins from this location. \cr
    yy0 \tab First year in current record. \cr
    ele \tab Code of theelement. \cr
    obs.name \tab Name of the element. \cr
    unit \tab Unit of the element. \cr
    country \tab The country in which the location is
    located. \cr
    quality \tab Code/description for data quality. \cr
    found \tab Flag: T - the data requested was found. \cr
    ref \tab Reference for the data set. \cr
  }}
\author{R.E. Benestad}}
\examples{
\dontrun{
helsinki.rr <- getnordklim("helsinki",ele=601)
}
}
\keyword{file}

\eof
\name{grd.box.ts}
\alias{grd.box.ts}
\title{Grid box time series}
\description{Plots time series from field objects, eg from
  \code{\link{retrieve.nc}}. Uses a bilinear interpolation scheme
  (\code{link{interp}}) from the \code{akima} package.}
\usage{
grd.box.ts(x,lon,lat,what="abs",greenwich=TRUE,mon=NULL,
                       col="grey10",lwd=1,lty=1,pch=26,add=FALSE,
                       filter=NULL,type="l",main=NULL,sub=NULL,xlab=NULL,ylab=NULL,
                       xlim=NULL,ylim=NULL)
}
\arguments{
    \item{x}{A field object.}
    \item{lon}{Longitude to plot.}
    \item{lat}{Latitude to plot.}
    \item{what}{What to draw: "ano"-> anomalies, "cli"-> climatological
      values, "abs" -> absolute values.}
    \item{greenwich}{Maps centre on the Greenwich meridian.}
    \item{mon}{Month to extract}
    \item{col}{Colour.}
    \item{lwd}{Line width}
    \item{lty}{Line style.}
    \item{pch}{Plot character.}
    \item{add}{'TRUE' adds curve to old plot.}
    \item{filter}{If not NULL, this is a vector specifying window
      weighting argument of same name in \code{link{filter}}.}
    \item{type}{same as in plot(), only works for single time series.}
    \item{main}{Preset main title (see \code{\link{plot}}).}
    \item{sub}{subtitle}
    \item{xlab}{x label}
    \item{ylab}{y label}
    \item{xlim}{see \code{\link{plot}}}
    \item{ylim}{see \code{\link{plot}}}

}
\value{A station object with interpolated values (see \code{\link{station.obj}} and
  \code{\link{station.obj.dm}}) that can be plotted using eg \code{\link{plotStation}}.    

  }
\author{R.E. Benestad}}
\examples{
\dontrun{
slp <- retrieve.nc("ncep_slp.nc")
grd.box.ts(slp,0,60,what="ano",mon=1)
}
}
\keyword{ts}






\eof
\name{helsinki.t2m}
\alias{helsinki.t2m}
\title{Monthly mean temperature in Helsinki.}
\description{A station record of monthly mean temperature from Helsinki.}
\usage{data(helsinki.t2m)}
\format{a <- list of "monthly.station.record" class:
    \tabular{ll}{
    val \tab The monthly values (a 12-column matrix with one
    column for each year). \cr
    station \tab station number. \cr
    yy \tab The years of observation (vector). \cr
    lat,lon \tab Latitude and longitude of the location. \cr
    x.0E65N,y.0E65N \tab Distance in km from 0E, 65N. \cr
    location \tab Name of location . \cr
    wmo.no \tab WMO number. \cr
    start \tab Start of observatins from this location. \cr
    yy0 \tab First year in current record. \cr
    ele \tab Code of theelement. \cr
    obs.name \tab Name of the element. \cr
    unit \tab Unit of the element. \cr
    country \tab The country in which the location is
    located. \cr
    quality \tab Code/description for data quality. \cr
    found \tab Flag: T - the data requested was found. \cr
    ref \tab Reference for the data set. \cr
  }}
\source{The Nordklim data set: \url{http://www.smhi.se/hfa_coord/nordklim/}}
\references{Tuomenvirta et al. (2001), "Nordklim data set 1.0", DNMI
  KLIMA 08/01, pp. 26; \cr
  The Norwegian Meteorological Institute, P.O. Box 43, 0313
Oslo, Norway (http://www.met.no).}
\examples{
}
\keyword{datasets}

\eof
\name{instring}
\alias{instring}
\title{instring}
\description{Finds the position of a character in a string (character
  vector). Similar to regexpr(), but a test with regexpr() failed with
  some characters. instring() returns all position with a character
  match, whereas regexpr() only returns the first position for a pattern
  match.}
\usage{instring(c,target,case.match=TRUE)
}
\arguments{
    \item{c}{Character to look for.}
    \item{target}{string to search.}
    \item{case.match}{FALSE -> not case sensitive.}
  }
\value{vector of intigers.}
\author{R.E. Benestad}
\examples{
instring("e","efile.dat")
# 1 5
regexpr("e","efile.dat")
#[1] 1
#attr(,"match.length")
#[1] 1 
# Case when regexpr() doesn't give the desired result:
regexpr(".","file.name")
#[1] 1
#attr(,"match.length")
#[1] 1
instring(".","file.name")
#[1] 5
}
\keyword{character}

\eof
\name{julday}
\alias{julday}
\title{Converts from month, day, and year to Julian days}
\description{The function computes Julian
  days from month, day, and year. The code is based on the algortithm
  from Press et al. (1989), "Numerical Recipes  
  in Pascal", Cambridge, p. 10. See also \code{chron} and \code{date}
for similar functions. This function was included to avoid the
dependency to the \code{chron} and \code{date} packages. See also \code{\link{caldat}}.}
\usage{julday(mm,id,iyyy)}
\arguments{
    \item{mm}{month.}
    \item{id}{day.}
    \item{iyyy}{year.}
 }
\value{real}
\author{R.E. Benestad}}
\examples{
julday(1,1,1)                       # 1721424
julday(1,1,1970)                    # 2440588
julday(9,4,2003)                    # 2452887
julday(9,4,2003)-julday(1,1,1970)   # 12299
julday(9,4,2003)-julday(1,1,2003)   # 246
julday(1,1,2003)-julday(1,1,2002)   # 365
julday(1,1,2001)-julday(1,1,2000)   # 366
}
\keyword{manip}

\eof
\name{km2lat}
\alias{km2lat}
\title{Convert long-lat to km-km}
\description{The function computes the latitude from given
  the distance from a reference point. See also \code{\link{km2lon}} and \code{\link{COn0E65N}}.}
\usage{km2lat(x, y, x.centre=0, y.centre=65)}
\arguments{
    \item{x}{not used.}
    \item{y}{distance from reference latitude in meridional direction.}
    \item{x.centre}{reference longitude.}
    \item{y.centre}{reference latitude.}
 }
\value{real}
\author{R.E. Benestad}}
\examples{
library(clim.pact)
data(oslo.t2m)
print(c(oslo.t2m$lon,oslo.t2m$lat))
#[1] 10.71667 59.95000
xy<-COn0E65N(oslo.t2m$lon,oslo.t2m$lat)
oslo.t2m$lon<-xy$x
oslo.t2m$lat<-xy$y
print(c(oslo.t2m$lon,oslo.t2m$lat))
#[1]  595.4086 -560.3004
lon<-km2lon(oslo.t2m$lon,oslo.t2m$lat,x.centre=0,y.centre=65)
lat<-km2lat(oslo.t2m$lon,oslo.t2m$lat,x.centre=0,y.centre=65)
print(c(lon,lat))
#[1] 10.71667 59.95000
}
\keyword{manip}

\eof
\name{km2lon}
\alias{km2lon}
\title{Convert long-lat to km-km}
\description{The function computes the longitude from given
  the distance from a reference point. See also \code{\link{km2lat}} and \code{\link{COn0E65N}}.}
\usage{km2lon(x, y, x.centre=0, y.centre=65)}
\arguments{
    \item{x}{not used.}
    \item{y}{distance from reference latitude in meridional direction.}
    \item{x.centre}{reference longitude.}
    \item{y.centre}{reference latitude.}
}
\value{real}
\author{R.E. Benestad}}
\examples{
library(clim.pact)
data(oslo.t2m)
print(c(oslo.t2m$lon,oslo.t2m$lat))
#[1] 10.71667 59.95000
xy<-COn0E65N(oslo.t2m$lon,oslo.t2m$lat)
oslo.t2m$lon<-xy$x
oslo.t2m$lat<-xy$y
print(c(oslo.t2m$lon,oslo.t2m$lat))
#[1]  595.4086 -560.3004
lon<-km2lon(oslo.t2m$lon,oslo.t2m$lat,x.centre=0,y.centre=65)
lat<-km2lat(oslo.t2m$lon,oslo.t2m$lat,x.centre=0,y.centre=65)
print(c(lon,lat))
#[1] 10.71667 59.95000
}
\keyword{manip}

\eof
\name{koebenhavn.t2m}
\alias{koebenhavn.t2m}
\title{Monthly mean temperature in Copenhagen.}
\description{A station record of monthly mean temperature Copenhagen.}
\usage{data(koebenhavn.t2m)}
\format{list of "monthly.station.record" class:
    \tabular{ll}{
    val \tab The monthly values (a 12-column matrix with one
    column for each year). \cr
    station \tab station number. \cr
    yy \tab The years of observation (vector). \cr
    lat,lon \tab Latitude and longitude of the location. \cr
    x.0E65N,y.0E65N \tab Distance in km from 0E, 65N. \cr
    location \tab Name of location . \cr
    wmo.no \tab WMO number. \cr
    start \tab Start of observatins from this location. \cr
    yy0 \tab First year in current record. \cr
    ele \tab Code of theelement. \cr
    obs.name \tab Name of the element. \cr
    unit \tab Unit of the element. \cr
    country \tab The country in which the location is
    located. \cr
    quality \tab Code/description for data quality. \cr
    found \tab Flag: T - the data requested was found. \cr
    ref \tab Reference for the data set. \cr
  }}
\source{The Nordklim data set: \url{http://www.smhi.se/hfa_coord/nordklim/}}
\references{Tuomenvirta et al. (2001), "Nordklim data set 1.0", DNMI
  KLIMA 08/01, pp. 26;
  The Norwegian Meteorological Institute, P.O. Box 43, 0313
Oslo, Norway (http://www.met.no).}
\examples{
}
\keyword{datasets}

\eof
\name{lagStation}
\alias{lagStation}
\title{Introduce a lag in station values}
\description{Shifts the station values in time: introduce a lag} 
\usage{lagStation(x,lag=0)}
\arguments{
    \item{x}{A station object (see \code{\link{station.obj}}).}
    \item{lag}{lag}
  }
\value{Astation object}
\author{R.E. Benestad}}
\examples{
data(oslo.t2m)
oslo.t2m.1 <- lagStation(oslo.t2m,1)
plotStation(oslo.t2m,mon=1,what="t")
plotStation(oslo.t2m.1,add=TRUE,mon=1,what="t",col="darkblue")
}
\keyword{manip}

\eof
\name{lower.case}
\alias{lower.case}
\title{convert to lower case}
\description{Converts characters to lower case.}
\usage{lower.case(u.case)}
\arguments{\item{u.case}{Strings or arrays of strings}.}
\value{converted strings or arrays of strings.}
\author{R.E. Benestad}}
\examples{
       print(upper.case(c("qwerty  e","asdf  rT")))       #  "QWERTY" "ASDF"
       print(lower.case(c("QWERTY","ASDF")))              #  "qwErty" "asdf"
       print(strip(c("Hello there!","Oslo"," ","NA ")))   # "Hello" "Oslo"  " "     "NA"
}
\keyword{character}

\eof
\name{map}
\alias{map}
\title{Produce a map}
\description{Produces maps.}
\usage{map(x,y=NULL,col="black",lwd=1,lty=1,sym=TRUE,
               plot=TRUE,inv.col=FALSE,add=FALSE,las = 1,
                    levels=NULL,main=NULL,sub=NULL,xlim=NULL,ylim=NULL)}
\arguments{
    \item{x}{A map object.}
    \item{y}{A map object. If given, \code{map.map} plots the
      difference: x - y}
    \item{col}{Colour of contours.}
    \item{lwd}{Contour line width.}
    \item{lty}{Contour line style.}
    \item{sym}{Symmetry: if True, use zlimits c(-|max|,+|max|).}
    \item{plot}{TRUE gives graphics}
    \item{inv.col}{Inverse color scheme (e.g. 'TRUE' gives red for drier
      and blue for wetter conditions)}.
    \item{add}{Add to plot: add contours only.}
    \item{las}{see \code{\link{par}}}
    \item{levels}{see \code{\link{contour}}}
    \item{main}{see \code{\link{plot}}}
    \item{sub}{see \code{\link{plot}}}
    \item{xlim}{see \code{\link{plot}}}
    \item{ylim}{see \code{\link{plot}}}
 }
\value{A map object}
\author{R.E. Benestad}}
\examples{
}
\keyword{hplot}

\eof
\name{map.eof}
\alias{map.eof}
\alias{mapEOF}
\title{Map eof}
\description{Draws maps of the spatial structures described by the EOF
  (\code{\link{EOF}} patterns. Is similar to \code{\link{plotEOF}}, but
  only plots the spatial information. Useful for comparing the spatial
  patterns in different EOFs.} 
\usage{map.eof(x,i.eof=1,nlevs=9,add=FALSE,
            col=c("red","blue","darkgreen","steelblue"),lwd=2,lty=1)
       mapEOF(x,i.eof=1,nlevs=5,add=FALSE,
            col=c("red","blue","darkgreen","steelblue"),lwd=2,lty=1)}
\arguments{
    \item{x}{ A field object. }
    \item{i.eof}{The EOF to plot.}
    \item{nlevs}{Number of contour levels. }
    \item{add}{Add a map on pre-existing map - see contour.}
    \item{col}{Colour.}
    \item{lwd}{Line width.}
    \item{lty}{Line type.}
  }
\value{A map object (currently, only the last field in a mixed.field object).}
\author{R.E. Benestad}}
\examples{
library(clim.pact)
data(eof.slp)
map.eof(eof.slp)
map.eof(eof.slp,i.eof=2,col="blue",add=TRUE)
}
\keyword{hplot}

\eof
\name{mapField}
\alias{mapField}
\title{MapField}
\description{Draws maps of fields in a field object, eg read using \code{\link{retrieve.nc}}.}
\usage{mapField(x,l=NULL,greenwich=TRUE,
                     what="ano",method="nice",val.rng=NULL,
                     col="black",col.coast="grey",lwd=2,lty=1,
                     add=FALSE,las = 1,levels=NULL,xlim=NULL,ylim=NULL)
\arguments{
    \item{x}{ A field object. }
    \item{l}{The field to map. Default: the last field in the record.}
    \item{what}{What to draw: "ano"-> anomalies, "cli"-> climatological
    values, "abs" -> absolute values. }
  \item{method}{"nice" -> \code{filled.contour}, otherwise use
    \code{image}.}
    \item{val.rng}{Valid range: interval used for colour scale.}
    \item{greenwich}{'TRUE' centres on Greenwich meridian.}
    \item{col}{Contour line colour for levels.}
    \item{col.coast}{Contour line colour for coast lines.}
    \item{lwd}{Line width.}
    \item{lty}{Line type.}
    \item{add}{Adds map to old figure.}
    \item{las}{See \code{\link{par}}}
    \item{levels}{See \code{\link{contour}}}
    \item{xlim}{see \code{\link{plot}}}
    \item{ylim}{see \code{\link{plot}}}
  }
\value{}
\author{R.E. Benestad}}
\examples{
library(clim.pact)
\dontrun{
skt<-retrieve.nc("skt.mon.mean.nc",
                 x.rng=c(-90,50),y.rng=c(0,75))
bitmap("ncep.skt.jpg",type="jpeg")
mapField(skt)
dev.off()
}
}
\keyword{hplot}

\eof
\name{meanField}
\alias{meanField}
\title{Mean field}
\description{Computes a map showing the mean field values.}
\usage{meanField(x,lon.rng=NULL,lat.rng=NULL,t.rng=NULL,mon=NULL)}
\arguments{
    \item{x}{A field object.}
    \item{lon.rng}{Extract the longitude interval.}
    \item{lat.rng}{Extract the latitude interval.}
    \item{t.rng}{Extract the time interval. Can be numerical (year) or character (date, e.g. "01-Jan-1998"}
    \item{mon}{Month (1-12) or season (1-12) to extract if !is.null.}
 }
\value{A map object}
\author{R.E. Benestad}}
\examples{
\dontrun{
slp <- retrieve.nc("ncep_slp.nc",x.rng=c(5,12),y.rng=c(58,63))
mslp <- meanField(slp)
}
}
\keyword{manip}

\eof
\name{mergeEOF}
\alias{mergeEOF}
\title{Merge EOFs}
\description{Merges two EOF objects by making the first one resembling
the second (a bit similar to \code{\link{mergeStation}}). Can be used
for reconstructing fields.} 
\usage{mergeEOF((eof1,eof2,plot=TRUE,silent=FALSE,method="lm",
               match="time",cut.off=8,adjust=TRUE))}
\arguments{
    \item{eof1}{The EOF object (see \code{\link{EOF}}) for the earliest data (assuming this
    data set contains most errors).}
    \item{eof2}{The EOF object (see \code{\link{EOF}}) for the most recent data (assuming this
    data set contains less errors)}
    \item{plot}{if 'TRUE' then plot diagnostics}
    \item{silent}{if 'TRUE' then do not print out diagnostics.}
    \item{method}{"lm" or "matrix projection" (G. Strang (1988),
    "Linear algrebra and its applications", Hartcourt Brace & Company,
    3rd ed.(p.147))}
    \item{match}{"time" or "space"}
    \item{cut.off}{How many EOFs to include}
    \item{adjust}{TRUE: apply \code{\link{adjust.eof}} to results.}
  }
\value{An 'eof' object.}
\author{R.E. Benestad}}
\examples{
\dontrun{
data(DNMI.slp)
NCEP.slp<-retrieve.nc("~/data/ncep/slp.mon.mean.nc",
                    x.rng=c(-90,50),y.rng=c(0,75))

#--------------------------------------------------
# Need to fix some details of the NCEP.slp object (only for 
# proper 'housekeeping')

NCEP.slp$dd[] <- 15
attr(NCEP.slp$tim,unit') <- "month"
class(NCEP.slp) <- c("field","monthly.field.object")
#---------------------------------------------------

eof1 <- EOF(DNMI.slp,mon=1)
eof2 <- EOF(NCEP.slp,mon=1)
eof <- mergeEOF(eof1,eof2)
}
}
\keyword{manip}

\eof
\name{mergeStation}
\alias{mergeStation}
\title{Merge climate station series.}
\description{Merges two series from different sources, eg from NACD
  (\code{\link{getnacd}}) and DNMI (\code{\link{getdnmi}}). The code is
  useful for updating long climate series with new observations from a
  different database. The routine cokpares data for overlapping times
  and prints out diagnostics about the two data sets.}
\usage{mergeStation(x.1,x.2,plot=FALSE)}
\arguments{
  \item{x.1}{1st series.}
  \item{x.2}{2nd series.}
  \item{plot}{'TRUE' plots the overlap.}
  }
\value{A climate station series object.}
\author{R.E. Benestad}}
\examples{
\dontrun{
oslo.1 <- getnacd("OSLO-BLINDERN")
oslo.2 <- getdnmi("oslo")
print(range(oslo.1$yy))
#[1] 1890 1990
print(range(oslo.2$yy))
#[1] 1937 2002
oslo <- mergeStation(oslo.1,oslo.2)
#[1] "Time intervals:"
#[1] 1890 1990
#[1] 1937 2002
#[1] 1937.042 1990.958
#[1] "RMSE:  0.04"
#
#Call:
#lm(formula = y ~ 1 + x, data = ovrlp)
#
#Residuals:
#     Min       1Q   Median       3Q      Max 
#-7.24005 -0.03271  0.01161  0.06006  7.61593
#Coefficients:
#            Estimate Std. Error t value Pr(>|t|)    
#(Intercept) 0.029044   0.047482   0.612    0.541    
#x           0.993886   0.004866 204.231   <2e-16 ***
#---
#Signif. codes:  0 `***' 0.001 `**' 0.01 `*' 0.05 `.' 0.1 ` ' 1 
#
#Residual standard error: 0.9738 on 644 degrees of freedom
#Multiple R-Squared: 0.9848,	Adjusted R-squared: 0.9848 
#F-statistic: 4.171e+04 on 1 and 644 DF,  p-value: < 2.2e-16

print(range(oslo$yy))
#[1] 1890 2002
}
}
\keyword{manip}

\eof
\name{mixFields}
\alias{mixFields}
\title{mixFields}
\description{Mix fields by combining two different gridded sets of
  observation. Observations/data for representing values at n different
  locations at a given time (t) can be described in terms of a
  vector
  \deqn{\vec{x}(t) = [x_1, x_2, ... x_n].}{x(t)=[x_1, x_2,
    ... x_n].}
  Two different sets of observations can be represented by two vectors
  y and z of lengths n and m respectively. In mix.fields, the
  information in these two data sets are combined combining the two vectors:
  \deqn{\vec{x}(t) = [\vec{y}(t),\vec{z}(t)] =
    [y_1, y_2, ... y_n, z_1, z_2, ... z_m].}{
    x(t)=[y(t), z(t)]= [y_1, y_2, ... y_n, z_1, z_2, ... z_m].}
  The length of the final vector of the mixed field is the sum of the
  lengths of the two respective vectors. The two data sets do not have
  to be on the same grid.

  reference: Bretherton et al. (1992) "An
  Intercomparison of Methods for finding Coupled Patterns in Climate
  Data", \emph{J. Climate}, \bold{vol 5}, 541-560.

  The output from \code{mixFields} can be used in \code{\link{EOF}}
  to compute mixed-common EOFs which subsecuently can be used as
  predictors in \code{\link{DS}} in order to downscale climate scenarios
  (Benestad et al. (2002), "Empirically downscaled temperature scenarios
  for Svalbard", \emph{Atm. Sci. Lett.}, doi.10.1006/asle.2002.0051).
}  
\usage{
mixFields(field.1,field.2,mon=NULL,interval=NULL) 
}
\arguments{
    \item{field.1}{A 'field.object'.}
    \item{field.2}{A 'field.object'.}
    \item{mon}{Calendar month to extract.}
    \item{interval}{Time interval to extract.}
  }
\value{A 'field.object'.}
\author{R.E. Benestad}
\examples{
\dontrun{
library(clim.pact)
x.1 <- retrieve.nc("/home/kareb/data/ncep/ncep_t2m.nc",
                   x.rng=c(-60,40),y.rng=c(50,75))
x.2 <- retrieve.nc("/home/kareb/data/ncep/ncep_slp.nc",
                   x.rng=c(-60,40),y.rng=c(50,75))
print(x.1$v.name)

print("Read GCM predictor data.")
X.1 <- retrieve.nc("data/mpi-gsdio_t2m.nc",
                   x.rng=c(-60,40),y.rng=c(50,75))
X.2 <- retrieve.nc("data/mpi-gsdio_slp.nc",
                   x.rng=c(-60,40),y.rng=c(50,75))
print(X.1$v.name)
print("Cat fields.")
xX.1 <- catFields(x.1,X.1,interval.1=c(1958,1998),interval.2=c(1958,2050))
xX.2 <- catFields(x.2,X.2,interval.1=c(1958,1998),interval.2=c(1958,2050))
xX <- mixFields(xX.1,xX.2,mon=1,
                 interval=c(1900,2050))
print("EOF")
eof.c <- eof(xX.1,mon=1)
eof.mc <- eof(xX,mon=1)
}
}
\keyword{models}

\eof
\name{mod}
\alias{mod}
\title{Modulus of a division.}
\description{Returns the modulus of a division: returns the remainder of
the expression x/y.}
\usage{mod(x,y)}
\arguments{
  \item{x}{nominator (integer).}
  \item{y}{denominator (integer).}
}
\value{integer value from 0 .. (y-1)}
\author{R.E. Benestad}}
\examples{
mod(101,10)   # 1
mod(4,12)     # 4
mod(123,12)   # 3
}
\keyword{arith}


\eof
\name{newFig}
\alias{newFig}
\title{Create a new Window}
\description{Creates a new window by calling the appropriate device, eg
  \code{\link{x11}}(), \code{windows()}, \code{\link{pdf}}(), \code{\link{postscript}}(),ect.}
\usage{newFig()}
\arguments{
}
\value{}
\author{R.E. Benestad}}
\examples{
}
\keyword{device}

\eof
\name{num2str}
\alias{num2str}
\alias{strings}
\alias{characters}
\title{Convert numbers to string and format}
\description{Convert numbers to string and format. Similar to FORTRAN
  'F8.2' format statement.}
\usage{num2str(x,dec=2,f.width=NULL,d.point=".")}
\arguments{ \item{x}{Real numbers.}
            \item{dec}{number of decmal points.}
            \item{f.width}{width of field.}
            \item{d.point}{character marking the decimal point.}
\value{string.}
\author{R.E. Benestad}}
\examples{
print(num2str(c(1,23.4282,-3.14),dec=3))
#[1] "1.000"  "23.428" "-3.140"
}
\keyword{character}

\eof
\name{objDS}
\alias{climate analysis}
\alias{objDS}
\alias{downscaling}
\title{Objective downscaling of monthly means}
\description{'Objective' downscaling based on \code{\link{DS}}. The
function selects region according to a correlation analysis, setting
the borders where the correlation with the station series become
zero. A fit to a truncated Fourier expansion is used to describe
profiles of correlation coefficients in zonal and meridional
directions from where the station is located.
}
\usage{objDS(field.obs,field.gcm,station,plot=TRUE,positive=NULL,
          mon=NULL,direc="output/",cal.id=NULL,
          ldetrnd=TRUE,i.eofs=seq(1,8,by=1),ex.tag="",
          method="lm",leps=FALSE,param="t2m",
          plot.res=FALSE,plot.rate=FALSE,xtr.args="",
          swsm="step",predm="predict",lsave=TRUE,rmac=TRUE,
          silent=FALSE)}

\arguments{
    \item{field.obs}{ The gridded observation predictor \code{\link{retrieve.nc}}.}
    \item{field.gcm}{ The climate simulation predictor \code{\link{retrieve.nc}}.}
    \item{station}{ A climate.station object (\code{\link{station.obj}} or 
        \code{\link{station.obj.dm}}). 
        [e.g. from \code{getnacd}, \code{getnordklim} or \code{station.obj}].}
    \item{plot}{'TRUE' produces figures.}
    \item{positive}{'TRUE': only consider the region where correlations
      are positive (important for temperature predictors).}
    \item{mon}{ month or season to downscale,loops though  the 12
      calendar months if NULL.}
    \item{direc}{ name of directory inwhich the output is dumped
          (e.g. figures, tables).}
    \item{cal.id}{ID tag used for calibration. By default use the 
	first field (\code{\link{catFields}}) for calibration.}
    \item{ldetrnd}{ F for no detrending; T for removing linear trends
	before model calibration.}
    \item{i.eofs}{ select which EOFs to include in the setp-wise screening.}
    \item{ex.tag}{Extra labelling tag for file names for experiments.}
    \item{method}{Sets the method to use for regression. Method is set
      to "lm" by default, but "anm" allows the incorporation of an
      analog model, see \code{\link[anm]{anm}}. "anm.weight" weights the
    principal components according to the eigenvalues, whereas "anm"
    uses unweighted series.}
    \item{leps}{'TRUE' produces EPS figures (files).}
    \item{param}{Name of parameter (for plot labels).}
    \item{plot.res}{'TRUE' shows statistics for residuals.}
    \item{plot.rate}{'TRUE' shows analysis of rate-of-change.}
    \item{xtr.args}{Extra/additional arguments in the formula.}
    \item{swsm}{Step-wise screening method, default=='step'; 'none'
      skips stepwise sceeening.}
    \item{predm}{Prediction method, default is "predict"}.
    \item{lsave}{TRUE -> saves the result on disc}.
    \item{rmac}{TRUE -> subtracts (removes) the annual cycle in station
      data.}
    \item{silent}{TRUE -> no output to screen.}.
}

\value{An 'objDS' object -  a list of objects:
  \tabular{rl}{
   station \tab a 'station' object  (see \code{\link{getnacd}}) \cr
   Jan    \tab a 'ds' (see \code{\link{DS}}) object \cr
   Feb    \tab a 'ds' object \cr
   Mar    \tab a 'ds' object \cr
   Apr    \tab a 'ds' object \cr
   May    \tab a 'ds' object \cr
   Jun    \tab a 'ds' object \cr
   Jul    \tab a 'ds' object \cr
   Aug    \tab a 'ds' object \cr
   Sep    \tab a 'ds' object \cr
   Oct    \tab a 'ds' object \cr
   Nov    \tab a 'ds' object \cr 
   Dec    \tab a 'ds' object \cr 
  }
}
\author{R.E. Benestad}}
\examples{
\dontrun{
library(clim.pact)
oslo<-getnordklim("Oslo-Blindern")
slp.obs <- retrieve.nc("ncep_slp.nc")         # Get gridded observations/analysis from NCEP
slp.gcm <- retrieve.nc("EH4OPYC_B2_slp.nc")   # Get results from climate models
ds <- objDS(field.obs=slp.obs,field.gcm=slp.gcm,station=oslo)

t2m <- retrieve.nc("~/data/analysis/DNMI_t2m.nc")
t2m.gcm <- retrieve.nc("~/data/mpi/mpi-gsdio_t2m.nc",
           x.rng=range(t2m$lon),y.rng=range(t2m$lat))
ds <- objDS(field.obs=t2m,field.gcm=t2m.gcm,station=oslo)
}
}
\keyword{models}
\keyword{multivariate}
\keyword{ts}
\keyword{spatial}

\eof
\name{oslo.dm}
\alias{oslo.dm}
\title{Daily Oslo record.}
\description{A station record of daily mean temperature and daily
  precipitation from Oslo-Blindern.}
\usage{data(oslo.dm)}
\format{a "daily.station.record"-class object.
  \tabular{ll}{
  t2m \tab a vector holding daily mean temperature. \cr
  precip \tab a vector holding daily precipitation. \cr
  dd \tab a vector holding day of month.\cr
  mm \tab a vector holding the month.\cr
  yy \tab a vector holding the year.\cr
  obs.name \tab the name of observation: \cr
  \tab eg c("Daily mean temperature","Daily precipitation"). \cr
  unit \tab the unite of observation: eg c("deg C","mm/day").\cr
  ele \tab element code: eg c("tam","rr").\cr
  station \tab local (national) station number.\cr
  lat \tab latitude.\cr
  lon \tab longitude.\cr
  alt \tab altitude.\cr
  location \tab name of location. \cr
  wmo.no \tab WMO number of station.\cr
  start \tab start of measurements.\cr
  yy0 \tab first year of record.\cr
  country \tab name of country.\cr
  ref \tab reference to the data.\cr}}
\source{The Norwegian Meteorological Institute, Climatology deivision.}
\references{The Norwegian Meteorological Institute, P.O. Box 43, 0313
Oslo, Norway (http://www.met.no).}
\examples{
}
\keyword{datasets}

\eof
\name{oslo.t2m}
\alias{oslo.t2m}
\title{Monthly mean temperature in Oslo.}
\description{A station record of monthly mean temperature from Oslo-Blindern.}
\usage{data(oslo.t2m)}
\format{list of "monthly.station.record" class:
    \tabular{ll}{
    val \tab The monthly values (a 12-column matrix with one
    column for each year). \cr
    station \tab station number. \cr
    yy \tab The years of observation (vector). \cr
    lat,lon \tab Latitude and longitude of the location. \cr
    x.0E65N,y.0E65N \tab Distance in km from 0E, 65N. \cr
    location \tab Name of location . \cr
    wmo.no \tab WMO number. \cr
    start \tab Start of observatins from this location. \cr
    yy0 \tab First year in current record. \cr
    ele \tab Code of theelement. \cr
    obs.name \tab Name of the element. \cr
    unit \tab Unit of the element. \cr
    country \tab The country in which the location is
    located. \cr
    quality \tab Code/description for data quality. \cr
    found \tab Flag: T - the data requested was found. \cr
    ref \tab Reference for the data set. \cr
  }}
\source{The Nordklim data set: \url{http://www.smhi.se/hfa_coord/nordklim/}}
\references{Tuomenvirta et al. (2001), "Nordklim data set 1.0", DNMI
  KLIMA 08/01, pp. 26; \cr
  The Norwegian Meteorological Institute, P.O. Box 43, 0313
Oslo, Norway (http://www.met.no).}
\examples{
}
\keyword{datasets}

\eof
\name{patternIndex}
\alias{patternIndex}
\title{Create a Index for a spatial pattern}
\description{Create a Index for a spatial pattern identified from a map
  object, eg \code{link{corField}}, \code{link{mapField}}, or
  \code{link{composite.field}}. The index is computed using a spatial correlation.}
\usage{patternIndex(map,field,anomaly=TRUE)}
\arguments{
    \item{map}{Map describing spatial structure.}
    \item{field}{Field in which the pattern is searched.}
    \item{anomaly}{If true, compute and use the anomalies of the given field.}
 }
 \value{list containing the fields:
   \tabular{rl}{
     index \tab index \cr
     yy    \tab years \cr
     mm    \tab months \cr
     dd    \tab days \cr
   }
   }
\author{R.E. Benestad}}
\examples{
\dontrun{
sst <- retrieve.nc("DNMI_sst.nc")
data(oslo.t2m)
csst <- composite.field(sst,oslo.t2m)
patternIndex(csst,sst,anomaly=FALSE)

lsst<-mapField(sst)
patternIndex(lsst,sst)
}
}
\keyword{manip}

\eof
\name{plotStation}
\alias{plotStation}
\title{Plots monthly station records.}
\description{Plots data in the monthly station records. The data
  may be read through \link{getnacd}, \link{getnordklim},
  \link{getdnmi}, or created using \link{station.obj}. The commands
  \link{avail.elem}, \link{avail.locs} can be used to identify the
  station records available (in a given subdirectory).
}
\usage{plotStation(obs,l.anom=TRUE,mon=NULL,
                        leps=FALSE,out.dir="output",what="b",trend=TRUE,
                        type="l",pch=26,col="black",lwd=3,lty=3,add=FALSE,
                        main=NULL,sub=NULL,xlab=NULL,ylab=NULL,normal.period=NULL)}

\arguments{
  \item{obs}{A climate station series. }
  \item{l.anom}{flag: T -> plot anomalies. }
  \item{mon}{select month to plot, A value of 0 plots all
    months. mon=c(12,1,2) plots the DJF mean.  }
  \item{leps}{Flag: T -> produce EPS files (hard copy). }
  \item{out.dir}{Directory where to store hard copies.}
  \item{what}{"t"=timeseries; "d"=distribution; "b"=both.}
  \item{trend}{show best-fit polynomial (5th order) trend}
  \item{type}{same as in \code{link{plot}}.}
  \item{pch}{same as in \code{link{plot}}.}
  \item{col}{colour, same as in \code{link{plot}}.}
  \item{lwd}{line width, same as in \code{link{plot}}.}
  \item{lty}{line type, same as in \code{link{plot}}.}
  \item{add}{TRUE adds a time series to previous  (see
  \code{link{grd.box.ts}}).}
  \item{main}{Preset main title (see \code{\link{plot}}).}
  \item{sub}{subtitle}
  \item{xlab}{x label}
  \item{ylab}{y label}
  \item{normal.period}{Normal period. NULL uses the entire data. Set to \code{c(1961,1990) for the last normal period.}}
}
\value{a <- list of "monthly.station.record" class:
  \tabular{ll}{
    val \tab The monthly values (a 12-column matrix with one
    column for each year). \cr
    station \tab station number. \cr
    yy \tab The years of observation (vector). \cr
    lat,lon \tab Latitude and longitude of the location. \cr
    x.0E65N,y.0E65N \tab Distance in km from 0E, 65N. \cr
    location \tab Name of location . \cr
    wmo.no \tab WMO number. \cr
    start \tab Start of observatins from this location. \cr
    yy0 \tab First year in current record. \cr
    ele \tab Code of theelement. \cr
    obs.name \tab Name of the element. \cr
    unit \tab Unit of the element. \cr
    country \tab The country in which the location is
    located. \cr
    quality \tab Code/description for data quality. \cr
    found \tab Flag: T - the data requested was found. \cr
    ref \tab Reference for the data set. \cr
  }}
\author{R.E. Benestad}}
\examples{
\dontrun{
data(tromsoe.t2m)
plotStation(tromsoe.t2m)
}
}
\keyword{hplot}

\eof
\name{plotDS}
\alias{plotDS}
\title{Plot downscaled results}
\description{Plots the results from \code{\link{DS}}.}
\usage{plotDS(ds.obj,leps=FALSE,plot.map=TRUE,plot.res=FALSE,
plot.rate=FALSE,add=FALSE,col="darkred",lwd=2,lty=1,
                   direc="output/",main=NULL,sub=NULL,xlab=NULL,ylab=NULL)}
\arguments{
    \item{ds.obj}{A \code{\link{DS}} object.} 
    \item{leps}{'TRUE' produces EPS files.}
    \item{plot.map}{'TRUE' shows the spatial predictor pattern.} 
    \item{plot.res}{'TRUE' shows statistics for residuals.} 
    \item{plot.rate}{'TRUE' shows analysis of rate-of-change.}
    \item{add}{TRUE: adds a scenario to old time series plot.}
    \item{col}{Colour of scenario time series.}
    \item{lwd}{Line width of scenario time series.}
    \item{lty}{Line style of scenario time series.}
    \item{direc}{Directory for graphical output.}
    \item{main}{Preset main title (see \code{\link{plot}}).}
    \item{sub}{subtitle}
    \item{xlab}{x label}
    \item{ylab}{y label}
    }
\value{\code{plotDS} returns a map object for the large-scale synoptic
  (anomaly) pattern, which can be plotted on a sphere
  (\code{\link{satellite}}) or coloured map (\code{\link{map}}).}
\author{R.E. Benestad}}
\examples{
data(helsinki.t2m)
data(eof.mc)
ds.helsinki<-DS(dat=helsinki.t2m,preds=eof.mc,plot=FALSE)
plotDS(ds.helsinki,leps=TRUE)
}
\keyword{hplot}

\eof
\name{plotDSobj}
\alias{climate diagnostics}
\alias{plotDSobj}
\title{Plotting routine for objective downscaling of monthly means}
\description{Plotting routine for \code{\link{objDS}}.
}
\usage{plotDSobj(result,outdir="output",figs=c(1,2,3,4)))}

\arguments{
    \item{result}{A 'objDS' object from \code{\link{objDS}}.}
    \item{outdir}{Directory for storing EPS-files with figures}
    \item{figs}{Figs to plot: 1 - time series, 2 - time series of 
    residuals, 3 - distribution of residuals, 4 - rates of change.}
}
\value{}
}
\author{R.E. Benestad}}
\examples{
\dontrun{
library(clim.pact)
source("clim.pact/R/ds.R")
source("clim.pact/R/objDS.R")
source("clim.pact/R/catFields.R")
source("clim.pact/R/eof.R")
oslo<-getnordklim("Oslo-Blindern")
t2m <- retrieve.nc("~/data/analysis/DNMI_t2m.nc")
t2m.gcm <- retrieve.nc("~/data/mpi/mpi-gsdio_t2m.nc",
           x.rng=range(t2m$lon),y.rng=range(t2m$lat))
ds <- objDS(field.obs=t2m,field.gcm=t2m.gcm,station=oslo,lsave=FALSE,plot=FALSE)
plotDSobj(result)
}
}
\keyword{models}
\keyword{multivariate}
\keyword{ts}
\keyword{spatial}

\eof
\name{plotEOF}
\alias{plotEOF}
\title{Plot EOFs}
\description{Plots the results from an (mixed-common) EOF analysis
  (\code{\link{EOF}}). This function produces 3 plots: i) EOF map, ii)
  variances, and iii) PC time series. Hard copies are also produced in
  EPS format under the current working directory: "plotEOF\_1.eps",
  "plotEOF\_2.eps" and "plotEOF\_3.eps" respectively.
}
\usage{plotEOF(x,i.eof=1,nlevs=5,
                   col=c("red","blue","darkgreen","steelblue")),
                   main=NULL,sub=NULL)}
\arguments{
    \item{x}{An \code{\link{EOF}} object.}
    \item{i.eof}{EOF to plot.}
    \item{nlevs}{Contour levels.}
    \item{col}{Colour.}
    \item{main}{Preset main title (see \code{\link{plot}}).}
    \item{sub}{subtitle}
    }
\value{}
\author{R.E. Benestad}}
\examples{
\dontrun{
data(eof.mc)
plotEOF(eof.mc)
x11()
data(eof.dmc)
plotEOF(eof.dmc)
}
}
\keyword{hplot}

\eof
\name{plotField}
\alias{plotField}
\title{plotField}
\description{Produce 2D plots like maps and Hovmuller diagrams. A
  poor man's version of Ferret's
  \url{http://ferret.wrc.noaa.gov/Ferret/} plot
  function. \code{plot.field} is a high level command that utilises
  \code{\link{mapField}} or \code{\link{grd.box.ts}} whenever appropriate.}  
\usage{plotField(x,lon=NULL,lat=NULL,tim=NULL,mon=NULL,val.rng=NULL,
                      col="black",col.coast="grey",lty=1,lwd=1,what="ano",
                      type="l",pch=26,my.col=NULL,add=FALSE,
                      main=NULL,sub=NULL,xlab=NULL,ylab=NULL,
                      xlim=NULL,ylim=NULL)}
\arguments{
  \item{x}{A field object.}
  \item{lon}{Position for longitude. One of \code{lon, lat, tim} must be set.}
  \item{lat}{Position for latitude.}
  \item{tim}{Position for time as time index (1:length(tim).}
  \item{mon}{Month to extract.}
  \item{val.rng}{Valid range: interval used for colour scale.}
  \item{col}{Contour line colour for levels.}
  \item{col.coast}{Contour line colour for coast lines.}
  \item{lty}{Contour line type.}
  \item{lwd}{Contour line width.}
  \item{what}{Choose between "ano" - anomaly; "abs" absolute; "cli"
    climatological.}
  \item{type}{same as in plot(), only works for single time series.}
  \item{pch}{same as in plot(), only works for single time series.}
  \item{my.col}{colour palette (see \code{link{rgb}}).}
  \item{add}{TRUE adds a time series to previous  (see \code{link{grd.box.ts}}).}
  \item{main}{Preset main title (see \code{\link{plot}}).}
  \item{sub}{subtitle}
  \item{xlab}{x label}
  \item{ylab}{y label}
  \item{xlim}{see \code{\link{plot}}}
  \item{ylim}{see \code{\link{plot}}}
}
\value{}
\author{R.E. Benestad}}
\examples{
\dontrun{
skt <- retrieve.nc("skt.mon.mean.nc",x.rng=c(-90,50),y.rng=c(0,75))

# Maps of monthly mean skin temperatures:
plotField(skt,tim=1,val.rng=c(-20,20))
dev2bitmap("ncep.skt_194801.jpg",type="jpeg")


plotField(skt,tim=100,col="blue",col.coast="darkgreen",val.rng=c(-10,10))

# For adding extra points/contours:

    # From filled.contour in base
    mar.orig <- (par.orig <- par(c("mar","las","mfrow")))$mar
    on.exit(par(par.orig))

    w <- (3 + mar.orig[2]) * par('csi') * 2.54
    layout(matrix(c(2, 1), nc=2), widths=c(1, lcm(w)))
   
    par(las = 1)
    mar <- mar.orig
    mar[4] <- 1
    par(mar=mar)
# End of section affecting the window set up.

points(0,50,pch=21,col="red")
grid()
dev2bitmap("ncep.skt_195604.jpg",type="jpeg")


# A hovmuller diagram:
plotField(skt,lon=0,val.rng=c(-10,10))
dev2bitmap("ncep.skt_lontim.jpg",type="jpeg")


# A single time series:
plotField(skt,lon=-20,lat=50)

}
}
\keyword{hplot}

\eof
\name{plumePlot}
\alias{plumePlot}
\title{Plot downscaled time series as plumes}
\description{Retreives an ensemble of time series from \code{\link{DS}}
  and plots these as a plume. The routine retrieves the ds objects from disc.}
\usage{plumePlot(ds.name.list=NULL,location,mon,direc="output",
                         t.rng=c(1850,2074),r2.th=50,p.th=0.05,
                         col="darkred",lwd=2,lty=1)}
\arguments{
  \item{ds.name.list}{A list of file names holding the ds objects.}
  \item{location}{Name of location to plot.}
  \item{mon}{Month to plot.}
  \item{direc}{The subdirectory in which the ds objects are stored.}
  \item{t.rng}{Time interval to plot.}
  \item{r2.th}{R-squared theshold: only use scenarios that account for
      equal to or more than \code{r2.th} of the variance in \%.}
  \item{p.th}{p-value threshold: only use scenarios that have p-values
      equal to or less than \code{p.th}.}
  \item{col}{Colour of scenario time series.}
  \item{lwd}{Line width of scenario time series.}
  \item{lty}{Line style of scenario time series.}
 }
\value{}
\author{R.E. Benestad}}
\examples{
\dontrun{
ds.list<-avail.ds()
plumePlot(ds.list,location="OSLO-BLINDERN",mon=1)
}
}
\keyword{hplot}

\eof
\name{r2cdf}
\alias{r2cdf}
\title{Save as netCDF file.}
\description{Saves a field object, map or eof object as a netCDF file by
  creating a CDF file (ASCII) and then calling 'ncgen' through \code{system()}.}
\usage{r2cdf(filename,x,missing=-999.99,cleanup=TRUE,
                  ofs=NULL,scal=NULL)}
\arguments{
  \item{filename}{Name of file.}
  \item{x}{a Field, map, or eof object}
  \item{missing}{Missing value}
  \item{cleanup}{TRUE removes the CDF-file after the call.}
  \item{ofs}{offset: 'NULL' -> automatic setting}
  \item{scal}{scaling factor: 'NULL' -> automatic setting}
 }
\value{}
\author{R.E. Benestad}}
\examples{
\dontrun{
# Save EOFs as netCDF (use ncview or Ferret to view)
data(eof.slp)
r2cdf("test.nc",eof.slp)
#
#
slp <- retrieve.nc("data/DNMI_slp.nc")
mslp <- meanField(slp)
r2cdf("test.nc",mslp)
r2cdf("test.nc",slp)
#
slp <- cdfextract("data/nmc_slp.nc","slp",x.rng=c(-80,40),y.rng=c(20,75),
                  t.rng=c(times[is],times[is]+499),plot=FALSE)
r2cdf("test.nc",slp)
#
data(oslo.t2m)
map <- composite.field(slp,oslo.t2m)
r2cdf("test.nc",map)
#
Xdum=list(dat=slp$dat[1:10,,],lon=slp$lon,lat=slp$lat,tim=slp$tim[1:10],
          lev=NULL,v.name=slp$v.name,attributes=slp$attributes)
class(Xdum)="field"
r2cdf("test.nc",Xdum)
#
# The definition of a 'field' object is:
ny<-length(slp$lat); nx<-length(slp$lon)
slp  <- list(dat=slp$dat,lon=slp$lon,lat=slp$lat,tim=slp$tim,lev=slp$lev,
             v.name=slp$v.nam,id.x=slp$id.x,id.t=slp$id.t,
             yy=slp$yy,mm=slp$mm,dd=slp$dd,n.fld=1,
             id.lon=rep(slp$v.name,nx),id.lat=rep(slp$v.name,ny),
             attributes=dat.att)
 class(slp) <- c("field")

}
}
\keyword{file}

\eof
\name{retrieve.nc}
\alias{retrieve.nc}
\alias{field.object}
\alias{fixField}
\alias{monthly}
\title{Retrieve data from a netCDF file}
\description{\code{retrieve.nc} reads a netCDF file and picks out vectors that look like
  lngitude, latitude and time. Returns the first 3-D field in the file.
  See also \code{\link{cdfextract}} (large data files). 

This version uses \code{\link{cdfcont}} to obtain vital meta data for
handling the data in the netCDF file and constructing a 'field' object.

This routine reequres the \code{\link[ncdf]{ncdf}}-package is currently only available for Linux systems at the CRAN web sites, but the Windows version can can be obtained from \url{http://www.stats.ox.ac.uk/pub/RWin/}.

\code{fixField} is a function for eg changing the time stamp if the given time origin is wrong.
}

\usage{retrieve.nc(filename=file.path("data","ncep_t2m.nc"),v.nam="AUTO",
                        l.scale=TRUE,greenwich=TRUE,silent=FALSE,
                        x.nam="lon",y.nam="lat",z.nam="lev",t.nam="tim",
                        x.rng=NULL,y.rng=NULL,z.rng=NULL,t.rng=NULL,force.chron=TRUE)
       fixField(x,torg=NULL,t.unit=NULL,scal=NULL,offs=NULL, 
                     x.rng=NULL,y.rng=NULL,z.rng=NULL,t.rng=NULL,greenwich=TRUE)
       monthly(x,param="t2m")}

}
\arguments{
    \item{filename}{name of netCDF file.}
    \item{v.nam}{name of variable. "AUTO" -> smart search.}
    \item{l.scale}{'TRUE' uses scaling.factor and add.offset.}
    \item{greenwich}{'TRUE' centres maps on Greenwhich meridian (0 deg E).}
    \item{x.nam}{Name of x-dimension.}
    \item{y.nam}{Name of y-dimension.}
    \item{z.nam}{Name of z-dimension.}
    \item{t.nam}{Name of time-axis.}
    \item{x.rng}{Region to extract.}
    \item{y.rng}{Region to extract.}
    \item{z.rng}{Region to extract.}
    \item{t.rng}{Time interval to extract.}
    \item{force.chron}{Check for monotonic chronological order (no
      jumping back and forth in time).}
    \item{x}{a field object.}
    \item{torg}{time origin.}
    \item{t.unit}{tim unit}
    \item{scal}{scaling factor}
    \item{offs}{constant offset}
    \item{silent}{To turn off printing to console.}
    \item{param}{Parameter to convert to monthly value}
  }
  \value{A "field.object" list:
    \tabular{ll}{
      dat \tab a 3-D matrix with the data. \cr
      lon \tab a vector of longitudes.  \cr
      lat \tab a vector of latitudes.  \cr
      tim \tab a vector of times from time.0 (see attributes). \cr
      lev \tab a vector of vertical levels (NULL for single level). \cr
      v.name \tab variable name.\cr
      id.x \tab ID labels for the spatial grid (for mixed fields, see \code{\link{mixFields}}). \cr
      id.t \tab ID labels for the time axis (for combined fields). \cr
      yy \tab a vector of years corresponding to \code{tim}. \cr
      mm \tab a vector of months corresponding to \code{tim}. \cr
      dd \tab a vector of days corresponding to \code{tim}. \cr
      n.fld \tab number of fields (for mixed fields, see
      \code{\link{mixFields}}). \cr
      id.lon \tab ID labels along the longitudes (for mixed fields, see
      \code{\link{mixFields}}). \cr
      id.lat \tab ID labels along the latitudes (for mixed fields, see
      \code{\link{mixFields}}). \cr
      }.}
\author{R.E. Benestad}}
\examples{
\dontrun{
X.1 <- retrieve.nc("data/mpi-gsdio_t2m.nc",
                   x.rng=c(-60,40),y.rng=c(50,75))
X.2 <- retrieve.nc("data/mpi-gsdio_slp.nc",
                   x.rng=c(-60,40),y.rng=c(50,75))

# The definition of a 'field' object is:
ny<-length(slp$lat); nx<-length(slp$lon)
slp  <- list(dat=X.2$dat,lon=X.2$lon,lat=X.2$lat,tim=X.2$tim,lev=X.2$lev,
             v.name=X.2$v.nam,id.x=X.2$id.x,id.t=X.2$id.t,
             yy=X.2$yy,mm=X.2$mm,dd=X.2$dd,n.fld=1,
             id.lon=rep(X.2$v.name,nx),id.lat=rep(X.2$v.name,ny),
             attributes=dat.att)
 class(slp) <- c("field")

}
}
\keyword{file}

\eof
\name{reverse}
\alias{reverse}
\alias{reverse.sort}
\title{Reverse}
\description{Reverses the order of a vector.\code{reverse.sort} returns
  a sorted vector in reverse order. }
\usage{reverse(x)
reverse.sort(x)
}
\arguments{
    \item{x}{a vector}
  }
\value{a vector.}
\author{R.E. Benestad}}
\examples{
reverse(c(1,3,5,7,2,4,6,8))      # 8 6 4 2 7 5 3 1
reverse.sort(c(1,3,5,7,2,4,6,8)) # 8 7 6 5 4 3 2 1
}
\keyword{manip}

\eof
\name{rotate}
\alias{rotate}
\title{Rotate spherical coordinates}
\description{The function uses the 3-dimensional space to find vectors
  describing the locations on a sphere that correspond to a given
  longitude and latitude. Two reference points are given, one for the
  new 'north pole': 
  \deqn{\vec{r}_0 = [\cos(\phi_0)\cos(\theta_0),\sin(\phi_0),\cos(\phi_0)\sin(\theta_0)].}
  {r0 = [cos(lat.0)*cos(lon.0),sin(lat.0),cos(lat.0)*sin(lon.0).} and
  and one for a point on the same meridian \deqn{\vec{r}_x}{rx}, but closer to the
  equator. The vector corresponing to each of the longitude-latitude point is given by:
  \deqn{\vec{r}_i = [\cos(\phi_i)\cos(\theta_i),\sin(\phi_i),\cos(\phi_i)\sin(\theta_i)].}
  {r[i] =[cos(lats[i])*cos(lons[i]),sin(lats[i]),cos(lats[i])*sin(lons[i]).}

  The new spherical coordinates are computed as follows: new latitude
  (\code{phi}) is the angle between the the vectors \deqn{\vec{r}_0}{r0}
    and \deqn{\vec{r}_i}{r[i]}. The new longitude (\code{theta}) is the
      angle between the the vectors \deqn{\vec{r}_i-\vec{r}_0}{r[i]-r0} 
    and \deqn{\vec{r}_x-\vec{r}_0}{rx-r0}. The angles are estimated by
    taking the inner-product and the arc-cosine.
}
\usage{rotate(lons,lats,lon.0=NULL,lat.0=NULL)}
\arguments{
    \item{lons}{Longitude coordinates to be rotated.}
    \item{lats}{Latitude coordinates to be rotated.}
    \item{lon.0}{Longitude coordinate of point corresponding to new 'north'pole.}
    \item{lat.0}{Latitude coordinate of point corresponding to new 'north'pole.}
 }
\value{list containing \code{phi} and \code{theta}, the new spherical coordinates.}
\author{R.E. Benestad}}
\examples{
}
\keyword{manip}

\eof
\name{satellite}
\alias{polar stereographic}
\alias{satellite}
\title{Satellite view / polar stereographic}
\description{Produces polar stereographic maps / satellite views.}
\usage{satellite(map.obj,col="black",lwd=2,lty=1,add=FALSE,
                      las = 1,lon.0=NULL,lat.0=NULL,method="normal",
                      ni=100,nj=100, n.nearest=4,max.dist=3,landdata=addland2)}
\arguments{
    \item{map.obj}{a map object (\code{\link{mapField}}).}
    \item{col}{contour colours.}
    \item{lwd}{contour line width.}
    \item{lty}{contour line style.}
    \item{add}{FLAG: true adds contour onto old plot.}
    \item{las}{see \code{\link{par}}.}
    \item{lon.0}{Reference longitude: centre of map; NULL selects automatically.}
    \item{lat.0}{Reference latitude: centre of map; NULL selects
      automatically.}
    \item{method}{A choice between "normal","polarstereo", and "distance".}
    \item{ni}{Number of grid points along x-axis in new grid.}
    \item{nj}{Number of grid points along y-axis in new grid.}
    \item{n.nearest}{Number of points to use in re-gridding.}
    \item{max.dist}{The maximum inter-point distance used for re-gridding.}
    \item{landdata}{"addland" gives hiher resolution for coast lines, but is slower.}
 }
\value{}
\author{R.E. Benestad}}
\examples{
\dontrun{
x <- retrieve.nc("T2M_p.nc")
a <- mapField(x)
satellite(a)
}
}
\keyword{hplot}

\eof
\name{station.obj}
\alias{station.obj}
\alias{monthly.station.record}
\title{Make monthly climate station series object.}
\description{Create a station object for use as predictand in empirical
  downscaling on monthly data.  Also see \code{\link{station.obj.dm}}.}
\usage{station.obj(x,yy,obs.name,unit,ele=NULL, mm=NULL,
                   station=NULL,lat=NULL,lon=NULL,alt=NULL,
                   location="unspecified",wmo.no=NULL,
                   start=NULL,yy0=NULL,country=NULL,ref=NULL)}
\arguments{
  \item{x}{the data: a matrix of 12 columns holding the observations of each
  calendar month: column 1 holds January values, col 2 holds February, .. 
        col 12 holds December values.}
  \item{yy}{A vector holding the year of observation of the same length
    as each of the 12 columns. Or a vector with the same length as the data if 
    \code{mm} is given.}
  \item{mm}{a vector of months with the same length as the data (optional).}
  \item{obs.name}{the name of observation (e.g. "Temperature").}
  \item{unit}{the unite of observation (e.g. "deg C").}
  \item{ele}{element code (e.g. 101).}
  \item{station}{local (national) station number.}
  \item{lat}{latitude.}
  \item{lon}{longitude.}
  \item{alt}{altitude.}
  \item{location}{name of location.}
  \item{wmo.no}{WMO number of station.}
  \item{start}{start of measurements.}
  \item{yy0}{first year of record.}
  \item{country}{name of country.}
  \item{ref}{reference to the data.}
  }
  \value{a "monthly.station.record"-class object.
  \tabular{ll}{
    val \tab The monthly values (a 12-column matrix with one
    column for each year)\cr
    station \tab station number. \cr
    yy \tab The years of observation (vector). \cr
    lat,lon \tab Latitude and longitude of the location. \cr
    x.0E65N,y.0E65N \tab Distance in km from 0E, 65N. \cr
    location \tab Name of location . \cr
    wmo.no \tab WMO number. \cr
    start \tab Start of observatins from this location. \cr
    yy0 \tab First year in current record. \cr
    ele \tab Code of theelement. \cr
    obs.name \tab Name of the element. \cr
    unit \tab Unit of the element. \cr
    country \tab The country in which the location is
    located. \cr
    quality \tab Code/description for data quality. \cr
    found \tab Flag: T-> the data requested was found. \cr
    ref \tab Reference for the data set. \cr
  }
\author{R.E. Benestad}}
\examples{
\dontrun{
a <- read.table("data/bjornholt.dat",
                  col.names=c("station","year","month","rr",
                    "tam","sam","sdm","uum","pom","tax","tan"))
obs <- station.obj(x=a$rr,yy=a$year,mm=a$month,
                   obs.name="Precipitation",unit="mm",ele=601,
                   lat=60.03,lon=10.41,alt=360,
                   station=a$station[1],location="Bjornholt",
                   country="Norway",ref="met.no Climate data base")
plot(obs,mon=11)
}
}
\keyword{data}

\eof
\name{station.obj.dm}
\alias{station.obj.dm}
\alias{daily.station.record}
\title{Make daily climate station series object.}
\description{Create a station object for use as predictand in empirical
  downscaling on monthly data. Also see \code{\link{station.obj}}.}
\usage{station.obj.dm(t2m,precip,dd,mm,yy,
                       obs.name=NULL,unit=NULL,ele=NULL,
                       station=NULL,lat=NULL,lon=NULL,alt=NULL,
                       location="unspecified",wmo.no=NULL,
                       start=NULL,yy0=NULL,country=NULL,ref=NULL)}
\arguments{
  \item{t2m}{a vector holding daily mean temperature. }
  \item{precip}{a vector holding daily precipitation. }
  \item{dd}{a vector holding day of month.}
  \item{mm}{a vector holding the month.}
  \item{yy}{a vector holding the year.}
  \item{obs.name}{the name of observation: 
  eg c("Daily mean temperature","Daily precipitation"). }
  \item{unit}{the unite of observation: eg c("deg C","mm/day").}
  \item{ele}{element code: eg c("tam","rr").}
  \item{station}{local (national) station number.}
  \item{lat}{latitude.}
  \item{lon}{longitude.}
  \item{alt}{altitude.}
  \item{location}{name of location. }
  \item{wmo.no}{WMO number of station.}
  \item{start}{start of measurements.}
  \item{yy0}{first year of record.}
  \item{country}{name of country.}
  \item{ref}{reference to the data.}
  }
  \value{a "daily.station.record"-class object.
  \tabular{ll}{
  t2m \tab a vector holding daily mean temperature. \cr
  precip \tab a vector holding daily precipitation. \cr
  day \tab a vector holding day of month.\cr
  month \tab a vector holding the month.\cr
  year \tab a vector holding the year.\cr
  obs.name \tab the name of observation: \cr
  \tab eg c("Daily mean temperature","Daily precipitation"). \cr
  unit \tab the unite of observation: eg c("deg C","mm/day").\cr
  ele \tab element code: eg c("tam","rr").\cr
  station \tab local (national) station number.\cr
  lat \tab latitude.\cr
  lon \tab longitude.\cr
  alt \tab altitude.\cr
  location \tab name of location. \cr
  wmo.no \tab WMO number of station.\cr
  start \tab start of measurements.\cr
  yy0 \tab first year of record.\cr
  country \tab name of country.\cr
  ref \tab reference to the data.\cr}
  }
\author{R.E. Benestad}}
\examples{
\dontrun{
blindern.raw <-read.table("~/data/stations/blindern_rr_day.dat",header=TRUE)
blindern.raw$rr[blindern.raw$rr < 0] <- NA
yy <- floor(blindern.raw$yyyymmdd/10000)
mm <- floor(blindern.raw$yyyymmdd/100) - 10000*yy
dd <- blindern.raw$yyyymmdd - 100*mm  - 10000*yy
blindern <- station.obj.dm(t2m=rep(NA,length(blindern.raw$rr)),
                           precip=blindern.raw$rr,
                           dd=dd,mm=mm,yy=yy,
                           obs.name=c("T(2m)","recip"),
                           unit=c("deg C","mm/day"),ele=NULL,
                           station=18700,lat=59.95,lon=10.71,alt=94,
                           location="Oslo-Blindern",wmo.no=NULL,
                           start=NULL,yy0=1937,country="Norway",
                           ref="www.met.no")
}
}
\keyword{data}

\eof
\name{stationmap}
\alias{stationmap}
\title{Plot climate station map.}
\description{Plot a map showing the locations of NACD (\code{\link{getnacd}})
  and Nordklim (\code{\link{getnordklim}}) station network (monthly data).}
\usage{stationmap(ele=101,NORDKLIM=TRUE,NACD=TRUE,silent=TRUE)}
\arguments{
  \item{ele}{The code for element (101 = T(2m), 401=SLP, 601= precip).}
  \item{NORDKLIM}{Show Nordklim stations.}
  \item{NACD}{Show NACD stations.}
  \item{silent}{Print station names if false.}
\value{}
\author{R.E. Benestad}}
\examples{
\dontrun{
stationmap()
}
}
\keyword{hplot}

\eof
\name{stockholm.t2m}
\alias{stockholm.t2m}
\title{Monthly mean temperature in Stockholm.}
\description{A station record of monthly mean temperature Stockholm.}
\usage{data(stockholm.t2m)}
\format{list of "monthly.station.record" class:
    \tabular{ll}{
    val \tab The monthly values (a 12-column matrix with one
    column for each year). \cr
    station \tab station number. \cr
    yy \tab The years of observation (vector). \cr
    lat,lon \tab Latitude and longitude of the location. \cr
    x.0E65N,y.0E65N \tab Distance in km from 0E, 65N. \cr
    location \tab Name of location . \cr
    wmo.no \tab WMO number. \cr
    start \tab Start of observatins from this location. \cr
    yy0 \tab First year in current record. \cr
    ele \tab Code of theelement. \cr
    obs.name \tab Name of the element. \cr
    unit \tab Unit of the element. \cr
    country \tab The country in which the location is
    located. \cr
    quality \tab Code/description for data quality. \cr
    found \tab Flag: T - the data requested was found. \cr
    ref \tab Reference for the data set. \cr
  }}
\source{The Nordklim data set: \url{http://www.smhi.se/hfa_coord/nordklim/}}
\references{Tuomenvirta et al. (2001), "Nordklim data set 1.0", DNMI
  KLIMA 08/01, pp. 26; \cr
  The Norwegian Meteorological Institute, P.O. Box 43, 0313
Oslo, Norway (http://www.met.no).}
\examples{
}
\keyword{datasets}

\eof
\name{strip}
\alias{strip}
\title{String operation functions}
\description{The function strips off trailing space (strips the
  strings by cutting off at the first space).}
\usage{strip(in.str)}
\arguments{\item{in.str}{Strings or arrays of strings.}}
\value{converted strings or arrays of strings.}
\author{R.E. Benestad}}
\examples{
       print(upper.case(c("qwerty  e","asdf  rT")))       #  "QWERTY" "ASDF"
       print(lower.case(c("QWERTY","ASDF")))              #  "qwErty" "asdf"
       print(strip(c("Hello there!","Oslo"," ","NA ")))   # "Hello" "Oslo"  " "     "NA"
}
\keyword{character}

\eof
\name{tromsoe.t2m}
\alias{tromsoe.t2m}
\title{Monthly mean temperature in Tromsoe.}
\description{A station record of monthly mean temperature Troms{\o}.}
\usage{data(tromsoe.t2m)}
\format{a <- list of "monthly.station.record" class:
    \tabular{ll}{
    val \tab The monthly values (a 12-column matrix with one
    column for each year). \cr
    station \tab station number. \cr
    yy \tab The years of observation (vector). \cr
    lat,lon \tab Latitude and longitude of the location. \cr
    x.0E65N,y.0E65N \tab Distance in km from 0E, 65N. \cr
    location \tab Name of location . \cr
    wmo.no \tab WMO number. \cr
    start \tab Start of observatins from this location. \cr
    yy0 \tab First year in current record. \cr
    ele \tab Code of theelement. \cr
    obs.name \tab Name of the element. \cr
    unit \tab Unit of the element. \cr
    country \tab The country in which the location is
    located. \cr
    quality \tab Code/description for data quality. \cr
    found \tab Flag: T - the data requested was found. \cr
    ref \tab Reference for the data set. \cr
  }}
\source{The Nordklim data set: \url{http://www.smhi.se/hfa_coord/nordklim/}}
\references{Tuomenvirta et al. (2001), "Nordklim data set 1.0", DNMI
  KLIMA 08/01, pp. 26; \cr
  The Norwegian Meteorological Institute, P.O. Box 43, 0313
Oslo, Norway (http://www.met.no).}
\examples{
}
\keyword{datasets}

\eof
\name{upper.case}
\alias{upper.case}
\title{convert to UPPER CASE}
\description{Converts characters to UPPER CASE.}
\usage{upper.case(u.case)}
\arguments{\item{u.case}{Strings or arrays of strings.}}
\value{converted strings or arrays of strings.}
\author{R.E. Benestad}}
\examples{
       print(upper.case(c("qwerty  e","asdf  rT")))       #  "QWERTY" "ASDF"
       print(lower.case(c("QWERTY","ASDF")))              #  "qwErty" "asdf"
       print(strip(c("Hello there!","Oslo"," ","NA ")))   # "Hello" "Oslo"  " "     "NA"
}
\keyword{character}

\eof
\name{what.data}
\alias{what.data}
\title{Data information}
\description{The data originally used by the clim.pact package: NACD,
  Nordklim and NCEP reanalysis and links to their sources.}
\usage{what.data()}
\arguments{
}
\author{R.E. Benestad}}
\examples{
what.data()
}
\keyword{data}

\eof
