ANSA

version 12.1.x

Scripting Language
A guide to ANSA automation

β BETA
CAE Systems S.A.

ANSA v.12.1.x

Scripting Language

BETA CAE Systems S.A.

page 2

ANSA v.12.1.x

Scripting Language

Table of Contents
SECTION 1 DESCRIPTION OF THE SCRIPTING LANGUAGE ....................................6
1.1. General ................................................................................................................................................. 6 1.2. Data Types ........................................................................................................................................... 6 1.2.1. User Defined Data Types (structures) ........................................................................................... 7 1.3. Variables............................................................................................................................................... 7 1.3.1. Naming of Variables and Restrictions............................................................................................ 7 1.3.2. Important Notes on Variables ........................................................................................................ 8 1.4. Operators and Basic Calculation....................................................................................................... 8 1.4.1. Expressions and assignments for numeric data types .................................................................. 8 1.4.2. Operator precedence ..................................................................................................................... 9 1.4.3. Important Notes on Operators ..................................................................................................... 10 1.4.4. Numeric intrinsic functions ........................................................................................................... 10 1.4.5. Expressions and assignments for string data types .................................................................... 11 1.4.6. Expressions and assignments for user defined data types (structures) ...................................... 11 1.5. Sets of data: Matrices and maps ..................................................................................................... 12 1.5.1. Matrices........................................................................................................................................ 12 1.5.2. Maps............................................................................................................................................. 15 1.6. Conditional Statements and Branching .......................................................................................... 16 1.6.1. The "if-else" blocks and the logical operators .............................................................................. 16 1.6.2. The switch statement ................................................................................................................... 17 1.6.3. The goto statement ...................................................................................................................... 18 1.7. Loop statements................................................................................................................................ 18 1.7.1. The foreach statement ................................................................................................................. 18 1.7.2. The for statement ......................................................................................................................... 19 1.7.3. The while statement ..................................................................................................................... 19 1.7.4. The do while construct ................................................................................................................. 19 1.7.5. The continue and break statements............................................................................................. 20 1.8. User functions and comments......................................................................................................... 20 1.8.1. Definition ...................................................................................................................................... 21 1.8.2. Argument list and function call ..................................................................................................... 21 1.8.3. Returning data from functions (return, byref call) ........................................................................ 21 1.8.4. Including Files .............................................................................................................................. 22 1.8.5. Scope and lifetime of variables .................................................................................................... 23 1.8.6. Recursive structures .................................................................................................................... 24 1.8.7. Initialization and un-initialization of matrices and variables ......................................................... 25 1.8.8. Use of help text and comments in functions ................................................................................ 25 1.8.9. Session commands for use in Scripting Language...................................................................... 26

SECTION 2 INTERACTING WITH ANSA .....................................................................27
2.1. General ............................................................................................................................................... 27 2.2. Handling Data .................................................................................................................................... 27 2.2.1. Data of element type .................................................................................................................... 27 2.2.2. ANSA cards and entity types ....................................................................................................... 27 2.3. Collecting entities.............................................................................................................................. 28 2.3.1. General......................................................................................................................................... 28 2.3.2. Collecting entities massively from the whole database ............................................................... 29 2.3.3. Collecting entities massively from other entities .......................................................................... 30 2.3.4. Collecting massively visible entities ............................................................................................. 31 2.3.5. Collecting available entity types of specific deck ......................................................................... 31 2.3.6. Get single entities......................................................................................................................... 32 2.3.7. Collecting part and groups from their ids ..................................................................................... 32 2.3.8. Collecting entities according to their name .................................................................................. 32 2.3.9. Collecting all new created/imported entities................................................................................. 33 2.3.10. Collecting a number of files or directories into a list .................................................................. 33 2.3.11. Select files or directories with the aid of the File Manager ........................................................ 34 2.4. Edit, Create and Delete Entities ....................................................................................................... 35 2.4.1. General......................................................................................................................................... 35 BETA CAE Systems S.A. page 3

ANSA v.12.1.x

Scripting Language

2.4.2. Get values from an entity using its Edit card................................................................................ 35 2.4.3. Modifying the card's values.......................................................................................................... 36 2.4.4. Creating new entities.................................................................................................................... 37 2.4.5 Creating parts and groups............................................................................................................. 37 2.4.6 Creating connection entities.......................................................................................................... 37 2.4.7 Editing the characteristics of a connection entity.......................................................................... 38 2.4.8 Realizing connections ................................................................................................................... 39 2.4.9 Getting the entities of connections................................................................................................ 41 2.4.10. Deleting entities.......................................................................................................................... 42 2.5. Creating user defined buttons and custom GUI ............................................................................ 42 2.5.1. General......................................................................................................................................... 42 2.5.2. Creation of user buttons using the AddUserButton function........................................................ 42 2.5.3. Creation of custom GUI................................................................................................................ 43 2.5.4. Setting Cancel and Ok buttons .................................................................................................... 44 2.5.5. Opening and Destroying Windows............................................................................................... 44 2.5.6. Callback functions ........................................................................................................................ 44 2.6. Setting of controls............................................................................................................................. 45 2.6.1. Setting edit fields and check buttons ........................................................................................... 45 2.6.2. Creating and setting up menus and radio buttons ....................................................................... 45 2.6.3 Creating and setting up List Boxes ............................................................................................... 47 2.6.4 Hiding and Showing controls ........................................................................................................ 50

SECTION 3 EXCHANGING DATA: TEXT FILES I/O ...................................................51
3.1 General ................................................................................................................................................ 51 3.2. Unformatted text files........................................................................................................................ 51 3.2.1. Opening and closing files ............................................................................................................. 51 3.2.2. Reading files ................................................................................................................................ 51 3.2.3. Writing files................................................................................................................................... 53 3.3. XML formatted files ........................................................................................................................... 54 3.3.1. Opening xml files.......................................................................................................................... 55 3.3.2. Getting nodes and sub-nodes...................................................................................................... 55 3.3.3. Getting the name of the node ...................................................................................................... 55 3.3.4. Getting attributes and node data.................................................................................................. 56 3.3.5 Writing XML files and setting the base node................................................................................. 56 3.3.6 Creating nodes.............................................................................................................................. 56 3.3.7 Setting attributes and node data ................................................................................................... 57

SECTION 4 SPECIALIZED FUNCTIONS .....................................................................58
4.1 General ................................................................................................................................................ 58 4.2 Description of Specialized functions ............................................................................................... 58 4.2.1 Creating Connectors and GEBs with scripting.............................................................................. 58 4.2.2 Executing specialized script functions from Connection Manager ............................................... 60

SECTION 5 HANDLING SCRIPTS AND ANSA_TRANSL ...........................................64
5.1. General ............................................................................................................................................... 64 5.2. Using command window .................................................................................................................. 64 5.2.1 Quick view of auxiliary built in functions........................................................................................ 64 5.2.2 Description of auxiliary built in functions ....................................................................................... 64 5.2.3 Loading scripts .............................................................................................................................. 65 5.2.4 Running scripts ............................................................................................................................. 66 5.3 Using script menu .............................................................................................................................. 67 5.3.1 Script menu interface .................................................................................................................... 67 5.3.2 SCRIPT category .......................................................................................................................... 67 5.3.3 FUNCTION category..................................................................................................................... 68 5.4 Automation through an ANSA_TRANSL file.................................................................................... 69 5.4.1 Location of ANSA_TRANSL file.................................................................................................... 69 5.4.2 How does ANSA interacts with ANSA_TRANSL .......................................................................... 69 5.4.3 Form of ANSA_TRANSL............................................................................................................... 69 5.4.4 What is a global code.................................................................................................................... 70 BETA CAE Systems S.A. page 4

.................................................5.......................................................................................................ANSA v......................................... Importing CAD files .........12.....4 Making use of the immediate tab ................3 Running scripts ...................................... 76 6........ 71 5................... 77 6.........................................................................4...........6 Compiled scripts.....2 Opening scripts ............................................................................................................... 76 6................................................................................................. 77 6..... 77 6....................................................................................................................................................................... page 5 ...................7 Making or importing snippets ................................................................................................................ 79 BETA CAE Systems S.......................................1.....................6..........................................................................................8 Debugging scripts ...1 Script Editor Layout.5 Help area....76 6.............................A...... Executing functions without any user interaction (autoexec)............................................................ 75 SECTION 6 SCRIPT EDITOR ...................................................... 76 6.....4............... 77 6..............x Scripting Language 5..........................

