The core submodule

rsutil.core contains the dependency-light contracts shared by setup, exchange, result parsing, campaign generation, and ASE interoperability. The models use stable zero-based site and pair identities and provide explicit serialization for machine-readable artifacts.

Core contracts

RSStructure is the canonical structure representation. It stores three lattice vectors, site positions, chemical identity, optional RS labels/type indices, coordinate convention, periodic-boundary flags, and metadata. SetupSpec is the normalized parameter contract for the legacy -S setup workflow, including supercells, SQS, 2D geometry, distortions, and recursion controls. PairKey(i, j, R) identifies a periodic interaction from site i to site j in translation R.

OperationResult, SetupResult, ValidationResult, SetupReport, and RunManifest carry diagnostics, output inventory, hashes, status, and provenance without requiring a scheduler or database. ExchangePair is the canonical exchange-pair record used by job generation and result parsing.

Hashing and filesystem primitives

The hashing helpers provide canonical JSON, ordinary content hashes, and scientific hashes. The path helpers create owned temporary/staging workspaces and perform atomic replacement; they are the basis of the non-destructive HT setup and campaign contracts.

Public API

Small, dependency-light data contracts used by HT services.

class rsutil.core.contracts.CoordinateConvention(value)

Bases: str, Enum

class rsutil.core.contracts.Diagnostic(severity: 'DiagnosticSeverity | str', code: 'ErrorCode | str', message: 'str', path: 'str | None' = None, details: 'Mapping[str, Any]'=<factory>)

Bases: object

class rsutil.core.contracts.DiagnosticSeverity(value)

Bases: str, Enum

class rsutil.core.contracts.ErrorCode(value)

Bases: str, Enum

class rsutil.core.contracts.ExchangePair(key: ~rsutil.core.contracts.PairKey, cartesian_displacement: tuple[float, float, float], distance: float, species_i: str, species_j: str, length_unit: str = 'unknown', label_i: str | None = None, label_j: str | None = None, cluster_index: int | None = None, shell: int | float | str | None = None, shell_metadata: ~typing.Mapping[str, ~typing.Any] = <factory>, provenance: ~typing.Mapping[str, ~typing.Any] = <factory>, rs_type_i: int | None = None, rs_type_j: int | None = None)

Bases: object

A canonical pair together with derived geometry and provenance.

property displacement: tuple[float, float, float]

Compatibility alias for the derived Cartesian displacement.

property pair_key: PairKey

Descriptive alias for the canonical identity.

class rsutil.core.contracts.OperationResult(status: 'OperationStatus' = <OperationStatus.SUCCESS: 'success'>, diagnostics: 'tuple[Diagnostic, ...]'=(), stdout: 'str' = '', stderr: 'str' = '', provenance: 'Mapping[str, Any]'=<factory>)

Bases: object

class rsutil.core.contracts.OperationStatus(value)

Bases: str, Enum

class rsutil.core.contracts.PairKey(i: int, j: int, R: tuple[int, int, int])

Bases: object

Canonical periodic pair identity (site_i, site_j, lattice_R).

Site indices are zero-based and refer to the stable ordering of the reference-cell RSStructure. R is an integer translation in the reference lattice basis; it is never a Cartesian displacement. One-based indices are accepted only at explicit RS/Fortran serialization boundaries via from_one_based() and to_one_based().

property as_tuple: tuple[int, int, tuple[int, int, int]]

Tuple form useful for deterministic sorting and dictionary keys.

classmethod from_one_based(i: int, j: int, R: Sequence[int]) → PairKey

Construct a canonical key from one-based RS/Fortran site indices.

property sort_key: tuple[int, int, int, int, int]

Stable lexicographic ordering key.

to_one_based() → tuple[int, int, tuple[int, int, int]]

Return (i, j, R) with one-based site indices for serialization.

class rsutil.core.contracts.RSStructure(lattice_vectors: tuple[tuple[float, float, float], ...], length_unit: str, sites: tuple[~rsutil.core.contracts.StructureSite, ...], coordinate_convention: ~rsutil.core.contracts.CoordinateConvention | str = CoordinateConvention.CARTESIAN, pbc: tuple[bool, bool, bool] = (True, True, True), metadata: ~typing.Mapping[str, ~typing.Any] = <factory>)

