Skip to content

Instantly share code, notes, and snippets.

@pastewka
Last active September 3, 2019 08:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pastewka/5eb680399e5feed7ae3954193084e784 to your computer and use it in GitHub Desktop.
Save pastewka/5eb680399e5feed7ae3954193084e784 to your computer and use it in GitHub Desktop.
Simple XDMF reader
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
# FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import xml.etree.ElementTree as ET
import numpy as np
###
def read_xml(fn):
"""Read XDMF XML descriptor file."""
tree = ET.parse(fn)
root = tree.getroot()
grid = root[0][0]
frames = []
for frame in grid:
frame_dict = {}
frame_dict['_id'] = int(frame.attrib['Name'])
for entry in frame:
if entry.tag == 'Time':
frame_dict['_time'] = float(entry.attrib['Value'])
elif entry.tag == 'Attribute':
data_dict = {}
for data in entry:
data_dict['shape'] = tuple(int(dim) for dim in data.attrib['Dimensions'].split())
for raw_data in data:
shape = tuple(int(dim) for dim in raw_data.attrib['Dimensions'].split())
assert shape == data_dict['shape']
assert raw_data.attrib['Format'] == 'Binary'
data_dict['type'] = '<f'+raw_data.attrib['Precision']
data_dict['seek'] = int(raw_data.attrib['Seek'])
data_dict['filename'] = raw_data.text.strip()
frame_dict[entry.attrib['Name']] = data_dict
frames += [frame_dict]
return frames
def read_frame(frame):
"""Read a single data frame."""
data = {}
for key, descr in frame.items():
if not key.startswith('_'):
with open(descr['filename'], 'rb') as f:
f.seek(descr['seek'])
data[key] = np.fromfile(f, dtype=np.dtype(descr['type']),
count=np.prod(descr['shape'])).reshape(descr['shape'])
return data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment