Skip to content

loqs.core.instructions.builders

Functions to construct common Instruction objects.

Each function documents both how to use it, as well as providing the following information about the created Instruction:

  • The apply function
    • The parameters it pulls, including the typical source
    • What keys are in the returned Frame
  • The map qubits function (if needed)
  • The parameter priorities (if not default)
  • The parameter aliases (if provided)

If information is omitted, it is implied to be the default.

Functions

  • The apply function
    • The parameters it pulls, including the typical source
    • What keys are in the returned Frame
  • The map qubits function (if needed)
  • The parameter priorities (if not default)
  • The parameter aliases (if provided)

If information is omitted, it is implied to be the default.

build_composite_instruction

build_composite_instruction(instructions: Sequence[InstructionLabelLike], extra_data: KwargDict | None = None, name: str = '(Unnamed composite instruction)') -> Instruction

Build a composite instruction that updates the stack.

The composite instruction holds a sequence of instructions that will be inserted into the stack. It is primarily intended for convenience and organization purposes, i.e. being able to define instructions in small modular pieces but still providing a high-level sequence of instructions via the composite instruction.

The apply function takes:

  • stack, usually from the QuantumProgram
  • instructions, usually from the data
  • any other kwarg a nested instruction needs (e.g. patch_label, patch_labels, model), pulled up from the nested instructions' own declared parameters -- see the param_priorities construction below

It returns a Frame where instructions have been inserted onto the front of InstructionStack stored at "stack".

There is a map qubits function, which calls the map qubits functions for the underlying instructions.

Parameters:

Name Type Description Default
instructions Sequence[InstructionLabelLike]

A list of instructions or instruction labels to be inserted onto the stack

required
name str

Name for logging purposes

'(Unnamed composite instruction)'

Returns:

Type Description
The built composite instruction

Examples:

>>> from loqs.core.instructions import InstructionStack
>>> from loqs.core.instructions.builders import build_composite_instruction
>>> inst = build_composite_instruction(
...     instructions=[("DummyGate1", "L0"), ("DummyGate2", "L0")],
...     name="Composite"
... )
>>> stack = InstructionStack([])
>>> f = inst.apply(stack=stack, instructions=inst.data["instructions"])
>>> f_stack = f["stack"]
>>> len(f_stack)
2
>>> f_stack[0]["instruction"]
'DummyGate1'
>>> f_stack[1]["instruction"]
'DummyGate2'

  • The apply function
    • The parameters it pulls, including the typical source
    • What keys are in the returned Frame
  • The map qubits function (if needed)
  • The parameter priorities (if not default)
  • The parameter aliases (if provided)

If information is omitted, it is implied to be the default.

build_lookup_decoder_instruction

build_lookup_decoder_instruction(lookup_table: Mapping[str, str], syndrome_labels: Sequence[SyndromeLabelLike], raw_syndrome_frame_key: str, diff_prev_syndrome: bool = True, name: str = '(Unnamed lookup decoder)') -> Instruction

Build a lookup table decoder instruction.

The lookup table decoder instruction takes a lookup table with syndrome keys and correction values and a sequence of SyndromeLabel objects so that it can pull the syndrome from previous measurement outcomes. It then applies a Pauli frame update to the relevant patch.

The apply function takes:

  • patch_label, usually from the InstructionLabel
  • lookup_table, usually from the Instruction.data
  • syndrome_labels, usually from the Instruction.data
  • raw_syndrome_frame_key, usually from the Instruction.data
  • diff_prev_syndrome, usually from the Instruction.data
  • patches, usually from the previous frame
  • syndrome_outcomes, an alias for measurement_outcomes from the previous frames
  • history, usually from the QuantumProgram

It returns a Frame with a PatchLayout that has an updated PauliFrame, the raw syndrome, and some other debugging information.

There is a map qubits function, which maps the syndrome_labels.

There is a non-standard parameter priority for syndrome_labels, as this can require more than just the previous single frame.

Parameters:

