Skip to content

Programs and sessions

The protocol a program implements so qccompute can find, plan, place and run it, and the sessions callers use to evaluate one molecule at many geometries. A program registers one object (an instance) under the qccompute.programs entry point group. The protocols are structural and what a program returns for capabilities and plan may be a plain mapping, so a program without subprograms never imports qccompute. What programs share as data (Request, Accuracy, ProgramError, Frame) is in qcdata. Design: the program interface.

qccompute.testing.check_program(program, inputs) checks the contract (install qccompute[testing] to validate keywords against the program's JSON Schema), and qccompute.testing.toy is a complete example program (Lennard-Jones).

qccompute.program.Program

A program qccompute can run: the object registered under qccompute.programs.

Structural: a program implements these methods without importing qccompute.

Optional: numerics(spec) -> str, which changes whenever results for an unchanged input may change (see numerics_of); without it the version stands for it.

Attributes:

Name Type Description
name str

The program's name, as in ProgramInput.program.

version() -> str

The program's version.

Source code in src/qccompute/program.py
1066
1067
1068
def version(self) -> str:
    """The program's version."""
    ...

capabilities() -> Capabilities | Mapping[str, Any]

What the program can do and how it may be run (a mapping is validated).

Source code in src/qccompute/program.py
1070
1071
1072
def capabilities(self) -> Capabilities | Mapping[str, Any]:
    """What the program can do and how it may be run (a mapping is validated)."""
    ...

settings_schema(calctype: CalcType) -> dict[str, Any]

The JSON Schema of keywords (and of resolved.settings) for a calctype.

Every key carries x-unit, x-tier (common, expert), x-concern (model, approximation, convergence, algorithm, resource, output) and x-applies-to where they apply.

Source code in src/qccompute/program.py
1074
1075
1076
1077
1078
1079
1080
1081
def settings_schema(self, calctype: CalcType) -> dict[str, Any]:
    """The JSON Schema of ``keywords`` (and of ``resolved.settings``) for a calctype.

    Every key carries ``x-unit``, ``x-tier`` (common, expert), ``x-concern``
    (model, approximation, convergence, algorithm, resource, output) and
    ``x-applies-to`` where they apply.
    """
    ...

record_schema(calctype: CalcType) -> dict[str, Any]

The JSON Schema of ProgramOutput.record for a calctype.

Source code in src/qccompute/program.py
1083
1084
1085
def record_schema(self, calctype: CalcType) -> dict[str, Any]:
    """The JSON Schema of ``ProgramOutput.record`` for a calctype."""
    ...

plan(inp: ProgramInput) -> Plan | Mapping[str, Any]

Validate an input and resolve its settings without running it.

A mapping is validated as a Plan: resolved (a qcdata.Resolved), resources, warnings and the program's own record.

Raises:

Type Description
ProgramError

The input cannot run (kind input or unsupported), with a did-you-mean suggestion for unknown keys.

Source code in src/qccompute/program.py
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
def plan(self, inp: ProgramInput) -> Plan | Mapping[str, Any]:
    """Validate an input and resolve its settings without running it.

    A mapping is validated as a `Plan`: ``resolved`` (a `qcdata.Resolved`),
    ``resources``, ``warnings`` and the program's own ``record``.

    Raises:
        ProgramError: The input cannot run (kind ``input`` or ``unsupported``),
            with a did-you-mean suggestion for unknown keys.
    """
    ...

compute(inp: ProgramInput, ctx: RunContext | None = None) -> ProgramOutput[ProgramInput, Data]

Run a calculation.

Parameters:

Name Type Description Default
inp ProgramInput

The input.

required
ctx RunContext | None

The runner's grant and subprograms; a runner always passes one. None: a direct call, after which a program with subprograms returns qccompute.compute(inp).

None

Returns:

Type Description
ProgramOutput[ProgramInput, Data]

The successful output.

Raises:

Type Description
ProgramError

The calculation failed, with its partial results or its whole failed output (output).

Source code in src/qccompute/program.py
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
def compute(
    self, inp: ProgramInput, ctx: RunContext | None = None
) -> ProgramOutput[ProgramInput, Data]:
    """Run a calculation.

    Args:
        inp: The input.
        ctx: The runner's grant and subprograms; a runner always passes one. None:
            a direct call, after which a program with subprograms returns
            ``qccompute.compute(inp)``.

    Returns:
        The successful output.

    Raises:
        ProgramError: The calculation failed, with its partial results or its
            whole failed output (``output``).
    """
    ...

qccompute.program.SessionProgram

A program that keeps state between geometries (capabilities().sessions).

open_session(inp: ProgramInput, ctx: RunContext | None = None, calctypes: frozenset[CalcType] | None = None) -> Session

Open a session at the input's atoms and first geometry.

Usually return Session(inp, calctypes=calctypes, ctx=ctx): the program's own session class is the protocol object. calctypes are the calculation types the session may run (None: everything the method supports; see session_calctypes). The keywords are checked against them: a setting that applies to none of them is an input error, and so is a later request of another type.

Raises:

Type Description
ProgramError

The input cannot run (kind input or unsupported).

Source code in src/qccompute/program.py
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
def open_session(
    self,
    inp: ProgramInput,
    ctx: RunContext | None = None,
    calctypes: frozenset[CalcType] | None = None,
) -> Session:
    """Open a session at the input's atoms and first geometry.

    Usually ``return Session(inp, calctypes=calctypes, ctx=ctx)``: the program's
    own session class is the protocol object. ``calctypes`` are the calculation
    types the session may run (None: everything the method supports; see
    `session_calctypes`). The keywords are checked against them: a setting that
    applies to none of them is an input error, and so is a later request of
    another type.

    Raises:
        ProgramError: The input cannot run (kind ``input`` or ``unsupported``).
    """
    ...

qccompute.program.BatchProgram

A program that evaluates many inputs at once (capabilities().batches).

compute_batch(inputs: Sequence[ProgramInput], ctx: RunContext | None = None) -> list[ProgramOutput[ProgramInput, Data]]

Run many calculations together.

Under a runner, ctx is the batch's: the whole list in one call, with the list's thread count (the sum of its inputs' shares) and the most GPUs any of them asks for. The program divides the threads among the inputs (one each to N one-thread searches run side by side), and records in each output's execution.threads what that input used; left unset, the runner records the input's own part. Likewise execution.wall_time: each input's own where the program can tell (a lockstep batch knows when each task finished), else left unset, and the runner records the whole batch's. The batch's wall time is always in timings["batch"] (s).

Returns:

Type Description
list[ProgramOutput[ProgramInput, Data]]

One output per input, in order; a failed calculation is a failed output

list[ProgramOutput[ProgramInput, Data]]

in its place (ProgramOutput.failure), and so is an input the program

list[ProgramOutput[ProgramInput, Data]]

refuses (kind input), so the other inputs still run. The runner

list[ProgramOutput[ProgramInput, Data]]

raises the failures together, or returns them in place.

Source code in src/qccompute/program.py
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
def compute_batch(
    self, inputs: Sequence[ProgramInput], ctx: RunContext | None = None
) -> list[ProgramOutput[ProgramInput, Data]]:
    """Run many calculations together.

    Under a runner, ``ctx`` is the batch's: the whole list in one call, with the
    list's thread count (the sum of its inputs' shares) and the most GPUs any of
    them asks for. The program divides the threads among the inputs (one each to
    N one-thread searches run side by side), and records in each output's
    ``execution.threads`` what that input used; left unset, the runner records the
    input's own part. Likewise ``execution.wall_time``: each input's own where the program
    can tell (a lockstep batch knows when each task finished), else left unset,
    and the runner records the whole batch's. The batch's wall time is always in
    ``timings["batch"]`` (s).

    Returns:
        One output per input, in order; a failed calculation is a failed output
        in its place (``ProgramOutput.failure``), and so is an input the program
        refuses (kind ``input``), so the other inputs still run. The runner
        raises the failures together, or returns them in place.
    """
    ...

qccompute.program.Session

The same program and molecule at many geometries, warm-started.

Opened from a ProgramInput (mychem.Session(inp) directly, or SessionProgram.open_session under qccompute). The input pins the atoms, charge, multiplicity, model and keywords (method, basis, grids, precision) for the session's lifetime, so all its evaluations lie on one potential energy surface; anything else needs a new session. A request may vary only how tightly it converges (qcdata.Request.accuracy), which history it continues (lineage, seed, commit) and which optional outputs it adds (outputs). Contract:

  • Results are Frame objects: the structure evaluated, its SinglePointData, and the request's own warnings and record (an SCF escalation, a stability probe, a fallback), with the shared warm_start at the top of the record. program and program_version are the session's.
  • Lineages are any JSON value, keyed by qcdata.lineage_key; None is the default lineage. A lineage's history is its last committed success.
  • A failed request raises ProgramError (with its failed frame) from compute; compute_many runs every request and then raises qcdata.ProgramErrors holding the failures and every frame in order. The session stays usable and the lineage's history is untouched: a caller may retry a smaller step.
  • A hessian request returns the energy and gradient too.

Attributes:

Name Type Description
program str

The program's name.

program_version str

The program's version.

program: str property

The program's name.

program_version: str property

The program's version.

input_data: ProgramInput property

The input the session was opened with: its atoms, settings and defaults.

compute(positions: np.ndarray | None = None, calctype: CalcType | str | None = None, *, accuracy: Accuracy | float | None = None, lineage: Lineage = None, outputs: Iterable[str] = (), seed: Iterable[Lineage] = (), commit: bool = True) -> Frame

Evaluate one geometry.

Parameters:

Name Type Description Default
positions ndarray | None

Atomic positions (bohr), n_atoms x 3; None: the input's own.

None
calctype CalcType | str | None

energy, gradient or hessian; None: the input's.

None
accuracy Accuracy | float | None

See qcdata.Request.accuracy.

None
lineage Lineage

See qcdata.Request.lineage.

None
outputs Iterable[str]

See qcdata.Request.outputs.

()
seed Iterable[Lineage]

See qcdata.Request.seed.

()
commit bool

See qcdata.Request.commit.

True

Returns:

Type Description
Frame

The evaluation, successful.

Raises:

Type Description
ProgramError

The evaluation failed; the session stays usable.

Source code in src/qccompute/program.py
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
def compute(
    self,
    positions: np.ndarray | None = None,
    calctype: CalcType | str | None = None,
    *,
    accuracy: Accuracy | float | None = None,
    lineage: Lineage = None,
    outputs: Iterable[str] = (),
    seed: Iterable[Lineage] = (),
    commit: bool = True,
) -> Frame:
    """Evaluate one geometry.

    Args:
        positions: Atomic positions (bohr), n_atoms x 3; None: the input's own.
        calctype: ``energy``, ``gradient`` or ``hessian``; None: the input's.
        accuracy: See `qcdata.Request.accuracy`.
        lineage: See `qcdata.Request.lineage`.
        outputs: See `qcdata.Request.outputs`.
        seed: See `qcdata.Request.seed`.
        commit: See `qcdata.Request.commit`.

    Returns:
        The evaluation, successful.

    Raises:
        ProgramError: The evaluation failed; the session stays usable.
    """
    ...

compute_many(requests: Sequence[Request]) -> list[Frame]

Evaluate many geometries (finite differences, path images, IRC branches).

Requests of one lineage run in list order, each reading the lineage's history as it stands at its place (qcdata.Request.commit); requests of different lineages may run concurrently. The requests share the session's thread count (ctx.threads when it opened): a program that runs several at once gives each the count divided by those it runs, at least 1. The results equal running the requests one at a time, each with the thread count it got.

Every request runs, failed ones included; then, if any failed, the call raises one qcdata.ProgramErrors group holding each failure's qcdata.ProgramError and every frame in request order (failed frames in place).

Parameters:

Name Type Description Default
requests Sequence[Request]

The evaluations.

required

Returns:

Type Description
list[Frame]

One frame per request, in order, all successful.

Raises:

Type Description
ProgramErrors

Some requests failed; results holds every frame.

Source code in src/qccompute/program.py
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
def compute_many(self, requests: Sequence[Request]) -> list[Frame]:
    """Evaluate many geometries (finite differences, path images, IRC branches).

    Requests of one lineage run in list order, each reading the lineage's history
    as it stands at its place (`qcdata.Request.commit`); requests of different
    lineages may run concurrently. The requests share the session's thread count
    (``ctx.threads`` when it opened): a program that runs several at once gives
    each the count divided by those it runs, at least 1. The results equal running
    the requests one at a time, each with the thread count it got.

    Every request runs, failed ones included; then, if any failed, the call
    raises one `qcdata.ProgramErrors` group holding each failure's
    `qcdata.ProgramError` and every frame in request order (failed frames in
    place).

    Args:
        requests: The evaluations.

    Returns:
        One frame per request, in order, all successful.

    Raises:
        ProgramErrors: Some requests failed; ``results`` holds every frame.
    """
    ...

reset(lineage: Lineage = ...) -> None

Drop warm-start and extrapolation history, after a large jump or a failure.

Parameters:

Name Type Description Default
lineage Lineage

The lineage to forget; None is the default lineage. Omitted: all.

...
Source code in src/qccompute/program.py
992
993
994
995
996
997
998
def reset(self, lineage: Lineage = ...) -> None:
    """Drop warm-start and extrapolation history, after a large jump or a failure.

    Args:
        lineage: The lineage to forget; None is the default lineage. Omitted: all.
    """
    ...

plan() -> Plan

The settings pinned for the session's lifetime, its resources and record.

Source code in src/qccompute/program.py
1000
1001
1002
def plan(self) -> Plan:
    """The settings pinned for the session's lifetime, its resources and record."""
    ...

close() -> None

Release the session's resources.

Source code in src/qccompute/program.py
1004
1005
1006
def close(self) -> None:
    """Release the session's resources."""
    ...

qccompute.program.RunContext(*, threads: int | None = None, gpus: Sequence[str] = (), memory_gib: float | None = None, device_memory_gib: float | None = None, timeout: float | None = None, plan: Plan | None = None, scratch: Path | None = None, runner: _Subprograms | None = None, progress: ProgressCallback | None = None)

What a runner gives one calculation: its threads, GPUs, memory and subprograms.

Runners make it and always pass one to Program.compute; a program reads its fields. The resource keywords threads, memory_gib and device_memory_gib are what a calculation asks for, and the runner grants them, at most what its caller has. A program uses at most what it is given; a request capped by it is a resource_capped warning, not an error.

Attributes:

Name Type Description
threads

The calculation's thread count: its threads keyword, else its caller's whole count (a runner's, a parent's, a session's), or 1 for a calculation that runs on GPUs (the docs' Threads page). The program uses at most this many, fewer where more don't help. Its subprograms run under it: never more of them at once than it holds, and a list of them shares it. None: no runner (a direct call). While the program runs, the runner holds the process's BLAS and OpenMP pools at this count (in this process, BLAS counts are process-wide), or at one thread when the input names subprograms.

gpus tuple[str, ...]

Identifiers of the GPUs granted, whole (as for CUDA_VISIBLE_DEVICES: indices or UUIDs); device_ordinals gives this process's CUDA ordinals.

memory_gib

Host memory granted (GiB): the calculation's share of its caller's (its threads' or its GPUs' share of the runner's, a parent's, a session's). The input's memory_gib keyword replaces it, at most the caller's. None: not known.

device_memory_gib

Memory granted on each GPU (GiB): the GPU's, at most a subprogram's parent's. The input's device_memory_gib keyword replaces it, at most that. None: not known or no GPU granted.

plan

The runner's plan of this input, when it made one, so the program need not plan again; exactly what program.plan(input) returned.

progress

Where the program reports what it is doing while it runs, if the caller listens; None when nobody does, so a program checks it before building an event. Call it with a small JSON object, the program's own (qcopt: one per step, {"event": "step", "step": 12, "energy": ...} in qcdata's units); the caller receives it with "path" added, the program names from the caller's input down to this one. It may be called from several threads. Nothing is stored.

Parameters:

Name Type Description Default
threads int | None

The calculation's thread count.

None
gpus Sequence[str]

GPU identifiers granted.

()
memory_gib float | None

Host memory granted (GiB).

None
device_memory_gib float | None

Memory granted on each GPU (GiB).

None
timeout float | None

Seconds the calculation may run, from now.

None
plan Plan | None

The runner's plan of the input.

None
scratch Path | None

A directory the calculation may write to, kept afterwards; None: a temporary one made on first use of scratch.

None
runner _Subprograms | None

What runs subprograms (a runner, or in a worker its client); None: the default runner.

None
progress ProgressCallback | None

Where the program's progress events go; None: nowhere.

None
Source code in src/qccompute/program.py
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
def __init__(
    self,
    *,
    threads: int | None = None,
    gpus: Sequence[str] = (),
    memory_gib: float | None = None,
    device_memory_gib: float | None = None,
    timeout: float | None = None,
    plan: Plan | None = None,
    scratch: Path | None = None,
    runner: _Subprograms | None = None,
    progress: ProgressCallback | None = None,
) -> None:
    """Create a context; runners do this, programs read it.

    Args:
        threads: The calculation's thread count.
        gpus: GPU identifiers granted.
        memory_gib: Host memory granted (GiB).
        device_memory_gib: Memory granted on each GPU (GiB).
        timeout: Seconds the calculation may run, from now.
        plan: The runner's plan of the input.
        scratch: A directory the calculation may write to, kept afterwards; None:
            a temporary one made on first use of `scratch`.
        runner: What runs subprograms (a runner, or in a worker its client); None:
            the default runner.
        progress: Where the program's progress events go; None: nowhere.
    """
    self.threads = threads
    self.gpus: tuple[str, ...] = tuple(gpus)
    self.memory_gib = memory_gib
    self.device_memory_gib = device_memory_gib
    self.plan = plan
    self.progress = progress
    self._deadline = None if timeout is None else time.monotonic() + timeout
    self._scratch = scratch
    # Where a temporary scratch directory is made; None: the system's temporary
    # directory. A worker's client gives it one it removes if the worker is killed.
    self._scratch_parent: Path | None = None
    self._made = False
    self._runner = runner
    # The input whose subprogram tree names the programs ctx may run, set by a
    # runner (a batch's inputs); None: no check. Their names, on first use.
    self._calling: Any = None
    self._named: frozenset[str] | None = None
    # The caller's requests (cancel), shared with its subprograms; None: none.
    self._control: _Control | None = None
    # The first call refused as naming a program the input does not name, which
    # fails the calculation whatever the program makes of it.
    self._refusal: ProgramError | None = None
    # For a calculation in a worker: the identities of the programs its runner
    # would run for it, so the worker may run a subprogram itself only when its
    # own programs are exactly those (`qccompute.serve`).
    self._identities: dict[str, str] | None = None
    # The count its subprograms run under (its own threads), made on first use.
    self._count: Any = None

timeout: float | None property

Seconds the calculation has left, if the caller set a limit.

A program that starts processes kills them when it runs out and fails with kind timeout; one that loops (SCF cycles, optimizer steps) checks it. The runner kills a program in a worker process when it runs out, but cannot stop one in its own process: there the limit is the program's to honour, and the runner only refuses to start its subprograms afterwards (ctx.compute, ctx.session and the session's requests fail with kind timeout). Subprograms get what is left. A calculation that is cancelled while it runs (future.cancel() on a submitted one) has no time left: 0.

scratch: Path property

A directory the calculation may write to, made on first use.

A temporary directory made here is removed when the runner's call returns, or in a worker process that is killed (a timeout, a cancel) when its client lets it go; a program called directly with RunContext() removes it itself (or uses its own temporary directory). With QCCOMPUTE_KEEP_SCRATCH set (KEEP_SCRATCH), every one is kept, for debugging.

stop_requested() -> bool

Whether the caller asked this calculation to stop (runner.stop(future)).

A program that works in steps (an optimizer, a path search, a dynamics run) checks it where it can end cleanly, before each step, and ends there: its output is a failure of kind stopped holding what it reached (a search's frames so far), raised as for any failure (ProgramError(out.error, output=out)). The request covers the whole calculation, its subprograms included: a program whose subprogram stopped stops too, with kind stopped. A program with no steps need not check. The runner never stores a stopped output. A cheap check (a flag, or in a worker a file's existence): call it every step.

Source code in src/qccompute/program.py
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
def stop_requested(self) -> bool:
    """Whether the caller asked this calculation to stop (``runner.stop(future)``).

    A program that works in steps (an optimizer, a path search, a dynamics run)
    checks it where it can end cleanly, before each step, and ends there: its
    output is a failure of kind ``stopped`` holding what it reached (a search's
    frames so far), raised as for any failure
    (``ProgramError(out.error, output=out)``). The request covers the whole
    calculation, its subprograms included: a program whose subprogram stopped
    stops too, with kind ``stopped``. A program with no steps need not check. The
    runner never stores a stopped output. A cheap check (a flag, or in a worker
    a file's existence): call it every step.
    """
    control = self._control
    return control is not None and control.stop_requested()

device_ordinals() -> list[int]

The granted GPUs as CUDA device ordinals in this process, in grant order.

A program selects its devices with these (torch.device("cuda", i), cudaSetDevice(i)), so every program maps a grant alike:

  • When this process's CUDA_VISIBLE_DEVICES is set, a GPU's ordinal is its position there. A worker process is started with CUDA_VISIBLE_DEVICES set to its grant, so its GPUs are 0, 1, ...; in the runner's process GPU "2" of CUDA_VISIBLE_DEVICES=1,2 is ordinal 1. UUIDs (GPU-..., MIG-...) match by value or unique prefix.
  • When it is unset, an index is its own ordinal, and a UUID is the index nvidia-smi gives it. nvidia-smi numbers GPUs in PCI bus order, so a runner that lists them with it sets CUDA_DEVICE_ORDER=PCI_BUS_ID (unless set), for CUDA to number them alike. A process that starts CUDA before it makes its runner sets that itself.

Returns:

Type Description
list[int]

One ordinal per granted GPU; empty when none is granted.

Raises:

Type Description
ProgramError

Kind environment: a granted GPU is not one this process can see.

Source code in src/qccompute/program.py
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
def device_ordinals(self) -> list[int]:
    """The granted GPUs as CUDA device ordinals in this process, in grant order.

    A program selects its devices with these (``torch.device("cuda", i)``,
    ``cudaSetDevice(i)``), so every program maps a grant alike:

    - When this process's ``CUDA_VISIBLE_DEVICES`` is set, a GPU's ordinal is its
      position there. A worker process is started with ``CUDA_VISIBLE_DEVICES``
      set to its grant, so its GPUs are 0, 1, ...; in the runner's process GPU
      ``"2"`` of ``CUDA_VISIBLE_DEVICES=1,2`` is ordinal 1. UUIDs (``GPU-...``,
      ``MIG-...``) match by value or unique prefix.
    - When it is unset, an index is its own ordinal, and a UUID is the index
      ``nvidia-smi`` gives it. ``nvidia-smi`` numbers GPUs in PCI bus order, so a
      runner that lists them with it sets ``CUDA_DEVICE_ORDER=PCI_BUS_ID`` (unless
      set), for CUDA to number them alike. A process that starts CUDA before it
      makes its runner sets that itself.

    Returns:
        One ordinal per granted GPU; empty when none is granted.

    Raises:
        ProgramError: Kind ``environment``: a granted GPU is not one this process
            can see.
    """
    if not self.gpus:
        return []
    visible = _cuda_visible_devices()
    ordinals: list[int] = []
    for gpu in self.gpus:
        ordinal = _ordinal(gpu, visible)
        if ordinal is None:
            where = (
                f"in this process's CUDA_VISIBLE_DEVICES ({','.join(visible)!r})"
                if visible is not None
                else "among the GPUs nvidia-smi lists"
            )
            raise ProgramError.of(
                "environment", f"The granted GPU {gpu!r} is not {where}."
            )
        ordinals.append(ordinal)
    return ordinals

cleanup() -> None

Remove the scratch directory if this context made it (runners call this).

Kept when QCCOMPUTE_KEEP_SCRATCH is set (KEEP_SCRATCH).

Source code in src/qccompute/program.py
744
745
746
747
748
749
750
751
752
753
def cleanup(self) -> None:
    """Remove the scratch directory if this context made it (runners call this).

    Kept when ``QCCOMPUTE_KEEP_SCRATCH`` is set (`KEEP_SCRATCH`).
    """
    if self._made and self._scratch is not None:
        if not _keep_scratch():
            shutil.rmtree(self._scratch, ignore_errors=True)
        self._scratch = None
        self._made = False

compute(inputs: Any, /, *, raise_exc: bool = True) -> Any

Run subprograms under this calculation's thread count, as Runner.compute does.

One gets this calculation's threads unless it sets threads (at most these); a list shares them, and never more run at once than this calculation holds, however many threads of the program call. Failures raise as from qccompute.compute: qcdata.ProgramError for one input, qcdata.ProgramErrors for a list; raise_exc=False returns them in place. A subprogram's failure that the program lets escape fails it with kind program and the subprogram's error as cause.

Every program a subprogram's input names must be named by this calculation's input, among its subprograms (recursively), so that the run's identities cover every program it used; another is refused, whatever raise_exc, and the calculation fails with that refusal (kind input, code unnamed_subprogram) whatever the program returns or raises afterwards.

Parameters:

Name Type Description Default
inputs Any

One input, or a list of independent inputs.

required
raise_exc bool

Raise for failures; False returns failed outputs.

True

Returns:

Type Description
Any

The output, or the outputs in input order.

Raises:

Type Description
ProgramError

A subprogram failed (with raise_exc); or kind input, code unnamed_subprogram: the input does not name the program.

ProgramErrors

Some subprograms of a list failed (with raise_exc).

Source code in src/qccompute/program.py
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
def compute(self, inputs: Any, /, *, raise_exc: bool = True) -> Any:
    """Run subprograms under this calculation's thread count, as ``Runner.compute`` does.

    One gets this calculation's threads unless it sets ``threads`` (at most these);
    a list shares them, and never more run at once than this calculation holds,
    however many threads of the program call. Failures raise
    as from ``qccompute.compute``: `qcdata.ProgramError` for one input,
    `qcdata.ProgramErrors` for a list; ``raise_exc=False`` returns them in place.
    A subprogram's failure that the program lets escape fails it with kind
    ``program`` and the subprogram's error as ``cause``.

    Every program a subprogram's input names must be named by this calculation's
    input, among its subprograms (recursively), so that the run's identities cover
    every program it used; another is refused, whatever ``raise_exc``, and the
    calculation fails with that refusal (kind ``input``, code
    ``unnamed_subprogram``) whatever the program returns or raises afterwards.

    Args:
        inputs: One input, or a list of independent inputs.
        raise_exc: Raise for failures; False returns failed outputs.

    Returns:
        The output, or the outputs in input order.

    Raises:
        ProgramError: A subprogram failed (with ``raise_exc``); or kind ``input``,
            code ``unnamed_subprogram``: the input does not name the program.
        ProgramErrors: Some subprograms of a list failed (with ``raise_exc``).
    """
    if self._calling is not None:
        one = isinstance(inputs, ProgramInput | FileInput)
        inputs = [inputs] if one else list(inputs)
        self._check_named(inputs)
        if one:
            inputs = inputs[0]
    return self._get_runner()._subcompute(inputs, self, raise_exc)

session(spec: ProgramInput | ProgramSpec, structure: Structure | None = None, *, threads: int | None = None, calctypes: Iterable[CalcType | str] | None = None) -> Session

Open a session of a subprogram under this calculation's thread count.

Parameters:

Name Type Description Default
spec ProgramInput | ProgramSpec

The subprogram's input, or its spec with structure.

required
structure Structure | None

With a spec: the atoms, charge, multiplicity and first geometry.

None
threads int | None

The session's thread count, at most this calculation's (a program running 8 tasks side by side on 16 threads gives each session 2), which its host memory follows; None: the input's threads keyword, else this calculation's whole count. Its requests run under both.

None
calctypes Iterable[CalcType | str] | None

The calctypes the session may run (see session_calctypes).

None

Returns:

Type Description
Session

The session; close it (or use it as a context manager) when done. It may be

Session

called from several threads at once: the runner serializes sessions of

Session

programs that are not thread-safe.

Raises:

Type Description
ProgramError

The program refuses the input; or kind input, code unnamed_subprogram: this calculation's input does not name it (see compute).

Source code in src/qccompute/program.py
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
def session(
    self,
    spec: ProgramInput | ProgramSpec,
    structure: Structure | None = None,
    *,
    threads: int | None = None,
    calctypes: Iterable[CalcType | str] | None = None,
) -> Session:
    """Open a session of a subprogram under this calculation's thread count.

    Args:
        spec: The subprogram's input, or its spec with ``structure``.
        structure: With a spec: the atoms, charge, multiplicity and first
            geometry.
        threads: The session's thread count, at most this calculation's (a program
            running 8 tasks side by side on 16 threads gives each session 2),
            which its host memory follows; None: the input's ``threads`` keyword,
            else this calculation's whole count. Its requests run under both.
        calctypes: The calctypes the session may run (see `session_calctypes`).

    Returns:
        The session; close it (or use it as a context manager) when done. It may be
        called from several threads at once: the runner serializes sessions of
        programs that are not thread-safe.

    Raises:
        ProgramError: The program refuses the input; or kind ``input``, code
            ``unnamed_subprogram``: this calculation's input does not name it
            (see `compute`).
    """
    if isinstance(spec, ProgramInput):
        inp = spec
    else:
        if structure is None:
            raise TypeError("A session from a ProgramSpec needs its structure.")
        inp = ProgramInput.from_spec(spec, structure)
    self._check_named((inp,))
    return self._get_runner()._subsession(inp, calctypes, threads, self)

qccompute.program.Capabilities

What a program can do and how it may be run.

Attributes:

Name Type Description
calctypes frozenset[CalcType]

The calculation types it computes.

methods dict[str, frozenset[CalcType]] | None

The methods it implements, each with the calctypes it computes, if it can list them (GFN-FF has no Hessian where GFN2 has one).

sessions bool

Whether it implements SessionProgram.open_session.

batches bool

Whether it implements BatchProgram.compute_batch.

in_process bool

Whether it may run in the runner's own process (it neither writes to the process's stdout/stderr file descriptors nor changes process-global state); otherwise the runner uses a worker process. A program whose input names subprograms may raise its own BLAS and OpenMP pools (held at 1) up to its thread count, only while none of its subprograms runs, restoring them before it returns.

