Coverage for ase/io/gpumd.py: 90.68%
118 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
1import numpy as np
3from ase import Atoms
4from ase.data import atomic_masses, chemical_symbols
5from ase.neighborlist import NeighborList
8def find_nearest_index(array, value):
9 array = np.asarray(array)
10 idx = (np.abs(array - value)).argmin()
11 return idx
14def find_nearest_value(array, value):
15 array = np.asarray(array)
16 idx = (np.abs(array - value)).argmin()
17 return array[idx]
20def write_gpumd(
21 fd,
22 atoms,
23 maximum_neighbors=None,
24 cutoff=None,
25 groupings=None,
26 use_triclinic=False,
27 species=None,
28):
29 """
30 Writes atoms into GPUMD input format.
32 Parameters
33 ----------
34 fd : file
35 File like object to which the atoms object should be written
36 atoms : Atoms
37 Input structure
38 maximum_neighbors: int
39 Maximum number of neighbors any atom can ever have (not relevant when
40 using force constant potentials)
41 cutoff: float
42 Initial cutoff distance used for building the neighbor list (not
43 relevant when using force constant potentials)
44 groupings : list[list[list[int]]]
45 Groups into which the individual atoms should be divided in the form of
46 a list of list of lists. Specifically, the outer list corresponds to
47 the grouping methods, of which there can be three at the most, which
48 contains a list of groups in the form of lists of site indices. The
49 sum of the lengths of the latter must be the same as the total number
50 of atoms.
51 use_triclinic: bool
52 Use format for triclinic cells
53 species : List[str]
54 GPUMD uses integers to define atom types. This list allows customized
55 such definitions (e.g, ['Pd', 'H'] means Pd is type 0 and H type 1).
56 If None, this list is built by assigning each distinct species to
57 an integer in the order of appearance in `atoms`.
59 Raises
60 ------
61 ValueError
62 Raised if parameters are incompatible
63 """
65 # Check velocties parameter
66 if atoms.get_velocities() is None:
67 has_velocity = 0
68 else:
69 has_velocity = 1
70 velocities = atoms.get_velocities()
72 # Check groupings parameter
73 if groupings is None:
74 number_of_grouping_methods = 0
75 else:
76 number_of_grouping_methods = len(groupings)
77 if number_of_grouping_methods > 3:
78 raise ValueError('There can be no more than 3 grouping methods!')
79 for g, grouping in enumerate(groupings):
80 all_indices = [i for group in grouping for i in group]
81 if len(all_indices) != len(atoms) or set(all_indices) != set(
82 range(len(atoms))
83 ):
84 raise ValueError(
85 'The indices listed in grouping method {} are'
86 ' not compatible with the input'
87 ' structure!'.format(g)
88 )
90 # If not specified, estimate the maximum_neighbors
91 if maximum_neighbors is None:
92 if cutoff is None:
93 cutoff = 0.1
94 maximum_neighbors = 1
95 else:
96 nl = NeighborList([cutoff / 2] * len(atoms), skin=2, bothways=True)
97 nl.update(atoms)
98 maximum_neighbors = 0
99 for atom in atoms:
100 maximum_neighbors = max(
101 maximum_neighbors, len(nl.get_neighbors(atom.index)[0])
102 )
103 maximum_neighbors *= 2
104 maximum_neighbors = min(maximum_neighbors, 1024)
106 # Add header and cell parameters
107 lines = []
108 if atoms.cell.orthorhombic and not use_triclinic:
109 triclinic = 0
110 else:
111 triclinic = 1
112 lines.append(
113 '{} {} {} {} {} {}'.format(
114 len(atoms),
115 maximum_neighbors,
116 cutoff,
117 triclinic,
118 has_velocity,
119 number_of_grouping_methods,
120 )
121 )
122 if triclinic:
123 lines.append(
124 (' {}' * 12)[1:].format(
125 *atoms.pbc.astype(int), *atoms.cell[:].flatten()
126 )
127 )
128 else:
129 lines.append(
130 (' {}' * 6)[1:].format(
131 *atoms.pbc.astype(int), *atoms.cell.lengths()
132 )
133 )
135 # Create symbols-to-type map, i.e. integers starting at 0
136 if not species:
137 symbol_type_map = {}
138 for symbol in atoms.get_chemical_symbols():
139 if symbol not in symbol_type_map:
140 symbol_type_map[symbol] = len(symbol_type_map)
141 else:
142 if any(sym not in species for sym in set(atoms.get_chemical_symbols())):
143 raise ValueError(
144 'The species list does not contain all chemical '
145 'species that are present in the atoms object.'
146 )
147 else:
148 symbol_type_map = {symbol: i for i, symbol in enumerate(species)}
150 # Add lines for all atoms
151 for a, atm in enumerate(atoms):
152 t = symbol_type_map[atm.symbol]
153 line = (' {}' * 5)[1:].format(t, *atm.position, atm.mass)
154 if has_velocity:
155 line += (' {}' * 3).format(*velocities[a])
156 if groupings is not None:
157 for grouping in groupings:
158 for i, group in enumerate(grouping):
159 if a in group:
160 line += f' {i}'
161 break
162 lines.append(line)
164 # Write file
165 fd.write('\n'.join(lines))
168def load_xyz_input_gpumd(fd, species=None, isotope_masses=None):
169 """
170 Read the structure input file for GPUMD and return an ase Atoms object
171 togehter with a dictionary with parameters and a types-to-symbols map
173 Parameters
174 ----------
175 fd : file | str
176 File object or name of file from which to read the Atoms object
177 species : List[str]
178 List with the chemical symbols that correspond to each type, will take
179 precedence over isotope_masses
180 isotope_masses: Dict[str, List[float]]
181 Dictionary with chemical symbols and lists of the associated atomic
182 masses, which is used to identify the chemical symbols that correspond
183 to the types not found in species_types. The default is to find the
184 closest match :data:`ase.data.atomic_masses`.
186 Returns
187 -------
188 atoms : Atoms
189 Atoms object
190 input_parameters : Dict[str, int]
191 Dictionary with parameters from the first row of the input file, namely
192 'N', 'M', 'cutoff', 'triclinic', 'has_velocity' and 'num_of_groups'
193 species : List[str]
194 List with the chemical symbols that correspond to each type
196 Raises
197 ------
198 ValueError
199 Raised if the list of species is incompatible with the input file
200 """
201 # Parse first line
202 first_line = next(fd)
203 input_parameters = {}
204 keys = ['N', 'M', 'cutoff', 'triclinic', 'has_velocity', 'num_of_groups']
205 types = [float if key == 'cutoff' else int for key in keys]
206 for k, (key, typ) in enumerate(zip(keys, types)):
207 input_parameters[key] = typ(first_line.split()[k])
209 # Parse second line
210 second_line = next(fd)
211 second_arr = np.array(second_line.split())
212 pbc = second_arr[:3].astype(bool)
213 if input_parameters['triclinic']:
214 cell = second_arr[3:].astype(float).reshape((3, 3))
215 else:
216 cell = np.diag(second_arr[3:].astype(float))
218 # Parse all remaining rows
219 n_rows = input_parameters['N']
220 n_columns = (
221 5
222 + input_parameters['has_velocity'] * 3
223 + input_parameters['num_of_groups']
224 )
225 rest_lines = [next(fd) for _ in range(n_rows)]
226 rest_arr = np.array([line.split() for line in rest_lines])
227 assert rest_arr.shape == (n_rows, n_columns)
229 # Extract atom types, positions and masses
230 atom_types = rest_arr[:, 0].astype(int)
231 positions = rest_arr[:, 1:4].astype(float)
232 masses = rest_arr[:, 4].astype(float)
234 # Determine the atomic species
235 if species is None:
236 type_symbol_map = {}
237 if isotope_masses is not None:
238 mass_symbols = {
239 mass: symbol
240 for symbol, masses in isotope_masses.items()
241 for mass in masses
242 }
243 symbols = []
244 for atom_type, mass in zip(atom_types, masses):
245 if species is None:
246 if atom_type not in type_symbol_map:
247 if isotope_masses is not None:
248 nearest_value = find_nearest_value(
249 list(mass_symbols.keys()), mass
250 )
251 symbol = mass_symbols[nearest_value]
252 else:
253 symbol = chemical_symbols[
254 find_nearest_index(atomic_masses, mass)
255 ]
256 type_symbol_map[atom_type] = symbol
257 else:
258 symbol = type_symbol_map[atom_type]
259 else:
260 if atom_type > len(species):
261 raise Exception(
262 'There is no entry for atom type {} in the '
263 'species list!'.format(atom_type)
264 )
265 symbol = species[atom_type]
266 symbols.append(symbol)
268 if species is None:
269 species = [type_symbol_map[i] for i in sorted(type_symbol_map.keys())]
271 # Create the Atoms object
272 atoms = Atoms(
273 symbols=symbols, positions=positions, masses=masses, pbc=pbc, cell=cell
274 )
275 if input_parameters['has_velocity']:
276 velocities = rest_arr[:, 5:8].astype(float)
277 atoms.set_velocities(velocities)
278 if input_parameters['num_of_groups']:
279 start_col = 5 + 3 * input_parameters['has_velocity']
280 groups = rest_arr[:, start_col:].astype(int)
281 atoms.info = {i: {'groups': groups[i, :]} for i in range(n_rows)}
283 return atoms, input_parameters, species
286def read_gpumd(fd, species=None, isotope_masses=None):
287 """
288 Read Atoms object from a GPUMD structure input file
290 Parameters
291 ----------
292 fd : file | str
293 File object or name of file from which to read the Atoms object
294 species : List[str]
295 List with the chemical symbols that correspond to each type, will take
296 precedence over isotope_masses
297 isotope_masses: Dict[str, List[float]]
298 Dictionary with chemical symbols and lists of the associated atomic
299 masses, which is used to identify the chemical symbols that correspond
300 to the types not found in species_types. The default is to find the
301 closest match :data:`ase.data.atomic_masses`.
303 Returns
304 -------
305 atoms : Atoms
306 Atoms object
308 Raises
309 ------
310 ValueError
311 Raised if the list of species is incompatible with the input file
312 """
314 return load_xyz_input_gpumd(fd, species, isotope_masses)[0]