oomph-convert Namespace Reference

Classes

class  TecplotParsingError
 
class  TecplotNode
 
class  TecplotZone
 
class  VtkXml
 
class  InputPoints
 
class  VtpXml
 

Functions

def usage ()
 
def main (argv)
 
def ok_to_write_ofile (flag, in_file_name, out_file_name)
 
def addTrailingZeros (filename, osuffix)
 
def tecplot_to_vtkxml (inputFilename, outputFilename)
 
def error (message)
 
def tecplot_to_vtpxml (inputFilename, outputFilename, dim)
 

Function Documentation

◆ addTrailingZeros()

def oomph-convert.addTrailingZeros (   filename,
  osuffix 
)
233 def addTrailingZeros(filename,osuffix):
234 
235  # -- Rename file by adding trailing zeros
236 
237  # 1) Define the number of digits in file name (up to limit_digits)
238 
239  # Assumption:
240  # - the last four characters in ofilename define the extension of filename(".vtu" or ".vtp")
241 
242  limit_digits = 11
243  extension_len = 4
244  digits = 0
245  for i in range(1, limit_digits+1):
246  try:
247  dummy = int(filename[-extension_len-i:-extension_len])
248  digits = i
249  except:
250  pass
251 
252  # 2) Rename the file
253  # - digits in filename: filename[-extension_len-digits:-extension_len]
254  # - extension in filename: filename[-extension_len:]
255  # - base file name in filename: filename[:lenBaseName]
256 
257  # Note: only filenames with 4 or less digits will have a trailing zero if
258  # the second digits in "%05i.vtu" is 5 in os.rename
259 
260  lenBaseName = len(filename) - digits - extension_len
261  if digits == 0:
262  cifer = 0
263  else:
264  cifer = int(filename[-extension_len-digits:-extension_len])
265 
266  return filename[:lenBaseName]+"%05i." % cifer+"%s" % osuffix
267 
268 #
return int(ret)+1
def addTrailingZeros(filename, osuffix)
Definition: oomph-convert.py:233

References int().

Referenced by main().

◆ error()

def oomph-convert.error (   message)
 Write an error message
551 def error(message):
552  """ Write an error message
553  """
554  sys.stderr.write("\nCONVERSION FAILED\n")
555  for line in message.split("\n"):
556  sys.stderr.write("*** %s\n" % line)
557  sys.exit(2)
558 
559 #
def error(message)
Definition: oomph-convert.py:551

Referenced by main(), tecplot_to_vtkxml(), and tecplot_to_vtpxml().

◆ main()

def oomph-convert.main (   argv)
 Main function