Name Type Description Default
lookup_table Mapping[str, str]

A dict with syndrome keys (as strings of "0" and "1") and data corrections (as Pauli strings with entries "IXYZ" and length = number of data qubits).

required
syndrome_labels Sequence[SyndromeLabelLike]

List of SyndromeLabels (or tuples to be cast as SydromeLabels) that describe which entries in the previous measurement outcomes correspond to which syndrome bit

required
raw_syndrome_frame_key str

The key to use in the output Frame for the raw syndrome information, as well as the key used when searching for previous syndrome information.

required
diff_prev_syndrome bool

Whether to do a bitwise XOR to the previous syndrome (True, default) or to use this round's syndrome information directly (False).

True
name str

Name for logging purposes

'(Unnamed lookup decoder)'

Returns:

Type Description
The built lookup table decoder instruction

Examples:

>>> from loqs.core import History, QECCode
>>> from loqs.core.recordables import PatchLayout, MeasurementOutcomes, QECCodePatch
>>> from loqs.core.instructions.builders import build_lookup_decoder_instruction
>>> inst = build_lookup_decoder_instruction(
...     lookup_table={"0": "I"},
...     syndrome_labels=[("A0", -1, 0)],
...     raw_syndrome_frame_key="raw_syn",
...     name="LookupDecoder"
... )
>>> inst.name
'LookupDecoder'
>>> code = QECCode({}, ["Q0"], ["Q0"])
>>> patch = QECCodePatch(code, ["Q0"], "I")
>>> patches = PatchLayout({"L0": patch})
>>> outcomes = MeasurementOutcomes({"A0": [0]})
>>> history = History()
>>> f = inst.apply(
...     patch_label="L0",
...     lookup_table=inst.data["lookup_table"],
...     syndrome_labels=inst.data["syndrome_labels"],
...     raw_syndrome_frame_key=inst.data["raw_syndrome_frame_key"],
...     diff_prev_syndrome=inst.data["diff_prev_syndrome"],
...     patches=patches,
...     syndrome_outcomes=outcomes,
...     history=history
... )
>>> f["decoded_error"]
'I'
>>> f["syndrome_diff"]
[0]

  • The apply function
    • The parameters it pulls, including the typical source
    • What keys are in the returned Frame
  • The map qubits function (if needed)
  • The parameter priorities (if not default)
  • The parameter aliases (if provided)

If information is omitted, it is implied to be the default.

build_object_builder_instruction

build_object_builder_instruction(frame_key: str, obj_class: type, name: str = '(Unnamed object builder)') -> Instruction

Build an instruction that can initialize LoQS objects.

LoQS This is a sort of meta-instruction that can build LoQS objects and then store them into a Frame. This is currently used primarily to initialize the BaseQuantumState if no initial_history is provided to a QuantumProgram. The constructor arguments should typically be provided in the InstructionLabel as args or kwargs.

The apply function takes variadic kwargs, since we do not know the constructor arguments until runtime. However, it takes at least the following:

  • frame_key, taken from Instruction.data
  • obj_class, taken from Instruction.data

It also must take all required args to the obj_class constructor, and returns a Frame with the constructed object stored under frame_key.

The parameter priorities are generated programatically using the inspect module for function signature introspection.

Parameters

frame_key: The key used to store the resulting object in the Frame

obj_class: The LoQS object to construct

name: Name for logging purposes

Returns
   The built object builder instruction
Examples

from loqs.core.instructions.builders import build_object_builder_instruction class MyClass: ... def init(self, x: int): ... self.x = x inst = build_object_builder_instruction( ... frame_key="my_obj", ... obj_class=MyClass, ... name="MyBuilder" ... ) inst.name 'MyBuilder' f = inst.apply(frame_key="my_obj", obj_class=MyClass, x=42) obj = f["my_obj"] obj.x 42


  • The apply function
    • The parameters it pulls, including the typical source
    • What keys are in the returned Frame
  • The map qubits function (if needed)
  • The parameter priorities (if not default)
  • The parameter aliases (if provided)