General A general description of the scripting language is given below. Strings s = "a string". we declare a series of printable text characters representing human readable stuff.Datatypes .User Functions .8. The description is organized in the following main sections: . page 6 . "this is a string") and can be assigned to any variable for storage and easy access. Elements This is ANSA .5. Note however that variables used in ANSA scripts.A. matrices etc. Such variables are represented in memory by 32 or 64 bits depending on the machine architecture. As string. In the latter case the decimal part is multiplied by the power of 10 after the E symbol. Typically.1.GUI Reference 1.5.2.x Scripting Language Section 1 Description of the Scripting Language 1. then you have an integer. A floating point variable can be expressed as a decimal number such as 112. as well as user defined types. Integers my_var = 10.Handling Model Data .1.Loop Statements .2). A floating point must contain a decimal point.Operators . strings.12. If you write neither.specific data type.2).8. the element data type is used in the declaration of function arguments (See Section 1. Floating point numbers are represented in memory by 32 or 64 bits depending on the machine architecture. Data types include integer or floating point numbers. or an exponent or both. are considered typeless and their type must be explicitly defined only when they are used as arguments of functions (See Section 1. Data Types The data type determines the kind of data that a variable or a function can hold. or with an exponent such as 1.Conditional Statements . representing entities used within the model. Values that are not integral are stored as floating point numbers. A string value is enclosed in quotes (e. BETA CAE Systems S. for example a shell element or a property or a set.125E2. Floating Point my_var = 112. The keyword used to declare such entities is element.Variables . The following paragraphs describe the available data types for writing an ANSA script.g. String variables are internally represented as arrays of characters. The integer data type is used by variables that can only have whole numbers as values.ANSA v.

projectfile. string. the language reserves some "names" as "keywords". 1. element.3. defbutton. foreach. PART_COORD_SYS_Z. default. the data type must be declared only when a variable is used as an argument of a function. Names usually indicate the kind of information that is stored in the variable and must be chosen in a manner that will not confuse the user. global. 4. 6. static. 11.1. or more conveniently.The data type describes what particular kind of data is stored in a variable. void. PART_COORD_SYS_DY3. 9. reserved words: include. PART_COORD_SYS_DX3. entrypoint reserved variables: FILENAME. continue. 7.. such as an integer number. user scripts can be more elegantly and concisely expressed if they can be written in terms of aggregate structures. script.The value of the data that a variable contains at any point is determined by the instructions of our code and. User Defined Data Types (structures) In many cases. byref. this value will usually change many times during program execution. Variable Name surface_area surface-area surface area SurfaceArea _surface_area surface@area _1-Surface Surface"1" Surface_1 Surface/1/ 1Surface Validity Valid Invalid Invalid Valid Valid Invalid Valid Invalid Valid Invalid Invalid Reason -Is considered an operation Contains blank space --Contains reserved characters -Contains reserved characters -Contains reserved characters Begins with a number Although the number of characters in a variable name can be unlimited. case. As we saw earlier. All other characters including the blank space are illegal. FLANCH_PROPERTY_ID. The following table lists some valid / invalid variable names: # 1. BETA CAE Systems S. 2.x Scripting Language 1. 3. possibly of different types. The reserved characters and reserved words for writing an ANSA script are listed below: reserved characters: =^*/+-%&'"\!(){}[]:. PART_COORD_SYS_DZ2. def. matrix. Variable names can include the letters A-Z (in upper or lower case). strict. for. These names are used to represent internal functions and are not allowed to be used as variable or function names. break. grouped together under a single name for convenient handling. its type is defined by the way the variable is used. it is usually a good programming practice to keep it short. a variable name. switch. A variable name is case sensitive and must begin with a letter or an underscore.ANSA v. 10. float. PART_COORD_SYS_DY2. Furthermore. ie. return. map pointer. page 7 . Naming of Variables and Restrictions The name we give to a variable is called an identifier.1. int.12.3. For every variable we distinguish its data type and its value: . PART_COORD_SYS_X. 8.2. PART_COORD_SYS_DX1. do. PART_COORD_SYS_DY1.1. PART_COORD_SYS_Y. char.<>. FILEPATH. in all other cases a variable is typeless. a string etc. . Such structures can be considered as user defined data types that represent a collection of one or more variables. the numbers 0-9 and the underscore character. goto.A. Variables A variable is a named memory location that contains data and can be modified during script execution. PART_COORD_SYS_DZ1. of course. 1. PART_COORD_SYS_DZ3. in. 5. if. else. while. PART_COORD_SYS_DX2. struct. The keyword used to declare such collections is struct and the individual variables within the collection are called its members.

it will switch from integer to string type. float and string variables respectively. then this line will be ignored.ANSA v.1. SYMMETRY_PART_PID_OFFSET reserved constants: NASTRAN LSDYNA PAMCRASH ABAQUS RADIOSS ANSYS CFD MORPH 1. where <variable name> is the name of the variable. PART_MATERIAL_NAME. Therefore. PART_NAME. Thus. SEPARATORS. 1. if var1.4. typeless variables can be proven dangerous when they must be passed as arguments to a function.3. For example. PART_PROPERTY_THICKNESS. If a user tries to explicitly define the type of a variable. Operators are used in order to compute new values out of old ones. TRANSLATIONS. Operators and Basic Calculation Various data types can be combined. string var3) 1. For example. However. assignment operators BETA CAE Systems S. the same variable is found in another statement like: my_var = "my string". POST_TRANSL_SCRIPT. Expressions and assignments for numeric data types An expression is formed by the combination of variables. This is done by an assignment statement whose general form is: <variable name> = <expression>. PART_PROPERTY_ID. MAT_REG. the data type of all variables that are communicated to a function must be explicitly declared in the functions' arguments.1. PART_MATERIAL_ID. since the same variable can be used in different ways. you should not explicitly define the data type of variables.A. to form expressions. Note 2: When to define the Data Type of a Variable The use of typeless variables reduces the total number of variables used in a script. PART_VSC. since the function should be aware as to how to treat these variables. by the appropriate operators. The results of a calculation can be stored for future use by assigning a value to a variable. int my_var. But. This is because all variables used in ANSA scripts are considered typeless and will automatically acquire the proper data type depending on their use at the time. PART_MODEL_NAME. in a statement like: my_var = 13. float var2. These expressions are evaluated when the script is executed. Important Notes on Variables Note 1: Typeless Variables When writing ANSA scripts. The sets of operators and the rules of how expressions may be written and evaluated are determined by the types of the operands involved. eg. they should be declared as: def my_function (int var1.4. the data type is a very critical attribute of any data value. constants and operators. while <expression> is an expression formed by the combination of variable names using operators.2. in such cases. the variable my_var is treated as being of integer type. and can be of two types: 1. PART_VERSION. PART_MASS. if later on. page 8 . arithmetic operators 2.12. POST_TRANSL_SCRIPT_ARGS.x Scripting Language PART_ID. PART_PROPERTY_NAME. SYMMETRY_PART_ID. var2 and var3 represent integer.

The expression i = i + 1. while i = i . Operator precedence The order of precedence is very much alike what is known from algebra. The meaning of such expressions is resolved by defining an order of precedence for operators. is a standard programming idiom for increasing a variable's value by 1. i = i / 2. interior_vol = exterior_vol-width_x * width_y * width_z. page 9 . 1. For instance. Operator + * / ** Operation Addition Subtraction Multiplication Division Exponentiation Some examples of arithmetic expressions are: surface_area = width_x * width_y. the 2nd example might be interpreted as interior_vol = (exterior_vol-width_x) * width_y * width_z. multiply and divide it by 2 respectively. These are: # 1. sets x to 1.ANSA v. Multiplication and division have equal precedence. or interior_vol = exterior_vol-(width_x * width_y * width_z).4. 4. hypot2 = a**2 + b**2.1. i = i * 2. The assignment operators are the ones that actually assign a value to a variable. the meaning of the 2nd and 3rd examples might not be clear.x Scripting Language There are five different arithmetic operators that can occur in numeric expressions. For example x = 1. 5. Thus. The well known “=“ sign is an assignment operator. exponentiations are carried out first. sets a to whatever b's value is. The same applies for addition and subtraction. This precedence will determine the order in which the expression is to be evaluated. the expression is evaluated from left to right. 2. will decrease a variable’s value by 1.A. is understood to be (x / y) * z and not x /(y * z) BETA CAE Systems S. When a number of multiplications and divisions are found in sequence. 3. and a = b.2.1. However. then multiplications and divisions and finally additions and subtractions. the expression x / y * z .12. Thus.

such as the square root of a number. i--. i -= 1. where v does not have to be mentioned twice.1. to enable such functions to be evaluated easily.A. 1. Important Notes on Operators Note 1: Combination of assignment with arithmetic operators The pattern: v = v op value. Note 2: Increment and decrement operators For the most common cases where we add or subtract the constant value 1 from a variable. and to the fully expanded: i = i + 1. 1.4. 1. can be shortly expressed as: v op = value.12. multiplication and division operators +. 1./ and value is a constant arithmetic value.ANSA v.4. These expressions correspond to the slightly longer: i += 1. BETA CAE Systems S.*. In their simpler form. Thus.4.1. op is any of the addition. the expression: x /(y * z).3. For example. the expressions i i i i = = = = i i i i + * / 1. where v is a variable. subtraction. they look like this: i++. ANSA scripting language allows the use of auto-increment or auto-decrement operators. i = i . can be equivalently written as: i i i i += -= *= /= 1. Some of the most important arithmetic functions are given in the table below. The ANSA scripting language incorporates several such intrinsic functions. 2. Numeric intrinsic functions It is often necessary to evaluate special mathematical functions. page 10 . 2. will be evaluated exactly as written. the sine or cosine of an angle.x Scripting Language It should be noted here that the use of parentheses can force the order of evaluation of certain expressions. 2. 2.-.

The operators that can be used to form expressions between string data types are: # 1. float z. 5.4. the string variable property = "PSHELL". 9.12. The above line defines a structure called point whose members are an integer called point_id and three floats for the coordinates x. Expressions and assignments for user defined data types (structures) A typical example of a user defined data type can be the point collection: Each point occupies a position in space as dictated by its coordinates and may also have a unique ID to distinguish it from other points.6. mat_name = "steel_105". page 11 .4. if we need to declare a point PA in space. The syntax for this reference is struct. The point coordinates are real numbers and the ID is an integer.A. 2. or with the equivalent property_id = property % id. intrinsic function Sqrt(x) Cos(x) Sin(x) Tan(x) Exp(x) Log(x) Asin(x) Acos(x) Atan(x) Abs(x) Description calculates the square root of x calculates the cosine of x calculates the sine of x calculates the tangent of x calculates e raised to the power or x calculates the natural algorithm of x calculates the arcsine of x calculates the arccosine of x calculates the arctangent of x calculates the absolute value of x comment -x is given in radians x is given in radians x is given in radians ----result between –pi/2 and +pi/2 -- 1.5. For example. operator + % operation string catenation string catenation For example. can be catenated with the string variable id = "with id 1". 7.x Scripting Language # 1. 8. and assign to the property_id variable the value "PSHELL with id 1" 1.member and in this case takes the form: BETA CAE Systems S. z. These point data can be grouped under the same structure in the following way: struct {int point_id. y. Now. Once the structure is defined. 6. float x. using statements similar to those of numeric types: property = "PSHELL".1. as property_id = property + id.} point. 10. y. float y. the PA variable can automatically reference the members of the point structure. in other words PA can reference its id and its x.ANSA v. z coordinates. we just need to type: point PA. it can be used as a regular data type for the declaration of other variables. 2. Expressions and assignments for string data types Characters may be assigned to string variables. 4. 3.

78. 2. Since matrix members are actually variables.z = 456.e.23. it is often necessary to handle data as sets of similar or different kind objects. to assign number 13 as the id of point PA type: PA. PA. "a". A matrix data type provides a way to collect entities under the same storage. len = MatLen(m). m[0] is the first element in a matrix. For example.00. we can declare an array (matrix) of points. pts[5].A. to declare an array called pts of 10 points in space using the structure point type: point pts[10]. As an extension to declaring a single point PA that belongs to the structure point. Matrices matrix m[10].45.z = 456. i. The function MatLen returns the length of matrix m.5. 1. Indices run from 0 to allocated space -1. Matrix members are accessed with index operators. Sets of data: Matrices and maps Most problems that occur in practice require more than simple variables for their definition and solution. matrices should be declared so that the program will reserve enough space to store the data.12. "some string". 99. so a matrix like: m={1..point_id = 13. As a good programming practice.1.point_id = 13.the id of point PA …x-coordinate of PA …y-coordinate of PA …z-coordinate of PA PA. for matrix m[10] they run from 0 to 9.x PA.y PA. to assign 13 as the id of the 5th point of the pts array. The reference to the individual variables of the pts array follows the same rules as before. and to assign the coordinates of pts[5] type: pts[5]. they can hold any type of variable. type: pts[5].ANSA v.x = 123..00.23}. PA. and to assign the coordinates of PA type: PA.y = 321.e. 1.y = 321. page 12 .x Scripting Language .point_id PA.z For example. pts[5]. For example. Towards this direction comes the definition of matrices and maps.1.x = 123.5. Thus. BETA CAE Systems S. i. The corresponding keyword for this declaration is matrix. 1.78.45. is perfectly valid.

To specify all the matrix members at once: m = {10. We can get any part of the string by using the indices of the characters.9}.A. Here are some examples: str str str str str str str = = = = = = = str(1:6). A string has a length equal to the number of characters that comprise it and each one character holds an index. In the former case. page 13 . For the 3x3 2 dimension matrix given above: i = m [1][0]. Having two conformable matrices A and B 2x3: BETA CAE Systems S. a matrix like: m = {{10.9}. For example the expression: B = 10*A. //This str(5:). will result to a matrix B whose members are 10x the corresponding members of A. would form a 3x3 2 dimension matrix.ANSA v.//This str(8:8). //This str(:7).7. will assign to i the value of 5. Retrieve a matrix member value: To retrieve a value of a specific member of a matrix. subtraction.2. //This will will will will will will will get the "Bumber" get the "Front" get the character "F" get the character "_" get the "mber_F" ge the "er_Front" get the "Bumber_" Important Note: The string length can be found using the function Strlen. Addition.12. //This str(3:8). //This str(8:12). {5.7.x Scripting Language Set some data in a matrix: To set some data to a specific position in a matrix: m[3] = 10.17} {6. matrices having the same shape). u has index 2……and t has index 12. str = "Bumber_Front". Thus. division and exponetiation operations between matrices should take place only between conformable matrices (i. the multiplication operation can take place both between conformable and unconformable matrices. the user must provide the corresponding index operator: i = m[0]. //This str(7:7). Matrix expressions: All algebric operations between matrices and constant values are interpreted as operations between each member of the matrix and the constant value. the multiplication takes place between each member of the matrices while in the latter case a matrix multiplication takes place.e.12. Handling strings as matrices Strings can be treated as matrices and in this way we can isolate any part of them without the use of any built in function. The first character has index 1 and the last has index equal to the string length. On the other hand.1. Matrix members can even be other matrices.25}}. The above string has 12 characters where B has index 1.

10.9}.2. CrossProduct(vec1. will lead to a matrix C 2x1: C = {{10*1+7*2+9*1}. The following table summarizes the intrinsic functions available for the management of matrices: # 1. {5.17}}. 8.A. 2x3 and B 3x1: A = {{10.no_of_values).17}}. vec2). a multiplication operation: C = A * B.no_of_values).2.12. Function MatLen(m). {2}. DotProduct(vec1.x Scripting Language A = {{10. MinIndex(m.1}}. {5*1+2*2+17*1}}.9}.17}}. TransposeMatrix(m) MaxIndex(m.1. 6. {5. B = {{1}. NormalVec(vec) Normalize(vec).no_of_values). 7. Having two non-conformable matrices A.9}. 2. {1. {1}}. page 14 . {5.no_of_values).4. Description returns the length of the matrix m returns the min value of the matrix m for the first no_of_values returns the max value of the matrix m for the first no_of_values returns the CrossProduct of vector 1 and vector 2 finds the dot product of vector 1 and vector 2 computes a unit normal vector of input vector 'vec' normalizes a vector transposes m finds the index of the maximum of an array of no_of_alues finds the index of the minimum of an array of no_of_values BETA CAE Systems S.1. 3. 5.1}. will lead to a matrix C: C = {{20.7. a multiplication operation: C = A*B. vec2). 4.7.2. Max(m.7. Min(m.ANSA v. 9. B = {{2.

However.5. where each node holds a specific value and is referenced by a specific key: (map_name. page 15 . To set some data to a specific node on a map. i = GetLastNode(m. key. An equivalent expression would be: m[1140] = 1. Retrieve a node value: To retrieve a value of a specific node. key. value). a number or even another map.1). An equivalent expression would be: i = m[1140] Delete a node: Deletion of a node within a map is achieved using the EraseMapNode command: EraseMapNode(m. since the former node uses a stringtype key and the latter node uses a numeric key. with larger maps taking precedence over smaller maps. key. Set some data in a map: When a map is created and initialized. use the SetMapNode: SetMapNode(m.1. A map data type can be seen as an expansion of the matrix. the user must first identify the first or the last node of the map using the GetFirstNode or the GetLastNode commands respectively: i = GetFirstNode(m.A. For example. 1) will assign the value 1 to the node holding the key 1140. Note that when maps are used as keys.ANSA v. it is originally blank. For example. value). The value of a map can be either a string or a number. the key can be a string. the user must provide the corresponding nodal key using the GetMapNode function: i = GetMapNode(m. key). will assign to i the value of 1.1140.g. key). when the map is not defined or is empty).1) comes after node (m. The keyword that specifies this data type is map.12. the command SetMapNode(m. the command i = GetMapNode(m. Iteration through the data in a map: In order to search through the data of a map. you need to initialize it first using the command CreateMap: m = CreateMap().x Scripting Language 1.2. Maps map m. A map is characterized by a name and is like a user defined treestructure. they are sorted according to the number of nodes they have. value). key. value) Note that to use a map. node (m.2). for the node (m. since the indexing is done with arbitrary values. BETA CAE Systems S."1140"). Nodes within the same map are sorted according to their key and the corresponding precedence order is: number > map > string For example. 1140. Both functions return 1 on success and 0 upon failure (e."1140"."1140".

value). i = GetPreviousNode(m. 3. else statement. GetLastNode(m.1. Identify the number of nodes in a map: To identify how many nodes a map contains.A. value).key.6.value). Such operators are summarized in the table below: # 1.e. key. The "if-else" blocks and the logical operators The if statement is the basic decision statement of a script.x Scripting Language Looping through the map is achieved using the GetNextNode and GetPreviousNode commands: i = GetNextNode(m. 6. key.12. GetFirstNode(m.key). Description initialize map m assign a value to the node referenced by key retrieve the data of the node referenced by key erase the data of the node referenced by key return the first node of the map forward advance to the next node of the map return the last node of the map backward advance to the next node of the map delete map and release memory identify how many nodes the map contains 1. Since the condition is interpreted as a logical operator.key. 2. DestroyMap(m). page 16 . GetNextNode(m. use the DestroyMap: DestroyMap(m).key). Destroy the map and release memory: To delete a map. then the else-block of statements is executed. value).6. GetMapNode(m. 5. Its operation is based on the evaluation of a condition that will yield a result that is either true or false. If the condition is false.key.value). GetPreviousNode(m.key. then the if-block of statements is executed. 7 8 Operator < <= > >= == != || && Meaning less than less than or equal to greater than or equal to greater than or equal to equal to not equal to Logical OR Logical AND BETA CAE Systems S. SetMapNode(m. not equal to 0).value). If the condition is true (i.1. The following table summarizes the intrinsic functions available for the management of maps: # 1 2 3 4 5 6 7 8 9 10 Function m = CreateMap(). EraseMapNode(m. GetMapEntries(m). 4. The if statement general form is: if (condition) statement.key.value). use the GetMapEntries: i = GetMapEntries(m). Conditional Statements and Branching 1. the operators used for its expression are the logical relational operators.ANSA v. The alternative line of execution is created with else: if (condition) statement.

. The switch statement The switch statement is an alternative form of a conditional statement. if (a>5) { b = 0. then b and c will be assigned zero values. In this case the logical expression a>5 will be evaluated. In this case the logical expression a>5 will be evaluated.. they will be assigned unit values as dictated by the else group of statements. In this case a unit value will be assigned to c only if both expressions are true.. default: statement. In this case the logical expression a>5 will be evaluated. } else if (a<3) { b = 1. c = 0. if(a>5) && b==1) c = 1. Otherwise.2. The expression can evaluate an integer or a string. } The switch statement evaluates the value of an expression and branches to one of the case labels. it evaluates the expression and then looks for a matching case label. break.. If it is proved true. When ANSA sees a switch statement. If none of the conditions is fulfilled. 1. this line will be ignored.. In this case a unit value will be assigned to c only if one of the two expressions is true. If it is proved true. then b and c will be assigned zero values. Otherwise. this block of statements will be ignored. If none is found. case constant2: statement.A.. break.e. The general form of the statement is: switch (expression) { case constant1: statement.which allows the definition of multiple possible execution paths. If no default is found. page 17 .x Scripting Language Some examples of the use of the if-else blocks follow: if (a>5) { b = 0. c = 1.The case labels can be in any order and must be constants or strings. c = 1.. the default label is used. . Otherwise. break. Duplicate labels are not allowed.. the whole block of statements will be ignored. then b and c will be assigned unit values.. } if(a>5 || b==1) c = 1. If it is proved true. } if (a>5) { b = 0.1. In this case the logical expression a>5 will be evaluated. . the statement does nothing. Note that two case labels cannot have the same value. } else { b = 1. then b will be assigned zero value.ANSA v.: BETA CAE Systems S. c = 0. so only one case will be selected. Otherwise. the logical expression a<3 will be evaluated. i. . The default label can be put anywhere in the switch. If it is proved true. c = 0. If it is proved true. then b and c will be assigned zero values.6. /* fall through */ case constant3: statement. } if (a>5) b = 0.12.

"PELAS"}.. The goto statement The goto statement is a powerful branching statement. break.7.1. 1.x Scripting Language a = 2.e. The general form of the statement is: foreach <item> in <array> { do something to <item> } An example of the statement use is given below: all_properties = {"PSHELL". some_label: .7.1. break. When the end of the loop is reached. switch (a) { case 0: Print("a is zero").ANSA v. Loop statements A loop comprises of a block of statements that are executed repetitively. foreach property in all_properties Print (property). /* will fall through default as well */ default: Print("a is not zero").. i. It can be used to create jumps and redirect the execution order of a program."PCOMP". the result is PSHELL PCOMP PBAR PBEAM PELAS BETA CAE Systems S. The foreach statement The foreach statement allows the iteration over the elements of an array.3."PBEAM". 1. the block is repeated from the start of the loop.A. case 2: Print("a is two"). foreach loops do not maintain any explicit counter. break. } The result is: a is two 1. case 1: Print("a is one")."PBAR". if (a>5) goto some_label.6. page 18 . break.12. Its general form is: goto < label > where < label > is the label of an executable statement.

2. a = 0. The program executes the specified statements repetitively for as long as the given condition remains true (i. The for statement The for statement introduces an indexed loop. the condition specifies the number of repetitions and the iteration-statement dictates the increment or decrement value of the explicit counter during the loop. The while statement The while statement introduces a conditional exit loop. The do while construct While the for and while statements check the condition before entering the loop.A.6. page 19 .ANSA v. } 1.e. Its general form is: BETA CAE Systems S. not equal to 0). The initial-statement initializes the explicit counter.7. the result is 0 1 2 3 4 Important Note: When a foreach or for loop statement affects only one line then it is not necessary to enclose this line in brackets: One line is affected for (a=0.12. condition. a<5. Print(a+1). a<5. where the number of repetitions is known before the loop is started.3. If operators are to be used for the expression of the condition. Its general form is: while (condition) body-statement. a<5. The general form of the for statement is: for (initial-statement. a++. while (a<3) { Print(a). the do while construct makes the check after every pass of the loop and thus guarantees that at least one pass will take place. a++) Print (a).7. More lines are affected for (a=0.7. iteration-statement) body-statement. for (a=0.4. these must be of logical relational type (see Section 1.1. a++) Print (a). } the above result will be something like 0 1 2 1. a++) { Print(a).1).x Scripting Language 1.

} In this case the result would be: 0 1 2 The continue statement jumps back to the beginning of the loop’s block to begin the next iteration. A typical example is given below: a = 0. the term main will be used to denote the function which is called by the user to execute the script. The repetitive use of functions saves much time while reduces the chances of error. } In this case the result would be: 1 2 4 1. The break statement allows the termination of a loop regardless of the loop control condition. the result is: 1 1. if ( a == 3) continue. if ( a == 3) break. In the example below a = 1. while (condition). Each user function is given a name. The continue and break statements The continue and break statements can be used to redirect the execution order of a loop. In other words it can lead to an unconditional branching. a++.5. do { Print (a). a++. } while (a>5). it omits a certain block of statements.A.8.ANSA v. Thus. A typical example is given below: a = 0. From now on.x Scripting Language do body-statement. while (a<5) { a++.1. BETA CAE Systems S.12. User functions and comments User functions allow to group a set of operations into a compact unit that can be easily and repeatedly accessed. optionally uses some input parameters (arguments) and returns the results as output parameters. while (a<5) { Print(a).7. page 20 . Print(a).

.. } 1.8... Definition User functions are defined using the def statement.ANSA v. A function that calls another function can store the returned value in an output argument or even can ignore it... This statement is followed by the function name.12. they can return a dummy value. } def fun_to_call2(int id) { .x Scripting Language 1.8. search_type = "GRID".1.A. there must be a way to “notify” the main function that called it for the result of the procedure it performed. counter = 100.2..search_type. string.. element etc) Important note 1: A sub-function can be called from a main function or from another sub-function. Returning data from functions (return. def main() { mass = 1. During the declaration of a sub-function it is necessary to define explicitly the type of the input arguments (int... BETA CAE Systems S...8. Functions that don’t return anything are executed normally and may not use the return command. } def fun_to_call1(float mass.. page 21 . nodes = CollectEntities(NASTRAN.. nodes). matrix nodes) { . Equivalent.0. Important note 2: Variable number of input arguments is not valid. string name.... Statement . fun_to_call2(id). The communication between the functions can be achieved through the return command.3. The rest of the code must be enclosed in brackets: A typical function has the form: def main(list of arguments if exist) { ... id = 10. } 1... float. byref call) Since the target of each sub . name = "right_door". name.... These arguments are passed from the main function as parameters and are used as initial values inside the function that is called.1.. } def fun_to_call3(int counter) { ....function is to perform a certain task.. This command can be used anywhere in the code and is followed by any data.1. Argument list and function call Each user-defined function accepts a number of input arguments (<=40).. fun_to_call3(counter) . fun_to_call1(mass..0)..

} Return dummy value def main() { a = 100. Print(result). return res.//The value of w is 20 } def rect_area(byref int w. This is very useful in cases where it is important for the user to know the new modified values of any variables that had been passed to a subfunction. int b) { res = a-b. b = 50. page 22 . Assures that no mistake will be made since no cutting or pasting actions are performed. int b) { res = a-b. b).A. a[2] = 3.4. } No return def main() { a = 100. then the execution of the script is terminated. def main() { w = 10. result= substr(a. The use of include has 2 major advantages: i) ii) The files remain short.ANSA v. result = substr(a. return 1. b).1. rect_area(w. } def substr(int a. h = 1. counter = counter +10. This declaration is made with the include statement. int h) { a = w*h. Another way of exchanging data is through the byref statement. Including Files Scripting language enables the collection of several existing functions into a file. } def substr(int a. w = w+10. a[1] = 10. } Only the data that are passing through the return command are valid for the main function.x Scripting Language Return value def main() { a = 100. result = substr(a.8. b = 50. BETA CAE Systems S. Important note: If the return command is used in the main function. } def substr(int a. The include statement must be declared in the global section of the script and is the best way of collecting functions.bs" #include "/home/work/FindNear. Print(w). h). int b) { res = a-b. b = 50. Print(result).bs" def my_fun() { a[0] = 11. b). Print(result). #include "/home/work/MinToMax. } Important note: The matrices and maps are considered byref by default 1. Each line like the one below: #include "fullpath to the name of file" is substituted from the contents of the included file (the quotes are necessary).12.

0.ANSA v. } Example of external static variable (2) static s. new_eid = eid+offset. Similar to this. } else s = s+1. subfun().A. external static variables help us to “hide” the function names and thus avoid possible conflicts. When a variable is declared within a function. search_type[0] = "SHELL". if(!IsInitialized(s)) { //Iniatializing s s = 0. def main() { offset = 1. global offset. Print("s value from main:"+s). An internal static variable can be defined in a user function and it is valid only for this function while holds its information regardless of the number of times the function will be called. In contrast to local variables. global variables must be declared prior to the definition of any function. an external static variable is valid throughout the script where it is defined. } def subfun() { Print("s value from subfun:"+s). Print("s value from main:"+s)."EID".1. then only the code within this function can access or change its value.0). Consequently. } BETA CAE Systems S. } } There is also a third type of variable called static. } def fun1(matrix shells) { foreach shell in shells { GetEntityCardValues(NASTRAN. fun1(shells). Example of internal static variable (1) def main() { static s. and are defined using the global keyword.eid). A static variable can be either external or internal and its major difference from the other two is that it can keep its value even if the execution of the script has come to an end. It is then said that this variable is local to this function. } else s = s+1.12.x Scripting Language MinToMax(a). offset = offset + 10. so they can be accessed and changed by any individual function of the program. As a result. def main() { if(!IsInitialized(s)) { s = 1. eid = GetInt(eid).shell. there is no conflict to have two or more variables of local character sharing the same name in different functions. Scope and lifetime of variables A variable's scope is determined by where you declare it. subfun(). //FindNear function has been included in the global section } 1.8. We can define any number and type of global variables.//MinToMax function has been included in the global section FindNear(). } def subfun() { Print("s value from subfun:"+s). page 23 . global variables are valid throughout the program. shells = CollectEntities(NASTRAN.5.search_type.

s from subfun = <empty> Execution 2 ---> s from main = 2.ANSA v. Recursive structures in ANSA have been proved very helpful when trying to search into entities that have a hierarchical structure. s from subfun = <empty> Execution 3 ---> s from main = 3.x Scripting Language In the first example the value of the variable after each execution will be: Execution 1 ---> s from main = 1.string path.path. } static def subfun() { Print("value of script 1: 10"). Suppose that we have loaded two scripts that both use a function called “subfun”.string type) { f = FileList(path+"/*"+type). if(f!=0){ foreach file in f{ filenames[i++] = file. Print(file). } def parse_tree(matrix filenames.1. } SCRIPT 2 After the execution of main1 the result is 'value of script 1: 10' After the execution of main2 the result is 'value of script 1: 20' 1.new_path.. parse_tree(filenames. page 24 ... no_of_files = MatLen(f). } } } BETA CAE Systems S.6. s from subfun = <empty> etc. s from subfun = 3 Execution 2 ---> s from main = 2.8. In order to avoid a conflict we define each of the common functions as static.12. type = "ansa".type).. A common example is the extraction of all ansa files that exist under a directory tree. } static def subfun() { Print("value of script 2: 20"). parse_tree(filenames. def main() { filenames = 0.A. path = "/home/demo/model".. This means that a function can call itself as many times as needed.type). s from subfun = 2 Execution 3 ---> s from main = 1. while in the second example: Execution 1 ---> s from main = 3. } } m = DirList(path).. if(m!=0) { foreach d in m{ new_path = path+"/"+d. Recursive structures Recursive structures are supported through scripting language. s from subfun = 1 etc. SCRIPT 1 def main1() { subfun(). } def main2() { subfun().

20. for(k=0..ANSA v. Initialization and un-initialization of matrices and variables A well-structured algorithm implies that any variables or matrices that change their values during the execution of a script must be first initialized. len = MatLen(data2). foreach part in parts { container[0] = part.. To release the memory occupied by variables or matrices. This function finds application in cases an existing matrix must be refilled with new data.12..8. } 1.k<len...//The container must be in a matrix form faces[k++] = CollectEntities(NASTRAN.. } . len = MatLen(data1). } .8.k<len.search_type. A variable or a matrix are initialized by assigning to them an initial value (zero value is preferred in most of the cases).0. statements .. ReleaseVar(m)...x Scripting Language Important Note: Only for the recursive structures the elements (pointers) are considered byref. //Define matrix data1 data1 ={10..k++) { m[i++] = data[k]..7. Use of help text and comments in functions The common practice has proven that even the most experienced programmer needs to keep some comments in order the code to be more readable and understandable. k = 0.1).A.8. data2 ={1. } } A comment line denoted by // symbol can be incorporated in a comment block (/* comment */).4}. The initialization is very crucial especially when a variable is used as counter for filling the indices of a matrix.40}. In ANSA scripting language there are two ways to add comments... page 25 . for(k=0. 1.2. parts = CollectEntities(NASTRAN. def my_fun() { //Collect the parts search_type[0] = "ANSAPART". statements .k++) { m[i++] = data[k].search_type... BETA CAE Systems S..0). the ReleaseVar function can be used to reset them to “un-initialized” state. The first is to use the symbol // which is practical in cases where a singleline comment is needed.3.30.container. //Initialize matrix m m = 0. /*Use each part as a container in order to collect its faces*/ search_type[0] = "FACE". For commenting-out a number of subsequent lines use the bounds of a /* comment */.1. def main() { //Initialize counter i i = 0.

## Name: NcogToSet Description: Function that adds the Ncog nodes of PAMCRASH rbodies to a set ## def NcogToSet() { statement } The user script help can be accessed in ANSA through the built in command script_help which is invoked from the command line and through the FUNCTION>RUN function of the SCRIPT menu. Session commands for use in Scripting Language All session commands can be used within the scripting language as well.9. This description is a text that must be enclosed between the symbols ## and must be written always prior to the function which describes.1.A.x Scripting Language A script function can also have its own help description. . All numerical arguments (if any) following the ":" symbol should be included into the paranthesis separated by commas.the ":" at the end of a session file command is substituted by a parenthesis "( )". NEW("discard"). SAVE_AS("filename").blank spaces and the ">" symbol in session file commands are substituted by an underscore "_" in ANSA Scripting Language. Non-numerical arguments should also appear within quotes. MESH_SHELL_MESH_FREE(). BETA CAE Systems S. Further informations and guidelines regarding loading and running scripts will be discussed in Section 5. 1.ANSA v.8. following this convention regarding the command syntax: . Examples: SESSION FILE Syntax TOPO>FACEs>ORIENT: SAVE AS: filename NEW:DISCARD MESH>SHELL MESH>FREE: SCRIPTING LANGUAGE Syntax TOPO_FACES_ORIENT().12. page 26 .

10. Building and executing batch mesh sessions. This entity name is of major importance since this is the keyword that must be used in order to collect the entity itself and to have access in its contents. Running automatically (after launching ANSA) a series of functions. Creating a model hierarchy. 2. Assignment of attributes to parts. 6. 12. page 27 . can be also referenced by elements (pointers). Use of system commands. 3. 13. Exceptions to this rule are the ANSA part and ANSA group. materials. 5. 9. All these tasks that can affect the model definition. BETA CAE Systems S. properties etc. Since the scripting language is C-like. Communication with the interface (File Manager functions.2. Before proceeding to the explanation of individual functions. Use of session commands 11. For example.1.2. one of the data types that are used within scripting language is the element (The user must not confuse it with the elements of ANSA DECKS). Using this element (pointer). Some entities that do not have cards in GUI like batch mesh sessions. each NASTRAN "shell" has a card with name SHELL and this is the keyword that must be used for dealing with this type of entity. 2.2. enclosed in brackets. Some of the tasks that can be performed within scripting language are the following: 1.ANSA v. General The basic idea behind the scripting language is to automate many repetitive and tedious procedures with the minimum user interaction or even to perform specific tasks that are not covered by the standard ANSA gui commands. it is important to emphasize in two basic topics: the treatment of ANSA elements and the meaning of ANSA entities and cards. Pick functions).A. An element (or pointer) either includes all the data held by an entity. Can be called anytime without reopening a file and as many times as the user wants. 7. ANSA cards and entity types Most of the entities in ANSA GUI have an entity card that includes all necessary infromations regarding them. The type of each entity is displayed on the card window header. The labels of card fields are also important since they must be used in order to get their values. Data of element type As mentioned in section 1. 4. we can access the contents of cards or we can even affect an entity (like translating a part or making a property visible). 2.1. are controlled through a series of functions that interact with the ANSA interface. or the entity itself. Creating user defined windows and buttons. Extracting any type of information from an already defined model. 8.x Scripting Language Section 2 Interacting with ANSA 2. Co-operating with the MORPH tool for controlling an optimization loop. Reading and writing ASCII files.12. which most of the times is the information that is included inside an entity card.2. Handling Data 2. Selections that take into account any criteria. we can say that the meaning of this type is similar to the pointer of the C language. which use different keywords.1.

Finally. Collecting entities 2.3.A.1.ANSA v. This can been seen if the function EditEntity is called. the deck curves use a variety of keywords that can be found under the help text of the built in function CreateLoadCurve. 2. page 28 .1.12. Keep in mind that all connection entities have cards that are actually hidden. BETA CAE Systems S. General The most significant functions for collecting entities are those that displayed in the following table: Common characteristic of these functions is that they return the elements (pointers) of the entities.3.x Entity keyword Scripting Language Field keywords The keywords of the entities that either don't have entity cards or the rule described before doesn’t cover them are the following: # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Entity type Ansa part Ansa group Batch mesh session Batch mesh group Spotweld Points Spotweld Lines Adhesive Lines Adhesive Faces Seam Lines Gumdrops Hemmings Bolts Solid facets Continuum shell facets Description ANSAPART ANSAGROUP BATCH_MESH_SESSION BATCH_MESH_SESSION_GROUP SpotweldPoint_Type SpotweldLine_Type AdhesiveLine_Type AdhesiveFace_Type SeamLine_Type GumDrop_Type Hemming_Type Bolt_Type SOLIDFACET TSHELLFACET Important Note: The keywords for points and geometric curves are "POINT" and "CURVE" respectively.

Report entities gathered since the previous matching call to the CollectNewModelEntitiesStart function End collection monitor for new entities created or imported to the model Collect types of entites that exist in model The types of entities that can be collected using these functions are: ELEMENTs (SHELLs.2. BETA CAE Systems S.x Scripting Language # 1 2 3 4 5 6 7 8 Function CollectEntities GetEntity GetFirstEntity GetNextEntity GetPartFromModuleId Name2Ents CollectNewModelEntitiesStart ReportNewModelEntities Description Collect entities massively Get a single entity Get the first entity according to its id Get the next entity according to its id 9 10 CollectNewModelEntitiesEnd TypesInCategory Get PARTs or GROUPs Get entities from their name Start collection monitor for new entities created or imported to the model.ANSA v.12. SOLIDs. SHELL) the appropriate function is the CollectEntities. Its syntax is very flexible and can accept either matrices or single elements (pointers).1. BEAMs. Let's see the capabilities of the CollectEntities function with some examples. 2. the first argument is an integer that refers to the DECK for which we require the entity type. One of the advantages of this function is that it can be used for finding entities that are used by other entities while it is the only function that can collect visible entities.3. etc) COORDINATE SYSTEMs CONSTRAINTs LOADs CONDITIONs (intial or boundary) BOXes SETs GRIDs ANSAPARTs ANSAGROUPs CONNECTIONs (all types) POINTs CURVEs PROPERTIEs MATERIALs INCLUDEs CONNECTORs GEBs Important note: The GetEntity function cannot collect ANSAPARTS and ANSAGROUPS of PART MANAGER In any of these functions where the "type" of an entity is required. These integers are given internally to ANSA and the user needs only to type the corresponding DECK name: NASTRAN LSDYNA PAMCRASH ABAQUS RADIOSS ANSYS Important note: If zero value is given instead of the deck name.A. Collecting entities massively from the whole database For collecting massively a type of entity (e. A variable number of input arguments can be specified as well.g. then the current deck will be taken into account. page 29 .

if we want to search for entities inside a container we BETA CAE Systems S. In scripting language terminology. def main() { //Collect first the shells of the whole database shells = CollectEntities(NASTRAN.search_type.search_grid.0).0)."GRID". search_type[1] = "PSOLID". For instance. The output argument is a matrix that contains the elements (pointers) of PSHELLs and PSOLIDs of the database. ents = CollectEntities(NASTRAN.x Scripting Language def main() { /*Define into a matrix the keywords of entities that you want to collect.shells.0). SHELLs are of higher level than GRIDs while PSHELLs are of higher level than SHELLs and GRIDs.sets."SET"). def main() { //Collect the sets of the database sets = CollectEntities(NASTRAN. //Collect all the entities that belong to these sets ents = CollectEntities(NASTRAN.0). def main() { //Collect first the shells of the whole database search_type[0] = "SHELL". //Collect the grids of the shells search_grid[0] = "GRID".0. } Instead of matrices in this case we could have used directly the keyword of the entity (as string). The second argument indicates the search domain and in case the user needs to collect entities from the whole database it must be zero.3.0. search_type[1] = "PSOLID". Many entities in ANSA are considered as containers since they include other entities inside them e. } In this approach the input arguments are matrices. The definition of the deck must be compatible with the entities that are going to be collected. page 30 . shells = CollectEntities(NASTRAN. In this case the equivalent keywords for PAMCRASH deck are PART_SHELL and PART_SOLID.0). ents = CollectEntities(PAMCRASH."SHELL". An approach like the following is not accepted: search_type[0] = "PSHELL". So.ANSA v.g SHELLs include GRIDs. 2.1.0. These containers are classified according to their level.search_type. These keywords are taken from the title of their cards*/ search_type[0] = "PSHELL".0.search_type. //Collect the grids of the shells grids = CollectEntities(NASTRAN. grids = CollectEntities(NASTRAN. the matrix of shells is considered as a container and must be given as a second argument in order to prompt the function to search only into the collected shells. A container can be either a matrix or a single element (pointer).shells.0).A.3.12. Collecting entities massively from other entities In this case we would like to collect the GRIDs that are used from SHELLs.0). This setting can be used for gathering all the entities that are included into a superior entity. } The third argument that defines the types of entities that we are looking for can be also set to zero. This makes sense in SETs and PARTs.0. } Attention must be given in the meaning of containers.

3.4. Collecting available entity types of specific deck As we saw in paragraphs 2."SHELL". This is more clear with the following example: Suppose that we have a matrix that contains elements (pointers) of SHELLs and SOLIDs. The searching area string can get the following forms: "__MATERIALS__": "__PROPERTIES__": "__ELEMENTS__": "__VISIBLE__": for getting all available material types of the specified deck for getting all available property types of the specified deck for getting all available element types of the specified deck for getting all types of entities of the specified deck."filter_visible"."PSHELL".pshells. shells = CollectEntities(NASTRAN."GRID". } Similarly we could have written: grids = CollectEntities(NASTRAN. Print(MatLen(shells)).3."recursive". that their visibility can be controlled through the F12 key page 31 BETA CAE Systems S."recursive".0."no"). For finding directly the GRIDs that are used by PSHELLs.ANSA v.pshells.3. } The last argument of CollectEntities is zero since SHELLs is only one level under PSHELLs. In simple cases where specific types are needed. the user just have to open the respective card and see what string to use as keyword. the use of the function TypesInCategory is more than necessary. Print(MatLen(grids)). Important Note: The matrix of elements (pointers) that is returned is not sorted according to the ids of the entities that they reference. the CollectEntities function needs to know what types of entities to search for. and 2.2.0.3.0). The ouput is a matrix with all supported types. ."PSHELL".5. A matrix that contains entities of specific type cannot be used as container for collecting entities of the same type.x Scripting Language can instruct the CollectEntities to search recursively until the lower level. Another equivalent syntax could be: shells = CollectEntities(NASTRAN. It will work only if we search for GRIDs.3.0.0). grids = CollectEntities(NASTRAN. Print(MatLen(grids))."yes"). The function uses two input arguments which are the name of the deck and a string that defines the searching area."yes"). } Important Note: Visible are considered all entities that their visibility is controlled through F12."GRID". The only excection are the FACEs 2. 2.5. Collecting massively visible entities CollectEntities is the only script function capable of collecting visible entities.A.1).1. This is very clear in the following examples.4.12. we have to invoke the function to search recursively until the lowest level. In this case the last argument takes the value 1."SHELL". def main() { grids = CollectEntities(NASTRAN."SHELL". For more complicated cases where the entities that we search for are not well known or they are too many to open their cards one by one.pshells. 2. def main() { pshells = CollectEntities(NASTRAN. def main() { pshells = CollectEntities(NASTRAN.0). In this case the CollectEntities will not work if we define as search type either SHELLs or SOLIDs.pshells.

the GetFirstEnity and GetNextEntity functions must be used.ent=GetNextEntity(NASTRAN. def main() { i = 0. } In this example we got the element (pointer) of the Pam-Crash GROUP with id 100."SHELL").ent.100).0. Keep in mind that we cannot use this function for collecting ANSAPARTs and ANSAGROUPs. It returns the element (pointer) of the entity. Suppose we want to get the elements (pointers) of the PART with Module id "1A" and of the GROUP with module id "100"."GROUP".//Initialize counter i for(ent=GetFirstEntity(NASTRAN. The GetFirstEnity can be used alone in case it is known that the database contains only one entity of specific type and with unknown id. The function for this is the Name2Ents.6. group = GetPartFromModuleId("100")."__MATERIALS__"). page 32 . def main() { part = GetPartFromModuleId("1A"). Collecting entities according to their name Apart from using ids.A.used_mat)). } } The entries of the matrix shells are sorted according to the ids of the shells that they reference.ANSA v. /*Collect the database materials using as search matrix the one that the TypesInCategory returned*/ used_mats = CollectEntities(LSDYNA.3.1. the functions GetEntity .0). For getting the elements of an entity sorted according to their ids.3. foreach used_mat in used_mats Print(GetEntityType(LSDYNA. The supported materials in this deck are too many (>100) and therefore the TypesInCatecory will help to identify them very quickly: def MatsOfDynaInModel() { //Get all supported material types of LSDYNA all_mats = TypesInCategory(LSDYNA. The use of GetEntity presupposes that the type and the id of the entity is known.x Scripting Language "__ALL_ENTITIES__": for getting all supported entities of the specified deck As an example we would like to identify which LSDYNA materials exist in the database. Collecting part and groups from their ids For collecting single ANSAPARTs and ANSAGROUPs that have known ids (Module Ids) the GetPartFromModuleId can be used. GetNextEntity are available. } 2.GetFirstEnity.8. names can be also used as searching pattern for collecting any type of entities. It takes just one argument while it accepts the Perl regular BETA CAE Systems S. Get single entities For getting only a single element (pointer) of an entity. def GetSingleEnt() { group = GetEntity(PAMCRASH.12.3.ent)) { shells[i++] = ent. 2.7.all_mats. } 2.

} } If no entities are found the function returns nothing. First.10. these paths can be passed as strings in other functions.3. "nooffset". Important Note: When it is needed to identify all directory hierarchy it is recommended to use the DirList recursively. ReadConnections("XML". if(type=="PSOLID") pshells[count_psolid++] = ent. } } 2.3.*"). Collecting a number of files or directories into a list For collecting efficiently a number of files (of specific formats) or directories. This case can be identified using the "!" operator. The collected entities are accessed through the ReportNewModelEntities. 2. "on"). A simple code should be like the following: BETA CAE Systems S.A. foreach new_entity in new_entities { Print(GetEntityType(ABAQUS. "". //Distinguish the type of entity if(type=="PSHELL") pshells[count_pshell++] = ent. new_entity)). "nooffset". //Initialize counters count_pshell = 0. def main() { container = CollectNewModelEntitiesStart(). Suppose that we would like to search in whole database for PSHELLs and PSOLIDs whose name starts with "Default" and to store them in 2 different matrices.9."/home/work/connections. InputAbaqus(". A combination of functions must be used in order to recognize all the changes of the model. The container is used as input and as result it returns a matrix of the entities./"+abaqus_model_name. def main() { //Collect entities that satisfy the searching pattern ents = Name2Ents("^Default. A typical example where we can use these functions is when we want to merge a number of ANSA files that exist in many directories: Suppose that all the files exist under 5 directories which are located under a folder named 'my_project'. it is important to set a starting point for collecting anything new. there are times where we import files. page 33 . Monitoring stops implicitly when the function CollectNewModelEntitiesEnd is called. "". This function is used mosly in combination with the GetEntityType in order to distinguish the type of entities. All these actions affect significantly the process since the amount of entities in the current database is increased and thus we may need to know exactly which are the new entities. these functions return a matrix with all the paths that were identified. new_entities = ReportNewModelEntities( container ). count_psolid = 0. ents = Name2Ents("^Default.*").x Scripting Language expressions. Actually.xml"). the commands FileList and DirList must be used. CollectNewModelEntitiesEnd(container). merge databases or read connection files. Collecting all new created/imported entities During the execution of scripts. if(!ents) Print("No entities were found"). The CollectNewModelEntitiesStart when called starts monitoring all the actions in the database and in case a new entity is identified it is stored in a container.12.1. Then. which is declared as output argument. "". "nooffset".ANSA v. It returns a matrix with all the elements whose name fulfils the searching filter."". which is used always between the two aforementioned functions. "". foreach ent in ents { type = GetEntityType(ent). "nooffset".

dir = SelectOpenDir("")."".1. page 34 ."". } BETA CAE Systems S. } or dir = SelectOpenDir("").csv)"). read_file = SelectOpenFile(0. //Loop through the directories foreach dir in dirs { //Find only the ANSA files that exist under each directory ansa_files = FileList("/home/work/my_project/"+dir."". /*The matrix 'read_file' contains only one entry since the the first argument of 'SelectOpenFile' was 0 */ Print("The file that was selected is: "+read_file[0]).ANSA v."".x Scripting Language def main() { //Get the 5 directories and store the paths into the matrix "dirs". read_file = SelectOpenFile(0. SelectOpenFile. SelectSaveFile. Print("Select the directory where the ANSA files are located"). save_file = SelectSaveFile(). } 2.""). "csv files (*. } } //Save in one database SAVE_AS("merged. "/*.csv)"). //Loop through the ANSA files foreach file in ansa_files { //Merge with the default options MERGE(file. "csv files (*. SelectSaveDir. This is an elegant way to use file and directory paths in user scripts.12."".A. if(!dir) { Print("No directory was selected"). The functions that deal with files return a matrix containing strings that represent the full path to the selected files.11.ansa"). if(!read_file) { Print("No file was selected"). Print("The file that was selected for writing errors is: "+save_file). This means that these functions open the File Manager and allow the selection or creation of files and directories. while those for directories return a string indicating the full path to the folder.3. since it enables the interactive definition of script parameters. Print("Select the log file for writing the error messages")."". Print("The selected directory is: "+dir).ansa"). Select files or directories with the aid of the File Manager Scripting language interacts directly with the File Manager through the commands SelectOpenDir. def Selection() { Print("Select the file for reading"). dirs = DirList("/home/work/my_project/")."". } If nothing is selected it can be identified using the “!” operator.

