Esempio n. 1
0
    def test_eoh(self):
        """ EOH test """
        size = 2
        aqua_globals.random_seed = 0

        temp = aqua_globals.random.random_sample((2**size, 2**size))
        h_1 = temp + temp.T
        qubit_op = MatrixOperator(matrix=h_1)

        temp = aqua_globals.random.random_sample((2**size, 2**size))
        h_1 = temp + temp.T
        evo_op = MatrixOperator(matrix=h_1)

        state_in = Custom(size, state='random')

        evo_time = 1
        num_time_slices = 100

        eoh = EOH(qubit_op,
                  state_in,
                  evo_op,
                  evo_time=evo_time,
                  num_time_slices=num_time_slices)

        backend = BasicAer.get_backend('statevector_simulator')
        quantum_instance = QuantumInstance(backend, shots=1)
        # self.log.debug('state_out:\n\n')

        ret = eoh.run(quantum_instance)
        self.log.debug('Evaluation result: %s', ret)
Esempio n. 2
0
    def test_eoh(self):
        SIZE = 2

        temp = np.random.random((2**SIZE, 2**SIZE))
        h1 = temp + temp.T
        qubit_op = MatrixOperator(matrix=h1)

        temp = np.random.random((2**SIZE, 2**SIZE))
        h1 = temp + temp.T
        evo_op = MatrixOperator(matrix=h1)

        state_in = Custom(SIZE, state='random')

        evo_time = 1
        num_time_slices = 100

        eoh = EOH(qubit_op,
                  state_in,
                  evo_op,
                  evo_time=evo_time,
                  num_time_slices=num_time_slices)

        backend = BasicAer.get_backend('statevector_simulator')
        quantum_instance = QuantumInstance(backend, shots=1)
        # self.log.debug('state_out:\n\n')

        ret = eoh.run(quantum_instance)
        self.log.debug('Evaluation result: {}'.format(ret))
    def test_eoh(self, mode):
        """ EOH test """
        size = 2
        aqua_globals.random_seed = 0

        temp = aqua_globals.random.random((2 ** size, 2 ** size))
        h_1 = temp + temp.T
        qubit_op = MatrixOperator(matrix=h_1)

        temp = aqua_globals.random.random((2 ** size, 2 ** size))
        h_1 = temp + temp.T
        evo_op = MatrixOperator(matrix=h_1)

        if mode == 'initial_state':
            with warnings.catch_warnings():
                warnings.filterwarnings('ignore', category=DeprecationWarning)
                state_in = Custom(size, state='random')
        else:
            random_state = aqua_globals.random.random(2 ** size)
            random_state = random_state / np.linalg.norm(random_state)
            state_in = QuantumCircuit(size)
            state_in.initialize(random_state, range(size))

        evo_time = 1
        num_time_slices = 100

        eoh = EOH(qubit_op, state_in, evo_op, evo_time=evo_time, num_time_slices=num_time_slices)

        backend = BasicAer.get_backend('statevector_simulator')
        quantum_instance = QuantumInstance(backend, shots=1)
        # self.log.debug('state_out:\n\n')

        ret = eoh.run(quantum_instance)
        self.log.debug('Evaluation result: %s', ret)
Esempio n. 4
0
    def setUp(self):
        super().setUp()
        seed = 0
        aqua_globals.random_seed = seed

        self.num_qubits = 3
        m_size = np.power(2, self.num_qubits)
        matrix = aqua_globals.random.rand(m_size, m_size)
        self.qubit_op = MatrixOperator(matrix=matrix)
