Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Portable calculation bundles

The water tutorial saves and verifies an HF reference for MP2. The hydroxyl and benzene tutorials export orbitals from a bundle.

Examples in this chapter that use samples/ or tests/data/ require a cloned repository and should be run from its root. Release binaries do not include those files; the first-calculation guide shows how to create local inputs and obtain a basis. Commands using rustiq assume the executable is installed or available on PATH. From a source checkout without installation, use the cargo run --locked -- prefix described in the CLI reference.

A .rustiq bundle is a portable snapshot of RustiQ calculation inputs and optional scientific artifacts, including atomic-orbital electron-repulsion integrals (AO ERIs) and converged Hartree–Fock orbitals. Use it to rerun a calculation, reuse compatible AO ERIs in a new calculation, or run MP2 from a saved RHF or UHF reference.

Create and inspect a bundle

Release binary

First follow the local-input workflow in the first-calculation guide. Use the calculation.toml generated by rustiq init and its downloaded or imported STO-3G basis; no additional basis setup is needed. Choose a destination that does not already exist.

rustiq run calculation.toml --artifact h2.rustiq
rustiq artifact inspect h2.rustiq
rustiq artifact verify h2.rustiq
rustiq run h2.rustiq

Tip

With an online-enabled build and network access, rustiq run calculation.toml --artifact h2.rustiq --auto-download fetches STO-3G if it is missing during bundle creation. Direct reruns of an existing bundle need no basis download.

Source checkout

Alternatively, from a cloned repository, make the checked-in STO-3G basis available, then run the H₂ sample and write a bundle to the current directory:

The runfile used here is the checked-in H₂ sample. Run these commands from the repository root:

[basis]
name = "sto-3g"

[molecule]
geometry = "../molecule.xyz"

[method.hf.guess]
type = "CoreHamiltonian"
cargo run --locked -- basis import tests/data/sto-3g.json
cargo run --locked -- run samples/h2/sto-3g/calculation.toml --artifact h2.rustiq

--artifact writes the current calculation collection as a new bundle, independently of text or JSON result output. For a Nickel study, the bundle contains one entry for each requested calculation. Each entry stores AO ERIs and, when HF converges, the HF orbitals and convergence metadata. This also applies to the HF reference of a successful MP2 run.

Inspect a bundle without the original runfile, geometry file, or basis store:

rustiq artifact inspect h2.rustiq
rustiq artifact inspect h2.rustiq --format json

Inspection displays canonical requested and resolved calculation snapshots, producer information, artifact representations, and captured source names and sizes. Requested values may differ from resolved values: for example, an Auto HF method can resolve to RHF, and requested Angstrom coordinates appear as resolved Bohr coordinates. Text output syntax-highlights the canonical TOML and XYZ when color is enabled by --color or RUSTIQ_COLOR; use --color never for plain text. The optional JSON payloads_verified field is false: inspection validates the archive index, provenance, scientific snapshots and declared artifact sizes, but does not hash or decode numerical payloads. Use artifact verify to check supported payloads eagerly; otherwise, execution checks a payload when its scientific stage selects and reads it. Inspection is structural, not a calculation or an independent scientific validation.

Use artifact verify to eagerly read and validate every supported numerical payload in the bundle:

rustiq artifact verify h2.rustiq

The command checks supported ao_eri and converged_hf payloads without materializing integral or orbital arrays. AO ERI checks cover payload hashes, NPY encoding, dimensions, and consistency with the declared AO basis. HF checks cover metadata, referenced payload integrity, array shapes, occupations, finite values, and context identity. HF verification supports the rustiq-converged-hf-orbitals-v1 representation. Verification limits NPY headers to 64 KiB.

The summary on stdout counts calculations and logical artifacts, rather than individual files. Diagnostics go to stderr. For the H₂ bundle created above:

Verification successful
  Calculations: 1
  Verified:     2
  Failed:       0
  Skipped:      0
  Calculation 0, artifact ao_eri (rustiq-compact-eri-v1): Valid
  Calculation 0, artifact converged_hf (rustiq-converged-hf-orbitals-v1): Valid

