\newcommand{\tl}{\textsf{TerraLib}}
\SweaveOpts{width=5.5,height=5.5,pdf=F}

<<label=Rsettings,echo=FALSE,results=hide>>=
options(width=40)
options(SweaveHooks=list(fig=function() par(mar=c(3,3,1,0.5),
mgp=c(2,0.8,0))))
#options(prompt="R> ")
require(aRT)
aRTsilent(TRUE)
@

\title{\pkg{aRT}: \R-\tl\ API}
\author{by Pedro R. de Andrade Neto, Marcos A. Carrero and
Paulo J. Ribeiro Júnior}
\maketitle
In \R, there are some spatial packages implementing statistical
analysis. But functions implementing spatial operations are 
not common in these packages. For example, in \pkg{sp}, there are
functions to do queries involving points and polygons, 
and functions as area and perimeter, but there are many other
spatial operations, such as:
\begin{itemize}
\item set operations on polygons: union, intersection, difference
and XOR;
\item spatial unary operations: buffer, convex hull, MBR (minimum
bounding rectangle) and centroid;
\item spatial operations over the three types of geometry,
implementing predicates, such as \emph{contain}, \emph{disjoint},
\emph{intersect}, \emph{touch}, \emph{cross},
\emph{overlap} and \emph{cover}.
\end{itemize}

On the other hand, Geographic Information Systems (GIS) are capable to
manipulate several complex georeferenced data structures.
GIS are an example of a multidisciplinary work that comprises
knowledge in areas such as cartography, databases and software
engineering. 

\tl\ is a set of GIS classes written in C++ for support 
building GIS applications. It manipulates points, lines,
polygons and raster data (grids), storing them in a Data-Base Management
System (DBMS), and it has all above (and other) spatial queries.
Its main objectives are:
\begin{itemize}
\item Encapsulate various DBMS, for example MySQL, PostgreSQL,
PostGIS and Oracle-spatial;
\item Give high-level support do spatial operations;
\item Enable database access without using SQL queries;
\item Retrieve spatial objects from DBMS in a \emph{proxy} way.
\end{itemize}

\pkg{aRT} is a package that implements the integration between \R\
and \tl. The main motivation for the package development is to enable
the access to geographical databases and spatial/temporal operations
on them. \tl provides its own way to access a geographical database,
and it has several internal tables to control the data and
their relations.
Therefore we cannot use database interfaces provided by R packages,
such as \pkg{RMySQL} or \pkg{ROracle}.

In this paper we objective to describe some concepts of
\pkg{aRT}, using spatial operations over three geometric types.
 A web site with further information can be found at
