---------------------------------------------------------------------- This is the API documentation for the amchi library. ---------------------------------------------------------------------- ## Classes Core classes UnsupportedElementError An element that amchi has no data for (amchi supports H to Xe, main group). Examples: >>> import amchi >>> from types import SimpleNamespace >>> iron = SimpleNamespace(symbols=["Fe"], coordinates=[[0, 0, 0]]) >>> amchi.from_geometry(iron) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... amchi._element.UnsupportedElementError: ... ParityMargins(*, atoms: dict[int, float], bonds: dict[amchi._types.Bond, float], reverse_atoms: dict[int, float] = ) -> None How far each candidate is from an ill-defined parity, with the candidates' keys. For an atom, `|det| / d**3`, with `d` the mean distance to its neighbors: 3.08 for an ideal tetrahedron, 0.77 for an ideal pyramid with a lone pair, and 0 for a planar atom. `reverse_atoms` gives the same for a TS atom's reverse neighbors. For a bond, the smallest `|cos|` of the dihedral angle over the pairs of neighbors across it: 1 when planar, 0 at 90°. Examples: >>> import amchi >>> amchi.ParityMargins(atoms={0: 3.08}, bonds={}).atoms {0: 3.08} Candidates(*, atoms: dict[int, tuple[int, ...]] = , reverse_atoms: dict[int, tuple[int, ...]] = , bonds: dict[amchi._types.Bond, tuple[tuple[int, ...], tuple[int, ...]]] = ) -> None The stereocenter candidates, each with its stereo-determining neighbors. `atoms` maps an atom to its 3 or 4 neighbors. `bonds` maps a bond `(i, j)` to the neighbors of `i`, then of `j`, without the other bond atom (1 to 4 on each side: 4 in a TS where `i` swaps both its other neighbors). Any neighbor order is valid: a local parity is measured against the order given. A bond given as `(j, i)` is sorted, with its two sides swapped. For a TS, `atoms` holds the reactant-side neighbors, or the product-side ones if the atom is tetrahedral only there. `reverse_atoms` holds the product-side neighbors of an atom that is tetrahedral on both sides with different neighbors; reading the TS reversed uses them. Each of its keys is also a key of `atoms`. Examples: >>> import amchi >>> candidates = amchi.Candidates(bonds={(3, 1): ([4], [0, 5])}) >>> candidates.bonds {(1, 3): ((0, 5), (4,))} Connectivity(*, bonds: tuple[amchi._types.Bond, ...], breaking: tuple[amchi._types.Bond, ...] = (), forming: tuple[amchi._types.Bond, ...] = ()) -> None The bonds of a species or a transition state. `bonds` are the bonds present throughout. A TS also has `breaking` and `forming` bonds, which are not repeated in `bonds`: the reactant has `bonds + breaking` and the product `bonds + forming`. Each pair is sorted to `(i, j)` with `i < j`. Examples: >>> import amchi >>> amchi.Connectivity(bonds=[[1, 0], [0, 2]]).bonds ((0, 1), (0, 2)) IllDefinedParityError A stereocenter whose parity the coordinates don't define. Examples: >>> import amchi >>> from types import SimpleNamespace >>> # CHFClBr with the four substituents in one plane >>> flat = SimpleNamespace( ... symbols=["C", "H", "F", "Cl", "Br"], ... coordinates=[[0, 0, 0], [1, 0, 0], [0, 1, 0], [-1, 0, 0], [0, -1, 0]], ... ) >>> amchi.from_geometry(flat) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... amchi._types.IllDefinedParityError: ... ## Protocols Structural typing protocols GeometryLike(*args, **kwargs) Anything with atomic symbols and Cartesian coordinates (N x 3, Å). Examples: >>> import amchi >>> from types import SimpleNamespace >>> helium = SimpleNamespace(symbols=["He"], coordinates=[[0, 0, 0]]) >>> amchi.from_geometry(helium) 'AMChI=2S/He' ## Exceptions Exception classes AmchiError Base class for the errors that amchi raises. Examples: >>> import amchi >>> issubclass(amchi.UnsupportedElementError, amchi.AmchiError) True ## Functions Public functions from_geometry(geometry: amchi._types.GeometryLike, *, stereo: bool = True) -> str The AMChI string of a species, with its connectivity and candidates derived. Raises the errors of `string`. Examples: >>> import amchi >>> from types import SimpleNamespace >>> # CHFClBr and its mirror image >>> chfclbr = SimpleNamespace( ... symbols=["C", "H", "F", "Cl", "Br"], ... coordinates=[ ... [0, 0, 0], [0, 0, 1.09], [1.31, 0, -0.46], ... [-0.83, 1.44, -0.59], [-0.91, -1.58, -0.65], ... ], ... ) >>> amchi.from_geometry(chfclbr) 'AMChI=2S/CHBrClF/c2-1(3)4/h1H/t1-/m1/s1' >>> chfclbr.coordinates = [[-x, y, z] for x, y, z in chfclbr.coordinates] >>> amchi.from_geometry(chfclbr) 'AMChI=2S/CHBrClF/c2-1(3)4/h1H/t1-/m0/s1' >>> amchi.from_geometry(chfclbr, stereo=False) 'AMChI=2S/CHBrClF/c2-1(3)4/h1H' from_ts_geometries(geometry: amchi._types.GeometryLike, reactant_geometry: amchi._types.GeometryLike, product_geometry: amchi._types.GeometryLike, *, stereo: bool = True) -> str The AMChI string of a TS, with its connectivity and candidates derived. The three geometries are in the same atom order: the TS (for the parities) and its reactant side and product side (for the bonds and the candidates). With `stereo=False` the string has no `b`, `t`, `m` or `s` layer. Raises the errors of `string`, and `ValueError` if the atoms differ. Examples: >>> import amchi >>> from types import SimpleNamespace >>> symbols = ["C", "H", "H", "H", "H", "O", "H"] >>> ring = [[0, 0, 0.3], [1, 0, 0.3], [-0.5, 0.87, 0.3], [-0.5, -0.87, 0.3]] >>> # CH3 + H2O: H4 moves from O5 to C0 >>> ts = SimpleNamespace( ... symbols=symbols, ... coordinates=[[0, 0, 0], *ring[1:], [0, 0, -1.3], [0, 0, -2.5], ... [0.9, 0, -2.8]], ... ) >>> reactant = SimpleNamespace( ... symbols=symbols, ... coordinates=[[0, 0, 0], *ring[1:], [-0.5, 0.5, -3.2], [0, 0, -2.5], ... [0.9, 0, -2.8]], ... ) >>> product = SimpleNamespace( ... symbols=symbols, ... coordinates=[[0, 0, 0], *ring[1:], [0, 0, -1.09], [0, 0, -3.2], ... [0.9, 0, -3.5]], ... ) >>> amchi.from_ts_geometries(ts, reactant, product) 'AMChI=2S/CH5O/c1-3-2/h2H,1H3/k3-2/f3-1/r0' >>> amchi.from_ts_geometries(ts, product, reactant) 'AMChI=2S/CH5O/c1-3-2/h2H,1H3/k3-2/f3-1/r1' string(geometry: amchi._types.GeometryLike, connectivity: amchi._types.Connectivity, candidates: amchi._types.Candidates, *, stereo: bool = True) -> str The AMChI string of a species or a transition state (TS). A TS has breaking or forming bonds in its connectivity, and its string has the `k` (breaking) and `f` (forming) layers, as read in its canonical direction, and an `r` layer if the given direction is the reverse of that (`r1`) or not (`r0`). With `stereo=False`, the candidates are ignored, and the string has no `b`, `t`, `m` or `s` layer. Raises: UnsupportedElementError: A symbol has no element data. IllDefinedParityError: A stereocenter's parity is exactly zero. ValueError: The inputs don't fit each other: the coordinates aren't N x 3, a bond names a missing atom, or a candidate's neighbors aren't the neighbors of its atom or bond (for a TS: aren't among them, over the breaking and forming bonds too). Examples: >>> import amchi >>> from types import SimpleNamespace >>> water = SimpleNamespace( ... symbols=["O", "H", "H"], ... coordinates=[[0, 0, 0], [0.96, 0, 0], [-0.24, 0.93, 0]], ... ) >>> connectivity = amchi.Connectivity(bonds=[(0, 1), (0, 2)]) >>> amchi.string(water, connectivity, amchi.Candidates()) 'AMChI=2S/H2O/h1H2' add_bond_candidate(candidates: amchi._types.Candidates, connectivity: amchi._types.Connectivity, bond: collections.abc.Collection[int]) -> amchi._types.Candidates Add a bond candidate, with all its neighbors by ascending index. No filter is applied: a caller overrides the perception on purpose. Remove an atom candidate of the bond yourself where it applies. For a TS, the bond and its neighbors may be breaking or forming bonds. Raises: ValueError: The pair isn't a bond, or one of its atoms has no other neighbor. Examples: >>> import amchi >>> connectivity = amchi.Connectivity(bonds=[(0, 1), (1, 2), (2, 3)]) >>> amchi.add_bond_candidate(amchi.Candidates(), connectivity, (2, 1)).bonds {(1, 2): ((0,), (3,))} candidates(symbols: collections.abc.Sequence[str], connectivity: amchi._types.Connectivity) -> amchi._types.Candidates The stereocenter candidates of a species or a TS, with their neighbors. An atom candidate has at least 3 neighbors and neighbors + lone pairs = 4, except a nitrogen with 3 neighbors whose lone pair is conjugated (D41). An atom with 3 neighbors in a 3-membered ring is a candidate whatever its conjugation, which includes a carbon radical whose neighbors are saturated (D42). A bond candidate is rigid and planar, has a neighbor on each side, is in no ring of fewer than 8 atoms, and doesn't join two atom candidates. The neighbors are listed hydrogens first, then the other atoms, each by ascending index (D21). For a TS, the rules apply to each side, except that a nitrogen conjugated on one side is a candidate on neither: its TS geometry can be exactly planar (D41). An atom's neighbors are those of the reactant side if it is a candidate there, else of the product side; an atom that is a candidate on both sides with different neighbors also gets the product-side ones in `reverse_atoms` (D26). A bond's neighbors are united over the sides where it is rigid and planar, and the ring test follows the bonds of the whole TS, leaving and reaching the bond through its listed neighbors only. Examples: >>> import amchi >>> # CHFClBr and FN=NF >>> connectivity = amchi.Connectivity(bonds=[(0, 1), (0, 2), (0, 3), (0, 4)]) >>> amchi.candidates(["C", "F", "Cl", "Br", "H"], connectivity).atoms {0: (4, 1, 2, 3)} >>> connectivity = amchi.Connectivity(bonds=[(0, 1), (1, 2), (2, 3)]) >>> amchi.candidates(["F", "N", "N", "F"], connectivity).bonds {(1, 2): ((0,), (3,))} >>> # An F atom moves from one C of CH3F to the other in the TS F...CH3...F >>> connectivity = amchi.Connectivity( ... bonds=[(0, 1), (0, 2), (0, 3)], breaking=[(0, 4)], forming=[(0, 5)] ... ) >>> result = amchi.candidates(["C", "H", "H", "H", "F", "F"], connectivity) >>> result.atoms, result.reverse_atoms ({0: (1, 2, 3, 4)}, {0: (1, 2, 3, 5)}) remove_candidate(candidates: amchi._types.Candidates, key: int | collections.abc.Collection[int]) -> amchi._types.Candidates Remove an atom candidate (an index) or a bond candidate (a pair). An atom candidate is removed with its reverse neighbors, if it has them. Raises: KeyError: It isn't a candidate. Examples: >>> import amchi >>> candidates = amchi.Candidates( ... atoms={0: (1, 2, 3)}, bonds={(4, 5): ([6], [7])} ... ) >>> amchi.remove_candidate(candidates, 0) Candidates(atoms={}, reverse_atoms={}, bonds={(4, 5): ((6,), (7,))}) >>> amchi.remove_candidate(candidates, (5, 4)) Candidates(atoms={0: (1, 2, 3)}, reverse_atoms={}, bonds={}) connectivity(geometry: amchi._types.GeometryLike) -> amchi._types.Connectivity The bonds of a species, from its interatomic distances. Two atoms are bonded within 1.05 times the larger of the sum of their covalent radii and the mean of their van der Waals radii. Then an atom with more bonds than its valence loses its longest ones. The excess and the neighbors are counted before any bond is removed, as in the old code. Examples: >>> import amchi >>> from types import SimpleNamespace >>> water = SimpleNamespace( ... symbols=["O", "H", "H"], ... coordinates=[[0, 0, 0], [0.96, 0, 0], [-0.24, 0.93, 0]], ... ) >>> amchi.connectivity(water).bonds ((0, 1), (0, 2)) ts_connectivity(reactant_geometry: amchi._types.GeometryLike, product_geometry: amchi._types.GeometryLike) -> amchi._types.Connectivity The bonds of a TS, from reactant-side and product-side geometries. Both geometries are in the TS atom order. Each side's bonds come from `connectivity`; a bond on both sides is present throughout, one on the reactant side only is breaking, and one on the product side only is forming. Examples: >>> import amchi >>> from types import SimpleNamespace >>> # H + H2 -> H2 + H >>> reactant = SimpleNamespace( ... symbols=["H", "H", "H"], ... coordinates=[[0, 0, 0], [0.74, 0, 0], [3, 0, 0]], ... ) >>> product = SimpleNamespace( ... symbols=["H", "H", "H"], ... coordinates=[[0, 0, 0], [2.26, 0, 0], [3, 0, 0]], ... ) >>> connectivity = amchi.ts_connectivity(reactant, product) >>> connectivity.breaking, connectivity.forming (((0, 1),), ((1, 2),)) parity_margins(geometry: amchi._types.GeometryLike, candidates: amchi._types.Candidates) -> amchi._parity.ParityMargins How nearly planar each candidate is, as a diagnostic. Examples: >>> import amchi >>> from types import SimpleNamespace >>> methane = SimpleNamespace( ... symbols=["C", "H", "H", "H", "H"], ... coordinates=[ ... [0, 0, 0], [1, 1, 1], [1, -1, -1], [-1, 1, -1], [-1, -1, 1] ... ], ... ) >>> candidates = amchi.Candidates(atoms={0: (1, 2, 3, 4)}) >>> round(amchi.parity_margins(methane, candidates).atoms[0], 2) 3.08 ## Type Aliases Type alias definitions Bond Type alias. Type aliases are created through the type statement:: type Alias = int In this example, Alias and int will be treated equivalently by static type checkers. At runtime, Alias is an instance of TypeAliasType. The __name__ attribute holds the name of the type alias. The value of the type alias is stored in the __value__ attribute. It is evaluated lazily, so the value is computed only if the attribute is accessed. The __module__ attribute holds the name of the module in which the type alias was defined; it can be assigned to. Type aliases can also be generic:: type ListOrSet[T] = list[T] | set[T] In this case, the type parameters of the alias are stored in the __type_params__ attribute. See PEP 695 for more information. ---------------------------------------------------------------------- This is the User Guide documentation for the package. ---------------------------------------------------------------------- ### Using amchi amchi computes the AMChI string of a species or a transition state (TS) from a 3D structure. The string names a species the way InChI does, plus its stereochemistry (`b`, `t`, `m`, `s` layers) from the coordinates. A TS adds its breaking and forming bonds (`k`, `f`) and its direction (`r`); see [Transition states](#transition-states). ## The three inputs `amchi.string(geometry, connectivity, candidates)` takes everything it needs explicitly: - **`geometry`** is anything with `symbols` and `coordinates` (N × 3, in Å): the `GeometryLike` protocol. Hydrogens must be explicit. Supported elements: main group, H to Xe. - **`connectivity`** is `amchi.Connectivity(bonds=[(0, 1), ...])`, with atoms as indices into the geometry. - **`candidates`** is `amchi.Candidates(atoms=..., bonds=...)`: the atoms and bonds that may be stereocenters, each with its stereo-determining neighbors. ```python import amchi from types import SimpleNamespace water = SimpleNamespace( symbols=["O", "H", "H"], coordinates=[[0, 0, 0], [0.96, 0, 0], [-0.24, 0.93, 0]], ) connectivity = amchi.Connectivity(bonds=[(0, 1), (0, 2)]) amchi.string(water, connectivity, amchi.Candidates()) # 'AMChI=2S/H2O/h1H2' ``` The candidates depend on the graph alone, so the string of a species changes with the conformer only through the parities. ## The helpers Two helpers derive the second and third inputs from a geometry, and `from_geometry` chains them with `string`: ```python connectivity = amchi.connectivity(geometry) candidates = amchi.candidates(geometry.symbols, connectivity) amchi.string(geometry, connectivity, candidates) # the same as amchi.from_geometry(geometry) ``` - `connectivity(geometry)` bonds two atoms within 1.05 times the larger of the sum of their covalent radii and the mean of their van der Waals radii, then drops the longest bonds of an atom with more bonds than its valence. - `candidates(symbols, connectivity)` finds the pyramidal atoms and the rigid planar bonds: the old AutoMol's rules, except that a nitrogen with an unsaturated neighbor (amides, anilines, enamines) is planar and no candidate, and that an atom with 3 neighbors in a 3-membered ring is a candidate even when conjugated, including a radical such as cyclopropyl. - `parity_margins(geometry, candidates)` is a diagnostic: how nearly planar each candidate is. ## Corrections The helpers perceive bonds and resonance without formal charges, so they can be wrong, and the explicit inputs let you correct them. HN=N(O)OH is the known case: the helpers miss its zwitterionic form HN=N(+)(O−)OH, so they miss the rigid planar N0=N1 bond, and both geometries get the same string. Add the bond candidate: ```python connectivity = amchi.connectivity(geometry) candidates = amchi.candidates(geometry.symbols, connectivity) candidates = amchi.add_bond_candidate(candidates, connectivity, (0, 1)) amchi.string(geometry, connectivity, candidates) ``` With the two geometries of HNNO in `tests/data/hand_cases.json`, `from_geometry` gives `AMChI=2S/H2N2O2/c1-2(3)4/h1,4H` for both, and the corrected candidates give `.../b2-1+` and `.../b2-1-`. `remove_candidate(candidates, key)` removes a candidate the helpers found wrongly: it takes an atom index or a bond pair, and raises `KeyError` for a non-candidate. `add_bond_candidate` applies no filter, since it is meant to override, and raises `ValueError` if the pair isn't a bond or an atom has no other neighbor. ## No stereo `stereo=False`, on `string` and `from_geometry`, ignores the candidates and writes no `b`, `t`, `m` or `s` layer: ```python amchi.from_geometry(geometry, stereo=False) # 'AMChI=2S/CHBrClF/c2-1(3)4/h1H' ``` ## Several components A geometry with several components gives one string. Components are sorted as in the old AutoMol, and repeated layers are written once behind a multiplier (`C4H6N.C2H5NO2.H2O`, `2*`). ## Transition states A TS takes the same three inputs. Its connectivity also lists the bonds that break and form, as atom pairs of the TS geometry: the reactant side has the `bonds` and the `breaking` bonds, the product side the `bonds` and the `forming` bonds. Here `ts` is the saddle point of CH3 + H2O → CH4 + OH, where H4 moves from O5 to C0 (the example of `from_ts_geometries`): ```python connectivity = amchi.Connectivity( bonds=[(0, 1), (0, 2), (0, 3), (5, 6)], breaking=[(4, 5)], forming=[(0, 4)] ) candidates = amchi.candidates(ts.symbols, connectivity) amchi.string(ts, connectivity, candidates) # 'AMChI=2S/CH5O/c1-3-2/h2H,1H3/k3-2/f3-1/r0' ``` The geometry is the saddle point, which gives the parities; the bonds and the candidates come from the two sides. `from_ts_geometries` derives both from a reactant-side and a product-side geometry in the TS atom order (for example, the end points of an IRC): ```python amchi.from_ts_geometries(ts, reactant, product) # 'AMChI=2S/CH5O/c1-3-2/h2H,1H3/k3-2/f3-1/r0' amchi.from_ts_geometries(ts, product, reactant) # 'AMChI=2S/CH5O/c1-3-2/h2H,1H3/k3-2/f3-1/r1' ``` - `ts_connectivity(reactant, product)` bonds each side as `connectivity` does: bonds of both sides are `bonds`, the rest `breaking` or `forming`. - `candidates` applies the species rules to each side, except that a nitrogen planar on one side is a candidate on neither, and a 3-membered ring counts only if none of its bonds is breaking or forming. An atom that is tetrahedral on both sides with different neighbors (a substitution site) has two neighbor lists, `atoms` for the reactant side and `reverse_atoms` for the product side, and each gets its own parity. A bond gets its neighbors from every side where it is rigid and planar, so it can have three neighbors at one end. - A transferring hydrogen is an atom of the backbone: it has a canonical number and appears in the `c` layer (`H` 3 above). ### The layers k, f and r - **`k`** lists the breaking bonds and **`f`** the forming bonds, as `j-i` in canonical numbers, read in the canonical direction. Above, H3 leaves O2 (`k3-2`) and bonds to C1 (`f3-1`). - **`r`** says how the given direction relates to the canonical one: `r0` if they are the same, `r1` if the given TS is the reverse. A TS whose two directions are equal (a degenerate rearrangement such as an identity H transfer) has no `r` layer. The layers come in the order `c`, `h`, `b`, `t`, `m`, `s`, `k`, `f`, `r`, and several components join `k`, `f` and `r` like the other layers (`/k;3-2,5-1/f;5-3/r;0`). ### What r and m mean together A TS has up to four forms: each direction, as it is and reflected. amchi canonicalizes the smallest of them (decision D29), and the string describes that form; `m` says whether the given TS is it or its mirror image, and `r` whether it is it or its reverse. So: - Swapping the reactant and the product changes the digit of `r` and nothing else. - Reflecting the geometry changes the digit of `m` and nothing else. - A TS whose mirror image is its own reverse is the exception: reflecting it gives the reversed TS, so `m` and `r` would say the same thing. It gets no `m` layer, and reflecting it changes `r`. 4 of the 300 sampled TSs are like this. The `r` layer depends on which geometry you call the reactant. Two records of the same saddle point with the end points swapped differ only in `r`, so drop it if the identity should not depend on the direction. ## Errors All errors that amchi raises on its own inherit from `amchi.AmchiError`: | error | when | |---|---| | `UnsupportedElementError` | A symbol has no element data | | `IllDefinedParityError` | A stereocenter's parity is exactly zero (all its neighbors in one plane) | | `ValueError` (not an `AmchiError`) | The inputs don't fit each other: the coordinates aren't N × 3, a bond names a missing atom, a candidate's neighbors aren't those of its atom or bond, or the reactant and product geometries of a TS have different atoms | A parity is ill-defined only when its determinant or dot product is exactly zero, as in the old AutoMol, so a nearly planar nitrogen still gets a parity. Check `parity_margins` to find such cases. ## Differences from the old AutoMol The strings equal the old `AMChI=1` strings, except in these intended ways: - The version prefix is `AMChI=2S` (D24). - The `c` layer is written the way InChI writes its connections layer, with one depth-first writer (D24). The old code used two writers, one of which depends on Python's set hash order. The layer describes the same graph in the same canonical numbers; every other layer is unchanged. - A TS is canonicalized as the smallest of its four forms (D29), and its atoms are told apart by which neighbor carries which reacting bond (D28). Where the old code was consistent, its strings are kept. It wasn't for 11 of the 300 sampled TSs: their old strings depended on the atom order, or broke the rules of [What r and m mean together](#what-r-and-m-mean-together). Known limitations of the old code are kept: cis- and trans-1,3-dimethylcyclobutane share a string, and a species with formal charges or hypervalent atoms can get the wrong candidates, which you can correct as above.