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
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
234,800
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: """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)
[ "def", "print_state", "(", "state", ":", "State", ",", "file", ":", "TextIO", "=", "None", ")", "->", "None", ":", "state", "=", "state", ".", "vec", ".", "asarray", "(", ")", "for", "index", ",", "amplitude", "in", "np", ".", "ndenumerate", "(", "...
Print a state vector
[ "Print", "a", "state", "vector" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L234-L239
234,801
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.probab...
python
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.probab...
[ "def", "print_probabilities", "(", "state", ":", "State", ",", "ndigits", ":", "int", "=", "4", ",", "file", ":", "TextIO", "=", "None", ")", "->", "None", ":", "prob", "=", "bk", ".", "evaluate", "(", "state", ".", "probabilities", "(", ")", ")", ...
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
234,802
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: """Returns the completely mixed density matrix""" 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", ...
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
234,803
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: """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...
[ "def", "join_densities", "(", "*", "densities", ":", "Density", ")", "->", "Density", ":", "vectors", "=", "[", "rho", ".", "vec", "for", "rho", "in", "densities", "]", "vec", "=", "reduce", "(", "outer_product", ",", "vectors", ")", "memory", "=", "di...
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
234,804
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': """Normalize the 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", ".", ...
Normalize the state
[ "Normalize", "the", "state" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L108-L111
234,805
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())) r...
python
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())) r...
[ "def", "sample", "(", "self", ",", "trials", ":", "int", ")", "->", "np", ".", "ndarray", ":", "# TODO: Can we do this within backend?", "probs", "=", "np", ".", "real", "(", "bk", ".", "evaluate", "(", "self", ".", "probabilities", "(", ")", ")", ")", ...
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
234,806
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...
python
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...
[ "def", "expectation", "(", "self", ",", "diag_hermitian", ":", "bk", ".", "TensorLike", ",", "trials", ":", "int", "=", "None", ")", "->", "bk", ".", "BKTensor", ":", "if", "trials", "is", "None", ":", "probs", "=", "self", ".", "probabilities", "(", ...
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...
[ "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
234,807
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(...
python
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(...
[ "def", "measure", "(", "self", ")", "->", "np", ".", "ndarray", ":", "# TODO: Can we do this within backend?", "probs", "=", "np", ".", "real", "(", "bk", ".", "evaluate", "(", "self", ".", "probabilities", "(", ")", ")", ")", "indices", "=", "np", ".", ...
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
234,808
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': """Convert a pure state to a density matrix""" 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...
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
234,809
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...
python
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...
[ "def", "benchmark", "(", "N", ",", "gates", ")", ":", "qubits", "=", "list", "(", "range", "(", "0", ",", "N", ")", ")", "ket", "=", "qf", ".", "zero_state", "(", "N", ")", "for", "n", "in", "range", "(", "0", ",", "N", ")", ":", "ket", "="...
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
234,810
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]) c...
python
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]) c...
[ "def", "sandwich_decompositions", "(", "coords0", ",", "coords1", ",", "samples", "=", "SAMPLES", ")", ":", "decomps", "=", "[", "]", "for", "_", "in", "range", "(", "samples", ")", ":", "circ", "=", "qf", ".", "Circuit", "(", ")", "circ", "+=", "qf"...
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
234,811
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 the Pauli sigma_X operator acting on the given qubit""" 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
234,812
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 the Pauli sigma_Y operator acting on the given qubit""" 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
234,813
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 the Pauli sigma_Z operator acting on the given qubit""" 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
234,814
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, c...
python
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, c...
[ "def", "pauli_sum", "(", "*", "elements", ":", "Pauli", ")", "->", "Pauli", ":", "terms", "=", "[", "]", "key", "=", "itemgetter", "(", "0", ")", "for", "term", ",", "grp", "in", "groupby", "(", "heapq", ".", "merge", "(", "*", "elements", ",", "...
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
234,815
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) ...
python
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) ...
[ "def", "pauli_product", "(", "*", "elements", ":", "Pauli", ")", "->", "Pauli", ":", "result_terms", "=", "[", "]", "for", "terms", "in", "product", "(", "*", "elements", ")", ":", "coeff", "=", "reduce", "(", "mul", ",", "[", "term", "[", "1", "]"...
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
234,816
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.iden...
python
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.iden...
[ "def", "pauli_pow", "(", "pauli", ":", "Pauli", ",", "exponent", ":", "int", ")", "->", "Pauli", ":", "if", "not", "isinstance", "(", "exponent", ",", "int", ")", "or", "exponent", "<", "0", ":", "raise", "ValueError", "(", "\"The exponent must be a non-ne...
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
234,817
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(ele...
python
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(ele...
[ "def", "pauli_commuting_sets", "(", "element", ":", "Pauli", ")", "->", "Tuple", "[", "Pauli", ",", "...", "]", ":", "if", "len", "(", "element", ")", "<", "2", ":", "return", "(", "element", ",", ")", "groups", ":", "List", "[", "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
[ "Gather", "the", "terms", "of", "a", "Pauli", "polynomial", "into", "commuting", "sets", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/paulialgebra.py#L348-L372
234,818
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: """Converts a numpy array to the backend's tensor object """ 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
234,819
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: """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
[ "def", "productdiag", "(", "tensor", ":", "BKTensor", ")", "->", "BKTensor", ":", "# DOCME: Explain", "N", "=", "rank", "(", "tensor", ")", "tensor", "=", "reshape", "(", "tensor", ",", "[", "2", "**", "(", "N", "//", "2", ")", ",", "2", "**", "(",...
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
234,820
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...
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...
[ "def", "tensormul", "(", "tensor0", ":", "BKTensor", ",", "tensor1", ":", "BKTensor", ",", "indices", ":", "typing", ".", "List", "[", "int", "]", ")", "->", "BKTensor", ":", "# Note: This method is the critical computational core of QuantumFlow", "# We currently have...
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 ...
[ "r", "Generalization", "of", "matrix", "multiplication", "to", "product", "tensors", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/numpybk.py#L159-L214
234,821
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,...
python
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,...
[ "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", "(", ...
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
234,822
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: """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)
[ "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
234,823
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)) ...
python
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)) ...
[ "def", "int_to_bitlist", "(", "x", ":", "int", ",", "pad", ":", "int", "=", "None", ")", "->", "Sequence", "[", "int", "]", ":", "if", "pad", "is", "None", ":", "form", "=", "'{:0b}'", "else", ":", "form", "=", "'{:0'", "+", "str", "(", "pad", ...
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
234,824
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)) retu...
python
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)) retu...
[ "def", "spanning_tree_count", "(", "graph", ":", "nx", ".", "Graph", ")", "->", "int", ":", "laplacian", "=", "nx", ".", "laplacian_matrix", "(", "graph", ")", ".", "toarray", "(", ")", "comatrix", "=", "laplacian", "[", ":", "-", "1", ",", ":", "-",...
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
234,825
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...
python
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...
[ "def", "rationalize", "(", "flt", ":", "float", ",", "denominators", ":", "Set", "[", "int", "]", "=", "None", ")", "->", "Fraction", ":", "if", "denominators", "is", "None", ":", "denominators", "=", "_DENOMINATORS", "frac", "=", "Fraction", ".", "from_...
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 ...
[ "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
234,826
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...
python
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...
[ "def", "symbolize", "(", "flt", ":", "float", ")", "->", "sympy", ".", "Symbol", ":", "try", ":", "ratio", "=", "rationalize", "(", "flt", ")", "res", "=", "sympy", ".", "simplify", "(", "ratio", ")", "except", "ValueError", ":", "ratio", "=", "ratio...
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
234,827
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 """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
[ "def", "pyquil_to_image", "(", "program", ":", "pyquil", ".", "Program", ")", "->", "PIL", ".", "Image", ":", "# pragma: no cover", "circ", "=", "pyquil_to_circuit", "(", "program", ")", "latex", "=", "circuit_to_latex", "(", "circ", ")", "img", "=", "render...
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
234,828
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 [] ...
python
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 [] ...
[ "def", "circuit_to_pyquil", "(", "circuit", ":", "Circuit", ")", "->", "pyquil", ".", "Program", ":", "prog", "=", "pyquil", ".", "Program", "(", ")", "for", "elem", "in", "circuit", ".", "elements", ":", "if", "isinstance", "(", "elem", ",", "Gate", "...
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
234,829
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 isinst...
python
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 isinst...
[ "def", "pyquil_to_circuit", "(", "program", ":", "pyquil", ".", "Program", ")", "->", "Circuit", ":", "circ", "=", "Circuit", "(", ")", "for", "inst", "in", "program", ".", "instructions", ":", "# print(type(inst))", "if", "isinstance", "(", "inst", ",", "...
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
234,830
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: """Parse a quil program and return a Program object""" 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
234,831
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]) ...
python
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]) ...
[ "def", "state_to_wavefunction", "(", "state", ":", "State", ")", "->", "pyquil", ".", "Wavefunction", ":", "# TODO: qubits?", "amplitudes", "=", "state", ".", "vec", ".", "asarray", "(", ")", "# pyQuil labels states backwards.", "amplitudes", "=", "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
234,832
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._pr...
python
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._pr...
[ "def", "load", "(", "self", ",", "binary", ":", "pyquil", ".", "Program", ")", "->", "'QuantumFlowQVM'", ":", "assert", "self", ".", "status", "in", "[", "'connected'", ",", "'done'", "]", "prog", "=", "quil_to_program", "(", "str", "(", "binary", ")", ...
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
234,833
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 ...
python
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 ...
[ "def", "run", "(", "self", ")", "->", "'QuantumFlowQVM'", ":", "assert", "self", ".", "status", "in", "[", "'loaded'", "]", "self", ".", "status", "=", "'running'", "self", ".", "_ket", "=", "self", ".", "_prog", ".", "run", "(", ")", "# Should set sta...
Run a previously loaded program
[ "Run", "a", "previously", "loaded", "program" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L401-L410
234,834
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: """ 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
[ "def", "wavefunction", "(", "self", ")", "->", "pyquil", ".", "Wavefunction", ":", "assert", "self", ".", "status", "==", "'done'", "assert", "self", ".", "_ket", "is", "not", "None", "wavefn", "=", "state_to_wavefunction", "(", "self", ".", "_ket", ")", ...
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
234,835
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...
python
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...
[ "def", "evaluate", "(", "tensor", ":", "BKTensor", ")", "->", "TensorLike", ":", "if", "isinstance", "(", "tensor", ",", "_DTYPE", ")", ":", "if", "torch", ".", "numel", "(", "tensor", ")", "==", "1", ":", "return", "tensor", ".", "item", "(", ")", ...
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
234,836
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: """Return the number of dimensions of a tensor""" 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", "]", ".", "...
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
234,837
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: """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
[ "def", "state_fidelity", "(", "state0", ":", "State", ",", "state1", ":", "State", ")", "->", "bk", ".", "BKTensor", ":", "assert", "state0", ".", "qubits", "==", "state1", ".", "qubits", "# FIXME", "tensor", "=", "bk", ".", "absolute", "(", "bk", ".",...
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
234,838
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: """The Fubini-Study angle between states. Equal to the Burrs angle for pure states. """ 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
234,839
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: """Returns True if states are almost identical. Closeness is measured with the metric Fubini-Study angle. """ 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
234,840
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 ...
python
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 ...
[ "def", "purity", "(", "rho", ":", "Density", ")", "->", "bk", ".", "BKTensor", ":", "tensor", "=", "rho", ".", "tensor", "N", "=", "rho", ".", "qubit_nb", "matrix", "=", "bk", ".", "reshape", "(", "tensor", ",", "[", "2", "**", "N", ",", "2", "...
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 participat...
[ "Calculate", "the", "purity", "of", "a", "mixed", "quantum", "state", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L59-L73
234,841
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...
python
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...
[ "def", "bures_distance", "(", "rho0", ":", "Density", ",", "rho1", ":", "Density", ")", "->", "float", ":", "fid", "=", "fidelity", "(", "rho0", ",", "rho1", ")", "op0", "=", "asarray", "(", "rho0", ".", "asoperator", "(", ")", ")", "op1", "=", "as...
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
234,842
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 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)))
[ "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
234,843
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: """The Fubini-Study angle between density matrices""" 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
234,844
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: """Returns True if densities are almost identical. Closeness is measured with the metric Fubini-Study angle. """ 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
234,845
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: ...
python
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: ...
[ "def", "entropy", "(", "rho", ":", "Density", ",", "base", ":", "float", "=", "None", ")", "->", "float", ":", "op", "=", "asarray", "(", "rho", ".", "asoperator", "(", ")", ")", "probs", "=", "np", ".", "linalg", ".", "eigvalsh", "(", "op", ")",...
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
234,846
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 qubits...
python
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 qubits...
[ "def", "mutual_info", "(", "rho", ":", "Density", ",", "qubits0", ":", "Qubits", ",", "qubits1", ":", "Qubits", "=", "None", ",", "base", ":", "float", "=", "None", ")", "->", "float", ":", "if", "qubits1", "is", "None", ":", "qubits1", "=", "tuple",...
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 bas...
[ "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
234,847
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: """The Fubini-Study angle between gates""" 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
234,848
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: """The Fubini-Study angle between channels""" 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
234,849
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 ma...
python
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 ma...
[ "def", "inner_product", "(", "vec0", ":", "QubitVector", ",", "vec1", ":", "QubitVector", ")", "->", "bk", ".", "BKTensor", ":", "if", "vec0", ".", "rank", "!=", "vec1", ".", "rank", "or", "vec0", ".", "qubit_nb", "!=", "vec1", ".", "qubit_nb", ":", ...
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
234,850
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...
python
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...
[ "def", "outer_product", "(", "vec0", ":", "QubitVector", ",", "vec1", ":", "QubitVector", ")", "->", "QubitVector", ":", "R", "=", "vec0", ".", "rank", "R1", "=", "vec1", ".", "rank", "N0", "=", "vec0", ".", "qubit_nb", "N1", "=", "vec1", ".", "qubit...
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
234,851
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.qubi...
python
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.qubi...
[ "def", "vectors_close", "(", "vec0", ":", "QubitVector", ",", "vec1", ":", "QubitVector", ",", "tolerance", ":", "float", "=", "TOLERANCE", ")", "->", "bool", ":", "if", "vec0", ".", "rank", "!=", "vec1", ".", "rank", ":", "return", "False", "if", "vec...
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
234,852
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: """Return tensor with with qubit indices flattened""" 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
234,853
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': """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
[ "def", "relabel", "(", "self", ",", "qubits", ":", "Qubits", ")", "->", "'QubitVector'", ":", "qubits", "=", "tuple", "(", "qubits", ")", "assert", "len", "(", "qubits", ")", "==", "self", ".", "qubit_nb", "vec", "=", "copy", "(", "self", ")", "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
234,854
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.r...
python
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.r...
[ "def", "H", "(", "self", ")", "->", "'QubitVector'", ":", "N", "=", "self", ".", "qubit_nb", "R", "=", "self", ".", "rank", "# (super) operator transpose", "tensor", "=", "self", ".", "tensor", "tensor", "=", "bk", ".", "reshape", "(", "tensor", ",", "...
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
234,855
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 the norm of this vector""" 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
234,856
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) ...
python
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) ...
[ "def", "partial_trace", "(", "self", ",", "qubits", ":", "Qubits", ")", "->", "'QubitVector'", ":", "N", "=", "self", ".", "qubit_nb", "R", "=", "self", ".", "rank", "if", "R", "==", "1", ":", "raise", "ValueError", "(", "'Cannot take trace of vector'", ...
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
234,857
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.r...
python
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.r...
[ "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...
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
234,858
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...
python
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...
[ "def", "run", "(", "self", ",", "ket", ":", "State", "=", "None", ")", "->", "State", ":", "if", "ket", "is", "None", ":", "qubits", "=", "self", ".", "qubits", "ket", "=", "zero_state", "(", "qubits", ")", "ket", "=", "self", ".", "_initilize", ...
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
234,859
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': """Return a copy of this Gate with new qubits""" 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
234,860
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: """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)
[ "def", "run", "(", "self", ",", "ket", ":", "State", ")", "->", "State", ":", "qubits", "=", "self", ".", "qubits", "indices", "=", "[", "ket", ".", "qubits", ".", "index", "(", "q", ")", "for", "q", "in", "qubits", "]", "tensor", "=", "bk", "....
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
234,861
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: """Apply the action of this gate upon a 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
234,862
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': """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)
[ "def", "aschannel", "(", "self", ")", "->", "'Channel'", ":", "N", "=", "self", ".", "qubit_nb", "R", "=", "4", "tensor", "=", "bk", ".", "outer", "(", "self", ".", "tensor", ",", "self", ".", "H", ".", "tensor", ")", "tensor", "=", "bk", ".", ...
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
234,863
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': """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)
[ "def", "su", "(", "self", ")", "->", "'Gate'", ":", "rank", "=", "2", "**", "self", ".", "qubit_nb", "U", "=", "asarray", "(", "self", ".", "asoperator", "(", ")", ")", "U", "/=", "np", ".", "linalg", ".", "det", "(", "U", ")", "**", "(", "1"...
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
234,864
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': """Return a copy of this channel with new qubits""" 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
234,865
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': """Return a copy of this channel with qubits in new order""" 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
234,866
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 :mat...
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 :mat...
[ "def", "sharp", "(", "self", ")", "->", "'Channel'", ":", "N", "=", "self", ".", "qubit_nb", "tensor", "=", "self", ".", "tensor", "tensor", "=", "bk", ".", "reshape", "(", "tensor", ",", "[", "2", "**", "N", "]", "*", "4", ")", "tensor", "=", ...
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....
[ "r", "Return", "the", "sharp", "transpose", "of", "the", "superoperator", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L315-L335
234,867
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: """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)
[ "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", "**...
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
234,868
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(se...
python
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(se...
[ "def", "evolve", "(", "self", ",", "rho", ":", "Density", ")", "->", "Density", ":", "N", "=", "rho", ".", "qubit_nb", "qubits", "=", "rho", ".", "qubits", "indices", "=", "list", "(", "[", "qubits", ".", "index", "(", "q", ")", "for", "q", "in",...
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
234,869
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: """Cast to float tensor""" 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?...
Cast to float tensor
[ "Cast", "to", "float", "tensor" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/eagerbk.py#L52-L57
234,870
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 =...
python
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 =...
[ "def", "astensor", "(", "array", ":", "TensorLike", ")", "->", "BKTensor", ":", "tensor", "=", "tf", ".", "convert_to_tensor", "(", "array", ",", "dtype", "=", "CTYPE", ")", "if", "DEVICE", "==", "'gpu'", ":", "tensor", "=", "tensor", ".", "gpu", "(", ...
Convert to product tensor
[ "Convert", "to", "product", "tensor" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/eagerbk.py#L60-L70
234,871
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_c...
python
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_c...
[ "def", "count_operations", "(", "elements", ":", "Iterable", "[", "Operation", "]", ")", "->", "Dict", "[", "Type", "[", "Operation", "]", ",", "int", "]", ":", "op_count", ":", "Dict", "[", "Type", "[", "Operation", "]", ",", "int", "]", "=", "defau...
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
234,872
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)...
python
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)...
[ "def", "map_gate", "(", "gate", ":", "Gate", ",", "args", ":", "Sequence", "[", "Qubits", "]", ")", "->", "Circuit", ":", "circ", "=", "Circuit", "(", ")", "for", "qubits", "in", "args", ":", "circ", "+=", "gate", ".", "relabel", "(", "qubits", ")"...
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
234,873
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): ...
python
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): ...
[ "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", ")", ":",...
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
234,874
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: """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
[ "def", "reversal_circuit", "(", "qubits", ":", "Qubits", ")", "->", "Circuit", ":", "N", "=", "len", "(", "qubits", ")", "circ", "=", "Circuit", "(", ")", "for", "n", "in", "range", "(", "N", "//", "2", ")", ":", "circ", "+=", "SWAP", "(", "qubit...
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
234,875
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: """Circuit equivalent of 1-qubit ZYZ gate""" 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", "+=", ...
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
234,876
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....
python
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....
[ "def", "phase_estimation_circuit", "(", "gate", ":", "Gate", ",", "outputs", ":", "Qubits", ")", "->", "Circuit", ":", "circ", "=", "Circuit", "(", ")", "circ", "+=", "map_gate", "(", "H", "(", ")", ",", "list", "(", "zip", "(", "outputs", ")", ")", ...
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 (approximatel...
[ "Returns", "a", "circuit", "for", "quantum", "phase", "estimation", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L269-L303
234,877
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: """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
[ "def", "ghz_circuit", "(", "qubits", ":", "Qubits", ")", "->", "Circuit", ":", "circ", "=", "Circuit", "(", ")", "circ", "+=", "H", "(", "qubits", "[", "0", "]", ")", "for", "q0", "in", "range", "(", "0", ",", "len", "(", "qubits", ")", "-", "1...
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
234,878
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: """Append gates from circuit to the end of this circuit""" 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", ".", ...
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
234,879
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...
python
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...
[ "def", "run", "(", "self", ",", "ket", ":", "State", "=", "None", ")", "->", "State", ":", "if", "ket", "is", "None", ":", "qubits", "=", "self", ".", "qubits", "ket", "=", "zero_state", "(", "qubits", "=", "qubits", ")", "for", "elem", "in", "se...
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
234,880
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: """ 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
[ "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
234,881
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: """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)
[ "def", "join_channels", "(", "*", "channels", ":", "Channel", ")", "->", "Channel", ":", "vectors", "=", "[", "chan", ".", "vec", "for", "chan", "in", "channels", "]", "vec", "=", "reduce", "(", "outer_product", ",", "vectors", ")", "return", "Channel", ...
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
234,882
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.al...
python
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.al...
[ "def", "channel_to_kraus", "(", "chan", ":", "Channel", ")", "->", "'Kraus'", ":", "qubits", "=", "chan", ".", "qubits", "N", "=", "chan", ".", "qubit_nb", "choi", "=", "asarray", "(", "chan", ".", "choi", "(", ")", ")", "evals", ",", "evecs", "=", ...
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
234,883
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) new...
python
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) new...
[ "def", "run", "(", "self", ",", "ket", ":", "State", ")", "->", "State", ":", "res", "=", "[", "op", ".", "run", "(", "ket", ")", "for", "op", "in", "self", ".", "operators", "]", "probs", "=", "[", "asarray", "(", "ket", ".", "norm", "(", ")...
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
234,884
rigetti/quantumflow
quantumflow/channels.py
Kraus.evolve
def evolve(self, rho: Density) -> Density: """Apply the action of this Kraus quantum operation upon a density""" qubits = rho.qubits results = [op.evolve(rho) for op in self.operators] tensors = [rho.tensor * w for rho, w in zip(results, self.weights)] tensor = reduce(add, tensor...
python
def evolve(self, rho: Density) -> Density: """Apply the action of this Kraus quantum operation upon a density""" qubits = rho.qubits results = [op.evolve(rho) for op in self.operators] tensors = [rho.tensor * w for rho, w in zip(results, self.weights)] tensor = reduce(add, tensor...
[ "def", "evolve", "(", "self", ",", "rho", ":", "Density", ")", "->", "Density", ":", "qubits", "=", "rho", ".", "qubits", "results", "=", "[", "op", ".", "evolve", "(", "rho", ")", "for", "op", "in", "self", ".", "operators", "]", "tensors", "=", ...
Apply the action of this Kraus quantum operation upon a density
[ "Apply", "the", "action", "of", "this", "Kraus", "quantum", "operation", "upon", "a", "density" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L79-L85
234,885
rigetti/quantumflow
quantumflow/channels.py
Kraus.H
def H(self) -> 'Kraus': """Return the complex conjugate of this Kraus operation""" operators = [op.H for op in self.operators] return Kraus(operators, self.weights)
python
def H(self) -> 'Kraus': """Return the complex conjugate of this Kraus operation""" operators = [op.H for op in self.operators] return Kraus(operators, self.weights)
[ "def", "H", "(", "self", ")", "->", "'Kraus'", ":", "operators", "=", "[", "op", ".", "H", "for", "op", "in", "self", ".", "operators", "]", "return", "Kraus", "(", "operators", ",", "self", ".", "weights", ")" ]
Return the complex conjugate of this Kraus operation
[ "Return", "the", "complex", "conjugate", "of", "this", "Kraus", "operation" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L103-L106
234,886
rigetti/quantumflow
quantumflow/channels.py
UnitaryMixture.asgate
def asgate(self) -> Gate: """Return one of the composite Kraus operators at random with the appropriate weights""" return np.random.choice(self.operators, p=self.weights)
python
def asgate(self) -> Gate: """Return one of the composite Kraus operators at random with the appropriate weights""" return np.random.choice(self.operators, p=self.weights)
[ "def", "asgate", "(", "self", ")", "->", "Gate", ":", "return", "np", ".", "random", ".", "choice", "(", "self", ".", "operators", ",", "p", "=", "self", ".", "weights", ")" ]
Return one of the composite Kraus operators at random with the appropriate weights
[ "Return", "one", "of", "the", "composite", "Kraus", "operators", "at", "random", "with", "the", "appropriate", "weights" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L119-L122
234,887
rigetti/quantumflow
quantumflow/visualization.py
_display_layers
def _display_layers(circ: Circuit, qubits: Qubits) -> Circuit: """Separate a circuit into groups of gates that do not visually overlap""" N = len(qubits) qubit_idx = dict(zip(qubits, range(N))) gate_layers = DAGCircuit(circ).layers() layers = [] lcirc = Circuit() layers.append(lcirc) un...
python
def _display_layers(circ: Circuit, qubits: Qubits) -> Circuit: """Separate a circuit into groups of gates that do not visually overlap""" N = len(qubits) qubit_idx = dict(zip(qubits, range(N))) gate_layers = DAGCircuit(circ).layers() layers = [] lcirc = Circuit() layers.append(lcirc) un...
[ "def", "_display_layers", "(", "circ", ":", "Circuit", ",", "qubits", ":", "Qubits", ")", "->", "Circuit", ":", "N", "=", "len", "(", "qubits", ")", "qubit_idx", "=", "dict", "(", "zip", "(", "qubits", ",", "range", "(", "N", ")", ")", ")", "gate_l...
Separate a circuit into groups of gates that do not visually overlap
[ "Separate", "a", "circuit", "into", "groups", "of", "gates", "that", "do", "not", "visually", "overlap" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/visualization.py#L235-L261
234,888
rigetti/quantumflow
quantumflow/visualization.py
render_latex
def render_latex(latex: str) -> PIL.Image: # pragma: no cover """ Convert a single page LaTeX document into an image. To display the returned image, `img.show()` Required external dependencies: `pdflatex` (with `qcircuit` package), and `poppler` (for `pdftocairo`). Args: A LaTeX...
python
def render_latex(latex: str) -> PIL.Image: # pragma: no cover """ Convert a single page LaTeX document into an image. To display the returned image, `img.show()` Required external dependencies: `pdflatex` (with `qcircuit` package), and `poppler` (for `pdftocairo`). Args: A LaTeX...
[ "def", "render_latex", "(", "latex", ":", "str", ")", "->", "PIL", ".", "Image", ":", "# pragma: no cover", "tmpfilename", "=", "'circ'", "with", "tempfile", ".", "TemporaryDirectory", "(", ")", "as", "tmpdirname", ":", "tmppath", "=", "os", ".", "path", "...
Convert a single page LaTeX document into an image. To display the returned image, `img.show()` Required external dependencies: `pdflatex` (with `qcircuit` package), and `poppler` (for `pdftocairo`). Args: A LaTeX document as a string. Returns: A PIL Image Raises: O...
[ "Convert", "a", "single", "page", "LaTeX", "document", "into", "an", "image", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/visualization.py#L264-L305
234,889
rigetti/quantumflow
quantumflow/visualization.py
circuit_to_image
def circuit_to_image(circ: Circuit, qubits: Qubits = None) -> PIL.Image: # pragma: no cover """Create an image of a quantum circuit. A convenience function that calls circuit_to_latex() and render_latex(). Args: circ: A quantum Circuit qubits: Optional qubi...
python
def circuit_to_image(circ: Circuit, qubits: Qubits = None) -> PIL.Image: # pragma: no cover """Create an image of a quantum circuit. A convenience function that calls circuit_to_latex() and render_latex(). Args: circ: A quantum Circuit qubits: Optional qubi...
[ "def", "circuit_to_image", "(", "circ", ":", "Circuit", ",", "qubits", ":", "Qubits", "=", "None", ")", "->", "PIL", ".", "Image", ":", "# pragma: no cover", "latex", "=", "circuit_to_latex", "(", "circ", ",", "qubits", ")", "img", "=", "render_latex", "("...
Create an image of a quantum circuit. A convenience function that calls circuit_to_latex() and render_latex(). Args: circ: A quantum Circuit qubits: Optional qubit list to specify qubit order Returns: Returns: A PIL Image (Use img.show() to display) Raises: ...
[ "Create", "an", "image", "of", "a", "quantum", "circuit", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/visualization.py#L308-L327
234,890
rigetti/quantumflow
quantumflow/visualization.py
_latex_format
def _latex_format(obj: Any) -> str: """Format an object as a latex string.""" if isinstance(obj, float): try: return sympy.latex(symbolize(obj)) except ValueError: return "{0:.4g}".format(obj) return str(obj)
python
def _latex_format(obj: Any) -> str: """Format an object as a latex string.""" if isinstance(obj, float): try: return sympy.latex(symbolize(obj)) except ValueError: return "{0:.4g}".format(obj) return str(obj)
[ "def", "_latex_format", "(", "obj", ":", "Any", ")", "->", "str", ":", "if", "isinstance", "(", "obj", ",", "float", ")", ":", "try", ":", "return", "sympy", ".", "latex", "(", "symbolize", "(", "obj", ")", ")", "except", "ValueError", ":", "return",...
Format an object as a latex string.
[ "Format", "an", "object", "as", "a", "latex", "string", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/visualization.py#L332-L340
234,891
rigetti/quantumflow
examples/eager_fit_gate.py
fit_zyz
def fit_zyz(target_gate): """ Tensorflow eager mode example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate. """ assert bk.BACKEND == 'eager' tf = bk.TL tfe = bk.tfe steps = 4000 dev = '/gpu:0' if bk.DEVICE == '...
python
def fit_zyz(target_gate): """ Tensorflow eager mode example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate. """ assert bk.BACKEND == 'eager' tf = bk.TL tfe = bk.tfe steps = 4000 dev = '/gpu:0' if bk.DEVICE == '...
[ "def", "fit_zyz", "(", "target_gate", ")", ":", "assert", "bk", ".", "BACKEND", "==", "'eager'", "tf", "=", "bk", ".", "TL", "tfe", "=", "bk", ".", "tfe", "steps", "=", "4000", "dev", "=", "'/gpu:0'", "if", "bk", ".", "DEVICE", "==", "'gpu'", "else...
Tensorflow eager mode example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate.
[ "Tensorflow", "eager", "mode", "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/eager_fit_gate.py#L21-L60
234,892
rigetti/quantumflow
quantumflow/meta.py
print_versions
def print_versions(file: typing.TextIO = None) -> None: """ Print version strings of currently installed dependencies ``> python -m quantumflow.meta`` Args: file: Output stream. Defaults to stdout. """ print('** QuantumFlow dependencies (> python -m quantumflow.meta) **') print(...
python
def print_versions(file: typing.TextIO = None) -> None: """ Print version strings of currently installed dependencies ``> python -m quantumflow.meta`` Args: file: Output stream. Defaults to stdout. """ print('** QuantumFlow dependencies (> python -m quantumflow.meta) **') print(...
[ "def", "print_versions", "(", "file", ":", "typing", ".", "TextIO", "=", "None", ")", "->", "None", ":", "print", "(", "'** QuantumFlow dependencies (> python -m quantumflow.meta) **'", ")", "print", "(", "'quantumflow \\t'", ",", "qf", ".", "__version__", ",", "f...
Print version strings of currently installed dependencies ``> python -m quantumflow.meta`` Args: file: Output stream. Defaults to stdout.
[ "Print", "version", "strings", "of", "currently", "installed", "dependencies" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/meta.py#L21-L40
234,893
rigetti/quantumflow
examples/tensorflow_fit_gate.py
fit_zyz
def fit_zyz(target_gate): """ Tensorflow example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate. """ assert bk.BACKEND == 'tensorflow' tf = bk.TL steps = 4000 t = tf.get_variable('t', [3]) gate = qf.ZYZ(t[0], t[1],...
python
def fit_zyz(target_gate): """ Tensorflow example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate. """ assert bk.BACKEND == 'tensorflow' tf = bk.TL steps = 4000 t = tf.get_variable('t', [3]) gate = qf.ZYZ(t[0], t[1],...
[ "def", "fit_zyz", "(", "target_gate", ")", ":", "assert", "bk", ".", "BACKEND", "==", "'tensorflow'", "tf", "=", "bk", ".", "TL", "steps", "=", "4000", "t", "=", "tf", ".", "get_variable", "(", "'t'", ",", "[", "3", "]", ")", "gate", "=", "qf", "...
Tensorflow example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate.
[ "Tensorflow", "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/tensorflow_fit_gate.py#L20-L50
234,894
rigetti/quantumflow
quantumflow/decompositions.py
zyz_decomposition
def zyz_decomposition(gate: Gate) -> Circuit: """ Returns the Euler Z-Y-Z decomposition of a local 1-qubit gate. """ if gate.qubit_nb != 1: raise ValueError('Expected 1-qubit gate') q, = gate.qubits U = asarray(gate.asoperator()) U /= np.linalg.det(U) ** (1/2) # SU(2) if ab...
python
def zyz_decomposition(gate: Gate) -> Circuit: """ Returns the Euler Z-Y-Z decomposition of a local 1-qubit gate. """ if gate.qubit_nb != 1: raise ValueError('Expected 1-qubit gate') q, = gate.qubits U = asarray(gate.asoperator()) U /= np.linalg.det(U) ** (1/2) # SU(2) if ab...
[ "def", "zyz_decomposition", "(", "gate", ":", "Gate", ")", "->", "Circuit", ":", "if", "gate", ".", "qubit_nb", "!=", "1", ":", "raise", "ValueError", "(", "'Expected 1-qubit gate'", ")", "q", ",", "=", "gate", ".", "qubits", "U", "=", "asarray", "(", ...
Returns the Euler Z-Y-Z decomposition of a local 1-qubit gate.
[ "Returns", "the", "Euler", "Z", "-", "Y", "-", "Z", "decomposition", "of", "a", "local", "1", "-", "qubit", "gate", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/decompositions.py#L65-L108
234,895
rigetti/quantumflow
quantumflow/decompositions.py
kronecker_decomposition
def kronecker_decomposition(gate: Gate) -> Circuit: """ Decompose a 2-qubit unitary composed of two 1-qubit local gates. Uses the "Nearest Kronecker Product" algorithm. Will give erratic results if the gate is not the direct product of two 1-qubit gates. """ # An alternative approach would be t...
python
def kronecker_decomposition(gate: Gate) -> Circuit: """ Decompose a 2-qubit unitary composed of two 1-qubit local gates. Uses the "Nearest Kronecker Product" algorithm. Will give erratic results if the gate is not the direct product of two 1-qubit gates. """ # An alternative approach would be t...
[ "def", "kronecker_decomposition", "(", "gate", ":", "Gate", ")", "->", "Circuit", ":", "# An alternative approach would be to take partial traces, but", "# this approach appears to be more robust.", "if", "gate", ".", "qubit_nb", "!=", "2", ":", "raise", "ValueError", "(", ...
Decompose a 2-qubit unitary composed of two 1-qubit local gates. Uses the "Nearest Kronecker Product" algorithm. Will give erratic results if the gate is not the direct product of two 1-qubit gates.
[ "Decompose", "a", "2", "-", "qubit", "unitary", "composed", "of", "two", "1", "-", "qubit", "local", "gates", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/decompositions.py#L111-L150
234,896
rigetti/quantumflow
quantumflow/decompositions.py
canonical_coords
def canonical_coords(gate: Gate) -> Sequence[float]: """Returns the canonical coordinates of a 2-qubit gate""" circ = canonical_decomposition(gate) gate = circ.elements[6] # type: ignore params = [gate.params[key] for key in ('tx', 'ty', 'tz')] return params
python
def canonical_coords(gate: Gate) -> Sequence[float]: """Returns the canonical coordinates of a 2-qubit gate""" circ = canonical_decomposition(gate) gate = circ.elements[6] # type: ignore params = [gate.params[key] for key in ('tx', 'ty', 'tz')] return params
[ "def", "canonical_coords", "(", "gate", ":", "Gate", ")", "->", "Sequence", "[", "float", "]", ":", "circ", "=", "canonical_decomposition", "(", "gate", ")", "gate", "=", "circ", ".", "elements", "[", "6", "]", "# type: ignore", "params", "=", "[", "gate...
Returns the canonical coordinates of a 2-qubit gate
[ "Returns", "the", "canonical", "coordinates", "of", "a", "2", "-", "qubit", "gate" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/decompositions.py#L153-L158
234,897
rigetti/quantumflow
quantumflow/decompositions.py
_eig_complex_symmetric
def _eig_complex_symmetric(M: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """Diagonalize a complex symmetric matrix. The eigenvalues are complex, and the eigenvectors form an orthogonal matrix. Returns: eigenvalues, eigenvectors """ if not np.allclose(M, M.transpose()): raise np....
python
def _eig_complex_symmetric(M: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """Diagonalize a complex symmetric matrix. The eigenvalues are complex, and the eigenvectors form an orthogonal matrix. Returns: eigenvalues, eigenvectors """ if not np.allclose(M, M.transpose()): raise np....
[ "def", "_eig_complex_symmetric", "(", "M", ":", "np", ".", "ndarray", ")", "->", "Tuple", "[", "np", ".", "ndarray", ",", "np", ".", "ndarray", "]", ":", "if", "not", "np", ".", "allclose", "(", "M", ",", "M", ".", "transpose", "(", ")", ")", ":"...
Diagonalize a complex symmetric matrix. The eigenvalues are complex, and the eigenvectors form an orthogonal matrix. Returns: eigenvalues, eigenvectors
[ "Diagonalize", "a", "complex", "symmetric", "matrix", ".", "The", "eigenvalues", "are", "complex", "and", "the", "eigenvectors", "form", "an", "orthogonal", "matrix", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/decompositions.py#L262-L309
234,898
rigetti/quantumflow
examples/qaoa_maxcut.py
maxcut_qaoa
def maxcut_qaoa( graph, steps=DEFAULT_STEPS, learning_rate=LEARNING_RATE, verbose=False): """QAOA Maxcut using tensorflow""" if not isinstance(graph, nx.Graph): graph = nx.from_edgelist(graph) init_scale = 0.01 init_bias = 0.5 init_beta = normal(loc=init_bi...
python
def maxcut_qaoa( graph, steps=DEFAULT_STEPS, learning_rate=LEARNING_RATE, verbose=False): """QAOA Maxcut using tensorflow""" if not isinstance(graph, nx.Graph): graph = nx.from_edgelist(graph) init_scale = 0.01 init_bias = 0.5 init_beta = normal(loc=init_bi...
[ "def", "maxcut_qaoa", "(", "graph", ",", "steps", "=", "DEFAULT_STEPS", ",", "learning_rate", "=", "LEARNING_RATE", ",", "verbose", "=", "False", ")", ":", "if", "not", "isinstance", "(", "graph", ",", "nx", ".", "Graph", ")", ":", "graph", "=", "nx", ...
QAOA Maxcut using tensorflow
[ "QAOA", "Maxcut", "using", "tensorflow" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/examples/qaoa_maxcut.py#L37-L87
234,899
rigetti/quantumflow
quantumflow/gates.py
identity_gate
def identity_gate(qubits: Union[int, Qubits]) -> Gate: """Returns the K-qubit identity gate""" _, qubits = qubits_count_tuple(qubits) return I(*qubits)
python
def identity_gate(qubits: Union[int, Qubits]) -> Gate: """Returns the K-qubit identity gate""" _, qubits = qubits_count_tuple(qubits) return I(*qubits)
[ "def", "identity_gate", "(", "qubits", ":", "Union", "[", "int", ",", "Qubits", "]", ")", "->", "Gate", ":", "_", ",", "qubits", "=", "qubits_count_tuple", "(", "qubits", ")", "return", "I", "(", "*", "qubits", ")" ]
Returns the K-qubit identity gate
[ "Returns", "the", "K", "-", "qubit", "identity", "gate" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L57-L60