\url{http://www.est.ufpr.br/aRT}.

\section{Database Connections}
To manipulate \tl\ data, we need a connection to a database.
But, before it, we need to connect to the DBMS:

<<label=openConn,echo=TRUE>>=
con=openConn(user="pedro", dbms="mysql")
@

\code{con} stores a MySQL connection, and it has information
about the DBMS authentication. With it, we can execute some administration tasks,
such as listing, removing and creating databases. To store a database connection,
we need to create an \code{aRTdb} object, and it is created from the connection:

<<label=deleteDb,echo=FALSE,results=hide>>=
if(any(showDbs(con) == "recife")) deleteDb(con, "recife", force=T)
@
<<label=createDb,echo=TRUE>>=
db=createDb(con, "recife")
@

In this example, we create a database named \emph{recife} and store its 
connection in the object \code{db}.

\section{Data (Manipulation?)}
To illustrate how to perform data (manipulation), we will insert some data
in the database.
We will use the data-sets of Recife city, in Brazil, available as
data of \pkg{aRT}. These data-sets are shown in
Figures~\ref{fig:bairros} and~\ref{fig:drenagem}.

<<label=data,echo=TRUE>>=
data(recife.districts)
data(recife.points)
data(recife.sewers)
@

\begin{figure}[htb]
\begin{center}
<<echo=FALSE,print=FALSE,fig=TRUE>>=
plot(recife.districts, col="red", xlab="", ylab="")
plot(recife.points, add=T)
@
\end{center}
\caption{Recife's districts}
\label{fig:bairros}
\end{figure}

\begin{figure}[htb]
\begin{center}
<<echo=FALSE,print=FALSE,fig=TRUE>>=
plot(recife.districts, col="gray", lty=0, xlab="", ylab="")
plot(recife.sewers, add=T, col="blue")
@
\end{center}
\caption{Recife's sewerage}
\label{fig:drenagem}
\end{figure}

\pkg{aRT} can only process database stored data. Therefore, the first 
step to do spatial queries on these data is pushing them into a
database.
In order to insert the data, we need to understand the
concept of \emph{layer}.
In \tl\, the access to data is provided by a \emph{layer}, which is a
collection of spatial data with attributes, representing objects with the
same characteristics.

To manipulate layers, we use \code{aRTlayer} objects.
To create a new layer we use the function \code{createLayer}, which
takes as arguments the database, and the layer name.
As we have three different geometries, we need to create three layers:

<<label=createLayer,echo=TRUE>>=
ldistricts = createLayer(db, "districts")
lpoints    = createLayer(db, "points")
lsewers    = createLayer(db, "sewers")
@
(An important thing is that \code{ldistricts} (as the others) stores
an external pointer to a \tl\ object.)

Once the layers are created, we can insert geometries.

<<label=addGeom,echo=TRUE>>=
addLines (lsewers,    recife.sewers)
addPolygons (ldistricts, recife.districts)
addPoints(lpoints,    recife.points)
@

Internally, \tl\ automatically associates the layer with a table,
that effectively stores the geometries.
To manipulate the data in a layer, it is necessary to have at
least one attribute table in it.
\tl\ has several types of table, and for the moment we will 
only create three tables.

<<label=createTable,echo=TRUE>>=
t = createTable(lsewers,    "sewers")
t = createTable(ldistricts, "districts")
t = createTable(lpoints,    "points")
@

Finally, after following the previous steps, we have the data stored in the database, 
and we can start to perform spatial queries.

\section{Spatial Queries}
\tl\ provides facilities for spatial, temporal and attributes queries on the database. 
The following examples illustrate some of these features that are currently implemented.

\subsection{Metrics}

As a first example, we will calculate
the perimeter and area of the city. The area can easily be obtained as the
sum of all districts area, but not the perimeter. To do this,
we need to join all the polygons to obtain the city polygon,
and then calculate its length. For calculate the union of all
districts we use the function \code{getSetMetric}, that implements set
operations (union, intersection, difference and XOR), and it can be
used as shown below.

<<label=createTable2,echo=TRUE>>=
#city=getSetMetric(ldistricts, "union", id=recife.districts["id"])
@

\emph{city} is a new geometry and it is not stored in the database.
To do some operation using this object, again, we need to store it
in the database. Then we will create an other layer:

<<label=createLayer2,echo=TRUE>>=
#city$id=c("1")
#$
lcity=createLayer(db, "city")
#addPolygons(lcity, city)
@

Now the result can be obtained using the method \code{getMetric}.
This function implements operations over the layer that
depends only of one object. Then it can return the area and the
length of all layer elements, answering our first question:

<<label=getMetric,echo=TRUE>>=
#getMetric(lcity, "area")
#getMetric(lcity, "length")
@

If we calculate the area using the sum of the districts area
the value is:

<<label=getMetric2,echo=TRUE>>=
sum(getMetric(ldistricts, "area")$area)
#$
@

It has an error of $0.00002\%$, almost insignificant.

\subsection{Relations}

Spatial relations define neighbourhood criterions over the
elements of one or two layer. For exemplify \pkg{aRT}
capabilities in spatial relations, we will answer two
questions about Recife's data.

The first question is: ``Which districts contains the points,
and which ones are their neighbours?''
First we will use the \emph{contain} operator on the 
districts layer, and
after that we ask for which layers \emph{touches} the selected
layers:

<<label=getRelation,echo=TRUE>>=
rel1=getRelation(ldistricts, "contains", lpoints)
rel2=getRelation(ldistricts, "touches", id=rel1)
@

The results of plotting are in Figure~\ref{fig:vizinhos}.

\begin{figure}[htb]
\begin{center}
<<echo=FALSE,print=FALSE,fig=TRUE>>=
plot(recife.districts, col="gray", lty=0, xlab="", ylab="")
plot(recife.districts, col="green", add=T, id=rel2)
plot(recife.districts, col="yellow", add=T, id=rel1)
@
\end{center}
\caption{Recife}
\label{fig:vizinhos}
\end{figure}


Still using the districts which contains the points, the second
question is: ``Which sewers are inside or touches the districts
that contain the points?''
Figure~\ref{fig:espacial}
<<label=getRelation2,echo=TRUE>>=
rel3=getRelation(lsewers, "crosses", layer=ldistricts, id=rel1)
rel4=getRelation(lsewers, "within",  layer=ldistricts, id=rel1)
@

\begin{figure}[htb]
\begin{center}
<<echo=FALSE,print=FALSE,fig=TRUE>>=
plot(recife.districts, col="gray", lty=0, id=rel1, xlab="", ylab="")
plot(recife.districts, col="gray", lty=0, add=T)
plot(recife.districts, col="yellow", lty=0, id=rel1, add=T)
plot(recife.sewers, add=T)
plot(recife.sewers, add=T, col="green", id=rel3)
plot(recife.sewers, add=T, col="red", id=rel4)
@
\end{center}
\caption{Recife}
\label{fig:espacial}
\end{figure}

With these spatial queries, it is easy to build a neighbourhood matrix,
based in any spatial criterion, not only touching, but
as a common river or the length of its dividing line is 
greater then a given threshold.

\section{Other Functionalities}
Some other functionalities actually implemented in aRT are:
\begin{itemize}
\item execute database queries, selecting attributes and
joining tables.
\item load data to R using a proxy, retrieving one geometry per time, 
instead of all geometries once. It is useful when working with large
datasets.
\item generate visualization environments to \tl-based GIS.
\end{itemize}

\section*{The Future}
\pkg{aRT} has the aim to integrate \R\ and \tl\ with the purpose to have
an environment for statistical analysis of spatial data stored in a DBMS.

Implement spatial manipulation and queries using non-database stored data,
avoiding the creation of new layers
simplifying the examples that need to create new layers for
consecutive queries (until now, if we want to execute  a query
in another query result, the data must be stored in a new layer).

The actual state of \tl\ developing is spatial-temporal databases,
with geometry varying in the time, and it is one of the future works
of this project.

\section*{Acknowledgements}
This work was partially supported by SAUDAVEL...

We also want to thank \tl\ developers Lúbia Vinhas and
Karine Reis for help.

\address{Pedro Ribeiro de Andrade Neto\\
Marcos Aurélio Carrero\\
Paulo Justiniano Ribeiro Júnior\\
Federal University of Paraná, Brazil
}

\email{\{pedro, marcos, paulojus\}@est.ufpr.br}

% vim: syntax=tex
