Skip to content

Commit

Permalink
Use Runtime for calibrations
Browse files Browse the repository at this point in the history
  • Loading branch information
nonhermitian committed Sep 20, 2024
1 parent 30d35d0 commit 1d59d78
Show file tree
Hide file tree
Showing 35 changed files with 1,134 additions and 1,056 deletions.
19 changes: 9 additions & 10 deletions mthree/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,18 @@
from .version import version as __version__
from .version import openmp
except ImportError:
__version__ = '0.0.0'
__version__ = "0.0.0"
openmp = False

from .mitigation import M3Mitigation


def about():
"""The M3 version info function.
"""
print('='*80)
print('# Matrix-free Measurement Mitigation (M3) version {}'.format(__version__))
print('# (C) Copyright IBM 2021.')
print('# Paul Nation, Hwajung Kang, Neereja Sundaresan')
print('# Jay Gambetta, and Matthew Treinish.')
print('# Compiled with OpenMP: {}'.format(openmp))
print('='*80)
"""The M3 version info function."""
print("=" * 80)
print("# Matrix-free Measurement Mitigation (M3) version {}".format(__version__))
print("# (C) Copyright IBM 2021.")
print("# Paul Nation, Hwajung Kang, Neereja Sundaresan")
print("# Jay Gambetta, and Matthew Treinish.")
print("# Compiled with OpenMP: {}".format(openmp))
print("=" * 80)
8 changes: 4 additions & 4 deletions mthree/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,12 @@ def system_info(backend):
# No other way to tell outside of configuration
# E.g. how to tell that ibmq_qasm_simulator is sim, but real devices not
# outside of configuration?
if hasattr(backend, 'configuration'):
if hasattr(backend, "configuration"):
info_dict["simulator"] = backend.configuration().simulator
else:
raise M3Error('Invalid backend passed.')
raise M3Error("Invalid backend passed.")
# Look for faulty qubits. Renaming to 'inoperable' here
if hasattr(backend, 'properties'):
if hasattr(backend.properties(), 'faulty_qubits'):
if hasattr(backend, "properties"):
if hasattr(backend.properties(), "faulty_qubits"):
info_dict["inoperable_qubits"] = backend.properties().faulty_qubits()
return info_dict
10 changes: 5 additions & 5 deletions mthree/circuits.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,12 @@ def balanced_cal_strings(num_qubits):
list: List of strings for balanced calibration circuits.
"""
strings = []
for rep in range(1, num_qubits+1):
str1 = ''
str2 = ''
for rep in range(1, num_qubits + 1):
str1 = ""
str2 = ""
for jj in range(int(np.ceil(num_qubits / rep))):
str1 += str(jj % 2) * rep
str2 += str((jj+1) % 2) * rep
str2 += str((jj + 1) % 2) * rep

strings.append(str1[:num_qubits])
strings.append(str2[:num_qubits])
Expand Down Expand Up @@ -92,7 +92,7 @@ def balanced_cal_circuits(cal_strings, layout, system_qubits, initial_reset=Fals
qc.reset(range(system_qubits))
qc.reset(range(system_qubits))
for idx, bit in enumerate(string[::-1]):
if bit == '1':
if bit == "1":
qc.x(layout[idx])
qc.measure(layout, range(num_active_qubits))
circs.append(qc)
Expand Down
70 changes: 39 additions & 31 deletions mthree/classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@


class ProbDistribution(dict):
"""A generic dict-like class for probability distributions.
"""
"""A generic dict-like class for probability distributions."""

def __init__(self, data, shots=None, mitigation_overhead=None):
"""A generic dict-like class for probability distributions.
Expand All @@ -58,7 +58,10 @@ def __init__(self, data, shots=None, mitigation_overhead=None):
self.shots = sum(data.values())
self.mitigation_overhead = 1
_data = {}
for key, val, in data.items():
for (
key,
val,
) in data.items():
_data[key] = val / self.shots
data = _data
else:
Expand All @@ -67,15 +70,18 @@ def __init__(self, data, shots=None, mitigation_overhead=None):
self.mitigation_overhead = 1
if self.shots != 1:
_data = {}
for key, val, in data.items():
for (
key,
val,
) in data.items():
_data[key] = val / self.shots
data = _data
else:
self.shots = shots
self.mitigation_overhead = mitigation_overhead
super().__init__(data)

