Debian Codegraph @

python/dolfin_utils/meshconvert/meshconvert.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # -*- coding: utf-8 -*-
2 """ Module for converting various mesh formats."""
3
4 # Copyright (C) 2006 Anders Logg
5 #
6 # This file is part of DOLFIN.
7 #
8 # DOLFIN is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU Lesser General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # DOLFIN is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU Lesser General Public License for more details.
17 #
18 # You should have received a copy of the GNU Lesser General Public License
19 # along with DOLFIN. If not, see <http://www.gnu.org/licenses/>.
20 #
21 # Modified by Garth N. Wells (gmsh function)
22 # Modified by Alexander H. Jarosch (gmsh fix)
23 # Modified by Angelo Simone (Gmsh and Medit fix)
24 # Modified by Andy R. Terrel (gmsh fix and triangle function)
25 # Modified by Magnus Vikstrom (metis and scotch function)
26 # Modified by Bartosz Sawicki (diffpack function)
27 # Modified by Gideon Simpson (Exodus II function)
28 # Modified by Kent-Andre Mardal (Star-CD function)
29 # Modified by Nuno Lopes (fix for emc2 mesh format (medit version 0))
30 # Modified by Neilen Marais (add gmsh support for reading physical region)
31 # Modified by Evan Lezar (add support for reading gmsh physical regions on facets)
32 # Modified by Jan Blechta (add triangle support for marker on edges and attributes on triangles)
33 #
34 # Last changed: 2014-02-06
35
36 # NOTE: This module does not depend on (py)dolfin beeing installed.
37 # NOTE: If future additions need that please import dolfin in a try: except:
38 # NOTE: clause and tell the user to install dolfin if it is not installed.
39
40
41 import getopt
42 import subprocess
43 import sys
44 import re
45 import warnings
46 import os.path
47 import numpy
48
49 from . import abaqus
50 from . import xml_writer
51
52 def format_from_suffix(suffix):
53 "Return format for given suffix"
54 if suffix == "xml":
55 return "xml"
56 elif suffix == "mesh":
57 return "mesh"
58 elif suffix == "gmsh":
59 return "gmsh"
60 elif suffix == "msh":
61 return "gmsh"
62 elif suffix == "gra":
63 return "metis"
64 elif suffix == "grf":
65 return "scotch"
66 elif suffix == "grid":
67 return "diffpack"
68 elif suffix == "inp":
69 return "abaqus"
70 elif suffix == "ncdf":
71 return "NetCDF"
72 elif suffix =="exo":
73 return "ExodusII"
74 elif suffix =="e":
75 return "ExodusII"
76 elif suffix == "vrt" or suffix == "cel":
77 return "StarCD"
78 elif suffix == "ele" or suffix == "node":
79 return "Triangle"
80 else:
81 _error("Sorry, unknown suffix %s." % suffix)
82
83 def mesh2xml(ifilename, ofilename):
84 """Convert between .mesh and .xml, parser implemented as a
85 state machine:
86
87 0 = read 'Vertices'
88 1 = read number of vertices
89 2 = read next vertex
90 3 = read 'Triangles' or 'Tetrahedra'
91 4 = read number of cells
92 5 = read next cell
93 6 = done
94
95 """
96
97 print("Converting from Medit format (.mesh) to DOLFIN XML format")
98
99 # Open files
100 ifile = open(ifilename, "r")
101 ofile = open(ofilename, "w")
102
103 # Scan file for cell type
104 cell_type = None
105 dim = 0
106 while 1:
107
108 # Read next line
109 line = ifile.readline()
110 if not line: break
111
112 # Remove newline
113 line = line.strip(" \n\r").split(" ")
114
115 # Read dimension either on same line or following line
116 if line[0] == "Dimension":
117 if (len(line) == 2):
118 line = line[1]
119 else:
120 line = ifile.readline()
121 num_dims = int(line)
122 if num_dims == 2:
123 cell_type = "triangle"
124 dim = 2
125 elif num_dims == 3:
126 cell_type = "tetrahedron"
127 dim = 3
128 break
129
130 # Check that we got the cell type
131 if cell_type == None:
132 _error("Unable to find cell type.")
133
134 # Step to beginning of file
135 ifile.seek(0)
136
137 # Write header
138 xml_writer.write_header_mesh(ofile, cell_type, dim)
139
140 # Current state
141 state = 0
142
143 # Write data
144 num_vertices_read = 0
145 num_cells_read = 0
146
147 while 1:
148
149 # Read next line
150 line = ifile.readline()
151 if not line: break
152
153 # Skip comments
154 if line[0] == '#':
155 continue
156
157 # Remove newline
158 line = line.rstrip("\n\r")
159
160 if state == 0:
161 if line == "Vertices" or line == " Vertices":
162 state += 1
163 elif state == 1:
164 num_vertices = int(line)
165 xml_writer.write_header_vertices(ofile, num_vertices)
166 state +=1
167 elif state == 2:
168 if num_dims == 2:
169 (x, y, tmp) = line.split()
170 x = float(x)
171 y = float(y)
172 z = 0.0
173 elif num_dims == 3:
174 (x, y, z, tmp) = line.split()
175 x = float(x)
176 y = float(y)
177 z = float(z)
178 xml_writer.write_vertex(ofile, num_vertices_read, x, y, z)
179 num_vertices_read +=1
180 if num_vertices == num_vertices_read:
181 xml_writer.write_footer_vertices(ofile)
182 state += 1
183 elif state == 3:
184 if (line == "Triangles" or line == " Triangles") and num_dims == 2:
185 state += 1
186 if line == "Tetrahedra" and num_dims == 3:
187 state += 1
188 elif state == 4:
189 num_cells = int(line)
190 xml_writer.write_header_cells(ofile, num_cells)
191 state +=1
192 elif state == 5:
193 if num_dims == 2:
194 (n0, n1, n2, tmp) = line.split()
195 n0 = int(n0) - 1
196 n1 = int(n1) - 1
197 n2 = int(n2) - 1
198 xml_writer.write_cell_triangle(ofile, num_cells_read, n0, n1, n2)
199 elif num_dims == 3:
200 (n0, n1, n2, n3, tmp) = line.split()
201 n0 = int(n0) - 1
202 n1 = int(n1) - 1
203 n2 = int(n2) - 1
204 n3 = int(n3) - 1
205 xml_writer.write_cell_tetrahedron(ofile, num_cells_read, n0, n1, n2, n3)
206 num_cells_read +=1
207 if num_cells == num_cells_read:
208 xml_writer.write_footer_cells(ofile)
209 state += 1
210 elif state == 6:
211 break
212
213 # Check that we got all data
214 if state == 6:
215 print("Conversion done")
216 else:
217 _error("Missing data, unable to convert")
218
219 # Write footer
220 xml_writer.write_footer_mesh(ofile)
221
222 # Close files
223 ifile.close()
224 ofile.close()
225
226 def gmsh2xml(ifilename, handler):
227 """Convert between .gmsh v2.0 format (http://www.geuz.org/gmsh/) and .xml,
228 parser implemented as a state machine:
229
230 0 = read 'MeshFormat'
231 1 = read mesh format data
232 2 = read 'EndMeshFormat'
233 3 = read 'Nodes'
234 4 = read number of vertices
235 5 = read vertices
236 6 = read 'EndNodes'
237 7 = read 'Elements'
238 8 = read number of cells
239 9 = read cells
240 10 = done
241
242 Afterwards, extract physical region numbers if they are defined in
243 the mesh file as a mesh function.
244
245 """
246
247 print("Converting from Gmsh format (.msh, .gmsh) to DOLFIN XML format")
248
249 # The dimension of the gmsh element types supported here as well as the dolfin cell types for each dimension
250 gmsh_dim = {15: 0, 1: 1, 2: 2, 4: 3}
251 cell_type_for_dim = {1: "interval", 2: "triangle", 3: "tetrahedron" }
252 # the gmsh element types supported for conversion
253 supported_gmsh_element_types = [1, 2, 4, 15]
254
255 # Open files
256 ifile = open(ifilename, "r")
257
258 # Scan file for cell type
259 cell_type = None
260 highest_dim = 0
261 line = ifile.readline()
262 while line:
263
264 # Remove newline
265 line = line.rstrip("\n\r")
266
267 # Read dimension
268 if line.find("$Elements") == 0:
269
270 line = ifile.readline()
271 num_elements = int(line)
272 if num_elements == 0:
273 _error("No elements found in gmsh file.")
274 line = ifile.readline()
275
276 # Now iterate through elements to find largest dimension. Gmsh
277 # format might include elements of lower dimensions in the element list.
278 # We also need to count number of elements of correct dimensions.
279 # Also determine which vertices are not used.
280 dim_count = {0: 0, 1: 0, 2: 0, 3: 0}
281 vertices_used_for_dim = {0: [], 1: [], 2: [], 3: []}
282 # Array used to store gmsh tags for 1D (type 1/line), 2D (type 2/triangular) elements and 3D (type 4/tet) elements
283 tags_for_dim = {0: [], 1: [], 2: [], 3: []}
284
285 while line.find("$EndElements") == -1:
286 element = line.split()
287 elem_type = int(element[1])
288 num_tags = int(element[2])
289 if elem_type in supported_gmsh_element_types:
290 dim = gmsh_dim[elem_type]
291 if highest_dim < dim:
292 highest_dim = dim
293 node_num_list = [int(node) for node in element[3 + num_tags:]]
294 vertices_used_for_dim[dim].extend(node_num_list)
295 if num_tags > 0:
296 tags_for_dim[dim].append(tuple(int(tag) for tag in element[3:3+num_tags]))
297 dim_count[dim] += 1
298 else:
299 #TODO: output a warning here. "gmsh element type %d not supported" % elem_type
300 pass
301 line = ifile.readline()
302 else:
303 # Read next line
304 line = ifile.readline()
305
306 # Check that we got the cell type and set num_cells_counted
307 if highest_dim == 0:
308 _error("Unable to find cells of supported type.")
309
310 num_cells_counted = dim_count[highest_dim]
311 vertex_set = set(vertices_used_for_dim[highest_dim])
312 vertices_used_for_dim[highest_dim] = None
313
314 vertex_dict = {}
315 for n,v in enumerate(vertex_set):
316 vertex_dict[v] = n
317
318 # Step to beginning of file
319 ifile.seek(0)
320
321 # Set mesh type
322 handler.set_mesh_type(cell_type_for_dim[highest_dim], highest_dim)
323
324 # Initialise node list (gmsh does not export all vertexes in order)
325 nodelist = {}
326
327 # Current state
328 state = 0
329
330 # Write data
331 num_vertices_read = 0
332 num_cells_read = 0
333
334 # Only import the dolfin objects if facet markings exist
335 process_facets = False
336 if len(tags_for_dim[highest_dim-1]) > 0:
337 # first construct the mesh
338 try:
339 from dolfin import MeshEditor, Mesh
340 except ImportError:
341 _error("DOLFIN must be installed to handle Gmsh boundary regions")
342 mesh = Mesh()
343 mesh_editor = MeshEditor ()
344 if (highest_dim == 2):
345 mesh_editor.open(mesh, "triangle", highest_dim, highest_dim)
346 elif (highest_dim == 3):
347 mesh_editor.open(mesh, "tetrahedron", highest_dim, highest_dim)
348 else:
349 raise RuntimeError
350 process_facets = True
351 else:
352 # TODO: Output a warning or an error here
353 me = None
354
355 while state != 10:
356
357 # Read next line
358 line = ifile.readline()
359 if not line: break
360
361 # Skip comments
362 if line[0] == '#':
363 continue
364
365 # Remove newline
366 line = line.rstrip("\n\r")
367
368 if state == 0:
369 if line == "$MeshFormat":
370 state = 1
371 elif state == 1:
372 (version, file_type, data_size) = line.split()
373 state = 2
374 elif state == 2:
375 if line == "$EndMeshFormat":
376 state = 3
377 elif state == 3:
378 if line == "$Nodes":
379 state = 4
380 elif state == 4:
381 num_vertices = len(vertex_dict)
382 handler.start_vertices(num_vertices)
383 if process_facets:
384 mesh_editor.init_vertices_global(num_vertices, num_vertices)
385 state = 5
386 elif state == 5:
387 (node_no, x, y, z) = line.split()
388 node_no = int(node_no)
389 x,y,z = [float(xx) for xx in (x,y,z)]
390 if node_no in vertex_dict:
391 node_no = vertex_dict[node_no]
392 else:
393 continue
394 nodelist[int(node_no)] = num_vertices_read
395 handler.add_vertex(num_vertices_read, [x, y, z])
396 if process_facets:
397 if highest_dim == 1:
398 coords = numpy.array([x])
399 elif highest_dim == 2:
400 coords = numpy.array([x, y])
401 elif highest_dim == 3:
402 coords = numpy.array([x, y, z])
403 mesh_editor.add_vertex(num_vertices_read, coords)
404
405 num_vertices_read +=1
406
407 if num_vertices == num_vertices_read:
408 handler.end_vertices()
409 state = 6
410 elif state == 6:
411 if line == "$EndNodes":
412 state = 7
413 elif state == 7:
414 if line == "$Elements":
415 state = 8
416 elif state == 8:
417 handler.start_cells(num_cells_counted)
418 if process_facets:
419 mesh_editor.init_cells_global(num_cells_counted, num_cells_counted)
420
421 state = 9
422 elif state == 9:
423 element = line.split()
424 elem_type = int(element[1])
425 num_tags = int(element[2])
426 if elem_type in supported_gmsh_element_types:
427 dim = gmsh_dim[elem_type]
428 else:
429 dim = 0
430 if dim == highest_dim:
431 node_num_list = [vertex_dict[int(node)] for node in element[3 + num_tags:]]
432 for node in node_num_list:
433 if not node in nodelist:
434 _error("Vertex %d of %s %d not previously defined." %
435 (node, cell_type_for_dim[dim], num_cells_read))
436 cell_nodes = [nodelist[n] for n in node_num_list]
437 handler.add_cell(num_cells_read, cell_nodes)
438
439 if process_facets:
440 cell_nodes = numpy.array([nodelist[n] for n in node_num_list], dtype=numpy.uintp)
441 mesh_editor.add_cell(num_cells_read, cell_nodes)
442
443 num_cells_read +=1
444
445 if num_cells_counted == num_cells_read:
446 handler.end_cells()
447 if process_facets:
448 mesh_editor.close()
449 state = 10
450 elif state == 10:
451 break
452
453 # Write mesh function based on the Physical Regions defined by
454 # gmsh, but only if they are not all zero. All zero physical
455 # regions indicate that no physical regions were defined.
456 if highest_dim not in [1,2,3]:
457 _error("Gmsh tags not supported for dimension %i. Probably a bug" % dim)
458
459 tags = tags_for_dim[highest_dim]
460 physical_regions = tuple(tag[0] for tag in tags)
461 if not all(tag == 0 for tag in physical_regions):
462 handler.start_meshfunction("physical_region", dim, num_cells_counted)
463 for i, physical_region in enumerate(physical_regions):
464 handler.add_entity_meshfunction(i, physical_region)
465 handler.end_meshfunction()
466
467 # Now process the facet markers
468 tags = tags_for_dim[highest_dim-1]
469 if (len(tags) > 0) and (mesh is not None):
470 physical_regions = tuple(tag[0] for tag in tags)
471 if not all(tag == 0 for tag in physical_regions):
472 mesh.init(highest_dim-1,0)
473
474 # Get the facet-node connectivity information (reshape as a row of node indices per facet)
475 if highest_dim==1:
476 # for 1d meshes the mesh topology returns the vertex to vertex map, which isn't what we want
477 # as facets are vertices
478 facets_as_nodes = numpy.array([[i] for i in range(mesh.num_facets())])
479 else:
480 facets_as_nodes = numpy.reshape(mesh.topology()(highest_dim-1,0)(),(mesh.num_facets(), highest_dim))
481
482 # Build the reverse map
483 nodes_as_facets = {}
484 for facet in range(mesh.num_facets()):
485 nodes_as_facets[tuple(facets_as_nodes[facet,:])] = facet
486
487 data = [int(0*k) for k in range(mesh.num_facets()) ]
488 for i, physical_region in enumerate(physical_regions):
489 nodes = [n-1 for n in vertices_used_for_dim[highest_dim-1][highest_dim*i:(highest_dim*i+highest_dim)]]
490 nodes.sort()
491
492 if physical_region != 0:
493 try:
494 index = nodes_as_facets[tuple(nodes)]
495 data[index] = physical_region
496 except IndexError:
497 raise Exception ( "The facet (%d) was not found to mark: %s" % (i, nodes) )
498
499 # Create and initialise the mesh function
500 handler.start_meshfunction("facet_region", highest_dim-1, mesh.num_facets() )
501 for index, physical_region in enumerate ( data ):
502 handler.add_entity_meshfunction(index, physical_region)
503 handler.end_meshfunction()
504
505 # Check that we got all data
506 if state == 10:
507 print("Conversion done")
508 else:
509 _error("Missing data, unable to convert \n\ Did you use version 2.0 of the gmsh file format?")
510
511 # Close files
512 ifile.close()
513
514 def triangle2xml(ifilename, ofilename):
515 """Convert between triangle format
516 (http://www.cs.cmu.edu/~quake/triangle.html) and .xml. The
517 given ifilename should be the prefix for the corresponding
518 .node, and .ele files.
519 """
520
521 def get_next_line (fp):
522 """Helper function for skipping comments and blank lines"""
523 line = fp.readline()
524 if line == '':
525 _error("Hit end of file prematurely.")
526 line = line.strip()
527 if not (line.startswith('#') or line == ''):
528 return line
529 return get_next_line(fp)
530
531
532 print("Converting from Triangle format {.node, .ele} to DOLFIN XML format")
533
534 # Open files
535 for suffix in [".node", ".ele"]:
536 if suffix in ifilename and ifilename[-len(suffix):] == suffix:
537 ifilename = ifilename.replace(suffix, "")
538 node_file = open(ifilename+".node", "r")
539 ele_file = open(ifilename+".ele", "r")
540 ofile = open(ofilename, "w")
541 try:
542 edge_file = open(ifilename+".edge", "r")
543 print("Found .edge file")
544 except IOError:
545 edge_file = None
546
547 # Read all the nodes
548 nodes = {}
549 num_nodes, dim, attr, bound = list(map(int, get_next_line(node_file).split()))
550 while len(nodes) < num_nodes:
551 node, x, y = get_next_line(node_file).split()[:3]
552 nodes[int(node)] = (float(x), float(y))
553
554 # Read all the triangles
555 tris = {}
556 tri_attrs = {}
557 num_tris, n_per_tri, attrs = list(map(int, get_next_line(ele_file).split()))
558 while len(tris) < num_tris:
559 line = get_next_line(ele_file).split()
560 tri, n1, n2, n3 = list(map(int, line[:4]))
561 # vertices are ordered according to current UFC ordering scheme -
562 # - may change in future!
563 tris[tri] = tuple(sorted((n1, n2, n3)))
564 tri_attrs[tri] = tuple(map(float, line[4:4+attrs]))
565
566 # Read all the boundary markers from edges
567 edge_markers_global = {}
568 edge_markers_local = []
569 got_negative_edge_markers = False
570 if edge_file is not None:
571 num_edges, num_edge_markers = list(map(int, get_next_line(edge_file).split()))
572 if num_edge_markers == 1:
573 while len(edge_markers_global) < num_edges:
574 edge, v1, v2, marker = list(map(int, get_next_line(edge_file).split()))
575 if marker < 0: got_negative_edge_markers = True
576 edge_markers_global[tuple(sorted((v1, v2)))] = marker
577 if got_negative_edge_markers:
578 print("Some edge markers are negative! dolfin will increase "\
579 "them by probably 2**32 when loading xml. "\
580 "Consider using non-negative edge markers only.")
581 for tri, vertices in tris.items():
582 v0, v1, v2 = sorted((vertices[0:3]))
583 try:
584 edge_markers_local.append((tri, 0, \
585 edge_markers_global[(v1, v2)]))
586 edge_markers_local.append((tri, 1, \
587 edge_markers_global[(v0, v2)]))
588 edge_markers_local.append((tri, 2, \
589 edge_markers_global[(v0, v1)]))
590 except IndexError:
591 raise Exception("meshconvert.py: The facet was not found.")
592 elif num_edge_markers == 0:
593 print("...but no markers in it. Ignoring it")
594 else:
595 print("...but %d markers specified in it. It won't be processed."\
596 %num_edge_markers)
597
598 # Write everything out
599 xml_writer.write_header_mesh(ofile, "triangle", 2)
600 xml_writer.write_header_vertices(ofile, num_nodes)
601 node_off = 0 if 0 in nodes else -1
602 for node, node_t in nodes.items():
603 xml_writer.write_vertex(ofile, node+node_off, node_t[0], node_t[1], 0.0)
604 xml_writer.write_footer_vertices(ofile)
605 xml_writer.write_header_cells(ofile, num_tris)
606 tri_off = 0 if 0 in tris else -1
607 for tri, tri_t in tris.items():
608 xml_writer.write_cell_triangle(ofile, tri+tri_off, tri_t[0] + node_off,
609 tri_t[1] + node_off, tri_t[2] + node_off)
610 xml_writer.write_footer_cells(ofile)
611 if len(edge_markers_local) > 0:
612 xml_writer.write_header_domains(ofile)
613 xml_writer.write_header_meshvaluecollection(ofile, \
614 "edge markers", 1, len(edge_markers_local), "uint")
615 for tri, local_edge, marker in edge_markers_local:
616 xml_writer.write_entity_meshvaluecollection(ofile, \
617 1, tri+tri_off, marker, local_edge)
618 xml_writer.write_footer_meshvaluecollection(ofile)
619 xml_writer.write_footer_domains(ofile)
620 xml_writer.write_footer_mesh(ofile)
621 for i in range(attrs):
622 afilename = ofilename.replace(".xml", ".attr"+str(i)+".xml")
623 afile = open(afilename, "w")
624 xml_writer.write_header_meshfunction2(afile)
625 xml_writer.write_header_meshvaluecollection(afile, \
626 "triangle attribs "+str(i), 2, num_tris, "double")
627 for tri, tri_a in tri_attrs.items():
628 xml_writer.write_entity_meshvaluecollection(afile, \
629 2, tri+tri_off, tri_a[i], 0)
630 xml_writer.write_footer_meshvaluecollection(afile)
631 xml_writer.write_footer_meshfunction(afile)
632 print("triangle attributes from .ele file written to "+afilename)
633 afile.close()
634
635 # Close files
636 node_file.close()
637 ele_file.close()
638 if edge_file is not None:
639 edge_file.close()
640 ofile.close()
641
642
643 def xml_old2xml(ifilename, ofilename):
644 "Convert from old DOLFIN XML format to new."
645
646 print("Converting from old (pre DOLFIN 0.6.2) to new DOLFIN XML format...")
647
648 # Open files
649 ifile = open(ifilename, "r")
650 ofile = open(ofilename, "w")
651
652 # Scan file for cell type (assuming there is just one)
653 cell_type = None
654 dim = 0
655 while 1:
656
657 # Read next line
658 line = ifile.readline()
659 if not line: break
660
661 # Read dimension
662 if "<triangle" in line:
663 cell_type = "triangle"
664 dim = 2
665 break
666 elif "<tetrahedron" in line:
667 cell_type = "tetrahedron"
668 dim = 3
669 break
670
671 # Step to beginning of file
672 ifile.seek(0)
673
674 # Read lines and make changes
675 while 1:
676
677 # Read next line
678 line = ifile.readline()
679 if not line: break
680
681 # Modify line
682 if "xmlns" in line:
683 line = "<dolfin xmlns:dolfin=\"http://fenicsproject.org\">\n"
684 if "<mesh>" in line:
685 line = " <mesh celltype=\"%s\" dim=\"%d\">\n" % (cell_type, dim)
686 if dim == 2 and " z=\"0.0\"" in line:
687 line = line.replace(" z=\"0.0\"", "")
688 if " name=" in line:
689 line = line.replace(" name=", " index=")
690 if " name =" in line:
691 line = line.replace(" name =", " index=")
692 if "n0" in line:
693 line = line.replace("n0", "v0")
694 if "n1" in line:
695 line = line.replace("n1", "v1")
696 if "n2" in line:
697 line = line.replace("n2", "v2")
698 if "n3" in line:
699 line = line.replace("n3", "v3")
700
701 # Write line
702 ofile.write(line)
703
704 # Close files
705 ifile.close();
706 ofile.close();
707 print("Conversion done")
708
709 def metis_graph2graph_xml(ifilename, ofilename):
710 "Convert from Metis graph format to DOLFIN Graph XML."
711
712 print("Converting from Metis graph format to DOLFIN Graph XML.")
713
714 # Open files
715 ifile = open(ifilename, "r")
716 ofile = open(ofilename, "w")
717
718 # Read number of vertices and edges
719 line = ifile.readline()
720 if not line:
721 _error("Empty file")
722
723 (num_vertices, num_edges) = line.split()
724
725 xml_writer.write_header_graph(ofile, "directed")
726 xml_writer.write_header_vertices(ofile, int(num_vertices))
727
728 for i in range(int(num_vertices)):
729 line = ifile.readline()
730 edges = line.split()
731 xml_writer.write_graph_vertex(ofile, i, len(edges))
732
733 xml_writer.write_footer_vertices(ofile)
734 xml_writer.write_header_edges(ofile, 2*int(num_edges))
735
736 # Step to beginning of file and skip header info
737 ifile.seek(0)
738 ifile.readline()
739 for i in range(int(num_vertices)):
740 print("vertex %g", i)
741 line = ifile.readline()
742 edges = line.split()
743 for e in edges:
744 xml_writer.write_graph_edge(ofile, i, int(e))
745
746 xml_writer.write_footer_edges(ofile)
747 xml_writer.write_footer_graph(ofile)
748
749 # Close files
750 ifile.close();
751 ofile.close();
752
753 def scotch_graph2graph_xml(ifilename, ofilename):
754 "Convert from Scotch graph format to DOLFIN Graph XML."
755
756 print("Converting from Scotch graph format to DOLFIN Graph XML.")
757
758 # Open files
759 ifile = open(ifilename, "r")
760 ofile = open(ofilename, "w")
761
762 # Skip graph file version number
763 ifile.readline()
764
765 # Read number of vertices and edges
766 line = ifile.readline()
767 if not line:
768 _error("Empty file")
769
770 (num_vertices, num_edges) = line.split()
771
772 # Read start index and numeric flag
773 # Start index is 0 or 1 (C/Fortran)
774 # Numeric flag is 3 bits where bit 1 enables vertex labels
775 # bit 2 enables edge weights and bit 3 enables vertex weights
776
777 line = ifile.readline()
778 (start_index, numeric_flag) = line.split()
779
780 # Handling not implented
781 if not numeric_flag == "000":
782 _error("Handling of scotch vertex labels, edge- and vertex weights not implemented")
783
784 xml_writer.write_header_graph(ofile, "undirected")
785 xml_writer.write_header_vertices(ofile, int(num_vertices))
786
787 # Read vertices and edges, first number gives number of edges from this vertex (not used)
788 for i in range(int(num_vertices)):
789 line = ifile.readline()
790 edges = line.split()
791 xml_writer.write_graph_vertex(ofile, i, len(edges)-1)
792
793 xml_writer.write_footer_vertices(ofile)
794 xml_writer.write_header_edges(ofile, int(num_edges))
795
796
797 # Step to beginning of file and skip header info
798 ifile.seek(0)
799 ifile.readline()
800 ifile.readline()
801 ifile.readline()
802 for i in range(int(num_vertices)):
803 line = ifile.readline()
804
805 edges = line.split()
806 for j in range(1, len(edges)):
807 xml_writer.write_graph_edge(ofile, i, int(edges[j]))
808
809 xml_writer.write_footer_edges(ofile)
810 xml_writer.write_footer_graph(ofile)
811
812 # Close files
813 ifile.close();
814 ofile.close();
815
816
817 def diffpack2xml(ifilename, ofilename):
818 "Convert from Diffpack tetrahedral/triangle grid format to DOLFIN XML."
819
820 print(diffpack2xml.__doc__)
821
822 # Format strings for MeshFunction XML files
823 meshfunction_header = """\
824 <?xml version="1.0" encoding="UTF-8"?>\n
825 <dolfin xmlns:dolfin="http://www.fenics.org/dolfin/">
826 <mesh_function type="uint" dim="%d" size="%d">\n"""
827 meshfunction_entity = " <entity index=\"%d\" value=\"%d\"/>\n"
828 meshfunction_footer = " </mesh_function>\n</dolfin>"
829
830 # Open files
831 ifile = open(ifilename, "r")
832 ofile = open(ofilename, "w")
833
834 # Read and analyze header
835 while 1:
836 line = ifile.readline()
837 if not line:
838 _error("Empty file")
839 if line[0] == "#":
840 break
841 if re.search(r"Number of elements", line):
842 num_cells = int(re.match(r".*\s(\d+).*", line).group(1))
843 if re.search(r"Number of nodes", line):
844 num_vertices = int(re.match(r".*\s(\d+).*", line).group(1))
845 if re.search(r"Number of space dim.", line):
846 num_dims = int(re.match(r".*\s(\d+).*", line).group(1))
847
848 if num_dims == 3:
849 xml_writer.write_header_mesh(ofile, "tetrahedron", 3)
850 elem_type = "ElmT4n3D"
851 write_cell_func = xml_writer.write_cell_tetrahedron
852 else:
853 xml_writer.write_header_mesh(ofile, "triangle", 2)
854 elem_type = "ElmT3n2D"
855 write_cell_func = xml_writer.write_cell_triangle
856
857 xml_writer.write_header_vertices(ofile, num_vertices)
858
859 # Read & write vertices and collect markers for vertices
860 vertex_markers = []
861 unique_vertex_markers = set()
862 for i in range(num_vertices):
863 line = ifile.readline()
864 m = re.match(r"^.*\(\s*(.*)\s*\).*\](.*)$", line)
865 x = list(map(float, re.split("[\s,]+", m.group(1))))
866 xml_writer.write_vertex(ofile, i, *x)
867 markers = list(map(int, m.group(2).split()))
868 vertex_markers.append(markers)
869 unique_vertex_markers.update(markers)
870
871 xml_writer.write_footer_vertices(ofile)
872 xml_writer.write_header_cells(ofile, num_cells)
873
874 # Output unique vertex markers as individual VertexFunctions
875 unique_vertex_markers.difference_update([0])
876 for unique_marker in unique_vertex_markers:
877 ofile_marker = open(ofilename.replace(".xml", "") + \
878 "_marker_" + str(unique_marker)+".xml", "w")
879 xml_writer.write_header_meshfunction(ofile_marker, 0, num_vertices)
880 for ind, markers in enumerate(vertex_markers):
881 if unique_marker in markers:
882 xml_writer.write_entity_meshfunction(ofile_marker, ind, unique_marker)
883 else:
884 xml_writer.write_entity_meshfunction(ofile_marker, ind, 0)
885 xml_writer.write_footer_meshfunction(ofile_marker)
886
887 # Ignore comment lines
888 while 1:
889 line = ifile.readline()
890 if not line:
891 _error("Empty file")
892 if line[0] == "#":
893 break
894
895 # Read & write cells and collect cell and face markers
896 cell_markers = []
897 facet_markers = []
898 facet_to_vert = [[1,2,3], [0,2,3], [0,1,3], [0,1,2]]
899 vert_to_facet = facet_to_vert # The same!
900
901 cell_ind = 0
902 while cell_ind < num_cells:
903 line = ifile.readline()
904 v = line.split()
905 if not v:
906 continue
907
908 if v[1] != elem_type:
909 _error("Only tetrahedral (ElmT4n3D) and triangular (ElmT3n2D) elements are implemented.")
910
911 # Store Cell markers
912 cell_markers.append(int(v[2]))
913
914 # Sort vertex indices
915 cell_indices = sorted([int(x)-1 for x in v[3:]])
916 write_cell_func(ofile, cell_ind, *cell_indices)
917
918 if num_dims == 2:
919 cell_ind += 1
920 continue
921
922 # Check Facet info
923 process_facet = set(range(4))
924 for local_vert_ind, global_vert_ind in enumerate(cell_indices):
925
926 # If no marker is included for vertex skip corresponding facet
927 if not vertex_markers[global_vert_ind]:
928 process_facet.difference_update(facet_to_vert[local_vert_ind])
929
930 # Process facets
931 for local_facet in process_facet:
932
933 # Start with markers from first vertex
934 global_first_vertex = cell_indices[facet_to_vert[local_facet][0]]
935 marker_intersection = set(vertex_markers[global_first_vertex])
936
937 # Process the other vertices
938 for local_vert in facet_to_vert[local_facet][1:]:
939 marker_intersection.intersection_update(\
940 vertex_markers[cell_indices[local_vert]])
941
942 if not marker_intersection:
943 break
944
945 # If not break we have a marker on local_facet
946 else:
947 assert(len(marker_intersection)==1)
948 facet_markers.append((cell_ind, local_facet, \
949 marker_intersection.pop()))
950 # Bump cell_ind
951 cell_ind += 1
952
953 xml_writer.write_footer_cells(ofile)
954 xml_writer.write_header_domains(ofile)
955
956 # Write facet markers if any
957 if facet_markers:
958 xml_writer.write_header_meshvaluecollection(ofile, "m", 2, \
959 len(facet_markers), "uint")
960 for cell, local_facet, marker in facet_markers:
961 xml_writer.write_entity_meshvaluecollection(ofile, 2, cell, \
962 marker, local_facet)
963 xml_writer.write_footer_meshvaluecollection(ofile)
964
965 xml_writer.write_header_meshvaluecollection(ofile, "m", num_dims, \
966 len(cell_markers), "uint")
967 for cell, marker in enumerate(cell_markers):
968 xml_writer.write_entity_meshvaluecollection(ofile, num_dims, cell, \
969 marker)
970 xml_writer.write_footer_meshvaluecollection(ofile)
971 xml_writer.write_footer_domains(ofile)
972 xml_writer.write_footer_mesh(ofile)
973
974 # Close files
975 ifile.close()
976 ofile.close()
977
978 class ParseError(Exception):
979 """ Error encountered in source file.
980 """
981
982 class DataHandler(object):
983 """ Baseclass for handlers of mesh data.
984
985 The actual handling of mesh data encountered in the source file is
986 delegated to a polymorfic object. Typically, the delegate will write the
987 data to XML.
988 @ivar _state: the state which the handler is in, one of State_*.
989 @ivar _cell_type: cell type in mesh. One of CellType_*.
990 @ivar _dim: mesh dimensions.
991 """
992 State_Invalid, State_Init, State_Vertices, State_Cells, \
993 State_MeshFunction, State_MeshValueCollection = list(range(6))
994 CellType_Tetrahedron, CellType_Triangle, CellType_Interval = list(range(3))
995
996 def __init__(self):
997 self._state = self.State_Invalid
998
999 def set_mesh_type(self, cell_type, dim):
1000 assert self._state == self.State_Invalid
1001 self._state = self.State_Init
1002 if cell_type == "tetrahedron":
1003 self._cell_type = self.CellType_Tetrahedron
1004 elif cell_type == "triangle":
1005 self._cell_type = self.CellType_Triangle
1006 elif cell_type == "interval":
1007 self._cell_type = self.CellType_Interval
1008 self._dim = dim
1009
1010 def start_vertices(self, num_vertices):
1011 assert self._state == self.State_Init
1012 self._state = self.State_Vertices
1013
1014 def add_vertex(self, vertex, coords):
1015 assert self._state == self.State_Vertices
1016
1017 def end_vertices(self):
1018 assert self._state == self.State_Vertices
1019 self._state = self.State_Init
1020
1021 def start_cells(self, num_cells):
1022 assert self._state == self.State_Init
1023 self._state = self.State_Cells
1024
1025 def add_cell(self, cell, nodes):
1026 assert self._state == self.State_Cells
1027
1028 def end_cells(self):
1029 assert self._state == self.State_Cells
1030 self._state = self.State_Init
1031
1032 def start_domains(self):
1033 assert self._state == self.State_Init
1034
1035 def end_domains(self):
1036 self._state = self.State_Init
1037
1038 def start_meshfunction(self, name, dim, size):
1039 assert self._state == self.State_Init
1040 self._state = self.State_MeshFunction
1041
1042 def add_entity_meshfunction(self, index, value):
1043 assert self._state == self.State_MeshFunction
1044
1045 def end_meshfunction(self):
1046 assert self._state == self.State_MeshFunction
1047 self._state = self.State_Init
1048
1049 def start_mesh_value_collection(self, name, dim, size, etype):
1050 assert self._state == self.State_Init
1051 self._state = self.State_MeshValueCollection
1052
1053 def add_entity_mesh_value_collection(self, dim, index, value, local_entity=0):
1054 assert self._state == self.State_MeshValueCollection
1055
1056 def end_mesh_value_collection(self):
1057 assert self._state == self.State_MeshValueCollection
1058 self._state = self.State_Init
1059
1060 def warn(self, msg):
1061 """ Issue warning during parse.
1062 """
1063 warnings.warn(msg)
1064
1065 def error(self, msg):
1066 """ Raise error during parse.
1067
1068 This method is expected to raise ParseError.
1069 """
1070 raise ParseError(msg)
1071
1072 def close(self):
1073 self._state = self.State_Invalid
1074
1075 class XmlHandler(DataHandler):
1076 """ Data handler class which writes to Dolfin XML.
1077 """
1078 def __init__(self, ofilename):
1079 DataHandler.__init__(self)
1080 self._ofilename = ofilename
1081 self.__ofile = open(ofilename, "w")
1082 self.__ofile_meshfunc = None
1083
1084 def ofile(self):
1085 return self.__ofile
1086
1087 def set_mesh_type(self, cell_type, dim):
1088 DataHandler.set_mesh_type(self, cell_type, dim)
1089 xml_writer.write_header_mesh(self.__ofile, cell_type, dim)
1090
1091 def start_vertices(self, num_vertices):
1092 DataHandler.start_vertices(self, num_vertices)
1093 xml_writer.write_header_vertices(self.__ofile, num_vertices)
1094
1095 def add_vertex(self, vertex, coords):
1096 DataHandler.add_vertex(self, vertex, coords)
1097 xml_writer.write_vertex(self.__ofile, vertex, *coords)
1098
1099 def end_vertices(self):
1100 DataHandler.end_vertices(self)
1101 xml_writer.write_footer_vertices(self.__ofile)
1102
1103 def start_cells(self, num_cells):
1104 DataHandler.start_cells(self, num_cells)
1105 xml_writer.write_header_cells(self.__ofile, num_cells)
1106
1107 def add_cell(self, cell, nodes):
1108 DataHandler.add_cell(self, cell, nodes)
1109 if self._cell_type == self.CellType_Tetrahedron:
1110 func = xml_writer.write_cell_tetrahedron
1111 elif self._cell_type == self.CellType_Triangle:
1112 func = xml_writer.write_cell_triangle
1113 elif self._cell_type == self.CellType_Interval:
1114 func = xml_writer.write_cell_interval
1115
1116 func(self.__ofile, cell, *nodes)
1117
1118 def end_cells(self):
1119 DataHandler.end_cells(self)
1120 xml_writer.write_footer_cells(self.__ofile)
1121
1122 def start_meshfunction(self, name, dim, size):
1123 DataHandler.start_meshfunction(self, name, dim, size)
1124 fname = os.path.splitext(self.__ofile.name)[0]
1125 self.__ofile_meshfunc = open("%s_%s.xml" % (fname, name), "w")
1126 xml_writer.write_header_meshfunction(self.__ofile_meshfunc, dim, size)
1127
1128 def add_entity_meshfunction(self, index, value):
1129 DataHandler.add_entity_meshfunction(self, index, value)
1130 xml_writer.write_entity_meshfunction(self.__ofile_meshfunc, index, value)
1131
1132 def end_meshfunction(self):
1133 DataHandler.end_meshfunction(self)
1134 xml_writer.write_footer_meshfunction(self.__ofile_meshfunc)
1135 self.__ofile_meshfunc.close()
1136 self.__ofile_meshfunc = None
1137
1138 def start_domains(self):
1139 #DataHandler.start_domains(self)
1140 xml_writer.write_header_domains(self.__ofile)
1141
1142 def end_domains(self):
1143 #DataHandler.end_domains(self)
1144 xml_writer.write_footer_domains(self.__ofile)
1145
1146 def start_mesh_value_collection(self, name, dim, size, etype):
1147 DataHandler.start_mesh_value_collection(self, name, dim, size, etype)
1148 xml_writer.write_header_meshvaluecollection(self.__ofile, name, dim, size, etype)
1149
1150 def add_entity_mesh_value_collection(self, dim, index, value, local_entity=0):
1151 DataHandler.add_entity_mesh_value_collection(self, dim, index, value)
1152 xml_writer.write_entity_meshvaluecollection(self.__ofile, dim, index, value, local_entity=local_entity)
1153
1154 def end_mesh_value_collection(self):
1155 DataHandler.end_mesh_value_collection(self)
1156 xml_writer.write_footer_meshvaluecollection(self.__ofile)
1157
1158 def close(self):
1159 DataHandler.close(self)
1160 if self.__ofile.closed:
1161 return
1162 xml_writer.write_footer_mesh(self.__ofile)
1163 self.__ofile.close()
1164 if self.__ofile_meshfunc is not None:
1165 self.__ofile_meshfunc.close()
1166
1167
1168 def netcdf2xml(ifilename,ofilename):
1169 "Convert from NetCDF format to DOLFIN XML."
1170
1171 print("Converting from NetCDF format (.ncdf) to DOLFIN XML format")
1172
1173 # Open files
1174 ifile = open(ifilename, "r")
1175 ofile = open(ofilename, "w")
1176
1177
1178 cell_type = None
1179 dim = 0
1180
1181 # Scan file for dimension, number of nodes, number of elements
1182 while 1:
1183 line = ifile.readline()
1184 if not line:
1185 _error("Empty file")
1186 if re.search(r"num_dim.*=", line):
1187 dim = int(re.match(".*\s=\s(\d+)\s;",line).group(1))
1188 if re.search(r"num_nodes.*=", line):
1189 num_vertices = int(re.match(".*\s=\s(\d+)\s;",line).group(1))
1190 if re.search(r"num_elem.*=", line):
1191 num_cells = int(re.match(".*\s=\s(\d+)\s;",line).group(1))
1192 if re.search(r"connect1 =",line):
1193 break
1194
1195 num_dims=dim
1196
1197 # Set cell type
1198 if dim == 2:
1199 cell_type = "triangle"
1200 if dim == 3:
1201 cell_type = "tetrahedron"
1202
1203 # Check that we got the cell type
1204 if cell_type == None:
1205 _error("Unable to find cell type.")
1206
1207 # Write header
1208 xml_writer.write_header_mesh(ofile, cell_type, dim)
1209 xml_writer.write_header_cells(ofile, num_cells)
1210 num_cells_read = 0
1211
1212 # Read and write cells
1213 while 1:
1214 # Read next line
1215 line = ifile.readline()
1216 if not line:
1217 break
1218 connect=re.split("[,;]",line)
1219 if num_dims == 2:
1220 n0 = int(connect[0])-1
1221 n1 = int(connect[1])-1
1222 n2 = int(connect[2])-1
1223 xml_writer.write_cell_triangle(ofile, num_cells_read, n0, n1, n2)
1224 elif num_dims == 3:
1225 n0 = int(connect[0])-1
1226 n1 = int(connect[1])-1
1227 n2 = int(connect[2])-1
1228 n3 = int(connect[3])-1
1229 xml_writer.write_cell_tetrahedron(ofile, num_cells_read, n0, n1, n2, n3)
1230 num_cells_read +=1
1231 if num_cells == num_cells_read:
1232 xml_writer.write_footer_cells(ofile)
1233 xml_writer.write_header_vertices(ofile, num_vertices)
1234 break
1235
1236 num_vertices_read = 0
1237 coords = [[],[],[]]
1238 coord = -1
1239
1240 while 1:
1241 line = ifile.readline()
1242 if not line:
1243 _error("Missing data")
1244 if re.search(r"coord =",line):
1245 break
1246
1247 # Read vertices
1248 while 1:
1249 line = ifile.readline()
1250 if not line:
1251 break
1252 if re.search(r"\A\s\s\S+,",line):
1253 coord+=1
1254 print("Found x_"+str(coord)+" coordinates")
1255 coords[coord] += line.split()
1256 if re.search(r";",line):
1257 break
1258
1259 # Write vertices
1260 for i in range(num_vertices):
1261 if num_dims == 2:
1262 x = float(re.split(",",coords[0].pop(0))[0])
1263 y = float(re.split(",",coords[1].pop(0))[0])
1264 z = 0
1265 if num_dims == 3:
1266 x = float(re.split(",",coords[0].pop(0))[0])
1267 y = float(re.split(",",coords[1].pop(0))[0])
1268 z = float(re.split(",",coords[2].pop(0))[0])
1269 xml_writer.write_vertex(ofile, i, x, y, z)
1270
1271
1272 # Write footer
1273 xml_writer.write_footer_vertices(ofile)
1274 xml_writer.write_footer_mesh(ofile)
1275
1276 # Close files
1277 ifile.close()
1278 ofile.close()
1279
1280 def exodus2xml(ifilename,ofilename):
1281 "Convert from Exodus II format to DOLFIN XML."
1282
1283 print("Converting from Exodus II format to NetCDF format")
1284
1285 name = ifilename.split(".")[0]
1286 netcdffilename = name +".ncdf"
1287 subprocess.run(['ncdump', ifilename, ' > ', netcdffilename], check=True)
1288 netcdf2xml(netcdffilename, ofilename)
1289
1290
1291 def _error(message):
1292 "Write an error message"
1293 for line in message.split("\n"):
1294 print("*** %s" % line)
1295 sys.exit(2)
1296
1297 def convert2xml(ifilename, ofilename, iformat=None):
1298 """Convert a file to the DOLFIN XML format.
1299
1300 """
1301 convert(ifilename, XmlHandler(ofilename), iformat=iformat)
1302
1303 def convert(ifilename, handler, iformat=None):
1304 """ Convert a file using a provided data handler.
1305
1306 Note that handler.close is called when this function finishes.
1307 @param ifilename: Name of input file.
1308 @param handler: The data handler (instance of L{DataHandler}).
1309 @param iformat: Format of input file.
1310 """
1311 if iformat is None:
1312 iformat = format_from_suffix(os.path.splitext(ifilename)[1][1:])
1313 # XXX: Backwards-compat
1314 if hasattr(handler, "_ofilename"):
1315 ofilename = handler._ofilename
1316 # Choose conversion
1317 if iformat == "mesh":
1318 # Convert from mesh to xml format
1319 mesh2xml(ifilename, ofilename)
1320 elif iformat == "gmsh":
1321 # Convert from gmsh to xml format
1322 gmsh2xml(ifilename, handler)
1323 elif iformat == "Triangle":
1324 # Convert from Triangle to xml format
1325 triangle2xml(ifilename, ofilename)
1326 elif iformat == "xml-old":
1327 # Convert from old to new xml format
1328 xml_old2xml(ifilename, ofilename)
1329 elif iformat == "metis":
1330 # Convert from metis graph to dolfin graph xml format
1331 metis_graph2graph_xml(ifilename, ofilename)
1332 elif iformat == "scotch":
1333 # Convert from scotch graph to dolfin graph xml format
1334 scotch_graph2graph_xml(ifilename, ofilename)
1335 elif iformat == "diffpack":
1336 # Convert from Diffpack tetrahedral grid format to xml format
1337 diffpack2xml(ifilename, ofilename)
1338 elif iformat == "abaqus":
1339 # Convert from abaqus to xml format
1340 abaqus.convert(ifilename, handler)
1341 elif iformat == "NetCDF":
1342 # Convert from NetCDF generated from ExodusII format to xml format
1343 netcdf2xml(ifilename, ofilename)
1344 elif iformat =="ExodusII":
1345 # Convert from ExodusII format to xml format via NetCDF
1346 exodus2xml(ifilename, ofilename)
1347 elif iformat == "StarCD":
1348 # Convert from Star-CD tetrahedral grid format to xml format
1349 starcd2xml(ifilename, ofilename)
1350 else:
1351 _error("Sorry, cannot convert between %s and DOLFIN xml file formats." % iformat)
1352
1353 # XXX: handler.close messes things for other input formats than abaqus or gmsh
1354 if iformat in ("abaqus", "gmsh"):
1355 handler.close()
1356
1357 def starcd2xml(ifilename, ofilename):
1358 "Convert from Star-CD tetrahedral grid format to DOLFIN XML."
1359
1360 print(starcd2xml.__doc__)
1361
1362 if not os.path.isfile(ifilename[:-3] + "vrt") or not os.path.isfile(ifilename[:-3] + "cel"):
1363 print("StarCD format requires one .vrt file and one .cel file")
1364 sys.exit(2)
1365
1366
1367 # open output file
1368 ofile = open(ofilename, "w")
1369
1370 # Open file, the vertices are in a .vrt file
1371 ifile = open(ifilename[:-3] + "vrt", "r")
1372
1373 write_header_mesh(ofile, "tetrahedron", 3)
1374
1375 # Read & write vertices
1376
1377 # first, read all lines (need to sweep to times through the file)
1378 lines = ifile.readlines()
1379
1380 # second, find the number of vertices
1381 num_vertices = -1
1382 counter = 0
1383 # nodenr_map is needed because starcd support node numbering like 1,2,4 (ie 3 is missing)
1384 nodenr_map = {}
1385 for line in lines:
1386 nodenr = int(line[0:15])
1387 nodenr_map[nodenr] = counter
1388 counter += 1
1389 num_vertices = counter
1390
1391 # third, run over all vertices
1392 xml_writer.write_header_vertices(ofile, num_vertices)
1393 for line in lines:
1394 nodenr = int(line[0:15])
1395 vertex0 = float(line[15:31])
1396 vertex1 = float(line[31:47])
1397 vertex2 = float(line[47:63])
1398 xml_writer.write_vertex(ofile, nodenr_map[nodenr], float(vertex0), float(vertex1), float(vertex2))
1399 xml_writer.write_footer_vertices(ofile)
1400
1401 # Open file, the cells are in a .cel file
1402 ifile = open(ifilename[:-3] + "cel", "r")
1403
1404 # Read & write cells
1405
1406 # first, read all lines (need to sweep to times through the file)
1407 lines = ifile.readlines()
1408
1409 # second, find the number of cells
1410 num_cells = -1
1411 counter = 0
1412 for line in lines:
1413 l = [int(a) for a in line.split()]
1414 cellnr, node0, node1, node2, node3, node4, node5, node6, node7, tmp1, tmp2 = l
1415 if node4 > 0:
1416 if node2 == node3 and node4 == node5 and node5 == node6 and node6 == node7: # these nodes should be equal
1417 counter += 1
1418 else:
1419 print("The file does contain cells that are not tetraheders. The cell number is ", cellnr, " the line read was ", line)
1420 else:
1421 # triangles on the surface
1422 # print "The file does contain cells that are not tetraheders node4==0. The cell number is ", cellnr, " the line read was ", line
1423 #sys.exit(2)
1424 pass
1425
1426 num_cells = counter
1427
1428 # third, run over all cells
1429 xml_writer.write_header_cells(ofile, num_cells)
1430 counter = 0
1431 for line in lines:
1432 l = [int(a) for a in line.split()]
1433 cellnr, node0, node1, node2, node3, node4, node5, node6, node7, tmp1, tmp2 = l
1434 if (node4 > 0):
1435 if node2 == node3 and node4 == node5 and node5 == node6 and node6 == node7: # these nodes should be equal
1436
1437 xml_writer.write_cell_tetrahedron(ofile, counter, nodenr_map[node0], nodenr_map[node1], nodenr_map[node2], nodenr_map[node4])
1438 counter += 1
1439
1440 xml_writer.write_footer_cells(ofile)
1441 xml_writer.write_footer_mesh(ofile)
1442
1443 # Close files
1444 ifile.close()
1445 ofile.close()