Kernel Machines
Data processing
- get_data(args: dict) Tuple[source]
Loads a dataset specified by a path for the qsvm training. The raw data file is in .h5 format.
- Parameters:
args (dict) – Dictionary with all the specification and parameters for the qsvm training.
- Returns:
- train_loader: Tuple[
numpy.ndarray,numpy.ndarray] Contains the training data vector and label pairs.
- test_loader: Tuple[
numpy.ndarray,numpy.ndarray] Contains the testing data vector and label pairs.
- train_loader: Tuple[
- Return type:
Tuple
- h5_to_ml_ready_numpy(file_path: str) ndarray[source]
Takes a .h5 file and returns an flattened numpy array. The .h5 file follows the convention: under the ‘latent_space’ key the autoencoder latent representation of the di-jet event is saved. It is of shape (n, 2,latent_dim), hence we want to reshape it to (n, 2*latent_dim,), where n is the number of events in the .h5 file.
- Parameters:
file_path (str) – Full path to .h5 file.
- Returns:
Flattened data array.
- Return type:
numpy.ndarray
- reshaper(array: ndarray) ndarray[source]
Takes the signal and background arrays, flattens, and stacks them. Returns the data feature array.
- Parameters:
array (
numpy.ndarray) – Data array to reshape. The expected initial shape is (n, 2, latent_dim).- Returns:
Reshaped array of shape (n, 2*latent_dim). Where n is the total number of events in the file.
- Return type:
numpy.ndarray
- get_train_dataset(sig: ndarray, bkg: ndarray, ntrain: int, is_unsup: bool) Tuple[ndarray, ndarray] | Tuple[ndarray, None][source]
Constructing the training dataset based on the conventions used for this work. Namely, last ntrain/2 from the sig file and the first ntrain/2 from the bkg file for supervised kernel machines. For the unsupervised case the first ntrain the QCD background are loaded.
- Parameters:
sig (
numpy.ndarray) – Array containing all the signal events needed for the training.bkg (
numpy.ndarray) – Array containing all the background events needed for the training.ntrain (int) – Desired training size.
is_unsup (bool) – Flags if the dataset to be loaded is for unsupervised training. If so, then only ntrain background samples are returned.
- Returns:
The training data and the corresponding labels. In the unsupervised case the latter is None.
- Return type:
Union[Tuple[
numpy.ndarray,numpy.ndarray], Tuple[numpy.ndarray, None]]
- get_test_dataset(sig: ndarray, bkg_test: ndarray, ntest: int, is_unsup: bool = False) Tuple[ndarray, ndarray][source]
Constructing the testing dataset based on the conventions used for this work. Namely, first ntest/2 samples from the signal and first ntest/2 from the dedicate background test file. The default ntest = 20k.
- Parameters:
sig (
numpy.ndarray) – Array containing all the signal events needed for the training.bkg_test (
numpy.ndarray) – Array containing all the background events needed for the training.ntest (int) – Number of requested testing samples in total (sig+bkg).
is_unsup (bool, optional) – Flags if the dataset to be loaded is for unsupervised training. If so, then only ntrain background samples are returned., by default False
- Returns:
numpy.ndarray– The testing datanumpy.ndarray– The corresponding labels. In the unsupervised case = None.
- create_output_y(n: int | Tuple[int]) ndarray[source]
Creates the out target/label files according the data file structure. n can refer to the number of training events or test events.
- get_kfold_data(test_data: ndarray, y_target: ndarray, kfolds: int = 5, full_dataset: bool = False) Tuple[ndarray, ndarray][source]
Split the testing dataset into k folds. With this resampling technique we will estimate the variance and the mean of the expected ROC curve and AUC.
- Parameters:
test_data (
numpy.ndarray) – Array of the testing data.y_target (
numpy.ndarray) – Array of targets/labels of the testing data.kfolds (int, optional) – _description_, by default 5
full_dataset (bool, optional) – Whether or not to return full concatenated dataset with signal and background data along with folded labels. If set to False (default value) the function returns just signal and background folds separately, by default False
- Returns:
numpy.ndarray– k-folds of of the test datasetnumpy.ndarray– Truth labels for the folds.
- split_sig_bkg(data: ndarray, target: ndarray) Tuple[ndarray, ndarray, ndarray, ndarray][source]
Split dataset into signal and background samples using the target. The target is supposed to be 1 for every signal and 0 for every bkg. This does not work for more than 2 class data.
- Parameters:
data (
numpy.ndarray) – Array cointaing the data.target (
numpy.ndarray) – Target array.
- Returns:
A tuple containing the numpy array of signal events and a numpy array containing the background events, along with their corresponding targets.
- Return type:
Tuple[
numpy.ndarray,numpy.ndarray,numpy.ndarray,numpy.ndarray]
Feature Maps
- u_dense_encoding(nqubits: int = 8, reps: int = 3) QuantumCircuit[source]
Constructs the data encoding circuit that was designed for the paper: https://arxiv.org/abs/2301.10780
- Parameters:
nqubits (int) – Number of qubits for the circuit.
reps (int) –
- Returns:
Quantum circuit to be used as a feature map for quantum the kernel machine.
- Return type:
qiskit.circuit.QuantumCircuit
- u_dense_encoding_all(nqubits: int = 8, reps: int = 3) QuantumCircuit[source]
Data encoding circuit with all-to-all entanglement.
- Parameters:
nqubits (int, optional) – Number of qubits for the circuit, by default 8
reps (int, optional) – Number of repetition of the data encoding circuit, by default 3
- Returns:
Quantum circuit to be used as a feature map for quantum the kernel machine.
- Return type:
qiskit.circuit.QuantumCircuit
- u_dense_encoding_no_ent(nqubits: int = 8, reps: int = 3, type: int = 0) QuantumCircuit[source]
Data encoding circuit without entanglement. The ‘type’ argument corresponds the two No-Entanglement (NE) circuits in the paper.
- Parameters:
nqubits (int, optional) – Number of qubits for the circuit, by default 8
reps (int, optional) – Number of repetition of the data encoding circuit, by default 3
- Returns:
Quantum circuit to be used as a feature map for quantum the kernel machine.
- Return type:
qiskit.circuit.QuantumCircuit
Unsupervised Quantum Kernel Machine
- class OneClassQSVM(hpars: dict)[source]
Bases:
OneClassSVMUnsupervised quantum kernel machine.
The construction is similar to the QSVM but the training here is unlabeled. The model is equipped with a quantum feature map, implemented by a data encoding circuit.
- _feature_map_name[source]
Name of the designed quantum circuit. As defined in
qad.algorithms.kernel_machines.feature_map_circuits- Type:
str
- _backend_config[source]
Configuration of the IBMQ backend, e.g. number of shots, qubit layout.
- Type:
dict
- _quantum_instance[source]
qiskit.utils.QuantumInstanceobject required for execution usingqiskit.- Type:
qiskit.utils.QuantumInstance
- _quantum_kernel[source]
Quantum kernel function constructed from the data encoding circuit.
- Type:
qiskit_machine_learning.kernels.QuantumKernel
- _kernel_matrix_train[source]
Kernel matrix constructed using the training dataset. Saved for computational efficiency.
- Type:
numpy.ndarray
- _kernel_matrix_test[source]
Kernel matrix constructed using the testing dataset. Saved for computational efficiency.
- Type:
numpy.ndarray
- _train_data[source]
Training dataset. Also saved for computational efficiency, since we don’t go above a training size of approx 6k.
- Type:
numpy.ndarray
- __init__(hpars: dict)[source]
Initialise the quantum feature map, the quantum instance and quantum kernel.
- Parameters:
hpars (dict) – Hyperparameters of the model and configuration parameters for the training. This dictionary is defined through argparse.
- property kernel_matrix_train[source]
Returns the kernel matrix elements produces by the training data
- property backend: Backend | IBMQBackend | None[source]
Returns the backend that the QSVM runs on. If it’s an ideal simulations, it returns None.
- property backend_config: dict[source]
Returns the backend configuration specified during the QSVM training.
- property nqubits: int[source]
Returns the number of qubits of the
qad.algorithms.kernel_machines.qsvm.QSVMcircuit.
- property quantum_instance: QuantumInstance[source]
Returns the quantum instance object that the
qad.algorithms.kernel_machines.qsvm.QSVMuses for the simulations, or hardware runs.
- property feature_map: QuantumCircuit[source]
Returns the
qiskit.circuit.QuantumCircuitthat implements the quantum feature map.
- property quantum_kernel: QuantumKernel[source]
Returns the
qiskit_machine_learning.kernels.QuantumKernelobject of the QSVM model.
- fit(train_data: ndarray, train_labels=None)[source]
Train the one-class QSVM model. In the case of kernel=precomputed the kernel_matrix elements from the inner products of training data vectors need to be passed to fit. Thus, the quantum kernel matrix elements are first evaluated and then passed to the OneClassSVM.fit appropriately.
The method also, times the kernel matrix element calculation and saves the matrix for later use, such as score calculation.
- Parameters:
train_data (
numpy.ndarray) – The training data vectors array of shape (ntrain, n_features).train_labels (_type_, optional) – Ignored, present only for API consistency by convention, by default None
- score(x: ndarray, y: ndarray, train_data: bool = False, sample_weight: ndarray | None = None) float[source]
Returns the mean accuracy on the given test data and labels. Need to compute the corresponding kernel matrix elements and then pass to the sklearn.svm.SVC.score.
- Parameters:
x (
numpy.ndarray) – Training dataset of shape (ntrain, nfeatures)y (
numpy.ndarray) – Target (ground truth) labels of the x_train or of x_test data arraystrain_data (bool, optional) – Flag that specifies whether the score is computed on the training data or new dataset (test). The reason behind this flag is to not compute the kernel matrix on the training data more than once, since it is the computationally expensive task in training the QSVM, by default False
sample_weight (
numpy.ndarray, optional) – Weights of the testing samples, of shape (ntrain,), by default None
- Returns:
The accuracy of the model on the given dataset x.
- Return type:
float
- predict(x: ndarray, input_is_matrix: bool = False) ndarray[source]
Predicts the label of a data vector X. Maps the prediction label of the one-class SVM from 1 -> 0 and -1 -> 1 for inliers (background) and outliers (anomalies/signal), respectively.
- Parameters:
x (
numpy.ndarray) – Data vector array of shape (n_samples, n_features)input_is_matrix (bool, optional) – Flag to enable the flxebility of being able to pass the dataset or the kernel matrix directly, by default False
- Returns:
The predicted labels of the input data vectors, of shape (n_samples).
- Return type:
numpy.ndarray
- decision_function(x_test: ndarray) ndarray[source]
Computes the score value (test statistic) of the QSVM model. It computes the displacement of the data vector x from the decision boundary. If the sign is positive then the predicted label of the model is +1 and -1 (or 0) otherwise.
The output of super().decision_function is multiplied by -1 in order to have the same sign convention between supervised and unsupervised kernel machines. For some reason the scores have the opposite sign for signal and background for sklearn.svm.SVC.decision_function and OneClassSVM.decision_function.
- Parameters:
x_test (
numpy.ndarray) – Array of data vectors of which the scores we want to compute.- Returns:
The corresponding array of scores of x.
- Return type:
numpy.ndarray
- get_transpiled_kernel_circuit(path: str, output_format: str = 'mpl', **kwargs: dict) QuantumCircuit[source]
Construct, save, and return the transpiled quantum kernel circuit figure.
- Parameters:
path (str) – Path for the output figure
output_format (str, optional) – Output image file format, by default “mpl”
- Returns:
Transpiled QuantumCircuit that represents the quantum kernel. i.e., the circuit that will be executed on the backend.
- Return type:
qiskit.circuit.QuantumCircuit
- save_circuit_physical_layout(circuit: QuantumCircuit, save_path: str)[source]
Plot and save the quantum circuit and its physical layout on the backend. Used only for hardware or noisy simulation runs.
- Parameters:
circuit (
qiskit.circuit.QuantumCircuit) – Circuit to map to the physical qubits of the backend.save_path (str) – Path to save the figure.
Custom One-Class SVM
- class CustomOneClassSVM(*, kernel='rbf', degree=3, gamma='scale', coef0=0, tol=0.001, nu=0.5, shrinking=True, cache_size=200, verbose=False, max_iter=-1)[source]
Bases:
OneClassSVMWrapper class of the OneClassSVM class, to redifine the predict and score to accommodate for the train.py and test.py design.
- score(x: ndarray, y: ndarray, train_data: bool = False, sample_weight: ndarray | None = None) float[source]
Return the mean accuracy on the given test data x and labels y.
- Parameters:
x (
numpy.ndarray) – array-like of shape (n_samples, n_features). Test samples.y (
numpy.ndarray) – array-like of shape (n_samples,). True labels for x.train_data (bool, optional) – To flag if the computation is on the training or testing datasets, by default False
sample_weight (
numpy.ndarray, optional) – array-like of shape (n_samples,), by default None
- Returns:
Mean accuracy of the model given x and y.
- Return type:
float
- predict(x: ndarray) ndarray[source]
Predicts the label of a data vector X. Maps the prediction label of the one-class SVM from 1 -> 0 and -1 -> 1 for inliers (background) and outliers (anomalies/signal), respectively.
- Parameters:
x (
numpy.ndarray) – Data vector array of shape (n_samples, n_features)- Returns:
The predicted labels of the input data vectors, of shape (n_samples).
- Return type:
numpy.ndarray
- decision_function(x: ndarray) ndarray[source]
Signed distance to the separating hyperplane, positive for an inlier and negative for an outlier. The output of super().decision_function is multiplied by -1 in order to have the same sign convention between supervised and unsupervised kernel machines. For some reason the scores have the opposite sign for signal and background for sklearn.svm.SVC.decision_function and OneClassSVM.decision_function.
Quantum SVM
- class QSVM(hpars: dict)[source]
Bases:
SVCQuantum support vector machine. Supervised SVM model equipped with a quantum feature map, implemented by a data encoding circuit.
- _feature_map_name[source]
Name of the designed quantum circuit. As defined in
qad.algorithms.kernel_machines.feature_map_circuits- Type:
str
- _backend_config[source]
Configuration of the IBMQ backend, e.g. number of shots, qubit layout.
- Type:
dict
- _quantum_instance[source]
QuantumInstance object required for execution using qiskit.
- Type:
qiskit.utils.QuantumInstance
- _quantum_kernel[source]
Quantum kernel function constructed from the data encoding circuit.
- Type:
qiskit_machine_learning.kernels.QuantumKernel
- _kernel_matrix_train[source]
Kernel matrix constructed using the training dataset. Saved for computational efficiency.
- Type:
numpy.ndarray
- _train_data[source]
Training dataset. Also saved for computational efficiency, since we don’t go above a training size of approx 6k.
- Type:
numpy.ndarray
- __init__(hpars: dict)[source]
Initialise the quantum feature map, the quantum instance and quantum kernel.
- Parameters:
hpars (dict) – Hyperparameters of the model and configuration parameters for the training. This dictionary is defined through argparse.
- property kernel_matrix_train[source]
Returns the kernel matrix elements produces by the training data
- property backend: Backend | IBMQBackend | None[source]
Returns the backend that the QSVM runs on. If it’s an ideal simulations, it returns None.
- property backend_config: dict[source]
Returns the backend configuration specified during the QSVM training.
- property nqubits: int[source]
Returns the number of qubits of the
qad.algorithms.kernel_machines.qsvm.QSVMcircuit.
- property quantum_instance: QuantumInstance[source]
Returns the quantum instance object that the
qad.algorithms.kernel_machines.qsvm.QSVMuses for the simulations, or hardware runs.
- property feature_map: QuantumCircuit[source]
Returns the
qiskit.circuit.QuantumCircuitthat implements the quantum feature map.
- property quantum_kernel: QuantumKernel[source]
Returns the
qiskit_machine_learning.kernels.QuantumKernelobject of the QSVM model.
- fit(train_data: ndarray, train_labels: ndarray)[source]
Train the QSVM model. In the case of QSVM where kernel=precomputed the kernel_matrix elements from the inner products of training data vectors need to be passed to fit. Thus, the quantum kernel matrix elements are first evaluated and then passed to the SVC.fit appropriately.
The method also, times the kernel matrix element calculation and saves the matrix for later use, such as score calculation.
- Parameters:
train_data (
numpy.ndarray) – The training data vectors array of shape (ntrain, n_features).train_labels (
numpy.ndarray) – The labels of training data vectors, 1 (signal) and 0 or -1 (background), of shape (ntrain,).
- score(x: ndarray, y: ndarray, train_data: bool = False, sample_weight: ndarray | None = None) float[source]
Returns the mean accuracy on the given test data and labels. Need to compute the corresponding kernel matrix elements and then pass to the sklearn.svm.SVC.score.
- Parameters:
x (
numpy.ndarray) – Training dataset of shape (ntrain, nfeatures)y (
numpy.ndarray) – Target (ground truth) labels of the x_train or of x_test data arraystrain_data (bool, optional) – Flag that specifies whether the score is computed on the training data or new dataset (test). The reason behind this flag is to not compute the kernel matrix on the training data more than once, since it is the computationally expensive task in training the QSVM, by default False
sample_weight (
numpy.ndarray, optional) – Weights of the testing samples, of shape (ntrain,), by default None
- Returns:
The accuracy of the model on the given dataset x.
- Return type:
float
- decision_function(x_test: ndarray) ndarray[source]
Computes the score value (test statistic) of the QSVM model. It computes the displacement of the data vector x from the decision boundary. If the sign is positive then the predicted label of the model is +1 and -1 (or 0) otherwise.
- Parameters:
x_test (
numpy.ndarray) – Test dataset data vectors.- Returns:
Score array of x.
- Return type:
numpy.ndarray
- get_transpiled_kernel_circuit(path: str, output_format: str = 'mpl', **kwargs: dict) QuantumCircuit[source]
Construct, save, and return the transpiled quantum kernel circuit figure.
- Parameters:
path (str) – Path for the output figure
output_format (str, optional) – Output image file format, by default “mpl”
- Returns:
Transpiled QuantumCircuit that represents the quantum kernel. i.e., the circuit that will be executed on the backend.
- Return type:
qiskit.circuit.QuantumCircuit
- save_circuit_physical_layout(circuit: QuantumCircuit, save_path: str)[source]
Plot and save the quantum circuit and its physical layout on the backend. Used only for hardware or noisy simulation runs.
- Parameters:
circuit (
qiskit.circuit.QuantumCircuit) – Circuit to map to the physical qubits of the backend.save_path (str) – Path to save the figure.
Functions
Helper functions
- print_accuracy_scores(test_acc: float, train_acc: float, is_unsup: bool)[source]
Prints the train and test accuracies of the model.
- Parameters:
test_acc (float) – The accuracy of the trained model on the test dataset.
train_acc (float) – The accuracy of the trained model on the train dataset.
is_unsup (bool) – Flag if the model is unsupervised. The printing is slighlty different if so.
- create_output_folder(args: dict, model: SVC | QSVM | CustomOneClassSVM | OneClassQSVM) str[source]
Creates output folder for the given model name and arguments.
- Parameters:
args (dict) – Arparse configuration arguments dictionary.
model (Union[
sklearn.svm.SVC, QSVM, CustomOneClassSVM, OneClassQSVM]) – Kernel machine, classical or quantum.
- Returns:
The output path.
- Return type:
str
- save_model(model: SVC | QSVM | CustomOneClassSVM | OneClassQSVM, path: str)[source]
Saves the qsvm model to a certain path.
- Parameters:
model (Union[
sklearn.svm.SVC, QSVM, CustomOneClassSVM, OneClassQSVM]) – Kernel machine that we want to save.path (str) – Path to save the model in.
- load_model(path: str) QSVM | SVC | CustomOneClassSVM | OneClassQSVM[source]
Load model from pickle file, i.e., deserialisation.
- Parameters:
path (str) – String of full path to load the model from.
- Returns:
Joblib object of the trained model.
- Return type:
Union[QSVM,
sklearn.svm.SVC, CustomOneClassSVM, OneClassQSVM]
- print_model_info(model: SVC | QSVM | CustomOneClassSVM | OneClassQSVM)[source]
Print information about the trained model, such as the C parameter value, number of support vectors, number of training and testing samples.
- Parameters:
model (Union[
sklearn.svm.SVC, QSVM, CustomOneClassSVM, OneClassQSVM]) – The trained kernel machine.
- init_kernel_machine(args: dict) SVC | QSVM | CustomOneClassSVM | OneClassQSVM[source]
Initialises the kernel machine. Depending on the flag, this will be a SVM or a QSVM.
- Parameters:
args (dict) – The argument dictionary defined in the training script.
- Returns:
The kernel machine model.
- Return type:
Union[
sklearn.svm.SVC, QSVM, CustomOneClassSVM, OneClassQSVM]
- eval_metrics(model: QSVM | SVC | CustomOneClassSVM | OneClassQSVM, train_data: ndarray, train_labels: ndarray, test_data: ndarray, test_labels: ndarray, out_path: str)[source]
Computes different evaluation metrics of the kernel machine models. ROC curve, FPR @TPR (working point), and accuracy. Prints and saves corresponding plots. The execution of this function is also timed.
- Parameters:
model (Union[QSVM,
sklearn.svm.SVC, CustomOneClassSVM, OneClassQSVM]) – Trained kernel machine model.train_data (
numpy.ndarray) – Training data array.train_labels (
numpy.ndarray) – Training data labels.test_data (
numpy.ndarray) – Testing data array.test_labels (
numpy.ndarray) – Testing data array.out_path (str) – Output path to saved the figures in.
- Raises:
TypeError – Passed model not of the correct type.
- plot_score_distributions(y_score: ndarray, y_label: ndarray, out_path: str)[source]
Plots and saves the score distributions for signal and background as a histogram.
- Parameters:
y_score (
numpy.ndarray) – Output score of a model.y_label (
numpy.ndarray) – True labels.out_path (str) – Output path to save the plot in.
- compute_roc_pr_curves(test_labels: ndarray, y_score: ndarray, out_path: str, model: SVC | QSVM | OneClassQSVM | CustomOneClassSVM)[source]
Computes the ROC and Precision-Recall (PR) curves and saves them in the model out_path. Also, prints the 1/FPR value around a TPR working point, default=0.8.
- Parameters:
test_labels (
numpy.ndarray) – Testing data truth labels.y_score (
numpy.ndarray) – Output model scores on the testing dataset.out_path (str) – Path to save plot.
model (Union[
sklearn.svm.SVC, QSVM, OneClassQSVM, CustomOneClassSVM]) – Kernel machine model.
- get_fpr_around_tpr_point(fpr: ndarray, tpr: ndarray, tpr_working_point: float = 0.8) Tuple[float][source]
Computes the mean 1/FPR value that corresponds to a small window aroun a given TPR working point (default: 0.8). If there are no values in the window, it widened sequentially until it includes some values around the working point.
- Parameters:
fpr (
numpy.ndarray) – False positive rate of the model on the test dataset.tpr (
numpy.ndarray) – True positive rate of the model on the test dataset.tpr_working_point (float, optional) – Working point of TPR (signal efficiency), by default 0.8
- Returns:
The mean and standard deviation of 1/FPR @ TPR=`tpr_working_point`.
- Return type:
Tuple
- export_hyperparameters(model: QSVM | SVC | CustomOneClassSVM | OneClassQSVM, outdir: str)[source]
Saves the hyperparameters of the model to a json file. QSVM and SVM have different hyperparameters.
- Parameters:
model (Union[QSVM,
sklearn.svm.SVC, CustomOneClassSVM, OneClassQSVM]) – Kernel machine model.outdir (str) – Output directory, where the json file is saved.
Backend configuration
- ideal_simulation(**kwargs) QuantumInstance[source]
Defines QuantumInstance for an ideal (statevector) simulation (no noise, no sampling statistics uncertainties).
- Returns:
Object used for the execution of quantum kernel machines using
qiskit.- Return type:
qiskit.utils.QuantumInstance
- noisy_simulation(ibmq_api_config: dict, backend_name: str, **kwargs) Tuple[QuantumInstance, Backend][source]
Prepare a
qiskit.utils.QuantumInstanceobject for simulation with noise based on the real quantum computer calibration data.- Parameters:
ibmq_api_config (dict) – Configuration file with API token and private configuration for IBMQ connection.
backend_name (str) – Name of the quantum computer, form ibm(q)_<city_name>.
kwargs – Keyword arguments for the
qiskit.utils.QuantumInstance.
- Returns:
- quantum_instance:
qiskit.utils.QuantumInstance Quantum instance object need to execute the quantum models in qiskit.
- quantum_computer_backend:
qiskit.providers.Backend Backend object representing a quantum computer from which a noisy simulation is based.
- quantum_instance:
- Return type:
Tuple
- connect_quantum_computer(ibmq_api_config: dict, backend_name: str) IBMQBackend[source]
Load a IBMQ-experience backend using a token (IBM-CERN hub credentials) This backend (i.e. quantum computer) can either be used for running on the real device or to load the calibration (noise/error info). With the latter data we can do a simulation of the hardware behaviour.
- Parameters:
ibmq_api_config (dict) – Configuration file for the IBMQ API token and provider information.
backend_name (str) – Quantum computer name
- Returns:
Backend object used for executing the quantum models in
qiskit.- Return type:
qiskit.providers.ibmq.IBMQBackend- Raises:
AttributeError – When a quantum computer name that doesn’t exist is given.
- configure_quantum_instance(ibmq_api_config: dict, run_type: str, backend_name: str | None = None, **kwargs) Tuple[QuantumInstance, Backend][source]
Gives the QuantumInstance object required for running the Quantum kernel. The quantum instance can be configured for a simulation of a backend with noise, an ideal (statevector) simulation or running on a real quantum device.
- Parameters:
ibmq_api_config (dict) – Configuration file for the IBMQ API token and provider information.
run_type (str) – Takes values the possible values {ideal,noisy, hardware} to specify what type of backend will be provided to the quantum instance object.
backend_name (str, optional) – Name of the quantum computer to run or base the noisy simulation on. For ideal runs it can be set to “none”., by default None.
kwargs – Dictionary of keyword arguments for the
qiskit.utils.QuantumInstance.
- Returns:
quantum_instance (
qiskit.utils.QuantumInstance) – Object with quantum computer backend.backend (
qiskit.providers.Backend) – The quantum computer backend object.
- Raises:
TypeError – When run_type is not in {ideal, noisy, hardware}.
- get_backend_configuration(backend: Backend) Tuple[source]
Gather backend configuration and properties from the calibration data. The output is used to build a noise model using the qiskit aer_simulator.
- Parameters:
backend (
qiskit.providers.Backend) – IBMQBackend object representing a a real quantum computer.- Returns:
- noise_model: From the 1-gate, 2-gate (CX) errors, thermal relaxation,
etc.
- coupling_map: list
Connectivity of the physical qubits.
- basis_gates: list
Gates that are physically implemented on the hardware. the transpiler decomposes the generic/abstract circuit to these physical basis gates, taking into acount also the coupling_map.
- Return type:
Tuple
- hardware_run(backend_name: str, ibmq_api_config: dict, **kwargs) Tuple[QuantumInstance, Backend][source]
Configure
qiskit.utils.QuantumInstancebased on a quantum computer. The circuits will be sent as jobs to be exececuted on the specified device in IBMQ.- Parameters:
backend_name (str) – Name of the quantum computer, form ibmq_<city_name>.
ibmq_api_config (dict) – Configuration file for the IBMQ API token and provider information.
- Returns:
- quantum_instance:
qiskit.utils.QuantumInstance Object with quantum computer backend.
- backend:
qiskit.providers.Backend The quantum computer backend object.
- quantum_instance:
- Return type:
Tuple
- time_and_exec(func: Callable, *args) float[source]
Executes the given function with its arguments, times and returns the execution time. Typically used for timing training, and testing tasks of the models.
- Parameters:
func (Callable) – Function to execute.
args (Arguments of the function.) –
- Returns:
The runtime.
- Return type:
float