Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stable/0.3: fix measures is NoneType problem and a typing problem #56

Merged
merged 12 commits into from
Aug 16, 2023
34 changes: 18 additions & 16 deletions src/quafu/results/results.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,31 @@ class Result(object):


class ExecResult(Result):
"""
"""
Class that save the execute results returned from backend.

Attributes:
counts (dict): Samples counts on each bitstring.
probabilities (dict): Calculated probabilities on each bitstring.
taskid (int): Unique task id for the execute result.
transpiled_circuit (QuantumCircuit): Quantum circuit transpiled on backend.
"""

def __init__(self, input_dict, measures):
def __init__(self, input_dict):
status_map = {0: "In Queue", 1: "Running", 2: "Completed", "Canceled": 3, 4: "Failed"}
self.measures = measures
self.taskid = input_dict['task_id']
self.taskname = input_dict['task_name']
self.transpiled_openqasm = input_dict["openqasm"]
from ..circuits.quantum_circuit import QuantumCircuit
self.transpiled_circuit = QuantumCircuit(0)
self.transpiled_circuit.from_openqasm(self.transpiled_openqasm)
self.measure_base = []

self.measures = self.transpiled_circuit.measures
self.task_status = status_map[input_dict["status"]]
self.res = eval(input_dict['res'])
self.counts = OrderedDict(sorted(self.res.items(), key=lambda s: s[0]))

self.logicalq_res = {}
cbits = list(self.measures.values())
indexed_cbits = {bit: i for i, bit in enumerate(sorted(cbits))}
Zhaoyilunnn marked this conversation as resolved.
Show resolved Hide resolved
Expand All @@ -35,23 +44,16 @@ def __init__(self, input_dict, measures):
newkey = "".join([key[i] for i in squeezed_cbits])
self.logicalq_res[newkey] = values

self.taskid = input_dict['task_id']
self.taskname = input_dict['task_name']
self.transpiled_openqasm = input_dict["openqasm"]
from ..circuits.quantum_circuit import QuantumCircuit
self.transpiled_circuit = QuantumCircuit(0)
self.transpiled_circuit.from_openqasm(self.transpiled_openqasm)
self.measure_base = []
total_counts = sum(self.counts.values())
self.probabilities = {}
for key in self.counts:
self.probabilities[key] = self.counts[key] / total_counts
for bit_str in self.counts:
self.probabilities[bit_str] = self.counts[bit_str] / total_counts

def calculate_obs(self, pos):
"""
Calculate observables Z on input position using probabilities

Args:
Args:
pos (list[int]): Positions of observalbes.
"""
return measure_obs(pos, self.logicalq_res)
Expand Down Expand Up @@ -91,11 +93,11 @@ def __init__(self, input, input_form):
def plot_probabilities(self, full: bool = False, reverse_basis: bool = False, sort: bool = None):
"""
Plot the probabilities from simulated results, ordered in big endian convention.

Args:
full: Whether plot on the full basis of measured qubits.
reverse_basis: Whether reverse the bitstring of basis. (Little endian convention).
sort: Sort the results by probabilities values. Can be `"ascend"` order or `"descend"` order.
sort: Sort the results by probabilities values. Can be `"ascend"` order or `"descend"` order.
"""

probs = self.probabilities
Expand Down
9 changes: 2 additions & 7 deletions src/quafu/tasks/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ def send(self,
else:
self.submit_history[group].append(task_id)

return ExecResult(res_dict, qc.measures)
return ExecResult(res_dict)

def retrieve(self, taskid: str) -> ExecResult:
"""
Expand All @@ -259,12 +259,7 @@ def retrieve(self, taskid: str) -> ExecResult:
response = requests.post(url, headers=headers, data=data)

res_dict = response.json()
measures = eval(res_dict["measure"])
if measures is None:
raise Exception("Measure info returned is None. This may be the error under repairing."
" See https://github.com/ScQ-Cloud/pyquafu/issues/50")

return ExecResult(res_dict, measures)
return ExecResult(res_dict)

def retrieve_group(self,
group: str,
Expand Down
5 changes: 3 additions & 2 deletions src/quafu/visualisation/circuitPlot.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from matplotlib.text import Text

from quafu.elements.quantum_element import Instruction, ControlledGate
from typing import Dict

# this line for developers only
# from quafu.circuits.quantum_circuit import QuantumCircuit
Expand Down Expand Up @@ -158,9 +159,9 @@ def __call__(self,
title,
size=30,
ha='center', va='baseline')
print(title)
self._text_list.append(title)

# TODO: adjust figure size according to title and other elements
# initialize a figure
_size_x = self._a_inch * abs(self.xs[-1] - self.xs[0])
_size_y = self._a_inch * abs(self.ys[-1] - self.ys[0])
Expand Down Expand Up @@ -237,7 +238,7 @@ def _gate_bbox(self, x, y, fc: str):
)
self._closed_patches.append(bbox)

def _inits_label(self, labels: dict[int: str] = None):
def _inits_label(self, labels: Dict[int, str] = None):
""" qubit-labeling """
if labels is None:
labels = self.q_label
Expand Down