EGO Script Language

Introduction

EGO Script is a simple, text-based language for creating and editing Dinamica EGO models. A model written in this format is stored in a file with the .ego extension. An .ego file is just another way of describing a model — it is equivalent to the XML form Dinamica EGO uses internally. Because the two are interchangeable, you can write a model as an EGO script, open it in the graphical interface, edit it there, and save it again, moving freely between the textual and visual representations.

Caution: When you round-trip a model through the graphical interface, the interface can rewrite a model's layout and the format of its inputs and outputs according to the options currently in effect, so a script reopened and saved from the GUI may not come back byte-for-byte identical to what you wrote. This is normal, and the resulting model is equivalent.
Tip: There are two practical ways to move between the visual and textual representations. First, a whole model can be saved as a .ego file from the GUI via FileSave Model, and reopened via FileOpen Model. Second, any selection of functors in the GUI sketch — or the entire model — can be copied to the clipboard and pasted directly into an external text editor as an EGO Script fragment; conversely, any EGO Script fragment copied from a text editor can be pasted straight into the GUI sketch.

This tutorial introduces the language from the ground up: the structure of a model, how functors are called and wired together, how containers and properties work, and the shorthand used to write expressions.

Overview

A complete EGO script model can be as short as the example below. It loads a raster map and saves a copy of it in a different format:

Script {{
  // Loads a GeoTiff map.
  x := LoadMap "c:/map.tif";
  // Saves an ERMapper map.
  SaveMap x "c:/map-copy.ers";
}};

Even this small example shows every essential element of the language.

The Script block

The Script {{ }} block delimits the script text. A single file can carry several script elements, and the Script block is what groups them together. For backward compatibility with earlier versions, this declaration may be omitted.

Tip: Omitting the Script block is discouraged — always wrap a model in an explicit Script block.

Functors, variables, and binding

Each statement inside the block calls a functor — a processing unit that consumes inputs and produces outputs. The second line of the example calls a Load Map to load the GeoTiff file “map.tif”, and binds the resulting map to the variable x. Two conventions are worth noting right away. First, a functor's name is written without spaces (LoadMap, not Load Map). Second, a variable is always defined and bound with the := operator. The third line calls Save Map to write the map held by x to an ERMapper file named “c:/map-copy.ers”. The position of a value relative to the functor name determines whether it is an input or an output:

  • Values and variables written after the functor name are bound to its input ports.
  • Variables written before the := operator are bound to its output ports.

So in x := LoadMap “c:/map.tif”, the string “c:/map.tif” is an input and x receives the output; in SaveMap x “c:/map-copy.ers”, both x and the filename are inputs, and the call produces no output that the script needs to keep.

A variable name must begin with an underscore or a letter, and may be followed by any combination of underscores, letters, and digits ([_a-zA-Z][_a-zA-Z0-9]*). Variable names are case-sensitive.

Variables are the primary mechanism by which functors pass data to one another, and data dependencies are the main source of execution ordering. A variable must be bound by the functor that produces it before any functor that reads it can run — this is what creates a dependency between the two. Functors that do not share a variable, directly or through a chain of intermediate variables, have no dependency on each other and may execute in any order or at the same time. Container functors, described in the Container functors section of the reference, impose a second ordering constraint on top of this.

Note: The position of a functor definition in the script file does not determine when it runs. Unless two functors are connected by a data dependency — directly or through a chain of variables — never assume anything about their relative execution order. The only exception is containers, covered later in this section.

A first look at comments

The sequence // begins a comment, which continues to the end of the line. The two comment lines in the example document what each step does. Comments are more than annotations — they attach to the functor that follows them and are preserved with the model; the Comments section of the reference describes this in detail.

Reference

This section describes how a functor call is written in EGO Script, the three interchangeable styles for supplying its inputs, how container functors hold and communicate with the functors nested inside them, the shorthand notation used to write the calculator functors that evaluate expressions, and how comments and properties annotate a model.


Functor calls

A functor call binds outputs — the variables written before := — and consumes inputs — the values, variables, and constants written after the functor name. Every functor defines a fixed set of typed ports for its inputs and outputs:

areaTable := CalcAreas landscape .no;

Here Calc Areas reads two inputs (landscape and the constant .no) and produces one output, bound to the variable areaTable. Constants are written with a leading dot (.no, .default, .int32, .none) — see Constants below.

