Python Manual Pages 2
Python Manual Pages 2
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.