qpandalite.analyzer package#
Submodules#
qpandalite.analyzer.expectation module#
Expectation value calculations for quantum measurement results.
- qpandalite.analyzer.expectation.calculate_exp_X(measured_result, nqubit, qubit_index=0)[源代码]
Calculate the expectation value of the Pauli-X operator.
The input
measured_resultmust contain results measured after applying a Hadamard gate on the target qubit (X-basis rotation).The formula is:
⟨X_k⟩ = Σ_b sign(b_k) * prob(b), wheresign(b_k) = +1when bitkis0and-1when1.- 参数:
measured_result (Dict[str, float] | List[float]) --
Z-basis measurement outcomes (after H rotation). Supports:
key-value dict:
{"00": 0.5, "11": 0.5}.list:
[p0, p1, ...]in computational-basis order.
nqubit (int) -- Number of qubits.
qubit_index (int) -- Which qubit to calculate ⟨X⟩ for (0 = MSB). Defaults to 0.
- 返回:
The expectation value
⟨X⟩as a float in[-1, 1].- 返回类型:
float
示例
>>> # Bell state |Φ+⟩ = (|00⟩ + |11⟩)/√2 has ⟨X⊗X⟩ = 1 >>> result = {"00": 0.5, "11": 0.5} >>> calculate_exp_X(result, nqubit=2) 1.0
>>> # Single-qubit |+⟩ state (H|0⟩) has ⟨X⟩ = 1 >>> result = {"0": 0.5, "1": 0.5} >>> calculate_exp_X(result, nqubit=1) 1.0
- qpandalite.analyzer.expectation.calculate_exp_Y(measured_result, nqubit, qubit_index=0)[源代码]
Calculate the expectation value of the Pauli-Y operator.
The input
measured_resultmust contain results measured after applyingS^† Hon the target qubit (Y-basis rotation).The formula is the same as for X:
⟨Y_k⟩ = p(bit_k=0) - p(bit_k=1)applied to the rotated measurement results.- 参数:
measured_result (Dict[str, float] | List[float]) --
Z-basis measurement outcomes (after S†H rotation). Supports:
key-value dict:
{"00": 0.5, "11": 0.5}.list:
[p0, p1, ...]in computational-basis order.
nqubit (int) -- Number of qubits.
qubit_index (int) -- Which qubit to calculate ⟨Y⟩ for (0 = MSB). Defaults to 0.
- 返回:
The expectation value
⟨Y⟩as a float in[-1, 1].- 返回类型:
float
示例
>>> # |+i⟩ state = (|0⟩ + i|1⟩)/√2, after S†H rotation >>> # measures |0⟩ with probability 1.0 → ⟨Y⟩ = 1.0 >>> result = {"0": 1.0} >>> calculate_exp_Y(result, nqubit=1) 1.0
>>> # Single-qubit |0⟩ has ⟨Y⟩ = 0 (after rotation: 50/50) >>> result = {"0": 0.5, "1": 0.5} >>> calculate_exp_Y(result, nqubit=1) 0.0
- qpandalite.analyzer.expectation.calculate_expectation(measured_result, hamiltonian)[源代码]
Calculate expectation value of a Hamiltonian from measurement results.
The Hamiltonian may contain only Z and I (identity) terms. This function works with results measured in the Z basis. For X or Y basis expectations, use
calculate_exp_X()orcalculate_exp_Y()instead.- 参数:
measured_result (Dict[str, float] | List[float]) --
Measurement outcomes in either:
key-value dict: Maps outcome strings (e.g.
"00") to probabilities, e.g.{"00": 0.5, "11": 0.5}.list: Probability vector in computational-basis order, e.g.
[0.5, 0, 0, 0.5]for a 2-qubit system.
hamiltonian (List[str] | str) -- A Hamiltonian string (e.g.
"ZZ") or a list of such strings. Each character must beZ,z,I, ori. The length must match the number of qubits.
- 抛出:
ValueError -- Hamiltonian contains invalid characters, or its length does not match the number of qubits in
measured_result.TypeError --
measured_resultis neither a dict nor a list.
- 返回:
The expectation value(s). If
hamiltonianis a list, returns a list of floats; otherwise a single float.- 返回类型:
float | List[float]
示例
>>> result = {"00": 0.5, "11": 0.5} >>> calculate_expectation(result, "ZZ") # Bell state |Φ+⟩ 1.0 >>> calculate_expectation(result, "ZI") 0.0 >>> calculate_expectation(result, ["ZZ", "ZI"]) [1.0, 0.0]
>>> # Using list format (2 qubits) >>> probs = [0.5, 0, 0, 0.5] # |00⟩ and |11⟩ each with prob 0.5 >>> calculate_expectation(probs, "ZZ") 1.0
- qpandalite.analyzer.expectation.calculate_multi_basis_expectation(measured_results, nqubit)[源代码]
Calculate expectation values for multiple measurement bases at once.
Given measurement results in different bases (X, Y, Z, or custom), compute the expectation value for each basis and return them as a dict.
The user is responsible for performing the correct basis rotation on the quantum circuit before measurement. For example:
Z basis: measure directly (no rotation).
X basis: apply
Hbefore measurement.Y basis: apply
S^\dagger Hbefore measurement.
Each basis label maps to a single expectation value for the MSB qubit (index 0). For per-qubit expectations, call
calculate_exp_X()/calculate_exp_Y()directly with the desiredqubit_index.备注
For Z-basis entries, this computes
⟨ZZ...Z⟩(the tensor product of Z on all qubits), not individual⟨Z_k⟩. For per-qubit Z expectations, usecalculate_expectation()with Hamiltonians like"ZI"or"IZ".- 参数:
measured_results (Dict[str, Dict[str, float] | List[float]]) --
A dict mapping basis labels to measurement outcomes. Each key is a basis name (e.g.
"X","Y","Z", or a custom label like"X0Z1"). Each value is either:key-value dict:
{"00": 0.5, "11": 0.5}list:
[0.5, 0, 0, 0.5]in computational-basis order.
nqubit (int) -- Number of qubits.
- 返回:
Mapping from basis label to expectation value. For Pauli-X bases,
calculate_exp_X()is used; for Pauli-Y,calculate_exp_Y(); otherwise Z-basis calculation viacalculate_expectation()with a"ZZ...Z"Hamiltonian.- 返回类型:
Dict[str, float]
示例
>>> z_result = {"0": 1.0} >>> x_result = {"0": 1.0} # After H rotation on |0⟩ >>> calculate_multi_basis_expectation( ... {"Z": z_result, "X": x_result}, nqubit=1 ... ) {'Z': 1.0, 'X': 1.0}
qpandalite.analyzer.result_adapter module#
Result Adapter
- class qpandalite.analyzer.result_adapter.QASMResultAdapter(counts, shots=None, metadata=None)[源代码]
基类:
objectAdapter for QASM Simulator results, converting raw output to a standardized analysis-ready format.
Takes a raw measurement counts dict from a QASM simulator and produces an
AnalysisResult-compatible object containing counts, probabilities, and metadata.The output can be passed directly to
qpandalite.analyzer.drawvisualization functions.- 参数:
counts (Dict[str, int]) -- Raw measurement counts, e.g.
{"00": 512, "11": 488}.shots (int | None) -- Total number of shots. If not provided, inferred from counts.
metadata (dict | None) -- Optional metadata dict (e.g. simulator type, circuit info).
- counts
Original measurement counts.
- Type:
Dict[str, int]
- probabilities
Normalized probability distribution.
- Type:
Dict[str, float]
- shots
Total number of shots.
- Type:
int
- metadata
Simulation metadata.
- Type:
dict
示例
>>> adapter = QASMResultAdapter( ... counts={"00": 512, "11": 488}, ... metadata={"simulator": "qasm_simulator"}, ... ) >>> adapter.probabilities {'00': 0.512, '11': 0.488} >>> adapter.shots 1000
- to_dict()[源代码]
Convert to a plain dict for serialization.
- 返回:
dict with keys
counts,probabilities,shots,metadata.- 返回类型:
dict
- qpandalite.analyzer.result_adapter.convert_originq_result(key_value_result, style='keyvalue', prob_or_shots='prob', reverse_key=True, key_style='bin', qubit_num=None)[源代码]
OriginQ result general adapter. Return adapted format given by the arguments.
- 参数:
key_value_result (Dict[str, int] or a list of Dict[str, int]) -- The raw result produced by machine.
style (str) -- Accepts "keyvalue" or "list". Defaults to 'keyvalue'.
prob_or_shots (str) -- Accepts "prob" or "shots". Defaults to 'prob'.
key_style (str) -- Accepts "bin" (as str) or "dec" (as int). Defaults to 'bin'.
reverse_key (bool, optional) -- Reverse the key (Change endian). Defaults to True.
- 抛出:
ValueError -- style is not "keyvalue" or "list"
ValueError -- prob_or_shots is not "prob" or "shots"
- 返回:
Adapted format given by arguments, or a list corresponding to the "List" input.
- 返回类型:
Dict/List
- qpandalite.analyzer.result_adapter.convert_quafu_result(quafu_result, style='keyvalue', prob_or_shots='prob', reverse_key=True, key_style='bin', qubit_num=None)[源代码]
Quafu result general adapter. Return adapted format given by the arguments.
- 参数:
quafu_result (List[Dict] or Dict) -- The raw result produced by Quafu. Each entry is a dict containing a
reskey with a JSON string of measurement counts (e.g.{"10": 2357, "00": 2628, ...}).style (str) -- Accepts
"keyvalue"or"list". Defaults to'keyvalue'.prob_or_shots (str) -- Accepts
"prob"or"shots". Defaults to'prob'.key_style (str) -- Accepts
"bin"(as str) or"dec"(as int). Defaults to'bin'.reverse_key (bool, optional) -- Reverse the key (change endian). Defaults to True.
qubit_num (int, optional) -- Override the number of qubits for key formatting. If not provided, it is guessed from the maximum key value.
- 抛出:
ValueError -- If style is not
"keyvalue"or"list".ValueError -- If prob_or_shots is not
"prob"or"shots".ValueError -- If key_style is not
"bin"or"dec".
- 返回:
Adapted format given by arguments, or a list corresponding to the
Listinput.- 返回类型:
Dict/List
- qpandalite.analyzer.result_adapter.kv2list(kv_result, guessed_qubit_num)[源代码]
Convert a key-value result dict to a flat list indexed by integer keys.
The list has length
2 ** guessed_qubit_numand is indexed by the integer representation of the measurement outcome.- 参数:
kv_result (dict) -- Key-value result dict, e.g.
{0: 0.1, 3: 0.9}. Keys must be integers.guessed_qubit_num (int) -- Number of qubits, used to determine the output list length (
2 ** guessed_qubit_num).
- 返回:
Flat list where
ret[k]holds the value for outcomek.- 返回类型:
list
- qpandalite.analyzer.result_adapter.list2kv(data)[源代码]
Convert a measurement result list to a key-value frequency dict.
- 参数:
data (List[str]) -- A list of measurement outcome strings, e.g.
['00', '01', '10', '00', '11', '00'].- 返回:
Frequency dict where keys are outcome strings and values are occurrence counts. Returns
{}for empty input.- 返回类型:
Dict[str, int]
- qpandalite.analyzer.result_adapter.normalize_result(data)[源代码]
Normalize measurement results to a probability distribution.
Accepts either a frequency dict or a raw list of outcome strings. List input is first converted via
list2kv(). Returns a dict whose values sum to 1.0. Returns{}for empty input.- 参数:
data (Union[Dict[str, int], List[str]]) -- Measurement results as a frequency dict
{'00': 3, '01': 1, ...}or a raw list['00', '01', '10', ...].- 返回:
Probability distribution dict with values summing to 1.0.
- 返回类型:
Dict[str, float]
- qpandalite.analyzer.result_adapter.shots2prob(measured_result, total_shots=None)[源代码]
Convert a shot-counts dict to a probability distribution.
- 参数:
measured_result (Dict[str, int]) -- Measurement counts, e.g.
{'00': 512, '11': 488}.total_shots (int, optional) -- Total number of shots. If not provided, it is inferred by summing the values of measured_result.
- 返回:
Probability dict where each count is divided by total_shots.
- 返回类型:
Dict[str, float]
qpandalite.analyzer.draw module#
Visualization utilities for quantum measurement results.
- qpandalite.analyzer.draw.plot_distribution(measured_result, title='Probability Distribution', figsize=(10, 6))[源代码]
Plot a bar chart of the probability distribution with a uniform reference line.
- 参数:
measured_result (Dict[str, float] | List[float]) --
Measurement results in one of two formats:
key-value dict: Maps outcome strings to probabilities, e.g.
{"00": 0.5, "11": 0.5}.list: Probability vector in computational-basis order, e.g.
[0.5, 0, 0, 0.5]for a 2-qubit system.
title (str) -- Plot title. Defaults to
"Probability Distribution".figsize (Tuple[int, int]) -- Figure size
(width, height)in inches. Defaults to(10, 6).
- 抛出:
ValueError -- If the list length does not correspond to a valid number of qubits (i.e. is not a power of 2).
- 返回类型:
None
示例
>>> from qpandalite.analyzer.draw import plot_distribution >>> # Key-value format >>> plot_distribution({"00": 0.5, "11": 0.5}, title="Bell State") >>> # List format (2 qubits) >>> plot_distribution([0.5, 0, 0, 0.5], title="Bell State")
- qpandalite.analyzer.draw.plot_histogram(measured_result, title='Measurement Result', figsize=(10, 6))[源代码]
Plot a histogram of measurement results.
- 参数:
measured_result (Dict[str, float] | List[float]) --
Measurement results in one of two formats:
key-value dict: Maps outcome strings to probabilities, e.g.
{"00": 0.5, "11": 0.5}.list: Probability vector in computational-basis order, e.g.
[0.5, 0, 0, 0.5]for a 2-qubit system.
title (str) -- Plot title. Defaults to
"Measurement Result".figsize (Tuple[int, int]) -- Figure size
(width, height)in inches. Defaults to(10, 6).
- 抛出:
ValueError -- If the list length does not correspond to a valid number of qubits (i.e. is not a power of 2).
- 返回类型:
None
示例
>>> from qpandalite.analyzer.draw import plot_histogram >>> # Key-value format >>> plot_histogram({"00": 0.5, "11": 0.5}, title="Bell State") >>> # List format (2 qubits) >>> plot_histogram([0.5, 0, 0, 0.5], title="Bell State")