コード例 #1
0
    def test_h2_one_qubit_qasm(self):
        """Test H2 with tapering and qasm backend"""
        two_qubit_reduction = True
        qubit_mapping = 'parity'
        core = Hamiltonian(transformation=TransformationType.FULL,
                           qubit_mapping=QubitMappingType.PARITY,
                           two_qubit_reduction=two_qubit_reduction,
                           freeze_core=False,
                           orbital_reduction=[])
        qubit_op, _ = core.run(self.molecule)

        num_orbitals = core.molecule_info['num_orbitals']
        num_particles = core.molecule_info['num_particles']

        # tapering
        z2_symmetries = Z2Symmetries.find_Z2_symmetries(qubit_op)
        # know the sector
        tapered_op = z2_symmetries.taper(qubit_op)[1]

        var_form = RY(tapered_op.num_qubits, depth=1)
        optimizer = SPSA(max_trials=50)

        eom_vqe = QEomVQE(tapered_op, var_form, optimizer, num_orbitals=num_orbitals,
                          num_particles=num_particles, qubit_mapping=qubit_mapping,
                          two_qubit_reduction=two_qubit_reduction,
                          z2_symmetries=tapered_op.z2_symmetries, untapered_op=qubit_op)

        backend = BasicAer.get_backend('qasm_simulator')
        quantum_instance = QuantumInstance(backend, shots=65536)
        result = eom_vqe.run(quantum_instance)
        np.testing.assert_array_almost_equal(self.reference, result['energies'], decimal=2)
コード例 #2
0
    def test_h2_one_qubit(self):
        """Test H2 with tapering."""
        two_qubit_reduction = False
        qubit_mapping = 'jordan_wigner'
        core = Hamiltonian(transformation=TransformationType.FULL,
                           qubit_mapping=QubitMappingType.JORDAN_WIGNER,
                           two_qubit_reduction=two_qubit_reduction,
                           freeze_core=False,
                           orbital_reduction=[])
        qubit_op, _ = core.run(self.molecule)

        num_orbitals = core.molecule_info['num_orbitals']
        num_particles = core.molecule_info['num_particles']

        z2_symmetries = Z2Symmetries.find_Z2_symmetries(qubit_op)
        tapered_op = z2_symmetries.taper(qubit_op)[5]
        eom_ee = QEomEE(tapered_op,
                        num_orbitals=num_orbitals,
                        num_particles=num_particles,
                        qubit_mapping=qubit_mapping,
                        two_qubit_reduction=two_qubit_reduction,
                        z2_symmetries=tapered_op.z2_symmetries,
                        untapered_op=qubit_op)
        result = eom_ee.run()
        np.testing.assert_array_almost_equal(self.reference,
                                             result['energies'])
コード例 #3
0
ファイル: hamiltonian.py プロジェクト: hushaohan/aqua
    def _process_z2symmetry_reduction(self, qubit_op, aux_ops):

        z2_symmetries = Z2Symmetries.find_Z2_symmetries(qubit_op)
        if z2_symmetries.is_empty():
            logger.debug('No Z2 symmetries found')
            z2_qubit_op = qubit_op
            z2_aux_ops = aux_ops
            z2_symmetries = Z2Symmetries([], [], [], None)
        else:
            logger.debug('%s Z2 symmetries found: %s', len(z2_symmetries.symmetries),
                         ','.join([symm.to_label() for symm in z2_symmetries.symmetries]))

            # Check auxiliary operators commute with main operator's symmetry
            logger.debug('Checking operators commute with symmetry:')
            symmetry_ops = []
            for symmetry in z2_symmetries.symmetries:
                symmetry_ops.append(WeightedPauliOperator(paulis=[[1.0, symmetry]]))
            commutes = Hamiltonian._check_commutes(symmetry_ops, qubit_op)
            if not commutes:
                raise QiskitChemistryError('Z2 symmetry failure main operator must commute '
                                           'with symmetries found from it')
            for i, aux_op in enumerate(aux_ops):
                commutes = Hamiltonian._check_commutes(symmetry_ops, aux_op)
                if not commutes:
                    aux_ops[i] = None  # Discard since no meaningful measurement can be done

            if self._z2symmetry_reduction == 'auto':
                hf_state = HartreeFock(num_orbitals=self._molecule_info[self.INFO_NUM_ORBITALS],
                                       qubit_mapping=self._qubit_mapping,
                                       two_qubit_reduction=self._two_qubit_reduction,
                                       num_particles=self._molecule_info[self.INFO_NUM_PARTICLES])
                z2_symmetries = Hamiltonian._pick_sector(z2_symmetries, hf_state.bitstr)
            else:
                if len(self._z2symmetry_reduction) != len(z2_symmetries.symmetries):
                    raise QiskitChemistryError('z2symmetry_reduction tapering values list has '
                                               'invalid length {} should be {}'.
                                               format(len(self._z2symmetry_reduction),
                                                      len(z2_symmetries.symmetries)))
                valid = np.all(np.isin(self._z2symmetry_reduction, [-1, 1]))
                if not valid:
                    raise QiskitChemistryError('z2symmetry_reduction tapering values list must '
                                               'contain -1\'s and/or 1\'s only was {}'.
                                               format(self._z2symmetry_reduction,))
                z2_symmetries.tapering_values = self._z2symmetry_reduction

            logger.debug('Apply symmetry with tapering values %s', z2_symmetries.tapering_values)
            chop_to = 0.00000001  # Use same threshold as qubit mapping to chop tapered operator
            z2_qubit_op = z2_symmetries.taper(qubit_op).chop(chop_to)
            z2_aux_ops = []
            for aux_op in aux_ops:
                z2_aux_ops.append(z2_symmetries.taper(aux_op).chop(chop_to) if aux_op is not None
                                  else None)

        return z2_qubit_op, z2_aux_ops, z2_symmetries