thread_safe bool

Whether separate calculations and sessions may run concurrently in threads of one process (the program releases the GIL and shares no mutable state); the runner then runs them side by side in threads instead of one at a time.

Whether a calculation uses GPUs is its plan's (Resources.gpus), not a capability: a program whose subprograms use GPUs plans theirs.

qccompute.program.Plan

A calculation planned but not run.

Attributes:

Name Type Description
resolved Resolved

The settings with every "auto" replaced, and why; exactly what the run's ProgramOutput.resolved will hold.

resources Resources

The GPUs the calculation needs, which the runner grants, and its memory, informational. A program with subprograms gives the largest over its subprograms' plans.

warnings list[ProgramWarning]

What the program would warn about.

record dict[str, Any]

The program's own detail of the plan (a placement, arithmetic and memory plan), shaped like a run's record.

qccompute.program.Resources

What one calculation asks of the machine, besides threads.

Programs don't suggest thread counts: a calculation's threads are its threads keyword, else its caller's whole count (the docs' Threads page). The runner grants the GPUs asked for, whole. Memory is informational: the runner records it in the plan and never schedules or caps by it (qc* makes no memory estimates). What memory a calculation is granted is in RunContext: memory_gib and device_memory_gib.

Attributes:

Name Type Description
memory_gib float | None

