Coverage for ase/io/formats.py: 91.09%

539 statements  

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

1"""File formats. 

2 

3This module implements the read(), iread() and write() functions in ase.io. 

4For each file format there is an IOFormat object. 

5 

6There is a dict, ioformats, which stores the objects. 

7 

8Example 

9======= 

10 

11The xyz format is implemented in the ase/io/xyz.py file which has a 

12read_xyz() generator and a write_xyz() function. This and other 

13information can be obtained from ioformats['xyz']. 

14""" 

15 

16import functools 

17import inspect 

18import io 

19import os 

20import re 

21import sys 

22import warnings 

23from collections.abc import Iterator, Sequence 

24from importlib import import_module 

25from importlib.metadata import entry_points 

26from pathlib import PurePath 

27from typing import ( 

28 IO, 

29 Any, 

30) 

31 

32from ase.atoms import Atoms 

33from ase.parallel import parallel_function, parallel_generator 

34from ase.utils import string2index 

35from ase.utils.plugins import ExternalIOFormat 

36 

37PEEK_BYTES = 50000 

38 

39 

40class UnknownFileTypeError(Exception): 

41 pass 

42 

43 

44class IOFormat: 

45 def __init__( 

46 self, 

47 name: str, 

48 desc: str, 

49 code: str, 

50 module_name: str, 

51 encoding: str | None = None, 

52 ) -> None: 

53 self.name = name 

54 self.description = desc 

55 assert len(code) == 2 

56 assert code[0] in list('+1') 

57 assert code[1] in list('BFS') 

58 self.code = code 

59 self.module_name = module_name 

60 self.encoding = encoding 

61 

62 # (To be set by define_io_format()) 

63 self.extensions: list[str] = [] 

64 self.globs: list[str] = [] 

65 self.magic: list[str] = [] 

66 self.magic_regex: bytes | None = None 

67 

68 def _buf_as_filelike(self, data: str | bytes) -> IO: 

69 encoding = self.encoding 

70 if encoding is None: 

71 encoding = 'utf-8' # Best hacky guess. 

72 

73 if self.isbinary: 

74 if isinstance(data, str): 

75 data = data.encode(encoding) 

76 else: 

77 if isinstance(data, bytes): 

78 data = data.decode(encoding) 

79 

80 return self._ioclass(data) 

81 

82 @property 

83 def _ioclass(self): 

84 if self.isbinary: 

85 return io.BytesIO 

86 else: 

87 return io.StringIO 

88 

89 def parse_images(self, data: str | bytes, **kwargs) -> Sequence[Atoms]: 

90 with self._buf_as_filelike(data) as fd: 

91 outputs = self.read(fd, **kwargs) 

92 if self.single: 

93 assert isinstance(outputs, Atoms) 

94 return [outputs] 

95 else: 

96 return list(self.read(fd, **kwargs)) 

97 

98 def parse_atoms(self, data: str | bytes, **kwargs) -> Atoms: 

99 images = self.parse_images(data, **kwargs) 

100 return images[-1] 

101 

102 @property 

103 def can_read(self) -> bool: 

104 return self._readfunc() is not None 

105 

106 @property 

107 def can_write(self) -> bool: 

108 return self._writefunc() is not None 

109 

110 @property 

111 def can_append(self) -> bool: 

112 writefunc = self._writefunc() 

113 return self.can_write and 'append' in writefunc.__code__.co_varnames 

114 

115 def __repr__(self) -> str: 

116 tokens = [f'{name}={value!r}' for name, value in vars(self).items()] 

117 return 'IOFormat({})'.format(', '.join(tokens)) 

118 

119 def __getitem__(self, i): 

120 # For compatibility. 

121 # 

122 # Historically, the ioformats were listed as tuples 

123 # with (description, code). We look like such a tuple. 

124 return (self.description, self.code)[i] 

125 

126 @property 

127 def single(self) -> bool: 

128 """Whether this format is for a single Atoms object.""" 

129 return self.code[0] == '1' 

130 

131 @property 

132 def _formatname(self) -> str: 

133 return self.name.replace('-', '_') 

134 

135 def _readfunc(self): 

136 return getattr(self.module, 'read_' + self._formatname, None) 

137 

138 def _writefunc(self): 

139 return getattr(self.module, 'write_' + self._formatname, None) 

140 

141 @property 

142 def read(self): 

143 if not self.can_read: 

144 self._warn_none('read') 

145 return None 

146 

147 return self._read_wrapper 

148 

149 def _read_wrapper(self, *args, **kwargs): 

150 function = self._readfunc() 

151 if function is None: 

152 self._warn_none('read') 

153 return None 

154 if not inspect.isgeneratorfunction(function): 

155 function = functools.partial(wrap_read_function, function) 

156 return function(*args, **kwargs) 

157 

158 def _warn_none(self, action): 

159 msg = ( 

160 'Accessing the IOFormat.{action} property on a format ' 

161 'without {action} support will change behaviour in the ' 

162 'future and return a callable instead of None. ' 

163 'Use IOFormat.can_{action} to check whether {action} ' 

164 'is supported.' 

165 ) 

166 warnings.warn(msg.format(action=action), FutureWarning) 

167 

168 @property 

169 def write(self): 