Esempio n. 5
0
 def setUp(self):
     super().setUp()
     qubit_op_simple = MatrixOperator(matrix=TestIQPE.H1)
     qubit_op_simple = op_converter.to_weighted_pauli_operator(qubit_op_simple)
     qubit_op_h2_with_2_qubit_reduction = WeightedPauliOperator.from_dict(TestIQPE.PAULI_DICT)
     qubit_op_zz = WeightedPauliOperator.from_dict(TestIQPE.PAULI_DICT_ZZ)
     self._dict = {
         'QUBIT_OP_SIMPLE': qubit_op_simple.to_opflow(),
         'QUBIT_OP_ZZ': qubit_op_zz.to_opflow(),
         'QUBIT_OP_H2_WITH_2_QUBIT_REDUCTION': qubit_op_h2_with_2_qubit_reduction.to_opflow()
     }
Esempio n. 6
0
    def test_ee(self):
        """ EE test """
        dummy_operator = MatrixOperator([[1]])
        ee = NumPyMinimumEigensolver()
        output = ee.compute_minimum_eigenvalue(self.qubit_op)

        self.assertAlmostEqual(output.eigenvalue, -1.85727503)
Esempio n. 7
0
    def test_vqe_reuse(self):
        """ Test vqe reuse """
        vqe = VQE()
        with self.assertRaises(AquaError):
            _ = vqe.run()

        num_qubits = self.qubit_op.num_qubits
        var_form = RY(num_qubits, depth=3)
        vqe.var_form = var_form
        with self.assertRaises(AquaError):
            _ = vqe.run()

        vqe.operator = self.qubit_op
        with self.assertRaises(AquaError):
            _ = vqe.run()

        qinst = QuantumInstance(BasicAer.get_backend('statevector_simulator'))
        vqe.quantum_instance = qinst
        result = vqe.run()
        self.assertAlmostEqual(result.eigenvalue.real, -1.85727503, places=5)

        operator = MatrixOperator(np.array([[1, 0, 0, 0],
                                            [0, -1, 0, 0],
                                            [0, 0, 2, 0],
                                            [0, 0, 0, 3]]))
        vqe.operator = operator
        result = vqe.run()
        self.assertAlmostEqual(result.eigenvalue.real, -1.0, places=5)
Esempio n. 8
0
 def run_qpe_algo(self,
                  num_ancillae: int = 1,
                  backend: BaseBackend = None,
                  print_eig: bool = False,
                  shots: int = 1024) -> dict:
     """ Runs the QPE algorithm directly.
     
     Args:
         num_ancillae (int, optional): ancillary qubit number, the higher the more accurate, but use more computing resources. Defaults to 1.
         backend (BaseBackend, optional): Choose the backend to run this algorithm. Defaults to None.
         print_eig (bool, optional): whether or not print the eigenvalue. Defaults to False.
         shots (int, optional): Indicate how many shots to take. Defaults to 1024.
     
     Returns:
         dict: returns the results dictionary of the QPE algorithm. Use the 'energy' key to get the eigenvalue.
     """
     if backend is None:  # Default backend to Aer.get_backend('qasm_simulator').
         backend = Aer.get_backend('qasm_simulator')
     # QPE
     m, n = self.matrix.shape
     qpe = QPE(operator=MatrixOperator(matrix=self.matrix),
               state_in=Custom(m),
               iqft=Standard(num_ancillae),
               num_time_slices=50,
               num_ancillae=num_ancillae,
               expansion_mode='suzuki',
               expansion_order=2,
               shallow_circuit_concat=True)
     results = qpe.run(
         QuantumInstance(backend=backend,
                         skip_qobj_validation=False,
                         shots=shots))
     if print_eig: print("ENERGY:", results['energy'])
     return results
