0% found this document useful (0 votes)
26 views

ANSA_Scripting_Python_Programming_Interface (1)

The document provides a comprehensive guide to the ANSA v.14.x Python Programming Interface, detailing its functionality for accessing ANSA core features, creating custom GUIs, and managing data. It includes an introduction to Python, data types, and various programming concepts, along with specific instructions for interacting with ANSA entities and executing scripts. Additionally, it covers specialized functions, automation, and GUI design, making it a valuable resource for developers working with ANSA.

Uploaded by

hicham IB
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

ANSA_Scripting_Python_Programming_Interface (1)

The document provides a comprehensive guide to the ANSA v.14.x Python Programming Interface, detailing its functionality for accessing ANSA core features, creating custom GUIs, and managing data. It includes an introduction to Python, data types, and various programming concepts, along with specific instructions for interacting with ANSA entities and executing scripts. Additionally, it covers specialized functions, automation, and GUI design, making it a valuable resource for developers working with ANSA.

Uploaded by

hicham IB
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 102

ANSA v.14.

x Python Programming Interface

BETA CAE Systems S.A. 1


ANSA v.14.x Python Programming Interface

Table of Contents
1. DESCRIPTION OF THE PROGRAMMING INTERFACE........................................................................5
1.1 Introduction.........................................................................................................................................5
1.2 The Python Programming Language................................................................................................5
1.3 Python Version...................................................................................................................................5
1.4 Python Documentation.......................................................................................................................5

2. SHORT INTRODUCTION TO PYTHON..................................................................................................5


2.1 Data Types...........................................................................................................................................5
2.1.1 Numbers.........................................................................................................................................5
2.1.2 Sequences Data Types..................................................................................................................6
2.1.3 The del Statement..........................................................................................................................6
2.1.4 The None Object............................................................................................................................7
2.2 Modules and Namespaces.................................................................................................................7
2.2.1 Module............................................................................................................................................7
2.2.2 Namespaces...................................................................................................................................7
2.3 Program Scope...................................................................................................................................7
2.4 if statements and branching..............................................................................................................8
2.4.1 The "if-else" blocks and the logical operators.................................................................................8
2.5 Loop statements.................................................................................................................................8
2.5.1 The for statement...........................................................................................................................8
2.5.2 The while statement.......................................................................................................................9
2.5.3 The continue, break and pass statements......................................................................................9
2.6 Handling Lists...................................................................................................................................10
2.6.1 Set data in a list............................................................................................................................10
2.6.2 Retrieve values from a list............................................................................................................10
2.6.3 Retrieve the length of a list...........................................................................................................10
2.7 Handling strings................................................................................................................................10
2.7.1 Adding strings...............................................................................................................................10
2.7.2 Handling strings as sequences.....................................................................................................11
2.8 Handling Dictionaries.......................................................................................................................11
2.8.1 Set keys and data in a Dictionary.................................................................................................11
2.8.2 Retrieve a key value.....................................................................................................................11
2.8.3 Delete a key..................................................................................................................................11
2.8.4 Iteration through the data in a Dictionary......................................................................................11
2.8.5 Check the existence of a key........................................................................................................12
2.8.6 Identify the number of keys in a dictionary:...................................................................................12
2.8.7 Destroy the dictionary and release memory.................................................................................12
2.9 User functions...................................................................................................................................12
2.9.1 Definition.......................................................................................................................................12
2.9.2 Returning data from functions.......................................................................................................13
2.9.3 Argument Matching Modes...........................................................................................................13
2.9.4 Help text and comments...............................................................................................................14
2.9.5 Global variables............................................................................................................................14
2.9.6 Program variables........................................................................................................................14
2.10 Handling Exceptions......................................................................................................................15
2.11 Object Oriented Programming Basics..........................................................................................15
2.12 Organizing scripts..........................................................................................................................17
2.12.1 Including files..............................................................................................................................17
2.12.2 Including files using the ImportCode Function............................................................................17

3. INTERACTING WITH ANSA.................................................................................................................18


3.1 General..............................................................................................................................................18
3.2 ANSA Modules and Namespaces....................................................................................................18
3.3 Handling data....................................................................................................................................19
3.3.1 The ANSA Entity...........................................................................................................................19
3.3.2 ANSA cards and entity types........................................................................................................20
3.4 Collecting entities.............................................................................................................................21
3.4.1 Collecting entities of the database................................................................................................21
3.4.2 Collecting entities from other entities............................................................................................22
3.4.3 Collecting visible entities...............................................................................................................23

BETA CAE Systems S.A. 2


ANSA v.14.x Python Programming Interface

3.4.4 Collecting the properties of entities...............................................................................................23


3.4.5 Collecting the materials of entities................................................................................................23
3.4.6 Getting single entities...................................................................................................................24
3.4.7 Getting single parts or groups through their ids............................................................................24
3.4.8 Collecting entities according to their name...................................................................................24
3.4.9 Collecting newly created/imported entities....................................................................................25
3.4.10 Picking entities from the screen..................................................................................................25
3.4.11 Select files or directories through File Manager..........................................................................25
3.5 Edit, Create and Delete Entities.......................................................................................................26
3.5.1 Get values from an entity using its Edit card.................................................................................26
3.5.2 Modifying the card's values..........................................................................................................27
3.5.3 Creating new entities....................................................................................................................27
3.5.4 Creating parts and groups............................................................................................................28
3.5.5 Creating connection entities.........................................................................................................28
3.5.6 Editing connection entities............................................................................................................29
3.5.7 Realizing connections...................................................................................................................29
3.5.8 Getting the entities of connections................................................................................................30
3.5.9 Deleting entities............................................................................................................................31
3.6 Subclassing the ANSA Entity..........................................................................................................31

4. SPECIALIZED FUNCTIONS.................................................................................................................33
4.1 General..............................................................................................................................................33
4.2 Creating Connectors and GEBs......................................................................................................33
4.3 Executing specialized script functions from Connection Manager..............................................35
4.3.1 Updating Connection's User Field................................................................................................35
4.3.2 User Thickness to Diameter Map.................................................................................................35
4.3.3 Updating RADIOSS spring PID....................................................................................................36
4.3.4 The post-realization script function...............................................................................................37
4.4 Includes Configurator.......................................................................................................................41
4.5 Results Mapper.................................................................................................................................42
4.6 Input - Output post functions..........................................................................................................43
4.6.1 Example of a Post Input Script.....................................................................................................43
4.6.2 Example of a Post Output Script...................................................................................................44

5. HANDLING SCRIPTS FROM GUI.........................................................................................................45


5.1 General..............................................................................................................................................45
5.2 Using script menu.............................................................................................................................45
5.2.1 Script menu functions...................................................................................................................46
5.3 Using the search engine..................................................................................................................47
5.3.1 Quick view of auxiliary built in functions........................................................................................47
5.3.2 Description of auxiliary built in functions.......................................................................................48
5.3.3 Loading scripts.............................................................................................................................49
5.3.4 Running scripts ............................................................................................................................49
5.4 Creation of user buttons .................................................................................................................50
5.5 Script plugins....................................................................................................................................51
5.5.1 Plugins characteristics..................................................................................................................51
5.5.2 Loading plugins in ANSA..............................................................................................................51

6. RUNNING SCRIPTS WITHOUT GUI.....................................................................................................52


6.1 Using the '-exec' flag........................................................................................................................52
6.1.1 Running scripts without input arguments......................................................................................52
6.1.2 Running scripts with input arguments...........................................................................................52

7. AUTOMATION THROUGH THE ANSA_TRANSL.PY FILE.................................................................54


7.1 Location of ANSA_TRANSL.py file..................................................................................................54
7.1.1 How does ANSA interacts with ANSA_TRANSL.py.....................................................................54
7.1.2 Form of ANSA_TRANSL.py..........................................................................................................54
7.1.3 Registers used for translation.......................................................................................................55
7.1.4 Excluded built in functions from CAD_Translate...........................................................................56
7.1.5 How to call system commands.....................................................................................................56
7.1.6 Importing neutral CAD files...........................................................................................................56
7.1.7 Executing functions without any user interaction (autoexec)........................................................61

8. INTERACTING WITH NATIVE CAD FILES..........................................................................................63

BETA CAE Systems S.A. 3


ANSA v.14.x Python Programming Interface

8.1 General..............................................................................................................................................63
8.2 Script commands related with Catia...............................................................................................63
8.2.1 Catia orientation check.................................................................................................................63
8.2.2 Extracting thickness from catia entities.........................................................................................63
8.2.3 Check geometry existence...........................................................................................................64
8.3 Reading the attributes of cad files (CATIA, NX, ProE)...................................................................64
8.4 Handling of catia properties............................................................................................................64
8.5 Writing in the cad log file.................................................................................................................65
8.5.1 The "Extra Options" field of Cad Translator..................................................................................65

9. BCGUI FUNCTIONS.............................................................................................................................66
9.1 What is BCGUI..................................................................................................................................66
9.2 BCGUI structure and philosophy....................................................................................................66
9.2.1 Widget classes or widgets............................................................................................................66
9.2.2 Layout classes or layouts.............................................................................................................71
9.2.3 Items.............................................................................................................................................71
9.2.4 General remarks...........................................................................................................................72
9.3 BCGUI examples...............................................................................................................................73
9.3.1 A simple BCWindow.....................................................................................................................73
9.3.2 Creating and using callback functions..........................................................................................73
9.3.3 Moving more data around.............................................................................................................74
9.3.4 Interacting with ANSA entities......................................................................................................75
9.3.5 Advanced BCGUI functionality.....................................................................................................81

10. SCRIPT EDITOR.................................................................................................................................86


10.1 Script Editor Layout........................................................................................................................86
10.2 Opening scripts...............................................................................................................................86
10.3 Running scripts...............................................................................................................................87
10.4 The immediate tab..........................................................................................................................87
10.5 Help area..........................................................................................................................................87
10.6 Compiled scripts.............................................................................................................................88
10.7 Making and importing snippets.....................................................................................................88
10.8 Creating projects............................................................................................................................89
10.8.1 Starting a new project.................................................................................................................89
10.8.2 Adding existing files to a project.................................................................................................90
10.8.3 Adding new files to a project.......................................................................................................91
10.8.4 Creating the ‘main’ script............................................................................................................92
10.8.5 Handling projects........................................................................................................................92
10.9 Debugging scripts..........................................................................................................................93

11. BCGUI DESIGNER..............................................................................................................................95


11.1 General............................................................................................................................................95
11.2 The Designer's interface................................................................................................................95
11.2.1 ToolBox......................................................................................................................................96
11.2.2 List of Constructed Items............................................................................................................97
11.2.3 Common Parameters (BC).........................................................................................................98
11.2.4 Parameters.................................................................................................................................99
11.2.5 CallBack Functions...................................................................................................................100
11.2.6 Help area..................................................................................................................................101
11.2.7 Source Code area....................................................................................................................101
11.2.8 Editing the source code............................................................................................................102

BETA CAE Systems S.A. 4


ANSA v.14.x Python Programming Interface

1. Description of the Programming Interface


1.1 Introduction
The ANSA Scripting Interface is an Application Programming Interface (API) that allows developers to
access the ANSA core functionality and data. The Scripting Interface allows for:
- creation and modification of the ANSA data/entities
- creation of custom GUI
- reading and writing custom file formats

The ANSA Scripting Interface is an extension of the Python Programming Language.

1.2 The Python Programming Language


Python is a general purpose, object-oriented, interpreted high-level programming language. It is known as
a clear and highly readable language with a large and comprehensive standard library. Python can be
utilized for both object-oriented and functional programming. It implements dynamic typing system and
automatic memory management.

1.3 Python Version


The Python version that is used by ANSA is Python v3.3.0.

1.4 Python Documentation


This guide is intended to provide a quick introduction of Python 3 and to describe the ANSA python
module. For more information about the capabilities of the Python programming language please refer to
the on-line language documentation provided by the Python Software Foundation (www.python.org). In
addition there are numerous books and resources that are available from third party vendors and
contributors.

2. Short Introduction to Python


2.1 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 Python built-in data types.

2.1.1 Numbers

Integer

The integer data type is used by variables that can only have whole numbers as values.

my_var = 10

BETA CAE Systems S.A. 5


ANSA v.14.x Python Programming Interface

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.

my_var = 112.5

Complex

c = 4+3j

Bool

b = True

2.1.2 Sequences Data Types


A sequence is an object containing a series of objects. There are three types of built in sequences in
Python. These are the list, tuple and string.

String

A string, is declared as 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 represented as lists of characters.

s = 'a string'
s = "a string"

List

A List is an ordered collection object type. A list can contain any type of an object such as integer, float
string, other lists, custom objects etc. Lists are mutable objects. Objects can be added, removed and
their order can be changed. The List object is similar to the matrix of the ANSA Scripting language.

my_list = [1, 2.3, 'world', [2, 3.7, 8.5]]


my_list.append('python')
print('result: ',my_list[2])

Tuple

A Tuple object is a simple group of objects. They are like lists but are immutable. They are constructed
once and no further change can be done to the object. No new objects can be added, nor can they be
removed or reordered.

my_tuple = (2.5, 7.9, 'python', (4.8, 'earth'))


print('result: ',my_tuple[3][1])

Dictionary

A Dictionary is an unordered collection. In a dictionary items are stored and fetched by a key instead of a
positional offset. Indexing a dictionary is a very fast and powerful operation. Dictionaries are the
equivalent to Maps of the ANSA Scripting Language.

my_dict = {'planet':'earth', 'world':3, 'test':10}


print('result: '+,my_dict['world'])

my_dict = {'planet':'earth', 'world':3, 'nest':{'test':10, 'entity':10}}


print('result: ',my_dict['nest']['entity'])

2.1.3 The del Statement

BETA CAE Systems S.A. 6


ANSA v.14.x Python Programming Interface

The del statement is used to delete references


del data[k]
del data[i:j]
del obj.attr
del variable

2.1.4 The None Object

Python provides a special object called None, which is always considered to be false. It is a special data
type and it serves as an empty placeholder.

2.2 Modules and Namespaces

2.2.1 Module
The module-based model in python is the core idea behind program architecture. Every file of Python
source code is a module. Other python files can access the items defined in a module by importing that
module. Import operations load another python file and allow access to that file's contents.

import math
import os

def main():
x = math.sqrt(9)
print('The square root is: '+str(x))
os.system('echo the square root of 9 is: ',x)

2.2.2 Namespaces
Each module file is a self-contained package of variables (Namespaces). One module file cannot see the
names of another module unless it is imported to that file, thus minimizing name collisions, even if
variables are spelled the same way.

2.3 Program Scope


In computer programming, a scope is the context within a computer program in which a variable name or
other identifier is valid and can be used, or within which a declaration has effect. Outside of the scope of a
variable name, the variable's value may still be stored, and may even be accessible in some way, but the
name does not refer to it; that is, the name is not bound to the variable's storage.

BETA CAE Systems S.A. 7


ANSA v.14.x Python Programming Interface

2.4 if statements and branching

2.4.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 elif and else:

if condition:
statement
elif condition:
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:

Operator Meaning
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
or Logical OR
and Logical AND
not Logical NOT

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

2.5.1 The for statement


The for statement allows the iteration over the elements of a sequence. for loops do not maintain any
explicit counter. The general form of the statement is:

for <item> in <sequence>:


do something to <item>

An example of the statement use is given below:

all_properties = ["PSHELL","PCOMP","PBAR","PBEAM","PELAS"]

for property in all_properties:


print(property)

the result is

PSHELL
PCOMP
PBAR
PBEAM
PELAS

BETA CAE Systems S.A. 8


ANSA v.14.x Python Programming Interface

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.

all_properties = {"PSHELL","PCOMP","PBAR","PBEAM","PELAS"};
length = len(all_properties)
for i in range(len):
property = all_properties[i]
print(property)

2.5.2 The while statement


The while statement introduces a conditional exit loop. The program executes the specified statements
repetitively for as long as the given condition remains true (i.e. not equal to 0). Its general form is:

while condition:
body-statement

If operators are to be used for the expression of the condition, these must be of logical relational type (see
section 2.4.1).

a = 0
while a<3:
print(a)
a += 1

the above result will be something like

0
1
2

2.5.3 The continue, break and pass statements


The continue and break statements can be used to redirect the execution order of a loop. The break
statement allows the termination of a loop regardless of the loop control condition. In other words it can
lead to an unconditional branching. A typical example is given below:

a = 0
while a<5:
print(a)
a += 1
if a == 3:
break

In this case the result would be:

0
1
2

The continue statement jumps back to the beginning of the loop’s block to begin the next iteration. Thus,
it omits a certain block of statements. A typical example is given below:

a = 0
while a<5:
a += 1
if a == 3:
continue
print(a)

In this case the result would be:

BETA CAE Systems S.A. 9


ANSA v.14.x Python Programming Interface

1
2
4

2.6 Handling Lists

2.6.1 Set data in a list


To add data into a list:

my_list = list()
my_list.append('hello')
my_list.append('world')

To specify all list members at once

m = [10, 7, 9]

List members can be even other lists. Thus, a definition like the following would form a 3x3 list:

my_list = [[10,7,9],
[5,2,17],
[6,12,55]]

my_list.remove(0) #Remove item from a list


my_list.insert(1, [2,5,7]) #Insert item in index

2.6.2 Retrieve values from a list


To retrieve a value of a specific member of a list, the user must provide the corresponding index operator:

val = my_list[0]

For the 3x3 list given above:

val = my_list[1][0]

will assign to val the value of 5.

2.6.3 Retrieve the length of a list


The function len returns the length of a matrix:

length = len(m)

In case of a 2 dimension list the function will return the number of rows. In order to get the number of
columns of a row, ask the length of a specific row, e.g

C = [[20,7,9],
[5,4,17]];

length = len(C[1])

In the above example, the number of columns for the second row will be 3.

2.7 Handling strings

2.7.1 Adding strings


Characters may be assigned to string variables, using statements similar to those of numeric types:

property = 'PSHELL'
mat_name = 'steel_105'

The '+' operator can be used to concatenate string data e.g.

BETA CAE Systems S.A. 10


ANSA v.14.x Python Programming Interface

property = 'PSHELL'
id = 'with id 1'
property_id = property + id

2.7.2 Handling strings as sequences


Strings can be treated as matrices and in this way any part of them can be isolated without the use of any
built in function. A string has a length equal to the number of characters that comprise it and each one
character holds an index.

str = 'Bumber_Front'

The above string has 12 characters where B has index 1, u has index 2……and t has index 12.
Any part of the string can be retrieved using the indices of the characters. Here are some examples:

val = str[0:6] #This will get the "Bumber"


val = str[7:12]#This will get the "Front"
val = str[7] #This will get the character "_"
val = str[5:] #This will get the "_Front"
val = str[:7] #This will get the "Bumber_"

Important Note: The length of a string can be found using the function len.

2.8 Handling Dictionaries

2.8.1 Set keys and data in a Dictionary


When a Dictionary is created and initialized, it is originally empty.

myDictionary = dict()

or

myDictionary = {}

To set some data to the dictionary:

myDictionary = {'Name':'aluminum', 'pid':19987}

Alternatively:

myDictionary['Name'] = 'aluminum'
myDictionary['pid'] = 19987

To retrieve a value of a specific key, the user must provide the corresponding key:

print(myDictionary['pid'])

2.8.2 Retrieve a key value

val = myDictionary['Name']
print(val)

2.8.3 Delete a key


A dictionary elements can be deleted using the del statement:

del myDictionary['Name']

2.8.4 Iteration through the data in a Dictionary


In order to iterate through a Dictionary:

for key, value in myDictionary.items():


print(key)
print(str(values))

BETA CAE Systems S.A. 11


ANSA v.14.x Python Programming Interface

2.8.5 Check the existence of a key


To check the existence of a key inside a dictionary, use:

if 'pid' in myDictionary:
print('OK')

2.8.6 Identify the number of keys in a dictionary:


To identify how many keys a dictionary contains:

length = len(myDictionary)

2.8.7 Destroy the dictionary and release memory


In order to delete a dictionary:

del myDictionary

2.9 User functions


User functions allow to group a set of operations into a compact unit that can be easily and repeatedly
accessed. The repetitive use of functions saves much time while reduces the chances of error. Each user
function is given a name, optionally uses some input parameters (arguments) and returns the results as
output parameters.
From now on, the term main will be used to denote the function which is called by the user to execute the
script.

2.9.1 Definition
User functions are defined using the def statement. This statement is followed by the function name. The
rest of the code must be idented. A typical function has the form:

def main(list of arguments if exist):


.......
Statement
.......

BETA CAE Systems S.A. 12


ANSA v.14.x Python Programming Interface

2.9.2 Returning data from functions


Since the target of each sub-function is to perform a certain task, there must be a way to notify the main
function that called it for the result of the procedure it performed.
The communication between the functions can be achieved through the return command. This command
can be used anywhere in the code and is followed by any data. A function that calls another function can
store the returned value in an output argument or even can ignore it. Functions that don’t return anything
are executed normally and may not use the return command. Equivalent, they can return a dummy
value.

Return value No return Return dummy value

def main(): def main(): def main():


a = 100 a = 100 a = 100
b = 50 b = 50 b = 50
res = substr(a, b) result = substr(a, b) result = substr(a, b)
print('Result:'+result) print(result) print(result)

def substr(a,b):
def substr(a, b): def substr(a, b): res = a-b
res = a-b res = a-b return 1
return res

2.9.3 Argument Matching Modes

Python provides additional techniques that alter the way arguments are passed to the called functions.
These are optional but allow the writing of code that supports very flexible calling patterns. The table
bellow describes these patterns.

Syntax Location Interpretation


func(value) Caller Normal arguments matched by position
func(name=value) Caller Keyword (named) arguments, matched by name
func(*name) Caller Pass all objects in name as individual positional arguments
func(**name) Caller Pass all key/values in name as individual keyword arguments
def func(name) Function Normal arguments matched by position
def func(name=value) Function Default argument value, if not passed in the call
def func(*name) Function Matches and collects positional arguments in a tuple
def func(**name) Function Matches and collects keyword arguments in a dictionary

Note: The named arguments pattern is widely supported in the ANSA module.

BETA CAE Systems S.A. 13


ANSA v.14.x Python Programming Interface

2.9.4 Help text and comments


The common practice has proven that even the most experienced programmer needs to keep some
comments in order for the code to be readable and understandable. In Python comments can be added
after the # sign. Comments between three pairs of quotes (“””Comment”””), under the function declaration,
define a python docstring (see python documentation for more information)

import ansa
from ansa import base
from ansa import constants

def my_fun():
“””Docstrings for function help “””
#Collect the parts
search_type = ('ANSAPART',)
parts = base.CollectEntities(constants.NASTRAN, None, search_type, True)
#Use each part as a container in order to collect its faces
search_type = ('FACE',)
faces = list()
for part in parts
container = [part] #The container must be in a matrix form
faces.append(base.CollectEntities(constants.NASTRAN,
container,earch_type,False))

2.9.5 Global variables


In contrast to local variables, global variables are valid throughout the program, so they can be accessed
and changed by any individual function of the program. Global variables must be declared prior to the
definition of any function (global section).

myInteger = 12
myFloat = 5.78 #myFloat and myInteger are now global for all functions

def main():
global myInteger
print('initial value: '+str(myInteger))
myInteger = 7
print('Final value: '+str(myInteger))

def fun():
global myInteger
sum = myInteger + 7
global myFloat
myFloat += 1.0

2.9.6 Program variables


However, the static variables cannot be used by another script, while they are lost every time the script is
unloaded. So, for storing and retrieving variables' data as long as the ANSA session is opened, the
functions BetaSetVariable and BetaGetVariable must be used. Any variables defined in this way are
considered as part of the program and thus they are accessible by any script. The BetaSetVariable
accepts bytes object. In order to generate a bytes object the pickle module needs to be used.

To set up program variables, follow the example below:


import pickle
import ansa
from ansa import base

def main():
var = 10
var_bo = pickle.dumps(var)
base.AnsaSetVariable('program_var1', var_bo)
m = [1, 10]
m_bo = pickle.dumps(m)
base.AnsaSetVariable('program_var2', m_bo)

To retrieve program variables:

BETA CAE Systems S.A. 14


ANSA v.14.x Python Programming Interface

def main():
val1 = base.AnsaGetVariable('program_var1')
val1_ = pickle.loads(val1)
print('val1: '+val1_)
val2 = base.AnsaGetVariable('program_var2')
val2_ = pickle.loads(val2)
for entry in val2_:
print("val2: "+entry)

Program variables' values can be cleared using the function AnsaClearVariable.

2.10 Handling Exceptions

Exception handling is the process of responding to the occurrence, during computation, of exceptions –
anomalous or exceptional situations requiring special processing – often changing the normal flow of
program execution. It is provided by specialized programming language constructs or computer hardware
mechanisms.

In python exceptions are handled with try and except statements. Any code that runs inside the try block
and raises an exception, the exception can be handled in the catch block.

try:
res = x / y
except DivisionByZero:
print('division by zero')
else:
print('result: '+str(res))

try:
val = myDict['Name']
except KeyError:
print('Key Name does not exist')
val = 0

2.11 Object Oriented Programming Basics


In object oriented programming, an object is an instance of a Class. A class is a construct that
encapsulates state and behaviour. By state we mean the class's data (attributes/variables). By behaviour
we mean the class's methods (functions). An example of a class is show below:

import math

class Point:
"""A class that stores the x,y,z coordinates of a a point,
with a method that calculates the distance from the origin and
a method that prints the description of the class"""
def __init__(self, x_coord, y_coord, z_coord):
"""This is the constructor of the class"""
self.x = x_coord
self.y = y_coord
self.z = z_coord

def distFromOrigin(self):
"""Method that calculates the distancefrom the origin"""
dist = math.sqrt(self.x**2 + self.y**2 + self.z**2)
return dist

def __repr__(self):
return 'A point with X: '+str(self.x)+' Y: '+str(self.y)+' Z'+ str(self.x)

BETA CAE Systems S.A. 15


ANSA v.14.x Python Programming Interface

def main():
myPoint = Point(100.57, 786.46, 436.89) #creation of class instance myPoint

print(myPoint.x) #access the value of attribute x

myPoint.x = 120.74 #assign new value

distance = myPoint.distFromOrigin()
print('The distance from the origin is: '+str(distance))

#In order to print the description of the object


print(myPoint) #This will print the return of the __repr__

BETA CAE Systems S.A. 16


ANSA v.14.x Python Programming Interface

2.12 Organizing scripts

2.12.1 Including files


In python modules are imported with the import statement. At the top of your python file import the desired
modules like in the example shown below

import math
import sys
import ansa

The import statement cannot take a full path. It looks directly into the python home directory. If a module
that needs to be imported resides outside the python home the following method needs to be called.

import sys
sys.path.append()

An example of this:

import sys
sys.path.append('/home/myHome/myLibrary.py')
import myLibrary

Note: Please refer to the official Python 3 documentation for more information on modules management

2.12.2 Including files using the ImportCode Function

The ansa.ImportCode(filepath) function in the ANSA extension of Python allows to easily import Python
modules. It imports both compiled and ascii modules

An example is:
import ansa
ansa.ImportCode('/home/myHome/myLibrary.pyb')

def main():
myLibray.myFunction()

BETA CAE Systems S.A. 17


ANSA v.14.x Python Programming Interface

3. Interacting with ANSA


3.1 General
The basic idea behind the scripting language is to automate many repetitive and tedious procedures with
the minimum user interaction or even to perform specific tasks that are not covered by the standard
ANSA commands. Some of the tasks that can be performed within scripting language are the following:

- Reading and writing ASCII files.


- Extracting any type of information from an already defined base.
- Selections that take into account any criteria.
- Assignment of attributes to parts, materials, properties etc.
- Use of system commands.
- Building and executing batch mesh sessions.
- Creating a model hierarchy.
- Creating user defined windows and buttons.
- Co-operating with the MORPH tool for controlling an optimization loop.
- Use of session commands
- Running automatically (after launching ANSA) a series of functions.
- Can be called anytime without reopening a file and as many times as the user wants.
- Communication with the interface (File Manager functions, Pick functions).

All these tasks that can affect the model definition, are controlled through a series of functions that
interact with the ANSA interface. Before proceeding to the explanation of individual functions, it is
important to emphasize in two basic topics: the treatment of ANSA elements and the meaning of ANSA
entities and cards.

3.2 ANSA Modules and Namespaces


The ANSA modules are:

Module Description
ansa.batchmesh Batchmesh related functions
ansa.guitk BCGUI functions
ansa.cad CAD and translator functions
ansa.base Topo, deck, visibility, element manipulation functions
ansa.connections Connections handling and realization functions
Ansa.constants A collection of all the ANSA constants and reserved methods
ansa.utils General functions
ansa.morph Morph functions
ansa.calc Mathematical fanctions
ansa.session ANSA session commands
ansa.taskmanager Task Manager functionality

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


ANSA v.14.x Python Programming Interface

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, FLUENT,
FLUENT2D, STAR, UH3D, CFDPP, OPENFOAM, PERMAS, MOLDEX3D,
RADTHERM, SESTRA, THESEUS

Constants are accessed through the constants module. An example:

ansa.constants.NASTRAN

Note: If zero value is given instead of the deck constant, then the current deck will be considered.

There are additional constants like the app_version and app_version_int.

Constants Description
ansa.constants.app_version returns the version as a string
ansa.constants.app_version_int returns the ANSA version as an integer
ansa.constants.app_home_dir The system directory used for configuration files by the
application
ansa.constants. app_root_dir It returns the application's root directory

3.3 Handling data

3.3.1 The ANSA Entity


In ANSA module, an ANSA entity is an object of type ansa.base.Entity. Such objects:
- are returned by functions
- can be created

They have special read only attributes:

_id
returns the ANSA Entity id

_name
returns the ANSA Entity name

and methods:

_isDefunct()
returns true if the referenced ANSA entity has been destroyed

_ansaType(deck)
returns the ANSA type of entity in the specified deck

An example of getting reference to the entities is shown below:


n = ansa.base.CreateEntity(ansa.constants.ABAQUS, "NODE")
nn = ansa.base.Entity(ansa.constants.ABAQUS, n._id, "NODE")
if n == nn:
print("OK: Objects are equal")
else:
print("ERROR")

Checking if the object is defunct:

BETA CAE Systems S.A. 19


ANSA v.14.x Python Programming Interface

l = []
l.append(shell)

n = ansa.base.Entity(ansa.constants.ABAQUS, 1, "NODE")

# the following call with delete the shell


ansa.base.DeleteEntity(n, force=True)

#now the object in l[0] has been deleted.


shell = l[0]
if shell._isDefunct():
print("This shell has left us")

3.3.2 ANSA cards and entity types


Most of the entities in ANSA have a card that includes all necessary information regarding them. The type
of each entity is displayed on the card window header, enclosed in brackets. This entity type is very
important since this is the keyword that must be used in order to have access in the card and its contents.
For example, a NASTRAN 'shell' has a card with type SHELL and this is the keyword that must be used
for dealing with this kind of entity. The labels of card fields are also important since they must be used in
order to get their values.

The types of entities that either don't have entity cards or the rule described before doesn’t cover them
are the following:

Entity type Description


Ansa part ANSAPART
Ansa group ANSAGROUP
Batch mesh group BATCH_MESH_SESSION_GROUP
Layer scenario BATCH_MESH_LAYERS_SCENARIO
Volume scenario BATCH_MESH_VOLUME_SCENARIO
Wrap scenario BATCH_MESH_WRAP_SCENARIO
Batch mesh session BATCH_MESH_SESSION
Layer session BATCH_MESH_LAYERS_SESSION
Volume session BATCH_MESH_VOLUME_SESSION
Wrap session BATCH_MESH_WRAP_SESSION
Solid facets SOLIDFACET
Continuum shell facets TSHELLFACET

Important Note: The deck curves use a variety of keywords that can be found under the help text of the
built in function CreateLoadCurve.

BETA CAE Systems S.A. 20


ANSA v.14.x Python Programming Interface

3.4 Collecting entities


The most significant functions for collecting entities are displayed in the following table:

Function Description
CollectEntities Collect entities massively
GetEntity Get a single entity
GetPartFromModuleId Get PARTs or GROUPs
NameToEnts Get entities from their name
CollectNewModelEntities Object that monitors and reports new model entity creation
TypesInCategory Collect types of entities that exist in mode

The types of entities that can be collected by using these functions are:

ELEMENTs (SHELLs, SOLIDs, BEAMs, etc)


COORDINATE SYSTEMs
CONSTRAINTs
LOADs
INITIAL CONDITIONs – BOUNDARY CONDITIONS
BOXes
SETs
GRIDs
ANSAPARTs - ANSAGROUPs
CONNECTIONs (all types)
GEOMETRIC ENTITIES (POINTS, CURVES, FACES, CONS)
PROPERTIEs
MATERIALs
INCLUDEs
CONNECTORs
GEBs
MORPHING ENTITIES

Important Note 1: If zero value is given instead of the deck name, then the current deck will be taken into
account.
Important Note 2: The MORPH statement must be used for handling entities coming from morph menu.

3.4.1 Collecting entities of the database


For collecting massively a type of entity (e.g. SHELL) the appropriate function is the CollectEntities. One
of the advantages of this function is that it can be used for finding entities that are used by other entities
while it is the only function that can collect visible entities. Its syntax is very flexible and can accept either
matrices or single elements (pointers). A variable number of input arguments can be specified as well.
Let's see the capabilities of the CollectEntities function with some examples.
import ansa
from ansa import base
from ansa import constants

def main():
#Define into a matrix the keywords of entities that you want to collect.
#These keywords are taken from the title of their cards
search_type = ['PSHELL', 'PSOLID']
ents = base.CollectEntities(constants.NASTRAN,None,search_type,True)

In this approach the input arguments are matrices. The second argument indicates the search domain
and in case the user needs to collect entities from the whole database it must be zero. The output
argument is a matrix that contains the elements (pointers) of PSHELLs and PSOLIDs of the database.
The definition of the deck must be compatible with the entities that are going to be collected. An approach
like the following is not accepted:search_type = ('PSHELL","PSOLID')
ents = base.CollectEntities(constants.PAMCRASH,None,search_type,False)

In this case the equivalent keywords for PAMCRASH deck are PART_SHELL and PART_SOLID.

BETA CAE Systems S.A. 21


ANSA v.14.x Python Programming Interface

For collecting all the properties or materials of the database a string indicating the entity category must be
used:

def main():
all_props = base.CollectEntities(constants.NASTRAN,None,'__PROPERTIES__')
all_mats = base.CollectEntities(constants.NASTRAN,None,'__MATERIALS__')

3.4.2 Collecting entities from other entities


In this case the GRIDs that are used from SHELLs must be collected. In scripting language terminology,
the matrix of shells is considered as a container and must be given as a second argument in order to
prompt the function to search only into the collected shells. A container can be either a matrix or a single
element (pointer).

def main():
#Collect first the shells of the whole database
search_type = ('SHELL',)
shells = CollectEntities(NASTRAN,0,"SHELL")
#Collect the grids of the shells
search_grid = ('GRID',)
grids = base.CollectEntities(constants.NASTRAN,shells,search_grid)

Alternatively, the entity's keyword could have been used instead (as string).

def main():
#Collect first the shells of the whole database
shells = base.CollectEntities(constants.NASTRAN,None,"SHELL")
#Collect the grids of the shells
grids = base.CollectEntities(constants.NASTRAN,shells,"GRID")

The third argument that defines the type of entities, can be also set to zero. This setting can be used for
collecting all the entities that are included into a superior entity. This makes sense in SETs, PARTs, or
Connections.

def main():
#Collect the sets of the database
sets = base.CollectEntities(constants.NASTRAN,0,"SET")
#Collect all the entities that belong to these sets
ents = CollectEntities(cpnstatns.NASTRAN,sets,False)

Attention must be given in the meaning of containers. Many entities in ANSA are considered as
containers since they include other entities inside them e.g. SHELLs include GRIDs. These containers
are classified according to their level. For instance, SHELLs are of higher level than GRIDs while
PSHELLs are of higher level than SHELLs and GRIDs. So, for searching entities inside a container the
CollectEntities must recursively search until the lower level. This is very clear in the following examples.

def main():
pshells = base.CollectEntities(constants.NASTRAN,None,'PSHELL',recursive=False)
shells = CollectEntities(constants.NASTRAN,pshells,'SHELL',False)
print(len(shells))

The last argument of CollectEntities is zero since SHELLs is only one level under PSHELLs.
Another equivalent syntax could be:

shells = base.CollectEntities(constants.NASTRAN,pshells,'SHELL',recursive=False)

For finding directly the GRIDs that are used by PSHELLs, the last argument must be set to 1 in order to
search recursively until the lower level.

def main():
pshells = base.CollectEntities(constants.NASTRAN,None,'PSHELL',recursive=False)
grids = base.CollectEntities(NASTRAN,pshells,"GRID",recursive=True)
print(len(grids))

BETA CAE Systems S.A. 22


ANSA v.14.x Python Programming Interface

A matrix that contains entities of specific type cannot be used as container for collecting entities of the
same type. For example, a matrix that contains elements (pointers) of SHELLs and SOLIDs cannot be
used as container for collecting SHELLs or SOLIDs but it can be used only for GRIDs which is a lower
level entity type.
Important Note: The matrix of elements (pointers) that is returned is not sorted according to the ids of the
entities that they reference.

3.4.3 Collecting visible entities


CollectEntities is the only script function capable of collecting visible entities.
def main():
shells = base.CollectEntities(constants.NASTRAN,0,'SHELL',filter_visible=True)
print(len(shells))

Important Note: Visible are considered all entities that their visibility is controlled through the Database
Browser, thus it is impossible to collect visible entities like PROPERTIES or MATERIALS.

3.4.4 Collecting the properties of entities


For getting the properties of given entities e.g. the properties of visible shells, the parameter
'prop_from_entities' must be used:

def main():
shells = base.CollectEntities(constants.NASTRAN,0,'SHELL',filter_visible=True)

props=base.CollectEntities(constants.NASTRAN,shells,'PSHELL',prop_from_entities=True)
len = len(props)
for i in range(len):
ret = base.GetEntityCardValues(constants.NASTRAN,props[i],('PID',))
print('PID: ',ret['PID'])

3.4.5 Collecting the materials of entities


For getting the materials of given entities e.g. the materials or parts, the parameter 'mat_from_entities'
must be used:

def main():
part = base.GetPartFromModuleId('1')
mats = base.CollectEntities(constantsNASTRAN,part,'MAT1',mat_from_entities=True)

If the type of material is not known then the “__MATERIALS__” can be used instead of “MAT1”

mats=base.CollectEntities(constants.NASTRAN,part,"__MATERIALS__",mat_from_entities=1)C
ollecting the entity types of a deck
As shown in paragraphs 2.3.2, 2.3.3, 2.3.4, the CollectEntities function needs to know what types of
entities to search for. In simple cases where specific types are needed, the user just have to open the
respective card and see the entity's keyword. For more complicated cases where the searching entities
are not well known or they are too many to open their cards one by one, the use of the function
TypesInCategory is necessary. The function uses two input arguments which are the name of the deck
and a string that defines the searching area. The output is a matrix with all supported types. The string
that denotes the searching area can get the following forms:

Category Description
"__MATERIALS__" Gets all available material types of the specified deck
"__PROPERTIES__" Gets all available property types of the specified deck
"__ELEMENTS__" Gets all available element types of the specified deck
"__VISIBLE__" Gets all visible element types of the specified deck, that their visibility can be
controlled through the Database Browser
"__ALL_ENTITIES__" Gets all supported entities of the specified deck
"__CONNECTIONS__" Gets all supported weld types

BETA CAE Systems S.A. 23


ANSA v.14.x Python Programming Interface

A useful example could be the collection of all connections types of the database in order to be realized.

def RealizeAllConnections():
#Get all connection types
connection_types = base.TypesInCategory(constants.LSDYNA,'__CONNECTIONS__')
connections = base.CollectEntities(constants.LSDYNA,None,connection_types)
base.RealizeConnections(connections,len(connections))

3.4.6 Getting single entities


For getting a single element (pointer) of an entity, the functions GetEntity, GetFirstEnity, GetNextEntity
are available.
The use of GetEntity presupposes that the type and the id of the entity is known. It returns the element
(pointer) of the entity.

def GetSingleEntity():
group = base.GetEntity(constants.PAMCRASH,'GROUP',100)

In this example the element (pointer) of the Pam-Crash GROUP with id 100 is returned.
The type is not necessarily needed if the function is used for getting properties or materials. In this case,
instead of the entity type, the keywords "__MATERIALS__" and "__PROPERTIES__" can be used.

def main():
prop = base.GetEntity(constants.NASTRAN,'__PROPERTIES__',10)
mat = base.GetEntity(constants.NASTRAN,'__MATERIALS__',10)

