Exemplo n.º 1
0
    def test_composite_tags(self):
        """
        Test the tags setter, add_tags_recursive, remove_tags_recursive
        """
        exp1 = FakeExperiment([0, 2])
        exp2 = FakeExperiment([1, 3])
        par_exp = BatchExperiment([exp1, exp2])
        expdata = par_exp.run(FakeBackend()).block_for_results()
        data1 = expdata.child_data(0)
        data2 = expdata.child_data(1)

        expdata.tags = ["a", "c", "a"]
        data1.tags = ["b"]
        self.assertEqual(sorted(expdata.tags), ["a", "c"])
        self.assertEqual(sorted(data1.tags), ["b"])
        self.assertEqual(sorted(data2.tags), [])

        expdata.add_tags_recursive(["d", "c"])
        self.assertEqual(sorted(expdata.tags), ["a", "c", "d"])
        self.assertEqual(sorted(data1.tags), ["b", "c", "d"])
        self.assertEqual(sorted(data2.tags), ["c", "d"])

        expdata.remove_tags_recursive(["a", "b"])
        self.assertEqual(sorted(expdata.tags), ["c", "d"])
        self.assertEqual(sorted(data1.tags), ["c", "d"])
        self.assertEqual(sorted(data2.tags), ["c", "d"])
Exemplo n.º 2
0
 def test_nested_composite(self):
     """
     Test nested parallel experiments.
     """
     exp1 = FakeExperiment([0, 2])
     exp2 = FakeExperiment([1, 3])
     exp3 = ParallelExperiment([exp1, exp2])
     exp4 = BatchExperiment([exp3, exp1])
     exp5 = ParallelExperiment([exp4, FakeExperiment([4])])
     nested_exp = BatchExperiment([exp5, exp3])
     expdata = nested_exp.run(FakeBackend())
     self.assertExperimentDone(expdata)
Exemplo n.º 3
0
    def test_mixed_batch_exp(self):
        """Test batch state and process tomography experiment"""
        # Subsystem unitaries
        state_op = qi.random_unitary(2, seed=321)
        chan_op = qi.random_unitary(2, seed=123)

        state_target = qi.Statevector(state_op.to_instruction())
        chan_target = qi.Choi(chan_op.to_instruction())

        state_exp = StateTomography(state_op)
        chan_exp = ProcessTomography(chan_op)
        batch_exp = BatchExperiment([state_exp, chan_exp])

        # Run batch experiments
        backend = AerSimulator(seed_simulator=9000)
        par_data = batch_exp.run(backend)
        self.assertExperimentDone(par_data)

        f_threshold = 0.95

        # Check state tomo results
        state_results = par_data.child_data(0).analysis_results()
        state = filter_results(state_results, "state").value

        # Check fit state fidelity
        state_fid = filter_results(state_results, "state_fidelity").value
        self.assertGreater(state_fid, f_threshold, msg="fit fidelity is low")

        # Manually check fidelity
        target_fid = qi.state_fidelity(state, state_target, validate=False)
        self.assertAlmostEqual(state_fid,
                               target_fid,
                               places=6,
                               msg="result fidelity is incorrect")

        # Check process tomo results
        chan_results = par_data.child_data(1).analysis_results()
        chan = filter_results(chan_results, "state").value

        # Check fit process fidelity
        chan_fid = filter_results(chan_results, "process_fidelity").value
        self.assertGreater(chan_fid, f_threshold, msg="fit fidelity is low")

        # Manually check fidelity
        target_fid = qi.process_fidelity(chan,
                                         chan_target,
                                         require_cp=False,
                                         require_tp=False)
        self.assertAlmostEqual(chan_fid,
                               target_fid,
                               places=6,
                               msg="result fidelity is incorrect")