Esempio n. 9
0
 def calc_classical_eig(self,
                        print_results: bool = False,
                        solver: str = "exact_solver") -> list:
     """ Prints Eigenvalues generated by the selected classical algorithm.
     
     Args:
         print_results (bool, optional): print the eigenvalues or not. Defaults to False.
         solver (str, optional): can be "exact_solver" or "numpy". Defaults to "exact_solver"
     """
     results = []
     print("=======TRADITIONAL=======")
     if solver == "exact_solver":
         # Classical Eigensolver in Qiskit
         eig_solver = ExactEigensolver(MatrixOperator(self.matrix), 2)
         results = eig_solver.run()['eigvals']
         print("EXACTSOLVER:", results)
     elif solver == "numpy":
         # Classical Eigenvalue Decomposition in NumPy
         results = list(np.linalg.eig(self.matrix)[0])
         print("EIGENVALUES:", results)
         # print("EIGENVECTORS:", list(list(item) for item in np.linalg.eig(matrix)[1]))
     else:
         print("No solver found. Check your solver name.")
     print("=========================")
     return results
Esempio n. 10
0
 def execute_qpe_circuit(self,
                         num_ancillae: int = 1,
                         backend: BaseBackend = None,
                         shots: int = 1024,
                         print_eig: bool = False) -> Result:
     """Runs the QPE algorithm by constructing the circuit explicitly.
     
     Args:
         num_ancillae (int, optional): ancillary qubit number, the higher the more accurate, but use more computing resources. Defaults to 1.
         backend (BaseBackend, optional): Choose the backend to run this algorithm. Defaults to None.
         shots (int, optional): Indicate how many shots to take. Defaults to 1024.
         print_eig (bool, optional): whether or not print the eigenvalue. Defaults to False.
     
     Returns:
         Result: returns a Qiskit.result object. Use get_counts() to get a dictionary for the qubits' probabilities.
     """
     if backend is None:  # Default backend to Aer.get_backend('qasm_simulator').
         backend = Aer.get_backend('qasm_simulator')
     # QPE Circuit
     m, n = self.matrix.shape
     qpe = QPE(operator=MatrixOperator(matrix=self.matrix),
               state_in=Custom(m),
               iqft=Standard(num_ancillae),
               num_time_slices=50,
               num_ancillae=num_ancillae,
               expansion_mode='suzuki',
               expansion_order=2,
               shallow_circuit_concat=True)
     results = execute(qpe.construct_circuit(measurement=True),
                       backend=backend).result()
     if print_eig: print(results.get_counts())
     return results
Esempio n. 11
0
    def init_params(cls, params, matrix):  # pylint: disable=arguments-differ
        """
        Initialize via parameters dictionary and algorithm input instance

        Args:
            params (dict): parameters dictionary
            matrix (numpy.ndarray): two dimensional array which represents the operator
        Returns:
            EigsQPE: instance of this class
        Raises:
            AquaError: Operator instance is required
        """
        if matrix is None:
            raise AquaError("Operator instance is required.")

        if not isinstance(matrix, np.ndarray):
            matrix = np.array(matrix)

        eigs_params = params.get(Pluggable.SECTION_KEY_EIGS)
        args = {k: v for k, v in eigs_params.items() if k != 'name'}
        num_ancillae = eigs_params['num_ancillae']
        negative_evals = eigs_params['negative_evals']

        # Adding an additional flag qubit for negative eigenvalues
        if negative_evals:
            num_ancillae += 1
            args['num_ancillae'] = num_ancillae

        args['operator'] = MatrixOperator(matrix=matrix)

        # Set up iqft, we need to add num qubits to params which is our num_ancillae bits here
        iqft_params = params.get(Pluggable.SECTION_KEY_IQFT)
        iqft_params['num_qubits'] = num_ancillae
        args['iqft'] = get_pluggable_class(
            PluggableType.IQFT, iqft_params['name']).init_params(params)

        # For converting the encoding of the negative eigenvalues, we need two
        # additional instances for QFT and IQFT
        if negative_evals:
            ne_params = params
            qft_num_qubits = iqft_params['num_qubits']
            ne_qft_params = params.get(Pluggable.SECTION_KEY_QFT)
            ne_qft_params['num_qubits'] = qft_num_qubits - 1
            ne_iqft_params = params.get(Pluggable.SECTION_KEY_IQFT)
            ne_iqft_params['num_qubits'] = qft_num_qubits - 1
            ne_params['qft'] = ne_qft_params
            ne_params['iqft'] = ne_iqft_params
            args['ne_qfts'] = [
                get_pluggable_class(
                    PluggableType.QFT,
                    ne_qft_params['name']).init_params(ne_params),
                get_pluggable_class(
                    PluggableType.IQFT,
                    ne_iqft_params['name']).init_params(ne_params)
            ]
        else:
            args['ne_qfts'] = [None, None]

        return cls(**args)