Text is the default and can be selected explicitly with --format text. Use rustiq artifact verify h2.rustiq --format json for a single versioned JSON summary on stdout. It includes the counts and an entry for every declared artifact with its calculation index, name, representation, and status. The statuses are valid, invalid, unknown_artifact, and unsupported_representation. Invalid entries include an errors array with the error chain. Diagnostics remain on stderr and --strict applies to either output format.

The first line distinguishes three outcomes:

StatusMeaning
Verification successfulEvery declared artifact passed; none failed or were skipped.
Verification incompleteNo supported artifact failed, but at least one artifact was skipped.
Verification failedAt least one supported artifact failed, regardless of skips.

Unknown artifact names and known artifacts with unsupported representations are skipped with warnings. Their payloads are not checked: an older reader’s inability to interpret a representation is not evidence of corruption. Supported artifacts with invalid metadata or payloads fail verification. A missing payload or a size mismatch is reported for that artifact. Independent failures are collected and reported together, with a summary after traversal. A fatal archive error that prevents opening or traversal can stop without a summary. Calculation indices in diagnostics are zero-based.

By default, exit code 0 means all supported artifacts passed; unsupported artifacts may still have been skipped. Use rustiq artifact verify PATH --strict to require exhaustive verification: skips without failures return 5, reported as a warning rather than evidence of corruption. Any supported artifact failure or fatal archive error returns 1 in either mode. Failures take precedence over skips. Strict mode returns 0 when every artifact passes.

A bundle without numerical artifacts returns 0 in either mode, with all three artifact counters at zero and an explicit message: No numerical artifacts declared; no numerical payload was verified.

Verification does not run the calculation or independently establish scientific correctness, physical validity, orbital orthonormality, or adequacy of the method and basis. Successful verification means the supported stored data passed its reader’s integrity and validation checks.

Run MP2 from saved Hartree–Fock

Create a bundle as shown above. From the repository root, use the checked-in method configuration. With a release binary, save these settings to postscf.toml and pass that path instead of the sample path.

[method.mp2]
frozen_orbitals = 0
memory_limit = "1 GiB"
rustiq run h2.rustiq --post-scf samples/h2/sto-3g/postscf.toml
rustiq run h2.rustiq --post-scf samples/h2/sto-3g/postscf.toml --calculation 0 --method mp2 --format json

From the directory where you saved postscf.toml and h2.rustiq, use:

rustiq run h2.rustiq --post-scf postscf.toml
rustiq run h2.rustiq --post-scf postscf.toml --format json

These commands evaluate the saved H₂ reference. The text report shows the MP2 correlation, electronic and total energies in Hartree. The total includes nuclear repulsion. See MP2 for the frozen-orbital convention and what the workspace memory limit covers.

For a study bundle, the default is to run every configured method on every calculation in manifest order. Use --calculation 2 to select the third entry, or repeat --method METHOD to select several configured methods when available. MP2 is currently the only supported method. The configuration contains only Post-HF method tables. Geometry, basis and HF settings come from the bundle, so the original geometry and basis files are unnecessary.

Each calculation uses one restored converged reference and its stored AO ERIs for the requested methods. Restoration can rebuild one-electron quantities. It does not run SCF or reconstruct AO ERIs. An unfinished SCF calculation cannot be restarted this way. A plain rustiq run h2.rustiq starts a fresh SCF run using the archived inputs.

When a calculation and method pair lacks a usable reference or prerequisite, RustiQ warns on stderr with its original zero-based calculation index and method name, then continues. A campaign with at least one success and only skips otherwise exits with code 0. If nothing succeeds it exits with code 1. A failed execution or a corrupt archived payload needed by a selected method is an error. If other pairs succeed, the exit code is 4 and the successful results are kept. JSON includes each pair’s status and summary counts, even when a completed campaign exits with an error.

To save the combined request in a new bundle, run:

rustiq run h2.rustiq --post-scf samples/h2/sto-3g/postscf.toml --artifact h2-mp2.rustiq

The output contains successful calculations in input manifest order. Each entry combines the archived HF inputs and the applied MP2 settings in its requested snapshot. This snapshot matches an equivalent direct Nickel study, including normalized defaults. The output carries the archived HF solution, AO ERIs, and source provenance, including the post-SCF TOML. Publication copies only the artifacts required by MP2 and checks their integrity. MP2 energies are available in the campaign report only.

