# Identity

AutoStorage names each stationary point by several identity algorithms. The graph-based ones take the geometry and the graph the user is working with, index-aligned (`identity_fn(geo, gra, other_geos)`), and store a canonical form.


# Graphs as data

A graph is a frozen value. `==` and `hash` compare its fields (labelled equality), and the JSON is one byte string per graph:

``` python
>>> import protomol as pm
>>> gra = pm.MolGraph(symbols=["O", "H", "H"], bonds=[(0, 1), (0, 2)])
>>> pm.to_json(gra)
'{"type":"MolGraph","symbols":["O","H","H"],"bonds":[[0,1],[0,2]],"charge":0,"spin":0}'
>>> pm.from_json(pm.to_json(gra)) == gra
True
>>> len({gra, pm.MolGraph(symbols=["O", "H", "H"], bonds=[(2, 0), (1, 0)])})
1
```

Any graph type can be a field of another pydantic model, which is how a task's input or a row can carry one:

``` python
>>> from pydantic import BaseModel
>>> class SpeciesTask(BaseModel):  # ae, illustrative
...     graph: pm.AnyGraph
...     method: str
>>> task = SpeciesTask(graph=gra, method="b3lyp/6-31g*")
>>> SpeciesTask.model_validate_json(task.model_dump_json()).graph == gra
True
```

Labelled equality is not isomorphism. The same molecule with its atoms in another order is a different graph:

``` python
>>> hoh = pm.MolGraph(symbols=["H", "O", "H"], bonds=[(0, 1), (1, 2)])
>>> hoh == gra
False
>>> # the atom indices show the order
>>> pm.display(hoh, atom_indices=True)  # doctest: +SKIP
```

`relabel(gra, atom_map)` reorders the atoms: atom k of the result is atom `atom_map[k]` of `gra`, the direction of AutoStorage's link `atom_map` (canonical atom k is input atom `atom_map[k]`). The inverse map, `np.argsort(atom_map)`, undoes it:

``` python
>>> pm.relabel(gra, [1, 0, 2]) == hoh
True
>>> pm.relabel(hoh, [1, 0, 2]) == gra  # [1, 0, 2] is its own inverse
True
```