108 def main(argv):
109  """ Main function
110  """
111  print "* oomph-convert.py, ver. 20110615"
112 
113  # Check python version. Bark at user if < 2.3 or if major is > 2
114  if sys.version_info<(2,3):
115  print >>sys.stderr, "You need at least Python 2.3 "
116  sys.exit(3)
117 
118  major = sys.version_info[0]
119  if major > 2:
120  print >>sys.stderr, "Python 3 and above versions are not supported yet "
121  sys.exit(3)
122 
123  # Get command-line arguments
124  try:
125  opts, args = getopt.getopt(argv, "hozp:")
126  except getopt.GetoptError:
127  usage()
128  sys.exit(2)
129 
130  # Get options
131  zero_pad_name_flag = False
132  write_points_flag = False
133  overwrite_flag = False
134  for opt, arg in opts:
135  if opt in ("-h"):
136  usage()
137  sys.exit()
138  if opt in ("-z"):
139  zero_pad_name_flag = True
140  if opt in ("-p"):
141  write_points_flag = True
142  argdim = arg
143  if argdim not in ("2","3"):
144  usage()
145  sys.exit()
146  if opt in ("-o"):
147  overwrite_flag = True
148 
149 
150  if len(args) == 1:
151  # Get filename and suffix
152  ifilename = args[0]
153  isuffix = ifilename.split(".")[-1]
154  # Set filename and suffix
155  extension_len = len(isuffix) + 1
156  lenBaseName = len(ifilename) - extension_len
157 
158  if write_points_flag:
159  ofilename = ifilename[:lenBaseName]+".vtp"
160  else:
161  ofilename = ifilename[:lenBaseName]+".vtu"
162 
163  osuffix = ofilename.split(".")[-1]
164 
165  elif len(args) == 2:
166  # Get filenames and suffixes
167  ifilename = args[0]
168  ofilename = args[1]
169  isuffix = ifilename.split(".")[-1]
170  osuffix = ofilename.split(".")[-1]
171 
172  else:
173  usage()
174  sys.exit(2)
175 
176 
177  # Zero pad output names if requested
178  if zero_pad_name_flag:
179  ofilename = addTrailingZeros(ofilename, osuffix)
180 
181 
182  # Check that we are allowed to write to the ofilename (allowed to
183  # overwrite or nothing to overwrite).
184  if ok_to_write_ofile(overwrite_flag, ifilename, ofilename):
185  start = time.time()
186 
187  # Convert from oomph-lib Tecplot format to VTK XML format
188  if isuffix == "dat" and osuffix == "vtu":
189  tecplot_to_vtkxml(ifilename, ofilename)
190 
191  # Convert from oomph-lib Tecplot format to VTP XML format
192  elif isuffix == "dat" and osuffix == "vtp":
193  tecplot_to_vtpxml(ifilename, ofilename,string.atoi(argdim))
194 
195  else:
196  error("Sorry, cannot convert between .%s and .%s file formats." % (isuffix, osuffix))
197 
198  end = time.time()
199  print "* Conversion done in %d seconds" % (end - start)
200  print '* Output file name: %(fn)s ' %{'fn': ofilename}
201 
202 
def tecplot_to_vtpxml(inputFilename, outputFilename, dim)
Definition: oomph-convert.py:846
def usage()
Definition: oomph-convert.py:62
def ok_to_write_ofile(flag, in_file_name, out_file_name)
Definition: oomph-convert.py:203
def main(argv)
Definition: oomph-convert.py:108
def tecplot_to_vtkxml(inputFilename, outputFilename)
Definition: oomph-convert.py:272

References addTrailingZeros(), error(), ok_to_write_ofile(), tecplot_to_vtkxml(), tecplot_to_vtpxml(), and usage().

◆ ok_to_write_ofile()

def oomph-convert.ok_to_write_ofile (   flag,
  in_file_name,
  out_file_name 
)
Check if the output file exists, if so decide if we should overwrite it
and tell the user what we are doing.
203 def ok_to_write_ofile(flag, in_file_name, out_file_name):
204  """Check if the output file exists, if so decide if we should overwrite it
205  and tell the user what we are doing."""
206 
207  if not os.path.exists(out_file_name):
208  return True
209 
210  print "File", in_file_name, "already exists!"
211 
212  # Get modification times (in seconds since unix epoch I think)
213  in_mtime = os.path.getmtime(in_file_name)
214  out_mtime = os.path.getmtime(out_file_name)
215 
216  if flag:
217  print "Overwriting regardless of modification times because of flag."
218  return True
219 
220  elif in_mtime > out_mtime:
221  print "Overwriting because input file is newer than output file"
222  return True
223 
224  else:
225  print "Not overwriting."
226  return False
227 
228 
229 #

Referenced by main().

◆ tecplot_to_vtkxml()

def oomph-convert.tecplot_to_vtkxml (   inputFilename,
  outputFilename 
)
 Converts Tecplot file generates by Oomph into Vtk XML file.
