Coverage for ase/pourbaix.py: 92.46%

398 statements  

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

1import functools 

2import re 

3from collections import Counter 

4from dataclasses import dataclass 

5from fractions import Fraction 

6from itertools import chain, combinations, product 

7 

8import numpy as np 

9from scipy.linalg import null_space 

10 

11from ase.formula import Formula 

12from ase.units import kB 

13 

14CONST = kB * np.log(10) # Nernst constant 

15 

16PREDEF_ENERGIES = { # Default chemical potentials 

17 'H+': 0.0, # for water, protons and electrons 

18 'e-': 0.0, 

19 'H2O': -2.4583, 

20} 

21 

22U_STD_AGCL = 0.222 # Standard redox potential of AgCl electrode 

23U_STD_SCE = 0.244 # Standard redox potential of SCE electrode 

24 

25 

26def parse_formula(formula: str, fmt: str = 'metal'): 

27 aq = formula.endswith('(aq)') 

28 charge = formula.count('+') - formula.count('-') 

29 formula_strip = formula.replace('(aq)', '').rstrip('+-') 

30 formula_obj = Formula(formula_strip, format=fmt) 

31 return formula_obj, charge, aq 

32 

33 

34def initialize_refs(refs_dct, reduce=False, fmt='metal'): 

35 """Convert dictionary entries to Species instances""" 

36 refs = {} 

37 for label, energy in refs_dct.items(): 

38 spec = Species.from_string(label, energy, reduce, fmt) 

39 refs[label] = spec 

40 return refs 

41 

42 

43def get_product_combos(reactant, refs): 

44 """Obtain all possible combinations of products. 

45 

46 Obtain - from the available references and based 

47 on the stoichiometry of the target material (reactant) - 

48 different combinations of products to be inserted 

49 in (electro)chemical reactions. 

50 """ 

51 ref_elem = reactant._main_elements 

52 allcombos = [[] for _ in range(len(ref_elem))] 

53 for ref in refs.values(): 

54 contained = ref.contains(ref_elem) 

55 for w in np.argwhere(contained).flatten(): 

56 allcombos[w].append(ref) 

57 return [np.unique(combo) for combo in product(*allcombos)] 

58 

59 

60def get_phases(reactant, refs, T, conc, reference, tol=1e-3): 

61 """Obtain all the possible decomposition pathways 

62 for a given reactant as a collection of RedOx objects. 

63 """ 

64 phases = [] 

65 phase_matrix = [] 

66 

67 for products in get_product_combos(reactant, refs): 

68 phase = RedOx.from_species(reactant, products, T, conc, reference, tol) 

69 if phase is not None: 

70 phases.append(phase) 

71 phase_matrix.append(phase._vector) 

72 

73 if len(phase_matrix) == 0: 

74 raise ValueError( 

75 'No valid decomposition pathways have been found' 

76 + ' given this set of references.' 

77 ) 

78 

79 return phases, np.array(phase_matrix).astype('float64') 

80 

81 

82def get_main_products(count): 

83 """Obtain the reaction products excluded protons, 

84 water and electrons. 

85 """ 

86 return [ 

87 spec 

88 for spec, coef in count.items() 

89 if coef > 0 and spec not in ['H+', 'H2O', 'e-'] 

90 ] 

91 

92 

93def format_label(count) -> str: 

94 """Obtain phase labels formatted in LaTeX math style.""" 

95 formatted = [] 

96 for prod in get_main_products(count): 

97 label = re.sub(r'(\S)([+-]+)', r'\1$^{\2}$', prod) 

98 label = re.sub(r'(\d+)', r'$_{\1}$', label) 

99 for symbol in ['+', '-']: 

100 count = label.count(symbol) 

101 if count > 1: 

102 label = label.replace(count * symbol, f'{count}{symbol}') 

103 if count == 1: 

104 label = label.replace(count * symbol, symbol) 

105 formatted.append(label) 

106 return ', '.join(f for f in formatted) 

107 

108 

109def make_coeff_nice(coeff, max_denom) -> str: 

110 """Convert a fraction into a string while limiting the denominator""" 

111 frac = abs(Fraction(coeff).limit_denominator(max_denom)) 

112 if frac.numerator == frac.denominator: 

