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

Python Manual Pages 2

The document provides a tutorial on using Python with the Marc software for post-processing data, detailing how to extract scalar values and node information from a post file. It explains the use of various Python functions to interact with the Mentat database, including obtaining maximum and minimum scalar values and their corresponding nodes. Additionally, it introduces the concept of sets in Mentat, outlining how to query set information and extract database properties through a sample script.

Uploaded by

qq2109235237
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Python Manual Pages 2

The document provides a tutorial on using Python with the Marc software for post-processing data, detailing how to extract scalar values and node information from a post file. It explains the use of various Python functions to interact with the Mentat database, including obtaining maximum and minimum scalar values and their corresponding nodes. Additionally, it introduces the concept of sets in Mentat, outlining how to query set information and extract database properties through a sample script.

Uploaded by

qq2109235237
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

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

53. py_send( max_nodes[i] )


54. py_send(" #")
55. py_send("*post_numerics")
56.
57. # Use database functions to find max/min
58. print " "
59. print " Label node scalar"
60. print " ------------------------------------------"
61. for i in range(0,len(label)):
62. str = "*post_value " + label[i]
63. py_send(str)
64. str = "node_id(%d)" % j
65. n_id = py_get_int("scalar_max_node()")
66. str = "scalar_1(%d)" % n_id
67. d = py_get_float(str)
68. n_id2 = py_get_int("scalar_min_node()")
69. str = "scalar_1(%d)" % n_id
70. f = py_get_float(str)
71. if d < -f:
72. d = -f
73. n_id = n_id2
74. str = " %18s %10i %g" % (label[i],n_id, d)
75. print str
76. return
77.
78. if __name__ == '__main__':
79. py_connect('',40007)
80. main()
81. py_disconnect()

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.

Running the Script


This script runs the same way as in the previous examples. Bring up the Python browser and browse to the Mentat
directory examples/python/tutorial/c06 and run the Python script chap6.py. The output appears as shown in Figure 5-1
for both runs where it searches the node list and using the Database functions.

Label node scalar


-------------------------------------------
Displacement x 53 0.00128282
Displacement y 49 0.00565143
External Force x 0 0
External Force y 50 187.5
Reaction Force x 82 2866.6
Reaction Force y 81 921.814

Figure 5-1 Resulting Output from chap6.py

Figure 5-2 Resulting Post Plot from chap6.py

In the next chapter, we will examine the post file using the Python module PyPost.
Chapter 7: PyMentat: Sets

7 PyMentat: Obtaining Model Data



Chapter Overview 51

Database Properties Basics 51
 Set Basics 52

A Sample Script to Extract Data 52

Running the Script 57
 Set ID’s and Set Names 61
CHAPTER 7 51
PyMentat: Obtaining Model Data

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

Database Properties Basics


Database properties can be obtained using a number of methods that return the data stored in Mentat’s database. Mentat
has functions that supports the following items:

• adapg Global adaptive remeshing criteria.


• apply Boundary condition properties.
• cbody Contact body data.
• ctable Contact table data
• geom Geometric properties.
• icond Initial condition properties.
• material Material properties.
• lcases Loadcase data.
• jobs Job 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:

• element_cbody Name of contact body that the element belongs.


• element_geom Name of the geometric property that the element belongs.
• element_material Name of the material property that the element belongs.
• element_orient Name of the orientation property that the element belongs.
52 Marc Python Tutorial

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:

• node The set contains the node IDs of its entries.


• element The set contains the element IDs of its entries.
• point The set contains the point IDs of its entries.
• curve The set contains the curve IDs of its entries.
• surface The set contains the surface IDs of its entries.
• edge The set contains the element IDs and the edge number of its entries.
• face The set contains the element IDs and the face number of its entries.

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.

A Sample Script to Extract Data


In this example, we will obtain some database and set information in a simple Mentat model.
This example is named chap7.py and can be found in the Mentat directory examples/python/tutorial/c07. The
following is the Python code:
1. from py_mentat import *
2. def main():
3. py_send("*new_model yes *open_model sets.mfd")
4.
5. m = py_get_int("nsets()")
6. print "Found ",m," sets"
7.
CHAPTER 7 53
PyMentat: Obtaining Model Data

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

