def _monte_carlo_dfe(program: Program, qubits: Sequence[int], in_states: list, n_terms: int,
                     benchmarker: BenchmarkConnection) -> ExperimentSetting:
    """Yield experiments over itertools.product(in_paulis).

    Used as a helper function for generate_monte_carlo_xxx_dfe_experiment routines.

    :param program: A program comprised of clifford gates
    :param qubits: The qubits to perform DFE on. This can be a superset of the qubits
        used in ``program``.
    :param in_states: Use these single-qubit Pauli operators in every itertools.product()
        to generate an exhaustive list of DFE experiments.
    :param n_terms: Number of preparation and measurement settings to be chosen at random
    :return: experiment setting iterator
    :rtype: ``ExperimentSetting``
    """
    all_st_inds = np.random.randint(len(in_states), size=(n_terms, len(qubits)))
    for st_inds in all_st_inds:
        i_st = functools.reduce(mul, (in_states[si](qubits[i])
                                      for i, si in enumerate(st_inds)
                                      if in_states[si] is not None), TensorProductState())

        # TODO: we should not pick a new one, we should just return a trivial experiment
        while len(i_st) == 0:
            # pick a new one
            second_try_st_inds = np.random.randint(len(in_states), size=len(qubits))
            i_st = functools.reduce(mul, (in_states[si](qubits[i])
                                          for i, si in enumerate(second_try_st_inds)
                                          if in_states[si] is not None), TensorProductState())

        yield ExperimentSetting(
            in_state=i_st,
            out_operator=benchmarker.apply_clifford_to_pauli(program, _state_to_pauli(i_st)),
        )
def _exhaustive_dfe(program: Program, qubits: Sequence[int], in_states,
                    benchmarker: BenchmarkConnection) -> ExperimentSetting:
    """Yield experiments over itertools.product(in_paulis).

    Used as a helper function for generate_exhaustive_xxx_dfe_experiment routines.

    :param program: A program comprised of clifford gates
    :param qubits: The qubits to perform DFE on. This can be a superset of the qubits
        used in ``program``.
    :param in_states: Use these single-qubit Pauli operators in every itertools.product()
        to generate an exhaustive list of DFE experiments.
    :return: experiment setting iterator
    :rtype: ``ExperimentSetting``
    """
    n_qubits = len(qubits)
    for i_states in itertools.product(in_states, repeat=n_qubits):
        i_st = functools.reduce(mul, (op(q) for op, q in zip(i_states, qubits) if op is not None),
                                TensorProductState())

        if len(i_st) == 0:
            continue

        yield ExperimentSetting(
            in_state=i_st,
            out_operator=benchmarker.apply_clifford_to_pauli(program, _state_to_pauli(i_st)),
        )
Exemplo n.º 3
0
def test_stats_from_measurements():
    d_results = {0: np.array([0] * 10), 1: np.array([1] * 10)}
    setting = ExperimentSetting(TensorProductState(), sZ(0) * sX(1))
    n_shots = 1000

    obs_mean, obs_var = _stats_from_measurements(d_results, setting, n_shots)
    assert obs_mean == -1.0
    assert obs_var == 0.0
Exemplo n.º 4
0
def _generate_random_states(n_qubits, n_terms):
    oneq_states = [SIC0, SIC1, SIC2, SIC3, plusX, minusX, plusY, minusY, plusZ, minusZ]
    all_s_inds = np.random.randint(len(oneq_states), size=(n_terms, n_qubits))
    states = []
    for s_inds in all_s_inds:
        state = functools.reduce(mul, (oneq_states[pi](i) for i, pi in enumerate(s_inds)),
                                 TensorProductState([]))
        states += [state]
    return states
Exemplo n.º 5
0
    def compile_tomo_expts(self, pauli_list=None):
        """
        This method compiles the tomography experiment circuits
        and prepares them for simulation.
        Every time the circuits are adjusted,
        re-compiling the tomography experiments
        is required to affect the outcome.
        """
        self.offset = 0
        # use Forest's sorting algo from the Tomography suite
        # to group Pauli measurements together
        experiments = []
        if pauli_list is None:
            pauli_list = self.pauli_list
        for term in pauli_list:
            # if the Pauli term is an identity operator,
            # add the term's coefficient directly to the VQE class' offset
            if len(term.operations_as_set()) == 0:
                self.offset += term.coefficient.real
            else:
                # initial state and term pair.
                experiments.append(ExperimentSetting(
                        TensorProductState(),
                        term))

        suite = Experiment(experiments, program=Program())

        gsuite = group_experiments(suite)

        grouped_list = []
        for setting in gsuite:
            group = []
            for term in setting:
                group.append(term.out_operator)
            grouped_list.append(group)

        if self.verbose:
            print('Number of tomography experiments: ', len(grouped_list))

        self.experiment_list = []
        for group in grouped_list:
            self.experiment_list.append(
                    GroupedPauliSetting(group,
                            qc=self.qc,
                            ref_state=self.ref_state,
                            ansatz=self.ansatz,
                            shotN=self.shotN,
                            parametric_way=self.parametric_way,
                            n_qubits=self.n_qubits,
                            method=self.method,
                            verbose=self.verbose,
                            cq=self.custom_qubits,
                            ))
