MODEL

Image modeling


EnvironmentsPYTHON :: EASI :: MODELER
Quick linksDescription :: Parameters :: Parameter descriptions :: Details :: Example

Back to top

Description


Implements a high-level modeling language which can be used for GIS and imagery applications.
Back to top

Parameters


model(file, source, undefval)

Name Type Caption Length Value range
FILE * str Input file name 1 -    
SOURCE * str Source of Model 1 -   n, filespec, text
UNDEFVAL List[float] Value for undefined operations 0 - 1  

* Required parameter
Back to top

Parameter descriptions

FILE

Specifies the name of the PCIDSK file to be modeled.

SOURCE

Specifies one of three sources for the text that contains the model equations to run using this function.

Acceptable values include:

UNDEFVAL

Optionally specifies the value that should be used for the result of numeric expressions that contain an undefined operation, such as division by zero or the logarithm of a negative value.

Back to top

Details

MODEL is a generalized image processing and raster GIS tool. Using a special programming language, the user enters a set of equations (model) describing how channels of imagery data and attribute data should be combined. The results appear in new data channels.

In imaging applications, input typically consists of image channels that contain raw imagery. In GIS applications, input usually consists of attribute data and image channels containing data 'layers'. Layers may include raw imagery, elevation, classification themes, digitized maps, and proximity maps.

All raster channels/layers are assumed to be contained in a single PCIDSK file. Attribute data may be held in text files or as segments in the PCIDSK file.

The text describing the model is read in and the equations are applied to each pixel in the raster data. Because imagery is often of unpredictable quality, it is possible to specify the results of undefined operations rather than have MODEL terminate immediately upon the detection of such an operation.

Image/Layer Data

MODEL works with the pixels in image channels on the PCIDSK database. This data can be 8-bit integer, 16-bit signed or unsigned integer, or 32-bit real. Although channels on the database are called 'image channels', this is only a convention. In fact, it is often more useful to think of a database as a series of registered data layers. The following chart lists some of the types of possible data layers that can be held in an image channel.

 Layer Type             Common Sources

 Raw Imagery          Satellite/Aircraft distributed on magnetic tape
 Elevation                  USGS DEM from tape, gridded from contours
 Theme/Overlays      USGS LULC from tape, digitized from maps
 Processed Imagery  Classified images, slopes calculated from elevation, etc.

Attribute Data

Attribute data is a set of numeric and/or character values which are associated with a range of values.

For example:

        23 : 27   ;  1.3  19  river  Mississippi

means that values on the range 23 to 27 are associated with the two numeric attributes 1.3 and 19 and the two character attributes 'river' and 'Mississippi'.

MODEL can access attribute data held in a text segment on PCIDSK files or in text files on disk. This is accomplished by tying the attribute data to a specific image channel (layer) and then using the gray level values for individual pixels to match against the ranges in the attribute data.

A special feature of MODEL is the ability to use lookup table (LUT) and pseudocolor table (PCT) segments held on a PCIDSK file as attribute data. LUT data is equivalent to attribute data having 256 entries, each entry having one numeric attribute. PCT data is equivalent to attribute data having 256 entries, each entry having three numeric attributes (red, green, blue).

Vector Data

Vector data cannot be directly handled. The GRDVEC function can be used to embed vector data into an image channel (layer) after which it can be used by model.

Errors

There are two general types of errors:

Complex models may require debugging. The following hints may help in this process:

Note: One of the most common debugging methods is to use strategically placed print statements. Due to the structure of MODEL, the use of parallelism (where available) cannot perform I/O while processing a pixel. This means that the print statement cannot be used within the processing section of the model, because parallelism is not used. The print statement can, however, be used in the INPUT/SET section.

Accuracy

All computations are made in double precision. On most systems, this will be 64-bit floating point. The results are truncated to the data type of the output image channel (8-bit integer, 16-bit signed/unsigned integer or 32-bit real). The user should take care that results generated by the model are appropriate for the channels selected for output.

Speed Hints

Modeling is a computationally intensive process. The modeling equations are re-executed for each pixel in the database. For example, a database file with 1000 by 1000 resolution would require that the modeling equations be evaluated 1,000,000 times.

To improve execution speed, MODEL "half compiles" the modeling equations; MODEL basically works as an interpreter. The following hints can help improve speed even further.

Note that comments, blank lines, and white space do not affect execution speed; these may be used liberally.

Limitations

Modeling is not only CPU-intensive, it is also memory-intensive. The following table lists approximate limitations for various computer systems. If these limits are exceeded, the MODEL program will terminate with an error message.

Feature      

Model Size (char)               32768            
Layers/Variables                128           
Attribute Data (Kbytes)       1000          
Array Data (Kbytes)            32

Language

The modeling language is similar to other procedural languages such as BASIC, FORTRAN, or C, but is specifically designed for raster imaging and GIS applications.

The modeling language is not case-sensitive, although character data is.

Constants

The following types of constants are available:

n           123.4                numerical constant
"text"     "abc"                string constant
'text'      'B12'                 string constant

Variables

Variables give access to image (layer) pixel values, attribute data, and other values. Variables are identified by a special leading character (#,%,@,$), followed by 1 to 7 characters.

Layer Variables

Layer variables are identified by the leading character '%'. Layer variables take on the gray level value of the pixel being processed for a particular layer (image channel); for example, %3 would take on the gray level value of the third image channel at the current pixel position. If a name is used (for example, %tree), the association between the name and an explicit layer is made when the model is first run using a SET or INPUT statement.

Syntax:    %x, %n

Examples:  %soil,%z,%1,%23

Attribute Variables

Attribute variables are identified by the leading character '%' and a '.'. Attribute variables take on the value of an attribute associated with the layer through the gray level value. For example, %2.3 would be evaluated as follows: at the current pixel location, the gray level value for the second image channel would be used as a key to a single line of attribute data associated with the layer; within this line, the list of attributes would be scanned and the third attribute value extracted; %2.3 would take on this value. Note that this value could be numeric or character, depending on the actual nature of the attribute.

Syntax:    %x.i, %n.i

Examples:  %slope.2, %5.3

Subscripts

It is possible to access the gray-level values and attribute data for adjacent pixels by subscripting layer or attribute variables. The following diagram shows the subscript syntax and relationship to the pixel being currently processed (which is [ 0, 0]).

                [-1,-1]  [ 0,-1]  [ 1,-1]
                [-1, 0]  [ 0, 0]  [ 1, 0]
                [-1, 1]  [ 0, 1]  [ 1, 1]

%x is equivalent to %x[0,0]. Subscripted pixels which are outside the bounds of the image are automatically assigned the value of the nearest pixel which is inside the image.

Note: It is NOT possible to assign a value to a subscripted pixel.

Numeric Variables

Numeric variables are identified by the leading character '#'. Numeric variables are used for temporary storage of numeric values. They have no relation to any layers or attributes and provide a convenient way of holding results of calculations or user-entered constants.

Syntax:    #x

Examples:  #tree, #t37

Character Variables

Character variables are identified by the leading character '$'. Character variables are used for temporary storage of character data. They have no relation to any layers or attributes and provide a convenient way of holding user-entered character data.

Syntax:    $x

Examples:  $name,$a

Numeric Array Variables

Numeric array variables are identified by the leading character '#' followed by 1 to 7 characters and an array subscript. Subscripts can range from 1 to the number of elements in the numeric array.

Syntax:  #x[n]

Examples: #array[7], #colval[127]

Numeric array variables allow access to one-dimensional array information held in PCIDSK array segments [type ARR:181].

Special

Special variables allow access to information about the file and location information about the pixel being processed. They can be used within numerical expressions like constants.

Variable Description

@x             current x (pixel) processing location
@y             current y (line ) processing location
@dbx           size of database in x (pixel) direction
@dby           size of database in y (line ) direction
@metrex        size of a pixel in x direction in metres
@metrey        size of a pixel in y direction in metres
@geox          x georeferenced center of current pixel
@geoy          y georeferenced center of current pixel
@sizex         x size of a pixel in georeferenced units
@sizey         y size of a pixel in georeferenced units

Character Expressions

Character expressions are limited to a single character constant character variable, or character attribute variable.

Examples of these are:

'abcdef'
"ab   123"
$answer
%3.2   (if the attribute is character)

It is not possible to access part of a character string, concatenate two strings, or process a string.

Character strings are case-sensitive. For example, 'abc' is not the same as 'ABC'.

Arithmetic Expressions

Arithmetic expressions are made up of arithmetic elements and arithmetic operators. The evaluation of an arithmetic expression yields a single numeric value. Arithmetic elements consist of: numeric constants, numeric variables, layer variables, numeric attribute variables, numeric array variables and special variables. Available operators are listed in the following sections.

Examples of arithmetic expressions are:

10.3
sin(%3) * 27.05 - (2+ln(#temp))
min(%1,%2,%3) * and(%6,15)

Operators

The following arithmetic operators are available, with standard algebraic precedence being observed:

'-x'            negation
'^'             exponentiation
'/'             division
'*'             multiplication
'+'             addition
'-'             subtraction
'()'            parenthesis

Single-value functions

The following single-value arithmetic functions are available:

sin   (e)               sine
cos   (e)               cosine
tan   (e)               tangent
asin  (e)               arc sine
acos  (e)               arc cosine
atan  (e)               arc tangent
deg   (e)               radians to degrees
rad   (e)               degrees to radians
ln    (e)               natural logarithm
exp   (e)               natural exponent
log10 (e)               base 10 logarithm
exp10 (e)               base 10 exponent
int   (e)               integer  part of real
frac  (e)               fraction part of real
abs   (e)               absolute value
where:
int(tan(2.3 * ln(%6)))

Multi-value functions

The following multi-value arithmetic functions are available:

atan2 (v1,v2)           arc tan (v1/v2) using signs of v1,v2
mod   (v1,v2)           remainder of v1/v2
min   (v1,v2,...,vn)    minimum value of v1,v2,...,vn
max   (v1,v2,...,vn)    maximum value of v1,v2,...,vn
where:
min (%1, %2, #temp, 25.5, @dbx)

Bit manipulation functions

The following bit manipulation functions are available. They are accomplished by converting passed values to integers, performing the logical operation on all the bits, and converting back. 'not' operations should be followed by an 'and' to remove high bits.

not (v1)                logical not
and (v1,v2,...,vn)      logical and
or  (v1,v2,...,vn)      logical inclusive or
xor (v1,v2,...,vn)      logical exclusive or
where:
#t = not(%1); #t= and(#t,255);   | to ensure only 8 bits

Sections

The statements and comments which make up a model are divided up into the following sections:

The Setup section sets up the processing environment. This includes: prompting the user for any required data; associating attribute data with image channels (layers); and printing messages to the user's screen. This section is executed once before any processing is done.

The following types of statements can be included in the 'Setup' section:

The Equations section defines the processing that should be done. This section is applied to each pixel in the database. For example, if the database has dimensions of 512 by 512, the equations section would be executed 262144 times.

The following types of statements can be included in the Equations section:

Each time this section is applied, numeric variables are reset to the value entered from an INPUT statement or to zero. Character variables are also reset to values entered or to the empty (null) string.

When MODEL is run, the following steps are followed:

  1. The model is read in and internal data structures are set up.
  2. The Setup section is executed and, if necessary, the user is prompted for required data.
  3. The image database is read in and the modeling equations in the Equations section are applied to each pixel. If any output channels (layers) are generated, these are written back to the file.

    Note: This step takes almost all the processing time.
  4. All data files are closed and the MODEL terminates.

COMMENT

The COMMENT ('!') statement is used to add documentation to the model. Commetns have no effect on the execution of the model; they may appear anywhere in the model and can be used inline. When a comment is encountered, the rest of the line is considered a comment.

Syntax:    ! text

Example:   ! This line could give the author's name
           !
           %6 = 257;     !This is an in-line comment

PRINT

The PRINT statement allows a line of text to be output to the user's terminal when the model is run.

Syntax:     PRINT "text";

Example:    print "The Soil Model takes 15 minutes to run";

INPUT

The INPUT statement allows the model to prompt the user for constants and layers (image channels) which should be associated with layer variables.

Syntax:    INPUT "text" #x;            | numerical constant
           INPUT "text" $x;            | character constant
           INPUT "text" %x;            | layer variable

Example:   input "Enter layer for Tree Coverage: " %tree ;

Values entered by the user for a layer variable are checked to ensure the image channel exists on the database file.

INPUTA

The INPUTA statement allows the model to prompt the user for the source of attribute information to associate with a layer variable or a numeric array variable.

Syntax:           INPUTA "text" %x ;
            INPUTA "text" #x[];

Example:   inputa "Enter source of tree attributes: " %tree;
           inputa "Enter segment number for array data: " #a[];

When a layer variable is used (for example, %x), if a number is entered, a check is run to verify if this a TEXT (attribute), LUT, or PCT segment on the database file. If a file name is entered, this is checked to ensure that it is an existing text file and that it contains valid attribute data.

When a numeric array variable is used (for example, #x[]), only a number can be entered, and this is checked to ensure that it is an array segment (type ARR:181) on the database file.

SET

The SET statement associates a layer variable with a channel on the file or a numeric variable with value. The value can either be a constant or come from an entry in the parameter file.

Syntax:   SET %x = n ;
          SET #x = parm(n);

Example:  set %trees   = 1;
          set #minimum = imstat(11);
          set #maximum = 23.5;

SETA

The SETA statement associates a numeric array variable with a database segment containing array data or a layer variable with attribute data held in a text file on disk or a database segment containing TEXT (attribute), LUT, or PCT data.

Syntax:  SETA #x[] = n ;         | numeric array to segment number n
         SETA %x = n ;           | layer variable to segment number n
         SETA %x = "filename" ;  | layer variable to text file name

Example:  seta %3 = "attr.txt";
          seta #means[] = 3 ;

ASSIGNMENT

There are three types of assignments:

Numeric variables:

Syntax:   #x = arithmetic expression ;

Example:  #cost = %crop.2 * 1.5 + log10(%rain) ;

Character variables:

Syntax:   $x = character expression ;

Example:  $x = "ABCDEF" ;

Layer variables:

The value assigned to the layer variable replaces its current value and will be written back to the PCIDSK database file. Note that the layer value is a real value until it is actually written to disk, at which time it is converted to the type that the channel has on disk.

Syntax:   %x = arithmetic expression ;

Example:  %3 = %crop.2 * 1.5 + log10(%rain);
Note: Assignment cannot be made to numeric array variables. Numeric variables are read-only, and get their contents from array segments held on PCIDSK database files.

IF

The syntax for the possible IF ... EXTRIF ... ELSE ... ENDIF constructs are shown below:

 IF cond THEN               IF cond THEN             IF cond THEN
   statement;statement;statement;
      ...       ...       ...
   statement;statement;statement;
 EXTRIF cond THEN           ELSE     ENDIF;
   statement;statement;
      ...       ...
   statement;statement;
 ELSE       ENDIF;
   statement;
      ...
   statement;
 ENDIF;

statement can be an ASSIGNMENT, GOTO, LABEL, STOP or another IF statement.

cond is a condition made up of a series of logical expressions joined by logical operators. This has the syntax:

(exp relopr exp) logopr (exp relopr exp) ...

where:

exp          is an arithmetic or character expression
relopr       is a relational operator
logopr       is a logical operator

The following relational operators are available and will work on either arithmetic or character expressions:

=            equals
>            greater than
<            less than
>=           greater than or equal
<=           less than or equal
<>           not equal

The following logical operators are available:

and
or
   if (%tree.2 = "spruce") and (%rain > 10) then
      %result = 5;
   else
      %result = %rain / 3;
   endif;

GOTO

The GOTO statement allows execution to transfer to a different part of the model. The LABEL statement is used in conjunction with the GOTO statement to provide a transfer location.

Syntax:  GOTO ident ;

Example:  if (%1 = 3) then goto skip; endif;
Note: GOTO statements should be used sparingly, or not at all if possible. MODEL does not detect 'infinite' loops created using GOTO statements.

LABEL

The LABEL statement provides a transfer location for GOTO statements.

Syntax:   LABEL ident;

Example:  label loop; #i=#i+1; if (#i<10) then goto loop; endif;

STOP

The STOP statement allows the model to be terminated prematurely if an error condition is detected.

Syntax:    STOP "message" ;

Example:   if (%3 = 0) then stop "zero value detected"; endif;

The message and the (x,y) position of the pixel that was being processed is printed.

Note: Because buffers are not flushed, if a STOP statement is executed, output will not reflect the current point of processing.

SEMI-COLON

The SEMI-COLON (';') acts as a statement separator. This allows for more than one statement per line and statements that span more than one line. Each statement must end with a semicolon except for IF constructs, where the semicolon goes after the associated ENDIF.

Back to top

Example

Detailed example

A project requires the generation of a map showing areas of high fire risk. The study region is mountainous and it has been determined that the risk of fire increases with elevation and ground cover type. The base elevation at which the risk starts varies with the time of the year and the amount of rainfall that has occurred. This base elevation is computed on a monthly basis from available weather data.

The file 'irvine.pix' contains 16-bit elevation data held in channel 10 (signed 16-bit channel) expressed in metres. Channel 6 contains Land use / Land coverage data obtained from the U.S. Geological Survey. Segment 28 on the database contains the attribute data identifying the coverage codes. A partial listing of this data is shown below:

 ! Land Use / Land Cover Classification System from USGS.
 !
 ! gray level ; Level 1      Level 2
 !
           11 ; Urban        Residential
           12 ; Urban        Commercial
           13 ; Urban        Industrial
           14 ; Urban        Transportation
           15 ; Urban        Commercial/Industrial 
           16 ; Urban        Mixed
           17 ; Urban        Other
           21 ; Agriculture  Crop/Pasture
           22 ; Agriculture  Orchards
           23 ; Agriculture  Feeding
           24 ; Agriculture  Other
           31 ; Rangeland    Herbaceous
         . . .

It has been determined that only land classed as 'Agriculture', 'Rangeland' and 'Forest' are at risk. The model will generate a new output channel (layer) showing areas of risk and will also generate a report giving the acreage of each class at risk. To improve the appearance of the report, the following text was entered into a text file, 'labels.att':

 ! Channel 7 Class ;  Class Name
          0         ;  'No Risk'
         20         ;  Agriculture
         30         ;  Rangeland
         40         ;  Forest

The actual model is shown below and was entered into a text file named 'risk.mod'.

!In this model, we are assuming that channel 6 is the coverage
!and channel 10 is elevation data.

!Setup Section

local float #base

!Prompt user for elevation
input "Enter base elevation: " #base;

!Land use/Land cover attributes
!seta %6 = 28;

!Labels for report
!seta %7 = 'labels.att';

print "Channel 7 will receive the new coverage map.";

!Equations section

model on "c:\temp\irvine.pix"

!local mvar   base, elev;

!elevation to a single value
!elev = %10;

!base = #base;
!if (elev < base) then
if (%10 < #base) then
    %7 = 0;
else
!"Agriculture"
    if     (%6 > 20 and %6 < 30) then
        %7 = 20;
!"Rangeland"
    elseif (%6 > 30 and %6 < 40) then
        %7 = 30;
!"Forest"
    elseif (%6 > 40 and %6 < 50) then
        %7 = 40;
!"No Risk"
    else
        %7 = 0;
    endif;
endif;

endmodel

!Report Section:  Generate an area report with title

local int nAgriculture, nRangeland, nForest, nNoRisk;
nAgriculture = 0;
nRangeland   = 0;
nForest      = 0;
nNoRisk      = 0;

local double hectares;
model on "c:\temp\irvine.pix"
    hectares = (@meterx * @metery / 10000.0);
endmodel

local int   fd, line, pixel
local float ptr scanline

fd = DBOpen("c:\temp\irvine.pix", "r")
scanline = EAlloc(float, DBPixels(fd))
for line = 1 to DBLines(fd)
    call DBReadLine(fd, 7, line-1, 0, DBPixels(fd), scanline)
    for pixel = 1 to DBPixels(fd)
        !"Agriculture"
        if     (scanline(pixel) = 20) then
            nAgriculture = nAgriculture + 1
        !"Rangeland"
        elseif (scanline(pixel) = 30) then
            nRangeland = nRangeland + 1
        !"Forest"
        elseif (scanline(pixel) = 40) then
            nForest = nForest + 1
        !"No Risk"
        else
            nNoRisk = nNoRisk + 1
        endif;
    endfor
endfor
call EFree(scanline)
call DBClose(fd)

print "Fire Risk Area Report";

!report %7 by hectares identify %7.1;

printf "\n%s\n\n", \
       "Value      Pixels    Hectares   Identifier"

printf "%s %8d %11.3f %s\n", \
       "    0   ", nNoRisk,      (nNoRisk * hectares),      "  No Risk"
printf "%s %8d %11.3f %s\n", \
       "   20   ", nAgriculture, (nAgriculture * hectares), "  Agriculture"
printf "%s %8d %11.3f %s\n", \
       "   30   ", nRangeland,   (nRangeland * hectares),   "  Rangeland"
printf "%s %8d %11.3f %s\n", \
       "   40   ", nForest,      (nForest * hectares),      "  Forest"

To run the model, enter the following commands:

from pci.model import model

file	=	"irvine.pix"
source	=	"risk.mod"
undefval	=	[]
imstat	=	model( file, source, undefval )

Arithmetic

Perform a 'Vegetative Index' calculation using channels 1 and 2, saving the result to channel 7. If channel 7 is 32 bit real, the following model is used:

%7=(%1-%2)/(%1+%2);

If channel 7 is 8-bit, some scaling and adjustment is necessary:

%7=((%1-%2)/(%1+%2))*128 + 127.5;

Blending

Create an image which smoothly blends channel 1 into channel 2 as we move across the image. The output is placed in channel 7.

%7 = (@x-1)/@dbx)*%2 + (@dbx-@x)/@dbx*%1;

Testimages

Create a gray level ramp of 0 to 255 across an image plane.

%7 = ((@x-1)*255) / @dbx;

Grids

A file is georeferenced in UTM coordinates. As part of the final processing steps, the user wishes a grid to be superimposed on the imagery along 1000-metre intervals in both the x and y directions. The input imagery is an RGB-enhanced image on channels 1, 2, 3. The output will be to channels 7, 8, and 9.

if (mod(@geox,1000)<=@sizex) or (mod(@geoy,1000)<=@sizey) then
    %7 = 255;   %8 = 255;   %9 = 255;
else
    %7 = %1;    %8 = %2;    %9 = %3;
endif;

The following model prompts the user for the spacing (in pixels) for a regular grid as well as an input and output channel.

input 'Enter the grid spacing:   ' #s;
input 'Enter the input  channel: ' %in;
input 'Enter the output channel: ' %out;
if (mod(@x,#s)=0) or (mod(@y,#s)=0) then
    %out=255;
    else
    %out=%in;
endif;

Volume

One of the steps in producing a study for a new dam project is to estimate the capacity of the reservoir that will be formed. This can be accomplished by summing the volume that is contributed by each pixel that will be in the reservoir.

Given that:
  • channel 10 has the elevation for each pixel expressed in metres
  • channel 7 has a mask where a pixel value of 27 means the pixel is in the reservoir area, any other value means it is not. (This mask was created from the elevation channel by altering the elevation data to show the line of the dam at its maximum final built height, thresholding at the surface elevation of the reservoir (program THR), burning the resulting bitmap into a channel (MAP), then identifying the polygon number which represents the reservoir (DCP)).

The following model calculates the volume of the reservoir at a user-defined water level.

        !       Reservoir Capacity Model
        !
        input 'Enter water level in metres: ' #level;
        !
        if (%7 = 23) then
           #volume = (#level - %10) * @metrex * @metrey;
           if (#volume < 0) then #volume = 0; endif;
        endif;
        !
        title ' Capacity of Reservoir in Cubic Metres';

Filtering

Perform a 3x3 smoothing filter on channel 4. Add 0.5 to the result since channel 7 is a 8U channel.

%7 = (%4[@x-1,@y-1] + %4[@x,@y-1] + %4[@x+1,@y-1] + \
      %4[@x-1,@y]   + %4[@x,@y]   + %4[@x+1,@y]   + \
      %4[@x-1,@y+1] + %4[@x,@y+1] + %4[@x+1,@y+1] ) / 9 + 0.5;
Note: The FAV function performs this operation more efficiently.

Enhancement

Segments 2, 3, and 4 are lookup tables for channels 1, 2, and 3 respectively. Perform an enhancement operation on the three channels and output the enhanced images to channels 7, 8, and 9.

seta %1=2; seta %2=3; seta %3=4;      %7=%1.1; %8=%2.1; %9=%3.1;
Note: The function LUT performs this operation more efficiently.

© PCI Geomatics Enterprises, Inc.®, 2026. All rights reserved.