If information is omitted, it is implied to be the default.

build_patch_builder_instruction

build_patch_builder_instruction(qec_code: QECCode, name: str = '(Unnamed patch builder)') -> Instruction

Build an instruction that can make patches from a QECCode.

This is a sort of meta-instruction that can build QECCodePatch objects and then store them into the main PatchLayout. The qubit labels for the new patch should typically be provided in the InstructionLabel as kwargs.

The apply function takes:

  • new_patch_label, usually taken from InstructionLabel. Not called patch_label since this instruction is always invoked globally (routing patch_label is None) -- this names the new patch being created, not the patch the instruction itself resolves against.
  • qubits, usually taken from InstructionLabel
  • qec_code, usually taken from Instruction.data
  • patches, usually taken from the previous frame, but can be taken from Instruction.data as a default fallback

It returns a Frame with an updated patches containing the new QECCodePatch under new_patch_label.

The parameter priorities for patches are not default, because we want to prioritize a true PatchLayout from the History over the default one provided in the Instruction.data.

Parameters:

Name Type Description Default
qec_code QECCode

The QECCode to use when constructing new patches.

required
name str

Name for logging purposes

'(Unnamed patch builder)'

Returns:

Type Description
The built patch builder instruction

Examples:

>>> from loqs.core import QECCode
>>> from loqs.core.instructions.builders import build_patch_builder_instruction
>>> code = QECCode(instructions={}, template_qubits=["q0", "q1"], template_data_qubits=["q0"])
>>> inst = build_patch_builder_instruction(qec_code=code, name="PatchBuilder")
>>> inst.name
'PatchBuilder'
>>> f = inst.apply(new_patch_label="L0", qubits=["Q0", "Q1"], qec_code=code, patches=None)
>>> patches = f["patches"]
>>> "L0" in patches
True
>>> patches["L0"].qubits
['Q0', 'Q1']

  • The apply function
    • The parameters it pulls, including the typical source
    • What keys are in the returned Frame
  • The map qubits function (if needed)
  • The parameter priorities (if not default)
  • The parameter aliases (if provided)

If information is omitted, it is implied to be the default.

build_patch_permute_instruction

build_patch_permute_instruction(mapping: Mapping[str | int, str | int], name: str = '(Unnamed patch permutation)') -> Instruction

Build an instruction that permute patch qubits.

This can permute the qubits in a patch, i.e. doing SWAP operations but in software.

The apply function takes:

  • patch_label, usually taken from InstructionLabel
  • mapping, usually taken from Instruction.data
  • patches, usually taken from the previous frame

It returns a Frame with an updated patches where the QECCodePatch stored under patch_label has had the qubits mapped via mapping.

There is a map qubits function that updates both the keys and values of mapping.

Parameters:

Name Type Description Default
mapping Mapping[str | int, str | int]

The qubit mapping to apply to the code patch

required
name str

Name for logging purposes

'(Unnamed patch permutation)'

Returns:

Type Description
The built patch permuter instruction

Examples:

>>> from loqs.core import QECCode
>>> from loqs.core.recordables import PatchLayout, QECCodePatch
>>> from loqs.core.instructions.builders import build_patch_permute_instruction
>>> inst = build_patch_permute_instruction(mapping={"Q0": "Q1", "Q1": "Q0"}, name="Permuter")
>>> inst.name
'Permuter'
>>> code = QECCode({}, ["q0", "q1"], ["q0"])
>>> patch = QECCodePatch(code, ["Q0", "Q1"], "II")
>>> patches = PatchLayout({"L0": patch})
>>> f = inst.apply(patch_label="L0", mapping={"Q0": "Q1", "Q1": "Q0"}, patches=patches)
>>> f["patches"]["L0"].qubits
['Q1', 'Q0']

  • The apply function
    • The parameters it pulls, including the typical source
    • What keys are in the returned Frame
  • The map qubits function (if needed)
  • The parameter priorities (if not default)
  • The parameter aliases (if provided)

