Пример #1
0
    def test_qv_failure_insufficient_trials(self):
        """
        Test that the quantum volume is unsuccessful when:
            there is less than 100 trials
        """
        dir_name = os.path.dirname(os.path.abspath(__file__))
        insufficient_trials_json_file = "qv_data_70_trials.json"
        with open(os.path.join(dir_name, insufficient_trials_json_file),
                  "r") as json_file:
            insufficient_trials_data = json.load(json_file,
                                                 cls=ExperimentDecoder)

        num_of_qubits = 3
        backend = Aer.get_backend("aer_simulator")

        qv_exp = QuantumVolume(num_of_qubits, seed=SEED)
        exp_data = ExperimentData(experiment=qv_exp, backend=backend)
        exp_data.add_data(insufficient_trials_data)

        qv_exp.run_analysis(exp_data)
        qv_result = exp_data.analysis_results(1)
        self.assertTrue(
            qv_result.extra["success"] is False and qv_result.value == 1,
            "quantum volume is successful with less than 100 trials",
        )
    def _initialize_components(self,
                               experiment_data: ExperimentData) -> List[str]:
        """Initialize child data components and return list of child experiment IDs"""
        # Check if component child experiment data containers have already
        # been created. If so the list of indices for their positions in the
        # ordered dict should exist. Index is used to extract the experiment
        # IDs for each child experiment which can change when re-running analysis
        # if replace_results=False, so that we update the correct child data
        # for each component experiment
        component_index = experiment_data.metadata.get("component_child_index",
                                                       [])
        if not component_index:
            experiment = experiment_data.experiment
            if experiment is None:
                raise AnalysisError(
                    "Cannot run composite analysis on an experiment data without either "
                    "a composite experiment, or composite experiment metadata."
                )
            # If the experiment Construct component data and update indices
            start_index = len(experiment_data.child_data())
            component_index = []
            for i, sub_exp in enumerate(experiment.component_experiment()):
                sub_data = sub_exp._initialize_experiment_data()
                experiment_data.add_child_data(sub_data)
                component_index.append(start_index + i)
            experiment_data.metadata["component_child_index"] = component_index

        # Child components exist so we can get their ID for accessing them
        child_ids = experiment_data._child_data.keys()
        component_ids = [child_ids[idx] for idx in component_index]
        return component_ids
Пример #3
0
    def test_qv_failure_insufficient_confidence(self):
        """
        Test that the quantum volume is unsuccessful when:
            there are more than 100 trials, the heavy output probability mean is more than 2/3
            but the confidence is not high enough
        """
        dir_name = os.path.dirname(os.path.abspath(__file__))
        insufficient_confidence_json = "qv_data_moderate_noise_100_trials.json"
        with open(os.path.join(dir_name, insufficient_confidence_json),
                  "r") as json_file:
            insufficient_confidence_data = json.load(json_file,
                                                     cls=ExperimentDecoder)

        num_of_qubits = 4
        backend = Aer.get_backend("aer_simulator")

        qv_exp = QuantumVolume(num_of_qubits, seed=SEED)
        exp_data = ExperimentData(experiment=qv_exp, backend=backend)
        exp_data.add_data(insufficient_confidence_data)

        qv_exp.run_analysis(exp_data)
        qv_result = exp_data.analysis_results(1)
        self.assertTrue(
            qv_result.extra["success"] is False and qv_result.value == 1,
            "quantum volume is successful with insufficient confidence",
        )
Пример #4
0
    def test_local_analysis(self):
        """Tests local mitigator generation from experimental data"""
        qubits = [0, 1, 2]
        run_data = [
            {
                "counts": {"000": 986, "010": 10, "100": 16, "001": 12},
                "metadata": {"label": "000"},
                "shots": 1024,
            },
            {
                "counts": {"111": 930, "110": 39, "011": 24, "101": 29, "010": 1, "100": 1},
                "metadata": {"label": "111"},
                "shots": 1024,
            },
        ]
        expected_assignment_matrices = [
            np.array([[0.98828125, 0.04003906], [0.01171875, 0.95996094]]),
            np.array([[0.99023438, 0.02929688], [0.00976562, 0.97070312]]),
            np.array([[0.984375, 0.02441406], [0.015625, 0.97558594]]),
        ]
        run_meta = {"physical_qubits": qubits}
        expdata = ExperimentData()
        expdata.add_data(run_data)
        expdata._metadata = run_meta
        exp = ReadoutMitigationExperiment(qubits)
        result = exp.analysis.run(expdata)
        mitigator = result.analysis_results(0).value

        self.assertEqual(len(qubits), mitigator._num_qubits)
        self.assertEqual(qubits, mitigator._qubits)
        self.assertTrue(matrix_equal(expected_assignment_matrices, mitigator._assignment_mats))
