def noise_model_depolarizing(error, measure=True, thermal=True): """ Creates error for depolarizing channel :param error: Probability of depolarizing channel :param measure: True or False, whether we include readout errors with probability 10 * error :param thermal: True or False, whether we include thermal relaxation, see noise_model_thermal :return: noise model for the error """ noise_model = NoiseModel() depolarizing = depolarizing_error(error, 1) cdepol_error = depolarizing_error(2 * error, 2) noise_model.add_all_qubit_quantum_error(cdepol_error, ['cx'], warnings=False) noise_model.add_all_qubit_quantum_error(depolarizing, ["u1", "u2", "u3"]) if measure: measure_error = 10 * error measure_error = array([[1 - measure_error, measure_error], [measure_error, 1 - measure_error]]) noise_model.add_all_qubit_readout_error(measure_error) if thermal: thermal = thermal_relaxation_error(1.5, 1.2, error) cthermal = thermal_relaxation_error(1.5, 1.2, 2 * error) cthermal = cthermal.tensor(cthermal) noise_model.add_all_qubit_quantum_error(cthermal, ['cx'], warnings=False) noise_model.add_all_qubit_quantum_error(thermal, ["u1", "u2", "u3"], warnings=False) return noise_model
def setUp(self): """Setup the tests.""" super().setUp() # depolarizing error self.p1q = 0.02 self.p2q = 0.10 self.pvz = 0.0 # basis gates self.basis_gates = ["sx", "rz", "cx"] # setup noise model sx_error = depolarizing_error(self.p1q, 1) rz_error = depolarizing_error(self.pvz, 1) cx_error = depolarizing_error(self.p2q, 2) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(sx_error, "sx") noise_model.add_all_qubit_quantum_error(rz_error, "rz") noise_model.add_all_qubit_quantum_error(cx_error, "cx") self.noise_model = noise_model # Need level1 for consecutive gate cancellation for reference EPC value calculation self.transpiler_options = { "basis_gates": self.basis_gates, "optimization_level": 1, } # Aer simulator self.backend = AerSimulator(noise_model=noise_model, seed_simulator=123)
def setUp(self): """Setup the tests.""" super().setUp() # Setup noise model, including more gate for complicated EPG computation # Note that 1Q channel error is amplified to check 1q channel correction mechanism x_error = depolarizing_error(0.04, 1) h_error = depolarizing_error(0.02, 1) s_error = depolarizing_error(0.00, 1) cx_error = depolarizing_error(0.08, 2) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(x_error, "x") noise_model.add_all_qubit_quantum_error(h_error, "h") noise_model.add_all_qubit_quantum_error(s_error, "s") noise_model.add_all_qubit_quantum_error(cx_error, "cx") # Need level1 for consecutive gate cancellation for reference EPC value calculation transpiler_options = { "basis_gates": ["x", "h", "s", "cx"], "optimization_level": 1, } # Aer simulator backend = AerSimulator(noise_model=noise_model, seed_simulator=123) # Prepare experiment data and cache for analysis exp_1qrb_q0 = rb.StandardRB( qubits=(0, ), lengths=[1, 10, 30, 50, 80, 120, 150, 200], seed=123, backend=backend, ) exp_1qrb_q0.set_transpile_options(**transpiler_options) expdata_1qrb_q0 = exp_1qrb_q0.run(analysis=None).block_for_results( timeout=300) exp_1qrb_q1 = rb.StandardRB( qubits=(1, ), lengths=[1, 10, 30, 50, 80, 120, 150, 200], seed=123, backend=backend, ) exp_1qrb_q1.set_transpile_options(**transpiler_options) expdata_1qrb_q1 = exp_1qrb_q1.run(analysis=None).block_for_results( timeout=300) exp_2qrb = rb.StandardRB( qubits=(0, 1), lengths=[1, 3, 5, 10, 15, 20, 30, 50], seed=123, backend=backend, ) exp_2qrb.set_transpile_options(**transpiler_options) expdata_2qrb = exp_2qrb.run(analysis=None).block_for_results( timeout=300) self.expdata_1qrb_q0 = expdata_1qrb_q0 self.expdata_1qrb_q1 = expdata_1qrb_q1 self.expdata_2qrb = expdata_2qrb
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 noisy_model(prob_one, prob_two): # Depolarizing quantum errors error_1 = noise.depolarizing_error(prob_one, 1) error_2 = noise.depolarizing_error(prob_two, 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']) basis_gates = noise_model.basis_gates return (noise_model, basis_gates)
def depolarizing_noise(n_qubits,p1,p2): # Depolarizing quantum errors error_1 = depolarizing_error(p1, 1) error_2 = depolarizing_error(p2, 2) # Add errors to noise model noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error_1, ['u1', 'u2', 'u3']) noise_model.add_all_qubit_quantum_error(error_2, ['cx']) return noise_model
def get_data_point(circ, theta, phi, lam, readout_params, depol_param, thermal_params, shots): """Generate a dict datapoint with the given circuit and noise parameters""" U3_gate_length = 7.111111111111112e-08 # extract parameters (p0_0, p1_0), (p0_1, p1_1) = readout_params depol_prob = depol_param t1, t2, population = thermal_params # Add Readout and Quantum Errors noise_model = NoiseModel() noise_model.add_all_qubit_readout_error(ReadoutError(readout_params)) noise_model.add_all_qubit_quantum_error(depolarizing_error(depol_param, 1), 'u3', warnings=False) noise_model.add_all_qubit_quantum_error( thermal_relaxation_error(t1, t2, U3_gate_length, excited_state_population=population), 'u3', warnings=False) job = execute(circ, QasmSimulator(), shots=shots, noise_model=noise_model) result = job.result() # add data point to DataFrame data_point = {'theta': theta, 'phi': phi, 'lam': lam, 'p0_0': p0_0, 'p1_0': p1_0, 'p0_1': p0_1, 'p1_1': p1_1, 'depol_prob': depol_prob, 't1': t1, 't2': t2, 'population': population, 'E': result.get_counts(0).get('1', 0) / shots} return data_point
def test_save_qiskit_noise_model(self): # Given noise_model = AerNoise.NoiseModel() quantum_error = AerNoise.depolarizing_error(0.0, 1) coherent_error = np.asarray([ np.asarray( [0.87758256 - 0.47942554j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j]), np.asarray( [0.0 + 0.0j, 0.87758256 + 0.47942554j, 0.0 + 0.0j, 0.0 + 0.0j]), np.asarray( [0.0 + 0.0j, 0.0 + 0.0j, 0.87758256 + 0.47942554j, 0.0 + 0.0j]), np.asarray( [0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.87758256 - 0.47942554j]), ]) noise_model.add_quantum_error( AerNoise.coherent_unitary_error(coherent_error), ["cx"], [0, 1]) filename = "noise_model.json" # When save_qiskit_noise_model(noise_model, filename) # Then with open("noise_model.json", "r") as f: data = json.loads(f.read()) self.assertEqual(data["module_name"], "qeqiskit.utils") self.assertEqual(data["function_name"], "load_qiskit_noise_model") self.assertIsInstance(data["data"], dict) # Cleanup subprocess.run(["rm", "noise_model.json"])
def depolarizing(backend, p=0.001): if backend.name() == 'qasm_simulator': qubit1 = p / 10 qubit2 = p error_qubit1 = noise.depolarizing_error(qubit1, 1) error_qubit2 = noise.depolarizing_error(qubit2, 2) noise_model.add_all_qubit_quantum_error(error_qubit1, qasm_1qubit_gates) noise_model.add_all_qubit_quantum_error(error_qubit2, qasm_2qubit_gates) else: print('SimulationError: Invalid option for noisy simulator') sys.exit() return noise_model
def test_empty_circuit_noise(self, method, device): """Test simulation with empty circuit and noise model.""" backend = self.backend(method=method, device=device) noise_model = noise.NoiseModel() noise_model.add_all_qubit_quantum_error(noise.depolarizing_error(0.1, 1), ['x']) result = backend.run( QuantumCircuit(), shots=1, noise_model=noise_model).result() self.assertSuccess(result)
def __get_counts(self, params: List[float or int], shots: int = 1000) -> dict: """ Here we run the circuit according to the given parameters for each gate and return the counts for each state. :param params: List of the parameters of the RY and RX gates of the circuit. :param shots: Total number of shots the circuit must execute """ # 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']) 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 circ = QuantumCircuit(2, 2) # Set gates and measurement circ.ry(params[0], 0) circ.rx(params[1], 1) circ.cx(0, 1) circ.measure([0, 1], [0, 1]) # Perform a noisy simulation and get the counts # noinspection PyTypeChecker result = execute(circ, Aer.get_backend('qasm_simulator'), basis_gates=basis_gates, noise_model=noise_model, shots=shots).result() counts = result.get_counts(0) return counts
def generateDepolarizingError(machine, gate, qubits): """ Return a depolarizing error """ try: gate_error = machine.properties().gate_error(gate, qubits) error = depolarizing_error(gate_error, len(qubits)) return error except: return None
def run_simulation(self, shots=8192, error_prob=0, target_state='0'): # add noise error_1 = noise.depolarizing_error(error_prob, 1) noise_model = noise.NoiseModel() noise_model.add_all_qubit_quantum_error(error_1, ['x', 'z']) # run simulation self.qc.measure(0, 0) emulator = Aer.get_backend('qasm_simulator') job = execute(self.qc, emulator, noise_model=noise_model, shots=shots) hist = job.result().get_counts() print(hist)
def build_noise_model(noise_rates, multiplier): noise_model = NoiseModel( basis_gates=['cx', 'id', 'reset', 'rz', 'sx', 'x']) gate_errors = {x[0]: x[1] * multiplier for x in noise_rates.items()} for gate in noise_rates: #Depolarizing error on CX if gate == 'cx': depol_err_cx = depolarizing_error(noise_rates[gate] * multiplier, 2) noise_model.add_all_qubit_quantum_error(depol_err_cx, ['cx']) #Depolarizing error on single qubit gates else: depol_err = depolarizing_error(noise_rates[gate] * multiplier, 1, standard_gates=False) noise_model.add_all_qubit_quantum_error(depol_err, [gate]) #Save error rates with open("gate_errors_{}.json".format(multiplier), "w") as f: json.dump(gate_errors, f) return noise_model
def make_noise_model(dep_err_rate, ro_err_rate, qubits): # Define a noise model that applies uniformly to the given qubits model = NoiseModel() dep_err = depolarizing_error(dep_err_rate, 2) ro_err = ReadoutError( [[1 - ro_err_rate, ro_err_rate], [ro_err_rate, 1 - ro_err_rate]] ) # Add depolarising error to CX gates between any qubits (implying full connectivity) for i, j in product(qubits, repeat=2): model.add_quantum_error(dep_err, ["cx"], [i, j]) # Add readout error for each qubit for i in qubits: model.add_readout_error(ro_err, qubits=[i]) return model
def U3Dataset(angle_step=9, probability_step=10, shots=1024, save_dir=None): # define constants basis_gates = ['u3'] simulator = QasmSimulator() df = pd.DataFrame() # generate circuits for theta, phi, lam in tqdm( itertools.product(np.linspace(0, np.pi, angle_step, endpoint=True), repeat=3)): # define circuit circ = QuantumCircuit(1, 1) gate = U3Gate(theta, phi, lam) circ.append(gate, [0]) circ.measure(0, 0) new_circ = qiskit.compiler.transpile(circ, basis_gates=basis_gates, optimization_level=0) print(new_circ) # generate noise models: for probability in np.linspace(0, 1, probability_step, endpoint=True): # add noise noise_model = NoiseModel() error = depolarizing_error(probability, 1) noise_model.add_all_qubit_quantum_error(error, ['x', 'u1', 'u2', 'u3']) # execution - Noisy job = execute(new_circ, simulator, shots=shots, noise_model=noise_model) result = job.result() # add to Pandas DF data = { 'theta': theta, 'phi': phi, 'lam': lam, 'p': probability, 'E': result.get_counts(0).get('0', 0) / shots } df = df.append(data, ignore_index=True) df = df[['theta', 'phi', 'lam', 'E', 'p']] if save_dir is not None: df.to_csv(save_dir) return df
def get_data_point(theta, phi, lam, readout_params, depol_param, thermal_params, shots): """Generate a dict datapoint with the given circuit and noise parameters""" U3_gate_length = 7.111111111111112e-08 circ = QuantumCircuit(1, 1) circ.append(U3Gate(theta, phi, lam), [0]) circ.measure(0, 0) new_circ = qiskit.compiler.transpile(circ, basis_gates=['u3'], optimization_level=0) # extract parameters (p0_0, p1_0), (p0_1, p1_1) = readout_params depol_prob = depol_param t1, t2, population = thermal_params noise_model = NoiseModel() # Add Readout and Quantum Errors noise_model.add_all_qubit_readout_error(ReadoutError(readout_params)) noise_model.add_all_qubit_quantum_error(depolarizing_error(depol_param, 1), 'u3', warnings=False) noise_model.add_all_qubit_quantum_error(thermal_relaxation_error( t1, t2, U3_gate_length, population), 'u3', warnings=False) job = execute(circ, QasmSimulator(), shots=shots, noise_model=noise_model) result = job.result() # add data point to DataFrame data_point = { 'theta': theta, 'phi': phi, 'lam': lam, 'p0_0': p0_0, 'p1_0': p1_0, 'p0_1': p0_1, 'p1_1': p1_1, 'depol_prob': depol_prob, 't1': t1, 't2': t2, 'population': population, 'E': result.get_counts(0).get('0', 0) / shots } return data_point
def _xtalk_errors(noise_model, xtalk_prop): for qubits, xtalks in xtalk_prop.items(): for noise_qubits, xtalkratio in xtalks.items(): prob = backend.properties().gate_error('cx', noise_qubits) xtalk_prob = prob * xtalkratio error = noise.depolarizing_error( xtalk_prob, 2) # defined as depolarizing error but fix it later nm.add_nonlocal_quantum_error( error=error, instructions='cx', qubits=list(qubits), noise_qubits=list(noise_qubits), ) return nm
def RXDataset(angle_step=10, probability_step=10, shots=1024, save_dir=None): # define constants basis_gates = ['u3'] simulator = QasmSimulator() df = pd.DataFrame() # generate circuits for angle in np.linspace(0, np.pi, angle_step, endpoint=True): # define circuit circ = QuantumCircuit(1, 1) rotate = RXGate(angle) circ.append(rotate, [0]) circ.measure(0, 0) new_circ = qiskit.compiler.transpile(circ, basis_gates=basis_gates, optimization_level=0) print(new_circ) # generate noise models: for probability in np.linspace(0, 1, probability_step, endpoint=True): # add noise noise_model = NoiseModel() error = depolarizing_error(probability, 1) noise_model.add_all_qubit_quantum_error(error, ['x', 'u1', 'u2', 'u3']) # execution - Noisy job = execute(new_circ, simulator, shots=shots, noise_model=noise_model) result = job.result() # add to Pandas DF data = { 'rx_theta': angle, 'p': probability, 'E': result.get_counts(0).get('0', 0) / shots } df = df.append(data, ignore_index=True) df = df[['rx_theta', 'E', 'p']] df.to_csv(save_dir + "/dataframe_RX.csv") return df
def test_batch_transpile_options_integrated(self): """ The goal is to verify that not only `_trasnpiled_circuits` works well (`test_batch_transpiled_circuits` takes care of it) but that it's correctly called within the entire flow of `BaseExperiment.run`. """ backend = Aer.get_backend("aer_simulator") noise_model = noise.NoiseModel() noise_model.add_all_qubit_quantum_error( noise.depolarizing_error(0.5, 2), ["cx", "swap"]) expdata = self.batch2.run(backend, noise_model=noise_model, shots=1000) expdata.block_for_results() self.assertEqual(expdata.child_data(0).analysis_results(0).value, 8) self.assertEqual( expdata.child_data(1).child_data(0).analysis_results(0).value, 16) self.assertEqual( expdata.child_data(1).child_data(1).analysis_results(0).value, 4)
def run_simulation(self, shots=8192, error_prob=0, target_state='000'): # add noise error_1 = noise.depolarizing_error(error_prob, 1) noise_model = noise.NoiseModel() noise_model.add_all_qubit_quantum_error(error_1, ['x', 'z']) # run simulation self.qc.measure([0, 1, 2], [4, 3, 2]) emulator = Aer.get_backend('qasm_simulator') job = execute(self.qc, emulator, noise_model=noise_model, shots=shots) hist = job.result().get_counts() # print(hist) # print statistics successes = 0 first_three = [n[0:3] for n in list(hist.keys())] for i in range(len(first_three)): if (first_three[i] == target_state): successes += hist.get(list(hist.keys())[i]) # print("success rate:", successes/shots) return successes / shots
def create_quantum_computer_simulation(couplingmap, depolarizingnoise=False, depolarizingnoiseparameter=0, bitfliperror=False, bitfliperrorparameter=0, measerror=False, measerrorparameter=0): """ Returns a dictionary, where the key is what type of simulation ("noisy_qasm", "noiseless_qasm", "real"), and the value are the objects required for that particular simulation """ sims = ["noisy_qasm", "noiseless_qasm"] dicto = dict() for sim in sims: if sim == "noiseless_qasm": backend = Aer.get_backend('qasm_simulator') dicto[sim] = backend elif sim == "noisy_qasm": backend = Aer.get_backend('qasm_simulator') coupling_map = CouplingMap(couplingmap) noise_model = NoiseModel() if depolarizingnoise == True: depolarizingerror = depolarizing_error( depolarizingnoiseparameter, 1) noise_model.add_all_qubit_quantum_error( depolarizingerror, ['u1', 'u2', 'u3']) if bitfliperror == True: error_gate1 = pauli_error([('X', bitfliperrorparameter), ('I', 1 - bitfliperrorparameter)]) noise_model.add_all_qubit_quantum_error( error_gate1, ["u1", "u2", "u3"]) error_gate2 = error_gate1.tensor(error_gate1) noise_model.add_all_qubit_quantum_error(error_gate2, ["cx"]) if measerror == True: error_meas = pauli_error([('X', measerrorparameter), ('I', 1 - measerrorparameter)]) noise_model.add_all_qubit_quantum_error(error_meas, "measure") dicto[sim] = (backend, coupling_map, noise_model) return dicto
def test_noise_model_io_using_core_functions(self): # Given noise_model = AerNoise.NoiseModel() quantum_error = AerNoise.depolarizing_error(0.0, 1) coherent_error = np.asarray([ np.asarray( [0.87758256 - 0.47942554j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j]), np.asarray( [0.0 + 0.0j, 0.87758256 + 0.47942554j, 0.0 + 0.0j, 0.0 + 0.0j]), np.asarray( [0.0 + 0.0j, 0.0 + 0.0j, 0.87758256 + 0.47942554j, 0.0 + 0.0j]), np.asarray( [0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.87758256 - 0.47942554j]), ]) noise_model.add_quantum_error( AerNoise.coherent_unitary_error(coherent_error), ["cx"], [0, 1]) noise_model_data = noise_model.to_dict(serializable=True) module_name = "qeqiskit.utils" function_name = "load_qiskit_noise_model" filename = "noise_model.json" # When save_noise_model(noise_model_data, module_name, function_name, filename) new_noise_model = load_noise_model(filename) # Then self.assertEqual( noise_model.to_dict(serializable=True), new_noise_model.to_dict(serializable=True), ) # Cleanup subprocess.run(["rm", "noise_model.json"])
def randbin3(data, F, theta_sphere, phi_sphere=0): # simulator --- WORKS prob_1 = 0.3 error_1 = noise.depolarizing_error(prob_1, 1) noise_model = noise.NoiseModel() noise_model.add_all_qubit_quantum_error(error_1, ['u3']) basis_gates = noise_model.basis_gates phi = data.const * F * data.t * data.F_degree q = QuantumRegister(1) c = ClassicalRegister(1) # Create a Quantum Circuit acting on the q register circuit = QuantumCircuit(q, c) rotate_angle = math.pi - 2*phi circuit.u3(theta_sphere, phi_sphere, 0, q) circuit.rz(2*phi, q) circuit.h(q) # Map the quantum measurement to the classical bits circuit.measure(q, c) # Execute the circuit on the qasm simulator job = execute(circuit, Aer.get_backend('qasm_simulator'), basis_gates=basis_gates, noise_model=noise_model, shots=1) #job_monitor(job) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(circuit) return int(list(counts.keys())[0])
grover_optimizer = GroverOptimizer(6, num_iterations=10, quantum_instance=backend) results = grover_optimizer.solve(qp) print("x={}".format(results.x)) print("fval={}".format(results.fval)) # Adding extra backends to target is nice, but where `pytket` really shines is in its compiler passes. The ability to exploit a large number of sources of redundancy in the circuit structure to reduce the execution cost on a noisy device is paramount in the NISQ era. We can examine the effects of this by looking at how effectively the algorithm works on the `qasm_simulator` from Qiskit Aer with a given noise model. # # (Note: some versions of `qiskit-aqua` give an `AssertionError` when the `solve()` step below is run. If you encounter this, try updating `qiskit-aqua` or, as a workaround, reducing the number of iterations to 2.) from qiskit.providers.aer import Aer from qiskit.providers.aer.noise import NoiseModel, depolarizing_error from qiskit.aqua import QuantumInstance backend = Aer.get_backend("qasm_simulator") model = NoiseModel() model.add_all_qubit_quantum_error(depolarizing_error(0.01, 1), ["p", "u"]) model.add_all_qubit_quantum_error(depolarizing_error(0.05, 2), ["cx"]) qi = QuantumInstance(backend, noise_model=model, seed_transpiler=2, seed_simulator=2) grover_optimizer = GroverOptimizer(6, num_iterations=10, quantum_instance=qi) results = grover_optimizer.solve(qp) print("x={}".format(results.x)) print("fval={}".format(results.fval)) print("n_circs={}".format(len(results.operation_counts))) # We can insert compilation passes from `pytket` into Qiskit as `TranspilerPass`es, compose with others to form a `PassManager`, and embed into the `QuantumInstance`. from pytket.passes import FullPeepholeOptimise from pytket.extensions.qiskit.tket_pass import TketPass from qiskit.transpiler import PassManager
from qiskit import QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram, circuit_drawer import qiskit.providers.aer.noise as noise import matplotlib.pyplot as plt # 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 circ = QuantumCircuit(3, 3) circ.h(0) circ.cx(0, 1) circ.cx(1, 2) circ.measure([0, 1, 2], [0, 1, 2]) # Perform a noise simulation result = execute( circ,
meshgridfirstlastparams = objend(X, Y) return meshgridfirststartparams #, meshgridfirstlastparams if __name__ == "__main__": import multiprocessing Noise_Modelling = False Shots_Modelling = True TEST_G = gnp_random_connected_graph(6, 0.2, 42) if Noise_Modelling: noise_args = np.linspace(0, 0.15, 15) Noise_Models = [noise.NoiseModel() for i in range(10)] for noise_arg, noisemodel in zip(noise_args, Noise_Models): noisemodel.add_all_qubit_quantum_error( noise.depolarizing_error(noise_arg, 1), ['u1', 'u2', 'u3']) args = [(TEST_G, 3, 5000, noisemodel) for noisemodel in Noise_Models] OUTPUT_ARR = np.zeros((len(Noise_Models), grid_size, grid_size)) elif Shots_Modelling: shots_arr = np.arange(5, 101, 1) args = [(TEST_G, 4, i, None) for i in shots_arr] OUTPUT_ARR = np.zeros((len(shots_arr), grid_size, grid_size)) with multiprocessing.Pool(multiprocessing.cpu_count() - 2) as p: results = p.starmap(qaoa_maxcut_grid_noise, args) for idx, result in enumerate(results): OUTPUT_ARR[idx] = result np.save("./datafiles/meshgridsnoisy.npy", OUTPUT_ARR) if Noise_Modelling else np.save( "./datafiles/meshgridshots.npy", OUTPUT_ARR)
def depolarizing_noise(p): noise_model = NoiseModel() error = depolarizing_error(p, num_qubits=1) noise_model.add_all_qubit_quantum_error(error, 'noise') noise_model.add_basis_gates(['unitary']) return noise_model
def __init__(self, name = 'simulator_benchmark', apps = {}, qubits = DEFAULT_QUBITS, runtime_names = DEFAULT_RUNTIME, measures = DEFAULT_MEASUREMENT_METHODS, measure_counts = DEFAULT_MEASUREMENT_COUNTS, noise_model_names = DEFAULT_NOISE_MODELS, fusion_bits = DEFAULT_FUSION_BITS, fusion = DEFAULT_FUSION, save_qasm = False, save_conf = False): self.timeout = 60 * 1000 self.__name__ = name self.apps = apps if isinstance(apps, list) else [app for app in apps] self.app2rep = {} if isinstance(apps, list) else apps self.qubits = qubits self.runtime_names = runtime_names self.measures = measures self.measure_counts = measure_counts self.noise_model_names = noise_model_names self.fusion_bits = fusion_bits self.fusion = fusion self.save_qasm = save_qasm self.save_conf = save_conf self.params = (self.apps, self.measures, self.measure_counts, self.noise_model_names, self.qubits) self.param_names = ["application", "measure_method", "measure_counts", "noise", "qubit"] all_simulators = [ QASM_SIMULATOR ] self.simulators = {} self.backend_options_list = {} self.backend_qubits = {} self.noise_models = {} self.noise_models[self.NOISE_IDEAL] = None if self.NOISE_DAMPING in self.noise_model_names: noise_model = NoiseModel() error = amplitude_damping_error(1e-3) noise_model.add_all_qubit_quantum_error(error, ['u3']) self.noise_models[self.NOISE_DAMPING] = noise_model if self.NOISE_DEPOLARIZING in self.noise_model_names: noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(depolarizing_error(1e-3, 1), ['u3']) noise_model.add_all_qubit_quantum_error(depolarizing_error(1e-2, 2), ['cx']) self.noise_models[self.NOISE_DEPOLARIZING] = noise_model if self.RUNTIME_STATEVECTOR_CPU in runtime_names: self.simulators[self.RUNTIME_STATEVECTOR_CPU] = QASM_SIMULATOR self.backend_options_list[self.RUNTIME_STATEVECTOR_CPU] = { 'method': self.RUNTIME_STATEVECTOR_CPU, 'fusion_max_qubit': self.fusion_bits, 'fusion_threshold': 0, 'fusion_enable': self.fusion } self.backend_qubits[self.RUNTIME_STATEVECTOR_CPU] = self.qubits if self.RUNTIME_STATEVECTOR_GPU in runtime_names: self.simulators[self.RUNTIME_STATEVECTOR_GPU] = QASM_SIMULATOR self.backend_options_list[self.RUNTIME_STATEVECTOR_GPU] = { 'method': self.RUNTIME_STATEVECTOR_GPU, 'fusion_max_qubit': self.fusion_bits, 'fusion_threshold': 0, 'fusion_enable': self.fusion, 'max_memory_mb': 307200 } self.backend_qubits[self.RUNTIME_STATEVECTOR_GPU] = self.qubits if self.RUNTIME_MPS_CPU in runtime_names: self.simulators[self.RUNTIME_MPS_CPU] = QASM_SIMULATOR self.backend_options_list[self.RUNTIME_MPS_CPU] = { 'method': self.RUNTIME_MPS_CPU } self.backend_qubits[self.RUNTIME_MPS_CPU] = self.qubits if self.RUNTIME_DENSITY_MATRIX_CPU in runtime_names: self.simulators[self.RUNTIME_DENSITY_MATRIX_CPU] = QASM_SIMULATOR self.backend_options_list[self.RUNTIME_DENSITY_MATRIX_CPU] = { 'method': self.RUNTIME_DENSITY_MATRIX_CPU } self.backend_qubits[self.RUNTIME_DENSITY_MATRIX_CPU] = [qubit for qubit in qubits if qubit <= 15] if self.RUNTIME_DENSITY_MATRIX_GPU in runtime_names: self.simulators[self.RUNTIME_DENSITY_MATRIX_GPU] = QASM_SIMULATOR self.backend_options_list[self.RUNTIME_DENSITY_MATRIX_GPU] = { 'method': self.RUNTIME_DENSITY_MATRIX_GPU } self.backend_qubits[self.RUNTIME_DENSITY_MATRIX_GPU] = [qubit for qubit in qubits if qubit <= 15]
GRAPH = gnp_random_connected_graph(4,0.2,42) args = [("roto", GRAPH, 3, False, shots, False) for shots in shot_arr] results = pool.starmap(qaoa_maxcut, args) pool.close() pool.join() for idx, result in enumerate(results): OUTPUT_ARR[idx] = result[1] np.save("./datafiles/shotsmaxcutroto2.npy", OUTPUT_ARR) if NOISE_TEST: noise_arr = np.linspace(0.001,0.3,100) OUTPUT_ARR = np.zeros((len(noise_arr), NUM_STEPS+1)) GRAPH = gnp_random_connected_graph(8,0.3,42) NOISE_MODELS = [noise.NoiseModel() for i in range(len(noise_arr))] for NoiseModel, NoiseStrength in zip(NOISE_MODELS, noise_arr): NoiseModel.add_all_qubit_quantum_error(noise.depolarizing_error(NoiseStrength,1), ['u1','u2','u3']) args = [("adam", GRAPH, 6, False, None, False, NoiseModel) for NoiseModel in NOISE_MODELS] results = pool.starmap(qaoa_maxcut, args) pool.close() pool.join() for idx, result in enumerate(results): OUTPUT_ARR[idx] = result[1] np.save("./datafiles/depolnoise1qubitadam.npy", OUTPUT_ARR) # %% ''' Old code ''' ''' (sequential train)