74. print str


75.
76. print ""
77. sn = py_get_string("material_name()")
78. print " Current material data: ", sn
79. st = py_get_string("material_type(%s)" % sn)
80. print " Type : ", st
81. e = py_get_data( "material:isotropic:youngs_modulus")
82. print " Youngs Modulus : ", e
83. p = py_get_data("material:isotropic:poissons_ratio")
84. print " Poissons Ratio : ", p
85. ys = py_get_data("material:plasticity:yield_stress")
86. print " Yield Stress : ", ys
87.
88. print ""
89. sn = py_get_string("ctable_name()")
90. print " Contact Table ", sn
91. sn = "contact_table:the_mesh:refined_mesh:dist_tol"
92. dt = py_get_data(sn)
93. print " Contact Dist Tol : ", dt
94.
95. print ""
96. sn = py_get_string("geom_name()")
97. print " Current geometry data: ", sn
98. thick = py_get_data("geometry:thick")
99. print " Thickness : ", thick
100.
101. print ""
102. m = py_get_int("nelements()")
103. max_eid = py_get_int("max_element_id( )")
104. print " Elements ", m, " Maximum id ", max_eid
105. for i in range(1,m+1):
106. id = py_get_int("element_id(%d)" % i)
107. print ""
56 Marc Python Tutorial

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

Lines 3 Open the model to examine the set information.


Lines 5-6 Obtain and print the number of sets found. This uses the nsets Database function.
Line 8 Loop through all the sets in the model. The sets begin at 1.
Line 9 Obtain the set ID. All of the set database functions will use the Set Id to locate the set information.
Line 10 Obtain the set name using the set_name database function.
Line 11 Obtain the set type using the set_type database function.
Line 12 Obtain the number of entries in this set.
Line 14 Ignore the loadcase, boundary condition (apply) and initial condition (icond) set types. These are
associated with the loadcase data.
Line 15 Print the set header information.
Line 16 Loop through all the entries in this set.
Line 17 Using the set_entry database function, obtain each item, and print out the results.
CHAPTER 7 57
PyMentat: Obtaining Model Data

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.

Running the Script


To run this script, bring up the Python browser and browse to the Mentat directory examples/python/tutorial/c07 and
run the Python script chap7.py. However, do not select the RUN AS SEPARATE PROCESS button since the Python
console/terminal window will exit when it is finished, and the resulting print statements will not be seen.
When the script completes, the output appears as shown in Figures 7-1 and 7-2.
58 Marc Python Tutorial

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

Set FACES is a face set with 2 entries


entry 1 is 4 face number 0
entry 2 is 2 face number 0
Set icond_velo_nodes is a node set with 1 entries
entry 1 is 5
Set icond_mass_nodes is a node set with 4 entries
entry 1 is 17
entry 2 is 18
entry 3 is 19
entry 4 is 20
Set icond_usersub_nodes is a node set with 1 entries
entry 1 is 15
Set apply_usersub_nodes is a node set with 1 entries
entry 1 is 16

Figure 7-1 Set output from chap7.py

The database output is shown in Figure 7-2.


CHAPTER 7 59
PyMentat: Obtaining Model Data

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

Current material : steel


Type : mechanical/isotropic
Youngs Modulus : 30000000.0
Poissons Ratio : 0.3
Yield Stress : 32000000.0

Contact Table : ctable1


Contact Dist Tol : 0.01
60 Marc Python Tutorial

Current geometry : th_shell


Thickness : 0.7

Contact Table
Contact Dist Tol : 0.01

Elements 4 Maximum id 4

Element 1 Class 4 Family 3 , Type 18

Contact Body : the_mesh


Geometry Property : th_shell
Orientation :
Material Property : steel

Element 2 Class 4 Family 3 , Type 18


Contact Body : refined_mesh
Geometry Property : th_shell
Orientation :
Material Property : steel

Element 3 Class 4 Family 3 , Type 3


Contact Body : the_mesh
Geometry Property : membrane
Orientation :
Material Property : stainless

Element 4 Class 4 Family 3 , Type 3


Contact Body : refined_mesh
Geometry Property : membrane
Orientation :
Material Property : stainless

Loadcase : forge_align , Type static


ArcLength Method : advanced_crisf

