LEGAL Operations:

How to Execute Map Algebra

LEGAL


Local Operations

Local Operations involve equivalent positions located in diferent information layers. Next, we will describe most of the local operators involved with Image, Numeric and Thematic expressions:

    Mathematical Operators are the arithmetic operators and mathematical functions applied point to point to quantitative data, suh as numeric grids and images.

    Transformation Operators are the transformation operators (Reclassify, Slice and Weight) that implement mapping between an input Thematic, Image or Numeric information layer and an output Thematic or Numeric layer. The value of each input position is defined by a previously defined table (Reclassifying, Slicing or Weighting).

    Boolean Operators are defined from comparison operators (<, <=, ==, !=, >=, >) and logical operators (&&, ||, !). The comparisom operators are based on order relationships, applied to quantitative data (images, numeric grids and objects numeric attributes). The compared elements are the results of the evaluation of point operations described by algebraic operations. The outcomes assume the values TRUE or FALSE.

    Conditional Operators:  a boolean expression is evaulated over each point position to decide which on of the two operatios, described by expressions of same type, should be evaluated to get the final result that must be of the same type of the expressions.

Back to top


Mathematical Operators

The mathematicalal operations are only applied to NUMERIC and IMAGE information layers:

  • arithmetic operators: addition (+), subtraction (-), multiplication (*) and divisão (/);
  • mathematical functions: sine (sin), cosine (cos), tangent (tan), arcsine (asin), arccosine (acos), arctangent (atan), logarithim (log), Log to the base 10 (log10), exponential (exp), square root(sqrt), integer (int), absolute value (abs); random value (rand)

Check the example below on mathematical operations. The figure shows on the left a weighted soils map and on the right a slope map. Consider we want to calculate a fitness indicator as the addition between the value assigned to th soil and the inverse of slope. The operation described below could be used as an intermediary step when calculating a map of soil fitness (the greater the value, the greater the fitness).

    aptness = soils_weight + 1/decliv


Check now the LEGAL program to do this operation:

    {
    // Part 1 - Declaration
    Numeric soil_weight ("Weighted_soil"),
             decliv ("Slope"),
             aptness ("NumericFitness");
    // Part 2 - Instantiation
    decliv = Retrieve(Name  = "Decliv94");
    soil_weight = Retrieve (Name = "Soils94");
    aptness = New (Name = "fit94", ResX=50, ResY=50,
              Min=0, Max=2, Scale = 50000);
    // Part 3 - Operation
    aptness = soil_weight + 1/decliv;
    }

Check other examples of mathematical operations:

    LS = (0.00984*(decliv ^ 1.18)*(rampa ^ 0.63));
    IV = (red / infrared) * 128;
    radAVHRR4 = 0.155 * ima + 150;
    tempAVHRR4 = 1.435*845.19/log(1+1.191 *10-5/radiance);

Back to top


Transformation Operators

The transformation operators perform a mapping of values defined by thematic and numeric variables to values that can be associated to othter numeric or thematic variables, acording to a mapping defined by transformation tables of specific type such as Reclassifying, Slicing and Weighting. These tables, previously declared and instatiated, are used as arguments to the operators. There are three types of transofrmation operators in LEGAL:

  • Weight: maps THEMATIC data into NUMERIC;
  • Slice: maps NUMERIC data into THEMATIC;
  • Reclassify: maps THEMATIC data into another THEMATIC.

Check below some examples of transformation operators:

    * "Reclassify a vegetation map with the following classes {Dense Ombrophilous Forest, Open Ombrophilous Forest, White-sand woodland, Seasonally deciduous tropical forest} into a map with the classes {Dense Forest, Open Forest}."
    * "Obtain an hypsometric map from an altimetric map with the mapping { (0-300m) - Plain, (300-500m) - Plateau, (>500m) - Mountain}".
    * "Quantify a themral infrared satellite image into a map of temperatures from the equation Temp = 27*Image/100."

Back to top


Weighting

    A weighting operator transforms thematic data into numeric:

    Weight (thematic_variable, weighting_table)

    The Figure below shows an example of weighting operator (converting a soils map into a weighting map)> The input information layer is a soils map with the classes { Le, Li, Ls, Aq } and the output is a DTM with values between 0.0 and 1.0, and the weighting operation consists in the association {(Le-0.60), (Li-0.20), (Ls-0.35), (Aq-0.10)}.



    Weighting operator example: if "SOILweight" is a numeric variable, "SOILS" a thematic variable and "weightSOIL" a weighting table, the sentence below shows the syntax of this operator:

      SOILweight = Weight (SOILS, weightSOIL);

