def __init__(self, operator, k=1, aux_operators=None): """Constructor. Args: operator (MatrixOperator): instance k (int): How many eigenvalues are to be computed aux_operators (list[MatrixOperator]): Auxiliary operators to be evaluated at each eigenvalue """ validate(locals(), self._INPUT_SCHEMA) super().__init__() self._operator = op_converter.to_matrix_operator(operator) if aux_operators is None: self._aux_operators = [] else: aux_operators = \ [aux_operators] if not isinstance(aux_operators, list) else aux_operators self._aux_operators = \ [op_converter.to_matrix_operator(aux_op) for aux_op in aux_operators] self._k = k if self._k > self._operator.matrix.shape[0]: self._k = self._operator.matrix.shape[0] logger.debug( "WARNING: Asked for %s eigenvalues but max possible is %s.", k, self._k) self._ret = {}
def __init__(self, operator: BaseOperator, k: int = 1, aux_operators: Optional[List[BaseOperator]] = None) -> None: """Constructor. Args: operator: instance k: How many eigenvalues are to be computed, has a min. value of 1. aux_operators: Auxiliary operators to be evaluated at each eigenvalue """ validate_min('k', k, 1) super().__init__() self._operator = op_converter.to_matrix_operator(operator) if aux_operators is None: self._aux_operators = [] else: aux_operators = \ [aux_operators] if not isinstance(aux_operators, list) else aux_operators self._aux_operators = \ [op_converter.to_matrix_operator(aux_op) for aux_op in aux_operators] self._k = k if self._k > self._operator.matrix.shape[0]: self._k = self._operator.matrix.shape[0] logger.debug( "WARNING: Asked for %s eigenvalues but max possible is %s.", k, self._k) self._ret = {}
def test_bksf_mapping(self): """Test bksf mapping. The spectrum of bksf mapping should be half of jordan wigner mapping. """ driver = PySCFDriver(atom='H .0 .0 0.7414; H .0 .0 .0', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() fer_op = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) jw_op = fer_op.mapping('jordan_wigner') bksf_op = fer_op.mapping('bksf') jw_op = op_converter.to_matrix_operator(jw_op) bksf_op = op_converter.to_matrix_operator(bksf_op) jw_eigs = np.linalg.eigvals(jw_op.matrix.toarray()) bksf_eigs = np.linalg.eigvals(bksf_op.matrix.toarray()) jw_eigs = np.sort(np.around(jw_eigs.real, 6)) bksf_eigs = np.sort(np.around(bksf_eigs.real, 6)) overlapped_spectrum = np.sum(np.isin(jw_eigs, bksf_eigs)) self.assertEqual(overlapped_spectrum, jw_eigs.size // 2)
def _config_the_best_mode(self, operator, backend): if not isinstance(operator, (WeightedPauliOperator, MatrixOperator, TPBGroupedWeightedPauliOperator)): logger.debug("Unrecognized operator type, skip auto conversion.") return operator ret_op = operator if not is_statevector_backend(backend) and not ( is_aer_provider(backend) and self._quantum_instance.run_config.shots == 1): if isinstance(operator, (WeightedPauliOperator, MatrixOperator)): logger.debug( "When running with Qasm simulator, grouped pauli can " "save number of measurements. " "We convert the operator into grouped ones.") ret_op = op_converter.to_tpb_grouped_weighted_pauli_operator( operator, TPBGroupedWeightedPauliOperator.sorted_grouping) else: if not is_aer_provider(backend): if not isinstance(operator, MatrixOperator): logger.info( "When running with non-Aer statevector simulator, " "represent operator as a matrix could " "achieve the better performance. We convert " "the operator to matrix.") ret_op = op_converter.to_matrix_operator(operator) else: if not isinstance(operator, WeightedPauliOperator): logger.info("When running with Aer simulator, " "represent operator as weighted paulis could " "achieve the better performance. We convert " "the operator to weighted paulis.") ret_op = op_converter.to_weighted_pauli_operator(operator) return ret_op
def test_hf_value(self, mapping): 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') qmolecule = driver.run() core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=mapping, two_qubit_reduction=False, freeze_core=False, orbital_reduction=[]) qubit_op, _ = core.run(qmolecule) qubit_op = op_converter.to_matrix_operator(qubit_op) hf = HartreeFock(qubit_op.num_qubits, core.molecule_info['num_orbitals'], core.molecule_info['num_particles'], mapping.value, False) qc = hf.construct_circuit('vector') hf_energy = qubit_op.evaluate_with_statevector( qc)[0].real + core._nuclear_repulsion_energy self.assertAlmostEqual(qmolecule.hf_energy, hf_energy, places=8)
def test_to_weighted_pauli_operator(self): """ to weighted pauli operator """ mat_op = op_converter.to_matrix_operator(self.pauli_op) pauli_op = op_converter.to_weighted_pauli_operator(mat_op) pauli_op.rounding(8) self.pauli_op.rounding(8) self.assertEqual(pauli_op, self.pauli_op)
def output_dressed_ham(self): i = 0 term_sums = [0] * 4**self.num_qubits sum_term = self.zero_term other_sum_term = self.zero_term for term in self.ham_term_list: for descendant in term['descendants']: weight, pauli, name = split_into_paulis(descendant) term_sums[int(base_4_map( name[0]))] = np.real(term_sums[int(base_4_map( name[0]))]) + np.real(weight[0] * self.constants[i]) other_sum_term = other_sum_term + np.real( weight[0] * self.constants[i]) * pauli[0] i = i + 1 for i, entry in enumerate(term_sums): if abs(entry) > 0.000001: pauli_num = quaternary(i) pauli_name = create_term(pauli_num, self.num_qubits) pauli = Pauli.from_label(pauli_name) wpauli = WeightedPauliOperator.from_list(paulis=[pauli]) sum_term = entry * wpauli + sum_term print(sum_term.print_details()) mat = to_matrix_operator(sum_term) print(mat.print_details()) #mat_2 = to_matrix_operator(other_sum_term) #print(mat_2.print_details()) print(term_sums)
def lih(dist=1.5): mol = PySCFDriver(atom= 'H 0.0 0.0 0.0;'\ 'Li 0.0 0.0 {}'.format(dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto-3g') mol = mol.run() freeze_list = [0] remove_list = [-3, -2] repulsion_energy = mol.nuclear_repulsion_energy num_particles = mol.num_alpha + mol.num_beta num_spin_orbitals = mol.num_orbitals * 2 remove_list = [x % mol.num_orbitals for x in remove_list] freeze_list = [x % mol.num_orbitals for x in freeze_list] remove_list = [x - len(freeze_list) for x in remove_list] remove_list += [ x + mol.num_orbitals - len(freeze_list) for x in remove_list ] freeze_list += [x + mol.num_orbitals for x in freeze_list] ferOp = FermionicOperator(h1=mol.one_body_integrals, h2=mol.two_body_integrals) ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list) num_spin_orbitals -= len(freeze_list) num_particles -= len(freeze_list) ferOp = ferOp.fermion_mode_elimination(remove_list) num_spin_orbitals -= len(remove_list) qubitOp = ferOp.mapping(map_type='parity', threshold=0.00000001) qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) shift = energy_shift + repulsion_energy cHam = op_converter.to_matrix_operator(qubitOp) cHam = cHam.dense_matrix + shift * numpy.identity(16) return cHam
def _run(self): evo_time = 1 # get the groundtruth via simple matrix * vector state_out_exact = op_converter.to_matrix_operator( self._operator).evolve( self._initial_state.construct_circuit('vector'), evo_time, None, 0) qr = QuantumRegister(self._operator.num_qubits, name='q') circuit = self._initial_state.construct_circuit('circuit', qr) circuit += self._operator.evolve(None, evo_time, None, 1, quantum_registers=qr, expansion_mode='suzuki', expansion_order=self._expansion_order) result = self._quantum_instance.execute(circuit) state_out_dynamics = np.asarray(result.get_statevector(circuit)) self._ret['score'] = state_fidelity(state_out_exact, state_out_dynamics) return self._ret
def operator(self, operator: BaseOperator) -> None: """ set operator """ self._in_operator = operator if operator is None: self._operator = None else: self._operator = op_converter.to_matrix_operator(operator) self._check_set_k()
def aux_operators(self, aux_operators: List[BaseOperator]) -> None: """ set aux operators """ self._in_aux_operators = aux_operators if aux_operators is None: self._aux_operators = [] else: aux_operators = \ [aux_operators] if not isinstance(aux_operators, list) else aux_operators self._aux_operators = \ [op_converter.to_matrix_operator(aux_op) for aux_op in aux_operators]
def test_evolve(self, expansion_mode, evo_time, num_time_slices): expansion_orders = [1, 2, 3, 4] if expansion_mode == 'suzuki' else [1] num_qubits = 2 paulis = [ Pauli.from_label(pauli_label) for pauli_label in itertools.product('IXYZ', repeat=num_qubits) ] weights = np.random.random(len(paulis)) pauli_op = WeightedPauliOperator.from_list(paulis, weights) matrix_op = op_converter.to_matrix_operator(pauli_op) state_in = Custom(num_qubits, state='random') # get the exact state_out from raw matrix multiplication state_out_exact = matrix_op.evolve( state_in=state_in.construct_circuit('vector'), evo_time=evo_time, num_time_slices=0) # self.log.debug('exact:\n{}'.format(state_out_exact)) self.log.debug('Under {} expansion mode:'.format(expansion_mode)) for expansion_order in expansion_orders: # assure every time the operator from the original one if expansion_mode == 'suzuki': self.log.debug( 'With expansion order {}:'.format(expansion_order)) state_out_matrix = matrix_op.evolve( state_in=state_in.construct_circuit('vector'), evo_time=evo_time, num_time_slices=num_time_slices, expansion_mode=expansion_mode, expansion_order=expansion_order) quantum_registers = QuantumRegister(pauli_op.num_qubits, name='q') qc = QuantumCircuit(quantum_registers) qc += state_in.construct_circuit('circuit', quantum_registers) qc += pauli_op.copy().evolve( evo_time=evo_time, num_time_slices=num_time_slices, quantum_registers=quantum_registers, expansion_mode=expansion_mode, expansion_order=expansion_order, ) state_out_circuit = self.quantum_instance_statevector.execute( qc).get_statevector(qc) self.log.debug( 'The fidelity between exact and matrix: {}'.format( state_fidelity(state_out_exact, state_out_matrix))) self.log.debug( 'The fidelity between exact and circuit: {}'.format( state_fidelity(state_out_exact, state_out_circuit))) f_mc = state_fidelity(state_out_matrix, state_out_circuit) self.log.debug( 'The fidelity between matrix and circuit: {}'.format(f_mc)) self.assertAlmostEqual(f_mc, 1)
def cost_operator_to_vec(C, offset=0): """Takes Qiskit WeightedPauliOperator representing the NxN cost Hamiltonian and converts it into a vector of length N of just the diagonal elements. Verifies that C is real and diagonal. """ C_mat = to_matrix_operator(C) m = C_mat.dense_matrix m_diag = np.zeros(m.shape[0]) assert (m.shape[0] == m.shape[1]) for i in range(m.shape[0]): for j in range(m.shape[1]): if i != j: assert (np.real(m[i][j]) == 0 and np.imag(m[i][j]) == 0) else: assert (np.imag(m[i][j]) == 0) m_diag[i] = np.real(m[i][j]) return m_diag + offset
def h2(dist=0.75): mol = PySCFDriver(atom= 'H 0.0 0.0 0.0;'\ 'H 0.0 0.0 {}'.format(dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto-3g') mol = mol.run() h1 = mol.one_body_integrals h2 = mol.two_body_integrals nuclear_repulsion_energy = mol.nuclear_repulsion_energy num_particles = mol.num_alpha + mol.num_beta + 0 ferOp = FermionicOperator(h1=h1, h2=h2) qubitOp = ferOp.mapping(map_type='parity', threshold=0.00000001) qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) cHam = op_converter.to_matrix_operator(qubitOp) cHam = cHam.dense_matrix + nuclear_repulsion_energy * numpy.identity(4) return cHam
def test_to_matrix_operator(self): """ to matrix operator """ pauli_op = op_converter.to_weighted_pauli_operator(self.mat_op) mat_op = op_converter.to_matrix_operator(pauli_op) diff = float(np.sum(np.abs(self.mat_op.matrix - mat_op.matrix))) self.assertAlmostEqual(0, diff, places=8)