170 if not self.can_write: 

171 self._warn_none('write') 

172 return None 

173 

174 return self._write_wrapper 

175 

176 def _write_wrapper(self, *args, **kwargs): 

177 function = self._writefunc() 

178 if function is None: 

179 raise ValueError(f'Cannot write to {self.name}-format') 

180 return function(*args, **kwargs) 

181 

182 @property 

183 def modes(self) -> str: 

184 modes = '' 

185 if self.can_read: 

186 modes += 'r' 

187 if self.can_write: 

188 modes += 'w' 

189 return modes 

190 

191 def full_description(self) -> str: 

192 lines = [ 

193 f'Name: {self.name}', 

194 f'Description: {self.description}', 

195 f'Modes: {self.modes}', 

196 f'Encoding: {self.encoding}', 

197 f'Module: {self.module_name}', 

198 f'Code: {self.code}', 

199 f'Extensions: {self.extensions}', 

200 f'Globs: {self.globs}', 

201 f'Magic: {self.magic}', 

202 ] 

203 return '\n'.join(lines) 

204 

205 @property 

206 def acceptsfd(self) -> bool: 

207 return self.code[1] != 'S' 

208 

209 @property 

210 def isbinary(self) -> bool: 

211 return self.code[1] == 'B' 

212 

213 @property 

214 def module(self): 

215 try: 

216 return import_module(self.module_name) 

217 except ImportError as err: 

218 raise UnknownFileTypeError( 

219 f'File format not recognized: {self.name}. Error: {err}' 

220 ) 

221 

222 def match_name(self, basename: str) -> bool: 

223 from fnmatch import fnmatch 

224 

225 return any(fnmatch(basename, pattern) for pattern in self.globs) 

226 

227 def match_magic(self, data: bytes) -> bool: 

228 if self.magic_regex: 

229 assert not self.magic, 'Define only one of magic and magic_regex' 

230 match = re.match(self.magic_regex, data, re.M | re.S) 

231 return match is not None 

232 

233 from fnmatch import fnmatchcase 

234 

235 return any( 

236 fnmatchcase(data, magic + b'*') # type: ignore[operator, type-var] 

237 for magic in self.magic 

238 ) 

239 

240 

241ioformats: dict[str, IOFormat] = {} # These will be filled at run-time. 

242extension2format: dict[str, IOFormat] = {} 

243 

244 

245all_formats = ioformats # Aliased for compatibility only. Please do not use. 

246format2modulename: dict[str, str] = {} # Left for compatibility only. 

247 

248 

249def define_io_format( 

250 name, 

251 desc, 

252 code, 

253 *, 

254 module=None, 

255 ext=None, 

256 glob=None, 

257 magic=None, 

258 encoding=None, 

259 magic_regex=None, 

260 external=False, 

261): 

262 if module is None: 

263 module = name.replace('-', '_') 

264 format2modulename[name] = module 

265 

266 if not external: 

267 module = 'ase.io.' + module 

268 

269 def normalize_patterns(strings): 

270 if strings is None: 

271 strings = [] 

272 elif isinstance(strings, (str, bytes)): 

273 strings = [strings] 

274 else: 

275 strings = list(strings) 

276 return strings 

277 

278 fmt = IOFormat(name, desc, code, module_name=module, encoding=encoding) 

279 fmt.extensions = normalize_patterns(ext) 

280 fmt.globs = normalize_patterns(glob) 

281 fmt.magic = normalize_patterns(magic) 

282 

283 if magic_regex is not None: 

284 fmt.magic_regex = magic_regex 

285 

286 for ext in fmt.extensions: 

287 if ext in extension2format: 

288 raise ValueError(f'extension "{ext}" already registered') 

289 extension2format[ext] = fmt 

290 

291 ioformats[name] = fmt 

292 return fmt 

293 

294 

295def get_ioformat(name: str) -> IOFormat: 

296 """Return ioformat object or raise appropriate error.""" 

297 if name not in ioformats: 

298 raise UnknownFileTypeError(name) 

299 fmt = ioformats[name] 

300 # Make sure module is importable, since this could also raise an error. 

301 fmt.module 

302 return ioformats[name] 

303 

304 

305def register_external_io_formats(group): 

306 if hasattr(entry_points(), 'select'): 

307 fmt_entry_points = entry_points().select(group=group) 

308 else: 

309 fmt_entry_points = entry_points().get(group, ()) 

310 

311 for entry_point in fmt_entry_points: 

312 try: 

313 define_external_io_format(entry_point) 

314 except Exception as exc: 

315 warnings.warn( 

316 'Failed to register external ' 

317 f'IO format {entry_point.name}: {exc}' 

318 ) 

319 

320 

321def define_external_io_format(entry_point): 

322 

323 fmt = entry_point.load() 

324 if entry_point.name in ioformats: 

325 raise ValueError(f'Format {entry_point.name} already defined') 

326 if not isinstance(fmt, ExternalIOFormat): 

327 raise TypeError( 

328 'Wrong type for registering external IO formats ' 

329 f'in format {entry_point.name}, expected ' 

330 'ExternalIOFormat' 

331 ) 

332 F(entry_point.name, **fmt._asdict(), external=True) 

333 

334 

