LEGAL

This page describes the LEGAL programming language - Algebra Based Space Geographic Language. The following subjects will be discussed:

LEGAL Programming
LEGAL Program Structure
Syntax Diagrams

LEGAL Reserved Words
Using Operators in LEGAL
Application Examples

Check below how to run a LEGAL program


See also
Digital Terrain Model (DTM) Concepts
Digital Image Processing Techniques
Geoprocessing and Decision Support
Spatial Analysis


LEGAL Programming - Maps Algebra


How to Execute Map Algebra

This page presents the procedures for defining the operations on data represented in a project of a SPRING database, on the form of algebric expressions such as: Thematic, Numeric, Image, Cadastral, Objects and Real, which were defined by the user using the LEGAL language.

On a map algebra, the operations might be described according to expressions similar to the ones used in mathematics which present arithmetic and boolean operations, except that they involve spatial data representation instead of numbers. A language that defines such expressions must allow the description of local, focal and zonal operations.

A Local operation characterizes each location in a study area (under a given spatial resolution) as a function of  its corresponding values given by one or more other data representations of the same area.

Focal (or neighboring) operations characterize a location in the study area in terms of a
selected set of values from locations in their vicinity. This class of operations is  not
actually, explicitly implemented in LEGAL. Howevver, a wide class of such operations can
be described by explicitly reffering each neighboring location involved in operations.
This is done by means of a "shifting" mechanism in which a neighboring location is given
in terms of  how many lines and columns it is appart from a focus location.

Zonal operations result from evaluating simple statistics on sets of local values (given
by any local operation) distributed by zones specified by means of boolean operations or
by a set of vector features.

LEGAL is strongly based on the Spring data model. The operators run over data representations of Numeric (regular grids), Image, Thematic, Cadastral and Object models. The Object and Cadastral models are complementary and allow spatialization of database table attributes using cadastral maps. The data model and operators are coherent and help interpreting the language sentences, providing a greater semantic control of spatial models definition. The syntax and running error messages help users on building the programs.

A LEGAL program consists in a sequence of operations described by sentences organized following certain rules and involving operators, functions and spatial data. Information Layers of Numeric and Image categories correspond to representations in raster format. Most operators of the Thematic model also use raster representation. Cadastral model maps, that represent data from the Object model, use representations on vector format.

Back


LEGAL Program Structure

A LEGAL program is composed by sentences (command lines) that are structured in four parts: declarations, instantiations, operations and commands:

  • Declaration: this is where the work variables are defined. Each variable must be explicitly declared with a name and associated to a category within the conceptual scheme.
  • Instantiation: this is where existent data are recovered from the database or a new Information Layer is created. Afterward, this new IL can be associated to the result of LEGAL operations.
  • Operations: this is where the map algebra is performed. They correspond to the application of one or more operators or functions over variables previoulsy declared and instantiated. They are described by algebraic expressions, following rules that allow the recursive definition of complex operations from simpler ones, based on data properties and involved operators. The assigning operation consists in assigning the result of the evaluation of an algebraic expression to a previously defined variable.
  • Commands: they allow the control of the program processing flow, being essential at situations that involve the following types of operations execution: alternative, conditional or repetitive.

Back


Syntactic Diagram

