Ansa Scripting

April 24, 2017 | Author: gtacom | Category: N/A
Share Embed Donate


Short Description

Download Ansa Scripting...

Description

ANSA version 13.x

Scripting Language A guide to ANSA automation

ANSA v.13.x

BETA CAE Systems S.A.

Scripting Language

page 1

ANSA v.13.x

Scripting Language

Table of Contents 1. DESCRIPTION OF THE SCRIPTING LANGUAGE....................................................5

1.1 General............................................................................................................................................................................5 1.2 Data Types......................................................................................................................................................................5 1.2.1 User Defined Data Types (structures)...........................................................................................................6 1.3 Variables.........................................................................................................................................................................6 1.3.1 Naming of Variables and Restrictions..........................................................................................................6 1.3.2 Declaration of variables...............................................................................................................................7 1.3.3 The const keyword.......................................................................................................................................7 1.3.4 Checking the variables’ spelling...................................................................................................................7 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......................................................................................................................9 1.4.4 Numeric intrinsic functions........................................................................................................................10 1.4.5 Expressions and assignments for string data types......................................................................................10 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..........................................................................................................................................................14 1.6 Conditional Statements and Branching...................................................................................................................15 1.6.1 The "if-else" blocks and the logical operators.............................................................................................15 1.6.2 The switch statement..................................................................................................................................17 1.6.3 The goto statement.....................................................................................................................................17 1.7 Loop statements...........................................................................................................................................................18 1.7.1 The foreach statement................................................................................................................................18 1.7.2 The for statement.......................................................................................................................................18 1.7.3 The while statement...................................................................................................................................19 1.7.4 The do while construct...............................................................................................................................19 1.7.5 The continue and break statements.............................................................................................................19 1.8 User functions and comments...................................................................................................................................20 1.8.1 Definition..................................................................................................................................................20 1.8.2 Argument list and function call..................................................................................................................20 1.8.3 Declaring functions as variables.................................................................................................................21 1.8.4 Returning data from functions (return, byref call).......................................................................................21 1.8.5 Scope and lifetime of variables..................................................................................................................22 1.8.6 public and private functions.......................................................................................................................24 1.8.7 Including files............................................................................................................................................24 1.8.8 Including project files................................................................................................................................25 1.8.9 Compilation control (Pre processor)...........................................................................................................25 1.8.10 Recursive structures.................................................................................................................................26 1.8.11 Initialization and un-initialization of matrices and variables in main and global code...............................27 1.8.12 Use of help text and comments in functions.............................................................................................28 1.9 Session commands for use in Scripting Language.................................................................................................29

2. INTERACTING WITH ANSA....................................................................................30

2.1 General..........................................................................................................................................................................30 2.2 Handling Data..............................................................................................................................................................30 2.2.1 Data of element type..................................................................................................................................30 2.2.2 ANSA cards and entity types.....................................................................................................................30 2.3 Collecting entities........................................................................................................................................................32 2.3.1 General......................................................................................................................................................32 2.3.2 Collecting entities massively from the whole database...............................................................................33 2.3.3 Collecting entities massively from other entities........................................................................................33 2.3.4 Collecting massively visible entities...........................................................................................................35 2.3.5 Collecting available entity types of specific deck.......................................................................................35 2.3.6 Getting single entities................................................................................................................................36 BETA CAE Systems S.A.

page 2

ANSA v.13.x

Scripting Language

2.3.7 Collecting part and groups from their ids...................................................................................................36 2.3.8 Collecting entities according to their name.................................................................................................37 2.3.9 Collecting all new created/imported entities...............................................................................................37 2.3.10 Collecting files and directories.................................................................................................................38 2.3.11 Select files or directories through File Manager.......................................................................................38 2.4 Edit, Create and Delete Entities................................................................................................................................39 2.4.1 General......................................................................................................................................................39 2.4.2 Getting values from an entity using its Edit card........................................................................................39 2.4.3 Modifying the card's values........................................................................................................................40 2.4.4 Creating new entities..................................................................................................................................41 2.4.5 Creating parts and groups...........................................................................................................................41 2.4.6 Creating connection entities.......................................................................................................................41 2.4.7 Editing the characteristics of a connection entity........................................................................................42 2.4.8 Realizing connections................................................................................................................................43 2.4.9 Getting the entities of connections.............................................................................................................45 2.4.10 Deleting entities.......................................................................................................................................46

3. CUSTOMIZE GUI.....................................................................................................47

3.1 General..........................................................................................................................................................................47 3.2 Creation of user buttons ............................................................................................................................................47 3.3 Creation of custom GUI ............................................................................................................................................47 3.3.1 Setting Cancel and Ok buttons...................................................................................................................48 3.3.2 Opening and Destroying Windows.............................................................................................................48 3.3.3 Callback functions.....................................................................................................................................49 3.4 Setting of controls........................................................................................................................................................49 3.4.1 Setting edit fields and check buttons..........................................................................................................49 3.4.2 Creating and setting up menus and radio buttons........................................................................................50 3.4.3 Creating and setting up List Boxes.............................................................................................................52 3.4.4 Hiding and Showing controls.....................................................................................................................55

4. HANDLING ASCII, XML AND BINARY FILES.........................................................56

4.1 General..........................................................................................................................................................................56 4.2 ASCII files....................................................................................................................................................................56 4.2.1 Opening and closing files ..........................................................................................................................56 4.2.2 Reading files..............................................................................................................................................56 4.2.3 Writing files...............................................................................................................................................58 4.3 XML files......................................................................................................................................................................59 4.3.1 Opening xml files......................................................................................................................................60 4.3.2 Getting nodes and sub-nodes......................................................................................................................60 4.3.3 Getting the name of the node.....................................................................................................................60 4.3.4 Getting attributes and node data.................................................................................................................61 4.3.5 Writing XML files and setting the base node..............................................................................................61 4.3.6 Creating nodes...........................................................................................................................................61 4.3.7 Setting attributes and node data..................................................................................................................62 4.4 BINARY files...............................................................................................................................................................63 4.4.1 Opening binary files...................................................................................................................................63 4.4.2 Reading and Writing binary files................................................................................................................63

5. SPECIALIZED FUNCTIONS....................................................................................64

5.1 General..........................................................................................................................................................................64 5.2 Description of Specialized functions........................................................................................................................64 5.2.1 Creating Connectors and GEBs with scripting............................................................................................64 5.2.2 Executing specialized script functions from Connection Manager..............................................................66

6. HANDLING SCRIPTS FROM GUI............................................................................70

6.1 General..........................................................................................................................................................................70 6.2 Using the Command Line window...........................................................................................................................70 6.2.1 Quick view of auxiliary built in functions..................................................................................................70 BETA CAE Systems S.A.

page 3

ANSA v.13.x

Scripting Language

6.2.2 Description of auxiliary built in functions..................................................................................................70 6.2.3 Loading scripts..........................................................................................................................................71 6.2.4 Running scripts..........................................................................................................................................72 6.3 Using script menu........................................................................................................................................................73 6.3.1 Script menu interface.................................................................................................................................73 6.3.2 File>Script options.....................................................................................................................................73

7. AUTOMATION THROUGH THE ANSA_TRANSL FILE...........................................76

7.1 Location of ANSA_TRANSL file..............................................................................................................................76 7.1.1 How does ANSA interacts with ANSA_TRANSL.....................................................................................76 7.1.2 Form of ANSA_TRANSL.........................................................................................................................76 7.1.3 Registers used for translation.....................................................................................................................77 7.1.4 Importing CAD files..................................................................................................................................78 7.1.5 Executing functions without any user interaction (autoexec)......................................................................84

8. EXTRACTING INFORMATION FROM CATIA.........................................................85

8.1 General..........................................................................................................................................................................85 8.2 Script commands related with Catia........................................................................................................................85 8.2.1 Orientation check.......................................................................................................................................85 8.2.2 Extracting thickness from catia entities......................................................................................................86 8.2.3 Checking geometry existence.....................................................................................................................86 8.3 Reading Header/Comment Section of Catia file....................................................................................................86 8.4 Creating connections from points and curves of Catia.........................................................................................88 8.5 Handling of properties...............................................................................................................................................89 8.6 Writing in the Catia log file.......................................................................................................................................89 8.7 The "Extra Options" field of Catia Translator......................................................................................................90

9. SCRIPT EDITOR......................................................................................................91

9.1 Script Editor Layout...................................................................................................................................................91 9.2 Opening scripts............................................................................................................................................................92 9.3 Running scripts............................................................................................................................................................92 9.4 Making use of the immediate tab..............................................................................................................................92 9.5 Help area......................................................................................................................................................................92 9.6 Compiled scripts..........................................................................................................................................................93 9.7 Making and importing snippets................................................................................................................................93 9.8 Creating projects.........................................................................................................................................................94 9.8.1 Starting a new project................................................................................................................................94 9.8.2 Adding existed files to a project.................................................................................................................95 9.8.3 Adding new files to a project......................................................................................................................97 9.8.4 Creating the ‘main’ script...........................................................................................................................98 9.8.5 Handling projects.......................................................................................................................................98 9.9 Debugging scripts........................................................................................................................................................98