Пример #5
0
def simulate_output_data(func, xvals, param_dict, **metadata):
    """Generate arbitrary fit data."""
    __shots = 100000

    expected_probs = func(xvals, **param_dict)
    counts = np.asarray(expected_probs * __shots, dtype=int)

    data = [{
        "counts": {
            "0": __shots - count,
            "1": count
        },
        "metadata":
        dict(xval=xi,
             qubits=(0, ),
             experiment_type="fake_experiment",
             **metadata),
    } for xi, count in zip(xvals, counts)]

    expdata = ExperimentData(experiment=FakeExperiment())
    for datum in data:
        expdata.add_data(datum)

    expdata.metadata["job_metadata"] = [{
        "run_options": {
            "meas_level": MeasLevel.CLASSIFIED
        }
    }]

    return expdata
    def create_experiment_data(self, iq_data: List[Any], single_shot: bool = False):
        """Populate avg_iq_data to use it for testing.

        Args:
            iq_data: A List of IQ data.
            single_shot: Indicates if the data is single-shot or not.
        """
        results = []
        if not single_shot:
            for circ_data in iq_data:
                res = ExperimentResult(
                    success=True,
                    meas_level=1,
                    meas_return="avg",
                    data=ExperimentResultData(memory=circ_data),
                    header=self.header,
                    shots=1024,
                )
                results.append(res)
        else:
            for circ_data in iq_data:
                res = ExperimentResult(
                    success=True,
                    meas_level=1,
                    meas_return="single",
                    data=ExperimentResultData(memory=circ_data),
                    header=self.header,
                    shots=1024,
                )
                results.append(res)

        # pylint: disable=attribute-defined-outside-init
        self.iq_experiment = ExperimentData(FakeExperiment())
        self.iq_experiment.add_data(Result(results=results, **self.base_result_args))
Пример #7
0
    def _add_cal_metadata(self, experiment_data: ExperimentData):
        """Add metadata to the experiment data making it more self contained.

        The following keys are added to each experiment's metadata:
            cal_param_value: The value of the drag parameter. This value together with
                the fit result will be used to find the new value of the drag parameter.
            cal_param_name: The name of the parameter in the calibrations.
            cal_schedule: The name of the schedule in the calibrations.
            target_angle: The target angle of the gate.
            cal_group: The calibration group to which the parameter belongs.
        """

        param_val = self._cals.get_parameter_value(
            self._param_name,
            self.physical_qubits,
            self._sched_name,
            group=self.experiment_options.group,
        )

        experiment_data.metadata["cal_param_value"] = param_val
        experiment_data.metadata["cal_param_name"] = self._param_name
        experiment_data.metadata["cal_schedule"] = self._sched_name
        experiment_data.metadata[
            "target_angle"] = self.experiment_options.target_angle
        experiment_data.metadata["cal_group"] = self.experiment_options.group
Пример #8
0
    def test_t1_analysis(self):
        """
        Test T1Analysis
        """

        data = ExperimentData()
        data._metadata = {"meas_level": 2}

        numbers = [
            750, 1800, 2750, 3550, 4250, 4850, 5450, 5900, 6400, 6800, 7000,
            7350, 7700
        ]

        for i, count0 in enumerate(numbers):
            data.add_data({
                "counts": {
                    "0": count0,
                    "1": 10000 - count0
                },
                "metadata": {
                    "xval": (3 * i + 1) * 1e-9,
                    "experiment_type": "T1",
                    "qubit": 0,
                    "unit": "s",
                },
            })

        res, _ = T1Analysis()._run_analysis(data)
        result = res[1]
        self.assertEqual(result.quality, "good")
        self.assertAlmostEqual(result.value.nominal_value, 25e-9, delta=3)