If information is omitted, it is implied to be the default.

build_patch_remover_instruction

build_patch_remover_instruction(name: str = '(Unnamed patch builder)') -> Instruction

Build an instruction that can make delete patches.

This is a sort of meta-instruction that can remove patches from the main PatchLayout. The patch label should typically be provided in the InstructionLabel as a kwarg.

The apply function takes:

  • del_patch_label, usually taken from InstructionLabel. Not called patch_label since this instruction is always invoked globally (routing patch_label is None) -- this names the patch being removed, not the patch the instruction itself resolves against.
  • patches, usually taken from the previous frame

It returns a Frame with an updated patches without the QECCodePatch under del_patch_label, and without any PatchRelation that named it (PatchLayout.__delitem__ drops these automatically -- nothing extra is needed here).

Parameters:

Name Type Description Default
name str

Name for logging purposes

'(Unnamed patch builder)'

Returns:

Type Description
The built patch remover instruction

Examples:

>>> from loqs.core import QECCode
>>> from loqs.core.recordables import PatchLayout, PatchRelation, QECCodePatch
>>> from loqs.core.instructions.builders import build_patch_remover_instruction
>>> inst = build_patch_remover_instruction(name="Remove Patch")
>>> inst.name
'Remove Patch'
>>> code = QECCode({}, ["q0"], ["q0"])
>>> patch = QECCodePatch(code, ["Q0"], "I")
>>> patches = PatchLayout({"L0": patch, "L1": code.create_patch(["Q1"])})
>>> patches.set_relation(PatchRelation({"a": "L0", "b": "L1"}))
>>> f = inst.apply(del_patch_label="L0", patches=patches)
>>> "L0" in f["patches"]
False
>>> f["patches"].relations
{}

  • The apply function
    • The parameters it pulls, including the typical source
    • What keys are in the returned Frame
  • The map qubits function (if needed)
  • The parameter priorities (if not default)
  • The parameter aliases (if provided)

If information is omitted, it is implied to be the default.

build_physical_circuit_instruction

build_physical_circuit_instruction(circuit: BasePhysicalCircuit, inplace: bool = True, model: BaseNoiseModel | None = None, pauli_frame_update: str | Sequence[str] | Mapping[str | int, str | int] | None = None, name: str = '(Unnamed physical circuit)') -> Instruction

Build an instruction that applies a physical circuit to a state.

This is the computational workhorse for LoQS. This stores a circuit that can propagate the quantum state forward in time. However, it can do some other common pre-/post-processing tasks. It can insert discrete errors into the circuit prior to application, and it can update the Pauli frame if the circuit represents the action of a Clifford gate.

The apply function takes:

  • model, usually from the QuantumProgram.default_noise_model, but also from InstructionLabel and Instruction.data
  • circuit, usually from the Instruction.data
  • state, usually from the previous frame
  • inplace, usually from the Instruction.data
  • error_injections, usually from the InstructionLabel
  • pauli_frame_update, usually from the Instruction.data
  • patch_label, usually from the InstructionLabel
  • patches, usually from the previous frame

It returns a Frame with an updated state, observed measurement_outcomes if requested, an updated patches if a PauliFrame update was requested, and some other debugging information.

There is a map qubits function calls circuit.map_qubit_labels().

Parameters:

Name Type Description Default
circuit BasePhysicalCircuit

The physical circuit to run

required
inplace bool

Whether to propagate the state in-place (True, default) or make a copy

True
model BaseNoiseModel | None

A model to use when converting the circuit into reps to apply to the state

None
pauli_frame_update str | Sequence[str] | Mapping[str | int, str | int] | None

Either a string that is passed to PauliFrame.update_from_transversal_clifford(), a list of strings that is passed to PauliFrame.update_from_clifford_conjugation(), a mapping that is passed to PauliFrame.map_frame(), or None (the default) if no Pauli frame update is required.

