Coverage for ase/io/rmc6f.py: 94.90%

196 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1import re 

2import time 

3 

4import numpy as np 

5 

6from ase.atoms import Atoms 

7from ase.cell import Cell 

8from ase.utils import reader, writer 

9 

10__all__ = ['read_rmc6f', 'write_rmc6f'] 

11 

12ncols2style = {9: 'no_labels', 10: 'labels', 11: 'magnetic'} 

13 

14 

15def _read_construct_regex(lines): 

16 """ 

17 Utility for constructing regular expressions used by reader. 

18 """ 

19 lines = [line.strip() for line in lines] 

20 lines_re = '|'.join(lines) 

21 lines_re = lines_re.replace(' ', r'\s+') 

22 lines_re = lines_re.replace('(', r'\(') 

23 lines_re = lines_re.replace(')', r'\)') 

24 return f'({lines_re})' 

25 

26 

27def _read_line_of_atoms_section(fields): 

28 """ 

29 Process `fields` line of Atoms section in rmc6f file and output extracted 

30 info as atom id (key) and list of properties for Atoms object (values). 

31 

32 Parameters 

33 ---------- 

34 fields: list[str] 

35 List of columns from line in rmc6f file. 

36 

37 

38 Returns 

39 ------ 

40 atom_id: int 

41 Atom ID 

42 properties: list[str|float] 

43 List of Atoms properties based on rmc6f style. 

44 Basically, have 1) element and fractional coordinates for 'labels' 

45 or 'no_labels' style and 2) same for 'magnetic' style except adds 

46 the spin. 

47 Examples for 1) 'labels' or 'no_labels' styles or 2) 'magnetic' style: 

48 1) [element, xf, yf, zf] 

49 2) [element, xf, yf, zf, spin] 

50 """ 

51 # Atom id 

52 atom_id = int(fields[0]) 

53 

54 # Get style used for rmc6f from file based on number of columns 

55 ncols = len(fields) 

56 style = ncols2style[ncols] 

57 

58 # Create the position dictionary 

59 properties = [] 

60 element = str(fields[1]) 

61 if style == 'no_labels': 

62 # id element xf yf zf ref_num ucell_x ucell_y ucell_z 

63 xf = float(fields[2]) 

64 yf = float(fields[3]) 

65 zf = float(fields[4]) 

66 properties = [element, xf, yf, zf] 

67 

68 elif style == 'labels': 

69 # id element label xf yf zf ref_num ucell_x ucell_y ucell_z 

70 xf = float(fields[3]) 

71 yf = float(fields[4]) 

72 zf = float(fields[5]) 

73 properties = [element, xf, yf, zf] 

74 

75 elif style == 'magnetic': 

76 # id element xf yf zf ref_num ucell_x ucell_y ucell_z M: spin 

77 xf = float(fields[2]) 

78 yf = float(fields[3]) 

79 zf = float(fields[4]) 

80 spin = float(fields[10].strip('M:')) 

81 properties = [element, xf, yf, zf, spin] 

82 else: 

83 raise Exception('Unsupported style for parsing rmc6f file format.') 

84 

85 return atom_id, properties 

86 

87 

88def _read_process_rmc6f_lines_to_pos_and_cell(lines): 

89 """ 

90 Processes the lines of rmc6f file to atom position dictionary and cell 

91 

92 Parameters 

93 ---------- 

94 lines: list[str] 

95 List of lines from rmc6f file. 

96 

97 Returns 

98 ------ 

99 pos : dict{int:list[str|float]} 

100 Dict for each atom id and Atoms properties based on rmc6f style. 

101 Basically, have 1) element and fractional coordinates for 'labels' 

102 or 'no_labels' style and 2) same for 'magnetic' style except adds 

103 the spin. 

104 Examples for 1) 'labels' or 'no_labels' styles or 2) 'magnetic' style: 

105 1) pos[aid] = [element, xf, yf, zf] 

106 2) pos[aid] = [element, xf, yf, zf, spin] 

107 cell: Cell object 

108 The ASE Cell object created from cell parameters read from the 'Cell' 

109 section of rmc6f file. 

110 """ 

111 

112 # Inititalize output pos dictionary 

113 pos = {} 

114 

115 # Defined the header an section lines we process 

116 header_lines = [ 

117 'Number of atoms:', 

118 'Supercell dimensions:', 

119 'Cell (Ang/deg):', 

120 'Lattice vectors (Ang):', 

121 ] 