Exemplo n.º 6
0
def test_group_experiments_greedy():
    ungrouped_tomo_expt = TomographyExperiment(
        [[ExperimentSetting(PauliTerm.from_compact_str('(1+0j)*Z7Y8Z1Y4Z2Y5Y0X6'),
                            PauliTerm.from_compact_str('(1+0j)*Z4X8Y5X3Y7Y1'))],
         [ExperimentSetting(sZ(7), sY(1))]], program=Program(H(0), H(1), H(2)),
        qubits=[0, 1, 2])
    grouped_tomo_expt = group_experiments(ungrouped_tomo_expt, method='greedy')
    expected_grouped_tomo_expt = TomographyExperiment(
        [[
            ExperimentSetting(TensorProductState.from_str('Z0_7 * Y0_8 * Z0_1 * Y0_4 * '
                                                          'Z0_2 * Y0_5 * Y0_0 * X0_6'),
                              PauliTerm.from_compact_str('(1+0j)*Z4X8Y5X3Y7Y1')),
            ExperimentSetting(plusZ(7), sY(1))
        ]],
        program=Program(H(0), H(1), H(2)),
        qubits=[0, 1, 2])
    assert grouped_tomo_expt == expected_grouped_tomo_expt
Exemplo n.º 7
0
def _sic_process_tomo_settings(qubits: Sequence[int]):
    """Yield settings over SIC basis cross I,X,Y,Z operators

    Used as a helper function for generate_process_tomography_experiment

    :param qubits: The qubits to tomographize.
    """
    for in_sics in itertools.product([SIC0, SIC1, SIC2, SIC3], repeat=len(qubits)):
        i_state = functools.reduce(mul, (state(q) for state, q in zip(in_sics, qubits)),
                                   TensorProductState())
        for o_ops in itertools.product([sI, sX, sY, sZ], repeat=len(qubits)):
            o_op = functools.reduce(mul, (op(q) for op, q in zip(o_ops, qubits)), sI())

            if is_identity(o_op):
                continue

            yield ExperimentSetting(
                in_state=i_state,
                out_operator=o_op,
            )
Exemplo n.º 8
0
def _pauli_process_tomo_settings(qubits):
    """Yield settings over +-XYZ basis cross I,X,Y,Z operators

    Used as a helper function for generate_process_tomography_experiment

    :param qubits: The qubits to tomographize.
    """
    for states in itertools.product([plusX, minusX, plusY, minusY, plusZ, minusZ],
                                    repeat=len(qubits)):
        i_state = functools.reduce(mul, (state(q) for state, q in zip(states, qubits)),
                                   TensorProductState())
        for o_ops in itertools.product([sI, sX, sY, sZ], repeat=len(qubits)):
            o_op = functools.reduce(mul, (op(q) for op, q in zip(o_ops, qubits)), sI())

            if is_identity(o_op):
                continue

            yield ExperimentSetting(
                in_state=i_state,
                out_operator=o_op,
            )
