Skip to content

lowering

Lowering dataclass

Lowering()

lower

lower(
    sym_name: str,
    noise_model: NoiseModel,
    return_qreg: bool = False,
) -> ir.Method

Lower the noise model to a method.

Parameters:

Name Type Description Default
name str

The name of the method to generate.

required
return_qreg bool

Use the quantum register as the return value.

False

Returns:

Name Type Description
Method Method

The generated kirin method.

Source code in .venv/lib/python3.12/site-packages/bloqade/qbraid/lowering.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def lower(
    self,
    sym_name: str,
    noise_model: schema.NoiseModel,
    return_qreg: bool = False,
) -> ir.Method:
    """Lower the noise model to a method.

    Args:
        name (str): The name of the method to generate.
        return_qreg (bool): Use the quantum register as the return value.

    Returns:
        Method: The generated kirin method.

    """
    self.process_noise_model(noise_model, return_qreg)
    block = ir.Block(stmts=self.block_list)
    ret_type = qasm2.types.QRegType if return_qreg else qasm2.types.CRegType
    block.args.append_from(types.MethodType[[], ret_type], name=f"{sym_name}_self")
    region = ir.Region(block)
    func_stmt = func.Function(
        sym_name=sym_name,
        signature=func.Signature(inputs=(), output=qasm2.types.QRegType),
        body=region,
    )

    mt = ir.Method(
        mod=None,
        py_func=None,
        sym_name=sym_name,
        dialects=qbraid_noise,
        code=func_stmt,
        arg_names=[],
    )
    qbraid_noise.run_pass(mt)  # type: ignore
    return mt

schema

CZ

Bases: Operation

A CZ gate operation.

Fields

op_type (str): The type of operation (Literal["CZ"]). participants (Tuple[Union[Tuple[int], Tuple[int, int]], ...]): The qubit indices that are participating in the CZ gate.

CZError

Bases: ErrorOperation[ErrorModelType]

CZError operation.

Fields

survival_prob (Tuple[float, ...]): The survival probabilities for each qubit. error_type (str): The type of error (Literal["CZError"]). storage_error (ErrorModelType): The error model for storage. entangled_error (ErrorModelType): The error model for entangled qubits. single_error (ErrorModelType): The error model for single qubits.

ErrorModel

Bases: BaseModel

Base class for error models.

ErrorOperation

Bases: BaseModel, Generic[ErrorModelType]

Base class for error operations.

GateEvent

Bases: BaseModel, Generic[ErrorModelType]

A gate event.

Fields

error (Union[SingleQubitError[ErrorModelType], CZError[ErrorModelType]]): The error model for the gate event. operation (OperationType): The operation for the gate event.

GlobalRz

Bases: Operation

GlobalRz operation.

Fields

op_type (str): The type of operation (Literal["GlobalRz"]). phi (float): The angle of rotation.

GlobalW

Bases: Operation

GlobalW operation.

Fields

op_type (str): The type of operation (Literal["GlobalW"]). theta (float): The angle of rotation. phi (float): The angle of rotation.

LocalRz

Bases: Operation

LocalRz operation.

Fields

op_type (str): The type of operation (Literal["LocalRz"]). participants (Tuple[int, ...]): The qubit indices that are participating in the local Rz gate. phi (float): The angle of rotation.

LocalW

Bases: Operation

LocalW operation.

Fields

op_type (str): The type of operation (Literal["LocalW"]). participants (Tuple[int, ...]): The qubit indices that are participating in the local W gate. theta (float): The angle of rotation. phi (float): The angle of rotation.

Measurement

Bases: Operation

Measurement operation.

Fields

op_type (str): The type of operation (Literal["Measurement"]). measure_tag (str): The tag to use for the measurement. participants (Tuple[int, ...]): The qubit indices that are participating in the measurement.

NoiseModel

Bases: BaseModel, Generic[ErrorModelType]

Noise model for a circuit.

Fields