Bases: object

Canonical RS structure independent of ASE and pymatgen.

classmethod from_ase(atoms: Any) → RSStructure

Convert an ASE Atoms object through the optional adapter.

The import is deliberately local: importing rsutil.core does not require ASE to be installed. The implementation lives in rsutil.ase so the core data model remains ASE-independent.

to_ase() → Any

Convert this structure through the optional ASE adapter.

class rsutil.core.contracts.RunManifest(schema_version: str = 'rsutil-run-v1', operation: str = 'setup', status: OperationStatus | str = OperationStatus.SUCCESS, input_hashes: Mapping[str, ~typing.Any]=<factory>, output_hashes: Mapping[str, ~typing.Any]=<factory>, normalized_setup_spec: Mapping[str, ~typing.Any]=<factory>, structure_hash: str | None = None, setup_identity_hash: str | None = None, software: Mapping[str, ~typing.Any]=<factory>, environment: Mapping[str, ~typing.Any]=<factory>, timestamps: Mapping[str, str]=<factory>, validation: Mapping[str, ~typing.Any]=<factory>, stochastic: Mapping[str, ~typing.Any]=<factory>)

Bases: object

Versioned, machine-readable provenance for one scientific operation.

class rsutil.core.contracts.SetupReport(schema_version: str = 'rsutil-setup-report-v1', result: SetupResult = <factory>, manifest: RunManifest = <factory>)

Bases: object

Versioned report envelope; the core result remains a typed object.

class rsutil.core.contracts.SetupResult(status: 'OperationStatus' = <OperationStatus.SUCCESS: 'success'>, diagnostics: 'tuple[Diagnostic, ...]'=(), stdout: 'str' = '', stderr: 'str' = '', provenance: 'Mapping[str, Any]'=<factory>, candidate_files: 'tuple[str, ...]'=(), semantic_validation: 'ValidationResult | None' = None, sphere_outputs: 'Mapping[str, str]'=<factory>)

Bases: OperationResult

class rsutil.core.contracts.SetupSpec(cluster_type: str = 'periodic', empty_spheres: bool = False, min_empty_radius: float = 1.2, max_empty_radius: float = 2.5, lmx: int = 2, rec_method: str = 'block', rec_steps: int = 20, lattice_dist: float = 0.0, basis_dist: float = 0.0, alat_scale: float = 1.0, seed: int | None = None, mode_2d: bool = False, z_iso_factor: float | None = None, supercell: tuple[int, int, int] = (1, 1, 1), sqs: str | None = None, sqs_shells: int = 3, sqs_steps: int = 5000, sqs_seed: int | None = None, preset: str | None = None)

Bases: object

Scientific setup parameters exposed by the legacy -S workflow.

property sqs_spec: str | None

Compatibility spelling for the SQS composition specification.

rsutil.core.contracts.Site

alias of StructureSite

class rsutil.core.contracts.StructureSite(index: int, position: tuple[float, float, float], element: str, atomic_number: int | None = None, rs_label: str | None = None, rs_type: str | None = None, metadata: ~typing.Mapping[str, ~typing.Any] = <factory>, rs_type_index: int | None = None)

Bases: object

One site in the canonical, stable ordering of an RSStructure.

Site indices are zero-based and must be contiguous in RSStructure. element is the chemical identity; RS-specific labels/types are kept separately so labels such as Fe1 do not become chemical symbols.

class rsutil.core.contracts.ValidationResult(valid: 'bool', diagnostics: 'tuple[Diagnostic, ...]' = (), schema_version: 'str' = 'rsutil-validation-v1')

Bases: object

Deterministic content and specification hashing helpers.

rsutil.core.hashing.canonical_json(value: Any, *, scientific: bool = False) → str

Serialize a value deterministically for storage or hashing.

Mapping insertion order does not affect the result. Set-like values are intentionally unsupported because their order is not a scientific contract; callers should provide an ordered sequence instead.