To map exported entries back to their source indices, keep the JSON campaign report. Filter its calculations to entries with at least one successful method. The remaining source_index values map in order to exported entries starting at index zero. A future format revision could record that mapping in the bundle itself. Existing destinations are rejected, and a campaign with no successes leaves no output bundle. The source bundle stays in read-only use throughout the campaign.

Rerun a saved calculation

Run a .rustiq bundle directly to reconstruct and execute its archived calculation settings, without the original runfile, geometry file, or basis store:

rustiq run h2.rustiq
rustiq run h2.rustiq --format json --pretty --color never

For a multi-calculation bundle, RustiQ reruns every entry in manifest order and reports a batch, like a multi-entry Nickel study. This is a fresh calculation: RustiQ restores the resolved scientific inputs and reuses compatible AO ERIs when present; otherwise it recomputes them. A corrupt compatible AO ERI payload causes an execution error. It then runs HF again and MP2 again when requested. It does not restore orbitals, density matrices, DIIS history, or prior results, so this command does not resume an SCF trajectory. A saved random seed is restored as an input; it does not guarantee bitwise-identical results across software versions or platforms.

To use different settings, supply a TOML or Nickel input and use --reuse instead. A direct archive rerun cannot be combined with --reuse, --artifact, --cache-dir, --auto-download, or --no-auto-download. With --format json, the rerun uses the normal single-calculation or batch result schema and omits the artifacts reuse-decision array because the bundle is the implicit artifact source. The source bundle remains unchanged; direct reruns do not use the local AO ERI cache or download basis sets.

Reuse AO ERIs in a new calculation

This workflow needs a TOML or Nickel input, its geometry, and an available basis. --reuse does not run the calculation saved in the bundle or restore its captured source files. Instead, RustiQ prepares the supplied input, checks the bundle for compatible AO ERIs, and runs HF again; it also runs MP2 again if the new input requests MP2. The archive itself supplies reusable artifacts and remains read-only.

For the release-binary workflow, use the local calculation.toml created in the first-calculation guide. Keep its downloaded basis available for this new run; its geometry path resolves beside calculation.toml:

rustiq run calculation.toml --reuse h2.rustiq --format json --pretty --color never

From a source checkout, the equivalent command uses the checked-in sample:

cargo run --locked -- run samples/h2/sto-3g/calculation.toml --reuse h2.rustiq --format json --pretty --color never

When a runfile is executed with --reuse or --artifact, its JSON result includes an artifacts entry. A reused AO ERI is reported like this:

{
  "artifacts": [
    {
      "name": "ao_eri",
      "decision": "reused",
      "origin": "archive",
      "source_index": 0
    }
  ]
}

decision says whether the bundle supplied a compatible artifact; the CLI reports reused, missing, or incompatible. origin says where the ERIs actually came from: archive, an enabled local cache, or fresh computation. For example, decision: incompatible with origin: cache means no bundle entry matched but an enabled local cache supplied the ERIs. When an archive entry is selected, source_index is its zero-based position in that bundle. In a batch, each result reports its own selection.

The reuse order is:

  1. First compatible AO ERI in the archive’s manifest order.
  2. Matching entry in the enabled local AO ERI cache.
  3. Recompute the AO ERIs.

The local-cache step is used only when [cache].enabled = true in the runfile. --cache-dir selects the cache location but does not enable caching; see the configuration guide for the input setting.

The archive remains read-only during reuse. To publish a new snapshot from the calculation, provide a new destination. For the release-binary workflow:

rustiq run calculation.toml --reuse h2.rustiq --artifact h2-updated.rustiq

For a source checkout, use the sample path:

cargo run --locked -- run samples/h2/sto-3g/calculation.toml --reuse h2.rustiq --artifact h2-updated.rustiq

What can be reused?

AO ERIs are reusable when the effective integral inputs match. RustiQ checks the ordered atomic numbers and nuclear coordinates in Bohr, effective AO basis functions, Schwarz screening setting, and integral representation and computation versions. A matching basis-set label or atom count alone is not enough. HF method and convergence settings, and whether MP2 is requested, do not change AO ERI compatibility. The persistence specification defines the complete identity.

