diff --git a/qiskit_experiments/calibration/experiments/__init__.py b/qiskit_experiments/calibration/experiments/__init__.py new file mode 100644 index 0000000000..8464d0228b --- /dev/null +++ b/qiskit_experiments/calibration/experiments/__init__.py @@ -0,0 +1,15 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2021. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Experiments used solely for calibrating schedules.""" + +from .rabi import RabiAnalysis, Rabi diff --git a/qiskit_experiments/calibration/experiments/rabi.py b/qiskit_experiments/calibration/experiments/rabi.py new file mode 100644 index 0000000000..43c1abdf78 --- /dev/null +++ b/qiskit_experiments/calibration/experiments/rabi.py @@ -0,0 +1,287 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2021. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Rabi amplitude experiment.""" + +from typing import Any, Dict, List, Optional, Union +import numpy as np + +from qiskit import QiskitError, QuantumCircuit +from qiskit.circuit import Gate, Parameter +from qiskit.qobj.utils import MeasLevel +from qiskit.providers import Backend +import qiskit.pulse as pulse +from qiskit.providers.options import Options + +from qiskit_experiments.analysis import ( + CurveAnalysis, + CurveAnalysisResult, + SeriesDef, + fit_function, + get_opt_value, + get_opt_error, +) +from qiskit_experiments.base_experiment import BaseExperiment +from qiskit_experiments.data_processing.processor_library import get_to_signal_processor + + +class RabiAnalysis(CurveAnalysis): + r"""Rabi analysis class based on a fit to a cosine function. + + Analyse a Rabi experiment by fitting it to a cosine function + + .. math:: + y = amp \cos\left(2 \pi {\rm freq} x + {\rm phase}\right) + baseline + + Fit Parameters + - :math:`amp`: Amplitude of the oscillation. + - :math:`baseline`: Base line. + - :math:`{\rm freq}`: Frequency of the oscillation. This is the fit parameter of interest. + - :math:`{\rm phase}`: Phase of the oscillation. + + Initial Guesses + - :math:`amp`: The maximum y value less the minimum y value. + - :math:`baseline`: The average of the data. + - :math:`{\rm freq}`: The frequency with the highest power spectral density. + - :math:`{\rm phase}`: Zero. + + Bounds + - :math:`amp`: [-2, 2] scaled to the maximum signal value. + - :math:`baseline`: [-1, 1] scaled to the maximum signal value. + - :math:`{\rm freq}`: [0, inf]. + - :math:`{\rm phase}`: [-pi, pi]. + """ + + __series__ = [ + SeriesDef( + fit_func=lambda x, amp, freq, phase, baseline: fit_function.cos( + x, amp=amp, freq=freq, phase=phase, baseline=baseline + ), + plot_color="blue", + ) + ] + + @classmethod + def _default_options(cls): + """Return the default analysis options. + + See :meth:`~qiskit_experiment.analysis.CurveAnalysis._default_options` for + descriptions of analysis options. + """ + default_options = super()._default_options() + default_options.p0 = {"amp": None, "freq": None, "phase": None, "baseline": None} + default_options.bounds = {"amp": None, "freq": None, "phase": None, "baseline": None} + default_options.fit_reports = {"freq": "rate"} + default_options.xlabel = "Amplitude" + default_options.ylabel = "Signal (arb. units)" + + return default_options + + def _setup_fitting(self, **options) -> Union[Dict[str, Any], List[Dict[str, Any]]]: + """Fitter options.""" + user_p0 = self._get_option("p0") + user_bounds = self._get_option("bounds") + + max_abs_y = np.max(np.abs(self._data().y)) + + # Use a fast Fourier transform to guess the frequency. + fft = np.abs(np.fft.fft(self._data().y - np.average(self._data().y))) + damp = self._data().x[1] - self._data().x[0] + freqs = np.linspace(0.0, 1.0 / (2.0 * damp), len(fft)) + + b_guess = np.average(self._data().y) + a_guess = np.max(self._data().y) - np.min(self._data().y) - b_guess + f_guess = freqs[np.argmax(fft[0 : len(fft) // 2])] + + if user_p0["phase"] is not None: + p_guesses = [user_p0["phase"]] + else: + p_guesses = [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4, np.pi] + + fit_options = [] + for p_guess in p_guesses: + fit_option = { + "p0": { + "amp": user_p0["amp"] or a_guess, + "freq": user_p0["freq"] or f_guess, + "phase": p_guess, + "baseline": user_p0["baseline"] or b_guess, + }, + "bounds": { + "amp": user_bounds["amp"] or (-2 * max_abs_y, 2 * max_abs_y), + "freq": user_bounds["freq"] or (0, np.inf), + "phase": user_bounds["phase"] or (-np.pi, np.pi), + "baseline": user_bounds["baseline"] or (-1 * max_abs_y, 1 * max_abs_y), + }, + } + fit_option.update(options) + fit_options.append(fit_option) + + return fit_options + + def _post_analysis(self, analysis_result: CurveAnalysisResult) -> CurveAnalysisResult: + """Algorithmic criteria for whether the fit is good or bad. + + A good fit has: + - a reduced chi-squared lower than three, + - more than a quarter of a full period, + - less than 10 full periods, and + - an error on the fit frequency lower than the fit frequency. + """ + fit_freq = get_opt_value(analysis_result, "freq") + fit_freq_err = get_opt_error(analysis_result, "freq") + + criteria = [ + analysis_result["reduced_chisq"] < 3, + 1.0 / 4.0 < fit_freq < 10.0, + (fit_freq_err is None or (fit_freq_err < fit_freq)), + ] + + if all(criteria): + analysis_result["quality"] = "computer_good" + else: + analysis_result["quality"] = "computer_bad" + + return analysis_result + + +class Rabi(BaseExperiment): + """An experiment that scans the amplitude of a pulse to calibrate rotations between 0 and 1. + + The circuits that are run have a custom rabi gate with the pulse schedule attached to it + through the calibrations. The circuits are of the form: + + .. parsed-literal:: + + ┌───────────┐ ░ ┌─┐ + q_0: ┤ Rabi(amp) ├─░─┤M├ + └───────────┘ ░ └╥┘ + measure: 1/═════════════════╩═ + 0 + + """ + + __analysis_class__ = RabiAnalysis + + @classmethod + def _default_run_options(cls) -> Options: + """Default option values for the experiment :meth:`run` method.""" + return Options( + meas_level=MeasLevel.KERNELED, + meas_return="single", + ) + + @classmethod + def _default_experiment_options(cls) -> Options: + """Default values for the pulse if no schedule is given. + + Users can set a schedule by doing + + .. code-block:: + + rabi.set_experiment_options(schedule=rabi_schedule) + + """ + return Options( + duration=160, + sigma=40, + amplitudes=np.linspace(-0.95, 0.95, 51), + schedule=None, + normalization=True, + ) + + def __init__(self, qubit: int): + """Setup a Rabi experiment on the given qubit. + + Args: + qubit: The qubit on which to run the Rabi experiment. + """ + super().__init__([qubit]) + + def circuits(self, backend: Optional[Backend] = None) -> List[QuantumCircuit]: + """Create the circuits for the Rabi experiment. + + Args: + backend: A backend object. + + Returns: + A list of circuits with a rabi gate with an attached schedule. Each schedule + will have a different value of the scanned amplitude. + + Raises: + QiskitError: + - If the user-provided schedule does not contain a channel with an index + that matches the qubit on which to run the Rabi experiment. + - If the user provided schedule has more than one free parameter. + """ + # TODO this is temporary logic. Need update of circuit data and processor logic. + self.set_analysis_options( + data_processor=get_to_signal_processor( + meas_level=self.run_options.meas_level, + meas_return=self.run_options.meas_return, + normalize=self.experiment_options.normalization, + ) + ) + + schedule = self.experiment_options.get("schedule", None) + + if schedule is None: + amp = Parameter("amp") + with pulse.build() as default_schedule: + pulse.play( + pulse.Gaussian( + duration=self.experiment_options.duration, + amp=amp, + sigma=self.experiment_options.sigma, + ), + pulse.DriveChannel(self.physical_qubits[0]), + ) + + schedule = default_schedule + else: + if self.physical_qubits[0] not in set(ch.index for ch in schedule.channels): + raise QiskitError( + f"User provided schedule {schedule.name} does not contain a channel " + "for the qubit on which to run Rabi." + ) + + if len(schedule.parameters) != 1: + raise QiskitError("Schedule in Rabi must have exactly one free parameter.") + + param = next(iter(schedule.parameters)) + + gate = Gate(name="Rabi", num_qubits=1, params=[param]) + + circuit = QuantumCircuit(1) + circuit.append(gate, (0,)) + circuit.measure_active() + circuit.add_calibration(gate, (self.physical_qubits[0],), schedule, params=[param]) + + circs = [] + for amp in self.experiment_options.amplitudes: + amp = np.round(amp, decimals=6) + assigned_circ = circuit.assign_parameters({param: amp}, inplace=False) + assigned_circ.metadata = { + "experiment_type": self._type, + "qubit": self.physical_qubits[0], + "xval": amp, + "unit": "arb. unit", + "amplitude": amp, + "schedule": str(schedule), + } + + if backend: + assigned_circ.metadata["dt"] = getattr(backend.configuration(), "dt", "n.a.") + + circs.append(assigned_circ) + + return circs diff --git a/qiskit_experiments/data_processing/nodes.py b/qiskit_experiments/data_processing/nodes.py index 8ceb1d6d7a..cbf44f487b 100644 --- a/qiskit_experiments/data_processing/nodes.py +++ b/qiskit_experiments/data_processing/nodes.py @@ -440,7 +440,7 @@ def _format_data(self, datum: dict, error: Optional[Any] = None) -> Tuple[dict, f"Key {bit_str} is not a valid count key in{self.__class__.__name__}." ) - if not isinstance(count, (int, float)): + if not isinstance(count, (int, float, np.integer)): raise DataProcessorError( f"Count {bit_str} is not a valid count value in {self.__class__.__name__}." ) diff --git a/qiskit_experiments/test/mock_iq_backend.py b/qiskit_experiments/test/mock_iq_backend.py index 35138428d1..91884f6a9a 100644 --- a/qiskit_experiments/test/mock_iq_backend.py +++ b/qiskit_experiments/test/mock_iq_backend.py @@ -12,13 +12,17 @@ """An mock IQ backend for testing.""" +from abc import abstractmethod from typing import Dict, List, Tuple import numpy as np +from qiskit import QuantumCircuit from qiskit.providers.backend import BackendV1 as Backend from qiskit.providers import JobV1 from qiskit.providers.models import QasmBackendConfiguration from qiskit.result import Result +from qiskit.qobj.utils import MeasLevel +from qiskit.providers.options import Options class TestJob(JobV1): @@ -79,17 +83,83 @@ def __init__( def _default_options(self): """Default options of the test backend.""" + return Options( + shots=1024, + meas_level=MeasLevel.KERNELED, + meas_return="single", + ) - def _draw_iq_shot(self, prob) -> List[List[float]]: + def _draw_iq_shots(self, prob, shots) -> List[List[List[float]]]: """Produce an IQ shot.""" - rand_i = self._rng.normal(0, self._iq_cluster_width) - rand_q = self._rng.normal(0, self._iq_cluster_width) + rand_i = self._rng.normal(0, self._iq_cluster_width, size=shots) + rand_q = self._rng.normal(0, self._iq_cluster_width, size=shots) - if self._rng.binomial(1, prob) > 0.5: - return [[self._iq_cluster_centers[0] + rand_i, self._iq_cluster_centers[1] + rand_q]] - else: - return [[self._iq_cluster_centers[2] + rand_i, self._iq_cluster_centers[3] + rand_q]] + memory = [] + for idx, state in enumerate(self._rng.binomial(1, prob, size=shots)): - def run(self, run_input, **options) -> TestJob: - """Subclasses will need to override this.""" + if state > 0.5: + point_i = self._iq_cluster_centers[0] + rand_i[idx] + point_q = self._iq_cluster_centers[1] + rand_q[idx] + else: + point_i = self._iq_cluster_centers[2] + rand_i[idx] + point_q = self._iq_cluster_centers[3] + rand_q[idx] + + memory.append([[point_i, point_q]]) + + return memory + + @abstractmethod + def _compute_probability(self, circuit: QuantumCircuit) -> float: + """Compute the probability used in the binomial distribution creating the IQ shot. + + An abstract method that subclasses will implement to create a probability of + being in the excited state based on the received quantum circuit. + + Args: + circuit: The circuit from which to compute the probability. + + Returns: + The probability that the binaomial distribution will use to generate an IQ shot. + """ + + def run(self, run_input, **options): + """Run the IQ backend.""" + + self.options.update_options(**options) + shots = self.options.get("shots") + meas_level = self.options.get("meas_level") + meas_return = self.options.get("meas_return") + + result = { + "backend_name": f"{self.__class__.__name__}", + "backend_version": "0", + "qobj_id": 0, + "job_id": 0, + "success": True, + "results": [], + } + + for circ in run_input: + run_result = { + "shots": shots, + "success": True, + "header": {"metadata": circ.metadata}, + } + + prob = self._compute_probability(circ) + + if meas_level == MeasLevel.CLASSIFIED: + ones = np.sum(self._rng.binomial(1, prob, size=shots)) + run_result["data"] = {"counts": {"1": ones, "0": shots - ones}} + else: + memory = self._draw_iq_shots(prob, shots) + + if meas_return == "avg": + memory = np.average(np.array(memory), axis=0).tolist() + + run_result["data"] = {"memory": memory} + + result["results"].append(run_result) + + return TestJob(self, result) diff --git a/test/calibration/experiments/test_rabi.py b/test/calibration/experiments/test_rabi.py new file mode 100644 index 0000000000..89305a1ba5 --- /dev/null +++ b/test/calibration/experiments/test_rabi.py @@ -0,0 +1,189 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2021. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Test Rabi amplitude Experiment class.""" + +from typing import Tuple +import numpy as np + +from qiskit import QuantumCircuit, execute +from qiskit.circuit import Parameter +from qiskit.providers.basicaer import QasmSimulatorPy +from qiskit.test import QiskitTestCase +from qiskit.qobj.utils import MeasLevel +import qiskit.pulse as pulse + +from qiskit_experiments import ExperimentData +from qiskit_experiments.calibration.experiments.rabi import RabiAnalysis, Rabi +from qiskit_experiments.data_processing.data_processor import DataProcessor +from qiskit_experiments.data_processing.nodes import Probability +from qiskit_experiments.test.mock_iq_backend import IQTestBackend + + +class RabiBackend(IQTestBackend): + """A simple and primitive backend, to be run by the Rabi tests.""" + + def __init__( + self, + iq_cluster_centers: Tuple[float, float, float, float] = (1.0, 1.0, -1.0, -1.0), + iq_cluster_width: float = 1.0, + amplitude_to_angle: float = np.pi, + ): + """Initialize the rabi backend.""" + self._amplitude_to_angle = amplitude_to_angle + + super().__init__(iq_cluster_centers, iq_cluster_width) + + @property + def rabi_rate(self) -> float: + """Returns the rabi rate.""" + return self._amplitude_to_angle / np.pi + + def _compute_probability(self, circuit: QuantumCircuit) -> float: + """Returns the probability based on the rotation angle and amplitude_to_angle.""" + amp = next(iter(circuit.calibrations["Rabi"].keys()))[1][0] + return np.sin(self._amplitude_to_angle * amp) ** 2 + + +class TestRabiEndToEnd(QiskitTestCase): + """Test the rabi experiment.""" + + def test_rabi_end_to_end(self): + """Test the Rabi experiment end to end.""" + + test_tol = 0.01 + backend = RabiBackend() + + rabi = Rabi(3) + rabi.set_experiment_options(amplitudes=np.linspace(-0.95, 0.95, 21)) + result = rabi.run(backend).analysis_result(0) + + self.assertEqual(result["quality"], "computer_good") + self.assertTrue(abs(result["popt"][1] - backend.rabi_rate) < test_tol) + + backend = RabiBackend(amplitude_to_angle=np.pi / 2) + + rabi = Rabi(3) + rabi.set_experiment_options(amplitudes=np.linspace(-0.95, 0.95, 21)) + result = rabi.run(backend).analysis_result(0) + self.assertEqual(result["quality"], "computer_good") + self.assertTrue(abs(result["popt"][1] - backend.rabi_rate) < test_tol) + + backend = RabiBackend(amplitude_to_angle=2.5 * np.pi) + + rabi = Rabi(3) + rabi.set_experiment_options(amplitudes=np.linspace(-0.95, 0.95, 101)) + result = rabi.run(backend).analysis_result(0) + + self.assertEqual(result["quality"], "computer_good") + self.assertTrue(abs(result["popt"][1] - backend.rabi_rate) < test_tol) + + +class TestRabiCircuits(QiskitTestCase): + """Test the circuits generated by the experiment and the options.""" + + def test_default_schedule(self): + """Test the default schedule.""" + + rabi = Rabi(2) + rabi.set_experiment_options(amplitudes=[0.5]) + circs = rabi.circuits(RabiBackend()) + + with pulse.build() as expected: + pulse.play(pulse.Gaussian(160, 0.5, 40), pulse.DriveChannel(2)) + + self.assertEqual(circs[0].calibrations["Rabi"][((2,), (0.5,))], expected) + self.assertEqual(len(circs), 1) + + def test_user_schedule(self): + """Test the user given schedule.""" + + amp = Parameter("my_double_amp") + with pulse.build() as my_schedule: + pulse.play(pulse.Drag(160, amp, 40, 10), pulse.DriveChannel(2)) + pulse.play(pulse.Drag(160, amp, 40, 10), pulse.DriveChannel(2)) + + rabi = Rabi(2) + rabi.set_experiment_options(schedule=my_schedule, amplitudes=[0.5]) + circs = rabi.circuits(RabiBackend()) + + assigned_sched = my_schedule.assign_parameters({amp: 0.5}, inplace=False) + self.assertEqual(circs[0].calibrations["Rabi"][((2,), (0.5,))], assigned_sched) + + +class TestRabiAnalysis(QiskitTestCase): + """Class to test the fitting.""" + + def simulate_experiment_data(self, thetas, amplitudes, shots=1024): + """Generate experiment data for Rx rotations with an arbitrary amplitude calibration.""" + circuits = [] + for theta in thetas: + qc = QuantumCircuit(1) + qc.rx(theta, 0) + qc.measure_all() + circuits.append(qc) + + sim = QasmSimulatorPy() + result = execute(circuits, sim, shots=shots, seed_simulator=10).result() + data = [ + { + "counts": self._add_uncertainty(result.get_counts(i)), + "metadata": { + "xval": amplitudes[i], + "meas_level": MeasLevel.CLASSIFIED, + "meas_return": "avg", + }, + } + for i, theta in enumerate(thetas) + ] + return data + + @staticmethod + def _add_uncertainty(counts): + """Ensure that we always have a non-zero sigma in the test.""" + for label in ["0", "1"]: + if label not in counts: + counts[label] = 1 + + return counts + + def test_good_analysis(self): + """Test the Rabi analysis.""" + experiment_data = ExperimentData() + + thetas = np.linspace(-np.pi, np.pi, 31) + amplitudes = np.linspace(-0.25, 0.25, 31) + expected_rate, test_tol = 2.0, 0.2 + + experiment_data.add_data(self.simulate_experiment_data(thetas, amplitudes, shots=400)) + + data_processor = DataProcessor("counts", [Probability(outcome="1")]) + + result = RabiAnalysis().run(experiment_data, data_processor=data_processor, plot=False) + + self.assertEqual(result[0]["quality"], "computer_good") + self.assertTrue(abs(result[0]["popt"][1] - expected_rate) < test_tol) + + def test_bad_analysis(self): + """Test the Rabi analysis.""" + experiment_data = ExperimentData() + + thetas = np.linspace(0.0, np.pi / 4, 31) + amplitudes = np.linspace(0.0, 0.95, 31) + + experiment_data.add_data(self.simulate_experiment_data(thetas, amplitudes, shots=200)) + + data_processor = DataProcessor("counts", [Probability(outcome="1")]) + + result = RabiAnalysis().run(experiment_data, data_processor=data_processor, plot=False) + + self.assertEqual(result[0]["quality"], "computer_bad") diff --git a/test/test_qubit_spectroscopy.py b/test/test_qubit_spectroscopy.py index 09b6a04a6f..47deefdca9 100644 --- a/test/test_qubit_spectroscopy.py +++ b/test/test_qubit_spectroscopy.py @@ -13,20 +13,19 @@ """Spectroscopy tests.""" from typing import Tuple - import numpy as np + +from qiskit import QuantumCircuit from qiskit.qobj.utils import MeasLevel from qiskit.test import QiskitTestCase from qiskit_experiments.characterization.qubit_spectroscopy import QubitSpectroscopy -from qiskit_experiments.test.mock_iq_backend import TestJob, IQTestBackend +from qiskit_experiments.test.mock_iq_backend import IQTestBackend from qiskit_experiments.analysis import get_opt_value class SpectroscopyBackend(IQTestBackend): - """ - A simple and primitive backend to test spectroscopy experiments. - """ + """A simple and primitive backend to test spectroscopy experiments.""" def __init__( self, @@ -44,51 +43,11 @@ def __init__( super().__init__(iq_cluster_centers, iq_cluster_width) - # pylint: disable = arguments-differ - def run( - self, circuits, shots=1024, meas_level=MeasLevel.KERNELED, meas_return="single", **options - ): - """Run the spectroscopy backend.""" - - result = { - "backend_name": "spectroscopy backend", - "backend_version": "0", - "qobj_id": 0, - "job_id": 0, - "success": True, - "results": [], - } - - for circ in circuits: - - run_result = { - "shots": shots, - "success": True, - "header": {"metadata": circ.metadata}, - } - - set_freq = float(circ.data[0][0].params[0]) - delta_freq = set_freq - self._freq_offset - prob = np.exp(-(delta_freq ** 2) / (2 * self._linewidth ** 2)) - - if meas_level == MeasLevel.CLASSIFIED: - counts = {"1": 0, "0": 0} - - for _ in range(shots): - counts[str(self._rng.binomial(1, prob))] += 1 - - run_result["data"] = {"counts": counts} - else: - memory = [self._draw_iq_shot(prob) for _ in range(shots)] - - if meas_return == "avg": - memory = np.average(np.array(memory), axis=0).tolist() - - run_result["data"] = {"memory": memory} - - result["results"].append(run_result) - - return TestJob(self, result) + def _compute_probability(self, circuit: QuantumCircuit) -> float: + """Returns the probability based on the frequency.""" + set_freq = float(circuit.data[0][0].params[0]) + delta_freq = set_freq - self._freq_offset + return np.exp(-(delta_freq ** 2) / (2 * self._linewidth ** 2)) class TestQubitSpectroscopy(QiskitTestCase):