Download as pdf or txt
Download as pdf or txt
You are on page 1of 84

LedaFlow Scripting Manual v2.

LedaFlow Scripting Manual


v2.4
Scripting

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

Rev. Written by Checked by Approved by


Date Sign. Date Sign. Date Sign.
1 15.08.2012 AEJ 17.08.2012 SØ 28.08.2012 LES
2 01.03.2013 GD 22.03.2013 KPL 22.03.2012 KPL
3 20.03.2014 HJL 27.03.2014 KPL 27.03.2014 KPL
4 31.03.2014 GD 01.04.2014 WD 01.04.2014 WD
5 22.09.2014 HJL 25.09.2014 WD 25.09.2014 WD
6 26.03.2015 GD 26.03.2015 WD 26.03.2015 WD
7 29.09.2015 GD 09.10.2015 WD 09.10.2015 WD
8 10.03.2016 GD 21.03.2016 WD 21.03.2016 WD
9 01.09.2016 GD 21.09.2016 WD 26.09.2016 WD
10 27.03.2017 HJL/GD 28.03.2017 KPL 28.03.2017 KPL
11 10.08.2017 GD/KPL 21.09.2017 WD 21.09.2017 WD
12 21.03.2018 GD 23.03.2018 HJL 23.03.2018 WD

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

2 GETTING STARTED ............................................................................................. 7


2.1 Writing a LedaFlow script ......................................................................................7
2.2 Running a LedaFlow script ....................................................................................8
2.3 Case identifiers .....................................................................................................10

3 EXAMPLES............................................................................................................12

4 LEDAFLOW SCRIPTING REFERENCE .......................................................... 14


4.1 Introduction ..........................................................................................................14
4.2 Module CALCULATE .........................................................................................14
4.3 Module CASES ....................................................................................................19
4.4 Module RESULTS ............................................................................................... 23
4.5 Module FILE ........................................................................................................31
4.6 Module FULLRESULTS .....................................................................................35
4.7 Module REQUEST ............................................................................................... 39
4.8 Module DATABASE ........................................................................................... 44
4.9 Module UTILS .....................................................................................................47
4.10 Module USERPREFERENCES ...........................................................................51
4.11 Module UNITS .....................................................................................................53

5 SCRIPTING IN LEDAFLOW : FAQ ..................................................................55


5.1 How to create a case from an input file ? ............................................................. 55
5.2 How to delete a case? ........................................................................................... 55
5.3 How to run a simulation? .....................................................................................55
5.4 How to extract results? .........................................................................................55
5.5 How to visualize the list of properties logged? ....................................................56
5.6 How to generate text files? ...................................................................................59
5.7 How to create parametric studies ? .......................................................................60

6 JAVASCRIPT REFERENCE ...............................................................................61


6.1 Comments .............................................................................................................61
6.2 Variables ...............................................................................................................61
6.3 JavaScript Objects ................................................................................................ 61
6.4 Operators ..............................................................................................................63
6.5 Comparisons and Logical Operators ....................................................................65
6.6 Loops ....................................................................................................................68
4
LedaFlow Scripting Manual v2.4

6.7 Functions ..............................................................................................................70


6.8 Special Text (escape sequences)...........................................................................71
6.9 Calling one script from another ............................................................................71
6.10 Printing results to the command window ............................................................. 72
6.11 Arrays ...................................................................................................................72
6.12 Math Object ..........................................................................................................75
6.13 Break Loops ..........................................................................................................77
6.14 try...catch ..............................................................................................................77
6.15 throw .....................................................................................................................78
6.16 JSON.....................................................................................................................79

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

2.1 Writing a LedaFlow script


To write a LedaFlow script you need a text editor.
 You can use the text editor provided in the LedaFlow GUI.

It supports basic features:

Shortcut Keys Description


Ctrl + A Select all
Ctrl + C Copy
Ctrl + F Search
Ctrl + I Indentation of selection
Ctrl + L Go to line
Ctrl + O Open a file
Ctrl + S Save a file
Ctrl + V Paste
Ctrl + X Cut
Ctrl + Y Redo
Ctrl + Z Undo
Ctrl + +/- Zoom / Unzoom

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.

2.2 Running a LedaFlow script


To “run” a script, you can either use the LedaFlow GUI, or the LedaFlow shell
application called “softsh” (for “Soft Shell”) provided in the LedaFlow folder
(typically in C:\Program Files (x86)\Kongsberg\LedaFlow Engineering)

2.2.1 From the LedaFlow GUI


To run a script from the client, select the script sheet you want to run and:
 Click the on the “run” button

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

2.2.2 From the command line


It is possible to run a script by using the LedaFlow script engine “softsh” from a
command prompt.
Note: if you open a command prompt, “softsh” will not be recognized, since it is
not in the path.
To run a script from the command line, you need to open a LedaFlow cmd. To do
so, click on the shortcut “LedaFlow® command prompt”.

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.

2.3 Case identifiers


2.3.1 What is the “uuid” of case?
In LedaFlow, when you import an input file or create a new case, some data
structures are created in the database. A case can be run by the simulator only if it
exists in the database.
The “uuid” is a unique identifier associated to each case, and is the way to refer to
it.

10
LedaFlow Scripting Manual v2.4

2.3.2 How to find the uuid of a case?


2.3.2.1 From the LedaFlow GUI
The uuid of an existing case can be found from the LedaFlow GUI by right selecting
on a case in the Case Browser and selecting the option Show Case ID. This gives
the case uuid similar to the following screenshot.

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.

2.3.2.2 From scripting


When you create a case by using the CASES module method:
createCaseFrom(inputfile), this methods returns a Javascript object. This object has
an attribute “uuid”.

var CASES = ledaModules.CASES();


var caseObj = CASES.createCaseFrom("ex.qs");
var uuid = caseObj.uuid;

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.

File Main Short description


module(s)
ex_backupAllDatabases.js DATABASE Backup all your databases into qz files
FILE
ex_csvCatalog.js RESULTS Write catalogs of properties to csv file
FILE
ex_generateSimpleHtml.js FILE Create an html file to show some
RESULTS results.
ex_networkAnalysis.js RESULTS Create a csv file showing calculated
FILE results (averages, min, max..etc) for a
set of given properties and for all pipes
of a network
ex_oneSqlitePerFile.js DATABASE Create, run and extract results from
cases using only files. One sqlite file is
associated with one case.
ex_requestModule.js REQUEST Illustrates all requests available from
the REQUEST module
ex_restartFiles.js CALCULATE Create a case from an input file,
initialize and run this case, generate a
restart file based on the last time
sample.
Then create new cases (typically based
on modified input file), initialize them
with restart file created and run them.
ex_turndownCurve.js CALCULATE Create a parametric study for any case
RESULTS with a mass flow rate parameter and run
FILE it. Extract parametric results and
generate an html file to show a
turndown plot.
snippet_createAFile.js FILE Demonstrate the methods to generate a
file from FILE module

12
LedaFlow Scripting Manual v2.4

File Main Short description


module(s)
snippet_createAndRunACase.js CASES Demonstrate how to create a case from
CALCULATE an input file and run it
snippet_createAndRunAParam CASES Demonstrate how to create a parametric
etricStudy.js CALCULATE study from an input file and run it
snippet_createCase.js CASES Demonstrate how to create a case from
an input file
snippet_createInputFile.js CASES Demonstrate how to generate an input
file for a given case
snippet_database.js DATABASE Demonstrate some of the methods of
the DATABASE module
snippet_exportCases.js CASES Demonstrate all the methods from
CASES to export cases to qz files
snippet_extractResults.js RESULTS Demonstrate how to extract results
snippet_findingCases.js CASES Demonstrate how to find cases in your
current database
snippet_fullresultsdump.js FULLRESULTS Demonstrate all the methods of the
FULLRESULTS module
snippet_olgaConversion.js CASES Demonstract how to convert an Olga
input file and to create the
corresponding LedaCase