335# We define all the IO formats below. Each IO format has a code, 

336# such as '1F', which defines some of the format's properties: 

337# 

338# 1=single atoms object 

339# +=multiple atoms objects 

340# F=accepts a file-descriptor 

341# S=needs a file-name str 

342# B=like F, but opens in binary mode 

343 

344F = define_io_format 

345F('abinit-gsr', 'ABINIT GSR file', '1S', module='abinit', glob='*o_GSR.nc') 

346F('abinit-in', 'ABINIT input file', '1F', module='abinit', magic=b'*znucl *') 

347F( 

348 'abinit-out', 

349 'ABINIT output file', 

350 '1F', 

351 module='abinit', 

352 magic=b'*.Version * of ABINIT', 

353) 

354F('aims', 'FHI-aims geometry file', '1S', ext='in') 

355F( 

356 'aims-output', 

357 'FHI-aims output', 

358 '+S', 

359 module='aims', 

360 magic=b'*Invoking FHI-aims ...', 

361) 

362F('bundletrajectory', 'ASE bundle trajectory', '+S') 

363# XXX: Define plugin in ase db backends package: 

364# F('aselmdb', 'ASE LMDB format', '+F') 

365F('castep-castep', 'CASTEP output file', '+F', module='castep', ext='castep') 

366F('castep-cell', 'CASTEP geom file', '1F', module='castep', ext='cell') 

367F('castep-geom', 'CASTEP trajectory file', '+F', module='castep', ext='geom') 

368F( 

369 'castep-md', 

370 'CASTEP molecular dynamics file', 

371 '+F', 

372 module='castep', 

373 ext='md', 

374) 

375F('castep-phonon', 'CASTEP phonon file', '1F', module='castep', ext='phonon') 

376F('cfg', 'AtomEye configuration', '1F') 

377F('cif', 'CIF-file', '+B', ext='cif') 

378F('cmdft', 'CMDFT-file', '1F', glob='*I_info') 

379F('cjson', 'Chemical json file', '1F', ext='cjson') 

380F('cp2k-dcd', 'CP2K DCD file', '+B', module='cp2k', ext='dcd') 

381F('cp2k-restart', 'CP2K restart file', '1F', module='cp2k', ext='restart') 

382F( 

383 'crystal', 

384 'Crystal fort.34 format', 

385 '1F', 

386 ext=['f34', '34'], 

387 glob=['f34', '34'], 

388) 

389F('cube', 'CUBE file', '1F', ext='cube') 

390F( 

391 'dacapo-text', 

392 'Dacapo text output', 

393 '1F', 

394 module='dacapo', 

395 magic=b'*&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n', 

396) 

397F('db', 'ASE SQLite database file', '+S') 

398F('dftb', 'DftbPlus input file', '1S', magic=b'Geometry') 

399F( 

400 'dlp4', 

401 'DL_POLY_4 CONFIG file', 

402 '1F', 

403 module='dlp4', 

404 ext='config', 

405 glob=['*CONFIG*'], 

406) 

407F('dlp-history', 'DL_POLY HISTORY file', '+F', module='dlp4', glob='HISTORY') 

408F('dmol-arc', 'DMol3 arc file', '+S', module='dmol', ext='arc') 

409F('dmol-car', 'DMol3 structure file', '1S', module='dmol', ext='car') 

410F('dmol-incoor', 'DMol3 structure file', '1S', module='dmol') 

411F('elk', 'ELK atoms definition from GEOMETRY.OUT', '1F', glob=['GEOMETRY.OUT']) 

412F('elk-in', 'ELK input file', '1F', module='elk') 

413F('eon', 'EON CON file', '+F', ext='con') 

414F('eps', 'Encapsulated Postscript', '1S') 

415F( 

416 'espresso-in', 

417 'Quantum espresso in file', 

418 '1F', 

419 module='espresso', 

420 ext='pwi', 

421 magic=[b'*\n&system', b'*\n&SYSTEM'], 

422) 

423F( 

424 'espresso-out', 

425 'Quantum espresso out file', 

426 '+F', 

427 module='espresso', 

428 ext=['pwo', 'out'], 

429 magic=b'*Program PWSCF', 

430) 

431F('exciting', 'exciting input', '1F', module='exciting', glob='input.xml') 

432F('exciting', 'exciting output', '1F', module='exciting', glob='INFO.out') 

433F('extxyz', 'Extended XYZ file', '+F', ext='xyz') 

434F('findsym', 'FINDSYM-format', '+F') 

435F( 

436 'gamess-us-out', 

437 'GAMESS-US output file', 

438 '1F', 

439 module='gamess_us', 

440 magic=b'*GAMESS', 

441) 

442F('gamess-us-in', 'GAMESS-US input file', '1F', module='gamess_us') 

443F( 

444 'gamess-us-punch', 

445 'GAMESS-US punchcard file', 

446 '1F', 

447 module='gamess_us', 

448 magic=b' $DATA', 

449 ext='dat', 

450) 

451F( 

452 'gaussian-in', 

453 'Gaussian com (input) file', 

454 '1F', 

455 module='gaussian', 

456 ext=['com', 'gjf'], 

457) 

