Debian Codegraph @

periodictable/core.py

raw
1 # This program is public domain
2 # Author: Paul Kienzle
3 """
4 Core classes for the periodic table.
5
6 * :class:`PeriodicTable`
7 The periodic table with attributes for each element.
8
9 .. Note:: PeriodicTable is not a singleton class. Use ``periodictable.element``
10 to access the common table.
11
12 * :class:`Element`
13 Element properties such as name, symbol, mass, density, etc.
14
15 * :class:`Isotope`
16 Isotope properties such as mass, density and neutron scattering factors.
17
18 * :class:`Ion`
19 Ion properties such as charge.
20
21 Elements are accessed from a periodic table using ``table[number]``,
22 ``table.name`` or ``table.symbol`` where *symbol* is the two letter symbol.
23 Individual isotopes are accessed using ``element[isotope]``. Individual ions
24 are references using ``element.ion[charge]``. Note that
25 ``element[isotope].ion[charge].mass`` will depend on the particular charge
26 since we subtract the charge times the rest mass of the electron from the
27 overall mass.
28
29 Helper functions:
30
31 * :func:`delayed_load`
32 Delay loading the element attributes until they are needed.
33
34 * :func:`get_data_path`
35 Return the path to the periodic table data files.
36
37 * :func:`define_elements`
38 Define external variables for each element in namespace.
39
40 * :func:`isatom`, :func:`iselement`, :func:`isisotope`, :func:`ision`
41 Tests for different types of structure components.
42
43 * :func:`default_table`
44 Returns the common periodic table.
45
46 * :func:`change_table`
47 Return the same item from a different table.
48
49 .. seealso::
50
51 :ref:`Adding properties <extending>` for details on extending the periodic
52 table with your own attributes.
53
54 :ref:`Custom tables <custom-table>` for details on managing your own
55 periodic table with custom values for the attributes.
56
57 """
58
59 __docformat__ = 'restructuredtext en'
60 __all__ = ['delayed_load', 'define_elements', 'get_data_path',
61 'default_table', 'change_table',
62 'Ion', 'IonSet', 'Isotope', 'Element', 'PeriodicTable',
63 'isatom', 'iselement', 'isisotope', 'ision']
64
65 from pathlib import Path
66 from typing import TYPE_CHECKING, cast, Any, Union, TypeVar, List, overload, Literal
67 from collections.abc import Sequence, Callable, Iterator
68
69 if TYPE_CHECKING:
70 # Circular imports; only include them for type checking
71 from .nsf import Neutron
72 from .activation import ActivationResult
73 from .xsf import Xray
74 from .magnetic_ff import MagneticFormFactor
75
76 from . import constants
77
78 Atom = Union["Element", "Isotope", "Ion"]
79 AtomVar = TypeVar('AtomVar', bound=Atom)
80
81 PUBLIC_TABLE_NAME = "public"
82
83 def delayed_load(all_props: Sequence[str], loader: Callable[[], None], element=True, isotope=False, ion=False):
84 """
85 Delayed loading of an element property table. When any of property
86 is first accessed the loader will be called to load the associated
87 data. The help string starts out as the help string for the loader
88 function. The attribute may be associated with any of :class:`Isotope`,
89 :class:`Ion`, or :class:`Element`. Some properties, such as
90 :mod:`mass <periodictable.mass>`, have both an isotope property for the
91 mass of specific isotopes, as well as an element property for the
92 mass of the collection of isotopes at natural abundance. Set the
93 keyword flags *element*, *isotope* and/or *ion* to specify which
94 of these classes will be assigned specific information on load.
95 """
96 def clearprops():
97 """
98 Remove the properties so that the attribute can be accessed
99 directly.
100 """
101 if element:
102 for p in all_props:
103 delattr(Element, p)
104 if isotope:
105 for p in all_props:
106 delattr(Isotope, p)
107 if ion:
108 for p in all_props:
109 delattr(Ion, p)
110
111 def getter(propname):
112 """
113 Property getter for attribute propname.
114
115 The first time the prop is accessed, the prop itself will be
116 deleted and the data loader for the property will be called
117 to set the real values. Subsequent references to the property
118 will be to the actual data.
119 """
120 def getfn(el):
121 #print "get", el, propname
122 clearprops()
123 loader()
124 return getattr(el, propname)
125 return getfn
126
127 def setter(propname):
128 """
129 Property setter for attribute propname.
130
131 This function is assumed to be called when the data loader for the
132 attribute is called before the property is referenced (for example,
133 if somebody imports periodictable.xsf before referencing Ni.xray).
134 In this case, we simply need to clear the delayed load property and
135 let the loader set the values as usual.
136
137 If the user tries to override a value in the table before first
138 referencing the table, then the above assumption is false. E.g.,
139 "Ni.K_alpha=5" followed by "print Cu.K_alpha" will yield an
140 undefined Cu.K_alpha. This will be difficult for future users
141 to debug.
142 """
143 def setfn(el, value):
144 #print "set", el, propname, value
145 clearprops()
146 # Since the property is now cleared the lazy loader will not be
147 # triggered in the getter for a different element, so call it here.
148 loader()
149 setattr(el, propname, value)
150 return setfn
151
152 doc = loader.__doc__
153 if element:
154 for p in all_props:
155 prop = property(getter(p), setter(p), doc=doc)
156 setattr(Element, p, prop)
157
158 if isotope:
159 for p in all_props:
160 prop = property(getter(p), setter(p), doc=doc)
161 setattr(Isotope, p, prop)
162
163 if ion:
164 for p in all_props:
165 prop = property(getter(p), setter(p), doc=doc)
166 setattr(Ion, p, prop)
167
168 # TODO: types for properties are not being handled correctly
169 # I've left them as simple "name: float" for now so that the editor will see them.
170 # Because I'm using delegation via __getattr__ the properties need to be listed in
171 # _AtomBase, but I can't define them as properties there because it confuses the
172 # delegation mechanism. Possible work-arounds are to build the delegation into the
173 # property, or figure out how to define a property return type that is seen by the
174 # static type analyzers without defining the property itself.
175 class _AtomBase:
176 """
177 Attributes common to element, isotope and ion.
178
179 This class is defined only for type hinting. Some of the attributes are accessible
180 as properties. Those not defined in isotope or ion are delegated to the base element
181 through attribute access magic.
182 """
183 # attributes delegated to Element class
184 table: str
185 name: str
186 symbol: str
187 number: int
188 ions: tuple[int, ...]
189 ion: "IonSet" # TODO: could be IonSet[Element] or IonSet[Isotope]
190 charge: int # element (=0), isotope (delegate to element), ion (!= 0)
191
192 #element: Union["Element", "Isotope"] # isotope or ion, not element
193
194 # mass.py
195 mass: float # property
196 _mass: float # internal
197 _mass_unc: float # Not yet official, but the data is loaded for some tables
198 mass_units: str # element, isotope, ion
199 #abundance: float # isotope only
200 #abundance_units: str # isotope only
201
202 # covalent_radius.py
203 covalent_radius: float|None # element
204 covalent_radius_uncertainty: float|None # element
205 covalent_radius_units: str # element
206
207 # crystal_structure.py
208 crystal_structure: dict[str, Any]|None # element
209
210 # density.py
211 density: float # property
212 _density: float
213 density_units: str
214 interatomic_distance: float # property
215 interatomic_distance_units: str
216 number_density: float # property
217 number_density_units: str
218 density_caveat: str|None
219
220 # nsf.py
221 neutron: "Neutron" # element and isotope
222 #nuclear_spin: str # isotope only
223
224 # activation.py
225 #neutron_activation: tuple["ActivationResult"]|None # isotope only
226
227 # xsf.py
228 K_alpha: float|None # element
229 K_beta1: float|None # element
230 K_alpha_units: str # element
231 K_beta1_units: str # element
232 xray: "Xray" # element
233
234 # magnetic_ff.py
235 magnetic_ff: dict[int, "MagneticFormFactor"] # element
236
237 class Element(_AtomBase):
238 """
239 Periodic table entry for an element.
240
241 An element is a name, symbol and number, plus a set of properties.
242 Individual isotopes can be referenced as element[*isotope_number*].
243 Individual ionization states can be referenced by element.ion[*charge*].
244 """
245 table: str = PUBLIC_TABLE_NAME
246 charge: int = 0
247
248 def __init__(self, name: str, symbol: str, Z: int, ions: tuple[int, ...], table: "str"):
249 self.name = name
250 self.symbol = symbol
251 self.number = Z
252 self._isotopes: dict[int, "Isotope"] = {} # The actual isotopes
253 self.ions = ions
254 self.ion = IonSet(self)
255 # Remember the table name for pickle dump/load
256 if table != self.table:
257 self.table = table
258
259 @property
260 def isotopes(self) -> list[int]:
261 """List of all isotopes"""
262 # Note: may want to return the iterator rather than the list...
263 return list(sorted(self._isotopes.keys()))
264
265 def add_isotope(self, number: int) -> "Isotope":
266 """
267 Add an isotope for the element.
268
269 :Parameters:
270 *number* : integer
271 Isotope number, which is the number protons plus neutrons.
272
273 :Returns: None
274 """
275 if number not in self._isotopes:
276 self._isotopes[number] = Isotope(self, number)
277 return self._isotopes[number]
278
279 def __getitem__(self, number: int) -> "Isotope":
280 try:
281 return self._isotopes[number]
282 except KeyError:
283 raise KeyError("%s is not an isotope of %s"%(number, self.symbol))
284
285 def __iter__(self) -> Iterator["Isotope"]:
286 """
287 Process the isotopes in order
288 """
289 for _, iso in sorted(self._isotopes.items()):
290 yield iso
291
292 # Note: using repr rather than str for the element symbol so
293 # that lists of elements print nicely. Since elements are
294 # effectively singletons, the symbol name is the representation
295 # of the instance.
296 def __repr__(self) -> str:
297 return self.symbol
298
299 def __reduce__(self):
300 return _make_element, (self.table, self.number)
301
302 class Isotope(_AtomBase):
303 """
304 Periodic table entry for an individual isotope.
305
306 An isotope is associated with an element. In addition to the element
307 properties (*symbol*, *name*, *atomic number*), it has specific isotope
308 properties (*isotope number*, *nuclear spin*, *relative abundance*).
309 Properties not specific to the isotope (e.g., *x-ray scattering factors*)
310 are retrieved from the associated element.
311 """
312 element: Element
313 isotope: int
314
315 # mass.py
316 # TODO: Do we still need to modify isotope.abundance during mass.init()?
317 @property
318 def abundance(self) -> float:
319 return self._abundance
320 _abundance: float
321 _abundance_unc: float
322 abundance_units: str # isotope only
323
324 # activation.py
325 neutron_activation: tuple["ActivationResult"] # isotope only
326
327 # nsf.py
328 nuclear_spin: str
329
330 def __init__(self, element: Element, isotope_number: int):
331 self.element = element
332 self.isotope = isotope_number
333 self.ion = IonSet(self)
334 def __getattr__(self, attr):
335 return getattr(self.element, attr)
336 def __str__(self) -> str:
337 # Deuterium and Tritium are special
338 if 'symbol' in self.__dict__:
339 return self.symbol
340 return "%d-%s"%(self.isotope, self.element.symbol)
341 def __repr__(self) -> str:
342 return "%s[%d]"%(self.element.symbol, self.isotope)
343 def __reduce__(self):
344 return _make_isotope, (self.element.table,
345 self.element.number,
346 self.isotope)
347
348 class Ion(_AtomBase):
349 """
350 Periodic table entry for an individual ion.
351
352 An ion is associated with an element. In addition to the element
353 properties (*symbol*, *name*, *atomic number*), it has specific ion
354 properties (*charge*). Properties not specific to the ion (i.e., *charge*)
355 are retrieved from the associated element.
356 """
357 element: Element|Isotope
358 # charge: int # inherited from _AtomBase
359
360 # TODO: abundance and activation need to be defined for charged isotopes.
361
362 def __init__(self, element: Element|Isotope, charge: int):
363 self.element = element
364 self.charge = charge
365 def __getattr__(self, attr: str) -> Any:
366 return getattr(self.element, attr)
367 @property
368 def mass(self) -> float: # type: ignore[override]
369 return getattr(self.element, 'mass') - constants.electron_mass*self.charge
370 def __str__(self) -> str:
371 sign = '+' if self.charge > 0 else '-'
372 value = '%d'%abs(self.charge) if abs(self.charge) > 1 else ''
373 charge_str = '{'+value+sign+'}' if self.charge != 0 else ''
374 return str(self.element)+charge_str
375 def __repr__(self) -> str:
376 return repr(self.element)+'.ion[%d]'%self.charge
377 def __reduce__(self):
378 if isinstance(self.element, Isotope):
379 iso = cast("Isotope", self.element)
380 return _make_isotope_ion, (iso.table, iso.number, iso.isotope, self.charge)
381 else:
382 el = cast("Element", self.element)
383 return _make_ion, (el.table, el.number, self.charge)
384
385 class IonSet:
386 """
387 The set of ions associated with an element or isotope.
388
389 This is a dictionary interface indexed by ion charge.
390 """
391 element_or_isotope: Element|Isotope
392 ionset: dict[int, Ion]
393
394 def __init__(self, element_or_isotope: Element|Isotope):
395 self.element_or_isotope = element_or_isotope
396 self.ionset = {}
397
398 def __getitem__(self, charge: int) -> Ion:
399 if charge not in self.ionset:
400 if charge not in self.element_or_isotope.ions:
401 raise ValueError("%(charge)d is not a valid charge for %(symbol)s"
402 % dict(charge=charge,
403 symbol=self.element_or_isotope.symbol))
404 self.ionset[charge] = Ion(self.element_or_isotope, charge)
405 return self.ionset[charge]
406
407
408 # Define the element names from the element table.
409 class PeriodicTable:
410 """
411 Defines the periodic table of the elements with isotopes.
412 Individidual elements are accessed by name, symbol or atomic number.
413 Individual isotopes are addressable by ``element[mass_number]`` or
414 ``elements.isotope(element name)``, ``elements.isotope(element symbol)``.
415
416 For example, the following all retrieve iron:
417
418 .. doctest::
419
420 >>> from periodictable import *
421 >>> print(elements[26])
422 Fe
423 >>> print(elements.Fe)
424 Fe
425 >>> print(elements.symbol('Fe'))
426 Fe
427 >>> print(elements.name('iron'))
428 Fe
429 >>> print(elements.isotope('Fe'))
430 Fe
431
432
433 To get iron-56, use:
434
435 .. doctest::
436
437 >>> print(elements[26][56])
438 56-Fe
439 >>> print(elements.Fe[56])
440 56-Fe
441 >>> print(elements.isotope('56-Fe'))
442 56-Fe
443
444
445 Deuterium and tritium are defined as 'D' and 'T'.
446
447 To show all the elements in the table, use the iterator:
448
449 .. doctest::
450
451 >>> from periodictable import *
452 >>> for el in elements: # lists the element symbols
453 ... print("%s %s"%(el.symbol, el.name)) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
454 H hydrogen
455 He helium
456 ...
457 Og oganesson
458
459
460 .. Note::
461 Properties can be added to the elements as needed, including *mass*,
462 *nuclear* and *X-ray* scattering cross sections.
463 See section :ref:`Adding properties <extending>` for details.
464 """
465 properties: List[str] # list method shadows builtin list, so using List instead
466 """Properties loaded into the table"""
467
468 # Tedious listing of available elements for typed table.El access
469 n: Element
470 H: Element
471 D: Isotope
472 T: Isotope
473 He: Element
474 Li: Element
475 Be: Element
476 B: Element
477 C: Element
478 N: Element
479 O: Element
480 F: Element
481 Ne: Element
482 Na: Element
483 Mg: Element
484 Al: Element
485 Si: Element
486 P: Element
487 S: Element
488 Cl: Element
489 Ar: Element
490 K: Element
491 Ca: Element
492 Sc: Element
493 Ti: Element
494 V: Element
495 Cr: Element
496 Mn: Element
497 Fe: Element
498 Co: Element
499 Ni: Element
500 Cu: Element
501 Zn: Element
502 Ga: Element
503 Ge: Element
504 As: Element
505 Se: Element
506 Br: Element
507 Kr: Element
508 Rb: Element
509 Sr: Element
510 Y: Element
511 Zr: Element
512 Nb: Element
513 Mo: Element
514 Tc: Element
515 Ru: Element
516 Rh: Element
517 Pd: Element
518 Ag: Element
519 Cd: Element
520 In: Element
521 Sn: Element
522 Sb: Element
523 Te: Element
524 I: Element
525 Xe: Element
526 Cs: Element
527 Ba: Element
528 La: Element
529 Ce: Element
530 Pr: Element
531 Nd: Element
532 Pm: Element
533 Sm: Element
534 Eu: Element
535 Gd: Element
536 Tb: Element
537 Dy: Element
538 Ho: Element
539 Er: Element
540 Tm: Element
541 Yb: Element
542 Lu: Element
543 Hf: Element
544 Ta: Element
545 W: Element
546 Re: Element
547 Os: Element
548 Ir: Element
549 Pt: Element
550 Au: Element
551 Hg: Element
552 Tl: Element
553 Pb: Element
554 Bi: Element
555 Po: Element
556 At: Element
557 Rn: Element
558 Fr: Element
559 Ra: Element
560 Ac: Element
561 Th: Element
562 Pa: Element
563 U: Element
564 Np: Element
565 Pu: Element
566 Am: Element
567 Cm: Element
568 Bk: Element
569 Cf: Element
570 Es: Element
571 Fm: Element
572 Md: Element
573 No: Element
574 Lr: Element
575 Rf: Element
576 Db: Element
577 Sg: Element
578 Bh: Element
579 Hs: Element
580 Mt: Element
581 Ds: Element
582 Rg: Element
583 Cn: Element
584 Nh: Element
585 Fl: Element
586 Mc: Element
587 Lv: Element
588 Ts: Element
589 Og: Element
590
591 def __init__(self, table: str) -> None:
592 if table in PRIVATE_TABLES:
593 raise ValueError("Periodic table '%s' is already defined"%table)
594 PRIVATE_TABLES[table] = self
595 self.properties = []
596 self._element = {}
597 for Z, (name, symbol, ions, uncommon_ions) in element_base.items():
598 element = Element(name=name.lower(), symbol=symbol, Z=Z,
599 ions=tuple(sorted(ions+uncommon_ions)), table=table)
600 self._element[element.number] = element
601 setattr(self, symbol, element)
602 PeriodicTable.__annotations__[symbol] = Element
603
604 # There are two specially named isotopes D and T
605 self.D = self.H.add_isotope(2)
606 self.D.name = 'deuterium'
607 self.D.symbol = 'D'
608 self.T = self.H.add_isotope(3)
609 self.T.name = 'tritium'
610 self.T.symbol = 'T'
611
612 def __getitem__(self, Z: int) -> Element:
613 """
614 Retrieve element Z.
615 """
616 return self._element[Z]
617
618 def __iter__(self) -> Iterator[Element]:
619 """
620 Process the elements in Z order
621 """
622 # CRUFT: Since 3.7 dictionaries use insertion order, so no need to sort
623 elements = sorted(self._element.items())
624 # Skipping the first entry (neutron) in the iterator
625 for _, el in elements[1:]:
626 yield el
627
628 @overload
629 def symbol(self, input: Literal["D"]) -> Isotope: ... # type: ignore[overload-overlap]
630
631 @overload
632 def symbol(self, input: Literal["T"]) -> Isotope: ... # type: ignore[overload-overlap]
633
634 @overload
635 def symbol(self, input: str) -> Element: ...
636
637 def symbol(self, input: str) -> Element|Isotope:
638 """
639 Lookup the an element in the periodic table using its symbol. Symbols
640 are included for 'D' and 'T', deuterium and tritium.
641
642 :Parameters:
643 *input* : string
644 Element symbol to be looked up in periodictable.
645
646 :Returns: Element
647
648 :Raises:
649 ValueError if the element symbol is not defined.
650
651 For example, print the element corresponding to 'Fe':
652
653 .. doctest::
654
655 >>> import periodictable
656 >>> print(periodictable.elements.symbol('Fe'))
657 Fe
658 """
659 if hasattr(self, input):
660 value = getattr(self, input)
661 if isinstance(value, (Element, Isotope)):
662 return value
663 raise ValueError("unknown element "+input)
664
665 def name(self, input: str) -> Element|Isotope:
666 """
667 Lookup an element given its name.
668
669 :Parameters:
670 *input* : string
671 Element name to be looked up in periodictable.
672
673 :Returns: Element (or Isotope for "D" and "T")
674
675 :Raises:
676 *ValueError* if element does not exist.
677
678 For example, print the element corresponding to 'iron':
679
680 .. doctest::
681
682 >>> import periodictable
683 >>> print(periodictable.elements.name('iron'))
684 Fe
685 """
686 for el in self:
687 if input == el.name:
688 return el
689 if input == self.D.name:
690 return self.D
691 if input == self.T.name:
692 return self.T
693 raise ValueError("unknown element "+input)
694
695 def isotope(self, input: str) -> Element|Isotope:
696 """
697 Lookup the element or isotope in the periodic table. Elements
698 are assumed to be given by the standard element symbols. Isotopes
699 are given by number-symbol, or 'D' and 'T' for 2-H and 3-H.
700
701 :Parameters:
702 *input* : string
703 Element name or isotope to be looked up in periodictable.
704
705 :Returns: Element
706
707 :Raises:
708 *ValueError* if element or isotope is not defined.
709
710 For example, print the element corresponding to '58-Ni'.
711
712 .. doctest::
713
714 >>> import periodictable
715 >>> print(periodictable.elements.isotope('58-Ni'))
716 58-Ni
717 """
718 # Parse #-Sym or Sym
719 # If # is not an integer, set isotope to -1 so that the isotope
720 # lookup will fail later.
721 parts = input.split('-')
722 if len(parts) == 1:
723 isotope = 0
724 symbol = parts[0]
725 elif len(parts) == 2:
726 try:
727 isotope = int(parts[0])
728 except Exception:
729 isotope = -1
730 symbol = parts[1]
731 else:
732 symbol = ''
733 isotope = -1
734
735 # All elements are attributes of the table
736 # Check that the attribute is an Element or an Isotope (for D or T)
737 # If it is an element, check that the isotope exists
738 if hasattr(self, symbol):
739 attr = getattr(self, symbol)
740 if isinstance(attr, Element):
741 # If no isotope, return the element
742 if isotope == 0:
743 return attr
744 # If isotope, check that it is valid
745 if isotope in attr.isotopes:
746 return attr[isotope]
747 elif isinstance(attr, Isotope):
748 # D, T must not have an associated isotope; 4-D is meaningless.
749 if isotope == 0:
750 return attr
751
752 # If we can't parse the string as an element or isotope, raise an error
753 raise ValueError("unknown element "+input)
754
755 # TODO: list method shadows builtin list in "properties: list[str]" above
756 def list(self, *props, **kw) -> None:
757 """
758 Print a list of elements with the given set of properties.
759
760 :Parameters:
761 *prop1*, *prop2*, ... : string
762 Name of the properties to print
763 *format*: string
764 Template for displaying the element properties, with one
765 % for each property.
766
767 :Returns: None
768
769 For example, print a table of mass and density.
770
771 .. doctest::
772
773 >>> from periodictable import elements
774 >>> elements.list('symbol', 'mass', 'density',
775 ... format="%-2s: %6.2f u %6.2f g/cm^3") # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
776 H : 1.01 u 0.07 g/cm^3
777 He: 4.00 u 0.12 g/cm^3
778 Li: 6.94 u 0.53 g/cm^3
779 ...
780 Bk: 247.00 u 14.00 g/cm^3
781 """
782 #TODO: accept template strings
783 #TODO: override signature in sphinx with
784 # .. method:: list(prop1, prop2, ..., format='')
785 format = kw.pop('format', None)
786 assert not kw # make sure *format* is the only keyword argument
787 for el in self:
788 try:
789 L = tuple(getattr(el, p) for p in props)
790 except AttributeError:
791 # Skip elements which don't define all the attributes
792 continue
793 # Skip elements with a value of None
794 if any(v is None for v in L):
795 continue
796
797 if format is None:
798 print(" ".join(str(p) for p in L))
799 else:
800 #try:
801 print(format%L)
802 #except:
803 # print "format", format, "args", L
804 # raise
805
806 def isatom(val: Any) -> bool:
807 """Return true if value is an element, isotope or ion"""
808 return isinstance(val, (Element, Isotope, Ion))
809
810 def isisotope(val: Any) -> bool:
811 """Return true if value is an isotope or isotope ion."""
812 if ision(val):
813 val = val.element
814 return isinstance(val, Isotope)
815
816 def ision(val: Any) -> bool:
817 """Return true if value is a specific ion of an element or isotope"""
818 return isinstance(val, Ion)
819
820 def iselement(val: Any) -> bool:
821 """Return true if value is an element or ion in natural abundance"""
822 if ision(val):
823 val = val.element
824 return isinstance(val, Element)
825
826 def change_table(atom: AtomVar, table: PeriodicTable) -> Atom:
827 """Search for the same element, isotope or ion from a different table"""
828 if ision(atom):
829 if isisotope(atom):
830 iso = cast(Isotope, atom)
831 return table[iso.number][iso.isotope].ion[iso.charge]
832 else:
833 return table[atom.number].ion[atom.charge]
834 else:
835 if isisotope(atom):
836 iso = cast(Isotope, atom)
837 return table[iso.number][iso.isotope]
838 else:
839 return table[atom.number]
840
841 PRIVATE_TABLES: dict[str, PeriodicTable] = {}
842 def _get_table(name: str) -> PeriodicTable:
843 try:
844 return PRIVATE_TABLES[name]
845 except KeyError:
846 raise ValueError("Periodic table '%s' is not initialized"%name)
847
848 def _make_element(table: str, Z: int) -> Element:
849 return _get_table(table)[Z]
850 def _make_isotope(table: str, Z: int, n: int) -> Isotope:
851 return _get_table(table)[Z][n]
852 def _make_ion(table: str, Z: int, c: int) -> Ion:
853 return _get_table(table)[Z].ion[c]
854 def _make_isotope_ion(table: str, Z: int, n: int, c: int) -> Ion:
855 return _get_table(table)[Z][n].ion[c]
856
857
858 # pylint: disable=bad-whitespace
859 element_base: dict[int, tuple[str, str, list[int], list[int]]] = {
860 # Z: ('name', 'symbol', [common ions], [uncommon ions])
861 # ion info comes from Wikipedia: list of oxidation states of the elements.
862 0: ('neutron', 'n', [], []),
863 1: ('Hydrogen', 'H', [-1, 1], []),
864 2: ('Helium', 'He', [], [1, 2]), # +1,+2 http://periodic.lanl.gov/2.shtml
865 3: ('Lithium', 'Li', [1], []),
866 4: ('Beryllium', 'Be', [2], [1]),
867 5: ('Boron', 'B', [3], [-5, -1, 1, 2]),
868 6: ('Carbon', 'C', [-4, -3, -2, -1, 1, 2, 3, 4], []),
869 7: ('Nitrogen', 'N', [-3, 3, 5], [-2, -1, 1, 2, 4]),
870 8: ('Oxygen', 'O', [-2], [-1, 1, 2]),
871 9: ('Fluorine', 'F', [-1], []),
872 10: ('Neon', 'Ne', [], []),
873 11: ('Sodium', 'Na', [1], [-1]),
874 12: ('Magnesium', 'Mg', [2], [1]),
875 13: ('Aluminum', 'Al', [3], [-2, -1, 1, 2]),
876 14: ('Silicon', 'Si', [-4, 4], [-3, -2, -1, 1, 2, 3]),
877 15: ('Phosphorus', 'P', [-3, 3, 5], [-2, -1, 1, 2, 4]),
878 16: ('Sulfur', 'S', [-2, 2, 4, 6], [-1, 1, 3, 5]),
879 17: ('Chlorine', 'Cl', [-1, 1, 3, 5, 7], [2, 4, 6]),
880 18: ('Argon', 'Ar', [], []),
881 19: ('Potassium', 'K', [1], [-1]),
882 20: ('Calcium', 'Ca', [2], [1]),
883 21: ('Scandium', 'Sc', [3], [1, 2]),
884 22: ('Titanium', 'Ti', [4], [-2, -1, 1, 2, 3]),
885 23: ('Vanadium', 'V', [5], [-3, -1, 1, 2, 3, 4]),
886 24: ('Chromium', 'Cr', [3, 6], [-4, -2, -1, 1, 2, 4, 5]),
887 25: ('Manganese', 'Mn', [2, 4, 7], [-3, -2, -1, 1, 3, 5, 6]),
888 26: ('Iron', 'Fe', [2, 3, 6], [-4, -2, -1, 1, 4, 5, 7]),
889 27: ('Cobalt', 'Co', [2, 3], [-3, -1, 1, 4, 5]),
890 28: ('Nickel', 'Ni', [2], [-2, -1, 1, 3, 4]),
891 29: ('Copper', 'Cu', [2], [-2, 1, 3, 4]),
892 30: ('Zinc', 'Zn', [2], [-2, 1]),
893 31: ('Gallium', 'Ga', [3], [-5, -4, -2, -1, 1, 2]),
894 32: ('Germanium', 'Ge', [-4, 2, 4], [-3, -2, -1, 1, 3]),
895 33: ('Arsenic', 'As', [-3, 3, 5], [-2, -1, 1, 2, 4]),
896 34: ('Selenium', 'Se', [-2, 2, 4, 6], [-1, 1, 3, 5]),
897 35: ('Bromine', 'Br', [-1, 1, 3, 5], [4, 7]),
898 36: ('Krypton', 'Kr', [2], []),
899 37: ('Rubidium', 'Rb', [1], [-1]),
900 38: ('Strontium', 'Sr', [2], [1]),
901 39: ('Yttrium', 'Y', [3], [1, 2]),
902 40: ('Zirconium', 'Zr', [4], [-2, 1, 2, 3]),
903 41: ('Niobium', 'Nb', [5], [-3, -1, 1, 2, 3, 4]),
904 42: ('Molybdenum', 'Mo', [4, 6], [-4, -2, -1, 1, 2, 3, 5]),
905 43: ('Technetium', 'Tc', [4, 7], [-3, -1, 1, 2, 3, 5, 6]),
906 44: ('Ruthenium', 'Ru', [3, 4], [-4, -2, 1, 2, 5, 6, 7, 8]),
907 45: ('Rhodium', 'Rh', [3], [-3, -1, 1, 2, 4, 5, 6]),
908 46: ('Palladium', 'Pd', [2, 4], [1, 3, 5, 6]),
909 47: ('Silver', 'Ag', [1], [-2, -1, 2, 3, 4]),
910 48: ('Cadmium', 'Cd', [2], [-2, 1]),
911 49: ('Indium', 'In', [3], [-5, -2, -1, 1, 2]),
912 50: ('Tin', 'Sn', [-4, 2, 4], [-3, -2, -1, 1, 3]),
913 51: ('Antimony', 'Sb', [-3, 3, 5], [-2, -1, 1, 2, 4]),
914 52: ('Tellurium', 'Te', [-2, 2, 4, 6], [-1, 1, 3, 5]),
915 53: ('Iodine', 'I', [-1, 1, 3, 5, 7], [4, 6]),
916 54: ('Xenon', 'Xe', [2, 4, 6], [8]),
917 55: ('Cesium', 'Cs', [1], [-1]),
918 56: ('Barium', 'Ba', [2], [1]),
919 57: ('Lanthanum', 'La', [3], [1, 2]),
920 58: ('Cerium', 'Ce', [3, 4], [2]),
921 59: ('Praseodymium', 'Pr', [3], [2, 4, 5]),
922 60: ('Neodymium', 'Nd', [3], [2, 4]),
923 61: ('Promethium', 'Pm', [3], [2]),
924 62: ('Samarium', 'Sm', [3], [2]),
925 63: ('Europium', 'Eu', [2, 3], []),
926 64: ('Gadolinium', 'Gd', [3], [1, 2]),
927 65: ('Terbium', 'Tb', [3], [1, 2, 4]),
928 66: ('Dysprosium', 'Dy', [3], [2, 4]),
929 67: ('Holmium', 'Ho', [3], [2]),
930 68: ('Erbium', 'Er', [3], [2]),
931 69: ('Thulium', 'Tm', [3], [2]),
932 70: ('Ytterbium', 'Yb', [3], [2]),
933 71: ('Lutetium', 'Lu', [3], [2]),
934 72: ('Hafnium', 'Hf', [4], [-2, 1, 2, 3]),
935 73: ('Tantalum', 'Ta', [5], [-3, -1, 1, 2, 3, 4]),
936 74: ('Tungsten', 'W', [4, 6], [-4, -2, -1, 1, 2, 3, 5]),
937 75: ('Rhenium', 'Re', [4], [-3, -1, 1, 2, 3, 5, 6, 7]),
938 76: ('Osmium', 'Os', [4], [-4, -2, -1, 1, 2, 3, 5, 6, 7, 8]),
939 77: ('Iridium', 'Ir', [3, 4], [-3, -1, 1, 2, 5, 6, 7, 8, 9]),
940 78: ('Platinum', 'Pt', [2, 4], [-3, -2, -1, 1, 3, 5, 6]),
941 79: ('Gold', 'Au', [3], [-3, -2, -1, 1, 2, 5]),
942 80: ('Mercury', 'Hg', [1, 2], [-2, 4]), # +4 doi:10.1002/anie.200703710
943 81: ('Thallium', 'Tl', [1, 3], [-5, -2, -1, 2]),
944 82: ('Lead', 'Pb', [2, 4], [-4, -2, -1, 1, 3]),
945 83: ('Bismuth', 'Bi', [3], [-3, -2, -1, 1, 2, 4, 5]),
946 84: ('Polonium', 'Po', [-2, 2, 4], [5, 6]),
947 85: ('Astatine', 'At', [-1, 1], [3, 5, 7]),
948 86: ('Radon', 'Rn', [2], [6]),
949 87: ('Francium', 'Fr', [1], []),
950 88: ('Radium', 'Ra', [2], []),
951 89: ('Actinium', 'Ac', [3], []),
952 90: ('Thorium', 'Th', [4], [1, 2, 3]),
953 91: ('Protactinium', 'Pa', [5], [3, 4]),
954 92: ('Uranium', 'U', [6], [1, 2, 3, 4, 5]),
955 93: ('Neptunium', 'Np', [5], [2, 3, 4, 6, 7]),
956 94: ('Plutonium', 'Pu', [4], [2, 3, 5, 6, 7]),
957 95: ('Americium', 'Am', [3], [2, 4, 5, 6, 7]),
958 96: ('Curium', 'Cm', [3], [4, 6]),
959 97: ('Berkelium', 'Bk', [3], [4]),
960 98: ('Californium', 'Cf', [3], [2, 4]),
961 99: ('Einsteinium', 'Es', [3], [2, 4]),
962 100: ('Fermium', 'Fm', [3], [2]),
963 101: ('Mendelevium', 'Md', [3], [2]),
964 102: ('Nobelium', 'No', [2], [3]),
965 103: ('Lawrencium', 'Lr', [3], []),
966 104: ('Rutherfordium', 'Rf', [4], []),
967 105: ('Dubnium', 'Db', [5], []),
968 106: ('Seaborgium', 'Sg', [6], []),
969 107: ('Bohrium', 'Bh', [7], []),
970 108: ('Hassium', 'Hs', [8], []),
971 109: ('Meitnerium', 'Mt', [], []),
972 110: ('Darmstadtium', 'Ds', [], []),
973 111: ('Roentgenium', 'Rg', [], []),
974 112: ('Copernicium', 'Cn', [2], []),
975 113: ('Nihonium', 'Nh', [], []),
976 114: ('Flerovium', 'Fl', [], []),
977 115: ('Moscovium', 'Mc', [], []),
978 116: ('Livermorium', 'Lv', [], []),
979 117: ('Tennessine', 'Ts', [], []),
980 118: ('Oganesson', 'Og', [], []),
981 }
982 # pylint: enable=bad-whitespace
983
984 def default_table(table: PeriodicTable|None=None) -> PeriodicTable:
985 """
986 Return the default table unless a specific table has been requested.
987
988 This is to be used in a context like::
989
990 def summary(table=None):
991 table = core.default_table(table)
992 ...
993 """
994 return table if table is not None else PUBLIC_TABLE
995
996 def define_elements(table: PeriodicTable, namespace: dict[str, Any]) -> list[str]:
997 """
998 Define external variables for each element in namespace. Elements
999 are defined both by name and by symbol.
1000
1001 This is called from *__init__* as::
1002
1003 elements = core.default_table()
1004 __all__ += core.define_elements(elements, globals())
1005
1006 :Parameters:
1007 *table* : PeriodicTable
1008 Set of elements
1009 *namespace* : dict
1010 Namespace in which to add the symbols.
1011 :Returns: [string, ...]
1012 A sequence listing the names defined.
1013
1014 .. Note:: This will only work for *namespace* globals(), not locals()!
1015 """
1016
1017 # Build the dictionary of element symbols
1018 names: list[str] = []
1019 for atom in [*table, table.D, table.T, table.n]:
1020 namespace[atom.symbol] = atom
1021 namespace[atom.name] = atom
1022 names.extend((atom.symbol, atom.name))
1023 return names
1024
1025 def get_data_path(data: Path|str) -> str:
1026 """
1027 Locate the directory for the tables for the named extension.
1028
1029 :Parameters:
1030 *data* : string
1031 Name of the extension data directory. For example, the xsf
1032 extension has data in the 'xsf' data directory.
1033
1034 :Returns: string
1035 Path to the data.
1036 """
1037 import sys
1038 import os
1039
1040 # Check for data path in the environment
1041 key = 'PERIODICTABLE_DATA'
1042 if key in os.environ:
1043 path = os.path.join(os.environ[key], data)
1044 if not os.path.isdir(path):
1045 raise RuntimeError('Path in environment %s not a directory'%key)
1046 return path
1047
1048 # Check for data path in the package
1049 path = os.path.join(os.path.dirname(__file__), data)
1050 if os.path.isdir(path):
1051 return path
1052
1053 # Check for data path next to exe/zip file.
1054 exepath = os.path.dirname(sys.executable)
1055 path = os.path.join(exepath, 'periodictable-data', data)
1056 if os.path.isdir(path):
1057 return path
1058
1059 # py2app puts the data in Contents/Resources, but the executable
1060 # is in Contents/MacOS.
1061 path = os.path.join(exepath, '..', 'Resources', 'periodictable-data', data)
1062 if os.path.isdir(path):
1063 return path
1064
1065 raise RuntimeError('Could not find the periodic table data files')
1066
1067 # Make a common copy of the table for everyone to use --- equivalent to
1068 # a singleton without incurring any complexity.
1069 PUBLIC_TABLE: PeriodicTable = PeriodicTable(PUBLIC_TABLE_NAME)