Skip to main content

KnowledgeBase

Functions

The following FVA-Workbench specific functions can be used in scripting:

Calculation

runCalcMethod()
Table 17. This function executes a calculation method (objective).

runCalcMethod(methodID, compID);

Parameter

Type

Description

methodID

string

Unique ID of the calculation method to run. A list of all calculation methods can be found in the section Calculations in scripting.

compID

int

Unique ID of the component in the model.

The system calculation is always performed on the gear unit (always has ID 1).

{options}

object

If specified, an output directory with the calculation kernel output files is created.

var options = {resultpath: path/to/results, createResultpath: true/false};

Return value

int

1 = calculation successful

0 = calculation terminated

-1 = error in the calculation

Possible errors

Calculation does not exist.

Component does not exist.

Component cannot be calculated with the specified calculation method.



Example 1 Perform a system calculation

1methodID = "001_SYSTEM_CALCULATION";
2var compID = 1;
3setAttr("gta_switch_iso_6336_2006", compID, true, EDAT);
4var status = runCalcMethod(methodID, compID);
5if (status == 1) {
6    println("Calculation was successful");
    } else {
7  println("Something went wrong");
    }

1

Assigns the ID for a system calculation to the methodID variable.

2

Assigns the ID of the gear unit to the compID variable. The ID of the gear unit is always 1.

3

Uses setAttr() to set the attribute with the ID "gta_switch_iso_6336_2006" to true. This will perform a load capacity calculation according to ISO 6336 (2996) as part of system calculation.

4

Starts the system calculation and stores the return value in the status variable.

5

If the return value in the status value = 1, then:

6

Output to the scripting console: "Calculation was successful."

7

For any other return value: "Something went wrong."

Example 2 Perform a bearing life calculation for a single bearing.

methodID = "800_ROLLING_BEARING_LIFETIME";
var compID = 15;
runCalcMethod(methodID, compID);
getNotifications()

This function returns all messages for an executed calculation as a JSON object.

getNotifications(NotificationType);

Parameter

Type

Description

NotificationType

String

ALL

All messages

ERROR

Error messages only

WARNING

Warnings only

INFO

Information messages only

Return value

JSON object

The messages are returned as a nested JSON object. The top level includes information about the calculation that was performed and the calculated component as well as the message itself. Some messages also have a second nested level, which may contain information about the relevant attribute and its value.

Example Output all messages for a calculation to the Scripting Monitor.

let notifications = getNotifications("ALL");

for(i = 0; i < notifications.length; i++) {
    let notification = notifications[i];
    println("Notification #" + i);
    println("---------------");
    println("Type:                " + notification.type);
    println("CalcMethodCompId:    " + notification.calcMethodCompId);
    println("CalcMethodCompName:  " + notification.calcMethodCompName);
    println("CalcMethodId:        " + notification.calcMethodId);
    println("CalcMethodName:      " + notification.calcMethodName);
    println("CalcStepName:        " + notification.calcStepName);
    println("Message:             " + notification.message);
    println(" ");

    let items = notification.items;

    for(j = 0; j < items.length; j++) {
	let notificationItem = items[j];
	println("   Notification Item #" + j);
	println("   ---------------------");
	println("   AttrId:   " + notificationItem.attrId);
	println("   CompId:   " + notificationItem.compId);
	println("   Message:  " + notificationItem.message);
	println("   Value:    " + notificationItem.value);
        println(" ");
    }
println(" ");
}
getNotifications_messages_view.png
getNotifications_scripting_monitor.png

Comparison of the Messages window in the user interface with the script output in the Scripting Monitor.

Accessing attributes

getAttr()
Table 18. This function returns the value of an attribute.

getAttr(attrID, compID, EDAT/RDAT);

Parameter

Type

Description

attrID

string

Unique ID of the attribute.

compID

int

Unique ID of the component in the model.

EDAT/RDAT

Specifies whether the input (EDAT) or calculated value (RDAT) should be returned.

Alternatively, 1 (EDAT) or 0 (RDAT) can be specified as a parameter.

For more information, see Data integrity (EDAT/RDAT)

Return value

Value of the attribute.

Possible errors

Incorrect Attribute ID or component ID.

Only for string, integer, double, boolean, array, and matrix attributes.



Example 1 Output the value of the normal pressure angle attribute to the console.

1let compID = getCompByType('cylindrical_mesh')[0];
2let value = getAttr("normal pressure angle", compID, EDAT);
3println(value);

1

Assigns the component ID of the first cylindrical gear stage in the model to the compID variable.

2

Assigns the input value (EDAT) of the normal pressure angle attribute to the value variable.

3

Outputs the value of the variable to the Scripting Monitor.

Example 2 Output the values of the static load rating array attribute to the console.

1let compID = getCompByType('bearing')[0];
2let value = getAttr("static capacity", compID, RDAT);
3println(value[0]);
4println(value[1]);