Exemplo n.º 9
0
    def compile_tomo_expts(self, pauli_list=None):
        """
        This method compiles the tomography experiment circuits
        and prepares them for simulation.
        Every time the circuits are adjusted,
        re-compiling the tomography experiments
        is required to affect the outcome.
        """
        # use Forest's sorting algo from the Tomography suite
        # to group Pauli measurements together
        settings = []
        if pauli_list is None:
            pauli_list = self.pauli_list

        for term in pauli_list:
            # skip an identity operator,
            if len(term.operations_as_set()) > 0:
                # initial state and term pair.
                settings.append(ExperimentSetting(
                        TensorProductState(),
                        term))
        # group_experiments cannot be directly run
        # because there may be experiment with multiple settings.
        # so here we just use group_experiments to sort out the settings,
        # then reset the experiments with additional measurements.
        experiments = Experiment(settings, Program())
        suite = group_experiments(experiments)
        # we just need the grouped settings.
        grouped_pauil_terms = []
        for setting in suite:
            group = []
            for i, term in enumerate(setting):
                pauil_term = term.out_operator.copy()
                # Coefficients to be multiplied.
                pauil_term.coefficient = complex(1.)
                if i == 0:
                    group.append(pauil_term)
                elif len(pauil_term) > len(group[0]):
                    group.insert(0, pauil_term)
                else:
                    group.append(pauil_term)
            # make sure the longest pauil_term contains all the small
            # pauil_terms. Otherwise, we prepare a bigger one.
            bigger_pauli = group[0]
            if len(group) > 1:
                for term in group[1:]:
                    for iq, op in term.operations_as_set():
                        if op != group[0][iq]:
                            assert(group[0][iq] == "I"), \
                                    (f"{term} and {group[0]}"
                                    " not compatible!")
                            if bigger_pauli is group[0]:
                                bigger_pauli == group[0].copy()
                            bigger_pauli *= PauliTerm(op, iq)
                if bigger_pauli is not group[0]:
                    print(f"new pauli_term generated: {bigger_pauli}")
                    group.insert(0, bigger_pauli)
            grouped_pauil_terms.append(group)
        # group settings with additional_expectations.
        grouped_settings = []
        for pauil_terms in grouped_pauil_terms:
            additional = None
            if len(pauil_terms) > 1:
                additional = []
                for term in pauil_terms[1:]:
                    additional.append(term.get_qubits())
            grouped_settings.append(
                    ExperimentSetting(TensorProductState(),
                            pauil_terms[0],
                            additional_expectations=additional))

        # get the uccsd program
        prog = Program()
        prog += RESET()
        prog += self.ref_state + self.ansatz
        prog.wrap_in_numshots_loop(shots=self.shotN)
        self.experiment_list = Experiment(grouped_settings, prog)
        print('Number of tomography experiments: ',
                len(self.experiment_list))
        # calibration expreimental results.
        self.calibrations = self.qc.calibrate(self.experiment_list)
Exemplo n.º 10
0
    def expval(self, observable, wires, par):
        # Single-qubit observable
        if len(wires) == 1:
            # identify Experiment Settings for each of the possible single-qubit observables
            wire = wires[0]
            qubit = self.wiring[wire]
            d_expt_settings = {
                "Identity":
                [ExperimentSetting(TensorProductState(), sI(qubit))],
                "PauliX": [ExperimentSetting(TensorProductState(), sX(qubit))],
                "PauliY": [ExperimentSetting(TensorProductState(), sY(qubit))],
                "PauliZ": [ExperimentSetting(TensorProductState(), sZ(qubit))],
                "Hadamard": [
                    ExperimentSetting(TensorProductState(),
                                      float(np.sqrt(1 / 2)) * sX(qubit)),
                    ExperimentSetting(TensorProductState(),
                                      float(np.sqrt(1 / 2)) * sZ(qubit))
                ]
            }
            # expectation values for single-qubit observables
            if observable in [
                    "PauliX", "PauliY", "PauliZ", "Identity", "Hadamard"
            ]:
                prep_prog = Program()
                for instr in self.program.instructions:
                    if isinstance(instr, Gate):
                        # assumes single qubit gates
                        gate, _ = instr.out().split(' ')
                        prep_prog += Program(str(gate) + ' ' + str(qubit))
                if self.readout_error is not None:
                    prep_prog.define_noisy_readout(qubit,
                                                   p00=self.readout_error[0],
                                                   p11=self.readout_error[1])
                tomo_expt = TomographyExperiment(
                    settings=d_expt_settings[observable], program=prep_prog)
                grouped_tomo_expt = group_experiments(tomo_expt)
                meas_obs = list(
                    measure_observables(
                        self.qc,
                        grouped_tomo_expt,
                        active_reset=self.active_reset,
                        symmetrize_readout=self.symmetrize_readout,
                        calibrate_readout=self.calibrate_readout))
                return np.sum(
                    [expt_result.expectation for expt_result in meas_obs])

            elif observable == 'Hermitian':
                # <H> = \sum_i w_i p_i
                Hkey = tuple(par[0].flatten().tolist())
                w = self._eigs[Hkey]['eigval']
                return w[0] * p0 + w[1] * p1

        # Multi-qubit observable
        # ----------------------
        # Currently, we only support qml.expval.Hermitian(A, wires),
        # where A is a 2^N x 2^N matrix acting on N wires.
        #
        # Eventually, we will also support tensor products of Pauli
        # matrices in the PennyLane UI.

        probs = self.probabilities(wires)

        if observable == 'Hermitian':
            Hkey = tuple(par[0].flatten().tolist())
            w = self._eigs[Hkey]['eigval']
            # <A> = \sum_i w_i p_i
            return w @ probs