458F( 

459 'gaussian-out', 

460 'Gaussian output file', 

461 '+F', 

462 module='gaussian', 

463 ext='log', 

464 magic=b'*Entering Gaussian System', 

465) 

466F('acemolecule-out', 'ACE output file', '1S', module='acemolecule') 

467F('acemolecule-input', 'ACE input file', '1S', module='acemolecule') 

468F('gen', 'DFTBPlus GEN format', '1F') 

469F('gif', 'Graphics interchange format', '+S', module='animation') 

470F('gpaw-out', 'GPAW text output', '+F', magic=b'* ___ ___ ___ _ _ _') 

471F('gpumd', 'GPUMD input file', '1F', glob='xyz.in') 

472F('gpw', 'GPAW restart-file', '1S', magic=[b'- of UlmGPAW', b'AFFormatGPAW']) 

473F('gromacs', 'Gromacs coordinates', '1F', ext='gro') 

474F('gromos', 'Gromos96 geometry file', '1F', ext='g96') 

475F('html', 'X3DOM HTML', '1F', module='x3d') 

476F('json', 'ASE JSON database file', '+F', ext='json', module='db') 

477F('jsv', 'JSV file format', '1F') 

478F( 

479 'lammps-dump-text', 

480 'LAMMPS text dump file', 

481 '+F', 

482 module='lammpsrun', 

483 magic_regex=b'.*?^ITEM: TIMESTEP$', 

484) 

485F('lammps-dump-binary', 'LAMMPS binary dump file', '+B', module='lammpsrun') 

486F( 

487 'lammps-data', 

488 'LAMMPS data file', 

489 '1F', 

490 module='lammpsdata', 

491 encoding='ascii', 

492) 

493F('magres', 'MAGRES ab initio NMR data file', '1F') 

494F('mol', 'MDL Molfile', '1F') 

495F('mp4', 'MP4 animation', '+S', module='animation') 

496F('mustem', 'muSTEM xtl file', '1F', ext='xtl') 

497F('mysql', 'ASE MySQL database file', '+S', module='db') 

498F('netcdftrajectory', 'AMBER NetCDF trajectory file', '+S', magic=b'CDF') 

499F('nomad-json', 'JSON from Nomad archive', '+F', ext='nomad-json') 

500F('nwchem-in', 'NWChem input file', '1F', module='nwchem', ext='nwi') 

501F( 

502 'nwchem-out', 

503 'NWChem output file', 

504 '+F', 

505 module='nwchem', 

506 ext='nwo', 

507 magic=b'*Northwest Computational Chemistry Package', 

508) 

509F('octopus-in', 'Octopus input file', '1F', module='octopus', glob='inp') 

510F( 

511 'onetep-out', 

512 'ONETEP output file', 

513 '+F', 

514 module='onetep', 

515 magic=b'*Linear-Scaling Ab Initio Total Energy Program*', 

516) 

517F( 

518 'onetep-in', 

519 'ONETEP input file', 

520 '1F', 

521 module='onetep', 

522 magic=[b'*lock species ', b'*LOCK SPECIES ', b'*--- INPUT FILE ---*'], 

523) 

524F('orca-output', 'ORCA output', '+F', module='orca', magic=b'* O R C A *') 

525F('proteindatabank', 'Protein Data Bank', '+F', ext='pdb') 

526F('png', 'Portable Network Graphics', '1B') 

527F('postgresql', 'ASE PostgreSQL database file', '+S', module='db') 

528F('pov', 'Persistance of Vision', '1S') 

529# prismatic: Should have ext='xyz' if/when multiple formats can have the same 

530# extension 

531F('prismatic', 'prismatic and computem XYZ-file', '1F') 

532F('py', 'Python file', '+F') 

533F('sys', 'qball sys file', '1F') 

534F('qbox', 'QBOX output file', '+F', magic=b'*:simulation xmlns:') 

535F('res', 'SHELX format', '1S', ext='shelx') 

536F('rmc6f', 'RMCProfile', '1S', ext='rmc6f') 

537 

538# Regex for floating-point numbers (integers, decimals, scientific notation) 

539float_re = rb'[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][-+]?\d+)?' 

540# Regex for catching element symbols 

541element_re = rb'\b[A-Z][a-z]{0,1}\b' 

542# Regex for comment lines: starts with #, !, or 'comment', safely reads to end 

543# of line 

544comment_re = rb'^[ \t]*(?:[#!]|comment)[^\r\n]*\r?\n' 

545# Regex for a lattice line 

546lattice_re = rb'^[ \t]*lattice(?:[ \t]+' + float_re + rb'){3}[ \t]*\r?\n' 

547 

548F( 

549 name='runnerdata', 

550 desc='RuNNer input.data file', 

551 code='+F', 

552 module='runner', 

553 ext='data', 

554 # ?x turns on re.VERBOSE for this string (ignore whitespace and comments) 

555 magic_regex=rb"""(?x) 

556 # Optional comment lines before the first 'begin' 

557 (?:""" 

558 + comment_re 

559 + rb""")* 

560 # Start of line: 'begin' 

561 ^begin 

562 # Optional properties, mandatory start with position(3) element 

563 (?:[ \t]+position\(3\)[ \t]+element(?:[ \t]+\S+)*)? 

564 # End of the begin line (handles Windows & Unix) 

565 [ \t]*\r?\n 

566 # 0 or more lattice lines OR comment lines intermixed 

567 (?:""" 

568 + comment_re 

569 + rb"""|""" 

570 + lattice_re 

571 + rb""")* 

572 # At least 1 atom line 

573 ^[ \t]*atom(?:[ \t]+""" 

574 + float_re 

575 + rb"""){3}[ \t]+""" 

576 + element_re 

577 + rb""" 

578 """, 

579) 