1

Assigns the component ID of the first rolling bearing in the model to the compID variable.

2

Assigns the calculated value (RDAT) of the static capacity attribute to the value variable.

static capacity is an array attribute and contains a value for every bearing row.

3

Outputs the attribute value for the first bearing row to the Scripting Monitor.

4

Outputs the attribute value for the second bearing row to the Scripting Monitor.

setAttr()
Table 19. This function sets the value of an attribute.

setAttr(attrID, compID, value, EDAT/RDAT);

Parameter

Type

Description

attrID

string

Unique ID of the attribute.

compID

int

Unique ID of the component in the model.

EDAT/RDAT

Specifies whether the input (EDAT) or calculated value (RDAT) should be returned. Alternatively, 1 (EDAT) or 0 (RDAT) can be specified as a parameter.

Possible errors

Incorrect Attribute ID.

Incorrect component ID.

Data type of the value does not match the attribute.

Value violates the constraints.



Example 1 Set the value of the oil temperature attribute to 90.

1var compID = 1;
2setAttr('temperature', compID, 90, EDAT);

1

Assigns the variable compID with the component ID of the gear unit. As the root component, the gear unit always has the ID of 1.

2

Assigns the attribute temperature of component 1 with the input value (EDAT).

Example 2 Set the attribute FVA_54 to true. The attribute FVA_54 corresponds to the "Calculation of micro pitting acc. to FVA 54" switch in the input editor.

1var compID = getCompByType('cylindrical_mesh')[0];
2setAttr('FVA_54', compID, true, EDAT);

1

Assigns the component ID of the first cylindrical stage to the compID variable.

2

Sets attribute FVA_54 to true (EDAT).

delAttr()
Table 20. This function deletes the input value (EDAT) of the attribute.

delAttr(attrID, compID);

Parameter

Type

Description

attrID

string

Unique ID of the attribute.

compID

int

Unique ID of the component in the model.

Return value

boolean

true if value deleted, otherwise false.

Possible errors

Incorrect component ID.

Incorrect attribute ID.



Example 1 Delete the lubricant attribute of the gear unit.

1delAttr('lubricant', 1);

1

Deletes the lubricant for the component gear unit.

getAttrProperty()
Table 21. This function returns the name, type, unit, or symbol of an attribute.

getAttrProperty(attrID, compID, propertyID);

Parameter

Type

Description

attrID

string

Unique ID of the attribute in the model.

compID

int

Unique ID of the component in the model.

propertyID

string

TYPE

Data type of the attribute.

NUMBER

Numeric attribute ID.

NAME

Attribute name

UNIT_NAME

Unit

SYMBOL

Symbol

EDAT_VALUE

EDAT value converted to string.

RDAT_VALUE

RDAT value converted to string.

Return value

Property of the attribute in the language in which the FVA-Workbench was started.

Possible errors

Incorrect component ID

Incorrect attribute ID

Attribute and component ID do not match.



Example Query the properties of the "face width" attribute on a cylindrical gear with ID 8.

1var compID = 8;
2var attributeID = 'face width';
3println('Name: ' + getAttrProperty(attributeID, compID, 'NAME'));
4println('Unit: ' + getAttrProperty(attributeID, compID, 'UNIT_NAME'));
5println('Symbol: ' + getAttrProperty(attributeID, compID, 'SYMBOL'));
6println('Value: ' + getAttrProperty(attributeID, compID, 'RDAT_VALUE'));

1

Assigns the component with ID 8 to the compID variable.

2

Assigns the ID of the face width attribute to the attributeID variable.

3

Outputs the name of the attribute to the scripting console.

4

Outputs the unit of the attribute to the scripting console.

5

Outputs the symbol of the attribute to the scripting console.

6

Outputs the output value of the attribute to the scripting console.

isAttrLocked()
Table 22. Checks whether write access is locked for the attribute.

isAttrLocked(attrID, compID);

Parameter

Type

Description

attrID

string

Unique ID of the attribute.

compID

int

Unique ID of the component in the model.

Return value

boolean

true - attribute cannot be written.

false - attribute can be written.



In some circumstances, the status of an attribute may be "locked." These attributes cannot be changed via script. For example, this is the case if specification of the attribute value would lead to overdetermination of the model.

Example 

If the option for "Specification of addendum modification acc. to DIN 3992" is selected from the distribution of the addendum modification pull-down menu for the cylindrical gear component in the Editor, the attributes for manually specifying the nominal addendum modification coefficient are locked and hidden.

The script checks whether the "addendum modification coefficient" attribute can be written. If so, the new value is set. If not, a message stating "nominal addendum modification coefficient cannot be written, check the distribution of the addendum modification" is shown.

let gearID = 8;
let addendum_modification = 0.3;
if(isAttrLocked("addendum modification coefficient", gearID) == false){
    setAttr("addendum modification coefficient", gearID, addendum_modification, EDAT);
}else{
    println("Addendum modification factor cannot be set, please check the addendum modification allocation.");
}
delRDAT()
Table 23. This function deletes all calculated attribute values (RDAT).

delRDAT();

Parameter

Type

Description

-

-

-



For more information see Data integrity (EDAT/RDAT)

Example 1 Delete all RDAT values.

delRDAT();

Accessing components

getCompByType()
Table 24. This function returns a list (array) of all component IDs of a certain type. If the model does not include any components of the specified type, an empty array (length = 0) is returned.

getCompProperty(compType);

Parameter

Type

Description

compType

string

Component type (e.g., "bearing")

Return value

array

Array of component IDs

Possible errors

Component type does not exist.



Example 1 Set the input type for all rolling bearings in the model to "rigidity."

1let bearings = getCompByType("bearing");

2for (i=0; i < bearings.length; i++){
3	setAttr("bearing data type", bearings[i], 2, EDAT);
    }

1

Assigns the variable bearings with an array of all rolling bearing IDs in the gear unit.

2

for loop that runs once for each element in the array.

3

Sets the attribute "input type " for each bearing to "rigidity" (value =2, see data type: combo attributes).

getCompProperty()
Table 25. This function delivers the name or type of a component.

getCompProperty(compID, propertyID);

Parameter

Type

Description

compID

int

Unique ID of the component in the model

propertyID

string

TYPE - component type (e.g., cylindrical_mesh)

NAME - component name

Return value

string

Property of the component

Possible errors

Incorrect component ID



Example 1 Output a component name and type to the scripting console.

1var compID = 3;
2println(getCompProperty(compID,'TYPE'));
3println(getCompProperty(compID,'NAME'));

1

Assigns a value of 3 to the compID variable.

2

Outputs the component type of component 3 to the scripting console.

3

Outputs the component name of component 3 to the scripting console.

Notice

In earlier versions of the FVA-Workbench, the properties IDENT_NO and DRAWING_NO could be queried via getCompProperty().

The drawing number (comp_drawing_number) and Ident number (comp_ident_number) are now attributes of the respective component and can be set or read via setAttr() and getAttr().

Example for reading the number of a drawing: getAttr("comp_drawing_number", 3, EDAT);

setCompProperty()
Table 26. This function can be used to change the name of a component.

setCompProperty(compID, propertyID);

Parameter

Type

Description

compID

int

Unique ID of the component in the model

propertyID

string

NAME - name of the component

Possible errors

Incorrect component ID



Example Change the name of a component.

var compID = 3;
setCompProperty(compID, "NAME", "New component name");
getSubComponents()
Table 27. The getSubComponents function can be used to query sub-components or connected components via scripting. The return value is an array with the component IDs of the sub-components.

getSubComponents(compID, subCompType);

Parameter

Type

Description

compID

int

ID of the main component

subCompType

string

Component type of the sub-component to be queried e.g., "cylindrical_mesh".

Return value

array

Array of the ID's of the sub-components. If there are no sub-components, an empty array will be returned.

Possible errors

The queried component type does not exist on the main component.

The main component does not exist.



Example 1 Query a cylindrical stage

1var stageID = 3;
2var gearIDs = getSubComponents(stageID, "general_gear");
3println(gearIDs[0]);
4println(gearIDs[1]);

1

Variable stageID includes the ID of the cylindrical stage.

2

getSubComponents() writes an array with the ID's of both cylindrical gears to the gearIDs variable.

3

Writes the ID of the first cylindrical gear to the console.

4

Writes the ID of the second cylindrical gear to the console

addSubComponent()
Table 28. Directly connected sub-components can be added to the primary components with the addSubComponent() function.

addSubComponent(baseCompID, compType, {options});

Parameter

Type

Description

baseCompID

int

ID of the primary component to which the sub-component should be added.

compType

string

Component type of the sub-component to be added. The following types are available:

  • Notch on a shaft -> addSubComponent(shaftID, "notch");

  • Load on a shaft -> addSubComponent(shaftID, "force");

  • Shaft section on a shaft -> addSubComponent(shaftID, "contour");

  • Modification on a cylindrical gear -> addSubComponent(gearID, "gear_correction");

{options}

object

The following additional options are available for shaft contours.

If no options are specified, shaft sections are added as outer contours from the left.

Shaft inner/outer contour

side: inner/outer

Specification of shaft contour from left/right

direction: left/right

Return value

int

ID of the newly added component

Possible errors

The primary component does not exist.

The sub-component type cannot be added to the primary component.



Note

Adding or deleting components may take some time, especially for large models, as the 3D model is updated each time.

Transaction mode can be enabled before the addSubComponent() call to speed up the process.

Example 1 Add a notch on a shaft and assign the basic attributes

1let shaftID = 3;
2let notchID = addSubComponent(shaftID, "notch");