コード例 #4
0
    def setUp(self):
        super().setUp()
        try:
            self.molecule = "H 0.000000 0.000000 0.735000;H 0.000000 0.000000 0.000000"
            self.driver = PySCFDriver(atom=self.molecule,
                                      unit=UnitsType.ANGSTROM,
                                      charge=0,
                                      spin=0,
                                      basis='631g')
            self.qmolecule = self.driver.run()
            self.core = Hamiltonian(transformation=TransformationType.FULL,
                                    qubit_mapping=QubitMappingType.PARITY,
                                    two_qubit_reduction=True,
                                    freeze_core=True,
                                    orbital_reduction=[])
            self.qubit_op, _ = self.core.run(self.qmolecule)

            z2_symmetries = Z2Symmetries.find_Z2_symmetries(self.qubit_op)
            tapered_ops = z2_symmetries.taper(self.qubit_op)
            smallest_eig_value = 99999999999999
            smallest_idx = -1
            for idx, _ in enumerate(tapered_ops):
                ee = ExactEigensolver(tapered_ops[idx], k=1)
                curr_value = ee.run()['energy']
                if curr_value < smallest_eig_value:
                    smallest_eig_value = curr_value
                    smallest_idx = idx
            self.the_tapered_op = tapered_ops[smallest_idx]

            self.reference_energy_pUCCD = -1.1434447924298028
            self.reference_energy_UCCD0 = -1.1476045878481704
            self.reference_energy_UCCD0full = -1.1515491334334347
            # reference energy of UCCSD/VQE with tapering everywhere
            self.reference_energy_UCCSD = -1.1516142309717594
            # reference energy of UCCSD/VQE when no tapering on excitations is used
            self.reference_energy_UCCSD_no_tap_exc = -1.1516142309717594
            # excitations for succ
            self.reference_singlet_double_excitations = [[0, 1, 4, 5],
                                                         [0, 1, 4, 6],
                                                         [0, 1, 4, 7],
                                                         [0, 2, 4, 6],
                                                         [0, 2, 4, 7],
                                                         [0, 3, 4, 7]]
            # groups for succ_full
            self.reference_singlet_groups = [[[0, 1, 4, 5]],
                                             [[0, 1, 4, 6], [0, 2, 4, 5]],
                                             [[0, 1, 4, 7], [0, 3, 4, 5]],
                                             [[0, 2, 4, 6]],
                                             [[0, 2, 4, 7], [0, 3, 4, 6]],
                                             [[0, 3, 4, 7]]]
        except QiskitChemistryError:
            self.skipTest('PYSCF driver does not appear to be installed')