`isomorphism(g1, g2)` compares two graphs up to atom numbering (VF2++). It returns an atom map `m` with `relabel(g1, m) == g2`, or `None`, and [deduplicate](../reference/deduplicate.md#protomol.deduplicate) keeps the first graph of each isomorphism class:

``` python
>>> pm.isomorphism(gra, hoh)
(1, 0, 2)
>>> pm.deduplicate([gra, hoh]) == [gra]
True
```


# Canonical form

`canonical_form(gra)` returns the canonical graph and the atom map to it: atom k of the canonical graph is atom `atom_map[k]` of `gra`. Two numberings of one molecule give one canonical graph, and [canonical_json](../reference/canonical_json.md#protomol.canonical_json) is its JSON, the string AutoStorage stores:

``` python
>>> import numpy as np
>>> can, atom_map = pm.canonical_form(hoh)
>>> atom_map
(1, 0, 2)
>>> pm.relabel(hoh, atom_map) == can   # atom_map is the relabelling
True
>>> pm.relabel(can, np.argsort(atom_map)) == hoh   # its inverse recovers the input
True
>>> pm.canonical_json(hoh) == pm.canonical_json(gra)
True
>>> pm.canonical_json(gra)
'{"type":"MolGraph","symbols":["O","H","H"],"bonds":[[0,1],[0,2]],"charge":0,"spin":0}'
```


## Canonical direction

A reaction graph and its [reverse](../reference/reverse.md#protomol.reverse) are one transition state seen from its two sides, but their canonical forms differ. `canonical_direction(gra)` returns whichever of the two has the smaller [canonical_json](../reference/canonical_json.md#protomol.canonical_json), and whether it reversed; atom indices are kept:

``` python
>>> ts = pm.examples.abstraction_ts()
>>> chosen, flipped = pm.canonical_direction(ts)
>>> again, flipped_again = pm.canonical_direction(pm.reverse(ts))
>>> chosen == again, flipped != flipped_again
(True, True)
>>> pm.canonical_json(chosen) == min(
...     pm.canonical_json(ts), pm.canonical_json(pm.reverse(ts))
... )
True
```


## Mirror images

`enantiomer(gra)` is the mirror image: every chiral LS inverted ([Tetrahedral](../reference/Tetrahedral.md#protomol.Tetrahedral), [AtropBond](../reference/AtropBond.md#protomol.AtropBond), and a reaction graph's change slots too), planar bonds and undetermined LS kept, atom indices kept. `is_chiral(gra)` says whether it differs from `gra`, and `canonical_enantiomer(gra)` picks one of the two reproducibly, the one with the smaller canonical JSON (like InChI's `/m0`). That is the enantiomer AutoEngine computes, and AutoStorage stores the other as its mirror partner:

``` python
>>> smg = pm.examples.species()
>>> pm.is_chiral(smg), pm.is_chiral(pm.from_smiles("C[C@@H](O)[C@@H](O)C"))  # meso
(True, False)
>>> mirror = pm.enantiomer(smg)
>>> pm.canonical_json(mirror) == pm.canonical_json(pm.from_smiles(r"C[C@H](O)/C=C/C"))
True
>>> pm.canonical_json(pm.canonical_enantiomer(smg)) == pm.canonical_json(
...     pm.canonical_enantiomer(mirror)
... )
True
```

On a reaction graph the choice doesn't depend on the direction: each mirror image is compared in its canonical direction, and the winner is returned in the input's direction.


## The canonical TS

A TS has four versions: the graph, its reverse, its mirror image, and the mirror image reversed. All four are one saddle point up to reflection, so they get one canonical TS: `canonical_direction(canonical_enantiomer(ts))`, the mirror image chosen first, then the direction. Atom indices are kept, so an atom map from [canonical_form](../reference/canonical_form.md#protomol.canonical_form) of the result applies to the TS geometry as it is (reflected, if [canonical_enantiomer](../reference/canonical_enantiomer.md#protomol.canonical_enantiomer) picked the mirror image):

``` python
>>> ts = pm.examples.stereoisomerization_ts()
>>> def canonical_ts(ts):
...     chosen, _ = pm.canonical_direction(pm.canonical_enantiomer(ts))
...     return pm.canonical_json(chosen)
>>> versions = [ts, pm.reverse(ts), pm.enantiomer(ts), pm.reverse(pm.enantiomer(ts))]
>>> len({canonical_ts(v) for v in versions})
1
```

A chain LS (an allene or cumulene axis) counts too, so an achiral allene is its own mirror image and a chiral one isn't:

``` python
>>> pm.is_chiral(pm.from_smiles("C=C=C")), pm.is_chiral(pm.from_smiles("C=C=CC"))
(False, False)
>>> axes = pm.stereoisomers(pm.from_smiles("CC=C=CC"))  # penta-2,3-diene
>>> [pm.is_chiral(axis) for axis in axes]
[True, True]
>>> pm.canonical_json(pm.enantiomer(axes[0])) == pm.canonical_json(axes[1])
True
```


# Stereo sites: the low-T scheme

Which features of a species get an LS is a scheme. [from_smiles](../reference/from_smiles.md#protomol.from_smiles) and [from_geometry](../reference/from_geometry.md#protomol.from_geometry) use the low-T scheme (pm P54); [low_t](../reference/low_t.md#protomol.low_t) applies it to any graph. A plain graph gets the scheme's sites, undetermined unless they are trivial, so [low_t](../reference/low_t.md#protomol.low_t) is how a [MolGraph](../reference/MolGraph.md#protomol.MolGraph) gets its stereo sites:

``` python
>>> amine = pm.from_smiles("C[N@](CC)C(C)O")
>>> plain = pm.without_stereo(amine)
>>> low = pm.low_t(plain)
>>> [(ls.atoms[0], ls.parity) for ls in low.atom_stereo if ls.parity != 1]
[(1, None), (4, None)]
```

The amine N and the CH centre are undetermined; the CH3 groups and the CH2 are trivial (parity 1). A site the graph already has keeps its parity, a site the scheme doesn't have loses its LS, and no parity is invented. So [low_t](../reference/low_t.md#protomol.low_t) leaves the output of [from_smiles](../reference/from_smiles.md#protomol.from_smiles) and [from_geometry](../reference/from_geometry.md#protomol.from_geometry) as it is, and applying it twice changes nothing:

``` python
>>> pm.low_t(amine) == amine
True
>>> pm.low_t(low) == low
True
```

A reaction graph's two sides are reassigned separately, and each [StereoChange](../reference/StereoChange.md#protomol.StereoChange) slot follows its side's site. The TS slots are kept as they are:

``` python
>>> ts = pm.examples.stereoisomerization_ts()
>>> pm.low_t(ts) == ts
True
```

> **Note: Note**
>
> Planned: January (`high_t`, InChI's rules) and Phase 5 (TS sites).


# An SMG identity algorithm

> **Note: Note**
>
> Planned: Phases 2 and 3. The AutoStorage side (`IdentityResult`, the registry, the `graph=` argument) is AutoStorage's API, shown here only for the protomol calls in it.

``` python
from autostorage import IdentityResult    # illustrative

def smg_low_t(geo, gra, other_geos):      # registered as "smg_low_t@1", orders {0}
    if gra is None:                       # AutoStorage perceives one for order 0
        gra = pm.from_geometry(geo)
    elif pm.geometry_mismatches(gra, geo):  # disagree: warn, naming the atoms; perceive
        gra = pm.from_geometry(geo)
    low = fill_parities(pm.low_t(gra), geo)  # added sites read from geo (private, P57)
    can, atom_map = pm.canonical_form(low)
    return IdentityResult(value=pm.canonical_json(can), atom_map=atom_map)
```

`smg_high_t@1` uses `high_t`, and `smg_conn@1` uses `pm.without_stereo`. The value is the canonical JSON; AutoStorage adds its hash for the uniqueness index (pm P47).


# Storing and finding a point by its graph

``` python
point = StationaryPointRow(geometry=geo, calculation=calc, order=0, graph=smg)  # illustrative
session.add(point)                        # the identities are computed on flush

stmt = autostorage.query.stationary_points(graph=smg, algorithm="smg@1")        # illustrative
```
