Coverage for ase/io/cif.py: 90.85%

492 statements  

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

1"""Module to read and write atoms in cif file format. 

2 

3See http://www.iucr.org/resources/cif/spec/version1.1/cifsyntax for a 

4description of the file format. STAR extensions as save frames, 

5global blocks, nested loops and multi-data values are not supported. 

6The "latin-1" encoding is required by the IUCR specification. 

7""" 

8 

9import collections.abc 

10import io 

11import re 

12import shlex 

13import warnings 

14from collections.abc import Iterator, Sequence 

15from typing import Any 

16 

17import numpy as np 

18 

19from ase import Atoms 

20from ase.cell import Cell 

21from ase.io.cif_unicode import format_unicode, handle_subscripts 

22from ase.spacegroup import crystal 

23from ase.spacegroup.spacegroup import Spacegroup, spacegroup_from_data 

24from ase.utils import iofunction 

25 

26rhombohedral_spacegroups = {146, 148, 155, 160, 161, 166, 167} 

27 

28 

29old_spacegroup_names = { 

30 'Abm2': 'Aem2', 

31 'Aba2': 'Aea2', 

32 'Cmca': 'Cmce', 

33 'Cmma': 'Cmme', 

34 'Ccca': 'Ccc1', 

35} 

36 

37# CIF maps names to either single values or to multiple values via loops. 

38CIFDataValue = str | int | float 

39CIFData = CIFDataValue | list[CIFDataValue] 

40 

41 

42def convert_value(value: str) -> CIFDataValue: 

43 """Convert CIF value string to corresponding python type.""" 

44 value = value.strip() 

45 if re.match('(".*")|(\'.*\')$', value): 

46 return handle_subscripts(value[1:-1]) 

47 elif re.match(r'[+-]?\d+$', value): 

48 return int(value) 

49 elif re.match(r'[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$', value): 

50 return float(value) 

51 elif re.match( 

52 r'[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?\(\d+\)$', value 

53 ): 

54 return float(value[: value.index('(')]) # strip off uncertainties 

55 elif re.match( 

56 r'[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?\(\d+$', value 

57 ): 

58 warnings.warn(f'Badly formed number: "{value}"') 

59 return float(value[: value.index('(')]) # strip off uncertainties 

60 else: 

61 return handle_subscripts(value) 

62 

63 

64def parse_multiline_string(lines: list[str], line: str) -> str: 

65 """Parse semicolon-enclosed multiline string and return it.""" 

66 assert line[0] == ';' 

67 strings = [line[1:].lstrip()] 

68 while True: 

69 line = lines.pop().strip() 

70 if line[:1] == ';': 

71 break 

72 strings.append(line) 

73 return '\n'.join(strings).strip() 

74 

75 

76def parse_singletag(lines: list[str], line: str) -> tuple[str, CIFDataValue]: 

77 """Parse a CIF tag (entries starting with underscore). Returns 

78 a key-value pair.""" 

79 kv = line.split(None, 1) 

80 if len(kv) == 1: 

81 key = line 

82 line = lines.pop().strip() 

83 while not line or line[0] == '#': 

84 line = lines.pop().strip() 

85 if line[0] == ';': 

86 value = parse_multiline_string(lines, line) 

87 else: 

88 value = line 

89 else: 

90 key, value = kv 

91 return key, convert_value(value) 

92 

93 

94def parse_cif_loop_headers(lines: list[str]) -> Iterator[str]: 

95 while lines: 

96 line = lines.pop() 

97 tokens = line.split() 

98 

99 if len(tokens) == 1 and tokens[0].startswith('_'): 

100 header = tokens[0].lower() 

101 yield header 

102 else: 

103 lines.append(line) # 'undo' pop 

104 return 

105 

106 

107def parse_cif_loop_data( 

108 lines: list[str], ncolumns: int 

109) -> list[list[CIFDataValue]]: 

110 columns: list[list[CIFDataValue]] = [[] for _ in range(ncolumns)] 

111 

112 tokens = [] 

113 while lines: 

114 line = lines.pop().strip() 

115 lowerline = line.lower() 

116 if ( 

117 not line 

118 or line.startswith('_') 

119 or lowerline.startswith('data_') 

120 or lowerline.startswith('loop_') 

121 ): 

