---------------------------------------------------------------------- This is the API documentation for the autogeom library. ---------------------------------------------------------------------- ## Geometry The model at the center of the package, and selecting or combining its atoms 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: >>> import autogeom >>> geo = autogeom.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 select_atoms(geo: autogeom._geometry.Geometry, keys: collections.abc.Sequence[int], *, charge: int | None = None, spin: int | None = None) -> autogeom._geometry.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: >>> import numpy as np >>> import autogeom >>> geo = autogeom.Geometry( ... symbols=["C", "H", "H", "H", "H"], ... coordinates=np.zeros((5, 3)), ... charge=0, ... spin=0, ... ) >>> methyl = autogeom.select_atoms(geo, [0, 1, 2, 3]) >>> methyl.symbols, methyl.spin (['C', 'H', 'H', 'H'], 1) remove_atoms(geo: autogeom._geometry.Geometry, keys: collections.abc.Collection[int], *, charge: int | None = None, spin: int | None = None) -> autogeom._geometry.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[autogeom._geometry.Geometry]) -> autogeom._geometry.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. ## Geometry Methods Methods for the Geometry class __eq__(self, other: object) -> bool Compare geometries field by field, including exact coordinates. __repr__(self) -> str Render the geometry as an xyz block. atom_count Number of atoms. masses Atomic masses. atomic_numbers Atomic numbers. covalent_radii Pyykko covalent radii, in Angstroms. valences Numbers of valence electrons. 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)``. ## XYZ files Reading and writing single- and multi-frame xyz xyz_block(geo: autogeom._geometry.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) -> autogeom._geometry.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: autogeom._geometry.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) -> autogeom._geometry.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[autogeom._geometry.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[autogeom._geometry.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_file(geos: collections.abc.Sequence[autogeom._geometry.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[autogeom._geometry.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. 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. ## Properties and measurements Quantities computed from the coordinates center_of_mass(geo: autogeom._geometry.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). inertia_tensor(geo: autogeom._geometry.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: >>> import numpy as np >>> import autogeom >>> geo = autogeom.Geometry( ... symbols=["O", "H", "H"], ... coordinates=[[0, 0, 0], [1, 0, 0], [0, 1, 0]], ... charge=0, ... spin=0, ... ) >>> tensor = autogeom.inertia_tensor(geo) >>> tensor.shape (3, 3) >>> bool(np.allclose(tensor, tensor.T)) True principal_axes(geo: autogeom._geometry.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). distance_matrix(geo: autogeom._geometry.Geometry) -> numpy.ndarray Calculate the interatomic distance matrix. Args: geo: Geometry. Returns: Distance matrix, shape ``(N, N)``. adjacency_matrix(geo: autogeom._geometry.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 `autogeom.rd.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)``. distance_keys(geo: autogeom._geometry.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)``. distance(geo: autogeom._geometry.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: autogeom._geometry.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: >>> import autogeom >>> geo = autogeom.Geometry( ... symbols=["O", "H", "H"], ... coordinates=[[0, 0, 0], [1, 0, 0], [0, 1, 0]], ... charge=0, ... spin=0, ... ) >>> autogeom.angle(geo, [1, 0, 2], degrees=True) 90.0 dihedral(geo: autogeom._geometry.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: >>> import autogeom >>> geo = autogeom.Geometry( ... symbols=["H", "O", "O", "H"], ... coordinates=[[0, 0, 1], [0, 0, 0], [0, 1, 0], [1, 1, 0]], ... charge=0, ... spin=0, ... ) >>> autogeom.dihedral(geo, [0, 1, 2, 3], degrees=True) 90.0 bonds(geo: autogeom._geometry.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: >>> import autogeom >>> geo = autogeom.Geometry( ... symbols=["O", "H", "H"], ... coordinates=[[0, 0, 0], [1, 0, 0], [0, 1, 0]], ... charge=0, ... spin=0, ... ) >>> b = autogeom.bonds(geo, autogeom.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: autogeom._geometry.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: >>> import autogeom >>> geo = autogeom.Geometry( ... symbols=["O", "H", "H"], ... coordinates=[[0, 0, 0], [1, 0, 0], [0, 1, 0]], ... charge=0, ... spin=0, ... ) >>> a = autogeom.angles(geo, autogeom.adjacency_matrix(geo)) >>> a.shape (1, 4) >>> round(float(a[0][-1]), 6) 1.570796 dihedrals(geo: autogeom._geometry.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: >>> import numpy as np >>> import autogeom >>> geo = autogeom.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 = autogeom.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 ## Transformations Moving atoms, and the rotations that align geometries translate(geo: autogeom._geometry.Geometry, arr: ArrayLike, *, keys: collections.abc.Collection[int] | None = None, in_place: bool = False) -> autogeom._geometry.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. rotate(geo: autogeom._geometry.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) -> autogeom._geometry.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. reflect(geo: autogeom._geometry.Geometry, normal: ArrayLike, *, origin: ArrayLike = (0.0, 0.0, 0.0), keys: collections.abc.Collection[int] | None = None, in_place: bool = False) -> autogeom._geometry.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. center(geo: autogeom._geometry.Geometry, *, in_place: bool = False) -> autogeom._geometry.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. twist(geo: autogeom._geometry.Geometry, keys: collections.abc.Sequence[int], angle: float, *, degrees: bool = False) -> autogeom._geometry.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: >>> import autogeom >>> geo = autogeom.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 = autogeom.twist(geo, (1, 2), 90, degrees=True) >>> round(autogeom.dihedral(geo, [0, 1, 2, 3], degrees=True), 6) 90.0 twist_angle(geo: autogeom._geometry.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. alignment_rotation(geo: autogeom._geometry.Geometry, ref: autogeom._geometry.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: >>> from scipy.spatial.transform import Rotation >>> import autogeom >>> ref = autogeom.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 = autogeom.rotate(ref, rot) >>> round(float(autogeom.alignment_rotation(geo, ref).magnitude()), 6) 0.523599 axis_alignment_rotation(geo: autogeom._geometry.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: >>> import autogeom >>> geo = autogeom.Geometry( ... symbols=["H", "H"], coordinates=[[0, 0, 0], [1, 0, 0]], charge=0, spin=0 ... ) >>> rot = autogeom.axis_alignment_rotation(geo, [0, 1], axis=[0, 1, 0]) >>> autogeom.rotate(geo, rot).coordinates.round(6).tolist() [[0.0, 0.0, 0.0], [0.0, 1.0, 0.0]] inertial_frame_rotation(geo: autogeom._geometry.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. ## Conversions InChI, SMILES, formulas, and RDKit molecules inchi(geo: autogeom._geometry.Geometry, *, stereo: bool = True) -> str Generate the standard InChI string of a geometry with RDKit. Args: geo: Geometry. stereo: Whether to include the stereo layers. Returns: InChI string. Raises: NotImplementedError: If the geometry contains a metal. GeometryConversionError: If no Lewis structure is consistent with the connectivity, charge, and spin. ValueError: If RDKit fails to generate an InChI. Example: >>> import autogeom >>> geo = autogeom.from_smiles("O") >>> autogeom.inchi(geo) 'InChI=1S/H2O/h1H2' %seealso from_inchi, smiles, formula from_inchi(inchi: str) -> autogeom._geometry.Geometry Embed a geometry for an InChI string with RDKit. Coordinates are embedded with a fixed random seed, so they are reproducible. Args: inchi: InChI string. Returns: The embedded geometry. Raises: ValueError: If the InChI string is invalid. Example: >>> import autogeom >>> geo = autogeom.from_inchi("InChI=1S/H2O/h1H2") >>> geo.symbols ['O', 'H', 'H'] %seealso inchi, from_smiles smiles(geo: autogeom._geometry.Geometry) -> str Generate the canonical SMILES string of a geometry with RDKit. Stereochemistry perceived from the 3D coordinates is included, and hydrogens are implicit. Args: geo: Geometry. Returns: SMILES string. Raises: NotImplementedError: If the geometry contains a metal. GeometryConversionError: If no Lewis structure is consistent with the connectivity, charge, and spin. Example: >>> import autogeom >>> geo = autogeom.from_smiles("C(O)C") >>> autogeom.smiles(geo) 'CCO' %seealso from_smiles, inchi from_smiles(smiles: str) -> autogeom._geometry.Geometry Embed a geometry for a SMILES string with RDKit. Coordinates are embedded with a fixed random seed, so they are reproducible. Args: smiles: SMILES string. Returns: The embedded geometry. Raises: ValueError: If the SMILES string is invalid. Example: >>> import autogeom >>> geo = autogeom.from_smiles("[OH]") >>> geo.symbols, geo.spin (['O', 'H'], 1) %seealso smiles, from_inchi formula(geo: autogeom._geometry.Geometry) -> str Generate the molecular formula of a geometry in Hill order. With carbon present, C comes first, then H, then the remaining elements alphabetically. Without carbon, all elements (including H) are alphabetical. Args: geo: Geometry. Returns: Molecular formula. Example: >>> import autogeom >>> autogeom.formula(autogeom.from_smiles("CO")) 'CH4O' >>> autogeom.formula(autogeom.from_smiles("Cl")) 'ClH' rdkit_mol(geo: autogeom._geometry.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 `autogeom.rd.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) -> autogeom._geometry.Geometry Convert an RDKit molecule to a geometry, embedding coordinates if missing. Args: mol: RDKit molecule. Returns: The geometry. ## Visualization Interactive views and rendered images 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. view(geo: autogeom._geometry.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: autogeom._geometry.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: autogeom._geometry.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. ## Exceptions and units Errors raised by the package, and its unit registry GeometryConversionError A geometry could not be converted to or from another representation. XYZFormatError An xyz block could not be parsed. ElementNotFoundError No element matches the given atomic number or symbol. ureg(input_string: 'str', case_sensitive: 'bool | None' = None, **values: 'QuantityArgument') -> 'QuantityT' The unit registry stores the definitions and relationships between units. Parameters ---------- filename : path of the units definition file to load or line-iterable object. Empty string to load the default definition file. (default) None to leave the UnitRegistry empty. force_ndarray : bool convert any input, scalar or not to a numpy.ndarray. (Default: False) force_ndarray_like : bool convert all inputs other than duck arrays to a numpy.ndarray. (Default: False) default_as_delta : In the context of a multiplication of units, interpret non-multiplicative units as their *delta* counterparts. (Default: False) autoconvert_offset_to_baseunit : If True converts offset units in quantities are converted to their plain units in multiplicative context. If False no conversion happens. (Default: False) on_redefinition : str action to take in case a unit is redefined. 'warn', 'raise', 'ignore' (Default: 'raise') auto_reduce_dimensions : If True, reduce dimensionality on appropriate operations. (Default: False) autoconvert_to_preferred : If True, converts preferred units on appropriate operations. (Default: False) preprocessors : list of callables which are iteratively ran on any input expression or unit string or None for no preprocessor. (Default=None) fmt_locale : locale identifier string, used in `format_babel` or None. (Default=None) case_sensitive : bool, optional Control default case sensitivity of unit parsing. (Default: True) cache_folder : str or pathlib.Path or None, optional Specify the folder in which cache files are saved and loaded from. If None, the cache is disabled. (default) ## RDKit molecules `autogeom.rd`: functions on RDKit `Mol` objects, which never see a `Geometry` from_smiles(smi: str, *, with_coords: bool = False) -> rdkit.Chem.rdchem.Mol Parse a SMILES string. Args: smi: SMILES string. with_coords: If `True`, embed 3D coordinates. Returns: RDKit molecule with explicit hydrogens. Raises: ValueError: If the SMILES string cannot be parsed. smiles(mol: rdkit.Chem.rdchem.Mol) -> str Write a canonical, non-isomeric SMILES string. Hydrogens are written as they appear in the molecule, so water with explicit hydrogens (e.g. from `from_smiles`) gives ``[H]O[H]``. Args: mol: RDKit molecule. Returns: SMILES string. from_inchi(inchi: str, *, with_coords: bool = False) -> rdkit.Chem.rdchem.Mol Parse an InChI string. Args: inchi: InChI string. with_coords: If `True`, embed 3D coordinates. Returns: RDKit molecule with explicit hydrogens. Raises: ValueError: If the InChI string cannot be parsed. inchi(mol: rdkit.Chem.rdchem.Mol, *, stereo: bool = True) -> str Write a standard InChI string. Args: mol: RDKit molecule. stereo: Whether to include the stereo layers. Returns: InChI string. Raises: ValueError: If InChI generation fails. from_xyz_block(xyz_block: str) -> rdkit.Chem.rdchem.Mol Parse an xyz block, determining connectivity (but not bond orders). Args: xyz_block: The xyz block. Returns: RDKit molecule. Raises: ValueError: If the xyz block cannot be parsed. xyz_block(mol: rdkit.Chem.rdchem.Mol) -> str Write an xyz block. Args: mol: RDKit molecule. Returns: The xyz block. symbols(mol: rdkit.Chem.rdchem.Mol) -> list[str] Get the atomic symbols. Args: mol: RDKit molecule. Returns: Atomic symbols. coordinates(mol: rdkit.Chem.rdchem.Mol) -> numpy._typing._array_like.NDArray[numpy.float64] Get the atomic coordinates. Args: mol: RDKit molecule. Returns: Coordinates, shape ``(N, 3)``. Raises: GeometryConversionError: If the molecule has no coordinates. charge(mol: rdkit.Chem.rdchem.Mol) -> int Get the total formal charge. Args: mol: RDKit molecule. Returns: Molecular charge. spin(mol: rdkit.Chem.rdchem.Mol) -> int Get the number of unpaired electrons. Args: mol: RDKit molecule. Returns: Number of unpaired electrons. has_coordinates(mol: rdkit.Chem.rdchem.Mol) -> bool Check whether the molecule has a conformer. Args: mol: RDKit molecule. Returns: `True` if the molecule has coordinates. set_coordinates(mol: rdkit.Chem.rdchem.Mol, coords: numpy._typing._array_like.NDArray[numpy.float64], *, in_place: bool = False) -> rdkit.Chem.rdchem.Mol Set the atomic coordinates, replacing any existing conformers. Args: mol: RDKit molecule. coords: Coordinates, shape ``(N, 3)``. in_place: If `True`, modify `mol` instead of returning a copy. Returns: The molecule with the given coordinates. Raises: ValueError: If `coords` does not have shape ``(N, 3)``. add_coordinates(mol: rdkit.Chem.rdchem.Mol, *, seed: int | None = 61453, in_place: bool = False) -> rdkit.Chem.rdchem.Mol Embed 3D coordinates if the molecule has none. Args: mol: RDKit molecule. seed: Random seed for embedding. If `None`, use a random seed. in_place: If `True`, modify `mol` instead of returning a copy. Returns: The molecule with coordinates, or `mol` unchanged if it already had them. Raises: GeometryConversionError: If embedding fails, even from random initial coordinates. add_atom_numbers(mol: rdkit.Chem.rdchem.Mol, to_number: collections.abc.Mapping[int, int], *, in_place: bool = False) -> rdkit.Chem.rdchem.Mol Label atoms for drawing as ``f"{symbol}{number}"``. Args: mol: RDKit molecule. to_number: Number for each atom index. in_place: If `True`, modify `mol` instead of returning a copy. Returns: The molecule with ``"atomLabel"`` properties set. canonical_ranks(mol: rdkit.Chem.rdchem.Mol, *, break_ties: bool = True) -> list[int] Rank atoms canonically. Args: mol: RDKit molecule. break_ties: If `True`, break ties so that every rank is unique. Returns: Canonical rank of each atom. assign_stereochemistry(mol: rdkit.Chem.rdchem.Mol, *, in_place: bool = False) -> rdkit.Chem.rdchem.Mol Assign stereochemistry from the 3D coordinates. Args: mol: RDKit molecule. in_place: If `True`, modify `mol` instead of returning a copy. Returns: The molecule with stereochemistry tags. chiral_centers(mol: rdkit.Chem.rdchem.Mol) -> list[tuple[int, str]] Find chiral centers and their R/S labels. Args: mol: RDKit molecule. Returns: ``(index, label)`` pairs for all chiral centers. max_bond_count(symbol: str, *, max_charge: int = 1) -> float Get the maximum number of bonds to an atom. Formal charges up to `max_charge` in magnitude are allowed, with a charged atom taking the valences of its isoelectronic neutral counterpart (as in `from_connectivity`), e.g. 4 for N (as N+), 3 for O (as O+), and 6 for S. Args: symbol: Atomic symbol. max_charge: Maximum magnitude of the formal charge. Returns: Maximum bond count, or `math.inf` if RDKit places no limit on the valence (e.g. for metals). from_connectivity(symbols: collections.abc.Sequence[str], bonds: collections.abc.Collection[tuple[int, int]], *, charge: int = 0, spin: int = 0, coords: numpy._typing._array_like.ArrayLike | None = None) -> rdkit.Chem.rdchem.Mol Build a molecule from connectivity, perceiving its Lewis structure. Bond orders, formal charges, and radical electrons come from an integer linear program over the bonded atoms: - Each atom takes one (charge, valence) state from RDKit's valence model, where a charged atom uses the valences of its isoelectronic neutral counterpart. - Each bond takes an order of 1, 2, or 3. - Each atom's valence is saturated by its bond orders plus radical electrons. - Formal charges sum to `charge` and radical electrons sum to `spin`. The objective penalizes, from most to least severe: closed-shell lone pairs beyond the default valence (singlet carbenes), formal charges, valence expansion, and multiple radical electrons on one atom. Ties put negative charge on more electronegative atoms, and positive charge and radicals on less electronegative ones. Args: symbols: Atomic symbols. bonds: Pairs of bonded atom indices. charge: Total molecular charge. spin: Number of unpaired electrons. coords: Coordinates, shape ``(N, 3)``, added as a conformer if given. Returns: Sanitized RDKit molecule with explicit hydrogens. Raises: NotImplementedError: If the molecule contains a metal. GeometryConversionError: If no Lewis structure is consistent with the connectivity, charge, and spin. rd.EMBED_SEED int([x]) -> integer int(x, base=10) -> integer Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating-point numbers, this truncates towards zero. If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral. >>> int('0b100', base=0) 4 ## Elements `autogeom.element`: periodic table data, looked up by atomic number or symbol Element(Z: int, A: int, group: int | None, period: int, symbol: str, mass: float, covalent_radius: float, valence: int, electronegativity: float | None, metal: bool) -> None Chemical element. Attributes: Z: Atomic number. A: Mass number. group: Group number, or `None` for lanthanides and actinides. period: Period number. symbol: Chemical symbol. mass: Atomic mass. covalent_radius: Pyykko covalent radius, in Angstroms. valence: Number of valence electrons. electronegativity: Pauling electronegativity, if defined. metal: Whether the element is a metal. from_key(key: int | str) -> autogeom.element.Element Look up an element. Args: key: Atomic number or symbol. Returns: The element. Raises: TypeError: If `key` is not an `int` or `str`. ElementNotFoundError: If no element matches `key`. number(key: int | str) -> int Get the atomic number. Args: key: Atomic number or symbol. Returns: Atomic number. mass_number(key: int | str) -> int Get the mass number. Args: key: Atomic number or symbol. Returns: Mass number. symbol(key: int | str) -> str Get the canonical symbol, e.g. ``"Cl"`` for ``"cl"`` or ``17``. Args: key: Atomic number or symbol. Returns: Atomic symbol. mass(key: int | str) -> float Get the atomic mass. Args: key: Atomic number or symbol. Returns: Atomic mass. covalent_radius(key: int | str) -> float Get the Pyykko covalent radius. Args: key: Atomic number or symbol. Returns: Covalent radius, in Angstroms. group(key: int | str) -> int | None Get the group number. Args: key: Atomic number or symbol. Returns: Group number, or `None` for lanthanides and actinides. period(key: int | str) -> int Get the period number. Args: key: Atomic number or symbol. Returns: Period number. electronegativity(key: int | str) -> float | None Get the Pauling electronegativity. Args: key: Atomic number or symbol. Returns: Pauling electronegativity, or `None` if undefined (e.g. He, Ne, Ar). is_metal(key: int | str) -> bool Check whether an element is a metal. Args: key: Atomic number or symbol. Returns: `True` for alkali, alkaline earth, poor, and transition metals, lanthanides, and actinides. shell_capacity(key: int | str) -> int Get the valence shell capacity of the element's period. Args: key: Atomic number or symbol. Returns: Shell capacity (2, 8, 18, or 32). valence(key: int | str, *, override: dict[str, int] | None = None) -> int Get the number of valence electrons. Args: key: Atomic number or symbol. override: Valence overrides by symbol. Returns: Number of valence electrons. bonding_capacity(key: int | str, *, override: dict[str, int] | None = None) -> int Get the bonding capacity, ``min(valence, shell_capacity - valence)``. Args: key: Atomic number or symbol. override: Bonding capacity overrides by symbol. Returns: Bonding capacity. ## Types `autogeom.types`: array types and Pydantic fields 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. 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. 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. ---------------------------------------------------------------------- This is the User Guide documentation for the package. ---------------------------------------------------------------------- ## Getting Started # Installation autogeom 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/autogeom/). ## With Pixi In a [Pixi](https://pixi.sh) workspace, add the `avcopan/automech` channel and then autogeom: ```bash pixi workspace channel add https://repo.prefix.dev/avcopan/automech pixi add autogeom ``` RDKit (InChI/SMILES conversions and bond perception) and py3Dmol (interactive viewing) are installed with it. :::{.callout-note} xyzrender, which `render_svg` and `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 autogeom # or: uv add autogeom ``` This installs xyzrender too. ## For development See [Contributing](https://github.com/avcopan/autogeom/blob/main/CONTRIBUTING.md). ## User Guide # Geometries autogeom is built around one model, `Geometry`, and functions that take a `Geometry` as their first argument. All of them are imported from the package root: ```python import autogeom from autogeom import 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 autogeom 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 the periodic table data in `autogeom.element`: ```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 functions: ```python import autogeom 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 functions xyz = autogeom.xyz_block(water, comment="water") water_rt = autogeom.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. A malformed or empty xyz block, or one whose atom count line doesn't match the number of atom lines, raises `autogeom.XYZFormatError`. Multi-frame xyz files, such as conformer lists, are read and written with `from_xyz_trajectory_file`, `xyz_trajectory_file`, and their `_block` counterparts; `xyz_trajectory_comments` returns the comment line of each frame. ## Molecular formula `formula` gives the molecular formula of a geometry: ```python autogeom.formula(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 [Conversions](../user-guide/conversions.qmd). ## Geometric properties A handful of properties are computed directly from the coordinates: ```python autogeom.center_of_mass(water) # mass-weighted centroid autogeom.distance_matrix(water) # pairwise atom-atom distances autogeom.adjacency_matrix(water) # binary connectivity, from covalent radii autogeom.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 = autogeom.adjacency_matrix(water) autogeom.bonds(water, amat) # [[z1, z2, distance], ...] autogeom.angles(water, amat) # [[z1, z2, z3, theta], ...] autogeom.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 autogeom.distance(water, [0, 1]) autogeom.angle(water, [1, 0, 2], degrees=True) # vertex in the middle peroxide = autogeom.from_smiles("OO") # O, O, H, H autogeom.dihedral(peroxide, [2, 0, 1, 3], degrees=True) # H-O-O-H ``` ## Transformations The rigid transformations return a new `Geometry` by default, or mutate in place with `in_place=True`: ```python from scipy.spatial.transform import Rotation shifted = autogeom.translate(water, [1.0, 0.0, 0.0]) rotated = autogeom.rotate(water, Rotation.from_euler("z", 90, degrees=True)) mirrored = autogeom.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 autogeom.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) autogeom.rotate(water, rot, origin=water.coordinates[0], keys=[2]) autogeom.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 = autogeom.alignment_rotation(water, rotated) # rotate(center(rotated), rot) ~ center(water) framed = autogeom.rotate(autogeom.center(water), autogeom.inertial_frame_rotation(water)) moments, axes = autogeom.principal_axes(water) # ascending; right-handed axes ``` ## Selecting and joining atoms To take a geometry apart or put several together, use `select_atoms`, `remove_atoms`, and `join`: ```python methane = autogeom.from_smiles("C") # C, H, H, H, H methyl = autogeom.select_atoms(methane, [0, 1, 2, 3]) # keep these atoms, in this order methyl = autogeom.remove_atoms(methane, [4]) # same, by removing atom 4 dimer = autogeom.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. To build a complex, first move one geometry next to the other with `place`, which puts atom `j` of the moving geometry a distance (in Å, or a `pint` quantity) from atom `i` of the fixed one, and turns the rest of it away: ```python water = autogeom.from_smiles("O") oh = autogeom.from_smiles("[OH]") oh = autogeom.place(oh, water, (0, 0), 2.5) # atom 0 of OH, 2.5 Å from water's O complex_ = autogeom.join([water, oh]) ``` By default it approaches along the normal to the fixed geometry's best-fit plane (or along the axis of a linear one); pass `direction` to choose. Only the one distance is set, so check the result for clashes with other atoms. ## Next steps - [Conversions](../user-guide/conversions.qmd): InChI, SMILES, formulas, and RDKit. - [Visualization](../user-guide/visualization.qmd): view or render a `Geometry`. # Conversions `Geometry` stays deliberately minimal (symbols, coordinates, charge, and spin), so conversions to and from other representations are functions rather than fields. They all go through [RDKit](https://www.rdkit.org/). ## InChI and SMILES `inchi` and `smiles` generate a string from a geometry: ```python import autogeom from autogeom 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, ) autogeom.inchi(water) # "InChI=1S/H2O/h1H2" autogeom.smiles(water) # "O" ``` Bonding is perceived from the coordinates, charge, and spin (see [RDKit molecules](#rdkit-molecules) below), and stereochemistry is assigned from the 3D structure. `smiles` returns RDKit's canonical SMILES with implicit hydrogens. In the other direction, `from_inchi` and `from_smiles` embed 3D coordinates: ```python ethanol = autogeom.from_smiles("CCO") water_rt = autogeom.from_inchi("InChI=1S/H2O/h1H2") ``` Embedding uses a fixed random seed, so the same string always gives the same geometry. An invalid string raises a `ValueError`. ## Molecular formula `formula` needs no bond perception, only the atomic symbols: ```python autogeom.formula(ethanol) # "C2H6O" ``` `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). ## RDKit molecules `rdkit_mol` and `from_rdkit_mol` convert between a `Geometry` and an RDKit `Mol`: ```python mol = autogeom.rdkit_mol(water) # Geometry -> rdkit.Chem.Mol water_rt = autogeom.from_rdkit_mol(mol) # rdkit.Chem.Mol -> Geometry ``` `rdkit_mol` takes the connectivity from `adjacency_matrix` (with valence caps) and then perceives bond orders, formal charges, and radical electrons that exactly match the geometry's charge and spin. It raises `NotImplementedError` for geometries with metals, and `autogeom.GeometryConversionError` if no Lewis structure is consistent with the connectivity, charge, and spin. `from_rdkit_mol` works whether or not the `Mol` already has 3D coordinates: if it doesn't, they are embedded first. ### The `rd` module For RDKit work that doesn't go through `Geometry` at all, `autogeom.rd` operates directly on `rdkit.Chem.Mol` objects: ```python from autogeom import rd water_mol = rd.from_smiles("O", with_coords=True) rd.smiles(water_mol) # canonical, non-isomeric SMILES ("[H]O[H]") rd.inchi(water_mol) # InChI rd.symbols(water_mol) # ["O", "H", "H"] rd.max_bond_count("N") # 4 (allowing formal charges of +/-1) rd.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). The module also has `from_connectivity` (the bond perception behind `rdkit_mol`), `add_atom_numbers` (RDKit atom labels), `canonical_ranks`, and `assign_stereochemistry`/`chiral_centers`. ## Adding a new conversion A bridge module such as `rd` knows only its external library and never imports `Geometry`. The `Geometry`-facing functions are built on top of it and exported from the package root. To support another library, follow the same split; see [Contributing](https://github.com/avcopan/autogeom/blob/main/CONTRIBUTING.md). ## Next steps - [Geometries](../user-guide/geometry.qmd): measure and transform a `Geometry`. - [Visualization](../user-guide/visualization.qmd): view or render a `Geometry`. # Visualization autogeom 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 `autogeom.View` is a `py3Dmol.view` subclass with convenience methods for adding `Geometry` objects and annotations: ```python from autogeom 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 import autogeom v = autogeom.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, which is useful for scripts, reports, or CI artifacts: ```python import autogeom autogeom.render_svg(water, out="water.svg") autogeom.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. :::{.callout-note} `render_svg` and `render_gif` need xyzrender, which is only on PyPI. See [Installation](../user-guide/installation.qmd). ::: ## Next steps - [Geometries](../user-guide/geometry.qmd): build and transform the `Geometry` you want to view. - [Conversions](../user-guide/conversions.qmd): make a `Geometry` from a SMILES or InChI string. # Vibrations autogeom computes harmonic frequencies and normal modes from a Cartesian Hessian, with the translations and rotations projected out. ## The input: `PESPoint` A `PESPoint` is the local quadratic model of the potential energy surface at a geometry: the `Geometry`, its Hessian, and optionally the gradient and energy. The units are atomic, apart from the coordinates: | field | shape | units | |---|---|---| | `geometry` | N atoms | Å | | `hessian` | `(3N, 3N)` | Hartree/Bohr² | | `gradient` (optional) | `(N, 3)` | Hartree/Bohr | | `energy` (optional) | | Hartree | | `rotor_kind` (optional) | | `RotorKind` | ```python import numpy as np import autogeom geo = autogeom.from_xyz_file("ts.xyz", charge=0, spin=1) hess = np.loadtxt("ts_hessian.txt") # e.g. from a quantum chemistry program point = autogeom.PESPoint(geometry=geo, hessian=hess) ``` `PESPoint` is frozen. On construction it converts the arrays to float64 (float32 storage is fine), checks their shapes against the geometry, rejects NaN and inf, and symmetrizes the Hessian. ## Atoms, linear and nonlinear molecules `autogeom.rotor_kind(geo)` returns a `RotorKind`: `ATOM`, `LINEAR` or `NONLINEAR`. A geometry is linear when every atom lies within `tol` (default 1e-3 Å) of the best-fit line, so a molecule linear to within optimization noise (such as CO2 bent by 1e-4 Å) counts as linear. `PESPoint` fills in `rotor_kind` from its geometry, unless you pass it: ```python point = autogeom.PESPoint( geometry=geo, hessian=hess, rotor_kind=autogeom.RotorKind.NONLINEAR ) ``` ## Frequencies and modes ```python vib = autogeom.vibrational_analysis(point) vib.frequencies # cm⁻¹, ascending; imaginary frequencies are negative vib.modes # (n_vib, N, 3) Cartesian displacements, each normalized ``` The rotor kind fixes the number of modes in advance: 3N − 6 for a nonlinear molecule, 3N − 5 for a linear one, and none for an atom (`3 * N - 3 - point.rotor_kind.rotation_count`). `vib.eigenvalues` and `vib.eigenvectors` hold the eigenvalues (Hartree/(Bohr² amu)) and orthonormal eigenvectors (one per row) of the projected, mass-weighted Hessian. The masses default to the most abundant isotopes (`geo.masses`), as Gaussian uses. Pass `masses=` (amu, one per atom) for isotopologues, or to match a program that uses standard atomic weights, such as ORCA: ```python masses = [2.014 if s == "H" else m for s, m in zip(geo.symbols, geo.masses)] vib_d = autogeom.vibrational_analysis(point, masses=masses) ``` ## Stationary-point order ```python autogeom.stationary_point_order(vib) # 0 for a minimum, 1 for a saddle point, ... ``` The order counts the negative eigenvalues, with no threshold: every sign counts, including a van der Waals saddle point's mode of 10–20i cm⁻¹. A wrong order means the structure isn't converged well enough. The one ambiguous case is a nearly free internal rotor, whose mode can lie within a few cm⁻¹ of zero.