113 return '' 

114 return str(frac) 

115 

116 

117def add_numbers(ax, text) -> None: 

118 """Add number identifiers to the different domains of a Pourbaix diagram.""" 

119 import matplotlib.patheffects as pfx 

120 

121 for i, (x, y, _) in enumerate(text): 

122 txt = ax.text(y, x, f'{i}', fontsize=20, horizontalalignment='center') 

123 txt.set_path_effects([pfx.withStroke(linewidth=2.0, foreground='w')]) 

124 

125 

126def add_labels(ax, text) -> None: 

127 """Add phase labels to the different domains of a Pourbaix diagram.""" 

128 import matplotlib.patheffects as pfx 

129 

130 for i, (x, y, species) in enumerate(text): 

131 label = format_label(species) 

132 annotation = ax.annotate( 

133 label, 

134 xy=(y, x), 

135 color='w', 

136 fontsize=16, 

137 horizontalalignment='center', 

138 ) 

139 annotation.set_path_effects( 

140 [pfx.withStroke(linewidth=2.0, foreground='k')] 

141 ) 

142 annotation.draggable() 

143 ax.add_artist(annotation) 

144 

145 

146def wrap_text(text) -> str: 

147 import textwrap 

148 

149 textlines = [] 

150 for i, (_, _, species) in enumerate(text): 

151 label = format_label(species) 

152 textlines.append( 

153 textwrap.fill( 

154 f'({i}) {label}', width=40, subsequent_indent=' ' 

155 ) 

156 ) 

157 return '\n'.join(textlines) 

158 

159 

160def add_phase_labels(fig, text, offset=0.0): 

161 """Add phase labels to the right of the diagram""" 

162 

163 fig.text( 

164 0.75 + offset, 0.5, wrap_text(text), fontsize=16, va='center', ha='left' 

165 ) 

166 

167 

168def add_redox_lines(axes, pH, reference, color='k') -> None: 

169 """Add water redox potentials to a Pourbaix diagram""" 

170 const = -0.5 * PREDEF_ENERGIES['H2O'] 

171 corr = { 

172 'SHE': 0, 

173 'RHE': 0, 

174 'Pt': 0, 

175 'AgCl': -U_STD_AGCL, 

176 'SCE': -U_STD_SCE, 

177 } 

178 kwargs = {'c': color, 'ls': '--', 'zorder': 2} 

179 if reference in ['SHE', 'AgCl', 'SCE']: 

180 slope = -59.2e-3 

181 axes.plot(pH, slope * pH + corr[reference], **kwargs) 

182 axes.plot(pH, slope * pH + const + corr[reference], **kwargs) 

183 elif reference in ['Pt', 'RHE']: 

184 axes.axhline(0 + corr[reference], **kwargs) 

185 axes.axhline(const + corr[reference], **kwargs) 

186 else: 

187 raise ValueError('The specified reference electrode doesnt exist') 

188 

189 

190@functools.total_ordering 

191class Species: 

192 """Class representing an individual chemical species, 

193 grouping relevant properties. 

194 

195 Initialization 

196 -------------- 

197 name: str 

198 A label representing the species 

199 

200 formula: Formula 

201 

202 charge: int 

203 the electric charge of the species, if ionic 

204 

205 aq: bool 

206 whether the species is solid (False) 

207 or acqueous (True) 

208 

209 energy: float 

210 the chemical potential of the species 

211 """ 

212 

213 def __init__( 

214 self, name: str, formula: Formula, charge: int, aq: bool, energy: float 

215 ): 

216 

217 self.name = name 

218 self.formula = formula 

219 self.energy = energy 

220 self.charge = charge 

221 self.aq = aq 

222 

223 self.count = formula.count() 

224 self.natoms = sum(self.count.values()) 

225 self._main_elements = [ 

226 e for e in self.count.keys() if e not in ['H', 'O'] 

227 ] 

228 

229 def __eq__(self, other): 

230 if not isinstance(other, Species): 

231 return NotImplemented 

232 return self.name == other.name 

233 

234 def __lt__(self, other): 

235 if not isinstance(other, Species): 

236 return NotImplemented 

237 return self.name < other.name 

238 

239 @classmethod 

