Coverage for ase/formula.py: 91.45%

269 statements  

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

1import re 

2from collections.abc import Sequence 

3from functools import lru_cache 

4from math import gcd 

5from typing import Union 

6 

7from ase.data import atomic_numbers, chemical_symbols 

8 

9# For type hints (A, A2, A+B): 

10Tree = str | tuple['Tree', int] | list['Tree'] 

11 

12 

13class Formula: 

14 def __init__( 

15 self, 

16 formula: Union[str, 'Formula'] = '', 

17 *, 

18 strict: bool = False, 

19 format: str = '', 

20 _tree: Tree | None = None, 

21 _count: dict[str, int] | None = None, 

22 ): 

23 """Chemical formula object. 

24 

25 Parameters 

26 ---------- 

27 formula: str 

28 Text string representation of formula. Examples: ``'6CO2'``, 

29 ``'30Cu+2CO'``, ``'Pt(CO)6'``. 

30 strict: bool 

31 Only allow real chemical symbols. 

32 format: str 

33 Reorder according to *format*. Must be one of hill, metal, 

34 ab2, a2b, periodic or reduce. 

35 

36 Examples 

37 -------- 

38 >>> from ase.formula import Formula 

39 >>> w = Formula('H2O') 

40 >>> w.count() 

41 {'H': 2, 'O': 1} 

42 >>> 'H' in w 

43 True 

44 >>> w == 'HOH' 

45 True 

46 >>> f'{w:latex}' 

47 'H$_{2}$O' 

48 >>> w.format('latex') 

49 'H$_{2}$O' 

50 >>> divmod(6 * w + 'Cu', w) 

51 (6, Formula('Cu')) 

52 

53 Raises 

54 ------ 

55 ValueError 

56 on malformed formula 

57 """ 

58 

59 # Be sure that Formula(x) works the same whether x is string or Formula 

60 assert isinstance(formula, (str, Formula)) 

61 formula = str(formula) 

62 

63 if format: 

64 assert _tree is None and _count is None 

65 if format not in { 

66 'hill', 

67 'metal', 

68 'abc', 

69 'reduce', 

70 'ab2', 

71 'a2b', 

72 'periodic', 

73 }: 

74 raise ValueError(f'Illegal format: {format}') 

75 formula = Formula(formula).format(format) 

76 

77 self._formula = formula 

78 

79 self._tree = _tree or parse(formula) 

80 self._count = _count or count_tree(self._tree) 

81 if strict: 

82 for symbol in self._count: 

83 if symbol not in atomic_numbers: 

84 raise ValueError('Unknown chemical symbol: ' + symbol) 

85 

86 def convert(self, fmt: str) -> 'Formula': 

87 """Reformat this formula as a new Formula. 

88 

89 Same formatting rules as Formula(format=...) keyword. 

90 """ 

91 return Formula(self._formula, format=fmt) 

92 

93 def count(self) -> dict[str, int]: 

94 """Return dictionary mapping chemical symbol to number of atoms. 

95 

96 Example 

97 ------- 

98 >>> Formula('H2O').count() 

99 {'H': 2, 'O': 1} 

100 """ 

101 return self._count.copy() 

102 

103 def reduce(self) -> tuple['Formula', int]: 

104 """Reduce formula. 

105 

106 Returns 

107 ------- 

108 formula: Formula 

109 Reduced formula. 

110 n: int 

111 Number of reduced formula units. 

112 

113 Example 

114 ------- 

115 >>> Formula('2H2O').reduce() 

116 (Formula('H2O'), 2) 

117 """ 

118 dct, N = self._reduce() 

119 return self.from_dict(dct), N 

120 

121 def stoichiometry(self) -> tuple['Formula', 'Formula', int]: 

