%\VignetteIndexEntry{API R TERRALIB}
%\VignetteDepends{}
%\VignetteKeywords{spatial}
%\VignettePackage{aRT}
\documentclass[a4paper, 12pt]{article}

%\usepackage{harvard} usado com style dcu, muda estilo da bibliografia colocando sobrenome primeiro
\usepackage[dvips]{graphicx}
\usepackage[latin1]{inputenc}
%\usepackage{amsmath,amssymb}
\usepackage{color,enumerate,longtable}
\usepackage{texnames,lastpage,verbatim,fancyvrb}
%\usepackage[brazil,brazilian]{babel}

% Sweave settings
%
% Setting default size for \includegraphics 
% setting global defaults for figures: directory, names and sizes  
%%% \ SweaveOpts{prefix.string=figures/fig,width=4,height=4}
\SweaveOpts{width=4,height=4}
% emulating Sweave: Sweave style for R input code and output
\DefineVerbatimEnvironment{Rin}{Verbatim}{fontshape=sl}
\DefineVerbatimEnvironment{Rout}{Verbatim}{}
\newcommand{\Rcmd}[1]{\textsl{\texttt{#1}}}
\newcommand{\Te}{{\normalfont\textsf{TerraLib}}{}}
\newcommand{\TV}{{\normalfont\textsf{TerraView}}{}}
\newcommand{\MySQL}{{\normalfont\textsf{MySQL}}{}}


% loading Defs from Rd.sty
\usepackage{Rd}
\renewcommand{\pkg}{}
\renewcommand{\Te}{TerraLib}
\renewcommand{\TV}{TerraView}
\renewcommand{\MySQL}{MySQL}

\title{\pkg{aRT}: API \R-TerraLib}
\author{Pedro R. de Andrade Neto, Marcos A. Carrero, Paulo J. Ribeiro Jr}

\date{\today}

\begin{document}
\maketitle

\section{Introduction}

\R{} is a language and environment for statistical computing and
graphics and is freely distributed under the terms of the GNU General Public License
\cite{R:2003}.
It is similar to the \code{S} language which was developed at AT\&T Bell Laboratories,
but they have important differences in the designs.

\R{} provides a wide variety of statistical and graphical techniques, is highly extensible
having interface with procedures written in C/C++ or FORTRAN. A web site
with further information can be found at \url{http://www.r-project.org}.

\Te\ is a Geographic Information System (GIS) library written in C++,
developed by \emph{Instituto Nacional de Pesquisas Espaciais} (INPE), available from the Internet
as open source, allowing a collaborative environment and its use for the development of
multiple GIS tools \cite{Camara}.
It defines a geographical data model and provides support for this model over a range of
different Data-Base Management Systems (DBMS). A web site with further information can be
found at \url{http://www.terralib.org}.

An example of application that use \Te\
class library is \TV. It is a Geographical Application tool, with spatial analysis
capabilities, and is also licensed as free software under the GNU General Public License.
It can be downloaded together with \Te.

\pkg{aRT} (API R-TerraLib) is a package that provides the integration between the
softwares \R\ and \Te. The aRT is still a prototype with some basic operations
which prove that the integration is possible. The idea is to have a package that uses the
statistical analysis provided by \R{} and the geographical data model and database support
by \Te. A web site with further information can be found at
\url{http://www.est.ufpr.br/aRT}

The main motivation for the package development is to facilitate the exchanging of
information between the spatial packages in \R{}
(see \url{http://sal.agecon.uiuc.edu/csiss/Rgeo/}) and the \Te{} ability to manage and
perform some spatial operations on the database. For instance, data can be easily moved
between \R{} and \Te{}. This way a data analyst could, for instance, import the data to
\R{}, perform some analysis using a spatial package such as \pkg{spdep}, \pkg{splancs},
\pkg{gstat}, \pkg{geoR}, among others, and return the results to the database. Those
results could them be accessed by a GIS software such as \TV. 

Section~\ref{req} lists the \pkg{aRT} requirements and dependencies. 
To start with the development we have defined six basic operations which are described in
Section~\ref{basic} with examples of the capabilities of \pkg{aRT}.

\section{Requirements and dependencies}\label{req}
\pkg{aRT} is being developed under a \code{GNU/Linux-Debian} platform  
and do not have guarantees to work in other one.
This prototype still doesn't have (yet...) an \emph{autoconfigure}, 
so the configuration must be done manually. The following softwares/libraries are necessary:

\begin{itemize}
\item{\code{MySQL} DBMS version 14.7 or upper and libraries:}\\
  \url{http://www.mysql.com}
\item{\code{Qt} library version 3.3.3 or upper (\code{Qt} is a multiplataform toolkit
in \code{C++} for the development of graphic interfaces, implemented by Trolltech:)}\\
    \url{http://www.trolltech.com}\\
    \code{Qt} library is used to \Te{} compilation.
\item{\Te{} 3.0.2 or upper:}\\
  \url{http://www.terralib.org}\\
  \Te{} library is generated through the compilation.
\item{\R{} language:}\\
  \url{http://cran.r-project.org}
\item{GNU gcc/g++ compiler, MAKE}\\
  \url{http://www.gnu.org}
\item{\pkg{aRT} package:}\\
  \url{http://www.est.ufpr.br/aRT}
\end{itemize}

There is a script to download and install MySQL/Qt/TerraLib under Debian/Linux
along with the package.

Once we installed  \code{MySQL}, \code{Qt}, \Te{} and \R{} in the directory
\dQuote{/usr/local}, the following environment variables should be placed, i.e, in the
\dQuote{.bash\_profile} or \dQuote{.bashrc} file of the user's login directory.
Change the directories according with the installations' pathes.

\begin{verbatim}
# Default directories (TerraLib, libmysqlclient.a and libR.so),
# used to __Make__ aRT: 

TERRALIBDIR=/usr/local/terralib
LIBMYSQLCLIENTDIR=/usr/lib
LIBRDIR=/usr/local/lib/R/lib

# TerraLib Shared libraries, used to __execute__ aRT: 

LD_LIBRARY_PATH=$TERRALIBDIR/terralibx/terralib:\
$TERRALIBDIR/terralibx/tiff:\
$TERRALIBDIR/terralibx/shapelib:\
$TERRALIBDIR/terralibx/stat

export TERRALIBDIR MYSQLDIR LD_LIBRARY_PATH LIBRDIR
\end{verbatim}

\section{Getting started}\label{basic}

After installing \pkg{aRT} and starting an \R\ session, load the package with the command
\code{source}. If the package is loaded successfully a message will be displayed.

<<label="Loading package">>=   
require(aRT)
@

\pkg{aRT} has four classes to manipulate TerraLib data/functions:
\code{aRT}, \code{aRTdb}, \code{aRTlayer} and \code{aRTtheme}.
The next subsections explain each class in details.

\subsection{aRT class}
Once the package is loaded, we need a DBMS connection. It can be done creating an 
\code{aRT} object. The constructor of \code{aRT} class gets the arguments
\code{user}, \code{password}, \code{host} and \code{port}, and their default values
are USER variable, empty string, ``localhost'' and 3306, respectivaly. For example:

<<label="Creating a DBMS connection">>=
con <- new("aRT", user="root", host="localhost", pass="")
print(con)
@

After the object \code{con} is created, the variables it contains cannot be 
changed. If you need to set them, the only way is to create another object. 
This occours because data is stored in a external pointer, but 
we will not explain these things here.

One \code{aRT} object stores a \emph{virtual} connection, i.e., all time that
a database access is required, it connects, do something, and then disconnect.
The objective of this class is to do some database administration functions, and
open \emph{real} connections. For example, if it is the first time you are
running \pkg{aRT}, maybe you need to add permissions to some users. To do this,
use \code{addUser()}:

<<label="Adding user">>=
addUser(con, "pedro")
@

\emph{Warning}: this function gives ALL permissions to a user. If you want to do
something different, you need to run mysql for yourself, and use the \code{GRANT}
command.

With an \code{aRT} object, you can also see the databases available and remove them.
The next example shows the databases and tries to remove the database parana if it
exists:

<<label="Showing databases">>=
showDbs(con)
if( any(showDbs(con) =="parana") ) deleteDb(con, "parana")
@

\subsection{aRTdb class}

To create a new database, or to access one, there is the \code{aRTdb} class.
Objects from this class stores a \emph{real} database connection, and needs
an \code{aRT} object to be created:

<<label="Creating new database">>=
db <- new("aRTdb", con, db="parana", create=TRUE)
print(db)
@

This constructor tries to load a database with name \code{parana}. If it does
not exists (the true, once we removed it), it checks for \code{create},
trying to create a new one. Once this object is created, it depends no
more of the \code{con} object.

\code{aRTdb} objects contains \emph{all} TerraLib objects in memory needed
by \pkg{aRT}. This means
that all objects opened from it depends on it, even after they are created
in \R. The last line of \code{print} shows the number of children this object
has. If this object is removed from \R, all childrens becomes invalid objects
when \R's garbage collector remove this object from memory.

\subsection{aRTlayer class}

To work with data in aRT, we need to manipulate \emph{layers}. A layer can
store any geometry of one kind (points, polygons or raster for now, lines
and cells in the future), and attributes. Layers are TerraLib abstrations
that uses tables of data and tables of control in one database. So they can
be created from \code{aRTdb} objects. 

<<label="Creating a new layer">>=
layer.points <- new("aRTlayer", db, layer="points", create=TRUE)
print(layer.points)
@

There is an argument \code{proj} in the constructor that says which
projection the layer data is. The defaul value is \code{plan}, meaning that
the data can be drawn as it is. The other option (until now) is \code{gepgraphic},
meaning that the data is in degrees. Then we need to convert the data before
plot it. ((Referência?? Simone??))

To insert data in the layer, we will use the bodmin dataset, part of \pkg{splancs}
package.

<<label="Splancs">>=
require(splancs)
data(bodmin)
names(bodmin)
@

Before insert into the database, we must convert the data to \pkg{aRT} format. 
\pkg{aRT} has some functions to convert data from other spatial packages (\pkg{splancs}
and \pkg{geoR}, actually). This functions have the format \texttt{<pkg>2aRT<datatype>},
where \texttt{pkg} can be \texttt{sp} or \texttt{gr}, and \texttt{datatype}
can be one of \texttt{points}, \texttt{polygons} or \texttt{attributes}. As example,
the next code converts bodmin data from \pkg{splancs} to \pkg{aRT}, and inserts it into
the database\footnote{You can disable the aRT functions message dump calling
\texttt{aRTsilent(TRUE)}}: 

<<label="Adding points">>=
points <- .sp2aRTpoints(bodmin)
addPoints(layer.points, points)
print(layer.points)
@

To insert the evolving polygon, we will create another layer:

<<label="Adding polygons">>=
polygons <- .sp2aRTpolygons(bodmin)
layer.pol <- new("aRTlayer", db, l="polygons", c=T)
addPolygons(layer.pol, polygons)
@

Finally we will do a kernel analysis, and insert the raster data into the database, in
another layer (ww is to remove a bug from latex2html):

<<label="Adding raster">>=
ww <- bodmin$poly
kernel2d(as.points(bodmin), bodmin$poly, h0=2, nx=100, ny=200) -> raster
layer.raster <- new("aRTlayer", db, l="raster", c=T)
addRaster(layer.raster, raster)
@

Finnaly, there are three layers created, children of \code{db}, as can be seen
in the next code:

<<label="Show layers">>=
showLayers(db)
print(db)
@

All \code{add} functions recieve an argument \code{close = TRUE}, telling
if it is the last time the data will be inserted in the layer. Once the
layer is closed, no geometry can be added to it\footnote{until now, there
is no protection to one who tries it, but no attributes of the geometry
inserted after close the layer can be retrieved.}. You can implicitly
close the layer and create the table calling \code{createEmptyTable()}.
After close the layer, attributes can be inserted. 

((Paulo, aqui eu queria falar do \code{addColumns()}, mas
no bodmin nao tem atributos associados aos dados... o q fazer??))

To get the layer's geometry call \code{getGeometry}, and then you
can plot it. But if you don't need the data the layer can be
plotted directly:

<<plotPoints,eval=F>>=
plot(layer.points)
@

\SweaveOpts{prefix.string=Rfigs/fig,width=5.5,height=5.5,pdf=F}
\setkeys{Gin}{width=0.7\textwidth}
\begin{figure} \begin{center}
\label{fig:surv}
<<echo=F, fig=T>>=
<<plotPoints>>
@
\caption{Point set in \texttt{layer.points}}
\end{center} \end{figure}

<<plotPol, eval=F>>=
plot(layer.pol)
@

\begin{figure} \begin{center}
\label{fig:surv}
<<echo=F, fig=T>>=
<<plotPol>>
@
\caption{Evolving polygon in \texttt{layer.pol}}
\end{center} \end{figure}

<<plotRaster, eval=F>>=
@
%plot(layer.raster)
%@

\begin{figure} \begin{center}
\label{fig:surv}
<<echo=F, fig=T>>=
<<plotRaster>>
@
\caption{Raster data from \texttt{layer.raster}}
\end{center} \end{figure}


You can plot different layers, using \code{add = TRUE}.

\subsection{aRTtheme class (TerraView users only)}

The last class implemented in aRT package is aRTtheme. Themes can be visualized
in TerraView software, and are (until now) useless for non-TerraView users. 

Now we will create themes of points and polygons, and put them in the
view \code{view}:

%<<Themes>>=
%theme.points<-new("aRTtheme",layer.points, th="points", cr=T, v="view")
%theme.pol<-new("aRTtheme",layer.pol, th="polygons", cr=T, v="view")
%@

There is an argument that can be used in raster themes: the colors configuration.
It can be used as in the next example.

%<<ThemeRaster>>=
%theme.raster<-new("aRTtheme",layer.raster, th="raster", col= terrain.colors(15), cr=T, v="view")
%@

\subsection{Spatial and attributes data format}

\subsection{Removing}

There are two kinds of removing aRT objects: from memory and from database. aRTdb's objects
stores all the memory of aRT objects. aRTlayers only have pointers to its aRTdb. To remove
data from memory is just call \code{rm}, and (for aRTDb's), if you want to free the memory
call \code{gc} explicitaly. Note that, once an aRTlayer object needs an aRTdb, if 
the garbage collector removes one aRTdb object, all the aRTlayers opened from it
will become invalid.

\bibliographystyle{plain}
\bibliography{bibli}

\end{document}