Exemplo n.º 4
0
 def test_nested_composite(self):
     """
     Test nested parallel experiments.
     """
     exp1 = FakeExperiment([0, 2])
     exp2 = FakeExperiment([1, 3])
     exp3 = ParallelExperiment([exp1, exp2])
     exp4 = BatchExperiment([exp3, exp1])
     exp5 = ParallelExperiment([exp4, FakeExperiment([4])])
     nested_exp = BatchExperiment([exp5, exp3])
     expdata = nested_exp.run(FakeBackend()).block_for_results()
     status = expdata.status()
     self.assertEqual(status.name, "DONE")
    def test_batch_exp_with_measurement_qubits(self):
        """Test batch process tomography experiment with kwargs"""
        seed = 1111
        nq = 3
        ops = [qi.random_unitary(2, seed=seed + i) for i in range(nq)]

        # Preparation circuit
        circuit = QuantumCircuit(nq)
        for i, op in enumerate(ops):
            circuit.append(op, [i])

        # Component experiments
        exps = []
        targets = []
        for i in range(nq):
            targets.append(ops[i])
            exps.append(
                ProcessTomography(circuit,
                                  measurement_qubits=[i],
                                  preparation_qubits=[i]))

        # Run batch experiments
        backend = AerSimulator(seed_simulator=9000)
        batch_exp = BatchExperiment(exps)
        batch_data = batch_exp.run(backend)
        batch_data.block_for_results()

        # Check target fidelity of component experiments
        f_threshold = 0.95
        for i in range(batch_exp.num_experiments):
            results = batch_data.component_experiment_data(
                i).analysis_results()

            # Check state is density matrix
            state = filter_results(results, "state").value
            self.assertTrue(isinstance(state, qi.Choi),
                            msg="fitted state is not a Choi matrix")

            # Check fit state fidelity
            fid = filter_results(results, "process_fidelity").value
            self.assertGreater(fid, f_threshold, msg="fit fidelity is low")

            # Manually check fidelity
            target_fid = qi.process_fidelity(state,
                                             targets[i],
                                             require_tp=False,
                                             require_cp=False)
            self.assertAlmostEqual(fid,
                                   target_fid,
                                   places=6,
                                   msg="result fidelity is incorrect")
Exemplo n.º 6
0
    def setUp(self):
        super().setUp()

        self.backend = FakeBackend()
        self.share_level = "hey"

        exp1 = FakeExperiment([0, 2])
        exp2 = FakeExperiment([1, 3])
        par_exp = ParallelExperiment([exp1, exp2])
        exp3 = FakeExperiment([0, 1, 2, 3])
        batch_exp = BatchExperiment([par_exp, exp3])

        self.rootdata = batch_exp.run(backend=self.backend).block_for_results()
        self.assertEqual(len(self.rootdata.child_data()), 2)

        self.rootdata.share_level = self.share_level
Exemplo n.º 7
0
    def test_batch_exp(self):
        """Test batch state tomography experiment with measurement_qubits kwarg"""
        # Subsystem unitaries
        seed = 1111
        nq = 3
        ops = [qi.random_unitary(2, seed=seed + i) for i in range(nq)]

        # Preparation circuit
        circuit = QuantumCircuit(nq)
        for i, op in enumerate(ops):
            circuit.append(op, [i])

        # Component experiments
        exps = []
        targets = []
        for i in range(nq):
            targets.append(qi.Statevector(ops[i].to_instruction()))
            exps.append(StateTomography(circuit, measurement_qubits=[i]))

        # Run batch experiments
        backend = AerSimulator(seed_simulator=9000)
        batch_exp = BatchExperiment(exps)
        batch_data = batch_exp.run(backend)
        self.assertExperimentDone(batch_data)

        # Check target fidelity of component experiments
        f_threshold = 0.95
        for i in range(batch_exp.num_experiments):
            results = batch_data.child_data(i).analysis_results()

            # Check state is density matrix
            state = filter_results(results, "state").value
            self.assertTrue(isinstance(state, qi.DensityMatrix),
                            msg="fitted state is not density matrix")

            # Check fit state fidelity
            fid = filter_results(results, "state_fidelity").value
            self.assertGreater(fid, f_threshold, msg="fit fidelity is low")

            # Manually check fidelity
            target_fid = qi.state_fidelity(state, targets[i], validate=False)
            self.assertAlmostEqual(fid,
                                   target_fid,
                                   places=6,
                                   msg="result fidelity is incorrect")
Exemplo n.º 8
0
    def test_analysis_replace_results_false(self):
        """
        Test replace_results of composite experiment data
        """
        exp1 = FakeExperiment([0, 2])
        exp2 = FakeExperiment([1, 3])
        par_exp = BatchExperiment([exp1, exp2])
        data1 = par_exp.run(FakeBackend()).block_for_results()

        # Additional data not part of composite experiment
        exp3 = FakeExperiment([0, 1])
        extra_data = exp3.run(FakeBackend()).block_for_results()
        data1.add_child_data(extra_data)

        # Replace results
        data2 = par_exp.analysis.run(data1).block_for_results()
        self.assertNotEqual(data1.experiment_id, data2.experiment_id)
        self.assertEqual(len(data1.child_data()), len(data2.child_data()))
        for sub1, sub2 in zip(data1.child_data(), data2.child_data()):
            self.assertNotEqual(sub1.experiment_id, sub2.experiment_id)
