def execute(self, circuits): """ A wrapper for all algorithms to interface with quantum backend. Args: circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute Returns: Result or [Result]: Result objects it will be a list if number of circuits exceed the maximum number (300) """ if not isinstance(circuits, list): circuits = [circuits] jobs = [] chunks = int(np.ceil(len(circuits) / self.MAX_CIRCUITS_PER_JOB)) for i in range(chunks): sub_circuits = circuits[i * self.MAX_CIRCUITS_PER_JOB:(i + 1) * self.MAX_CIRCUITS_PER_JOB] jobs.append( q_execute(sub_circuits, self._backend, **self._execute_config)) results = [] for job in jobs: results.append(job.result(**self._qjob_config)) if len(jobs) == 1: results = results[0] return results
def test_cnx(self, num_controls, num_ancillae): c = QuantumRegister(num_controls, name='c') o = QuantumRegister(1, name='o') a = QuantumRegister(num_ancillae, name='a') qc = QuantumCircuit(o, c, a) allsubsets = list( chain(*[ combinations(range(num_controls), ni) for ni in range(num_controls + 1) ])) for subset in allsubsets: for idx in subset: qc.x(c[idx]) qc.cnx([c[i] for i in range(num_controls)], [a[i] for i in range(num_ancillae)], o[0]) for idx in subset: qc.x(c[idx]) # print(qc.qasm()) vec = np.asarray( q_execute( qc, 'local_statevector_simulator').result().get_statevector( qc)) vec_o = [0, 1] if len(subset) == num_controls else [1, 0] np.testing.assert_almost_equal( vec, np.array(vec_o + [0] * (2**(num_controls + num_ancillae + 1) - 2)))
def execute(self, circuits): """ A wrapper for all algorithms to interface with quantum backend. Args: circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute Returns: Result or [Result]: Result objects it will be a list if number of circuits exceed the maximum number (300) """ if not isinstance(circuits, list): circuits = [circuits] jobs = [] chunks = int(np.ceil(len(circuits) / self.MAX_CIRCUITS_PER_JOB)) for i in range(chunks): sub_circuits = circuits[i * self.MAX_CIRCUITS_PER_JOB:(i + 1) * self.MAX_CIRCUITS_PER_JOB] jobs.append( q_execute(sub_circuits, self._backend, **self._execute_config)) if logger.isEnabledFor(logging.DEBUG): logger.debug(summarize_circuits(circuits)) results = [] for job in jobs: results.append(job.result(**self._qjob_config)) result = functools.reduce(lambda x, y: x + y, results) return result
def execute(self, circuits): """ A wrapper for all algorithms to interface with quantum backend. Args: circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute """ job = q_execute(circuits, self._backend, **self._execute_config) result = job.result(**self._qjob_config) return result
def test_sat_oracle(self, cnf_str, sols): num_shots = 1024 sat = SAT() sat.init_args(cnf_str) sat_circuit = sat.construct_circuit() m = ClassicalRegister(1, name='m') for assignment in itertools.product([True, False], repeat=len(sat.variable_register())): qc = QuantumCircuit(m, sat.variable_register()) for idx, tf in enumerate(assignment): if tf: qc.x(sat.variable_register()[idx]) qc += sat_circuit qc.measure(sat._qr_outcome, m) counts = q_execute(qc, 'local_qasm_simulator', shots=num_shots).result().get_counts(qc) if assignment in sols: assert(counts['1'] == num_shots) else: assert(counts['0'] == num_shots)
def test_evolution(self): SIZE = 2 #SPARSITY = 0 #X = [[0, 1], [1, 0]] #Y = [[0, -1j], [1j, 0]] Z = [[1, 0], [0, -1]] I = [[1, 0], [0, 1]] h1 = np.kron(I, Z) # + 0.5 * np.kron(Y, X)# + 0.3 * np.kron(Z, X) + 0.4 * np.kron(Z, Y) # np.random.seed(2) temp = np.random.random((2 ** SIZE, 2 ** SIZE)) h1 = temp + temp.T qubitOp = Operator(matrix=h1) # qubitOp_jw.chop_by_threshold(10 ** -10) # self.log.debug('matrix:\n{}\n'.format(qubitOp.matrix)) # self.log.debug('paulis:') # self.log.debug(qubitOp.print_operators('paulis')) if qubitOp.grouped_paulis is None: qubitOp._matrix_to_paulis() qubitOp._paulis_to_grouped_paulis() for ps in qubitOp.grouped_paulis: for p1 in ps: for p2 in ps: if p1 != p2: diff = p1[1].to_matrix() @ p2[1].to_matrix() - p2[1].to_matrix() @ p1[1].to_matrix() if diff.any(): raise RuntimeError('Paulis within the same group do not commute!') flattened_grouped_paulis = [pauli for group in qubitOp.grouped_paulis for pauli in group[1:]] if sorted([str(p) for p in flattened_grouped_paulis]) != sorted([str(p) for p in qubitOp.paulis]): raise RuntimeError('grouped_paulis and paulis do not match!') state_in = get_initial_state_instance('CUSTOM') state_in.init_args(SIZE, state='random') evo_time = 1 num_time_slices = 1 # announces params self.log.debug('evo time: {}'.format(evo_time)) self.log.debug('num time slices: {}'.format(num_time_slices)) self.log.debug('state_in: {}'.format(state_in._state_vector)) # get the exact state_out from raw matrix multiplication state_out_exact = qubitOp.evolve(state_in.construct_circuit('vector'), evo_time, 'matrix', 0) # self.log.debug('exact:\n{}'.format(state_out_exact)) for grouping in ['default', 'random']: self.log.debug('Under {} paulis grouping:'.format(grouping)) for expansion_mode in ['trotter', 'suzuki']: self.log.debug('Under {} expansion mode:'.format(expansion_mode)) for expansion_order in [1, 2, 3, 4] if expansion_mode == 'suzuki' else [1]: if expansion_mode == 'suzuki': self.log.debug('With expansion order {}:'.format(expansion_order)) state_out_matrix = qubitOp.evolve( state_in.construct_circuit('vector'), evo_time, 'matrix', num_time_slices, paulis_grouping=grouping, expansion_mode=expansion_mode, expansion_order=expansion_order ) quantum_registers = QuantumRegister(qubitOp.num_qubits) qc = state_in.construct_circuit('circuit', quantum_registers) qc += qubitOp.evolve( None, evo_time, 'circuit', num_time_slices, quantum_registers=quantum_registers, paulis_grouping=grouping, expansion_mode=expansion_mode, expansion_order=expansion_order ) job = q_execute(qc, 'local_statevector_simulator') state_out_circuit = np.asarray(job.result().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)