thickness.A. General Once the entities have been collected. page 35 . Let's see how we can get the values of the name. property id and material id of all the SECTION_SHELL cards of LSDYNA deck: BETA CAE Systems S. It always follows functions that had collected a number of entities in a prior step and its arguments are pairs of labels – values.4. modify or delete some of them. Edit.ANSA v.2). Create and Delete Entities 2.4. Get values from an entity using its Edit card The only function that enables the access into the fields of an edit card without changing the contents .4.1. next step is to edit.2.x Scripting Language 2.1. The functions that are used very often for this purpose are: # 1 2 3 4 5 6 7 8 9 10 Function GetEntityCardValues SetEntityCardValues CreateEntityVa CreateConnectionPoint CreateConnectionLine CreateConnectionFace RealizeConnections DeleteEntity NewPart NewGroup Description Get values from a card Set values to a card Creates a new entity Creates a connection point Create a connection line Create a connection face Realize connections Delete an entity Creates new parts Creates new groups 2. These labels are the keywords of the fields as they appear in the edit card (See section 2. The definition of the deck and element are mandatory. is the GetEntityCardValues.2.12.

"IDPRT". Important note: The global labels ( __id__ .1. In this case the function will return the number of wrong occurrences."MID". The status variable will be 1 since the thickness field label is wrong ("T" instead of "T1")."T". status = SetEntityCardValues(PAMCRASH.1. //Initialize counters count_name = 0.x Scripting Language def GetValues() { props = CollectEntities(LSDYNA.. names[count_name++] = name.75). Although the 'IDPRT' is correct."Name"."__prop__"."Name". SetEntityCardValues(PAMCRASH. pids[count_pid++] = pid. } If a keyword is given wrong."IDPRT". a pair of labels – values must be declared."PID".1. count_thick = 0.10)."__id__".prop.mid.__type__ ) are also valid. which works similarly to the GetEntityCardValues."T1".12. Modifying the card's values The contents of a card can be modified with the SetEntityCardValues function. foreach prop in props { GetEntityCardValues(LSDYNA.1.0).75). The output value of the function is equal to the number of occurrences that were not found due to an improper definition of a keyword."h".1000.pid.1000.__prop__ .pid). the function will not work because of the 'h1' label and therefore will return status = 1. BETA CAE Systems S. 2.pid. //Set the new values for id and thickness..t. For avoiding opening and closing cards only for seeing the names of the labels.prop. three global label – keywords have been introduced in v12.prop. In the following example we will change the id and thickness of a specific property. property and type without knowing the actual name of their labels.name. mids[count_mid++] = mid.0.prop."MID"."SECTION_SHELL". Again.ANSA v.2. Independently from the deck we can write: status = GetEntityCardValues(LSDYNA.3. count_mid = 0. count_pid = 0.id. The benefit is that we can extract the entity's id. page 36 . def SetValues() { //Get the PART_SHELL property with id 10 prop = GetEntity(PAMCRASH.A.mid. Their syntax is the following: __id__ for entity's ID __type__ for entity's ANSA type __prop__ for entity's property id A very common case is when we must extract the id and the property id from a shell."PART_SHELL". the function will not work even if all the other keywords had been defined correctly. statement } It is obvious that the user must be familiar with the labels of each edit card since they must be written exactly as they appear in the cards. thickness[count_thick++] = t.4."PID".name."h1"..prop. status = GetEntityCardValues(LSDYNA.t).. } .

ANSA v. } During the creation of an entity.969971 . 822."."GRID". zcoord = GetFloat(m[3]).id. -710. materials etc. the rest information that is needed to succefsfully define a connection entity.4. ycoord = GetFloat(m[2]). //Create a group with name 'side' and without id group = NewGroup("side". Suppose that we have a text file with ids and coordinates of grids that we want to create: The form of the file is like the following 82310..539978 .".. } 2."").4.699951 . properties.. 2.g. all the fields that are necessary for its definition but were not specified by the user (e. In the example that will follow a spotweld point and a adhesive line will be created: BETA CAE Systems S.023010 . 821. Except from the definition of the type and id. It returns the element of the newly created entity."X1". } Fclose(fr). faces) the functions CreateConnectionPoint. -710. the id) are automatically filled by ANSA."X3".4. Creating new entities Scripting language can also be used to create new entities like nodes.1. must be given in a matrix form. The function that can be used for this purpose is the CreateEntityVa.0).x Scripting Language 2. Both accept a name and optionally an id and return the element (pointer) of the newly created part/group.zcoord).ycoord. lines. def CreateGrids() { //Open file for reading fd = Fopen("filepath to the grid file".2 ) and pairs of labels – values. CreateEntityVa(NASTRAN.line)) { m = TokenizeString(line.. Also.093018 . like the position of the point and the parts that will be connected. page 37 ."NID"."r").325989 82290. def main() { //Create a part with name 'door' and id 10 part = NewPart("door". the id of the connection can be given explicitly from the user or can be defined from ANSA by giving a zero as second argument. id = GetInt(m[0]). Important Note: Not all entities of ANSA can be created with the CreateEntityVa. xcoord = GetFloat(m[1])."X2". The function returns the element (pointer) of the created connection entity in order to be used later in the realization function. 1672.4.12.6 Creating connection entities For the creation of connection entities (points.xcoord.A. It is necessary to declare the entity type keyword ( Section 2. //Read the file while(Read(fd.5 Creating parts and groups For creating ANSA parts and ANSA groups the functions NewPart and NewGroup must be used. CreateConnectionLine and CreateConnectionFace can be used. 1678."10").2..

cnctn_c. part_ids_curve[1] = 3.1.g: xyz. SetEntityCardValues(NASTRAN. "W". e.3.0) xyz[0] = 2. xyz.0.4.ANSA v. 2 Great attention must be given in the first argument of all three functions since this string indicates the type of the entity that will be created.0. 1 part_ids_curve. or the ids and pids of connected parts etc can be exported or edited through the GetEntityCardValues and SetEntityCardValues.defaults and it can be one of the following: SpotweldPoint_Type Bolt_Type GumDrop_Type SpotweldLine_Type AdhesiveLine_Type SeamLine_Type Hemming_Type AdhesiveFace_Type 2. 122.1). 3 curves. "CURVE".A. 0.x Scripting Language def CreateCnctEnts { //create a spotweld point of ID 122 at (2. page 38 . 3. 3). the length of each matrix must follow the matrix itself.15). 2). } As you noticed. xyz[1] = 3. -1. part_ids_curve.3. cnctn_c = CreateConnectionLine("AdhesiveLine_Type".0. 3 part_ids_point. part_ids_point[2] = "4". curves. part_ids_point. 3. The strings for getting all these characteristics are: "ID" for connection id "X" for x coordinate "Y" for y coordinate "Z" for z coordinate "D" for diameter "S" for S "M" for M "W" for W "H" for H "P1" for part/property 1 "P2" for part/property 2 "P3" for part/property 3 "P4" for part/property 4 "Status" for Status "Error Class" for Error class "Name" for name "Comment" for comment BETA CAE Systems S. cnctn_p = CreateConnectionPoint("SpotweldPoint_Type". part_ids_point[1] = "bp_416". /* part ids that will be connected*/ part_ids_curve[0] = 2. xyz[2] = -1.7 Editing the characteristics of a connection entity The basic informations that follow a connection entity like its ID. /* part ids that will be connected*/ part_ids_point[0] = 1. //create an adhesive line of arbitrary ID curves[0] = GetEntity(NASTRAN.12. The correct syntax of it can be found only in the connection section of ANSA. 1.

4. foreach connection in connections { GetEntityCardvalues(NASTRAN.p1.000000 # SpotweldPoint_SPIDER_RBE2_PinFlags = 123456 # SpotweldPoint_SPIDER_ProjectToPerim = y # SpotweldPoint_SPIDER_PointsAroundHole = 8 # SpotweldPoint_SPIDER_ParallelToPerim = y # SpotweldPoint_SPIDER_PBAR_ID = # SpotweldPoint_SPIDER_KeepSamePID = n # SpotweldPoint_SPIDER_ForceZeroGap = n # SpotweldPoint_SPIDER_DoNotMove = y # SpotweldPoint_SPIDER_DoNotCreateCoord = n # SpotweldPoint_SPIDER_DistanceFromPerimeter = 3..defaults.z.connection.000000 # SpotweldPoint_SPIDER2_Zone1_Index = 2 # SpotweldPoint_SPIDER2_Zone1 = 0. Print("ID "+id+" x:"+x+" y:"+y+" z:"+z).id. or connections = CollectEntities(NASTRAN.000000 # SpotweldPoint_SPIDER_DiSize_Index = 1 # SpotweldPoint_SPIDER_DiSize = 3.."Z"."AdhesiveLine_Type". page 39 .p2.250000 # SpotweldPoint_SPIDER2_SearchDist = 5.1). } ..g: .y.A. the user have to realize them using the functions RealizeConnection (for one entity) or RealizeConnections (for any number of entities).connection."W". connections = CollectEntities(NASTRAN.p4)."Y". The number of input arguments is variable and whatever is not defined takes a default value from ANSA.0.x."SpotweldPoint_Type". "P2". foreach connection in connections { SetEntityCardvalues(NASTRAN.p3.1. 2.8 Realizing connections After creating the connection enities. As an example.x Scripting Language e...000000 # SpotweldPoint_SPIDER2_RBE2PinFlags = 1235 # SpotweldPoint_SPIDER2_PointsAroundHole = 8 BETA CAE Systems S.defaults. the strings that can be used for spotweld representations are: # Default Page for Spotweld Points # format : RBE2|RBAR|CBAR|CBEAM|CELAS2|RBE2-CELAS1-RBE2| # PASTED NODES|CBUSH|DYNA SPOT WELD|PAM SPOT WELD| # NASTRAN CWELD|PAM PLINK|RBE3-HEXA-RBE3|AUTO SP2| # RBE3-CBUSH-RBE3|SPIDER|RADIOSS WELD| # ABAQUS FASTENER|SPIDER2|RBE3-CELAS1-RBE3| # RBE3-CBAR-RBE3|RBE3-CBEAM-RBE3|PERMAS SPOTWELD # SpotweldPoint_Type = RBE2 while the strings for individual representation settings are: # Connection Manager Values # SpotweldPoint_SPIDER_SearchDist = 5. } .0). All the representation characteristics that appear in the GUI are fully supported within these functions using a specific name convention that is taken from ANSA.."P1".0)."P3".12.0.ANSA v."P4".000000 # SpotweldPoint_SPIDER_CreateRBE2 = y # SpotweldPoint_SPIDER_CBAR_PinFlags = 0 # SpotweldPoint_SPIDER2_Zone2_Index = 2 # SpotweldPoint_SPIDER2_Zone2 = 0."X"."ID".

ANSA v.2 is correct .A."SpotweldPoint_Type".000000 # SpotweldPoint_RBE3-HEXA-RBE3_DoNotMove = y # SpotweldPoint_RBE3-HEXA-RBE3_AreaScaleFactor = 0. //Number of adhesive lines no_lines = MatLen(adh_lines).0)."y" 5.000000 . 4. 0.2000). 2. page 40 . specific PSOLID id and the option “Force Ortho Solids” activated. The order of settings doesn’t affect the final result. then the default will be created like in case of the adhesive line. def RealizeAllCncts() { //Collect the spotwelds of the database spots = CollectEntities(NASTRAN."SpotweldPoint_NASTRAN-CWELD_WeldType"."SpotweldPoint_Type". The only alphanumeric characters that are used are the ‘y’ and ‘n’ indicating yes or no respectively.2."y". The value of a setting must always follow the setting. e.12. Options available in GUI as drop down menus are given with their sequence order.2. //Collect the adhesive lines of the database adh_lines = CollectEntities(NASTRAN.g: BETA CAE Systems S. # SpotweldPoint_AUTO-SP2_BoxSize = 6.no_lines.2.10.1.. 10."NASTRAN CWELD"."AdhesiveLine_RBE3_HEXA_RBE3_SearchDist". If the name of the representation is omited. We will use the RealizeConnections which is faster than the RealizeConnection since realizes massively. //Realize the spotwelds RealizeConnections(spots.."AdhesiveLine_Type". } Some notes here are necessary: 1. e.0.. "SpotweldPoint_NASTRAN-CWELD_WeldType". "SpotweldPoint_NASTRAN-CWELD_SearchDist". "AdhesiveLine_RBE3_HEXA_RBE3_PSOLID_ID". //Number of connection points no_spots = MatLen(spots).000000 # SpotweldPoint_ABAQUS_FASTENER_UseThicknessToDiameterMap = y # SpotweldPoint_ABAQUS_FASTENER_UseConnector = n # SpotweldPoint_ABAQUS_FASTENER_SearchDist = # SpotweldPoint_ABAQUS_FASTENER_FASTENER_PID = 0 # SpotweldPoint_ABAQUS_FASTENER_CONNECTOR_PID = 0 In the example that will follow we want to realize the spotweld points into NASTRAN WELDs with option ELPAT and specific PWELD id and the adhesive lines in RBE3-HEXA-RBE3 with 2 stripes.0)..x Scripting Language # SpotweldPoint_SPIDER2_ParallelZones = n # SpotweldPoint_SPIDER2_PBAR_ID = # SpotweldPoint_SPIDER2_ForceZeroGap = n # SpotweldPoint_SPIDER2_DoNotMove = y # SpotweldPoint_SPIDER2_CBARPinFlags = 0 # SpotweldPoint_RBE3-HEXA-RBE3_UseThicknessAsHeight = n # SpotweldPoint_RBE3-HEXA-RBE3_SpecifyHeight = n # SpotweldPoint_RBE3-HEXA-RBE3_SeparateRefCPinflags = n # SpotweldPoint_RBE3-HEXA-RBE3_SearchDist = # SpotweldPoint_RBE3-HEXA-RBE3_RefCPinFlags = 123 # SpotweldPoint_RBE3-HEXA-RBE3_PinFlags = 123 # SpotweldPoint_RBE3-HEXA-RBE3_PSOLID_ID = # SpotweldPoint_RBE3-HEXA-RBE3_Height = # SpotweldPoint_RBE3-HEXA-RBE3_ForceOrthoSolids = n # SpotweldPoint_RBE3-HEXA-RBE3_FailIfAspect = 0. "SpotweldPoint_NASTRAN-CWELD_PWELD_ID".no_spots. These arguments must be given as strings.g "AdhesiveLine_RBE3_HEXA_RBE3_ForceOrthoSolids".1000). //Realize the adhesive lines RealizeConnections(adh_lines. eg: . "AdhesiveLine_RBE3_HEXA_RBE3_NumOfStripes". "AdhesiveLine_RBE3_HEXA_RBE3_ForceOrthoSolids". "SpotweldPoint_NASTRAN-CWELD_WeldType" is wrong 3.

x.0)."EID".A. Suppose that we have to realize all spotweld points in RBE3-HEXA-RBE3 representation and to print in the text window the ids of RBE3s and HEXAs that belong to each connection point def CheckRBE3_HEXA_RBE3() { //Collects all Spotwelds.ent).12. 6. all the settings that were used are passed to connection manager and can be easily viewed.//Initialize if(eclass=="RBE3-HEXA-RBE3") { //Loops through the Entities of each Spotwelds for(ent=GetFirstFeRep(cnctn). if(type=="RBE3") { GetEntityCardValues(NASTRAN. After the realization.ent."X". if(i==0) { no_of_rbe = eid. foreach cnctn in concts { GetEntityCardValues(NASTRAN.y.2. } else no_of_rbe=no_of_rbe+". i = 1.x Scripting Language "SpotweldPoint_NASTRAN-CWELD_WeldType".0. page 41 ."Y".p[1]. The way that we can use them is through a loop that will going to search recursively for all elements.ent. since "ELPAT" option is second in the drop down menu of connection manager."Error Class". i=0."P4".eid).cid."+eid.cnctn.p[0]. concts = CollectEntities(NASTRAN.p[2].4. GetNextFeRep."ID".status. //Initialize j=0.ent=GetNextFeRep(cnctn. 2.1.9 Getting the entities of connections The elements that paticipate into a connection entity can be retrieved through the functions GetFirstFeRep.ANSA v. "SpotweldPoint_Type". } if(type=="SOLID") { BETA CAE Systems S."P2"."Z".p[3]."P3". "Status". The input for the former one must be always the connection element while for the latter the connection element and the last found entity.z. "P1".ent)) { type=GetEntityType(NASTRAN.eclass).

ANSA v. For example the force flag for deleting PSHELLs properties must be 1 since there are shells that use this property. Important Note: To significantly reduce execution time.ent.1). 2.A."EID". if(j==0) { no_of_solids = eid.5. Use 1 to delete entities and any references to these entities. no_of_rbe=0. } BETA CAE Systems S. Creation of user buttons using the AddUserButton function The AddUserButton function is used for the creation of buttons. Creating user defined buttons and custom GUI 2. } else no_of_solids = no_of_solids+".10. Suppose that all unused nodes must be deleted. tables etc. lists. } } Print("Done"). DeleteEntity(nodes. for the management of specific tasks that must be controlled through a number of definitions and actions."+eid. The function accepts a single element (pointer) of an entity or a matrix of elements (pointers). Deleting entities Unnessecery entiites can be deleted using the DeleteEntity function.0). Its syntax needs 3 arguments which are the name of the button. def ButtonTest() { AddUserButton("Test Button". It can delete either a single entity or a number of entities at once. } The second argument is a force flag.1. it is highly recommended to delete entities massively instead one at a time.12.4. } RBE3s with ids:"+no_of_rbe+" and SOLIDs with Important note : The GetFirstFeRep. After the execution of DeleteEntity the property itself and the shells / grids that are associated with it will be deleted.x Scripting Language GetEntityCardValues(NASTRAN. In the following example a button with name "Test Button" will be created and each time it will be pressed the function "test" will be executed. Additionally. 2. radio buttons.5. The buttons that can be created are similar to the buttons of the GUI and are used to invoke user functions.2. } } Print("Connection with cid "+cid+" has ids:"+no_of_solids). def DeleteNodes() { nodes = CheckFree("all"). the name of the function that will be called and the button’s position in the USER MENU window. page 42 .eid). General ANSA scripting language enables the creation of user defined buttons and fully customized graphical interfaces. no_of_solids=0. j = 1. menu buttons. This GUI can handle check buttons.5.1."test". They are placed always under TOOLS>USER MENU. it is very useful to create our own custom GUI. and can be called anytime during the process like any other script function. GetNextFeRep functions can be used in all types of connection entities: 2.

