Professional Documents
Culture Documents
LedaFlow Scripting Manual
LedaFlow Scripting Manual
Kongsberg Digital AS
Drengsrudbekken 12, P.O. Box 451, N-1383 Asker, Norway
Telephone +47 67 80 48 00 Telefax +47 67 80 48 30 http://www.kongsberg.com/kdi
LedaFlow
Revisions
Document history
The information contained in this document may be subject to change at a later date
(due, for instance, to availability of components). Notice will be given only in case such
a change is deemed to be of any consequence for customers. Kongsberg Digital AS
shall not be liable for incidental or consequential damages in connection with the
furnishing, performance, or use of this document.
2
LedaFlow Scripting Manual v2.4
© 2018 Kongsberg Digital AS. All rights reserved. No part of this work covered by the
copyright hereon may be reproduced or otherwise copied without prior permission from
Kongsberg Digital AS.
3
LedaFlow
Table of contents
1 INTRODUCTION TO SCRIPTING IN LEDAFLOW ........................................6
3 EXAMPLES............................................................................................................12
7 OTHERS .................................................................................................................81
7.1 Softsh exit codes ...................................................................................................81
7.2 License tools .........................................................................................................82
7.3 Saving output to a file ........................................................................................... 84
5
LedaFlow
1 INTRODUCTION TO SCRIPTING IN
LEDAFLOW
Scripting languages (commonly called scripting programming languages or script
languages) are computer programming languages that are typically interpreted and
can be typed directly from a keyboard. Whereas computer programs are converted
permanently into binary executable files before they are run, scripts remain in their
original form and are interpreted command-by-command each time they are run. A
script consists of lines of executable computer code written in a script language.
The scripting language used with LedaFlow is based on the ECMAScript scripting
language, as defined in standard ECMA-262 (JavaScript). Extensions to this
language have been introduced by the LedaFlow development team in order to
define LedaFlow objects and set up a case. In LedaFlow, the scripts are written in
Javascript and have the extension *.js.
Through a script file we can, for example:
Create a case in the database from an input file
Run a case
Output data to a file
Combining these we can implement a range of scripts from very simple single cases
to complex automated analysis algorithm. This provides us with the ability to
standardise our work flows so that we can readily set up simulations to follow the
same sequence of simulation and analysis, time after time.
In this manual we will:
Introduce you to some fundamental javascript concepts
Describe the LedaFlow script modules
Give example scripts
6
LedaFlow Scripting Manual v2.4
2 GETTING STARTED
7
LedaFlow
You can use Notepad++. Download it from the web. Use “Javascript”
language.
Save your scripts under the Javascript format *.js.
Do not use '-' in the name of the script files.
OR
Use the shortcut “Ctrl+R”
The script is interpreted by softsh and softsh outputs are displayed in the bottom
section of the sheet
8
LedaFlow Scripting Manual v2.4
Example
9
LedaFlow
After completion, a regular return code will be available. See section 7.1 for a
complete description of the exit codes and their interpretations.
10
LedaFlow Scripting Manual v2.4
Note also, that when running a script from the LedaFlow GUI, the javascript object
“CASE_SELECTED” refers to the case obj currently selected in the case browser.
So you can refer to the uuid of the case selected by : CASE_SELECTED.uuid.
That enables you to be able to run the script on the case currently selected from the
client.
You can also traverse your current project (database) using the CASES module
methods findCasesWithName, findFirstCaseWithName, visibleCases. This method
returns a list of “case object” that has the uuid attribute, as shown above.
11
LedaFlow
3 EXAMPLES
All the examples are included with the LedaFlow installer and located in the folder
C:/Kongsberg/LedaFlowScriptExamples/v2.4/.
All examples/snippets are commented with explanations.
12
LedaFlow Scripting Manual v2.4
13
LedaFlow
4.1 Introduction
LedaFlow scripting comes with a set of LedaFlow specific modules gathered under
the global namespace “ledaModules”.
A LedaFlow module is an object containing a set of methods. You first need to
create a module object by calling the ledaModules function.
var moduleX = ledaModules.X();
ledaModules.CALCULATE() [Object]
4.2.2 setCaseId(uuid)
uuid (String): uuid of the case to set for the module
14
LedaFlow Scripting Manual v2.4
4.2.3 calculateSS(uuid)
uuid (String): uuid of a case. OPTIONAL if uuid has been set using “setCaseId”
To launch the steady-state preprocessor locally, i.e. not through the simulation
manager). It will block the script until the calculation is finished.
If you set an id in the module, using “setCaseId” (advised), the uuid argument
is not needed.
You can also pass a case id as an argument to the method. In this case, any uuid that
may have been passed with setCaseId, is disregarded.
4.2.4 calculate(uuid)
uuid (String): uuid of a case. OPTIONAL if uuid has been set using “setCaseId”
To launch the LedaFlow transient simulator locally, i.e. not through the simulation
manager) and will block the script until the calculation is finished.
If you set an id in the module, using “setCaseId” (advised), the uuid argument
is not needed.
15
LedaFlow
…
calcModule.calculate();
You can also pass a case id as an argument to the method. In this case, any uuid that
may have been passed with setCaseId, is disregarded.
This will write a restart file. “restartfile” is the name of the file (full or relative path).
The sample is the index of the global time sample.
This will initialize a case with a restart file. “restartfile” is the name of the restart
file (full or relative path). “reset” is boolean to indicate if the time should be reset
to 0 or not.
16
LedaFlow Scripting Manual v2.4
4.2.7 nSamples(uuid)
uuid (String): uuid of a case. OPTIONAL if uuid has been set using “setCaseId”
Return the number of global time samples available for the case. Typically used as
argument when calling the writeRestartFile method.
4.2.8 calculateSSParametric(uuid)
uuid (String) : uuid of the parametric study
To launch the parametricapp locally (i.e. not through the simulation manager) and
run “Initialize” on a given parametric study. Note however that the parametricapp
will use the simulation manager if the current database settings are “Use simulation
manager”.
All the sub-cases will be run per default. However, if you have run the study from
the LedaFlow GUI already and you used the option “Run only following cases”,
then only these sub-cases will be run.
This function will not return (blocking the script) until all calculations are
completed.
4.2.9 calculateParametric(uuid)
uuid (String) : uuid of the parametric study
17
LedaFlow
To launch the parametricapp locally (i.e. not through the simulation manager) and
run transient simulations. Note however that the parametricapp will use the
simulation manager if the current database settings are “Use simulation manager”.
All the sub-cases will be run per default. However, if you have run the study from
the LedaFlow GUI already and you used the option “Run only following cases”,
then only these sub-cases will be run.
This function will not return (blocking the script) until all calculations are
completed.
18
LedaFlow Scripting Manual v2.4
ledaModules.CASES() [Object]
19
LedaFlow
4.3.2 caseobj(uuid)
uuid (String) : uuid of the case
Returns a “case object” for a given uuid. The case object has the following
attributes:
4.3.3 visibleCases()
Output structure: [caseObj1, caseObj2,…,caseObjn]
Returns a list of cases objects of the “visible” cases of your current project
(database). I.e. all the cases you see in the case browser in the LedaFlow GUI.
4.3.4 createCaseFrom(inputFile)
inputFile (String) : name of the input file with full or relative path
Create a case in the current project (database), based on the given input file, and
returns a case object (see 4.3.2)
4.3.5 removeCase(uuid)
uuid (String) : uuid of the case
Remove the case with the given uuid from the current database. Note that you can
also pass a case obj instead of the uuid.
20
LedaFlow Scripting Manual v2.4
4.3.6 findCasesWithName(name)
name (String) : name of the case to find
Find the cases with given “name” in the visible cases, and return a list of
corresponding case objects. “name” can be a string or a regular expression.
4.3.7 findFirstCaseWithName(name)
name (String) : name of the case to find
4.3.8 writeInputFile(inputfile,
uuid,pvtTablesEmbedded)
inputFile (String) : name of the input file with full or relative path
uuid (String) : uuid of the case
pvtTablesEmbedded (Bool) [OPTIONAL]:to force or not the pvt tables embedment.
Write input file for case with given “uuid”. Note that you can also pass a case obj
instead of the uuid. If pvtTablesEmbedded is not defined, the user preferences will
control if the pvt tables are embedded into the input files or not.
See example snippet_createInpuFile.js.
21
LedaFlow
4.3.10 showCases()
Print a text representation of the folders and cases present in the current database
like seen in the case browser.
The folders are marked with [Folder] and the base cases of parametric studies are
marked with [PS Base case].
Each folder and case have an ID. The folder IDs can be used to export a folder.
4.3.11 exportAllCases(dbfile)
dbFile (String) : name of the dbFile with full or relative path (extension .qz to provide)
Performs the equivalent to exporting the root folder “/” from the case browser to a
.qz file. The “dbfile” is the resulting file name where the database will be stored.
Note that the file extension should be .qz.
See example ex_backupAllDatabases.js.
4.3.12 exportFolder(folderid,dbfile)
folderid (String): uuid of the folder as displayed in showCases()
dbFile (String) : name of the dbFile with full or relative path (extension .qz to provide)
Performs the equivalent to exporting a folder from the case browser to a .qz file.
The “folderid” can be obtained by using the showCases() function. The “dbfile” is
the resulting file name where the folder and cases will be stored. Note that the file
extension should be .qz.
22
LedaFlow Scripting Manual v2.4
ledaModules.RESULTS() [Object]
4.4.2 makeCatalog(uuid)
uuid (String) : uuid of the case for which the catalog will be created
This method returns a “catalog” object for the case/parametric study of identifier
uuid. A catalog object is an object containing information on all the properties
logged. Note that the catalog of a parametric study is equivalent to the catalog of
its base case.
To visualize the catalog, check How to visualize the list of properties logged?.
ledaModules.RESULTS().makeCatalog(uuid) [Object]
23
LedaFlow
4.4.2.1 trends
Type: array
Array of “trend properties” defined in all trend loggers of the case. A “trend
property” is an object with many attributes. The relevant ones for a user are shown
in the table below.
trendProperty [Object]
4.4.2.2 profiles
Type: array
profileProperty [Object]
25
LedaFlow
Function that filers the trends properties arrays based on a given filter and return a filtered list.
The given filter is an object that should have attributes names found in a property (ie loggerName,
propertyName, field….). For each of these attributes you can give a list of values.
If strict is set to false, it will look for an exact match, if strict is set to false, it will just check if the
given values are contained in the trends properties values. See examples below.
var filter = {
loggerName:[ "Node 1 – T","Node 2 - T"]
};
var f1 = catalog.filterTrends(filter, true);
/* f1 is a list of trends properties, all of which has loggerName
equal to “Node 1 – T” or "Node 2 – T"*/
filter = {
loggerCategory:["Mass flow rate"],
field: ["Total"]
}
var f2 = catalog.filterTrends(filter, false);
/* f2 is a list of trends properties, all of which has
loggerCategory containing “Mass flow rate” and field containing
“Total”, for ex “Total gas”, “Total liquid”…etc.*/
4.4.2.5 fullName(property)
property (Object) : profile or trend property
26
LedaFlow Scripting Manual v2.4
4.4.3 makeExtractor(uuid)
This method returns an “extractor” object for the case/parametric study of identifier
uuid. An “extractor” object is a tool with methods to extract results.
ledaModules.RESULTS().makeExtractor(uuid) [Object]
27
LedaFlow
4.4.3.1 id
Type: String
Case id given as an input
4.4.3.2 catalog
Type: Object
Object catalog of properties. An extractor.catalog is exactly the same as catalog
generated by “makeCatalog”. See section “makeCatalog” for detailed description.
//Output
…
Pipe 1_Density - gas
Pipe 1_Density - oil
Pipe 1_Density - water
Pipe 1_Density - gas in oil
Pipe 1_Density - gas in water
Pipe 1_Density - oil in gas
Pipe 1_Density - oil in water
Pipe 1_Density - water in gas
Pipe 1_Density - water in oil
….
28
LedaFlow Scripting Manual v2.4
4.4.3.3 getTrendTimes( )
Output struture: [t0, t1,…,tn]
Function that returns the array of time points for trends variables.
4.4.3.4 getProfileTimes( )
Output: [t0, t1,…,tn]
Function that returns the array of time points for trends variables.
4.4.3.5 getTrendValuesForAllTimes(trendProperty)
trendProperty (Object) : an element of the catalog.trends
Output structure:
getTrendValuesForAllTimes(trendProperty) [Object]
29
LedaFlow
4.4.3.6 getProfileValuesForAllTimes(profileProperty)
profileProperty (Object) : an element of the catalog.profiles
Output structure:
{property:profileProperty, mesh:[x1,…,xq], value:[ {time: t0, valueForGivenTime:[v1,…,vq]},…,
{time: tn, valueForGivenTime:[v1,….,vq]} ] }
getProfileValuesForAllTimes(profileProperty) [Object]
4.4.3.7 setSubCase(subCaseIndex)
For Parametric studies, it is necessary to indicate on which subcase results you want
to work with. You do so by giving the subCaseIndex (1 for case_1, 2 for case_2,
etc.). Per default the subCaseIndex is 1.
extractor.setSubCase(5);
// the extractor will extract results for case_5
30
LedaFlow Scripting Manual v2.4
ledaModules.FILE() [Object]
4.5.1 openWithApplication(filename)
filename (String): name of the file to open, with full or relative path.
To open the file given by filename with the application associated (by Windows) to
the extension of the file. To change the application associated to a file check Control
Panel/Default programs/Associate a file type or protocol with a program.
4.5.2 currentPath()
Returns the current path, i.e. the path of the script file in use.
31
LedaFlow
4.5.3 fileExists(filename)
filename (String): file name including full path
Check if the file exists. Returns true if file exists, false otherwise.
4.5.4 folderExists(path)
path (String): full path to folder
Check if the folder exists. Returns true if folder exists, false otherwise.
4.5.5 createFolder(path)
path (String): the path of the folder to create
Create a folder at the given path. Returns true if folder has been created, false if it
was not possible (folder existing already for example).
32
LedaFlow Scripting Manual v2.4
4.5.6 writeFileFromTemplate(data,template,filename)
data (Object): object containing all necessary information to customize your template.
template (String): name of the template file to be used, with full or relative path
filename (String): name of the output file, with full or relative path
This method creates a file based on a text file template, a Javascript object data and
a filename.
A template template is a text file containing anything you want. The specificity of
a template, is that all parts between tags: <eval> and </eval> will be evaluated and
replaced by the expression it will return. In these expressions between the tags
<eval> and </eval>, the name “data” will refer to the data data passed as argument
to the method.
The ouput file filename is equal to the template file where parts between tags <eval>
and </eval> are replaced
template_ex.txt
Hello , this is an example
We can create files based on template and expressions evaluated in
javascript !
For example, <eval> data.goodIdea </eval>
Or here I want to show data.hello:
<eval>
var tmp = "";
for(var i = 0; i < data.hello.length; i++)
tmp += data.hello[i]+" ";
tmp;
</eval>
End of my template
Outputfile.txt
Hello , this is an example
We can create files based on template and expressions evaluated in
javascript !
For example, LedaFlow script rocks!
Or here I want to show data.hello:
Hello dear LedaFlow user
End of my template
33
LedaFlow
4.5.7 writeFileFromString(string,filename)
string (String): the string to write to file
filename (String): the filename with full or relative path
This method creates a file “filename” based on a string “string” by writing the string
to the file.
4.5.8 writeJsonFileFromObject(object,filename)
object (Object): the object to write to file
filename (String): the filename with full or relative path
This method creates a file “filename” based on an object “object” by writing the
object in JSON (Javascript Object Notation) to the file.
var F = ledaModules.FILE();
var object = {a:"THIS",b:"IS A TEST"};
var filename = "test.json";
F.writeJsonfileFromObject(object, filename);
/* test.json
{
"a": "THIS",
"b": "IS A TEST"
}
*/
4.5.9 readJsonFile(filename)
filename (String): the filename to read with full or relative path
This method reads the file “filename” assumed to be in JSON, and returns a
corresponding Javascript object.
/*test.json is
{
"a": "THIS",
"b": "IS A TEST"
}
34
LedaFlow Scripting Manual v2.4
*/
4.5.10 csvRow(list,pickerParameter,separator)
list (Array): list of objects
pickerParameter (Function or Array or String): can be a function, an arrays of Strings, or one
single String. If no pickerParameter is provided, the method will return a copy of the “list”.
separator (String) [OPTIONAL]: Separator to be used. If nothing is provided, the default
separator USERPREF.listSeparator() will be used.
This method is an helper method to build csv strings based on a list of elements. It
returns a csv string resulting from looping over all the elements of the “list”, with
the pickerParameter applied.
print("k1:"+k1);
print("k2:"+k2);
print("k3:"+k3);
/*
k1:123,456,
k2:1,3,
k3:hello user!!!!!,This is an example!!!!!,
*/
The FULLRESULTS module is the script counterpart of the LedaFlow GUI “Output
files generator”. It gives the tools to write a case related loggers results to files.
35
LedaFlow
ledaModules.FULLRESULTS() [Object]
4.6.2 setUuid(uuid)
uuid (String): uuid of a case
36
LedaFlow Scripting Manual v2.4
fullRModule.setUuid("530cd8d6-32f4-4f69-990e-ba1ad89b426b");
This method will dump all the results from all the profile loggers or only the ones
given by loggersname to a single separated values file filename. The separator can
be specified using USERPREF.setListSeparator( ).
USERPREF.setListSeparator(",");
var fullRModule = ledaModules.FULLRESULTS();
var uuid = CASE_SELECTED.uuid;
fullRModule.setUuid(uuid);
fullRModule.trendLoggersToSvFile("trends.csv");
This method will dump all the trend loggers to a single json file filename
This method will dump all the results from all the profile loggers or only the ones
specified by loggersnames to a single separated values file filename. The separator
can be specified using USERPREF.setListSeparator.
37
LedaFlow
USERPREF.setListSeparator(",");
var fullRModule = ledaModules.FULLRESULTS();
var uuid = CASE_SELECTED.uuid;
fullRModule.setUuid(uuid);
fullRModule.profileLoggersToSvFile("profiles.csv");
This method will dump all the results from all the profile loggers or only the ones
specified by loggersnames to a json file filename.
WARNING: This method will be very slow for large cases with a lot of data.
Furthermore, the output file may become very large. It is therefore NOT
recommended for large sets of data.
38
LedaFlow Scripting Manual v2.4
ledaModules.REQUEST() [Object]
4.7.2 request(requestObject)
requestObject (Object): object containing information on what is requested
requestObject [Object]
39
LedaFlow
requestObject [Object]
40
LedaFlow Scripting Manual v2.4
requestObject [Object]
requestObject [Object]
41
LedaFlow
requestObject [Object]
requestModule.request(
{
requested : "FULLTRENDS",
folder : ".",
uuid : "50f6d985-3957-425b-b653-c5a3591d375b",
trendCatalogFilename : "tcatalog.json",
extension : ".csv",
});
requestObject [Object]
42
LedaFlow Scripting Manual v2.4
requestModule.request(
{
requested : "FULLPROFILES",
folder : ".",
uuid : "50f6d985-3957-425b-b653-c5a3591d375b",
profileCatalogFilename : "pcatalog.json",
extension : ".csv"
});
requestModule.request(
{
requested : "STATUS",
filename : "status.json",
uuid : "50f6d985-3957-425b-b653-c5a3591d375b"
});
43
LedaFlow
ledaModules.DATABASE() [Object]
4.8.2 deleteOldAndCreateNewSqliteFile(dbfile)
dbfile (String): the name of the sqlite file to create with full or relative path
Creates a sqlite database with the name “dbfile” and connect to it. If any sqlite file
with the same name already exists, the file will be overwritten.
var DB = ledaModules.DATABASE();
DB.deleteOldAndCreateNewSqliteFile("case1");
// Creates case1.qz sqlite file
DB.deleteOldAndCreateNewSqliteFile("./sqlitefile/case2");
// Create folder sqlitefile and case2.qz inside it
44
LedaFlow Scripting Manual v2.4
4.8.3 connectToSqliteFile(dbfile)
dbfile (String): Name of the sqlite file to connect to with full or relative path
Connects to the sqlite file database dbfile. If the file does not exist, a new one will
be created. This is exactly the same as deleteOldAndCreateNewSqliteFile, except
that it does not delete the sqlite file dbfile if this one exists.
4.8.4 connectToFirstCase()
Returns the uuid of the first case of the database to which you are connected to. The
main use is, when you are in a configuration where you want to have one sqlite file
per case.
4.8.5 connectToDatabase(dbname)
dbname (String): Name of the database to connect
Connects the current softshell session to the database dbname. Once you use this,
all operations in that softshell session will be performed in that database. This is the
scripting counterpart of the GUI “Connection and database management-
>Databases->Select among available databases.
var DB = ledaModules.DATABASE();
DB.connectToDatabase("mydatabase2");
4.8.6 getDatabaseNames()
Returns a list of the names of the databases in your database management system
(ex: MariaDB). This is the scripting counterpart of the GUI “Connection and
database management->Databases->Available databases.
45
LedaFlow
var DB = ledaModules.DATABASE();
var availableDatabases = DB.getDatabaseNames();
// availableDatabases is: ["mydatabase1","mydatabase2"]
46
LedaFlow Scripting Manual v2.4
UTILS [Object]
4.9.1 showObj(obj)
obj (Object/Array/Number/String/Boolean): object to show
var a = "Hello";
print("___________________");
UTILS.showObj(a);
print("___________________");
var b = [1,2,3];
UTILS.showObj(b);
print("___________________");
var c = {a:"This is a", b:[1,2,3],c:5};
UTILS.showObj(c);
print("___________________");
/* Screen output:
___________________
"Hello"
___________________
47
LedaFlow
[1, 2, 3
]
___________________
{
"a": "This is a",
"b":
[1, 2, 3
],
"c": 5
}
___________________
*/
4.9.2 loggers(uuid)
uuid (String): uuid of a case
/* Screen output:
[
{
"loggerName": "Pipe 1",
"targetType": "Pipe",
"loggerType": "Profile"
},
{
"loggerName": "Pipe 1 (Trend)",
"targetType": "Pipe",
"loggerType": "Trend"
},
{
"loggerName": "Node 1",
"targetType": "LedaNwNode_nPh_b_1D_massInlet",
"loggerType": "Trend"
},
{
48
LedaFlow Scripting Manual v2.4
4.9.3 pipeLoggers(uuid)
Same as the method “loggers”, but filtering to return only loggers object with
targetType “Pipe” and loggerType “Profile”.
4.9.4 trendLoggers(uuid)
Same as the method “loggers”, but filtering to return only loggers object with
loggerType “Trend”.
4.9.5 psSubcasesWithResults(uuid)
uuid (String): uuid of a parametric study
For a parametric study, returns an array of the sub-cases for which a result exists.
49
LedaFlow
4.9.6 currentDate()
Returns a string with the current date.
print(UTILS.currentDate());
//Output on the screen:
//2016-09-21T10:51:06
50
LedaFlow Scripting Manual v2.4
USERPREFERENCES [Object]
UTILS.showObj(USERPREF.units());
USERPREF.setPreferredUnits();
print(USERPREF.units()["Pressure"]); //for ex:"bara"
USERPREF.setSIUnits();
51
LedaFlow
print(USERPREF.units()["Pressure"]); //”Pa”
USERPREF.setUnitForGroup("atm","Pressure");
print(USERPREF.units()["Pressure"]); //atm
52
LedaFlow Scripting Manual v2.4
UNITS [Object]
var U = ledaModules.UNITS();
var U = ledaModules.UNITS();
var USERPREF = ledaModules.USERPREFERENCES();
54
LedaFlow Scripting Manual v2.4
/* We just take the first trend and profile properties, for sake of
demonstration */
var trendProperty = trendProperties[0];
var profileProperty = profileProperties[0];
/* We print out data from the last point in time, i.e. from the last
object in the array values */
if(values.length > 0)
{
var lastResult = values[values.length-1];
var lastTime = lastResult.time;
var lastValue = lastResult.valueForGivenTime;
print("***PROFILE PROPERTY:"+fullName);
print("TIME:"+lastTime);
print("MESH:"+mesh);
print("PROFILE:"+lastValue);
}
else
{
print("No results populated for this case.");
}
56
LedaFlow Scripting Manual v2.4
Here, for the case “Example” and the logger “Pipe 1”, the user can select among 23
properties: 9 for Heat transfer coefficients, and 14 for Mass flow rate.
The scripting counterpart to this is provided by the module RESULTS. This module
gives a way to generate, for a given case, a list of all logged profile properties
(profile catalog), as well as a list of all logged trend properties (trend catalog).
Each of these logged profile properties and logged trend properties are represented
by an Object. This object has, among others, the attributes loggerName and
displayName.
loggerName is the name of the associated logger. For example: “Pipe 1”.
displayName is the name of the logged variable. It is the same name as the
one visible in the LedaFlow GUI. For example “MFR - gas” or “Heat
transfer - gas-oil”.
Both displayName and loggerName will most likely play an important role when
you wish to filter a catalog to retain only the properties you are interested in, since
the pair (loggerName, displayName) is a unique identifier for a logged property.
57
LedaFlow
For the case “Example” (see snapshot above), the profile catalog will contain the
23 objects:
If you wish to have a full list of the logged properties for your case, i.e. visualize
the trend and profile catalogs, a script is provided in the example folder for this
purpose: ex_catalogCsv.js. This script exports the catalogs to a csv file.
// Import ledaModules
var resMod = ledaModules.RESULTS();
var outFile = ledaModules.FILE();
var cases = ledaModules.CASES();
58
LedaFlow Scripting Manual v2.4
print ("\n > Creating catalog for case ", caseName, "\n");
var catalog = resMod.makeCatalog(uuid);
// Header
str += sep;
for(var k = 0; k < keysToShow.length;k++)
str += keysToShow[k]+sep;
str += "\n\n";
for (j = 0; j < properties.length; j++)
{
var myProperty = properties[j];
str += sep ;
for(var k = 0; k < keysToShow.length; k++)
str += myProperty[keysToShow[k]]+sep;
str += "\n";
}
// writes to output file and opens it
outFile.writeFileFromString(str,filename);
outFile.openWithApplication(filename);
59
LedaFlow
module.writeFileFromString(str,filename);
module.openWithApplication(filename);
60
LedaFlow Scripting Manual v2.4
6 JAVASCRIPT REFERENCE
The following reference section includes descriptions and examples from
javascripting obtained from http://www.w3schools.com/js/js_comparisons.asp
6.1 Comments
Comments can be added to the script to provide explanations of the code or to make
it more readable. Single lines of comments can start with //. Multiple lines can
start with /* and end with */. Using comments is a useful way to prevent execution
of parts of the code during development.
6.2 Variables
Local variables are declared using the “var” keyword:
Each instruction should end with a semicolon for clarity. You can have multiple
instructions on one line separated by semi-colons.
61
LedaFlow
person.lastName;
person["lastName"];
62
LedaFlow Scripting Manual v2.4
objectName.methodName()
name = person.fullName();
If you access the fullName property, without (), it will return the function definition:
name = person.fullName;
6.4 Operators
There are two types of operators in scripting, namely assignment = and arithmetic
+.
63
LedaFlow
64
LedaFlow Scripting Manual v2.4
var x = "Hello";
var y = 5;
var z = x + y; // will give Hello 5, a string
var z = 5 + 5; // will give 10, a number
z = "5"+5; // will give 55, a string
6.5.1 Comparisons
Given x=5, the table below provides explanations of the available comparison
operators:
6.5.2 Logical
Given x=6 and y=3, the table below provides explanations of the available logical
operators:
65
LedaFlow
If age < 18 then the variable voteable will be assigned the value ”Too young”,
otherwise the value would be ” Can vote”.
6.5.4 if...else
The IF ELSE loop executes actions based on the logical conditions.
Syntax
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if neither condition1 nor condition2 is true
}
A simple example is given below where we print ‘yes’ if the i =1, ‘no’ if i=0,
otherwise we print ‘maybe’:
if(i==1)
{
print(“yes”);
}
else if (i==0)
{
66
LedaFlow Scripting Manual v2.4
print(“no”);
}
else
{
print(“maybe”);
}
6.5.5 switch
Use the SWITCH command to choose one of many blocks of code. We have a
single expression n (most often a variable), that is evaluated once. The value of the
expression is then compared with the values for each case in the structure. If there
is a match, the block of code associated with that case is executed. Use break to
prevent the code from running into the next case automatically.
Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
In the following simple example we get today’s day. We have used the default to
specify if there is no match:
67
LedaFlow
case 5:
x="Today it's Friday";
break;
case 6:
x="Today it's Saturday";
break;
default:
x="The Beatles: Eight days a week";
break;
}
6.6 Loops
6.6.1 for
The for...in statement loops through the properties of an object. A for...in loop can
be used to iterate through a range of values replacing them in a string that is then
read by the script.
Syntax
for (variable in object)
{
code to be executed
}
In the following simple example the array person is set up with the variables:
firstname, lastname and age, which are set to the values John, Doe and 25. Printing
txt would give an output of “JohnDoe25”.
68
LedaFlow Scripting Manual v2.4
print(arrayname.length);
// the following loop prints each element of the array to the
command line on a separate line
for( var i = 0; i < arrayname.length; i++ )
{
print( arrayname[ i ] );
}
6.6.2 while
The while loop keeps repeating the operation until the specified condition is not
true.
Syntax
while (variable<endvalue)
{
code to be executed
}
A simple example is given below where we print i starting at ten until it is no longer
greater than zero:
var i = 10;
while ( i > 0 ) {
print( i );
i--;
}
69
LedaFlow
6.7 Functions
A function is a block of code that executes when called. This is useful if you wish
to repeat a sequence of code frequently.
Syntax
function functionname()
{
some code
}
Note that function is in lowercase letters. Also note that the function name is case
sensitive. When calling a function we must use exactly the same capitalisation.
6.7.1 Arguments
When you call a function you can pass values (arguments) to it.
Syntax
function functionname(argument1, argument2)
{
some code
}
//Function call
// will print "HelloWorld"
myFunction("Hello","World");
70
LedaFlow Scripting Manual v2.4
The return statement will cause the function to stop executing. So this can be used
to simply exit a function.
Note: that variables defined within functions are only available within the
function. When we exit the function the variable is destroyed. If a variable is
defined outside a function it can be used within any function.
The table below lists other special characters that can be added to a text string with
the backslash sign:
Code Outputs
\' single quote
\" double quote
\\ backslash
\n new line
\r carriage return
\t Tab
\b backspace
\f form feed
71
LedaFlow
Syntax
include (filename);
6.11 Arrays
6.11.1 Array Object
An array is a variable that can hold more than one value. Arrays can be either
numbers, strings or Boolean. Examples of declaring arrays are given below:
72
LedaFlow Scripting Manual v2.4
6.11.2.2 join()
Joins the arrays into a string.
6.11.2.3 pop()
Removes the last element in an array.
6.11.2.4 push()
Adds a new element to the end of an array.
6.11.2.5 reverse()
Reverses the order of the elements in an array.
73
LedaFlow
6.11.2.6 shift()
Removes the first element of an array.
Note that the first number in the slice is the position of first element that is kept and
the second number is the position of the first element that is removed of the
remaining array. The example has used an array with elements numbered as their
position.
6.11.2.8 sort()
Re-orders the array in ascending order. If the array is of strings the order will be
alphabetical. If the array is numbers the order is following the first digit.
6.11.2.9 splice(index,howmany,item1,...,itemN)
index: An integer that specifies the location to add/remove items. Use negative values
to specify the position from the end of the array.
howmany: The number of items to remove. Use 0 if no items will be removed.
Item1,..., itemN [OPTIONAL]: The new item(s) to be added to the array
74
LedaFlow Scripting Manual v2.4
6.11.2.10 map(function)
The map method creates a new array with the results of calling provided function
on every element in this array.
6.11.2.11 toString()
Converts an array into a string; returning all the elements in the array separated by
commas.
Property Description
E Returns Euler’s number (approximately
2.718)
LN2 Returns the natural logarithm of 2
(approximately 0.693)
LN10 Returns the natural logarithm of 10
(approximately 2.302)
75
LedaFlow
Property Description
LOG2E Returns the base-2 logarithm of E
(approximately 1.442)
LOG10E Returns the base-10 logarithm of E
(approximately 0.434)
PI Returns pi (approximately 3.14)
SQRT1_2 Returns the square root of ½
(approximatively 0.707)
SQRT2 Returns the square root of 2 (approximately
1.414)
Methods
Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x) Returns the arctangent of x as a numeric
value between -PI/2 and PI/2 radians
atan2(y,x) Returns the arctangent of the quotient of
its arguments. The number returned
represents the counterclockwise angle in
radians (not degrees) between the positive
X axis and the point (x, y). Note: With
atan2(), the y coordinate is passed as the
first argument and the x coordinate is
passed as the second argument.
ceil(x) Returns x, rounded upwards to the nearest
integer
cos(x) Returns the cosine of x (x is in radians)
exp(x) Returns the value of Ex
floor(x) Returns x, rounded downwards to the nearest
integer
log(x) Returns the natural logarithm (base E) of
x
max(x,y,z,...,n) Returns the number with the highest value
min(x,y,z,...,n) Returns the number with the lowest value
pow(x,y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Rounds x to the nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle
76
LedaFlow Scripting Manual v2.4
for (i=0;i<10;i++)
{
if (i==3)
{
break;
}
print("The number is " + i);
}
6.13.2 continue
The continue statement will break just the current loop and continue with the loop.
In the syntax example below the output will be 0, 1, 2, 4, 5, 6, 7, 8, and 9.
for (i=0;i<10;i++)
{
if (i==3)
{
continue;
}
print("The number is " + i);
}
}
6.14 try...catch
The try...catch statement allows us to test a block of code for errors. The try block
contains the code to be tested and the catch block contains the code to be executed
if an error occurs.
77
LedaFlow
Syntax
try
{
code to test
}
catch(err)
{
code to execute if there is an error
}
6.15 throw
The throw statement allows us to create an exception and can be used with the
try...catch statement to control program flow and generate error messages.
Syntax
throw exception
var x=74;
var MsgTxt;
try
{
if(x>10)
{
throw "Err1";
}
else if(x<5)
{
throw "Err2";
}
else if(isNaN(x))
{
throw "Err3";
}
}
catch(err)
{
if(err=="Err1")
{
MsgTxt="Error! The value is too high";
}
if(err=="Err2")
78
LedaFlow Scripting Manual v2.4
{
MsgTxt="Error! The value is too low";
}
if(err=="Err3")
{
MsgTxt="Error! The value is not a number";
}
}
print(MsgTxt);
6.16 JSON
6.16.1 JSON Syntax Rules
JSON syntax is derived from JavaScript object notation syntax:
Data is in name/value pairs
Data is separated by commas
Curly braces hold objects
Square brackets hold arrays
"firstName":"John"
Just like JavaScript, JSON objects can contain multiple name/values pairs:
{"firstName":"John", "lastName":"Doe"}
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter","lastName":"Jones"}
]
In the example above, the property "employees" is an array containing three objects.
Each object is a record of a person (with a first name and a last name).
JSON uses JavaScript Syntax
Because JSON syntax is derived from JavaScript object notation, very little extra
software is needed to work with JSON within JavaScript.
With JavaScript you can create an array of objects and assign data to it, like this:
var employees = [
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter","lastName": "Jones"}
];
The first entry in the JavaScript object array can be accessed like this:
employees[0].firstName = "Gilbert";
It can also be modified like this:
employees[0]["firstName"] = "Gilbert";
80
LedaFlow Scripting Manual v2.4
7 OTHERS
When invoked from the regular Windows command line (cmd.exe), softsh always
returns with an error code in the %ERRORLEVEL% variable.
The value 0 indicates success, while a non-zero integer signifies that an error has
occurred.
Below is a list of the individual return codes and their probably causes.
81
LedaFlow
82
LedaFlow Scripting Manual v2.4
/*
ID | Feature | Available
1 | leda_ledaflow | true
2 | leda_integrated | false
3 | leda_steadystate | true
4 | leda_qsash | true
5 | leda_set | true
6 | leda_profileModel | false
7 | leda_1DPointModel | false
8 | leda_steadystateq3d | false
9 | leda_singleCompTrackingCore | true
10 | leda_singleCompTrackingGui | true
11 | leda_fullCompTrackingCore | true
12 | leda_fullCompTrackingGui | true
14 | leda_commercial | true
*/
// ### Example 3:
// Check if LedaFlow (featureID = 1) license is available ###
//
var lic = new LicenseUtils();
var isAvailable = lic.isLicenseAvailable(1);
print(isAvailable) ;
// Example 1
var f = new File();
f.open("Intro2.txt",File.WriteOnly);
f.writeLine("This is the first line of the file");
f.writeLine("This will be the second line");
f.flush(); // Flushes cached content to the physical file
f.writeLine("This will not be flushed until the file is closed");
f.close();
Running a script with the above code creates one file called “Intro2.txt” with the
following content:
This is the first line of the file
84