Change to the new inputAO ERI compatibility
HF method, initial guess, or SCF convergence limitCan remain compatible; HF runs again with the new settings.
Add or change MP2 settingsCan remain compatible; MP2 runs again from the new HF result.
Geometry, effective AO basis, or Schwarz screeningIncompatible; RustiQ checks the local cache, then recomputes if needed.

CLI-created bundles store scientific input snapshots and optional AO ERIs. They capture converged HF orbitals when available. Save the result JSON separately when reported results matter. Neither API stores density matrices, DIIS history, or MP2 results. Captured input and geometry bytes are provenance for inspection; they do not affect compatibility, and Nickel imports are not captured recursively. The same reconstruction is available to Rust callers; see the Rust API examples in the persistence specification.

Converged HF orbitals through Rust

The library exposes ConvergedHfArtifact through RustiQData::set and get. ConvergedHf::from_solution(&solution) copies orbital data from a converged AnyHfSolution, retaining its originating calculation identity and no AO ERIs. The entry created by RustiQData::from_calculation(&prepared) must match that identity. RustiQBundle reads and writes these entries alongside existing AO ERIs; older V1 archives without HF remain readable.

As with AO ERIs, set::<ConvergedHfArtifact>(&value) stages the artifact on disk immediately. Cloning an entry shares its stored payloads; replacing the artifact in one clone does not affect the others. Each get::<ConvergedHfArtifact>() reads and validates the payload again and returns an independently owned value. ArtifactRef::new::<ConvergedHfArtifact>(&value) also supports direct borrowed publication without staging. Republishing stored HF data streams its NPY files without retaining decoded orbital arrays.

The only supported HF representation label is rustiq-converged-hf-orbitals-v1.

Orbital arrays are stored as NumPy-compatible NPY files. For RHF, each calculation entry contains:

orbitals/
├── converged-hf.json
├── coefficients.npy
└── energies.npy

For UHF, the two spin channels have separate directories:

orbitals/
├── converged-hf.json
├── coefficients/
│   ├── alpha.npy
│   └── beta.npy
└── energies/
    ├── alpha.npy
    └── beta.npy

These paths are relative to calculations/<id>/ inside the bundle, alongside calculation.json, request.json, and optional arrays/integrals/ao-eri.npy. persistence::validate_matching_npy_shapes(alpha_reader, beta_reader) compares the ranks and axis lengths in two NPY headers before loading values. This header-only check does not validate dtype, values, or payload integrity.

The JSON metadata references each array by its fixed path, byte size, and SHA-256 digest. Typed access checks every referenced payload. NPY arrays have no fixed byte-size ceiling; readers check their dimensions against the HF record.

The read-only HfOrbitals enum carries distinct RhfOrbitals and UhfOrbitals types for shared spatial orbitals and separate alpha/beta channels. UhfOrbitals::channels uses Spin<C> and its shared payload save/load operations. Their serialized descriptor layout is unchanged; only RHF and UHF are supported. Coefficients use column-major storage: rows retain the original AO order, columns match orbital energies in Hartree, and occupied orbitals form a prefix. The number of columns is the retained overlap rank, which can be smaller than the AO row count. RHF occupied spatial orbitals carry two electrons each; UHF channels carry one electron per occupied orbital.

Run the offline example from a checkout:

cargo run -p rustiq-chem-core --example persist_hf --no-default-features

The example writes into a temporary directory and verifies the restored RHF coefficients and MP2 correlation energy. The API checks context identity, dimensions, occupations, finite values, convergence metadata, and payload integrity on each typed access. These checks do not independently establish physical validity or orbital orthonormality. hf_is_compatible checks context compatibility without verifying the payload. Reading the artifact alone does not construct an executable solution. To restore one for MP2, the same calculation entry must also contain compatible AO ERIs. In Rust, RustiQData::check::<A>() checks one typed artifact and returns Ok(false) when it is absent. RustiQBundle::check() returns an ArtifactCheckSummary with the outcome of every declared artifact.

The CLI artifact verify uses RustiQBundle::check_archive() to verify the archive and report individual artifact failures.

Restoring a solution for MP2

The public RestoreFromRustiQ trait constructs an owned object from a RustiQData entry. RustiQData::restore::<T>() delegates to that trait. Converged RhfSolution, UhfSolution, and AnyHfSolution implement it:

use rustiq_core::{persistence::RustiQData, prelude::*};