272 def tecplot_to_vtkxml(inputFilename, outputFilename):
273  """ Converts Tecplot file generates by Oomph into Vtk XML file.
274  """
275 
276  #---------------------------------------------------------------------------
277  # Retrieve the zones from the input Tecplot file
278  #---------------------------------------------------------------------------
279  try:
280  input = open(inputFilename, "r")
281  except:
282  error("Failed to open input file for reading !")
283 
284  sys.stdout.write("Parse input file for Tecplot zones........")
285  sys.stdout.flush()
286  line = 0
287  ignoredlines = 0
288  zones = list()
289  while 1:
290  zone = None
291  linetmp = line
292  try:
293  (zone, line) = TecplotZone.parse(input, line)
294  except TecplotParsingError, e:
295  input.close()
296  error(str(e))
297 
298  if zone:
299  zones.append(zone)
300  ignoredlines+=line-linetmp-1-zone.nodesCount()
301  else:
302  print "done"
303  input.close() # Close input file
304  break
305 
306  nbzones = len(zones)
307  sys.stdout.write("* %d lines ignored\n" % ignoredlines)
308  if nbzones == 0:
309 
310  #---------------------------------------------------------------------------
311  # Dummy output
312  #---------------------------------------------------------------------------
313  try:
314  output = open(outputFilename, "w")
315  except:
316  error("Failed to open output file for writing !")
317 
318  output.close()
319  error("The input file " + inputFilename + "\n does not contain any Tecplot zone! Created an empty file... \n You may want to try converting this file to point \n data with -p2 option if dim == 2 or -p3 option if dim == 3")
320 
321  #---------------------------------------------------------------------------
322  # Compute global informations
323  #---------------------------------------------------------------------------
324 
325  # Get the solution dimension (compute the maximum value)
326  dimension=0
327  for zone in zones:
328  if zone.dimension > dimension:
329  dimension=zone.dimension
330 
331  if dimension == 1:
332  error("1D is not supported. Use GnuPlot to display the data file.")
333 
334  # Loop over the zones to get the number of nodes and cells
335  nodesCount = 0
336  cellsCount = 0
337  for zone in zones:
338  nodesCount += zone.nodesCount()
339  cellsCount += zone.cellsCount[0]
340 
341  # Get the field count
342  # Assumption: the number of fields is assumed to be constant over all zones
343  fieldsCount = len(zones[0].nodes[0].fields)
344 
345  #---------------------------------------------------------------------------
346  # Write into Vtk XML output file
347  #---------------------------------------------------------------------------
348  try:
349  output = open(outputFilename, "w")
350  except:
351  error("Failed to open output file for writing !")
352 
353  output.write(VtkXml.header)
354  output.write(VtkXml.unstructuredGridHeader)
355  output.write(VtkXml.pieceHeader % (nodesCount, cellsCount))
356 
357  #---------------------------------------------------------------------------
358  # Nodes
359  #---------------------------------------------------------------------------
360  sys.stdout.write("Write nodal coordinates...................")
361  sys.stdout.flush()
362  output.write(VtkXml.pointsHeader)
363  for zone in zones:
364  for node in zone.nodes:
365  output.write("%e %e %e\n" %(node.coordinates[0], node.coordinates[1], node.coordinates[2]))
366  output.write(VtkXml.pointsFooter)
367  print "done"
368 
369  #---------------------------------------------------------------------------
370  # Cells
371  #---------------------------------------------------------------------------
372  output.write(VtkXml.cellsHeader)
373 
374  # Cell connectivity
375  #---------------------------------------------------------------------------
376  sys.stdout.write("Write cell connectivity...................")
377  sys.stdout.flush()
378  output.write(VtkXml.connectivityHeader)
379  pos = 0 # Current cell origin node index
380 
381  zoneCount=0
382  for zone in zones:
383 
384  zoneCount+=1
385  if zone.cellFormat[0] == 1:
386 
387  if zoneCount == 1: maxNode=0
388 
389  # dump connectivities
390  for element in range (0, zone.cellsCount[0]):
391  conn=zone.connectivities[element]
392  for i in range(0, len(conn)):
393  dum=int(conn[i])
394  # renumber connectivity table if it belongs to zone > 1
395  if zoneCount > 1: dum+=maxNode+1
396  conn[i]=dum-1
397  output.write("%i " %(conn[i]))
398  output.write("\n")
399 
400  # compute maximum node number for renumbering of next connectivity table
401  maxNode=0
402  for element in range (0, zone.cellsCount[0]):
403  conn=zone.connectivities[element]
404  for i in range(0, len(conn)):
405  conn[i]=int(conn[i])
406  dum=max(conn)
407  if dum > maxNode:
408  maxNode = dum
409 
410  if zone.cellFormat[0] == 2:
411 
412  dimI = zone.edges[0]
413 
414  if zone.dimension[0] == 1: # Line (dim I = 2)
415  indexes = [pos, pos+1]
416  output.write(" ".join(map(str, indexes)) + "\n")
417  pos += dimI
418 
419  if zone.dimension[0] == 2: # Quad
420  dimJ = zone.edges[1]
421  indexes = 4 * [0]
422  for j in range(dimJ - 1):
423  for i in range(dimI - 1):
424  # Unique face of the cell
425  indexes[0] = pos # bottom-left node
426  indexes[1] = pos + 1 # bottom-right node
427  indexes[2] = pos + 1 + dimI # top-right node
428  indexes[3] = pos + dimI # to-left node
429  output.write(" ".join(map(str, indexes)) + "\n")
430  # Next cell
431  pos += 1
432  # Next row of cells
433  pos += 1
434  # Next zone
435  pos += dimI
436 
437  if zone.dimension[0] == 3: # Hexahedron
438  indexes = 8 * [0]
439  dimJ = zone.edges[1]
440  dimK = zone.edges[2]
441  for k in range(dimK - 1):
442  for j in range(dimJ - 1):
443  for i in range(dimI - 1):
444  # Front face of the cell
445  indexes[0] = pos # bottom-left node
446  indexes[1] = pos + 1 # bottom-right node
447  indexes[2] = pos + 1 + dimI # top-right node
448  indexes[3] = pos + dimI # to-left node
449  # Back face of the cell
450  backPos = pos + dimI * dimJ
451  indexes[4] = backPos
452  indexes[5] = backPos + 1
453  indexes[6] = backPos + 1 + dimI
454  indexes[7] = backPos + dimI
455  output.write(" ".join(map(str, indexes)) + "\n")
456  # Next cell
457  pos += 1
458  # Next row of cells
459  pos += 1
460  # Next k
461  pos += dimI
462  # Next zone
463  pos += dimI * dimJ
464 
465  output.write(VtkXml.connectivityFooter)
466  print "done"
467 
468  # Cell offset
469  #---------------------------------------------------------------------------
470  sys.stdout.write("Write cell offsets........................")
471  sys.stdout.flush()
472  output.write(VtkXml.offsetsHeader)
473  offset = 0
474  for zone in zones:
475  for i in range(1,zone.cellsCount[0]+1):
476  if zone.cellType[0] == 3: # VTK_LINE
477  offset +=2
478  if zone.cellType[0] == 5: # VTK_TRIANGLE
479  offset +=3
480  if zone.cellType[0] == 9: # VTK_QUAD
481  offset +=4
482  if zone.cellType[0] == 10: # VTK_TETRAHEDRON
483  offset +=4
484  if zone.cellType[0] == 12: # VTK_HEXAHEDRON
485  offset +=8
486  output.write(str(offset) + "\n")
487  output.write(VtkXml.offsetsFooter)
488  print "done"
489 
490  # Cell types
491  #---------------------------------------------------------------------------
492  sys.stdout.write("Write cell types..........................")
493  sys.stdout.flush()
494 
495  output.write(VtkXml.typesHeader)
496 
497  cellType0 = zones[0].cellType[0]
498  warn = 0
499  for zone in zones:
500  if zone.cellType[0] == 3: # VTK_LINE
501  cellType = "3"
502  if zone.cellType[0] == 5: # VTK_TRIANGLE
503  cellType = "5"
504  if zone.cellType[0] == 9: # VTK_QUAD
505  cellType = "9"
506  if zone.cellType[0] == 10: # VTK_TETRAHEDRON
507  cellType = "10"
508  if zone.cellType[0] == 12: # VTK_HEXAHEDRON
509  cellType = "12"
510 
511  if warn == 0 and not zone.cellType[0] == cellType0:#Check if types are differents
512  warn = 1
513  output.write(zone.cellsCount[0] * (cellType + "\n"))
514 
515  output.write(VtkXml.typesFooter)
516  print "done"
517  if warn == 1:
518  sys.stdout.write("Warning: Different types of elements \n")
519  output.write(VtkXml.cellsFooter)
520 
521  #---------------------------------------------------------------------------
522  # Fields
523  #---------------------------------------------------------------------------
524  output.write(VtkXml.pointDataHeader)
525  for fieldIndex in range(fieldsCount):
526  sys.stdout.write("Write field %02d/%02d........................." % (fieldIndex + 1, fieldsCount))
527  sys.stdout.flush()
528  output.write(VtkXml.fieldHeader % (fieldIndex + 1))
529  for zone in zones:
530  for node in zone.nodes:
531  output.write("%e\n" % node.fields[fieldIndex])
532 
533  print "done"
534  output.write(VtkXml.fieldFooter)
535 
536  output.write(VtkXml.pointDataFooter)
537 
538  output.write(VtkXml.pieceFooter)
539  output.write(VtkXml.unstructuredGridFooter)
540  output.write(VtkXml.footer)
541 
542  #---------------------------------------------------------------------------
543  # Close output file
544  #---------------------------------------------------------------------------
545  output.close()
546 
547 #
#define max(a, b)
Definition: datatypes.h:23
str
Definition: compute_granudrum_aor.py:141

