Beispiel #1
0
    def get_exact_gs(self, hamiltonian=None):
        """
        Calculate the exact groundstate energy of the loaded Hamiltonian

        :param PauliSum hamiltonian: (optional) Hamiltonian of which
                one would like to calculate the GS energy

        :return: groundstate energy
        :rtype: float
        """
        if hamiltonian is None:
            h = get_sparse_operator(
                    pyquilpauli_to_qubitop(PauliSum(self.pauli_list)))
        else:
            if isinstance(hamiltonian, PauliSum):
                h = get_sparse_operator(pyquilpauli_to_qubitop(hamiltonian))
            else:
                raise TypeError('please give a PauliSum()'
                        ' object as the Hamiltonian.')

        if h.shape[0] > 1024:
            # sparse matrix eigenvalue decomposition is less accurate,
            # but is necessary for larger matrices
            [w, _] = sp.sparse.linalg.eigsh(h, k=1)
        else:
            [w, _] = np.linalg.eigh(h.todense())

        Egs = min(w).real

        return Egs
Beispiel #2
0
def test_pauli_to_quops(paulis):

    qubitops = pyquilpauli_to_qubitop(paulis)
    assert isinstance(qubitops, QubitOperator)

    for ind, term in enumerate(qubitops.terms.items()):

        # check that the qubits composing the generated QubitOperator
        # object corresponds to the chosen PauliSum instance
        qubit = term[0][0][0]
        ops = term[0][0][1]
        coeff = term[1].real

        assert coeff == true_values[ind][0]
        assert qubit == true_qubits[ind]
        assert ops == true_values[ind][1]
