Coverage for ase/io/mustem.py: 95.41%
109 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"""Module to read and write atoms in xtl file format for the muSTEM software.
3See http://tcmp.ph.unimelb.edu.au/mustem/muSTEM.html for a few examples of
4this format and the documentation of muSTEM.
6See https://github.com/HamishGBrown/MuSTEM for the source code of muSTEM.
7"""
9import numpy as np
11from ase.atoms import Atoms, symbols2numbers
12from ase.data import chemical_symbols
13from ase.utils import reader, writer
15from .utils import verify_cell_for_export, verify_dictionary
18@reader
19def read_mustem(fd):
20 r"""Import muSTEM input file.
22 Reads cell, atom positions, etc. from muSTEM xtl file.
23 The mustem xtl save the root mean square (RMS) displacement, which is
24 convert to Debye-Waller (in Ų) factor by:
26 .. math::
28 B = RMS * 8\pi^2
30 """
31 from ase.geometry import cellpar_to_cell
33 # Read comment:
34 fd.readline()
36 # Parse unit cell parameter
37 cellpar = [float(i) for i in fd.readline().split()[:3]]
38 cell = cellpar_to_cell(cellpar)
40 # beam energy
41 fd.readline()
43 # Number of different type of atoms
44 element_number = int(fd.readline().strip())
46 # List of numpy arrays:
47 # length of the list = number of different atom type (element_number)
48 # length of each array = number of atoms for each atom type
49 atomic_numbers = []
50 positions = []
51 debye_waller_factors = []
52 occupancies = []
54 for _ in range(element_number):
55 # Read the element
56 _ = fd.readline()
57 line = fd.readline().split()
58 atoms_number = int(line[0])
59 atomic_number = int(line[1])
60 occupancy = float(line[2])
61 DW = float(line[3]) * 8 * np.pi**2
62 # read all the position for each element
63 positions.append(np.genfromtxt(fname=fd, max_rows=atoms_number))
64 atomic_numbers.append(np.ones(atoms_number, dtype=int) * atomic_number)
65 occupancies.append(np.ones(atoms_number) * occupancy)
66 debye_waller_factors.append(np.ones(atoms_number) * DW)
68 positions = np.vstack(positions)
70 atoms = Atoms(cell=cell, scaled_positions=positions)
71 atoms.set_atomic_numbers(np.hstack(atomic_numbers))
72 atoms.set_array('occupancies', np.hstack(occupancies))
73 atoms.set_array('debye_waller_factors', np.hstack(debye_waller_factors))
75 return atoms
78class XtlmuSTEMWriter:
79 """See the docstring of the `write_mustem` function."""
81 def __init__(
82 self,
83 atoms,
84 keV,
85 debye_waller_factors=None,
86 comment=None,
87 occupancies=None,
88 fit_cell_to_atoms=False,
89 ):
90 verify_cell_for_export(atoms.get_cell())
92 self.atoms = atoms.copy()
93 self.atom_types = sorted(set(atoms.symbols))
94 self.keV = keV
95 self.comment = comment
96 self.occupancies = self._get_occupancies(occupancies)
97 self.RMS = self._get_RMS(debye_waller_factors)
99 self.numbers = symbols2numbers(self.atom_types)
100 if fit_cell_to_atoms:
101 self.atoms.translate(-self.atoms.positions.min(axis=0))
102 self.atoms.set_cell(self.atoms.positions.max(axis=0))
104 def _get_occupancies(self, occupancies):
105 if occupancies is None:
106 if 'occupancies' in self.atoms.arrays:
107 occupancies = {
108 element: self._parse_array_from_atoms(
109 'occupancies', element, True
110 )
111 for element in self.atom_types
112 }
113 else:
114 occupancies = 1.0
115 if np.isscalar(occupancies):
116 occupancies = {atom: occupancies for atom in self.atom_types}
117 elif isinstance(occupancies, dict):
118 verify_dictionary(self.atoms, occupancies, 'occupancies')
120 return occupancies
122 def _get_RMS(self, DW):
123 if DW is None:
124 if 'debye_waller_factors' in self.atoms.arrays:
125 DW = {
126 element: self._parse_array_from_atoms(
127 'debye_waller_factors', element, True
128 )
129 / (8 * np.pi**2)
130 for element in self.atom_types
131 }
132 elif np.isscalar(DW):
133 if len(self.atom_types) > 1:
134 raise ValueError(
135 'This cell contains more then one type of '
136 'atoms and the Debye-Waller factor needs to '
137 'be provided for each atom using a '
138 'dictionary.'
139 )
140 DW = {self.atom_types[0]: DW / (8 * np.pi**2)}
141 elif isinstance(DW, dict):
142 verify_dictionary(self.atoms, DW, 'debye_waller_factors')
143 for key, value in DW.items():
144 DW[key] = value / (8 * np.pi**2)
146 if DW is None:
147 raise ValueError(
148 'Missing Debye-Waller factors. It can be '
149 'provided as a dictionary with symbols as key or '
150 'if the cell contains only a single type of '
151 'element, the Debye-Waller factor can also be '
152 'provided as float.'
153 )
155 return DW
157 def _parse_array_from_atoms(self, name, element, check_same_value):
158 """
159 Return the array "name" for the given element.
161 Parameters
162 ----------
163 name : str
164 The name of the arrays. Can be any key of `atoms.arrays`
165 element : str, int
166 The element to be considered.
167 check_same_value : bool
168 Check if all values are the same in the array. Necessary for
169 'occupancies' and 'debye_waller_factors' arrays.
171 Returns
172 -------
173 array containing the values corresponding defined by "name" for the
174 given element. If check_same_value, return a single element.
176 """
177 if isinstance(element, str):
178 element = symbols2numbers(element)[0]
179 sliced_array = self.atoms.arrays[name][self.atoms.numbers == element]
181 if check_same_value:
182 # to write the occupancies and the Debye Waller factor of xtl file
183 # all the value must be equal
184 if np.unique(sliced_array).size > 1:
185 raise ValueError(
186 "All the '{}' values for element '{}' must be "
187 'equal.'.format(name, chemical_symbols[element])
188 )
189 sliced_array = sliced_array[0]
191 return sliced_array
193 def _get_position_array_single_atom_type(self, number):
194 # Get the scaled (reduced) position for a single atom type
195 return self.atoms.get_scaled_positions()[self.atoms.numbers == number]
197 def _get_file_header(self):
198 # 1st line: comment line
199 if self.comment is None:
200 s = '{} atoms with chemical formula: {}\n'.format(
201 len(self.atoms), self.atoms.get_chemical_formula()
202 )
203 else:
204 s = self.comment
205 # 2nd line: lattice parameter
206 s += '{} {} {} {} {} {}\n'.format(*self.atoms.cell.cellpar().tolist())
207 # 3td line: acceleration voltage
208 s += f'{self.keV}\n'
209 # 4th line: number of different atom
210 s += f'{len(self.atom_types)}\n'
211 return s
213 def _get_element_header(
214 self, atom_type, number, atom_type_number, occupancy, RMS
215 ):
216 return '{}\n{} {} {} {:.3g}\n'.format(
217 atom_type, number, atom_type_number, occupancy, RMS
218 )
220 def _get_file_end(self):
221 return 'Orientation\n 1 0 0\n 0 1 0\n 0 0 1\n'
223 def write_to_file(self, fd):
224 if isinstance(fd, str):
225 fd = open(fd, 'w')
227 fd.write(self._get_file_header())
228 for atom_type, number, occupancy in zip(
229 self.atom_types, self.numbers, self.occupancies
230 ):
231 positions = self._get_position_array_single_atom_type(number)
232 atom_type_number = positions.shape[0]
233 fd.write(
234 self._get_element_header(
235 atom_type,
236 atom_type_number,
237 number,
238 self.occupancies[atom_type],
239 self.RMS[atom_type],
240 )
241 )
242 np.savetxt(fname=fd, X=positions, fmt='%.6g', newline='\n')
244 fd.write(self._get_file_end())
247@writer
248def write_mustem(fd, *args, **kwargs):
249 r"""Write muSTEM input file.
251 Parameters
252 ----------
254 atoms: Atoms object
256 keV: float
257 Energy of the electron beam in keV required for the image simulation.
259 debye_waller_factors: float or dictionary of float with atom type as key
260 Debye-Waller factor of each atoms. Since the prismatic/computem
261 software use root means square RMS) displacements, the Debye-Waller
262 factors (B) needs to be provided in Ų and these values are converted
263 to RMS displacement by:
265 .. math::
267 RMS = \frac{B}{8\pi^2}
269 occupancies: float or dictionary of float with atom type as key (optional)
270 Occupancy of each atoms. Default value is `1.0`.
272 comment: str (optional)
273 Comments to be written in the first line of the file. If not
274 provided, write the total number of atoms and the chemical formula.
276 fit_cell_to_atoms: bool (optional)
277 If `True`, fit the cell to the atoms positions. If negative coordinates
278 are present in the cell, the atoms are translated, so that all
279 positions are positive. If `False` (default), the atoms positions and
280 the cell are unchanged.
281 """
282 writer = XtlmuSTEMWriter(*args, **kwargs)
283 writer.write_to_file(fd)