Esempio n. 12
0
def Generate_op(op,*args, **kwargs):
    parameter = kwargs['parameter']
    ham = kwargs['ham']
    energy_step_tol = kwargs['energy_step_tol']
    mat = np.identity(2**op.num_qubits)
    Iden = to_weighted_pauli_operator(MatrixOperator(mat)) #creates random hamiltonian from random matrix "mat"
    #return np.exp(1j*parameter*op)*ham*np.exp(-1j*parameter*op).chop(threshold=energy_step_tol, copy=True)
    return (np.cos(parameter)*Iden + 1j*np.sin(parameter)*op)*ham*(np.cos(parameter)*Iden - 1j*np.sin(parameter)*op).chop(threshold=energy_step_tol, copy=True)
Esempio n. 13
0
def to_matrix_operator_from_WeightedPauliOperator(operator):
    """
    Copy and paste from https://github.com/Qiskit/qiskit-aqua/blob/master/qiskit/aqua/operators/op_converter.py of version 0.6.1

    Converting a given operator to `MatrixOperator`
    Args:
        operator (WeightedPauliOperator):
            one of supported operator type
    Returns:
        MatrixOperator: the converted matrix operator
    Raises:
        AquaError: Unsupported type to convert
    """
    if operator.is_empty():
        return MatrixOperator(None)
    hamiltonian = 0
    for weight, pauli in operator.paulis:
        hamiltonian += weight * pauli.to_spmatrix()
    return MatrixOperator(matrix=hamiltonian, z2_symmetries=operator.z2_symmetries,
                              name=operator.name)
Esempio n. 14
0
    def setUp(self):
        super().setUp()
        seed = 0
        aqua_globals.random_seed = seed

        self.num_qubits = 2
        m_size = np.power(2, self.num_qubits)
        matrix = aqua_globals.random.rand(m_size, m_size)
        self.mat_op = MatrixOperator(matrix=matrix)
        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.pauli_op = WeightedPauliOperator.from_list(paulis, weights)
Esempio n. 15
0
def create_eigs(matrix, num_auxiliary, num_time_slices, negative_evals):
    ne_qfts = [None, None]
    if negative_evals:
        num_auxiliary += 1
        ne_qfts = [QFT(num_auxiliary - 1), QFT(num_auxiliary - 1).inverse()]

    return EigsQPE(MatrixOperator(matrix=matrix),
                   QFT(num_auxiliary).inverse(),
                   num_time_slices=num_time_slices,
                   num_ancillae=num_auxiliary,
                   expansion_mode='suzuki',
                   expansion_order=2,
                   evo_time=None,  # This is t, can set to: np.pi*3/4
                   negative_evals=negative_evals,
                   ne_qfts=ne_qfts)
Esempio n. 16
0
def create_eigs(matrix, num_ancillae, num_time_slices, negative_evals):
    ne_qfts = [None, None]
    if negative_evals:
        num_ancillae += 1
        ne_qfts = [QFT(num_ancillae - 1), QFT(num_ancillae - 1).inverse()]
    ret = EigsQPE(MatrixOperator(matrix=matrix),
                   QFT(num_ancillae).inverse(),
                   num_time_slices=num_time_slices,
                   num_ancillae=num_ancillae,
                   expansion_mode='suzuki',
                   expansion_order=2,
                   evo_time=None,  # This is t, can set to: np.pi*3/4
                   negative_evals=negative_evals,
                   ne_qfts=ne_qfts)
    #print(ret.construct_circuit(mode='circuit'))
    return ret
