partition
stringclasses 3
values | func_name
stringlengths 1
134
| docstring
stringlengths 1
46.9k
| path
stringlengths 4
223
| original_string
stringlengths 75
104k
| code
stringlengths 75
104k
| docstring_tokens
listlengths 1
1.97k
| repo
stringlengths 7
55
| language
stringclasses 1
value | url
stringlengths 87
315
| code_tokens
listlengths 19
28.4k
| sha
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|
test
|
is_square_matrix
|
Test if an array is a square matrix.
|
qiskit/quantum_info/operators/predicates.py
|
def is_square_matrix(mat):
"""Test if an array is a square matrix."""
mat = np.array(mat)
if mat.ndim != 2:
return False
shape = mat.shape
return shape[0] == shape[1]
|
def is_square_matrix(mat):
"""Test if an array is a square matrix."""
mat = np.array(mat)
if mat.ndim != 2:
return False
shape = mat.shape
return shape[0] == shape[1]
|
[
"Test",
"if",
"an",
"array",
"is",
"a",
"square",
"matrix",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/predicates.py#L65-L71
|
[
"def",
"is_square_matrix",
"(",
"mat",
")",
":",
"mat",
"=",
"np",
".",
"array",
"(",
"mat",
")",
"if",
"mat",
".",
"ndim",
"!=",
"2",
":",
"return",
"False",
"shape",
"=",
"mat",
".",
"shape",
"return",
"shape",
"[",
"0",
"]",
"==",
"shape",
"[",
"1",
"]"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
is_diagonal_matrix
|
Test if an array is a diagonal matrix
|
qiskit/quantum_info/operators/predicates.py
|
def is_diagonal_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
"""Test if an array is a diagonal matrix"""
if atol is None:
atol = ATOL_DEFAULT
if rtol is None:
rtol = RTOL_DEFAULT
mat = np.array(mat)
if mat.ndim != 2:
return False
return np.allclose(mat, np.diag(np.diagonal(mat)), rtol=rtol, atol=atol)
|
def is_diagonal_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
"""Test if an array is a diagonal matrix"""
if atol is None:
atol = ATOL_DEFAULT
if rtol is None:
rtol = RTOL_DEFAULT
mat = np.array(mat)
if mat.ndim != 2:
return False
return np.allclose(mat, np.diag(np.diagonal(mat)), rtol=rtol, atol=atol)
|
[
"Test",
"if",
"an",
"array",
"is",
"a",
"diagonal",
"matrix"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/predicates.py#L74-L83
|
[
"def",
"is_diagonal_matrix",
"(",
"mat",
",",
"rtol",
"=",
"RTOL_DEFAULT",
",",
"atol",
"=",
"ATOL_DEFAULT",
")",
":",
"if",
"atol",
"is",
"None",
":",
"atol",
"=",
"ATOL_DEFAULT",
"if",
"rtol",
"is",
"None",
":",
"rtol",
"=",
"RTOL_DEFAULT",
"mat",
"=",
"np",
".",
"array",
"(",
"mat",
")",
"if",
"mat",
".",
"ndim",
"!=",
"2",
":",
"return",
"False",
"return",
"np",
".",
"allclose",
"(",
"mat",
",",
"np",
".",
"diag",
"(",
"np",
".",
"diagonal",
"(",
"mat",
")",
")",
",",
"rtol",
"=",
"rtol",
",",
"atol",
"=",
"atol",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
is_symmetric_matrix
|
Test if an array is a symmetrix matrix
|
qiskit/quantum_info/operators/predicates.py
|
def is_symmetric_matrix(op, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
"""Test if an array is a symmetrix matrix"""
if atol is None:
atol = ATOL_DEFAULT
if rtol is None:
rtol = RTOL_DEFAULT
mat = np.array(op)
if mat.ndim != 2:
return False
return np.allclose(mat, mat.T, rtol=rtol, atol=atol)
|
def is_symmetric_matrix(op, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
"""Test if an array is a symmetrix matrix"""
if atol is None:
atol = ATOL_DEFAULT
if rtol is None:
rtol = RTOL_DEFAULT
mat = np.array(op)
if mat.ndim != 2:
return False
return np.allclose(mat, mat.T, rtol=rtol, atol=atol)
|
[
"Test",
"if",
"an",
"array",
"is",
"a",
"symmetrix",
"matrix"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/predicates.py#L86-L95
|
[
"def",
"is_symmetric_matrix",
"(",
"op",
",",
"rtol",
"=",
"RTOL_DEFAULT",
",",
"atol",
"=",
"ATOL_DEFAULT",
")",
":",
"if",
"atol",
"is",
"None",
":",
"atol",
"=",
"ATOL_DEFAULT",
"if",
"rtol",
"is",
"None",
":",
"rtol",
"=",
"RTOL_DEFAULT",
"mat",
"=",
"np",
".",
"array",
"(",
"op",
")",
"if",
"mat",
".",
"ndim",
"!=",
"2",
":",
"return",
"False",
"return",
"np",
".",
"allclose",
"(",
"mat",
",",
"mat",
".",
"T",
",",
"rtol",
"=",
"rtol",
",",
"atol",
"=",
"atol",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
is_hermitian_matrix
|
Test if an array is a Hermitian matrix
|
qiskit/quantum_info/operators/predicates.py
|
def is_hermitian_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
"""Test if an array is a Hermitian matrix"""
if atol is None:
atol = ATOL_DEFAULT
if rtol is None:
rtol = RTOL_DEFAULT
mat = np.array(mat)
if mat.ndim != 2:
return False
return np.allclose(mat, np.conj(mat.T), rtol=rtol, atol=atol)
|
def is_hermitian_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
"""Test if an array is a Hermitian matrix"""
if atol is None:
atol = ATOL_DEFAULT
if rtol is None:
rtol = RTOL_DEFAULT
mat = np.array(mat)
if mat.ndim != 2:
return False
return np.allclose(mat, np.conj(mat.T), rtol=rtol, atol=atol)
|
[
"Test",
"if",
"an",
"array",
"is",
"a",
"Hermitian",
"matrix"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/predicates.py#L98-L107
|
[
"def",
"is_hermitian_matrix",
"(",
"mat",
",",
"rtol",
"=",
"RTOL_DEFAULT",
",",
"atol",
"=",
"ATOL_DEFAULT",
")",
":",
"if",
"atol",
"is",
"None",
":",
"atol",
"=",
"ATOL_DEFAULT",
"if",
"rtol",
"is",
"None",
":",
"rtol",
"=",
"RTOL_DEFAULT",
"mat",
"=",
"np",
".",
"array",
"(",
"mat",
")",
"if",
"mat",
".",
"ndim",
"!=",
"2",
":",
"return",
"False",
"return",
"np",
".",
"allclose",
"(",
"mat",
",",
"np",
".",
"conj",
"(",
"mat",
".",
"T",
")",
",",
"rtol",
"=",
"rtol",
",",
"atol",
"=",
"atol",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
is_positive_semidefinite_matrix
|
Test if a matrix is positive semidefinite
|
qiskit/quantum_info/operators/predicates.py
|
def is_positive_semidefinite_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
"""Test if a matrix is positive semidefinite"""
if atol is None:
atol = ATOL_DEFAULT
if rtol is None:
rtol = RTOL_DEFAULT
if not is_hermitian_matrix(mat, rtol=rtol, atol=atol):
return False
# Check eigenvalues are all positive
vals = np.linalg.eigvalsh(mat)
for v in vals:
if v < -atol:
return False
return True
|
def is_positive_semidefinite_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
"""Test if a matrix is positive semidefinite"""
if atol is None:
atol = ATOL_DEFAULT
if rtol is None:
rtol = RTOL_DEFAULT
if not is_hermitian_matrix(mat, rtol=rtol, atol=atol):
return False
# Check eigenvalues are all positive
vals = np.linalg.eigvalsh(mat)
for v in vals:
if v < -atol:
return False
return True
|
[
"Test",
"if",
"a",
"matrix",
"is",
"positive",
"semidefinite"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/predicates.py#L110-L123
|
[
"def",
"is_positive_semidefinite_matrix",
"(",
"mat",
",",
"rtol",
"=",
"RTOL_DEFAULT",
",",
"atol",
"=",
"ATOL_DEFAULT",
")",
":",
"if",
"atol",
"is",
"None",
":",
"atol",
"=",
"ATOL_DEFAULT",
"if",
"rtol",
"is",
"None",
":",
"rtol",
"=",
"RTOL_DEFAULT",
"if",
"not",
"is_hermitian_matrix",
"(",
"mat",
",",
"rtol",
"=",
"rtol",
",",
"atol",
"=",
"atol",
")",
":",
"return",
"False",
"# Check eigenvalues are all positive",
"vals",
"=",
"np",
".",
"linalg",
".",
"eigvalsh",
"(",
"mat",
")",
"for",
"v",
"in",
"vals",
":",
"if",
"v",
"<",
"-",
"atol",
":",
"return",
"False",
"return",
"True"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
is_identity_matrix
|
Test if an array is an identity matrix.
|
qiskit/quantum_info/operators/predicates.py
|
def is_identity_matrix(mat,
ignore_phase=False,
rtol=RTOL_DEFAULT,
atol=ATOL_DEFAULT):
"""Test if an array is an identity matrix."""
if atol is None:
atol = ATOL_DEFAULT
if rtol is None:
rtol = RTOL_DEFAULT
mat = np.array(mat)
if mat.ndim != 2:
return False
if ignore_phase:
# If the matrix is equal to an identity up to a phase, we can
# remove the phase by multiplying each entry by the complex
# conjugate of the phase of the [0, 0] entry.
theta = np.angle(mat[0, 0])
mat = np.exp(-1j * theta) * mat
# Check if square identity
iden = np.eye(len(mat))
return np.allclose(mat, iden, rtol=rtol, atol=atol)
|
def is_identity_matrix(mat,
ignore_phase=False,
rtol=RTOL_DEFAULT,
atol=ATOL_DEFAULT):
"""Test if an array is an identity matrix."""
if atol is None:
atol = ATOL_DEFAULT
if rtol is None:
rtol = RTOL_DEFAULT
mat = np.array(mat)
if mat.ndim != 2:
return False
if ignore_phase:
# If the matrix is equal to an identity up to a phase, we can
# remove the phase by multiplying each entry by the complex
# conjugate of the phase of the [0, 0] entry.
theta = np.angle(mat[0, 0])
mat = np.exp(-1j * theta) * mat
# Check if square identity
iden = np.eye(len(mat))
return np.allclose(mat, iden, rtol=rtol, atol=atol)
|
[
"Test",
"if",
"an",
"array",
"is",
"an",
"identity",
"matrix",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/predicates.py#L126-L146
|
[
"def",
"is_identity_matrix",
"(",
"mat",
",",
"ignore_phase",
"=",
"False",
",",
"rtol",
"=",
"RTOL_DEFAULT",
",",
"atol",
"=",
"ATOL_DEFAULT",
")",
":",
"if",
"atol",
"is",
"None",
":",
"atol",
"=",
"ATOL_DEFAULT",
"if",
"rtol",
"is",
"None",
":",
"rtol",
"=",
"RTOL_DEFAULT",
"mat",
"=",
"np",
".",
"array",
"(",
"mat",
")",
"if",
"mat",
".",
"ndim",
"!=",
"2",
":",
"return",
"False",
"if",
"ignore_phase",
":",
"# If the matrix is equal to an identity up to a phase, we can",
"# remove the phase by multiplying each entry by the complex",
"# conjugate of the phase of the [0, 0] entry.",
"theta",
"=",
"np",
".",
"angle",
"(",
"mat",
"[",
"0",
",",
"0",
"]",
")",
"mat",
"=",
"np",
".",
"exp",
"(",
"-",
"1j",
"*",
"theta",
")",
"*",
"mat",
"# Check if square identity",
"iden",
"=",
"np",
".",
"eye",
"(",
"len",
"(",
"mat",
")",
")",
"return",
"np",
".",
"allclose",
"(",
"mat",
",",
"iden",
",",
"rtol",
"=",
"rtol",
",",
"atol",
"=",
"atol",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
is_unitary_matrix
|
Test if an array is a unitary matrix.
|
qiskit/quantum_info/operators/predicates.py
|
def is_unitary_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
"""Test if an array is a unitary matrix."""
if atol is None:
atol = ATOL_DEFAULT
if rtol is None:
rtol = RTOL_DEFAULT
mat = np.array(mat)
# Compute A^dagger.A and see if it is identity matrix
mat = np.conj(mat.T).dot(mat)
return is_identity_matrix(mat, ignore_phase=False, rtol=rtol, atol=atol)
|
def is_unitary_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
"""Test if an array is a unitary matrix."""
if atol is None:
atol = ATOL_DEFAULT
if rtol is None:
rtol = RTOL_DEFAULT
mat = np.array(mat)
# Compute A^dagger.A and see if it is identity matrix
mat = np.conj(mat.T).dot(mat)
return is_identity_matrix(mat, ignore_phase=False, rtol=rtol, atol=atol)
|
[
"Test",
"if",
"an",
"array",
"is",
"a",
"unitary",
"matrix",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/predicates.py#L149-L158
|
[
"def",
"is_unitary_matrix",
"(",
"mat",
",",
"rtol",
"=",
"RTOL_DEFAULT",
",",
"atol",
"=",
"ATOL_DEFAULT",
")",
":",
"if",
"atol",
"is",
"None",
":",
"atol",
"=",
"ATOL_DEFAULT",
"if",
"rtol",
"is",
"None",
":",
"rtol",
"=",
"RTOL_DEFAULT",
"mat",
"=",
"np",
".",
"array",
"(",
"mat",
")",
"# Compute A^dagger.A and see if it is identity matrix",
"mat",
"=",
"np",
".",
"conj",
"(",
"mat",
".",
"T",
")",
".",
"dot",
"(",
"mat",
")",
"return",
"is_identity_matrix",
"(",
"mat",
",",
"ignore_phase",
"=",
"False",
",",
"rtol",
"=",
"rtol",
",",
"atol",
"=",
"atol",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
OptimizeSwapBeforeMeasure.run
|
Return a new circuit that has been optimized.
|
qiskit/transpiler/passes/optimize_swap_before_measure.py
|
def run(self, dag):
"""Return a new circuit that has been optimized."""
swaps = dag.op_nodes(SwapGate)
for swap in swaps:
final_successor = []
for successor in dag.successors(swap):
final_successor.append(successor.type == 'out' or (successor.type == 'op' and
successor.op.name == 'measure'))
if all(final_successor):
# the node swap needs to be removed and, if a measure follows, needs to be adapted
swap_qargs = swap.qargs
measure_layer = DAGCircuit()
for qreg in dag.qregs.values():
measure_layer.add_qreg(qreg)
for creg in dag.cregs.values():
measure_layer.add_creg(creg)
for successor in dag.successors(swap):
if successor.type == 'op' and successor.op.name == 'measure':
# replace measure node with a new one, where qargs is set with the "other"
# swap qarg.
dag.remove_op_node(successor)
old_measure_qarg = successor.qargs[0]
new_measure_qarg = swap_qargs[swap_qargs.index(old_measure_qarg) - 1]
measure_layer.apply_operation_back(Measure(), [new_measure_qarg],
[successor.cargs[0]])
dag.extend_back(measure_layer)
dag.remove_op_node(swap)
return dag
|
def run(self, dag):
"""Return a new circuit that has been optimized."""
swaps = dag.op_nodes(SwapGate)
for swap in swaps:
final_successor = []
for successor in dag.successors(swap):
final_successor.append(successor.type == 'out' or (successor.type == 'op' and
successor.op.name == 'measure'))
if all(final_successor):
# the node swap needs to be removed and, if a measure follows, needs to be adapted
swap_qargs = swap.qargs
measure_layer = DAGCircuit()
for qreg in dag.qregs.values():
measure_layer.add_qreg(qreg)
for creg in dag.cregs.values():
measure_layer.add_creg(creg)
for successor in dag.successors(swap):
if successor.type == 'op' and successor.op.name == 'measure':
# replace measure node with a new one, where qargs is set with the "other"
# swap qarg.
dag.remove_op_node(successor)
old_measure_qarg = successor.qargs[0]
new_measure_qarg = swap_qargs[swap_qargs.index(old_measure_qarg) - 1]
measure_layer.apply_operation_back(Measure(), [new_measure_qarg],
[successor.cargs[0]])
dag.extend_back(measure_layer)
dag.remove_op_node(swap)
return dag
|
[
"Return",
"a",
"new",
"circuit",
"that",
"has",
"been",
"optimized",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/optimize_swap_before_measure.py#L23-L50
|
[
"def",
"run",
"(",
"self",
",",
"dag",
")",
":",
"swaps",
"=",
"dag",
".",
"op_nodes",
"(",
"SwapGate",
")",
"for",
"swap",
"in",
"swaps",
":",
"final_successor",
"=",
"[",
"]",
"for",
"successor",
"in",
"dag",
".",
"successors",
"(",
"swap",
")",
":",
"final_successor",
".",
"append",
"(",
"successor",
".",
"type",
"==",
"'out'",
"or",
"(",
"successor",
".",
"type",
"==",
"'op'",
"and",
"successor",
".",
"op",
".",
"name",
"==",
"'measure'",
")",
")",
"if",
"all",
"(",
"final_successor",
")",
":",
"# the node swap needs to be removed and, if a measure follows, needs to be adapted",
"swap_qargs",
"=",
"swap",
".",
"qargs",
"measure_layer",
"=",
"DAGCircuit",
"(",
")",
"for",
"qreg",
"in",
"dag",
".",
"qregs",
".",
"values",
"(",
")",
":",
"measure_layer",
".",
"add_qreg",
"(",
"qreg",
")",
"for",
"creg",
"in",
"dag",
".",
"cregs",
".",
"values",
"(",
")",
":",
"measure_layer",
".",
"add_creg",
"(",
"creg",
")",
"for",
"successor",
"in",
"dag",
".",
"successors",
"(",
"swap",
")",
":",
"if",
"successor",
".",
"type",
"==",
"'op'",
"and",
"successor",
".",
"op",
".",
"name",
"==",
"'measure'",
":",
"# replace measure node with a new one, where qargs is set with the \"other\"",
"# swap qarg.",
"dag",
".",
"remove_op_node",
"(",
"successor",
")",
"old_measure_qarg",
"=",
"successor",
".",
"qargs",
"[",
"0",
"]",
"new_measure_qarg",
"=",
"swap_qargs",
"[",
"swap_qargs",
".",
"index",
"(",
"old_measure_qarg",
")",
"-",
"1",
"]",
"measure_layer",
".",
"apply_operation_back",
"(",
"Measure",
"(",
")",
",",
"[",
"new_measure_qarg",
"]",
",",
"[",
"successor",
".",
"cargs",
"[",
"0",
"]",
"]",
")",
"dag",
".",
"extend_back",
"(",
"measure_layer",
")",
"dag",
".",
"remove_op_node",
"(",
"swap",
")",
"return",
"dag"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
left_sample
|
Left sample a continuous function.
Args:
continuous_pulse: Continuous pulse function to sample.
duration: Duration to sample for.
*args: Continuous pulse function args.
**kwargs: Continuous pulse function kwargs.
|
qiskit/pulse/samplers/strategies.py
|
def left_sample(continuous_pulse: Callable, duration: int, *args, **kwargs) -> np.ndarray:
"""Left sample a continuous function.
Args:
continuous_pulse: Continuous pulse function to sample.
duration: Duration to sample for.
*args: Continuous pulse function args.
**kwargs: Continuous pulse function kwargs.
"""
times = np.arange(duration)
return continuous_pulse(times, *args, **kwargs)
|
def left_sample(continuous_pulse: Callable, duration: int, *args, **kwargs) -> np.ndarray:
"""Left sample a continuous function.
Args:
continuous_pulse: Continuous pulse function to sample.
duration: Duration to sample for.
*args: Continuous pulse function args.
**kwargs: Continuous pulse function kwargs.
"""
times = np.arange(duration)
return continuous_pulse(times, *args, **kwargs)
|
[
"Left",
"sample",
"a",
"continuous",
"function",
".",
"Args",
":",
"continuous_pulse",
":",
"Continuous",
"pulse",
"function",
"to",
"sample",
".",
"duration",
":",
"Duration",
"to",
"sample",
"for",
".",
"*",
"args",
":",
"Continuous",
"pulse",
"function",
"args",
".",
"**",
"kwargs",
":",
"Continuous",
"pulse",
"function",
"kwargs",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/samplers/strategies.py#L31-L40
|
[
"def",
"left_sample",
"(",
"continuous_pulse",
":",
"Callable",
",",
"duration",
":",
"int",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"np",
".",
"ndarray",
":",
"times",
"=",
"np",
".",
"arange",
"(",
"duration",
")",
"return",
"continuous_pulse",
"(",
"times",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_to_choi
|
Transform a QuantumChannel to the Choi representation.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _to_choi(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Choi representation."""
if rep == 'Choi':
return data
if rep == 'Operator':
return _from_operator('Choi', data, input_dim, output_dim)
if rep == 'SuperOp':
return _superop_to_choi(data, input_dim, output_dim)
if rep == 'Kraus':
return _kraus_to_choi(data, input_dim, output_dim)
if rep == 'Chi':
return _chi_to_choi(data, input_dim, output_dim)
if rep == 'PTM':
data = _ptm_to_superop(data, input_dim, output_dim)
return _superop_to_choi(data, input_dim, output_dim)
if rep == 'Stinespring':
return _stinespring_to_choi(data, input_dim, output_dim)
raise QiskitError('Invalid QuantumChannel {}'.format(rep))
|
def _to_choi(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Choi representation."""
if rep == 'Choi':
return data
if rep == 'Operator':
return _from_operator('Choi', data, input_dim, output_dim)
if rep == 'SuperOp':
return _superop_to_choi(data, input_dim, output_dim)
if rep == 'Kraus':
return _kraus_to_choi(data, input_dim, output_dim)
if rep == 'Chi':
return _chi_to_choi(data, input_dim, output_dim)
if rep == 'PTM':
data = _ptm_to_superop(data, input_dim, output_dim)
return _superop_to_choi(data, input_dim, output_dim)
if rep == 'Stinespring':
return _stinespring_to_choi(data, input_dim, output_dim)
raise QiskitError('Invalid QuantumChannel {}'.format(rep))
|
[
"Transform",
"a",
"QuantumChannel",
"to",
"the",
"Choi",
"representation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L21-L38
|
[
"def",
"_to_choi",
"(",
"rep",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
":",
"if",
"rep",
"==",
"'Choi'",
":",
"return",
"data",
"if",
"rep",
"==",
"'Operator'",
":",
"return",
"_from_operator",
"(",
"'Choi'",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"if",
"rep",
"==",
"'SuperOp'",
":",
"return",
"_superop_to_choi",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"if",
"rep",
"==",
"'Kraus'",
":",
"return",
"_kraus_to_choi",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"if",
"rep",
"==",
"'Chi'",
":",
"return",
"_chi_to_choi",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"if",
"rep",
"==",
"'PTM'",
":",
"data",
"=",
"_ptm_to_superop",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"return",
"_superop_to_choi",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"if",
"rep",
"==",
"'Stinespring'",
":",
"return",
"_stinespring_to_choi",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"raise",
"QiskitError",
"(",
"'Invalid QuantumChannel {}'",
".",
"format",
"(",
"rep",
")",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_to_superop
|
Transform a QuantumChannel to the SuperOp representation.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _to_superop(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the SuperOp representation."""
if rep == 'SuperOp':
return data
if rep == 'Operator':
return _from_operator('SuperOp', data, input_dim, output_dim)
if rep == 'Choi':
return _choi_to_superop(data, input_dim, output_dim)
if rep == 'Kraus':
return _kraus_to_superop(data, input_dim, output_dim)
if rep == 'Chi':
data = _chi_to_choi(data, input_dim, output_dim)
return _choi_to_superop(data, input_dim, output_dim)
if rep == 'PTM':
return _ptm_to_superop(data, input_dim, output_dim)
if rep == 'Stinespring':
return _stinespring_to_superop(data, input_dim, output_dim)
raise QiskitError('Invalid QuantumChannel {}'.format(rep))
|
def _to_superop(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the SuperOp representation."""
if rep == 'SuperOp':
return data
if rep == 'Operator':
return _from_operator('SuperOp', data, input_dim, output_dim)
if rep == 'Choi':
return _choi_to_superop(data, input_dim, output_dim)
if rep == 'Kraus':
return _kraus_to_superop(data, input_dim, output_dim)
if rep == 'Chi':
data = _chi_to_choi(data, input_dim, output_dim)
return _choi_to_superop(data, input_dim, output_dim)
if rep == 'PTM':
return _ptm_to_superop(data, input_dim, output_dim)
if rep == 'Stinespring':
return _stinespring_to_superop(data, input_dim, output_dim)
raise QiskitError('Invalid QuantumChannel {}'.format(rep))
|
[
"Transform",
"a",
"QuantumChannel",
"to",
"the",
"SuperOp",
"representation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L41-L58
|
[
"def",
"_to_superop",
"(",
"rep",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
":",
"if",
"rep",
"==",
"'SuperOp'",
":",
"return",
"data",
"if",
"rep",
"==",
"'Operator'",
":",
"return",
"_from_operator",
"(",
"'SuperOp'",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"if",
"rep",
"==",
"'Choi'",
":",
"return",
"_choi_to_superop",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"if",
"rep",
"==",
"'Kraus'",
":",
"return",
"_kraus_to_superop",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"if",
"rep",
"==",
"'Chi'",
":",
"data",
"=",
"_chi_to_choi",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"return",
"_choi_to_superop",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"if",
"rep",
"==",
"'PTM'",
":",
"return",
"_ptm_to_superop",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"if",
"rep",
"==",
"'Stinespring'",
":",
"return",
"_stinespring_to_superop",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"raise",
"QiskitError",
"(",
"'Invalid QuantumChannel {}'",
".",
"format",
"(",
"rep",
")",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_to_kraus
|
Transform a QuantumChannel to the Kraus representation.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _to_kraus(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Kraus representation."""
if rep == 'Kraus':
return data
if rep == 'Stinespring':
return _stinespring_to_kraus(data, input_dim, output_dim)
if rep == 'Operator':
return _from_operator('Kraus', data, input_dim, output_dim)
# Convert via Choi and Kraus
if rep != 'Choi':
data = _to_choi(rep, data, input_dim, output_dim)
return _choi_to_kraus(data, input_dim, output_dim)
|
def _to_kraus(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Kraus representation."""
if rep == 'Kraus':
return data
if rep == 'Stinespring':
return _stinespring_to_kraus(data, input_dim, output_dim)
if rep == 'Operator':
return _from_operator('Kraus', data, input_dim, output_dim)
# Convert via Choi and Kraus
if rep != 'Choi':
data = _to_choi(rep, data, input_dim, output_dim)
return _choi_to_kraus(data, input_dim, output_dim)
|
[
"Transform",
"a",
"QuantumChannel",
"to",
"the",
"Kraus",
"representation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L61-L72
|
[
"def",
"_to_kraus",
"(",
"rep",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
":",
"if",
"rep",
"==",
"'Kraus'",
":",
"return",
"data",
"if",
"rep",
"==",
"'Stinespring'",
":",
"return",
"_stinespring_to_kraus",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"if",
"rep",
"==",
"'Operator'",
":",
"return",
"_from_operator",
"(",
"'Kraus'",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"# Convert via Choi and Kraus",
"if",
"rep",
"!=",
"'Choi'",
":",
"data",
"=",
"_to_choi",
"(",
"rep",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"return",
"_choi_to_kraus",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_to_chi
|
Transform a QuantumChannel to the Chi representation.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _to_chi(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Chi representation."""
if rep == 'Chi':
return data
# Check valid n-qubit input
_check_nqubit_dim(input_dim, output_dim)
if rep == 'Operator':
return _from_operator('Chi', data, input_dim, output_dim)
# Convert via Choi representation
if rep != 'Choi':
data = _to_choi(rep, data, input_dim, output_dim)
return _choi_to_chi(data, input_dim, output_dim)
|
def _to_chi(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Chi representation."""
if rep == 'Chi':
return data
# Check valid n-qubit input
_check_nqubit_dim(input_dim, output_dim)
if rep == 'Operator':
return _from_operator('Chi', data, input_dim, output_dim)
# Convert via Choi representation
if rep != 'Choi':
data = _to_choi(rep, data, input_dim, output_dim)
return _choi_to_chi(data, input_dim, output_dim)
|
[
"Transform",
"a",
"QuantumChannel",
"to",
"the",
"Chi",
"representation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L75-L86
|
[
"def",
"_to_chi",
"(",
"rep",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
":",
"if",
"rep",
"==",
"'Chi'",
":",
"return",
"data",
"# Check valid n-qubit input",
"_check_nqubit_dim",
"(",
"input_dim",
",",
"output_dim",
")",
"if",
"rep",
"==",
"'Operator'",
":",
"return",
"_from_operator",
"(",
"'Chi'",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"# Convert via Choi representation",
"if",
"rep",
"!=",
"'Choi'",
":",
"data",
"=",
"_to_choi",
"(",
"rep",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"return",
"_choi_to_chi",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_to_ptm
|
Transform a QuantumChannel to the PTM representation.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _to_ptm(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the PTM representation."""
if rep == 'PTM':
return data
# Check valid n-qubit input
_check_nqubit_dim(input_dim, output_dim)
if rep == 'Operator':
return _from_operator('PTM', data, input_dim, output_dim)
# Convert via Superoperator representation
if rep != 'SuperOp':
data = _to_superop(rep, data, input_dim, output_dim)
return _superop_to_ptm(data, input_dim, output_dim)
|
def _to_ptm(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the PTM representation."""
if rep == 'PTM':
return data
# Check valid n-qubit input
_check_nqubit_dim(input_dim, output_dim)
if rep == 'Operator':
return _from_operator('PTM', data, input_dim, output_dim)
# Convert via Superoperator representation
if rep != 'SuperOp':
data = _to_superop(rep, data, input_dim, output_dim)
return _superop_to_ptm(data, input_dim, output_dim)
|
[
"Transform",
"a",
"QuantumChannel",
"to",
"the",
"PTM",
"representation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L89-L100
|
[
"def",
"_to_ptm",
"(",
"rep",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
":",
"if",
"rep",
"==",
"'PTM'",
":",
"return",
"data",
"# Check valid n-qubit input",
"_check_nqubit_dim",
"(",
"input_dim",
",",
"output_dim",
")",
"if",
"rep",
"==",
"'Operator'",
":",
"return",
"_from_operator",
"(",
"'PTM'",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"# Convert via Superoperator representation",
"if",
"rep",
"!=",
"'SuperOp'",
":",
"data",
"=",
"_to_superop",
"(",
"rep",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"return",
"_superop_to_ptm",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_to_stinespring
|
Transform a QuantumChannel to the Stinespring representation.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _to_stinespring(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Stinespring representation."""
if rep == 'Stinespring':
return data
if rep == 'Operator':
return _from_operator('Stinespring', data, input_dim, output_dim)
# Convert via Superoperator representation
if rep != 'Kraus':
data = _to_kraus(rep, data, input_dim, output_dim)
return _kraus_to_stinespring(data, input_dim, output_dim)
|
def _to_stinespring(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Stinespring representation."""
if rep == 'Stinespring':
return data
if rep == 'Operator':
return _from_operator('Stinespring', data, input_dim, output_dim)
# Convert via Superoperator representation
if rep != 'Kraus':
data = _to_kraus(rep, data, input_dim, output_dim)
return _kraus_to_stinespring(data, input_dim, output_dim)
|
[
"Transform",
"a",
"QuantumChannel",
"to",
"the",
"Stinespring",
"representation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L103-L112
|
[
"def",
"_to_stinespring",
"(",
"rep",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
":",
"if",
"rep",
"==",
"'Stinespring'",
":",
"return",
"data",
"if",
"rep",
"==",
"'Operator'",
":",
"return",
"_from_operator",
"(",
"'Stinespring'",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"# Convert via Superoperator representation",
"if",
"rep",
"!=",
"'Kraus'",
":",
"data",
"=",
"_to_kraus",
"(",
"rep",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"return",
"_kraus_to_stinespring",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_to_operator
|
Transform a QuantumChannel to the Operator representation.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _to_operator(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Operator representation."""
if rep == 'Operator':
return data
if rep == 'Stinespring':
return _stinespring_to_operator(data, input_dim, output_dim)
# Convert via Kraus representation
if rep != 'Kraus':
data = _to_kraus(rep, data, input_dim, output_dim)
return _kraus_to_operator(data, input_dim, output_dim)
|
def _to_operator(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Operator representation."""
if rep == 'Operator':
return data
if rep == 'Stinespring':
return _stinespring_to_operator(data, input_dim, output_dim)
# Convert via Kraus representation
if rep != 'Kraus':
data = _to_kraus(rep, data, input_dim, output_dim)
return _kraus_to_operator(data, input_dim, output_dim)
|
[
"Transform",
"a",
"QuantumChannel",
"to",
"the",
"Operator",
"representation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L115-L124
|
[
"def",
"_to_operator",
"(",
"rep",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
":",
"if",
"rep",
"==",
"'Operator'",
":",
"return",
"data",
"if",
"rep",
"==",
"'Stinespring'",
":",
"return",
"_stinespring_to_operator",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"# Convert via Kraus representation",
"if",
"rep",
"!=",
"'Kraus'",
":",
"data",
"=",
"_to_kraus",
"(",
"rep",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"return",
"_kraus_to_operator",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_from_operator
|
Transform Operator representation to other representation.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _from_operator(rep, data, input_dim, output_dim):
"""Transform Operator representation to other representation."""
if rep == 'Operator':
return data
if rep == 'SuperOp':
return np.kron(np.conj(data), data)
if rep == 'Choi':
vec = np.ravel(data, order='F')
return np.outer(vec, np.conj(vec))
if rep == 'Kraus':
return ([data], None)
if rep == 'Stinespring':
return (data, None)
if rep == 'Chi':
_check_nqubit_dim(input_dim, output_dim)
data = _from_operator('Choi', data, input_dim, output_dim)
return _choi_to_chi(data, input_dim, output_dim)
if rep == 'PTM':
_check_nqubit_dim(input_dim, output_dim)
data = _from_operator('SuperOp', data, input_dim, output_dim)
return _superop_to_ptm(data, input_dim, output_dim)
raise QiskitError('Invalid QuantumChannel {}'.format(rep))
|
def _from_operator(rep, data, input_dim, output_dim):
"""Transform Operator representation to other representation."""
if rep == 'Operator':
return data
if rep == 'SuperOp':
return np.kron(np.conj(data), data)
if rep == 'Choi':
vec = np.ravel(data, order='F')
return np.outer(vec, np.conj(vec))
if rep == 'Kraus':
return ([data], None)
if rep == 'Stinespring':
return (data, None)
if rep == 'Chi':
_check_nqubit_dim(input_dim, output_dim)
data = _from_operator('Choi', data, input_dim, output_dim)
return _choi_to_chi(data, input_dim, output_dim)
if rep == 'PTM':
_check_nqubit_dim(input_dim, output_dim)
data = _from_operator('SuperOp', data, input_dim, output_dim)
return _superop_to_ptm(data, input_dim, output_dim)
raise QiskitError('Invalid QuantumChannel {}'.format(rep))
|
[
"Transform",
"Operator",
"representation",
"to",
"other",
"representation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L127-L148
|
[
"def",
"_from_operator",
"(",
"rep",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
":",
"if",
"rep",
"==",
"'Operator'",
":",
"return",
"data",
"if",
"rep",
"==",
"'SuperOp'",
":",
"return",
"np",
".",
"kron",
"(",
"np",
".",
"conj",
"(",
"data",
")",
",",
"data",
")",
"if",
"rep",
"==",
"'Choi'",
":",
"vec",
"=",
"np",
".",
"ravel",
"(",
"data",
",",
"order",
"=",
"'F'",
")",
"return",
"np",
".",
"outer",
"(",
"vec",
",",
"np",
".",
"conj",
"(",
"vec",
")",
")",
"if",
"rep",
"==",
"'Kraus'",
":",
"return",
"(",
"[",
"data",
"]",
",",
"None",
")",
"if",
"rep",
"==",
"'Stinespring'",
":",
"return",
"(",
"data",
",",
"None",
")",
"if",
"rep",
"==",
"'Chi'",
":",
"_check_nqubit_dim",
"(",
"input_dim",
",",
"output_dim",
")",
"data",
"=",
"_from_operator",
"(",
"'Choi'",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"return",
"_choi_to_chi",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"if",
"rep",
"==",
"'PTM'",
":",
"_check_nqubit_dim",
"(",
"input_dim",
",",
"output_dim",
")",
"data",
"=",
"_from_operator",
"(",
"'SuperOp'",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"return",
"_superop_to_ptm",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
"raise",
"QiskitError",
"(",
"'Invalid QuantumChannel {}'",
".",
"format",
"(",
"rep",
")",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_stinespring_to_operator
|
Transform Stinespring representation to Operator representation.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _stinespring_to_operator(data, input_dim, output_dim):
"""Transform Stinespring representation to Operator representation."""
trace_dim = data[0].shape[0] // output_dim
if data[1] is not None or trace_dim != 1:
raise QiskitError(
'Channel cannot be converted to Operator representation')
return data[0]
|
def _stinespring_to_operator(data, input_dim, output_dim):
"""Transform Stinespring representation to Operator representation."""
trace_dim = data[0].shape[0] // output_dim
if data[1] is not None or trace_dim != 1:
raise QiskitError(
'Channel cannot be converted to Operator representation')
return data[0]
|
[
"Transform",
"Stinespring",
"representation",
"to",
"Operator",
"representation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L159-L165
|
[
"def",
"_stinespring_to_operator",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
":",
"trace_dim",
"=",
"data",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
"//",
"output_dim",
"if",
"data",
"[",
"1",
"]",
"is",
"not",
"None",
"or",
"trace_dim",
"!=",
"1",
":",
"raise",
"QiskitError",
"(",
"'Channel cannot be converted to Operator representation'",
")",
"return",
"data",
"[",
"0",
"]"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_superop_to_choi
|
Transform SuperOp representation to Choi representation.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _superop_to_choi(data, input_dim, output_dim):
"""Transform SuperOp representation to Choi representation."""
shape = (output_dim, output_dim, input_dim, input_dim)
return _reshuffle(data, shape)
|
def _superop_to_choi(data, input_dim, output_dim):
"""Transform SuperOp representation to Choi representation."""
shape = (output_dim, output_dim, input_dim, input_dim)
return _reshuffle(data, shape)
|
[
"Transform",
"SuperOp",
"representation",
"to",
"Choi",
"representation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L168-L171
|
[
"def",
"_superop_to_choi",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
":",
"shape",
"=",
"(",
"output_dim",
",",
"output_dim",
",",
"input_dim",
",",
"input_dim",
")",
"return",
"_reshuffle",
"(",
"data",
",",
"shape",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_choi_to_superop
|
Transform Choi to SuperOp representation.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _choi_to_superop(data, input_dim, output_dim):
"""Transform Choi to SuperOp representation."""
shape = (input_dim, output_dim, input_dim, output_dim)
return _reshuffle(data, shape)
|
def _choi_to_superop(data, input_dim, output_dim):
"""Transform Choi to SuperOp representation."""
shape = (input_dim, output_dim, input_dim, output_dim)
return _reshuffle(data, shape)
|
[
"Transform",
"Choi",
"to",
"SuperOp",
"representation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L174-L177
|
[
"def",
"_choi_to_superop",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
":",
"shape",
"=",
"(",
"input_dim",
",",
"output_dim",
",",
"input_dim",
",",
"output_dim",
")",
"return",
"_reshuffle",
"(",
"data",
",",
"shape",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_kraus_to_choi
|
Transform Kraus representation to Choi representation.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _kraus_to_choi(data, input_dim, output_dim):
"""Transform Kraus representation to Choi representation."""
choi = 0
kraus_l, kraus_r = data
if kraus_r is None:
for i in kraus_l:
vec = i.ravel(order='F')
choi += np.outer(vec, vec.conj())
else:
for i, j in zip(kraus_l, kraus_r):
choi += np.outer(i.ravel(order='F'), j.ravel(order='F').conj())
return choi
|
def _kraus_to_choi(data, input_dim, output_dim):
"""Transform Kraus representation to Choi representation."""
choi = 0
kraus_l, kraus_r = data
if kraus_r is None:
for i in kraus_l:
vec = i.ravel(order='F')
choi += np.outer(vec, vec.conj())
else:
for i, j in zip(kraus_l, kraus_r):
choi += np.outer(i.ravel(order='F'), j.ravel(order='F').conj())
return choi
|
[
"Transform",
"Kraus",
"representation",
"to",
"Choi",
"representation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L180-L191
|
[
"def",
"_kraus_to_choi",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
":",
"choi",
"=",
"0",
"kraus_l",
",",
"kraus_r",
"=",
"data",
"if",
"kraus_r",
"is",
"None",
":",
"for",
"i",
"in",
"kraus_l",
":",
"vec",
"=",
"i",
".",
"ravel",
"(",
"order",
"=",
"'F'",
")",
"choi",
"+=",
"np",
".",
"outer",
"(",
"vec",
",",
"vec",
".",
"conj",
"(",
")",
")",
"else",
":",
"for",
"i",
",",
"j",
"in",
"zip",
"(",
"kraus_l",
",",
"kraus_r",
")",
":",
"choi",
"+=",
"np",
".",
"outer",
"(",
"i",
".",
"ravel",
"(",
"order",
"=",
"'F'",
")",
",",
"j",
".",
"ravel",
"(",
"order",
"=",
"'F'",
")",
".",
"conj",
"(",
")",
")",
"return",
"choi"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_choi_to_kraus
|
Transform Choi representation to Kraus representation.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _choi_to_kraus(data, input_dim, output_dim, atol=ATOL_DEFAULT):
"""Transform Choi representation to Kraus representation."""
# Check if hermitian matrix
if is_hermitian_matrix(data, atol=atol):
# Get eigen-decomposition of Choi-matrix
w, v = la.eigh(data)
# Check eigenvaleus are non-negative
if len(w[w < -atol]) == 0:
# CP-map Kraus representation
kraus = []
for val, vec in zip(w, v.T):
if abs(val) > atol:
k = np.sqrt(val) * vec.reshape(
(output_dim, input_dim), order='F')
kraus.append(k)
# If we are converting a zero matrix, we need to return a Kraus set
# with a single zero-element Kraus matrix
if not kraus:
kraus.append(np.zeros((output_dim, input_dim), dtype=complex))
return (kraus, None)
# Non-CP-map generalized Kraus representation
mat_u, svals, mat_vh = la.svd(data)
kraus_l = []
kraus_r = []
for val, vec_l, vec_r in zip(svals, mat_u.T, mat_vh.conj()):
kraus_l.append(
np.sqrt(val) * vec_l.reshape((output_dim, input_dim), order='F'))
kraus_r.append(
np.sqrt(val) * vec_r.reshape((output_dim, input_dim), order='F'))
return (kraus_l, kraus_r)
|
def _choi_to_kraus(data, input_dim, output_dim, atol=ATOL_DEFAULT):
"""Transform Choi representation to Kraus representation."""
# Check if hermitian matrix
if is_hermitian_matrix(data, atol=atol):
# Get eigen-decomposition of Choi-matrix
w, v = la.eigh(data)
# Check eigenvaleus are non-negative
if len(w[w < -atol]) == 0:
# CP-map Kraus representation
kraus = []
for val, vec in zip(w, v.T):
if abs(val) > atol:
k = np.sqrt(val) * vec.reshape(
(output_dim, input_dim), order='F')
kraus.append(k)
# If we are converting a zero matrix, we need to return a Kraus set
# with a single zero-element Kraus matrix
if not kraus:
kraus.append(np.zeros((output_dim, input_dim), dtype=complex))
return (kraus, None)
# Non-CP-map generalized Kraus representation
mat_u, svals, mat_vh = la.svd(data)
kraus_l = []
kraus_r = []
for val, vec_l, vec_r in zip(svals, mat_u.T, mat_vh.conj()):
kraus_l.append(
np.sqrt(val) * vec_l.reshape((output_dim, input_dim), order='F'))
kraus_r.append(
np.sqrt(val) * vec_r.reshape((output_dim, input_dim), order='F'))
return (kraus_l, kraus_r)
|
[
"Transform",
"Choi",
"representation",
"to",
"Kraus",
"representation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L194-L223
|
[
"def",
"_choi_to_kraus",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
",",
"atol",
"=",
"ATOL_DEFAULT",
")",
":",
"# Check if hermitian matrix",
"if",
"is_hermitian_matrix",
"(",
"data",
",",
"atol",
"=",
"atol",
")",
":",
"# Get eigen-decomposition of Choi-matrix",
"w",
",",
"v",
"=",
"la",
".",
"eigh",
"(",
"data",
")",
"# Check eigenvaleus are non-negative",
"if",
"len",
"(",
"w",
"[",
"w",
"<",
"-",
"atol",
"]",
")",
"==",
"0",
":",
"# CP-map Kraus representation",
"kraus",
"=",
"[",
"]",
"for",
"val",
",",
"vec",
"in",
"zip",
"(",
"w",
",",
"v",
".",
"T",
")",
":",
"if",
"abs",
"(",
"val",
")",
">",
"atol",
":",
"k",
"=",
"np",
".",
"sqrt",
"(",
"val",
")",
"*",
"vec",
".",
"reshape",
"(",
"(",
"output_dim",
",",
"input_dim",
")",
",",
"order",
"=",
"'F'",
")",
"kraus",
".",
"append",
"(",
"k",
")",
"# If we are converting a zero matrix, we need to return a Kraus set",
"# with a single zero-element Kraus matrix",
"if",
"not",
"kraus",
":",
"kraus",
".",
"append",
"(",
"np",
".",
"zeros",
"(",
"(",
"output_dim",
",",
"input_dim",
")",
",",
"dtype",
"=",
"complex",
")",
")",
"return",
"(",
"kraus",
",",
"None",
")",
"# Non-CP-map generalized Kraus representation",
"mat_u",
",",
"svals",
",",
"mat_vh",
"=",
"la",
".",
"svd",
"(",
"data",
")",
"kraus_l",
"=",
"[",
"]",
"kraus_r",
"=",
"[",
"]",
"for",
"val",
",",
"vec_l",
",",
"vec_r",
"in",
"zip",
"(",
"svals",
",",
"mat_u",
".",
"T",
",",
"mat_vh",
".",
"conj",
"(",
")",
")",
":",
"kraus_l",
".",
"append",
"(",
"np",
".",
"sqrt",
"(",
"val",
")",
"*",
"vec_l",
".",
"reshape",
"(",
"(",
"output_dim",
",",
"input_dim",
")",
",",
"order",
"=",
"'F'",
")",
")",
"kraus_r",
".",
"append",
"(",
"np",
".",
"sqrt",
"(",
"val",
")",
"*",
"vec_r",
".",
"reshape",
"(",
"(",
"output_dim",
",",
"input_dim",
")",
",",
"order",
"=",
"'F'",
")",
")",
"return",
"(",
"kraus_l",
",",
"kraus_r",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_stinespring_to_kraus
|
Transform Stinespring representation to Kraus representation.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _stinespring_to_kraus(data, input_dim, output_dim):
"""Transform Stinespring representation to Kraus representation."""
kraus_pair = []
for stine in data:
if stine is None:
kraus_pair.append(None)
else:
trace_dim = stine.shape[0] // output_dim
iden = np.eye(output_dim)
kraus = []
for j in range(trace_dim):
vec = np.zeros(trace_dim)
vec[j] = 1
kraus.append(np.kron(iden, vec[None, :]).dot(stine))
kraus_pair.append(kraus)
return tuple(kraus_pair)
|
def _stinespring_to_kraus(data, input_dim, output_dim):
"""Transform Stinespring representation to Kraus representation."""
kraus_pair = []
for stine in data:
if stine is None:
kraus_pair.append(None)
else:
trace_dim = stine.shape[0] // output_dim
iden = np.eye(output_dim)
kraus = []
for j in range(trace_dim):
vec = np.zeros(trace_dim)
vec[j] = 1
kraus.append(np.kron(iden, vec[None, :]).dot(stine))
kraus_pair.append(kraus)
return tuple(kraus_pair)
|
[
"Transform",
"Stinespring",
"representation",
"to",
"Kraus",
"representation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L226-L241
|
[
"def",
"_stinespring_to_kraus",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
":",
"kraus_pair",
"=",
"[",
"]",
"for",
"stine",
"in",
"data",
":",
"if",
"stine",
"is",
"None",
":",
"kraus_pair",
".",
"append",
"(",
"None",
")",
"else",
":",
"trace_dim",
"=",
"stine",
".",
"shape",
"[",
"0",
"]",
"//",
"output_dim",
"iden",
"=",
"np",
".",
"eye",
"(",
"output_dim",
")",
"kraus",
"=",
"[",
"]",
"for",
"j",
"in",
"range",
"(",
"trace_dim",
")",
":",
"vec",
"=",
"np",
".",
"zeros",
"(",
"trace_dim",
")",
"vec",
"[",
"j",
"]",
"=",
"1",
"kraus",
".",
"append",
"(",
"np",
".",
"kron",
"(",
"iden",
",",
"vec",
"[",
"None",
",",
":",
"]",
")",
".",
"dot",
"(",
"stine",
")",
")",
"kraus_pair",
".",
"append",
"(",
"kraus",
")",
"return",
"tuple",
"(",
"kraus_pair",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_stinespring_to_choi
|
Transform Stinespring representation to Choi representation.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _stinespring_to_choi(data, input_dim, output_dim):
"""Transform Stinespring representation to Choi representation."""
trace_dim = data[0].shape[0] // output_dim
stine_l = np.reshape(data[0], (output_dim, trace_dim, input_dim))
if data[1] is None:
stine_r = stine_l
else:
stine_r = np.reshape(data[1], (output_dim, trace_dim, input_dim))
return np.reshape(
np.einsum('iAj,kAl->jilk', stine_l, stine_r.conj()),
2 * [input_dim * output_dim])
|
def _stinespring_to_choi(data, input_dim, output_dim):
"""Transform Stinespring representation to Choi representation."""
trace_dim = data[0].shape[0] // output_dim
stine_l = np.reshape(data[0], (output_dim, trace_dim, input_dim))
if data[1] is None:
stine_r = stine_l
else:
stine_r = np.reshape(data[1], (output_dim, trace_dim, input_dim))
return np.reshape(
np.einsum('iAj,kAl->jilk', stine_l, stine_r.conj()),
2 * [input_dim * output_dim])
|
[
"Transform",
"Stinespring",
"representation",
"to",
"Choi",
"representation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L244-L254
|
[
"def",
"_stinespring_to_choi",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
":",
"trace_dim",
"=",
"data",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
"//",
"output_dim",
"stine_l",
"=",
"np",
".",
"reshape",
"(",
"data",
"[",
"0",
"]",
",",
"(",
"output_dim",
",",
"trace_dim",
",",
"input_dim",
")",
")",
"if",
"data",
"[",
"1",
"]",
"is",
"None",
":",
"stine_r",
"=",
"stine_l",
"else",
":",
"stine_r",
"=",
"np",
".",
"reshape",
"(",
"data",
"[",
"1",
"]",
",",
"(",
"output_dim",
",",
"trace_dim",
",",
"input_dim",
")",
")",
"return",
"np",
".",
"reshape",
"(",
"np",
".",
"einsum",
"(",
"'iAj,kAl->jilk'",
",",
"stine_l",
",",
"stine_r",
".",
"conj",
"(",
")",
")",
",",
"2",
"*",
"[",
"input_dim",
"*",
"output_dim",
"]",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_kraus_to_stinespring
|
Transform Kraus representation to Stinespring representation.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _kraus_to_stinespring(data, input_dim, output_dim):
"""Transform Kraus representation to Stinespring representation."""
stine_pair = [None, None]
for i, kraus in enumerate(data):
if kraus is not None:
num_kraus = len(kraus)
stine = np.zeros((output_dim * num_kraus, input_dim),
dtype=complex)
for j, mat in enumerate(kraus):
vec = np.zeros(num_kraus)
vec[j] = 1
stine += np.kron(mat, vec[:, None])
stine_pair[i] = stine
return tuple(stine_pair)
|
def _kraus_to_stinespring(data, input_dim, output_dim):
"""Transform Kraus representation to Stinespring representation."""
stine_pair = [None, None]
for i, kraus in enumerate(data):
if kraus is not None:
num_kraus = len(kraus)
stine = np.zeros((output_dim * num_kraus, input_dim),
dtype=complex)
for j, mat in enumerate(kraus):
vec = np.zeros(num_kraus)
vec[j] = 1
stine += np.kron(mat, vec[:, None])
stine_pair[i] = stine
return tuple(stine_pair)
|
[
"Transform",
"Kraus",
"representation",
"to",
"Stinespring",
"representation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L270-L283
|
[
"def",
"_kraus_to_stinespring",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
":",
"stine_pair",
"=",
"[",
"None",
",",
"None",
"]",
"for",
"i",
",",
"kraus",
"in",
"enumerate",
"(",
"data",
")",
":",
"if",
"kraus",
"is",
"not",
"None",
":",
"num_kraus",
"=",
"len",
"(",
"kraus",
")",
"stine",
"=",
"np",
".",
"zeros",
"(",
"(",
"output_dim",
"*",
"num_kraus",
",",
"input_dim",
")",
",",
"dtype",
"=",
"complex",
")",
"for",
"j",
",",
"mat",
"in",
"enumerate",
"(",
"kraus",
")",
":",
"vec",
"=",
"np",
".",
"zeros",
"(",
"num_kraus",
")",
"vec",
"[",
"j",
"]",
"=",
"1",
"stine",
"+=",
"np",
".",
"kron",
"(",
"mat",
",",
"vec",
"[",
":",
",",
"None",
"]",
")",
"stine_pair",
"[",
"i",
"]",
"=",
"stine",
"return",
"tuple",
"(",
"stine_pair",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_kraus_to_superop
|
Transform Kraus representation to SuperOp representation.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _kraus_to_superop(data, input_dim, output_dim):
"""Transform Kraus representation to SuperOp representation."""
kraus_l, kraus_r = data
superop = 0
if kraus_r is None:
for i in kraus_l:
superop += np.kron(np.conj(i), i)
else:
for i, j in zip(kraus_l, kraus_r):
superop += np.kron(np.conj(j), i)
return superop
|
def _kraus_to_superop(data, input_dim, output_dim):
"""Transform Kraus representation to SuperOp representation."""
kraus_l, kraus_r = data
superop = 0
if kraus_r is None:
for i in kraus_l:
superop += np.kron(np.conj(i), i)
else:
for i, j in zip(kraus_l, kraus_r):
superop += np.kron(np.conj(j), i)
return superop
|
[
"Transform",
"Kraus",
"representation",
"to",
"SuperOp",
"representation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L286-L296
|
[
"def",
"_kraus_to_superop",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
":",
"kraus_l",
",",
"kraus_r",
"=",
"data",
"superop",
"=",
"0",
"if",
"kraus_r",
"is",
"None",
":",
"for",
"i",
"in",
"kraus_l",
":",
"superop",
"+=",
"np",
".",
"kron",
"(",
"np",
".",
"conj",
"(",
"i",
")",
",",
"i",
")",
"else",
":",
"for",
"i",
",",
"j",
"in",
"zip",
"(",
"kraus_l",
",",
"kraus_r",
")",
":",
"superop",
"+=",
"np",
".",
"kron",
"(",
"np",
".",
"conj",
"(",
"j",
")",
",",
"i",
")",
"return",
"superop"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_chi_to_choi
|
Transform Chi representation to a Choi representation.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _chi_to_choi(data, input_dim, output_dim):
"""Transform Chi representation to a Choi representation."""
num_qubits = int(np.log2(input_dim))
return _transform_from_pauli(data, num_qubits)
|
def _chi_to_choi(data, input_dim, output_dim):
"""Transform Chi representation to a Choi representation."""
num_qubits = int(np.log2(input_dim))
return _transform_from_pauli(data, num_qubits)
|
[
"Transform",
"Chi",
"representation",
"to",
"a",
"Choi",
"representation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L299-L302
|
[
"def",
"_chi_to_choi",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
":",
"num_qubits",
"=",
"int",
"(",
"np",
".",
"log2",
"(",
"input_dim",
")",
")",
"return",
"_transform_from_pauli",
"(",
"data",
",",
"num_qubits",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_choi_to_chi
|
Transform Choi representation to the Chi representation.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _choi_to_chi(data, input_dim, output_dim):
"""Transform Choi representation to the Chi representation."""
num_qubits = int(np.log2(input_dim))
return _transform_to_pauli(data, num_qubits)
|
def _choi_to_chi(data, input_dim, output_dim):
"""Transform Choi representation to the Chi representation."""
num_qubits = int(np.log2(input_dim))
return _transform_to_pauli(data, num_qubits)
|
[
"Transform",
"Choi",
"representation",
"to",
"the",
"Chi",
"representation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L305-L308
|
[
"def",
"_choi_to_chi",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
":",
"num_qubits",
"=",
"int",
"(",
"np",
".",
"log2",
"(",
"input_dim",
")",
")",
"return",
"_transform_to_pauli",
"(",
"data",
",",
"num_qubits",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_bipartite_tensor
|
Tensor product (A ⊗ B) to bipartite matrices and reravel indicies.
This is used for tensor product of superoperators and Choi matrices.
Args:
mat1 (matrix_like): a bipartite matrix A
mat2 (matrix_like): a bipartite matrix B
shape1 (tuple): bipartite-shape for matrix A (a0, a1, a2, a3)
shape2 (tuple): bipartite-shape for matrix B (b0, b1, b2, b3)
Returns:
np.array: a bipartite matrix for reravel(A ⊗ B).
Raises:
QiskitError: if input matrices are wrong shape.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _bipartite_tensor(mat1, mat2, shape1=None, shape2=None):
"""Tensor product (A ⊗ B) to bipartite matrices and reravel indicies.
This is used for tensor product of superoperators and Choi matrices.
Args:
mat1 (matrix_like): a bipartite matrix A
mat2 (matrix_like): a bipartite matrix B
shape1 (tuple): bipartite-shape for matrix A (a0, a1, a2, a3)
shape2 (tuple): bipartite-shape for matrix B (b0, b1, b2, b3)
Returns:
np.array: a bipartite matrix for reravel(A ⊗ B).
Raises:
QiskitError: if input matrices are wrong shape.
"""
# Convert inputs to numpy arrays
mat1 = np.array(mat1)
mat2 = np.array(mat2)
# Determine bipartite dimensions if not provided
dim_a0, dim_a1 = mat1.shape
dim_b0, dim_b1 = mat2.shape
if shape1 is None:
sdim_a0 = int(np.sqrt(dim_a0))
sdim_a1 = int(np.sqrt(dim_a1))
shape1 = (sdim_a0, sdim_a0, sdim_a1, sdim_a1)
if shape2 is None:
sdim_b0 = int(np.sqrt(dim_b0))
sdim_b1 = int(np.sqrt(dim_b1))
shape2 = (sdim_b0, sdim_b0, sdim_b1, sdim_b1)
# Check dimensions
if len(shape1) != 4 or shape1[0] * shape1[1] != dim_a0 or \
shape1[2] * shape1[3] != dim_a1:
raise QiskitError("Invalid shape_a")
if len(shape2) != 4 or shape2[0] * shape2[1] != dim_b0 or \
shape2[2] * shape2[3] != dim_b1:
raise QiskitError("Invalid shape_b")
return _reravel(mat1, mat2, shape1, shape2)
|
def _bipartite_tensor(mat1, mat2, shape1=None, shape2=None):
"""Tensor product (A ⊗ B) to bipartite matrices and reravel indicies.
This is used for tensor product of superoperators and Choi matrices.
Args:
mat1 (matrix_like): a bipartite matrix A
mat2 (matrix_like): a bipartite matrix B
shape1 (tuple): bipartite-shape for matrix A (a0, a1, a2, a3)
shape2 (tuple): bipartite-shape for matrix B (b0, b1, b2, b3)
Returns:
np.array: a bipartite matrix for reravel(A ⊗ B).
Raises:
QiskitError: if input matrices are wrong shape.
"""
# Convert inputs to numpy arrays
mat1 = np.array(mat1)
mat2 = np.array(mat2)
# Determine bipartite dimensions if not provided
dim_a0, dim_a1 = mat1.shape
dim_b0, dim_b1 = mat2.shape
if shape1 is None:
sdim_a0 = int(np.sqrt(dim_a0))
sdim_a1 = int(np.sqrt(dim_a1))
shape1 = (sdim_a0, sdim_a0, sdim_a1, sdim_a1)
if shape2 is None:
sdim_b0 = int(np.sqrt(dim_b0))
sdim_b1 = int(np.sqrt(dim_b1))
shape2 = (sdim_b0, sdim_b0, sdim_b1, sdim_b1)
# Check dimensions
if len(shape1) != 4 or shape1[0] * shape1[1] != dim_a0 or \
shape1[2] * shape1[3] != dim_a1:
raise QiskitError("Invalid shape_a")
if len(shape2) != 4 or shape2[0] * shape2[1] != dim_b0 or \
shape2[2] * shape2[3] != dim_b1:
raise QiskitError("Invalid shape_b")
return _reravel(mat1, mat2, shape1, shape2)
|
[
"Tensor",
"product",
"(",
"A",
"⊗",
"B",
")",
"to",
"bipartite",
"matrices",
"and",
"reravel",
"indicies",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L323-L363
|
[
"def",
"_bipartite_tensor",
"(",
"mat1",
",",
"mat2",
",",
"shape1",
"=",
"None",
",",
"shape2",
"=",
"None",
")",
":",
"# Convert inputs to numpy arrays",
"mat1",
"=",
"np",
".",
"array",
"(",
"mat1",
")",
"mat2",
"=",
"np",
".",
"array",
"(",
"mat2",
")",
"# Determine bipartite dimensions if not provided",
"dim_a0",
",",
"dim_a1",
"=",
"mat1",
".",
"shape",
"dim_b0",
",",
"dim_b1",
"=",
"mat2",
".",
"shape",
"if",
"shape1",
"is",
"None",
":",
"sdim_a0",
"=",
"int",
"(",
"np",
".",
"sqrt",
"(",
"dim_a0",
")",
")",
"sdim_a1",
"=",
"int",
"(",
"np",
".",
"sqrt",
"(",
"dim_a1",
")",
")",
"shape1",
"=",
"(",
"sdim_a0",
",",
"sdim_a0",
",",
"sdim_a1",
",",
"sdim_a1",
")",
"if",
"shape2",
"is",
"None",
":",
"sdim_b0",
"=",
"int",
"(",
"np",
".",
"sqrt",
"(",
"dim_b0",
")",
")",
"sdim_b1",
"=",
"int",
"(",
"np",
".",
"sqrt",
"(",
"dim_b1",
")",
")",
"shape2",
"=",
"(",
"sdim_b0",
",",
"sdim_b0",
",",
"sdim_b1",
",",
"sdim_b1",
")",
"# Check dimensions",
"if",
"len",
"(",
"shape1",
")",
"!=",
"4",
"or",
"shape1",
"[",
"0",
"]",
"*",
"shape1",
"[",
"1",
"]",
"!=",
"dim_a0",
"or",
"shape1",
"[",
"2",
"]",
"*",
"shape1",
"[",
"3",
"]",
"!=",
"dim_a1",
":",
"raise",
"QiskitError",
"(",
"\"Invalid shape_a\"",
")",
"if",
"len",
"(",
"shape2",
")",
"!=",
"4",
"or",
"shape2",
"[",
"0",
"]",
"*",
"shape2",
"[",
"1",
"]",
"!=",
"dim_b0",
"or",
"shape2",
"[",
"2",
"]",
"*",
"shape2",
"[",
"3",
"]",
"!=",
"dim_b1",
":",
"raise",
"QiskitError",
"(",
"\"Invalid shape_b\"",
")",
"return",
"_reravel",
"(",
"mat1",
",",
"mat2",
",",
"shape1",
",",
"shape2",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_reravel
|
Reravel two bipartite matrices.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _reravel(mat1, mat2, shape1, shape2):
"""Reravel two bipartite matrices."""
# Reshuffle indicies
left_dims = shape1[:2] + shape2[:2]
right_dims = shape1[2:] + shape2[2:]
tensor_shape = left_dims + right_dims
final_shape = (np.product(left_dims), np.product(right_dims))
# Tensor product matrices
data = np.kron(mat1, mat2)
data = np.reshape(
np.transpose(np.reshape(data, tensor_shape), (0, 2, 1, 3, 4, 6, 5, 7)),
final_shape)
return data
|
def _reravel(mat1, mat2, shape1, shape2):
"""Reravel two bipartite matrices."""
# Reshuffle indicies
left_dims = shape1[:2] + shape2[:2]
right_dims = shape1[2:] + shape2[2:]
tensor_shape = left_dims + right_dims
final_shape = (np.product(left_dims), np.product(right_dims))
# Tensor product matrices
data = np.kron(mat1, mat2)
data = np.reshape(
np.transpose(np.reshape(data, tensor_shape), (0, 2, 1, 3, 4, 6, 5, 7)),
final_shape)
return data
|
[
"Reravel",
"two",
"bipartite",
"matrices",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L366-L378
|
[
"def",
"_reravel",
"(",
"mat1",
",",
"mat2",
",",
"shape1",
",",
"shape2",
")",
":",
"# Reshuffle indicies",
"left_dims",
"=",
"shape1",
"[",
":",
"2",
"]",
"+",
"shape2",
"[",
":",
"2",
"]",
"right_dims",
"=",
"shape1",
"[",
"2",
":",
"]",
"+",
"shape2",
"[",
"2",
":",
"]",
"tensor_shape",
"=",
"left_dims",
"+",
"right_dims",
"final_shape",
"=",
"(",
"np",
".",
"product",
"(",
"left_dims",
")",
",",
"np",
".",
"product",
"(",
"right_dims",
")",
")",
"# Tensor product matrices",
"data",
"=",
"np",
".",
"kron",
"(",
"mat1",
",",
"mat2",
")",
"data",
"=",
"np",
".",
"reshape",
"(",
"np",
".",
"transpose",
"(",
"np",
".",
"reshape",
"(",
"data",
",",
"tensor_shape",
")",
",",
"(",
"0",
",",
"2",
",",
"1",
",",
"3",
",",
"4",
",",
"6",
",",
"5",
",",
"7",
")",
")",
",",
"final_shape",
")",
"return",
"data"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_transform_from_pauli
|
Change of basis of bipartite matrix represenation.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _transform_from_pauli(data, num_qubits):
"""Change of basis of bipartite matrix represenation."""
# Change basis: sum_{i=0}^3 =|\sigma_i>><i|
basis_mat = np.array(
[[1, 0, 0, 1], [0, 1, 1j, 0], [0, 1, -1j, 0], [1, 0j, 0, -1]],
dtype=complex)
# Note that we manually renormalized after change of basis
# to avoid rounding errors from square-roots of 2.
cob = basis_mat
for _ in range(num_qubits - 1):
dim = int(np.sqrt(len(cob)))
cob = np.reshape(
np.transpose(
np.reshape(
np.kron(basis_mat, cob), (2, 2, dim, dim, 4, dim * dim)),
(0, 2, 1, 3, 4, 5)), (4 * dim * dim, 4 * dim * dim))
return np.dot(np.dot(cob, data), cob.conj().T) / 2**num_qubits
|
def _transform_from_pauli(data, num_qubits):
"""Change of basis of bipartite matrix represenation."""
# Change basis: sum_{i=0}^3 =|\sigma_i>><i|
basis_mat = np.array(
[[1, 0, 0, 1], [0, 1, 1j, 0], [0, 1, -1j, 0], [1, 0j, 0, -1]],
dtype=complex)
# Note that we manually renormalized after change of basis
# to avoid rounding errors from square-roots of 2.
cob = basis_mat
for _ in range(num_qubits - 1):
dim = int(np.sqrt(len(cob)))
cob = np.reshape(
np.transpose(
np.reshape(
np.kron(basis_mat, cob), (2, 2, dim, dim, 4, dim * dim)),
(0, 2, 1, 3, 4, 5)), (4 * dim * dim, 4 * dim * dim))
return np.dot(np.dot(cob, data), cob.conj().T) / 2**num_qubits
|
[
"Change",
"of",
"basis",
"of",
"bipartite",
"matrix",
"represenation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L400-L416
|
[
"def",
"_transform_from_pauli",
"(",
"data",
",",
"num_qubits",
")",
":",
"# Change basis: sum_{i=0}^3 =|\\sigma_i>><i|",
"basis_mat",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"1",
",",
"0",
",",
"0",
",",
"1",
"]",
",",
"[",
"0",
",",
"1",
",",
"1j",
",",
"0",
"]",
",",
"[",
"0",
",",
"1",
",",
"-",
"1j",
",",
"0",
"]",
",",
"[",
"1",
",",
"0j",
",",
"0",
",",
"-",
"1",
"]",
"]",
",",
"dtype",
"=",
"complex",
")",
"# Note that we manually renormalized after change of basis",
"# to avoid rounding errors from square-roots of 2.",
"cob",
"=",
"basis_mat",
"for",
"_",
"in",
"range",
"(",
"num_qubits",
"-",
"1",
")",
":",
"dim",
"=",
"int",
"(",
"np",
".",
"sqrt",
"(",
"len",
"(",
"cob",
")",
")",
")",
"cob",
"=",
"np",
".",
"reshape",
"(",
"np",
".",
"transpose",
"(",
"np",
".",
"reshape",
"(",
"np",
".",
"kron",
"(",
"basis_mat",
",",
"cob",
")",
",",
"(",
"2",
",",
"2",
",",
"dim",
",",
"dim",
",",
"4",
",",
"dim",
"*",
"dim",
")",
")",
",",
"(",
"0",
",",
"2",
",",
"1",
",",
"3",
",",
"4",
",",
"5",
")",
")",
",",
"(",
"4",
"*",
"dim",
"*",
"dim",
",",
"4",
"*",
"dim",
"*",
"dim",
")",
")",
"return",
"np",
".",
"dot",
"(",
"np",
".",
"dot",
"(",
"cob",
",",
"data",
")",
",",
"cob",
".",
"conj",
"(",
")",
".",
"T",
")",
"/",
"2",
"**",
"num_qubits"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_reshuffle
|
Reshuffle the indicies of a bipartite matrix A[ij,kl] -> A[lj,ki].
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _reshuffle(mat, shape):
"""Reshuffle the indicies of a bipartite matrix A[ij,kl] -> A[lj,ki]."""
return np.reshape(
np.transpose(np.reshape(mat, shape), (3, 1, 2, 0)),
(shape[3] * shape[1], shape[0] * shape[2]))
|
def _reshuffle(mat, shape):
"""Reshuffle the indicies of a bipartite matrix A[ij,kl] -> A[lj,ki]."""
return np.reshape(
np.transpose(np.reshape(mat, shape), (3, 1, 2, 0)),
(shape[3] * shape[1], shape[0] * shape[2]))
|
[
"Reshuffle",
"the",
"indicies",
"of",
"a",
"bipartite",
"matrix",
"A",
"[",
"ij",
"kl",
"]",
"-",
">",
"A",
"[",
"lj",
"ki",
"]",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L419-L423
|
[
"def",
"_reshuffle",
"(",
"mat",
",",
"shape",
")",
":",
"return",
"np",
".",
"reshape",
"(",
"np",
".",
"transpose",
"(",
"np",
".",
"reshape",
"(",
"mat",
",",
"shape",
")",
",",
"(",
"3",
",",
"1",
",",
"2",
",",
"0",
")",
")",
",",
"(",
"shape",
"[",
"3",
"]",
"*",
"shape",
"[",
"1",
"]",
",",
"shape",
"[",
"0",
"]",
"*",
"shape",
"[",
"2",
"]",
")",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_check_nqubit_dim
|
Return true if dims correspond to an n-qubit channel.
|
qiskit/quantum_info/operators/channel/transformations.py
|
def _check_nqubit_dim(input_dim, output_dim):
"""Return true if dims correspond to an n-qubit channel."""
if input_dim != output_dim:
raise QiskitError(
'Not an n-qubit channel: input_dim' +
' ({}) != output_dim ({})'.format(input_dim, output_dim))
num_qubits = int(np.log2(input_dim))
if 2**num_qubits != input_dim:
raise QiskitError('Not an n-qubit channel: input_dim != 2 ** n')
|
def _check_nqubit_dim(input_dim, output_dim):
"""Return true if dims correspond to an n-qubit channel."""
if input_dim != output_dim:
raise QiskitError(
'Not an n-qubit channel: input_dim' +
' ({}) != output_dim ({})'.format(input_dim, output_dim))
num_qubits = int(np.log2(input_dim))
if 2**num_qubits != input_dim:
raise QiskitError('Not an n-qubit channel: input_dim != 2 ** n')
|
[
"Return",
"true",
"if",
"dims",
"correspond",
"to",
"an",
"n",
"-",
"qubit",
"channel",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L426-L434
|
[
"def",
"_check_nqubit_dim",
"(",
"input_dim",
",",
"output_dim",
")",
":",
"if",
"input_dim",
"!=",
"output_dim",
":",
"raise",
"QiskitError",
"(",
"'Not an n-qubit channel: input_dim'",
"+",
"' ({}) != output_dim ({})'",
".",
"format",
"(",
"input_dim",
",",
"output_dim",
")",
")",
"num_qubits",
"=",
"int",
"(",
"np",
".",
"log2",
"(",
"input_dim",
")",
")",
"if",
"2",
"**",
"num_qubits",
"!=",
"input_dim",
":",
"raise",
"QiskitError",
"(",
"'Not an n-qubit channel: input_dim != 2 ** n'",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_hide_tick_lines_and_labels
|
Set visible property of ticklines and ticklabels of an axis to False
|
qiskit/visualization/bloch.py
|
def _hide_tick_lines_and_labels(axis):
"""
Set visible property of ticklines and ticklabels of an axis to False
"""
for item in axis.get_ticklines() + axis.get_ticklabels():
item.set_visible(False)
|
def _hide_tick_lines_and_labels(axis):
"""
Set visible property of ticklines and ticklabels of an axis to False
"""
for item in axis.get_ticklines() + axis.get_ticklabels():
item.set_visible(False)
|
[
"Set",
"visible",
"property",
"of",
"ticklines",
"and",
"ticklabels",
"of",
"an",
"axis",
"to",
"False"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/bloch.py#L625-L630
|
[
"def",
"_hide_tick_lines_and_labels",
"(",
"axis",
")",
":",
"for",
"item",
"in",
"axis",
".",
"get_ticklines",
"(",
")",
"+",
"axis",
".",
"get_ticklabels",
"(",
")",
":",
"item",
".",
"set_visible",
"(",
"False",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Bloch.set_label_convention
|
Set x, y and z labels according to one of conventions.
Args:
convention (str):
One of the following:
- "original"
- "xyz"
- "sx sy sz"
- "01"
- "polarization jones"
- "polarization jones letters"
see also: http://en.wikipedia.org/wiki/Jones_calculus
- "polarization stokes"
see also: http://en.wikipedia.org/wiki/Stokes_parameters
Raises:
Exception: If convention is not valid.
|
qiskit/visualization/bloch.py
|
def set_label_convention(self, convention):
"""Set x, y and z labels according to one of conventions.
Args:
convention (str):
One of the following:
- "original"
- "xyz"
- "sx sy sz"
- "01"
- "polarization jones"
- "polarization jones letters"
see also: http://en.wikipedia.org/wiki/Jones_calculus
- "polarization stokes"
see also: http://en.wikipedia.org/wiki/Stokes_parameters
Raises:
Exception: If convention is not valid.
"""
ketex = "$\\left.|%s\\right\\rangle$"
# \left.| is on purpose, so that every ket has the same size
if convention == "original":
self.xlabel = ['$x$', '']
self.ylabel = ['$y$', '']
self.zlabel = ['$\\left|0\\right>$', '$\\left|1\\right>$']
elif convention == "xyz":
self.xlabel = ['$x$', '']
self.ylabel = ['$y$', '']
self.zlabel = ['$z$', '']
elif convention == "sx sy sz":
self.xlabel = ['$s_x$', '']
self.ylabel = ['$s_y$', '']
self.zlabel = ['$s_z$', '']
elif convention == "01":
self.xlabel = ['', '']
self.ylabel = ['', '']
self.zlabel = ['$\\left|0\\right>$', '$\\left|1\\right>$']
elif convention == "polarization jones":
self.xlabel = [ketex % "\\nearrow\\hspace{-1.46}\\swarrow",
ketex % "\\nwarrow\\hspace{-1.46}\\searrow"]
self.ylabel = [ketex % "\\circlearrowleft", ketex %
"\\circlearrowright"]
self.zlabel = [ketex % "\\leftrightarrow", ketex % "\\updownarrow"]
elif convention == "polarization jones letters":
self.xlabel = [ketex % "D", ketex % "A"]
self.ylabel = [ketex % "L", ketex % "R"]
self.zlabel = [ketex % "H", ketex % "V"]
elif convention == "polarization stokes":
self.ylabel = ["$\\nearrow\\hspace{-1.46}\\swarrow$",
"$\\nwarrow\\hspace{-1.46}\\searrow$"]
self.zlabel = ["$\\circlearrowleft$", "$\\circlearrowright$"]
self.xlabel = ["$\\leftrightarrow$", "$\\updownarrow$"]
else:
raise Exception("No such convention.")
|
def set_label_convention(self, convention):
"""Set x, y and z labels according to one of conventions.
Args:
convention (str):
One of the following:
- "original"
- "xyz"
- "sx sy sz"
- "01"
- "polarization jones"
- "polarization jones letters"
see also: http://en.wikipedia.org/wiki/Jones_calculus
- "polarization stokes"
see also: http://en.wikipedia.org/wiki/Stokes_parameters
Raises:
Exception: If convention is not valid.
"""
ketex = "$\\left.|%s\\right\\rangle$"
# \left.| is on purpose, so that every ket has the same size
if convention == "original":
self.xlabel = ['$x$', '']
self.ylabel = ['$y$', '']
self.zlabel = ['$\\left|0\\right>$', '$\\left|1\\right>$']
elif convention == "xyz":
self.xlabel = ['$x$', '']
self.ylabel = ['$y$', '']
self.zlabel = ['$z$', '']
elif convention == "sx sy sz":
self.xlabel = ['$s_x$', '']
self.ylabel = ['$s_y$', '']
self.zlabel = ['$s_z$', '']
elif convention == "01":
self.xlabel = ['', '']
self.ylabel = ['', '']
self.zlabel = ['$\\left|0\\right>$', '$\\left|1\\right>$']
elif convention == "polarization jones":
self.xlabel = [ketex % "\\nearrow\\hspace{-1.46}\\swarrow",
ketex % "\\nwarrow\\hspace{-1.46}\\searrow"]
self.ylabel = [ketex % "\\circlearrowleft", ketex %
"\\circlearrowright"]
self.zlabel = [ketex % "\\leftrightarrow", ketex % "\\updownarrow"]
elif convention == "polarization jones letters":
self.xlabel = [ketex % "D", ketex % "A"]
self.ylabel = [ketex % "L", ketex % "R"]
self.zlabel = [ketex % "H", ketex % "V"]
elif convention == "polarization stokes":
self.ylabel = ["$\\nearrow\\hspace{-1.46}\\swarrow$",
"$\\nwarrow\\hspace{-1.46}\\searrow$"]
self.zlabel = ["$\\circlearrowleft$", "$\\circlearrowright$"]
self.xlabel = ["$\\leftrightarrow$", "$\\updownarrow$"]
else:
raise Exception("No such convention.")
|
[
"Set",
"x",
"y",
"and",
"z",
"labels",
"according",
"to",
"one",
"of",
"conventions",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/bloch.py#L207-L260
|
[
"def",
"set_label_convention",
"(",
"self",
",",
"convention",
")",
":",
"ketex",
"=",
"\"$\\\\left.|%s\\\\right\\\\rangle$\"",
"# \\left.| is on purpose, so that every ket has the same size",
"if",
"convention",
"==",
"\"original\"",
":",
"self",
".",
"xlabel",
"=",
"[",
"'$x$'",
",",
"''",
"]",
"self",
".",
"ylabel",
"=",
"[",
"'$y$'",
",",
"''",
"]",
"self",
".",
"zlabel",
"=",
"[",
"'$\\\\left|0\\\\right>$'",
",",
"'$\\\\left|1\\\\right>$'",
"]",
"elif",
"convention",
"==",
"\"xyz\"",
":",
"self",
".",
"xlabel",
"=",
"[",
"'$x$'",
",",
"''",
"]",
"self",
".",
"ylabel",
"=",
"[",
"'$y$'",
",",
"''",
"]",
"self",
".",
"zlabel",
"=",
"[",
"'$z$'",
",",
"''",
"]",
"elif",
"convention",
"==",
"\"sx sy sz\"",
":",
"self",
".",
"xlabel",
"=",
"[",
"'$s_x$'",
",",
"''",
"]",
"self",
".",
"ylabel",
"=",
"[",
"'$s_y$'",
",",
"''",
"]",
"self",
".",
"zlabel",
"=",
"[",
"'$s_z$'",
",",
"''",
"]",
"elif",
"convention",
"==",
"\"01\"",
":",
"self",
".",
"xlabel",
"=",
"[",
"''",
",",
"''",
"]",
"self",
".",
"ylabel",
"=",
"[",
"''",
",",
"''",
"]",
"self",
".",
"zlabel",
"=",
"[",
"'$\\\\left|0\\\\right>$'",
",",
"'$\\\\left|1\\\\right>$'",
"]",
"elif",
"convention",
"==",
"\"polarization jones\"",
":",
"self",
".",
"xlabel",
"=",
"[",
"ketex",
"%",
"\"\\\\nearrow\\\\hspace{-1.46}\\\\swarrow\"",
",",
"ketex",
"%",
"\"\\\\nwarrow\\\\hspace{-1.46}\\\\searrow\"",
"]",
"self",
".",
"ylabel",
"=",
"[",
"ketex",
"%",
"\"\\\\circlearrowleft\"",
",",
"ketex",
"%",
"\"\\\\circlearrowright\"",
"]",
"self",
".",
"zlabel",
"=",
"[",
"ketex",
"%",
"\"\\\\leftrightarrow\"",
",",
"ketex",
"%",
"\"\\\\updownarrow\"",
"]",
"elif",
"convention",
"==",
"\"polarization jones letters\"",
":",
"self",
".",
"xlabel",
"=",
"[",
"ketex",
"%",
"\"D\"",
",",
"ketex",
"%",
"\"A\"",
"]",
"self",
".",
"ylabel",
"=",
"[",
"ketex",
"%",
"\"L\"",
",",
"ketex",
"%",
"\"R\"",
"]",
"self",
".",
"zlabel",
"=",
"[",
"ketex",
"%",
"\"H\"",
",",
"ketex",
"%",
"\"V\"",
"]",
"elif",
"convention",
"==",
"\"polarization stokes\"",
":",
"self",
".",
"ylabel",
"=",
"[",
"\"$\\\\nearrow\\\\hspace{-1.46}\\\\swarrow$\"",
",",
"\"$\\\\nwarrow\\\\hspace{-1.46}\\\\searrow$\"",
"]",
"self",
".",
"zlabel",
"=",
"[",
"\"$\\\\circlearrowleft$\"",
",",
"\"$\\\\circlearrowright$\"",
"]",
"self",
".",
"xlabel",
"=",
"[",
"\"$\\\\leftrightarrow$\"",
",",
"\"$\\\\updownarrow$\"",
"]",
"else",
":",
"raise",
"Exception",
"(",
"\"No such convention.\"",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Bloch.clear
|
Resets Bloch sphere data sets to empty.
|
qiskit/visualization/bloch.py
|
def clear(self):
"""Resets Bloch sphere data sets to empty.
"""
self.points = []
self.vectors = []
self.point_style = []
self.annotations = []
|
def clear(self):
"""Resets Bloch sphere data sets to empty.
"""
self.points = []
self.vectors = []
self.point_style = []
self.annotations = []
|
[
"Resets",
"Bloch",
"sphere",
"data",
"sets",
"to",
"empty",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/bloch.py#L295-L301
|
[
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"points",
"=",
"[",
"]",
"self",
".",
"vectors",
"=",
"[",
"]",
"self",
".",
"point_style",
"=",
"[",
"]",
"self",
".",
"annotations",
"=",
"[",
"]"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Bloch.add_points
|
Add a list of data points to bloch sphere.
Args:
points (array_like):
Collection of data points.
meth (str):
Type of points to plot, use 'm' for multicolored, 'l' for points
connected with a line.
|
qiskit/visualization/bloch.py
|
def add_points(self, points, meth='s'):
"""Add a list of data points to bloch sphere.
Args:
points (array_like):
Collection of data points.
meth (str):
Type of points to plot, use 'm' for multicolored, 'l' for points
connected with a line.
"""
if not isinstance(points[0], (list, np.ndarray)):
points = [[points[0]], [points[1]], [points[2]]]
points = np.array(points)
if meth == 's':
if len(points[0]) == 1:
pnts = np.array([[points[0][0]],
[points[1][0]], [points[2][0]]])
pnts = np.append(pnts, points, axis=1)
else:
pnts = points
self.points.append(pnts)
self.point_style.append('s')
elif meth == 'l':
self.points.append(points)
self.point_style.append('l')
else:
self.points.append(points)
self.point_style.append('m')
|
def add_points(self, points, meth='s'):
"""Add a list of data points to bloch sphere.
Args:
points (array_like):
Collection of data points.
meth (str):
Type of points to plot, use 'm' for multicolored, 'l' for points
connected with a line.
"""
if not isinstance(points[0], (list, np.ndarray)):
points = [[points[0]], [points[1]], [points[2]]]
points = np.array(points)
if meth == 's':
if len(points[0]) == 1:
pnts = np.array([[points[0][0]],
[points[1][0]], [points[2][0]]])
pnts = np.append(pnts, points, axis=1)
else:
pnts = points
self.points.append(pnts)
self.point_style.append('s')
elif meth == 'l':
self.points.append(points)
self.point_style.append('l')
else:
self.points.append(points)
self.point_style.append('m')
|
[
"Add",
"a",
"list",
"of",
"data",
"points",
"to",
"bloch",
"sphere",
".",
"Args",
":",
"points",
"(",
"array_like",
")",
":",
"Collection",
"of",
"data",
"points",
".",
"meth",
"(",
"str",
")",
":",
"Type",
"of",
"points",
"to",
"plot",
"use",
"m",
"for",
"multicolored",
"l",
"for",
"points",
"connected",
"with",
"a",
"line",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/bloch.py#L303-L329
|
[
"def",
"add_points",
"(",
"self",
",",
"points",
",",
"meth",
"=",
"'s'",
")",
":",
"if",
"not",
"isinstance",
"(",
"points",
"[",
"0",
"]",
",",
"(",
"list",
",",
"np",
".",
"ndarray",
")",
")",
":",
"points",
"=",
"[",
"[",
"points",
"[",
"0",
"]",
"]",
",",
"[",
"points",
"[",
"1",
"]",
"]",
",",
"[",
"points",
"[",
"2",
"]",
"]",
"]",
"points",
"=",
"np",
".",
"array",
"(",
"points",
")",
"if",
"meth",
"==",
"'s'",
":",
"if",
"len",
"(",
"points",
"[",
"0",
"]",
")",
"==",
"1",
":",
"pnts",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"points",
"[",
"0",
"]",
"[",
"0",
"]",
"]",
",",
"[",
"points",
"[",
"1",
"]",
"[",
"0",
"]",
"]",
",",
"[",
"points",
"[",
"2",
"]",
"[",
"0",
"]",
"]",
"]",
")",
"pnts",
"=",
"np",
".",
"append",
"(",
"pnts",
",",
"points",
",",
"axis",
"=",
"1",
")",
"else",
":",
"pnts",
"=",
"points",
"self",
".",
"points",
".",
"append",
"(",
"pnts",
")",
"self",
".",
"point_style",
".",
"append",
"(",
"'s'",
")",
"elif",
"meth",
"==",
"'l'",
":",
"self",
".",
"points",
".",
"append",
"(",
"points",
")",
"self",
".",
"point_style",
".",
"append",
"(",
"'l'",
")",
"else",
":",
"self",
".",
"points",
".",
"append",
"(",
"points",
")",
"self",
".",
"point_style",
".",
"append",
"(",
"'m'",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Bloch.add_vectors
|
Add a list of vectors to Bloch sphere.
Args:
vectors (array_like):
Array with vectors of unit length or smaller.
|
qiskit/visualization/bloch.py
|
def add_vectors(self, vectors):
"""Add a list of vectors to Bloch sphere.
Args:
vectors (array_like):
Array with vectors of unit length or smaller.
"""
if isinstance(vectors[0], (list, np.ndarray)):
for vec in vectors:
self.vectors.append(vec)
else:
self.vectors.append(vectors)
|
def add_vectors(self, vectors):
"""Add a list of vectors to Bloch sphere.
Args:
vectors (array_like):
Array with vectors of unit length or smaller.
"""
if isinstance(vectors[0], (list, np.ndarray)):
for vec in vectors:
self.vectors.append(vec)
else:
self.vectors.append(vectors)
|
[
"Add",
"a",
"list",
"of",
"vectors",
"to",
"Bloch",
"sphere",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/bloch.py#L331-L342
|
[
"def",
"add_vectors",
"(",
"self",
",",
"vectors",
")",
":",
"if",
"isinstance",
"(",
"vectors",
"[",
"0",
"]",
",",
"(",
"list",
",",
"np",
".",
"ndarray",
")",
")",
":",
"for",
"vec",
"in",
"vectors",
":",
"self",
".",
"vectors",
".",
"append",
"(",
"vec",
")",
"else",
":",
"self",
".",
"vectors",
".",
"append",
"(",
"vectors",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Bloch.add_annotation
|
Add a text or LaTeX annotation to Bloch sphere,
parametrized by a qubit state or a vector.
Args:
state_or_vector (array_like):
Position for the annotation.
Qobj of a qubit or a vector of 3 elements.
text (str):
Annotation text.
You can use LaTeX, but remember to use raw string
e.g. r"$\\langle x \\rangle$"
or escape backslashes
e.g. "$\\\\langle x \\\\rangle$".
**kwargs:
Options as for mplot3d.axes3d.text, including:
fontsize, color, horizontalalignment, verticalalignment.
Raises:
Exception: If input not array_like or tuple.
|
qiskit/visualization/bloch.py
|
def add_annotation(self, state_or_vector, text, **kwargs):
"""Add a text or LaTeX annotation to Bloch sphere,
parametrized by a qubit state or a vector.
Args:
state_or_vector (array_like):
Position for the annotation.
Qobj of a qubit or a vector of 3 elements.
text (str):
Annotation text.
You can use LaTeX, but remember to use raw string
e.g. r"$\\langle x \\rangle$"
or escape backslashes
e.g. "$\\\\langle x \\\\rangle$".
**kwargs:
Options as for mplot3d.axes3d.text, including:
fontsize, color, horizontalalignment, verticalalignment.
Raises:
Exception: If input not array_like or tuple.
"""
if isinstance(state_or_vector, (list, np.ndarray, tuple)) \
and len(state_or_vector) == 3:
vec = state_or_vector
else:
raise Exception("Position needs to be specified by a qubit " +
"state or a 3D vector.")
self.annotations.append({'position': vec,
'text': text,
'opts': kwargs})
|
def add_annotation(self, state_or_vector, text, **kwargs):
"""Add a text or LaTeX annotation to Bloch sphere,
parametrized by a qubit state or a vector.
Args:
state_or_vector (array_like):
Position for the annotation.
Qobj of a qubit or a vector of 3 elements.
text (str):
Annotation text.
You can use LaTeX, but remember to use raw string
e.g. r"$\\langle x \\rangle$"
or escape backslashes
e.g. "$\\\\langle x \\\\rangle$".
**kwargs:
Options as for mplot3d.axes3d.text, including:
fontsize, color, horizontalalignment, verticalalignment.
Raises:
Exception: If input not array_like or tuple.
"""
if isinstance(state_or_vector, (list, np.ndarray, tuple)) \
and len(state_or_vector) == 3:
vec = state_or_vector
else:
raise Exception("Position needs to be specified by a qubit " +
"state or a 3D vector.")
self.annotations.append({'position': vec,
'text': text,
'opts': kwargs})
|
[
"Add",
"a",
"text",
"or",
"LaTeX",
"annotation",
"to",
"Bloch",
"sphere",
"parametrized",
"by",
"a",
"qubit",
"state",
"or",
"a",
"vector",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/bloch.py#L344-L372
|
[
"def",
"add_annotation",
"(",
"self",
",",
"state_or_vector",
",",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"state_or_vector",
",",
"(",
"list",
",",
"np",
".",
"ndarray",
",",
"tuple",
")",
")",
"and",
"len",
"(",
"state_or_vector",
")",
"==",
"3",
":",
"vec",
"=",
"state_or_vector",
"else",
":",
"raise",
"Exception",
"(",
"\"Position needs to be specified by a qubit \"",
"+",
"\"state or a 3D vector.\"",
")",
"self",
".",
"annotations",
".",
"append",
"(",
"{",
"'position'",
":",
"vec",
",",
"'text'",
":",
"text",
",",
"'opts'",
":",
"kwargs",
"}",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Bloch.render
|
Render the Bloch sphere and its data sets in on given figure and axes.
|
qiskit/visualization/bloch.py
|
def render(self, title=''):
"""
Render the Bloch sphere and its data sets in on given figure and axes.
"""
if self._rendered:
self.axes.clear()
self._rendered = True
# Figure instance for Bloch sphere plot
if not self._ext_fig:
self.fig = plt.figure(figsize=self.figsize)
if not self._ext_axes:
self.axes = Axes3D(self.fig, azim=self.view[0], elev=self.view[1])
if self.background:
self.axes.clear()
self.axes.set_xlim3d(-1.3, 1.3)
self.axes.set_ylim3d(-1.3, 1.3)
self.axes.set_zlim3d(-1.3, 1.3)
else:
self.plot_axes()
self.axes.set_axis_off()
self.axes.set_xlim3d(-0.7, 0.7)
self.axes.set_ylim3d(-0.7, 0.7)
self.axes.set_zlim3d(-0.7, 0.7)
self.axes.grid(False)
self.plot_back()
self.plot_points()
self.plot_vectors()
self.plot_front()
self.plot_axes_labels()
self.plot_annotations()
self.axes.set_title(title, fontsize=self.font_size, y=1.08)
|
def render(self, title=''):
"""
Render the Bloch sphere and its data sets in on given figure and axes.
"""
if self._rendered:
self.axes.clear()
self._rendered = True
# Figure instance for Bloch sphere plot
if not self._ext_fig:
self.fig = plt.figure(figsize=self.figsize)
if not self._ext_axes:
self.axes = Axes3D(self.fig, azim=self.view[0], elev=self.view[1])
if self.background:
self.axes.clear()
self.axes.set_xlim3d(-1.3, 1.3)
self.axes.set_ylim3d(-1.3, 1.3)
self.axes.set_zlim3d(-1.3, 1.3)
else:
self.plot_axes()
self.axes.set_axis_off()
self.axes.set_xlim3d(-0.7, 0.7)
self.axes.set_ylim3d(-0.7, 0.7)
self.axes.set_zlim3d(-0.7, 0.7)
self.axes.grid(False)
self.plot_back()
self.plot_points()
self.plot_vectors()
self.plot_front()
self.plot_axes_labels()
self.plot_annotations()
self.axes.set_title(title, fontsize=self.font_size, y=1.08)
|
[
"Render",
"the",
"Bloch",
"sphere",
"and",
"its",
"data",
"sets",
"in",
"on",
"given",
"figure",
"and",
"axes",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/bloch.py#L380-L415
|
[
"def",
"render",
"(",
"self",
",",
"title",
"=",
"''",
")",
":",
"if",
"self",
".",
"_rendered",
":",
"self",
".",
"axes",
".",
"clear",
"(",
")",
"self",
".",
"_rendered",
"=",
"True",
"# Figure instance for Bloch sphere plot",
"if",
"not",
"self",
".",
"_ext_fig",
":",
"self",
".",
"fig",
"=",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"self",
".",
"figsize",
")",
"if",
"not",
"self",
".",
"_ext_axes",
":",
"self",
".",
"axes",
"=",
"Axes3D",
"(",
"self",
".",
"fig",
",",
"azim",
"=",
"self",
".",
"view",
"[",
"0",
"]",
",",
"elev",
"=",
"self",
".",
"view",
"[",
"1",
"]",
")",
"if",
"self",
".",
"background",
":",
"self",
".",
"axes",
".",
"clear",
"(",
")",
"self",
".",
"axes",
".",
"set_xlim3d",
"(",
"-",
"1.3",
",",
"1.3",
")",
"self",
".",
"axes",
".",
"set_ylim3d",
"(",
"-",
"1.3",
",",
"1.3",
")",
"self",
".",
"axes",
".",
"set_zlim3d",
"(",
"-",
"1.3",
",",
"1.3",
")",
"else",
":",
"self",
".",
"plot_axes",
"(",
")",
"self",
".",
"axes",
".",
"set_axis_off",
"(",
")",
"self",
".",
"axes",
".",
"set_xlim3d",
"(",
"-",
"0.7",
",",
"0.7",
")",
"self",
".",
"axes",
".",
"set_ylim3d",
"(",
"-",
"0.7",
",",
"0.7",
")",
"self",
".",
"axes",
".",
"set_zlim3d",
"(",
"-",
"0.7",
",",
"0.7",
")",
"self",
".",
"axes",
".",
"grid",
"(",
"False",
")",
"self",
".",
"plot_back",
"(",
")",
"self",
".",
"plot_points",
"(",
")",
"self",
".",
"plot_vectors",
"(",
")",
"self",
".",
"plot_front",
"(",
")",
"self",
".",
"plot_axes_labels",
"(",
")",
"self",
".",
"plot_annotations",
"(",
")",
"self",
".",
"axes",
".",
"set_title",
"(",
"title",
",",
"fontsize",
"=",
"self",
".",
"font_size",
",",
"y",
"=",
"1.08",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Bloch.plot_front
|
front half of sphere
|
qiskit/visualization/bloch.py
|
def plot_front(self):
"""front half of sphere"""
u_angle = np.linspace(-np.pi, 0, 25)
v_angle = np.linspace(0, np.pi, 25)
x_dir = np.outer(np.cos(u_angle), np.sin(v_angle))
y_dir = np.outer(np.sin(u_angle), np.sin(v_angle))
z_dir = np.outer(np.ones(u_angle.shape[0]), np.cos(v_angle))
self.axes.plot_surface(x_dir, y_dir, z_dir, rstride=2, cstride=2,
color=self.sphere_color, linewidth=0,
alpha=self.sphere_alpha)
# wireframe
self.axes.plot_wireframe(x_dir, y_dir, z_dir, rstride=5, cstride=5,
color=self.frame_color,
alpha=self.frame_alpha)
# equator
self.axes.plot(1.0 * np.cos(u_angle), 1.0 * np.sin(u_angle),
zs=0, zdir='z', lw=self.frame_width,
color=self.frame_color)
self.axes.plot(1.0 * np.cos(u_angle), 1.0 * np.sin(u_angle),
zs=0, zdir='x', lw=self.frame_width,
color=self.frame_color)
|
def plot_front(self):
"""front half of sphere"""
u_angle = np.linspace(-np.pi, 0, 25)
v_angle = np.linspace(0, np.pi, 25)
x_dir = np.outer(np.cos(u_angle), np.sin(v_angle))
y_dir = np.outer(np.sin(u_angle), np.sin(v_angle))
z_dir = np.outer(np.ones(u_angle.shape[0]), np.cos(v_angle))
self.axes.plot_surface(x_dir, y_dir, z_dir, rstride=2, cstride=2,
color=self.sphere_color, linewidth=0,
alpha=self.sphere_alpha)
# wireframe
self.axes.plot_wireframe(x_dir, y_dir, z_dir, rstride=5, cstride=5,
color=self.frame_color,
alpha=self.frame_alpha)
# equator
self.axes.plot(1.0 * np.cos(u_angle), 1.0 * np.sin(u_angle),
zs=0, zdir='z', lw=self.frame_width,
color=self.frame_color)
self.axes.plot(1.0 * np.cos(u_angle), 1.0 * np.sin(u_angle),
zs=0, zdir='x', lw=self.frame_width,
color=self.frame_color)
|
[
"front",
"half",
"of",
"sphere"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/bloch.py#L437-L457
|
[
"def",
"plot_front",
"(",
"self",
")",
":",
"u_angle",
"=",
"np",
".",
"linspace",
"(",
"-",
"np",
".",
"pi",
",",
"0",
",",
"25",
")",
"v_angle",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"np",
".",
"pi",
",",
"25",
")",
"x_dir",
"=",
"np",
".",
"outer",
"(",
"np",
".",
"cos",
"(",
"u_angle",
")",
",",
"np",
".",
"sin",
"(",
"v_angle",
")",
")",
"y_dir",
"=",
"np",
".",
"outer",
"(",
"np",
".",
"sin",
"(",
"u_angle",
")",
",",
"np",
".",
"sin",
"(",
"v_angle",
")",
")",
"z_dir",
"=",
"np",
".",
"outer",
"(",
"np",
".",
"ones",
"(",
"u_angle",
".",
"shape",
"[",
"0",
"]",
")",
",",
"np",
".",
"cos",
"(",
"v_angle",
")",
")",
"self",
".",
"axes",
".",
"plot_surface",
"(",
"x_dir",
",",
"y_dir",
",",
"z_dir",
",",
"rstride",
"=",
"2",
",",
"cstride",
"=",
"2",
",",
"color",
"=",
"self",
".",
"sphere_color",
",",
"linewidth",
"=",
"0",
",",
"alpha",
"=",
"self",
".",
"sphere_alpha",
")",
"# wireframe",
"self",
".",
"axes",
".",
"plot_wireframe",
"(",
"x_dir",
",",
"y_dir",
",",
"z_dir",
",",
"rstride",
"=",
"5",
",",
"cstride",
"=",
"5",
",",
"color",
"=",
"self",
".",
"frame_color",
",",
"alpha",
"=",
"self",
".",
"frame_alpha",
")",
"# equator",
"self",
".",
"axes",
".",
"plot",
"(",
"1.0",
"*",
"np",
".",
"cos",
"(",
"u_angle",
")",
",",
"1.0",
"*",
"np",
".",
"sin",
"(",
"u_angle",
")",
",",
"zs",
"=",
"0",
",",
"zdir",
"=",
"'z'",
",",
"lw",
"=",
"self",
".",
"frame_width",
",",
"color",
"=",
"self",
".",
"frame_color",
")",
"self",
".",
"axes",
".",
"plot",
"(",
"1.0",
"*",
"np",
".",
"cos",
"(",
"u_angle",
")",
",",
"1.0",
"*",
"np",
".",
"sin",
"(",
"u_angle",
")",
",",
"zs",
"=",
"0",
",",
"zdir",
"=",
"'x'",
",",
"lw",
"=",
"self",
".",
"frame_width",
",",
"color",
"=",
"self",
".",
"frame_color",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Bloch.plot_axes
|
axes
|
qiskit/visualization/bloch.py
|
def plot_axes(self):
"""axes"""
span = np.linspace(-1.0, 1.0, 2)
self.axes.plot(span, 0 * span, zs=0, zdir='z', label='X',
lw=self.frame_width, color=self.frame_color)
self.axes.plot(0 * span, span, zs=0, zdir='z', label='Y',
lw=self.frame_width, color=self.frame_color)
self.axes.plot(0 * span, span, zs=0, zdir='y', label='Z',
lw=self.frame_width, color=self.frame_color)
|
def plot_axes(self):
"""axes"""
span = np.linspace(-1.0, 1.0, 2)
self.axes.plot(span, 0 * span, zs=0, zdir='z', label='X',
lw=self.frame_width, color=self.frame_color)
self.axes.plot(0 * span, span, zs=0, zdir='z', label='Y',
lw=self.frame_width, color=self.frame_color)
self.axes.plot(0 * span, span, zs=0, zdir='y', label='Z',
lw=self.frame_width, color=self.frame_color)
|
[
"axes"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/bloch.py#L459-L467
|
[
"def",
"plot_axes",
"(",
"self",
")",
":",
"span",
"=",
"np",
".",
"linspace",
"(",
"-",
"1.0",
",",
"1.0",
",",
"2",
")",
"self",
".",
"axes",
".",
"plot",
"(",
"span",
",",
"0",
"*",
"span",
",",
"zs",
"=",
"0",
",",
"zdir",
"=",
"'z'",
",",
"label",
"=",
"'X'",
",",
"lw",
"=",
"self",
".",
"frame_width",
",",
"color",
"=",
"self",
".",
"frame_color",
")",
"self",
".",
"axes",
".",
"plot",
"(",
"0",
"*",
"span",
",",
"span",
",",
"zs",
"=",
"0",
",",
"zdir",
"=",
"'z'",
",",
"label",
"=",
"'Y'",
",",
"lw",
"=",
"self",
".",
"frame_width",
",",
"color",
"=",
"self",
".",
"frame_color",
")",
"self",
".",
"axes",
".",
"plot",
"(",
"0",
"*",
"span",
",",
"span",
",",
"zs",
"=",
"0",
",",
"zdir",
"=",
"'y'",
",",
"label",
"=",
"'Z'",
",",
"lw",
"=",
"self",
".",
"frame_width",
",",
"color",
"=",
"self",
".",
"frame_color",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Bloch.plot_axes_labels
|
axes labels
|
qiskit/visualization/bloch.py
|
def plot_axes_labels(self):
"""axes labels"""
opts = {'fontsize': self.font_size,
'color': self.font_color,
'horizontalalignment': 'center',
'verticalalignment': 'center'}
self.axes.text(0, -self.xlpos[0], 0, self.xlabel[0], **opts)
self.axes.text(0, -self.xlpos[1], 0, self.xlabel[1], **opts)
self.axes.text(self.ylpos[0], 0, 0, self.ylabel[0], **opts)
self.axes.text(self.ylpos[1], 0, 0, self.ylabel[1], **opts)
self.axes.text(0, 0, self.zlpos[0], self.zlabel[0], **opts)
self.axes.text(0, 0, self.zlpos[1], self.zlabel[1], **opts)
for item in (self.axes.w_xaxis.get_ticklines() +
self.axes.w_xaxis.get_ticklabels()):
item.set_visible(False)
for item in (self.axes.w_yaxis.get_ticklines() +
self.axes.w_yaxis.get_ticklabels()):
item.set_visible(False)
for item in (self.axes.w_zaxis.get_ticklines() +
self.axes.w_zaxis.get_ticklabels()):
item.set_visible(False)
|
def plot_axes_labels(self):
"""axes labels"""
opts = {'fontsize': self.font_size,
'color': self.font_color,
'horizontalalignment': 'center',
'verticalalignment': 'center'}
self.axes.text(0, -self.xlpos[0], 0, self.xlabel[0], **opts)
self.axes.text(0, -self.xlpos[1], 0, self.xlabel[1], **opts)
self.axes.text(self.ylpos[0], 0, 0, self.ylabel[0], **opts)
self.axes.text(self.ylpos[1], 0, 0, self.ylabel[1], **opts)
self.axes.text(0, 0, self.zlpos[0], self.zlabel[0], **opts)
self.axes.text(0, 0, self.zlpos[1], self.zlabel[1], **opts)
for item in (self.axes.w_xaxis.get_ticklines() +
self.axes.w_xaxis.get_ticklabels()):
item.set_visible(False)
for item in (self.axes.w_yaxis.get_ticklines() +
self.axes.w_yaxis.get_ticklabels()):
item.set_visible(False)
for item in (self.axes.w_zaxis.get_ticklines() +
self.axes.w_zaxis.get_ticklabels()):
item.set_visible(False)
|
[
"axes",
"labels"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/bloch.py#L469-L492
|
[
"def",
"plot_axes_labels",
"(",
"self",
")",
":",
"opts",
"=",
"{",
"'fontsize'",
":",
"self",
".",
"font_size",
",",
"'color'",
":",
"self",
".",
"font_color",
",",
"'horizontalalignment'",
":",
"'center'",
",",
"'verticalalignment'",
":",
"'center'",
"}",
"self",
".",
"axes",
".",
"text",
"(",
"0",
",",
"-",
"self",
".",
"xlpos",
"[",
"0",
"]",
",",
"0",
",",
"self",
".",
"xlabel",
"[",
"0",
"]",
",",
"*",
"*",
"opts",
")",
"self",
".",
"axes",
".",
"text",
"(",
"0",
",",
"-",
"self",
".",
"xlpos",
"[",
"1",
"]",
",",
"0",
",",
"self",
".",
"xlabel",
"[",
"1",
"]",
",",
"*",
"*",
"opts",
")",
"self",
".",
"axes",
".",
"text",
"(",
"self",
".",
"ylpos",
"[",
"0",
"]",
",",
"0",
",",
"0",
",",
"self",
".",
"ylabel",
"[",
"0",
"]",
",",
"*",
"*",
"opts",
")",
"self",
".",
"axes",
".",
"text",
"(",
"self",
".",
"ylpos",
"[",
"1",
"]",
",",
"0",
",",
"0",
",",
"self",
".",
"ylabel",
"[",
"1",
"]",
",",
"*",
"*",
"opts",
")",
"self",
".",
"axes",
".",
"text",
"(",
"0",
",",
"0",
",",
"self",
".",
"zlpos",
"[",
"0",
"]",
",",
"self",
".",
"zlabel",
"[",
"0",
"]",
",",
"*",
"*",
"opts",
")",
"self",
".",
"axes",
".",
"text",
"(",
"0",
",",
"0",
",",
"self",
".",
"zlpos",
"[",
"1",
"]",
",",
"self",
".",
"zlabel",
"[",
"1",
"]",
",",
"*",
"*",
"opts",
")",
"for",
"item",
"in",
"(",
"self",
".",
"axes",
".",
"w_xaxis",
".",
"get_ticklines",
"(",
")",
"+",
"self",
".",
"axes",
".",
"w_xaxis",
".",
"get_ticklabels",
"(",
")",
")",
":",
"item",
".",
"set_visible",
"(",
"False",
")",
"for",
"item",
"in",
"(",
"self",
".",
"axes",
".",
"w_yaxis",
".",
"get_ticklines",
"(",
")",
"+",
"self",
".",
"axes",
".",
"w_yaxis",
".",
"get_ticklabels",
"(",
")",
")",
":",
"item",
".",
"set_visible",
"(",
"False",
")",
"for",
"item",
"in",
"(",
"self",
".",
"axes",
".",
"w_zaxis",
".",
"get_ticklines",
"(",
")",
"+",
"self",
".",
"axes",
".",
"w_zaxis",
".",
"get_ticklabels",
"(",
")",
")",
":",
"item",
".",
"set_visible",
"(",
"False",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Bloch.plot_vectors
|
Plot vector
|
qiskit/visualization/bloch.py
|
def plot_vectors(self):
"""Plot vector"""
# -X and Y data are switched for plotting purposes
for k in range(len(self.vectors)):
xs3d = self.vectors[k][1] * np.array([0, 1])
ys3d = -self.vectors[k][0] * np.array([0, 1])
zs3d = self.vectors[k][2] * np.array([0, 1])
color = self.vector_color[np.mod(k, len(self.vector_color))]
if self.vector_style == '':
# simple line style
self.axes.plot(xs3d, ys3d, zs3d,
zs=0, zdir='z', label='Z',
lw=self.vector_width, color=color)
else:
# decorated style, with arrow heads
arr = Arrow3D(xs3d, ys3d, zs3d,
mutation_scale=self.vector_mutation,
lw=self.vector_width,
arrowstyle=self.vector_style,
color=color)
self.axes.add_artist(arr)
|
def plot_vectors(self):
"""Plot vector"""
# -X and Y data are switched for plotting purposes
for k in range(len(self.vectors)):
xs3d = self.vectors[k][1] * np.array([0, 1])
ys3d = -self.vectors[k][0] * np.array([0, 1])
zs3d = self.vectors[k][2] * np.array([0, 1])
color = self.vector_color[np.mod(k, len(self.vector_color))]
if self.vector_style == '':
# simple line style
self.axes.plot(xs3d, ys3d, zs3d,
zs=0, zdir='z', label='Z',
lw=self.vector_width, color=color)
else:
# decorated style, with arrow heads
arr = Arrow3D(xs3d, ys3d, zs3d,
mutation_scale=self.vector_mutation,
lw=self.vector_width,
arrowstyle=self.vector_style,
color=color)
self.axes.add_artist(arr)
|
[
"Plot",
"vector"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/bloch.py#L494-L518
|
[
"def",
"plot_vectors",
"(",
"self",
")",
":",
"# -X and Y data are switched for plotting purposes",
"for",
"k",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"vectors",
")",
")",
":",
"xs3d",
"=",
"self",
".",
"vectors",
"[",
"k",
"]",
"[",
"1",
"]",
"*",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
"]",
")",
"ys3d",
"=",
"-",
"self",
".",
"vectors",
"[",
"k",
"]",
"[",
"0",
"]",
"*",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
"]",
")",
"zs3d",
"=",
"self",
".",
"vectors",
"[",
"k",
"]",
"[",
"2",
"]",
"*",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
"]",
")",
"color",
"=",
"self",
".",
"vector_color",
"[",
"np",
".",
"mod",
"(",
"k",
",",
"len",
"(",
"self",
".",
"vector_color",
")",
")",
"]",
"if",
"self",
".",
"vector_style",
"==",
"''",
":",
"# simple line style",
"self",
".",
"axes",
".",
"plot",
"(",
"xs3d",
",",
"ys3d",
",",
"zs3d",
",",
"zs",
"=",
"0",
",",
"zdir",
"=",
"'z'",
",",
"label",
"=",
"'Z'",
",",
"lw",
"=",
"self",
".",
"vector_width",
",",
"color",
"=",
"color",
")",
"else",
":",
"# decorated style, with arrow heads",
"arr",
"=",
"Arrow3D",
"(",
"xs3d",
",",
"ys3d",
",",
"zs3d",
",",
"mutation_scale",
"=",
"self",
".",
"vector_mutation",
",",
"lw",
"=",
"self",
".",
"vector_width",
",",
"arrowstyle",
"=",
"self",
".",
"vector_style",
",",
"color",
"=",
"color",
")",
"self",
".",
"axes",
".",
"add_artist",
"(",
"arr",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Bloch.plot_points
|
Plot points
|
qiskit/visualization/bloch.py
|
def plot_points(self):
"""Plot points"""
# -X and Y data are switched for plotting purposes
for k in range(len(self.points)):
num = len(self.points[k][0])
dist = [np.sqrt(self.points[k][0][j] ** 2 +
self.points[k][1][j] ** 2 +
self.points[k][2][j] ** 2) for j in range(num)]
if any(abs(dist - dist[0]) / dist[0] > 1e-12):
# combine arrays so that they can be sorted together
zipped = list(zip(dist, range(num)))
zipped.sort() # sort rates from lowest to highest
dist, indperm = zip(*zipped)
indperm = np.array(indperm)
else:
indperm = np.arange(num)
if self.point_style[k] == 's':
self.axes.scatter(
np.real(self.points[k][1][indperm]),
- np.real(self.points[k][0][indperm]),
np.real(self.points[k][2][indperm]),
s=self.point_size[np.mod(k, len(self.point_size))],
alpha=1,
edgecolor='none',
zdir='z',
color=self.point_color[np.mod(k, len(self.point_color))],
marker=self.point_marker[np.mod(k,
len(self.point_marker))])
elif self.point_style[k] == 'm':
pnt_colors = np.array(self.point_color *
int(np.ceil(num /
float(len(self.point_color)))))
pnt_colors = pnt_colors[0:num]
pnt_colors = list(pnt_colors[indperm])
marker = self.point_marker[np.mod(k, len(self.point_marker))]
pnt_size = self.point_size[np.mod(k, len(self.point_size))]
self.axes.scatter(np.real(self.points[k][1][indperm]),
-np.real(self.points[k][0][indperm]),
np.real(self.points[k][2][indperm]),
s=pnt_size, alpha=1, edgecolor='none',
zdir='z', color=pnt_colors,
marker=marker)
elif self.point_style[k] == 'l':
color = self.point_color[np.mod(k, len(self.point_color))]
self.axes.plot(np.real(self.points[k][1]),
-np.real(self.points[k][0]),
np.real(self.points[k][2]),
alpha=0.75, zdir='z',
color=color)
|
def plot_points(self):
"""Plot points"""
# -X and Y data are switched for plotting purposes
for k in range(len(self.points)):
num = len(self.points[k][0])
dist = [np.sqrt(self.points[k][0][j] ** 2 +
self.points[k][1][j] ** 2 +
self.points[k][2][j] ** 2) for j in range(num)]
if any(abs(dist - dist[0]) / dist[0] > 1e-12):
# combine arrays so that they can be sorted together
zipped = list(zip(dist, range(num)))
zipped.sort() # sort rates from lowest to highest
dist, indperm = zip(*zipped)
indperm = np.array(indperm)
else:
indperm = np.arange(num)
if self.point_style[k] == 's':
self.axes.scatter(
np.real(self.points[k][1][indperm]),
- np.real(self.points[k][0][indperm]),
np.real(self.points[k][2][indperm]),
s=self.point_size[np.mod(k, len(self.point_size))],
alpha=1,
edgecolor='none',
zdir='z',
color=self.point_color[np.mod(k, len(self.point_color))],
marker=self.point_marker[np.mod(k,
len(self.point_marker))])
elif self.point_style[k] == 'm':
pnt_colors = np.array(self.point_color *
int(np.ceil(num /
float(len(self.point_color)))))
pnt_colors = pnt_colors[0:num]
pnt_colors = list(pnt_colors[indperm])
marker = self.point_marker[np.mod(k, len(self.point_marker))]
pnt_size = self.point_size[np.mod(k, len(self.point_size))]
self.axes.scatter(np.real(self.points[k][1][indperm]),
-np.real(self.points[k][0][indperm]),
np.real(self.points[k][2][indperm]),
s=pnt_size, alpha=1, edgecolor='none',
zdir='z', color=pnt_colors,
marker=marker)
elif self.point_style[k] == 'l':
color = self.point_color[np.mod(k, len(self.point_color))]
self.axes.plot(np.real(self.points[k][1]),
-np.real(self.points[k][0]),
np.real(self.points[k][2]),
alpha=0.75, zdir='z',
color=color)
|
[
"Plot",
"points"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/bloch.py#L520-L571
|
[
"def",
"plot_points",
"(",
"self",
")",
":",
"# -X and Y data are switched for plotting purposes",
"for",
"k",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"points",
")",
")",
":",
"num",
"=",
"len",
"(",
"self",
".",
"points",
"[",
"k",
"]",
"[",
"0",
"]",
")",
"dist",
"=",
"[",
"np",
".",
"sqrt",
"(",
"self",
".",
"points",
"[",
"k",
"]",
"[",
"0",
"]",
"[",
"j",
"]",
"**",
"2",
"+",
"self",
".",
"points",
"[",
"k",
"]",
"[",
"1",
"]",
"[",
"j",
"]",
"**",
"2",
"+",
"self",
".",
"points",
"[",
"k",
"]",
"[",
"2",
"]",
"[",
"j",
"]",
"**",
"2",
")",
"for",
"j",
"in",
"range",
"(",
"num",
")",
"]",
"if",
"any",
"(",
"abs",
"(",
"dist",
"-",
"dist",
"[",
"0",
"]",
")",
"/",
"dist",
"[",
"0",
"]",
">",
"1e-12",
")",
":",
"# combine arrays so that they can be sorted together",
"zipped",
"=",
"list",
"(",
"zip",
"(",
"dist",
",",
"range",
"(",
"num",
")",
")",
")",
"zipped",
".",
"sort",
"(",
")",
"# sort rates from lowest to highest",
"dist",
",",
"indperm",
"=",
"zip",
"(",
"*",
"zipped",
")",
"indperm",
"=",
"np",
".",
"array",
"(",
"indperm",
")",
"else",
":",
"indperm",
"=",
"np",
".",
"arange",
"(",
"num",
")",
"if",
"self",
".",
"point_style",
"[",
"k",
"]",
"==",
"'s'",
":",
"self",
".",
"axes",
".",
"scatter",
"(",
"np",
".",
"real",
"(",
"self",
".",
"points",
"[",
"k",
"]",
"[",
"1",
"]",
"[",
"indperm",
"]",
")",
",",
"-",
"np",
".",
"real",
"(",
"self",
".",
"points",
"[",
"k",
"]",
"[",
"0",
"]",
"[",
"indperm",
"]",
")",
",",
"np",
".",
"real",
"(",
"self",
".",
"points",
"[",
"k",
"]",
"[",
"2",
"]",
"[",
"indperm",
"]",
")",
",",
"s",
"=",
"self",
".",
"point_size",
"[",
"np",
".",
"mod",
"(",
"k",
",",
"len",
"(",
"self",
".",
"point_size",
")",
")",
"]",
",",
"alpha",
"=",
"1",
",",
"edgecolor",
"=",
"'none'",
",",
"zdir",
"=",
"'z'",
",",
"color",
"=",
"self",
".",
"point_color",
"[",
"np",
".",
"mod",
"(",
"k",
",",
"len",
"(",
"self",
".",
"point_color",
")",
")",
"]",
",",
"marker",
"=",
"self",
".",
"point_marker",
"[",
"np",
".",
"mod",
"(",
"k",
",",
"len",
"(",
"self",
".",
"point_marker",
")",
")",
"]",
")",
"elif",
"self",
".",
"point_style",
"[",
"k",
"]",
"==",
"'m'",
":",
"pnt_colors",
"=",
"np",
".",
"array",
"(",
"self",
".",
"point_color",
"*",
"int",
"(",
"np",
".",
"ceil",
"(",
"num",
"/",
"float",
"(",
"len",
"(",
"self",
".",
"point_color",
")",
")",
")",
")",
")",
"pnt_colors",
"=",
"pnt_colors",
"[",
"0",
":",
"num",
"]",
"pnt_colors",
"=",
"list",
"(",
"pnt_colors",
"[",
"indperm",
"]",
")",
"marker",
"=",
"self",
".",
"point_marker",
"[",
"np",
".",
"mod",
"(",
"k",
",",
"len",
"(",
"self",
".",
"point_marker",
")",
")",
"]",
"pnt_size",
"=",
"self",
".",
"point_size",
"[",
"np",
".",
"mod",
"(",
"k",
",",
"len",
"(",
"self",
".",
"point_size",
")",
")",
"]",
"self",
".",
"axes",
".",
"scatter",
"(",
"np",
".",
"real",
"(",
"self",
".",
"points",
"[",
"k",
"]",
"[",
"1",
"]",
"[",
"indperm",
"]",
")",
",",
"-",
"np",
".",
"real",
"(",
"self",
".",
"points",
"[",
"k",
"]",
"[",
"0",
"]",
"[",
"indperm",
"]",
")",
",",
"np",
".",
"real",
"(",
"self",
".",
"points",
"[",
"k",
"]",
"[",
"2",
"]",
"[",
"indperm",
"]",
")",
",",
"s",
"=",
"pnt_size",
",",
"alpha",
"=",
"1",
",",
"edgecolor",
"=",
"'none'",
",",
"zdir",
"=",
"'z'",
",",
"color",
"=",
"pnt_colors",
",",
"marker",
"=",
"marker",
")",
"elif",
"self",
".",
"point_style",
"[",
"k",
"]",
"==",
"'l'",
":",
"color",
"=",
"self",
".",
"point_color",
"[",
"np",
".",
"mod",
"(",
"k",
",",
"len",
"(",
"self",
".",
"point_color",
")",
")",
"]",
"self",
".",
"axes",
".",
"plot",
"(",
"np",
".",
"real",
"(",
"self",
".",
"points",
"[",
"k",
"]",
"[",
"1",
"]",
")",
",",
"-",
"np",
".",
"real",
"(",
"self",
".",
"points",
"[",
"k",
"]",
"[",
"0",
"]",
")",
",",
"np",
".",
"real",
"(",
"self",
".",
"points",
"[",
"k",
"]",
"[",
"2",
"]",
")",
",",
"alpha",
"=",
"0.75",
",",
"zdir",
"=",
"'z'",
",",
"color",
"=",
"color",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Bloch.plot_annotations
|
Plot annotations
|
qiskit/visualization/bloch.py
|
def plot_annotations(self):
"""Plot annotations"""
# -X and Y data are switched for plotting purposes
for annotation in self.annotations:
vec = annotation['position']
opts = {'fontsize': self.font_size,
'color': self.font_color,
'horizontalalignment': 'center',
'verticalalignment': 'center'}
opts.update(annotation['opts'])
self.axes.text(vec[1], -vec[0], vec[2],
annotation['text'], **opts)
|
def plot_annotations(self):
"""Plot annotations"""
# -X and Y data are switched for plotting purposes
for annotation in self.annotations:
vec = annotation['position']
opts = {'fontsize': self.font_size,
'color': self.font_color,
'horizontalalignment': 'center',
'verticalalignment': 'center'}
opts.update(annotation['opts'])
self.axes.text(vec[1], -vec[0], vec[2],
annotation['text'], **opts)
|
[
"Plot",
"annotations"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/bloch.py#L573-L584
|
[
"def",
"plot_annotations",
"(",
"self",
")",
":",
"# -X and Y data are switched for plotting purposes",
"for",
"annotation",
"in",
"self",
".",
"annotations",
":",
"vec",
"=",
"annotation",
"[",
"'position'",
"]",
"opts",
"=",
"{",
"'fontsize'",
":",
"self",
".",
"font_size",
",",
"'color'",
":",
"self",
".",
"font_color",
",",
"'horizontalalignment'",
":",
"'center'",
",",
"'verticalalignment'",
":",
"'center'",
"}",
"opts",
".",
"update",
"(",
"annotation",
"[",
"'opts'",
"]",
")",
"self",
".",
"axes",
".",
"text",
"(",
"vec",
"[",
"1",
"]",
",",
"-",
"vec",
"[",
"0",
"]",
",",
"vec",
"[",
"2",
"]",
",",
"annotation",
"[",
"'text'",
"]",
",",
"*",
"*",
"opts",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Bloch.show
|
Display Bloch sphere and corresponding data sets.
|
qiskit/visualization/bloch.py
|
def show(self, title=''):
"""
Display Bloch sphere and corresponding data sets.
"""
self.render(title=title)
if self.fig:
plt.show(self.fig)
|
def show(self, title=''):
"""
Display Bloch sphere and corresponding data sets.
"""
self.render(title=title)
if self.fig:
plt.show(self.fig)
|
[
"Display",
"Bloch",
"sphere",
"and",
"corresponding",
"data",
"sets",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/bloch.py#L586-L592
|
[
"def",
"show",
"(",
"self",
",",
"title",
"=",
"''",
")",
":",
"self",
".",
"render",
"(",
"title",
"=",
"title",
")",
"if",
"self",
".",
"fig",
":",
"plt",
".",
"show",
"(",
"self",
".",
"fig",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Bloch.save
|
Saves Bloch sphere to file of type ``format`` in directory ``dirc``.
Args:
name (str):
Name of saved image. Must include path and format as well.
i.e. '/Users/Paul/Desktop/bloch.png'
This overrides the 'format' and 'dirc' arguments.
output (str):
Format of output image.
dirc (str):
Directory for output images. Defaults to current working directory.
|
qiskit/visualization/bloch.py
|
def save(self, name=None, output='png', dirc=None):
"""Saves Bloch sphere to file of type ``format`` in directory ``dirc``.
Args:
name (str):
Name of saved image. Must include path and format as well.
i.e. '/Users/Paul/Desktop/bloch.png'
This overrides the 'format' and 'dirc' arguments.
output (str):
Format of output image.
dirc (str):
Directory for output images. Defaults to current working directory.
"""
self.render()
if dirc:
if not os.path.isdir(os.getcwd() + "/" + str(dirc)):
os.makedirs(os.getcwd() + "/" + str(dirc))
if name is None:
if dirc:
self.fig.savefig(os.getcwd() + "/" + str(dirc) + '/bloch_' +
str(self.savenum) + '.' + output)
else:
self.fig.savefig(os.getcwd() + '/bloch_' + str(self.savenum) +
'.' + output)
else:
self.fig.savefig(name)
self.savenum += 1
if self.fig:
plt.close(self.fig)
|
def save(self, name=None, output='png', dirc=None):
"""Saves Bloch sphere to file of type ``format`` in directory ``dirc``.
Args:
name (str):
Name of saved image. Must include path and format as well.
i.e. '/Users/Paul/Desktop/bloch.png'
This overrides the 'format' and 'dirc' arguments.
output (str):
Format of output image.
dirc (str):
Directory for output images. Defaults to current working directory.
"""
self.render()
if dirc:
if not os.path.isdir(os.getcwd() + "/" + str(dirc)):
os.makedirs(os.getcwd() + "/" + str(dirc))
if name is None:
if dirc:
self.fig.savefig(os.getcwd() + "/" + str(dirc) + '/bloch_' +
str(self.savenum) + '.' + output)
else:
self.fig.savefig(os.getcwd() + '/bloch_' + str(self.savenum) +
'.' + output)
else:
self.fig.savefig(name)
self.savenum += 1
if self.fig:
plt.close(self.fig)
|
[
"Saves",
"Bloch",
"sphere",
"to",
"file",
"of",
"type",
"format",
"in",
"directory",
"dirc",
".",
"Args",
":",
"name",
"(",
"str",
")",
":",
"Name",
"of",
"saved",
"image",
".",
"Must",
"include",
"path",
"and",
"format",
"as",
"well",
".",
"i",
".",
"e",
".",
"/",
"Users",
"/",
"Paul",
"/",
"Desktop",
"/",
"bloch",
".",
"png",
"This",
"overrides",
"the",
"format",
"and",
"dirc",
"arguments",
".",
"output",
"(",
"str",
")",
":",
"Format",
"of",
"output",
"image",
".",
"dirc",
"(",
"str",
")",
":",
"Directory",
"for",
"output",
"images",
".",
"Defaults",
"to",
"current",
"working",
"directory",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/bloch.py#L594-L622
|
[
"def",
"save",
"(",
"self",
",",
"name",
"=",
"None",
",",
"output",
"=",
"'png'",
",",
"dirc",
"=",
"None",
")",
":",
"self",
".",
"render",
"(",
")",
"if",
"dirc",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"getcwd",
"(",
")",
"+",
"\"/\"",
"+",
"str",
"(",
"dirc",
")",
")",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"getcwd",
"(",
")",
"+",
"\"/\"",
"+",
"str",
"(",
"dirc",
")",
")",
"if",
"name",
"is",
"None",
":",
"if",
"dirc",
":",
"self",
".",
"fig",
".",
"savefig",
"(",
"os",
".",
"getcwd",
"(",
")",
"+",
"\"/\"",
"+",
"str",
"(",
"dirc",
")",
"+",
"'/bloch_'",
"+",
"str",
"(",
"self",
".",
"savenum",
")",
"+",
"'.'",
"+",
"output",
")",
"else",
":",
"self",
".",
"fig",
".",
"savefig",
"(",
"os",
".",
"getcwd",
"(",
")",
"+",
"'/bloch_'",
"+",
"str",
"(",
"self",
".",
"savenum",
")",
"+",
"'.'",
"+",
"output",
")",
"else",
":",
"self",
".",
"fig",
".",
"savefig",
"(",
"name",
")",
"self",
".",
"savenum",
"+=",
"1",
"if",
"self",
".",
"fig",
":",
"plt",
".",
"close",
"(",
"self",
".",
"fig",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
two_qubit_kak
|
Deprecated after 0.8
|
qiskit/mapper/compiling.py
|
def two_qubit_kak(unitary_matrix, verify_gate_sequence=False):
"""Deprecated after 0.8
"""
warnings.warn("two_qubit_kak function is now accessible under "
"qiskit.quantum_info.synthesis", DeprecationWarning)
return synthesis.two_qubit_kak(unitary_matrix)
|
def two_qubit_kak(unitary_matrix, verify_gate_sequence=False):
"""Deprecated after 0.8
"""
warnings.warn("two_qubit_kak function is now accessible under "
"qiskit.quantum_info.synthesis", DeprecationWarning)
return synthesis.two_qubit_kak(unitary_matrix)
|
[
"Deprecated",
"after",
"0",
".",
"8"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/mapper/compiling.py#L27-L32
|
[
"def",
"two_qubit_kak",
"(",
"unitary_matrix",
",",
"verify_gate_sequence",
"=",
"False",
")",
":",
"warnings",
".",
"warn",
"(",
"\"two_qubit_kak function is now accessible under \"",
"\"qiskit.quantum_info.synthesis\"",
",",
"DeprecationWarning",
")",
"return",
"synthesis",
".",
"two_qubit_kak",
"(",
"unitary_matrix",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
DrawElement.top
|
Constructs the top line of the element
|
qiskit/visualization/text.py
|
def top(self):
""" Constructs the top line of the element"""
ret = self.top_format % self.top_connect.center(
self.width, self.top_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.top_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.top_pad)
ret = ret.center(self.layer_width, self.top_bck)
return ret
|
def top(self):
""" Constructs the top line of the element"""
ret = self.top_format % self.top_connect.center(
self.width, self.top_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.top_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.top_pad)
ret = ret.center(self.layer_width, self.top_bck)
return ret
|
[
"Constructs",
"the",
"top",
"line",
"of",
"the",
"element"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L36-L45
|
[
"def",
"top",
"(",
"self",
")",
":",
"ret",
"=",
"self",
".",
"top_format",
"%",
"self",
".",
"top_connect",
".",
"center",
"(",
"self",
".",
"width",
",",
"self",
".",
"top_pad",
")",
"if",
"self",
".",
"right_fill",
":",
"ret",
"=",
"ret",
".",
"ljust",
"(",
"self",
".",
"right_fill",
",",
"self",
".",
"top_pad",
")",
"if",
"self",
".",
"left_fill",
":",
"ret",
"=",
"ret",
".",
"rjust",
"(",
"self",
".",
"left_fill",
",",
"self",
".",
"top_pad",
")",
"ret",
"=",
"ret",
".",
"center",
"(",
"self",
".",
"layer_width",
",",
"self",
".",
"top_bck",
")",
"return",
"ret"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
DrawElement.mid
|
Constructs the middle line of the element
|
qiskit/visualization/text.py
|
def mid(self):
""" Constructs the middle line of the element"""
ret = self.mid_format % self.mid_content.center(
self.width, self._mid_padding)
if self.right_fill:
ret = ret.ljust(self.right_fill, self._mid_padding)
if self.left_fill:
ret = ret.rjust(self.left_fill, self._mid_padding)
ret = ret.center(self.layer_width, self.mid_bck)
return ret
|
def mid(self):
""" Constructs the middle line of the element"""
ret = self.mid_format % self.mid_content.center(
self.width, self._mid_padding)
if self.right_fill:
ret = ret.ljust(self.right_fill, self._mid_padding)
if self.left_fill:
ret = ret.rjust(self.left_fill, self._mid_padding)
ret = ret.center(self.layer_width, self.mid_bck)
return ret
|
[
"Constructs",
"the",
"middle",
"line",
"of",
"the",
"element"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L48-L57
|
[
"def",
"mid",
"(",
"self",
")",
":",
"ret",
"=",
"self",
".",
"mid_format",
"%",
"self",
".",
"mid_content",
".",
"center",
"(",
"self",
".",
"width",
",",
"self",
".",
"_mid_padding",
")",
"if",
"self",
".",
"right_fill",
":",
"ret",
"=",
"ret",
".",
"ljust",
"(",
"self",
".",
"right_fill",
",",
"self",
".",
"_mid_padding",
")",
"if",
"self",
".",
"left_fill",
":",
"ret",
"=",
"ret",
".",
"rjust",
"(",
"self",
".",
"left_fill",
",",
"self",
".",
"_mid_padding",
")",
"ret",
"=",
"ret",
".",
"center",
"(",
"self",
".",
"layer_width",
",",
"self",
".",
"mid_bck",
")",
"return",
"ret"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
DrawElement.bot
|
Constructs the bottom line of the element
|
qiskit/visualization/text.py
|
def bot(self):
""" Constructs the bottom line of the element"""
ret = self.bot_format % self.bot_connect.center(
self.width, self.bot_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.bot_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.bot_pad)
ret = ret.center(self.layer_width, self.bot_bck)
return ret
|
def bot(self):
""" Constructs the bottom line of the element"""
ret = self.bot_format % self.bot_connect.center(
self.width, self.bot_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.bot_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.bot_pad)
ret = ret.center(self.layer_width, self.bot_bck)
return ret
|
[
"Constructs",
"the",
"bottom",
"line",
"of",
"the",
"element"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L60-L69
|
[
"def",
"bot",
"(",
"self",
")",
":",
"ret",
"=",
"self",
".",
"bot_format",
"%",
"self",
".",
"bot_connect",
".",
"center",
"(",
"self",
".",
"width",
",",
"self",
".",
"bot_pad",
")",
"if",
"self",
".",
"right_fill",
":",
"ret",
"=",
"ret",
".",
"ljust",
"(",
"self",
".",
"right_fill",
",",
"self",
".",
"bot_pad",
")",
"if",
"self",
".",
"left_fill",
":",
"ret",
"=",
"ret",
".",
"rjust",
"(",
"self",
".",
"left_fill",
",",
"self",
".",
"bot_pad",
")",
"ret",
"=",
"ret",
".",
"center",
"(",
"self",
".",
"layer_width",
",",
"self",
".",
"bot_bck",
")",
"return",
"ret"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
DrawElement.length
|
Returns the length of the element, including the box around.
|
qiskit/visualization/text.py
|
def length(self):
""" Returns the length of the element, including the box around."""
return max(len(self.top), len(self.mid), len(self.bot))
|
def length(self):
""" Returns the length of the element, including the box around."""
return max(len(self.top), len(self.mid), len(self.bot))
|
[
"Returns",
"the",
"length",
"of",
"the",
"element",
"including",
"the",
"box",
"around",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L72-L74
|
[
"def",
"length",
"(",
"self",
")",
":",
"return",
"max",
"(",
"len",
"(",
"self",
".",
"top",
")",
",",
"len",
"(",
"self",
".",
"mid",
")",
",",
"len",
"(",
"self",
".",
"bot",
")",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
DrawElement.connect
|
Connects boxes and elements using wire_char and setting proper connectors.
Args:
wire_char (char): For example '║' or '│'.
where (list["top", "bot"]): Where the connector should be set.
label (string): Some connectors have a label (see cu1, for example).
|
qiskit/visualization/text.py
|
def connect(self, wire_char, where, label=None):
"""
Connects boxes and elements using wire_char and setting proper connectors.
Args:
wire_char (char): For example '║' or '│'.
where (list["top", "bot"]): Where the connector should be set.
label (string): Some connectors have a label (see cu1, for example).
"""
if 'top' in where and self.top_connector:
self.top_connect = self.top_connector[wire_char]
if 'bot' in where and self.bot_connector:
self.bot_connect = self.bot_connector[wire_char]
if label:
self.top_format = self.top_format[:-1] + (label if label else "")
|
def connect(self, wire_char, where, label=None):
"""
Connects boxes and elements using wire_char and setting proper connectors.
Args:
wire_char (char): For example '║' or '│'.
where (list["top", "bot"]): Where the connector should be set.
label (string): Some connectors have a label (see cu1, for example).
"""
if 'top' in where and self.top_connector:
self.top_connect = self.top_connector[wire_char]
if 'bot' in where and self.bot_connector:
self.bot_connect = self.bot_connector[wire_char]
if label:
self.top_format = self.top_format[:-1] + (label if label else "")
|
[
"Connects",
"boxes",
"and",
"elements",
"using",
"wire_char",
"and",
"setting",
"proper",
"connectors",
".",
"Args",
":",
"wire_char",
"(",
"char",
")",
":",
"For",
"example",
"║",
"or",
"│",
".",
"where",
"(",
"list",
"[",
"top",
"bot",
"]",
")",
":",
"Where",
"the",
"connector",
"should",
"be",
"set",
".",
"label",
"(",
"string",
")",
":",
"Some",
"connectors",
"have",
"a",
"label",
"(",
"see",
"cu1",
"for",
"example",
")",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L87-L103
|
[
"def",
"connect",
"(",
"self",
",",
"wire_char",
",",
"where",
",",
"label",
"=",
"None",
")",
":",
"if",
"'top'",
"in",
"where",
"and",
"self",
".",
"top_connector",
":",
"self",
".",
"top_connect",
"=",
"self",
".",
"top_connector",
"[",
"wire_char",
"]",
"if",
"'bot'",
"in",
"where",
"and",
"self",
".",
"bot_connector",
":",
"self",
".",
"bot_connect",
"=",
"self",
".",
"bot_connector",
"[",
"wire_char",
"]",
"if",
"label",
":",
"self",
".",
"top_format",
"=",
"self",
".",
"top_format",
"[",
":",
"-",
"1",
"]",
"+",
"(",
"label",
"if",
"label",
"else",
"\"\"",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
MultiBox.center_label
|
In multi-bit elements, the label is centered vertically.
Args:
input_length (int): Rhe amount of wires affected.
order (int): Which middle element is this one?
|
qiskit/visualization/text.py
|
def center_label(self, input_length, order):
"""
In multi-bit elements, the label is centered vertically.
Args:
input_length (int): Rhe amount of wires affected.
order (int): Which middle element is this one?
"""
location_in_the_box = '*'.center(input_length * 2 - 1).index('*') + 1
top_limit = order * 2 + 2
bot_limit = top_limit + 2
if top_limit <= location_in_the_box < bot_limit:
if location_in_the_box == top_limit:
self.top_connect = self.label
elif location_in_the_box == top_limit + 1:
self.mid_content = self.label
else:
self.bot_connect = self.label
|
def center_label(self, input_length, order):
"""
In multi-bit elements, the label is centered vertically.
Args:
input_length (int): Rhe amount of wires affected.
order (int): Which middle element is this one?
"""
location_in_the_box = '*'.center(input_length * 2 - 1).index('*') + 1
top_limit = order * 2 + 2
bot_limit = top_limit + 2
if top_limit <= location_in_the_box < bot_limit:
if location_in_the_box == top_limit:
self.top_connect = self.label
elif location_in_the_box == top_limit + 1:
self.mid_content = self.label
else:
self.bot_connect = self.label
|
[
"In",
"multi",
"-",
"bit",
"elements",
"the",
"label",
"is",
"centered",
"vertically",
".",
"Args",
":",
"input_length",
"(",
"int",
")",
":",
"Rhe",
"amount",
"of",
"wires",
"affected",
".",
"order",
"(",
"int",
")",
":",
"Which",
"middle",
"element",
"is",
"this",
"one?"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L181-L197
|
[
"def",
"center_label",
"(",
"self",
",",
"input_length",
",",
"order",
")",
":",
"location_in_the_box",
"=",
"'*'",
".",
"center",
"(",
"input_length",
"*",
"2",
"-",
"1",
")",
".",
"index",
"(",
"'*'",
")",
"+",
"1",
"top_limit",
"=",
"order",
"*",
"2",
"+",
"2",
"bot_limit",
"=",
"top_limit",
"+",
"2",
"if",
"top_limit",
"<=",
"location_in_the_box",
"<",
"bot_limit",
":",
"if",
"location_in_the_box",
"==",
"top_limit",
":",
"self",
".",
"top_connect",
"=",
"self",
".",
"label",
"elif",
"location_in_the_box",
"==",
"top_limit",
"+",
"1",
":",
"self",
".",
"mid_content",
"=",
"self",
".",
"label",
"else",
":",
"self",
".",
"bot_connect",
"=",
"self",
".",
"label"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
EmptyWire.fillup_layer
|
Given a layer, replace the Nones in it with EmptyWire elements.
Args:
layer (list): The layer that contains Nones.
first_clbit (int): The first wire that is classic.
Returns:
list: The new layer, with no Nones.
|
qiskit/visualization/text.py
|
def fillup_layer(layer, first_clbit):
"""
Given a layer, replace the Nones in it with EmptyWire elements.
Args:
layer (list): The layer that contains Nones.
first_clbit (int): The first wire that is classic.
Returns:
list: The new layer, with no Nones.
"""
for nones in [i for i, x in enumerate(layer) if x is None]:
layer[nones] = EmptyWire('═') if nones >= first_clbit else EmptyWire('─')
return layer
|
def fillup_layer(layer, first_clbit):
"""
Given a layer, replace the Nones in it with EmptyWire elements.
Args:
layer (list): The layer that contains Nones.
first_clbit (int): The first wire that is classic.
Returns:
list: The new layer, with no Nones.
"""
for nones in [i for i, x in enumerate(layer) if x is None]:
layer[nones] = EmptyWire('═') if nones >= first_clbit else EmptyWire('─')
return layer
|
[
"Given",
"a",
"layer",
"replace",
"the",
"Nones",
"in",
"it",
"with",
"EmptyWire",
"elements",
".",
"Args",
":",
"layer",
"(",
"list",
")",
":",
"The",
"layer",
"that",
"contains",
"Nones",
".",
"first_clbit",
"(",
"int",
")",
":",
"The",
"first",
"wire",
"that",
"is",
"classic",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L367-L379
|
[
"def",
"fillup_layer",
"(",
"layer",
",",
"first_clbit",
")",
":",
"for",
"nones",
"in",
"[",
"i",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"layer",
")",
"if",
"x",
"is",
"None",
"]",
":",
"layer",
"[",
"nones",
"]",
"=",
"EmptyWire",
"(",
"'═') ",
"i",
" n",
"nes >",
" f",
"rst_clbit e",
"se E",
"ptyWire('",
"─",
"')",
"",
"return",
"layer"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
BreakWire.fillup_layer
|
Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer.
|
qiskit/visualization/text.py
|
def fillup_layer(layer_length, arrow_char):
"""
Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer.
"""
breakwire_layer = []
for _ in range(layer_length):
breakwire_layer.append(BreakWire(arrow_char))
return breakwire_layer
|
def fillup_layer(layer_length, arrow_char):
"""
Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer.
"""
breakwire_layer = []
for _ in range(layer_length):
breakwire_layer.append(BreakWire(arrow_char))
return breakwire_layer
|
[
"Creates",
"a",
"layer",
"with",
"BreakWire",
"elements",
".",
"Args",
":",
"layer_length",
"(",
"int",
")",
":",
"The",
"length",
"of",
"the",
"layer",
"to",
"create",
"arrow_char",
"(",
"char",
")",
":",
"The",
"char",
"used",
"to",
"create",
"the",
"BreakWire",
"element",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L393-L406
|
[
"def",
"fillup_layer",
"(",
"layer_length",
",",
"arrow_char",
")",
":",
"breakwire_layer",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"layer_length",
")",
":",
"breakwire_layer",
".",
"append",
"(",
"BreakWire",
"(",
"arrow_char",
")",
")",
"return",
"breakwire_layer"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
InputWire.fillup_layer
|
Creates a layer with InputWire elements.
Args:
names (list): List of names for the wires.
Returns:
list: The new layer
|
qiskit/visualization/text.py
|
def fillup_layer(names): # pylint: disable=arguments-differ
"""
Creates a layer with InputWire elements.
Args:
names (list): List of names for the wires.
Returns:
list: The new layer
"""
longest = max([len(name) for name in names])
inputs_wires = []
for name in names:
inputs_wires.append(InputWire(name.rjust(longest)))
return inputs_wires
|
def fillup_layer(names): # pylint: disable=arguments-differ
"""
Creates a layer with InputWire elements.
Args:
names (list): List of names for the wires.
Returns:
list: The new layer
"""
longest = max([len(name) for name in names])
inputs_wires = []
for name in names:
inputs_wires.append(InputWire(name.rjust(longest)))
return inputs_wires
|
[
"Creates",
"a",
"layer",
"with",
"InputWire",
"elements",
".",
"Args",
":",
"names",
"(",
"list",
")",
":",
"List",
"of",
"names",
"for",
"the",
"wires",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L416-L429
|
[
"def",
"fillup_layer",
"(",
"names",
")",
":",
"# pylint: disable=arguments-differ",
"longest",
"=",
"max",
"(",
"[",
"len",
"(",
"name",
")",
"for",
"name",
"in",
"names",
"]",
")",
"inputs_wires",
"=",
"[",
"]",
"for",
"name",
"in",
"names",
":",
"inputs_wires",
".",
"append",
"(",
"InputWire",
"(",
"name",
".",
"rjust",
"(",
"longest",
")",
")",
")",
"return",
"inputs_wires"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
TextDrawing.dump
|
Dumps the ascii art in the file.
Args:
filename (str): File to dump the ascii art.
encoding (str): Optional. Default "utf-8".
|
qiskit/visualization/text.py
|
def dump(self, filename, encoding="utf8"):
"""
Dumps the ascii art in the file.
Args:
filename (str): File to dump the ascii art.
encoding (str): Optional. Default "utf-8".
"""
with open(filename, mode='w', encoding=encoding) as text_file:
text_file.write(self.single_string())
|
def dump(self, filename, encoding="utf8"):
"""
Dumps the ascii art in the file.
Args:
filename (str): File to dump the ascii art.
encoding (str): Optional. Default "utf-8".
"""
with open(filename, mode='w', encoding=encoding) as text_file:
text_file.write(self.single_string())
|
[
"Dumps",
"the",
"ascii",
"art",
"in",
"the",
"file",
".",
"Args",
":",
"filename",
"(",
"str",
")",
":",
"File",
"to",
"dump",
"the",
"ascii",
"art",
".",
"encoding",
"(",
"str",
")",
":",
"Optional",
".",
"Default",
"utf",
"-",
"8",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L473-L481
|
[
"def",
"dump",
"(",
"self",
",",
"filename",
",",
"encoding",
"=",
"\"utf8\"",
")",
":",
"with",
"open",
"(",
"filename",
",",
"mode",
"=",
"'w'",
",",
"encoding",
"=",
"encoding",
")",
"as",
"text_file",
":",
"text_file",
".",
"write",
"(",
"self",
".",
"single_string",
"(",
")",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
TextDrawing.lines
|
Generates a list with lines. These lines form the text drawing.
Args:
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
Returns:
list: A list of lines with the text drawing.
|
qiskit/visualization/text.py
|
def lines(self, line_length=None):
"""
Generates a list with lines. These lines form the text drawing.
Args:
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
Returns:
list: A list of lines with the text drawing.
"""
if line_length is None:
line_length = self.line_length
if line_length is None:
if ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
line_length = 80
else:
line_length, _ = get_terminal_size()
noqubits = len(self.qregs)
layers = self.build_layers()
if not line_length:
line_length = self.line_length
layer_groups = [[]]
rest_of_the_line = line_length
for layerno, layer in enumerate(layers):
# Replace the Nones with EmptyWire
layers[layerno] = EmptyWire.fillup_layer(layer, noqubits)
TextDrawing.normalize_width(layer)
if line_length == -1:
# Do not use pagination (aka line breaking. aka ignore line_length).
layer_groups[-1].append(layer)
continue
# chop the layer to the line_length (pager)
layer_length = layers[layerno][0].length
if layer_length < rest_of_the_line:
layer_groups[-1].append(layer)
rest_of_the_line -= layer_length
else:
layer_groups[-1].append(BreakWire.fillup_layer(len(layer), '»'))
# New group
layer_groups.append([BreakWire.fillup_layer(len(layer), '«')])
rest_of_the_line = line_length - layer_groups[-1][-1][0].length
layer_groups[-1].append(
InputWire.fillup_layer(self.wire_names(with_initial_value=False)))
rest_of_the_line -= layer_groups[-1][-1][0].length
layer_groups[-1].append(layer)
rest_of_the_line -= layer_groups[-1][-1][0].length
lines = []
for layer_group in layer_groups:
wires = [i for i in zip(*layer_group)]
lines += TextDrawing.draw_wires(wires, self.vertically_compressed)
return lines
|
def lines(self, line_length=None):
"""
Generates a list with lines. These lines form the text drawing.
Args:
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
Returns:
list: A list of lines with the text drawing.
"""
if line_length is None:
line_length = self.line_length
if line_length is None:
if ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
line_length = 80
else:
line_length, _ = get_terminal_size()
noqubits = len(self.qregs)
layers = self.build_layers()
if not line_length:
line_length = self.line_length
layer_groups = [[]]
rest_of_the_line = line_length
for layerno, layer in enumerate(layers):
# Replace the Nones with EmptyWire
layers[layerno] = EmptyWire.fillup_layer(layer, noqubits)
TextDrawing.normalize_width(layer)
if line_length == -1:
# Do not use pagination (aka line breaking. aka ignore line_length).
layer_groups[-1].append(layer)
continue
# chop the layer to the line_length (pager)
layer_length = layers[layerno][0].length
if layer_length < rest_of_the_line:
layer_groups[-1].append(layer)
rest_of_the_line -= layer_length
else:
layer_groups[-1].append(BreakWire.fillup_layer(len(layer), '»'))
# New group
layer_groups.append([BreakWire.fillup_layer(len(layer), '«')])
rest_of_the_line = line_length - layer_groups[-1][-1][0].length
layer_groups[-1].append(
InputWire.fillup_layer(self.wire_names(with_initial_value=False)))
rest_of_the_line -= layer_groups[-1][-1][0].length
layer_groups[-1].append(layer)
rest_of_the_line -= layer_groups[-1][-1][0].length
lines = []
for layer_group in layer_groups:
wires = [i for i in zip(*layer_group)]
lines += TextDrawing.draw_wires(wires, self.vertically_compressed)
return lines
|
[
"Generates",
"a",
"list",
"with",
"lines",
".",
"These",
"lines",
"form",
"the",
"text",
"drawing",
".",
"Args",
":",
"line_length",
"(",
"int",
")",
":",
"Optional",
".",
"Breaks",
"the",
"circuit",
"drawing",
"to",
"this",
"length",
".",
"This",
"useful",
"when",
"the",
"drawing",
"does",
"not",
"fit",
"in",
"the",
"console",
".",
"If",
"None",
"(",
"default",
")",
"it",
"will",
"try",
"to",
"guess",
"the",
"console",
"width",
"using",
"shutil",
".",
"get_terminal_size",
"()",
".",
"If",
"you",
"don",
"t",
"want",
"pagination",
"at",
"all",
"set",
"line_length",
"=",
"-",
"1",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L483-L549
|
[
"def",
"lines",
"(",
"self",
",",
"line_length",
"=",
"None",
")",
":",
"if",
"line_length",
"is",
"None",
":",
"line_length",
"=",
"self",
".",
"line_length",
"if",
"line_length",
"is",
"None",
":",
"if",
"(",
"'ipykernel'",
"in",
"sys",
".",
"modules",
")",
"and",
"(",
"'spyder'",
"not",
"in",
"sys",
".",
"modules",
")",
":",
"line_length",
"=",
"80",
"else",
":",
"line_length",
",",
"_",
"=",
"get_terminal_size",
"(",
")",
"noqubits",
"=",
"len",
"(",
"self",
".",
"qregs",
")",
"layers",
"=",
"self",
".",
"build_layers",
"(",
")",
"if",
"not",
"line_length",
":",
"line_length",
"=",
"self",
".",
"line_length",
"layer_groups",
"=",
"[",
"[",
"]",
"]",
"rest_of_the_line",
"=",
"line_length",
"for",
"layerno",
",",
"layer",
"in",
"enumerate",
"(",
"layers",
")",
":",
"# Replace the Nones with EmptyWire",
"layers",
"[",
"layerno",
"]",
"=",
"EmptyWire",
".",
"fillup_layer",
"(",
"layer",
",",
"noqubits",
")",
"TextDrawing",
".",
"normalize_width",
"(",
"layer",
")",
"if",
"line_length",
"==",
"-",
"1",
":",
"# Do not use pagination (aka line breaking. aka ignore line_length).",
"layer_groups",
"[",
"-",
"1",
"]",
".",
"append",
"(",
"layer",
")",
"continue",
"# chop the layer to the line_length (pager)",
"layer_length",
"=",
"layers",
"[",
"layerno",
"]",
"[",
"0",
"]",
".",
"length",
"if",
"layer_length",
"<",
"rest_of_the_line",
":",
"layer_groups",
"[",
"-",
"1",
"]",
".",
"append",
"(",
"layer",
")",
"rest_of_the_line",
"-=",
"layer_length",
"else",
":",
"layer_groups",
"[",
"-",
"1",
"]",
".",
"append",
"(",
"BreakWire",
".",
"fillup_layer",
"(",
"len",
"(",
"layer",
")",
",",
"'»')",
")",
"",
"# New group",
"layer_groups",
".",
"append",
"(",
"[",
"BreakWire",
".",
"fillup_layer",
"(",
"len",
"(",
"layer",
")",
",",
"'«')",
"]",
")",
"",
"rest_of_the_line",
"=",
"line_length",
"-",
"layer_groups",
"[",
"-",
"1",
"]",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
".",
"length",
"layer_groups",
"[",
"-",
"1",
"]",
".",
"append",
"(",
"InputWire",
".",
"fillup_layer",
"(",
"self",
".",
"wire_names",
"(",
"with_initial_value",
"=",
"False",
")",
")",
")",
"rest_of_the_line",
"-=",
"layer_groups",
"[",
"-",
"1",
"]",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
".",
"length",
"layer_groups",
"[",
"-",
"1",
"]",
".",
"append",
"(",
"layer",
")",
"rest_of_the_line",
"-=",
"layer_groups",
"[",
"-",
"1",
"]",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
".",
"length",
"lines",
"=",
"[",
"]",
"for",
"layer_group",
"in",
"layer_groups",
":",
"wires",
"=",
"[",
"i",
"for",
"i",
"in",
"zip",
"(",
"*",
"layer_group",
")",
"]",
"lines",
"+=",
"TextDrawing",
".",
"draw_wires",
"(",
"wires",
",",
"self",
".",
"vertically_compressed",
")",
"return",
"lines"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
TextDrawing.wire_names
|
Returns a list of names for each wire.
Args:
with_initial_value (bool): Optional (Default: True). If true, adds the initial value to
the name.
Returns:
List: The list of wire names.
|
qiskit/visualization/text.py
|
def wire_names(self, with_initial_value=True):
"""
Returns a list of names for each wire.
Args:
with_initial_value (bool): Optional (Default: True). If true, adds the initial value to
the name.
Returns:
List: The list of wire names.
"""
qubit_labels = self._get_qubit_labels()
clbit_labels = self._get_clbit_labels()
if with_initial_value:
qubit_labels = ['%s: |0>' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: 0 ' % clbit for clbit in clbit_labels]
else:
qubit_labels = ['%s: ' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: ' % clbit for clbit in clbit_labels]
return qubit_labels + clbit_labels
|
def wire_names(self, with_initial_value=True):
"""
Returns a list of names for each wire.
Args:
with_initial_value (bool): Optional (Default: True). If true, adds the initial value to
the name.
Returns:
List: The list of wire names.
"""
qubit_labels = self._get_qubit_labels()
clbit_labels = self._get_clbit_labels()
if with_initial_value:
qubit_labels = ['%s: |0>' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: 0 ' % clbit for clbit in clbit_labels]
else:
qubit_labels = ['%s: ' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: ' % clbit for clbit in clbit_labels]
return qubit_labels + clbit_labels
|
[
"Returns",
"a",
"list",
"of",
"names",
"for",
"each",
"wire",
".",
"Args",
":",
"with_initial_value",
"(",
"bool",
")",
":",
"Optional",
"(",
"Default",
":",
"True",
")",
".",
"If",
"true",
"adds",
"the",
"initial",
"value",
"to",
"the",
"name",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L551-L571
|
[
"def",
"wire_names",
"(",
"self",
",",
"with_initial_value",
"=",
"True",
")",
":",
"qubit_labels",
"=",
"self",
".",
"_get_qubit_labels",
"(",
")",
"clbit_labels",
"=",
"self",
".",
"_get_clbit_labels",
"(",
")",
"if",
"with_initial_value",
":",
"qubit_labels",
"=",
"[",
"'%s: |0>'",
"%",
"qubit",
"for",
"qubit",
"in",
"qubit_labels",
"]",
"clbit_labels",
"=",
"[",
"'%s: 0 '",
"%",
"clbit",
"for",
"clbit",
"in",
"clbit_labels",
"]",
"else",
":",
"qubit_labels",
"=",
"[",
"'%s: '",
"%",
"qubit",
"for",
"qubit",
"in",
"qubit_labels",
"]",
"clbit_labels",
"=",
"[",
"'%s: '",
"%",
"clbit",
"for",
"clbit",
"in",
"clbit_labels",
"]",
"return",
"qubit_labels",
"+",
"clbit_labels"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
TextDrawing.draw_wires
|
Given a list of wires, creates a list of lines with the text drawing.
Args:
wires (list): A list of wires with instructions.
vertically_compressed (bool): Default is `True`. It merges the lines
so the drawing will take less vertical room.
Returns:
list: A list of lines with the text drawing.
|
qiskit/visualization/text.py
|
def draw_wires(wires, vertically_compressed=True):
"""
Given a list of wires, creates a list of lines with the text drawing.
Args:
wires (list): A list of wires with instructions.
vertically_compressed (bool): Default is `True`. It merges the lines
so the drawing will take less vertical room.
Returns:
list: A list of lines with the text drawing.
"""
lines = []
bot_line = None
for wire in wires:
# TOP
top_line = ''
for instruction in wire:
top_line += instruction.top
if bot_line is None:
lines.append(top_line)
else:
if vertically_compressed:
lines.append(TextDrawing.merge_lines(lines.pop(), top_line))
else:
lines.append(TextDrawing.merge_lines(lines[-1], top_line, icod="bot"))
# MID
mid_line = ''
for instruction in wire:
mid_line += instruction.mid
lines.append(TextDrawing.merge_lines(lines[-1], mid_line, icod="bot"))
# BOT
bot_line = ''
for instruction in wire:
bot_line += instruction.bot
lines.append(TextDrawing.merge_lines(lines[-1], bot_line, icod="bot"))
return lines
|
def draw_wires(wires, vertically_compressed=True):
"""
Given a list of wires, creates a list of lines with the text drawing.
Args:
wires (list): A list of wires with instructions.
vertically_compressed (bool): Default is `True`. It merges the lines
so the drawing will take less vertical room.
Returns:
list: A list of lines with the text drawing.
"""
lines = []
bot_line = None
for wire in wires:
# TOP
top_line = ''
for instruction in wire:
top_line += instruction.top
if bot_line is None:
lines.append(top_line)
else:
if vertically_compressed:
lines.append(TextDrawing.merge_lines(lines.pop(), top_line))
else:
lines.append(TextDrawing.merge_lines(lines[-1], top_line, icod="bot"))
# MID
mid_line = ''
for instruction in wire:
mid_line += instruction.mid
lines.append(TextDrawing.merge_lines(lines[-1], mid_line, icod="bot"))
# BOT
bot_line = ''
for instruction in wire:
bot_line += instruction.bot
lines.append(TextDrawing.merge_lines(lines[-1], bot_line, icod="bot"))
return lines
|
[
"Given",
"a",
"list",
"of",
"wires",
"creates",
"a",
"list",
"of",
"lines",
"with",
"the",
"text",
"drawing",
".",
"Args",
":",
"wires",
"(",
"list",
")",
":",
"A",
"list",
"of",
"wires",
"with",
"instructions",
".",
"vertically_compressed",
"(",
"bool",
")",
":",
"Default",
"is",
"True",
".",
"It",
"merges",
"the",
"lines",
"so",
"the",
"drawing",
"will",
"take",
"less",
"vertical",
"room",
".",
"Returns",
":",
"list",
":",
"A",
"list",
"of",
"lines",
"with",
"the",
"text",
"drawing",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L574-L612
|
[
"def",
"draw_wires",
"(",
"wires",
",",
"vertically_compressed",
"=",
"True",
")",
":",
"lines",
"=",
"[",
"]",
"bot_line",
"=",
"None",
"for",
"wire",
"in",
"wires",
":",
"# TOP",
"top_line",
"=",
"''",
"for",
"instruction",
"in",
"wire",
":",
"top_line",
"+=",
"instruction",
".",
"top",
"if",
"bot_line",
"is",
"None",
":",
"lines",
".",
"append",
"(",
"top_line",
")",
"else",
":",
"if",
"vertically_compressed",
":",
"lines",
".",
"append",
"(",
"TextDrawing",
".",
"merge_lines",
"(",
"lines",
".",
"pop",
"(",
")",
",",
"top_line",
")",
")",
"else",
":",
"lines",
".",
"append",
"(",
"TextDrawing",
".",
"merge_lines",
"(",
"lines",
"[",
"-",
"1",
"]",
",",
"top_line",
",",
"icod",
"=",
"\"bot\"",
")",
")",
"# MID",
"mid_line",
"=",
"''",
"for",
"instruction",
"in",
"wire",
":",
"mid_line",
"+=",
"instruction",
".",
"mid",
"lines",
".",
"append",
"(",
"TextDrawing",
".",
"merge_lines",
"(",
"lines",
"[",
"-",
"1",
"]",
",",
"mid_line",
",",
"icod",
"=",
"\"bot\"",
")",
")",
"# BOT",
"bot_line",
"=",
"''",
"for",
"instruction",
"in",
"wire",
":",
"bot_line",
"+=",
"instruction",
".",
"bot",
"lines",
".",
"append",
"(",
"TextDrawing",
".",
"merge_lines",
"(",
"lines",
"[",
"-",
"1",
"]",
",",
"bot_line",
",",
"icod",
"=",
"\"bot\"",
")",
")",
"return",
"lines"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
TextDrawing.params_for_label
|
Get the params and format them to add them to a label. None if there
are no params of if the params are numpy.ndarrays.
|
qiskit/visualization/text.py
|
def params_for_label(instruction):
"""Get the params and format them to add them to a label. None if there
are no params of if the params are numpy.ndarrays."""
if not hasattr(instruction.op, 'params'):
return None
if all([isinstance(param, ndarray) for param in instruction.op.params]):
return None
ret = []
for param in instruction.op.params:
if isinstance(param, (sympy.Number, float)):
ret.append('%.5g' % param)
else:
ret.append('%s' % param)
return ret
|
def params_for_label(instruction):
"""Get the params and format them to add them to a label. None if there
are no params of if the params are numpy.ndarrays."""
if not hasattr(instruction.op, 'params'):
return None
if all([isinstance(param, ndarray) for param in instruction.op.params]):
return None
ret = []
for param in instruction.op.params:
if isinstance(param, (sympy.Number, float)):
ret.append('%.5g' % param)
else:
ret.append('%s' % param)
return ret
|
[
"Get",
"the",
"params",
"and",
"format",
"them",
"to",
"add",
"them",
"to",
"a",
"label",
".",
"None",
"if",
"there",
"are",
"no",
"params",
"of",
"if",
"the",
"params",
"are",
"numpy",
".",
"ndarrays",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L620-L635
|
[
"def",
"params_for_label",
"(",
"instruction",
")",
":",
"if",
"not",
"hasattr",
"(",
"instruction",
".",
"op",
",",
"'params'",
")",
":",
"return",
"None",
"if",
"all",
"(",
"[",
"isinstance",
"(",
"param",
",",
"ndarray",
")",
"for",
"param",
"in",
"instruction",
".",
"op",
".",
"params",
"]",
")",
":",
"return",
"None",
"ret",
"=",
"[",
"]",
"for",
"param",
"in",
"instruction",
".",
"op",
".",
"params",
":",
"if",
"isinstance",
"(",
"param",
",",
"(",
"sympy",
".",
"Number",
",",
"float",
")",
")",
":",
"ret",
".",
"append",
"(",
"'%.5g'",
"%",
"param",
")",
"else",
":",
"ret",
".",
"append",
"(",
"'%s'",
"%",
"param",
")",
"return",
"ret"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
TextDrawing.label_for_box
|
Creates the label for a box.
|
qiskit/visualization/text.py
|
def label_for_box(instruction):
""" Creates the label for a box."""
label = instruction.name.capitalize()
params = TextDrawing.params_for_label(instruction)
if params:
label += "(%s)" % ','.join(params)
return label
|
def label_for_box(instruction):
""" Creates the label for a box."""
label = instruction.name.capitalize()
params = TextDrawing.params_for_label(instruction)
if params:
label += "(%s)" % ','.join(params)
return label
|
[
"Creates",
"the",
"label",
"for",
"a",
"box",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L638-L644
|
[
"def",
"label_for_box",
"(",
"instruction",
")",
":",
"label",
"=",
"instruction",
".",
"name",
".",
"capitalize",
"(",
")",
"params",
"=",
"TextDrawing",
".",
"params_for_label",
"(",
"instruction",
")",
"if",
"params",
":",
"label",
"+=",
"\"(%s)\"",
"%",
"','",
".",
"join",
"(",
"params",
")",
"return",
"label"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
TextDrawing.merge_lines
|
Merges two lines (top and bot) in the way that the overlapping make senses.
Args:
top (str): the top line
bot (str): the bottom line
icod (top or bot): in case of doubt, which line should have priority? Default: "top".
Returns:
str: The merge of both lines.
|
qiskit/visualization/text.py
|
def merge_lines(top, bot, icod="top"):
"""
Merges two lines (top and bot) in the way that the overlapping make senses.
Args:
top (str): the top line
bot (str): the bottom line
icod (top or bot): in case of doubt, which line should have priority? Default: "top".
Returns:
str: The merge of both lines.
"""
ret = ""
for topc, botc in zip(top, bot):
if topc == botc:
ret += topc
elif topc in '┼╪' and botc == " ":
ret += "│"
elif topc == " ":
ret += botc
elif topc in '┬╥' and botc in " ║│" and icod == "top":
ret += topc
elif topc in '┬' and botc == " " and icod == "bot":
ret += '│'
elif topc in '╥' and botc == " " and icod == "bot":
ret += '║'
elif topc in '┬│' and botc == "═":
ret += '╪'
elif topc in '┬│' and botc == "─":
ret += '┼'
elif topc in '└┘║│░' and botc == " " and icod == "top":
ret += topc
elif topc in '─═' and botc == " " and icod == "top":
ret += topc
elif topc in '─═' and botc == " " and icod == "bot":
ret += botc
elif topc in "║╥" and botc in "═":
ret += "╬"
elif topc in "║╥" and botc in "─":
ret += "╫"
elif topc in '╫╬' and botc in " ":
ret += "║"
elif topc == '└' and botc == "┌":
ret += "├"
elif topc == '┘' and botc == "┐":
ret += "┤"
elif botc in "┐┌" and icod == 'top':
ret += "┬"
elif topc in "┘└" and botc in "─" and icod == 'top':
ret += "┴"
else:
ret += botc
return ret
|
def merge_lines(top, bot, icod="top"):
"""
Merges two lines (top and bot) in the way that the overlapping make senses.
Args:
top (str): the top line
bot (str): the bottom line
icod (top or bot): in case of doubt, which line should have priority? Default: "top".
Returns:
str: The merge of both lines.
"""
ret = ""
for topc, botc in zip(top, bot):
if topc == botc:
ret += topc
elif topc in '┼╪' and botc == " ":
ret += "│"
elif topc == " ":
ret += botc
elif topc in '┬╥' and botc in " ║│" and icod == "top":
ret += topc
elif topc in '┬' and botc == " " and icod == "bot":
ret += '│'
elif topc in '╥' and botc == " " and icod == "bot":
ret += '║'
elif topc in '┬│' and botc == "═":
ret += '╪'
elif topc in '┬│' and botc == "─":
ret += '┼'
elif topc in '└┘║│░' and botc == " " and icod == "top":
ret += topc
elif topc in '─═' and botc == " " and icod == "top":
ret += topc
elif topc in '─═' and botc == " " and icod == "bot":
ret += botc
elif topc in "║╥" and botc in "═":
ret += "╬"
elif topc in "║╥" and botc in "─":
ret += "╫"
elif topc in '╫╬' and botc in " ":
ret += "║"
elif topc == '└' and botc == "┌":
ret += "├"
elif topc == '┘' and botc == "┐":
ret += "┤"
elif botc in "┐┌" and icod == 'top':
ret += "┬"
elif topc in "┘└" and botc in "─" and icod == 'top':
ret += "┴"
else:
ret += botc
return ret
|
[
"Merges",
"two",
"lines",
"(",
"top",
"and",
"bot",
")",
"in",
"the",
"way",
"that",
"the",
"overlapping",
"make",
"senses",
".",
"Args",
":",
"top",
"(",
"str",
")",
":",
"the",
"top",
"line",
"bot",
"(",
"str",
")",
":",
"the",
"bottom",
"line",
"icod",
"(",
"top",
"or",
"bot",
")",
":",
"in",
"case",
"of",
"doubt",
"which",
"line",
"should",
"have",
"priority?",
"Default",
":",
"top",
".",
"Returns",
":",
"str",
":",
"The",
"merge",
"of",
"both",
"lines",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L647-L697
|
[
"def",
"merge_lines",
"(",
"top",
",",
"bot",
",",
"icod",
"=",
"\"top\"",
")",
":",
"ret",
"=",
"\"\"",
"for",
"topc",
",",
"botc",
"in",
"zip",
"(",
"top",
",",
"bot",
")",
":",
"if",
"topc",
"==",
"botc",
":",
"ret",
"+=",
"topc",
"elif",
"topc",
"in",
"'┼╪' and",
"bot",
" == ",
" \"",
"",
"",
"ret",
"+=",
"\"│\"",
"elif",
"topc",
"==",
"\" \"",
":",
"ret",
"+=",
"botc",
"elif",
"topc",
"in",
"'┬╥' and",
"bot",
" in ",
" ║",
"\" and ico",
" ==",
"\"top",
":",
"",
"",
"ret",
"+=",
"topc",
"elif",
"topc",
"in",
"'┬' a",
"d b",
"tc =",
" \"",
"\" a",
"d i",
"od =",
" \"",
"ot\":",
"",
"ret",
"+=",
"'│'",
"elif",
"topc",
"in",
"'╥' a",
"d b",
"tc =",
" \"",
"\" a",
"d i",
"od =",
" \"",
"ot\":",
"",
"ret",
"+=",
"'║'",
"elif",
"topc",
"in",
"'┬│' and",
"bot",
" == ",
"═\"",
"",
"",
"ret",
"+=",
"'╪'",
"elif",
"topc",
"in",
"'┬│' and",
"bot",
" == ",
"─\"",
"",
"",
"ret",
"+=",
"'┼'",
"elif",
"topc",
"in",
"'└┘║│░' and botc ",
"= \"",
"\" an",
" i",
"od ",
"= \"",
"op\":",
"",
"",
"",
"ret",
"+=",
"topc",
"elif",
"topc",
"in",
"'─═' and",
"bot",
" == ",
" \"",
"and",
"ico",
" == ",
"to",
"\":",
"",
"ret",
"+=",
"topc",
"elif",
"topc",
"in",
"'─═' and",
"bot",
" == ",
" \"",
"and",
"ico",
" == ",
"bo",
"\":",
"",
"ret",
"+=",
"botc",
"elif",
"topc",
"in",
"\"║╥\" and",
"bot",
" in ",
"═\"",
"",
"",
"ret",
"+=",
"\"╬\"",
"elif",
"topc",
"in",
"\"║╥\" and",
"bot",
" in ",
"─\"",
"",
"",
"ret",
"+=",
"\"╫\"",
"elif",
"topc",
"in",
"'╫╬' and",
"bot",
" in ",
" \"",
"",
"",
"ret",
"+=",
"\"║\"",
"elif",
"topc",
"==",
"'└' a",
"d b",
"tc =",
" \"",
"\":",
"",
"ret",
"+=",
"\"├\"",
"elif",
"topc",
"==",
"'┘' a",
"d b",
"tc =",
" \"",
"\":",
"",
"ret",
"+=",
"\"┤\"",
"elif",
"botc",
"in",
"\"┐┌\" and",
"ico",
" == ",
"to",
"':",
"",
"ret",
"+=",
"\"┬\"",
"elif",
"topc",
"in",
"\"┘└\" and",
"bot",
" in ",
"─\"",
"and i",
"od ",
"= 't",
"p'",
"",
"",
"ret",
"+=",
"\"┴\"",
"else",
":",
"ret",
"+=",
"botc",
"return",
"ret"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
TextDrawing.normalize_width
|
When the elements of the layer have different widths, sets the width to the max elements.
Args:
layer (list): A list of elements.
|
qiskit/visualization/text.py
|
def normalize_width(layer):
"""
When the elements of the layer have different widths, sets the width to the max elements.
Args:
layer (list): A list of elements.
"""
instructions = [instruction for instruction in filter(lambda x: x is not None, layer)]
longest = max([instruction.length for instruction in instructions])
for instruction in instructions:
instruction.layer_width = longest
|
def normalize_width(layer):
"""
When the elements of the layer have different widths, sets the width to the max elements.
Args:
layer (list): A list of elements.
"""
instructions = [instruction for instruction in filter(lambda x: x is not None, layer)]
longest = max([instruction.length for instruction in instructions])
for instruction in instructions:
instruction.layer_width = longest
|
[
"When",
"the",
"elements",
"of",
"the",
"layer",
"have",
"different",
"widths",
"sets",
"the",
"width",
"to",
"the",
"max",
"elements",
".",
"Args",
":",
"layer",
"(",
"list",
")",
":",
"A",
"list",
"of",
"elements",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L700-L709
|
[
"def",
"normalize_width",
"(",
"layer",
")",
":",
"instructions",
"=",
"[",
"instruction",
"for",
"instruction",
"in",
"filter",
"(",
"lambda",
"x",
":",
"x",
"is",
"not",
"None",
",",
"layer",
")",
"]",
"longest",
"=",
"max",
"(",
"[",
"instruction",
".",
"length",
"for",
"instruction",
"in",
"instructions",
"]",
")",
"for",
"instruction",
"in",
"instructions",
":",
"instruction",
".",
"layer_width",
"=",
"longest"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
TextDrawing._instruction_to_gate
|
Convert an instruction into its corresponding Gate object, and establish
any connections it introduces between qubits
|
qiskit/visualization/text.py
|
def _instruction_to_gate(self, instruction, layer):
""" Convert an instruction into its corresponding Gate object, and establish
any connections it introduces between qubits"""
current_cons = []
connection_label = None
# add in a gate that operates over multiple qubits
def add_connected_gate(instruction, gates, layer, current_cons):
for i, gate in enumerate(gates):
layer.set_qubit(instruction.qargs[i], gate)
actual_index = self.qregs.index(instruction.qargs[i])
current_cons.append((actual_index, gate))
if instruction.name == 'measure':
gate = MeasureFrom()
layer.set_qubit(instruction.qargs[0], gate)
layer.set_clbit(instruction.cargs[0], MeasureTo())
elif instruction.name in ['barrier', 'snapshot', 'save', 'load',
'noise']:
# barrier
if not self.plotbarriers:
return layer, current_cons, connection_label
for qubit in instruction.qargs:
layer.set_qubit(qubit, Barrier())
elif instruction.name == 'swap':
# swap
gates = [Ex() for _ in range(len(instruction.qargs))]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction.name == 'cswap':
# cswap
gates = [Bullet(), Ex(), Ex()]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction.name == 'reset':
layer.set_qubit(instruction.qargs[0], Reset())
elif instruction.condition is not None:
# conditional
cllabel = TextDrawing.label_for_conditional(instruction)
qulabel = TextDrawing.label_for_box(instruction)
layer.set_cl_multibox(instruction.condition[0], cllabel, top_connect='┴')
layer.set_qubit(instruction.qargs[0], BoxOnQuWire(qulabel, bot_connect='┬'))
elif instruction.name in ['cx', 'CX', 'ccx']:
# cx/ccx
gates = [Bullet() for _ in range(len(instruction.qargs) - 1)]
gates.append(BoxOnQuWire('X'))
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction.name == 'cy':
# cy
gates = [Bullet(), BoxOnQuWire('Y')]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction.name == 'cz':
# cz
gates = [Bullet(), Bullet()]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction.name == 'ch':
# ch
gates = [Bullet(), BoxOnQuWire('H')]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction.name == 'cu1':
# cu1
connection_label = TextDrawing.params_for_label(instruction)[0]
gates = [Bullet(), Bullet()]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction.name == 'rzz':
# rzz
connection_label = "zz(%s)" % TextDrawing.params_for_label(instruction)[0]
gates = [Bullet(), Bullet()]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction.name == 'cu3':
# cu3
params = TextDrawing.params_for_label(instruction)
gates = [Bullet(), BoxOnQuWire("U3(%s)" % ','.join(params))]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction.name == 'crz':
# crz
label = "Rz(%s)" % TextDrawing.params_for_label(instruction)[0]
gates = [Bullet(), BoxOnQuWire(label)]
add_connected_gate(instruction, gates, layer, current_cons)
elif len(instruction.qargs) == 1 and not instruction.cargs:
# unitary gate
layer.set_qubit(instruction.qargs[0],
BoxOnQuWire(TextDrawing.label_for_box(instruction)))
elif len(instruction.qargs) >= 2 and not instruction.cargs:
# multiple qubit gate
label = instruction.name
params = TextDrawing.params_for_label(instruction)
if params:
label += "(%s)" % ','.join(params)
layer.set_qu_multibox(instruction.qargs, label)
else:
raise VisualizationError(
"Text visualizer does not know how to handle this instruction", instruction)
# sort into the order they were declared in
# this ensures that connected boxes have lines in the right direction
current_cons.sort(key=lambda tup: tup[0])
current_cons = [g for q, g in current_cons]
return layer, current_cons, connection_label
|
def _instruction_to_gate(self, instruction, layer):
""" Convert an instruction into its corresponding Gate object, and establish
any connections it introduces between qubits"""
current_cons = []
connection_label = None
# add in a gate that operates over multiple qubits
def add_connected_gate(instruction, gates, layer, current_cons):
for i, gate in enumerate(gates):
layer.set_qubit(instruction.qargs[i], gate)
actual_index = self.qregs.index(instruction.qargs[i])
current_cons.append((actual_index, gate))
if instruction.name == 'measure':
gate = MeasureFrom()
layer.set_qubit(instruction.qargs[0], gate)
layer.set_clbit(instruction.cargs[0], MeasureTo())
elif instruction.name in ['barrier', 'snapshot', 'save', 'load',
'noise']:
# barrier
if not self.plotbarriers:
return layer, current_cons, connection_label
for qubit in instruction.qargs:
layer.set_qubit(qubit, Barrier())
elif instruction.name == 'swap':
# swap
gates = [Ex() for _ in range(len(instruction.qargs))]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction.name == 'cswap':
# cswap
gates = [Bullet(), Ex(), Ex()]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction.name == 'reset':
layer.set_qubit(instruction.qargs[0], Reset())
elif instruction.condition is not None:
# conditional
cllabel = TextDrawing.label_for_conditional(instruction)
qulabel = TextDrawing.label_for_box(instruction)
layer.set_cl_multibox(instruction.condition[0], cllabel, top_connect='┴')
layer.set_qubit(instruction.qargs[0], BoxOnQuWire(qulabel, bot_connect='┬'))
elif instruction.name in ['cx', 'CX', 'ccx']:
# cx/ccx
gates = [Bullet() for _ in range(len(instruction.qargs) - 1)]
gates.append(BoxOnQuWire('X'))
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction.name == 'cy':
# cy
gates = [Bullet(), BoxOnQuWire('Y')]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction.name == 'cz':
# cz
gates = [Bullet(), Bullet()]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction.name == 'ch':
# ch
gates = [Bullet(), BoxOnQuWire('H')]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction.name == 'cu1':
# cu1
connection_label = TextDrawing.params_for_label(instruction)[0]
gates = [Bullet(), Bullet()]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction.name == 'rzz':
# rzz
connection_label = "zz(%s)" % TextDrawing.params_for_label(instruction)[0]
gates = [Bullet(), Bullet()]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction.name == 'cu3':
# cu3
params = TextDrawing.params_for_label(instruction)
gates = [Bullet(), BoxOnQuWire("U3(%s)" % ','.join(params))]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction.name == 'crz':
# crz
label = "Rz(%s)" % TextDrawing.params_for_label(instruction)[0]
gates = [Bullet(), BoxOnQuWire(label)]
add_connected_gate(instruction, gates, layer, current_cons)
elif len(instruction.qargs) == 1 and not instruction.cargs:
# unitary gate
layer.set_qubit(instruction.qargs[0],
BoxOnQuWire(TextDrawing.label_for_box(instruction)))
elif len(instruction.qargs) >= 2 and not instruction.cargs:
# multiple qubit gate
label = instruction.name
params = TextDrawing.params_for_label(instruction)
if params:
label += "(%s)" % ','.join(params)
layer.set_qu_multibox(instruction.qargs, label)
else:
raise VisualizationError(
"Text visualizer does not know how to handle this instruction", instruction)
# sort into the order they were declared in
# this ensures that connected boxes have lines in the right direction
current_cons.sort(key=lambda tup: tup[0])
current_cons = [g for q, g in current_cons]
return layer, current_cons, connection_label
|
[
"Convert",
"an",
"instruction",
"into",
"its",
"corresponding",
"Gate",
"object",
"and",
"establish",
"any",
"connections",
"it",
"introduces",
"between",
"qubits"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L711-L828
|
[
"def",
"_instruction_to_gate",
"(",
"self",
",",
"instruction",
",",
"layer",
")",
":",
"current_cons",
"=",
"[",
"]",
"connection_label",
"=",
"None",
"# add in a gate that operates over multiple qubits",
"def",
"add_connected_gate",
"(",
"instruction",
",",
"gates",
",",
"layer",
",",
"current_cons",
")",
":",
"for",
"i",
",",
"gate",
"in",
"enumerate",
"(",
"gates",
")",
":",
"layer",
".",
"set_qubit",
"(",
"instruction",
".",
"qargs",
"[",
"i",
"]",
",",
"gate",
")",
"actual_index",
"=",
"self",
".",
"qregs",
".",
"index",
"(",
"instruction",
".",
"qargs",
"[",
"i",
"]",
")",
"current_cons",
".",
"append",
"(",
"(",
"actual_index",
",",
"gate",
")",
")",
"if",
"instruction",
".",
"name",
"==",
"'measure'",
":",
"gate",
"=",
"MeasureFrom",
"(",
")",
"layer",
".",
"set_qubit",
"(",
"instruction",
".",
"qargs",
"[",
"0",
"]",
",",
"gate",
")",
"layer",
".",
"set_clbit",
"(",
"instruction",
".",
"cargs",
"[",
"0",
"]",
",",
"MeasureTo",
"(",
")",
")",
"elif",
"instruction",
".",
"name",
"in",
"[",
"'barrier'",
",",
"'snapshot'",
",",
"'save'",
",",
"'load'",
",",
"'noise'",
"]",
":",
"# barrier",
"if",
"not",
"self",
".",
"plotbarriers",
":",
"return",
"layer",
",",
"current_cons",
",",
"connection_label",
"for",
"qubit",
"in",
"instruction",
".",
"qargs",
":",
"layer",
".",
"set_qubit",
"(",
"qubit",
",",
"Barrier",
"(",
")",
")",
"elif",
"instruction",
".",
"name",
"==",
"'swap'",
":",
"# swap",
"gates",
"=",
"[",
"Ex",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"instruction",
".",
"qargs",
")",
")",
"]",
"add_connected_gate",
"(",
"instruction",
",",
"gates",
",",
"layer",
",",
"current_cons",
")",
"elif",
"instruction",
".",
"name",
"==",
"'cswap'",
":",
"# cswap",
"gates",
"=",
"[",
"Bullet",
"(",
")",
",",
"Ex",
"(",
")",
",",
"Ex",
"(",
")",
"]",
"add_connected_gate",
"(",
"instruction",
",",
"gates",
",",
"layer",
",",
"current_cons",
")",
"elif",
"instruction",
".",
"name",
"==",
"'reset'",
":",
"layer",
".",
"set_qubit",
"(",
"instruction",
".",
"qargs",
"[",
"0",
"]",
",",
"Reset",
"(",
")",
")",
"elif",
"instruction",
".",
"condition",
"is",
"not",
"None",
":",
"# conditional",
"cllabel",
"=",
"TextDrawing",
".",
"label_for_conditional",
"(",
"instruction",
")",
"qulabel",
"=",
"TextDrawing",
".",
"label_for_box",
"(",
"instruction",
")",
"layer",
".",
"set_cl_multibox",
"(",
"instruction",
".",
"condition",
"[",
"0",
"]",
",",
"cllabel",
",",
"top_connect",
"=",
"'┴')",
"",
"layer",
".",
"set_qubit",
"(",
"instruction",
".",
"qargs",
"[",
"0",
"]",
",",
"BoxOnQuWire",
"(",
"qulabel",
",",
"bot_connect",
"=",
"'┬'))",
"",
"",
"elif",
"instruction",
".",
"name",
"in",
"[",
"'cx'",
",",
"'CX'",
",",
"'ccx'",
"]",
":",
"# cx/ccx",
"gates",
"=",
"[",
"Bullet",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"instruction",
".",
"qargs",
")",
"-",
"1",
")",
"]",
"gates",
".",
"append",
"(",
"BoxOnQuWire",
"(",
"'X'",
")",
")",
"add_connected_gate",
"(",
"instruction",
",",
"gates",
",",
"layer",
",",
"current_cons",
")",
"elif",
"instruction",
".",
"name",
"==",
"'cy'",
":",
"# cy",
"gates",
"=",
"[",
"Bullet",
"(",
")",
",",
"BoxOnQuWire",
"(",
"'Y'",
")",
"]",
"add_connected_gate",
"(",
"instruction",
",",
"gates",
",",
"layer",
",",
"current_cons",
")",
"elif",
"instruction",
".",
"name",
"==",
"'cz'",
":",
"# cz",
"gates",
"=",
"[",
"Bullet",
"(",
")",
",",
"Bullet",
"(",
")",
"]",
"add_connected_gate",
"(",
"instruction",
",",
"gates",
",",
"layer",
",",
"current_cons",
")",
"elif",
"instruction",
".",
"name",
"==",
"'ch'",
":",
"# ch",
"gates",
"=",
"[",
"Bullet",
"(",
")",
",",
"BoxOnQuWire",
"(",
"'H'",
")",
"]",
"add_connected_gate",
"(",
"instruction",
",",
"gates",
",",
"layer",
",",
"current_cons",
")",
"elif",
"instruction",
".",
"name",
"==",
"'cu1'",
":",
"# cu1",
"connection_label",
"=",
"TextDrawing",
".",
"params_for_label",
"(",
"instruction",
")",
"[",
"0",
"]",
"gates",
"=",
"[",
"Bullet",
"(",
")",
",",
"Bullet",
"(",
")",
"]",
"add_connected_gate",
"(",
"instruction",
",",
"gates",
",",
"layer",
",",
"current_cons",
")",
"elif",
"instruction",
".",
"name",
"==",
"'rzz'",
":",
"# rzz",
"connection_label",
"=",
"\"zz(%s)\"",
"%",
"TextDrawing",
".",
"params_for_label",
"(",
"instruction",
")",
"[",
"0",
"]",
"gates",
"=",
"[",
"Bullet",
"(",
")",
",",
"Bullet",
"(",
")",
"]",
"add_connected_gate",
"(",
"instruction",
",",
"gates",
",",
"layer",
",",
"current_cons",
")",
"elif",
"instruction",
".",
"name",
"==",
"'cu3'",
":",
"# cu3",
"params",
"=",
"TextDrawing",
".",
"params_for_label",
"(",
"instruction",
")",
"gates",
"=",
"[",
"Bullet",
"(",
")",
",",
"BoxOnQuWire",
"(",
"\"U3(%s)\"",
"%",
"','",
".",
"join",
"(",
"params",
")",
")",
"]",
"add_connected_gate",
"(",
"instruction",
",",
"gates",
",",
"layer",
",",
"current_cons",
")",
"elif",
"instruction",
".",
"name",
"==",
"'crz'",
":",
"# crz",
"label",
"=",
"\"Rz(%s)\"",
"%",
"TextDrawing",
".",
"params_for_label",
"(",
"instruction",
")",
"[",
"0",
"]",
"gates",
"=",
"[",
"Bullet",
"(",
")",
",",
"BoxOnQuWire",
"(",
"label",
")",
"]",
"add_connected_gate",
"(",
"instruction",
",",
"gates",
",",
"layer",
",",
"current_cons",
")",
"elif",
"len",
"(",
"instruction",
".",
"qargs",
")",
"==",
"1",
"and",
"not",
"instruction",
".",
"cargs",
":",
"# unitary gate",
"layer",
".",
"set_qubit",
"(",
"instruction",
".",
"qargs",
"[",
"0",
"]",
",",
"BoxOnQuWire",
"(",
"TextDrawing",
".",
"label_for_box",
"(",
"instruction",
")",
")",
")",
"elif",
"len",
"(",
"instruction",
".",
"qargs",
")",
">=",
"2",
"and",
"not",
"instruction",
".",
"cargs",
":",
"# multiple qubit gate",
"label",
"=",
"instruction",
".",
"name",
"params",
"=",
"TextDrawing",
".",
"params_for_label",
"(",
"instruction",
")",
"if",
"params",
":",
"label",
"+=",
"\"(%s)\"",
"%",
"','",
".",
"join",
"(",
"params",
")",
"layer",
".",
"set_qu_multibox",
"(",
"instruction",
".",
"qargs",
",",
"label",
")",
"else",
":",
"raise",
"VisualizationError",
"(",
"\"Text visualizer does not know how to handle this instruction\"",
",",
"instruction",
")",
"# sort into the order they were declared in",
"# this ensures that connected boxes have lines in the right direction",
"current_cons",
".",
"sort",
"(",
"key",
"=",
"lambda",
"tup",
":",
"tup",
"[",
"0",
"]",
")",
"current_cons",
"=",
"[",
"g",
"for",
"q",
",",
"g",
"in",
"current_cons",
"]",
"return",
"layer",
",",
"current_cons",
",",
"connection_label"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
TextDrawing.build_layers
|
Constructs layers.
Returns:
list: List of DrawElements.
Raises:
VisualizationError: When the drawing is, for some reason, impossible to be drawn.
|
qiskit/visualization/text.py
|
def build_layers(self):
"""
Constructs layers.
Returns:
list: List of DrawElements.
Raises:
VisualizationError: When the drawing is, for some reason, impossible to be drawn.
"""
wire_names = self.wire_names(with_initial_value=True)
if not wire_names:
return []
layers = [InputWire.fillup_layer(wire_names)]
for instruction_layer in self.instructions:
layer = Layer(self.qregs, self.cregs)
for instruction in instruction_layer:
layer, current_connections, connection_label = \
self._instruction_to_gate(instruction, layer)
layer.connections.append((connection_label, current_connections))
layer.connect_with("│")
layers.append(layer.full_layer)
return layers
|
def build_layers(self):
"""
Constructs layers.
Returns:
list: List of DrawElements.
Raises:
VisualizationError: When the drawing is, for some reason, impossible to be drawn.
"""
wire_names = self.wire_names(with_initial_value=True)
if not wire_names:
return []
layers = [InputWire.fillup_layer(wire_names)]
for instruction_layer in self.instructions:
layer = Layer(self.qregs, self.cregs)
for instruction in instruction_layer:
layer, current_connections, connection_label = \
self._instruction_to_gate(instruction, layer)
layer.connections.append((connection_label, current_connections))
layer.connect_with("│")
layers.append(layer.full_layer)
return layers
|
[
"Constructs",
"layers",
".",
"Returns",
":",
"list",
":",
"List",
"of",
"DrawElements",
".",
"Raises",
":",
"VisualizationError",
":",
"When",
"the",
"drawing",
"is",
"for",
"some",
"reason",
"impossible",
"to",
"be",
"drawn",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L830-L855
|
[
"def",
"build_layers",
"(",
"self",
")",
":",
"wire_names",
"=",
"self",
".",
"wire_names",
"(",
"with_initial_value",
"=",
"True",
")",
"if",
"not",
"wire_names",
":",
"return",
"[",
"]",
"layers",
"=",
"[",
"InputWire",
".",
"fillup_layer",
"(",
"wire_names",
")",
"]",
"for",
"instruction_layer",
"in",
"self",
".",
"instructions",
":",
"layer",
"=",
"Layer",
"(",
"self",
".",
"qregs",
",",
"self",
".",
"cregs",
")",
"for",
"instruction",
"in",
"instruction_layer",
":",
"layer",
",",
"current_connections",
",",
"connection_label",
"=",
"self",
".",
"_instruction_to_gate",
"(",
"instruction",
",",
"layer",
")",
"layer",
".",
"connections",
".",
"append",
"(",
"(",
"connection_label",
",",
"current_connections",
")",
")",
"layer",
".",
"connect_with",
"(",
"\"│\")",
"",
"layers",
".",
"append",
"(",
"layer",
".",
"full_layer",
")",
"return",
"layers"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Layer.set_qubit
|
Sets the qubit to the element
Args:
qubit (qbit): Element of self.qregs.
element (DrawElement): Element to set in the qubit
|
qiskit/visualization/text.py
|
def set_qubit(self, qubit, element):
"""
Sets the qubit to the element
Args:
qubit (qbit): Element of self.qregs.
element (DrawElement): Element to set in the qubit
"""
self.qubit_layer[self.qregs.index(qubit)] = element
|
def set_qubit(self, qubit, element):
"""
Sets the qubit to the element
Args:
qubit (qbit): Element of self.qregs.
element (DrawElement): Element to set in the qubit
"""
self.qubit_layer[self.qregs.index(qubit)] = element
|
[
"Sets",
"the",
"qubit",
"to",
"the",
"element",
"Args",
":",
"qubit",
"(",
"qbit",
")",
":",
"Element",
"of",
"self",
".",
"qregs",
".",
"element",
"(",
"DrawElement",
")",
":",
"Element",
"to",
"set",
"in",
"the",
"qubit"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L877-L884
|
[
"def",
"set_qubit",
"(",
"self",
",",
"qubit",
",",
"element",
")",
":",
"self",
".",
"qubit_layer",
"[",
"self",
".",
"qregs",
".",
"index",
"(",
"qubit",
")",
"]",
"=",
"element"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Layer.set_clbit
|
Sets the clbit to the element
Args:
clbit (cbit): Element of self.cregs.
element (DrawElement): Element to set in the clbit
|
qiskit/visualization/text.py
|
def set_clbit(self, clbit, element):
"""
Sets the clbit to the element
Args:
clbit (cbit): Element of self.cregs.
element (DrawElement): Element to set in the clbit
"""
self.clbit_layer[self.cregs.index(clbit)] = element
|
def set_clbit(self, clbit, element):
"""
Sets the clbit to the element
Args:
clbit (cbit): Element of self.cregs.
element (DrawElement): Element to set in the clbit
"""
self.clbit_layer[self.cregs.index(clbit)] = element
|
[
"Sets",
"the",
"clbit",
"to",
"the",
"element",
"Args",
":",
"clbit",
"(",
"cbit",
")",
":",
"Element",
"of",
"self",
".",
"cregs",
".",
"element",
"(",
"DrawElement",
")",
":",
"Element",
"to",
"set",
"in",
"the",
"clbit"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L886-L893
|
[
"def",
"set_clbit",
"(",
"self",
",",
"clbit",
",",
"element",
")",
":",
"self",
".",
"clbit_layer",
"[",
"self",
".",
"cregs",
".",
"index",
"(",
"clbit",
")",
"]",
"=",
"element"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Layer.set_cl_multibox
|
Sets the multi clbit box.
Args:
creg (string): The affected classical register.
label (string): The label for the multi clbit box.
top_connect (char): The char to connect the box on the top.
|
qiskit/visualization/text.py
|
def set_cl_multibox(self, creg, label, top_connect='┴'):
"""
Sets the multi clbit box.
Args:
creg (string): The affected classical register.
label (string): The label for the multi clbit box.
top_connect (char): The char to connect the box on the top.
"""
clbit = [bit for bit in self.cregs if bit[0] == creg]
self._set_multibox("cl", clbit, label, top_connect=top_connect)
|
def set_cl_multibox(self, creg, label, top_connect='┴'):
"""
Sets the multi clbit box.
Args:
creg (string): The affected classical register.
label (string): The label for the multi clbit box.
top_connect (char): The char to connect the box on the top.
"""
clbit = [bit for bit in self.cregs if bit[0] == creg]
self._set_multibox("cl", clbit, label, top_connect=top_connect)
|
[
"Sets",
"the",
"multi",
"clbit",
"box",
".",
"Args",
":",
"creg",
"(",
"string",
")",
":",
"The",
"affected",
"classical",
"register",
".",
"label",
"(",
"string",
")",
":",
"The",
"label",
"for",
"the",
"multi",
"clbit",
"box",
".",
"top_connect",
"(",
"char",
")",
":",
"The",
"char",
"to",
"connect",
"the",
"box",
"on",
"the",
"top",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L935-L944
|
[
"def",
"set_cl_multibox",
"(",
"self",
",",
"creg",
",",
"label",
",",
"top_connect",
"=",
"'┴'):",
"",
"",
"clbit",
"=",
"[",
"bit",
"for",
"bit",
"in",
"self",
".",
"cregs",
"if",
"bit",
"[",
"0",
"]",
"==",
"creg",
"]",
"self",
".",
"_set_multibox",
"(",
"\"cl\"",
",",
"clbit",
",",
"label",
",",
"top_connect",
"=",
"top_connect",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Layer.connect_with
|
Connects the elements in the layer using wire_char.
Args:
wire_char (char): For example '║' or '│'.
|
qiskit/visualization/text.py
|
def connect_with(self, wire_char):
"""
Connects the elements in the layer using wire_char.
Args:
wire_char (char): For example '║' or '│'.
"""
if len([qbit for qbit in self.qubit_layer if qbit is not None]) == 1:
# Nothing to connect
return
for label, affected_bits in self.connections:
if not affected_bits:
continue
affected_bits[0].connect(wire_char, ['bot'])
for affected_bit in affected_bits[1:-1]:
affected_bit.connect(wire_char, ['bot', 'top'])
affected_bits[-1].connect(wire_char, ['top'], label)
if label:
for affected_bit in affected_bits:
affected_bit.right_fill = len(label) + len(affected_bit.mid)
|
def connect_with(self, wire_char):
"""
Connects the elements in the layer using wire_char.
Args:
wire_char (char): For example '║' or '│'.
"""
if len([qbit for qbit in self.qubit_layer if qbit is not None]) == 1:
# Nothing to connect
return
for label, affected_bits in self.connections:
if not affected_bits:
continue
affected_bits[0].connect(wire_char, ['bot'])
for affected_bit in affected_bits[1:-1]:
affected_bit.connect(wire_char, ['bot', 'top'])
affected_bits[-1].connect(wire_char, ['top'], label)
if label:
for affected_bit in affected_bits:
affected_bit.right_fill = len(label) + len(affected_bit.mid)
|
[
"Connects",
"the",
"elements",
"in",
"the",
"layer",
"using",
"wire_char",
".",
"Args",
":",
"wire_char",
"(",
"char",
")",
":",
"For",
"example",
"║",
"or",
"│",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L955-L979
|
[
"def",
"connect_with",
"(",
"self",
",",
"wire_char",
")",
":",
"if",
"len",
"(",
"[",
"qbit",
"for",
"qbit",
"in",
"self",
".",
"qubit_layer",
"if",
"qbit",
"is",
"not",
"None",
"]",
")",
"==",
"1",
":",
"# Nothing to connect",
"return",
"for",
"label",
",",
"affected_bits",
"in",
"self",
".",
"connections",
":",
"if",
"not",
"affected_bits",
":",
"continue",
"affected_bits",
"[",
"0",
"]",
".",
"connect",
"(",
"wire_char",
",",
"[",
"'bot'",
"]",
")",
"for",
"affected_bit",
"in",
"affected_bits",
"[",
"1",
":",
"-",
"1",
"]",
":",
"affected_bit",
".",
"connect",
"(",
"wire_char",
",",
"[",
"'bot'",
",",
"'top'",
"]",
")",
"affected_bits",
"[",
"-",
"1",
"]",
".",
"connect",
"(",
"wire_char",
",",
"[",
"'top'",
"]",
",",
"label",
")",
"if",
"label",
":",
"for",
"affected_bit",
"in",
"affected_bits",
":",
"affected_bit",
".",
"right_fill",
"=",
"len",
"(",
"label",
")",
"+",
"len",
"(",
"affected_bit",
".",
"mid",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Id.latex
|
Return the correspond math mode latex string.
|
qiskit/qasm/node/id.py
|
def latex(self, prec=15, nested_scope=None):
"""Return the correspond math mode latex string."""
if not nested_scope:
return "\textrm{" + self.name + "}"
else:
if self.name not in nested_scope[-1]:
raise NodeException("Expected local parameter name: ",
"name=%s, " % self.name,
"line=%s, " % self.line,
"file=%s" % self.file)
else:
return nested_scope[-1][self.name].latex(prec,
nested_scope[0:-1])
|
def latex(self, prec=15, nested_scope=None):
"""Return the correspond math mode latex string."""
if not nested_scope:
return "\textrm{" + self.name + "}"
else:
if self.name not in nested_scope[-1]:
raise NodeException("Expected local parameter name: ",
"name=%s, " % self.name,
"line=%s, " % self.line,
"file=%s" % self.file)
else:
return nested_scope[-1][self.name].latex(prec,
nested_scope[0:-1])
|
[
"Return",
"the",
"correspond",
"math",
"mode",
"latex",
"string",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/node/id.py#L42-L54
|
[
"def",
"latex",
"(",
"self",
",",
"prec",
"=",
"15",
",",
"nested_scope",
"=",
"None",
")",
":",
"if",
"not",
"nested_scope",
":",
"return",
"\"\\textrm{\"",
"+",
"self",
".",
"name",
"+",
"\"}\"",
"else",
":",
"if",
"self",
".",
"name",
"not",
"in",
"nested_scope",
"[",
"-",
"1",
"]",
":",
"raise",
"NodeException",
"(",
"\"Expected local parameter name: \"",
",",
"\"name=%s, \"",
"%",
"self",
".",
"name",
",",
"\"line=%s, \"",
"%",
"self",
".",
"line",
",",
"\"file=%s\"",
"%",
"self",
".",
"file",
")",
"else",
":",
"return",
"nested_scope",
"[",
"-",
"1",
"]",
"[",
"self",
".",
"name",
"]",
".",
"latex",
"(",
"prec",
",",
"nested_scope",
"[",
"0",
":",
"-",
"1",
"]",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Id.sym
|
Return the correspond symbolic number.
|
qiskit/qasm/node/id.py
|
def sym(self, nested_scope=None):
"""Return the correspond symbolic number."""
if not nested_scope or self.name not in nested_scope[-1]:
raise NodeException("Expected local parameter name: ",
"name=%s, line=%s, file=%s" % (
self.name, self.line, self.file))
else:
return nested_scope[-1][self.name].sym(nested_scope[0:-1])
|
def sym(self, nested_scope=None):
"""Return the correspond symbolic number."""
if not nested_scope or self.name not in nested_scope[-1]:
raise NodeException("Expected local parameter name: ",
"name=%s, line=%s, file=%s" % (
self.name, self.line, self.file))
else:
return nested_scope[-1][self.name].sym(nested_scope[0:-1])
|
[
"Return",
"the",
"correspond",
"symbolic",
"number",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/node/id.py#L56-L63
|
[
"def",
"sym",
"(",
"self",
",",
"nested_scope",
"=",
"None",
")",
":",
"if",
"not",
"nested_scope",
"or",
"self",
".",
"name",
"not",
"in",
"nested_scope",
"[",
"-",
"1",
"]",
":",
"raise",
"NodeException",
"(",
"\"Expected local parameter name: \"",
",",
"\"name=%s, line=%s, file=%s\"",
"%",
"(",
"self",
".",
"name",
",",
"self",
".",
"line",
",",
"self",
".",
"file",
")",
")",
"else",
":",
"return",
"nested_scope",
"[",
"-",
"1",
"]",
"[",
"self",
".",
"name",
"]",
".",
"sym",
"(",
"nested_scope",
"[",
"0",
":",
"-",
"1",
"]",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Id.real
|
Return the correspond floating point number.
|
qiskit/qasm/node/id.py
|
def real(self, nested_scope=None):
"""Return the correspond floating point number."""
if not nested_scope or self.name not in nested_scope[-1]:
raise NodeException("Expected local parameter name: ",
"name=%s, line=%s, file=%s" % (
self.name, self.line, self.file))
else:
return nested_scope[-1][self.name].real(nested_scope[0:-1])
|
def real(self, nested_scope=None):
"""Return the correspond floating point number."""
if not nested_scope or self.name not in nested_scope[-1]:
raise NodeException("Expected local parameter name: ",
"name=%s, line=%s, file=%s" % (
self.name, self.line, self.file))
else:
return nested_scope[-1][self.name].real(nested_scope[0:-1])
|
[
"Return",
"the",
"correspond",
"floating",
"point",
"number",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/node/id.py#L65-L72
|
[
"def",
"real",
"(",
"self",
",",
"nested_scope",
"=",
"None",
")",
":",
"if",
"not",
"nested_scope",
"or",
"self",
".",
"name",
"not",
"in",
"nested_scope",
"[",
"-",
"1",
"]",
":",
"raise",
"NodeException",
"(",
"\"Expected local parameter name: \"",
",",
"\"name=%s, line=%s, file=%s\"",
"%",
"(",
"self",
".",
"name",
",",
"self",
".",
"line",
",",
"self",
".",
"file",
")",
")",
"else",
":",
"return",
"nested_scope",
"[",
"-",
"1",
"]",
"[",
"self",
".",
"name",
"]",
".",
"real",
"(",
"nested_scope",
"[",
"0",
":",
"-",
"1",
"]",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
compile
|
Compile a list of circuits into a qobj.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend): a backend to compile for
config (dict): dictionary of parameters (e.g. noise) used by runner
basis_gates (list[str]): list of basis gates names supported by the
target. Default: ['u1','u2','u3','cx','id']
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
shots (int): number of repetitions of each circuit, for sampling
max_credits (int): maximum credits to use
seed (int): random seed for simulators
seed_mapper (int): random seed for swapper mapper
qobj_id (int): identifier for the generated qobj
pass_manager (PassManager): a pass manger for the transpiler pipeline
memory (bool): if True, per-shot measurement bitstrings are returned as well
Returns:
Qobj: the qobj to be run on the backends
Raises:
QiskitError: if the desired options are not supported by backend
|
qiskit/tools/compiler.py
|
def compile(circuits, backend,
config=None, basis_gates=None, coupling_map=None, initial_layout=None,
shots=1024, max_credits=10, seed=None, qobj_id=None, seed_mapper=None,
pass_manager=None, memory=False):
"""Compile a list of circuits into a qobj.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend): a backend to compile for
config (dict): dictionary of parameters (e.g. noise) used by runner
basis_gates (list[str]): list of basis gates names supported by the
target. Default: ['u1','u2','u3','cx','id']
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
shots (int): number of repetitions of each circuit, for sampling
max_credits (int): maximum credits to use
seed (int): random seed for simulators
seed_mapper (int): random seed for swapper mapper
qobj_id (int): identifier for the generated qobj
pass_manager (PassManager): a pass manger for the transpiler pipeline
memory (bool): if True, per-shot measurement bitstrings are returned as well
Returns:
Qobj: the qobj to be run on the backends
Raises:
QiskitError: if the desired options are not supported by backend
"""
warnings.warn('qiskit.compile() is deprecated and will be removed in Qiskit Terra 0.9. '
'Please use qiskit.compiler.transpile() to transform circuits '
'and qiskit.compiler.assemble() to produce a runnable qobj.',
DeprecationWarning)
new_circuits = transpile(circuits,
basis_gates=basis_gates,
coupling_map=coupling_map,
initial_layout=initial_layout,
seed_transpiler=seed_mapper,
backend=backend,
pass_manager=pass_manager)
qobj = assemble(new_circuits,
qobj_header=None,
shots=shots,
max_credits=max_credits,
seed_simulator=seed,
memory=memory,
qobj_id=qobj_id,
config=config) # deprecated
return qobj
|
def compile(circuits, backend,
config=None, basis_gates=None, coupling_map=None, initial_layout=None,
shots=1024, max_credits=10, seed=None, qobj_id=None, seed_mapper=None,
pass_manager=None, memory=False):
"""Compile a list of circuits into a qobj.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend): a backend to compile for
config (dict): dictionary of parameters (e.g. noise) used by runner
basis_gates (list[str]): list of basis gates names supported by the
target. Default: ['u1','u2','u3','cx','id']
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
shots (int): number of repetitions of each circuit, for sampling
max_credits (int): maximum credits to use
seed (int): random seed for simulators
seed_mapper (int): random seed for swapper mapper
qobj_id (int): identifier for the generated qobj
pass_manager (PassManager): a pass manger for the transpiler pipeline
memory (bool): if True, per-shot measurement bitstrings are returned as well
Returns:
Qobj: the qobj to be run on the backends
Raises:
QiskitError: if the desired options are not supported by backend
"""
warnings.warn('qiskit.compile() is deprecated and will be removed in Qiskit Terra 0.9. '
'Please use qiskit.compiler.transpile() to transform circuits '
'and qiskit.compiler.assemble() to produce a runnable qobj.',
DeprecationWarning)
new_circuits = transpile(circuits,
basis_gates=basis_gates,
coupling_map=coupling_map,
initial_layout=initial_layout,
seed_transpiler=seed_mapper,
backend=backend,
pass_manager=pass_manager)
qobj = assemble(new_circuits,
qobj_header=None,
shots=shots,
max_credits=max_credits,
seed_simulator=seed,
memory=memory,
qobj_id=qobj_id,
config=config) # deprecated
return qobj
|
[
"Compile",
"a",
"list",
"of",
"circuits",
"into",
"a",
"qobj",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/compiler.py#L19-L69
|
[
"def",
"compile",
"(",
"circuits",
",",
"backend",
",",
"config",
"=",
"None",
",",
"basis_gates",
"=",
"None",
",",
"coupling_map",
"=",
"None",
",",
"initial_layout",
"=",
"None",
",",
"shots",
"=",
"1024",
",",
"max_credits",
"=",
"10",
",",
"seed",
"=",
"None",
",",
"qobj_id",
"=",
"None",
",",
"seed_mapper",
"=",
"None",
",",
"pass_manager",
"=",
"None",
",",
"memory",
"=",
"False",
")",
":",
"warnings",
".",
"warn",
"(",
"'qiskit.compile() is deprecated and will be removed in Qiskit Terra 0.9. '",
"'Please use qiskit.compiler.transpile() to transform circuits '",
"'and qiskit.compiler.assemble() to produce a runnable qobj.'",
",",
"DeprecationWarning",
")",
"new_circuits",
"=",
"transpile",
"(",
"circuits",
",",
"basis_gates",
"=",
"basis_gates",
",",
"coupling_map",
"=",
"coupling_map",
",",
"initial_layout",
"=",
"initial_layout",
",",
"seed_transpiler",
"=",
"seed_mapper",
",",
"backend",
"=",
"backend",
",",
"pass_manager",
"=",
"pass_manager",
")",
"qobj",
"=",
"assemble",
"(",
"new_circuits",
",",
"qobj_header",
"=",
"None",
",",
"shots",
"=",
"shots",
",",
"max_credits",
"=",
"max_credits",
",",
"seed_simulator",
"=",
"seed",
",",
"memory",
"=",
"memory",
",",
"qobj_id",
"=",
"qobj_id",
",",
"config",
"=",
"config",
")",
"# deprecated",
"return",
"qobj"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_filter_deprecation_warnings
|
Apply filters to deprecation warnings.
Force the `DeprecationWarning` warnings to be displayed for the qiskit
module, overriding the system configuration as they are ignored by default
[1] for end-users. Additionally, silence the `ChangedInMarshmallow3Warning`
messages.
TODO: on Python 3.7, this might not be needed due to PEP-0565 [2].
[1] https://docs.python.org/3/library/warnings.html#default-warning-filters
[2] https://www.python.org/dev/peps/pep-0565/
|
qiskit/util.py
|
def _filter_deprecation_warnings():
"""Apply filters to deprecation warnings.
Force the `DeprecationWarning` warnings to be displayed for the qiskit
module, overriding the system configuration as they are ignored by default
[1] for end-users. Additionally, silence the `ChangedInMarshmallow3Warning`
messages.
TODO: on Python 3.7, this might not be needed due to PEP-0565 [2].
[1] https://docs.python.org/3/library/warnings.html#default-warning-filters
[2] https://www.python.org/dev/peps/pep-0565/
"""
deprecation_filter = ('always', None, DeprecationWarning,
re.compile(r'^qiskit\.*', re.UNICODE), 0)
# Instead of using warnings.simple_filter() directly, the internal
# _add_filter() function is used for being able to match against the
# module.
try:
warnings._add_filter(*deprecation_filter, append=False)
except AttributeError:
# ._add_filter is internal and not available in some Python versions.
pass
# Add a filter for ignoring ChangedInMarshmallow3Warning, as we depend on
# marhsmallow 2 explicitly. 2.17.0 introduced new deprecation warnings that
# are useful for eventually migrating, but too verbose for our purposes.
warnings.simplefilter('ignore', category=ChangedInMarshmallow3Warning)
|
def _filter_deprecation_warnings():
"""Apply filters to deprecation warnings.
Force the `DeprecationWarning` warnings to be displayed for the qiskit
module, overriding the system configuration as they are ignored by default
[1] for end-users. Additionally, silence the `ChangedInMarshmallow3Warning`
messages.
TODO: on Python 3.7, this might not be needed due to PEP-0565 [2].
[1] https://docs.python.org/3/library/warnings.html#default-warning-filters
[2] https://www.python.org/dev/peps/pep-0565/
"""
deprecation_filter = ('always', None, DeprecationWarning,
re.compile(r'^qiskit\.*', re.UNICODE), 0)
# Instead of using warnings.simple_filter() directly, the internal
# _add_filter() function is used for being able to match against the
# module.
try:
warnings._add_filter(*deprecation_filter, append=False)
except AttributeError:
# ._add_filter is internal and not available in some Python versions.
pass
# Add a filter for ignoring ChangedInMarshmallow3Warning, as we depend on
# marhsmallow 2 explicitly. 2.17.0 introduced new deprecation warnings that
# are useful for eventually migrating, but too verbose for our purposes.
warnings.simplefilter('ignore', category=ChangedInMarshmallow3Warning)
|
[
"Apply",
"filters",
"to",
"deprecation",
"warnings",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/util.py#L28-L56
|
[
"def",
"_filter_deprecation_warnings",
"(",
")",
":",
"deprecation_filter",
"=",
"(",
"'always'",
",",
"None",
",",
"DeprecationWarning",
",",
"re",
".",
"compile",
"(",
"r'^qiskit\\.*'",
",",
"re",
".",
"UNICODE",
")",
",",
"0",
")",
"# Instead of using warnings.simple_filter() directly, the internal",
"# _add_filter() function is used for being able to match against the",
"# module.",
"try",
":",
"warnings",
".",
"_add_filter",
"(",
"*",
"deprecation_filter",
",",
"append",
"=",
"False",
")",
"except",
"AttributeError",
":",
"# ._add_filter is internal and not available in some Python versions.",
"pass",
"# Add a filter for ignoring ChangedInMarshmallow3Warning, as we depend on",
"# marhsmallow 2 explicitly. 2.17.0 introduced new deprecation warnings that",
"# are useful for eventually migrating, but too verbose for our purposes.",
"warnings",
".",
"simplefilter",
"(",
"'ignore'",
",",
"category",
"=",
"ChangedInMarshmallow3Warning",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
local_hardware_info
|
Basic hardware information about the local machine.
Gives actual number of CPU's in the machine, even when hyperthreading is
turned on. CPU count defaults to 1 when true count can't be determined.
Returns:
dict: The hardware information.
|
qiskit/util.py
|
def local_hardware_info():
"""Basic hardware information about the local machine.
Gives actual number of CPU's in the machine, even when hyperthreading is
turned on. CPU count defaults to 1 when true count can't be determined.
Returns:
dict: The hardware information.
"""
results = {
'os': platform.system(),
'memory': psutil.virtual_memory().total / (1024 ** 3),
'cpus': psutil.cpu_count(logical=False) or 1
}
return results
|
def local_hardware_info():
"""Basic hardware information about the local machine.
Gives actual number of CPU's in the machine, even when hyperthreading is
turned on. CPU count defaults to 1 when true count can't be determined.
Returns:
dict: The hardware information.
"""
results = {
'os': platform.system(),
'memory': psutil.virtual_memory().total / (1024 ** 3),
'cpus': psutil.cpu_count(logical=False) or 1
}
return results
|
[
"Basic",
"hardware",
"information",
"about",
"the",
"local",
"machine",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/util.py#L63-L77
|
[
"def",
"local_hardware_info",
"(",
")",
":",
"results",
"=",
"{",
"'os'",
":",
"platform",
".",
"system",
"(",
")",
",",
"'memory'",
":",
"psutil",
".",
"virtual_memory",
"(",
")",
".",
"total",
"/",
"(",
"1024",
"**",
"3",
")",
",",
"'cpus'",
":",
"psutil",
".",
"cpu_count",
"(",
"logical",
"=",
"False",
")",
"or",
"1",
"}",
"return",
"results"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_has_connection
|
Checks if internet connection exists to host via specified port.
If any exception is raised while trying to open a socket this will return
false.
Args:
hostname (str): Hostname to connect to.
port (int): Port to connect to
Returns:
bool: Has connection or not
|
qiskit/util.py
|
def _has_connection(hostname, port):
"""Checks if internet connection exists to host via specified port.
If any exception is raised while trying to open a socket this will return
false.
Args:
hostname (str): Hostname to connect to.
port (int): Port to connect to
Returns:
bool: Has connection or not
"""
try:
host = socket.gethostbyname(hostname)
socket.create_connection((host, port), 2)
return True
except Exception: # pylint: disable=broad-except
return False
|
def _has_connection(hostname, port):
"""Checks if internet connection exists to host via specified port.
If any exception is raised while trying to open a socket this will return
false.
Args:
hostname (str): Hostname to connect to.
port (int): Port to connect to
Returns:
bool: Has connection or not
"""
try:
host = socket.gethostbyname(hostname)
socket.create_connection((host, port), 2)
return True
except Exception: # pylint: disable=broad-except
return False
|
[
"Checks",
"if",
"internet",
"connection",
"exists",
"to",
"host",
"via",
"specified",
"port",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/util.py#L80-L99
|
[
"def",
"_has_connection",
"(",
"hostname",
",",
"port",
")",
":",
"try",
":",
"host",
"=",
"socket",
".",
"gethostbyname",
"(",
"hostname",
")",
"socket",
".",
"create_connection",
"(",
"(",
"host",
",",
"port",
")",
",",
"2",
")",
"return",
"True",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"return",
"False"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
PTM.compose
|
Return the composition channel self∘other.
Args:
other (QuantumChannel): a quantum channel.
qargs (list): a list of subsystem positions to compose other on.
front (bool): If False compose in standard order other(self(input))
otherwise compose in reverse order self(other(input))
[default: False]
Returns:
PTM: The composition channel as a PTM object.
Raises:
QiskitError: if other cannot be converted to a channel or
has incompatible dimensions.
|
qiskit/quantum_info/operators/channel/ptm.py
|
def compose(self, other, qargs=None, front=False):
"""Return the composition channel self∘other.
Args:
other (QuantumChannel): a quantum channel.
qargs (list): a list of subsystem positions to compose other on.
front (bool): If False compose in standard order other(self(input))
otherwise compose in reverse order self(other(input))
[default: False]
Returns:
PTM: The composition channel as a PTM object.
Raises:
QiskitError: if other cannot be converted to a channel or
has incompatible dimensions.
"""
if qargs is not None:
return PTM(
SuperOp(self).compose(other, qargs=qargs, front=front))
# Convert other to PTM
if not isinstance(other, PTM):
other = PTM(other)
# Check dimensions match up
if front and self._input_dim != other._output_dim:
raise QiskitError(
'input_dim of self must match output_dim of other')
if not front and self._output_dim != other._input_dim:
raise QiskitError(
'input_dim of other must match output_dim of self')
if front:
# Composition A(B(input))
input_dim = other._input_dim
output_dim = self._output_dim
return PTM(np.dot(self._data, other.data), input_dim, output_dim)
# Composition B(A(input))
input_dim = self._input_dim
output_dim = other._output_dim
return PTM(np.dot(other.data, self._data), input_dim, output_dim)
|
def compose(self, other, qargs=None, front=False):
"""Return the composition channel self∘other.
Args:
other (QuantumChannel): a quantum channel.
qargs (list): a list of subsystem positions to compose other on.
front (bool): If False compose in standard order other(self(input))
otherwise compose in reverse order self(other(input))
[default: False]
Returns:
PTM: The composition channel as a PTM object.
Raises:
QiskitError: if other cannot be converted to a channel or
has incompatible dimensions.
"""
if qargs is not None:
return PTM(
SuperOp(self).compose(other, qargs=qargs, front=front))
# Convert other to PTM
if not isinstance(other, PTM):
other = PTM(other)
# Check dimensions match up
if front and self._input_dim != other._output_dim:
raise QiskitError(
'input_dim of self must match output_dim of other')
if not front and self._output_dim != other._input_dim:
raise QiskitError(
'input_dim of other must match output_dim of self')
if front:
# Composition A(B(input))
input_dim = other._input_dim
output_dim = self._output_dim
return PTM(np.dot(self._data, other.data), input_dim, output_dim)
# Composition B(A(input))
input_dim = self._input_dim
output_dim = other._output_dim
return PTM(np.dot(other.data, self._data), input_dim, output_dim)
|
[
"Return",
"the",
"composition",
"channel",
"self∘other",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/ptm.py#L131-L170
|
[
"def",
"compose",
"(",
"self",
",",
"other",
",",
"qargs",
"=",
"None",
",",
"front",
"=",
"False",
")",
":",
"if",
"qargs",
"is",
"not",
"None",
":",
"return",
"PTM",
"(",
"SuperOp",
"(",
"self",
")",
".",
"compose",
"(",
"other",
",",
"qargs",
"=",
"qargs",
",",
"front",
"=",
"front",
")",
")",
"# Convert other to PTM",
"if",
"not",
"isinstance",
"(",
"other",
",",
"PTM",
")",
":",
"other",
"=",
"PTM",
"(",
"other",
")",
"# Check dimensions match up",
"if",
"front",
"and",
"self",
".",
"_input_dim",
"!=",
"other",
".",
"_output_dim",
":",
"raise",
"QiskitError",
"(",
"'input_dim of self must match output_dim of other'",
")",
"if",
"not",
"front",
"and",
"self",
".",
"_output_dim",
"!=",
"other",
".",
"_input_dim",
":",
"raise",
"QiskitError",
"(",
"'input_dim of other must match output_dim of self'",
")",
"if",
"front",
":",
"# Composition A(B(input))",
"input_dim",
"=",
"other",
".",
"_input_dim",
"output_dim",
"=",
"self",
".",
"_output_dim",
"return",
"PTM",
"(",
"np",
".",
"dot",
"(",
"self",
".",
"_data",
",",
"other",
".",
"data",
")",
",",
"input_dim",
",",
"output_dim",
")",
"# Composition B(A(input))",
"input_dim",
"=",
"self",
".",
"_input_dim",
"output_dim",
"=",
"other",
".",
"_output_dim",
"return",
"PTM",
"(",
"np",
".",
"dot",
"(",
"other",
".",
"data",
",",
"self",
".",
"_data",
")",
",",
"input_dim",
",",
"output_dim",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
PTM.power
|
The matrix power of the channel.
Args:
n (int): compute the matrix power of the superoperator matrix.
Returns:
PTM: the matrix power of the SuperOp converted to a PTM channel.
Raises:
QiskitError: if the input and output dimensions of the
QuantumChannel are not equal, or the power is not an integer.
|
qiskit/quantum_info/operators/channel/ptm.py
|
def power(self, n):
"""The matrix power of the channel.
Args:
n (int): compute the matrix power of the superoperator matrix.
Returns:
PTM: the matrix power of the SuperOp converted to a PTM channel.
Raises:
QiskitError: if the input and output dimensions of the
QuantumChannel are not equal, or the power is not an integer.
"""
if n > 0:
return super().power(n)
return PTM(SuperOp(self).power(n))
|
def power(self, n):
"""The matrix power of the channel.
Args:
n (int): compute the matrix power of the superoperator matrix.
Returns:
PTM: the matrix power of the SuperOp converted to a PTM channel.
Raises:
QiskitError: if the input and output dimensions of the
QuantumChannel are not equal, or the power is not an integer.
"""
if n > 0:
return super().power(n)
return PTM(SuperOp(self).power(n))
|
[
"The",
"matrix",
"power",
"of",
"the",
"channel",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/ptm.py#L172-L187
|
[
"def",
"power",
"(",
"self",
",",
"n",
")",
":",
"if",
"n",
">",
"0",
":",
"return",
"super",
"(",
")",
".",
"power",
"(",
"n",
")",
"return",
"PTM",
"(",
"SuperOp",
"(",
"self",
")",
".",
"power",
"(",
"n",
")",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_html_checker
|
Internal function that updates the status
of a HTML job monitor.
Args:
job_var (BaseJob): The job to keep track of.
interval (int): The status check interval
status (widget): HTML ipywidget for output ot screen
header (str): String representing HTML code for status.
_interval_set (bool): Was interval set by user?
|
qiskit/tools/jupyter/jupyter_magics.py
|
def _html_checker(job_var, interval, status, header,
_interval_set=False):
"""Internal function that updates the status
of a HTML job monitor.
Args:
job_var (BaseJob): The job to keep track of.
interval (int): The status check interval
status (widget): HTML ipywidget for output ot screen
header (str): String representing HTML code for status.
_interval_set (bool): Was interval set by user?
"""
job_status = job_var.status()
job_status_name = job_status.name
job_status_msg = job_status.value
status.value = header % (job_status_msg)
while job_status_name not in ['DONE', 'CANCELLED']:
time.sleep(interval)
job_status = job_var.status()
job_status_name = job_status.name
job_status_msg = job_status.value
if job_status_name == 'ERROR':
break
else:
if job_status_name == 'QUEUED':
job_status_msg += ' (%s)' % job_var.queue_position()
if not _interval_set:
interval = max(job_var.queue_position(), 2)
else:
if not _interval_set:
interval = 2
status.value = header % (job_status_msg)
status.value = header % (job_status_msg)
|
def _html_checker(job_var, interval, status, header,
_interval_set=False):
"""Internal function that updates the status
of a HTML job monitor.
Args:
job_var (BaseJob): The job to keep track of.
interval (int): The status check interval
status (widget): HTML ipywidget for output ot screen
header (str): String representing HTML code for status.
_interval_set (bool): Was interval set by user?
"""
job_status = job_var.status()
job_status_name = job_status.name
job_status_msg = job_status.value
status.value = header % (job_status_msg)
while job_status_name not in ['DONE', 'CANCELLED']:
time.sleep(interval)
job_status = job_var.status()
job_status_name = job_status.name
job_status_msg = job_status.value
if job_status_name == 'ERROR':
break
else:
if job_status_name == 'QUEUED':
job_status_msg += ' (%s)' % job_var.queue_position()
if not _interval_set:
interval = max(job_var.queue_position(), 2)
else:
if not _interval_set:
interval = 2
status.value = header % (job_status_msg)
status.value = header % (job_status_msg)
|
[
"Internal",
"function",
"that",
"updates",
"the",
"status",
"of",
"a",
"HTML",
"job",
"monitor",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/jupyter/jupyter_magics.py#L25-L58
|
[
"def",
"_html_checker",
"(",
"job_var",
",",
"interval",
",",
"status",
",",
"header",
",",
"_interval_set",
"=",
"False",
")",
":",
"job_status",
"=",
"job_var",
".",
"status",
"(",
")",
"job_status_name",
"=",
"job_status",
".",
"name",
"job_status_msg",
"=",
"job_status",
".",
"value",
"status",
".",
"value",
"=",
"header",
"%",
"(",
"job_status_msg",
")",
"while",
"job_status_name",
"not",
"in",
"[",
"'DONE'",
",",
"'CANCELLED'",
"]",
":",
"time",
".",
"sleep",
"(",
"interval",
")",
"job_status",
"=",
"job_var",
".",
"status",
"(",
")",
"job_status_name",
"=",
"job_status",
".",
"name",
"job_status_msg",
"=",
"job_status",
".",
"value",
"if",
"job_status_name",
"==",
"'ERROR'",
":",
"break",
"else",
":",
"if",
"job_status_name",
"==",
"'QUEUED'",
":",
"job_status_msg",
"+=",
"' (%s)'",
"%",
"job_var",
".",
"queue_position",
"(",
")",
"if",
"not",
"_interval_set",
":",
"interval",
"=",
"max",
"(",
"job_var",
".",
"queue_position",
"(",
")",
",",
"2",
")",
"else",
":",
"if",
"not",
"_interval_set",
":",
"interval",
"=",
"2",
"status",
".",
"value",
"=",
"header",
"%",
"(",
"job_status_msg",
")",
"status",
".",
"value",
"=",
"header",
"%",
"(",
"job_status_msg",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
constant
|
Continuous constant pulse.
Args:
times: Times to output pulse for.
amp: Complex pulse amplitude.
|
qiskit/pulse/pulse_lib/continuous.py
|
def constant(times: np.ndarray, amp: complex) -> np.ndarray:
"""Continuous constant pulse.
Args:
times: Times to output pulse for.
amp: Complex pulse amplitude.
"""
return np.full(len(times), amp, dtype=np.complex_)
|
def constant(times: np.ndarray, amp: complex) -> np.ndarray:
"""Continuous constant pulse.
Args:
times: Times to output pulse for.
amp: Complex pulse amplitude.
"""
return np.full(len(times), amp, dtype=np.complex_)
|
[
"Continuous",
"constant",
"pulse",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/pulse_lib/continuous.py#L18-L25
|
[
"def",
"constant",
"(",
"times",
":",
"np",
".",
"ndarray",
",",
"amp",
":",
"complex",
")",
"->",
"np",
".",
"ndarray",
":",
"return",
"np",
".",
"full",
"(",
"len",
"(",
"times",
")",
",",
"amp",
",",
"dtype",
"=",
"np",
".",
"complex_",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
square
|
Continuous square wave.
Args:
times: Times to output wave for.
amp: Pulse amplitude. Wave range is [-amp, amp].
period: Pulse period, units of dt.
phase: Pulse phase.
|
qiskit/pulse/pulse_lib/continuous.py
|
def square(times: np.ndarray, amp: complex, period: float, phase: float = 0) -> np.ndarray:
"""Continuous square wave.
Args:
times: Times to output wave for.
amp: Pulse amplitude. Wave range is [-amp, amp].
period: Pulse period, units of dt.
phase: Pulse phase.
"""
x = times/period+phase/np.pi
return amp*(2*(2*np.floor(x) - np.floor(2*x)) + 1).astype(np.complex_)
|
def square(times: np.ndarray, amp: complex, period: float, phase: float = 0) -> np.ndarray:
"""Continuous square wave.
Args:
times: Times to output wave for.
amp: Pulse amplitude. Wave range is [-amp, amp].
period: Pulse period, units of dt.
phase: Pulse phase.
"""
x = times/period+phase/np.pi
return amp*(2*(2*np.floor(x) - np.floor(2*x)) + 1).astype(np.complex_)
|
[
"Continuous",
"square",
"wave",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/pulse_lib/continuous.py#L37-L47
|
[
"def",
"square",
"(",
"times",
":",
"np",
".",
"ndarray",
",",
"amp",
":",
"complex",
",",
"period",
":",
"float",
",",
"phase",
":",
"float",
"=",
"0",
")",
"->",
"np",
".",
"ndarray",
":",
"x",
"=",
"times",
"/",
"period",
"+",
"phase",
"/",
"np",
".",
"pi",
"return",
"amp",
"*",
"(",
"2",
"*",
"(",
"2",
"*",
"np",
".",
"floor",
"(",
"x",
")",
"-",
"np",
".",
"floor",
"(",
"2",
"*",
"x",
")",
")",
"+",
"1",
")",
".",
"astype",
"(",
"np",
".",
"complex_",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
triangle
|
Continuous triangle wave.
Args:
times: Times to output wave for.
amp: Pulse amplitude. Wave range is [-amp, amp].
period: Pulse period, units of dt.
phase: Pulse phase.
|
qiskit/pulse/pulse_lib/continuous.py
|
def triangle(times: np.ndarray, amp: complex, period: float, phase: float = 0) -> np.ndarray:
"""Continuous triangle wave.
Args:
times: Times to output wave for.
amp: Pulse amplitude. Wave range is [-amp, amp].
period: Pulse period, units of dt.
phase: Pulse phase.
"""
return amp*(-2*np.abs(sawtooth(times, 1, period, (phase-np.pi/2)/2)) + 1).astype(np.complex_)
|
def triangle(times: np.ndarray, amp: complex, period: float, phase: float = 0) -> np.ndarray:
"""Continuous triangle wave.
Args:
times: Times to output wave for.
amp: Pulse amplitude. Wave range is [-amp, amp].
period: Pulse period, units of dt.
phase: Pulse phase.
"""
return amp*(-2*np.abs(sawtooth(times, 1, period, (phase-np.pi/2)/2)) + 1).astype(np.complex_)
|
[
"Continuous",
"triangle",
"wave",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/pulse_lib/continuous.py#L63-L72
|
[
"def",
"triangle",
"(",
"times",
":",
"np",
".",
"ndarray",
",",
"amp",
":",
"complex",
",",
"period",
":",
"float",
",",
"phase",
":",
"float",
"=",
"0",
")",
"->",
"np",
".",
"ndarray",
":",
"return",
"amp",
"*",
"(",
"-",
"2",
"*",
"np",
".",
"abs",
"(",
"sawtooth",
"(",
"times",
",",
"1",
",",
"period",
",",
"(",
"phase",
"-",
"np",
".",
"pi",
"/",
"2",
")",
"/",
"2",
")",
")",
"+",
"1",
")",
".",
"astype",
"(",
"np",
".",
"complex_",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
cos
|
Continuous cosine wave.
Args:
times: Times to output wave for.
amp: Pulse amplitude.
freq: Pulse frequency, units of 1/dt.
phase: Pulse phase.
|
qiskit/pulse/pulse_lib/continuous.py
|
def cos(times: np.ndarray, amp: complex, freq: float, phase: float = 0) -> np.ndarray:
"""Continuous cosine wave.
Args:
times: Times to output wave for.
amp: Pulse amplitude.
freq: Pulse frequency, units of 1/dt.
phase: Pulse phase.
"""
return amp*np.cos(2*np.pi*freq*times+phase).astype(np.complex_)
|
def cos(times: np.ndarray, amp: complex, freq: float, phase: float = 0) -> np.ndarray:
"""Continuous cosine wave.
Args:
times: Times to output wave for.
amp: Pulse amplitude.
freq: Pulse frequency, units of 1/dt.
phase: Pulse phase.
"""
return amp*np.cos(2*np.pi*freq*times+phase).astype(np.complex_)
|
[
"Continuous",
"cosine",
"wave",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/pulse_lib/continuous.py#L75-L84
|
[
"def",
"cos",
"(",
"times",
":",
"np",
".",
"ndarray",
",",
"amp",
":",
"complex",
",",
"freq",
":",
"float",
",",
"phase",
":",
"float",
"=",
"0",
")",
"->",
"np",
".",
"ndarray",
":",
"return",
"amp",
"*",
"np",
".",
"cos",
"(",
"2",
"*",
"np",
".",
"pi",
"*",
"freq",
"*",
"times",
"+",
"phase",
")",
".",
"astype",
"(",
"np",
".",
"complex_",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_fix_gaussian_width
|
r"""Enforce that the supplied gaussian pulse is zeroed at a specific width.
This is acheived by subtracting $\Omega_g(center \pm zeroed_width/2)$ from all samples.
amp: Pulse amplitude at `2\times center+1`.
center: Center (mean) of pulse.
sigma: Width (standard deviation) of pulse.
zeroed_width: Subtract baseline to gaussian pulses to make sure
$\Omega_g(center \pm zeroed_width/2)=0$ is satisfied. This is used to avoid
large discontinuities at the start of a gaussian pulse. If unsupplied,
defaults to $2*(center+1)$ such that the samples are zero at $\Omega_g(-1)$.
rescale_amp: If `zeroed_width` is not `None` and `rescale_amp=True` the pulse will
be rescaled so that $\Omega_g(center)-\Omega_g(center\pm zeroed_width/2)=amp$.
ret_scale_factor: Return amplitude scale factor.
|
qiskit/pulse/pulse_lib/continuous.py
|
def _fix_gaussian_width(gaussian_samples, amp: float, center: float, sigma: float,
zeroed_width: Union[None, float] = None, rescale_amp: bool = False,
ret_scale_factor: bool = False) -> np.ndarray:
r"""Enforce that the supplied gaussian pulse is zeroed at a specific width.
This is acheived by subtracting $\Omega_g(center \pm zeroed_width/2)$ from all samples.
amp: Pulse amplitude at `2\times center+1`.
center: Center (mean) of pulse.
sigma: Width (standard deviation) of pulse.
zeroed_width: Subtract baseline to gaussian pulses to make sure
$\Omega_g(center \pm zeroed_width/2)=0$ is satisfied. This is used to avoid
large discontinuities at the start of a gaussian pulse. If unsupplied,
defaults to $2*(center+1)$ such that the samples are zero at $\Omega_g(-1)$.
rescale_amp: If `zeroed_width` is not `None` and `rescale_amp=True` the pulse will
be rescaled so that $\Omega_g(center)-\Omega_g(center\pm zeroed_width/2)=amp$.
ret_scale_factor: Return amplitude scale factor.
"""
if zeroed_width is None:
zeroed_width = 2*(center+1)
zero_offset = gaussian(np.array([-zeroed_width/2]), amp, center, sigma)
gaussian_samples -= zero_offset
amp_scale_factor = 1.
if rescale_amp:
amp_scale_factor = amp/(amp-zero_offset)
gaussian_samples *= amp_scale_factor
if ret_scale_factor:
return gaussian_samples, amp_scale_factor
return gaussian_samples
|
def _fix_gaussian_width(gaussian_samples, amp: float, center: float, sigma: float,
zeroed_width: Union[None, float] = None, rescale_amp: bool = False,
ret_scale_factor: bool = False) -> np.ndarray:
r"""Enforce that the supplied gaussian pulse is zeroed at a specific width.
This is acheived by subtracting $\Omega_g(center \pm zeroed_width/2)$ from all samples.
amp: Pulse amplitude at `2\times center+1`.
center: Center (mean) of pulse.
sigma: Width (standard deviation) of pulse.
zeroed_width: Subtract baseline to gaussian pulses to make sure
$\Omega_g(center \pm zeroed_width/2)=0$ is satisfied. This is used to avoid
large discontinuities at the start of a gaussian pulse. If unsupplied,
defaults to $2*(center+1)$ such that the samples are zero at $\Omega_g(-1)$.
rescale_amp: If `zeroed_width` is not `None` and `rescale_amp=True` the pulse will
be rescaled so that $\Omega_g(center)-\Omega_g(center\pm zeroed_width/2)=amp$.
ret_scale_factor: Return amplitude scale factor.
"""
if zeroed_width is None:
zeroed_width = 2*(center+1)
zero_offset = gaussian(np.array([-zeroed_width/2]), amp, center, sigma)
gaussian_samples -= zero_offset
amp_scale_factor = 1.
if rescale_amp:
amp_scale_factor = amp/(amp-zero_offset)
gaussian_samples *= amp_scale_factor
if ret_scale_factor:
return gaussian_samples, amp_scale_factor
return gaussian_samples
|
[
"r",
"Enforce",
"that",
"the",
"supplied",
"gaussian",
"pulse",
"is",
"zeroed",
"at",
"a",
"specific",
"width",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/pulse_lib/continuous.py#L99-L129
|
[
"def",
"_fix_gaussian_width",
"(",
"gaussian_samples",
",",
"amp",
":",
"float",
",",
"center",
":",
"float",
",",
"sigma",
":",
"float",
",",
"zeroed_width",
":",
"Union",
"[",
"None",
",",
"float",
"]",
"=",
"None",
",",
"rescale_amp",
":",
"bool",
"=",
"False",
",",
"ret_scale_factor",
":",
"bool",
"=",
"False",
")",
"->",
"np",
".",
"ndarray",
":",
"if",
"zeroed_width",
"is",
"None",
":",
"zeroed_width",
"=",
"2",
"*",
"(",
"center",
"+",
"1",
")",
"zero_offset",
"=",
"gaussian",
"(",
"np",
".",
"array",
"(",
"[",
"-",
"zeroed_width",
"/",
"2",
"]",
")",
",",
"amp",
",",
"center",
",",
"sigma",
")",
"gaussian_samples",
"-=",
"zero_offset",
"amp_scale_factor",
"=",
"1.",
"if",
"rescale_amp",
":",
"amp_scale_factor",
"=",
"amp",
"/",
"(",
"amp",
"-",
"zero_offset",
")",
"gaussian_samples",
"*=",
"amp_scale_factor",
"if",
"ret_scale_factor",
":",
"return",
"gaussian_samples",
",",
"amp_scale_factor",
"return",
"gaussian_samples"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
gaussian
|
r"""Continuous unnormalized gaussian pulse.
Integrated area under curve is $\Omega_g(amp, sigma) = amp \times np.sqrt(2\pi \sigma^2)$
Args:
times: Times to output pulse for.
amp: Pulse amplitude at `center`. If `zeroed_width` is set pulse amplitude at center
will be $amp-\Omega_g(center\pm zeroed_width/2)$ unless `rescale_amp` is set,
in which case all samples will be rescaled such that the center
amplitude will be `amp`.
center: Center (mean) of pulse.
sigma: Width (standard deviation) of pulse.
zeroed_width: Subtract baseline to gaussian pulses to make sure
$\Omega_g(center \pm zeroed_width/2)=0$ is satisfied. This is used to avoid
large discontinuities at the start of a gaussian pulse.
rescale_amp: If `zeroed_width` is not `None` and `rescale_amp=True` the pulse will
be rescaled so that $\Omega_g(center)-\Omega_g(center\pm zeroed_width/2)=amp$.
ret_x: Return centered and standard deviation normalized pulse location.
$x=(times-center)/sigma.
|
qiskit/pulse/pulse_lib/continuous.py
|
def gaussian(times: np.ndarray, amp: complex, center: float, sigma: float,
zeroed_width: Union[None, float] = None, rescale_amp: bool = False,
ret_x: bool = False) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]:
r"""Continuous unnormalized gaussian pulse.
Integrated area under curve is $\Omega_g(amp, sigma) = amp \times np.sqrt(2\pi \sigma^2)$
Args:
times: Times to output pulse for.
amp: Pulse amplitude at `center`. If `zeroed_width` is set pulse amplitude at center
will be $amp-\Omega_g(center\pm zeroed_width/2)$ unless `rescale_amp` is set,
in which case all samples will be rescaled such that the center
amplitude will be `amp`.
center: Center (mean) of pulse.
sigma: Width (standard deviation) of pulse.
zeroed_width: Subtract baseline to gaussian pulses to make sure
$\Omega_g(center \pm zeroed_width/2)=0$ is satisfied. This is used to avoid
large discontinuities at the start of a gaussian pulse.
rescale_amp: If `zeroed_width` is not `None` and `rescale_amp=True` the pulse will
be rescaled so that $\Omega_g(center)-\Omega_g(center\pm zeroed_width/2)=amp$.
ret_x: Return centered and standard deviation normalized pulse location.
$x=(times-center)/sigma.
"""
times = np.asarray(times, dtype=np.complex_)
x = (times-center)/sigma
gauss = amp*np.exp(-x**2/2).astype(np.complex_)
if zeroed_width is not None:
gauss = _fix_gaussian_width(gauss, amp=amp, center=center, sigma=sigma,
zeroed_width=zeroed_width, rescale_amp=rescale_amp)
if ret_x:
return gauss, x
return gauss
|
def gaussian(times: np.ndarray, amp: complex, center: float, sigma: float,
zeroed_width: Union[None, float] = None, rescale_amp: bool = False,
ret_x: bool = False) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]:
r"""Continuous unnormalized gaussian pulse.
Integrated area under curve is $\Omega_g(amp, sigma) = amp \times np.sqrt(2\pi \sigma^2)$
Args:
times: Times to output pulse for.
amp: Pulse amplitude at `center`. If `zeroed_width` is set pulse amplitude at center
will be $amp-\Omega_g(center\pm zeroed_width/2)$ unless `rescale_amp` is set,
in which case all samples will be rescaled such that the center
amplitude will be `amp`.
center: Center (mean) of pulse.
sigma: Width (standard deviation) of pulse.
zeroed_width: Subtract baseline to gaussian pulses to make sure
$\Omega_g(center \pm zeroed_width/2)=0$ is satisfied. This is used to avoid
large discontinuities at the start of a gaussian pulse.
rescale_amp: If `zeroed_width` is not `None` and `rescale_amp=True` the pulse will
be rescaled so that $\Omega_g(center)-\Omega_g(center\pm zeroed_width/2)=amp$.
ret_x: Return centered and standard deviation normalized pulse location.
$x=(times-center)/sigma.
"""
times = np.asarray(times, dtype=np.complex_)
x = (times-center)/sigma
gauss = amp*np.exp(-x**2/2).astype(np.complex_)
if zeroed_width is not None:
gauss = _fix_gaussian_width(gauss, amp=amp, center=center, sigma=sigma,
zeroed_width=zeroed_width, rescale_amp=rescale_amp)
if ret_x:
return gauss, x
return gauss
|
[
"r",
"Continuous",
"unnormalized",
"gaussian",
"pulse",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/pulse_lib/continuous.py#L132-L165
|
[
"def",
"gaussian",
"(",
"times",
":",
"np",
".",
"ndarray",
",",
"amp",
":",
"complex",
",",
"center",
":",
"float",
",",
"sigma",
":",
"float",
",",
"zeroed_width",
":",
"Union",
"[",
"None",
",",
"float",
"]",
"=",
"None",
",",
"rescale_amp",
":",
"bool",
"=",
"False",
",",
"ret_x",
":",
"bool",
"=",
"False",
")",
"->",
"Union",
"[",
"np",
".",
"ndarray",
",",
"Tuple",
"[",
"np",
".",
"ndarray",
",",
"np",
".",
"ndarray",
"]",
"]",
":",
"times",
"=",
"np",
".",
"asarray",
"(",
"times",
",",
"dtype",
"=",
"np",
".",
"complex_",
")",
"x",
"=",
"(",
"times",
"-",
"center",
")",
"/",
"sigma",
"gauss",
"=",
"amp",
"*",
"np",
".",
"exp",
"(",
"-",
"x",
"**",
"2",
"/",
"2",
")",
".",
"astype",
"(",
"np",
".",
"complex_",
")",
"if",
"zeroed_width",
"is",
"not",
"None",
":",
"gauss",
"=",
"_fix_gaussian_width",
"(",
"gauss",
",",
"amp",
"=",
"amp",
",",
"center",
"=",
"center",
",",
"sigma",
"=",
"sigma",
",",
"zeroed_width",
"=",
"zeroed_width",
",",
"rescale_amp",
"=",
"rescale_amp",
")",
"if",
"ret_x",
":",
"return",
"gauss",
",",
"x",
"return",
"gauss"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
gaussian_deriv
|
Continuous unnormalized gaussian derivative pulse.
Args:
times: Times to output pulse for.
amp: Pulse amplitude at `center`.
center: Center (mean) of pulse.
sigma: Width (standard deviation) of pulse.
ret_gaussian: Return gaussian with which derivative was taken with.
|
qiskit/pulse/pulse_lib/continuous.py
|
def gaussian_deriv(times: np.ndarray, amp: complex, center: float, sigma: float,
ret_gaussian: bool = False) -> np.ndarray:
"""Continuous unnormalized gaussian derivative pulse.
Args:
times: Times to output pulse for.
amp: Pulse amplitude at `center`.
center: Center (mean) of pulse.
sigma: Width (standard deviation) of pulse.
ret_gaussian: Return gaussian with which derivative was taken with.
"""
gauss, x = gaussian(times, amp=amp, center=center, sigma=sigma, ret_x=True)
gauss_deriv = -x/sigma*gauss
if ret_gaussian:
return gauss_deriv, gauss
return gauss_deriv
|
def gaussian_deriv(times: np.ndarray, amp: complex, center: float, sigma: float,
ret_gaussian: bool = False) -> np.ndarray:
"""Continuous unnormalized gaussian derivative pulse.
Args:
times: Times to output pulse for.
amp: Pulse amplitude at `center`.
center: Center (mean) of pulse.
sigma: Width (standard deviation) of pulse.
ret_gaussian: Return gaussian with which derivative was taken with.
"""
gauss, x = gaussian(times, amp=amp, center=center, sigma=sigma, ret_x=True)
gauss_deriv = -x/sigma*gauss
if ret_gaussian:
return gauss_deriv, gauss
return gauss_deriv
|
[
"Continuous",
"unnormalized",
"gaussian",
"derivative",
"pulse",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/pulse_lib/continuous.py#L168-L183
|
[
"def",
"gaussian_deriv",
"(",
"times",
":",
"np",
".",
"ndarray",
",",
"amp",
":",
"complex",
",",
"center",
":",
"float",
",",
"sigma",
":",
"float",
",",
"ret_gaussian",
":",
"bool",
"=",
"False",
")",
"->",
"np",
".",
"ndarray",
":",
"gauss",
",",
"x",
"=",
"gaussian",
"(",
"times",
",",
"amp",
"=",
"amp",
",",
"center",
"=",
"center",
",",
"sigma",
"=",
"sigma",
",",
"ret_x",
"=",
"True",
")",
"gauss_deriv",
"=",
"-",
"x",
"/",
"sigma",
"*",
"gauss",
"if",
"ret_gaussian",
":",
"return",
"gauss_deriv",
",",
"gauss",
"return",
"gauss_deriv"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
gaussian_square
|
r"""Continuous gaussian square pulse.
Args:
times: Times to output pulse for.
amp: Pulse amplitude.
center: Center of the square pulse component.
width: Width of the square pulse component.
sigma: Width (standard deviation) of gaussian rise/fall portion of the pulse.
zeroed_width: Subtract baseline of gaussian square pulse
to enforce $\OmegaSquare(center \pm zeroed_width/2)=0$.
|
qiskit/pulse/pulse_lib/continuous.py
|
def gaussian_square(times: np.ndarray, amp: complex, center: float, width: float,
sigma: float, zeroed_width: Union[None, float] = None) -> np.ndarray:
r"""Continuous gaussian square pulse.
Args:
times: Times to output pulse for.
amp: Pulse amplitude.
center: Center of the square pulse component.
width: Width of the square pulse component.
sigma: Width (standard deviation) of gaussian rise/fall portion of the pulse.
zeroed_width: Subtract baseline of gaussian square pulse
to enforce $\OmegaSquare(center \pm zeroed_width/2)=0$.
"""
square_start = center-width/2
square_stop = center+width/2
if zeroed_width:
zeroed_width = min(width, zeroed_width)
gauss_zeroed_width = zeroed_width-width
else:
gauss_zeroed_width = None
funclist = [functools.partial(gaussian, amp=amp, center=square_start, sigma=sigma,
zeroed_width=gauss_zeroed_width, rescale_amp=True),
functools.partial(gaussian, amp=amp, center=square_stop, sigma=sigma,
zeroed_width=gauss_zeroed_width, rescale_amp=True),
functools.partial(constant, amp=amp)]
condlist = [times <= square_start, times >= square_stop]
return np.piecewise(times.astype(np.complex_), condlist, funclist)
|
def gaussian_square(times: np.ndarray, amp: complex, center: float, width: float,
sigma: float, zeroed_width: Union[None, float] = None) -> np.ndarray:
r"""Continuous gaussian square pulse.
Args:
times: Times to output pulse for.
amp: Pulse amplitude.
center: Center of the square pulse component.
width: Width of the square pulse component.
sigma: Width (standard deviation) of gaussian rise/fall portion of the pulse.
zeroed_width: Subtract baseline of gaussian square pulse
to enforce $\OmegaSquare(center \pm zeroed_width/2)=0$.
"""
square_start = center-width/2
square_stop = center+width/2
if zeroed_width:
zeroed_width = min(width, zeroed_width)
gauss_zeroed_width = zeroed_width-width
else:
gauss_zeroed_width = None
funclist = [functools.partial(gaussian, amp=amp, center=square_start, sigma=sigma,
zeroed_width=gauss_zeroed_width, rescale_amp=True),
functools.partial(gaussian, amp=amp, center=square_stop, sigma=sigma,
zeroed_width=gauss_zeroed_width, rescale_amp=True),
functools.partial(constant, amp=amp)]
condlist = [times <= square_start, times >= square_stop]
return np.piecewise(times.astype(np.complex_), condlist, funclist)
|
[
"r",
"Continuous",
"gaussian",
"square",
"pulse",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/pulse_lib/continuous.py#L186-L213
|
[
"def",
"gaussian_square",
"(",
"times",
":",
"np",
".",
"ndarray",
",",
"amp",
":",
"complex",
",",
"center",
":",
"float",
",",
"width",
":",
"float",
",",
"sigma",
":",
"float",
",",
"zeroed_width",
":",
"Union",
"[",
"None",
",",
"float",
"]",
"=",
"None",
")",
"->",
"np",
".",
"ndarray",
":",
"square_start",
"=",
"center",
"-",
"width",
"/",
"2",
"square_stop",
"=",
"center",
"+",
"width",
"/",
"2",
"if",
"zeroed_width",
":",
"zeroed_width",
"=",
"min",
"(",
"width",
",",
"zeroed_width",
")",
"gauss_zeroed_width",
"=",
"zeroed_width",
"-",
"width",
"else",
":",
"gauss_zeroed_width",
"=",
"None",
"funclist",
"=",
"[",
"functools",
".",
"partial",
"(",
"gaussian",
",",
"amp",
"=",
"amp",
",",
"center",
"=",
"square_start",
",",
"sigma",
"=",
"sigma",
",",
"zeroed_width",
"=",
"gauss_zeroed_width",
",",
"rescale_amp",
"=",
"True",
")",
",",
"functools",
".",
"partial",
"(",
"gaussian",
",",
"amp",
"=",
"amp",
",",
"center",
"=",
"square_stop",
",",
"sigma",
"=",
"sigma",
",",
"zeroed_width",
"=",
"gauss_zeroed_width",
",",
"rescale_amp",
"=",
"True",
")",
",",
"functools",
".",
"partial",
"(",
"constant",
",",
"amp",
"=",
"amp",
")",
"]",
"condlist",
"=",
"[",
"times",
"<=",
"square_start",
",",
"times",
">=",
"square_stop",
"]",
"return",
"np",
".",
"piecewise",
"(",
"times",
".",
"astype",
"(",
"np",
".",
"complex_",
")",
",",
"condlist",
",",
"funclist",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
drag
|
r"""Continuous Y-only correction DRAG pulse for standard nonlinear oscillator (SNO) [1].
[1] Gambetta, J. M., Motzoi, F., Merkel, S. T. & Wilhelm, F. K.
Analytic control methods for high-fidelity unitary operations
in a weakly nonlinear oscillator. Phys. Rev. A 83, 012308 (2011).
Args:
times: Times to output pulse for.
amp: Pulse amplitude at `center`.
center: Center (mean) of pulse.
sigma: Width (standard deviation) of pulse.
beta: Y correction amplitude. For the SNO this is $\beta=-\frac{\lambda_1^2}{4\Delta_2}$.
Where $\lambds_1$ is the relative coupling strength between the first excited and second
excited states and $\Delta_2$ is the detuning between the resepective excited states.
zeroed_width: Subtract baseline to gaussian pulses to make sure
$\Omega_g(center \pm zeroed_width/2)=0$ is satisfied. This is used to avoid
large discontinuities at the start of a gaussian pulse.
rescale_amp: If `zeroed_width` is not `None` and `rescale_amp=True` the pulse will
be rescaled so that $\Omega_g(center)-\Omega_g(center\pm zeroed_width/2)=amp$.
|
qiskit/pulse/pulse_lib/continuous.py
|
def drag(times: np.ndarray, amp: complex, center: float, sigma: float, beta: float,
zeroed_width: Union[None, float] = None, rescale_amp: bool = False) -> np.ndarray:
r"""Continuous Y-only correction DRAG pulse for standard nonlinear oscillator (SNO) [1].
[1] Gambetta, J. M., Motzoi, F., Merkel, S. T. & Wilhelm, F. K.
Analytic control methods for high-fidelity unitary operations
in a weakly nonlinear oscillator. Phys. Rev. A 83, 012308 (2011).
Args:
times: Times to output pulse for.
amp: Pulse amplitude at `center`.
center: Center (mean) of pulse.
sigma: Width (standard deviation) of pulse.
beta: Y correction amplitude. For the SNO this is $\beta=-\frac{\lambda_1^2}{4\Delta_2}$.
Where $\lambds_1$ is the relative coupling strength between the first excited and second
excited states and $\Delta_2$ is the detuning between the resepective excited states.
zeroed_width: Subtract baseline to gaussian pulses to make sure
$\Omega_g(center \pm zeroed_width/2)=0$ is satisfied. This is used to avoid
large discontinuities at the start of a gaussian pulse.
rescale_amp: If `zeroed_width` is not `None` and `rescale_amp=True` the pulse will
be rescaled so that $\Omega_g(center)-\Omega_g(center\pm zeroed_width/2)=amp$.
"""
gauss_deriv, gauss = gaussian_deriv(times, amp=amp, center=center, sigma=sigma,
ret_gaussian=True)
if zeroed_width is not None:
gauss, scale_factor = _fix_gaussian_width(gauss, amp=amp, center=center, sigma=sigma,
zeroed_width=zeroed_width,
rescale_amp=rescale_amp,
ret_scale_factor=True)
gauss_deriv *= scale_factor
return gauss + 1j*beta*gauss_deriv
|
def drag(times: np.ndarray, amp: complex, center: float, sigma: float, beta: float,
zeroed_width: Union[None, float] = None, rescale_amp: bool = False) -> np.ndarray:
r"""Continuous Y-only correction DRAG pulse for standard nonlinear oscillator (SNO) [1].
[1] Gambetta, J. M., Motzoi, F., Merkel, S. T. & Wilhelm, F. K.
Analytic control methods for high-fidelity unitary operations
in a weakly nonlinear oscillator. Phys. Rev. A 83, 012308 (2011).
Args:
times: Times to output pulse for.
amp: Pulse amplitude at `center`.
center: Center (mean) of pulse.
sigma: Width (standard deviation) of pulse.
beta: Y correction amplitude. For the SNO this is $\beta=-\frac{\lambda_1^2}{4\Delta_2}$.
Where $\lambds_1$ is the relative coupling strength between the first excited and second
excited states and $\Delta_2$ is the detuning between the resepective excited states.
zeroed_width: Subtract baseline to gaussian pulses to make sure
$\Omega_g(center \pm zeroed_width/2)=0$ is satisfied. This is used to avoid
large discontinuities at the start of a gaussian pulse.
rescale_amp: If `zeroed_width` is not `None` and `rescale_amp=True` the pulse will
be rescaled so that $\Omega_g(center)-\Omega_g(center\pm zeroed_width/2)=amp$.
"""
gauss_deriv, gauss = gaussian_deriv(times, amp=amp, center=center, sigma=sigma,
ret_gaussian=True)
if zeroed_width is not None:
gauss, scale_factor = _fix_gaussian_width(gauss, amp=amp, center=center, sigma=sigma,
zeroed_width=zeroed_width,
rescale_amp=rescale_amp,
ret_scale_factor=True)
gauss_deriv *= scale_factor
return gauss + 1j*beta*gauss_deriv
|
[
"r",
"Continuous",
"Y",
"-",
"only",
"correction",
"DRAG",
"pulse",
"for",
"standard",
"nonlinear",
"oscillator",
"(",
"SNO",
")",
"[",
"1",
"]",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/pulse_lib/continuous.py#L216-L249
|
[
"def",
"drag",
"(",
"times",
":",
"np",
".",
"ndarray",
",",
"amp",
":",
"complex",
",",
"center",
":",
"float",
",",
"sigma",
":",
"float",
",",
"beta",
":",
"float",
",",
"zeroed_width",
":",
"Union",
"[",
"None",
",",
"float",
"]",
"=",
"None",
",",
"rescale_amp",
":",
"bool",
"=",
"False",
")",
"->",
"np",
".",
"ndarray",
":",
"gauss_deriv",
",",
"gauss",
"=",
"gaussian_deriv",
"(",
"times",
",",
"amp",
"=",
"amp",
",",
"center",
"=",
"center",
",",
"sigma",
"=",
"sigma",
",",
"ret_gaussian",
"=",
"True",
")",
"if",
"zeroed_width",
"is",
"not",
"None",
":",
"gauss",
",",
"scale_factor",
"=",
"_fix_gaussian_width",
"(",
"gauss",
",",
"amp",
"=",
"amp",
",",
"center",
"=",
"center",
",",
"sigma",
"=",
"sigma",
",",
"zeroed_width",
"=",
"zeroed_width",
",",
"rescale_amp",
"=",
"rescale_amp",
",",
"ret_scale_factor",
"=",
"True",
")",
"gauss_deriv",
"*=",
"scale_factor",
"return",
"gauss",
"+",
"1j",
"*",
"beta",
"*",
"gauss_deriv"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
default_pass_manager
|
The default pass manager that maps to the coupling map.
Args:
basis_gates (list[str]): list of basis gate names supported by the target.
coupling_map (CouplingMap): coupling map to target in mapping.
initial_layout (Layout or None): initial layout of virtual qubits on physical qubits
seed_transpiler (int or None): random seed for stochastic passes.
Returns:
PassManager: A pass manager to map and optimize.
|
qiskit/transpiler/preset_passmanagers/default.py
|
def default_pass_manager(basis_gates, coupling_map, initial_layout, seed_transpiler):
"""
The default pass manager that maps to the coupling map.
Args:
basis_gates (list[str]): list of basis gate names supported by the target.
coupling_map (CouplingMap): coupling map to target in mapping.
initial_layout (Layout or None): initial layout of virtual qubits on physical qubits
seed_transpiler (int or None): random seed for stochastic passes.
Returns:
PassManager: A pass manager to map and optimize.
"""
pass_manager = PassManager()
pass_manager.property_set['layout'] = initial_layout
pass_manager.append(Unroller(basis_gates))
# Use the trivial layout if no layout is found
pass_manager.append(TrivialLayout(coupling_map),
condition=lambda property_set: not property_set['layout'])
# if the circuit and layout already satisfy the coupling_constraints, use that layout
# otherwise layout on the most densely connected physical qubit subset
pass_manager.append(CheckMap(coupling_map))
pass_manager.append(DenseLayout(coupling_map),
condition=lambda property_set: not property_set['is_swap_mapped'])
# Extend the the dag/layout with ancillas using the full coupling map
pass_manager.append(FullAncillaAllocation(coupling_map))
pass_manager.append(EnlargeWithAncilla())
# Circuit must only contain 1- or 2-qubit interactions for swapper to work
pass_manager.append(Unroll3qOrMore())
# Swap mapper
pass_manager.append(LegacySwap(coupling_map, trials=20, seed=seed_transpiler))
# Expand swaps
pass_manager.append(Decompose(SwapGate))
# Change CX directions
pass_manager.append(CXDirection(coupling_map))
# Unroll to the basis
pass_manager.append(Unroller(['u1', 'u2', 'u3', 'id', 'cx']))
# Simplify single qubit gates and CXs
simplification_passes = [Optimize1qGates(), CXCancellation(), RemoveResetInZeroState()]
pass_manager.append(simplification_passes + [Depth(), FixedPoint('depth')],
do_while=lambda property_set: not property_set['depth_fixed_point'])
return pass_manager
|
def default_pass_manager(basis_gates, coupling_map, initial_layout, seed_transpiler):
"""
The default pass manager that maps to the coupling map.
Args:
basis_gates (list[str]): list of basis gate names supported by the target.
coupling_map (CouplingMap): coupling map to target in mapping.
initial_layout (Layout or None): initial layout of virtual qubits on physical qubits
seed_transpiler (int or None): random seed for stochastic passes.
Returns:
PassManager: A pass manager to map and optimize.
"""
pass_manager = PassManager()
pass_manager.property_set['layout'] = initial_layout
pass_manager.append(Unroller(basis_gates))
# Use the trivial layout if no layout is found
pass_manager.append(TrivialLayout(coupling_map),
condition=lambda property_set: not property_set['layout'])
# if the circuit and layout already satisfy the coupling_constraints, use that layout
# otherwise layout on the most densely connected physical qubit subset
pass_manager.append(CheckMap(coupling_map))
pass_manager.append(DenseLayout(coupling_map),
condition=lambda property_set: not property_set['is_swap_mapped'])
# Extend the the dag/layout with ancillas using the full coupling map
pass_manager.append(FullAncillaAllocation(coupling_map))
pass_manager.append(EnlargeWithAncilla())
# Circuit must only contain 1- or 2-qubit interactions for swapper to work
pass_manager.append(Unroll3qOrMore())
# Swap mapper
pass_manager.append(LegacySwap(coupling_map, trials=20, seed=seed_transpiler))
# Expand swaps
pass_manager.append(Decompose(SwapGate))
# Change CX directions
pass_manager.append(CXDirection(coupling_map))
# Unroll to the basis
pass_manager.append(Unroller(['u1', 'u2', 'u3', 'id', 'cx']))
# Simplify single qubit gates and CXs
simplification_passes = [Optimize1qGates(), CXCancellation(), RemoveResetInZeroState()]
pass_manager.append(simplification_passes + [Depth(), FixedPoint('depth')],
do_while=lambda property_set: not property_set['depth_fixed_point'])
return pass_manager
|
[
"The",
"default",
"pass",
"manager",
"that",
"maps",
"to",
"the",
"coupling",
"map",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/preset_passmanagers/default.py#L30-L83
|
[
"def",
"default_pass_manager",
"(",
"basis_gates",
",",
"coupling_map",
",",
"initial_layout",
",",
"seed_transpiler",
")",
":",
"pass_manager",
"=",
"PassManager",
"(",
")",
"pass_manager",
".",
"property_set",
"[",
"'layout'",
"]",
"=",
"initial_layout",
"pass_manager",
".",
"append",
"(",
"Unroller",
"(",
"basis_gates",
")",
")",
"# Use the trivial layout if no layout is found",
"pass_manager",
".",
"append",
"(",
"TrivialLayout",
"(",
"coupling_map",
")",
",",
"condition",
"=",
"lambda",
"property_set",
":",
"not",
"property_set",
"[",
"'layout'",
"]",
")",
"# if the circuit and layout already satisfy the coupling_constraints, use that layout",
"# otherwise layout on the most densely connected physical qubit subset",
"pass_manager",
".",
"append",
"(",
"CheckMap",
"(",
"coupling_map",
")",
")",
"pass_manager",
".",
"append",
"(",
"DenseLayout",
"(",
"coupling_map",
")",
",",
"condition",
"=",
"lambda",
"property_set",
":",
"not",
"property_set",
"[",
"'is_swap_mapped'",
"]",
")",
"# Extend the the dag/layout with ancillas using the full coupling map",
"pass_manager",
".",
"append",
"(",
"FullAncillaAllocation",
"(",
"coupling_map",
")",
")",
"pass_manager",
".",
"append",
"(",
"EnlargeWithAncilla",
"(",
")",
")",
"# Circuit must only contain 1- or 2-qubit interactions for swapper to work",
"pass_manager",
".",
"append",
"(",
"Unroll3qOrMore",
"(",
")",
")",
"# Swap mapper",
"pass_manager",
".",
"append",
"(",
"LegacySwap",
"(",
"coupling_map",
",",
"trials",
"=",
"20",
",",
"seed",
"=",
"seed_transpiler",
")",
")",
"# Expand swaps",
"pass_manager",
".",
"append",
"(",
"Decompose",
"(",
"SwapGate",
")",
")",
"# Change CX directions",
"pass_manager",
".",
"append",
"(",
"CXDirection",
"(",
"coupling_map",
")",
")",
"# Unroll to the basis",
"pass_manager",
".",
"append",
"(",
"Unroller",
"(",
"[",
"'u1'",
",",
"'u2'",
",",
"'u3'",
",",
"'id'",
",",
"'cx'",
"]",
")",
")",
"# Simplify single qubit gates and CXs",
"simplification_passes",
"=",
"[",
"Optimize1qGates",
"(",
")",
",",
"CXCancellation",
"(",
")",
",",
"RemoveResetInZeroState",
"(",
")",
"]",
"pass_manager",
".",
"append",
"(",
"simplification_passes",
"+",
"[",
"Depth",
"(",
")",
",",
"FixedPoint",
"(",
"'depth'",
")",
"]",
",",
"do_while",
"=",
"lambda",
"property_set",
":",
"not",
"property_set",
"[",
"'depth_fixed_point'",
"]",
")",
"return",
"pass_manager"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
default_pass_manager_simulator
|
The default pass manager without a coupling map.
Args:
basis_gates (list[str]): list of basis gate names to unroll to.
Returns:
PassManager: A passmanager that just unrolls, without any optimization.
|
qiskit/transpiler/preset_passmanagers/default.py
|
def default_pass_manager_simulator(basis_gates):
"""
The default pass manager without a coupling map.
Args:
basis_gates (list[str]): list of basis gate names to unroll to.
Returns:
PassManager: A passmanager that just unrolls, without any optimization.
"""
pass_manager = PassManager()
pass_manager.append(Unroller(basis_gates))
pass_manager.append([RemoveResetInZeroState(), Depth(), FixedPoint('depth')],
do_while=lambda property_set: not property_set['depth_fixed_point'])
return pass_manager
|
def default_pass_manager_simulator(basis_gates):
"""
The default pass manager without a coupling map.
Args:
basis_gates (list[str]): list of basis gate names to unroll to.
Returns:
PassManager: A passmanager that just unrolls, without any optimization.
"""
pass_manager = PassManager()
pass_manager.append(Unroller(basis_gates))
pass_manager.append([RemoveResetInZeroState(), Depth(), FixedPoint('depth')],
do_while=lambda property_set: not property_set['depth_fixed_point'])
return pass_manager
|
[
"The",
"default",
"pass",
"manager",
"without",
"a",
"coupling",
"map",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/preset_passmanagers/default.py#L86-L103
|
[
"def",
"default_pass_manager_simulator",
"(",
"basis_gates",
")",
":",
"pass_manager",
"=",
"PassManager",
"(",
")",
"pass_manager",
".",
"append",
"(",
"Unroller",
"(",
"basis_gates",
")",
")",
"pass_manager",
".",
"append",
"(",
"[",
"RemoveResetInZeroState",
"(",
")",
",",
"Depth",
"(",
")",
",",
"FixedPoint",
"(",
"'depth'",
")",
"]",
",",
"do_while",
"=",
"lambda",
"property_set",
":",
"not",
"property_set",
"[",
"'depth_fixed_point'",
"]",
")",
"return",
"pass_manager"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
QuantumCircuit.has_register
|
Test if this circuit has the register r.
Args:
register (Register): a quantum or classical register.
Returns:
bool: True if the register is contained in this circuit.
|
qiskit/circuit/quantumcircuit.py
|
def has_register(self, register):
"""
Test if this circuit has the register r.
Args:
register (Register): a quantum or classical register.
Returns:
bool: True if the register is contained in this circuit.
"""
has_reg = False
if (isinstance(register, QuantumRegister) and
register in self.qregs):
has_reg = True
elif (isinstance(register, ClassicalRegister) and
register in self.cregs):
has_reg = True
return has_reg
|
def has_register(self, register):
"""
Test if this circuit has the register r.
Args:
register (Register): a quantum or classical register.
Returns:
bool: True if the register is contained in this circuit.
"""
has_reg = False
if (isinstance(register, QuantumRegister) and
register in self.qregs):
has_reg = True
elif (isinstance(register, ClassicalRegister) and
register in self.cregs):
has_reg = True
return has_reg
|
[
"Test",
"if",
"this",
"circuit",
"has",
"the",
"register",
"r",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L104-L121
|
[
"def",
"has_register",
"(",
"self",
",",
"register",
")",
":",
"has_reg",
"=",
"False",
"if",
"(",
"isinstance",
"(",
"register",
",",
"QuantumRegister",
")",
"and",
"register",
"in",
"self",
".",
"qregs",
")",
":",
"has_reg",
"=",
"True",
"elif",
"(",
"isinstance",
"(",
"register",
",",
"ClassicalRegister",
")",
"and",
"register",
"in",
"self",
".",
"cregs",
")",
":",
"has_reg",
"=",
"True",
"return",
"has_reg"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
QuantumCircuit.mirror
|
Mirror the circuit by reversing the instructions.
This is done by recursively mirroring all instructions.
It does not invert any gate.
Returns:
QuantumCircuit: the mirrored circuit
|
qiskit/circuit/quantumcircuit.py
|
def mirror(self):
"""Mirror the circuit by reversing the instructions.
This is done by recursively mirroring all instructions.
It does not invert any gate.
Returns:
QuantumCircuit: the mirrored circuit
"""
reverse_circ = self.copy(name=self.name+'_mirror')
reverse_circ.data = []
for inst, qargs, cargs in reversed(self.data):
reverse_circ.data.append((inst.mirror(), qargs, cargs))
return reverse_circ
|
def mirror(self):
"""Mirror the circuit by reversing the instructions.
This is done by recursively mirroring all instructions.
It does not invert any gate.
Returns:
QuantumCircuit: the mirrored circuit
"""
reverse_circ = self.copy(name=self.name+'_mirror')
reverse_circ.data = []
for inst, qargs, cargs in reversed(self.data):
reverse_circ.data.append((inst.mirror(), qargs, cargs))
return reverse_circ
|
[
"Mirror",
"the",
"circuit",
"by",
"reversing",
"the",
"instructions",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L123-L136
|
[
"def",
"mirror",
"(",
"self",
")",
":",
"reverse_circ",
"=",
"self",
".",
"copy",
"(",
"name",
"=",
"self",
".",
"name",
"+",
"'_mirror'",
")",
"reverse_circ",
".",
"data",
"=",
"[",
"]",
"for",
"inst",
",",
"qargs",
",",
"cargs",
"in",
"reversed",
"(",
"self",
".",
"data",
")",
":",
"reverse_circ",
".",
"data",
".",
"append",
"(",
"(",
"inst",
".",
"mirror",
"(",
")",
",",
"qargs",
",",
"cargs",
")",
")",
"return",
"reverse_circ"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
QuantumCircuit.inverse
|
Invert this circuit.
This is done by recursively inverting all gates.
Returns:
QuantumCircuit: the inverted circuit
Raises:
QiskitError: if the circuit cannot be inverted.
|
qiskit/circuit/quantumcircuit.py
|
def inverse(self):
"""Invert this circuit.
This is done by recursively inverting all gates.
Returns:
QuantumCircuit: the inverted circuit
Raises:
QiskitError: if the circuit cannot be inverted.
"""
inverse_circ = self.copy(name=self.name+'_dg')
inverse_circ.data = []
for inst, qargs, cargs in reversed(self.data):
inverse_circ.data.append((inst.inverse(), qargs, cargs))
return inverse_circ
|
def inverse(self):
"""Invert this circuit.
This is done by recursively inverting all gates.
Returns:
QuantumCircuit: the inverted circuit
Raises:
QiskitError: if the circuit cannot be inverted.
"""
inverse_circ = self.copy(name=self.name+'_dg')
inverse_circ.data = []
for inst, qargs, cargs in reversed(self.data):
inverse_circ.data.append((inst.inverse(), qargs, cargs))
return inverse_circ
|
[
"Invert",
"this",
"circuit",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L138-L153
|
[
"def",
"inverse",
"(",
"self",
")",
":",
"inverse_circ",
"=",
"self",
".",
"copy",
"(",
"name",
"=",
"self",
".",
"name",
"+",
"'_dg'",
")",
"inverse_circ",
".",
"data",
"=",
"[",
"]",
"for",
"inst",
",",
"qargs",
",",
"cargs",
"in",
"reversed",
"(",
"self",
".",
"data",
")",
":",
"inverse_circ",
".",
"data",
".",
"append",
"(",
"(",
"inst",
".",
"inverse",
"(",
")",
",",
"qargs",
",",
"cargs",
")",
")",
"return",
"inverse_circ"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
QuantumCircuit.combine
|
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Return self + rhs as a new object.
|
qiskit/circuit/quantumcircuit.py
|
def combine(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Return self + rhs as a new object.
"""
# Check registers in LHS are compatible with RHS
self._check_compatible_regs(rhs)
# Make new circuit with combined registers
combined_qregs = deepcopy(self.qregs)
combined_cregs = deepcopy(self.cregs)
for element in rhs.qregs:
if element not in self.qregs:
combined_qregs.append(element)
for element in rhs.cregs:
if element not in self.cregs:
combined_cregs.append(element)
circuit = QuantumCircuit(*combined_qregs, *combined_cregs)
for instruction_context in itertools.chain(self.data, rhs.data):
circuit.append(*instruction_context)
return circuit
|
def combine(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Return self + rhs as a new object.
"""
# Check registers in LHS are compatible with RHS
self._check_compatible_regs(rhs)
# Make new circuit with combined registers
combined_qregs = deepcopy(self.qregs)
combined_cregs = deepcopy(self.cregs)
for element in rhs.qregs:
if element not in self.qregs:
combined_qregs.append(element)
for element in rhs.cregs:
if element not in self.cregs:
combined_cregs.append(element)
circuit = QuantumCircuit(*combined_qregs, *combined_cregs)
for instruction_context in itertools.chain(self.data, rhs.data):
circuit.append(*instruction_context)
return circuit
|
[
"Append",
"rhs",
"to",
"self",
"if",
"self",
"contains",
"compatible",
"registers",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L155-L182
|
[
"def",
"combine",
"(",
"self",
",",
"rhs",
")",
":",
"# Check registers in LHS are compatible with RHS",
"self",
".",
"_check_compatible_regs",
"(",
"rhs",
")",
"# Make new circuit with combined registers",
"combined_qregs",
"=",
"deepcopy",
"(",
"self",
".",
"qregs",
")",
"combined_cregs",
"=",
"deepcopy",
"(",
"self",
".",
"cregs",
")",
"for",
"element",
"in",
"rhs",
".",
"qregs",
":",
"if",
"element",
"not",
"in",
"self",
".",
"qregs",
":",
"combined_qregs",
".",
"append",
"(",
"element",
")",
"for",
"element",
"in",
"rhs",
".",
"cregs",
":",
"if",
"element",
"not",
"in",
"self",
".",
"cregs",
":",
"combined_cregs",
".",
"append",
"(",
"element",
")",
"circuit",
"=",
"QuantumCircuit",
"(",
"*",
"combined_qregs",
",",
"*",
"combined_cregs",
")",
"for",
"instruction_context",
"in",
"itertools",
".",
"chain",
"(",
"self",
".",
"data",
",",
"rhs",
".",
"data",
")",
":",
"circuit",
".",
"append",
"(",
"*",
"instruction_context",
")",
"return",
"circuit"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
QuantumCircuit.extend
|
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Modify and return self.
|
qiskit/circuit/quantumcircuit.py
|
def extend(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Modify and return self.
"""
# Check registers in LHS are compatible with RHS
self._check_compatible_regs(rhs)
# Add new registers
for element in rhs.qregs:
if element not in self.qregs:
self.qregs.append(element)
for element in rhs.cregs:
if element not in self.cregs:
self.cregs.append(element)
# Add new gates
for instruction_context in rhs.data:
self.append(*instruction_context)
return self
|
def extend(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Modify and return self.
"""
# Check registers in LHS are compatible with RHS
self._check_compatible_regs(rhs)
# Add new registers
for element in rhs.qregs:
if element not in self.qregs:
self.qregs.append(element)
for element in rhs.cregs:
if element not in self.cregs:
self.cregs.append(element)
# Add new gates
for instruction_context in rhs.data:
self.append(*instruction_context)
return self
|
[
"Append",
"rhs",
"to",
"self",
"if",
"self",
"contains",
"compatible",
"registers",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L184-L209
|
[
"def",
"extend",
"(",
"self",
",",
"rhs",
")",
":",
"# Check registers in LHS are compatible with RHS",
"self",
".",
"_check_compatible_regs",
"(",
"rhs",
")",
"# Add new registers",
"for",
"element",
"in",
"rhs",
".",
"qregs",
":",
"if",
"element",
"not",
"in",
"self",
".",
"qregs",
":",
"self",
".",
"qregs",
".",
"append",
"(",
"element",
")",
"for",
"element",
"in",
"rhs",
".",
"cregs",
":",
"if",
"element",
"not",
"in",
"self",
".",
"cregs",
":",
"self",
".",
"cregs",
".",
"append",
"(",
"element",
")",
"# Add new gates",
"for",
"instruction_context",
"in",
"rhs",
".",
"data",
":",
"self",
".",
"append",
"(",
"*",
"instruction_context",
")",
"return",
"self"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
QuantumCircuit.append
|
Append an instruction to the end of the circuit, modifying
the circuit in place.
Args:
instruction (Instruction or Operator): Instruction instance to append
qargs (list(tuple)): qubits to attach instruction to
cargs (list(tuple)): clbits to attach instruction to
Returns:
Instruction: a handle to the instruction that was just added
Raises:
QiskitError: if the gate is of a different shape than the wires
it is being attached to.
|
qiskit/circuit/quantumcircuit.py
|
def append(self, instruction, qargs=None, cargs=None):
"""Append an instruction to the end of the circuit, modifying
the circuit in place.
Args:
instruction (Instruction or Operator): Instruction instance to append
qargs (list(tuple)): qubits to attach instruction to
cargs (list(tuple)): clbits to attach instruction to
Returns:
Instruction: a handle to the instruction that was just added
Raises:
QiskitError: if the gate is of a different shape than the wires
it is being attached to.
"""
qargs = qargs or []
cargs = cargs or []
# Convert input to instruction
if not isinstance(instruction, Instruction) and hasattr(instruction, 'to_instruction'):
instruction = instruction.to_instruction()
if not isinstance(instruction, Instruction):
raise QiskitError('object is not an Instruction.')
# do some compatibility checks
self._check_dups(qargs)
self._check_qargs(qargs)
self._check_cargs(cargs)
if instruction.num_qubits != len(qargs) or \
instruction.num_clbits != len(cargs):
raise QiskitError("instruction %s with %d qubits and %d clbits "
"cannot be appended onto %d qubits and %d clbits." %
(instruction.name,
instruction.num_qubits, instruction.num_clbits,
len(qargs), len(cargs)))
# add the instruction onto the given wires
instruction_context = instruction, qargs, cargs
self.data.append(instruction_context)
# track variable parameters in instruction
for param_index, param in enumerate(instruction.params):
if isinstance(param, Parameter):
current_symbols = self.parameters
if param in current_symbols:
self._parameter_table[param].append((instruction, param_index))
else:
self._parameter_table[param] = [(instruction, param_index)]
return instruction
|
def append(self, instruction, qargs=None, cargs=None):
"""Append an instruction to the end of the circuit, modifying
the circuit in place.
Args:
instruction (Instruction or Operator): Instruction instance to append
qargs (list(tuple)): qubits to attach instruction to
cargs (list(tuple)): clbits to attach instruction to
Returns:
Instruction: a handle to the instruction that was just added
Raises:
QiskitError: if the gate is of a different shape than the wires
it is being attached to.
"""
qargs = qargs or []
cargs = cargs or []
# Convert input to instruction
if not isinstance(instruction, Instruction) and hasattr(instruction, 'to_instruction'):
instruction = instruction.to_instruction()
if not isinstance(instruction, Instruction):
raise QiskitError('object is not an Instruction.')
# do some compatibility checks
self._check_dups(qargs)
self._check_qargs(qargs)
self._check_cargs(cargs)
if instruction.num_qubits != len(qargs) or \
instruction.num_clbits != len(cargs):
raise QiskitError("instruction %s with %d qubits and %d clbits "
"cannot be appended onto %d qubits and %d clbits." %
(instruction.name,
instruction.num_qubits, instruction.num_clbits,
len(qargs), len(cargs)))
# add the instruction onto the given wires
instruction_context = instruction, qargs, cargs
self.data.append(instruction_context)
# track variable parameters in instruction
for param_index, param in enumerate(instruction.params):
if isinstance(param, Parameter):
current_symbols = self.parameters
if param in current_symbols:
self._parameter_table[param].append((instruction, param_index))
else:
self._parameter_table[param] = [(instruction, param_index)]
return instruction
|
[
"Append",
"an",
"instruction",
"to",
"the",
"end",
"of",
"the",
"circuit",
"modifying",
"the",
"circuit",
"in",
"place",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L239-L290
|
[
"def",
"append",
"(",
"self",
",",
"instruction",
",",
"qargs",
"=",
"None",
",",
"cargs",
"=",
"None",
")",
":",
"qargs",
"=",
"qargs",
"or",
"[",
"]",
"cargs",
"=",
"cargs",
"or",
"[",
"]",
"# Convert input to instruction",
"if",
"not",
"isinstance",
"(",
"instruction",
",",
"Instruction",
")",
"and",
"hasattr",
"(",
"instruction",
",",
"'to_instruction'",
")",
":",
"instruction",
"=",
"instruction",
".",
"to_instruction",
"(",
")",
"if",
"not",
"isinstance",
"(",
"instruction",
",",
"Instruction",
")",
":",
"raise",
"QiskitError",
"(",
"'object is not an Instruction.'",
")",
"# do some compatibility checks",
"self",
".",
"_check_dups",
"(",
"qargs",
")",
"self",
".",
"_check_qargs",
"(",
"qargs",
")",
"self",
".",
"_check_cargs",
"(",
"cargs",
")",
"if",
"instruction",
".",
"num_qubits",
"!=",
"len",
"(",
"qargs",
")",
"or",
"instruction",
".",
"num_clbits",
"!=",
"len",
"(",
"cargs",
")",
":",
"raise",
"QiskitError",
"(",
"\"instruction %s with %d qubits and %d clbits \"",
"\"cannot be appended onto %d qubits and %d clbits.\"",
"%",
"(",
"instruction",
".",
"name",
",",
"instruction",
".",
"num_qubits",
",",
"instruction",
".",
"num_clbits",
",",
"len",
"(",
"qargs",
")",
",",
"len",
"(",
"cargs",
")",
")",
")",
"# add the instruction onto the given wires",
"instruction_context",
"=",
"instruction",
",",
"qargs",
",",
"cargs",
"self",
".",
"data",
".",
"append",
"(",
"instruction_context",
")",
"# track variable parameters in instruction",
"for",
"param_index",
",",
"param",
"in",
"enumerate",
"(",
"instruction",
".",
"params",
")",
":",
"if",
"isinstance",
"(",
"param",
",",
"Parameter",
")",
":",
"current_symbols",
"=",
"self",
".",
"parameters",
"if",
"param",
"in",
"current_symbols",
":",
"self",
".",
"_parameter_table",
"[",
"param",
"]",
".",
"append",
"(",
"(",
"instruction",
",",
"param_index",
")",
")",
"else",
":",
"self",
".",
"_parameter_table",
"[",
"param",
"]",
"=",
"[",
"(",
"instruction",
",",
"param_index",
")",
"]",
"return",
"instruction"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
QuantumCircuit._attach
|
DEPRECATED after 0.8
|
qiskit/circuit/quantumcircuit.py
|
def _attach(self, instruction, qargs, cargs):
"""DEPRECATED after 0.8"""
self.append(instruction, qargs, cargs)
|
def _attach(self, instruction, qargs, cargs):
"""DEPRECATED after 0.8"""
self.append(instruction, qargs, cargs)
|
[
"DEPRECATED",
"after",
"0",
".",
"8"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L292-L294
|
[
"def",
"_attach",
"(",
"self",
",",
"instruction",
",",
"qargs",
",",
"cargs",
")",
":",
"self",
".",
"append",
"(",
"instruction",
",",
"qargs",
",",
"cargs",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.