122 """Reduce to unique stoichiometry using "chemical symbols" A, B, C, ... 

123 

124 Examples 

125 -------- 

126 >>> Formula('CO2').stoichiometry() 

127 (Formula('AB2'), Formula('CO2'), 1) 

128 >>> Formula('(H2O)4').stoichiometry() 

129 (Formula('AB2'), Formula('OH2'), 4) 

130 """ 

131 count1, N = self._reduce() 

132 c = ord('A') 

133 count2 = {} 

134 count3 = {} 

135 for n, symb in sorted((n, symb) for symb, n in count1.items()): 

136 count2[chr(c)] = n 

137 count3[symb] = n 

138 c += 1 

139 return self.from_dict(count2), self.from_dict(count3), N 

140 

141 def format(self, fmt: str = '') -> str: 

142 """Format formula as string. 

143 

144 Formats: 

145 

146 * ``'hill'``: alphabetically ordered with C and H first 

147 * ``'metal'``: alphabetically ordered with metals first 

148 * ``'ab2'``: count-ordered first then alphabetically ordered 

149 * ``'abc'``: old name for ``'ab2'`` 

150 * ``'a2b'``: reverse count-ordered first then alphabetically ordered 

151 * ``'periodic'``: periodic-table ordered: period first then group 

152 * ``'reduce'``: Reduce and keep order (ABBBC -> AB3C) 

153 * ``'latex'``: LaTeX representation 

154 * ``'html'``: HTML representation 

155 * ``'rest'``: reStructuredText representation 

156 

157 Example 

158 ------- 

159 >>> Formula('H2O').format('html') 

160 'H<sub>2</sub>O' 

161 """ 

162 return format(self, fmt) 

163 

164 def __format__(self, fmt: str) -> str: 

165 """Format Formula as str. 

166 

167 Possible formats: ``'hill'``, ``'metal'``, ``'abc'``, ``'reduce'``, 

168 ``'latex'``, ``'html'``, ``'rest'``. 

169 

170 Example 

171 ------- 

172 >>> f = Formula('OH2') 

173 >>> '{f}, {f:hill}, {f:latex}'.format(f=f) 

174 'OH2, H2O, OH$_{2}$' 

175 """ 

176 

177 if fmt == 'hill': 

178 count = self.count() 

179 count2 = {symb: count.pop(symb) for symb in 'CH' if symb in count} 

180 for symb, n in sorted(count.items()): 

181 count2[symb] = n 

182 return dict2str(count2) 

183 

184 if fmt == 'metal': 

185 count = self.count() 

186 result2 = [(s, count.pop(s)) for s in non_metals if s in count] 

187 result = [(s, count[s]) for s in sorted(count)] 

188 result += sorted(result2) 

189 return dict2str(dict(result)) 

190 

191 if fmt == 'abc' or fmt == 'ab2': 

192 _, f, N = self.stoichiometry() 

193 return dict2str({symb: n * N for symb, n in f._count.items()}) 

194 

195 if fmt == 'a2b': 

196 _, f, N = self.stoichiometry() 

197 return dict2str( 

198 { 

199 symb: -n * N 

200 for n, symb in sorted( 

201 [(-n, symb) for symb, n in f._count.items()] 

202 ) 

203 } 

204 ) 

205 

206 if fmt == 'periodic': 

207 count = self.count() 

208 order = periodic_table_order() 

209 items = sorted( 

210 count.items(), key=lambda item: order.get(item[0], 0) 

211 ) 

212 return ''.join( 

213 symb + (str(n) if n > 1 else '') for symb, n in items 

214 ) 

215 

216 if fmt == 'reduce': 

217 symbols = list(self) 

218 nsymb = len(symbols) 

219 parts = [] 

220 i1 = 0 

221 for i2, symbol in enumerate(symbols): 

222 if i2 == nsymb - 1 or symbol != symbols[i2 + 1]: 

223 parts.append(symbol) 

224 m = i2 + 1 - i1 

225 if m > 1: 

226 parts.append(str(m)) 

227 i1 = i2 + 1 

228 return ''.join(parts) 