Important Note: The GetEntity function cannot collect ANSAPARTS and ANSAGROUPS of PART
MANAGER through their Module Id.

3.4.7 Getting single parts or groups through their ids


For getting single ANSAPARTs and ANSAGROUPs that have known ids (Module Ids) the
GetPartFromModuleId can be used.
Suppose that the elements (pointers) of the PART with module id "1A" and of the GROUP with module id
"100" must be taken.

def main():
part = base.GetPartFromModuleId("1A")
group = base.GetPartFromModuleId("100")

3.4.8 Collecting entities according to their name


Apart from using ids, names can be also used as searching pattern for collecting any type of entities. The
function for this is the Name2Ents. It takes just one argument while it accepts Perl regular expressions. It
returns a matrix with the elements (pointers) of all entities whose name fulfills the searching filter. This
function is used mostly in combination with the GetEntityType in order to distinguish the type of entities.
Suppose that the whole database must be searched in order to collect and store any PSHELLs and
PSOLIDs whose name starts with "Default".

def main():
#Collect entities that satisfy the searching pattern
ents = base.Name2Ents("^Default.*")
pshells = list()
psolids = list()
for ent in ents:
type = base.GetEntityType(ent)
#Distinguish the type of entity
if type == "PSHELL":
pshells.append(ent)
if type == "PSOLID":
psolids.append(ent)

If no entities are found the function returns nothing. This case can be identified using the "!" operator.

ents = base.Name2Ents("^Default.*")
if not ents:
print('No entities were found')

BETA CAE Systems S.A. 24


ANSA v.14.x Python Programming Interface

3.4.9 Collecting newly created/imported entities


Actions like importing files, merging databases or reading connection files are very common during the
execution of scripts. In any case, they affect significantly the process since the amount of entities in the
current database is increased and thus it may needed to know exactly which are the new entities. The
CollectNewModelEntities must be used in order to recognize all the changes of the base. The example
below demonstrates the use of the object.
import ansa
from ansa import base

def main():
collector = base.CollectNewModelEntities()
n = base.CreateEntity(ansa.constants.ABAQUS, 'NODE')
new_entities = collector.report()
del collector
print(len(new_entities))

For collecting only specific types of entities, the CollectNewModelEntities must be initialized with the
parameter “filter_types” followed by a matrix containing the entity types to be monitored:

def main():

ents = ("SHELL_SECTION","SHELL")
container = base.CollectNewModelEntitiesStart(constants.ABAQUS,filter_types=pshell)
base.InputAbaqus("./"+abaqus_model_name, "nooffset", "nooffset", "nooffset",
"nooffset","", "", "", "", "", "on")
connections.ReadConnections("XML","/home/work/connections.xml")
new_entities = container.Report()
del container
for new_entity in new_entities:
print(base.GetEntityType(constants.ABAQUS, new_entity))

3.4.10 Picking entities from the screen


The user is able to pick one or more entities from the screen using the command PickEntities. The
function must be declared with the deck and a matrix containing the entity types. When the function is
executed, ANSA highlights on the screen only the defined entities and waits the user to confirm the
selections. After the confirmation the execution of the script continues normally. The function returns a
matrix having the elements (pointers) of the selected entities.

def main():
types_to_pick = ('SHELL','SOLID')
ents = base.PickEntities(constants.NASTRAN,types_to_pick)
print(len(ents))

3.4.11 Select files or directories through File Manager


Scripting language interacts directly with the File Manager through the commands SelectOpenDir,
SelectSaveDir, SelectOpenFile, SelectSaveFile, SelectOpenFileIn, SelectSaveFileIn. These functions
open the File Manager and allow the selection or creation of files and directories. This is an elegant way
to use file and directory paths in user scripts, since it enables the interactive definition of script
parameters. The functions that deal with files return a matrix containing strings that represent the full path
to the selected files, while those for directories return a string indicating the full path to the folder.

Import ansa
from ansa import utils

def Selection():
print('Select the file for reading')
read_file = utils.SelectOpenFile(0, 'csv files (*.csv)')
#The matrix 'read_file' contains only one entry since the
#the first argument of 'SelectOpenFile' was 0
print('The file that was selected is: '+read_file[0])
print('Select the log file for writing the error messages')
save_file = utils.SelectSaveFile()
print('The file that was selected for writing errors is: '+save_file)

BETA CAE Systems S.A. 25


ANSA v.14.x Python Programming Interface

print('Select the directory where the ANSA files are located')


dir = utils.SelectOpenDir('')
print('The selected directory is: '+dir)

If nothing is selected it can be identified using the ! operator.

read_file = utils.SelectOpenFile(0, 'csv files (*.csv)')


if not read_file:
print('No file was selected')
or

dir = utils.SelectOpenDir('')
if not dir:
print('No directory was selected')

3.5 Edit, Create and Delete Entities


Once the entities have been collected, next step is to edit, modify or delete some of them. The functions
that are used very often for this purpose are:

Function Description
GetEntityCardValues Get values from a card
SetEntityCardValues Set values to a card
CreateEntity Creates a new entity
CreateConnectionPoint Creates a connection point
CreateConnectionLine Create a connection line
CreateConnectionFace Create a connection face
RealizeConnections Realize connections
DeleteEntity Delete an entity
NewPart Creates new parts
NewGroup Creates new groups

3.5.1 Get values from an entity using its Edit card


The only function that enables the access into the fields of an edit card without changing the contents , is
the GetEntityCardValues. It always follows functions that had collected a number of entities in a prior
step and its arguments are pairs of labels – values. These labels are the keywords of the fields as they
appear in the edit card (see section 3.3.2). The definition of the deck and element are mandatory. The
following example demonstrates how to get the values of the name, thickness, property id and material id
of all the SECTION_SHELL cards of LSDYNA deck:

import ansa
from ansa import base
from ansa import constants

BETA CAE Systems S.A. 26


ANSA v.14.x Python Programming Interface

def GetValues():
props = base.CollectEntities(LSDYNA,None,'SECTION_SHELL')
#Initialize counters
names = list()
thickness = list()
pids = list()
mids = list()

for prop in props:


vals=base.GetEntityCardValues(constants.LSDYNA,prop,('Name','PID','MID','T1'))
names.append(vals['Name'])
thickness.append(vals['T1'])
pids.append(vals['PID'])
mids.append(vals['MID'])

.....
statement

It is obvious that the user must be familiar with the labels of each edit card since they must be written
exactly as they appear in the cards. The output value of the function is a dictionary with keys the
requested fields and values the corresponding values. If an error occurs the return of the particular field
will be None

To avoid opening and closing cards only for seeing the names of the labels, three global label – keywords
can be used. These keywords allow the extraction of the entity's id, property and type without knowing the
name of the respective labels. Their syntax is the following:

__id__ for entity's ID


__type__ for entity's ANSA type
__prop__ for entity's property id
For example, the id and the property of a shell can be taken as following:

status = base.GetEntityCardValues(constants.LSDYNA,prop,('__id__','__prop__'))
For getting values from a card different than the one that is currently used, the redirection symbol '-> ' can
be used. A typical example is to get the material name while the property card is accessed.
def main():
pshell = base.GetEntity(constants.NASTRAN,'PSHELL',100)
ret = base.GetEntityCardValues(NASTRAN,pshell,('MID1->Name',))
print(ret['MID1->Name'])

3.5.2 Modifying the card's values


The contents of a card can be modified with the SetEntityCardValues function, which works similarly to
the GetEntityCardValues. Again, a pair of labels – values must be declared. In the following example the
id and thickness of a specific property will be changed.

def SetValues():
#Get the PART_SHELL property with id 10
prop = base.GetEntity(constants.PAMCRASH,'PART_SHELL',10)
#Set the new values for id and thickness.
base.SetEntityCardValues(constants.PAMCRASH,prop,{'IDPRT':1000,'h':1.75})

If a keyword is given wrong, the function will not work even if all the other keywords had been defined
correctly. In this case the function will return the number of wrong occurrences.

status = base.SetEntityCardValues(constants.PAMCRASH,prop,{'IDPRT':1000,'h':1.75})

Although the 'IDPRT' is correct, the function will not work because of the 'h1' label and therefore will
return 'status=1'.

Important Note: The global labels ( __id__ ,__prop__ ,__type__ ) are also valid.

3.5.3 Creating new entities


Scripting language can also be used to create new entities like nodes, properties, materials etc. The
function that can be used for this purpose is the CreateEntity. It is necessary to declare the entity type

BETA CAE Systems S.A. 27


ANSA v.14.x Python Programming Interface

keyword (see section 3.3.2) and pairs of labels – values. It returns the reference of the newly created
entity.

def CreateGrid():

vals = {'NID':100,'X1':3.5,'X2':10.8,'X3':246.7}
base.CreateEntity(constants.NASTRAN,"GRID",vals)

During the creation of an entity, all the fields that are necessary for its definition but were not specified by
the user (e.g. the id) are automatically filled by ANSA.

Important Note: Not all entities of ANSA can be created with the CreateEntity.

3.5.4 Creating parts and groups


For creating ANSA parts and ANSA groups the functions NewPart and NewGroup must be used. Both
accept a name and optionally an id and return the element (pointer) of the newly created part/group.

def main():
#Create a part with name 'door' and id 10
part = base.NewPart('door','10')
#Create a group with name 'side' and without id
group = base.NewGroup('side','')

3.5.5 Creating connection entities


For the creation of connection entities (points, lines, faces) the functions CreateConnectionPoint,
CreateConnectionLine and CreateConnectionFace can be used. Except from the definition of the type
and id, the rest information that is needed to successfully define a connection entity, like the position of
the point and the parts that will be connected, must be given in a matrix form. Also, the id of the
connection can be given explicitly from the user or can be defined from ANSA by giving a zero as second
argument. The function returns the element (pointer) of the created connection entity in order to be used
later in the realization function. In the example that follows a spotweld point and a adhesive line will be
created:

import ansa
from ansa import connections
from ansa import base
from ansa import constants

def CreateCnctEnts():
#create a spotweld point of ID 122 at (2.3, 3.0, -1.0)
xyz = (2.3, 3.0, -1.0)

#part ids that will be connected


part_ids_point = (1, 'bp_416', 4)

cnctn_p=connections.CreateConnectionPoint('SpotweldPoint_Type',122,xyz=3,
part_ids_point=3)
#create an adhesive line of arbitrary ID
curves = (base.GetEntity(constants.NASTRAN, 'CURVE',15),))
#part ids that will be connected
part_ids_curve = (2,3)
cnctn_c=connections.CreateConnectionLine('AdhesiveLine_Type",0,curves,1,
part_ids_curve=2)
base.SetEntityCardValues(constants.NASTRAN, cnctn_c, {'W':1})

As noticed, the length of each matrix must follow the matrix itself, e.g.

xyz, 3
part_ids_point, 3
curves, 1
part_ids_curve, 2

Attention must be given in the first argument of all three functions since this string indicates the type of the
entity that will be created. The syntax of it can be found in the title of each connection card.

BETA CAE Systems S.A. 28


ANSA v.14.x Python Programming Interface

3.5.6 Editing connection entities


The basic information that follow a connection entity like its ID, or the ids and pids of connected parts etc
can be exported or edited through the GetEntityCardValues and SetEntityCardValues.

Connections = base.CollectEntities(constants.NASTRAN,None,'SpotweldPoint_Type',
recursive=False)
for connection in connections:
vals = ('ID','X','Y','Z','P1','P2','P3','P4')
ret= base.GetEntityCardvalues(NASTRAN,connection,vals)
print("ID "+str(ret['ID'])+" x:"+str(ret['X']))

...

or

connections = base.CollectEntities(constants.NASTRAN,None,'AdhesiveLine_Type',
recursive=False)
for connection in connections:
base.SetEntityCardvalues(constants.NASTRAN,connection,{'W':1})

3.5.7 Realizing connections


After creating the connection entities, the user have to realize them using the functions
RealizeConnection (for one entity) or RealizeConnections (for any number of entities). All the
representation characteristics that appear in the GUI are fully supported within these functions using a
specific name convention that is taken from ANSA.defaults. The number of input arguments is variable
and whatever is not defined takes a default value from ANSA.defaults. As an example, the strings that
can be used for spotweld representations are:

# Default Page for Spotweld Points


# format : RBE2|RBAR|CBAR|CBEAM|CELAS2|RBE2-CELAS1-RBE2|
# PASTED NODES|CBUSH|DYNA SPOT WELD|PAM SPOT WELD|
# NASTRAN CWELD|PAM PLINK|RBE3-HEXA-RBE3|AUTO SP2|
# RBE3-CBUSH-RBE3|SPIDER|RADIOSS WELD|
# ABAQUS FASTENER|SPIDER2|RBE3-CELAS1-RBE3|
# RBE3-CBAR-RBE3|RBE3-CBEAM-RBE3|PERMAS SPOTWELD
# SpotweldPoint_Type = RBE2

while the strings for individual representation settings are:

# Connection Manager Values


# SpotweldPoint_SPIDER_SearchDist = 5.000000
# SpotweldPoint_SPIDER_RBE2_PinFlags = 123456
# SpotweldPoint_SPIDER_ProjectToPerim = y
# SpotweldPoint_SPIDER_PointsAroundHole = 8
# SpotweldPoint_SPIDER_ParallelToPerim = y
# SpotweldPoint_SPIDER_PBAR_ID =
# SpotweldPoint_SPIDER_KeepSamePID = n
# SpotweldPoint_SPIDER_ForceZeroGap = n
# SpotweldPoint_SPIDER_DoNotMove = y
# SpotweldPoint_SPIDER_DoNotCreateCoord = n
# SpotweldPoint_SPIDER_DistanceFromPerimeter = 3.000000
# SpotweldPoint_SPIDER_DiSize_Index = 1
# SpotweldPoint_SPIDER_DiSize = 3.000000
# SpotweldPoint_SPIDER_CreateRBE2 = y
# SpotweldPoint_SPIDER_CBAR_PinFlags = 0
# SpotweldPoint_SPIDER2_Zone2_Index = 2
# SpotweldPoint_SPIDER2_Zone2 = 0.000000
# SpotweldPoint_SPIDER2_Zone1_Index = 2
# SpotweldPoint_SPIDER2_Zone1 = 0.250000
# SpotweldPoint_SPIDER2_SearchDist = 5.000000
# SpotweldPoint_SPIDER2_RBE2PinFlags = 1235
# SpotweldPoint_SPIDER2_PointsAroundHole = 8
# SpotweldPoint_SPIDER2_ParallelZones = n

BETA CAE Systems S.A. 29


ANSA v.14.x Python Programming Interface

# SpotweldPoint_SPIDER2_PBAR_ID =
# SpotweldPoint_SPIDER2_ForceZeroGap = n
# SpotweldPoint_SPIDER2_DoNotMove = y
# SpotweldPoint_SPIDER2_CBARPinFlags = 0
# SpotweldPoint_RBE3-HEXA-RBE3_UseThicknessAsHeight = n
# SpotweldPoint_RBE3-HEXA-RBE3_SpecifyHeight = n
# SpotweldPoint_RBE3-HEXA-RBE3_SeparateRefCPinflags = n
# SpotweldPoint_RBE3-HEXA-RBE3_SearchDist =
# SpotweldPoint_RBE3-HEXA-RBE3_RefCPinFlags = 123
# SpotweldPoint_RBE3-HEXA-RBE3_PinFlags = 123
# SpotweldPoint_RBE3-HEXA-RBE3_PSOLID_ID =
# SpotweldPoint_RBE3-HEXA-RBE3_Height =
# SpotweldPoint_RBE3-HEXA-RBE3_ForceOrthoSolids = n
# SpotweldPoint_RBE3-HEXA-RBE3_FailIfAspect = 0.000000
# SpotweldPoint_RBE3-HEXA-RBE3_DoNotMove = y
# SpotweldPoint_RBE3-HEXA-RBE3_AreaScaleFactor = 0.000000

In the example that follows the spotweld points must be realized in NASTRAN CWELDs with option
ELPAT and specific PWELD id, while the adhesive lines must be realized in RBE3-HEXA-RBE3 with 2
stripes, specific PSOLID id and the option ‘Force Ortho Solids’ activated. The RealizeConnections will
be used instead of the RealizeConnection since it can realize massively and thus faster.

def RealizeAllCncts():
#Collect the spotwelds of the database
spots = base.CollectEntities(constants.NASTRAN,None,'SpotweldPoint_Type')
#Collect the adhesive lines of the database
adh_lines = base.CollectEntities(constants.NASTRAN, None,'AdhesiveLine_Type')
#Number of connection points
no_spots = len(spots)
#Number of adhesive lines
no_lines = len(adh_lines)
#Realize the spotwelds
connections.RealizeConnections(spots,no_spots,
{"SpotweldPoint_Type":"NASTRAN CWELD",
"SpotweldPoint_NASTRAN-CWELD_WeldType":2,
"SpotweldPoint_NASTRAN-CWELD_SearchDist":10,
"SpotweldPoint_NASTRAN-CWELD_PWELD_ID":1000})
#Realize the adhesive lines
connections.RealizeConnections(adh_lines,no_lines,
{"AdhesiveLine_RBE3_HEXA_RBE3_SearchDist":10,
"AdhesiveLine_RBE3_HEXA_RBE3_NumOfStripes":2,
"AdhesiveLine_RBE3_HEXA_RBE3_ForceOrthoSolids":"y",
"AdhesiveLine_RBE3_HEXA_RBE3_PSOLID_ID":2000})

Some notes are necessary:


- The order of settings doesn’t affect the final result.
- The value of a setting must always follow the setting, e.g.
"SpotweldPoint_NASTRAN-CWELD_WeldType",2 is correct
"SpotweldPoint_NASTRAN-CWELD_WeldType" is wrong
- If the name of the representation is omitted, then the default will be created like in case of the adhesive
line.
- The only alphanumeric characters that are used are the ‘y’ and ‘n’ indicating yes or no respectively.
These arguments must be given as strings, e.g.
"AdhesiveLine_RBE3_HEXA_RBE3_ForceOrthoSolids","y"
- Options available in GUI as drop down menus are given with their sequence order, e.g.
"SpotweldPoint_NASTRAN-CWELD_WeldType",2, since "ELPAT" option is second in the drop down
menu of connection manager.
- After the realization, all the settings that were used are passed to connection manager and can be easily
viewed.

3.5.8 Getting the entities of connections


The elements that participate into a connection entity can be retrieved through the CollectEntities
function.
Suppose that all spotweld points must be realized in RBE3-HEXA-RBE3 representation and the ids of the
RBE3s and HEXAs that belong to each connection point must be reported in the Ansa Info window.

BETA CAE Systems S.A. 30


ANSA v.14.x Python Programming Interface

def CheckRBE3_HEXA_RBE3():
nastran = constants.NASTRAN

#Collects all Spotwelds.


concts = base.CollectEntities(nastran,None, 'SpotweldPoint_Type')
for cnctn in concts:
vals = ("X","Y","Z","P1","P2","P3","P4","Status","ID","Error Class")
ret = base.GetEntityCardValues(constants.NASTRAN,cnctn,vals)
i = 0 #Initialize
j = 0 #Initialize
if ret['Error Class']=="RBE3-HEXA-RBE3":
ents = base.CollectEntities(nastran, cnctn, False)
#Loops through the Entities of each Spotwelds
for ent in ents:
type = ent._ansaType(nastran)
if type == "RBE3":
if i == 0:
no_of_rbe = ent._id
i = 1;
else:
no_of_rbe = str(no_of_rbe)+","+str(rbe3_vals['EID'])

if type=="SOLID":
if j==0:
no_of_solids = ent._id
j = 1
else:
no_of_solids = str(no_of_solids)+","+str(eid)