Exemplo n.º 11
0
    def expval(self, observable):
        wires = observable.wires
        # Single-qubit observable
        if len(wires) == 1:
            # identify Experiment Settings for each of the possible single-qubit observables
            wire = wires[0]
            qubit = self.wiring[wire]
            d_expt_settings = {
                "Identity":
                [ExperimentSetting(TensorProductState(), sI(qubit))],
                "PauliX": [ExperimentSetting(TensorProductState(), sX(qubit))],
                "PauliY": [ExperimentSetting(TensorProductState(), sY(qubit))],
                "PauliZ": [ExperimentSetting(TensorProductState(), sZ(qubit))],
                "Hadamard": [
                    ExperimentSetting(TensorProductState(),
                                      float(np.sqrt(1 / 2)) * sX(qubit)),
                    ExperimentSetting(TensorProductState(),
                                      float(np.sqrt(1 / 2)) * sZ(qubit))
                ]
            }
            # expectation values for single-qubit observables
            if observable.name in [
                    "PauliX", "PauliY", "PauliZ", "Identity", "Hadamard"
            ]:
                prep_prog = Program()
                for instr in self.program.instructions:
                    if isinstance(instr, Gate):
                        # split gate and wires -- assumes 1q and 2q gates
                        tup_gate_wires = instr.out().split(' ')
                        gate = tup_gate_wires[0]
                        str_instr = str(gate)
                        # map wires to qubits
                        for w in tup_gate_wires[1:]:
                            str_instr += f' {int(w)}'
                        prep_prog += Program(str_instr)

                if self.readout_error is not None:
                    prep_prog.define_noisy_readout(qubit,
                                                   p00=self.readout_error[0],
                                                   p11=self.readout_error[1])

                # All observables are rotated and can be measured in the PauliZ basis
                tomo_expt = Experiment(settings=d_expt_settings["PauliZ"],
                                       program=prep_prog)
                grouped_tomo_expt = group_experiments(tomo_expt)
                meas_obs = list(
                    measure_observables(
                        self.qc,
                        grouped_tomo_expt,
                        active_reset=self.active_reset,
                        symmetrize_readout=self.symmetrize_readout,
                        calibrate_readout=self.calibrate_readout))
                return np.sum(
                    [expt_result.expectation for expt_result in meas_obs])

            elif observable.name == 'Hermitian':
                # <H> = \sum_i w_i p_i
                Hkey = tuple(par[0].flatten().tolist())
                w = self._eigs[Hkey]['eigval']
                return w[0] * p0 + w[1] * p1

        return super().expval(observable)
Exemplo n.º 12
0
    def expval(self, observable):
        wires = observable.wires

        # `measure_observables` called only when parametric compilation is turned off
        if not self.parametric_compilation:

            # Single-qubit observable
            if len(wires) == 1:

                # Ensure sensible observable
                assert observable.name in [
                    "PauliX", "PauliY", "PauliZ", "Identity", "Hadamard"
                ], "Unknown observable"

                # Create appropriate PauliZ operator
                wire = wires[0]
                qubit = self.wiring[wire]
                pauli_obs = sZ(qubit)

            # Multi-qubit observable
            elif len(wires) > 1 and isinstance(
                    observable, Tensor) and not self.parametric_compilation:

                # All observables are rotated to be measured in the Z-basis, so we just need to
                # check which wires exist in the observable, map them to physical qubits, and measure
                # the product of PauliZ operators on those qubits
                pauli_obs = sI()
                for wire in observable.wires:
                    qubit = wire
                    pauli_obs *= sZ(self.wiring[qubit])

            # Program preparing the state in which to measure observable
            prep_prog = Program()
            for instr in self.program.instructions:
                if isinstance(instr, Gate):
                    # split gate and wires -- assumes 1q and 2q gates
                    tup_gate_wires = instr.out().split(" ")
                    gate = tup_gate_wires[0]
                    str_instr = str(gate)
                    # map wires to qubits
                    for w in tup_gate_wires[1:]:
                        str_instr += f" {int(w)}"
                    prep_prog += Program(str_instr)

            if self.readout_error is not None:
                for wire in observable.wires:
                    qubit = wire
                    prep_prog.define_noisy_readout(self.wiring[qubit],
                                                   p00=self.readout_error[0],
                                                   p11=self.readout_error[1])

            # Measure out multi-qubit observable
            tomo_expt = Experiment(
                settings=[ExperimentSetting(TensorProductState(), pauli_obs)],
                program=prep_prog)
            grouped_tomo_expt = group_experiments(tomo_expt)
            meas_obs = list(
                measure_observables(
                    self.qc,
                    grouped_tomo_expt,
                    active_reset=self.active_reset,
                    symmetrize_readout=self.symmetrize_readout,
                    calibrate_readout=self.calibrate_readout,
                ))

            # Return the estimated expectation value
            return np.sum(
                [expt_result.expectation for expt_result in meas_obs])

        # Calculation of expectation value without using `measure_observables`
        return super().expval(observable)