Skip to content

Commit

Permalink
found lots of other commented-out function definitions
Browse files Browse the repository at this point in the history
  • Loading branch information
rileyjmurray committed Sep 30, 2024
1 parent 2cdfe87 commit 024d553
Show file tree
Hide file tree
Showing 18 changed files with 0 additions and 3,738 deletions.
388 changes: 0 additions & 388 deletions pygsti/algorithms/mirroring.py

Large diffs are not rendered by default.

1,131 changes: 0 additions & 1,131 deletions pygsti/algorithms/randomcircuit.py

Large diffs are not rendered by default.

234 changes: 0 additions & 234 deletions pygsti/algorithms/rbfit.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,132 +17,6 @@
from pygsti.tools import rbtools as _rbt


# Obsolute function to be deleted.
# def std_practice_analysis(RBSdataset, seed=[0.8, 0.95], bootstrap_samples=200, asymptote='std', rtype='EI',
# datatype='auto'):
# """
# Implements a "standard practice" analysis of RB data. Fits the average success probabilities to the exponential
# decay A + Bp^m, using least-squares fitting, with (1) A fixed (as standard, to 1/2^n where n is the number of
# qubits the data is for), and (2) A, B and p all allowed to varying. Confidence intervals are also estimated using
# a standard non-parameteric boostrap.

# Parameters
# ----------
# RBSdataset : RBSummaryDataset
# An RBSUmmaryDataset containing the data to analyze

# seed : list, optional
# Seeds for the fit of B and p (A is seeded to the asymptote defined by `asympote`).

# bootstrap_samples : int, optional
# The number of samples in the bootstrap.

# asymptote : str or float, optional
# The A value for the fitting to A + Bp^m with A fixed. If a string must be 'std', in
# in which case A is fixed to 1/2^n.

# rtype : {'EI','AGI'}, optional
# The RB error rate rescaling convention. 'EI' results in RB error rates that are associated
# with the entanglement infidelity, which is the error probability with stochastic errors (and
# is equal to the diamond distance). 'AGI' results in RB error rates that are associated with
# average gate infidelity.

# Returns
# -------
# RBResults
# An object encapsulating the RB results (and data).

# """
# assert(datatype == 'raw' or datatype == 'adjusted' or datatype == 'auto'), "Unknown data type!"

# if datatype == 'auto':
# if RBSdataset.datatype == 'hamming_distance_counts':
# datatype = 'adjusted'
# else:
# datatype = 'raw'

# lengths = RBSdataset.lengths
# n = RBSdataset.num_qubits

# if isinstance(asymptote, str):
# assert(asymptote == 'std'), "If `asympotote` is a string it must be 'std'!"
# if datatype == 'raw':
# asymptote = 1 / 2**n
# elif datatype == 'adjusted':
# asymptote = 1 / 4**n

# if datatype == 'adjusted':
# ASPs = RBSdataset.adjusted_ASPs
# if datatype == 'raw':
# ASPs = RBSdataset.ASPs

# FF_results, FAF_results = std_least_squares_fit(lengths, ASPs, n, seed=seed, asymptote=asymptote,
# ftype='full+FA', rtype=rtype)

# parameters = ['A', 'B', 'p', 'r']
# bootstraps_FF = {}
# bootstraps_FAF = {}

# if bootstrap_samples > 0:

# bootstraps_FF = {p: [] for p in parameters}
# bootstraps_FAF = {p: [] for p in parameters}
# failcount_FF = 0
# failcount_FAF = 0

# # Add bootstrapped data, if neccessary.
# RBSdataset.add_bootstrapped_datasets(samples=bootstrap_samples)

# for i in range(bootstrap_samples):

# if datatype == 'adjusted':
# BS_ASPs = RBSdataset.bootstraps[i].adjusted_ASPs
# if datatype == 'raw':
# BS_ASPs = RBSdataset.bootstraps[i].ASPs

# BS_FF_results, BS_FAF_results = std_least_squares_fit(lengths, BS_ASPs, n, seed=seed,
# asymptote=asymptote, ftype='full+FA',
# rtype=rtype)

