Python Manual
Python Manual
Japan Asia-Pacific
MSC Software Japan Ltd. MSC Software (S) Pte. Ltd.
Shinjuku First West 8F 100 Beach Road
23-7 Nishi Shinjuku #16-05 Shaw Tower
1-Chome, Shinjuku-Ku Singapore 189702
Tokyo 160-0023, JAPAN Telephone: 65-6272-0082
Telephone: (81) (3)-6911-1200 Email: [email protected]
Email: [email protected]
Worldwide Web
www.mscsoftware.com
User Documentation: Copyright 2016 MSC Software Corporation. All Rights Reserved.
U.S. Patent 9,361,413
This document, and the software described in it, are furnished under license and may be used or copied only in accordance with the
terms of such license. Any reproduction or distribution of this document, in whole or in part, without the prior written authorization of
MSC Software Corporation is strictly prohibited.
MSC Software Corporation reserves the right to make changes in specifications and other information contained in this document
without prior notice. The concepts, methods, and examples presented in this document are for illustrative and educational purposes
only and are not intended to be exhaustive or to apply to any particular engineering problem or design. THIS DOCUMENT IS
PROVIDED ON AN “AS-IS” BASIS AND ALL EXPRESS AND IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BE LEGALLY INVALID.
MSC Software logo, MSC, MSC Nastran, Adams, Dytran, Marc, Mentat, and Patran are trademarks or registered trademarks of
MSC Software Corporation or its subsidiaries in the United States and/or other countries.
NASTRAN is a registered trademark of NASA. Python is a trademark of the Python Software Foundation. Parasolid is a registered
trademark of Siemens Product Lifecycle Management Software, Inc. All other trademarks are the property of their respective owners.
This software may contain certain third-party software that is protected by copyright and licensed from MSC Software suppliers.
Additional terms and conditions and/or notices may apply for certain third party software. Such additional third party software terms
and conditions and/or notices may be set forth in documentation and/or at http://web.mscsoftware.com/thirdpartysoftware (or
successor website designated by MSC from time to time).
METIS is copyrighted by the regents of the University of Minnesota. MS MPI is developed by Microsoft Corporation. PCGLSS 8.0,
Copyright 1992-2016 Computational Applications and System Integration Inc. All rights reserved. Portions of this software are
owned by Siemens Product Lifecycle Management Software, Inc. Copyright 2016.
Use, duplication, or disclosure by the U.S. Government is subject to restrictions as set forth in FAR 12.212 (Commercial Computer
Software) and DFARS 227.7202 (Commercial Computer Software and Commercial Computer Software Documentation),
as applicable.
MA*V2016*Z*Z*Z*DC-PYTH
Contents
Marc Python Tutorial and Reference Manual
Contents
Preface
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Documentation Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1 Introduction
Welcome . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Background Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Plate Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Postprocessing Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Scalar Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Set Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
PyPost Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
12 PyPost: Plotting
Chapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Introduction
Using the Python Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Variable Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1 PyMentat References
PyMentat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2 PyPost References
PyPost . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Arithmetic Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Database Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Preface
10 Marc Python Tutorial
Introduction
The purpose of this manual is to introduce the user to the Python modules. The tutorial covers the basics of the modules
and helps the novice Python user in becoming comfortable in programming with these modules through a number of
examples that display some typical uses of creating and processing a model in various stages. This tutorial is not
intended to be a Python programming manual. The book Programming Python by Mark Lutz should be used for this
purpose. This manual does assume that the Python user is experienced in using Mentat.
Part I introduces the user to the PyMentat module. This module interacts with Mentat to create, modify, and post
process models.
Part II introduces the user to the PyPost module. This module functions independently of Mentat to postprocess
a Marc post file (results file).
Part III introduces the user to more advanced uses of the PyMentat and PyPost modules.
Documentation Conventions
Listed below are some font and syntax conventions that are used to make the information in this manual easier to
understand:
• Cross-references (Links) are highlighted in Blue.
• Names of buttons that appear on the Mentat screen are in Initial Caps. The command issued will appear in
lower case, such as *add_nodes. Note that the "*" always precedes the command name to instruct Mentat that
a command is being issued.
• Literal user input and program prompts are in courier font.
• Names of processors are indicated in UPPER CASE.
• A carriage return keystroke is indicated by <CR>.
• The left mouse button is indicated by <ML>.
• The middle mouse button is indicated by <MM>.
• The right mouse button is indicated by <MR>.
1 Introduction
Welcome 13
The Basics of Using PyMentat 13
The Basics of Using PyPost 15
A Brief Look at Python Programming 16
CHAPTER 1 13
Introduction
Welcome
Welcome to Python – a set of API’s designed to be used by Python scripts to enhance the functionality of Mentat.
MAIN
MESH GENERATION
grid ON
nodes ADD
you will see that the command name of *add_nodes is issued in the dialogue area of Mentat. Therefore, if you want
your Python script to add a node, your script should send the command *add_nodes to Mentat.
Unless you are a very experienced Mentat user, you will most likely develop your PyMentat Python script using the
technique outlined in Figure 1-1.
14 Marc Python Tutorial
To aid in the development of converting the procedure files to Python scripts, the Python script shown in Figure 1-2
can be used to generate the Python code for any given Mentat procedure file. To use the script, run it as follows:
python py_create.py mentat.proc my_script.py
This script simply reads the procedure file and wraps a py_send command around it. You need to edit the resulting
Python script to add PARAMETERS and other variables for conditional processing.
CHAPTER 1 15
Introduction
#!/usr/bin/python
import sys
import string
def main(fnamei, fnameo):
i = open(fnamei,"r")
o = open(fnameo,"w")
o.write("from py_mentat import *\n")
o.write("def main():\n")
for line in i.readlines():
s = string.strip(line)
if s == "":
continue
st = " py_send(\"%s \")\n" % s
o.write(st)
o.write("\n")
o.write("if __name__ == '__main__':\n")
o.write(" main()\n")
if __name__ == "__main__":
main(sys.argv[1],sys.argv[2])
Figure 1-2 A Python Script to Convert a Marc Mentat Procedure File to a Python Script
Function Description
close Closes a currently open post file and frees any allocated memory.
dies Returns the number of dies in the post file.
domains Returns the number of domains stored in the post file.
element Returns the element data for a particular element.
elements Returns the number of elements in the current increment.
element_id Returns the id of a particular element.
element_scalar Returns a list of a particular element scalar data for a particular element.
element_scalars Returns the number of element scalars available.
element_scalar_label Returns the name of a particular element scalar.
element_sequence Returns the index number of a particular element ID.
element_tensor Returns a list of a particular element tensor for a particular element.
element_tensors Returns the number of element tensors available.
16 Marc Python Tutorial
Function Description
element_tensor_label Returns the name of a particular element tensor.
element_vector Returns a list of a particular element vector data for a particular element.
element_vectors Returns the number of element vectors available
element_vector_label Returns the name of a particular element vector.
extrapolation Sets the integration point extrapolation method.
increments Returns the number of increments available in the post file
moveto Move to a specified increment in the post file
node Returns the nodal data for a particular node.
nodes Returns the number of nodes for the current increment.
node_displacement Returns the nodal displacement values for a particular node.
node_displacements Returns a 1 if nodal displacements are present in the post file, 0 otherwise.
node_id Returns the ID of a particular node
node_scalar Returns the value of a particular node scalar for a particular node.
node_scalars Returns the number of node scalars available.
node_scalar_label Returns the name of a particular node scalar.
node_sequence Returns the index number of a particular node ID
node_vector Returns the value of a particular node vector at a particular node.
node_vectors Returns the number of node vectors available.
node_vector_label Returns the name of a particular node vector.
post_open Opens a post file and returns the PyPost object of it.
set Returns the data for a particular set.
sets Returns the number of sets in the post file.
title Returns the title of the post file.
A Python script that will use the PyMentat module needs to import the py_mentat module using the following
syntax:
from py_mentat import *
Similarly, a Python script that will use the PyPost module needs to import the py_post module using the following
syntax
from py_post import *
One of the biggest differences between the Python language and other programming languages is that Python does not
denote blocks of code with reserved words or symbols such as if..then..endif (FORTRAN) or if { ... }
(curly braces in C). Instead, indenting is used for this purpose. For example, the take following block of FORTRAN
code:
if(jtype.eq.49) then
ladt=idt+lofr
endif
The block of FORTRAN code would need to be coded as follows in Python:
if jtype == 49:
ladt=idt+lofr
Python matches the amount of indenting to the block of code. The colon at the end of the if statement denotes that it
is a compound statement. All the lines that are to be in that block of code need to be at the same indent level. The block
of code is ended when the indenting level returns to the level of to the compound statement. The examples in the
following chapters will show you more about the Python syntax.
The material covered in this tutorial is very basic and should be easy to access and understand for the first time Python
user. Once you have worked through the sample sessions in Part II you should feel comfortable enough to do a
complete analysis simply by extrapolating from what you have learned in the example problems.
A multi-dimension list is created by first creating a single dimensional list, and then creating the other dimensions, as
follows (a 3x2 array):
A = [None] * 3
for i in range(3)
A[i] = [None] * 2
Chapter 2: PyMentat: A Simple Example
Chapter Overview
In this section, it will be demonstrated how to create a basic Python script that sends commands to Mentat. For this
purpose, a rectangular grid of elements will be created. Upon completion of this chapter, you should have a clearer
understanding of the following areas:
• The basics for a PyMentat script
• How a Python script communicates with Mentat
• Python Menu layout
Lines 2-15 The make_nodes routine creates a grid of s x t nodes, starting in the lower left-hand corner at the
point (xs, ys, 0.0). The function range is a built-in Python function that builds a Python list of integers.
Note line 11: This is where the Mentat command string for adding a node is composed. The
*add_nodes command is placed in a Python string, along with the x,y,z node coordinates. The
statement uses Python’s % operator. It is used on string objects, and works much like C’s sprintf
function. A %f, %g, or %e designates a floating point number, and a %d designates an integer. The
objects on the right of the % symbol are paired with the conversion codes starting with the first % code
inside the quoted string. The py_send routine is called with the string to send the command string
to Mentat, at which time it runs the command string just as if it was typed in the Mentat dialogue area.
Lines 18-31 The make_elements routine performs the element connectivity of the node grid using the Mentat
command *add_elements. The loop beginning in line 24 builds the elements moving across the
node grid in the X-direction and up the grid in the Y-direction.
Lines 33-40 The main routine sets the size of the grid and the starting position.
MAIN
UTILS
PYTHON
To run the script, select the RUN button. The other menu items in Figure 2-1 will be discussed in a later chapter on
sockets. When the RUN button is selected, the browser window as shown in Figure 2-2 appears.
Note the button named RUN AS SEPARATE PROCESS. This will run the script in a separate window and
communicate to Mentat using a BSD socket connection. This item is discussed in a later chapter. In order to use this
option, a Python script would need to use the py_connect routine to complete the socket connection with Mentat.
This will be discussed in the next chapter. Do not select this option for this example. Browse to the
examples/python/c02 directory and select the file chap2.py. Then select OK to run the script.
When the script completes, a mesh is created as shown in Figure 2-3.
24 Marc Python Tutorial
In the next chapter, we will modify the script to use Mentat PARAMETERS to create a variably sized grid.
Chapter 3: PyMentat: Obtaining Data from Mentat
Chapter Overview
In this chapter, it will be demonstrated how to use Mentat PARAMETERS in a Python script using the PyMentat
module. It will also be shown how to run a Python script as a separate process. Upon completion of this chapter, you
should have a clearer understanding of the following areas:
• The py_get_int and py_get_float methods
Lines 2-31 The make_nodes and make_elements routines are the same as in the previous chapter.
Lines 33-39 The main routine obtains the values for the size of the grid and the starting point from Mentat using
parameters. The py_get_int method evaluates a formula and returns an integer (fixed point) result
similar to the *calculator command. The py_get_float method evaluates a formula and returns a
floating point number. In this case, these methods obtain the values for these parameters.
Lines 41-44 If the script is invoked as a separate process, (such as “python chap3.py”), then the Python interpreter
sets the Python variable __name__ to the string ‘__main__’. If this is the case, then the Python
script should attempt to make a socket connection to Mentat. The py_connect method is discussed
in more detail in a later chapter.
the py_get_int or py_get_float method. These parameters may be combined with any of the Arithmetic or
Database functions described in the Marc Python Reference Manual.
When using the py_get_int or py_get_float methods, they must be used on a system of the same byte
architecture. The values are not converted to a machine independent format before being transmitted.
MAIN
UTILS
PARAMETERS
NEW PARAMETER
x_size
10
y_size
8
x_start
-1.0
y_start
-1.0
Remember to press the carriage <CR> after typing in each of the numbers to create the parameters. The procedure file
chap3.proc may be executed to perform the above commands for you if you wish.
You may also type the *define command in Mentat’s command prompt window to create or edit the parameter. For
example, to create the parameter x_size you would type
*define x_size 10
As in the previous chapter, bring up the Python browser window with the menus:
MAIN
UTILS
PYTHON
RUN
When the script completes, a mesh will be created the same as in the previous chapter.
Chapter 4: PyMentat: Building Complex Geometry
Chapter Overview
In this chapter, it will be demonstrated how to build more complex geometry using Python. To continue with the
example discussed in Chapter 3, we will examine a script that creates a more complex model. This example uses
Mentat’s user-defined menu to present a simple menu for controlling the model’s properties.
Upon completion of this chapter, you should have a clearer understanding of the following areas:
• Adding points, curves, and lines
• Become more familiar with Python programming
Background Information
A rectangular plate of user defined width and height contains a varying number of holes of user-defined diameter d,
equally spaced by a user-defined distance s. It is desired that the Python script determine how many holes can be placed
in the plate, and center the array of holes in the plate with the distance from any edge to the nearest hole to be at least
the distance s.
d d d
t=.75
height
d d d
d d d
width
This example is named chap4.py and can be found in the Mentat directory examples/python/tutorial/c04. The
following is the Python script:
1. from py_mentat import *
2. def add_plate(xs,ys,width, height):
3. py_send("*set_curve_type line")
4. py_send("*add_points")
5. py_send("%f %f 0" % (xs, ys))
6. py_send("%f %f 0" % (xs+width, ys))
7. py_send("%f %f 0" % (xs+width, ys+height))
8. py_send("%f %f 0" % (xs, ys+height))
9. py_send("*set_curve_type line")
10. py_send("*add_curves")
11. py_send("1 2")
12. py_send("2 3")
13. py_send("3 4")
14. py_send("4 1")
15. py_send("*fill_view")
16. return
17.
18. def build_plate(xstart,ystart,width, height, diameter, spacing):
19. f = diameter+spacing
20. nx = int((width-spacing)/f)
21. ny = int((height-spacing)/f)
22. if (nx < 1 or ny < 1 ):
23. print "Holes are too big!"
24. return 1
25. print "creating hole grid of ",nx, " by ",ny
26.
27. add_plate(xs,ys,width,height)
28. xs = .5 * (width - f * (nx - 1)) + xstart
29. ys = .5 * (height - f * (ny - 1)) + ystart
30. py_send("*set_curve_type circle_cr")
31. py_send("*add_curves")
32. r = diameter / 2
32 Marc Python Tutorial
Lines 2-16 The add_plate routine creates the plate using four connected curves. It first generates the end points
of the curve using the *add_points command, and then creates the curves by connecting the points
with the *add_curves commands. In line 15, the *fill_view command is issued to center and
fill the plate properly on the screen.
Lines 18-38 The build_plate routine calculates the number of holes that can be placed in the plate and creates them
in their proper position. The variables nx and ny in lines 20 and 21 are the number of holes to be
placed in the x and y direction, respectively. The Python int function is used to force the values to be
an integer. Once it has been determined that the plate is big enough to contain at least one hole, the
add_plate routine is called in line 27 to create the plate itself. The initial x and y position for the first
hole is calculated in lines 28-29. The loop in lines 38-44 controls the vertical (height) placement, and
the inner loop in lines 35-37 controls the horizontal (width) placement.
Lines 40-48 The main routine obtains the values for the size of the plate, the diameter of the holes, and the spacing
between holes from Mentat. The lower-left corner of the plate is calculated in lines 45-46 so that the
plate has its center at (0,0). The build_plate routine is then called to create the geometry.
Lines 50-52 If run in a separate process, make a socket connection to Mentat.
CHAPTER 4 33
PyMentat: Building Complex Geometry
WIDTH
12.0
HEIGHT
8.0
DIAMETER
.75
SPACING
0.4
MESH SIZE
0.2
Remember to press the carriage return <CR> after typing in the numbers. Note that the MESH SIZE parameter is not
used in this example. When you specify these values, the menu creates these parameters in Mentat, and the values for
these parameters are obtained by the Python script to control the number of holes in the plate. Select the BUILD button
to create the model.
When the script completes, a plate will be created as shown in Figure 4-2.
34 Marc Python Tutorial
In the next chapter, we will mesh the plate and add the geometric and material properties, boundary conditions, and
job parameters.
Chapter 5: PyMentat: Adding Model Properties
Chapter Overview
In this chapter, it will be demonstrated how to add properties to the geometry create in the previous chapter.
Upon completion of this chapter, you should have a clearer understanding of the following areas:
• Using the Database functions
• Node and Element IDs
Plate Properties
As shown in Chapter 4, a rectangular plate of user defined width and height contains a varying number of holes of
user-defined diameter d, equally spaced by a distance s specified by the user. The array of holes will be centered in the
plate, with the distance from any edge to the nearest hole to be at least the distance s.
In this chapter, we will update the Python script to apply the properties described in Figure 5-1 to the plate. The material
behavior is linear elastic with Young’s modulus E = 30e6 and Poisson’s ratio = 0.3. A compression load with
magnitude p = 1000 Lb/in2 will be applied to the top of the plate.
Y
1000 Lb/in2
d d d
t=.75
height
fixed d d d
d d d
width
This example is named chap5.py and can be found in the Mentat directory examples/python/tutorial/c05. The
following Python code has been added to the code shown in the previous chapter:
79. # check if f1 == f2 within tolerance of tol
80. def check_tol(f1, f2, tol):
81. if f1 == f2:
82. return 1
83. if f1 + tol < f2:
84. if f1 - tol > f2:
85. return 1
86. return 0
87.
88. def mesh_plate(width, height, diameter, spacing):
89. py_send("*set_curve_div_type_fix_avgl")
90. l = spacing/2.0
91. py_send("*set_curve_div_avgl %f" % l)
92. py_send("*apply_curve_divisions all_existing")
93. py_send("*dt_planar_trimesh all_existing")
94. return
95.
96. def add_bc(xs,ys,width,height):
97. py_send("*renumber_all")
98. n = py_get_int("nnodes()")
99. # add fixed bc at left edge
100. py_send("*apply_type fixed_displacement")
101. py_send("*apply_dof x")
102. py_send("*apply_dof y")
103. py_send("*apply_dof z")
104.
105. node_list = []
106. for i in range(1,n+1):
107. str = "node_x(%d)" % i
108. f = py_get_float(str)
109. if check_tol(f, xs, .001):
110. node_list.append(i)
38 Marc Python Tutorial
111.
112. py_send("*add_apply_nodes ")
113. for i in range(0,len(node_list)):
114. str = "%d " % node_list[i]
115. py_send(str)
116. py_send(" # ")
117. # add edge load at top
118. py_send("*new_apply")
119. py_send("*apply_type edge_load")
120. py_send("*apply_value p 1000.0 ")
121. py_send("*add_apply_curves 3 #")
122. return
123.
124. def add_matl():
125. py_send("*material_type mechanical:isotropic")
126. py_send("*material_value isotropic:youngs_modulus 3e7 .3")
127. py_send("*add_material_elements all_existing")
128. return
129.
130. def add_job():
131. py_send("*loadcase_type static")
132. py_send("*job_class mechanical")
133. py_send("*job_option dimen:pstress")
134. py_send("*add_post_tensor stress")
135. py_send("*add_post_var von_mises")
136. py_send("*element_type 6 all_existing")
137. py_send("*element_type 6 all_existing")
138. return
139.
140. def add_geom_prop():
141. py_send("*geometry_type mech_planar_pstress ")
142. py_send("*geometry_value thick .75")
143. py_send("*add_geometry_elements all_existing")
144. return
CHAPTER 5 39
PyMentat: Adding Model Properties
145.
146. def main():
147. xs = 0.0
148. ys = 0.0
149. width = py_get_float("width")
150. height = py_get_float("height")
151. diameter = py_get_float("diameter")
152. spacing = py_get_float("spacing")
153. build_plate(xs,ys,width, height, diameter, spacing)
154. mesh_plate(width, height, diameter, spacing)
155. add_bc(xs,ys,width, height)
156. add_matl()
157. add_geom_prop()
158. add_job()
159. py_send("save_as_model chap5.mfd yes")
160. return
161.
162. if __name__ == ’__main__’:
163. py_connect("",40007)
164. main()
165. py_disconnect()
166.
Lines 2-8 The check_tol routine is a convenience function to compare two floating point number for equality
within a certain tolerance.
Lines 10-17 The mesh_plate routine generates a 2-D planar Delaunay triangle mesh. To generate the curve
divisions, the spacing between the holes is used to control the average length of the segments.
Lines 19-46 The add_bc routine creates the boundary conditions for the plate. The left edge of the plate is fixed,
and the top edge of the plate has an edge load. We first obtain the number of nodes using the Database
function nnodes in line 3. In line 11, we renumber all the nodes in the database so that the node index
is the same as the node ID. This will be discussed more in detail later in this chapter. We set the
displacement type to be fixed in lines 6-12. The code in lines 14-20 searches through the entire node
list looking for a node that lies on the left edge of the plate by examining it’s position in the X direction.
If a match is found, we obtain the node ID (which may be different from it’s index position in the
database) and store that in our node_list. In lines 21-25, the command *add_apply_nodes is used
to apply the fixed boundary conditions. We loop through the node_list and send the IDs, and then #
symbol to signal the End List command. Lines 28-31 is where the top edge load is created. Here,
we simply apply the load to the curve at the top of the plate (curve number 3).
40 Marc Python Tutorial
Lines 48-52 The add_matl routine applies the material properties to all the elements of the plate.
Lines 54-61 The add_job routine creates the necessary job parameters.
Lines 63-67 The add_geom_prop routine applies the necessary geometric properties.
Lines 69-83 The main routine is similar to that of Chapter 4, however, the additional routines are called to add the
boundary conditions, the material properties, the geometric properties, and the job parameters.
x = -1.0
y = -1.0
z = 0.0
ID = 1
x = 1.0
y = -1.0
z = 0.0
ID = 2
x = 1.0
y = 1.0
z = 0.0
ID = 3
x = -1.0
y = 1.0
z = 0.0
ID = 4
The linked list of nodes in Figure 5-2 shows a square grid of nodes 1,2,3,4. If node 2 is deleted, then the list would
become 1,3,4 as shown in Figure 5-3.
CHAPTER 5 41
PyMentat: Adding Model Properties
x = -1.0
y = -1.0
z = 0.0
ID = 1
x = 1.0
y = 1.0
z = 0.0
ID = 3
x = -1.0
y = 1.0
z = 0.0
ID = 4
If the database function node_id is now called with the value of 2, it returns with 3, since the second item in the list
is node 3. If the command renumber_all is issued, then the nodes will be renumbered to the sequence 1,2,3 and
node_id(2) will return 2.
If we did not issue the renumber_all command, then the code sequence in lines 20-24 would need to be:
for i in range(1,n+1):
str = "node_id(%d)" % i
j = py_get_int(str)
str = "node_x(%d)" % j
f = py_get_float(str)
if check_tol(f, xs, .001):
node_list.append(j)
We want to avoid using the node_id function as much as possible because it needs to search the entire database to
find the node.
UTIL
PARAMETERS
NEW PARAMETER
WIDTH
8.0
HEIGHT
42 Marc Python Tutorial
4.0
DIAMETER
1.0
SPACING
0.5
Remember to press the carriage return <CR> after typing in each of the numbers. Select the BUILD button to create the
model.
When the script completes, a mesh will be created as shown in Figure 5-4.
MAIN
JOBS
RUN
SUBMIT 1
In the next chapter, we will examine postprocessing using the PyMentat module.
Chapter 6: PyMentat: Processing a Post File
Chapter Overview
In this chapter, it will be demonstrated how to use the Postprocessing commands of Mentat in a Python script. This
example will use the post file of the example created in the previous chapter.
Upon completion of this chapter, you should have a clearer understanding of the following areas:
• The basics of using PyMentat for Postprocessing
• How to write an efficient PyMentat postprocessing PyMentat script
• Selecting nodes for display
Postprocessing Basics
PyMentat may also be used to postprocess a post file.
In this example, we will obtain all of the nodal scalar values on the post file generated by running the example in the
previous chapter.
This example is named chap6.py and can be found in the Mentat directory examples/python/tutorial/c06. The
following is the Python code:
1. from py_mentat import *
2.
3. def main():
4. py_send("*post_close")
5. py_send("*post_open chap5_job1.t16")
6. py_send("*post_next")
7. py_send("*fill_view")
8. py_send("*post_contour_lines")
9.
10. n = py_get_int("nnodes()") # get number of nodes
11. label = []
12. label.append("Displacement x")
13. label.append("Displacement y")
14. label.append("*External Force x")
15. label.append("External Force y")
16. label.append("Reaction Force x")
17. label.append("Reaction Force y")
18.
19. max_scalars = []
46 Marc Python Tutorial
20. max_nodes = []
21. for i in range(0,len(label)):
22. max_scalars.append(0.0)
23. max_nodes.append(0)
24. str = "*post_value " + label[i]
25. py_send(str)
26.
27. j = 1
28. while j <= n:
29. str = "node_id(%d)" % j
30. n_id = py_get_int(str)
31. str = "post_node_extra(%d)" % n_id
32. flag = py_get_int(str)
33. if flag == 0: # check for valid post node
34. str = "scalar_1(%d)" % n_id
35. f = py_get_float(str)
36. if f < 0.0:
37. f = -f
38. if f > max_scalars[i]
39. max_scalars[i] = f
40. max_nodes[i] = n_id
41. j = j + 1
42.
43. py_send("*draw_legend off")
44. py_send("*unpost_nodes all_existing")
45. py_send("*post_nodes ")
46.
47. print " Label node scalar"
48. print " ------------------------------------------"
49. for i in range(0,len(label)):
50. j = max_nodes[i]
51. str = " %18s %10i %g" % (label[i],
p.py_node_id(j),max_scalars[i])
52. print str
CHAPTER 6 47
PyMentat: Processing a Post File
Lines 4-7 These statements open the post file and setup some options. We need to do a *post_next in line 6
so that we are at "increment 0" in Marc terminology.
Line 8 We need to tell Mentat that we are working with scalar values, so one of the SCALAR PLOT commands
need to be sent.
48 Marc Python Tutorial
Line 10 This statement will get the number of nodes in the model. Note that this number may change at
different increments due to rezoning.
Lines 11-17 A Python list is used to store the names of the nodal scalars that are in the post file. This is a convenient
way of storing the names for use later. A Python list has an append method, and it is used to add the
desired string to the list. Note that a Python list can be a list of anything, integers, floating points
values, Python dictionaries, or other lists.
Lines 19-20 The max_scalars and max_nodes variables are declared as Python Lists. The index of the list
will be each of the scalars in the post file. The maximum scalar value will be stored in the
max_scalars list. The node associated with the max_scalar value will be stored in the
max_nodes list.
Lines 21 The loop for all of the scalars in our list.
Lines 22-23 We append initial values to our list. Remember that max_scalars and max_nodes are linked lists,
so we must have the item added to the list before we access it.
Lines 24-25 Specify the scalar name to use.
Lines 28 Loop through all the nodes. Note that we use a while loop for this. We had been using the Python
range function; however, for the range function, Python builds a list of all the values in the range. If
we had 100,000 nodes, Python would build a list with that many items.
Lines 29-30 Obtain the node ID for this node.
Lines 31-32 Not all nodes in the post file are visible nodes. Some are nodes used explicitly by Marc to perform
special functions and are considered “extra” nodes. The Database function post_node_extra
returns a zero if a node is not an extra node, one if it is. This check is required to verify that the values
obtained are true post file values at a node.
Lines 33-34 Obtain the scalar value using the Database function scalar_1.
Lines 35-36 We will use only positive values. If it is negative, then change it to positive.
Lines 37-39 Check the current value against the highest value in our list.
Line 43 Turn off the legend.
Lines 44-45 We need to remove all nodes from the post nodes list and then start the *post_nodes selection.
Note that once the *post_nodes selection process has begun, we cannot call any of the py_get
routines.
Line 43 Start the *select_node command.
Lines 47-52 Print out the results for each scalar.
Line 53 Send this node as one of the nodes to select. Note that we use the Python backquote operator which
converts an integer for a float into a string.
Line 54 Send the # symbol to signify End of List.
Line 55 Turn on NUMERICS.
Line 58-76 This section uses the database functions to find the node with the maximum (or minimum) value. It
loops through all the post values in the list, and then calls scalar_max_node and
scalar_min_node to obtain the node number at which the largest and smallest values occur. It
then calls the function scalar_1 to obtain the value associated with that node.
CHAPTER 6 49
PyMentat: Processing a Post File
Scalar Values
Using the PyMentat module for postprocessing is somewhat complex: you have to know what the scalar labels are,
check for valid nodes, etc. The PyPost module avoids this by providing methods to obtain what these items are.
In the next chapter, we will examine the post file using the Python module PyPost.
Chapter 7: PyMentat: Sets
Chapter Overview
In this chapter, it will be demonstrated how to obtain information regarding sets and to how to extract database
properties in a Python script . This example will use a simple model containing various sets and database properties.
Upon completion of this chapter, you should have a clearer understanding of the following areas:
• The basics of sets in Mentat
• How to query set information in a Python script
• How to obtain database properties
• How to obtain element data
Specific element properties may also be obtained using a number of methods that return the name of the item for each
element. Mentat provides the following element property methods:
Set Basics
The use of sets help to group items together to make it easier to reference them later. Mentat supports the following set
types:
A number of database functions are available in Mentat to support sets. The list of functions may be found in the Marc
Python Reference Manual, Appendix A, Table A-2.
A Mentat model may contain any number of sets. The database function nsets is used to obtain the number of sets in
a model. Sets are referenced by its set id. The set id is obtained using the database function set_id, which takes an
index number as its only argument. The remaining set functions use the set id to refer to the set; however, Mentat refers
to sets by name. The set name is obtained using the set_name function, and the set type is obtained using the
set_type function.
Each set in turn may contain multiple entries. The number of entries can be obtained using the function
nset_entries. The values for the entries are obtained using the set_entry function, which returns a single
value. If the set type is an edge set or a face set, the second value, the edge or face number, is obtained by calling the
set_edge or set_face function, respectively.
8. for i in range(1,m+1):
9. id = py_get_int("set_id(%d)" % i)
10. sn = py_get_string("set_name(%d)" % id)
11. st = py_get_string("set_type(%d)" % id)
12. n = py_get_int("nset_entries(%d)" % id)
13.
14. if stype not in ("icond","apply","lcase"):
15. print "Set ",sn,"is a ",stype," set with ",n,"entries"
16. for j in range(1,n+1):
17. k = py_get_int("set_entry(%d,%d)" % (id, j))
18. print " entry ",j," is ",k,
19. if (stype == 'face'):
20. l = py_get_int("set_edge(%d,%d)" % (id, j))
21. print " face number ",l
22. elif(stype == 'edge'):
23. l = py_get_int("set_edge(%d,%d)" % (id, j))
24. print " edge number ",l
25. else:
26. print " "
27.
28. print " "
29. m = py_get_int("ncbodys()")
30. print "Found ",m," Contact Bodys"
31. for i in range(1,m+1):
32. sn = py_get_string("cbody_name_index(%d)" % i)
33. id = py_get_int("cbody_id(%s)" % sn)
34. print " Contact Body ", i, " Id ",id, " Name ", sn
35.
36. m = py_get_int("nmaterials()")
37. print "\n Materials ",m
38. for i in range(1,m+1):
39. sn = py_get_string("material_name_index(%d)" % i)
40. st = py_get_string("material_type(%s)" % sn)
54 Marc Python Tutorial
41. p = py_get_float("material_par
(%s,isotropic:youngs_modulus)" % sn)
42. str = " Material %14s Type %19s Young's Mod %g" % (sn,st,p)
43. print str
44. mt = py_get_string("material_opt( %s,plasticity:method)" % sn)
45. st = py_get_string("material_opt( %s,plasticity:yield)" % sn)
46. str = " Plasticity method %9s Yield Surface %s" % (mt, st)
47. print str
48.
49. m = py_get_int("napplys()")
50. print "\n Boundary Conditions ",m
51. for i in range(1,m+1):
52. sn = py_get_string("apply_name_index(%d)" % i)
53. st = py_get_string("apply_type(%s)" % sn)
54. so = py_get_string("apply_opt(%s,dof_values)" % sn)
55. str = " Boundary Cond %14s Type %19s Values by: % s" % (sn,st,so)
56. print str
57.
58. m = py_get_int("ngeoms()")
59. print "\n Geometric Properties ",m
60. for i in range(1,m+1):
61. sn = py_get_string("geom_name_index(%d)" % i)
62. st = py_get_string("geom_type(%s)" % sn)
63. p = py_get_float("geom_par(%s,thick)" % sn)
64. str = " Geometric Prop %12s Type %19s Thick %g" % (sn,st,p)
65. print str
66.
67. m = py_get_int("niconds()")
68. print "\n Initial Conditions ",m
69. for i in range(1,m+1):
70. sn = py_get_string("icond_name_index(%d)" % i)
71. st = py_get_string("icond_type(%s)" % sn)
72. so = py_get_string("icond_opt(%s,dof_values)" % sn)
73. str = " Initial Cond %14s Type %12s Values by: %s" % (sn,st,so)
CHAPTER 7 55
PyMentat: Obtaining Model Data
108. sn = "element_class(%d)" % id
109. e_class = py_get_int(sn)
110. sn = "element_family(%d)" % id
111. e_fam = py_get_int(sn)
112. e_ty = py_get_int(sn)
113. print " Element ", id, " Class ",e_cl," Family ",e_fam,",
Type ",e_ty
114. cbn = py_get_string("element_cbody(%d)" % id)
115. gmn = py_get_string("element_geom(%d)" % id)
116. orn = py_get_string("element_orient(%d)" % id)
117. mtn = py_get_string("element_material(%d)"% id)
118. print " Contact Body : ", cbn
119. print " Geometry Property : ", gmn
120. print " Orientation : ", orn
121. print " Material Property : ", mtn
122.
123. return
124.
125. if __name__ == '__main__':
126. py_connect('',40007)
127. main()
128. py_disconnect()
Line 18-26 Depending on the set type, obtain the edge number or the face number if it is an edge or face set.
Line 28-34 Obtain the number of contact bodies. For each contact body, get the contact body name based on its
index, 1 - ncbodys using the cbody_name_index database function. Supplying an index of
0 will return the current contact body name. Also obtained is the contact body index. Note from the
output that the index and ID are not identical.
Line 36-74 In a manner similar to that for contact bodies, obtain the number of materials, boundary conditions,
geometric properties and initial conditions. For each item, obtain the name using the index based
name functions, xxx_name_index. Valid index values are from 1...m, where a value of 0
indicates the current item name. Note that in line 40 the function material_par is used to obtain
a material parameter using a syntax similar to that used for py_get_data as described below.
However, in the xxx_par methods the class token is not used.
Line 76-99 This code displays how to obtain some values of the current material and contact table using the
py_get_data function. The syntax for this function is basically the same that is used in the
command that sets the value. In this example, the value obtained is Young’s modulus. The command
that sets the value is:
*material_value isotropic:youngs_modulus
The argument to the function will use the same parameter to obtain the value, with the first token
specifying the class:
py_get_data(‘material:isotropic:youngs_modulus’)
sn=’contact_table::the_mesh:refined_mesh:dist_tol’)
py_get_data(sn))
This function supports materials (material), contact bodies (contact_body), contact tables
(contact_table), boundary conditions (apply), geometric properties (geometry), global
remeshing (adapg), local adaptivity, (adapt) initial conditions (icond), loadcases (loadcase)
and jobs (job). It provides multi-level data retrieval which is also supported in the function
material_par. However, the py_get_data function only operates on the current item class.
Line 101-121 Obtain specific element information such as its class, type and familty. Also obtain the material,
geometric property, orientation property and contact body in which it belongs.
Found 16 sets
Set TOP is a node set with 2 entries
entry 1 is 3
entry 2 is 4
Set BOTTOM is a node set with 2 entries
entry 1 is 1
entry 2 is 2
Set LITTLE_EL is a element set with 1 entries
entry 1 is 2
Set RIGHT_ELEMENT is a element set with 1 entries
entry 1 is 3
Set RULED_SURF is a surface set with 1 entries
entry 1 is 1
Set BEZIER_CURVE is a curve set with 2 entries
entry 1 is 1
entry 2 is 2
Set EDGES is a edge set with 4 entries
entry 1 is 1 edge number 2
entry 2 is 2 edge number 1
entry 3 is 3 edge number 1
entry 4 is 3 edge number 2
Contact Bodys 4
Contact Body 1 , Id 1 Name surface
Contact Body 2 , Id 2 Name the_mesh
Contact Body 3 , Id 3 Name refined_mesh
Contact Body 4 , Id 5 Name empty_cbody
Materials 2
Material steel Type mechanical/isotropic Young's
Mod 3e+007
Plasticity method default Yield Surface general_plasticity
Material stainless Type mechanical/isotropic Young's
Mod 2.9e+007
Plasticity method chaboche Yield Surface von_mises
Boundary Conditions 3
Boundary Cond apply1 Type point_load Values
by: entered
Boundary Cond apply2 Type point_load Values
by: entered
Boundary Cond apply_usersub Type fixed_displacement Values
by: usersub
Geometric Properties 2
Geometric Prop th_shell Type mech_three_shell Thick
0.7
Geometric Prop membrane Type mech_three_membrane Thick
0.2
Initial Conditions 3
Initial Cond icond_velo Type velocity Values by:
entered
Initial Cond icond_mass Type point_mass Values by:
entered
Initial Cond icond_usersub Type displacement Values by:
usersub
Contact Table
Contact Dist Tol : 0.01
Elements 4 Maximum id 4
def find_set_id(name):
n = py_get_int("nsets()")
for i in range(1,n+1):
id = py_get_int("set_id(%d)" % i)
sname = py_get_string("set_name(%d)" %
id)
if( sname == name):
return id
return -1
Figure 7-3 Python Code to Find the Set ID of a Given Set Name
Chapter 8: PyPost: Reading a Post File
Chapter Overview
In this chapter, it will be demonstrated the basics of using PyPost to read a Marc post file. This example will use the
post file of the example created in the previous chapter.
Upon completion of this chapter, you should have a clearer understanding of the following areas:
• The basics of using PyPost
• How to use PyPost to read nodal data
PyPost Basics
In the previous chapter, it was shown how to use PyMentat to post process a post file. The PyMentat module depends
on interacting with Mentat. Sometimes it is more convenient to work in a non-GUI environment, such as an X-Term
window or a Microsoft Windows command prompt window. The PyPost module works in this manner.
PyPost is an API used in a Python script to obtain the results from a Marc post file. The PyPost module contains one
routine that is used to open a post file, post_open. This routine returns a PyPost object. This PyPost object contains
the methods that are used to access various data items in the post file.
When using the PyPost module, you will import the module in the same way as importing the PyMentat module using
the statement:
from py_post import *
To begin accessing a post file, you must call the PyPost routine post_open, such as:
pObj = post_open("chap5_job1.t16")
This statement opens the post file named chap5_job1.t16 and returns a PyPost object, storing it in the variable pObj.
This example is named chap8.py and can be found in the Mentat directory examples/python/tutorial/c08. The
following Python code obtains the nodal scalar values from the post file used in the previous chapter:
1. from py_post import *
2. def main(fname):
3. p = post_open(fname)
4. try:
5. p.moveto(1)
6. except:
7. print ‘Error opening post file: ‘,fname
8. return
9.
10. max_scalars = []
11. max_nodes = []
64 Marc Python Tutorial
12.
13. nns = p.node_scalars()
14. print "Found ", nns, " node scalars "
15. for i in range(0,nns):
16. max_scalars.append(-1.0e20)
17. max_nodes.append(0)
18.
19. # find maximum nodal scalars
20. for j in range(0, nns):
21. k= 0
22. numnodes = p.nodes()
23. while k < numnodes:
24. d = p.node_scalar(k,j)
25. if d < 0.0:
26. d = -d
27. if d > max_scalars[j] :
28. max_scalars[j] = d
29. max_nodes[j] = p.node_id(k)
30. k = k + 1
31.
32. print " Label node scalar"
33. print " ---------------------------------------"
34.
35. for i in range(0,nns):
36. str = " %18s %10i %g" % (p.node_scalar_label(i),
max_nodes[i],max_scalars[i])
37. print str
38. return
39.
40. if __name__ == '__main__':
41. main("../c06/chap5_job1.t16")
CHAPTER 8 65
PyPost: Reading a Post File
Line 3 The post_open routine is called with the post file name chap5_job1.t16. It returns the PyPost
object that is stored in the variable p. All subsequent PyPost methods called will be members of this
PyPost object.
Lines 4-5 The max_scalars and max_nodes variables are declared as Python Lists. The index of the list
will be each of the scalars in the post file. The maximum scalar value will be stored in the
max_scalars list. The node associated with the max_scalar value will be stored in the
max_nodes list.
Line 7 Go to the first increment.
Lines 4-8 We call the moveto method to go to the first increment using the try/except statements to check for
an error. When the post file is opened, it is at increment 0. Increment 0 contains only the model data.
We need to explicitly go to the first increment even though there is only one increment of data in the
post file.
Lines 10-11 The max_scalars and max_nodes variables are declared as Python Lists. The index of the list
will be each of the scalars in the post file.
Line 13 This statement will call the node_scalars method to obtain the total number of nodal scalars
stored in the post file.
Lines 15-17 The lists are initialized.
Line 20 This begins the main loop for the scalars.
Line 22 Obtain the number of nodes. If this post file had multiple increments, we would have to call the nodes
method every increment, since rezoning will change the number of nodes.
Line 23 Loop through all the nodes. Note that we use a while loop for this. We had been using the range
function, however, Python builds a list of all the values in the range for this function. If we had
100,000 nodes, Python would build a list that large.
Line 24 Get the scalar value for this scalar (k) and node (j).
Lines 25-26 Ignore the sign of the values and only work with magnitudes.
Lines 27-29 Check the current value against the current maximum value. Convert the node sequence number to
the node id using the node_id method.
Lines 35-37 Print out the results for each scalar.
Found 6
node scalars
Label node scalar
-------------------------------------------
Displacement x 53 0.00128282
Displacement y 49 0.00565143
External Force x 1 0
External Force y 50 187.5
Reaction Force x 82 2866.6
Reaction Force y 81 921.814
Chapter Overview
In this chapter, it will be demonstrated how to obtain element data from a post file. This example will use the post file
of that created in Chapter 6: PyMentat: Processing a Post File.
Upon completion of this chapter you should have a clearer understanding of the following areas:
• Obtaining the element data from a post file
• The element extrapolation methods available
linear Extrapolate by averaging the integration points to the centroid of the element and then doing a
linear extrapolation from the centroid through the integration point to the node.
translate Do not extrapolate, but rather copy the data at each integration point to its corresponding node. In
those cases where there are fewer integration points than nodes, some averaging of neighboring
integration points may be done.
average The average of all the integration points is computed and assigned to the nodes. Therefore, all
nodes have an equal value assigned to them.
4 7 3 4 7 3
3 4
8 6 8 6
1 2
1 5 2 1 5 2
Eight node quadrilateral Four Gaussian integration points
Node
Integration pt
Figure 9-1 Element Class 8: Eight Noded Isoparametric Quadrilateral Elements
The quadrilateral element of Figure 9-1 contains eight nodes and four integration points. For this element, the PyPost
method of element_scalar will return a list of eight nodes and eight scalar values. If the extrapolation method is
average, all eight nodes will have the same value. If the extrapolation method is translate, then node 5 would be
calculated by averaging integration points 1 and 2. If the integration method is linear, then all four integration points
are averaged together and computed for the centroid of the element. The values for the nodes are linearly extrapolated
from the centroid to their position on the element.
This example is named chap8.py and can be found in the Mentat directory examples/python/tutorial/c08. The
following is the Python code:
1. from py_post import *
2. def main(fname):
3. p = post_open(fname)
4. try:
5. p.moveto(1)
6. except:
7. print ‘Error opening post file: ‘,fname
8. return
9.
10. max_scalars = []
11. max_nodes = []
12. max_incs = []
13. nns = p.node_scalars()
70 Marc Python Tutorial
47. k = 0
48. numelems = p.elements()
49. while k < numelems:
50. sca = p.element_scalar(k,j)
51. l = len(sca)
52. m = 0
53. while m < l :
54. val = sca[m]
55. if val < 0.0:
56. val = -val
57. if val > max_scalars[nns+j] :
58. max_scalars[nns+j] = val
59. max_nodes[nns+j] = nod[m]
60. max_incs[nns+j] = p.increment
61. m = m + 1
62. k = k + 1
63. j = j + 1
64.
65. print " Item Label increment node scalar"
66. print " ------------------------------------------"
67.
68. for i in range(0,nns+nes):
69. if i < nns:
70. s = p.node_scalar_label(i)
71. else:
72. s = p.element_scalar_label(i-nns)
73. str = "%7i %36s %7i %10i %g" % ((i+1),s,max_incs[i],
max_nodes[i],max_scalars[i])
74. print str
75.
76. return
77.
78. if __name__ == '__main__':
79. main("../c06/chap5_job1.t16")
72 Marc Python Tutorial
Line 3 The post_open routine is called with the post file name chap5_job1.t16. It returns the PyPost
object that is stored in the variable p. All subsequent PyPost calls will be members of this PyPost
object.
Lines 4-8 We call the moveto method to go to the first increment using the try/except statements to check for an
error. When the post file is opened, it is at increment 0. Increment 0 contains only the model data. We
need to explicitly go to the first increment even though there is only one increment of data in the post
file.
Lines 10-12 The max_scalars, max_nodes, and max_incs variables are declared as Python Lists. The
index of the list will be each of the scalars in the post file. The maximum scalar value will be stored
in the max_scalars list. The node associated with the max_scalar value will be stored in the
max_nodes list and the associated increment will be stored in the max_incs list.
Lines 13-14 The node_scalars method is called to obtain the total number of nodal scalars and the
element_scalars method is called to obtain the total number of element scales stored in the post
file.
Lines 19-22 The lists are initialized. Note that the lists contain both the nodal and element scalar data.
Line 24 The outer loop is the one for the increments.
Lines 25-26 We call the moveto method with the current index number to step through the increments. Remember
that the index number passed in the moveto method is not the same number as that which appears in
the post file. In line 21, we print out the current index number, and the increment number as it appears
in the post file.
Lines 29-42 This is the nodal scalars section, which is the same as that of the previous chapter.
Lines 45 Begin the loop for the element scalars.
Lines 48-49 Obtain the number of elements in the current increment. Rezoning may cause the number of elements
to change between increments. Loop through all the elements.
Line 50 Obtain the element scalars. The element_scalar method will return a list of PyScalar values. A
PyScalar has two members: an id and a value. The id represents the node ID, and value represents the
scalar value.
Line 53 Loop over every node in the list.
Line 54 The PyScalar list returned is "read-only". This means that the values in the list cannot be changed.
Lines 55-60 Check each value in the PyScalar list and compare them to the maximum values.
Lines 65-74 Print out the results for each scalar.
When the script completes, the output will be appear as shown in Figure 9-2.
In the next chapter, we will write a simple script to find the stresses greater than a given value.
Chapter 10: PyPost: Element Tensor Data
Chapter Overview
In this chapter, it will be demonstrated how to use the PyPost module to examine the element tensors. This example
will use the post file of that created in Chapter 6: PyMentat: Processing a Post File.
Upon completion of this chapter, you should have a clearer understanding of the following areas:
• Obtaining the element tensors
• Working with elements tensor data in a Python script
22.
23. def get_tensors(fname):
24. p = post_open(fname)
25. try:
26. p.moveto(1)
27. except:
28. print ‘Error opening post file: ‘,fname
29. return
30.
31. max_values = []
32.
33. net = p.element_tensors()
34. ninc = p.increments()
35. print "Found ", net, " element tensors "
36. print ninc, " increments "
37.
38. if net == 0 :
39. print "Did not find element tensors"
40. return
41.
42. for i in range(0,net):
43. max_values.append(TensorData(0.0, 0, 0))
44.
45. i = 1
46. while i < ninc:
47. print "Scanning increment ",i
48. p.moveto(i)
49.
50. j = 0
51. while j < net:
52. k = 0
53. num = p.elements()
54. while k < num:
55. el = p.element_tensor(k,j)
CHAPTER 10 77
PyPost: Element Tensor Data
56. l = len(el)
57. m = 0
58. while m < l :
59. d = el[m].intensity
60. if d > max_values[j].value() :
61. max_values[j].set_data(d, el[m].id, i)
62. m = m + 1
63. k = k + 1
64. j = j + 1
65.
66. i = i + 1 # next increment
67.
68. print " Item Label increment node tensor"
69. print " ------------------------------------------"
70.
71. for i in range(0,net):
72. j = max_value[i].node()
73. s = p.element_tensor_label(i)
74. str = "%7i %16s %7i %10i %g" %
((i+1),s,max_values[i].increment(),
j,max_values[i].value())
75. print str
76. return 1
77.
78. def main(fname):
79. get_tensors(fname)
80. return
81.
82. if __name__ == '__main__':
83. main(sys.argv[1])
Line 2 The system module sys is imported to provide access to the command line arguments.
Lines 3-21 A Python class is created to hold and retrieve the data.
Line 24 The post_open routine is called with the post file name passed in as the first command line
argument.
78 Marc Python Tutorial
Lines 25-29 We call the moveto method to go to the first increment using the try/except statements to check for an
error. When the post file is opened, it is at increment 0. Increment 0 contains only the model data. We
need to explicitly go to the first increment even though there is only one increment of data in the post
file. This must be performed before we attempt to get any data from the post file, such as the number
of element scalars available.
Lines 33-34 The number of element tensors and the number of increments in the post file are obtained.
Line 46 Begin the increment loop.
Line 53 Obtain the number of elements in this increment. Rezoning may cause the number of elements to
change between increments.
Lines 55-58 Obtain the list of PyTensors, and find the length of the list.
Lines 58-61 For each item in the list, compare it to the maximum value. The set_data method of the
TensorData class is used to set the values.
Lines 71-75 Print the results. In line 69, the node method of the TensorData class is called to obtain the node ID.
Line 83 The filename is specified as the first argument to the script.
Chapter Overview
In this chapter, it will be demonstrated how to use Mentat Parameters in a Python script using the PyMentat module.
It will also be shown how to run a Python script as a separate process. Upon completion of this chapter, you should
have a clearer understanding of the following areas:
• The py_connect method
• Handling socket errors
MAIN
UTILS
PARAMETERS
NEW PARAMETER
x_size
10
y_size
8
x_start
-1.0
y_start
-1.0
Remember to press the carriage <CR> after typing in each of the numbers to create the parameters. The procedure file
chap3.proc may be executed to perform the above commands for you if you wish.
CHAPTER 11 83
PyMentat: Using the py_connect Method
You may also type the *define command in Mentat’s command prompt window to create or edit the parameter. For
example, to create the parameter x_size you would type
*define x_size 10
As in the previous chapter, bring up the Python browser window with the menus:
MAIN
UTILS
PYTHON
RUN
When the script completes, a mesh is created the same as in Chapter 3: PyMentat: Obtaining Data from Mentat.
Chapter 12: PyPost: Plotting
12 PyPost: Plotting
Chapter Overview 85
Charting Script for Mentat 85
The Gnuplot Module 88
The PyOpenGL Module 92
CHAPTER 12 85
PyPost: Plotting
Chapter Overview
In this chapter, it will be demonstrated how to use third party Python modules in a Python script to plot the results from
a post file. Three examples of plotting will be shown:
• Using the gdchart module to create a GIF plot
• Using the gnuplot module to create charts with Gnuplot.
• Using the OpenGL module to display 3-D models with PyOpenGL.
The examples shown here were developed only for Microsoft Windows. See the readme.txt file in the
examples/python/tutorial/c12 directory for information regarding what needs to be installed to run these
examples.
18.
19. def main(fname):
20. p = post_open(fname)
21. p.moveto(1)
22. nns = p.node_scalars()
23. ninc = p.increments()
24. print " Increments = ",ninc
25.
26. # The list of nodes to plot
27. check_nodes = (42, 66, 78, 86)
28.
29. # Create an array for the displacements of
30. # the nodes in the list
31. displacements = [None]*len(check_nodes)
32. for i in range(0,len(check_nodes)):
33. displacements[i] = [0.0] * ninc
34.
35. Incs = [' '] * ninc
36.
37. nlocy = 0
38. for i in range(0,nns):
39. s = p.node_scalar_label(i)
40. if s == "Displacement Y" :
41. nlocy = i
42.
43. for i in range(1, ninc):
44. p.moveto(i)
45. print "scanning post file increment",p.increment
46. Incs[i] = `p.increment`
47.
48. # get the Y displacements for specified nodes
49. for k in range(0,len(check_nodes)):
50. j = p.node_sequence(check_nodes[k])
51. displacements[k][i] = p.node_scalar(j,nlocy)
CHAPTER 12 87
PyPost: Plotting
52.
53. title = "Nodes "
54. for k in range(0,len(check_nodes)-1):
55. title = title + `check_nodes[k]` + ","
56. title = title + `check_nodes[len(check_nodes)-1]`
57.
58. do_plot("chapt12a.gif", title, Incs ,displacements)
59.
60. if __name__ == '__main__':
61. main("../c09/chap9.t16")
In this example, you would run the script on the command line as:
python chap12a.py
The output from the script is shown in Figure 12-1.
88 Marc Python Tutorial
7. except:
8. print "Gnuplot has not been installed"
9.
10. def gnu_plot(fname, title, Incs, dta, check_nodes):
11. import time
12. g = Gnuplot.Gnuplot(debug=1)
13.
14. g.title(title)
15. g('set data style linespoints')
16. g('set size .6,.6')
17. d = [None] * len(check_nodes)
18. for i in range(0,len(check_nodes)):
19. d[i] = Gnuplot.Data(Incs, dta[i], title="Node "
+ `check_nodes[i]`, with='lines ' + `i+3`+ ' ' + `i+3`)
20. g.xlabel('Increments')
21. g.ylabel('Y-Displ')
22. g.plot(d[0], d[1], d[2], d[3])
23. if os.name == "nt" :
24. raw_input('Please press return to continue...\n')
25. else :
26. time.sleep(5)
27.
28. g.hardcopy(fname, color=1) # enhanced = 1
29. print '**** Saved plot to postscript file "%s" ****\n' % fname
30. time.sleep(1)
31. return
32.
33. def main(fname):
34. p = post_open(fname)
35.
36. p.moveto(1)
37. nns = p.node_scalars()
38. ninc = p.increments()
39. print " Increments = ",ninc
90 Marc Python Tutorial
40.
41. check_nodes = (42,66,78, 86)
42. displacements = [None]*len(check_nodes)
43. for i in range(0,len(check_nodes)):
44. displacements[i] = [0.0] * ninc
45.
46. Incs = [0] * ninc
47. nlocy = 0
48.
49. # find the index for the displacements
50. for i in range(0,nns):
51. s = p.node_scalar_label(i)
52. if s == "Displacement Y" :
53. nlocy = i
54.
55. for i in range(1, ninc):
56. p.moveto(i)
57. print "scanning post file increment",p.increment
58. Incs[i] = p.increment
59.
60. # find all y displacements for specified nodes
61. for k in range(len(check_nodes)):
62. j = p.node_sequence(check_nodes[k])
63. dy = p.node_scalar(j,nlocy) # k
64. displacements[k][i] = dy
65.
66. gnu_plot("chap12b.ps", "Node Displacements", Incs, displacements,
check_nodes)
67.
68. if __name__ == '__main__':
69. main("chap12.t16")
Lines 4-8 Use the try/except statement to trap an error if the module gnuplot is not available.
Line 10 The gnu_plot routine is a convenient wrapper function to the plotting routine Gnuplot in the
gnuplot module.
CHAPTER 12 91
PyPost: Plotting
When the script completes, a plot as shown in Figure 12-2 is displayed in the Gnuplot program, and is saved as a
PostScript plot in the file chap12b.ps.
198.
199. k = 0
200. n = p.elements()
201.
202. # Create the x and y coordinate arrays for plotting.
203. # We should check the element list to find out how many
204. # nodes are in each element.
205. # We know for this model all elements have 3 nodes.
206. nodex = [0.0]*(n*3)
207. nodey = [0.0]*(n*3)
208. nodedx = [0.0]*(n*3)
209. nodedy = [0.0]*(n*3)
210. maxx = maxy = -10000.0
211. minx = miny = 10000.0
212.
213. cnt=0
214. # build the x and y coordinate arrays
215. while k < p.elements():
216. el = p.element(k)
217. for m in range(0,el.len):
218. id=find_node(el.items[m],nod)
219. if id >=0 :
220. nodex[cnt] = nod[id].x()
221. nodey[cnt] = nod[id].y()
222. nodedx[cnt] = nod[id].x() + nod[id].dx()
223. nodedy[cnt] = nod[id].y() + nod[id].dy()
224. find_maxmin(nodex[cnt], nodey[cnt])
225. find_maxmin(nodedx[cnt], nodedy[cnt])
226. cnt = cnt+1
227. k = k +1
228.
229. # Generate the Win object containing the viewport info
230. minx = minx - .25*(maxx-minx)
231. maxx = maxx + .25*(maxx-minx)
CHAPTER 12 99
PyPost: Plotting
Lines 116-133 The draw_legend routine draws a legend in the lower left corner reflecting the color of the lines
used for the deformed and undeformed shape.
Lines 135-147 The redraw routine is called by the Tkinter toolkit (which is registered at line 247) to redraw the
window. It calls the mode_3d routine to setup the 3-D window, and then draws the elements, plots
the nodes, and draws the legend. If the window is resized or receives an expose event, the toolkit
will call this routine.
Lines 149-153 The find_node routine finds the index of a node id in the nod array.
Lines 155-160 The find_maxmin routine finds the maximum and minimum x and y values in the model. This is
used to determine the values to specify when creating the 3-D window.
Lines 163-167 Declare some global variables.
Lines 176-182 Determine the index of the X and Y displacements in the post file.
Lines 188-197 Create an array of Displ objects to store the displacement data. Loop over all of the nodes and
create an object.
Lines 206-209 Create the arrays to store the actual x and y coordinates to plot.
Line 215 Loop through all the elements.
Lines 217-226 For each node in the element, get the index of the node in the nod array and store the data in the
undeformed x and y arrays (nodex and nodey), and also in the deformed x and y arrays (nodedx
and nodedy). The find_maxmin routine is called to find the maximum and minimum values so that
the window may be scaled appropriately.
Lines 229-234 Find the minimum and maximum values for the data so that the window can be created with the
proper limits.
Lines 236-237 Create the window frame using the Tkinter toolkit.
Lines 238-242 Create a quit button and a label that specifies the number of increments.
Lines 243-247 Create the OpenGL object and specify the width, height and whether double buffering is needed.
Specify the redraw routine (line 244) and get the window focus. Then start the main loop event
processing (line 247).
CHAPTER 12 101
PyPost: Plotting
Chapter Overview
In this chapter the basics of obtaining database values using the menu system lookup functions will be demonstrated.
Upon completion of this chapter, you should have a clearer understanding of the following areas:
• The fundamentals of the menu system lookup functions.
• How to use the lookup functions in a Python script to obtain database values.
Integer py_ms_int
Double py_ms_double
String py_ms_string
Boolean py_ms_bool
State py_ms_state
The list of possible database item names are quite long and are not listed here - the name of the item should be obtained
via the menu file. To obtain the name of a database item, run Mentat, and when viewing the required item on a menu
screen, place the cursor over the desired menu item and press the F2 function key to view/edit the menu file. On a Unix
system, the cursor goes directly to the menu item; however, on Microsoft Windows, you need to do a search to get to
the proper location. For example, open a model file or a post file and go to the UTILS->SIZES menu. Place the cursor
over the COUNT item in the ELEMENTS row and press the F2 button. On a Unix system, the cursor is brought to the
proper location which displays an integer database item displaying db_count_elements. For this case, the
function call uses the py_ms_int function to retrieve the value:
nelems = py_ms_int(‘db_count_elements’,0)
For Microsoft Windows users that are using the default editor, you need to do a search of “COUNT” (that is, search
for part of the table’s title) to get to the proper menu text. If you have a ‘vi’ editor for Microsoft Windows, you can use
that instead by modifying the bin\edit_window.bat script.
The names of some items may require spaces to be used in the text; however, this is not allowed in the Python text
strings. Substitute a ‘&’ or a ‘@’ symbol for any embedded spaces.
104 Marc Python Tutorial
Integer Function
The database values for integer items may be obtained using the py_ms_int function. The first argument is the name
of the database item, the second argument is the index of the item. Any item in a menu file that is represented as an
integer may be obtained, such as:
integer {
position +10 =
size 10 4
display ‘db_count_nodes’
}
The Python code for this example would be:
nnodes = py_ms_int(‘db_count_nodes’,0)
The index value is nonzero where lists of items are used, such as the values on a post file for each increment. An
example would be post_size: The following obtains the post file size data for the 6th increment on the post file:
n = py_ms_int(‘post_size’,5)
Double Function
The database values for floating point (float or double) items may be obtained using the py_ms_double function.
The database may store items either as a double or a float; hence, for float items, the value is cast as a double and
returned. The first argument is the name of the database item, the second argument is the index of the item. Any item
in a menu file that is represented as a float may be obtained, for example:
float {
position +26 =
size 12 4
display lcase_time_step
}
The Python code for this example would be:
tstep = py_ms_double(‘lcase_time_step’,0)
An example of a menu item that uses a non-zero index would be post_time: The following obtains the post file time
value for the 6th increment on the post file:
n = py_ms_double(‘post_time’,5)
String Function
The database values for string or text items may be obtained using the py_ms_string function. The first argument
is the name of the database item, the second argument is the index of the item. Any item in a menu file that is
represented as a text item (character string) may be obtained, for example:
text {
position +1 +4
CHAPTER 13 105
PyMentat: Menu System Lookup Functions
size 30 4
display post_file
command ‘*post_open’
}
The Python code for this example would be:
tstep = py_ms_string(‘post_file’,0)
In some cases a text value of an integer or floating point value are displayed. In these cases the string will appear as
display d_gmodel_data_defmag
display i_geomdist_grid_div
The first character denotes the data type, such as i for integer or d for double (float).
The index value is non-zero where lists of items are used, such as the values on a post file for each increment. An
example would be post_time: The following obtains the name of the second contact body in a model file:
str = py_ms_string(‘cbody_list_name’, 1)
Boolean Function
The database values for boolean items may be obtained using the py_ms_bool function. The first argument is the
name of the database item, the second argument is the index of the item. Any item in a menu file that is represented as
a toggle or a oneonly may be obtained, for example:
toggle {
position +15 =
size 8 4
text ‘GRID’
true_command ‘*set_grid on’
false_command ‘*set_grid off’
toggle set_grid
}
oneonly {
position 1 +4
size 10 4
text ‘FOLLOWER FORCE’
commands ‘*job_option follow:on’
oneonly ‘*job_option follow:on’
}
The Python code for the examples shown above would be:
bGrid = py_ms_bool(‘set_grid’,0)
bFollow = py_ms_bool(‘*job_option&follow:on’,0)
The grid example returns 1 if the grid is on; false if it is off. The job_option example returns true if the follower
force option is on; false if not. If an option has multiple states, then the State function is used. The job_option of
follower force actually has four states, so the state function should be used to get the active state.
106 Marc Python Tutorial
State Function
The database values for state items may be obtained using the py_ms_state function. State items are similar to
boolean items, except that in most cases they have multiple conditions, but not in all cases (such as
acis_file_check). The first argument is the name of the database item, the second argument is the index of the
item.
There are much fewer state items than integer, double, string or booleans, and the return values may not be clear, hence
they are listed in the following table. A state item is generally represented in a menu file that is defined as a roller item,
however it may also appear as a oneonly. Note that in some cases the name will include the preceding asterisk, simliar
to that of the actual command. A menu example for a roller button is as follows:
roller {
position 1 1
size 36 4
nvalues 4
texts ‘NO FOLLOWER FORCE’
‘FOLLOWER FORCE’
‘FOLLOWER FORCE/STIFFNESS’
‘FOLLOWER FORCE/(BEGIN INC)’
commands ‘*job_option follow:off’
‘*job_option follow:on’
‘*job_option follow:stiffness’
‘*job_option follow:begin_inc’
roller ‘job_option follow’
}
ctable_bodies_option
ctable_entry
curve_div_applyrest_state *set_curve_div_applyrest_<cvs|lps> command state:
0 = individual cuirves (cvs), 1 = detected loops (lps).
curve_div_tol_state State of *set_curve_div_tol_(rel, abs) commands:
0 = relative, 1 = absolute.
geometry_option
job_option
job_post_eq_layers Post layers: 0 for default, 1 for All, 2 for out&mid, 3 for list.
match_mesh_dir *set_match_mesh_dir state: 0 = from side a to b, 1 = from side b to a.
mesh_parameter_ SuperForm mesh parameter settings.
mesh_split_method_1d Match split method 1D: 0=element base, 1 = plane
mesh_split_method_2d Match split method 2D: 0=element base, 1 = plane, 3 = smooth
mesh_split_method_3d Match split method 3D: 0=element base, 1 = plane
numerics_format Numerics format: 0 for automatic, 1 for exponential, 2 for floating, 3 for
integer
save_file_type Formatted file type returns 0, binary type returns 1
select_filter 0 = none, 1 = outline, 2 = surface, 3 = top, 4 = bottom
select_method 0 = single, 1 = path, 2 = box, 3 = user_box, 4 = plane, 5 = flood,
6 = associate, 7 = point_dist, 8 = curve_dist, 9 =s urface_dist
108 Marc Python Tutorial
MentatDCOM: Connecting to
14 Mentat using a .NET Module
Chapter Overview 111
MentatDCOM Basics 111
Running the Program 114
MentatDCOM and PyMentat 115
CHAPTER 14 111
MentatDCOM: Connecting to Mentat using a .NET Module
Chapter Overview
In this chapter it will be demonstrated the basics of using the MentatDCOM module to connect to Mentat using
programs created with Microsoft Visual Studio 2005 or later. An example will be shown which uses code similar to
that of the example discussed in Chapter 2.
Upon completion of this chapter, you should have a clearer understanding of the following areas:
• The basics of using MentatDCOM
• How to use MentatDCOM to send data to Mentat
MentatDCOM Basics
In Chapter 2, it was shown how to use PyMentat to connect to Mentat and build a simple model. The MentatDCOM
module is a .NET assembly module built with Microsoft Visual Studio 2005 to provide an API simliar to that of
PyMentat to send and receive data from Mentat. As a .NET assembly module, it allows any .NET module to access the
members functions, using languages such as VB.NET, C#, J#, etc. It connects to Mentat using a DCOM interface which
must be registered in the Microsoft Windows registry before it can be used. This is done by running the *dcom_reg
command in Mentat. This command has to be run only once. The interface remains registered if Mentat is closed.
The DCOM interface is initiated in a Mentat session using the *dcom_init command. The MentatDCOM module
contains a class named MentatData which must be instantiated by the client. This MentatData object contains the
methods that are used to send commands and retrieve various data items. The first method that must be called is used
to start the connection, connect and returns either 0 for a successfull connection or non-zero if there was an error.
Note that the MentatDCOM module (DLL) must be in the same directory as your executable, otherwise it will not be
found.
When using the MentatDCOM module, you will import the module in a similar way as importing the PyMentat
module, using the appropriate language syntax:
C++/CLI
using namespace MentatDCOM;
C#
using MentatDCOM;
VB.Net
Imports MentatDCOM
In the main program, the MentatData object is created which provides acces to the member functions:
C++/CLI
MentatData p = gcnew MentatData();
C#
MentatData p = new MentatData();
112 Marc Python Tutorial
VB.Net
Dim p as New MentatData()
The program example discussed in this chapter will be a C# program performing the same functions as shown in
Chapter 2.
1. using System;
2. using MentatDCOM;
3. namespace MentatTest
4. {
5. class Chap14
6. {
7. static MentatData p;
8. static void make_nodes(int s, int t, double xs, double ys)
9. {
10. int i, j;
11. double x, y, z, delx, dely;
12. y = ys;
13. z = 0.0;
14. delx = 1.0/(double)s;
15. dely = 1.0/(double)t;
16. string str;
17. for(i = 0; i < t; i++)
18. {
19. x = xs;
20. for(j = 0; j < s; j++)
21. {
22. str = "*add_nodes " + x.ToString()
23. + " " + y.ToString() + " " + z.ToString();
24.
25. p.send(str);
26. x = x + delx;
27. }
28. y = y + dely;
29. }
30. return;
CHAPTER 14 113
MentatDCOM: Connecting to Mentat using a .NET Module
31. }
32.
33. static void make_elements(int n, int m)
34. {
35. int i, j, n1, n2, n3, n4;
36. string str;
37. for(i = 1; i < m; i++) // the "y" dir
38. {
39. n1 = (i-1) * (n) + 1;
40. n2 = n1 + 1;
41. n4 = n1 + (n);
42. n3 = n2 + (n);
43. for(j = 1; j < n; j++ ) // the "x" dir
44. {
45. str = "*add_elements "+n1.ToString()+" " +
46. n2.ToString() + " " + n3.ToString() + " " + n4.ToString();
47. p.send(str);
48. n1++;
49. n2++;
50. n3++;
51. n4++;
52. }
53. }
54. return;
55. }
56.
57. static void Main(string[] args)
58. {
59. string host = "local";
60. if (args.Length > 0){
61. host = args[0];
62. }
63. Console.WriteLine("chap14 {0}", host);
64. p = new MentatData();
114 Marc Python Tutorial
Lines 1-2 Import the modules to be used. The System module is required for using the WriteLine method, the
MentatDCOM module provides access to the MentatData class.
Lines 7 Declare the MentatData object member.he argument list passed to the main function is checked for
the post file name.
Lines 8-55 This code is similar to the Python code of Chapter 2.
Lines 60-62 The argument list passed to the main function is checked for the host name.
Line 64 The MentatData Object class is initialized. It creates the MentatData object and is stored in the
variable p. All subsequent MentatDCOM methods called will be members of this object.
Lines 65-69 The connect method is called with the hostname of the computer.
Lines 70-75 This code is similar to the Python code of Chapter 2.
Line 76 The disconnect method is called to close the connection.
The buildit.bat script will compile the program for you. Start Mentat (from either the shortcut on the desktop or
another command prompt window) and enter the command:
*dcom_init
Run the DCOM program as:
chap14_cs
When the script completes, a mesh will be created as shown in Figure 14-1.
connect(String ^host) This method is called py_connect in PyMentat. It initializes the connection to
Mentat. Note that the port number has been removed. It returns zero on success,
non-zero on failure. The host string is currently ignored.
int ret = p.connect(‘localhost’); // C# syntax
int ret = p->connect(‘localhost’); // C++ syntax
ret = p.connect(‘localhost’); ‘ VB syntax
116 Marc Python Tutorial
disconnect() This method is called py_disconnect in PyMentat and closes the DCOM
connection.
p.disconnect();
send() This method is called py_send in PyMentat and sends a command string:
p.send(‘*set_grid on’);
get_string() This method is called py_get_string in PyMentat and returns a string:
String ^nm = p.get_string(‘model_name()’);
Console::WriteLine(‘{0}’, nm);
get_double() This method is called py_get_float in PyMentat. It returns a type of double.
string s = ‘element_mass(-1)’;
double f = p.get_double(s);
Console::WriteLine(‘Mass {0}’, f);
get_int() This method is called py_get_int in PyMentat. It returns a type of integer.
string s = ‘nnodes()’;
int n = p.get_int(s);
Console::WriteLine(‘Node count {0}’, n);
update() This method is called py_update in PyMentat. It forces a graphics update to
allow the image_save routines to function properly.
p.send(‘*image_save_rgb 1 test.rgb yes’);
p.update();
Note that graphics updates will not function properly when running the OpenGL
version of Mentat. The OopenGL graphics engine reports a ‘ERROR_BUSY’
error for the OpenGL calls when a separate process accesses Mentat via DCOM.
Note: The Mentat DCOM module (MentatDCOM.dll) must be in the same directory as your executable,
otherwise it will not be found.
Chapter 15: MarcPost: Reading a Post File using a .NET Module
Chapter Overview
In this chapter, it will be demonstrated the basics of using the MarcPost module to read a Marc post file using programs
created with Microsoft Visual Studio 2005 or later. This example will use the post file of the example used in Chapter
6: PyMentat: Processing a Post File.
Upon completion of this chapter, you should have a clearer understanding of the following areas:
• The basics of using MarcPost
• How to use MarcPost to read nodal data
MarcPost Basics
In Chapter 8: PyPost: Reading a Post File, it was shown how to use PyPost to post process a Marc post file. The
MarcPost module is a .NET assembly module built with Microsoft Visual Studio 2005 to provide an API similar to that
of PyPost to obtain the results from a Marc post file. As a .NET assembly module, it allows any .NET module to access
the members functions, using languages such as VB.NET, C#, J#, etc. The MarcPost module contains a method that is
used to open a post file, open (or post_open) and return a PostData object. This PostData object contains the
methods that are used to access various data items in the post file. Note that the MarcPost module (MarcPost.dll)
must be in the same directory as your executable, otherwise it will not be found.
When using the MarcPost module, you will import the module in a similar way as importing the PyPost module, using
the appropriate language syntax:
C++/CLI
using namespace MarcPost;
C#
using MarcPost;
VB.Net
Imports MarcPost
In the main program the PostData object is created which provides acces to the member functions:
C++/CLI
PostData p = gcnew PostData();
C#
PostData p = new PostData();
VB.Net
Dim p as New PostData()
CHAPTER 15 119
MarcPost: Reading a Post File using a .NET Module
The program example discussed in this chapter will be a C# program performing the same functions as shown in
Chapter 8: PyPost: Reading a Post File.
1. using System;
2. using MarcPost;
3. namespace MarcTest
4. {
5. class Chap15
6. {
7. static void Main(string[] args)
8. {
9. if (args.Length < 1){
10. Console.WriteLine("CSPost requires filename");
11. return 1;
12. }
13. Console.WriteLine("CPost {0}", args[0]);
14. PostData p = new PostData();
15. if (p.open(args[0]) > 0)
16. {
17. Console.WriteLine("Failed to open {0}", args[0]);
18. return;
19. }
20. p.moveto(1);
21. int nns = p.node_scalars();
22. Console.WriteLine("Found {0} node scalars", nns);
23. double[] max_scalars = new double[nns];
24. int[] max_nodes = new int[nns];
25. int j, k, numnodes;
26. double d;
27. for(j=0;j<nns;j++) max_scalars[j] = -1.0e20;
28. for(j=0;j<nns;j++)
29. {
30. numnodes = p.nodes();
120 Marc Python Tutorial
31. for(k=0;k<numnodes;k++)
32. {
33. d = p.node_scalar(k,j);
34. if(d < 0.0) d = -d;
35. if(d > max_scalars[j])
36. {
37. max_scalars[j] = d;
38. max_nodes[j] = p.node_id(k);
39. }
40. }
41. }
42. Console.WriteLine(" Label node scalar");
43. Console.WriteLine(" ---------------------------------------------");
44. for(j=0;j<nns;j++)
45. {
46. Console.WriteLine(" {0,20} {1,10:d} {2,-24:g}",
p.node_scalar_label(j),
47. max_nodes[j], max_scalars[j]);
48. }
49. } // end Main
50. } // end class
51. }
Lines 1-2 Import the modules to be used. The System module is required for using the WriteLine method, the
MarcPost module provides access to the PostData class.
Lines 9-12 The argument list passed to the main function is checked for the post file name.
Line 14 The PostData class is initialized. It created the PostData object and is stored in the variable p. All
subsequent MarcPost methods called will be members of this object
Lines 15-19 The open method is called with the post file name chap5_job1.t16.
Line 20 Call the moveto method to go to the first increment. When the post file is opened, it is at increment 0
which contains only the model data. We need to explicitly go to the first increment even though there
is only one increment of data in the post file.
Lines 23-25 The max_scalars and max_nodes variables are declared as arrays. The index of the list will be
each of the scalars in the post file. The maximum scalar value will be stored in the max_scalars
list. The node associated with the max_scalar value will be stored in the max_nodes list.
Line 27 The max_scalars array is initialized.
CHAPTER 15 121
MarcPost: Reading a Post File using a .NET Module
Found 6
node scalars
Label node scalar
-------------------------------------------
Displacement X 53 0.00128282303921878
Displacement Y 49 0.00565143441781402
External Force X 1 0
External Force Y 50 187.5
Reaction Force X 82 2866.59521484375
Reaction Force Y 81 921.813659667969
General Description
cutback The total number of cutbacks
cycles The number of recycles for this increment
increment The current increment
separation The total number of separation recycles
split The total number of increment splittings
soltype The dynamic response flag: 0=Normal, 1=Modal, 2=Buckle, 3=Harmonic, 4=Complex.
subinc The current sub-increment. Non-zero for dynamic analysis.
Energy Description (from block 5180n)
creepenergy The total creep strain energy
dampenergy The total damping energy
elasticenergy The total elastic strain energy
energy The total energy
kineticenergy The total kinetic energy
plasticenergy The total plastic strain energy
thermalenergy The total thermal energy
strainenergy The total strain energy
Variables
buckle The buckling factor (for a buckling analysis)
frequency The frequency (for a modal or harmonic analysis). This value is zero for the static increments of the
analysis and non-zero for the dynamic increments
machangle The machine angle (SuperForm only)
pressure The process pressure
time The transient time
mass The total mass
volume The total volume
Work Description (from block 5180n)
appliedwork The total work done by applied force or displacement
contactwork The total work done by contact or external forces
foundwork The total work done by foundations
CHAPTER 15 123
MarcPost: Reading a Post File using a .NET Module
int post_open(String ^filename) Opens the specified post file and returns 0 on success and 1 otherwise.
int close() Closes a currently open post file. Returns 0.
String ^title() Returns the title of the post file.
int increments() Returns the number of increments on the post file.
int domains() Returns the number of domains.
void moveto(int i) Moves to the i-th increment on the post file.
position() Returns the current increment on the post file, that is, the increment moved to
by the moveto method. In PyPost, position is an attribute; however, in
MarcPost position is a member function. This change is necessary since it
could be changed by the user; however, the position in the file will not be
updated (use the moveto method instead). Example use:
int pos = p.position();
int nodes() Returns the number of nodes in the model for the current increment. The
number of nodes may change for each increment due to remeshing.
int node_id(int i) Returns the id of the i-th node.
int node_sequence(int id) Returns the index number of a particular node id or -1 if the id does not exist.
Node ^node(int i) Returns the nodal data for the i-th node.
int node_displacements() Returns 1 if displacements are available on the post file and 0 otherwise.
int node_displacement(int i, Returns the x-, y- and z-displacements of the i-th node. The return value if the
double *x, double *y, double* z) method is 0 on success and 1 on failure.
int node_scalars() Returns the number of nodal scalar quantities available.
124 Marc Python Tutorial
double node_scalar(int i, int j) Returns the value of the j-th nodal scalar quantity at the i-th node.
String^ node_scalar_label(int i) Returns the name of the i-th nodal scalar quantity.
int node_vectors() Returns the number of nodal vectors available.
String^ node_vector_label(int i) Returns the name of the i-th nodal vector.
int node_vector(int i, int j, Returns the x-, y-, and z-components of the j-th nodal vector at the i-th node.
double *x, double *y, double *z) The return value of the method is 0.
int elements() Returns the number of elements in the model for the current increment. The
number of elements may change for each increment due to remeshing.
int element_id(int i) Returns the id of the i-th element.
element_sequence(int id) Returns the index number of a particular element id or -1 if the id does not
exist.
Element^ element(int i) Returns the element data for the i-th element.
int element_scalars() Returns the number of element scalars available.
String^ element_scalar_label(int i) Returns the name of the i-th element scalar.
int element_vectors() Returns the number of element vectors available.
String^ elelment_vector_label(int i) Returns the name of the i-th element vector.
int element_tensors() Returns the number of element tensor available.
String^ element_tensor_label(int i) Returns the name of the i-th element vector.
int extrapolation(String^ type) Sets the integration point extrapolation method for element data. The
argument is a string specifying the extrapolation method to use:
double cbody_rotation(int i) Returns the rotation for the i-th contact body.
int cbody_displacement(int i, Returns the x-, y-, and z-displacements of the i-th contact body. The return
double* x, double *y, double *z) value of the method is 0 if the body exists and 1 otherwise.
int cbody_force(int i, double* x, Returns the forces in x-, y-, and z-directions for the i-th contact body. The
double *y, double *z) return value of the method is 0 if the body exists and 1 otherwise.
int cbody_moment(int i, Returns the moments about the x-, y-, and z-axes for the i-th contact body. The
double *x, double *y, double *z) return value of the method is 0 if the body exists and 1 otherwise.
int cbody_velocity(int i, Returns the velocities in x-, y-, and z-directions of the i-th contact body. The
double *x, double *y, double *z) return value of the method is 0 if the body exists and 1 otherwise.
int sets() Returns the number of sets on the post file.
String ^version() This method returns the MarcPost module version information:
String ^ver = p.version();
Console::WriteLine(‘{0}’,ver);
Example output Assembly name MarcPost, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null
Marc Python Reference
Introduction
Using the Python Modules 3
Variable Types 3
3 Marc Python Reference
Variable Types
The type definitions for functions and methods used in this manual are as follows:
String A character string. This type is similar to the C type of char, and the FORTRAN type of character*(*)”. A
string may be specified by using either single quotes or double quotes.
Float A floating point value. This is similar to the C type of double and the FORTRAN type of real*8.
Integer An integer (or fixed point) value. This is similar to the C type of long int and the FORTRAN type of
integer*8.
List A Python List object. A Python list is essentially a linked list that can be accessed as an array.
Chapter 1: PyMentat References
1 PyMentat References
PyMentat 5
py_connect 6
py_disconnect 7
py_echo 8
py_get_data 9
py_get_float 10
py_get_int 11
py_get_string 12
py_prompt 13
py_send 14
5 Marc Python Reference
PyMentat
This chapter describes the PyMentat routines.
PyMentat is the interface module for Python scripts to communicate to Mentat. Mentat must be running prior to
invoking any PyMentat routine.
A Python script using PyMentat can be run either in “embedded” mode or as a separate process. If invoked as a separate
process, the py_port/py_connect routines must be the first PyMentat routines called.
All Python scripts that need access to the PyMentat module must import the module as:
from py_mentat import *
CHAPTER 1 6
PyMentat References
Synopsis
py_connect(String hostname, Integer nPort)
Arguments
hostname Hostname of system to make connection with
nPort Port number
Description
This routine attempts to establish a socket connect with Mentat on the host specified by hostname, using port number
nPort. The hostname can be an IP address or a DNS name. If hostname is an empty string (“”), then the local host is
used.
A Python script executed as a separate process would use this routine to enable it to communicate with Mentat. It must
be the first PyMentat function called. In addition, Mentat should be waiting for a connection (the Mentat command
*py_connect should have been issued).
Example
if __name__ == ”__main__”:
py_connect(”127.0.0.1”, 40007)
main()
7 Marc Python Reference
Synopsis
py_disconnect()
Arguments
None
Description
This routine terminates a socket connect with Mentat after a successful connection with the py_connect routine.
Example
if __name__ == ”__main__”:
py_connect(”127.0.0.1”, 40007)
...
py_disconnect()
main()
CHAPTER 1 8
PyMentat References
Synopsis
py_echo(int flag)
Arguments
flag An integer used to enable/disable echo.
Description
This routine affects command echoing in Mentat’s dialogue area. If flag is set to true (a nonzero value), then the
commands are echoed. If flag is set to false (zero), then commands sent to Mentat are not echoed. This routine is most
helpful in debugging Python scripts. The default setting is on. Note that enabling echo slightly affects performance.
Mentat command echoing for Python scripts may also be enabled in Mentat using the button:
UTILS->PYTHON->SCRIPT ECHO
Example
py_echo(0)# disables echo
py_echo(1) # enables echo
9 Marc Python Reference
py_get_data Returns a floating point value from the database from the current data class
Synopsis
Float py_get_data(String name)
Arguments
name A string representing the database value to be returned.
Description
This routine parses the string specified in name and returns a floating point result. It has the form:
Dataclass:param_name
where Dataclass is one of:
adapg, adaptg, apply, contact_body, contact_table, geometry, icond, job,
loadcase, material
The Dataclass used is the currently selected item. The naming convention for param_name is consistent with that used
in the menu files for displaying floating point values.
Examples
a = py_get_data(‘material:isotropic:young_modulue’)
b = py_get_data(‘job:singularity_thresh’)
c = py_get_data(‘geometry:cont_radius’)
d = py_get_data(‘icond:base_vec1_x’)
e = py_get_data(‘apply:apply_dof_value_x’)
f = py_get_data(‘contact_body:friction’)
f = py_get_data(‘contact_table:ctable1:ctable2:friction’)
CHAPTER 1 10
PyMentat References
Synopsis
Float py_get_float(String name)
Arguments
name A string representing the expression to be evaluated.
Description
This routine evaluates the expression specified in name and returns a floating point result. Any Arithmetic or Database
function combination may be used in the expression.
Note: The variables created and used in the Python script are not stored by Mentat and are not available to be
used directly in the expression. Mentat parameters may be defined and used for this purpose.
Example
s = py_get_float(‘point_u1(npoints())’)
str = ‘curve_length(0)/curve_ndiv(0)’
d = py_get_float(str)
f = py_get_float(‘node_x(0)*d’) # is invalid
str = ‘node_x(0)*%g’ % d
f = py_get_float(str) # is correct
11 Marc Python Reference
Synopsis
Integer py_get_int(String name)
Arguments
name A string representing the expression to be evaluated.
Description
This routine evaluates the expression specified in name and returns an integer result. Only Database functions may be
used in the expression since the Arithmetic functions are floating point routines.
Note: The variables created and used in the Python script are not stored by Mentat and are not available to be
used directly in the expression. Mentat parameters may be defined and used for this purpose.
Example
str = ‘npoints()’
i = py_get_int(‘npoints()’)
j = py_get_int(‘node_id(i)’) # is invalid
str = ‘node_id(%d)’” % i
j = py_get_int(str) # is correct
CHAPTER 1 12
PyMentat References
Synopsis
String py_get_string(String name)
Arguments
name A string representing the function or parameter to be returned.
Description
This routine evaluates the function or parameter specified in name and returns a string result. Any database function
that returns a string may be used in the expression, such as set_name() or job_title(). If name is a string that
begins with ‘$’, then it is interpreted as being the name of a PARAMETER that is currently defined and its expression
is returned.
Note: The variables created and used in the Python script are not stored by Mentat and are not available to be
used directly in the name argument. Mentat PARAMETERS may be defined and used for this purpose.
Example
id = py_get_int(‘set_id(1)‘)
nam = py_get_string(‘set_name(%d)’ % id)
typ = py_get_string(‘set_type(%d)’ % id)
print ‘Set ‘,nam, ‘ is type ‘,typ
py_send(‘*define filename myfile.mfd’)
s = py_get_string(‘$filename’)
print ‘Filename: ‘,s
13 Marc Python Reference
Synopsis
py_prompt(String name)
Arguments
name The string to print in the dialogue area.
Description
This routine prints the string name in the Mentat dialogue area.
Example
py_prompt(”Evaluating Mesh”)
CHAPTER 1 14
PyMentat References
Synopsis
py_send(String command)
Arguments
command A string that contains the Mentat command(s) to be executed.
Description
This routine sends the string command to Mentat for execution. The string may contain multiple Mentat commands
(which must be separated by blanks) and can be constructed using standard Python string operations. The command(s)
will be executed just as if they were typed in the Mentat dialog area.
Graphics windows will not be updated automatically after the string has been executed. They will be updated only after
the Python script has finished executing. The special command *py_update can be sent to Mentat to force a refresh
of the graphics windows during execution of the Python script. This command must be used if one wants to create a
snapshot of the graphics window from the Python script. For example, the following two Python commands save a
snapshot of the current graphics window into the file image.png:
py_send(“*py_update”)
py_send(“*image_save_current image.png yes”)
Example
py_send(“*add_nodes %f %f %f” % (x, y, z)) # creates a node at
# position (x,y,z)
Chapter 2: PyPost References
2 PyPost References
PyPost 21
close 25
cbody 26
cbody_angle 28
cbody_displacement 29
cbody_force 30
cbody_moment 31
cbody_name 32
cbody_rotation 33
cbody_transform 34
cbody_velocity 35
cbody_volume 36
cbodies 37
domain 38
element 39
elements 40
element_id 41
element_scalar 42
element_scalars 43
element_scalar_label 44
element_sequence 45
CHAPTER 2 20
PyPost References
element_tensor 46
element_tensors 47
element_tensor_label 48
element_vector 49
element_vectors 50
element_vector_label 51
extrapolation 52
global_value 53
global_values 54
global_value_label 55
increments 56
moveto 57
node 58
nodes 59
node_displacement 60
node_displacements 61
node_id 62
node_scalar 63
node_scalars 64
node_scalar_label 65
node_sequence 66
node_vector 67
node_vectors 68
node_vector_label 69
post_open 70
set 71
sets 72
title 73
version 74
21 Marc Python Reference
PyPost
This chapter describes the PyPost routines and methods.
The PyPost module is used by a Python script to read data from a Marc post file.
All Python scripts that need access to the PyPost module must import the module as:
from py_post import *
The PyPost object contains attributes that are accessible after opening a post file. For example:
from py_post import *
p = post_open(‘chap19.t16’)
p.moveto(11)
print ‘increment number ‘,p.increment
The PyPost object contains the following attributes:
General Description
cutback The total number of cutbacks
cycles The number of recycles for this increment
extrapolate The current extrapolation method
filename The postfile name associated with this object
increment The current increment
position The current position (as supplied to moveto())
revision The post file revision
separation The total number of separation recycles
split The total number of increment splittings
soltype The dynamic response flag: 0=Normal, 1=Modal, 2=Buckle, 3=Harmonic, 4=Complex.
subinc The current sub-increment. Non-zero for dynamic analysis.
Energy Description (from block 5180n)
creepenergy The total creep strain energy
dampenergy The total damping energy
elasticenergy The total elastic strain energy
energy The total energy
kineticenergy The total kinetic energy
plasticenergy The total plastic strain energy
thermalenergy The total thermal energy
strainenergy The total strain energy
CHAPTER 2 22
PyPost References
Variables
buckle The buckling factor (for a buckling analysis)
frequency The frequency (for a modal or harmonic analysis). This value is zero for the static increments of the
analysis and non-zero for the dynamic increments. The following code segment will search all
increments to find the first dynamic increment.
firstdyn = 0
for i in range(1,ninc):
p.moveto(i)
if p.frequency != 0:
firstdyn = i
Note that soltype can also be check for being non-zero.
machangle The machine angle (SuperForm only)
pressure The process pressure
time The transient time
mass The total mass
volume The total volume
Work Description (from block 5180n)
appliedwork The total work done by applied force or displacement
contactwork The total work done by contact or external forces
foundwork The total work done by foundations
frictionwork The total work due to friction
springwork The total work done by springs
work The total work
close Closes a currently open post file and frees any allocated memory
Synopsis
close( )
Arguments
None
Description
This method closes the post file associated with the PyPost object.
Example
p = post_open(‘c08_job1.t19’)
p.close( )
CHAPTER 2 26
PyPost References
Synopsis
PyContactBody cbody(Integer index)
Arguments
index Contact body index number
Description
Return a PyContactBody object for contact body index. The cbodies method should be called prior to calling the
cbody method to obtain the total number of contact bodies that are available. The PyContactBody object contains the
geometry for the contact body if the revision of the post file is 8 or higher (member revision of the PyPost object).
This method returns a PyContactBody object.
• PyContactBody Members
id - contact body ID
name - name of the contact body (string)
type - contact body type
0 - deformable
1 - 2-D line elements (line type 9)
2 - 3-D patch elements (elem type 18)
3 - 2-D curves
4 - 3-D surfaces
bodytype - physical type of contact body
1 - rigid
2 - deformable structure
3 - symmetry
4 - deformable heat-rigid
5 - workpiece (SuperForm only)
6 - deformable acoustic
Prior to post revision 8, only rigid contact bodies have the following set:
Also See
cbodies, cbody_name
Example
p = post_open(‘ch03_job1.t16’)
p.moveto(0)
n = p.cbodies()
for i in range(0,n):
d = p.cbody(i)
print ‘contact body id ‘,d.id,’ name ‘,d.name,’
Type ‘,d.type
print ‘Physical type ‘,d.bodytype
CHAPTER 2 28
PyPost References
Synopsis
Float cbody_angle(Integer index)
Arguments
index cbody index number
Description
Return the value of the contact body angle at contact body index if available. The cbodies method should be called
prior to calling the cbody_angle method to obtain the total number of cbodies that are available.
This method returns a float.
Also See
cbodies, cbody_name
Example
p = post_open(‘ch03_job1.t16’)
p.moveto(0)
n = p.cbodies()
for i in range(0,p.increments())
p.moveto(i)
for j in range(0,n):
a = p.cbody_angle(i)
29 Marc Python Reference
Synopsis
Float, Float, Float cbody_displacement(Integer index)
Arguments
index Contact body index number
Description
Return the values of the contact body displacement at contact body index. The cbodies method should be called prior
to calling the cbody_displacement method to obtain the total number of contact bodies that are available.
This method returns three floats.
Also See
cbodies, cbody_name
Example
p = post_open(‘ch03_job1.t16’)
p.moveto(0)
n = p.cbodies()
for i in range(0,p.increments())
p.moveto(i)
for j in range(0,n):
x,y,z = p.cbody_displacement(i)
CHAPTER 2 30
PyPost References
Synopsis
Float, Float, Float cbody_force(Integer index)
Arguments
index Contact body index number
Description
Return the values of the contact body force at contact body index. The cbodies method should be called prior to
calling the cbody_force method to obtain the total number of contact bodies that are available.
This method returns three floats.
Also See
cbodies, cbody_name
Example
p = post_open(‘ch03_job1.t16’)
p.moveto(0)
n=p.cbodies()
n = p.cbodies()
for i in range(0,p.increments())
p.moveto(i)
for j in range(0,n):
x,y,z = p.cbody_force(i)
31 Marc Python Reference
Synopsis
Float, Float, Float cbody_moment(Integer index)
Arguments
index Contact body index number
Description
Return the values of the moment for contact body index. The cbodies method should be called prior to calling the
cbody_moment method to obtain the total number of contact bodies that are available.
This method returns three floats.
Also See
cbodies, cbody_name
Example
p = post_open(‘ch03_job1.t16’)
p.moveto(0)
n = p.cbodies()
for i in range(0,p.increments())
p.moveto(i)
for j in range(0,n):
x,y,z = p.cbody_moment(i)
CHAPTER 2 32
PyPost References
Synopsis
String cbody_name(Integer index)
Arguments
index Contact body index number
Description
Return the name contact body index. The cbodies method should be called prior to calling the cbody_name
method to obtain the total number of contact bodies that are available.
This method returns a string.
Also See
cbodies
Example
p = post_open(‘ch03_job1.t16’)
p.moveto(0)
n = p.cbodies()
for i in range(0,n):
print ‘ contact body ‘,p.cbody_id(), ‘ is named ‘,
p.cbody_name(i)
33 Marc Python Reference
Synopsis
Float cbody_rotation(Integer index)
Arguments
index Contact body index number
Description
Return the value of the contact body rotation for contact body index. The cbodies method should be called prior to
calling the cbody_rotation method to obtain the total number of contact bodies that are available.
This method returns a float.
Also See
cbodies, cbody_name
Example
p = post_open(‘ch03_job1.t16’)
p.moveto(1)
n = p.cbodies()
for i in range(0,p.increments())
p.moveto(i)
for j in range(0,n):
r = p.cbody_rotation(i)
CHAPTER 2 34
PyPost References
Synopsis
List Float cbody_transform(Integer index)
Arguments
index Contact body index number
Description
Return the values of the transform for contact body index. The cbodies method should be called prior to calling the
cbody_transform method to obtain the total number of contact bodies that are available.
A transform is actually a 4x4 array of floats, however this method returns an array of 16 floats. They are arranged as
follows:
Also See
cbodies, cbody_name
Example
p = post_open(‘ch03_job1.t16’)
p.moveto(1)
print cbody_transform(p.cbodies()-1)
35 Marc Python Reference
Synopsis
Float cbody_velocity(Integer index)
Arguments
index Contact body index number
Description
Return the value for the velocity of the contact body index. The cbodies method should be called prior to calling the
cbody_velocity method to obtain the total number of contact bodies that are available.
This method returns a float.
Also See
cbodies, cbody_name
Example
p = post_open(‘ch03_job1.t16’)
p.moveto(0)
n = p.cbodies()
for i in range(0,p.increments())
p.moveto(i)
for j in range(0,n):
v = p.cbody_velocity(i)
CHAPTER 2 36
PyPost References
Synopsis
Float cbody_volume(Integer index)
Arguments
index Contact body index number
Description
Return the value for the volume of the contact body index. The cbodies method should be called prior to calling the
cbody_displacement method to obtain the total number of cbodies that are available.
This method returns a float.
Also See
cbodies, cbody_name
Example
p = post_open(‘ch03_job1.t16’)
p.moveto(0)
n = p.cbodies()
for i in range(0,p.increments())
p.moveto(i)
for j in range(0,n):
v = p.cbody_volume(i)
37 Marc Python Reference
Synopsis
Integer cbodies()
Arguments
None
Description
Returns the number of contact bodies.
Example
p = post_open(‘c07_job1.t19’)
p.moveto(0)
n = p.cbodies()
CHAPTER 2 38
PyPost References
Synopsis
Integer domains()
Arguments
None
Description
Returns the number of domains in the post file.
Example
p = post_open(‘c07_job1.t19’)
n = p.domains()
39 Marc Python Reference
Synopsis
PyElement element(int nelem)
Arguments
nelem The element index number
Description
Returns a PyElement object containing the element data for element nelem in the current increment. This data may
change for each increment due to rezoning.
PyElement Members
type - element type
len - number of nodes in the element
items - list of node IDs that comprise the element
Example
p = post_open(‘c08_job1.t19’)
p.moveto(0)
n = p.elements()
for i in range(0,n):
el = p.element(i)
print el
CHAPTER 2 40
PyPost References
Synopsis
Integer elements()
Arguments
None
Description
Returns the number of elements in the current increment. This may change for each increment due to rezoning.
Example
p = post_open(‘c08_job1.t19’)
p.moveto(0)
n = p.elements()
41 Marc Python Reference
Synopsis
Integer element_id(Integer nelem)
Arguments
nelem The element index number
Description
Returns ID of element at index number nelem.
Example
p = post_open(‘c08_job1.t19’)
# print the id’s of each element
p.moveto(0)
n = p.elements()
for i in range(0,n):
print ‘Element ‘,i,’ has id ‘, p.element_id(i)
CHAPTER 2 42
PyPost References
Synopsis
List PyScalar element_scalar(Integer nelem, Integer ns)
Arguments
nelem Element index number
ns Scalar index number
Description
Returns a PyScalar list for element scalar nscalar for element at index nelem. A scala is returned for each node in the
element.
This PyScalar list contains the node id and the scalar value. The list returned is read-only, meaning that the values in
the list cannot be changed.
Example
P = post_open(‘c08_job1.t19’)
p.moveto(1)
ne = p.element_scalars()
n = p.elements()
for i in range(0,ne):
for j in range(0,n):
slist = p.element_scalar(j,i)
print ‘Element ‘,j
for k in range(0,len(slist)):
print ‘ Node ‘,slist[k].id, ‘Scalar ‘,
,slist[k].value
slist[k].value = -slist[k].value # Causes Error
43 Marc Python Reference
Synopsis
Integer element_scalars()
Arguments
None
Description
Returns the number of element scalars available. This method returns an integer.
Example
P = post_open(‘c08_job1.t19’)
# print the element scalar labels
p.moveto(1)
n = p.element_scalars()
for i in range(0,n):
print p.element_scalar_label(i)
CHAPTER 2 44
PyPost References
Synopsis
String element_scalar_label(Integer nscalar)
Arguments
nscalar Scalar index number
Description
Return the name of element scalar nscalar.
This method returns a string.
Example
p = post_open(‘c08_job1.t19’)
# print the element scalar labels
p.moveto(1)
n = p.element_scalars()
for i in range(0,n):
print p.element_scalar_label(i)
45 Marc Python Reference
Synopsis
Integer element_sequence(Integer nelem)
Arguments
nelem The element ID
Description
Returns the index number of element with ID nelem. This is the inverse of the element_id method.
Example
p = post_open(‘c08_job1.t19’)
# print the id’s of each element
p.moveto(0)
n = p.elements()
for i in range(0,n):
print ‘Element Id ‘,i,’ index ‘,p.element_sequence(i)
CHAPTER 2 46
PyPost References
Synopsis
List PyTensor element_tensor(Integer nelem, Integer ntens)
Arguments
nelem Element index number
ntens Tensor index number
Description
Returns a list of nodes and nodal tensor values for element tensor ntens for element an index nelem. A scalar is returned
for each node in the element.
This PyTensor list contains the node ID and the tensor values. The list returned is read-only, meaning that the values
in the list cannot be changed. This method returns a Python list of PyTensor values.
Example
P = post_open(‘c08_job1.t19’)
p.moveto(1)
ne = p.element_tensors()
n = p.elements()
for i in range(0,ne):
for j in range(0,n):
tlist = p.element_tensor(j,i)
print ‘Element ‘,j
for k in range(0,len(tlist)):
print ‘ Tensor ‘,tlist[k]
47 Marc Python Reference
Synopsis
Integer element_tensors()
Arguments
None
Description
Returns the number of element tensors available. This method returns an integer.
Example
P = post_open(‘c08_job1.t19’)
# print the element tensor labels
p.moveto(1)
n = p.element_tensors()
for i in range(0,n):
print p.element_tensor_label(i)
CHAPTER 2 48
PyPost References
Synopsis
String element_tensor_label(Integer ntens)
Arguments
ntens Tensor index number
Description
Return the name of element tensor ntens.
This method returns a string.
Example
p = post_open(‘c08_job1.t19’)
# print the element tensor labels
p.moveto(1)
n = p.element_tensors()
for i in range(0,n):
print p.element_tensor_label(i)
49 Marc Python Reference
Synopsis
List PyVector element_vector(Integer nelem, Integer nv)
Arguments
nelem Element index number
nv Vector index number
Description
Returns a list of nodes and values for element vector nv for element at index nelem. A scalar is returned for each node
in the element.
This PyVector list contains the node id and the vector values. The list returned is read-only, meaning that the values in
the list cannot be changed.
This method returns a Python list of PyVector values.
Example
P = post_open(‘c08_job1.t19’)
p.moveto(1)
ne = p.element_vectors()
n = p.elements()
for i in range(0,ne):
for j in range(0,n):
vlist = p.element_vector(j,i)
print ‘Element ‘,j
for k in range(0,len(vlist)):
print ‘ Vector ‘,vlist[k]
CHAPTER 2 50
PyPost References
Synopsis
Integer element_vectors()
Arguments
None
Description
Returns the number of element vectors available. This method returns an integer.
Example
P = post_open(‘c08_job1.t19’)
# print the element vector labels
p.moveto(1)
n = p.element_vectors()
for i in range(0,n):
print p.element_vector_label(i)
51 Marc Python Reference
Synopsis
String element_vector_label(Integer nscalar)
Arguments
nvec Vector index number
Description
Return the name of element vector nvec. This method returns a string.
Example
p = post_open(‘c08_job1.t19’)
# print the element vector labels
p.moveto(1)
n = p.element_vectors()
for i in range(0,n):
print p.element_vector_label(i)
CHAPTER 2 52
PyPost References
Synopsis
extrapolation(String type)
Arguments
type A string representing the integration method to use
Description
This method controls the manner in which element integration point data is extrapolated to the nodes of an element. In
addition, they control the inter-element averaging of the nodal data after it has been extrapolated. The available
methods are:
linear Extrapolate by averaging the integration points to the centroid of the element and then doing a
linear extrapolation from the centroid through the integration point to the node.
translate Do not extrapolate, but rather copy the data at each integration point to its corresponding node. In
those cases where there are fewer integration points than nodes, some averaging of neighboring
integration points may be done.
average The average of all the integration points is computed and assigned to the nodes. Therefore, all
nodes have an equal value assigned to them.
Example
P = post_open(‘c08_job1.t19’)
p.extrapolation(‘linear’)
print ‘Extrapolation method is ‘, p.extrapolate
53 Marc Python Reference
Synopsis
Float global_value(Integer index)
Arguments
index Global value index number
Description
Return the value of a particular global value index.
This method returns a float.
Example
# Post file from Userguide Example 3.5
p = post_open(‘airspring_axito3d_wcav_job1.t16’)
ninc = p.increments()
p.moveto(ninc-1)
n = p.global_values()
for i in range(0,n):
print p.global_value_label(i), ‘: ‘, p.global_value(i)
Resulting Output:
Volume Cavity 1 : 0.00172809232026
Pressure Cavity 1 : 1904785.625
Mass Cavity 1 : 0.0363396443427
Temperature Cavity 1 : 300.0
Loadcase Percentage Completion : 0.0
CHAPTER 2 54
PyPost References
Synopsis
Integer global_values()
Arguments
None
Description
Returns the number of global values available. This method returns an integer.
Example
P = post_open(‘airspring_axito3d_wcav_job1.t16’)
# print the global value labels
n = p.global_values()
for i in range(0,n):
print p.global_value_label(i)
55 Marc Python Reference
Synopsis
String global_value_label(Integer index)
Arguments
index Global value index number
Description
Return the name of global value index.
This method returns a string.
Example
p = post_open(‘airspring_axito3d_wcav_job1.t16’)
# print the global value labels
n = p.global_values()
for i in range(0,n):
print p.global_value_label(i)
CHAPTER 2 56
PyPost References
Synopsis
Integer increments()
Arguments
None
Description
The number of increments on the post file plus one is returned. Note that a post file starts with a header, which contains
the model data, but no results. This header is included in the increments method. So if a post file only contains
increment 0, the increments method returns two. If a post file contains increment 0 and sub-increments 0:1 and 0:2,
then the increments method returns four. The increments method is often combined with the moveto method
(see moveto) to skip to a particular increment.
Example
p = post_open(‘c08_job1.t19’)
n = p.increments()
57 Marc Python Reference
Synopsis
moveto(Integer i)
Arguments
i increment number
Description
Moves to the specified increment in the post file. Increment number 0 only contains the model itself. There is no scalar
data for increment 0. The first increment with data is increment 1.
When the moveto method is called, the following members of the PyPost object are available:
Example
p = post_open(‘c07_job1.t19’)
p.moveto(4)
print ‘increment ‘,p.increment,’ Time ‘,p.time
print ‘Frequency ‘,p.frequency
CHAPTER 2 58
PyPost References
Synopsis
PyNode node(int nnode)
Arguments
nnode The node index number
Description
Returns a PyNode object containing the nodal data for node at index nnode in the current increment. This data may
change for each increment due to rezoning.
PyNode Members
id - node ID
x - x coordinate
y - y coordinate
z - z coordinate
Example
p = post_open(‘c08_job1.t19’)
p.moveto(0)
n = p.nodes()
for i in range(0,n):
nod = p.node(i)
print "Node index number ",i, " Id ",nod.id
print " x = ",nod.x, " y = ",nod.y," z = ",p.z
59 Marc Python Reference
Synopsis
Integer nodes()
Arguments
None
Description
Returns the number of nodes in the current increment. This may change for each increment due to rezoning.
Example
p = post_open(‘c07_job1.t19’)
p.moveto(0)
n = p.nodes()
CHAPTER 2 60
PyPost References
Synopsis
Float, Float, Float node_displacement(Integer index)
Arguments
index Node index number
Description
Return the values of the nodal displacement at node index if available. The node_displacements method should
be called prior to calling the node_displacement method to make sure that nodal displacements are available.
This method returns three floats.
Also See
node_displacements
Example
p = post_open(‘c07_job1.t19’)
p.moveto(1)
n = p.nodes()
have_disp = p.node_displacements()
if have_disp:
for i in range(0,n):
x,y,z = p.node_displacement(i)
61 Marc Python Reference
Synopsis
Integer node_displacements()
Arguments
None
Description
This method should be used prior to calling the node_displacement method to determine if nodal displacements
are available. Returns 1 if nodal displacements are available; 0 otherwise.
Example
# print the name of each scalar label
p = post_open(’c07_job1.t19’)
p.moveto(1)
if p.node_displacements() :
print "Nodal displacements available"
CHAPTER 2 62
PyPost References
Synopsis
Integer node_id(Integer node)
Arguments
node The node index number
Description
Returns ID of node at index node.
Example
p = post_open(‘c08_job1.t19’)
# print the id’s of each node
p.moveto(0)
n = p.nodes()
for i in range(0,n):
print ‘Node ‘,i,’ has id ‘, p.node_id(i)
63 Marc Python Reference
Synopsis
Float node_scalar(Integer index, Integer scalar)
Arguments
index Node index number
scalar Scalar index number
Description
Return the value of a particular node scalar scalar at a particular node index.
This method returns a float.
Example
# get each scalar for node at index 4
f = [ ]
p = post_open(‘c07_job1.t19’)
p.moveto(1)
n = p.node_scalars()
id = node_id(4)
print ‘node scalars for node id ‘,id
for i in range(0,n):
f.append(p.node_scalar(4, i))
print ‘scalar ‘,f[i]
CHAPTER 2 64
PyPost References
Synopsis
Integer node_scalars()
Arguments
None
Description
Returns the number of node scalars available.
Example
# print the name of each scalar label
p = post_open(‘c07_job1.t19’)
p.moveto(1)
n = p.node_scalars()
for i in range(0, n):
print p.node_scalar_label(i)
65 Marc Python Reference
Synopsis
String node_scalar_label(Integer index)
Arguments
index Scalar index number
Description
Return the name of node scalar index.
This method returns a string.
Example
# print the name of each scalar label
p = post_open(‘c07_job1.t19’)
p.moveto(1)
n = p.node_scalars()
for i in range(0, n):
print p.node_scalar_label(i)
CHAPTER 2 66
PyPost References
Synopsis
Integer node_sequence(Integer node)
Arguments
node The node ID
Description
Returns the index number of node with ID node. This is the inverse of the node_id method.
Example
p = post_open(‘c08_job1.t19’)
p.moveto(0)
# print the index of each node
n = p.nodes()
for i in range(0,n):
print ‘Node Id ‘,i,’ has index ‘, p.node_sequence(i)
67 Marc Python Reference
Synopsis
PyVector node_vector(Integer index, Integer nv)
Arguments
index Node index number
nv Vector index number
Description
Return the vector of a particular node vector nv at a particular node index.
This method returns a PyVector.
Example
# get each vector for node 4
p = post_open(‘c07_job1.t19’)
p.moveto(1)
n = p.node_vectors()
for i in range(0,n):
v = p.node_vector(4, i)
print ‘Vector ‘,i,’ is ‘, v.x, v.y, v.z
CHAPTER 2 68
PyPost References
Synopsis
Integer node_vectors()
Arguments
None
Description
Returns the number of node vectors available.
Example
# print the name of each vector label
p = post_open(‘c07_job1.t19’)
p.moveto(1)
n = p.node_vectors()
for i in range(0, n):
print p.node_vector_label(i)
69 Marc Python Reference
Synopsis
String node_vector_label(Integer index)
Arguments
index Vector index number
Description
Return the name of node vector index.
This method returns a string.
Example
# print the name of each vector label
p = post_open(‘c07_job1.t19’)
p.moveto(1)
n = p.node_vectors()
for i in range(0, n):
print p.node_vector_label(i)
CHAPTER 2 70
PyPost References
Synopsis
PyPost post_open(String filename)
Arguments
filename Post file name.
Description
This method opens the specified post file and returns a PyPost object. This is the first PyPost routine that a Python
script should call. A call to moveto( ) should follow to force a reading of the increment data at the first increment
on the post file.
Members
position - current increment position
filename - the post file name
revision - the revision of the post file
The following members are updated when the moveto method is called:
Example
p1 = post_open(‘e7x14_solver0.t19’)
p1.moveto(0)
p2 = post_open(‘e7x14_solver1.t19’)
p2.moveto(0)
print ‘Comparing ‘,p1.filename, ‘ to ‘,p2.filename
71 Marc Python Reference
Synopsis
PyPostSet set(int nset)
Arguments
nset The set index number
Description
Returns a PyPostSet object containing the set data for set nset in the models.
Members
name - set name
type - set type
len - number of items in the set
items - list of data that comprise the set
Example
p = post_open(‘c08_job1.t19’)
p.moveto(0)
n = p.sets()
for i in range(0,n):
s = p.set(i)
print ‘Name:’,s.name, ‘Type: ‘,s.type
for j in range(0,s.len):
print ‘Item:’,j, ‘Value: ‘,s.items[j]
CHAPTER 2 72
PyPost References
Synopsis
Integer sets()
Arguments
None
Description
Returns the number of sets in the post file.
Example
p = post_open(‘c07_job1.t19’)
p.moveto(0)
n = p.sets()
73 Marc Python Reference
Synopsis
String title( )
Arguments
None
Description
Returns the title of the model stored in the post file.
This method returns a string.
Example
# print the title
p = post_open(‘c08_job1.t19’)
print ‘Title: ‘,p.title()
CHAPTER 2 74
PyPost References
Synopsis
String version( )
Arguments
None
Description
Return the version string of the PyPost module.
This method returns a string.
Example
print ‘PyPost version is ‘,version()
p = post_open(‘c08_job1.t19’)
Appendix A
Introduction
This chapter describes the Arithmetic and Database function supported by Mentat. If the argument to any function is
shown in capital letters (such as ARGn), then the argument is an index and may be negative; in which case, the entities
are counted in reverse order (i.e., ARGn = -1 would refer to the last item). A good example of the usage of these
functions can be found in the Marc User’s Guide, Chapter 31 procedure file. If the argument to a database function is
in lower case (such as argn), then the value is an ID, such as a node ID or an element ID unless otherwise described.
Arithmetic Functions
The following are the Marc Mentat Arithmetic Functions which can be used in the py_get_float or py_get_int
functions or in a formula.
Database Functions
The following are the Mentat Database Functions which can be used in the py_get_float, py_get_int, or
py_get_string functions.
Note that the database functions may also be used as the argument to many commands. For example:
*remove_elements element_id(-1)
would remove the last element of the model. To use numeric values in a string based command (such as
*job_title), a PARAMETER needs to be created from the database function and then used in the string command.
For example:
*eval_define num nnodes()
*job_title Model with $num nodes
will create an evaluated parameter named num using the nnodes( ) database function, and then use that in the
*job_title command (note the use of the $ to signify it is the name of a parameter). The job title for the CONTACT
demo would appear as:
Model with 72 nodes
mater_type(arg1) Material type for material named arg1. If arg1 is empty, then it uses the
current material.
mater_nsubmats(arg1) Number of submaterials of material named arg1, or of the current
material is arg1 is empty. The material must be a composite, mixture or
rebar material.
mater_vsubmat_name(arg1,arg2) Name of submaterial number arg2 of materal named arg1, or of the
current material if arg1 is empty. Material arg1 (or the current material
if arg1 is empty) must be a composite, mixture or rebar material.
mater_vsubmat_opt(arg1,arg2,arg3) Option string for the option named arg3 for submaterial number arg2 of
material named arg1, or of the current material if arg1 is empty. Material
arg1 (or the current material if arg1 is empty) must be a composite,
mixture or rebar material. Option argument uses same syntax as in the
*mater_submat_option command.
Example:
mater_vsubmat_opt(material3,5,general:thickdir)
CHAPTER A 98
Arithmetic and Database Functions
mater_vsubmat_par_table(arg1,arg2,arg3) Returns the parameter table name for the parameter named arg3 for
submaterial number arg2 or the material named arg1, or of the current
marterial if arg1 is empty. Material arg1 (or the current material if arg1
is empty) must be a composite, mixture or rebar material. Parameter
argument uses same syntax as in the
*mater_submat_param_table command.
mater_fsubmat_name(arg1,arg2) Name of submaterial arg2 of material named arg1, or of the current
marterial if arg1 is empty. Material arg1 (or the current material if arg1
is empty) must be an interface, gasket, pshell or pyrolysis material. The
submaterial argument arg2 takes the same values as the first argument
to the *mater_submat_set_mater command.
Example:
mater_fsubmat_name(material3,bend)
mesh_par(arg1) Meshing parameter value named arg1.
Example:
mesh_par(qt_max_elements)
Valid parameters:
angle_cylindrical_part, attempts, axis_orientation,
base_element_size_<x|y|z>, boundary_refine_level,
boundary_refine_tolerance, box_<1...10>_max_<x|y|z>,
box_<1...10>_min_<x|y|z>, box_<1...10>_active,
box_<1...10>_type, box_<1...10>_level, critical_ring_angle,
coarsening_level, coon_representation, curvature_tolerance,
edge_detection, edge_angle, edge_length, el_gap, edge_tolerance,
enhance_mode, hex_elements, gap, grid_type, in_rat, mesher_type,
self_contact, shrink_factor, ties, write_extended
99 Marc Python Reference
Utility Functions
The following are the Mentat Utility Functions which can be used in the py_get_float, py_get_int, or
py_get_string functions.
Set Functions
The following are the Mentat Set functions which can be used in a call to the py_get_float or py_get_int
functions. The set_name and set_type functions return a string and must be used in a call to the
py_get_string function.