229 

230 if fmt == 'latex': 

231 return self._tostr('$_{', '}$') 

232 

233 if fmt == 'html': 

234 return self._tostr('<sub>', '</sub>') 

235 

236 if fmt == 'rest': 

237 return self._tostr(r'\ :sub:`', r'`\ ') 

238 

239 if fmt == '': 

240 return self._formula 

241 

242 raise ValueError('Invalid format specifier') 

243 

244 @staticmethod 

245 def from_dict(dct: dict[str, int]) -> 'Formula': 

246 """Convert dict to Formula. 

247 

248 >>> Formula.from_dict({'H': 2}) 

249 Formula('H2') 

250 """ 

251 dct2 = {} 

252 for symb, n in dct.items(): 

253 if not (isinstance(symb, str) and isinstance(n, int) and n >= 0): 

254 raise ValueError(f'Bad dictionary: {dct}') 

255 if n > 0: # filter out n=0 symbols 

256 dct2[symb] = n 

257 return Formula( 

258 dict2str(dct2), 

259 _tree=[([(symb, n) for symb, n in dct2.items()], 1)], 

260 _count=dct2, 

261 ) 

262 

263 @staticmethod 

264 def from_list(symbols: Sequence[str]) -> 'Formula': 

265 """Convert list of chemical symbols to Formula.""" 

266 return Formula(''.join(symbols), _tree=[(symbols[:], 1)]) # type: ignore[list-item] 

267 

268 def __len__(self) -> int: 

269 """Number of atoms.""" 

270 return sum(self._count.values()) 

271 

272 def __getitem__(self, symb: str) -> int: 

273 """Number of atoms with chemical symbol *symb*.""" 

274 return self._count.get(symb, 0) 

275 

276 def __contains__(self, f: Union[str, 'Formula']) -> bool: 

277 """Check if formula contains chemical symbols in *f*. 

278 

279 Type of *f* must be str or Formula. 

280 

281 Examples 

282 -------- 

283 >>> 'OH' in Formula('H2O') 

284 True 

285 >>> 'O2' in Formula('H2O') 

286 False 

287 """ 

288 if isinstance(f, str): 

289 f = Formula(f) 

290 for symb, n in f._count.items(): 

291 if self[symb] < n: 

292 return False 

293 return True 

294 

295 def __eq__(self, other) -> bool: 

296 """Equality check. 

297 

298 Note that order is not important. 

299 

300 Example 

301 ------- 

302 >>> Formula('CO') == Formula('OC') 

303 True 

304 """ 

305 if isinstance(other, str): 

306 other = Formula(other) 

307 elif not isinstance(other, Formula): 

308 return False 

309 return self._count == other._count 

310 

311 def __add__(self, other: Union[str, 'Formula']) -> 'Formula': 

312 """Add two formulas.""" 

313 if not isinstance(other, str): 

314 other = other._formula 

315 return Formula(self._formula + '+' + other) 

316 

317 def __radd__(self, other: str): # -> Formula 

318 return Formula(other) + self 

319 

320 def __mul__(self, N: int) -> 'Formula': 

321 """Repeat formula `N` times.""" 

322 if N == 0: 

323 return Formula('') 

324 return self.from_dict({symb: n * N for symb, n in self._count.items()}) 

325 

326 def __rmul__(self, N: int): # -> Formula 

327 return self * N 

328 

329 def __divmod__(self, other: Union['Formula', str]) -> tuple[int, 'Formula']: 

330 """Return the tuple (self // other, self % other). 

331 

332 Invariant:: 

333 

334 div, mod = divmod(self, other) 

335 div * other + mod == self 

336 

337 Example 

338 ------- 

339 >>> divmod(Formula('H2O'), 'H') 

340 (2, Formula('O')) 

341 """ 

342 if isinstance(other, str): 

343 other = Formula(other) 

