Class FWSimVarMap

java.lang.Object
net.simplace.sim.util.FWSimVarMap
All Implemented Interfaces:
org.apache.commons.jexl3.JexlContext

public class FWSimVarMap extends Object implements org.apache.commons.jexl3.JexlContext
The variable map of a simulation: holds all FWSimVariables of a simulation, keyed by name, together with the system variables (current date, year, day of year, project and simulation id, spin-up settings, ...).

The var map is also the context in which rules are evaluated (JexlContext), and provides methods to replace parameter tokens like ${name} in strings. Values are read via getValue or the force...Value methods, which convert values of other data types.

When variables are linked, units, data types and content types can be checked; when values are set, data type, source and limits are checked according to the check level of the session.

Author:
Andreas Enders
  • Field Details

    • CURRENT_DATE

      public static final String CURRENT_DATE
      signifying the string used as id for the current date in the VarMap
      See Also:
    • CURRENT_YEAR

      public static final String CURRENT_YEAR
      signifying the string used as id for the current year in the VarMap
      See Also:
    • CURRENT_DAY

      public static final String CURRENT_DAY
      signifying the string used as id for the current day of month
      See Also:
    • CURRENT_MONTH

      public static final String CURRENT_MONTH
      signifying the string used as id for the current month in the VarMap
      See Also:
    • CURRENT_DOY

      public static final String CURRENT_DOY
      signifying the string used as id for the current day of year
      See Also:
    • PROJECT_ID

      public static final String PROJECT_ID
      id of the variable holding the current project id
      See Also:
    • PROJECT_ITERATION

      public static final String PROJECT_ITERATION
      id of the variable holding the iteration number of the project
      See Also:
    • SIMULATION_ID

      public static final String SIMULATION_ID
      id of the variable holding the current simulation id
      See Also:
    • SIMULATION_NAME

      public static final String SIMULATION_NAME
      id of the variable holding the name of the current simulation
      See Also:
    • SIMULATION_NUMBER

      public static final String SIMULATION_NUMBER
      id of the variable holding the number of the current simulation
      See Also:
    • SESSION_ID

      public static final String SESSION_ID
      id of the variable holding the id of the current session
      See Also:
    • SPINUP_DAYS

      public static final String SPINUP_DAYS
      signifying the integer number of spin up days in the VarMap
      See Also:
    • SPINUP_DO_RESET

      public static final String SPINUP_DO_RESET
      signifying whether date has to be reset after spinup
      See Also:
    • SPINUP_RESET

      public static final String SPINUP_RESET
      signifying whether date was reset after spinup
      See Also:
    • SPINUP_ACTIVE

      public static final String SPINUP_ACTIVE
      signifying whether the simulation is in the spin-up period (true) or not (false); can be written as output column of outputs with spinup="true", whose spin-up lines may repeat the dates of the run
      See Also:
    • SYNCHRONIZE_FREQUENCE

      public static final String SYNCHRONIZE_FREQUENCE
      signifying whether threads are synchronized within one project (true) or not (false)
      See Also:
    • SYNCHRONIZE_RULE

      public static final String SYNCHRONIZE_RULE
      the rule for the data synchronized within one project if FREQUENCE is COMPLEX
      See Also:
    • PROJECT_LINES

      public static final String PROJECT_LINES
      projectlines that are read from project file
      See Also:
    • SIMULATIONS_SELECTED

      public static final String SIMULATIONS_SELECTED
      id of the variable holding the selected simulations of the current iteration
      See Also:
    • END_DATE

      public static final String END_DATE
      id of the variable holding the end date of the simulation
      See Also:
    • START_DATE

      public static final String START_DATE
      id of the variable holding the start date of the simulation
      See Also:
    • DATE_FORMAT

      public static final DateTimeFormatter DATE_FORMAT
      Default date format dd.MM.yyyy
    • COMPARATOR

      public static Comparator<FWSimVariable<?>> COMPARATOR
      Compares variables by name
  • Constructor Details

    • FWSimVarMap

      public FWSimVarMap(HashMap<String, FWSimVariable<?>> aFormInputParameterMap, FWSimModel aModel, String aProjectID, FWSimSession aCurrentSession)
      Creates the var map of a simulation and adds the system variables.
      Parameters:
      aFormInputParameterMap - the variables of the simulation, keyed by name; used directly, not copied
      aModel - the model (simulation) the var map belongs to
      aProjectID - id of the current project
      aCurrentSession - the current session
    • FWSimVarMap

      public FWSimVarMap(HashMap<String, FWSimVariable<?>> aParameterMap)
      Creates a var map without session, e.g. for tests or for writing the simulations of a project file. Project id, simulation name and number are taken from the given variables if present (defaults: TestProject, TestSimulation); the values of other given system variables (e.g. start and end date) are kept.
      Parameters:
      aParameterMap - the variables, keyed by name; used directly, not copied
    • FWSimVarMap

      public FWSimVarMap()
      Creates an empty var map with system variables only, e.g. for generating documentation.
  • Method Details

    • setWaiting

      public void setWaiting(boolean shouldWait) throws InterruptedException
      Suspends the calling thread on this var map (wait()) or wakes up a waiting thread (notify()). The caller must hold the monitor of this object.
      Parameters:
      shouldWait - true to wait, false to wake up a waiting thread
      Throws:
      InterruptedException - if the waiting thread is interrupted
    • getVarMap

      public HashMap<String, FWSimVariable<?>> getVarMap()
      Returns:
      the underlying map of all variables, keyed by name
    • getStringValue

      public String getStringValue(String aKey)
      Parameters:
      aKey - name of the variable
      Returns:
      the value converted with toString(), or null if the value is not set
    • forceIntegerValue

      public Integer forceIntegerValue(String aKey)
      Returns a value converted to Integer (decimals are truncated).
      Parameters:
      aKey - name of the variable
      Returns:
      the converted value, or null if the value is not set or not convertible
    • forceDoubleValue

      public Double forceDoubleValue(String aKey)
      Returns a value converted to Double.
      Parameters:
      aKey - name of the variable
      Returns:
      the converted value, or null if the value is not set or not convertible
    • forceBooleanValue

      public boolean forceBooleanValue(String aParamKey)
      Returns a value converted to boolean. Use this only if the variable is not a BOOLEAN variable; otherwise use getValue().
      Parameters:
      aParamKey - name of the variable
      Returns:
      the converted value (see StringHelper.parseBoolean(Object)), false if not convertible
    • forceDateValue

      public LocalDateTime forceDateValue(String aParamKey)
      Returns a value converted to a date. Use this only if the variable is not a DATE variable; otherwise use getValue().
      Parameters:
      aParamKey - name of the variable
      Returns:
      the converted date (see StringHelper.parseDate(Object, LocalDateTime)), or null if not convertible
    • forceDoubleArrayValue

      public Double[] forceDoubleArrayValue(String aString)
      Returns a value as double array. If the variable is no double array, the single variables <name>.0, <name>.1, ... are collected into an array. Use this only if the variable is not a DOUBLEARRAY variable; otherwise use getValue().
      Parameters:
      aString - name of the variable; the variable must exist
      Returns:
      the array, or null if it cannot be determined
    • forceDoubleMapValue

      public TreeMap<Double,Double> forceDoubleMapValue(String aKey)
      Returns a value as sorted map. A double array is interpreted as key/value pairs {k1, v1, k2, v2, ...} (see FWSimHelper.ArrayToMap(Double[])).
      Parameters:
      aKey - name of the variable; the variable must exist
      Returns:
      the map, or null if it cannot be determined
      See Also:
    • forceIntegerArrayValue

      public Integer[] forceIntegerArrayValue(String aString)
      Returns a value as integer array. If the variable is no integer array, the single variables <name>.0, <name>.1, ... are collected into an array. Use this only if the variable is not an INTARRAY variable; otherwise use getValue().
      Parameters:
      aString - name of the variable; the variable must exist
      Returns:
      the array, or null if it cannot be determined
    • replaceParamTokens

      public String replaceParamTokens(String aString, Object aDefault)
      Replaces parameter tokens like ${name} in a string with the values of the variables of this var map.
      Parameters:
      aString - string containing parameter tokens
      aDefault - value returned if the string cannot be resolved
      Returns:
      the string with replaced tokens
      See Also:
    • getValue

      public Object getValue(String aKey)
      Returns the value of a variable; for variables with a rule, the rule is evaluated.
      Parameters:
      aKey - name of the variable
      Returns:
      the value, or null if the variable does not exist or has no value
      See Also:
    • getValue

      public Object getValue(String aKey, Object aDefault)
      Returns the value of a variable. For variables whose rule is more than a plain variable name (except management variables), the rule is evaluated and its result returned.
      Parameters:
      aKey - name of the variable
      aDefault - value returned if the variable does not exist or has no value
      Returns:
      the value, or aDefault
    • setValue

      public void setValue(String aKey, Object aValue, FWSimVariable.DATA_TYPE aDataType, FWSimVariable.CONTENT_TYPE aContentType, FWSimFieldContainer aSourceComponent) throws SimValueOutOfRangeException
      Sets the value of a variable. Strings are converted to the data type of the variable. The value is only set if it differs from the current value; checks are done as in FWSimVariable.setValue(Object, FWSimFieldContainer). If the variable does not exist, it is created with the given data and content type and a warning is logged.
      Parameters:
      aKey - name of the variable
      aValue - the value; null clears the value
      aDataType - data type used if the variable has to be created
      aContentType - content type used if the variable has to be created
      aSourceComponent - component that sets the value, for checking purposes
      Throws:
      SimValueOutOfRangeException - (runtime exception) if the value exceeds min or max and the check level is STRICT
      RuntimeException - if the value does not match the data type of the variable
    • initValue

      public void initValue(String aKey, FWSimVariable<?> aFWSimVariable)
      Adds a variable to the var map. If it has no value, it is reset to its default value. If aKey differs from the variable name, the variable is registered under both names (the second as link).
      Parameters:
      aKey - key to register the variable under
      aFWSimVariable - the variable
    • addVariable

      public void addVariable(String aKey, FWSimVariable<?> aFWSimVariable, boolean isLink)
      Adds a variable to the var map (replacing a variable with the same key). A warning is logged if the key differs from the variable name and the variable is not added as link.
      Parameters:
      aKey - key to register the variable under
      aFWSimVariable - the variable
      isLink - true if the key is an additional name (link) for the variable
    • getProjectID

      public String getProjectID()
      Returns:
      the id of the current project
    • getSimulationID

      public String getSimulationID()
      Returns the id of the current simulation. If it is not set yet, it is generated.
      Returns:
      the simulation id
      See Also:
    • generateSimulationID

      public String generateSimulationID()
      Generates the simulation id from project iteration, project id, simulation name and number, and stores it.
      Returns:
      the generated simulation id
      See Also:
    • setSimulationName

      public void setSimulationName(String aSimulationName)
      Sets the simulation name and clears the simulation id, so that it is generated again.
      Parameters:
      aSimulationName - the new simulation name
    • getSimulationName

      public String getSimulationName()
      Returns:
      simulation name
    • getSimulationNumber

      public Integer getSimulationNumber()
      Returns:
      the simulation number
    • getIteration

      public Integer getIteration()
      Returns:
      the iteration number of the project
    • getCurrentSession

      public FWSimSession getCurrentSession()
      Returns:
      the current session
    • isSynchronized

      public boolean isSynchronized()
      Returns:
      true if the simulations of a project are synchronized (synchronize frequency other than NON)
    • getSynchronizedFrequence

      public FWSimIOAdapter.FREQUENCE getSynchronizedFrequence()
      Returns:
      the frequency in which the simulations of a project are synchronized, NON if not synchronized
    • getSynchronizeRule

      public String getSynchronizeRule()
      Returns:
      the rule for synchronisation (used with frequency COMPLEX), or null if not synchronized
    • isWaiting

      public boolean isWaiting()
      Returns:
      true if a thread is waiting on this var map (see setWaiting(boolean))
    • getCurrentDateString

      public String getCurrentDateString()
      Returns:
      the current model date formatted as dd.MM.yyyy, or null if not set
    • getStartDate

      public LocalDateTime getStartDate()
      Returns:
      the start date of the simulation
    • getEndDate

      public LocalDateTime getEndDate()
      Returns:
      the end date of the simulation
    • calculateStatistics

      public void calculateStatistics()
      Lets the output manager of the session calculate the statistics outputs for this var map.
    • setProjectID

      public void setProjectID(String aProjectID)
      Sets the project id and clears the simulation id, so that it is generated again.
      Parameters:
      aProjectID - the new project id
    • setSessionID

      public void setSessionID(String aSessionID)
      Parameters:
      aSessionID - id of the current session
    • setSimulationNumber

      public void setSimulationNumber(Integer aSimulationNumber)
      Sets the simulation number and clears the simulation id, so that it is generated again.
      Parameters:
      aSimulationNumber - the new simulation number
    • setCurrentSession

      public void setCurrentSession(FWSimSession aFwSimSession)
      Sets the current session and its id.
      Parameters:
      aFwSimSession - the current session
    • removeVariable

      public void removeVariable(String aElement)
      Removes a variable from the var map. Use with care - the variable might still be needed.
      Parameters:
      aElement - name of the variable
    • filterData

      public Object[] filterData(HashMap<String, FWSimVariable<?>> aFilterMap)
      Returns the values of the variables whose names are the keys of a map.
      Parameters:
      aFilterMap - map whose keys are the variable names
      Returns:
      the values in the iteration order of the keys
      See Also:
    • filterData

      public Object[] filterData(Set<String> aKeySet)
      Returns the values of the given variables (rules are evaluated, see getValue(String)).
      Parameters:
      aKeySet - names of the variables
      Returns:
      the values in the iteration order of the set; null for unknown variables
    • putAllVariables

      public void putAllVariables(Map<String, FWSimVariable<?>> aVarMap)
      Adds several variables to the var map (replacing variables with the same key). If checks are enabled, a warning is logged for keys of system variables.
      Parameters:
      aVarMap - the variables to add, keyed by name
    • isVariableAvailable

      public boolean isVariableAvailable(String aKey)
      Parameters:
      aKey - name of the variable
      Returns:
      true if the variable exists and has a non-empty value (see StringHelper.isEmpty(Object))
    • isSpinupPeriode

      public boolean isSpinupPeriode()
      Returns:
      true if the simulation is in the spin-up period
    • doSpinupReset

      public boolean doSpinupReset()
      Returns:
      true if the date has just been reset to the start date after (or during) the spin-up
    • toString

      public String toString()
      Returns a text with simulation id, current date and one line per entry of the var map (for debugging).
      Overrides:
      toString in class Object
    • toArray

      public String[][] toArray()
      Returns:
      a table with a header row and one row per entry sorted by key: key, variable name, value as string
    • addLink

      public void addLink(String aKey, FWSimVariable<?> aVar, boolean performChecks) throws SimLinkInvalidException
      Links a variable (usually a component input) to another variable: the source variable is registered under the key of the target, so both names refer to the same variable. Variables of type var with a rule are not linked if the target does not exist.
      Parameters:
      aKey - name of the target (e.g. the input variable)
      aVar - the source variable (e.g. an output of another component)
      performChecks - if true, it is checked that both variables exist and have the same data type
      Throws:
      SimLinkInvalidException - if a check fails
    • removeLink

      public void removeLink(String aName, FWSimVariable<?> aFwSimVariable)
      Removes a link: the link name is removed from the variable currently registered under aName, and aFwSimVariable is registered under this name instead.
      Parameters:
      aName - name of the linked target
      aFwSimVariable - the variable to register under the name from now on
    • initializeCurrentDate

      public void initializeCurrentDate(LocalDateTime aDate)
      Sets the current date at the start of a simulation and starts the spin-up count down if spin-up days are set.
      Parameters:
      aDate - the first model date
    • updateCurrentDate

      public void updateCurrentDate()
      Called at the start of each time step: during spin-up the count down is decreased; at the end of the spin-up (or when the end date is reached during spin-up) the date is reset to the start date if configured. Then the current model date is written to the system variables (see writeCurrentDateVariables()). With spinupdays = n, the first n steps are the spin-up.
    • writeCurrentDateVariables

      public void writeCurrentDateVariables()
      Writes the current model date to the system variables (date, year, day of year, month, day of month) and the spin-up state, without changing the spin-up count down. Used when a simulation is created: before (#623 finding), updateCurrentDate() was called there, which already counted one spin-up day, so spinupdays = n gave only n-1 spin-up steps.
    • getCurrentDate

      public LocalDateTime getCurrentDate()
      Returns:
      the current model date
    • setCurrentDate

      public void setCurrentDate(LocalDateTime aCurrentDate)
      Sets the current model date. The system variables are only updated by updateCurrentDate().
      Parameters:
      aCurrentDate - the current model date
    • getCurrentDOY

      public int getCurrentDOY()
      Returns:
      current DayOfYear
    • getCurrentYear

      public int getCurrentYear()
      Returns:
      current Year
    • getCurrentDayOfMonth

      public int getCurrentDayOfMonth()
      Returns:
      current Day of Month
    • getCurrentMonth

      public int getCurrentMonth()
      Returns:
      current Month
    • hasSimulationEnded

      public Boolean hasSimulationEnded()
      Returns:
      true if the simulation has ended
    • setSimulationEnd

      public void setSimulationEnd()
      Marks the simulation as ended.
    • clone

      public FWSimVarMap clone(FWSimSession aSession)
      Copies the var map for another session. Every variable is copied with FWSimVariable.clone(FWSimVarMap) (new variable object, shared meta data) and links are rebuilt to the copies.
      Parameters:
      aSession - session of the copy
      Returns:
      the copy
    • cloneToControlMap

      public FWSimVarMap cloneToControlMap()
      Creates a reduced copy for the simulation control: only project variables (var, dyn) and system variables are copied (without the date parts and spin-up variables); links are not copied.
      Returns:
      the reduced copy
    • getSimLinks

      public HashMap<String,String> getSimLinks()
      Returns:
      all links as map from link name (target) to the name of the linked source variable
    • reset

      public void reset()
      Resets the variables of the simulation control containers (e.g. generators) to their default values. Other variables are not changed.
    • hasSimVariable

      public boolean hasSimVariable(String aRule)
      Checks whether a variable exists. In rules, dots in names are written as double underscores; they are converted back before the lookup.
      Parameters:
      aRule - name of the variable, possibly with __ instead of dots
      Returns:
      true if a variable with this name exists
    • getSimVariable

      public FWSimVariable<?> getSimVariable(String aKey) throws SimFieldMissingException
      Returns the variable registered under a key. For links this is the linked source variable, whose name may differ from the key. Keys with an index or parameter specification (!, ${) are resolved to the base name if necessary.
      Parameters:
      aKey - name or link name of the variable
      Returns:
      the variable
      Throws:
      SimFieldMissingException - if no variable is registered under the key
    • getValueToDatabaseString

      public String getValueToDatabaseString(String aSourceKey) throws SimFieldMissingException
      Formats the value of a variable as SQL literal: dates as 'yyyy-MM-dd', numbers unquoted, arrays as {v1,v2,...}, other values quoted (quotes in the value are not escaped).
      Parameters:
      aSourceKey - name of the variable
      Returns:
      the SQL literal
      Throws:
      SimFieldMissingException - if the variable does not exist
    • getVariables

      public Collection<FWSimVariable<?>> getVariables(FWSimVariable.CONTENT_TYPE aContentType, boolean aIsSorted)
      Returns all variables of a content type (each variable once, even if it is registered under several names).
      Parameters:
      aContentType - the content type
      aIsSorted - if true, the list is sorted by name
      Returns:
      the variables
    • getVariables

      Returns all variables owned by a container, grouped by content type. Variables registered under several names (links) appear several times.
      Parameters:
      aContainer - the owning container
      Returns:
      map from content type to the variables
    • has

      public boolean has(String aName)
      JEXL context: checks whether a variable exists. Double underscores in the name stand for dots. Found variables are cached for faster access.
      Specified by:
      has in interface org.apache.commons.jexl3.JexlContext
      See Also:
      • JexlContext.has(String)
    • get

      public Object get(String aName)
      JEXL context: returns the value of a variable. Double underscores in the name stand for dots. A warning is logged if the variable does not exist.
      Specified by:
      get in interface org.apache.commons.jexl3.JexlContext
      See Also:
      • JexlContext.get(String)
    • set

      public void set(String aName, Object aValue)
      JEXL context: sets the value of a variable (converted to its data type, with the owner as source). Double underscores in the name stand for dots. A warning is logged if the variable does not exist.
      Specified by:
      set in interface org.apache.commons.jexl3.JexlContext
      See Also:
      • JexlContext.set(String, Object)
    • printJexlMap

      public String printJexlMap()
      Returns:
      the cache of variables used in rule evaluation, formatted as text (for debugging)
    • isInternal

      public static boolean isInternal(String aVarName)
      Parameters:
      aVarName - name of a variable
      Returns:
      true if the name is the name of a system variable (e.g. CURRENT.DATE, projectid)
    • checkInternal

      public boolean checkInternal(FWSimVariable<?> aFwSimVariable)
      Checks that a system variable is the instance managed by this var map (for the id and name variables). A warning is logged if another instance with the same name is found.
      Parameters:
      aFwSimVariable - the variable to check
      Returns:
      false if the variable is a system variable but not the managed instance, otherwise true