Host memory the calculation expects to use (GiB), if known; informational, not scheduled.

gpus int

GPUs the calculation uses: the runner grants this many (a program whose subprograms use GPUs plans theirs). A program in a worker sees only those granted.

device_memory_gib float | None

Memory per GPU the calculation expects to use (GiB), if known; informational, not scheduled.

qccompute.program.FunctionProgram(name: str, energy_gradient: Callable[..., tuple[float, Any]], hessian: Callable[..., Any] | None = None, *, version: str | None = None, takes_input: bool = False, settings: Mapping[str, Any] | None = None)

A program made of Python functions of the positions.

For a model surface, an ML potential in a script, or teaching: the smallest complete program. Its keywords are the shared threads (its thread count; the runner holds the BLAS pools at it), the shared accuracy, which it records as met, since the functions converge nothing ({"target", "thresholds": {}, "estimate"} with an estimate of 0.0 per target, as qcdata's conventions give), and the settings it declares; any other keyword is an unknown_key input error. It runs in process and is thread-safe::

def morse(x):  # positions (bohr, n x 3) -> energy (Eh), gradient (Eh/bohr)
    ...
    return energy, gradient

qccompute.register_program(FunctionProgram("morse", morse))
out = qccompute.compute(ProgramInput(program="morse", calctype="gradient",
                                     structure=h2))

With takes_input=True the functions also get the input, so one program serves any molecule and setting: energy_gradient(positions, inp) reads the symbols, charge, multiplicity, model and keywords (an engine over a library's calculator). Without it they get the positions alone and the program ignores the model.

An exception from a function is a failed calculation of kind internal, with the function's traceback in the failed output; a qcdata.ProgramError it raises (kind input for a setting's value it refuses) is the calculation's failure.

Parameters:

Name Type Description Default
name str

The program's name, as in ProgramInput.program.

required
energy_gradient Callable[..., tuple[float, Any]]

Positions (bohr, n_atoms x 3), and with takes_input the input, to the energy (Eh) and the gradient (Eh/bohr, n_atoms x 3).

required
hessian Callable[..., Any] | None

The same arguments to the Hessian (Eh/bohr^2, 3 n_atoms x 3 n_atoms); without it the program computes energies and gradients only.

None
version str | None

The program's version and numerics identity, for provenance and the store. None: a digest of the functions (fn- and 16 hex digits), taken on each use, of their code, constants, defaults, closures and the module globals they read, recursing into the Python functions they call. Editing a function or a value it reads (an energy scale) changes it, so a store never serves results of the old function. An object the functions use that is not plain data (an ML model) counts by its type and attributes; give version when that is not enough (a model's checksum).

None
takes_input bool

Call the functions with the input after the positions.

False
settings Mapping[str, Any] | None

The JSON Schema of the keywords the functions read (an object schema; its properties name them, with x-unit, x-tier and x-concern as for any program). Needs takes_input: a keyword the functions never see would change nothing. The program refuses keys it does not name; checking their values is the functions' (or qccompute.testing's, against the schema).

None

Raises:

Type Description
ValueError

settings without takes_input, or naming accuracy or threads, which every FunctionProgram accepts.

Source code in src/qccompute/program.py
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
def __init__(
    self,
    name: str,
    energy_gradient: Callable[..., tuple[float, Any]],
    hessian: Callable[..., Any] | None = None,
    *,
    version: str | None = None,
    takes_input: bool = False,
    settings: Mapping[str, Any] | None = None,
) -> None:
    """Make a program of the functions."""
    declared = dict((settings or {}).get("properties") or {})
    if declared and not takes_input:
        raise ValueError(
            f"{name}: settings need takes_input=True; the functions would never "
            "see a keyword, so it could not affect the calculation."
        )
    shared = sorted({"accuracy", "threads"} & set(declared))
    if shared:
        raise ValueError(
            f"{name}: {shared} are shared keywords every FunctionProgram accepts; "
            "do not declare them."
        )
    self.name = name
    self._energy_gradient = energy_gradient
    self._hessian = hessian
    self._version = version
    self._takes_input = takes_input
    self._schema: dict[str, Any] = {
        **(settings or {}),
        "type": "object",
        "properties": {
            **declared,
            "accuracy": _ACCURACY_SCHEMA,
            "threads": _THREADS_SCHEMA,
        },
        "additionalProperties": False,
    }
    self._keys = frozenset(self._schema["properties"])
    calctypes = {CalcType.energy, CalcType.gradient}
    if hessian is not None:
        calctypes.add(CalcType.hessian)
    self._caps = Capabilities(
        calctypes=frozenset(calctypes), in_process=True, thread_safe=True
    )

version() -> str

The version given, else the digest of the functions as they are now.

Source code in src/qccompute/program.py
1847
1848
1849
1850
1851
def version(self) -> str:
    """The version given, else the digest of the functions as they are now."""
    if self._version is not None:
        return self._version
    return "fn-" + _digest_of((self._energy_gradient, self._hessian))[:16]

numerics(spec: Any = None) -> str

The numerics identity: the version (by default the functions' digest).

Parameters:

Name Type Description Default
spec Any

The input or subprogram spec; the functions are the same for all.

None

Returns:

Type Description
str

The identity.

Source code in src/qccompute/program.py
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
def numerics(self, spec: Any = None) -> str:
    """The numerics identity: the version (by default the functions' digest).

    Args:
        spec: The input or subprogram spec; the functions are the same for all.

    Returns:
        The identity.
    """
    return self.version()

capabilities() -> Capabilities

Energies and gradients (and Hessians with a Hessian function).

Source code in src/qccompute/program.py
1864
1865
1866
def capabilities(self) -> Capabilities:
    """Energies and gradients (and Hessians with a Hessian function)."""
    return self._caps

settings_schema(calctype: CalcType) -> dict[str, Any]

The settings declared, and the shared accuracy and threads.

Source code in src/qccompute/program.py
1868
1869
1870
def settings_schema(self, calctype: CalcType) -> dict[str, Any]:
    """The settings declared, and the shared ``accuracy`` and ``threads``."""
    return self._schema

record_schema(calctype: CalcType) -> dict[str, Any]

The shared accuracy, when a target is given.

Source code in src/qccompute/program.py
1872
1873
1874
def record_schema(self, calctype: CalcType) -> dict[str, Any]:
    """The shared ``accuracy``, when a target is given."""
    return self._RECORD_SCHEMA

plan(inp: ProgramInput) -> Plan

Check the input: a structure, a supported calctype, keywords it knows.

The resolved settings are the keywords given. An accuracy target is met: the plan's record holds the record key accuracy, which the run records.

Raises:

Type Description
ProgramError

Kind input (unknown_key; threads that is not a positive integer; a malformed accuracy, no_effect for one with no target; no structure) or unsupported.

Source code in src/qccompute/program.py
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
def plan(self, inp: ProgramInput) -> Plan:
    """Check the input: a structure, a supported calctype, keywords it knows.

    The resolved settings are the keywords given. An ``accuracy`` target is met:
    the plan's record holds the record key ``accuracy``, which the run records.

    Raises:
        ProgramError: Kind ``input`` (``unknown_key``; ``threads`` that is not a
            positive integer; a malformed ``accuracy``, ``no_effect`` for one with
            no target; no structure) or ``unsupported``.
    """
    if inp.calctype not in self._caps.calctypes:
        raise ProgramError.of(
            "unsupported",
            f"{self.name} computes {sorted(c.value for c in self._caps.calctypes)},"
            f" not {inp.calctype}.",
        )
    if inp.structure is None:
        raise ProgramError.of("input", f"{self.name} needs a structure.")
    if not inp.keywords:
        return _EMPTY_PLAN
    unknown = sorted(set(inp.keywords) - self._keys)
    if unknown:
        raise ProgramError.of(
            "input",
            f"{self.name} has the settings {sorted(self._keys)}; unknown {unknown}.",
            code="unknown_key",
        )
    threads = inp.keywords.get("threads", 1)
    if isinstance(threads, bool) or not isinstance(threads, int) or threads < 1:
        raise ProgramError.of(
            "input", f"threads is a positive integer, not {threads!r}."
        )
    settings = dict(inp.keywords)
    target = Accuracy.from_keywords(inp.keywords)
    if target is None:
        return Plan(resolved=Resolved(settings=settings))
    met = _accuracy_met(target)
    settings["accuracy"] = met["target"]
    return Plan(resolved=Resolved(settings=settings), record={"accuracy": met})

compute(inp: ProgramInput, ctx: RunContext | None = None) -> ProgramOutput[ProgramInput, Data]

Evaluate the functions at the input's structure.

Raises:

Type Description
ProgramError

The input is refused, or a function raised (kind internal; the failed output holds its traceback).

Source code in src/qccompute/program.py
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
def compute(
    self, inp: ProgramInput, ctx: RunContext | None = None
) -> ProgramOutput[ProgramInput, Data]:
    """Evaluate the functions at the input's structure.

    Raises:
        ProgramError: The input is refused, or a function raised (kind
            ``internal``; the failed output holds its traceback).
    """
    start = time.perf_counter()
    # A runner hands on the plan it made.
    plan = ctx.plan if ctx is not None and ctx.plan is not None else self.plan(inp)
    assert inp.structure is not None
    x = np.asarray(inp.structure.geometry, dtype=float).reshape(-1, 3)
    provenance = Provenance(program=self.name, program_version=self.version())
    # What the runner granted; called directly, what the input asks for.
    threads = (ctx.threads if ctx is not None else None) or inp.keywords.get(
        "threads", 1
    )
    given = (inp,) if self._takes_input else ()
    try:
        energy, gradient = self._energy_gradient(x.copy(), *given)
        values: dict[str, Any] = {"energy": float(energy)}
        if inp.calctype != CalcType.energy:
            values["gradient"] = np.asarray(gradient, dtype=float).reshape(-1, 3)
        if inp.calctype == CalcType.hessian:
            assert self._hessian is not None
            hessian = self._hessian(x.copy(), *given)
            values["hessian"] = np.asarray(hessian, dtype=float)
        results = SinglePointData(provenance=provenance, **values)
    except ProgramError:  # the function's own refusal or failure
        raise
    except Exception as e:  # noqa: BLE001 - the function's failure, with its trace
        error = ErrorInfo(
            kind=ErrorKind.internal, message=f"{type(e).__name__}: {e}"
        )
        out = ProgramOutput.failure(
            inp,
            error,
            traceback="".join(traceback.format_exception(e)),
            execution=ExecutionInfo(threads=threads),
        )
        raise ProgramError(error, output=out) from e
    return ProgramOutput(
        input_data=inp,
        success=True,
        results=results,
        resolved=plan.resolved,
        record=plan.record,
        execution=ExecutionInfo(
            threads=threads, timings={"total": time.perf_counter() - start}
        ),
    )

qccompute.program.ComputeSession(compute: Callable[..., Any], inp: ProgramInput, calctypes: Iterable[CalcType | str] | None = None, *, program_version: str)

A session over compute, for programs without sessions of their own.

Each request becomes the session's input at the new positions and calctype, computed by compute: a runner's compute (one input raises qcdata.ProgramError on failure; a list with raise_exc=False returns failed outputs in place). A runner computes compute_many's requests as a list, side by side, sharing the session's thread count. It keeps no history: every request starts fresh (warm_start false), so lineage, seed and commit change nothing. A request's accuracy becomes the accuracy keyword of the input it computes, replacing the session input's own; the program records it as it records the keyword (a program with no convergence settings, as met). A hessian result without a gradient is completed by a gradient calculation.

Parameters:

Name Type Description Default
compute Callable[..., Any]

Computes one input, or a list with raise_exc=False.

required
inp ProgramInput

The program, model, keywords and structure; its geometry and calctype are the defaults of a request.

required
calctypes Iterable[CalcType | str] | None

The calctypes the session may run (see session_calctypes; by default energy, gradient and Hessian, which the program may still refuse).

None
program_version str

The program's version (program.version()), the session's from its opening.

required
Source code in src/qccompute/program.py
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
def __init__(
    self,
    compute: Callable[..., Any],
    inp: ProgramInput,
    calctypes: Iterable[CalcType | str] | None = None,
    *,
    program_version: str,
):
    """Create the session."""
    if inp.structure is None:
        raise TypeError("A session's input needs a structure.")
    self._compute = compute
    self._inp = inp
    self._structure: Structure = inp.structure
    self.calctypes = session_calctypes(calctypes)
    self.program = inp.program
    self.program_version = program_version
    self._closed = False

input_data: ProgramInput property

The input the session was opened with.

compute(positions: np.ndarray | None = None, calctype: CalcType | str | None = None, *, accuracy: Accuracy | float | None = None, lineage: Lineage = None, outputs: Iterable[str] = (), seed: Iterable[Lineage] = (), commit: bool = True) -> Frame

Evaluate one geometry; see Session.compute.

Parameters:

Name Type Description Default
positions ndarray | None

Atomic positions (bohr); None: the input's own.

None
calctype CalcType | str | None

energy, gradient or hessian; None: the input's.

None
accuracy Accuracy | float | None

The input's accuracy keyword for this request (a number targets the calctype's highest derivative); None: the input's own.

None
lineage Lineage

Ignored: a stateless session keeps no history.

None
outputs Iterable[str]

Not supported; must be empty.

()
seed Iterable[Lineage]

Ignored, like lineage.

()
commit bool

Ignored, like lineage.

True

Returns:

Type Description
Frame

The evaluation.

Raises:

Type Description
ProgramError

The calculation failed, or outputs were requested.

Source code in src/qccompute/program.py
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
def compute(
    self,
    positions: np.ndarray | None = None,
    calctype: CalcType | str | None = None,
    *,
    accuracy: Accuracy | float | None = None,
    lineage: Lineage = None,
    outputs: Iterable[str] = (),
    seed: Iterable[Lineage] = (),
    commit: bool = True,
) -> Frame:
    """Evaluate one geometry; see `Session.compute`.

    Args:
        positions: Atomic positions (bohr); None: the input's own.
        calctype: ``energy``, ``gradient`` or ``hessian``; None: the input's.
        accuracy: The input's ``accuracy`` keyword for this request (a number
            targets the calctype's highest derivative); None: the input's own.
        lineage: Ignored: a stateless session keeps no history.
        outputs: Not supported; must be empty.
        seed: Ignored, like ``lineage``.
        commit: Ignored, like ``lineage``.

    Returns:
        The evaluation.

    Raises:
        ProgramError: The calculation failed, or outputs were requested.
    """
    if self._closed:
        raise RuntimeError("The session is closed.")
    if tuple(outputs):
        raise ProgramError.of(
            "unsupported",
            "A session over compute takes optional outputs from the input's "
            "keywords, not per request.",
        )
    return self._one(self._input(positions, calctype, accuracy))

compute_many(requests: Sequence[Request]) -> list[Frame]

Evaluate many geometries in one call to compute.

Parameters:

Name Type Description Default
requests Sequence[Request]

The evaluations.

required

Returns:

Type Description
list[Frame]

One frame per request, in order.

Raises:

Type Description
ProgramErrors

Some requests failed; results holds every frame.

Source code in src/qccompute/program.py
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
def compute_many(self, requests: Sequence[Request]) -> list[Frame]:
    """Evaluate many geometries in one call to compute.

    Args:
        requests: The evaluations.

    Returns:
        One frame per request, in order.

    Raises:
        ProgramErrors: Some requests failed; ``results`` holds every frame.
    """
    if self._closed:
        raise RuntimeError("The session is closed.")
    frames: list[Frame | None] = [None] * len(requests)
    inputs: list[ProgramInput] = []
    places: list[int] = []
    for i, r in enumerate(requests):
        try:
            if r.outputs:
                raise ProgramError.of(
                    "unsupported", "per-request outputs need a program session"
                )
            inputs.append(self._input(r.positions, r.calctype, r.accuracy))
            places.append(i)
        except ProgramError as e:
            geometry = (
                self._structure.geometry if r.positions is None else r.positions
            )
            structure = self._structure.model_copy(
                update={
                    "geometry": np.asarray(geometry, dtype=float).reshape(-1, 3)
                }
            )
            frames[i] = failed_frame(structure, e, self.program)
    outputs = self._compute(inputs, raise_exc=False) if inputs else []
    for i, inp, out in zip(places, inputs, outputs, strict=True):
        try:
            if not out.success:
                frame = self._as_frame(out)
            elif inp.calctype == CalcType.hessian and out.results.gradient is None:
                frame = self._one(inp)
            else:
                frame = self._as_frame(out)
            frames[i] = frame
        except ProgramError as e:
            assert inp.structure is not None
            frames[i] = failed_frame(inp.structure, e, self.program)
    return ProgramErrors.check([f for f in frames if f is not None])

reset(lineage: Lineage = ...) -> None

Nothing to reset: a stateless session keeps no history.

Source code in src/qccompute/program.py
1365
1366
def reset(self, lineage: Lineage = ...) -> None:
    """Nothing to reset: a stateless session keeps no history."""

plan() -> Plan

Not known to a stateless session: the input's keywords, unresolved.

Source code in src/qccompute/program.py
1368
1369
1370
def plan(self) -> Plan:
    """Not known to a stateless session: the input's keywords, unresolved."""
    return Plan(resolved=Resolved(settings=dict(self._inp.keywords)))

close() -> None

Close the session.

Source code in src/qccompute/program.py
1372
1373
1374
def close(self) -> None:
    """Close the session."""
    self._closed = True

qccompute.program.register_program(program: Program) -> None

Make a program findable by name in this process, ahead of installed ones.

For programs that are not installed packages: in tests, notebooks and scripts. Runners in this process find it through find_program, and so do the subprograms of a program in a worker process (geomeTRIC's gradients), which run back in this process. A registered program that itself runs in a worker process (in_process=False, or a runner with isolation="process") reaches it as a top-level attribute of an importable module when it is one, else pickled: its class and what it holds must then be importable in the worker (nothing defined in the script being run, no lambdas or closures), or running it there fails with kind environment, saying so.

Parameters:

Name Type Description Default
program Program

An object implementing Program.

required

Raises:

Type Description
TypeError

The object does not implement Program, or is a class.

Source code in src/qccompute/program.py
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
def register_program(program: Program) -> None:
    """Make a program findable by name in this process, ahead of installed ones.

    For programs that are not installed packages: in tests, notebooks and scripts.
    Runners in this process find it through `find_program`, and so do the
    subprograms of a program in a worker process (geomeTRIC's gradients), which run
    back in this process. A registered program that itself runs in a worker process
    (``in_process=False``, or a runner with ``isolation="process"``) reaches it as a
    top-level attribute of an importable module when it is one, else pickled: its
    class and what it holds must then be importable in the worker (nothing defined
    in the script being run, no lambdas or closures), or running it there fails
    with kind ``environment``, saying so.

    Args:
        program: An object implementing `Program`.

    Raises:
        TypeError: The object does not implement `Program`, or is a class.
    """
    _require_program(program, repr(program))
    with _registry_lock:
        _registered[program.name] = program

qccompute.program.unregister_program(name: str) -> None

Forget a program added with register_program; installed programs stay.

Parameters:

Name Type Description Default
name str

The program's name.

required
Source code in src/qccompute/program.py
1436
1437
1438
1439
1440
1441
1442
1443
def unregister_program(name: str) -> None:
    """Forget a program added with `register_program`; installed programs stay.

    Args:
        name: The program's name.
    """
    with _registry_lock:
        _registered.pop(name, None)

qccompute.program.find_program(name: str) -> Program | None

The program of this name: registered in this process, else installed.

Installed programs are read from the qccompute.programs entry points and loaded once per process.

Parameters:

Name Type Description Default
name str

The program's name, as in ProgramInput.program.

required

Returns:

Type Description
Program | None

The program object, or None if none is registered or installed.

Raises:

Type Description
TypeError

The installed object does not implement Program, or is a class.

Source code in src/qccompute/program.py
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
def find_program(name: str) -> Program | None:
    """The program of this name: registered in this process, else installed.

    Installed programs are read from the ``qccompute.programs`` entry points and loaded
    once per process.

    Args:
        name: The program's name, as in ``ProgramInput.program``.

    Returns:
        The program object, or None if none is registered or installed.

    Raises:
        TypeError: The installed object does not implement `Program`, or is a class.
    """
    with _registry_lock:
        if name in _registered:
            return _registered[name]
        if name in _installed:
            return _installed[name]
    ep = _entry_points().get(name)
    program: Program | None = None
    if ep is not None:
        program = _require_program(
            ep.load(), f"The qccompute.programs entry point {name!r} ({ep.value})"
        )
    with _registry_lock:
        return _installed.setdefault(name, program)

qccompute.program.available_programs() -> list[str]

Names of the programs qccompute can find, without loading any.

The programs registered in this process and those installed packages offer under the qccompute.programs entry points. A package may offer a program whose executable is not on this machine (qccodec offers every external program it has an adapter for: ORCA, Psi4, TeraChem, ...); running it then fails with kind environment. An external program's numerics says not installed when its executable cannot be found.

Returns:

Type Description
list[str]

The names, sorted.

Source code in src/qccompute/program.py
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
def available_programs() -> list[str]:
    """Names of the programs qccompute can find, without loading any.

    The programs registered in this process and those installed packages offer
    under the ``qccompute.programs`` entry points. A package may offer a program whose
    executable is not on this machine (qccodec offers every external program it has
    an adapter for: ORCA, Psi4, TeraChem, ...); running it then fails with kind
    ``environment``. An external program's ``numerics`` says ``not installed`` when its
    executable cannot be found.

    Returns:
        The names, sorted.
    """
    with _registry_lock:
        registered = set(_registered)
    return sorted(registered | set(_entry_points()))

qccompute.program.numerics_of(program: Program, spec: ProgramSpec | FileInput) -> str

A program's numerics identity for a spec: program.numerics(spec), else its version.

numerics(spec) -> str is optional in the protocol: a string that changes whenever the program's results for an unchanged input may change (a numerics epoch the program bumps; an external program: its executable's sha256; an ML potential: its model's checksum). It takes the spec (an input, or a subprogram's ProgramSpec), so a program of several methods can give each its own. A store files every run under the identities of the programs that made it, and a runner reuses a run only when they are those it would run now.

Parameters:

Name Type Description Default
program Program

The program.

required
spec ProgramSpec | FileInput

The input, or the subprogram's spec, it would run.

required

Returns:

Type Description
str

The identity.

Source code in src/qccompute/program.py
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
def numerics_of(program: Program, spec: ProgramSpec | FileInput) -> str:
    """A program's numerics identity for a spec: ``program.numerics(spec)``, else its version.

    ``numerics(spec) -> str`` is optional in the protocol: a string that changes
    whenever the program's results for an unchanged input may change (a numerics
    epoch the program bumps; an external program: its executable's sha256; an ML potential: its
    model's checksum). It takes the spec (an input, or a subprogram's `ProgramSpec`),
    so a program of several methods can give each its own. A store files every run
    under the identities of the programs that made it, and a runner reuses a run only
    when they are those it would run now.

    Args:
        program: The program.
        spec: The input, or the subprogram's spec, it would run.

    Returns:
        The identity.
    """
    numerics = getattr(program, "numerics", None)
    if callable(numerics):
        return str(numerics(spec))
    return program.version()

qccompute.program.capabilities_of(program: Program) -> Capabilities

A program's capabilities, validated: it may return a mapping or any object.

Parameters:

Name Type Description Default
program Program

The program.

required

Returns:

Type Description
Capabilities

Its Capabilities.

Source code in src/qccompute/program.py
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
def capabilities_of(program: Program) -> Capabilities:
    """A program's capabilities, validated: it may return a mapping or any object.

    Args:
        program: The program.

    Returns:
        Its `Capabilities`.
    """
    return Capabilities.model_validate(program.capabilities(), from_attributes=True)

qccompute.program.plan_of(program: Program, inp: ProgramInput) -> Plan

A program's plan for an input, validated: it may return a mapping or any object.

Parameters:

Name Type Description Default
program Program

The program.

required
inp ProgramInput

The input.

required

Returns:

Type Description
Plan

The Plan.

Raises:

Type Description
ProgramError

The input cannot run.

Source code in src/qccompute/program.py
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
def plan_of(program: Program, inp: ProgramInput) -> Plan:
    """A program's plan for an input, validated: it may return a mapping or any object.

    Args:
        program: The program.
        inp: The input.

    Returns:
        The `Plan`.

    Raises:
        ProgramError: The input cannot run.
    """
    return Plan.model_validate(program.plan(inp), from_attributes=True)

qccompute.testing.check_program(program: Program, inputs: Sequence[ProgramInput], *, energy_tol: float = 1e-08) -> list[str]

Check that a program meets the AFH program contract.

The program is registered while the checks run, so a program with subprograms called directly (ctx=None) reaches itself through qccompute.compute.

Parameters:

Name Type Description Default
program Program

The program object (what its qccompute.programs entry point loads).

required
inputs Sequence[ProgramInput]

Small inputs the program can compute quickly, covering the calctypes to check; the first one also exercises the thread grant, sessions and batches.

required
energy_tol float

Tolerance (Eh) for energy components adding up and for sessions and batches agreeing with plain computes.

1e-08

Returns:

Type Description
list[str]

The names of the checks that ran.

Raises:

Type Description
ConformanceError

One or more checks failed; the message lists all of them.

Source code in src/qccompute/testing/__init__.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def check_program(
    program: Program,
    inputs: Sequence[ProgramInput],
    *,
    energy_tol: float = 1e-8,
) -> list[str]:
    """Check that a program meets the AFH program contract.

    The program is registered while the checks run, so a program with subprograms
    called directly (``ctx=None``) reaches itself through ``qccompute.compute``.

    Args:
        program: The program object (what its ``qccompute.programs`` entry point loads).
        inputs: Small inputs the program can compute quickly, covering the calctypes
            to check; the first one also exercises the thread grant, sessions and
            batches.
        energy_tol: Tolerance (Eh) for energy components adding up and for sessions
            and batches agreeing with plain computes.

    Returns:
        The names of the checks that ran.

    Raises:
        ConformanceError: One or more checks failed; the message lists all of them.
    """
    previous = _registered.get(program.name) if isinstance(program, Program) else None
    if isinstance(program, Program) and not isinstance(program, type):
        register_program(program)
    try:
        return _check_program(program, inputs, energy_tol)
    finally:
        if previous is not None:
            register_program(previous)
        elif isinstance(program, Program) and not isinstance(program, type):
            unregister_program(program.name)