Class: helper

Helper functions ABE Library

The library provides a number of helper functions.

Building STPs

The library provides functions to simplify the construction of Stand treatment programs.

  • lib.createSTP: takes one or several activites and creates a STP with a given name

Introspection

  • use formattedLog() and formattedSTP() for a detailed look into past and plant activitites

Miscallaneous

  • Logging: use log() and dbg() functions and lib.logevel to control the amount of log information
  • Activity log: use activityLog() (internally) to add to the stand-level log data

Internals

  • lib.mergeOptions: help with global / local settings
  • lib.selectOptimalPatches: compare patches and select the best based on a criterion

Useful activites

  • changeSTP: set follow-up STP when the current STP ends
  • repeater: simple activity to repeatedly run a single JS function / activity

Methods Overview

Method Return Type Description
CheckManagementOfStands() void Sanity check for all stands, if they have a STP.
activityLog() void Management history
buildProgram() void Library function to build a full iLand STP from a collection of elements.
buildRareSpeciesFilter(threshold) void Constructs a iLand expression for filtering trees based on the proportion of target species in the stand.
changeSTP(options) object Switches the active Stand Treatment Program (STP) for a stand.
createSTP() void Main library function to create stand treatment programs in iLand.
dbg() void Internal debug function to log a string str to the iLand logfile.
formattedLog() void returns the activity log for the currently active stand as formatted HTML.
formattedSTP() void returns a readable description of the current STP as formatted HTML.
getAllStandGridIds() void Helper function to get a list of all unique stand ids from the standGrid.
initAllStands() void Initializes all stands of the current simulation (initStandObj()).
initStandObj() void Initializes the stand.obj Javascript object for the current stand (stand.id).
log() void Internal function to log a string str to the iLand logfile.
mergeOptions() void Helper function to combine deafult options and user-provided options for activities.
repeater(options) object Creates a repeater activity that repeatedly triggers a specified signal.
selectOptimalPatches(options) object Selects optimal patches based on a given criterion.

Methods Details

CheckManagementOfStands()

Returns: void

Sanity check for all stands, if they have a STP.


activityLog()

Returns: void

Management history

Stands store a activity log, also used for DNN training.
`activityLog` is the internal function to populate the management history. The `extraValues` is
any value that can be defined by the activity itself.

See also: TODO: write management history, activityLog()


buildProgram()

Returns: void

Library function to build a full iLand STP from a collection of elements.

The function takes one or multiple elements that are typically Javascript objects to define iLand activities. These Javascript objects typically are returnd by library functions; for example, the library function lib.thinning.tending() returns (one or more) definitions of iLand activities. buildProgram combines multiple elements to a single Javascript object. Note that this function does not intitalize iLand activities - it merely operates on Javascript objects. Use createSTP to actually create a stand treatment program in iLand!

Example:

//
      const StructureThinning = lib.thinning.selectiveThinning({mode = 'dynamic'});
      const StructureHarvest = lib.harvest.targetDBH({dbhList = {"fasy":65,   //source: 'Waldbau auf ökologischer Grundlage', p.452
           "frex":60, "piab":45, "quro":75, "pisy":45, "lade":65,
           "qupe":75, "psme":65, "abal":45, "acps":60, "pini":45}});

       const stp = lib.buildProgram(StructureThinning, StructureHarvest);
       // you can still modify the program, e.g, by adding activities!
       stp['a_new_activity'] = { type: 'general', schedule: .... };



   @param concepts one or multiple concepts, typically the result of calls to library function
   @return object a definitions of multiple activities combined in a single object
   @method buildProgram

buildRareSpeciesFilter(threshold)

Returns: void

Constructs a iLand expression for filtering trees based on the proportion of target species in the stand. When the relative basal area of all target species combined is below threshold, then trees of these species are filtered out. The chance of being filtered out declines linearly up to 2x threshold, above no trees are filtered. The species list can be provided in multiple formats.

Parameters:

  • threshold (number): The relative basal area threshold (0..1) for filtering.

changeSTP(options)

Returns: object

