def sample(self, shots=None, vis=False): """ Sample final optimized circuit for output. Args: shots: No. of samples to take. vis: Boolean value. Displays histogram if set to True. Return: Bitstring for output with max measurement counts and the average expectation value. """ # Resolve defaults if shots is None: shots = self.num_shots # Sample maximum cost value circ = self.variational_ckt.bind_parameters({self.beta: self.beta_val, self.gamma: self.gamma_val}) result = execute(circ, self.backend, shots=shots).result() counts = result.get_counts() # Display data if asked if vis: fig = plt.figure() ax = fig.add_subplot(1, 1, 1) plt.subplots_adjust(left=0.15, right=0.85, top=0.9, bottom=0.25) plot_histogram(counts, title='Sample Output', bar_labels=False, ax=ax) # Return optimized selection avg_cost = sum([self.cost_function(z)*count for z, count in counts.items()]) / self.num_shots return max(counts, key=counts.get), avg_cost
def plot_results2(self, tab, data): axes = tab.figure.add_subplot(111) axes.clear() plot_histogram(data, ax=axes) # for tick in axes.get_xticklabels(): # tick.set_rotation(0) tab.canvas.draw()
def run(params, show=False): results = execute(qc, backend=BasicAer.get_backend('qasm_simulator'), parameter_binds=[{ thetaX: params[0], rhoX: params[1], rhoZ: params[2], thetaZ: 0 }], shots=1024).result() answer = results.get_counts() Jx = answer.get("11", 0) - answer.get("00", 0) if show: plot_histogram(answer) plt.show() results = execute(qc, backend=BasicAer.get_backend('qasm_simulator'), parameter_binds=[{ thetaX: params[0], rhoX: params[1], rhoZ: params[2], thetaZ: pi / 2 }], shots=1024).result() answer = results.get_counts() Jy2 = (n * 1024 + answer.get("11", 0) + answer.get("00", 0) - answer.get("01", 0) - answer.get("10", 0)) / 4 xi = n * Jy2 / (Jx**2 + 1e-09) if show: plot_histogram(answer) plt.show() return xi
def get_noise(prob_1, prob_2, qc): # Error probabilities # prob_1 = 0.001 # 1-qubit gate # prob_2 = 0.01 # 2-qubit gate # Depolarizing quantum errors error_1 = noise.depolarizing_error(prob_1, 1) error_2 = noise.depolarizing_error(prob_2, 2) # Add errors to noise model noise_model = noise.NoiseModel() noise_model.add_all_qubit_quantum_error(error_1, ['u1', 'u2', 'u3']) noise_model.add_all_qubit_quantum_error(error_2, ['cx']) # Get basis gates from noise model basis_gates = noise_model.basis_gates # Make a circuit # Perform a noise simulation new_result = execute(qc, Aer.get_backend('qasm_simulator'), basis_gates=basis_gates, noise_model=noise_model).result() if np.empty_like(new_result) == 0: new_counts = new_result.get_counts(0) plot_histogram(new_counts) return [noise_model, new_counts] else: return noise_model
def plot(): axes = tab.figure.add_subplot(111) axes.clear() plot_histogram(test.result.get_counts(test.circuit), ax=axes) tab.canvas.draw() tab.canvas.print_png( 'c:\\Users\\grig_\\PycharmProjects\\untitled\\lastTest.png')
def main(): circuit = QuantumCircuit(2, 2) circuit.u2(0, math.pi, 0) circuit.cx(0, 1) circuit.measure_all() circuit2 = QuantumCircuit(2, 2) circuit2.h(0) circuit2.cx(0, 1) circuit2.measure_all() print("Available QuaC backends:") print(Quac.backends()) simulator = Quac.get_backend('generic_counts_simulator', n_qubits=2, max_shots=10000, max_exp=75, basis_gates=['u1', 'u2', 'u3', 'cx']) # generic backends require extra parameters # Noise model with T1, T2, and measurement error terms noise_model = QuacNoiseModel( [1000, 1000], [50000, 50000], [np.eye(2), np.array([[0.95, 0.1], [0.05, 0.9]])], None ) # Execute the circuit on the QuaC simulator job = execute([circuit, circuit2], simulator, shots=1000, quac_noise_model=noise_model) print(job.result()) print(job.result().get_counts()) plot_histogram(job.result().get_counts(), title="Bell States Example") plt.show()
def run(): circuitManager = qct.CircuitManager(2, measures=['PreMeasure'], qMeasures=["Qubit A", "Qubit B"]) circuit = circuitManager.circuit circuit.h(0) circuitManager.measure(0, 'PreMeasure') circuit.cx(0, 1) circuit.h(0) circuit.h(1) circuitManager.measureAll(barrier=True) circuitManager.simulate(AerSimulator(), 1000) # Draw the circuit fig = pyplot.figure() plta = fig.add_subplot(2, 1, 1) circuit.draw(output='mpl', ax=plta) pyplot.get_current_fig_manager().set_window_title('Circuit') circuitManager.printEntanglementTable() circuitManager.printEntanglements() pltb = fig.add_subplot(2, 1, 2) vs.plot_histogram(circuitManager.counts, ax=pltb) pyplot.show()
def solve_maxcut_qaoa(graph): print("initialized backend") # operator, offset = get_operator(graph) # print("initialized operator") # # qaoa = QAOA(operator, p=1, optimizer=L_BFGS_B(maxfun=1000)) # print("running the experinment") # result = qaoa.run(backend) # print("got the results") qc = get_quantum_circuit(graph, [1.9], [2]) simulator = get_compute_backend("simulation") backend = get_compute_backend( "quantum") # currently set to IBMQ melbourne 16 qubit meas_job = execute(qc, simulator, shots=100000) result_sim = meas_job.result() counts_sim = result_sim.get_counts() quantum_job = execute(qc, backend) job_monitor(quantum_job) quantum_result = quantum_job.result() counts_quantum = quantum_result.get_counts() plot_histogram([counts_sim, counts_quantum], legend=["simulator", "quantum_hardware"]) return counts_quantum
def print_results(test_name, result, transpile_time, trials, n, b): print() print() print('===================================') print() print('Test:', test_name) print('Transpile time:', transpile_time, 'sec') print('Run time:', result.time_taken, 'sec') print() print('===================================') print('===================================') print() counts = result.get_counts(circuit) counts_sorted = sorted(counts.items(), key=lambda item: item[1], reverse=True) for idx, (key, value) in enumerate(counts_sorted): print('===================================') print() print('Result', idx + 1) print('Frequency:', counts[key]) print() print('a is', key) print('b is', b) print() print('===================================') print() print() plot_histogram(counts, title='Test: ' + test_name) plt.savefig('bernstein_vazirani_hist_%s_{:%Y-%m-%d_%H-%M-%S}.png'.format( datetime.datetime.now()) % test_name)
def run(gates): qc = QuantumCircuit(len(gates), len(gates)) maxLen = len(max(gates, key=len)) for j in range(maxLen): for (i, qubit) in enumerate(gates): if j < len(qubit): if qubit[j] == 'H': qc.h(i) elif qubit[j] == 'X': qc.x(i) elif qubit[j] == 'Y': qc.y(i) elif qubit[j] == 'Z': qc.z(i) elif qubit[j] == 'M': qc.measure([i], [i]) backend = BasicAer.get_backend('qasm_simulator') result = execute(qc, backend, shots=1000).result() counts = result.get_counts(qc) plot_histogram(counts) plt.savefig('temp.png') plt.close() with open('temp.png', 'rb') as image_file: encoded = base64.encodebytes(image_file.read()) return encoded
def state_draw(state): dict = {} state = list(state) tmp = int(math.log(len(state), 2)) for i in range(len(state)): dict[str(bin(i)[2:].zfill(tmp))] = 1000 * np.abs(state[i])**2 plot_histogram(dict).savefig("state_prb.png")
def real_circuit(): """Run a smaller circuit on a real computer""" # This circuit is smaller so we can run it at IBM main = QuantumRegister(1, 'main') counting = QuantumRegister(2, 'counting') classical = ClassicalRegister(10, 'classical') circ = QuantumCircuit(main, counting, classical) phase_estimation(circ, main, counting, classical) circ.draw('mpl') plt.savefig('simple_schematic.png') return IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() backend = ibmq.least_busy( provider.backends( filters=lambda b: b.configuration().n_qubits >= 3 and not b. configuration().simulator and b.status().operational == True)) job = execute(circ, backend=backend, shots=8000) result = job.result() with open('results.pkl', 'wb') as f: pickle.dumps(result) plot_histogram(result.get_counts()) plt.show()
def state_draw(state): state_dict = {} state = list(state) n_qubits = int(math.log(len(state), 2)) for i in range(len(state)): state_dict[bin(i)[2:].zfill(n_qubits)[::-1]] = 1000 * np.abs( state[i])**2 plot_histogram(state_dict).savefig("state_prb.png")
def plot_from_csv(path, N, a): filename = path + N + '_' + str(a) + '.csv' with open(filename, newline='') as f: reader = csv.reader(f) data = dict(list(reader)) # print(data) plot_histogram( data, figsize=(10, 10), title=f'N={N} a={a} result(Nor)').savefig(path + f'/{N}_{a}_res.png')
def executeAndPlot(cir, backend): print(cir.draw(output="text")) job = execute(cir, backend=backend, shots=1024) job_monitor(job) results = job.result() plot_histogram( results.get_counts(cir)) # histogram of results from simulation plt.show() plt.close()
def assign_state(): qc = QuantumCircuit(1) # Problem 1: Create a state vector that will give a 1/3 probability of measuring |0> q = [1j / sqrt(3), -sqrt(6) / 3] qc.initialize(q, 0) result = execute(qc, backend).result() plot_histogram(result.get_counts()) plt.show()
def simulate_and_show_result(qc, title="", circle_title=""): result = simulate(qc).get_counts() circuit_drawer(qc, output='mpl') plt.title(circle_title) # qc.draw(output='mpl', title = "labas") # print(result) plot_histogram(result, title=title) plt.show() return result
def print_results(test_name, circuit_size, results, meas_filter, transpile_time, trials, n, b): print() print() print('===================================') print() print('Test:', test_name) print('Transpile time:', transpile_time, 'sec') print('Number of gates in transpiled circuit:', circuit_size) print('Run time:', sum([result.time_taken for result in results]) / trials, 'sec') print() print('===================================') print('===================================') print() # Compute counts and error-mitigated counts counts = {} mitigated_counts = {} for result in results: c = result.get_counts() mitigated_results = meas_filter.apply(result) mc = mitigated_results.get_counts(0) counts = { key: counts.get(key, 0) + c.get(key, 0) for key in set(counts) | set(c) } mitigated_counts = { key: mitigated_counts.get(key, 0) + mc.get(key, 0) for key in set(mitigated_counts) | set(mc) } counts_sorted = sorted(counts.items(), key=lambda item: item[1], reverse=True) for idx, (key, value) in enumerate(counts_sorted): print('===================================') print() print('Result', idx + 1) print('Frequency:', counts[key]) print('Mitigated frequency:', mitigated_counts[key]) print() print('a is', key) print('b is', b) print() print('===================================') print() print() plot_histogram([counts, mitigated_counts], title=test_name, legend=['raw', 'mitigated']) plt.axhline(1 / (2**n), color='k', linestyle='dashed', linewidth=1) plt.savefig('bernstein_vazirani_hist_%s_{:%Y-%m-%d_%H-%M-%S}.png'.format( datetime.datetime.now()) % test_name)
def run_quantum_job(backend: BaseBackend, circuit: QuantumCircuit): shots = 1024 job = execute(circuit, backend=backend, shots=shots, optimization_level=3) job_monitor(job, interval=2) # Get the results of the computation results = job.result() answer = results.get_counts() plot_histogram(answer).show()
def save_histogram(counts): """ This function simply saves a history in the working directory with the name "histogram.png" of some given counts """ # Save histogram plot_histogram(counts, title="Results", figsize=(9, 12)).savefig("histogram.png")
def schrodinger_with_Z_gates_experiment(): pi_val = np.pi/2 qc = schrodinger_circle_with_Z_gates(pi_val) qc.draw(output='mpl') # plt.show() counts = tools.simulate(qc).get_counts() print(counts) plot_histogram(counts, title="Šredingerio lygties būsenos, su Z vartų keitiniu, kai $\Phi = \\frac{\pi}{2}$ ") plt.show()
def superpos_cnot_prob(): qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.measure(1, 1) backend = q.Aer.get_backend('qasm_simulator') results = q.execute(qc, backend).result().get_counts() plot_histogram(results) plt.show()
def simple_xor_circuit_evaluate(n0, n1): print(f"evaluating binary number {n1}{n0}") qc = simple_xor_circuit(n0, n1) for j in range(2): qc.measure(j, j) counts = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=256).result().get_counts() plot_histogram(counts) plt.show()
def controlerd_t_gate(): qc.h(0) qc.cu1(0, 1) qc.measure(0, 0) qc.measure(1, 1) backend = q.Aer.get_backend('qasm_simulator') results = q.execute(qc, backend).result().get_counts() plot_histogram(results) plt.show()
def basic_qubit_initialization(): # instantiate 1 qubit qc = QuantumCircuit(1) # by default, the execute method runs and polls the circuit 1,024 times result = execute(qc, backend).result() # the default state should be |0>, or [1, 0] plot_histogram(result.get_counts()) # calling plt.show() is necessary for me plt.show()
def schrodinger_inverse_gates_experiment(): pi_val = np.pi / 2 qc = schrodinger_circle_inverse_gates(pi_val, measure=True) qc.draw(output='mpl') # plt.show() counts = tools.simulate(qc).get_counts() print(counts) plot_histogram(counts, title="Grįžtamos sistemos būsenos") plt.show()
def add(n0, n1): qc = add_circuit(n0, n1) qc.measure(2, 0) qc.measure(3, 1) counts = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=256).result().get_counts() qc.draw(output="mpl") plot_histogram(counts) plt.show()
def simulate(qc): simulator = Aer.get_backend('aer_simulator') qc = transpile(qc, simulator) # Run and get counts result = simulator.run(qc).result() counts = result.get_counts(qc) plot_histogram(counts, title='Bell-State counts', number_to_keep=len(counts)) return counts
def print_results(test_name, circuit_size, results, meas_filter, transpile_time, trials, n, b): print() print() print('===================================') print() print('Test:', test_name) print('Transpile time:', transpile_time, 'sec') print('Number of gates in transpiled circuit:', circuit_size) print('Run time:', sum([result.time_taken for result in results]) / trials, 'sec') print() print('===================================') print('===================================') print() # Compute counts and error-mitigated counts counts = {} mitigated_counts = {} for result in results: c = result.get_counts() mitigated_results = meas_filter.apply(result) mc = mitigated_results.get_counts(0) counts = {key: counts.get(key, 0) + c.get(key, 0) for key in set(counts) | set(c)} mitigated_counts = {key: mitigated_counts.get(key, 0) + mc.get(key, 0) for key in set(mitigated_counts) | set(mc)} counts_sorted = sorted(counts.items(), key=lambda item: item[1], reverse=True) for idx, (key, value) in enumerate(counts_sorted): verdict = 'Constant!' print('===================================') print() print('Result', idx + 1) print('Frequency:', counts[key]) print('Mitigated frequency:', mitigated_counts[key]) # Constant function if measure all 0's, balanced otherwise for i in range(n): if key[i] != '0': verdict = 'Balanced!' break print('Measurement:', key) print('Function is:', verdict) print() print() print('===================================') print() print() plot_histogram([counts, mitigated_counts], title=test_name, legend=['raw', 'mitigated']) plt.axhline(1/(2 ** n), color='k', linestyle='dashed', linewidth=1) plt.savefig('deutsch_jozsa_hist_%s_%d_{:%Y-%m-%d_%H-%M-%S}.png'.format(datetime.datetime.now()) % (test_name, trials), bbox_inches = "tight")
def print_real(cls, job: BaseJob, algorithm: str): results = job.result() answer = results.get_counts() print("\nTotal counts are:", answer) elapsed = results.time_taken print( f"The time it took for the experiment to complete after validation was {elapsed} seconds" ) plot_histogram(data=answer, title=f"{constants.algorithms[int(algorithm)]}") plt.show() return