580F('sdf', 'SDF format', '1F') 

581F('siesta-xv', 'Siesta .XV file', '1F', glob='*.XV', module='siesta') 

582F('struct', 'WIEN2k structure file', '1S', module='wien2k') 

583F('struct_out', 'SIESTA STRUCT file', '1F', module='siesta') 

584F( 

585 'traj', 

586 'ASE trajectory', 

587 '+B', 

588 module='trajectory', 

589 ext='traj', 

590 magic=[b'- of UlmASE-Trajectory', b'AFFormatASE-Trajectory'], 

591) 

592F('turbomole', 'TURBOMOLE coord file', '1F', glob='coord', magic=b'$coord') 

593F( 

594 'turbomole-gradient', 

595 'TURBOMOLE gradient file', 

596 '+F', 

597 module='turbomole', 

598 glob='gradient', 

599 magic=b'$grad', 

600) 

601F('v-sim', 'V_Sim ascii file', '1F', ext='ascii') 

602F( 

603 'vasp', 

604 'VASP POSCAR/CONTCAR', 

605 '1F', 

606 ext='poscar', 

607 glob=['*POSCAR*', '*CONTCAR*', '*CENTCAR*'], 

608) 

609F('vasp-out', 'VASP OUTCAR file', '+F', module='vasp', glob='*OUTCAR*') 

610F('vasp-xdatcar', 'VASP XDATCAR file', '+F', module='vasp', glob='*XDATCAR*') 

611F('vasp-xml', 'VASP vasprun.xml file', '+F', module='vasp', glob='*vasp*.xml') 

612F('vti', 'VTK XML Image Data', '1F', module='vtkxml') 

613F('vtu', 'VTK XML Unstructured Grid', '1F', module='vtkxml', ext='vtu') 

614F('wout', 'Wannier90 output', '1F', module='wannier90') 

615F('x3d', 'X3D', '1S') 

616F('xsd', 'Materials Studio file', '1F') 

617F( 

618 'xsf', 

619 'XCrySDen Structure File', 

620 '+F', 

621 magic=[ 

622 b'*\nANIMSTEPS', 

623 b'*\nCRYSTAL', 

624 b'*\nSLAB', 

625 b'*\nPOLYMER', 

626 b'*\nMOLECULE', 

627 b'*\nATOMS', 

628 ], 

629) 

630F('xtd', 'Materials Studio file', '+F') 

631# xyz: No `ext='xyz'` in the definition below. 

632# The .xyz files are handled by the extxyz module by default. 

633F('xyz', 'XYZ-file', '+F') 

634 

635# Register IO formats exposed through the ase.ioformats entry point 

636register_external_io_formats('ase.ioformats') 

637 

638 

639def get_compression(filename: str) -> tuple[str, str | None]: 

640 """ 

641 Parse any expected file compression from the extension of a filename. 

642 Return the filename without the extension, and the extension. Recognises 

643 ``.gz``, ``.bz2``, ``.xz``. 

644 

645 >>> get_compression('H2O.pdb.gz') 

646 ('H2O.pdb', 'gz') 

647 >>> get_compression('crystal.cif') 

648 ('crystal.cif', None) 

649 

650 Parameters 

651 ---------- 

652 filename: str 

653 Full filename including extension. 

654 

655 Returns 

656 ------- 

657 (root, extension): (str, str or None) 

658 Filename split into root without extension, and the extension 

659 indicating compression format. Will not split if compression 

660 is not recognised. 

661 """ 

662 # Update if anything is added 

663 valid_compression = ['gz', 'bz2', 'xz'] 

664 

665 # Use stdlib as it handles most edge cases 

666 root, compression = os.path.splitext(filename) 

667 

668 # extension keeps the '.' so remember to remove it 

669 if compression.strip('.') in valid_compression: 

670 return root, compression.strip('.') 

671 else: 

672 return filename, None 

673 

674 

675def open_with_compression(filename: str, mode: str = 'r') -> IO: 

676 """ 

677 Wrapper around builtin `open` that will guess compression of a file 

678 from the filename and open it for reading or writing as if it were 

679 a standard file. 

680 

681 Implemented for ``gz``(gzip), ``bz2``(bzip2) and ``xz``(lzma). 

682 

683 Supported modes are: 

684 * 'r', 'rt', 'w', 'wt' for text mode read and write. 

685 * 'rb, 'wb' for binary read and write. 

686 

687 Parameters 

688 ---------- 

689 filename: str 

690 Path to the file to open, including any extensions that indicate 

691 the compression used. 

692 mode: str 

693 Mode to open the file, same as for builtin ``open``, e.g 'r', 'w'. 

694 

695 Returns 

696 ------- 

697 fd: file 

698 File-like object open with the specified mode. 

699 """ 