APPENDIX.................................................................................................................101

Sample scripts..................................................................................................................................................................101

BETA CAE Systems S.A.

page 4

ANSA v.13.x

Scripting Language

1. Description of the Scripting Language 1.1 General A general description of the scripting language is given below. The description is organized in the following main sections: - Datatypes - Variables - Operators - Conditional Statements - Loop Statements - User Functions

1.2 Data Types The data type determines the kind of data that a variable or a function can hold. Data types include integer or floating point numbers, strings, matrices etc. as well as user defined types. The following paragraphs describe the available data types for writing an ANSA script. Note however that variables used in ANSA scripts, are considered typeless. Integers The integer data type is used by variables that can only have whole numbers as values. Such variables are represented in memory by 32 or 64 bits depending on the machine architecture. my_var = 10; Floating Point Values that are not integral are stored as floating point numbers. A floating point variable can be expressed as a decimal number such as 112.5, or with an exponent such as 1.125E2. In the latter case the decimal part is multiplied by the power of 10 after the E symbol. A floating point must contain a decimal point, or an exponent or both. If you write neither, then you have an integer. Floating point numbers are represented in memory by 32 or 64 bits depending on the machine architecture. my_var = 112.5; Strings As string, we declare a series of printable text characters representing human readable stuff. A string value is enclosed in quotes (e.g. "this is a string") and can be assigned to any variable for storage and easy access. String variables are internally represented as arrays of characters. s = "a string"; Elements This is ANSA - specific data type, representing entities used within the model, for example a shell element or a property or a set. The keyword used to declare such entities is element. Typically, the element data type is used in the declaration of function arguments (See Section 1.8.2).

BETA CAE Systems S.A.

page 5

ANSA v.13.x

Scripting Language

1.2.1 User Defined Data Types (structures) In many cases, user scripts can be more elegantly and concisely expressed if they can be written in terms of aggregate structures. Such structures can be considered as user defined data types that represent a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling. The keyword used to declare such collections is called struct and the individual variables within the collection are called its members.

1.3 Variables A variable is a named memory location that contains data and can be modified during script execution. For every variable we distinguish its data type and its value: - The data type describes what particular kind of data is stored in a variable, such as an integer number, a string etc. As we saw earlier, variables are typeless, meaning that their type is defined by the way the variables are used. - The value of the data that a variable contains at any point, is determined by the instructions of our code and, of course, this value will usually change many times during program execution. 1.3.1 Naming of Variables and Restrictions The name of a variable is called an identifier, or more conveniently, a variable name. Variable names can include the letters A-Z (in upper or lower case), the numbers 0-9 and the underscore character. All other characters including the blank space are illegal. A variable name is case sensitive and must begin with a letter or an underscore. 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. The following table lists some valid / invalid variable names: # 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.

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, it is usually a good programming practice to keep it short. Furthermore, the language reserves some "names" as "keywords". These names are used to represent internal functions and are not allowed to be used as variable or function names. The reserved characters and reserved words for writing an ANSA script are listed below: reserved characters: =^*/+-%&'"\!(){}[]:;,. reserved words: include, void, int, def, float, char, string, matrix, map pointer, element, struct, byref, if, else, for, do, while, foreach, in, const, switch, break, continue, goto, case, default, return, static, global, projectfile, defbutton, script, stricton, strictoff, public, private reserved variables: FILENAME, FILEPATH, FLANCH_PROPERTY_ID, PART_COORD_SYS_DX1, PART_COORD_SYS_DX2, PART_COORD_SYS_DX3, PART_COORD_SYS_DY1, PART_COORD_SYS_DY2, PART_COORD_SYS_DY3, PART_COORD_SYS_DZ1, PART_COORD_SYS_DZ2, PART_COORD_SYS_DZ3, PART_COORD_SYS_X, PART_COORD_SYS_Y, PART_COORD_SYS_Z, PART_ID, PART_MASS, PART_MATERIAL_ID, PART_MATERIAL_NAME, BETA CAE Systems S.A.

page 6

ANSA v.13.x

Scripting Language

PART_MODEL_NAME, PART_NAME, PART_VERSION, PART_VSC, PART_PROPERTY_ID, PART_PROPERTY_NAME, PART_PROPERTY_THICKNESS, POST_TRANSL_SCRIPT, POST_TRANSL_SCRIPT_ARGS, TRANSLATIONS, SEPARATORS, MAT_REG, SYMMETRY_PART_ID, SYMMETRY_PART_PID_OFFSET reserved constants: NASTRAN LSDYNA PAMCRASH ABAQUS RADIOSS ANSYS CFD MORPH 1.3.2 Declaration of variables When writing ANSA scripts, it is not necessary to explicitly define the data type of variables. This is because all variables used in ANSA scripts are considered by default typeless and automatically acquire the proper data type depending on their use at the time. For example, in a statement like: my_var = 13;

the variable my_var is treated as being of integer type. But, if later on, the same variable is found in another statement like: my_var = "my string";

it will switch from integer to string type The use of typeless variables reduces the total number of variables used in a script, since the same variable can be used in different ways. However, typeless variables can be proven dangerous when they must be passed as arguments to a function, since the function should be aware as to how to treat these variables. Thus, in such cases, the data type of all variables that are communicated to a function must be explicitly declared in the functions' arguments. For example, if var1, var2 and var3 represent integer, float and string variables respectively, they should be declared as: def my_function (int var1, float var2, string var3)

