Class FWSimHelper
java.lang.Object
net.simplace.sim.util.FWSimHelper
Static helper methods for simulations: converting values and arrays, handling project data files and simulation
ids, and more. Parameter tokens and expressions are replaced by
FWParameterResolver.- Author:
- Andreas Enders
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic Comparator<FWSimFieldContainer> Compares field containers by their order number.static final Comparator<FWSimVariable<?>> Orders variables within a SimComponent for readable output: by content type (sys, constant, input, res, state, rate, out, privat), then by name. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic FileaddResourceFiles(String aWorkDir, String aSimulationExperimentPath, String aSolutionFileName, String aProjectFileName) Packs a simulation experiment into a ZIP file: the solution (foldersolution/), the project file if given (folderproject/) and the resource files of the experiment.static LinkedHashMap<String, String> ArrayToLinkedMap(Object[] aArray) Converts an array into a map where each element (as string) is both key and value, e.g.ArrayToMap(Double[] aArray) Interprets an array as key/value pairs{k1, v1, k2, v2, ...}and returns them as sorted map.static BooleancheckForAction(LocalDateTime aCurrentDate, FWSimIOAdapter.FREQUENCE aFrequence, JexlRuleScript aJexlScript, FWSimVarMap aVarMap) Checks whether an action (e.g.static HashMap<String, FWSimVariable<?>> filterVarMap(HashMap<String, FWSimVariable<?>> aMap, String aRegexp) Filters a map of variables by key.static Collection<String> findResources(String aPackage, String aRegexp) Finds resources on the class path whose name matches a regular expression.static StringgenerateSimulationID(Integer aProjectIteration, String aProjectID, String aSimulationName, Integer aSimulationNumber) Builds a simulation id of the formprojectid_II__NAME_NNNNNNN: project id, two-digit iteration, simulation name in upper case and, if given, the seven-digit simulation number.static FWSimVariable.DATA_TYPEgetDataTypeFromValue(String aFirstValue) Guesses the data type from a value string: DOUBLE, INT, INTARRAY/DOUBLEARRAY ({1,2}), BOOLEAN, DATE (yyyy-MM-ddordd.MM.yyyystyle) or CHARARRAY; otherwise CHAR.static Object[][]getObjectArrayFromVarMap(FWSimVarMap aVarMap) Converts a var map into an array of key/value pairs.static StringgetParameterName(String aKey) Returns the variable name referenced by a key: the name of the first parameter token (${name}), or otherwise the part before!.static FilegetSortedCopyFile(File aProjectDataFile) Returns the file the sorted copy of an unsorted project data file is written to:<name>_sorted.<extension>next to the original.static voidlogInitialInfo(boolean aForce) Logs a banner with system information (user, cores, memory, version) at the start of the application.static PreparedStatementprepareCountSelect(String aTableName, String aConnectionPoolDefault) Prepares a statement counting the simulations of a project.static PreparedStatementprepareDatabase(String aTableName, HashMap<String, FWSimVariable<?>> aHeaderVariables, String aConnectionPoolDefault, boolean aDropIfExists, boolean aDoCreateTable) Prepares a database table for writing variables: optionally drops and (re)creates the table with one column per variable, and returns a prepared INSERT statement with one placeholder per variable.static PreparedStatementprepareLimitedSelect(String aTableName, HashMap<String, FWSimVariable<?>> aFieldMap, String aConnectionPoolDefault) Prepares a paged SELECT (HSQLDB syntaxSELECT LIMIT offset count ...) of the given columns for a project.splitProjectDataByNumberOfCores(File aProjectDataFile, String aDivider, int[] aListOfCores) Splits a project data file into line ranges for several machines with different numbers of cores; machines with more cores get proportionally more lines.static LinkedHashMap<String, String> splitProjectDataBySimulationCount(File aProjectDataFile, String aDivider, int aSplitCount) Splits a project data file into about aSplitCount ranges of lines for parallel processing.static LinkedHashMap<String, String> splitProjectDataBySimulationCount(File aProjectDataFile, String aDivider, int aSplitNumber, String[][] aReadCSVtoArray) Splits already read project data into ranges of about aSplitNumber lines.static ObjectunzipArray(FWSimVariable<?> aTargetVariable, ArrayList<String> aFieldMapIndizes, Object[] aSourceArray, Set<String> aParametersFromString, FWSimFieldContainer aContainer) Evaluates the rules!UNZIP_KEYS(${C})!and!UNZIP_VALUES(${C})!: from an array of key/value pairsC = {k1, v1, k2, v2, ...}the keys (even positions) or values (odd positions) are extracted.static ObjectzipArray(FWSimVariable<?> aTargetVariable, ArrayList<String> aFieldMapIndizes, Object[] aSourceArray, Set<String> aParametersFromString, FWSimFieldContainer aContainer) Evaluates the rule!ZIP(${A},${B})!: the arrays A and B are merged alternately intoC = {a1, b1, a2, b2, ...}.
-
Field Details
-
FIELD_COMPERATOR
Compares field containers by their order number. -
SIM_VAR_COMARATOR
Orders variables within a SimComponent for readable output: by content type (sys, constant, input, res, state, rate, out, privat), then by name.
-
-
Constructor Details
-
FWSimHelper
public FWSimHelper()
-
-
Method Details
-
ArrayToLinkedMap
Converts an array into a map where each element (as string) is both key and value, e.g. for choice fields of forms.- Parameters:
aArray- the elements- Returns:
- the map in array order
-
ArrayToMap
-
findSimComponents
-
findResources
Finds resources on the class path whose name matches a regular expression.- Parameters:
aPackage- not usedaRegexp- regular expression for the resource names- Returns:
- the matching resource names
- See Also:
-
findResourceTransformers
-
findSelectors
-
findGenerators
-
findIterators
-
getDataTypeFromValue
Guesses the data type from a value string: DOUBLE, INT, INTARRAY/DOUBLEARRAY ({1,2}), BOOLEAN, DATE (yyyy-MM-ddordd.MM.yyyystyle) or CHARARRAY; otherwise CHAR.- Parameters:
aFirstValue- value to analyse- Returns:
- the guessed data type
-
getObjectArrayFromVarMap
Converts a var map into an array of key/value pairs.- Parameters:
aVarMap- the var map- Returns:
- one row per entry:
{key, value}(values are not evaluated from rules)
-
getParameterName
-
unzipArray
public static Object unzipArray(FWSimVariable<?> aTargetVariable, ArrayList<String> aFieldMapIndizes, Object[] aSourceArray, Set<String> aParametersFromString, FWSimFieldContainer aContainer) Evaluates the rules!UNZIP_KEYS(${C})!and!UNZIP_VALUES(${C})!: from an array of key/value pairsC = {k1, v1, k2, v2, ...}the keys (even positions) or values (odd positions) are extracted. Double, int and text arrays are supported.- Parameters:
aTargetVariable- variable with the rule; its data type decides the array typeaFieldMapIndizes- names of the source fields, in the order of aSourceArrayaSourceArray- values of the source fieldsaParametersFromString- parameter names found in the rule; must contain exactly one nameaContainer- container evaluating the rule (for log messages)- Returns:
- the extracted array, or
nullif the rule is invalid (a warning is logged)
-
zipArray
public static Object zipArray(FWSimVariable<?> aTargetVariable, ArrayList<String> aFieldMapIndizes, Object[] aSourceArray, Set<String> aParametersFromString, FWSimFieldContainer aContainer) Evaluates the rule!ZIP(${A},${B})!: the arrays A and B are merged alternately intoC = {a1, b1, a2, b2, ...}. Double, int and text arrays are supported. A is the parameter that comes first in the rule.- Parameters:
aTargetVariable- variable with the rule; its data type decides the array typeaFieldMapIndizes- names of the source fields, in the order of aSourceArrayaSourceArray- values of the source fieldsaParametersFromString- parameter names found in the rule; must contain exactly two namesaContainer- container evaluating the rule (for log messages)- Returns:
- the merged array, or
nullif the rule is invalid (a warning is logged)
-
filterVarMap
public static HashMap<String, FWSimVariable<?>> filterVarMap(HashMap<String, FWSimVariable<?>> aMap, String aRegexp) Filters a map of variables by key.- Parameters:
aMap- map to filteraRegexp- regular expression the whole key must match- Returns:
- a new map containing only the entries whose keys match
-
addResourceFiles
public static File addResourceFiles(String aWorkDir, String aSimulationExperimentPath, String aSolutionFileName, String aProjectFileName) throws MissingSimResourceException Packs a simulation experiment into a ZIP file: the solution (foldersolution/), the project file if given (folderproject/) and the resource files of the experiment.- Parameters:
aWorkDir- the work directoryaSimulationExperimentPath- directory of the simulation experiment; must be located in the work directoryaSolutionFileName- path of the solution file (*.sol.xml)aProjectFileName- path of the project file, or empty for a run without project- Returns:
- the ZIP file in the temp directory
- Throws:
MissingSimResourceException- if the experiment is not located in the work directory or a file cannot be packed
-
logInitialInfo
public static void logInitialInfo(boolean aForce) Logs a banner with system information (user, cores, memory, version) at the start of the application. The banner is logged only once unless forced.- Parameters:
aForce- iftrue, the banner is logged even if it was logged before
-
prepareDatabase
public static PreparedStatement prepareDatabase(String aTableName, HashMap<String, FWSimVariable<?>> aHeaderVariables, String aConnectionPoolDefault, boolean aDropIfExists, boolean aDoCreateTable) throws SQLException Prepares a database table for writing variables: optionally drops and (re)creates the table with one column per variable, and returns a prepared INSERT statement with one placeholder per variable. Dots in variable names become double underscores in column names.- Parameters:
aTableName- name of the tableaHeaderVariables- the variables to store, in column orderaConnectionPoolDefault- name of the connection poolaDropIfExists- iftrue, an existing table is dropped (and then created)aDoCreateTable- iftrue, the table is created- Returns:
- the prepared INSERT statement
- Throws:
SQLException- if a database operation fails
-
prepareLimitedSelect
public static PreparedStatement prepareLimitedSelect(String aTableName, HashMap<String, FWSimVariable<?>> aFieldMap, String aConnectionPoolDefault) throws SQLException Prepares a paged SELECT (HSQLDB syntaxSELECT LIMIT offset count ...) of the given columns for a project. Parameters: offset, count, project iteration, project id.- Parameters:
aTableName- name of the tableaFieldMap- the variables to select (keys are the column names, dots as double underscores)aConnectionPoolDefault- name of the connection pool- Returns:
- the prepared SELECT statement
- Throws:
SQLException- if the statement cannot be prepared
-
prepareCountSelect
public static PreparedStatement prepareCountSelect(String aTableName, String aConnectionPoolDefault) throws SQLException Prepares a statement counting the simulations of a project. Parameters: project iteration, project id.- Parameters:
aTableName- name of the tableaConnectionPoolDefault- name of the connection pool- Returns:
- the prepared COUNT statement
- Throws:
SQLException- if the statement cannot be prepared
-
generateSimulationID
public static String generateSimulationID(Integer aProjectIteration, String aProjectID, String aSimulationName, Integer aSimulationNumber) Builds a simulation id of the formprojectid_II__NAME_NNNNNNN: project id, two-digit iteration, simulation name in upper case and, if given, the seven-digit simulation number.- Parameters:
aProjectIteration- iteration number of the projectaProjectID- project idaSimulationName- simulation nameaSimulationNumber- simulation number, ornull- Returns:
- the simulation id
-
splitProjectDataBySimulationCount
public static LinkedHashMap<String,String> splitProjectDataBySimulationCount(File aProjectDataFile, String aDivider, int aSplitCount) Splits a project data file into about aSplitCount ranges of lines for parallel processing. Lines of the same project (first column) are never split. For an unsorted file a sorted copy is written (seegetSortedCopyFile(File)); the ranges then refer to the copy. The application exits if the file cannot be read.- Parameters:
aProjectDataFile- CSV file with the project data (first column: project id)aDivider- column divider; tab if emptyaSplitCount- number of parts- Returns:
- map from line range (e.g.
1-2000) to the project id at the end of the range
-
splitProjectDataBySimulationCount
public static LinkedHashMap<String,String> splitProjectDataBySimulationCount(File aProjectDataFile, String aDivider, int aSplitNumber, String[][] aReadCSVtoArray) Splits already read project data into ranges of about aSplitNumber lines. Lines of the same project (first column) are never split. For an unsorted file a sorted copy is written (seegetSortedCopyFile(File)); the ranges then refer to the copy.- Parameters:
aProjectDataFile- CSV file with the project data (never changed)aDivider- column divideraSplitNumber- number of lines per rangeaReadCSVtoArray- content of the file including the header line- Returns:
- map from line range (e.g.
1-2000) to the project id at the end of the range
-
splitProjectDataByNumberOfCores
public static List<String> splitProjectDataByNumberOfCores(File aProjectDataFile, String aDivider, int[] aListOfCores) Splits a project data file into line ranges for several machines with different numbers of cores; machines with more cores get proportionally more lines. Lines of the same project (first column) are never split. For an unsorted file a sorted copy is written (seegetSortedCopyFile(File)); the ranges then refer to the copy. The application exits if the file cannot be read.- Parameters:
aProjectDataFile- CSV file with the project data (first column: project id)aDivider- column divider; tab if emptyaListOfCores- number of cores per machine- Returns:
- the line ranges, e.g.
1-2000
-
getSortedCopyFile
-
checkForAction
public static Boolean checkForAction(LocalDateTime aCurrentDate, FWSimIOAdapter.FREQUENCE aFrequence, JexlRuleScript aJexlScript, FWSimVarMap aVarMap) Checks whether an action (e.g. writing an aggregated output) is due on the current date:- YEARLY: on the last day of the year,
- MONTHLY: on the last day of the month,
- COMPLEX: if the rule evaluates to
true, - BOOLEAN: if the variable named by the rule is
true, - END: at the end of the simulation.
- Parameters:
aCurrentDate- the current model dateaFrequence- the frequencyaJexlScript- the rule (for COMPLEX and BOOLEAN)aVarMap- var map used to evaluate the rule- Returns:
trueif the action is due;falsefor other frequencies
-