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

Beta_script_to_python_conversion_guide (1)

fghjkk

Uploaded by

pablo.souza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Beta_script_to_python_conversion_guide (1)

fghjkk

Uploaded by

pablo.souza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

BETA Script to Python

Conversion Guide
ANSA Application Programming Interface
Introduction
Beginning with ANSA and META v14.0 the Python programming language is embedded in
both programs.
ANSA and META scripting is now Python scripting.
The old BETA Script language is still supported and will be supported for as long as
possible.
Users are recommended to switch to Python Scripting as soon as possible, since Python
is now the main scripting language.

The Python version embedded in ANSA and META is Python v3.3.0

BETA Script to Python Conversion Guide 2


BETA Script to Python
Documentation

Python v3.3 is embedded in ANSA and META. For additional help in Python language
features and functionality please refer to:
• python.org
• stackoverflow.com
or simply do a Google search with your python related query

Documentation on the ANSA and META libraries of functions are available in the online
script help of each program and on the respective scripting guides of their installation
directory

BETA Script to Python Conversion Guide 3


BETA Script to Python
Data Types Differences
In both languages, variables are type-less and dynamic. Floats and integers are
defined in a similar way. Python has two additional data types complex and bool.

complex c = 4 + 3j

bool b = True

Integer division
In Python (version 3) all divisions, by default, are floating point divisions. Thus
3/2 = 1.5
In order to perform integer division the use of // is needed. i.e 3//2 = 1

BETA Script to Python Conversion Guide 4


BETA Script to Python
String differences

Strings behaviour is similar in both languages. A few differences are shown below:
s = „Earth‟
String ranges are requested with s[0:4] syntax. This range is closed on the left side
and open on the right side [0,4). Thus printing this in python we get:
print(s[0:4])
>>„Eart‟ #print result
In a string concatenation, non string variables need to be converted to a string
before they can be concatenated
x = 4.5
y = „Earth‟
z = y+str(4.5)
Strings can be created with both single and double quotes
x = „Earth‟
y = “Earth”

BETA Script to Python Conversion Guide 5


BETA Script to Python
From Matrix to List
The List data structure is the python equivalent of the BETA Script Matrix
Creating a matrix in BETA Script:
BETA Script myMatrix = {1, 2.3, “world”,{2,3.7,8.5}};

Creating a list in Python:


Python myList = [1, 2.3, „world‟,[2,3.7,8.5]]

Adding a member into a matrix:


BETA Script myMatrix[4] = “earth”;
Adding a member into a list:
Python myList.append(„earth‟)
Creating an empty matrix:
BETA Script myMatrix = {};
Creating an empty list:
Python myList = [] or myList = list()

BETA Script to Python Conversion Guide 6


BETA Script to Python
From Map to Dictionary
The Dictionary data structure is the python equivalent of the BETA Script Map
In BETA Script a Map needs to be initialized as follows
BETA Script myMap = CreateMap();

In Python a Dictionary can be initialized either empty or with values.


Python myDict = dict()
myDict = {}
myDict = {„planet‟:‟earth‟,‟circum‟:40075}

The way new member are added in a dictionary is similar for both languages
BETA Sript myMap = CreateMap();
myMap[“planet”] = “earth”;
myMap[“circum”] = 40075;

Python myDict = dict()


myDict[„planet‟] = „earth‟
myDict[„circum‟] = 40075
BETA Script to Python Conversion Guide 7
BETA Script to Python
Additional Containers
Some brief information about some additional python containers
Tuple
A tuple is a non-homogeneous ordered immutable sequence. A tuple can contain
any type of objects and data types such as integers, float, other lists custom
objects. Once created it cannot be mutated
myTuple = (2,3.6,(„hello‟,‟word‟,5))

Set
A set is a non-homogeneous un-ordered mutable sequence. All the members of a
set are unique. There are no duplicate values.
mySet = {1, 2.3, „world‟}

BETA Script to Python Conversion Guide 8


BETA Script to Python
Container length – From MatLen to len
In Python the length of a container is measured by the len() function. This function
is common for strings, lists, dictionaries etc. This is the equivalent to BETA Script’s
MatLen
Python len(my_list)