700 

701 # Compressed formats sometimes default to binary, so force text mode. 

702 if mode == 'r': 

703 mode = 'rt' 

704 elif mode == 'w': 

705 mode = 'wt' 

706 elif mode == 'a': 

707 mode = 'at' 

708 

709 _root, compression = get_compression(filename) 

710 

711 if compression == 'gz': 

712 import gzip 

713 

714 return gzip.open(filename, mode=mode) # type: ignore[return-value] 

715 elif compression == 'bz2': 

716 import bz2 

717 

718 return bz2.open(filename, mode=mode) 

719 elif compression == 'xz': 

720 import lzma 

721 

722 return lzma.open(filename, mode) 

723 else: 

724 # Either None or unknown string 

725 return open(filename, mode) 

726 

727 

728def is_compressed(fd: io.BufferedIOBase) -> bool: 

729 """Check if the file object is in a compressed format.""" 

730 compressed = False 

731 

732 # We'd like to avoid triggering imports unless already imported. 

733 # Also, Python can be compiled without e.g. lzma so we need to 

734 # protect against that: 

735 if 'gzip' in sys.modules: 

736 import gzip 

737 

738 compressed = compressed or isinstance(fd, gzip.GzipFile) 

739 if 'bz2' in sys.modules: 

740 import bz2 

741 

742 compressed = compressed or isinstance(fd, bz2.BZ2File) 

743 if 'lzma' in sys.modules: 

744 import lzma 

745 

746 compressed = compressed or isinstance(fd, lzma.LZMAFile) 

747 return compressed 

748 

749 

750def wrap_read_function(read, filename, index=None, **kwargs): 

751 """Convert read-function to generator.""" 

752 if index is None: 

753 yield read(filename, **kwargs) 

754 else: 

755 yield from read(filename, index, **kwargs) 

756 

757 

758NameOrFile = str | PurePath | IO 

759 

760 

761def write( 

762 filename: NameOrFile, 

763 images: Atoms | Sequence[Atoms], 

764 format: str | None = None, 

765 parallel: bool = True, 

766 append: bool = False, 

767 **kwargs: Any, 

768) -> None: 

769 """Write Atoms object(s) to file. 

770 

771 filename: str or file 

772 Name of the file to write to or a file descriptor. The name '-' 

773 means standard output. 

774 images: Atoms object or list of Atoms objects 

775 A single Atoms object or a list of Atoms objects. 

776 format: str 

777 Used to specify the file-format. If not given, the 

778 file-format will be taken from suffix of the filename. 

779 parallel: bool 

780 Default is to write on master only. Use parallel=False to write 

781 from all slaves. 

782 append: bool 

783 Default is to open files in 'w' or 'wb' mode, overwriting 

784 existing files. In some cases opening the file in 'a' or 'ab' 

785 mode (appending) is useful, 

786 e.g. writing trajectories or saving multiple Atoms objects in one file. 

787 WARNING: If the file format does not support multiple entries without 

788 additional keywords/headers, files created using 'append=True' 

789 might not be readable by any program! They will nevertheless be 

790 written without error message. 

791 

792 The use of additional keywords is format specific. write() may 

793 return an object after writing certain formats, but this behaviour 

794 may change in the future. 

795 

796 """ 

797 

798 if isinstance(filename, PurePath): 

799 filename = str(filename) 

800 

801 if isinstance(filename, str): 

802 fd = None 

803 if filename == '-': 

804 fd = sys.stdout 

805 filename = None # type: ignore[assignment] 

806 elif format is None: 

807 format = filetype(filename, read=False) 

808 assert isinstance(format, str) 

809 else: 

810 fd = filename # type: ignore[assignment] 

811 if format is None: 

812 try: 

813 format = filetype(filename, read=False) 

814 assert isinstance(format, str) 

815 except UnknownFileTypeError: 

816 format = None 

817 filename = None # type: ignore[assignment] 

818 

819 format = format or 'json' # default is json 

820 

821 io = get_ioformat(format) 

822 

823 return _write( 

824 filename, 

825 fd, 

826 format, 

827 io, 

828 images, 

829 parallel=parallel, 

830 append=append, 

831 **kwargs, 

832 ) 

833 

834 

835@parallel_function 

836def _write( 

837 filename, fd, format, io, images, parallel=None, append=False, **kwargs 

838): 

839 if isinstance(images, Atoms): 

840 images = [images] 

841 

842 if io.single: 

843 if len(images) > 1: 

844 raise ValueError( 

845 '{}-format can only store 1 Atoms object.'.format(format) 

846 ) 

847 images = images[0] 

848 

849 if not io.can_write: 

850 raise ValueError(f"Can't write to {format}-format") 

851 

852 # Special case for json-format: 

853 if format == 'json' and (len(images) > 1 or append): 

854 if filename is not None: 

855 return io.write(filename, images, append=append, **kwargs) 

856 raise ValueError( 

857 "Can't write more than one image to file-descriptor " 

858 'using json-format.' 

859 ) 

860 

861 if io.acceptsfd: 

862 open_new = fd is None 

863 try: 

864 if open_new: 

865 mode = 'wb' if io.isbinary else 'w' 

866 if append: 

867 mode = mode.replace('w', 'a') 

