Ejemplo n.º 1
0
    def test_chop_real_only(self):

        paulis = ['IXYZ', 'XXZY', 'IIZZ', 'XXYY', 'ZZXX', 'YYYY']
        coeffs = [0.2, 0.6, 0.8, -0.2, -0.6, -0.8]
        op = Operator(paulis=[])
        for coeff, pauli in zip(coeffs, paulis):
            pauli_term = [coeff, Pauli.from_label(pauli)]
            op += Operator(paulis=[pauli_term])

        op1 = copy.deepcopy(op)
        op1.chop(threshold=0.4)
        self.assertEqual(len(op1.paulis), 4, "\n{}".format(op1.print_operators()))
        gt_op1 = Operator(paulis=[])
        for i in range(1, 3):
            pauli_term = [coeffs[i], Pauli.from_label(paulis[i])]
            gt_op1 += Operator(paulis=[pauli_term])
            pauli_term = [coeffs[i+3], Pauli.from_label(paulis[i+3])]
            gt_op1 += Operator(paulis=[pauli_term])
        self.assertEqual(op1, gt_op1)

        op2 = copy.deepcopy(op)
        op2.chop(threshold=0.7)
        self.assertEqual(len(op2.paulis), 2, "\n{}".format(op2.print_operators()))
        gt_op2 = Operator(paulis=[])
        for i in range(2, 3):
            pauli_term = [coeffs[i], Pauli.from_label(paulis[i])]
            gt_op2 += Operator(paulis=[pauli_term])
            pauli_term = [coeffs[i+3], Pauli.from_label(paulis[i+3])]
            gt_op2 += Operator(paulis=[pauli_term])
        self.assertEqual(op2, gt_op2)

        op3 = copy.deepcopy(op)
        op3.chop(threshold=0.9)
        self.assertEqual(len(op3.paulis), 0, "\n{}".format(op3.print_operators()))
        gt_op3 = Operator(paulis=[])
        for i in range(3, 3):
            pauli_term = [coeffs[i], Pauli.from_label(paulis[i])]
            gt_op3 += Operator(paulis=[pauli_term])
            pauli_term = [coeffs[i+3], Pauli.from_label(paulis[i+3])]
            gt_op3 += Operator(paulis=[pauli_term])
        self.assertEqual(op3, gt_op3)
    def construct_circuit(self, x, qr=None, inverse=False):
        """
        Construct the second order expansion based on given data.

        Args:
            x (numpy.ndarray): 1-D to-be-transformed data.
            qr (QauntumRegister, optional): the QuantumRegister object for the circuit, if None,
                                  generate new registers with name q.
            inverse (bool, optional): whether or not inverse the circuit

        Returns:
            QuantumCircuit: a quantum circuit transform data x.
        Raises:
            TypeError: invalid input
            ValueError: invalid input
        """
        if not isinstance(x, np.ndarray):
            raise TypeError("x must be numpy array.")
        if x.ndim != 1:
            raise ValueError("x must be 1-D array.")
        if x.shape[0] != self._num_qubits:
            raise ValueError("number of qubits and data dimension must be the same.")

        if qr is None:
            qr = QuantumRegister(self._num_qubits, name='q')

        qc = QuantumCircuit(qr)
        for _ in range(self._depth):
            for i in range(self._num_qubits):
                qc.u2(0, pi, qr[i])
            for pauli in self._pauli_strings:
                coeff = self._data_map_func(self._extract_data_for_rotation(pauli, x))
                p = Pauli.from_label(pauli)

                inst = evolution_instruction([[coeff, p]], 1, 1)
                qc.append(inst, qr)
                qc = qc.decompose()
        return qc
Ejemplo n.º 3
0
    def test_group_paulis_2(self):
        """
            Test with normal grouping approach
        """

        num_qubits = 4
        pauli_term = []
        for pauli_label in itertools.product('IXYZ', repeat=num_qubits):
            coeff = np.random.random(1)[0]
            pauli_term.append([coeff, Pauli.from_label(''.join(pauli_label))])
        op = Operator(paulis=pauli_term)
        op.coloring = None
        paulis = copy.deepcopy(op.paulis)
        op.to_grouped_paulis()
        flattened_grouped_paulis = [pauli for group in op.grouped_paulis for pauli in group[1:]]

        for gp in flattened_grouped_paulis:
            passed = False
            for p in paulis:
                if p[1] == gp[1]:
                    passed = p[0] == gp[0]
                    break
            self.assertTrue(passed, "non-existed paulis in grouped_paulis: {}".format(gp[1].to_label()))
    def test_chop_real(self):
        """ chop real test """
        paulis = [
            Pauli.from_label(x)
            for x in ['IXYZ', 'XXZY', 'IIZZ', 'XXYY', 'ZZXX', 'YYYY']
        ]
        coeffs = [0.2, 0.6, 0.8, -0.2, -0.6, -0.8]
        op = WeightedPauliOperator.from_list(paulis, coeffs)
        ori_op = op.copy()

        for threshold, num_paulis in zip([0.4, 0.7, 0.9], [4, 2, 0]):
            op = ori_op.copy()
            op1 = op.chop(threshold=threshold, copy=True)
            self.assertEqual(len(op.paulis), 6,
                             "\n{}".format(op.print_details()))
            self.assertEqual(len(op1.paulis), num_paulis,
                             "\n{}".format(op1.print_details()))

            op1 = op.chop(threshold=threshold, copy=False)
            self.assertEqual(len(op.paulis), num_paulis,
                             "\n{}".format(op.print_details()))
            self.assertEqual(len(op1.paulis), num_paulis,
                             "\n{}".format(op1.print_details()))
Ejemplo n.º 5
0
    def test_sorted_grouping(self):
        """Test with color grouping approach."""
        num_qubits = 2
        paulis = [Pauli.from_label(pauli_label)
                  for pauli_label in itertools.product('IXYZ', repeat=num_qubits)]
        weights = aqua_globals.random.random_sample(len(paulis))
        op = WeightedPauliOperator.from_list(paulis, weights)
        grouped_op = op_converter.to_tpb_grouped_weighted_pauli_operator(
            op, TPBGroupedWeightedPauliOperator.sorted_grouping)

        # check all paulis are still existed.
        for g_p in grouped_op.paulis:
            passed = False
            for pauli in op.paulis:
                if pauli[1] == g_p[1]:
                    passed = pauli[0] == g_p[0]
                    break
            self.assertTrue(passed,
                            "non-existed paulis in grouped_paulis: {}".format(g_p[1].to_label()))

        # check the number of basis of grouped
        # one should be less than and equal to the original one.
        self.assertGreaterEqual(len(op.basis), len(grouped_op.basis))
Ejemplo n.º 6
0
def qubitop_to_qiskitpauli(
        qubit_operator: QubitOperator) -> WeightedPauliOperator:
    """Convert a OpenFermion QubitOperator to a WeightedPauliOperator.

    Args:
        qubit_operator: OpenFermion QubitOperator to convert

    Returns:
        WeightedPauliOperator representing the qubit operator
    """
    if not isinstance(qubit_operator, QubitOperator):
        raise TypeError(
            "qubit_operator must be an OpenFermion QubitOperator object")

    terms = []
    for qubit_terms, coefficient in qubit_operator.terms.items():
        string_term = "I" * count_qubits(qubit_operator)
        for i, (term_qubit, term_pauli) in enumerate(qubit_terms):
            string_term = (string_term[:term_qubit] + term_pauli +
                           string_term[term_qubit + 1:])
        terms.append([coefficient, Pauli.from_label(string_term)])

    return WeightedPauliOperator(terms)
