Coverage for ase/io/qbox.py: 96.67%
90 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1"""This module contains functions to read from QBox output files"""
3import re
4import xml.etree.ElementTree as ET
6from ase import Atom, Atoms
7from ase.calculators.singlepoint import SinglePointCalculator
8from ase.utils import reader
10# Compile regexs for fixing XML
11re_find_bad_xml = re.compile(r'<(/?)([A-z]+) expectation ([a-z]+)')
14@reader
15def read_qbox(f, index=-1):
16 """Read data from QBox output file
18 Inputs:
19 f - str or fileobj, path to file or file object to read from
20 index - int or slice, which frames to return
22 Returns
23 -------
24 list of Atoms or atoms, requested frame(s)
25 """
27 # Check whether this is a QB@all output
28 version = None
29 for line in f:
30 if '<release>' in line:
31 version = ET.fromstring(line)
32 break
33 if version is None:
34 raise Exception('Parse Error: Version not found')
35 is_qball = 'qb@LL' in version.text or 'qball' in version.text
37 # Load in atomic species
38 species = {}
39 if is_qball:
40 # Read all of the lines between release and the first call to `run`
41 species_data = []
42 for line in f:
43 if '<run' in line:
44 break
45 species_data.append(line)
46 species_data = '\n'.join(species_data)
48 # Read out the species information with regular expressions
49 symbols = re.findall('symbol_ = ([A-Z][a-z]?)', species_data)
50 masses = re.findall('mass_ = ([0-9.]+)', species_data)
51 names = re.findall('name_ = ([a-z]+)', species_data)
52 numbers = re.findall('atomic_number_ = ([0-9]+)', species_data)
54 # Compile them into a dictionary
55 for name, symbol, mass, number in zip(names, symbols, masses, numbers):
56 spec_data = dict(
57 symbol=symbol, mass=float(mass), number=float(number)
58 )
59 species[name] = spec_data
60 else:
61 # Find all species
62 species_blocks = _find_blocks(f, 'species', '<cmd>run')
64 for spec in species_blocks:
65 name = spec.get('name')
66 spec_data = dict(
67 symbol=spec.find('symbol').text,
68 mass=float(spec.find('mass').text),
69 number=int(spec.find('atomic_number').text),
70 )
71 species[name] = spec_data
73 # Find all of the frames
74 frames = _find_blocks(f, 'iteration', None)
76 # If index is an int, return one frame
77 if isinstance(index, int):
78 return _parse_frame(frames[index], species)
79 else:
80 return [_parse_frame(frame, species) for frame in frames[index]]
83def _find_blocks(fp, tag, stopwords='[qbox]'):
84 """Find and parse a certain block of the file.
86 Reads a file sequentially and stops when it either encounters the
87 end of the file, or until the it encounters a line that contains a
88 user-defined string *after it has already found at least one
89 desired block*. Use the stopwords ``[qbox]`` to read until the next
90 command is issued.
92 Groups the text between the first line that contains <tag> and the
93 next line that contains </tag>, inclusively. The function then
94 parses the XML and returns the Element object.
96 Inputs:
97 fp - file-like object, file to be read from
98 tag - str, tag to search for (e.g., 'iteration').
99 `None` if you want to read until the end of the file
100 stopwords - str, halt parsing if a line containing this string
101 is encountered
103 Returns
104 -------
105 list of xml.ElementTree, parsed XML blocks found by this class
106 """
108 start_tag = f'<{tag}'
109 end_tag = f'</{tag}>'
111 blocks = [] # Stores all blocks
112 cur_block = [] # Block being filled
113 in_block = False # Whether we are currently parsing
114 for line in fp:
115 # Check if the block has started
116 if start_tag in line:
117 if in_block:
118 raise Exception('Parsing failed: Encountered nested block')
119 else:
120 in_block = True
122 # Add data to block
123 if in_block:
124 cur_block.append(line)
126 # Check for stopping conditions
127 if stopwords is not None:
128 if stopwords in line and len(blocks) > 0:
129 break
131 if end_tag in line:
132 if in_block:
133 blocks.append(cur_block)
134 cur_block = []
135 in_block = False
136 else:
137 raise Exception(
138 'Parsing failed: End tag found before start tag'
139 )
141 # Join strings in a block into a single string
142 blocks = [''.join(b) for b in blocks]
144 # Ensure XML compatibility. There are two specific tags in QBall that are
145 # not valid XML, so we need to run a
146 blocks = [re_find_bad_xml.sub(r'<\1\2_expectation_\3', b) for b in blocks]
148 # Parse the blocks
149 return [ET.fromstring(b) for b in blocks]
152def _parse_frame(tree, species):
153 """Parse a certain frame from QBOX output
155 Inputs:
156 tree - ElementTree, <iteration> block from output file
157 species - dict, data about species. Key is name of atom type,
158 value is data about that type
159 Return:
160 Atoms object describing this iteration"""
162 # Load in data about the system
163 energy = float(tree.find('etotal').text)
165 # Load in data about the cell
166 unitcell = tree.find('atomset').find('unit_cell')
167 cell = []
168 for d in ['a', 'b', 'c']:
169 cell.append([float(x) for x in unitcell.get(d).split()])
171 stress_tree = tree.find('stress_tensor')
172 if stress_tree is None:
173 stresses = None
174 else:
175 stresses = [
176 float(stress_tree.find(f'sigma_{x}').text)
177 for x in ['xx', 'yy', 'zz', 'yz', 'xz', 'xy']
178 ]
180 # Create the Atoms object
181 atoms = Atoms(pbc=True, cell=cell)
183 # Load in the atom information
184 forces = []
185 for atom in tree.find('atomset').findall('atom'):
186 # Load data about the atom type
187 spec = atom.get('species')
188 symbol = species[spec]['symbol']
189 mass = species[spec]['mass']
191 # Get data about position / velocity / force
192 pos = [float(x) for x in atom.find('position').text.split()]
193 force = [float(x) for x in atom.find('force').text.split()]
194 momentum = [float(x) * mass for x in atom.find('velocity').text.split()]
196 # Create the objects
197 atom = Atom(symbol=symbol, mass=mass, position=pos, momentum=momentum)
198 atoms += atom
199 forces.append(force)
201 # Create the calculator object that holds energy/forces
202 calc = SinglePointCalculator(
203 atoms, energy=energy, forces=forces, stress=stresses
204 )
205 atoms.calc = calc
207 return atoms