Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_results_save_load(self):
"""Test saving and loading the results of a circuit.
Test for the 'unitary_simulator_py' and 'qasm_simulator'
"""
metadata = {'testval': 5}
qr = qiskit.QuantumRegister(2)
cr = qiskit.QuantumRegister(2)
qc1 = qiskit.QuantumCircuit(qr, cr, name='qc1')
qc2 = qiskit.QuantumCircuit(qr, cr, name='qc2')
qc1.h(qr)
qc2.cx(qr[0], qr[1])
circuits = [qc1, qc2]
result1 = execute(circuits, backend=Aer.get_backend('unitary_simulator_py')).result()
result2 = execute(circuits, backend=Aer.get_backend('qasm_simulator_py')).result()
test_1_path = self._get_resource_path('test_save_load1.json')
test_2_path = self._get_resource_path('test_save_load2.json')
# delete these files if they exist
if os.path.exists(test_1_path):
os.remove(test_1_path)
if os.path.exists(test_2_path):
os.remove(test_2_path)
file1 = file_io.save_result_to_file(result1, test_1_path, metadata=metadata)
file2 = file_io.save_result_to_file(result2, test_2_path, metadata=metadata)
_, metadata_loaded1 = file_io.load_result_from_file(file1)
def test_execute_in_aer(self):
"""Test executing a circuit in an Aer simulator"""
qr = qiskit.QuantumRegister(1)
cr = qiskit.ClassicalRegister(1)
circuit = qiskit.QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr, cr)
backend = qiskit.Aer.get_backend('qasm_simulator')
shots = 2000
results = qiskit.execute(circuit, backend, shots=shots).result()
self.assertDictAlmostEqual({'0': 1000, '1': 1000},
results.get_counts(),
delta=100)
def test_evaluate_with_aer_mode(self):
""" evaluate with aer mode test """
try:
from qiskit import Aer
except Exception as ex: # pylint: disable=broad-except
self.skipTest("Aer doesn't appear to be installed. Error: '{}'".format(str(ex)))
return
statevector_simulator = Aer.get_backend('statevector_simulator')
quantum_instance_statevector = QuantumInstance(statevector_simulator, shots=1)
wave_function = self.var_form.construct_circuit(
np.array(aqua_globals.random.randn(self.var_form.num_parameters)))
circuits = self.qubit_op.construct_evaluation_circuit(wave_function=wave_function,
statevector_mode=True)
reference = self.qubit_op.evaluate_with_result(
result=quantum_instance_statevector.execute(circuits), statevector_mode=True)
circuits = self.qubit_op.construct_evaluation_circuit(
wave_function=wave_function, statevector_mode=True, use_simulator_operator_mode=True)
extra_args = {
'expectation': {
'params': [self.qubit_op.aer_paulis],
'num_qubits': self.qubit_op.num_qubits}
def test_truncate_disable(self):
"""Test explicitly disabling truncation with noise model option"""
circuit = self.create_circuit_for_truncate()
qasm_sim = Aer.get_backend('qasm_simulator')
backend_options = self.BACKEND_OPTS.copy()
backend_options["truncate_verbose"] = True
backend_options["truncate_enable"] = False
backend_options['optimize_ideal_threshold'] = 1
backend_options['optimize_noise_threshold'] = 1
result = execute(circuit,
qasm_sim,
noise_model=basic_device_noise_model(self.device_properties()),
shots=100,
coupling_map=[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9, 0]], # 10-qubit device
backend_options=backend_options).result()
self.assertFalse('truncate_qubits' in result.to_dict()['results'][0]['metadata'], msg="truncate_qubits must not work.")
def test_w_noise(self):
""" with noise test """
# build noise model
# Asymetric readout error on qubit-0 only
try:
from qiskit.providers.aer.noise import NoiseModel
from qiskit import Aer
self.backend = Aer.get_backend('qasm_simulator')
except Exception as ex: # pylint: disable=broad-except
self.skipTest("Aer doesn't appear to be installed. Error: '{}'".format(str(ex)))
return
os.environ.pop('QISKIT_AQUA_CIRCUIT_CACHE', None)
probs_given0 = [0.9, 0.1]
probs_given1 = [0.3, 0.7]
noise_model = NoiseModel()
noise_model.add_readout_error([probs_given0, probs_given1], [0])
quantum_instance = QuantumInstance(self.backend, seed_transpiler=self.random_seed,
seed_simulator=self.random_seed, shots=1024,
noise_model=noise_model,
circuit_caching=False)
res_w_noise = quantum_instance.execute(self.qc).get_counts(self.qc)
def test_vqe_statevector_snapshot_mode(self):
""" VQE Aer statevector_simulator snapshot mode test """
try:
# pylint: disable=import-outside-toplevel
from qiskit import Aer
except Exception as ex: # pylint: disable=broad-except
self.skipTest("Aer doesn't appear to be installed. Error: '{}'".format(str(ex)))
return
backend = Aer.get_backend('statevector_simulator')
num_qubits = self.qubit_op.num_qubits
init_state = Zero(num_qubits)
var_form = RY(num_qubits, 3, initial_state=init_state)
optimizer = L_BFGS_B()
algo = VQE(self.qubit_op, var_form, optimizer, max_evals_grouped=1)
quantum_instance = QuantumInstance(backend,
seed_simulator=aqua_globals.random_seed,
seed_transpiler=aqua_globals.random_seed)
result = algo.run(quantum_instance)
self.assertAlmostEqual(result['energy'], -1.85727503, places=6)
num_of_gates = (np.linspace(1, 30, 10)).astype(int)
gate_time = 0.11
qubits = [0]
n_echos = 5
alt_phase_echo = True
circs, xdata = t2_circuits(num_of_gates, gate_time, qubits,
n_echos, alt_phase_echo)
expected_t2 = 20
error = thermal_relaxation_error(np.inf, expected_t2, gate_time, 0.5)
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error, 'id')
# TODO: Include SPAM errors
backend = qiskit.Aer.get_backend('qasm_simulator')
shots = 100
backend_result = qiskit.execute(
circs, backend,
shots=shots,
seed_simulator=SEED,
backend_options={'max_parallel_experiments': 0},
noise_model=noise_model,
optimization_level=0).result()
initial_t2 = expected_t2
initial_a = 1
initial_c = 0.5*(-1)
T2Fitter(backend_result, xdata, qubits,
fit_p0=[initial_a, initial_t2, initial_c],
fit_bounds=([0, 0, -1], [2, expected_t2*1.2, 1]))
def run(self, ket: State = None) -> State:
circ = self._circuit
if ket is not None:
circ = Circuit(Initialize(ket)) + circ
qkcircuit = circuit_to_qiskit(circ, translate=True)
simulator = qiskit.Aer.get_backend('statevector_simulator')
job = qiskit.execute(qkcircuit, simulator)
result = job.result()
tensor = result.get_statevector()
res = State(tensor, list(reversed(self.qubits)))
if ket is not None:
res = res.permute(ket.qubits)
return res