print("Connection with cid ",cid," has RBE3s with ids:",no_of_rbe," and SOLIDs with
ids:",no_of_solids)
no_of_rbe = 0
no_of_solids = 0
print("Done")

3.5.9 Deleting entities


Obsolete entities can be deleted using the DeleteEntity function. It can delete either a single entity or a
number of entities at once. The function accepts a single element (pointer) of an entity or a matrix of
elements (pointers). Suppose that all unused nodes must be deleted.

def DeleteNodes():
nodes = base.CheckFree("all")
base.DeleteEntity(nodes,0)

The second argument is a force flag. Use 1 to delete entities and any references to these entities. For
example the force flag for deleting PSHELLs properties must be 1 since there are shells that use this
property. After the execution of DeleteEntity the property and the shells / grids that are associated with it
will all be deleted.
Important Note 1: To significantly reduce execution time, it is highly recommended to delete entities
massively instead one at a time.
Important Note 2: It is recommended to use the DeletePart function for deleting ANSAPARTs since it
offers more options.
Important Note 3: To delete unused entities use the Compress function

3.6 Subclassing the ANSA Entity

BETA CAE Systems S.A. 31


ANSA v.14.x Python Programming Interface

Inheritance is one of the most fundamental concepts of object orientated programming. It is a way to
reuse code of existing objects, or to establish a subtype from an existing object. In the example below by
subclassing the ANSA Entity object we extend the behavior of this object of meet our program design
requirements.

import ansa
from ansa import base
from ansa import constants

class extendedProp(ansa.base.Entity):
”””subclassing the entity of object of type ELEMENT_SHELL we extend
its behavior to return the cog and to return the number of Elements”””
def __init__(self, deck, id, type):
super().__init__(deck, id, type)

def CalculateCog(self):
return base.Cog(self)

def ElementNumber(self):
ents = base.CollectEntities(constants.LSDYNA, self, "ELEMENT_SHELL")
return len(ents)

def main():
ents = base.CollectEntities(constants.LSDYNA, None, "SECTION_SHELL")

extended = list()
for ent in ents:
ret = base.GetEntityCardValues(deck=constants.LSDYNA, entity=ent,
fields=('PID',))

extended.append(extendedProp(constants.LSDYNA, ret['PID'], 'SECTION_SHELL'))

(x, y, z) = extended[0].CalculateCog()
print('cog: %f %f %f' % ( x, y, z))

ret = extended[0].ElementNumber()
print('number of elements: '+str(ret))

BETA CAE Systems S.A. 32


ANSA v.14.x Python Programming Interface

4. Specialized Functions
4.1 General
Specialized functions in scripting language are actually user functions that have a unique syntax (input
and output arguments) and can be called automatically by the program when the user performs specific
tasks. Connectors, GEBs, Connection Manager, Includes Configurator, Results Mapper, I/O windows are
the tools where these functions can operate.

4.2 Creating Connectors and GEBs


User defined representations or interfaces of connectors and GEBs, can be created through a special
script function of certain syntax. As soon as the 'Apply' button is pressed, ANSA calls the function with the
necessary input arguments. The user specifies the script function in the 'func_name' field of GEBs and
connectors which is accessible if the interface option 'UserScript' is selected.

The interface function uses 4 arguments:


i. The current Generic Entity: variable of type ansa entity (object).
ii. The entities given from the representation. These entities will be passed to the function as a
list. Each list entry is of type ansa entity (object).
iii. The entities identified from the search. These entities will be passed to the function as a list.
Each list entry is of type ansa entity (object).
iv. Some user arguments are transferred to the function in the form of a string type variable.
The arguments are explicitly defined by the user at the 'func_arguments' field.
The representation function uses 3 arguments:
i. The current Generic Entity: variable of type ansa entity (object).
ii. A matrix that contains other matrices. The number of sub - matrices is equal to the number of
interfaces. Each matrix entry is of type ansa entity (object).
iii. Some user arguments transferred to the function in the form of a string type variable.

BETA CAE Systems S.A. 33


ANSA v.14.x Python Programming Interface

In the example shown, the function to be executed is named ‘BarInterface’. This function is defined as
follows:

BarInterface(GEB_BC, FromRepr, FromSearch, args).

The matrix ‘FromSearch’ contains all the nodes that lie in the inner/outer zone of the hole. The matrix
‘FromRepr’ contains one ‘Spc1’ node, which is by default located at the x, y, z Generic Entity coordinates.
Finally, the string 'args' will be the string '60' specified in the ‘func_arguments’ field.
Note that the function must return a non-zero value on success and a zero value on failure. In the latter
case the GEB will get a failure status. After the realization of this generic entity, each node identified from
the search will be connected to the ‘Spc1’ node with a ‘CBAR’ element.

def BarInterface(GEB_BC, FromRepr, FromSearch, diam):


all_search_nodes = len(FromSearch)
radius = float(diam)/2
area = 3.14*radius**2
#Get the id of the representation node
ret = base.GetEntityCardValues(constants.NASTRAN,FromRepr[0],("NID",))
#Create a PBAR property
new_prop = base.CreateEntity(constants.NASTRAN,'PBAR',{"A":area})
ret2 = base.GetEntityCardValues(constants.NASTRAN,new_prop,("PID",))
for i in range(all_search_nodes):
#Get the id of each search node
ret3 = base.GetEntityCardValues(constants.NASTRAN,FromSearch[i],("NID",))
#Create the bar
vals = {"N1":ret['NID'],"N2":ret3['NID'],"IPART":ret2['PID'],"x1":1}
CreateEntityVa(PAMCRASH,"BEAM", vals)

return 1

Important Note 1: Press F1 on the 'func_name' field to load the user script function.
Important Note 2: The number and type of input arguments denotes the signature of the user function.
Thus, after loading, only the functions of a specific signature will be recognized.

BETA CAE Systems S.A. 34


ANSA v.14.x Python Programming Interface

4.3 Executing specialized script functions from Connection Manager


The Connection Manager communicates with four specialized scripting functions that control :
- The Connections' 'User' field
- The Connections' diameter 'D'
- The PIDs of the RADIOSS springs
- Any other customization

4.3.1 Updating Connection's User Field


To instruct the Connections Manager to auto-fill the non editable 'User' column of connections, a user
script function can be used. In this approach the Connection Manager will automatically call this function
every time a spotweld is applied.
The script function can be loaded and specified in the general connections settings (Window>Options), by
hitting F1 key in the 'Update User Field Function' field.

Alternatively, the user can specify its name in the ANSA.defaults, under the variable:

weld_user_field_update = UserPlinkProp

The function's syntax must be the following:


Function (connection)

The input argument of this function is the element (pointer) of the entity that is going to be created. Having
this, it is easy to extract all necessary information. At the end of the script a string must be returned. A
possible use of this function is to display in the 'User' field the property id of the newly created plinks:

def UserPlinkProp(connection):

if connection._ansaType(constants.PAMCRASH) == 'PLINK':
ret = base.GetEntityCardValues(PAMCRASH,connection,('IPART',))

return ret['IPART']

Important Note 1: The number and type of input arguments denotes the signature of the user function.
Thus, after loading, only the functions of a specific signature will be recognized.

4.3.2 User Thickness to Diameter Map


When the diameter 'D' of a connection is not prescribed in the diameter field of the Connection Manager,
ANSA can auto-assign a diameter value taking into consideration the thickness of the flanges that are
connected (provided that the flag 'Use thickness to Diameter Map' -when available, is active). There are
two alternative methods for the control of the mapping, both specified in the general connections options
(or in the ANSA.defaults file):

i. Through a thickness-diameter table


ii. Through a user script function

By default ANSA will follow the thickness-diameter table method with the default table available in the
ANSA.defaults:

thick_spw_diam = 4.00,1.02,5.00,1.78,6.00
To define a mapping scheme that cannot be described by a table, a user-script function can be used. In
this approach, Connection Manager will automatically call this function every time a spotweld is applied
(provided that the flag 'Use thickness to Diameter Map' -when available, is active).
The script function can be loaded and specified in the general connections settings (Window>Options), by
hitting F1 key in the 'Function name' field.

BETA CAE Systems S.A. 35


ANSA v.14.x Python Programming Interface

Alternatively, the user can specify its name in the ANSA.defaults, under the variable:

thick_spw_diam = AssignDiameter

The function's syntax must be the following:

Function(thickness)

The input argument is a thickness value while the returned value is the diameter that will be applied:

def AssignDiameter(thickness):
if thickness <= 1:
diameter = thickness
elif thickness > 1 and thickness < 2:
diameter = thickness/4
elif thickness >= 2 && thickness < 3:
diameter = thickness/2
else
diameter = thickness*2
return diameter

Important Note 1: The thickness that is given as input, is the one that calculated according to the 'Master
Flange Election Method'.
Important Note 2: The number and type of input arguments denotes the signature of the thickness to
diameter map function. Thus, after loading, only the functions of a specific signature will be recognized.

4.3.3 Updating RADIOSS spring PID


For RADIOSS WELD FE representation, the user can control the properties that will be generated
(SPRING, Type 13) by specifying a mapping between the flange thickness and the spring PID. This
feature is activated through the “Use Thickness To PID” flag in the FE-representation options. A user
script function defined under the general connections options or in the ANSA.defaults can control the
mapping. Connection Manager automatically calls this function every time a spotweld is applied (provided
that the flag “Use Thickness to PID map”, is active).
The script function can be loaded and specified in the general connections settings (Window>Options), by
hitting F1 key in the 'Thickness to PID Map Function' field.

BETA CAE Systems S.A. 36


ANSA v.14.x Python Programming Interface

Alternatively, the user can specify its name in the ANSA.defaults, under the variable:

shell_to_spring_pid = DefineSpringId

The function's syntax must be the following:

Function(shells)

The input argument is a matrix that contains the projected shells while the output is the element (pointer)
of the property that is going to be assigned to the newly created radioss springs. The property is created
by the function or it can be any existing one.

def DefineSpringId(shells):

thickness = list()
for shell in shells:

prop = GetEntity(RADIOSS,"PROP/SHELL", shell._id)


ret_val = GetEntityCardValues(RADIOSS,prop,("THICK",))
thickness.append(ret_val['THICK'])

max_thick = max(thickness)
print(max_thick)
if max_thick <= 1:
vals = {"Name":"Maximum thickness less than "+str(max_thick),
"PID":500",
"TYPE":"SPR_BEAM 13",
"MASS":0.5}
ent = base.CreateEntity(RADIOSS,"PROP/SPR_BEAM", vals)
else:
vals = {"Name”:"Maximum thickness greater than "+str(max),
"PID":1000",
"TYPE":"SPR_BEAM 13",
"MASS":1}
ent = base.CreateEntity(constants.RADIOSS,"PROP/SPR_BEAM",vals)
return ent

In the above example a different PROP/SPR_BEAM is assigned to each spring according to the
thicknesses of the shells that connects.

Important Note 1: The number and type of input arguments denotes the signature of the user function.
Thus, after loading, only the functions of a specific signature will be recognized.

4.3.4 The post-realization script function


The script function used for the modification of the connection elements into a custom model is called
post-realization (just due to the fact that it runs every time after the connections “realization” through the
Connection Manager). It uses standard input arguments that are supplied by Connection Manager in
every call.

No. Input argument Description


1 cnctn The connection entity currently being processed
2 projections Each entry of this list is a [x, y, z] list with the coordinates of the
projections of the connection point on each of the connected
parts. The number of entries of this matrix is equal to the
number of connected parts.
3 projection_ents Each entry of this list is the ANSA entity found at the projection.
The number of entries of this matrix is equal to the number of
connected parts. If the FE-representation generated is a point-
to-point model then the list will contain node entities.
Otherwise, if the matrix will contain shell/solid entities.
4 interface_ents Each entry of this list is the element entity created as “interface”
element on each connected part. “Interface” elements are

BETA CAE Systems S.A. 37


ANSA v.14.x Python Programming Interface

those that connect the “body” element of the connection with


the structure (e.g. in an RBE3-HEXA-RBE3 connection, the
interface elements are the RBE3s). For FE-representations
with no interface elements (e.g. RBE2) this matrix is empty.
The number of entries of this matrix is equal to the number of
connected parts.
5 body_ents Each entry of this list is the element entity created as “body”
element on each connected part. “Body” elements are the main
elements of the FE-representation (e.g. in an RBE3-HEXA-
RBE3 connection, the body element is the HEXA). The number
of entries of this list is equal to the number of connected parts
minus one.
6 misc This matrix carries miscellaneous information whenever
applicable
- For spot-welds, whenever the thickness to diameter mapping
is used, misc [0] carries the actual diameter used for the
connection after the mapping.
- For the SPIDER2 FE-representation of spot-welds and for
bolts, the misc [1] carries a map with the shell elements of the
zones created after reconstruct:

hole_data = misc[1]
central_shells = hole_data["center_elements"]
zone1_shells = hole_data["zone1_elements"]
zone2_shells = hole_data["zone2_elements"]
all_connected_parts = len (projections)
for i in range(all_connected_parts):
central_shells_of_flange = central_shells[i]
zone1_shells_of_flange = zone1_shells[i]
zone2_shells_of_flange = zone2_shells[i]

The return value of the post-realization function determines what should be the “Error Class” for each
connection and signifies connection modification success or failure. The supported return values with
their meaning are listed in the table below:

Return value Meaning


1 Success.
The connection will display in its 'Error Class' field the name of the FE-representation
specified (e.g. SPIDER2, CBAR, etc.).
Its 'Status' will be 'Ok'.
0 Success.
The connection will display in its 'Error Class' field the string 'Custom FE'.
Its 'Status' will be 'Ok'.
-1 Failure.
The connection modification failed and thus the connection elements will be deleted.
The 'Status' and the 'Error Class' of the connection will be blank.

The set-up of a post-realization function consists of 2 steps:

1) Load the script


2) Declare the name of the post-realization script function

The name of post-realization script function must be declared so that the Connection Manager knows
which function to execute. This declaration is performed in the general connections options, under
Windows>Options.
Press F1 in the 'Post Realization Function' field to launch the Select Script Function window. From this
window the user can also load the script , thus complete both steps at once.

BETA CAE Systems S.A. 38


ANSA v.14.x Python Programming Interface

Alternatively, the user can specify its name in the ANSA.defaults, under the variable:
post_realization_fn = PostRealizationFunction

A couple of examples of post-realization functions are given below:

Example 1: Understanding the input arguments: This post-realization function will just print some
information in the ANSA Info window

def PostRealizationFunction(cnctn, proj, proj_ents, interfaces, bodies, misc):


flange = 1
for point in proj:
print ("Projection on flange "+str(flange)+" : "+str(point [0])+
", "+str(point[1])+", "+str(point [2]))
flange += 1

flange = 1
for ents in proj_ents:
for ent in ents:
type = ent._ansaType(constants.NASTRAN)
print ("Projection ent on flange "+str(flange)+" : "+type+" ID: "+ent._id)

flange += 1

flange = 1;
for ents in interfaces:
for ent in ents:
type = ent._ansaType(constants.NASTRAN)

print("Interface ent on flange "+flange+" : "+type+" ID: "+ent._id)

flange += 1

flange = 1;
for ents in bodies:
for ent in ents:
type = ent._ansaType(constants.NASTRAN)
print("Body ent on flange "+flange+" : "+type+" ID: "+ent._id)

flange += 1
return 1

BETA CAE Systems S.A. 39


ANSA v.14.x Python Programming Interface

Example 2: Create a SPIDER2 with CBEAM body instead of CBAR

def PostRealizationFunction (cnctn, proj, proj_ents, interfaces, bodies, misc):


D = float(misc [0])
pi = 4 * math.atan(1)
A = math.pi * D ** 2 / 4
I1 = math.pi * D ** 4 / 64
I2 = I1
J = math.pi * D ** 4 / 32
existing_pbeams = base.CollectEntities (constants.NASTRAN, 0, "PBEAM")
for prop in existing_pbeams:
tokens = prop._name.split("=")
prop_id = 0
if tokens[1] == str(D):
prop_id = prop._id

if not prop_id:
vals = {"Name":"SPW_SPIDER_D="+D, "A(A)":A,
"I1(A)":I1, "I2(A)":I2, "J(A)":J}

new_pbeam_ent = CreateEntity(NASTRAN, "PBEAM", vals)

for ents in bodies:


for ent in ents:
if ent._ansaType(constants.NASTRAN) == "CBAR":
ret = base.ChangeElemType(constants.NASTRAN,ent,"target_name",
"CBEAM", "PID", ent._id)
if ret:
return -1 #Failure. Erase-FE.

return 1

Important Note 1:The post-realization function can work for all connection points, connection lines and
surfaces and for all FE-representations except of SPIDER.
Important Note 2: To have the same post-realization function available every time ANSA is launched
load the script through an ANSA_TRANSL.

BETA CAE Systems S.A. 40


ANSA v.14.x Python Programming Interface

4.4 Includes Configurator


Using Include Configurations, script functions can
be automatically executed when:

-Updating or reloading a configuration. A script


can be executed before (pre_func_name) and/or
after (post_func_name) loading the configuration.

-Outputting a configuration (output_func_name).

The above script functions must have specific arguments:

Function (conf, arg)

where:
-conf is the Includes Configuration entity.
-arg is a map that is automatically created, having the following entries:
i) arg["UserArgs"] is the string that is input by the user in the pre- post- or output_func_arguments
field of the configuration's card.
ii) arg["Include"] is an Include entity that can be created when updating/reloading a configuration. If the
user assigns entities to this Include, then it will be added to the configuration. If this include remains
intact, then it is discarded from the database. This entry is not available for the Output script.
The user can add as many other entries as needed in map arg.

The following sample script prints the user argument in the Ansa Info window and reports the contents of
each Include of the configuration in a log file:

def TestPrePostOutputScript(conf, arg):


if arg["UserArgs"]:
print("arg[\"UserArgs\"] " + arg["UserArgs"])

all_types_of_ents = base.TypesInCategory (0, "__ALL_ENTITIES__")


f = open ("include_log.txt", 'w')
includes_of_configuration = base.GetConfigurationIncludes(conf)
for incl in includes_of_configuration:
GetEntityCardValues (0, incl, "Name", name)
f.write ("*******************\nINCLUDE "+name+":")
for type in all_types_of_ents:
ents = CollectEntities (0, incl, type)
num_of_ents = MatLen(ents)
if (num_of_ents):
f.write (num_of_ents + " "+type+"s")
f.close()

BETA CAE Systems S.A. 41


ANSA v.14.x Python Programming Interface

4.5 Results Mapper


In the User Script tab, script functions to be
executed automatically as a first step
(pre_func_name) or last step (post_func_name)
of mapping application can be specified.

The above functions must have specific arguments:

SamplePreMapFunc (results_mapper, source_entities, arget_entities, user_args)

SamplePostMapFunc (results_mapper, source_entities, target_and_new_entities, user_args)

where:
-source_entities are all the entities of the source file (i.e. entities that would be created in ANSA if the file
were input).
-target_and new_entities is a matrix that contains: i) the entities of the current (target) mesh, that have
been identified based on the specified connectivity and search pattern, ii) entities that have been created
from the results mapper (e.g. pressures, temperatures etc.). The latter are available only for the post map
function. The respective argument of the pre map function is a matrix that contains only the target entities.
-user_args is the string that can be specified from the user in the pre_func_arguments or
post_func_arguments fields.
An example of application of a pre-map function is the case when the Transformation matrix is already
known and its values reside in text file like the following:

#Tranformation matrix info for sample script

0.86597526 -0.01000431 -0.49998453 0.


0.010116526 0.99994516 -0.0024861349 0.
0.4999826 -0.00290507 0.86603 0.
299.17157 148.64174 1460.384 1.

A pre-map script can extract info from this file and assign it to the results mapper:

def SamplPreMapFunc (results_mapper, source_entities, target_entities, user_args):


f = open('transf_matrix_info.txt' , 'r')
for line in f:
if line[0]=="#":
continue
tokens = line.split(" \t")
for i in range(4):
tokens.append(float(tokens[i]))
#Do something

BETA CAE Systems S.A. 42


ANSA v.14.x Python Programming Interface

4.6 Input - Output post functions


The user is able to run a script function just after the input or output of a deck file. The function is defined
in the input or output parameters window and is executed automatically as soon as ANSA has finished
the input or output process.

The post input and output functions must have specific arguments:

PostInput(input_filename, input_function_args)

where:
- input_filename is the full path to the selected deck file.
- input_function_args is a set of auxiliary user defined arguments.

PostOutput(output_filename, output_function_args)

where
- output_filename is the full path to the created deck file.
- output_function_args is a set of auxiliary user defined arguments.

In both cases the function must return 1 for success, otherwise an error message will be printed in the
Ansa Info window.

To set up the Post Input Script and the Post Output Script functions the corresponding scripts must be
first loaded. The 'Post func name' must be declared so that ANSA knows which function to execute. Hit
F1 in the 'Post func name' field to launch the 'Select script function' window and load the script. Pick the
relative function and press Ok to assign its name in the field. In the 'Post func args' type any string
representing user define data. If no auxiliary data are needed, leave the field blank.

Important Note: The number and type of input arguments denotes the signature of the user function.
Thus, after loading, only the functions of a specific signature will be recognized.

4.6.1 Example of a Post Input Script

A Post Input Script will be executed only when all


physical data have been already imported in ANSA.
A simple example of such a function could be the
reading of deck file comment lines of specific
syntax that hold information not read by ANSA, like
'Model Id' 'LoadCase name' etc. Through the 'Post
func args' the script function will be notified to read
these lines by typing 'yes' and then they will be
added to the General Comment.

def InputPost(filename, post_func_args):


if post_func_args == "yes":
fr = open(filename,'r')
for line in fr:
if line.find("Model Id") >= 0:
tokens = line.split(":")
model_id = tokens[1].letters()

elif line.find('LoadCase Name'):


tokens = line.split(':')
loadcase_name = tokens[1].letters()
fr.close()
comment = "Model Id:"+model_id+"\n"+
"LoadCase:"+loadcase_name

BETA CAE Systems S.A. 43


ANSA v.14.x Python Programming Interface

base.SetGeneralComment(comment)

4.6.2 Example of a Post Output Script

A Post Output Script is executed only when all physical data have been already exported. The user could
use a Post output function in order to add to the exported deck file some comments written in a specific
syntax suitable for reading by another software. In this case no 'Post func args' need to be defined.

def OutputPost(filename, post_func_args):


fw = open(filename+"_temp","w")
fw.write("$ Some user comments")
fr = open(filename,"r")

for line in fr:


fw.write(line)
fw.close()
fr.close()
os.move(filename+"_temp",filename)
os.remove(filename)

BETA CAE Systems S.A. 44


ANSA v.14.x Python Programming Interface

5. Handling Scripts From GUI


5.1 General
Basic actions such as loading, parsing or executing user defined functions, can be carried out in ANSA
with 3 distinct ways which are the Script menu, the command window and the Script Editor. This chapter
focus on the description of the first two along with other useful functionality

5.2 Using script menu


The Script option that is located under the File menu, reveals the Script menu:

BETA CAE Systems S.A. 45


ANSA v.14.x Python Programming Interface

5.2.1 Script menu functions


• Tools>Script>Script editor:
Opens the Script Editor interface.
• Tools>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.
• Tools>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.
• Tools>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.
• Tools>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.

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.
• Tools>Script>Reload:
Reloads the last loaded script.
• Tools>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.
• Tools>Script>Run function:
Runs a function. When selecting this button the following window opens:

BETA CAE Systems S.A. 46


ANSA v.14.x Python Programming Interface

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 Tools>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. Press Ok to proceed to the function execution or Cancel to abort.

5.3 Using the search engine

5.3.1 Quick view of auxiliary built in functions

BETA CAE Systems S.A. 47


ANSA v.14.x Python Programming Interface

The Command Line window is an easy tool for handling scripts. Typing in the command line the word
USER>ANSA lists all available auxiliary built in functions in the Ansa Info window.

5.3.2 Description of auxiliary built in functions


A brief description of the functions listed in Ansa Info window is given below:

load_script
Usage: USER:load_script: <full path to the new script>
Example: USER>:oad_script:/home/jharal/work/CombineSets.c
Description: Clear all previous loaded scripts and loads the one specified above
reload_script
Usage: USER:reload_script()
Example: USER:reload_script()
Description: Reloads all loaded scripts.
add_script
Usage: USER:add_script: <full path to the new script>
Example: USER:add_script: /home/jharal/work/CombineSets.c
Description: Adds a script.
import_script
Usage: USER:import_script: <full path to the new script>
Example: USER:import_script:/home/jharal/work/CombineSets.c
Description: Append new script in the current active ones
unload_script
Usage:USER:unload_script()
Example: USER:unload_script()
Description: Unloads all loaded functions
default
Usage: USER:default()
Example: USER:default()
Description: Opens a window with all loaded scripts and waits the user to select the new default one.

BETA CAE Systems S.A. 48


ANSA v.14.x Python Programming Interface

5.3.3 Loading scripts


A script is successfully loaded only when is free of syntax errors. Specifically, ANSA parses the script that
the user attempts to load and in case of an error displays in the Ansa Info window the error line of the
code.

In the above example the script 'MakeSkin.bs' has an error in line 25.
After all necessary corrections the script is loaded again. This time no errors occurred.

Important Note 1: If a script has more than one error, then only the first occurrence will be displayed.
Important Note 2: A wrong syntax of a built in function is reported in run time.

5.3.4 Running scripts


After a script is loaded, all the functions that contains can be viewed in the Ansa Info window by typing
USER> in the command line. Exceptions are those functions that have been declared with an '_'
(_myFynction).

USER>load_script(ANSA_TRANSL)

Write in command line:


USER><function name> followed by parentheses to run any function.
i.e USER:TriasWithCommonEdge()

BETA CAE Systems S.A. 49


ANSA v.14.x Python Programming Interface

If function contains input arguments it is displayed in Ansa Info window in the form:
USER><function name (type of input argument)> i.e, USER:PrintText('ANSA', 'v14.2.2')

The 'PrintText' function accepts two strings as input arguments. These arguments are given in the
command line after the name of the function and have to be separated with comma. All other ways are
ignored.
Finally, all functions that executed via command line display their possible messages in the Ansa Info
window.

5.4 Creation of user buttons


ANSA module enables the creation of user defined buttons. This is done with function decorators. There
are three ways the function decorator @ansa.session.defbutton can be used.

Decorator Comment
@ansa.session.defbutton The function name is the button name placed in the
default button group
@ansa.session.defbutton('Visibility') The function name is the button name placed in the
specified button group
@ansa.session.defbutton('Visibility', 'Test Button') Button name and group is specified in the defbutton

Couple of examples are shown below.

import ansa
@ansa.session.defbutton
def Test_Button():
print('ANSA')

For placing buttons in specific groups, the name of the group must be specified in the defbutton:
import ansa

@ansa.session.defbutton('Visibility')
def Test_Button():
base.SetViewAngles("F10")

Once the script is loaded, a button called "Test_Button" is created under the "Visibility" group of
Windows>User Script Buttons and placed in the first free position.

BETA CAE Systems S.A. 50


ANSA v.14.x Python Programming Interface

5.5 Script plugins


Script plugins are user defined scripts that are loaded in ANSA only at start up. The plugins are
accessible through the File>Script plugins and act as any other user functions. Although the plugins are
common scripts, they are not treated as modules and thus they cannot be loaded, unloaded or executed
through the File>Script menu or command line.

5.5.1 Plugins characteristics


A script is considered a plugin only if its extension is .bpl. Any function within the plugin that is defined
with the defbutton statement and its syntax is error free, it will be added under the File>Script plugins
menu. The names that appear in the menu, are the names of the defbutton functions.

5.5.2 Loading plugins in ANSA


Script plugins are loaded in ANSA in two distinct ways:
1) By placing all scripts under the config/plugins directory of ANSA installation package.
2) By forcing ANSA to read the scripts from a user defined directory. This can be done only when ANSA
is launched with the -plugins flag, followed by a directory full path, e.g.

ansa -plugins /home/demo/my_plugins/

ANSA reads the plugins always starting from the config/plugins directory and afterwards from the user
directory. A message is always displayed in ANSA Info window informing the user regarding the loading
process of all plugins.

In the above case, ANSA loaded two plugins from a user directory and one plugin from the
/config/plugins/ folder. The plugins then are considered extensions of the program and can be executed
through the File>Script plugins

Important Note: Plugin functions are loaded normally even if they have the same name.

BETA CAE Systems S.A. 51


ANSA v.14.x Python Programming Interface

6. Running scripts without GUI


6.1 Using the '-exec' flag
For running ANSA in batch mode, the user is able to use the exec flag. Each time an exec flag is used , it
is followed by a script command. The syntax of the commands is platform dependent and therefore
special attention must be given for Windows and Unix systems. In most general case, a script must be
first loaded and then executed, thus the exec flag must be used twice.

6.1.1 Running scripts without input arguments


Let's see how the 'main' function located under the script 'test.bs' can be executed:

def main():
print("Hello")

Linux OS:

ansa -nogui -exec load_script:/home/demo/test.bs -exec main

Windows OS:

For filepaths that don't contain blank spaces:

ansa -nogui -exec load_script:C:\temp\demo\test.bs -exec main


or
ansa -nogui -exec load_script:C:/temp/demo/test.bs -exec main

For filepaths that contain blank spaces:

ansa -nogui -exec “load_script:C:\”Documents and Settings\test.bs”” -exec main


or
ansa -nogui -exec “load_script:C:\”Documents and Settings/test.bs”” -exec main

6.1.2 Running scripts with input arguments


In case the function accepts input arguments:

def main(a, b):


print(a+" = "+b)

Linux OS:

ansa -nogui -exec load_script:/home/demo/test.bs -exec 'main( "value",10 )'

Windows OS:

For filepaths that don't contain blank spaces:

ansa -nogui -exec load_script:C:/temp/demo/test.bs -exec main( \"value\",10 )


or
ansa -nogui -exec load_script:C:\temp\demo\test.bs -exec main ( \"value\",10 )

For filepaths that contain blank spaces:

ansa -nogui -exec “load_script:C:\”Documents and Settings\test.bs”” -exec main( \"value\",10 )


or
ansa -nogui -exec “load_script:C:\”Documents and Settings/test.bs”” -exec main( \"value\",10 )

BETA CAE Systems S.A. 52


ANSA v.14.x Python Programming Interface

Important Note: Any scripting functions related to graphics performance cannot be executed in 'nogui'
mode, e.g. the SelectOpenFile, SelectOpenDir, PrintToFile etc. Exceptions are the OREntity,
ANDEntity, NOTEntity.

BETA CAE Systems S.A. 53


ANSA v.14.x Python Programming Interface

7. Automation through the ANSA_TRANSL.py file


7.1 Location of ANSA_TRANSL.py file
When ANSA is called to run, it will search for an ANSA_TRANSL text file within the locations listed in the
following list. The numbers on the left indicate precedence (from lowest to highest):

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. Its location is 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 Ansa Info
window:

1. NOTICE script [ansa home directory/ANSA_TRANSL] not found


2. NOTICE 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.py


ANSA_TRANSL interacts with ANSA in three ways:
(a) When ANSA tries to read a native or neutral CAD file it 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 are translated into ANSA databases and the property, material, thickness,
and other specific characteristics of each component must be assigned to the related fields within ANSA.
In case of translation of native cad files (CATIA, JT, etc), the ANSA_TRANSL is called indirectly either by
the CAD translators interface or by the command line scripts 'ansa_cad.sh', 'ansa_cad.bat' of the
installation directory.
(b) When a user executes a custom script he can run any function defined 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 Window or from Script menu (see section 5.3.3 and section 5.2.1).

Important Note: ANSA_TRANSL can be also loaded manually.

7.1.2 Form of ANSA_TRANSL.py


The ANSA_TRANSL syntax follows the same principals as any other common script, thus it can contain a
global section and a section with user defined functions. In addition, the latter may contain a specific
function called CAD_Translate. This function substitutes the old global code (v12.x) and is executed
while ANSA is reading neutral cad files (iges, step, vda) or during the translation of native CAD files
(Catia, UG, ProE, JT). CAD_Translate accepts no arguments and follows the same rules as any other
user function.

global a
string b

def CAD_Translate():
...code...

def Translation():
...code...

BETA CAE Systems S.A. 54


ANSA v.14.x Python Programming Interface

If ANSA finds among 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: Any ANSA_TRANSL that comes from versions prior to v13.0 is valid only if it is in
binary format.

7.1.3 Registers used for translation


The CAD_Translate function can contain any script function and it is executed only when cad files are
used and when all the actual entities have been translated into ANSA.
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 or translated
cad models. Below is the list with all currently supported ANSA registers.

ANSA registers Description


FILENAME The name of the CAD file currently processed
FILEPATH The directory path of the CAD file
SEPARATORS Definition of whatever is used to separate words (eg. ,_.)
TRANSLATIONS Default character translations (eg. " " = "_" blank space is
translated into an underscore)
PART_ID Module ID of current Part
PART_NAME The name of the Part as appears in the Part's Manager
PART_VERSION The version of the Part as appears in the Part's Manager
PART_PROPERTY_ID The Property ID that will be assigned to all entities of the Part
PART_PROPERTY_NAME The name of the above property as appears in the PR.LIST
PART_PROPERTY_THICKNESS The thickness of the Property
PART_MATERIAL_ID The Material ID that will be assigned to all entities of the Part
PART_MATERIAL_NAME The name of the above material as appears in the M.LIST
PART_COORD_SYS_X X-coordinate of the Origin used for Part's position
PART_COORD_SYS_Y Y-coordinate of the Origin used for Part's position
PART_COORD_SYS_X Z-coordinate of the Origin used for Part's position
PART_COORD_SYS_DX1 X-component of X-axis used for Part's transformation
PART_COORD_SYS_DY1 Y-component of X-axis used for Part's transformation
PART_COORD_SYS_DZ1 Z-component of X-axis used for Part's transformation
PART_COORD_SYS_DX2 X-component of Y-axis used for Part's transformation
PART_COORD_SYS_DY2 Y-component of Y-axis used for Part's transformation
PART_COORD_SYS_DZ2 Z-component of Y-axis used for Part's transformation
PART_COORD_SYS_DX3 X-component of Z-axis used for Part's transformation
PART_COORD_SYS_DY3 Y-component of Z-axis used for Part's transformation
PART_COORD_SYS_DZ3 Z-component of Z-axis used for Part's transformation

The basic advantage of registers is that they can pass directly a value to an entity without first 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, the registers PART_PROPERTY_NAME and PART_MATERIAL_NAME
can be used to assign the property and material name of the component.

PART_PROPERTY_NAME = "panel"
PART_MATERIAL_NAME = "steel"

The same could be done using the built in functions:

pshell = base.GetFirstEntity(constants.NASTRAN,"PSHELL")
base.SetEntityCardValues(constants.NASTRAN,pshell,"Name","panel")
material = base.GetFirstEntity(constants.NASTRAN,"MAT1")
SetEntityCardValues(constants.NASTRAN, material,"Name","steel")

Obviously, in the second case more lines of code are needed 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.

BETA CAE Systems S.A. 55


ANSA v.14.x Python Programming Interface

7.1.4 Excluded built in functions from CAD_Translate


When the ANSA_TRANSL is called by the CAD translators interface or by the 'ansa_cad.sh',
'ansa_cad.bat' scripts, any built in functions coming from the following categories are excluded and thus
will not be executed:
- Batch mesh
- Decks
- Morph
- Tools
- Mesh
- Task
Also, from the Session category the functions related to TOPO, MESH, DECK, MORPH, TANK, CROSS
modules are also excluded.
In case any of these functions will be used, the following message will be displayed:

1. Function not found : <function name>, at line x

7.1.5 How to call system commands


Very often during a process driven by a script that is running by ANSA, a system command is needed to
perform an action that is essential for the process. In most cases, the system command may call another
software like META or the cad translator. The built in function System lets the user execute any operating
system command using the syntax that the UNIX terminal or the windows command line would accept.
The input argument must be a string.

def CAD_Translate():
cad_filepath = "/home/demo/test.CATPart"
os.system("/home/demo/beta/ansa_v13.1.1/ansa_cad.sh -i "+cad_filepath)

The System command can also use the environment variables of the system. Especially for calling the
cad translator, the 'ANSA_EXEC_DIR' can be used to access the ANSA installation directory. The dollar
character $ must be in front of an environment variable in order to get its value:

def CAD_Translate():
os.ystem("$ANSA_EXEC_DIR/ansa_cad.sh -i "+cad_filepath)

Important Note: The function EnvironmentVar gets the value of any environment variable.

7.1.6 Importing neutral CAD files


Information about a part (like its name, property, material, thickness, position, etc) can reside as
comments into the header section of a neutral CAD file (.iges, .step, .vda) in the form of keywords. Using
a special ANSA_TRANSL script, these keywords are read and the related information is passed directly
into ANSA. Such an ANSA_TRANSL must contain the CAD_Translate function.
A cad header can be read using the built in function GetNextFileLine. The syntax accepts a string
argument where each line of the header is going to be stored after a successful call of the function.
Usually it is used together with a while statement.

IGES header example

MODEL : SPACE MOBILE S 1


PART NUMBER : 1234567 S 2
TITLE : LEFT FLOOR BEAM S 3
PROP ID : 456 S 4
VERSION : A S 5
THICKNESS : 1.5 S 6
MAT ID : 7892 S 7
MAT NAME : St 50 BH S 8
POSITION : L S 9
VERSION : B S 10
THICKNESS : 1.2 S 11
1H,,1H;,,57H/usr/people/CAD_data2/STELIOS_TEST/INTERFACES/header.iges,7HG 1
ANSA9.x,3H1.2,32,36,6,306,15,,1.,2,2HMM,1,1.,13H991109.153539,0.001, G 2
10000.,,,9,1,13H991109.153539; G 3
126 1 0 0 0 0 0 000000001D 1
126 0 0 8 0 0 0BSPLINE 1D 2

BETA CAE Systems S.A. 56


ANSA v.14.x Python Programming Interface

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 1
0.75,0.875,0.875,1.,1.,1.,1.,1.,1.,0.707107,1.,0.707107,1.,1., 1P 2
1.,0.707107,1.,0.707107,1.,406.539,1057.63,-6.75,401.539, 1P 3
1057.63,-6.75,396.539,1057.63,-6.75,396.539,1050.88,-6.75, 1P 4
396.539,1050.88,0.,396.539,1050.88,6.75,396.539,1057.63,6.75, 1P 5
401.539,1057.63,6.75,406.539,1057.63,6.75,406.539,1050.88,6.75, 1P 6
406.539,1050.88,0.,406.539,1050.88,-6.75,406.539,1057.63,-6.75, 1P 7
0.5,0.75,0.,0.,0.; 1P 8
S 13G 3D 2P 8 T 1

The above HEADER is easy to be extracted using only the following 2 lines under the CAD_Translate
function:

def CAD_Translate():
for line in 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. 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*/


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

BETA CAE Systems S.A. 57


ANSA v.14.x Python Programming Interface

m = TokenizeString(in_line,"=",0);
sub_ass_name = GetString(m[1]);
NewGroup(sub_ass_name,0);
}
/* Look for a "TITLE = ...." line */
else if(MatchString(in_line,"TITLE"))
{
m = TokenizeString(in_line,"=",0);
pdm_id = GetString(m[1]);
}
/* Look for a "MODULE ID = ...." line */
else if(MatchString(in_line,"MODULE ID"))
{
m = TokenizeString(in_line,"=",0);
module_id = GetInt(m[1]);
}
/* Look for a "PROPERTY NAME = ...." line */
else if(MatchString(in_line,"PROPERTY NAME"))
{
m = TokenizeString(in_line,"=",0);
property_name = GetString(m[1]);
}
/* Look for a "PID = ...." line */
else if(MatchString(in_line,"PID"))
{
m = TokenizeString(in_line,"=",0);
property_id = GetInt(m[1]);
}
/* Look for a "MATERIAL NAME = ...." line */
else if(MatchString(in_line,"MATERIAL NAME"))
{
m = TokenizeString(in_line,"=",0);
material_name = GetString(m[1]);
}
/* Look for a "MID = ...." line */
else if(MatchString(in_line,"MID"))
{
m = TokenizeString(in_line,"=",0);
material_id = GetInt(m[1]);
}
/* Look for a "THICKNESS = ...." line */
else if(MatchString(in_line,"THICKNESS"))
{
m = TokenizeString(in_line,"=",0);
thickness = GetFloat(m[1]);
}
/* Look for an "ORIGIN = ...." line */
else if(MatchString(in_line,"ORIGIN"))
{
/* Read X,Y,Z Origin Coordinates */
m = TokenizeString(in_line,"=,",0);
PART_COORD_SYS_X = GetFloat(m[1]);
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]);

BETA CAE Systems S.A. 58


ANSA v.14.x Python Programming Interface

PART_COORD_SYS_DY2 = GetFloat(m[2]);
PART_COORD_SYS_DZ2 = GetFloat(m[3]);
}
/* Look for a "Z_AXIS = ...." line */
else if(MatchString(in_line,"Z_AXIS"))
{
/* Read DX,DY,DZ of Z Axis Vector */
m = TokenizeString(in_line,"=,",0);
PART_COORD_SYS_DX3 = GetFloat(m[1]);
PART_COORD_SYS_DY3 = GetFloat(m[2]);
PART_COORD_SYS_DZ3 = GetFloat(m[3]);
}
}
}
else
{
/* Warn user if Attributes File does not Exist */
if(fd_log)
Write(fd_log,"Warning : No Attributes File");
else
Print("Warning : No Attributes File");
}
if(!pdm_id)
{
/* Warn user if No PDM data in Attributes File */
if(fd_log)
Write(fd_log,"Warning : NO PDM Id");
else
Print("Warning : NO PDM Id");
}
/* Construct PART name to the taste of user */
if(i = MatchSeparators(FILENAME))
{
if(pdm_id)
name = FILENAME(:i-1)%"_"%pdm_id;
else
name = FILENAME(:i-1);
}
else
{
if(pdm_id)
name = FILENAME%"_"%pdm_id;
else
name = FILENAME;
}
/* Finally Assign PART Atributes to ANSA Registers */
PART_NAME = pdm_id;
PART_ID = module_id;
PART_PROPERTY_ID = property_id;
PART_PROPERTY_NAME = property_name;
PART_PROPERTY_THICKNESS = thickness;
PART_MATERIAL_ID = material_id;
PART_MATERIAL_NAME = material_name;
}

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.