Пример #9
0
    def test_t1_low_quality(self):
        """
        A test where the fit's quality will be low
        """

        data = ExperimentData()
        data._metadata = {
            "job_metadata": [
                {
                    "run_options": {
                        "meas_level": 2
                    },
                },
            ]
        }

        for i in range(10):
            data.add_data({
                "counts": {
                    "0": 10,
                    "1": 10
                },
                "metadata": {
                    "xval": i * 1e-9,
                    "experiment_type": "T1",
                    "qubit": 0,
                    "unit": "s",
                },
            })

        res, _ = T1Analysis()._run_analysis(data)
        result = res[1]
        self.assertEqual(result.quality, "bad")
    def _add_cal_metadata(self, experiment_data: ExperimentData):
        """Add metadata to the experiment data making it more self contained.

        The following keys are added to each circuit's metadata:
            angles_schedules: A list of parameter update information. Each entry of the list
                is a tuple with four entries: the target angle of the rotation, the name of the
                amplitude parameter to update, the name of the schedule containing the amplitude
                parameter to update, and the previous value of the amplitude parameter to update.
            cal_group: The calibration group to which the amplitude parameters belong.
        """

        param_values = []
        for angle, param_name, schedule_name, _ in self.experiment_options.angles_schedules:
            param_val = self._cals.get_parameter_value(
                param_name,
                self._physical_qubits,
                schedule_name,
                group=self.experiment_options.group,
            )

            param_values.append(
                AnglesSchedules(
                    target_angle=angle,
                    parameter=param_name,
                    schedule=schedule_name,
                    previous_value=param_val,
                ))

        experiment_data.metadata["angles_schedules"] = param_values
        experiment_data.metadata["cal_group"] = self.experiment_options.group
    def _add_child_data(self, experiment_data: ExperimentData):
        """Save empty component experiment data as child data.

        This will initialize empty ExperimentData objects for each component
        experiment and add them as child data to the main composite experiment
        ExperimentData container container for saving.

        Args:
            experiment_data: a composite experiment experiment data container.
        """
        component_index = experiment_data.metadata.get("component_child_index",
                                                       [])
        if component_index:
            # Child components are already initialized
            return

        # Initialize the component experiment data containers and add them
        # as child data to the current experiment data
        child_components = self._initialize_component_experiment_data(
            experiment_data)
        start_index = len(experiment_data.child_data())
        for i, subdata in enumerate(child_components):
            experiment_data.add_child_data(subdata)
            component_index.append(start_index + i)

        # Store the indices of the added child data in metadata
        experiment_data.metadata["component_child_index"] = component_index
Пример #12
0
    def _load_json_data(self, rb_exp_data_file_name: str):
        """
        loader for the experiment data and configuration setup.
        Args:
            rb_exp_data_file_name(str): The file name that contain the experiment data.
        Returns:
            list: containing dict of the experiment setup configuration and list of dictionaries
                containing the experiment results.
            ExperimentData:  ExperimentData object that was creates by the analysis function.
        """
        expdata1 = ExperimentData()
        self.assertTrue(
            os.path.isfile(rb_exp_data_file_name),
            "The file containing the experiment data doesn't exist."
            " Please run the data generator.",
        )
        with open(rb_exp_data_file_name, "r") as json_file:
            data = json.load(json_file)
            # The experiment attributes added
            exp_attributes = data[0]
            # pylint: disable=protected-access, invalid-name
            expdata1._metadata = data[0]
            # The experiment data located in index [1] as it is a list of dicts
            expdata1.add_data(data[1])

        return data, exp_attributes, expdata1
Пример #13
0
    def _run_analysis(
        self, experiment_data: ExperimentData
    ) -> Tuple[List[AnalysisResultData], List["matplotlib.figure.Figure"]]:
        r"""Run analysis for :math:`T_\phi` experiment.
        It invokes CompositeAnalysis._run_analysis that will invoke
        _run_analysis for the two sub-experiments.
        Based on the results, it computes the result for :math:`T_phi`.
        """
        super()._run_analysis(experiment_data)

        t1_result = experiment_data.child_data(0).analysis_results("T1")
        t2star_result = experiment_data.child_data(1).analysis_results("T2star")
        tphi = 1 / (1 / t2star_result.value - 1 / (2 * t1_result.value))

        quality_tphi = (
            "good" if (t1_result.quality == "good" and t2star_result.quality == "good") else "bad"
        )

        analysis_results = [
            AnalysisResultData(
                name="T_phi",
                value=tphi,
                chisq=None,
                quality=quality_tphi,
                extra={"unit": "s"},
            )
        ]
        return analysis_results, []
Пример #14
0
    def test_composite_single_kerneled_memory_marginalization(self):
        """Test the marginalization of level 1 data."""
        test_data = ExperimentData()

        datum = {
            "memory": [
                # qubit 0,   qubit 1,    qubit 2
                [[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]],  # shot 1
                [[0.1, 0.1], [1.1, 1.1], [2.1, 2.1]],  # shot 2
                [[0.2, 0.2], [1.2, 1.2], [2.2, 2.2]],  # shot 3
                [[0.3, 0.3], [1.3, 1.3], [2.3, 2.3]],  # shot 4
                [[0.4, 0.4], [1.4, 1.4], [2.4, 2.4]],  # shot 5
            ],
            "metadata": {
                "experiment_type":
                "ParallelExperiment",
                "composite_index": [0, 1, 2],
                "composite_metadata": [
                    {
                        "experiment_type": "FineXAmplitude",
                        "qubits": [0]
                    },
                    {
                        "experiment_type": "FineXAmplitude",
                        "qubits": [1]
                    },
                    {
                        "experiment_type": "FineXAmplitude",
                        "qubits": [2]
                    },
                ],
                "composite_qubits": [[0], [1], [2]],
                "composite_clbits": [[0], [1], [2]],
            },
            "shots":
            5,
            "meas_level":
            1,
        }

        test_data.add_data(datum)

        all_sub_data = CompositeAnalysis([])._marginalized_component_data(
            test_data.data())
        for idx, sub_data in enumerate(all_sub_data):
            expected = {
                "metadata": {
                    "experiment_type": "FineXAmplitude",
                    "qubits": [idx]
                },
                "memory": [
                    [[idx + 0.0, idx + 0.0]],
                    [[idx + 0.1, idx + 0.1]],
                    [[idx + 0.2, idx + 0.2]],
                    [[idx + 0.3, idx + 0.3]],
                    [[idx + 0.4, idx + 0.4]],
                ],
            }

            self.assertEqual(expected, sub_data[0])
Пример #15
0
    def test_t1_analysis(self):
        """
        Test T1Analysis
        """

        data = ExperimentData()
        numbers = [
            750, 1800, 2750, 3550, 4250, 4850, 5450, 5900, 6400, 6800, 7000,
            7350, 7700
        ]

        for i, count0 in enumerate(numbers):
            data.add_data({
                "counts": {
                    "0": count0,
                    "1": 10000 - count0
                },
                "metadata": {
                    "xval": 3 * i + 1,
                    "experiment_type": "T1",
                    "qubit": 0,
                    "unit": "ns",
                    "dt_factor_in_sec": None,
                },
            })

        res = T1Analysis()._run_analysis(data)[0][0]
        self.assertEqual(res.quality, "good")
        self.assertAlmostEqual(res.value.value, 25e-9, delta=3)
Пример #16
0
    def setUp(self):
        """Here, single-shots average to points at plus/minus 1.

        The setting corresponds to four single-shots done on two qubits.
        """
        super().setUp()

        circ_es = ExperimentResultData(memory=[[1.0, 1.0], [-1.0, 1.0]])
        self._sig_gs = np.array([1.0, -1.0]) / np.sqrt(2.0)

        circ_gs = ExperimentResultData(memory=[[-1.0, -1.0], [1.0, -1.0]])
        self._sig_es = np.array([-1.0, 1.0]) / np.sqrt(2.0)

        circ_x90p = ExperimentResultData(memory=[[0.0, 0.0], [0.0, 0.0]])
        self._sig_x90 = np.array([0, 0])

        circ_x45p = ExperimentResultData(memory=[[-0.5, -0.5], [0.5, -0.5]])
        self._sig_x45 = np.array([0.5, -0.5]) / np.sqrt(2.0)

        res_es = ExperimentResult(
            shots=4,
            success=True,
            meas_level=1,
            meas_return="avg",
            data=circ_es,
            header=self.header,
        )

        res_gs = ExperimentResult(
            shots=4,
            success=True,
            meas_level=1,
            meas_return="avg",
            data=circ_gs,
            header=self.header,
        )

        res_x90p = ExperimentResult(
            shots=4,
            success=True,
            meas_level=1,
            meas_return="avg",
            data=circ_x90p,
            header=self.header,
        )

        res_x45p = ExperimentResult(
            shots=4,
            success=True,
            meas_level=1,
            meas_return="avg",
            data=circ_x45p,
            header=self.header,
        )

        self.data = ExperimentData(FakeExperiment())
        self.data.add_data(
            Result(results=[res_es, res_gs, res_x90p, res_x45p],
                   **self.base_result_args))
