Class ScenarioDescription

java.lang.Object
ca.spatial.patchworks.ScenarioDescription
All Implemented Interfaces:
Selectable<ScenarioDescription>, Comparable<ScenarioDescription>

public class ScenarioDescription extends Object implements Comparable<ScenarioDescription>, Selectable<ScenarioDescription>
This class implements the description of a scenario to be added to the ScenarioSet. The scenario description records the scenario name, a description of its purpose, a list of TargetDescription objects that characterize the parameters of the scenario, and other runtime parameters.

ScenarioDescription objects may be used as stand-alone objects, but most often they are used as components of a ScenarioSet, and in most cases ScenarioDescription objects are created by adding values to an existing ScenarioSet. For example,

 s = new ScenarioSet(improve, iterations, checkPointCount, makeZip,
                     subtargetPrefix, subtargetImprove, factory);

 s.addScenario("scenarios/C5_Spatial2",
               "The Spatial2 builds on Spatial1 and adds harvest patches.",
               new TargetDescription[] {useVQO(1e12, true), 
                                        ndyGS(10000,0,true),  
                                        noDisturbancePatch, 
                                        harvestPatches(0.0001,true),
                                        deliveredHarvest(1,true),
                                        evenFlowMill(1000, true),
                                        roadBudget(1,true),
                                        useCompartAccess}
              );
 
In the above code a ScenarioSet is created with a set of default runtime parameters. A scenario is added specifying a name label, a title, and a set of TargetDescription objects that describe target settings. All other required parameters for the ScenarioDescription are inherited from the ScenarioSet defaults.

The essential parameters to a ScenarioDescription are the name label and the array of TargetDescription objects. The name label is used as the folder name when the scenario results are saved out. The TargetDescription objects describe model pre-conditions, the targets to be activated and the target values to be set. See the TargetDescription documentation for more information about creating and using TargetDescription objects.

Scenarios have several modes of operation. The default activity is ScenarioDescription.Activity.SOLVE, but this may be overriden with the setActivity(ca.spatial.patchworks.ScenarioDescription.Activity) method. The ScenarioDescription.Activity.SOLVE mode which starts from the initial condition, applies all targets, cues the ScenarioChangeListener tp deactivate flow targets for the initial iterations, iterates until convergence, and saves out results. See the ScenarioDescription.Activity class for a description of each available mode.

The ScenarioDescription class uses a fluent interface for customization. Methods may be chained together to modify default values and to set values that are not otherwise available using the convenience methods. For example,

 s.addScenario("scenarios/C5_Spatial2",
               "The Spatial2 builds on Spatial1 and adds harvest patches.",
               new TargetDescription[] {useVQO(1e12, true), 
                                        ndyGS(10000,0,true),  
                                        noDisturbancePatch, 
                                        harvestPatches(0.0001,true),
                                        deliveredHarvest(1,true),
                                        evenFlowMill(1000, true),
                                        roadBudget(1,true),
                                        useCompartAccess}
              ).setIterations(300000)
               .setImprovement(0.001)
               .setActivity(ScenarioDescription.Activity.CONTINUE);
 
will add a scenario to the ScenarioSet, and will override the iteration, improvement values and activity values.

When run under the supervision of a ScenarioSet a scenario can be initialized with target values, run until the specified convergence criteria are met, and the report values are saved out. An optional ScenarioChangeListener object can be used to apply more precise control over the scenario life cycle. A scenario specific argument may be attached to a ScenarioDescription using the setUserArg(java.lang.Object) method. This value may be retrieved by the ScenarioChangeListener using the getUserArg() method. The value of this argument may be any object reference, such as a String or an array of other objects. See the ScenarioChangeListener documentation for an example of how this may be used.