"Buttons Demo"}. Its definition is different from the control matrix and is like the one below: id x y w h length of total control matrix total control matrix Window name dialog = {100.100. 208. 0.10. an additional matrix must be created for the overall window. 150. MatLen( controls )."BUTTON". 6. Notice that x and y are set to zero. 41. Finally. a button is created under TOOLS>USER MENU. page 43 . 41. 4. 7. "CANCEL". size).3.100. "OK". 30. "labeltop"}. 150. "My Button 2". 290. 30.12. 41. position. EDIT → Creates edit fields RADIO → Creates radio buttons CHECK → Creates check buttons BUTTON → Creates simple and menu buttons LABEL → Creates labels LIST_BOX → Creates lists TABLE → Creates tables LIST_VIEW → Creates list views id type x y w h These matrices compose a total matrix that will be used as basis for the final window description. "Text" .ANSA v."BUTTON". controls."BUTTON". Each control is defined in a separate matrix while all these matrices are parts of a total matrix. "EDIT". "User defined buttons". BETA CAE Systems S. Creation of custom GUI One of the most advanced capabilities of scripting language is the creation of user-defined graphical user interfaces. 91.x Scripting Language def test() { Print("ANSA").10.5. 1. 130. "RT_btn"}. 60. "onEditChange"}. "okbtn"}. "edittxt".A. "button_LT". 20. a reference name for handling the control and optionally the name of the function (Callback) that will be called with the control activation.1."LABEL". 3. 5. 40. "button_RT". A GUI is defined through a series of matrices. 8. In this case the window will be placed in a default position. 330. "LT_btn"}. 10. The format of each matrix is specific and basically contains information regarding the attributes of controls (caption. "cancelbtn"} }."BUTTON". The available control types are: 1. "My Button 1". 2. 60. 130. 91. 0. 190. 2. where 'x' and 'y' correspond to control position and 'w' and 'h' are the width and height respectively. 21. Important Note: If a zero value is given as third argument. 2. 10. 41. } Once the function "ButtonTest" is called. then ANSA will place the button in the first available position. A typical syntax of a control matrix is the following: caption reference Callback name {100. 170. controls = { { { { { { 10.

"cancelbtn")."LT_btn"}. string control_name) { Print ("Button 1 was pressed"). "okbtn"). the function CreateWindow must be called in order to create the window. win = CreateWindow ("Win1". { 20. when you no longer need the window.6.A. page 44 . Its name is defined in a control matrix (See 2. Important Note: The CreateWindow function creates a window but it doesn't open it..1.12. The functions SetOkButton and SetCancelButton are used in order to give to these special buttons their known characteristics. Every code that creates windows must end with the function DestroyWindow.4.40.4). controls = { . The output takes a value that corresponds to the pressed button. 2. the user interface is ready to open."My Button 1"..ANSA v. dialog). This function destroys a window that was created by a call to CreateWindow. This function needs a reference name and the window matrix. In the end the GUI should look like the following: 2. It is used to free the internal memory of the windowing system."BUTTON". 2. the control reference name and the control result. In most cases these are the window reference name. Callback functions A callback function is a separate routine that is called every time a control is activated. SetCancelButton ("Win1". } def LT_btn (string window_name.5. Their syntax needs the window reference name and the control reference name of each button.60.5. thus can be very helpful for any actions that follow its activation. Setting Cancel and Ok buttons Almost all types of user-defined windows need an OK and a CANCEL button. The OpenWindow function opens the window using its reference name: res = OpenWindow ("Win1"). SetOkButton ("Win1". } BETA CAE Systems S..120. DestroyWindow("Win1").5.. Opening and Destroying Windows After creating the window and setting the default values of the controls."button_LT".x Scripting Language Since all necessary matrices were created.5. There are certain arguments required for its definition.5. .41.

the initial value will be the one defined in the control matrix The function for setting the state of a check box is the SetCheckButton. 160. 30.45. 90. string txt) { Print("window:"+window_name +". "ref_name". 10. All of them take three input arguments. {50. "text". controls = { {10. {40. BETA CAE Systems S. 290. { 1."onEditChange"}. "ref_name". // StringSet("Win1". 160. "BUTTON". }. "RADIO". "cancelbtn"} }. Callbacks that are carried from other controls must have 3 arguments. 160. edit_box:"+edt_name +". 2. 340.310. 20. 30. The first two arguments are the window name and the internal reference name of the control. page 45 . } CreateWindow("Win2". 190..34). "ref_name"}. 91. 2. 130.6.. First.45. 160. { 2. 30.5. In case none of this function is called. 41. "Select Entities". "Select Deck". "radio3"}. {30. {60. 21. "LABEL".ANSA v. "RADIO".2.x Scripting Language In the above example the callback 'LT_btn' doesn't have a third argument because a BUTTON is a control whose result is taken through the OpenWindow function. 30. 20. like in cases of menus and tables. "OK". "RADIO".A. 41. "LABEL". FloatSet. } 2. which assign a string. {101. "EDIT"."labelbottom"}.50. "radio2"}.. controls = { . 210. 170. Their types are "RADIO" and "BUTTON" respectively. Creating and setting up menus and radio buttons Special attention must be given in the creation of menus and radio buttons since they require some extra definitions. 10. "labeltop"}. dialog). "PAMCRASH". Setting edit fields and check buttons An edit field can be set up using the functions StringSet. "BUTTON". OpenWindow("Win1"). "Cancel". 91. 50. string edt_name.20.. "ref_name". def onEditChange(string window_name.12.6. 160. the internal reference name of the control and the value: controls = { {1. 1. "EDIT". // FloatSet("Win1". the setting of a control needs additional definitions of matrices.6. "ABAQUS". "radio1"}. {20. while the third is an integer that takes zero value for unchecked state and 1 for checked state. . text:"+txt). integer and float respectively. 340.. "text".4.310. but there are also cases where a simple call to a function is enough like in edit fields and check buttons. "NASTRAN". IntSet("Win1".20. Usually. In this phase it is not allowed to set a Callback function since this will be done later with functions SetRadioGroup and SetMenu.. IntSet.1.1. "none"). 20. 30. which are the window name. 30. "edittxt". "okbtn"}. "btn". "BUTTON". 20. . Setting of controls The code between the CreateWindow and OpenWindow statements is used for an initial set up of any type of control. 20. 1). 50. both controls are defined in the control matrix as described in 2. "btn_lower"}.

{30. 0. {50. "radio3"}. menu_group = {"Elements". "Demo"}. StringSet (window_name. "RADIO". "Select Entities". 30. The SetMenu requires similarly the window name ("Win4"). 91. the group matrix ("menu_group") and the active option. 30. 311.ANSA v. "radio1"}. 10. "btn_lower". SetMenu ("Win4". MatLen ( controls ). dialog = {100. 0. 160. we must create the callback functions which will allow to recognize any change of the controls.A.12. 41. "RADIO". three radio buttons and a menu button. controls. "Radio Buttons Demo"}. an internal reference name for the group ("rgroup_1") and the name of callback function ("RadioCallback"). 311. "BUTTON". } In this case. { 1. "btn". string option) { if(option=="Elements") Print("Elements option was selected"). the name of the callback function. Keep in mind that the option number starts always from zero. "OK". 160. dialog). if ( Atoi(option) == 2) Print("PAMCRASH option was selected"). 30. These functions accept the typical three arguments (See 2. "rgroup_1". 190. 30. 20. "LABEL". {40. "labeltop"}. In the final step these matrices will be passed to the respective setup functions: SetRadioGroup ("Win4". the group matrix ("radio_group"). "RadioCallback"). After the creation of the window two group matrices must be defined for radio and menu control. menu group. "ABAQUS". 404. 340. btn_name. option). "radio2"}. if ( Atoi(option) == 1) Print("ABAQUS option was selected"). win = CreateWindow ("Win4". 10.7) and in their simpler form can be like the following: def MenuCallBack (string window_name. indicating the active radio button. the StringSet built in function will change the status of menu. {20. These matrices will contain the available options with the difference that in case of radio buttons the internal reference names must be given while in menus the available options are given directly: radio_group = {"radio1". "Select Deck". def main() { controls = { {10."labelbotton"}. "btn_lower"}.x Scripting Language dialog = {100. string group. "MenuCallback". "BUTTON". 20. if(option=="Nodes") Print("Nodes option was selected"). "RADIO". 170. "NASTRAN".5. win = CreateWindow ("Win4". 160. def RadioCallback (string window_name. 50. 290.1. 160. the internal reference name as it is defined in control matrix ("btn_lower"). 20. BETA CAE Systems S."radio2". 21. 210. 41. SetOkButton ("Win4". "LABEL". dialog). 90. "BUTTON". 91. "okbtn"). "cancelbtn"} }. controls. The SetRadioGroup requires the window name ("Win4"). page 46 . "PAMCRASH". 20. 0. After setting up the radio buttons and the menu."Nodes"}. string btn_name. } After all settings the window must be destroyed. 160. { 2. radio_group."radio3"}. {60. 130. 30. 20. 0. The above control matrix contains 2 labels. MatLen ( controls ). an integer. "Cancel". string option) { if ( Atoi(option) == 0) Print("NASTRAN option was selected"). "okbtn"}. 0). 340. 30. 404. 0.

} def MenuCallBack (string window_name. "BUTTON". window = CreateWindow("Window2". if ( Atoi(option) == 1) Print("ABAQUS option was selected"). string btn_name. "rgroup_1". btn_name. page 47 . It takes three arguments. "LIST_BOX". "Window2"}. radio_group.270. 380. "onModify"}. "okbutton").320.1.30. radio_group = {"radio1". while the others will be simple buttons. "Ok". "MenuCallBack"."radio3"}. StringSet (window_name. which are the window name. } def RadioCallback (string window_name. SetOkButton("Window2". The control type that must be declared first is the LIST_BOX."radio2".12. menu_group .80. "BUTTON". "modify".ANSA v.270.30. DestroyWindow("Win4"). controls. selected or highlighted. { 1.10. the reference name of the list box control (“list 1”) and a string that will be BETA CAE Systems S. dialog = {1000. "RadioCallback").80. res = OpenWindow ("Win4"). which we will try to create step by step. opt). {102.360.A. "list1"}. "okbutton"} }.10. 0). string option) { if(option=="Elements") Print("Elements option was selected"). menu_group = {"Elements". controls = { {100. "Nodes"}. Items (entries) can ne added in a LIST BOX with the AddListBoxItem function. we must start from the definition of the control matrix. if ( Atoi(option) == 2) Print("PAMCRASH option was selected").250. is the one below: Like in all scripts related with GUI. string option) { if ( Atoi(option) == 0) Print("NASTRAN option was selected"). } 2.50. "btn_lower". "Modify".100. "".x Scripting Language SetCancelButton ("Win4". A very simple window. 0. string group. SetMenu ("Win4". dialog).3 Creating and setting up List Boxes A "List Box" is a type of window where a list of items (entries) can be displayed. SetRadioGroup ("Win4". 100.230.6. "cancelbtn"). MatLen(controls). if(option=="Nodes") Print("Nodes option was selected").

"list1"."list1") Print("current text:"+ current_text). } } } BETA CAE Systems S.12."item2"). The most important functions in this area are the OnLBIHighlighted and onLBISelected. // set the listbox to multiselect mode LBSetMultiSel("Window2". "list1". string id) { Print("Highlight:"+id).1. } The third argument is the unique id of the item that was selected/highlighted. which takes only the two known arguments. The onHighlight and onSelect have the form: static def onHighlight(string window_name. By default. The number of times that this function must be called is equal to the number of lines that we wish to add in the box window. AddListBoxItem("Window2". "onSelect").x Scripting Language written in each line. Callbacks for this type of control can be used in order to identify which items where selected or highlighted in order to perform specific actions. txt). } static def onSelect(string window_name. the above definition allows the user to select only one entry from the window."item1"). "onHighlight"). AddListBoxItem("Window2". txt). string id) { Print("Select:"+id). no callback function was set for the LIST BOX control. string btn_name. onLBISelected("Window2". if (res) { if (cur >= 0) { SetLBItemText(window_name."list1". For multiselections the above function returns the string represented from the last selected item. current_text = LBCurText("Window2". AddListBoxItem("Window2". The third argument is an integer that its values are zero (multiselection off) or one (multiselection on). For getting the text of the current item we just call the LBCurText function.A."list1". // add some items in the listbox AddListBoxItem("Window2". we must call the LBSetMultiSel function."list1"."list1".ANSA v. which controls this behavior."list1"."item4"). For multiselections. "list1"). page 48 . Keep in mind that all functions regarding the LIST BOX accept always the aforementioned first two arguments and thus they are not going to be mentioned again."list1". string btn_name) { cur = LBCurrent(window_name. Note that the counting starts from zero."item3"). As it seems from the control matrix. Special attention must be given to the callback onModify of the control matrix that will be used for items modifications: static def onModify(string window_name. cur. Except for the first two arguments the name of the callback must be given: // set the event callbacks onLBIHighlighted("Window2". res = UserInput("Please type some text". string btn_name.1).