122 lines.append(line) 

123 break 

124 

125 if line.startswith('#'): 

126 continue 

127 

128 line = line.split(' #')[0] 

129 

130 if line.startswith(';'): 

131 moretokens = [parse_multiline_string(lines, line)] 

132 else: 

133 if ncolumns == 1: 

134 moretokens = [line] 

135 else: 

136 moretokens = shlex.split(line, posix=False) 

137 

138 tokens += moretokens 

139 if len(tokens) < ncolumns: 

140 continue 

141 if len(tokens) == ncolumns: 

142 for i, token in enumerate(tokens): 

143 columns[i].append(convert_value(token)) 

144 else: 

145 warnings.warn( 

146 f'Wrong number {len(tokens)} of tokens, ' 

147 f'expected {ncolumns}: {tokens}' 

148 ) 

149 

150 # (Due to continue statements we cannot move this to start of loop) 

151 tokens = [] 

152 

153 if tokens: 

154 assert len(tokens) < ncolumns 

155 raise RuntimeError( 

156 'CIF loop ended unexpectedly with incomplete row: ' 

157 f'{tokens}, expected {ncolumns} tokens' 

158 ) 

159 

160 return columns 

161 

162 

163def parse_loop(lines: list[str]) -> dict[str, list[CIFDataValue]]: 

164 """Parse a CIF loop. Returns a dict with column tag names as keys 

165 and a lists of the column content as values.""" 

166 

167 headers = list(parse_cif_loop_headers(lines)) 

168 # Dict would be better. But there can be repeated headers. 

169 

170 columns = parse_cif_loop_data(lines, len(headers)) 

171 

172 columns_dict = {} 

173 for i, header in enumerate(headers): 

174 if header in columns_dict: 

175 warnings.warn(f'Duplicated loop tags: {header}') 

176 else: 

177 columns_dict[header] = columns[i] 

178 return columns_dict 

179 

180 

181def parse_items(lines: list[str], line: str) -> dict[str, CIFData]: 

182 """Parse a CIF data items and return a dict with all tags.""" 

183 tags: dict[str, CIFData] = {} 

184 

185 while True: 

186 if not lines: 

187 break 

188 line = lines.pop().strip() 

189 if not line: 

190 continue 

191 lowerline = line.lower() 

192 if not line or line.startswith('#'): 

193 continue 

194 elif line.startswith('_'): 

195 key, value = parse_singletag(lines, line) 

196 tags[key.lower()] = value 

197 elif lowerline.startswith('loop_'): 

198 tags.update(parse_loop(lines)) 

199 elif lowerline.startswith('data_'): 

200 if line: 

201 lines.append(line) 

202 break 

203 elif line.startswith(';'): 

204 parse_multiline_string(lines, line) 

205 else: 

206 raise ValueError(f'Unexpected CIF file entry: "{line}"') 

207 return tags 

208 

209 

210class NoStructureData(RuntimeError): 

211 pass 

212 

213 

214class CIFBlock(collections.abc.Mapping): 

215 """A block (i.e., a single system) in a crystallographic information file. 

216 

217 Use this object to query CIF tags or import information as ASE objects.""" 

218 

219 cell_tags = [ 

220 '_cell_length_a', 

221 '_cell_length_b', 

222 '_cell_length_c', 

223 '_cell_angle_alpha', 

224 '_cell_angle_beta', 

225 '_cell_angle_gamma', 

226 ] 

227 

228 def __init__(self, name: str, tags: dict[str, CIFData]): 

229 self.name = name 

230 self._tags = tags 

231 

232 def __repr__(self) -> str: 

233 tags = set(self._tags) 

234 return f'CIFBlock({self.name}, tags={tags})' 

235 

236 def __getitem__(self, key: str) -> CIFData: 

237 return self._tags[key] 

238 

239 def __iter__(self) -> Iterator[str]: 

240 return iter(self._tags) 

241 

242 def __len__(self) -> int: 

243 return len(self._tags) 

244 

245 def get(self, key, default=None): 

246 return self._tags.get(key, default) 

247 

248 def get_cellpar(self) -> list | None: 

249 try: 