# if BS_FF_results['success']:
# for p in parameters:
# bootstraps_FF[p].append(BS_FF_results['estimates'][p])
# else:
# failcount_FF += 1
# if BS_FAF_results['success']:
# for p in parameters:
# bootstraps_FAF[p].append(BS_FAF_results['estimates'][p])
# else:
# failcount_FAF += 1

# failrate_FF = failcount_FF / bootstrap_samples
# failrate_FAF = failcount_FAF / bootstrap_samples

# std_FF = {p: _np.std(_np.array(bootstraps_FF[p])) for p in parameters}
# std_FAF = {p: _np.std(_np.array(bootstraps_FAF[p])) for p in parameters}

# else:
# bootstraps_FF = None
# std_FF = None
# failrate_FF = None
# bootstraps_FAF = None
# std_FAF = None
# failrate_FAF = None

# fits = {}
# fits['full'] = FitResults('LS', FF_results['seed'], rtype, FF_results['success'], FF_results['estimates'],
# FF_results['variable'], stds=std_FF, bootstraps=bootstraps_FF,
# bootstraps_failrate=failrate_FF)

# fits['A-fixed'] = FitResults('LS', FAF_results['seed'], rtype, FAF_results['success'],
# FAF_results['estimates'], FAF_results['variable'], stds=std_FAF,
# bootstraps=bootstraps_FAF, bootstraps_failrate=failrate_FAF)

# results = SimpleRBResults(RBSdataset, rtype, fits)

# return results


def std_least_squares_fit(lengths, asps, n, seed=None, asymptote=None, ftype='full', rtype='EI'):
"""
Implements a "standard" least-squares fit of RB data.
Expand Down Expand Up @@ -469,111 +343,3 @@ def _from_nice_serialization(cls, state):
return cls(state['fit_type'], state['seed'], state['r_type'], state['success'],
state['estimates'], state['variable'], state['stds'],
state['bootstraps'], state['bootstraps_failrate'])

# Obsolute RB results class
# class SimpleRBResults(object):
# """
# An object to contain the results of an RB analysis.

# """

# def __init__(self, data, rtype, fits):
# """
# Initialize an RBResults object.

# Parameters
# ----------
# data : RBSummaryDataset
# The RB summary data that the analysis was performed for.

# rtype : {'IE','AGI'}
# The type of RB error rate, corresponding to different dimension-dependent
# re-scalings of (1-p), where p is the RB decay constant in A + B*p^m.

# fits : dict
# A dictionary containing FitResults objects, obtained from one or more
# fits of the data (e.g., a fit with all A, B and p as free parameters and
# a fit with A fixed to 1/2^n).
# """
# self.data = data
# self.rtype = rtype
# self.fits = fits

# def plot(self, fitkey=None, decay=True, success_probabilities=True, size=(8, 5), ylim=None, xlim=None,
# legend=True, title=None, figpath=None):
# """
# Plots RB data and, optionally, a fitted exponential decay.

# Parameters
# ----------
# fitkey : dict key, optional
# The key of the self.fits dictionary to plot the fit for. If None, will
# look for a 'full' key (the key for a full fit to A + Bp^m if the standard
# analysis functions are used) and plot this if possible. It otherwise checks
# that there is only one key in the dict and defaults to this. If there are
# multiple keys and none of them are 'full', `fitkey` must be specified when
# `decay` is True.

# decay : bool, optional
# Whether to plot a fit, or just the data.

# success_probabilities : bool, optional
# Whether to plot the success probabilities distribution, as a violin plot. (as well
# as the *average* success probabilities at each length).

# size : tuple, optional
# The figure size

# ylim, xlim : tuple, optional
# The x and y limits for the figure.

# legend : bool, optional
# Whether to show a legend.

# title : str, optional
# A title to put on the figure.

# figpath : str, optional
# If specified, the figure is saved with this filename.
# """

# # Future : change to a plotly plot.
# try: import matplotlib.pyplot as _plt
# except ImportError: raise ValueError("This function requires you to install matplotlib!")