3setAttr("notch kind", notchID, 6, EDAT);
4setAttr("position", notchID, 6, EDAT);
5setAttr("notch width", notchID, 5, EDAT);
6setAttr("notch radius", notchID, 2, EDAT);
7setAttr("depth", notchID, 2, EDAT);
8setAttr("surface roughness", notchID, 10, EDAT);

1

The shaftID variable includes the ID of the shaft on which the notch should be added.

2

Adds a new component of type "notch" on shaft 3 via addSubComponent(). The return value of the function, the ID of the new notch, is saved in the notchID variable.

3

Sets the "notch form" combo attribute for the new notch to 6 via setAttr(). The value 6 corresponds to a rectangular notch. (See image for additional options)

notch_kind_combo.png

4

Sets the position of the notch.

5

Sets the width of the notch.

6

Sets the radius of the notch.

7

Sets the depth of the notch.

8

Sets the surface roughness R_z of the notch.

Example 2 Add a contour to an existing shaft

var shaftID = 3;
var nbrOuterContours = 3;
var nbrInnerContours = 2;
var outerContourIDs = [];
var innerContourIDs = [];
var outerContourlenght = [30, 50, 20];
var innerContourlenght = [40, 80];
var outerContourDiameters = [30, 50, 25];
var innerContourDiameters = [10, 20];

for (let i = 0; i < nbrOuterContours; i++){
  let options = {};
  outerContourIDs.push(addSubComponent(shaftID, "contour",{side: "outer", direction: "left"}));
}
for (let i = 0; i < nbrInnerContours; i++){
    innerContourIDs.push(addSubComponent(shaftID, "contour",{side: "inner", direction: "left"}));
}
for(let i = 0; i < nbrOuterContours; i++){
    setAttr("length",             outerContourIDs[i], outerContourlenght[i], EDAT);
    setAttr("beginning diameter", outerContourIDs[i], outerContourDiameters[i], EDAT);
    setAttr("end diameter",       outerContourIDs[i], outerContourDiameters[i], EDAT);
}
for(let i = 0; i < nbrInnerContours; i++){
    setAttr("length",             innerContourIDs[i], innerContourlenght[i], EDAT);
    setAttr("beginning diameter", innerContourIDs[i], innerContourDiameters[i], EDAT);
    setAttr("end diameter",       innerContourIDs[i], innerContourDiameters[i], EDAT);
}
deleteSubComponent()
Table 29. Sub-components can be deleted via the deleteSubComponent() function.

deleteSubComponent(baseCompID, compID);

Parameter

Type

Description

baseCompID

string

ID of the primary component from which the sub-component should be deleted.

compType

string

ID of the component to be deleted.

Possible errors

The primary component does not exist.

The sub-component does not exist.



Example Delete a load component from a shaft

var shaftID = 4;
var forceID = 10;

deleteSubComponent(shaftID, forceID);
addDbComponent()
Table 30. Database components from the Global Database can be added to the model with this function.

addDbComponent(dbType, entryId);

Parameter

Type

Description

dbType

string

Type of the database component to be added.

  • Lubricant -> "lubricant"

  • Material -> "material"

  • Tool -> "tool"

  • Load spectrum -> "spectrum"

  • Wöhler SN curve -> "sn_curve"

  • Resistance characteristic curve dataset -> "resistance_characteristic_data_curve"

  • Measurement series -> "data_curve"

  • Coefficient of friction -> "friction_coefficient"

entryId

int

Unique ID of the component in the model.

Return value

string

ID of the newly added component

Possible errors

Incorrect database type

Database entry does not exist



Example Add the material 16MnCr5 as a component to the model and allocate it to a cylindrical gear

gearID = 8;
var materialID = addDbComponent("material", "16MnCr5");
setAttr("material", gearID, materialID, EDAT);
deleteDbComponent()
Table 31. This function can be used to delete database components from the model.

deleteDbComponent(compId);

Parameter

Type

Description

compId

string

ID of the database component to be deleted.

Possible errors

Database component does not exist in the model.



Example Delete the database component with the ID 120

deleteDbComponent("120");
refreshDbComp()
Table 32. This function updates a component from the Global Database.

refreshDbComp(dbCompID);

Parameter

Type

Description

dbCompID

int

Unique ID of the database component in the model

Possible errors

Database component does not exist in the model.



Example 1 Update the component with the ID 22 with data from the Global Database.

refreshDbComp(22);

Output

println()
Table 33. This feature writes data to the scripting console. A break is added to the end of each line. If no line break is added, the print() function can be used.

println(data);

Parameter

Type

Description

data

any

Data to be output to the scripting console.

Possible errors

Missing Component ID

Missing Attribute ID



Example 1

1var text = "This is text";
2var array = [1, 2.2, 3, 4];
3println(text);
    for (i=0; i<array.length; i++){
4     println(array[i]);
    }

1

Assigns a string to a text variable.

2

Assigns an array of multiple numbers to an array variable.

3