250 return [self[tag] for tag in self.cell_tags] 

251 except KeyError: 

252 return None 

253 

254 def get_cell(self) -> Cell: 

255 cellpar = self.get_cellpar() 

256 if cellpar is None: 

257 return Cell.new([0, 0, 0]) 

258 return Cell.new(cellpar) 

259 

260 def _raw_scaled_positions(self) -> np.ndarray | None: 

261 coords = [ 

262 self.get(name) 

263 for name in [ 

264 '_atom_site_fract_x', 

265 '_atom_site_fract_y', 

266 '_atom_site_fract_z', 

267 ] 

268 ] 

269 # XXX Shall we try to handle mixed coordinates? 

270 # (Some scaled vs others fractional) 

271 if None in coords: 

272 return None 

273 return np.array(coords).T 

274 

275 def _raw_positions(self) -> np.ndarray | None: 

276 coords = [ 

277 self.get('_atom_site_cartn_x'), 

278 self.get('_atom_site_cartn_y'), 

279 self.get('_atom_site_cartn_z'), 

280 ] 

281 if None in coords: 

282 return None 

283 return np.array(coords).T 

284 

285 def _get_site_coordinates(self): 

286 scaled = self._raw_scaled_positions() 

287 

288 if scaled is not None: 

289 return 'scaled', scaled 

290 

291 cartesian = self._raw_positions() 

292 

293 if cartesian is None: 

294 raise NoStructureData('No positions found in structure') 

295 

296 return 'cartesian', cartesian 

297 

298 def _get_symbols_with_deuterium(self): 

299 labels = self._get_any(['_atom_site_type_symbol', '_atom_site_label']) 

300 if labels is None: 

301 raise NoStructureData('No symbols') 

302 

303 symbols = [] 

304 for label in labels: 

305 if label == '.' or label == '?': 

306 raise NoStructureData('Symbols are undetermined') 

307 # Strip off additional labeling on chemical symbols 

308 match = re.search(r'([A-Z][a-z]?)', label) 

309 symbol = match.group(0) 

310 symbols.append(symbol) 

311 return symbols 

312 

313 def get_symbols(self) -> list[str]: 

314 symbols = self._get_symbols_with_deuterium() 

315 return [symbol if symbol != 'D' else 'H' for symbol in symbols] 

316 

317 def _where_deuterium(self): 

318 return np.array( 

319 [symbol == 'D' for symbol in self._get_symbols_with_deuterium()], 

320 bool, 

321 ) 

322 

323 def _get_masses(self) -> np.ndarray | None: 

324 mask = self._where_deuterium() 

325 if not any(mask): 

326 return None 

327 

328 symbols = self.get_symbols() 

329 masses = Atoms(symbols).get_masses() 

330 masses[mask] = 2.01355 

331 return masses 

332 

333 def _get_any(self, names): 

334 for name in names: 

335 if name in self: 

336 return self[name] 

337 return None 

338 

339 def _get_spacegroup_number(self): 

340 # Symmetry specification, see 

341 # http://www.iucr.org/resources/cif/dictionaries/cif_sym for a 

342 # complete list of official keys. In addition we also try to 

343 # support some commonly used depricated notations 

344 return self._get_any( 

345 [ 

346 '_space_group.it_number', 

347 '_space_group_it_number', 

348 '_symmetry_int_tables_number', 

349 ] 

350 ) 

351 

352 def _get_spacegroup_name(self): 

353 hm_symbol = self._get_any( 

354 [ 

355 '_space_group_name_h-m_alt', 

356 '_symmetry_space_group_name_h-m', 

357 '_space_group.Patterson_name_h-m', 

358 '_space_group.patterson_name_h-m', 

359 ] 

360 ) 

361 

362 hm_symbol = old_spacegroup_names.get(hm_symbol, hm_symbol) 

363 return hm_symbol 

364 

365 def _get_sitesym(self): 

366 sitesym = self._get_any( 

367 [ 

368 '_space_group_symop_operation_xyz', 

369 '_space_group_symop.operation_xyz', 

370 '_symmetry_equiv_pos_as_xyz', 

371 ] 

372 ) 

373 if isinstance(sitesym, str): 

374 sitesym = [sitesym] 