122 sections = ['Atoms'] 

123 

124 # Construct header and sections regex 

125 header_lines_re = _read_construct_regex(header_lines) 

126 sections_re = _read_construct_regex(sections) 

127 

128 section = None 

129 header = True 

130 

131 # Remove any lines that are blank 

132 lines = [line for line in lines if line != ''] 

133 

134 # Process each line of rmc6f file 

135 pos = {} 

136 for line in lines: 

137 # check if in a section 

138 m = re.match(sections_re, line) 

139 if m is not None: 

140 section = m.group(0).strip() 

141 header = False 

142 continue 

143 

144 # header section 

145 if header: 

146 field = None 

147 val = None 

148 

149 # Regex that matches whitespace-separated floats 

150 float_list_re = r'\s+(\d[\d|\s\.]+[\d|\.])' 

151 m = re.search(header_lines_re + float_list_re, line) 

152 if m is not None: 

153 field = m.group(1) 

154 val = m.group(2) 

155 

156 if field is not None and val is not None: 

157 if field == 'Number of atoms:': 

158 """ 

159 NOTE: Can just capture via number of atoms ingested. 

160 Maybe use in future for a check. 

161 code: natoms = int(val) 

162 """ 

163 

164 if field.startswith('Supercell'): 

165 """ 

166 NOTE: wrapping back down to unit cell is not 

167 necessarily needed for ASE object. 

168 

169 code: supercell = [int(x) for x in val.split()] 

170 """ 

171 

172 if field.startswith('Cell'): 

173 cellpar = [float(x) for x in val.split()] 

174 cell = Cell.fromcellpar(cellpar) 

175 

176 if field.startswith('Lattice'): 

177 """ 

178 NOTE: Have questions about RMC fractionalization matrix for 

179 conversion in data2config vs. the ASE matrix. 

180 Currently, just support the Cell section. 

181 """ 

182 

183 # main body section 

184 if section is not None: 

185 if section == 'Atoms': 

186 atom_id, atom_props = _read_line_of_atoms_section(line.split()) 

187 pos[atom_id] = atom_props 

188 

189 return pos, cell 

190 

191 

192def _write_output_column_format(columns, arrays): 

193 """ 

194 Helper function to build output for data columns in rmc6f format 

195 

196 Parameters 

197 ---------- 

198 columns: list[str] 

199 List of keys in arrays. Will be columns in the output file. 

200 arrays: dict{str:np.array} 

201 Dict with arrays for each column of rmc6f file that are 

202 property of Atoms object. 

203 

204 Returns 

205 ------ 

206 property_ncols : list[int] 

207 Number of columns for each property. 

208 dtype_obj: np.dtype 

209 Data type object for the columns. 

210 formats_as_str: str 

211 The format for printing the columns. 

212 

213 """ 

214 fmt_map = { 

215 'd': ('R', '%14.6f '), 

216 'f': ('R', '%14.6f '), 

217 'i': ('I', '%8d '), 

218 'O': ('S', '%s'), 

219 'S': ('S', '%s'), 

220 'U': ('S', '%s'), 

221 'b': ('L', ' %.1s '), 

222 } 

223 

224 property_types = [] 

225 property_ncols = [] 

226 dtypes = [] 

227 formats = [] 

228 

229 # Take each column and setup formatting vectors 

230 for column in columns: 

231 array = arrays[column] 

232 dtype = array.dtype 

233 

234 property_type, fmt = fmt_map[dtype.kind] 

235 property_types.append(property_type) 

236 

237 # Flags for 1d vectors 

238 is_1d = len(array.shape) == 1 

239 is_1d_as_2d = len(array.shape) == 2 and array.shape[1] == 1 

240 

241 # Construct the list of key pairs of column with dtype 

242 if is_1d or is_1d_as_2d: 

243 ncol = 1 

244 dtypes.append((column, dtype)) 

245 else: 

246 ncol = array.shape[1] 

247 for c in range(ncol): 

248 dtypes.append((column + str(c), dtype)) 

249 

250 # Add format and number of columns for this property to output array 

251 formats.extend([fmt] * ncol) 

252 property_ncols.append(ncol) 

253 

254 # Prepare outputs to correct data structure 

255 dtype_obj = np.dtype(dtypes) 

256 formats_as_str = ''.join(formats) + '\n' 

257 

258 return property_ncols, dtype_obj, formats_as_str 

259 