Esempio n. 17
0
    def _create_eigs(matrix, num_ancillae, negative_evals):
        # Adding an additional flag qubit for negative eigenvalues
        ne_qfts = [None, None]
        if negative_evals:
            num_ancillae += 1
            ne_qfts = [StandardQFTS(num_ancillae - 1), StandardIQFTS(num_ancillae - 1)]

        return EigsQPE(MatrixOperator(matrix=matrix),
                       StandardIQFTS(num_ancillae),
                       num_time_slices=1,
                       num_ancillae=num_ancillae,
                       expansion_mode='suzuki',
                       expansion_order=2,
                       evo_time=None,
                       negative_evals=negative_evals,
                       ne_qfts=ne_qfts)
Esempio n. 18
0
    def create_eigs(self, matrix, num_ancillae, num_time_slices,
                    negative_evals):
        ne_qfts = [None, None]
        if negative_evals:
            num_ancillae += 1
            ne_qfts = [QFT(num_ancillae - 1), QFT(num_ancillae - 1).inverse()]

        return EigsQPE(MatrixOperator(matrix=matrix),
                       QFT(num_ancillae).inverse(),
                       num_time_slices=num_time_slices,
                       num_ancillae=num_ancillae,
                       expansion_mode='suzuki',
                       expansion_order=2,
                       evo_time=np.pi * 3 / 4,
                       negative_evals=negative_evals,
                       ne_qfts=ne_qfts)
def limit_paulis(mat, n=5, sparsity=None):
    """
    Limits the number of Pauli basis matrices of a hermitian matrix to the n
    highest magnitude ones.

    Args:
        mat (np.ndarray): Input matrix
        n (int): number of surviving Pauli matrices (default=5)
        sparsity (float): sparsity of matrix < 1

    Returns:
        scipy.sparse.csr_matrix: matrix
    """
    # pylint: disable=import-outside-toplevel
    from qiskit.aqua.operators import MatrixOperator
    from qiskit.aqua.operators.legacy.op_converter import to_weighted_pauli_operator
    # Bringing matrix into form 2**Nx2**N
    __l = mat.shape[0]
    if np.log2(__l) % 1 != 0:
        k = int(2**np.ceil(np.log2(__l)))
        m = np.zeros([k, k], dtype=np.complex128)
        m[:__l, :__l] = mat
        m[__l:, __l:] = np.identity(k - __l)
        mat = m

    # Getting Pauli matrices
    # pylint: disable=invalid-name
    op = MatrixOperator(matrix=mat)
    op = to_weighted_pauli_operator(op)
    paulis = sorted(op.paulis, key=lambda x: abs(x[0]), reverse=True)
    g = 2**op.num_qubits
    mat = scipy.sparse.csr_matrix(([], ([], [])),
                                  shape=(g, g),
                                  dtype=np.complex128)

    # Truncation
    if sparsity is None:
        for pa in paulis[:n]:
            mat += pa[0] * pa[1].to_spmatrix()
    else:
        idx = 0
        while mat[:__l, :__l].nnz / __l**2 < sparsity:
            mat += paulis[idx][0] * paulis[idx][1].to_spmatrix()
            idx += 1
        n = idx
    mat = mat.toarray()
    return mat[:__l, :__l]
def create_eigs(matrix, num_ancillae, negative_evals):
    ne_qfts = [None, None]
    if negative_evals:
        num_ancillae += 1
        ne_qfts = [
            StandardQFTS(num_ancillae - 1),
            StandardIQFTS(num_ancillae - 1)
        ]

    return EigsQPE(MatrixOperator(matrix=matrix),
                   StandardIQFTS(num_ancillae),
                   num_time_slices=50,
                   num_ancillae=num_ancillae,
                   expansion_mode='suzuki',
                   expansion_order=2,
                   evo_time=None,
                   negative_evals=negative_evals,
                   ne_qfts=ne_qfts)