all_qubits (Tuple[int, ...]): The qubit indices for the noise model. gate_events (List[GateEvent[ErrorModelType]]): The gate events for the noise model.

num_qubits property

num_qubits: int

Return the number of qubits in the noise model.

decompiled_circuit

decompiled_circuit() -> str

Clean the circuit of noise.

Returns:

Name Type Description
str str

The decompiled circuit from hardware execution.

Source code in .venv/lib/python3.12/site-packages/bloqade/qbraid/schema.py
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
def decompiled_circuit(self) -> str:
    """Clean the circuit of noise.

    Returns:
        str: The decompiled circuit from hardware execution.

    """
    from bloqade.noise import native
    from bloqade.qasm2.emit import QASM2
    from bloqade.qasm2.passes import glob, parallel

    mt = self.lower_noise_model("method")

    native.RemoveNoisePass(mt.dialects)(mt)
    parallel.ParallelToUOp(mt.dialects)(mt)
    glob.GlobalToUOP(mt.dialects)(mt)
    return QASM2(qelib1=True).emit_str(mt)

lower_noise_model

lower_noise_model(sym_name: str, return_qreg: bool = False)

Lower the noise model to a method.

Parameters:

Name Type Description Default
sym_name str

The name of the method to generate.

required
return_qreg bool

Whether to return the quantum register after the method has completed execution. Useful for obtaining the full state vector.

False

Returns:

Name Type Description
Method

The generated kirin method.

Source code in .venv/lib/python3.12/site-packages/bloqade/qbraid/schema.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
def lower_noise_model(self, sym_name: str, return_qreg: bool = False):
    """Lower the noise model to a method.

    Args:
        sym_name (str): The name of the method to generate.
        return_qreg (bool): Whether to return the quantum register after the method
            has completed execution. Useful for obtaining the full state vector.

    Returns:
        Method: The generated kirin method.

    """
    from bloqade.qbraid.lowering import Lowering

    return Lowering().lower(sym_name, self, return_qreg)

Operation

Bases: BaseModel

Base class for operations.

PauliErrorModel

Bases: ErrorModel

Pauli error model.

Fields

error_model_type (str): The type of error model (Literal["PauliNoise"]). errors (Tuple[Tuple[int, Tuple[float, float, float]], ...]): The qubit indices and the error rates for each qubit.

SingleQubitError

Bases: ErrorOperation[ErrorModelType]

SingleQubitError operation.

Fields

survival_prob (Tuple[float, ...]): The survival probabilities for each qubit. error_type (str): The type of error (Literal["SingleQubitError"]). operator_error (ErrorModelType): The error model for the single qubit.

simulation_result

QuEraSimulationResult dataclass

QuEraSimulationResult(
    flair_visual_version: str,
    counts: dict[str, int],
    logs: DataFrame,
    atom_animation_state: AnimateQPUState,
    noise_model: NoiseModel,
)

Results of the QuEra hardware model simulation.

Fields

flair_visual_version (str): The version of the Flair Visual package used to generate the simulation result. counts (dict[str, int]): The measurement bitstrings of the simulation. logs (DataFrame): Grainular logs events of what happened to each atom during the simulation. atom_animation_state (vis_qpustate.AnimateQPUState): Object used to play back atom trajectories and events during the simulation. noise_model (NoiseModel): The noise model used in the simulation.

animate

animate(
    dilation_rate: float = 0.05,
    fps: int = 30,
    gate_display_dilation: float = 1.0,
    save_mpeg: bool = False,
    filename: str = "vqpu_animation",
    start_block: int = 0,
    n_blocks: Optional[int] = None,
)

animate the qpu state

Parameters:

Name Type Description Default
dilation_rate float

Conversion factor from the qpu time to animation time units. when dilation_rate=1.0, 1 (us) of qpu exec time corresponds to 1 second of animation time.

0.05
fps int

frame per second. Defaults to 30.

30
gate_display_dilation float

relative dilation rate of a gate event. Defaults to 1. When setting higher value, the gate event will be displayed longer.