1.3.3 The const keyword A variable can get a unique and unchangeable value if defined as constant. Once it is defined, it keeps its original value even if later on is given a different value. This kind of variables can be declared in global or function code, using the keyword const followed by the type of variable. The type is auxiliary and is used only for the definition. const float pi = 3.14; def main() { pi = 3; Print(pi);//The 3.14 will be printed }

1.3.4 Checking the variables’ spelling A very frequent problem for all programmers is the variables’ spelling. Especially in lengthy codes where there is a significant number of variables, an error like that can cause erroneous results and a serious waste of time for debugging. This can be totally avoided if using the statement #stricton written in global section of the script. Doing this, the parser issues a warning when it comes across an undeclared variable. The declaration of variables is given explicitly either in the global section or within a function and must follow always a specific data type. The script stops this check by invoking the statement #strictoff. Thus, any code located between the two statements is examined also for variables’ spelling errors. Important Note 1: Although the variables get a type, they are still typeless.

BETA CAE Systems S.A.

page 7

ANSA v.13.x

Scripting Language

#stricton

In the next example, the parser will recognize the two undeclared variables (‘value’ and ‘params’) and will return the following warning message:

int a; float b; float param;

-----------------------------------------------------------------------------------------

def main() { a = 1; b = 1.2; value = a*b; params = a/b; } #strictoff

Important Note 2: There is no restriction to the number of times the #stricton and #strictoff can be invoked inside a script. Important Note 3: #strictoff is the default state.

1.4 Operators and Basic Calculation Various data types can be combined, by the appropriate operators, to form expressions. These expressions are evaluated when the script is executed. The results of a calculation can be stored for future use by assigning a value to a variable. This is done by an assignment statement whose general form is: = ;

where is the name of the variable, while is an expression formed by the combination of variable names using operators. The sets of operators and the rules of how expressions may be written and evaluated are determined by the types of the operands involved. Therefore, the data type is a very critical attribute of any data value. 1.4.1 Expressions and assignments for numeric data types An expression is formed by the combination of variables, constants and operators. Operators are used in order to compute new values out of old ones, and can be of two types: 1. arithmetic operators 2. assignment operators There are five different arithmetic operators that can occur in numeric expressions. These are: # 1. 2. 3. 4. 5.

Operator + * / **

Operation Addition Subtraction Multiplication Division Exponentiation

Some examples of arithmetic expressions are: surface_area = width_x * width_y; interior_vol = exterior_vol-width_x * width_y * width_z; hypot2 = a**2 + b**2;

However, the meaning of the 2nd and 3rd examples might not be clear. For instance, the 2nd example might be interpreted as interior_vol = (exterior_vol-width_x) * width_y * width_z;

or interior_vol = exterior_vol-(width_x * width_y * width_z);

BETA CAE Systems S.A.

page 8

ANSA v.13.x

Scripting Language

The meaning of such expressions is resolved by defining an order of precedence for operators. This precedence will determine the order in which the expression is to be evaluated. The assignment operators are the ones that actually assign a value to a variable. The well known “=“ sign is an assignment operator. For example x = 1;

sets x to 1, and a = b;

sets a to whatever b's value is. The expression i = i + 1;

is a standard programming idiom for increasing a variable's value by 1, while i = i - 1; i = i * 2; i = i / 2;

will decrease a variable’s value by 1, multiply and divide it by 2 respectively. 1.4.2 Operator precedence The order of precedence is very much alike what is known from algebra. Thus, exponentiations are carried out first, then multiplications and divisions and finally additions and subtractions. Multiplication and division have equal precedence. When a number of multiplications and divisions are found in sequence, the expression is evaluated from left to right. The same applies for addition and subtraction. Thus, the expression x / y * z ;

is understood to be (x / y) * z

and not x /(y * z)

It should be noted here that the use of parentheses can force the order of evaluation of certain expressions. Thus, the expression: x /(y * z);

will be evaluated exactly as written. 1.4.3 Important Notes on Operators Note 1: Combination of assignment with arithmetic operators The pattern: v = v op value;

where v is a variable, op is any of the addition, subtraction, multiplication and division operators +,-,*,/ and value is a constant arithmetic value, can be shortly expressed as: v op = value;

where v does not have to be mentioned twice. For example, the expressions i = i + 1;

BETA CAE Systems S.A.

page 9

ANSA v.13.x

Scripting Language

i = i - 1; i = i * 2; i = i / 2;

can be equivalently written as: i i i i

+= -= *= /=

1; 1; 2; 2;

Note 2: Increment and decrement operators For the most common cases where we add or subtract the constant value 1 from a variable, ANSA scripting language allows the use of auto-increment or auto-decrement operators. In their simpler form, they look like this: i++; i--;

These expressions correspond to the slightly longer: i += 1; i -= 1;

and to the fully expanded: i = i + 1; i = i - 1;

1.4.4 Numeric intrinsic functions It is often necessary to evaluate special mathematical functions, such as the square root of a number, the sine or cosine of an angle. ANSA scripting language incorporates several such intrinsic functions, to enable such functions to be evaluated easily. Some of the most important arithmetic functions are given in the table below.

# 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.

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.4.5 Expressions and assignments for string data types Characters may be assigned to string variables, using statements similar to those of numeric types: property = "PSHELL"; mat_name = "steel_105";

The operators that can be used to form expressions between string data types are: # 1. 2.

operator + %

operation string catenation string catenation

For example, the string variable BETA CAE Systems S.A.

page 10

ANSA v.13.x

Scripting Language

property = "PSHELL";

can be concatenated with the string variable id = "with id 1";

as

property_id = property + id;

or with the equivalent property_id = property % id;

and assign to the property_id variable the value "PSHELL with id 1"

1.4.6 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 also have a unique ID to distinguish it from other points. The point coordinates are real numbers and the ID is an integer. These point data can be grouped under the same structure in the following way: struct {int point_id; float x; float y; float z;} point;

The above line defines a structure called point whose members are an integer called point_id and three floats for the coordinates x, y, z. Once the structure is defined, it can be used as a regular data type for the declaration of other variables. For example, if we need to declare a point PA in space, we just need to type: point PA;

Now, the PA variable can automatically reference the members of the point structure, in other words PA can reference its id and its x, y, z coordinates. The syntax for this reference is struct.member and in this case takes the form: PA.point_id …the id of point PA PA.x …x-coordinate of PA PA.y …y-coordinate of PA PA.z …z-coordinate of PA For example, to assign number 13 as the id of point PA type: PA.point_id = 13;

and to assign the coordinates of PA type: PA.x = 123.45; PA.y = 321.00; PA.z = 456.78;

As an extension to declaring a single point PA that belongs to the structure point, we can declare an array (matrix) of points. For example, to declare an array called pts of 10 points in space using the structure point type: point pts[10];

The reference to the individual variables of the pts array follows the same rules as before. For example, to assign 13 as the id of the 5th point of the pts array, type: pts[5].point_id = 13;

and to assign the coordinates of pts[5] type: BETA CAE Systems S.A.

page 11

ANSA v.13.x

Scripting Language

pts[5].x = 123.45; pts[5].y = 321.00; pts[5].z = 456.78;

1.5 Sets of data: Matrices and maps Most problems that occur in practice require more than simple variables for their definition and solution. Thus, it is often necessary to handle data as sets of similar or different kind objects. Towards this direction comes the definition of matrices and maps. 1.5.1 Matrices A matrix data type provides a way to collect entities under the same storage. As a good programming practice, matrices should be declared so that the program will reserve enough space to store the data. The corresponding keyword for this declaration is matrix. Since matrix members are actually variables, they can hold any type of variable, so a matrix like: m={1, 1.23, "some string", "a", 2, 99.23};

is perfectly valid. Matrix members are accessed with index operators, i.e. m[0] is the first element in a matrix. Indices run from 0 to allocated space -1, i.e. for matrix m[10] they run from 0 to 9. The function MatLen returns the length of matrix m. len = MatLen(m);

Set some data in a matrix: To set some data to a specific position in a matrix type: m[3] = 10;

To specify all the matrix members at once: m = {10,7,9};

Matrix members can even be other matrices. Thus, a matrix like: m = {{10,7,9}, {5,2,17} {6,12,25}};

would form a 3x3 2 dimension matrix. Retrieve a matrix member value: To retrieve a value of a specific member of a matrix, the user must provide the corresponding index operator: i = m[0];

For the 3x3 2 dimension matrix given above: i = m [1][0];

will assign to i the value of 5. Handling strings A string has a length equal to the number of characters that comprise it and each one character holds an index. The first character has index 1 and the last one has index equal to the string length. This characteristic is essential for isolating specific parts of a string variable. str = "Bumber_Front";

The above string has 12 characters where B has index 1, u has index 2……and t has index 12. BETA CAE Systems S.A.

page 12

ANSA v.13.x

Scripting Language

We can get any part of the string by using the indices of the characters. Here are some examples: str str str str str str str

= = = = = = =

str(1:6); //This str(8:12);//This str(8:8); //This str(7:7); //This str(3:8); //This str(5:); //This str(:7); //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. Matrix expressions: All algebraic operations between matrices and constant values are interpreted as operations between each member of the matrix and the constant value. For example the expression: B = 10*A;

will result to a matrix B whose members are 10x the corresponding members of A. Addition, subtraction, division and exponentiation operations between matrices should take place only between conformable matrices (i.e. matrices having the same shape). On the other hand, the multiplication operation can take place both between conformable and unconformable matrices. In the former case, the multiplication takes place between each member of the matrices while in the latter case a matrix multiplication takes place. Having two conformable matrices A and B 2x3: A

= {{10,7,9}, {5,2,17}};

B = {{2,1,1}, {1,2,1}};

an addition operation: C = A+B;

will lead to a matrix C: C = {{12,8,10}, {6,4,18}};

Having two non-conformable matrices A, 2x3 and B 3x1: A = {{10,7,9}, {5,2,17}}; B = {{1}, {2}, {1}};

a multiplication operation: C = A * B;

will lead to a matrix C 2x1: C = {{10*1+7*2+9*1}, {5*1+2*2+17*1}};

BETA CAE Systems S.A.

page 13

ANSA v.13.x

Scripting Language

The following table summarizes some intrinsic functions available for the management of matrices: # 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.

Function MatLen(m); Min(m,no_of_values); Max(m,no_of_values); CrossProduct(vec1, vec2); DotProduct(vec1, vec2); NormalVec(vec) Normalize(vec); TransposeMatrix(m) MaxIndex(m,no_of_values); MinIndex(m,no_of_values);

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_values finds the index of the minimum of an array of no_of_values

1.5.2 Maps A map data type can be seen as an expansion of the matrix, since the indexing is done with arbitrary values. The keyword that specifies this data type is map. A map is characterized by a name and is like a user defined tree-structure, where each node holds a specific value and is referenced by a specific key: (map_name, key, value)

Note that to use a map, you need to initialize it first using the command CreateMap: m = CreateMap();

Set some data in a map: When a map is created and initialized, it is originally blank. To set some data to a specific node of a map, use the SetMapNode: SetMapNode(m, key, value);

For example, the command SetMapNode(m, 1140, 1) will assign the value 1 to the node holding the key 1140. An equivalent expression would be: m[1140] = 1;

The values and keys of a map can be of any type. Nodes within the same map are sorted according to their key and the corresponding precedence order is: number > map > string For example, node (m,"1140",1) comes after node (m,1140,2), since the former node uses a stringtype key and the latter node uses a numeric key. Note that when maps are used as keys, they are sorted according to the number of nodes they have, with larger maps taking precedence over smaller maps. Retrieve a node value: To retrieve a value of a specific node, the user must provide the corresponding nodal key using the GetMapNode function: i = GetMapNode(m, key);

For example, for the node (m,"1140",1), the command i = GetMapNode(m,"1140");

will assign to i the value of 1. An equivalent expression would be: i = m[1140]

BETA CAE Systems S.A.

page 14

ANSA v.13.x

Scripting Language

Delete a node: Deletion of a node within a map is achieved using the EraseMapNode command: EraseMapNode(m, key);

Iteration through the data in a map: In order to search through the data of a map, 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, key, value); i = GetLastNode(m, key, value);

Both functions return 1 on success and 0 upon failure (e.g. when the map is not defined or is empty). Looping through the map is achieved using the GetNextNode and GetPreviousNode commands: i = GetNextNode(m, key, value); i = GetPreviousNode(m, key, value); for(ret=GetFirstNode(m, key, value);ret;ret= GetNextNode(m, key, value)) { Print("For key "+key+" the value is "+value); }

Destroy the map and release memory: To delete a map, use the DestroyMap: DestroyMap(m);