The “in” operator


The “in” operator is a membership test operator. It looks quickly to find if a given
object exists inside a container such as a list or a dictionary

if „earth‟ in myList
if „pid‟ in myDict

Deletion of data
The del statement is used to delete references
del data[k]
del data[i:j]
del obj.attr
del variable
BETA Script to Python Conversion Guide 9
BETA Script to Python
General coding Syntax
The most noticeable difference between BETA Script and Python is the absence of
curly braces ({}) in python. New blocks in python are defined by (:) followed by
indentation in the next line

BETA Script Python


def main() def main():
{ x = 5
x = 5; if x > 3:
if (x > 3) { print(„OK‟)
Print(“OK”); else:
} else { print(„not OK‟)
Print(“not OK”); return 0
}
return 0;
}

Python statements do NOT end with a semicolon (;)


If statements do not require a parenthesis

BETA Script to Python Conversion Guide 10


BETA Script to Python
“if-else” blocks in Python
if all_nodes > 99 and all_nodes < 200:
print(„Nodes are in range 100-200‟)
range_100 = 1
elif all_nodes > 200:
print(„Nodes are in range of greater than 200‟)
else:
print („Nodes fewer than 100‟)
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
BETA Script to Python Conversion Guide 11
BETA Script to Python
Loop statements
Fast iteration of a list:

BETA Script Python


my_mat = {5,6.7,97,”earth”,”sun”}; my_list = [5,6.7,97,‟earth‟,„sun‟]
foreach val in my_mat { for val in my_list:
Print(val); print(val)
}

Dictionary iteration:
BETA Script
my_map = CreateMap();

for (ret=GetFirstNode(my_map,key,data);ret;ret=GetNextNode(my_map,key,data)){
Print(key);
Print(data);
}

Python
my_dict = {„Name‟:‟aluminum‟, „pid‟:19987, „thick‟:1.83}
for key,val in my_dict.items():
print(key)
print(val)

BETA Script to Python Conversion Guide 12


BETA Script to Python
Loop statements - More on the for loop
The for loop is very different in python. The limits and the rest of the loop are
managed by the range() function or any other iterable object

range(start_value, end_value, step)

Example of a for loop:

BETA Script Python


n=1 num_list = list()
for (i=0;i<100;i++) { for i in range(1,100,2):
m[i]=n; num_list.append(i)
n += 2
}

BETA Script to Python Conversion Guide 13


BETA Script to Python
Function Calls
In Python function arguments do not have their type stated

BETA Script Python


def main() def CalcSum(x,y):
{ return x+y
a = 3.1;
b = 2.4; def main():
sum = CalcSum(a,b); a = 3.1
} b = 2.4
sum = CalcSum(a,b)
def CalcSum(float x, float y)
{
return x+y;
}

BETA Script to Python Conversion Guide 14


BETA Script to Python
Positional, Named and Optional Arguments
CalcType is called by positional CalcType is called by named arguments
arguments
def Calc(x,y, cal_type): def Calc(x,y, cal_type):
if cal_type == „add‟: if cal_type == „add‟:
return x+y return x+y
elif cal_type == „sub‟: elif cal_type == „sub‟:
return x-y return x-y
else: else:
return x/y return x/y

def main(): def main():


a = 3.1 a = 3.1
b = 2.4 b = 2.4
ret = Calc(a,b,‟add‟) ret = Calc(x=a,y=b,cal_type=‟add‟)

def Calc(x,y, cal_type=„add‟):


if cal_type == „add‟: In the a function definition a default
return x+y argument value can be set. In the Calc
elif cal_type == „sub‟:
return x-y function cal_type’s default value is
else: ‘add’. If the caller wants the default
return x/y
values only the required arguments a,b
def main(): may be given.
a = 3.1
b = 2.4
ret = Calc(a,b)

BETA Script to Python Conversion Guide 15


BETA Script to Python
Modules
A module-based architecture is the core idea behind the python program
architecture. Every file in 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 the file’s contents.