270. "Modify". BETA CAE Systems S. which returns the unique id of the item. "item3"). The new text will be given in the forth argument.ANSA v. window = CreateWindow("Window2". string id) { Print("Highlight:"+id)."list1". AddListBoxItem("Window2". Selected_items = LBSelectedItems("Window2".30. 100.12. "LIST_BOX"."list1". if (res) { if (cur >= 0) { SetLBItemText(window_name. "Ok"."list1". Making a loop in the Selected_items matrix. 380. it must be first recognized by its id. cur. sel_item_id)). SetOkButton("Window2". } The final code is the following: static def onHighlight(string window_name. "item2").320. AddListBoxItem("Window2".80. 50. "item4"). txt). } static def onModify(string window_name. This is made with the LBCurrent function.360. we call the LBSelectedItems function. // add some items in the listbox AddListBoxItem("Window2". "". 250. Next. The selected items are returned in a matrix with their id representation. // set the listbox to multiselect mode LBSetMultiSel("Window2". "BUTTON"."list1"."list1". Print("selected item:"+ sel_item_id +". "BUTTON".270.x Scripting Language Before setting a new value to an item. "okbutton"} }.230. AddListBoxItem("Window2". "modify". txt). controls.100."list1". onLBISelected("Window2". {102. "onSelect"). "list1"."list1"). dialog).1).10. Finally. "+ Lbitext).30. res = UserInput("Please type some text". "list1". "okbutton"). string btn_name) { cur = LBCurrent(window_name. "onModify"}. "item1"). we get the item texts with the LBItemText. } static def onSelect(string window_name. 10. res = OpenWindow("Window2")."list1". { 1. string id) { Print("Select:"+id). "onHighlight"). for getting all the item texts after a multiselection action. "Window2"}. "list1").1.A. page 49 . MatLen(controls). // set the event callbacks onLBIHighlighted("Window2". string btn_name. "list1"}. foreach sel_item_id in Selected_items { Lbitext = LBItemText("Window2". string btn_name. this output is given as third argument in the SetLBItemText .80. } } } def main() { controls = { {100. dialog = {1000.

4 Hiding and Showing controls The visibility of all controls can be handled through the HideControl and ShowControl functions. } "btn_1")."btn_1"}. DestroyWindow("Hide/Show").250. 100.30. "onCheckChange"}.x Scripting Language if (res) { Print("current text:"+LBCurText("Window2". 400. BETA CAE Systems S. } else { HideControl(window_name. dialog). "BUTTON".160."list1"). string state) { if (state ==0) { ShowControl(window_name. controls. "list1".150. Their syntax is the same and needs the window name and the reference name of the control.20. "CHECK" . HideControl(window_name. "okbutton").150. {104. static def onCheckChange(string window_name. "BUTTON" . 50.30. "Option 1". "check1". Selected_items = LBSelectedItems("Window2". "BUTTON" . "hide / show buttons"."btn_2"}. window = CreateWindow("Hide/Show". "btn_2"). which hides or shows the buttons according to the status of a check box. Print("selected item:"+sel_item_id+". { 1. } 2.1.210.100. } } DestroyWindow("Window2"). 50. "Ok". ShowControl(window_name. string btn_name. foreach sel_item_id in Selected_items { Lbitext = LBItemText("Window2". } } def main() { controls = { {102.A.75. 165. {103. SetOkButton("Hide/Show". "okbutton"} }.20. dialog = {1000. MatLen(controls).6. "+ Lbitext). "btn_2"). In the example that will follow.20. "Hide/Show"}. the visibility of all buttons is controlled through a callback.ANSA v.100. "btn_1"). page 50 .12. 50.70. "Option 2". res = OpenWindow("Hide/Show")."list1")).sel_item_id)).