Inputs can be supplied in three interchangeable styles — positional, nominal, and inline. The styles may be mixed freely between calls, and even within a single call.

Constants

Constants supply a fixed value directly to an input port, without connecting a functor. They come in several forms:

  • Numeric literals — integer or real values written directly (0, 250, 3.14).
  • Text constants — text enclosed in double quotes. The syntax is identical regardless of the specific type: the port determines whether the value is treated as a String, a MapFilename, a TableFilename, a LookupTableFilename, a WeightsFilename, a GenericFilename, a Folder, a Name, or a Code. For example, "c:/data/landscape.tif" supplied to a MapFilename port is a map filename constant, not a generic string.
  • Dot constants — a leading dot followed by a keyword (.yes, .no, .int32, .default). Each data type defines its own set of dot constants; for example, boolean ports accept .yes and .no, cell type ports accept .int32, .float32, and so on, and storage mode ports accept .default. The constants accepted by a port depend entirely on its type.
  • Structured constants — complex values such as tables, matrices, or transition specifications, enclosed in square brackets [ … ]. These are specific to individual functors and can be multi-line.

A call can mix all constant forms with variable references in a single argument list. This call loads a map, supplying a map filename constant, two dot constants for the null-value override and storage mode, and a numeric literal for the suffix digit count:

landscape := LoadCategoricalMap "c:/data/landscape.tif" .none .default 0;

Here “c:/data/landscape.tif” is a map filename constant (the filename port is type MapFilename), .none leaves the nullable nullValue port without a value, .default is a storage mode dot constant, and 0 is a numeric literal.

Structured constants use the same square-bracket syntax as expressions but appear as positional arguments. This call passes a transition matrix directly as a structured constant, specifying one transition (from class 2 to class 1) and its rate:

changes := CalcChangeMatrix landscape [ 2->1 0.05 ];

Here [ 2→1 0.05 ] is a structured constant representing a transition matrix with a 5% rate from class 2 to class 1.

Two dot constants have special predefined meanings:

  • .UNBOUND — available for any input port regardless of type. Indicates the port is not connected, or its connection is being deliberately ignored. This constant appears in particular when a script fragment is copied from the GUI to a text editor and some of the original inputs are not part of the copied selection — those unresolved connections are written as .UNBOUND.
  • .none — available only for optional nullable input ports (ports that explicitly accept a missing value as meaningful input and whose default value is already .none). Indicates the port is intentionally left without a value.

Positional syntax

In positional syntax, arguments fill the input ports in order: the first argument fills the first port, the second fills the second, and so on.

landscape := LoadCategoricalMap "c:/landscape.tif";
areaTable := CalcAreas landscape .no;

Omitting optional inputs. A functor's optional input ports always come after its required ones. In positional syntax you may stop supplying arguments early, but you cannot skip an optional input and then supply a later one — once you omit a port, every port after it is omitted too. To leave a gap, use nominal syntax (described below) for that call.

Load Categorical Map, for example, takes a required filename followed by several optional inputs; this call supplies the first few of them positionally and omits the rest:

landscape := LoadCategoricalMap "c:/landscape.ers" .no .no 0 0 .none .none;

Discarding outputs. A functor may return several outputs. Write an underscore (_) in any output position to discard that output. When you want only one output from the middle of the list, underscores act as placeholders for the positions you skip:

// GetProjectionInfo returns nine outputs; keep only the seventh (the coordinate type):
_ _ _ _ _ _ coordinateType _ _ := GetProjectionInfo landscape;

// GetElevationGraphInfo returns three outputs; keep only the first:
patchInfo _ _ := GetElevationGraphInfo elevationGraph .no .no;

Nominal syntax

In nominal syntax (also referred to as named parameters in the Dinamica EGO GUI options), inputs are enclosed in a pair of single curly braces { } and bound by port name: each entry is written as portName = value, with entries separated by commas. Order does not matter, and any optional port may be omitted regardless of position. See ports for a full description of port properties including types, nullability, and default values. This is the clearest style for functors with many optional inputs:

patchMap := CalcPatchLabelMap {
    source = elevationMap,
    initialPatchLabel = 1,
    onlyOrthogonalsAreAllowed = .no,
    windowLines = 3,
    windowColumns = 3,
    cellType = .int32,
    nullValue = .default,
    patchLabelsAreSparse = .no,
    useSequentialPatchLabels = .no
};
Note: Port names in the script use camelCase with a lowercase first letter (e.g. cellType, resultIsSparse). In the GUI the same ports are displayed with spaces between words and all words capitalised (e.g. “Cell Type”, “Result Is Sparse”). The same conversion rules that govern functor aliases and variable names apply here — see Alias and variable name conversion.
Note: The single braces { } used here for nominal syntax are distinct from the double braces {{ }} used to delimit a container functor's block of contained functors.

Outputs follow the opposite rule. An output is bound by name as variable = portName — the variable you choose on the left, the functor's output port name on the right — also inside single braces { }, placed before :=:

{ areaTable = areas } := CalcAreas { source = landscape };

When a functor produces multiple outputs, all of them can be bound in a single braces block, separated by commas:

{ woeCoefficients = weights, woeReport = report } := DetermineWeightsOfEvidenceCoefficients initialLandscape finalLandscape ranges;

Any output can be replaced with _ to discard it when only some outputs are needed.

So inputs read portName = value while outputs read variable = portName. The two directions are summarized below:

Position Form Left side Right side
Input (after name) portName = value input port name value/variable
Output (before :=) variable = portName your variable output port name

Styles may be combined. A call can take positional inputs but bind a named output, or vice versa:

landscape := LoadCategoricalMap { filename = "c:/landscape.tif" };
{ areaTable = areas } := CalcAreas landscape;
SaveTable { table = areaTable, filename = "c:/areas.csv" };

The port names used in nominal syntax are the input and output names defined by each functor (for instance, Calc Patch Label Map defines the inputs source, initialPatchLabel, windowLines, and so on). Names are case-sensitive.

Inline syntax

Inline syntax nests one call directly inside another instead of binding an intermediate variable. The nested call is wrapped in parentheses, and its single output is passed straight into the enclosing input port — the same idea as nesting function calls in conventional programming languages.

These two fragments are equivalent. The first names an intermediate variable:

landscape := LoadCategoricalMap { filename = "c:/landscape.tif" };
{ areaTable = areas } := CalcAreas landscape;

The second inlines the LoadCategoricalMap call into the CalcAreas call:

{ areaTable = areas } := CalcAreas (LoadCategoricalMap { filename = "c:/landscape.tif" });

Inline calls nest to any depth and combine with the other styles. This call computes a column with one functor and feeds it straight into another that adds the column to a table, which is in turn fed into a third functor:

spatialIndex := CreateSpatialIndexFor2DPoints (AddTableColumn {
    table = yCoordinateTable,
    columnName = "X_Coordinate",
    columnType = .real,
    columnIndex = 0,
    columnShouldBeKey = .no,
    columnValues = xCoordinateTable,
    defaultValue = .none
});

Inlining is convenient only when you need a single output from the nested call. If you need more than one of its outputs, bind it to variables instead.

Setting the @inline property on a functor prevents it from being inlined when the script is written. The same effect also applies automatically whenever any other property is defined for the functor — such as a comment, a custom alias, or any other annotation — because an inlined functor carries no separate node to attach that information to, so it would be lost. See Properties for the full list of functor properties.


Container functors

A container functor is a functor that holds other functors inside it. The contained functors execute within the container's scope.

Containers are the second source of execution ordering in Dinamica EGO, alongside data dependencies. All functors inside a container execute as part of that container's execution. This means that if container B depends on container A — for example, B consumes a value produced by something inside A — then B will only start after A has fully completed. As a consequence, every functor inside B is guaranteed to run after every functor inside A, and the contents of the two containers will never execute simultaneously.