コード例 #5
0
    def test_h2_one_qubit_statevector(self):
        """Test H2 with tapering and statevector backend."""
        two_qubit_reduction = True
        qubit_mapping = 'parity'
        warnings.filterwarnings('ignore', category=DeprecationWarning)
        core = Hamiltonian(transformation=TransformationType.FULL,
                           qubit_mapping=QubitMappingType.PARITY,
                           two_qubit_reduction=two_qubit_reduction,
                           freeze_core=False,
                           orbital_reduction=[])
        warnings.filterwarnings('always', category=DeprecationWarning)
        qubit_op, _ = core.run(self.molecule)

        num_orbitals = core.molecule_info['num_orbitals']
        num_particles = core.molecule_info['num_particles']

        # tapering
        z2_symmetries = Z2Symmetries.find_Z2_symmetries(qubit_op)
        # know the sector
        tapered_op = z2_symmetries.taper(qubit_op)[1]

        initial_state = HartreeFock(num_orbitals=num_orbitals,
                                    num_particles=num_particles,
                                    qubit_mapping=qubit_mapping,
                                    two_qubit_reduction=two_qubit_reduction,
                                    sq_list=tapered_op.z2_symmetries.sq_list)
        var_form = UCCSD(num_orbitals=num_orbitals,
                         num_particles=num_particles,
                         initial_state=initial_state,
                         qubit_mapping=qubit_mapping,
                         two_qubit_reduction=two_qubit_reduction,
                         z2_symmetries=tapered_op.z2_symmetries)
        optimizer = SPSA(maxiter=50)

        eom_vqe = QEomVQE(tapered_op,
                          var_form,
                          optimizer,
                          num_orbitals=num_orbitals,
                          num_particles=num_particles,
                          qubit_mapping=qubit_mapping,
                          two_qubit_reduction=two_qubit_reduction,
                          z2_symmetries=tapered_op.z2_symmetries,
                          untapered_op=qubit_op)

        backend = BasicAer.get_backend('statevector_simulator')
        quantum_instance = QuantumInstance(backend)
        result = eom_vqe.run(quantum_instance)
        np.testing.assert_array_almost_equal(self.reference,
                                             result['energies'],
                                             decimal=5)
コード例 #6
0
    def setUp(self):
        super().setUp()
        try:
            driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0 1.6',
                                 unit=UnitsType.ANGSTROM,
                                 charge=0,
                                 spin=0,
                                 basis='sto3g')
        except QiskitChemistryError:
            self.skipTest('PYSCF driver does not appear to be installed')
        self.qmolecule = driver.run()
        self.core = Hamiltonian(transformation=TransformationType.FULL,
                                qubit_mapping=QubitMappingType.PARITY,
                                two_qubit_reduction=True,
                                freeze_core=True,
                                orbital_reduction=[])
        self.qubit_op, _ = self.core.run(self.qmolecule)
        self.z2_symmetries = Z2Symmetries.find_Z2_symmetries(self.qubit_op)

        self.reference_energy = -7.882096489442