1.0
save_mpeg bool

Save as mpeg. Defaults to False.

False
filename str

The file name of saved mpeg file. Defaults to "vqpu_animation". When save_mpeg is False, this argument is ignored.

'vqpu_animation'
start_block int

The start block to animate. Defaults to 0.

0
n_blocks int

number of blocks to animate. Defaults to None. When None, animate all blocks after start_block.

None

Returns: ani: matplotlib animation object

Source code in .venv/lib/python3.12/site-packages/bloqade/qbraid/simulation_result.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def animate(
    self,
    dilation_rate: float = 0.05,
    fps: int = 30,
    gate_display_dilation: float = 1.0,
    save_mpeg: bool = False,
    filename: str = "vqpu_animation",
    start_block: int = 0,
    n_blocks: Optional[int] = None,
):
    """animate the qpu state

    Args:
        dilation_rate (float): Conversion factor from the qpu time to animation time units. when dilation_rate=1.0, 1 (us) of qpu exec time corresponds to 1 second of animation time.
        fps (int, optional): frame per second. Defaults to 30.
        gate_display_dilation (float, optional): relative dilation rate of a gate event. Defaults to 1. When setting higher value, the gate event will be displayed longer.
        save_mpeg (bool, optional): Save as mpeg. Defaults to False.
        filename (str, optional): The file name of saved mpeg file. Defaults to "vqpu_animation". When `save_mpeg` is False, this argument is ignored.
        start_block (int, optional): The start block to animate. Defaults to 0.
        n_blocks (int, optional): number of blocks to animate. Defaults to None. When None, animate all blocks after `start_block`.
    Returns:
        ani: matplotlib animation object
    """
    from bloqade.visual.animation.animate import animate_qpu_state

    ani = animate_qpu_state(
        state=self.atom_animation_state,
        dilation_rate=dilation_rate,
        fps=fps,
        gate_display_dilation=gate_display_dilation,
        start_block=start_block,
        n_blocks=n_blocks,
        save_mpeg=save_mpeg,
        filename=filename,
    )
    return ani

from_json classmethod

from_json(json: dict) -> QuEraSimulationResult

deserialize the object from a JSON serializable dictionary.

Source code in .venv/lib/python3.12/site-packages/bloqade/qbraid/simulation_result.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
@classmethod
def from_json(cls, json: dict) -> "QuEraSimulationResult":
    """deserialize the object from a JSON serializable dictionary."""
    flair_visual_version = json["flair_visual_version"]
    counts = json["counts"]
    logs = pd.read_csv(StringIO(json["logs"]), index_col=0)
    atom_animation_state = vis_qpustate.AnimateQPUState.from_json(
        json["atom_animation_state"]
    )
    noise_model = NoiseModel(**json["noise_model"])

    return cls(
        flair_visual_version=flair_visual_version,
        counts=counts,
        logs=logs,
        atom_animation_state=atom_animation_state,
        noise_model=noise_model,
    )

to_json

to_json() -> Dict[str, Any]

Turn the object into a JSON serializable dictionary.

Source code in .venv/lib/python3.12/site-packages/bloqade/qbraid/simulation_result.py
54
55
56
57
58
59
60
61
62
def to_json(self) -> Dict[str, Any]:
    """Turn the object into a JSON serializable dictionary."""
    return {
        "flair_visual_version": self.flair_visual_version,
        "counts": self.counts,
        "logs": self.logs.to_csv(),
        "atom_animation_state": self.atom_animation_state.to_json(),
        "noise_model": self.noise_model.model_dump(mode="json"),
    }

target

qBraid

qBraid(
    *,
    allow_parallel: bool = False,
    allow_global: bool = False,
    provider: QbraidProvider,
    qelib1: bool = True
)

qBraid target for Bloqade kernels.

qBraid target that accepts a Bloqade kernel and submits the kernel to the QuEra simulator hosted on qBraid. A QbraidJob is obtainable that then lets you query the status of the submitted program on the simulator as well as obtain results.