Containers fall into a few families:

  • Sequencing. Group runs its contents as a unit, with no repetition or condition. It exists to organize a model and to give a block a shared property such as a label or color.
  • Conditional. If Then runs its contents only when a condition is true; If Not Then runs them only when a condition is false.
  • Loops. Several containers repeat their contents. Repeat runs them a fixed number of times; For iterates over a numeric range; For Each iterates over the rows of a table; For Each Category iterates over the categories of a map; For Each Region iterates over the regions of a map; and While and Do While repeat for as long as a condition holds.
  • Region management. Region Manager establishes a region context and runs its contents once for that context, exposing the region to the functors inside it.
  • Error handling. Skip On Error and Skip All On Error execute their contained functors while capturing and ignoring any error that occurs. Both accept a trapAndIgnoreErrors boolean input — when set to false, they behave as a plain Group and errors are not suppressed. Both also produce an executionCompletedSuccessfully output that can be tested by subsequent functors. The two differ in what happens to results already produced when an error is raised: Skip On Error preserves the outputs of any functors that completed successfully before the error; Skip All On Error discards all of them. They are typically paired with a junction outside the container to react to the outcome — see Error-handling pattern below.

The calculator functors described later in this section are also containers: each holds the expression it evaluates, and in its verbose form holds a block of operand definitions.

The contained functors are written inside a double-brace block {{ … }} that follows the container call:

_ := Group .none {{
    attributeTable := ExtractCategoricalMapAttributes landscape regions .yes;
    cellCounts := GetTableFromKey attributeTable [ 9 ];
    countLookup := LookupTable cellCounts;
}};

Containers nest to any depth, and like any functor they may carry properties such as a label or color (see Functor properties, below).

A container exchanges data with the functors inside it through internal ports: internal output ports carry values from the container into the block, and internal input ports carry values from the block back to the container.

Sequence ports

Most container functors expose two optional sequencing ports alongside their regular inputs and outputs:

  • sequenceInput — a value connected here has no effect on the computation, but forces the functor that produced that value to complete before this container starts.
  • sequenceOutput — connecting this output to another container's sequenceInput forces this container to complete before the other one starts.

These ports carry no data of their own; their only purpose is to impose execution ordering. Because any data type can be connected to a sequenceInput port, the output of one container can feed directly into the next container's sequencing slot:

// ForEachCategory completes before Group starts.
sequenceOut := ForEachCategory finalLandscape .none {{
    // ...
}};
_ := Group sequenceOut {{
    // ...
}};
Note: Sequence ports are only needed when two containers have no natural data dependency between them — if one container already produces a value that the other consumes, the ordering is already established and no sequencing port is required. Before sequence ports were available, models used a forced-dependency pattern — creating a dummy data value inside one container and consuming it inside another to manufacture an artificial data dependency. This idiom still appears in older scripts but is now a last resort, used only for functors that do not expose sequenceInput and sequenceOutput ports (such as Skip On Error and Skip All On Error, which instead expose an executionCompletedSuccessfully boolean output that can serve the same purpose).

Internal output ports

An internal output port carries a value from the container into the functors nested inside it. The container produces the value; the contained functors consume it. A loop's current iteration value and a manager object made available to a block are typical internal outputs.

An internal output port is read at the top of the block with the same variable = portName form used for ordinary outputs — your variable on the left, the port name on the right. If present, these bindings must be the first declarations inside the container block, before any functor calls. A loop, for example, exposes its current element through an internal output port named step:

ForEachCategory categorization {{
    currentCategory = step;             // read the internal output port `step`
    categoryId := Step currentCategory;
    // ...
}};

Here step is the port the loop provides, and currentCategory is the variable that receives it for use inside the block.

RegionManager provides another example. It creates a region context and exposes it to the functors inside its block through an internal output port:

RegionManager regionMap 0 {{
    manager = regionManager;            // read the internal output port `regionManager`
    allRegions := GetAllRegionsInfo manager;
}};

manager = regionManager; reads the container's internal output port regionManager into the variable manager, which Get All Regions Info then consumes. The name on the right is always the port; the name on the left is your variable.

Internal input ports

An internal input port carries a value the other way: from the functors inside the block back to the container. The contained functors produce the value; the container consumes it. The condition that decides whether a loop repeats is the clearest example.

A While or DoWhile loop has an internal input port for its repeat condition. It is fed by placing a Set While Condition functor inside the loop body — the condition output port of SetWhileCondition is auto-bound to the loop's condition internal input, so no explicit connection is needed:

_ := DoWhile .none {{
    // ... contained functors compute `keepGoing`, a non-zero value to continue ...
    _ := SetWhileCondition keepGoing;   // condition output auto-binds to the loop
}};

The SetWhileCondition auto-binding works in both directions: the output is automatically wired to whichever enclosing While or DoWhile contains it, and the loop evaluates it before each iteration to decide whether to run the body again.

