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 readout_povm.ops]) # Dict used for constructing our sparse matrix, keys are tuples (row_index, col_index), values # are the non-zero elements of the final matrix. c_jk_m_elms = {} # This explicitly exploits the sparsity of all operators involved for k in range(len(channel_ops)): pi_jr__rk_rm = (pi_jr * channel_transfer_matrices[k]).tocoo() for (j, m, val) in ut.izip(pi_jr__rk_rm.row, pi_jr__rk_rm.col, pi_jr__rk_rm.data): # The multi-index (j,k) is enumerated in column-major ordering (like Fortran arrays) c_jk_m_elms[(j + k * readout_povm.pi_basis.dim, m)] = val.real # create sparse matrix from COO-format (see scipy.sparse docs) _keys, _values = ut.izip(*c_jk_m_elms.items()) _rows, _cols = ut.izip(*_keys) c_jk_m = coo_matrix((list(_values), (list(_rows), list(_cols))), shape=(readout_povm.pi_basis.dim * len(channel_ops), pauli_basis.dim)).tocsr() return c_jk_m
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 quantum map corresponding to the k-th pre-measurement channel, i.e., :math:`\Lambda_k(\rho) = E_k \rho E_k^\dagger` where :math:`E_k` is the k-th channel operator. This map can also be represented via its transfer matrix :math:`\mathcal{R}_{k}`. In that case one also requires the overlap between the (generalized) Pauli basis ops and the projection operators :math:`\pi_{jl}:=\sbraket{\Pi_j}{P_l} = \tr{\Pi_j P_l}`. See the grove documentation on tomography for detailed information. :param DiagonalPOVM readout_povm: The POVM corresponding to the readout plus classifier. :param OperatorBasis pauli_basis: The (generalized) Pauli basis employed in the estimation. :param list channel_ops: The pre-measurement channel operators as `qutip.Qobj` :return: The coefficient matrix necessary to set up the binomial state tomography problem. :rtype: scipy.sparse.csr_matrix
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_tomography_program.inst(Pragma("END_PRESERVE_BLOCK")) yield state_tomography_program
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 tomographed. :param list|NoneType qubits: A list of Qubits or Numbers, to perform the tomography on. If `None`, performs it on all in state_prep. :param generator rotation_generator: A generator that yields tomography rotations to perform. :return: Program for state tomography. :rtype: Program
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 on which to run the program. :param list qubits: List of qubits for the program. to use in the tomography analysis. :param bool use_run: If ``True``, use append measurements on all qubits and use ``cxn.run`` instead of ``cxn.run_and_measure``. :return: The state tomogram. :rtype: StateTomography
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-level systems.") # prepare the log-likelihood function parameters, see documentation n_kj = np.asarray(histograms) c_jk_m = _prepare_c_jk_m(readout_povm, pauli_basis, channel_ops) rho_m = cvxpy.Variable(pauli_basis.dim) p_jk = c_jk_m * rho_m obj = -n_kj.ravel() * cvxpy.log(p_jk) p_jk_mat = cvxpy.reshape(p_jk, pi_basis.dim, len(channel_ops)) # cvxpy has col-major order # Default constraints: # MLE must describe valid probability distribution # i.e., for each k, p_jk must sum to one and be element-wise non-negative: # 1. \sum_j p_jk == 1 for all k # 2. p_jk >= 0 for all j, k # where p_jk = \sum_m c_jk_m rho_m constraints = [ p_jk >= 0, np.matrix(np.ones((1, pi_basis.dim))) * p_jk_mat == 1, ] rho_m_real_imag = sum((rm * o_ut.to_realimag(Pm) for (rm, Pm) in ut.izip(rho_m, pauli_basis.ops)), 0) if POSITIVE in settings.constraints: if tomography._SDP_SOLVER.is_functional(): constraints.append(rho_m_real_imag >> 0) else: # pragma no coverage _log.warning("No convex solver capable of semi-definite problems installed.\n" "Dropping the positivity constraint on the density matrix.") if UNIT_TRACE in settings.constraints: # this assumes that the first element of the Pauli basis is always proportional to # the identity constraints.append(rho_m[0, 0] == 1. / pauli_basis.ops[0].tr().real) prob = cvxpy.Problem(cvxpy.Minimize(obj), constraints) _log.info("Starting convex solver") prob.solve(solver=tomography.SOLVER, **settings.solver_kwargs) if prob.status != cvxpy.OPTIMAL: # pragma no coverage _log.warning("Problem did not converge to optimal solution. " "Solver settings: {}".format(settings.solver_kwargs)) return StateTomography(np.array(rho_m.value).ravel(), pauli_basis, settings)
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 corresponding to the readout plus classifier. :param list channel_ops: The tomography measurement channels as `qutip.Qobj`'s. :param TomographySettings settings: The solver and estimation settings. :return: The generated StateTomography object. :rtype: StateTomography
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) returned_bitstring = qc.run(executable) # We are only running a single shot, so we are only interested in the first element. bitstring = np.array(returned_bitstring, dtype=int) constant = all([bit == 0 for bit in bitstring]) return constant
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 cloud to run pyQuil programs. :param bitstring_map: A dictionary whose keys are bitstrings, and whose values are bits represented as strings. :type bistring_map: Dict[String, String] :return: True if the bitstring_map represented a constant function, false otherwise. :rtype: bool
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)) self.computational_qubits = self._qubits[:self.n_qubits] self.ancillas = self._qubits[self.n_qubits:] self.unitary_matrix = self.unitary_function(bitstring_map) self.deutsch_jozsa_circuit = self._construct_deutsch_jozsa_circuit()
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 oracle oracle_prog = Program() oracle_prog.defgate(ORACLE_GATE_NAME, self.unitary_matrix) scratch_bit = self.ancillas[1] qubits_for_funct = [scratch_bit] + self.computational_qubits oracle_prog.inst(tuple([ORACLE_GATE_NAME] + qubits_for_funct)) dj_prog += oracle_prog # Here the oracle does not leave the computational qubits unchanged, so we use a CNOT to # to move the result to the query qubit, and then we uncompute with the dagger. dj_prog.inst(CNOT(self._qubits[0], self.ancillas[0])) dj_prog += oracle_prog.dagger() dj_prog.inst([H(qubit) for qubit in self.computational_qubits]) return dj_prog
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 == 2 ** (num_qubits - 1): unitary_funct = np.zeros(shape=(2 ** num_qubits, 2 ** num_qubits)) index_lists = [list(range(2 ** (num_qubits - 1))), list(range(2 ** (num_qubits - 1), 2 ** num_qubits))] for j in range(2 ** num_qubits): bitstring = np.binary_repr(j, num_qubits) value = int(mappings[bitstring]) mappings.pop(bitstring) i = index_lists[value].pop() unitary_funct[i, j] = 1 return np.kron(np.identity(2), unitary_funct) # Only ones were entered elif bitsum == 2 ** num_qubits: x_gate = np.array([[0, 1], [1, 0]]) return np.kron(SWAP_MATRIX, np.identity(2 ** (num_qubits - 1))).dot( np.kron(x_gate, np.identity(2 ** num_qubits))) else: raise ValueError("f(x) must be constant or balanced")
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, where the 0th is the scratch bit and the return value of the function is left in the 1st. :param mappings: Dictionary of the mappings of f(x) on all length n bitstrings, e.g. >>> {'00': '0', '01': '1', '10': '1', '11': '0'} :return: ndarray representing specified unitary transformation.
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(qubits[0])) return oracle_prog else: bitflip_prog = Program() for i, qubit in enumerate(qubits): if bitstring[i] == '0': bitflip_prog.inst(X(qubit)) oracle_prog += bitflip_prog controls = qubits[:-1] target = qubits[-1] operation = np.array([[1, 0], [0, -1]]) gate_name = 'Z' n_qubit_controlled_z = (ControlledProgramBuilder() .with_controls(controls) .with_target(target) .with_operation(operation) .with_gate_name(gate_name) .build()) oracle_prog += n_qubit_controlled_z oracle_prog += bitflip_prog return oracle_prog
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 to least significant qubit. :param bitstring: The desired bitstring, given as a string of ones and zeros. e.g. "101" :return: A program representing this oracle.
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 >= 0).all() or not (confusion_rate_matrix <= 1).all(): raise CRMValueError("Confusion matrix must have values in [0, 1]:" "\n{}".format(confusion_rate_matrix)) ops = [sum((pi_j * pjk for (pi_j, pjk) in izip(pi_basis.ops, pjs)), 0) for pjs in confusion_rate_matrix] return DiagonalPOVM(pi_basis=pi_basis, confusion_rate_matrix=confusion_rate_matrix, ops=ops)
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 conditional on a prepared qubit state. :return: The POVM corresponding to confusion_rate_matrix. :rtype: DiagonalPOVM
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(operator) < EPS
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 = basis.dim choi = sum((pauli_tm[jj, kk] * sbasis.ops[jj + kk * D] for jj in range(D) for kk in range(D))) choi.superrep = CHOI return choi
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: The Pauli Transfer Matrix as 2d-array. :param OperatorBasis basis: The operator basis, typically products of normalized Paulis. :return: The Choi matrix as qutip.Qobj. :rtype: qutip.Qobj
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 isomorphically represented in doubled up form as:: R(Z) = [ Z_r Z_i] [-Z_i Z_r] R(X)*R(Y) = [ (X_r*Y_r-X_i*Y_i) (X_r*Y_i + X_i*Y_r)] [-(X_r*Y_i + X_i*Y_r) (X_r*Y_r-X_i*Y_i) ] = R(X*Y). In particular, ``Z`` is complex positive (semi-)definite iff ``R(Z)`` is real positive (semi-)definite. :param (qutip.Qobj|scipy.sparse.base.spmatrix) z: The operator representation matrix. :returns: R(Z) the doubled up representation. :rtype: scipy.sparse.csr_matrix
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)] return OperatorBasis(labels_ops)
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]) sop.superrep = "super" return sop
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]) return m[::-1]
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\\times n` matrix of 0s and 1s, in row-echelon (upper-triangle) form :param s: An :math:`n\\times 1` vector of 0s and 1s :return: The :math:`n\\times 1` vector of 0s and 1s that solves the above system of equations.
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_operators.append(PauliSum([PauliTerm("X", ii, -1.0)])) cost_operators.append(PauliSum([PauliTerm("I", 0, len(asset_list))])) if minimizer_kwargs is None: minimizer_kwargs = {'method': 'Nelder-Mead', 'options': {'ftol': 1.0e-2, 'xtol': 1.0e-2, 'disp': True}} qc = get_qc(f"{len(asset_list)}q-qvm") qaoa_inst = QAOA(qc, list(range(len(asset_list))), steps=steps, cost_ham=cost_operators, ref_ham=ref_operators, store_basis=True, minimizer=minimize, minimizer_kwargs=minimizer_kwargs, vqe_options={'disp': print}) return qaoa_inst
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") p_gradient.wrap_in_numshots_loop(n_measurements) executable = qc.compiler.native_quil_to_executable(p_gradient) measurements = qc.run(executable) # summarize measurements bf_estimate = perturbation_sign * measurements_to_bf(measurements) bf_explicit = '{0:.16f}'.format(bf_estimate) deci_estimate = binary_float_to_decimal_float(bf_explicit) # rescale gradient deci_estimate *= gradient_max return deci_estimate
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 QuantumComputer object. :return: Decimal estimate of gradient.
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 very serious (sparse-)matrix index magic, # basically we exploit the same index math as in `qutip.sprepost()` # i.e., if a matrix X is linearly mapped `X -> A.dot(X).dot(B)` # then this can be rewritten as # `np.kron(B.T, A).dot(X.T.ravel()).reshape((B.shape[1], A.shape[0])).T` # The extra matrix transpose operations are necessary because numpy by default # uses row-major storage, whereas these operations are conventionally defined for column-major # storage. d_ln = spvstack([(rlnq * rho0_q).T for rlnq in pre_channel_transfer_matrices]).tocoo() b_jkl_mn = spkron(d_ln, c_jk_m).real return b_jkl_mn
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 transfer matrix of the quantum map corresponding to the k-th pre-measurement channel, while :math:`\mathcal{R}_{l}` is the transfer matrix of the l-th state preparation process. We also require the overlap between the (generalized) Pauli basis ops and the projection operators :math:`\pi_{jl}:=\sbraket{\Pi_j}{P_l} = \tr{\Pi_j P_l}`. See the grove documentation on tomography for detailed information. :param DiagonalPOVM readout_povm: The POVM corresponding to the readout plus classifier. :param OperatorBasis pauli_basis: The (generalized) Pauli basis employed in the estimation. :param list pre_channel_ops: The state preparation channel operators as `qutip.Qobj` :param list post_channel_ops: The pre-measurement (post circuit) channel operators as `qutip.Qobj` :param qutip.Qobj rho0: The initial state as a density matrix. :return: The coefficient matrix necessary to set up the binomial state tomography problem. :rtype: scipy.sparse.csr_matrix
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_program.inst(tomographic_pre_rotation) process_tomography_program.inst(process) process_tomography_program.inst(tomography_post_rotation) process_tomography_program.inst(Pragma("END_PRESERVE_BLOCK")) yield process_tomography_program
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|NoneType qubits: The specific qubits for which to generate the tomographic sequences :param pre_rotation_generator: A generator that yields tomographic pre-rotations to perform. :param post_rotation_generator: A generator that yields tomographic post-rotations to perform. :return: Program for process tomography. :rtype: Program
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 tomography analysis. :param bool use_run: If ``True``, use append measurements on all qubits and use ``cxn.run`` instead of ``cxn.run_and_measure``. :return: The process tomogram :rtype: ProcessTomography
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 two-level systems") rho0 = grove.tomography.operator_utils.n_qubit_ground_state(nqc) n_lkj = np.asarray(histograms) b_jkl_mn = _prepare_b_jkl_mn(readout_povm, pauli_basis, pre_channel_ops, post_channel_ops, rho0) r_mn = cvxpy.Variable(pauli_basis.dim ** 2) p_jkl = b_jkl_mn.real * r_mn obj = -np.matrix(n_lkj.ravel()) * cvxpy.log(p_jkl) # cvxpy has col-major order and we collapse k and l onto single dimension p_jkl_mat = cvxpy.reshape(p_jkl, pi_basis.dim, len(pre_channel_ops) * len(post_channel_ops)) # Default constraints: # MLE must describe valid probability distribution # i.e., for each k and l, p_jkl must sum to one and be element-wise non-negative: # 1. \sum_j p_jkl == 1 for all k, l # 2. p_jkl >= 0 for all j, k, l # where p_jkl = \sum_m b_jkl_mn r_mn constraints = [p_jkl >= 0, np.matrix(np.ones((1, pi_basis.dim))) * p_jkl_mat == 1] r_mn_mat = cvxpy.reshape(r_mn, pauli_basis.dim, pauli_basis.dim) super_pauli_basis = pauli_basis.super_basis() choi_real_imag = sum((r_mn_mat[jj, kk] * o_ut.to_realimag( super_pauli_basis.ops[jj + kk * pauli_basis.dim]) for jj in range(pauli_basis.dim) for kk in range(pauli_basis.dim)), 0) if COMPLETELY_POSITIVE in settings.constraints: if tomography._SDP_SOLVER.is_functional(): constraints.append(choi_real_imag >> 0) else: # pragma no coverage _log.warning("No convex solver capable of semi-definite problems installed.\n" "Dropping the complete positivity constraint on the process") if TRACE_PRESERVING in settings.constraints: constraints.append(r_mn_mat[0, 0] == 1) constraints.append(r_mn_mat[0, 1:] == 0) prob = cvxpy.Problem(cvxpy.Minimize(obj), constraints) _ = prob.solve(solver=tomography.SOLVER, **settings.solver_kwargs) r_mn_est = r_mn.value.reshape((pauli_basis.dim, pauli_basis.dim)).transpose() return ProcessTomography(r_mn_est, pauli_basis, settings)
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: The POVM corresponding to readout plus classifier. :param list pre_channel_ops: The input state preparation channels as `qutip.Qobj`'s. :param list post_channel_ops: The tomography post-process channels as `qutip.Qobj`'s. :param TomographySettings settings: The solver and estimation settings. :return: The ProcessTomography object and results from the the given data. :rtype: ProcessTomography
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(sother) else: tm_other = csr_matrix(reference_unitary) dimension = self.pauli_basis.ops[0].shape[0] return np.trace(tm_other.T * self.r_est).real / dimension ** 2
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 as ``rho -> other*rho*other.dag()``, can also be a superoperator or Pauli-transfer matrix. :return: The process fidelity, a real number between 0 and 1. :rtype: float
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()`, alternatively a superoperator or Pauli-transfer matrix. :return: The average gate fidelity, a real number between 1/(d+1) and 1, where d is the Hilbert space dimension. :rtype: float
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_idx)) return _core_qft(qs, coeff) + list(reversed(cR)) + [H(q)]
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=complex) for i in range(len(state_vector)): mat[i, 0] = state_vector[i] U = np.linalg.qr(mat)[0] # make sure U|0> = |v> zero_state = np.zeros(len(U)) zero_state[0] = 1 if np.allclose(U.dot(zero_state), state_vector): return U else: # adjust phase if needed return -1 * U
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 whose length is at least two and a power of two. :return: Unitary operator that encodes state_vector :rtype: 2d array
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^m` for some positive integer :math:`m`. :rtype: 1darray
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)) + int(dot_product_bias, 2)) % 2 ) return bit_map
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} (\\mathbf{a}\\in\\{0,1\\}^n, b\\in\\{0,1\\}) :param dot_product_vector: a string of 0's and 1's that represents the dot-product partner in :math:`f` :param dot_product_bias: 0 or 1 as a string representing the bias term in :math:`f` :return: A dictionary containing all possible bitstring of length equal to :math:`a` and the function value :math:`f`
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 transitions and pad the index # according to all possible states the ancilla-subsystem could be in ufunc = np.zeros(shape=(2 ** (n_bits + 1), 2 ** (n_bits + 1))) index_mapping_dct = defaultdict(dict) for b in range(2**n_ancillas): # padding according to ancilla state pad_str = np.binary_repr(b, width=1) for k, v in bitstring_map.items(): # add mapping from initial state to the state in the ancilla system. # pad_str corresponds to the initial state of the ancilla system. index_mapping_dct[pad_str + k] = utils.bitwise_xor(pad_str, v) + k # calculate matrix indices that correspond to the transition-matrix-element # of the oracle unitary i, j = int(pad_str+k, 2), int(utils.bitwise_xor(pad_str, v) + k, 2) ufunc[i, j] = 1 return ufunc, index_mapping_dct
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} (\\mathbf{a}\\in\\{0,1\\}^n, b\\in\\{0,1\\}) where :math:`(\\cdot)` is the bitwise dot product, that represents the transition-matrix elements of the corresponding qubit and ancilla subsystems. :param Dict[String, String] bitstring_map: truth-table of the input bitstring map in dictionary format :return: a dense matrix containing the permutation of the bit strings and a dictionary containing the indices of the non-zero elements of the computed permutation matrix as key-value-pairs :rtype: Tuple[2darray, Dict[String, String]]
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 self.computational_qubits]) full_bv_circuit.inst( tuple(["BV-ORACLE"] + sorted(self.computational_qubits + [self.ancilla], reverse=True))) full_bv_circuit.inst([H(i) for i in self.computational_qubits]) return full_bv_circuit
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 of a function for Bernstein-Vazirani with the keys being all possible bit vectors strings and the values being the function values :rtype: Program
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.bv_circuit = self._create_bv_circuit(bitstring_map) # find vector by running the full bv circuit full_circuit = Program() full_ro = full_circuit.declare('ro', 'BIT', len(self.computational_qubits) + 1) full_circuit += self.bv_circuit full_circuit += [MEASURE(qubit, ro) for qubit, ro in zip(self.computational_qubits, full_ro)] full_executable = qc.compile(full_circuit) full_results = qc.run(full_executable) bv_vector = full_results[0][::-1] # To get the bias term we skip the Walsh-Hadamard transform ancilla_circuit = Program() ancilla_ro = ancilla_circuit.declare('ro', 'BIT', len(self.computational_qubits) + 1) ancilla_circuit += self.bv_circuit ancilla_circuit += [MEASURE(self.ancilla, ancilla_ro[self.ancilla])] ancilla_executable = qc.compile(ancilla_circuit) ancilla_results = qc.run(ancilla_executable) bv_bias = ancilla_results[0][0] self.solution = ''.join([str(b) for b in bv_vector]), str(bv_bias) return 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 bitstring_map: a truth table describing the boolean function, whose dot-product vector and bias is to be found
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 function would return True. If the inputs were [sX(0), sY(0) * sZ(2)] this function would return False. :param pauli_a: Pauli term to check commutation against `pauli_b` :param pauli_b: Pauli term to check commutation against `pauli_a` :return: Boolean of commutation result :rtype: Bool
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_basis_commutes(pauli_term, pauli_from_key): updated_pauli_set = diagonal_sets[key] + [pauli_term] diagonalizing_term = get_diagonalizing_basis(updated_pauli_set) if len(diagonalizing_term) > len(key): del diagonal_sets[key] new_key = tuple(sorted(diagonalizing_term._ops.items(), key=lambda x: x[0])) diagonal_sets[new_key] = updated_pauli_set else: diagonal_sets[key] = updated_pauli_set return diagonal_sets # made it through all keys and sets so need to make a new set else: # always need to sort because new pauli term functionality new_key = tuple(sorted(pauli_term._ops.items(), key=lambda x: x[0])) diagonal_sets[new_key] = [pauli_term] return diagonal_sets
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 where key value pair is tuple indicating diagonal basis and list of PauliTerms that share that basis :rtype: dict
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 associated with that basis.
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.append([term]) continue for k, group in enumerate(group_terms): if commutation_check(group, term): group_inds[k] += [(i, j)] group_terms[k] += [term] break else: # for ... else means loop completed without a `break` # Which means this needs to start its own group. group_inds.append([(i, j)]) group_terms.append([term]) return group_inds
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. Each set is a list of tuples (i, j) to find the particular commuting term. i is the index of the pauli sum from whence the term came. j is the index within the set.
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 trivially commutes with for term_group in commuting_terms: if check_trivial_commutation(term_group, term): term_group.append(term) break else: commuting_terms.append([term]) return commuting_terms
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 list") if ancilla is None: ancilla = max(register_a + register_b) + 1 swap_program = Program() swap_program += H(ancilla) for a, b in zip(register_a, register_b): swap_program += CSWAP(ancilla, a, b) swap_program += H(ancilla) return swap_program
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 control the swap operation.
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_map(term)) for driver_pauli_sum in self.ref_ham: for term in driver_pauli_sum.terms: driver_list.append(exponential_map(term)) cost_para_programs.append(cost_list) driver_para_programs.append(driver_list) def psi_ref(params): if len(params) != 2*self.steps: raise ValueError("params doesn't match the number of parameters set by `steps`") betas = params[:self.steps] gammas = params[self.steps:] prog = Program() prog += self.ref_state_prep for idx in range(self.steps): for fprog in cost_para_programs[idx]: prog += fprog(gammas[idx]) for fprog in driver_para_programs[idx]: prog += fprog(betas[idx]) return prog return psi_ref
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 = self.get_parameterized_program() result = vqe.vqe_run(param_prog, cost_ham, stacked_params, qc=self.qc, **self.vqe_options) self.result = result betas = result.x[:self.steps] gammas = result.x[self.steps:] return betas, gammas
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 = wf.amplitudes.reshape((-1, 1)) probs = np.zeros_like(wf) for xx in range(2 ** len(self.qubits)): probs[xx] = np.conj(wf[xx]) * wf[xx] return probs
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', 'BIT', len(self.qubits)) sampling_prog += param_prog(stacked_params) sampling_prog += [MEASURE(qubit, r) for qubit, r in zip(self.qubits, ro)] sampling_prog.wrap_in_numshots_loop(samples) executable = self.qc.compile(sampling_prog) bitstring_samples = self.qc.run(executable) bitstring_tuples = list(map(tuple, bitstring_samples)) freq = Counter(bitstring_tuples) most_frequent_bit_string = max(freq, key=lambda x: freq[x]) return most_frequent_bit_string, freq
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 betas: List of beta angles :param gammas: List of gamma angles :param samples: (Optional) number of samples to get back from the QuantumComputer. :returns: tuple representing the bitstring, Counter object from collections holding all output bitstrings and their frequency.
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 return oracle_matrix
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 oracle for the given bitstring_map
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) return "".join([str(bit) for bit in sampled_bitstring[0]])
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 cloud to run pyQuil programs. :param bitstring_map: a mapping from bitstrings to the phases that the oracle should impart on them. If the oracle should "look" for a bitstring, it should have a ``-1``, otherwise it should have a ``1``. :return: Returns the bitstring resulting from measurement after Grover's Algorithm.
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 iterations to repeat the algorithm for. The default is the integer closest to :math:`\frac{\pi}{4}\sqrt{N}`, where :math:`N` is the size of the domain. :return: A program corresponding to the desired instance of Grover's Algorithm.
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_cnots
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 labelled :math:`1, 2, \ldots, k`, where :math:`k` is the number of control qubits. The returned list provides the qubit that controls each successive CNOT, in order from left to right. :param int k: the number of control qubits :return: the list of positions of the controls :rtype: list
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), 2): # find z rotation angles phi = phases[i] psi = phases[i + 1] z_thetas.append(phi - psi) # update phases after applying such rotations kappa = (phi + psi) / 2. new_phases.append(kappa) # find y rotation angles a = magnitudes[i] b = magnitudes[i + 1] if a == 0 and b == 0: y_thetas.append(0) else: y_thetas.append( 2 * np.arcsin((a - b) / (np.sqrt(2 * (a ** 2 + b ** 2))))) # update magnitudes after applying such rotations c = np.sqrt((a ** 2 + b ** 2) / 2.) new_magnitudes.append(c) return z_thetas, y_thetas, new_phases, new_magnitudes
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:`-\\pi` to :math:`\\pi`. :param list magnitudes: positive, real value magnitudes such that the sum of the square of each magnitude is :math:`2^{-m}` for some nonnegative integer :math:`m`. :return: A tuple t of four lists such that - t[0] are the z-rotations needed to unify adjacent pairs of phases - t[1] are the y-rotations needed to unify adjacent pairs of magnitudes - t[2] are the updated phases after these rotations are applied - t[3] are the updated magnitudes after these rotations are applied :rtype: tuple
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 reversed_gates.append(gate(-angles[j], target)) if len(controls) > 0: reversed_gates.append(CNOT(controls[control_indices[j] - 1], target)) return Program().inst(reversed_gates[::-1])
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 angles must both be :math:`2^n`. :param list angles: The angles of rotation in the the decomposition, in order from left to right :param list control_indices: a list of positions for the controls of the CNOTs used when decomposing uniformly controlled rotations; see get_cnot_control_positions for labelling conventions. :param int target: Index of the target of all rotations :param list controls: Index of the controls, in order from bottom to top. :param str mode: The unification mode. Is either 'phase', corresponding to controlled RZ rotations, or 'magnitude', corresponding to controlled RY rotations. :return: The reversed circuit of this unification step. :rtype: Program
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-product value
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: numpy.ndarray
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 :param list qubits: Each qubit to include in the basis state preparation. :return: Yields programs for each basis state preparation. :rtype: Program
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.ndarray assignment_probs: A matrix of assignment probabilities :param QVMConnection cxn: the QVM connection. :return: The resulting sampled outcomes from assignment_probs applied to cxn, one dimensional. :rtype: numpy.ndarray
9.98302
7.850864
1.271582