1 / 169

Enviromental Modelling Introduction to TerraME

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.

Télécharger la présentation

Enviromental Modelling Introduction to TerraME

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Enviromental ModellingIntroduction to TerraME Tiago Garcia de Senna Carneiro (UFOP) Gilberto Câmara (INPE)

  2. Dynamic Spatial Models f (It) f (It+1) f (It+2) f ( It+n ) F F . . “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)

  3. Forecast tp + 10 Calibration Calibration Dynamic Spatial Models tp - 20 tp - 10 tp Source: Cláudia Almeida

  4. 1980 1990 GIS t+1 load 2000 When? Where? t ≥ tf How? CLUE Model Spatial dynamical models have a common structure How much? idle play

  5. What is a spatial dynamical model? • A closed microworld with • Spatial and temporal structure • Entities • Rules of behaviour What is changing? When? Where? Why?

  6. Computational Modelling with Cell Spaces Cell Spaces • Hybridautomata Control Mode A Flow Condition Control Mode B Flow Condition Event Jump • GeneralizedProximityMatrix • Database support

  7. Cell Spaces

  8. 2500 m 2.500 m e 500 m Cellular Data Base Resolution

  9. Software: Open source GIS Visualization (TerraView) Modelling (TerraME) Spatio-temporal Database (TerraLib) Statistics (R interface) Data Mining(GeoDMA)

  10. TerraLib EnviromentalModeling Framework C++ Signal Processing librarys C++ Mathematicallibrarys C++ Statisticallibrarys TerraME architecture RondôniaModel DinamicaModel TROLLModel CLUEModel TerraME Language TerraME Compiler TerraME Virtual Machine TerraLib

  11. TerraME functionality

  12. Enviromental ModellingIntroduction to LUA Tiago Garcia de Senna Carneiro (UFOP) Gilberto Câmara (INPE)

  13. 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”

  14. 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) end end

  15. Tipos • Tipos associados a valores • Variáveis armazenam qualquer tipo • Polimorfismo natural • Tipos existentes • nil • boolean • number • string • table • function • userdata • thread

  16. 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

  17. Tipo boolean • Valor booleano • Falso (false) ou verdadeiro (true) • if (choveu == true) then ....

  18. Tipo number • Único tipo nativo para valores numéricos • double (por default) local a = 3 local b = 3.5 local c = 4.5e-8

  19. 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

  20. 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”;

  21. 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

  22. 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.

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

  24. Tipo Table loc = { cover = "forest", distRoad = 0.3, distUrban = 2 }; loc.cover = “cerrado”; loc[“cover”] = “soja”; if (loc.distUrban > 1.5) then loc.desfPot = loc.distRoad + loc.distUrban;

  25. 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 };

  26. Data structures with tables • Simple and efficient implementation • Records • Syntactic sugar t.x for t["x"]: t = {} t.x = 10 t.y = 20 print(t.x, t.y) print(t["x"], t["y"])

  27. Data structures with tables (2) for i=1,n do print(a[i]) end • Arrays • Use integers as indexes • Sets • Use elements as indexes • “Bags" • Elements as indexes, counters as values t = {} t[x] = 1 -- t = t  {x} if t[x] then... -- x  t?

  28. list = {value=v, next=list} value - v next - 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 old list ...

  29. Library functions for tables • table.insert • Inserts a new element • table.remove • Removes an element • table.sort • Orders the elements

  30. My first Lua program C = 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 do solo.acum = solo.acum + C – solo.k*solo.acum; end

  31. function inc (x) return x+1 end inc = function (x) return x+1 end sugar Type function Funções are first-class values Functions can be assigned to table fields if w.pick(x,y) then w.redraw() end w = { redraw = function () ... end, pick = function (x,y) ... end, }

  32. Type function (2) • Passagem por valor e retorno múltiplo • Suporte a atribuições múltiplas (x,y = y,x) a, b = f() print(f()) function f() return 1,2 end • Suporte a número variável de argumentos • Argumentos "empacotados" em uma tabela function f(...) print(arg[1], arg[2]) end

  33. 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 end end add1 = add(1) print(add1(10)) --> 11 upvalue

  34. 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"] = 1975 article(temp)

  35. function a:foo (x) ... end a.foo = function (self,x) ... end sugar sugar a:foo(x) a.foo(a,x) 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...

  36. Exemplo: tipo Point -- Metatable de Point local Point_metatable = { __add = function (p1,p2) return Point(p1.x+p2.x,p1.y+p2.y,p1.z+p2.z} end } -- Construtor function 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 self 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+q -- {7.2, 2.3, 3.2}

  37. Herança Simples: mecanismo de delegação -- Métodos local Point_methods = { Print = function (self) print(self.x, self.y, self.z) end, ... } -- Metatable local 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+q r:Print()

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

  39. Basic • Oferecem funções básicas • print • type • setmetatable • pairs

  40. 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

  41. Meu segundo programa em Lua C = 2; -- rain/t K = 0.4; -- flow coefficient q = 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); end end -- for time = 0, 20, 1 do -- soil water q = q + chuva(time) - K*q; end -- report print(“q = "..q);

  42. Defining a model in TerraME Part 1: The cell space

  43. Cell Spaces • Components • Cell Spaces • Generalizes Proximity Matriz – GPM • Hybrid Automata model • Nested enviroment Computational Modelling with Cell Spaces fonte: Carneiro (2006)

  44. is represented as a cell space environment… … where automatarules change the space properties in time. Several agents can share the same environment. Basic concepts A dynamical model…

  45. GIS The TerraME spatial model The space local properties, constraints, and connectivity can be modeled by: A 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) - a spatial structure: a lattice of cells - a set of geographic data: each cell has various attributes

  46. TerraME extensions to Lua • To build spatial dynamic models,TerraME includes new value types in LUA usingthe constructor mechanism. • These values are: CellularSpace, Cell, Neighbourhood

  47. 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

  48. Constructors in Lua • LUA has a powerful syntactical tool, called constructor. • When the modeller writes name{…}, the LUA interpreter replacesit 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.

  49. GIS Loading Data -- Loads the TerraLib cellular space csQ = 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");

  50. Database management -- loads a cellular space csAmazonia:load(); csAmazonia:createMooreNeighborhood(); -- csAmazonia:loadNeighborhood (“GPM”); … -- save (time, themeName, attrTableName) -- for time = 1, 10,1 do csAmazonia:save(time, “sim", {"water"}); end

More Related