Skip to content

Commit

Permalink
Merge pull request #621 from haimeng-zhang/upgrade-to-qiskit-1.2
Browse files Browse the repository at this point in the history
Update to use qiskit-ibm-runtime and qiskit >= 1.2
  • Loading branch information
rtvuser1 authored Sep 30, 2024
2 parents 5c832a8 + 7bb7dcb commit 7b3a9d9
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 20 deletions.
33 changes: 17 additions & 16 deletions _common/qiskit/execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,10 +149,9 @@ def __init__(self, qiskit_result):
def get_counts(self, qc=0):
# counts= self.qiskit_result.quasi_dists[0].binary_probabilities()
# for key in counts.keys():
# counts[key] = int(counts[key] * self.qiskit_result.metadata[0]['shots'])
# counts[key] = int(counts[key] * self.qiskit_result.metadata[0]['shots'])
qc_index = 0 # this should point to the index of the circuit in a pub
register_name = list(self.qiskit_result[qc_index].data.keys())[0]
bitvals = getattr(self.qiskit_result[qc_index].data, register_name)
bitvals = next(iter(self.qiskit_result[qc_index].data.values()))
counts = bitvals.get_counts()
return counts

Expand Down Expand Up @@ -254,6 +253,7 @@ def set_execution_target(backend_id='qasm_simulator',
provider_name='Quantinuum')
"""
global backend
global sampler
global session
global use_sessions
global session_count
Expand Down Expand Up @@ -295,7 +295,11 @@ def set_execution_target(backend_id='qasm_simulator',
# handle Statevector simulator specially
elif backend_id == 'statevector_simulator':
backend = Aer.get_backend("statevector_simulator")


elif backend_id == "statevector_sampler":
from qiskit.primitives import StatevectorSampler
sampler = StatevectorSampler()

# handle 'fake' backends here
elif 'fake' in backend_id:
backend = getattr(
Expand All @@ -310,7 +314,6 @@ def set_execution_target(backend_id='qasm_simulator',
# otherwise use the given providername or backend_id to find the backend
else:
global service
global sampler

# if provider_module name and provider_name are provided, obtain a custom provider
if provider_module_name and provider_name:
Expand Down Expand Up @@ -389,8 +392,8 @@ def set_execution_target(backend_id='qasm_simulator',

# get Sampler resilience level and transpiler optimization level from exec_options
options = Options()
options.resilience_level = exec_options.get("resilience_level", 1)
options.optimization_level = exec_options.get("optimization_level", 3)
# options.resilience_level = exec_options.get("resilience_level", 1)
# options.optimization_level = exec_options.get("optimization_level", 3)

# special handling for ibmq_qasm_simulator to set noise model
if backend_id == "ibmq_qasm_simulator":
Expand Down Expand Up @@ -430,11 +433,10 @@ def set_execution_target(backend_id='qasm_simulator',
from qiskit_ibm_runtime import QiskitRuntimeService, Session, SamplerOptions as Options, SamplerV2 as Sampler

# create the Runtime Service object
service = QiskitRuntimeService(instance=f'{hub}/{group}/{project}')
print(f'setting instance {hub}/{group}/{project}')
service = QiskitRuntimeService()
# obtain a backend from the service
backend = service.backend(backend_id)

# DEVNOTE: here we assume if the sessions flag is set, we use Sampler
# however, we may want to add a use_sampler option so that we can separate these

Expand Down Expand Up @@ -679,7 +681,7 @@ def execute_circuit(circuit):

#************************************************
# Initiate execution (with noise if specified and this is a simulator backend)
if this_noise is not None and not use_sessions and backend_name.endswith("qasm_simulator"):
if this_noise is not None and not sampler and backend_name.endswith("qasm_simulator"):
logger.info(f"Performing noisy simulation, shots = {shots}")

# if the noise model has associated QV value, copy it to metrics module for plotting
Expand Down Expand Up @@ -754,9 +756,9 @@ def execute_circuit(circuit):
logger.info(f'Running trans_qc, shots={shots}')
st = time.time()

if use_sessions:
if sampler:
# turn input into pub-like
job = sampler.run([trans_qc], shots=shots, **backend_exec_options_copy)
job = sampler.run([trans_qc], shots=shots)
else:
job = backend.run(trans_qc, shots=shots, **backend_exec_options_copy)

Expand Down Expand Up @@ -1133,16 +1135,15 @@ def job_complete(job):
# if we are using sessions, structure of result object is different;
# use a BenchmarkResult object to hold session result and provide a get_counts()
# that returns counts to the benchmarks in the same form as without sessions
if use_sessions:
if sampler:
result = BenchmarkResult(result)
#counts = result.get_counts()

# actual_shots = result.metadata[0]['shots']
# get the name of the classical register
# TODO: need to rewrite to allow for submit multiple circuits in one job
register_name = list(result.qiskit_result[0].data.keys())[0]
# get DataBin associated with the classical register
bitvals = getattr(result.qiskit_result[0].data, register_name)
bitvals = next(iter(result.qiskit_result[0].data.values()))
actual_shots = bitvals.num_shots
result_obj = result.metadata # not sure how to update to be V2 compatible
results_obj = result.metadata
Expand Down
4 changes: 2 additions & 2 deletions monte-carlo/qiskit/mc_benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ def square_on_objective(qc, qr):
qc.cx(control, num_state_qubits)

def state_prep(qc, qr, target_dist, num_state_qubits):
"""
r"""
Use controlled Ry gates to construct the superposition Sum \sqrt{p_i} |i>
"""
r_probs = mc_utils.region_probs(target_dist, num_state_qubits)
Expand Down Expand Up @@ -505,7 +505,7 @@ def get_args():
parser.add_argument("--skip_qubits", "-k", default=1, help="Number of qubits to skip", type=int)
parser.add_argument("--max_circuits", "-c", default=3, help="Maximum circuit repetitions", type=int)
parser.add_argument("--method", "-m", default=1, help="Algorithm Method", type=int)
parser.add_argument("--num_state_qubits", "-nsq", default=0.0, help="Number of State Qubits", type=int)
parser.add_argument("--num_state_qubits", "-nsq", default=1, help="Number of State Qubits", type=int)
parser.add_argument("--nonoise", "-non", action="store_true", help="Use Noiseless Simulator")
parser.add_argument("--verbose", "-v", action="store_true", help="Verbose")
return parser.parse_args()
Expand Down
3 changes: 2 additions & 1 deletion quantum-fourier-transform/qiskit/qft_benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,8 @@ def QuantumFourierTransform (num_qubits, secret_int, method=1):

def qft_gate(input_size):
global QFT_, num_gates, depth
qr = QuantumRegister(input_size); qc = QuantumCircuit(qr, name="qft")
# avoid name "qft" as workaround of https://github.com/Qiskit/qiskit/issues/13174
qr = QuantumRegister(input_size); qc = QuantumCircuit(qr, name="qft_")

# Generate multiple groups of diminishing angle CRZs and H gate
for i_qubit in range(0, input_size):
Expand Down
2 changes: 1 addition & 1 deletion shors/qiskit/shors_benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ def analyze_and_print_result(qc, result, num_qubits, order, num_shots, method):

# Execute program with default parameters
def run (min_qubits=3, max_circuits=1, max_qubits=18, num_shots=100, method = 1,
verbose=verbose, backend_id='qasm_simulator', provider_backend=None,
verbose=verbose, backend_id='statevector_sampler', provider_backend=None,
hub="ibm-q", group="open", project="main", exec_options=None,
context=None):

Expand Down

0 comments on commit 7b3a9d9

Please sign in to comment.