375 return sitesym 

376 

377 def _get_fractional_occupancies(self): 

378 return self.get('_atom_site_occupancy') 

379 

380 def _get_setting(self) -> int | None: 

381 setting_str = self.get('_symmetry_space_group_setting') 

382 if setting_str is None: 

383 return None 

384 

385 setting = int(setting_str) 

386 if setting not in [1, 2]: 

387 raise ValueError( 

388 f'Spacegroup setting must be 1 or 2, not {setting}' 

389 ) 

390 return setting 

391 

392 def get_spacegroup(self, subtrans_included) -> Spacegroup: 

393 # XXX The logic in this method needs serious cleaning up! 

394 no = self._get_spacegroup_number() 

395 if isinstance(no, str): 

396 # If the value was specified as "key 'value'" with ticks, 

397 # then "integer values" become strings and we'll have to 

398 # manually convert it: 

399 no = int(no) 

400 

401 hm_symbol = self._get_spacegroup_name() 

402 sitesym = self._get_sitesym() 

403 

404 if sitesym: 

405 # Special cases: sitesym can be None or an empty list. 

406 # The empty list could be replaced with just the identity 

407 # function, but it seems more correct to try to get the 

408 # spacegroup number and derive the symmetries for that. 

409 subtrans = [(0.0, 0.0, 0.0)] if subtrans_included else None 

410 

411 spacegroup = spacegroup_from_data( 

412 no=no, 

413 symbol=hm_symbol, 

414 sitesym=sitesym, 

415 subtrans=subtrans, 

416 setting=1, 

417 ) # should the setting be passed from somewhere? 

418 elif no is not None: 

419 spacegroup = no 

420 elif hm_symbol is not None: 

421 spacegroup = hm_symbol 

422 else: 

423 spacegroup = 1 

424 

425 setting_std = self._get_setting() 

426 

427 setting = 1 

428 setting_name = None 

429 if '_symmetry_space_group_setting' in self: 

430 assert setting_std is not None 

431 setting = setting_std 

432 elif '_space_group_crystal_system' in self: 

433 setting_name = self['_space_group_crystal_system'] 

434 elif '_symmetry_cell_setting' in self: 

435 setting_name = self['_symmetry_cell_setting'] 

436 

437 if setting_name: 

438 no = Spacegroup(spacegroup).no 

439 if no in rhombohedral_spacegroups: 

440 if setting_name == 'hexagonal': 

441 setting = 1 

442 elif setting_name in ('trigonal', 'rhombohedral'): 

443 setting = 2 

444 else: 

445 warnings.warn( 

446 f'unexpected crystal system {setting_name!r} ' 

447 f'for space group {spacegroup!r}' 

448 ) 

449 # FIXME - check for more crystal systems... 

450 else: 

451 warnings.warn( 

452 f'crystal system {setting_name!r} is not ' 

453 f'interpreted for space group {spacegroup!r}. ' 

454 'This may result in wrong setting!' 

455 ) 

456 

457 spg = Spacegroup(spacegroup, setting) 

458 if no is not None: 

459 assert int(spg) == no, (int(spg), no) 

460 return spg 

461 

462 def get_unsymmetrized_structure(self) -> Atoms: 

463 """Return Atoms without symmetrizing coordinates. 

464 

465 This returns a (normally) unphysical Atoms object 

466 corresponding only to those coordinates included 

467 in the CIF file, useful for e.g. debugging. 

468 

469 This method may change behaviour in the future.""" 

470 symbols = self.get_symbols() 

471 coordtype, coords = self._get_site_coordinates() 

472 

473 atoms = Atoms( 

474 symbols=symbols, cell=self.get_cell(), masses=self._get_masses() 

475 ) 

476 

477 if coordtype == 'scaled': 

478 atoms.set_scaled_positions(coords) 

479 else: 

480 assert coordtype == 'cartesian' 

481 atoms.positions[:] = coords 

482 

483 return atoms 

484 

485 def has_structure(self): 

486 """Whether this CIF block has an atomic configuration.""" 

487 try: 

488 self.get_symbols() 

489 self._get_site_coordinates() 

490 except NoStructureData: 

491 return False 

492 else: 

493 return True 

494 