260 

261def _write_output(filename, header_lines, data, fmt, order=None): 

262 """ 

263 Helper function to write information to the filename 

264 

265 Parameters 

266 ---------- 

267 filename : file|str 

268 A file like object or filename 

269 header_lines : list[str] 

270 Header section of output rmc6f file 

271 data: np.array[len(atoms)] 

272 Array for the Atoms section to write to file. Has 

273 the columns that need to be written on each row 

274 fmt: str 

275 The format string to use for writing each column in 

276 the rows of data. 

277 order : list[str] 

278 If not None, gives a list of atom types for the order 

279 to write out each. 

280 """ 

281 fd = filename 

282 

283 # Write header section 

284 for line in header_lines: 

285 fd.write(f'{line} \n') 

286 

287 # If specifying the order, fix the atom id and write to file 

288 natoms = data.shape[0] 

289 if order is not None: 

290 new_id = 0 

291 for atype in order: 

292 for i in range(natoms): 

293 if atype == data[i][1]: 

294 new_id += 1 

295 data[i][0] = new_id 

296 fd.write(fmt % tuple(data[i])) 

297 # ...just write rows to file 

298 else: 

299 for i in range(natoms): 

300 fd.write(fmt % tuple(data[i])) 

301 

302 

303@reader 

304def read_rmc6f(filename, atom_type_map=None): 

305 """ 

306 Parse a RMCProfile rmc6f file into ASE Atoms object 

307 

308 Parameters 

309 ---------- 

310 filename : file|str 

311 A file like object or filename. 

312 atom_type_map: dict{str:str} 

313 Map of atom types for conversions. Mainly used if there is 

314 an atom type in the file that is not supported by ASE but 

315 want to map to a supported atom type instead. 

316 

317 Example to map deuterium to hydrogen: 

318 atom_type_map = { 'D': 'H' } 

319 

320 Returns 

321 ------ 

322 structure : Atoms 

323 The Atoms object read in from the rmc6f file. 

324 """ 

325 

326 fd = filename 

327 lines = fd.readlines() 

328 

329 # Process the rmc6f file to extract positions and cell 

330 pos, cell = _read_process_rmc6f_lines_to_pos_and_cell(lines) 

331 

332 # create an atom type map if one does not exist from unique atomic symbols 

333 if atom_type_map is None: 

334 symbols = [atom[0] for atom in pos.values()] 

335 atom_type_map = {atype: atype for atype in symbols} 

336 

337 # Use map of tmp symbol to actual symbol 

338 for atom in pos.values(): 

339 atom[0] = atom_type_map[atom[0]] 

340 

341 # create Atoms from read-in data 

342 symbols = [] 

343 scaled_positions = [] 

344 spin = None 

345 magmoms = [] 

346 for atom in pos.values(): 

347 if len(atom) == 4: 

348 element, x, y, z = atom 

349 else: 

350 element, x, y, z, spin = atom 

351 

352 element = atom_type_map[element] 

353 symbols.append(element) 

354 scaled_positions.append([x, y, z]) 

355 if spin is not None: 

356 magmoms.append(spin) 

357 

358 atoms = Atoms( 

359 scaled_positions=scaled_positions, 

360 symbols=symbols, 

361 cell=cell, 

362 magmoms=magmoms, 

363 pbc=[True, True, True], 

364 ) 

365 

366 return atoms 

367 

368 

369@writer 

370def write_rmc6f(filename, atoms, order=None, atom_type_map=None): 

371 """ 

372 Write output in rmc6f format - RMCProfile v6 fractional coordinates 

373 

374 Parameters 

375 ---------- 

376 filename : file|str 

377 A file like object or filename. 

378 atoms: Atoms object 

379 The Atoms object to be written. 

380 

381 order : list[str] 

382 If not None, gives a list of atom types for the order 

383 to write out each. 

384 atom_type_map: dict{str:str} 

385 Map of atom types for conversions. Mainly used if there is 

386 an atom type in the Atoms object that is a placeholder 

387 for a different atom type. This is used when the atom type 

388 is not supported by ASE but is in RMCProfile. 

389 

390 Example to map hydrogen to deuterium: 

391 atom_type_map = { 'H': 'D' } 

392 """ 

393 

394 # get atom types and how many of each (and set to order if passed) 

395 atom_types = set(atoms.symbols) 

396 if order is not None: 

397 if set(atom_types) != set(order): 