Check now, the program in LEGAL to perform such operation:


    {
    // Part  1- Declaration
    Thematic SOILS ("Soils");
    Table weightSOIL (Weighting);
    Numeric SOILweight ("SoilWeightdo");
    // Defining the tables of weights
    weightSOIL = New (CategoryIn = "Soils",
             Le : 0.60, Li : 0.2, Ls : 0.35, Aq : 0.1);
    // Part 2 - Soils map Instantiation
    SOILS = Retrieve (Name = "SoilCE");
    // CReating a new weighted soils map
    SOILweight = New (Name = "soilp", ResX = 30, ResY = 30,
           Scale = 100000, Min = 0, Max = 1);
    // Part 3 - Weighting Operation
    SOILweight = Weight (SOILS, weightSOIL);
    }

The program above performs the following steps:

  1. Initially the information layers and weighting tables are defined (three first lines of the program, not considering the comment lines) The weighting table is created and the weights are assigned to each class;
  2. Next, the soils map to be weighted is retrieved (Retrieve function). The output information layer is created (New operator). The new plan is created as a regular grid of 30 x 30 meters resolution, scale 1:100.000 and maximum and minimum values;
  3. The wieghting operation is performed through the Weight function.

Back to top


Slicing

    The slicing operation transforms a numeric information layer in a thematic one, acording to the syntax:

    Slice (numeric_variable, slicing_table)

    The figure below shows an example of the slicing operator where the slope map in degrees is transofrmed to a slope classes map:

    0 to 5% "low"
    5 to 15% "medium"
    greater than 15% "high"

     

     

      Example of program in LEGAL:

        {
        // Part 1 - Declaration
        // Variables Declaration
        Thematic classes_decl ("Slope");
        Numeric decliv_num ("Slope_Numeric");
        Table tab_fatia (Slicing);
        // Slicing table definition
        tab_fatia:= New ( CategoryOut = "Slope",
                     [0.0, 5.0] : "Low",
                     [5.0, 15.0]: "Average",
                     [15.0, 45.0]: "High");
        // Part 2 - Instantiation
        // Numeric Slope IL Retrieving
        decliv_num = Retrieve (Name = "Declivity_SJC");
        // Output IL generation
        classes_decl = New (Name = "Classes_Decl",
                       ResX = 50, ResY = 50, Scale = 100000);
        // Part 3 - Operation
        // Slicing Operation
        classes_decl = Slice (decliv_num, tab_fatia);
        }


      The programa above performs the following steps:

      1. Initially the information layers and slicing tables are defined (three first lines of the program, not considering the comment lines) The slicing table is created to define the mapping between thematic classes and numeric ranges.
      2. Next, the slope map to be sliced is retrieved (Retrieve operator).
      3. The output IL is created (New operator). This IL will be created as a thematic image, 50 x 50 meters resolution, scale 1:100.000.
      4. The slicing operation is finally performed (Slice function) to assign values to the position of the new plan created above.

Back to top

A PARTIR DAQUI


Reclassifying

    A operação de reclassificação transforma um information layer thematic em outro thematic segundo a syntax:

    Reclassify (thematic_variable, reclassification_table)

    Como exemplo, temos um mapa de cobertura do soil na Amazônia com diferentes classes {"Floresta Densa", "Floresta Várzea", "Rebrota", "Área Desmatada", "Cerrado"}. Este mapa thematic será reclassificado para um novo mapa, apenas com as classes {"Floresta", "Desmatamento", "Cerrado"}.

Example de programa em LEGAL que executaria esta operação:

    {
    // Part 1 - Declaration
    Thematic cobertura ("Floresta");
    Thematic desmat ("Desmatamento");
    Table tab_recl (Reclassifying);
    tab_recl= New(CategoryIn = "Floresta",
            CategoryOut = "Desmatamento",
         "FlorestaDensa" : "Floresta",
         "FlorestaVarzea" : "Floresta",
        "Rebrota"  : "Desmatamento",
        "AreaDesmatada" : "Desmatamento",
        "Cerrado"  : "Cerrado");
    // Part 2 - Instantiation
    // Recuperação da variável
    cobertura = Retrieve (Name = "Uso_JiParana");
    // Criação do novo PI
    desmat = New (Name = "Desmat_JiParana", ResX= 30,
                   ResY = 30, Scale = 100000);
    // Part 3 - Operation
    // Reclassifying
    desmat= Reclassify (cobertura, tab_recl);
    }

Back to top


Boolean Operators

Operations booleanas são de grande utilidade em análise espacial qualitativa na geração de dados thematics, a partir de regras aplicadas a dados de entrada de qualquer outro modelo (Temático, Numérico and Image). Entretanto, qualquer tipo de dado pode ser definido por expressões booleanas.

Não existe um tipo de dados previsto no modelo de dados Spring para representar explicitamente os resultados de boolean operations, estas são tomadas como auxiliares na determinação de campos dos diversos modelos.

No exemplo abaixo, o operador "Assign" é usado para determinar o plano "adequação", no qual as classes "inadequado" and "adequado", em função de expressões booleanas. Cada expressão booleana compõem-se de expressões de classe que envolvem a grade numérica de "Slope" and o mapa thematic "Soils".

Example:

Como exemplo de uso de boolean operations, considere a determinação de um mapa de aptidão agrícola, a partir dos mapas de soil, declividade, precipitação and do conjunto hipotético de regras expresso na tabela abaixo.

RULES FOR AGRICULTURAL APTNESS

Agricultural Aptness Soils Slope
Good Purple Latosoil 0-3%
Medium Red-Yellow Latosoil 3-8%
Inapt Quartz Sand >8%


Em LEGAL, é necessário especificar um conjunto de condições a serem satisfeitas para cada classe de saída, através do Assign operador. No programa descrito a seguir, um mapa de Aptidão Agrícola é determinado, com base na topografia and tipo de soil.

    {
        Thematic soils ("Soils"), aptness ("Aptness");
        Numeric decliv ("Altimetry");
        decliv = Retrieve(Name  = "Slope");
        soils = Retrieve (Name = "Mapa de Soils");
        aptness = New (Name = "AptnessAgricola", ResX=50, ResY=50, Scale = 50000);
        aptness=  Assign
             {
               "Boa" : soil == "LatosoilRoxo" && decliv.>= O && decliv < 3" ),
               "Average" : soil == "LatosolVeAm" && decliv.>= 3 && decliv < 8" ),
               "Inapto" : Outros) };
    }

Back to top


Conditional Operator

Uma expressão condicional  baseia-se na avaliação de uma expressão booleana para decidir entre duas expressões alternativas de um mesmo tipo, que deve ser avaliada para obtenção do resultado final, segundo a syntax

expressao_booleana ? expressao1 : expressão2

Example:

Restrição de uma imagem TM a uma região descrita por expressão booleana:

    {
    // Example de como Mascarar uma Image
    Image tm5, tm5M ("Imagens-TM");
    Thematic masc ("Fazendas");
    tm5 = Retrieve(Name = "Banda-5");
    masc = Retrieve (Name = "Mapa_Fazendas");
    tm5M = New(Name="Image_Fazendas", ResX=100, ResY=100);
    // Operation
    tm5M =  masc  == "Fazendas-Gado" ? tm5 : Image(255) ;
    }

O programa acima recorta (mascara) a imagem de satélite "tm5, apenas nas regiões onde existe a classe "Fazenda-Gado" do information layer "Fazendas".

Como as expressões alternativas devem ser de tipo Image neste caso, o valor 255 deve ser "maqueado" como uma imagem. Ao ser instanciada a variável tm5M pelo operador New, um novo information layer foi efetivamente criado, contendo uma imagem "em branco", isto é, com valor 255 associado a cada um de seus pixels, isso nos oferece uma alternativa para a operação do programa acima dada pela expressão:

tm5M = ( masc  == "Fazendas-Gado" ) ? tm5 : tm5M  ;

Na verdade as expressões do tipo Image usadas como alternativas do exemplo acima são as mais simples possíveis, consistindo de apenas nomes de variáveis or números. Expressões mais complexas poderiam ser usadas, considere, por exemplo a obtencao não apenas de um simples recorte das regiões de fazendas de gado, mas sim de uma imagem contendo os índices de vegetação em tais imagens. A operação seria similar a:

ivdn = ( masc  == "Fazendas-Gado" ) ? ( tm3 - tm4 ) / ( tm3 + tm4 ) : ivdn ;

Novas expressões condicionais podem ser usadas também como expressões alternativas, permitindo a definição de uma vasta classe de operações, no exemplo acima poderíamos estar interessados em Fazendas-Gado de todos os estados da região sul and Fazendas-Agricolas da região norte do pais, representados em um mapa thematic de regiões do Brasill. A operação poderia ser descrita de uma maneira similar a:

ivdn = ( masc  == "Fazendas-Gado" ) ? ( tm3 - tm4 ) / ( tm3 + tm4 ) :
  
                     ( regiao == "Sul" ) ? Image ( 128 ) :  Image ( 255 ) ;

 

 

Back to top


Focal Operations

Em Legal é possível realizar muitas operações com base no acesso, and envolvimento em operações, das posições vizinhas à cada posição de uma representação matricial que se deseja caracterizar. São referenciadas por um par de coordenadas relativas, que indica valores de deslocamento em termos de número de linhas and colunas. Por exemplo:

variable  [i, j]

Os índices i and j referem-se ao deslocamento relativo à cada posição numa representação matricial, em termos do numero de linhas and colunas. Podem ser   aplicados a qualquer variável associada a planos matriciais envolvidos em uma expressão pontual genérica.

No exemplo abaixo uma grade numérica é gerada, and a cada posição é atribuído o valor 1, sempre que alguma, entre as posições vizinhas (acima, abaixo, à esquerda or à direita),  numa grade numérica de Altitudes, for de maior valor.

Example:

{
     Numeric descen, altitude ("Altimetry");
    altitude = Retrieve (Name = "Altitudes");
    descen = New (Name="Descendentes", ResX=25, ResY=25, Scale=100000, Min=0, Max=255) ;
    descen = altitude < altitude[1,1] || altitude < altitude[1,0] || altitude < altitude[1,-1] || altitude < altitude[0,1] ? 1 : 0 ;
}

A posição de referência a cada passo da geração do resultado, corresponde à posição de índices "[0,0]", que é normalmente expressa sem índices, como pode ser observado no exemplo acima (ondel a variável "altitude"  aparece sem índices).

Back to top


Zonal Operations

Data Attributes do modelo Object podem ser envolvidos em expressões da linguagem, graças ao mecanismo adotado para representar sua distribuição, baseado no conceito de mapa cadastral. Mapas cadastrais oferecem suporte à representação de objetos em diferentes escalas, and são categorizados no ambiente Spring através do modelo Cadastral. Os elementos de um tal mapa são dados sob a forma de polígonos, linhas and pontos que podem estar associados a objetos de interesse, de uma maneira semelhante à que define um information layer qualquer.

A principal finalidade associada às expressões envolvendo objetos cadastrais, está relacionada a seu uso junto à classe de operadores Zonal, o operador Spatialize, o operador Update and o SliceAttribute, que atuam sobre atributos de Objects.

O operador SliceAttribute maps, através de uma tabela de Slicing, os valores associados a algum atributo numérico de  Objects associados à um mapa de categoria Cadastral and cuja  representação no Spring é sempre vetorial. O operador Spatialize permite a geração de mapas thematics or de grades numéricas a partir de atributos numéricos or textuais de objetos cadastrais.

Os operadores Zonal efetuam sumarizações de valores   resultantes da avaliação de expressões temáticas, numéricas, imagens and booleanas.envolvendo um or mais information layer, sobre regiões delimitadas por zonas dadas por expressões booleanas or por mapas cadastrais. Tais sumarizações correspondem a estatísticas simples, tais como: Majority, Maximum, Average, Variety etc. O operador Update maps valores resultantes de operadores zonais, em atributos de objetos cadastrais, permitindo a extração de resultados sob a forma de atributos em tabelas de bancos de dados.

No exemplo abaixo, o atributo "DECLIVE" do objeto "Blocks" é atualizado à partir de valores médios obtidos através de valores de declividade fornecidos pela grade numérica "Slope", sobre as zonas definidas pelos polígonos de um mapa cadastral, associadas às instâncias do objeto.

Examples:

{
    Object zonas ("Blocks");
    Cadastral cad ("Cad_Urbano");
    Numeric decliv ("Altimetry");
    cad = Retrieve (Name = "Blocks_map");
    decliv = Retrieve (Name = "Slope");
    zonas. "DECLIVE" = ZonalAverage (decliv, zonas OnMap cad );
}

O mesmo efeito do programa acima pode ser obtido através do operador Update combinado com o de ZonalAverage

{
...
    zonas. "DECLIVE" = Update (decliv, zonas OnMap cad, ZonalAverage);
}

Back to top