868 fd = open_with_compression(filename, mode) 

869 # XXX remember to re-enable compressed open 

870 # fd = io.open(filename, mode) 

871 return io.write(fd, images, **kwargs) 

872 finally: 

873 if open_new and fd is not None: 

874 fd.close() 

875 else: 

876 if fd is not None: 

877 raise ValueError( 

878 "Can't write {}-format to file-descriptor".format(format) 

879 ) 

880 if io.can_append: 

881 return io.write(filename, images, append=append, **kwargs) 

882 elif append: 

883 raise ValueError( 

884 'Cannot append to {}-format, write-function ' 

885 'does not support the append keyword.'.format(format) 

886 ) 

887 else: 

888 return io.write(filename, images, **kwargs) 

889 

890 

891def read( 

892 filename: NameOrFile, 

893 index: Any | None = None, 

894 format: str | None = None, 

895 parallel: bool = True, 

896 do_not_split_by_at_sign: bool = False, 

897 **kwargs, 

898) -> Atoms | list[Atoms]: 

899 """Read Atoms object(s) from file. 

900 

901 Parameters 

902 ---------- 

903 filename: str or file 

904 Name of the file to read from or a file descriptor. 

905 index: int, slice or str 

906 The last configuration will be returned by default. Examples: 

907 

908 * ``index=0``: first configuration 

909 * ``index=-2``: second to last 

910 * ``index=':'`` or ``index=slice(None)``: all 

911 * ``index='-3:'`` or ``index=slice(-3, None)``: three last 

912 * ``index='::2'`` or ``index=slice(0, None, 2)``: even 

913 * ``index='1::2'`` or ``index=slice(1, None, 2)``: odd 

914 

915 .. versionchanged:: 3.30.0 (:mr:`4328`) 

916 

917 It raises an error for negative out-of-range integer-like index, 

918 e.g., ``index=-3`` for a file with two images. 

919 

920 format: str 

921 Used to specify the file-format. If not given, the 

922 file-format will be guessed by the *filetype* function. 

923 parallel: bool 

924 Default is to read on master and broadcast to slaves. Use 

925 parallel=False to read on all slaves. 

926 do_not_split_by_at_sign: bool 

927 If False (default) ``filename`` is splitted by at sign ``@`` 

928 

929 Notes 

930 ----- 

931 Many formats allow on open file-like object to be passed instead 

932 of ``filename``. In this case the format cannot be auto-detected, 

933 so the ``format`` argument should be explicitly given. 

934 

935 """ 

936 if isinstance(filename, PurePath): 

937 filename = str(filename) 

938 if filename == '-': 

939 filename = sys.stdin 

940 if isinstance(index, str): 

941 try: 

942 index = string2index(index) 

943 except ValueError: 

944 pass 

945 

946 filename, index = parse_filename(filename, index, do_not_split_by_at_sign) 

947 if index is None: 

948 index = -1 

949 format = format or filetype(filename, read=isinstance(filename, str)) 

950 

951 io = get_ioformat(format) 

952 if isinstance(index, (slice, str)): 

953 return list( 

954 _iread(filename, index, format, io, parallel=parallel, **kwargs) 

955 ) 

956 else: 

957 # For index=-1, stop=None avoids the empty slice [-1:0]. 

958 index = slice(index, (index + 1) or None) 

959 return next( 

960 _iread(filename, index, format, io, parallel=parallel, **kwargs) 

961 ) 

962 

963 

964def iread( 

965 filename: NameOrFile, 

966 index: Any | None = None, 

967 format: str | None = None, 

968 parallel: bool = True, 

969 do_not_split_by_at_sign: bool = False, 

970 **kwargs, 

971) -> Iterator[Atoms]: 

972 """Iterator for reading Atoms objects from file. 

973 

974 Works as the `read` function, but yields one Atoms object at a time 

975 instead of all at once.""" 

976 

977 if isinstance(filename, PurePath): 

978 filename = str(filename) 

979 

980 if isinstance(index, str): 

981 index = string2index(index) 

982 

983 filename, index = parse_filename(filename, index, do_not_split_by_at_sign) 

984 

985 if index is None or index == ':': 

986 index = slice(None, None, None) 

987 

988 if not isinstance(index, (slice, str)): 

989 # For index=-1, stop=None avoids the empty slice [-1:0]. 

990 index = slice(index, (index + 1) or None) 

991 

992 format = format or filetype(filename, read=isinstance(filename, str)) 

993 io = get_ioformat(format) 

994 

995 yield from _iread(filename, index, format, io, parallel=parallel, **kwargs) 

996 

997 

998@parallel_generator 

999def _iread( 

1000 filename, index, format, io, parallel=None, full_output=False, **kwargs 

1001): 

1002 

1003 if not io.can_read: 

1004 raise ValueError(f"Can't read from {format}-format") 

1005 

1006 if io.single: 

1007 start = index.start 

1008 assert start is None or start == 0 or start == -1 

1009 args = () 

1010 else: 

1011 args = (index,) 

1012 

1013 must_close_fd = False 

1014 if isinstance(filename, str): 

1015 if io.acceptsfd: 

1016 mode = 'rb' if io.isbinary else 'r' 

1017 fd = open_with_compression(filename, mode) 