コード例 #7
0
    def _process_z2symmetry_reduction(
            self, qubit_op: WeightedPauliOperator,
            aux_ops: List[WeightedPauliOperator]) -> Tuple:
        """
        Implement z2 symmetries in the qubit operator

        Args:
            qubit_op : qubit operator
            aux_ops: auxiliary operators

        Returns:
            (z2_qubit_op, z2_aux_ops, z2_symmetries)

        Raises:
            QiskitChemistryError: Invalid input
        """
        z2_symmetries = Z2Symmetries.find_Z2_symmetries(qubit_op)
        if z2_symmetries.is_empty():
            logger.debug('No Z2 symmetries found')
            z2_qubit_op = qubit_op
            z2_aux_ops = aux_ops
            z2_symmetries = Z2Symmetries([], [], [], None)
        else:
            logger.debug(
                '%s Z2 symmetries found: %s', len(z2_symmetries.symmetries),
                ','.join(
                    [symm.to_label() for symm in z2_symmetries.symmetries]))

            # Check auxiliary operators commute with main operator's symmetry
            logger.debug('Checking operators commute with symmetry:')
            symmetry_ops = []
            for symmetry in z2_symmetries.symmetries:
                symmetry_ops.append(
                    WeightedPauliOperator(paulis=[[1.0, symmetry]]))
            commutes = FermionicTransformation._check_commutes(
                symmetry_ops, qubit_op)
            if not commutes:
                raise QiskitChemistryError(
                    'Z2 symmetry failure main operator must commute '
                    'with symmetries found from it')
            for i, aux_op in enumerate(aux_ops):
                commutes = FermionicTransformation._check_commutes(
                    symmetry_ops, aux_op)
                if not commutes:
                    aux_ops[
                        i] = None  # Discard since no meaningful measurement can be done

            if self._z2symmetry_reduction == 'auto':
                from ..circuit.library.initial_states.hartree_fock import hartree_fock_bitstring
                hf_bitstr = hartree_fock_bitstring(
                    num_orbitals=self._molecule_info['num_orbitals'],
                    qubit_mapping=self._qubit_mapping,
                    two_qubit_reduction=self._two_qubit_reduction,
                    num_particles=self._molecule_info['num_particles'])
                z2_symmetries = FermionicTransformation._pick_sector(
                    z2_symmetries, hf_bitstr)
            else:
                if len(self._z2symmetry_reduction) != len(
                        z2_symmetries.symmetries):
                    raise QiskitChemistryError(
                        'z2symmetry_reduction tapering values list has '
                        'invalid length {} should be {}'.format(
                            len(self._z2symmetry_reduction),
                            len(z2_symmetries.symmetries)))
                valid = np.all(np.isin(self._z2symmetry_reduction, [-1, 1]))
                if not valid:
                    raise QiskitChemistryError(
                        'z2symmetry_reduction tapering values list must '
                        'contain -1\'s and/or 1\'s only was {}'.format(
                            self._z2symmetry_reduction, ))
                z2_symmetries.tapering_values = self._z2symmetry_reduction

            logger.debug('Apply symmetry with tapering values %s',
                         z2_symmetries.tapering_values)
            chop_to = 0.00000001  # Use same threshold as qubit mapping to chop tapered operator
            z2_qubit_op = z2_symmetries.taper(qubit_op).chop(chop_to)
            z2_aux_ops = []
            for aux_op in aux_ops:
                if aux_op is None:
                    z2_aux_ops += [None]
                else:
                    z2_aux_ops += [z2_symmetries.taper(aux_op).chop(chop_to)]

        return z2_qubit_op, z2_aux_ops, z2_symmetries
コード例 #8
0
def taper(molecule, core, qubit_op, A_op, outf):

    z2_symmetries = Z2Symmetries.find_Z2_symmetries(qubit_op)
    the_ancillas = A_op
    nsym = len(z2_symmetries.sq_paulis)
    the_tapered_op = qubit_op
    sqlist = None
    z2syms = None

    outf.write('\n\nstart tapering... \n\n')

    if (nsym > 0):
        outf.write('Z2 symmetries found:\n')
        for symm in z2_symmetries.symmetries:
            outf.write(symm.to_label() + '\n')
        outf.write('single qubit operators found:\n')
        for sq in z2_symmetries.sq_paulis:
            outf.write(sq.to_label() + '\n')
        outf.write('cliffords found:\n')
        for clifford in z2_symmetries.cliffords:
            outf.write(clifford.print_details() + '\n')
        outf.write('single-qubit list: {}\n'.format(z2_symmetries.sq_list))

        tapered_ops = z2_symmetries.taper(qubit_op)
        for tapered_op in tapered_ops:
            outf.write(
                "Number of qubits of tapered qubit operator: {}\n".format(
                    tapered_op.num_qubits))

        ee = NumPyEigensolver(qubit_op, k=1)
        result = core.process_algorithm_result(ee.run())
        for line in result[0]:
            outf.write(line + '\n')

        smallest_eig_value = 99999999999999
        smallest_idx = -1
        for idx in range(len(tapered_ops)):
            ee = NumPyEigensolver(tapered_ops[idx], k=1)
            curr_value = ee.run()['eigenvalues'][0]
            if curr_value < smallest_eig_value:
                smallest_eig_value = curr_value
                smallest_idx = idx
            outf.write(
                "Lowest eigenvalue of the {}-th tapered operator (computed part) is {:.12f}\n"
                .format(idx, curr_value))

        the_tapered_op = tapered_ops[smallest_idx]
        the_coeff = tapered_ops[smallest_idx].z2_symmetries.tapering_values
        outf.write(
            "The {}-th tapered operator matches original ground state energy, with corresponding symmetry sector of {}\n"
            .format(smallest_idx, the_coeff))
        sqlist = the_tapered_op.z2_symmetries.sq_list
        z2syms = the_tapered_op.z2_symmetries

        the_ancillas = []
        for A in A_op:
            A_taper = z2_symmetries.taper(A)
            if (type(A_taper) == list):
                the_ancillas.append(A_taper[smallest_idx])
            else:
                the_ancillas.append(A_taper)

    outf.write('\n\n...finish tapering \n\n')

    return the_tapered_op, the_ancillas, z2syms, sqlist
