forked from nschloe/meshio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dolfin_io.py
260 lines (212 loc) · 7.59 KB
/
dolfin_io.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# -*- coding: utf-8 -*-
#
'''
I/O for DOLFIN's XML format, cf.
<https://people.sc.fsu.edu/~jburkardt/data/dolfin_xml/dolfin_xml.html>.
.. moduleauthor:: Nico Schlömer <nico.schloemer@gmail.com>
'''
import logging
import os
import re
import numpy
def _read_mesh(filename):
from lxml import etree as ET
dolfin_to_meshio_type = {
'triangle': ('triangle', 3),
'tetrahedron': ('tetra', 4),
}
# Use iterparse() to avoid loading the entire file via parse(). iterparse()
# allows to discard elements (via clear()) after they have been processed.
# See <https://stackoverflow.com/a/326541/353337>.
for event, elem in ET.iterparse(filename, events=('start', 'end')):
if event == 'end':
continue
if elem.tag == 'dolfin':
# Don't be too strict with the assertion. Some meshe files don't
# have the proper tags.
# assert elem.attrib['nsmap'] \
# == '{\'dolfin\': \'https://fenicsproject.org/\'}'
pass
elif elem.tag == 'mesh':
dim = int(elem.attrib['dim'])
cell_type, npc = dolfin_to_meshio_type[elem.attrib['celltype']]
cell_tags = ['v{}'.format(i) for i in range(npc)]
elif elem.tag == 'vertices':
points = numpy.empty((int(elem.attrib['size']), 3))
keys = ['x', 'y']
if dim == 2:
points[:, 2] = 0.0
else:
assert dim == 3
keys += ['z']
elif elem.tag == 'vertex':
k = int(elem.attrib['index'])
points[k][:dim] = [elem.attrib[key] for key in keys]
elif elem.tag == 'cells':
cells = {
cell_type:
numpy.empty((int(elem.attrib['size']), npc), dtype=int)
}
elif elem.tag in ['triangle', 'tetrahedron']:
k = int(elem.attrib['index'])
cells[cell_type][k] = [elem.attrib[t] for t in cell_tags]
else:
logging.warning('Unknown entry %s. Ignoring.', elem.tag)
elem.clear()
return points, cells, cell_type
def _read_cell_data(filename, cell_type):
from lxml import etree as ET
dolfin_type_to_numpy_type = {
'int': numpy.dtype('int'),
'float': numpy.dtype('float'),
'uint': numpy.dtype('uint'),
}
cell_data = {cell_type: {}}
dir_name = os.path.dirname(filename)
if not os.path.dirname(filename):
dir_name = os.getcwd()
# Loop over all files in the same directory as `filename`.
basename = os.path.splitext(os.path.basename(filename))[0]
for f in os.listdir(dir_name):
# Check if there are files by the name "<filename>_*.xml"; if yes,
# extract the * pattern and make it the name of the data set.
out = re.match('{}_([^\\.]+)\\.xml'.format(basename), f)
if not out:
continue
name = out.group(1)
parser = ET.XMLParser(remove_comments=True, huge_tree=True)
tree = ET.parse(os.path.join(dir_name, f), parser)
root = tree.getroot()
mesh_functions = list(root)
assert len(mesh_functions) == 1
mesh_function = mesh_functions[0]
assert mesh_function.tag == 'mesh_function'
size = int(mesh_function.attrib['size'])
dtype = dolfin_type_to_numpy_type[mesh_function.attrib['type']]
data = numpy.empty(size, dtype=dtype)
for child in mesh_function:
assert child.tag == 'entity'
idx = int(child.attrib['index'])
data[idx] = child.attrib['value']
cell_data[cell_type][name] = data
return cell_data
def read(filename):
points, cells, cell_type = _read_mesh(filename)
point_data = {}
cell_data = _read_cell_data(filename, cell_type)
field_data = {}
return points, cells, point_data, cell_data, field_data
def _write_mesh(filename, points, cell_type, cells):
from lxml import etree as ET
stripped_cells = {cell_type: cells[cell_type]}
dolfin = ET.Element(
'dolfin',
nsmap={'dolfin': 'https://fenicsproject.org/'}
)
meshio_to_dolfin_type = {
'triangle': 'triangle',
'tetra': 'tetrahedron',
}
if len(cells) > 1:
discarded_cells = list(cells.keys())
discarded_cells.remove(cell_type)
logging.warning(
'DOLFIN XML can only handle one cell type at a time. '
'Using %s, discarding %s.',
cell_type, ', '.join(discarded_cells)
)
dim = 2 if all(points[:, 2] == 0) else 3
mesh = ET.SubElement(
dolfin,
'mesh',
celltype=meshio_to_dolfin_type[cell_type],
dim=str(dim)
)
vertices = ET.SubElement(mesh, 'vertices', size=str(len(points)))
for k, point in enumerate(points):
ET.SubElement(
vertices,
'vertex',
index=str(k),
x=repr(point[0]),
y=repr(point[1]),
z=repr(point[2])
)
num_cells = 0
for cls in stripped_cells.values():
num_cells += len(cls)
xcells = ET.SubElement(mesh, 'cells', size=str(num_cells))
idx = 0
for ct, cls in stripped_cells.items():
for cell in cls:
cell_entry = ET.SubElement(
xcells,
meshio_to_dolfin_type[ct],
index=str(idx)
)
for k, c in enumerate(cell):
cell_entry.attrib['v{}'.format(k)] = str(c)
idx += 1
tree = ET.ElementTree(dolfin)
tree.write(filename, pretty_print=True)
return
def _numpy_type_to_dolfin_type(dtype):
types = {
'int': [numpy.int8, numpy.int16, numpy.int32, numpy.int64],
'uint': [numpy.uint8, numpy.uint16, numpy.uint32, numpy.uint64],
'float': [numpy.float16, numpy.float32, numpy.float64],
}
for key, numpy_types in types.items():
for numpy_type in numpy_types:
if numpy.issubdtype(dtype, numpy_type):
return key
assert False, 'Could not convert NumPy data type to DOLFIN data type.'
return None
def _write_cell_data(filename, dim, cell_data):
from lxml import etree as ET
dolfin = ET.Element(
'dolfin',
nsmap={'dolfin': 'https://fenicsproject.org/'}
)
mesh_function = ET.SubElement(
dolfin,
'mesh_function',
type=_numpy_type_to_dolfin_type(cell_data.dtype),
dim=str(dim),
size=str(len(cell_data))
)
for k, value in enumerate(cell_data):
ET.SubElement(
mesh_function,
'entity',
index=str(k),
value=repr(value),
)
tree = ET.ElementTree(dolfin)
tree.write(filename)
return
def write(filename,
points,
cells,
point_data=None,
cell_data=None,
field_data=None):
logging.warning(
'Dolfin\'s XML is a legacy format. Consider using XDMF instead.'
)
point_data = {} if point_data is None else point_data
cell_data = {} if cell_data is None else cell_data
field_data = {} if field_data is None else field_data
if 'tetra' in cells:
cell_type = 'tetra'
else:
assert 'triangle' in cells
cell_type = 'triangle'
_write_mesh(filename, points, cell_type, cells)
if cell_type in cell_data:
for key, data in cell_data[cell_type].items():
cell_data_filename = \
'{}_{}.xml'.format(os.path.splitext(filename)[0], key)
dim = 2 if all(points[:, 2] == 0) else 3
_write_cell_data(cell_data_filename, dim, numpy.array(data))
return