---------------------------------------------------------------------- This is the API documentation for the autostorage library. ---------------------------------------------------------------------- ## Classes Core classes Database(path: str | pathlib.Path, *, echo: bool = False) -> None Database connection manager. Attributes: path: Path to SQLite database file. engine: SQLAlchemy engine instance. AutostorageSession(bind: 'Optional[_SessionBind]' = None, *, autoflush: 'bool' = True, future: 'Literal[True]' = True, expire_on_commit: 'bool' = True, autobegin: 'bool' = True, twophase: 'bool' = False, binds: 'Optional[Dict[_SessionBindKey, _SessionBind]]' = None, enable_baked_queries: 'bool' = True, info: 'Optional[_InfoType]' = None, query_cls: 'Optional[Type[Query[Any]]]' = None, autocommit: 'Literal[False]' = False, join_transaction_mode: 'JoinTransactionMode' = 'conditional_savepoint', close_resets_only: 'Union[bool, _NoArg]' = _NoArg.NO_ARG, execution_options: 'OrmExecuteOptionsParameter' = immutabledict({})) `sqlmodel.Session` with autostorage's validation and identity listeners. IdentityAlgorithm(*, name: str, kind: autostorage.types.IdentityKind, identity_fn: autostorage.identity.IdentityProtocol, parent: autostorage.identity.IdentityAlgorithm | None = None, orders: frozenset[int] | None = None) -> None A registered identity algorithm. Attributes: name: Unique algorithm name (mirrored into `IdentityAlgorithmRow`). kind: Category of identity produced. identity_fn: ``(geo, other_geos=None) -> str``, generating the identity. parent: Algorithm whose identity selects the `other_geos` passed to `identity_fn`, if any. orders: Stationary point orders the algorithm applies to. `None` if it applies to any order. IdentityAlgorithmRegistry() Central registry of all known identity algorithms. CalculationGeometryLink(*, geometry_id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=False, foreign_key='geometry.id', ondelete='CASCADE', unique=PydanticUndefined, index=False, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, calculation_id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=False, foreign_key='calculation.id', ondelete='CASCADE', unique=PydanticUndefined, index=False, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, role: Annotated[autostorage.types.Role, FieldInfoMetadata(primary_key=PydanticUndefined, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=Column('role', Enum('input', 'output', name='role'), table=), sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)]) -> None Association table linking geometries to a calculation. CalculationRow(*, id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = , model_id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=False, nullable=False, foreign_key='model.id', ondelete='CASCADE', unique=PydanticUndefined, index=True, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, calc_type: str, input_provenance: Annotated[dict[str, Any] | None, FieldInfoMetadata(primary_key=PydanticUndefined, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=Column('input_provenance', JSON(), table=), sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = , output_provenance: Annotated[dict[str, Any] | None, FieldInfoMetadata(primary_key=PydanticUndefined, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=Column('output_provenance', JSON(), table=), sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = ) -> None Quantum chemistry calculation and its associated data. Attributes: id: Primary key. model_id: Foreign key to the model used for this calculation. calc_type: Type of calculation (energy, gradient, hessian, etc.). input_provenance: Metadata describing how the input was generated. output_provenance: Metadata describing how the output was produced. model: Model used for this calculation. geometry_links: Raw link rows connecting geometries to this calculation. trajectory_links: Raw link rows connecting trajectories to this calculation. properties: Property values (energies, gradients, Hessians, ...) produced by this calculation. validations: Validation results performed by this calculation. stationary_points: Stationary points identified by this calculation. CalculationTrajectoryLink(*, trajectory_id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=False, foreign_key='trajectory.id', ondelete='CASCADE', unique=PydanticUndefined, index=False, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, calculation_id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=False, foreign_key='calculation.id', ondelete='CASCADE', unique=PydanticUndefined, index=False, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, role: Annotated[autostorage.types.Role, FieldInfoMetadata(primary_key=PydanticUndefined, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=Column('role', Enum('input', 'output', name='role'), table=), sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)]) -> None Association table linking trajectories to a calculation. GeometryRow(*, symbols: Annotated[list[str], FieldInfoMetadata(primary_key=PydanticUndefined, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=Column('symbols', JSON(), table=), sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)], coordinates: Annotated[numpy._typing._array_like.NDArray[numpy.float64], FieldInfoMetadata(primary_key=PydanticUndefined, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=Column('coordinates', CompressedArrayTypeDecorator(), table=), sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined), SkipValidation(), BeforeValidator(func=, json_schema_input_type=PydanticUndefined), PlainSerializer(func=, return_type=, when_used='always')], charge: int = 0, spin: int = 0, id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = , hash: Annotated[str | None, FieldInfoMetadata(primary_key=PydanticUndefined, nullable=False, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=True, index=True, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None) -> None Molecular geometry definition and metadata. Attributes: id: Primary key. symbols: Atomic symbols in order. coordinates: Atomic coordinates in Angstrom. A `pint.Quantity` with length units is converted to Angstrom. charge: Total molecular charge. spin: Number of unpaired electrons (2S). hash: `geometry_hash` of this geometry, set on flush. Unique, so the same geometry can't be stored twice. properties: Property values (energies, gradients, Hessians, ...) computed at this geometry. stationary_points: Stationary points defined by this geometry. trajectory_links: Raw link rows connecting this geometry to trajectories. calculation_links: Raw link rows connecting this geometry to calculations. GeometryTrajectoryLink(*, geometry_id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=False, foreign_key='geometry.id', ondelete='CASCADE', unique=PydanticUndefined, index=False, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, trajectory_id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=False, foreign_key='trajectory.id', ondelete='CASCADE', unique=PydanticUndefined, index=False, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, index: Annotated[list[int] | None, FieldInfoMetadata(primary_key=PydanticUndefined, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=Column('index', JSON(), table=), sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, values: Annotated[list[float | None] | None, FieldInfoMetadata(primary_key=PydanticUndefined, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=Column('values', JSON(), table=), sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None) -> None Association table linking geometries to a trajectory. IdentityAlgorithmRow(*, name: Annotated[str, FieldInfoMetadata(primary_key=True, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)], kind: autostorage.types.IdentityKind, parent_algorithm_name: Annotated[str | None, FieldInfoMetadata(primary_key=False, nullable=True, foreign_key='identity_algorithm.name', ondelete='CASCADE', unique=PydanticUndefined, index=False, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None) -> None A chemical identifier algorithm, mirroring an `IdentityAlgorithm`. Attributes: name: Primary key; the registered algorithm name (e.g. ``rdkit_inchi``). kind: Category of identifier produced (e.g. ``stereoisomer``, ``formula``). parent_algorithm_name: Foreign key to the parent algorithm, whose identity disambiguates this one's `other_geos`, if any. IdentityRow(*, id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = , algorithm_name: Annotated[str | None, FieldInfoMetadata(primary_key=False, nullable=False, foreign_key='identity_algorithm.name', ondelete='CASCADE', unique=PydanticUndefined, index=True, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, value: str) -> None A chemical identifier associated with one or more stationary points. Attributes: id: Primary key. algorithm_name: Foreign key to the generating `IdentityAlgorithmRow`. algorithm: Method used to generate the identifier (e.g. ``rdkit inchi``, ``rdkit smiles``); its ``kind`` gives the category (e.g. ``stereoisomer``, ``formula``). value: The resulting identifier string. stationary_links: Link rows to the stationary points sharing this identity. IdentityStationaryLink(*, stationary_id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=False, foreign_key='stationary_point.id', ondelete='CASCADE', unique=PydanticUndefined, index=False, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, identity_id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=False, foreign_key='identity.id', ondelete='CASCADE', unique=PydanticUndefined, index=False, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, identity_cache: Annotated[dict[str, Any] | None, FieldInfoMetadata(primary_key=PydanticUndefined, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=Column('identity_cache', CompressedJSONTypeDecorator(), table=), sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None) -> None Association table linking chemical identities to stationary points. Removing a link from `StationaryPointRow.identity_links` or `IdentityRow.stationary_links` deletes it. ModelRow(*, id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = , program: str, program_version: str | None = None, method: str, basis: str | None = None, keywords: Annotated[dict[str, Any] | None, FieldInfoMetadata(primary_key=PydanticUndefined, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=Column('keywords', JSON(), table=), sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = ) -> None Calculation model specification. Attributes: id: Primary key. program: Quantum chemistry program used (psi4, ORCA, ...) program_version: Quantum chemistry program version. method: Computational method (B3LYP, MP2, ...) basis: Orbital basis set. keywords: Additional keywords and options for the calculation. calculations: Calculations performed using this model. PropertyKindRow(*, name: Annotated[str, FieldInfoMetadata(primary_key=True, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)], units: str) -> None A kind of property (e.g. ``energy``, ``gradient``, ``hessian``). Rows mirror the in-memory `autostorage.property.PropertyKindRegistry`, keyed by name. Validation, unit conversion, and storage dtype are looked up from the registry by name, so rows loaded from the database behave the same as freshly seeded ones. The units are also stored, so the database records what its values mean. PropertyValueRow(*, id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = , geometry_id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=False, nullable=False, foreign_key='geometry.id', ondelete='CASCADE', unique=PydanticUndefined, index=True, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, calculation_id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=False, nullable=False, foreign_key='calculation.id', ondelete='CASCADE', unique=PydanticUndefined, index=True, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, property_kind_name: Annotated[str | None, FieldInfoMetadata(primary_key=False, nullable=False, foreign_key='property_kind.name', ondelete='CASCADE', unique=PydanticUndefined, index=True, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, value: Annotated[Any, FieldInfoMetadata(primary_key=PydanticUndefined, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=Column('value', CompressedArrayTypeDecorator(), table=), sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)]) -> None Property value for a specific geometry and calculation. StageRow(*, id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = , is_ts: bool = False) -> None A chemical state (reactant, product, or transition state) in a reaction. Attributes: id: Primary key. is_ts: Whether this stage represents a transition state. stationaries: Stationary points that make up this stage (bidirectional via `link_model=StageStationaryLink`). steps: Reaction steps referencing this stage as `stage1`, `stage2`, or `stage_ts`. Read-only view derived from `StepRow`'s foreign keys; use `stage1`, `stage2`, `stage_ts` relationships on `StepRow` for writing. StageStationaryLink(*, stationary_id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=False, foreign_key='stationary_point.id', ondelete='CASCADE', unique=PydanticUndefined, index=False, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, stage_id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=False, foreign_key='stage.id', ondelete='CASCADE', unique=PydanticUndefined, index=False, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None) -> None Association table linking stationary points to reaction stages. Relationships are managed via `StationaryPointRow.stages` and `StageRow.stationaries`, using this table as their `link_model`. StationaryPointRow(*, id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = , geometry_id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=False, nullable=False, foreign_key='geometry.id', ondelete='CASCADE', unique=PydanticUndefined, index=True, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, calculation_id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=False, nullable=False, foreign_key='calculation.id', ondelete='CASCADE', unique=PydanticUndefined, index=True, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, order: int = 0, is_pseudo: bool = False, is_validated: bool = False) -> None A stationary point on a potential energy surface. Attributes: id: Primary key. geometry_id: Foreign key to the underlying molecular geometry. calculation_id: Foreign key to the calculation that identified this point. order: Hessian index (0 for minima, 1 for first-order saddle points). is_pseudo: Whether this point is not a true stationary point (e.g. constrained). is_validated: Whether every Hessian of the geometry has `order` negative eigenvalues; set on flush, unless the point is pseudo. geometry: Geometry defining the coordinates of this point. calculation: Calculation that identified this point. identity_links: Link rows to this point's chemical identifiers (e.g. InChI, SMILES), each with its `identity_cache`. stages: Reaction stages this stationary point belongs to. StepRow(*, id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = , stage_id1: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=False, nullable=False, foreign_key='stage.id', ondelete='CASCADE', unique=PydanticUndefined, index=False, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, stage_id2: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=False, nullable=False, foreign_key='stage.id', ondelete='CASCADE', unique=PydanticUndefined, index=True, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, stage_id_ts: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=False, nullable=True, foreign_key='stage.id', ondelete='CASCADE', unique=PydanticUndefined, index=True, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, is_barrierless: bool = False) -> None An elementary reaction step connecting a reactant, TS, and product. StepValidationLink(*, step_id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=False, foreign_key='step.id', ondelete='CASCADE', unique=PydanticUndefined, index=False, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, validation_id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=False, foreign_key='validation.id', ondelete='CASCADE', unique=PydanticUndefined, index=False, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None) -> None Association table linking validations to a step. Relationships are managed via `ValidationRow.step` and `StepRow.validations`, using this table as their `link_model`. TrajectoryAxisRow(*, trajectory_id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=False, foreign_key='trajectory.id', ondelete='CASCADE', unique=PydanticUndefined, index=False, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, axis: Annotated[int, FieldInfoMetadata(primary_key=True, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)], kind: autostorage.types.AxisKind, keys: Annotated[list[int] | None, FieldInfoMetadata(primary_key=PydanticUndefined, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=Column('keys', JSON(), table=), sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, units: str | None = None, label: str | None = None) -> None Physical coordinate that one dimension of a trajectory runs along. Examples: A relaxed scan of the H-O-O-H dihedral of hydrogen peroxide: >>> axis = TrajectoryAxisRow(axis=0, kind="dihedral", keys=[0, 1, 2, 3]) >>> geo = GeometryRow( ... symbols=["H", "O", "O", "H"], ... coordinates=[[0, 0, 1], [0, 0, 0], [0, 1, 0], [1, 1, 0]], ... ) >>> axis.measure(geo) 90.0 TrajectoryRow(*, id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = , ndim: Annotated[int | None, FieldInfoMetadata(primary_key=PydanticUndefined, nullable=True, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None) -> None Ordered sequence of geometries from a calculation trajectory. Attributes: id: Primary key. ndim: Length of each linked geometry's `index` (inferred from the first link if unset). axes: Physical coordinates (e.g. a scanned dihedral) that the dimensions run along, ordered by `axis`. Dimensions without one are only indexed. geometry_links: Raw link rows connecting geometries to this trajectory. calculation_links: Raw link rows connecting calculations to this trajectory. ValidationRow(*, id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=True, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = , calculation_id: Annotated[uuid.UUID | None, FieldInfoMetadata(primary_key=False, nullable=False, foreign_key='calculation.id', ondelete='CASCADE', unique=PydanticUndefined, index=True, sa_type=PydanticUndefined, sa_column=PydanticUndefined, sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = None, method: str, extras: Annotated[dict[str, Any], FieldInfoMetadata(primary_key=PydanticUndefined, nullable=PydanticUndefined, foreign_key=PydanticUndefined, ondelete=PydanticUndefined, unique=PydanticUndefined, index=PydanticUndefined, sa_type=PydanticUndefined, sa_column=Column('extras', JSON(), table=), sa_column_args=PydanticUndefined, sa_column_kwargs=PydanticUndefined)] = ) -> None Validation result for a specific step and calculation. Attributes: id: Primary key. calculation_id: Foreign key to the calculation that performed this validation. method: Type of validation step (e.g., ``irc``) extras: Additional metadata attached to this validation. calculation: Calculation that performed this validation. step: Reaction step this validation belongs to. PropertyKind(*, name: str, validation_fn: autostorage.property.PropertyValidationProtocol, units: str, dtype: type[numpy.floating] = ) -> None A registered kind of property. Attributes: name: Unique property kind name (primary key of `PropertyKindRow`). validation_fn: Function checking that a value has the expected shape. units: Native units, as a `pint` unit string; values are stored in these. dtype: NumPy dtype used to store values of this kind. PropertyKindRegistry() Central registry of all known property kinds. CompressedArrayTypeDecorator(dtype: Any = , *args: Any, **kwargs: Any) -> None Stores a NumPy array as zlib-compressed binary data in the DB. Shape and dtype are preserved via the NumPy `.npy` format, so this works for arrays of any dimensionality (flat vectors, coordinate matrices, Hessians, ...). CompressedJSONTypeDecorator(*args: 'Any', **kwargs: 'Any') Stores a JSON-serializable value as zlib-compressed binary data in the DB. ## Protocols Structural typing protocols IdentityProtocol(*args, **kwargs) Protocol for identity functions. PropertyValidationProtocol(*args, **kwargs) Protocol for property value validation functions. ## Enumerations Enum types AxisKind(*values) Physical coordinate that a trajectory dimension runs along. IdentityKind(*values) Category of molecular identity, from coarsest to finest. Role(*values) Relationship between calculations and geometries/trajectories. ## Exceptions Exception classes IdentityGenerationWarning An identity algorithm could not generate an identity for a geometry. StationaryOrderWarning A stationary point's Hessian does not have the point's `order`. ## Functions Public functions geometry_hash(geo: autogeom._geometry.Geometry) -> str SHA-256 digest of a Geometry's symbols, coordinates, charge, and spin. create_identity_algorithms(session: sqlmodel.orm.session.Session) -> None Create or update a row for every registered identity algorithm. create_property_kinds(session: sqlmodel.orm.session.Session) -> None Create a row for every registered property kind that is missing one. Raises: ValueError: If a stored kind's units differ from the registered ones, since its stored values would then be misread. set_geometry_hash(mapper: sqlalchemy.orm.mapper.Mapper[autostorage.models.GeometryRow], connection: sqlalchemy.engine.base.Connection, target: autostorage.models.GeometryRow) -> None Set `hash`, whose unique index rejects duplicate geometries. sort_step_stage_ids(mapper: sqlalchemy.orm.mapper.Mapper[autostorage.models.StepRow], connection: sqlalchemy.engine.base.Connection, target: autostorage.models.StepRow) -> None Auto-sort stage_id1 and stage_id2 so stage_id1 < stage_id2. verify_step_barrierless_consistency(mapper: sqlalchemy.orm.mapper.Mapper[autostorage.models.StepRow], connection: sqlalchemy.engine.base.Connection, target: autostorage.models.StepRow) -> None Verify that `is_barrierless` is True exactly when `stage_id_ts` is None. verify_property_values_before_flush(session: sqlmodel.orm.session.Session, flush_context: sqlalchemy.orm.unitofwork.UOWTransaction, instances: object) -> None Convert property values to their kind's native units and dtype, and validate. A `pint.Quantity` is converted to the kind's units; other values are assumed to be in those units already. verify_valid_stationary_has_hessian(session: sqlmodel.orm.session.Session, flush_context: sqlalchemy.orm.unitofwork.UOWTransaction, instances: object) -> None Verify that stationary points marked as validated have a Hessian. validate_stationary_order_before_flush(session: sqlmodel.orm.session.Session, flush_context: sqlalchemy.orm.unitofwork.UOWTransaction, instances: object) -> None Set `is_validated` from whether the Hessians have the stationary point's order. Runs for new or modified stationary points, and for those whose geometry gains, changes, or loses a Hessian. A point is validated if every Hessian of its geometry has `order` negative eigenvalues (`autogeom.stationary_point_order`); otherwise it is not, with a `StationaryOrderWarning`. Pseudo stationary points are skipped. verify_trajectory_geometry_ndim(session: sqlmodel.orm.session.Session, flush_context: sqlalchemy.orm.unitofwork.UOWTransaction, instances: object) -> None Ensure each linked geometry's index length matches its trajectory's ndim. A trajectory without an ndim adopts the index length of its first link. This runs before the flush (rather than in a mapper-level "before_insert" hook) so that the inferred `TrajectoryRow.ndim` is persisted too. fill_trajectory_axis_values(session: sqlmodel.orm.session.Session, flush_context: sqlalchemy.orm.unitofwork.UOWTransaction, instances: object) -> None Validate trajectory axes, and fill in the values of their geometries. Missing values of measurable axes (distances, angles, dihedrals) are measured from each geometry, and `pint.Quantity` values are converted to the axis's units. Adding an axis to a trajectory fills in the values of its existing geometries. Registered after `verify_trajectory_geometry_ndim`, so that the inferred ndim is available. add_registry_identities_before_flush(session: sqlmodel.orm.session.Session, flush_context: sqlalchemy.orm.unitofwork.UOWTransaction, instances: object) -> None Attach registry identities to new stationary points. Generates and attaches an `IdentityRow` for every registered algorithm (e.g. InChI, SMILES, Hill formula). Identities of persisted stationary points are regenerated if their geometry or order changes. stationary_point_by_identity(algorithm: autostorage.identity.IdentityAlgorithm | autostorage.models.IdentityAlgorithmRow | str, value: str, *, include_pseudo: bool = False) -> sqlmodel.sql._expression_select_cls.SelectOfScalar Select stationary points with a given identity. Args: algorithm: Identity algorithm, e.g. `autostorage.rdkit_inchi`, an `IdentityAlgorithmRow`, or an algorithm name. value: Identity value, e.g. an InChI string. include_pseudo: Whether to also select pseudo stationary points. Returns: Statement to run with `session.exec(...)`. rdkit_inchi_conn_identity_fn(geo: autogeom._geometry.Geometry, other_geos: OtherGeometries = None) -> str Generate a connectivity InChI string with RDKit. rdkit_inchi_identity_fn(geo: autogeom._geometry.Geometry, other_geos: OtherGeometries = None) -> str Generate a standard InChI string with RDKit. rdkit_smiles_identity_fn(geo: autogeom._geometry.Geometry, other_geos: OtherGeometries = None) -> str Generate a SMILES string with RDKit. If a geometry in `other_geos` has the same InChI, its SMILES key is returned, so that equivalent species share one (possibly non-canonical) SMILES. Otherwise, RDKit's canonical SMILES is returned. hill_formula_identity_fn(geo: autogeom._geometry.Geometry, other_geos: OtherGeometries = None) -> str Generate the molecular formula in Hill order. ## Constants Module-level constants and data hill_formula A registered identity algorithm. Attributes: name: Unique algorithm name (mirrored into `IdentityAlgorithmRow`). kind: Category of identity produced. identity_fn: ``(geo, other_geos=None) -> str``, generating the identity. parent: Algorithm whose identity selects the `other_geos` passed to `identity_fn`, if any. orders: Stationary point orders the algorithm applies to. `None` if it applies to any order. rdkit_inchi A registered identity algorithm. Attributes: name: Unique algorithm name (mirrored into `IdentityAlgorithmRow`). kind: Category of identity produced. identity_fn: ``(geo, other_geos=None) -> str``, generating the identity. parent: Algorithm whose identity selects the `other_geos` passed to `identity_fn`, if any. orders: Stationary point orders the algorithm applies to. `None` if it applies to any order. rdkit_inchi_conn A registered identity algorithm. Attributes: name: Unique algorithm name (mirrored into `IdentityAlgorithmRow`). kind: Category of identity produced. identity_fn: ``(geo, other_geos=None) -> str``, generating the identity. parent: Algorithm whose identity selects the `other_geos` passed to `identity_fn`, if any. orders: Stationary point orders the algorithm applies to. `None` if it applies to any order. rdkit_smiles A registered identity algorithm. Attributes: name: Unique algorithm name (mirrored into `IdentityAlgorithmRow`). kind: Category of identity produced. identity_fn: ``(geo, other_geos=None) -> str``, generating the identity. parent: Algorithm whose identity selects the `other_geos` passed to `identity_fn`, if any. orders: Stationary point orders the algorithm applies to. `None` if it applies to any order. energy_property_kind A registered kind of property. Attributes: name: Unique property kind name (primary key of `PropertyKindRow`). validation_fn: Function checking that a value has the expected shape. units: Native units, as a `pint` unit string; values are stored in these. dtype: NumPy dtype used to store values of this kind. gradient_property_kind A registered kind of property. Attributes: name: Unique property kind name (primary key of `PropertyKindRow`). validation_fn: Function checking that a value has the expected shape. units: Native units, as a `pint` unit string; values are stored in these. dtype: NumPy dtype used to store values of this kind. hessian_property_kind A registered kind of property. Attributes: name: Unique property kind name (primary key of `PropertyKindRow`). validation_fn: Function checking that a value has the expected shape. units: Native units, as a `pint` unit string; values are stored in these. dtype: NumPy dtype used to store values of this kind. types.MAX_DECOMPRESSED_BYTES 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 ## Type Aliases Type alias definitions OtherGeometries Type alias. Type aliases are created through the type statement:: type Alias = int In this example, Alias and int will be treated equivalently by static type checkers. At runtime, Alias is an instance of TypeAliasType. The __name__ attribute holds the name of the type alias. The value of the type alias is stored in the __value__ attribute. It is evaluated lazily, so the value is computed only if the attribute is accessed. The __module__ attribute holds the name of the module in which the type alias was defined; it can be assigned to. Type aliases can also be generic:: type ListOrSet[T] = list[T] | set[T] In this case, the type parameters of the alias are stored in the __type_params__ attribute. See PEP 695 for more information. ---------------------------------------------------------------------- This is the User Guide documentation for the package. ---------------------------------------------------------------------- ## Getting Started # Quickstart ## Installation autostorage requires Python 3.13 or later. With [Pixi](https://pixi.sh), add it from the [`avcopan/automech`](https://prefix.dev/channels/avcopan/automech) channel on prefix.dev, which also has autogeom: ```bash pixi workspace channel add https://repo.prefix.dev/avcopan/automech pixi add autostorage ``` Or install it from PyPI: ```bash pip install autostorage # or: uv add autostorage ``` ## Usage ```python import numpy as np from sqlmodel import select from autostorage import ( CalculationGeometryLink, CalculationRow, Database, GeometryRow, ModelRow, PropertyValueRow, Role, StationaryPointRow, energy_property_kind, query, rdkit_inchi, ) # Open (or create) a SQLite database; ":memory:" also works for scratch use. with Database("workflow.db") as db, db.session() as session: # Create a model specifying the program, method, and basis. model = ModelRow(program="orca", method="b3lyp", basis="def2-svp") # Create a calculation using this model. calc = CalculationRow(model=model, calc_type="energy") # Create a geometry (validated by autogeom: known elements, consistent spin). geo = GeometryRow( symbols=["H", "O", "H"], coordinates=np.array([[0, 0, 0.96], [0, 0, 0], [0.93, 0, -0.24]]), charge=0, spin=0, ) # Link the geometry to the calculation as an input. link = CalculationGeometryLink(calculation=calc, geometry=geo, role=Role.INPUT) # Add all objects to the session and commit. session.add_all([model, calc, geo, link]) session.commit() # Attach an energy to the geometry/calculation pair. Values are validated # against their property kind ("energy", "gradient", "hessian") on flush. energy = PropertyValueRow( geometry=geo, calculation=calc, property_kind_name=energy_property_kind.name, value=-76.02, ) session.add(energy) session.commit() # Query the energy back by geometry and property kind. found = session.exec( select(PropertyValueRow).where( PropertyValueRow.geometry_id == geo.id, PropertyValueRow.property_kind_name == "energy", ) ).one() print(float(found.value)) # Stationary points are automatically given identities (InChI, SMILES, # Hill formula), which can be used to look them up. session.add(StationaryPointRow(geometry=geo, calculation=calc)) session.commit() stmt = query.stationary_point_by_identity(rdkit_inchi, "InChI=1S/H2O/h1H2") print(session.exec(stmt).all()) ``` The `Database.session()` method returns an `AutostorageSession` (a `sqlmodel.Session`) that supports the context manager protocol. Validation and automatic identities are only applied by these sessions. Commit explicitly to persist changes; closing a session rolls back anything uncommitted. See the {doc}`API reference ` for full details on every model and method. ## User Guide # Data Models autostorage uses SQLModel/SQLAlchemy to define a relational schema for computational chemistry workflow data. The models form a graph structure where molecular geometries, calculations, stationary points, and chemical identities are linked through explicit relationship tables. ## Model Overview The schema is organized into five functional groups: ### Link Tables Association tables implementing many-to-many relationships between entities. | Model | Description | |-------|-------------| | `CalculationGeometryLink` | Associates geometries with calculations, tracking whether each geometry is an input or output | | `GeometryTrajectoryLink` | Links geometries to trajectories with position indices and, optionally, the physical value along each dimension (`values`) | | `CalculationTrajectoryLink` | Associates trajectories with calculations as inputs or outputs | | `StageStationaryLink` | Connects stationary points to reaction stages | | `StepValidationLink` | Links validation calculations to reaction steps | | `IdentityStationaryLink` | Associates chemical identities with stationary points; its `identity_cache` holds data that makes generating identities cheaper | ### Core Data Models The fundamental entities representing molecular structures, calculations, and their results. | Model | Description | |-------|-------------| | `GeometryRow` | Molecular geometry with atomic symbols, coordinates, charge, and spin; extends `autogeom.Geometry` | | `TrajectoryRow` | Ordered sequence of geometries from a dynamic calculation; `view(axis, at)` animates the geometries along one dimension, and `values_along(axis, at)` gives their physical values | | `TrajectoryAxisRow` | The physical coordinate (distance, angle, dihedral, or other) that one dimension of a trajectory runs along, such as a scanned dihedral | | `ModelRow` | Calculation model specification (program, method, basis set, keywords) | | `CalculationRow` | Quantum chemistry calculation with provenance metadata | | `PropertyKindRow` | A kind of property (`energy`, `gradient`, `hessian`, ...), mirroring `PropertyKindRegistry` by name | | `PropertyValueRow` | A property value for a geometry/calculation pair, validated against its kind's expected shape | | `ValidationRow` | Validation result (e.g., IRC) for a reaction step | ### Stationary Points Models representing critical points on potential energy surfaces. | Model | Description | |-------|-------------| | `StationaryPointRow` | A stationary point with Hessian index and validation status | ### Reaction Network Models defining elementary reaction steps and their constituent chemical states. | Model | Description | |-------|-------------| | `StageRow` | A chemical state in a reaction (reactant, product, or transition state) | | `StepRow` | An elementary reaction step connecting two stages via a transition state (or barrierless) | ### Chemical Identities Models for chemical identification and classification. | Model | Description | |-------|-------------| | `IdentityAlgorithmRow` | An identity algorithm (name, kind, parent), mirroring an `IdentityAlgorithm` | | `IdentityRow` | A chemical identifier value (InChI, SMILES, Hill formula, ...) generated by an algorithm; attached to stationary points automatically | ## Scans and Other Trajectories A trajectory's geometries are placed on a grid by their integer `index`. To record what a dimension means physically, such as the dihedral angle of a relaxed scan, give the trajectory a `TrajectoryAxisRow` for that dimension: ```python from autostorage import AxisKind, GeometryTrajectoryLink, TrajectoryAxisRow, TrajectoryRow scan = TrajectoryRow() scan.axes.append( TrajectoryAxisRow( axis=0, kind=AxisKind.DIHEDRAL, keys=[0, 1, 2, 3], label="H-O-O-H torsion" ) ) for i, geo in enumerate(scan_geometries): scan.geometry_links.append(GeometryTrajectoryLink(geometry=geo, index=[i])) session.add(scan) session.commit() scan.values_along(0) # dihedrals in degrees, in index order scan.values_along(0, units="radian") ``` On flush, each link's `values` (one per dimension, aligned with `index`) are filled in: - Missing values of distance, angle, and dihedral axes are measured from the geometry with autogeom. Distances default to Angstrom and angles to degrees; set `units` on the axis to store them in other units. Measured dihedrals lie between -180° and 180°. - Given values are kept, so you can store a scan's nominal (constrained) values instead. A `pint.Quantity` is converted to the axis's units. - `AxisKind.OTHER` axes (e.g. an IRC arc length) are never measured, so their values must be given. - Adding an axis to a stored trajectory fills in the values of its existing geometries. ## Design Principles - **autogeom integration**: `GeometryRow` extends `autogeom.Geometry` directly rather than wrapping it, delegating validation and format conversions to autogeom - **Identities from a registry**: identities are generated by the algorithms in `IdentityAlgorithmRegistry` (see [Identities](../user-guide/identities.qmd)) - **Registries mirrored by name**: `IdentityAlgorithmRow` and `PropertyKindRow` rows are seeded from their in-memory registries when a `Database` is opened, and looked up by name - **Explicit relationships**: Many-to-many relationships use dedicated link tables rather than implicit joins - **Cascading deletes**: deleting a row deletes its link rows and the data that depends on it: a model's calculations, a geometry's or calculation's property values and stationary points, and a calculation's validations. Geometries, stages, steps, and identities are kept - **Provenance tracking**: Calculations record both input and output provenance metadata - **Native units**: each property kind declares its native units (`energy` in Hartree, `gradient` in Hartree/Bohr, `hessian` in Hartree/Bohr²). Values are always stored in them: a `pint.Quantity` (e.g. `autogeom.ureg.Quantity(-1.2, "kcal/mol")`) is converted on flush, and a value without units is assumed to be in the native units already. molar units such as kcal/mol are converted with Avogadro's constant. `PropertyKind.from_native(value, "kcal/mol")` converts a stored value back out, and `PropertyKind.quantity` attaches the native units to it - **Validated stationary points**: on flush, a stationary point is marked `is_validated` if every Hessian of its geometry has `order` negative eigenvalues after translations and rotations are projected out (`autogeom.vibrational_analysis` and `autogeom.stationary_point_order`). Otherwise, `is_validated` is reset to `False` and a `StationaryOrderWarning` is issued. This check runs again when the point or one of its Hessians is added, changed, or deleted. Pseudo stationary points are skipped - **Compressed storage**: NumPy arrays (coordinates and property values) are stored as zlib-compressed binary data via `CompressedArrayTypeDecorator`; property values are stored as float64, except Hessians (float32). Identity caches are stored as zlib-compressed JSON via `CompressedJSONTypeDecorator` - **Graph structure**: The schema forms a directed graph where calculations consume and produce geometries/trajectories, geometries carry results, stationary points reference geometries, and reaction steps connect stages # Database The `autostorage.database` module provides SQLite database connection management through the `Database` class. ## Overview The `Database` class is a lightweight wrapper around SQLAlchemy's engine and session management, configured for SQLite with: - **Foreign key enforcement** — SQLite's `PRAGMA foreign_keys=ON` is automatically enabled - **Thread-safe pooling** — `check_same_thread=False` lets pooled connections move between threads; sessions are not thread-safe, so use one `session()` per thread - **Canonical JSON serialization** — JSON column comparisons work regardless of dict key order - **Automatic schema creation** — All SQLModel tables are created on initialization ## Creating a Database ```python from autostorage import Database # Create or connect to a database db = Database("path/to/database.db") # Enable SQL logging for debugging db = Database("path/to/database.db", echo=True) ``` The database file is created if it doesn't exist. All tables defined in `autostorage.models` are automatically created via SQLModel metadata. ## Using Sessions Sessions manage transactions and provide the query interface. Always use sessions as context managers to ensure proper cleanup: ```python from sqlmodel import select from autostorage import Database, GeometryRow db = Database("molecules.db") # Create a session context with db.session() as session: # Add a geometry geo = GeometryRow( 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, ) session.add(geo) session.commit() # Explicitly commit changes # Query geometries results = session.exec(select(GeometryRow)).all() ``` **Important**: Each call to `db.session()` creates a **new** session. Nothing is committed automatically — you must call `session.commit()` to persist changes. ### Session Lifecycle ```python with db.session() as session: # Add/modify rows session.add(row) # Flush to DB without committing (assigns IDs, checks constraints) session.flush() # Commit the transaction session.commit() # Session is automatically closed here ``` For more details on session usage, querying, transaction control, and advanced patterns, see the [SQLAlchemy Session documentation](https://docs.sqlalchemy.org/en/21/orm/session_basics.html). ## Closing the Database When finished with a database, dispose of the connection pool: ```python db.close() ``` This is typically unnecessary for short-lived scripts but recommended for long-running applications. # Identities An identity is a string that says what a stationary point *is*: its formula, its InChI, its SMILES, a conformer label. Each identity comes from an **identity algorithm**, and each algorithm partitions the stationary points in a database into groups that share a value. Different algorithms partition at different resolutions, so the same stationary points can be grouped by formula, by stereoisomer, or by conformer. ## Built-in algorithms autostorage registers the following algorithms itself: | algorithm | kind | parent | value | |---|---|---|---| | `rdkit_inchi_conn` | `isomer` | | Connectivity InChI (no stereo layers), from `autogeom.inchi(geo, stereo=False)` | | `rdkit_inchi` | `stereoisomer` | | Standard InChI, from `autogeom.inchi` | | `rdkit_smiles` | `stereoisomer` | `rdkit_inchi` | SMILES, from `autogeom.smiles` | | `hill_formula` | `formula` | `rdkit_inchi` | Formula in Hill order, from `autogeom.formula` | When a `StationaryPointRow` is added through a `Database.session()`, an `IdentityRow` is attached to it for every registered algorithm, and regenerated if its geometry or `order` changes. Algorithms registered with restricted `orders = {0}`, such as `rdkit_inchi_conn`, `rdkit_inchi`, and `rdkit_smiles`, are skipped for higher-order saddle points. Unrestricted algorithms such as `hill_formula` apply to all algorithms. Stationary points with the same value share one `IdentityRow`. Stereoisomers such as cis- and trans-1,2-difluoroethene therefore share one `rdkit_inchi_conn` identity but have different `rdkit_inchi` identities. If an algorithm fails for a geometry (for example, InChI for a metal complex), an `IdentityGenerationWarning` is issued and that identity is skipped. Look stationary points up by identity with `query.stationary_point_by_identity`: ```python from autostorage import Database, query, rdkit_inchi with Database(":memory:") as db, db.session() as session: stmt = query.stationary_point_by_identity(rdkit_inchi, "InChI=1S/H2O/h1H2") waters = session.exec(stmt).all() ``` ## Kinds Every algorithm has an `IdentityKind` that says what sort of identity it produces: `formula`, `isomer`, `stereoisomer`, or `conformer`. This lets code select algorithms by kind without naming a specific one. ## Parents and `other_geos` An identity function has the signature `(geo, other_geos=None) -> str`. For an algorithm with a `parent`, `other_geos` holds one geometry per existing identity value among the stationary points that share this geometry's *parent* identity. The function can then return one of those existing values instead of making a new one. `rdkit_smiles` uses this: its parent is `rdkit_inchi`, so if a stationary point with the same InChI already has a SMILES, that SMILES is reused, even if it isn't RDKit's canonical one. The same mechanism lets a conformer algorithm compare a new geometry only against the conformers of the same species. ## Registering your own algorithm Register an algorithm before opening the `Database`, which mirrors the registry into its `identity_algorithm` table: ```python import uuid from collections.abc import Mapping import autogeom import numpy as np from autogeom import Geometry from autostorage import Database, IdentityAlgorithmRegistry, IdentityKind, rdkit_inchi def rmsd_conformer_identity_fn( geo: Geometry, other_geos: Mapping[str, Geometry] | None = None ) -> str: """Reuse the label of an existing conformer within 0.1 Å RMSD, or make a new one.""" for label, other_geo in (other_geos or {}).items(): aligned = autogeom.rotate( autogeom.center(geo), autogeom.alignment_rotation(geo, other_geo) ) diff = aligned.coordinates - autogeom.center(other_geo).coordinates if np.sqrt((diff**2).sum(axis=1).mean()) < 0.1: return label return uuid.uuid4().hex rmsd_conformer = IdentityAlgorithmRegistry.register( name="rmsd_conformer", kind=IdentityKind.CONFORMER, identity_fn=rmsd_conformer_identity_fn, parent=rdkit_inchi, # compare only against geometries with the same InChI orders={0}, # must be compatible with parent orders ) db = Database(":memory:") # new stationary points now also get an rmsd_conformer identity db.close() ``` Algorithm names must be unique: registering a name twice raises a `ValueError`. `IdentityAlgorithmRegistry.get(name)` returns a registered algorithm, and `IdentityAlgorithmRegistry.algorithms` lists them all. An identity function should raise `ValueError`, `NotImplementedError`, or `autogeom.GeometryConversionError` for a geometry it cannot handle; these are reported as an `IdentityGenerationWarning`. ## Next steps - [Data models](../user-guide/models.qmd): the `IdentityAlgorithmRow` and `IdentityRow` tables that store identities. - [Database](../user-guide/database.qmd): opening a `Database`, which mirrors the registry into it.