Skip to content

Session steps: requests, accuracy, failures

A session (qccompute's execution protocol) evaluates one molecule at many geometries. What one step asks for and how it fails are data, shared by every program: a Request, its Accuracy target, and ProgramError, the exception form of ErrorInfo. A step's result is a Frame. Lineages are any JSON value; programs key their histories by lineage_key. An input's own target, for compute and for requests that give none, is the shared keyword accuracy (conventions), read with Accuracy.from_keywords.

qcdata.Request

One step of a session: where to evaluate, what, and from which history.

Attributes:

Name Type Description
positions SerializableMatrix | None

Atomic positions (bohr), n_atoms x 3, atoms as the session's input. None: the input's own geometry.

calctype CalcType | None

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

accuracy Accuracy | float | None

Target accuracy of this request (a bare number targets the calctype's highest derivative); it replaces the input's accuracy keyword for this request. None: the keyword's target, else the session's settings.

lineage Lineage

The chain of steps this one continues. A session keeps warm-start and extrapolation history per lineage (keyed by lineage_key), so NEB images, IRC branches and parallel tasks each start from their own last success. None is the default lineage.

outputs frozenset[str]

Optional outputs that do not change the surface but may cost extra. A name that fills a top-level SinglePointData field is that field's name (dipole_moment, polarizability); others name what they add (ir). The wavefunction's parts are orbitals, overlap, hamiltonian and core_hamiltonian; a program fills in what one implies (each brings the basis set, hamiltonian also overlap and orbitals), as the conventions list. A program refuses an output it cannot give with kind unsupported, code not_applicable.

seed list[Lineage]

Lineages to start from, in order, when lineage has no history yet: the first with history is used, and with none the request starts fresh. Both IRC branches start from the transition state's lineage this way. A request seeded from a lineage runs after every earlier request of that lineage in the same list. The record names the lineage used.

commit bool

Whether a success becomes lineage's history. False stores nothing: a finite-difference fan-out in the center's lineage starts every displacement from the center, without keeping a state per displacement. In a list, a request reads its lineage's history as it stands at its own place: after every earlier committing request of that lineage, unaffected by later ones. In [A, B (commit=False), C, D (commit=False)], all in one lineage, B starts from A and D from C; B may run alongside C if it reads the history from before C.

qcdata.Accuracy

How tightly a calculation converges: targets, absolute and in atomic units.

Each field is the numerical error from convergence the caller can tolerate in that quantity; a field left out sets no target for it. It is a target, not a guarantee: the program picks the thresholds it expects to meet it (a DFT program: SCF orbital gradient and response residual; axtb: energy and charge change) and records the target, the thresholds and any error estimate it has under the shared record key accuracy. Explicit convergence settings are floors: a target may tighten them, never loosen them. Approximations (basis, grids, precision) are not covered.

A target is given two ways. The shared keyword accuracy (an object of these fields, read with from_keywords) is the input's own target: of compute, and of every session request that gives none. A request's Request.accuracy replaces it for that request. The keyword is part of the input, so of its calculation key: a tighter target is another calculation. A program with no convergence settings (a force field, an ML potential) accepts a target, keyword or request alike, and records it as met: empty thresholds and an estimate of 0.0 per target. A program whose convergence settings take no targets yet refuses it with kind unsupported.

Attributes:

Name Type Description
energy float | None

Target error of the energy (Eh).

gradient float | None

Target error of the largest absolute gradient component (Eh/bohr).

hessian float | None

Target error of the largest absolute Hessian element (Eh/bohr^2).

from_keywords classmethod

from_keywords(
    keywords: Mapping[str, Any],
) -> Accuracy | None

Read the shared keyword accuracy: the input's own target, if it sets one.

The keyword is a JSON object of Accuracy's targets ({"energy": 1e-8, "gradient": 1e-6}), never a bare number: an input's target applies to every calctype a session runs, so a number would have no single quantity to aim at. An Accuracy given in keywords is stored in this form (ProgramSpec.keywords).

Parameters:

Name Type Description Default
keywords Mapping[str, Any]

The input's keywords (ProgramSpec.keywords).

required

Returns:

Type Description
Accuracy | None

The target, or None when the keywords set none (absent or null).

Raises:

Type Description
ProgramError

Kind input: the value is not an object of positive, finite targets; code unknown_key for a key other than energy, gradient and hessian, and no_effect when it sets none.

Source code in src/qcdata/models/steps.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
@classmethod
def from_keywords(cls, keywords: Mapping[str, Any]) -> Accuracy | None:
    """Read the shared keyword ``accuracy``: the input's own target, if it sets one.

    The keyword is a JSON object of `Accuracy`'s targets
    (``{"energy": 1e-8, "gradient": 1e-6}``), never a bare number: an input's
    target applies to every calctype a session runs, so a number would have no
    single quantity to aim at. An `Accuracy` given in keywords is stored in this
    form (`ProgramSpec.keywords`).

    Args:
        keywords: The input's keywords (`ProgramSpec.keywords`).

    Returns:
        The target, or None when the keywords set none (absent or null).

    Raises:
        ProgramError: Kind ``input``: the value is not an object of positive,
            finite targets; code ``unknown_key`` for a key other than ``energy``,
            ``gradient`` and ``hessian``, and ``no_effect`` when it sets none.
    """
    value = keywords.get("accuracy")
    if value is None:
        return None
    if not isinstance(value, Mapping):
        raise ProgramError.of(
            "input",
            "The keyword accuracy is a JSON object of targets (energy in Eh, "
            "gradient in Eh/bohr, hessian in Eh/bohr^2), such as "
            f'{{"gradient": 1e-06}}, not {type(value).__name__} {value!r}.',
        )
    unknown = sorted(set(value) - set(_TARGETS))
    if unknown:
        import difflib  # imported on use: only a refusal needs it

        hints = [
            f"accuracy.{k}"
            + "".join(
                f" (did you mean accuracy.{m}?)"
                for m in difflib.get_close_matches(k, _TARGETS, n=1)
            )
            for k in unknown
        ]
        raise ProgramError.of(
            "input",
            f"Unknown keyword {', '.join(hints)}; accuracy takes "
            f"{', '.join(_TARGETS)}.",
            code="unknown_key",
        )
    try:
        accuracy = cls.model_validate(value)
    except ValidationError as e:
        errors = "; ".join(
            f"accuracy.{'.'.join(map(str, err['loc']))}: "
            + err["msg"].removeprefix("Value error, ").rstrip(".")
            for err in e.errors()
        )
        raise ProgramError.of(
            "input", f"The keyword accuracy is not valid: {errors}."
        ) from None
    if accuracy.energy is accuracy.gradient is accuracy.hessian is None:
        raise ProgramError.of(
            "input",
            "The keyword accuracy sets no target; give energy, gradient or "
            "hessian, or leave it out.",
            code="no_effect",
        )
    return accuracy

of classmethod

of(
    value: Accuracy | float | None, calctype: CalcType | str
) -> Accuracy | None

Read a request's accuracy: a bare number targets its highest derivative.

Parameters:

Name Type Description Default
value Accuracy | float | None

An Accuracy, a number, or None.

required
calctype CalcType | str

The request's calculation type.

required

Returns:

Type Description
Accuracy | None

The accuracy, or None when the request gives none: the input's own target

Accuracy | None

(from_keywords) then applies, else the session's settings.

Source code in src/qcdata/models/steps.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
@classmethod
def of(
    cls, value: Accuracy | float | None, calctype: CalcType | str
) -> Accuracy | None:
    """Read a request's accuracy: a bare number targets its highest derivative.

    Args:
        value: An `Accuracy`, a number, or None.
        calctype: The request's calculation type.

    Returns:
        The accuracy, or None when the request gives none: the input's own target
        (`from_keywords`) then applies, else the session's settings.
    """
    if value is None or isinstance(value, Accuracy):
        return value
    name = {"energy": "energy", "gradient": "gradient", "hessian": "hessian"}.get(
        CalcType(calctype).value, "energy"
    )
    return cls.model_validate({name: float(value)})

qcdata.ProgramError

ProgramError(
    error: ErrorInfo,
    results: Data | None = None,
    *,
    frame: Frame | None = None,
    output: ProgramOutput[Any, Any] | None = None,
)

A failed calculation: ErrorInfo raised, with what was computed before it failed.

Every program's compute and every session call raise it (or a subclass) when a calculation fails, an input the program refuses included; any other exception is a bug. A program catches this one class from its subprograms, whichever programs they are. A runner turns it into a failed ProgramOutput only where it needs data: a store, the outputs of a list, a worker's reply.

A program whose result is one output raises ProgramError(out.error, output=out) with its failed output, so that nothing it reached is lost (a trajectory's frames, its record and resolved settings); callers read exc.output. A failed session step raises with its frame.

Attributes:

Name Type Description
error

What went wrong, as a kind and code callers can branch on.

frame

The failed step, when there was one: its structure, partial results, warnings and record (an SCF's iteration history, its stability analyses).

output

The whole failed output, when the program has one.

results

What was computed before the failure, if anything: of the output's results type for a whole output, SinglePointData for a step.

Parameters:

Name Type Description Default
error ErrorInfo

What went wrong.

required
results Data | None

Partial results, if any; when not given, taken from output, else from frame.

None
frame Frame | None

The failed step, if any.

None
output ProgramOutput[Any, Any] | None

The failed output, if any.

None
Source code in src/qcdata/models/steps.py
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
def __init__(
    self,
    error: ErrorInfo,
    results: Data | None = None,
    *,
    frame: Frame | None = None,
    output: ProgramOutput[Any, Any] | None = None,
):
    """Create the exception.

    Args:
        error: What went wrong.
        results: Partial results, if any; when not given, taken from ``output``,
            else from ``frame``.
        frame: The failed step, if any.
        output: The failed output, if any.
    """
    super().__init__(f"{error.kind}: {error.message}")
    self.error = error
    self.frame = frame
    self.output = output
    if results is None and output is not None:
        results = output.results
    if results is None and frame is not None:
        results = frame.results
    self.results = results

of classmethod

of(
    kind: ErrorKind | str,
    message: str,
    *,
    code: str | None = None,
    details: dict[str, Any] | None = None,
) -> ProgramError

Shorthand for a ProgramError without partial results.

Parameters:

Name Type Description Default
kind ErrorKind | str

The error kind.

required
message str

A human-readable explanation.

required
code str | None

A program-defined code refining the kind.

None
details dict[str, Any] | None

Structured facts about the failure (ErrorInfo.details).

None

Returns:

Type Description
ProgramError

The exception.

Source code in src/qcdata/models/steps.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
@classmethod
def of(
    cls,
    kind: ErrorKind | str,
    message: str,
    *,
    code: str | None = None,
    details: dict[str, Any] | None = None,
) -> ProgramError:
    """Shorthand for a ProgramError without partial results.

    Args:
        kind: The error kind.
        message: A human-readable explanation.
        code: A program-defined code refining the kind.
        details: Structured facts about the failure (`ErrorInfo.details`).

    Returns:
        The exception.
    """
    return cls(
        ErrorInfo(
            kind=ErrorKind(kind), message=message, code=code, details=details or {}
        )
    )

qcdata.lineage_key

lineage_key(lineage: Any) -> str

The text a program keys a lineage's history by: its canonical JSON.

Keys sorted, compact separators, tuples as lists, so ("irc", "forward") and ["irc", "forward"] are the same lineage, in process and over a worker's wire.

Parameters:

Name Type Description Default
lineage Any

Any JSON value; None is the default lineage.

required

Returns:

Type Description
str

The canonical JSON text.

Raises:

Type Description
TypeError

The value is not JSON (a set, an object, ...).

ValueError

The value holds a non-finite number.

Source code in src/qcdata/models/steps.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
def lineage_key(lineage: Any) -> str:
    """The text a program keys a lineage's history by: its canonical JSON.

    Keys sorted, compact separators, tuples as lists, so ``("irc", "forward")`` and
    ``["irc", "forward"]`` are the same lineage, in process and over a worker's wire.

    Args:
        lineage: Any JSON value; None is the default lineage.

    Returns:
        The canonical JSON text.

    Raises:
        TypeError: The value is not JSON (a set, an object, ...).
        ValueError: The value holds a non-finite number.
    """
    return json.dumps(
        lineage,
        sort_keys=True,
        separators=(",", ":"),
        ensure_ascii=False,
        allow_nan=False,
    )