Пример #17
0
    def test_qv_success(self):
        """
        Test a successful run of quantum volume.
        Compare the results to a pre-run experiment
        """
        dir_name = os.path.dirname(os.path.abspath(__file__))
        successful_json_file = "qv_data_moderate_noise_300_trials.json"
        with open(os.path.join(dir_name, successful_json_file),
                  "r") as json_file:
            successful_data = json.load(json_file, cls=ExperimentDecoder)

        num_of_qubits = 4
        backend = Aer.get_backend("aer_simulator")

        qv_exp = QuantumVolume(range(num_of_qubits), seed=SEED)
        exp_data = ExperimentData(experiment=qv_exp, backend=backend)
        exp_data.add_data(successful_data)

        qv_exp.analysis.run(exp_data)
        results_json_file = "qv_result_moderate_noise_300_trials.json"
        with open(os.path.join(dir_name, results_json_file), "r") as json_file:
            successful_results = json.load(json_file, cls=ExperimentDecoder)

        results = exp_data.analysis_results()
        for result, reference in zip(results, successful_results):
            if isinstance(result.value, UFloat):
                # ufloat is distinguished by object id. so usually not identical to cache.
                self.assertTupleEqual(
                    (result.value.n, result.value.s),
                    (reference["value"].n, reference["value"].s),
                    "result value is not the same as precalculated analysis",
                )
            else:
                self.assertEqual(
                    result.value,
                    reference["value"],
                    "result value is not the same as precalculated analysis",
                )
            self.assertEqual(
                result.name,
                reference["name"],
                "result name is not the same as precalculated analysis",
            )
            for key, value in reference["extra"].items():
                if isinstance(value, float):
                    self.assertAlmostEqual(
                        result.extra[key],
                        value,
                        msg="result " + str(key) + " is not the same as the "
                        "pre-calculated analysis",
                    )
                else:
                    self.assertTrue(
                        result.extra[key] == value,
                        "result " + str(key) + " is not the same as the "
                        "pre-calculated analysis",
                    )
 def _initialize_experiment_data(self):
     """Initialize the return data container for the experiment run"""
     experiment_data = ExperimentData(experiment=self)
     # Initialize child experiment data
     for sub_exp in self._experiments:
         sub_data = sub_exp._initialize_experiment_data()
         experiment_data.add_child_data(sub_data)
     experiment_data.metadata["component_child_index"] = list(range(self.num_experiments))
     return experiment_data
Пример #19
0
    def test_to_real(self):
        """Test scaling and conversion to real part."""
        processor = DataProcessor("memory", [ToReal(scale=1e-3)])

        exp_data = ExperimentData(FakeExperiment())
        exp_data.add_data(self.result_lvl1)

        # Test to real on a single datum
        new_data = processor(exp_data.data(0))

        expected_old = {
            "memory": [
                [[1103260.0, -11378508.0], [2959012.0, -16488753.0]],
                [[442170.0, -19283206.0], [-5279410.0, -15339630.0]],
                [[3016514.0, -14548009.0], [-3404756.0, -16743348.0]],
            ],
            "metadata": {"experiment_type": "fake_test_experiment"},
            "job_id": "job-123",
            "meas_level": 1,
            "shots": 3,
        }

        expected_new = np.array([[1103.26, 2959.012], [442.17, -5279.41], [3016.514, -3404.7560]])

        self.assertEqual(exp_data.data(0), expected_old)
        np.testing.assert_array_almost_equal(
            unp.nominal_values(new_data),
            expected_new,
        )
        self.assertTrue(np.isnan(unp.std_devs(new_data)).all())

        # Test that we can call with history.
        new_data, history = processor.call_with_history(exp_data.data(0))

        self.assertEqual(exp_data.data(0), expected_old)
        np.testing.assert_array_almost_equal(
            unp.nominal_values(new_data),
            expected_new,
        )

        self.assertEqual(history[0][0], "ToReal")
        np.testing.assert_array_almost_equal(
            unp.nominal_values(history[0][1]),
            expected_new,
        )

        # Test to real on more than one datum
        new_data = processor(exp_data.data())

        expected_new = np.array(
            [
                [[1103.26, 2959.012], [442.17, -5279.41], [3016.514, -3404.7560]],
                [[5131.962, 4438.87], [3415.985, 2942.458], [5199.964, 4030.843]],
            ]
        )
        np.testing.assert_array_almost_equal(
            unp.nominal_values(new_data),
            expected_new,
        )
class BaseDataProcessorTest(QiskitExperimentsTestCase):
    """Define some basic setup functionality for data processor tests."""

    def setUp(self):
        """Define variables needed for most tests."""
        super().setUp()

        self.base_result_args = dict(
            backend_name="test_backend",
            backend_version="1.0.0",
            qobj_id="id-123",
            job_id="job-123",
            success=True,
        )

        self.header = QobjExperimentHeader(
            memory_slots=2,
            metadata={"experiment_type": "fake_test_experiment"},
        )

    def create_experiment_data(self, iq_data: List[Any], single_shot: bool = False):
        """Populate avg_iq_data to use it for testing.

        Args:
            iq_data: A List of IQ data.
            single_shot: Indicates if the data is single-shot or not.
        """
        results = []
        if not single_shot:
            for circ_data in iq_data:
                res = ExperimentResult(
                    success=True,
                    meas_level=1,
                    meas_return="avg",
                    data=ExperimentResultData(memory=circ_data),
                    header=self.header,
                    shots=1024,
                )
                results.append(res)
        else:
            for circ_data in iq_data:
                res = ExperimentResult(
                    success=True,
                    meas_level=1,
                    meas_return="single",
                    data=ExperimentResultData(memory=circ_data),
                    header=self.header,
                    shots=1024,
                )
                results.append(res)

        # pylint: disable=attribute-defined-outside-init
        self.iq_experiment = ExperimentData(FakeExperiment())
        self.iq_experiment.add_data(Result(results=results, **self.base_result_args))