495 def get_atoms( 

496 self, 

497 store_tags=False, 

498 primitive_cell=False, 

499 subtrans_included=True, 

500 fractional_occupancies=True, 

501 ) -> Atoms: 

502 """Returns an Atoms object from a cif tags dictionary. See read_cif() 

503 for a description of the arguments.""" 

504 if primitive_cell and subtrans_included: 

505 raise RuntimeError( 

506 'Primitive cell cannot be determined when sublattice ' 

507 'translations are included in the symmetry operations listed ' 

508 'in the CIF file, i.e. when `subtrans_included` is True.' 

509 ) 

510 

511 cell = self.get_cell() 

512 assert cell.rank in [0, 3] 

513 

514 kwargs: dict[str, Any] = {} 

515 if store_tags: 

516 kwargs['info'] = self._tags.copy() 

517 

518 if fractional_occupancies: 

519 occupancies = self._get_fractional_occupancies() 

520 else: 

521 occupancies = None 

522 

523 if occupancies is not None: 

524 # no warnings in this case 

525 kwargs['onduplicates'] = 'keep' 

526 

527 # The unsymmetrized_structure is not the asymmetric unit 

528 # because the asymmetric unit should have (in general) a smaller cell, 

529 # whereas we have the full cell. 

530 unsymmetrized_structure = self.get_unsymmetrized_structure() 

531 

532 if cell.rank == 3: 

533 spacegroup = self.get_spacegroup(subtrans_included) 

534 atoms = crystal( 

535 unsymmetrized_structure, 

536 spacegroup=spacegroup, 

537 setting=spacegroup.setting, 

538 occupancies=occupancies, 

539 primitive_cell=primitive_cell, 

540 **kwargs, 

541 ) 

542 else: 

543 atoms = unsymmetrized_structure 

544 if kwargs.get('info') is not None: 

545 atoms.info.update(kwargs['info']) 

546 if occupancies is not None: 

547 occ_dict = { 

548 str(i): {sym: occupancies[i]} 

549 for i, sym in enumerate(atoms.symbols) 

550 } 

551 atoms.info['occupancy'] = occ_dict 

552 

553 return atoms 

554 

555 

556def parse_block(lines: list[str], line: str) -> CIFBlock: 

557 assert line.lower().startswith('data_') 

558 blockname = line.split('_', 1)[1].rstrip() 

559 tags = parse_items(lines, line) 

560 return CIFBlock(blockname, tags) 

561 

562 

563def parse_cif(fileobj, reader='ase') -> Iterator[CIFBlock]: 

564 if reader == 'ase': 

565 return parse_cif_ase(fileobj) 

566 elif reader == 'pycodcif': 

567 return parse_cif_pycodcif(fileobj) 

568 else: 

569 raise ValueError(f'No such reader: {reader}') 

570 

571 

572def parse_cif_ase(fileobj) -> Iterator[CIFBlock]: 

573 """Parse a CIF file using ase CIF parser.""" 

574 

575 if isinstance(fileobj, str): 

576 with open(fileobj, 'rb') as fileobj: 

577 data = fileobj.read() 

578 else: 

579 data = fileobj.read() 

580 

581 if isinstance(data, bytes): 

582 data = data.decode('latin1') 

583 data = format_unicode(data) 

584 lines = [e for e in data.split('\n') if len(e) > 0] 

585 if len(lines) > 0 and lines[0].rstrip() == '#\\#CIF_2.0': 

586 warnings.warn( 

587 'CIF v2.0 file format detected; `ase` CIF reader might ' 

588 'incorrectly interpret some syntax constructions, use ' 

589 '`pycodcif` reader instead' 

590 ) 

591 lines = [''] + lines[::-1] # all lines (reversed) 

592 

593 while lines: 

594 line = lines.pop().strip() 

595 if not line or line.startswith('#'): 

596 continue 

597 

598 yield parse_block(lines, line) 

599 

600 

601def parse_cif_pycodcif(fileobj) -> Iterator[CIFBlock]: 

602 """Parse a CIF file using pycodcif CIF parser.""" 

603 if not isinstance(fileobj, str): 

604 fileobj = fileobj.name 

605 

606 try: 

607 from pycodcif import parse 