240 def from_string( 

241 cls, string: str, energy: float, reduce: bool = True, fmt: str = 'metal' 

242 ): 

243 """Initialize the class provided a formula and an energy. 

244 

245 string: str 

246 The chemical formula of the species (e.g. ``ZnO``). 

247 For solid species, the formula is automatically reduced to the 

248 unit formula, and the chemical potential normalized accordingly. 

249 Acqueous species are specified by expliciting 

250 all the positive or negative charges and by appending ``(aq)``. 

251 Parentheses for grouping functional groups are acceptable. 

252 e.g. 

253 Be3(OH)3[3+] ➜ wrong 

254 Be3(OH)3+++ ➜ wrong 

255 Be3(OH)3+++(aq) ➜ correct 

256 Be3O3H3+++(aq) ➜ correct 

257 

258 energy: float 

259 the energy (chemical potential) associated with the species. 

260 

261 reduce: bool 

262 reduce to the unit formula and normalize the energy accordingly. 

263 Formulae and energies of acqueous species are never reduced. 

264 

265 fmt: str 

266 Formula formatting according to the available options in 

267 ase.formula.Formula 

268 """ 

269 formula, charge, aq = parse_formula(string, fmt=fmt) 

270 if not aq: 

271 if reduce: 

272 formula, n_fu = formula.reduce() 

273 energy /= n_fu 

274 name = str(formula) 

275 else: 

276 name = string 

277 return cls(name, formula, charge, aq, energy) 

278 

279 def get_chemsys(self): 

280 """Get the possible combinations of elements based 

281 on the stoichiometry. Useful for database queries. 

282 """ 

283 elements = set(self.count.keys()) 

284 elements.update(['H', 'O']) 

285 chemsys = list( 

286 chain.from_iterable( 

287 [combinations(elements, i + 1) for i in range(len(elements))] 

288 ) 

289 ) 

290 return chemsys 

291 

292 def balance_electrochemistry(self): 

293 """Obtain number of H2O, H+, e- "carried" by the species 

294 in electrochemical reactions. 

295 """ 

296 n_H2O = -self.count.get('O', 0) 

297 n_H = -2 * n_H2O - self.count.get('H', 0) 

298 n_e = n_H + self.charge 

299 return n_H2O, n_H, n_e 

300 

301 def _count_array(self, elements): 

302 return np.array([self.count.get(e, 0) for e in elements]) 

303 

304 def contains(self, elements): 

305 return [elem in self._main_elements for elem in elements] 

306 

307 def get_fractional_composition(self, elements): 

308 """Obtain the fractional content of each element.""" 

309 N_all = sum(self.count.values()) 

310 N_elem = sum([self.count.get(e, 0) for e in elements]) 

311 return N_elem / N_all 

312 

313 def __repr__(self): 

314 return f'Species({self.name})' 

315 

316 

317class RedOx: 

318 def __init__(self, species, coeffs, T=298.15, conc=1e-6, reference='SHE'): 

319 """RedOx class representing an (electro)chemical reaction. 

320 

321 Initialization 

322 -------------- 

323 

324 species: list[Species] 

325 The reactant and products excluded H2O, protons and electrons. 

326 

327 coeffs: list[float] 

328 The stoichiometric coefficients of the above species. 

329 Positive coefficients are associated with the products, 

330 negative coefficients with the reactants. 

331 

332 T: float 

333 The temperature in Kelvin. Default: 298.15 K. 

334 

335 conc: float 

336 The concentration of ionic species. Default: 1.0e-6 M. 

337 

338 reference: str 

339 The reference electrode. Default: SHE. 

340 available options: SHE, RHE, AgCl, Pt. 

341 

342 

343 Relevant methods 

344 ---------------- 

345 

346 from_species(reactant, products, T, conc, reference) 

347 Initialize the class from the reactant as a Species object 

348 and the product(s) a list of Species objects. 

349 

350 equation() 

351 Print the chemical equation of the reaction. 

352 

353 get_free_energy(U, pH): 

354 Obtain the reaction free energy at a given 

355 applied potential (U) and pH. 

356 

357 """ 

358 self.species = species 

359 self.coeffs = coeffs 

360 self.T = T 

361 self.conc = conc 

362 self.reference = reference 

363 self.count = Counter() 

364 

365 alpha = CONST * T # 0.059 eV @ T=298.15K 

366 const_term = 0 

367 pH_term = 0 

368 U_term = 0 

369 

370 for spec, coef in zip(species, coeffs): 

371 self.count[spec.name] = coef 

372 amounts = spec.balance_electrochemistry() 

373 

374 const_term += coef * ( 

375 spec.energy + alpha * (spec.aq * np.log10(conc)) 

376 ) 

377 pH_term += -coef * alpha * amounts[1] 

378 U_term += -coef * amounts[2] 

379 

380 for name, n in zip(['H2O', 'H+', 'e-'], amounts): 

381 const_term += coef * n * PREDEF_ENERGIES[name] 

382 self.count[name] += coef * n 

383 

384 const_corr, pH_corr = self.get_ref_correction(reference, alpha) 

385 self._vector = [ 

386 float(const_term + const_corr), 

387 float(U_term), 

388 float(pH_term + pH_corr), 

389 ] 

390 

391 @classmethod 

392 def from_species( 

393 cls, 

394 reactant, 

395 products, 

396 T: float = 298.15, 

397 conc: float = 1e-6, 

398 reference: str = 'SHE', 

399 tol: float = 1e-3, 

400 ): 

401 """Initialize the class from a combination of 

402 reactant and products. The stoichiometric 

403 coefficients are automatically determined. 

404 

405 reactant: Species 

406 products: list[Species] 

407 """ 

408 reac_elem = reactant._main_elements 

409 reac_count = [-reactant._count_array(reac_elem)] 

410 prod_count = [p._count_array(reac_elem) for p in products] 

411 elem_matrix = np.array(reac_count + prod_count).T 

412 coeffs = null_space(elem_matrix).flatten() 

413 

414 if len(coeffs) > 0 and all(coeffs > tol): 

415 coeffs /= coeffs[0] 

416 coeffs[0] = -coeffs[0] 

417 species = (reactant, *products) 

418 phase = cls(species, coeffs, T, conc, reference) 

419 return phase 

420 

421 return None 

422 

423 def get_ref_correction( 

424 self, reference: str, alpha: float 

425 ) -> tuple[float, float]: 

426 """Correct the constant and pH contributions to the reaction free energy 

427 based on the reference electrode of choice and the temperature 

428 (alpha=k_B*T*ln(10)) 

429 """ 

430 n_e = self.count['e-'] 

431 gibbs_corr = 0.0 

432 pH_corr = 0.0 

433 if reference in ['RHE', 'Pt']: 

434 pH_corr += n_e * alpha 

435 if reference == 'Pt' and n_e < 0: 

436 gibbs_corr += n_e * 0.5 * PREDEF_ENERGIES['H2O'] 

437 if reference == 'AgCl': 

438 gibbs_corr -= n_e * U_STD_AGCL 

439 if reference == 'SCE': 

440 gibbs_corr -= n_e * U_STD_SCE 

441 

442 return gibbs_corr, pH_corr 

443 

444 def equation(self, max_denom: int = 50) -> str: 

445 """Print the chemical reaction.""" 

446 

447 reactants = [] 

448 products = [] 

449 for s, n in self.count.items(): 

450 if abs(n) <= 1e-6: 

451 continue 

452 nice_coeff = make_coeff_nice(n, max_denom) 

453 substr = f'{nice_coeff}{s}' 

454 if n > 0: 

455 products.append(substr) 

456 else: 

457 reactants.append(substr) 

458 

459 return ' ➜ '.join([' + '.join(reactants), ' + '.join(products)]) 

460 

461 def get_free_energy(self, U: float, pH: float) -> float: 

462 """Evaluate the reaction free energy 

463 at a given applied potential U and pH""" 

464 return self._vector[0] + self._vector[1] * U + self._vector[2] * pH 

465 

466 

467class Pourbaix: 

468 """Pourbaix class for acqueous stability evaluations. 

469 

470 Allows to determine the most stable phase in a given set 

471 of pH and potential conditions and to evaluate a complete diagram. 

472 

473 Initialization 

474 -------------- 

475 

476 material_name: str 

477 The formula of the target material. It is preferrable 

478 to provide the reduced formula (e.g. RuO2 instad of Ru2O4). 

479 

480 refs_dct: dict 

481 A dictionary containing the formulae of the target material 

482 and its competing phases (solid and/or ionic) as keys, 

483 and their formation energies as values. 

484 

485 T: float 

486 Temperature in Kelvin. Default: 298.15 K. 

487 

488 conc: float 

489 Concentration of the ionic species. Default: 1e-6 mol/L. 

490 

491 reference: str 

492 The reference electrode. Default: SHE. 

493 available options: SHE, RHE, AgCl, Pt. 

494 

495 

496 Relevant methods 

497 ---------------- 

498 

499 get_pourbaix_energy(U, pH) 

500 obtain the energy of the target material 

501 relative to the most stable phase at a given potential U and pH. 

502 If negative, the target material can be regarded as stable. 

503 plot(...) 

504 plot a complete Pourbaix diagram in a given pH and potential window. 

505 

506 

507 Relevant attributes 

508 ------------------- 

509 

510 material: Species 

511 the target material as a Species object 

512 

513 phases: list[RedOx] 

514 the available decomposition reactions of the target material 

515 into its competing phases as a list of RedOx objects. 

516 

517 """ 

518 

519 def __init__( 

520 self, 

521 material_name: str, 

522 refs_dct: dict, 

523 T: float = 298.15, 

524 conc: float = 1.0e-6, 

525 reference: str = 'SHE', 

526 ): 

527 

528 self.material_name = material_name 

529 self.refs = refs_dct 

530 self.T = T 

531 self.conc = conc 

532 self.reference = reference 

533 

534 refs = initialize_refs(refs_dct) 

535 self.material = refs.pop(material_name) 

536 self.phases, phase_matrix = get_phases( 

537 self.material, refs, T, conc, reference 

538 ) 

539 self._const = phase_matrix[:, 0] 

540 self._var = phase_matrix[:, 1:] 

541 

542 def _decompose(self, U, pH): 

543 """Evaluate the reaction energy for decomposing 

544 the target material into each of the available products 

545 at a given pH and applied potential. 

546 

547 Example: 

548 -------- 

549 >>> from ase.phasediagram import solvated 

550 >>> from ase.pourbaix import Pourbaix 

551 >>> refs = solvated('CoO') + [ 

552 ... ('Co', 0.0), 

553 ... ('CoO', -2.509), 

554 ... ('Co3O4', -9.402)] 

555 >>> pb = Pourbaix('CoO',dict(refs)) 

556 >>> energy = pb._decompose(U=1.5, pH=0) 

557 """ 

558 return self._const + np.dot(self._var, [U, pH]) 

559 

560 def _get_pourbaix_energy(self, U, pH): 

561 """Evaluate the Pourbaix energy""" 

562 energies = self._decompose(U, pH) 

563 i_min = np.argmin(energies) 

564 return -energies[i_min], i_min 

565 

566 def get_pourbaix_energy(self, U, pH, verbose=False): 

567 """Evaluate the Pourbaix energy, print info about 

568 the most stable phase and the corresponding energy at 

569 a given potential U and pH. 

570 

571 The Pourbaix energy represents the energy of the target material 

572 relative to the most stable competing phase. If negative, 

573 the target material can be considered as stable. 

574 """ 

575 energy, index = self._get_pourbaix_energy(U, pH) 

576 phase = self.phases[index] 

577 if verbose: 

578 if energy <= 0.0: 

579 print(f'{self.material.name} is stable.') 

580 else: 

581 print(f'Stable phase: \n{phase.equation()}') 

582 print(f'Energy: {energy:.3f} eV') 

583 return energy, phase 

584 

585 def get_equations(self, contains: str | None = None): 

586 """Print the chemical reactions of the available phases. 

587 

588 the argument `contains' allows to filter for phases containing a 

589 particular species 

590 e.g. get_equations(contains='ZnO') 

591 """ 

592 equations = [] 

593 for i, p in enumerate(self.phases): 

594 if contains is not None and contains not in p.count: 

595 continue 

596 equations.append(f'{i}) {p.equation()}') 

597 return equations 

598 

599 def diagram(self, U=None, pH=None): 

600 """Actual evaluation of the complete diagram 

601 

602 Returns 

603 ------- 

604 

605 pour: 

606 The stability domains of the diagram on the pH vs. U grid. 

607 domains are represented by indexes (as integers) 

608 that map to Pourbaix.phases 

609 the target material is stable (index=-1) 

610 

611 meta: 

612 The Pourbaix energy on the pH vs. U grid. 

613 

614 text: 

615 The coordinates and phases information for 

616 text placement on the diagram. 

617 

618 domains: 

619 ... 

620 

621 """ 

622 pour = np.zeros((len(U), len(pH))) 

623 meta = pour.copy() 

624 

625 for i, u in enumerate(U): 

626 for j, p in enumerate(pH): 

627 meta[i, j], pour[i, j] = self._get_pourbaix_energy(u, p) 

628 

629 # Identifying the region where the target material 

630 # is stable and updating the diagram accordingly 

631 where_stable = meta <= 0 

632 pour[where_stable] = -1 

633 

634 text = [] 

635 domains = [int(i) for i in np.unique(pour)] 

636 for phase_id in domains: 

637 if phase_id == -1: 

638 where = where_stable 

639 txt = {self.material.name: 1} 

640 else: 

641 where = pour == phase_id 

642 phase = self.phases[int(phase_id)] 

643 txt = phase.count 

644 x = np.dot(where.sum(1), U) / where.sum() 

645 y = np.dot(where.sum(0), pH) / where.sum() 

646 text.append((x, y, txt)) 

647 

648 return PourbaixDiagram(self, U, pH, pour, meta, text, domains) 

649 

650 def get_phase_boundaries(self, phmin, phmax, umin, umax, domains, tol=1e-6): 

651 """Plane intersection method for finding 

652 the boundaries between phases seen in the final plot. 

653 

654 Returns a list of tuples, each representing a single boundary, 

655 of the form ([[x1, x2], [y1, y2]], [id1, id2]), namely the 

656 x and y coordinates of the simplices connected by the boundary 

657 and the id's of the phases at each side of the boundary. 

658 """ 

659 from collections import defaultdict 

660 from itertools import combinations 

661 

662 # Planes identifying the diagram frame 

663 planes = [ 

664 (np.array([0.0, 1.0, 0.0]), umin, 'bottom'), 

665 (np.array([0.0, 1.0, 0.0]), umax, 'top'), 

666 (np.array([1.0, 0.0, 0.0]), phmin, 'left'), 

667 (np.array([1.0, 0.0, 0.0]), phmax, 'right'), 

668 ] 

669 

670 # Planes associated with the stable domains of the diagram. 

671 # Given x=pH, y=U, z=E_pbx=-DeltaG, each plane has expression: 

672 # _vector[2]*x + _vector[1]*y + z = -_vector[0] 

673 # The region where the target material is stable 

674 # (id=-1, if present) is delimited by the xy plane (Epbx=0) 

675 for d in domains: 

676 if d == -1: 

677 plane = np.array([0.0, 0.0, 1.0]) 

678 const = 0.0 

679 else: 

680 pvec = self.phases[d]._vector 

681 plane = np.array([pvec[2], pvec[1], 1]) 

682 const = -pvec[0] 

683 planes.append((plane, const, d)) 

684 

685 # The simplices are found from the intersection points between 

686 # all possible plane triplets. If the z coordinate of the point 

687 # matches the corresponding pourbaix energy, 

688 # then the point is a simplex. 

689 simplices = [] 

690 for (p1, c1, id1), (p2, c2, id2), (p3, c3, id3) in combinations( 

691 planes, 3 

692 ): 

693 A = np.vstack((p1, p2, p3)) 

694 c = np.array([c1, c2, c3]) 

695 ids = (id1, id2, id3) 

696 

697 try: 

698 # triplets containing parallel planes raise a LinAlgError 

699 # and are automatically excluded. 

700 invA = np.linalg.inv(A) 

701 except np.linalg.LinAlgError: 

702 continue 

703 

704 pt = np.dot(invA, c) 

705 Epbx = self._get_pourbaix_energy(pt[1], pt[0])[0] 

706 if ( 

707 pt[2] >= -tol 

708 and np.isclose(Epbx, pt[2], rtol=0, atol=tol) 

709 and phmin - tol <= pt[0] <= phmax + tol 

710 and umin - tol <= pt[1] <= umax + tol 

711 ): 