Job : forging_analysis , Type mechanical


Follower Force : begin_inc

Figure 7-2 Database output from chap7.py


CHAPTER 7 61
PyMentat: Obtaining Model Data

Set ID’s and Set Names


In most cases, it is desirable to reference sets using their names. However, all of the database functions for sets use the
set id. The following piece of Python code will take a set name and search for the set ID.

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

8 PyPost: Reading a Post File



Chapter Overview 63

PyPost Basics 63
 Running the Script 65
CHAPTER 8 63
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.

Running the Script


This script is intended to be run outside of Mentat. In an X-terminal window or a Microsoft Windows command prompt
window, change your directory to the Mentat directory examples/python/tutorial/c08. Run the Python script chap8.py
as:
python chap8.py
When the script completes, the output is printed as shown in Figure 8-1.
66 Marc Python Tutorial

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

Figure 8-1 Resulting Output from chap8.py

In the next chapter, we will begin working with element data.


Chapter 9: PyPost: Obtaining Element Data

9 PyPost: Obtaining Element Data



Chapter Overview 68

Processing Element Data 68
 Running the Script 72
68 Marc Python Tutorial

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

Processing Element Data


In the previous chapter, you saw how to use the Pypost module to process nodal data. In this chapter, we will process
element data.
Processing the element data is more complex since elements contain multiple nodes and integration points. The values
obtained at the nodes are obtained by extrapolating the values at the integration points. There are three extrapolation
methods available through the extrapolation method:

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.

Consider the quadrilateral element shown Figure 9-1.


CHAPTER 9 69
PyPost: Obtaining Element Data

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

14. nes = p.element_scalars()


15.
16. ninc = p.increments()
17. print " Increments = ",ninc,", Nodal scalars = ",nns, ",
Element scalars ",nes
18.
19. for i in range(0,nns+nes):
20. max_scalars.append(-1.0)
21. max_nodes.append(0)
22. max_incs.append(0)
23.
24. for i in range(1, ninc):
25. p.moveto(i)
26. print "scanning increment ",i," post file number ",p.increment
27.
28. # find maximum nodal scalars
29. j = 0
30. while j < nns:
31. k = 0
32. numnodes = p.nodes()
33. while k < numnodes:
34. d = p.node_scalar(k,j)
35. if d < 0.0:
36. d = -d
37. if d > max_scalars[j] :
38. max_scalars[j] = d
39. max_nodes[j] = p.node_id(k)
40. max_incs[j] = p.increment
41. k = k + 1
42. j = j + 1
43.
44. # find maximum element scalars
45. j = 0
46. while j < nes:
CHAPTER 9 71
PyPost: Obtaining Element Data

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.

Running the Script


This script is run similar to that of the previous chapter. In an X-terminal window or Microsoft Windows command
prompt window, change your directory to the Mentat directory examples/python/tutorial/c09. Run the Python script
chap9.py as:
python chap9.py
CHAPTER 9 73
PyPost: Obtaining Element Data

When the script completes, the output will be appear as shown in Figure 9-2.

Increments = 26 , Nodal scalars = 9 , Element scalars 6

Item Label increment node scalar


---------------------------------------------------------------------------
1 Displacement x 240 1 0.829858
2 Displacement y 190 23 0.0844004
3 Displacement z 240 75 1.83052
4 External Force x 240 60 216.668
5 External Force y 240 66 357.812
6 External Force z 0 1 0
7 Reaction Force x 240 18 4017.09
8 Reaction Force y 220 98 111.656
9 Reaction Force z 240 18 1.24391
10 Equivalent Von Mises Stress Layer 1 240 44 106931
11 Equivalent Von Mises Stress Layer 3 240 24 77594.8
12 Equivalent Von Mises Stress Layer 5 240 24 103107
13 Equivalent Plastic Strain Layer 1 240 45 0.181767
14 Equivalent Plastic Strain Layer 3 240 24 0.0871299
15 Equivalent Plastic Strain Layer 5 240 23 0.211298

Figure 9-2 Resulting Output from chap9.py

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

10 PyPost: Element Tensor Data



Chapter Overview 75

Processing Element Tensor Data 75
 Running the Script 78
CHAPTER 10 75
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

Processing Element Tensor Data