Пример #21
0
    def _initialize(
        self,
        experiment_data: ExperimentData,
    ):
        """Initialize curve analysis with experiment data.

        This method is called ahead of other processing.

        Args:
            experiment_data: Experiment data to analyze.

        Raises:
            AnalysisError: When circuit metadata for ops count is missing.
        """
        super()._initialize(experiment_data)

        if self.options.gate_error_ratio is not None:
            # If gate error ratio is not False, EPG analysis is enabled.
            # Here analysis prepares gate error ratio and gate counts for EPC to EPG conversion.

            # If gate count dictionary is not set it will compute counts from circuit metadata.
            avg_gpc = defaultdict(float)
            n_circs = len(experiment_data.data())
            for circ_result in experiment_data.data():
                try:
                    count_ops = circ_result["metadata"]["count_ops"]
                except KeyError as ex:
                    raise AnalysisError(
                        "'count_ops' key is not found in the circuit metadata. "
                        "This analysis cannot compute error per gates. "
                        "Please disable this with 'gate_error_ratio=False'."
                    ) from ex
                nclif = circ_result["metadata"]["xval"]
                for (qinds, gate), count in count_ops:
                    formatted_key = tuple(sorted(qinds)), gate
                    avg_gpc[formatted_key] += count / nclif / n_circs
            self._gate_counts_per_clifford = dict(avg_gpc)

            if self.options.gate_error_ratio == "default":
                # Gate error dict is computed for gates appearing in counts dictionary
                # Error ratio among gates is determined based on the predefined lookup table.
                # This is not always accurate for every quantum backends.
                gate_error_ratio = {}
                for qinds, gate in self._gate_counts_per_clifford.keys():
                    if set(qinds) != set(
                            experiment_data.metadata["physical_qubits"]):
                        continue
                    gate_error_ratio[gate] = _lookup_epg_ratio(
                        gate, len(qinds))
                self.set_options(gate_error_ratio=gate_error_ratio)

        # Get qubit number
        self._physical_qubits = experiment_data.metadata["physical_qubits"]
Пример #22
0
    def _add_cal_metadata(self, experiment_data: ExperimentData):
        """Add the oscillation frequency of the experiment to the metadata."""

        param_val = self._cals.get_parameter_value(
            self._param_name,
            self.physical_qubits,
            group=self.experiment_options.group,
        )

        experiment_data.metadata["cal_param_value"] = param_val
        experiment_data.metadata["cal_group"] = self.experiment_options.group
        experiment_data.metadata["osc_freq"] = self.experiment_options.osc_freq
    def test_to_imag(self):
        """Test that we can average the data."""
        processor = DataProcessor("memory")
        processor.append(ToImag(scale=1e-3))

        exp_data = ExperimentData(FakeExperiment())
        exp_data.add_data(self.result_lvl1)

        new_data, error = processor(exp_data.data(0))

        expected_old = {
            "memory": [
                [[1103260.0, -11378508.0], [2959012.0, -16488753.0]],
                [[442170.0, -19283206.0], [-5279410.0, -15339630.0]],
                [[3016514.0, -14548009.0], [-3404756.0, -16743348.0]],
            ],
            "metadata": {
                "experiment_type": "fake_test_experiment"
            },
            "job_id":
            "job-123",
            "meas_level":
            1,
            "shots":
            3,
        }

        expected_new = np.array([
            [-11378.508, -16488.753],
            [-19283.206000000002, -15339.630000000001],
            [-14548.009, -16743.348],
        ])

        self.assertEqual(exp_data.data(0), expected_old)
        self.assertTrue(np.allclose(new_data, expected_new))
        self.assertIsNone(error)

        # Test that we can call with history.
        new_data, error, history = processor.call_with_history(
            exp_data.data(0))
        self.assertEqual(exp_data.data(0), expected_old)
        self.assertTrue(np.allclose(new_data, expected_new))

        self.assertEqual(history[0][0], "ToImag")
        self.assertTrue(np.allclose(history[0][1], expected_new))

        # Test to imaginary on more than one datum
        new_data, error = processor(exp_data.data())

        expected_new = np.array([
            [[-11378.508, -16488.753], [-19283.206, -15339.630],
             [-14548.009, -16743.348]],
            [[-16630.257, -13752.518], [-16031.913, -15840.465],
             [-14955.998, -14538.923]],
        ])

        self.assertTrue(np.allclose(new_data, expected_new))