712 simplex = np.round(pt[:2], 3) 

713 simplices.append((simplex, ids)) 

714 

715 # The final segments to plot on the diagram are found from 

716 # the pairs of unique simplices that have two neighboring phases 

717 # in common, diagram frame excluded. 

718 duplicate_filter = defaultdict(int) 

719 

720 def are_boundaries_there(comm): 

721 bounds = ['bottom', 'top', 'left', 'right'] 

722 for c in comm: 

723 if c in bounds: 

724 return True 

725 return False 

726 

727 for (s1, id1), (s2, id2) in combinations(simplices, 2): 

728 # common neighboring phases, diagram frame excluded 

729 common = {*id1} & {*id2} 

730 

731 simplices_are_distinct = not np.allclose(s1, s2, rtol=0, atol=tol) 

732 only_two_phases_in_common = len(common) == 2 

733 diagram_frame_excluded = not are_boundaries_there(common) 

734 

735 # Filtering out duplicates 

736 if all( 

737 [ 

738 simplices_are_distinct, 

739 only_two_phases_in_common, 

740 diagram_frame_excluded, 

741 ] 

742 ): 

743 testarray = sorted([s1, s2], key=lambda s: (s[0], s[1])) 

744 testarray.append(sorted(common)) 

745 testarray = np.array(testarray).flatten() 

746 duplicate_filter[tuple(testarray)] += 1 

747 

748 segments = [] 

749 for segment in duplicate_filter: 

750 coords, phases = np.split(np.array(segment), [4]) 

751 segments.append((coords.reshape(2, 2).T, list(phases.astype(int)))) 

752 return segments 

753 

754 

755@dataclass 

756class PourbaixDiagram: 

757 pbx: Pourbaix 

758 U: np.ndarray 

759 pH: np.ndarray 

760 pour: np.ndarray 

761 meta: np.ndarray 

762 text: list[tuple[float, float, str]] 

763 domains: list[int] 

764 

765 def __post_init__(self): 

766 def _issorted(array): 

767 return all(np.diff(array) > 0) 

768 

769 # We might as well require the input domains to be sorted: 

770 if not _issorted(self.U): 

771 raise ValueError('U must be sorted') 

772 

773 if not _issorted(self.pH): 

774 raise ValueError('pH must be sorted') 

775 

776 @property 

777 def pHrange(self): 

778 return (self.pH[0], self.pH[-1]) 

779 

780 @property 

781 def Urange(self): 

782 return (self.U[0], self.U[-1]) 

783 

784 def _draw_diagram_axes( 

785 self, 

786 cap, 

787 normalize, 

788 include_text, 

789 include_water, 

790 labeltype, 

791 cmap, 

792 *, 

793 ax, 

794 ): 

795 """Backend for drawing Pourbaix diagrams.""" 

796 

797 meta = self.meta.copy() 

798 if normalize: 

799 meta /= self.pbx.material.natoms 

800 cbarlabel = r'$\Delta G_{pbx}$ (eV/atom)' 

801 else: 

802 cbarlabel = r'$\Delta G_{pbx}$ (eV)' 

803 

804 fig = ax.get_figure() 

805 extent = [*self.pHrange, *self.Urange] 

806 

807 fig.subplots_adjust(left=0.1, right=0.97, top=0.97, bottom=0.14) 

808 

809 if isinstance(cap, list): 

810 vmin = cap[0] 

811 vmax = cap[1] 

812 else: 

813 vmin = -cap 

814 vmax = cap 

815 

816 colorplot = ax.imshow( 

817 meta, 

818 cmap=cmap, 

819 extent=extent, 

820 vmin=vmin, 

821 vmax=vmax, 

822 origin='lower', 

823 aspect='auto', 

824 interpolation='gaussian', 

825 ) 

826 

827 cbar = fig.colorbar(colorplot, ax=ax, pad=0.02) 

828 

829 bounds = self.pbx.get_phase_boundaries( 

830 *self.pHrange, *self.Urange, self.domains 

831 ) 

832 for coords, _ in bounds: 

833 ax.plot(coords[0], coords[1], '-', c='k', lw=1.0) 