In LEGAL, each sentence might include symbols (for example, ‘{‘, ‘(‘, ‘;’, ‘,’), operators (for example, ‘+’, ‘*’, ‘&&’, ‘||’, ‘<‘, ‘<=‘, ‘!=‘), reserved words (for example, New, Thematic, Name, ResX), variable names (soils, veg, atitudes, ind_verde etc.) and item names of a SPRING database (ILs, cadastral maps, categories, geo-classes, attributes etc.).

The descritpion of the sentences, depicted as syntactic diagrams, indicates through arrows, the possible paths to make up valid sentences in LEGAL. The reserved mandatory words are written in bold (first character in caps);the words not capitalized indicate variable names; the words written between quotes indicate database items names and the italic ones indicate syntactic items that will be decribed in a separate diagram.

The item program corresponds to the following syntactic diagram:

The diagram above indicates that a LEGAL program starts with a '{' , can have many sentences of the types declarations, instantiations and operations ended by a ';', and finishes with a '}'.

Example:

This program determines a regular grid of vegetation indexes calculated, for each position of the grid, using images that correspond to 3 and 4 from LANDSAT TM sensor:

        ivdn = (band 4 - band 3)/(band4 + band3).

As yor can see, first yor need to declare the variables that will represent each one of the LANDSAT images involved (input data) as well as the output grid (output data). Therefore, it is necessary to define three variables: band3, band4 (associated to the Image model) and ivdn (associated to the Numeric model). These categories between quotes must be defined in the data model of the active SPRING database.

Now we have the declarations:

Image band3, band4 ("Landsat_TM");
Numeric ivdn ("Indexes");

It is necessary to  instantiate the variables, by associating them to information layers containing representations that will be involved in the algebraic operations. Considering the example above, we will need:

  1. to associate the variables band3 and band4 to existent images in ILs (for example "TM3" and "TM4"), using the the Retrieve operator.
  2. to associate a variable ivdn, using the New operator, to an information layer (for example: "IVDN"), that will be created to store the operation output.

The the Retrieve operator is used to associate an existent information layer to a variable, while the New operator creates an New information layer, to be associated to the variable.

Now, the instantiations:

band3 = Retrieve (Name = "TM3" );
band4 = Retrieve (Name = "TM4" );
ivdn = New (Name = "IVDN", ResX = 30, ResY = 30 );

Observe that some parameters besides Name must be informed in case new information layers are created using the language.

Finally the operations which involve the previously declared and instantiated variables are defined. The expressions that show the operations we wish to evaluate are described using syntactic rules:

  1. Multiplication and division have priority over addition and subtraction;
  2. Parenthesis ('(' and ')') change the priority natural order;
  3. The properties associative, commutative and distributive for artihmetic and boolenan operators also work for spatial domain.

Then, here is the operation:

ivdn = Numeric ((band4 - band3) / (band4 + band3));

The term Numeric indicates that the outcome of an expression involving images must be understood as values to be stored in a regular grid, allowing then the representation of real numbers and not only integer (as in an Image).

A complete LEGAL program would have the following lines:

{
        Image
band3, band4 ("Landsat_TM");
        Numeric ivdn ("Indexes");
        band3 = Retrieve (Name="TM3");
        band4 = Retrieve (Name="TM4");
        ivdn = New (Name = "IVDN", ResX = 30, ResY = 30, Scale = 100000, Min = 0, Max = 1 );
        ivdn = Numeric ( ( band4 - band3 ) / ( band4 + band3 ) ) ;
}

Back


Declarations

A declaration consists in the definition of the variables that will be associated to the information layers, cadastral maps, objects, transformation tables and real values involved in a LEGAL program.

The variables can be Thematic, Numeric, Image, Cadastral and Object. There are also auxiliary variables which are associated to Tables,declared as the others and the ones associated to Real numbers that do not need to be declared.

The Thematic, Numeric and Image variables are often referred as field variables de campo and correspond to the concept of field used on the PRING data model (data with spatial extension). In a certain way, the Cadastral model can also be seen like this, aiming at supporting the objects with spatial extension though.

The Object model can be used in operations involving fields, associating objects and vector features represented in cadastral maps (points, lines and polygons). However, it is possible to define a vast class of algebraic expressions just involving Objects and their attributes, with no association with maps.


Variables Declaration

A variable declaration is the association of a Name to a model and category on the Spring active database. Then it can be associated to information layers, cadastral maps or objects, from the category and model chosen.

Syntax:

The first part indicates the data model to be associated to the variable; variable_name will be the variable identifier in the program; category_name, between quotes and parenthesis, indicates the active database category associated to the representations (fields) instantiated to the variable along the program.

Examples:

Thematic soil("Soils"), geo("Geology");
Numeric alti1 ("Altimetry");
Image band3, band4 ("LandSat");
Object obj("Estados");
Cadastral cad("DivisaoEstadual");


Declaration of Table Variables

Table variables for transformation are used to define operations based on the mapping of fields of different categories in the SPRING data model (Thematic-Thematic, Numeric-Thematic and Thematic-Numeric). In the declaration of table variables the word Table is followed by the types of transformation - Reclassification, Slicing or Weighting. The categories and values that define the mapping are established at the Instantiation phase.

Syntax:

Examples:

Table slices (Slicing), weights (Weighting);
Table reclass (Reclassification);

Back


Instantiation

The Instantiation consists in effectively associating information layers to variables from Thematic, Numeric and Image models; or cadastral mapas to variables of Cadastral model or transformation Tables to previously declared Table variables.

Variables from the Object model are not associated to spatial representations. They are only declared and the objects attributes are explicitly referred by the attribute name as it is defined on the active SPRING database.

There is no spatial representation involved in Real Variables and the Declaration and Instantiation are mixed up. When a real value is assigned to a variable name (that hasn't been declared), this will define this variable.

The New operator creates new information layers or Tables and associates them to previously declared variables. The association of variables to information layers and previously created cadastral maps is done using the Retrieve operator.


Instantiation of Field and Cadastral Variables

When an information layer associated to a variable of Thematic, Numeric or Image is created through the New operator, it is necessary to provide some parameters besides the Name:

Name

Information Layer to be associated to a variable

ResX and ResY

Resolution of an Information Layer

Scale

Scale for Thematic and Numeric ILs . (the default value is 1)

Min and Max

Range of estimated values for a numeric grid to be created

Repres

Representation to be considered. It can assume values Raster or Vector. (the default is Raster)

Nbits

Number of bits for image pixels (the default value is 8)

Interpolator

Interpolator mode for generating grids or images. It can assume the values Neighbor and Bilinear (as default).

Notice that it is not possibile to create data from the Cadastral model - they can only be retrieved.

Instantiation:

legal-04.gif (9059 bytes)

When we instantiate a variable using the Retrieve operator, the word Name followed by the information layer name of cadastral map of the active project must be provided (shown on the Control Panel).

The type of representation assumes Raster for information layers and Vector for cadastral maps. Some operations over Thematic information layers might use vector representation, and, in this case, Repres = Vector must be explicitly presented.

The Min and Max parameters are estimates calculated by the user over the range of values of a numeric grid defined by the New operator. However, at the end of the operations that result this grid, the actual minimum and maximum values found are registered on the correspondent information layer. For numeric and image grids, it is possible define the type of interpolation to be used when there is a difference between the resolution of a new grid or Image and the resoluition of the information layers. Therefore, the word Neighbor corresponds to the Closest Neighbor interpolation and Bilinear to Bilinear Interpolation. The closest neighbor interpolation will be always adopted when thematic information layers are involved.

NOTE: Field Variables instantiated by the Retrieve operator can be used to store the results of assigning operations and in this case, the positions at the information layer are only changed in relation to the data previus state.

Examples:

tema = Retrieve (Name = "hydrographicbasin");
alti = Retrieve (Name = "Altimetricheights");
ima = Retrieve (Name = "TM4");

soil = New (Name = "Soils_A", ResX=50, ResY=50, Scale=100000, Repres = Vetor);
alt1 = New (Name = "Altimetry", ResX=50, ResY=50, Scale = 1000, Min=0, Max=100);
ima = New (Name = "ImageTM_Res", ResX=30, ResY=30);
ima = New (Name = "ImageTM_Res", ResX=30, ResY=30, Nbits = 16);
alt2 = New (Name = "Altimetry", ResX=50, ResY=50, Scale = 1000, Min=0, Max=100, Interpolator= Neighbor);


Instantiation of Table Variables

The reserved words CategoryIn and CategoryOut are used when a Table variable is instantiated to indicate the thematic (s) category (ies) involved in the transformation operator. There are three types of transformation implemented:

Reclassification, Weighting and Slicing.

In the Reclassification transformation, two (initial and final) thematic categories must be provided while in the Weighting transformation, it is only necessary to provide the input thematic category. For the Slicing transformation, the output thematic category must be provided.

Syntax:

Examples:

Reclassification Table:

The Reclassification Table describes a mapping between classes of two thematic categories, associated to CategoryIn and CategoryOut.

grupo = New ( CategoryIn = "Vegetacao", CategoryOut = "Vegetacao",
        "Da" : "FlorestaAluvial",
        "Db", "Ds1", "Ds2", "Ds4", "Dm" : "Florestabrofila",
        "sd", "sp", "sA" : "Savanas",
        "Pfm", "Pa", "Pah" : "FmPioneiras",
        "Ap" : "Floresfila" ) ;

Slicing Table :

The Slicing table shows a mapping between the numeric values intervals and thematic classes of a certain thematic category associated to CategoryOut.

grupo = New ( CategoryOut = "Vegetacao",
        [0.0, 0.2] : "Floresta",
        [0.2, 0.45] , [0.8, 1.0] : "Mata_galeria",
        [0.45, 0.8] : "Cerrado" ) ;

Weighting Table:

The Weighting table describes a mapping between classes of a thematic category associated to CategoryIn, and numeric values that define wights to be associated to this class.

ponde1 = New ( CategoryIn = "Vegetacao",
        "Floresta" : 0.2,
        "Mata_galeria", "Mata" : 0.43,
        "Cerrado" : 0.456 );


Instantiation of Real Variables

As it was mentioned before, the simple assignment of numeric values (integer or real) to a variable Name, that hasn't been used before, defines a Real variable. It can be used in expressions involving integer, real or image data.

Syntax:

Examples:

           pi = 3.1416 ;
           r = pi ;
and = 2.1478 ;

 

Back


Operations

After the variables are created and instantiated, we can define valid operations over them. Operations are sequences of one or more operators over data associated to variables and they are written by algebraic expressions.

A sentence that describes LEGAL operations correspondes to an assigning expression in which the outcome of an algebraic expression is assigned to a previously defined and instantiated variable .

Syntax:

legal-12.gif (2346 bytes)

Depending on the data model obtained, these expressions can be classified in: thematic, numeric, image, real and object.

The zonal_expressions also have their results assigned to variables of Thematic, Numeric, Objects and Real models. However, there are no grammar rules in the language allowing their participation in more complex algebraic expressions, involving other operators. This also happens with the operators: Spatialize and SliceAttribute. These expressions are considered together in the group of zonal expressions.

In the object_expressions, the objects are treated independently from any association with cadastral maps. This allows non-spatial manipulation of attributes of the same object. This class of expressions can use the same functionalities valid for quantitative and qualitative data, as long as the involved types of attributes are consistent with the operators utilized.

The real_expressions involve numbers and real variables, and all functionalities of operators and mathematic functions available for quantitative data. They can be used in non-spatial operations, participating mainly on more complex expressions involving quantitative fields.

The boolean_expressions are maybe the more significant class of operations. Their outcomes are never assigned to any type of variables. They are auxiliary functions that allow the definition of regions from comparing the results of of other types of expressions.

Syntax:

All operators involved in expressions with type associated to fields (Thematic, Image and Numeric), as well as to Boolean expressions belong to the class or Local operators. Check the list below:

  • Arithmetic operators: ‘+’, ‘-’, ‘*’, ‘/’ and ‘^
  • Mathematical functions: sin, cos, asin, acos, atan, log, log10, exp, sqrt etc.
  • Table transformations: Slice, Weight and Reclassify
  • Boolean operators: &&, ||, |, !, >, >=, ==, !=, <=, <
  • Conditional: '?'
  • Conditional assignment: Assign

These operators act over each one of the elements of image raster representation, thematic maps or numeric grids.

A PARTIR DAQUI:

Uma extensa classe de operations de Vizinhança, podem ser implementadas em LEGAL à partir da referência explícita aos elementos vizinhos a cada posição, num percorrimento pontual, como nas operations locais. Tal estratégia de posicionamento relativo consiste de  indicar um valor de deslocamento, em termos do número de linhas and de colunas, relativo a cada posição caracterizada, de modo que elementos vizinhos, em um or mais planos envolvidos em uma expressão algébrica, possam ser considerados na caracterização de cada posição resultante.

Assim, se uma variable aparece em uma expressão algébrica de forma indexada: ( por ex.: variavel [i, j] ), isso indica que o valor a ser considerado em sua avaliação refere-se ao da posição dada pelo deslocamento de ‘i’ linhas and ‘j’colunas relativas a cada posição percorrida para obtenção do resultado ponto a ponto.

The Zonal operations permitem a avaliação de estatísticas simples (maioria, media, maximo, etc) sobre valores definidos por expressões aritméticas or booleanas envolvendo campos(Thematics, Numerics or Imagens) distribuídos sobre zonas definidas explicitamente por feições lineares (polígonos, linhas and pontos)  de cadastral maps, or implicitamente por expressões booleanas envolvendo variables de campos.

Zones devem ser entendidas como regiões disjuntas que recobrem uma área de estudo, for example: os temas de um mapa Thematic, as faixas de altitudes em uma grade altimétrica, os municípios em um mapa cadastral de divisão municipal, as regiões cujo tipo de soil dado por um mapa de soils coincidem com certas faixas de declividade dadas por um mapa de declividades, etc.

 

Back


Real Expressions

The Real expressions are built using constants and real variables (unidimensional), following the usual arithmetic, rules of expressions and priority of operators. Since the objective of this language is to work with spatial data, these expressions can be seen as auxiliaries. The concepts associated to the unidimensional variables and constants will be extensive to spatial variables and constants and consitute the main basis for LEGAL language construction.

Check below the Syntactic Diagram for building real expressions:

Syntax:

The main item here is defined by a real_expression; the symbols +, -, *, /, ^, represent the arithmetic operators; the parentesis ( and ) are used to change the priority between operators in an expression; number and real_variable can assume numbers, variable names and constants that represent numbers; the mathematical_function item corresponds to names of available mathematic functions:

sin, cos, tan

funções trigonométricas em radianos

asin, acos, atan

funções trigonométricas inversas

log, log10

funções logarítmicas na base and e na base 10

exp

exponencial na base e

sqrt

raiz quadrada

int

parte inteira de um número

abs

valor absoluto

rand

valor aleatório

Examples:

  • segundo as regras descritas pelo diagrama, é possível formar sentenças de tamanho ilimitado, bastando para isso seguir as setas indicadoras. Assim, vamos ilustrar a geração de uma operation simples como elevar ao quadrado, a soma de duthe variables_reais:

                (A+B)^2    ...........................................o quadrado da soma de duthe variables:

Sejam A and B, duthe variables reais previamente definidas, observe a sequência de passos para formação da expressão algébrica acima com base nas regras sintáticas:

  • A segunda  regra implica que, isoladamente, A and B são real_expressions;
  • A terceira regra implica que a soma A + B é uma real_expression;
  • A quinta regra, implicaque (A+B) é uma real_expression;
  • A primeira regra implica que o número 2 é uma real_expression;
  • A terceira regra implica que (A+B)^2 é uma real_expression..

Back


Image Expressions

As expressões do tipo Image envolvem valores inteiros, tipicamente entre 0 and 255 (imagens de 8 bits), valores fora dessa faixa serão substituídos pelo extremo mais próximo. O diagrama abaixo mostra as opções para variables que envolvam expressões de imagens.

Syntax:

Expressões dos tipos Real, Numeric and Thematic podem ser entendidas como imagens desde que se use o operator Image, como mostram as regras 5, 6 and 7. Um dado Thematic é normalmente entendido como qualitativo, os valores pontuais representam classes temáticas (geoclasses), identificadas por seus Names de geoclasse. Entretanto, cada geoclasse, como pode-se observar na interface "model de Dados", está associada também a um número inteiro, o seu índice da geoclasse. Esse valor será considerado pelo operator Image, ao trata-lo como uma Image.

O resultado da avaliação de uma expressão_condicional_Image depende da avaliação de uma expressão_booleana que aparece antes do sinal "?". Uma expressão_booleana, como será visto mais adiante, pode resultar em dois possíveis valores: VERDADEIRO or FALSO. Se o resultado for VERDADEIRO, a ação indicada pela expressão_Image1 que antecede do sinal ":" fornecerá o resultado, caso contrário a expressão_Image2 que segue-se ao sinal ":" fornecerá o resultado.

Examples de expressões Image::

ima1 = Image(grade1);
ima3 = ima2 + 20;
res_ima1 = abs(sen(ima1)- 255);

Back


Numeric Expressions

As expressões do tipo Numeric envolvem valores reais dentro de uma faixa de valores definida pelos valores associados às palavras chaves Min and Max; valores fora dessa faixa são associados a valores "nulos", isto é sem informação. O diagrama abaixo mostra as opções para variables que envolvam expressões de imagens.

Syntax:

 

Expressões dos tipos Real and Image podem ser entendidas como grades numéricas desde que se use o operator Numeric, como mostram as regras 7 and 8.

O resultado da avaliação de uma expressão_condicional_numérica depende da avaliação da expressão_booleana que aparece antes do sinal "?", and . que pode resultar em dois possíveis valores: VERDADEIRO or FALSO. Se o resultado da expressão booleana for VERDADEIRO, a ação indicada pela expressão_numerica1 que antecede do sinal ":" fornecerá o resultado final, caso contrário a expressão_numerica2, que segue-se ao sinal ":", fornecerá o resultado.

Examples de expressões Numéricas:

  • ph_fe1 = Numeric(band_spot2);
    soma_grade = (grade_soil + grade_decl)/2;
    grade_seno = sen(grade1);

Back


Thematic Expressions

No caso das expressões de tipo Thematic, os operators aritméticos perdem o sentido, já que os valores encontrados nos elementos de sua representação indicam geoclasses and não valores reais. Assim as expressões possíveis são aquelas que envolvem valores de geoclasses, tais como as  transformações baseadas em Tables and atribuição condicional.

Syntax:

 

Qualquer palavra  pode ser entendida como um Name de geoclasse desde que se use o operator Thematic or Classe, como mostram as regras 3 and 4. Um dado Thematic é normalmente entendido como qualitativo, os valores pontuais representam classes temáticas (geoclasses), identificadas por seus Names de geoclasse, de modo que tais Names são os próprios "valores" representados. Entretanto, é possivel "maquear" os valores inteiros de uma Image, vistos como índices de geo-classes, para geo-classes, como indica a regra 5.

Expressões boleanas, como será visto mais adiante, ao serem avaliadas, podem resultar em dois possíveis valores: VERDADEIRO or FALSO.

O resultado da avaliação do operator Assign depende da avaliação pontual de expressões_booleanas associadas à classes temáticas. A primeira delas que resultar em um valor VERDADEIRO irá determinar a classe a ser tomada como resultado final.

O resultado da avaliação de uma expressão_condicional_temática depende da avaliação da expressão_booleana que aparece antes do sinal "?".   Se o resultado da expressão_booleana for VERDADEIRO, a ação indicada pela expressão_tematica1 que antecede do sinal ":" fornecerá o resultado final, caso contrário a expressão_temática2, que segue-se ao sinal ":", fornecerá o resultado.

Example de expressões temáticas:

  • cl_declividade = Slice ( decliv , tab_decliv ) ;
    desmat= Reclassify ( cobertura ,   tab_recl ) ;
    aptidao= Assign ( CategoryOut = "Aptidao" )
                 { "Boa" :    (soil == "LatosoilRoxo" && decliv == "O-3" ) ,
                   "Inapto" : (soil == "AreiaQuat" && decliv == ">8" ) };

Back


Boolean Expressions

Uma expressão booleana descreve o conjunto de posições que satisfazem um mesmo critério de pertinência, dado pela combinação de expressões dos tipos anteriores através dos operators de comparação:

< 

less than

<=

less than or equal to

> 

greater than

>=

greater than or equal to

==

equal to

!=

not equal

and logical operators:

&&

logic AND

||

logic OR (união)

|

OU-exclusivo (união disjunta)

! or ~

NAO-lógico (complemento)

Syntax:

 

As expressões de comparação and as booleanas são auxiliares, não sendo possível atribuir seus resultados a variables. Entretanto, elas oferecem um modo eficiente de descrever condições envolvendo atributos espaciais (or não, no caso das expressões_Object) resultantes da avaliação de expressões sobre campos, Objects and reais, sem a necessidade de gerar resultados binários intermediários.O resultado da avaliação de uma expressão booleana pode assumir um entre os valores: VERDADEIRO or FALSO.

No caso de expressões_comparação envolvendo expressões_temáticas or expressões_Object envolvendo atributos de tipo texto, apenas os operators locais de igualdade (==) and desigualdade (!=) fazem sentido, para todas as outras, todos os operators de comparação ( > , >= , <= , < ) podem ser utilizados.

Back


Zonal Expressions

Nesse grupo de operations destacam-se as estatísticas simples como: maioria, variedade, máximo, soma, media etc. Tais operators consistem-se de sumarizações sobre conjuntos de valores oriundos de um certo plano, que estejam contidos em zonas definidas por outros planos or cadastral maps.

   

 

 

 

  

 

 

 

 



 

Quando o resultado de  uma expressão_zonal é atribuído à uma variable_temática, sempre que as zonas envolvidas forem definidas por uma expressão_cadastral, o resultado deverá ser um plano Thematic de representação vetorial. Assim, na Instantiation dessa variable, o parâmetro Repres = Vetor deve ser indicado.

Examples:

  • Determinação de um mapa Thematic de "atividade econômica" à partir do atributo "ATIVIDADE" do Object Municípios.

Cadastral cad ("Divisao Municipios") ;
Thematic tem ("Temas Municipais") ;
Object obj ("Municipios") ;
tem = New (Name = "Municipais", ResX = 100, ResY =100, Scale = 100000, Repres = Vetor) ;
tem = Espacialize (obj ."ATIVIDADE" NoMapa cad) ;

Em um caso como este, é necessário que existam pré-definidas, no data model, a category temática "Temas Municipais" and as associadas a ela  and as   geo-classes de Names idênticos aos dos valores textuais do atributo "ATIVIDADE".

  • Determinação do tipo de vegetação predominante por município. O plano "Mapa de Vegetacao" deve ter  representação matricial.

Cadastral cad ("Divisao Municipios") ;
Thematic tem ("Temas Municipais") ;
Thematic veg ("Vegetacao") ;
Object obj ("Municipios") ;
veg = Retrieve (Name = "Mapa de Vegetacaoo") ;
tem = New (Name = "ClassesMunicipais", ResX = 100, ResY =100, Scale = 100000, Repres = Vetor);
tem = MaioriaZonal (veg , obj  NoMapa cad) ;

  • Atualização do atributo "DECLIVE" de Objects da category "Quadras" com valores médios de declividade avaliados a partir da grade numérica "Declividade", sobre as zonas definidas pelos polígonos de um mapa cadastral, usando o operator MediaZonal.

    Object zonas ("Quadras");
    Cadastral cad ("Cad_Urbano");
    Numeric decliv ("Altimetry");
    cad = Retrieve (Name = "Mapa_quadras");
    decliv = Retrieve (Name = "Declividade");
    zonas . "DECLIVE" = MediaZonal ( decliv, zonas OnMap cad );

Back


Object Expressions

As expressões do tipo Object envolvem valores oriundos de atributos de um mesmo Object, os resultados das operations assim definidas devem ser armazenados sob a forma de atributos, prèviamente definidos, do mesmo Object. Aqui as possiveis associações de Objects a cadastral maps não são levadas em conta; como em uma planilha, as colunas são envolvidas em operations afim de gerar valores para outras colunas . Dito de outra forma, são operations entre colunas de uma mesma Table que representa o Object.

Assim como as real_expressions, as expressões_Object, por envolverem apenas valores Scaleres que caracterizam atributos em Tables de bancos de dados convencionais, também são não-espaciais, isto and ' não envolvem information layers or cadastral maps. Além disso, diferentemente daquelas, tais valores não podem ser "maqueados" para representar implìcitamente dasos de outros models no Spring.

Syntax:

legal-18.gif (4094 bytes)

O resultado da avaliação de uma expressão_condicional_Object depende da avaliação da expressão_booleana que aparece antes do sinal "?". A expressão_booleana, neste caso poderá envolver apenas expressões-Object and /or real_expressions, podendo resultar em dois possíveis valores: VERDADEIRO or FALSO. Se o resultado for VERDADEIRO, a ação indicada pela expressão_Object que antecede do sinal ":" fornecerá o resultado, caso contrário a expressão_Object que segue-se ao sinal ":" fornecerá o resultado.

Examples de expressões Object::

estado."Previsão" = estado."Atual" * estado."Taxa_anual" ;
estado ."Previsão" = estado."Desempenho" > 50 ? estado."Atual" * estado."Taxa_anual" : estado."Atual" ;

Back


Control Commands

Constituem uma classe de operators que pemitem o controle do fluxo de execução de um programa em LEGAL, o que pode ser feito com base em alguma condição dada por uma expressão booleana, or à partir do controle do número de iterações a que deve ser submetido um certo grupo de operations algébricas em um programa qualquer, de maneira explícita or tambem de  por alguma condição booleana. Eses comandos são baseados em constructos da linguagem tais como:

  • Se ( condição ) { operations } Senao { operations }..................>>>NAO IMPLEMENTADO<<<
  • Enquanto ( condição ) { operations }

As condições referidas acima são dadas por uma expressão_booleana envolvendo apenas  expressões_ reais, isto significa que são condições baseadas em valores Scaleres, tipicamente por nariáveis_reais que devem funcionar como contadores de passos and que são alteradas explicitamente a cada passo  Por Example:

{
...
n = 0 ;
Enquanto (n < 10)
{
   operation_1 ;
    operation_2 ;
    ...
    n = n + 1 ;
} ;
...
}

Apenas o operator Enquanto está disponível  na versão atual do Spring/LEGAL.

No comando Se...Senão... o resultado da avaliação de uma expressão_booleana (VERDADEIRO or FALSO) irá determinar qual entre duas sequencias de operations deve ser processada.

No comando Enquanto... uma sequencia de operations deve ser executada repetidas vezes até que a avaliação da condição dada por uma  expressão_booleana resulte VERDADEIRO.

Syntax:

legal-10.gif (2226 bytes)

 

Examples:

  • Determinação de um mapa Thematic de "densidade populacional" a partir de um dado Thematic inicial, representado no plano de imformação "DensPop", já existente, que é modificado à partir de iterações controladas pela variable_real "n". A cada iteração um conjunto de regras definidas por expressões_booleanas envolvendo as vizinhanças de cada posição são avaliadas, afim de determinar a evolução das diversas classes de densidade populacional ao longo de um certo número de iterações.

{
    Thematic densidade, dens, den ("Densidade_Populacional");
    densidade = Retrieve (Name="DensPop");
    dens = New (Name = "EvolucaoDensPop", ResX=30, ResY=30, Scale = 100000 ) ;
    den = New (Name = "Den2", ResX=30, ResY=30, Scale = 100000 ) ;
    den = densidade ;
    n=0;
    While n < 10
   {
        dens = den ;
        //Primeira regra:
        //Posições de densidade média, com dois  vizinhos de densidade média and um de alta tendem a
        //tornar-se de alta densidade.
        dens  ==  Classe ("Media") &&
        ( (den[-1,-1] == Classe("Media") && den[1,0] == Classe("Alta") && den[-1,1] == Classe("Media")) ||
          (den[-1,1] == Classe( "Media") && den[0,-1] == Classe("Alta") && den[1,1] == Classe("Media")) ||
          (den[1,1] == Classe("Media") && den[-1,0] == Classe("Alta") && den[1,-1] == Classe("Media")) ||
          (den[1,-1] == Classe("Media") && den[0,1] == Classe("Alta") && den[-1,-1] == Classe("Media"))   ) ?
        Classe("Alta") :
        //Segunda regra:
        //Posições de densidade média, com dois vizinhos de densidade média te um de baixa endem a
        //manter a densidade.
        dens  ==  Classe ("Media") &&
        ( (den[-1,-1] == Classe("Media") && den[1,0] == Classe("Baixa") && den[-1,1] == Classe("Media")) ||
          (den[-1,1] == Classe( "Media") && den[0,-1] == Classe("Baixa") && den[1,1] == Classe("Media")) ||
          (den[1,1] == Classe("Media") && den[-1,0] == Classe("Baixa") && den[1,-1] == Classe("Media")) ||
          (den[1,-1] == Classe("Media") && den[0,1] == Classe("Alta") && den[-1,-1] == Classe("Media")) ) ?
        Classe("Baixa") :
        //Terceira regra:
        //Posições de densidade média, com um vizinhos de densidade média, um de densidade alta and um de
        //densidade baixa tendem a manter a densidade.
        dens  ==  Classe ("Media") &&
        ( (den[-1,-1] == Classe("Alta") && den[1,0] == Classe("Media") && den[-1,1] == Classe("Baixa")) ||
          (den[-1,1] == Classe( "Alta") && den[0,-1] == Classe("Media") && den[1,1] == Classe("Baixa")) ||
          (den[1,1] == Classe("Alta") && den[-1,0] == Classe("Media") && den[1,-1] == Classe("Baixa")) ||
          (den[1,-1] == Classe("Alta") && den[0,1] == Classe("Media") && den[-1,-1] == Classe("Baixa"))   ) ?
        Classe("Media") : den ;        //Fim da operation condicional
        n = n+1;
    };
}

O Example acima é fictício, muitas diferentes regras poderiam ser definidas afim de determinar o comportamento dinâmico da evolução do crescimento (or decrescimento) da concentração populacional, com base nas vizinhanças imediatas de cada posição de um information layer. Ao final de cada iteração (or passo) a variable_real "n" é incrementada and ao início do passo seguinte, o valor de "n" é comparado afim de determinar a continuidade or não da sequencia de operations definidas no ambito do comando While.

Observe que afim de preservar a informação original contida no information layer "DensPop", foram criadas duas cópias dele. Uma delas é atualizada apos cada iteração, servindo de base para a iteração seguinte.

Esse Example ilustra também o uso de indexação relativa na definição de operations de vizinhança.

Back