See Also:
ScenarioSet, TargetDescription, ScenarioChangeListener
  • Constructor Details

    • ScenarioDescription

      public ScenarioDescription(String label, String description, TargetDescription[] targets, ScenarioDescription.Activity activity, double improve, int iterations, int checkpointCount, boolean makeZipfile, ConvergenceSpec[] specs, ChangeListenerFactory factory)
      Create this scenario with the specified parameters.
      Parameters:
      label - The name to be given to this scenario.
      description - Text that describes the purpose of the scenario. This text will be recorded as meta-data.
      targets - A list of targets that should be applied to this scenario.
      activity - An ScenarioDescription.Activity code to indicate the default treatment for this scenario.
      improve - A double value that specifies the convergance criteria. The value will be tested against the percent decrease in the objective function. If the amount of decrease is less than the convergence criteria then the simulation will stop.
      iterations - An integer that specifies the number of iterations to run before checking the convergence criteria.
      checkpointCount - An integer that specifies the number of iterations to pass before saving the scenario data files. This will periodically save out the files so that the program may be restarted from a partial solution. This can guard against catastrohic loss from a power failure or network outage during very long running simulations. The checkpoint count is only checked when the convergence criteria is tested, so this value should be a mutiple of the iterations parameter.
      makeZipfile - A boolean that specifies if the reports should automatically be saved together into a ZIP file.
      specs - An array of ConvergenceSpec
      factory - A reference to a ChangeListenerFactory object that will be called when convergence is being tested.
  • Method Details

    • runScenario

      public void runScenario() throws InterruptedException
      Run this scenario. The set of operations that take place depend on the value of the activity code (see setActivity(ca.spatial.patchworks.ScenarioDescription.Activity)). If the iteration count is set to zero then the scenario will not run, and the reports will be immediately saved.
      Throws:
      InterruptedException
    • runScenario

      public void runScenario(ScenarioDescription.Activity activity) throws InterruptedException
      Run this scenario using the operations implied by the ScenarioDescription.Activity code..
      Throws:
      InterruptedException
    • analyzeWithListener

      public void analyzeWithListener(ScenarioChangeListener sdc, boolean wait) throws InterruptedException
      Start the scheduler and run until convergence. Use the provided listener object to react to life cycle events. If the ScenarioChangeListener object is null then life cycle events will not be dispatched.
      Parameters:
      sdc - A reference to a ScenarioChangeListener object to handle life cycle events. May be null in which case life cycle events are ignored.
      wait - Indicate if the scenario manager should wait and not return until the scenario is complete. If the flag is true, then do not return until the scenario is over. If false, then return immediately.
      Throws:
      InterruptedException
    • analyze

      public void analyze(ChangeListenerFactory factory, boolean wait) throws InterruptedException
      Start the scheduler and run until convergence. If a factory has been provided then create and set a custom listener object. The custom listener object will be called by the ScenarioDescription.DefaultScenarioChangeListener at the appropriate times.
      Parameters:
      factory - A reference to a ChangeListenerFactory object. This object will be used to create a listener to handle life cycle events. May be null in which case no custom life cycle event handler will be added, and only the ScenarioDescription.DefaultScenarioChangeListener processing will occur.
      wait - Indicate if the scenario manager should wait and not return until the scenario is complete. If the flag is true, then do not return until the scenario is over. If false, then return immediately.
      Throws:
      InterruptedException
    • reloadScenario

      public void reloadScenario(boolean ignoreWarnings)
      Reload all of the files in a saved scenario
      Parameters:
      ignoreWarnings - to ignore warnings about missing files and continue loading what is available.
    • makeZip

      public void makeZip()
      Pack up a zip file from the reports saved from this scenario. The reports must already be saved for this to work.
    • activateCategory

      public void activateCategory(String regex)
      Call TargetDescription.activate(java.lang.Object) with a value of true for each of the TargetDescription objects that have category values that match to the regular expression string. For example, the following activates TargetDescriptions that contain "Flow" or "Patch" in the category name.
       sd.activateCategory(".*(Flow|Patch).*");
       
      Parameters:
      regex - the regular expression string to use to determine the TargetDescription objects to activate.
      See Also:
      String.matches(java.lang.String)
    • deactivateCategory

      public TargetDescription[] deactivateCategory(String regex)
      Call TargetDescription.deactivate(java.lang.Object) with a value of false for each of the TargetDescription objects that have category values that match to the regular expression string. For example, the following activates TargetDescriptions that contain "Flow" or "Patch" in the category name.
       sd.deactivateCategory(".*(Flow|Patch).*");
       
      Parameters:
      regex - the regular expression string to use to determine the TargetDescription objects to deactivate.
      See Also:
      String.matches(java.lang.String)
    • activate

      public static void activate(TargetDescription[] targetDescriptions)
      Call TargetDescription.activate(java.lang.Object) with a value of true for each of the TargetDecription objects in the list.
      Parameters:
      targetDescriptions - the array of TargetDescription objects to activate.
    • activateAccount

      public static void activateAccount(String regex)
      Call Target.setActive(boolean) with a value of true for each of the Target objects that have account names that match to the regular expression string. For example, the following activates targets having names that start with "patch" or "ratio".
       sd.activateAccount("^(patch|ratio).*");
       
      Parameters:
      regex - the regular expression string to use to determine the Target objects to activate.
      See Also:
      String.matches(java.lang.String)
    • activate

      public static void activate(Target[] targets)
      Call Target.setActive(boolean) with a value of true for each of the Target objects that are in the targets array.

      For example, the following deactivates targets having names that start with "patch" or "ratio" and collects the selected targets int the savedTargets array. After some intermediate processing steps these targets are then reactivated using the activateAccounts method.

       savedTargets = sd.deactivateTarget("^(patch|ratio).*");
       // other processing steps...
      
       // and later on...
       sd.activate(savedTargets);
       
      Parameters:
      targets - an array of references for the Targets objects that are to be activated.
    • deactivateAccount

      public static Target[] deactivateAccount(String regex)
      Call Target.setActive(boolean) with a value of false for each of the Target objects that have account names that match to the regular expression string and are currently acitve. For example, the following deactivates targets having names that start with "patch" or "ratio".
       savedTargets = sd.deactivateAccount("^(patch|ratio).*");
       

      This method returns an array of references to the Target objects that have been deactivated. This list will only include targets with matching names that were active when the deactivate command was run.

      To reactivate the array of Targets that is returned from this method use the activate(Target[]) method.

      Parameters:
      regex - the regular expression string to use to determine the Target objects to deactivate.
      Returns:
      an array of the targets that were deactivated (names matched and were active).
      See Also:
      String.matches(java.lang.String)
    • isSelected

      public boolean isSelected()
      A flag that indicates if this scenario is selected for execution.
      Specified by:
      isSelected in interface Selectable<ScenarioDescription>
    • setSelected

      public ScenarioDescription setSelected(boolean mode)
      Set a flag to indicate that this scenario is selected for execution.
      Specified by:
      setSelected in interface Selectable<ScenarioDescription>
    • getLabel

      public String getLabel()
      The name of the scenario
    • getTargets

      public TargetDescription[] getTargets()
      Get a list of target description objects that will be applied when this scenario is run.
    • getDescription

      public String getDescription()
      Return the descriptive text for this scenario.
    • getImprovement

      public double getImprovement()
      The value of the objective function convergence criteria
    • setImprovement

      public ScenarioDescription setImprovement(double improve)
      Set the value of the objective function convergence criteria. If the value is set to a negative number then stop the simulation after the number of viable iterations has met the iteration count. If the improvement count is less than zero then the ScenarioChangeListener.evaluateBefore() and ScenarioChangeListener.evaluateAfter(boolean, ca.spatial.patchworks.ScenarioMonitor) life cycle routines will not be invoked.
    • getUserArg

      public Object getUserArg()
      Get the value of the userArg. This is an arbitrary object that can be specified for each description
    • setUserArg

      public ScenarioDescription setUserArg(Object userArg)
      Set the value of the userArg. This is an arbitrary object that can be specified for each description.
      Parameters:
      userArg - Any arbirary object reference. This value may subsequently be retrieved and used within the ScenarioChangeListener or elsewhere.
      Returns:
      A reference to the ScenarioDescription object.
    • printMessage

      public void printMessage(String message)
    • printError

      public void printError(String message)
    • getActivity

      public ScenarioDescription.Activity getActivity()
      Get the default setting of the ScenarioDescription.Activity code for this scenario.
    • setActivity

      public ScenarioDescription setActivity(ScenarioDescription.Activity activity)
      Parameters:
      activity - the activity that should be run
    • getCancelBefore

      public boolean getCancelBefore()
    • setCancelBefore

      public ScenarioDescription setCancelBefore(boolean mode)
      Set a flag to indicate if the current set of treatments should be cancelled before the simulation is started.
      Parameters:
      mode - If the mode value is true, then all scheduled treatments are cancelled before the simulation is started.
    • getIterations

      public int getIterations()
      A count of the number of iterations that should occur before the objective function is tested against the convergence criteria.
    • setIterations

      public ScenarioDescription setIterations(int count)
      Set the number of iterations that should occur before the objective function is tested against the convergence criteria.
    • getCheckpointCount

      public int getCheckpointCount()
      Get the number of iterations that should occur between saving the simulation state data. Checkpoints will save the simulation data so that the model can be restarted from the save point. This can save time if the simulation is interrupted (for example, due to a power failure).
    • setCheckpointCount

      public ScenarioDescription setCheckpointCount(int count)
      Get the number of iterations that should occur between saving the simulation state data.
    • getMakeZipFile

      public boolean getMakeZipFile()
      A flag to indicate if the simulation results should be archived into a zip file after the simulation has completed.
    • setMakeZipFile

      public ScenarioDescription setMakeZipFile(boolean mode)
      Set a flag to indicate if the simulation results should be archived into a zip file after the simulation has completed.
    • setChangeListenerFactory

      public ScenarioDescription setChangeListenerFactory(ChangeListenerFactory factory)
      Set a ScenarioChangeListener that will be used to control the simulation environment when the runScenario() method is called.
    • getChangeListenerFactory

      public ChangeListenerFactory getChangeListenerFactory()
    • makeCriteria

      public static ConvergenceSpec[] makeCriteria(String[] patterns, double[] values)
      Set the extended convergence criteria to be used for this scenario. Each of the strings in the patterns array represent a regular expression that will be matched against target names. If this array is non-null, then the convergence testing mechanism will perform an extended analysis. Each target is matched against the patterns, and the change in value from one sampling point to the next is measured. The sum of change for each pattern is expressed as a percent, and compared to the corresponding number in the values array. If the amount of chage is greater than the value then the convergence criteria is not satisfied.
      Parameters:
      patterns - An array of regular expression strings that will be matched against target names.
      values - An array of convergence criteria values.
    • setCriteria

      public ScenarioDescription setCriteria(ConvergenceSpec[] specs)
    • getCriteria

      public ConvergenceSpec[] getCriteria()
    • applyTargets

      public String applyTargets()
      Apply the list of targets.
    • getTargetForCategory

      public TargetDescription getTargetForCategory(String cat)
    • clearTargets

      public static void clearTargets()
      Clear all targets.
    • compareTo

      public int compareTo(ScenarioDescription o)
      Determine the sorting order of scenario descriptions. The rule is to sort in the order that scenarios are added to the set.
      Specified by:
      compareTo in interface Comparable<ScenarioDescription>
    • canSave

      public boolean canSave()
      Check if the scenario can be saved to the specified location
    • toString

      public String toString()
      Overrides:
      toString in class Object