Пример #24
0
    def test_composite_avg_kerneled_memory_marginalization(self):
        """The the marginalization of level 1 averaged data."""
        test_data = ExperimentData()

        datum = {
            "memory": [
                [0.0, 0.1],  # qubit 0
                [1.0, 1.1],  # qubit 1
                [2.0, 2.1],  # qubit 2
            ],
            "metadata": {
                "experiment_type":
                "ParallelExperiment",
                "composite_index": [0, 1, 2],
                "composite_metadata": [
                    {
                        "experiment_type": "FineXAmplitude",
                        "qubits": [0]
                    },
                    {
                        "experiment_type": "FineXAmplitude",
                        "qubits": [1]
                    },
                    {
                        "experiment_type": "FineXAmplitude",
                        "qubits": [2]
                    },
                ],
                "composite_qubits": [[0], [1], [2]],
                "composite_clbits": [[0], [1], [2]],
            },
            "shots": 5,
            "meas_level": 1,
        }

        test_data.add_data(datum)

        all_sub_data = CompositeAnalysis([])._marginalized_component_data(
            test_data.data())
        for idx, sub_data in enumerate(all_sub_data):
            expected = {
                "metadata": {
                    "experiment_type": "FineXAmplitude",
                    "qubits": [idx]
                },
                "memory": [[idx + 0.0, idx + 0.1]],
            }

            self.assertEqual(expected, sub_data[0])
    def _component_experiment_data(
            self, experiment_data: ExperimentData) -> List[ExperimentData]:
        """Return a list of marginalized experiment data for component experiments.

        Args:
            experiment_data: a composite experiment experiment data container.

        Returns:
            The list of analysis-ready marginalized experiment data for each
            component experiment.

        Raises:
            AnalysisError: if the component experiment data cannot be extracted.
        """
        if not self._flatten_results:
            # Retrieve child data for component experiments for updating
            component_index = experiment_data.metadata.get(
                "component_child_index", [])
            if not component_index:
                raise AnalysisError(
                    "Unable to extract component child experiment data")
            component_expdata = [
                experiment_data.child_data(i) for i in component_index
            ]
        else:
            # Initialize temporary ExperimentData containers for
            # each component experiment to analysis on. These will
            # not be saved but results and figures will be collected
            # from them
            component_expdata = self._initialize_component_experiment_data(
                experiment_data)

        # Compute marginalize data for each component experiment
        marginalized_data = self._marginalized_component_data(
            experiment_data.data())

        # Add the marginalized component data and component job metadata
        # to each component child experiment. Note that this will clear
        # any currently stored data in the experiment. Since copying of
        # child data is handled by the `replace_results` kwarg of the
        # parent container it is safe to always clear and replace the
        # results of child containers in this step
        for sub_expdata, sub_data in zip(component_expdata, marginalized_data):
            # Clear any previously stored data and add marginalized data
            sub_expdata._data.clear()
            sub_expdata.add_data(sub_data)

        return component_expdata
Пример #26
0
    def test_t1_parallel(self):
        """
        Test parallel experiments of T1 using a simulator.
        """

        t1 = [25, 15]
        delays = list(range(1, 40, 3))

        exp0 = T1(0, delays)
        exp2 = T1(2, delays)
        par_exp = ParallelExperiment([exp0, exp2])
        res = par_exp.run(T1Backend([t1[0], None, t1[1]]))
        self.assertExperimentDone(res)

        for i in range(2):
            sub_res = res.child_data(i).analysis_results("T1")
            self.assertEqual(sub_res.quality, "good")
            self.assertAlmostEqual(sub_res.value.n, t1[i], delta=3)

        res.service = FakeService()
        res.save()
        loaded_data = ExperimentData.load(res.experiment_id, res.service)

        for i in range(2):
            sub_res = res.child_data(i).analysis_results("T1")
            sub_loaded = loaded_data.child_data(i).analysis_results("T1")
            self.assertEqual(repr(sub_res), repr(sub_loaded))