Switches the active Stand Treatment Program (STP) for a stand.

This function allows you to dynamically change the STP that is being applied to a stand during a simulation. It’s particularly useful for implementing adaptive management strategies or scenarios where different management regimes should be applied based on specific conditions or triggers.

Parameters:

  • options (object): Options for configuring the STP change. @param {string} options.STP The name of the STP to switch to. This STP must already be defined in the iLand project. @param {object} options.schedule Schedule object for triggering the STP change (default: { signal: ‘end’ }). @param {string} options.id A unique identifier for the activity (default: ‘change_stp’).

Return Value Description: act - An object describing the STP change activity.

Example:

// Switch to the 'harvest_STP' when the 'start' signal is received.
  lib.changeSTP({
      STP: 'harvest_STP',
      schedule: { signal: 'start' }
  });

  // Switch to 'passive_STP' after 100 years.
   lib.changeSTP({
      STP: 'passive_STP',
      schedule: { absolute: true, opt: 100}
  });

createSTP()

Returns: void

Main library function to create stand treatment programs in iLand.

The function takes one or multiple elements that are typically Javascript objects to define iLand activities, combines them, and creates a STP in iLand. If the STP already exists, it updates the existing STP (using fmengine.updateManagement), and creates a new stp otherwise (using fmengine.addManagement).

See also: buildProgram(),updateManagement()

Example:

//
      const StructureThinning = lib.thinning.selectiveThinning({mode = 'dynamic'});
      const StructureHarvest = lib.harvest.targetDBH({dbhList = {"fasy":65,   //source: 'Waldbau auf ökologischer Grundlage', p.452
           "frex":60, "piab":45, "quro":75, "pisy":45, "lade":65,
           "qupe":75, "psme":65, "abal":45, "acps":60, "pini":45}});

       lib.createSTP('my_structure_stp',StructureThinning, StructureHarvest);

   @param stp_name {string} name of the stand treatment program
   @param concepts one or multiple concepts, typically the result of calls to library function
   @method createSTP

dbg()

Returns: void

Internal debug function to log a string str to the iLand logfile. You can control the amount of log messages by setting lib.loglevel to the following values: * 0: None - no messages from abe-library * 1: Normal - limited amount of messages from the library, usually only high level * 2: Debug - high number of log messages. Use for debugging and not in productive model applications.

See also: lib.dbg()


formattedLog()

Returns: void

returns the activity log for the currently active stand as formatted HTML.

Example:

// show the log for stand 13 in a popup window
     fmengine.standId = 13;
     Globals.alert( lib.formattedLog() );

formattedSTP()

Returns: void

returns a readable description of the current STP as formatted HTML.

The description is a list of activites of the STP that is assigned the currently active stand. Items are greyed out if they have already been run in the current rotation, provide the planned year and a detailed descriptions (as provdied by the library functions)

Example:

// show the log for stand 13 in a popup window
     fmengine.standId = 13;
     Globals.alert( lib.formattedSTP() );

getAllStandGridIds()

Returns: void

Helper function to get a list of all unique stand ids from the standGrid.


initAllStands()

Returns: void

Initializes all stands of the current simulation (initStandObj()).


initStandObj()

Returns: void

Initializes the stand.obj Javascript object for the current stand (stand.id).


log()

Returns: void

Internal function to log a string str to the iLand logfile. You can control the amount of log messages by setting lib.loglevel to the following values: * 0: None - no messages from abe-library * 1: Normal - limited amount of messages from the library, usually only high level * 2: Debug - high number of log messages. Use for debugging and not in productive model applications.

See also: lib.dbg()

Example:

// set log level (e.g. in iLand Javascript console or in your code) after loading the library
     lib.loglevel = 2; //debug!
     ...
     // somewhere in library code: running the function now produces log messages
     lib.dbg(`selectiveThinning: repeat ${stand.obj.lib.selective_thinning_counter}, removed ${harvested} trees.`);


 @param str {String} string to log
 @method log

mergeOptions()

Returns: void