Outputs the text variable to the scripting console.

4

for-loop that goes through each entry in the array and writes the number to the scripting console.

format()
Table 34. Formats text or numbers
format_parameter.png

Parameter

Description

align

Text direction (left or right justified)

width

Field width

precision

Number of decimal places to be shown

type

Data type of the value to be formatted

value

Value to be formatted



Figure 34. Example - Output of formatted attribute text (name, symbol, value, unit)
Example - Output of formatted attribute text (name, symbol, value, unit)


1

format("%-12s", "Power");

(-) left justified

(12) 12 spaces wide

(s) value of type string

2

format("%-3s", "P");

(-) left justified

(3) 3 spaces wide

(s) value of type string

3

format("%10.3f",  148,2456);

() right justified

(10) 10 spaces wide

(f) value of type floating point number

(.3) 3 decimal places

4

format("%3s", "kW");

() right justified

(3) 3 spaces wide

(s) value of type string

alert()
Table 35. This function outputs a message as a dialog. The program waits until the user confirms the message with [OK].

alert(data);

Parameter

Type

Description

data

any

Text or data to be shown in the dialog.



Example 1 Output text as a message.

var text = "This is a message. Click OK to continue."
alert(text);
alertbox.png

Example 2 Output multiple messages in a loop.

1for (i = 0; i < 5; i++){
2    alert("This is the " + i + ". run"); 
     }

1

for loop in which the run variable i is increased from 0 to 4.

2

Outputs i as a message.

prompt()
Table 36. This function creates an input dialog with text. This can be used to request data from the user when the script is run. These files can then be further processed in the script.

prompt(data);

Parameter

Type

Description

data

any

Text or data to be displayed as text in the input dialog.



Example 1 Request torque from the user and set the attribute value of the load component accordingly.

1var forceID = 20;
2var torque = prompt("Please enter input torque");
3setAttr("scaled torque", forceID, torque, EDAT);

1

Assigns the variable forceID with the ID of a load component.

2

Writes the return value of the prompt() function to the torque variable.

3

Sets the input value (EDAT) of the torque attribute for load component 20 to the value in specified in the dialog box.

promptbox.png
promptFile()
Table 37. Displays a file selection dialog, which requires the user to enter a filename. Optional parameters can be used to specify a default file path and to suggest a file name and dialog type.

promptFile({options})

Parameter

Type

Description

{options}

object

directory - default file path

filename - suggested file name

type - type of dialog: open ("open") or save ("save"). Default: "open"



Note

This function can only be used in GUI operation, not in batch operation.

Example 1 Write text to a file selected by the user.

1let options = {directory: "c/example", filename: "myfile.txt", type: "save"};
2let path = promptFile(options);
3let text = "This Text will be written to the ASCII File";
4writeToFile(path, text, "c", "UTF-8");

1

Options for the file selection dialog

2

Opens a file selection dialog in the c:\example directory and writes the selected path and filename to the path variable.

3

Text to be written to the output file.

4

Writes the text to the specified file.

promptDirectory()
Table 38. Displays a folder selection dialog. The optional baseDirectory parameter can be used to specify a standard directory.

promptDirectory(baseDirectory);

Parameter

Type

Description

data

string

Specification of a predefined path

If no parameter is specified, the most recently selected directory is displayed.



Note

This function can only be used in GUI operation, not in batch operation.

Example 1 Write a text file to a user-selected directory.

1let directory = promptDirectory("c:/example");
2let filename = "text.txt";
3let path = directory +"/"+ filename;
4let text = "This Text will be written to the ASCII File";
5writeToFile(path, text, "c", "UTF-8");

1

Opens a directory selection dialog and writes the selected path to the directory variable. C:\example is selected by default.

2

Stores the name of the output file in the filename variable.

3

Assembles the strings into a complete file path and stores it in the path variable.

4

Text to be written in the output file.

5

Writes the text to the specified file.

promptSelect()
Table 39. Creates a dialog with a drop-down selection list, which can be used to request data from the user while the script is running. This data can then be processed in the script.

promptFile(baseDirectory)

Parameter

Type

Description

caption

string

Text shown above the drop down list

dropDownEntries

array of strings

Array of strings: each string corresponds to an entry in the drop down list.



Note

This function can only be used in GUI operation, not in batch operation.

Example 1 Query the user for criteria for the proposed modification and set the corresponding attribute in the FVA-Workbench.

attribute_overview_mod_criterion.png

The possible values for the "3D load distribution tooth modification criterium" combo attribute can be seen in the attribute overview.

1let dropDownEntries = [
                           "Linear increase in pressure", 
                           "Uniform pressure distribution", 
                           "Linear increase of line loads", 
                           "Uniform line loads"
                          ];
2let modCriterion = promptSelect("Select modification criterion for 3d loaddistribution", dropDownEntries);