def paul(n_qubits: int, index: int, axis: Union[int, str]):
    """Return a Pauli string with a single non-trivial element.
    Parameters
    ----------
    n_qubits : int
        Number of qubits.
    index : int
        Index of non-trivial term.
    axis : Union[int, str]
        Axis for Pauli string. Either a string, or an int, e.g. `'X'` or `'1'`.
    Returns
    -------
    WeightedPauliOperator($0)
        Resulting Pauli operator.
    """
    label = ['I'] * n_qubits
    pauli_dict = {0: 'I', 1: 'X', 2: 'Y', 3: 'Z'}
    if isinstance(axis, str):
        if not axis in list(pauli_dict.values()):
            raise ValueError('Invalid axis provided')
        label[index] = axis
    elif isinstance(axis, int):
        label[index] = pauli_dict[axis]
    return WeightedPauliOperator(paulis=[[1.0, Pauli.from_label(label)]])
    def test_unsorted_grouping(self):
        """Test with normal grouping approach."""

        num_qubits = 4
        paulis = [
            Pauli.from_label(pauli_label)
            for pauli_label in itertools.product('IXYZ', repeat=num_qubits)
        ]
        weights = aqua_globals.random.random(len(paulis))
        op = WeightedPauliOperator.from_list(paulis, weights)
        grouped_op = op_converter.to_tpb_grouped_weighted_pauli_operator(
            op, TPBGroupedWeightedPauliOperator.unsorted_grouping)

        for g_p in grouped_op.paulis:
            passed = False
            for pauli in op.paulis:
                if pauli[1] == g_p[1]:
                    passed = pauli[0] == g_p[0]
                    break
            self.assertTrue(
                passed, "non-existed paulis in grouped_paulis: {}".format(
                    g_p[1].to_label()))

        self.assertGreaterEqual(len(op.basis), len(grouped_op.basis))
Ejemplo n.º 9
0
    def test_chop_complex(self):
        paulis = [
            Pauli.from_label(x)
            for x in ['IXYZ', 'XXZY', 'IIZZ', 'XXYY', 'ZZXX', 'YYYY']
        ]
        coeffs = [
            0.2 + -0.5j, 0.6 - 0.3j, 0.8 - 0.6j, -0.5 + -0.2j, -0.3 + 0.6j,
            -0.6 + 0.8j
        ]
        op = WeightedPauliOperator.from_list(paulis, coeffs)
        ori_op = op.copy()
        for threshold, num_paulis in zip([0.4, 0.7, 0.9], [6, 2, 0]):
            op = ori_op.copy()
            op1 = op.chop(threshold=threshold, copy=True)
            self.assertEqual(len(op.paulis), 6,
                             "\n{}".format(op.print_details()))
            self.assertEqual(len(op1.paulis), num_paulis,
                             "\n{}".format(op1.print_details()))

            op1 = op.chop(threshold=threshold, copy=False)
            self.assertEqual(len(op.paulis), num_paulis,
                             "\n{}".format(op.print_details()))
            self.assertEqual(len(op1.paulis), num_paulis,
                             "\n{}".format(op1.print_details()))
    def setUp(self):
        super().setUp()
        seed = 0
        aqua_globals.random_seed = seed

        self.num_qubits = 3
        paulis = [
            Pauli.from_label(pauli_label)
            for pauli_label in itertools.product('IXYZ',
                                                 repeat=self.num_qubits)
        ]
        weights = aqua_globals.random.random_sample(len(paulis))
        self.qubit_op = WeightedPauliOperator.from_list(paulis, weights)
        self.var_form = RYRZ(self.qubit_op.num_qubits, 1)

        qasm_simulator = BasicAer.get_backend('qasm_simulator')
        self.quantum_instance_qasm = QuantumInstance(qasm_simulator,
                                                     shots=65536,
                                                     seed_simulator=seed,
                                                     seed_transpiler=seed)
        statevector_simulator = BasicAer.get_backend('statevector_simulator')
        self.quantum_instance_statevector = \
            QuantumInstance(statevector_simulator, shots=1,
                            seed_simulator=seed, seed_transpiler=seed)