608 except ImportError: 

609 raise ImportError( 

610 'parse_cif_pycodcif requires pycodcif ' 

611 + '(http://wiki.crystallography.net/cod-tools/pycodcif/)' 

612 ) 

613 

614 data, _, _ = parse(fileobj) 

615 

616 for datablock in data: 

617 tags = datablock['values'] 

618 for tag in tags.keys(): 

619 values = [convert_value(x) for x in tags[tag]] 

620 if len(values) == 1: 

621 tags[tag] = values[0] 

622 else: 

623 tags[tag] = values 

624 yield CIFBlock(datablock['name'], tags) 

625 

626 

627def iread_cif( 

628 fileobj, 

629 index=-1, 

630 store_tags: bool = False, 

631 primitive_cell: bool = False, 

632 subtrans_included: bool = True, 

633 fractional_occupancies: bool = True, 

634 reader: str = 'ase', 

635) -> Iterator[Atoms]: 

636 # Find all CIF blocks with valid crystal data 

637 # TODO: return Atoms of the block name ``index`` if it is a string. 

638 images = [] 

639 for block in parse_cif(fileobj, reader): 

640 if not block.has_structure(): 

641 continue 

642 

643 atoms = block.get_atoms( 

644 store_tags, 

645 primitive_cell, 

646 subtrans_included, 

647 fractional_occupancies=fractional_occupancies, 

648 ) 

649 images.append(atoms) 

650 

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

652 index = slice(None, None, None) 

653 

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

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

656 

657 for atoms in images[index]: 

658 yield atoms 

659 

660 

661def read_cif( 

662 fileobj, 

663 index=-1, 

664 *, 

665 store_tags: bool = False, 

666 primitive_cell: bool = False, 

667 subtrans_included: bool = True, 

668 fractional_occupancies: bool = True, 

669 reader: str = 'ase', 

670) -> Atoms | list[Atoms]: 

671 """Read Atoms object from CIF file. 

672 

673 Parameters 

674 ---------- 

675 store_tags : bool 

676 If true, the *info* attribute of the returned Atoms object will be 

677 populated with all tags in the corresponding cif data block. 

678 primitive_cell : bool 

679 If true, the primitive cell is built instead of the conventional cell. 

680 subtrans_included : bool 

681 If true, sublattice translations are assumed to be included among the 

682 symmetry operations listed in the CIF file (seems to be the common 

683 behaviour of CIF files). 

684 Otherwise the sublattice translations are determined from setting 1 of 

685 the extracted space group. A result of setting this flag to true, is 

686 that it will not be possible to determine the primitive cell. 

687 fractional_occupancies : bool 

688 If true, the resulting atoms object will be tagged equipped with a 

689 dictionary `occupancy`. The keys of this dictionary will be integers 

690 converted to strings. The conversion to string is done in order to 

691 avoid troubles with JSON encoding/decoding of the dictionaries with 

692 non-string keys. 

693 Also, in case of mixed occupancies, the atom's chemical symbol will be 

694 that of the most dominant species. 

695 reader : str 

696 Select CIF reader. 

697 

698 * ``ase`` : built-in CIF reader (default) 

699 * ``pycodcif`` : CIF reader based on ``pycodcif`` package 

700 

701 Notes 

702 ----- 

703 Only blocks with valid crystal data will be included. 

704 """ 

705 g = iread_cif( 

706 fileobj, 

707 index, 

708 store_tags, 

709 primitive_cell, 

710 subtrans_included, 

711 fractional_occupancies, 

712 reader, 

713 ) 

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

715 # Return list of atoms 

716 return list(g) 

717 else: 

718 # Return single atoms object 

719 return next(g) 

720 

721 

722def format_cell(cell: Cell) -> str: 

723 assert cell.rank == 3 

724 lines = [] 

725 for name, value in zip(CIFBlock.cell_tags, cell.cellpar()): 

726 line = f'{name:20} {value}\n' 

727 lines.append(line) 

728 assert len(lines) == 6 

729 return ''.join(lines) 

730 

731 

732def format_generic_spacegroup_info() -> str: 

733 # We assume no symmetry whatsoever 