Beispiel #3
0
    def __init__(self, qc: Union[QuantumComputer, None] = None,
            hamiltonian: Union[PauliSum, List[PauliTerm], None] = None,
            molecule: MolecularData = None,
            method: str = 'Numpy',
            strategy: str = 'UCCSD',
            optimizer: str = 'BFGS',
            maxiter: int = 100000,
            shotN: int = 10000,
            active_reset: bool = True,
            tomography: bool = False,
            verbose: bool = False,
            parametric: bool = False,
            custom_qubits = None):
        """

        VQE experiment class.
        Initialize an instance of this class to prepare a VQE experiment.
        One may instantiate this class either based on
        an OpenFermion MolecularData object
        (containing a chemistry problem Hamiltonian)
        or manually suggest a Hamiltonian.

        The VQE can run circuits on different virtual or real backends:
        currently, we support the Rigetti QPU backend, locally running QVM,
        a WavefunctionSimulator, a NumpyWavefunctionSimulator.
        Alternatively, one may run the VQE ansatz unitary directly
        (not decomposed as a circuit)
        via direct exponentiation of the unitary ansatz,
        with the 'linalg' method.
        The different backends do not all support parametric gates (yet),
        and the user can specify whether or not to use it.

        Currently, we support two built-in ansatz strategies
        and the option of setting your own ansatz circuit.
        The built-in UCCSD and HF strategies are based on data
        from MolecularData object and thus require one.
        For finding the groundstate of a custom Hamiltonian,
        it is required to manually set an ansatz strategy.

        Currently, the only classical optimizer for the VQE
        is the scipy.optimize.minimize module.
        This may be straightforwardly extended in future releases,
        contributions are welcome.
        This class can be initialized with any algorithm in the scipy class,
        and the max number of iterations can be specified.

        For some QuantumComputer objects,
        the qubit lattice is not numbered 0..N-1
        but has architecture-specific logical labels.
        These need to be manually read from the lattice topology
        and specified in the list custom_qubits.
        On the physical hardware QPU,
        actively resetting the qubits is supported
        to speed up the repetition time of VQE.

        To debug and during development, set verbose=True
        to print output details to the console.

        :param [QuantumComputer(),None] qc:  object
        :param [PauliSum, list(PauliTerm)] hamiltonian:
                Hamiltonian which one would like to simulate
        :param MolecularData molecule: OpenFermion Molecule data object.
                If this is given, the VQE module assumes a
                chemistry experiment using OpenFermion
        :param str method: string describing the Backend solver method.
                current options: {Numpy, WFS, linalg, QC}
        :param str strategy: string describing circuit VQE strategy.
                current options: {UCCSD, HF, custom_program}
        :param str optimizer: classical optimization algorithm,
                choose from scipy.optimize.minimize options
        :param int maxiter: max number of iterations
        :param int shotN: number of shots in the Tomography experiments
        :param bool active_reset:  whether or not to actively reset the qubits
        :param bool tomography: set to False for access to full wavefunction,
                set to True for just sampling from it
        :param bool verbose: set to True for verbose output to the console,
                for all methods in this class
        :param bool parametric: set to True to use parametric gate compilation,
                False to compile a new circuit for every iteration
        :param list() custom_qubits: list of qubits, i.e. [7,0,1,2] ordering
                the qubit IDs as they appear on the QPU
                lattice of the QuantumComputer() object.

        """

        if isinstance(hamiltonian, PauliSum):
            if molecule is not None:
                raise TypeError('Please supply either a Hamiltonian object'
                        ' or a Molecule object, but not both.')
            # Hamiltonian as a PauliSum, extracted to give a list instead
            self.pauli_list = hamiltonian.terms
            self.n_qubits = self.get_qubit_req()
            # assumes 0-(N-1) ordering and every pauli index is in use
        elif isinstance(hamiltonian, List):
            if molecule is not None:
                raise TypeError('Please supply either a Hamiltonian object'
                        ' or a Molecule object, but not both.')
            if len(hamiltonian) > 0:
                if all([isinstance(term, PauliTerm) for term in hamiltonian]):
                    self.pauli_list = hamiltonian
                    self.n_qubits = self.get_qubit_req()
                else:
                    raise TypeError('Hamiltonian as a list must '
                            'contain only PauliTerm objects')
            else:
                print('Warning, empty hamiltonian passed, '
                        'assuming identity Hamiltonian = 1')
                self.pauli_list = [ID()]
                # this is allowed in principle,
                # but won't make a lot of sense to use.
        elif hamiltonian is None:
            if molecule is None:
                raise TypeError('either feed a MolecularData object '
                        'or a PyQuil Hamiltonian to this class')
            else:
                self.H = normal_ordered(get_fermion_operator(
                        molecule.get_molecular_hamiltonian()))
                # store Fermionic
                # Hamiltonian in FermionOperator() instance
                self.qubitop = jordan_wigner(self.H)
                # Apply jordan_wigner transformation and store
                self.n_qubits = 2 * molecule.n_orbitals
                self.pauli_list = qubitop_to_pyquilpauli(self.qubitop).terms
        else:
            raise TypeError('hamiltonian must be a PauliSum '
                    'or list of PauliTerms')

        # abstract QC. can refer to a qvm or qpu.
        # QC architecture and available gates decide the compilation of the
        # programs!
        if isinstance(qc, QuantumComputer):
            self.qc = qc
        elif qc is None:
            self.qc = None
        else:
            raise TypeError('qc must be a QuantumComputer object.'
                    ' If you do not use a QC backend, omit, or supply '
                    'qc=None')

        # number of shots in a tomography experiment
        if isinstance(shotN, int):
            self.shotN = shotN
        elif isinstance(shotN, float):
            self.shotN = int(shotN)
        else:
            raise TypeError('shotN must be an integer or float')
        print(f"shots = {self.shotN}")

        # simulation method. Choose from
        methodoptions = ['WFS', 'linalg', 'QC', 'Numpy']
        if method in methodoptions:
            self.method = method
        else:
            raise ValueError('choose a method from the following list: '\
                    + str(methodoptions) +
                    '. If a QPU, QVM is passed to qc, select QC.')

        # circuit strategy. choose from UCCSD, HF, custom_program
        strategyoptions = ['UCCSD', 'HF', 'custom_program']
        if strategy in strategyoptions:
            if (strategy in ['UCCSD', 'HF']) and molecule is None:
                raise ValueError('Strategy selected, UCCSD or HF, '
                        'requires a MolecularData object from PySCF as input.')
            self.strategy = strategy
        else:
            raise ValueError('choose a circuit strategy from the'
                    ' following list: ' + str(strategyoptions))

        # classical optimizer
        classical_options = ['Nelder-Mead', 'Powell', 'CG', 'BFGS',
                'Newton-CG', 'L-BFGS-B ', 'TNC', 'COBYLA',
                'SLSQP', 'trust-constr', 'dogleg', 'trust-ncg',
                'trust-exact', 'trust-krylov']
        if optimizer not in classical_options:
            raise ValueError('choose a classical optimizer from'
                    ' the following list: ' + str(classical_options))
        else:
            self.optimizer = optimizer

        # store the optimizer historical values
        self.history = []

        # chemistry files. must be properly formatted
        # in order to use a UCCSD ansatz (see MolecularData)
        self.molecule = molecule

        # whether or not the qubits should be actively reset.
        # False will make the hardware wait for 3 coherence lengths
        # to go back to |0>
        self.active_reset = active_reset

        # max number of iterations for the classical optimizer
        self.maxiter = maxiter

        # vqe results, stores output of scipy.optimize.minimize,
        # a OptimizeResult object. initialize to None
        self.res = None

        # list of grouped experiments (only relevant to tomography)
        self.experiment_list = None

        # whether to print debugging data to console
        self.verbose = verbose

        # real QPU has a custom qubit labeling
        self.custom_qubits = custom_qubits

        # i'th function call
        self.it_num = 0

        # whether to perform parametric method
        self.parametric_way = parametric

        # whether to do tomography or just calculate the wavefunction
        self.tomography = tomography

        # set empty circuit unitary.
        # This is used for the direct linear algebraic methods.
        self.circuit_unitary = None

        if strategy not in ['UCCSD', 'HF', 'custom_program']:
            raise ValueError('please select a strategy from UCCSD,'
                    ' HF, custom_program or modify this class with your '
                    'own options')

        if strategy == 'UCCSD':
            # load UCCSD initial amps from the CCSD amps
            # in the MolecularData() object
            amps = uccsd_singlet_get_packed_amplitudes(
                    self.molecule.ccsd_single_amps,
                    self.molecule.ccsd_double_amps,
                    n_qubits=self.molecule.n_orbitals * 2,
                    n_electrons=self.molecule.n_electrons)
            self.initial_packed_amps = amps
        else:
            # allocate empty initial angles for the circuit. modify later.
            self.initial_packed_amps = []

        if (strategy == 'UCCSD') and (method != 'linalg'):
            # UCCSD circuit strategy preparations
            self.ref_state = ref_state_preparation_circuit(
                    molecule,
                    ref_type='HF',
                    cq=self.custom_qubits)

            if self.parametric_way:
                # in the parametric_way,
                # the circuit is built with free parameters
                self.ansatz = uccsd_ansatz_circuit_parametric(
                        self.molecule.n_orbitals,
                        self.molecule.n_electrons,
                        cq=self.custom_qubits)
            else:
                # in the non-parametric_way,
                # the circuit has hard-coded angles for the gates.
                self.ansatz = uccsd_ansatz_circuit(
                        self.initial_packed_amps,
                        self.molecule.n_orbitals,
                        self.molecule.n_electrons,
                        cq=self.custom_qubits)
        elif strategy == 'HF':
            self.ref_state = ref_state_preparation_circuit(
                    self.molecule,
                    ref_type='HF',
                    cq=self.custom_qubits)
            self.ansatz = Program()
        elif strategy == 'custom_program':
            self.parametric_way = True
            self.ref_state = Program()
            self.ansatz = Program()

        if self.tomography:
            self.term_es = {}
            if self.method == 'linalg':
                raise NotImplementedError('Tomography is not'
                        ' yet implemented for the linalg method.')
        else:
            # avoid having to re-calculate the PauliSum object each time,
            # store it.
            self.pauli_sum = PauliSum(self.pauli_list)

        # perform miscellaneous method-specific preparations
        if self.method == 'QC':
            if qc is None:
                raise ValueError('Method is QC, please supply a valid '
                        'QuantumComputer() object to the qc variable.')
        elif self.method == 'WFS':
            if (self.qc is not None) or (self.custom_qubits is not None):
                raise ValueError('The WFS method is not intended to be used'
                        ' with a custom qubit lattice'
                        ' or QuantumComputer object.')
        elif self.method == 'Numpy':
            if self.parametric_way:
                raise ValueError('NumpyWavefunctionSimulator() backend'
                        ' does not yet support parametric programs.')
            if (self.qc is not None) or (self.custom_qubits is not None):
                raise ValueError('NumpyWavefunctionSimulator() backend is'
                        ' not intended to be used with a '
                        'QuantumComputer() object or custom lattice. '
                        'Consider using PyQVM instead')
        elif self.method == 'linalg':
            if molecule is not None:
                # sparse initial state vector from the MolecularData() object
                self.initial_psi = jw_hartree_fock_state(
                        self.molecule.n_electrons,
                        2*self.molecule.n_orbitals)
                # sparse operator from the MolecularData() object
                self.hamiltonian_matrix = get_sparse_operator(
                        self.H,
                        n_qubits=self.n_qubits)
            else:
                self.hamiltonian_matrix = get_sparse_operator(
                        pyquilpauli_to_qubitop(PauliSum(self.pauli_list)))
                self.initial_psi = None
                print('Please supply VQE initial state with method'
                        ' VQEexperiment().set_initial_state()')
        else:
            raise ValueError('unknown method: please choose from method ='
                    ' {linalg, WFS, tomography} for direct linear '
                    'algebra, pyquil WavefunctionSimulator, '
                    'or doing Tomography, respectively')