Ejemplo n.º 11
0
    def test_chop(self):
        """ chop test """
        paulis = [Pauli.from_label(x) for x in ['IIXX', 'ZZXX', 'ZZZZ', 'XXZZ', 'XXXX', 'IXXX']]
        coeffs = [0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
        op = WeightedPauliOperator.from_list(paulis, coeffs)
        grouped_op = op_converter.to_tpb_grouped_weighted_pauli_operator(
            op, TPBGroupedWeightedPauliOperator.sorted_grouping)

        original_num_basis = len(grouped_op.basis)
        chopped_grouped_op = grouped_op.chop(0.35, copy=True)
        self.assertLessEqual(len(chopped_grouped_op.basis), 3)
        self.assertLessEqual(len(chopped_grouped_op.basis), original_num_basis)
        # ZZXX group is remove
        for b, _ in chopped_grouped_op.basis:
            self.assertFalse(b.to_label() == 'ZZXX')

        chopped_grouped_op = grouped_op.chop(0.55, copy=True)
        self.assertLessEqual(len(chopped_grouped_op.basis), 1)
        self.assertLessEqual(len(chopped_grouped_op.basis), original_num_basis)

        for b, _ in chopped_grouped_op.basis:
            self.assertFalse(b.to_label() == 'ZZXX')
            self.assertFalse(b.to_label() == 'ZZZZ')
            self.assertFalse(b.to_label() == 'XXZZ')
Ejemplo n.º 12
0
def qubitop_to_pauliop(n_qubits, qubit_operator):
    """Convert an openfermion QubitOperator to a qiskit WeightedPauliOperator.
    Args:
        qubit_operator ("QubitOperator"): Openfermion QubitOperator to convert to a qiskit.WeightedPauliOperator.
    Returns:
        paulis ("WeightedPauliOperator"): Qiskit WeightedPauliOperator.
    """
    if not isinstance(qubit_operator, QubitOperator):
        raise TypeError("qubit_operator must be an openFermion QubitOperator object.")
    paulis = []

    for qubit_terms, coefficient in qubit_operator.terms.items():
        count=0
        pauli_label = ['I' for _ in range(n_qubits)]
        coeff = coefficient
        
        for tensor_term in qubit_terms:
            pauli_label[tensor_term[0]] = tensor_term[1]
                    
        paulis.append([coeff, Pauli.from_label(pauli_label)])
    
    pauliOp = WeightedPauliOperator(paulis)
    
    return pauliOp
Ejemplo n.º 13
0
    def test_create_from_paulis_0(self):
        """Test with single paulis."""
        num_qubits = 4
        for pauli_label in itertools.product('IXYZ', repeat=num_qubits):
            coeff = np.random.random(1)[0]
            pauli_term = [coeff, Pauli.from_label(pauli_label)]
            op = Operator(paulis=[pauli_term])

            depth = 1
            var_form = RYRZ(op.num_qubits, depth)
            circuit = var_form.construct_circuit(
                np.array(np.random.randn(var_form.num_parameters)))
            run_config = {'shots': 1}
            backend = Aer.get_backend('statevector_simulator')
            non_matrix_mode = op.eval('paulis',
                                      circuit,
                                      backend,
                                      run_config=run_config)[0]
            matrix_mode = op.eval('matrix',
                                  circuit,
                                  backend,
                                  run_config=run_config)[0]

            self.assertAlmostEqual(matrix_mode, non_matrix_mode, 6)
Ejemplo n.º 14
0
    def calculate_cik(self):
        # ! ----------------------------------
        # ! Check if this needs to be refersed ?
        # ! ----------------------------------

        ham_terms_circ = [
            ug(Pauli.from_label(i).to_operator(),
               label=" (" + i + ")").control(1)
            for i in list(self.ham_pauli.keys())
        ]
        coeff = list(self.ham_pauli.values())
        if self.verbose:

            iterations = tqdm(range(self.num_parameters),
                              desc="Calculating C_ij parameterized circuits\n")
        else:
            iterations = range(self.num_parameters)

        for i in iterations:
            for j in range(len(ham_terms_circ)):
                self.make_cik_circ(ik=[i, j],
                                   h_pauli=ham_terms_circ,
                                   coeff=coeff)
                self.circuit_cik_a_values[i][j] = np.abs(-1j / 2 * coeff[j])
Ejemplo n.º 15
0
    def test_bksf_edge_op_aij(self):
        """Test bksf mapping, edge operator aij"""
        edge_matrix = np.triu(np.ones((4, 4)))
        edge_list = np.array(
            np.nonzero(np.triu(edge_matrix) - np.diag(np.diag(edge_matrix))))
        qterm_a01 = edge_operator_aij(edge_list, 0, 1)
        qterm_a02 = edge_operator_aij(edge_list, 0, 2)
        qterm_a03 = edge_operator_aij(edge_list, 0, 3)
        qterm_a12 = edge_operator_aij(edge_list, 1, 2)
        qterm_a13 = edge_operator_aij(edge_list, 1, 3)
        qterm_a23 = edge_operator_aij(edge_list, 2, 3)

        ref_qterm_a01 = Operator(paulis=[[1.0, Pauli.from_label('IIIIIX')]])
        ref_qterm_a02 = Operator(paulis=[[1.0, Pauli.from_label('IIIIXZ')]])
        ref_qterm_a03 = Operator(paulis=[[1.0, Pauli.from_label('IIIXZZ')]])
        ref_qterm_a12 = Operator(paulis=[[1.0, Pauli.from_label('IIXIZZ')]])
        ref_qterm_a13 = Operator(paulis=[[1.0, Pauli.from_label('IXZZIZ')]])
        ref_qterm_a23 = Operator(paulis=[[1.0, Pauli.from_label('XZZZZI')]])

        self.assertEqual(
            qterm_a01, ref_qterm_a01,
            "\n{} vs \n{}".format(qterm_a01.print_operators(),
                                  ref_qterm_a01.print_operators()))
        self.assertEqual(
            qterm_a02, ref_qterm_a02,
            "\n{} vs \n{}".format(qterm_a02.print_operators(),
                                  ref_qterm_a02.print_operators()))
        self.assertEqual(
            qterm_a03, ref_qterm_a03,
            "\n{} vs \n{}".format(qterm_a03.print_operators(),
                                  ref_qterm_a03.print_operators()))
        self.assertEqual(
            qterm_a12, ref_qterm_a12,
            "\n{} vs \n{}".format(qterm_a12.print_operators(),
                                  ref_qterm_a12.print_operators()))
        self.assertEqual(
            qterm_a13, ref_qterm_a13,
            "\n{} vs \n{}".format(qterm_a13.print_operators(),
                                  ref_qterm_a13.print_operators()))
        self.assertEqual(
            qterm_a23, ref_qterm_a23,
            "\n{} vs \n{}".format(qterm_a23.print_operators(),
                                  ref_qterm_a23.print_operators()))
Ejemplo n.º 16
0
class FermionicOperator(object):
    r"""
    A set of functions to map fermionic Hamiltonians to qubit Hamiltonians.

    References:
    - E. Wigner and P. Jordan., Über das Paulische Äguivalenzverbot, \
        Z. Phys., 47:631 (1928). \
    - S. Bravyi and A. Kitaev. Fermionic quantum computation, \
        Ann. of Phys., 298(1):210–226 (2002). \
    - A. Tranter, S. Sofia, J. Seeley, M. Kaicher, J. McClean, R. Babbush, \
        P. Coveney, F. Mintert, F. Wilhelm, and P. Love. The Bravyi–Kitaev \
        transformation: Properties and applications. Int. Journal of Quantum \
        Chemistry, 115(19):1431–1441 (2015). \
    - S. Bravyi, J. M. Gambetta, A. Mezzacapo, and K. Temme, \
        arXiv e-print arXiv:1701.08213 (2017). \
    - K. Setia, J. D. Whitfield, arXiv:1712.00446 (2017)
    """

    def __init__(self, h1, h2=None, ph_trans_shift=None):
        """Constructor.

        This class requires the integrals stored in the 'chemist' notation
            h2(i,j,k,l) --> adag_i adag_k a_l a_j
        There is another popular notation is the 'physicist' notation
            h2(i,j,k,l) --> adag_i adag_j a_k a_l
        If you are using the 'physicist' notation, you need to convert it to
        the 'chemist' notation first. E.g., h2 = numpy.einsum('ikmj->ijkm', h2)

        Args:
            h1 (numpy.ndarray): second-quantized fermionic one-body operator, a 2-D (NxN) tensor
            h2 (numpy.ndarray): second-quantized fermionic two-body operator,
                                a 4-D (NxNxNxN) tensor
            ph_trans_shift (float): energy shift caused by particle hole transformation
        """
        self._h1 = h1
        if h2 is None:
            h2 = np.zeros((h1.shape[0], h1.shape[0], h1.shape[0], h1.shape[0]), dtype=h1.dtype)
        self._h2 = h2
        self._ph_trans_shift = ph_trans_shift
        self._modes = self._h1.shape[0]
        self._map_type = None

    @property
    def modes(self):
        """Getter of modes."""
        return self._modes

    @property
    def h1(self):
        """Getter of one body integral tensor."""
        return self._h1

    @h1.setter
    def h1(self, new_h1):
        """Setter of one body integral tensor."""
        self._h1 = new_h1

    @property
    def h2(self):
        """Getter of two body integral tensor."""
        return self._h2

    @h2.setter
    def h2(self, new_h2):
        """Setter of two body integral tensor."""
        self._h2 = new_h2

    def __eq__(self, other):
        """Overload == ."""
        ret = np.all(self._h1 == other._h1)
        if not ret:
            return ret
        ret = np.all(self._h2 == other._h2)
        return ret

    def __ne__(self, other):
        """Overload != ."""
        return not self.__eq__(other)

    def transform(self, unitary_matrix):
        """Transform the one and two body term based on unitary_matrix."""
        self._h1_transform(unitary_matrix)
        self._h2_transform(unitary_matrix)

    def _h1_transform(self, unitary_matrix):
        """
        Transform h1 based on unitry matrix, and overwrite original property.

        Args:
            unitary_matrix (numpy.ndarray): A 2-D unitary matrix for h1 transformation.
        """
        self._h1 = unitary_matrix.T.conj().dot(self._h1.dot(unitary_matrix))

    def _h2_transform(self, unitary_matrix):
        """
        Transform h2 to get fermionic hamiltonian, and overwrite original property.

        Args:
            unitary_matrix (numpy.ndarray): A 2-D unitary matrix for h1 transformation.
        """
        num_modes = unitary_matrix.shape[0]
        temp_ret = np.zeros((num_modes, num_modes, num_modes, num_modes),
                            dtype=unitary_matrix.dtype)
        unitary_matrix_dagger = np.conjugate(unitary_matrix)

        # option 3: temp1 is a 3-D tensor, temp2 and temp3 are 2-D tensors
        for a in range(num_modes):
            temp1 = np.einsum('i,i...->...', unitary_matrix_dagger[:, a], self._h2)
            for b in range(num_modes):
                temp2 = np.einsum('j,j...->...', unitary_matrix[:, b], temp1)
                temp3 = np.einsum('kc,k...->...c', unitary_matrix_dagger, temp2)
                temp_ret[a, b, :, :] = np.einsum('ld,l...c->...cd', unitary_matrix, temp3)

        self._h2 = temp_ret

    def _jordan_wigner_mode(self, n):
        """
        Jordan_Wigner mode.

        Each Fermionic Operator is mapped to 2 Pauli Operators, added together with the
        appropriate phase, i.e.:

        a_i^\\dagger = Z^i (X + iY) I^(n-i-1) = (Z^i X I^(n-i-1)) + i (Z^i Y I^(n-i-1))
        a_i = Z^i (X - iY) I^(n-i-1)

        This is implemented by creating an array of tuples, each including two operators.
        The phase between two elements in a tuple is implicitly assumed, and added calculated at the
        appropriate time (see for example _one_body_mapping).

        Args:
            n (int): number of modes
        """
        a = []
        for i in range(n):
            a_z = np.asarray([1] * i + [0] + [0] * (n - i - 1), dtype=np.bool)
            a_x = np.asarray([0] * i + [1] + [0] * (n - i - 1), dtype=np.bool)
            b_z = np.asarray([1] * i + [1] + [0] * (n - i - 1), dtype=np.bool)
            b_x = np.asarray([0] * i + [1] + [0] * (n - i - 1), dtype=np.bool)
            a.append((Pauli(a_z, a_x), Pauli(b_z, b_x)))
        return a

    def _parity_mode(self, n):
        """
        Parity mode.

        Args:
            n (int): number of modes
        """
        a = []
        for i in range(n):
            a_z = [0] * (i - 1) + [1] if i > 0 else []
            a_x = [0] * (i - 1) + [0] if i > 0 else []
            b_z = [0] * (i - 1) + [0] if i > 0 else []
            b_x = [0] * (i - 1) + [0] if i > 0 else []
            a_z = np.asarray(a_z + [0] + [0] * (n - i - 1), dtype=np.bool)
            a_x = np.asarray(a_x + [1] + [1] * (n - i - 1), dtype=np.bool)
            b_z = np.asarray(b_z + [1] + [0] * (n - i - 1), dtype=np.bool)
            b_x = np.asarray(b_x + [1] + [1] * (n - i - 1), dtype=np.bool)
            a.append((Pauli(a_z, a_x), Pauli(b_z, b_x)))
        return a

    def _bravyi_kitaev_mode(self, n):
        """
        Bravyi-Kitaev mode.

        Args:
            n (int): number of modes
        """

        def parity_set(j, n):
            """Computes the parity set of the j-th orbital in n modes.

            Args:
                j (int) : the orbital index
                n (int) : the total number of modes

            Returns:
                numpy.ndarray: Array of mode indexes
            """
            indexes = np.array([])
            if n % 2 != 0:
                return indexes

            if j < n / 2:
                indexes = np.append(indexes, parity_set(j, n / 2))
            else:
                indexes = np.append(indexes, np.append(
                    parity_set(j - n / 2, n / 2) + n / 2, n / 2 - 1))
            return indexes

        def update_set(j, n):
            """Computes the update set of the j-th orbital in n modes.

            Args:
                j (int) : the orbital index
                n (int) : the total number of modes

            Returns:
                numpy.ndarray: Array of mode indexes
            """
            indexes = np.array([])
            if n % 2 != 0:
                return indexes
            if j < n / 2:
                indexes = np.append(indexes, np.append(
                    n - 1, update_set(j, n / 2)))
            else:
                indexes = np.append(indexes, update_set(j - n / 2, n / 2) + n / 2)
            return indexes

        def flip_set(j, n):
            """Computes the flip set of the j-th orbital in n modes.

            Args:
                j (int) : the orbital index
                n (int) : the total number of modes

            Returns:
                numpy.ndarray: Array of mode indexes
            """
            indexes = np.array([])
            if n % 2 != 0:
                return indexes
            if j < n / 2:
                indexes = np.append(indexes, flip_set(j, n / 2))
            elif j >= n / 2 and j < n - 1:
                indexes = np.append(indexes, flip_set(j - n / 2, n / 2) + n / 2)
            else:
                indexes = np.append(np.append(indexes, flip_set(
                    j - n / 2, n / 2) + n / 2), n / 2 - 1)
            return indexes

        a = []
        # FIND BINARY SUPERSET SIZE
        bin_sup = 1
        while n > np.power(2, bin_sup):
            bin_sup += 1
        # DEFINE INDEX SETS FOR EVERY FERMIONIC MODE
        update_sets = []
        update_pauli = []

        parity_sets = []
        parity_pauli = []

        flip_sets = []

        remainder_sets = []
        remainder_pauli = []
        for j in range(n):

            update_sets.append(update_set(j, np.power(2, bin_sup)))
            update_sets[j] = update_sets[j][update_sets[j] < n]

            parity_sets.append(parity_set(j, np.power(2, bin_sup)))
            parity_sets[j] = parity_sets[j][parity_sets[j] < n]

            flip_sets.append(flip_set(j, np.power(2, bin_sup)))
            flip_sets[j] = flip_sets[j][flip_sets[j] < n]

            remainder_sets.append(np.setdiff1d(parity_sets[j], flip_sets[j]))

            update_pauli.append(Pauli(np.zeros(n, dtype=np.bool), np.zeros(n, dtype=np.bool)))
            parity_pauli.append(Pauli(np.zeros(n, dtype=np.bool), np.zeros(n, dtype=np.bool)))
            remainder_pauli.append(Pauli(np.zeros(n, dtype=np.bool), np.zeros(n, dtype=np.bool)))
            for k in range(n):
                if np.in1d(k, update_sets[j]):
                    update_pauli[j].update_x(True, k)
                if np.in1d(k, parity_sets[j]):
                    parity_pauli[j].update_z(True, k)
                if np.in1d(k, remainder_sets[j]):
                    remainder_pauli[j].update_z(True, k)

            x_j = Pauli(np.zeros(n, dtype=np.bool), np.zeros(n, dtype=np.bool))
            x_j.update_x(True, j)
            y_j = Pauli(np.zeros(n, dtype=np.bool), np.zeros(n, dtype=np.bool))
            y_j.update_z(True, j)
            y_j.update_x(True, j)
            a.append((update_pauli[j] * x_j * parity_pauli[j],
                      update_pauli[j] * y_j * remainder_pauli[j]))
        return a

    def mapping(self, map_type, threshold=0.00000001):
        """Map fermionic operator to qubit operator.

        Using multiprocess to speedup the mapping, the improvement can be
        observed when h2 is a non-sparse matrix.

        Args:
            map_type (str): case-insensitive mapping type.
                            "jordan_wigner", "parity", "bravyi_kitaev", "bksf"
            threshold (float): threshold for Pauli simplification

        Returns:
            WeightedPauliOperator: create an Operator object in Paulis form.

        Raises:
            QiskitChemistryError: if the `map_type` can not be recognized.
        """
        """
        ####################################################################
        ############   DEFINING MAPPED FERMIONIC OPERATORS    ##############
        ####################################################################
        """

        self._map_type = map_type
        n = self._modes  # number of fermionic modes / qubits
        map_type = map_type.lower()
        if map_type == 'jordan_wigner':
            a = self._jordan_wigner_mode(n)
        elif map_type == 'parity':
            a = self._parity_mode(n)
        elif map_type == 'bravyi_kitaev':
            a = self._bravyi_kitaev_mode(n)
        elif map_type == 'bksf':
            return bksf_mapping(self)
        else:
            raise QiskitChemistryError('Please specify the supported modes: '
                                       'jordan_wigner, parity, bravyi_kitaev, bksf')
        """
        ####################################################################
        ############    BUILDING THE MAPPED HAMILTONIAN     ################
        ####################################################################
        """
        pauli_list = WeightedPauliOperator(paulis=[])
        if logger.isEnabledFor(logging.DEBUG):
            logger.debug("Mapping one-body terms to Qubit Hamiltonian:")
            TextProgressBar(output_handler=sys.stderr)
        results = parallel_map(FermionicOperator._one_body_mapping,
                               [(self._h1[i, j], a[i], a[j])
                                for i, j in itertools.product(range(n), repeat=2) if self._h1[i, j] != 0],
                               task_args=(threshold,), num_processes=aqua_globals.num_processes)
        for result in results:
            pauli_list += result
        pauli_list.chop(threshold=threshold)

        if logger.isEnabledFor(logging.DEBUG):
            logger.debug("Mapping two-body terms to Qubit Hamiltonian:")
            TextProgressBar(output_handler=sys.stderr)
        results = parallel_map(FermionicOperator._two_body_mapping,
                               [(self._h2[i, j, k, m], a[i], a[j], a[k], a[m])
                                for i, j, k, m in itertools.product(range(n), repeat=4) if self._h2[i, j, k, m] != 0],
                               task_args=(threshold,), num_processes=aqua_globals.num_processes)
        for result in results:
            pauli_list += result
        pauli_list.chop(threshold=threshold)

        if self._ph_trans_shift is not None:
            pauli_term = [self._ph_trans_shift, Pauli.from_label('I' * self._modes)]
            pauli_list += WeightedPauliOperator(paulis=[pauli_term])

        return pauli_list

    @staticmethod
    def _one_body_mapping(h1_ij_aij, threshold):
        """
        Subroutine for one body mapping.

        Args:
            h1_ij_aij (tuple): value of h1 at index (i,j), pauli at index i, pauli at index j
            threshold: (float): threshold to remove a pauli

        Returns:
            WeightedPauliOperator: Operator for those paulis
        """
        h1_ij, a_i, a_j = h1_ij_aij
        pauli_list = []
        for alpha in range(2):
            for beta in range(2):
                pauli_prod = Pauli.sgn_prod(a_i[alpha], a_j[beta])
                coeff = h1_ij / 4 * pauli_prod[1] * np.power(-1j, alpha) * np.power(1j, beta)
                pauli_term = [coeff, pauli_prod[0]]
                if np.absolute(pauli_term[0]) > threshold:
                    pauli_list.append(pauli_term)
        return WeightedPauliOperator(paulis=pauli_list)

    @staticmethod
    def _two_body_mapping(h2_ijkm_a_ijkm, threshold):
        """
        Subroutine for two body mapping. We use the chemists notation
        for the two-body term, h2(i,j,k,m) adag_i adag_k a_m a_j.

        Args:
            h2_ijkm_aijkm (tuple): value of h2 at index (i,j,k,m),
                                   pauli at index i, pauli at index j,
                                   pauli at index k, pauli at index m
            threshold: (float): threshold to remove a pauli

        Returns:
            WeightedPauliOperator: Operator for those paulis
        """
        h2_ijkm, a_i, a_j, a_k, a_m = h2_ijkm_a_ijkm
        pauli_list = []
        for alpha in range(2):
            for beta in range(2):
                for gamma in range(2):
                    for delta in range(2):
                        pauli_prod_1 = Pauli.sgn_prod(a_i[alpha], a_k[beta])
                        pauli_prod_2 = Pauli.sgn_prod(pauli_prod_1[0], a_m[gamma])
                        pauli_prod_3 = Pauli.sgn_prod(pauli_prod_2[0], a_j[delta])

                        phase1 = pauli_prod_1[1] * pauli_prod_2[1] * pauli_prod_3[1]
                        phase2 = np.power(-1j, alpha + beta) * np.power(1j, gamma + delta)
                        pauli_term = [h2_ijkm / 16 * phase1 * phase2, pauli_prod_3[0]]
                        if np.absolute(pauli_term[0]) > threshold:
                            pauli_list.append(pauli_term)
        return WeightedPauliOperator(paulis=pauli_list)

    @staticmethod
    def _n_body_mapping(h_a, threshold):        
        h = h_a[0]
        a = []
        for i in range(0,len(h_a[1:]),2):
            a.append(h_a[1+i])
        for i in range(1,len(h_a[1:]),2)[::-1]:
            a.append(h_a[1+i])        
        n = int(len(a)/2)        
        a_lst = []        
        for i in range(n):
            a_lst.append(WeightedPauliOperator([[1,a[i][0]]])+WeightedPauliOperator([[-1j,a[i][1]]]))        
        for i in range(n):
            a_lst.append(WeightedPauliOperator([[1, a[n+i][0]]])+WeightedPauliOperator([[1j, a[n+i][1]]]))        
        product = a_lst[0]        
        for element in a_lst[1:]:
            product = product*element        
        product = (h/(2**(n*2))) * product        
        
        return product

    def mapping_new(self, map_type, threshold=0.00000001):
        """Map fermionic operator to qubit operator.        Using multiprocess to speedup the mapping, the improvement can be
        observed when h2 is a non-sparse matrix.        Args:
            map_type (str): case-insensitive mapping type.
                            "jordan_wigner", "parity", "bravyi_kitaev", "bksf"
            threshold (float): threshold for Pauli simplification        Returns:
            WeightedPauliOperator: create an Operator object in Paulis form.        Raises:
            QiskitChemistryError: if the `map_type` can not be recognized.
        """        # ###################################################################
        # ###########   DEFINING MAPPED FERMIONIC OPERATORS    ##############
        # ###################################################################        self._map_type = map_type
        n = self._modes  # number of fermionic modes / qubits
        map_type = map_type.lower()
        if map_type == 'jordan_wigner':
            a_list = self._jordan_wigner_mode(n)
        elif map_type == 'parity':
            a_list = self._parity_mode(n)
        elif map_type == 'bravyi_kitaev':
            a_list = self._bravyi_kitaev_mode(n)
        elif map_type == 'bksf':
            return bksf_mapping(self)
        else:
            raise QiskitChemistryError('Please specify the supported modes: '
                                       'jordan_wigner, parity, bravyi_kitaev, bksf')        # ###################################################################
        # ###########    BUILDING THE MAPPED HAMILTONIAN     ################
        # ###################################################################        pauli_list = WeightedPauliOperator(paulis=[])
        if logger.isEnabledFor(logging.DEBUG):
            logger.debug("Mapping one-body terms to Qubit Hamiltonian:")
            TextProgressBar(output_handler=sys.stderr)
        results = parallel_map(FermionicOperator._n_body_mapping,
                               [(self._h1[i, j], a_list[i], a_list[j])
                                for i, j in itertools.product(range(n), repeat=2)
                                if self._h1[i, j] != 0],
                               task_args=(threshold,), num_processes=aqua_globals.num_processes)
        for result in results:
            pauli_list += result
        pauli_list.chop(threshold=threshold)        if logger.isEnabledFor(logging.DEBUG):
            logger.debug("Mapping two-body terms to Qubit Hamiltonian:")
            TextProgressBar(output_handler=sys.stderr)
        results = parallel_map(FermionicOperator._n_body_mapping,
                               [(self._h2[i, j, k, m], a_list[i], a_list[j], a_list[k], a_list[m])
                                for i, j, k, m in itertools.product(range(n), repeat=4)
                                if self._h2[i, j, k, m] != 0],
                               task_args=(threshold,), num_processes=aqua_globals.num_processes)
        for result in results:
            pauli_list += result
        pauli_list.chop(threshold=threshold)        if self._ph_trans_shift is not None:
            pauli_term = [self._ph_trans_shift, Pauli.from_label('I' * self._modes)]
            pauli_list += WeightedPauliOperator(paulis=[pauli_term])        return pauli_list
Ejemplo n.º 17
0
def _conversion(basis, matrix):
    pauli = Pauli.from_label(''.join(basis))
    trace_value = np.sum(matrix.dot(pauli.to_spmatrix()).diagonal())
    return trace_value, pauli
Ejemplo n.º 18
0
def find_symmetry_ops(r_matrices):
    """

    Args:
        r_matrices (list[numpy.ndarray]): a list of rotation matrices.

    Returns:
        numpy.ndarray: the V matrix
        list[Operator]: symmetry paulis
        list[Operator]: cliffords, composed of symmetries and single-qubit op
        list[int]: position of the single-qubit operators that anticommute
            with the cliffords

    """
    modes = r_matrices[0].shape[0]

    g_matrices = []
    for r_matrix in r_matrices:
        g_matrix = -1j * scila.logm(r_matrix)
        g_matrices.append(g_matrix)

    sim_dia = []
    for g_matrix in g_matrices:
        sim_dia.append(qt.Qobj(g_matrix))

    d_v = qt.simdiag(sim_dia)

    d_matrices = d_v[0]
    v_matrix = np.hstack([d_v[1][i].data.toarray() for i in range(modes)])

    # check the build d_matrix
    for eig in d_matrices.flatten():
        print(eig)
        if not (np.isclose(eig, 0.0) or np.isclose(eig, np.pi)):
            # print(np.where(d_matrices.flatten()==eig))
            raise ValueError('The specified R matrix is invalid. \
                                        Eigenvalues of G includes: {}'.format(
                eig))
    single_qubit_list = []
    cliffords = []
    pauli_symmetries = []
    existed_pi_locs = []
    # pdb.set_trace()
    for d_idx in range(len(d_matrices)):
        pi_index = np.where(np.isclose(d_matrices[d_idx], np.pi))[0]
        single_qubit_pauli = ['I'] * modes
        pi_loc = 0
        for i in pi_index:
            if i not in existed_pi_locs:
                pi_loc = i
                existed_pi_locs.extend(pi_index.tolist())
                break
        single_qubit_pauli[pi_loc] = 'X'
        single_qubit_pauli = ''.join(single_qubit_pauli)
        single_qubit_op = Operator(
            paulis=[[1.0, Pauli.from_label(single_qubit_pauli[::-1])]])
        single_qubit_list.append(pi_loc)
        symmetries_pauli_label = ''
        for i in range(modes):
            symmetries_pauli_label += 'I' if i not in pi_index else 'Z'
        sym_pauli = Pauli.from_label(symmetries_pauli_label[::-1])
        pauli_symmetries.append(sym_pauli)
        symmetries_op = Operator(paulis=[[1.0, sym_pauli]])
        clifford_op = single_qubit_op + symmetries_op
        clifford_op.scaling_coeff(1.0 / np.sqrt(2))
        cliffords.append(clifford_op)

    return v_matrix, pauli_symmetries, cliffords, single_qubit_list
Ejemplo n.º 19
0
    def mapping(self, map_type, threshold=0.00000001):
        """Map fermionic operator to qubit operator.

        Using multiprocess to speedup the mapping, the improvement can be
        observed when h2 is a non-sparse matrix.

        Args:
            map_type (str): case-insensitive mapping type.
                            "jordan_wigner", "parity", "bravyi_kitaev", "bksf"
            threshold (float): threshold for Pauli simplification

        Returns:
            WeightedPauliOperator: create an Operator object in Paulis form.

        Raises:
            QiskitChemistryError: if the `map_type` can not be recognized.
        """
        """
        ####################################################################
        ############   DEFINING MAPPED FERMIONIC OPERATORS    ##############
        ####################################################################
        """

        self._map_type = map_type
        n = self._modes  # number of fermionic modes / qubits
        map_type = map_type.lower()
        if map_type == 'jordan_wigner':
            a = self._jordan_wigner_mode(n)
        elif map_type == 'parity':
            a = self._parity_mode(n)
        elif map_type == 'bravyi_kitaev':
            a = self._bravyi_kitaev_mode(n)
        elif map_type == 'bksf':
            return bksf_mapping(self)
        else:
            raise QiskitChemistryError('Please specify the supported modes: '
                                       'jordan_wigner, parity, bravyi_kitaev, bksf')
        """
        ####################################################################
        ############    BUILDING THE MAPPED HAMILTONIAN     ################
        ####################################################################
        """
        pauli_list = WeightedPauliOperator(paulis=[])
        if logger.isEnabledFor(logging.DEBUG):
            logger.debug("Mapping one-body terms to Qubit Hamiltonian:")
            TextProgressBar(output_handler=sys.stderr)
        results = parallel_map(FermionicOperator._one_body_mapping,
                               [(self._h1[i, j], a[i], a[j])
                                for i, j in itertools.product(range(n), repeat=2) if self._h1[i, j] != 0],
                               task_args=(threshold,), num_processes=aqua_globals.num_processes)
        for result in results:
            pauli_list += result
        pauli_list.chop(threshold=threshold)

        if logger.isEnabledFor(logging.DEBUG):
            logger.debug("Mapping two-body terms to Qubit Hamiltonian:")
            TextProgressBar(output_handler=sys.stderr)
        results = parallel_map(FermionicOperator._two_body_mapping,
                               [(self._h2[i, j, k, m], a[i], a[j], a[k], a[m])
                                for i, j, k, m in itertools.product(range(n), repeat=4) if self._h2[i, j, k, m] != 0],
                               task_args=(threshold,), num_processes=aqua_globals.num_processes)
        for result in results:
            pauli_list += result
        pauli_list.chop(threshold=threshold)

        if self._ph_trans_shift is not None:
            pauli_term = [self._ph_trans_shift, Pauli.from_label('I' * self._modes)]
            pauli_list += WeightedPauliOperator(paulis=[pauli_term])

        return pauli_list
    def test_evaluate_single_pauli_statevector(self):
        """ evaluate single pauli statevector test """
        # X
        op = WeightedPauliOperator.from_list([Pauli.from_label('X')])
        qr = QuantumRegister(1, name='q')
        wave_function = QuantumCircuit(qr)
        # + 1 eigenstate
        wave_function.h(qr[0])
        circuits = op.construct_evaluation_circuit(wave_function=wave_function,
                                                   statevector_mode=True)
        result = self.quantum_instance_statevector.execute(circuits)
        actual_value = op.evaluate_with_result(result=result,
                                               statevector_mode=True)
        self.assertAlmostEqual(1.0, actual_value[0].real, places=5)
        # - 1 eigenstate
        wave_function = QuantumCircuit(qr)
        wave_function.x(qr[0])
        wave_function.h(qr[0])
        circuits = op.construct_evaluation_circuit(wave_function=wave_function,
                                                   statevector_mode=True)
        result = self.quantum_instance_statevector.execute(circuits)
        actual_value = op.evaluate_with_result(result=result,
                                               statevector_mode=True)
        self.assertAlmostEqual(-1.0, actual_value[0].real, places=5)

        # Y
        op = WeightedPauliOperator.from_list([Pauli.from_label('Y')])
        qr = QuantumRegister(1, name='q')
        wave_function = QuantumCircuit(qr)
        # + 1 eigenstate
        wave_function.h(qr[0])
        wave_function.s(qr[0])
        circuits = op.construct_evaluation_circuit(wave_function=wave_function,
                                                   statevector_mode=True)
        result = self.quantum_instance_statevector.execute(circuits)
        actual_value = op.evaluate_with_result(result=result,
                                               statevector_mode=True)
        self.assertAlmostEqual(1.0, actual_value[0].real, places=5)
        # - 1 eigenstate
        wave_function = QuantumCircuit(qr)
        wave_function.x(qr[0])
        wave_function.h(qr[0])
        wave_function.s(qr[0])
        circuits = op.construct_evaluation_circuit(wave_function=wave_function,
                                                   statevector_mode=True)
        result = self.quantum_instance_statevector.execute(circuits)
        actual_value = op.evaluate_with_result(result=result,
                                               statevector_mode=True)
        self.assertAlmostEqual(-1.0, actual_value[0].real, places=5)

        # Z
        op = WeightedPauliOperator.from_list([Pauli.from_label('Z')])
        qr = QuantumRegister(1, name='q')
        wave_function = QuantumCircuit(qr)
        # + 1 eigenstate
        circuits = op.construct_evaluation_circuit(wave_function=wave_function,
                                                   statevector_mode=True)
        result = self.quantum_instance_statevector.execute(circuits)
        actual_value = op.evaluate_with_result(result=result,
                                               statevector_mode=True)
        self.assertAlmostEqual(1.0, actual_value[0].real, places=5)
        # - 1 eigenstate
        wave_function = QuantumCircuit(qr)
        wave_function.x(qr[0])
        circuits = op.construct_evaluation_circuit(wave_function=wave_function,
                                                   statevector_mode=True)
        result = self.quantum_instance_statevector.execute(circuits)
        actual_value = op.evaluate_with_result(result=result,
                                               statevector_mode=True)
        self.assertAlmostEqual(-1.0, actual_value[0].real, places=5)
Ejemplo n.º 21
0
def convert_to_wpauli_list(term, args):
		if term[0] == complex(0):
			separated_ham = 0*WeightedPauliOperator.from_list(paulis = [Pauli.from_label('I'*num_qubits)])
		else:
			separated_ham = WeightedPauliOperator.from_list([term[1]],[term[0]])
Ejemplo n.º 22
0
    def __init__(self,
                 operator,
                 optimizer,
                 var_form=None,
                 max_evals_grouped=1,
                 aux_operators=None,
                 callback=None,
                 auto_conversion=True,
                 initial_point=None,
                 ham_list=None,
                 operator_list=None,
                 nonzero_terms=None,
                 starting_point=False,
                 expecs=None,
                 expec_mode=False,
                 dir_to_bracket=False,
                 ham_term_list=None,
                 ham_energy_list=None,
                 base_3_list=None,
                 param_list=None):

        super().__init__(operator=operator,
                         var_form=var_form,
                         optimizer=optimizer,
                         initial_point=initial_point,
                         max_evals_grouped=max_evals_grouped,
                         aux_operators=aux_operators,
                         callback=callback,
                         auto_conversion=auto_conversion)
        self.num_qubits = operator.num_qubits
        if expecs == None and expec_mode == True:
            expecs = pd.read_csv(
                '{}_qubit_pauli_values.csv'.format(self.num_qubits)
            )  #this file is required unless you pass in the expecation values (in order) manually
            expecs = expecs.to_dict()
        if expec_mode == True:
            self.expecs = expecs
        else:
            self.expecs = []
        if operator_list is not None:
            self.op_list = operator_list
        else:
            self.op_list = var_form.operator_pool.pool
        if initial_point is not None:
            self.param_list = initial_point
        elif param_list is not None:
            self.param_list = param_list
        else:
            self.param_list = [0] * len(self.op_list)
        self.starting_point = starting_point
        if starting_point:
            self.ham_list = ham_list
            self.nonzero_terms = nonzero_terms
        self.zero_term = 0 * WeightedPauliOperator.from_list(
            paulis=[Pauli.from_label('I' * self.num_qubits)])
        self.empt_term = self.zero_term - self.zero_term
        self.dir_to_bracket = dir_to_bracket
        self.ham_term_list = ham_term_list
        self.ham_energy_list = ham_energy_list
        self.base_3_list = base_3_list
        self.constants = []
Ejemplo n.º 23
0
# Immutable convenience objects


def make_immutable(obj):
    """ Delete the __setattr__ property to make the object mostly immutable. """

    # TODO figure out how to get correct error message
    # def throw_immutability_exception(self, *args):
    #     raise AquaError('Operator convenience globals are immutable.')

    obj.__setattr__ = None
    return obj


# 1-Qubit Paulis
X = make_immutable(PrimitiveOp(Pauli.from_label('X')))
Y = make_immutable(PrimitiveOp(Pauli.from_label('Y')))
Z = make_immutable(PrimitiveOp(Pauli.from_label('Z')))
I = make_immutable(PrimitiveOp(Pauli.from_label('I')))

# Clifford+T, and some other common non-parameterized gates
CX = make_immutable(PrimitiveOp(CXGate()))
S = make_immutable(PrimitiveOp(SGate()))
H = make_immutable(PrimitiveOp(HGate()))
T = make_immutable(PrimitiveOp(TGate()))
Swap = make_immutable(PrimitiveOp(SwapGate()))
CZ = make_immutable(PrimitiveOp(CZGate()))

# 1-Qubit Paulis
Zero = make_immutable(StateFn('0'))
One = make_immutable(StateFn('1'))
Ejemplo n.º 24
0
    def mapping(self, map_type, threshold=0.00000001, num_workers=4):
        """Map fermionic operator to qubit operator.

        Using multiprocess to speedup the mapping, the improvement can be
        observed when h2 is a non-sparse matrix.

        Args:
            map_type (str): case-insensitive mapping type.
                            "jordan_wigner", "parity", "bravyi_kitaev", "bksf"
            threshold (float): threshold for Pauli simplification
            num_workers (int): number of processes used to map.

        Returns:
            Operator: create an Operator object in Paulis form.

        Raises:
            QiskitChemistryError: if the `map_type` can not be recognized.
        """
        """
        ####################################################################
        ############   DEFINING MAPPED FERMIONIC OPERATORS    ##############
        ####################################################################
        """
        self._map_type = map_type
        n = self._modes  # number of fermionic modes / qubits
        map_type = map_type.lower()
        if map_type == 'jordan_wigner':
            a = self._jordan_wigner_mode(n)
        elif map_type == 'parity':
            a = self._parity_mode(n)
        elif map_type == 'bravyi_kitaev':
            a = self._bravyi_kitaev_mode(n)
        elif map_type == 'bksf':
            return bksf_mapping(self)
        else:
            raise QiskitChemistryError(
                'Please specify the supported modes: '
                'jordan_wigner, parity, bravyi_kitaev, bksf')
        """
        ####################################################################
        ############    BUILDING THE MAPPED HAMILTONIAN     ################
        ####################################################################
        """
        max_workers = min(num_workers, multiprocessing.cpu_count())
        pauli_list = Operator(paulis=[])
        with concurrent.futures.ProcessPoolExecutor(
                max_workers=max_workers) as executor:
            # One-body
            futures = [
                executor.submit(FermionicOperator._one_body_mapping,
                                self._h1[i, j], a[i], a[j], threshold)
                for i, j in itertools.product(range(n), repeat=2)
                if self._h1[i, j] != 0
            ]

            for future in futures:
                result = future.result()
                pauli_list += result
            pauli_list.chop(threshold=threshold)

            # Two-body
            futures = [
                executor.submit(FermionicOperator._two_body_mapping,
                                self._h2[i, j, k,
                                         m], a[i], a[j], a[k], a[m], threshold)
                for i, j, k, m in itertools.product(range(n), repeat=4)
                if self._h2[i, j, k, m] != 0
            ]
            for future in futures:
                result = future.result()
                pauli_list += result
            pauli_list.chop(threshold=threshold)

        if self._ph_trans_shift is not None:
            pauli_term = [
                self._ph_trans_shift,
                Pauli.from_label('I' * self._modes)
            ]
            pauli_list += Operator(paulis=[pauli_term])

        return pauli_list
Ejemplo n.º 25
0
    '9': [],
    '10': []
}