13
LedaFlow

4 LEDAFLOW SCRIPTING REFERENCE

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();

4.2 Module CALCULATE


4.2.1 Overview
The module CALCULATE gathers all methods related to running simulations.

var calculateModule = ledaModules.CALCULATE();

ledaModules.CALCULATE() [Object]

Attributes Type Description


setCaseId(uuid) Function Set the current case id for
the module
calculateSS(uuid) Function To run steady-state
preprocessor.
calculate(uuid) Function To run transient
calculations.
writeRestartFile(sample, Function To write a restart file
restartfile,uuid)
loadRestartFile(restartfile, Function To initialize with a restart
reset,uuid) file.
nSamples(uuid) Function Number of global time samples
calculateSSParametric(uuid) Function To run steady-state on a
parametric study.
calculateParametric(uuid) Function To run transient on a
parametric study.
purge(type,reset,uuid) Funtion To purge results

4.2.2 setCaseId(uuid)
uuid (String): uuid of the case to set for the module

14
LedaFlow Scripting Manual v2.4

Assign a case id to the module.

var calcModule = ledaModules.CALCULATE();


var caseId = "9da8e6b2-e8b8-43df-8b9d-00f03c96f062";
calcModule.setCaseId(caseId);
// do things on case 1
var caseId2 = "5da8e6b2-e8b8-43df-8b9d-00f03c96f062";
calcModule.setCaseId(caseId2);
// do things on case 2

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.

var calcModule = ledaModules.CALCULATE();


var caseId = "9da8e6b2-e8b8-43df-8b9d-00f03c96f062";
calcModule.setCaseId(caseId);
calcModule.calculateSS();

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.

var calcModule = ledaModules.CALCULATE();


var caseId = "9da8e6b2-e8b8-43df-8b9d-00f03c96f062"
calcModule.calculateSS(caseId);

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.

var calcModule = ledaModules.CALCULATE();


var caseId = "9da8e6b2-e8b8-43df-8b9d-00f03c96f062";
calcModule.setCaseId(caseId);

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.

var calcModule = ledaModules.CALCULATE();


var caseId = "9da8e6b2-e8b8-43df-8b9d-00f03c96f062";

calcModule.calculate(caseId);

4.2.5 writeRestartFile(sample, restartfile, uuid)


sample (Number): index of the global time sample
restartfile (String): name of the restart file (with full or relative path)
uuid (String) [OPTIONAL]: uuid of the case

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.

var calcModule = ledaModules.CALCULATE();


var caseId = "9da8e6b2-e8b8-43df-8b9d-00f03c96f062";
calcModule.setCaseId(caseId);

calcModule.writeRestartFile(4,”myrestartfile.lrs”);

4.2.6 loadRestartFile(restartfile, reset, uuid)


restartfile (String): name of the restart file (with full or relative path)
reset (Boolean) : to reset time to 0 or not
uuid (String) [OPTIONAL]: uuid of the case

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.

var calcModule = ledaModules.CALCULATE();


var caseId = "9da8e6b2-e8b8-43df-8b9d-00f03c96f062";
calcModule.setCaseId(caseId);

calcModule.loadRestartFile(”myrestartfile.lrs”, true);

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.

var calcModule = ledaModules.CALCULATE();


var caseId = "9da8e6b2-e8b8-43df-8b9d-00f03c96f062";
calcModule.setCaseId(caseId);

var nSamples = calcModule.nSamples();
calcModule.writeRestartFile(nSamples,”myrestartfile.lrs”);

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.

var calcModule = ledaModules.CALCULATE();


var studyId = "9da8e6b2-e8b8-43df-8b9d-00f03c96f062";
calcModule.calculateSSParametric(studyId);

var calcModule = ledaModules.CALCULATE();


var caseModule = ledaModules.CASES();
var inputFile_absolutePath =
"C:/Kongsberg/LedaFlowSampleCases/v2.2/FlowlineRiser_linesizing.1D,
3 phases, Table, Parametric.qs";
var myCase = caseModule.createCaseFrom(inputFile_absolutePath);
calcModule.calculateSSParametric(myCase.psUuid);
See snippet_createAndRunParametricStudy.js.

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.

var calcModule = ledaModules.CALCULATE();


var studyId = "9da8e6b2-e8b8-43df-8b9d-00f03c96f062";
calcModule.calculateParametric(studyId);
See also snippet_createAndRunParametricStudy.js.

4.2.10 purge(type, reset, uuid)


type (String): type of purging (“KeepFirst” or “KeepLast”)
reset (Number): reset the time to 0 or not
uuid (String): uuid of a case. OPTIONAL if uuid has been set using “setCaseId”

Purge all the results keeping only one global sample.


“type” defines if this global sample should be the first or last one.”type” can be
either “KeepFirst” or “KeepLast”.
“reset” defines if you want to reset the time to 0s or leave it as it is. “reset” can be
0 or 1. 0 if you do not want to reset, 1 if you do want to reset the time to 0s.
If you set an id in the module, using “setCaseId” (advised), the uuid argument
is not needed.

var calcModule = ledaModules.CALCULATE();


var caseId = CASE_SELECTED.uuid;
calcModule.setCaseId(caseId);
calcModule.calculateSS();
calcModule.calculate();
//Purge all results keeping only the last global sample without
resetting the time
calcModule.purge("KeepLast",0,caseId);

18
LedaFlow Scripting Manual v2.4

4.3 Module CASES


4.3.1 Overview
The CASES module is the script counterpart to the LedaFlow GUI case browser. It
enables you import/export cases, inspect the existing cases in your current project
(database).

var casesModule = ledaModules.CASES();

ledaModules.CASES() [Object]

Attributes Type Description


caseobj(uuid) Function Returns a case object
visibleCases() Function List the visible cases
createCaseFrom(inputfile) Function Create case from input file
removeCase(uuid) Function Remove case
findCasesWithName(regexp) Function Find cases with a given
name among the visible
cases
findFirstCaseWithName(reg) Function Find first case with given
name among the visible
cases
writeInputFile(inputfile, Function Write input file
uuid,pvtTableEmbedded)
convertOlgaFile(olgaFile, Function Convert Olga input file to
ledaFile) LedaFlow input file
showCases() function Print the folder and case
structure of the current
database, like seen in the
case browser.
exportAllCases(dbfile) function Export all cases and
folders in the current
database to a file. This is
the same as exporting the
root folder to .qz in the
GUI.
exportFolder(folderid,dbfile function Export a folder and all its
) sub-folders and cases to a
file. This is the same as
exporting a folder to .qz
in the GUI.

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:

Case object [Object]

Attributes Type Description


uuid String Case id of the case
name String Name of the case
phases String “2-ph” or “3-ph”
created String Creation date

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

Output structure: Object

Create a case in the current project (database), based on the given input file, and
returns a case object (see 4.3.2)

var CASES = ledaModules.CASES();


var caseObj = CASES.createCaseFrom("ex.qs");
This will create a case inside your database, the same way a case is created in your
database when you import an input file in the LedaFlow GUI.
See example snippet_createCase.js.

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.

var casesMod = ledaModules.CASES();


var caseId = "2efefcad-e6c9-4cc6-a6e9-cfc845a388ce";
casesMod.removeCase(caseid);

20
LedaFlow Scripting Manual v2.4

See example snippet_createAndRunACase.js.

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.

var casesMod = ledaModules.CASES();


var casesNamedTEST = casesMod.findCasesWithName("TEST");
var reg = new RegExp("gas");
var casesWithGas = casesMod.findCasesWithName(reg);

4.3.7 findFirstCaseWithName(name)
name (String) : name of the case to find

Provided for convenience, this method returns the first element of


findCasesWithName(name).

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.

4.3.9 convertOlgaFile(olgaFile, ledaFile)


olgaFile (String) : name of the Olga input file with full or relative path
ledaFile (String) : name of the LedaFlow input file generated with full or relative path

Convert an Olga 5, 6, or 7 input file “olgaFile” to a LedaFlow input file “ledaFile”.


The function returns a Boolean: true if the conversion was successful. It generates
and saves a conversion report in HTML format (same name as ledaFile but with the
extension .html). In case something went wrong, it retrieves a descriptive error
message.
See example snippet_olgaConversion.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

4.4 Module RESULTS


4.4.1 Overview
The RESULTS module gathers all methods related to extraction of results.

var resultsModule = ledaModules.RESULTS();

ledaModules.RESULTS() [Object]

Attributes Type Description


makeCatalog(uuid) Function Create a results properties
catalog object
makeExtractor(uuid) Function Create an result extractor 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]

Attributes Type Description


trends Array List of all trends properties
available for the given case.
profiles Array List of all profiles properties
available for the given case.
filterTrends(filter, Function To filter the trends properties
strict)
filterProfiles(filter, Function To filter the profiles properties
strict)
fullName(property) Function Full name of a trend or profile
property

23
LedaFlow

4.4.2.1 trends
Type: array

Structure: [trendprop1, … , trendpropn]

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.

var uuid = CASE_SELECTED.uuid;


var RES = ledaModules.RESULTS();
var catalog = RES.makeCatalog(uuid);
UTILS.showObj(catalog.trends);

trendProperty [Object]

Attributes Type Description


intid Integer The id for the trend property
loggerName String
Name of the logger where the
trend properties is defined
displayName String Name of the property
field String Name of the field. For example
“Gas”
unitGroup String Name of the unit group of the
property. For example “Pressure”.
defaultUnit String Unit of the property. This unit
will be equal to the one defined
in the user preferences in the
LedaFlow GUI for the given unit
group. For example “bar”
All other attributes: logProperty, componentIndex, zElementIndex,
plotObjectType… are used by softsh to retrieve results and are not
relevant from a user point of view

4.4.2.2 profiles
Type: array

Structure: [profileprop1, … , profilepropn]


Array of “profile properties” defined in all profile loggers of the case. A “profile
property” is an object with many attributes. The relevant ones for a user are shown
in the table below.
24
LedaFlow Scripting Manual v2.4

var uuid = CASE_SELECTED.uuid;


var RES = ledaModules.RESULTS();
var catalog = RES.makeCatalog(uuid);
UTILS.showObj(catalog.profiles);

profileProperty [Object]

Attributes Type Description


intid Integer The id for the trend property
loggerName String Name of the logger where the
trend properties is defined
displayName String
Name of the property. This name
is self-explanatory. The pair
(loggerName,displayName) is a
unique identifier for a property.
I.e. it will be at most 1
property with a given loggerName
and a given displayName for a
given case.

field String Name of the field. For example


“Gas”
unitGroup String Name of the unit group of the
property. For example “Pressure”.
defaultUnit String Unit of the property. For example
“bar”
cellType String Is “cellBoundary” or “cellCenter”
“cellBoundary” for properties
given on the boundaries of the
mesh cells (like Mass flow
rates), “cellCenter” for
properties given in cell centers
of the mesh cells (like Pressure)
All other attributes: logProperty, componentIndex, zElementIndex,
plotObjectType… are used by softsh to retrieve results and are not
relevant from a user point of view

25
LedaFlow

4.4.2.3 filterTrends(filter, strict)


filter (Object) : filter object
strict(Boolean): exact match or not

Output structure: [trendprop1,…,trendpropq]

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.4 filterProfiles(filter, strict)


filter (Object) : filter object
strict(Boolean): exact match or not

Output structure: [profileprop1,…,profilepropq]


Similar to filterTrends, but for profiles.

4.4.2.5 fullName(property)
property (Object) : profile or trend property

Returns the “full name” of the property by building the string:


property.loggerName+”_”+property.displayName.

26
LedaFlow Scripting Manual v2.4

For a given case, each property has a unique full name.

var uuid = CASE_SELECTED.uuid;


var RES = ledaModules.RESULTS();
var catalog = RES.makeCatalog(uuid);

for(var i = 0; i < catalog.trends.length; i++) {


var trendProperty = catalog.trends[i];
print(catalog.fullName(trendProperty));
}
for(i = 0; i < catalog.profiles.length; i++) {
var profileProperty = catalog.profiles[i];
print(catalog.fullName(profileProperty));
}

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]

Attributes Type Description


id String Uuid of the case given
as input
catalog Object Catalog object (see
previous section)
getTrendTimes() Function Returns array of times
for trends properties
getProfileTimes() Function Returns array of times
for profile properties
getTrendValuesForAllTimes Function Returns results for all
(trendProperty) times for a given trend
property
getProfileValuesForAllTimes Function Returns results for all
(profileProp) times for a given
profile property
setSubCase(subCaseIndex) Function Only for Parametric
studies. Select the
subCaseIndex.

27
LedaFlow

4.4.3.1 id
Type: String
Case id given as an input

var uuid = CASE_SELECTED.uuid; // ”50f6d985-3957-425b-b653-


c5a3591d375b"
var RES = ledaModules.RESULTS();
var extractor = RES.makeExtractor(uuid);

var caseid = extractor.id;


// caseId is "50f6d985-3957-425b-b653-c5a3591d375b"

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.

var uuid = CASE_SELECTED.uuid;


var RES = ledaModules.RESULTS();
var extractor = RES.makeExtractor(uuid);
var catalog = extractor.catalog;

for(var i = 0; i < catalog.trends.length; i++) {


var trendProperty = catalog.trends[i];
print(catalog.fullName(trendProperty));
}
for(i = 0; i < catalog.profiles.length; i++) {
var profileProperty = catalog.profiles[i];
print(catalog.fullName(profileProperty));
}

//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.

var uuid = CASE_SELECTED.uuid;


var RES = ledaModules.RESULTS();
var extractor = RES.makeExtractor(uuid);
var trendTimes = extractor.getTrendTimes();
// trendTimes is for ex:[0,10,20,30,40,50]

4.4.3.4 getProfileTimes( )
Output: [t0, t1,…,tn]
Function that returns the array of time points for trends variables.

var uuid = CASE_SELECTED.uuid;


var RES = ledaModules.RESULTS();
var extractor = RES.makeExtractor(uuid);
var profileTimes = extractor.getProfileTimes();
// profile times is for ex:[0,60,120,180,240,300]

4.4.3.5 getTrendValuesForAllTimes(trendProperty)
trendProperty (Object) : an element of the catalog.trends

Output structure:

{ property:trendProperty, time:[t0,…,tn], value:[vt1,…,vtn ] }


Function that returns an object containing trend results for the property
“trendProperty”. “trendProperty” needs to be a property of the extractor catalog.
The object returned has several attributes:

getTrendValuesForAllTimes(trendProperty) [Object]

Attributes Type Description


property Object A copy of the input trend property
time Array[number] Array of the trends time
value Array[number]
Array of the results values for the
trend property. The unit is the unit
associated to trendProperty, and each
value corresponds to the time value
with same index given in the time
array.

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]

Attributes Type Description


property Object A copy of the input profile
property
mesh Array[number] the mesh (l-coordinates) to
which the property is associated
values Array[Object] An array of objects. Each object
[ {time: t0, contains a property time (single
valueForGivenTime:[v1,…,vq]},…, number) and a property
{time: tn, valueForGivenTime.
valueForGivenTime:[v1,….,vq]} ] valueForGivenTime is an array of
values. The unit used is the one
defined in the profile property
and each index corresponds to a
a mesh index.

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

4.5 Module FILE


4.5.1 Overview
The FILE module gathers methods related to reading and writing files.

ledaModules.FILE() [Object]

Attributes Type Description