fn main() -> Result<(), Box<dyn std::error::Error>> {
let data = RustiQData::open("calculation.rustiq")?;
let hf: RhfSolution = data.restore()?;
// Equivalent: RhfSolution::restore_from_rustiq(&data)?
let mp2 = hf.mp2(Mp2Config::default())?;
println!("MP2 correlation energy: {} Hartree", mp2.correlation_energy);
Ok(())
}

Use UhfSolution for an unrestricted calculation. To let the archive select RHF or UHF, use the resume_mp2 example. From the repository root, create a single calculation HF bundle, then run the example with two new file paths:

cargo run -- run samples/h2/sto-3g/calculation.toml --artifact h2-hf.rustiq
cargo run -p rustiq-chem-core --no-default-features --example resume_mp2 -- h2-hf.rustiq h2-mp2.rustiq

The example prints the HF reference and both MP2 energies in Hartree. It writes a new bundle with the applied MP2 settings, the archived HF reference, the AO integrals, and the source provenance. RustiQBundle::with_calculations carries the input bundle’s provenance into the new bundle.

//! Run MP2 from saved HF orbitals and write a portable snapshot of the applied settings.
use rustiq_core::{
    config::Mp2Config,
    persistence::{PostScfSession, RustiQBundle},
};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut args = std::env::args_os().skip(1);
    let (Some(input), Some(output), None) = (args.next(), args.next(), args.next()) else {
        return Err("usage: resume_mp2 <input.rustiq> <output.rustiq>".into());
    };

    let bundle = RustiQBundle::open_for_restore(input)?;
    let [entry] = bundle.calculations() else {
        return Err("expected a bundle containing one calculation".into());
    };

    let mut session = PostScfSession::new(entry);
    let mp2 = session.run(&Mp2Config::default())?;
    println!("HF reference: {:?}", mp2.reference);
    println!(
        "MP2 correlation energy: {:.12} Eh",
        mp2.result.correlation_energy
    );
    println!(
        "MP2 total energy: {:.12} Eh",
        mp2.result.electronic_energy + mp2.nuclear_repulsion_energy
    );

    let mut resumed = bundle.with_calculations(vec![mp2.update_snapshot(entry.clone())?])?;
    resumed.write(output)?;
    Ok(())
}

PostScfMethod gives each method a reference description, a converged solution type, and its own output and error types. Executor selection uses the description alone, so a method can decline a reference before the session loads scientific data. A method can also choose an execution function specific to the reference it accepts.

PostScfSession uses the bundle’s HF metadata and restores a converged AnyHfSolution on the first compatible request. It reuses that solution or the restoration error on later compatible requests. Method execution errors leave the shared reference available. A new HF-based method implements PostScfMethod with ResolvedHfMethod and AnyHfSolution, which automatically satisfies the session’s PostHfMethod bound. MP2 requires no changes.

A future reference can use its own description and converged solution type with PostScfMethod. Running that reference from an archive would also require persisted reference metadata, restoration and validation for its scientific data, and a caller that connects restoration to executor selection. SCF iteration takes place upstream of ScfSolution, the generic output model. The CLI uses the same session and handles method selection, reporting and bundle publication.

Restoration validates the HF artifact, its context, and the compatible AO ERI payload. Missing, unsupported, incompatible, or corrupt required artifacts are errors; requesting RHF from a UHF entry, or vice versa, also returns an error. It does not run SCF or compute missing ERIs. It rebuilds the density from the occupied orbitals and recomputes the kinetic and nuclear-attraction integrals to reconstruct the energy decomposition. The electron-repulsion component is the stored electronic energy minus the reconstructed kinetic and nuclear-attraction components. Because final orbital and SCF densities can differ within the convergence tolerance, these components can differ from the original summary. Original HF energies and convergence diagnostics are retained; execution timings are not persisted and are zero in the restored summary. These checks trust the persisted convergence record; they do not independently certify orbital canonicality or physical validity.

The restored solution owns its scientific data and remains usable after the bundle is closed. Restoration does not modify the source. The offline persist_hf example above saves both artifacts, reopens the bundle, restores RHF, and compares the resulting MP2 correlation energy with the original solution within 1e-12 Eh. It uses a temporary directory that is removed on exit, closes the bundle before MP2, and prints HF total, MP2 correlation, and MP2 total energies (HF total plus MP2 correlation). This checks the persistence round trip for the bundled H2/STO-3G case, rather than independent scientific accuracy. The CLI can restore stored HF explicitly with --post-scf. SCF and DIIS restart remain future work.

