Enviromental Modelling Introduction to TerraME

169
Enviromental Modelling Introduction to TerraME Tiago Garcia de Senna Carneiro (UFOP) Gilberto Câmara (INPE)

description

Enviromental Modelling Introduction to TerraME. Tiago Garcia de Senna Carneiro (UFOP) Gilberto Câmara (INPE). Dynamic Spatial Models. f (I t ). f (I t+1 ). f (I t+2 ). f ( I t+n ). F. F. - PowerPoint PPT Presentation

Transcript of Enviromental Modelling Introduction to TerraME

Enviromental Modelling

Introduction to TerraME

Tiago Garcia de Senna Carneiro (UFOP)Gilberto Câmara (INPE)

f ( It+n )

. . FF

f (It) f (It+1) f (It+2)

Dynamic Spatial Models

“A dynamical spatial model is a computational representation of a real-world process where a location on the earth’s surface changes in response to variations on external and internal dynamics on the landscape” (Peter Burrough)

tp - 20 tp - 10

tp

Calibration Calibration tp + 10

ForecastForecast

Dynamic Spatial Models

Source: Cláudia Almeida

Spatial dynamical models have a common structure

How much?

Where?

How?

When?

t+1load

t ≥ tf

idle

1980

1990

2000

GIS

play

CLUEModel

What is a spatial dynamical model?

A closed microworld with Spatial and temporal structure Entities Rules of behaviour

What is changing?

When?Where?Why?

Computational Modelling with Cell Spaces

Cell Spaces

Generalized Proximity Matrix

Control

Mode B

Flow

Conditio

n

Jump

EventControl

Mode A

Flow

Conditio

n

Hybrid automata

Database support

Cell Spaces

2500 m 2.500 m e 500 m

Cellular Data Base Resolution

Software: Open source GIS

Visualization (TerraView)

Spatio-temporalDatabase (TerraLib)

Modelling (TerraME)

Data Mining(GeoDMA)Statistics (R interface)

TerraLib

TerraLib EnviromentalModeling Framework

C++ Signal Processing

librarys

C++ Mathematical

librarys

C++ Statisticallibrarys

TerraME Virtual Machine

TerraME Compiler

TerraME Language

RondôniaModel DinamicaModel TROLLModel CLUEModel

TerraME architecture

TerraME functionality

Eclipse & LUA plugin• model description• model highlight syntax

TerraView• data acquisition• data visualization• data management• data analysis

TerraLibdatabase

da

ta

Model source code

MODEL DATA

mod

el

• model syntax semantic checking• model execution

TerraME INTERPRETER

LUA interpreter

TerraME framework

TerraME/LUA interface

model d

ata

Enviromental Modelling

Introduction to LUA

Tiago Garcia de Senna Carneiro (UFOP)Gilberto Câmara (INPE)

Por que Lua?

Pequena Portátil Eficiente Fácil integração com C/C++ Simples e flexível

Sintaxe simples Facilidades para descrição de dados Mecanismos de extensão “Simple things simple, complex things possible”

Como é Lua?

Sintaxe convencional

Unidade básica de execução: chunk Chunk = lista de comandos Arquivo ou string do programa hospedeiro

function fat (n) if n == 0 then return 1 else return n*fat(n-1) endend

Tipos Tipos associados a valores

Variáveis armazenam qualquer tipo Polimorfismo natural

Tipos existentes nil boolean number string table function userdata thread

Tipo nil

Propósito maior: ser diferente dos demais

Tipo do valor default das variáveis

Também significa o falso booleano Qualquer valor de outro tipo significa verdadeiro

Com exceção de false

Tipo boolean

Valor booleano Falso (false) ou verdadeiro (true)

if (choveu == true) then ....

Tipo number

Único tipo nativo para valores numéricos double (por default)

local a = 3local b = 3.5local c = 4.5e-8

Tipo userdata

Armazena um ponteiro void* de C

Tipo opaco para a linguagem Somente atribuição e teste de igualdade

Linguagem extensível em C “Esqueleto” para construção de linguagens de domínio

específico

Tipo string

Valores imutáveis Sem limite de tamanho

É comum ler arquivo completo em uma string Strings não usam ‘\0’ para terminação

Podem armazenar dados binários quaisquer Pattern-matching poderoso

Implementado via biblioteca padrão

meunome = “Silvana Amaral”;

Tipo table Resultado da expressão {}

Arrays associativos Qualquer valor como chave

Com exceção de nil

Único mecanismo de estruturação de dados São para Lua o que listas são para Lisp

Tables

The only structured data type is table. implements associative arrays, that is, arrays that can be

indexed not only with integers, but with string, double, table, or function values.

For table indexing, both table.name and table[''name''] are acceptable. Tables can be used to implement records, arrays, and recursive data types.

Tipo Table

loc = { cover = "forest", distRoad = 0.3, distUrban =

2 };

Campo Valor

cover “forest”

distRoad 0.3

distUrban 2

Tipo Table loc = { cover = "forest", distRoad = 0.3, distUrban = 2 };

loc.cover = “cerrado”;loc[“cover”] = “soja”;