A container may also expose a sequencing-only internal port (carrying no data) used to force one container to finish before another begins — see Sequence ports.

Carrying and selecting values across iterations

Two families of functors are commonly used together with loops and manage how a value flows from one place, or one iteration, to the next.

A mux carries a value across the iterations of a loop. On the first iteration it emits its initial input. On every later iteration it emits its feedback input — the value produced by the previous pass — so the loop can build on its own prior result. Muxes are typed: Mux Map, Mux Categorical Map, Mux Table, Mux Lookup Table, Mux Value, Mux Tuple, and so on. A mux at the top of a loop body, paired with a variable assigned at the bottom, forms the loop's running state. This loop counts from 0 and stops once the counter reaches 10:

_ := DoWhile .none {{
    // First pass: 0. Later passes: `nextCount` from the previous pass.
    count := MuxValue 0 nextCount;

    nextCount := $ [ $count + 1 ];

    // A boolean converts to a real (true -> 1, false -> 0), so a value calculator turns a
    // stop test into the numeric flag the loop expects: non-zero continues, zero stops.
    keepGoing := $ [ $nextCount < 10 ];

    _ := SetWhileCondition keepGoing;
}};

A junction selects between two dataflows. It reads its first input; if that input carries data, the junction passes it through. If the first input is empty, it passes the second input through instead. If both are empty, the junction reports an error. Junctions are typed, with one per data kind — Map Junction, Categorical Map Junction, Table Junction, Lookup Table Junction, Value Junction, String Junction, and so on:

// `primary` if it has data, otherwise `fallback`:
chosen := MapJunction primary fallback;

Error-handling pattern

The error-handling containers are most useful when combined with a junction outside the block. The sentinel and the risky functor inside the container have no data dependency on each other, so they execute independently. The pattern works as follows:

  1. If the risky functor raises an error, Skip All On Error captures it and discards all results produced by functors inside the container — including the sentinel, even though it completed successfully on its own.
  2. Outside the container, a junction tests whether anything propagated out. If the sentinel was discarded (error case), the container produced nothing and the junction falls back to its default value. If no error occurred, the sentinel propagates normally and the junction forwards it.

This example tests whether a map file can be loaded successfully:

_ := SkipAllOnError .yes {{
    // The sentinel has no dependency on LoadMap — both execute independently.
    // If LoadMap raises an error, SkipAllOnError discards all results inside,
    // including this sentinel.
    booleanValue0 := BooleanValue .yes;
    _ := LoadMap inputMapFilename;
}};
// If the sentinel was discarded (error), the junction falls back to false (0).
// If no error occurred, the sentinel propagates and the junction returns true.
result := ValueJunction booleanValue0 0;

Skip On Error behaves differently: instead of discarding all results, it preserves the outputs of any functors that had already completed when the error was raised. In the pattern above this means the sentinel would always propagate — making Skip On Error suitable for cases where partial results from a failed block are still useful, not for a simple success/failure test.


Calculator functor shorthand

A family of calculator functors evaluates an expression and returns a result of a given type:

Functor Returns
Calculate Map a map
Calculate Categorical Map a categorical map
Calculate Lookup Table Values a lookup table (keys taken from a base table; values computed)
Calculate Lookup Table Keys And Values a lookup table (both keys and values computed)
Calculate Value a single value
See also: This section covers only the EGO Script syntax used to call these functors. For the full semantics of each one — inputs, parameters, the expression language, and null handling — see Calculate Functors — Complete Operator Documentation.

Each of these functors can be written in two syntactic forms: the verbose form, which uses the functor's full name and explicit hook functors to connect data, or the abbreviated syntax (also called shorthand), which replaces the functor name with a compact symbol and references operands directly by variable name. The abbreviated symbol for each functor is:

Shorthand Functor
# CalculateMap
## CalculateCategoricalMap
% CalculateLookupTableValues
%% CalculateLookupTableKeysAndValues
$ CalculateValue
Note: The shorthand is the symbol alone — the [ … ] that usually appears next is simply the functor's first argument (the expression to evaluate), not part of the symbol itself. Whatever follows the bracket (.int8 .default .no .none, or a base table and column names) are the functor's remaining inputs, supplied in positional order.