3switch (modCriterion) {
        case "Linear increase in pressure":   modCriterion = "0"; break; 
        case "Uniform pressure distribution": modCriterion = "1"; break;
        case "Linear increase of line loads": modCriterion = "2"; break;
        case "Uniform line loads":            modCriterion = "3"; break;
        default: break; 
    };

4setAttr("modification_criterion_load_distribution_3d", 1, modCriterion, EDAT);

1

Writes the selection options for the drop-down menu as a string array to the dropDownEntries variable.

2

Opens the drop-down dialog; the return value is written to the modCriterion variable.

3

The switch case statement assigns a valid value for the "modification_criterion_load_distribution_3d" attribute to the strings selected by the user.

4

Sets the input value for the "modification_criterion_load_distribution_3d" attribute in the FVA-Workbench.

drop_down_window.png
clearMonitor()
Table 40. This function deletes the contents of the Scripting Monitor.

clearMonitor();

Parameter

Type

Description

-

-

-



Example 1 Clear the monitor

clearMonitor();
generateReport()
Table 41. This function generates an HTML report from the calculation results for the current model using a specified report template. Existing files will be overwritten.

generateReport(templateFile, outputFile, {options});

Parameter

Type

Description

templateFile

string

Path + name of the report template file

outputFile

int

Path + name of the HTML file

{options}

object

Single-column layout

compactView:true/false

Language

language: "de"/"en"

Hierarchical model tree

completeTree: true/false

Navigation bar

navigationBar: true/false

Calculation messages

notifications: true/false

Possible errors

Access restrictions on folders/files

Missing report template



Example 1 Generate an HTML report

1var templateFile = "C:\\template.wbrep";
2var outputFile = "C:\\temp\\output\\report.html";
3var options = {compactView: false, 
                   language: "de", 
                   completeTree: false, 
                   notifications: true, 
                   navigationBar: true};
4generateReport(templateFile, outputFile, options);

1

Path to report template

2

Path where the output report will be generated

3

Options to be considered when generating the report

4

Function for generating the report

loadModel()
Table 42. This function loads a gearbox model.

loadModel(path)

Parameter

Type

Description

path

string

Path + name of the file

Possible errors

Model file does not exist or access is denied.



Note

This function can only be used in batch operation.

Example 1 Load a model from the specified directory.

loadModel("c:\\modell.wbpz");
saveModel()
Table 43. This function saves the currently loaded model.

saveModel();

Parameter

Type

Description

Possible errors

Access to the model file is denied.



Example 1 Save the model file

saveModel();
exportModel()
Table 44. This function can be used to export the model in various formats. The file extension determines the format to be exported. Additional options can be specified for a REXS export. Existing files will be overwritten.

exportModel(fileName, {options});

Parameter

Type

Description

fileName

string

Path + name of the model file. The following file extensions are supported:

.wbpz

.wbpx

.wbps

.rexs

{options}

object

IncludeEmptyAttributes

Determines whether empty attributes should be included in the output file. (true/false)

DataClass

Determines whether EDAT or RDAT should be written. If the RDAT data is not valid, EDAT will automatically be written. (EDAT/RDAT)

Version

Specifies the version of the REXS specification to be used. (1.0/1.1/1.2)

Possible errors

The user does not have write permissions to the specified directory.



Example 1 Export the file model.wbpz to the C:\temp directory.

exportModel("C:\\temp\\model.wbpz");

Example 2 Export the model in REXS format (version 1.2)

1var options = {IncludeEmptyAttributes: "true" ,DataClass: "RDAT", Version: 1.2};
2exportModel("C:\\temp\\model.rexs", options);

1

Variable options that contain .rexs specific information.

2

Exports the model via exportModel(), including options.

readFile()
Table 45. Imports files in ASCII format. The file is read line-by-line and saved to an array.

readFile(path);

Parameter

Type

Description

path

string

Path + name of the file

Return value

array

Contents of the file in a string array

Possible errors

File does not exist or access is denied.

File is in binary format.



Example 1 Import a text file and output it to the scripting console

1var path = "c:\\textfile.txt";
2var text = readFile(path);

3for (i = 0; i < text.length; i++){
4    println(text[i]);
5    println(parseFloat(text[i])+ parseFloat(text[i]));
     }

1

Assigns the path variable with the path to the text file.

2

Uses readFile() to assign the text variable with an array with a number of entries equal to the number of lines in the textfile.txt file.

3

For loop which increases the counting variable i from 0 to text.length (number of lines in the text file).

4

Outputs every line of the text file to the scripting console.

5

Uses parseFloat() to convert every array entry in the text variable to a floating point number which can then be used for further calculations. If the array entry does not contain a number that can be converted, parseFloat() returns NaN (Not a Number) as a value.

writeToFile()
Table 46. This function writes text to a file. If the specified folder does not exist, it will be created.

writeToFile(path, text, mode, encoding);

Parameter

Type

Description

path

string

Path + name of the text file