BETA CAE Systems S.A. 59


ANSA v.14.x Python Programming Interface

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.

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

BETA CAE Systems S.A. 60


ANSA v.14.x Python Programming Interface

}
}
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;
if(!model_name) model_name = "U";
if(!status) status = "U";
if(!thickness) thickness = 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.7 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.

BETA CAE Systems S.A. 61


ANSA v.14.x Python Programming Interface

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: 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 Ansa Info window:

unloading function: autoexec, in: <path of ANSA_TRANSL that was read before the last
one>

BETA CAE Systems S.A. 62


ANSA v.14.x Python Programming Interface

8. Interacting with native CAD files


8.1 General
This chapter describes a way of exploiting useful cae information like property name or material name, as
well as orientation information that have been defined inside native CAD files (Catia, NX, Jtopen, ProE).
However, due to the binary format of CAD 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 CAD_Translate function and
specific scripting commands.

8.2 Script commands related with Catia


The most important script commands that are related to the cad translator are summarized in the
following table:

# Cad function Description


1. VolumesCreated Checks if volume entities were created
2. MaterialVector Checks if material vector was found in the file
3. MatVecThickness Returns thickness according to material vector or layer thickness
4 OrientationVector Checks if orientation vector was found in the file
5. PartContainsGeometry Checks the existence of geometry in file

8.2.1 Catia orientation check


A successful orientation of parts during translation saves a lot of manual work for the user, but also
eliminates the case of mispositioned or intersected parts during the assembly. The most commonly used
methods to extract the orientation information are:
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
More information can be found in cad_data_translators.pdf

The functions used to recognize such definitions are the MaterialVector and OrientationVector. Both
accept no arguments and return 1 on success and 0 on 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 an ANSA_TRANSL.log file.