Parameters:

Name Type Description Default
allow_parallel bool

Allow parallel gate in the resulting QASM2 AST. Defaults to False. In the case its False, and the input kernel uses parallel gates, they will get rewrite into uop gates.

False
allow_global bool

Allow global gate in the resulting QASM2 AST. Defaults to False. In the case its False, and the input kernel uses global gates, they will get rewrite into parallel gates. If both allow_parallel and allow_global are False, the input kernel will be rewritten to use uop gates.

False
provider QbraidProvider

Qbraid-provided object to allow submission of the kernel to the QuEra simulator.

required
qelib1 bool

Include the include "qelib1.inc" line in the resulting QASM2 AST that's submitted to qBraid. Defaults to True.

True
Source code in .venv/lib/python3.12/site-packages/bloqade/qbraid/target.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def __init__(
    self,
    *,
    allow_parallel: bool = False,
    allow_global: bool = False,
    provider: "QbraidProvider",  # inject externally for easier mocking
    qelib1: bool = True,
) -> None:
    """Initialize the qBraid target.

    Args:
        allow_parallel (bool):
            Allow parallel gate in the resulting QASM2 AST. Defaults to `False`.
            In the case its False, and the input kernel uses parallel gates, they will get rewrite into uop gates.

        allow_global (bool):
            Allow global gate in the resulting QASM2 AST. Defaults to `False`.
            In the case its False, and the input kernel uses global gates, they will get rewrite into parallel gates.
            If both `allow_parallel` and `allow_global` are False, the input kernel will be rewritten to use uop gates.

        provider (QbraidProvider):
            Qbraid-provided object to allow submission of the kernel to the QuEra simulator.
        qelib1 (bool):
            Include the `include "qelib1.inc"` line in the resulting QASM2 AST that's
            submitted to qBraid. Defaults to `True`.
    """

    self.qelib1 = qelib1
    self.provider = provider
    self.allow_parallel = allow_parallel
    self.allow_global = allow_global

emit

emit(
    method: Method,
    shots: Optional[int] = None,
    tags: Optional[dict[str, str]] = None,
) -> Union[QbraidJob, list[QbraidJob]]

Submit the Bloqade kernel to the QuEra simulator on qBraid.

Parameters:

Name Type Description Default
method Method

The kernel to submit to qBraid.

required
shots Optional[int]

(Optional[int]): Number of times to run the kernel. Defaults to None.

None
tags Optional[dict[str, str]]

(Optional[dict[str,str]]): A dictionary of tags to associate with the Job.

None

Returns:

Type Description
Union[QbraidJob, list[QbraidJob]]

Union[QbraidJob, list[QbraidJob]]: An object you can query for the status of your submission as well as obtain simulator results from.

Source code in .venv/lib/python3.12/site-packages/bloqade/qbraid/target.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def emit(
    self,
    method: ir.Method,
    shots: Optional[int] = None,
    tags: Optional[dict[str, str]] = None,
) -> Union["QbraidJob", list["QbraidJob"]]:
    """Submit the Bloqade kernel to the QuEra simulator on qBraid.

    Args:
        method (ir.Method):
            The kernel to submit to qBraid.
        shots: (Optional[int]):
            Number of times to run the kernel. Defaults to None.
        tags: (Optional[dict[str,str]]):
            A dictionary of tags to associate with the Job.

    Returns:
        Union[QbraidJob, list[QbraidJob]]:
            An object you can query for the status of your submission as well as
            obtain simulator results from.
    """

    # Convert method to QASM2 string
    qasm2_emitter = QASM2(
        allow_parallel=self.allow_parallel,
        allow_global=self.allow_global,
        qelib1=self.qelib1,
    )
    qasm2_prog = qasm2_emitter.emit_str(method)

    # Submit the QASM2 string to the qBraid simulator
    quera_qasm_simulator = self.provider.get_device("quera_qasm_simulator")

    return quera_qasm_simulator.run(qasm2_prog, shots=shots, tags=tags)