Verbose form

In the verbose form, data is connected through hook functors — Number Map, Number Table, and Number Value — which supply maps, tables, and scalar values to the expression respectively. Each hook is assigned a number, and the expression references it by a type-specific numbered prefix: i1, i2… for maps; t1, t2… for tables and lookup tables; v1, v2… for values. Each type is numbered independently:

proximityMap := CalculateCategoricalMap {
    expression = [
        if t1[?i1] then 1 else null
    ],
    cellType = .int8,
    nullValue = .default,
    resultIsSparse = .no,
    resultFormat = .none
} {{
    // i1
    NumberMap   regions      1;
    // t1
    NumberTable regionCounts 1;
}};

The following uses two table hooks and two value hooks at once, keeping every top whose height and slope both clear a threshold:

hilltops := CalculateLookupTableValues [
    if t1[line] >= v1 and t2[line] >= v2 then 1 else null
] "Top_Id" "Is_Hilltop" .none {{
    // t1
    NumberTable saddleHeights     1;
    // t2
    NumberTable saddleAngles      2;
    // v1
    NumberValue minimumHeight     1;
    // v2
    NumberValue minimumSlopeAngle 2;
}};

Abbreviated syntax

In the abbreviated syntax, the hook block is omitted entirely. The expression references connected data directly by variable name, prefixed by a sigil that identifies the type:

Type Sigil Named form Verbose equivalent
map # #regions i1, i2, …
table or lookup table % %regionCounts t1, t2, …
value $ $radius v1, v2, …

The same two calculations from the verbose section above, written in abbreviated syntax:

proximityMap := ## [
    if %regionCounts[?#regions] then 1 else null
] .int8 .default .no .none;
hilltops := % [
    if %saddleHeights[line] >= $minimumHeight and %saddleAngles[line] >= $minimumSlopeAngle then 1 else null
] "Top_Id" "Is_Hilltop" .none;

