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", "(", "state", ")", ":", "ket", "=", "\"\"", ".", "join", "(", "[", "str", "(", "n", ")", "for", "n", "in", "index", "]", ")", "print", "(", "ket", ",", "\":\"", ",", "amplitude", ",", "file", "=", "file", ")" ]
Print a state vector
[ "Print", "a", "state", "vector" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L234-L239
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.probabilities()) for index, prob in np.ndenumerate(prob): prob = round(prob, ndigits) if prob == 0.0: continue ket = "".join([str(n) for n in index]) print(ket, ":", prob, file=file)
python
def print_probabilities(state: State, ndigits: int = 4, file: TextIO = None) -> None: """ Pretty print state probabilities. Args: state: ndigits: Number of digits of accuracy file: Output stream (Defaults to stdout) """ prob = bk.evaluate(state.probabilities()) for index, prob in np.ndenumerate(prob): prob = round(prob, ndigits) if prob == 0.0: continue ket = "".join([str(n) for n in index]) print(ket, ":", prob, file=file)
[ "def", "print_probabilities", "(", "state", ":", "State", ",", "ndigits", ":", "int", "=", "4", ",", "file", ":", "TextIO", "=", "None", ")", "->", "None", ":", "prob", "=", "bk", ".", "evaluate", "(", "state", ".", "probabilities", "(", ")", ")", "for", "index", ",", "prob", "in", "np", ".", "ndenumerate", "(", "prob", ")", ":", "prob", "=", "round", "(", "prob", ",", "ndigits", ")", "if", "prob", "==", "0.0", ":", "continue", "ket", "=", "\"\"", ".", "join", "(", "[", "str", "(", "n", ")", "for", "n", "in", "index", "]", ")", "print", "(", "ket", ",", "\":\"", ",", "prob", ",", "file", "=", "file", ")" ]
Pretty print state probabilities. Args: state: ndigits: Number of digits of accuracy file: Output stream (Defaults to stdout)
[ "Pretty", "print", "state", "probabilities", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L243-L259
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", "**", "N", "return", "Density", "(", "matrix", ",", "qubits", ")" ]
Returns the completely mixed density matrix
[ "Returns", "the", "completely", "mixed", "density", "matrix" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L322-L326
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", "=", "dict", "(", "ChainMap", "(", "*", "[", "rho", ".", "memory", "for", "rho", "in", "densities", "]", ")", ")", "# TESTME", "return", "Density", "(", "vec", ".", "tensor", ",", "vec", ".", "qubits", ",", "memory", ")" ]
Join two mixed states into a larger qubit state
[ "Join", "two", "mixed", "states", "into", "a", "larger", "qubit", "state" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L349-L355
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", ".", "qubits", ",", "self", ".", "_memory", ")" ]
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())) res = np.random.multinomial(trials, probs.ravel()) res = res.reshape(probs.shape) return res
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())) res = np.random.multinomial(trials, probs.ravel()) res = res.reshape(probs.shape) return res
[ "def", "sample", "(", "self", ",", "trials", ":", "int", ")", "->", "np", ".", "ndarray", ":", "# TODO: Can we do this within backend?", "probs", "=", "np", ".", "real", "(", "bk", ".", "evaluate", "(", "self", ".", "probabilities", "(", ")", ")", ")", "res", "=", "np", ".", "random", ".", "multinomial", "(", "trials", ",", "probs", ".", "ravel", "(", ")", ")", "res", "=", "res", ".", "reshape", "(", "probs", ".", "shape", ")", "return", "res" ]
Measure the state in the computational basis the the given number of trials, and return the counts of each output configuration.
[ "Measure", "the", "state", "in", "the", "computational", "basis", "the", "the", "given", "number", "of", "trials", "and", "return", "the", "counts", "of", "each", "output", "configuration", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L121-L129
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 number of trials is specified, we sample the given number of times. Else we return the exact expectation (as if we'd performed an infinite number of trials. ) """ if trials is None: probs = self.probabilities() else: probs = bk.real(bk.astensorproduct(self.sample(trials) / trials)) diag_hermitian = bk.astensorproduct(diag_hermitian) return bk.sum(bk.real(diag_hermitian) * probs)
python
def expectation(self, diag_hermitian: bk.TensorLike, trials: int = None) -> bk.BKTensor: """Return the expectation of a measurement. Since we can only measure our computer in the computational basis, we only require the diagonal of the Hermitian in that basis. If the number of trials is specified, we sample the given number of times. Else we return the exact expectation (as if we'd performed an infinite number of trials. ) """ if trials is None: probs = self.probabilities() else: probs = bk.real(bk.astensorproduct(self.sample(trials) / trials)) diag_hermitian = bk.astensorproduct(diag_hermitian) return bk.sum(bk.real(diag_hermitian) * probs)
[ "def", "expectation", "(", "self", ",", "diag_hermitian", ":", "bk", ".", "TensorLike", ",", "trials", ":", "int", "=", "None", ")", "->", "bk", ".", "BKTensor", ":", "if", "trials", "is", "None", ":", "probs", "=", "self", ".", "probabilities", "(", ")", "else", ":", "probs", "=", "bk", ".", "real", "(", "bk", ".", "astensorproduct", "(", "self", ".", "sample", "(", "trials", ")", "/", "trials", ")", ")", "diag_hermitian", "=", "bk", ".", "astensorproduct", "(", "diag_hermitian", ")", "return", "bk", ".", "sum", "(", "bk", ".", "real", "(", "diag_hermitian", ")", "*", "probs", ")" ]
Return the expectation of a measurement. Since we can only measure our computer in the computational basis, we only require the diagonal of the Hermitian in that basis. If the number of trials is specified, we sample the given number of times. Else we return the exact expectation (as if we'd performed an infinite number of trials. )
[ "Return", "the", "expectation", "of", "a", "measurement", ".", "Since", "we", "can", "only", "measure", "our", "computer", "in", "the", "computational", "basis", "we", "only", "require", "the", "diagonal", "of", "the", "Hermitian", "in", "that", "basis", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L131-L147
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(np.ndindex(*[2] * self.qubit_nb))) res = np.random.choice(probs.size, p=probs.ravel()) res = indices[res] return res
python
def measure(self) -> np.ndarray: """Measure the state in the computational basis. Returns: A [2]*bits array of qubit states, either 0 or 1 """ # TODO: Can we do this within backend? probs = np.real(bk.evaluate(self.probabilities())) indices = np.asarray(list(np.ndindex(*[2] * self.qubit_nb))) res = np.random.choice(probs.size, p=probs.ravel()) res = indices[res] return res
[ "def", "measure", "(", "self", ")", "->", "np", ".", "ndarray", ":", "# TODO: Can we do this within backend?", "probs", "=", "np", ".", "real", "(", "bk", ".", "evaluate", "(", "self", ".", "probabilities", "(", ")", ")", ")", "indices", "=", "np", ".", "asarray", "(", "list", "(", "np", ".", "ndindex", "(", "*", "[", "2", "]", "*", "self", ".", "qubit_nb", ")", ")", ")", "res", "=", "np", ".", "random", ".", "choice", "(", "probs", ".", "size", ",", "p", "=", "probs", ".", "ravel", "(", ")", ")", "res", "=", "indices", "[", "res", "]", "return", "res" ]
Measure the state in the computational basis. Returns: A [2]*bits array of qubit states, either 0 or 1
[ "Measure", "the", "state", "in", "the", "computational", "basis", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L149-L160
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", ",", "self", ".", "_memory", ")" ]
Convert a pure state to a density matrix
[ "Convert", "a", "pure", "state", "to", "a", "density", "matrix" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L162-L165
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.X(qubit0).run(ket) ket = qf.T(qubit1).run(ket) ket = qf.CNOT(qubit0, qubit1).run(ket) return ket.vec.tensor
python
def benchmark(N, gates): """Create and run a circuit with N qubits and given number of gates""" qubits = list(range(0, N)) ket = qf.zero_state(N) for n in range(0, N): ket = qf.H(n).run(ket) for _ in range(0, (gates-N)//3): qubit0, qubit1 = random.sample(qubits, 2) ket = qf.X(qubit0).run(ket) ket = qf.T(qubit1).run(ket) ket = qf.CNOT(qubit0, qubit1).run(ket) return ket.vec.tensor
[ "def", "benchmark", "(", "N", ",", "gates", ")", ":", "qubits", "=", "list", "(", "range", "(", "0", ",", "N", ")", ")", "ket", "=", "qf", ".", "zero_state", "(", "N", ")", "for", "n", "in", "range", "(", "0", ",", "N", ")", ":", "ket", "=", "qf", ".", "H", "(", "n", ")", ".", "run", "(", "ket", ")", "for", "_", "in", "range", "(", "0", ",", "(", "gates", "-", "N", ")", "//", "3", ")", ":", "qubit0", ",", "qubit1", "=", "random", ".", "sample", "(", "qubits", ",", "2", ")", "ket", "=", "qf", ".", "X", "(", "qubit0", ")", ".", "run", "(", "ket", ")", "ket", "=", "qf", ".", "T", "(", "qubit1", ")", ".", "run", "(", "ket", ")", "ket", "=", "qf", ".", "CNOT", "(", "qubit0", ",", "qubit1", ")", ".", "run", "(", "ket", ")", "return", "ket", ".", "vec", ".", "tensor" ]
Create and run a circuit with N qubits and given number of gates
[ "Create", "and", "run", "a", "circuit", "with", "N", "qubits", "and", "given", "number", "of", "gates" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/tools/benchmark.py#L31-L45
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]) circ += qf.random_gate([1]) circ += qf.CANONICAL(*coords1, 0, 1) gate = circ.asgate() coords = qf.canonical_coords(gate) decomps.append(coords) return decomps
python
def sandwich_decompositions(coords0, coords1, samples=SAMPLES): """Create composite gates, decompose, and return a list of canonical coordinates""" decomps = [] for _ in range(samples): circ = qf.Circuit() circ += qf.CANONICAL(*coords0, 0, 1) circ += qf.random_gate([0]) circ += qf.random_gate([1]) circ += qf.CANONICAL(*coords1, 0, 1) gate = circ.asgate() coords = qf.canonical_coords(gate) decomps.append(coords) return decomps
[ "def", "sandwich_decompositions", "(", "coords0", ",", "coords1", ",", "samples", "=", "SAMPLES", ")", ":", "decomps", "=", "[", "]", "for", "_", "in", "range", "(", "samples", ")", ":", "circ", "=", "qf", ".", "Circuit", "(", ")", "circ", "+=", "qf", ".", "CANONICAL", "(", "*", "coords0", ",", "0", ",", "1", ")", "circ", "+=", "qf", ".", "random_gate", "(", "[", "0", "]", ")", "circ", "+=", "qf", ".", "random_gate", "(", "[", "1", "]", ")", "circ", "+=", "qf", ".", "CANONICAL", "(", "*", "coords1", ",", "0", ",", "1", ")", "gate", "=", "circ", ".", "asgate", "(", ")", "coords", "=", "qf", ".", "canonical_coords", "(", "gate", ")", "decomps", ".", "append", "(", "coords", ")", "return", "decomps" ]
Create composite gates, decompose, and return a list of canonical coordinates
[ "Create", "composite", "gates", "decompose", "and", "return", "a", "list", "of", "canonical", "coordinates" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/examples/weyl.py#L82-L97
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, coeff)) return Pauli(tuple(terms))
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, coeff)) return Pauli(tuple(terms))
[ "def", "pauli_sum", "(", "*", "elements", ":", "Pauli", ")", "->", "Pauli", ":", "terms", "=", "[", "]", "key", "=", "itemgetter", "(", "0", ")", "for", "term", ",", "grp", "in", "groupby", "(", "heapq", ".", "merge", "(", "*", "elements", ",", "key", "=", "key", ")", ",", "key", "=", "key", ")", ":", "coeff", "=", "sum", "(", "g", "[", "1", "]", "for", "g", "in", "grp", ")", "if", "not", "isclose", "(", "coeff", ",", "0.0", ")", ":", "terms", ".", "append", "(", "(", "term", ",", "coeff", ")", ")", "return", "Pauli", "(", "tuple", "(", "terms", ")", ")" ]
Return the sum of elements of the Pauli algebra
[ "Return", "the", "sum", "of", "elements", "of", "the", "Pauli", "algebra" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/paulialgebra.py#L245-L255
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) for qubit, qops in groupby(heapq.merge(*ops, key=key), key=key): res = next(qops)[1] # Operator: X Y Z for op in qops: pair = res + op[1] res, rescoeff = PAULI_PROD[pair] coeff *= rescoeff if res != 'I': out.append((qubit, res)) p = Pauli(((tuple(out), coeff),)) result_terms.append(p) return pauli_sum(*result_terms)
python
def pauli_product(*elements: Pauli) -> Pauli: """Return the product of elements of the Pauli algebra""" result_terms = [] for terms in product(*elements): coeff = reduce(mul, [term[1] for term in terms]) ops = (term[0] for term in terms) out = [] key = itemgetter(0) for qubit, qops in groupby(heapq.merge(*ops, key=key), key=key): res = next(qops)[1] # Operator: X Y Z for op in qops: pair = res + op[1] res, rescoeff = PAULI_PROD[pair] coeff *= rescoeff if res != 'I': out.append((qubit, res)) p = Pauli(((tuple(out), coeff),)) result_terms.append(p) return pauli_sum(*result_terms)
[ "def", "pauli_product", "(", "*", "elements", ":", "Pauli", ")", "->", "Pauli", ":", "result_terms", "=", "[", "]", "for", "terms", "in", "product", "(", "*", "elements", ")", ":", "coeff", "=", "reduce", "(", "mul", ",", "[", "term", "[", "1", "]", "for", "term", "in", "terms", "]", ")", "ops", "=", "(", "term", "[", "0", "]", "for", "term", "in", "terms", ")", "out", "=", "[", "]", "key", "=", "itemgetter", "(", "0", ")", "for", "qubit", ",", "qops", "in", "groupby", "(", "heapq", ".", "merge", "(", "*", "ops", ",", "key", "=", "key", ")", ",", "key", "=", "key", ")", ":", "res", "=", "next", "(", "qops", ")", "[", "1", "]", "# Operator: X Y Z", "for", "op", "in", "qops", ":", "pair", "=", "res", "+", "op", "[", "1", "]", "res", ",", "rescoeff", "=", "PAULI_PROD", "[", "pair", "]", "coeff", "*=", "rescoeff", "if", "res", "!=", "'I'", ":", "out", ".", "append", "(", "(", "qubit", ",", "res", ")", ")", "p", "=", "Pauli", "(", "(", "(", "tuple", "(", "out", ")", ",", "coeff", ")", ",", ")", ")", "result_terms", ".", "append", "(", "p", ")", "return", "pauli_sum", "(", "*", "result_terms", ")" ]
Return the product of elements of the Pauli algebra
[ "Return", "the", "product", "of", "elements", "of", "the", "Pauli", "algebra" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/paulialgebra.py#L258-L279
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.identity() if exponent == 1: return pauli # https://en.wikipedia.org/wiki/Exponentiation_by_squaring y = Pauli.identity() x = pauli n = exponent while n > 1: if n % 2 == 0: # Even x = x * x n = n // 2 else: # Odd y = x * y x = x * x n = (n - 1) // 2 return x * y
python
def pauli_pow(pauli: Pauli, exponent: int) -> Pauli: """ Raise an element of the Pauli algebra to a non-negative integer power. """ if not isinstance(exponent, int) or exponent < 0: raise ValueError("The exponent must be a non-negative integer.") if exponent == 0: return Pauli.identity() if exponent == 1: return pauli # https://en.wikipedia.org/wiki/Exponentiation_by_squaring y = Pauli.identity() x = pauli n = exponent while n > 1: if n % 2 == 0: # Even x = x * x n = n // 2 else: # Odd y = x * y x = x * x n = (n - 1) // 2 return x * y
[ "def", "pauli_pow", "(", "pauli", ":", "Pauli", ",", "exponent", ":", "int", ")", "->", "Pauli", ":", "if", "not", "isinstance", "(", "exponent", ",", "int", ")", "or", "exponent", "<", "0", ":", "raise", "ValueError", "(", "\"The exponent must be a non-negative integer.\"", ")", "if", "exponent", "==", "0", ":", "return", "Pauli", ".", "identity", "(", ")", "if", "exponent", "==", "1", ":", "return", "pauli", "# https://en.wikipedia.org/wiki/Exponentiation_by_squaring", "y", "=", "Pauli", ".", "identity", "(", ")", "x", "=", "pauli", "n", "=", "exponent", "while", "n", ">", "1", ":", "if", "n", "%", "2", "==", "0", ":", "# Even", "x", "=", "x", "*", "x", "n", "=", "n", "//", "2", "else", ":", "# Odd", "y", "=", "x", "*", "y", "x", "=", "x", "*", "x", "n", "=", "(", "n", "-", "1", ")", "//", "2", "return", "x", "*", "y" ]
Raise an element of the Pauli algebra to a non-negative integer power.
[ "Raise", "an", "element", "of", "the", "Pauli", "algebra", "to", "a", "non", "-", "negative", "integer", "power", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/paulialgebra.py#L282-L308
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(element) < 2: return (element,) groups: List[Pauli] = [] # typing: List[Pauli] for term in element: pterm = Pauli((term,)) assigned = False for i, grp in enumerate(groups): if paulis_commute(grp, pterm): groups[i] = grp + pterm assigned = True break if not assigned: groups.append(pterm) return tuple(groups)
python
def pauli_commuting_sets(element: Pauli) -> Tuple[Pauli, ...]: """Gather the terms of a Pauli polynomial into commuting sets. Uses the algorithm defined in (Raeisi, Wiebe, Sanders, arXiv:1108.4318, 2011) to find commuting sets. Except uses commutation check from arXiv:1405.5749v2 """ if len(element) < 2: return (element,) groups: List[Pauli] = [] # typing: List[Pauli] for term in element: pterm = Pauli((term,)) assigned = False for i, grp in enumerate(groups): if paulis_commute(grp, pterm): groups[i] = grp + pterm assigned = True break if not assigned: groups.append(pterm) return tuple(groups)
[ "def", "pauli_commuting_sets", "(", "element", ":", "Pauli", ")", "->", "Tuple", "[", "Pauli", ",", "...", "]", ":", "if", "len", "(", "element", ")", "<", "2", ":", "return", "(", "element", ",", ")", "groups", ":", "List", "[", "Pauli", "]", "=", "[", "]", "# typing: List[Pauli]", "for", "term", "in", "element", ":", "pterm", "=", "Pauli", "(", "(", "term", ",", ")", ")", "assigned", "=", "False", "for", "i", ",", "grp", "in", "enumerate", "(", "groups", ")", ":", "if", "paulis_commute", "(", "grp", ",", "pterm", ")", ":", "groups", "[", "i", "]", "=", "grp", "+", "pterm", "assigned", "=", "True", "break", "if", "not", "assigned", ":", "groups", ".", "append", "(", "pterm", ")", "return", "tuple", "(", "groups", ")" ]
Gather the terms of a Pauli polynomial into commuting sets. Uses the algorithm defined in (Raeisi, Wiebe, Sanders, arXiv:1108.4318, 2011) to find commuting sets. Except uses commutation check from arXiv:1405.5749v2
[ "Gather", "the", "terms", "of", "a", "Pauli", "polynomial", "into", "commuting", "sets", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/paulialgebra.py#L348-L372
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", "**", "(", "N", "//", "2", ")", "]", ")", "tensor", "=", "np", ".", "diag", "(", "tensor", ")", "tensor", "=", "reshape", "(", "tensor", ",", "[", "2", "]", "*", "(", "N", "//", "2", ")", ")", "return", "tensor" ]
Returns the matrix diagonal of the product tensor
[ "Returns", "the", "matrix", "diagonal", "of", "the", "product", "tensor" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/numpybk.py#L150-L156
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:`B^{b_0,b_1,b_2}`. An operator has K dimensions, K/2 for contravariant indices (e.g. ket components) and K/2 for covariant (bra) indices, e.g. :math:`A^{a_0,a_1}_{a_2,a_3}` for a 2-qubit gate. The given indices of A are contracted against B, replacing the given positions. E.g. ``tensormul(A, B, [0,2])`` is equivalent to .. math:: C^{a_0,b_1,a_1} =\sum_{i_0,i_1} A^{a_0,a_1}_{i_0,i_1} B^{i_0,b_1,i_1} Args: tensor0: A tensor product representation of a gate tensor1: A tensor product representation of a gate or state indices: List of indices of tensor1 on which to act. Returns: Resultant state or gate tensor """ # Note: This method is the critical computational core of QuantumFlow # We currently have two implementations, one that uses einsum, the other # using matrix multiplication # # numpy: # einsum is much faster particularly for small numbers of qubits # tensorflow: # Little different is performance, but einsum would restrict the # maximum number of qubits to 26 (Because tensorflow only allows 26 # einsum subscripts at present] # torch: # einsum is slower than matmul N = rank(tensor1) K = rank(tensor0) // 2 assert K == len(indices) out = list(EINSUM_SUBSCRIPTS[0:N]) left_in = list(EINSUM_SUBSCRIPTS[N:N+K]) left_out = [out[idx] for idx in indices] right = list(EINSUM_SUBSCRIPTS[0:N]) for idx, s in zip(indices, left_in): right[idx] = s subscripts = ''.join(left_out + left_in + [','] + right + ['->'] + out) # print('>>>', K, N, subscripts) tensor = einsum(subscripts, tensor0, tensor1) return tensor
python
def tensormul(tensor0: BKTensor, tensor1: BKTensor, indices: typing.List[int]) -> BKTensor: r""" Generalization of matrix multiplication to product tensors. A state vector in product tensor representation has N dimension, one for each contravariant index, e.g. for 3-qubit states :math:`B^{b_0,b_1,b_2}`. An operator has K dimensions, K/2 for contravariant indices (e.g. ket components) and K/2 for covariant (bra) indices, e.g. :math:`A^{a_0,a_1}_{a_2,a_3}` for a 2-qubit gate. The given indices of A are contracted against B, replacing the given positions. E.g. ``tensormul(A, B, [0,2])`` is equivalent to .. math:: C^{a_0,b_1,a_1} =\sum_{i_0,i_1} A^{a_0,a_1}_{i_0,i_1} B^{i_0,b_1,i_1} Args: tensor0: A tensor product representation of a gate tensor1: A tensor product representation of a gate or state indices: List of indices of tensor1 on which to act. Returns: Resultant state or gate tensor """ # Note: This method is the critical computational core of QuantumFlow # We currently have two implementations, one that uses einsum, the other # using matrix multiplication # # numpy: # einsum is much faster particularly for small numbers of qubits # tensorflow: # Little different is performance, but einsum would restrict the # maximum number of qubits to 26 (Because tensorflow only allows 26 # einsum subscripts at present] # torch: # einsum is slower than matmul N = rank(tensor1) K = rank(tensor0) // 2 assert K == len(indices) out = list(EINSUM_SUBSCRIPTS[0:N]) left_in = list(EINSUM_SUBSCRIPTS[N:N+K]) left_out = [out[idx] for idx in indices] right = list(EINSUM_SUBSCRIPTS[0:N]) for idx, s in zip(indices, left_in): right[idx] = s subscripts = ''.join(left_out + left_in + [','] + right + ['->'] + out) # print('>>>', K, N, subscripts) tensor = einsum(subscripts, tensor0, tensor1) return tensor
[ "def", "tensormul", "(", "tensor0", ":", "BKTensor", ",", "tensor1", ":", "BKTensor", ",", "indices", ":", "typing", ".", "List", "[", "int", "]", ")", "->", "BKTensor", ":", "# Note: This method is the critical computational core of QuantumFlow", "# We currently have two implementations, one that uses einsum, the other", "# using matrix multiplication", "#", "# numpy:", "# einsum is much faster particularly for small numbers of qubits", "# tensorflow:", "# Little different is performance, but einsum would restrict the", "# maximum number of qubits to 26 (Because tensorflow only allows 26", "# einsum subscripts at present]", "# torch:", "# einsum is slower than matmul", "N", "=", "rank", "(", "tensor1", ")", "K", "=", "rank", "(", "tensor0", ")", "//", "2", "assert", "K", "==", "len", "(", "indices", ")", "out", "=", "list", "(", "EINSUM_SUBSCRIPTS", "[", "0", ":", "N", "]", ")", "left_in", "=", "list", "(", "EINSUM_SUBSCRIPTS", "[", "N", ":", "N", "+", "K", "]", ")", "left_out", "=", "[", "out", "[", "idx", "]", "for", "idx", "in", "indices", "]", "right", "=", "list", "(", "EINSUM_SUBSCRIPTS", "[", "0", ":", "N", "]", ")", "for", "idx", ",", "s", "in", "zip", "(", "indices", ",", "left_in", ")", ":", "right", "[", "idx", "]", "=", "s", "subscripts", "=", "''", ".", "join", "(", "left_out", "+", "left_in", "+", "[", "','", "]", "+", "right", "+", "[", "'->'", "]", "+", "out", ")", "# print('>>>', K, N, subscripts)", "tensor", "=", "einsum", "(", "subscripts", ",", "tensor0", ",", "tensor1", ")", "return", "tensor" ]
r""" Generalization of matrix multiplication to product tensors. A state vector in product tensor representation has N dimension, one for each contravariant index, e.g. for 3-qubit states :math:`B^{b_0,b_1,b_2}`. An operator has K dimensions, K/2 for contravariant indices (e.g. ket components) and K/2 for covariant (bra) indices, e.g. :math:`A^{a_0,a_1}_{a_2,a_3}` for a 2-qubit gate. The given indices of A are contracted against B, replacing the given positions. E.g. ``tensormul(A, B, [0,2])`` is equivalent to .. math:: C^{a_0,b_1,a_1} =\sum_{i_0,i_1} A^{a_0,a_1}_{i_0,i_1} B^{i_0,b_1,i_1} Args: tensor0: A tensor product representation of a gate tensor1: A tensor product representation of a gate or state indices: List of indices of tensor1 on which to act. Returns: Resultant state or gate tensor
[ "r", "Generalization", "of", "matrix", "multiplication", "to", "product", "tensors", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/numpybk.py#L159-L214
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, value in mapping.items(): inv_map.setdefault(value, set()).add(key) return inv_map
python
def invert_map(mapping: dict, one_to_one: bool = True) -> dict: """Invert a dictionary. If not one_to_one then the inverted map will contain lists of former keys as values. """ if one_to_one: inv_map = {value: key for key, value in mapping.items()} else: inv_map = {} for key, value in mapping.items(): inv_map.setdefault(value, set()).add(key) return inv_map
[ "def", "invert_map", "(", "mapping", ":", "dict", ",", "one_to_one", ":", "bool", "=", "True", ")", "->", "dict", ":", "if", "one_to_one", ":", "inv_map", "=", "{", "value", ":", "key", "for", "key", ",", "value", "in", "mapping", ".", "items", "(", ")", "}", "else", ":", "inv_map", "=", "{", "}", "for", "key", ",", "value", "in", "mapping", ".", "items", "(", ")", ":", "inv_map", ".", "setdefault", "(", "value", ",", "set", "(", ")", ")", ".", "add", "(", "key", ")", "return", "inv_map" ]
Invert a dictionary. If not one_to_one then the inverted map will contain lists of former keys as values.
[ "Invert", "a", "dictionary", ".", "If", "not", "one_to_one", "then", "the", "inverted", "map", "will", "contain", "lists", "of", "former", "keys", "as", "values", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/utils.py#L38-L49
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)) [0, 1, 0, 0] """ if pad is None: form = '{:0b}' else: form = '{:0' + str(pad) + 'b}' return [int(b) for b in form.format(x)]
python
def int_to_bitlist(x: int, pad: int = None) -> Sequence[int]: """Converts an integer to a binary sequence of bits. Pad prepends with sufficient zeros to ensures that the returned list contains at least this number of bits. >>> from quantumflow.utils import int_to_bitlist >>> int_to_bitlist(4, 4)) [0, 1, 0, 0] """ if pad is None: form = '{:0b}' else: form = '{:0' + str(pad) + 'b}' return [int(b) for b in form.format(x)]
[ "def", "int_to_bitlist", "(", "x", ":", "int", ",", "pad", ":", "int", "=", "None", ")", "->", "Sequence", "[", "int", "]", ":", "if", "pad", "is", "None", ":", "form", "=", "'{:0b}'", "else", ":", "form", "=", "'{:0'", "+", "str", "(", "pad", ")", "+", "'b}'", "return", "[", "int", "(", "b", ")", "for", "b", "in", "form", ".", "format", "(", "x", ")", "]" ]
Converts an integer to a binary sequence of bits. Pad prepends with sufficient zeros to ensures that the returned list contains at least this number of bits. >>> from quantumflow.utils import int_to_bitlist >>> int_to_bitlist(4, 4)) [0, 1, 0, 0]
[ "Converts", "an", "integer", "to", "a", "binary", "sequence", "of", "bits", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/utils.py#L62-L77
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)) return count
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)) return count
[ "def", "spanning_tree_count", "(", "graph", ":", "nx", ".", "Graph", ")", "->", "int", ":", "laplacian", "=", "nx", ".", "laplacian_matrix", "(", "graph", ")", ".", "toarray", "(", ")", "comatrix", "=", "laplacian", "[", ":", "-", "1", ",", ":", "-", "1", "]", "det", "=", "np", ".", "linalg", ".", "det", "(", "comatrix", ")", "count", "=", "int", "(", "round", "(", "det", ")", ")", "return", "count" ]
Return the number of unique spanning trees of a graph, using Kirchhoff's matrix tree theorem.
[ "Return", "the", "number", "of", "unique", "spanning", "trees", "of", "a", "graph", "using", "Kirchhoff", "s", "matrix", "tree", "theorem", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/utils.py#L108-L116
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, 9, 10, 12, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192 Raises: ValueError: If cannot rationalize float """ if denominators is None: denominators = _DENOMINATORS frac = Fraction.from_float(flt).limit_denominator() if frac.denominator not in denominators: raise ValueError('Cannot rationalize') return frac
python
def rationalize(flt: float, denominators: Set[int] = None) -> Fraction: """Convert a floating point number to a Fraction with a small denominator. Args: flt: A floating point number denominators: Collection of standard denominators. Default is 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192 Raises: ValueError: If cannot rationalize float """ if denominators is None: denominators = _DENOMINATORS frac = Fraction.from_float(flt).limit_denominator() if frac.denominator not in denominators: raise ValueError('Cannot rationalize') return frac
[ "def", "rationalize", "(", "flt", ":", "float", ",", "denominators", ":", "Set", "[", "int", "]", "=", "None", ")", "->", "Fraction", ":", "if", "denominators", "is", "None", ":", "denominators", "=", "_DENOMINATORS", "frac", "=", "Fraction", ".", "from_float", "(", "flt", ")", ".", "limit_denominator", "(", ")", "if", "frac", ".", "denominator", "not", "in", "denominators", ":", "raise", "ValueError", "(", "'Cannot rationalize'", ")", "return", "frac" ]
Convert a floating point number to a Fraction with a small denominator. Args: flt: A floating point number denominators: Collection of standard denominators. Default is 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192 Raises: ValueError: If cannot rationalize float
[ "Convert", "a", "floating", "point", "number", "to", "a", "Fraction", "with", "a", "small", "denominator", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/utils.py#L171-L189
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: ratio = rationalize(flt) res = sympy.simplify(ratio) except ValueError: ratio = rationalize(flt/np.pi) res = sympy.simplify(ratio) * sympy.pi return res
python
def symbolize(flt: float) -> sympy.Symbol: """Attempt to convert a real number into a simpler symbolic representation. Returns: A sympy Symbol. (Convert to string with str(sym) or to latex with sympy.latex(sym) Raises: ValueError: If cannot simplify float """ try: ratio = rationalize(flt) res = sympy.simplify(ratio) except ValueError: ratio = rationalize(flt/np.pi) res = sympy.simplify(ratio) * sympy.pi return res
[ "def", "symbolize", "(", "flt", ":", "float", ")", "->", "sympy", ".", "Symbol", ":", "try", ":", "ratio", "=", "rationalize", "(", "flt", ")", "res", "=", "sympy", ".", "simplify", "(", "ratio", ")", "except", "ValueError", ":", "ratio", "=", "rationalize", "(", "flt", "/", "np", ".", "pi", ")", "res", "=", "sympy", ".", "simplify", "(", "ratio", ")", "*", "sympy", ".", "pi", "return", "res" ]
Attempt to convert a real number into a simpler symbolic representation. Returns: A sympy Symbol. (Convert to string with str(sym) or to latex with sympy.latex(sym) Raises: ValueError: If cannot simplify float
[ "Attempt", "to", "convert", "a", "real", "number", "into", "a", "simpler", "symbolic", "representation", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/utils.py#L192-L208
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_latex", "(", "latex", ")", "return", "img" ]
Returns an image of a pyquil circuit. See circuit_to_latex() for more details.
[ "Returns", "an", "image", "of", "a", "pyquil", "circuit", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L160-L168
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 [] prog.gate(elem.name, params, elem.qubits) elif isinstance(elem, Measure): prog.measure(elem.qubit, elem.cbit) else: # FIXME: more informative error message raise ValueError('Cannot convert operation to pyquil') return prog
python
def circuit_to_pyquil(circuit: Circuit) -> pyquil.Program: """Convert a QuantumFlow circuit to a pyQuil program""" prog = pyquil.Program() for elem in circuit.elements: if isinstance(elem, Gate) and elem.name in QUIL_GATES: params = list(elem.params.values()) if elem.params else [] prog.gate(elem.name, params, elem.qubits) elif isinstance(elem, Measure): prog.measure(elem.qubit, elem.cbit) else: # FIXME: more informative error message raise ValueError('Cannot convert operation to pyquil') return prog
[ "def", "circuit_to_pyquil", "(", "circuit", ":", "Circuit", ")", "->", "pyquil", ".", "Program", ":", "prog", "=", "pyquil", ".", "Program", "(", ")", "for", "elem", "in", "circuit", ".", "elements", ":", "if", "isinstance", "(", "elem", ",", "Gate", ")", "and", "elem", ".", "name", "in", "QUIL_GATES", ":", "params", "=", "list", "(", "elem", ".", "params", ".", "values", "(", ")", ")", "if", "elem", ".", "params", "else", "[", "]", "prog", ".", "gate", "(", "elem", ".", "name", ",", "params", ",", "elem", ".", "qubits", ")", "elif", "isinstance", "(", "elem", ",", "Measure", ")", ":", "prog", ".", "measure", "(", "elem", ".", "qubit", ",", "elem", ".", "cbit", ")", "else", ":", "# FIXME: more informative error message", "raise", "ValueError", "(", "'Cannot convert operation to pyquil'", ")", "return", "prog" ]
Convert a QuantumFlow circuit to a pyQuil program
[ "Convert", "a", "QuantumFlow", "circuit", "to", "a", "pyQuil", "program" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L171-L185
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 isinstance(inst, pyquil.Halt): # Ignore continue if isinstance(inst, pyquil.Pragma): # TODO Barrier? continue elif isinstance(inst, pyquil.Measurement): circ += Measure(inst.qubit.index) # elif isinstance(inst, pyquil.ResetQubit): # TODO # continue elif isinstance(inst, pyquil.Gate): defgate = STDGATES[inst.name] gate = defgate(*inst.params) qubits = [q.index for q in inst.qubits] gate = gate.relabel(qubits) circ += gate else: raise ValueError('PyQuil program is not protoquil') return circ
python
def pyquil_to_circuit(program: pyquil.Program) -> Circuit: """Convert a protoquil pyQuil program to a QuantumFlow Circuit""" circ = Circuit() for inst in program.instructions: # print(type(inst)) if isinstance(inst, pyquil.Declare): # Ignore continue if isinstance(inst, pyquil.Halt): # Ignore continue if isinstance(inst, pyquil.Pragma): # TODO Barrier? continue elif isinstance(inst, pyquil.Measurement): circ += Measure(inst.qubit.index) # elif isinstance(inst, pyquil.ResetQubit): # TODO # continue elif isinstance(inst, pyquil.Gate): defgate = STDGATES[inst.name] gate = defgate(*inst.params) qubits = [q.index for q in inst.qubits] gate = gate.relabel(qubits) circ += gate else: raise ValueError('PyQuil program is not protoquil') return circ
[ "def", "pyquil_to_circuit", "(", "program", ":", "pyquil", ".", "Program", ")", "->", "Circuit", ":", "circ", "=", "Circuit", "(", ")", "for", "inst", "in", "program", ".", "instructions", ":", "# print(type(inst))", "if", "isinstance", "(", "inst", ",", "pyquil", ".", "Declare", ")", ":", "# Ignore", "continue", "if", "isinstance", "(", "inst", ",", "pyquil", ".", "Halt", ")", ":", "# Ignore", "continue", "if", "isinstance", "(", "inst", ",", "pyquil", ".", "Pragma", ")", ":", "# TODO Barrier?", "continue", "elif", "isinstance", "(", "inst", ",", "pyquil", ".", "Measurement", ")", ":", "circ", "+=", "Measure", "(", "inst", ".", "qubit", ".", "index", ")", "# elif isinstance(inst, pyquil.ResetQubit): # TODO", "# continue", "elif", "isinstance", "(", "inst", ",", "pyquil", ".", "Gate", ")", ":", "defgate", "=", "STDGATES", "[", "inst", ".", "name", "]", "gate", "=", "defgate", "(", "*", "inst", ".", "params", ")", "qubits", "=", "[", "q", ".", "index", "for", "q", "in", "inst", ".", "qubits", "]", "gate", "=", "gate", ".", "relabel", "(", "qubits", ")", "circ", "+=", "gate", "else", ":", "raise", "ValueError", "(", "'PyQuil program is not protoquil'", ")", "return", "circ" ]
Convert a protoquil pyQuil program to a QuantumFlow Circuit
[ "Convert", "a", "protoquil", "pyQuil", "program", "to", "a", "QuantumFlow", "Circuit" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L188-L213
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]) return pyquil.Wavefunction(amplitudes)
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]) return pyquil.Wavefunction(amplitudes)
[ "def", "state_to_wavefunction", "(", "state", ":", "State", ")", "->", "pyquil", ".", "Wavefunction", ":", "# TODO: qubits?", "amplitudes", "=", "state", ".", "vec", ".", "asarray", "(", ")", "# pyQuil labels states backwards.", "amplitudes", "=", "amplitudes", ".", "transpose", "(", ")", "amplitudes", "=", "amplitudes", ".", "reshape", "(", "[", "amplitudes", ".", "size", "]", ")", "return", "pyquil", ".", "Wavefunction", "(", "amplitudes", ")" ]
Convert a QuantumFlow state to a pyQuil Wavefunction
[ "Convert", "a", "QuantumFlow", "state", "to", "a", "pyQuil", "Wavefunction" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L350-L358
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._prog = prog self.program = binary self.status = 'loaded' return self
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._prog = prog self.program = binary self.status = 'loaded' return self
[ "def", "load", "(", "self", ",", "binary", ":", "pyquil", ".", "Program", ")", "->", "'QuantumFlowQVM'", ":", "assert", "self", ".", "status", "in", "[", "'connected'", ",", "'done'", "]", "prog", "=", "quil_to_program", "(", "str", "(", "binary", ")", ")", "self", ".", "_prog", "=", "prog", "self", ".", "program", "=", "binary", "self", ".", "status", "=", "'loaded'", "return", "self" ]
Load a pyQuil program, and initialize QVM into a fresh state. Args: binary: A pyQuil program
[ "Load", "a", "pyQuil", "program", "and", "initialize", "QVM", "into", "a", "fresh", "state", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L379-L394
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 # QuantumComputer calls wait() after run, which expects state to be # 'running', and whose only effect to is to set state to 'done' return self
python
def run(self) -> 'QuantumFlowQVM': """Run a previously loaded program""" assert self.status in ['loaded'] self.status = 'running' self._ket = self._prog.run() # Should set state to 'done' after run complete. # Makes no sense to keep status at running. But pyQuil's # QuantumComputer calls wait() after run, which expects state to be # 'running', and whose only effect to is to set state to 'done' return self
[ "def", "run", "(", "self", ")", "->", "'QuantumFlowQVM'", ":", "assert", "self", ".", "status", "in", "[", "'loaded'", "]", "self", ".", "status", "=", "'running'", "self", ".", "_ket", "=", "self", ".", "_prog", ".", "run", "(", ")", "# Should set state to 'done' after run complete.", "# Makes no sense to keep status at running. But pyQuil's", "# QuantumComputer calls wait() after run, which expects state to be", "# 'running', and whose only effect to is to set state to 'done'", "return", "self" ]
Run a previously loaded program
[ "Run", "a", "previously", "loaded", "program" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L401-L410
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", "wavefn" ]
Return the wavefunction of a completed program.
[ "Return", "the", "wavefunction", "of", "a", "completed", "program", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L437-L444
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[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[0].cpu().numpy() + 1.0j * tensor[1].cpu().numpy() return tensor
[ "def", "evaluate", "(", "tensor", ":", "BKTensor", ")", "->", "TensorLike", ":", "if", "isinstance", "(", "tensor", ",", "_DTYPE", ")", ":", "if", "torch", ".", "numel", "(", "tensor", ")", "==", "1", ":", "return", "tensor", ".", "item", "(", ")", "if", "tensor", ".", "numel", "(", ")", "==", "2", ":", "return", "tensor", "[", "0", "]", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "+", "1.0j", "*", "tensor", "[", "1", "]", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "return", "tensor", "[", "0", "]", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "+", "1.0j", "*", "tensor", "[", "1", "]", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "return", "tensor" ]
Return the value of a tensor
[ "Return", "the", "value", "of", "a", "tensor" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/torchbk.py#L91-L100
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", "]", ".", "size", "(", ")", ")" ]
Return the number of dimensions of a tensor
[ "Return", "the", "number", "of", "dimensions", "of", "a", "tensor" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/torchbk.py#L136-L141
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", ".", "inner", "(", "state0", ".", "tensor", ",", "state1", ".", "tensor", ")", ")", "**", "bk", ".", "fcast", "(", "2", ")", "return", "tensor" ]
Return the quantum fidelity between pure states.
[ "Return", "the", "quantum", "fidelity", "between", "pure", "states", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L32-L36
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 the linear entropy, 1- purity, and the participation ratio, 1/purity. """ tensor = rho.tensor N = rho.qubit_nb matrix = bk.reshape(tensor, [2**N, 2**N]) return bk.trace(bk.matmul(matrix, matrix))
python
def purity(rho: Density) -> bk.BKTensor: """ Calculate the purity of a mixed quantum state. Purity, defined as tr(rho^2), has an upper bound of 1 for a pure state, and a lower bound of 1/D (where D is the Hilbert space dimension) for a competently mixed state. Two closely related measures are the linear entropy, 1- purity, and the participation ratio, 1/purity. """ tensor = rho.tensor N = rho.qubit_nb matrix = bk.reshape(tensor, [2**N, 2**N]) return bk.trace(bk.matmul(matrix, matrix))
[ "def", "purity", "(", "rho", ":", "Density", ")", "->", "bk", ".", "BKTensor", ":", "tensor", "=", "rho", ".", "tensor", "N", "=", "rho", ".", "qubit_nb", "matrix", "=", "bk", ".", "reshape", "(", "tensor", ",", "[", "2", "**", "N", ",", "2", "**", "N", "]", ")", "return", "bk", ".", "trace", "(", "bk", ".", "matmul", "(", "matrix", ",", "matrix", ")", ")" ]
Calculate the purity of a mixed quantum state. Purity, defined as tr(rho^2), has an upper bound of 1 for a pure state, and a lower bound of 1/D (where D is the Hilbert space dimension) for a competently mixed state. Two closely related measures are the linear entropy, 1- purity, and the participation ratio, 1/purity.
[ "Calculate", "the", "purity", "of", "a", "mixed", "quantum", "state", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L59-L73
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.trace(op0) tr1 = np.trace(op1) return np.sqrt(tr0 + tr1 - 2.*np.sqrt(fid))
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.trace(op0) tr1 = np.trace(op1) return np.sqrt(tr0 + tr1 - 2.*np.sqrt(fid))
[ "def", "bures_distance", "(", "rho0", ":", "Density", ",", "rho1", ":", "Density", ")", "->", "float", ":", "fid", "=", "fidelity", "(", "rho0", ",", "rho1", ")", "op0", "=", "asarray", "(", "rho0", ".", "asoperator", "(", ")", ")", "op1", "=", "asarray", "(", "rho1", ".", "asoperator", "(", ")", ")", "tr0", "=", "np", ".", "trace", "(", "op0", ")", "tr1", "=", "np", ".", "trace", "(", "op1", ")", "return", "np", ".", "sqrt", "(", "tr0", "+", "tr1", "-", "2.", "*", "np", ".", "sqrt", "(", "fid", ")", ")" ]
Return the Bures distance between mixed quantum states Note: Bures distance cannot be calculated within the tensor backend.
[ "Return", "the", "Bures", "distance", "between", "mixed", "quantum", "states" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L95-L106
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: The von-Neumann entropy of rho """ op = asarray(rho.asoperator()) probs = np.linalg.eigvalsh(op) probs = np.maximum(probs, 0.0) # Compensate for floating point errors return scipy.stats.entropy(probs, base=base)
python
def entropy(rho: Density, base: float = None) -> float: """ Returns the von-Neumann entropy of a mixed quantum state. Args: rho: A density matrix base: Optional logarithm base. Default is base e, and entropy is measures in nats. For bits set base to 2. Returns: The von-Neumann entropy of rho """ op = asarray(rho.asoperator()) probs = np.linalg.eigvalsh(op) probs = np.maximum(probs, 0.0) # Compensate for floating point errors return scipy.stats.entropy(probs, base=base)
[ "def", "entropy", "(", "rho", ":", "Density", ",", "base", ":", "float", "=", "None", ")", "->", "float", ":", "op", "=", "asarray", "(", "rho", ".", "asoperator", "(", ")", ")", "probs", "=", "np", ".", "linalg", ".", "eigvalsh", "(", "op", ")", "probs", "=", "np", ".", "maximum", "(", "probs", ",", "0.0", ")", "# Compensate for floating point errors", "return", "scipy", ".", "stats", ".", "entropy", "(", "probs", ",", "base", "=", "base", ")" ]
Returns the von-Neumann entropy of a mixed quantum state. Args: rho: A density matrix base: Optional logarithm base. Default is base e, and entropy is measures in nats. For bits set base to 2. Returns: The von-Neumann entropy of rho
[ "Returns", "the", "von", "-", "Neumann", "entropy", "of", "a", "mixed", "quantum", "state", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L133-L148
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 qubits0: Qubits of system 0 qubits1: Qubits of system 1. If none, taken to be all remaining qubits base: Optional logarithm base. Default is base e Returns: The bipartite von-Neumann mutual information. """ if qubits1 is None: qubits1 = tuple(set(rho.qubits) - set(qubits0)) rho0 = rho.partial_trace(qubits1) rho1 = rho.partial_trace(qubits0) ent = entropy(rho, base) ent0 = entropy(rho0, base) ent1 = entropy(rho1, base) return ent0 + ent1 - ent
python
def mutual_info(rho: Density, qubits0: Qubits, qubits1: Qubits = None, base: float = None) -> float: """Compute the bipartite von-Neumann mutual information of a mixed quantum state. Args: rho: A density matrix of the complete system qubits0: Qubits of system 0 qubits1: Qubits of system 1. If none, taken to be all remaining qubits base: Optional logarithm base. Default is base e Returns: The bipartite von-Neumann mutual information. """ if qubits1 is None: qubits1 = tuple(set(rho.qubits) - set(qubits0)) rho0 = rho.partial_trace(qubits1) rho1 = rho.partial_trace(qubits0) ent = entropy(rho, base) ent0 = entropy(rho0, base) ent1 = entropy(rho1, base) return ent0 + ent1 - ent
[ "def", "mutual_info", "(", "rho", ":", "Density", ",", "qubits0", ":", "Qubits", ",", "qubits1", ":", "Qubits", "=", "None", ",", "base", ":", "float", "=", "None", ")", "->", "float", ":", "if", "qubits1", "is", "None", ":", "qubits1", "=", "tuple", "(", "set", "(", "rho", ".", "qubits", ")", "-", "set", "(", "qubits0", ")", ")", "rho0", "=", "rho", ".", "partial_trace", "(", "qubits1", ")", "rho1", "=", "rho", ".", "partial_trace", "(", "qubits0", ")", "ent", "=", "entropy", "(", "rho", ",", "base", ")", "ent0", "=", "entropy", "(", "rho0", ",", "base", ")", "ent1", "=", "entropy", "(", "rho1", ",", "base", ")", "return", "ent0", "+", "ent1", "-", "ent" ]
Compute the bipartite von-Neumann mutual information of a mixed quantum state. Args: rho: A density matrix of the complete system qubits0: Qubits of system 0 qubits1: Qubits of system 1. If none, taken to be all remaining qubits base: Optional logarithm base. Default is base e Returns: The bipartite von-Neumann mutual information.
[ "Compute", "the", "bipartite", "von", "-", "Neumann", "mutual", "information", "of", "a", "mixed", "quantum", "state", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L152-L178
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 match') vec1 = vec1.permute(vec0.qubits) # Make sure qubits in same order return bk.inner(vec0.tensor, vec1.tensor)
python
def inner_product(vec0: QubitVector, vec1: QubitVector) -> bk.BKTensor: """ Hilbert-Schmidt inner product between qubit vectors The tensor rank and qubits must match. """ if vec0.rank != vec1.rank or vec0.qubit_nb != vec1.qubit_nb: raise ValueError('Incompatibly vectors. Qubits and rank must match') vec1 = vec1.permute(vec0.qubits) # Make sure qubits in same order return bk.inner(vec0.tensor, vec1.tensor)
[ "def", "inner_product", "(", "vec0", ":", "QubitVector", ",", "vec1", ":", "QubitVector", ")", "->", "bk", ".", "BKTensor", ":", "if", "vec0", ".", "rank", "!=", "vec1", ".", "rank", "or", "vec0", ".", "qubit_nb", "!=", "vec1", ".", "qubit_nb", ":", "raise", "ValueError", "(", "'Incompatibly vectors. Qubits and rank must match'", ")", "vec1", "=", "vec1", ".", "permute", "(", "vec0", ".", "qubits", ")", "# Make sure qubits in same order", "return", "bk", ".", "inner", "(", "vec0", ".", "tensor", ",", "vec1", ".", "tensor", ")" ]
Hilbert-Schmidt inner product between qubit vectors The tensor rank and qubits must match.
[ "Hilbert", "-", "Schmidt", "inner", "product", "between", "qubit", "vectors" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L233-L242
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 vectors. Rank must match') if not set(vec0.qubits).isdisjoint(vec1.qubits): raise ValueError('Overlapping qubits') qubits: Qubits = tuple(vec0.qubits) + tuple(vec1.qubits) tensor = bk.outer(vec0.tensor, vec1.tensor) # Interleave (super)-operator axes # R = 1 perm = (0, 1) # R = 2 perm = (0, 2, 1, 3) # R = 4 perm = (0, 4, 1, 5, 2, 6, 3, 7) tensor = bk.reshape(tensor, ([2**N0] * R) + ([2**N1] * R)) perm = [idx for ij in zip(range(0, R), range(R, 2*R)) for idx in ij] tensor = bk.transpose(tensor, perm) return QubitVector(tensor, qubits)
python
def outer_product(vec0: QubitVector, vec1: QubitVector) -> QubitVector: """Direct product of qubit vectors The tensor ranks must match and qubits must be disjoint. """ R = vec0.rank R1 = vec1.rank N0 = vec0.qubit_nb N1 = vec1.qubit_nb if R != R1: raise ValueError('Incompatibly vectors. Rank must match') if not set(vec0.qubits).isdisjoint(vec1.qubits): raise ValueError('Overlapping qubits') qubits: Qubits = tuple(vec0.qubits) + tuple(vec1.qubits) tensor = bk.outer(vec0.tensor, vec1.tensor) # Interleave (super)-operator axes # R = 1 perm = (0, 1) # R = 2 perm = (0, 2, 1, 3) # R = 4 perm = (0, 4, 1, 5, 2, 6, 3, 7) tensor = bk.reshape(tensor, ([2**N0] * R) + ([2**N1] * R)) perm = [idx for ij in zip(range(0, R), range(R, 2*R)) for idx in ij] tensor = bk.transpose(tensor, perm) return QubitVector(tensor, qubits)
[ "def", "outer_product", "(", "vec0", ":", "QubitVector", ",", "vec1", ":", "QubitVector", ")", "->", "QubitVector", ":", "R", "=", "vec0", ".", "rank", "R1", "=", "vec1", ".", "rank", "N0", "=", "vec0", ".", "qubit_nb", "N1", "=", "vec1", ".", "qubit_nb", "if", "R", "!=", "R1", ":", "raise", "ValueError", "(", "'Incompatibly vectors. Rank must match'", ")", "if", "not", "set", "(", "vec0", ".", "qubits", ")", ".", "isdisjoint", "(", "vec1", ".", "qubits", ")", ":", "raise", "ValueError", "(", "'Overlapping qubits'", ")", "qubits", ":", "Qubits", "=", "tuple", "(", "vec0", ".", "qubits", ")", "+", "tuple", "(", "vec1", ".", "qubits", ")", "tensor", "=", "bk", ".", "outer", "(", "vec0", ".", "tensor", ",", "vec1", ".", "tensor", ")", "# Interleave (super)-operator axes", "# R = 1 perm = (0, 1)", "# R = 2 perm = (0, 2, 1, 3)", "# R = 4 perm = (0, 4, 1, 5, 2, 6, 3, 7)", "tensor", "=", "bk", ".", "reshape", "(", "tensor", ",", "(", "[", "2", "**", "N0", "]", "*", "R", ")", "+", "(", "[", "2", "**", "N1", "]", "*", "R", ")", ")", "perm", "=", "[", "idx", "for", "ij", "in", "zip", "(", "range", "(", "0", ",", "R", ")", ",", "range", "(", "R", ",", "2", "*", "R", ")", ")", "for", "idx", "in", "ij", "]", "tensor", "=", "bk", ".", "transpose", "(", "tensor", ",", "perm", ")", "return", "QubitVector", "(", "tensor", ",", "qubits", ")" ]
Direct product of qubit vectors The tensor ranks must match and qubits must be disjoint.
[ "Direct", "product", "of", "qubit", "vectors" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L248-L277
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.qubit_nb != vec1.qubit_nb: return False if set(vec0.qubits) ^ set(vec1.qubits): return False return bk.evaluate(fubini_study_angle(vec0, vec1)) <= tolerance
python
def vectors_close(vec0: QubitVector, vec1: QubitVector, tolerance: float = TOLERANCE) -> bool: """Return True if vectors in close in the projective Hilbert space. Similarity is measured with the Fubini–Study metric. """ if vec0.rank != vec1.rank: return False if vec0.qubit_nb != vec1.qubit_nb: return False if set(vec0.qubits) ^ set(vec1.qubits): return False return bk.evaluate(fubini_study_angle(vec0, vec1)) <= tolerance
[ "def", "vectors_close", "(", "vec0", ":", "QubitVector", ",", "vec1", ":", "QubitVector", ",", "tolerance", ":", "float", "=", "TOLERANCE", ")", "->", "bool", ":", "if", "vec0", ".", "rank", "!=", "vec1", ".", "rank", ":", "return", "False", "if", "vec0", ".", "qubit_nb", "!=", "vec1", ".", "qubit_nb", ":", "return", "False", "if", "set", "(", "vec0", ".", "qubits", ")", "^", "set", "(", "vec1", ".", "qubits", ")", ":", "return", "False", "return", "bk", ".", "evaluate", "(", "fubini_study_angle", "(", "vec0", ",", "vec1", ")", ")", "<=", "tolerance" ]
Return True if vectors in close in the projective Hilbert space. Similarity is measured with the Fubini–Study metric.
[ "Return", "True", "if", "vectors", "in", "close", "in", "the", "projective", "Hilbert", "space", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L310-L325
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", ".", "qubits", "=", "qubits", "return", "vec" ]
Return a copy of this vector with new qubits
[ "Return", "a", "copy", "of", "this", "vector", "with", "new", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L137-L143
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.reshape(tensor, [2] * R * N) tensor = bk.conj(tensor) return QubitVector(tensor, self.qubits)
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.reshape(tensor, [2] * R * N) tensor = bk.conj(tensor) return QubitVector(tensor, self.qubits)
[ "def", "H", "(", "self", ")", "->", "'QubitVector'", ":", "N", "=", "self", ".", "qubit_nb", "R", "=", "self", ".", "rank", "# (super) operator transpose", "tensor", "=", "self", ".", "tensor", "tensor", "=", "bk", ".", "reshape", "(", "tensor", ",", "[", "2", "**", "(", "N", "*", "R", "//", "2", ")", "]", "*", "2", ")", "tensor", "=", "bk", ".", "transpose", "(", "tensor", ")", "tensor", "=", "bk", ".", "reshape", "(", "tensor", ",", "[", "2", "]", "*", "R", "*", "N", ")", "tensor", "=", "bk", ".", "conj", "(", "tensor", ")", "return", "QubitVector", "(", "tensor", ",", "self", ".", "qubits", ")" ]
Return the conjugate transpose of this tensor.
[ "Return", "the", "conjugate", "transpose", "of", "this", "tensor", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L165-L178
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) for q in qubits: new_qubits.remove(q) if not new_qubits: raise ValueError('Cannot remove all qubits with partial_trace.') indices = [self.qubits.index(qubit) for qubit in qubits] subscripts = list(EINSUM_SUBSCRIPTS)[0:N*R] for idx in indices: for r in range(1, R): subscripts[r * N + idx] = subscripts[idx] subscript_str = ''.join(subscripts) # Only numpy's einsum works with repeated subscripts tensor = self.asarray() tensor = np.einsum(subscript_str, tensor) return QubitVector(tensor, new_qubits)
python
def partial_trace(self, qubits: Qubits) -> 'QubitVector': """ Return the partial trace over some subset of qubits""" N = self.qubit_nb R = self.rank if R == 1: raise ValueError('Cannot take trace of vector') new_qubits: List[Qubit] = list(self.qubits) for q in qubits: new_qubits.remove(q) if not new_qubits: raise ValueError('Cannot remove all qubits with partial_trace.') indices = [self.qubits.index(qubit) for qubit in qubits] subscripts = list(EINSUM_SUBSCRIPTS)[0:N*R] for idx in indices: for r in range(1, R): subscripts[r * N + idx] = subscripts[idx] subscript_str = ''.join(subscripts) # Only numpy's einsum works with repeated subscripts tensor = self.asarray() tensor = np.einsum(subscript_str, tensor) return QubitVector(tensor, new_qubits)
[ "def", "partial_trace", "(", "self", ",", "qubits", ":", "Qubits", ")", "->", "'QubitVector'", ":", "N", "=", "self", ".", "qubit_nb", "R", "=", "self", ".", "rank", "if", "R", "==", "1", ":", "raise", "ValueError", "(", "'Cannot take trace of vector'", ")", "new_qubits", ":", "List", "[", "Qubit", "]", "=", "list", "(", "self", ".", "qubits", ")", "for", "q", "in", "qubits", ":", "new_qubits", ".", "remove", "(", "q", ")", "if", "not", "new_qubits", ":", "raise", "ValueError", "(", "'Cannot remove all qubits with partial_trace.'", ")", "indices", "=", "[", "self", ".", "qubits", ".", "index", "(", "qubit", ")", "for", "qubit", "in", "qubits", "]", "subscripts", "=", "list", "(", "EINSUM_SUBSCRIPTS", ")", "[", "0", ":", "N", "*", "R", "]", "for", "idx", "in", "indices", ":", "for", "r", "in", "range", "(", "1", ",", "R", ")", ":", "subscripts", "[", "r", "*", "N", "+", "idx", "]", "=", "subscripts", "[", "idx", "]", "subscript_str", "=", "''", ".", "join", "(", "subscripts", ")", "# Only numpy's einsum works with repeated subscripts", "tensor", "=", "self", ".", "asarray", "(", ")", "tensor", "=", "np", ".", "einsum", "(", "subscript_str", ",", "tensor", ")", "return", "QubitVector", "(", "tensor", ",", "new_qubits", ")" ]
Return the partial trace over some subset of qubits
[ "Return", "the", "partial", "trace", "over", "some", "subset", "of", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L201-L227
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.random.normal([3])) def loss_fn(): """Loss""" gate = qf.ZYZ(t[0], t[1], t[2]) ang = qf.fubini_study_angle(target_gate.vec, gate.vec) return ang opt = tf.optimizers.Adam(learning_rate=0.001) opt.minimize(loss_fn, var_list=[t]) for step in range(steps): opt.minimize(loss_fn, var_list=[t]) loss = loss_fn() print(step, loss.numpy()) if loss < 0.01: break else: print("Failed to coverge") return bk.evaluate(t)
python
def fit_zyz(target_gate): """ Tensorflow 2.0 example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate. """ steps = 1000 dev = '/gpu:0' if bk.DEVICE == 'gpu' else '/cpu:0' with tf.device(dev): t = tf.Variable(tf.random.normal([3])) def loss_fn(): """Loss""" gate = qf.ZYZ(t[0], t[1], t[2]) ang = qf.fubini_study_angle(target_gate.vec, gate.vec) return ang opt = tf.optimizers.Adam(learning_rate=0.001) opt.minimize(loss_fn, var_list=[t]) for step in range(steps): opt.minimize(loss_fn, var_list=[t]) loss = loss_fn() print(step, loss.numpy()) if loss < 0.01: break else: print("Failed to coverge") return bk.evaluate(t)
[ "def", "fit_zyz", "(", "target_gate", ")", ":", "steps", "=", "1000", "dev", "=", "'/gpu:0'", "if", "bk", ".", "DEVICE", "==", "'gpu'", "else", "'/cpu:0'", "with", "tf", ".", "device", "(", "dev", ")", ":", "t", "=", "tf", ".", "Variable", "(", "tf", ".", "random", ".", "normal", "(", "[", "3", "]", ")", ")", "def", "loss_fn", "(", ")", ":", "\"\"\"Loss\"\"\"", "gate", "=", "qf", ".", "ZYZ", "(", "t", "[", "0", "]", ",", "t", "[", "1", "]", ",", "t", "[", "2", "]", ")", "ang", "=", "qf", ".", "fubini_study_angle", "(", "target_gate", ".", "vec", ",", "gate", ".", "vec", ")", "return", "ang", "opt", "=", "tf", ".", "optimizers", ".", "Adam", "(", "learning_rate", "=", "0.001", ")", "opt", ".", "minimize", "(", "loss_fn", ",", "var_list", "=", "[", "t", "]", ")", "for", "step", "in", "range", "(", "steps", ")", ":", "opt", ".", "minimize", "(", "loss_fn", ",", "var_list", "=", "[", "t", "]", ")", "loss", "=", "loss_fn", "(", ")", "print", "(", "step", ",", "loss", ".", "numpy", "(", ")", ")", "if", "loss", "<", "0.01", ":", "break", "else", ":", "print", "(", "\"Failed to coverge\"", ")", "return", "bk", ".", "evaluate", "(", "t", ")" ]
Tensorflow 2.0 example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate.
[ "Tensorflow", "2", ".", "0", "example", ".", "Given", "an", "arbitrary", "one", "-", "qubit", "gate", "use", "gradient", "descent", "to", "find", "corresponding", "parameters", "of", "a", "universal", "ZYZ", "gate", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/examples/tensorflow2_fit_gate.py#L21-L53
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(qubits) ket = self._initilize(ket) pc = 0 while pc >= 0 and pc < len(self): instr = self.instructions[pc] ket = ket.update({PC: pc + 1}) ket = instr.run(ket) pc = ket.memory[PC] return ket
python
def run(self, ket: State = None) -> State: """Compiles and runs a program. The optional program argument supplies the initial state and memory. Else qubits and classical bits start from zero states. """ if ket is None: qubits = self.qubits ket = zero_state(qubits) ket = self._initilize(ket) pc = 0 while pc >= 0 and pc < len(self): instr = self.instructions[pc] ket = ket.update({PC: pc + 1}) ket = instr.run(ket) pc = ket.memory[PC] return ket
[ "def", "run", "(", "self", ",", "ket", ":", "State", "=", "None", ")", "->", "State", ":", "if", "ket", "is", "None", ":", "qubits", "=", "self", ".", "qubits", "ket", "=", "zero_state", "(", "qubits", ")", "ket", "=", "self", ".", "_initilize", "(", "ket", ")", "pc", "=", "0", "while", "pc", ">=", "0", "and", "pc", "<", "len", "(", "self", ")", ":", "instr", "=", "self", ".", "instructions", "[", "pc", "]", "ket", "=", "ket", ".", "update", "(", "{", "PC", ":", "pc", "+", "1", "}", ")", "ket", "=", "instr", ".", "run", "(", "ket", ")", "pc", "=", "ket", ".", "memory", "[", "PC", "]", "return", "ket" ]
Compiles and runs a program. The optional program argument supplies the initial state and memory. Else qubits and classical bits start from zero states.
[ "Compiles", "and", "runs", "a", "program", ".", "The", "optional", "program", "argument", "supplies", "the", "initial", "state", "and", "memory", ".", "Else", "qubits", "and", "classical", "bits", "start", "from", "zero", "states", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/programs.py#L152-L170
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", ".", "tensormul", "(", "self", ".", "tensor", ",", "ket", ".", "tensor", ",", "indices", ")", "return", "State", "(", "tensor", ",", "ket", ".", "qubits", ",", "ket", ".", "memory", ")" ]
Apply the action of this gate upon a state
[ "Apply", "the", "action", "of", "this", "gate", "upon", "a", "state" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L161-L166
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", ".", "reshape", "(", "tensor", ",", "[", "2", "**", "N", "]", "*", "R", ")", "tensor", "=", "bk", ".", "transpose", "(", "tensor", ",", "[", "0", ",", "3", ",", "1", ",", "2", "]", ")", "return", "Channel", "(", "tensor", ",", "self", ".", "qubits", ")" ]
Converts a Gate into a Channel
[ "Converts", "a", "Gate", "into", "a", "Channel" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L243-L252
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", "/", "rank", ")", "return", "Gate", "(", "tensor", "=", "U", ",", "qubits", "=", "self", ".", "qubits", ")" ]
Convert gate tensor to the special unitary group.
[ "Convert", "gate", "tensor", "to", "the", "special", "unitary", "group", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L254-L259
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 :math:`S` is a Hermitian-map (i.e. transforms Hermitian operators to hJrmitian operators) Flattening the :math:`S^\#` superoperator to a matrix gives the Choi matrix representation. (See channel.choi()) """ N = self.qubit_nb tensor = self.tensor tensor = bk.reshape(tensor, [2**N] * 4) tensor = bk.transpose(tensor, (0, 2, 1, 3)) tensor = bk.reshape(tensor, [2] * 4 * N) return Channel(tensor, self.qubits)
python
def sharp(self) -> 'Channel': r"""Return the 'sharp' transpose of the superoperator. The transpose :math:`S^\#` switches the two covariant (bra) indices of the superoperator. (Which in our representation are the 2nd and 3rd super-indices) If :math:`S^\#` is Hermitian, then :math:`S` is a Hermitian-map (i.e. transforms Hermitian operators to hJrmitian operators) Flattening the :math:`S^\#` superoperator to a matrix gives the Choi matrix representation. (See channel.choi()) """ N = self.qubit_nb tensor = self.tensor tensor = bk.reshape(tensor, [2**N] * 4) tensor = bk.transpose(tensor, (0, 2, 1, 3)) tensor = bk.reshape(tensor, [2] * 4 * N) return Channel(tensor, self.qubits)
[ "def", "sharp", "(", "self", ")", "->", "'Channel'", ":", "N", "=", "self", ".", "qubit_nb", "tensor", "=", "self", ".", "tensor", "tensor", "=", "bk", ".", "reshape", "(", "tensor", ",", "[", "2", "**", "N", "]", "*", "4", ")", "tensor", "=", "bk", ".", "transpose", "(", "tensor", ",", "(", "0", ",", "2", ",", "1", ",", "3", ")", ")", "tensor", "=", "bk", ".", "reshape", "(", "tensor", ",", "[", "2", "]", "*", "4", "*", "N", ")", "return", "Channel", "(", "tensor", ",", "self", ".", "qubits", ")" ]
r"""Return the 'sharp' transpose of the superoperator. The transpose :math:`S^\#` switches the two covariant (bra) indices of the superoperator. (Which in our representation are the 2nd and 3rd super-indices) If :math:`S^\#` is Hermitian, then :math:`S` is a Hermitian-map (i.e. transforms Hermitian operators to hJrmitian operators) Flattening the :math:`S^\#` superoperator to a matrix gives the Choi matrix representation. (See channel.choi())
[ "r", "Return", "the", "sharp", "transpose", "of", "the", "superoperator", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L315-L335
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", "**", "(", "N", "*", "2", ")", "]", "*", "2", ")" ]
Return the Choi matrix representation of this super operator
[ "Return", "the", "Choi", "matrix", "representation", "of", "this", "super", "operator" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L337-L342
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(self.tensor, rho.tensor, indices) return Density(tensor, qubits, rho.memory)
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(self.tensor, rho.tensor, indices) return Density(tensor, qubits, rho.memory)
[ "def", "evolve", "(", "self", ",", "rho", ":", "Density", ")", "->", "Density", ":", "N", "=", "rho", ".", "qubit_nb", "qubits", "=", "rho", ".", "qubits", "indices", "=", "list", "(", "[", "qubits", ".", "index", "(", "q", ")", "for", "q", "in", "self", ".", "qubits", "]", ")", "+", "list", "(", "[", "qubits", ".", "index", "(", "q", ")", "+", "N", "for", "q", "in", "self", ".", "qubits", "]", ")", "tensor", "=", "bk", ".", "tensormul", "(", "self", ".", "tensor", ",", "rho", ".", "tensor", ",", "indices", ")", "return", "Density", "(", "tensor", ",", "qubits", ",", "rho", ".", "memory", ")" ]
Apply the action of this channel upon a density
[ "Apply", "the", "action", "of", "this", "channel", "upon", "a", "density" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L354-L363
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? # pragma: no cover", "return", "newvalue" ]
Cast to float tensor
[ "Cast", "to", "float", "tensor" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/eagerbk.py#L52-L57
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 = tf.reshape(tensor, ([2]*N)) return 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 = tf.reshape(tensor, ([2]*N)) return tensor
[ "def", "astensor", "(", "array", ":", "TensorLike", ")", "->", "BKTensor", ":", "tensor", "=", "tf", ".", "convert_to_tensor", "(", "array", ",", "dtype", "=", "CTYPE", ")", "if", "DEVICE", "==", "'gpu'", ":", "tensor", "=", "tensor", ".", "gpu", "(", ")", "# pragma: no cover", "# size = np.prod(np.array(tensor.get_shape().as_list()))", "N", "=", "int", "(", "math", ".", "log2", "(", "size", "(", "tensor", ")", ")", ")", "tensor", "=", "tf", ".", "reshape", "(", "tensor", ",", "(", "[", "2", "]", "*", "N", ")", ")", "return", "tensor" ]
Convert to product tensor
[ "Convert", "to", "product", "tensor" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/eagerbk.py#L60-L70
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_count[type(elem)] += 1 return dict(op_count)
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_count[type(elem)] += 1 return dict(op_count)
[ "def", "count_operations", "(", "elements", ":", "Iterable", "[", "Operation", "]", ")", "->", "Dict", "[", "Type", "[", "Operation", "]", ",", "int", "]", ":", "op_count", ":", "Dict", "[", "Type", "[", "Operation", "]", ",", "int", "]", "=", "defaultdict", "(", "int", ")", "for", "elem", "in", "elements", ":", "op_count", "[", "type", "(", "elem", ")", "]", "+=", "1", "return", "dict", "(", "op_count", ")" ]
Return a count of different operation types given a colelction of operations, such as a Circuit or DAGCircuit
[ "Return", "a", "count", "of", "different", "operation", "types", "given", "a", "colelction", "of", "operations", "such", "as", "a", "Circuit", "or", "DAGCircuit" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L141-L149
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) return circ
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) return circ
[ "def", "map_gate", "(", "gate", ":", "Gate", ",", "args", ":", "Sequence", "[", "Qubits", "]", ")", "->", "Circuit", ":", "circ", "=", "Circuit", "(", ")", "for", "qubits", "in", "args", ":", "circ", "+=", "gate", ".", "relabel", "(", "qubits", ")", "return", "circ" ]
Applies the same gate all input qubits in the argument list. >>> circ = qf.map_gate(qf.H(), [[0], [1], [2]]) >>> print(circ) H(0) H(1) H(2)
[ "Applies", "the", "same", "gate", "all", "input", "qubits", "in", "the", "argument", "list", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L152-L167
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): q1 = qubits[n1] angle = pi / 2 ** (n1-n0) circ += CPHASE(angle, q1, q0) circ.extend(reversal_circuit(qubits)) return circ
python
def qft_circuit(qubits: Qubits) -> Circuit: """Returns the Quantum Fourier Transform circuit""" # Kudos: Adapted from Rigetti Grove, grove/qft/fourier.py N = len(qubits) circ = Circuit() for n0 in range(N): q0 = qubits[n0] circ += H(q0) for n1 in range(n0+1, N): q1 = qubits[n1] angle = pi / 2 ** (n1-n0) circ += CPHASE(angle, q1, q0) circ.extend(reversal_circuit(qubits)) return circ
[ "def", "qft_circuit", "(", "qubits", ":", "Qubits", ")", "->", "Circuit", ":", "# Kudos: Adapted from Rigetti Grove, grove/qft/fourier.py", "N", "=", "len", "(", "qubits", ")", "circ", "=", "Circuit", "(", ")", "for", "n0", "in", "range", "(", "N", ")", ":", "q0", "=", "qubits", "[", "n0", "]", "circ", "+=", "H", "(", "q0", ")", "for", "n1", "in", "range", "(", "n0", "+", "1", ",", "N", ")", ":", "q1", "=", "qubits", "[", "n1", "]", "angle", "=", "pi", "/", "2", "**", "(", "n1", "-", "n0", ")", "circ", "+=", "CPHASE", "(", "angle", ",", "q1", ",", "q0", ")", "circ", ".", "extend", "(", "reversal_circuit", "(", "qubits", ")", ")", "return", "circ" ]
Returns the Quantum Fourier Transform circuit
[ "Returns", "the", "Quantum", "Fourier", "Transform", "circuit" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L170-L184
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", "(", "qubits", "[", "n", "]", ",", "qubits", "[", "N", "-", "1", "-", "n", "]", ")", "return", "circ" ]
Returns a circuit to reverse qubits
[ "Returns", "a", "circuit", "to", "reverse", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L187-L193
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", "+=", "TY", "(", "t1", ",", "q0", ")", "circ", "+=", "TZ", "(", "t2", ",", "q0", ")", "return", "circ" ]
Circuit equivalent of 1-qubit ZYZ gate
[ "Circuit", "equivalent", "of", "1", "-", "qubit", "ZYZ", "gate" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L260-L266
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. After evolution and measurement, the output qubits will be (approximately) a binary fraction representation of the phase. The output registers can be converted with the aid of the quantumflow.utils.bitlist_to_int() method. >>> import numpy as np >>> import quantumflow as qf >>> N = 8 >>> phase = 1/4 >>> gate = qf.RZ(-4*np.pi*phase, N) >>> circ = qf.phase_estimation_circuit(gate, range(N)) >>> res = circ.run().measure()[0:N] >>> est_phase = int(''.join([str(d) for d in res]), 2) / 2**N # To float >>> print(phase, est_phase) 0.25 0.25 """ circ = Circuit() circ += map_gate(H(), list(zip(outputs))) # Hadamard on all output qubits for cq in reversed(outputs): cgate = control_gate(cq, gate) circ += cgate gate = gate @ gate circ += qft_circuit(outputs).H return circ
python
def phase_estimation_circuit(gate: Gate, outputs: Qubits) -> Circuit: """Returns a circuit for quantum phase estimation. The gate has an eigenvector with eigenvalue e^(i 2 pi phase). To run the circuit, the eigenvector should be set on the gate qubits, and the output qubits should be in the zero state. After evolution and measurement, the output qubits will be (approximately) a binary fraction representation of the phase. The output registers can be converted with the aid of the quantumflow.utils.bitlist_to_int() method. >>> import numpy as np >>> import quantumflow as qf >>> N = 8 >>> phase = 1/4 >>> gate = qf.RZ(-4*np.pi*phase, N) >>> circ = qf.phase_estimation_circuit(gate, range(N)) >>> res = circ.run().measure()[0:N] >>> est_phase = int(''.join([str(d) for d in res]), 2) / 2**N # To float >>> print(phase, est_phase) 0.25 0.25 """ circ = Circuit() circ += map_gate(H(), list(zip(outputs))) # Hadamard on all output qubits for cq in reversed(outputs): cgate = control_gate(cq, gate) circ += cgate gate = gate @ gate circ += qft_circuit(outputs).H return circ
[ "def", "phase_estimation_circuit", "(", "gate", ":", "Gate", ",", "outputs", ":", "Qubits", ")", "->", "Circuit", ":", "circ", "=", "Circuit", "(", ")", "circ", "+=", "map_gate", "(", "H", "(", ")", ",", "list", "(", "zip", "(", "outputs", ")", ")", ")", "# Hadamard on all output qubits", "for", "cq", "in", "reversed", "(", "outputs", ")", ":", "cgate", "=", "control_gate", "(", "cq", ",", "gate", ")", "circ", "+=", "cgate", "gate", "=", "gate", "@", "gate", "circ", "+=", "qft_circuit", "(", "outputs", ")", ".", "H", "return", "circ" ]
Returns a circuit for quantum phase estimation. The gate has an eigenvector with eigenvalue e^(i 2 pi phase). To run the circuit, the eigenvector should be set on the gate qubits, and the output qubits should be in the zero state. After evolution and measurement, the output qubits will be (approximately) a binary fraction representation of the phase. The output registers can be converted with the aid of the quantumflow.utils.bitlist_to_int() method. >>> import numpy as np >>> import quantumflow as qf >>> N = 8 >>> phase = 1/4 >>> gate = qf.RZ(-4*np.pi*phase, N) >>> circ = qf.phase_estimation_circuit(gate, range(N)) >>> res = circ.run().measure()[0:N] >>> est_phase = int(''.join([str(d) for d in res]), 2) / 2**N # To float >>> print(phase, est_phase) 0.25 0.25
[ "Returns", "a", "circuit", "for", "quantum", "phase", "estimation", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L269-L303
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", ")", ":", "circ", "+=", "CNOT", "(", "qubits", "[", "q0", "]", ",", "qubits", "[", "q0", "+", "1", "]", ")", "return", "circ" ]
Returns a circuit that prepares a multi-qubit Bell state from the zero state.
[ "Returns", "a", "circuit", "that", "prepares", "a", "multi", "-", "qubit", "Bell", "state", "from", "the", "zero", "state", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L359-L369
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", ".", "elements", ".", "extend", "(", "[", "other", "]", ")" ]
Append gates from circuit to the end of this circuit
[ "Append", "gates", "from", "circuit", "to", "the", "end", "of", "this", "circuit" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L53-L58
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 self.elements: ket = elem.run(ket) return ket
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 self.elements: ket = elem.run(ket) return ket
[ "def", "run", "(", "self", ",", "ket", ":", "State", "=", "None", ")", "->", "State", ":", "if", "ket", "is", "None", ":", "qubits", "=", "self", ".", "qubits", "ket", "=", "zero_state", "(", "qubits", "=", "qubits", ")", "for", "elem", "in", "self", ".", "elements", ":", "ket", "=", "elem", ".", "run", "(", "ket", ")", "return", "ket" ]
Apply the action of this circuit upon a state. If no initial state provided an initial zero state will be created.
[ "Apply", "the", "action", "of", "this", "circuit", "upon", "a", "state", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L87-L99
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", "(", "vec", ".", "tensor", ",", "vec", ".", "qubits", ")" ]
Join two channels acting on different qubits into a single channel acting on all qubits
[ "Join", "two", "channels", "acting", "on", "different", "qubits", "into", "a", "single", "channel", "acting", "on", "all", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L170-L175
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.allclose(evals.imag, 0.0) # FIXME exception assert np.all(evals.real >= 0.0) # FIXME exception values = np.sqrt(evals.real) ops = [] for i in range(2**(2*N)): if not np.isclose(values[i], 0.0): mat = np.reshape(evecs[i], (2**N, 2**N))*values[i] g = Gate(mat, qubits) ops.append(g) return Kraus(ops)
python
def channel_to_kraus(chan: Channel) -> 'Kraus': """Convert a channel superoperator into a Kraus operator representation of the same channel.""" qubits = chan.qubits N = chan.qubit_nb choi = asarray(chan.choi()) evals, evecs = np.linalg.eig(choi) evecs = np.transpose(evecs) assert np.allclose(evals.imag, 0.0) # FIXME exception assert np.all(evals.real >= 0.0) # FIXME exception values = np.sqrt(evals.real) ops = [] for i in range(2**(2*N)): if not np.isclose(values[i], 0.0): mat = np.reshape(evecs[i], (2**N, 2**N))*values[i] g = Gate(mat, qubits) ops.append(g) return Kraus(ops)
[ "def", "channel_to_kraus", "(", "chan", ":", "Channel", ")", "->", "'Kraus'", ":", "qubits", "=", "chan", ".", "qubits", "N", "=", "chan", ".", "qubit_nb", "choi", "=", "asarray", "(", "chan", ".", "choi", "(", ")", ")", "evals", ",", "evecs", "=", "np", ".", "linalg", ".", "eig", "(", "choi", ")", "evecs", "=", "np", ".", "transpose", "(", "evecs", ")", "assert", "np", ".", "allclose", "(", "evals", ".", "imag", ",", "0.0", ")", "# FIXME exception", "assert", "np", ".", "all", "(", "evals", ".", "real", ">=", "0.0", ")", "# FIXME exception", "values", "=", "np", ".", "sqrt", "(", "evals", ".", "real", ")", "ops", "=", "[", "]", "for", "i", "in", "range", "(", "2", "**", "(", "2", "*", "N", ")", ")", ":", "if", "not", "np", ".", "isclose", "(", "values", "[", "i", "]", ",", "0.0", ")", ":", "mat", "=", "np", ".", "reshape", "(", "evecs", "[", "i", "]", ",", "(", "2", "**", "N", ",", "2", "**", "N", ")", ")", "*", "values", "[", "i", "]", "g", "=", "Gate", "(", "mat", ",", "qubits", ")", "ops", ".", "append", "(", "g", ")", "return", "Kraus", "(", "ops", ")" ]
Convert a channel superoperator into a Kraus operator representation of the same channel.
[ "Convert", "a", "channel", "superoperator", "into", "a", "Kraus", "operator", "representation", "of", "the", "same", "channel", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L181-L203
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) newket = np.random.choice(res, p=probs) return newket.normalize()
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) newket = np.random.choice(res, p=probs) return newket.normalize()
[ "def", "run", "(", "self", ",", "ket", ":", "State", ")", "->", "State", ":", "res", "=", "[", "op", ".", "run", "(", "ket", ")", "for", "op", "in", "self", ".", "operators", "]", "probs", "=", "[", "asarray", "(", "ket", ".", "norm", "(", ")", ")", "*", "w", "for", "ket", ",", "w", "in", "zip", "(", "res", ",", "self", ".", "weights", ")", "]", "probs", "=", "np", ".", "asarray", "(", "probs", ")", "probs", "/=", "np", ".", "sum", "(", "probs", ")", "newket", "=", "np", ".", "random", ".", "choice", "(", "res", ",", "p", "=", "probs", ")", "return", "newket", ".", "normalize", "(", ")" ]
Apply the action of this Kraus quantum operation upon a state
[ "Apply", "the", "action", "of", "this", "Kraus", "quantum", "operation", "upon", "a", "state" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L70-L77
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, tensors) return Density(tensor, qubits)
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, tensors) return Density(tensor, qubits)
[ "def", "evolve", "(", "self", ",", "rho", ":", "Density", ")", "->", "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", ",", "tensors", ")", "return", "Density", "(", "tensor", ",", "qubits", ")" ]
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) unused = [True] * N for gl in gate_layers: assert isinstance(gl, Circuit) for gate in gl: indices = [qubit_idx[q] for q in gate.qubits] if not all(unused[min(indices):max(indices)+1]): # New layer lcirc = Circuit() layers.append(lcirc) unused = [True] * N unused[min(indices):max(indices)+1] = \ [False] * (max(indices) - min(indices) + 1) lcirc += gate return Circuit(layers)
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) unused = [True] * N for gl in gate_layers: assert isinstance(gl, Circuit) for gate in gl: indices = [qubit_idx[q] for q in gate.qubits] if not all(unused[min(indices):max(indices)+1]): # New layer lcirc = Circuit() layers.append(lcirc) unused = [True] * N unused[min(indices):max(indices)+1] = \ [False] * (max(indices) - min(indices) + 1) lcirc += gate return Circuit(layers)
[ "def", "_display_layers", "(", "circ", ":", "Circuit", ",", "qubits", ":", "Qubits", ")", "->", "Circuit", ":", "N", "=", "len", "(", "qubits", ")", "qubit_idx", "=", "dict", "(", "zip", "(", "qubits", ",", "range", "(", "N", ")", ")", ")", "gate_layers", "=", "DAGCircuit", "(", "circ", ")", ".", "layers", "(", ")", "layers", "=", "[", "]", "lcirc", "=", "Circuit", "(", ")", "layers", ".", "append", "(", "lcirc", ")", "unused", "=", "[", "True", "]", "*", "N", "for", "gl", "in", "gate_layers", ":", "assert", "isinstance", "(", "gl", ",", "Circuit", ")", "for", "gate", "in", "gl", ":", "indices", "=", "[", "qubit_idx", "[", "q", "]", "for", "q", "in", "gate", ".", "qubits", "]", "if", "not", "all", "(", "unused", "[", "min", "(", "indices", ")", ":", "max", "(", "indices", ")", "+", "1", "]", ")", ":", "# New layer", "lcirc", "=", "Circuit", "(", ")", "layers", ".", "append", "(", "lcirc", ")", "unused", "=", "[", "True", "]", "*", "N", "unused", "[", "min", "(", "indices", ")", ":", "max", "(", "indices", ")", "+", "1", "]", "=", "[", "False", "]", "*", "(", "max", "(", "indices", ")", "-", "min", "(", "indices", ")", "+", "1", ")", "lcirc", "+=", "gate", "return", "Circuit", "(", "layers", ")" ]
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 document as a string. Returns: A PIL Image Raises: OSError: If an external dependency is not installed. """ tmpfilename = 'circ' with tempfile.TemporaryDirectory() as tmpdirname: tmppath = os.path.join(tmpdirname, tmpfilename) with open(tmppath + '.tex', 'w') as latex_file: latex_file.write(latex) subprocess.run(["pdflatex", "-halt-on-error", "-output-directory={}".format(tmpdirname), "{}".format(tmpfilename+'.tex')], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=True) subprocess.run(['pdftocairo', '-singlefile', '-png', '-q', tmppath + '.pdf', tmppath]) img = PIL.Image.open(tmppath + '.png') return img
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 document as a string. Returns: A PIL Image Raises: OSError: If an external dependency is not installed. """ tmpfilename = 'circ' with tempfile.TemporaryDirectory() as tmpdirname: tmppath = os.path.join(tmpdirname, tmpfilename) with open(tmppath + '.tex', 'w') as latex_file: latex_file.write(latex) subprocess.run(["pdflatex", "-halt-on-error", "-output-directory={}".format(tmpdirname), "{}".format(tmpfilename+'.tex')], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=True) subprocess.run(['pdftocairo', '-singlefile', '-png', '-q', tmppath + '.pdf', tmppath]) img = PIL.Image.open(tmppath + '.png') return img
[ "def", "render_latex", "(", "latex", ":", "str", ")", "->", "PIL", ".", "Image", ":", "# pragma: no cover", "tmpfilename", "=", "'circ'", "with", "tempfile", ".", "TemporaryDirectory", "(", ")", "as", "tmpdirname", ":", "tmppath", "=", "os", ".", "path", ".", "join", "(", "tmpdirname", ",", "tmpfilename", ")", "with", "open", "(", "tmppath", "+", "'.tex'", ",", "'w'", ")", "as", "latex_file", ":", "latex_file", ".", "write", "(", "latex", ")", "subprocess", ".", "run", "(", "[", "\"pdflatex\"", ",", "\"-halt-on-error\"", ",", "\"-output-directory={}\"", ".", "format", "(", "tmpdirname", ")", ",", "\"{}\"", ".", "format", "(", "tmpfilename", "+", "'.tex'", ")", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "DEVNULL", ",", "check", "=", "True", ")", "subprocess", ".", "run", "(", "[", "'pdftocairo'", ",", "'-singlefile'", ",", "'-png'", ",", "'-q'", ",", "tmppath", "+", "'.pdf'", ",", "tmppath", "]", ")", "img", "=", "PIL", ".", "Image", ".", "open", "(", "tmppath", "+", "'.png'", ")", "return", "img" ]
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: OSError: If an external dependency is not installed.
[ "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 qubit list to specify qubit order Returns: Returns: A PIL Image (Use img.show() to display) Raises: NotImplementedError: For unsupported gates. OSError: If an external dependency is not installed. """ latex = circuit_to_latex(circ, qubits) img = render_latex(latex) return img
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 qubit list to specify qubit order Returns: Returns: A PIL Image (Use img.show() to display) Raises: NotImplementedError: For unsupported gates. OSError: If an external dependency is not installed. """ latex = circuit_to_latex(circ, qubits) img = render_latex(latex) return img
[ "def", "circuit_to_image", "(", "circ", ":", "Circuit", ",", "qubits", ":", "Qubits", "=", "None", ")", "->", "PIL", ".", "Image", ":", "# pragma: no cover", "latex", "=", "circuit_to_latex", "(", "circ", ",", "qubits", ")", "img", "=", "render_latex", "(", "latex", ")", "return", "img" ]
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: NotImplementedError: For unsupported gates. OSError: If an external dependency is not installed.
[ "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", "\"{0:.4g}\"", ".", "format", "(", "obj", ")", "return", "str", "(", "obj", ")" ]
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 == 'gpu' else '/cpu:0' with tf.device(dev): t = tfe.Variable(np.random.normal(size=[3]), name='t') def loss_fn(): """Loss""" gate = qf.ZYZ(t[0], t[1], t[2]) ang = qf.fubini_study_angle(target_gate.vec, gate.vec) return ang loss_and_grads = tfe.implicit_value_and_gradients(loss_fn) # opt = tf.train.GradientDescentOptimizer(learning_rate=0.005) opt = tf.train.AdamOptimizer(learning_rate=0.001) # train = opt.minimize(ang, var_list=[t]) for step in range(steps): loss, grads_and_vars = loss_and_grads() sys.stdout.write('\r') sys.stdout.write("step: {:3d} loss: {:10.9f}".format(step, loss.numpy())) if loss < 0.0001: break opt.apply_gradients(grads_and_vars) print() return bk.evaluate(t)
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 == 'gpu' else '/cpu:0' with tf.device(dev): t = tfe.Variable(np.random.normal(size=[3]), name='t') def loss_fn(): """Loss""" gate = qf.ZYZ(t[0], t[1], t[2]) ang = qf.fubini_study_angle(target_gate.vec, gate.vec) return ang loss_and_grads = tfe.implicit_value_and_gradients(loss_fn) # opt = tf.train.GradientDescentOptimizer(learning_rate=0.005) opt = tf.train.AdamOptimizer(learning_rate=0.001) # train = opt.minimize(ang, var_list=[t]) for step in range(steps): loss, grads_and_vars = loss_and_grads() sys.stdout.write('\r') sys.stdout.write("step: {:3d} loss: {:10.9f}".format(step, loss.numpy())) if loss < 0.0001: break opt.apply_gradients(grads_and_vars) print() return bk.evaluate(t)
[ "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", "'/cpu:0'", "with", "tf", ".", "device", "(", "dev", ")", ":", "t", "=", "tfe", ".", "Variable", "(", "np", ".", "random", ".", "normal", "(", "size", "=", "[", "3", "]", ")", ",", "name", "=", "'t'", ")", "def", "loss_fn", "(", ")", ":", "\"\"\"Loss\"\"\"", "gate", "=", "qf", ".", "ZYZ", "(", "t", "[", "0", "]", ",", "t", "[", "1", "]", ",", "t", "[", "2", "]", ")", "ang", "=", "qf", ".", "fubini_study_angle", "(", "target_gate", ".", "vec", ",", "gate", ".", "vec", ")", "return", "ang", "loss_and_grads", "=", "tfe", ".", "implicit_value_and_gradients", "(", "loss_fn", ")", "# opt = tf.train.GradientDescentOptimizer(learning_rate=0.005)", "opt", "=", "tf", ".", "train", ".", "AdamOptimizer", "(", "learning_rate", "=", "0.001", ")", "# train = opt.minimize(ang, var_list=[t])", "for", "step", "in", "range", "(", "steps", ")", ":", "loss", ",", "grads_and_vars", "=", "loss_and_grads", "(", ")", "sys", ".", "stdout", ".", "write", "(", "'\\r'", ")", "sys", ".", "stdout", ".", "write", "(", "\"step: {:3d} loss: {:10.9f}\"", ".", "format", "(", "step", ",", "loss", ".", "numpy", "(", ")", ")", ")", "if", "loss", "<", "0.0001", ":", "break", "opt", ".", "apply_gradients", "(", "grads_and_vars", ")", "print", "(", ")", "return", "bk", ".", "evaluate", "(", "t", ")" ]
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('quantumflow \t', qf.__version__, file=file) print('python \t', sys.version[0:5], file=file) print('numpy \t', np.__version__, file=file) print('networkx \t', nx.__version__, file=file) print('cvxpy \t', cvx.__version__, file=file) print('pyquil \t', pyquil.__version__, file=file) print(bk.name, ' \t', bk.version, '(BACKEND)', file=file)
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('quantumflow \t', qf.__version__, file=file) print('python \t', sys.version[0:5], file=file) print('numpy \t', np.__version__, file=file) print('networkx \t', nx.__version__, file=file) print('cvxpy \t', cvx.__version__, file=file) print('pyquil \t', pyquil.__version__, file=file) print(bk.name, ' \t', bk.version, '(BACKEND)', file=file)
[ "def", "print_versions", "(", "file", ":", "typing", ".", "TextIO", "=", "None", ")", "->", "None", ":", "print", "(", "'** QuantumFlow dependencies (> python -m quantumflow.meta) **'", ")", "print", "(", "'quantumflow \\t'", ",", "qf", ".", "__version__", ",", "file", "=", "file", ")", "print", "(", "'python \\t'", ",", "sys", ".", "version", "[", "0", ":", "5", "]", ",", "file", "=", "file", ")", "print", "(", "'numpy \\t'", ",", "np", ".", "__version__", ",", "file", "=", "file", ")", "print", "(", "'networkx \\t'", ",", "nx", ".", "__version__", ",", "file", "=", "file", ")", "print", "(", "'cvxpy \\t'", ",", "cvx", ".", "__version__", ",", "file", "=", "file", ")", "print", "(", "'pyquil \\t'", ",", "pyquil", ".", "__version__", ",", "file", "=", "file", ")", "print", "(", "bk", ".", "name", ",", "' \\t'", ",", "bk", ".", "version", ",", "'(BACKEND)'", ",", "file", "=", "file", ")" ]
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], t[2]) ang = qf.fubini_study_angle(target_gate.vec, gate.vec) opt = tf.train.AdamOptimizer(learning_rate=0.001) train = opt.minimize(ang, var_list=[t]) with tf.Session() as sess: init_op = tf.global_variables_initializer() sess.run(init_op) for step in range(steps): sess.run(train) loss = sess.run(ang) sys.stdout.write('\r') sys.stdout.write("step: {} gate_angle: {}".format(step, loss)) if loss < 0.0001: break print() return sess.run(t)
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], t[2]) ang = qf.fubini_study_angle(target_gate.vec, gate.vec) opt = tf.train.AdamOptimizer(learning_rate=0.001) train = opt.minimize(ang, var_list=[t]) with tf.Session() as sess: init_op = tf.global_variables_initializer() sess.run(init_op) for step in range(steps): sess.run(train) loss = sess.run(ang) sys.stdout.write('\r') sys.stdout.write("step: {} gate_angle: {}".format(step, loss)) if loss < 0.0001: break print() return sess.run(t)
[ "def", "fit_zyz", "(", "target_gate", ")", ":", "assert", "bk", ".", "BACKEND", "==", "'tensorflow'", "tf", "=", "bk", ".", "TL", "steps", "=", "4000", "t", "=", "tf", ".", "get_variable", "(", "'t'", ",", "[", "3", "]", ")", "gate", "=", "qf", ".", "ZYZ", "(", "t", "[", "0", "]", ",", "t", "[", "1", "]", ",", "t", "[", "2", "]", ")", "ang", "=", "qf", ".", "fubini_study_angle", "(", "target_gate", ".", "vec", ",", "gate", ".", "vec", ")", "opt", "=", "tf", ".", "train", ".", "AdamOptimizer", "(", "learning_rate", "=", "0.001", ")", "train", "=", "opt", ".", "minimize", "(", "ang", ",", "var_list", "=", "[", "t", "]", ")", "with", "tf", ".", "Session", "(", ")", "as", "sess", ":", "init_op", "=", "tf", ".", "global_variables_initializer", "(", ")", "sess", ".", "run", "(", "init_op", ")", "for", "step", "in", "range", "(", "steps", ")", ":", "sess", ".", "run", "(", "train", ")", "loss", "=", "sess", ".", "run", "(", "ang", ")", "sys", ".", "stdout", ".", "write", "(", "'\\r'", ")", "sys", ".", "stdout", ".", "write", "(", "\"step: {} gate_angle: {}\"", ".", "format", "(", "step", ",", "loss", ")", ")", "if", "loss", "<", "0.0001", ":", "break", "print", "(", ")", "return", "sess", ".", "run", "(", "t", ")" ]
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 abs(U[0, 0]) > abs(U[1, 0]): theta1 = 2 * np.arccos(min(abs(U[0, 0]), 1)) else: theta1 = 2 * np.arcsin(min(abs(U[1, 0]), 1)) cos_halftheta1 = np.cos(theta1/2) if not np.isclose(cos_halftheta1, 0.0): phase = U[1, 1] / cos_halftheta1 theta0_plus_theta2 = 2 * np.arctan2(np.imag(phase), np.real(phase)) else: theta0_plus_theta2 = 0.0 sin_halftheta1 = np.sin(theta1/2) if not np.isclose(sin_halftheta1, 0.0): phase = U[1, 0] / sin_halftheta1 theta0_sub_theta2 = 2 * np.arctan2(np.imag(phase), np.real(phase)) else: theta0_sub_theta2 = 0.0 theta0 = (theta0_plus_theta2 + theta0_sub_theta2) / 2 theta2 = (theta0_plus_theta2 - theta0_sub_theta2) / 2 t0 = theta0/np.pi t1 = theta1/np.pi t2 = theta2/np.pi circ1 = Circuit() circ1 += TZ(t2, q) circ1 += TY(t1, q) circ1 += TZ(t0, q) return circ1
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 abs(U[0, 0]) > abs(U[1, 0]): theta1 = 2 * np.arccos(min(abs(U[0, 0]), 1)) else: theta1 = 2 * np.arcsin(min(abs(U[1, 0]), 1)) cos_halftheta1 = np.cos(theta1/2) if not np.isclose(cos_halftheta1, 0.0): phase = U[1, 1] / cos_halftheta1 theta0_plus_theta2 = 2 * np.arctan2(np.imag(phase), np.real(phase)) else: theta0_plus_theta2 = 0.0 sin_halftheta1 = np.sin(theta1/2) if not np.isclose(sin_halftheta1, 0.0): phase = U[1, 0] / sin_halftheta1 theta0_sub_theta2 = 2 * np.arctan2(np.imag(phase), np.real(phase)) else: theta0_sub_theta2 = 0.0 theta0 = (theta0_plus_theta2 + theta0_sub_theta2) / 2 theta2 = (theta0_plus_theta2 - theta0_sub_theta2) / 2 t0 = theta0/np.pi t1 = theta1/np.pi t2 = theta2/np.pi circ1 = Circuit() circ1 += TZ(t2, q) circ1 += TY(t1, q) circ1 += TZ(t0, q) return circ1
[ "def", "zyz_decomposition", "(", "gate", ":", "Gate", ")", "->", "Circuit", ":", "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", "abs", "(", "U", "[", "0", ",", "0", "]", ")", ">", "abs", "(", "U", "[", "1", ",", "0", "]", ")", ":", "theta1", "=", "2", "*", "np", ".", "arccos", "(", "min", "(", "abs", "(", "U", "[", "0", ",", "0", "]", ")", ",", "1", ")", ")", "else", ":", "theta1", "=", "2", "*", "np", ".", "arcsin", "(", "min", "(", "abs", "(", "U", "[", "1", ",", "0", "]", ")", ",", "1", ")", ")", "cos_halftheta1", "=", "np", ".", "cos", "(", "theta1", "/", "2", ")", "if", "not", "np", ".", "isclose", "(", "cos_halftheta1", ",", "0.0", ")", ":", "phase", "=", "U", "[", "1", ",", "1", "]", "/", "cos_halftheta1", "theta0_plus_theta2", "=", "2", "*", "np", ".", "arctan2", "(", "np", ".", "imag", "(", "phase", ")", ",", "np", ".", "real", "(", "phase", ")", ")", "else", ":", "theta0_plus_theta2", "=", "0.0", "sin_halftheta1", "=", "np", ".", "sin", "(", "theta1", "/", "2", ")", "if", "not", "np", ".", "isclose", "(", "sin_halftheta1", ",", "0.0", ")", ":", "phase", "=", "U", "[", "1", ",", "0", "]", "/", "sin_halftheta1", "theta0_sub_theta2", "=", "2", "*", "np", ".", "arctan2", "(", "np", ".", "imag", "(", "phase", ")", ",", "np", ".", "real", "(", "phase", ")", ")", "else", ":", "theta0_sub_theta2", "=", "0.0", "theta0", "=", "(", "theta0_plus_theta2", "+", "theta0_sub_theta2", ")", "/", "2", "theta2", "=", "(", "theta0_plus_theta2", "-", "theta0_sub_theta2", ")", "/", "2", "t0", "=", "theta0", "/", "np", ".", "pi", "t1", "=", "theta1", "/", "np", ".", "pi", "t2", "=", "theta2", "/", "np", ".", "pi", "circ1", "=", "Circuit", "(", ")", "circ1", "+=", "TZ", "(", "t2", ",", "q", ")", "circ1", "+=", "TY", "(", "t1", ",", "q", ")", "circ1", "+=", "TZ", "(", "t0", ",", "q", ")", "return", "circ1" ]
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 to take partial traces, but # this approach appears to be more robust. if gate.qubit_nb != 2: raise ValueError('Expected 2-qubit gate') U = asarray(gate.asoperator()) rank = 2**gate.qubit_nb U /= np.linalg.det(U) ** (1/rank) R = np.stack([U[0:2, 0:2].reshape(4), U[0:2, 2:4].reshape(4), U[2:4, 0:2].reshape(4), U[2:4, 2:4].reshape(4)]) u, s, vh = np.linalg.svd(R) v = vh.transpose() A = (np.sqrt(s[0]) * u[:, 0]).reshape(2, 2) B = (np.sqrt(s[0]) * v[:, 0]).reshape(2, 2) q0, q1 = gate.qubits g0 = Gate(A, qubits=[q0]) g1 = Gate(B, qubits=[q1]) if not gates_close(gate, Circuit([g0, g1]).asgate()): raise ValueError("Gate cannot be decomposed into two 1-qubit gates") circ = Circuit() circ += zyz_decomposition(g0) circ += zyz_decomposition(g1) assert gates_close(gate, circ.asgate()) # Sanity check return circ
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 to take partial traces, but # this approach appears to be more robust. if gate.qubit_nb != 2: raise ValueError('Expected 2-qubit gate') U = asarray(gate.asoperator()) rank = 2**gate.qubit_nb U /= np.linalg.det(U) ** (1/rank) R = np.stack([U[0:2, 0:2].reshape(4), U[0:2, 2:4].reshape(4), U[2:4, 0:2].reshape(4), U[2:4, 2:4].reshape(4)]) u, s, vh = np.linalg.svd(R) v = vh.transpose() A = (np.sqrt(s[0]) * u[:, 0]).reshape(2, 2) B = (np.sqrt(s[0]) * v[:, 0]).reshape(2, 2) q0, q1 = gate.qubits g0 = Gate(A, qubits=[q0]) g1 = Gate(B, qubits=[q1]) if not gates_close(gate, Circuit([g0, g1]).asgate()): raise ValueError("Gate cannot be decomposed into two 1-qubit gates") circ = Circuit() circ += zyz_decomposition(g0) circ += zyz_decomposition(g1) assert gates_close(gate, circ.asgate()) # Sanity check return circ
[ "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", "(", "'Expected 2-qubit gate'", ")", "U", "=", "asarray", "(", "gate", ".", "asoperator", "(", ")", ")", "rank", "=", "2", "**", "gate", ".", "qubit_nb", "U", "/=", "np", ".", "linalg", ".", "det", "(", "U", ")", "**", "(", "1", "/", "rank", ")", "R", "=", "np", ".", "stack", "(", "[", "U", "[", "0", ":", "2", ",", "0", ":", "2", "]", ".", "reshape", "(", "4", ")", ",", "U", "[", "0", ":", "2", ",", "2", ":", "4", "]", ".", "reshape", "(", "4", ")", ",", "U", "[", "2", ":", "4", ",", "0", ":", "2", "]", ".", "reshape", "(", "4", ")", ",", "U", "[", "2", ":", "4", ",", "2", ":", "4", "]", ".", "reshape", "(", "4", ")", "]", ")", "u", ",", "s", ",", "vh", "=", "np", ".", "linalg", ".", "svd", "(", "R", ")", "v", "=", "vh", ".", "transpose", "(", ")", "A", "=", "(", "np", ".", "sqrt", "(", "s", "[", "0", "]", ")", "*", "u", "[", ":", ",", "0", "]", ")", ".", "reshape", "(", "2", ",", "2", ")", "B", "=", "(", "np", ".", "sqrt", "(", "s", "[", "0", "]", ")", "*", "v", "[", ":", ",", "0", "]", ")", ".", "reshape", "(", "2", ",", "2", ")", "q0", ",", "q1", "=", "gate", ".", "qubits", "g0", "=", "Gate", "(", "A", ",", "qubits", "=", "[", "q0", "]", ")", "g1", "=", "Gate", "(", "B", ",", "qubits", "=", "[", "q1", "]", ")", "if", "not", "gates_close", "(", "gate", ",", "Circuit", "(", "[", "g0", ",", "g1", "]", ")", ".", "asgate", "(", ")", ")", ":", "raise", "ValueError", "(", "\"Gate cannot be decomposed into two 1-qubit gates\"", ")", "circ", "=", "Circuit", "(", ")", "circ", "+=", "zyz_decomposition", "(", "g0", ")", "circ", "+=", "zyz_decomposition", "(", "g1", ")", "assert", "gates_close", "(", "gate", ",", "circ", ".", "asgate", "(", ")", ")", "# Sanity check", "return", "circ" ]
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", ".", "params", "[", "key", "]", "for", "key", "in", "(", "'tx'", ",", "'ty'", ",", "'tz'", ")", "]", "return", "params" ]
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.linalg.LinAlgError('Not a symmetric matrix') # The matrix of eigenvectors should be orthogonal. # But the standard 'eig' method will fail to return an orthogonal # eigenvector matrix when the eigenvalues are degenerate. However, # both the real and # imaginary part of M must be symmetric with the same orthogonal # matrix of eigenvectors. But either the real or imaginary part could # vanish. So we use a randomized algorithm where we diagonalize a # random linear combination of real and imaginary parts to find the # eigenvectors, taking advantage of the 'eigh' subroutine for # diagonalizing symmetric matrices. # This can fail if we're very unlucky with our random coefficient, so we # give the algorithm a few chances to succeed. # Empirically, never seems to fail on randomly sampled complex # symmetric 4x4 matrices. # If failure rate is less than 1 in a million, then 16 rounds # will have overall failure rate less than 1 in a googol. # However, cannot (yet) guarantee that there aren't special cases # which have much higher failure rates. # GEC 2018 max_attempts = 16 for _ in range(max_attempts): c = np.random.uniform(0, 1) matrix = c * M.real + (1-c) * M.imag _, eigvecs = np.linalg.eigh(matrix) eigvecs = np.array(eigvecs, dtype=complex) eigvals = np.diag(eigvecs.transpose() @ M @ eigvecs) # Finish if we got a correct answer. reconstructed = eigvecs @ np.diag(eigvals) @ eigvecs.transpose() if np.allclose(M, reconstructed): return eigvals, eigvecs # Should never happen. Hopefully. raise np.linalg.LinAlgError( 'Cannot diagonalize complex symmetric matrix.')
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.linalg.LinAlgError('Not a symmetric matrix') # The matrix of eigenvectors should be orthogonal. # But the standard 'eig' method will fail to return an orthogonal # eigenvector matrix when the eigenvalues are degenerate. However, # both the real and # imaginary part of M must be symmetric with the same orthogonal # matrix of eigenvectors. But either the real or imaginary part could # vanish. So we use a randomized algorithm where we diagonalize a # random linear combination of real and imaginary parts to find the # eigenvectors, taking advantage of the 'eigh' subroutine for # diagonalizing symmetric matrices. # This can fail if we're very unlucky with our random coefficient, so we # give the algorithm a few chances to succeed. # Empirically, never seems to fail on randomly sampled complex # symmetric 4x4 matrices. # If failure rate is less than 1 in a million, then 16 rounds # will have overall failure rate less than 1 in a googol. # However, cannot (yet) guarantee that there aren't special cases # which have much higher failure rates. # GEC 2018 max_attempts = 16 for _ in range(max_attempts): c = np.random.uniform(0, 1) matrix = c * M.real + (1-c) * M.imag _, eigvecs = np.linalg.eigh(matrix) eigvecs = np.array(eigvecs, dtype=complex) eigvals = np.diag(eigvecs.transpose() @ M @ eigvecs) # Finish if we got a correct answer. reconstructed = eigvecs @ np.diag(eigvals) @ eigvecs.transpose() if np.allclose(M, reconstructed): return eigvals, eigvecs # Should never happen. Hopefully. raise np.linalg.LinAlgError( 'Cannot diagonalize complex symmetric matrix.')
[ "def", "_eig_complex_symmetric", "(", "M", ":", "np", ".", "ndarray", ")", "->", "Tuple", "[", "np", ".", "ndarray", ",", "np", ".", "ndarray", "]", ":", "if", "not", "np", ".", "allclose", "(", "M", ",", "M", ".", "transpose", "(", ")", ")", ":", "raise", "np", ".", "linalg", ".", "LinAlgError", "(", "'Not a symmetric matrix'", ")", "# The matrix of eigenvectors should be orthogonal.", "# But the standard 'eig' method will fail to return an orthogonal", "# eigenvector matrix when the eigenvalues are degenerate. However,", "# both the real and", "# imaginary part of M must be symmetric with the same orthogonal", "# matrix of eigenvectors. But either the real or imaginary part could", "# vanish. So we use a randomized algorithm where we diagonalize a", "# random linear combination of real and imaginary parts to find the", "# eigenvectors, taking advantage of the 'eigh' subroutine for", "# diagonalizing symmetric matrices.", "# This can fail if we're very unlucky with our random coefficient, so we", "# give the algorithm a few chances to succeed.", "# Empirically, never seems to fail on randomly sampled complex", "# symmetric 4x4 matrices.", "# If failure rate is less than 1 in a million, then 16 rounds", "# will have overall failure rate less than 1 in a googol.", "# However, cannot (yet) guarantee that there aren't special cases", "# which have much higher failure rates.", "# GEC 2018", "max_attempts", "=", "16", "for", "_", "in", "range", "(", "max_attempts", ")", ":", "c", "=", "np", ".", "random", ".", "uniform", "(", "0", ",", "1", ")", "matrix", "=", "c", "*", "M", ".", "real", "+", "(", "1", "-", "c", ")", "*", "M", ".", "imag", "_", ",", "eigvecs", "=", "np", ".", "linalg", ".", "eigh", "(", "matrix", ")", "eigvecs", "=", "np", ".", "array", "(", "eigvecs", ",", "dtype", "=", "complex", ")", "eigvals", "=", "np", ".", "diag", "(", "eigvecs", ".", "transpose", "(", ")", "@", "M", "@", "eigvecs", ")", "# Finish if we got a correct answer.", "reconstructed", "=", "eigvecs", "@", "np", ".", "diag", "(", "eigvals", ")", "@", "eigvecs", ".", "transpose", "(", ")", "if", "np", ".", "allclose", "(", "M", ",", "reconstructed", ")", ":", "return", "eigvals", ",", "eigvecs", "# Should never happen. Hopefully.", "raise", "np", ".", "linalg", ".", "LinAlgError", "(", "'Cannot diagonalize complex symmetric matrix.'", ")" ]
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_bias, scale=init_scale, size=[steps]) init_gamma = normal(loc=init_bias, scale=init_scale, size=[steps]) beta = tf.get_variable('beta', initializer=init_beta) gamma = tf.get_variable('gamma', initializer=init_gamma) circ = qubo_circuit(graph, steps, beta, gamma) cuts = graph_cuts(graph) maxcut = cuts.max() expect = circ.run().expectation(cuts) loss = - expect # === Optimization === opt = tf.train.GradientDescentOptimizer(learning_rate=learning_rate) train = opt.minimize(loss, var_list=[beta, gamma]) with tf.Session() as sess: init_op = tf.global_variables_initializer() sess.run(init_op) block = 10 min_difference = 0.0001 last_ratio = -1 for step in range(0, MAX_OPT_STEPS, block): for _ in range(block): sess.run(train) ratio = sess.run(expect) / maxcut if ratio - last_ratio < min_difference: break last_ratio = ratio if verbose: print("# step: {} ratio: {:.4f}%".format(step, ratio)) opt_beta = sess.run(beta) opt_gamma = sess.run(gamma) return ratio, opt_beta, opt_gamma
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_bias, scale=init_scale, size=[steps]) init_gamma = normal(loc=init_bias, scale=init_scale, size=[steps]) beta = tf.get_variable('beta', initializer=init_beta) gamma = tf.get_variable('gamma', initializer=init_gamma) circ = qubo_circuit(graph, steps, beta, gamma) cuts = graph_cuts(graph) maxcut = cuts.max() expect = circ.run().expectation(cuts) loss = - expect # === Optimization === opt = tf.train.GradientDescentOptimizer(learning_rate=learning_rate) train = opt.minimize(loss, var_list=[beta, gamma]) with tf.Session() as sess: init_op = tf.global_variables_initializer() sess.run(init_op) block = 10 min_difference = 0.0001 last_ratio = -1 for step in range(0, MAX_OPT_STEPS, block): for _ in range(block): sess.run(train) ratio = sess.run(expect) / maxcut if ratio - last_ratio < min_difference: break last_ratio = ratio if verbose: print("# step: {} ratio: {:.4f}%".format(step, ratio)) opt_beta = sess.run(beta) opt_gamma = sess.run(gamma) return ratio, opt_beta, opt_gamma
[ "def", "maxcut_qaoa", "(", "graph", ",", "steps", "=", "DEFAULT_STEPS", ",", "learning_rate", "=", "LEARNING_RATE", ",", "verbose", "=", "False", ")", ":", "if", "not", "isinstance", "(", "graph", ",", "nx", ".", "Graph", ")", ":", "graph", "=", "nx", ".", "from_edgelist", "(", "graph", ")", "init_scale", "=", "0.01", "init_bias", "=", "0.5", "init_beta", "=", "normal", "(", "loc", "=", "init_bias", ",", "scale", "=", "init_scale", ",", "size", "=", "[", "steps", "]", ")", "init_gamma", "=", "normal", "(", "loc", "=", "init_bias", ",", "scale", "=", "init_scale", ",", "size", "=", "[", "steps", "]", ")", "beta", "=", "tf", ".", "get_variable", "(", "'beta'", ",", "initializer", "=", "init_beta", ")", "gamma", "=", "tf", ".", "get_variable", "(", "'gamma'", ",", "initializer", "=", "init_gamma", ")", "circ", "=", "qubo_circuit", "(", "graph", ",", "steps", ",", "beta", ",", "gamma", ")", "cuts", "=", "graph_cuts", "(", "graph", ")", "maxcut", "=", "cuts", ".", "max", "(", ")", "expect", "=", "circ", ".", "run", "(", ")", ".", "expectation", "(", "cuts", ")", "loss", "=", "-", "expect", "# === Optimization ===", "opt", "=", "tf", ".", "train", ".", "GradientDescentOptimizer", "(", "learning_rate", "=", "learning_rate", ")", "train", "=", "opt", ".", "minimize", "(", "loss", ",", "var_list", "=", "[", "beta", ",", "gamma", "]", ")", "with", "tf", ".", "Session", "(", ")", "as", "sess", ":", "init_op", "=", "tf", ".", "global_variables_initializer", "(", ")", "sess", ".", "run", "(", "init_op", ")", "block", "=", "10", "min_difference", "=", "0.0001", "last_ratio", "=", "-", "1", "for", "step", "in", "range", "(", "0", ",", "MAX_OPT_STEPS", ",", "block", ")", ":", "for", "_", "in", "range", "(", "block", ")", ":", "sess", ".", "run", "(", "train", ")", "ratio", "=", "sess", ".", "run", "(", "expect", ")", "/", "maxcut", "if", "ratio", "-", "last_ratio", "<", "min_difference", ":", "break", "last_ratio", "=", "ratio", "if", "verbose", ":", "print", "(", "\"# step: {} ratio: {:.4f}%\"", ".", "format", "(", "step", ",", "ratio", ")", ")", "opt_beta", "=", "sess", ".", "run", "(", "beta", ")", "opt_gamma", "=", "sess", ".", "run", "(", "gamma", ")", "return", "ratio", ",", "opt_beta", ",", "opt_gamma" ]
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