openWithApplication(filename) Function Open with the application
associated to the filename
extension
fileExists(filename) Function Check if a file exists
folderExists(path) Function Check if a folder exists
currentPath() Function Returns current path
createFolder(path) Function Create a folder
writeFileFromTemplate(data, Function Write a file based on a
template, filename) template and a data object
writeFileFromString(string, Function Write a file based on a
filename) string
writeJsonFileFromObject(object, Function Write an object to file in
filename) JSON
readJsonFile(filename) Function Read a file using JSON
and returns the
corresponding object
csvRow(list,pickerParameter, Function Utility method to help
separator) building csv files

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.

var module = ledaModules.FILE();


var filename = "mytestfile.txt";
//Open mytextfile.txt with application associated to “.txt”
module.openWithApplication(filename);

4.5.2 currentPath()

Returns the current path, i.e. the path of the script file in use.
31
LedaFlow

var fileModule = ledaModules.FILE();


print(fileModule.currentPath());
// C:/Users/guyde/Desktop

4.5.3 fileExists(filename)
filename (String): file name including full path

Check if the file exists. Returns true if file exists, false otherwise.

var fileModule = ledaModules.FILE();


var exists = fileModule.fileExists("C:/Kongsberg/file.txt");

4.5.4 folderExists(path)
path (String): full path to folder

Check if the folder exists. Returns true if folder exists, false otherwise.

var fileModule = ledaModules.FILE();


var exists = fileModule.folderExists("C:/Kongsberg");

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).

var fileModule = ledaModules.FILE();


