qbiocode.utils.qutils module#
Summary#
Functions:
Execute quantum circuit on Aer simulator. |
|
This function returns an ansatz based on the specified type and parameters. |
|
This function to get the backend and session for the specified primitive. |
|
This function creates an Estimator instance with specified options. |
|
This function returns a feature map based on the specified type and parameters. |
|
This function returns an optimizer based on the specified type and parameters. |
|
This function creates a Sampler instance with specified options. |
|
Extract probability predictions from measurement counts. |
|
This function transpiles the given quantum circuit based on the optimization level and backend. |
|
Map a row of features to the rotation angle of a feature-map gate. |
Reference#
- get_backend_session(args, primitive, num_qubits)[source]#
This function to get the backend and session for the specified primitive.
- Parameters:
args (dict) – Dictionary containing backend and other parameters.
primitive (str) – The type of primitive to instantiate (‘sampler’ or ‘estimator’).
num_qubits (int) – Number of qubits for the backend.
- Returns:
The backend instance. session: The session instance. prim: The instantiated primitive (Sampler or Estimator).
- Return type:
backend
- transpile_circuit(circuit, opt_level, backend, initial_layout, PT=False, dd_sequence='XpXm')[source]#
This function transpiles the given quantum circuit based on the optimization level and backend.
- Parameters:
circuit (QuantumCircuit) – The quantum circuit to be transpiled.
opt_level (int or str) – Optimization level for transpilation.
backend (Backend) – The backend to which the circuit will be transpiled.
initial_layout (Layout) – Initial layout for the transpilation.
PT (bool) – Whether to apply pulse twirling. Defaults to False.
dd_sequence (str) – Sequence for dynamical decoupling. Defaults to ‘XpXm’.
- Returns:
The transpiled quantum circuit.
- Return type:
t_qc (QuantumCircuit)
- get_sampler(mode=None, shots=1024, dd=True, dd_seq='XpXm', PT=True)[source]#
This function creates a Sampler instance with specified options.
- Parameters:
mode (Session) – The session mode for the sampler.
shots (int) – Number of shots for sampling.
dd (bool) – Whether to enable dynamical decoupling.
dd_seq (str) – Sequence type for dynamical decoupling.
PT (bool) – Whether to enable pulse twirling.
- Returns:
An instance of the Sampler with the specified options.
- Return type:
Sampler
- get_estimator(mode=None, shots=1024, resil_level=2, dd=True, dd_seq='XpXm', PT=True)[source]#
This function creates an Estimator instance with specified options.
- Parameters:
mode (Session) – The session mode for the estimator.
shots (int) – Number of shots for estimation.
resil_level (int) – Resilience level for error suppression.
dd (bool) – Whether to enable dynamical decoupling.
dd_seq (str) – Sequence type for dynamical decoupling.
PT (bool) – Whether to enable pulse twirling.
- Returns:
An instance of the Estimator with the specified options.
- Return type:
Estimator
- get_ansatz(ansatz_type, feat_dimension, reps=1, entanglement='linear')[source]#
This function returns an ansatz based on the specified type and parameters. It supports ‘esu2’, ‘amp’, and ‘twolocal’ ansatz types, constructing it using the specified feature dimension, number of repetitions, and entanglement type.
- Parameters:
ansatz_type (str) – Type of the ansatz (‘esu2’, ‘amp’, or ‘twolocal’).
feat_dimension (int) – Number of qubits for the ansatz.
reps (int) – Number of repetitions for the ansatz.
entanglement (str) – Type of entanglement for the ansatz.
- Returns:
An instance of the specified ansatz type.
- Return type:
ansatz
- SUPPORTED_FEATURE_MAPS = ('Z', 'ZZ', 'P')#
Feature-map names accepted by
get_feature_map(), in the spelling the config files use. Exported so callers can validate at their own boundary – e.g.qbiocode.learning.compute_pqk.compute_pqk()rejects a mistypedencodingbefore it creates directories or reads a projection cache.
- SUPPORTED_ENTANGLEMENTS = ('full', 'linear', 'reverse_linear', 'pairwise', 'circular', 'sca')#
Entanglement patterns accepted by qiskit’s ZZ/Pauli feature maps. Validated because qiskit itself reports an unknown pattern as “Something went wrong in Rust space”, which names neither the parameter nor the value. A callable or an explicit index list is also valid and is passed through to qiskit unchecked.
- SUPPORTED_OPTIMIZERS = ('SPSA', 'COBYLA', 'GradientDescent', 'L_BFGS_B')#
Optimizer names accepted by
get_optimizer().
- unit_coefficient_data_map(x)[source]#
Map a row of features to the rotation angle of a feature-map gate.
This is the
data_map_funcused by the projected-quantum-kernel paths. It divides by two at every step so that every multiplicative factor of a data feature inside a single-qubit gate is 1.0, rather than qiskit’s defaultprod(pi - x_i).- Parameters:
x – one row of features – either numeric, or a symbolic
ParameterVector. Qiskit calls a data map with both: with symbolic parameters when it builds the feature-map circuit (PauliFeatureMap.pauli_blockpasses aParameterVector), and with numeric values only if a caller evaluates the map directly.- Returns:
a
floatfor numeric input, or the unevaluatedParameterExpressionfor symbolic input.- Return type:
The mapped angle
Notes
Narrowing the symbolic case with
float()raisesTypeError: Parameter expression with unbound parameters ... is not numericand makes everydata_map=Truefeature map unbuildable, so the symbolic expression is returned untouched for qiskit to bind later.
- get_feature_map(feature_map, feat_dimension, reps=1, entanglement='linear', data_map_func=None)[source]#
This function returns a feature map based on the specified type and parameters. It supports ‘Z’, ‘ZZ’, and ‘P’ feature maps, constructing it using the specified feature dimension, number of repetitions, entanglement type, and data mapping function. :type feature_map: str :param feature_map: Type of the feature map (‘Z’, ‘ZZ’, or ‘P’). :type feature_map: str :type feat_dimension: int :param feat_dimension: Number of qubits for the feature map. :type feat_dimension: int :type reps: int :param reps: Number of repetitions for the feature map. :type reps: int :type entanglement: str :param entanglement: Type of entanglement for the feature map. :type entanglement: str :type data_map_func: callable, optional :param data_map_func: Function to map data to the feature map parameters. :type data_map_func: callable, optional
- Returns:
An instance of the specified feature map type. feat_dimension (int): The number of qubits in the feature map.
- Return type:
feature_map
- Raises:
ValueError – if
feature_mapis not one of'Z','ZZ','P', or iffeat_dimension/repsis not a positive integer.
- get_optimizer(type='COBYLA', max_iter=100, learning_rate_a=None, perturbation_gamma=None, prior_iter=0)[source]#
This function returns an optimizer based on the specified type and parameters. It supports ‘SPSA’, ‘COBYLA’, ‘GradientDescent’, and ‘L_BFGS_B’ optimizer types, constructing it using the specified maximum iterations, learning rate, perturbation gamma, and prior iterations.
- Parameters:
type (str) – Type of the optimizer (‘SPSA’, ‘COBYLA’, ‘GradientDescent’, or ‘L_BFGS_B’).
max_iter (int) – Maximum number of iterations for the optimizer.
learning_rate_a (float, optional) – Initial learning rate for SPSA.
perturbation_gamma (float, optional) – Perturbation gamma for SPSA.
prior_iter (int) – Number of prior iterations to consider.
- Returns:
An instance of the specified optimizer type.
- Return type:
optimizer
- Raises:
ValueError – if
typeis not one of'SPSA','COBYLA','GradientDescent','L_BFGS_B', or ifmax_iteris not a positive integer.
- retrieve_probabilities(counts)[source]#
Extract probability predictions from measurement counts.
Converts raw measurement counts from quantum circuit execution into probability predictions for binary classification. Handles edge cases where only one outcome is observed.
- Parameters:
counts (dict) – Measurement counts with keys ‘0’ and/or ‘1’ Example: {‘0’: 4123, ‘1’: 4069}
- Returns:
[p0, p1] where p0 is probability of class 0 and p1 is probability of class 1. Always sums to 1.0.
- Return type:
list of float
Notes
Handles missing keys gracefully (assigns probability 0 or 1)
If only ‘0’ observed: returns [1.0, 0.0]
If only ‘1’ observed: returns [0.0, 1.0]
If both observed: returns normalized probabilities
Examples
>>> counts = {'0': 6000, '1': 2000} >>> retrieve_probabilities(counts) [0.75, 0.25]
>>> counts = {'0': 8192} # Only one outcome >>> retrieve_probabilities(counts) [1.0, 0.0]
- execute_circuit(qc, n_shots=8192, device='CPU')[source]#
Execute quantum circuit on Aer simulator.
General-purpose function for executing quantum circuits using the Qiskit Aer simulator with statevector method. Useful for custom quantum algorithms that need direct circuit execution without the full runtime service setup.
- Parameters:
qc (QuantumCircuit) – Quantum circuit to execute
n_shots (int, optional) – Number of measurement shots (default: 8192)
device (str, optional) – Device type: ‘CPU’ or ‘GPU’ (default: ‘CPU’) Note: GPU requires qiskit-aer-gpu installation
- Returns:
Measurement counts dictionary with bitstring keys and count values Example: {‘0’: 4123, ‘1’: 4069}
- Return type:
dict
Notes
Uses statevector simulation method for exact state evolution
Automatically transpiles circuit with optimization level 3
Parallel threshold set to 50 qubits for statevector parallelization
For hardware execution, use get_backend_session() instead
Examples
>>> from qiskit import QuantumCircuit >>> from qbiocode.utils import execute_circuit >>> qc = QuantumCircuit(2, 2) >>> qc.h(0) >>> qc.cx(0, 1) >>> qc.measure([0, 1], [0, 1]) >>> counts = execute_circuit(qc, n_shots=1024) >>> print(counts) {'00': 512, '11': 512}