.2.": "). Fopen("/home/work/test. Write(f. Unformatted text files The most important functions for the handling of text files are listed in the following table: # 1 2 3 4 5 6 Function Fopen("/home/work/test. Breaks a string into tokens Locates a substring The last two functions are the most significant string functions. Description Opens a file for writing. ANSA can read and write ASCII unformatted files (txt. If everything is ok then it returns an integer which is used later for any action instead of the name of the file.2.". Reads each line of a fille Writes into a file.. 3."text to write").. Opens a file for appending. reading.20". Their use is necessary during the reading of an ASCII file.//Closes the file } Important Note: If you try to open a file for writing or appending to it and the file doesn't exist. Fclose(f).2. Read(f. then the file is created automatically 3.. TokenizeString("1.1.) while it can also handle formatted XML files.line)."w")..". the language checks if the user has permissions on this file. def main() { f = Fopen("home/work/test. csv etc.12.0) MatchString("10_PID:40".ANSA v. In this way it is possible to pass any information from a file that contains any data (engineering data. Suppose that the file that we want to read has the following context and we just want to read and print each line..1.txt".2."a")..txt". Fclose(f). creating the file itself or browsing through its contents. Closes a file.x Scripting Language Section 3 Exchanging data: Text files I/O 3. 3. The script function that is used is called Read and most of the times it is used together with a while statement.A. This is made in order to assure that the file will be read from the beginning to the end."r").2. BETA CAE Systems S."r"). Statements . making use of the output integer of the Fopen function. page 51 . Fopen("/home/work/test. Specifically.5. The script functions that are used to open and a close a file are the Fopen and Fclose. connection information) to an ANSA database. Opening and closing files In the most general case of reading a file or appending to it.1 General ANSA scripting language is capable to handle external formatted and unformatted files.csv". Opens a file for reading. //Opens a file for reading . Reading files The reading of an ASCII file is made line-by-line. The treatment of such files includes many operations like opening.txt". Some basic functions that can be used for these purposes are presented and explained in the following paragraphs..

0 Z_AXIS = 0.1. tokens = TokenizeString(line.245.0.505_-44.0).0).//Print each line } Fclose(f). The second argument can host any number of separators: def main() { // NID.".-42. Print("The string line was separated in "+MatLen(tokens)+ "tokens"). In our example the length of the matrix is 4 and each entry will have the following values: tokens[0] = 234 tokens[1] = -42. def main() { // NID."r"). Some types of separators need the backslash symbol \ for their definition: BETA CAE Systems S. } The result will be a matrix with the same entries as before.0.//Closes the file } In almost all cases there is the need to extract specific information from the lines of a text in order to use it accordingly. in a comma-separated form.-44. tokens = TokenizeString(line.0.8 MAT_NAME = Steel X_AXIS = 1.17.x Scripting Language SUBSTRUCTURE = side MODULE_ID = 100 TITLE = B-PILLAR MODULE_ID = 1000 PID = 20 PIDNAME = MAT1_BP THICKNESS = 0.ANSA v.245:17. The TokenizeString splits a string to its contents according to a separator symbol.1. Usually.A.782". The new strings are stored in a matrix. xcoord ycoord zcoord line = "234. Print("The string line was separated in "+MatLen(tokens)+"tokens").505 tokens[2] = -44.245 tokens[3] = 17.attr".782 It is recommended to convert each of the tokens to the appropriate form (float. page 52 .0 def main() { f = Fopen("/home/work/test.1 ORIGIN = 0._:". ". can be split into four different strings.s)) { Print(s).782". } After the execution of the script the function will return a matrix with the tokens.12. the TokenizeString and MatchString functions are enough for getting such information. integer etc. For example a variable called "line" that indicates a node id and its coordinates.505. ".-42. xcoord ycoord zcoord line = "234. //Opens the file for reading //Read each line of the file and store it under the variable s while(Read(f.) before any further use.0 Y_AXIS = 0.

A very useful application is demonstrated in the following example were we would like to identify all PSHELL's names that contain the string "Default" and store them in matrix in order to delete them.245.0). } In this case the number of entries in 'tokens' will be five since the function has used 1 as last input argument. Suppose that we want to write in a ‘csv’ file (comma-separated) the PID.12. foreach pshell in pshells { GetEntityCardValues(NASTRAN. Print("The string line was separated in "+MatLen(tokens)+" tokens").".1). name and thickness of all PSHELL properties of our model.A.name). First input argument is the parent string and second argument the sub-string that must be matched. pos = MatchString(name.0.pshell.2. } 3. For \ separator : TokenizeString(line.0).-44."\t". If nothing is found zero is returned. It returns an integer indicating the position of the first occurrence of the sub-string.0). pos = MatchString(parent. For blank separator just leave a space: TokenizeString(line. } } DeleteEntity(to_del. The MatchString is used to identify a specific sub-string within a parent string. def main() { parent = "name_roof_pid_100".0). " " .. } The 'pos' variable will be 11 since the first occurrence of pid is in the 11th position.-42.0). Every time that the function is called a new line is written."Default").1).17."Name". A simple code should be like the following: BETA CAE Systems S. page 53 . Writing files The function Write enables the writing in a file.782 tokens = TokenizeString(line. Last argument declares if a blank token will be saved in the output matrix (flag=1) or not (flag=0): def main() { line = 234. "pid")."\"". Its only argument is the integer returned by the Fopen function.ANSA v.3.x Scripting Language For tab separator: TokenizeString(line. if(pos) { to_del[count++]= pshell.1. def SubStitute() { //Initialize count = 0. For " separator : TokenizeString(line."PSHELL"."\\".505. pshells = CollectEntities(NASTRAN.". The extra entry will be an empty string.

"scripted"). 3.5</Parameter> <Parameter Code = "comment">"Connect 2 flanges"</Parameter> </SpotweldPoints> <Parts> <PartInfo Code = "Part Name 1">"upper"</PartInfo> <PartInfo Code = "Part Name 2">"lower"</PartInfo> <PartInfo Code = "Prop Id 1">10</PartInfo> <PartInfo Code = "Prop Id 2">20</PartInfo> </Parts> </Connection_Elements> </Data> BETA CAE Systems S.node). sub_param). XmlGetNode(base.csv"."VTAElements/"). "T".name. use the \n symbol enclosed in quotes. XML formatted files The most important functions for the handling of xml files are listed in the following table: # 1 2 3 4 5 6 7 8 9 Function XmlOpenBase("/home/script. sub_node. XmlNodeName(base. XmlSetNodeData(base. sub_node.1).1. Write(f. "VTAElements/").12.x Scripting Language def main() { f = Fopen("home/work/test.1). "val". root."PSHELL". XmlGetSubNodes(base.xml".pid.ANSA v. //Opens a file for writing //Collect the PSHELLs pshells = CollectEntities(NASTRAN.Thickness")."+thickness)."")."Spotwelds".A.Name."Name".0). XmlGetStringValue(base.sub_param.pid+".0. XmlGetNodeData(base."+name+". //Loop through the PSHELLs foreach pshell in pshells { GetEntityCardValues(NASTRAN.0</Parameter> <Parameter Code = "zcoord">3. //Write the HEADER Write(f.node_connection. } Fclose(f). XmlNewNode(base.thickness). } For writing more than one lines after each call of Write.node). Description Opens a XML data base Fetces a node Fetches the subnodes of a node Gets the name of a node Gets the string value of a node Gets node's data Creates new node Set a string value to a node Sets node's data For the clarification of the above functions the following xml scheme is going to be used for reading and writing: <Data> <Connection_Elements> <SpotweldPoints> <Parameter Code = "Connection Name">Spot1</Parameter> <Parameter Code = "xcoord">1."PID.pshell.3."Connection Elements"."str")."w"). XmlNewNode(base."PID". XmlSetStringValue(base. page 54 . "some_data"). XmlGetNode(base."Nameî.2</Parameter> <Parameter Code = "ycoord">5.

Alternatively."Connection_Elements"). like the <Connection_Elements>. Its syntax is very simple and it needs the base and the node element (pointer)."Data/").3. Getting the name of the node In an XML file each node holds a name. When this function points to a non existent file then this file is automatically created. <Parts> subnodes = XmlGetSubNodes(base.. <SpotweldPoints> and <Parts>. it can take an arbitrary internal name that will not be used further. which describes most of the times an area of interest.2. 3. } The key point in this function is the output value which is of type element (pointer) and indicates the xml database. The second argument is necessary only when writing XML files where it is used as base node. In our example nodes are considered the tags <Data>. The output is always a matrix that contains the elements (pointers) of the sub-nodes.3.data[0]. "internal_name").1.x Scripting Language 3.3."Data" The nodes that comes hierarchically just after the root. Getting nodes and sub-nodes For getting the element (pointer) of a node the XmlGetNode must be used. <Parts> are the subnodes of the <Connection_Elements>. 3. Attention must be given in the function's second argument since it must be taken from the output matrix of the XmlGetNode that was called before. after getting a node it is easy to get its sub-nodes using the XmlGetSubNodes. Almost all the XML functions that are going to be used later will need this element(pointer). page 55 . foreach subnode in subnodes { node_name = XmlNodeName(base. In case of reading."Connection_Elements"). //For getting the <SpotweldPoints>. The root node in this structure is considered the <Data> and this is the node that must be fetched first. The name can be extracted using the XmlNodeName function. connection_elements[0]). can be taken if we write: //For getting the <Connection_Elements> connection_elements = XmlGetNode (base. Opening xml files For opening an xml file the XmlOpenBase function must be used. <Connection_Elements>.xml".ANSA v.subnode).data[0]. In our example the node <Connection_Elements> is the subnode of <Data> while the nodes <SpotweldPoints>. //This will get the <Data> The output data is a matrix that contains the element (pointer) of . } BETA CAE Systems S. //For getting the <Data> Since "Data" is the root we can set second argument as blank: node = XmlGetNode(base. connection_elements = XmlGetNode (base..""). <Parts> subnodes = XmlGetSubNodes(base. The code that we must use is: data = XmlGetNode(base.3. The syntax for getting it is: data = XmlGetNode(base.12. connection_elements[0]). def main() { base = XmlOpenBase("/home/work/connections.A.data[0]. //For getting the <Connection_Elements> connection_elements = XmlGetNode (base."Data/"). Print(node_name). .1. //For getting the <SpotweldPoints>."Connection_Elements").

2.sub_node).xml". Let's focus on node <SpotweldPoints> that has the sub-nodes <Parameter> which in turn have the attribute 'Code'. In the latter case an element (pointer) indicating the parent node will be needed. In the following example: node_connection = XmlNewNode(base. connection_elements = XmlGetNode(base.1)."Data"). data = XmlGetNode(base.12. if(param_name=="Connection Name") connection_name = XmlGetNodeData(base. base = XmlOpenBase("/home/jharal/tmp/test. 'comment').sub_node).sub_of_spots).sub_of_spots).xml". Their use is demonstrated together with the complete example: def main() { base = XmlOpenBase("/home/work/connections. 3."Connection Elements". if(param_name=="xcoord") xcoord = XmlGetNodeData(base. 1. if(param_name=="zcoord") zcoord = XmlGetNodeData(base."Connection_Elements").A. 'xcoord'. The second argument is important since it defines the base node. BETA CAE Systems S. Print("zcoord:"+zcoord). sub_nodes = XmlGetSubNodes(base."Code". Getting attributes and node data Apart from its name. if(node_name=="SpotweldPoints") { subs_of_spots = XmlGetSubNodes(base. if(param_name=="comment") comment = XmlGetNodeData(base. foreach sub_node in sub_nodes { node_name = XmlNodeName(base. the function XmlOpenBase must be used. 'ycoord'.sub_of_spots).6 Creating nodes A new node can be created with the function XmlNewNode.5 Writing XML files and setting the base node In order to create a new XML file. page 56 .data[0]. 3. if(param_name=="ycoord") ycoord = XmlGetNodeData(base. which in our case is the <Data>.sub_of_spots).sub_of_spots).3.ANSA v. Depending on the syntax a node can be created just after the base node (3 arguments) or in any other place (4 arguments). Its syntax accepts either 3 or 4 arguments. while each node holds data that is associated with each of these parameters ('Spot1. "internal_name"). Print("xcoord:"+xcoord).""). } } } Important Note1: The name of an attribute is necessary for retrieving the attribute values. } Print("connection_name:"+connection_name). Important Note2: If the attribute hasn't got a value then a default can be assigned through the forth argument of XmlGetStringValue 3. a node can also have attributes and data that are also important for the process.3. foreach sub_of_spots in subs_of_spots { param_name = XmlGetStringValue(base. Print("comment:"+comment). This attribute takes five parameter names ('Connection Name'.4. Two new functions will be introduced for extracting all these information: These are the XmlGetStringValue and the XmlGetNodeData. 5.connection_elements[0]). 3. Connect 2 flanges').3.1.x Scripting Language In the above example the names 'SpotweldPoints' and 'Parts' are going to be displayed on the screen. 'zcoord'.sub_of_spots."Data/").5. Print("ycoord:"+ycoord).

node_parts.0).1)."Part Name 2".node_param. parameter_names_parts = {"Part Name 1"."Parameters". parameter_names_spots = {"Connection name"."Spot1"). } node_parts = XmlNewNode(base.node_param."Code".node_param."Parameters".1).xml"."comment"}.7 Setting attributes and node data Attribute names and attribute parameters are given through the XmlSetStringValue.parameter_names_spots[i]).node_connection. } XmlCloseBase(base.node_param.node_connection.node_data_parts[i]).ANSA v."5."3.1). Recapitulating."Prop Id 1".2"). } BETA CAE Systems S."10". XmlSetNodeData(base.i<4.node_param.node_connection."ycoord"."Code"."Connect 2 flanges"}. XmlSetNodeData(base. node_data_spots = {"Spot1"."SpotweldPoints"."Code". page 57 ."Prop Id 2"}. or XmlSetNodeData(base.node_param. the node 'SpotweldPoints' will be created after the 'Connection Elements'. XmlSetStringValue(base.1).node_data_spots[i]).1).3.0)."1. for(i=0. node_data_parts = {"upper".x Scripting Language the node 'Connection Elements' will be placed after the node 'Data' while if you write: node_spot = XmlNewNode(base.node_param. XmlSetStringValue(base. for(i=0."Connection name")."xcoord".node_spot.node_spot."zcoord"."Parts". then we should write: node_param = XmlNewNode(base. the final code for writing the whole xml file (See paragraph 3.3) is the following: def main() { base = XmlOpenBase("/home/jharal/tmp/test. XmlSetStringValue(base.2".0). or XmlSetStringValue(base."Code".A."Parameters". It is clear that in this case the output of the previous call was used.node_param.i++) { node_param = XmlNewNode(base."1. XmlSetNodeData(base. node_connection = XmlNewNode(base.parameter_names_parts[i]). 3."xcoord")."SpotweldPoints".12. node_spot = XmlNewNode(base. Last argument indicates whether the node appears once (1) or more (0). In our example it is 1 since both nodes are written once. In a similar way the function XmlSetNodeData sets data to a node.i++) { node_param = XmlNewNode(base.0"."Connection Elements"."Data").1."20"}.5". On the other hand if we create the node 'Parameter' which appears more than once.i<5."lower".

ANSA before executes any specialized function either checks its existence in ANSA. These names are stored under variables that indicate the type of the action that will take place. between the available options the user can select to call a script function that will create the desired combination of entities. These entities will be transferred to the script through a matrix. Similarly. post_realization_fn = <name of function> It is called in order to make any custom changes for each successfully realized connection. GEBs ( trims and output requests) and connection manager are basically the fields where these functions can operate. Therefore. ANSA makes a check in ANSA. This option is available only when the representation is RADIOSS WELD. These entities will be transferred to the script through a matrix. Weld_user_field_update = < name of function > It is called in order to update the non editable User field of each connection.2 Description of Specialized functions During the creation of connectors and GEBs from the GUI. The current Generic Entity: variable of type element (pointer).x Scripting Language Section 4 Specialized Functions 4. This function uses 4 arguments by default: i.1 General Specialized functions in scripting language are actually user functions that have a unique syntax (input and output arguments) and can be called automatically from the program when the user performs specific tasks. the user must decide between several built in representations and interfaces. These options cover a variety of cases but sometimes the analysis requires a different approach. during the realization process into the connection manager. 4. Before any execution. This function needs to be loaded prior to its call. searches the name of the function that must call. The program undertakes to feed the function with the correct data. Each matrix entry is of type element (pointer).A. 4. the user has to load the functions prior to execution and therefore it is prefered to put them into an ANSA_TRANSL file.1. The entities identified from the search. The entities given from the representation.1 Creating Connectors and GEBs with scripting The interface of connectors and GEBs and the representation of connectors support the option of "UserScript" The "UserScript" interface will execute a user defined function to create any custom interface or representation between the entities identified from the search and the representation/interface entity. Some user arguments transferred to the function in the form of a string type variable.ANSA v.12. Specifically. iv.defaults file. user functions can be called in order to assign in the newly created entities specific characteristics. iii. In all cases. page 58 . Connectors. or execute it directly (Connectors. The variable names are four: shell_to_spring_pid = <name of function> It is called in order to assign PROP/SPRING properties to springs. thick_spw_diam = <name of function> It is called in order to map the flange thickness with the diameter of the connection.defaults and then executes it (connection manager). BETA CAE Systems S. Each matrix entry is of type element (pointer). GEBs). ii.2.

radius = Atof(diam)/2. //Create a PBAR property new_prop = CreateEntityVa(NASTRAN.new_prop.area)."N1"."A".property_id. the bars are finally created because of the positive return value. area = 3. string diam) { all_search_nodes = MatLen (FromSearch). //Create the bar CreateEntityVa(PAMCRASH. //Get the id of the representation node GetEntityCardValues(NASTRAN.A. matrix FromSearch. } Keep in mind that even though the ‘CreateEntityVa’ is invoked."PID".ANSA v. "IPART".property_id). each node identified from the search will be connected to the ‘Spc1’ node with a ‘CBAR’ element.1)."NID".src_id).src_id. Important Note: The script that contains the function ‘BarInterface’ should be already loaded."BEAM". the function to be executed is named ‘BarInterface’.FromSearch[i].repr_id).repr_id. matrix FromSearch. page 59 . } return 1. matrix FromRepr. which is by default located at the x.i++) { //Get the id of each search node GetEntityCardValues(NASTRAN. The matrix ‘FromRepr’ will contain one ‘Spc1’ node. Finally.1. This function is defined as follows: BarInterface (element GEB_BC."x1".i<all_search_nodes.14*radius**2. GetEntityCardValues(NASTRAN. z Generic Entity coordinates. matrix FromRepr. the string args will be the ‘60’ string specified in the ‘func_arguments’ field! Note that the function must return a non-zero value on success and a zero value on failure. for(i=0. After the realization of this generic entity. y.x Scripting Language In the example shown."N2".FromRepr[0].12."PBAR". string args) The matrix ‘FromSearch’ will contain all the nodes that lie in the inner/outer zone of the hole. BETA CAE Systems S. def BarInterface (element GEB_BC."NID".

ret = GetNextFeRep(connection.defaults the name of the function that must be called just after realization: # Custom function to update User field of a Connection # function format : string Function( element CONNECTION ). # weld_user_field_update = # A function name is assigned to this variable.ANSA v.12. i.ipart).ret. eg: # weld_user_field_update = UserPlinkProp # This function should have the required syntax.e. break. This ‘User’ field can be updated only during the realization process and it’s usage can vary according to user needs. there is one called ‘User’ which is editable only through scripting.A.ret)) { if(GetEntityType(PAMCRASH. Having this information it is easy to extract all necessary informations. At the end of the script a string must be returned.ret)=="PLINK") { GetEntityCardValues(PAMCRASH.2 Executing specialized script functions from Connection Manager Weld_user_field_update: Among the available fields of each connection entity. string Function (element connection) and should return a string The input argument of this function is the element (pointer) of the entity that is going to be created. } } return ipart. First.1. } BETA CAE Systems S. is to display the property id for each plink that is created. A very useful operation of this. we define in ANSA."IPART".ret.x Scripting Language 4.2. page 60 . A possible use of this function is to display in the ‘User’ field the property id of the newly created plinks: def UserPlinkProp(element connection) { for(ret = GetFirstFeRep(connection).

.x Scripting Language thick_spw_diam: During the realization of many representations in connection manager (CBEAM.1.t1 . else if(thickness>1 && thickness<2) diameter = thickness/4. } The thickness that is given as input is the one that calculated according to the ANSA.THINNEST|THICKEST|MEAN spw_diam_mflng = INNER . CBAR) the diameter of a newly created entity is taken from a rule that is specified in ANSA.00 In many case this rule is applied only when the option ‘Use Thickness to Diameter Map’ is activated. THINNEST shell_to_spring_pid: The RADIOSS WELD is the only representation that can use the option ‘Use thickness to PID Map’. page 61 . # where you get a matrix of the projected shells.]]] # (where t : Thickness class upper bound # 0 < t(i) < t(i+1) # i < 100 # d : Spot Weld Diameter for it ) thick_spw_diam = 4.. # and you must return the property to be used by the # springs that will be created.defaults under the variable ‘shell_to_spring_pid’..78.d3 [.A.02.defaults variable ‘spw_diam_mflng’: # Master Flange Election Method # format : INNER|OUTER|MIDDLE|ALL. else diameter = thickness*2.d2 [.defaults as following: # Flange Thickness to Spot Weld Diameter Map # format : d1 [. This property can be # either created or selected by the properties list # shell_to_spring_pid = A function name is assigned to this variable eg: # shell_to_spring_pid = DefineSpringId # BETA CAE Systems S. # Projected shells to Radioss Spring PID mapping function # function format : element Function( matrix Shells ).1.6.1. then he can specify after ‘thick_spw_diam’ the name of a script function : # thick_spw_diam # = AssignDiameter This function should have the syntax: float Function(float thickness) and should return a diameter The input argument is a thickness value while the returned value is the diameter that will be applied: def AssignDiameter(float thickness) { if(thickness<=1) diameter = thickness..t2 .00.5. then ANSA during realization calls a function that is declared in ANSA..ANSA v. return diameter. If this option is activated.12. If the user requires a more complicated rule.00. else if(thickness>=2 && thickness<3) diameter = thickness/2.

after a successful realization. The input argument is a matrix that contains the projected shells while the output must be the element of the property that is going to be assigned to the newly created radioss springs. # matrix heads_per_flange."TYPE". # where : # -"Connection" is the connection element that has just been realized # -"XYZ_per_flange" is a matrix of the x."Name". prop = GetEntity(RADIOSS.1000"."MASS". return ent.1). i = 0. else ent = CreateEntityVa(RADIOSS. thickness[i++] = Atof(t).0. page 62 . # matrix ProjEnts_per_flange.A. connection will report in the usual manner # # the post-realization function is called for each successfully realized connection.z coords of the projection on the flange # -"ProjEnts_per_flange" is a matrix of the entities at the projection # -"heads_per_flange" is a matrix of the entities at head of the connection # -"bodies_per_flange_pair" is a matrix of the entities between the flanges # -"miscellaneous" is a matrix of miscellaneous information.len)."Maximum thickness greater than "+max. "PID". # matrix bodies_per_flange_pair.y.500". the connection manager is able to call a user-script function.ANSA v."PID"."SPR_BEAM 13"."SPR_BEAM 13". } In the above example a different PROP/SPR_BEAM is assigned to each spring according to the thicknesses of the shells that connects."THICK". # matrix miscellaneous ). if(max<=1) ent = CreateEntityVa(RADIOSS."MASS".1."TYPE". foreach shell in shells { GetEntityCardValues(RADIOSS. connection will report as CUSTOM_FE # 1 if user made changes. # for the user to make any custom changes on its elemens.Print(max). GetEntityCardValues(RADIOSS.t). def DefineSpringId(matrix shells) { len = MatLen(shells). # and information for future use."PROP/SPR_BEAM". "PID"."Maximum thickness less than "+max. that will allow the user to make the required changes."PROP/SPR_BEAM". # matrix XYZ_per_flange."PROP/SHELL".5). USAGE: in the ANSA. you can see the following variable: # # User connection post realization function # function format : int Function( entity Connection.defaults file. "Name". where # "miscellaneous[0]" is diameter used during realization # return value: 0 if user made changes.prop.x Scripting Language This function should have the syntax element Function(matrix shells) and should return the element (pointer) of a property.pid).shell. post_realization_fn: If it is necessary to alter the results of some realized connections. # BETA CAE Systems S.12. The property is created into the function or it can be any existing one. } max = Max(thickness.pid).

TYPE ). id = "+ ID + ". for( j=0. eg: # post_realization_fn = PostRealizationCallback # This function should have the required syntax. j<nents..users may delete/add more fe-representations to the connection . j<nents. "__type__". j++ ) { ent = ProjEnts[i][j].12. ID. nents = MatLen( ProjEnts[i] ). " + XYZ[i][1] + ".1. "__id__". // CONNECTION: Print( "Connection: " + id )."+TYPE ).. Print( nHeads + " HEADs:" ). heads[i][j]. id ). matrix ProjEnts. for( i=0. for( i=0.users may produce a file output reporting on the quality of the produced elements/holes Following is an example of how to extract the various information from a connection that has just been applied: def PostRealizationCallback( element cnctn. matrix heads. for( j=0.users can set the attributes of a Property of.users can modify diameters of bars according to their own scheme (like thickness to diameter mapping) ."+TYPE ). ON EACH FLANGE: nHeads = MatLen(heads). GetEntityCardValues( NASTRAN. cnctn. page 63 . nents = MatLen( heads[i] ). i++ ) { Print( "-" +i + "> " ).x Scripting Language post_realization_fn = A function name is assigned to this variable. "__type__". // PROJECTION COORDINATES ON EACH FLANGE: n = MatLen( XYZ ). say. } // PROJECTION ENTITIES ON EACH FLANGE: ( face/shell/node(s) ) n = MatLen( ProjEnts ). Print( "... i<n. and user should return 1 on success of the application.A.. } } } BETA CAE Systems S. Print( ". matrix others ) { GetEntityCardValues(NASTRAN. matrix XYZ_per_flange... j++ ) { GetEntityCardValues(NASTRAN. "__id__". int Function( element Connection.. id = "+ ID + ". Possible uses: . matrix ProjEnts_per_flange. matrix bodies. i++ ) { Print( "pt[" + i + "] = {" + XYZ[i][0] + ". i. a bar to their own values. matrix bodies_per_flange_pair ). ent.e. matrix XYZ. TYPE ). ID. . i++ ) { Print( " Ent[" + i + "]:" ). i<n. i<nHeads.ANSA v. } } // INTERFACE ENTITIES PRODUCED BY CONNECTION MANAGER. for( i=0. matrix heads_per_flange. " + XYZ[i][2] + "}" ). "__id__".

2 Description of auxiliary built in functions A brief description of the functions listed in text window is given below: load_script Usage: USER>load_script: <full path to the new script> Example: USER>load_script:/home/jharal/work/CombineSets.ANSA v. Using command window 5. When a function name is given.c Description: Clear all previous loaded scripts and loads the one specified above import_script Usage: USER>import_script: <full path to the new script> Example: USER>import_script:/home/jharal/work/CombineSets.x Scripting Language Section 5 Handling Scripts and ANSA_TRANSL 5. General Basic actions such as loading. This behavior is common for all built in commands.12. At the end it will be shown another way of automating an ANSA process through the use of the ANSA_TRANSL file. the SCRIPT menu and the SCRIPT EDITOR. can be handled in ANSA with 3 distinct ways which are the command window of GUI. Note that after typing the letter ‘U’ ANSA autocompletes to USER>. In this chapter we will focus on the description of the first two along with other useful functionality.2. export_library Usage: USER>export_library: Description: This function is obsolete export_help Usage: USER>export_help: <filename to write> BETA CAE Systems S. then the help text of the function is displayed.1.c Description: Append new script in the current active ones list_library Usage: USER>list_library:<name of built in function> or blank Example: USER>list_library: or USER>list_library: Print Description: When the function is not followed by a function name it displays the available built in functions per category.2.A. page 64 .2. If we type in command line the word USER> then ANSA lists all available auxiliary built in functions next to the text window. 5. 5.1.1 Quick view of auxiliary built in functions A very quick way to handle scripts is through the command window which is the one that is located in the down left corner of the GUI. parsing or executing user defined functions.

This time no errors occured: If the user try to reload a script that is already loaded and ANSA recognize that no changes have been made to it the message: NOTICE: script file [tmp/OutputActran.3 Loading scripts A script is succesfully loaded only when is free of syntax errors.A. page 65 . then every time it is loaded only the first occurence will be displayed. After all necessary corrections the script is loaded again. BETA CAE Systems S.1.x Scripting Language Example: USER>export_help:/home/jharal/work/help.2.12.txt Description: Writes in the specified text file all available built in functions along with their help text unload_function Usage:USER>unload_function: <function name> Example: USER>unload_function: CombineSets Description: Unloads an already loaded function unload_script Usage:USER>unload_script: Example: USER>unload_script: Description: Unloads all loaded functions script_help Usage: USER>script_help: <function name> Example: USER>script_help: CombineSets Description: Displays the help text of a user defined function (See 1.8. Specifically. Important Note:If a script has more than one error.ANSA v.c] already loaded will be displayed.7) list_category Usage: USER>list_category: <name of category> Example: USER> list_category: CONNECTION MANAGER FUNCTIONS Description: Displays the built in functions of the specified category list_categories Usage: USER>list_categories: Example: USER> list_categories: Description: Displays all the categories of built in functions 5. before loading anything ANSA parses the script that the user attempts to load and displays in the text window the error line of the code: In the above example the script “OutputActran.c” has an error in line 19.

all functions that executed via command line display their possible messages in the text window: Error message due to wrong syntax of input arguments: 8515.x Scripting Language Keep in mind that every time a script is loaded then automatically unloads all previous loaded ones.ANSA v.A.1. all the functions that contains can be viewed in the text window by typing USER> in the command line. These arguments are given in the command line just after the name of the function and have to be separated with a blank space or with comma.5). If you wish to run one of the loaded function you should write in command line: USER><function name>: If function contains input arguments then this is displayed in text window in the form: USER><function name (type of input argument)> The "MeasureDistance" function accepts two integers as input arguments. All other ways are not recognized and ANSA responds with the message: incompatible number of arguments Finally.8521 Message that was "MeasureDistance" printed from BETA CAE Systems S. 5. Exceptions are those functions that have been declared as static (See Section 1.2.8.12.4 Running scripts After a script is loaded. page 66 .

Adds a script in the database. FUNCTION and EDITOR. The one that was previously default remains loaded but its functions are not available anymore. Unloads loaded or added scripts. Any function located in an imported script is appended to loaded ones and is ready to run any time. Each time a script is set as default.x Scripting Language 5. Sets a script as default. LOAD IMPORT ADD DEFAULT Imports a script.A. Every script that is loaded becomes the default one. Selecting this button opens a window where all loaded and added scripts are displayed. Selecting this button opens the list with all loaded and added scripts of the database.3. All previous loaded scripts are unloaded.3 Using script menu 5. An added script is considered loaded but the functions that holds are not available for running. the script with zero index is the default. Press then OK to confirm. Always.ANSA v.1 Script menu interface The SCRIPT button that is located in the main GUI. The index in front of each path indicates which is the default sequence. the functions that holds become available. The user is prompt to select a file from the File Manager. all the functions of the first one are lost and the functions of the second become available. Consequently. reveals the script menu: The menu is splited in three sub-categories: SCRIPT. Important Note: Imported scripts are not listed in the above window. The user is prompt to select a file from the File Manager. Important Note: A loaded script takes always zero index while an added script takes the first available index. UNLOAD BETA CAE Systems S.12. Let’s see them one by one: Loads a script. Select a script from the list and press the "Set as default" button to become the default one. The user is prompt to select a file from the File Manager. page 67 . When the default script is unloaded then as default becomes the script with the next index.1. This means that all the functions that holds are ready to run any time.2 SCRIPT category This category contains five functions that basically control the script files. Select the script to unload and confirm with OK. 5.3.

if a user unloads the zero index script then the functions of the imported scripts will be lost too. Select a function from the list.A. If the function needs input arguments. 5.x Scripting Language Functions of imported scripts retain a relationship with the zero index script since they are appended to it. Its help is displayed in the User function description. page 68 . all the available scripts are displayed while the default one is always active.3. then automatically its functions will become available while the previous ones will be unavailable. So.ANSA v. These functions come from the imported scripts and from the default script.12.3 FUNCTION category Runs a function. When selecting this button the following window opens: RUN In the Function list all available functions are displayed. the functions of the imported script will become unavailable. then these must be given in the Type function arguments field in comma separated form. In Available modules menu.1. BETA CAE Systems S. Other useful buttons are the Load module which acts similarly to SCRIPT>ADD and the Reload module which reloads the active script. if the default status is changed. If another module is selected. Similarly.

User's HOME Directory This is the local home directory of the user. a user can call to run a previously defined function within ANSA_TRANSL. f = fopen(weld_file.."a+").3." ".4. During the attempt to read an ANSA_TRANSL. it will search for an ANSA_TRANSL file within the locations listed in the following table.2 How does ANSA interacts with ANSA_TRANSL ANSA_TRANSL interacts with ANSA in two ways: (a) when ANSA tries to read a CAD file. NOTICE script file : [ansa_home directory] 2.. "r"). line)){ m = tokenize_string(line. part1 = m[5]. while(read(f. step.4.A.".8.2). thickness.". NOTICE script file : [user_home directory] 3. /* Translate spaces to underscores */ = "=:. /* Open Attributes File for Reading */ if(attr_filename && attr_fd=fopen(attr_filename.txt". wz = atof(m[4]). This functionality is very useful in cases where multiple CAD files should be translated into ANSA databases and the property.3. then the last read will overwrite the previous ones. The functions are listed in the Function list area of previously described window. else print("Reading :"%attr_filename). These functions are invoked from the command prompt of the Text Window or from SCRIPT menu (See 5.")) { /* Replace Extension with .4. type = m[0]. ANSA will display the following messages in the Text Window: 1.1.3. if functions with same name are identified.x Scripting Language LIST UNLOAD Lists in the text window all built in functions Unloads one or more functions."Reading :"%attr_filename). In the second way. /* Log Attributes File Name */ if(fd_log) i=write(fd_log. ANSA_HOME Directory This is the directory where the environment variable ANSA_HOME is pointing at. global_code section def WeldParts(string dir_path){ weld_file = dir_path+"CONNECTIONS. and (b) when a user executes a custom script. user_functions section The global section is executed while reading cad files (iges.3).attr */ attr_filename=FILEPATH%FILENAME(:i-1)%". and other specific characteristics for each part must be assigned to the related fields within ANSA. In the first way. 3. wy = atof(m[3]).2.2. The numbers on the left indicate precedence (from lowest to highest): # Location Description 1.4 and 5. vda) or during the translation of catia and unigraphics file.. BETA CAE Systems S. Similarly. /* Everything that will separate Words /* Guess Attributes File Name */ if(i=match_string(FILENAME. Working Directory This is the directory from which ANSA was called to run.0).12.4 Automation through an ANSA_TRANSL file 5.3 and 5.] 5.log".1) and is executed as it was explained in paragraph 5.1 Location of ANSA_TRANSL file When ANSA is called to run."Reading :"%attr filename). This can be done at any time during the user interaction with ANSA and can affect whatever is currently loaded in ANSA.3 Form of ANSA_TRANSL The general structure of an ANSA_TRANSL contains a global_code section and a user_functions section: TRANSLATIONS SEPARATORS or Numbers*/ : " "="_". wid = atoi(m[1]). either geometry or FE-model data. The user section contains a series of user functions written in the normal way (See 1. ANSA will read and execute automatically all the commands written within the ANSA_TRANSL global code section. 2.attr". wx = atof(m[2]). } /* Open Log File for Appending */ fd_log=fopen("ANSA_TRANSL. material. 5. page 69 . NOTICE script file : [current directory] Reading ANSA_TRANSL from [. Important Note: ANSA_TRANSL can be also loaded manually (See 5.ANSA v.path where ANSA_TRANSL it was found. 5."r")) { /* Log Attributes File Name */ if(fd log) i=write(fd log. If ANSA find between the ANSA_TRANSL files more than one global code then the last read will be kept.

Below is the list with all currently supported ANSA registers.4.LIST The thickness of the Property The Material ID that will be assigned to all entities of the Part The name of the above material as appears in the M. ANSA_TRANSL global code can use a number of global functions/keywords called registers. property id..code.. } Apart from the built in functions.4 What is a global code The global code can contain any script function and is written as any other code with the difference that it must be written always first in the file and without the def statement....) Default character translations (eg.. } def ChangePids(element pshell) { ..LIST X-coordinate of the Origin used for Part's position Y-coordinate of the Origin used for Part's position Z-coordinate of the Origin used for Part's position X-component of X-axis used for Part's transformation Y-component of X-axis used for Part's transformation Z-component of X-axis used for Part's transformation X-component of Y-axis used for Part's transformation Y-component of Y-axis used for Part's transformation Z-component of Y-axis used for Part's transformation X-component of Z-axis used for Part's transformation Y-component of Z-axis used for Part's transformation Z-component of Z-axis used for Part's transformation Obsolete Obsolete Obsolete Obsolete Obsolete Obsolete BETA CAE Systems S.code...... " " = "_" blank space is translated into an underscore) Module ID of current Part The name of the Part as appears in the Part's Manager The Property ID that will be assigned to all entities of the Part The name of the above property as appears in the PR. . ChangePids(pshell). page 70 . } def ChangePids(element pshell) { ._... def Translation() { ..1. must be assigned to the read cad models. 5. ANSA_TRANSL without global code def Translation() { .x Scripting Language Important Note: It is recommended the global code and all common user functions to be kept in the ANSA_TRANSL of ANSA installation directory. ANSA registers FILENAME FILEPATH SEPARATORS TRANSLATIONS PART_ID PART_NAME PART_PROPERTY_ID PART_PROPERTY_NAME PART_PROPERTY_THICKNESS PART_MATERIAL_ID PART_MATERIAL_NAME PART_COORD_SYS_X PART_COORD_SYS_Y PART_COORD_SYS_X PART_COORD_SYS_DX1 PART_COORD_SYS_DY1 PART_COORD_SYS_DZ1 PART_COORD_SYS_DX2 PART_COORD_SYS_DY2 PART_COORD_SYS_DZ2 PART_COORD_SYS_DX3 PART_COORD_SYS_DY3 PART_COORD_SYS_DZ3 POST_TRANSL_SCRIPT POST_TRANSL_SCRIPT_ARGS FLANCH_PROPERTY_ID PART_MODEL_NAME SYMMETRY_PART_ID SYMMETRY_PART_ID_OFFSET Description The name of the CAD file currently processed The directory path of the CAD file Definition of whatever is used to separate words (eg. These registers cannot be used from user defined functions and their use is very common when attributes like property name.code.code..12.A. material name etc. } ANSA_TRANSL with global code pshell = GetFirstEntity(NASTRAN."PSHELL").ANSA v. The global code is executed only when pure cad files are used and when all the actual entities have been translated into ANSA.

1.707107..707107.-6. 5.0.1..1.0.1.9.25. this approximation saves a lot of user work.1... The syntax accepts a string argument where each line of the header is going to be stored after a succesful call of the function.2. /* Log Attributes File Name */ A cad header can be read with the function GetNextFileLine. . CAD File HEADER Section NAME : CH-CBN-OUTER-L PID : 21 THICKNESS: 1.1."a+")..2.63.ANSA v. IGES header example MODEL PART NUMBER TITLE PROP ID VERSION THICKNESS MAT ID MAT NAME POSITION VERSION THICKNESS S S S S S S S S S S S S S 1H. The same could be made with the use of built in functions: pshell = GetFirstEntity(NASTRAN..material."PSHELL"). 1P 1. material. .2HMM.0. /* Everything that will separate /* Guess Attributes File Name */ if(i=match_string(FILENAME.0.306.. .". } /* Open Log File for Appending */ fd_log=fopen("ANSA_TRANSL. .2 1 2 3 4 5 6 7 8 9 10 11 12 13 1 2 3 1 2 1 2 3 Header BETA CAE Systems S.153539.0. SetEntityCardValues(NASTRAN. 1P 0. thickness..0.0.. Clearly.539.. For example. .5.attr */ attr_filename=FILEPATH%FILENAME(:i-1)%".5.0.1.6. /* Translate spaces to = "=:.0.406.25.0. position. G 10000. ..1.0.. . . DATA Section ANSA_TRANSL TRANSLATIONS underscores */ SEPARATORS Words or Numbers*/ : " "="_"...". PART_MATERIAL_NAME = "steel".001...2. page 71 . SetEntityCardValues(NASTRAN. property.1.707107.0..x Scripting Language The basic advantage of registers is that they can pass directly a value to an entity without the need to search for the entity.15.12.0.0. material = GetFirstEntity(NASTRAN. such an ANSA_TRANSL does not have a user_functions section and all the translation process is handled through the global_code section.7HG ANSA9.4.1.75. Important Note: If the cad file has more than one properties.75.13H991109.pshell.log"... In its simpler form.401.57H/usr/people/CAD_data2/STELIOS_TEST/INTERFACES/header."Name". G 126 1 0 0 0 0 0 000000001D 126 0 0 8 0 0 0BSPLINE 1D 126. It is obvious that in the second case the user must write more lines of code and consequently the possibilities of making an error are greater.1.875.1057.153539.x.375.1.1. .0. Importing CAD files Information about a part (like its name."steel").A.5. etc) can reside as comments into the header section of a CAD file in the form of keywords..5 7892 St 50 BH L B 1. .13H991109.0.0.1.36..5 MATERIAL : MATS1_STEEL MID : 2 . Using a special ANSA_TRANSL script.12.iges."MAT1"). .375. minimize the code and eliminates the possibility of error.1H.32.3H1.0.attr".1...539. then registers like PART_PROPERTY_NAME. PART_PROPERTY_THICKNESS etc will affect them all.707107."Name". if we like to name the property and the material of the model we just assign the respective strings to the registers PART_PROPERTY_NAME and PART_MATERIAL_NAME.75. these keywords are read and the related information is passed directly into ANSA. ..0..0.875. 1P : : : : : : : : : : : SPACE MOBILE 1234567 LEFT FLOOR BEAM 456 A 1. Usually it is used together with a while statement. PART_PROPERTY_NAME = "panel".0."panel").")) { /* Replace Extension with .1.

ANSA v.12.1.x

Scripting Language
1P 1P 1P 1P 1P T 4 5 6 7 8 1

1057.63,-6.75,396.539,1057.63,-6.75,396.539,1050.88,-6.75, 396.539,1050.88,0.,396.539,1050.88,6.75,396.539,1057.63,6.75, 401.539,1057.63,6.75,406.539,1057.63,6.75,406.539,1050.88,6.75, 406.539,1050.88,0.,406.539,1050.88,-6.75,406.539,1057.63,-6.75, 0.5,0.75,0.,0.,0.; S 13G 3D 2P 8

The above HEADER is easy to be extracted using only the following 2 lines as global code:
while(GetNextFileLine(in_line)) Print(in_line);

Besides the header section of a CAD file, information about a part can also be given through standard text files, the so called attribute files. In this case, for each CAD file that is opened into ANSA, ANSA_TRANSL will read the corresponding attribute file and retrieve information about the specific part. This information is then assigned to the related fields within ANSA.
CAD File
Attributes File (TXT File)
NAME : PID : THICKNESS: MATERIAL : MID : . . . . . . keyword_1 . keyword_2 . FRONT_DOOR_LT 21 1.5 MATS1_STEEL 2 . . . . . . . . . . . . . . . . . . . . .

DATA Section 01234567891 . . . 123 . 1 01234567. 01234567. . . 2

ANSA_TRANSL
TRANSLATIONS underscores */ SEPARATORS Words or Numbers*/ : " "="_"; /* Translate spaces to = "=:,;"; /* Everything that will separate

/* Guess Attributes File Name */ if(i=match_string(FILENAME,".")) { /* Replace Extension with .attr */ attr_filename=FILEPATH%FILENAME(:i-1)%".attr"; } /* Open Log File for Appending */ fd_log=fopen("ANSA_TRANSL.log","a+"); /* Log Attributes File Name */ if(fd_log) i=write(fd_log,"Reading :"%attr_filename); else print("Reading :"%attr_filename); /* Open Attributes File for Reading */ if(attr_filename && attr_fd=fopen(attr_filename,"r")) {

Suppose that the attribute file has the form:
SUBSTRUCTURE = LEFT TITLE = B PILLAR MODULE ID = 999 PID = 100 PROPERTY NAME = B_PILLAR_999 THICKNESS = 0.97 MID = 1000 MATERIAL NAME = MAT1_STEEL ORIGIN = 0.,-100.,0. X_AXIS = 1.,0.,0. Y_AXIS = 0.,1.,0. Z_AXIS = 0.,1.,0.

The ANSA_TRANSL that could be used in order to read the attribute file and assign the values to every imported cad file is the following:
/*--------------------- GLOBAL CODE -----------------*/ /*---------------------------------------------------*/ /*---Informations are written in ANSA_TRANSL.log-----*/ /*---------------------------------------------------*/ /*---------------------------------------------------*/ SEPARATORS = "=:,;"; /* Separator of Words or Numbers*/ if(i = MatchString(FILENAME,".")) { /* Replace Extension with .attr */ attr_filename=FILEPATH%FILENAME(:i-1)%".attr"; } /* Open Log File for Appending */ fd_log = Fopen("ANSA_TRANSL.log","a+");

BETA CAE Systems S.A.

page 72

ANSA v.12.1.x

Scripting Language

/* Log Attributes File Name */ if(fd_log) Write(fd_log,"Reading :"%attr_filename); else Print("Reading :"%attr_filename); /* Open Attributes File for Reading */ attr_fd = Fopen(attr_filename,"r"); if(attr_filename && attr_fd) { /* Loop throught all lines in Attributes File */ while(Read(attr_fd,in_line)) { /* Look for a "SUBSTRUCT = ...." line */ if(MatchString(in_line,"SUBSTRUCT")) { m = TokenizeString(in_line,"=",0); sub_ass_name = GetString(m[1]); NewGroup(sub_ass_name,0); } /* Look for a "TITLE = ...." line */ else if(MatchString(in_line,"TITLE")) { m = TokenizeString(in_line,"=",0); pdm_id = GetString(m[1]); } /* Look for a "MODULE ID = ...." line */ else if(MatchString(in_line,"MODULE ID")) { m = TokenizeString(in_line,"=",0); module_id = GetInt(m[1]); } /* Look for a "PROPERTY NAME = ...." line */ else if(MatchString(in_line,"PROPERTY NAME")) { m = TokenizeString(in_line,"=",0); property_name = GetString(m[1]); } /* Look for a "PID = ...." line */ else if(MatchString(in_line,"PID")) { m = TokenizeString(in_line,"=",0); property_id = GetInt(m[1]); } /* Look for a "MATERIAL NAME = ...." line */ else if(MatchString(in_line,"MATERIAL NAME")) { m = TokenizeString(in_line,"=",0); material_name = GetString(m[1]); } /* Look for a "MID = ...." line */ else if(MatchString(in_line,"MID")) { m = TokenizeString(in_line,"=",0); material_id = GetInt(m[1]); } /* Look for a "THICKNESS = ...." line */ else if(MatchString(in_line,"THICKNESS")) { m = TokenizeString(in_line,"=",0); thickness = GetFloat(m[1]); } /* Look for an "ORIGIN = ...." line */ else if(MatchString(in_line,"ORIGIN")) { /* Read X,Y,Z Origin Coordinates */ m = TokenizeString(in_line,"=,",0); PART_COORD_SYS_X = GetFloat(m[1]);

BETA CAE Systems S.A.

page 73

ANSA v.12.1.x

Scripting Language
PART_COORD_SYS_Y = GetFloat(m[2]); PART_COORD_SYS_Z = GetFloat(m[3]); } /* Look for a "X_AXIS = ...." line */ else if(MatchString(in_line,"X_AXIS")) { /* Read DX,DY,DZ of X Axis Vector */ m = TokenizeString(in_line,"=,",0); PART_COORD_SYS_DX1 = GetFloat(m[1]); PART_COORD_SYS_DY1 = GetFloat(m[2]); PART_COORD_SYS_DZ1 = GetFloat(m[3]); } /* Look for a "Y_AXIS = ...." line */ else if(MatchString(in_line,"Y_AXIS")) { /* Read DX,DY,DZ of Y Axis Vector */ m = TokenizeString(in_line,"=,",0); PART_COORD_SYS_DX2 = GetFloat(m[1]); PART_COORD_SYS_DY2 = GetFloat(m[2]); PART_COORD_SYS_DZ2 = GetFloat(m[3]); } /* Look for a "Z_AXIS = ...." line */ else if(MatchString(in_line,"Z_AXIS")) { /* Read DX,DY,DZ of Z Axis Vector */ m = TokenizeString(in_line,"=,",0); PART_COORD_SYS_DX3 = GetFloat(m[1]); PART_COORD_SYS_DY3 = GetFloat(m[2]); PART_COORD_SYS_DZ3 = GetFloat(m[3]); }

} } else

{
/* Warn user if Attributes File does not Exist */ if(fd_log) Write(fd_log,"Warning : No Attributes File"); else Print("Warning : No Attributes File"); } if(!pdm_id) { /* Warn user if No PDM data in Attributes File */ if(fd_log) Write(fd_log,"Warning : NO PDM Id"); else Print("Warning : NO PDM Id"); } /* Construct PART name to the taste of user */ if(i = MatchSeparators(FILENAME)) { if(pdm_id) name = FILENAME(:i-1)%"_"%pdm_id; else name = FILENAME(:i-1); } else { if(pdm_id) name = FILENAME%"_"%pdm_id; else name = FILENAME; } /* Finally Assign PART Atributes to ANSA Registers */ PART_NAME = pdm_id; PART_ID = module_id; PART_PROPERTY_ID = property_id;

BETA CAE Systems S.A.

page 74

ANSA v.12.1.x

Scripting Language

PART_PROPERTY_NAME = property_name; PART_PROPERTY_THICKNESS = thickness; PART_MATERIAL_ID = material_id; PART_MATERIAL_NAME = material_name;

It is clear that the key functions for reading this file is the MatchString and TokenizeString which were discussed in Section 3. Also, the use of registers made the code more compact and easy to read since it was avoided the use of other built in functions which could do the same actions in a more “complicated” way. 5.4.6. Executing functions without any user interaction (autoexec) When ANSA is launched, and the search for an ANSA_TRANSL is finished, ANSA will look for a specialized function called autoexec. This is an optional function that can be located only in an ANSA_TRANSL file and accepts no arguments. If ANSA finds the autoexec function, it will automatically execute any command that is located within, without any further user intervention. Thus, the autoexec can be used to automate any series of command prior to start working with ANSA, for example to define additional user-buttons that will become available to the user as soon as ANSA is launched. In the ANSA_TRANSL that is given below, the autoexec function will instruct ANSA to add a user button titled "my button". When this "my button" is pressed, the "btn_function" is called and, in this case, it will print a "Welcome to ANSA" message.
def autoexec() { AddUserButton("My button", "fun_btn",0); } def fun_btn() { Print("Welcome to ANSA"); }

In order to see the user button and the corresponding message press TOOLS>USER MENU. At the appearing "User Menu" window, press "my button" and the "Welcome to ANSA" message is printed on the Text Window (See section 5.2.4). Important Note: As mentioned, if the autoexec function exist in more than one ANSA_TRANSL files the last one will be executed and all the others will be unloaded. A message then will be displayed in the text window:
unloading function: autoexec, in: <path of ANSA_TRANSL that was read before the last one>

BETA CAE Systems S.A.

page 75

3 Running scripts If the script contains a function called main. a dynamic help is always displayed whenever a function name is written correctly in the main window Main Menu Main Window Shortcut Keys Help Output Area Dynamic Help List Functions List 6.3). while when the Output tab is active it displays any message that is reported from the parser (e.g syntax errors) or from a user script This area contains all available built in functions.x Scripting Language Section 6 Script Editor 6. When the Help tab is active it displays the help text of a built in function. Otherwise you should go to Project>Run which acts similar to button SCRIPT>FUNCTION>RUN (See Section 5. If a script has a syntax error then this is reported in the output area. The main features of this interface are highlighted and briefly described below. 6. BETA CAE Systems S.1 Script Editor Layout Script Editor is a fully independent tool. where a user can easily build or test his own scripts. integrated in ANSA.ANSA v. There is no restriction regarding how many scripts can be remained opened simultaneously.A. a new tab having the name of the script is added next to the Help tab of main window.3. The edit functions enable the code modification while the debug functions are used for the identification of syntax or logical errors This area has double use. page 76 .1. then every time the F5 button is pressed the script is executed.12. Main Menu Shortcut Keys Scripts Main Window Dynamic Help List Functions List Help/Output Area Contains the script editor functions The area where the code is written or tested Buttons for calling the most important edit and debug functions. It can be invoked through the SCRIPT>EDITOR>EDIT.2 Opening scripts Every time a new script is imported. Additionally.

0.x Scripting Language 6. In this way the user can have a library of functions or code that uses mostly. The easiest way to create a snippet is to mark the code in the main window and then right click to open the context menu. An arrow on the left of every parameter indicates which argument must be written next. Furthermore. script menu) while it can be used as an include file too. Important Note: A compiled script cannot be executed through the Script Editor.1) in the code. Moreover. 6. when the immediate tab is active it is not allowed to have any def statement (See Section 1. Print(MatLen(Spots)).8. BETA CAE Systems S. } Important Note: Scripts made in the immediate environment can be executed normally.ANSA v.5 Help area This area helps the user to find all built in functions either by their category or by their name. any variable that is written in the global section of the script has no sense. This file is located in the working directory and can hold separately any number of snippets. page 77 . For example in order to test how many spotwelds exist in the database we write: Spots = CollectEntities(NASTRAN.xml. A compiled script can be loaded and run throughout all the normal ways (command line.4 Making use of the immediate tab Many times during the development of code there is the need to test a function or a simple line very quickly and with the minimum necessary definitions. Print(MatLen(Spots))."SpotweldPoint_Type").7 Making or importing snippets Snippets are sections of code or even fully independent functions that can be created or loaded anytime through the editor.0.12. all the functions that hold can be called from any other script even from uncompiled ones. 6. the respective help text is displayed in the Output Area. 6.1. Therefore. A double click on a function displays a help text in the Output Area. Consequently.A. Important Note: Pressing F1 while the cursor is pointing on a built in function name (written in the main window). the Dynamic help recognized the "CollectEntities" and therefore the necessary parameters were displayed according to their precedence. The first time a snippet is created.6 Compiled scripts For protecting the script code from any external source there is a capability to compile it in a binary format through the Project>Compile. a Dynamic help tab is always activated every time a function name is written correctly in the main window: In the above example."SpotweldPoint_Type"). it is saved without any warning in an xml file called snippets. Instead of def fun_name() { Spots = CollectEntities(NASTRAN.

This function opens the previous window where the user can select a snippet from the available list on the left. the respective code is inserted into the main window at the cursor position.1. a snippet is distinguished from its name and it is stored either in an ANSA or a META snippets list. Selecting it and pressing the Import button.ANSA v. Moreover.A. the selected code goes to the code section of the window where the user can further edit it. BETA CAE Systems S.12. page 78 . By default the ANSA tab is active. A snippet can be imported from the Tools>Code snippet option of the main menu.x Scripting Language Pressing the Make snippet option opens the snippet window: Automatically.

we select the most important of them. is through the debugger which executes the code line by line. its type (local or global) and the current value. This is very useful in cases where a script function have logical errors which probably lead to strange results.1. If there is no such clue. A variable can be added in the watch list if we right click on it and select the Add watch option.ANSA v. in such cases the first step is to identify the variables that produce the error. In the above example the cursor is pointing on variable p and therefore when selecting on the menu that opens the option Add watch: main::p. Second.8 Debugging scripts Scripts can be run in two ways.x Scripting Language 6. There are also times that unidentified problematic areas of functions like endless loops or wrong input data result in an infinite execution.12. First. the function where it belongs. button This window displays also the variable name. In the later case we can pause the execution of a script in order to investigate the status of variables. This list can be displayed pressing the or through the View>Watch window of the main menu. page 79 . the ‘normal’ run. executes the code directly. Usually. Next. BETA CAE Systems S. All these situations can be traced using the debugger of script editor. p is added in the watch list. we add them in the watch list which help us to inspect their history during the execution of the script.A.

the debugger cannot reach it unless we change the way that searches the code. the script runs without stop until the next breakpoint. The first instructs the execution sequence to step into a sub function. we can press Suppose that you would like to trace any changes of matrix p. we must define the lines where the execution of the script will be paused. Keep pressing or until the execution is finished. The execution stops in line 5 and the current or <F10>. On the other hand pressing the button inserted. Pressing anytime the button . page 80 . For running the function in debug mode the button {Shift+F5} or Project>Debug. After each stop we are able to identify in the watch list any change of the variable. Alternatively. the status of p is displayed in watch window.A.x Scripting Language Finally. breakpoints are inserted to them. From now on every time you press the button execution continues and stops in each line. Insert a breakpoint in line 5 and open the watch window. Important Note: The name of the function must be "main" must be pressed. In our example after the second stop the matrix p changes and now holds the first value which is 20. Whenever a breakpoint is breakpoint.ANSA v. This can be achieved through the and . For letting the editor to distinguish these inserts a lines. Consequently. If the variable that we are looking for is not in the "main" function but in a sub function. Having the cursor on a line and pressing the button deletes a breakpoint. it is recommended the lines that are selected to be just before or after the variable definition. Important Note: When the execution stops over a breakpoint the line is colored blue. the respective line is colored red.12. Press <Shift+F5> to run in debug mode.1. Let’s see this with an example: BETA CAE Systems S. while the buttons second to step out of a sub function.

in this line and from that point we press the button We can return any time to the "main" function pressing .12. The execution stops until we get inside foo.ANSA v. For this.1. BETA CAE Systems S.A. page 81 .x Scripting Language Assume we are interested in watching the values of the variable k which is located in sub function foo. we set a breakpoint in a line prior to foo call (line 6) and press <Shift+F5>.

Sign up to vote on this title
UsefulNot useful