for i in range(0, 1):
    k = 0
    runtime_sum = 0
    exact_time_sum = 0
    vqeruntime_sum = 0
    num_qubits = 4
    print('num_qubits', num_qubits)
    while k < runs:
        initial_state = Zero(num_qubits)
        op_list = []
        wop = 0 * WeightedPauliOperator.from_list(
            paulis=[Pauli.from_label('I' * num_qubits)], weights=[1.0])
        #mat = np.random.uniform(0, 1, size=(2**num_qubits, 2**num_qubits)) + 1j * np.random.uniform(0, 1, size=(2**num_qubits, 2**num_qubits))
        #mat = np.conjugate(np.transpose(mat)) + mat

        #ham = to_weighted_pauli_operator(MatrixOperator(mat)) #creates random hamiltonian from random matrix "mat"
        #ham = get_h_4_hamiltonian(0.5, 2, "jw")
        ham = retrieve_ham(k)
        op_list = retrieve_op_list(k, rev=True)
        #op_list = [WeightedPauliOperator.from_list([Pauli.from_label('YYZZ')],[1.0]),
        # WeightedPauliOperator.from_list([Pauli.from_label('XXXY')], [1.0]),
        # WeightedPauliOperator.from_list([Pauli.from_label('IIYZ')], [1.0])]
        print(ham.print_details())
        #ham = Gen_rand_rand_ham(k+1, num_qubits)
        qubitOp = ham
        num_qubits = qubitOp.num_qubits
        print('iteration: ', k + 1)