def expval(self, exp_ops=''):
def expval(self, exp_ops=""):
"""Compute expectation value from distribution.
Parameters:
Expand All @@ -100,7 +106,7 @@ def expval(self, exp_ops=''):
elif isinstance(exp_ops, list):
return np.array([self.expval(item) for item in exp_ops], dtype=float)
else:
raise M3Error('Invalid type passed to exp_ops')
raise M3Error("Invalid type passed to exp_ops")

def stddev(self):
"""Compute standard deviation from distribution.
Expand All @@ -116,12 +122,12 @@ def stddev(self):
using bitstrings as the keys.
"""
if self.shots is None:
raise M3Error('Prob-dist is missing shots information.')
raise M3Error("Prob-dist is missing shots information.")
if self.mitigation_overhead is None:
raise M3Error('Prob-dist is missing mitigation overhead.')
raise M3Error("Prob-dist is missing mitigation overhead.")
return math.sqrt(self.mitigation_overhead / self.shots)

def expval_and_stddev(self, exp_ops=''):
def expval_and_stddev(self, exp_ops=""):
"""Compute expectation value and standard deviation from distribution.
Parameters:
Expand All @@ -140,8 +146,8 @@ def expval_and_stddev(self, exp_ops=''):


class QuasiDistribution(dict):
"""A dict-like class for representing quasi-probabilities.
"""
"""A dict-like class for representing quasi-probabilities."""

def __init__(self, data, shots=None, mitigation_overhead=None):
"""A dict-like class for representing quasi-probabilities.
Expand All @@ -154,7 +160,7 @@ def __init__(self, data, shots=None, mitigation_overhead=None):
self.mitigation_overhead = mitigation_overhead
super().__init__(data)

def expval(self, exp_ops=''):
def expval(self, exp_ops=""):
"""Compute expectation value from distribution.
Parameters:
Expand All @@ -176,7 +182,7 @@ def expval(self, exp_ops=''):
elif isinstance(exp_ops, list):
return np.array([self.expval(item) for item in exp_ops], dtype=float)
else:
raise M3Error('Invalid type passed to exp_ops')
raise M3Error("Invalid type passed to exp_ops")

def stddev(self):
"""Compute standard deviation estimate from distribution.
Expand All @@ -188,12 +194,12 @@ def stddev(self):
M3Error: Missing shots or mitigation_overhead information.
"""
if self.shots is None:
raise M3Error('Quasi-dist is missing shots information.')
raise M3Error("Quasi-dist is missing shots information.")
if self.mitigation_overhead is None:
raise M3Error('Quasi-dist is missing mitigation overhead.')
raise M3Error("Quasi-dist is missing mitigation overhead.")
return math.sqrt(self.mitigation_overhead / self.shots)

def expval_and_stddev(self, exp_ops=''):
def expval_and_stddev(self, exp_ops=""):
"""Compute expectation value and standard deviation estimate from distribution.
Parameters:
Expand Down Expand Up @@ -232,8 +238,8 @@ def nearest_probability_distribution(self, return_distance=False):


class QuasiCollection(list):
"""A list subclass that makes handling multiple quasi-distributions easier.
"""
"""A list subclass that makes handling multiple quasi-distributions easier."""

def __init__(self, data):
"""QuasiCollection constructor.
Expand All @@ -245,7 +251,7 @@ def __init__(self, data):
"""
for dd in data:
if not isinstance(dd, QuasiDistribution):
raise TypeError('QuasiCollection requires QuasiDistribution instances.')
raise TypeError("QuasiCollection requires QuasiDistribution instances.")
super().__init__(data)

@property
Expand All @@ -266,7 +272,7 @@ def mitigation_overhead(self):
"""
return np.array([item.mitigation_overhead for item in self], dtype=float)