if (loc.distUrban > 1.5) thenloc.desfPot = loc.distRoad + loc.distUrban;

Tables and functions in Lua

loc = { cover = "forest", distRoad = 0.3, distUrban = 2 };

...loc.reset = function( self )

self.cover = ""; self.distRoad = 0.0; self.distUrban = 0.0;

end loc = { cover = "forest", distRoad = 0.3,

distUrban = 2, reset };

Data structures with tables

Simple and efficient implementation Records

Syntactic sugar t.x for t["x"]:

t = {}t.x = 10t.y = 20print(t.x, t.y)print(t["x"], t["y"])

Data structures with tables (2)

Arrays Use integers as indexes

Sets Use elements as indexes

“Bags" Elements as indexes, counters as values

for i=1,n do print(a[i]) end

t = {}t[x] = 1 -- t = t {x}if t[x] then... -- x t?

Data structures with tables (3) Listas

Tables in Lua are “objects”, that is, dynamically allocated “things” manipulated through pointers to them.

Tables in Lua can directly represent dynamic structures such as trees and graphs, even cyclic structures.

list

value - vnext -

old list...

list = {value=v, next=list}

Library functions for tables

table.insert Inserts a new element

table.remove Removes an element

table.sort Orders the elements

My first Lua programC = 2; -- rain/t

-- defines a location with an absortion capacity and makes it rain

solo = { acum = 0, k = 0.4; }

for time = 0, 20, 1 dosolo.acum = solo.acum + C – solo.k*solo.acum;

end

Type function

Funções are first-class values

function inc (x) return x+1end

inc = function (x) return x+1 end

sugar

w = { redraw = function () ... end, pick = function (x,y) ... end,}

if w.pick(x,y) then w.redraw()end

Functions can be assigned to table fields

Type function (2)

function f() return 1,2end

a, b = f()print(f())

Passagem por valor e retorno múltiploSuporte a atribuições múltiplas (x,y = y,x)

Suporte a número variável de argumentosArgumentos "empacotados" em uma tabela

function f(...) print(arg[1], arg[2])end

Lexical scope

Acesso a variáveis em escopos externos Expressão cujo valor é calculado quando a função

que a contém é criada Quando o fecho é feito

function add (x) return function (y) return y+x endend

add1 = add(1)print(add1(10)) --> 11

upvalue

Constructors

Data description + imperative semantics

article{ author="F.P.Brooks", title="The Mythical Man-Month", year=1975}

temp = {}temp["author"] = "F.P.Brooks"temp["title"] = "The Mythical Man-Month"temp["year"] = 1975article(temp)

Objects Funções 1a classe + tabelas = quase OO

Tabelas podem ter funções como campos

Sugar para definição e chamada de métodos Trata parâmetro implícito self Ainda falta herança...

a.foo(a,x)a:foo(x)

a.foo = function (self,x) ...end

function a:foo (x) ...end

sugar

sugar

Exemplo: tipo Point-- Metatable de Pointlocal Point_metatable = { __add = function (p1,p2) return Point(p1.x+p2.x,p1.y+p2.y,p1.z+p2.z} end}-- Construtorfunction Point (self) self.x = tonumber(self.x) or 0.0 self.y = tonumber(self.y) or 0.0 self.z = tonumber(self.z) or 0.0 setmetatable(self,Point_metatable) return selfend-----------------------------------------------local p = Point{x=3.0,y=1.3,z=3.2}local q = Point{x=4.2,y=1.0}local r = p+q -- {7.2, 2.3, 3.2}

-- Métodoslocal Point_methods = { Print = function (self) print(self.x, self.y, self.z) end, ...}-- Metatablelocal Point_metatable = { __index = Point_methods, __add = function (p1,p2) return Point(p1.x+p2.x,p1.y+p2.y,p1.z+p2.z} end}------------------------------------------------local p = Point{x=3.0,y=1.3,z=3.2}local q = Point{x=4.2,y=1.0}local r = p+qr:Print()

Herança Simples: mecanismo de delegação

Bibliotecas padrão Basic String Table Math IO OS Debug Coroutine

Basic

Oferecem funções básicas print type setmetatable pairs

String Funções para manipulação de strings

Casamento de padrões (pattern matching) string.find

Permite buscar a ocorrência de um padrão numa string string.gsub

Permite substituir ocorrâncias de um padrão por uma sequência de caracteres dentro de uma string

Meu segundo programa em Lua C = 2; -- rain/tK = 0.4; -- flow coefficientq = 0; --function chuva (t) if (t < 10) then

return 4 – 4*math.cos(math.pi*t/10);else

return 4 – 4*math.cos(math.pi*(t-10)/10); endend--for time = 0, 20, 1 do

-- soil waterq = q + chuva(time) - K*q;

end-- report