344 N = min(self[symb] // n for symb, n in other._count.items()) 

345 dct = self.count() 

346 if N: 

347 for symb, n in other._count.items(): 

348 dct[symb] -= n * N 

349 if dct[symb] == 0: 

350 del dct[symb] 

351 return N, self.from_dict(dct) 

352 

353 def __rdivmod__(self, other): 

354 return divmod(Formula(other), self) 

355 

356 def __mod__(self, other): 

357 return divmod(self, other)[1] 

358 

359 def __rmod__(self, other): 

360 return Formula(other) % self 

361 

362 def __floordiv__(self, other): 

363 return divmod(self, other)[0] 

364 

365 def __rfloordiv__(self, other): 

366 return Formula(other) // self 

367 

368 def __iter__(self): 

369 return self._tree_iter() 

370 

371 def _tree_iter(self, tree=None): 

372 if tree is None: 

373 tree = self._tree 

374 if isinstance(tree, str): 

375 yield tree 

376 elif isinstance(tree, tuple): 

377 tree, N = tree 

378 for _ in range(N): 

379 yield from self._tree_iter(tree) 

380 else: 

381 for tree in tree: 

382 yield from self._tree_iter(tree) 

383 

384 def __str__(self): 

385 return self._formula 

386 

387 def __repr__(self): 

388 return f'Formula({self._formula!r})' 

389 

390 def _reduce(self): 

391 N = 0 

392 for n in self._count.values(): 

393 if N == 0: 

394 N = n 

395 else: 

396 N = gcd(n, N) 

397 dct = {symb: n // N for symb, n in self._count.items()} 

398 return dct, N 

399 

400 def _tostr(self, sub1, sub2): 

401 parts = [] 

402 for tree, n in self._tree: 

403 s = tree2str(tree, sub1, sub2) 

404 if s[0] == '(' and s[-1] == ')': 

405 s = s[1:-1] 

406 if n > 1: 

407 s = str(n) + s 

408 parts.append(s) 

409 return '+'.join(parts) 

410 

411 

412def dict2str(dct: dict[str, int]) -> str: 

413 """Convert symbol-to-number dict to str. 

414 

415 >>> dict2str({'A': 1, 'B': 2}) 

416 'AB2' 

417 """ 

418 return ''.join(symb + (str(n) if n > 1 else '') for symb, n in dct.items()) 

419 

420 

421def parse(f: str) -> Tree: 

422 """Convert formula string to tree structure. 

423 

424 >>> parse('2A+BC2') 

425 [('A', 2), (['B', ('C', 2)], 1)] 

426 """ 

427 if not f: 

428 return [] 

429 parts = f.split('+') 

430 result = [] 

431 for part in parts: 

432 n, f = strip_number(part) 

433 result.append((parse2(f), n)) 

434 return result # type: ignore[return-value] 

435 

436 

437def parse2(f: str) -> Tree: 

438 """Convert formula string to tree structure (no "+" symbols). 

439 

440 >>> parse('10(H2O)') 

441 [(([('H', 2), 'O'], 1), 10)] 

442 """ 

443 units = [] 

444 while f: 

445 unit: str | tuple[str, int] | Tree 

446 if f[0] == '(': 

447 level = 0 

448 for i, c in enumerate(f[1:], 1): 

449 if c == '(': 

450 level += 1 

451 elif c == ')': 

452 if level == 0: 

453 break 

454 level -= 1 

455 else: 

456 raise ValueError 

457 f2 = f[1:i] 

458 n, f = strip_number(f[i + 1 :]) 

459 unit = (parse2(f2), n) 

460 else: 

461 m = re.match('([A-Z][a-z]?)([0-9]*)', f) 

462 if m is None: 

463 raise ValueError 

464 symb = m.group(1) 

465 number = m.group(2) 

466 if number: 

467 unit = (symb, int(number)) 

468 else: 

469 unit = symb 

470 f = f[m.end() :] 

471 units.append(unit) 

472 if len(units) == 1: 

473 return unit 

474 return units 

475 

476 

477def strip_number(s: str) -> tuple[int, str]: 

478 """Strip leading nuimber. 

479 

480 >>> strip_number('10AB2') 

481 (10, 'AB2') 

482 >>> strip_number('AB2') 

483 (1, 'AB2') 

484 """ 

485 m = re.match('[0-9]*', s) 

486 assert m is not None 

487 return int(m.group() or 1), s[m.end() :] 

488 

489 

490def tree2str(tree: Tree, sub1: str, sub2: str) -> str: 

491 """Helper function for html, latex and rest formats.""" 

492 if isinstance(tree, str): 

493 return tree 

494 if isinstance(tree, tuple): 

495 tree, N = tree 

496 s = tree2str(tree, sub1, sub2) 

497 if N == 1: 

498 if s[0] == '(' and s[-1] == ')': 

499 return s[1:-1] 

500 return s 

501 return s + sub1 + str(N) + sub2 

502 return '(' + ''.join(tree2str(tree, sub1, sub2) for tree in tree) + ')' 

503 

504 

505def count_tree(tree: Tree) -> dict[str, int]: 

506 if isinstance(tree, str): 

507 return {tree: 1} 

508 if isinstance(tree, tuple): 

509 tree, N = tree 

510 return {symb: n * N for symb, n in count_tree(tree).items()} 

511 dct = {} # type: dict[str, int] 

512 for tree in tree: 

513 for symb, n in count_tree(tree).items(): 

514 m = dct.get(symb, 0) 

515 dct[symb] = m + n 

516 return dct 

517 

518 

519# non metals, half-metals/metalloid, halogen, noble gas: 

520non_metals = [ 

521 'H', 

522 'He', 

523 'B', 

524 'C', 

525 'N', 

526 'O', 

527 'F', 

528 'Ne', 

529 'Si', 

530 'P', 

531 'S', 

532 'Cl', 

533 'Ar', 

534 'Ge', 

535 'As', 

536 'Se', 

537 'Br', 

538 'Kr', 

539 'Sb', 

540 'Te', 

541 'I', 

542 'Xe', 

543 'Po', 

544 'At', 

545 'Rn', 

546] 

547 

548 

549@lru_cache 

550def periodic_table_order() -> dict[str, int]: 

551 """Create dict for sorting after period first then row.""" 

552 return { 

553 symbol: n 

554 for n, symbol in enumerate( 

555 chemical_symbols[87:] 

556 + chemical_symbols[55:87] 

557 + chemical_symbols[37:55] 

558 + chemical_symbols[19:37] 

559 + chemical_symbols[11:19] 

560 + chemical_symbols[3:11] 

561 + chemical_symbols[1:3] 

562 ) 

563 } 

564 

565 

566# Backwards compatibility: 

567def formula_hill(numbers, empirical=False): 

568 """Convert list of atomic numbers to a chemical formula as a string. 

569 

570 Elements are alphabetically ordered with C and H first. 

571 

572 If argument `empirical`, element counts will be divided by greatest common 

573 divisor to yield an empirical formula""" 

574 symbols = [chemical_symbols[Z] for Z in numbers] 

575 f = Formula('', _tree=[(symbols, 1)]) 

576 if empirical: 

577 f, _ = f.reduce() 

578 return f.format('hill') 

579 

580 

581# Backwards compatibility: 

582def formula_metal(numbers, empirical=False): 

583 """Convert list of atomic numbers to a chemical formula as a string. 

584 

585 Elements are alphabetically ordered with metals first. 

586 

587 If argument `empirical`, element counts will be divided by greatest common 

588 divisor to yield an empirical formula""" 

589 symbols = [chemical_symbols[Z] for Z in numbers] 

590 f = Formula('', _tree=[(symbols, 1)]) 

591 if empirical: 

592 f, _ = f.reduce() 

593 return f.format('metal')