734 return '\n'.join( 

735 [ 

736 '_space_group_name_H-M_alt "P 1"', 

737 '_space_group_IT_number 1', 

738 '', 

739 'loop_', 

740 ' _space_group_symop_operation_xyz', 

741 " 'x, y, z'", 

742 '', 

743 ] 

744 ) 

745 

746 

747class CIFLoop: 

748 def __init__(self): 

749 self.names = [] 

750 self.formats = [] 

751 self.arrays = [] 

752 

753 def add(self, name, array, fmt): 

754 assert name.startswith('_') 

755 self.names.append(name) 

756 self.formats.append(fmt) 

757 self.arrays.append(array) 

758 if len(self.arrays[0]) != len(self.arrays[-1]): 

759 raise ValueError( 

760 f'Loop data "{name}" has {len(array)} ' 

761 'elements, expected {len(self.arrays[0])}' 

762 ) 

763 

764 def tostring(self): 

765 lines = [] 

766 append = lines.append 

767 append('loop_') 

768 for name in self.names: 

769 append(f' {name}') 

770 

771 template = ' ' + ' '.join(self.formats) 

772 

773 ncolumns = len(self.arrays) 

774 nrows = len(self.arrays[0]) if ncolumns > 0 else 0 

775 for row in range(nrows): 

776 arraydata = [array[row] for array in self.arrays] 

777 line = template.format(*arraydata) 

778 append(line) 

779 append('') 

780 return '\n'.join(lines) 

781 

782 

783@iofunction('wb') 

784def write_cif( 

785 fd, images, cif_format=None, wrap=True, labels=None, loop_keys=None 

786) -> None: 

787 r"""Write *images* to CIF file. 

788 

789 wrap: bool 

790 Wrap atoms into unit cell. 

791 

792 labels: list 

793 Use this list (shaped list[i_frame][i_atom] = string) for the 

794 '_atom_site_label' section instead of automatically generating 

795 it from the element symbol. 

796 

797 loop_keys: dict 

798 Add the information from this dictionary to the `loop\_` 

799 section. Keys are printed to the `loop\_` section preceeded by 

800 ' _'. dict[key] should contain the data printed for each atom, 

801 so it needs to have the setup `dict[key][i_frame][i_atom] = 

802 string`. The strings are printed as they are, so take care of 

803 formating. Information can be re-read using the `store_tags` 

804 option of the cif reader. 

805 

806 """ 

807 

808 if cif_format is not None: 

809 warnings.warn( 

810 'The cif_format argument is deprecated and may be ' 

811 'removed in the future. Use loop_keys to customize ' 

812 'data written in loop.', 

813 FutureWarning, 

814 ) 

815 

816 if loop_keys is None: 

817 loop_keys = {} 

818 

819 if hasattr(images, 'get_positions'): 

820 images = [images] 

821 

822 fd = io.TextIOWrapper(fd, encoding='latin-1') 

823 try: 

824 for i, atoms in enumerate(images): 

825 blockname = f'data_image{i}\n' 

826 image_loop_keys = {key: loop_keys[key][i] for key in loop_keys} 

827 

828 write_cif_image( 

829 blockname, 

830 atoms, 

831 fd, 

832 wrap=wrap, 

833 labels=None if labels is None else labels[i], 

834 loop_keys=image_loop_keys, 

835 ) 

836 

837 finally: 

838 # Using the TextIOWrapper somehow causes the file to close 

839 # when this function returns. 

840 # Detach in order to circumvent this highly illogical problem: 

841 fd.detach() 

842 

843 

844def autolabel(symbols: Sequence[str]) -> list[str]: 

845 no: dict[str, int] = {} 

846 labels = [] 

847 for symbol in symbols: 

848 if symbol in no: 

849 no[symbol] += 1 

850 else: 

851 no[symbol] = 1 

852 labels.append('%s%d' % (symbol, no[symbol])) 

853 return labels 

854 

855 

856def chemical_formula_header(atoms): 

857 counts = atoms.symbols.formula.count() 

858 formula_sum = ' '.join(f'{sym}{count}' for sym, count in counts.items()) 

859 return ( 

860 f'_chemical_formula_structural {atoms.symbols}\n' 

861 f'_chemical_formula_sum "{formula_sum}"\n' 

862 ) 

