# Geometries

The [Geometry](../reference/Geometry.md#automol.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](../reference/Geometry.md#automol.Geometry).


# Creating a [Geometry](../reference/Geometry.md#automol.Geometry)

A [Geometry](../reference/Geometry.md#automol.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](../reference/Geometry.md#automol.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](../reference/Geometry.md#automol.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](../reference/Geometry.md#automol.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](../reference/geom.XYZFormatError.md#automol.geom.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](identity.md).


# 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](../reference/geom.adjacency_matrix.md#automol.geom.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](../reference/geom.distance_keys.md#automol.geom.distance_keys) produces an order-independent geometric fingerprint useful for comparing or hashing geometries.

[bonds](../reference/geom.bonds.md#automol.geom.bonds), [angles](../reference/geom.angles.md#automol.geom.angles), and [dihedrals](../reference/geom.dihedrals.md#automol.geom.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](../reference/geom.distance.md#automol.geom.distance), [angle](../reference/geom.angle.md#automol.geom.angle), and [dihedral](../reference/geom.dihedral.md#automol.geom.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](../reference/Geometry.md#automol.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](../reference/geom.rotate.md#automol.geom.rotate) and [reflect](../reference/geom.reflect.md#automol.geom.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](../reference/geom.alignment_rotation.md#automol.geom.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](../reference/geom.inertial_frame_rotation.md#automol.geom.inertial_frame_rotation) finds the rotation into the principal axis frame, with the principal axes from [principal_axes](../reference/geom.principal_axes.md#automol.geom.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](../reference/geom.join.md#automol.geom.join) sums the charges and spins.


# Next steps

- [Molecular identity](identity.md) -- generate InChI/SMILES from a [Geometry](../reference/Geometry.md#automol.Geometry), or a [Geometry](../reference/Geometry.md#automol.Geometry) from one.
- [Visualization](visualization.md) -- view or render a [Geometry](../reference/Geometry.md#automol.Geometry).
- [Interoperability](interoperability.md) -- convert to/from RDKit.