コード例 #9
0
ファイル: tmp.py プロジェクト: paulineollitrault/COBRA
def run_ucc_r12(opt):
    """
    Parameters
    ----------
    * opt dictionary with user and default options/thresholds
    Returns
    -------
    * UCC-R12 ground state energy
        
    """

    import itertools
    import logging
    import numpy as np
    import time
    from datetime import datetime

    import qiskit    
    from qiskit                            import BasicAer,Aer    
    from qiskit.aqua                       import set_qiskit_aqua_logging, QuantumInstance
    from qiskit.aqua.operators             import Z2Symmetries, WeightedPauliOperator
    from qiskit.aqua.algorithms.adaptive   import VQE
    from qiskit.aqua.algorithms.classical  import ExactEigensolver
    from qiskit.aqua.components.optimizers import L_BFGS_B,CG,SPSA,SLSQP, COBYLA

    from qiskit.chemistry.drivers                                      import PySCFDriver, UnitsType, HFMethodType
    from qiskit.chemistry.core                                         import TransformationType, QubitMappingType
    from qiskit.chemistry.aqua_extensions.components.initial_states    import HartreeFock
    from qiskit.chemistry                                              import set_qiskit_chemistry_logging

    # ----- local functions ----- #
    import sys
    sys.path.append('/Users/mario/Documents/GitHub/R12-F12/project_ec/ucc_ec/')
    from qmolecule_ec   import QMolecule_ec,build_parameter_list
    from hamiltonian_ec import Hamiltonian
    from uccsd_ec       import UCCSD

    from davidson import davidson

    #import logging
    #set_qiskit_chemistry_logging(logging.DEBUG)

    logfile = open(opt["logfile"],'w')
    dateTimeObj = datetime.now()
    logfile.write("date and time "+str(dateTimeObj)+"\n")
    logfile.write("\n\n")

    import subprocess
    label = subprocess.check_output(['git','log','-1','--format="%H"']).strip()
    logfile.write("git commit "+str(label)+"\n")
    logfile.write("\n\n")

    qiskit_dict = qiskit.__qiskit_version__
    logfile.write("qiskit version \n")
    for k in qiskit_dict:
    	logfile.write(k+" : "+qiskit_dict[k]+"\n")
    logfile.write("\n\n")

    logfile.write("local run options \n")
    for k in opt:
    	logfile.write(k+" : "+str(opt[k])+"\n")
    logfile.write("\n\n")

    import time
    t0 = time.time()

    if(opt["input_file"] is None):
     # ----- normal molecular calc ----- #
     if(opt["calc_type"].lower() == "rhf"):  hf=HFMethodType.RHF
     if(opt["calc_type"].lower() == "rohf"): hf=HFMethodType.ROHF
     if(opt["calc_type"].lower() == "uhf"):  hf=HFMethodType.UHF
     driver      = PySCFDriver(atom=opt["geometry"],unit=UnitsType.ANGSTROM,charge=opt["charge"],spin=opt["spin"],basis=opt["basis"],hf_method=hf)
     molecule    = driver.run()
     molecule_ec = QMolecule_ec(molecule=molecule,filename=None,logfile=logfile)
    else:
     # ----- custom matrix elements ----- #
     molecule_ec = QMolecule_ec(molecule=None,filename=opt["input_file"],calc=opt["calc_type"],nfreeze=opt["nfreeze"],logfile=logfile)

    molecule_ec.mo_eri_ints_ec = (molecule_ec.mo_eri_ints_ec).transpose((0,1,3,2))

    t1 = time.time()
    logfile.write("classical ES and setup: %f [s] \n" % (t1-t0))
    logfile.write("\n\n")

    core        = Hamiltonian(qubit_mapping=QubitMappingType.PARITY,two_qubit_reduction=True,freeze_core=False)
    qubit_op, _ = core.run(molecule_ec)

    t2 = time.time()
    logfile.write("second-quantized Hamiltonian setup : %f [s] \n" % (t2-t1))
    logfile.write("\n\n")

    logfile.write("Original number of qubits %d \n" % (qubit_op.num_qubits))
    z2_symmetries = Z2Symmetries.find_Z2_symmetries(qubit_op)

    nsym = len(z2_symmetries.sq_paulis)
    the_tapered_op = qubit_op
    sqlist = None
    z2syms = None

    if(nsym>0):

       logfile.write('\nZ2 symmetries found: \n')
       for symm in z2_symmetries.symmetries:
           logfile.write(symm.to_label())
       logfile.write('\nsingle-qubit operators found: \n')
       for sq in z2_symmetries.sq_paulis:
           logfile.write(sq.to_label())
       logfile.write('\nCliffords found: \n')
       for clifford in z2_symmetries.cliffords:
           logfile.write(clifford.print_details())
       logfile.write('\nsingle-qubit list: {} \n'.format(z2_symmetries.sq_list))
       
       tapered_ops = z2_symmetries.taper(qubit_op)
       for tapered_op in tapered_ops:
           logfile.write("Number of qubits of tapered qubit operator: %d \n" % (tapered_op.num_qubits))
       
       t3 = time.time()
       logfile.write("detection of symmetries: %f [s] \n" % (t3-t2))
     
       smallest_eig_value = 99999999999999
       smallest_idx = -1
      
       for idx in range(len(tapered_ops)):
           td0 = time.time()
           from utils import retrieve_SCF_energy
           print("In sector ",idx,len(tapered_ops))
           curr_value = retrieve_SCF_energy(tapered_ops[idx].copy(),core,opt) #,parm_list)
           curr_value = np.abs(curr_value-molecule_ec.hf_energy)
           print("Deviation ",curr_value)
           if curr_value < smallest_eig_value:
              smallest_eig_value = curr_value
              smallest_idx = idx
              if(curr_value<1e-6): break
           td1 = time.time()
           val = curr_value
           logfile.write("Lowest-energy computational basis state of the {}-th tapered operator is %s %f \n" % (str(idx),val))
           logfile.write("HF search time %f: \n" % (td1-td0))
     
       the_tapered_op = tapered_ops[smallest_idx]
       the_coeff = tapered_ops[smallest_idx].z2_symmetries.tapering_values
       logfile.write("{}-th tapered operator, with corresponding symmetry sector of {}".format(smallest_idx, the_coeff))
       logfile.write("\nNumber of qubits in the {}-th tapered operator {}\n\n".format(smallest_idx,the_tapered_op.num_qubits))

       sqlist = the_tapered_op.z2_symmetries.sq_list
       z2syms = the_tapered_op.z2_symmetries

    # ========
    # setup initial state
    # ========

    init_state = HartreeFock(num_qubits=the_tapered_op.num_qubits, num_orbitals=core._molecule_info['num_orbitals'],
                        qubit_mapping=core._qubit_mapping, two_qubit_reduction=core._two_qubit_reduction,
                        num_particles=core._molecule_info['num_particles'],sq_list=sqlist)

    # ---- initial parameter guess 
    init_parm = None
    if(opt["start_pt"].lower()=="file"):
       init_parm = np.loadtxt('vqe.parameters')
    if(opt["var_form"].lower()=="uccsd" and opt["start_pt"].lower()=="ccsd"):
       parm_list    = build_parameter_list(molecule_ec)

    logfile.write("Initial parameters = %d\n" % len(parm_list))
    for mu,p in enumerate(parm_list):
        logfile.write('%d %f\n' % (mu,p))

    if(opt["var_form"].lower()=="uccsd"):
        var_form = UCCSD(num_qubits=the_tapered_op.num_qubits,depth=opt["UCCSD_depth"],
                   num_orbitals=core._molecule_info['num_orbitals'],
                   num_particles=core._molecule_info['num_particles'],
                   active_occupied=opt["UCCSD_active_occupied"], active_unoccupied=opt["UCCSD_active_unoccupied"], initial_state=init_state,
                   qubit_mapping=core._qubit_mapping, two_qubit_reduction=core._two_qubit_reduction,
                   num_time_slices=opt["UCCSD_num_time_slices"],z2_symmetries=z2syms,init_parm=parm_list)

        if(opt["var_form"].lower()=="uccsd" and opt["start_pt"].lower()=="ccsd"):
           nparm,ndepth = len(var_form._mask),var_form._depth
           init_parm    = np.zeros(nparm*ndepth)
           for idp in range(ndepth):
            for ims in range(nparm):
             init_parm[ims+idp*nparm] = parm_list[var_form._mask[ims]]

        logfile.write("Selected parameters = %d\n" % nparm)
        for mu,p in enumerate(var_form._mask):
            logfile.write('%d %f\n' % (p,parm_list[p]))

    elif(opt["var_form"].lower()=="ry"):
        var_form = RY(the_tapered_op.num_qubits,depth=opt["R_depth"],
                   entanglement=opt["R_entanglement"],initial_state=HF_state)
    elif(opt["var_form"].lower()=="ryrz"):
        var_form = RYRZ(the_tapered_op.num_qubits,depth=opt["R_depth"],
                   entanglement=opt["R_entanglement"],initial_state=HF_state)
    elif(opt["var_form"].lower()=="swaprz"):
        var_form = SwapRZ(the_tapered_op.num_qubits,depth=opt["R_depth"],
                   entanglement=opt["R_entanglement"],initial_state=HF_state)
    else:
        print("invalid variational form")
        assert(False)

    # setup optimizer
    if(  opt["optimizer"].lower()=="bfgs"):  optimizer = L_BFGS_B(maxiter=opt["max_eval"])
    elif(opt["optimizer"].lower()=="cg"):    optimizer = CG(maxiter=opt["max_eval"])
    elif(opt["optimizer"].lower()=="slsqp"): optimizer = SLSQP(maxiter=opt["max_eval"])
    elif(opt["optimizer"].lower()=="spsa"):  optimizer = SPSA()
    elif(opt["optimizer"].lower()=="cobyla"): optimizer = COBYLA(maxiter=opt["max_eval"])
    else:                                    print("not coded yet"); assert(False) 

    # set vqe
    if(opt["var_form"].lower()=="uccsd"): algo = VQE(the_tapered_op,var_form,optimizer,initial_point=init_parm)
    else:                                 algo = VQE(the_tapered_op,var_form,optimizer)
    # setup backend
    backend = Aer.get_backend('statevector_simulator')
    quantum_instance = QuantumInstance(backend=backend)

    t0 = time.time()

    algo_result = algo.run(quantum_instance)

    t1 = time.time()

    logfile.write("\nVQE time [s] %f \n\n" % (t1-t0))

    result = core.process_algorithm_result(algo_result)
    for line in result[0]:
        logfile.write(line+"\n")
    
    logfile.write("\nThe parameters for UCCSD are:\n")
    for i,(tc,tq) in enumerate(zip(init_parm,algo_result['opt_params'])):
     logfile.write("%d %f %f \n" % (i,tc,tq))

    if(opt["print_parameters"]):
       par_file = open('vqe.parameters','w')
       for p in algo_result['opt_params']:
        par_file.write("%f \n" % p)
       par_file.close()

    #td0 = time.time()
    #ee = davidson(the_tapered_op,'fci')
    #td1 = time.time()
    #logfile.write("\n\nExact diagonalization, energy: %f \n" % (ee+molecule_ec.nuclear_repulsion_energy+molecule_ec.energy_offset_ec))

    #logfile.write("Davidson FCI time: %f [s] \n" % (td1-td0))
    
    print('============================================================================')
    print('                                      DONE!')
    print('============================================================================')
    

    return 0
コード例 #10
0
                     basis='sto3g')
#                     basis='sto6g')
#                     basis='631g')

qmolecule = driver.run()

core = Hamiltonian(transformation=TransformationType.FULL,
                   qubit_mapping=QubitMappingType.PARITY,
                   two_qubit_reduction=True,
                   freeze_core=False,
                   orbital_reduction=[])

qubit_op, _ = core.run(qmolecule)

# find the symmetries of the Hamiltonian
z2_symmetries = Z2Symmetries.find_Z2_symmetries(qubit_op)
tapered_ops = z2_symmetries.taper(qubit_op)
smallest_idx = 0

# Prior knowledge of which tapered_op has ground state
# or you can find the operator that has the ground state by diagonalising each operator
#smallest_eig_value = 99999999999999
#smallest_idx = -1
#for idx in range(len(tapered_ops)):
#    print('operator number: ', idx)
#    ee = ExactEigensolver(tapered_ops[idx], k=1)
#    curr_value = ee.run()['energy']
#    if curr_value < smallest_eig_value:
#        smallest_eig_value = curr_value
#        smallest_idx = idx
#print('Operator number: ', smallest_idx, ' contains the ground state.')