834 

835 if labeltype == 'numbers': 

836 add_numbers(ax, self.text) 

837 elif labeltype == 'phases': 

838 add_labels(ax, self.text) 

839 elif labeltype is None: 

840 pass 

841 else: 

842 raise ValueError("The provided label type doesn't exist") 

843 

844 if include_water: 

845 add_redox_lines(ax, self.pH, self.pbx.reference, 'w') 

846 

847 ax.set_xlim(*self.pHrange) 

848 ax.set_ylim(*self.Urange) 

849 ax.set_xlabel('pH', fontsize=22) 

850 ax.set_ylabel( 

851 r'$\it{U}$' + f' vs. {self.pbx.reference} (V)', fontsize=22 

852 ) 

853 ax.set_xticks(np.arange(self.pHrange[0], self.pHrange[1] + 1, 2)) 

854 ax.set_yticks(np.arange(self.Urange[0], self.Urange[1] + 1, 1)) 

855 ax.xaxis.set_tick_params(width=1.5, length=5) 

856 ax.yaxis.set_tick_params(width=1.5, length=5) 

857 ax.tick_params(axis='both', labelsize=22) 

858 

859 ticks = np.linspace(vmin, vmax, num=5) 

860 cbar.set_ticks(ticks) 

861 cbar.set_ticklabels(ticks) 

862 cbar.outline.set_linewidth(1.5) 

863 cbar.ax.tick_params(labelsize=20, width=1.5, length=5) 

864 cbar.ax.set_ylabel(cbarlabel, fontsize=20) 

865 

866 for axis in ['top', 'bottom', 'left', 'right']: 

867 ax.spines[axis].set_linewidth(1.5) 

868 

869 if include_text: 

870 fig.subplots_adjust(right=0.75) 

871 add_phase_labels(fig, self.text, offset=0.05) 

872 return ax, cbar 

873 

874 fig.tight_layout() 

875 return cbar 

876 

877 def plot( 

878 self, 

879 cap=1.0, 

880 # figsize=[12, 6], 

881 normalize=True, 

882 include_text=True, 

883 include_water=False, 

884 labeltype='numbers', 

885 cmap='RdYlGn_r', 

886 filename=None, 

887 ax=None, 

888 show=False, 

889 ): 

890 """Plot a complete Pourbaix diagram. 

891 

892 Keyword arguments 

893 ----------------- 

894 

895 Urange: list 

896 The potential range onto which to draw the diagram. 

897 

898 pHrange: list 

899 The pH range onto which to draw the diagram. 

900 

901 npoints: int 

902 The resolution of the diagram. Higher values 

903 mean higher resolution and thus higher compute times. 

904 

905 cap: float/list 

906 If float, the limit (in both the positive and negative direction) 

907 of the Pourbaix energy colormap. 

908 If list, the first and second value determine the colormap limits. 

909 

910 figsize: list 

911 The horizontal and vertical size of the graph. 

912 

913 normalize: bool 

914 Normalize energies by the number of 

915 atoms in the target material unit formula. 

916 

917 include_text: bool 

918 Report to the right of the diagram the main products 

919 associated with the stability domains. 

920 

921 include_water: bool 

922 Include in the diagram the stability domain of water. 

923 

924 labeltype: str/None 

925 The labeling style of the diagram domains. Options: 

926 'numbers': just add numbers associated with the 

927 different phases, the latter shown 

928 on the right if include_text=True. 

929 'phases': Write the main products directly on the diagram. 

930 These labels can be dragged around if the placement 

931 is unsatisfactory. Redundant if include_text=True. 

932 None: Don't draw any labels. 

933 

934 filename: str/None 

935 If passed as a string, the figure will be saved with that name. 

936 

937 show: bool 

938 Spawn a window showing the diagram. 

939 

940 """ 

941 import matplotlib.pyplot as plt 

942 

943 if ax is None: 

944 ax = plt.gca() 

945 

946 fig = ax.get_figure() 

947 

948 self._draw_diagram_axes( 

949 cap, normalize, include_text, include_water, labeltype, cmap, ax=ax 

950 ) 

951 

952 if filename is not None: 

953 fig.savefig(filename) 

954 

955 if show: 

956 plt.show()