def mapping(self, map_type, threshold=0.00000001): 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') pauli_list = WeightedPauliOperator(paulis=[]) for h in self._hs: results = parallel_map(FermionicOperatorNBody._n_body_mapping, [FermionicOperatorNBody._prep_mapping(h[indexes],a_list,indexes) for indexes in list(itertools.product(range(n), repeat=len(h.shape))) if h[indexes] != 0], num_processes=aqua_globals.num_processes) # for indexes in list(itertools.product(range(n), repeat=len(h.shape))): # h_a = [h[indexes]] # for i in indexes: # h_a.append(a_list[i]) 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_equal_operator(self): """ equal operator 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] op1 = WeightedPauliOperator.from_list(paulis, coeffs) coeffs = [0.2, 0.6, 0.8, -0.2, -0.6, -0.8] op2 = WeightedPauliOperator.from_list(paulis, coeffs) coeffs = [-0.2, -0.6, -0.8, 0.2, 0.6, 0.8] op3 = WeightedPauliOperator.from_list(paulis, coeffs) coeffs = [-0.2, 0.6, 0.8, -0.2, -0.6, -0.8] op4 = WeightedPauliOperator.from_list(paulis, coeffs) self.assertEqual(op1, op2) self.assertNotEqual(op1, op3) self.assertNotEqual(op1, op4) self.assertNotEqual(op3, op4)
def setUp(self): super().setUp() self.seed = 0 aqua_globals.random_seed = self.seed 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"} ] } self.qubit_op = WeightedPauliOperator.from_dict(pauli_dict)
def get_exact_cover_qubitops(list_of_subsets): """Construct the Hamiltonian for the exact solver problem. Notes: Assumption: the union of the subsets contains all the elements to cover. The Hamiltonian is: sum_{each element e}{(1-sum_{every subset_i that contains e}{Xi})^2}, where Xi (Xi=1 or 0) means whether should include the subset i. Args: list_of_subsets: list of lists (i.e., subsets) Returns: WeightedPauliOperator: operator for the Hamiltonian float: a constant shift for the obj function. """ n = len(list_of_subsets) U = [] for sub in list_of_subsets: U.extend(sub) U = np.unique(U) # U is the universe shift = 0 pauli_list = [] for e in U: cond = [True if e in sub else False for sub in list_of_subsets] indices_has_e = np.arange(n)[cond] num_has_e = len(indices_has_e) Y = 1-0.5*num_has_e shift += Y*Y for i in indices_has_e: for j in indices_has_e: if i != j: wp = np.zeros(n) vp = np.zeros(n) vp[i] = 1 vp[j] = 1 pauli_list.append([0.25, Pauli(vp, wp)]) else: shift += 0.25 for i in indices_has_e: wp = np.zeros(n) vp = np.zeros(n) vp[i] = 1 pauli_list.append([-Y, Pauli(vp, wp)]) return WeightedPauliOperator(paulis=pauli_list), shift
def test_evolve(self, expansion_mode, evo_time, num_time_slices): """ evolve test """ 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 = aqua_globals.random.random_sample(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%s', state_out_exact) self.log.debug('Under %s expansion mode:', 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 %s:', 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: %s', state_fidelity(state_out_exact, state_out_matrix)) self.log.debug('The fidelity between exact and circuit: %s', 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: %s', f_mc) self.assertAlmostEqual(f_mc, 1)
def spin_operator(num_qubits): pauli_list = [] for i in range(num_qubits): if i < num_qubits: c = 1 / 2 else: c = -1 / 2 a_z = np.asarray([0] * i + [1] + [0] * (num_qubits - i - 1), dtype=np.bool) a_x = np.asarray([0] * i + [0] + [0] * (num_qubits - i - 1), dtype=np.bool) pauli_list.append([c, Pauli(a_z, a_x)]) op = WeightedPauliOperator(pauli_list) return op
def retrieve_op_list(number, rev = False, num_qubits = 4): adapt_op_df = pd.read_csv('load_adapt_roto_2_op_df.csv') adapt_op_dict = adapt_op_df.to_dict() op_label_list = list(adapt_op_dict['Ham_{}'.format(number)]) op_list = [] for label in op_label_list: op_name = adapt_op_dict['Ham_{}'.format(number)][label] print(op_name) op = Pauli.from_label(op_name[:num_qubits]) op = WeightedPauliOperator.from_list([op]) op_list.append(op) if rev: return reverse(op_list) return op_list
def hamiltonian_operator: """ Creates the Hamilton for which we want to estimate the least eigenvalue. """ pauli_dict = { 'paulis': [{"coeff": {"imag": 0.0, "real": -0.5}, "label": "II"}, {"coeff": {"imag": 0.0, "real": -0.5}, "label": "ZZ"}, {"coeff": {"imag": 0.0, "real": 0.5}, "label": "XX"}, {"coeff": {"imag": 0.0, "real": 0.5}, "label": "YY"} ] } return WeightedPauliOperator.from_dict(pauli_dict)
def test_instruction() -> None: # TKET-446 qreg = QuantumRegister(3) paulis = list(map(Pauli.from_label, ["XXI", "YYI", "ZZZ"])) weights = [0.3, 0.5 + 1j * 0.2, -0.4] op = WeightedPauliOperator.from_list(paulis, weights) evolution_circ = op.evolve(None, 1.2, num_time_slices=1, quantum_registers=qreg) tk_circ = qiskit_to_tk(evolution_circ) cmds = tk_circ.get_commands() assert len(cmds) == 1 assert cmds[0].op.type == OpType.CircBox
def setUp(self): super().setUp() self.random_seed = 0 np.random.seed(self.random_seed) 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 = WeightedPauliOperator.from_dict(pauli_dict) self.algo_input = EnergyInput(qubit_op)
def _setup(self, operator: Optional[BaseOperator]) -> None: self._operator = None self._ret = {} self._pauli_list = None self._phase_estimation_circuit = None self._slice_pauli_list = None if operator: self._operator = op_converter.to_weighted_pauli_operator( operator.copy()) self._ret['translation'] = sum( [abs(p[0]) for p in self._operator.reorder_paulis()]) self._ret['stretch'] = 0.5 / self._ret['translation'] # translate the operator self._operator.simplify() translation_op = WeightedPauliOperator([[ self._ret['translation'], Pauli(np.zeros(self._operator.num_qubits), np.zeros(self._operator.num_qubits)) ]]) translation_op.simplify() self._operator += translation_op self._pauli_list = self._operator.reorder_paulis() # stretch the operator for p in self._pauli_list: p[0] = p[0] * self._ret['stretch'] if len(self._pauli_list) == 1: slice_pauli_list = self._pauli_list else: if self._expansion_mode == 'trotter': slice_pauli_list = self._pauli_list else: slice_pauli_list = suzuki_expansion_slice_pauli_list( self._pauli_list, 1, self._expansion_order) self._slice_pauli_list = slice_pauli_list
def retrieve_ham(number, num_qubits = 4): adapt_data_df = pd.read_csv('load_adapt_roto_2_data_df.csv') adapt_data_dict = adapt_data_df.to_dict() Ham_list = adapt_data_dict['hamiltonian'] Ham = Ham_list[number] single_ham_list = Ham.split('\n') pauli_list = [0]*(len(single_ham_list)-1) weight_list = [0]*(len(single_ham_list)-1) for counter2 in range(0, len(single_ham_list)-1,1): pauli_list[counter2] = Pauli.from_label(single_ham_list[counter2][:num_qubits]) weight_list[counter2] = complex(single_ham_list[counter2][num_qubits:]) qubit_op = WeightedPauliOperator.from_list(pauli_list,weight_list) return qubit_op
def _drop_even_y_paulis( operator: WeightedPauliOperator) -> WeightedPauliOperator: new_paulis = [] if len(operator.paulis) > 1: raise ValueError( 'Removal of Pauli strings from operator with more than one term is not supported\n' 'Tried to remove even Y strings from {}'.format( operator.paulis)) for weight, pauli in operator.paulis: if pauli.to_label().count('Y') % 2 == 0: new_weight = 0.0 + 0.j else: new_weight = weight new_paulis.append([new_weight, pauli]) return WeightedPauliOperator(paulis=new_paulis).chop()
def test_qubitop_to_qiskitpauli(): """ Conversion of QubitOperator; accuracy test """ hop_term = FermionOperator(((2, 1), (0, 0))) term = hop_term + hermitian_conjugated(hop_term) pauli_term = jordan_wigner(term) qiskit_op = qubitop_to_qiskitpauli(pauli_term) ground_truth = WeightedPauliOperator([[0.5, Pauli.from_label("XZX")], [0.5, Pauli.from_label("YZY")]]) assert ground_truth == qiskit_op
def x_mixer(n: int, axis: str = 'X'): """Construct the original QAOA mixer. Parameters ---------- n : int Number of qubits. Returns ------- WeightedPauliOperator QAOA Mixer, `X_1+X_2+...`. """ op = WeightedPauliOperator([]) for o in PauliPool.from_pauli_strings(x_strings(n, axis=axis)).pool: op += o return op
def __init__(self, operator: WeightedPauliOperator, timelimit: int = 600, thread: int = 1, display: int = 2) -> None: validate_min('timelimit', timelimit, 1) validate_min('thread', thread, 0) validate_range('display', display, 0, 5) super().__init__() self._ins = IsingInstance() self._ins.parse(operator.to_dict()['paulis']) self._timelimit = timelimit self._thread = thread self._display = display self._sol = None
def __init__(self, cost_operator, p, initial_state=None, mixer_operator=None): """ Constructor, following the QAOA paper https://arxiv.org/abs/1411.4028 Args: cost_operator (WeightedPauliOperator): The operator representing the cost of the optimization problem, denoted as U(B, gamma) in the original paper. p (int): The integer parameter p, which determines the depth of the circuit, as specified in the original paper. initial_state (InitialState, optional): An optional initial state to use. mixer_operator (WeightedPauliOperator, optional): An optional custom mixer operator to use instead of the global X-rotations, denoted as U(B, beta) in the original paper. Raises: TypeError: invalid input """ super().__init__() cost_operator = op_converter.to_weighted_pauli_operator(cost_operator) self._cost_operator = cost_operator self._num_qubits = cost_operator.num_qubits self._p = p self._initial_state = initial_state self._num_parameters = 2 * p self._bounds = [(0, np.pi)] * p + [(0, 2 * np.pi)] * p self._preferred_init_points = [0] * p * 2 # prepare the mixer operator v = np.zeros(self._cost_operator.num_qubits) ws = np.eye(self._cost_operator.num_qubits) if mixer_operator is None: self._mixer_operator = reduce(lambda x, y: x + y, [ WeightedPauliOperator([[1.0, Pauli(v, ws[i, :])]]) for i in range(self._cost_operator.num_qubits) ]) else: if not isinstance(mixer_operator, WeightedPauliOperator): raise TypeError( 'The mixer should be a qiskit.aqua.operators.WeightedPauliOperator ' + 'object, found {} instead'.format(type(mixer_operator))) self._mixer_operator = mixer_operator self.support_parameterized_circuit = True
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.random((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(len(paulis)) self.pauli_op = WeightedPauliOperator.from_list(paulis, weights)
def get_max_independent_set_operator(num_nodes): """ Contructs the cost operator for max independent set 1/2 \sum_i Z_i Args: num_nodes (int): Number of nodes """ pauli_list = [] for i in range(num_nodes): x_p = np.zeros(num_nodes, dtype=np.bool) z_p = np.zeros(num_nodes, dtype=np.bool) z_p[i] = True pauli_list.append([0.5, Pauli(z_p, x_p)]) shift = -num_nodes / 2 return WeightedPauliOperator(paulis=pauli_list), shift
def test_chop_complex(self): """ chop complex test """ 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 test_chop_real(self): """ chop real test """ paulis = [Pauli(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()))
def from_pauli_strings(cls, string_list): """Creates pool from list of given Pauli strings. ``` pool = PauliPool.from_pauli_strings(['IZZ', 'XXY']) ``` """ result = cls() result.name = 'pauli_string_list_{}'.format(string_list) lengths = list(map(len, string_list)) if not all(x == lengths[0] for x in lengths): raise ValueError('All strings should be of equal length') res = [Pauli.from_label(word.upper()) for word in string_list] res = list(map(lambda p: WeightedPauliOperator(paulis=[[1.0, p]]), res)) result.add_ops(res) return result
def get_TFIM_qubit_op( N, B, J=1, pbc=False, resolve_degeneracy=False, ): """ Construct the qubit Hamiltonian for 1d TFIM: H = \sum_{i} ( J Z_i Z_{i+1} + B X_i ) Parameters ---------- N : int The number of spin 1/2 particles in the chain B : float Transverse field strength J : float, optional default 1. Ising interaction strength pbc : boolean, optional default False Set the boundary conditions of the 1d spin chain resolve_degeneracy : boolean, optional default False Lift the ground state degeneracy (when |B*J| < 1) with a small Z field Returns ------- qubitOp : qiskit.aqua.operators.WeightedPauliOperator Qiskit representation of the qubit Hamiltonian """ pauli_terms = [] # ZZ terms pauli_terms += [ (-J,Pauli.from_label('I'*(i)+'ZZ'+'I'*((N-1)-(i+1)))) for i in range(N-1) ] # optional periodic boundary condition term if pbc: pauli_terms += [ (-J,Pauli.from_label('Z'+'I'*(N-2)+'Z')) ] # for B*J<1 the ground state is degenerate, can optionally lift that degeneracy with a # small Z field if resolve_degeneracy: pauli_terms += [ (np.min([J,B])*1E-3,Pauli.from_label('I'*(i)+'Z'+'I'*(N-(i+1)))) for i in range(N) ] # X terms pauli_terms += [ (-B,Pauli.from_label('I'*(i)+'X'+'I'*(N-(i+1)))) for i in range(N) ] qubitOp = WeightedPauliOperator(pauli_terms) return qubitOp
def get_mixing_operator(graph, k): num_nodes = graph.number_of_nodes() num_qubits = num_nodes * k z_p = np.zeros(num_qubits, dtype=np.bool) x_p = np.zeros(num_qubits, dtype=np.bool) operator_list = [] for node in range(num_nodes): for color in range(k): color_next = (color + 1) % k x_p[node * k + color] = True x_p[node * k + color_next] = True operator_list.append([1 / k, Pauli(z_p, x_p)]) x_p[node * k + color_next] = False x_p[node * k + color] = False H_m = WeightedPauliOperator(paulis=operator_list) return H_m
def stabilizers(fer_op): """ stabilizers """ edge_list = bravyi_kitaev_fast_edge_list(fer_op) num_qubits = edge_list.shape[1] graph = networkx.Graph() graph.add_edges_from(tuple(edge_list.transpose())) stabs = np.asarray(networkx.cycle_basis(graph)) stabilizer_ops = [] for stab in stabs: a_op = WeightedPauliOperator(paulis=[[1.0, Pauli.from_label('I' * num_qubits)]]) stab = np.asarray(stab) for i in range(np.size(stab)): a_op = a_op * edge_operator_aij(edge_list, stab[i], stab[(i + 1) % np.size(stab)]) * 1j stabilizer_ops.append(a_op) return stabilizer_ops
def _drop_higher_order_z_strings( operator: WeightedPauliOperator) -> WeightedPauliOperator: new_paulis = [] if len(operator.paulis) > 1: raise ValueError( 'Removal of Pauli strings from operator with more than one term is not supported\n' 'Tried to remove particle number violating strings from {}'. format(operator.paulis)) for weight, pauli in operator.paulis: nontrivial_terms = len( pauli.to_label()) - pauli.to_label().count('I') if pauli.to_label().count('Z') >= 2 and nontrivial_terms > 2: new_weight = 0.0 + 0.j else: new_weight = weight new_paulis.append([new_weight, pauli]) return WeightedPauliOperator(paulis=new_paulis).chop()
def _drop_particle_number_violating_paulis( operator: WeightedPauliOperator) -> WeightedPauliOperator: new_paulis = [] if len(operator.paulis) > 1: raise ValueError( 'Removal of Pauli strings from operator with more than one term is not supported\n' 'Tried to remove particle number violating strings from {}'. format(operator.paulis)) for weight, pauli in operator.paulis: x_terms = pauli.to_label().count('X') y_terms = pauli.to_label().count('Y') if (x_terms + y_terms) % 2 == 1: new_weight = 0.0 + 0.j else: new_weight = weight new_paulis.append([new_weight, pauli]) return WeightedPauliOperator(paulis=new_paulis).chop()
def _three_body_mapping(h3_ijkmpq_a_ijkmpq, threshold): """ Subroutine for three body mapping. We use the chemists notation for the two-body term, h2(i,j,k,m,p,q) adag_i adag_k adag_p a_q a_m a_j . Args: h2_ijkmpq_a_ijkmpq (tuple): value of h3 at index (i,j,k,m,p,q), pauli at index i, pauli at index j, pauli at index k, pauli at index m, pauli at index p, pauli at index q threshold (float): threshold to remove a pauli Returns: WeightedPauliOperator: Operator for those paulis """ h3_ijkmpq, a_i, a_j, a_k, a_m, a_p, a_q = h3_ijkmpq_a_ijkmpq pauli_list = [] for alpha in range(2): for beta in range(2): for gamma in range(2): for delta in range(2): for theta in range(2): for phi 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_p[gamma]) pauli_prod_3 = Pauli.sgn_prod( pauli_prod_2[0], a_q[delta]) pauli_prod_4 = Pauli.sgn_prod( pauli_prod_3[0], a_m[theta]) pauli_prod_5 = Pauli.sgn_prod( pauli_prod_4[0], a_j[phi]) phase1 = pauli_prod_1[1] * pauli_prod_2[1] * pauli_prod_3[1] * \ pauli_prod_4[1] * pauli_prod_5[1] phase2 = np.power(-1j, alpha + beta + gamma) * \ np.power(1j, delta + theta + phi) pauli_term = [ h3_ijkmpq / 64 * phase1 * phase2, pauli_prod_5[0] ] if np.absolute(pauli_term[0]) > threshold: pauli_list.append(pauli_term) return WeightedPauliOperator(paulis=pauli_list)
def get_operator(weight_matrix): r"""Generate Hamiltonian for the graph partitioning Notes: Goals: 1 separate the vertices into two set of the same size 2 make sure the number of edges between the two set is minimized. Hamiltonian: H = H_A + H_B H_A = sum\_{(i,j)\in E}{(1-ZiZj)/2} H_B = (sum_{i}{Zi})^2 = sum_{i}{Zi^2}+sum_{i!=j}{ZiZj} H_A is for achieving goal 2 and H_B is for achieving goal 1. Args: weight_matrix (numpy.ndarray) : adjacency matrix. Returns: WeightedPauliOperator: operator for the Hamiltonian float: a constant shift for the obj function. """ num_nodes = len(weight_matrix) pauli_list = [] shift = 0 for i in range(num_nodes): for j in range(i): if weight_matrix[i, j] != 0: x_p = np.zeros(num_nodes, dtype=np.bool) z_p = np.zeros(num_nodes, dtype=np.bool) z_p[i] = True z_p[j] = True pauli_list.append([-0.5, Pauli(z_p, x_p)]) shift += 0.5 for i in range(num_nodes): for j in range(num_nodes): if i != j: x_p = np.zeros(num_nodes, dtype=np.bool) z_p = np.zeros(num_nodes, dtype=np.bool) z_p[i] = True z_p[j] = True pauli_list.append([1, Pauli(z_p, x_p)]) else: shift += 1 return WeightedPauliOperator(paulis=pauli_list), shift
def _check_commutes(cliffords: List[WeightedPauliOperator], operator: WeightedPauliOperator) -> bool: """ Check commutations Args: cliffords : cliffords operator: qubit operator Returns: Boolean: does_commute """ commutes = [] for clifford in cliffords: commutes.append(operator.commute_with(clifford)) does_commute = np.all(commutes) logger.debug(' \'%s\' commutes: %s, %s', operator.name, does_commute, commutes) return does_commute