In the previous chapter, you saw how to use the PyPost module to process nodal and element scalar data. In this chapter,
we will process the element tensor data and use the PyTensor data type.
This example is named chap10.py and can be found in the Mentat directory examples/python/tutorial/c10. The Python
code is as follows:
1. from py_post import *
2. import sys
3. class TensorData:
4. def __init__(self, v, n, i):
5. self.Value = v
6. self.Node = n
7. self.Inc = i
8.
9. def set_data(self, v,n,i):
10. self.Value = v
11. self.Node = n
12. self.Inc = i
13.
14. def increment(self):
15. return self.Inc
16.
17. def value(self):
18. return self.Value
19.
20. def node(self):
21. return self.Node
76 Marc Python Tutorial

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.

Running the Script


This script is run similar to that of the previous chapter. In an X-terminal window or Microsoft Windows command
prompt window, change your directory to the Mentat directory examples/python/tutorial/c10. Run the Python script
chap10.py as:
python chap10.py chap10.t16
When the script completes, the output appears as shown in Figure 10-1.

Found 2 element tensors


12 increments
Scanning increment 1
Scanning increment 2
Scanning increment 3
Scanning increment 4
Scanning increment 5
Scanning increment 6
Scanning increment 7
Scanning increment 8
Scanning increment 9
Scanning increment 10
Scanning increment 11
Item Label increment node tensor
----------------------------------------------------------
1 Stress 4 15 58564.1
2 Plastic Strain 6 9 0.103661
Figure 10-1 Resulting Output from chap10.py
Chapter 11: PyMentat: Using the py_connect Method

PyMentat: Using the py_connect


11 Method

Chapter Overview 80
 Creating a Simple Python Script for Marc Mentat 80

The py_connect Method 80

Handling Socket Errors 81
 Running the Script 82
80 Marc Python Tutorial

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

Creating a Simple Python Script for Marc Mentat


We will use the Python script shown in Chapter 3: PyMentat: Obtaining Data from Mentat which will create a simple
element grid and use Mentat Parameters to control the size of the grid. This example is named chap3.py and can be
found in the Mentat directory examples/python/tutorial/c03. The code is shown completely in Chapter 3: PyMentat:
Obtaining Data from Mentat; however, what we are interested in now is at lines 41-44 as follows:

12. if __name__ == ’__main__’:


13. py_connect("",40007)
14. main()
15. py_disconnect()
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 first argument to py_connect is the hostname, and if it is NULL, it will use the
local host. The second argument is the port number.

The py_connect Method


The py_connect method provides a method in which a Python script performs a BSD socket connection to Mentat
to send commands and obtain parameters. It allows Mentat to be fully interactive while the Python script is executing.
When the Run command in the Python menu is selected, it will bring up the Python browser window. An option in the
Python browser window is Run As Separate Process. If this is enabled, then Mentat will initiate a socket connection
using the command for the Initiate Connection menu item, and then the Python script is run using the python interpreter
(python.exe on Microsoft Windows) program located in Mentat’s bin directory. The Python script will need to complete
the connection using a call to the PyMentat method py_connect, specifying the hostname and the port number to
be used. The port number used in the Python script must be the same as specified in Marc Mentat, and may be changed
by selecting the Port button. The hostname may be blank (an empty string), in which case the connection will be
attempted on the local host.
All output from the Python script will appear in Mentat’s XTerm window on Unix or the Command Prompt window
on Microsoft Windows. When Python scripts ends it should call the py_disconnect method to complete the
termination of the socket connection.
CHAPTER 11 81
PyMentat: Using the py_connect Method

Handling Socket Errors