Esempio n. 21
0
    def construct_wpo_operator(self):
        """Returns Weighted Pauli Operator (WPO) constructed from Hamiltonian
            text file.

        Args:
            None

        Returns:
            qubit_op (QISKit WPO object): Weighted Pauli Operator
        """
        # Loading matrix representation of Hamiltonian txt file
        H = np.loadtxt(self.file_path)
        # Converting Hamiltonian to Matrix Operator
        qubit_op = MatrixOperator(matrix=H)
        # Converting to Pauli Operator
        qubit_op = to_weighted_pauli_operator(qubit_op)
        self.num_qubits = qubit_op.num_qubits
        self.num_paulis = len(qubit_op.paulis)
        return qubit_op
Esempio n. 22
0
    def _create_eigs(matrix, num_ancillae, negative_evals):
        # Adding an additional flag qubit for negative eigenvalues
        ne_qfts = [None, None]
        if negative_evals:
            num_ancillae += 1
            ne_qfts = [QFT(num_ancillae - 1), QFT(num_ancillae - 1).inverse()]

        iqft = QFT(num_ancillae).inverse()

        eigs_qpe = EigsQPE(MatrixOperator(matrix=matrix),
                           iqft,
                           num_time_slices=1,
                           num_ancillae=num_ancillae,
                           expansion_mode='suzuki',
                           expansion_order=2,
                           evo_time=None,
                           negative_evals=negative_evals,
                           ne_qfts=ne_qfts)

        return eigs_qpe
Esempio n. 23
0
    def _create_eigs(matrix,
                     num_ancillae,
                     negative_evals,
                     use_circuit_library=True):
        # Adding an additional flag qubit for negative eigenvalues
        ne_qfts = [None, None]
        if not use_circuit_library:
            warnings.filterwarnings('ignore', category=DeprecationWarning)

        if negative_evals:
            num_ancillae += 1
            if use_circuit_library:
                ne_qfts = [
                    QFT(num_ancillae - 1),
                    QFT(num_ancillae - 1).inverse()
                ]
            else:
                ne_qfts = [
                    StandardQFTS(num_ancillae - 1),
                    StandardIQFTS(num_ancillae - 1)
                ]

        if use_circuit_library:
            iqft = QFT(num_ancillae).inverse()
        else:
            iqft = StandardIQFTS(num_ancillae)

        eigs_qpe = EigsQPE(MatrixOperator(matrix=matrix),
                           iqft,
                           num_time_slices=1,
                           num_ancillae=num_ancillae,
                           expansion_mode='suzuki',
                           expansion_order=2,
                           evo_time=None,
                           negative_evals=negative_evals,
                           ne_qfts=ne_qfts)

        if not use_circuit_library:
            warnings.filterwarnings('always', category=DeprecationWarning)

        return eigs_qpe
Esempio n. 24
0
class TestMatrixOperator(QiskitAquaTestCase):
    """MatrixOperator tests."""
    def setUp(self):
        super().setUp()
        seed = 0
        np.random.seed(seed)
        aqua_globals.random_seed = seed

        self.num_qubits = 3
        m_size = np.power(2, self.num_qubits)
        matrix = np.random.rand(m_size, m_size)
        self.qubit_op = MatrixOperator(matrix=matrix)

    def test_num_qubits(self):
        op = MatrixOperator(matrix=np.zeros((2, 2)))
        self.assertEqual(op.num_qubits, 0)
        self.assertEqual(self.qubit_op.num_qubits, self.num_qubits)

    def test_is_empty(self):
        op = MatrixOperator(matrix=np.zeros((2, 2)))
        self.assertTrue(op.is_empty())
        self.assertFalse(self.qubit_op.is_empty())
Esempio n. 25
0
    def test_invalid_primitive(self):
        """Test invalid MatrixOp construction"""
        msg = "MatrixOp can only be instantiated with " \
              "['list', 'ndarray', 'spmatrix', 'Operator'], not "

        with self.assertRaises(TypeError) as cm:
            _ = MatrixOp('invalid')

        self.assertEqual(str(cm.exception), msg + "'str'")

        with self.assertRaises(TypeError) as cm:
            _ = MatrixOp(MatrixOperator(np.eye(2)))

        self.assertEqual(str(cm.exception), msg + "'MatrixOperator'")

        with self.assertRaises(TypeError) as cm:
            _ = MatrixOp(None)

        self.assertEqual(str(cm.exception), msg + "'NoneType'")

        with self.assertRaises(TypeError) as cm:
            _ = MatrixOp(2.0)

        self.assertEqual(str(cm.exception), msg + "'float'")
Esempio n. 26
0
 def test_is_empty(self):
     """ is empty test """
     op = MatrixOperator(matrix=np.zeros((2, 2)))
     self.assertTrue(op.is_empty())
     self.assertFalse(self.qubit_op.is_empty())
Esempio n. 27
0
 def test_num_qubits(self):
     """ num qubits test """
     op = MatrixOperator(matrix=np.zeros((2, 2)))
     self.assertEqual(op.num_qubits, 0)
     self.assertEqual(self.qubit_op.num_qubits, self.num_qubits)
def run_exp(num_reps=1):

    # choice of Hi basis
    H_basis = [Pauli.from_label(p) for p in ['II', 'ZI', 'IZ', 'ZZ', 'YY', 'XX']]

    num_qubits = 2
    evo_time = 1
    epsilon = 0.1
    L = 32    ## number of local hamiltonian terms

    ############################################################
    # Generate a random Hamiltonian H as the sum of m basis Hi operators
    ############################################################

    hs = np.random.random(L)
    indexes = np.random.randint(low=0, high=6, size=L)

    ## H in matrix form
    H_matrix = np.zeros((2 ** num_qubits, 2 ** num_qubits))

    ## H as a list of pauli operators (unweighted)
    H_list = []
    for i in range(L):
        H_matrix = H_matrix + hs[i] * H_basis[indexes[i]].to_matrix()
        H_list.append(H_basis[indexes[i]])
    print('matrix H: \n', H_matrix)

    # H as a pauli operator
    H_qubitOp = op_converter.to_weighted_pauli_operator(MatrixOperator(matrix=H_matrix))

    # Generate an initial state
    state_in = Custom(num_qubits, state='random')

    ############################################################
    # Ground truth and benchmarks
    ############################################################

    # Ground truth
    state_in_vec = state_in.construct_circuit('vector')
    groundtruth = expm(-1.j * H_matrix * evo_time) @ state_in_vec
    print('The directly computed groundtruth evolution result state is')
    print('{}\n.'.format(groundtruth))

    # Build circuit using Qiskit's evolve algorithm, which based on Trotter-Suzuki.
    quantum_registers = QuantumRegister(num_qubits)
    circuit = state_in.construct_circuit('circuit', quantum_registers)
    circuit += H_qubitOp.evolve(
        None, evo_time, num_time_slices=10,
        quantum_registers=quantum_registers,
        expansion_mode='suzuki',
        expansion_order=1
    )

    # Simulate Trotter-Suzuki circuit and print it
    backend = BasicAer.get_backend('statevector_simulator')
    job = q_execute(circuit, backend)
    circuit_execution_result = np.asarray(job.result().get_statevector(circuit))
    print('The simulated (suzuki) evolution result state is')
    print('{}\n'.format(circuit_execution_result))

    # The difference between the ground truth and the simulated state
    # measured by "Fidelity"
    fidelity_suzuki = state_fidelity(groundtruth, circuit_execution_result)
    print('Fidelity between the groundtruth and the circuit result states is {}.'.format(fidelity_suzuki))
    print('\n')

    ############################################################
    # Our qdrift implementation
    ############################################################

    quantum_registers = QuantumRegister(num_qubits)
    circuit = state_in.construct_circuit('circuit', quantum_registers)

    # Contruct the circuit which implements qdrift
    circuit = time_evolve_qubits(quantum_registers, circuit, num_qubits, H_list, hs, evo_time, epsilon, num_reps)

    # Simulate circuit and print it
    backend = BasicAer.get_backend('statevector_simulator')
    job = q_execute(circuit, backend)
    circuit_execution_result = np.asarray(job.result().get_statevector(circuit))
    print('The simulated (qdrift) evolution result state is\n{}.'.format(circuit_execution_result))
    print('\n')

    # Measure the fidelity
    fidelity_qdrift = state_fidelity(groundtruth, circuit_execution_result)
    print('Fidelity between the groundtruth and the circuit result states is {}.'.format(fidelity_qdrift))
    print('\n')

    print('benchmark, suzuki:', fidelity_suzuki)
    print('qdrift:', fidelity_qdrift)
    return fidelity_qdrift, fidelity_suzuki
