repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
fusepy/fusepy
fusell.py
FUSELL.unlink
def unlink(self, req, parent, name): """Remove a file Valid replies: reply_err """ self.reply_err(req, errno.EROFS)
python
def unlink(self, req, parent, name): """Remove a file Valid replies: reply_err """ self.reply_err(req, errno.EROFS)
[ "def", "unlink", "(", "self", ",", "req", ",", "parent", ",", "name", ")", ":", "self", ".", "reply_err", "(", "req", ",", "errno", ".", "EROFS", ")" ]
Remove a file Valid replies: reply_err
[ "Remove", "a", "file" ]
5d997d6706cc0204e1b3ca679651485a7e7dda49
https://github.com/fusepy/fusepy/blob/5d997d6706cc0204e1b3ca679651485a7e7dda49/fusell.py#L756-L762
train
200,300
fusepy/fusepy
fusell.py
FUSELL.rmdir
def rmdir(self, req, parent, name): """Remove a directory Valid replies: reply_err """ self.reply_err(req, errno.EROFS)
python
def rmdir(self, req, parent, name): """Remove a directory Valid replies: reply_err """ self.reply_err(req, errno.EROFS)
[ "def", "rmdir", "(", "self", ",", "req", ",", "parent", ",", "name", ")", ":", "self", ".", "reply_err", "(", "req", ",", "errno", ".", "EROFS", ")" ]
Remove a directory Valid replies: reply_err
[ "Remove", "a", "directory" ]
5d997d6706cc0204e1b3ca679651485a7e7dda49
https://github.com/fusepy/fusepy/blob/5d997d6706cc0204e1b3ca679651485a7e7dda49/fusell.py#L764-L770
train
200,301
fusepy/fusepy
fusell.py
FUSELL.rename
def rename(self, req, parent, name, newparent, newname): """Rename a file Valid replies: reply_err """ self.reply_err(req, errno.EROFS)
python
def rename(self, req, parent, name, newparent, newname): """Rename a file Valid replies: reply_err """ self.reply_err(req, errno.EROFS)
[ "def", "rename", "(", "self", ",", "req", ",", "parent", ",", "name", ",", "newparent", ",", "newname", ")", ":", "self", ".", "reply_err", "(", "req", ",", "errno", ".", "EROFS", ")" ]
Rename a file Valid replies: reply_err
[ "Rename", "a", "file" ]
5d997d6706cc0204e1b3ca679651485a7e7dda49
https://github.com/fusepy/fusepy/blob/5d997d6706cc0204e1b3ca679651485a7e7dda49/fusell.py#L781-L787
train
200,302
fusepy/fusepy
fusell.py
FUSELL.link
def link(self, req, ino, newparent, newname): """Create a hard link Valid replies: reply_entry reply_err """ self.reply_err(req, errno.EROFS)
python
def link(self, req, ino, newparent, newname): """Create a hard link Valid replies: reply_entry reply_err """ self.reply_err(req, errno.EROFS)
[ "def", "link", "(", "self", ",", "req", ",", "ino", ",", "newparent", ",", "newname", ")", ":", "self", ".", "reply_err", "(", "req", ",", "errno", ".", "EROFS", ")" ]
Create a hard link Valid replies: reply_entry reply_err
[ "Create", "a", "hard", "link" ]
5d997d6706cc0204e1b3ca679651485a7e7dda49
https://github.com/fusepy/fusepy/blob/5d997d6706cc0204e1b3ca679651485a7e7dda49/fusell.py#L789-L796
train
200,303
fusepy/fusepy
fusell.py
FUSELL.listxattr
def listxattr(self, req, ino, size): """List extended attribute names Valid replies: reply_buf reply_data reply_xattr reply_err """ self.reply_err(req, errno.ENOSYS)
python
def listxattr(self, req, ino, size): """List extended attribute names Valid replies: reply_buf reply_data reply_xattr reply_err """ self.reply_err(req, errno.ENOSYS)
[ "def", "listxattr", "(", "self", ",", "req", ",", "ino", ",", "size", ")", ":", "self", ".", "reply_err", "(", "req", ",", "errno", ".", "ENOSYS", ")" ]
List extended attribute names Valid replies: reply_buf reply_data reply_xattr reply_err
[ "List", "extended", "attribute", "names" ]
5d997d6706cc0204e1b3ca679651485a7e7dda49
https://github.com/fusepy/fusepy/blob/5d997d6706cc0204e1b3ca679651485a7e7dda49/fusell.py#L916-L925
train
200,304
fusepy/fusepy
fusell.py
FUSELL.removexattr
def removexattr(self, req, ino, name): """Remove an extended attribute Valid replies: reply_err """ self.reply_err(req, errno.ENOSYS)
python
def removexattr(self, req, ino, name): """Remove an extended attribute Valid replies: reply_err """ self.reply_err(req, errno.ENOSYS)
[ "def", "removexattr", "(", "self", ",", "req", ",", "ino", ",", "name", ")", ":", "self", ".", "reply_err", "(", "req", ",", "errno", ".", "ENOSYS", ")" ]
Remove an extended attribute Valid replies: reply_err
[ "Remove", "an", "extended", "attribute" ]
5d997d6706cc0204e1b3ca679651485a7e7dda49
https://github.com/fusepy/fusepy/blob/5d997d6706cc0204e1b3ca679651485a7e7dda49/fusell.py#L927-L933
train
200,305
fusepy/fusepy
fusell.py
FUSELL.access
def access(self, req, ino, mask): """Check file access permissions Valid replies: reply_err """ self.reply_err(req, errno.ENOSYS)
python
def access(self, req, ino, mask): """Check file access permissions Valid replies: reply_err """ self.reply_err(req, errno.ENOSYS)
[ "def", "access", "(", "self", ",", "req", ",", "ino", ",", "mask", ")", ":", "self", ".", "reply_err", "(", "req", ",", "errno", ".", "ENOSYS", ")" ]
Check file access permissions Valid replies: reply_err
[ "Check", "file", "access", "permissions" ]
5d997d6706cc0204e1b3ca679651485a7e7dda49
https://github.com/fusepy/fusepy/blob/5d997d6706cc0204e1b3ca679651485a7e7dda49/fusell.py#L935-L941
train
200,306
fusepy/fusepy
fusell.py
FUSELL.create
def create(self, req, parent, name, mode, fi): """Create and open a file Valid replies: reply_create reply_err """ self.reply_err(req, errno.ENOSYS)
python
def create(self, req, parent, name, mode, fi): """Create and open a file Valid replies: reply_create reply_err """ self.reply_err(req, errno.ENOSYS)
[ "def", "create", "(", "self", ",", "req", ",", "parent", ",", "name", ",", "mode", ",", "fi", ")", ":", "self", ".", "reply_err", "(", "req", ",", "errno", ".", "ENOSYS", ")" ]
Create and open a file Valid replies: reply_create reply_err
[ "Create", "and", "open", "a", "file" ]
5d997d6706cc0204e1b3ca679651485a7e7dda49
https://github.com/fusepy/fusepy/blob/5d997d6706cc0204e1b3ca679651485a7e7dda49/fusell.py#L943-L950
train
200,307
rigetti/grove
grove/tomography/state_tomography.py
state_tomography_programs
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 """ 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
python
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 """ 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", ")", ":", "if", "qubits", "is", "None", ":", "qubits", "=", "state_prep", ".", "get_qubits", "(", ")", "f...
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
[ "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", "...
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/state_tomography.py#L223-L244
train
200,308
rigetti/grove
grove/tomography/state_tomography.py
do_state_tomography
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 """ 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)
python
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 """ 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", ")", ":", "return", "tomography", ".", "_do_tomography", "(", "preparation_program", ",", "nsamples", ",", "cxn", "...
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
[ "Method", "to", "perform", "both", "a", "QPU", "and", "QVM", "state", "tomography", "and", "use", "the", "latter", "as", "as", "reference", "to", "calculate", "the", "fidelity", "of", "the", "former", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/state_tomography.py#L247-L265
train
200,309
rigetti/grove
grove/tomography/state_tomography.py
StateTomography.estimate_from_ssr
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 """ 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)
python
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 """ 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", ")", ":", "nqc", "=", "len", "(", "channel_ops", "[", "0", "]", ".", "dims", "[", "0", "]", ")", "pauli_basis", "=", "grove", ".", "tomography", ".",...
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
[ "Estimate", "a", "density", "matrix", "from", "single", "shot", "histograms", "obtained", "by", "measuring", "bitstrings", "in", "the", "Z", "-", "eigenbasis", "after", "application", "of", "given", "channel", "operators", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/state_tomography.py#L105-L168
train
200,310
rigetti/grove
grove/tomography/state_tomography.py
StateTomography.plot_state_histogram
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. """ 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)
python
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. """ 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", ")", ":", "title", "=", "\"Estimated state\"", "nqc", "=", "int", "(", "round", "(", "np", ".", "log2", "(", "self", ".", "rho_est", ".", "data", ".", "shape", "[", "0", "]", ")", ")", ")", "la...
Visualize the complex matrix elements of the estimated state. :param matplotlib.Axes ax: A matplotlib Axes object to plot into.
[ "Visualize", "the", "complex", "matrix", "elements", "of", "the", "estimated", "state", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/state_tomography.py#L195-L204
train
200,311
rigetti/grove
grove/tomography/state_tomography.py
StateTomography.plot
def plot(self): """ Visualize the state. :return: The generated figure. :rtype: matplotlib.Figure """ 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
python
def plot(self): """ Visualize the state. :return: The generated figure. :rtype: matplotlib.Figure """ 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", ")", ":", "width", "=", "10", "# The pleasing golden ratio.", "height", "=", "width", "/", "1.618", "f", "=", "plt", ".", "figure", "(", "figsize", "=", "(", "width", ",", "height", ")", ")", "ax", "=", "f", ".", "add_subp...
Visualize the state. :return: The generated figure. :rtype: matplotlib.Figure
[ "Visualize", "the", "state", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/state_tomography.py#L206-L220
train
200,312
rigetti/grove
grove/deutsch_jozsa/deutsch_jozsa.py
DeutschJosza.is_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 """ 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
python
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 """ 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", ":", "self", ".", "_init_attr", "(", "bitstring_map", ")", "prog", "=", "Program", "(", ")", "dj_ro...
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
[ "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", "th...
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/deutsch_jozsa/deutsch_jozsa.py#L46-L69
train
200,313
rigetti/grove
grove/deutsch_jozsa/deutsch_jozsa.py
DeutschJosza.unitary_function
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. """ 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")
python
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. """ 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", ":", "num_qubits", "=", "int", "(", "np", ".", "log2", "(", "len", "(", "mappings", ")", ")", ")", "bitsum", "=", "sum", "(", "...
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.
[ "Creates", "a", "unitary", "transformation", "that", "maps", "each", "state", "to", "the", "values", "specified", "in", "mappings", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/deutsch_jozsa/deutsch_jozsa.py#L124-L165
train
200,314
rigetti/grove
grove/amplification/oracles.py
basis_selector_oracle
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. """ 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
python
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. """ 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", ":", "if", "len", "(", "qubits", ")", "!=", "len", "(", "bitstring", ")", ":", "raise", "ValueError", "(", "\"The bitstring s...
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.
[ "Defines", "an", "oracle", "that", "selects", "the", "ith", "element", "of", "the", "computational", "basis", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/amplification/oracles.py#L28-L66
train
200,315
rigetti/grove
grove/tomography/operator_utils.py
make_diagonal_povm
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 """ 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)
python
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 """ 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", ")", ":", "confusion_rate_matrix", "=", "np", ".", "asarray", "(", "confusion_rate_matrix", ")", "if", "not", "np", ".", "allclose", "(", "confusion_rate_matrix", ".", "sum", "(", "axis", ...
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
[ "Create", "a", "DiagonalPOVM", "from", "a", "pi_basis", "and", "the", "confusion_rate_matrix", "associated", "with", "a", "readout", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/operator_utils.py#L70-L94
train
200,316
rigetti/grove
grove/tomography/operator_utils.py
is_hermitian
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 """ 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
python
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 """ 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", ")", ":", "if", "isinstance", "(", "operator", ",", "qt", ".", "Qobj", ")", ":", "return", "(", "operator", ".", "dag", "(", ")", "-", "operator", ")", ".", "norm", "(", "FROBENIUS", ")", "/", "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
[ "Check", "if", "matrix", "or", "operator", "is", "hermitian", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/operator_utils.py#L97-L109
train
200,317
rigetti/grove
grove/tomography/operator_utils.py
is_projector
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 """ # 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)
python
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 """ # 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", ")", ":", "# 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", "(", "F...
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
[ "Check", "if", "operator", "is", "a", "projector", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/operator_utils.py#L112-L122
train
200,318
rigetti/grove
grove/tomography/operator_utils.py
choi_matrix
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 """ 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
python
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 """ 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", ")", ":", "if", "not", "basis", ".", "is_orthonormal", "(", ")", ":", "# pragma no coverage", "raise", "ValueError", "(", "\"Need an orthonormal operator basis.\"", ")", "if", "not", "all", "(", "(", "is_hermi...
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
[ "Compute", "the", "Choi", "matrix", "for", "a", "quantum", "process", "from", "its", "Pauli", "Transfer", "Matrix", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/operator_utils.py#L125-L149
train
200,319
rigetti/grove
grove/tomography/operator_utils.py
OperatorBasis.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 """ 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
python
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 """ 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", ")", ":", "if", "self", ".", "_metric", "is", "None", ":", "_log", ".", "debug", "(", "\"Computing and caching operator basis metric\"", ")", "self", ".", "_metric", "=", "np", ".", "matrix", "(", "[", "[", "(", "j", ".", ...
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
[ "Compute", "a", "matrix", "of", "Hilbert", "-", "Schmidt", "inner", "products", "for", "the", "basis", "operators", "update", "self", ".", "_metric", "and", "return", "the", "value", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/operator_utils.py#L212-L223
train
200,320
rigetti/grove
grove/tomography/operator_utils.py
OperatorBasis.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 """ 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
python
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 """ 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", ")", ":", "if", "self", ".", "_is_orthonormal", "is", "None", ":", "_log", ".", "debug", "(", "\"Testing and caching if operator basis is orthonormal\"", ")", "self", ".", "_is_orthonormal", "=", "np", ".", "allclose", "(", ...
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
[ "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", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/operator_utils.py#L225-L237
train
200,321
rigetti/grove
grove/tomography/operator_utils.py
OperatorBasis.all_hermitian
def all_hermitian(self): """ Check if all basis operators are hermitian. """ 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
python
def all_hermitian(self): """ Check if all basis operators are hermitian. """ 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", ")", ":", "if", "self", ".", "_all_hermitian", "is", "None", ":", "_log", ".", "debug", "(", "\"Testing and caching if all basis operator are hermitian\"", ")", "self", ".", "_all_hermitian", "=", "all", "(", "(", "is_hermitian...
Check if all basis operators are hermitian.
[ "Check", "if", "all", "basis", "operators", "are", "hermitian", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/operator_utils.py#L239-L246
train
200,322
rigetti/grove
grove/tomography/operator_utils.py
OperatorBasis.product
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. """ 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)
python
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. """ 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", ")", ":", "if", "len", "(", "bases", ")", ">", "1", ":", "basis_rest", "=", "bases", "[", "0", "]", ".", "product", "(", "*", "bases", "[", "1", ":", "]", ")", "else", ":", "assert", "len", "(...
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.
[ "Compute", "the", "tensor", "product", "with", "another", "basis", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/operator_utils.py#L258-L274
train
200,323
rigetti/grove
grove/tomography/operator_utils.py
OperatorBasis.super_basis
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. """ labels_ops = [(bnl + "^T (x) " + bml, qt.sprepost(bm, bn)) for (bnl, bn), (bml, bm) in itertools.product(self, self)] return OperatorBasis(labels_ops)
python
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. """ 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", ")", ":", "labels_ops", "=", "[", "(", "bnl", "+", "\"^T (x) \"", "+", "bml", ",", "qt", ".", "sprepost", "(", "bm", ",", "bn", ")", ")", "for", "(", "bnl", ",", "bn", ")", ",", "(", "bml", ",", "bm", ")", "...
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.
[ "Generate", "the", "superoperator", "basis", "in", "which", "the", "Choi", "matrix", "can", "be", "represented", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/operator_utils.py#L292-L305
train
200,324
rigetti/grove
grove/tomography/operator_utils.py
OperatorBasis.project_op
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 """ 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
python
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 """ 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", ")", ":", "if", "not", "self", ".", "is_orthonormal", "(", ")", ":", "# pragma no coverage", "raise", "ValueError", "(", "\"project_op only implemented for orthonormal operator bases\"", ")", "return", "self", ".", "basis...
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
[ "Project", "an", "operator", "onto", "the", "basis", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/operator_utils.py#L307-L317
train
200,325
rigetti/grove
grove/simon/utils.py
is_unitary
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 """ rows, cols = matrix.shape if rows != cols: return False return np.allclose(np.eye(rows), matrix.dot(matrix.T.conj()))
python
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 """ 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", ":", "rows", ",", "cols", "=", "matrix", ".", "shape", "if", "rows", "!=", "cols", ":", "return", "False", "return", "np", ".", "allclose", "(", "np", ".", "eye", "("...
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
[ "A", "helper", "function", "that", "checks", "if", "a", "matrix", "is", "unitary", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/simon/utils.py#L9-L19
train
200,326
rigetti/grove
grove/simon/utils.py
most_significant_bit
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 """ return np.argwhere(np.asarray(lst) == 1)[0][0]
python
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 """ return np.argwhere(np.asarray(lst) == 1)[0][0]
[ "def", "most_significant_bit", "(", "lst", ":", "np", ".", "ndarray", ")", "->", "int", ":", "return", "np", ".", "argwhere", "(", "np", ".", "asarray", "(", "lst", ")", "==", "1", ")", "[", "0", "]", "[", "0", "]" ]
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
[ "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", "t...
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/simon/utils.py#L22-L30
train
200,327
rigetti/grove
grove/simon/utils.py
bitwise_xor
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 """ 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)
python
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 """ 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", ":", "if", "len", "(", "bs0", ")", "!=", "len", "(", "bs1", ")", ":", "raise", "ValueError", "(", "\"Bit strings are not of equal length\"", ")", "n_bits", "=", "le...
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
[ "A", "helper", "to", "calculate", "the", "bitwise", "XOR", "of", "two", "bit", "string" ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/simon/utils.py#L33-L44
train
200,328
rigetti/grove
grove/pyqaoa/numpartition_qaoa.py
numpart_qaoa
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. """ 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
python
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. """ 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", ")", ":", "cost_operators", "=", "[", "]", "ref_operators", "=", "[", "]", "for", "ii", "in", "range", "(", "len", "(", "ass...
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.
[ "generate", "number", "partition", "driver", "and", "cost", "functions" ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/pyqaoa/numpartition_qaoa.py#L25-L57
train
200,329
rigetti/grove
grove/alpha/jordan_gradient/jordan_gradient.py
estimate_gradient
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. """ # 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
python
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. """ # 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", ":", "# sca...
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.
[ "Estimate", "the", "gradient", "using", "function", "evaluation", "at", "perturbation", "h", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/alpha/jordan_gradient/jordan_gradient.py#L28-L66
train
200,330
rigetti/grove
grove/tomography/process_tomography.py
process_tomography_programs
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 """ 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
python
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 """ 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", ")", ":", "if", "qubits", "is", ...
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
[ "Generator", "that", "yields", "tomographic", "sequences", "that", "wrap", "a", "process", "encoded", "by", "a", "QUIL", "program", "proc", "in", "tomographic", "rotations", "on", "the", "specified", "qubits", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/process_tomography.py#L275-L302
train
200,331
rigetti/grove
grove/tomography/process_tomography.py
do_process_tomography
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 """ 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)
python
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 """ 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", ")", ":", "return", "tomography", ".", "_do_tomography", "(", "process", ",", "nsamples", ",", "cxn", ",", "qubits", ",",...
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
[ "Method", "to", "perform", "a", "process", "tomography", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/process_tomography.py#L305-L322
train
200,332
rigetti/grove
grove/tomography/process_tomography.py
ProcessTomography.estimate_from_ssr
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 """ 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)
python
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 """ 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", ")", ":", "nqc", "=", "len", "(", "pre_channel_ops", "[", "0", "]", ".", "dims", "[", "0", "]", ")", "pauli_basis", "=", "...
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
[ "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", ...
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/process_tomography.py#L99-L164
train
200,333
rigetti/grove
grove/tomography/process_tomography.py
ProcessTomography.process_fidelity
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 """ 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
python
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 """ 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", ")", ":", "if", "isinstance", "(", "reference_unitary", ",", "qt", ".", "Qobj", ")", ":", "if", "not", "reference_unitary", ".", "issuper", "or", "reference_unitary", ".", "superrep", "!=", "\"s...
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
[ "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", ...
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/process_tomography.py#L181-L201
train
200,334
rigetti/grove
grove/tomography/process_tomography.py
ProcessTomography.to_kraus
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] """ return [k.data.toarray() for k in qt.to_kraus(self.sop)]
python
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] """ return [k.data.toarray() for k in qt.to_kraus(self.sop)]
[ "def", "to_kraus", "(", "self", ")", ":", "return", "[", "k", ".", "data", ".", "toarray", "(", ")", "for", "k", "in", "qt", ".", "to_kraus", "(", "self", ".", "sop", ")", "]" ]
Compute the Kraus operator representation of the estimated process. :return: The process as a list of Kraus operators. :rytpe: List[np.array]
[ "Compute", "the", "Kraus", "operator", "representation", "of", "the", "estimated", "process", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/process_tomography.py#L245-L252
train
200,335
rigetti/grove
grove/tomography/process_tomography.py
ProcessTomography.plot_pauli_transfer_matrix
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. """ title = "Estimated process" ut.plot_pauli_transfer_matrix(self.r_est, ax, self.pauli_basis.labels, title)
python
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. """ title = "Estimated process" ut.plot_pauli_transfer_matrix(self.r_est, ax, self.pauli_basis.labels, title)
[ "def", "plot_pauli_transfer_matrix", "(", "self", ",", "ax", ")", ":", "title", "=", "\"Estimated process\"", "ut", ".", "plot_pauli_transfer_matrix", "(", "self", ".", "r_est", ",", "ax", ",", "self", ".", "pauli_basis", ".", "labels", ",", "title", ")" ]
Plot the elements of the Pauli transfer matrix. :param matplotlib.Axes ax: A matplotlib Axes object to plot into.
[ "Plot", "the", "elements", "of", "the", "Pauli", "transfer", "matrix", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/process_tomography.py#L254-L261
train
200,336
rigetti/grove
grove/tomography/process_tomography.py
ProcessTomography.plot
def plot(self): """ Visualize the process. :return: The generated figure. :rtype: matplotlib.Figure """ fig, (ax1) = plt.subplots(1, 1, figsize=(10, 8)) self.plot_pauli_transfer_matrix(ax1) return fig
python
def plot(self): """ Visualize the process. :return: The generated figure. :rtype: matplotlib.Figure """ fig, (ax1) = plt.subplots(1, 1, figsize=(10, 8)) self.plot_pauli_transfer_matrix(ax1) return fig
[ "def", "plot", "(", "self", ")", ":", "fig", ",", "(", "ax1", ")", "=", "plt", ".", "subplots", "(", "1", ",", "1", ",", "figsize", "=", "(", "10", ",", "8", ")", ")", "self", ".", "plot_pauli_transfer_matrix", "(", "ax1", ")", "return", "fig" ]
Visualize the process. :return: The generated figure. :rtype: matplotlib.Figure
[ "Visualize", "the", "process", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/process_tomography.py#L263-L272
train
200,337
rigetti/grove
grove/qft/fourier.py
bit_reversal
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. """ p = Program() n = len(qubits) for i in range(int(n / 2)): p.inst(SWAP(qubits[i], qubits[-i - 1])) return p
python
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. """ 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", ":", "p", "=", "Program", "(", ")", "n", "=", "len", "(", "qubits", ")", "for", "i", "in", "range", "(", "int", "(", "n", "/", "2", ")", ")", ":", "p", ...
Generate a circuit to do bit reversal. :param qubits: Qubits to do bit reversal with. :return: A program to do bit reversal.
[ "Generate", "a", "circuit", "to", "do", "bit", "reversal", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/qft/fourier.py#L23-L34
train
200,338
rigetti/grove
grove/qft/fourier.py
qft
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. """ p = Program().inst(_core_qft(qubits, 1)) return p + bit_reversal(qubits)
python
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. """ p = Program().inst(_core_qft(qubits, 1)) return p + bit_reversal(qubits)
[ "def", "qft", "(", "qubits", ":", "List", "[", "int", "]", ")", "->", "Program", ":", "p", "=", "Program", "(", ")", ".", "inst", "(", "_core_qft", "(", "qubits", ",", "1", ")", ")", "return", "p", "+", "bit_reversal", "(", "qubits", ")" ]
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.
[ "Generate", "a", "program", "to", "compute", "the", "quantum", "Fourier", "transform", "on", "a", "set", "of", "qubits", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/qft/fourier.py#L60-L69
train
200,339
rigetti/grove
grove/qft/fourier.py
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. """ 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
python
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. """ 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", ":", "qft_result", "=", "Program", "(", ")", ".", "inst", "(", "_core_qft", "(", "qubits", ",", "-", "1", ")", ")", "qft_result", "+=", "bit_reversal", "(", "qub...
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.
[ "Generate", "a", "program", "to", "compute", "the", "inverse", "quantum", "Fourier", "transform", "on", "a", "set", "of", "qubits", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/qft/fourier.py#L72-L86
train
200,340
rigetti/grove
grove/alpha/arbitrary_state/unitary_operator.py
unitary_operator
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 """ 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
python
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 """ 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", ")", ":", "if", "not", "np", ".", "allclose", "(", "[", "np", ".", "linalg", ".", "norm", "(", "state_vector", ")", "]", ",", "[", "1", "]", ")", ":", "raise", "ValueError", "(", "\"Vector must be normalize...
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
[ "Uses", "QR", "factorization", "to", "create", "a", "unitary", "operator", "that", "can", "encode", "an", "arbitrary", "normalized", "vector", "into", "the", "wavefunction", "of", "a", "quantum", "state", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/alpha/arbitrary_state/unitary_operator.py#L16-L52
train
200,341
rigetti/grove
grove/alpha/arbitrary_state/unitary_operator.py
fix_norm_and_length
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 """ # 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
python
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 """ # 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", ")", ":", "# normalize", "norm_vector", "=", "vector", "/", "np", ".", "linalg", ".", "norm", "(", "vector", ")", "# pad with zeros", "num_bits", "=", "get_bits_needed", "(", "len", "(", "vector", ")", ")", "state...
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
[ "Create", "a", "normalized", "and", "zero", "padded", "version", "of", "vector", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/alpha/arbitrary_state/unitary_operator.py#L55-L75
train
200,342
rigetti/grove
grove/bernstein_vazirani/bernstein_vazirani.py
BernsteinVazirani._create_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 """ 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
python
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 """ 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", ":", "unitary", ",", "_", "=", "self", ".", "_compute_unitary_oracle_matrix", "(", "bit_map", ")", "full_bv_circuit", "=", "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
[ "Implementation", "of", "the", "Bernstein", "-", "Vazirani", "Algorithm", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/bernstein_vazirani/bernstein_vazirani.py#L133-L157
train
200,343
rigetti/grove
grove/bernstein_vazirani/bernstein_vazirani.py
BernsteinVazirani.run
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 """ # 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
python
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 """ # 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'", ":", "# initialize all attributes", "self", ".", "input_bitmap", "=", "bitstring_map", "self", ".", ...
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
[ "Runs", "the", "Bernstein", "-", "Vazirani", "algorithm", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/bernstein_vazirani/bernstein_vazirani.py#L159-L200
train
200,344
rigetti/grove
grove/bernstein_vazirani/bernstein_vazirani.py
BernsteinVazirani.get_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] """ if self.solution is None: raise AssertionError("You need to `run` this algorithm first") return self.solution
python
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] """ if self.solution is None: raise AssertionError("You need to `run` this algorithm first") return self.solution
[ "def", "get_solution", "(", "self", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "if", "self", ".", "solution", "is", "None", ":", "raise", "AssertionError", "(", "\"You need to `run` this algorithm first\"", ")", "return", "self", ".", "solution" ]
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]
[ "Returns", "the", "solution", "of", "the", "BV", "algorithm" ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/bernstein_vazirani/bernstein_vazirani.py#L202-L211
train
200,345
rigetti/grove
grove/bernstein_vazirani/bernstein_vazirani.py
BernsteinVazirani.check_solution
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 """ 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()])
python
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 """ 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", ":", "if", "self", ".", "solution", "is", "None", ":", "raise", "AssertionError", "(", "\"You need to `run` this algorithm first\"", ")", "assert_map", "=", "create_bv_bitmap", "(", "*", "self", ".", "solu...
Checks if the the found solution correctly reproduces the input. :return: True if solution correctly reproduces input bitstring map :rtype: Bool
[ "Checks", "if", "the", "the", "found", "solution", "correctly", "reproduces", "the", "input", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/bernstein_vazirani/bernstein_vazirani.py#L213-L223
train
200,346
rigetti/grove
grove/measurements/term_grouping.py
diagonal_basis_commutes
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 """ 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
python
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 """ 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", ")", ":", "overlapping_active_qubits", "=", "set", "(", "pauli_a", ".", "get_qubits", "(", ")", ")", "&", "set", "(", "pauli_b", ".", "get_qubits", "(", ")", ")", "for", "qubit_index", "in", ...
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
[ "Test", "if", "pauli_a", "and", "pauli_b", "share", "a", "diagonal", "basis" ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/measurements/term_grouping.py#L24-L47
train
200,347
rigetti/grove
grove/measurements/term_grouping.py
get_diagonalizing_basis
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 """ 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)))
python
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 """ 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", ")", ":", "qubit_ops", "=", "set", "(", "reduce", "(", "lambda", "x", ",", "y", ":", "x", "+", "y", ",", "[", "list", "(", "term", ".", "_ops", ".", "items", "(", ")", ")", "for", "term", ...
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
[ "Find", "the", "Pauli", "Term", "with", "the", "most", "non", "-", "identity", "terms" ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/measurements/term_grouping.py#L50-L62
train
200,348
rigetti/grove
grove/measurements/term_grouping.py
_max_key_overlap
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 """ # 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
python
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 """ # 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", ")", ":", "# 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", ".", "...
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
[ "Calculate", "the", "max", "overlap", "of", "a", "pauli", "term", "ID", "with", "keys", "of", "diagonal_sets" ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/measurements/term_grouping.py#L65-L101
train
200,349
rigetti/grove
grove/measurements/term_grouping.py
commuting_sets_by_zbasis
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. """ diagonal_sets = {} for term in pauli_sums: diagonal_sets = _max_key_overlap(term, diagonal_sets) return diagonal_sets
python
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. """ 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", ")", ":", "diagonal_sets", "=", "{", "}", "for", "term", "in", "pauli_sums", ":", "diagonal_sets", "=", "_max_key_overlap", "(", "term", ",", "diagonal_sets", ")", "return", "diagonal_sets" ]
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.
[ "Computes", "commuting", "sets", "based", "on", "terms", "having", "the", "same", "diagonal", "basis" ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/measurements/term_grouping.py#L104-L118
train
200,350
rigetti/grove
grove/measurements/term_grouping.py
check_trivial_commutation
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 """ 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
python
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 """ 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", ")", ":", "if", "not", "isinstance", "(", "pauli_list", ",", "list", ")", ":", "raise", "TypeError", "(", "\"pauli_list should be a list\"", ")", "for", "term", "in", "pauli_list", ":...
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
[ "Check", "if", "a", "PauliTerm", "trivially", "commutes", "with", "a", "list", "of", "other", "terms", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/measurements/term_grouping.py#L121-L136
train
200,351
rigetti/grove
grove/measurements/term_grouping.py
commuting_sets_by_indices
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. """ 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
python
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. """ 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", ")", ":", "assert", "isinstance", "(", "pauli_sums", ",", "list", ")", "group_inds", "=", "[", "]", "group_terms", "=", "[", "]", "for", "i", ",", "pauli_sum", "in", "enumerate", ...
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.
[ "For", "a", "list", "of", "pauli", "sums", "find", "commuting", "sets", "and", "keep", "track", "of", "which", "pauli", "sum", "they", "came", "from", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/measurements/term_grouping.py#L139-L173
train
200,352
rigetti/grove
grove/measurements/term_grouping.py
commuting_sets_trivial
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 """ 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
python
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 """ 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", ")", ":", "if", "not", "isinstance", "(", "pauli_sum", ",", "(", "PauliTerm", ",", "PauliSum", ")", ")", ":", "raise", "TypeError", "(", "\"This method can only group PauliTerm or PauliSum objects\"", ")", "if", "is...
Group a pauli term into commuting sets using trivial check :param pauli_sum: PauliSum term :return: list of lists containing individual Pauli Terms
[ "Group", "a", "pauli", "term", "into", "commuting", "sets", "using", "trivial", "check" ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/measurements/term_grouping.py#L176-L199
train
200,353
rigetti/grove
grove/ising/ising_qaoa.py
ising
def ising(h: List[int], J: Dict[Tuple[int, int], int], num_steps: int = 0, verbose: bool = True, rand_seed: int = None, connection: QuantumComputer = None, samples: int = None, initial_beta: List[float] = None, initial_gamma: List[float] = None, minimizer_kwargs: Dict[str, Any] = None, vqe_option: Dict[str, Union[bool, int]] = None) -> Tuple[List[int], Union[int, float], Program]: """ Ising set up method :param h: External magnetic term of the Ising problem. :param J: Interaction term of the Ising problem. :param num_steps: (Optional.Default=2 * len(h)) Trotterization order for the QAOA algorithm. :param verbose: (Optional.Default=True) Verbosity of the code. :param rand_seed: (Optional. Default=None) random seed when beta and gamma angles are not provided. :param connection: (Optional) connection to the QVM. Default is None. :param samples: (Optional. Default=None) VQE option. Number of samples (circuit preparation and measurement) to use in operator averaging. :param initial_beta: (Optional. Default=None) Initial guess for beta parameters. :param initial_gamma: (Optional. Default=None) Initial guess for gamma parameters. :param minimizer_kwargs: (Optional. Default=None). Minimizer optional arguments. If None set to {'method': 'Nelder-Mead', 'options': {'fatol': 1.0e-2, 'xatol': 1.0e-2, 'disp': False} :param vqe_option: (Optional. Default=None). VQE optional arguments. If None set to vqe_option = {'disp': print_fun, 'return_all': True, 'samples': samples} :return: Most frequent Ising string, Energy of the Ising string, Circuit used to obtain result. """ if num_steps == 0: num_steps = 2 * len(h) n_nodes = len(h) cost_operators = [] driver_operators = [] for i, j in J.keys(): cost_operators.append(PauliSum([PauliTerm("Z", i, J[(i, j)]) * PauliTerm("Z", j)])) for i in range(n_nodes): cost_operators.append(PauliSum([PauliTerm("Z", i, h[i])])) driver_operators.append(PauliSum([PauliTerm("X", i, -1.0)])) if connection is None: qubits = list(sum(J.keys(), ())) connection = get_qc(f"{len(qubits)}q-qvm") if minimizer_kwargs is None: minimizer_kwargs = {'method': 'Nelder-Mead', 'options': {'fatol': 1.0e-2, 'xatol': 1.0e-2, 'disp': False}} if vqe_option is None: vqe_option = {'disp': print, 'return_all': True, 'samples': samples} if not verbose: vqe_option['disp'] = None qaoa_inst = QAOA(connection, list(range(n_nodes)), steps=num_steps, init_betas=initial_beta, init_gammas=initial_gamma, cost_ham=cost_operators, ref_ham=driver_operators, minimizer=minimize, minimizer_kwargs=minimizer_kwargs, rand_seed=rand_seed, vqe_options=vqe_option, store_basis=True) betas, gammas = qaoa_inst.get_angles() most_freq_string, sampling_results = qaoa_inst.get_string(betas, gammas) most_freq_string_ising = [ising_trans(it) for it in most_freq_string] energy_ising = energy_value(h, J, most_freq_string_ising) param_prog = qaoa_inst.get_parameterized_program() circuit = param_prog(np.hstack((betas, gammas))) return most_freq_string_ising, energy_ising, circuit
python
def ising(h: List[int], J: Dict[Tuple[int, int], int], num_steps: int = 0, verbose: bool = True, rand_seed: int = None, connection: QuantumComputer = None, samples: int = None, initial_beta: List[float] = None, initial_gamma: List[float] = None, minimizer_kwargs: Dict[str, Any] = None, vqe_option: Dict[str, Union[bool, int]] = None) -> Tuple[List[int], Union[int, float], Program]: """ Ising set up method :param h: External magnetic term of the Ising problem. :param J: Interaction term of the Ising problem. :param num_steps: (Optional.Default=2 * len(h)) Trotterization order for the QAOA algorithm. :param verbose: (Optional.Default=True) Verbosity of the code. :param rand_seed: (Optional. Default=None) random seed when beta and gamma angles are not provided. :param connection: (Optional) connection to the QVM. Default is None. :param samples: (Optional. Default=None) VQE option. Number of samples (circuit preparation and measurement) to use in operator averaging. :param initial_beta: (Optional. Default=None) Initial guess for beta parameters. :param initial_gamma: (Optional. Default=None) Initial guess for gamma parameters. :param minimizer_kwargs: (Optional. Default=None). Minimizer optional arguments. If None set to {'method': 'Nelder-Mead', 'options': {'fatol': 1.0e-2, 'xatol': 1.0e-2, 'disp': False} :param vqe_option: (Optional. Default=None). VQE optional arguments. If None set to vqe_option = {'disp': print_fun, 'return_all': True, 'samples': samples} :return: Most frequent Ising string, Energy of the Ising string, Circuit used to obtain result. """ if num_steps == 0: num_steps = 2 * len(h) n_nodes = len(h) cost_operators = [] driver_operators = [] for i, j in J.keys(): cost_operators.append(PauliSum([PauliTerm("Z", i, J[(i, j)]) * PauliTerm("Z", j)])) for i in range(n_nodes): cost_operators.append(PauliSum([PauliTerm("Z", i, h[i])])) driver_operators.append(PauliSum([PauliTerm("X", i, -1.0)])) if connection is None: qubits = list(sum(J.keys(), ())) connection = get_qc(f"{len(qubits)}q-qvm") if minimizer_kwargs is None: minimizer_kwargs = {'method': 'Nelder-Mead', 'options': {'fatol': 1.0e-2, 'xatol': 1.0e-2, 'disp': False}} if vqe_option is None: vqe_option = {'disp': print, 'return_all': True, 'samples': samples} if not verbose: vqe_option['disp'] = None qaoa_inst = QAOA(connection, list(range(n_nodes)), steps=num_steps, init_betas=initial_beta, init_gammas=initial_gamma, cost_ham=cost_operators, ref_ham=driver_operators, minimizer=minimize, minimizer_kwargs=minimizer_kwargs, rand_seed=rand_seed, vqe_options=vqe_option, store_basis=True) betas, gammas = qaoa_inst.get_angles() most_freq_string, sampling_results = qaoa_inst.get_string(betas, gammas) most_freq_string_ising = [ising_trans(it) for it in most_freq_string] energy_ising = energy_value(h, J, most_freq_string_ising) param_prog = qaoa_inst.get_parameterized_program() circuit = param_prog(np.hstack((betas, gammas))) return most_freq_string_ising, energy_ising, circuit
[ "def", "ising", "(", "h", ":", "List", "[", "int", "]", ",", "J", ":", "Dict", "[", "Tuple", "[", "int", ",", "int", "]", ",", "int", "]", ",", "num_steps", ":", "int", "=", "0", ",", "verbose", ":", "bool", "=", "True", ",", "rand_seed", ":"...
Ising set up method :param h: External magnetic term of the Ising problem. :param J: Interaction term of the Ising problem. :param num_steps: (Optional.Default=2 * len(h)) Trotterization order for the QAOA algorithm. :param verbose: (Optional.Default=True) Verbosity of the code. :param rand_seed: (Optional. Default=None) random seed when beta and gamma angles are not provided. :param connection: (Optional) connection to the QVM. Default is None. :param samples: (Optional. Default=None) VQE option. Number of samples (circuit preparation and measurement) to use in operator averaging. :param initial_beta: (Optional. Default=None) Initial guess for beta parameters. :param initial_gamma: (Optional. Default=None) Initial guess for gamma parameters. :param minimizer_kwargs: (Optional. Default=None). Minimizer optional arguments. If None set to {'method': 'Nelder-Mead', 'options': {'fatol': 1.0e-2, 'xatol': 1.0e-2, 'disp': False} :param vqe_option: (Optional. Default=None). VQE optional arguments. If None set to vqe_option = {'disp': print_fun, 'return_all': True, 'samples': samples} :return: Most frequent Ising string, Energy of the Ising string, Circuit used to obtain result.
[ "Ising", "set", "up", "method" ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/ising/ising_qaoa.py#L45-L132
train
200,354
rigetti/grove
grove/circuit_primitives/swap.py
swap_circuit_generator
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. """ 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
python
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. """ 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", ":", "if", "len", "(", "register_a", ")", "!=", "len", "(", "register_b...
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.
[ "Generate", "the", "swap", "test", "circuit", "primitive", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/circuit_primitives/swap.py#L20-L48
train
200,355
rigetti/grove
grove/pyqaoa/qaoa.py
QAOA.get_parameterized_program
def get_parameterized_program(self): """ Return a function that accepts parameters and returns a new Quil program. :returns: a function """ 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): """ Construct a Quil program for the vector (beta, gamma). :param params: array of 2 . p angles, betas first, then gammas :return: a pyquil program object """ 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
python
def get_parameterized_program(self): """ Return a function that accepts parameters and returns a new Quil program. :returns: a function """ 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): """ Construct a Quil program for the vector (beta, gamma). :param params: array of 2 . p angles, betas first, then gammas :return: a pyquil program object """ 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", ")", ":", "cost_para_programs", "=", "[", "]", "driver_para_programs", "=", "[", "]", "for", "idx", "in", "range", "(", "self", ".", "steps", ")", ":", "cost_list", "=", "[", "]", "driver_list", "=", "[", ...
Return a function that accepts parameters and returns a new Quil program. :returns: a function
[ "Return", "a", "function", "that", "accepts", "parameters", "and", "returns", "a", "new", "Quil", "program", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/pyqaoa/qaoa.py#L132-L178
train
200,356
rigetti/grove
grove/pyqaoa/qaoa.py
QAOA.get_angles
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. """ 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
python
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. """ 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", "]", "]", ":", "stacked_params", "=", "np", ".", "hstack", "(", "(", "self", ".", "betas", ",", "self", ".", "gammas", ")", ")", "vqe...
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.
[ "Finds", "optimal", "angles", "with", "the", "quantum", "variational", "eigensolver", "method", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/pyqaoa/qaoa.py#L180-L199
train
200,357
rigetti/grove
grove/pyqaoa/qaoa.py
QAOA.probabilities
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. """ 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
python
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. """ 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", ":", "if", "isinstance", "(", "angles", ",", "list", ")", ":", "angles", "=", "np", ".", "array", "(", "angles", ")", "assert", "an...
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.
[ "Computes", "the", "probability", "of", "each", "state", "given", "a", "particular", "set", "of", "angles", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/pyqaoa/qaoa.py#L201-L220
train
200,358
rigetti/grove
grove/pyqaoa/qaoa.py
QAOA.get_string
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. """ 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
python
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. """ 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", ")", ":", "if", "samples", "<=", "0", "and", "not", "isinstance", "(", "samples",...
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.
[ "Compute", "the", "most", "probable", "string", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/pyqaoa/qaoa.py#L222-L252
train
200,359
rigetti/grove
grove/amplification/grover.py
Grover._compute_grover_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 """ 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
python
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 """ 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", ":", "n_bits", "=", "len", "(", "list", "(", "bitstring_map", ".", "keys", "(", ")", ")", "[", "0", "]", ")", "or...
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
[ "Computes", "the", "unitary", "matrix", "that", "encodes", "the", "oracle", "function", "for", "Grover", "s", "algorithm" ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/amplification/grover.py#L43-L58
train
200,360
rigetti/grove
grove/amplification/grover.py
Grover._construct_grover_circuit
def _construct_grover_circuit(self) -> None: """ Constructs an instance of Grover's Algorithm, using initialized values. :return: None """ 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)
python
def _construct_grover_circuit(self) -> None: """ Constructs an instance of Grover's Algorithm, using initialized values. :return: None """ 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", ":", "oracle", "=", "Program", "(", ")", "oracle_name", "=", "\"GROVER_ORACLE\"", "oracle", ".", "defgate", "(", "oracle_name", ",", "self", ".", "unitary_function_mapping", ")", "oracle", ".", ...
Constructs an instance of Grover's Algorithm, using initialized values. :return: None
[ "Constructs", "an", "instance", "of", "Grover", "s", "Algorithm", "using", "initialized", "values", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/amplification/grover.py#L60-L70
train
200,361
rigetti/grove
grove/amplification/grover.py
Grover._init_attr
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 """ 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()
python
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 """ 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", ":", "self", ".", "bit_map", "=", "bitstring_map", "self", ".", "unitary_function_mapping", "=", "self", ".", "_compute_grover_oracle_matrix", ...
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
[ "Initializes", "an", "instance", "of", "Grover", "s", "Algorithm", "given", "a", "bitstring_map", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/amplification/grover.py#L72-L85
train
200,362
rigetti/grove
grove/amplification/grover.py
Grover.find_bitstring
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. """ 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]])
python
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. """ 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", ":", "self", ".", "_init_attr", "(", "bitstring_map", ")", "ro", "=", "self", ".", "grover_circuit"...
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.
[ "Runs", "Grover", "s", "Algorithm", "to", "find", "the", "bitstring", "that", "is", "designated", "by", "bistring_map", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/amplification/grover.py#L87-L108
train
200,363
rigetti/grove
grove/amplification/grover.py
Grover.oracle_grover
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. """ 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
python
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. """ 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", ":", "if", "num_iter", "is", "None", ":", "num_iter", "=", "int", "(", "round", "(", ...
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.
[ "Implementation", "of", "Grover", "s", "Algorithm", "for", "a", "given", "oracle", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/amplification/grover.py#L111-L127
train
200,364
rigetti/grove
grove/alpha/arbitrary_state/arbitrary_state.py
get_rotation_parameters
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 """ # 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
python
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 """ # 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", ")", ":", "# will hold the angles for controlled rotations", "# in the phase unification and probability unification steps,", "# respectively", "z_thetas", "=", "[", "]", "y_thetas", "=", "[", "]", "# will hold...
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
[ "Simulates", "one", "step", "of", "rotations", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/alpha/arbitrary_state/arbitrary_state.py#L65-L120
train
200,365
rigetti/grove
grove/alpha/arbitrary_state/arbitrary_state.py
get_reversed_unification_program
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 """ 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])
python
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 """ 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", ")", ":", "if", "mode", "==", "'phase'", ":", "gate", "=", "RZ", "elif", "mode", "==", "'magnitude'", ":", "gate", "=", "RY", "el...
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
[ "Gets", "the", "Program", "representing", "the", "reversed", "circuit", "for", "the", "decomposition", "of", "the", "uniformly", "controlled", "rotations", "in", "a", "unification", "step", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/alpha/arbitrary_state/arbitrary_state.py#L123-L166
train
200,366
rigetti/grove
grove/alpha/fermion_transforms/fenwick_tree.py
FenwickNode.get_ancestors
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) """ node = self ancestor_list = [] while node.parent is not None: ancestor_list.append(node.parent) node = node.parent return ancestor_list
python
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) """ 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", ")", ":", "node", "=", "self", "ancestor_list", "=", "[", "]", "while", "node", ".", "parent", "is", "not", "None", ":", "ancestor_list", ".", "append", "(", "node", ".", "parent", ")", "node", "=", "node", ".", "...
Returns a list of ancestors of the node. Ordered from the earliest. :return: node's ancestors, ordered from most recent :rtype: list(FenwickNode)
[ "Returns", "a", "list", "of", "ancestors", "of", "the", "node", ".", "Ordered", "from", "the", "earliest", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/alpha/fermion_transforms/fenwick_tree.py#L34-L46
train
200,367
rigetti/grove
grove/bernstein_vazirani/utils.py
bitwise_dot_product
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 """ 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)
python
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 """ 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", ":", "if", "len", "(", "bs0", ")", "!=", "len", "(", "bs1", ")", ":", "raise", "ValueError", "(", "\"Bit strings are not of equal length\"", ")", "return", "s...
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
[ "A", "helper", "to", "calculate", "the", "bitwise", "dot", "-", "product", "between", "two", "string", "representing", "bit", "-", "vectors" ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/bernstein_vazirani/utils.py#L6-L16
train
200,368
rigetti/grove
grove/tomography/utils.py
notebook_mode
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 """ global NOTEBOOK_MODE global TRANGE NOTEBOOK_MODE = m if NOTEBOOK_MODE: TRANGE = tqdm.tnrange else: TRANGE = tqdm.trange
python
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 """ global NOTEBOOK_MODE global TRANGE NOTEBOOK_MODE = m if NOTEBOOK_MODE: TRANGE = tqdm.tnrange else: TRANGE = tqdm.trange
[ "def", "notebook_mode", "(", "m", ")", ":", "global", "NOTEBOOK_MODE", "global", "TRANGE", "NOTEBOOK_MODE", "=", "m", "if", "NOTEBOOK_MODE", ":", "TRANGE", "=", "tqdm", ".", "tnrange", "else", ":", "TRANGE", "=", "tqdm", ".", "trange" ]
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
[ "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", "sequenc...
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/utils.py#L109-L125
train
200,369
rigetti/grove
grove/tomography/utils.py
sample_outcomes
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 """ dist = np.cumsum(probs) rs = np.random.rand(n) return np.array([(np.where(r < dist)[0][0]) for r in rs])
python
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 """ 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", ")", ":", "dist", "=", "np", ".", "cumsum", "(", "probs", ")", "rs", "=", "np", ".", "random", ".", "rand", "(", "n", ")", "return", "np", ".", "array", "(", "[", "(", "np", ".", "where", "(", ...
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
[ "For", "a", "discrete", "probability", "distribution", "probs", "with", "outcomes", "0", "1", "...", "k", "-", "1", "draw", "n", "random", "samples", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/utils.py#L139-L151
train
200,370
rigetti/grove
grove/tomography/utils.py
sample_bad_readout
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 """ wf = cxn.wavefunction(program) return sample_outcomes(assignment_probs.dot(abs(wf.amplitudes.ravel())**2), num_samples)
python
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 """ 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", ")", ":", "wf", "=", "cxn", ".", "wavefunction", "(", "program", ")", "return", "sample_outcomes", "(", "assignment_probs", ".", "dot", "(", "abs", "(", "wf...
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
[ "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" ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/utils.py#L192-L206
train
200,371
rigetti/grove
grove/tomography/utils.py
plot_pauli_transfer_matrix
def plot_pauli_transfer_matrix(ptransfermatrix, ax, labels, title): """ Visualize the Pauli Transfer Matrix of a process. :param numpy.ndarray ptransfermatrix: The Pauli Transfer Matrix :param ax: The matplotlib axes. :param labels: The labels for the operator basis states. :param title: The title for the plot :return: The modified axis object. :rtype: AxesSubplot """ im = ax.imshow(ptransfermatrix, interpolation="nearest", cmap=rigetti_3_color_cm, vmin=-1, vmax=1) dim = len(labels) plt.colorbar(im, ax=ax) ax.set_xticks(range(dim)) ax.set_xlabel("Input Pauli Operator", fontsize=20) ax.set_yticks(range(dim)) ax.set_ylabel("Output Pauli Operator", fontsize=20) ax.set_title(title, fontsize=25) ax.set_xticklabels(labels, rotation=45) ax.set_yticklabels(labels) ax.grid(False) return ax
python
def plot_pauli_transfer_matrix(ptransfermatrix, ax, labels, title): """ Visualize the Pauli Transfer Matrix of a process. :param numpy.ndarray ptransfermatrix: The Pauli Transfer Matrix :param ax: The matplotlib axes. :param labels: The labels for the operator basis states. :param title: The title for the plot :return: The modified axis object. :rtype: AxesSubplot """ im = ax.imshow(ptransfermatrix, interpolation="nearest", cmap=rigetti_3_color_cm, vmin=-1, vmax=1) dim = len(labels) plt.colorbar(im, ax=ax) ax.set_xticks(range(dim)) ax.set_xlabel("Input Pauli Operator", fontsize=20) ax.set_yticks(range(dim)) ax.set_ylabel("Output Pauli Operator", fontsize=20) ax.set_title(title, fontsize=25) ax.set_xticklabels(labels, rotation=45) ax.set_yticklabels(labels) ax.grid(False) return ax
[ "def", "plot_pauli_transfer_matrix", "(", "ptransfermatrix", ",", "ax", ",", "labels", ",", "title", ")", ":", "im", "=", "ax", ".", "imshow", "(", "ptransfermatrix", ",", "interpolation", "=", "\"nearest\"", ",", "cmap", "=", "rigetti_3_color_cm", ",", "vmin"...
Visualize the Pauli Transfer Matrix of a process. :param numpy.ndarray ptransfermatrix: The Pauli Transfer Matrix :param ax: The matplotlib axes. :param labels: The labels for the operator basis states. :param title: The title for the plot :return: The modified axis object. :rtype: AxesSubplot
[ "Visualize", "the", "Pauli", "Transfer", "Matrix", "of", "a", "process", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/utils.py#L244-L268
train
200,372
rigetti/grove
grove/tomography/utils.py
state_histogram
def state_histogram(rho, ax=None, title="", threshold=0.001): """ Visualize a density matrix as a 3d bar plot with complex phase encoded as the bar color. This code is a modified version of `an equivalent function in qutip <http://qutip.org/docs/3.1.0/apidoc/functions.html#qutip.visualization.matrix_histogram_complex>`_ which is released under the (New) BSD license. :param qutip.Qobj rho: The density matrix. :param Axes3D ax: The axes object. :param str title: The axes title. :param float threshold: (Optional) minimum magnitude of matrix elements. Values below this are hidden. :return: The axis :rtype: mpl_toolkits.mplot3d.Axes3D """ rho_amps = rho.data.toarray().ravel() nqc = int(round(np.log2(rho.shape[0]))) if ax is None: fig = plt.figure(figsize=(10, 6)) ax = Axes3D(fig, azim=-35, elev=35) cmap = rigetti_4_color_cm norm = mpl.colors.Normalize(-np.pi, np.pi) colors = cmap(norm(np.angle(rho_amps))) dzs = abs(rho_amps) colors[:, 3] = 1.0 * (dzs > threshold) xs, ys = np.meshgrid(range(2 ** nqc), range(2 ** nqc)) xs = xs.ravel() ys = ys.ravel() zs = np.zeros_like(xs) dxs = dys = np.ones_like(xs) * 0.8 _ = ax.bar3d(xs, ys, zs, dxs, dys, dzs, color=colors) ax.set_xticks(np.arange(2 ** nqc) + .4) ax.set_xticklabels(basis_labels(nqc)) ax.set_yticks(np.arange(2 ** nqc) + .4) ax.set_yticklabels(basis_labels(nqc)) ax.set_zlim3d([0, 1]) cax, kw = mpl.colorbar.make_axes(ax, shrink=.75, pad=.1) cb = mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm) cb.set_ticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi]) cb.set_ticklabels((r'$-\pi$', r'$-\pi/2$', r'$0$', r'$\pi/2$', r'$\pi$')) cb.set_label('arg') ax.view_init(azim=-55, elev=45) ax.set_title(title) return ax
python
def state_histogram(rho, ax=None, title="", threshold=0.001): """ Visualize a density matrix as a 3d bar plot with complex phase encoded as the bar color. This code is a modified version of `an equivalent function in qutip <http://qutip.org/docs/3.1.0/apidoc/functions.html#qutip.visualization.matrix_histogram_complex>`_ which is released under the (New) BSD license. :param qutip.Qobj rho: The density matrix. :param Axes3D ax: The axes object. :param str title: The axes title. :param float threshold: (Optional) minimum magnitude of matrix elements. Values below this are hidden. :return: The axis :rtype: mpl_toolkits.mplot3d.Axes3D """ rho_amps = rho.data.toarray().ravel() nqc = int(round(np.log2(rho.shape[0]))) if ax is None: fig = plt.figure(figsize=(10, 6)) ax = Axes3D(fig, azim=-35, elev=35) cmap = rigetti_4_color_cm norm = mpl.colors.Normalize(-np.pi, np.pi) colors = cmap(norm(np.angle(rho_amps))) dzs = abs(rho_amps) colors[:, 3] = 1.0 * (dzs > threshold) xs, ys = np.meshgrid(range(2 ** nqc), range(2 ** nqc)) xs = xs.ravel() ys = ys.ravel() zs = np.zeros_like(xs) dxs = dys = np.ones_like(xs) * 0.8 _ = ax.bar3d(xs, ys, zs, dxs, dys, dzs, color=colors) ax.set_xticks(np.arange(2 ** nqc) + .4) ax.set_xticklabels(basis_labels(nqc)) ax.set_yticks(np.arange(2 ** nqc) + .4) ax.set_yticklabels(basis_labels(nqc)) ax.set_zlim3d([0, 1]) cax, kw = mpl.colorbar.make_axes(ax, shrink=.75, pad=.1) cb = mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm) cb.set_ticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi]) cb.set_ticklabels((r'$-\pi$', r'$-\pi/2$', r'$0$', r'$\pi/2$', r'$\pi$')) cb.set_label('arg') ax.view_init(azim=-55, elev=45) ax.set_title(title) return ax
[ "def", "state_histogram", "(", "rho", ",", "ax", "=", "None", ",", "title", "=", "\"\"", ",", "threshold", "=", "0.001", ")", ":", "rho_amps", "=", "rho", ".", "data", ".", "toarray", "(", ")", ".", "ravel", "(", ")", "nqc", "=", "int", "(", "rou...
Visualize a density matrix as a 3d bar plot with complex phase encoded as the bar color. This code is a modified version of `an equivalent function in qutip <http://qutip.org/docs/3.1.0/apidoc/functions.html#qutip.visualization.matrix_histogram_complex>`_ which is released under the (New) BSD license. :param qutip.Qobj rho: The density matrix. :param Axes3D ax: The axes object. :param str title: The axes title. :param float threshold: (Optional) minimum magnitude of matrix elements. Values below this are hidden. :return: The axis :rtype: mpl_toolkits.mplot3d.Axes3D
[ "Visualize", "a", "density", "matrix", "as", "a", "3d", "bar", "plot", "with", "complex", "phase", "encoded", "as", "the", "bar", "color", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/utils.py#L285-L332
train
200,373
rigetti/grove
grove/tomography/utils.py
bitlist_to_int
def bitlist_to_int(bitlist): """Convert a binary bitstring into the corresponding unsigned integer. :param list bitlist: A list of ones of zeros. :return: The corresponding integer. :rtype: int """ ret = 0 for b in bitlist: ret = (ret << 1) | (int(b) & 1) return ret
python
def bitlist_to_int(bitlist): """Convert a binary bitstring into the corresponding unsigned integer. :param list bitlist: A list of ones of zeros. :return: The corresponding integer. :rtype: int """ ret = 0 for b in bitlist: ret = (ret << 1) | (int(b) & 1) return ret
[ "def", "bitlist_to_int", "(", "bitlist", ")", ":", "ret", "=", "0", "for", "b", "in", "bitlist", ":", "ret", "=", "(", "ret", "<<", "1", ")", "|", "(", "int", "(", "b", ")", "&", "1", ")", "return", "ret" ]
Convert a binary bitstring into the corresponding unsigned integer. :param list bitlist: A list of ones of zeros. :return: The corresponding integer. :rtype: int
[ "Convert", "a", "binary", "bitstring", "into", "the", "corresponding", "unsigned", "integer", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/utils.py#L335-L346
train
200,374
rigetti/grove
grove/tomography/utils.py
sample_assignment_probs
def sample_assignment_probs(qubits, nsamples, cxn): """ Sample the assignment probabilities of qubits using nsamples per measurement, and then compute the estimated assignment probability matrix. See the docstring for estimate_assignment_probs for more information. :param list qubits: Qubits to sample the assignment probabilities for. :param int nsamples: The number of samples to use in each measurement. :param QPUConnection|QVMConnection cxn: The Connection object to connect to Forest. :return: The assignment probability matrix. :rtype: numpy.ndarray """ num_qubits = len(qubits) dimension = 2 ** num_qubits hists = [] preps = basis_state_preps(*qubits) jobs = [] _log.info('Submitting jobs...') for jj, p in izip(TRANGE(dimension), preps): jobs.append(cxn.run_and_measure_async(p, qubits, nsamples)) _log.info('Waiting for results...') for jj, job_id in izip(TRANGE(dimension), jobs): job = cxn.wait_for_job(job_id) results = job.result() idxs = list(map(bitlist_to_int, results)) hists.append(make_histogram(idxs, dimension)) return estimate_assignment_probs(hists)
python
def sample_assignment_probs(qubits, nsamples, cxn): """ Sample the assignment probabilities of qubits using nsamples per measurement, and then compute the estimated assignment probability matrix. See the docstring for estimate_assignment_probs for more information. :param list qubits: Qubits to sample the assignment probabilities for. :param int nsamples: The number of samples to use in each measurement. :param QPUConnection|QVMConnection cxn: The Connection object to connect to Forest. :return: The assignment probability matrix. :rtype: numpy.ndarray """ num_qubits = len(qubits) dimension = 2 ** num_qubits hists = [] preps = basis_state_preps(*qubits) jobs = [] _log.info('Submitting jobs...') for jj, p in izip(TRANGE(dimension), preps): jobs.append(cxn.run_and_measure_async(p, qubits, nsamples)) _log.info('Waiting for results...') for jj, job_id in izip(TRANGE(dimension), jobs): job = cxn.wait_for_job(job_id) results = job.result() idxs = list(map(bitlist_to_int, results)) hists.append(make_histogram(idxs, dimension)) return estimate_assignment_probs(hists)
[ "def", "sample_assignment_probs", "(", "qubits", ",", "nsamples", ",", "cxn", ")", ":", "num_qubits", "=", "len", "(", "qubits", ")", "dimension", "=", "2", "**", "num_qubits", "hists", "=", "[", "]", "preps", "=", "basis_state_preps", "(", "*", "qubits", ...
Sample the assignment probabilities of qubits using nsamples per measurement, and then compute the estimated assignment probability matrix. See the docstring for estimate_assignment_probs for more information. :param list qubits: Qubits to sample the assignment probabilities for. :param int nsamples: The number of samples to use in each measurement. :param QPUConnection|QVMConnection cxn: The Connection object to connect to Forest. :return: The assignment probability matrix. :rtype: numpy.ndarray
[ "Sample", "the", "assignment", "probabilities", "of", "qubits", "using", "nsamples", "per", "measurement", "and", "then", "compute", "the", "estimated", "assignment", "probability", "matrix", ".", "See", "the", "docstring", "for", "estimate_assignment_probs", "for", ...
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/utils.py#L349-L377
train
200,375
rigetti/grove
grove/tomography/utils.py
run_in_parallel
def run_in_parallel(programs, nsamples, cxn, shuffle=True): """ Take sequences of Protoquil programs on disjoint qubits and execute a single sequence of programs that executes the input programs in parallel. Optionally randomize within each qubit-specific sequence. The programs are passed as a 2d array of Quil programs, where the (first) outer axis iterates over disjoint sets of qubits that the programs involve and the inner axis iterates over a sequence of related programs, e.g., tomography sequences, on the same set of qubits. :param Union[np.ndarray,List[List[Program]]] programs: A rectangular list of lists, or a 2d array of Quil Programs. The outer list iterates over disjoint qubit groups as targets, the inner list over programs to run on those qubits, e.g., tomographic sequences. :param int nsamples: Number of repetitions for executing each Program. :param QPUConnection|QVMConnection cxn: The quantum machine connection. :param bool shuffle: If True, the order of each qubit specific sequence (2nd axis) is randomized Default is True. :return: An array of 2d arrays that provide bitstring histograms for each input program. The axis of the outer array iterates over the disjoint qubit groups, the outer axis of the inner 2d array iterates over the programs for that group and the inner most axis iterates over all possible bitstrings for the qubit group under consideration. :rtype np.array """ if shuffle: n_groups = len(programs) n_progs_per_group = len(programs[0]) permutations = np.outer(np.ones(n_groups, dtype=int), np.arange(n_progs_per_group, dtype=int)) inverse_permutations = np.zeros_like(permutations) for jj in range(n_groups): # in-place operation np.random.shuffle(permutations[jj]) # store inverse permutation inverse_permutations[jj] = np.argsort(permutations[jj]) # apply to programs shuffled_programs = np.empty((n_groups, n_progs_per_group), dtype=object) for jdx, (progsj, pj) in enumerate(zip(programs, permutations)): shuffled_programs[jdx] = [progsj[pjk] for pjk in pj] shuffled_results = _run_in_parallel(shuffled_programs, nsamples, cxn) # reverse shuffling of results results = np.array([resultsj[pj] for resultsj, pj in zip(shuffled_results, inverse_permutations)]) return results else: return _run_in_parallel(programs, nsamples, cxn)
python
def run_in_parallel(programs, nsamples, cxn, shuffle=True): """ Take sequences of Protoquil programs on disjoint qubits and execute a single sequence of programs that executes the input programs in parallel. Optionally randomize within each qubit-specific sequence. The programs are passed as a 2d array of Quil programs, where the (first) outer axis iterates over disjoint sets of qubits that the programs involve and the inner axis iterates over a sequence of related programs, e.g., tomography sequences, on the same set of qubits. :param Union[np.ndarray,List[List[Program]]] programs: A rectangular list of lists, or a 2d array of Quil Programs. The outer list iterates over disjoint qubit groups as targets, the inner list over programs to run on those qubits, e.g., tomographic sequences. :param int nsamples: Number of repetitions for executing each Program. :param QPUConnection|QVMConnection cxn: The quantum machine connection. :param bool shuffle: If True, the order of each qubit specific sequence (2nd axis) is randomized Default is True. :return: An array of 2d arrays that provide bitstring histograms for each input program. The axis of the outer array iterates over the disjoint qubit groups, the outer axis of the inner 2d array iterates over the programs for that group and the inner most axis iterates over all possible bitstrings for the qubit group under consideration. :rtype np.array """ if shuffle: n_groups = len(programs) n_progs_per_group = len(programs[0]) permutations = np.outer(np.ones(n_groups, dtype=int), np.arange(n_progs_per_group, dtype=int)) inverse_permutations = np.zeros_like(permutations) for jj in range(n_groups): # in-place operation np.random.shuffle(permutations[jj]) # store inverse permutation inverse_permutations[jj] = np.argsort(permutations[jj]) # apply to programs shuffled_programs = np.empty((n_groups, n_progs_per_group), dtype=object) for jdx, (progsj, pj) in enumerate(zip(programs, permutations)): shuffled_programs[jdx] = [progsj[pjk] for pjk in pj] shuffled_results = _run_in_parallel(shuffled_programs, nsamples, cxn) # reverse shuffling of results results = np.array([resultsj[pj] for resultsj, pj in zip(shuffled_results, inverse_permutations)]) return results else: return _run_in_parallel(programs, nsamples, cxn)
[ "def", "run_in_parallel", "(", "programs", ",", "nsamples", ",", "cxn", ",", "shuffle", "=", "True", ")", ":", "if", "shuffle", ":", "n_groups", "=", "len", "(", "programs", ")", "n_progs_per_group", "=", "len", "(", "programs", "[", "0", "]", ")", "pe...
Take sequences of Protoquil programs on disjoint qubits and execute a single sequence of programs that executes the input programs in parallel. Optionally randomize within each qubit-specific sequence. The programs are passed as a 2d array of Quil programs, where the (first) outer axis iterates over disjoint sets of qubits that the programs involve and the inner axis iterates over a sequence of related programs, e.g., tomography sequences, on the same set of qubits. :param Union[np.ndarray,List[List[Program]]] programs: A rectangular list of lists, or a 2d array of Quil Programs. The outer list iterates over disjoint qubit groups as targets, the inner list over programs to run on those qubits, e.g., tomographic sequences. :param int nsamples: Number of repetitions for executing each Program. :param QPUConnection|QVMConnection cxn: The quantum machine connection. :param bool shuffle: If True, the order of each qubit specific sequence (2nd axis) is randomized Default is True. :return: An array of 2d arrays that provide bitstring histograms for each input program. The axis of the outer array iterates over the disjoint qubit groups, the outer axis of the inner 2d array iterates over the programs for that group and the inner most axis iterates over all possible bitstrings for the qubit group under consideration. :rtype np.array
[ "Take", "sequences", "of", "Protoquil", "programs", "on", "disjoint", "qubits", "and", "execute", "a", "single", "sequence", "of", "programs", "that", "executes", "the", "input", "programs", "in", "parallel", ".", "Optionally", "randomize", "within", "each", "qu...
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/utils.py#L380-L429
train
200,376
rigetti/grove
grove/measurements/estimation.py
remove_imaginary_terms
def remove_imaginary_terms(pauli_sums: PauliSum) -> PauliSum: """ Remove the imaginary component of each term in a Pauli sum. :param pauli_sums: The Pauli sum to process. :return: a purely Hermitian Pauli sum. """ if not isinstance(pauli_sums, PauliSum): raise TypeError("not a pauli sum. please give me one") new_term = sI(0) * 0.0 for term in pauli_sums: new_term += term_with_coeff(term, term.coefficient.real) return new_term
python
def remove_imaginary_terms(pauli_sums: PauliSum) -> PauliSum: """ Remove the imaginary component of each term in a Pauli sum. :param pauli_sums: The Pauli sum to process. :return: a purely Hermitian Pauli sum. """ if not isinstance(pauli_sums, PauliSum): raise TypeError("not a pauli sum. please give me one") new_term = sI(0) * 0.0 for term in pauli_sums: new_term += term_with_coeff(term, term.coefficient.real) return new_term
[ "def", "remove_imaginary_terms", "(", "pauli_sums", ":", "PauliSum", ")", "->", "PauliSum", ":", "if", "not", "isinstance", "(", "pauli_sums", ",", "PauliSum", ")", ":", "raise", "TypeError", "(", "\"not a pauli sum. please give me one\"", ")", "new_term", "=", "s...
Remove the imaginary component of each term in a Pauli sum. :param pauli_sums: The Pauli sum to process. :return: a purely Hermitian Pauli sum.
[ "Remove", "the", "imaginary", "component", "of", "each", "term", "in", "a", "Pauli", "sum", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/measurements/estimation.py#L21-L34
train
200,377
rigetti/grove
grove/measurements/estimation.py
get_rotation_program
def get_rotation_program(pauli_term: PauliTerm) -> Program: """ Generate a rotation program so that the pauli term is diagonal. :param pauli_term: The Pauli term used to generate diagonalizing one-qubit rotations. :return: The rotation program. """ meas_basis_change = Program() for index, gate in pauli_term: if gate == 'X': meas_basis_change.inst(RY(-np.pi / 2, index)) elif gate == 'Y': meas_basis_change.inst(RX(np.pi / 2, index)) elif gate == 'Z': pass else: raise ValueError() return meas_basis_change
python
def get_rotation_program(pauli_term: PauliTerm) -> Program: """ Generate a rotation program so that the pauli term is diagonal. :param pauli_term: The Pauli term used to generate diagonalizing one-qubit rotations. :return: The rotation program. """ meas_basis_change = Program() for index, gate in pauli_term: if gate == 'X': meas_basis_change.inst(RY(-np.pi / 2, index)) elif gate == 'Y': meas_basis_change.inst(RX(np.pi / 2, index)) elif gate == 'Z': pass else: raise ValueError() return meas_basis_change
[ "def", "get_rotation_program", "(", "pauli_term", ":", "PauliTerm", ")", "->", "Program", ":", "meas_basis_change", "=", "Program", "(", ")", "for", "index", ",", "gate", "in", "pauli_term", ":", "if", "gate", "==", "'X'", ":", "meas_basis_change", ".", "ins...
Generate a rotation program so that the pauli term is diagonal. :param pauli_term: The Pauli term used to generate diagonalizing one-qubit rotations. :return: The rotation program.
[ "Generate", "a", "rotation", "program", "so", "that", "the", "pauli", "term", "is", "diagonal", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/measurements/estimation.py#L37-L55
train
200,378
rigetti/grove
grove/alpha/phaseestimation/phase_estimation.py
controlled
def controlled(m: np.ndarray) -> np.ndarray: """ Make a one-qubit-controlled version of a matrix. :param m: A matrix. :return: A controlled version of that matrix. """ rows, cols = m.shape assert rows == cols n = rows I = np.eye(n) Z = np.zeros((n, n)) controlled_m = np.bmat([[I, Z], [Z, m]]) return controlled_m
python
def controlled(m: np.ndarray) -> np.ndarray: """ Make a one-qubit-controlled version of a matrix. :param m: A matrix. :return: A controlled version of that matrix. """ rows, cols = m.shape assert rows == cols n = rows I = np.eye(n) Z = np.zeros((n, n)) controlled_m = np.bmat([[I, Z], [Z, m]]) return controlled_m
[ "def", "controlled", "(", "m", ":", "np", ".", "ndarray", ")", "->", "np", ".", "ndarray", ":", "rows", ",", "cols", "=", "m", ".", "shape", "assert", "rows", "==", "cols", "n", "=", "rows", "I", "=", "np", ".", "eye", "(", "n", ")", "Z", "="...
Make a one-qubit-controlled version of a matrix. :param m: A matrix. :return: A controlled version of that matrix.
[ "Make", "a", "one", "-", "qubit", "-", "controlled", "version", "of", "a", "matrix", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/alpha/phaseestimation/phase_estimation.py#L28-L42
train
200,379
rigetti/grove
grove/alpha/phaseestimation/phase_estimation.py
phase_estimation
def phase_estimation(U: np.ndarray, accuracy: int, reg_offset: int = 0) -> Program: """ Generate a circuit for quantum phase estimation. :param U: A unitary matrix. :param accuracy: Number of bits of accuracy desired. :param reg_offset: Where to start writing measurements (default 0). :return: A Quil program to perform phase estimation. """ assert isinstance(accuracy, int) rows, cols = U.shape m = int(log2(rows)) output_qubits = range(0, accuracy) U_qubits = range(accuracy, accuracy + m) p = Program() ro = p.declare('ro', 'BIT', len(output_qubits)) # Hadamard initialization for i in output_qubits: p.inst(H(i)) # Controlled unitaries for i in output_qubits: if i > 0: U = np.dot(U, U) cU = controlled(U) name = "CONTROLLED-U{0}".format(2 ** i) # define the gate p.defgate(name, cU) # apply it p.inst((name, i) + tuple(U_qubits)) # Compute the QFT p = p + inverse_qft(output_qubits) # Perform the measurements for i in output_qubits: p.measure(i, ro[reg_offset + i]) return p
python
def phase_estimation(U: np.ndarray, accuracy: int, reg_offset: int = 0) -> Program: """ Generate a circuit for quantum phase estimation. :param U: A unitary matrix. :param accuracy: Number of bits of accuracy desired. :param reg_offset: Where to start writing measurements (default 0). :return: A Quil program to perform phase estimation. """ assert isinstance(accuracy, int) rows, cols = U.shape m = int(log2(rows)) output_qubits = range(0, accuracy) U_qubits = range(accuracy, accuracy + m) p = Program() ro = p.declare('ro', 'BIT', len(output_qubits)) # Hadamard initialization for i in output_qubits: p.inst(H(i)) # Controlled unitaries for i in output_qubits: if i > 0: U = np.dot(U, U) cU = controlled(U) name = "CONTROLLED-U{0}".format(2 ** i) # define the gate p.defgate(name, cU) # apply it p.inst((name, i) + tuple(U_qubits)) # Compute the QFT p = p + inverse_qft(output_qubits) # Perform the measurements for i in output_qubits: p.measure(i, ro[reg_offset + i]) return p
[ "def", "phase_estimation", "(", "U", ":", "np", ".", "ndarray", ",", "accuracy", ":", "int", ",", "reg_offset", ":", "int", "=", "0", ")", "->", "Program", ":", "assert", "isinstance", "(", "accuracy", ",", "int", ")", "rows", ",", "cols", "=", "U", ...
Generate a circuit for quantum phase estimation. :param U: A unitary matrix. :param accuracy: Number of bits of accuracy desired. :param reg_offset: Where to start writing measurements (default 0). :return: A Quil program to perform phase estimation.
[ "Generate", "a", "circuit", "for", "quantum", "phase", "estimation", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/alpha/phaseestimation/phase_estimation.py#L45-L81
train
200,380
rigetti/grove
grove/alpha/jordan_gradient/gradient_utils.py
binary_float_to_decimal_float
def binary_float_to_decimal_float(number: Union[float, str]) -> float: """ Convert binary floating point to decimal floating point. :param number: Binary floating point. :return: Decimal floating point representation of binary floating point. """ if isinstance(number, str): if number[0] == '-': n_sign = -1 else: n_sign = 1 elif isinstance(number, float): n_sign = np.sign(number) number = str(number) deci = 0 for ndx, val in enumerate(number.split('.')[-1]): deci += float(val) / 2**(ndx+1) deci *= n_sign return deci
python
def binary_float_to_decimal_float(number: Union[float, str]) -> float: """ Convert binary floating point to decimal floating point. :param number: Binary floating point. :return: Decimal floating point representation of binary floating point. """ if isinstance(number, str): if number[0] == '-': n_sign = -1 else: n_sign = 1 elif isinstance(number, float): n_sign = np.sign(number) number = str(number) deci = 0 for ndx, val in enumerate(number.split('.')[-1]): deci += float(val) / 2**(ndx+1) deci *= n_sign return deci
[ "def", "binary_float_to_decimal_float", "(", "number", ":", "Union", "[", "float", ",", "str", "]", ")", "->", "float", ":", "if", "isinstance", "(", "number", ",", "str", ")", ":", "if", "number", "[", "0", "]", "==", "'-'", ":", "n_sign", "=", "-",...
Convert binary floating point to decimal floating point. :param number: Binary floating point. :return: Decimal floating point representation of binary floating point.
[ "Convert", "binary", "floating", "point", "to", "decimal", "floating", "point", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/alpha/jordan_gradient/gradient_utils.py#L6-L27
train
200,381
rigetti/grove
grove/alpha/jordan_gradient/gradient_utils.py
measurements_to_bf
def measurements_to_bf(measurements: np.ndarray) -> float: """ Convert measurements into gradient binary fraction. :param measurements: Output measurements of gradient program. :return: Binary fraction representation of gradient estimate. """ try: measurements.sum(axis=0) except AttributeError: measurements = np.asarray(measurements) finally: stats = measurements.sum(axis=0) / len(measurements) stats_str = [str(int(i)) for i in np.round(stats[::-1][1:])] bf_str = '0.' + ''.join(stats_str) bf = float(bf_str) return bf
python
def measurements_to_bf(measurements: np.ndarray) -> float: """ Convert measurements into gradient binary fraction. :param measurements: Output measurements of gradient program. :return: Binary fraction representation of gradient estimate. """ try: measurements.sum(axis=0) except AttributeError: measurements = np.asarray(measurements) finally: stats = measurements.sum(axis=0) / len(measurements) stats_str = [str(int(i)) for i in np.round(stats[::-1][1:])] bf_str = '0.' + ''.join(stats_str) bf = float(bf_str) return bf
[ "def", "measurements_to_bf", "(", "measurements", ":", "np", ".", "ndarray", ")", "->", "float", ":", "try", ":", "measurements", ".", "sum", "(", "axis", "=", "0", ")", "except", "AttributeError", ":", "measurements", "=", "np", ".", "asarray", "(", "me...
Convert measurements into gradient binary fraction. :param measurements: Output measurements of gradient program. :return: Binary fraction representation of gradient estimate.
[ "Convert", "measurements", "into", "gradient", "binary", "fraction", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/alpha/jordan_gradient/gradient_utils.py#L30-L48
train
200,382
rigetti/grove
grove/amplification/amplification.py
amplification_circuit
def amplification_circuit(algorithm: Program, oracle: Program, qubits: List[int], num_iter: int, decompose_diffusion: bool = False) -> Program: """ Returns a program that does ``num_iter`` rounds of amplification, given a measurement-less algorithm, an oracle, and a list of qubits to operate on. :param algorithm: A program representing a measurement-less algorithm run on qubits. :param oracle: An oracle maps any basis vector ``|psi>`` to either ``+|psi>`` or ``-|psi>`` depending on whether ``|psi>`` is in the desirable subspace or the undesirable subspace. :param qubits: the qubits to operate on :param num_iter: number of iterations of amplifications to run :param decompose_diffusion: If True, decompose the Grover diffusion gate into two qubit gates. If False, use a defgate to define the gate. :return: The amplified algorithm. """ program = Program() uniform_superimposer = Program().inst([H(qubit) for qubit in qubits]) program += uniform_superimposer if decompose_diffusion: diffusion = decomposed_diffusion_program(qubits) else: diffusion = diffusion_program(qubits) # To avoid redefining gates, we collect them before building our program. defined_gates = oracle.defined_gates + algorithm.defined_gates + diffusion.defined_gates for _ in range(num_iter): program += (oracle.instructions + algorithm.dagger().instructions + diffusion.instructions + algorithm.instructions) # We redefine the gates in the new program. for gate in defined_gates: program.defgate(gate.name, gate.matrix) return program
python
def amplification_circuit(algorithm: Program, oracle: Program, qubits: List[int], num_iter: int, decompose_diffusion: bool = False) -> Program: """ Returns a program that does ``num_iter`` rounds of amplification, given a measurement-less algorithm, an oracle, and a list of qubits to operate on. :param algorithm: A program representing a measurement-less algorithm run on qubits. :param oracle: An oracle maps any basis vector ``|psi>`` to either ``+|psi>`` or ``-|psi>`` depending on whether ``|psi>`` is in the desirable subspace or the undesirable subspace. :param qubits: the qubits to operate on :param num_iter: number of iterations of amplifications to run :param decompose_diffusion: If True, decompose the Grover diffusion gate into two qubit gates. If False, use a defgate to define the gate. :return: The amplified algorithm. """ program = Program() uniform_superimposer = Program().inst([H(qubit) for qubit in qubits]) program += uniform_superimposer if decompose_diffusion: diffusion = decomposed_diffusion_program(qubits) else: diffusion = diffusion_program(qubits) # To avoid redefining gates, we collect them before building our program. defined_gates = oracle.defined_gates + algorithm.defined_gates + diffusion.defined_gates for _ in range(num_iter): program += (oracle.instructions + algorithm.dagger().instructions + diffusion.instructions + algorithm.instructions) # We redefine the gates in the new program. for gate in defined_gates: program.defgate(gate.name, gate.matrix) return program
[ "def", "amplification_circuit", "(", "algorithm", ":", "Program", ",", "oracle", ":", "Program", ",", "qubits", ":", "List", "[", "int", "]", ",", "num_iter", ":", "int", ",", "decompose_diffusion", ":", "bool", "=", "False", ")", "->", "Program", ":", "...
Returns a program that does ``num_iter`` rounds of amplification, given a measurement-less algorithm, an oracle, and a list of qubits to operate on. :param algorithm: A program representing a measurement-less algorithm run on qubits. :param oracle: An oracle maps any basis vector ``|psi>`` to either ``+|psi>`` or ``-|psi>`` depending on whether ``|psi>`` is in the desirable subspace or the undesirable subspace. :param qubits: the qubits to operate on :param num_iter: number of iterations of amplifications to run :param decompose_diffusion: If True, decompose the Grover diffusion gate into two qubit gates. If False, use a defgate to define the gate. :return: The amplified algorithm.
[ "Returns", "a", "program", "that", "does", "num_iter", "rounds", "of", "amplification", "given", "a", "measurement", "-", "less", "algorithm", "an", "oracle", "and", "a", "list", "of", "qubits", "to", "operate", "on", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/amplification/amplification.py#L47-L83
train
200,383
rigetti/grove
grove/alpha/fermion_transforms/jwtransform.py
JWTransform._operator_generator
def _operator_generator(index, conj): """ Internal method to generate the appropriate operator """ pterm = PauliTerm('I', 0, 1.0) Zstring = PauliTerm('I', 0, 1.0) for j in range(index): Zstring = Zstring*PauliTerm('Z', j, 1.0) pterm1 = Zstring*PauliTerm('X', index, 0.5) scalar = 0.5 * conj * 1.0j pterm2 = Zstring*PauliTerm('Y', index, scalar) pterm = pterm * (pterm1 + pterm2) pterm = pterm.simplify() return pterm
python
def _operator_generator(index, conj): """ Internal method to generate the appropriate operator """ pterm = PauliTerm('I', 0, 1.0) Zstring = PauliTerm('I', 0, 1.0) for j in range(index): Zstring = Zstring*PauliTerm('Z', j, 1.0) pterm1 = Zstring*PauliTerm('X', index, 0.5) scalar = 0.5 * conj * 1.0j pterm2 = Zstring*PauliTerm('Y', index, scalar) pterm = pterm * (pterm1 + pterm2) pterm = pterm.simplify() return pterm
[ "def", "_operator_generator", "(", "index", ",", "conj", ")", ":", "pterm", "=", "PauliTerm", "(", "'I'", ",", "0", ",", "1.0", ")", "Zstring", "=", "PauliTerm", "(", "'I'", ",", "0", ",", "1.0", ")", "for", "j", "in", "range", "(", "index", ")", ...
Internal method to generate the appropriate operator
[ "Internal", "method", "to", "generate", "the", "appropriate", "operator" ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/alpha/fermion_transforms/jwtransform.py#L62-L77
train
200,384
rigetti/grove
grove/pyqaoa/maxcut_qaoa.py
maxcut_qaoa
def maxcut_qaoa(graph, steps=1, rand_seed=None, connection=None, samples=None, initial_beta=None, initial_gamma=None, minimizer_kwargs=None, vqe_option=None): """ Max cut set up method :param graph: Graph definition. Either networkx or list of tuples :param steps: (Optional. Default=1) Trotterization order for the QAOA algorithm. :param rand_seed: (Optional. Default=None) random seed when beta and gamma angles are not provided. :param connection: (Optional) connection to the QVM. Default is None. :param samples: (Optional. Default=None) VQE option. Number of samples (circuit preparation and measurement) to use in operator averaging. :param initial_beta: (Optional. Default=None) Initial guess for beta parameters. :param initial_gamma: (Optional. Default=None) Initial guess for gamma parameters. :param minimizer_kwargs: (Optional. Default=None). Minimizer optional arguments. If None set to ``{'method': 'Nelder-Mead', 'options': {'ftol': 1.0e-2, 'xtol': 1.0e-2, 'disp': False}`` :param vqe_option: (Optional. Default=None). VQE optional arguments. If None set to ``vqe_option = {'disp': print_fun, 'return_all': True, 'samples': samples}`` """ if not isinstance(graph, nx.Graph) and isinstance(graph, list): maxcut_graph = nx.Graph() for edge in graph: maxcut_graph.add_edge(*edge) graph = maxcut_graph.copy() cost_operators = [] driver_operators = [] for i, j in graph.edges(): cost_operators.append(PauliTerm("Z", i, 0.5)*PauliTerm("Z", j) + PauliTerm("I", 0, -0.5)) for i in graph.nodes(): driver_operators.append(PauliSum([PauliTerm("X", i, -1.0)])) if connection is None: connection = get_qc(f"{len(graph.nodes)}q-qvm") if minimizer_kwargs is None: minimizer_kwargs = {'method': 'Nelder-Mead', 'options': {'ftol': 1.0e-2, 'xtol': 1.0e-2, 'disp': False}} if vqe_option is None: vqe_option = {'disp': print, 'return_all': True, 'samples': samples} qaoa_inst = QAOA(connection, list(graph.nodes()), steps=steps, cost_ham=cost_operators, ref_ham=driver_operators, store_basis=True, rand_seed=rand_seed, init_betas=initial_beta, init_gammas=initial_gamma, minimizer=minimize, minimizer_kwargs=minimizer_kwargs, vqe_options=vqe_option) return qaoa_inst
python
def maxcut_qaoa(graph, steps=1, rand_seed=None, connection=None, samples=None, initial_beta=None, initial_gamma=None, minimizer_kwargs=None, vqe_option=None): """ Max cut set up method :param graph: Graph definition. Either networkx or list of tuples :param steps: (Optional. Default=1) Trotterization order for the QAOA algorithm. :param rand_seed: (Optional. Default=None) random seed when beta and gamma angles are not provided. :param connection: (Optional) connection to the QVM. Default is None. :param samples: (Optional. Default=None) VQE option. Number of samples (circuit preparation and measurement) to use in operator averaging. :param initial_beta: (Optional. Default=None) Initial guess for beta parameters. :param initial_gamma: (Optional. Default=None) Initial guess for gamma parameters. :param minimizer_kwargs: (Optional. Default=None). Minimizer optional arguments. If None set to ``{'method': 'Nelder-Mead', 'options': {'ftol': 1.0e-2, 'xtol': 1.0e-2, 'disp': False}`` :param vqe_option: (Optional. Default=None). VQE optional arguments. If None set to ``vqe_option = {'disp': print_fun, 'return_all': True, 'samples': samples}`` """ if not isinstance(graph, nx.Graph) and isinstance(graph, list): maxcut_graph = nx.Graph() for edge in graph: maxcut_graph.add_edge(*edge) graph = maxcut_graph.copy() cost_operators = [] driver_operators = [] for i, j in graph.edges(): cost_operators.append(PauliTerm("Z", i, 0.5)*PauliTerm("Z", j) + PauliTerm("I", 0, -0.5)) for i in graph.nodes(): driver_operators.append(PauliSum([PauliTerm("X", i, -1.0)])) if connection is None: connection = get_qc(f"{len(graph.nodes)}q-qvm") if minimizer_kwargs is None: minimizer_kwargs = {'method': 'Nelder-Mead', 'options': {'ftol': 1.0e-2, 'xtol': 1.0e-2, 'disp': False}} if vqe_option is None: vqe_option = {'disp': print, 'return_all': True, 'samples': samples} qaoa_inst = QAOA(connection, list(graph.nodes()), steps=steps, cost_ham=cost_operators, ref_ham=driver_operators, store_basis=True, rand_seed=rand_seed, init_betas=initial_beta, init_gammas=initial_gamma, minimizer=minimize, minimizer_kwargs=minimizer_kwargs, vqe_options=vqe_option) return qaoa_inst
[ "def", "maxcut_qaoa", "(", "graph", ",", "steps", "=", "1", ",", "rand_seed", "=", "None", ",", "connection", "=", "None", ",", "samples", "=", "None", ",", "initial_beta", "=", "None", ",", "initial_gamma", "=", "None", ",", "minimizer_kwargs", "=", "No...
Max cut set up method :param graph: Graph definition. Either networkx or list of tuples :param steps: (Optional. Default=1) Trotterization order for the QAOA algorithm. :param rand_seed: (Optional. Default=None) random seed when beta and gamma angles are not provided. :param connection: (Optional) connection to the QVM. Default is None. :param samples: (Optional. Default=None) VQE option. Number of samples (circuit preparation and measurement) to use in operator averaging. :param initial_beta: (Optional. Default=None) Initial guess for beta parameters. :param initial_gamma: (Optional. Default=None) Initial guess for gamma parameters. :param minimizer_kwargs: (Optional. Default=None). Minimizer optional arguments. If None set to ``{'method': 'Nelder-Mead', 'options': {'ftol': 1.0e-2, 'xtol': 1.0e-2, 'disp': False}`` :param vqe_option: (Optional. Default=None). VQE optional arguments. If None set to ``vqe_option = {'disp': print_fun, 'return_all': True, 'samples': samples}``
[ "Max", "cut", "set", "up", "method" ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/pyqaoa/maxcut_qaoa.py#L29-L83
train
200,385
rigetti/grove
grove/tomography/tomography.py
default_rotations
def default_rotations(*qubits): """ Generates the Quil programs for the tomographic pre- and post-rotations of any number of qubits. :param list qubits: A list of qubits to perform tomography on. """ for gates in cartesian_product(TOMOGRAPHY_GATES.keys(), repeat=len(qubits)): tomography_program = Program() for qubit, gate in izip(qubits, gates): tomography_program.inst(gate(qubit)) yield tomography_program
python
def default_rotations(*qubits): """ Generates the Quil programs for the tomographic pre- and post-rotations of any number of qubits. :param list qubits: A list of qubits to perform tomography on. """ for gates in cartesian_product(TOMOGRAPHY_GATES.keys(), repeat=len(qubits)): tomography_program = Program() for qubit, gate in izip(qubits, gates): tomography_program.inst(gate(qubit)) yield tomography_program
[ "def", "default_rotations", "(", "*", "qubits", ")", ":", "for", "gates", "in", "cartesian_product", "(", "TOMOGRAPHY_GATES", ".", "keys", "(", ")", ",", "repeat", "=", "len", "(", "qubits", ")", ")", ":", "tomography_program", "=", "Program", "(", ")", ...
Generates the Quil programs for the tomographic pre- and post-rotations of any number of qubits. :param list qubits: A list of qubits to perform tomography on.
[ "Generates", "the", "Quil", "programs", "for", "the", "tomographic", "pre", "-", "and", "post", "-", "rotations", "of", "any", "number", "of", "qubits", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/tomography.py#L72-L82
train
200,386
rigetti/grove
grove/tomography/tomography.py
default_channel_ops
def default_channel_ops(nqubits): """ Generate the tomographic pre- and post-rotations of any number of qubits as qutip operators. :param int nqubits: The number of qubits to perform tomography on. :return: Qutip object corresponding to the tomographic rotation. :rtype: Qobj """ for gates in cartesian_product(TOMOGRAPHY_GATES.values(), repeat=nqubits): yield qt.tensor(*gates)
python
def default_channel_ops(nqubits): """ Generate the tomographic pre- and post-rotations of any number of qubits as qutip operators. :param int nqubits: The number of qubits to perform tomography on. :return: Qutip object corresponding to the tomographic rotation. :rtype: Qobj """ for gates in cartesian_product(TOMOGRAPHY_GATES.values(), repeat=nqubits): yield qt.tensor(*gates)
[ "def", "default_channel_ops", "(", "nqubits", ")", ":", "for", "gates", "in", "cartesian_product", "(", "TOMOGRAPHY_GATES", ".", "values", "(", ")", ",", "repeat", "=", "nqubits", ")", ":", "yield", "qt", ".", "tensor", "(", "*", "gates", ")" ]
Generate the tomographic pre- and post-rotations of any number of qubits as qutip operators. :param int nqubits: The number of qubits to perform tomography on. :return: Qutip object corresponding to the tomographic rotation. :rtype: Qobj
[ "Generate", "the", "tomographic", "pre", "-", "and", "post", "-", "rotations", "of", "any", "number", "of", "qubits", "as", "qutip", "operators", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/tomography.py#L85-L94
train
200,387
rigetti/grove
grove/tomography/tomography.py
_SDP_SOLVER.is_functional
def is_functional(cls): """ Checks lazily whether a convex solver is installed that handles positivity constraints. :return: True if a solver supporting positivity constraints is installed. :rtype: bool """ if not cls._tested: cls._tested = True np.random.seed(SEED) test_problem_dimension = 10 mat = np.random.randn(test_problem_dimension, test_problem_dimension) posmat = mat.dot(mat.T) posvar = cvxpy.Variable(test_problem_dimension, test_problem_dimension) prob = cvxpy.Problem(cvxpy.Minimize((cvxpy.trace(posmat * posvar) + cvxpy.norm(posvar))), [posvar >> 0, cvxpy.trace(posvar) >= 1.]) try: prob.solve(SOLVER) cls._functional = True except cvxpy.SolverError: # pragma no coverage _log.warning("No convex SDP solver found. You will not be able to solve" " tomography problems with matrix positivity constraints.") return cls._functional
python
def is_functional(cls): """ Checks lazily whether a convex solver is installed that handles positivity constraints. :return: True if a solver supporting positivity constraints is installed. :rtype: bool """ if not cls._tested: cls._tested = True np.random.seed(SEED) test_problem_dimension = 10 mat = np.random.randn(test_problem_dimension, test_problem_dimension) posmat = mat.dot(mat.T) posvar = cvxpy.Variable(test_problem_dimension, test_problem_dimension) prob = cvxpy.Problem(cvxpy.Minimize((cvxpy.trace(posmat * posvar) + cvxpy.norm(posvar))), [posvar >> 0, cvxpy.trace(posvar) >= 1.]) try: prob.solve(SOLVER) cls._functional = True except cvxpy.SolverError: # pragma no coverage _log.warning("No convex SDP solver found. You will not be able to solve" " tomography problems with matrix positivity constraints.") return cls._functional
[ "def", "is_functional", "(", "cls", ")", ":", "if", "not", "cls", ".", "_tested", ":", "cls", ".", "_tested", "=", "True", "np", ".", "random", ".", "seed", "(", "SEED", ")", "test_problem_dimension", "=", "10", "mat", "=", "np", ".", "random", ".", ...
Checks lazily whether a convex solver is installed that handles positivity constraints. :return: True if a solver supporting positivity constraints is installed. :rtype: bool
[ "Checks", "lazily", "whether", "a", "convex", "solver", "is", "installed", "that", "handles", "positivity", "constraints", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/tomography.py#L111-L135
train
200,388
rigetti/grove
grove/measurements/amplitude_measurement.py
measure_wf_coefficients
def measure_wf_coefficients(prep_program, coeff_list, reference_state, quantum_resource, variance_bound=1.0E-6): """ Measure a set of coefficients with a phase relative to the reference_state :param prep_program: pyQuil program to prepare the state :param coeff_list: list of integers labeling amplitudes to measure :param reference_state: Integer of the computational basis state to use as a reference :param quantum_resource: An instance of a quantum abstract machine :param variance_bound: Default 1.0E-6. variance of the monte carlo estimator for the non-hermitian operator :return: returns a list of reference_state amplitude + coeff_list amplitudes """ num_qubits = len(prep_program.get_qubits()) normalizer_ops = projector_generator(reference_state, reference_state) c0_coeff, _, _ = estimate_locally_commuting_operator( prep_program, normalizer_ops, variance_bound=variance_bound, quantum_resource=quantum_resource) c0_coeff = np.sqrt(c0_coeff) amplitudes = [] for ii in coeff_list: if ii == reference_state: amplitudes.append(c0_coeff) else: bra = list(map(int, np.binary_repr(ii, width=num_qubits))) c_ii_op = projector_generator(reference_state, bra) result = estimate_locally_commuting_operator( prep_program, c_ii_op, variance_bound=variance_bound, quantum_resource=quantum_resource) amplitudes.append(result[0] / c0_coeff) return amplitudes
python
def measure_wf_coefficients(prep_program, coeff_list, reference_state, quantum_resource, variance_bound=1.0E-6): """ Measure a set of coefficients with a phase relative to the reference_state :param prep_program: pyQuil program to prepare the state :param coeff_list: list of integers labeling amplitudes to measure :param reference_state: Integer of the computational basis state to use as a reference :param quantum_resource: An instance of a quantum abstract machine :param variance_bound: Default 1.0E-6. variance of the monte carlo estimator for the non-hermitian operator :return: returns a list of reference_state amplitude + coeff_list amplitudes """ num_qubits = len(prep_program.get_qubits()) normalizer_ops = projector_generator(reference_state, reference_state) c0_coeff, _, _ = estimate_locally_commuting_operator( prep_program, normalizer_ops, variance_bound=variance_bound, quantum_resource=quantum_resource) c0_coeff = np.sqrt(c0_coeff) amplitudes = [] for ii in coeff_list: if ii == reference_state: amplitudes.append(c0_coeff) else: bra = list(map(int, np.binary_repr(ii, width=num_qubits))) c_ii_op = projector_generator(reference_state, bra) result = estimate_locally_commuting_operator( prep_program, c_ii_op, variance_bound=variance_bound, quantum_resource=quantum_resource) amplitudes.append(result[0] / c0_coeff) return amplitudes
[ "def", "measure_wf_coefficients", "(", "prep_program", ",", "coeff_list", ",", "reference_state", ",", "quantum_resource", ",", "variance_bound", "=", "1.0E-6", ")", ":", "num_qubits", "=", "len", "(", "prep_program", ".", "get_qubits", "(", ")", ")", "normalizer_...
Measure a set of coefficients with a phase relative to the reference_state :param prep_program: pyQuil program to prepare the state :param coeff_list: list of integers labeling amplitudes to measure :param reference_state: Integer of the computational basis state to use as a reference :param quantum_resource: An instance of a quantum abstract machine :param variance_bound: Default 1.0E-6. variance of the monte carlo estimator for the non-hermitian operator :return: returns a list of reference_state amplitude + coeff_list amplitudes
[ "Measure", "a", "set", "of", "coefficients", "with", "a", "phase", "relative", "to", "the", "reference_state" ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/measurements/amplitude_measurement.py#L76-L110
train
200,389
rigetti/grove
grove/measurements/amplitude_measurement.py
measure_pure_state
def measure_pure_state(prep_program, reference_state, quantum_resource, variance_bound=1.0E-6): """ Measure the coefficients of the pure state :param prep_program: pyQuil program to prepare the state :param reference_state: Integer of the computational basis state to use as a reference :param quantum_resource: An instance of a quantum abstract machine :param variance_bound: Default 1.0E-6. variance of the monte carlo estimator for the non-hermitian operator :return: an estimate of the wavefunction as a numpy.ndarray """ num_qubits = len(prep_program.get_qubits()) amplitudes_to_measure = list(range(2 ** num_qubits)) amplitudes = measure_wf_coefficients(prep_program, amplitudes_to_measure, reference_state, quantum_resource, variance_bound=variance_bound) wavefunction = np.asarray(amplitudes) return wavefunction.reshape((-1, 1))
python
def measure_pure_state(prep_program, reference_state, quantum_resource, variance_bound=1.0E-6): """ Measure the coefficients of the pure state :param prep_program: pyQuil program to prepare the state :param reference_state: Integer of the computational basis state to use as a reference :param quantum_resource: An instance of a quantum abstract machine :param variance_bound: Default 1.0E-6. variance of the monte carlo estimator for the non-hermitian operator :return: an estimate of the wavefunction as a numpy.ndarray """ num_qubits = len(prep_program.get_qubits()) amplitudes_to_measure = list(range(2 ** num_qubits)) amplitudes = measure_wf_coefficients(prep_program, amplitudes_to_measure, reference_state, quantum_resource, variance_bound=variance_bound) wavefunction = np.asarray(amplitudes) return wavefunction.reshape((-1, 1))
[ "def", "measure_pure_state", "(", "prep_program", ",", "reference_state", ",", "quantum_resource", ",", "variance_bound", "=", "1.0E-6", ")", ":", "num_qubits", "=", "len", "(", "prep_program", ".", "get_qubits", "(", ")", ")", "amplitudes_to_measure", "=", "list"...
Measure the coefficients of the pure state :param prep_program: pyQuil program to prepare the state :param reference_state: Integer of the computational basis state to use as a reference :param quantum_resource: An instance of a quantum abstract machine :param variance_bound: Default 1.0E-6. variance of the monte carlo estimator for the non-hermitian operator :return: an estimate of the wavefunction as a numpy.ndarray
[ "Measure", "the", "coefficients", "of", "the", "pure", "state" ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/measurements/amplitude_measurement.py#L113-L134
train
200,390
rigetti/grove
grove/utils/utility_programs.py
ControlledProgramBuilder.build
def build(self): """Builds this controlled gate. :return: The controlled gate, defined by this object. :rtype: Program """ self.defined_gates = set(STANDARD_GATE_NAMES) prog = self._recursive_builder(self.operation, self.gate_name, self.control_qubits, self.target_qubit) return prog
python
def build(self): """Builds this controlled gate. :return: The controlled gate, defined by this object. :rtype: Program """ self.defined_gates = set(STANDARD_GATE_NAMES) prog = self._recursive_builder(self.operation, self.gate_name, self.control_qubits, self.target_qubit) return prog
[ "def", "build", "(", "self", ")", ":", "self", ".", "defined_gates", "=", "set", "(", "STANDARD_GATE_NAMES", ")", "prog", "=", "self", ".", "_recursive_builder", "(", "self", ".", "operation", ",", "self", ".", "gate_name", ",", "self", ".", "control_qubit...
Builds this controlled gate. :return: The controlled gate, defined by this object. :rtype: Program
[ "Builds", "this", "controlled", "gate", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/utils/utility_programs.py#L109-L120
train
200,391
rigetti/grove
grove/utils/utility_programs.py
ControlledProgramBuilder._defgate
def _defgate(self, program, gate_name, gate_matrix): """Defines a gate named gate_name with matrix gate_matrix in program. In addition, updates self.defined_gates to track what has been defined. :param Program program: Pyquil Program to add the defgate and gate to. :param str gate_name: The name of the gate to add to program. :param numpy.ndarray gate_matrix: The array corresponding to the gate to define. :return: the modified Program. :retype: Program """ new_program = pq.Program() new_program += program if gate_name not in self.defined_gates: new_program.defgate(gate_name, gate_matrix) self.defined_gates.add(gate_name) return new_program
python
def _defgate(self, program, gate_name, gate_matrix): """Defines a gate named gate_name with matrix gate_matrix in program. In addition, updates self.defined_gates to track what has been defined. :param Program program: Pyquil Program to add the defgate and gate to. :param str gate_name: The name of the gate to add to program. :param numpy.ndarray gate_matrix: The array corresponding to the gate to define. :return: the modified Program. :retype: Program """ new_program = pq.Program() new_program += program if gate_name not in self.defined_gates: new_program.defgate(gate_name, gate_matrix) self.defined_gates.add(gate_name) return new_program
[ "def", "_defgate", "(", "self", ",", "program", ",", "gate_name", ",", "gate_matrix", ")", ":", "new_program", "=", "pq", ".", "Program", "(", ")", "new_program", "+=", "program", "if", "gate_name", "not", "in", "self", ".", "defined_gates", ":", "new_prog...
Defines a gate named gate_name with matrix gate_matrix in program. In addition, updates self.defined_gates to track what has been defined. :param Program program: Pyquil Program to add the defgate and gate to. :param str gate_name: The name of the gate to add to program. :param numpy.ndarray gate_matrix: The array corresponding to the gate to define. :return: the modified Program. :retype: Program
[ "Defines", "a", "gate", "named", "gate_name", "with", "matrix", "gate_matrix", "in", "program", ".", "In", "addition", "updates", "self", ".", "defined_gates", "to", "track", "what", "has", "been", "defined", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/utils/utility_programs.py#L122-L137
train
200,392
rigetti/grove
grove/pyvqe/vqe.py
parity_even_p
def parity_even_p(state, marked_qubits): """ Calculates the parity of elements at indexes in marked_qubits Parity is relative to the binary representation of the integer state. :param state: The wavefunction index that corresponds to this state. :param marked_qubits: The indexes to be considered in the parity sum. :returns: A boolean corresponding to the parity. """ assert isinstance(state, int), \ f"{state} is not an integer. Must call parity_even_p with an integer state." mask = 0 for q in marked_qubits: mask |= 1 << q return bin(mask & state).count("1") % 2 == 0
python
def parity_even_p(state, marked_qubits): """ Calculates the parity of elements at indexes in marked_qubits Parity is relative to the binary representation of the integer state. :param state: The wavefunction index that corresponds to this state. :param marked_qubits: The indexes to be considered in the parity sum. :returns: A boolean corresponding to the parity. """ assert isinstance(state, int), \ f"{state} is not an integer. Must call parity_even_p with an integer state." mask = 0 for q in marked_qubits: mask |= 1 << q return bin(mask & state).count("1") % 2 == 0
[ "def", "parity_even_p", "(", "state", ",", "marked_qubits", ")", ":", "assert", "isinstance", "(", "state", ",", "int", ")", ",", "f\"{state} is not an integer. Must call parity_even_p with an integer state.\"", "mask", "=", "0", "for", "q", "in", "marked_qubits", ":"...
Calculates the parity of elements at indexes in marked_qubits Parity is relative to the binary representation of the integer state. :param state: The wavefunction index that corresponds to this state. :param marked_qubits: The indexes to be considered in the parity sum. :returns: A boolean corresponding to the parity.
[ "Calculates", "the", "parity", "of", "elements", "at", "indexes", "in", "marked_qubits" ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/pyvqe/vqe.py#L277-L292
train
200,393
rigetti/grove
grove/pyvqe/vqe.py
VQE.vqe_run
def vqe_run(self, variational_state_evolve, hamiltonian, initial_params, gate_noise=None, measurement_noise=None, jacobian=None, qc=None, disp=None, samples=None, return_all=False): """ functional minimization loop. :param variational_state_evolve: function that takes a set of parameters and returns a pyQuil program. :param hamiltonian: (PauliSum) object representing the hamiltonian of which to take the expectation value. :param initial_params: (ndarray) vector of initial parameters for the optimization :param gate_noise: list of Px, Py, Pz probabilities of gate being applied to every gate after each get application :param measurement_noise: list of Px', Py', Pz' probabilities of a X, Y or Z being applied before a measurement. :param jacobian: (optional) method of generating jacobian for parameters (Default=None). :param qc: (optional) QuantumComputer object. :param disp: (optional, bool) display level. If True then each iteration expectation and parameters are printed at each optimization iteration. :param samples: (int) Number of samples for calculating the expectation value of the operators. If `None` then faster method ,dotting the wave function with the operator, is used. Default=None. :param return_all: (optional, bool) request to return all intermediate parameters determined during the optimization. :return: (vqe.OptResult()) object :func:`OptResult <vqe.OptResult>`. The following fields are initialized in OptResult: -x: set of w.f. ansatz parameters -fun: scalar value of the objective function -iteration_params: a list of all intermediate parameter vectors. Only returned if 'return_all=True' is set as a vqe_run() option. -expectation_vals: a list of all intermediate expectation values. Only returned if 'return_all=True' is set as a vqe_run() option. """ self._disp_fun = disp if disp is not None else lambda x: None iteration_params = [] expectation_vals = [] self._current_expectation = None if samples is None: print("""WARNING: Fast method for expectation will be used. Noise models will be ineffective""") if qc is None: qubits = hamiltonian.get_qubits() qc = QuantumComputer(name=f"{len(qubits)}q-noisy-qvm", qam=QVM(gate_noise=gate_noise, measurement_noise=measurement_noise)) else: self.qc = qc def objective_function(params): """ closure representing the functional :param params: (ndarray) vector of parameters for generating the the function of the functional. :return: (float) expectation value """ pyquil_prog = variational_state_evolve(params) mean_value = self.expectation(pyquil_prog, hamiltonian, samples, qc) self._current_expectation = mean_value # store for printing return mean_value def print_current_iter(iter_vars): self._disp_fun("\tParameters: {} ".format(iter_vars)) if jacobian is not None: grad = jacobian(iter_vars) self._disp_fun("\tGrad-L1-Norm: {}".format(np.max(np.abs(grad)))) self._disp_fun("\tGrad-L2-Norm: {} ".format(np.linalg.norm(grad))) self._disp_fun("\tE => {}".format(self._current_expectation)) if return_all: iteration_params.append(iter_vars) expectation_vals.append(self._current_expectation) # using self.minimizer arguments = funcsigs.signature(self.minimizer).parameters.keys() if disp is not None and 'callback' in arguments: self.minimizer_kwargs['callback'] = print_current_iter args = [objective_function, initial_params] args.extend(self.minimizer_args) if 'jac' in arguments: self.minimizer_kwargs['jac'] = jacobian result = self.minimizer(*args, **self.minimizer_kwargs) if hasattr(result, 'status'): if result.status != 0: self._disp_fun("Classical optimization exited with an error index: %i" % result.status) results = OptResults() if hasattr(result, 'x'): results.x = result.x results.fun = result.fun else: results.x = result if return_all: results.iteration_params = iteration_params results.expectation_vals = expectation_vals return results
python
def vqe_run(self, variational_state_evolve, hamiltonian, initial_params, gate_noise=None, measurement_noise=None, jacobian=None, qc=None, disp=None, samples=None, return_all=False): """ functional minimization loop. :param variational_state_evolve: function that takes a set of parameters and returns a pyQuil program. :param hamiltonian: (PauliSum) object representing the hamiltonian of which to take the expectation value. :param initial_params: (ndarray) vector of initial parameters for the optimization :param gate_noise: list of Px, Py, Pz probabilities of gate being applied to every gate after each get application :param measurement_noise: list of Px', Py', Pz' probabilities of a X, Y or Z being applied before a measurement. :param jacobian: (optional) method of generating jacobian for parameters (Default=None). :param qc: (optional) QuantumComputer object. :param disp: (optional, bool) display level. If True then each iteration expectation and parameters are printed at each optimization iteration. :param samples: (int) Number of samples for calculating the expectation value of the operators. If `None` then faster method ,dotting the wave function with the operator, is used. Default=None. :param return_all: (optional, bool) request to return all intermediate parameters determined during the optimization. :return: (vqe.OptResult()) object :func:`OptResult <vqe.OptResult>`. The following fields are initialized in OptResult: -x: set of w.f. ansatz parameters -fun: scalar value of the objective function -iteration_params: a list of all intermediate parameter vectors. Only returned if 'return_all=True' is set as a vqe_run() option. -expectation_vals: a list of all intermediate expectation values. Only returned if 'return_all=True' is set as a vqe_run() option. """ self._disp_fun = disp if disp is not None else lambda x: None iteration_params = [] expectation_vals = [] self._current_expectation = None if samples is None: print("""WARNING: Fast method for expectation will be used. Noise models will be ineffective""") if qc is None: qubits = hamiltonian.get_qubits() qc = QuantumComputer(name=f"{len(qubits)}q-noisy-qvm", qam=QVM(gate_noise=gate_noise, measurement_noise=measurement_noise)) else: self.qc = qc def objective_function(params): """ closure representing the functional :param params: (ndarray) vector of parameters for generating the the function of the functional. :return: (float) expectation value """ pyquil_prog = variational_state_evolve(params) mean_value = self.expectation(pyquil_prog, hamiltonian, samples, qc) self._current_expectation = mean_value # store for printing return mean_value def print_current_iter(iter_vars): self._disp_fun("\tParameters: {} ".format(iter_vars)) if jacobian is not None: grad = jacobian(iter_vars) self._disp_fun("\tGrad-L1-Norm: {}".format(np.max(np.abs(grad)))) self._disp_fun("\tGrad-L2-Norm: {} ".format(np.linalg.norm(grad))) self._disp_fun("\tE => {}".format(self._current_expectation)) if return_all: iteration_params.append(iter_vars) expectation_vals.append(self._current_expectation) # using self.minimizer arguments = funcsigs.signature(self.minimizer).parameters.keys() if disp is not None and 'callback' in arguments: self.minimizer_kwargs['callback'] = print_current_iter args = [objective_function, initial_params] args.extend(self.minimizer_args) if 'jac' in arguments: self.minimizer_kwargs['jac'] = jacobian result = self.minimizer(*args, **self.minimizer_kwargs) if hasattr(result, 'status'): if result.status != 0: self._disp_fun("Classical optimization exited with an error index: %i" % result.status) results = OptResults() if hasattr(result, 'x'): results.x = result.x results.fun = result.fun else: results.x = result if return_all: results.iteration_params = iteration_params results.expectation_vals = expectation_vals return results
[ "def", "vqe_run", "(", "self", ",", "variational_state_evolve", ",", "hamiltonian", ",", "initial_params", ",", "gate_noise", "=", "None", ",", "measurement_noise", "=", "None", ",", "jacobian", "=", "None", ",", "qc", "=", "None", ",", "disp", "=", "None", ...
functional minimization loop. :param variational_state_evolve: function that takes a set of parameters and returns a pyQuil program. :param hamiltonian: (PauliSum) object representing the hamiltonian of which to take the expectation value. :param initial_params: (ndarray) vector of initial parameters for the optimization :param gate_noise: list of Px, Py, Pz probabilities of gate being applied to every gate after each get application :param measurement_noise: list of Px', Py', Pz' probabilities of a X, Y or Z being applied before a measurement. :param jacobian: (optional) method of generating jacobian for parameters (Default=None). :param qc: (optional) QuantumComputer object. :param disp: (optional, bool) display level. If True then each iteration expectation and parameters are printed at each optimization iteration. :param samples: (int) Number of samples for calculating the expectation value of the operators. If `None` then faster method ,dotting the wave function with the operator, is used. Default=None. :param return_all: (optional, bool) request to return all intermediate parameters determined during the optimization. :return: (vqe.OptResult()) object :func:`OptResult <vqe.OptResult>`. The following fields are initialized in OptResult: -x: set of w.f. ansatz parameters -fun: scalar value of the objective function -iteration_params: a list of all intermediate parameter vectors. Only returned if 'return_all=True' is set as a vqe_run() option. -expectation_vals: a list of all intermediate expectation values. Only returned if 'return_all=True' is set as a vqe_run() option.
[ "functional", "minimization", "loop", "." ]
dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/pyvqe/vqe.py#L82-L192
train
200,394
tfoxy/graphene-django-optimizer
graphene_django_optimizer/query.py
_get_path_from_parent
def _get_path_from_parent(self, parent): """ Return a list of PathInfos containing the path from the parent model to the current model, or an empty list if parent is not a parent of the current model. """ if hasattr(self, 'get_path_from_parent'): return self.get_path_from_parent(parent) if self.model is parent: return [] model = self.concrete_model # Get a reversed base chain including both the current and parent # models. chain = model._meta.get_base_chain(parent) or [] chain.reverse() chain.append(model) # Construct a list of the PathInfos between models in chain. path = [] for i, ancestor in enumerate(chain[:-1]): child = chain[i + 1] link = child._meta.get_ancestor_link(ancestor) path.extend(link.get_reverse_path_info()) return path
python
def _get_path_from_parent(self, parent): """ Return a list of PathInfos containing the path from the parent model to the current model, or an empty list if parent is not a parent of the current model. """ if hasattr(self, 'get_path_from_parent'): return self.get_path_from_parent(parent) if self.model is parent: return [] model = self.concrete_model # Get a reversed base chain including both the current and parent # models. chain = model._meta.get_base_chain(parent) or [] chain.reverse() chain.append(model) # Construct a list of the PathInfos between models in chain. path = [] for i, ancestor in enumerate(chain[:-1]): child = chain[i + 1] link = child._meta.get_ancestor_link(ancestor) path.extend(link.get_reverse_path_info()) return path
[ "def", "_get_path_from_parent", "(", "self", ",", "parent", ")", ":", "if", "hasattr", "(", "self", ",", "'get_path_from_parent'", ")", ":", "return", "self", ".", "get_path_from_parent", "(", "parent", ")", "if", "self", ".", "model", "is", "parent", ":", ...
Return a list of PathInfos containing the path from the parent model to the current model, or an empty list if parent is not a parent of the current model.
[ "Return", "a", "list", "of", "PathInfos", "containing", "the", "path", "from", "the", "parent", "model", "to", "the", "current", "model", "or", "an", "empty", "list", "if", "parent", "is", "not", "a", "parent", "of", "the", "current", "model", "." ]
f9ecbf8952312c46c0b1820253ee824d594ae4a6
https://github.com/tfoxy/graphene-django-optimizer/blob/f9ecbf8952312c46c0b1820253ee824d594ae4a6/graphene_django_optimizer/query.py#L382-L404
train
200,395
tanghaibao/jcvi
jcvi/algorithms/lis.py
patience_sort
def patience_sort(xs): '''Patience sort an iterable, xs. This function generates a series of pairs (x, pile), where "pile" is the 0-based index of the pile "x" should be placed on top of. Elements of "xs" must be less-than comparable. ''' pile_tops = list() for x in xs: pile = bisect.bisect_left(pile_tops, x) if pile == len(pile_tops): pile_tops.append(x) else: pile_tops[pile] = x yield x, pile
python
def patience_sort(xs): '''Patience sort an iterable, xs. This function generates a series of pairs (x, pile), where "pile" is the 0-based index of the pile "x" should be placed on top of. Elements of "xs" must be less-than comparable. ''' pile_tops = list() for x in xs: pile = bisect.bisect_left(pile_tops, x) if pile == len(pile_tops): pile_tops.append(x) else: pile_tops[pile] = x yield x, pile
[ "def", "patience_sort", "(", "xs", ")", ":", "pile_tops", "=", "list", "(", ")", "for", "x", "in", "xs", ":", "pile", "=", "bisect", ".", "bisect_left", "(", "pile_tops", ",", "x", ")", "if", "pile", "==", "len", "(", "pile_tops", ")", ":", "pile_t...
Patience sort an iterable, xs. This function generates a series of pairs (x, pile), where "pile" is the 0-based index of the pile "x" should be placed on top of. Elements of "xs" must be less-than comparable.
[ "Patience", "sort", "an", "iterable", "xs", "." ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/algorithms/lis.py#L14-L28
train
200,396
tanghaibao/jcvi
jcvi/algorithms/lis.py
longest_monotonic_subseq_length
def longest_monotonic_subseq_length(xs): '''Return the length of the longest monotonic subsequence of xs, second return value is the difference between increasing and decreasing lengths. >>> longest_monotonic_subseq_length((4, 5, 1, 2, 3)) (3, 1) >>> longest_monotonic_subseq_length((1, 2, 3, 5, 4)) (4, 2) >>> longest_monotonic_subseq_length((1, 2, 1)) (2, 0) ''' li = longest_increasing_subseq_length(xs) ld = longest_decreasing_subseq_length(xs) return max(li, ld), li - ld
python
def longest_monotonic_subseq_length(xs): '''Return the length of the longest monotonic subsequence of xs, second return value is the difference between increasing and decreasing lengths. >>> longest_monotonic_subseq_length((4, 5, 1, 2, 3)) (3, 1) >>> longest_monotonic_subseq_length((1, 2, 3, 5, 4)) (4, 2) >>> longest_monotonic_subseq_length((1, 2, 1)) (2, 0) ''' li = longest_increasing_subseq_length(xs) ld = longest_decreasing_subseq_length(xs) return max(li, ld), li - ld
[ "def", "longest_monotonic_subseq_length", "(", "xs", ")", ":", "li", "=", "longest_increasing_subseq_length", "(", "xs", ")", "ld", "=", "longest_decreasing_subseq_length", "(", "xs", ")", "return", "max", "(", "li", ",", "ld", ")", ",", "li", "-", "ld" ]
Return the length of the longest monotonic subsequence of xs, second return value is the difference between increasing and decreasing lengths. >>> longest_monotonic_subseq_length((4, 5, 1, 2, 3)) (3, 1) >>> longest_monotonic_subseq_length((1, 2, 3, 5, 4)) (4, 2) >>> longest_monotonic_subseq_length((1, 2, 1)) (2, 0)
[ "Return", "the", "length", "of", "the", "longest", "monotonic", "subsequence", "of", "xs", "second", "return", "value", "is", "the", "difference", "between", "increasing", "and", "decreasing", "lengths", "." ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/algorithms/lis.py#L31-L44
train
200,397
tanghaibao/jcvi
jcvi/algorithms/lis.py
longest_increasing_subsequence
def longest_increasing_subsequence(xs): '''Return a longest increasing subsequence of xs. (Note that there may be more than one such subsequence.) >>> longest_increasing_subsequence(range(3)) [0, 1, 2] >>> longest_increasing_subsequence([3, 1, 2, 0]) [1, 2] ''' # Patience sort xs, stacking (x, prev_ix) pairs on the piles. # Prev_ix indexes the element at the top of the previous pile, # which has a lower x value than the current x value. piles = [[]] # Create a dummy pile 0 for x, p in patience_sort(xs): if p + 1 == len(piles): piles.append([]) # backlink to the top of the previous pile piles[p + 1].append((x, len(piles[p]) - 1)) # Backtrack to find a longest increasing subsequence npiles = len(piles) - 1 prev = 0 lis = list() for pile in range(npiles, 0, -1): x, prev = piles[pile][prev] lis.append(x) lis.reverse() return lis
python
def longest_increasing_subsequence(xs): '''Return a longest increasing subsequence of xs. (Note that there may be more than one such subsequence.) >>> longest_increasing_subsequence(range(3)) [0, 1, 2] >>> longest_increasing_subsequence([3, 1, 2, 0]) [1, 2] ''' # Patience sort xs, stacking (x, prev_ix) pairs on the piles. # Prev_ix indexes the element at the top of the previous pile, # which has a lower x value than the current x value. piles = [[]] # Create a dummy pile 0 for x, p in patience_sort(xs): if p + 1 == len(piles): piles.append([]) # backlink to the top of the previous pile piles[p + 1].append((x, len(piles[p]) - 1)) # Backtrack to find a longest increasing subsequence npiles = len(piles) - 1 prev = 0 lis = list() for pile in range(npiles, 0, -1): x, prev = piles[pile][prev] lis.append(x) lis.reverse() return lis
[ "def", "longest_increasing_subsequence", "(", "xs", ")", ":", "# Patience sort xs, stacking (x, prev_ix) pairs on the piles.", "# Prev_ix indexes the element at the top of the previous pile,", "# which has a lower x value than the current x value.", "piles", "=", "[", "[", "]", "]", "#...
Return a longest increasing subsequence of xs. (Note that there may be more than one such subsequence.) >>> longest_increasing_subsequence(range(3)) [0, 1, 2] >>> longest_increasing_subsequence([3, 1, 2, 0]) [1, 2]
[ "Return", "a", "longest", "increasing", "subsequence", "of", "xs", "." ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/algorithms/lis.py#L78-L104
train
200,398
tanghaibao/jcvi
jcvi/algorithms/lis.py
backtracking
def backtracking(a, L, bestsofar): """ Start with the heaviest weight and emit index """ w, j = max(L.items()) while j != -1: yield j w, j = bestsofar[j]
python
def backtracking(a, L, bestsofar): """ Start with the heaviest weight and emit index """ w, j = max(L.items()) while j != -1: yield j w, j = bestsofar[j]
[ "def", "backtracking", "(", "a", ",", "L", ",", "bestsofar", ")", ":", "w", ",", "j", "=", "max", "(", "L", ".", "items", "(", ")", ")", "while", "j", "!=", "-", "1", ":", "yield", "j", "w", ",", "j", "=", "bestsofar", "[", "j", "]" ]
Start with the heaviest weight and emit index
[ "Start", "with", "the", "heaviest", "weight", "and", "emit", "index" ]
d2e31a77b6ade7f41f3b321febc2b4744d1cdeca
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/algorithms/lis.py#L144-L151
train
200,399