qecx.QECXDocument¶
- class qecx.QECXDocument(code_data, *, code_name=None)¶
Bases:
objectSingle mutable, typed representation of a QECX document.
The document is the one mutable object of the model: every model object it stores (code data, template entries, operation variants, cycles, decoders, references, layout, properties) is frozen, valid by construction, and registered and returned by identity. Accessors return the stored objects themselves, mapping-valued accessors as read-only views; only circuits are returned as copies. Authoring follows the document’s dependency order: anything a registration references (template entries, syndrome-measurement variants, decoder slugs, citation keys) must already be registered, and every registration and edit rejects atomically, so the document is reference-consistent after every call.
Validation runs in three tiers. Construction checks live on the model classes; every registration and editing method runs targeted context checks over exactly the objects it touches (its cascade closure) and raises
QECXAuthoringErrorat the offending call, leaving the document untouched; and the full document-level rule engine runs at the three document-validation points (load(),validate(),save()), where it is authoritative over every typed check. Completeness requirements run only at the document-validation points, so a mid-authoring document accepts edits freely;missing()previews them.The
replace_methods cascade-rewrite the closure of referrers of the replaced node (references only, never content: a variant’s internals are content and changing them means replacing the variant) and return the new node. After a replace, author-held variables for the replaced node and its rebuilt referrers are stale by design; re-read them from the document. Theremove_methods raise while the removed node is still referenced.Examples
code = CSSCodeData(n=7, k=1, d=3, H_X=..., H_Z=..., logical_operators_X=..., logical_operators_Z=...) doc = QECXDocument(code, code_name="steane_7_1_3") # The data-register entry (size 7) is auto-seeded from code.n. syn_entry = RegisterTemplateEntry( "syndrome", 3, purpose=RegisterPurpose.SYNDROME) doc.add_ancilla_register_template(syn_entry) synd = SyndromeMeasurementVariant(name="x_only", circuit=..., ...) doc.add_operation(synd) # first in its group: the default doc.add_error_correction_cycle_variant(ECCycleVariant( name="standard", steps=(ECCycleStep(measurement=synd, repeat=ref(code).d),), fault_tolerant=True, )) doc.syndrome_measurements.variants # {"x_only": synd} synd2 = doc.replace_operation( synd, replace(synd, description="weight-3 X checks")) # synd and the cycle step referencing it are stale; re-read from doc. doc.missing() # previews any unmet completeness requirements # register the operations and decoder the preview still lists, then: doc.save("steane_7_1_3.qecx", layout="auto")
Start a document whose code section is
code_data.The data-register entry is seeded into the register template automatically with size
code_data.n; it needs no declaration.replace_code_data()andupdate_code_data()change the code section later.- Parameters:
- classmethod load(source, *, validate=True)¶
Load a QECX document and return its typed representation.
Loading validates first and parses second: the resolved document dict runs through the full rule engine, then a two-pass graph reconstruction builds the typed object graph, so every stored reference resolves to a registered object. Error-severity findings abort the load; each warning-severity finding is emitted as a Python warning. Variants created by loading retain their stored circuit text (
source_qasm) and re-save it byte for byte, while a copy of one made withdataclasses.replacesaves its own circuit; every payload of the loaded content records where it sat, so a latersave()reproduces the layout. The container form is detected from content.- Parameters:
source (str | Path | BinaryIO | BufferedIOBase) – Path to the file, or a readable binary stream such as an open file or an
io.BytesIO; an anonymous stream is recorded under a placeholder source label.validate (bool) – If
True(default), run the full rule engine on the resolved document and raiseQECXValidationFailedErroron any error-severity findings. IfFalse, skip that document-level check, loading a document that breaks cross-object or semantic rules so it can be inspected and repaired. Per-object construction and reference resolution always apply, so a document that is not structurally constructible, or that carries an unresolvable reference, still fails to load; inspect those through the dict-levelvalidate_qecxpath. Repairing one is a dict-level edit: correct the referencevalidate_qecx()names, then re-enter throughfrom_dict().
- Returns:
The loaded document.
- Return type:
- Raises:
FileNotFoundError – If
sourcenames a file that does not exist.QECXLoadError – If the bytes cannot be parsed, an archive reference cannot be resolved, or the resolved document cannot be reconstructed into typed objects (a field of the wrong type or an invalid value, or a reference that does not resolve).
QECXValidationFailedError – If
validateisTrueand validation produced one or more error-severity findings.
- classmethod loads(text, *, validate=True)¶
Load a QECX document from inline JSON text.
The text form of
load():textis the inline-container JSON of a complete document. Validation and graph reconstruction behave exactly as inload().- Parameters:
- Returns:
The loaded document.
- Return type:
- Raises:
QECXLoadError – If
textis not parseable JSON, or the resolved document cannot be reconstructed into typed objects.QECXValidationFailedError – If
validateisTrueand validation produced one or more error-severity findings.
- classmethod from_dict(data, *, validate=True)¶
Build a typed document from an already-parsed document dict.
The in-memory entry of the loader family:
datais a fully resolved document dict, shaped asto_dict()returns it. Validation and graph reconstruction behave exactly as inload();datais never mutated.- Parameters:
- Returns:
The reconstructed document.
- Return type:
- Raises:
QECXLoadError – If
datacannot be reconstructed into typed objects (a field of the wrong type or an invalid value, or a reference that does not resolve).QECXValidationFailedError – If
validateisTrueand validation produced one or more error-severity findings.
- copy()¶
Return an independent document holding the same content.
The branching entry point: the copy shares the frozen model objects with the original (structural sharing), but registrations and edits on either never affect the other. Externalization hints and retained circuit text carry over, so both documents preserve their loaded layout at save time.
- Returns:
An independent document with equal content.
- Return type:
- property register_template: RegisterTemplate¶
The register template composed of the per-block and global tiers.
- property data_qreg: RegisterTemplateEntry¶
The auto-seeded data-register template entry.
Shortcut for the per-code-block tier’s data-register entry; its size tracks the code’s physical-qubit count.
- template_entry(name)¶
Return the template entry registered under
name.Looks across both template tiers, the auto-seeded data-register entry included; template names are unique across tiers, so the name identifies the entry.
- emit_data_register()¶
Return the data quantum register built from its template entry.
The document holds exactly one data register; its
sizeandnamecome from the auto-seeded data-register template entry.- Returns:
- The data register built from the entry’s
sizeandname.
- Return type:
QuantumRegister
- emit_ancilla_register(register)¶
Return the ancilla quantum register identified by
register.Resolves the register’s name (
registerwhen astr, else itsname), looks it up among the ancilla register templates across both tiers, and builds the qiskit register from the registered entry.- Parameters:
register (str | RegisterTemplateEntry) – The register’s name, or its template entry.
- Returns:
- The register built from the registered entry’s
sizeandname.
- Return type:
QuantumRegister
- Raises:
KeyError – If no ancilla register template carries the resolved name, including when it names a register of another kind (the entry form resolves via its name, so the same
KeyErrorapplies).ValueError – If the supplied
RegisterTemplateEntry’s name is registered but the entry does not equal the registered one (a stale or foreign entry is not silently accepted).
- emit_classical_register(register)¶
Return the classical register identified by
register.Resolves the register’s name (
registerwhen astr, else itsname), looks it up among the classical register templates across both tiers, and builds the qiskit register from the registered entry.- Parameters:
register (str | RegisterTemplateEntry) – The register’s name, or its template entry.
- Returns:
- The register built from the registered entry’s
sizeandname.
- Return type:
ClassicalRegister
- Raises:
KeyError – If no classical register template carries the resolved name, including when it names a register of another kind (the entry form resolves via its name, so the same
KeyErrorapplies).ValueError – If the supplied
RegisterTemplateEntry’s name is registered but the entry does not equal the registered one (a stale or foreign entry is not silently accepted).
- property operations: Mapping[str, OperationSet]¶
The operation sets, keyed by each set’s
operations_key.One entry per operation type, each an
OperationSetholding that type’s variants.
- property state_preparations: StatePreparationSet¶
State-preparation variants grouped by target logical state.
- property data_measurements: DataMeasurementSet¶
Data-measurement variants grouped by measurement basis.
- property syndrome_measurements: SyndromeMeasurementSet¶
The single group of syndrome-measurement variants.
- property logical_gates: LogicalGateSet¶
Logical-gate variants addressed by gate name and operand signature.
Resolve a gate name and operand signature to a single variant with
LogicalGateSet.find.
- property logical_measurements: LogicalMeasurementSet¶
Logical-measurement variants addressed by observable and operand signature.
Resolve an observable and operand signature to a single variant with
LogicalMeasurementSet.find.
- property error_correction_cycles: VariantGroup[ECCycleVariant]¶
The error-correction-cycle variants.
- property decoder_config: Mapping[str, DecoderEntry]¶
Decoder configuration declarations keyed by slug, in registration order.
- property qubit_layout: QubitLayout | None¶
The layout section, or
Nonewhile unset.
- property properties: Properties | None¶
The provenance-metadata section, or
Nonewhile unset.
- add_ancilla_register_template(entry: RegisterTemplateEntry, *, scope: Literal['block', 'global'] = 'block') RegisterTemplateEntry¶
- add_ancilla_register_template(*, name: str, size: int, purpose: RegisterPurpose | None = None, purpose_description: str | None = None, scope: Literal['block', 'global'] = 'block') RegisterTemplateEntry
Register a persistent ancilla quantum-register declaration.
Accepts either a pre-built
RegisterTemplateEntryor its fields as keywords. The registered entry becomes available for operation variants to inherit as a declaration target. A block-scoped entry is instantiated once per code block; a global entry exists once, shared across blocks.- Parameters:
entry (RegisterTemplateEntry | None) – Entry to register, or
Nonewhen the fields are passed as keywords.name (str) – Register name, in the keyword form.
size (int) – Number of qubits, in the keyword form.
purpose (RegisterPurpose | None) – Purpose classification, in the keyword form.
purpose_description (str | None) – Free-form purpose description, in the keyword form.
scope (Literal["block", "global"]) – The template tier the entry joins.
- Returns:
The registered entry.
- Return type:
- Raises:
ValueError – If
entryis given alongside any field keyword.QECXAuthoringError – If the entry’s name is already declared anywhere in the template (the automatically seeded data register included); or if the entry’s purpose is not valid for an ancilla register.
- add_classical_register_template(entry: RegisterTemplateEntry, *, scope: Literal['block', 'global'] = 'block') RegisterTemplateEntry¶
- add_classical_register_template(*, name: str, size: int, purpose: RegisterPurpose | None = None, purpose_description: str | None = None, scope: Literal['block', 'global'] = 'block') RegisterTemplateEntry
Register a persistent classical-register declaration.
Accepts either a pre-built
RegisterTemplateEntryor its fields as keywords. The registered entry declares classical state retained and reused across operation invocations. A block-scoped entry is instantiated once per code block; a global entry exists once, shared across blocks.- Parameters:
entry (RegisterTemplateEntry | None) – Entry to register, or
Nonewhen the fields are passed as keywords.name (str) – Register name, in the keyword form.
size (int) – Number of classical bits, in the keyword form.
purpose (RegisterPurpose | None) – Purpose classification, in the keyword form.
purpose_description (str | None) – Free-form purpose description, in the keyword form.
scope (Literal["block", "global"]) – The template tier the entry joins.
- Returns:
The registered entry.
- Return type:
- Raises:
ValueError – If
entryis given alongside any field keyword.QECXAuthoringError – If the entry’s name is already declared anywhere in the template (the automatically seeded data register included); or if the entry’s purpose is not valid for a classical register.
- add_operation(variant, *, make_default=False, externalize=None)¶
Register an operation variant under its derived group.
One method for all operation kinds: the variant’s own key fields (target state, measurement basis, gate or observable with operand tuple, or membership in the single syndrome-measurement group) derive the group it registers under. The first variant registered in a group becomes the group default. Citations follow the register-if-new, verify-if-known rule: a cited reference with a new key joins the bibliography, one with a known key must equal the stored entry.
- Parameters:
variant (OperationVariant) – The variant to register: an instance of one of the kind classes.
make_default (bool) – Make this variant the group default;
Falsenever unsets an existing default.externalize (bool | None) – Hint deciding whether the variant’s stored circuit text becomes a separate archive member when the document is saved;
Nonedefers to the save-time layout mode.
- Returns:
variant, now the registered variant of its group.- Return type:
- Raises:
QECXAuthoringError – If the variant’s group already holds a variant with its name; if an inherited declaration’s target is not a registered template entry; if a state-preparation, reset, or data-measurement variant declares no inherited data register; if a state key’s length does not equal the code’s logical-qubit count; if an operand addresses a logical qubit at or beyond the code’s logical-qubit count, or an all-wildcard block’s operands do not number exactly that count; if a data-measurement result register’s size does not equal the code’s physical-qubit count; if a readout declaration’s source is not valid for the document’s code type; if a syndrome register’s size does not equal the number of addressed syndrome operators, or one of its indices reaches past its source; if a transversal readout register’s size does not equal the number of qubits it reads, a qubit it reads lies outside the code’s physical qubits, one of its indices reaches past its source, or a declared operator acts on a qubit it does not read; if a logical-gate or logical-measurement variant resolves to the same gate name or observable and the same canonical operand signature (operand block ranks and pinned logical qubits, operand roles ignored) as a distinct already-registered group; or if a citation carries a key already registered with different content.
- add_error_correction_cycle_variant(variant: ECCycleVariant, *, make_default: bool = False) ECCycleVariant¶
- add_error_correction_cycle_variant(*, name: str, steps: Sequence[ECCycleStep], repeat: int | ScalarRef = 1, fault_tolerant: bool | None = None, description: str | None = None, references: Sequence[Reference] = (), make_default: bool = False) ECCycleVariant
Register an error-correction-cycle variant.
Accepts either a pre-built
ECCycleVariantor its fields as keywords. The first variant registered becomes the section default. Every step’s measurement must be a registered syndrome-measurement variant (by identity). Citations follow the register-if-new, verify-if-known rule ofadd_operation().- Parameters:
variant (ECCycleVariant | None) – The cycle variant to register, or
Nonewhen the fields are passed as keywords.name (str) – Variant name, in the keyword form.
steps (Sequence[ECCycleStep]) – Ordered measurement steps, in the keyword form.
repeat (int | ScalarRef) – Number of times the step sequence repeats, in the keyword form.
fault_tolerant (bool | None) – Fault-tolerance claim, in the keyword form.
description (str | None) – Human-readable summary, in the keyword form.
references (Sequence[Reference]) – Citations attached to the variant, in the keyword form.
make_default (bool) – Make this variant the section default;
Falsenever unsets an existing default.
- Returns:
The registered cycle variant.
- Return type:
- Raises:
ValueError – If
variantis given alongside any field keyword.QECXAuthoringError – If a cycle variant with the variant’s name is already registered; if a step’s measurement is not a registered syndrome-measurement variant; if a parametric repeat does not address a positive-integer field of the document; or if a citation carries a key already registered with different content.
- add_decoder(entry: DecoderEntry) DecoderEntry¶
- add_decoder(*, slug: str, parameters: Mapping[str, object] = _UNSET, tags: Sequence[DecoderTag] = _UNSET) DecoderEntry
Register a syndrome-decoder declaration.
Accepts either a pre-built
DecoderEntryor its fields as keywords. The entry’s presence in the document is itself the capability declaration. A slug the validator does not recognize is accepted; decoder-specific checks then cannot run for it. Tag references into the document (override variants and their syndrome registers) must already be registered.- Parameters:
entry (DecoderEntry | None) – The decoder declaration to register, or
Nonewhen the fields are passed as keywords.slug (str) – Short decoder name, in the keyword form.
parameters (Mapping[str, object]) – Global decoder settings, in the keyword form.
tags (Sequence[DecoderTag]) – Per-detector tags, in the keyword form.
- Returns:
The registered decoder entry.
- Return type:
- Raises:
ValueError – If
entryis given alongside any field keyword.QECXAuthoringError – If a decoder with the entry’s slug is already registered; if a tag’s source is not a valid syndrome source for the document’s code type; if a tag’s literal value list does not match its source’s syndrome-operator count or its register’s size; or if an override references a syndrome-measurement variant that is not registered, or a classical register that variant’s
syndrome_cregsdoes not list.
- add_decoder_tag(slug: str, tag: DecoderTag) DecoderEntry¶
- add_decoder_tag(slug: str, *, name: str, by_source: Mapping[SyndromeSource, Sequence[object | ScalarRef] | SequenceRef] = _UNSET, overrides: Mapping[SyndromeMeasurementVariant, Mapping[ClassicalRegister, Sequence[object | ScalarRef] | SequenceRef]] = _UNSET) DecoderEntry
Register one per-detector tag on an already-declared decoder.
Accepts either a pre-built
DecoderTagor its fields as keywords, after the requiredslug. Convenience form of rebuilding the decoder entry: the stored entry is replaced by one additionally carrying the tag, which becomes the entry registered underslug.- Parameters:
slug (str) – Slug of the decoder receiving the tag.
tag (DecoderTag | None) – The tag to attach, or
Nonewhen the tag’s fields are passed as keywords.name (str) – Tag name, in the keyword form.
by_source (Mapping[SyndromeSource, ...]) – Source-anchored values, in the keyword form (see
DecoderTag).overrides (Mapping[SyndromeMeasurementVariant, ...]) – Per-variant refinements, in the keyword form (see
DecoderTag).
- Returns:
The rebuilt entry, now registered under
slug.- Return type:
- Raises:
ValueError – If
tagis given alongside any field keyword.QECXAuthoringError – If
slugis not a registered decoder; if the decoder already carries a tag with the tag’s name; or on any violation of the tag reference and length checks ofadd_decoder().
- add_reference(ref: Reference) Reference¶
- add_reference(*, key: str, title: str | None = None, doi: str | None = None, arxiv: str | None = None, url: str | None = None, note: str | None = None, authors: str | None = None, year: int | None = None) Reference
Register a bibliography entry.
Accepts either a pre-built
Referenceor its fields as keywords. Registration order is the document’s bibliography order; by convention the first registered entry is the primary, code-defining reference. Entries may also be registered implicitly by the citation-carrying registration methods; use this method to control ordering or to register entries no variant cites. Registering an entry equal to an already registered one is accepted and leaves the bibliography unchanged. An equal resubmission is a no-op because a reference is identified by its citation key alone under the register-if-new, verify-if-known rule; a decoder slug and an operation’s(kind, keys, name)are instead unique identifiers, so re-registering under one already taken is a conflict.- Parameters:
- Returns:
The registered entry; the pre-existing equal one on an idempotent resubmission.
- Return type:
- Raises:
ValueError – If
refis given alongside any field keyword.QECXAuthoringError – If a differing entry with the same key is already registered (the message names the key).
- set_qubit_layout(layout)¶
Set the layout section, replacing any previous layout.
The edit is atomic: on failure the document is untouched.
Noneclears the layout section. The replaced section leaves the document, its externalization hints with it;update_qubit_layout()carries same-named hints over.- Parameters:
layout (QubitLayout | None) – The layout section to store;
Noneclears it.- Raises:
QECXAuthoringError – If a placement of
layoutis keyed by a template entry that is not registered.
- update_qubit_layout(**fields)¶
Rewrite named fields of the layout section.
Convenience patch over
set_qubit_layout(): unnamed fields keep their stored values, and the rebuilt section replaces the stored one atomically. Externalization hints of payloads the rebuilt section also carries follow it.- Parameters:
**fields (object) –
QubitLayoutfield names mapped to their new values.- Returns:
The new layout section object.
- Return type:
- Raises:
QECXAuthoringError – If a name in
fieldsis not aQubitLayoutfield, or on any violation of the construction or context checks by the rebuilt section.
- set_qubit_placement(entry, placement)¶
Record where one template entry’s qubits or bits sit in the layout.
Convenience form of rebuilding the layout section: placements accumulate per entry, and calling again for the same entry replaces that entry’s placement only.
- Parameters:
entry (RegisterTemplateEntry) – Registered template entry the placement belongs to.
placement (CellPlacement | CoordinatePlacement) – Where each qubit or bit of the entry’s register sits.
- Raises:
QECXAuthoringError – If
entryis not a registered template entry; if a cell placement is recorded without a stored cell complex; if the placement’s number of entries does not equal the entry’s size; if a cell placement addresses an element index out of range for its cell type; or if a coordinate placement’s tuple arity disagrees with the stored embedding’s dimension.
- set_properties(props)¶
Set the properties section, replacing any previous properties.
Noneclears the properties section. The replaced section leaves the document, its externalization hints with it;update_properties()carries same-named hints over.- Parameters:
props (Properties | None) – The provenance metadata to store;
Noneclears it.
- update_properties(**fields)¶
Rewrite named fields of the properties section.
Convenience patch over
set_properties(): unnamed fields keep their stored values, and the rebuilt section replaces the stored one atomically. An unset properties section is patched from an empty one. Externalization hints of payloads the rebuilt section also carries follow it.- Parameters:
**fields (object) –
Propertiesfield names mapped to their new values.- Returns:
The new properties section object.
- Return type:
- Raises:
QECXAuthoringError – If a name in
fieldsis not aPropertiesfield, or the rebuilt section fails its construction checks.
- set_code_name(code_name)¶
Set the code name, replacing any previous name.
- update_code_data(**fields)¶
Rewrite named fields of the code-data section within its code class.
Convenience patch over
replace_code_data()for same-class changes: unnamed fields keep their stored values, and the rebuilt code object replaces the stored one atomically. Optional authored fields such as the subsystem codes’declared_H_X/declared_H_Z/declared_stabilizer_generatorsare ordinary fields, so they too are preserved unless named infields.- Parameters:
**fields (object) – Field names of the stored code class mapped to their new values.
- Returns:
The new code data object.
- Return type:
- Raises:
QECXAuthoringError – If a name in
fieldsis not a field of the stored code class, or on any failure ofreplace_code_data()for the rebuilt object.
- replace_code_data(new_code_data)¶
Replace the algebraic code data, revalidating its dependents.
The replacement may change the code class. The auto-seeded data-register entry is rebuilt when the physical-qubit count changes, cascading into its referrers; everything sized or keyed by the code (state keys, operand indices, readout sources, readout register sizes, qubits and indices, parametric references into the code section) is re-checked against the new object. The edit is atomic: on failure the document is untouched. The previous code object and author-held variables for it go stale. The code name is preserved across the replacement;
set_code_name()changes it.- Parameters:
new_code_data (CodeData) – The new code section.
- Returns:
new_code_data, now the stored code section.- Return type:
- Raises:
QECXAuthoringError – If registered content is inconsistent with
new_code_data: a state key length, operand index, result-register size, readout source, or readout register size, qubit, index or coverage disagrees with it, or a parametric reference addresses a code field it does not have.
- replace_template_entry(old, new)¶
Replace a template entry, cascade-rewriting its referrers.
Every referrer of
oldis rebuilt to referencenew: inherited declarations targeting the entry, the variants holding those declarations, the cycle steps and decoder overrides referencing those variants, and the entry’s recorded placement. References are rewritten, content never. The edit is atomic: on failure the document is untouched.old, its rebuilt referrers, and author-held variables for them go stale; re-read them from the document.- Parameters:
old (RegisterTemplateEntry) – The registered entry to replace.
new (RegisterTemplateEntry) – Its replacement.
- Returns:
new, now the registered entry.- Return type:
- Raises:
QECXAuthoringError – If
oldis not a registered template entry; ifoldis the auto-seeded data-register entry, which onlyreplace_code_data()rebuilds; or on any violation of the registration checks bynewor by a rebuilt referrer.
- replace_operation(old, new)¶
Replace an operation variant, cascade-rewriting its referrers.
newpasses the same checks asadd_operation(), and its own key fields decide the group it registers under. Referrers ofold(cycle steps and decoder overrides, for a syndrome-measurement variant) are rebuilt to referencenew; references are rewritten, content never: the variant’s internals are exactly whatnewsupplies. The edit is atomic: on failure the document is untouched.old, its rebuilt referrers, and author-held variables for them go stale; re-read them from the document.- Parameters:
old (OperationVariant) – The registered variant to replace.
new (OperationVariant) – Its replacement.
- Returns:
new, now the registered variant.- Return type:
- Raises:
QECXAuthoringError – If
oldis not a registered variant, or on any violation of theadd_operation()checks bynewor of the registration checks by a rebuilt referrer.
- replace_error_correction_cycle_variant(old, new)¶
Replace an error-correction-cycle variant.
newpasses the same checks asadd_error_correction_cycle_variant(). The edit is atomic: on failure the document is untouched.oldand author-held variables for it go stale; re-read the variant from the document.- Parameters:
old (ECCycleVariant) – The registered variant to replace.
new (ECCycleVariant) – Its replacement.
- Returns:
new, now the registered variant.- Return type:
- Raises:
QECXAuthoringError – If
oldis not a registered cycle variant, or on any violation of theadd_error_correction_cycle_variant()checks bynew.
- replace_decoder(slug, new)¶
Replace the decoder entry registered under
slug.newpasses the same checks asadd_decoder(). The edit is atomic: on failure the document is untouched.- Parameters:
slug (str) – Slug of the registered entry to replace.
new (DecoderEntry) – Its replacement.
- Returns:
new, now the registered entry.- Return type:
- Raises:
QECXAuthoringError – If
slugis not a registered decoder; ifnew.slugdiffers fromslug; or on any violation of theadd_decoder()checks bynew.
- replace_reference(old, new)¶
Replace a bibliography entry, cascade-rewriting its citers.
Every variant citing
oldis rebuilt to citenewin its place; the bibliography position is retained. The edit is atomic: on failure the document is untouched.old, its rebuilt citers, and author-held variables for them go stale; re-read them from the document.- Parameters:
- Returns:
new, now the registered entry.- Return type:
- Raises:
QECXAuthoringError – If
oldis not a registered bibliography entry, or the key ofnewcollides with an already registered entry other thanold.
- remove_template_entry(entry)¶
Remove a template entry that nothing references.
Removal raises while the entry is referenced by an inherited declaration or a recorded placement. The auto-seeded data-register entry is structurally required and cannot be removed.
- Parameters:
entry (RegisterTemplateEntry) – The registered entry to remove.
- Raises:
QECXAuthoringError – If
entryis not a registered template entry; if it is the auto-seeded data-register entry; or if it is still referenced (the message names the referrers).
- remove_operation(variant)¶
Remove an operation variant that nothing references.
Removal raises while the variant is referenced (cycle steps and decoder overrides, for a syndrome-measurement variant).
- Parameters:
variant (OperationVariant) – The registered variant to remove.
- Raises:
QECXAuthoringError – If
variantis not a registered variant, or it is still referenced (the message names the referrers).
- remove_error_correction_cycle_variant(variant)¶
Remove an error-correction-cycle variant.
- Parameters:
variant (ECCycleVariant) – The registered variant to remove.
- Raises:
QECXAuthoringError – If
variantis not a registered cycle variant.
- remove_decoder(slug)¶
Remove the decoder entry registered under
slug.- Parameters:
slug (str) – Slug of the registered entry to remove.
- Raises:
QECXAuthoringError – If
slugis not a registered decoder.
- remove_reference(ref)¶
Remove a bibliography entry that nothing cites.
Removal raises while the entry is cited by a registered variant.
- Parameters:
ref (Reference) – The registered entry to remove.
- Raises:
QECXAuthoringError – If
refis not a registered bibliography entry, or it is still cited (the message names the citing variants).
- remove_qubit_placement(entry)¶
Remove one template entry’s recorded placement.
Convenience form of rebuilding the layout section without that placement.
- Parameters:
entry (RegisterTemplateEntry) – Entry whose placement is removed.
- Raises:
QECXAuthoringError – If no placement is recorded for
entry.
- set_default(variant)¶
Make a registered variant its group’s default.
The group is inferred from the variant object: its kind and key fields identify the group, and the variant must be the registered object of that group (identity, not name equality).
- Parameters:
variant (OperationVariant | ECCycleVariant) – The registered variant to promote.
- Raises:
QECXAuthoringError – If
variantis not a registered variant of its group.
- missing()¶
Return the document’s unmet completeness requirements.
Completeness rules run only at the document-validation points; this method is their preview while authoring.
- Returns:
One finding per unmet completeness requirement, in document order; empty exactly when save-time validation’s completeness check passes.
- Return type:
tuple[ValidationError, …]
- validate()¶
Run the full document-level rule engine and return every finding.
One of the three document-validation points: the document’s dict form runs through the complete rule set, completeness included. The engine is authoritative: its findings outrank every construction-time and per-method check. Findings are returned, not raised.
- Returns:
All findings in document order; empty for a valid, complete document.
- Return type:
tuple[ValidationError, …]
- view(config=None, **overrides)¶
Return a viewer over the document for display methods.
Renders through the dict-level bridge of
to_qecx_file(), which runs no validation, so partial documents render. The viewer’s settings start fromconfigwhen given, otherwise fromDEFAULT_VIEWER_CONFIGas currently set, withoverridesapplied on top. The viewer holds a newViewerConfig: neitherconfignorDEFAULT_VIEWER_CONFIGis modified, and later changes to either do not reach the returned viewer.- Parameters:
config (ViewerConfig | None) – Base settings for the viewer.
None(default) usesDEFAULT_VIEWER_CONFIG.**overrides (Any) – Viewer settings for this call, keyed by
ViewerConfigfield name (for examplecircuit_mode="text").
- Returns:
Viewer over the document’s current content.
- Return type:
- Raises:
TypeError – If a key of
overridesis not aViewerConfigfield.
- to_qecx_file()¶
Return the document’s dict-level view.
The viewer bridge; it runs no validation, so partial documents convert and mid-authoring content can be rendered. The returned object holds an independent dict; mutating it never affects this document.
- Returns:
Dict-level view of the document.
- Return type:
- to_dict()¶
Return the document as a fully resolved document dict.
The dict is JSON-shaped and independent: mutating it never affects the document. It carries the format version
CURRENT_QECX_VERSION, whatever version a loaded source declared. For a document whosevalidate()run finds no error,from_dict()reconstructs the dict into an equal document. Parametric references serialize raw, and the creator stamp applied at save time is absent.
- dumps()¶
Return the document as inline JSON text.
Serializes the complete document after the same validation and stamping as
save(): completeness plus the full rule engine run first, error findings raise, each warning finding is emitted as a Python warning, and the creator stamp is applied. Every payload is written inline, whatever its disposition;dump_qecx()withlayout="inline"is the corresponding module-level writer.- Returns:
Inline JSON text of the complete document.
- Return type:
- Raises:
QECXValidationFailedError – If the document is incomplete, or validation produced one or more error-severity findings; the completeness findings match those
missing()returns.
- set_externalization(element, payload, externalize)¶
Hint whether one payload of an element becomes its own archive member.
The hint decides where the payload sits when the document is saved under
layout="preserve"; the layout mode decides for a payload carrying no hint.add_operation()records the same hint for a variant’s circuit text at registration.One payload holds another wherever the document places the other’s value inside its own, across elements as well: a bibliography entry sits inside the properties section. Hints that disagree never stand inside each other, and a call maintains that: hinting a payload drops the hints of the payloads it holds, and hinting one payload inside a hinted wider one, or clearing that payload’s hint, first carries the wider hint’s value onto the payloads it stops covering (a member path carries as
True). Content of the wider payload that is no payload of its own takes no value over: it stays inline while a hint stands inside it.- Parameters:
element (OperationVariant | CodeData | QubitLayout | ECCycleVariant | DecoderEntry | Properties | Reference) – The document’s element carrying the payload.
payload (str) – Name of the payload: a field of
element, the fields reaching a nested one joined by dots, or"."for the element as a whole.externalize (bool | None) –
Trueto place the payload in its own archive member,Falseto keep it inline,Noneto clear the hint and leave the payload to the save-time layout mode.
- Raises:
QECXAuthoringError – If
elementis not part of this document, orpayloadis not one ofelement’s payloads.
- property externalized: Mapping[OperationVariant | CodeData | QubitLayout | ECCycleVariant | DecoderEntry | Properties | Reference, Mapping[str, str | bool]]¶
Read-only view of the document’s externalization hints.
Keys are the document’s hinted externalizable elements, looked up by identity: an equal but distinct object is not found. Each value maps the element’s hinted payload names to the archive member path the payload was read from,
Falsefor a payload the loaded document carried inline, or the boolean an author supplied. Saving underlayout="preserve"reproduces that layout.
- save(target, *, layout='preserve', auto_threshold_bytes=_AUTO_THRESHOLD_BYTES, force_archive=False)¶
Validate, stamp, and write the document.
Every save validates: completeness plus the full rule engine run first, error findings raise, and each warning finding is emitted as a Python warning. The written document carries the format version from
CURRENT_QECX_VERSIONand, when the properties section sets no creator, a creator stamped fromqecx_creator();uuidandcreated_dateare never generated automatically, so saving identical content twice yields identical documents. A variant created byload()re-saves its circuit fragment byte for byte.dump_qecx()is the corresponding module-level writer.- Parameters:
target (str | Path | BinaryIO | BufferedIOBase) – Destination path, or a writable binary stream such as an open file or an
io.BytesIO; an existing file is overwritten.layout (Literal["preserve", "inline", "auto", "external"]) – Where the document’s externalizable payloads go.
"preserve"writes each payload where it sat, an undecided one following the document’s prevailing style: inline for a document whose payloads all record as inline, the automatic decision otherwise."inline"writes every payload into the document."auto"decides every payload on its size, externalizing the ones aboveauto_threshold_bytes."external"writes every payload holding content to a member of its own. The payloads are the fields holding unbounded collection content, an element the format gives no such field being one payload as a whole; a payload the document records or hints at a wider granularity is written at that granularity under every mode, the payloads inside it riding along. A payload with no content never becomes a member, and a payload staying external keeps the member path it was read from. The envelope follows the outcome: a ZIP archive when at least one payload becomes a member, inline JSON text otherwise.auto_threshold_bytes (int) – Payload size from which an automatic decision externalizes, in bytes of the serialized payload.
force_archive (bool) – Write the ZIP envelope even when no payload becomes a member; with
layout="inline"that writes an archive carrying the manifest alone.
- Raises:
QECXValidationFailedError – If the document is incomplete, or validation produced one or more error-severity findings; the completeness findings match those
missing()returns.