Пример #27
0
    def test_t1_end2end(self):
        """
        Test T1 experiment using a simulator.
        """
        t1 = 25e-6
        backend = T1Backend(
            [t1],
            initial_prob1=[0.02],
            readout0to1=[0.02],
            readout1to0=[0.02],
        )

        delays = np.arange(1e-6, 40e-6, 3e-6)

        exp = T1(0, delays)
        exp.analysis.set_options(p0={"amp": 1, "tau": t1, "base": 0})
        exp_data = exp.run(backend, shots=10000)
        self.assertExperimentDone(exp_data)
        res = exp_data.analysis_results("T1")
        self.assertRoundTripSerializable(res.value,
                                         check_func=self.ufloat_equiv)
        self.assertEqual(res.quality, "good")
        self.assertAlmostEqual(res.value.n, t1, delta=3)
        self.assertEqual(res.extra["unit"], "s")

        exp_data.service = FakeService()
        exp_data.save()
        loaded_data = ExperimentData.load(exp_data.experiment_id,
                                          exp_data.service)
        exp_res = exp_data.analysis_results()
        load_res = loaded_data.analysis_results()
        repr1 = sorted([repr(res) for res in exp_res])
        repr2 = sorted([repr(res) for res in load_res])
        self.assertEqual(repr1, repr2)
Пример #28
0
    def update_calibrations(self, experiment_data: ExperimentData):
        r"""Update the amplitude of the pulse in the calibrations.

        The update rule of this experiment is

        .. math::

            A \to A \frac{\theta_\text{target}}{\theta_\text{target} + {\rm d}\theta}

        Where :math:`A` is the amplitude of the pulse before the update.

        Args:
            experiment_data: The experiment data from which to extract the measured over/under
                rotation used to adjust the amplitude.
        """
        data = experiment_data.data()

        # No data -> no update
        if len(data) > 0:
            result_index = self.experiment_options.result_index
            group = data[0]["metadata"]["cal_group"]
            target_angle = data[0]["metadata"]["target_angle"]
            prev_amp = data[0]["metadata"]["cal_param_value"]

            d_theta = BaseUpdater.get_value(experiment_data, "d_theta",
                                            result_index)

            BaseUpdater.add_parameter_value(
                self._cals,
                experiment_data,
                prev_amp * target_angle / (target_angle + d_theta),
                self._param_name,
                self._sched_name,
                group,
            )
Пример #29
0
    def test_t1_end2end(self):
        """
        Test T1 experiment using a simulator.
        """
        t1 = 25e-6
        backend = T1Backend(
            [t1],
            initial_prob1=[0.02],
            readout0to1=[0.02],
            readout1to0=[0.02],
        )

        delays = np.arange(1e-6, 40e-6, 3e-6)

        exp = T1(0, delays)
        exp.analysis.set_options(p0={"amp": 1, "tau": t1, "base": 0})
        exp_data = exp.run(backend, shots=10000)
        res = exp_data.analysis_results("T1")
        fitval = res.value
        self.assertEqual(res.quality, "good")
        self.assertAlmostEqual(fitval.value, t1, delta=3)
        self.assertEqual(fitval.unit, "s")

        exp_data.service = FakeService()
        exp_data.save()
        loaded_data = ExperimentData.load(exp_data.experiment_id,
                                          exp_data.service)
        self.assertEqual(repr(exp_data.analysis_results("T1")),
                         repr(loaded_data.analysis_results("T1")))
Пример #30
0
    def setUp(self):
        """Setup variables used for testing."""
        super().setUp()

        mem1 = ExperimentResultData(memory=[
            [[1103260.0, -11378508.0], [2959012.0, -16488753.0]],
            [[442170.0, -19283206.0], [-5279410.0, -15339630.0]],
            [[3016514.0, -14548009.0], [-3404756.0, -16743348.0]],
        ])

        mem2 = ExperimentResultData(memory=[
            [[5131962.0, -16630257.0], [4438870.0, -13752518.0]],
            [[3415985.0, -16031913.0], [2942458.0, -15840465.0]],
            [[5199964.0, -14955998.0], [4030843.0, -14538923.0]],
        ])

        res1 = ExperimentResult(shots=3,
                                success=True,
                                meas_level=1,
                                data=mem1,
                                header=self.header)
        res2 = ExperimentResult(shots=3,
                                success=True,
                                meas_level=1,
                                data=mem2,
                                header=self.header)

        self.result_lvl1 = Result(results=[res1, res2],
                                  **self.base_result_args)

        raw_counts1 = {"0x0": 4, "0x2": 6}
        raw_counts2 = {"0x0": 2, "0x2": 8}
        data1 = ExperimentResultData(counts=dict(**raw_counts1))
        data2 = ExperimentResultData(counts=dict(**raw_counts2))
        res1 = ExperimentResult(shots=10,
                                success=True,
                                meas_level=2,
                                data=data1,
                                header=self.header)
        res2 = ExperimentResult(shots=10,
                                success=True,
                                meas_level=2,
                                data=data2,
                                header=self.header)
        self.exp_data_lvl2 = ExperimentData(FakeExperiment())
        self.exp_data_lvl2.add_data(
            Result(results=[res1, res2], **self.base_result_args))