Esempio n. 29
0
from parameterized import parameterized
from qiskit import BasicAer
from qiskit.aqua import QuantumInstance
from qiskit.aqua.operators import MatrixOperator, WeightedPauliOperator, op_converter
from qiskit.aqua.utils import decimal_to_binary
from qiskit.aqua.algorithms import ExactEigensolver
from qiskit.aqua.algorithms import QPE
from qiskit.aqua.components.iqfts import Standard
from qiskit.aqua.components.initial_states import Custom

X = np.array([[0, 1], [1, 0]])
Y = np.array([[0, -1j], [1j, 0]])
Z = np.array([[1, 0], [0, -1]])
_I = np.array([[1, 0], [0, 1]])
H1 = X + Y + Z + _I
QUBIT_OP_SIMPLE = MatrixOperator(matrix=H1)
QUBIT_OP_SIMPLE = op_converter.to_weighted_pauli_operator(QUBIT_OP_SIMPLE)

PAULI_DICT = {
    'paulis': [{
        "coeff": {
            "imag": 0.0,
            "real": -1.052373245772859
        },
        "label": "II"
    }, {
        "coeff": {
            "imag": 0.0,
            "real": 0.39793742484318045
        },
        "label": "IZ"
Esempio n. 30
0
from qiskit.aqua import QuantumInstance
from qiskit.aqua.operators import MatrixOperator, WeightedPauliOperator, op_converter
from qiskit.aqua.utils import decimal_to_binary
from qiskit.aqua.algorithms import ExactEigensolver
from qiskit.aqua.algorithms import QPE
from qiskit.aqua.components.iqfts import Standard
from qiskit.aqua.components.initial_states import Custom
from test.aqua.common import QiskitAquaTestCase


X = np.array([[0, 1], [1, 0]])
Y = np.array([[0, -1j], [1j, 0]])
Z = np.array([[1, 0], [0, -1]])
_I = np.array([[1, 0], [0, 1]])
h1 = X + Y + Z + _I
qubit_op_simple = MatrixOperator(matrix=h1)
qubit_op_simple = op_converter.to_weighted_pauli_operator(qubit_op_simple)

pauli_dict = {
    'paulis': [
        {"coeff": {"imag": 0.0, "real": -1.052373245772859}, "label": "II"},
        {"coeff": {"imag": 0.0, "real": 0.39793742484318045}, "label": "IZ"},
        {"coeff": {"imag": 0.0, "real": -0.39793742484318045}, "label": "ZI"},
        {"coeff": {"imag": 0.0, "real": -0.01128010425623538}, "label": "ZZ"},
        {"coeff": {"imag": 0.0, "real": 0.18093119978423156}, "label": "XX"}
    ]
}
qubit_op_h2_with_2_qubit_reduction = WeightedPauliOperator.from_dict(pauli_dict)


pauli_dict_zz = {