Exemplo n.º 9
0
    def test_flatten_results_partial(self):
        """Test flattening results."""
        exp0 = FakeExperiment([0])
        exp1 = FakeExperiment([1])
        exp2 = FakeExperiment([2])
        exp3 = FakeExperiment([3])
        comp_exp = BatchExperiment([
            ParallelExperiment([exp0, exp1, exp2], flatten_results=True),
            ParallelExperiment([exp2, exp3], flatten_results=True),
        ], )
        expdata = comp_exp.run(FakeBackend())
        self.assertExperimentDone(expdata)
        # Check out experiment wasnt flattened
        self.assertEqual(len(expdata.child_data()), 2)
        self.assertEqual(len(expdata.analysis_results()), 0)

        # check inner experiments were flattened
        child0 = expdata.child_data(0)
        child1 = expdata.child_data(1)
        self.assertEqual(len(child0.child_data()), 0)
        self.assertEqual(len(child1.child_data()), 0)
        # Check right number of analysis results is returned
        self.assertEqual(len(child0.analysis_results()), 9)
        self.assertEqual(len(child1.analysis_results()), 6)
Exemplo n.º 10
0
class TestBatchTranspileOptions(QiskitExperimentsTestCase):
    """
    For batch experiments, circuits are transpiled with the transpile options of the
    sub-experiments
    """
    class SimpleExperiment(BaseExperiment):
        """
        An experiment that creates a circuit of four qubits.
        Qubits 1 and 2 are inactive.
        Qubits 0 and 3 form a Bell state.
        The purpose: we will test with varying coupling maps, spanning from a coupling map that
        directly connects qubits 0 and 3 (hence qubits 1 and 2 remains inactive also in the
        transpiled circuit) to a coupling map with distance 3 between qubits 0 and 3.
        """
        def __init__(self, qubits, backend=None):
            super().__init__(
                qubits,
                analysis=TestBatchTranspileOptions.SimpleAnalysis(),
                backend=backend)

        def circuits(self):
            circ = QuantumCircuit(4, 4)
            circ.h(0)
            circ.cx(0, 3)
            circ.barrier()
            circ.measure(range(4), range(4))
            return [circ]

    class SimpleAnalysis(BaseAnalysis):
        """
        The number of non-zero counts is equal to
        2^(distance between qubits 0 and 3 in the transpiled circuit + 1)
        """
        def _run_analysis(self, experiment_data):
            analysis_results = [
                AnalysisResultData(name="non-zero counts",
                                   value=len(
                                       experiment_data.data(0)["counts"])),
            ]

            return analysis_results, []

    def setUp(self):
        super().setUp()

        exp1 = self.SimpleExperiment(range(4))
        exp2 = self.SimpleExperiment(range(4))
        exp3 = self.SimpleExperiment(range(4))
        batch1 = BatchExperiment([exp2, exp3])
        self.batch2 = BatchExperiment([exp1, batch1])

        exp1.set_transpile_options(coupling_map=[[0, 1], [1, 3], [3, 2]])
        exp2.set_transpile_options(coupling_map=[[0, 1], [1, 2], [2, 3]])

        # exp3 circuit: two active qubits and six instructions: hadamard, cnot, four measurements.
        # exp1 circuit: three active qubits (0, 1, 3) and seven instructions: hadamard,
        #               two 2Q gates, four measurements.
        # exp2 circuit: four active qubits and eight instructions.

    def test_batch_transpiled_circuits(self):
        """
        For batch experiments, circuits are transpiled with the transpile options of the
        sub-experiments
        """
        circs = self.batch2._transpiled_circuits()
        numbers_of_gates = [len(circ.data) for circ in circs]
        self.assertEqual(set(numbers_of_gates), set([7, 8, 9]))

    def test_batch_transpile_options_integrated(self):
        """
        The goal is to verify that not only `_trasnpiled_circuits` works well
        (`test_batch_transpiled_circuits` takes care of it) but that it's correctly called within
        the entire flow of `BaseExperiment.run`.
        """
        backend = Aer.get_backend("aer_simulator")
        noise_model = noise.NoiseModel()
        noise_model.add_all_qubit_quantum_error(
            noise.depolarizing_error(0.5, 2), ["cx", "swap"])

        expdata = self.batch2.run(backend, noise_model=noise_model, shots=1000)
        expdata.block_for_results()

        self.assertEqual(expdata.child_data(0).analysis_results(0).value, 8)
        self.assertEqual(
            expdata.child_data(1).child_data(0).analysis_results(0).value, 16)
        self.assertEqual(
            expdata.child_data(1).child_data(1).analysis_results(0).value, 4)