---------------------------------------------------------------------- This is the API documentation for the automol library. ---------------------------------------------------------------------- ## Classes Core classes Geometry(*, symbols: list[str], coordinates: Annotated[numpy._typing._array_like.NDArray[numpy.float64], SkipValidation(), BeforeValidator(func=, json_schema_input_type=PydanticUndefined), PlainSerializer(func=, return_type=, when_used='always')], charge: int, spin: int) -> None Molecular geometry. Attributes: symbols: Atomic symbols, e.g. ``["H", "O", "H"]``. Validated against the periodic table and canonicalized (``"cl"`` -> ``"Cl"``). coordinates: Cartesian coordinates in Angstroms, shape ``(N, 3)`` and ordered like `symbols`. A `pint.Quantity` with length units is converted to Angstroms; plain values are assumed to be Angstroms. charge: Total molecular charge. spin: Number of unpaired electrons (``2S``). Must be non-negative and have the same parity as the electron count. Example: >>> geo = Geometry( ... symbols=["H", "O", "H"], ... coordinates=[[0.0, 0.0, -0.74], [0.0, 0.0, 0.0], [0.0, 0.0, 0.74]], ... charge=0, ... spin=0, ... ) >>> geo.atom_count 3 View(query='', width=640, height=480, viewergrid=None, data=None, style=None, linked=True, options={}, format=None, js='https://cdn.jsdelivr.net/npm/3dmol@2.5.4/build/3Dmol-min.js') A `py3Dmol.view` with helpers for geometries and arrows. Algorithm(*, name: str, kind: automol.ident.IdentityKind, parent_algorithm: automol.ident.Algorithm | None = None, identity_fn: automol.ident.IdentityProtocol, geometry_fn: automol.ident.GeometryProtocol = ) -> None Identity algorithm. Function signatures are validated on construction. Attributes: name: Unique algorithm name. kind: Category of identity produced. parent_algorithm: Algorithm whose identity disambiguates this one's `other_geos`, if any. identity_fn: ``(geo, other_geos=None) -> str``, generating the identity. geometry_fn: ``(value) -> Geometry``, inverting `identity_fn` if supported. AlgorithmRegistry() Registry of all known identity algorithms. ## Geometry Methods Methods for the Geometry class validate_symbols(v: list[str]) -> list[str] Validate and canonicalize atomic symbols. Args: v: Atomic symbols. Returns: Canonicalized atomic symbols. Raises: ValueError: If any symbol is not a known element. validate_consistency(v: Any, info: pydantic_core.core_schema.ValidationInfo) -> Any Check that symbols, coordinates, charge, and spin are consistent. Args: v: Candidate field value. info: Validation context. Returns: The unchanged value. __eq__(self, other: object) -> bool Compare geometries field by field, including exact coordinates. __repr__(self) -> str Render the geometry as an xyz block. xyz_block(self, *, comment: str | None = None) -> str Format the geometry as an xyz block (see `xyz_block`). xyz_file(self, *, path: str | pathlib.Path, comment: str | None = None) -> None Write the geometry to an xyz file (see `xyz_file`). from_xyz_block(xyz_block: str, *, charge: int, spin: int) -> Self Parse a geometry from an xyz block (see `from_xyz_block`). from_xyz_file(path: str | pathlib.Path, *, charge: int, spin: int) -> Self Read a geometry from an xyz file (see `from_xyz_file`). relabel_atoms(self, indices: collections.abc.Sequence[int]) -> Self Reorder the atoms. Args: indices: Permutation of ``range(atom_count)`` giving the new order, e.g. ``[2, 0, 1]`` moves atom 2 to position 0, atom 0 to position 1, and atom 1 to position 2. Returns: A reordered copy. Other fields, including those of subclasses, are kept. Raises: ValueError: If `indices` is not a permutation of ``range(atom_count)``. ## Enumerations Enum types IdentityKind(*values) Category of molecular identity. ## Exceptions Exception classes ElementNotFoundError No element matches the given atomic number or symbol. XYZFormatError An xyz block could not be parsed. ## Functions Public functions xyz_block(geo: automol.geom.Geometry, *, comment: str | None = None) -> str Format a geometry as an xyz block. Args: geo: Geometry. comment: Comment line. Defaults to the charge and spin, e.g. ``"Geometry(q=0, s=0)"``. Returns: The xyz block. Raises: ValueError: If `comment` contains a newline. from_xyz_block(xyz_block: str, *, charge: int, spin: int) -> automol.geom.Geometry Parse a geometry from a single-frame xyz block. Atoms may be given by symbol (case-insensitive) or atomic number. Args: xyz_block: The xyz block. charge: Total molecular charge. spin: Number of unpaired electrons. Returns: The parsed geometry. Raises: XYZFormatError: If the block is empty, the atom count line is missing or does not match the number of atom lines, or an atom line cannot be parsed. xyz_file(geo: automol.geom.Geometry, *, path: str | pathlib.Path, comment: str | None = None) -> None Write a geometry to an xyz file. Args: geo: Geometry. path: Output path. comment: Comment line. Defaults to the charge and spin, e.g. ``"Geometry(q=0, s=0)"``. from_xyz_file(path: str | pathlib.Path, *, charge: int, spin: int) -> automol.geom.Geometry Read a geometry from an xyz file (see `from_xyz_block`). Args: path: Path to the xyz file. charge: Total molecular charge. spin: Number of unpaired electrons. Returns: The parsed geometry. xyz_trajectory_block(geos: collections.abc.Sequence[automol.geom.Geometry], *, comments: collections.abc.Sequence[str] | None = None) -> str Format geometries as a multi-frame xyz block, one frame per geometry. Args: geos: Geometries. comments: Comment line for each frame. Defaults to the charge and spin (see `xyz_block`). Returns: The xyz block. Raises: ValueError: If `comments` doesn't have one entry per geometry. from_xyz_trajectory_block(xyz_block: str, *, charge: int, spin: int) -> list[automol.geom.Geometry] Parse geometries from a multi-frame xyz block, e.g. a list of conformers. Each frame is an atom count line, a comment line, and the atom lines (see `from_xyz_block`). A single-frame block gives a list of one geometry. Args: xyz_block: The xyz block. charge: Total molecular charge, for every frame. spin: Number of unpaired electrons, for every frame. Returns: The parsed geometries, in order. Raises: XYZFormatError: If the block is empty, or a frame is malformed. xyz_trajectory_comments(xyz_block: str) -> list[str] Get the comment line of each frame of a multi-frame xyz block. Programs often store a per-frame value there, such as CREST's energies. Args: xyz_block: The xyz block. Returns: The comment lines, stripped of surrounding whitespace, in order. Raises: XYZFormatError: If the block is empty, or a frame is malformed. xyz_trajectory_file(geos: collections.abc.Sequence[automol.geom.Geometry], *, path: str | pathlib.Path, comments: collections.abc.Sequence[str] | None = None) -> None Write geometries to a multi-frame xyz file (see `xyz_trajectory_block`). Args: geos: Geometries. path: Output path. comments: Comment line for each frame. Defaults to the charge and spin. from_xyz_trajectory_file(path: str | pathlib.Path, *, charge: int, spin: int) -> list[automol.geom.Geometry] Read geometries from a multi-frame xyz file (see `from_xyz_trajectory_block`). Args: path: Path to the xyz file. charge: Total molecular charge, for every frame. spin: Number of unpaired electrons, for every frame. Returns: The parsed geometries, in order. rdkit_mol(geo: automol.geom.Geometry) -> rdkit.Chem.rdchem.Mol Convert a geometry to an RDKit molecule. Connectivity comes from `adjacency_matrix` (with valence caps). Bond orders, formal charges, and radicals are perceived to match the geometry's charge and spin (see `automol.rd.mol.from_connectivity`), and stereochemistry is assigned from the 3D coordinates. Args: geo: Geometry. Returns: RDKit molecule with perceived bonding and stereochemistry. Raises: NotImplementedError: If the geometry contains a metal. GeometryConversionError: If no Lewis structure is consistent with the connectivity, charge, and spin. from_rdkit_mol(mol: rdkit.Chem.rdchem.Mol) -> automol.geom.Geometry Convert an RDKit molecule to a geometry, embedding coordinates if missing. Args: mol: RDKit molecule. Returns: The geometry. select_atoms(geo: automol.geom.Geometry, keys: collections.abc.Sequence[int], *, charge: int | None = None, spin: int | None = None) -> automol.geom.Geometry Select a subset of atoms. Args: geo: Geometry. keys: Indices of the atoms to keep, in the order to keep them. charge: Charge of the selection. Defaults to the charge of `geo`. spin: Spin of the selection. Defaults to the spin of `geo` if that is consistent with the electron count, and otherwise to the lowest consistent spin (e.g. 1 for a methyl radical selected from methane). Returns: The selected atoms. Example: >>> geo = Geometry( ... symbols=["C", "H", "H", "H", "H"], ... coordinates=np.zeros((5, 3)), ... charge=0, ... spin=0, ... ) >>> methyl = select_atoms(geo, [0, 1, 2, 3]) >>> methyl.symbols, methyl.spin (['C', 'H', 'H', 'H'], 1) remove_atoms(geo: automol.geom.Geometry, keys: collections.abc.Collection[int], *, charge: int | None = None, spin: int | None = None) -> automol.geom.Geometry Remove a subset of atoms. Args: geo: Geometry. keys: Indices of the atoms to remove. charge: Charge of the remaining atoms (see `select_atoms`). spin: Spin of the remaining atoms (see `select_atoms`). Returns: The remaining atoms, in their original order. join(geos: collections.abc.Sequence[automol.geom.Geometry]) -> automol.geom.Geometry Join geometries into one. Args: geos: Geometries, in order. Returns: A geometry with the atoms of each geometry in turn, and the summed charges and spins. center_of_mass(geo: automol.geom.Geometry) -> numpy._typing._array_like.NDArray[numpy.float64] Calculate the center of mass. Args: geo: Geometry. Returns: Center of mass coordinates (the origin for an empty geometry). distance_matrix(geo: automol.geom.Geometry) -> numpy.ndarray Calculate the interatomic distance matrix. Args: geo: Geometry. Returns: Distance matrix, shape ``(N, N)``. distance_keys(geo: automol.geom.Geometry) -> numpy.ndarray Build a sorted distance descriptor. Each unique atom pair gives a row ``[z_low, z_high, distance]``. Rows are sorted by atomic numbers, then by distance. Args: geo: Geometry. Returns: Descriptor array, shape ``(npairs, 3)``. adjacency_matrix(geo: automol.geom.Geometry, *, sigma: float = 1.3, flood_fill: bool = False, enforce_valence: bool = False) -> numpy.ndarray Determine connectivity from covalent radii. Two atoms are bonded if their distance is less than `sigma` times the sum of their covalent radii. Args: geo: Geometry. sigma: Scaling factor for the sum of covalent radii. flood_fill: If `True`, increase `sigma` in steps of 0.05 until the molecule is a single fragment, or until no more bonds can be added. enforce_valence: If `True`, cap the bonds to each atom at `automol.rd.mol.max_bond_count`. Bonds are accepted shortest first, relative to the sum of covalent radii, so the result does not depend on atom order. Returns: Symmetric 0/1 adjacency matrix, shape ``(N, N)``. inertia_tensor(geo: automol.geom.Geometry) -> numpy.ndarray Calculate the inertia tensor about the center of mass. Args: geo: Geometry. Returns: Inertia tensor, shape ``(3, 3)`` (zero for an empty geometry). Example: >>> geo = Geometry( ... symbols=["O", "H", "H"], ... coordinates=[[0, 0, 0], [1, 0, 0], [0, 1, 0]], ... charge=0, ... spin=0, ... ) >>> tensor = inertia_tensor(geo) >>> tensor.shape (3, 3) >>> bool(np.allclose(tensor, tensor.T)) True principal_axes(geo: automol.geom.Geometry) -> tuple[numpy._typing._array_like.NDArray[numpy.float64], numpy._typing._array_like.NDArray[numpy.float64]] Calculate the principal moments and axes of inertia. Args: geo: Geometry. Returns: The principal moments, in ascending order, and the principal axes, as the columns of a ``(3, 3)`` rotation matrix (a right-handed frame). inertial_frame_rotation(geo: automol.geom.Geometry) -> scipy.spatial.transform._rotation.Rotation Find the rotation into the principal axis frame. After ``rotate(center(geo), rot)``, the principal axes with the smallest to largest moments lie along x, y, and z, so the inertia tensor is diagonal. Args: geo: Geometry. Returns: The rotation. distance(geo: automol.geom.Geometry, keys: collections.abc.Sequence[int]) -> float Measure the distance between two atoms. Args: geo: Geometry. keys: Indices of the two atoms. Returns: The distance, in Angstroms. angle(geo: automol.geom.Geometry, keys: collections.abc.Sequence[int], *, degrees: bool = False) -> float Measure the angle between three atoms. Args: geo: Geometry. keys: Indices of the three atoms, with the vertex in the middle. degrees: If `True`, return degrees instead of radians. Returns: The angle, between 0 and pi. Example: >>> geo = Geometry( ... symbols=["O", "H", "H"], ... coordinates=[[0, 0, 0], [1, 0, 0], [0, 1, 0]], ... charge=0, ... spin=0, ... ) >>> angle(geo, [1, 0, 2], degrees=True) 90.0 dihedral(geo: automol.geom.Geometry, keys: collections.abc.Sequence[int], *, degrees: bool = False) -> float Measure the dihedral angle between four atoms. Looking down the 2-3 bond, the angle is positive when atom 4 is rotated clockwise from atom 1. Args: geo: Geometry. keys: Indices of the four atoms. degrees: If `True`, return degrees instead of radians. Returns: The dihedral angle, between -pi and pi. Example: >>> geo = Geometry( ... symbols=["H", "O", "O", "H"], ... coordinates=[[0, 0, 1], [0, 0, 0], [0, 1, 0], [1, 1, 0]], ... charge=0, ... spin=0, ... ) >>> dihedral(geo, [0, 1, 2, 3], degrees=True) 90.0 bonds(geo: automol.geom.Geometry, amat: ArrayLike) -> numpy.ndarray List bond distances. Args: geo: Geometry. amat: Adjacency matrix. Returns: Sorted rows ``[z1, z2, distance]`` with ``z1 <= z2``, shape ``(nbonds, 3)``. Example: >>> geo = Geometry( ... symbols=["O", "H", "H"], ... coordinates=[[0, 0, 0], [1, 0, 0], [0, 1, 0]], ... charge=0, ... spin=0, ... ) >>> b = bonds(geo, adjacency_matrix(geo)) >>> b.shape (2, 3) >>> [tuple(float(x) for x in row) for row in b] [(1.0, 8.0, 1.0), (1.0, 8.0, 1.0)] angles(geo: automol.geom.Geometry, amat: ArrayLike) -> numpy.ndarray List bond angles. Args: geo: Geometry. amat: Adjacency matrix. Returns: Sorted rows ``[z1, z2, z3, theta]`` with `theta` in radians, `z2` the central atom, and ``z1 <= z3``, shape ``(nangles, 4)``. Example: >>> geo = Geometry( ... symbols=["O", "H", "H"], ... coordinates=[[0, 0, 0], [1, 0, 0], [0, 1, 0]], ... charge=0, ... spin=0, ... ) >>> a = angles(geo, adjacency_matrix(geo)) >>> a.shape (1, 4) >>> round(float(a[0][-1]), 6) 1.570796 dihedrals(geo: automol.geom.Geometry, amat: ArrayLike) -> numpy.ndarray List dihedral angles. Args: geo: Geometry. amat: Adjacency matrix. Returns: Sorted rows ``[z1, z2, z3, z4, phi]`` with `phi` in radians, shape ``(ndihedrals, 5)``. Each row is oriented so that ``(z1, z2, z3, z4) <= (z4, z3, z2, z1)``, which leaves `phi` unchanged. Example: >>> geo = Geometry( ... symbols=["H", "O", "O", "H"], ... coordinates=[[0, 0, 1], [0, 0, 0], [0, 1, 0], [1, 1, 0]], ... charge=0, ... spin=0, ... ) >>> amat = np.array( ... [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]] ... ) >>> d = dihedrals(geo, amat) >>> d.shape (1, 5) >>> [float(x) for x in d[0][:4]] [1.0, 8.0, 8.0, 1.0] >>> round(float(d[0][-1]), 6) 1.570796 translate(geo: automol.geom.Geometry, arr: ArrayLike, *, keys: collections.abc.Collection[int] | None = None, in_place: bool = False) -> automol.geom.Geometry Translate a geometry. Args: geo: Geometry. arr: Translation vector, or one vector per selected atom. keys: Atoms to translate. If `None`, translate all atoms. in_place: If `True`, modify `geo` instead of returning a copy. Returns: The translated geometry. reflect(geo: automol.geom.Geometry, normal: ArrayLike, *, origin: ArrayLike = (0.0, 0.0, 0.0), keys: collections.abc.Collection[int] | None = None, in_place: bool = False) -> automol.geom.Geometry Reflect a geometry across a plane. Args: geo: Geometry. normal: Normal vector of the reflection plane. origin: A point on the reflection plane. keys: Atoms to reflect. If `None`, reflect all atoms. in_place: If `True`, modify `geo` instead of returning a copy. Returns: The reflected geometry. Raises: ValueError: If `normal` is a zero vector. rotate(geo: automol.geom.Geometry, rot: scipy.spatial.transform._rotation.Rotation, *, origin: ArrayLike = (0.0, 0.0, 0.0), keys: collections.abc.Collection[int] | None = None, in_place: bool = False) -> automol.geom.Geometry Rotate a geometry about a point. Args: geo: Geometry. rot: Rotation to apply. origin: Point to rotate about. keys: Atoms to rotate. If `None`, rotate all atoms. in_place: If `True`, modify `geo` instead of returning a copy. Returns: The rotated geometry. twist(geo: automol.geom.Geometry, keys: collections.abc.Sequence[int], angle: float, *, degrees: bool = False) -> automol.geom.Geometry Rotate a group about a bond, e.g. a methyl or amine group. Everything on the side of atom `j` of the bond ``(i, j)`` rotates about the axis from `i` to `j`, by the right-hand rule (thumb from `i` to `j`). Bond lengths and angles are kept; only the dihedral angles about the bond change. Args: geo: Geometry. keys: The bond, ``(i, j)``. The side of `j` moves. angle: Angle to rotate by. degrees: If `True`, `angle` is in degrees instead of radians. Returns: The twisted geometry. Raises: ValueError: If `i` and `j` aren't bonded, or the bond is in a ring. Example: >>> geo = Geometry( ... symbols=["H", "O", "O", "H"], ... coordinates=[[1, 0, 0], [0, 0, 0], [0, 0, 1.4], [1, 0, 1.4]], ... charge=0, ... spin=0, ... ) >>> geo = twist(geo, (1, 2), 90, degrees=True) >>> round(dihedral(geo, [0, 1, 2, 3], degrees=True), 6) 90.0 twist_angle(geo: automol.geom.Geometry, keys: collections.abc.Sequence[int], vec: ArrayLike, target: ArrayLike, *, degrees: bool = False) -> float Find the twist about a bond that turns one direction onto another. Both directions are projected onto the plane perpendicular to the bond, and the result is the signed angle between the projections, so that ``twist(geo, keys, twist_angle(geo, keys, vec, target))`` turns `vec` (as part of the moving group) to point as close as possible to `target`. Args: geo: Geometry. keys: The bond, ``(i, j)``, as for `twist`. vec: Direction attached to the moving group, e.g. a bond direction. target: Direction to turn it toward. degrees: If `True`, return the angle in degrees instead of radians. Returns: The angle, between -pi and pi (or -180 and 180 degrees). Raises: ValueError: If `vec` or `target` is parallel to the bond. center(geo: automol.geom.Geometry, *, in_place: bool = False) -> automol.geom.Geometry Translate a geometry so that its center of mass is at the origin. Args: geo: Geometry. in_place: If `True`, modify `geo` instead of returning a copy. Returns: The centered geometry. alignment_rotation(geo: automol.geom.Geometry, ref: automol.geom.Geometry) -> scipy.spatial.transform._rotation.Rotation Find the rotation that best aligns a reference geometry onto a geometry. The rotation is found by the Kabsch algorithm, after moving both centers of mass to the origin. Atoms are matched by index. Args: geo: Target geometry. ref: Reference geometry, with the same atoms as `geo`. Returns: The rotation `rot` minimizing the RMSD between ``rotate(center(ref), rot)`` and ``center(geo)``. Raises: ValueError: If the geometries have different symbols. Example: >>> ref = Geometry( ... symbols=["O", "H", "H"], ... coordinates=[[0, 0, 0], [1, 0, 0], [0, 1, 0]], ... charge=0, ... spin=0, ... ) >>> rot = Rotation.from_euler("z", 30, degrees=True) >>> geo = rotate(ref, rot) >>> round(float(alignment_rotation(geo, ref).magnitude()), 6) 0.523599 axis_alignment_rotation(geo: automol.geom.Geometry, keys: collections.abc.Sequence[int], axis: ArrayLike = (0.0, 0.0, 1.0)) -> scipy.spatial.transform._rotation.Rotation Find the smallest rotation pointing the vector between two atoms along an axis. Use it to put a bond or other molecular axis along a coordinate axis, e.g. before spinning the geometry about that axis. Args: geo: Geometry. keys: Two atoms, ``(i, j)``. The vector from `i` to `j` is aligned. axis: Direction to point it in. Returns: The rotation, to apply with `rotate` (about atom `i` to keep it in place, e.g. ``rotate(geo, rot, origin=geo.coordinates[i])``). Raises: ValueError: If `keys` isn't two distinct atoms at different positions. Example: >>> geo = Geometry( ... symbols=["H", "H"], coordinates=[[0, 0, 0], [1, 0, 0]], charge=0, spin=0 ... ) >>> rot = axis_alignment_rotation(geo, [0, 1], axis=[0, 1, 0]) >>> rotate(geo, rot).coordinates.round(6).tolist() [[0.0, 0.0, 0.0], [0.0, 1.0, 0.0]] view(geo: automol.geom.Geometry, *, view: py3Dmol.view | None = None, label: bool = False) -> py3Dmol.view Display a geometry with py3Dmol. Args: geo: Geometry. view: Existing view to add the geometry to. If `None`, create one. label: If `True`, label atoms by index. Returns: The view containing the geometry. render_svg(geo: automol.geom.Geometry, *, out: str | pathlib.Path | None = None, config: 'str | xyzrender.RenderConfig' = 'default', include_h: bool = True) -> 'xyzrender.SVGResult' Render a geometry as an SVG image with xyzrender. The result displays inline in Jupyter. Args: geo: Geometry. out: Output path. The suffix is replaced with ``.svg``. config: xyzrender preset name or `xyzrender.RenderConfig`. include_h: If `True`, include hydrogen atoms. Returns: The SVG render result. render_gif(geo: automol.geom.Geometry, *, out: str | pathlib.Path | None = None, config: 'str | xyzrender.RenderConfig' = 'default', include_h: bool = True, rotation_axis: str = 'x') -> 'xyzrender.GIFResult' Render a geometry rotating about an axis as a GIF with xyzrender. The result displays inline in Jupyter. Args: geo: Geometry. out: Output path. The suffix is replaced with ``.gif``. config: xyzrender preset name or `xyzrender.RenderConfig`. include_h: If `True`, include hydrogen atoms. rotation_axis: Axis to rotate about. Returns: The GIF render result. ## Constants Module-level constants and data hill_formula Identity algorithm. Function signatures are validated on construction. Attributes: name: Unique algorithm name. kind: Category of identity produced. parent_algorithm: Algorithm whose identity disambiguates this one's `other_geos`, if any. identity_fn: ``(geo, other_geos=None) -> str``, generating the identity. geometry_fn: ``(value) -> Geometry``, inverting `identity_fn` if supported. rdkit_inchi Identity algorithm. Function signatures are validated on construction. Attributes: name: Unique algorithm name. kind: Category of identity produced. parent_algorithm: Algorithm whose identity disambiguates this one's `other_geos`, if any. identity_fn: ``(geo, other_geos=None) -> str``, generating the identity. geometry_fn: ``(value) -> Geometry``, inverting `identity_fn` if supported. rdkit_smiles Identity algorithm. Function signatures are validated on construction. Attributes: name: Unique algorithm name. kind: Category of identity produced. parent_algorithm: Algorithm whose identity disambiguates this one's `other_geos`, if any. identity_fn: ``(geo, other_geos=None) -> str``, generating the identity. geometry_fn: ``(value) -> Geometry``, inverting `identity_fn` if supported. Annotated(*args, **kwargs) Runtime representation of an annotated type. At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't' with extra metadata. The alias behaves like a normal typing alias. Instantiating is the same as instantiating the underlying type; binding it to types is also the same. The metadata itself is stored in a '__metadata__' attribute as a tuple. NDArray(*args, **kwargs) 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. ## Other Additional exports automol.rd RDKit bridge, operating on RDKit `Mol` objects only (never `Geometry`). ---------------------------------------------------------------------- This is the User Guide documentation for the package. ---------------------------------------------------------------------- ## Getting Started # Installation automol requires Python 3.13 or later. It is published as a conda package on [prefix.dev](https://prefix.dev/channels/avcopan/automech) and as a Python package on [PyPI](https://pypi.org/project/automol/). ## With Pixi In a [Pixi](https://pixi.sh) workspace, add the `avcopan/automech` channel and then automol: ```bash pixi workspace channel add https://repo.prefix.dev/avcopan/automech pixi add automol ``` RDKit (identity and InChI/SMILES conversions) and py3Dmol (interactive viewing) are installed with it. :::{.callout-note} xyzrender, which `geom.render_svg` and `geom.render_gif` use, is only on PyPI, so the conda package leaves it out. To render images, add it as a PyPI dependency: ```bash pixi add --pypi xyzrender ``` Everything else works without it, and the render functions raise an `ImportError` explaining this if it is missing. ::: ## With pip or uv ```bash pip install automol # or: uv add automol ``` This installs xyzrender too. ## For development See [Contributing](https://github.com/avcopan/automol/blob/main/CONTRIBUTING.md). ## User Guide # Geometries The `Geometry` model and the `automol.geom` module are the core of automol: almost everything else (identities, visualization, RDKit interoperability) is built on top of `Geometry`. ## Creating a `Geometry` A `Geometry` is a pydantic model with four fields: atomic `symbols`, Cartesian `coordinates` (in Angstroms), `charge`, and `spin` (number of unpaired electrons, i.e. `2S`): ```python from automol import Geometry water = Geometry( symbols=["O", "H", "H"], coordinates=[[0.0, 0.0, 0.0], [0.0, 0.0, 0.96], [0.93, 0.0, -0.24]], charge=0, spin=0, ) ``` `Geometry` is validated on construction and on assignment (a pydantic `ValidationError`, which is a `ValueError`, is raised otherwise): - `symbols` must be known elements; they are canonicalized, so `"cl"` becomes `"Cl"`. - `coordinates` must have shape `(len(symbols), 3)`. - `spin` must be non-negative, no larger than the electron count, and of the same parity. Geometries compare equal (`==`) when all fields match, with coordinates compared exactly. ### Per-atom properties `Geometry` exposes several derived, per-atom properties, backed by `automol.utils.element`'s periodic table data: ```python water.atom_count # 3 water.masses # isotopic masses, e.g. [15.9949, 1.0078, 1.0078] water.atomic_numbers # [8, 1, 1] water.covalent_radii # Pyykko covalent radii, in Angstroms water.valences # number of valence electrons per atom ``` ## Reading and writing xyz `Geometry` round-trips through the standard xyz format, both as instance methods and as module-level functions in `automol.geom`: ```python from automol import geom xyz = water.xyz_block(comment="water") water_rt = Geometry.from_xyz_block(xyz, charge=0, spin=0) water.xyz_file(path="water.xyz") water_rt = Geometry.from_xyz_file("water.xyz", charge=0, spin=0) # equivalent module-level functions xyz = geom.xyz_block(water, comment="water") water_rt = geom.from_xyz_block(xyz, charge=0, spin=0) ``` `charge` and `spin` aren't part of the xyz format, so they must be supplied explicitly when reading. Atoms may be given by symbol (case-insensitive) or atomic number. Only single-frame xyz blocks are supported. A malformed or empty xyz block, or one whose atom count line doesn't match the number of atom lines, raises `automol.utils.exc.XYZFormatError`. ## Molecular formula ```python from automol import hill_formula hill_formula.identity_fn(water) # "H2O" ``` Elements are in Hill order: with carbon present, C comes first, then H, then the rest alphabetically; without carbon, all elements (including H) are alphabetical. See [Molecular identity](../user-guide/identity.qmd). ## Geometric properties `automol.geom` also exposes a handful of properties computed directly from coordinates: ```python geom.center_of_mass(water) # mass-weighted centroid geom.distance_matrix(water) # pairwise atom-atom distances geom.adjacency_matrix(water) # binary connectivity, from covalent radii geom.distance_keys(water) # sorted (z1, z2, distance) descriptor ``` `adjacency_matrix` draws an edge between two atoms when their distance is less than `sigma` times the sum of their covalent radii (`sigma=1.3` by default). With `flood_fill=True`, `sigma` is increased until the molecule is connected (or no more edges can be added). With `enforce_valence=True`, the number of bonds to each atom is capped at its maximum valence, keeping the shortest bonds relative to their covalent radii. `distance_keys` produces an order-independent geometric fingerprint useful for comparing or hashing geometries. `bonds`, `angles`, and `dihedrals` take a geometry and an adjacency matrix and return sorted arrays of bonded pairs, triples, and quadruples, given by atomic numbers, with their distances or angles (in radians): ```python amat = geom.adjacency_matrix(water) geom.bonds(water, amat) # [[z1, z2, distance], ...] geom.angles(water, amat) # [[z1, z2, z3, theta], ...] geom.dihedrals(water, amat) # [[z1, z2, z3, z4, phi], ...] ``` To measure specific atoms by index, use `distance`, `angle`, and `dihedral` (in radians, or degrees with `degrees=True`): ```python geom.distance(water, [0, 1]) geom.angle(water, [1, 0, 2], degrees=True) # vertex in the middle from automol import rd peroxide = geom.from_rdkit_mol(rd.mol.from_smiles("OO")) # O, O, H, H geom.dihedral(peroxide, [2, 0, 1, 3], degrees=True) # H-O-O-H ``` ## Transformations `automol.geom` provides rigid transformations that return a new `Geometry` by default, or mutate in place with `in_place=True`: ```python from scipy.spatial.transform import Rotation shifted = geom.translate(water, [1.0, 0.0, 0.0]) rotated = geom.rotate(water, Rotation.from_euler("z", 90, degrees=True)) mirrored = geom.reflect(water, normal=[0, 0, 1]) ``` All three accept a `keys` argument to restrict the transformation to a subset of atoms by index, leaving the rest untouched: ```python geom.translate(water, [1.0, 0.0, 0.0], keys=[0]) # move only atom 0 ``` `rotate` and `reflect` also accept an `origin`: the point to rotate about, or a point on the reflection plane. For example, to rotate atom 2 about atom 0, or to move the center of mass to the origin: ```python rot = Rotation.from_euler("z", 30, degrees=True) geom.rotate(water, rot, origin=water.coordinates[0], keys=[2]) geom.center(water) ``` `alignment_rotation` finds the rotation that best maps one geometry onto another with the same atoms (by the Kabsch algorithm, about their centers of mass), and `inertial_frame_rotation` finds the rotation into the principal axis frame, with the principal axes from `principal_axes`: ```python rot = geom.alignment_rotation(water, rotated) # rotate(center(rotated), rot) ~ center(water) framed = geom.rotate(geom.center(water), geom.inertial_frame_rotation(water)) moments, axes = geom.principal_axes(water) # ascending; right-handed axes ``` ## Selecting and joining atoms ```python methane = geom.from_rdkit_mol(rd.mol.from_smiles("C")) # C, H, H, H, H methyl = geom.select_atoms(methane, [0, 1, 2, 3]) # keep these atoms, in this order methyl = geom.remove_atoms(methane, [4]) # same, by removing atom 4 dimer = geom.join([methyl, methyl]) # concatenate atoms ``` Selections keep the charge, and keep the spin when it is still consistent with the electron count (otherwise they use the lowest consistent spin, so the methyl radical above has `spin=1`). Pass `charge` and `spin` to override. `join` sums the charges and spins. ## Next steps - [Molecular identity](../user-guide/identity.qmd) — generate InChI/SMILES from a `Geometry`, or a `Geometry` from one. - [Visualization](../user-guide/visualization.qmd) — view or render a `Geometry`. - [Interoperability](../user-guide/interoperability.qmd) — convert to/from RDKit. # Molecular Identity `automol.ident` generates string identifiers (InChI, SMILES, molecular formulas, ...) from a `Geometry` and, where possible, reconstructs a `Geometry` from an identifier. Each algorithm is an `automol.Algorithm` instance; the built-in ones are `rdkit_inchi`, `rdkit_smiles`, and `hill_formula`. ## Generating an identifier from a `Geometry` ```python from automol import Geometry, hill_formula, rdkit_inchi, rdkit_smiles water = Geometry( symbols=["O", "H", "H"], coordinates=[[0.0, 0.0, 0.0], [0.0, 0.0, 0.96], [0.93, 0.0, -0.24]], charge=0, spin=0, ) rdkit_inchi.identity_fn(water) # "InChI=1S/H2O/h1H2" rdkit_smiles.identity_fn(water) # "O" hill_formula.identity_fn(water) # "H2O" ``` `hill_formula` uses Hill order: with carbon present, C comes first, then H, then the remaining elements alphabetically; without carbon, all elements (including H) are alphabetical (e.g. `"ClH"` for HCl). ## Going back to a `Geometry` Algorithms that support the inverse direction reconstruct a `Geometry` from the identifier, with reproducible (seeded) 3D coordinates: ```python water_rt = rdkit_inchi.geometry_fn("InChI=1S/H2O/h1H2") ``` An invalid identifier raises a `ValueError`. Calling `geometry_fn` on an algorithm with no known inverse (such as `hill_formula`) raises `NotImplementedError`. ## `kind` Every algorithm is tagged with an `IdentityKind` describing what sort of identity it produces (`"formula"`, `"isomer"`, `"stereoisomer"`, or `"conformer"`). This lets code group or dispatch on `kind` without hardcoding a specific algorithm. ## Parent algorithms and `other_geos` An identity function has the signature `(geo, other_geos=None) -> str`. `other_geos` maps previously assigned identifiers to their geometries, which lets an algorithm reuse an existing identifier for an equivalent species. An algorithm's `parent_algorithm` is the algorithm used to decide that equivalence. For example, `rdkit_smiles` has `rdkit_inchi` as its parent: if a geometry in `other_geos` has the same InChI, its (possibly non-canonical) SMILES key is returned; otherwise RDKit's canonical SMILES is returned. ```python other_geos = {"C(C)CCC": rdkit_smiles.geometry_fn("C(C)CCC")} pentane = rdkit_smiles.geometry_fn("CCCCC") rdkit_smiles.identity_fn(pentane, other_geos) # "C(C)CCC" ``` ## Registering an algorithm Algorithms are registered with `automol.ident.AlgorithmRegistry`, so higher-level packages can add their own without touching `automol` itself: ```python from automol import rdkit_inchi from automol.ident import AlgorithmRegistry, IdentityKind def my_identity_fn(geo, other_geos=None) -> str: ... # Geometry -> identifier my_algorithm = AlgorithmRegistry.register( name="my algorithm", kind=IdentityKind.CONFORMER, identity_fn=my_identity_fn, parent_algorithm=rdkit_inchi, # optional ) ``` `geometry_fn` (signature `(value) -> Geometry`) is optional. A function whose signature is incompatible with these shapes is rejected with a validation error. All registered algorithms are listed in `AlgorithmRegistry.algorithms`, and registering a name twice raises `automol.utils.exc.AlgorithmAlreadyRegisteredError`. # Visualization `automol.geom` builds on [py3Dmol](https://3dmol.csb.pitt.edu/) for interactive 3D viewing (e.g. in a Jupyter notebook) and on [xyzrender](https://pypi.org/project/xyzrender/) for static image and animation output. ## Interactive viewing `automol.View` is a `py3Dmol.view` subclass with convenience methods for adding `Geometry` objects and annotations: ```python from automol import Geometry, View water = Geometry( symbols=["O", "H", "H"], coordinates=[[0.0, 0.0, 0.0], [0.0, 0.0, 0.96], [0.93, 0.0, -0.24]], charge=0, spin=0, ) v = View() v.add_geometry(water, label=True) # label=True adds atom-index labels v.show() ``` In a notebook, the view renders inline; `v.show()` (inherited from `py3Dmol.view`) is only needed outside of that auto-display context. For a one-off view without constructing a `View` yourself: ```python from automol import geom v = geom.view(water, label=True) ``` ### Annotating with vectors `add_xyz_axes` draws the standard x/y/z axes (useful for checking orientation after a rotation), and `add_vector`/`add_vectors` draw arbitrary arrows — for example, an inertial axis or a bond dipole: ```python v.add_xyz_axes(scale=2.0) v.add_vector([1.0, 0.0, 0.0], start_coord=[0.0, 0.0, 0.0], color="purple") v.add_vectors( [[1, 0, 0], [0, 1, 0]], colors=["red", "green"], ) ``` `direction=True` treats the vector as an offset from `start_coord` rather than an absolute endpoint. ## Rendering to files `render_svg` and `render_gif` produce a static or rotating image without needing a browser or notebook — useful for scripts, reports, or CI artifacts: ```python from automol import geom geom.render_svg(water, out="water.svg") geom.render_gif(water, out="water.gif", rotation_axis="y") ``` Both accept `config` (an `xyzrender` `RenderConfig`, or `"default"`) and `include_h` to control whether hydrogens are drawn. `out` is optional — omit it to get the rendered result back without writing a file; the result also displays inline automatically in a notebook. # Interoperability `Geometry` stays deliberately minimal — symbols, coordinates, charge, and spin — so that conversions to other libraries' representations live outside the core model. `automol.geom` provides the `Geometry`-facing conversions; `automol.rd.mol` provides the lower-level RDKit building blocks they're built from. ## RDKit ```python from automol import Geometry, geom water = Geometry( symbols=["O", "H", "H"], coordinates=[[0.0, 0.0, 0.0], [0.0, 0.0, 0.96], [0.93, 0.0, -0.24]], charge=0, spin=0, ) mol = geom.rdkit_mol(water) # Geometry -> rdkit.Chem.Mol water_rt = geom.from_rdkit_mol(mol) # rdkit.Chem.Mol -> Geometry ``` `from_rdkit_mol` works whether or not the `Mol` already has 3D coordinates — if it doesn't, coordinates are embedded automatically (with a fixed random seed, so results are reproducible) before extraction. For lower-level RDKit work that doesn't go through `Geometry` at all, `automol.rd.mol` operates directly on `rdkit.Chem.Mol` objects: ```python from automol.rd import mol water_mol = mol.from_smiles("O", with_coords=True) mol.smiles(water_mol) # canonical, non-isomeric SMILES ("[H]O[H]") mol.inchi(water_mol) # InChI mol.symbols(water_mol) # ["O", "H", "H"] mol.max_bond_count("N") # 4 (allowing formal charges of +/-1) mol.coordinates(water_mol) # (N, 3) array; raises GeometryConversionError # if the Mol has no coordinates ``` The parsers (`from_smiles`, `from_inchi`, `from_xyz_block`) raise a `ValueError` for invalid input, and `add_coordinates` accepts a `seed` (`None` for a random one). Other utilities in this module include `add_atom_numbers` (for RDKit atom labels), `canonical_ranks` (RDKit's canonical atom ranking), and `assign_stereochemistry`/`chiral_centers` (stereochemistry from 3D coordinates). ## Adding a new conversion `automol` enforces a module layering (`ident` > `geom` > `rd` > `utils`; see the `import-linter` contract in `pyproject.toml`) where each module may only depend on modules below it. `geom/core.py` depends on `rd` (not the reverse) precisely because `rd` sits below `geom` in that layering, which is why the RDKit conversions (`rdkit_mol`/`from_rdkit_mol`) live in `geom/core.py` while the lower-level, `Geometry`-agnostic RDKit utilities they're built from live in `rd/mol.py`. If you're adding support for another third-party library, follow that same split: put library-specific, `Mol`/`Atoms`/etc.-facing utilities in their own module beneath `geom` in the layering, and put the `Geometry`-facing conversion functions in `geom` itself (as `rdkit_mol`/`from_rdkit_mol` already do) — rather than adding a new top-level dependency to the `Geometry` model itself.