def CAD_Translate():
orient_found = cad.OrientationVector()
if not orient_found:
fw = open("ANSA_TRANSL.log","w")
fw.write(FILENAME+" doesn’t contain an orientation
vector in the specified layer ")
fw.fclose(fw)

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, the thickness taken from a curve must be set to the fields 'T' and 'cad_thickness' of a PSHELL
card.

BETA CAE Systems S.A. 63


ANSA v.14.x Python Programming Interface

def CAD_Translate():
thickness = cad.MatVecThickness();
ents = base.CollectEntities(constants.NASTRAN, None, 'PSHELL')
vals = {"T":thickness, "cad_thickness":thickness}
base.SetEntityCardValues(NASTRAN,ents[0], vals)

8.2.3 Check geometry existence


For checking if the cad file contains any geometry, the function PartContainsGeometry must be used. It
accepts no arguments and returns 1 if at least one entity is found or 0 if the file is empty.

def CAD_Translate():
status = cad.PartContainsGeometry();
if not status:
fw = open('report.txt','a')
text = FILENAME+" doesn’t contain any geometry"
fw.write(text)
fw.fclose()

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

8.3 Reading the attributes of cad files (CATIA, NX, ProE)


By default, during the cad translation any part or properties attributes are written as comments under the
ANSAPART or property comment field. If additional attributes of other entities (usually CURVEs or
POINTs) must be extracted then the flag -read_attributes must be used. The attributes are written in the
following form:
<ATTRIBUTE NAME>:<ATTRIBUTE VALUE>
The following script reads the comment field of the ANSAPART, as it was written during the cad
translation, and prints some attribute values.

def CAD_Translate():
ents = base.CollectEntities(constants.NASTRAN, None, 'ANSAPART')
ret_vals = base.GetEntityCardValues(constants.NASTRAN,ents[0],("Comment",))
lines = ret_vals['Comment'].split("\n")
for line in lines:
m = line.split(":")
attribute_name = m[0].letters()
if attribute_name == "PartNumber":
module_id = m[1].letters()
print(module_id)
elif attribute_name=="Revision":
version = m[1].letters()
print(version)

Important Note: The function GetNextFileLine cannot read the cad files headers and attributes.

8.4 Handling of catia properties


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

def CAD_Translate{
tp_del = list()
pshells = base.CollectEntities(constants.NASTRAN,None,"PSHELL")
for pshell in pshells:
ret_val = base.GetEntityCardValues(constants.NASTRAN,pshell,("Name",))
if ret_val['Name'] == "Bolts" or et_val['Name'] == "Auxiliaries":
to_del.append(pshell)
base.DeleteEntity(to_del,1)

BETA CAE Systems S.A. 64


ANSA v.14.x Python Programming Interface

8.5 Writing in the cad log file


The option Create log file (-log) of cad translator creates a log file named as: <filename_number.log>.
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 any text in the created log file:

def CAD_Translate:
fid = cad.TranslatorLogFile()
pshells = base.CollectEntities(constants.NASTRAN,None,"PSHELL")
no_pshells = str(len(pshells))
fid.write("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.

8.5.1 The "Extra Options" field of Cad Translator


Extra Options (-user options) is used in conjunction with a built in script function called
ProgramArguments. When the latter 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'.

def CAD_Translate:
args = utils.ProgramArguments()
for arg in args:
if arg.find("skin"))
base.Skin(1,0,3,1,0,0,5)
elif arg.find("link"):
base.OffsetLink("0.5")

BETA CAE Systems S.A. 65


ANSA v.14.x Python Programming Interface

9. BCGUI Functions
9.1 What is BCGUI
BCGUI (BETA C interface Graphical User Interface ) is a powerful and versatile library of GUI functions. It
is meant to help script users build windows that consist of any type of graphical interface, like lineEdits,
comboBoxes, checkBoxes, Lists etc, in order to interact faster and easier with ANSA entities.

9.2 BCGUI structure and philosophy


BCGUI entities are divided in 3 categories of classes:

9.2.1 Widget classes or widgets


This category includes the important GUI entities that are visible and manageable by the user, like
windows, buttons, combo boxes.
BCWindow
Provides a window that may hold any other widget, layout or item. It is the highest-level widget that can
be created by the BCGUI library. A vertical layout is provided by default.

BCLineEdit
Provides a one-line text editor.

BCCheckBox
Provides an option box with a text label on the right.

BCComboBox
It is a combination of a 'BCPushButton', a 'BCLineEdit' and
a 'BCPopupMenu'.

BCPushButton
It is a button that can perform an action on click or on toggle.

A simple 'BCWindow' with a 'BCLineEdit', a 'BCCheckBox', a 'BCComboBox' and 'BCPushButton' are


shown below:

BCFrame
The 'BCFrame' class provides a flexible visual box which can obtain several shadow styles and
accommodate other widgets. A layout must be set in a 'BCFrame' since they do not have one by default.
For placing widgets inside, vertically or horizontally, use functions BCVBoxCreate or BCHBoxCreate
respectively.

BCLabel
Provides text or image display.

BCLabelTicker
Provides an auto-scrolling label

BCSpinBox
Provides a widget that allows the user to choose a value either by clicking the up/down buttons to
increase/decrease the value currently displayed or by typing the value directly into it.

BETA CAE Systems S.A. 66


ANSA v.14.x Python Programming Interface

BCSeparator
Creates a thin line to separate widgets.

BCSlider
Provides a vertical or horizontal widget for controlling a bounded value. It lets the user move a slider
along a horizontal or vertical groove and translates the slider's position into an integer value within the
legal range.

BCStatusBar
Provides a horizontal bar suitable for presenting status information.
BCToolBox
BCLabel BCSpinBox
Provides a column of tabbed widget items. It displays a column of tabs one above the other, with the

BCFrame
BCSeparator
BCFrame
BCSlider
BCStatusBar
current item displayed below the current tab. Every tab has an index position within the column of tabs. A
tab's item is a widget (e.g. a 'BCFrame').

BCDrawerGrid
It is a widget that can accommodate other widgets and manage their visibility.

BCButtonGroup
Provides a box frame with a title at the top. 'BCPushButtons', 'BCToolButtons', 'BCRadioButtons' and
'BCCheckBoxes' can be inserted. These widgets can be arranged vertically or horizontally.

BCRadioButton
Provides a two-state button with a text label, that can be switched on (checked) or off (unchecked). Radio
buttons when grouped, provide a "one of many" choice.

BCDialogButtonBox
It is a widget that automatically adds to itself an 'Ok' and a 'Cancel' 'BCPushButton' when it is created.
This is the recommended way to create the 'Ok' and 'Cancel' buttons since they are automatically
connected to the accept and reject functions of the 'BCWindow'.

BCDrawerGrid
opened

BCRadioButton

BCButtonGroup

BCDrawerGrid closed

BCToolBox
BCDialogButtonBox

BETA CAE Systems S.A. 67


ANSA v.14.x Python Programming Interface

The same 'BCWindow' with the 'BCDrawerGrid' open, showing the 'BCPushButton' it holds.

BCToolButton
Performs an action on press, on click or on toggle. Unlike 'BCPushButtons', they tend to occupy all
available space and they have a different look and feel. They are also ideal to be used with other widgets,
like 'BCButtonLineEdits', 'BCButtonComboBoxes', 'BCListViews' etc.

BCButtonLineEdit
Provides a one-line text editor that can hold buttons to its left or to its right.

BCCalculator
This class consists of a function set that create and manage a calculator window. It can be easily
combined with a 'BCButtonLineEdit' by inserting a 'toolButton' which provides a calculator when pressed.
The calculator's output can be sent back to the 'BCButtonLineEdit' by pressing the '->' calculator's button
(see the images below).

BCButtonComboBox
The 'BCButtonComboBox' can be seen as a combination of a 'BCComboBox' and a 'BCButtonLineEdit'. It
has the advantage that one or many buttons can be displayeComboVal_d left or right of its 'lineEdit'.

In the following picture a 'BCWindow' containing a 'BCLabel', a 'BCButtonLineEdit' and a


'BCButtonComboBox' are shown. The 'BCPushButton' inside the 'BCButtonLineEdit', when pressed pops
up a calculator. The upper lineEdit displays user's input and the lower the calculation's output. By
pressing the '->' button the calculator's output, shown in the second lineEdit is inserted into the
'BCButtonLineEdit' from which the calculator was called.

BETA CAE Systems S.A. 68


ANSA v.14.x Python Programming Interface

BCWidgetStack
Provides a stack of widgets of which only one (the top most) is visible at any time.

BCSplitter
Provides a splitter widget that lets the user control the size of child widgets by dragging the boundary
between the children.

In the following image a 'BCSplitter' separates a 'BCListView' from a 'BCWidgetStack'. The selection of a
'BCListViewItem' from the 'BCListView' raises a different 'BCFrame' (i.e. widget) on the widget area.

BCTabWidget
Provides a 'tabBar' of tabs and a 'page area' below the tabs. Each tab is associated with a different page.
Only the current tab's page is shown in the page area; all the other tabs' pages are hidden.

BCTextEdit
Provides a powerful single-page rich text editor. 'BCTextEdit' by default allows undo/redo history to be
kept while some other word processing attributes (for example <Ctrl+C> for copy, <Ctrl+V> for paste). It
works on paragraphs and characters. A paragraph is a formatted string which is word-wrapped to fit into
the width of the widget. By default when reading plain text, one newline signify a paragraph. A document
consists of zero or more paragraphs, indexed from 0. Characters are indexed on a per-paragraph basis,
also indexed from 0.

BCTextBrowser
Provides a BCTextEdit with hypertext navigation.

In the image below a 'BCTabWidget' with 2 tabs was inserted in a 'BCWidgetStack'. Each tab holds a
'BCTextEdit'.

BCTable
The BCTable class provides a flexible editable (spreadsheet-like) table widget. In 'BCTable's' other
widgets can be inserted as well.

BETA CAE Systems S.A. 69


ANSA v.14.x Python Programming Interface

BCPopupMenu
Provides a pull down menu of choices.

A 'BCTable' has a vertical and a horizontal header. Rows and columns can be selected through the
headers.

BCListView
It implements a list/tree view. It can display and control a hierarchy of multi-column items, and provides
the ability to add new items at any time.

BCListViewInfoBox
It is a 'BCFrame' placed at the bottom of a 'BCListView' providing information about the total and the
selected items of a 'BCListView', as well as custom texts.

BCWidgetExpand
It is a widget used to save space in forms. Use this class to provide expansion functionality to the widgets
without having to resize the parent window. The class is simple to use and really useful in widgets
applying a scroll bar (such as 'BCListViews' or 'BCTextEdits'). Drag the mouse towards the direction
where the widget must be expanded, while holding 'Shift' and middle mouse button. The widget remains
expanded while the mouse cursor is inside it.

BCLineEditPath
It is a 'BCFrame' containing a 'BCComboBox' with the more recent paths used, a 'BCToolButton' for
browsing files and another 'BCToolButton' for clearing the history. These paths will be available any time
ANSA is used. The history-box frame can be a 'files', 'folders' or 'everything' type and it can be used with
'open' or 'save as' mode.

BETA CAE Systems S.A. 70


ANSA v.14.x Python Programming Interface

BCTimer
The 'BCTimer' provides timer signals and single-shot timers.

BCProgressBar
It is used to give the user an indication of the progress of an operation and to reassure them that the
application is still running.

9.2.2 Layout classes or layouts


These are the invisible entities that manage the layout of widgets.
BCBoxLayout
The 'BCBoxLayout' is one of the most useful tools for managing geometry. It consists of a rectangular box
having transparent outside border which can obtain horizontal or vertical orientation for it's children (either
widgets or other layouts). It is usually used as a parent in widgets creation.

BCGridLayout
The 'BCGridLayout' class lays out widgets in a grid. It takes the space made available to it (by its parent
layout or widget), divides it up into rows and columns, and puts each widget it manages into the correct
cell.

Layouts are used to define the widgets' placement inside a 'BCWindow'. A 'BCWindow' has by default a
'BCBoxLayout' with a vertical orientation (red lines). This means that all children of the 'BCWindow' or its
'BCBoxLayout' will be placed one below the other, according to the order they have been created. In the
following example, children can be either widgets (the 'Ok' and 'Cancel' BCPushButtons) or other layouts
(the horizontal 'BCBoxLayout' and the 'BCGridLayout').

9.2.3 Items
BCSpacer
Provides a blank space in a layout. It can be extended to all directions, according to the default
parameters.

BCListViewItem and BCCheckListItem


These consist the content of a 'BCListView'. They may belong to the 'BCListView' directly (top-level items)
or to other items, if hierarchy is allowed. Controllable widgets can be added to them, like 'checkBoxes',
'comboBoxes' and 'buttons'.

BETA CAE Systems S.A. 71


ANSA v.14.x Python Programming Interface

9.2.4 General remarks


The creation of graphical interface with BCGUI may include any of the above widgets, layouts or items
following the parent-child logic. This means that a BCGUI entity is constructed as a child of another one.
In this way the relation, i.e. the placement and the dependencies of each entity, can be easily defined.
Actions like showing, hiding or destroying a parent widget, automatically are applied recursively to all its
children.
The 'BCWindow' is the highest level widget a user can create in script and ANSA main window is set
automatically as parent:

Pseudocode for a simple BCWindow

w = guitk.BCWindowCreate()
le = guitk.BCLineEditCreate(w) #le has parent w
f = guitk.BCFrameCreate(w) #f has parent w and placed below le
l = guitk.BCBoxLayoutCreate(f) #l has parent f
b1 = guitk.BCPushButtonCreate(l) #b1 has parent l
b2 = guitk.BCPushButtonCreate(l) #b2 has parent l and will be placed next
#to or below b1, according l's orientation.

Here is the pseudocode for the layouts example:

Pseudocode for layouts example

w = guitk.BCWindowCreate()
horizontal = guitk.BCBoxLayoutCreate(w) #horizontal layout is the 1st child
guitk.BCLabelCreate(horizontal) #label belongs to horizontal
guitk.BCLineEdit(horizontal) #lineEdit is horizontal's 2nd child
grid = guitk.BCGridLayout(w) #grid layout is placed below horizontal
for row in range(3):
for col in range(3):
but = guitkBCPushButtonCreate(grid) #Create button at (row, col)

ok = guitk.BCPushButtonCreate(w) #'ok' button is BCWindow's 3rd child


cancel = guitk.BCPushButtonCreate(w) #'cancel' button is BCWindow's 4th child

BCGUI functions were built in a way to be immediately comprehensible, even by beginner users.
Help for all BCGUI functions (prototype, arguments, operation etc.) can be found in script editor's help.

The name of a BCGUI function consists of the class it belongs to (e.g. BCLineEdit) plus the action
performed on an object of this class (e.g. SetText). Thus, the function name is BCLineEditSetText.
If a function does not begin with a class name, it means that it is a general function, applicable to all
widgets and layouts (not items). For example BCName function returns the name that may have been set
to a widget or layout by the BCSetName.
Also in case of 'BCPushButtons' and 'BCToolButtons' there are many BCButton... functions, applicable to
both classes of buttons.

From the example above it is concluded that:


all BCGUI functions start with BC.
each different word starts with a capital letter.

Generally, the first argument of functions is the widget, layout on which an action will be performed, or its
parent in case of BC...Create functions.

BETA CAE Systems S.A. 72


ANSA v.14.x Python Programming Interface

9.3 BCGUI examples


In this section some real code examples are presented.

9.3.1 A simple BCWindow


The first example is the code implementation of the pseudocode as presented in the previous section:

def main():
w = guitk.BCWindowCreate('Simple BCWindow', guitk.constants.BCOnExitDestroy)
le = guitk.BCLineEditCreate(w, 'This is a lineEdit')
f = guitk.BCFrameCreate(w)
l = guitk.BCBoxLayoutCreate(f, guitk.constants.BCHorizontal)
b1 = guitk.BCPushButtonCreate(l, "Button 1", None, 0)
b2 = guitk.BCPushButtonCreate(l, "Button 2", None, 0)
guitk.BCShow(w)

In order for a widget to be displayed, BCShow must be called for it. This will trigger a recursive call for the
widget's children as well. In the example above, only one BCShow call for 'BCWindow' 'w' is enough to
show everything that it contains. The 'BCOnExitDestroy' option used in 'BCWindowCreate' means that
when the window closes (by pressing escape <esc>, return or the[x] button) it will be destroyed. The
other available option is the 'BCOnExitHide' but it is strongly recommended to avoid using it, since a
wrong usage may lead to memory leaks.
Note that a 'BCWindow' is good to have a unique name. Any information about the window (e.g size,
position, values of its widgets etc) will be stored in ANSA.xml under this name. However, it must not be
confused with the name of the title bar that can be always changed by using the BCSetCaption.

9.3.2 Creating and using callback functions


In the previous example a 'BCWindow' with 2 “dummy” buttons was created, i.e. on button click no
operation has been defined. This is where the user needs to define callback functions, i.e. functions that
will be called when a user interacts with widgets or items.
Callback functions are defined as normal script functions and their name is passed as a string argument
to the appropriate BCGUI functions, followed by a user argument of any data type (float, string, integer,
matrix etc).
Help about BCGUI callback functions (prototype, arguments etc.) can be found at the end of the
description section of each BCGUI function that uses a callback as an argument.
In the following example, a 'BCWindow' is created with 2 'BCLineEdits' and a 'BCPushButton'. The upper
'BCLineEdit' accepts doubles as input and when <Enter> is pressed the square root calculation of the
current value is triggered, while the calculated value is set to the lower (output) 'BCLineEdit'. When the
'BCPushButton' is pressed, the calculated value is printed in the Output window. In both callback
functions the output 'BCLineEdit' is passed as data.

def calculateFun(le, data):


#le is the input; data is the output

newVal = math.sqrt(guitk.BCLineEditGetDouble(le))#Calculation of the square root


guitk.BCLineEditSetDouble(data, newVal)#Set calculated value to the output lineEdit
return 1 # Returns 1 so that the window will remain open.

BETA CAE Systems S.A. 73


ANSA v.14.x Python Programming Interface

def printFun(button, data): #button is butPrint; data is the output

textToPrint = +The calculated value is ' + str(guitk.BCLineEditGetDouble(data))


print(textToPrint) #Just print the value shown in output lineEdit

def main():
w = guitk.BCWindowCreate('Sqrt calculation', guitk.constants.BCOnExitDestroy)
grid = guitk.BCGridLayoutCreate(w, 2, 2)

input = guitk.BCLineEditCreateDouble(grid, 0)
guitk.BCGridLayoutAddWidget(grid, input, 0, 0,
guitk.constants.BCAlignLeft+guitk.constants.BCAlignVCenter)

output = guitk.BCLineEditCreateDouble(grid, 0)
guitk.BCGridLayoutAddWidget(grid, output, 1, 0,
guitk.constants.BCAlignLeft+guitk.constants.BCAlignVCenter)
//Alignment enumerators OR'ed together
guitk.BCLineEditSetReadOnly(output, 1);

guitk.BCLineEditSetEnterPressedFunction(input, calculateFun, output)

butPrint = guitk.BCPushButtonCreate(grid, '', printFun, output)


guitk.BCButtonSetPixmapFile(butPrint, "print_16.png")
guitk.BCGridLayoutAddWidget(grid, butPrint, 1, 1, guitk.constants.BCAlignCenter)

guitk.BCGridLayoutSetColStretch(grid, 0, 1) #The 1st column should take all


guitk.BCGridLayoutSetColStretch(grid, 1, 0) #the expansion.
guitk.BCDialogButtonBoxCreate(w)
guitk.BCShow(w)

Keep in mind that it is not allowed to pass directly a matrix with its contents to a callback, e.g.:

guitk.BCLineEditSetEnterPressedFunction(input, calculateFun, [output,1])

Important Note: Any changes of the user argument of callbacks can be known to the 'main' function if the
datatype of the argument is defined with the 'byref' statement.

9.3.3 Moving more data around


An alternative way to pass more data to callbacks is to use the BCSetUserDataKey and
BCGetUserDataKey functions. The first one associates key - data pairs (of types string-element) to a
widget or layout and the second one retrieves the data using the corresponding string keys.

def calculateEquation(data):
#Retrieving widgets from BCWindow w (==data)
input = guitk.BCGetUserDataKey(data, "input")
sp1 = guitk.BCGetUserDataKey(data, "sp1")
sp2 = guitk.BCGetUserDataKey(data, "sp2")
lab = guitk.BCGetUserDataKey(data, "lab")
output = guitk.BCGetUserDataKey(data, "output")

#Calculation
d = guitk.BCLineEditGetDouble(input);
if d == 0: return
i_1 = guitk.BCSpinBoxGetInt(sp1)
i_2 = guitk.BCSpinBoxGetInt(sp2)
result = math.power(d, i_1) * math.exp(i_2) / math.log(d)

//Show result

BETA CAE Systems S.A. 74


ANSA v.14.x Python Programming Interface

guitk.BCLabelSetText(lab, d)
guitk.BCLineEditSetDouble(output, result)

def lineEditChangedFun(le, text, data):


#le here is the input lineEdit; data is the w BCWindow

calculateEquation(data)
return 0

def spinBoxChangedFun(sp, val, data):


#sp here could be sp1 or sp2 BCSpinBoxes; data is the w BCWindow
calculateEquation(data)
return 0

def printFun(button, data):


#button here is butPrint; data is the w BCWindow
#Just print the value shown in output lineEdit
output = guitk.BCGetUserDataKey(data, "output")
textToPrint = "The calculated value is " + guitk.BCLineEditGetDouble(output)
print(textToPrint)

def main():
w = guitk.BCWindowCreate("Equation calculation", guitk.constants.BCOnExitDestroy)
l1 = guitk.BCBoxLayoutCreate(w, guitk.constants.BCHorizontal)
input = guitk.constants.BCLineEditCreateDouble(l1, 0)
guitk.BCLineEditSetDouble(input, 1)
guitk.BCLabelCreate(l1, " ^ ")
sp1 = guitk.BCSpinBoxCreate(l1)
guitk.BCSpinBoxSetMinValue(sp1, 2)
guitk.BCSpinBoxSetMaxValue(sp1, 15)
guitk.BCLabelCreate(l1, " * e ^ ")
sp2 = guitk.BCSpinBoxCreate(l1)
guitk.BCSpinBoxSetMinValue(sp2, 1)
guitk.BCSpinBoxSetMaxValue(sp2, 10)
guitk.BCLabelCreate(l1, " / log(")
lab = guitk.BCLabelCreate(l1, guitk.BCLineEditGetText(input))
guitk.BCLabelCreate(l1, ")")
guitk.BCSpacerCreate(w)
l2 = guitk.BCBoxLayoutCreate(w, BCHorizontal)
output = guitk.BCLineEditCreateDouble(l2, 0)
guitk.BCLineEditSetReadOnly(output, 1)
butPrint = guitk.BCPushButtonCreate(l2, None, printFun, w) #You can also set
#the widget before the data assignment
guitk.BCButtonSetPixmapFile(butPrint, "print_16.png")
guitk.BCSpacerCreate(l2) #Horizontal spacer. Keeps output and butPrint to the left

guitk.BCSetUserDataKey(w, "input", input)


guitk.BCSetUserDataKey(w, "sp1", sp1)
guitk.BCSetUserDataKey(w, "sp2", sp2)
guitk.BCSetUserDataKey(w, "lab", lab)#We hold the lab in order to change its text.
guitk.BCSetUserDataKey(w, "output", output)

guitk.BCSpinBoxSetValueChangedFunction(sp1, spinBoxChangedFun, w)
guitk.BCSpinBoxSetValueChangedFunction(sp2, spinBoxChangedFun, w)
guitk.BCLineEditSetTextChangeFunction(input,lineEditChangedFun, w)

guitk.BCDialogButtonBoxCreate(w)
guitk.BCShow(w)

9.3.4 Interacting with ANSA entities


In this example a 'BCListView' is created and filled with all PSHELLs found in the current ANSA database.
If there are too many PSHELLs to process an increasing 'BCProgressBar' that appears in place of
'BCLineEditPath' allows to see them all. After the procedure, the 'BCProgressBar' is replaced again by the
'BCLineEditPath'. A 'BCWidgetStack' was used for this effect.
The items shown on each PSHELL are:

BETA CAE Systems S.A. 75


ANSA v.14.x Python Programming Interface

Elements visibility
Color
PID
Name
Element number
MID
FROZEN_ID

The visibility of PSHELLs can be controlled by the checkboxes.


Double click on an item will open its entity card for editing and on close the item will be updated.
Right click on an item removes it completely from list, without deleting the PSHELL itself. Note the use of
BCTimer in this case.
'Name' can be changed through the list.
'MID' can be changed through the list and a check is made whether the new MID is valid. If not, the old
'MID' is restored and a warning is displayed on the first section of 'BCListViewInfoBox', at the bottom of
'BCListView'.
A multi-condition filter is set to the list.
The 'BCListView' itself is inserted in a 'BCWidgetExpand' widget in order to be expanded to its full size
without resizing the size of its containing 'BCWindow'.
A 'BCLineEditPath' is set on top of the list which can be used to load new ANSA databases that will
trigger a list update.

#Column numbers declaration


COL_NUMS = 7
CHECK_COL = 0
COLOR_COL = 1
PID_COL = 2
NAME_COL = 3
ELEMS_COL = 4
MID_COL = 5
FROZEN_COL = 6

LINE_EDIT_PATH_ID = 0
PROGRESS_BAR_ID = 1

def checkButtonPressedFun(item, state, data):

search_type = ("FACE", "SHELL")


pshell = guitk.BCListViewItemGetUserData(item)
shells = guitk.CollectEntities(constants.NASTRAN, pshell, search_type, True)
if state:
base.ANDEntity(shells)
else:
base.NOTEntity(shells)
#If the property has non-visible elements, uncheck button
if state and not len(shells):
guitk.BCCheckListItemSetOn(item, 0)
base.RedrawAll()

def renameFun(item, column, list):

pshell = guitk.BCListViewItemGetUserData(item);

if column == NAME_COL: #Renaming PSHELL's Name


newName = guitk.BCListViewItemGetText(item, NAME_COL)
SetEntityCardValues(NASTRAN, pshell, "Name", newName)
elif column == MID_COL: #Resetting PSHELL's MID
newMID = guitk.BCListViewItemGetText(item, MID_COL)

mats = base.CollectEntities(constants.NASTRAN, None, "MAT1",False)


i = 0;
ids = list()
for mat in mats:
ids.append(mat._id)

#Check if user inputed MID exists


if not newMID in ids:

BETA CAE Systems S.A. 76


ANSA v.14.x Python Programming Interface

base.SetEntityCardValues(constantsNASTRAN, pshell, {"MID1":newMID})


else:
base.GetEntityCardValues(NASTRAN, pshell, ("MID1",))
guitk.BCListViewItemSetText(item, MID_COL, mid)
guitk.BCListViewInfoBoxSetMessage(list, 0,
"No material with id "+newMID+" exists!")

def updateItem(list, item):

search_type = ("FACE", "SHELL")


pshell = guitk.BCListViewItemGetUserData(item)
ret = base.GetEntityCardValues(constants.NASTRAN,
pshell, ("PID", "MID1", "Name", "FROZEN_ID", "COLOR_R", "COLOR_B", "COLOR_G"))

shells = base.CollectEntities(constants.NASTRAN, pshell, search_type, True)


num = len(shells)

v = None
for ent in shells:
v += IsEntityVisible(ent)

if v: v = 1
base.BCCheckListItemSetOn(item, v)
base.BCListViewItemSetRectangleColor(item, COLOR_COL, ret['color_r'],
ret['color_g'],
ret['color_b'])
base.BCListViewItemSetText(item, PID_COL, ret['PID'])
base.BCListViewItemSetText(item, NAME_COL, ret['Name'])
base.BCListViewItemSetText(item, ELEMS_COL, num)
base.BCListViewItemSetText(item, MID_COL, ret['MID'])
base.BCListViewItemSetText(item, FROZEN_COL, ret['FROZEN_ID'])
base.BCListViewFilterUpdateComboBox(list, FROZEN_COL)

def destroyItem(item):
#Just delete the item, not the PSHELL itself.
BCListViewItemDestroy(item)
return 0

def mouseClickFun(list, mb, eitem, col, data):


if !item: return 0

if mb == BCRightButton: guitk.BCTimerSingleShot(0, "destroyItem", item)


return 0

def doubleClickFun(list, item, int col, element data):


if !item: return 1

pshell = guitk.BCListViewItemGetUserData(item)
base.EditEntity(pshell)
updateItem(list, item) #Update item after a possible editing.
return 1

def updateList(element list):


base.BCListViewClear(list)
ws = base.BCGetUserDataKey(list, "ws");
pb = base.BCWidgetStackWidget(ws, PROGRESS_BAR_ID) #Getting the BCProgressBar
with its id
base.BCWidgetStackRaiseId(ws, PROGRESS_BAR_ID)
base.BCProgressBarSetProgress(pb, 0)

search_type[ = ("PSHELL",)
pshells = CollectEntities(NASTRAN, None, search_type, False)
BCProgressBarSetTotalSteps(pb, len(pshells))
search_type = ("FACE", "SHELL")

rename = (0, 0, 0, 3, 0, 2, 0)
for pshell in pshells:

BETA CAE Systems S.A. 77


ANSA v.14.x Python Programming Interface

shells = base.CollectEntities(constants,NASTRAN, pshell, search_type, True)


ret = base.GetEntityCardValues(constants.NASTRAN, pshell, ("PID", pid, "MID1",
mid, "Name", "FROZEN_ID", "COLOR_R", "COLOR_B", "COLOR_G"))

titles = ["", "", ret['PID'], ret['Name'], num, ret['MID'], ret['FROZEN_ID']]


item = base.BCListViewAddCheckItem(list, COL_NUMS, titles, rename)
base.BCListViewItemSetUserData(item, pshell)
base.BCListViewItemSetRectangleColor(item, COLOR_COL, ret['COLOR_R'],
ret['COLOR_G'],
ret['COLOR_B'])
base.BCListViewItemSetRenamedFunction(item, renameFun, list)

#Check if current pshell has any visible entities


v = 0;
for ent in shells:
v += IsEntityVisible(ent)

if v: v = 1

#Update progressBar
current = base.BCProgressBarProgress(pb)
base.BCProgressBarSetProgress(pb, current+1)

base.BCCheckListItemSetOn(item, v)
base.BCCheckListItemSetStateChangedFunction(item, checkButtonPressedFun, 0)
i += 1

base.BCListViewFilterUpdateComboBox(list, FROZEN_COL)
base.BCWidgetStackRaiseId(ws, LINE_EDIT_PATH_ID)

def onEnterFun(element le, element list):


#Open file and update list
file = guitk.BCLineEditGetText(le)
print(file)
base.Open(file)
updateList(list)
return 1

def clearListFun(b, list):


guitk.BCListViewClear(list)

def main ():


titles = ("Visible", "Color", "PID", "Name", "Elements", "MID", "FROZEN_ID")

base.SetCurrentDeck(constants.NASTRAN)
w = guitk.BCWindowCreate("PIDs list", guitk.constants.BCOnExitDestroy)

//Create a widgetStack to place a BCLineEditPath and a BCProgressBar


ws = guitk.BCWidgetStackCreate(w)
lep = guitk.BCLineEditPathCreate(w, 1, base.DataBaseName(),
0, "ANSA_Example_lineEditPath")
guitk.BCWidgetStackAddWidget(ws, lep, LINE_EDIT_PATH_ID)
pb = guitk.BCProgressBarCreate(ws, 0)
guitk.BCWidgetStackAddWidget(ws, pb, PROGRESS_BAR_ID)
guitk.BCWidgetStackRaiseWidget(ws, lep);

#The list will be controlled by BCWidgetExpand we


we = guitk.BCWidgetExpandCreate(w);
list = guitk.BCListViewCreate(we, COL_NUMS, titles, 0);
guitk.BCWidgetExpandSetWidget(we, list);

#Setting BCLineEditPath
combo = guitk.BCLineEditPathGetCombo(lep);
guitk.BCComboBoxSetSizePolicy(combo, guitk.constants.BCExpanding,
guitk.constants.BCExpanding) //You can resize lep to minimum
le = guitk.BCComboBoxGetLineEdit(combo);
guitk.BCLineEditSetExtentionsFilter(le, ("ansa",)) #Show only *.ansa files

BETA CAE Systems S.A. 78


ANSA v.14.x Python Programming Interface

#The file selected by file manager will update the list, as well
guitk.BCLineEditPathSetDialogEnterEnabled(lep, 1)
guitk.BCLineEditPathSetEnterPressedFunction(lep, "onEnterFun", list)

#Set the alignment of data shown in each column.


guitk.BCListViewSetColumnAlignment(list, PID_COL, guitk.constants.BCAlignRight)
guitk.BCListViewSetColumnAlignment(list, ELEMS_COL, guitk.constants.BCAlignRight)
guitk.BCListViewSetColumnAlignment(list, MID_COL, guitk.constants.BCAlignRight)
guitk.BCListViewSetColumnAlignment(list, FROZEN_COL,
guitk.constants.BCAlignCenter)

#Set the multi condition filter.


BCListViewSetFilterEnabled(list, 1);
BCListViewSetColumnDataTypes(list, (guitk.constants.BCInvalid,
guitk.constants.BCInvalid,
guitk.constants.BCInt,
guitk.constants.BCString, guitk.constants.BCInt,
guitk.constants.BCInt, guitk.constants.BCBool))
guitk.BCListViewFilterSetColumnEnabled(list, CHECK_COL, 0)
guitk.BCListViewFilterSetColumnEnabled(list, COLOR_COL, 0)
guitk.BCListViewFilterSetComboBox(list, FROZEN_COL)

#Set a BCListViewInfoBox and a DoubleClickedFunction


guitk.BCListViewInfoBoxCreate(w, list)
guitk.BCListViewSetDoubleClickedFunction(list, doubleClickFun, 0)
guitk.BCListViewSetMouseClickedFunction(list, mouseClickFun, 0)

BCSetUserDataKey(list, "ws", ws) #We will need lep in updateList


updateList(list)

ddb = guitk.BCDialogButtonBoxCreate(w)
clear = guitk.BCPushButtonCreate(ddb, "Clear list", clearListFun, list)
guitk.BCDialogButtonBoxAddButton(ddb, clear)

guitk.BCShow(w)

On script run the 'BCWindow' containing the 'BCListView' and other widgets is created, showing the
PSHELLs of the current database. It is then docked by the user to the left docking area and resized to
minimum width in order to save space for the drawing area. The use of 'BCWidgetExpand' tool is shown
here:

Controlling the PSHELLs visibility through the 'BCListView'.

BETA CAE Systems S.A. 79


ANSA v.14.x Python Programming Interface

Renaming PSHELLs through the 'BCListView'.

Changing the MID attribute of a PSHELL. An invalid MID is given (4).

After 'Enter' was pressed the MID changed back to its original value and a warning appeared in the
'BCListViewInfoBox'.

The PSHELL card appears on double-click and the FROZEN_ID value is changed to 'YES'.

BETA CAE Systems S.A. 80


ANSA v.14.x Python Programming Interface

The 'BCListView' is updated after closing the card.

9.3.5 Advanced BCGUI functionality


This example demonstrates how widgets can be placed inside container widgets, such as
'BCDrawerGrids', 'BCToolBoxes' and 'BCTabWidgets'. It also demonstrates how the widgets' state can be
saved in the current xml file (apart from the 'BCWindow's' position and size, which is done automatically)
and retrieve it on demand. Finally, some interesting ways of controlling and displaying data are shown.
For simplicity reasons most callback functions have been omitted.
A 'BCWindow' is created under the name 'AutoSavingSettings'. It contains a 'BCTabWidget' with 2 tabs.
The first contains a 'BCToolBox' and the other a 'BCButtonLineEdit' with a calculator button, a
'BCGridLayout' with 9 'BCPushButtons', a 'BCTextEdit' and 'BCLabelTicker' (i.e. a 'BCLabel' whose text
can scroll when mouse pointer is over it and can be dragged to the left or to the right).
Only the first tab's widgets' state can be saved to and read from xml, that's why the 2 extra buttons in
'BCDialogButtonBox' are enabled only when this tab is current.

BETA CAE Systems S.A. 81


ANSA v.14.x Python Programming Interface

The 'BCWindow' flashes when 'Enter' is pressed


with an invalid 'BCSpinBox' value.

When the current tab changes, the 'BCCaption' of 'BCWindow' (the title) changes as well to the tab's
label. Nevertheless, its 'BCName' ('AutoSavingSettings') must never change and it must be unique, i.e. no
other window with the same 'BCName' should exist in ANSA. The reason for this is that all settings are
saved to xml under this name.
A control has been set for closing 'BCWindow's' when pressing 'Enter'. Normally, a window closes on
'Enter' unless a BCWindowSetCheckFunction or a BCWindowSetAcceptFunction are set. In this case
the first one must be used, and the 'BCWindow's' exit is controlled by the current value of the 'BCSpinBox'
found in the “Red frame”. If it is higher than 6, a warning appears in ANSA Info , the 'BCWindow' flashes
and stays open.
Initially, the 'BCComboBox' in the “Green frame” has 3 options: 'All', 'None' and 'Write Protected'. The first
2 operate as normal 'comboBox' options. If the last is selected a 'BCPopupMenu' appears containing a
hierarchical 'BCListView' and a 'BCPushButton' at the bottom. In this way any options offered by a
'BCComboBox' can be refined to the finest detail.

#Creation of the BCPopupMenu


def fillList(lview):
num = 8;
rename = (0,)
iName = ("tmpItem",)

for i in range(num):
lvitem = guitk.BCListViewAddItem(lview, 1, iName, rename)
guitk.BCListViewItemAddItem(lvitem, 1, iName, rename)

def comboActFun(combo, index, data):


title = ("",)
if index == 0: #Write Protected
popup = guitk.BCPopupMenuCreate(combo)
frame = guitk.BCFrameCreate(popup)
vbox = guitk.BCBoxLayoutCreate(frame, guitk.constants.BCVertical)
guitk.BCBoxLayoutSetMargin(vbox, 0)
guitk.BCBoxLayoutSetSpacing(vbox, 0)
lview = guitk.BCListViewCreate(vbox, 1, title, 1)
guitk.BCListViewSetResizeMode(lview, guitk.constants.BCLastColumn)
guitk.BCListViewHeaderHide(lview)
guitk.BCListViewSetIsRootDecorated(lview, 1)
guitk.BCListViewSetSelectionMode(lview, guitk.constants.BCMulti)
guitk.BCListViewSetSortingColumn(lview, 0, 1)
ok_but = BCPushButtonCreate(vbox, "OK", "", 0)
fillList(lview)
guitk.BCPopupMenuInsertWidget(popup, frame)
guitk.BCPopupMenuPopupToParentWidget(popup)

BETA CAE Systems S.A. 82


ANSA v.14.x Python Programming Interface

def radioButtonGroupPressed(bgroup, index, data):


i = index + 1
print("radioButtonGroupPressed " + i)

def toolboxCreation(window, element vb):


numButtons = 4
wp = "Write Protected"
a = "All"
none = "None";
comboVals = (wp, a, none)

guitk.BCLabelCreate(vb, "Default Widgets")


#Create the whole toolBox
toolBox = guitk.BCToolBoxCreate(vb)
blueFrame = guitk.BCFrameCreate(vb)
guitk.BCBoxLayoutCreate(blueFrame, BCVertical)
guitk.BCSetBackgroundColor(blueFrame, 160, 160, 255)
redFrame = guitk.BCFrameCreate(vb)
guitk.BCSetBackgroundColor(redFrame, 255, 160, 160)
guitk.BCBoxLayoutCreate(redFrame, BCHorizontal);
greenFrame = guitk.BCFrameCreate(vb)
guitk.BCSetBackgroundColor(greenFrame, 160, 255, 160)
guitk.BCBoxLayoutCreate(greenFrame, BCHorizontal)
guitk.BCToolBoxAddItem(toolBox, blueFrame, "Blue frame")
guitk.BCToolBoxAddItem(toolBox, redFrame, "Red frame")
guitk.BCToolBoxAddItem(toolBox, greenFrame, "Green frame")

#'Blue frame'
#Check out the widget setting to a BCDrawerGridCreate
drawer = guitk.BCDrawerGridCreate(blueFrame)
checkFrame = guitk.BCFrameCreate(drawer)
guitk.BCBoxLayoutCreate(checkFrame, guitk.constants,BCHorizontal)
checkBoxA = guitk.BCCheckBoxCreate(checkFrame, "CheckBox A")
checkBoxB = guitk.BCCheckBoxCreate(checkFrame, "CheckBox B")
checkBoxC = guitk.BCCheckBoxCreate(checkFrame, "CheckBox C")
bgroup = guitk.BCButtonGroupCreate(drawer, "Exclusive Radios",
guitk.constants.BCVertical)
guitk.BCButtonGroupSetCheckable(bgroup, 1)
for i in range(numButtons):
ii = i + 1
name = "RadioButton " + str(ii)
rb = guitk.BCRadioButtonCreate(bgroup, name, "", 0)
guitk.BCRadioButtonSetPressFunction(rb, "", 0)
guitk.BCButtonGroupInsert(bgroup, rb, i)

guitk.BCButtonGroupSetPressedFunction(bgroup, "radioButtonGroupPressed", 0)
buttonFrame = guitk.BCFrameCreate(drawer)
guitk.BCBoxLayoutCreate(buttonFrame, guitk.constants.BCHorizontal)
toggleButton1 = guitk.BCPushButtonCreate(buttonFrame, "toggleButton1", "", 0)
guitk.BCRadioButtonAddManagedWidget(rb, toggleButton1, BCManagedShow,
BCManagedHide)
toggleButton2 = guitk.BCToolButtonCreate(buttonFrame, "filter_16.png",
"toggleButton2", "", 0)
guitk.BCButtonSetToggleButton(toggleButton1, 1)
guitk.BCDrawerGridInsertWidget(drawer, checkFrame, 1, "CheckBoxes")
guitk.BCDrawerGridInsertStableWidget(drawer, bgroup)
guitk.BCDrawerGridInsertWidget(drawer, buttonFrame, 1, "Buttons")

#'Red frame'
guitk.BCLabelCreate(redFrame, "Degrees");
spin = guitk.BCSpinBoxCreate(redFrame);
guitk.BCSetUserDataKey(window, "spin", spin);

#'Green frame'
guitk.BCLabelCreate(greenFrame, "Include Files")
combo = guitk.BCComboBoxCreate(greenFrame, comboVals)
guitk.BCComboBoxSetActivatedFunction(combo, "comboActFun", 0)

//This is for reading and saving to xml


guitk.BCSetSaveSettings(toolBox, "coloredToolBox")

BETA CAE Systems S.A. 83


ANSA v.14.x Python Programming Interface

guitk.BCSetSaveSettings(checkBoxA, "CheckBox A")


guitk.BCSetSaveSettings(checkBoxB, "CheckBox B")
guitk.BCSetSaveSettings(checkBoxC, "CheckBox C")
guitk.BCSetSaveSettings(bgroup, "Exclusive Radios")
guitk.BCSetSaveSettings(toggleButton1, "toggleButton1")
guitk.BCSetSaveSettings(toggleButton2, "toggleButton2")
guitk.BCSetSaveSettings(spin, "Degrees")
guitk.BCSetSaveSettings(combo, "writeProperties")

def calcCallBack(button, data):


#The callback that creates and shows a BCCalculator connected to the BCLineEdit
calcWin = guitk.BCWindowCreate("Calculator", guitk.constants.BCOnExitDestroy)
calc = guitk.BCCalculatorCreate(calcWin)
guitk.BCCalculatorConnectWithButtonLineEdit(calc, data)
guitk.BCShow(calcWin)
return 1

def buttonsCreation(window, vb2):


#Create BCButtonLineEdit with calculator
leCalc = guitk.BCButtonLineEditCreate(vb2, "")
buttonCalc = guitk.BCToolButtonCreate(leCalc, "calculator_16.png", "",
"calcCallBack", leCalc)
guitk.BCButtonLineEditAddRightButton(leCalc, buttonCalc)

//Create dummy buttons in a gridLayout


g = guitk.BCGridLayoutCreate(vb2, 3, 3)
for r in range(3):
for c in range(3):
b = guitk.BCPushButtonCreate(g, "button_"+r+"_"+c, "", 0)
guitk.BCGridLayoutAddWidget(g, b, r, c, guitk.constants.BCAlignCenter)

guitk.BCTextEditCreate(vb2, "")
guitk.BCLabelTickerCreate(vb2, "BCTicker has the ability to scroll from left to
right if the text can not fit in the widget`s width.
User can also scroll left or right by pressing (and keep pressed) the left mouse
button and moving the cursor right or left.")

def tabChangedFun(tw, oldPage, newPage, window):


readOnDemand = guitk.BCGetUserDataKey(window, "readOnDemand")
saveOnDemand = guitk.BCGetUserDataKey(window, "saveOnDemand")
vb1 = guitk.BCGetUserDataKey(window, "vb1")
if newPage == vb1:
e = 1
else:
e = 0
#Disable read and save button for second tab, since they are not applicable
guitk.BCSetEnabled(readOnDemand, e)
guitk.BCSetEnabled(saveOnDemand, e)
guitk.BCSetCaption(window, guitk.BCTabWidgetGetTabLabel(tw, newPage))

def checkWindow(wid, usd):


spin = guitk.BCGetUserDataKey(wid, "spin")
if guitk.BCSpinBoxGetInt(spin) > 6:
guitk.BCWindowFlash(wid) #That's a flashy feature...
return "The spin box value is too high!"
return ""

def readSettingsOnDemand(b, window):


guitk.BCWindowReadControlSettings(window)

def saveSettingsOnDemand(b, window):


guitk.BCWindowSaveControlSettings(window)

def main():
window = guitk.BCWindowCreate("AutoSavingSettings",
guitk.constants.BCOnExitDestroy)

BETA CAE Systems S.A. 84


ANSA v.14.x Python Programming Interface

#Check on 'Enter' press


guitk.BCWindowSetCheckFunction(window, "checkWindow", 0)

#Do save settings to xml


guitk.BCWindowSetSaveSettings(window, 1)
#Creation of BCTabWidget
tw = guitk.BCTabWidgetCreate(window)
vb1 = guitk.BCVBoxCreate(tw)
guitk.toolboxCreation(window, vb1)
guitk.BCTabWidgetAddTab(tw, vb1, "toolBox")
#NOTE: We create a BCFrame to be able to insert a gridLayout.
vb2 = guitk.BCFrameCreate(tw)
guitk.BCBoxLayoutCreate(vb2, guitk.constants.BCVertical)
buttonsCreation(window, vb2)
guitk.BCTabWidgetAddTab(tw, vb2, "buttons and textEdit")
guitk.BCTabWidgetSetTabMovingEnabled(tw, 1)
guitk.BCTabWidgetSetCurrentTab(tw, vb1)

#Creation of BCDialogButtonBox with the 2 extra buttons


dbb = guitk.BCDialogButtonBoxCreate(window)
readOnDemand = guitk.BCPushButtonCreate(dbb, "Read On Demand",
readSettingsOnDemand, window);
saveOnDemand = guitk.BCPushButtonCreate(dbb, "Save On Demand",
saveSettingsOnDemand, window)
guitk.BCDialogButtonBoxAddButton(dbb, readOnDemand)
guitk.BCDialogButtonBoxAddButton(dbb, saveOnDemand)

#Setting the CurrentChangedFunction


guitk.BCSetUserDataKey(window, readOnDemand, readOnDemand)
guitk.BCSetUserDataKey(window, saveOnDemand, saveOnDemand)
guitk.BCSetUserDataKey(window, vb1, vb1)
guitk.BCTabWidgetSetCurrentChangedFunction(tw, tabChangedFun, window)
guitk.BCShow(window)

BETA CAE Systems S.A. 85


ANSA v.14.x Python Programming Interface

10. Script Editor


10.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 tool are
highlighted and briefly described below.

Main Menu Contains the script editor functions


Main Window The area where the code is written or tested
Shortcut Keys 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
Help This area has a double use. When the Help tab is active it
Output Area 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
Dynamic Help List This area contains all available built in functions. Additionally, a
Functions List dynamic help is always displayed whenever a function name is
written correctly in the main window

10.2 Opening scripts

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

BETA CAE Systems S.A. 86


ANSA v.14.x Python Programming Interface

10.3 Running scripts

By default, if the script contains a function called 'main', then every time the F5 button is pressed this
particular function is executed. However, if the user add the keyword entrypoint in front of the def
statement of a function, then this function becomes stronger than 'main' and it will be finally executed if
the F5 will be pressed.

entrypoint def test()


{
Print("....");
}

In the most general case, any function regardless of its name, can be executed through the Debug>Run
function which acts similar to File>Script>Run function (see section 5.2.1). Any syntax errors are
reported in the output area.

10.4 The immediate tab


For testing functions or a few lines of code the immediate tab can be used. For simplicity, if it is active, the
code inside is not allowed to have any def statement (see section 2.9.1). 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 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.

10.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 1: 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.
Important Note 2: A color code indicates the built in commands and the reserved keywords.

BETA CAE Systems S.A. 87


ANSA v.14.x Python Programming Interface

10.6 Compiled scripts


Compilation of scripts is possible through the Project>Compile. A compiled script can be loaded and run
throughout all the normal ways (command line, script menu) except the Script Editor. Furthermore, all the
functions that holds can be called from any other script even from decompiled ones.

Important Note 1: A compiled script can be used as projectfile but not as include file.
Important Note 2: Scripts can be compiled normally even if they contain #include or #projectfile
statements.

10.7 Making and importing snippets


Snippets are sections of code or complete 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 mostly used. 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.

Selecting 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.
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 snippets 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.

BETA CAE Systems S.A. 88


ANSA v.14.x Python Programming Interface

10.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 an xml project 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.

10.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 an
ANSA_TRANSL file is going to be created, so the respective check button is deactivated.

After pressing ok, a file named ANSA_TRANSL.bpr is created in the selected folder. This is the project
file and initially has the following form:

BETA CAE Systems S.A. 89


ANSA v.14.x Python Programming Interface

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.

10.8.2 Adding existing 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:

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:

BETA CAE Systems S.A. 90


ANSA v.14.x Python Programming Interface

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.

10.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 not 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 the right window is opened 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. 91


ANSA v.14.x Python Programming Interface

10.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:

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

10.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 (see section 10.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.

BETA CAE Systems S.A. 92


ANSA v.14.x Python Programming Interface

10.9 Debugging scripts


Scripts can run in two ways. First, the ‘normal’ run, executes the code directly. Second in debug mode,
the debugger executes the code line by line. In the later case the execution of a script can be paused 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, the first step is to identify the variables that
produce the error, otherwise if there is no such clue, the most important of them are selected. Next, they
are added in the watch list where it is easy to inspect their history during the execution of the script. A
variable can be added in the watch list using the Add watch option located under the right mouse button
menu.

In the above example the cursor is pointing on variable b and therefore when selecting on the menu that
opens the option Add watch: main::b, b 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, the lines where the execution of the script will be paused must be selected. After each stop any
change of the variable can be viewed in the list. 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.

BETA CAE Systems S.A. 93


ANSA v.14.x Python Programming Interface

For running the function in debug mode the button must be pressed. Alternatively, press {Shift+F5}
or Debug>Debug.

Important Note: The name of the function must be 'main'

Suppose that any changes of matrix b'. must be traced. Insert a breakpoint in line 5 and open the watch
window. Press <Shift+F5> to run in debug mode. The execution stops in line 5 and the current status of
'b' is displayed in watch window. From now on every time the button or <F10> is pressed, the
execution continues and stops in each line. Pressing anytime the button , the script runs without stop until
the end. In the example, after the second stop the matrix 'b' holds the first two values {10,13}.

Keep pressing or until the execution is finished.

Important Note: When the execution stops over a breakpoint, the line is colored blue.

If the 'watched' variable is not in the "main" function but in a sub function, the debugger cannot reach it
unless the way that searches the code is changed. 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 it with an example:
Assume that the 'watched' variable 'k' is located in sub function 'foo'. Set a breakpoint in a line prior to
'foo' call (line 6) and press <Shift+F5>. The execution stops in this line and from that point press the
button until the debugger gets inside 'foo'.

Pressing anytime returns to the "main" function.

BETA CAE Systems S.A. 94


ANSA v.14.x Python Programming Interface

11. BCGUI Designer


11.1 General
The designer is a tool that enables the easy generation of windows using a graphical user interface. The
functions used for creating the interface belong to the BCGUI function group that was presented in
section 9. The great advantage of the designer is the automatic generation of code that reduces the
preparation time of a script. The following paragraphs will focus in the presentation of the designer's
interface but without any particular emphasis on the BCGUI functions that are used in the background.

11.2 The Designer's interface


The designer is accessed through the Script Editor with the function Tools>Designer. It's interface as
initially is launched, contains the following sections:

ToolBox
This is the window that hosts all the functions for creating widgets, layouts or items.

List with Constructed Items


This is a tree list with all created items.

Common Parameters (BC)


This window lists all the parameters that are common for each BCGUI item.

Parameters
This window displays all the parameters related to the selected item of the List with Constructed Items
window.

CallBack Functions
This is the window where it hosts all created callback functions.

Source Code
This is the area where the automatically created code resides.

Help
This is the area where the help text of the selected parameter is displayed.

BETA CAE Systems S.A. 95


ANSA v.14.x Python Programming Interface

11.2.1 ToolBox
The ToolBox is the starting point of all actions performed in designer. It hosts in separate tabs all the
necessary functions for creating the main window, buttons, containers, views, widgets and input items.
Initially, only the Window tab is active since this will create the window that will be used as the parent of
all features. Expand the Window tree and press the Apply Settings button to create the main window
with the name 'TopWindow'.

This will make the rest of categories available.

Expanding any object under any category will reveal a set of basic options necessary for the creation of
the object. These options are actually the input arguments of a BCGUI function and thus they are
characterized by their type (integer, string, element etc) and their value. The options initially have the
default values but they can be also set up by the user, except those that are of element type. The button
Apply Settings always creates the object. In the following example a button and a check box have been
created under the top window.

BETA CAE Systems S.A. 96


ANSA v.14.x Python Programming Interface

The parent object controls the objects' order. As it is shown above, any object that is added directly to the
top window is distributed vertically. To control the order create a predefined horizontal HBox or a vertical
box layout VBox, or a BoxLayout with controllable orientation and add the two widgets within.

11.2.2 List of Constructed Items


All the created objects are listed under the List of Constructed Items. The list has a tree structure where
it is easy to recognize any parent-child relationship or objects' classes.

BETA CAE Systems S.A. 97


ANSA v.14.x Python Programming Interface

Actions like drug and drop are allowed and thus the position of an object can be altered any time.

Pressing on an object of the list, highlights with yellow the corresponding object of the TopWindow. On
the contrary, pressing <Ctrl+Left mouse button> over an object of the TopWindow, highlights the object
on the list.

Any object can be deleted either pressing the Delete button of the keyboard or with the Delete Item
option under the right mouse button

11.2.3 Common Parameters (BC)


The Common Parameters (BC) window lists all the options that are considered as common for all
individual objects. The name and the input arguments of the parameters are displayed in two separate
columns.

BETA CAE Systems S.A. 98


ANSA v.14.x Python Programming Interface

In order to change the default parameter options, expand the parameter and type where it is allowed the
new value. At the end, press the Apply Settings button to confirm the changes. In the following image, a
tooltip is going to be added for the button 'BCPushButton_1'. Select the button object from the List With
Constructed Items or from the screen and type the tooltip text under the Values column of the tip
parameter. After confirmation, place the cursor over the button to see the tooltip.

11.2.4 Parameters
The Parameters window lists all the unique options of a selected object. As soon as an object is selected
either from the screen or from the List With Constructed Items, the title of the Parameters window and
the actual parameters change accordingly. The picture below shows the Parameters window when the
check box is selected. The name and the input arguments of the parameters are displayed in two
separate columns.

BETA CAE Systems S.A. 99


ANSA v.14.x Python Programming Interface

The name of each parameter describes its use.


As in any other list of parameters , the corresponding options have the default values but they can get
new ones by the user. For example, to change the name of the button expand the 'ButtonSetText' and
type a new value for the option 'text'. At the end, press the Apply Settings button to confirm the changes.

11.2.5 CallBack Functions


Those parameters that their name ends in 'Function', set up the callback functions of the object (see
section 9.3.2). In order to find all parameters related to callback functions, activate the filter and type
'function' in the Parameters field:

Two callbacks of different type have been filtered. The user can change any option according to his
needs. When the Apply Settings button is pressed the callback type and its name automatically are
listed under the CallBack window. The title of the window indicates the parent object type:

The last argument of all callback functions can be of any type and corresponds to user data.

BETA CAE Systems S.A. 100


ANSA v.14.x Python Programming Interface

11.2.6 Help area


Each parameter corresponds to a BCGUI function. Selecting either a common parameter or a unique
parameter, the Help area displays the help text of the parameter-function.

The help text of functions that set up callbacks, contain also the syntax of the callback. Thus, the user is
also informed about the input arguments and the return values of it.

11.2.7 Source Code area


The Source Code window is the area where the designer automatically writes the code as soon as an
action is performed. An action is performed every time the Apply Settings button is pressed or when the
tree under the List With Constructed Items is updated with manual movements. The generated code
consists of one main function and any number of callback functions.

BETA CAE Systems S.A. 101


ANSA v.14.x Python Programming Interface

The source code is not editable and changes automatically only when an action is performed or when an
object is deleted. However, it can be totally cleared without destroying the created window through the
Code>Clear Source Code. The next time an action will be performed, the source code will be again
generated.

11.2.8 Editing the source code


The source code, including the main function and the callbacks that are constructed by the designer tool,
will be probably only a small portion of an extensive script. The rest of the code must be manually added
by the user through the script editor. The script code can be saved as any other script through the
File>Save and then can be reopened by the script editor for further editing. Alternatively, it can be directly
sent to the editor through the Code>Set Code to Script Editor.

Replace the 'add_function_name' with 'main' and run the code in order to launch the created interface.
Important Note: The designer cannot be used for opening scripts unless it is free of user defined code.

BETA CAE Systems S.A. 102

You might also like