Relative paths can also be specified. In this case, the parent directory is the directory where the FVA-Workbench is installed.

text

string

Text to be written to the file

mode

string

a

Adds the text to an existing file. The file will be created if necessary.

c

If the file already exists, the contents will be replaced. Otherwise, the system will create the file and add the text.

encoding

string

If no parameters are specified, the default encoding of the operating system is used. It is recommended to specify the encoding to ensure compatibility between different systems.

UTF-8

UTF-16BE

UTF-16LE

UTF-16

ISO-8859-1

US-ASCII

BINARY

Possible errors

The user does not have write permissions to the specified path.



Example Create a text file and add additional text.

1var path = "C:\\temp\\test.txt";
2writeToFile(path, "Part 1\n", "c", "UTF-8");
3writeToFile(path, "Part 2\n", "a", "UTF-8");
4writeToFile(path, "Part 3",   "c", "UTF-8");

1

Path to the text file

2

Creates a UTF-8 encoded text file with the contents "Part 1." \n adds a line break.

3

Adds the text "Part 2" to the existing file.

4

Writes the text "Part 3" to the file. "Part 1" and "Part 2" will be deleted.

fileExists()
Table 47. Checks whether the specified file exists.

fileExists(filepath);

Parameter

Type

Description

filepath

string

Path to the file

Return value

boolean

Returns true if the specified file exists.



Example

let filestatus = fileExists("c:/example/file.txt");
println(filestatus);
isFileReadable()
Table 48. Checks whether the specified file exists and can be read.

isFileReadable(filepath);

Parameter

Type

Description

filepath

string

File path

Return value

boolean

Returns true if the specified file exists and can be read.



Example

let filestatus = isFileReadable("c:/example/file.txt");
println(filestatus);
isFileWriteable()
Table 49. Checks whether the specified file exists and can be written.

isFileWriteable(filepath);

Parameter

Type

Description

filepath

string

File path

Return value

boolean

Returns true if the specified file exist and can be written.



Example

let filestatus = isFileWriteable("c:/example/file.txt");
println(filestatus);
exportNotifications()
Table 50. Exports notifications from the message output to an .xml file. If the file already exists, it will be overwritten.

exportNotifications(path);

Parameter

Type

Description

path

string

Path + name of the file

Possible errors

The user does not have write permissions to the specified path.



Example 1 Export calculation messages as .xml.

exportNotifications("C:\\temp\\notifications.xml");

Additional

#include
Table 51. This function includes external script files. For example, this can be used to offload frequently used functions. External scripts can be added to the main script at any location. Relative or absolute paths can be used for external scripts. To use a relative path, the base directory must be specified under Settings -> Directories -> Global scripts.

#include "path\\script.wbjs";

Parameter

Type

Description

Possible errors

The specified script file or path does not exist

The file extension is not .wbjs



Notice

For more examples, see Embedding external scripts

Example 1 Include external scripts

1#include "*";
2#include "folder\\*";
3#include "folder\\script.wbjs";
4#include "c:\\scripting\\folder\\script.wbjs"

1

Includes all scripts in the base directory

2

Includes all scripts in a sub-folder of the base directory.

3

Includes one script in a sub-folder of the base directory.

4

Includes a script via an absolute path.

startTransactionMode()
Table 52. This function activates transaction mode. In transaction mode, all functions that are not absolutely necessary for the calculation are disabled. This reduces the calculation time.

startTransactionMode();



The following functions are disabled:

  • 3D View updates

  • Correlations (synchronization between different attributes)

  • Creating model snapshots

endTransactionMode()
Table 53. Deactivates transaction mode

endTransactionMode();



stopScript()
Table 54. Stops execution of the currently running script. Optionally, the text can also be displayed on the Scripting Monitor.

stopScript(message);

Parameter

Type

Description

message

any

Text or data to be output on the Scripting Monitor after termination of the script



Example 1 Output multiple messages in a loop

1var safety = 1.8;
2if(safety > 2){
3    generateReport("c:\\template.wbrep", "c:\\report.html");
4}else{
5    stopScript("The safety is: "+safety+"\nScript was stopped");
}

1

Assigns a value of 1.8 to the safety variable

2

If the value for safety is greater than 2, then...

3

Generates an output report

4

If safety is less than 2 or the value is undefined, then...

5

Terminates the script and displays a message on the Scripting Monitor

isBatchMode()
Table 55. Checks whether the script will be executed in batch operation or via the GUI.

isBatchMode()

Parameter

Type

Description

Return value

boolean

Function returns true if the script is executed in batch mode.



Some scripting functions can only be executed in the GUI or in batch mode. The isBatchMode() function can be used to check which mode the FVA-Workbench is in while the script is running, and to react accordingly.

Example

If the script is executed in GUI mode, a dialog queries the user for the directory to be used. In batch mode, the directory in which the model file is located is used.