Identify the number of nodes in a map: To identify how many nodes a map contains, use the GetMapEntries: i = GetMapEntries(m);

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(); SetMapNode(m,key,value); GetMapNode(m,key); EraseMapNode(m,key); GetFirstNode(m,key,value); GetNextNode(m,key,value); GetLastNode(m,key,value); GetPreviousNode(m,key,value); DestroyMap(m); GetMapEntries(m);

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.6 Conditional Statements and Branching 1.6.1 The "if-else" blocks and the logical operators The if statement is the basic decision statement of a script. 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 true (i.e. not equal to 0), then the if-block of statements is executed. If the condition is false, then the else-block of statements is executed. The if statement general form is: if (condition) statement;

The alternative line of execution is created with else: if (condition)

BETA CAE Systems S.A.

page 15

ANSA v.13.x

Scripting Language

statement; else statement;

Since the condition is interpreted as a logical operator, the operators used for its expression are the logical relational operators. Such operators are summarized in the table below: # 1. 2. 3. 4. 5. 6. 7 8 9

Operator < >= == != || && ^

Meaning less than less than or equal to greater than greater than or equal to equal to not equal to Logical OR Logical AND Logical XOR

Some examples of the use of the if-else blocks follow: if (a>5) { b = 0; c = 0; } if (a>5) { b = 0; c = 0; } else { b = 1; c = 1; } if (a>5 ^ c==1) b = 0;

In this case the logical expression a>5 will be evaluated. If it is proved true, then b and c will be assigned zero values. Otherwise, this block of statements will be ignored. In this case the logical expression a>5 will be evaluated. If it is proved true, then b and c will be assigned zero values. Otherwise, they will be assigned unit values as dictated by the else group of statements.

In this case b will be assigned zero value, only if one of the two expressions is true. It is similar to : if((a>5 && c!=1) || (c==1 && a5) { b = 0; c = 0; } else if (a5 || b==1) c = 1; if(a>5) && b==1) c = 1;

BETA CAE Systems S.A.

In this case the logical expression a>5 will be evaluated. If it is proved true, then b and c will be assigned zero values. Otherwise, the logical expression a

where < label > is the label of an executable statement. i.e. some_label: ... if (a>5) goto some_label;

BETA CAE Systems S.A.

page 17

ANSA v.13.x

Scripting Language

1.7 Loop statements A loop comprises of a block of statements that are executed repetitively. When the end of the loop is reached, the block is repeated from the start of the loop. 1.7.1 The foreach statement The foreach statement allows the iteration over the elements of an array. foreach loops do not maintain any explicit counter. The general form of the statement is: foreach in { do something to }

An example of the statement use is given below: all_properties = {"PSHELL","PCOMP","PBAR","PBEAM","PELAS"}; foreach property in all_properties Print (property); the result is PSHELL PCOMP PBAR PBEAM PELAS

1.7.2 The for statement The for statement introduces an indexed loop, where the number of repetitions is known before the loop is started. The general form of the for statement is: for (initial-statement; condition; iteration-statement) body-statement;