import math
import os
def main():
x = math.sqrt(9)
print(„The square root is: ‟,x)
os.stdout.write(„The square root of 9 is: ‟+str(x))

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

BETA Script to Python Conversion Guide 16


BETA Script to Python
Exception Handling
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 except block.
a=1
b=0
try:
res = a/b
except ZeroDivisionError:
print('Division by zero.')

myDict = {'python':'new', 'betascript':'old'}


try:
print(myDict['C++'])
except KeyError:
print('Key does exist.')

BETA Script to Python Conversion Guide 17


BETA Script to Python
From Structs to Classes
In Object Oriented Programming a class is similar to a struct with the addition that
it may have functions associated with it.
BETA Script Python
struct Point { class Point:
def __init__(self):
float x; self.x = 0
float y; self.y = 0
float z; self.z = 0
string name; self.name = None
};
def main():
def main() myPoint = Point()
{ myPoint.x = 120.74
myPoint = Point(); myPoint.y = 42.36
myPoint.x = 120.74; myPoint.z = 72.894
myPoint.y = 42.36; myPoint.name = „test point‟
myPoint.z = 72.894;
myPoint.name = „test point‟;
}

BETA Script to Python Conversion Guide 18


Handling ASCII files
Reading files in Python
file_mat = utils.SelectOpenFile(0,‟CSV files(*.csv)‟) Pop-up file manager to select a
file = file_mat [0]; single file, using a file-type filter

f = open(file,”r”) Open a file for reading (“r’)

for line in f: Loop through the lines of the file


print(line)

f.close() Close a file

Hints & Tips

 To split a comma or semi-colon separated line into its components, you can use
the line.split(‘;’) method which is the equivalent to BETA Script’s Tokenize Function
 The equivalent to MatchString function in Python is the line.find(‘my_string’)
method

BETA Script to Python Conversion Guide 19


Handling ASCII files
Writing files in Python
file_mat = utils.SelectSaveFile(”CSV files(*.csv)”) Pop-up file manager to specify a
file = file_mat[0] new or existing filename.

f = open(file,”w”) Open a file for writing (“w’)

f.write(line) Write a line to the file

f.close() Close a file

Hints & Tips

 Opening an existing file with the option “w” in open will overwrite its contents.
 To add lines at the end of an existing file, you can open it with the option “a”
(append), i.e. open (f, “a”)

BETA Script to Python Conversion Guide 20


The ANSA Module

BETA Script to Python Conversion Guide 21


BETA Script to Python
ANSA Modules

The ANSA modules are:


Module Description
ansa.batchmesh Batchmesh 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
ansa.utils General functions
ansa.morph Morph functions
ansa.calc Mathematical functions
ansa.session ANSA session commands
ansa.taskmanager Task Manager functions
BETA Script to Python Conversion Guide 22
Introduction to the ANSA Python Module
The ANSA constants are accessed by ansa.constants and they are:
NASTRAN, LSDYNA, PAMCRASH, ABAQUS, RADIOSS, ANSYS, FLUENT, FLUENT2D, STAR,
UH3D, CFDPP, OPENFOAM, PERMAS, MOLDEX3D, RADTHERM, SESTRA, THESEUS

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,
PART_MODEL_NAME, PART_NAME, PART_VERSION, PART_VSC,

ansa.constants.app_version #returns the version as a string


ansa.constants.app_version_int #returns the version as an integer
ansa.constants.app_home_dir #The system directory used for the configuration
files
ansa.constants.app_root_dir #The application’s root directory
BETA Script to Python Conversion Guide 23
BETA Script to Python
The ANSA Entity Object
ANSA entities are exported to Python as objects of type ansa.base.entity. The
entity class is the root class of the ANSA module. Entity objects can be created and
returned by functions of the ANSA module.

They have special read only attributes:


_id
returns the ANSA Entity id
_name
return the ANSA Entity Name

and methods:
_isDefunct()
returns true the referenced ANSA entity has been destroyed
_ansaType(deck)
returns the ANSA type of an entity in the specific deck