References error(), int(), max, and compute_granudrum_aor.str.

Referenced by main().

◆ tecplot_to_vtpxml()

def oomph-convert.tecplot_to_vtpxml (   inputFilename,
  outputFilename,
  dim 
)
 Converts Tecplot file generates by Oomph into Vtp XML file.
846 def tecplot_to_vtpxml(inputFilename, outputFilename, dim):
847  """ Converts Tecplot file generates by Oomph into Vtp XML file.
848  """
849 
850  #---------------------------------------------------------------------------
851  # Retrieve the points from the input Tecplot file
852  #---------------------------------------------------------------------------
853  try:
854  input = open(inputFilename, "r")
855  except:
856  error("Failed to open input file for reading !")
857 
858  sys.stdout.write("Parse input file for points........")
859  sys.stdout.flush()
860  line = 0
861  prev_line=0
862  offset_list=[]
863  count=0
864  nzone=1
865  points = list()
866  while 1:
867  point = None
868  try:
869  (point, line) = InputPoints.parse(input, line, dim)
870  #print "line %d %d is..." % (line, prev_line)
871  if line != prev_line+1 :
872  #print "...normal point"
873  #else:
874  #print "...start point"
875  if prev_line !=0:
876  offset_list.append(count)
877  nzone+=1
878  count+=1
879  prev_line=line
880 
881  except TecplotParsingError, e:
882  input.close()
883  error(str(e))
884 
885  if point:
886  points.append(point)
887  else:
888  print "done"
889  input.close() # Close input file
890  break
891 
892  offset_list.append(count-1)
893  nbpoints = len(points)
894 
895  if nbpoints == 0:
896  error("The input file does not contain any point !")
897 
898 
899  #---------------------------------------------------------------------------
900  # Compute global informations
901  #---------------------------------------------------------------------------
902 
903  # Get the field count
904  # Assumption: the number of fields is assumed to be constant over all points
905  fieldsCount = len(points[0].fields)
906 
907  #---------------------------------------------------------------------------
908  # Write into Vtp XML output file
909  #---------------------------------------------------------------------------
910  try:
911  output = open(outputFilename, "w")
912  except:
913  error("Failed to open output file for writing !")
914 
915  output.write(VtpXml.header)
916  output.write(VtpXml.polyDataHeader)
917  output.write(VtpXml.pieceHeader % (nbpoints,nzone))
918 
919  #---------------------------------------------------------------------------
920  # Nodes
921  #---------------------------------------------------------------------------
922  sys.stdout.write("Write points coordinates...................")
923  sys.stdout.flush()
924  output.write(VtpXml.pointsHeader)
925  for point in points:
926  output.write("%e %e %e\n" %(point.coordinates[0], point.coordinates[1], point.coordinates[2]))
927  output.write(VtpXml.pointsFooter)
928  print "done"
929 
930  #---------------------------------------------------------------------------
931  # Fields
932  #---------------------------------------------------------------------------
933  output.write(VtpXml.pointDataHeader)
934  for fieldIndex in range(fieldsCount):
935  sys.stdout.write("Write field %02d/%02d........................." % (fieldIndex + 1, fieldsCount))
936  sys.stdout.flush()
937  output.write(VtpXml.fieldHeader % (fieldIndex + 1))
938  for point in points:
939  output.write("%e\n" % point.fields[fieldIndex])
940 
941  print "done"
942  output.write(VtpXml.fieldFooter)
943 
944  output.write(VtpXml.pointDataFooter)
945 
946  #---------------------------------------------------------------------------
947  # Headers and footers
948  #---------------------------------------------------------------------------
949 
950  output.write(VtpXml.vertsHeader)
951  output.write(VtpXml.vertsFooter)
952  output.write(VtpXml.linesHeader)
953  #Prepare line information:
954  output.write(VtkXml.connectivityHeader)
955  for i in range(0,nbpoints):
956  output.write("%i "%i)
957  output.write(VtkXml.connectivityFooter)
958  output.write(VtkXml.offsetsHeader)
959  for offset in offset_list:
960  output.write("%i "%offset)
961  output.write(VtkXml.offsetsFooter)
962  #end line information
963  output.write(VtpXml.linesFooter)
964  output.write(VtpXml.stripsHeader)
965  output.write(VtpXml.stripsFooter)
966  output.write(VtpXml.polysHeader)
967  output.write(VtpXml.polysFooter)
968  output.write(VtpXml.pieceFooter)
969  output.write(VtpXml.polyDataFooter)
970  output.write(VtpXml.footer)
971 
972  #---------------------------------------------------------------------------
973  # Close output file
974  #---------------------------------------------------------------------------
975  output.close()
976 
977 #