None
name str

Name for logging purposes

'(Unnamed physical circuit)'

Returns:

Type Description
The built physical circuit instruction

Examples:

>>> from loqs.backends import ListPhysicalCircuit as PhysCirc, DictNoiseModel, NumpyStatevectorQuantumState
>>> from loqs.backends.reps import UnitaryGateRep, ZBasisProjectionInstrumentRep
>>> from loqs.core.recordables import PatchLayout
>>> from loqs.core.instructions.builders import build_physical_circuit_instruction
>>> circ = PhysCirc(circuit=[], qubit_labels=[0, 1])
>>> inst = build_physical_circuit_instruction(circuit=circ, name="PhysCirc")
>>> inst.name
'PhysCirc'
>>> model = DictNoiseModel({}, {}, gatereps=[UnitaryGateRep], instreps=[ZBasisProjectionInstrumentRep])
>>> state = NumpyStatevectorQuantumState(2, qubit_labels=[0, 1])
>>> patches = PatchLayout()
>>> f = inst.apply(
...     model=model,
...     circuit=circ,
...     state=state,
...     inplace=True,
...     error_injections=None,
...     pauli_frame_update=None,
...     patch_label="L0",
...     patches=patches
... )
>>> complex(f["state"].state[0, 0])
(1+0j)

  • The apply function
    • The parameters it pulls, including the typical source
    • What keys are in the returned Frame
  • The map qubits function (if needed)
  • The parameter priorities (if not default)
  • The parameter aliases (if provided)

If information is omitted, it is implied to be the default.

build_repeat_until_success_instruction

build_repeat_until_success_instruction(instructions: InstructionStackLike, rus_key: str, test_frame_key: str = 'rus_success', expected: object = True, max_repeats: int = 100, name: str = '(Unnamed repeat-until-success instruction)') -> Instruction

Build an instruction that repeats a physical circuit instruction until success.

This is a special case feed-forward type of instruction. It first applies the underlying instruction (presumed to be a physical circuit instruction, although this is not actively checked), and then compares the measurement outcomes to a set of target outcomes. If the outcomes do not match, this places itself on top of the stack.

The apply function takes variadic kwargs since we do not know the underlying instruction arguments until runtime. However, it takes at least the following:

  • observed, usually from the previous frame
  • expected, usually from the Instruction.data
  • rus_key, usually from the Instruction.data
  • patch_label, usually from the InstructionLabel
  • repeat_count, usually (except first time) from the InstructionLabel
  • instructions, usually from the Instruction.data
  • max_repeats, usually from the Instruction.data
  • stack, usually from the QuantumProgram

It returns a Frame with the outcome of the underlying instruction, as well as an updated stack with a reset and this operation again in the case of failure, and some debugging information.

There is a map qubits function that maps the qubits of instruction and reset_key, in the case that reset_key is an Instruction.

Parameters:

Name Type Description Default
instruction

The underlying instruction to run and repeat until success. This should include reset to 0 as the first instruction, and the final frame should contain a success_frame_key as True if successful and False if not.

required
success_frame_key

The key to check in the final frame for success.

required
max_repeats int

The number of repeats after which an error is thrown. Defaults to 100.

100
name str

Name for logging purposes

'(Unnamed repeat-until-success instruction)'

Returns:

Type Description
The built repeat-until-success instruction

Examples:

>>> from loqs.core.instructions import InstructionStack
>>> from loqs.core.instructions.builders import build_repeat_until_success_instruction
>>> inst = build_repeat_until_success_instruction(instructions=[], rus_key="success", name="RUS")
>>> inst.name
'RUS'
>>> stack = InstructionStack([])
>>> f = inst.apply(
...     observed=True,
...     expected=True,
...     rus_key="success",
...     patch_label="L0",
...     repeat_count=1,
...     instructions=[],
...     max_repeats=10,
...     stack=stack
... )
>>> f["rus_success"]
True
>>> f["total_rus_count"]
1