BETA Script to Python Conversion Guide 24


BETA Script to Python
Some of the Basic Differences
 Most of the string tags such as “on” and ”off” have been replaced by Boolean values
 When a function returns a reference or a container, the return value for failure is
None.
 When a function argument can be a container or “nothing”, “nothing ” is denoted
with None, and not 0
 All returned arguments are returned in their appropriate type and not as strings as in
BETA Script, in functions like GetEntityCardValues

BETA Script to Python Conversion Guide 25


BETA Script to Python
Use of the ANSA modules
The appropriate module needs to be imported in order to use its functions. In the
example below the base, morph and constants module are imported

import ansa
from ansa import base
from ansa import morph
from ansa import constants

def test_fun():
mp1 = base.GetEntity(constants.LSDYNA, „MORPHPOINT‟, 1)
mp2 = base.GetEntity(constants.LSDYNA, „MORPHPOINT‟, 2)
m_points = [mp1,mp2]
me1 = base.GetEntity(constants.LSDYNA, „MORPHEDGE‟, 1)
me2 = base.GetEntity(constants.LSDYNA, „MORPHEDGE‟, 2)
m_edges = [me1, me2]
morph.MorphMove(m_points, m_edges, 1, 100)

BETA Script to Python Conversion Guide 26


BETA Script to Python
Common functions differences
CollectEntities

BETA Script
def main()
{
ents = CollectEntities(LSDYNA, 0, “SECTION_SHELL”, “recursive”, “YES”);
}

Python
import ansa
from ansa import base
from ansa import constants

def main():
ents = base.CollectEntities(constants.LSDYNA, None, „SECTION_SHELL‟, recursive=True)

 Named arguments can be used for the optional arguments such as “recursive”.
 Booleans replace the “YES”/”NO” strings
 None is now used to denote a none container

BETA Script to Python Conversion Guide 27


BETA Script to Python
Common functions differences
GetEntityCardValues
BETA Script
def main()
{
GetEntityCardValues(LSDYNA, ent, “T1”, thick, “NIP”, nip, “MID”, mid);
Print(„The Thickness is: ‟+thick);
}

Python
import ansa
from ansa import base
from ansa import constants

def main():
fields = [„T1‟,‟NIP‟,‟MID‟]
vals = base.GetEntityCardValues(constants.LSDYNA, ent, fields)
print(„The Thickness is:‟, vals[„T1‟])

 A list with the fields that we want to extract values from is given
 The function return a Dictionary with keys the field tags given in the list
 The values of the Dictionary is the same with the field’s value type. A float will return as a float, a
strings as a string etc
BETA Script to Python Conversion Guide 28
BETA Script to Python
Common functions differences
SetEntityCardValues

BETA Script
def main()
{
SetEntityCardValues(LSDYNA, ent, “T1”, thick, “NIP”, nip, “MID”, mid);
}

Python
import ansa
from ansa import base
from ansa import constants

def main():
fields = {„T1‟:1.2,‟NIP‟:2,‟MID‟:1200}
base.SetEntityCardValues(constants.LSDYNA, ent, fields)

 A Dictionary with keys the card’s field tags and values the new desired values is given

BETA Script to Python Conversion Guide 29


BETA Script to Python
Common functions differences
CreateEntity

BETA Script
def main()
{
CreateEntityVa(LSDYNA, “SECTION_SHELL”, “Name”, “Test Prop”, “T1”, “1.2”);
}

Python
import ansa
from ansa import base
from ansa import constants

def main():
fields = {„Name‟:‟Test Prop‟,‟T1‟:1.2}
base.CreateEntity(constants.LSDYNA, „SECTION_SHELL‟, fields)

 The functionality of CreateEntity and CreateEntityVa is combined to a single function


(CreateEntity) in the python ANSA module

BETA Script to Python Conversion Guide 30


BETA Script to Python
Interacting directly with an ANSA Entity Object
The name and the id of an entity can be read directly from its object. So there is no
need to call GetEntityCardValues()
import ansa
from ansa import base
from ansa import constant