863 

864 

865class BadOccupancies(ValueError): 

866 pass 

867 

868 

869def expand_kinds(atoms, coords): 

870 # try to fetch occupancies // spacegroup_kinds - occupancy mapping 

871 symbols = list(atoms.symbols) 

872 coords = list(coords) 

873 occupancies = [1] * len(symbols) 

874 occ_info = atoms.info.get('occupancy') 

875 kinds = atoms.arrays.get('spacegroup_kinds') 

876 if occ_info is not None and kinds is not None: 

877 for i, kind in enumerate(kinds): 

878 occ_info_kind = occ_info[str(kind)] 

879 symbol = symbols[i] 

880 if symbol not in occ_info_kind: 

881 raise BadOccupancies( 

882 'Occupancies present but no occupancy info for "{symbol}"' 

883 ) 

884 occupancies[i] = occ_info_kind[symbol] 

885 # extend the positions array in case of mixed occupancy 

886 for sym, occ in occ_info[str(kind)].items(): 

887 if sym != symbols[i]: 

888 symbols.append(sym) 

889 coords.append(coords[i]) 

890 occupancies.append(occ) 

891 return symbols, coords, occupancies 

892 

893 

894def atoms_to_loop_data(atoms, wrap, labels, loop_keys): 

895 if atoms.cell.rank == 3: 

896 coord_type = 'fract' 

897 coords = atoms.get_scaled_positions(wrap).tolist() 

898 else: 

899 coord_type = 'Cartn' 

900 coords = atoms.get_positions(wrap).tolist() 

901 

902 try: 

903 symbols, coords, occupancies = expand_kinds(atoms, coords) 

904 except BadOccupancies as err: 

905 warnings.warn(str(err)) 

906 occupancies = [1] * len(atoms) 

907 symbols = list(atoms.symbols) 

908 

909 if labels is None: 

910 labels = autolabel(symbols) 

911 

912 coord_headers = [ 

913 f'_atom_site_{coord_type}_{axisname}' for axisname in 'xyz' 

914 ] 

915 

916 loopdata = {} 

917 loopdata['_atom_site_label'] = (labels, '{:<8s}') 

918 loopdata['_atom_site_occupancy'] = (occupancies, '{:6.4f}') 

919 

920 _coords = np.array(coords) 

921 for i, key in enumerate(coord_headers): 

922 loopdata[key] = (_coords[:, i], '{}') 

923 

924 loopdata['_atom_site_type_symbol'] = (symbols, '{:<2s}') 

925 loopdata['_atom_site_symmetry_multiplicity'] = ([1.0] * len(symbols), '{}') 

926 

927 for key in loop_keys: 

928 # Should expand the loop_keys like we expand the occupancy stuff. 

929 # Otherwise user will never figure out how to do this. 

930 values = [loop_keys[key][i] for i in range(len(symbols))] 

931 loopdata['_' + key] = (values, '{}') 

932 

933 return loopdata, coord_headers 

934 

935 

936def write_cif_image(blockname, atoms, fd, *, wrap, labels, loop_keys): 

937 fd.write(blockname) 

938 fd.write(chemical_formula_header(atoms)) 

939 

940 rank = atoms.cell.rank 

941 if rank == 3: 

942 fd.write(format_cell(atoms.cell)) 

943 fd.write('\n') 

944 fd.write(format_generic_spacegroup_info()) 

945 fd.write('\n') 

946 elif rank != 0: 

947 raise ValueError( 

948 'CIF format can only represent systems with ' 

949 f'0 or 3 lattice vectors. Got {rank}.' 

950 ) 

951 

952 loopdata, coord_headers = atoms_to_loop_data(atoms, wrap, labels, loop_keys) 

953 

954 headers = [ 

955 '_atom_site_type_symbol', 

956 '_atom_site_label', 

957 '_atom_site_symmetry_multiplicity', 

958 *coord_headers, 

959 '_atom_site_occupancy', 

960 ] 

961 

962 headers += ['_' + key for key in loop_keys] 

963 

964 loop = CIFLoop() 

965 for header in headers: 

966 array, fmt = loopdata[header] 

967 loop.add(header, array, fmt) 

968 

969 fd.write(loop.tostring())