# if decay and fitkey is None:
# allfitkeys = list(self.fits.keys())
# if 'full' in allfitkeys: fitkey = 'full'
# else:
# assert(len(allfitkeys) == 1), \
# "There are multiple fits and none have the key 'full'. Please specify the fit to plot!"
# fitkey = allfitkeys[0]

# _plt.figure(figsize=size)
# _plt.plot(self.data.lengths, self.data.ASPs, 'o', label='Average success probabilities')

# if decay:
# lengths = _np.linspace(0, max(self.data.lengths), 200)
# A = self.fits[fitkey].estimates['A']
# B = self.fits[fitkey].estimates['B']
# p = self.fits[fitkey].estimates['p']
# _plt.plot(lengths, A + B * p**lengths,
# label='Fit, r = {:.2} +/- {:.1}'.format(self.fits[fitkey].estimates['r'],
# self.fits[fitkey].stds['r']))

# if success_probabilities:
# _plt.violinplot(list(self.data.success_probabilities), self.data.lengths, points=10, widths=1.,
# showmeans=False, showextrema=False, showmedians=False) # , label='Success probabilities')

# if title is not None: _plt.title(title)
# _plt.ylabel("Success probability")
# _plt.xlabel("RB sequence length $(m)$")
# _plt.ylim(ylim)
# _plt.xlim(xlim)

# if legend: _plt.legend()

# if figpath is not None: _plt.savefig(figpath, dpi=1000)
# else: _plt.show()

# return
122 changes: 0 additions & 122 deletions pygsti/baseobjs/errorgenbasis.py
Original file line number Diff line number Diff line change
Expand Up @@ -514,125 +514,3 @@ def intersection(self, other_basis):

def difference(self, other_basis):
return self.to_explicit_basis().difference(other_basis)