References error(), and compute_granudrum_aor.str.

Referenced by main().

◆ usage()

def oomph-convert.usage ( )
 Display usage
62 def usage():
63  """ Display usage
64  """
65  print """\
66 
67 NAME
68  oomph-convert.py - script for converting from oomph-lib tecplot format to VTK XML.
69 
70 
71 SYNOPSIS
72  oomph-convert.py [OPTION] [input_file.dat] [output_file]
73 
74 
75 OPTIONS
76  -p2 or -p3 outputs only points in 2D or 3D (.vtp)
77  -h display this help text and exit
78  -z add trailing zeros to the output filename
79  -o force overwrite existing files
80 
81  By default output files will overwrite old ones only if the input file is
82  newer than the output file.
83 
84 
85 TYPICAL USAGE EXAMPLES
86  oomph-convert.py -h -> display help text
87  oomph-convert.py soln12.dat soln12.vtu -> generate soln12.vtu
88  oomph-convert.py -z soln12.dat soln12.vtu -> generate soln00012.vtu
89  oomph-convert.py soln12.dat -> generate soln12.vtu
90  oomph-convert.py -z soln12.dat -> generate soln00012.vtu
91  oomph-convert.py soln12.dat nsol2.vtu -> generate nsol2.vtu
92  oomph-convert.py -z soln12.dat nsol2.vtu -> generate nsol00002.vtu
93  oomph-convert.py soln.dat -> generate soln.vtu
94  oomph-convert.py -z soln.dat -> generate soln00000.vtu
95  oomph-convert.py -p3 soln12.dat soln12.vtp -> generate soln12.vtp
96  oomph-convert.py -p2 -z soln12.dat soln12.vtp -> generate soln00012.vtp
97  oomph-convert.py -p3 soln12.dat -> generate soln12.vtp
98  oomph-convert.py -p2 -z soln12.dat -> generate soln00012.vtp
99  oomph-convert.py -p3 soln12.dat nsol2.vtp -> generate nsol2.vtp
100  oomph-convert.py -p2 -z soln12.dat nsol2.vtp -> generate nsol00002.vtp
101  oomph-convert.py -p3 soln.dat -> generate soln.vtp
102  oomph-convert.py -p2 -z soln.dat -> generate soln00000.vtp"""
103 
104 #

Referenced by main().