1018 must_close_fd = True 

1019 else: 

1020 fd = filename 

1021 else: 

1022 assert io.acceptsfd 

1023 fd = filename 

1024 

1025 # Make sure fd is closed in case loop doesn't finish: 

1026 try: 

1027 for dct in io.read(fd, *args, **kwargs): 

1028 if not isinstance(dct, dict): 

1029 dct = {'atoms': dct} 

1030 if full_output: 

1031 yield dct 

1032 else: 

1033 yield dct['atoms'] 

1034 finally: 

1035 if must_close_fd: 

1036 fd.close() 

1037 

1038 

1039def parse_filename(filename, index=None, do_not_split_by_at_sign=False): 

1040 if not isinstance(filename, str): 

1041 return filename, index 

1042 

1043 basename = os.path.basename(filename) 

1044 if do_not_split_by_at_sign or '@' not in basename: 

1045 return filename, index 

1046 

1047 newindex = None 

1048 newfilename, newindex = filename.rsplit('@', 1) 

1049 

1050 if isinstance(index, slice): 

1051 return newfilename, index 

1052 try: 

1053 newindex = string2index(newindex) 

1054 except ValueError: 

1055 warnings.warn( 

1056 'Can not parse index for path \n' 

1057 ' "%s" \nConsider set ' 

1058 'do_not_split_by_at_sign=True \nif ' 

1059 'there is no index.' % filename 

1060 ) 

1061 return newfilename, newindex 

1062 

1063 

1064def match_magic(data: bytes) -> IOFormat: 

1065 data = data[:PEEK_BYTES] 

1066 for ioformat in ioformats.values(): 

1067 if ioformat.match_magic(data): 

1068 return ioformat 

1069 raise UnknownFileTypeError('Cannot guess file type from contents') 

1070 

1071 

1072def filetype( 

1073 filename: NameOrFile, 

1074 read: bool = True, 

1075 guess: bool = True, 

1076) -> str: 

1077 """Try to guess the type of the file. 

1078 

1079 First, special signatures in the filename will be checked for. If that 

1080 does not identify the file type, then the first 2000 bytes of the file 

1081 will be read and analysed. Turn off this second part by using 

1082 read=False. 

1083 

1084 Can be used from the command-line also:: 

1085 

1086 $ ase info filename ... 

1087 """ 

1088 

1089 orig_filename = filename 

1090 if hasattr(filename, 'name'): 

1091 filename = filename.name 

1092 

1093 ext = None 

1094 if isinstance(filename, str): 

1095 if os.path.isdir(filename): 

1096 if os.path.basename(os.path.normpath(filename)) == 'states': 

1097 return 'eon' 

1098 return 'bundletrajectory' 

1099 

1100 if filename.startswith('postgres'): 

1101 return 'postgresql' 

1102 

1103 if filename.startswith('mysql') or filename.startswith('mariadb'): 

1104 return 'mysql' 

1105 

1106 if filename.endswith('aselmdb'): 

1107 return 'db' 

1108 

1109 # strip any compression extensions that can be read 

1110 root, _compression = get_compression(filename) 

1111 basename = os.path.basename(root) 

1112 

1113 if '.' in basename: 

1114 ext = os.path.splitext(basename)[1].strip('.').lower() 

1115 

1116 for fmt in ioformats.values(): 

1117 if fmt.match_name(basename): 

1118 return fmt.name 

1119 

1120 if not read: 

1121 if ext is None: 

1122 raise UnknownFileTypeError('Could not guess file type') 

1123 ioformat = extension2format.get(ext) 

1124 if ioformat: 

1125 return ioformat.name 

1126 

1127 # askhl: This is strange, we don't know if ext is a format: 

1128 return ext 

1129 

1130 if orig_filename == filename: 

1131 fd = open_with_compression(filename, 'rb') 

1132 else: 

1133 fd = orig_filename # type: ignore[assignment] 

1134 else: 

1135 fd = filename 

1136 if fd is sys.stdin: 

1137 return 'json' 

1138 

1139 data = fd.read(PEEK_BYTES) 

1140 if fd is not filename: 

1141 fd.close() 

1142 else: 

1143 fd.seek(0) 

1144 

1145 if len(data) == 0: 

1146 raise UnknownFileTypeError(f'Empty file: {filename}') 

1147 

1148 try: 

1149 return match_magic(data).name 

1150 except UnknownFileTypeError: 

1151 pass 

1152 

1153 format = None 

1154 if ext in extension2format: 

1155 format = extension2format[ext].name 

1156 

1157 if format is None and guess: 

1158 format = ext 

1159 if format is None: 

1160 # Do quick xyz check: 

1161 lines = data.splitlines() 

1162 if lines and lines[0].strip().isdigit(): 

1163 return extension2format['xyz'].name 

1164 

1165 raise UnknownFileTypeError('Could not guess file type') 

1166 assert isinstance(format, str) 

1167 return format 

1168 

1169 

1170def index2range(index: int | slice, length: int) -> range: 

1171 """Convert slice or integer to range. 

1172 

1173 If index is an integer, range will contain only that integer.""" 

1174 if isinstance(index, int): 

1175 return range(index, index + 1) 

1176 return range(length)[index]