print(“q = "..q);

Defining a model in TerraME Part 1: The cell space

Computational Modelling with Cell Spaces

Cell Spaces

Components Cell Spaces Generalizes Proximity Matriz – GPM Hybrid Automata model Nested enviroment

fonte: Carneiro (2006)

Basic concepts

is represented as a cell space environment…… where automata rules change the space properties in time.Several agents can share the same environment.

A dynamical model…

The TerraME spatial model

The space local properties, constraints, and connectivity can be modeled by:

- a set of geographic data: each cell has various attributes

GIS

- a spatial structure: a lattice of cellsA cell-space where each cell a unique neighborhood

- Space is nether isomorphic nor structurally homogeneous. (Couclelis 1997)

- Actions at a distance are considered. (Takeyana 1997), (O’Sullivan 1999)

TerraME extensions to Lua

To build spatial dynamic models, TerraME includes new value types in LUA using the constructor mechanism.

These values are: CellularSpace, Cell, Neighbourhood

Cellular Space

A CellularSpace is a multivalued set of Cells.

It consists of a geographical area of interest, divided into a regular grid.

Each cell in the grid has one or more attributes.

CellularSpaces are stored and retrieved from a TerraLib database, so the modeller should specify the properties of the CellularSpace

Constructors in Lua

LUA has a powerful syntactical tool, called constructor.

When the modeller writes name{…}, the LUA interpreter replaces it by name({… }), passing the table {…} as a parameter to the function name( ).

This function typically initializes, checks properties values and adds auxiliary data structure or methods.

Loading Data

-- Loads the TerraLib cellular spacecsQ = CellularSpace{

dbType = "ADO",host = “localhost",database = "c:\\TerraME\\Database\\CabecaDeBoi.mdb",user = "",password = "",layer = "cellsLobo90x90",theme = "cells",select = { "altimetria", “soilWater", “infCap" }

}csQ:load();createMooreNeighborhood(csQ);csCabecaDeBoi:loadNeighborhood(“Moore_SerraDoLobo1985");

GIS

Database management

-- loads a cellular spacecsAmazonia:load();csAmazonia:createMooreNeighborhood();-- csAmazonia:loadNeighborhood (“GPM”);

…-- save (time, themeName, attrTableName) -- for time = 1, 10,1 do csAmazonia:save(time, “sim", {"water"});end

Referencing cells

A CellularSpace has a special attribute called cells. It is a one-dimensional table of references for each Cell in the CellularSpace

-- c is the seventh cell in the cellular spacec = csCabecaDeBoi.cells[ 7 ];-- Updating the attribute “infcap” from the

seventh cellc.infcap = 10;print (csCabecaDeBoi.cells[7].infCap);

The Cell type

A Cell value has two special attributes: latency and past. The latency attribute registers the period of time since the

last change in a cell attribute value.The past attribute is a copy of all cell attribute values in

the instant of the last change.

if(cell.cover == "abandoned" and cell.latency >= 10 ) then cell.cover = "secFor"; end

cell.water = cell.past.water + 2;

Traversing a Cell Space

ForEachCell(cs, function())

Applies the chosen function to each cell of the cellular space. This function enables using different rules in a cellular space.

ForEachCell(csQ, function(i, cell) cell.water = cell.past.water + 2; return true; end);

Traversing a NeighbourhoodForEachCell(csQ,

function(i, cell) count = 0; ForEachNeighbor(cell, 0,

function(cell, neigh) if (neigh ~= cell) then

count = count + 1; end -- if end ); -- for each neighbor

cell.value = count; …. end); --

Von Neumann Neighborhood

Moore Neighborhood

Isotropic neighbourhoods in cell spaces

Generalized Proximity Matrix (GPM)

In a cell-space, each cell has a different neighbourhood

Defined by a NxN matrix

44434241

34333231

24232221

14131211

wwww

wwww

wwww

wwww

W

One simple example Consider a 5x 5 cell-space For each cell, a different matrix The neighbours of a cell (the (2,3) cell are):

0 0 1 1 0

0 0 * 1 0

0 0 1 1 0

0 0 1 1 0

0 0 1 0 0

Using Generalized Proximity Matrices

Consolidated area Emergent area

SynchronizationLeia sempre do antigo (“past”)Escreva sempre no novo (“present”)Sincronize no final

ForEachCell ( csValeDoAnary )

end

count = 0 ;

print(“Number of deforested cells: ”.. count);

Function (I, cell)

if ( cell.past.cover == “forest” ) then

cell.cover = “deforested”;

count = count + 1 ;

end

cell.synchronize( );

Syncronizationtn tn+1

rule

?

fonte: Carneiro (2006)

TerraME basics: some simple examples

An Example: The Majority Model for Segregation Start with a CA with “white” and “black” cells (random)

The new cell state is the state of the majority of the cell’s Moore neighbours, or the cell’s previous state if the neighbours are equally divided between “white” and “black” White cells change to black if there are five or more black

neighbours Black cells change to white if there are five or more black

neighbours What is the result after 50 iterations? How long will it take for a stable state to occur?

The Modified Majority Model for Segregation

Include random individual variation Some individuals are more susceptible to their neighbours

than others In general, white cells with five neighbours change to black,

but: Some “white” cells change to black if there are only four “black”

neighbours Some “white” cells change to black only if there are six “black”

neighbours Variation of individual difference

What happens in this case after 50 iterations and 500 iterations?

Key property of cellular spaces: potential

POTENTIAL

What is the potential of a cell?

Potential refers to the capacity for change

Higher potential means higher chance of change

How can we compute potential?

Potential

People

Nature

Different models for calculating potential

Brian Arthur’s model of increasing returns

Vicsek-Salay model: structure from randomness

Schelling’’s model: segregation as self-organization

The Brian Arthur model of increasing returns

Create a cell space and fill it with random values For example, take a 30 x 30 cell space and populate

with random values (1..1000)

The Brian Arthur model of increasing returns

Think of this cellular space as the starting point for a population

What happens if the rich get richer?

This model is called “increasing returns” This effect is well-known in the software industry Customer may become dependent on proprietary data formats High switching costs might prevent the change to another

product Examples: QWERTY keyboard, and Microsoft Windows

Arthur, B. (1994). “Increasing Returns and Path Dependence in the Economy”. Ann Arbor, MI: The University of Michigan Press.

The Brian Arthur model of increasing returns

Consider a situation where the potential grows with a return factor ( is a scale factor)

O < < 1 - decreasing returns (increased competition)

= 1 – linear growth > 1 – increasing returns (rich get richer)

)()1( tPtP ii

The Brian Arthur model of increasing returns

Take the random 30 x 30 cell space and apply the increasing returns model = 2 – What happens?

The Vicsek-Szaly Model: Structure from Randomness

Consider a CA with a 4 x 4 neighbourhood

Establish a random initial distribution Historical accident that

set the process in motion

Pure averaging model

)()0( noiseP ii

5

)(

)1(

jjj

i

tP

tP

TerraME: defining a model

Model implementation in TerraME

Land Unitn

Land Unit2

Land Unit1

...Rondônia

G

Global rate

...

+

+

+

Rsmall

Rlarge

Rsmall

(two types of agentes Rsmall and R large)

+

+

+

Asmall

Alarge

Asmall

...

(two types of agentes Asmall and A large)

Each Land Unit is an environment, nested in the Rondônia environment.

Environment

Agent

Legend

TerraME rules of behaviour

How can we define rules of behaviour?

stats inference model

tn tn+1

inputresults

analysis

1

2

modelling

theory

model

tn tn+1

inputresults

2

modelling

1

laws

theory-driven models

data-driven models

Types of models

Theory-driven models General laws and rules Can deal with non-stationary phenomena

Data-driven models Rules derived from statistical inference Case-specific Stationary phenomena

Models of Computation

Agent based models Cellular automata models

(Rosenschein and Kaelbling, 1995)

(Wooldbridge, 1995)

(von Neumann, 1966) (Minsky, 1967)

(Aguiar et al, 2004)

(Pedrosa et al, 2003)

(Straatman et al, 2001)

Which Cellular Automata?

For realistic geographical models the basic CA principles too constrained to be useful

Extending the basic CA paradigm From binary (active/inactive) values to a set of

inhomogeneous local states From discrete to continuous values (30% cultivated land,

40% grassland and 30% forest) Transition rules: diverse combinations Neighborhood definitions from a stationary 8-cell to

generalized neighbourhood From system closure to external events to external output

during transitions

Spatial dynamic modeling

Locations change due to external forces

Realistic representation of landscape

Elements of dynamic models

Geographical space is inhomogeneous

Different types of models

discretization of space in cells

generalization of CA

discrete and continous processes

Flexible neighborhood definitions

Extensibility to include user-defined models

Demands Requirements

Hybrid Automata

Formalism developed by Tom Henzinger (UC Berkeley) Applied to embedded systems, robotics, process control,

and biological systems Hybrid automaton

Combines discrete transition graphs with continous dynamical systems

Infinite-state transition system

Traditional Cellular Automata Discrete state transition system (e.g, Life)

At each step in time, the following effects occur: Any live cell with fewer than two neighbors dies, as if by

loneliness. Any live cell with more than three neighbors dies, as if by

overcrowding. Any live cell with two or three neighbors lives, unchanged,

to the next generation. Any dead cell with exactly three neighbors comes to life.

Alive Dead

0,1 or 4+ neighbours

3 neighbours

2-3 neighbours

Hybrid Automata Variables Control graph Flow and Jump conditions Events

Control Mode A

Flow Condition

Control Mode B

Flow Condition

Event

Jump condition

Event

Modelo Hidrológico Simples

A water balance Automata

DRYsoilwater=soilwater+pre-evap

WETSurplus=soilwater-infilcp

Soilwater=infilcp

input soilwater>=infilcp

input

Surplus>0

TRANSPORTINGMOVE(LDD, surplus, infilcp)

discharge

Control Mode

Flow Condition Jump Condition Event Transition

DRY Solwat=solwat+pre-evap Solwat>=infcap WET

WET Surplus=soilwater-infilcap Surplus>0 discharge TRANSP

TRANSP MOVE(LDD,surplus, infilcap) Surplus>0 input DRY

input

Agents and CA: Humans as ants

Old Settlements(more than 20 years)

Recent Settlements(less than 4

years)

Farms

Settlements 10 to 20 anos

Source: Escada, 2003

Identify different actors and try to model their actions

Actors and patterns9o S

10o S

9o 30’ S

10o 30’ S

9o S

9o 30’ S

10o S

10o 30’ S

0 50Km

62o 30’ W 62o W

62o 30’ W 62o W

Model hypothesis: Occupation processes are different for Small and

Medium/Large farms.

Rate of change is not distributed uniformly in space and time: rate in each land unit is influenced by settlement age and parcel size; for small farms, rate of change in the first years is also influenced by installation credit received.

Location of change: For small farms, deforestation has a concentrated pattern that spreads along roads. For large farmers, the pattern is not so clear.

Large farms

Medium farms

Urban areas

Small farms

Reserves

Model overview

Global study

area rate

in time

Deforestation Rate Distribution from 1985 to 2000 - Land Units Level:

Large/Medium Rate Distribution sub-model Small Farms Distribution sub-model

Allocation of changes - Cellular space level:

Large/Medium allocation sub-model Small allocation sub-model

2.500 m (large and

medium)

500 m (small)Large farms

Medium farms

Urban areas

Small farms

Reserves

Land unit 1 rate t

Land unit 2 rate t

Deforestation Rate Distribution Module

Newly implanted

Deforesting

Slowing down

latency > 6 years

Deforestation > 80%

Small Units Agent

Factors affecting rate: Global rate Relation properties density -

speedy of change Year of creation Credit in the first years (small)

Iddle

Year of creation

Deforestation = 100%

Large and Medium Units AgentDeforesting

Slowing downIddle

Year of creation

Deforestation = 100%

Deforestation > 80%

Allocation Module: different factors andrules

Factors affecting location of changes:

Small Farmers (500 m resolution): Connection to opened areas

through roads network Proximity to urban areas

Medium/Large Farmers (2500 m resolution):

Connection to opened areas through roads network

Connection to opened areas in the same line of ownerships

Allocation Module: different resolution, variables and neighborhoods

1985

1997 1997Large farm environments:

2500 m resolution

Continuous variable:% deforested

Two alternative neighborhood relations:•connection through roads• farm limits proximity

Small farms environments:

500 m resolution

Categorical variable: deforested or forest

One neighborhood relation: •connection through roads

Model implementation in TerraME

Land Unitn

Land Unit2

Land Unit1

...Rondônia

G

Global rate

...

+

+

+

Rsmall

Rlarge

Rsmall

(two types of agents Rsmall and R large)

+

+

+

Asmall

Alarge

Asmall

...

(two types of agents Asmall and A large)

Each Land Unit is a scale, nested in the Rondônia scale.

Environment

Agent

Legend

Defining a model – part 3: TerraME temporal model

Asynchronous ProcessesMultiple Temporal Resolutions

The TerraME Timer

1:32:00 Mens. 11.

1:32:10 Mens. 32.

1:38:07 Mens. 23.

1:42:00 Mens.44.

Execute an agent over the cellular space regions

Save the spatial data

Draw cellular spaces and agents states

Carrie out the comunication between agents

. . .return value

true

1. Get first pair 2. Execute the ACTION

3. Timer =EVENT

4. timeToHappen += period

TerraME Timer Object

Neighborhood based rules & Time

Rule:

if ( all neighbors = 1 ) then 0

General rule form:

cell.soilWater= cell. soilWater + 2;

111

111

111

111

111

111

ttt

ttt

ttt

111

111

11

111

111

110

ttt

ttt

ttt

1º step

111

111

11

111

111

110

ttt

ttt

ttt

2º step

111

111

111

111

111

111

ttt

ttt

ttt

111

111

11

111

111

110

ttt

ttt

ttt

1º step

111

111

11

111

111

110

ttt

ttt

ttt

2º step

ttt

ttt

ttt

111

111

111

111

111

111

111

111

111

ttt

ttt

ttt

1º step

ttt

ttt

ttt

111

111

110

111

111

111

111

111

111

ttt

ttt

ttt

2º step

ttt

ttt

ttt

111

111

100

111

111

111

111

111

111

ttt

ttt

ttt

one copy of thecellular space

past

present

update

Temporal inconsistency

for i, cell ipairs( csValeDoAnary ) do

end

count = 0 ;

print(“Number of deforested cells: ”.. count);

if ( cell.past.cover == “forest” ) then

cell.cover = “deforested”;

count = count + 1 ;

end

cell.synchronize( );

Runtime Rule Activitytn tn+1

rule

?

TerraME Synchronization Schemes

Processes Might Be

Sequential in Time Parallel in Time

Sequential in Space execute(globalAutomaton1);synchronize( );execute(globalAutomaton2);synchronize( );

execute(globalAutomaton1);execute(globalAutomaton2);synchronize( );

Parallel in Space execute(localAutomaton1);synchronize( );execute(localAutomaton2);synchronize( );

execute(localAutomaton1);execute(localAutomaton2);synchronize( );

What is a Cell-Space?

Raster spatial data structure where each cell can handle one or more types of attribute.

Cell spaces were used in some of the very early GIS implementations and have been since discarded in most GIS implementations in favor of one-attribute raster data structures.

Cell spaces allow easier integrated modelling in a GIS environment

Cell Spaces

(a) land_cover equals deforested in 1985 (a) land_cover equals deforested in 1985

attr_id object_id initial_time final_time land_cover dist_primary_road dist_secondary_roadC34L181985-01-0100:00:001985-12-3123:59:59C34L18 01/01/1985 31/12/1985 forest 7068.90 669.22C34L181988-01-0100:00:001988-12-3123:59:59C34L18 01/01/1988 31/12/1988 forest 7068.90 669.22C34L181991-01-0100:00:001991-12-3123:59:59C34L18 01/01/1991 31/12/1991 forest 7068.90 669.22C34L181994-01-0100:00:001994-12-3123:59:59C34L18 01/01/1994 31/12/1994 deforested 7068.90 669.22C34L181997-01-0100:00:001997-12-3123:59:59C34L18 01/01/1997 31/12/1997 deforested 7068.90 669.22C34L182000-01-0100:00:002000-12-3123:59:59C34L18 01/01/2000 31/12/2000 deforested 7068.90 669.22C34L191985-01-0100:00:001985-12-3123:59:59C34L19 01/01/1985 31/12/1985 forest 7087.29 269.24C34L191988-01-0100:00:001988-12-3123:59:59C34L19 01/01/1988 31/12/1988 deforested 7087.29 269.24C34L191991-01-0100:00:001991-12-3123:59:59C34L19 01/01/1991 31/12/1991 deforested 7087.29 269.24C34L191994-01-0100:00:001994-12-3123:59:59C34L19 01/01/1994 31/12/1994 deforested 7087.29 269.24C34L191997-01-0100:00:001997-12-3123:59:59C34L19 01/01/1997 31/12/1997 deforested 7087.29 269.24C34L192000-01-0100:00:002000-12-3123:59:59C34L19 01/01/2000 31/12/2000 deforested 7087.29 269.24

Cell-space x Cellular Automata

CA Homogeneous, isotropic space Local action One attribute per cell (discrete values) Finite space state

Cell-space Non-homogeneous space Action-at-a-distance Many attributes per cell Infinite space state

Hybrid Automata

Formalism developed by Tom Henzinger (UC Berkeley) Applied to embedded systems, robotics, process control,

and biological systems Hybrid automaton

Combines discrete transition graphs with continous dynamical systems

Infinite-state transition system

Hybrid Automata

Variables Control graph Flow and Jump conditions Events

Control Mode

A

Flow

Condition

Control Mode

B

Flow

Condition

Event

Jump condition

Event

Neighborhood Definition

Traditional CA Isotropic space Local neighborhood definition (e.g. Moore)

Real-world Anisotropic space Action-at-a-distance

TerraME Generalized calculation of proximity matrix

Space is Anisotropic

Spaces of fixed location and spaces of fluxes in Amazonia

Motivation

Which objects are NEAR each other?

Motivation

Which objects are NEAR each other?

Using Generalized Proximity Matrices

Consolidated area Emergent area

Computational Modelling with Cell Spaces

Cell Spaces

Components Cell Spaces Generalizes Proximity Matriz – GPM Hybrid Automata model Nested enviroment

TerraME basic concepts

An environment on the Earth could be modeled as a synthetic environment in the computer representation world…… which has three dimensions:

Space, time and behavior.

Environment: A Key Concept in TerraME

An environment has 3 kinds of sub models: Spatial Model: cellular space + region + GPM (Generalized

Proximity Matrix) Behavioral Model: hybrid automata + situated agents Temporal Model: discrete event simulator

The spatio-temporal structure is shared by several communicating agents

Support for Nested Environments

UU

U

Environments can be nested

Space can be modelled in different resolutions

Multiscale modelling

Agents: Local Global

Behavioural Model

Software Architecture

TerraLib

TerraLib TerraME Framework

C++ Signal Processing

librarys

C++ Mathematical

librarys

C++ Statisticallibrarys

TerraME Virtual Machine

TerraME Compiler

TerraME Language

RondôniaModel São Felix Model Amazon Model Hydro Model

http://www.terralib.org/

Deforestation

Forest

Non-forest

Deforestation Map – 2000 (INPE/PRODES Project)

Introduction: Rondônia modeling exercise study area

km

Projetos de Colonização

10

8

15

1614

13

Projetos antigosNovos projetosProjetos planejados

km

Projetos de Colonização

10

8

15

1614

13

Projetos antigosNovos projetosProjetos planejados

Projetos antigosNovos projetosProjetos planejados

Federal Government induced colonization area (since the 70s):

Small, medium and large farms. Mosaic of land use patterns. Definition of land units and typology

of actors based on multi-temporal images (85-00) and colonization projects information (Escada, 2003).

Intersects 10 municipalities (~100x200 km).

Actors and patterns9o S

10o S

9o 30’ S

10o 30’ S

9o S

9o 30’ S

10o S

10o 30’ S

0 50Km

62o 30’ W 62o W

62o 30’ W 62o W

Model hypothesis: Occupation processes are different for

Small and Medium/Large farms.

Rate of change is not distributed uniformly in space and time: rate in each land unit is influenced by settlement age and parcel size; for small farms, rate of change in the first years is also influenced by installation credit received.

Location of change: For small farms, deforestation has a concentrated pattern that spreads along roads. For large farmers, the pattern is not so clear.

Large farms

Medium farms

Urban areas

Small farms

Reserves

Model overview

Global study

area rate

in time

Deforestation Rate Distribution from 1985 to 2000 - Land Units Level:

Large/Medium Rate Distribution sub-model

Small Farms Distribution sub-model

Allocation of changes - Cellular space level:

Large/Medium allocation sub-model

Small allocation sub-model

2.500 m (large and

medium)

500 m (small)Large farms

Medium farms

Urban areas

Small farms

Reserves

Land unit 1 rate t

Land unit 2 rate t

Model implementation in TerraME

Land Unitn

Land Unit2

Land Unit1

...Rondônia

G

Global rate

...

+

+

+

Rsmall

Rlarge

Rsmall

(two types of agentes Rsmall and R large)

+

+

+

Asmall

Alarge

Asmall

...

(two types of agentes Asmall and A large)

Each Land Unit is an environment, nested in the Rondônia environment.

Environment

Agent

Legend

Deforestation Rate Distribution Module

Newly implanted

Deforesting

Slowing down

latency > 6 years

Deforestation > 80%

Small Units Agent

Factors affecting rate: Global rate Relation properties density -

speedy of change Year of creation Credit in the first years

(small)

Iddle

Year of creation

Deforestation = 100%

Large and Medium Units AgentDeforesting

Slowing downIddle

Year of creation

Deforestation = 100%

Deforestation > 80%

Allocation Module: different factors andrules

Factors affecting location of changes:

Small Farmers (500 m resolution): Connection to opened

areas through roads network

Proximity to urban areas

Medium/Large Farmers (2500 m resolution):

Connection to opened areas through roads network

Connection to opened areas in the same line of ownerships

Allocation Module: different resolution, variables and neighborhoods

1985

1997 1997Large farm environments:

2500 m resolution

Continuous variable:% deforested

Two alternative neighborhood relations:•connection through roads• farm limits proximity

Small farms environments:

500 m resolution

Categorical variable: deforested or forest

One neighborhood relation: •connection through roads

1985 1988 1991

1994 1997

Simulation Results

Simulation Results

1985 to 1997

Contributions TerraME models many aspects of spatial and temporal

Rondônia study area complexity combining: Multiple scales Multiple actors and behaviors Multiple time events and assynchronous processes Alternative neighborhood relationships Continuous and discrete behavior

Calibration and Validation

M

t1980

t1990

M

t1990 t2000

t2000

dados reais

dados simulados

M

t2010

Ajustou?Ajustou?calibração validação

t2010?

Data Coherence

Distancia a centros urbanos

Data Coherence

1985 1988 1991

1994 1997 2000

Processo de desflorestamento

Conclusions

Computational modelling on cellular spaces is an emerging trend in land use modelling

Realistic assumptions are built in TerraME We have tried to avoid the five orders of ignorance

TerraME is an evolving project We hope to learn more as we do further experiments

Spatial Dynamical Modeling with TerraME

Tiago Garcia de Senna CarneiroAntônio Miguel Vieira MonteiroGilberto Câmara

TerraME Concepts: An Earth’s environment …

can be represented as a synthetic environment…… where analytical entities (rules) change the space properties in time.Several interacting entities share the same spatiotemporal structure.

myModel = Enviroment{ id = "myModel", -- Add cellular spaces (spatial dimension) cs1 = CellularSpace{ … },

-- Add rules (behaviour) rul1 = Automata{ … },… -- Add timer (temporal dimension) t1 = Timer{ … }, -- glue rules to spaces

} myModel.execute();

myModel = Enviroment{ id = "myModel", -- Add cellular spaces (spatial dimension) cs1 = CellularSpace{ … }, cs2 = CellularSpace{ … },

-- Add rules (behaviour) rul1 = Automata{ … },… rulN = Automata{ … }, -- Add timers (temporal dimension) t1 = Timer{ … }, tN = Timer{ … },

} myModel.execute();

myModel = Enviroment{ id = "myModel", -- Add cellular spaces (spatial dimension) cs1 = CellularSpace{ … },

-- Add rules to this CA (behaviour) rul1 = Automata{ … },… -- Add timers to this CA (temporal dimension) t1 = Timer{ … },

-- Add CA to this CA (nested-CAs) model1 = Environment{ … } … model2 = Environment{ … }, } myModel.execute();

Simulation of Physical Processes

- rain drainage in a terrain -

O Brasil “from the space”2000

Espinhaço Range

Minas Gerais State “from the space”

2000

Point of View

Itacolomido Itambé Peak

Lobo’s Range

Itacolomido Itambé Peak

Lobo’s Range

9 km

9 km

rainrain rain

N

Itacolomi do ItambéPeak Lobo’s Range

Picture direction

Itacolomido Itambé Peak

Lobo’s Range

SimulationResult(36 min.)

TerraME Advanced: Non- isotropic spaces

Von Neumann Neighborhood

Moore Neighborhood

Isotropic neighbourhoods in cell spaces

Neighborhood Definition

Traditional CA Isotropic space Local neighborhood definition (e.g. Moore)

Real-world Anisotropic space Action-at-a-distance

TerraME Generalized calculation of proximity matrix

Space is anisotropic

Spaces of fixed location and spaces of fluxes in Amazonia

Motivation

Which objects are NEAR each other?

Motivation

Which objects are NEAR each other?

Geographical space is multidimensional

Spaces of absolute locations Determined by cartesian coordinates of

objects

Spaces of relative locations Determined by connectivity properties

of objects

Challenge to GIS applications Capture spatial relations in absolute

and relative spaces

How do we capture nearness relations?

Traditional spatial analysis techniques Operate in absolute space Two objects are near if...

They are close in euclidian distance OR

They “touch” each other

Spatial weights matrix Constructed from pairwise

spatial relations Example – using “touch”

44434241

34333231

24232221

14131211

wwww

wwww

wwww

wwww

W

P2

P3

otherwisew

OtouchOifw

ij

jiij

,1

,1

Generalized Proximity Matrix (GPM)

In a cell-space, each cell has a different neighbourhood

Defined by a NxN matrix

44434241

34333231

24232221

14131211

wwww

wwww

wwww

wwww

W

One simple example Consider a 5x 5 cell-space For each cell, a different matrix The neighbours of a cell (the (2,3) cell are):

0 0 1 1 0

0 0 * 1 0

0 0 1 1 0

0 0 1 1 0

0 0 1 0 0

Using Generalized Proximity Matrices

Consolidated area Emergent area

TerraME

O que é TerraME? Quais os requisitos? Quais as principais características? Arquitetura e componentes Onde obter?

TerraME: quais as principais características?

Acesso direto a um banco de dados celular espaço-temporal

Espaço pode ser não isotrópico: relações de vizinhança convencionais e por rede

Conceito de Ambientes aninhados: Diferentes comportamentos no espaço e tempo no mesmo

modelo Diferentes escalas temporais e espaciais no mesmo

modelo Diferentes relações de vizinhança no mesmo modelo Multiplas abordagens de modelagem no mesmo modelo:

agentes, automatos celulares, modelos de simulação, etc.

Características: Integração com Banco de dados geográfico

fonte: Carneiro (2006)

Espaço celular em ambiente Terralib/TerraView

Características: Relações de proximidade através de redes

Forest

Deforested

No data

Non-forest-

Water

Roads

100 km

Transamazônica

Br 163-

São Felix do Xingu

Prodes/INPE

Fontes: Aguiar et al., 2003

Redes físicas ou lógicas: estradas,linhas de transmissão, comunicão,mercado

Um ambiente tem três sub-modelos Espacial: espaço celular, relações de proximidade Comportamental: modelos celulares, autômatos, agentes situados,etc. Temporal:

Características: Conceito de Ambiente em TerraME

Cellular space

Características: Ambientes podem ser aninhados

Prodes/INPE 2000-2001

Cada ambiente aninhado tem seu próprio modelo temporal, comportamental e espacial

Agriculture to urban

Natural vegetation/water to urban

Agriculture/natural vegetation to water

Water to agriculture

Landsat 1988–96

(K. Seto, Boston U.)

Ambientes aninhados: possibilitam modelos de comportamento, espaço e tempo heterogêneos

Ambientes aninhados: possibilitam modelos de comportamento, espaço e tempo heterogêneos

2500 m 2.500 m e 500 m

Exemplo: múltiplas resoluções espaciais para modelar áreas de pequeno e grandes

Ambientes aninhados: possibilitam modelos de comportamento, espaço e tempo heterogêneos

Carneiro et al., 2004 (Amsterdam LUCC WS)

1985

1997 1997Large farm environments:

2500 m resolution

Continuous variable:% deforested

Two alternative neighborhood relations:•connection through roads• farm limits proximity

Small farms environments:

500 m resolution

Categorical variable: deforested or forest

One neighborhood relation: •connection through roads

Exemplo de modelo de alocação de desflorestamento em Rondônia:resoluções diferentes, variáveis, fatores e relações de vizinhança

Carneiro et al., 2004 (Amsterdam LUCC WS)

Simulation Results

1985 to 1997

Ambientes aninhados: modelagem multi-escala

Prodes/INPE 2000-2001

TerraME

O que é TerraME? Quais os requisitos? Quais as principais características? Arquitetura e componentes Onde obter?

TerraLib

TerraLib EnviromentalModeling Framework

C++ Signal Processing

librarys

C++ Mathematical

librarys

C++ Statisticallibrarys

TerraME Virtual Machine

TerraME: arquitetura e aplicações

TerraME Compiler

TerraME Language

SãoFelixAgentsModel RunoffModel TROLLModel CLUE

fonte: Carneiro (2006)

Amazonia Prata

TerraME: componentes

Eclipse & LUA plugin• model description• model highlight syntax

TerraView• data acquisition• data visualization• data management• data analysis

TerraLibdatabase

da

ta

Model source code

MODEL DATA

mod

el

• model syntax semantic checking• model execution

TerraME INTERPRETER

LUA interpreter

TerraME framework

TerraME/LUA interface

model d

ata

fonte: Carneiro (2006)