exact_dict = {'2': [], '3': [], '4': [], '5': [], '6': [], '7': [], '8': [], '9': [], '10': []}
num_qubits = 4
#test = random_diagonal_hermitian(2)
#print(test.print_details())
#mat = to_matrix_operator(test)
#print(mat.print_details())
for i in range(0,1):
    k = 0
    runtime_sum = 0
    exact_time_sum = 0
    vqeruntime_sum = 0
    print('num_qubits', num_qubits)
    while k < runs:
        initial_state = Zero(num_qubits)
        op_list = []
        wop = 0*WeightedPauliOperator.from_list(paulis=[Pauli.from_label('I'*num_qubits)], weights=[1.0])
        #mat = np.random.uniform(0, 1, size=(2**num_qubits, 2**num_qubits)) + 1j * np.random.uniform(0, 1, size=(2**num_qubits, 2**num_qubits))
        #mat = np.conjugate(np.transpose(mat)) + mat
        
        #ham = to_weighted_pauli_operator(MatrixOperator(mat)) #creates random hamiltonian from random matrix "mat"
        ham = get_h_4_hamiltonian(0.25, 2, "jw")
        #ham = retrieve_ham(0, num_qubits = num_qubits)
        print('old_ham', ham.print_details())
        #ham = get_h_4_hamiltonian(0.5,2,'jw')
        #op_list = retrieve_op_list(0, rev = True, num_qubits = num_qubits)
        #for op in op_list:
        #    print(op.print_details())
        op_list = [WeightedPauliOperator.from_list([Pauli.from_label('IIXX')]), WeightedPauliOperator.from_list([Pauli.from_label('XXXY')])]
        #op_list = [WeightedPauliOperator.from_list([Pauli.from_label('YYZZ')],[1.0]),
        # WeightedPauliOperator.from_list([Pauli.from_label('XXXY')], [1.0]),
        # WeightedPauliOperator.from_list([Pauli.from_label('IIYZ')], [1.0])]