Sometimes a socket may become unusable and Mentat cannot make a connection to a certain port. A port number may
be described as "in use", even though it appears that no Python script is running. You should check that no "zombie"
Python process is running in the background (using the ’ps’ command on Unix or the Task Manager on Microsoft
Windows). If a Python process is running and it has a connection to the port, it must terminate before another process
can make a connection to that port.
The error "Specified address in use" may occur in the following scenario on a Unix system:
1. Mentat is started and the Initiate Connection button is selected.
2. In a separate window, a Python script makes a successful socket connection to Mentat.
3. Mentat exits before the Python script completes or calls the py_disconnect method.
4. Mentat is started again, and the Initiate Connection button is selected. The error "Specified address in use" may
occur. To resolve the problem, use a different port number or wait for the socket timeout to occur (about 4-5
minutes).
If all else fails, try using a different port number. You may also want to specify the port number as an argument to the
Python script. You may do this as shown in the following code example:
1. import sys
2. if __name__ == ’__main__’:
3. port = 40007
4. if len(sys.argv) > 1:
5. port = sys.argv[1]
6. py_connect("",port)
7. main()
8. py_disconnect()
The sys module is used to obtain the "command line arguments", which contains the Python list attribute named argv.
The first item in the argv list in the name of the script being run, and is therefore sys.argv[0]. If the length of this list
is greater than 1, then extra arguments were passed to the Python script. In this example, you would run the script on
the command line as:
python chap3.py 40008
The script would use the port number of 40008 and attempt to make the socket connection with Mentat. The script
could also be run using the Python browser window, shown in Figure 11-1. In this case, the Run As Separate Process
button would be selected, and you would also specify the port number in the Call Arguments text box.
82 Marc Python Tutorial

Figure 11-1 Python Browser Window

Running the Script


First, start Mentat. Before running this example, some Parameters need to be defined. The values for these parameters
will be obtained by the Python script to control the size and the position of the grid.
Select the following menus:

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.

Charting Script for Mentat


In this first example, we will use a simple charting module that creates a JPEG file. We will use it here to create a plot
of the Y displacements for four nodes. Note that this module is somewhat limited since it does not support annotations
and has no support for legends. However, it can be useful for creating quick and simple plots. We will use a post file
which displays a simple contact example. This example is named chap12a.py and can be found in the Mentat directory
examples/python/tutorial/c12. The output from this example is a JPEG file name chap12a.jpg.
The following is the Python code to use the gdchart module to create a JPEG plot.
1. from py_post import *
2. import gdchart
3. opt = gdchart.option
4.
5. opt(set_color=(0xff8080, 0x8080ff, 0x80ff80))
6. opt(bg_color=0xaaaaaa, plot_color=0x0000cd, line_color=0x000000)
7. size = (450, 450)
8.
9. def do_plot(fname, t, Incs, dta):
10. opt(set_color=(0xff8080, 0x8080ff, 0x80ff80))
11. opt(bg_color=0xaaaaaa, plot_color=0x0000cd,
12. line_color=0x000000,format=gdchart.GDC_JPEG)
13. opt(title=t, xtitle='Increment', ytitle=' Y-Displ',grid=1)
14. f=open(fname,’wb’)
15. gdchart.chart(gdchart.GDC_LINE, size, f,
16. Incs, dta[0], dta[1], dta[2], dta[3])
17. f.close()
86 Marc Python Tutorial

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

Line 2 The chart module gdchart is imported.


Lines 9-17 The do_plot routine is a convenient wrapper function to the plotting routine chart in the gdchart
module. We pass in the filename for the plot, the title, and the X and Y values to plot.
Line 27 Create the list of nodes IDs to plot.
Lines 31-33 Create a two-dimensional array for the displacements. The list is the size [number of nodes to plot] x
[number of increments].
Line 35 Create a string array for the increments.
Line 38-41 Find the index to the displacements for the node scalars.
Line 43 Loop through all the increments.
Lines 49-51 Loop over the list of nodes to plot. Use the node_sequence routine to get the sequence number
for the IDs in the check_nodes list.
Lines 53-56 Create the title for the plot. It will contain the list of the nodes used in the plot.

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

Figure 12-1 The Resulting JPEG File from chap12a.py

The Gnuplot Module


The gnuplot module interfaces with the Gnuplot program to create PostScript plots. It does not create plots on its own.
Instead, it communicates with the Gnuplot program in much the same way as the PyMentat module communicates with
Mentat. The gnuplot module sends commands to the Gnuplot program, and plots appear in the Gnuplot window. This
module is more robust than the gdchart module because it supports annotations and provides much more control over
the plot.
1. from py_post import *
2. import os
3.
4. try:
5. # Check if the package has been installed correctly
6. import Gnuplot
CHAPTER 12 89
PyPost: Plotting

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.

You might also like