def expval(self, exp_ops=''):
def expval(self, exp_ops=""):
"""Expectation value over entire collection.
Parameters:
Expand All @@ -284,7 +290,7 @@ def expval(self, exp_ops=''):
"""
if isinstance(exp_ops, list):
if len(exp_ops) != len(self):
raise M3Error('exp_ops length does not match container length')
raise M3Error("exp_ops length does not match container length")
out = []
for idx, item in enumerate(self):
out.append(item.expval(exp_ops[idx]))
Expand All @@ -293,7 +299,7 @@ def expval(self, exp_ops=''):
return out
return np.array([item.expval(exp_ops) for item in self])

def expval_and_stddev(self, exp_ops=''):
def expval_and_stddev(self, exp_ops=""):
"""Expectation value and standard deviation over entire collection.
Parameters:
Expand All @@ -311,7 +317,7 @@ def expval_and_stddev(self, exp_ops=''):
"""
if isinstance(exp_ops, list):
if len(exp_ops) != len(self):
raise M3Error('exp_ops length does not match container length')
raise M3Error("exp_ops length does not match container length")
out = []
for idx, item in enumerate(self):
out.append(item.expval_and_stddev(exp_ops[idx]))
Expand All @@ -332,12 +338,14 @@ def nearest_probability_distribution(self):
Returns:
ProbCollection: Collection of ProbDistributions.
"""
return ProbCollection([item.nearest_probability_distribution() for item in self])
return ProbCollection(
[item.nearest_probability_distribution() for item in self]
)


class ProbCollection(list):
"""A list subclass that makes handling multiple probability-distributions easier.
"""
"""A list subclass that makes handling multiple probability-distributions easier."""

def __init__(self, data):
"""ProbCollection constructor.
Expand All @@ -349,7 +357,7 @@ def __init__(self, data):
"""
for dd in data:
if not isinstance(dd, ProbDistribution):
raise TypeError('ProbCollection requires ProbDistribution instances.')
raise TypeError("ProbCollection requires ProbDistribution instances.")
super().__init__(data)

@property
Expand All @@ -370,7 +378,7 @@ def mitigation_overhead(self):
"""
return np.array([item.mitigation_overhead for item in self], dtype=float)

def expval(self, exp_ops=''):
def expval(self, exp_ops=""):
"""Expectation value over entire collection.
Parameters:
Expand All @@ -388,7 +396,7 @@ def expval(self, exp_ops=''):
"""
if isinstance(exp_ops, list):
if len(exp_ops) != len(self):
raise M3Error('exp_ops length does not match container length')
raise M3Error("exp_ops length does not match container length")
out = []
for idx, item in enumerate(self):
out.append(item.expval(exp_ops[idx]))
Expand All @@ -397,7 +405,7 @@ def expval(self, exp_ops=''):
return out
return np.array([item.expval(exp_ops) for item in self], dtype=float)

def expval_and_stddev(self, exp_ops=''):
def expval_and_stddev(self, exp_ops=""):
"""Expectation value and standard deviation over entire collection.
Parameters:
Expand All @@ -415,7 +423,7 @@ def expval_and_stddev(self, exp_ops=''):
"""
if isinstance(exp_ops, list):
if len(exp_ops) != len(self):
raise M3Error('exp_ops length does not match container length')
raise M3Error("exp_ops length does not match container length")
out = []
for idx, item in enumerate(self):
out.append(item.expval_and_stddev(exp_ops[idx]))
Expand Down
4 changes: 2 additions & 2 deletions mthree/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ class M3Error(Exception):

def __init__(self, *message):
"""Set the error message."""
super().__init__(' '.join(message))
self.message = ' '.join(message)
super().__init__(" ".join(message))
self.message = " ".join(message)

def __str__(self):
"""Return the message."""
Expand Down
Loading

0 comments on commit 1d59d78

Please sign in to comment.