The initial-statement initializes the explicit counter, the condition specifies the number of repetitions and the iteration-statement dictates the increment or decrement value of the explicit counter during the loop. for (a=0; aScript options • FILE>Script>Script editor: Opens the Script Editor interface. • FILE>Script>Load: Loads a script. The user is prompt to select a file from the File Manager. All previous loaded scripts are unloaded. Every script that is loaded becomes the default one. This means that all the functions that holds are ready to run any time. • FILE>Script>Import: Imports a script. The user is prompt to select a file from the File Manager. Any function located in an imported script is appended to loaded ones and is ready to run any time. • FILE>Script>Add Adds a script in the database. The user is prompt to select a file from the File Manager. An added script is considered loaded but the functions that holds are not available for running. • FILE>Script>Default: Sets a script as default. Selecting this button opens a window where all loaded and added scripts are displayed. The index in front of each path indicates which is the default sequence. Always, the script with zero index is the default. Select a script from the list and press the "Set as default" button to become the default one. Press then OK to confirm. Important Note: A loaded script takes always zero index while an added script takes the first available index.

BETA CAE Systems S.A.

page 73

ANSA v.13.x

Scripting Language

Each time a script is set as default, the functions that holds become available. The one that was previously default remains loaded but its functions are not available anymore. Important Note: Imported scripts are not listed in the above window. • FILE>Script>Reload: Reloads all loaded and imported scripts. • FILE>Script>Unload: Unloads loaded or added scripts. Selecting this button opens the list with all loaded and added scripts of the database. Select the script to unload and confirm with Ok. When the default script is unloaded then as default becomes the script with the next index. Consequently, all the functions of the first one are lost and the functions of the second become available.

Functions of imported scripts retain a relationship with the zero index script since they are appended to it. So, if a user unloads the zero index script then the functions of the imported scripts will be lost too. Similarly, if the default status is changed, the functions of the imported script will become unavailable. • FILE>Script>Run function: Runs a function. When selecting this button the following window opens:

BETA CAE Systems S.A.

page 74

ANSA v.13.x

Scripting Language

In the Function list all available functions are displayed. These functions come from the imported scripts and from the default script. In Available modules menu, all the available scripts are displayed while the default one is always active. If another module is selected, then automatically its functions will become available while the previous ones will be unavailable. Other useful buttons are the Load module which acts similarly to SCRIPT>ADD and the Reload module which reloads the active script. Select a function from the list. Its help is displayed in the User function description. If the function needs input arguments, then these must be given in the Type function arguments field in comma separated form.

BETA CAE Systems S.A.

page 75

ANSA v.13.x

Scripting Language

7. Automation through the ANSA_TRANSL file 7.1 Location of ANSA_TRANSL file When ANSA is called to run, it will search for an ANSA_TRANSL file within the locations listed in the following table. The numbers on the left indicate precedence (from lowest to highest): # Location Description 1. ANSA_HOME Directory This is the directory where the environment variable ANSA_HOME is pointing at. 2. Hidden BETA directory located in User's HOME directory This is the directory that is created as soon as ANSA is launched for the first time. It is located in: /home/user/.BETA/ANSA/version_13.x/ 3. Working Directory This is the directory from which ANSA was called to run. During the attempt to read an ANSA_TRANSL, ANSA will display the following messages in the Text Window: 1. ERROR script : [ansa home directory/ANSA_TRANSL] not found 2. ERROR script : [hidden BETA directory/ANSA_TRANSL] not found Reading script from :[..path where ANSA_TRANSL was found..] 7.1.1 How does ANSA interacts with ANSA_TRANSL ANSA_TRANSL interacts with ANSA in two ways: (a) when ANSA tries to read a CAD file, and (b) when a user executes a custom script. In the first way, ANSA will read and execute automatically all the commands written within the ANSA_TRANSL CAD_Translate function. This functionality is very useful in cases where multiple CAD files should be translated into ANSA databases and the property, material, thickness, and other specific characteristics for each part must be assigned to the related fields within ANSA. In the second way, a user can call to run a previously defined function within ANSA_TRANSL. This can be done at any time during the user interaction with ANSA and can affect whatever is currently loaded in ANSA, either geometry or FE-model data. These functions are invoked from the command prompt of the Command Line Window or from SCRIPT menu (See Section 6.2.3 and Section 6.3.2). Important Note: ANSA_TRANSL can be also loaded manually. 7.1.2 Form of ANSA_TRANSL The general structure of an ANSA_TRANSL contains a global section and a user_functions section:

TRANSLATIONS SEPARATORS

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

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

global section

/* Log Attributes File Name */ if(fd_log) i=write(fd_log,"Reading :"%attr_filename); else print("Reading :"%attr_filename); /* Open Attributes File for Reading */ attr_fd=fopen(attr_filename,"r")) { defif(attr_filename WeldParts(string&&dir_path){ /* Log Attributes File Name */ weld_file = dir_path+"CONNECTIONS.txt"; i=write(fd_log,"Reading :"%attr_filename); f if(fd_log) = fopen(weld_file, "r"); else print("Reading :"%attr_filename); while(read(f, line)){ m = tokenize_string(line," ",0); type = m[0]; wid = atoi(m[1]); wx = atof(m[2]); wy = atof(m[3]); wz = atof(m[4]); part1 = m[5]; part2 = m[6]; for ( part = GetFirstEntity(NASTRAN, "ANSAPART" ); part; part = GetNextEntity(NASTRAN, part) ) { GetEntityCardValues(NASTRAN, part, "Name", part_name, "Module Id", mid ); if (part_name==part1) mid1 = mid; if (part_name==part2) mid2 = mid; } i1 = CreateWeldPoint(wid, wx, wy, wz, mid1, mid2); i2 = ProjectWeldPoint( i1, 1, 0, 0, 0, 0, 5 );

user_functions section

The global section is the place where any variables or structures are allowed to be defined. The user_functions section may contain a series of user functions in addition with a specific one called CAD_Translate. This function substitutes the old global code (v12.x) and is executed while reading cad BETA CAE Systems S.A.

page 76

ANSA v.13.x

Scripting Language

files (iges, step, vda) or during the translation of any of the supported CAD filetypes (Catia, UG, ProE, JT). CAD_Translate accepts no arguments and has the same form as any other user function. If ANSA finds between the ANSA_TRANSL files more than one global code then the last read will be kept. Similarly, if functions with same name are identified, then the last read will overwrite the previous ones. Important Note 1: It is recommended the CAD_Translate and all common user functions to be kept in the ANSA_TRANSL of ANSA installation directory. Important Note 2: ANSA_TRANSLs that come from versions prior to v13.0 are valid only if they are in binary format. 7.1.3 Registers used for translation The CAD_Translate function can contain any script function, is written as any other code but it is executed only when pure cad files are used and when all the actual entities have been translated into ANSA. ANSA_TRANSL def CAD_Translate() { ...code... } def Translation() { ...code... } def ChangePids(element pshell) { ...code...

} Apart from the built in functions, the CAD_Translate can use a number of functions/keywords called registers. These registers cannot be used from user defined functions and their use is very common when attributes like property name, property id, material name etc, must be assigned to the read cad models. Below is the list with all currently supported ANSA registers. ANSA registers FILENAME FILEPATH SEPARATORS TRANSLATIONS PART_ID PART_NAME PART_VERSION 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 BETA CAE Systems S.A.

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. ,_.) Default character translations (eg. " " = "_" 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 version 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.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.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 page 77

ANSA v.13.x

Scripting Language

POST_TRANSL_SCRIPT_ARGS FLANCH_PROPERTY_ID PART_MODEL_NAME SYMMETRY_PART_ID SYMMETRY_PART_ID_OFFSET

Obsolete Obsolete Obsolete Obsolete Obsolete

The basic advantage of registers is that they can pass directly a value to an entity without the need to search for the entity. Clearly, this approximation saves a lot of user work, minimize the code and eliminates the possibility of error. For example, 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. PART_PROPERTY_NAME = "panel"; PART_MATERIAL_NAME = "steel";

The same could be made with the use of built in functions: pshell = GetFirstEntity(NASTRAN,"PSHELL"); SetEntityCardValues(NASTRAN,pshell,"Name","panel"); material = GetFirstEntity(NASTRAN,"MAT1"); SetEntityCardValues(NASTRAN,material,"Name","steel");

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. Important Note: If the cad file has more than one properties, then registers like PART_PROPERTY_NAME, PART_PROPERTY_THICKNESS etc will affect them all. 7.1.4 Importing CAD files Information about a part (like its name, property, material, thickness, position, etc) can reside as comments into the header section of a CAD file in the form of keywords. Using a special ANSA_TRANSL script, these keywords are read and the related information is passed directly into ANSA. In its simpler form, such an ANSA_TRANSL does not have a user_functions section and all the translation process is handled through the CAD translation section. CAD File ANSA_TRANSL

HEADER Section NAME : CH-CBN-OUTER-L PID : 21 THICKNESS: 1.5 MATERIAL : MATS1_STEEL MID : 2 . . . . . . . . . . . . .

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

DATA Section 01234567891 . . . 123 . 1

A cad header can be read with the function GetNextFileLine. The syntax accepts a string argument where each line of the header is going to be stored after a succesful call of the function. Usually it is used together with a while statement. IGES header example MODEL PART NUMBER TITLE PROP ID VERSION THICKNESS MAT ID MAT NAME POSITION VERSION THICKNESS

: : : : : : : : : : :

SPACE MOBILE 1234567 LEFT FLOOR BEAM 456 A 1.5 7892 St 50 BH L B 1.2

BETA CAE Systems S.A.

S S S S S S S S S S S S S

1 2 3 4 5 6 7 8 9 10 11 12 13

Header

page 78

ANSA v.13.x

Scripting Language

1H,,1H;,,57H/usr/people/CAD_data2/STELIOS_TEST/INTERFACES/header.iges,7HG ANSA9.x,3H1.2,32,36,6,306,15,,1.,2,2HMM,1,1.,13H991109.153539,0.001, G 10000.,,,9,1,13H991109.153539; G 126 1 0 0 0 0 0 000000001D 126 0 0 8 0 0 0BSPLINE 1D 126,12,2,0,0,0,0,0.,0.,0.,0.25,0.25,0.375,0.375,0.5,0.5,0.75, 1P 0.75,0.875,0.875,1.,1.,1.,1.,1.,1.,0.707107,1.,0.707107,1.,1., 1P 1.,0.707107,1.,0.707107,1.,406.539,1057.63,-6.75,401.539, 1P 1057.63,-6.75,396.539,1057.63,-6.75,396.539,1050.88,-6.75, 1P 396.539,1050.88,0.,396.539,1050.88,6.75,396.539,1057.63,6.75, 1P 401.539,1057.63,6.75,406.539,1057.63,6.75,406.539,1050.88,6.75, 1P 406.539,1050.88,0.,406.539,1050.88,-6.75,406.539,1057.63,-6.75, 1P 0.5,0.75,0.,0.,0.; 1P S 13G 3D 2P 8 T

1 2 3 1 2 1 2 3 4 5 6 7 8 1

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 .

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

FRONT_DOOR_LT 21 1.5 MATS1_STEEL 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: /*---------------------------------------------------*/ /*---Informations are written in ANSA_TRANSL.log-----*/ /*---------------------------------------------------*/ /*---------------------------------------------------*/ def CAD_Translate(){ { SEPARATORS = "=:,;"; /* Separator of Words or Numbers*/

BETA CAE Systems S.A.

page 79

ANSA v.13.x

Scripting Language

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

BETA CAE Systems S.A.

page 80

ANSA v.13.x

Scripting Language } /* 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]); 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;

BETA CAE Systems S.A.

page 81

ANSA v.13.x

Scripting Language

else name = FILENAME; } /* Finally Assign PART Atributes to ANSA Registers */ PART_NAME = pdm_id; PART_ID = module_id; PART_PROPERTY_ID = property_id; PART_PROPERTY_NAME = property_name; PART_PROPERTY_THICKNESS = thickness; PART_MATERIAL_ID = material_id; PART_MATERIAL_NAME = material_name;

} The key functions for reading this file is the MatchString and TokenizeString which were discussed in Section 4.2.2. It is clear that 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. VDA-FS header example The sample vda file contains in its start section the information describing the part that is supposed to be in this file. The information is formatted in such way that cooperates with the sample ANSA_TRANSL file. The most important information is: T-SNR :8165630 T-KOGR :4115 T-LRKZ ;R T-SDKZ ; T-EBEZ :XYZ T-TNAME:CSAULE OUTER ==================== V-MATNR;10163 V-MATNO;DIN EN 10163 V-MATNA;St14 V-MATDI; 0.

In this case the sample ANSA_TRANSL script file has the appropriate format in order to import the information needed from the sample vda file. Follow the same check steps as for the iges file case. VDAFS = HEADER / 35 00000010 ************************************************************************00000020 VDAFS VERSION : 2.0 00000030 ------------- ANGABEN UEBER DEN ABSENDER -------------------------------00000040 SENDERFIRMA : BETA 00000050 ANSPRECHPARTNER : 00000060 TELEFON : 00000070 ADRESSE : 00000080 ERZEUGENDES SYSTEM : ANSA V9 R0 00000090 ERZEUGUNGSDATUM : 00000100 SENDE-FILENAME : 00000110 ------------- ANGABEN UEBER DAS TEIL -----------------------------------00000120 PROJEKT : xx 00000130 OBJEKTKENNUNG : 00000140 VARIANTE : xx 00000150 VERTRAULICHKEIT : xx 00000160 GUELTIGKEITSDATUM : 00000170 ------------- ANGABEN UEBER/FUER DEN EMPFAENGER ------------------------00000180 EMPFAENGERFIRMA : xx 00000190 EMPFAENGERNAME : xx 00000200 ************************************************************************00000210 TOLERANZ : XXXXX MM 00000220 WINKELTOLERANZ : XXXXX GRAD 00000230 ************************************************************************00000240 T-SNR :8165630 00000290 T-KOGR :4115 00000300 T-LRKZ ;R 00000310 T-SDKZ ; 00000320

BETA CAE Systems S.A.

page 82

ANSA v.13.x

Scripting Language

T-EBEZ :XYZ 00000330 T-TNAME:CSAULE OUTER 00000380 ========================================================================00000640 V-MATNR;10163 00000770 V-MATNO;DIN EN 10163 00000780 V-MATNA;St14 00000790 V-MATDI; 0.8 00000810 ************************************************************************00001600 SET1 = BEGINSET 00000250

ANSA_TRANSL file for VDA-FS header example def CAD_Translate(){ SEPARATORS = ":;"; version = "A"; while(GetNextFileLine(in_line)) { if(i = MatchString(in_line,"V-VERSI")) { if(j = MatchSeparators(in_line(i:))) { cur_version = GetString(in_line(j+i:)); if(cur_version>version) version = cur_version; } } else if(MatchString(in_line,"Modelfile:")) { if(GetNextFileLine(in_line)) { serial_number = GetInt(in_line(:7)); } else break; } else if(!position && (i = MatchString(in_line,"T-LRKZ"))) { if(j = MatchSeparators(in_line(i:))) position = GetString(in_line(j+i:)); } else if(!name && (i = MatchString(in_line,"T-TNAME"))) { if(j = MatchSeparators(in_line(i:))) name = GetString(in_line(j+i:)); } else if(!serial_number && (i = MatchString(in_line,"T-SNR"))) { if(j = MatchSeparators(in_line(i:))) serial_number = GetInt(in_line(j+i:)); } else if(!model_name && (i = MatchString(in_line,"T-EBEZ"))) { if(j = MatchSeparators(in_line(i:))) model_name = GetString(in_line(j+i:)); } else if(!status && (i = MatchString(in_line,"D-DOALT"))) { if(j = MatchSeparators(in_line(i:))) status = GetString(in_line(j+i:)); } else if(version == cur_version) { if(i = MatchString(in_line,"V-MATDI")) { if(j = MatchSeparators(in_line(i:))) thickness = GetFloat(in_line(j+i:)); } else if(i = MatchString(in_line,"V-MATNR")) { if(j = MatchSeparators(in_line(i:))) material_id = GetInt(in_line(j+i:)); } else if(i = MatchString(in_line,"V-MATNA")) { if(j = MatchSeparators(in_line(i:))) material_name = GetString(in_line(j+i:)); } } } if(!serial_number) { i = MatchString(FILENAME,"."); serial_number = GetInt(FILENAME(:i-1)); } if(!name) name = FILENAME; if(!version) version = "A"; if(!position) position = "L"; if(!serial_number) property_id = 1; else property_id = serial_number;

BETA CAE Systems S.A.

page 83

ANSA v.13.x

Scripting Language

if(!model_name) model_name = "U"; if(!status) status = "U"; if(!thickness) hickness = 1.5; if(!material_id) material_id = 1; if(!material_name) material_name = "Default Material MAT1"; if(serial_number && !symmetry_number) symmetry_number = serial_number; PART_NAME = name ; PART_VERSION = version; PART_MODEL_NAME = model_name ; PART_ID = serial_number ; SYMMETRY_PART_ID = symmetry_number ; PART_PROPERTY_NAME = version%"_"%status%"_"%serial_number%"_"%position%"_"%name ; PART_PROPERTY_ID = property_id ; SYMMETRY_PART_PID_OFFSET= 0; PART_PROPERTY_THICKNESS = thickness ; PART_MATERIAL_NAME = material_name ; PART_MATERIAL_ID = material_id ; }

7.1.5 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 commands prior to start working with ANSA, for example to print a ‘Hello’ message followed by the current date and time as soon as ANSA is launched. def autoexec() { New("discard"); Print("Hello"); Print("Today is: "+Date()); Print("ANSA opened at "+Time()); }

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:

If no autoexec is found, ANSA will display a relative message in Ansa Info window: Function [autoexec] not found.

BETA CAE Systems S.A.

page 84

ANSA v.13.x

Scripting Language

8. Extracting information from Catia 8.1 General This chapter tries to describe a way of exploiting useful cae information like connections, sections, attributes like property name or material name, as well as orientation information that have been defined inside Catia. However, due to the binary format of Catia files, it is difficult for a preprocessor to receive and use automatically and efficiently these data. Nevertheless, the evolution of cad translators allows the recognition of many of these features and consequently gives the capability to use them in any study. ANSA has access to some of these features through the ANSA_TRANSL global code and specific scripting commands.

8.2 Script commands related with Catia The most important script commands that are related to the Catia translator are summarized in the following table: #

Catia function

1.

LayerThickness

2.

MaterialVector

3.

MatVecThickness

4.

OrientationVector

5.

PartContainsGeometry

Description Checks if layer thickness was found in the file Checks if material vector was found in the file Returns thickness according to material vector Checks if orientation vector was found in the file Checks the existence of geometry in file

8.2.1 Orientation check A successful orientation of parts during translation saves a lot of manual work for the cae user, but also eliminates the case of mispositioned or intersected parts during the assembly. The orientation information can be extracted from Catia translator through three different ways: a) The material vector which is invoked through the option: -matvec b) The orientation vector which is invoked through the option: -use_orient_vec #layer number c) The thickness lines which is invoked through the option: -layer_thick #layer number More information can be found in Section 3.3.1 of cad_data_translators.pdf The functions that can be used in order to recognize such definitions are the LayerThickness, MateriaVector and OrientationVector. All of them accept no arguments and return 1 for success and 0 for failure. In the following example every file that is translated is checked whether it contains an orientation vector. In case of a missing vector a message is written in the ANSAPART comment of the resulted ansa file. orient_found = OrientationVector(); if(!orient_found) { comment = FILENAME+" doesn’t contain an orientation vector in the specified layer "; part = GetFirstEntity(NASTRAN,"ANSAPART"); SetEntityCardValues(NASTRAN,part,"Comment",comment); }

BETA CAE Systems S.A.

page 85

ANSA v.13.x

Scripting Language

8.2.2 Extracting thickness from catia entities Thickness information from Catia files can be retrieved using the function MatVecThickness. It accepts no arguments and returns the thickness as defined in the cad file. Actually, the MatVecThickness returns the 1/100 of the length of the specified material vector curve. In case of failure it returns -1.After getting the value, an extra care must be made so as to pass the information into the appropriate fields. For example, we need to get the thickness from a curve and set it to the fields "T" and "cad_thickness" of a PSHELL card. thickness = MatVecThickness(); pshell = GetFirstEntity(NASTRAN, "PSHELL"); SetEntityCardValues(NASTRAN,pshell,"T",thickness,"cad_thickness",thickness);

Important Note: The "cad_thickness" field is accessible only through scripting. 8.2.3 Checking geometry existence For checking if the Catia file contains any geometry, the function PartContainsGeometry must be used. It accepts no arguments and returns 1 if at least one entity is found and 0 if the file is empty. status = PartContainsGeometry(); If(!status) { fw = Fopen("report.txt","a"); text = FILENAME+" doesn’t contain any geometry"; Write(fw,text); Fclose(fw); }

The above global code writes a report with all parts that don’t contain any geometric entity.

8.3 Reading Header/Comment Section of Catia file In cases where the part attributes need to be predefined in the cad file, it is recommended to store them under two specific Catia features which are the Catia header for CATIA V5 or the Catia comment section for CATIA V4. Then, during translation this data can be read and passed within the final ansa file. The function that must be used is the GetNextFileLine which returns in case of CATIA V5 a line of the following form: : while for CATIA V4 returns each line exactly as it is written. Subsequent to this function, it is necessary to call the TokenizeString which will split the respective strings. Suppose that we have the following model comment section and Catia header. The ideal ANSA_TRANSL should be the one below (for CATIA V5): while(GetNextFileLine(line)) { m = TokenizeString(line, ":",0); attribute_name = GetString(m[0]); if(attribute_name=="PartNumber") { module_id = GetString(m[1]); } else if(attribute_name=="Revision") { Version = GetString(m[1]); } }

BETA CAE Systems S.A.

page 86

ANSA v.13.x

Scripting Language

CATIA V5 HEADER

CATIA V4 COMMENT

Part Number: 32000B Revision: B Description: Left Part

BETA CAE Systems S.A.

page 87

ANSA v.13.x

Scripting Language

If we just print the GetNextFIleLine output, we will see the following: PartNumber : 32000B Revision : B Definition : 1 Nomenclature : A28 Source: Unknown Description : Left Part Int : 28 F : 17 Creation D : 2.008e+0.7s

8.4 Creating connections from points and curves of Catia During the translation of Catia points and curves into the equivalent ANSA entities, their names and their position in the tree structure are transferred automatically in ANSA. Specifically, they are kept under the "Name" and "Comment" fields respectively. It is obvious that a well organized cad file can lead to an automatic weld spot definition. A simple Catia structure that could describe the weld information in a manner that could be interpreted easily through scripting is the following

Keep in mind that any other configurable structure, even more complicated, is also recognized and mirrored within ANSA points and curves points = CollectEntities(NASTRAN,0,"POINT",0); foreach point in points { GetEntityCardValues(NASTRAN,point,"X",x,"Y",y,"Z",z,"Name",name,"Comment",comment); if(MatchString(comment,"Connection Points")) { tokens = TokenizeString(name,"_",0); if(MatLen(tokens==3)) { pids[0] = tokens[1]; pids[1] = tokens[2]; } else if(MatLen(tokens==4)) { pids[0] = tokens[1]; pids[1] = tokens[2]; pids[2] = tokens[3]; } xyz[0] = x; xyz[1] = y; xyz[2] = z; CreateConnectionPoint("SpotweldPoint_Type",0,xyz,3,pids,MatLen(pids)); ReleaseVar(pids); } }

The point card after translation looks like the following:

BETA CAE Systems S.A.

page 88

ANSA v.13.x

Scripting Language

The same approach could have been followed for connection curves.

8.5 Handling of properties Except of points and curves, ANSA also handles in a special way the names of Geometrical Sets and PartBodies of Catia. These names are interpreted as ANSA property names and thus they can be treated during the translation of Catia files. Suppose that the cad designer needs to create auxiliary geometric entities (FACEs) that actually don’t mean anything to the cae user. These entities are positioned to a Geometrical Set called "Auxiliaries". Also, another PartBody with name "Bolts" includes all the bolts of the current part. An ANSA_TRANSL could be used in order to delete the unnecessary created properties. i = 0; pshells = CollectEntities(NASTRAN,0,"PSHELL",0); foreach pshell in pshells { GetEntityCardValues(NASTRAN,pshell,"Name",name); if(name=="Bolts" || name=="Auxiliaries") { To_del[i++] = pshell; } } DeleteEntity(to_del,1);

8.6 Writing in the Catia log file The option "Create log file" (-log) of Catia translator creates a log file named as: . The user has access into this file through the function TranslatorLogFile. The function accepts no arguments and returns an integer. Having this integer the user can append anyt text in the created log file: fid = TranslatorLogFile(); pshells = CollectEntities(NASTRAN,0,"PSHELL",0); no_pshells = MatLen(pshells); Write(fid,"The file contains "+no_pshells+" of PSHELL properties");

The above code appends in the end of the log file a message regarding the number of the created PSHELL properties.

BETA CAE Systems S.A.

page 89

ANSA v.13.x

Scripting Language

8.7 The "Extra Options" field of Catia Translator "Extra Options" (-user options) is used in conjunction with a script function called ProgramArguments. When this function is called, it returns all options used for the translation of the cad files, including the user options that were written in the "Extra Options" field. In this way, the user can signal to ANSA_TRANSL the execution of a specific code. Suppose that the user would like to skin or to offset the Catia files. Since such options are not supported in the translator, he could pass some user defined options through the "Extra Options" in order to be read by an ANSA_TRANSL. The options could be either "skin" or "link".

. args = ProgramArguments(); foreach arg in args { if(MatchString(arg,"skin")) Skin(1,0,3,1,0,0,5); else if(MatchString(arg,"link")) OffsetLink("0.5"); }

BETA CAE Systems S.A.

page 90

ANSA v.13.x

Scripting Language

9. Script Editor 9.1 Script Editor Layout Script Editor is a fully independent tool, integrated in ANSA, where a user can easily build or test his own scripts. It can be invoked through the File>Script>Script editor. The main features of this interface are highlighted and briefly described below.

Main Menu

Scripts

Main Window Dynamic Help List Functions List

Help/Output Area

Shortcut Keys Main Menu Main Window Shortcut Keys Help Output Area Dynamic Help List Functions List

BETA CAE Systems S.A.

Contains the script editor functions The area where the code is written or tested Buttons for calling the most important edit and debug functions. 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. When the Help tab is active it displays the help text of a built in function, 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. Additionally, a dynamic help is always displayed whenever a function name is written correctly in the main window

page 91

ANSA v.13.x

Scripting Language

9.2 Opening scripts Every time a new script is imported, a new tab having the name of the script is added next to the Help tab of main window. There is no restriction regarding how many scripts can be remained opened simultaneously.

9.3 Running scripts If the script contains a function called main, then every time the F5 button is pressed the script is executed. Otherwise, you should go to Debug>Run function which acts similar to button File>Script>Run function (See Section 6.3.2). If a script has a syntax error then this is reported in the output area.

9.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. Therefore, when the immediate tab is active it is not allowed to have any def statement (See Section 1.8.1) in the code. Consequently, any variable that is written in the global section of the script has no sense. For example in order to test how many spotwelds exist in the database we write: Spots = CollectEntities(NASTRAN,0,"SpotweldPoint_Type"); Print(MatLen(Spots));

Instead of def fun_name() { Spots = CollectEntities(NASTRAN,0,"SpotweldPoint_Type"); Print(MatLen(Spots)); }

Important Note: Scripts made in the immediate environment can be executed normally.

9.5 Help area This area helps the user to find all built in functions either by their category or by their name. A double click on a function displays a help text in the Output Area. Moreover, a Dynamic help tab is always activated every time a function name is written correctly in the main window:

In the above example, the Dynamic help recognized the ‘CollectEntities’ and therefore the necessary parameters were displayed according to their precedence. An arrow on the left of every parameter indicates which argument must be written next. Important Note: Pressing F1 while the cursor is pointing on a built in function name (written in the main window), the respective help text is displayed in the Output Area.

BETA CAE Systems S.A.

page 92

ANSA v.13.x

Scripting Language

9.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 compiled script can be loaded and run throughout all the normal ways (command line, script menu) while it can be used as an include file too. Furthermore, all the functions that holds can be called from any other script even from decompiled ones. Important Note 1: A compiled script cannot be executed through the Script Editor. Important Note 2: Scripts can be compiled normally even if they contain #include or #projectfile statements.

9.7 Making and importing snippets Snippets are sections of code or even fully independent functions that can be created or loaded anytime through the editor. The first time a snippet is created, it is saved without any warning in an xml file called snippets.xml. This file is located in the working directory and can hold separately any number of snippets. 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.

Pressing the Make snippet option opens the snippet window:

Automatically, the selected code goes to the code section of the window where the user can further edit it. BETA CAE Systems S.A.

page 93

ANSA v.13.x

Scripting Language

Moreover, a snippet is distinguished from its name and it is stored either in an ANSA or a META snippets list. By default the ANSA tab is active. A snippet can be imported from the Tools>Code snippet option of the main menu. This function opens the previous window where the user can select a snippet from the available list on the left. Selecting it and pressing the Import button, the respective code is inserted into the main window at the cursor position.

9.8 Creating projects A project is a collection of user scripts, organized in a way that they can be accessed anytime through Script Editor. The project environment is embedded in Script Editor and offers two distinctive capabilities: First, enables the creation of a project file, which is actually an xml file, holding references to scripts’ file paths under a specific structure. Next, it can create a ‘main’ script with #projectfile statements. The files that are referenced in this script, are those that are included in the xml file. The project environment can be activated through Window>Project window.

9.8.1 Starting a new project A new project can be created either from Project>New project of main menu or if right click inside Project window and select the New project option. In the window that opens, type the name of the project and the directory where it will be saved. Also, there is an option to append the default extension ‘bs’ to the final ‘main’ script. In this example we are going to create an ANSA_TRANSL file so the respective check button is de activated.

BETA CAE Systems S.A.

page 94

ANSA v.13.x

Scripting Language

As soon as we press ok, a file named ANSA_TRANSL.bpr is created in the selected folder. This is the project file and initially has the following form:

Also, in Project window, the following structure is displayed:

Two categories can been seen in the above picture. The category Include files can host auxiliary files that are added normally in the project file but are not incorporated in the ‘main’ script. The Source files are the basic files that will be referenced either in the project file or in the ‘main’ script. 9.8.2 Adding existed files to a project Existed source files can be added in a project if right click on the respective option and select Add existing file.

From the File manager that opens, select one or more scripts to add. After selection the project structure will be as following: BETA CAE Systems S.A.

page 95

ANSA v.13.x

Scripting Language

An added file can be accessed if double click on it with left mouse button. As soon as the file is selected, its content is displayed in the main window where can be viewed or edited. Press the Project>Save project to update the xml project file and next edit the file to see the changes:

Suppose that some of these files use include files that the user would like also to add in the project. This can be done if right click on the respective option and select Add existing include. Again, the File manager opens and waits for files selection. The selected file is added under the Include files category:

To update the xml project file press again the Project>Save project.

BETA CAE Systems S.A.

page 96

ANSA v.13.x

Scripting Language

9.8.3 Adding new files to a project A new source file can be added if right click on the respective option (Source files) and select Add new file or from File>New file. The windows that opens in both cases are almost the same. When the second approach is used, an extra option called Add file to project is displayed.

Select the Empty script option and press Ok (If you open the right window activate the extra option). A new source file is added with initial name Untitled new file and a new empty file is created in main window. Write the new script and press the Save file button

Name the file and select the directory where it will be saved. Automatically, the initial file path is updated.

BETA CAE Systems S.A.

page 97

ANSA v.13.x

Scripting Language

9.8.4 Creating the ‘main’ script The final ‘main’ script can be extracted either from Project>Export main script or if right click on project filename (in this case ANSA_TRANSL) and select the option Export main script. Automatically, a file called ANSA_TRANSL (without extension) is created in the same directory where the ANSA_TRANSL.bpr was saved. Edit the file to see the code inside:

As it seems all the source files were added in the main script using the #projectfile statement. As mentioned before, no include file was added in the main ‘script’. 9.8.5 Handling projects A project can be opened either from Project>Open project or if right click in project window and select the respective option. The user must select any xml project file from the File manager that opens. The xml structure is displayed in the Project window where the user can handle any script as it was explained before. A project can be also executed similarly as any other function (Section 9.3). Also, it can be compiled and debugged as any other individual script. However, keep in mind that an open project has compilation priority. This means that if a project is opened, then the Compile, Run, Run function, Debug and Debug function commands, will generate and run the project code and not the code of the current open file.

9.9 Debugging scripts Scripts can be run in two ways. First, the ‘normal’ run, executes the code directly. Second, is through the debugger which executes the code line by line. In the later case we can pause the execution of a script in order to investigate the status of variables. This is very useful in cases where a script function have logical errors which probably lead to strange results. There are also times that unidentified problematic areas of functions like endless loops or wrong input data result in an infinite execution. All these situations can be traced using the debugger of Script Editor. Usually, in such cases the first step is to identify the variables that produce the error. If there is no such clue, we select the most important of them. Next, we add them in the watch list which help us to inspect their history during the execution of the script. A variable can be added in the watch list if we right click on it and select the Add watch option.

BETA CAE Systems S.A.

page 98

ANSA v.13.x

Scripting Language

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, p is added in the watch list. This list can be displayed pressing the button or through the View>Watch window of the main menu.

This window displays also the variable name, the function where it belongs, its type (local or global) and the current value. Finally, we must define the lines where the execution of the script will be paused. After each stop we are able to identify in the watch list any change of the variable. Consequently, it is recommended the lines that are selected to be just before or after the variable definition. For letting the editor to distinguish these lines, breakpoints are inserted to them. Having the cursor on a line and pressing the button inserts a breakpoint. On the other hand pressing the button deletes a breakpoint. Whenever a breakpoint is inserted, the respective line is colored red.

For running the function in debug mode the button {Shift+F5} or Project>Debug.

must be pressed. Alternatively, we can press

Important Note: The name of the function must be "main" Suppose that you would like to trace any changes of matrix p. Insert a breakpoint in line 5 and open the watch window. Press to run in debug mode. The execution stops in line 5 and the current status of p is displayed in watch window. From now on every time you press the button or , the execution continues and stops in each line. Pressing anytime the button , the script runs without stop until the next breakpoint. In our example after the second stop the matrix p changes and now holds the first value which is 20.

BETA CAE Systems S.A.

page 99

ANSA v.13.x

Keep pressing

Scripting Language

or

until the execution is finished.

Important Note: When the execution stops over a breakpoint the line is colored blue. If the variable that we are looking for is not in the "main" function but in a sub function, the debugger cannot reach it unless we change the way that searches the code. This can be achieved through the buttons and . The first instructs the execution sequence to step into a sub function, while the second to step out of a sub function. Let’s see this with an example: Assume we are interested in watching the values of the variable k which is located in sub function foo. For this, we set a breakpoint in a line prior to foo call (line 6) and press . The execution stops in this line and from that point we press the button until we get inside foo.

We can return any time to the "main" function pressing

BETA CAE Systems S.A.

.

page 100

ANSA v.13.x

Scripting Language

APPENDIX Sample scripts In ANSA installation directory, under the path docs/scripts, there is a list of user defined scripts that can be served as examples for either a beginner or an expert user. These scripts can be loaded automatically if you move the file user_ANSA_TRANSL from the config directory into the current directory and rename it as ANSA_TRANSL. Additionally, for every function a button will be created under TOOLS>USER MENU. Some of the most important scripts that can be found within this directory are: Script Name AlphabetSorting

CheckContactsDyna CheckEmptySets CheckPlink

CombineSets CompareConnectionPoints

CompressRbe2 CompressRbodys OutputVpmFromPartManager DetectSingleTripleBounds

Filename2Pid

BETA CAE Systems S.A.

Description Renumbers the properties according to the alphabetical order of their names. In the input window that appears, the user must write the DECK, the type of property (For example PSHELL,PSOLID etc) and the starting id. The starting id must be out of the current range of all property ids. Reads the ‘messag’ file of DYNA solver and reports the results in a check window. Checks the sets of the database whether they are empty. Reads the "*msg" file exported from PAMCRASH and displays in the check window the warning messages regarding the PLINKs definitions. The user must select the "*msg" from the file manager that opens. Adds, subtracts or intersects sets into a target set. Compare the positions of current connection points with the ones that exist in a selected vip file. Geometric points are created and stored in 4 new ANSAPARTS indicating the results. The user must select a ‘vip’ file from the file manager and to define a tolerance. Compress the RBE2s that have free dependent nodes Compress the RBODYs that have free dependent nodes Creates an ‘xml vpm’ tree describing the already defined hierarchy of ANSA Part Manager. Detects elements that have single or triple bounds and stores them in 2 sets respectively. The functions works for 1st order elements. If a shell has single and triple bounds then it is stored in both sets. Note that elements with single or triple bounds are considered those who have a whole side that lies in such a bound and not those that have at least one of their nodes in this bound. Renames the only existing PID of the ansa database with the ansa filename and saves the file. The ansa files are located in a directory. The functions works for NASTRAN deck and PSHELL property

page 101

ANSA v.13.x

FindVisibleParts

IgesPerPart InputGEBsAndConnectors

MakeSkin

MergeInDir

BETA CAE Systems S.A.

Scripting Language

Finds visible parts. A part is considered visible even it has only one of its shells or faces visible. The entities are stored in a matrix. Return: The function returns a matrix with the elements (pointers) of visible parts Output an iges for each part Input Connectors and Generic Entities of all types simultaneously. The script will: - Resolve all dependencies of GEBs and CONNECTORs upon other GEBs and CONNECTORs - Create the properties (DEFINED=NO) and parts that are referenced in the "connectivity" and "Part1", "Part2" fields of GEBs and CONNECTORs respectively but probably do not exist in the database - Create all SETs that are referenced by GEBs in the "ResultsFromSet" search option, if they don't exist - Create all local coordinate systems that are referenced by GEBs and CONNECTORs in the "cord" field, if they don't exist - Notify the user in case GEBs or CONNECTORs with the same ids already exist in the database - The current deck during the input must support the generated entities - The xml files are produced through the "InputGEBsAndConnectors.c" and "OutputConnectorEntities.c" scripts. Tips: The user can read the xml files in an empty ANSA db, save it and then merge it in the assembly db with the options: -Properties ->Keep Old -Merge Sets By Name -> Yes -Merge Parts -> Yes Applies the skin function to all ansa files that are located in a user defined source directory, and outputs the files in a user defined output directory. If the skin function is applied correctly the name of the ansa file is changed to _done.ansa and if not to _not_done.ansa Merges files located in a specific directory and saves with the name "merged.ansa". The filenames must not have spaces.

page 102

ANSA v.13.x

OpenCatiaInANSA OutputActran OutputConnectors OutputGEs PartName2Pid

PartToPid

PedestrianWithIncludePam

PlinksToCwelds

PropsFromPart PropShellToSet

BETA CAE Systems S.A.

Scripting Language

Translates the selected Catia File and opens it in ANSA. The ansa file is saved in the current directory. This function must be used in Linux OS. Outputs in ACTRAN solver. Outputs connectors entities in XML format. Outputs all Generic Entities of selected type in XML format. Renames the user given type of property with the name of the ANSAPART. It is required the pids to be equal with the module ids and the desired deck to be activated. Creates a "PSHELL" property for each part of the database. The ids of the created "PSHELLS" start from a user value. The names of the properties are the names of the parts. Note that the script can work also in FE models. When running this function TOPO menu must be active. Reads the Points (target or contact or test) from a file, positions the headform to them and creates an PAMCRASH INCLUDE file for each point.The user is prompted to select the file containing the points The form of this file is : ID;X;Y;Z !!!! No empty line should exist in the points text file !!!! Details: The coordinate system should be defined with nodes (attached to the headform mesh) The arguments of the array are: Head model SET id, [Default value is 1000] Bonnet SET id, [Default value is 1001] The angle that you want as hit angle on the bonnet, [Default value is 30] The user must give the reference include name [Default "impactor.pc"] The include files are named as "Incshot*.pc". Switch CWELDS to PLINKS and the opposite. The script takes into account the 'RSEAR' values of PLINK for the realization of CWELDS and the "D" values of CWELDS for the realization of PLINKS. It keeps also the initial properties during the conversion. Finds the properties that the given part is using. The part must contain only geometry. Return: A matrix with PIDs Creates a set for each 'SHELL' property. The user must select the Deck, the type of property and must give the starting set id. The set takes the name of the property.

page 103

ANSA v.13.x

QualityReport RandomColorsPID RedConsGridsInSet RedConsShellsTriasInSet ReleaseConnections

SplitConnectionCurve

SampleBatchMesh

TakePictures

Scripting Language

Makes a report of violating shells according to the specified values. The user is prompt to create the log file through the file manager. Applies new random colors to all visible properties. Places the grids of red CONS into a set. The name of set is "Red Cons Grids". The model must be meshed. Place the shells and trias of red CONS in 2 sets. The names of sets are "Red Cons Shells" and "Red Cons Trias". The model must be meshed. Releases FE-representations of Connection Entities from their Connection Entity. The FErepresentations are added to a separate part in Parts Manager while the Connection Entities remain intact. Splits the selected curves from the original connection curves (Adhesive, Seamline, Spotweldline, Hemming). At the end, the created curves have the same characteristics as the original one, while they keep the original id in their comments. Reads from a directory the ansa_mpar and the ansa_qual files, creates a session, adds in the session all the ANSAPARTS of the database, runs the session and exports statistics in the same directory. The statistics file is exported in the format that is defined in ANSA.defaults. (Html, text, text csv). The ansa_mpar must be called "sample_parameters.ansa_mpar". The ansa_qual must be called "sample_quality.ansa_qual". Sets the 6 views of ANSA and takes from each one a snapshot. The pictures are saved in 'jpeg' format. The user is prompt to select the directory where the pictures will be saved. The entities must be visible.

Furthermore, under the docs/scripts/Windows directory, there are useful examples regarding the creation of user custom gui using the windows scripting library of functions.

BETA CAE Systems S.A.

page 104

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF