id
int32
0
252k
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
51
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
248,600
jrief/django-angular
djng/views/crud.py
NgCRUDView.ng_delete
def ng_delete(self, request, *args, **kwargs): """ Delete object and return it's data in JSON encoding The response is build before the object is actually deleted so that we can still retrieve a serialization in the response even with a m2m relationship """ if 'pk' not in request.GET: raise NgMissingParameterError("Object id is required to delete.") obj = self.get_object() response = self.build_json_response(obj) obj.delete() return response
python
def ng_delete(self, request, *args, **kwargs): if 'pk' not in request.GET: raise NgMissingParameterError("Object id is required to delete.") obj = self.get_object() response = self.build_json_response(obj) obj.delete() return response
[ "def", "ng_delete", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'pk'", "not", "in", "request", ".", "GET", ":", "raise", "NgMissingParameterError", "(", "\"Object id is required to delete.\"", ")", "obj", "=", "self", ".", "get_object", "(", ")", "response", "=", "self", ".", "build_json_response", "(", "obj", ")", "obj", ".", "delete", "(", ")", "return", "response" ]
Delete object and return it's data in JSON encoding The response is build before the object is actually deleted so that we can still retrieve a serialization in the response even with a m2m relationship
[ "Delete", "object", "and", "return", "it", "s", "data", "in", "JSON", "encoding", "The", "response", "is", "build", "before", "the", "object", "is", "actually", "deleted", "so", "that", "we", "can", "still", "retrieve", "a", "serialization", "in", "the", "response", "even", "with", "a", "m2m", "relationship" ]
9f2f8247027173e3b3ad3b245ca299a9c9f31b40
https://github.com/jrief/django-angular/blob/9f2f8247027173e3b3ad3b245ca299a9c9f31b40/djng/views/crud.py#L170-L183
248,601
jrief/django-angular
djng/forms/angular_model.py
NgModelFormMixin._post_clean
def _post_clean(self): """ Rewrite the error dictionary, so that its keys correspond to the model fields. """ super(NgModelFormMixin, self)._post_clean() if self._errors and self.prefix: self._errors = ErrorDict((self.add_prefix(name), value) for name, value in self._errors.items())
python
def _post_clean(self): super(NgModelFormMixin, self)._post_clean() if self._errors and self.prefix: self._errors = ErrorDict((self.add_prefix(name), value) for name, value in self._errors.items())
[ "def", "_post_clean", "(", "self", ")", ":", "super", "(", "NgModelFormMixin", ",", "self", ")", ".", "_post_clean", "(", ")", "if", "self", ".", "_errors", "and", "self", ".", "prefix", ":", "self", ".", "_errors", "=", "ErrorDict", "(", "(", "self", ".", "add_prefix", "(", "name", ")", ",", "value", ")", "for", "name", ",", "value", "in", "self", ".", "_errors", ".", "items", "(", ")", ")" ]
Rewrite the error dictionary, so that its keys correspond to the model fields.
[ "Rewrite", "the", "error", "dictionary", "so", "that", "its", "keys", "correspond", "to", "the", "model", "fields", "." ]
9f2f8247027173e3b3ad3b245ca299a9c9f31b40
https://github.com/jrief/django-angular/blob/9f2f8247027173e3b3ad3b245ca299a9c9f31b40/djng/forms/angular_model.py#L42-L48
248,602
WoLpH/python-progressbar
progressbar/bar.py
ProgressBar.percentage
def percentage(self): '''Return current percentage, returns None if no max_value is given >>> progress = ProgressBar() >>> progress.max_value = 10 >>> progress.min_value = 0 >>> progress.value = 0 >>> progress.percentage 0.0 >>> >>> progress.value = 1 >>> progress.percentage 10.0 >>> progress.value = 10 >>> progress.percentage 100.0 >>> progress.min_value = -10 >>> progress.percentage 100.0 >>> progress.value = 0 >>> progress.percentage 50.0 >>> progress.value = 5 >>> progress.percentage 75.0 >>> progress.value = -5 >>> progress.percentage 25.0 >>> progress.max_value = None >>> progress.percentage ''' if self.max_value is None or self.max_value is base.UnknownLength: return None elif self.max_value: todo = self.value - self.min_value total = self.max_value - self.min_value percentage = todo / total else: percentage = 1 return percentage * 100
python
def percentage(self): '''Return current percentage, returns None if no max_value is given >>> progress = ProgressBar() >>> progress.max_value = 10 >>> progress.min_value = 0 >>> progress.value = 0 >>> progress.percentage 0.0 >>> >>> progress.value = 1 >>> progress.percentage 10.0 >>> progress.value = 10 >>> progress.percentage 100.0 >>> progress.min_value = -10 >>> progress.percentage 100.0 >>> progress.value = 0 >>> progress.percentage 50.0 >>> progress.value = 5 >>> progress.percentage 75.0 >>> progress.value = -5 >>> progress.percentage 25.0 >>> progress.max_value = None >>> progress.percentage ''' if self.max_value is None or self.max_value is base.UnknownLength: return None elif self.max_value: todo = self.value - self.min_value total = self.max_value - self.min_value percentage = todo / total else: percentage = 1 return percentage * 100
[ "def", "percentage", "(", "self", ")", ":", "if", "self", ".", "max_value", "is", "None", "or", "self", ".", "max_value", "is", "base", ".", "UnknownLength", ":", "return", "None", "elif", "self", ".", "max_value", ":", "todo", "=", "self", ".", "value", "-", "self", ".", "min_value", "total", "=", "self", ".", "max_value", "-", "self", ".", "min_value", "percentage", "=", "todo", "/", "total", "else", ":", "percentage", "=", "1", "return", "percentage", "*", "100" ]
Return current percentage, returns None if no max_value is given >>> progress = ProgressBar() >>> progress.max_value = 10 >>> progress.min_value = 0 >>> progress.value = 0 >>> progress.percentage 0.0 >>> >>> progress.value = 1 >>> progress.percentage 10.0 >>> progress.value = 10 >>> progress.percentage 100.0 >>> progress.min_value = -10 >>> progress.percentage 100.0 >>> progress.value = 0 >>> progress.percentage 50.0 >>> progress.value = 5 >>> progress.percentage 75.0 >>> progress.value = -5 >>> progress.percentage 25.0 >>> progress.max_value = None >>> progress.percentage
[ "Return", "current", "percentage", "returns", "None", "if", "no", "max_value", "is", "given" ]
963617a1bb9d81624ecf31f3457185992cd97bfa
https://github.com/WoLpH/python-progressbar/blob/963617a1bb9d81624ecf31f3457185992cd97bfa/progressbar/bar.py#L297-L337
248,603
WoLpH/python-progressbar
examples.py
example
def example(fn): '''Wrap the examples so they generate readable output''' @functools.wraps(fn) def wrapped(): try: sys.stdout.write('Running: %s\n' % fn.__name__) fn() sys.stdout.write('\n') except KeyboardInterrupt: sys.stdout.write('\nSkipping example.\n\n') # Sleep a bit to make killing the script easier time.sleep(0.2) examples.append(wrapped) return wrapped
python
def example(fn): '''Wrap the examples so they generate readable output''' @functools.wraps(fn) def wrapped(): try: sys.stdout.write('Running: %s\n' % fn.__name__) fn() sys.stdout.write('\n') except KeyboardInterrupt: sys.stdout.write('\nSkipping example.\n\n') # Sleep a bit to make killing the script easier time.sleep(0.2) examples.append(wrapped) return wrapped
[ "def", "example", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "wrapped", "(", ")", ":", "try", ":", "sys", ".", "stdout", ".", "write", "(", "'Running: %s\\n'", "%", "fn", ".", "__name__", ")", "fn", "(", ")", "sys", ".", "stdout", ".", "write", "(", "'\\n'", ")", "except", "KeyboardInterrupt", ":", "sys", ".", "stdout", ".", "write", "(", "'\\nSkipping example.\\n\\n'", ")", "# Sleep a bit to make killing the script easier", "time", ".", "sleep", "(", "0.2", ")", "examples", ".", "append", "(", "wrapped", ")", "return", "wrapped" ]
Wrap the examples so they generate readable output
[ "Wrap", "the", "examples", "so", "they", "generate", "readable", "output" ]
963617a1bb9d81624ecf31f3457185992cd97bfa
https://github.com/WoLpH/python-progressbar/blob/963617a1bb9d81624ecf31f3457185992cd97bfa/examples.py#L16-L31
248,604
rigetti/quantumflow
quantumflow/datasets/__init__.py
load_stdgraphs
def load_stdgraphs(size: int) -> List[nx.Graph]: """Load standard graph validation sets For each size (from 6 to 32 graph nodes) the dataset consists of 100 graphs drawn from the Erdős-Rényi ensemble with edge probability 50%. """ from pkg_resources import resource_stream if size < 6 or size > 32: raise ValueError('Size out of range.') filename = 'datasets/data/graph{}er100.g6'.format(size) fdata = resource_stream('quantumflow', filename) return nx.read_graph6(fdata)
python
def load_stdgraphs(size: int) -> List[nx.Graph]: from pkg_resources import resource_stream if size < 6 or size > 32: raise ValueError('Size out of range.') filename = 'datasets/data/graph{}er100.g6'.format(size) fdata = resource_stream('quantumflow', filename) return nx.read_graph6(fdata)
[ "def", "load_stdgraphs", "(", "size", ":", "int", ")", "->", "List", "[", "nx", ".", "Graph", "]", ":", "from", "pkg_resources", "import", "resource_stream", "if", "size", "<", "6", "or", "size", ">", "32", ":", "raise", "ValueError", "(", "'Size out of range.'", ")", "filename", "=", "'datasets/data/graph{}er100.g6'", ".", "format", "(", "size", ")", "fdata", "=", "resource_stream", "(", "'quantumflow'", ",", "filename", ")", "return", "nx", ".", "read_graph6", "(", "fdata", ")" ]
Load standard graph validation sets For each size (from 6 to 32 graph nodes) the dataset consists of 100 graphs drawn from the Erdős-Rényi ensemble with edge probability 50%.
[ "Load", "standard", "graph", "validation", "sets" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/datasets/__init__.py#L23-L37
248,605
rigetti/quantumflow
quantumflow/datasets/__init__.py
load_mnist
def load_mnist(size: int = None, border: int = _MNIST_BORDER, blank_corners: bool = False, nums: List[int] = None) \ -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: """Download and rescale the MNIST database of handwritten digits MNIST is a dataset of 60,000 28x28 grayscale images handwritten digits, along with a test set of 10,000 images. We use Keras to download and access the dataset. The first invocation of this method may take a while as the dataset has to be downloaded and cached. If size is None, then we return the original MNIST data. For rescaled MNIST, we chop off the border, downsample to the desired size with Lanczos resampling, and then (optionally) zero out the corner pixels. Returns (x_train, y_train, x_test, y_test) x_train ndarray of shape (60000, size, size) y_train ndarray of shape (60000,) x_test ndarray of shape (10000, size, size) y_test ndarray of shape (10000,) """ # DOCME: Fix up formatting above, # DOCME: Explain nums argument # JIT import since keras startup is slow from keras.datasets import mnist def _filter_mnist(x: np.ndarray, y: np.ndarray, nums: List[int] = None) \ -> Tuple[np.ndarray, np.ndarray]: xt = [] yt = [] items = len(y) for n in range(items): if nums is not None and y[n] in nums: xt.append(x[n]) yt.append(y[n]) xt = np.stack(xt) yt = np.stack(yt) return xt, yt def _rescale(imgarray: np.ndarray, size: int) -> np.ndarray: N = imgarray.shape[0] # Chop off border imgarray = imgarray[:, border:-border, border:-border] rescaled = np.zeros(shape=(N, size, size), dtype=np.float) for n in range(0, N): img = Image.fromarray(imgarray[n]) img = img.resize((size, size), Image.LANCZOS) rsc = np.asarray(img).reshape((size, size)) rsc = 256.*rsc/rsc.max() rescaled[n] = rsc return rescaled.astype(dtype=np.uint8) def _blank_corners(imgarray: np.ndarray) -> None: # Zero out corners sz = imgarray.shape[1] corner = (sz//2)-1 for x in range(0, corner): for y in range(0, corner-x): imgarray[:, x, y] = 0 imgarray[:, -(1+x), y] = 0 imgarray[:, -(1+x), -(1+y)] = 0 imgarray[:, x, -(1+y)] = 0 (x_train, y_train), (x_test, y_test) = mnist.load_data() if nums: x_train, y_train = _filter_mnist(x_train, y_train, nums) x_test, y_test = _filter_mnist(x_test, y_test, nums) if size: x_train = _rescale(x_train, size) x_test = _rescale(x_test, size) if blank_corners: _blank_corners(x_train) _blank_corners(x_test) return x_train, y_train, x_test, y_test
python
def load_mnist(size: int = None, border: int = _MNIST_BORDER, blank_corners: bool = False, nums: List[int] = None) \ -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: # DOCME: Fix up formatting above, # DOCME: Explain nums argument # JIT import since keras startup is slow from keras.datasets import mnist def _filter_mnist(x: np.ndarray, y: np.ndarray, nums: List[int] = None) \ -> Tuple[np.ndarray, np.ndarray]: xt = [] yt = [] items = len(y) for n in range(items): if nums is not None and y[n] in nums: xt.append(x[n]) yt.append(y[n]) xt = np.stack(xt) yt = np.stack(yt) return xt, yt def _rescale(imgarray: np.ndarray, size: int) -> np.ndarray: N = imgarray.shape[0] # Chop off border imgarray = imgarray[:, border:-border, border:-border] rescaled = np.zeros(shape=(N, size, size), dtype=np.float) for n in range(0, N): img = Image.fromarray(imgarray[n]) img = img.resize((size, size), Image.LANCZOS) rsc = np.asarray(img).reshape((size, size)) rsc = 256.*rsc/rsc.max() rescaled[n] = rsc return rescaled.astype(dtype=np.uint8) def _blank_corners(imgarray: np.ndarray) -> None: # Zero out corners sz = imgarray.shape[1] corner = (sz//2)-1 for x in range(0, corner): for y in range(0, corner-x): imgarray[:, x, y] = 0 imgarray[:, -(1+x), y] = 0 imgarray[:, -(1+x), -(1+y)] = 0 imgarray[:, x, -(1+y)] = 0 (x_train, y_train), (x_test, y_test) = mnist.load_data() if nums: x_train, y_train = _filter_mnist(x_train, y_train, nums) x_test, y_test = _filter_mnist(x_test, y_test, nums) if size: x_train = _rescale(x_train, size) x_test = _rescale(x_test, size) if blank_corners: _blank_corners(x_train) _blank_corners(x_test) return x_train, y_train, x_test, y_test
[ "def", "load_mnist", "(", "size", ":", "int", "=", "None", ",", "border", ":", "int", "=", "_MNIST_BORDER", ",", "blank_corners", ":", "bool", "=", "False", ",", "nums", ":", "List", "[", "int", "]", "=", "None", ")", "->", "Tuple", "[", "np", ".", "ndarray", ",", "np", ".", "ndarray", ",", "np", ".", "ndarray", ",", "np", ".", "ndarray", "]", ":", "# DOCME: Fix up formatting above,", "# DOCME: Explain nums argument", "# JIT import since keras startup is slow", "from", "keras", ".", "datasets", "import", "mnist", "def", "_filter_mnist", "(", "x", ":", "np", ".", "ndarray", ",", "y", ":", "np", ".", "ndarray", ",", "nums", ":", "List", "[", "int", "]", "=", "None", ")", "->", "Tuple", "[", "np", ".", "ndarray", ",", "np", ".", "ndarray", "]", ":", "xt", "=", "[", "]", "yt", "=", "[", "]", "items", "=", "len", "(", "y", ")", "for", "n", "in", "range", "(", "items", ")", ":", "if", "nums", "is", "not", "None", "and", "y", "[", "n", "]", "in", "nums", ":", "xt", ".", "append", "(", "x", "[", "n", "]", ")", "yt", ".", "append", "(", "y", "[", "n", "]", ")", "xt", "=", "np", ".", "stack", "(", "xt", ")", "yt", "=", "np", ".", "stack", "(", "yt", ")", "return", "xt", ",", "yt", "def", "_rescale", "(", "imgarray", ":", "np", ".", "ndarray", ",", "size", ":", "int", ")", "->", "np", ".", "ndarray", ":", "N", "=", "imgarray", ".", "shape", "[", "0", "]", "# Chop off border", "imgarray", "=", "imgarray", "[", ":", ",", "border", ":", "-", "border", ",", "border", ":", "-", "border", "]", "rescaled", "=", "np", ".", "zeros", "(", "shape", "=", "(", "N", ",", "size", ",", "size", ")", ",", "dtype", "=", "np", ".", "float", ")", "for", "n", "in", "range", "(", "0", ",", "N", ")", ":", "img", "=", "Image", ".", "fromarray", "(", "imgarray", "[", "n", "]", ")", "img", "=", "img", ".", "resize", "(", "(", "size", ",", "size", ")", ",", "Image", ".", "LANCZOS", ")", "rsc", "=", "np", ".", "asarray", "(", "img", ")", ".", "reshape", "(", "(", "size", ",", "size", ")", ")", "rsc", "=", "256.", "*", "rsc", "/", "rsc", ".", "max", "(", ")", "rescaled", "[", "n", "]", "=", "rsc", "return", "rescaled", ".", "astype", "(", "dtype", "=", "np", ".", "uint8", ")", "def", "_blank_corners", "(", "imgarray", ":", "np", ".", "ndarray", ")", "->", "None", ":", "# Zero out corners", "sz", "=", "imgarray", ".", "shape", "[", "1", "]", "corner", "=", "(", "sz", "//", "2", ")", "-", "1", "for", "x", "in", "range", "(", "0", ",", "corner", ")", ":", "for", "y", "in", "range", "(", "0", ",", "corner", "-", "x", ")", ":", "imgarray", "[", ":", ",", "x", ",", "y", "]", "=", "0", "imgarray", "[", ":", ",", "-", "(", "1", "+", "x", ")", ",", "y", "]", "=", "0", "imgarray", "[", ":", ",", "-", "(", "1", "+", "x", ")", ",", "-", "(", "1", "+", "y", ")", "]", "=", "0", "imgarray", "[", ":", ",", "x", ",", "-", "(", "1", "+", "y", ")", "]", "=", "0", "(", "x_train", ",", "y_train", ")", ",", "(", "x_test", ",", "y_test", ")", "=", "mnist", ".", "load_data", "(", ")", "if", "nums", ":", "x_train", ",", "y_train", "=", "_filter_mnist", "(", "x_train", ",", "y_train", ",", "nums", ")", "x_test", ",", "y_test", "=", "_filter_mnist", "(", "x_test", ",", "y_test", ",", "nums", ")", "if", "size", ":", "x_train", "=", "_rescale", "(", "x_train", ",", "size", ")", "x_test", "=", "_rescale", "(", "x_test", ",", "size", ")", "if", "blank_corners", ":", "_blank_corners", "(", "x_train", ")", "_blank_corners", "(", "x_test", ")", "return", "x_train", ",", "y_train", ",", "x_test", ",", "y_test" ]
Download and rescale the MNIST database of handwritten digits MNIST is a dataset of 60,000 28x28 grayscale images handwritten digits, along with a test set of 10,000 images. We use Keras to download and access the dataset. The first invocation of this method may take a while as the dataset has to be downloaded and cached. If size is None, then we return the original MNIST data. For rescaled MNIST, we chop off the border, downsample to the desired size with Lanczos resampling, and then (optionally) zero out the corner pixels. Returns (x_train, y_train, x_test, y_test) x_train ndarray of shape (60000, size, size) y_train ndarray of shape (60000,) x_test ndarray of shape (10000, size, size) y_test ndarray of shape (10000,)
[ "Download", "and", "rescale", "the", "MNIST", "database", "of", "handwritten", "digits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/datasets/__init__.py#L43-L127
248,606
rigetti/quantumflow
quantumflow/backend/tensorflow2bk.py
astensor
def astensor(array: TensorLike) -> BKTensor: """Covert numpy array to tensorflow tensor""" tensor = tf.convert_to_tensor(value=array, dtype=CTYPE) return tensor
python
def astensor(array: TensorLike) -> BKTensor: tensor = tf.convert_to_tensor(value=array, dtype=CTYPE) return tensor
[ "def", "astensor", "(", "array", ":", "TensorLike", ")", "->", "BKTensor", ":", "tensor", "=", "tf", ".", "convert_to_tensor", "(", "value", "=", "array", ",", "dtype", "=", "CTYPE", ")", "return", "tensor" ]
Covert numpy array to tensorflow tensor
[ "Covert", "numpy", "array", "to", "tensorflow", "tensor" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/tensorflow2bk.py#L74-L77
248,607
rigetti/quantumflow
quantumflow/backend/tensorflow2bk.py
inner
def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor: """Return the inner product between two states""" # Note: Relying on fact that vdot flattens arrays N = rank(tensor0) axes = list(range(N)) return tf.tensordot(tf.math.conj(tensor0), tensor1, axes=(axes, axes))
python
def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor: # Note: Relying on fact that vdot flattens arrays N = rank(tensor0) axes = list(range(N)) return tf.tensordot(tf.math.conj(tensor0), tensor1, axes=(axes, axes))
[ "def", "inner", "(", "tensor0", ":", "BKTensor", ",", "tensor1", ":", "BKTensor", ")", "->", "BKTensor", ":", "# Note: Relying on fact that vdot flattens arrays", "N", "=", "rank", "(", "tensor0", ")", "axes", "=", "list", "(", "range", "(", "N", ")", ")", "return", "tf", ".", "tensordot", "(", "tf", ".", "math", ".", "conj", "(", "tensor0", ")", ",", "tensor1", ",", "axes", "=", "(", "axes", ",", "axes", ")", ")" ]
Return the inner product between two states
[ "Return", "the", "inner", "product", "between", "two", "states" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/tensorflow2bk.py#L92-L97
248,608
rigetti/quantumflow
quantumflow/qaoa.py
graph_cuts
def graph_cuts(graph: nx.Graph) -> np.ndarray: """For the given graph, return the cut value for all binary assignments of the graph. """ N = len(graph) diag_hamiltonian = np.zeros(shape=([2]*N), dtype=np.double) for q0, q1 in graph.edges(): for index, _ in np.ndenumerate(diag_hamiltonian): if index[q0] != index[q1]: weight = graph[q0][q1].get('weight', 1) diag_hamiltonian[index] += weight return diag_hamiltonian
python
def graph_cuts(graph: nx.Graph) -> np.ndarray: N = len(graph) diag_hamiltonian = np.zeros(shape=([2]*N), dtype=np.double) for q0, q1 in graph.edges(): for index, _ in np.ndenumerate(diag_hamiltonian): if index[q0] != index[q1]: weight = graph[q0][q1].get('weight', 1) diag_hamiltonian[index] += weight return diag_hamiltonian
[ "def", "graph_cuts", "(", "graph", ":", "nx", ".", "Graph", ")", "->", "np", ".", "ndarray", ":", "N", "=", "len", "(", "graph", ")", "diag_hamiltonian", "=", "np", ".", "zeros", "(", "shape", "=", "(", "[", "2", "]", "*", "N", ")", ",", "dtype", "=", "np", ".", "double", ")", "for", "q0", ",", "q1", "in", "graph", ".", "edges", "(", ")", ":", "for", "index", ",", "_", "in", "np", ".", "ndenumerate", "(", "diag_hamiltonian", ")", ":", "if", "index", "[", "q0", "]", "!=", "index", "[", "q1", "]", ":", "weight", "=", "graph", "[", "q0", "]", "[", "q1", "]", ".", "get", "(", "'weight'", ",", "1", ")", "diag_hamiltonian", "[", "index", "]", "+=", "weight", "return", "diag_hamiltonian" ]
For the given graph, return the cut value for all binary assignments of the graph.
[ "For", "the", "given", "graph", "return", "the", "cut", "value", "for", "all", "binary", "assignments", "of", "the", "graph", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qaoa.py#L68-L81
248,609
rigetti/quantumflow
quantumflow/dagcircuit.py
DAGCircuit.depth
def depth(self, local: bool = True) -> int: """Return the circuit depth. Args: local: If True include local one-qubit gates in depth calculation. Else return the multi-qubit gate depth. """ G = self.graph if not local: def remove_local(dagc: DAGCircuit) \ -> Generator[Operation, None, None]: for elem in dagc: if dagc.graph.degree[elem] > 2: yield elem G = DAGCircuit(remove_local(self)).graph return nx.dag_longest_path_length(G) - 1
python
def depth(self, local: bool = True) -> int: G = self.graph if not local: def remove_local(dagc: DAGCircuit) \ -> Generator[Operation, None, None]: for elem in dagc: if dagc.graph.degree[elem] > 2: yield elem G = DAGCircuit(remove_local(self)).graph return nx.dag_longest_path_length(G) - 1
[ "def", "depth", "(", "self", ",", "local", ":", "bool", "=", "True", ")", "->", "int", ":", "G", "=", "self", ".", "graph", "if", "not", "local", ":", "def", "remove_local", "(", "dagc", ":", "DAGCircuit", ")", "->", "Generator", "[", "Operation", ",", "None", ",", "None", "]", ":", "for", "elem", "in", "dagc", ":", "if", "dagc", ".", "graph", ".", "degree", "[", "elem", "]", ">", "2", ":", "yield", "elem", "G", "=", "DAGCircuit", "(", "remove_local", "(", "self", ")", ")", ".", "graph", "return", "nx", ".", "dag_longest_path_length", "(", "G", ")", "-", "1" ]
Return the circuit depth. Args: local: If True include local one-qubit gates in depth calculation. Else return the multi-qubit gate depth.
[ "Return", "the", "circuit", "depth", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/dagcircuit.py#L97-L113
248,610
rigetti/quantumflow
quantumflow/dagcircuit.py
DAGCircuit.components
def components(self) -> List['DAGCircuit']: """Split DAGCircuit into independent components""" comps = nx.weakly_connected_component_subgraphs(self.graph) return [DAGCircuit(comp) for comp in comps]
python
def components(self) -> List['DAGCircuit']: comps = nx.weakly_connected_component_subgraphs(self.graph) return [DAGCircuit(comp) for comp in comps]
[ "def", "components", "(", "self", ")", "->", "List", "[", "'DAGCircuit'", "]", ":", "comps", "=", "nx", ".", "weakly_connected_component_subgraphs", "(", "self", ".", "graph", ")", "return", "[", "DAGCircuit", "(", "comp", ")", "for", "comp", "in", "comps", "]" ]
Split DAGCircuit into independent components
[ "Split", "DAGCircuit", "into", "independent", "components" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/dagcircuit.py#L124-L127
248,611
rigetti/quantumflow
quantumflow/states.py
zero_state
def zero_state(qubits: Union[int, Qubits]) -> State: """Return the all-zero state on N qubits""" N, qubits = qubits_count_tuple(qubits) ket = np.zeros(shape=[2] * N) ket[(0,) * N] = 1 return State(ket, qubits)
python
def zero_state(qubits: Union[int, Qubits]) -> State: N, qubits = qubits_count_tuple(qubits) ket = np.zeros(shape=[2] * N) ket[(0,) * N] = 1 return State(ket, qubits)
[ "def", "zero_state", "(", "qubits", ":", "Union", "[", "int", ",", "Qubits", "]", ")", "->", "State", ":", "N", ",", "qubits", "=", "qubits_count_tuple", "(", "qubits", ")", "ket", "=", "np", ".", "zeros", "(", "shape", "=", "[", "2", "]", "*", "N", ")", "ket", "[", "(", "0", ",", ")", "*", "N", "]", "=", "1", "return", "State", "(", "ket", ",", "qubits", ")" ]
Return the all-zero state on N qubits
[ "Return", "the", "all", "-", "zero", "state", "on", "N", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L186-L191
248,612
rigetti/quantumflow
quantumflow/states.py
w_state
def w_state(qubits: Union[int, Qubits]) -> State: """Return a W state on N qubits""" N, qubits = qubits_count_tuple(qubits) ket = np.zeros(shape=[2] * N) for n in range(N): idx = np.zeros(shape=N, dtype=int) idx[n] += 1 ket[tuple(idx)] = 1 / sqrt(N) return State(ket, qubits)
python
def w_state(qubits: Union[int, Qubits]) -> State: N, qubits = qubits_count_tuple(qubits) ket = np.zeros(shape=[2] * N) for n in range(N): idx = np.zeros(shape=N, dtype=int) idx[n] += 1 ket[tuple(idx)] = 1 / sqrt(N) return State(ket, qubits)
[ "def", "w_state", "(", "qubits", ":", "Union", "[", "int", ",", "Qubits", "]", ")", "->", "State", ":", "N", ",", "qubits", "=", "qubits_count_tuple", "(", "qubits", ")", "ket", "=", "np", ".", "zeros", "(", "shape", "=", "[", "2", "]", "*", "N", ")", "for", "n", "in", "range", "(", "N", ")", ":", "idx", "=", "np", ".", "zeros", "(", "shape", "=", "N", ",", "dtype", "=", "int", ")", "idx", "[", "n", "]", "+=", "1", "ket", "[", "tuple", "(", "idx", ")", "]", "=", "1", "/", "sqrt", "(", "N", ")", "return", "State", "(", "ket", ",", "qubits", ")" ]
Return a W state on N qubits
[ "Return", "a", "W", "state", "on", "N", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L194-L202
248,613
rigetti/quantumflow
quantumflow/states.py
ghz_state
def ghz_state(qubits: Union[int, Qubits]) -> State: """Return a GHZ state on N qubits""" N, qubits = qubits_count_tuple(qubits) ket = np.zeros(shape=[2] * N) ket[(0, ) * N] = 1 / sqrt(2) ket[(1, ) * N] = 1 / sqrt(2) return State(ket, qubits)
python
def ghz_state(qubits: Union[int, Qubits]) -> State: N, qubits = qubits_count_tuple(qubits) ket = np.zeros(shape=[2] * N) ket[(0, ) * N] = 1 / sqrt(2) ket[(1, ) * N] = 1 / sqrt(2) return State(ket, qubits)
[ "def", "ghz_state", "(", "qubits", ":", "Union", "[", "int", ",", "Qubits", "]", ")", "->", "State", ":", "N", ",", "qubits", "=", "qubits_count_tuple", "(", "qubits", ")", "ket", "=", "np", ".", "zeros", "(", "shape", "=", "[", "2", "]", "*", "N", ")", "ket", "[", "(", "0", ",", ")", "*", "N", "]", "=", "1", "/", "sqrt", "(", "2", ")", "ket", "[", "(", "1", ",", ")", "*", "N", "]", "=", "1", "/", "sqrt", "(", "2", ")", "return", "State", "(", "ket", ",", "qubits", ")" ]
Return a GHZ state on N qubits
[ "Return", "a", "GHZ", "state", "on", "N", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L205-L211
248,614
rigetti/quantumflow
quantumflow/states.py
random_state
def random_state(qubits: Union[int, Qubits]) -> State: """Return a random state from the space of N qubits""" N, qubits = qubits_count_tuple(qubits) ket = np.random.normal(size=([2] * N)) \ + 1j * np.random.normal(size=([2] * N)) return State(ket, qubits).normalize()
python
def random_state(qubits: Union[int, Qubits]) -> State: N, qubits = qubits_count_tuple(qubits) ket = np.random.normal(size=([2] * N)) \ + 1j * np.random.normal(size=([2] * N)) return State(ket, qubits).normalize()
[ "def", "random_state", "(", "qubits", ":", "Union", "[", "int", ",", "Qubits", "]", ")", "->", "State", ":", "N", ",", "qubits", "=", "qubits_count_tuple", "(", "qubits", ")", "ket", "=", "np", ".", "random", ".", "normal", "(", "size", "=", "(", "[", "2", "]", "*", "N", ")", ")", "+", "1j", "*", "np", ".", "random", ".", "normal", "(", "size", "=", "(", "[", "2", "]", "*", "N", ")", ")", "return", "State", "(", "ket", ",", "qubits", ")", ".", "normalize", "(", ")" ]
Return a random state from the space of N qubits
[ "Return", "a", "random", "state", "from", "the", "space", "of", "N", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L214-L219
248,615
rigetti/quantumflow
quantumflow/states.py
join_states
def join_states(*states: State) -> State: """Join two state vectors into a larger qubit state""" vectors = [ket.vec for ket in states] vec = reduce(outer_product, vectors) return State(vec.tensor, vec.qubits)
python
def join_states(*states: State) -> State: vectors = [ket.vec for ket in states] vec = reduce(outer_product, vectors) return State(vec.tensor, vec.qubits)
[ "def", "join_states", "(", "*", "states", ":", "State", ")", "->", "State", ":", "vectors", "=", "[", "ket", ".", "vec", "for", "ket", "in", "states", "]", "vec", "=", "reduce", "(", "outer_product", ",", "vectors", ")", "return", "State", "(", "vec", ".", "tensor", ",", "vec", ".", "qubits", ")" ]
Join two state vectors into a larger qubit state
[ "Join", "two", "state", "vectors", "into", "a", "larger", "qubit", "state" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L225-L229
248,616
rigetti/quantumflow
quantumflow/states.py
print_state
def print_state(state: State, file: TextIO = None) -> None: """Print a state vector""" state = state.vec.asarray() for index, amplitude in np.ndenumerate(state): ket = "".join([str(n) for n in index]) print(ket, ":", amplitude, file=file)
python
def print_state(state: State, file: TextIO = None) -> None: state = state.vec.asarray() for index, amplitude in np.ndenumerate(state): ket = "".join([str(n) for n in index]) print(ket, ":", amplitude, file=file)
[ "def", "print_state", "(", "state", ":", "State", ",", "file", ":", "TextIO", "=", "None", ")", "->", "None", ":", "state", "=", "state", ".", "vec", ".", "asarray", "(", ")", "for", "index", ",", "amplitude", "in", "np", ".", "ndenumerate", "(", "state", ")", ":", "ket", "=", "\"\"", ".", "join", "(", "[", "str", "(", "n", ")", "for", "n", "in", "index", "]", ")", "print", "(", "ket", ",", "\":\"", ",", "amplitude", ",", "file", "=", "file", ")" ]
Print a state vector
[ "Print", "a", "state", "vector" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L234-L239
248,617
rigetti/quantumflow
quantumflow/states.py
print_probabilities
def print_probabilities(state: State, ndigits: int = 4, file: TextIO = None) -> None: """ Pretty print state probabilities. Args: state: ndigits: Number of digits of accuracy file: Output stream (Defaults to stdout) """ prob = bk.evaluate(state.probabilities()) for index, prob in np.ndenumerate(prob): prob = round(prob, ndigits) if prob == 0.0: continue ket = "".join([str(n) for n in index]) print(ket, ":", prob, file=file)
python
def print_probabilities(state: State, ndigits: int = 4, file: TextIO = None) -> None: prob = bk.evaluate(state.probabilities()) for index, prob in np.ndenumerate(prob): prob = round(prob, ndigits) if prob == 0.0: continue ket = "".join([str(n) for n in index]) print(ket, ":", prob, file=file)
[ "def", "print_probabilities", "(", "state", ":", "State", ",", "ndigits", ":", "int", "=", "4", ",", "file", ":", "TextIO", "=", "None", ")", "->", "None", ":", "prob", "=", "bk", ".", "evaluate", "(", "state", ".", "probabilities", "(", ")", ")", "for", "index", ",", "prob", "in", "np", ".", "ndenumerate", "(", "prob", ")", ":", "prob", "=", "round", "(", "prob", ",", "ndigits", ")", "if", "prob", "==", "0.0", ":", "continue", "ket", "=", "\"\"", ".", "join", "(", "[", "str", "(", "n", ")", "for", "n", "in", "index", "]", ")", "print", "(", "ket", ",", "\":\"", ",", "prob", ",", "file", "=", "file", ")" ]
Pretty print state probabilities. Args: state: ndigits: Number of digits of accuracy file: Output stream (Defaults to stdout)
[ "Pretty", "print", "state", "probabilities", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L243-L259
248,618
rigetti/quantumflow
quantumflow/states.py
mixed_density
def mixed_density(qubits: Union[int, Qubits]) -> Density: """Returns the completely mixed density matrix""" N, qubits = qubits_count_tuple(qubits) matrix = np.eye(2**N) / 2**N return Density(matrix, qubits)
python
def mixed_density(qubits: Union[int, Qubits]) -> Density: N, qubits = qubits_count_tuple(qubits) matrix = np.eye(2**N) / 2**N return Density(matrix, qubits)
[ "def", "mixed_density", "(", "qubits", ":", "Union", "[", "int", ",", "Qubits", "]", ")", "->", "Density", ":", "N", ",", "qubits", "=", "qubits_count_tuple", "(", "qubits", ")", "matrix", "=", "np", ".", "eye", "(", "2", "**", "N", ")", "/", "2", "**", "N", "return", "Density", "(", "matrix", ",", "qubits", ")" ]
Returns the completely mixed density matrix
[ "Returns", "the", "completely", "mixed", "density", "matrix" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L322-L326
248,619
rigetti/quantumflow
quantumflow/states.py
join_densities
def join_densities(*densities: Density) -> Density: """Join two mixed states into a larger qubit state""" vectors = [rho.vec for rho in densities] vec = reduce(outer_product, vectors) memory = dict(ChainMap(*[rho.memory for rho in densities])) # TESTME return Density(vec.tensor, vec.qubits, memory)
python
def join_densities(*densities: Density) -> Density: vectors = [rho.vec for rho in densities] vec = reduce(outer_product, vectors) memory = dict(ChainMap(*[rho.memory for rho in densities])) # TESTME return Density(vec.tensor, vec.qubits, memory)
[ "def", "join_densities", "(", "*", "densities", ":", "Density", ")", "->", "Density", ":", "vectors", "=", "[", "rho", ".", "vec", "for", "rho", "in", "densities", "]", "vec", "=", "reduce", "(", "outer_product", ",", "vectors", ")", "memory", "=", "dict", "(", "ChainMap", "(", "*", "[", "rho", ".", "memory", "for", "rho", "in", "densities", "]", ")", ")", "# TESTME", "return", "Density", "(", "vec", ".", "tensor", ",", "vec", ".", "qubits", ",", "memory", ")" ]
Join two mixed states into a larger qubit state
[ "Join", "two", "mixed", "states", "into", "a", "larger", "qubit", "state" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L349-L355
248,620
rigetti/quantumflow
quantumflow/states.py
State.normalize
def normalize(self) -> 'State': """Normalize the state""" tensor = self.tensor / bk.ccast(bk.sqrt(self.norm())) return State(tensor, self.qubits, self._memory)
python
def normalize(self) -> 'State': tensor = self.tensor / bk.ccast(bk.sqrt(self.norm())) return State(tensor, self.qubits, self._memory)
[ "def", "normalize", "(", "self", ")", "->", "'State'", ":", "tensor", "=", "self", ".", "tensor", "/", "bk", ".", "ccast", "(", "bk", ".", "sqrt", "(", "self", ".", "norm", "(", ")", ")", ")", "return", "State", "(", "tensor", ",", "self", ".", "qubits", ",", "self", ".", "_memory", ")" ]
Normalize the state
[ "Normalize", "the", "state" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L108-L111
248,621
rigetti/quantumflow
quantumflow/states.py
State.sample
def sample(self, trials: int) -> np.ndarray: """Measure the state in the computational basis the the given number of trials, and return the counts of each output configuration. """ # TODO: Can we do this within backend? probs = np.real(bk.evaluate(self.probabilities())) res = np.random.multinomial(trials, probs.ravel()) res = res.reshape(probs.shape) return res
python
def sample(self, trials: int) -> np.ndarray: # TODO: Can we do this within backend? probs = np.real(bk.evaluate(self.probabilities())) res = np.random.multinomial(trials, probs.ravel()) res = res.reshape(probs.shape) return res
[ "def", "sample", "(", "self", ",", "trials", ":", "int", ")", "->", "np", ".", "ndarray", ":", "# TODO: Can we do this within backend?", "probs", "=", "np", ".", "real", "(", "bk", ".", "evaluate", "(", "self", ".", "probabilities", "(", ")", ")", ")", "res", "=", "np", ".", "random", ".", "multinomial", "(", "trials", ",", "probs", ".", "ravel", "(", ")", ")", "res", "=", "res", ".", "reshape", "(", "probs", ".", "shape", ")", "return", "res" ]
Measure the state in the computational basis the the given number of trials, and return the counts of each output configuration.
[ "Measure", "the", "state", "in", "the", "computational", "basis", "the", "the", "given", "number", "of", "trials", "and", "return", "the", "counts", "of", "each", "output", "configuration", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L121-L129
248,622
rigetti/quantumflow
quantumflow/states.py
State.expectation
def expectation(self, diag_hermitian: bk.TensorLike, trials: int = None) -> bk.BKTensor: """Return the expectation of a measurement. Since we can only measure our computer in the computational basis, we only require the diagonal of the Hermitian in that basis. If the number of trials is specified, we sample the given number of times. Else we return the exact expectation (as if we'd performed an infinite number of trials. ) """ if trials is None: probs = self.probabilities() else: probs = bk.real(bk.astensorproduct(self.sample(trials) / trials)) diag_hermitian = bk.astensorproduct(diag_hermitian) return bk.sum(bk.real(diag_hermitian) * probs)
python
def expectation(self, diag_hermitian: bk.TensorLike, trials: int = None) -> bk.BKTensor: if trials is None: probs = self.probabilities() else: probs = bk.real(bk.astensorproduct(self.sample(trials) / trials)) diag_hermitian = bk.astensorproduct(diag_hermitian) return bk.sum(bk.real(diag_hermitian) * probs)
[ "def", "expectation", "(", "self", ",", "diag_hermitian", ":", "bk", ".", "TensorLike", ",", "trials", ":", "int", "=", "None", ")", "->", "bk", ".", "BKTensor", ":", "if", "trials", "is", "None", ":", "probs", "=", "self", ".", "probabilities", "(", ")", "else", ":", "probs", "=", "bk", ".", "real", "(", "bk", ".", "astensorproduct", "(", "self", ".", "sample", "(", "trials", ")", "/", "trials", ")", ")", "diag_hermitian", "=", "bk", ".", "astensorproduct", "(", "diag_hermitian", ")", "return", "bk", ".", "sum", "(", "bk", ".", "real", "(", "diag_hermitian", ")", "*", "probs", ")" ]
Return the expectation of a measurement. Since we can only measure our computer in the computational basis, we only require the diagonal of the Hermitian in that basis. If the number of trials is specified, we sample the given number of times. Else we return the exact expectation (as if we'd performed an infinite number of trials. )
[ "Return", "the", "expectation", "of", "a", "measurement", ".", "Since", "we", "can", "only", "measure", "our", "computer", "in", "the", "computational", "basis", "we", "only", "require", "the", "diagonal", "of", "the", "Hermitian", "in", "that", "basis", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L131-L147
248,623
rigetti/quantumflow
quantumflow/states.py
State.measure
def measure(self) -> np.ndarray: """Measure the state in the computational basis. Returns: A [2]*bits array of qubit states, either 0 or 1 """ # TODO: Can we do this within backend? probs = np.real(bk.evaluate(self.probabilities())) indices = np.asarray(list(np.ndindex(*[2] * self.qubit_nb))) res = np.random.choice(probs.size, p=probs.ravel()) res = indices[res] return res
python
def measure(self) -> np.ndarray: # TODO: Can we do this within backend? probs = np.real(bk.evaluate(self.probabilities())) indices = np.asarray(list(np.ndindex(*[2] * self.qubit_nb))) res = np.random.choice(probs.size, p=probs.ravel()) res = indices[res] return res
[ "def", "measure", "(", "self", ")", "->", "np", ".", "ndarray", ":", "# TODO: Can we do this within backend?", "probs", "=", "np", ".", "real", "(", "bk", ".", "evaluate", "(", "self", ".", "probabilities", "(", ")", ")", ")", "indices", "=", "np", ".", "asarray", "(", "list", "(", "np", ".", "ndindex", "(", "*", "[", "2", "]", "*", "self", ".", "qubit_nb", ")", ")", ")", "res", "=", "np", ".", "random", ".", "choice", "(", "probs", ".", "size", ",", "p", "=", "probs", ".", "ravel", "(", ")", ")", "res", "=", "indices", "[", "res", "]", "return", "res" ]
Measure the state in the computational basis. Returns: A [2]*bits array of qubit states, either 0 or 1
[ "Measure", "the", "state", "in", "the", "computational", "basis", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L149-L160
248,624
rigetti/quantumflow
quantumflow/states.py
State.asdensity
def asdensity(self) -> 'Density': """Convert a pure state to a density matrix""" matrix = bk.outer(self.tensor, bk.conj(self.tensor)) return Density(matrix, self.qubits, self._memory)
python
def asdensity(self) -> 'Density': matrix = bk.outer(self.tensor, bk.conj(self.tensor)) return Density(matrix, self.qubits, self._memory)
[ "def", "asdensity", "(", "self", ")", "->", "'Density'", ":", "matrix", "=", "bk", ".", "outer", "(", "self", ".", "tensor", ",", "bk", ".", "conj", "(", "self", ".", "tensor", ")", ")", "return", "Density", "(", "matrix", ",", "self", ".", "qubits", ",", "self", ".", "_memory", ")" ]
Convert a pure state to a density matrix
[ "Convert", "a", "pure", "state", "to", "a", "density", "matrix" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L162-L165
248,625
rigetti/quantumflow
tools/benchmark.py
benchmark
def benchmark(N, gates): """Create and run a circuit with N qubits and given number of gates""" qubits = list(range(0, N)) ket = qf.zero_state(N) for n in range(0, N): ket = qf.H(n).run(ket) for _ in range(0, (gates-N)//3): qubit0, qubit1 = random.sample(qubits, 2) ket = qf.X(qubit0).run(ket) ket = qf.T(qubit1).run(ket) ket = qf.CNOT(qubit0, qubit1).run(ket) return ket.vec.tensor
python
def benchmark(N, gates): qubits = list(range(0, N)) ket = qf.zero_state(N) for n in range(0, N): ket = qf.H(n).run(ket) for _ in range(0, (gates-N)//3): qubit0, qubit1 = random.sample(qubits, 2) ket = qf.X(qubit0).run(ket) ket = qf.T(qubit1).run(ket) ket = qf.CNOT(qubit0, qubit1).run(ket) return ket.vec.tensor
[ "def", "benchmark", "(", "N", ",", "gates", ")", ":", "qubits", "=", "list", "(", "range", "(", "0", ",", "N", ")", ")", "ket", "=", "qf", ".", "zero_state", "(", "N", ")", "for", "n", "in", "range", "(", "0", ",", "N", ")", ":", "ket", "=", "qf", ".", "H", "(", "n", ")", ".", "run", "(", "ket", ")", "for", "_", "in", "range", "(", "0", ",", "(", "gates", "-", "N", ")", "//", "3", ")", ":", "qubit0", ",", "qubit1", "=", "random", ".", "sample", "(", "qubits", ",", "2", ")", "ket", "=", "qf", ".", "X", "(", "qubit0", ")", ".", "run", "(", "ket", ")", "ket", "=", "qf", ".", "T", "(", "qubit1", ")", ".", "run", "(", "ket", ")", "ket", "=", "qf", ".", "CNOT", "(", "qubit0", ",", "qubit1", ")", ".", "run", "(", "ket", ")", "return", "ket", ".", "vec", ".", "tensor" ]
Create and run a circuit with N qubits and given number of gates
[ "Create", "and", "run", "a", "circuit", "with", "N", "qubits", "and", "given", "number", "of", "gates" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/tools/benchmark.py#L31-L45
248,626
rigetti/quantumflow
examples/weyl.py
sandwich_decompositions
def sandwich_decompositions(coords0, coords1, samples=SAMPLES): """Create composite gates, decompose, and return a list of canonical coordinates""" decomps = [] for _ in range(samples): circ = qf.Circuit() circ += qf.CANONICAL(*coords0, 0, 1) circ += qf.random_gate([0]) circ += qf.random_gate([1]) circ += qf.CANONICAL(*coords1, 0, 1) gate = circ.asgate() coords = qf.canonical_coords(gate) decomps.append(coords) return decomps
python
def sandwich_decompositions(coords0, coords1, samples=SAMPLES): decomps = [] for _ in range(samples): circ = qf.Circuit() circ += qf.CANONICAL(*coords0, 0, 1) circ += qf.random_gate([0]) circ += qf.random_gate([1]) circ += qf.CANONICAL(*coords1, 0, 1) gate = circ.asgate() coords = qf.canonical_coords(gate) decomps.append(coords) return decomps
[ "def", "sandwich_decompositions", "(", "coords0", ",", "coords1", ",", "samples", "=", "SAMPLES", ")", ":", "decomps", "=", "[", "]", "for", "_", "in", "range", "(", "samples", ")", ":", "circ", "=", "qf", ".", "Circuit", "(", ")", "circ", "+=", "qf", ".", "CANONICAL", "(", "*", "coords0", ",", "0", ",", "1", ")", "circ", "+=", "qf", ".", "random_gate", "(", "[", "0", "]", ")", "circ", "+=", "qf", ".", "random_gate", "(", "[", "1", "]", ")", "circ", "+=", "qf", ".", "CANONICAL", "(", "*", "coords1", ",", "0", ",", "1", ")", "gate", "=", "circ", ".", "asgate", "(", ")", "coords", "=", "qf", ".", "canonical_coords", "(", "gate", ")", "decomps", ".", "append", "(", "coords", ")", "return", "decomps" ]
Create composite gates, decompose, and return a list of canonical coordinates
[ "Create", "composite", "gates", "decompose", "and", "return", "a", "list", "of", "canonical", "coordinates" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/examples/weyl.py#L82-L97
248,627
rigetti/quantumflow
quantumflow/paulialgebra.py
sX
def sX(qubit: Qubit, coefficient: complex = 1.0) -> Pauli: """Return the Pauli sigma_X operator acting on the given qubit""" return Pauli.sigma(qubit, 'X', coefficient)
python
def sX(qubit: Qubit, coefficient: complex = 1.0) -> Pauli: return Pauli.sigma(qubit, 'X', coefficient)
[ "def", "sX", "(", "qubit", ":", "Qubit", ",", "coefficient", ":", "complex", "=", "1.0", ")", "->", "Pauli", ":", "return", "Pauli", ".", "sigma", "(", "qubit", ",", "'X'", ",", "coefficient", ")" ]
Return the Pauli sigma_X operator acting on the given qubit
[ "Return", "the", "Pauli", "sigma_X", "operator", "acting", "on", "the", "given", "qubit" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/paulialgebra.py#L224-L226
248,628
rigetti/quantumflow
quantumflow/paulialgebra.py
sY
def sY(qubit: Qubit, coefficient: complex = 1.0) -> Pauli: """Return the Pauli sigma_Y operator acting on the given qubit""" return Pauli.sigma(qubit, 'Y', coefficient)
python
def sY(qubit: Qubit, coefficient: complex = 1.0) -> Pauli: return Pauli.sigma(qubit, 'Y', coefficient)
[ "def", "sY", "(", "qubit", ":", "Qubit", ",", "coefficient", ":", "complex", "=", "1.0", ")", "->", "Pauli", ":", "return", "Pauli", ".", "sigma", "(", "qubit", ",", "'Y'", ",", "coefficient", ")" ]
Return the Pauli sigma_Y operator acting on the given qubit
[ "Return", "the", "Pauli", "sigma_Y", "operator", "acting", "on", "the", "given", "qubit" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/paulialgebra.py#L229-L231
248,629
rigetti/quantumflow
quantumflow/paulialgebra.py
sZ
def sZ(qubit: Qubit, coefficient: complex = 1.0) -> Pauli: """Return the Pauli sigma_Z operator acting on the given qubit""" return Pauli.sigma(qubit, 'Z', coefficient)
python
def sZ(qubit: Qubit, coefficient: complex = 1.0) -> Pauli: return Pauli.sigma(qubit, 'Z', coefficient)
[ "def", "sZ", "(", "qubit", ":", "Qubit", ",", "coefficient", ":", "complex", "=", "1.0", ")", "->", "Pauli", ":", "return", "Pauli", ".", "sigma", "(", "qubit", ",", "'Z'", ",", "coefficient", ")" ]
Return the Pauli sigma_Z operator acting on the given qubit
[ "Return", "the", "Pauli", "sigma_Z", "operator", "acting", "on", "the", "given", "qubit" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/paulialgebra.py#L234-L236
248,630
rigetti/quantumflow
quantumflow/paulialgebra.py
pauli_sum
def pauli_sum(*elements: Pauli) -> Pauli: """Return the sum of elements of the Pauli algebra""" terms = [] key = itemgetter(0) for term, grp in groupby(heapq.merge(*elements, key=key), key=key): coeff = sum(g[1] for g in grp) if not isclose(coeff, 0.0): terms.append((term, coeff)) return Pauli(tuple(terms))
python
def pauli_sum(*elements: Pauli) -> Pauli: terms = [] key = itemgetter(0) for term, grp in groupby(heapq.merge(*elements, key=key), key=key): coeff = sum(g[1] for g in grp) if not isclose(coeff, 0.0): terms.append((term, coeff)) return Pauli(tuple(terms))
[ "def", "pauli_sum", "(", "*", "elements", ":", "Pauli", ")", "->", "Pauli", ":", "terms", "=", "[", "]", "key", "=", "itemgetter", "(", "0", ")", "for", "term", ",", "grp", "in", "groupby", "(", "heapq", ".", "merge", "(", "*", "elements", ",", "key", "=", "key", ")", ",", "key", "=", "key", ")", ":", "coeff", "=", "sum", "(", "g", "[", "1", "]", "for", "g", "in", "grp", ")", "if", "not", "isclose", "(", "coeff", ",", "0.0", ")", ":", "terms", ".", "append", "(", "(", "term", ",", "coeff", ")", ")", "return", "Pauli", "(", "tuple", "(", "terms", ")", ")" ]
Return the sum of elements of the Pauli algebra
[ "Return", "the", "sum", "of", "elements", "of", "the", "Pauli", "algebra" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/paulialgebra.py#L245-L255
248,631
rigetti/quantumflow
quantumflow/paulialgebra.py
pauli_product
def pauli_product(*elements: Pauli) -> Pauli: """Return the product of elements of the Pauli algebra""" result_terms = [] for terms in product(*elements): coeff = reduce(mul, [term[1] for term in terms]) ops = (term[0] for term in terms) out = [] key = itemgetter(0) for qubit, qops in groupby(heapq.merge(*ops, key=key), key=key): res = next(qops)[1] # Operator: X Y Z for op in qops: pair = res + op[1] res, rescoeff = PAULI_PROD[pair] coeff *= rescoeff if res != 'I': out.append((qubit, res)) p = Pauli(((tuple(out), coeff),)) result_terms.append(p) return pauli_sum(*result_terms)
python
def pauli_product(*elements: Pauli) -> Pauli: result_terms = [] for terms in product(*elements): coeff = reduce(mul, [term[1] for term in terms]) ops = (term[0] for term in terms) out = [] key = itemgetter(0) for qubit, qops in groupby(heapq.merge(*ops, key=key), key=key): res = next(qops)[1] # Operator: X Y Z for op in qops: pair = res + op[1] res, rescoeff = PAULI_PROD[pair] coeff *= rescoeff if res != 'I': out.append((qubit, res)) p = Pauli(((tuple(out), coeff),)) result_terms.append(p) return pauli_sum(*result_terms)
[ "def", "pauli_product", "(", "*", "elements", ":", "Pauli", ")", "->", "Pauli", ":", "result_terms", "=", "[", "]", "for", "terms", "in", "product", "(", "*", "elements", ")", ":", "coeff", "=", "reduce", "(", "mul", ",", "[", "term", "[", "1", "]", "for", "term", "in", "terms", "]", ")", "ops", "=", "(", "term", "[", "0", "]", "for", "term", "in", "terms", ")", "out", "=", "[", "]", "key", "=", "itemgetter", "(", "0", ")", "for", "qubit", ",", "qops", "in", "groupby", "(", "heapq", ".", "merge", "(", "*", "ops", ",", "key", "=", "key", ")", ",", "key", "=", "key", ")", ":", "res", "=", "next", "(", "qops", ")", "[", "1", "]", "# Operator: X Y Z", "for", "op", "in", "qops", ":", "pair", "=", "res", "+", "op", "[", "1", "]", "res", ",", "rescoeff", "=", "PAULI_PROD", "[", "pair", "]", "coeff", "*=", "rescoeff", "if", "res", "!=", "'I'", ":", "out", ".", "append", "(", "(", "qubit", ",", "res", ")", ")", "p", "=", "Pauli", "(", "(", "(", "tuple", "(", "out", ")", ",", "coeff", ")", ",", ")", ")", "result_terms", ".", "append", "(", "p", ")", "return", "pauli_sum", "(", "*", "result_terms", ")" ]
Return the product of elements of the Pauli algebra
[ "Return", "the", "product", "of", "elements", "of", "the", "Pauli", "algebra" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/paulialgebra.py#L258-L279
248,632
rigetti/quantumflow
quantumflow/paulialgebra.py
pauli_pow
def pauli_pow(pauli: Pauli, exponent: int) -> Pauli: """ Raise an element of the Pauli algebra to a non-negative integer power. """ if not isinstance(exponent, int) or exponent < 0: raise ValueError("The exponent must be a non-negative integer.") if exponent == 0: return Pauli.identity() if exponent == 1: return pauli # https://en.wikipedia.org/wiki/Exponentiation_by_squaring y = Pauli.identity() x = pauli n = exponent while n > 1: if n % 2 == 0: # Even x = x * x n = n // 2 else: # Odd y = x * y x = x * x n = (n - 1) // 2 return x * y
python
def pauli_pow(pauli: Pauli, exponent: int) -> Pauli: if not isinstance(exponent, int) or exponent < 0: raise ValueError("The exponent must be a non-negative integer.") if exponent == 0: return Pauli.identity() if exponent == 1: return pauli # https://en.wikipedia.org/wiki/Exponentiation_by_squaring y = Pauli.identity() x = pauli n = exponent while n > 1: if n % 2 == 0: # Even x = x * x n = n // 2 else: # Odd y = x * y x = x * x n = (n - 1) // 2 return x * y
[ "def", "pauli_pow", "(", "pauli", ":", "Pauli", ",", "exponent", ":", "int", ")", "->", "Pauli", ":", "if", "not", "isinstance", "(", "exponent", ",", "int", ")", "or", "exponent", "<", "0", ":", "raise", "ValueError", "(", "\"The exponent must be a non-negative integer.\"", ")", "if", "exponent", "==", "0", ":", "return", "Pauli", ".", "identity", "(", ")", "if", "exponent", "==", "1", ":", "return", "pauli", "# https://en.wikipedia.org/wiki/Exponentiation_by_squaring", "y", "=", "Pauli", ".", "identity", "(", ")", "x", "=", "pauli", "n", "=", "exponent", "while", "n", ">", "1", ":", "if", "n", "%", "2", "==", "0", ":", "# Even", "x", "=", "x", "*", "x", "n", "=", "n", "//", "2", "else", ":", "# Odd", "y", "=", "x", "*", "y", "x", "=", "x", "*", "x", "n", "=", "(", "n", "-", "1", ")", "//", "2", "return", "x", "*", "y" ]
Raise an element of the Pauli algebra to a non-negative integer power.
[ "Raise", "an", "element", "of", "the", "Pauli", "algebra", "to", "a", "non", "-", "negative", "integer", "power", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/paulialgebra.py#L282-L308
248,633
rigetti/quantumflow
quantumflow/paulialgebra.py
pauli_commuting_sets
def pauli_commuting_sets(element: Pauli) -> Tuple[Pauli, ...]: """Gather the terms of a Pauli polynomial into commuting sets. Uses the algorithm defined in (Raeisi, Wiebe, Sanders, arXiv:1108.4318, 2011) to find commuting sets. Except uses commutation check from arXiv:1405.5749v2 """ if len(element) < 2: return (element,) groups: List[Pauli] = [] # typing: List[Pauli] for term in element: pterm = Pauli((term,)) assigned = False for i, grp in enumerate(groups): if paulis_commute(grp, pterm): groups[i] = grp + pterm assigned = True break if not assigned: groups.append(pterm) return tuple(groups)
python
def pauli_commuting_sets(element: Pauli) -> Tuple[Pauli, ...]: if len(element) < 2: return (element,) groups: List[Pauli] = [] # typing: List[Pauli] for term in element: pterm = Pauli((term,)) assigned = False for i, grp in enumerate(groups): if paulis_commute(grp, pterm): groups[i] = grp + pterm assigned = True break if not assigned: groups.append(pterm) return tuple(groups)
[ "def", "pauli_commuting_sets", "(", "element", ":", "Pauli", ")", "->", "Tuple", "[", "Pauli", ",", "...", "]", ":", "if", "len", "(", "element", ")", "<", "2", ":", "return", "(", "element", ",", ")", "groups", ":", "List", "[", "Pauli", "]", "=", "[", "]", "# typing: List[Pauli]", "for", "term", "in", "element", ":", "pterm", "=", "Pauli", "(", "(", "term", ",", ")", ")", "assigned", "=", "False", "for", "i", ",", "grp", "in", "enumerate", "(", "groups", ")", ":", "if", "paulis_commute", "(", "grp", ",", "pterm", ")", ":", "groups", "[", "i", "]", "=", "grp", "+", "pterm", "assigned", "=", "True", "break", "if", "not", "assigned", ":", "groups", ".", "append", "(", "pterm", ")", "return", "tuple", "(", "groups", ")" ]
Gather the terms of a Pauli polynomial into commuting sets. Uses the algorithm defined in (Raeisi, Wiebe, Sanders, arXiv:1108.4318, 2011) to find commuting sets. Except uses commutation check from arXiv:1405.5749v2
[ "Gather", "the", "terms", "of", "a", "Pauli", "polynomial", "into", "commuting", "sets", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/paulialgebra.py#L348-L372
248,634
rigetti/quantumflow
quantumflow/backend/numpybk.py
astensor
def astensor(array: TensorLike) -> BKTensor: """Converts a numpy array to the backend's tensor object """ array = np.asarray(array, dtype=CTYPE) return array
python
def astensor(array: TensorLike) -> BKTensor: array = np.asarray(array, dtype=CTYPE) return array
[ "def", "astensor", "(", "array", ":", "TensorLike", ")", "->", "BKTensor", ":", "array", "=", "np", ".", "asarray", "(", "array", ",", "dtype", "=", "CTYPE", ")", "return", "array" ]
Converts a numpy array to the backend's tensor object
[ "Converts", "a", "numpy", "array", "to", "the", "backend", "s", "tensor", "object" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/numpybk.py#L98-L102
248,635
rigetti/quantumflow
quantumflow/backend/numpybk.py
productdiag
def productdiag(tensor: BKTensor) -> BKTensor: """Returns the matrix diagonal of the product tensor""" # DOCME: Explain N = rank(tensor) tensor = reshape(tensor, [2**(N//2), 2**(N//2)]) tensor = np.diag(tensor) tensor = reshape(tensor, [2]*(N//2)) return tensor
python
def productdiag(tensor: BKTensor) -> BKTensor: # DOCME: Explain N = rank(tensor) tensor = reshape(tensor, [2**(N//2), 2**(N//2)]) tensor = np.diag(tensor) tensor = reshape(tensor, [2]*(N//2)) return tensor
[ "def", "productdiag", "(", "tensor", ":", "BKTensor", ")", "->", "BKTensor", ":", "# DOCME: Explain", "N", "=", "rank", "(", "tensor", ")", "tensor", "=", "reshape", "(", "tensor", ",", "[", "2", "**", "(", "N", "//", "2", ")", ",", "2", "**", "(", "N", "//", "2", ")", "]", ")", "tensor", "=", "np", ".", "diag", "(", "tensor", ")", "tensor", "=", "reshape", "(", "tensor", ",", "[", "2", "]", "*", "(", "N", "//", "2", ")", ")", "return", "tensor" ]
Returns the matrix diagonal of the product tensor
[ "Returns", "the", "matrix", "diagonal", "of", "the", "product", "tensor" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/numpybk.py#L150-L156
248,636
rigetti/quantumflow
quantumflow/backend/numpybk.py
tensormul
def tensormul(tensor0: BKTensor, tensor1: BKTensor, indices: typing.List[int]) -> BKTensor: r""" Generalization of matrix multiplication to product tensors. A state vector in product tensor representation has N dimension, one for each contravariant index, e.g. for 3-qubit states :math:`B^{b_0,b_1,b_2}`. An operator has K dimensions, K/2 for contravariant indices (e.g. ket components) and K/2 for covariant (bra) indices, e.g. :math:`A^{a_0,a_1}_{a_2,a_3}` for a 2-qubit gate. The given indices of A are contracted against B, replacing the given positions. E.g. ``tensormul(A, B, [0,2])`` is equivalent to .. math:: C^{a_0,b_1,a_1} =\sum_{i_0,i_1} A^{a_0,a_1}_{i_0,i_1} B^{i_0,b_1,i_1} Args: tensor0: A tensor product representation of a gate tensor1: A tensor product representation of a gate or state indices: List of indices of tensor1 on which to act. Returns: Resultant state or gate tensor """ # Note: This method is the critical computational core of QuantumFlow # We currently have two implementations, one that uses einsum, the other # using matrix multiplication # # numpy: # einsum is much faster particularly for small numbers of qubits # tensorflow: # Little different is performance, but einsum would restrict the # maximum number of qubits to 26 (Because tensorflow only allows 26 # einsum subscripts at present] # torch: # einsum is slower than matmul N = rank(tensor1) K = rank(tensor0) // 2 assert K == len(indices) out = list(EINSUM_SUBSCRIPTS[0:N]) left_in = list(EINSUM_SUBSCRIPTS[N:N+K]) left_out = [out[idx] for idx in indices] right = list(EINSUM_SUBSCRIPTS[0:N]) for idx, s in zip(indices, left_in): right[idx] = s subscripts = ''.join(left_out + left_in + [','] + right + ['->'] + out) # print('>>>', K, N, subscripts) tensor = einsum(subscripts, tensor0, tensor1) return tensor
python
def tensormul(tensor0: BKTensor, tensor1: BKTensor, indices: typing.List[int]) -> BKTensor: r""" Generalization of matrix multiplication to product tensors. A state vector in product tensor representation has N dimension, one for each contravariant index, e.g. for 3-qubit states :math:`B^{b_0,b_1,b_2}`. An operator has K dimensions, K/2 for contravariant indices (e.g. ket components) and K/2 for covariant (bra) indices, e.g. :math:`A^{a_0,a_1}_{a_2,a_3}` for a 2-qubit gate. The given indices of A are contracted against B, replacing the given positions. E.g. ``tensormul(A, B, [0,2])`` is equivalent to .. math:: C^{a_0,b_1,a_1} =\sum_{i_0,i_1} A^{a_0,a_1}_{i_0,i_1} B^{i_0,b_1,i_1} Args: tensor0: A tensor product representation of a gate tensor1: A tensor product representation of a gate or state indices: List of indices of tensor1 on which to act. Returns: Resultant state or gate tensor """ # Note: This method is the critical computational core of QuantumFlow # We currently have two implementations, one that uses einsum, the other # using matrix multiplication # # numpy: # einsum is much faster particularly for small numbers of qubits # tensorflow: # Little different is performance, but einsum would restrict the # maximum number of qubits to 26 (Because tensorflow only allows 26 # einsum subscripts at present] # torch: # einsum is slower than matmul N = rank(tensor1) K = rank(tensor0) // 2 assert K == len(indices) out = list(EINSUM_SUBSCRIPTS[0:N]) left_in = list(EINSUM_SUBSCRIPTS[N:N+K]) left_out = [out[idx] for idx in indices] right = list(EINSUM_SUBSCRIPTS[0:N]) for idx, s in zip(indices, left_in): right[idx] = s subscripts = ''.join(left_out + left_in + [','] + right + ['->'] + out) # print('>>>', K, N, subscripts) tensor = einsum(subscripts, tensor0, tensor1) return tensor
[ "def", "tensormul", "(", "tensor0", ":", "BKTensor", ",", "tensor1", ":", "BKTensor", ",", "indices", ":", "typing", ".", "List", "[", "int", "]", ")", "->", "BKTensor", ":", "# Note: This method is the critical computational core of QuantumFlow", "# We currently have two implementations, one that uses einsum, the other", "# using matrix multiplication", "#", "# numpy:", "# einsum is much faster particularly for small numbers of qubits", "# tensorflow:", "# Little different is performance, but einsum would restrict the", "# maximum number of qubits to 26 (Because tensorflow only allows 26", "# einsum subscripts at present]", "# torch:", "# einsum is slower than matmul", "N", "=", "rank", "(", "tensor1", ")", "K", "=", "rank", "(", "tensor0", ")", "//", "2", "assert", "K", "==", "len", "(", "indices", ")", "out", "=", "list", "(", "EINSUM_SUBSCRIPTS", "[", "0", ":", "N", "]", ")", "left_in", "=", "list", "(", "EINSUM_SUBSCRIPTS", "[", "N", ":", "N", "+", "K", "]", ")", "left_out", "=", "[", "out", "[", "idx", "]", "for", "idx", "in", "indices", "]", "right", "=", "list", "(", "EINSUM_SUBSCRIPTS", "[", "0", ":", "N", "]", ")", "for", "idx", ",", "s", "in", "zip", "(", "indices", ",", "left_in", ")", ":", "right", "[", "idx", "]", "=", "s", "subscripts", "=", "''", ".", "join", "(", "left_out", "+", "left_in", "+", "[", "','", "]", "+", "right", "+", "[", "'->'", "]", "+", "out", ")", "# print('>>>', K, N, subscripts)", "tensor", "=", "einsum", "(", "subscripts", ",", "tensor0", ",", "tensor1", ")", "return", "tensor" ]
r""" Generalization of matrix multiplication to product tensors. A state vector in product tensor representation has N dimension, one for each contravariant index, e.g. for 3-qubit states :math:`B^{b_0,b_1,b_2}`. An operator has K dimensions, K/2 for contravariant indices (e.g. ket components) and K/2 for covariant (bra) indices, e.g. :math:`A^{a_0,a_1}_{a_2,a_3}` for a 2-qubit gate. The given indices of A are contracted against B, replacing the given positions. E.g. ``tensormul(A, B, [0,2])`` is equivalent to .. math:: C^{a_0,b_1,a_1} =\sum_{i_0,i_1} A^{a_0,a_1}_{i_0,i_1} B^{i_0,b_1,i_1} Args: tensor0: A tensor product representation of a gate tensor1: A tensor product representation of a gate or state indices: List of indices of tensor1 on which to act. Returns: Resultant state or gate tensor
[ "r", "Generalization", "of", "matrix", "multiplication", "to", "product", "tensors", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/numpybk.py#L159-L214
248,637
rigetti/quantumflow
quantumflow/utils.py
invert_map
def invert_map(mapping: dict, one_to_one: bool = True) -> dict: """Invert a dictionary. If not one_to_one then the inverted map will contain lists of former keys as values. """ if one_to_one: inv_map = {value: key for key, value in mapping.items()} else: inv_map = {} for key, value in mapping.items(): inv_map.setdefault(value, set()).add(key) return inv_map
python
def invert_map(mapping: dict, one_to_one: bool = True) -> dict: if one_to_one: inv_map = {value: key for key, value in mapping.items()} else: inv_map = {} for key, value in mapping.items(): inv_map.setdefault(value, set()).add(key) return inv_map
[ "def", "invert_map", "(", "mapping", ":", "dict", ",", "one_to_one", ":", "bool", "=", "True", ")", "->", "dict", ":", "if", "one_to_one", ":", "inv_map", "=", "{", "value", ":", "key", "for", "key", ",", "value", "in", "mapping", ".", "items", "(", ")", "}", "else", ":", "inv_map", "=", "{", "}", "for", "key", ",", "value", "in", "mapping", ".", "items", "(", ")", ":", "inv_map", ".", "setdefault", "(", "value", ",", "set", "(", ")", ")", ".", "add", "(", "key", ")", "return", "inv_map" ]
Invert a dictionary. If not one_to_one then the inverted map will contain lists of former keys as values.
[ "Invert", "a", "dictionary", ".", "If", "not", "one_to_one", "then", "the", "inverted", "map", "will", "contain", "lists", "of", "former", "keys", "as", "values", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/utils.py#L38-L49
248,638
rigetti/quantumflow
quantumflow/utils.py
bitlist_to_int
def bitlist_to_int(bitlist: Sequence[int]) -> int: """Converts a sequence of bits to an integer. >>> from quantumflow.utils import bitlist_to_int >>> bitlist_to_int([1, 0, 0]) 4 """ return int(''.join([str(d) for d in bitlist]), 2)
python
def bitlist_to_int(bitlist: Sequence[int]) -> int: return int(''.join([str(d) for d in bitlist]), 2)
[ "def", "bitlist_to_int", "(", "bitlist", ":", "Sequence", "[", "int", "]", ")", "->", "int", ":", "return", "int", "(", "''", ".", "join", "(", "[", "str", "(", "d", ")", "for", "d", "in", "bitlist", "]", ")", ",", "2", ")" ]
Converts a sequence of bits to an integer. >>> from quantumflow.utils import bitlist_to_int >>> bitlist_to_int([1, 0, 0]) 4
[ "Converts", "a", "sequence", "of", "bits", "to", "an", "integer", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/utils.py#L52-L59
248,639
rigetti/quantumflow
quantumflow/utils.py
int_to_bitlist
def int_to_bitlist(x: int, pad: int = None) -> Sequence[int]: """Converts an integer to a binary sequence of bits. Pad prepends with sufficient zeros to ensures that the returned list contains at least this number of bits. >>> from quantumflow.utils import int_to_bitlist >>> int_to_bitlist(4, 4)) [0, 1, 0, 0] """ if pad is None: form = '{:0b}' else: form = '{:0' + str(pad) + 'b}' return [int(b) for b in form.format(x)]
python
def int_to_bitlist(x: int, pad: int = None) -> Sequence[int]: if pad is None: form = '{:0b}' else: form = '{:0' + str(pad) + 'b}' return [int(b) for b in form.format(x)]
[ "def", "int_to_bitlist", "(", "x", ":", "int", ",", "pad", ":", "int", "=", "None", ")", "->", "Sequence", "[", "int", "]", ":", "if", "pad", "is", "None", ":", "form", "=", "'{:0b}'", "else", ":", "form", "=", "'{:0'", "+", "str", "(", "pad", ")", "+", "'b}'", "return", "[", "int", "(", "b", ")", "for", "b", "in", "form", ".", "format", "(", "x", ")", "]" ]
Converts an integer to a binary sequence of bits. Pad prepends with sufficient zeros to ensures that the returned list contains at least this number of bits. >>> from quantumflow.utils import int_to_bitlist >>> int_to_bitlist(4, 4)) [0, 1, 0, 0]
[ "Converts", "an", "integer", "to", "a", "binary", "sequence", "of", "bits", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/utils.py#L62-L77
248,640
rigetti/quantumflow
quantumflow/utils.py
spanning_tree_count
def spanning_tree_count(graph: nx.Graph) -> int: """Return the number of unique spanning trees of a graph, using Kirchhoff's matrix tree theorem. """ laplacian = nx.laplacian_matrix(graph).toarray() comatrix = laplacian[:-1, :-1] det = np.linalg.det(comatrix) count = int(round(det)) return count
python
def spanning_tree_count(graph: nx.Graph) -> int: laplacian = nx.laplacian_matrix(graph).toarray() comatrix = laplacian[:-1, :-1] det = np.linalg.det(comatrix) count = int(round(det)) return count
[ "def", "spanning_tree_count", "(", "graph", ":", "nx", ".", "Graph", ")", "->", "int", ":", "laplacian", "=", "nx", ".", "laplacian_matrix", "(", "graph", ")", ".", "toarray", "(", ")", "comatrix", "=", "laplacian", "[", ":", "-", "1", ",", ":", "-", "1", "]", "det", "=", "np", ".", "linalg", ".", "det", "(", "comatrix", ")", "count", "=", "int", "(", "round", "(", "det", ")", ")", "return", "count" ]
Return the number of unique spanning trees of a graph, using Kirchhoff's matrix tree theorem.
[ "Return", "the", "number", "of", "unique", "spanning", "trees", "of", "a", "graph", "using", "Kirchhoff", "s", "matrix", "tree", "theorem", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/utils.py#L108-L116
248,641
rigetti/quantumflow
quantumflow/utils.py
rationalize
def rationalize(flt: float, denominators: Set[int] = None) -> Fraction: """Convert a floating point number to a Fraction with a small denominator. Args: flt: A floating point number denominators: Collection of standard denominators. Default is 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192 Raises: ValueError: If cannot rationalize float """ if denominators is None: denominators = _DENOMINATORS frac = Fraction.from_float(flt).limit_denominator() if frac.denominator not in denominators: raise ValueError('Cannot rationalize') return frac
python
def rationalize(flt: float, denominators: Set[int] = None) -> Fraction: if denominators is None: denominators = _DENOMINATORS frac = Fraction.from_float(flt).limit_denominator() if frac.denominator not in denominators: raise ValueError('Cannot rationalize') return frac
[ "def", "rationalize", "(", "flt", ":", "float", ",", "denominators", ":", "Set", "[", "int", "]", "=", "None", ")", "->", "Fraction", ":", "if", "denominators", "is", "None", ":", "denominators", "=", "_DENOMINATORS", "frac", "=", "Fraction", ".", "from_float", "(", "flt", ")", ".", "limit_denominator", "(", ")", "if", "frac", ".", "denominator", "not", "in", "denominators", ":", "raise", "ValueError", "(", "'Cannot rationalize'", ")", "return", "frac" ]
Convert a floating point number to a Fraction with a small denominator. Args: flt: A floating point number denominators: Collection of standard denominators. Default is 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192 Raises: ValueError: If cannot rationalize float
[ "Convert", "a", "floating", "point", "number", "to", "a", "Fraction", "with", "a", "small", "denominator", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/utils.py#L171-L189
248,642
rigetti/quantumflow
quantumflow/utils.py
symbolize
def symbolize(flt: float) -> sympy.Symbol: """Attempt to convert a real number into a simpler symbolic representation. Returns: A sympy Symbol. (Convert to string with str(sym) or to latex with sympy.latex(sym) Raises: ValueError: If cannot simplify float """ try: ratio = rationalize(flt) res = sympy.simplify(ratio) except ValueError: ratio = rationalize(flt/np.pi) res = sympy.simplify(ratio) * sympy.pi return res
python
def symbolize(flt: float) -> sympy.Symbol: try: ratio = rationalize(flt) res = sympy.simplify(ratio) except ValueError: ratio = rationalize(flt/np.pi) res = sympy.simplify(ratio) * sympy.pi return res
[ "def", "symbolize", "(", "flt", ":", "float", ")", "->", "sympy", ".", "Symbol", ":", "try", ":", "ratio", "=", "rationalize", "(", "flt", ")", "res", "=", "sympy", ".", "simplify", "(", "ratio", ")", "except", "ValueError", ":", "ratio", "=", "rationalize", "(", "flt", "/", "np", ".", "pi", ")", "res", "=", "sympy", ".", "simplify", "(", "ratio", ")", "*", "sympy", ".", "pi", "return", "res" ]
Attempt to convert a real number into a simpler symbolic representation. Returns: A sympy Symbol. (Convert to string with str(sym) or to latex with sympy.latex(sym) Raises: ValueError: If cannot simplify float
[ "Attempt", "to", "convert", "a", "real", "number", "into", "a", "simpler", "symbolic", "representation", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/utils.py#L192-L208
248,643
rigetti/quantumflow
quantumflow/forest/__init__.py
pyquil_to_image
def pyquil_to_image(program: pyquil.Program) -> PIL.Image: # pragma: no cover """Returns an image of a pyquil circuit. See circuit_to_latex() for more details. """ circ = pyquil_to_circuit(program) latex = circuit_to_latex(circ) img = render_latex(latex) return img
python
def pyquil_to_image(program: pyquil.Program) -> PIL.Image: # pragma: no cover circ = pyquil_to_circuit(program) latex = circuit_to_latex(circ) img = render_latex(latex) return img
[ "def", "pyquil_to_image", "(", "program", ":", "pyquil", ".", "Program", ")", "->", "PIL", ".", "Image", ":", "# pragma: no cover", "circ", "=", "pyquil_to_circuit", "(", "program", ")", "latex", "=", "circuit_to_latex", "(", "circ", ")", "img", "=", "render_latex", "(", "latex", ")", "return", "img" ]
Returns an image of a pyquil circuit. See circuit_to_latex() for more details.
[ "Returns", "an", "image", "of", "a", "pyquil", "circuit", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L160-L168
248,644
rigetti/quantumflow
quantumflow/forest/__init__.py
circuit_to_pyquil
def circuit_to_pyquil(circuit: Circuit) -> pyquil.Program: """Convert a QuantumFlow circuit to a pyQuil program""" prog = pyquil.Program() for elem in circuit.elements: if isinstance(elem, Gate) and elem.name in QUIL_GATES: params = list(elem.params.values()) if elem.params else [] prog.gate(elem.name, params, elem.qubits) elif isinstance(elem, Measure): prog.measure(elem.qubit, elem.cbit) else: # FIXME: more informative error message raise ValueError('Cannot convert operation to pyquil') return prog
python
def circuit_to_pyquil(circuit: Circuit) -> pyquil.Program: prog = pyquil.Program() for elem in circuit.elements: if isinstance(elem, Gate) and elem.name in QUIL_GATES: params = list(elem.params.values()) if elem.params else [] prog.gate(elem.name, params, elem.qubits) elif isinstance(elem, Measure): prog.measure(elem.qubit, elem.cbit) else: # FIXME: more informative error message raise ValueError('Cannot convert operation to pyquil') return prog
[ "def", "circuit_to_pyquil", "(", "circuit", ":", "Circuit", ")", "->", "pyquil", ".", "Program", ":", "prog", "=", "pyquil", ".", "Program", "(", ")", "for", "elem", "in", "circuit", ".", "elements", ":", "if", "isinstance", "(", "elem", ",", "Gate", ")", "and", "elem", ".", "name", "in", "QUIL_GATES", ":", "params", "=", "list", "(", "elem", ".", "params", ".", "values", "(", ")", ")", "if", "elem", ".", "params", "else", "[", "]", "prog", ".", "gate", "(", "elem", ".", "name", ",", "params", ",", "elem", ".", "qubits", ")", "elif", "isinstance", "(", "elem", ",", "Measure", ")", ":", "prog", ".", "measure", "(", "elem", ".", "qubit", ",", "elem", ".", "cbit", ")", "else", ":", "# FIXME: more informative error message", "raise", "ValueError", "(", "'Cannot convert operation to pyquil'", ")", "return", "prog" ]
Convert a QuantumFlow circuit to a pyQuil program
[ "Convert", "a", "QuantumFlow", "circuit", "to", "a", "pyQuil", "program" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L171-L185
248,645
rigetti/quantumflow
quantumflow/forest/__init__.py
pyquil_to_circuit
def pyquil_to_circuit(program: pyquil.Program) -> Circuit: """Convert a protoquil pyQuil program to a QuantumFlow Circuit""" circ = Circuit() for inst in program.instructions: # print(type(inst)) if isinstance(inst, pyquil.Declare): # Ignore continue if isinstance(inst, pyquil.Halt): # Ignore continue if isinstance(inst, pyquil.Pragma): # TODO Barrier? continue elif isinstance(inst, pyquil.Measurement): circ += Measure(inst.qubit.index) # elif isinstance(inst, pyquil.ResetQubit): # TODO # continue elif isinstance(inst, pyquil.Gate): defgate = STDGATES[inst.name] gate = defgate(*inst.params) qubits = [q.index for q in inst.qubits] gate = gate.relabel(qubits) circ += gate else: raise ValueError('PyQuil program is not protoquil') return circ
python
def pyquil_to_circuit(program: pyquil.Program) -> Circuit: circ = Circuit() for inst in program.instructions: # print(type(inst)) if isinstance(inst, pyquil.Declare): # Ignore continue if isinstance(inst, pyquil.Halt): # Ignore continue if isinstance(inst, pyquil.Pragma): # TODO Barrier? continue elif isinstance(inst, pyquil.Measurement): circ += Measure(inst.qubit.index) # elif isinstance(inst, pyquil.ResetQubit): # TODO # continue elif isinstance(inst, pyquil.Gate): defgate = STDGATES[inst.name] gate = defgate(*inst.params) qubits = [q.index for q in inst.qubits] gate = gate.relabel(qubits) circ += gate else: raise ValueError('PyQuil program is not protoquil') return circ
[ "def", "pyquil_to_circuit", "(", "program", ":", "pyquil", ".", "Program", ")", "->", "Circuit", ":", "circ", "=", "Circuit", "(", ")", "for", "inst", "in", "program", ".", "instructions", ":", "# print(type(inst))", "if", "isinstance", "(", "inst", ",", "pyquil", ".", "Declare", ")", ":", "# Ignore", "continue", "if", "isinstance", "(", "inst", ",", "pyquil", ".", "Halt", ")", ":", "# Ignore", "continue", "if", "isinstance", "(", "inst", ",", "pyquil", ".", "Pragma", ")", ":", "# TODO Barrier?", "continue", "elif", "isinstance", "(", "inst", ",", "pyquil", ".", "Measurement", ")", ":", "circ", "+=", "Measure", "(", "inst", ".", "qubit", ".", "index", ")", "# elif isinstance(inst, pyquil.ResetQubit): # TODO", "# continue", "elif", "isinstance", "(", "inst", ",", "pyquil", ".", "Gate", ")", ":", "defgate", "=", "STDGATES", "[", "inst", ".", "name", "]", "gate", "=", "defgate", "(", "*", "inst", ".", "params", ")", "qubits", "=", "[", "q", ".", "index", "for", "q", "in", "inst", ".", "qubits", "]", "gate", "=", "gate", ".", "relabel", "(", "qubits", ")", "circ", "+=", "gate", "else", ":", "raise", "ValueError", "(", "'PyQuil program is not protoquil'", ")", "return", "circ" ]
Convert a protoquil pyQuil program to a QuantumFlow Circuit
[ "Convert", "a", "protoquil", "pyQuil", "program", "to", "a", "QuantumFlow", "Circuit" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L188-L213
248,646
rigetti/quantumflow
quantumflow/forest/__init__.py
quil_to_program
def quil_to_program(quil: str) -> Program: """Parse a quil program and return a Program object""" pyquil_instructions = pyquil.parser.parse(quil) return pyquil_to_program(pyquil_instructions)
python
def quil_to_program(quil: str) -> Program: pyquil_instructions = pyquil.parser.parse(quil) return pyquil_to_program(pyquil_instructions)
[ "def", "quil_to_program", "(", "quil", ":", "str", ")", "->", "Program", ":", "pyquil_instructions", "=", "pyquil", ".", "parser", ".", "parse", "(", "quil", ")", "return", "pyquil_to_program", "(", "pyquil_instructions", ")" ]
Parse a quil program and return a Program object
[ "Parse", "a", "quil", "program", "and", "return", "a", "Program", "object" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L216-L219
248,647
rigetti/quantumflow
quantumflow/forest/__init__.py
state_to_wavefunction
def state_to_wavefunction(state: State) -> pyquil.Wavefunction: """Convert a QuantumFlow state to a pyQuil Wavefunction""" # TODO: qubits? amplitudes = state.vec.asarray() # pyQuil labels states backwards. amplitudes = amplitudes.transpose() amplitudes = amplitudes.reshape([amplitudes.size]) return pyquil.Wavefunction(amplitudes)
python
def state_to_wavefunction(state: State) -> pyquil.Wavefunction: # TODO: qubits? amplitudes = state.vec.asarray() # pyQuil labels states backwards. amplitudes = amplitudes.transpose() amplitudes = amplitudes.reshape([amplitudes.size]) return pyquil.Wavefunction(amplitudes)
[ "def", "state_to_wavefunction", "(", "state", ":", "State", ")", "->", "pyquil", ".", "Wavefunction", ":", "# TODO: qubits?", "amplitudes", "=", "state", ".", "vec", ".", "asarray", "(", ")", "# pyQuil labels states backwards.", "amplitudes", "=", "amplitudes", ".", "transpose", "(", ")", "amplitudes", "=", "amplitudes", ".", "reshape", "(", "[", "amplitudes", ".", "size", "]", ")", "return", "pyquil", ".", "Wavefunction", "(", "amplitudes", ")" ]
Convert a QuantumFlow state to a pyQuil Wavefunction
[ "Convert", "a", "QuantumFlow", "state", "to", "a", "pyQuil", "Wavefunction" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L350-L358
248,648
rigetti/quantumflow
quantumflow/forest/__init__.py
QuantumFlowQVM.load
def load(self, binary: pyquil.Program) -> 'QuantumFlowQVM': """ Load a pyQuil program, and initialize QVM into a fresh state. Args: binary: A pyQuil program """ assert self.status in ['connected', 'done'] prog = quil_to_program(str(binary)) self._prog = prog self.program = binary self.status = 'loaded' return self
python
def load(self, binary: pyquil.Program) -> 'QuantumFlowQVM': assert self.status in ['connected', 'done'] prog = quil_to_program(str(binary)) self._prog = prog self.program = binary self.status = 'loaded' return self
[ "def", "load", "(", "self", ",", "binary", ":", "pyquil", ".", "Program", ")", "->", "'QuantumFlowQVM'", ":", "assert", "self", ".", "status", "in", "[", "'connected'", ",", "'done'", "]", "prog", "=", "quil_to_program", "(", "str", "(", "binary", ")", ")", "self", ".", "_prog", "=", "prog", "self", ".", "program", "=", "binary", "self", ".", "status", "=", "'loaded'", "return", "self" ]
Load a pyQuil program, and initialize QVM into a fresh state. Args: binary: A pyQuil program
[ "Load", "a", "pyQuil", "program", "and", "initialize", "QVM", "into", "a", "fresh", "state", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L379-L394
248,649
rigetti/quantumflow
quantumflow/forest/__init__.py
QuantumFlowQVM.run
def run(self) -> 'QuantumFlowQVM': """Run a previously loaded program""" assert self.status in ['loaded'] self.status = 'running' self._ket = self._prog.run() # Should set state to 'done' after run complete. # Makes no sense to keep status at running. But pyQuil's # QuantumComputer calls wait() after run, which expects state to be # 'running', and whose only effect to is to set state to 'done' return self
python
def run(self) -> 'QuantumFlowQVM': assert self.status in ['loaded'] self.status = 'running' self._ket = self._prog.run() # Should set state to 'done' after run complete. # Makes no sense to keep status at running. But pyQuil's # QuantumComputer calls wait() after run, which expects state to be # 'running', and whose only effect to is to set state to 'done' return self
[ "def", "run", "(", "self", ")", "->", "'QuantumFlowQVM'", ":", "assert", "self", ".", "status", "in", "[", "'loaded'", "]", "self", ".", "status", "=", "'running'", "self", ".", "_ket", "=", "self", ".", "_prog", ".", "run", "(", ")", "# Should set state to 'done' after run complete.", "# Makes no sense to keep status at running. But pyQuil's", "# QuantumComputer calls wait() after run, which expects state to be", "# 'running', and whose only effect to is to set state to 'done'", "return", "self" ]
Run a previously loaded program
[ "Run", "a", "previously", "loaded", "program" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L401-L410
248,650
rigetti/quantumflow
quantumflow/forest/__init__.py
QuantumFlowQVM.wavefunction
def wavefunction(self) -> pyquil.Wavefunction: """ Return the wavefunction of a completed program. """ assert self.status == 'done' assert self._ket is not None wavefn = state_to_wavefunction(self._ket) return wavefn
python
def wavefunction(self) -> pyquil.Wavefunction: assert self.status == 'done' assert self._ket is not None wavefn = state_to_wavefunction(self._ket) return wavefn
[ "def", "wavefunction", "(", "self", ")", "->", "pyquil", ".", "Wavefunction", ":", "assert", "self", ".", "status", "==", "'done'", "assert", "self", ".", "_ket", "is", "not", "None", "wavefn", "=", "state_to_wavefunction", "(", "self", ".", "_ket", ")", "return", "wavefn" ]
Return the wavefunction of a completed program.
[ "Return", "the", "wavefunction", "of", "a", "completed", "program", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L437-L444
248,651
rigetti/quantumflow
quantumflow/backend/torchbk.py
evaluate
def evaluate(tensor: BKTensor) -> TensorLike: """Return the value of a tensor""" if isinstance(tensor, _DTYPE): if torch.numel(tensor) == 1: return tensor.item() if tensor.numel() == 2: return tensor[0].cpu().numpy() + 1.0j * tensor[1].cpu().numpy() return tensor[0].cpu().numpy() + 1.0j * tensor[1].cpu().numpy() return tensor
python
def evaluate(tensor: BKTensor) -> TensorLike: if isinstance(tensor, _DTYPE): if torch.numel(tensor) == 1: return tensor.item() if tensor.numel() == 2: return tensor[0].cpu().numpy() + 1.0j * tensor[1].cpu().numpy() return tensor[0].cpu().numpy() + 1.0j * tensor[1].cpu().numpy() return tensor
[ "def", "evaluate", "(", "tensor", ":", "BKTensor", ")", "->", "TensorLike", ":", "if", "isinstance", "(", "tensor", ",", "_DTYPE", ")", ":", "if", "torch", ".", "numel", "(", "tensor", ")", "==", "1", ":", "return", "tensor", ".", "item", "(", ")", "if", "tensor", ".", "numel", "(", ")", "==", "2", ":", "return", "tensor", "[", "0", "]", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "+", "1.0j", "*", "tensor", "[", "1", "]", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "return", "tensor", "[", "0", "]", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "+", "1.0j", "*", "tensor", "[", "1", "]", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "return", "tensor" ]
Return the value of a tensor
[ "Return", "the", "value", "of", "a", "tensor" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/torchbk.py#L91-L100
248,652
rigetti/quantumflow
quantumflow/backend/torchbk.py
rank
def rank(tensor: BKTensor) -> int: """Return the number of dimensions of a tensor""" if isinstance(tensor, np.ndarray): return len(tensor.shape) return len(tensor[0].size())
python
def rank(tensor: BKTensor) -> int: if isinstance(tensor, np.ndarray): return len(tensor.shape) return len(tensor[0].size())
[ "def", "rank", "(", "tensor", ":", "BKTensor", ")", "->", "int", ":", "if", "isinstance", "(", "tensor", ",", "np", ".", "ndarray", ")", ":", "return", "len", "(", "tensor", ".", "shape", ")", "return", "len", "(", "tensor", "[", "0", "]", ".", "size", "(", ")", ")" ]
Return the number of dimensions of a tensor
[ "Return", "the", "number", "of", "dimensions", "of", "a", "tensor" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/torchbk.py#L136-L141
248,653
rigetti/quantumflow
quantumflow/measures.py
state_fidelity
def state_fidelity(state0: State, state1: State) -> bk.BKTensor: """Return the quantum fidelity between pure states.""" assert state0.qubits == state1.qubits # FIXME tensor = bk.absolute(bk.inner(state0.tensor, state1.tensor))**bk.fcast(2) return tensor
python
def state_fidelity(state0: State, state1: State) -> bk.BKTensor: assert state0.qubits == state1.qubits # FIXME tensor = bk.absolute(bk.inner(state0.tensor, state1.tensor))**bk.fcast(2) return tensor
[ "def", "state_fidelity", "(", "state0", ":", "State", ",", "state1", ":", "State", ")", "->", "bk", ".", "BKTensor", ":", "assert", "state0", ".", "qubits", "==", "state1", ".", "qubits", "# FIXME", "tensor", "=", "bk", ".", "absolute", "(", "bk", ".", "inner", "(", "state0", ".", "tensor", ",", "state1", ".", "tensor", ")", ")", "**", "bk", ".", "fcast", "(", "2", ")", "return", "tensor" ]
Return the quantum fidelity between pure states.
[ "Return", "the", "quantum", "fidelity", "between", "pure", "states", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L32-L36
248,654
rigetti/quantumflow
quantumflow/measures.py
state_angle
def state_angle(ket0: State, ket1: State) -> bk.BKTensor: """The Fubini-Study angle between states. Equal to the Burrs angle for pure states. """ return fubini_study_angle(ket0.vec, ket1.vec)
python
def state_angle(ket0: State, ket1: State) -> bk.BKTensor: return fubini_study_angle(ket0.vec, ket1.vec)
[ "def", "state_angle", "(", "ket0", ":", "State", ",", "ket1", ":", "State", ")", "->", "bk", ".", "BKTensor", ":", "return", "fubini_study_angle", "(", "ket0", ".", "vec", ",", "ket1", ".", "vec", ")" ]
The Fubini-Study angle between states. Equal to the Burrs angle for pure states.
[ "The", "Fubini", "-", "Study", "angle", "between", "states", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L39-L44
248,655
rigetti/quantumflow
quantumflow/measures.py
states_close
def states_close(state0: State, state1: State, tolerance: float = TOLERANCE) -> bool: """Returns True if states are almost identical. Closeness is measured with the metric Fubini-Study angle. """ return vectors_close(state0.vec, state1.vec, tolerance)
python
def states_close(state0: State, state1: State, tolerance: float = TOLERANCE) -> bool: return vectors_close(state0.vec, state1.vec, tolerance)
[ "def", "states_close", "(", "state0", ":", "State", ",", "state1", ":", "State", ",", "tolerance", ":", "float", "=", "TOLERANCE", ")", "->", "bool", ":", "return", "vectors_close", "(", "state0", ".", "vec", ",", "state1", ".", "vec", ",", "tolerance", ")" ]
Returns True if states are almost identical. Closeness is measured with the metric Fubini-Study angle.
[ "Returns", "True", "if", "states", "are", "almost", "identical", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L47-L53
248,656
rigetti/quantumflow
quantumflow/measures.py
purity
def purity(rho: Density) -> bk.BKTensor: """ Calculate the purity of a mixed quantum state. Purity, defined as tr(rho^2), has an upper bound of 1 for a pure state, and a lower bound of 1/D (where D is the Hilbert space dimension) for a competently mixed state. Two closely related measures are the linear entropy, 1- purity, and the participation ratio, 1/purity. """ tensor = rho.tensor N = rho.qubit_nb matrix = bk.reshape(tensor, [2**N, 2**N]) return bk.trace(bk.matmul(matrix, matrix))
python
def purity(rho: Density) -> bk.BKTensor: tensor = rho.tensor N = rho.qubit_nb matrix = bk.reshape(tensor, [2**N, 2**N]) return bk.trace(bk.matmul(matrix, matrix))
[ "def", "purity", "(", "rho", ":", "Density", ")", "->", "bk", ".", "BKTensor", ":", "tensor", "=", "rho", ".", "tensor", "N", "=", "rho", ".", "qubit_nb", "matrix", "=", "bk", ".", "reshape", "(", "tensor", ",", "[", "2", "**", "N", ",", "2", "**", "N", "]", ")", "return", "bk", ".", "trace", "(", "bk", ".", "matmul", "(", "matrix", ",", "matrix", ")", ")" ]
Calculate the purity of a mixed quantum state. Purity, defined as tr(rho^2), has an upper bound of 1 for a pure state, and a lower bound of 1/D (where D is the Hilbert space dimension) for a competently mixed state. Two closely related measures are the linear entropy, 1- purity, and the participation ratio, 1/purity.
[ "Calculate", "the", "purity", "of", "a", "mixed", "quantum", "state", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L59-L73
248,657
rigetti/quantumflow
quantumflow/measures.py
bures_distance
def bures_distance(rho0: Density, rho1: Density) -> float: """Return the Bures distance between mixed quantum states Note: Bures distance cannot be calculated within the tensor backend. """ fid = fidelity(rho0, rho1) op0 = asarray(rho0.asoperator()) op1 = asarray(rho1.asoperator()) tr0 = np.trace(op0) tr1 = np.trace(op1) return np.sqrt(tr0 + tr1 - 2.*np.sqrt(fid))
python
def bures_distance(rho0: Density, rho1: Density) -> float: fid = fidelity(rho0, rho1) op0 = asarray(rho0.asoperator()) op1 = asarray(rho1.asoperator()) tr0 = np.trace(op0) tr1 = np.trace(op1) return np.sqrt(tr0 + tr1 - 2.*np.sqrt(fid))
[ "def", "bures_distance", "(", "rho0", ":", "Density", ",", "rho1", ":", "Density", ")", "->", "float", ":", "fid", "=", "fidelity", "(", "rho0", ",", "rho1", ")", "op0", "=", "asarray", "(", "rho0", ".", "asoperator", "(", ")", ")", "op1", "=", "asarray", "(", "rho1", ".", "asoperator", "(", ")", ")", "tr0", "=", "np", ".", "trace", "(", "op0", ")", "tr1", "=", "np", ".", "trace", "(", "op1", ")", "return", "np", ".", "sqrt", "(", "tr0", "+", "tr1", "-", "2.", "*", "np", ".", "sqrt", "(", "fid", ")", ")" ]
Return the Bures distance between mixed quantum states Note: Bures distance cannot be calculated within the tensor backend.
[ "Return", "the", "Bures", "distance", "between", "mixed", "quantum", "states" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L95-L106
248,658
rigetti/quantumflow
quantumflow/measures.py
bures_angle
def bures_angle(rho0: Density, rho1: Density) -> float: """Return the Bures angle between mixed quantum states Note: Bures angle cannot be calculated within the tensor backend. """ return np.arccos(np.sqrt(fidelity(rho0, rho1)))
python
def bures_angle(rho0: Density, rho1: Density) -> float: return np.arccos(np.sqrt(fidelity(rho0, rho1)))
[ "def", "bures_angle", "(", "rho0", ":", "Density", ",", "rho1", ":", "Density", ")", "->", "float", ":", "return", "np", ".", "arccos", "(", "np", ".", "sqrt", "(", "fidelity", "(", "rho0", ",", "rho1", ")", ")", ")" ]
Return the Bures angle between mixed quantum states Note: Bures angle cannot be calculated within the tensor backend.
[ "Return", "the", "Bures", "angle", "between", "mixed", "quantum", "states" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L110-L115
248,659
rigetti/quantumflow
quantumflow/measures.py
density_angle
def density_angle(rho0: Density, rho1: Density) -> bk.BKTensor: """The Fubini-Study angle between density matrices""" return fubini_study_angle(rho0.vec, rho1.vec)
python
def density_angle(rho0: Density, rho1: Density) -> bk.BKTensor: return fubini_study_angle(rho0.vec, rho1.vec)
[ "def", "density_angle", "(", "rho0", ":", "Density", ",", "rho1", ":", "Density", ")", "->", "bk", ".", "BKTensor", ":", "return", "fubini_study_angle", "(", "rho0", ".", "vec", ",", "rho1", ".", "vec", ")" ]
The Fubini-Study angle between density matrices
[ "The", "Fubini", "-", "Study", "angle", "between", "density", "matrices" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L118-L120
248,660
rigetti/quantumflow
quantumflow/measures.py
densities_close
def densities_close(rho0: Density, rho1: Density, tolerance: float = TOLERANCE) -> bool: """Returns True if densities are almost identical. Closeness is measured with the metric Fubini-Study angle. """ return vectors_close(rho0.vec, rho1.vec, tolerance)
python
def densities_close(rho0: Density, rho1: Density, tolerance: float = TOLERANCE) -> bool: return vectors_close(rho0.vec, rho1.vec, tolerance)
[ "def", "densities_close", "(", "rho0", ":", "Density", ",", "rho1", ":", "Density", ",", "tolerance", ":", "float", "=", "TOLERANCE", ")", "->", "bool", ":", "return", "vectors_close", "(", "rho0", ".", "vec", ",", "rho1", ".", "vec", ",", "tolerance", ")" ]
Returns True if densities are almost identical. Closeness is measured with the metric Fubini-Study angle.
[ "Returns", "True", "if", "densities", "are", "almost", "identical", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L123-L129
248,661
rigetti/quantumflow
quantumflow/measures.py
entropy
def entropy(rho: Density, base: float = None) -> float: """ Returns the von-Neumann entropy of a mixed quantum state. Args: rho: A density matrix base: Optional logarithm base. Default is base e, and entropy is measures in nats. For bits set base to 2. Returns: The von-Neumann entropy of rho """ op = asarray(rho.asoperator()) probs = np.linalg.eigvalsh(op) probs = np.maximum(probs, 0.0) # Compensate for floating point errors return scipy.stats.entropy(probs, base=base)
python
def entropy(rho: Density, base: float = None) -> float: op = asarray(rho.asoperator()) probs = np.linalg.eigvalsh(op) probs = np.maximum(probs, 0.0) # Compensate for floating point errors return scipy.stats.entropy(probs, base=base)
[ "def", "entropy", "(", "rho", ":", "Density", ",", "base", ":", "float", "=", "None", ")", "->", "float", ":", "op", "=", "asarray", "(", "rho", ".", "asoperator", "(", ")", ")", "probs", "=", "np", ".", "linalg", ".", "eigvalsh", "(", "op", ")", "probs", "=", "np", ".", "maximum", "(", "probs", ",", "0.0", ")", "# Compensate for floating point errors", "return", "scipy", ".", "stats", ".", "entropy", "(", "probs", ",", "base", "=", "base", ")" ]
Returns the von-Neumann entropy of a mixed quantum state. Args: rho: A density matrix base: Optional logarithm base. Default is base e, and entropy is measures in nats. For bits set base to 2. Returns: The von-Neumann entropy of rho
[ "Returns", "the", "von", "-", "Neumann", "entropy", "of", "a", "mixed", "quantum", "state", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L133-L148
248,662
rigetti/quantumflow
quantumflow/measures.py
mutual_info
def mutual_info(rho: Density, qubits0: Qubits, qubits1: Qubits = None, base: float = None) -> float: """Compute the bipartite von-Neumann mutual information of a mixed quantum state. Args: rho: A density matrix of the complete system qubits0: Qubits of system 0 qubits1: Qubits of system 1. If none, taken to be all remaining qubits base: Optional logarithm base. Default is base e Returns: The bipartite von-Neumann mutual information. """ if qubits1 is None: qubits1 = tuple(set(rho.qubits) - set(qubits0)) rho0 = rho.partial_trace(qubits1) rho1 = rho.partial_trace(qubits0) ent = entropy(rho, base) ent0 = entropy(rho0, base) ent1 = entropy(rho1, base) return ent0 + ent1 - ent
python
def mutual_info(rho: Density, qubits0: Qubits, qubits1: Qubits = None, base: float = None) -> float: if qubits1 is None: qubits1 = tuple(set(rho.qubits) - set(qubits0)) rho0 = rho.partial_trace(qubits1) rho1 = rho.partial_trace(qubits0) ent = entropy(rho, base) ent0 = entropy(rho0, base) ent1 = entropy(rho1, base) return ent0 + ent1 - ent
[ "def", "mutual_info", "(", "rho", ":", "Density", ",", "qubits0", ":", "Qubits", ",", "qubits1", ":", "Qubits", "=", "None", ",", "base", ":", "float", "=", "None", ")", "->", "float", ":", "if", "qubits1", "is", "None", ":", "qubits1", "=", "tuple", "(", "set", "(", "rho", ".", "qubits", ")", "-", "set", "(", "qubits0", ")", ")", "rho0", "=", "rho", ".", "partial_trace", "(", "qubits1", ")", "rho1", "=", "rho", ".", "partial_trace", "(", "qubits0", ")", "ent", "=", "entropy", "(", "rho", ",", "base", ")", "ent0", "=", "entropy", "(", "rho0", ",", "base", ")", "ent1", "=", "entropy", "(", "rho1", ",", "base", ")", "return", "ent0", "+", "ent1", "-", "ent" ]
Compute the bipartite von-Neumann mutual information of a mixed quantum state. Args: rho: A density matrix of the complete system qubits0: Qubits of system 0 qubits1: Qubits of system 1. If none, taken to be all remaining qubits base: Optional logarithm base. Default is base e Returns: The bipartite von-Neumann mutual information.
[ "Compute", "the", "bipartite", "von", "-", "Neumann", "mutual", "information", "of", "a", "mixed", "quantum", "state", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L152-L178
248,663
rigetti/quantumflow
quantumflow/measures.py
gate_angle
def gate_angle(gate0: Gate, gate1: Gate) -> bk.BKTensor: """The Fubini-Study angle between gates""" return fubini_study_angle(gate0.vec, gate1.vec)
python
def gate_angle(gate0: Gate, gate1: Gate) -> bk.BKTensor: return fubini_study_angle(gate0.vec, gate1.vec)
[ "def", "gate_angle", "(", "gate0", ":", "Gate", ",", "gate1", ":", "Gate", ")", "->", "bk", ".", "BKTensor", ":", "return", "fubini_study_angle", "(", "gate0", ".", "vec", ",", "gate1", ".", "vec", ")" ]
The Fubini-Study angle between gates
[ "The", "Fubini", "-", "Study", "angle", "between", "gates" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L183-L185
248,664
rigetti/quantumflow
quantumflow/measures.py
channel_angle
def channel_angle(chan0: Channel, chan1: Channel) -> bk.BKTensor: """The Fubini-Study angle between channels""" return fubini_study_angle(chan0.vec, chan1.vec)
python
def channel_angle(chan0: Channel, chan1: Channel) -> bk.BKTensor: return fubini_study_angle(chan0.vec, chan1.vec)
[ "def", "channel_angle", "(", "chan0", ":", "Channel", ",", "chan1", ":", "Channel", ")", "->", "bk", ".", "BKTensor", ":", "return", "fubini_study_angle", "(", "chan0", ".", "vec", ",", "chan1", ".", "vec", ")" ]
The Fubini-Study angle between channels
[ "The", "Fubini", "-", "Study", "angle", "between", "channels" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L199-L201
248,665
rigetti/quantumflow
quantumflow/qubits.py
inner_product
def inner_product(vec0: QubitVector, vec1: QubitVector) -> bk.BKTensor: """ Hilbert-Schmidt inner product between qubit vectors The tensor rank and qubits must match. """ if vec0.rank != vec1.rank or vec0.qubit_nb != vec1.qubit_nb: raise ValueError('Incompatibly vectors. Qubits and rank must match') vec1 = vec1.permute(vec0.qubits) # Make sure qubits in same order return bk.inner(vec0.tensor, vec1.tensor)
python
def inner_product(vec0: QubitVector, vec1: QubitVector) -> bk.BKTensor: if vec0.rank != vec1.rank or vec0.qubit_nb != vec1.qubit_nb: raise ValueError('Incompatibly vectors. Qubits and rank must match') vec1 = vec1.permute(vec0.qubits) # Make sure qubits in same order return bk.inner(vec0.tensor, vec1.tensor)
[ "def", "inner_product", "(", "vec0", ":", "QubitVector", ",", "vec1", ":", "QubitVector", ")", "->", "bk", ".", "BKTensor", ":", "if", "vec0", ".", "rank", "!=", "vec1", ".", "rank", "or", "vec0", ".", "qubit_nb", "!=", "vec1", ".", "qubit_nb", ":", "raise", "ValueError", "(", "'Incompatibly vectors. Qubits and rank must match'", ")", "vec1", "=", "vec1", ".", "permute", "(", "vec0", ".", "qubits", ")", "# Make sure qubits in same order", "return", "bk", ".", "inner", "(", "vec0", ".", "tensor", ",", "vec1", ".", "tensor", ")" ]
Hilbert-Schmidt inner product between qubit vectors The tensor rank and qubits must match.
[ "Hilbert", "-", "Schmidt", "inner", "product", "between", "qubit", "vectors" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L233-L242
248,666
rigetti/quantumflow
quantumflow/qubits.py
outer_product
def outer_product(vec0: QubitVector, vec1: QubitVector) -> QubitVector: """Direct product of qubit vectors The tensor ranks must match and qubits must be disjoint. """ R = vec0.rank R1 = vec1.rank N0 = vec0.qubit_nb N1 = vec1.qubit_nb if R != R1: raise ValueError('Incompatibly vectors. Rank must match') if not set(vec0.qubits).isdisjoint(vec1.qubits): raise ValueError('Overlapping qubits') qubits: Qubits = tuple(vec0.qubits) + tuple(vec1.qubits) tensor = bk.outer(vec0.tensor, vec1.tensor) # Interleave (super)-operator axes # R = 1 perm = (0, 1) # R = 2 perm = (0, 2, 1, 3) # R = 4 perm = (0, 4, 1, 5, 2, 6, 3, 7) tensor = bk.reshape(tensor, ([2**N0] * R) + ([2**N1] * R)) perm = [idx for ij in zip(range(0, R), range(R, 2*R)) for idx in ij] tensor = bk.transpose(tensor, perm) return QubitVector(tensor, qubits)
python
def outer_product(vec0: QubitVector, vec1: QubitVector) -> QubitVector: R = vec0.rank R1 = vec1.rank N0 = vec0.qubit_nb N1 = vec1.qubit_nb if R != R1: raise ValueError('Incompatibly vectors. Rank must match') if not set(vec0.qubits).isdisjoint(vec1.qubits): raise ValueError('Overlapping qubits') qubits: Qubits = tuple(vec0.qubits) + tuple(vec1.qubits) tensor = bk.outer(vec0.tensor, vec1.tensor) # Interleave (super)-operator axes # R = 1 perm = (0, 1) # R = 2 perm = (0, 2, 1, 3) # R = 4 perm = (0, 4, 1, 5, 2, 6, 3, 7) tensor = bk.reshape(tensor, ([2**N0] * R) + ([2**N1] * R)) perm = [idx for ij in zip(range(0, R), range(R, 2*R)) for idx in ij] tensor = bk.transpose(tensor, perm) return QubitVector(tensor, qubits)
[ "def", "outer_product", "(", "vec0", ":", "QubitVector", ",", "vec1", ":", "QubitVector", ")", "->", "QubitVector", ":", "R", "=", "vec0", ".", "rank", "R1", "=", "vec1", ".", "rank", "N0", "=", "vec0", ".", "qubit_nb", "N1", "=", "vec1", ".", "qubit_nb", "if", "R", "!=", "R1", ":", "raise", "ValueError", "(", "'Incompatibly vectors. Rank must match'", ")", "if", "not", "set", "(", "vec0", ".", "qubits", ")", ".", "isdisjoint", "(", "vec1", ".", "qubits", ")", ":", "raise", "ValueError", "(", "'Overlapping qubits'", ")", "qubits", ":", "Qubits", "=", "tuple", "(", "vec0", ".", "qubits", ")", "+", "tuple", "(", "vec1", ".", "qubits", ")", "tensor", "=", "bk", ".", "outer", "(", "vec0", ".", "tensor", ",", "vec1", ".", "tensor", ")", "# Interleave (super)-operator axes", "# R = 1 perm = (0, 1)", "# R = 2 perm = (0, 2, 1, 3)", "# R = 4 perm = (0, 4, 1, 5, 2, 6, 3, 7)", "tensor", "=", "bk", ".", "reshape", "(", "tensor", ",", "(", "[", "2", "**", "N0", "]", "*", "R", ")", "+", "(", "[", "2", "**", "N1", "]", "*", "R", ")", ")", "perm", "=", "[", "idx", "for", "ij", "in", "zip", "(", "range", "(", "0", ",", "R", ")", ",", "range", "(", "R", ",", "2", "*", "R", ")", ")", "for", "idx", "in", "ij", "]", "tensor", "=", "bk", ".", "transpose", "(", "tensor", ",", "perm", ")", "return", "QubitVector", "(", "tensor", ",", "qubits", ")" ]
Direct product of qubit vectors The tensor ranks must match and qubits must be disjoint.
[ "Direct", "product", "of", "qubit", "vectors" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L248-L277
248,667
rigetti/quantumflow
quantumflow/qubits.py
vectors_close
def vectors_close(vec0: QubitVector, vec1: QubitVector, tolerance: float = TOLERANCE) -> bool: """Return True if vectors in close in the projective Hilbert space. Similarity is measured with the Fubini–Study metric. """ if vec0.rank != vec1.rank: return False if vec0.qubit_nb != vec1.qubit_nb: return False if set(vec0.qubits) ^ set(vec1.qubits): return False return bk.evaluate(fubini_study_angle(vec0, vec1)) <= tolerance
python
def vectors_close(vec0: QubitVector, vec1: QubitVector, tolerance: float = TOLERANCE) -> bool: if vec0.rank != vec1.rank: return False if vec0.qubit_nb != vec1.qubit_nb: return False if set(vec0.qubits) ^ set(vec1.qubits): return False return bk.evaluate(fubini_study_angle(vec0, vec1)) <= tolerance
[ "def", "vectors_close", "(", "vec0", ":", "QubitVector", ",", "vec1", ":", "QubitVector", ",", "tolerance", ":", "float", "=", "TOLERANCE", ")", "->", "bool", ":", "if", "vec0", ".", "rank", "!=", "vec1", ".", "rank", ":", "return", "False", "if", "vec0", ".", "qubit_nb", "!=", "vec1", ".", "qubit_nb", ":", "return", "False", "if", "set", "(", "vec0", ".", "qubits", ")", "^", "set", "(", "vec1", ".", "qubits", ")", ":", "return", "False", "return", "bk", ".", "evaluate", "(", "fubini_study_angle", "(", "vec0", ",", "vec1", ")", ")", "<=", "tolerance" ]
Return True if vectors in close in the projective Hilbert space. Similarity is measured with the Fubini–Study metric.
[ "Return", "True", "if", "vectors", "in", "close", "in", "the", "projective", "Hilbert", "space", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L310-L325
248,668
rigetti/quantumflow
quantumflow/qubits.py
QubitVector.flatten
def flatten(self) -> bk.BKTensor: """Return tensor with with qubit indices flattened""" N = self.qubit_nb R = self.rank return bk.reshape(self.tensor, [2**N]*R)
python
def flatten(self) -> bk.BKTensor: N = self.qubit_nb R = self.rank return bk.reshape(self.tensor, [2**N]*R)
[ "def", "flatten", "(", "self", ")", "->", "bk", ".", "BKTensor", ":", "N", "=", "self", ".", "qubit_nb", "R", "=", "self", ".", "rank", "return", "bk", ".", "reshape", "(", "self", ".", "tensor", ",", "[", "2", "**", "N", "]", "*", "R", ")" ]
Return tensor with with qubit indices flattened
[ "Return", "tensor", "with", "with", "qubit", "indices", "flattened" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L131-L135
248,669
rigetti/quantumflow
quantumflow/qubits.py
QubitVector.relabel
def relabel(self, qubits: Qubits) -> 'QubitVector': """Return a copy of this vector with new qubits""" qubits = tuple(qubits) assert len(qubits) == self.qubit_nb vec = copy(self) vec.qubits = qubits return vec
python
def relabel(self, qubits: Qubits) -> 'QubitVector': qubits = tuple(qubits) assert len(qubits) == self.qubit_nb vec = copy(self) vec.qubits = qubits return vec
[ "def", "relabel", "(", "self", ",", "qubits", ":", "Qubits", ")", "->", "'QubitVector'", ":", "qubits", "=", "tuple", "(", "qubits", ")", "assert", "len", "(", "qubits", ")", "==", "self", ".", "qubit_nb", "vec", "=", "copy", "(", "self", ")", "vec", ".", "qubits", "=", "qubits", "return", "vec" ]
Return a copy of this vector with new qubits
[ "Return", "a", "copy", "of", "this", "vector", "with", "new", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L137-L143
248,670
rigetti/quantumflow
quantumflow/qubits.py
QubitVector.H
def H(self) -> 'QubitVector': """Return the conjugate transpose of this tensor.""" N = self.qubit_nb R = self.rank # (super) operator transpose tensor = self.tensor tensor = bk.reshape(tensor, [2**(N*R//2)] * 2) tensor = bk.transpose(tensor) tensor = bk.reshape(tensor, [2] * R * N) tensor = bk.conj(tensor) return QubitVector(tensor, self.qubits)
python
def H(self) -> 'QubitVector': N = self.qubit_nb R = self.rank # (super) operator transpose tensor = self.tensor tensor = bk.reshape(tensor, [2**(N*R//2)] * 2) tensor = bk.transpose(tensor) tensor = bk.reshape(tensor, [2] * R * N) tensor = bk.conj(tensor) return QubitVector(tensor, self.qubits)
[ "def", "H", "(", "self", ")", "->", "'QubitVector'", ":", "N", "=", "self", ".", "qubit_nb", "R", "=", "self", ".", "rank", "# (super) operator transpose", "tensor", "=", "self", ".", "tensor", "tensor", "=", "bk", ".", "reshape", "(", "tensor", ",", "[", "2", "**", "(", "N", "*", "R", "//", "2", ")", "]", "*", "2", ")", "tensor", "=", "bk", ".", "transpose", "(", "tensor", ")", "tensor", "=", "bk", ".", "reshape", "(", "tensor", ",", "[", "2", "]", "*", "R", "*", "N", ")", "tensor", "=", "bk", ".", "conj", "(", "tensor", ")", "return", "QubitVector", "(", "tensor", ",", "self", ".", "qubits", ")" ]
Return the conjugate transpose of this tensor.
[ "Return", "the", "conjugate", "transpose", "of", "this", "tensor", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L165-L178
248,671
rigetti/quantumflow
quantumflow/qubits.py
QubitVector.norm
def norm(self) -> bk.BKTensor: """Return the norm of this vector""" return bk.absolute(bk.inner(self.tensor, self.tensor))
python
def norm(self) -> bk.BKTensor: return bk.absolute(bk.inner(self.tensor, self.tensor))
[ "def", "norm", "(", "self", ")", "->", "bk", ".", "BKTensor", ":", "return", "bk", ".", "absolute", "(", "bk", ".", "inner", "(", "self", ".", "tensor", ",", "self", ".", "tensor", ")", ")" ]
Return the norm of this vector
[ "Return", "the", "norm", "of", "this", "vector" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L180-L182
248,672
rigetti/quantumflow
quantumflow/qubits.py
QubitVector.partial_trace
def partial_trace(self, qubits: Qubits) -> 'QubitVector': """ Return the partial trace over some subset of qubits""" N = self.qubit_nb R = self.rank if R == 1: raise ValueError('Cannot take trace of vector') new_qubits: List[Qubit] = list(self.qubits) for q in qubits: new_qubits.remove(q) if not new_qubits: raise ValueError('Cannot remove all qubits with partial_trace.') indices = [self.qubits.index(qubit) for qubit in qubits] subscripts = list(EINSUM_SUBSCRIPTS)[0:N*R] for idx in indices: for r in range(1, R): subscripts[r * N + idx] = subscripts[idx] subscript_str = ''.join(subscripts) # Only numpy's einsum works with repeated subscripts tensor = self.asarray() tensor = np.einsum(subscript_str, tensor) return QubitVector(tensor, new_qubits)
python
def partial_trace(self, qubits: Qubits) -> 'QubitVector': N = self.qubit_nb R = self.rank if R == 1: raise ValueError('Cannot take trace of vector') new_qubits: List[Qubit] = list(self.qubits) for q in qubits: new_qubits.remove(q) if not new_qubits: raise ValueError('Cannot remove all qubits with partial_trace.') indices = [self.qubits.index(qubit) for qubit in qubits] subscripts = list(EINSUM_SUBSCRIPTS)[0:N*R] for idx in indices: for r in range(1, R): subscripts[r * N + idx] = subscripts[idx] subscript_str = ''.join(subscripts) # Only numpy's einsum works with repeated subscripts tensor = self.asarray() tensor = np.einsum(subscript_str, tensor) return QubitVector(tensor, new_qubits)
[ "def", "partial_trace", "(", "self", ",", "qubits", ":", "Qubits", ")", "->", "'QubitVector'", ":", "N", "=", "self", ".", "qubit_nb", "R", "=", "self", ".", "rank", "if", "R", "==", "1", ":", "raise", "ValueError", "(", "'Cannot take trace of vector'", ")", "new_qubits", ":", "List", "[", "Qubit", "]", "=", "list", "(", "self", ".", "qubits", ")", "for", "q", "in", "qubits", ":", "new_qubits", ".", "remove", "(", "q", ")", "if", "not", "new_qubits", ":", "raise", "ValueError", "(", "'Cannot remove all qubits with partial_trace.'", ")", "indices", "=", "[", "self", ".", "qubits", ".", "index", "(", "qubit", ")", "for", "qubit", "in", "qubits", "]", "subscripts", "=", "list", "(", "EINSUM_SUBSCRIPTS", ")", "[", "0", ":", "N", "*", "R", "]", "for", "idx", "in", "indices", ":", "for", "r", "in", "range", "(", "1", ",", "R", ")", ":", "subscripts", "[", "r", "*", "N", "+", "idx", "]", "=", "subscripts", "[", "idx", "]", "subscript_str", "=", "''", ".", "join", "(", "subscripts", ")", "# Only numpy's einsum works with repeated subscripts", "tensor", "=", "self", ".", "asarray", "(", ")", "tensor", "=", "np", ".", "einsum", "(", "subscript_str", ",", "tensor", ")", "return", "QubitVector", "(", "tensor", ",", "new_qubits", ")" ]
Return the partial trace over some subset of qubits
[ "Return", "the", "partial", "trace", "over", "some", "subset", "of", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L201-L227
248,673
rigetti/quantumflow
examples/tensorflow2_fit_gate.py
fit_zyz
def fit_zyz(target_gate): """ Tensorflow 2.0 example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate. """ steps = 1000 dev = '/gpu:0' if bk.DEVICE == 'gpu' else '/cpu:0' with tf.device(dev): t = tf.Variable(tf.random.normal([3])) def loss_fn(): """Loss""" gate = qf.ZYZ(t[0], t[1], t[2]) ang = qf.fubini_study_angle(target_gate.vec, gate.vec) return ang opt = tf.optimizers.Adam(learning_rate=0.001) opt.minimize(loss_fn, var_list=[t]) for step in range(steps): opt.minimize(loss_fn, var_list=[t]) loss = loss_fn() print(step, loss.numpy()) if loss < 0.01: break else: print("Failed to coverge") return bk.evaluate(t)
python
def fit_zyz(target_gate): steps = 1000 dev = '/gpu:0' if bk.DEVICE == 'gpu' else '/cpu:0' with tf.device(dev): t = tf.Variable(tf.random.normal([3])) def loss_fn(): """Loss""" gate = qf.ZYZ(t[0], t[1], t[2]) ang = qf.fubini_study_angle(target_gate.vec, gate.vec) return ang opt = tf.optimizers.Adam(learning_rate=0.001) opt.minimize(loss_fn, var_list=[t]) for step in range(steps): opt.minimize(loss_fn, var_list=[t]) loss = loss_fn() print(step, loss.numpy()) if loss < 0.01: break else: print("Failed to coverge") return bk.evaluate(t)
[ "def", "fit_zyz", "(", "target_gate", ")", ":", "steps", "=", "1000", "dev", "=", "'/gpu:0'", "if", "bk", ".", "DEVICE", "==", "'gpu'", "else", "'/cpu:0'", "with", "tf", ".", "device", "(", "dev", ")", ":", "t", "=", "tf", ".", "Variable", "(", "tf", ".", "random", ".", "normal", "(", "[", "3", "]", ")", ")", "def", "loss_fn", "(", ")", ":", "\"\"\"Loss\"\"\"", "gate", "=", "qf", ".", "ZYZ", "(", "t", "[", "0", "]", ",", "t", "[", "1", "]", ",", "t", "[", "2", "]", ")", "ang", "=", "qf", ".", "fubini_study_angle", "(", "target_gate", ".", "vec", ",", "gate", ".", "vec", ")", "return", "ang", "opt", "=", "tf", ".", "optimizers", ".", "Adam", "(", "learning_rate", "=", "0.001", ")", "opt", ".", "minimize", "(", "loss_fn", ",", "var_list", "=", "[", "t", "]", ")", "for", "step", "in", "range", "(", "steps", ")", ":", "opt", ".", "minimize", "(", "loss_fn", ",", "var_list", "=", "[", "t", "]", ")", "loss", "=", "loss_fn", "(", ")", "print", "(", "step", ",", "loss", ".", "numpy", "(", ")", ")", "if", "loss", "<", "0.01", ":", "break", "else", ":", "print", "(", "\"Failed to coverge\"", ")", "return", "bk", ".", "evaluate", "(", "t", ")" ]
Tensorflow 2.0 example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate.
[ "Tensorflow", "2", ".", "0", "example", ".", "Given", "an", "arbitrary", "one", "-", "qubit", "gate", "use", "gradient", "descent", "to", "find", "corresponding", "parameters", "of", "a", "universal", "ZYZ", "gate", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/examples/tensorflow2_fit_gate.py#L21-L53
248,674
rigetti/quantumflow
quantumflow/programs.py
Program.run
def run(self, ket: State = None) -> State: """Compiles and runs a program. The optional program argument supplies the initial state and memory. Else qubits and classical bits start from zero states. """ if ket is None: qubits = self.qubits ket = zero_state(qubits) ket = self._initilize(ket) pc = 0 while pc >= 0 and pc < len(self): instr = self.instructions[pc] ket = ket.update({PC: pc + 1}) ket = instr.run(ket) pc = ket.memory[PC] return ket
python
def run(self, ket: State = None) -> State: if ket is None: qubits = self.qubits ket = zero_state(qubits) ket = self._initilize(ket) pc = 0 while pc >= 0 and pc < len(self): instr = self.instructions[pc] ket = ket.update({PC: pc + 1}) ket = instr.run(ket) pc = ket.memory[PC] return ket
[ "def", "run", "(", "self", ",", "ket", ":", "State", "=", "None", ")", "->", "State", ":", "if", "ket", "is", "None", ":", "qubits", "=", "self", ".", "qubits", "ket", "=", "zero_state", "(", "qubits", ")", "ket", "=", "self", ".", "_initilize", "(", "ket", ")", "pc", "=", "0", "while", "pc", ">=", "0", "and", "pc", "<", "len", "(", "self", ")", ":", "instr", "=", "self", ".", "instructions", "[", "pc", "]", "ket", "=", "ket", ".", "update", "(", "{", "PC", ":", "pc", "+", "1", "}", ")", "ket", "=", "instr", ".", "run", "(", "ket", ")", "pc", "=", "ket", ".", "memory", "[", "PC", "]", "return", "ket" ]
Compiles and runs a program. The optional program argument supplies the initial state and memory. Else qubits and classical bits start from zero states.
[ "Compiles", "and", "runs", "a", "program", ".", "The", "optional", "program", "argument", "supplies", "the", "initial", "state", "and", "memory", ".", "Else", "qubits", "and", "classical", "bits", "start", "from", "zero", "states", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/programs.py#L152-L170
248,675
rigetti/quantumflow
quantumflow/ops.py
Gate.relabel
def relabel(self, qubits: Qubits) -> 'Gate': """Return a copy of this Gate with new qubits""" gate = copy(self) gate.vec = gate.vec.relabel(qubits) return gate
python
def relabel(self, qubits: Qubits) -> 'Gate': gate = copy(self) gate.vec = gate.vec.relabel(qubits) return gate
[ "def", "relabel", "(", "self", ",", "qubits", ":", "Qubits", ")", "->", "'Gate'", ":", "gate", "=", "copy", "(", "self", ")", "gate", ".", "vec", "=", "gate", ".", "vec", ".", "relabel", "(", "qubits", ")", "return", "gate" ]
Return a copy of this Gate with new qubits
[ "Return", "a", "copy", "of", "this", "Gate", "with", "new", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L142-L146
248,676
rigetti/quantumflow
quantumflow/ops.py
Gate.run
def run(self, ket: State) -> State: """Apply the action of this gate upon a state""" qubits = self.qubits indices = [ket.qubits.index(q) for q in qubits] tensor = bk.tensormul(self.tensor, ket.tensor, indices) return State(tensor, ket.qubits, ket.memory)
python
def run(self, ket: State) -> State: qubits = self.qubits indices = [ket.qubits.index(q) for q in qubits] tensor = bk.tensormul(self.tensor, ket.tensor, indices) return State(tensor, ket.qubits, ket.memory)
[ "def", "run", "(", "self", ",", "ket", ":", "State", ")", "->", "State", ":", "qubits", "=", "self", ".", "qubits", "indices", "=", "[", "ket", ".", "qubits", ".", "index", "(", "q", ")", "for", "q", "in", "qubits", "]", "tensor", "=", "bk", ".", "tensormul", "(", "self", ".", "tensor", ",", "ket", ".", "tensor", ",", "indices", ")", "return", "State", "(", "tensor", ",", "ket", ".", "qubits", ",", "ket", ".", "memory", ")" ]
Apply the action of this gate upon a state
[ "Apply", "the", "action", "of", "this", "gate", "upon", "a", "state" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L161-L166
248,677
rigetti/quantumflow
quantumflow/ops.py
Gate.evolve
def evolve(self, rho: Density) -> Density: """Apply the action of this gate upon a density""" # TODO: implement without explicit channel creation? chan = self.aschannel() return chan.evolve(rho)
python
def evolve(self, rho: Density) -> Density: # TODO: implement without explicit channel creation? chan = self.aschannel() return chan.evolve(rho)
[ "def", "evolve", "(", "self", ",", "rho", ":", "Density", ")", "->", "Density", ":", "# TODO: implement without explicit channel creation?", "chan", "=", "self", ".", "aschannel", "(", ")", "return", "chan", ".", "evolve", "(", "rho", ")" ]
Apply the action of this gate upon a density
[ "Apply", "the", "action", "of", "this", "gate", "upon", "a", "density" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L168-L172
248,678
rigetti/quantumflow
quantumflow/ops.py
Gate.aschannel
def aschannel(self) -> 'Channel': """Converts a Gate into a Channel""" N = self.qubit_nb R = 4 tensor = bk.outer(self.tensor, self.H.tensor) tensor = bk.reshape(tensor, [2**N]*R) tensor = bk.transpose(tensor, [0, 3, 1, 2]) return Channel(tensor, self.qubits)
python
def aschannel(self) -> 'Channel': N = self.qubit_nb R = 4 tensor = bk.outer(self.tensor, self.H.tensor) tensor = bk.reshape(tensor, [2**N]*R) tensor = bk.transpose(tensor, [0, 3, 1, 2]) return Channel(tensor, self.qubits)
[ "def", "aschannel", "(", "self", ")", "->", "'Channel'", ":", "N", "=", "self", ".", "qubit_nb", "R", "=", "4", "tensor", "=", "bk", ".", "outer", "(", "self", ".", "tensor", ",", "self", ".", "H", ".", "tensor", ")", "tensor", "=", "bk", ".", "reshape", "(", "tensor", ",", "[", "2", "**", "N", "]", "*", "R", ")", "tensor", "=", "bk", ".", "transpose", "(", "tensor", ",", "[", "0", ",", "3", ",", "1", ",", "2", "]", ")", "return", "Channel", "(", "tensor", ",", "self", ".", "qubits", ")" ]
Converts a Gate into a Channel
[ "Converts", "a", "Gate", "into", "a", "Channel" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L243-L252
248,679
rigetti/quantumflow
quantumflow/ops.py
Gate.su
def su(self) -> 'Gate': """Convert gate tensor to the special unitary group.""" rank = 2**self.qubit_nb U = asarray(self.asoperator()) U /= np.linalg.det(U) ** (1/rank) return Gate(tensor=U, qubits=self.qubits)
python
def su(self) -> 'Gate': rank = 2**self.qubit_nb U = asarray(self.asoperator()) U /= np.linalg.det(U) ** (1/rank) return Gate(tensor=U, qubits=self.qubits)
[ "def", "su", "(", "self", ")", "->", "'Gate'", ":", "rank", "=", "2", "**", "self", ".", "qubit_nb", "U", "=", "asarray", "(", "self", ".", "asoperator", "(", ")", ")", "U", "/=", "np", ".", "linalg", ".", "det", "(", "U", ")", "**", "(", "1", "/", "rank", ")", "return", "Gate", "(", "tensor", "=", "U", ",", "qubits", "=", "self", ".", "qubits", ")" ]
Convert gate tensor to the special unitary group.
[ "Convert", "gate", "tensor", "to", "the", "special", "unitary", "group", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L254-L259
248,680
rigetti/quantumflow
quantumflow/ops.py
Channel.relabel
def relabel(self, qubits: Qubits) -> 'Channel': """Return a copy of this channel with new qubits""" chan = copy(self) chan.vec = chan.vec.relabel(qubits) return chan
python
def relabel(self, qubits: Qubits) -> 'Channel': chan = copy(self) chan.vec = chan.vec.relabel(qubits) return chan
[ "def", "relabel", "(", "self", ",", "qubits", ":", "Qubits", ")", "->", "'Channel'", ":", "chan", "=", "copy", "(", "self", ")", "chan", ".", "vec", "=", "chan", ".", "vec", ".", "relabel", "(", "qubits", ")", "return", "chan" ]
Return a copy of this channel with new qubits
[ "Return", "a", "copy", "of", "this", "channel", "with", "new", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L298-L302
248,681
rigetti/quantumflow
quantumflow/ops.py
Channel.permute
def permute(self, qubits: Qubits) -> 'Channel': """Return a copy of this channel with qubits in new order""" vec = self.vec.permute(qubits) return Channel(vec.tensor, qubits=vec.qubits)
python
def permute(self, qubits: Qubits) -> 'Channel': vec = self.vec.permute(qubits) return Channel(vec.tensor, qubits=vec.qubits)
[ "def", "permute", "(", "self", ",", "qubits", ":", "Qubits", ")", "->", "'Channel'", ":", "vec", "=", "self", ".", "vec", ".", "permute", "(", "qubits", ")", "return", "Channel", "(", "vec", ".", "tensor", ",", "qubits", "=", "vec", ".", "qubits", ")" ]
Return a copy of this channel with qubits in new order
[ "Return", "a", "copy", "of", "this", "channel", "with", "qubits", "in", "new", "order" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L304-L307
248,682
rigetti/quantumflow
quantumflow/ops.py
Channel.sharp
def sharp(self) -> 'Channel': r"""Return the 'sharp' transpose of the superoperator. The transpose :math:`S^\#` switches the two covariant (bra) indices of the superoperator. (Which in our representation are the 2nd and 3rd super-indices) If :math:`S^\#` is Hermitian, then :math:`S` is a Hermitian-map (i.e. transforms Hermitian operators to hJrmitian operators) Flattening the :math:`S^\#` superoperator to a matrix gives the Choi matrix representation. (See channel.choi()) """ N = self.qubit_nb tensor = self.tensor tensor = bk.reshape(tensor, [2**N] * 4) tensor = bk.transpose(tensor, (0, 2, 1, 3)) tensor = bk.reshape(tensor, [2] * 4 * N) return Channel(tensor, self.qubits)
python
def sharp(self) -> 'Channel': r"""Return the 'sharp' transpose of the superoperator. The transpose :math:`S^\#` switches the two covariant (bra) indices of the superoperator. (Which in our representation are the 2nd and 3rd super-indices) If :math:`S^\#` is Hermitian, then :math:`S` is a Hermitian-map (i.e. transforms Hermitian operators to hJrmitian operators) Flattening the :math:`S^\#` superoperator to a matrix gives the Choi matrix representation. (See channel.choi()) """ N = self.qubit_nb tensor = self.tensor tensor = bk.reshape(tensor, [2**N] * 4) tensor = bk.transpose(tensor, (0, 2, 1, 3)) tensor = bk.reshape(tensor, [2] * 4 * N) return Channel(tensor, self.qubits)
[ "def", "sharp", "(", "self", ")", "->", "'Channel'", ":", "N", "=", "self", ".", "qubit_nb", "tensor", "=", "self", ".", "tensor", "tensor", "=", "bk", ".", "reshape", "(", "tensor", ",", "[", "2", "**", "N", "]", "*", "4", ")", "tensor", "=", "bk", ".", "transpose", "(", "tensor", ",", "(", "0", ",", "2", ",", "1", ",", "3", ")", ")", "tensor", "=", "bk", ".", "reshape", "(", "tensor", ",", "[", "2", "]", "*", "4", "*", "N", ")", "return", "Channel", "(", "tensor", ",", "self", ".", "qubits", ")" ]
r"""Return the 'sharp' transpose of the superoperator. The transpose :math:`S^\#` switches the two covariant (bra) indices of the superoperator. (Which in our representation are the 2nd and 3rd super-indices) If :math:`S^\#` is Hermitian, then :math:`S` is a Hermitian-map (i.e. transforms Hermitian operators to hJrmitian operators) Flattening the :math:`S^\#` superoperator to a matrix gives the Choi matrix representation. (See channel.choi())
[ "r", "Return", "the", "sharp", "transpose", "of", "the", "superoperator", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L315-L335
248,683
rigetti/quantumflow
quantumflow/ops.py
Channel.choi
def choi(self) -> bk.BKTensor: """Return the Choi matrix representation of this super operator""" # Put superop axes in [ok, ib, ob, ik] and reshape to matrix N = self.qubit_nb return bk.reshape(self.sharp.tensor, [2**(N*2)] * 2)
python
def choi(self) -> bk.BKTensor: # Put superop axes in [ok, ib, ob, ik] and reshape to matrix N = self.qubit_nb return bk.reshape(self.sharp.tensor, [2**(N*2)] * 2)
[ "def", "choi", "(", "self", ")", "->", "bk", ".", "BKTensor", ":", "# Put superop axes in [ok, ib, ob, ik] and reshape to matrix", "N", "=", "self", ".", "qubit_nb", "return", "bk", ".", "reshape", "(", "self", ".", "sharp", ".", "tensor", ",", "[", "2", "**", "(", "N", "*", "2", ")", "]", "*", "2", ")" ]
Return the Choi matrix representation of this super operator
[ "Return", "the", "Choi", "matrix", "representation", "of", "this", "super", "operator" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L337-L342
248,684
rigetti/quantumflow
quantumflow/ops.py
Channel.evolve
def evolve(self, rho: Density) -> Density: """Apply the action of this channel upon a density""" N = rho.qubit_nb qubits = rho.qubits indices = list([qubits.index(q) for q in self.qubits]) + \ list([qubits.index(q) + N for q in self.qubits]) tensor = bk.tensormul(self.tensor, rho.tensor, indices) return Density(tensor, qubits, rho.memory)
python
def evolve(self, rho: Density) -> Density: N = rho.qubit_nb qubits = rho.qubits indices = list([qubits.index(q) for q in self.qubits]) + \ list([qubits.index(q) + N for q in self.qubits]) tensor = bk.tensormul(self.tensor, rho.tensor, indices) return Density(tensor, qubits, rho.memory)
[ "def", "evolve", "(", "self", ",", "rho", ":", "Density", ")", "->", "Density", ":", "N", "=", "rho", ".", "qubit_nb", "qubits", "=", "rho", ".", "qubits", "indices", "=", "list", "(", "[", "qubits", ".", "index", "(", "q", ")", "for", "q", "in", "self", ".", "qubits", "]", ")", "+", "list", "(", "[", "qubits", ".", "index", "(", "q", ")", "+", "N", "for", "q", "in", "self", ".", "qubits", "]", ")", "tensor", "=", "bk", ".", "tensormul", "(", "self", ".", "tensor", ",", "rho", ".", "tensor", ",", "indices", ")", "return", "Density", "(", "tensor", ",", "qubits", ",", "rho", ".", "memory", ")" ]
Apply the action of this channel upon a density
[ "Apply", "the", "action", "of", "this", "channel", "upon", "a", "density" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L354-L363
248,685
rigetti/quantumflow
quantumflow/backend/eagerbk.py
fcast
def fcast(value: float) -> TensorLike: """Cast to float tensor""" newvalue = tf.cast(value, FTYPE) if DEVICE == 'gpu': newvalue = newvalue.gpu() # Why is this needed? # pragma: no cover return newvalue
python
def fcast(value: float) -> TensorLike: newvalue = tf.cast(value, FTYPE) if DEVICE == 'gpu': newvalue = newvalue.gpu() # Why is this needed? # pragma: no cover return newvalue
[ "def", "fcast", "(", "value", ":", "float", ")", "->", "TensorLike", ":", "newvalue", "=", "tf", ".", "cast", "(", "value", ",", "FTYPE", ")", "if", "DEVICE", "==", "'gpu'", ":", "newvalue", "=", "newvalue", ".", "gpu", "(", ")", "# Why is this needed? # pragma: no cover", "return", "newvalue" ]
Cast to float tensor
[ "Cast", "to", "float", "tensor" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/eagerbk.py#L52-L57
248,686
rigetti/quantumflow
quantumflow/backend/eagerbk.py
astensor
def astensor(array: TensorLike) -> BKTensor: """Convert to product tensor""" tensor = tf.convert_to_tensor(array, dtype=CTYPE) if DEVICE == 'gpu': tensor = tensor.gpu() # pragma: no cover # size = np.prod(np.array(tensor.get_shape().as_list())) N = int(math.log2(size(tensor))) tensor = tf.reshape(tensor, ([2]*N)) return tensor
python
def astensor(array: TensorLike) -> BKTensor: tensor = tf.convert_to_tensor(array, dtype=CTYPE) if DEVICE == 'gpu': tensor = tensor.gpu() # pragma: no cover # size = np.prod(np.array(tensor.get_shape().as_list())) N = int(math.log2(size(tensor))) tensor = tf.reshape(tensor, ([2]*N)) return tensor
[ "def", "astensor", "(", "array", ":", "TensorLike", ")", "->", "BKTensor", ":", "tensor", "=", "tf", ".", "convert_to_tensor", "(", "array", ",", "dtype", "=", "CTYPE", ")", "if", "DEVICE", "==", "'gpu'", ":", "tensor", "=", "tensor", ".", "gpu", "(", ")", "# pragma: no cover", "# size = np.prod(np.array(tensor.get_shape().as_list()))", "N", "=", "int", "(", "math", ".", "log2", "(", "size", "(", "tensor", ")", ")", ")", "tensor", "=", "tf", ".", "reshape", "(", "tensor", ",", "(", "[", "2", "]", "*", "N", ")", ")", "return", "tensor" ]
Convert to product tensor
[ "Convert", "to", "product", "tensor" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/eagerbk.py#L60-L70
248,687
rigetti/quantumflow
quantumflow/circuits.py
count_operations
def count_operations(elements: Iterable[Operation]) \ -> Dict[Type[Operation], int]: """Return a count of different operation types given a colelction of operations, such as a Circuit or DAGCircuit """ op_count: Dict[Type[Operation], int] = defaultdict(int) for elem in elements: op_count[type(elem)] += 1 return dict(op_count)
python
def count_operations(elements: Iterable[Operation]) \ -> Dict[Type[Operation], int]: op_count: Dict[Type[Operation], int] = defaultdict(int) for elem in elements: op_count[type(elem)] += 1 return dict(op_count)
[ "def", "count_operations", "(", "elements", ":", "Iterable", "[", "Operation", "]", ")", "->", "Dict", "[", "Type", "[", "Operation", "]", ",", "int", "]", ":", "op_count", ":", "Dict", "[", "Type", "[", "Operation", "]", ",", "int", "]", "=", "defaultdict", "(", "int", ")", "for", "elem", "in", "elements", ":", "op_count", "[", "type", "(", "elem", ")", "]", "+=", "1", "return", "dict", "(", "op_count", ")" ]
Return a count of different operation types given a colelction of operations, such as a Circuit or DAGCircuit
[ "Return", "a", "count", "of", "different", "operation", "types", "given", "a", "colelction", "of", "operations", "such", "as", "a", "Circuit", "or", "DAGCircuit" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L141-L149
248,688
rigetti/quantumflow
quantumflow/circuits.py
map_gate
def map_gate(gate: Gate, args: Sequence[Qubits]) -> Circuit: """Applies the same gate all input qubits in the argument list. >>> circ = qf.map_gate(qf.H(), [[0], [1], [2]]) >>> print(circ) H(0) H(1) H(2) """ circ = Circuit() for qubits in args: circ += gate.relabel(qubits) return circ
python
def map_gate(gate: Gate, args: Sequence[Qubits]) -> Circuit: circ = Circuit() for qubits in args: circ += gate.relabel(qubits) return circ
[ "def", "map_gate", "(", "gate", ":", "Gate", ",", "args", ":", "Sequence", "[", "Qubits", "]", ")", "->", "Circuit", ":", "circ", "=", "Circuit", "(", ")", "for", "qubits", "in", "args", ":", "circ", "+=", "gate", ".", "relabel", "(", "qubits", ")", "return", "circ" ]
Applies the same gate all input qubits in the argument list. >>> circ = qf.map_gate(qf.H(), [[0], [1], [2]]) >>> print(circ) H(0) H(1) H(2)
[ "Applies", "the", "same", "gate", "all", "input", "qubits", "in", "the", "argument", "list", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L152-L167
248,689
rigetti/quantumflow
quantumflow/circuits.py
qft_circuit
def qft_circuit(qubits: Qubits) -> Circuit: """Returns the Quantum Fourier Transform circuit""" # Kudos: Adapted from Rigetti Grove, grove/qft/fourier.py N = len(qubits) circ = Circuit() for n0 in range(N): q0 = qubits[n0] circ += H(q0) for n1 in range(n0+1, N): q1 = qubits[n1] angle = pi / 2 ** (n1-n0) circ += CPHASE(angle, q1, q0) circ.extend(reversal_circuit(qubits)) return circ
python
def qft_circuit(qubits: Qubits) -> Circuit: # Kudos: Adapted from Rigetti Grove, grove/qft/fourier.py N = len(qubits) circ = Circuit() for n0 in range(N): q0 = qubits[n0] circ += H(q0) for n1 in range(n0+1, N): q1 = qubits[n1] angle = pi / 2 ** (n1-n0) circ += CPHASE(angle, q1, q0) circ.extend(reversal_circuit(qubits)) return circ
[ "def", "qft_circuit", "(", "qubits", ":", "Qubits", ")", "->", "Circuit", ":", "# Kudos: Adapted from Rigetti Grove, grove/qft/fourier.py", "N", "=", "len", "(", "qubits", ")", "circ", "=", "Circuit", "(", ")", "for", "n0", "in", "range", "(", "N", ")", ":", "q0", "=", "qubits", "[", "n0", "]", "circ", "+=", "H", "(", "q0", ")", "for", "n1", "in", "range", "(", "n0", "+", "1", ",", "N", ")", ":", "q1", "=", "qubits", "[", "n1", "]", "angle", "=", "pi", "/", "2", "**", "(", "n1", "-", "n0", ")", "circ", "+=", "CPHASE", "(", "angle", ",", "q1", ",", "q0", ")", "circ", ".", "extend", "(", "reversal_circuit", "(", "qubits", ")", ")", "return", "circ" ]
Returns the Quantum Fourier Transform circuit
[ "Returns", "the", "Quantum", "Fourier", "Transform", "circuit" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L170-L184
248,690
rigetti/quantumflow
quantumflow/circuits.py
reversal_circuit
def reversal_circuit(qubits: Qubits) -> Circuit: """Returns a circuit to reverse qubits""" N = len(qubits) circ = Circuit() for n in range(N // 2): circ += SWAP(qubits[n], qubits[N-1-n]) return circ
python
def reversal_circuit(qubits: Qubits) -> Circuit: N = len(qubits) circ = Circuit() for n in range(N // 2): circ += SWAP(qubits[n], qubits[N-1-n]) return circ
[ "def", "reversal_circuit", "(", "qubits", ":", "Qubits", ")", "->", "Circuit", ":", "N", "=", "len", "(", "qubits", ")", "circ", "=", "Circuit", "(", ")", "for", "n", "in", "range", "(", "N", "//", "2", ")", ":", "circ", "+=", "SWAP", "(", "qubits", "[", "n", "]", ",", "qubits", "[", "N", "-", "1", "-", "n", "]", ")", "return", "circ" ]
Returns a circuit to reverse qubits
[ "Returns", "a", "circuit", "to", "reverse", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L187-L193
248,691
rigetti/quantumflow
quantumflow/circuits.py
zyz_circuit
def zyz_circuit(t0: float, t1: float, t2: float, q0: Qubit) -> Circuit: """Circuit equivalent of 1-qubit ZYZ gate""" circ = Circuit() circ += TZ(t0, q0) circ += TY(t1, q0) circ += TZ(t2, q0) return circ
python
def zyz_circuit(t0: float, t1: float, t2: float, q0: Qubit) -> Circuit: circ = Circuit() circ += TZ(t0, q0) circ += TY(t1, q0) circ += TZ(t2, q0) return circ
[ "def", "zyz_circuit", "(", "t0", ":", "float", ",", "t1", ":", "float", ",", "t2", ":", "float", ",", "q0", ":", "Qubit", ")", "->", "Circuit", ":", "circ", "=", "Circuit", "(", ")", "circ", "+=", "TZ", "(", "t0", ",", "q0", ")", "circ", "+=", "TY", "(", "t1", ",", "q0", ")", "circ", "+=", "TZ", "(", "t2", ",", "q0", ")", "return", "circ" ]
Circuit equivalent of 1-qubit ZYZ gate
[ "Circuit", "equivalent", "of", "1", "-", "qubit", "ZYZ", "gate" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L260-L266
248,692
rigetti/quantumflow
quantumflow/circuits.py
phase_estimation_circuit
def phase_estimation_circuit(gate: Gate, outputs: Qubits) -> Circuit: """Returns a circuit for quantum phase estimation. The gate has an eigenvector with eigenvalue e^(i 2 pi phase). To run the circuit, the eigenvector should be set on the gate qubits, and the output qubits should be in the zero state. After evolution and measurement, the output qubits will be (approximately) a binary fraction representation of the phase. The output registers can be converted with the aid of the quantumflow.utils.bitlist_to_int() method. >>> import numpy as np >>> import quantumflow as qf >>> N = 8 >>> phase = 1/4 >>> gate = qf.RZ(-4*np.pi*phase, N) >>> circ = qf.phase_estimation_circuit(gate, range(N)) >>> res = circ.run().measure()[0:N] >>> est_phase = int(''.join([str(d) for d in res]), 2) / 2**N # To float >>> print(phase, est_phase) 0.25 0.25 """ circ = Circuit() circ += map_gate(H(), list(zip(outputs))) # Hadamard on all output qubits for cq in reversed(outputs): cgate = control_gate(cq, gate) circ += cgate gate = gate @ gate circ += qft_circuit(outputs).H return circ
python
def phase_estimation_circuit(gate: Gate, outputs: Qubits) -> Circuit: circ = Circuit() circ += map_gate(H(), list(zip(outputs))) # Hadamard on all output qubits for cq in reversed(outputs): cgate = control_gate(cq, gate) circ += cgate gate = gate @ gate circ += qft_circuit(outputs).H return circ
[ "def", "phase_estimation_circuit", "(", "gate", ":", "Gate", ",", "outputs", ":", "Qubits", ")", "->", "Circuit", ":", "circ", "=", "Circuit", "(", ")", "circ", "+=", "map_gate", "(", "H", "(", ")", ",", "list", "(", "zip", "(", "outputs", ")", ")", ")", "# Hadamard on all output qubits", "for", "cq", "in", "reversed", "(", "outputs", ")", ":", "cgate", "=", "control_gate", "(", "cq", ",", "gate", ")", "circ", "+=", "cgate", "gate", "=", "gate", "@", "gate", "circ", "+=", "qft_circuit", "(", "outputs", ")", ".", "H", "return", "circ" ]
Returns a circuit for quantum phase estimation. The gate has an eigenvector with eigenvalue e^(i 2 pi phase). To run the circuit, the eigenvector should be set on the gate qubits, and the output qubits should be in the zero state. After evolution and measurement, the output qubits will be (approximately) a binary fraction representation of the phase. The output registers can be converted with the aid of the quantumflow.utils.bitlist_to_int() method. >>> import numpy as np >>> import quantumflow as qf >>> N = 8 >>> phase = 1/4 >>> gate = qf.RZ(-4*np.pi*phase, N) >>> circ = qf.phase_estimation_circuit(gate, range(N)) >>> res = circ.run().measure()[0:N] >>> est_phase = int(''.join([str(d) for d in res]), 2) / 2**N # To float >>> print(phase, est_phase) 0.25 0.25
[ "Returns", "a", "circuit", "for", "quantum", "phase", "estimation", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L269-L303
248,693
rigetti/quantumflow
quantumflow/circuits.py
ghz_circuit
def ghz_circuit(qubits: Qubits) -> Circuit: """Returns a circuit that prepares a multi-qubit Bell state from the zero state. """ circ = Circuit() circ += H(qubits[0]) for q0 in range(0, len(qubits)-1): circ += CNOT(qubits[q0], qubits[q0+1]) return circ
python
def ghz_circuit(qubits: Qubits) -> Circuit: circ = Circuit() circ += H(qubits[0]) for q0 in range(0, len(qubits)-1): circ += CNOT(qubits[q0], qubits[q0+1]) return circ
[ "def", "ghz_circuit", "(", "qubits", ":", "Qubits", ")", "->", "Circuit", ":", "circ", "=", "Circuit", "(", ")", "circ", "+=", "H", "(", "qubits", "[", "0", "]", ")", "for", "q0", "in", "range", "(", "0", ",", "len", "(", "qubits", ")", "-", "1", ")", ":", "circ", "+=", "CNOT", "(", "qubits", "[", "q0", "]", ",", "qubits", "[", "q0", "+", "1", "]", ")", "return", "circ" ]
Returns a circuit that prepares a multi-qubit Bell state from the zero state.
[ "Returns", "a", "circuit", "that", "prepares", "a", "multi", "-", "qubit", "Bell", "state", "from", "the", "zero", "state", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L359-L369
248,694
rigetti/quantumflow
quantumflow/circuits.py
Circuit.extend
def extend(self, other: Operation) -> None: """Append gates from circuit to the end of this circuit""" if isinstance(other, Circuit): self.elements.extend(other.elements) else: self.elements.extend([other])
python
def extend(self, other: Operation) -> None: if isinstance(other, Circuit): self.elements.extend(other.elements) else: self.elements.extend([other])
[ "def", "extend", "(", "self", ",", "other", ":", "Operation", ")", "->", "None", ":", "if", "isinstance", "(", "other", ",", "Circuit", ")", ":", "self", ".", "elements", ".", "extend", "(", "other", ".", "elements", ")", "else", ":", "self", ".", "elements", ".", "extend", "(", "[", "other", "]", ")" ]
Append gates from circuit to the end of this circuit
[ "Append", "gates", "from", "circuit", "to", "the", "end", "of", "this", "circuit" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L53-L58
248,695
rigetti/quantumflow
quantumflow/circuits.py
Circuit.run
def run(self, ket: State = None) -> State: """ Apply the action of this circuit upon a state. If no initial state provided an initial zero state will be created. """ if ket is None: qubits = self.qubits ket = zero_state(qubits=qubits) for elem in self.elements: ket = elem.run(ket) return ket
python
def run(self, ket: State = None) -> State: if ket is None: qubits = self.qubits ket = zero_state(qubits=qubits) for elem in self.elements: ket = elem.run(ket) return ket
[ "def", "run", "(", "self", ",", "ket", ":", "State", "=", "None", ")", "->", "State", ":", "if", "ket", "is", "None", ":", "qubits", "=", "self", ".", "qubits", "ket", "=", "zero_state", "(", "qubits", "=", "qubits", ")", "for", "elem", "in", "self", ".", "elements", ":", "ket", "=", "elem", ".", "run", "(", "ket", ")", "return", "ket" ]
Apply the action of this circuit upon a state. If no initial state provided an initial zero state will be created.
[ "Apply", "the", "action", "of", "this", "circuit", "upon", "a", "state", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L87-L99
248,696
rigetti/quantumflow
quantumflow/circuits.py
Circuit.asgate
def asgate(self) -> Gate: """ Return the action of this circuit as a gate """ gate = identity_gate(self.qubits) for elem in self.elements: gate = elem.asgate() @ gate return gate
python
def asgate(self) -> Gate: gate = identity_gate(self.qubits) for elem in self.elements: gate = elem.asgate() @ gate return gate
[ "def", "asgate", "(", "self", ")", "->", "Gate", ":", "gate", "=", "identity_gate", "(", "self", ".", "qubits", ")", "for", "elem", "in", "self", ".", "elements", ":", "gate", "=", "elem", ".", "asgate", "(", ")", "@", "gate", "return", "gate" ]
Return the action of this circuit as a gate
[ "Return", "the", "action", "of", "this", "circuit", "as", "a", "gate" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L111-L118
248,697
rigetti/quantumflow
quantumflow/channels.py
join_channels
def join_channels(*channels: Channel) -> Channel: """Join two channels acting on different qubits into a single channel acting on all qubits""" vectors = [chan.vec for chan in channels] vec = reduce(outer_product, vectors) return Channel(vec.tensor, vec.qubits)
python
def join_channels(*channels: Channel) -> Channel: vectors = [chan.vec for chan in channels] vec = reduce(outer_product, vectors) return Channel(vec.tensor, vec.qubits)
[ "def", "join_channels", "(", "*", "channels", ":", "Channel", ")", "->", "Channel", ":", "vectors", "=", "[", "chan", ".", "vec", "for", "chan", "in", "channels", "]", "vec", "=", "reduce", "(", "outer_product", ",", "vectors", ")", "return", "Channel", "(", "vec", ".", "tensor", ",", "vec", ".", "qubits", ")" ]
Join two channels acting on different qubits into a single channel acting on all qubits
[ "Join", "two", "channels", "acting", "on", "different", "qubits", "into", "a", "single", "channel", "acting", "on", "all", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L170-L175
248,698
rigetti/quantumflow
quantumflow/channels.py
channel_to_kraus
def channel_to_kraus(chan: Channel) -> 'Kraus': """Convert a channel superoperator into a Kraus operator representation of the same channel.""" qubits = chan.qubits N = chan.qubit_nb choi = asarray(chan.choi()) evals, evecs = np.linalg.eig(choi) evecs = np.transpose(evecs) assert np.allclose(evals.imag, 0.0) # FIXME exception assert np.all(evals.real >= 0.0) # FIXME exception values = np.sqrt(evals.real) ops = [] for i in range(2**(2*N)): if not np.isclose(values[i], 0.0): mat = np.reshape(evecs[i], (2**N, 2**N))*values[i] g = Gate(mat, qubits) ops.append(g) return Kraus(ops)
python
def channel_to_kraus(chan: Channel) -> 'Kraus': qubits = chan.qubits N = chan.qubit_nb choi = asarray(chan.choi()) evals, evecs = np.linalg.eig(choi) evecs = np.transpose(evecs) assert np.allclose(evals.imag, 0.0) # FIXME exception assert np.all(evals.real >= 0.0) # FIXME exception values = np.sqrt(evals.real) ops = [] for i in range(2**(2*N)): if not np.isclose(values[i], 0.0): mat = np.reshape(evecs[i], (2**N, 2**N))*values[i] g = Gate(mat, qubits) ops.append(g) return Kraus(ops)
[ "def", "channel_to_kraus", "(", "chan", ":", "Channel", ")", "->", "'Kraus'", ":", "qubits", "=", "chan", ".", "qubits", "N", "=", "chan", ".", "qubit_nb", "choi", "=", "asarray", "(", "chan", ".", "choi", "(", ")", ")", "evals", ",", "evecs", "=", "np", ".", "linalg", ".", "eig", "(", "choi", ")", "evecs", "=", "np", ".", "transpose", "(", "evecs", ")", "assert", "np", ".", "allclose", "(", "evals", ".", "imag", ",", "0.0", ")", "# FIXME exception", "assert", "np", ".", "all", "(", "evals", ".", "real", ">=", "0.0", ")", "# FIXME exception", "values", "=", "np", ".", "sqrt", "(", "evals", ".", "real", ")", "ops", "=", "[", "]", "for", "i", "in", "range", "(", "2", "**", "(", "2", "*", "N", ")", ")", ":", "if", "not", "np", ".", "isclose", "(", "values", "[", "i", "]", ",", "0.0", ")", ":", "mat", "=", "np", ".", "reshape", "(", "evecs", "[", "i", "]", ",", "(", "2", "**", "N", ",", "2", "**", "N", ")", ")", "*", "values", "[", "i", "]", "g", "=", "Gate", "(", "mat", ",", "qubits", ")", "ops", ".", "append", "(", "g", ")", "return", "Kraus", "(", "ops", ")" ]
Convert a channel superoperator into a Kraus operator representation of the same channel.
[ "Convert", "a", "channel", "superoperator", "into", "a", "Kraus", "operator", "representation", "of", "the", "same", "channel", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L181-L203
248,699
rigetti/quantumflow
quantumflow/channels.py
Kraus.run
def run(self, ket: State) -> State: """Apply the action of this Kraus quantum operation upon a state""" res = [op.run(ket) for op in self.operators] probs = [asarray(ket.norm()) * w for ket, w in zip(res, self.weights)] probs = np.asarray(probs) probs /= np.sum(probs) newket = np.random.choice(res, p=probs) return newket.normalize()
python
def run(self, ket: State) -> State: res = [op.run(ket) for op in self.operators] probs = [asarray(ket.norm()) * w for ket, w in zip(res, self.weights)] probs = np.asarray(probs) probs /= np.sum(probs) newket = np.random.choice(res, p=probs) return newket.normalize()
[ "def", "run", "(", "self", ",", "ket", ":", "State", ")", "->", "State", ":", "res", "=", "[", "op", ".", "run", "(", "ket", ")", "for", "op", "in", "self", ".", "operators", "]", "probs", "=", "[", "asarray", "(", "ket", ".", "norm", "(", ")", ")", "*", "w", "for", "ket", ",", "w", "in", "zip", "(", "res", ",", "self", ".", "weights", ")", "]", "probs", "=", "np", ".", "asarray", "(", "probs", ")", "probs", "/=", "np", ".", "sum", "(", "probs", ")", "newket", "=", "np", ".", "random", ".", "choice", "(", "res", ",", "p", "=", "probs", ")", "return", "newket", ".", "normalize", "(", ")" ]
Apply the action of this Kraus quantum operation upon a state
[ "Apply", "the", "action", "of", "this", "Kraus", "quantum", "operation", "upon", "a", "state" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L70-L77