rsutil.core.hashing.file_hash(path: str | Path, *, algorithm: str = 'sha256', chunk_size: int = 1048576) → str

Hash file content without incorporating path metadata or timestamps.

rsutil.core.hashing.hash_file(path: str | Path, *, algorithm: str = 'sha256', chunk_size: int = 1048576) → str

Hash file content without incorporating path metadata or timestamps.

rsutil.core.hashing.hash_json(value: Any, *, algorithm: str = 'sha256') → str

Return a hash of canonical JSON, including all supplied fields.

rsutil.core.hashing.scientific_hash(value: Any, *, algorithm: str = 'sha256') → str

Return a deterministic identity hash for scientific specifications.

Provenance timestamps are excluded recursively. They belong in run records, not in scientific identity.

rsutil.core.hashing.specification_hash(value: Any, *, algorithm: str = 'sha256') → str

Return a deterministic identity hash for scientific specifications.

Provenance timestamps are excluded recursively. They belong in run records, not in scientific identity.

Explicit, reusable filesystem and workspace primitives.

These helpers never change the caller’s process working directory. Legacy fixed-filename programs can be run by callers with subprocess and cwd=workspace.path while the rest of the application keeps explicit paths.

class rsutil.core.paths.Workspace(path: Path, *, keep: bool = False, owned: bool = True)

Bases: object

An owned temporary directory that is cleaned up on context exit.

child(name: str) → Path

Return a resolved child path and reject lexical/symlink escapes.

cleanup() → None

Remove this workspace, including after an exception.

Only the directory created by Workspace.create is removable by this object. Cleanup is idempotent and can be disabled with keep=True for debugging.

classmethod create(parent: str | PathLike[str] | None = None, *, prefix: str = 'rsutil-', same_filesystem_as: str | PathLike[str] | None = None, keep: bool = False) → Workspace

Create an isolated directory, optionally beside a destination.

same_filesystem_as is useful for staging a candidate before an atomic replacement. The temporary directory is created in the destination’s parent directory, so os.replace can remain atomic.

rsutil.core.paths.as_path(path: str | PathLike[str]) → Path

Return a Path without consulting or changing the process CWD.

rsutil.core.paths.atomic_replace(source: str | PathLike[str], destination: str | PathLike[str], *, overwrite: bool = True) → Path

Atomically replace a destination with a staged file on the same filesystem.

rsutil.core.paths.isolated_workspace(parent: str | PathLike[str] | None = None, *, prefix: str = 'rsutil-', same_filesystem_as: str | PathLike[str] | None = None) → Iterator[Path]

Yield an isolated temporary workspace and always clean it up.

rsutil.core.paths.stage_file(source: str | PathLike[str], workspace: str | PathLike[str], *, name: str | None = None) → Path

Copy one explicit source file into a workspace and return its path.

rsutil.core.paths.stage_files(sources: Iterable[str | PathLike[str]], workspace: str | PathLike[str]) → tuple[Path, ...]

Copy explicit source files into a workspace, preserving file names.

rsutil.core.paths.staging_workspace(destination: str | PathLike[str], *, prefix: str = 'rsutil-stage-')

Return a context manager for a same-filesystem staging directory.

rsutil.core.paths.temporary_workspace(parent: str | PathLike[str] | None = None, *, prefix: str = 'rsutil-', same_filesystem_as: str | PathLike[str] | None = None) → Iterator[Path]

Yield an isolated temporary workspace and always clean it up.

Exceptions raised by the reusable RS-utils core.

exception rsutil.core.errors.ExchangeError

Bases: RsutilError

An exchange mapping or exchange operation failed.

exception rsutil.core.errors.ParserError

Bases: RsutilError

An input or result file could not be parsed unambiguously.

exception rsutil.core.errors.RsutilError

Bases: Exception

Base class for expected RS-utils operation errors.

exception rsutil.core.errors.SetupError

Bases: RsutilError

A setup operation could not be completed.

exception rsutil.core.errors.ValidationError

Bases: RsutilError, ValueError

An input or typed contract failed validation.