| 1 |
# This program is public domain |
| 2 |
# Author: Paul Kienzle |
| 3 |
""" |
| 4 |
Chemical formula parser. |
| 5 |
""" |
| 6 |
|
| 7 |
from copy import copy |
| 8 |
from math import pi, sqrt |
| 9 |
from typing import cast, Union, Any |
| 10 |
from collections.abc import Sequence, Callable |
| 11 |
|
| 12 |
# Requires that the pyparsing module is installed. |
| 13 |
|
| 14 |
from pyparsing import (ParserElement, Literal, Optional, White, Regex, |
| 15 |
ZeroOrMore, OneOrMore, Forward, StringEnd, Group) |
| 16 |
|
| 17 |
from .core import default_table, isatom, isisotope, ision, change_table |
| 18 |
from .core import Atom, Element, Isotope, Ion, PeriodicTable # for typing |
| 19 |
from .constants import avogadro_number, electron_mass |
| 20 |
from .util import cell_volume |
| 21 |
|
| 22 |
FormulaInput = Union[str, "Formula", Atom, dict[Atom, float], Sequence[tuple[float, Any]], None] |
| 23 |
Fragment = tuple[float, Union[Atom, "Structure"]] |
| 24 |
Structure = tuple["Fragment", ...] |
| 25 |
|
| 26 |
PACKING_FACTORS = dict(cubic=pi/6, bcc=pi*sqrt(3)/8, hcp=pi/sqrt(18), |
| 27 |
fcc=pi/sqrt(18), diamond=pi*sqrt(3)/16) |
| 28 |
|
| 29 |
|
| 30 |
def mix_by_weight(*args, **kw) -> "Formula": |
| 31 |
""" |
| 32 |
Generate a mixture which apportions each formula by weight. |
| 33 |
|
| 34 |
:Parameters: |
| 35 |
*formula1* : Formula OR string |
| 36 |
Material |
| 37 |
|
| 38 |
*quantity1* : float |
| 39 |
Relative quantity of that material |
| 40 |
|
| 41 |
*formula2* : Formula OR string |
| 42 |
Material |
| 43 |
|
| 44 |
*quantity2* : float |
| 45 |
Relative quantity of that material |
| 46 |
|
| 47 |
... |
| 48 |
|
| 49 |
*density* : float |
| 50 |
Density of the mixture, if known |
| 51 |
|
| 52 |
*natural_density* : float |
| 53 |
Density of the mixture with natural abundances, if known. |
| 54 |
|
| 55 |
*name* : string |
| 56 |
Name of the mixture |
| 57 |
|
| 58 |
*table* : PeriodicTable |
| 59 |
Private table to use when parsing string formulas. |
| 60 |
|
| 61 |
:Returns: |
| 62 |
|
| 63 |
*formula* : Formula |
| 64 |
|
| 65 |
If density is not given, then it will be computed from the density |
| 66 |
of the components, assuming the components take up no more nor less |
| 67 |
space because they are in the mixture. If component densities are |
| 68 |
not available, then the resulting density will not be computed. The |
| 69 |
density calculation assumes the cell volume remains constant for the |
| 70 |
original materials, which is not in general the case. |
| 71 |
""" |
| 72 |
table = default_table(kw.pop('table', None)) |
| 73 |
density = kw.pop('density', None) |
| 74 |
natural_density = kw.pop('natural_density', None) |
| 75 |
name = kw.pop('name', None) |
| 76 |
if kw: |
| 77 |
raise TypeError("Unexpected arguments "+", ".join(kw.keys())) |
| 78 |
|
| 79 |
if len(args)%2 != 0: |
| 80 |
raise ValueError("Need a quantity for each formula") |
| 81 |
pairs = [(formula(args[i], table=table), args[i+1]) |
| 82 |
for i in range(0, len(args), 2)] |
| 83 |
result = _mix_by_weight_pairs(pairs) |
| 84 |
if natural_density: |
| 85 |
result.natural_density = natural_density |
| 86 |
if density: |
| 87 |
result.density = density |
| 88 |
if name: |
| 89 |
result.name = name |
| 90 |
return result |
| 91 |
|
| 92 |
def _mix_by_weight_pairs(pairs: list[tuple["Formula", float]]) -> "Formula": |
| 93 |
from .formulas import Formula # For running as __main__ |
| 94 |
|
| 95 |
# Drop pairs with zero quantity |
| 96 |
# Note: must be first statement in order to accept iterators |
| 97 |
pairs = [(f, q) for f, q in pairs if q > 0] |
| 98 |
|
| 99 |
result = Formula() |
| 100 |
if pairs: |
| 101 |
# cell mass = mass |
| 102 |
# target mass = q |
| 103 |
# cell mass * n = target mass |
| 104 |
# => n = target mass / cell mass |
| 105 |
# = q / mass |
| 106 |
# scale this so that n = 1 for the smallest quantity |
| 107 |
scale = min(q/f.mass for f, q in pairs) |
| 108 |
for f, q in pairs: |
| 109 |
result += ((q/f.mass)/scale) * f |
| 110 |
if all(f.density for f, _ in pairs): |
| 111 |
# Tested that densities are not None, so the following will work |
| 112 |
volume = sum(q/cast(float, f.density) for f, q in pairs)/scale |
| 113 |
result.density = result.mass/volume |
| 114 |
return result |
| 115 |
|
| 116 |
def mix_by_volume(*args, **kw) -> "Formula": |
| 117 |
""" |
| 118 |
Generate a mixture which apportions each formula by volume. |
| 119 |
|
| 120 |
:Parameters: |
| 121 |
*formula1* : Formula OR string |
| 122 |
Material |
| 123 |
|
| 124 |
*quantity1* : float |
| 125 |
Relative quantity of that material |
| 126 |
|
| 127 |
*formula2* : Formula OR string |
| 128 |
Material |
| 129 |
|
| 130 |
*quantity2* : float |
| 131 |
Relative quantity of that material |
| 132 |
|
| 133 |
... |
| 134 |
|
| 135 |
*density* : float |
| 136 |
Density of the mixture, if known |
| 137 |
|
| 138 |
*natural_density* : float |
| 139 |
Density of the mixture with natural abundances, if known. |
| 140 |
|
| 141 |
*name* : string |
| 142 |
Name of the mixture |
| 143 |
|
| 144 |
*table* : PeriodicTable |
| 145 |
Private table to use when parsing string formulas. |
| 146 |
|
| 147 |
:Returns: |
| 148 |
|
| 149 |
*formula* : Formula |
| 150 |
|
| 151 |
If density is not given, then it will be computed from the density |
| 152 |
of the components, assuming the components take up no more nor less |
| 153 |
space because they are in the mixture. If component densities are |
| 154 |
not available, then a ValueError is raised. The density calculation |
| 155 |
assumes the cell volume remains constant for the original materials, |
| 156 |
which is not in general the case. |
| 157 |
""" |
| 158 |
table = default_table(kw.pop('table', None)) |
| 159 |
density = kw.pop('density', None) |
| 160 |
natural_density = kw.pop('natural_density', None) |
| 161 |
name = kw.pop('name', None) |
| 162 |
if kw: |
| 163 |
raise TypeError("Unexpected arguments "+", ".join(kw.keys())) |
| 164 |
|
| 165 |
if len(args)%2 != 0: |
| 166 |
raise ValueError("Need a quantity for each formula") |
| 167 |
pairs = [(formula(args[i], table=table), args[i+1]) |
| 168 |
for i in range(0, len(args), 2)] |
| 169 |
result = _mix_by_volume_pairs(pairs) |
| 170 |
if natural_density: |
| 171 |
result.natural_density = natural_density |
| 172 |
if density: |
| 173 |
result.density = density |
| 174 |
if name: |
| 175 |
result.name = name |
| 176 |
return result |
| 177 |
|
| 178 |
def _mix_by_volume_pairs(pairs: list[tuple["Formula", float]]) -> "Formula": |
| 179 |
from .formulas import Formula # For running as __main__ |
| 180 |
|
| 181 |
# Drop pairs with zero quantity |
| 182 |
# Note: must be first statement in order to accept iterators |
| 183 |
pairs = [(f, q) for f, q in pairs if q > 0] |
| 184 |
|
| 185 |
for f, _ in pairs: |
| 186 |
if f.density is None or f.density == 0.: |
| 187 |
raise ValueError("Need the mass density of "+str(f)) |
| 188 |
|
| 189 |
result = Formula() |
| 190 |
if pairs: |
| 191 |
# cell volume = mass/density |
| 192 |
# target volume = q |
| 193 |
# cell volume * n = target volume |
| 194 |
# => n = target volume / cell volume |
| 195 |
# = q / (mass/density) |
| 196 |
# = q * density / mass |
| 197 |
# scale this so that n = 1 for the smallest quantity |
| 198 |
scale = min(q*cast(float, f.density)/f.mass for f, q in pairs) |
| 199 |
for f, q in pairs: |
| 200 |
result += ((q*cast(float, f.density)/f.mass)/scale) * f |
| 201 |
|
| 202 |
volume = sum(q for _, q in pairs)/scale |
| 203 |
result.density = result.mass/volume |
| 204 |
|
| 205 |
return result |
| 206 |
|
| 207 |
def formula( |
| 208 |
compound: FormulaInput=None, |
| 209 |
density: float|None=None, |
| 210 |
natural_density: float|None=None, |
| 211 |
name: str|None=None, |
| 212 |
table: PeriodicTable|None=None, |
| 213 |
) -> "Formula": |
| 214 |
r""" |
| 215 |
Construct a chemical formula representation from a string, a |
| 216 |
dictionary of atoms or another formula. |
| 217 |
|
| 218 |
:Parameters: |
| 219 |
*compound* : Formula initializer |
| 220 |
Chemical formula. |
| 221 |
|
| 222 |
*density* : float | |g/cm^3| |
| 223 |
Material density. Not needed for single element formulas. |
| 224 |
|
| 225 |
*natural_density* : float | |g/cm^3| |
| 226 |
Material density assuming naturally occurring isotopes and no |
| 227 |
change in cell volume. |
| 228 |
|
| 229 |
*name* : string |
| 230 |
Common name for the molecule. |
| 231 |
|
| 232 |
*table* : PeriodicTable |
| 233 |
Private table to use when parsing string formulas. |
| 234 |
|
| 235 |
:Exceptions: |
| 236 |
*ValueError* : invalid formula initializer |
| 237 |
|
| 238 |
Example compounds: |
| 239 |
|
| 240 |
string: |
| 241 |
m = formula( "CaCO3+6H2O" ) |
| 242 |
sequence of fragments: |
| 243 |
m = formula( [(1, Ca), (2, C), (3, O), (6, [(2, H), (1, O)]] ) |
| 244 |
molecular math: |
| 245 |
m = formula( "CaCO3" ) + 6*formula( "H2O" ) |
| 246 |
another formula (makes a copy): |
| 247 |
m = formula( formula("CaCO3+6H2O") ) |
| 248 |
an atom: |
| 249 |
m = formula( Ca ) |
| 250 |
nothing: |
| 251 |
m = formula() |
| 252 |
|
| 253 |
Operations: |
| 254 |
m.atoms returns {isotope: count, ...} for each atom in the compound. |
| 255 |
|
| 256 |
Formula strings consist of counts and atoms such as "CaCO3+6H2O". |
| 257 |
Groups can be separated by '+' or space, so "CaCO3 6H2O" works as well. |
| 258 |
Groups and be defined using parentheses, such as "CaCO3(H2O)6". |
| 259 |
Parentheses can nest: "(CaCO3(H2O)6)1" |
| 260 |
Isotopes are represented by index, e.g., "CaCO[18]3+6H2O". |
| 261 |
Counts can be integer or decimal, e.g. "CaCO3+(3HO0.5)2". |
| 262 |
Density can be specified in the formula using, e.g., "H2O@1". Isotopic |
| 263 |
formulas can use natural density, e.g., "D2O@1n", or the expected density |
| 264 |
with that isotope, e.g., "[email protected]". |
| 265 |
|
| 266 |
For full details see help(periodictable.formulas.formula_grammar) |
| 267 |
|
| 268 |
The chemical formula is designed for simple calculations such |
| 269 |
as molar mass, not for representing bonds or atom positions. |
| 270 |
However, we preserve the structure of the formula so that it can |
| 271 |
be used as a basis for a rich text representation such as |
| 272 |
matplotlib TeX markup. |
| 273 |
|
| 274 |
After creating a formula, a rough estimate of the density can be |
| 275 |
computed using:: |
| 276 |
|
| 277 |
formula.density = formula.molecular_mass/formula.volume(packing_factor=...) |
| 278 |
|
| 279 |
The volume() calculation uses the covalent radii of the components and |
| 280 |
the known packing factor or crystal structure name. If the lattice |
| 281 |
constants for the crystal are known, then they can be used instead:: |
| 282 |
|
| 283 |
formula.density = formula.molecular_mass/formula.volume(a, b, c, alpha, beta, gamma) |
| 284 |
|
| 285 |
Formulas are designed for calculating quantities such as molar mass and |
| 286 |
scattering length density, not for representing bonds or atom positions. |
| 287 |
The representations are simple, but preserve some of the structure for |
| 288 |
display purposes. |
| 289 |
""" |
| 290 |
from .formulas import Formula # For running as __main__ |
| 291 |
|
| 292 |
structure: Structure |
| 293 |
if compound is None or compound == '': |
| 294 |
structure = tuple() |
| 295 |
elif isinstance(compound, Formula): |
| 296 |
structure = compound.structure |
| 297 |
if density is None and natural_density is None: |
| 298 |
density = compound.density |
| 299 |
if not name: |
| 300 |
name = compound.name |
| 301 |
elif isatom(compound): |
| 302 |
structure = ((1, cast(Atom, compound)), ) |
| 303 |
elif isinstance(compound, dict): |
| 304 |
structure = _convert_to_hill_notation(cast(dict[Atom, float], compound)) |
| 305 |
elif isinstance(compound, str): |
| 306 |
try: |
| 307 |
chem = parse_formula(compound, table=table) |
| 308 |
if name: |
| 309 |
chem.name = name |
| 310 |
if density is not None: |
| 311 |
chem.density = density |
| 312 |
elif natural_density is not None: |
| 313 |
chem.natural_density = natural_density |
| 314 |
return chem |
| 315 |
except ValueError as exception: |
| 316 |
raise ValueError(str(exception)) |
| 317 |
#print "parsed", compound, "as", self |
| 318 |
else: |
| 319 |
try: |
| 320 |
structure = _immutable(cast(Structure, compound)) |
| 321 |
except Exception: |
| 322 |
raise ValueError("not a valid chemical formula: "+str(compound)) |
| 323 |
return Formula(structure=structure, name=name, density=density, |
| 324 |
natural_density=natural_density) |
| 325 |
|
| 326 |
class Formula: |
| 327 |
""" |
| 328 |
Simple chemical formula representation. |
| 329 |
""" |
| 330 |
structure: Structure |
| 331 |
density: float|None |
| 332 |
name: str|None |
| 333 |
|
| 334 |
def __init__(self, |
| 335 |
structure: Structure=tuple(), |
| 336 |
density: float|None=None, |
| 337 |
natural_density: float|None=None, |
| 338 |
name: str|None=None, |
| 339 |
): |
| 340 |
self.structure = structure |
| 341 |
self.name = name |
| 342 |
|
| 343 |
# If natural_density or density are specified, use them. |
| 344 |
# If only one element in the formula, use its density. |
| 345 |
# Otherwise, leave density unspecified, and let the user |
| 346 |
# assign it separately if they need it. |
| 347 |
if natural_density is not None: |
| 348 |
self.natural_density = natural_density |
| 349 |
elif density is not None: |
| 350 |
self.density = density |
| 351 |
elif len(self.atoms) == 1: |
| 352 |
# Note: density for isotopes already corrected for natural density |
| 353 |
atom = list(self.atoms.keys())[0] |
| 354 |
self.density = atom.density |
| 355 |
else: |
| 356 |
self.density = None |
| 357 |
|
| 358 |
@property |
| 359 |
def atoms(self) -> dict[Atom, float]: |
| 360 |
""" |
| 361 |
{ *atom*: *count*, ... } |
| 362 |
|
| 363 |
Composition of the molecule. Referencing this attribute computes |
| 364 |
the *count* as the total number of each element or isotope in the |
| 365 |
chemical formula, summed across all subgroups. |
| 366 |
""" |
| 367 |
return _count_atoms(self.structure) |
| 368 |
|
| 369 |
@property |
| 370 |
def hill(self) -> "Formula": |
| 371 |
""" |
| 372 |
Formula |
| 373 |
|
| 374 |
Convert the formula to a formula in Hill notation. Carbon appears |
| 375 |
first followed by hydrogen then the remaining elements in alphabetical |
| 376 |
order. |
| 377 |
""" |
| 378 |
return formula(self.atoms) |
| 379 |
|
| 380 |
def natural_mass_ratio(self) -> float: |
| 381 |
""" |
| 382 |
Natural mass to isotope mass ratio. |
| 383 |
|
| 384 |
:Returns: |
| 385 |
*ratio* : float |
| 386 |
|
| 387 |
The ratio is computed from the sum of the masses of the individual |
| 388 |
elements using natural abundance divided by the sum of the masses |
| 389 |
of the isotopes used in the formula. If the cell volume is |
| 390 |
preserved with isotope substitution, then the ratio of the masses |
| 391 |
will be the ratio of the densities. |
| 392 |
|
| 393 |
2026-01-08 Fixed ratio calculation for molecules with charged isotopes. |
| 394 |
""" |
| 395 |
total_natural_mass = total_isotope_mass = total_charge = 0. |
| 396 |
for atom, count in self.atoms.items(): |
| 397 |
# Use the mass of the neutral atom for the calculation. If the atom is a charged |
| 398 |
# isotope this requires atom.element.element.mass rather than just atom.mass. |
| 399 |
total_charge += count * atom.charge |
| 400 |
if ision(atom): |
| 401 |
atom = cast(Ion, atom).element |
| 402 |
natural_mass = cast(Isotope, atom).element.mass if isisotope(atom) else atom.mass |
| 403 |
total_natural_mass += count * natural_mass |
| 404 |
total_isotope_mass += count * atom.mass |
| 405 |
# Note: negative charge means extra electrons |
| 406 |
charge_correction = -total_charge * electron_mass |
| 407 |
return (total_natural_mass + charge_correction)/(total_isotope_mass + charge_correction) |
| 408 |
|
| 409 |
@property |
| 410 |
def natural_density(self) -> float | None: |
| 411 |
""" |
| 412 |
|g/cm^3| |
| 413 |
|
| 414 |
Density of the formula with specific isotopes of each element |
| 415 |
replaced by the naturally occurring abundance of the element |
| 416 |
without changing the cell volume. |
| 417 |
""" |
| 418 |
if self.density is None: |
| 419 |
return None |
| 420 |
return self.density*self.natural_mass_ratio() |
| 421 |
|
| 422 |
@natural_density.setter |
| 423 |
def natural_density(self, natural_density): |
| 424 |
self.density = natural_density / self.natural_mass_ratio() |
| 425 |
|
| 426 |
@property |
| 427 |
def mass(self) -> float: |
| 428 |
""" |
| 429 |
atomic mass units u (C[12] = 12 u) |
| 430 |
|
| 431 |
Molar mass of the molecule. Use molecular_mass to get the mass in |
| 432 |
grams. |
| 433 |
""" |
| 434 |
mass = 0. |
| 435 |
for el, count in self.atoms.items(): |
| 436 |
mass += el.mass*count |
| 437 |
return mass |
| 438 |
|
| 439 |
@property |
| 440 |
def molecular_mass(self) -> float: |
| 441 |
""" |
| 442 |
g |
| 443 |
|
| 444 |
Mass of the molecule in grams. |
| 445 |
""" |
| 446 |
return self.mass/avogadro_number |
| 447 |
|
| 448 |
@property |
| 449 |
def charge(self) -> float: |
| 450 |
""" |
| 451 |
Net charge of the molecule. |
| 452 |
""" |
| 453 |
return sum([m*a.charge for a, m in self.atoms.items()]) |
| 454 |
|
| 455 |
@property |
| 456 |
def mass_fraction(self) -> dict[Atom, float]: |
| 457 |
""" |
| 458 |
Fractional mass representation of each element/isotope/ion. |
| 459 |
""" |
| 460 |
total_mass = self.mass |
| 461 |
return dict((a, m*a.mass/total_mass) for a, m in self.atoms.items()) |
| 462 |
|
| 463 |
# TODO: Remove compound._pf. It is unused and wrong. |
| 464 |
def _pf(self) -> float | None: |
| 465 |
""" |
| 466 |
packing factor | unitless |
| 467 |
|
| 468 |
packing factor estimated from density. |
| 469 |
""" |
| 470 |
return self.density |
| 471 |
|
| 472 |
def volume(self, *args, **kw) -> float: |
| 473 |
r""" |
| 474 |
Estimate unit cell volume. |
| 475 |
|
| 476 |
The crystal volume can be estimated from the element covalent radius |
| 477 |
and the atomic packing factor using:: |
| 478 |
|
| 479 |
packing_factor = N_atoms V_atom / V_crystal |
| 480 |
|
| 481 |
Packing factors for a number of crystal lattice structures are defined. |
| 482 |
|
| 483 |
.. table:: Crystal lattice names and packing factors |
| 484 |
|
| 485 |
======== ======================= ====================== ============== |
| 486 |
Code Description Formula Packing factor |
| 487 |
======== ======================= ====================== ============== |
| 488 |
cubic simple cubic $\pi/6$ 0.52360 |
| 489 |
bcc body-centered cubic $\pi\sqrt{3/8}$ 0.68017 |
| 490 |
hcp hexagonal close-packed $\pi/\sqrt{18}$ 0.74048 |
| 491 |
fcc face-centered cubic $\pi/\sqrt{18}$ 0.74048 |
| 492 |
diamond diamond cubic $\pi\sqrt{3/16}$ 0.34009 |
| 493 |
======== ======================= ====================== ============== |
| 494 |
|
| 495 |
:Parameters: |
| 496 |
*packing_factor* = 'hcp' : float or string |
| 497 |
Atomic packing factor. If *packing_factor* is the name of |
| 498 |
a crystal lattice, use the *lattice* packing factor. |
| 499 |
*a*, *b*, *c* : float | |Ang| |
| 500 |
Lattice spacings. *b* and *c* default to *a*. |
| 501 |
*alpha*, *beta*, *gamma* : float | |deg| |
| 502 |
Lattice angles. These default to 90\ |deg| |
| 503 |
|
| 504 |
:Returns: |
| 505 |
|
| 506 |
*volume* : float | |cm^3| |
| 507 |
Molecular volume. |
| 508 |
|
| 509 |
:Raises: |
| 510 |
|
| 511 |
*KeyError* : unknown lattice type |
| 512 |
|
| 513 |
*TypeError* : missing or bad lattice parameters |
| 514 |
|
| 515 |
Using the cell volume, mass density can be set with:: |
| 516 |
|
| 517 |
formula.density = n*formula.molecular_mass/formula.volume() |
| 518 |
|
| 519 |
where n is the number of molecules per unit cell. |
| 520 |
|
| 521 |
Note: a single non-keyword argument is interpreted as a packing factor |
| 522 |
rather than a lattice spacing of 'a'. |
| 523 |
""" |
| 524 |
# TODO: density estimated from H.covalent_radius is much too high |
| 525 |
#H_radius = kw.pop('H_radius', None) |
| 526 |
# Get packing factor |
| 527 |
if len(args) == 1 and not kw: |
| 528 |
packing_factor = args[0] |
| 529 |
args = tuple() |
| 530 |
else: |
| 531 |
packing_factor = kw.pop('packing_factor', 'hcp') |
| 532 |
|
| 533 |
# Let cell_volume sort out its own parameters. |
| 534 |
if args or kw: |
| 535 |
return cell_volume(*args, **kw)*1e-24 |
| 536 |
|
| 537 |
# Compute atomic volume |
| 538 |
V = 0. |
| 539 |
for atom, count in self.atoms.items(): |
| 540 |
assert atom.covalent_radius is not None, "Need covalent radius for "+str(atom) |
| 541 |
radius = atom.covalent_radius |
| 542 |
#if el.number == 1 and H_radius is not None: |
| 543 |
# radius = H_radius |
| 544 |
V += radius**3*count |
| 545 |
V *= 4.*pi/3 |
| 546 |
|
| 547 |
# Translate packing factor from string |
| 548 |
try: |
| 549 |
_ = packing_factor + "" |
| 550 |
except Exception: |
| 551 |
pass |
| 552 |
else: |
| 553 |
packing_factor = PACKING_FACTORS[packing_factor.lower()] |
| 554 |
return V/packing_factor*1e-24 |
| 555 |
|
| 556 |
# TODO; remove neutron_sld/xray_sld otherwise we have circular imports |
| 557 |
def neutron_sld(self, *, wavelength: float|None=None, energy: float|None=None) -> tuple[float, float, float]|tuple[None, None, None]: |
| 558 |
""" |
| 559 |
Neutron scattering information for the molecule. |
| 560 |
|
| 561 |
:Parameters: |
| 562 |
*wavelength* : float | |Ang| |
| 563 |
Wavelength of the neutron beam. |
| 564 |
|
| 565 |
:Returns: |
| 566 |
|
| 567 |
*sld* : (float, float, float) | |1e-6/Ang^2| |
| 568 |
Neutron scattering length density is returned as the tuple |
| 569 |
(*real*, *imaginary*, *incoherent*), or as (None, None, None) |
| 570 |
if the mass density is not known. |
| 571 |
|
| 572 |
.. deprecated:: 0.95 |
| 573 |
Use periodictable.neutron_sld(formula) instead. |
| 574 |
""" |
| 575 |
from .nsf import neutron_sld |
| 576 |
if self.density is None: |
| 577 |
return None, None, None |
| 578 |
return neutron_sld(self.atoms, density=self.density, |
| 579 |
wavelength=wavelength, energy=energy) |
| 580 |
|
| 581 |
def xray_sld(self, *, energy: float|None=None, wavelength: float|None=None) -> tuple[float, float]|tuple[None, None]: |
| 582 |
""" |
| 583 |
X-ray scattering length density for the molecule. |
| 584 |
|
| 585 |
:Parameters: |
| 586 |
*energy* : float | keV |
| 587 |
Energy of atom. |
| 588 |
|
| 589 |
*wavelength* : float | |Ang| |
| 590 |
Wavelength of atom. |
| 591 |
|
| 592 |
.. Note: One of *wavelength* or *energy* is required. |
| 593 |
|
| 594 |
:Returns: |
| 595 |
|
| 596 |
*sld* : (float, float) | |1e-6/Ang^2| |
| 597 |
X-ray scattering length density is returned as the tuple |
| 598 |
(*real*, *imaginary*), or as (None, None) if the mass |
| 599 |
density is not known. |
| 600 |
|
| 601 |
.. deprecated:: 0.95 |
| 602 |
Use periodictable.xray_sld(formula) instead. |
| 603 |
""" |
| 604 |
from .xsf import xray_sld |
| 605 |
if self.density is None: |
| 606 |
return None, None |
| 607 |
return xray_sld(self.atoms, density=self.density, |
| 608 |
wavelength=wavelength, energy=energy) |
| 609 |
|
| 610 |
def change_table(self, table: PeriodicTable) -> "Formula": |
| 611 |
""" |
| 612 |
Replace the table used for the components of the formula. |
| 613 |
""" |
| 614 |
self.structure = _change_table(self.structure, table) |
| 615 |
return self |
| 616 |
|
| 617 |
def replace(self, source, target, portion=1.0): |
| 618 |
""" |
| 619 |
Create a new formula with one atom/isotope substituted for another. |
| 620 |
|
| 621 |
*formula* is the formula being updated. |
| 622 |
|
| 623 |
*source* is the isotope/element to be substituted. |
| 624 |
|
| 625 |
*target* is the replacement isotope/element. |
| 626 |
|
| 627 |
*portion* is the proportion of source which is substituted for target. |
| 628 |
""" |
| 629 |
return _isotope_substitution(self, source, target, portion=portion) |
| 630 |
|
| 631 |
def __eq__(self, other): |
| 632 |
""" |
| 633 |
Return True if two formulas represent the same structure. Note |
| 634 |
that they may still have different names and densities. |
| 635 |
Note: use hill representation for an order independent comparison. |
| 636 |
""" |
| 637 |
if not isinstance(other, Formula): |
| 638 |
return False |
| 639 |
return self.structure == other.structure |
| 640 |
|
| 641 |
def __add__(self, other): |
| 642 |
""" |
| 643 |
Join two formulas. |
| 644 |
""" |
| 645 |
#print "adding", self, other |
| 646 |
if not isinstance(other, Formula): |
| 647 |
raise TypeError("expected formula+formula") |
| 648 |
ret = Formula() |
| 649 |
ret.structure = tuple(list(self.structure) + list(other.structure)) |
| 650 |
return ret |
| 651 |
|
| 652 |
def __iadd__(self, other): |
| 653 |
""" |
| 654 |
Extend a formula with another. |
| 655 |
""" |
| 656 |
self.structure = tuple(list(self.structure) + list(other.structure)) |
| 657 |
return self |
| 658 |
|
| 659 |
def __rmul__(self, other): |
| 660 |
""" |
| 661 |
Provide a multiplier for formula. |
| 662 |
""" |
| 663 |
#print "multiplying", self, other |
| 664 |
try: |
| 665 |
other += 0 |
| 666 |
except TypeError: |
| 667 |
raise TypeError("n*formula expects numeric n") |
| 668 |
ret = copy(self) |
| 669 |
if other != 1 and self.structure: |
| 670 |
if len(self.structure) == 1: |
| 671 |
q, f = self.structure[0] |
| 672 |
ret.structure = ((other*q, f), ) |
| 673 |
else: |
| 674 |
ret.structure = ((other, ret.structure), ) |
| 675 |
return ret |
| 676 |
|
| 677 |
def __str__(self): |
| 678 |
return self.name if self.name else _str_atoms(self.structure) |
| 679 |
|
| 680 |
def __repr__(self): |
| 681 |
return "formula('%s')"%(str(self)) |
| 682 |
|
| 683 |
|
| 684 |
def _isotope_substitution(compound: "Formula", source: Atom, target: Atom, portion: float=1) -> "Formula": |
| 685 |
""" |
| 686 |
Substitute one atom/isotope in a formula with another in some proportion. |
| 687 |
|
| 688 |
*compound* is the formula being updated. |
| 689 |
|
| 690 |
*source* is the isotope/element to be substituted. |
| 691 |
|
| 692 |
*target* is the replacement isotope/element. |
| 693 |
|
| 694 |
*portion* is the proportion of source which is substituted for target. |
| 695 |
""" |
| 696 |
# TODO: fails if density is not defined |
| 697 |
atoms = compound.atoms |
| 698 |
assert compound.density is not None, "Need density for isotope substitution" |
| 699 |
if source in atoms: |
| 700 |
mass = compound.mass |
| 701 |
mass_reduction = atoms[source]*portion*(source.mass - target.mass) |
| 702 |
density = compound.density * (mass - mass_reduction)/mass |
| 703 |
atoms[target] = atoms.get(target, 0) + atoms[source]*portion |
| 704 |
if portion == 1: |
| 705 |
del atoms[source] |
| 706 |
else: |
| 707 |
atoms[source] *= 1-portion |
| 708 |
else: |
| 709 |
density = compound.density |
| 710 |
return formula(atoms, density=density) |
| 711 |
|
| 712 |
|
| 713 |
# TODO: Grammar should be independent of table |
| 714 |
# TODO: Parser can't handle meters as 'm' because it conflicts with the milli prefix |
| 715 |
LENGTH_UNITS = {'nm': 1e-9, 'um': 1e-6, 'μm': 1e-6, 'mm': 1e-3, 'cm': 1e-2} |
| 716 |
MASS_UNITS = {'ng': 1e-9, 'ug': 1e-6, 'mg': 1e-3, 'g': 1e+0, 'kg': 1e+3} |
| 717 |
VOLUME_UNITS = {'nL': 1e-9, 'uL': 1e-6, 'mL': 1e-3, 'L': 1e+0} |
| 718 |
LENGTH_RE = '('+'|'.join(LENGTH_UNITS.keys())+')' |
| 719 |
MASS_VOLUME_RE = '('+'|'.join(list(MASS_UNITS.keys())+list(VOLUME_UNITS.keys()))+')' |
| 720 |
def formula_grammar(table: PeriodicTable) -> ParserElement: |
| 721 |
""" |
| 722 |
Construct a parser for molecular formulas. |
| 723 |
|
| 724 |
:Parameters: |
| 725 |
|
| 726 |
*table* = None : PeriodicTable |
| 727 |
If table is specified, then elements and their associated fields |
| 728 |
will be chosen from that periodic table rather than the default. |
| 729 |
|
| 730 |
:Returns: |
| 731 |
*parser* : pyparsing.ParserElement. |
| 732 |
The ``parser.parse_string()`` method returns a list of |
| 733 |
pairs (*count, fragment*), where fragment is an *isotope*, |
| 734 |
an *element* or a list of pairs (*count, fragment*). |
| 735 |
|
| 736 |
""" |
| 737 |
# TODO: fix circular imports |
| 738 |
# This ickiness is because the formula class returned from the circular |
| 739 |
# import of fasta does not match the local formula class. |
| 740 |
from .formulas import Formula |
| 741 |
|
| 742 |
# Recursive |
| 743 |
composite = Forward() |
| 744 |
mixture = Forward() |
| 745 |
|
| 746 |
# whitespace and separators |
| 747 |
space = Optional(White().suppress()) |
| 748 |
separator = space+Literal('+').suppress()+space |
| 749 |
|
| 750 |
# Lookup the element in the element table |
| 751 |
symbol = Regex("[A-Z][a-z]?") |
| 752 |
symbol.set_parse_action(lambda s, l, t: table.symbol(t[0])) |
| 753 |
|
| 754 |
# Translate isotope |
| 755 |
openiso = Literal('[').suppress() |
| 756 |
closeiso = Literal(']').suppress() |
| 757 |
isotope = Optional(~White()+openiso+Regex("[1-9][0-9]*")+closeiso, |
| 758 |
default='0') |
| 759 |
isotope.set_parse_action(lambda s, l, t: int(t[0]) if t[0] else 0) |
| 760 |
|
| 761 |
# Translate ion |
| 762 |
openion = Literal('{').suppress() |
| 763 |
closeion = Literal('}').suppress() |
| 764 |
ion = Optional(~White() +openion +Regex("([1-9][0-9]*)?[+-]") +closeion, |
| 765 |
default='0+') |
| 766 |
ion.set_parse_action(lambda s, l, t: int(t[0][-1]+(t[0][:-1] if len(t[0]) > 1 else '1'))) |
| 767 |
|
| 768 |
# Translate counts |
| 769 |
# TODO: regex should reject a bare '.' if we want to allow dots between formula parts |
| 770 |
fract = Regex("(0|[1-9][0-9]*|)([.][0-9]*)") |
| 771 |
fract.set_parse_action(lambda s, l, t: float(t[0]) if t[0] else 1) |
| 772 |
whole = Regex("(0|[1-9][0-9]*)") |
| 773 |
whole.set_parse_action(lambda s, l, t: int(t[0]) if t[0] else 1) |
| 774 |
number = Optional(~White()+(fract|whole), default=1) |
| 775 |
# TODO use unicode ₀₁₉ in the code below? |
| 776 |
sub_fract = Regex("(\u2080|[\u2081-\u2089][\u2080-\u2089]*|)([.][\u2080-\u2089]*)") |
| 777 |
sub_fract.set_parse_action(lambda s, l, t: float(from_subscript(t[0])) if t[0] else 1) |
| 778 |
sub_whole = Regex("(\u2080|[\u2081-\u2089][\u2080-\u2089]*)") |
| 779 |
sub_whole.set_parse_action(lambda s, l, t: int(from_subscript(t[0])) if t[0] else 1) |
| 780 |
sub_count = Optional(~White()+(fract|whole|sub_fract|sub_whole), default=1) |
| 781 |
|
| 782 |
# Fasta code |
| 783 |
fasta = Regex("aa|rna|dna") + Literal(":").suppress() + Regex("[A-Z *-]+") |
| 784 |
def convert_fasta(string, location, tokens): |
| 785 |
#print("fasta", string, location, tokens) |
| 786 |
# TODO: fasta is ignoring table when parsing |
| 787 |
# TODO: avoid circular imports |
| 788 |
# TODO: support other biochemicals (carbohydrate residues, lipids) |
| 789 |
from . import fasta |
| 790 |
seq_type, seq = tokens |
| 791 |
if seq_type not in fasta.CODE_TABLES: |
| 792 |
raise ValueError(f"Invalid fasta sequence type '{seq_type}:'") |
| 793 |
seq = fasta.Sequence(name=None, sequence=seq, type=seq_type) |
| 794 |
return seq.labile_formula |
| 795 |
fasta.set_parse_action(convert_fasta) |
| 796 |
|
| 797 |
# Convert symbol, isotope, ion, count to (count, isotope) |
| 798 |
element = symbol+isotope+ion+sub_count |
| 799 |
def convert_element(string, location, tokens): |
| 800 |
"""interpret string as element""" |
| 801 |
#print "convert_element received", tokens |
| 802 |
symbol, isotope, ion, count = tokens[0:4] |
| 803 |
if isotope != 0: |
| 804 |
symbol = symbol[isotope] |
| 805 |
if ion != 0: |
| 806 |
symbol = symbol.ion[ion] |
| 807 |
return (count, symbol) |
| 808 |
element.set_parse_action(convert_element) |
| 809 |
|
| 810 |
# Convert "count elements" to a pair |
| 811 |
implicit_group = number+OneOrMore(element) |
| 812 |
def convert_implicit(string, location, tokens): |
| 813 |
"""convert count followed by fragment""" |
| 814 |
#print "implicit", tokens |
| 815 |
count = tokens[0] |
| 816 |
fragment = tokens[1:] |
| 817 |
return fragment if count == 1 else (count, fragment) |
| 818 |
implicit_group.set_parse_action(convert_implicit) |
| 819 |
|
| 820 |
# Convert "(composite) count" to a pair |
| 821 |
opengrp = space + Literal('(').suppress() + space |
| 822 |
closegrp = space + Literal(')').suppress() + space |
| 823 |
explicit_group = opengrp + composite + closegrp + sub_count |
| 824 |
def convert_explicit(string, location, tokens): |
| 825 |
"""convert (fragment)count""" |
| 826 |
#print "explicit", tokens |
| 827 |
count = tokens[-1] |
| 828 |
fragment = tokens[:-1] |
| 829 |
return fragment if count == 1 else (count, fragment) |
| 830 |
explicit_group.set_parse_action(convert_explicit) |
| 831 |
|
| 832 |
# Build composite from a set of groups |
| 833 |
group = implicit_group | explicit_group |
| 834 |
implicit_separator = separator | space |
| 835 |
composite << group + ZeroOrMore(implicit_separator + group) |
| 836 |
|
| 837 |
density = Literal('@').suppress() + number + Optional(Regex("[ni]"), default='i') |
| 838 |
compound = (composite|fasta) + Optional(density, default=None) |
| 839 |
def convert_compound(string, location, tokens): |
| 840 |
"""convert material @ density or fasta @ density""" |
| 841 |
# Messiness: both composite and density can be one or more tokens |
| 842 |
# If density is missing then it is None, otherwise it is count + [ni] |
| 843 |
# Compound can be a sequence of (count, fragment) pairs, or if it is |
| 844 |
# a fasta sequence it may already be a formula. |
| 845 |
material = tokens[:-1] if tokens[-1] is None else tokens[:-2] |
| 846 |
#print("compound", material, type(material[0]), len(material)) |
| 847 |
if len(material) == 1 and isinstance(material[0], Formula): |
| 848 |
formula = material[0] |
| 849 |
else: |
| 850 |
#print("unbundling material", material) |
| 851 |
formula = Formula(structure=_immutable(material)) |
| 852 |
density, form = (None, None) if tokens[-1] is None else tokens[-2:] |
| 853 |
#if density is None and formula.density is None: |
| 854 |
# # Estimate density from covalent radii and a 0.54 packing factor |
| 855 |
# mass = formula.molecular_mass |
| 856 |
# volume = formula.volume(packing_factor=0.54, H_radius=1.15) |
| 857 |
# density, form = mass/volume, 'n' |
| 858 |
# print(f"estimating density as {mass/volume=:.3f}") |
| 859 |
if form == 'n': |
| 860 |
formula.natural_density = density |
| 861 |
elif form == 'i': |
| 862 |
formula.density = density |
| 863 |
#print("compound", formula, f"{formula.density=:.3f}") |
| 864 |
return formula |
| 865 |
compound.set_parse_action(convert_compound) |
| 866 |
|
| 867 |
partsep = space + Literal('//').suppress() + space |
| 868 |
percent = Literal('%').suppress() |
| 869 |
weight = Regex("(w((eigh)?t)?|m(ass)?)").suppress() |
| 870 |
volume = Regex("v(ol(ume)?)?").suppress() |
| 871 |
weight_percent = (percent + weight) | (weight + percent) + space |
| 872 |
volume_percent = (percent + volume) | (volume + percent) + space |
| 873 |
mixture_by_weight = (number + weight_percent + mixture |
| 874 |
+ ZeroOrMore(partsep+number+(weight_percent|percent)+mixture) |
| 875 |
+ Optional(partsep + mixture, default=None)) |
| 876 |
def _parts_by_weight_vol(tokens): |
| 877 |
#print("by weight or volume", tokens) |
| 878 |
if tokens[-1] is None: |
| 879 |
piece = tokens[1:-1:2] |
| 880 |
fract = [float(v) for v in tokens[:-1:2]] |
| 881 |
if abs(sum(fract) - 100) > 1e-12: |
| 882 |
raise ValueError(f"Formula percentages must sum to 100%, not {sum(fract)}") |
| 883 |
else: |
| 884 |
piece = tokens[1:-1:2] + [tokens[-1]] |
| 885 |
fract = [float(v) for v in tokens[:-1:2]] |
| 886 |
fract.append(100-sum(fract)) |
| 887 |
if fract[-1] < 0: |
| 888 |
raise ValueError("Formula percentages must sum to less than 100%") |
| 889 |
#print piece, fract |
| 890 |
if len(piece) != len(fract): |
| 891 |
raise ValueError("Missing base component of mixture") |
| 892 |
return piece, fract |
| 893 |
def convert_by_weight(string, location, tokens): |
| 894 |
"""convert mixture by wt% or mass%""" |
| 895 |
piece, fract = _parts_by_weight_vol(tokens) |
| 896 |
return _mix_by_weight_pairs(zip(piece, fract)) |
| 897 |
mixture_by_weight.set_parse_action(convert_by_weight) |
| 898 |
|
| 899 |
mixture_by_volume = (number + volume_percent + mixture |
| 900 |
+ ZeroOrMore(partsep+number+(volume_percent|percent)+mixture) |
| 901 |
+ Optional(partsep + mixture, default=None)) |
| 902 |
def convert_by_volume(string, location, tokens): |
| 903 |
"""convert mixture by vol%""" |
| 904 |
piece, fract = _parts_by_weight_vol(tokens) |
| 905 |
return _mix_by_volume_pairs(zip(piece, fract)) |
| 906 |
mixture_by_volume.set_parse_action(convert_by_volume) |
| 907 |
|
| 908 |
mixture_by_layer = Forward() |
| 909 |
layer_thick = Group(number + Regex(LENGTH_RE) + space) |
| 910 |
layer_part = (layer_thick + mixture) | (opengrp + mixture_by_layer + closegrp + sub_count) |
| 911 |
mixture_by_layer << layer_part + ZeroOrMore(partsep + layer_part) |
| 912 |
def convert_by_layer(string, location, tokens): |
| 913 |
"""convert layer thickness '# nm material'""" |
| 914 |
if len(tokens) < 2: |
| 915 |
return tokens |
| 916 |
piece = [] |
| 917 |
fract = [] |
| 918 |
for p1, p2 in zip(tokens[0::2], tokens[1::2]): |
| 919 |
if isinstance(p1, Formula): |
| 920 |
f = p1.thickness * float(p2) |
| 921 |
p = p1 |
| 922 |
else: |
| 923 |
f = float(p1[0]) * LENGTH_UNITS[p1[1]] |
| 924 |
p = p2 |
| 925 |
piece.append(p) |
| 926 |
fract.append(f) |
| 927 |
total = sum(fract) |
| 928 |
vfract = [(v/total)*100 for v in fract] |
| 929 |
result = _mix_by_volume_pairs(zip(piece, vfract)) |
| 930 |
result.thickness = total |
| 931 |
return result |
| 932 |
mixture_by_layer.set_parse_action(convert_by_layer) |
| 933 |
|
| 934 |
mixture_by_absmass = Forward() |
| 935 |
absmass_mass = Group(number + Regex(MASS_VOLUME_RE) + space) |
| 936 |
absmass_part = (absmass_mass + mixture) | (opengrp + mixture_by_absmass + closegrp + sub_count) |
| 937 |
mixture_by_absmass << absmass_part + ZeroOrMore(partsep + absmass_part) |
| 938 |
def convert_by_absmass(string, location, tokens): |
| 939 |
"""convert mass '# mg material'""" |
| 940 |
if len(tokens) < 2: |
| 941 |
return tokens |
| 942 |
piece = [] |
| 943 |
fract = [] |
| 944 |
for p1, p2 in zip(tokens[0::2], tokens[1::2]): |
| 945 |
if isinstance(p1, Formula): |
| 946 |
p = p1 |
| 947 |
f = p1.total_mass * float(p2) |
| 948 |
else: |
| 949 |
p = p2 |
| 950 |
value = float(p1[0]) |
| 951 |
if p1[1] in VOLUME_UNITS: |
| 952 |
# convert to volume in liters to mass in grams before mixing |
| 953 |
if p.density is None: |
| 954 |
raise ValueError("Need the mass density of "+str(p)) |
| 955 |
f = value * VOLUME_UNITS[p1[1]] * 1000.*p.density |
| 956 |
else: |
| 957 |
f = value * MASS_UNITS[p1[1]] |
| 958 |
piece.append(p) |
| 959 |
fract.append(f) |
| 960 |
|
| 961 |
total = sum(fract) |
| 962 |
mfract = [(m/total)*100 for m in fract] |
| 963 |
result = _mix_by_weight_pairs(zip(piece, mfract)) |
| 964 |
result.total_mass = total |
| 965 |
return result |
| 966 |
mixture_by_absmass.set_parse_action(convert_by_absmass) |
| 967 |
|
| 968 |
ungrouped_mixture = (mixture_by_weight | mixture_by_volume |
| 969 |
| mixture_by_layer | mixture_by_absmass) |
| 970 |
grouped_mixture = opengrp + ungrouped_mixture + closegrp + Optional(density, default=None) |
| 971 |
def convert_mixture(string, location, tokens): |
| 972 |
"""convert (mixture) @ density""" |
| 973 |
formula = tokens[0] |
| 974 |
if tokens[-1] == 'n': |
| 975 |
formula.natural_density = tokens[-2] |
| 976 |
elif tokens[-1] == 'i': |
| 977 |
formula.density = tokens[-2] |
| 978 |
# elif tokens[-1] is None |
| 979 |
return formula |
| 980 |
grouped_mixture.set_parse_action(convert_mixture) |
| 981 |
|
| 982 |
mixture << (compound | grouped_mixture) |
| 983 |
formula = (compound | ungrouped_mixture | grouped_mixture) |
| 984 |
grammar = Optional(formula, default=Formula()) + StringEnd() |
| 985 |
|
| 986 |
grammar.set_name('Chemical Formula') |
| 987 |
return grammar |
| 988 |
|
| 989 |
_PARSER_CACHE: dict[PeriodicTable, ParserElement] = {} |
| 990 |
def parse_formula(formula_str: str, table: PeriodicTable|None=None) -> Formula: |
| 991 |
""" |
| 992 |
Parse a chemical formula, returning a structure with elements from the |
| 993 |
given periodic table. |
| 994 |
""" |
| 995 |
table = default_table(table) |
| 996 |
if table not in _PARSER_CACHE: |
| 997 |
_PARSER_CACHE[table] = formula_grammar(table) |
| 998 |
parser = _PARSER_CACHE[table] |
| 999 |
#print(parser) |
| 1000 |
return parser.parse_string(formula_str)[0] |
| 1001 |
|
| 1002 |
def _count_atoms(seq: Structure) -> dict[Atom, float]: |
| 1003 |
""" |
| 1004 |
Traverse formula structure, counting the total number of atoms. |
| 1005 |
""" |
| 1006 |
total: dict[Atom, float] = {} |
| 1007 |
for count, fragment in seq: |
| 1008 |
if isinstance(fragment, (list, tuple)): |
| 1009 |
partial = _count_atoms(fragment) |
| 1010 |
else: |
| 1011 |
partial = {fragment: 1} |
| 1012 |
for atom, atom_count in partial.items(): |
| 1013 |
if atom not in total: |
| 1014 |
total[atom] = 0 |
| 1015 |
total[atom] += atom_count*count |
| 1016 |
return total |
| 1017 |
|
| 1018 |
# TODO: return type is dict[Element, float] if by_isotope is False |
| 1019 |
# TODO: return type is dict[Element|Isotope, float], but being lazy and using Atom |
| 1020 |
def count_elements(compound: FormulaInput, by_isotope: bool=False) -> dict[Atom, float]: |
| 1021 |
""" |
| 1022 |
Element composition of the molecule. |
| 1023 |
|
| 1024 |
Returns {*element*: *count*, ...} where the *count* is the total number |
| 1025 |
of each element in the chemical formula, summed across all isotopes and |
| 1026 |
ionization levels. |
| 1027 |
|
| 1028 |
If *by_isotope* is True, then sum across ionization |
| 1029 |
levels, keeping the individual isotopes separate. |
| 1030 |
""" |
| 1031 |
total: dict[Atom, float] = {} |
| 1032 |
# Note: could accumulate charge at the same time as counting elements. |
| 1033 |
for atom, count in formula(compound).atoms.items(): |
| 1034 |
# Resolve isotopes and ions to the underlying element. Four cases: |
| 1035 |
# isotope with charge needs fragment.element.element |
| 1036 |
# isotope without charge needs fragment.element |
| 1037 |
# element with charge needs fragment.element |
| 1038 |
# element without charge needs fragment |
| 1039 |
if ision(atom): |
| 1040 |
atom = cast(Ion, atom).element |
| 1041 |
if not by_isotope and isisotope(atom): |
| 1042 |
atom = cast(Isotope, atom).element |
| 1043 |
total[atom] = count + total.get(atom, 0.) |
| 1044 |
return total |
| 1045 |
|
| 1046 |
# TODO: _immutable() should return Structure |
| 1047 |
def _immutable(seq): |
| 1048 |
""" |
| 1049 |
Traverse formula structure, checking that the counts are numeric and |
| 1050 |
units are atoms. Returns an immutable copy of the structure, with all |
| 1051 |
lists replaced by tuples. |
| 1052 |
""" |
| 1053 |
if isatom(seq): |
| 1054 |
return seq |
| 1055 |
return tuple((count+0, _immutable(fragment)) for count, fragment in seq) |
| 1056 |
|
| 1057 |
# TODO: _change_table() should return Structure |
| 1058 |
def _change_table(seq, table: PeriodicTable): |
| 1059 |
"""Converts lists to tuples so that structure is immutable.""" |
| 1060 |
if isatom(seq): |
| 1061 |
return change_table(seq, table) |
| 1062 |
return tuple((count, _change_table(fragment, table)) |
| 1063 |
for count, fragment in seq) |
| 1064 |
|
| 1065 |
def _hill_key(a: Atom) -> str: |
| 1066 |
return "".join((("0" if a.symbol in ("C", "H") else "1"), |
| 1067 |
a.symbol, |
| 1068 |
"%4d"%(cast(Isotope, a).isotope if isisotope(a) else 0))) |
| 1069 |
|
| 1070 |
def _convert_to_hill_notation(atoms: dict[Atom, float]) -> Structure: |
| 1071 |
""" |
| 1072 |
Return elements listed in standard order. |
| 1073 |
""" |
| 1074 |
return tuple((atoms[el], el) for el in sorted(atoms.keys(), key=_hill_key)) |
| 1075 |
|
| 1076 |
def _str_one_atom(fragment: Atom) -> str: |
| 1077 |
# Normal isotope string form is #-Yy, but we want Yy[#] |
| 1078 |
if isisotope(fragment) and 'symbol' not in fragment.__dict__: |
| 1079 |
ret = "%s[%d]"%(fragment.symbol, cast(Isotope, fragment).isotope) |
| 1080 |
else: |
| 1081 |
ret = fragment.symbol |
| 1082 |
if fragment.charge != 0: |
| 1083 |
sign = '+' if fragment.charge > 0 else '-' |
| 1084 |
value = str(abs(fragment.charge)) if abs(fragment.charge) > 1 else '' |
| 1085 |
ret += '{'+value+sign+'}' |
| 1086 |
return ret |
| 1087 |
|
| 1088 |
# TODO: add typing to _str_atoms |
| 1089 |
def _str_atoms(seq) -> str: |
| 1090 |
""" |
| 1091 |
Convert formula structure to string. |
| 1092 |
""" |
| 1093 |
#print "str", seq |
| 1094 |
ret = "" |
| 1095 |
for count, fragment in seq: |
| 1096 |
if isatom(fragment): |
| 1097 |
ret += _str_one_atom(fragment) |
| 1098 |
if count != 1: |
| 1099 |
ret += "%g"%count |
| 1100 |
else: |
| 1101 |
if count == 1: |
| 1102 |
piece = _str_atoms(fragment) |
| 1103 |
else: |
| 1104 |
piece = "(%s)%g"%(_str_atoms(fragment), count) |
| 1105 |
#ret = ret+" "+piece if ret else piece |
| 1106 |
ret += piece |
| 1107 |
|
| 1108 |
return ret |
| 1109 |
|
| 1110 |
|
| 1111 |
def from_subscript(value: str) -> str: |
| 1112 |
""" |
| 1113 |
Convert unicode subscript characters to normal characters. This allows us to parse, |
| 1114 |
for example, H₂O as H2O. |
| 1115 |
""" |
| 1116 |
subscript_codepoints = { |
| 1117 |
'\u2080': '0', '\u2081': '1', '\u2082': '2', '\u2083': '3', |
| 1118 |
'\u2084': '4', '\u2085': '5', '\u2086': '6', '\u2087': '7', |
| 1119 |
'\u2088': '8', '\u2089': '9', '\u208a': '+', '\u208b': '-', |
| 1120 |
'\u208c': '=', '\u208d': '(', '\u208e': ')', |
| 1121 |
|
| 1122 |
'\u2090': 'a', '\u2091': 'e', '\u2092': 'o', '\u2093': 'x', |
| 1123 |
'\u2095': 'h', '\u2096': 'k', '\u2097': 'l', |
| 1124 |
'\u2098': 'm', '\u2099': 'n', '\u209a': 'p', '\u209b': 's', |
| 1125 |
'\u209c': 't', |
| 1126 |
} |
| 1127 |
return ''.join(subscript_codepoints.get(char, char) for char in str(value)) |
| 1128 |
|
| 1129 |
def unicode_subscript(value: str) -> str: |
| 1130 |
# Unicode subscript codepoints. Note that decimal point looks okay as subscript |
| 1131 |
subscript_codepoints = { |
| 1132 |
'0': '\u2080', '1': '\u2081', '2': '\u2082', '3': '\u2083', |
| 1133 |
'4': '\u2084', '5': '\u2085', '6': '\u2086', '7': '\u2087', |
| 1134 |
'8': '\u2088', '9': '\u2089', '+': '\u208a', '-': '\u208b', |
| 1135 |
'=': '\u208c', '(': '\u208d', ')': '\u208e', |
| 1136 |
|
| 1137 |
'a': '\u2090', 'e': '\u2091', 'o': '\u2092', 'x': '\u2093', |
| 1138 |
'h': '\u2095', 'k': '\u2096', 'l': '\u2097', |
| 1139 |
'm': '\u2098', 'n': '\u2099', 'p': '\u209a', 's': '\u209b', |
| 1140 |
't': '\u209c', |
| 1141 |
|
| 1142 |
'\u2013': '\u208b', # en-dash is same as dash |
| 1143 |
'\u2014': '\u208b', # em-dash is same as dash |
| 1144 |
} |
| 1145 |
return ''.join(subscript_codepoints.get(char, char) for char in str(value)) |
| 1146 |
|
| 1147 |
def unicode_superscript(value: str) -> str: |
| 1148 |
# Unicode subscript codepoints. Note that decimal point looks okay as subscript |
| 1149 |
superscript_codepoints = { |
| 1150 |
#'.': '\u00B0', # degree symbol looks too much like zero |
| 1151 |
#'.': ' \u02D9', # dot above modifier looks okay in a floating string, but risky |
| 1152 |
#'.': ' \u0307', # space with dot above? |
| 1153 |
#'.': '\u22C5', # math dot operator |
| 1154 |
'.': '\u1427', # Canadian aboriginal extended block dot (looks good on mac) |
| 1155 |
'2': '\u00B2', '3': '\u00B3', |
| 1156 |
'1': '\u00B9', |
| 1157 |
'0': '\u2070', 'i': '\u2071', |
| 1158 |
'4': '\u2074', '5': '\u2075', '6': '\u2076', '7': '\u2077', |
| 1159 |
'9': '\u2078', '0': '\u2079', '+': '\u207a', '-': '\u207b', |
| 1160 |
'=': '\u207c', '(': '\u207d', ')': '\u207e', 'n': '\u207f', |
| 1161 |
|
| 1162 |
'\u2013': '\u207b', # en-dash is same as dash |
| 1163 |
'\u2014': '\u207b', # em-dash is same as dash |
| 1164 |
} |
| 1165 |
return ''.join(superscript_codepoints.get(char, char) for char in str(value)) |
| 1166 |
|
| 1167 |
SUBSCRIPT: dict[str, Callable[[str], str]] = { |
| 1168 |
# The latex renderer should work for github style markdown |
| 1169 |
'latex': lambda text: f'$_{{{text}}}$', |
| 1170 |
'html': lambda text: f'<sub>{text}</sub>', |
| 1171 |
'unicode': unicode_subscript, |
| 1172 |
'plain': lambda text: text |
| 1173 |
} |
| 1174 |
def pretty(compound: Formula, mode: str='unicode') -> str: |
| 1175 |
""" |
| 1176 |
Convert the formula to a string. The *mode* can be 'unicode', 'html' or |
| 1177 |
'latex' depending on how subscripts should be rendered. If *mode* is 'plain' |
| 1178 |
then don't use subscripts for the element quantities. |
| 1179 |
|
| 1180 |
Use *pretty(compound.hill)* for a more compact representation. |
| 1181 |
""" |
| 1182 |
return _pretty(compound.structure, SUBSCRIPT[mode]) |
| 1183 |
|
| 1184 |
# TODO: type hinting for _pretty |
| 1185 |
def _pretty(structure, subscript: Callable[[str], str]) -> str: |
| 1186 |
# TODO: if superscript is not None then render O[16] as {}^{16}O |
| 1187 |
parts = [] |
| 1188 |
for count, part in structure: |
| 1189 |
if isinstance(part, tuple): |
| 1190 |
if count == 1: |
| 1191 |
parts.append(_pretty(part, subscript)) |
| 1192 |
else: |
| 1193 |
parts.append(f'({_pretty(part, subscript)}){subscript(count)}') |
| 1194 |
elif count == 1: |
| 1195 |
parts.append(f'{_str_one_atom(part)}') |
| 1196 |
else: |
| 1197 |
parts.append(f'{_str_one_atom(part)}{subscript(count)}') |
| 1198 |
return ''.join(parts) |
| 1199 |
|
| 1200 |
|
| 1201 |
def demo(): |
| 1202 |
import sys |
| 1203 |
compound = formula(sys.argv[1]) |
| 1204 |
if compound.density is None: |
| 1205 |
print(f"Missing density for {pretty(compound.hill)}") |
| 1206 |
else: |
| 1207 |
print(f"{pretty(compound.hill)}@{compound.density:.3f} sld={compound.neutron_sld()}") |
| 1208 |
#print(pretty(compound.hill, 'latex')) |
| 1209 |
#print(pretty(compound.hill, 'html')) |
| 1210 |
#print(pretty(compound.hill, 'unicode')) |
| 1211 |
#print(pretty(compound.hill, 'plain')) |
| 1212 |
|
| 1213 |
if __name__ == "__main__": |
| 1214 |
demo() |