let filename = "textfile.txt";
let text = "This text will be written to the file";
let directory;
let resultpath;

if (isBatchMode() == true) {
    directory = getModelProperty("FOLDER");
} else {
    directory = promptDirectory();
}

resultpath = directory+filename;
println("File written: "+resultpath);
writeToFile(resultpath, text, "c", "UTF-8");
getModelProperty();
Table 56. Queries various characteristics of the model.

getModelProperty(propertyID);

Parameter

Type

Description

propertyID

string

FILEPATH

Complete path to the model file.

c:/example/modelfolder/model.wbpz

FOLDER

Path where the model file is located.

c:/example/modelfolder/

FILENAME

Name of the model file.

model.wbpz

FILENAME_NO_EXT

Name of the model file without file extension.

model

MODEL_NAME

Name of the project or model.

Can be changed under Project -> Properties -> Project name

Twin-screw extruder



Example 1 Write a text file to a subdirectory of the model folder.

1let modelpath = getModelProperty("FOLDER");
2let modelname = getModelProperty("MODEL_NAME");
3let filepath = modelpath + "new_directory/textfile.txt";
4writeToFile(filepath, modelname, "c", "UTF-8");

1

Assigns the path of the model file to the modelpath variable.

2

Assigns the name of the model to the modelname variable.

3

Appends the string "new_directory/textfile.txt" to the modelpath variable and writes it to the filepath.

4

Writes a text file that includes the model name as text to the path of the filepath variable.

getDirectory()
Table 57. Returns the paths to directories defined in the settings.

getDirectory(folderID);

Parameter

Type

Description

folderID

string

global_scripts

global scripts

models

preferred location for saving gearbox models

temp

temporary files

report_templates

report templates

reports

preferred output folder for reports



Example Query the directory for report templates and the output folder and create a results report.

1let reportTemplateDirectory = getDirectory("report_templates");
2let templateFile = reportTemplateDirectory +"\\myReportTemplate.wbrep";

3let outputDirectory = getDirectory("reports");
4let outputFile = outputDirectory+"\\report.html";

5generateReport(templateFile, outputFile);

6println("Report was saved here: "+outputFile);

1

Queries the path in which the .wbrep report templates are located and saves it to the reportTemplateDirectory variable

2

Appends the name of the report template to reportTemplateDirectory and saves it to the templateFile variable.

3

Queries the path in which the .html results reports are saved by default and saves it to the outputDirectory variable.

4

Appends the names of the output reports to outputDirectory and saves them to the outputFile variable.

5

Creates a report.

6

Outputs the location of the output report to the Scripting Monitor.

get() - HTTP request
Table 58. Method to retrieve data from a server.

get(url)

Parameter

Type

Description

url

string

url of the server from which the data is requested



Example

World Clock API is a server that returns the current date and time in JSON. The server returns the data as a string. The JSON.parse command can be used to convert this string to a JSON object. Elements in the JSON object can then be accessed using dot notation.

let JSON_string = get('http://worldclockapi.com/api/json/utc/now');
let JSON_object = JSON.parse(JSON_string);

println(JSON_string);
println(JSON_object.currentDateTime);
println(JSON_object.dayOfTheWeek);
post() - HTTP request
Table 59. Method to send data to a server.

post(url, parameter)

Parameter

Type

Description

url

string

url of the server from which the data is requested

parameter

object

Parameters to be transmitted to the server (e.g., username and password)



Example

In this script, "name" and "password" are transferred as parameters to a demo server. The response from the server is a JSON string, which also includes the parameters that were sent. The JSON.parse command can be used to convert the string to a JSON object.

let JSON_string = post('https://postman-echo.com/post', {'name':'mustermann', 'password':'secret'});
let JSON_object = JSON.parse(JSON_string);

println(JSON_string);
println(JSON_object.data.name);
println(JSON_object.data.password);
getLanguage()
Table 60. Returns the language in which the FVA-Workbench was started.

getLanguage();

Parameter

Type

Description

Return value

string

de

German

en

English



Example Output different messages after a calculation, depending on the language.

1let status = runCalcMethod("001_SYSTEM_CALCULATION", 1);
2let language = getLanguage();
3let success_message = language == "de" ? "Die Berechnung war erfolgreich" : "Calculation was successful";
4let fail_message = language == "de" ? "Die Berechnung ist fehlgeschlagen" : "Calculation failed";

5if (status == 1) {
6    println(success_message);
7    } else {
8  println(fail_message );
    }

1

Executes a system calculation and saves the return value in the status variable.

2

Queries the current language of the FVA-Workbench and saves the return value in the language variable.

3

Writes the message to be output after a successful calculation to the success_message variable. If the value in the language variable is "en" the English string is used, and vice-versa.

4

As with the success message, the message to be output after a failed calculation is written to the fail_message variable.

5

If the return value in the status variable = 1, then:

6

The success message is output to the scripting console

7

Otherwise:

8

The failure message is output