Export orbitals to Molden

After saving a converged HF calculation to h2.rustiq, export it for use in software that reads the Molden format.

rustiq artifact export h2.rustiq --format molden --calculation 0 -o h2.molden

Running from a repository checkout, use cargo run --locked -- in place of rustiq. The index is zero-based in manifest order, as displayed by artifact inspect. You can omit it for a single-calculation bundle. For a bundle with multiple entries, choose one index per exported file. With -o FILE or --output FILE, RustiQ creates the destination and refuses to overwrite an existing file. Add --force to replace it. Omit the output option to write to standard output. The destination cannot point to the input bundle. File output is written to a temporary file beside the destination and replaces the destination atomically after writing succeeds.

The exporter uses the saved orbitals, resolved geometry, and effective AO basis. It does not need the original basis file or AO ERIs, and it leaves the input bundle read-only. If the saved HF orbitals are missing or invalid, or the basis cannot be represented, RustiQ reports an error before opening the output file. Coordinates are in Bohr and orbital energies are in Hartree. Restricted HF writes one set of spatial orbitals with occupation 2 for each occupied orbital. Unrestricted HF writes alpha and beta orbitals, each with occupation 1 for occupied orbitals. In both cases, virtual orbitals have occupation 0, and the export includes only orbital columns retained by HF.

Supported shells are Cartesian s through g and real spherical d. The exporter checks that the stored AO components can be grouped into contracted shells, converts primitive coefficients to the Molden convention, and reorders the MO coefficient rows to match. It rejects mixed spherical and Cartesian representations of d and higher shells, as well as functions it cannot associate with distinct atomic centers. Orbital symmetry labels are written as A because the bundle does not store point-group assignments. The V1 bundle stores normalized AO components. Export therefore reconstructs contracted shells from the AO order and primitive patterns. Explicit shell metadata could remove this inference in a future format revision.

Rust callers use the same exporter through data.export(ExportFormat::Molden)?.write_to(writer)?, with ExportFormat from rustiq_core::persistence. Call export to validate the selected RustiQData and load its saved orbitals, then call write_to to stream the result to any std::io::Write destination.

Publication and failures

--artifact publishes the current requested collection; it does not append to the source bundle. RustiQ replaces the explicit --reuse source when both options point to the same bundle. Pass --force to replace another existing destination. Post-SCF output requires a separate destination from the input bundle, even with --force.

Run outcomeBundle behavior
Every requested calculation produces a resultPublish the current collection.
A preparation or execution error occursDo not publish; preserve any prior destination.
HF-only run reaches its iteration limitIts result can still publish the AO ERIs. A single HF run returns exit code 3; a batch with non-converged results and no execution errors publishes, then returns 3 if none converged or 4 if some succeeded. See the CLI exit-code contract.
MP2 was requested but HF did not convergeMP2 execution fails, so the collection is not published.

JSON for a completed calculation or batch may already have been written when a later publication error is reported. See the CLI reference for exact exit and publication behavior and the persistence V1 specification for the archive contract and the EZFIO comparison.

The generic SCF persistence entry point is ScfSolution<M, Converged>::to_artifact, available when the method descriptor implements PersistScf. Its associated Artifact selects the versioned storage contract and value type. Each method owns its context identity, conversion and artifact validation; the generic layer requires no common orbital layout, HF summary, or retained AO integrals. RHF and UHF descriptors implement this contract using ConvergedHfArtifact. ConvergedHf::from_solution is a runtime HF convenience adapter to the same path.

The generic NPY conversion handles owned nalgebra matrices with static or dynamic dimensions. Its expected shape is (rows, columns), and its writer preserves both axes in Fortran order. The slice writer used for HF energies emits (n,) instead.

Nalgebra Vector and RowVector types additionally accept one-dimensional NPY arrays (n,), taking their orientation from the target type. Two-dimensional input must match the requested orientation exactly. General matrices, including DMatrix with one row or column, always require an exact two-dimensional shape.