#OLD - maybe not needed?
#class LowWeightElementaryErrorgenBasis(ElementaryErrorgenBasis):
# """
# Spanned by the elementary error generators of given type(s) (e.g. "Hamiltonian" and/or "other")
# and with elements corresponding to a `Basis`, usually of Paulis.
# """
#
# def __init__(self, basis_1q, state_space, other_mode, max_ham_weight=None, max_other_weight=None,
# must_overlap_with_these_sslbls=None):
# self._basis_1q = basis_1q
# self._other_mode = other_mode
# self.state_space = state_space
# self._max_ham_weight = max_ham_weight
# self._max_other_weight = max_other_weight
# self._must_overlap_with_these_sslbls = must_overlap_with_these_sslbls
#
# assert(self.state_space.is_entirely_qubits), "FOGI only works for models containing just qubits (so far)"
# sslbls = self.state_space.sole_tensor_product_block_labels # all the model's state space labels
# self.sslbls = sslbls # the "support" of this space - the qubit labels
#
# self._cached_label_indices = None
# self._cached_labels_by_support = None
# self._cached_elements = None
#
# #Needed?
# # self.dim = len(self.labels) # TODO - update this so we don't always need to build labels
# # # (this defeats lazy building via property below) - we can just compute this, especially if
# # # not too fancy
#
# @property
# def labels(self):
# if self._cached_label_indices is None:
#
# def _basis_el_strs(possible_bels, wt):
# for els in _itertools.product(*([possible_bels] * wt)):
# yield ''.join(els)
#
# labels = {}
# all_bels = self.basis_1q.labels[1:] # assume first element is identity
# nontrivial_bels = self.basis_1q.labels[1:] # assume first element is identity
#
# max_weight = self._max_ham_weight if (self._max_ham_weight is not None) else len(self.sslbls)
# for weight in range(1, max_weight + 1):
# for support in _itertools.combinations(self.sslbls, weight):
# if (self._must_overlap_with_these_sslbls is not None
# and len(self._must_overlap_with_these_sslbls.intersection(support)) == 0):
# continue
# if support not in labels: labels[support] = [] # always True?
# labels[support].extend([('H', bel) for bel in _basis_el_strs(nontrivial_bels, weight)])
#
# max_weight = self._max_other_weight if (self._max_other_weight is not None) else len(self.sslbls)
# if self._other_mode != "all":
# for weight in range(1, max_weight + 1):
# for support in _itertools.combinations(self.sslbls, weight):
# if (self._must_overlap_with_these_sslbls is not None
# and len(self._must_overlap_with_these_sslbls.intersection(support)) == 0):
# continue
# if support not in labels: labels[support] = []
# labels[support].extend([('S', bel) for bel in _basis_el_strs(nontrivial_bels, weight)])
# else:
# #This is messy code that relies on basis labels being single characters -- TODO improve(?)
# idle_char = self.basis_1q.labels[1:] # assume first element is identity
# assert(len(idle_char) == 1 and all([len(c) == 1 for c in nontrivial_bels])), \
# "All basis el labels must be single chars for other_mode=='all'!"
# for support in _itertools.combinations(self.sslbls, max_weight):
# # Loop over all possible basis elements for this max-weight support, computing the actual support
# # of each one individually and appending it to the appropriate list
# for bel1 in _basis_el_strs(all_bels, max_weight):
# nonidle_indices1 = [i for i in range(max_weight) if bel1[i] != idle_char]
# for bel2 in _basis_el_strs(all_bels, max_weight):
# nonidle_indices2 = [i for i in range(max_weight) if bel2[i] != idle_char]
# nonidle_indices = list(sorted(set(nonidle_indices1) + set(nonidle_indices2)))
# bel1 = ''.join([bel1[i] for i in nonidle_indices]) # trim to actual support
# bel2 = ''.join([bel2[i] for i in nonidle_indices]) # trim to actual support
# actual_support = tuple([support[i] for i in nonidle_indices])
#
# if (self._must_overlap_with_these_sslbls is not None
# and len(self._must_overlap_with_these_sslbls.intersection(actual_support)) == 0):
# continue
#
# if actual_support not in labels: labels[actual_support] = []
# labels[actual_support].append(('S', bel1, bel2))
#
# self._cached_labels_by_support = labels
# self._cached_label_indices = _collections.OrderedDict(((support_lbl, i) for i, support_lbl in enumerate(
# ((support, lbl) for support, lst in labels.items() for lbl in lst))))
#
# return tuple(self._cached_label_indices.keys())
#
# @property
# def element_supports_and_matrices(self):
# if self._cached_elements is None:
# self._cached_elements = tuple(
# ((support, _ot.lindblad_error_generator(elemgen_label, self.basis_1q, normalize=True, sparse=False))
# for support, elemgen_label in self.labels))
# return self._cached_elements
#
# def element_index(self, label):
# """
# TODO: docstring
# """
# if self._cached_label_indices is None:
# self.labels # triggers building of labels
# return self._cached_label_indices[label]
#
# @property
# def sslbls(self):
# """ The support of this errorgen space, e.g., the qubits where its elements may be nontrivial """
# return self.sslbls
#
# def create_subbasis(self, must_overlap_with_these_sslbls, retain_max_weights=True):
# """
# Create a sub-basis of this basis by including only the elements
# that overlap the given support (state space labels)
# """
# #Note: can we reduce self.state_space?
# return CompleteErrorgenBasis(self._basis_1q, self.state_space, self._other_mode,
# self._max_ham_weight if retain_max_weights else None,
# self._max_other_weight if retain_max_weights else None,
# self._must_overlap_with_these_sslbls)
10 changes: 0 additions & 10 deletions pygsti/baseobjs/errorgenspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,13 +97,3 @@ def normalize(self, norm_order=2):
for j in range(self.vectors.shape[1]):
sign = +1 if max(self.vectors[:, j]) >= -min(self.vectors[:, j]) else -1
self.vectors[:, j] /= sign * _np.linalg.norm(self.vectors[:, j], ord=norm_order)


#class LowWeightErrorgenSpace(ErrorgenSpace):
# """
# Like a SimpleErrorgenSpace but spanned by only the elementary error generators corresponding to
# low-weight (up to some maximum weight) basis elements
# (so far, only Pauli-product bases work for this, since `Basis` objects don't keep track of each
# element's weight (?)).
# """
# pass
Loading

0 comments on commit 024d553

Please sign in to comment.