Helper function to combine deafult options and user-provided options for activities.

The function throws an error when options include values not defined in defaults. You should therefore define all potential keys that can be used by the user with value undefined!

Example:

// pattern
     const default_options = { schedule: undefined, intensity: 10 };
     // create an object with combined options (even if not provided)
     const opts = lib.mergeOptions(defaultOptions, options || {});
     // ...


   @param defaults object containing default values
   @param options object user-defined options
   @return object that contains default values updated with user-provided options
   @method mergeOptions

repeater(options)

Returns: object

Creates a repeater activity that repeatedly triggers a specified signal.

This function is useful for creating activities that need to be executed multiple times at regular intervals, such as repeated thinnings or harvests. The repeater can be configured to trigger based on a schedule or a signal, and it can optionally block other activities until it has finished.

Parameters:

  • options (object): Options for configuring the repeater. @param {object} options.schedule Schedule object for starting the repeater. @param {string} options.id A unique identifier for the repeater activity (default: ‘repeater’). @param {number} options.count Number of times to repeat the signal (default: undefined). @param {number} options.interval Interval (in years) between repetitions (default: 1). @param {string} options.signal Name of the signal to emit at each repetition. @param {boolean} options.block Whether the repeater should block other activities until it finishes (default: true). @param {function|undefined} options.parameter Function to provide the signal parameter when the signal is emitted (default: undefined).

Return Value Description: act - An object describing the repeater activity.

Example:

// Repeat the 'thinning' signal 5 times every 10 years, starting in year 50.
  lib.repeater({
      schedule: { start: 50 },
      count: 5,
      interval: 10,
      signal: 'thinning'
  });

  // Repeat the 'harvest' signal 3 times every 2 years, triggered by the 'ready_for_harvest' signal,
  // and provide a custom parameter to the signal.
  lib.repeater({
      schedule: { signal: 'ready_for_harvest' },
      count: 3,
      interval: 2,
      signal: 'harvest',
      parameter: function() {
          // Example: Return the current stand's basal area as the parameter.
          return stand.basalArea();
      }
  });

selectOptimalPatches(options)

Returns: object

Selects optimal patches based on a given criterion.

This function helps with selecting the best patches in a stand based on a specified criterion (e.g., light availability, basal area) or a custom function. It’s useful for setting up spatially explicit management activities like creating gaps or targeting specific areas within a stand for treatments.

Parameters:

  • options (object): Options for configuring the patch selection. @param {string} options.id A unique identifier for the activity (default: ‘selectOptimalPatches’). @param {number} options.N Number of patches to select per hectare (default: 4). @param {number} options.patchsize Size of the patches (in cells, assuming a square shape, e.g., 2 for 2x2 cells, which is 20x20m or 400m2) (default: 2). @param {number} options.spacing Space (in 10m cells) between candidate patches (default: 0). @param {string} options.criterium Criterion for selecting patches (‘max_light’, ‘min_light’, or ‘min_basalarea’) (default: ‘max_light’). @param {function|undefined} options.customFun Custom function for evaluating patches. This function should take a patch object as input and return a score (default: undefined). @param {number} options.patchId ID to assign to the selected patches (default: 1). @param {string} options.sendSignal Optional: Signal that should be send after selecting patches (default: undefined). @param {object} options.schedule Schedule object for triggering the patch selection (default: { signal: ‘start’ }).

Return Value Description: act - An object describing the patch selection activity.

Example:

// Select 5 patches per hectare based on maximum light availability, using 3x3 patches.
    lib.selectOptimalPatches({
        N: 5,
        patchsize: 3,
        criterium: 'max_light'
    });

    // Select 2 patches per hectare based on a custom evaluation function.
    lib.selectOptimalPatches({
        N: 2,
        customFun: function(patch) {
            // Example: Score based on proximity to a specific location
            const targetX = 50;
            const targetY = 50;
            const distance = Math.sqrt(Math.pow(patch.x - targetX, 2) + Math.pow(patch.y - targetY, 2));
            return 1 / distance; // Higher score for closer patches
        }
    });