code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
self.reply_err(req, errno.EROFS) | def mkdir(self, req, parent, name, mode) | Create a directory
Valid replies:
reply_entry
reply_err | 12.340338 | 11.65463 | 1.058836 |
self.reply_err(req, errno.EROFS) | def unlink(self, req, parent, name) | Remove a file
Valid replies:
reply_err | 16.37602 | 14.281656 | 1.146647 |
self.reply_err(req, errno.EROFS) | def rmdir(self, req, parent, name) | Remove a directory
Valid replies:
reply_err | 14.457818 | 13.507663 | 1.070342 |
self.reply_err(req, errno.EROFS) | def symlink(self, req, link, parent, name) | Create a symbolic link
Valid replies:
reply_entry
reply_err | 16.165007 | 12.252917 | 1.319278 |
self.reply_err(req, errno.EROFS) | def rename(self, req, parent, name, newparent, newname) | Rename a file
Valid replies:
reply_err | 17.245539 | 13.980862 | 1.23351 |
self.reply_err(req, errno.EROFS) | def link(self, req, ino, newparent, newname) | Create a hard link
Valid replies:
reply_entry
reply_err | 12.897254 | 12.239334 | 1.053755 |
self.reply_err(req, errno.EIO) | def read(self, req, ino, size, off, fi) | Read data
Valid replies:
reply_buf
reply_err | 11.542398 | 14.071573 | 0.820264 |
self.reply_err(req, errno.EROFS) | def write(self, req, ino, buf, off, fi) | Write data
Valid replies:
reply_write
reply_err | 11.478338 | 11.03946 | 1.039755 |
if ino == 1:
attr = {'st_ino': 1, 'st_mode': S_IFDIR}
entries = [('.', attr), ('..', attr)]
self.reply_readdir(req, size, off, entries)
else:
self.reply_err(req, errno.ENOENT) | def readdir(self, req, ino, size, off, fi) | Read directory
Valid replies:
reply_readdir
reply_err | 3.682506 | 3.595381 | 1.024233 |
self.reply_err(req, errno.ENOSYS) | def setxattr(self, req, ino, name, value, flags) | Set an extended attribute
Valid replies:
reply_err | 9.757969 | 11.759875 | 0.829768 |
self.reply_err(req, errno.ENOSYS) | def getxattr(self, req, ino, name, size) | Set an extended attribute
Valid replies:
reply_buf
reply_data
reply_xattr
reply_err | 9.578153 | 10.269987 | 0.932635 |
self.reply_err(req, errno.ENOSYS) | def listxattr(self, req, ino, size) | List extended attribute names
Valid replies:
reply_buf
reply_data
reply_xattr
reply_err | 10.026235 | 10.403501 | 0.963737 |
self.reply_err(req, errno.ENOSYS) | def removexattr(self, req, ino, name) | Remove an extended attribute
Valid replies:
reply_err | 10.348712 | 10.928613 | 0.946937 |
self.reply_err(req, errno.ENOSYS) | def access(self, req, ino, mask) | Check file access permissions
Valid replies:
reply_err | 9.905429 | 11.08427 | 0.893647 |
self.reply_err(req, errno.ENOSYS) | def create(self, req, parent, name, mode, fi) | Create and open a file
Valid replies:
reply_create
reply_err | 15.588343 | 12.547033 | 1.242393 |
channel_transfer_matrices = [pauli_basis.transfer_matrix(qt.to_super(ek)) for ek in channel_ops]
# This bit could be more efficient but does not run super long and is thus preserved for
# readability.
pi_jr = csr_matrix(
[pauli_basis.project_op(n_j).toarray().ravel()
for n_j in r... | def _prepare_c_jk_m(readout_povm, pauli_basis, channel_ops) | Prepare the coefficient matrix for state tomography. This function uses sparse matrices
for much greater efficiency.
The coefficient matrix is defined as:
.. math::
C_{(jk)m} = \tr{\Pi_{s_j} \Lambda_k(P_m)} = \sum_{r}\pi_{jr}(\mathcal{R}_{k})_{rm}
where :math:`\Lambda_k(\cdot)` is the qua... | 5.432262 | 5.096438 | 1.065894 |
if qubits is None:
qubits = state_prep.get_qubits()
for tomography_program in rotation_generator(*qubits):
state_tomography_program = Program(Pragma("PRESERVE_BLOCK"))
state_tomography_program.inst(state_prep)
state_tomography_program.inst(tomography_program)
state_t... | def state_tomography_programs(state_prep, qubits=None,
rotation_generator=tomography.default_rotations) | Yield tomographic sequences that prepare a state with Quil program `state_prep` and then append
tomographic rotations on the specified `qubits`. If `qubits is None`, it assumes all qubits in
the program should be tomographically rotated.
:param Program state_prep: The program to prepare the state to be tom... | 2.110665 | 2.115777 | 0.997584 |
return tomography._do_tomography(preparation_program, nsamples, cxn, qubits,
tomography.MAX_QUBITS_STATE_TOMO,
StateTomography, state_tomography_programs,
DEFAULT_STATE_TOMO_SETTINGS, use_run=use_run) | def do_state_tomography(preparation_program, nsamples, cxn, qubits=None, use_run=False) | Method to perform both a QPU and QVM state tomography, and use the latter as
as reference to calculate the fidelity of the former.
:param Program preparation_program: Program to execute.
:param int nsamples: Number of samples to take for the program.
:param QVMConnection|QPUConnection cxn: Connection o... | 4.337358 | 5.782846 | 0.750039 |
nqc = len(channel_ops[0].dims[0])
pauli_basis = grove.tomography.operator_utils.PAULI_BASIS ** nqc
pi_basis = readout_povm.pi_basis
if not histograms.shape[1] == pi_basis.dim: # pragma no coverage
raise ValueError("Currently tomography is only implemented for two-l... | def estimate_from_ssr(histograms, readout_povm, channel_ops, settings) | Estimate a density matrix from single shot histograms obtained by measuring bitstrings in
the Z-eigenbasis after application of given channel operators.
:param numpy.ndarray histograms: The single shot histograms, `shape=(n_channels, dim)`.
:param DiagognalPOVM readout_povm: The POVM correspond... | 5.445082 | 5.389993 | 1.010221 |
title = "Estimated state"
nqc = int(round(np.log2(self.rho_est.data.shape[0])))
labels = ut.basis_labels(nqc)
return ut.state_histogram(self.rho_est, ax, title) | def plot_state_histogram(self, ax) | Visualize the complex matrix elements of the estimated state.
:param matplotlib.Axes ax: A matplotlib Axes object to plot into. | 8.168687 | 8.103365 | 1.008061 |
width = 10
# The pleasing golden ratio.
height = width / 1.618
f = plt.figure(figsize=(width, height))
ax = f.add_subplot(111, projection="3d")
self.plot_state_histogram(ax)
return f | def plot(self) | Visualize the state.
:return: The generated figure.
:rtype: matplotlib.Figure | 5.409165 | 5.007969 | 1.080112 |
self._init_attr(bitstring_map)
prog = Program()
dj_ro = prog.declare('ro', 'BIT', len(self.computational_qubits))
prog += self.deutsch_jozsa_circuit
prog += [MEASURE(qubit, ro) for qubit, ro in zip(self.computational_qubits, dj_ro)]
executable = qc.compile(prog)... | def is_constant(self, qc: QuantumComputer, bitstring_map: Dict[str, str]) -> bool | Computes whether bitstring_map represents a constant function, given that it is constant
or balanced. Constant means all inputs map to the same value, balanced means half of the
inputs maps to one value, and half to the other.
:param QVMConnection cxn: The connection object to the Rigetti clo... | 4.313994 | 4.579091 | 0.942107 |
self.bit_map = bitstring_map
self.n_qubits = len(list(bitstring_map.keys())[0])
# We use one extra qubit for making the oracle,
# and one for storing the answer of the oracle.
self.n_ancillas = 2
self._qubits = list(range(self.n_qubits + self.n_ancillas))
... | def _init_attr(self, bitstring_map: Dict[str, str]) | Acts instead of __init__ method to instantiate the necessary Deutsch-Jozsa state.
:param Dict[String, String] bitstring_map: truth-table of the input bitstring map in
dictionary format, used to construct the oracle in the Deutsch-Jozsa algorithm.
:return: None
:rtype: NoneType | 3.022035 | 2.700495 | 1.119067 |
dj_prog = Program()
# Put the first ancilla qubit (query qubit) into minus state
dj_prog.inst(X(self.ancillas[0]), H(self.ancillas[0]))
# Apply Hadamard, Oracle, and Hadamard again
dj_prog.inst([H(qubit) for qubit in self.computational_qubits])
# Build the ora... | def _construct_deutsch_jozsa_circuit(self) | Builds the Deutsch-Jozsa circuit. Which can determine whether a function f mapping
:math:`\{0,1\}^n \to \{0,1\}` is constant or balanced, provided that it is one of them.
:return: A program corresponding to the desired instance of Deutsch Jozsa's Algorithm.
:rtype: Program | 4.07044 | 4.133818 | 0.984669 |
num_qubits = int(np.log2(len(mappings)))
bitsum = sum([int(bit) for bit in mappings.values()])
# Only zeros were entered
if bitsum == 0:
return np.kron(SWAP_MATRIX, np.identity(2 ** (num_qubits - 1)))
# Half of the entries were 0, half 1
elif bitsum... | def unitary_function(mappings: Dict[str, str]) -> np.ndarray | Creates a unitary transformation that maps each state to the values specified in mappings.
Some (but not all) of these transformations involve a scratch qubit, so room for one is
always provided. That is, if given the mapping of n qubits, the calculated transformation
will be on n + 1 qubits, w... | 2.615488 | 2.592922 | 1.008703 |
if len(qubits) != len(bitstring):
raise ValueError("The bitstring should be the same length as the number of qubits.")
oracle_prog = Program()
# In the case of one qubit, we just want to flip the phase of state relative to the other.
if len(bitstring) == 1:
oracle_prog.inst(Z(qubit... | def basis_selector_oracle(qubits: List[int], bitstring: str) -> Program | Defines an oracle that selects the ith element of the computational basis.
Flips the sign of the state :math:`\\vert x\\rangle>`
if and only if x==bitstring and does nothing otherwise.
:param qubits: The qubits the oracle is called on. The qubits are assumed to be ordered from
most significant qubit ... | 3.001739 | 2.953634 | 1.016287 |
confusion_rate_matrix = np.asarray(confusion_rate_matrix)
if not np.allclose(confusion_rate_matrix.sum(axis=0), np.ones(confusion_rate_matrix.shape[1])):
raise CRMUnnormalizedError("Unnormalized confusion matrix:\n{}".format(
confusion_rate_matrix))
if not (confusion_rate_matrix >=... | def make_diagonal_povm(pi_basis, confusion_rate_matrix) | Create a DiagonalPOVM from a ``pi_basis`` and the ``confusion_rate_matrix`` associated with a
readout.
See also the grove documentation.
:param OperatorBasis pi_basis: An operator basis of rank-1 projection operators.
:param numpy.ndarray confusion_rate_matrix: The matrix of detection probabilities co... | 2.778834 | 2.884377 | 0.963409 |
if isinstance(operator, qt.Qobj):
return (operator.dag() - operator).norm(FROBENIUS) / operator.norm(FROBENIUS) < EPS
if isinstance(operator, np.ndarray):
return np.linalg.norm(operator.T.conj() - operator) / np.linalg.norm(operator) < EPS
return spnorm(operator.H - operator) / spnorm(o... | def is_hermitian(operator) | Check if matrix or operator is hermitian.
:param (numpy.ndarray|qutip.Qobj) operator: The operator or matrix to be tested.
:return: True if the operator is hermitian.
:rtype: bool | 3.65876 | 3.934595 | 0.929895 |
# verify that P^dag=P and P^2-P=0 holds up to relative numerical accuracy EPS.
return (is_hermitian(operator) and (operator * operator - operator).norm(FROBENIUS)
/ operator.norm(FROBENIUS) < EPS) | def is_projector(operator) | Check if operator is a projector.
:param qutip.Qobj operator: The operator or matrix to be tested.
:return: True if the operator is a projector.
:rtype: bool | 16.503983 | 16.190397 | 1.019369 |
if not basis.is_orthonormal(): # pragma no coverage
raise ValueError("Need an orthonormal operator basis.")
if not all((is_hermitian(op) for op in basis.ops)): # pragma no coverage
raise ValueError("Need an operator basis of hermitian operators.")
sbasis = basis.super_basis()
D ... | def choi_matrix(pauli_tm, basis) | Compute the Choi matrix for a quantum process from its Pauli Transfer Matrix.
This agrees with the definition in
`Chow et al. <https://doi.org/10.1103/PhysRevLett.109.060501>`_
except for a different overall normalization.
Our normalization agrees with that of qutip.
:param numpy.ndarray pauli_tm:... | 5.243599 | 4.70523 | 1.114419 |
if isinstance(z, qt.Qobj):
z = z.data
if not is_hermitian(z): # pragma no coverage
raise ValueError("Need a hermitian matrix z")
return spvstack([sphstack([z.real, z.imag]), sphstack([z.imag.T, z.real])]).tocsr().real | def to_realimag(z) | Convert a complex hermitian matrix to a real valued doubled up representation, i.e., for
``Z = Z_r + 1j * Z_i`` return ``R(Z)``::
R(Z) = [ Z_r Z_i]
[-Z_i Z_r]
A complex hermitian matrix ``Z`` with elementwise real and imaginary parts
``Z = Z_r + 1j * Z_i`` can be
isomorphica... | 5.838829 | 5.005451 | 1.166494 |
if self._metric is None:
_log.debug("Computing and caching operator basis metric")
self._metric = np.matrix([[(j.dag() * k).tr() for k in self.ops] for j in self.ops])
return self._metric | def metric(self) | Compute a matrix of Hilbert-Schmidt inner products for the basis operators, update
self._metric, and return the value.
:return: The matrix of inner products.
:rtype: numpy.matrix | 7.299793 | 5.829048 | 1.252313 |
if self._is_orthonormal is None:
_log.debug("Testing and caching if operator basis is orthonormal")
self._is_orthonormal = np.allclose(self.metric(), np.eye(self.dim))
return self._is_orthonormal | def is_orthonormal(self) | Compute a matrix of Hilbert-Schmidt inner products for the basis operators, and see if they
are orthonormal. If they are return True, else, False.
:return: True if the basis vectors represented by this OperatorBasis are orthonormal, False
otherwise.
:rtype: bool | 4.257524 | 3.721303 | 1.144095 |
if self._all_hermitian is None:
_log.debug("Testing and caching if all basis operator are hermitian")
self._all_hermitian = all((is_hermitian(op) for op in self.ops))
return self._all_hermitian | def all_hermitian(self) | Check if all basis operators are hermitian. | 4.02983 | 3.054404 | 1.319351 |
if len(bases) > 1:
basis_rest = bases[0].product(*bases[1:])
else:
assert len(bases) == 1
basis_rest = bases[0]
labels_ops = [(b1l + b2l, qt.tensor(b1, b2)) for (b1l, b1), (b2l, b2) in
itertools.product(self, basis_rest)]
... | def product(self, *bases) | Compute the tensor product with another basis.
:param bases: One or more additional bases to form the product with.
:return (OperatorBasis): The tensor product basis as an OperatorBasis object. | 4.007391 | 3.60863 | 1.110502 |
labels_ops = [(bnl + "^T (x) " + bml, qt.sprepost(bm, bn)) for (bnl, bn), (bml, bm) in
itertools.product(self, self)]
return OperatorBasis(labels_ops) | def super_basis(self) | Generate the superoperator basis in which the Choi matrix can be represented.
The follows the definition in
`Chow et al. <https://doi.org/10.1103/PhysRevLett.109.060501>`_
:return (OperatorBasis): The super basis as an OperatorBasis object. | 18.373369 | 17.006174 | 1.080394 |
if not self.is_orthonormal(): # pragma no coverage
raise ValueError("project_op only implemented for orthonormal operator bases")
return self.basis_transform.H * qt.operator_to_vector(op).data | def project_op(self, op) | Project an operator onto the basis.
:param qutip.Qobj op: The operator to project.
:return: The projection coefficients as a numpy array.
:rtype: scipy.sparse.csr_matrix | 13.167946 | 10.787826 | 1.22063 |
if not self.is_orthonormal(): # pragma no coverage
raise ValueError("transfer_matrix() only implemented for orthonormal operator bases.")
return self.basis_transform.H * superoperator.data * self.basis_transform | def transfer_matrix(self, superoperator) | Compute the transfer matrix :math:`R_{jk} = \tr[P_j sop(P_k)]`.
:param qutip.Qobj superoperator: The superoperator to transform.
:return: The transfer matrix in sparse form.
:rtype: scipy.sparse.csr_matrix | 7.753423 | 8.423981 | 0.920399 |
if not self.is_orthonormal(): # pragma no coverage
raise ValueError("super_from_tm() only implemented for orthonormal operator bases")
data = self.basis_transform * transfer_matrix * self.basis_transform.H
sop = qt.Qobj(data, dims=[self.ops[0].dims, self.ops[0].dims])
... | def super_from_tm(self, transfer_matrix) | Reconstruct a super operator from a transfer matrix representation.
This inverts `self.transfer_matrix(...)`.
:param (numpy.ndarray) transfer_matrix: A process in transfer matrix form.
:return: A qutip super operator.
:rtype: qutip.Qobj. | 5.362558 | 5.198525 | 1.031554 |
rows, cols = matrix.shape
if rows != cols:
return False
return np.allclose(np.eye(rows), matrix.dot(matrix.T.conj())) | def is_unitary(matrix: np.ndarray) -> bool | A helper function that checks if a matrix is unitary.
:param matrix: a matrix to test unitarity of
:return: true if and only if matrix is unitary | 3.083483 | 3.296571 | 0.93536 |
return np.argwhere(np.asarray(lst) == 1)[0][0] | def most_significant_bit(lst: np.ndarray) -> int | A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,
i.e. the first position where a 1 appears, reading left to right.
:param lst: a 1d array of 0s and 1s with at least one 1
:return: the first position in lst that a 1 appears | 6.219416 | 5.655249 | 1.09976 |
if len(bs0) != len(bs1):
raise ValueError("Bit strings are not of equal length")
n_bits = len(bs0)
return PADDED_BINARY_BIT_STRING.format(xor(int(bs0, 2), int(bs1, 2)), n_bits) | def bitwise_xor(bs0: str, bs1: str) -> str | A helper to calculate the bitwise XOR of two bit string
:param bs0: String of 0's and 1's representing a number in binary representations
:param bs1: String of 0's and 1's representing a number in binary representations
:return: String of 0's and 1's representing the XOR between bs0 and bs1 | 3.697918 | 3.630961 | 1.018441 |
# iterate backwards, starting from second to last row for back-substitution
m = np.copy(s)
n = len(s)
for row_num in range(n - 2, -1, -1):
row = W[row_num]
for col_num in range(row_num + 1, n):
if row[col_num] == 1:
m[row_num] = xor(s[row_num], s[col_num]... | def binary_back_substitute(W: np.ndarray, s: np.ndarray) -> np.ndarray | Perform back substitution on a binary system of equations, i.e. it performs Gauss elimination
over the field :math:`GF(2)`. It finds an :math:`\\mathbf{x}` such that
:math:`\\mathbf{\\mathit{W}}\\mathbf{x}=\\mathbf{s}`, where all arithmetic is taken bitwise
and modulo 2.
:param W: A square :math:`n\\ti... | 3.404162 | 3.221508 | 1.056698 |
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) | def isclose(a, b, rel_tol=1e-10, abs_tol=0.0) | Compares two parameter values.
:param a: First parameter
:param b: Second parameter
:param rel_tol: Relative tolerance
:param abs_tol: Absolute tolerance
:return: Boolean telling whether or not the parameters are close enough to be the same | 1.786488 | 2.824766 | 0.632438 |
cost_operators = []
ref_operators = []
for ii in range(len(asset_list)):
for jj in range(ii + 1, len(asset_list)):
cost_operators.append(PauliSum([PauliTerm("Z", ii, 2*asset_list[ii]) *
PauliTerm("Z", jj, A*asset_list[jj])]))
ref_o... | def numpart_qaoa(asset_list, A=1.0, minimizer_kwargs=None, steps=1) | generate number partition driver and cost functions
:param asset_list: list to binary partition
:param A: (float) optional constant for level separation. Default=1.
:param minimizer_kwargs: Arguments for the QAOA minimizer
:param steps: (int) number of steps approximating the solution. | 2.636765 | 2.730442 | 0.965691 |
# encode oracle values into phase
phase_factor = np.exp(1.0j * 2 * np.pi * abs(f_h))
U = np.array([[phase_factor, 0],
[0, phase_factor]])
p_gradient = phase_estimation(U, precision)
return p_gradient | def gradient_program(f_h: float, precision: int) -> Program | Gradient estimation via Jordan's algorithm (10.1103/PhysRevLett.95.050501).
:param f_h: Oracle output at perturbation h.
:param precision: Bit precision of gradient.
:return: Quil program to estimate gradient of f. | 6.900042 | 5.737073 | 1.202711 |
# scale f_h by range of values gradient can take on
f_h *= 1. / gradient_max
# generate gradient program
perturbation_sign = np.sign(f_h)
p_gradient = gradient_program(f_h, precision)
# run gradient program
if qc is None:
qc = get_qc(f"{len(p_gradient.get_qubits())}q-qvm")
... | def estimate_gradient(f_h: float, precision: int,
gradient_max: int = 1,
n_measurements: int = 50,
qc: QuantumComputer = None) -> float | Estimate the gradient using function evaluation at perturbation, h.
:param f_h: Oracle output at perturbation h.
:param precision: Bit precision of gradient.
:param gradient_max: OOM estimate of largest gradient value.
:param n_measurements: Number of times to measure system.
:param qc: The Quantum... | 4.340205 | 4.190699 | 1.035676 |
c_jk_m = state_tomography._prepare_c_jk_m(readout_povm, pauli_basis, post_channel_ops)
pre_channel_transfer_matrices = [pauli_basis.transfer_matrix(qt.to_super(ek))
for ek in pre_channel_ops]
rho0_q = pauli_basis.project_op(rho0)
# These next lines hide some ve... | def _prepare_b_jkl_mn(readout_povm, pauli_basis, pre_channel_ops, post_channel_ops, rho0) | Prepare the coefficient matrix for process tomography. This function uses sparse matrices
for much greater efficiency. The coefficient matrix is defined as:
.. math::
B_{(jkl)(mn)}=\sum_{r,q}\pi_{jr}(\mathcal{R}_{k})_{rm} (\mathcal{R}_{l})_{nq} (\rho_0)_q
where :math:`\mathcal{R}_{k}` is the ... | 8.180702 | 8.09517 | 1.010566 |
if qubits is None:
qubits = process.get_qubits()
for tomographic_pre_rotation in pre_rotation_generator(*qubits):
for tomography_post_rotation in post_rotation_generator(*qubits):
process_tomography_program = Program(Pragma("PRESERVE_BLOCK"))
process_tomography_progr... | def process_tomography_programs(process, qubits=None,
pre_rotation_generator=tomography.default_rotations,
post_rotation_generator=tomography.default_rotations) | Generator that yields tomographic sequences that wrap a process encoded by a QUIL program `proc`
in tomographic rotations on the specified `qubits`.
If `qubits is None`, it assumes all qubits in the program should be
tomographically rotated.
:param Program process: A Quil program
:param list|NoneT... | 2.09034 | 2.013873 | 1.03797 |
return tomography._do_tomography(process, nsamples, cxn, qubits,
tomography.MAX_QUBITS_PROCESS_TOMO,
ProcessTomography, process_tomography_programs,
DEFAULT_PROCESS_TOMO_SETTINGS, use_run=use_run) | def do_process_tomography(process, nsamples, cxn, qubits=None, use_run=False) | Method to perform a process tomography.
:param Program process: Process to execute.
:param int nsamples: Number of samples to take for the program.
:param QVMConnection|QPUConnection cxn: Connection on which to run the program.
:param list qubits: List of qubits for the program.
to use in the tomog... | 5.337957 | 6.975687 | 0.765223 |
nqc = len(pre_channel_ops[0].dims[0])
pauli_basis = grove.tomography.operator_utils.PAULI_BASIS ** nqc
pi_basis = readout_povm.pi_basis
if not histograms.shape[-1] == pi_basis.dim: # pragma no coverage
raise ValueError("Currently tomography is only implemented for ... | def estimate_from_ssr(histograms, readout_povm, pre_channel_ops, post_channel_ops, settings) | Estimate a quantum process from single shot histograms obtained by preparing specific input
states and measuring bitstrings in the Z-eigenbasis after application of given channel
operators.
:param numpy.ndarray histograms: The single shot histograms.
:param DiagonalPOVM readout_povm: Th... | 4.596108 | 4.500054 | 1.021345 |
if isinstance(reference_unitary, qt.Qobj):
if not reference_unitary.issuper or reference_unitary.superrep != "super":
sother = qt.to_super(reference_unitary)
else:
sother = reference_unitary
tm_other = self.pauli_basis.transfer_matrix(... | def process_fidelity(self, reference_unitary) | Compute the quantum process fidelity of the estimated state with respect to a unitary
process. For non-sparse reference_unitary, this implementation this will be expensive in
higher dimensions.
:param (qutip.Qobj|matrix-like) reference_unitary: A unitary operator that induces a process
... | 4.750783 | 4.456162 | 1.066115 |
process_fidelity = self.process_fidelity(reference_unitary)
dimension = self.pauli_basis.ops[0].shape[0]
return (dimension * process_fidelity + 1.0) / (dimension + 1.0) | def avg_gate_fidelity(self, reference_unitary) | Compute the average gate fidelity of the estimated process with respect to a unitary
process. See `Chow et al., 2012, <https://doi.org/10.1103/PhysRevLett.109.060501>`_
:param (qutip.Qobj|matrix-like) reference_unitary: A unitary operator that induces a process
as `rho -> other*rho*other.dag(... | 3.829417 | 4.456157 | 0.859354 |
return [k.data.toarray() for k in qt.to_kraus(self.sop)] | def to_kraus(self) | Compute the Kraus operator representation of the estimated process.
:return: The process as a list of Kraus operators.
:rytpe: List[np.array] | 11.087306 | 13.681363 | 0.810395 |
title = "Estimated process"
ut.plot_pauli_transfer_matrix(self.r_est, ax, self.pauli_basis.labels, title) | def plot_pauli_transfer_matrix(self, ax) | Plot the elements of the Pauli transfer matrix.
:param matplotlib.Axes ax: A matplotlib Axes object to plot into. | 8.185627 | 11.85125 | 0.690697 |
fig, (ax1) = plt.subplots(1, 1, figsize=(10, 8))
self.plot_pauli_transfer_matrix(ax1)
return fig | def plot(self) | Visualize the process.
:return: The generated figure.
:rtype: matplotlib.Figure | 4.599424 | 4.898166 | 0.93901 |
p = Program()
n = len(qubits)
for i in range(int(n / 2)):
p.inst(SWAP(qubits[i], qubits[-i - 1]))
return p | def bit_reversal(qubits: List[int]) -> Program | Generate a circuit to do bit reversal.
:param qubits: Qubits to do bit reversal with.
:return: A program to do bit reversal. | 2.874767 | 3.028387 | 0.949273 |
q = qubits[0]
qs = qubits[1:]
if 1 == len(qubits):
return [H(q)]
else:
n = 1 + len(qs)
cR = []
for idx, i in enumerate(range(n - 1, 0, -1)):
q_idx = qs[idx]
angle = math.pi / 2 ** (n - i)
cR.append(CPHASE(coeff * angle, q, q_i... | def _core_qft(qubits: List[int], coeff: int) -> Program | Generates the core program to perform the quantum Fourier transform
:param qubits: A list of qubit indexes.
:param coeff: A modifier for the angle used in rotations (-1 for inverse QFT, 1 for QFT)
:return: A Quil program to compute the core (inverse) QFT of the qubits. | 3.394872 | 3.223603 | 1.05313 |
p = Program().inst(_core_qft(qubits, 1))
return p + bit_reversal(qubits) | def qft(qubits: List[int]) -> Program | Generate a program to compute the quantum Fourier transform on a set of qubits.
:param qubits: A list of qubit indexes.
:return: A Quil program to compute the Fourier transform of the qubits. | 16.318125 | 17.448442 | 0.93522 |
qft_result = Program().inst(_core_qft(qubits, -1))
qft_result += bit_reversal(qubits)
inverse_qft = Program()
while len(qft_result) > 0:
new_inst = qft_result.pop()
inverse_qft.inst(new_inst)
return inverse_qft | def inverse_qft(qubits: List[int]) -> Program | Generate a program to compute the inverse quantum Fourier transform on a set of qubits.
:param qubits: A list of qubit indexes.
:return: A Quil program to compute the inverse Fourier transform of the qubits. | 4.181827 | 4.370807 | 0.956763 |
if not np.allclose([np.linalg.norm(state_vector)], [1]):
raise ValueError("Vector must be normalized")
if 2 ** get_bits_needed(len(state_vector)) != len(state_vector):
raise ValueError("Vector length must be a power of two and at least two")
mat = np.identity(len(state_vector), dtype... | def unitary_operator(state_vector) | Uses QR factorization to create a unitary operator
that can encode an arbitrary normalized vector into
the wavefunction of a quantum state.
Assumes that the state of the input qubits is to be expressed as
.. math::
(1, 0, \\ldots, 0)^T
:param 1d array state_vector: Normalized vector whos... | 3.27903 | 2.928354 | 1.119752 |
# normalize
norm_vector = vector / np.linalg.norm(vector)
# pad with zeros
num_bits = get_bits_needed(len(vector))
state_vector = np.zeros(2 ** num_bits, dtype=complex)
for i in range(len(vector)):
state_vector[i] = norm_vector[i]
return state_vector | def fix_norm_and_length(vector) | Create a normalized and zero padded version of vector.
:param 1darray vector: a vector with at least one nonzero component.
:return: a vector that is the normalized version of vector,
padded at the end with the smallest number of 0s necessary
to make the length of the vector :math:`2^... | 2.912073 | 3.180566 | 0.915583 |
assert n > 0, "Inout should be positive"
num_bits = int(np.ceil(np.log2(n)))
return max(1, num_bits) | def get_bits_needed(n) | Calculates the smallest positive integer :math:`m` for which
:math:`2^m\geq n`.
:param int n: A positive integer
:return: The positive integer :math:`m`, as specified above
:rtype: int | 5.173301 | 5.710428 | 0.905939 |
n_bits = len(dot_product_vector)
bit_map = {}
for bit_val in range(2 ** n_bits):
bit_map[np.binary_repr(bit_val, width=n_bits)] = str(
(int(utils.bitwise_dot_product(np.binary_repr(bit_val, width=n_bits),
dot_product_vector))
+... | def create_bv_bitmap(dot_product_vector: str, dot_product_bias: str) -> Dict[str, str] | This function creates a map from bitstring to function value for a boolean formula :math:`f`
with a dot product vector :math:`a` and a dot product bias :math:`b`
.. math::
f:\\{0,1\\}^n\\rightarrow \\{0,1\\}
\\mathbf{x}\\rightarrow \\mathbf{a}\\cdot\\mathbf{x}+b\\pmod{2}
... | 2.710725 | 2.797054 | 0.969136 |
n_bits = len(list(bitstring_map.keys())[0])
n_ancillas = 1
# We instantiate an empty matrix of size n_bits + 1 to encode the mapping from n qubits
# to one ancillas, which explains the additional +1 overhead.
# To construct the matrix we go through all possible state tr... | def _compute_unitary_oracle_matrix(bitstring_map: Dict[str, str]) -> Tuple[np.ndarray,
Dict[str, str]] | Computes the unitary matrix that encodes the oracle function used in the Bernstein-Vazirani
algorithm. It generates a dense matrix for a function :math:`f`
.. math::
f:\\{0,1\\}^n\\rightarrow \\{0,1\\}
\\mathbf{x}\\rightarrow \\mathbf{a}\\cdot\\mathbf{x}+b\\pmod{2}
... | 5.239434 | 5.079177 | 1.031552 |
unitary, _ = self._compute_unitary_oracle_matrix(bit_map)
full_bv_circuit = Program()
full_bv_circuit.defgate("BV-ORACLE", unitary)
# Put ancilla bit into minus state
full_bv_circuit.inst(X(self.ancilla), H(self.ancilla))
full_bv_circuit.inst([H(i) for i in se... | def _create_bv_circuit(self, bit_map: Dict[str, str]) -> Program | Implementation of the Bernstein-Vazirani Algorithm.
Given a list of input qubits and an ancilla bit, all initially in the
:math:`\\vert 0\\rangle` state, create a program that can find :math:`\\vec{a}` with one
query to the given oracle.
:param Dict[String, String] bit_map: truth-table... | 3.681065 | 3.636218 | 1.012333 |
# initialize all attributes
self.input_bitmap = bitstring_map
self.n_qubits = len(list(bitstring_map.keys())[0])
self.computational_qubits = list(range(self.n_qubits))
self.ancilla = self.n_qubits # is the highest index now.
# construct BV circuit
self.... | def run(self, qc: QuantumComputer, bitstring_map: Dict[str, str]) -> 'BernsteinVazirani' | Runs the Bernstein-Vazirani algorithm.
Given a connection to a QVM or QPU, find the :math:`\\mathbf{a}` and :math:`b` corresponding
to the function represented by the oracle function that will be constructed from the
bitstring map.
:param qc: connection to the QPU or QVM
:param... | 2.875813 | 2.819948 | 1.019811 |
if self.solution is None:
raise AssertionError("You need to `run` this algorithm first")
return self.solution | def get_solution(self) -> Tuple[str, str] | Returns the solution of the BV algorithm
:return: a tuple of string corresponding to the dot-product partner vector and the bias term
:rtype: Tuple[String, String] | 8.51535 | 9.209006 | 0.924676 |
if self.solution is None:
raise AssertionError("You need to `run` this algorithm first")
assert_map = create_bv_bitmap(*self.solution)
return all([assert_map[k] == v for k, v in self.input_bitmap.items()]) | def check_solution(self) -> bool | Checks if the the found solution correctly reproduces the input.
:return: True if solution correctly reproduces input bitstring map
:rtype: Bool | 9.493877 | 7.801595 | 1.216915 |
overlapping_active_qubits = set(pauli_a.get_qubits()) & set(pauli_b.get_qubits())
for qubit_index in overlapping_active_qubits:
if (pauli_a[qubit_index] != 'I' and pauli_b[qubit_index] != 'I' and
pauli_a[qubit_index] != pauli_b[qubit_index]):
return False
return True | def diagonal_basis_commutes(pauli_a, pauli_b) | Test if `pauli_a` and `pauli_b` share a diagonal basis
Example:
Check if [A, B] with the constraint that A & B must share a one-qubit
diagonalizing basis. If the inputs were [sZ(0), sZ(0) * sZ(1)] then this
function would return True. If the inputs were [sX(5), sZ(4)] this
functio... | 2.187293 | 2.268353 | 0.964265 |
qubit_ops = set(reduce(lambda x, y: x + y,
[list(term._ops.items()) for term in list_of_pauli_terms]))
qubit_ops = sorted(list(qubit_ops), key=lambda x: x[0])
return PauliTerm.from_list(list(map(lambda x: tuple(reversed(x)), qubit_ops))) | def get_diagonalizing_basis(list_of_pauli_terms) | Find the Pauli Term with the most non-identity terms
:param list_of_pauli_terms: List of Pauli terms to check
:return: The highest weight Pauli Term
:rtype: PauliTerm | 3.11195 | 3.391607 | 0.917544 |
# a lot of the ugliness comes from the fact that
# list(PauliTerm._ops.items()) is not the appropriate input for
# Pauliterm.from_list()
for key in list(diagonal_sets.keys()):
pauli_from_key = PauliTerm.from_list(
list(map(lambda x: tuple(reversed(x)), key)))
if diagonal... | def _max_key_overlap(pauli_term, diagonal_sets) | Calculate the max overlap of a pauli term ID with keys of diagonal_sets
Returns a different key if we find any collisions. If no collisions is
found then the pauli term is added and the key is updated so it has the
largest weight.
:param pauli_term:
:param diagonal_sets:
:return: dictionary w... | 4.011458 | 3.641475 | 1.101603 |
diagonal_sets = {}
for term in pauli_sums:
diagonal_sets = _max_key_overlap(term, diagonal_sets)
return diagonal_sets | def commuting_sets_by_zbasis(pauli_sums) | Computes commuting sets based on terms having the same diagonal basis
Following the technique outlined in the appendix of arXiv:1704.05018.
:param pauli_sums: PauliSum object to group
:return: dictionary where key value pair is a tuple corresponding to the
basis and a list of PauliTerms assoc... | 7.094287 | 7.894599 | 0.898625 |
if not isinstance(pauli_list, list):
raise TypeError("pauli_list should be a list")
for term in pauli_list:
if not _commutes(term, single_pauli_term):
return False
return True | def check_trivial_commutation(pauli_list, single_pauli_term) | Check if a PauliTerm trivially commutes with a list of other terms.
:param list pauli_list: A list of PauliTerm objects
:param PauliTerm single_pauli_term: A PauliTerm object
:returns: True if pauli_two object commutes with pauli_list, False otherwise
:rtype: bool | 2.540773 | 2.279662 | 1.114539 |
assert isinstance(pauli_sums, list)
group_inds = []
group_terms = []
for i, pauli_sum in enumerate(pauli_sums):
for j, term in enumerate(pauli_sum):
if len(group_inds) == 0:
# Initialization
group_inds.append([(i, j)])
group_terms... | def commuting_sets_by_indices(pauli_sums, commutation_check) | For a list of pauli sums, find commuting sets and keep track of which pauli sum they came from.
:param pauli_sums: A list of PauliSum
:param commutation_check: a function that checks if all elements of a list
and a single pauli term commute.
:return: A list of commuting sets. ... | 2.966714 | 2.902018 | 1.022293 |
if not isinstance(pauli_sum, (PauliTerm, PauliSum)):
raise TypeError("This method can only group PauliTerm or PauliSum objects")
if isinstance(pauli_sum, PauliTerm):
pauli_sum = PauliSum([pauli_sum])
commuting_terms = []
for term in pauli_sum:
# find the group that it triv... | def commuting_sets_trivial(pauli_sum) | Group a pauli term into commuting sets using trivial check
:param pauli_sum: PauliSum term
:return: list of lists containing individual Pauli Terms | 2.623217 | 2.591324 | 1.012308 |
ener_ising = 0
for elm in J.keys():
if elm[0] == elm[1]:
raise TypeError()
else:
ener_ising += J[elm] * int(sol[elm[0]]) * int(sol[elm[1]])
for i in range(len(h)):
ener_ising += h[i] * int(sol[i])
return ener_ising | def energy_value(h: List[Union[int, float]],
J: Dict[Tuple[int, int], Union[int, float]],
sol: List[int]) -> Union[int, float] | Obtain energy of an Ising solution for a given Ising problem (h,J).
:param h: External magnetic term of the Ising problem.
:param J: Interaction term of the Ising problem.
:param sol: Ising solution.
:return: Energy of the Ising string. | 2.771748 | 2.717578 | 1.019933 |
if len(register_a) != len(register_b):
raise RegisterSizeMismatch("registers involve different numbers of qubits")
if not isinstance(register_a, list):
raise TypeError("Register A needs to be list")
if not isinstance(register_b, list):
raise TypeError("Register B needs to be a ... | def swap_circuit_generator(register_a: List[int], register_b: List[int], ancilla: int) -> Program | Generate the swap test circuit primitive.
Registers A and B must be of equivalent size for swap to work. This module uses the CSWAP gate
in pyquil.
:param register_a: qubit labels in the 'A' register
:param register_b: qubit labels in the 'B' register
:param ancilla: ancilla to measure and contro... | 2.239498 | 2.333305 | 0.959796 |
cost_para_programs = []
driver_para_programs = []
for idx in range(self.steps):
cost_list = []
driver_list = []
for cost_pauli_sum in self.cost_ham:
for term in cost_pauli_sum.terms:
cost_list.append(exponential_ma... | def get_parameterized_program(self) | Return a function that accepts parameters and returns a new Quil program.
:returns: a function | 3.010519 | 2.959285 | 1.017313 |
stacked_params = np.hstack((self.betas, self.gammas))
vqe = VQE(self.minimizer, minimizer_args=self.minimizer_args,
minimizer_kwargs=self.minimizer_kwargs)
cost_ham = reduce(lambda x, y: x + y, self.cost_ham)
# maximizing the cost function!
param_prog =... | def get_angles(self) -> Tuple[List[float], List[float]] | Finds optimal angles with the quantum variational eigensolver method.
Stored VQE result
:returns: A tuple of the beta angles and the gamma angles for the optimal solution. | 3.880093 | 3.531331 | 1.098762 |
if isinstance(angles, list):
angles = np.array(angles)
assert angles.shape[0] == 2 * self.steps, "angles must be 2 * steps"
param_prog = self.get_parameterized_program()
prog = param_prog(angles)
wf = WavefunctionSimulator().wavefunction(prog)
wf = ... | def probabilities(self, angles: List[float]) -> np.ndarray | Computes the probability of each state given a particular set of angles.
:param angles: A concatenated list of angles [betas]+[gammas]
:return: The probabilities of each outcome given those angles. | 3.952916 | 4.018754 | 0.983617 |
if samples <= 0 and not isinstance(samples, int):
raise ValueError("samples variable must be positive integer")
param_prog = self.get_parameterized_program()
stacked_params = np.hstack((betas, gammas))
sampling_prog = Program()
ro = sampling_prog.declare('ro... | def get_string(self, betas: List[float], gammas: List[float], samples: int = 100) | Compute the most probable string.
The method assumes you have passed init_betas and init_gammas with your
pre-computed angles or you have run the VQE loop to determine the
angles. If you have not done this you will be returning the output for
a random set of angles.
:param bet... | 3.407905 | 3.053917 | 1.115913 |
n_bits = len(list(bitstring_map.keys())[0])
oracle_matrix = np.zeros(shape=(2 ** n_bits, 2 ** n_bits))
for b in range(2 ** n_bits):
pad_str = np.binary_repr(b, n_bits)
phase_factor = bitstring_map[pad_str]
oracle_matrix[b, b] = phase_factor
re... | def _compute_grover_oracle_matrix(bitstring_map: Dict[str, int]) -> np.ndarray | Computes the unitary matrix that encodes the oracle function for Grover's algorithm
:param bitstring_map: dict with string keys corresponding to bitstrings,
and integer values corresponding to the desired phase on the output state.
:return: a numpy array corresponding to the unitary matrix for... | 2.604465 | 2.489852 | 1.046032 |
oracle = Program()
oracle_name = "GROVER_ORACLE"
oracle.defgate(oracle_name, self.unitary_function_mapping)
oracle.inst(tuple([oracle_name] + self.qubits))
self.grover_circuit = self.oracle_grover(oracle, self.qubits) | def _construct_grover_circuit(self) -> None | Constructs an instance of Grover's Algorithm, using initialized values.
:return: None | 5.690984 | 5.827217 | 0.976621 |
self.bit_map = bitstring_map
self.unitary_function_mapping = self._compute_grover_oracle_matrix(bitstring_map)
self.n_qubits = self.unitary_function_mapping.shape[0]
self.qubits = list(range(int(np.log2(self.n_qubits))))
self._construct_grover_circuit() | def _init_attr(self, bitstring_map: Dict[str, int]) -> None | Initializes an instance of Grover's Algorithm given a bitstring_map.
:param bitstring_map: dict with string keys corresponding to bitstrings, and integer
values corresponding to the desired phase on the output state.
:type bitstring_map: Dict[String, Int]
:return: None | 4.047122 | 3.446283 | 1.174344 |
self._init_attr(bitstring_map)
ro = self.grover_circuit.declare('ro', 'BIT', len(self.qubits))
self.grover_circuit += [MEASURE(qubit, ro[idx]) for idx, qubit in enumerate(self.qubits)]
executable = qc.compile(self.grover_circuit)
sampled_bitstring = qc.run(executable)
... | def find_bitstring(self, qc: QuantumComputer, bitstring_map: Dict[str, int]) -> str | Runs Grover's Algorithm to find the bitstring that is designated by ``bistring_map``.
In particular, this will prepare an initial state in the uniform superposition over all bit-
strings, an then use Grover's Algorithm to pick out the desired bitstring.
:param qc: the connection to the Rigetti... | 3.669801 | 3.707505 | 0.98983 |
if num_iter is None:
num_iter = int(round(np.pi * 2 ** (len(qubits) / 2.0 - 2.0)))
uniform_superimposer = Program().inst([H(qubit) for qubit in qubits])
amp_prog = amplification_circuit(uniform_superimposer, oracle, qubits, num_iter)
return amp_prog | def oracle_grover(oracle: Program, qubits: List[int], num_iter: int = None) -> Program | Implementation of Grover's Algorithm for a given oracle.
:param oracle: An oracle defined as a Program. It should send :math:`\ket{x}`
to :math:`(-1)^{f(x)}\ket{x}`, where the range of f is {0, 1}.
:param qubits: List of qubits for Grover's Algorithm.
:param num_iter: The number of ... | 3.92029 | 3.812922 | 1.028159 |
M = np.full((2 ** k, 2 ** k), 2 ** -k)
for i in range(2 ** k):
g_i = i ^ (i >> 1) # Gray code for i
for j in range(2 ** k):
M[i, j] *= (-1) ** (bin(j & g_i).count("1"))
return M | def get_uniformly_controlled_rotation_matrix(k) | Returns the matrix represented by :math:`M_{ij}` in arXiv:quant-ph/0407010.
This matrix converts the angles of :math:`k`-fold uniformly
controlled rotations to the angles of the efficient gate decomposition.
:param int k: number of control qubits
:return: the matrix :math:`M_{ij}`
:rtype: 2darray | 3.741431 | 4.089416 | 0.914906 |
rotation_cnots = [1, 1]
for i in range(2, k + 1):
# algorithm described is to replace the last control
# with a control to the new qubit
# and then repeat the sequence twice
rotation_cnots[-1] = i
rotation_cnots = rotation_cnots + rotation_cnots
return rotation_c... | def get_cnot_control_positions(k) | Returns a list of positions for the controls of the CNOTs used when
decomposing uniformly controlled rotations, as outlined in
arXiv:quant-ph/0407010.
Referencing Fig. 2 in the aforementioned paper, this method
uses the convention that, going up from the target qubit,
the control qubits are labelle... | 5.512309 | 5.50036 | 1.002173 |
# will hold the angles for controlled rotations
# in the phase unification and probability unification steps,
# respectively
z_thetas = []
y_thetas = []
# will hold updated phases and magnitudes after rotations
new_phases = []
new_magnitudes = []
for i in range(0, len(phases),... | def get_rotation_parameters(phases, magnitudes) | Simulates one step of rotations.
Given lists of phases and magnitudes of the same length :math:`N`,
such that :math:`N=2^n` for some positive integer :math:`n`,
finds the rotation angles required for one step of phase and magnitude
unification.
:param list phases: real valued phases from :math:`-\... | 2.996522 | 2.636771 | 1.136436 |
if mode == 'phase':
gate = RZ
elif mode == 'magnitude':
gate = RY
else:
raise ValueError("mode must be \'phase\' or \'magnitude\'")
reversed_gates = []
for j in range(len(angles)):
if angles[j] != 0:
# angle is negated in conjugated/reversed circuit... | def get_reversed_unification_program(angles, control_indices,
target, controls, mode) | Gets the Program representing the reversed circuit
for the decomposition of the uniformly controlled
rotations in a unification step.
If :math:`n` is the number of controls, the indices within control indices
must range from 1 to :math:`n`, inclusive. The length of control_indices
and the length of... | 3.547174 | 3.053188 | 1.161794 |
node = self
ancestor_list = []
while node.parent is not None:
ancestor_list.append(node.parent)
node = node.parent
return ancestor_list | def get_ancestors(self) | Returns a list of ancestors of the node. Ordered from the earliest.
:return: node's ancestors, ordered from most recent
:rtype: list(FenwickNode) | 2.445113 | 2.784186 | 0.878215 |
result = []
ancestors = self.get_update_set(j)
# This runs in O(log(N)log(N)) where N is the number of qubits.
for a in ancestors:
for c in a.children:
if c.index < j:
result.append(c)
return result | def get_remainder_set(self, j) | Return the set of children with indices less than j of all ancestors
of j. The set C from (arXiv:1701.07072).
:param int j: fermionic site index
:return: children of j-ancestors, with indices less than j
:rtype: list(FenwickNode) | 5.379706 | 4.004251 | 1.343499 |
if len(bs0) != len(bs1):
raise ValueError("Bit strings are not of equal length")
return str(sum([int(bs0[i]) * int(bs1[i]) for i in range(len(bs0))]) % 2) | def bitwise_dot_product(bs0: str, bs1: str) -> str | A helper to calculate the bitwise dot-product between two string representing bit-vectors
:param bs0: String of 0's and 1's representing a number in binary representations
:param bs1: String of 0's and 1's representing a number in binary representations
:return: 0 or 1 as a string corresponding to the dot-... | 2.312445 | 2.384437 | 0.969807 |
global _QUTIP_ERROR_LOGGED
try:
import qutip
except ImportError: # pragma no coverage
qutip = None
if not _QUTIP_ERROR_LOGGED:
_log.error("Could not import qutip. Tomography tools will not function.")
_QUTIP_ERROR_LOGGED = True
return qutip | def import_qutip() | Try importing the qutip module, log an error if unsuccessful.
:return: The qutip module if successful or None
:rtype: Optional[module] | 3.195686 | 3.19128 | 1.001381 |
global _CVXPY_ERROR_LOGGED
try:
import cvxpy
except ImportError: # pragma no coverage
cvxpy = None
if not _CVXPY_ERROR_LOGGED:
_log.error("Could not import cvxpy. Tomography tools will not function.")
_CVXPY_ERROR_LOGGED = True
return cvxpy | def import_cvxpy() | Try importing the qutip module, log an error if unsuccessful.
:return: The cvxpy module if successful or None
:rtype: Optional[module] | 3.470099 | 3.478014 | 0.997724 |
global NOTEBOOK_MODE
global TRANGE
NOTEBOOK_MODE = m
if NOTEBOOK_MODE:
TRANGE = tqdm.tnrange
else:
TRANGE = tqdm.trange | def notebook_mode(m) | Configure whether this module should assume that it is being run from a jupyter notebook.
This sets some global variables related to how progress for long measurement sequences is
indicated.
:param bool m: If True, assume to be in notebook.
:return: None
:rtype: NoneType | 5.753413 | 5.223889 | 1.101366 |
dist = np.cumsum(probs)
rs = np.random.rand(n)
return np.array([(np.where(r < dist)[0][0]) for r in rs]) | def sample_outcomes(probs, n) | For a discrete probability distribution ``probs`` with outcomes 0, 1, ..., k-1 draw ``n``
random samples.
:param list probs: A list of probabilities.
:param Number n: The number of random samples to draw.
:return: An array of samples drawn from distribution probs over 0, ..., len(probs) - 1
:rtype:... | 3.577672 | 4.181709 | 0.855553 |
for prep in cartesian_product([I, X], repeat=len(qubits)):
basis_prep = Program(Pragma("PRESERVE_BLOCK"))
for gate, qubit in zip(prep, qubits):
basis_prep.inst(gate(qubit))
basis_prep.inst(Pragma("END_PRESERVE_BLOCK"))
yield basis_prep | def basis_state_preps(*qubits) | Generate a sequence of programs that prepares the measurement
basis states of some set of qubits in the order such that the qubit
with highest index is iterated over the most quickly:
E.g., for ``qubits=(0, 1)``, it returns the circuits::
I_0 I_1
I_0 X_1
X_0 I_1
X_0 X_1
... | 3.630756 | 3.477125 | 1.044183 |
wf = cxn.wavefunction(program)
return sample_outcomes(assignment_probs.dot(abs(wf.amplitudes.ravel())**2), num_samples) | def sample_bad_readout(program, num_samples, assignment_probs, cxn) | Generate `n` samples of measuring all outcomes of a Quil `program`
assuming the assignment probabilities `assignment_probs` by simulating the
wave function on a qvm QVMConnection `cxn`
:param pyquil.quil.Program program: The program.
:param int num_samples: The number of samples
:param numpy.ndarra... | 9.98302 | 7.850864 | 1.271582 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.