\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{DS}
\alias{climate analysis}
\alias{DS}
\alias{downscaling}
\title{Downscaling of monthly 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]. 

  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. 
}
\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=TRUE,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)
}
\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
}
  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{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{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{names.netCDF}}, however this function does not depend on
  the \code{netCDF} library.}
\usage{cdfcont(filename)}
\arguments{
    \item{filename}{name of netCDF file.}
 }
\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)}
\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}}.}
\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=FALSE,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)
compositeField(x,y,lsig.mask=TRUE,sig.lev=0.05,s=0.42,mon=NULL,
                      lty=1,col="black",lwd=1)
}
\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.}
 }
\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)}
\arguments{
    \item{x}{A field object.}
    \item{y}{A station series.}
    \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.}
 }
\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{delta}
\alias{delta}
\alias{delta function}
\title{Delta function}
\description{The dirac delta function: delta (i,j) returns 1 if i==j, 0
  otherwise. Used in \code{\link{optint}}.}
\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{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="prompt",ele.c='101',silent = FALSE,direc)}

\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{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)
}
\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}}.}
}
\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{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)}
\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}}}
 }
\value{A map object}
\author{R.E. Benestad}}
\examples{
}
\keyword{hplot}
\eof
\name{map.eof}
\alias{map.eof}
\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=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)}
\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 \link{par}}
  }
\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.}
    \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{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{optint}
\alias{optimum interpolation}
\alias{optint}
\title{Optimum interpolation}
\description{
  Solves for w in:
  \deqn{\sum_j M_{ij} w_ik = \langle pi_j pi_k \rangle }{sum_j(M_ij
    w_ik) = <pi_j pi_k>. }

  Then computes a correction: \deqn{r = w_i q}{r = w_i q,}
  where q = gridded observations - first guess.

  Reference: Reynolds and Smith (1994), Improved global sea surface
  temperature analysis using optimum interpolation, \emph{J. Climate}, 
  \bold{vol 7}, 929-948.

  \bold{NB: The testing of this routine is not yet finished - there may
    still be some bugs in this function.}
   }
\usage{optint(lon,lat,obs,lon.grd,lat.grd,fguess,eps,
              lambda=50,M=NULL,piipij=NULL,w=NULL,tim=NULL,date=NULL)}
\arguments{
    \item{lon}{A vector of longitude coordinates.}
    \item{lat}{A vector of latitude coordinates.}
    \item{obs}{A vector of observations.}
    \item{lon.grd}{A vector of longitude coordinates for gridded values.}
    \item{lat.grd}{A vector of latitude coordinates for gridded values.}
    \item{fguess}{First guess values on given grid (\code{lon.grd,lat.grd}).}
    \item{eps}{Error estimates on given grid (\code{lon.grd,lat.grd}).}
    \item{lambda}{Correlation length.}
    \item{M}{Interpolation model matrix.}
    \item{piipij}{Interpolation weights.}
    \item{w}{Interpolation weights..}
    \item{tim}{Time index.}
    \item{date}{Date stamp.}
 }
\value{A map object with additional elements: \code{M, piipij, w}}
\author{R.E. Benestad}}
\examples{
# This example takes a little while to run..
\dontrun{
lon <- c(12.02, 10.47,  9.28, 10.78, 10.71,  9.12,  8.20,  9.52,  8.18,  8.52,
          8.07,  6.15,  5.63,  6.37,  5.92,  5.33,  6.50,  7.42,  6.17, 10.00,
         10.02, 11.12, 10.93, 14.02, 13.98, 14.43, 15.42, 17.80, 18.53, 18.93,
         21.02, 21.88, 23.35, 23.52, 31.08, 15.47, 11.93)
lat <- c(60.61, 61.10, 62.12, 59.38, 59.95, 60.58, 60.52, 59.90, 59.83, 59.03,
         58.20, 58.88, 58.88, 59.65, 60.40, 60.38, 60.65, 62.23, 62.57,
         63.20, 62.82, 63.20, 63.47, 65.52, 66.82, 67.27, 68.70, 68.73,
         69.06, 69.65, 69.73, 69.83, 69.98, 69.33, 70.37, 78.25, 78.92)
val <- c(1.74, 1.43, 0.98, 1.31, 1.10, 1.39, 1.07, 1.33,-0.04, 1.07,
         1.07, 0.22, 0.89, 0.98, 0.77, 0.81, 1.43, 0.30, 0.69,-0.17,
         1.17, 0.32, 1.55, 1.65, 0.75, 0.78, 0.56, 0.04, 0.57, 0.52,
         0.51, 0.51, 0.96, 0.32, 0.35,-0.36, 0.00) 
library(akima)
lon.grd <- seq(min(lon),max(lon),length=20)
lat.grd <- seq(min(lat),max(lat),length=20)
fguess <- interp(lon,lat,val,lon.grd,lat.grd)$z
fguess[is.na(fguess)]<-mean(fguess,na.rm=TRUE)
eps <- abs(fguess)*0 + 0.1
opt.int <- optint(lon,lat,val,lon.grd,lat.grd,fguess,eps)
image(opt.int$lon,opt.int$lat,opt.int$map)
contour(opt.int$lon,opt.int$lat,opt.int$map,lwd=1,add=TRUE)
contour(lon.grd,lat.grd,fguess,lty=2,lwd=2,col="darkblue",add=TRUE)
addland()
}
}
\keyword{manip}\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")}

\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.}
}
\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/")}
\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.}
    }
\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{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,sub=NULL,
                   col=c("red","blue","darkgreen","steelblue"))}
\arguments{
    \item{x}{An \code{\link{EOF}} object.}
    \item{i.eof}{EOF to plot.}
    \item{nlevs}{Contour levels.}
    \item{sub}{subtitle.}
    \item{col}{Colour.}
    }
\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")}
\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.} 
}
\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}
\title{Retrieve data from a netCDF file}
\description{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).}
\usage{retrieve.nc(f.name="data/ncep_t2m.nc",v.nam="AUTO",
                        l.scale=TRUE,greenwich=TRUE,
                        x.nam="lon",y.nam="lat",z.nam="lev",t.nam="tim",
                        x.rng=NULL,y.rng=NULL,t.rng=NULL)
}
\arguments{
    \item{f.name}{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{t.rng}{Time interval to extract.}
  }
  \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 <- map.field(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)}
\arguments{
  \item{ele}{The code for element (101 = T(2m), 401=SLP, 601= precip).}
\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(string.array})}
\arguments{\item{string.array}{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