// Creates folder fileModule.currentPath()/TESTSCRIPT
var relativePathExample = "TESTSCRIPT";
var folder1Created = fileModule.createFolder(relativePathExample);
if(folder1Created)
print(fileModule.currentPath()+"/"+relativePathExample+" has been
created");
else
throw "Folder "+relativePathExample+" not created";

var fullPathExample = "C:/TEST";

// Create folder C:/TEST


var folder2Created = fileModule.createFolder(fullPathExample);
if(folder2Created)
print(fullPathExample+" has been created");
else
throw (fullPathExample+" not created");

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

var OUT = ledaModules.FILE();


var mydata = {
hello: ["Hello","dear","LedaFlow","User"],
goodIdea: "LedaFlow script rocks!"};
var template = "template_ex.txt";
var output = "outputfile.txt";

OUT.writeFileFromTemplate(mydata, template, output);


OUT.openWithApplication(output);

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

See example ex_generateSimpleHtml.js.

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.

var module = ledaModules.FILE();

var str = "Hello LedaFlow user";


var filename = "createAFile_fromString.txt";
module.writeFileFromString(str,filename);
module.openWithApplication(filename);

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

*/

var readObject = F.readJsonFile("test.json");


print(readObject.a);
print(readObject.b);

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.

var OUT = ledaModules.FILE();


var list = [{a:"hello user",b:123,c:{p1:1,p2:2}},{a:"This is an
example",b:456, c:{p1:3,p2:4}}];
var k1 = OUT.csvRow(list, "b");
var k2 = OUT.csvRow(list, ["c","p1"]);
var k3 = OUT.csvRow(list, function(k){return k.a+"!!!!!"});

print("k1:"+k1);
print("k2:"+k2);
print("k3:"+k3);

/*
k1:123,456,
k2:1,3,
k3:hello user!!!!!,This is an example!!!!!,
*/

4.6 Module FULLRESULTS


4.6.1 Overview

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.

See example snippet_fullresultsdump.js.

var fullRModule = ledaModules.FULLRESULTS();

35
LedaFlow

ledaModules.FULLRESULTS() [Object]

Attributes Type Description


setUuid Function Set the case uuid on which
the module is going to
extract and dump results
to file
setSubcases(subcases) Function Only useful for parametric
studies.
Set the specific subcases
(array of indices like:
[1,2,3] or number).
Counterpart of “Export
only for” in the LedaFlow
GUI. If not used, all
subcases will be exported.
trendLoggersToSvFile Function Dump all properties of all
trend loggers of the case
to a single separated
values file. The separator
used is the one defined
by:
USERPREF.setListSeparator
trendLoggersToJsonFile Function Dump all properties of all
trend loggers of the case
to a single json file
profileLoggersToSvFile Function Dump all properties of all
profile loggers to a
single separated values
file. The separator used
is the one defined by:
USERPREF.setListSeparator.
profileLoggersToJsonFile Function Dump all properties of all
profile loggers to a
single json file (slow and
results in a very large
file. Use only for
specific purposes).

4.6.2 setUuid(uuid)
uuid (String): uuid of a case

36
LedaFlow Scripting Manual v2.4

Assign a case id (uuid of a case or parametric study) to the module. This is


mandatory, to use any of the module methods.

fullRModule.setUuid("530cd8d6-32f4-4f69-990e-ba1ad89b426b");

4.6.3 trendLoggersToSvFile(filename, loggersnames)


filename (String): name of a file, with full or relative path
loggersnames (Array of String) [OPTIONAL]: trend loggers to take into account. If no names are
provided, all trend loggers will be taken into account.

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");

4.6.4 trendLoggersToJsonFile(filename, loggersnames)


filename (String): name of a file, with full or relative path
loggersnames (Array of String) [OPTIONAL]: trend loggers to take into account. If no names are
provided, all trend loggers will be taken into account.

This method will dump all the trend loggers to a single json file filename

var fullRModule = ledaModules.FULLRESULTS();


var uuid = CASE_SELECTED.uuid;
fullRModule.setUuid(uuid);
fullRModule.trendLoggersToJsonFile("trends.json");

4.6.5 profileLoggersToSvFile(filename, loggersnames)


filename (String): name of a file, with full or relative path
loggersnames (Array of String) [OPTIONAL]: profile loggers name to take into account. If no
names are provided, all profile loggers will be taken into account.

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");

4.6.6 profileLoggersToJsonFile(filename, loggersnames)


filename (String): name of a file, with full or relative path
loggersnames (Array of String) [OPTIONAL]: profile loggers name to take into account. If no
names are provided, all profile loggers will be taken into account.

This method will dump all the results from all the profile loggers or only the ones
specified by loggersnames to a json file filename.

var fullRModule = ledaModules.FULLRESULTS();


var uuid = CASE_SELECTED.uuid;
fullRModule.setUuid(uuid);
fullRModule.profileLoggersToJsonFile("profiles.json");

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

4.7 Module REQUEST


4.7.1 Overview
The REQUEST module is a high level module (i.e, internally using several other
modules) and offers the possibility to request predefined type of information on a
case. The result of the request will be written to a file.

var requestModule = ledaModules.REQUEST();

See example ex_requestModule.js.

ledaModules.REQUEST() [Object]

Attributes Type Description


request(requestObject) Function Write file containing
requested information
keys Object Contains all the available
keys for a request
reportToUi Function To enable/disable
reporting to LedaFlow GUI

4.7.2 request(requestObject)
requestObject (Object): object containing information on what is requested

The method request takes a request object requestObject as argument. A request


object is a Javascript object with different attributes. The common attributes for a
request object are shown in the table below.

requestObject [Object]

Attributes Type Description


requested String This is a keyword. The accepted keywords
are:
"TRENDCATALOG"
"PROFILECATALOG"
"TREND"
"PROFILE"
"STATUS"
"CASEINFO",
"NETWORKINFO"
"FULLTRENDS"
"FULLPROFILES"

39
LedaFlow

requestObject [Object]

Attributes Type Description


filename String Name of the output file (both full and
relative path are accepted)
uuid String Uuid of the case to treat
(OR) String Name of the sqlite file to connect to.
sqliteFilename First case of the file will be used. This
is useful if you are in the configuration
of working with one SqliteFile per case.
In this case the “uuid” property is not
needed and is discarded.

4.7.3 Trend catalog request (TRENDCATALOG)


This request dumps the trend catalog to a json file. No extra attributes needed.

var requestModule = ledaModules.REQUEST();


//Defines the request object
var requestObject = {
requested : "TRENDCATALOG",
filename : "tcatalog.json",
uuid : "50f6d985-3957-425b-b653-c5a3591d375b"
}
//Call the request method
requestModule.request(requestObject);

4.7.4 Profile catalog request (PROFILECATALOG)


This request dumps the profile catalog to a json file. No extra attributes needed.

var requestModule = ledaModules.REQUEST();


//Defines the request object
var requestObject = {
requested : "PROFILECATALOG",
filename : "pcatalog.json",
uuid : "50f6d985-3957-425b-b653-c5a3591d375b"
};
//Call the request method
requestModule.request(requestObject);

40
LedaFlow Scripting Manual v2.4

4.7.5 Trend request (TREND)


This request dumps the results of a trend property to a json file. Extra attributes are
needed:

requestObject [Object]

Attributes Type Description


trendCatalogFilename String Name of the trend catalog file
(catalog file needs to be present)
propId Integer Id of the trend property in the
catalog

var requestModule = ledaModules.REQUEST();


requestModule.request(
{
requested : "TREND",
filename : "trendproperty.json",
uuid : "50f6d985-3957-425b-b653-c5a3591d375b"
trendCatalogFilename : "tcatalog.json",
propId : 5,
});

4.7.6 Profile request (PROFILE)


This request dumps the results of a trend property to a json file. Extra attributes are
needed:

requestObject [Object]

Attributes Type Description


profileCatalogFilename String Name of the profile catalog file.
propId Integer Id of the profile property in the
catalog

var requestModule = ledaModules.REQUEST();


requestModule.request(
{
requested : "PROFILE",
filename : "profileproperty.json",
uuid : "50f6d985-3957-425b-b653-c5a3591d375b"
trendCatalogFilename : "pcatalog.json",
propId : 5,
});

41
LedaFlow

4.7.7 Full trends request (FULLTRENDS)


This request dumps to a file the results of all trend properties defined in a given json
catalog file. Extra attributes are needed:

requestObject [Object]

Attributes Type Description


trendCatalogFilename String Name of json profile catalog file to
be used
folder (instead of String The path of the folder where to create
“filename”) the case. The name of the file itself
will be casename_trends
extension String Use “.json” for json file. Any other
type of extensions will export as a
separated values file.

requestModule.request(
{
requested : "FULLTRENDS",
folder : ".",
uuid : "50f6d985-3957-425b-b653-c5a3591d375b",
trendCatalogFilename : "tcatalog.json",
extension : ".csv",
});

4.7.8 Full profiles request (FULLPROFILES)


This request dumps to a file the results of all profile properties defined in a given
json catalog file. Extra attributes are needed:

requestObject [Object]

Attributes Type Description


profileCatalogFilename String Name of the json profile catalog
file to be used
folder (instead of String The path of the folder where to
“filename”) create the case. The name of the
file itself will be
“casename_profiles”.
extension String Use “.json” for json file. Any other
type of extensions will export as a
separated values file.

42
LedaFlow Scripting Manual v2.4

requestModule.request(
{
requested : "FULLPROFILES",
folder : ".",
uuid : "50f6d985-3957-425b-b653-c5a3591d375b",
profileCatalogFilename : "pcatalog.json",
extension : ".csv"
});

4.7.9 Status request (STATUS)

requestModule.request(
{
requested : "STATUS",
filename : "status.json",
uuid : "50f6d985-3957-425b-b653-c5a3591d375b"
});

43
LedaFlow

4.8 Module DATABASE


4.8.1 Overview
The DATABASE module gathers methods related to database connections, display
of database contents and export functionality.

var dbModule = ledaModules.DATABASE();

ledaModules.DATABASE() [Object]

Attributes Type Description


deleteOldAndCreateNewSqliteFile(dbfile) function Create and connect
to a given sqlite
file
connectToSqliteFile(dbfile) function Connect to an
existing sqlite
file
connectToFirstCase() function Returns the uuid of
the first case
available in the
current database
connection
connectToDatabase(dbname) function Connect to an
existing database
in the database
management system
(ex: MariaDB)
getDatabaseNames() function Get a list of the
names of the
available databases

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

4.9 Module UTILS


UTILS is a library of several (non-releated) methods.

UTILS [Object]

Attributes Type Description


showObj(jsObject) Function Print a javascript
object in JSON
loggers(uuid) Function Return an array of
objects representing all
loggers for a given case
pipeLoggers(uuid) Function Same as loggers, but
returning only profile
loggers
trendLoggers(uuid) Function Same as loggers, but
returning only trend
loggers
psSubcasesWithResults(uuid) Function Only for Parametric
studies. Returns a list
of sub-cases indices
with a result
currentDate() Function Returns a string with
the current date

4.9.1 showObj(obj)
obj (Object/Array/Number/String/Boolean): object to show

This function prints to the screen the content of obj, in JSON.

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

Output (Array): [loggerObj1, loggerObj2,…,loggerObjn]

loggerObj is of the form: {loggerName:.., targetType:…,loggerType:…}


For the case with identifier uuid, returns an array of logger object. Each logger
object has three attributes: loggerName (the name of the logger, as referenced in
the LedaFlow GUI), targetType (the type of the object on which is logging, for
example “Pipe”), and the loggerType (it can be either “Profile” or “Trend”).

var uuid = CASE_SELECTED.uuid;


var loggers = UTILS.loggers(uuid);
UTILS.showObj(loggers);

/* 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

"loggerName": "Node 2",


"targetType": "LedaNwNode_nPh_b_1D_pressureInlet",
"loggerType": "Trend"
},
{
"loggerName": "Global",
"targetType": "LedaImplicitNetwork",
"loggerType": "Trend"
}
]
*/

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.

var caseId = CASE_SELECTED.uuid;


var subcases = UTILS.psSubcasesWithResults(caseId));
//subcases = [2,3,4]

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

4.10 Module USERPREFERENCES


USERPREFERENCES is an object used to set Users Preferences.

USERPREFERENCES [Object]

Attributes Type Description


listSeparator() Function Returns the value
separator used to create
separated values files
setListSeparator(sep) Function Set the value separator
used to create separated
values files to sep
decimalSeparator() Function Returns the decimal
separator used to created
separated values files
setDecimalSeparator(sep) Function Set the decimal separator
used to create separated
values files to sep
setPreferredUnits() Function Set the unit for each unit
group to the ones
registered in the user
preferences (in LedaFlow
GUI).
setSIUnits() Function Set all default units for
each unit group to SI
units.
setUnitForGroup(unit,unitGroup) Function Set the unit unit as
default unit for the unit
group unitGroup
units() Function Returns an object which
keys are unit groups and
values are corresponding
desired units.

var USERPREF = ledaModules.USERPREFERENCES();


USERPREF.setListSeparator(";");
print(USERPREF.listSeparator());
USERPREF.setDecimalSeparator(",");

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

4.11 Module UNITS


The UNITS module provides access to LedaFlow’s unit conversion system.
Internally LedaFlow operates exclusively in SI units, but in practical use one
seldomly deal with those directly. The LedaFlow Engineering GUI permits a user
to either use some of the standard unit sets or even select which custom units to
display results in. For example, it is quite common to use psi or bar instead of Pa
for pressure.
A unit group is a collection of alternative units for a particular physical property.
Consider for example the unit group “Temperature”. Among the available units
within that unit group we have K, °C and °F. So while LedaFlow internally always
operates on temperatures in K, a user should be able to easily work with in any
preferred unit without caring much about the conversion.

UNITS [Object]

Attributes Type Description


siToValue(val, unitGroup, unit) Function Convert from SI units to
another unit within the
given unit group.
valueToSi(val, unitGroup, unit) Function Convert from a particular
unit to SI.
unitGroups() Function Returns a list of all
available unit groups.
units(unitGroup) Function Returns a list of all
available units within a
given unit group.

Unit conversion can be performed on variables of any rank; scalars, vectors,


matrices etc. Note that it is necessary to go via SI when converting from one non-
SI unit to another.

var U = ledaModules.UNITS();

// Print all unit groups


var groups = U.unitGroups();
print(groups);

// Print all supported units within the "Pressure" group


var pUnits = U.units("Pressure")
print(pUnits);

// Convert temperature scalar from DegC to SI (Kelvin) and to F.


var tempInDegC = 20.0;
var tempInK = U.valueToSi(tempInDegC, "Temperature", "C");
var tempInDegF = U.siToValue(tempInK, "Temperature", "F");
print(tempInDegF); // => 68
53
LedaFlow

// Vectors/Matrices supported: Pressure from psia to bara


var pInPsi = [14.5038, 29.0076];
var pInBar = U.siToValue(
U.valueToSi(pInPsi, "Pressure", "psia"),
"Pressure", "bara");
print(pInBar[0]); // => 1.0000018078270199

The USERPREFERENCES module holds information about desired unit set. To


convert from SI to the desired unit, we must first identify desired unit for the
relevant unit group.

var U = ledaModules.UNITS();
var USERPREF = ledaModules.USERPREFERENCES();

// Get desired unit for the Temperature group


var desiredUnit = USERPREF.units()["Temperature"]

// Convert temperature in K to desired unit


var tempInK = 293.15;
var temp = U.siToValue(tempInK, "Temperature", desiredUnit);
print(tempInK + " Kelvin is " + temp + " in " + desiredUnit);

54
LedaFlow Scripting Manual v2.4

5 SCRIPTING IN LEDAFLOW : FAQ

5.1 How to create a case from an input file ?


You need to use the method createCaseFrom of the module CASES.

5.2 How to delete a case?


You need to use the removeCase from the module CASES.

5.3 How to run a simulation?


You need to use the calculateSS and calculate methods from the module
CALCULATE.

5.4 How to extract results?


You need to use the module RESULTS. The main idea is that for a given case, you
can access to a list of all trends variables logged, and a list of all profile variables
logged. You can filter if needed the list of trends or profile properties by using
LedaFlow script methods or usual filter javascript methods. Methods to get results
for each of these trends or profile properties are available.
See example snippet_extractResults.js.

var resMod = ledaModules.RESULTS();


var uuid = "9da8e6b2-e8b8-43df-8b9d-00f03c96f062"

// Create an extractor for the case using "makeExtractor"


var extractor = resMod.makeExtractor(uuid);

/* The extractor contains a catalog of all the profile and trend


properties available for the case. We filter trend and profile
properties with unit of type "Pressure" */
var trendProperties =
extractor.catalog.filterTrends({unitGroup:["Pressure"]},false);
var profileProperties =
extractor.catalog.filterProfiles({unitGroup:["Pressure"]},false);

/* We just take the first trend and profile properties, for sake of
demonstration */
var trendProperty = trendProperties[0];
var profileProperty = profileProperties[0];

/* We demonstrate here how to get results for a trend property.


We use the method "getTrendValuesForAllTimes" */
var resTrendProp = extractor.getTrendValuesForAllTimes(trendProperty);
var time = resTrendProp.time; //vector of time points (in s)
55
LedaFlow

var value = resTrendProp.value; // vector of values for the trend


property in unit trendProperty.defaultUnit
var fullName = trendProperty.loggerName+"_"+trendProperty.displayName;
print("***TREND PROPERTY:"+fullName);
print("TIMES:"+time);
print("TREND:"+value);

// How to get to profile properties using "getProfileValuesForAllTimes"


var resProfileProp =
extractor.getProfileValuesForAllTimes(profileProperty);
var mesh = resProfileProp.mesh;// mesh vector in L coordinates and meter
var values = resProfileProp.values;// array of objects [{time:0,
valueForGivenTime:[1,2,...]}..etc]
var fullName =
profileProperty.loggerName+"_"+profileProperty.displayName;

/* 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.");
}

5.5 How to visualize the list of properties logged?


In the LedaFlow GUI, you can graphically visualize the logged variables for a given
logger and select which one(s) you wish to plot.
For example:

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:

{loggerName: "Pipe1", displayName:"Heat transfer - average wall",…}


{loggerName: "Pipe1", displayName:"Heat transfer - gas oil",…}
{loggerName: "Pipe1", displayName:"Heat transfer - gas wall",…}
{loggerName: "Pipe1", displayName:"Heat transfer - gas water",…}
{loggerName: "Pipe1", displayName:"Heat transfer - OHTC",…}
{loggerName: "Pipe1", displayName:"Heat transfer - oil-wall",…}
{loggerName: "Pipe1", displayName:"Heat transfer - oil-water",…}
{loggerName: "Pipe1", displayName:"Heat transfer - surroundings",…}
{loggerName: "Pipe1", displayName:"Heat transfer - water-wall",…}
{loggerName: "Pipe1", displayName:"MFR - gas",…}
{loggerName: "Pipe1", displayName:"MFR - gas in oil",…}
{loggerName: "Pipe1", displayName:"MFR - gas in water",…}
{loggerName: "Pipe1", displayName:"MFR - oil",…}
{loggerName: "Pipe1", displayName:"MFR - oil ingas",…}
{loggerName: "Pipe1", displayName:"MFR - oil in water",…}
{loggerName: "Pipe1", displayName:"MFR - total",…}
{loggerName: "Pipe1", displayName:"MFR - total gas",…}
{loggerName: "Pipe1", displayName:"MFR - total liquid",…}
{loggerName: "Pipe1", displayName:"MFR - total oil",…}
{loggerName: "Pipe1", displayName:"MFR - total water",…}
{loggerName: "Pipe1", displayName:"MFR - water",…}
{loggerName: "Pipe1", displayName:"MFR - water in gas",…}
{loggerName: "Pipe1", displayName:"MFR - water in oil",…}

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.

/// User inputs ///


// catalogType can be "Profile or "Trends"
var catalogType = "Profile";
// separator used for the csv file created
var sep = ",";
// attributes to show for each properties
var keysToShow =
["intid","loggerName","field","displayName","loggerCategory"];
/// End user inputs ///

// uses the case selected in LedaFlow client


if(!this.CASE_SELECTED)
throw "Select a case";
var uuid = CASE_SELECTED.uuid;

// Import ledaModules
var resMod = ledaModules.RESULTS();
var outFile = ledaModules.FILE();
var cases = ledaModules.CASES();

58
LedaFlow Scripting Manual v2.4

var caseObj = cases.caseobj(uuid);


var caseName = caseObj.name
var str = "";
var filename = caseName +
"_"+catalogType.toLowerCase()+"_catalog.csv"

print ("\n > Creating catalog for case ", caseName, "\n");
var catalog = resMod.makeCatalog(uuid);

var properties = [];


if(catalogType == "Profile")
properties = catalog.profiles;
else if(catalogType == "Trends")
properties = catalog.trends;
else
throw "catalogType is \"Profile\" or \"Trend\"";

// defines output string


str += "Case :"+ caseName + "\n\n"
str += "# Properties :"+sep+properties.length +"\n\n"
str += catalogType+" catalog\n\n";

// 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);

print(" > Script finished...");

5.6 How to generate text files?


You need to use the module FILE.
Below are demonstrated the main methods.

var module = ledaModules.FILE();

59
LedaFlow

var str = "Hello LedaFlow user";


var filename = "createAFile_fromString.txt";

module.writeFileFromString(str,filename);
module.openWithApplication(filename);

var filename = "createAFile_fromTemplate.txt";


var templatename = "template_createFile.dat"; //provided
var jsObject = { text: "Hello LedaFlow user. This is an example for
writeFileFromTemplate" };
module.writeFileFromTemplate(jsObject, templatename, filename);
module.openWithApplication(filename);

var filename = "createAFile_json.json";


module.writeJsonfileFromObject(jsObject, filename);
module.openWithApplication(filename);

See examples snippet_createAFile.js and ex_generateSimpleHtml.js.

5.7 How to create parametric studies ?


It is possible to create parametric studies, using the same methods a parametric
study input file does. It is also possible to extract parametric studies results using
the RESULTS module.
 This is illustrated in ex_turndownCurve.js.
o To create a parametric study, defaultParametricStudy(sutdyname,
baseCaseId) is used. A parameter is then added by the use of
addPARAMETER(parameterObject).
o Results are extracted by using a RESULTS extractor, applied to the
given subcases of the study
 To define a parameter object, it is suggested that you create a specific
parametric study with the GUI, using the parameters intended and write it
to input file. Use the parameter objects of the input file to re-inject into your
script. The parameter object fields that you will then need to modify are
values and objLabel.

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.

// Comments can be added to explain the intent of the code


var x = 3; // and can be added to explain each line
/*If you have many lines of explanation you can enclose them
with the asterix and the backslash */
/* Comments can be used to prevent the execution of code during
development */
// var b = “Hello”;

6.2 Variables
Local variables are declared using the “var” keyword:

var a = 3; // Assign the integer 3 to variable a


var b = “Hello”; // Assign the string “Hello” to b

Each instruction should end with a semicolon for clarity. You can have multiple
instructions on one line separated by semi-colons.

var a = 3; var b = “Hello”;


// Is acceptable syntax but may be more difficult to read

6.3 JavaScript Objects


JavaScript variables are containers for data values.
This code assigns a simple value (Fiat) to a variable named car:

var car = "Fiat";


Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable (of type Object)
named car:

61
LedaFlow

var car = {type:"Fiat", model:500, color:"white"};


The values are written as name:value pairs (name and value separated by a colon).

JavaScript objects are containers for named values

6.3.1 Object Properties


The name:values pairs (in JavaScript objects) are called properties.

var person = {firstName:"John", lastName:"Doe", age:50,


eyeColor:"blue"}

6.3.2 Object Methods


Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.JavaScript objects are
containers for named values (called properties) and methodsObject
Definition
You define (and create) a JavaScript object with an object literal:

var person = {firstName:"John", lastName:"Doe", age:50,


eyeColor:"blue"}
Spaces and line breaks are not important. An object definition can span multiple
lines.

6.3.4 Accessing Object Properties


You can access object properties in two ways:
objectName.propertyName
or
objectName[propertyName]

person.lastName;

person["lastName"];

62
LedaFlow Scripting Manual v2.4

6.3.5 Accessing Object Methods

You access an object method with the following syntax:

objectName.methodName()

name = person.fullName();
If you access the fullName property, without (), it will return the function definition:

name = person.fullName;

6.3.6 Do Not Declare Strings, Numbers, and Booleans


as Objects!
When a JavaScript variable is declared with the keyword "new", the variable is
created as an object:

var x = new String(); // Declares x as a String object


var y = new Number(); // Declares y as a Number object
var z = new Boolean(); // Declares z as a Boolean object
”.

6.4 Operators
There are two types of operators in scripting, namely assignment = and arithmetic
+.

x = 5; //assigns the value 5 to the variable x


y = 2; //assigns the value 2 to the variable y
z = y + x; // adds y to x to give z

6.4.1 Arithmetic Operators


Arithmetic operators are used to perform arithmetic between variables.

Operator Description Example Result Result


of y of x
+ Addition x=y+2 5 7
- Subtraction x=y-2 5 3
* Multiplication x=y*2 5 10
/ Division x=y/2 5 2.5

63
LedaFlow

Operator Description Example Result Result


of y of x
% Modulus (division x=y%2 5 1
remainder)
++ Increment x=++y 6 6
x=y++ 6 5
-- Decrement x=--y 4 4
x=y-- 4 5

If the increment/decrement operator is added before a variable, then the variable


value is changed by one before the assignment. So x = ++y will increment y first
by one (changing y from 5 to 6) then assign the new value of y to x.
If the increment/decrement operator occurs after a variable, the variable value is
changed by one after the assignment. So x = y++ will assign the value of y to x
then increment the value of y by one.

6.4.2 Assignment Operators


Assignment operators assign values to variables.
Given that x=10 and y=5, the table below provides examples of the available
assignment operators:

Operator Example Same As Result


of x
= x=y 5
+= x+=y x=x+y 15
-= x-=y x=x-y 5
*= x*=y x=x*y 50
/= x/=y x=x/y 2
%= x%=y x=x%y 0

6.4.3 Strings and the + Operator


The + operator can be used to add strings together.

var st1 = "Hello";


var st2 = "World";
//adds st1 to st2 to give st3, which is HelloWorld
var st3 = st1+st2;
Note to add a space between the two strings we need to insert a space into one of
the strings or add a space into the expression:

64
LedaFlow Scripting Manual v2.4

6.4.4 Adding strings and numbers


We can add strings and numbers to return a string. Note that adding a number to
a string will always result in a string.

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 Comparisons and Logical Operators


Logical statements compare values and take action. Comparison operators are used
in logical statements to determine equality or differences.

6.5.1 Comparisons
Given x=5, the table below provides explanations of the available comparison
operators:

Operator Description Comparing Returns


== Is equal to x==8 False
x==5 True
=== Is exactly equal to x===”5” False
(value and type)
x===5 True
!= Is not equal to x!=8 True
!== Is not equal to x!==”5” True
(value or type)
x!==5 False
x!==8 False
> Is greater than x>8 False
< Is less than x<8 True
>= Is greater than or x>=8 False
equal to
<= Is less than or equal x<=8 True
to

6.5.2 Logical
Given x=6 and y=3, the table below provides explanations of the available logical
operators:

65
LedaFlow

Operator Description Example Returns


&& and (x < 10 && y > 1) True
|| or (x==5 || y==5) False
! not !(x==y) True

6.5.3 Conditional Operator


The conditional operator assigns a value to a variable based on a condition.
Syntax
variablename = (condition) ? value1 : value2

var voteable=(age<18)?”Too young”:”Can vote”;

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:

var day=new Date().getDay();


switch (day)
{
case 0:
x="Today it's Sunday";
break;
case 1:
x="Today it's Monday";
break;
case 2:
x="Today it's Tuesday";
break;
case 3:
x="Today it's Wednesday";
break;
case 4:
x="Today it's Thursday";
break;

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”.

var person = { firstname: "John", lastname:"Doe", age:25};


var txt = "";
for (x in person)
{
txt = txt + person[x];
}
print(txt);
//JonDoe25
In the example below we start by defining an array called arrayname that contains
the letters “a” to “e”. We then define a for loop that steps through the array values
from the first element (“a”) to the last (“e”) and executes the command to print the
value to the screen.

var arrayname = [ "a", "b", "c", "d", "e" ];


// prints the number of elements in arrayname to
// the command line, that is 5

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 ] );
}

There are a few conventions in this example worth explaining:


 Notice that the index of the first element is 0 not 1.
 The length property returns the length of an array. In this case the length of
the array is 5
 The loop is repeated until the condition i < str.length is no longer true.
 str[0] returns the first element of the array str
 The curly brackets { and } enclose all the code we will repeat each time we
run the through the loop
So a rough translation of the for...in loop says: “For each of the values of i from
zero to the number of elements of the array arrayname, print the value of the array
element number. Then increment 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 myFunction(txt1, txt2)


{
var txtNew = txt1 + txt2;
print(txtNew);
}

//Function call
// will print "HelloWorld"
myFunction("Hello","World");

6.7.2 Returning values


You can return a value to where the function was called with the return statement.

function myFunction(txt1, txt2)


{
var txtNew = txt1 + txt2;
return txtNew;
}

var example = myFunction("Hello","World");


//example is "HelloWorld"

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.

6.8 Special Text (escape sequences)


Special text is indicated by the backslash, \. It is used to insert apostrophes, new
lines, quotes, and other special characters into a text string. It is useful for example
if you wanted to nest a quote within a string such as, “To be or not to be” with the
quotation marks.
In script, a string is started and stopped with either single or double quotes.
To solve this problem we use the backslash. So our definition would be:

var txt = "Hamlet\’s most famous line appears \"To be or not to


be\" in a play by Shakespeare";

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

6.9 Calling one script from another


6.9.1 include
The include function allows us to call another script. This allows us to have
standard scripts for common actions in our project from which we can call case
definition scripts, so the same set of operations can be applied to a selection of
different cases.

71
LedaFlow

Syntax
include (filename);

6.10 Printing results to the command window


To print to the console, use the instruction ‘print ( )’. Use ‘+’ to concatenate
different strings:

print ("This will be printed on the screen");


var pi = 3.14;
print("This is the number pi:" + pi);

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:

var myArray=new Array();


// Note Array() starts with capital. The array size is
// dynamic and will adjust to how many elements
// are added

var myArray=new Array(5); // sets the array size to 5 elements

// These can be used by specifying each element:


myArray[0]=1; //notice that the index of the first
element is 0 not 1
myArray[1]=3;
myArray[2]=0; //etc

var myArray= new Array(1,3,0); // a condensed way to declare


// the array and the elements in one line

var myArray= [1,3,0];


// an even briefer approach. Scripting detects that this is
// an array by the multiple elements

72
LedaFlow Scripting Manual v2.4

6.11.2 Array methods


6.11.2.1 concat()
Concatenates arrays.

var myArrayOne= [1,2];


var myArrayTwo= [3,4,5];
var myArrayThree= [6,7];
var newArray=myArrayOne.concat(myArrayTwo, myArrayThree);

// Creates the array [1,2,3,4,5,6,7]

6.11.2.2 join()
Joins the arrays into a string.

var myArray= [1,”hello”];


var str = myArray.join(“_”);
// Creates the string “1_hello”

6.11.2.3 pop()
Removes the last element in an array.

var myArrayOne= [1,2,3];


myArrayOne.pop();
// myArray is now [1,2]

6.11.2.4 push()
Adds a new element to the end of an array.

var myArrayOne= [1,2,3];


myArrayOne.push(4);
// myArrayOne is now [1,2,3,4]

6.11.2.5 reverse()
Reverses the order of the elements in an array.

var myArrayOne= [1,2,3];


myArrayOne.reverse();
// myArrayOne is now [3,2,1]

73
LedaFlow

6.11.2.6 shift()
Removes the first element of an array.

var myArrayOne= [1,2,3];


var k=myArrayOne.shift();
// myArrayOne is now [2,3]. k = 1

6.11.2.7 slice(begin, end)


Removes a selected range of elements.

var myArrayOne= [0,1,2,3,4,5];


var newArray=myArrayOne.slice(1,3);
// newArray = [1,2];

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.

var myArray= [0,1,2,3,4,5,11,22,23,59];


myArray.sort();
// myArray = [0,1,11,2,22,23,3,4,5,59];

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

Adds/removes items to/from an array.

var myArray= [0,1,2,3,4,5];


var k =myArray.splice(2,3);
//k = [2,3,4], myArray = [0,1,5];

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.

var numbers = [1,2,3,4,5];


var square = numbers.map(function(x) { return x*x;});
//square = [1,4,9,16,25];
var backtoroots = square.map(Math.sqrt);
//backtoroots = [1,2,3,4,5];

6.11.2.11 toString()
Converts an array into a string; returning all the elements in the array separated by
commas.

var myArray= [0,1,2,3,4,5];


var str = myArray.toString();
//str = “0,1,2,3,4,5”

6.11.2.12 unshift(Item1,..., itemN)


Item1,..., itemN [OPTIONAL]: The new item(s) to be added to the array

Adds new items to the beginning of an array.

6.12 Math Object


The Math object allows you to perform mathematical tasks.
All properties/methods of Math can be called by using Math as an object.

var x = Math.PI; // Returns pi


var y = Math.sqrt(16); // Returns the square root of 16

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

6.13 Break Loops


6.13.1 break
The break statement will break a loop and continue with the code after the loop, if
any. In the syntax example below the output will be 0, 1 and 2.

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
}

Note that try and catch are written in lowercase letters.

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

The exception can be a string, integer, Boolean or an object.


Note that throw is written in lowercase letters.

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

6.16.2 JSON Data - A Name and a Value


JSON data is written as name/value pairs.
A name/value pair consists of a field name (in double quotes), followed by a colon,
followed by a value:

"firstName":"John"

JSON names require double quotes. JavaScript names don't.

6.16.3 JSON Values


JSON values can be:
 A number (integer or floating point)
 A string (in double quotes)
 A Boolean (true or false)
 An array (in square brackets)
 An object (in curly braces)
 Null

6.16.4 JSON Objects


JSON objects are written inside curly braces.
79
LedaFlow

Just like JavaScript, JSON objects can contain multiple name/values pairs:

{"firstName":"John", "lastName":"Doe"}

6.16.5 JSON Arrays


JSON arrays are written inside square brackets.
Just like JavaScript, a JSON array can contain multiple objects:

"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:

// returns John Doe


employees[0].firstName + " " + employees[0].lastName;
It can also be accessed like this:

// returns John Doe


employees[0]["firstName"] + " " + employees[0]["lastName"];
Data can be modified 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

7.1 Softsh exit codes

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.

If called from Windows PowerShell, the exit code is in the equivalent


$LASTEXITCODE variable.

Below is a list of the individual return codes and their probably causes.

Exit code Description


0 Successful execution
-1 License failure. Softsh was unable to check
out a valid license.
-2 Database connection failure. Softsh could
not connect to the database, either because
it is not running/available or the supplied
connection parameters were inconsistent.
-3 Unable to open script file. The provided
script file could be opened for reading.
Most likely the provided path was invalid.
-4 Script error. Softsh caught an exception
and could not recover. Most probably caused
by a syntactical error in the provided
script file.

81
LedaFlow

7.2 License tools


Scripting can be used to check which licenses are available.
The class LicenseUtils provides the following methods:
 getLicenseAvailability(bool print)
o This method can be used to check the license keys
availability, by returning a String with the
description of which licenses are available and
which are not. If used with the input argument set
to true, the description will be printed in the
screen.
 isLicenseAvailable(int featureID)
o This method checks if a particular license key
(feature) is available for checkout. It returns a
Boolean value indicating if the license is available
or not.

The license keys description is the following:


 leda_ledaflow: LedaFlow (transient simulation) license
 leda_integrated: License to allow running LedaFlow in an
integrated environment (for example with K-Spice)
 leda_steadystate: SteadyState license
 leda_set: Softsh and LedaFlow Engineering (user
interface) license
 leda_profileModel: Profile model license
 leda_steadystateq3d: Q3D SteadyState license
 leda_singleCompTrackingCore: Custom fluids
simulation license (SteadyState and transient)
 leda_singleCompTrackingGui: Custom fluids user
interface license
 leda_fullCompTrackingCore: Composition tracking
simulation license (SteadyState and transient)
 leda_fullCompTrackingGui: Composition tracking user
interface license
 leda_commercial: Commercial version license

82
LedaFlow Scripting Manual v2.4

// ###### Example 1: Show available licenses ######


var lic = new LicenseUtils();
lic.getLicenseAvailability(true);

// This is printed in the screen


/*
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 2: Print available licenses ######


var lic = new LicenseUtils();
print(lic.getLicenseAvailability());

/*
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) ;

// this is printed in the screen


/*
true
*/
83
LedaFlow

7.3 Saving output to a file


Once we have retrieved data from the database and stored it locally we may want
to export it into text files. You can use the methods of the module FILES.
Another possibility is to use the class “File”. This enables to do more advanced
operations like appending to an existing file. We show below examples on how to
use it.

// 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();

// Example 2: Append to an existing file


var f = new File();
f.open("Intro2.txt",File.Append);
f.writeLine("Yes, this will be appended.");
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

This will be the second line

This will not be flushed until the file is closed

Yes, this will be appended.

84

You might also like