def main():
ent = base.GetEntity(constants.LSDYNA, “SECTION_SHELL”, 1)
print(„The name is: ‟,ent._name)
print(„The id is: ‟, ent._id)

In addition the type of entity can be retrieved by calling the object method _ansaType().
This does the same job as the GetEntityType() function.

ent._ansaType(constants.LSDYNA)

BETA Script to Python Conversion Guide 31


BETA Script to Python
User defined functions - Buttons

Script buttons are automatically created with the use of a special decorator. On top of
the programs main function the following syntax can be used

Decorator Description
@ansa.session.defbutton The function name is the button name placed
in the default button group
@ansa.session.defbutton(‘Button Group’) The function name is the button name placed
in the specified button group
@ansa.session.defbutton(‘Button Group’, Button name and group is specified
‘Function Name’)

import ansa

@ansa.session.defbutton(‟Custom Group‟, „My Test Function‟)


def MyTestFun():
print (‘Hello World‘)

BETA Script to Python Conversion Guide 32


The META Module

BETA Script to Python Conversion Guide 33


BETA Script to Python
META Modules
The META modules are:
Module Description Module Description
meta.calc Mathematical functions meta.windows META windows functions
meta.utils General functions meta.models Models functions
meta.guitk BCGUI functions meta.nodes Nodes functions
meta.annotations Annotations functions meta.pages Pages functions
meta.boundaries Boundaries functions meta.parts Parts functions
meta.constants A collection of all the META meta.plot2d 2d plot functions
constants (META KEYWORDS)
meta.connections Connections functions meta.report Report functions
meta.coordsystems Coordinate systems functions meta.results Results functions
meta.planes Cut planes functions meta.spreadsheet Spreadsheet functions
meta.elements Elements functions meta.betavisibility Visibility functions
meta.groups Groups functions meta.visuals Images & videos functions
meta.isofunctions Cut planes functions meta.session Session functions
meta.materials Elements functions meta.betascript BETA scripting functions

BETA Script to Python Conversion Guide 34


BETA Script to Python
Use of the META modules
The appropriate module needs to be imported in order to use its functions. All meta script functions
have remained exactly the same in Python (name, arguments, argument types)

From meta structs to Classes


In Python all META structs have been replaced by equivalent classes. These classes can be used
directly without the need to define their type first.

BETA Script Python


#include "meta_structs" import meta
from meta import parts
def main()
{ def main():
part p; model_id = 0
model_id = 0; all_parts = parts.Parts(model_id)
all_parts = Parts(model_id); for p in all_parts:
foreach p in all_parts { print(p.id)
Print(p.id); print(p.name)
Print(p.name);
}
}

BETA Script to Python Conversion Guide 35


BETA Script to Python
The META_KEYWORDS constants are accessed by meta.constants
BETA Script
#include "meta_structs"

def main()
{
part p;
model_id = 0;
part_type = PSHELL;
collected_parts = PartsByType(model_id, part_type);
foreach p in collected_parts {
Print(p.id);
}
}
Python
import meta
from meta import parts
from meta import constants

def main():
model_id = 0
part_type = constants.PSHELL
collected_parts = parts.PartsByType(model_id, part_type)
for p in collected_parts:
print(p.id,p)

BETA Script to Python Conversion Guide 36


BCGUI

BETA Script to Python Conversion Guide 37


BETA Script to Python
BCGUI differences
BETA Script
def win()
{
TopWindow = BCWindowCreate(“My Window”, BCOnExitDestroy);

BCButtonSetClickedFunction(BCPushButton_1, “my_callback_function”, my_data);
}

Python
import ansa
from ansa import guitk

def win():
TopWindow = guitk.BCWindowCreate(„My Window‟, guitk.constants.BCOnExitDestroy)

guitk.BCButtonSetClickedFunction(BCPushButton_1, my_callback_function, my_data)

 Python code requires the guitk module to be used


 What used to be called enumerators under BETA Script, in python are guitk.constants
 Python directly support function names as function arguments. Thus function names in
callbacks should not be inside quotes

BETA Script to Python Conversion Guide 38

You might also like