The operands are named directly and the hook block disappears entirely. A lookup by key is written %table[key]; ? tests whether a key is present, as in %regionCounts[?#regions].

Conversion between forms

Converting abbreviated syntax to verbose is always lossless. Converting verbose to abbreviated is only possible when all hooks are free of comments, properties, and identifiers that do not appear in the expression.

Note: This constraint applies specifically when the GUI saves a script or generates a fragment in abbreviated syntax. When writing a script by hand in a text editor, the situation does not arise — you simply write the appropriate form directly.
Tip: You can control which form Dinamica EGO uses when saving a script via the Use abbreviated syntax for Calculate family functors option, found under ToolsOptions | EGO Script — see Script generation options for the full list of generation options.

The two lookup-table calculators

CalculateLookupTableValues (%) computes only the values of a lookup table; the keys are taken from a base table supplied as an argument. The example below marks each row whose key equals its own value:

// Shorthand
dominantTops := % [
    if %dominanceLookup[line] = line then 1 else null
] "Top_Id" "Is_Dominant" dominanceLookup;

// Verbose equivalent
dominantTops := CalculateLookupTableValues [
    if t1[line] = line then 1 else null
] "Top_Id" "Is_Dominant" dominanceLookup {{
    // t1
    NumberTable dominanceLookup 1;
}};

CalculateLookupTableKeysAndValues (%%) computes both the keys and the values, using a separate expression for each. In the verbose form the two expressions are the functor's first two positional arguments:

// Shorthand
nearestDistances := %% {
    keyColumnExpression   = [ %nearestPoints[[line]["Point_Id"]] ],
    valueColumnExpression = [ %nearestPoints[[line]["Nearest_Distance"]] ],
    keyColumnName   = "Point_Id",
    valueColumnName = "Nearest_Distance",
    baseLookupTable = pointKeys
};

// Verbose equivalent
nearestDistances := CalculateLookupTableKeysAndValues [
    t1[[line]["Point_Id"]]
] [
    t1[[line]["Nearest_Distance"]]
] "Point_Id" "Nearest_Distance" pointKeys {{
    // t1
    NumberTable nearestPoints 1;
}};

Side-by-side comparison

The following example illustrates how the two forms look on a realistic expression involving multiple map operands, a value operand, a neighbourhood function, and the ? error-catch operator.

Verbose form:

// Restore the noisy cells marked for restoration. The replacement value is
// derived from a window that grows with the current time step.
updatedRestoredImage := CalculateMap [
    if i1 = 2 then
        nbMedian(i2, v1, v1) ? i3
    else
        i3
] cellType nullValue .no .none {{
    NumberMap  arePixelsOriginalOrNoisyWithCategories 1;
    NumberMap  originalPixelsOnlyInRestoredImage     2;
    NumberMap  currentRestoredImage                  3;
    NumberValue lK                                   1;
}};

Shorthand form:

// Restore the noisy cells marked for restoration. The replacement value is
// derived from a window that grows with the current time step.
updatedRestoredImage := # [
    if #arePixelsOriginalOrNoisyWithCategories = 2 then
        nbMedian(#originalPixelsOnlyInRestoredImage, $lK, $lK) ? #currentRestoredImage
    else
        #currentRestoredImage
] cellType nullValue .no .none;

In the verbose form the three maps arrive as i1, i2, i3 and the value as v1, each supplied by a hook in the trailing block. In the abbreviated form the same operands are referenced directly by their variable names — #arePixelsOriginalOrNoisyWithCategories, #originalPixelsOnlyInRestoredImage, #currentRestoredImage, and $lK — with the trailing block omitted entirely.


Comments

A single-line comment begins with // and runs to the end of the line:

// This is a single-line comment.

A multi-line comment is surrounded by /:

/* This is a multi-line
comment */

The two styles differ in one important way:

Note: Multi-line comments are not preserved when a model is opened in the graphical interface, but single-line comments are. Because of this, a multi-line comment is usually better written as consecutive // lines:
// This is a multi-line
// comment

A comment placed immediately before a functor becomes that functor's comment property (see Properties). A comment placed before the Script keyword becomes the model's title (metadata.title).

Brief and extended comments

When a // comment is parsed, the line === splits it into two separate properties: the text before === becomes the functor's comment (the brief comment), and the text after it becomes its extendedcomment (the extended comment):

// Generate the initial seed.
//
// ===
// Living cells are represented by 1 and dead cells by 0.

Here Generate the initial seed. is stored as the comment property and Living cells are represented by 1 and dead cells by 0. as the extendedcomment property. In the graphical interface, the comment is displayed directly on the functor's visual node; the extendedcomment appears only in the tooltip shown when hovering over the node.


Properties

A property annotates a functor (or the model as a whole) with metadata. Properties do not change what a model computes; they affect how it is labeled, displayed, and organized in the visual editor, and they carry documentation.

A property is written immediately before the functor it applies to. There are two equivalent syntaxes — the @ form and the comment form:

@name = value
/** name = value */

A property name must start with a letter or _, followed by letters, _, and .. A value may contain any characters, including blanks; a value that spans line breaks must be surrounded by double quotes:

@alias = Largest Patch Area
@collapsed = yes
@notes = "The model input is a map where the non-null values identify the patches.

The output is a table containing the largest patch index per category."

Internally each property has a fully qualified name (such as dff.functor.alias), but many are read and written in a short form that drops the qualified prefix. Writing the @shortName = value form forces the short name to expand to its full property name.

Functor properties

The per-functor properties you will see most often are:

Short form Qualified name Effect
alias dff.functor.alias A human-readable name shown for the functor in the GUI in place of its variable name. When saving, the alias is used to derive the variable name. When loading, the variable name is used to reconstruct the alias. See Alias and variable name conversion below.
color dff.functor.color A background color for the functor's node, as a hex code such as #ccffcc. Useful to visually differentiate or group related functors and groups.
inline dff.functor.inline When set, prevents the functor from being inlined when the script is written. Any other property defined on the functor (a comment, alias, etc.) has the same effect automatically, since an inlined functor has no separate node to preserve that information. Values: yes/no or true/false.
comment dff.functor.comment The functor's brief comment — the text before === in a // comment (see Comments).
extendedcomment dff.functor.extendedcomment The functor's extended comment — the text after === in a // comment (see Comments).
collapsed dff.container.collapsed Indicates that a container is drawn closed (its contents hidden) in the graphical interface. Applies to containers only. Values: yes/no or true/false.
Note: A few per-functor properties exist only while a model is open in the editor and are never written to the saved model: dff.functor.text, dff.functor.file, dff.functor.line, and dff.functor.column.

Alias and variable name conversion

The GUI and the script use two directions of conversion between an alias and a variable name.

Saving (alias → variable name): When the GUI writes a script, it derives the variable name from the alias by splitting the alias into words — using spaces, underscores, and lowercase-to-uppercase transitions (CamelCase) as word boundaries — then recombining them as a valid identifier. Leading and trailing spaces or underscores are ignored. Non-alphanumeric characters other than underscores are ignored entirely. The result starts with a lowercase letter.

Alias Variable name
Initial Landscape initialLandscape
initial_landscape initialLandscape
Deforestation Rate (%/yr) deforestationRateYr
WOfE Probability Map wOfEProbabilityMap
_Slope_ slope

If two or more functors produce the same variable name from their aliases, a number is appended to disambiguate: the first functor keeps the base name, subsequent ones become name2, name3, and so on.

If the conversion alias → variable → alias does not round-trip back to the same original alias — for example because non-alphanumeric characters were discarded — the GUI explicitly writes the @alias property in the saved script to preserve the original alias without loss of information. In such cases you will see an explicit @alias = … annotation even though the functor's variable name is present.

Loading (variable name → alias): When a script is read back into the GUI and a functor has no explicit @alias property, the alias is reconstructed from the variable name using the following rules:

  • The first letter is converted to uppercase.
  • A space is inserted at every lowercase-to-uppercase transition.
  • A space is inserted at every letter-to-digit and digit-to-letter transition.
  • Sequences of consecutive uppercase letters are treated as a single word — no space is inserted within them.
  • Leading and trailing underscores are discarded.
  • Internal underscores (and sequences of multiple underscores) are converted to a single space.
Variable name Reconstructed alias
initialLandscape Initial Landscape
distance_to_deforested Distance To Deforested
calcURL Calc URL
map2Region Map 2 Region
saddleHeight2 Saddle Height 2

Model-level metadata

A separate group of properties describes the model as a whole rather than any single functor. These also use a short form, dropping the metadata. (or dff.) prefix:

Short form Qualified name Describes
title metadata.title The model's title.
author metadata.author The model's author.
organization metadata.organization The author's organization.
description metadata.description A description of what the model does.
keywords metadata.keywords Search keywords for the model.
notes metadata.notes Free-form notes about the model.
showproperties metadata.showproperties Whether the property window opens when the model is opened. Values: yes/no or true/false.
metaversion metadata.version The model's metadata version.
date dff.date The date the model was last written.
version dff.version The version of Dinamica EGO that last updated the model.
Note: description is model-level metadata; it is not a property of an individual functor.

Submodels expose their own inputs and outputs to callers through a further set of properties, such as @submodel.in.constant.name and @submodel.out.result.name. These are covered in the section on building submodels.


Script generation options

When the GUI saves a script or generates an EGO Script fragment, a set of options controls how the output is formatted. These are found under ToolsOptions | EGO Script:

Option Description
Minimum number of functor inputs to use named parameters Below this threshold, inputs are written in positional syntax; at or above it, nominal (named parameter) syntax is used instead.
Inline any suitable functor When enabled, eligible functors are written inline rather than as separate named definitions.
Inline suitable functors using named parameters When enabled, functors are eligible for inlining even if their inputs would be written using nominal syntax.
Also inline: Suitable containers Extends inlining to container functors that qualify.
Also inline: Suitable muxes Extends inlining to mux functors that qualify.
Also inline: Suitable functors bound to feedback inputs Extends inlining to functors whose output feeds back into a loop's mux.
Use abbreviated syntax for Calculate family functors Whether the Calculate family is written using the shorthand symbol (#, ##, %, etc.) or the full functor name. See the Calculator functor shorthand section for details.
Preferred number of columns before wrapping comments The line width at which the generator wraps long comment text.

A note on ''CalcAreas''

CalcAreas returns a single output, areas, of type Table. The table has a key column Category and the data columns Area_In_Cells, Area_In_Hectares, and Area_In_Square_Meters, so one call yields every area measure for every category at once. A common mistake is to treat the output as if it were a single hectares figure; it is a table. To work with one measure, read the corresponding column from it:

areaTable := CalcAreas landscape .no;
// the Area_In_Hectares column
hectaresColumn := GetTableColumn areaTable 3;