398 raise Exception('The order is not a set of the atom types.') 

399 atom_types = order 

400 

401 atom_count_dict = atoms.symbols.formula.count() 

402 natom_types = [str(atom_count_dict[atom_type]) for atom_type in atom_types] 

403 

404 # create an atom type map if one does not exist from unique atomic symbols 

405 if atom_type_map is None: 

406 symbols = set(np.array(atoms.symbols)) 

407 atom_type_map = {atype: atype for atype in symbols} 

408 

409 # HEADER SECTION 

410 

411 # get type and number of each atom type 

412 atom_types_list = [atom_type_map[atype] for atype in atom_types] 

413 atom_types_present = ' '.join(atom_types_list) 

414 natom_types_present = ' '.join(natom_types) 

415 

416 header_lines = [ 

417 '(Version 6f format configuration file)', 

418 '(Generated by ASE - Atomic Simulation Environment https://ase-lib.org/ )', # noqa: E501 

419 'Metadata date: ' + time.strftime('%d-%m-%Y'), 

420 f'Number of types of atoms: {len(atom_types)} ', 

421 f'Atom types present: {atom_types_present}', 

422 f'Number of each atom type: {natom_types_present}', 

423 'Number of moves generated: 0', 

424 'Number of moves tried: 0', 

425 'Number of moves accepted: 0', 

426 'Number of prior configuration saves: 0', 

427 f'Number of atoms: {len(atoms)}', 

428 'Supercell dimensions: 1 1 1', 

429 ] 

430 

431 # magnetic moments 

432 if atoms.has('magmoms'): 

433 spin_str = 'Number of spins: {}' 

434 spin_line = spin_str.format(len(atoms.get_initial_magnetic_moments())) 

435 header_lines.extend([spin_line]) 

436 

437 density_str = 'Number density (Ang^-3): {}' 

438 density_line = density_str.format(len(atoms) / atoms.get_volume()) 

439 cell_angles = [str(x) for x in atoms.cell.cellpar()] 

440 cell_line = 'Cell (Ang/deg): ' + ' '.join(cell_angles) 

441 header_lines.extend([density_line, cell_line]) 

442 

443 # get lattice vectors from cell lengths and angles 

444 # NOTE: RMCProfile uses a different convention for the fractionalization 

445 # matrix 

446 

447 cell_parameters = atoms.cell.cellpar() 

448 cell = Cell.fromcellpar(cell_parameters).T 

449 x_line = ' '.join([f'{i:12.6f}' for i in cell[0]]) 

450 y_line = ' '.join([f'{i:12.6f}' for i in cell[1]]) 

451 z_line = ' '.join([f'{i:12.6f}' for i in cell[2]]) 

452 lat_lines = ['Lattice vectors (Ang):', x_line, y_line, z_line] 

453 header_lines.extend(lat_lines) 

454 header_lines.extend(['Atoms:']) 

455 

456 # ATOMS SECTION 

457 

458 # create columns of data for atoms (fr_cols) 

459 fr_cols = ['id', 'symbols', 'scaled_positions', 'ref_num', 'ref_cell'] 

460 if atoms.has('magmoms'): 

461 fr_cols.extend('magmom') 

462 

463 # Collect data to be written out 

464 natoms = len(atoms) 

465 

466 arrays = {} 

467 arrays['id'] = np.array(range(1, natoms + 1, 1), int) 

468 arrays['symbols'] = np.array(atoms.symbols) 

469 arrays['ref_num'] = np.zeros(natoms, int) 

470 arrays['ref_cell'] = np.zeros((natoms, 3), int) 

471 arrays['scaled_positions'] = np.array(atoms.get_scaled_positions()) 

472 

473 # get formatting for writing output based on atom arrays 

474 ncols, dtype_obj, fmt = _write_output_column_format(fr_cols, arrays) 

475 

476 # Pack fr_cols into record array 

477 data = np.zeros(natoms, dtype_obj) 

478 for column, ncol in zip(fr_cols, ncols): 

479 value = arrays[column] 

480 if ncol == 1: 

481 data[column] = np.squeeze(value) 

482 else: 

483 for c in range(ncol): 

484 data[column + str(c)] = value[:, c] 

485 

486 # Use map of tmp symbol to actual symbol 

487 for i in range(natoms): 

488 data[i][1] = atom_type_map[data[i][1]] 

489 

490 # Write the output 

491 _write_output(filename, header_lines, data, fmt, order=order)