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
single_gate_matrix
Get the matrix for a single qubit. Args: gate(str): the single qubit gate name params(list): the operation parameters op['params'] Returns: array: A numpy array representing the matrix
qiskit/providers/basicaer/basicaertools.py
def single_gate_matrix(gate, params=None): """Get the matrix for a single qubit. Args: gate(str): the single qubit gate name params(list): the operation parameters op['params'] Returns: array: A numpy array representing the matrix """ # Converting sym to floats improves the performance of the simulator 10x. # This a is a probable a FIXME since it might show bugs in the simulator. (theta, phi, lam) = map(float, single_gate_params(gate, params)) return np.array([[np.cos(theta / 2), -np.exp(1j * lam) * np.sin(theta / 2)], [np.exp(1j * phi) * np.sin(theta / 2), np.exp(1j * phi + 1j * lam) * np.cos(theta / 2)]])
def single_gate_matrix(gate, params=None): """Get the matrix for a single qubit. Args: gate(str): the single qubit gate name params(list): the operation parameters op['params'] Returns: array: A numpy array representing the matrix """ # Converting sym to floats improves the performance of the simulator 10x. # This a is a probable a FIXME since it might show bugs in the simulator. (theta, phi, lam) = map(float, single_gate_params(gate, params)) return np.array([[np.cos(theta / 2), -np.exp(1j * lam) * np.sin(theta / 2)], [np.exp(1j * phi) * np.sin(theta / 2), np.exp(1j * phi + 1j * lam) * np.cos(theta / 2)]])
[ "Get", "the", "matrix", "for", "a", "single", "qubit", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/basicaertools.py#L41-L58
[ "def", "single_gate_matrix", "(", "gate", ",", "params", "=", "None", ")", ":", "# Converting sym to floats improves the performance of the simulator 10x.", "# This a is a probable a FIXME since it might show bugs in the simulator.", "(", "theta", ",", "phi", ",", "lam", ")", "=", "map", "(", "float", ",", "single_gate_params", "(", "gate", ",", "params", ")", ")", "return", "np", ".", "array", "(", "[", "[", "np", ".", "cos", "(", "theta", "/", "2", ")", ",", "-", "np", ".", "exp", "(", "1j", "*", "lam", ")", "*", "np", ".", "sin", "(", "theta", "/", "2", ")", "]", ",", "[", "np", ".", "exp", "(", "1j", "*", "phi", ")", "*", "np", ".", "sin", "(", "theta", "/", "2", ")", ",", "np", ".", "exp", "(", "1j", "*", "phi", "+", "1j", "*", "lam", ")", "*", "np", ".", "cos", "(", "theta", "/", "2", ")", "]", "]", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
einsum_matmul_index
Return the index string for Numpy.eignsum matrix-matrix multiplication. The returned indices are to perform a matrix multiplication A.B where the matrix A is an M-qubit matrix, matrix B is an N-qubit matrix, and M <= N, and identity matrices are implied on the subsystems where A has no support on B. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: str: An indices string for the Numpy.einsum function.
qiskit/providers/basicaer/basicaertools.py
def einsum_matmul_index(gate_indices, number_of_qubits): """Return the index string for Numpy.eignsum matrix-matrix multiplication. The returned indices are to perform a matrix multiplication A.B where the matrix A is an M-qubit matrix, matrix B is an N-qubit matrix, and M <= N, and identity matrices are implied on the subsystems where A has no support on B. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: str: An indices string for the Numpy.einsum function. """ mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices, number_of_qubits) # Right indices for the N-qubit input and output tensor tens_r = ascii_uppercase[:number_of_qubits] # Combine indices into matrix multiplication string format # for numpy.einsum function return "{mat_l}{mat_r}, ".format(mat_l=mat_l, mat_r=mat_r) + \ "{tens_lin}{tens_r}->{tens_lout}{tens_r}".format(tens_lin=tens_lin, tens_lout=tens_lout, tens_r=tens_r)
def einsum_matmul_index(gate_indices, number_of_qubits): """Return the index string for Numpy.eignsum matrix-matrix multiplication. The returned indices are to perform a matrix multiplication A.B where the matrix A is an M-qubit matrix, matrix B is an N-qubit matrix, and M <= N, and identity matrices are implied on the subsystems where A has no support on B. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: str: An indices string for the Numpy.einsum function. """ mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices, number_of_qubits) # Right indices for the N-qubit input and output tensor tens_r = ascii_uppercase[:number_of_qubits] # Combine indices into matrix multiplication string format # for numpy.einsum function return "{mat_l}{mat_r}, ".format(mat_l=mat_l, mat_r=mat_r) + \ "{tens_lin}{tens_r}->{tens_lout}{tens_r}".format(tens_lin=tens_lin, tens_lout=tens_lout, tens_r=tens_r)
[ "Return", "the", "index", "string", "for", "Numpy", ".", "eignsum", "matrix", "-", "matrix", "multiplication", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/basicaertools.py#L69-L97
[ "def", "einsum_matmul_index", "(", "gate_indices", ",", "number_of_qubits", ")", ":", "mat_l", ",", "mat_r", ",", "tens_lin", ",", "tens_lout", "=", "_einsum_matmul_index_helper", "(", "gate_indices", ",", "number_of_qubits", ")", "# Right indices for the N-qubit input and output tensor", "tens_r", "=", "ascii_uppercase", "[", ":", "number_of_qubits", "]", "# Combine indices into matrix multiplication string format", "# for numpy.einsum function", "return", "\"{mat_l}{mat_r}, \"", ".", "format", "(", "mat_l", "=", "mat_l", ",", "mat_r", "=", "mat_r", ")", "+", "\"{tens_lin}{tens_r}->{tens_lout}{tens_r}\"", ".", "format", "(", "tens_lin", "=", "tens_lin", ",", "tens_lout", "=", "tens_lout", ",", "tens_r", "=", "tens_r", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
einsum_vecmul_index
Return the index string for Numpy.eignsum matrix-vector multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, vector v is an N-qubit vector, and M <= N, and identity matrices are implied on the subsystems where A has no support on v. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: str: An indices string for the Numpy.einsum function.
qiskit/providers/basicaer/basicaertools.py
def einsum_vecmul_index(gate_indices, number_of_qubits): """Return the index string for Numpy.eignsum matrix-vector multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, vector v is an N-qubit vector, and M <= N, and identity matrices are implied on the subsystems where A has no support on v. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: str: An indices string for the Numpy.einsum function. """ mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices, number_of_qubits) # Combine indices into matrix multiplication string format # for numpy.einsum function return "{mat_l}{mat_r}, ".format(mat_l=mat_l, mat_r=mat_r) + \ "{tens_lin}->{tens_lout}".format(tens_lin=tens_lin, tens_lout=tens_lout)
def einsum_vecmul_index(gate_indices, number_of_qubits): """Return the index string for Numpy.eignsum matrix-vector multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, vector v is an N-qubit vector, and M <= N, and identity matrices are implied on the subsystems where A has no support on v. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: str: An indices string for the Numpy.einsum function. """ mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices, number_of_qubits) # Combine indices into matrix multiplication string format # for numpy.einsum function return "{mat_l}{mat_r}, ".format(mat_l=mat_l, mat_r=mat_r) + \ "{tens_lin}->{tens_lout}".format(tens_lin=tens_lin, tens_lout=tens_lout)
[ "Return", "the", "index", "string", "for", "Numpy", ".", "eignsum", "matrix", "-", "vector", "multiplication", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/basicaertools.py#L100-L124
[ "def", "einsum_vecmul_index", "(", "gate_indices", ",", "number_of_qubits", ")", ":", "mat_l", ",", "mat_r", ",", "tens_lin", ",", "tens_lout", "=", "_einsum_matmul_index_helper", "(", "gate_indices", ",", "number_of_qubits", ")", "# Combine indices into matrix multiplication string format", "# for numpy.einsum function", "return", "\"{mat_l}{mat_r}, \"", ".", "format", "(", "mat_l", "=", "mat_l", ",", "mat_r", "=", "mat_r", ")", "+", "\"{tens_lin}->{tens_lout}\"", ".", "format", "(", "tens_lin", "=", "tens_lin", ",", "tens_lout", "=", "tens_lout", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_einsum_matmul_index_helper
Return the index string for Numpy.eignsum matrix multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, matrix v is an N-qubit vector, and M <= N, and identity matrices are implied on the subsystems where A has no support on v. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: tuple: (mat_left, mat_right, tens_in, tens_out) of index strings for that may be combined into a Numpy.einsum function string. Raises: QiskitError: if the total number of qubits plus the number of contracted indices is greater than 26.
qiskit/providers/basicaer/basicaertools.py
def _einsum_matmul_index_helper(gate_indices, number_of_qubits): """Return the index string for Numpy.eignsum matrix multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, matrix v is an N-qubit vector, and M <= N, and identity matrices are implied on the subsystems where A has no support on v. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: tuple: (mat_left, mat_right, tens_in, tens_out) of index strings for that may be combined into a Numpy.einsum function string. Raises: QiskitError: if the total number of qubits plus the number of contracted indices is greater than 26. """ # Since we use ASCII alphabet for einsum index labels we are limited # to 26 total free left (lowercase) and 26 right (uppercase) indexes. # The rank of the contracted tensor reduces this as we need to use that # many characters for the contracted indices if len(gate_indices) + number_of_qubits > 26: raise QiskitError("Total number of free indexes limited to 26") # Indicies for N-qubit input tensor tens_in = ascii_lowercase[:number_of_qubits] # Indices for the N-qubit output tensor tens_out = list(tens_in) # Left and right indices for the M-qubit multiplying tensor mat_left = "" mat_right = "" # Update left indices for mat and output for pos, idx in enumerate(reversed(gate_indices)): mat_left += ascii_lowercase[-1 - pos] mat_right += tens_in[-1 - idx] tens_out[-1 - idx] = ascii_lowercase[-1 - pos] tens_out = "".join(tens_out) # Combine indices into matrix multiplication string format # for numpy.einsum function return mat_left, mat_right, tens_in, tens_out
def _einsum_matmul_index_helper(gate_indices, number_of_qubits): """Return the index string for Numpy.eignsum matrix multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, matrix v is an N-qubit vector, and M <= N, and identity matrices are implied on the subsystems where A has no support on v. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: tuple: (mat_left, mat_right, tens_in, tens_out) of index strings for that may be combined into a Numpy.einsum function string. Raises: QiskitError: if the total number of qubits plus the number of contracted indices is greater than 26. """ # Since we use ASCII alphabet for einsum index labels we are limited # to 26 total free left (lowercase) and 26 right (uppercase) indexes. # The rank of the contracted tensor reduces this as we need to use that # many characters for the contracted indices if len(gate_indices) + number_of_qubits > 26: raise QiskitError("Total number of free indexes limited to 26") # Indicies for N-qubit input tensor tens_in = ascii_lowercase[:number_of_qubits] # Indices for the N-qubit output tensor tens_out = list(tens_in) # Left and right indices for the M-qubit multiplying tensor mat_left = "" mat_right = "" # Update left indices for mat and output for pos, idx in enumerate(reversed(gate_indices)): mat_left += ascii_lowercase[-1 - pos] mat_right += tens_in[-1 - idx] tens_out[-1 - idx] = ascii_lowercase[-1 - pos] tens_out = "".join(tens_out) # Combine indices into matrix multiplication string format # for numpy.einsum function return mat_left, mat_right, tens_in, tens_out
[ "Return", "the", "index", "string", "for", "Numpy", ".", "eignsum", "matrix", "multiplication", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/basicaertools.py#L127-L175
[ "def", "_einsum_matmul_index_helper", "(", "gate_indices", ",", "number_of_qubits", ")", ":", "# Since we use ASCII alphabet for einsum index labels we are limited", "# to 26 total free left (lowercase) and 26 right (uppercase) indexes.", "# The rank of the contracted tensor reduces this as we need to use that", "# many characters for the contracted indices", "if", "len", "(", "gate_indices", ")", "+", "number_of_qubits", ">", "26", ":", "raise", "QiskitError", "(", "\"Total number of free indexes limited to 26\"", ")", "# Indicies for N-qubit input tensor", "tens_in", "=", "ascii_lowercase", "[", ":", "number_of_qubits", "]", "# Indices for the N-qubit output tensor", "tens_out", "=", "list", "(", "tens_in", ")", "# Left and right indices for the M-qubit multiplying tensor", "mat_left", "=", "\"\"", "mat_right", "=", "\"\"", "# Update left indices for mat and output", "for", "pos", ",", "idx", "in", "enumerate", "(", "reversed", "(", "gate_indices", ")", ")", ":", "mat_left", "+=", "ascii_lowercase", "[", "-", "1", "-", "pos", "]", "mat_right", "+=", "tens_in", "[", "-", "1", "-", "idx", "]", "tens_out", "[", "-", "1", "-", "idx", "]", "=", "ascii_lowercase", "[", "-", "1", "-", "pos", "]", "tens_out", "=", "\"\"", ".", "join", "(", "tens_out", ")", "# Combine indices into matrix multiplication string format", "# for numpy.einsum function", "return", "mat_left", ",", "mat_right", ",", "tens_in", ",", "tens_out" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
circuit_to_dag
Build a ``DAGCircuit`` object from a ``QuantumCircuit``. Args: circuit (QuantumCircuit): the input circuit. Return: DAGCircuit: the DAG representing the input circuit.
qiskit/converters/circuit_to_dag.py
def circuit_to_dag(circuit): """Build a ``DAGCircuit`` object from a ``QuantumCircuit``. Args: circuit (QuantumCircuit): the input circuit. Return: DAGCircuit: the DAG representing the input circuit. """ dagcircuit = DAGCircuit() dagcircuit.name = circuit.name for register in circuit.qregs: dagcircuit.add_qreg(register) for register in circuit.cregs: dagcircuit.add_creg(register) for instruction, qargs, cargs in circuit.data: # Get arguments for classical control (if any) if instruction.control is None: control = None else: control = (instruction.control[0], instruction.control[1]) dagcircuit.apply_operation_back(instruction.copy(), qargs, cargs, control) return dagcircuit
def circuit_to_dag(circuit): """Build a ``DAGCircuit`` object from a ``QuantumCircuit``. Args: circuit (QuantumCircuit): the input circuit. Return: DAGCircuit: the DAG representing the input circuit. """ dagcircuit = DAGCircuit() dagcircuit.name = circuit.name for register in circuit.qregs: dagcircuit.add_qreg(register) for register in circuit.cregs: dagcircuit.add_creg(register) for instruction, qargs, cargs in circuit.data: # Get arguments for classical control (if any) if instruction.control is None: control = None else: control = (instruction.control[0], instruction.control[1]) dagcircuit.apply_operation_back(instruction.copy(), qargs, cargs, control) return dagcircuit
[ "Build", "a", "DAGCircuit", "object", "from", "a", "QuantumCircuit", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/converters/circuit_to_dag.py#L13-L39
[ "def", "circuit_to_dag", "(", "circuit", ")", ":", "dagcircuit", "=", "DAGCircuit", "(", ")", "dagcircuit", ".", "name", "=", "circuit", ".", "name", "for", "register", "in", "circuit", ".", "qregs", ":", "dagcircuit", ".", "add_qreg", "(", "register", ")", "for", "register", "in", "circuit", ".", "cregs", ":", "dagcircuit", ".", "add_creg", "(", "register", ")", "for", "instruction", ",", "qargs", ",", "cargs", "in", "circuit", ".", "data", ":", "# Get arguments for classical control (if any)", "if", "instruction", ".", "control", "is", "None", ":", "control", "=", "None", "else", ":", "control", "=", "(", "instruction", ".", "control", "[", "0", "]", ",", "instruction", ".", "control", "[", "1", "]", ")", "dagcircuit", ".", "apply_operation_back", "(", "instruction", ".", "copy", "(", ")", ",", "qargs", ",", "cargs", ",", "control", ")", "return", "dagcircuit" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
exp_fit_fun
Function used to fit the exponential decay.
qiskit/tools/qcvv/fitters.py
def exp_fit_fun(x, a, tau, c): """Function used to fit the exponential decay.""" # pylint: disable=invalid-name return a * np.exp(-x / tau) + c
def exp_fit_fun(x, a, tau, c): """Function used to fit the exponential decay.""" # pylint: disable=invalid-name return a * np.exp(-x / tau) + c
[ "Function", "used", "to", "fit", "the", "exponential", "decay", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qcvv/fitters.py#L23-L26
[ "def", "exp_fit_fun", "(", "x", ",", "a", ",", "tau", ",", "c", ")", ":", "# pylint: disable=invalid-name", "return", "a", "*", "np", ".", "exp", "(", "-", "x", "/", "tau", ")", "+", "c" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
osc_fit_fun
Function used to fit the decay cosine.
qiskit/tools/qcvv/fitters.py
def osc_fit_fun(x, a, tau, f, phi, c): """Function used to fit the decay cosine.""" # pylint: disable=invalid-name return a * np.exp(-x / tau) * np.cos(2 * np.pi * f * x + phi) + c
def osc_fit_fun(x, a, tau, f, phi, c): """Function used to fit the decay cosine.""" # pylint: disable=invalid-name return a * np.exp(-x / tau) * np.cos(2 * np.pi * f * x + phi) + c
[ "Function", "used", "to", "fit", "the", "decay", "cosine", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qcvv/fitters.py#L29-L32
[ "def", "osc_fit_fun", "(", "x", ",", "a", ",", "tau", ",", "f", ",", "phi", ",", "c", ")", ":", "# pylint: disable=invalid-name", "return", "a", "*", "np", ".", "exp", "(", "-", "x", "/", "tau", ")", "*", "np", ".", "cos", "(", "2", "*", "np", ".", "pi", "*", "f", "*", "x", "+", "phi", ")", "+", "c" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
plot_coherence
Plot coherence data. Args: xdata ydata std_error fit fit_function xunit exp_str qubit_label Raises: ImportError: If matplotlib is not installed.
qiskit/tools/qcvv/fitters.py
def plot_coherence(xdata, ydata, std_error, fit, fit_function, xunit, exp_str, qubit_label): """Plot coherence data. Args: xdata ydata std_error fit fit_function xunit exp_str qubit_label Raises: ImportError: If matplotlib is not installed. """ if not HAS_MATPLOTLIB: raise ImportError('The function plot_coherence needs matplotlib. ' 'Run "pip install matplotlib" before.') plt.errorbar(xdata, ydata, std_error, marker='.', markersize=9, c='b', linestyle='') plt.plot(xdata, fit_function(xdata, *fit), c='r', linestyle='--', label=(exp_str + '= %s %s' % (str(round(fit[1])), xunit))) plt.xticks(fontsize=14, rotation=70) plt.yticks(fontsize=14) plt.xlabel('time [%s]' % (xunit), fontsize=16) plt.ylabel('P(1)', fontsize=16) plt.title(exp_str + ' measurement of Q$_{%s}$' % (str(qubit_label)), fontsize=18) plt.legend(fontsize=12) plt.grid(True) plt.show()
def plot_coherence(xdata, ydata, std_error, fit, fit_function, xunit, exp_str, qubit_label): """Plot coherence data. Args: xdata ydata std_error fit fit_function xunit exp_str qubit_label Raises: ImportError: If matplotlib is not installed. """ if not HAS_MATPLOTLIB: raise ImportError('The function plot_coherence needs matplotlib. ' 'Run "pip install matplotlib" before.') plt.errorbar(xdata, ydata, std_error, marker='.', markersize=9, c='b', linestyle='') plt.plot(xdata, fit_function(xdata, *fit), c='r', linestyle='--', label=(exp_str + '= %s %s' % (str(round(fit[1])), xunit))) plt.xticks(fontsize=14, rotation=70) plt.yticks(fontsize=14) plt.xlabel('time [%s]' % (xunit), fontsize=16) plt.ylabel('P(1)', fontsize=16) plt.title(exp_str + ' measurement of Q$_{%s}$' % (str(qubit_label)), fontsize=18) plt.legend(fontsize=12) plt.grid(True) plt.show()
[ "Plot", "coherence", "data", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qcvv/fitters.py#L42-L72
[ "def", "plot_coherence", "(", "xdata", ",", "ydata", ",", "std_error", ",", "fit", ",", "fit_function", ",", "xunit", ",", "exp_str", ",", "qubit_label", ")", ":", "if", "not", "HAS_MATPLOTLIB", ":", "raise", "ImportError", "(", "'The function plot_coherence needs matplotlib. '", "'Run \"pip install matplotlib\" before.'", ")", "plt", ".", "errorbar", "(", "xdata", ",", "ydata", ",", "std_error", ",", "marker", "=", "'.'", ",", "markersize", "=", "9", ",", "c", "=", "'b'", ",", "linestyle", "=", "''", ")", "plt", ".", "plot", "(", "xdata", ",", "fit_function", "(", "xdata", ",", "*", "fit", ")", ",", "c", "=", "'r'", ",", "linestyle", "=", "'--'", ",", "label", "=", "(", "exp_str", "+", "'= %s %s'", "%", "(", "str", "(", "round", "(", "fit", "[", "1", "]", ")", ")", ",", "xunit", ")", ")", ")", "plt", ".", "xticks", "(", "fontsize", "=", "14", ",", "rotation", "=", "70", ")", "plt", ".", "yticks", "(", "fontsize", "=", "14", ")", "plt", ".", "xlabel", "(", "'time [%s]'", "%", "(", "xunit", ")", ",", "fontsize", "=", "16", ")", "plt", ".", "ylabel", "(", "'P(1)'", ",", "fontsize", "=", "16", ")", "plt", ".", "title", "(", "exp_str", "+", "' measurement of Q$_{%s}$'", "%", "(", "str", "(", "qubit_label", ")", ")", ",", "fontsize", "=", "18", ")", "plt", ".", "legend", "(", "fontsize", "=", "12", ")", "plt", ".", "grid", "(", "True", ")", "plt", ".", "show", "(", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
shape_rb_data
Take the raw rb data and convert it into averages and std dev Args: raw_rb (numpy.array): m x n x l list where m is the number of seeds, n is the number of Clifford sequences and l is the number of qubits Return: numpy_array: 2 x n x l list where index 0 is the mean over seeds, 1 is the std dev overseeds
qiskit/tools/qcvv/fitters.py
def shape_rb_data(raw_rb): """Take the raw rb data and convert it into averages and std dev Args: raw_rb (numpy.array): m x n x l list where m is the number of seeds, n is the number of Clifford sequences and l is the number of qubits Return: numpy_array: 2 x n x l list where index 0 is the mean over seeds, 1 is the std dev overseeds """ rb_data = [] rb_data.append(np.mean(raw_rb, 0)) rb_data.append(np.std(raw_rb, 0)) return rb_data
def shape_rb_data(raw_rb): """Take the raw rb data and convert it into averages and std dev Args: raw_rb (numpy.array): m x n x l list where m is the number of seeds, n is the number of Clifford sequences and l is the number of qubits Return: numpy_array: 2 x n x l list where index 0 is the mean over seeds, 1 is the std dev overseeds """ rb_data = [] rb_data.append(np.mean(raw_rb, 0)) rb_data.append(np.std(raw_rb, 0)) return rb_data
[ "Take", "the", "raw", "rb", "data", "and", "convert", "it", "into", "averages", "and", "std", "dev" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qcvv/fitters.py#L75-L90
[ "def", "shape_rb_data", "(", "raw_rb", ")", ":", "rb_data", "=", "[", "]", "rb_data", ".", "append", "(", "np", ".", "mean", "(", "raw_rb", ",", "0", ")", ")", "rb_data", ".", "append", "(", "np", ".", "std", "(", "raw_rb", ",", "0", ")", ")", "return", "rb_data" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
rb_epc
Take the rb fit data and convert it into EPC (error per Clifford) Args: fit (dict): dictionary of the fit quantities (A, alpha, B) with the keys 'qn' where n is the qubit and subkeys 'fit', e.g. {'q0':{'fit': [1, 0, 0.9], 'fiterr': [0, 0, 0]}}} rb_pattern (list): (see randomized benchmarking functions). Pattern which specifies which qubits performing RB with which qubits. E.g. [[1],[0,2]] is Q1 doing 1Q RB simultaneously with Q0/Q2 doing 2Q RB Return: dict: updates the passed in fit dictionary with the epc
qiskit/tools/qcvv/fitters.py
def rb_epc(fit, rb_pattern): """Take the rb fit data and convert it into EPC (error per Clifford) Args: fit (dict): dictionary of the fit quantities (A, alpha, B) with the keys 'qn' where n is the qubit and subkeys 'fit', e.g. {'q0':{'fit': [1, 0, 0.9], 'fiterr': [0, 0, 0]}}} rb_pattern (list): (see randomized benchmarking functions). Pattern which specifies which qubits performing RB with which qubits. E.g. [[1],[0,2]] is Q1 doing 1Q RB simultaneously with Q0/Q2 doing 2Q RB Return: dict: updates the passed in fit dictionary with the epc """ for patterns in rb_pattern: for qubit in patterns: fitalpha = fit['q%d' % qubit]['fit'][1] fitalphaerr = fit['q%d' % qubit]['fiterr'][1] nrb = 2 ** len(patterns) fit['q%d' % qubit]['fit_calcs'] = {} fit['q%d' % qubit]['fit_calcs']['epc'] = [(nrb - 1) / nrb * (1 - fitalpha), fitalphaerr / fitalpha] fit['q%d' % qubit]['fit_calcs']['epc'][1] *= fit['q%d' % qubit]['fit_calcs']['epc'][0] return fit
def rb_epc(fit, rb_pattern): """Take the rb fit data and convert it into EPC (error per Clifford) Args: fit (dict): dictionary of the fit quantities (A, alpha, B) with the keys 'qn' where n is the qubit and subkeys 'fit', e.g. {'q0':{'fit': [1, 0, 0.9], 'fiterr': [0, 0, 0]}}} rb_pattern (list): (see randomized benchmarking functions). Pattern which specifies which qubits performing RB with which qubits. E.g. [[1],[0,2]] is Q1 doing 1Q RB simultaneously with Q0/Q2 doing 2Q RB Return: dict: updates the passed in fit dictionary with the epc """ for patterns in rb_pattern: for qubit in patterns: fitalpha = fit['q%d' % qubit]['fit'][1] fitalphaerr = fit['q%d' % qubit]['fiterr'][1] nrb = 2 ** len(patterns) fit['q%d' % qubit]['fit_calcs'] = {} fit['q%d' % qubit]['fit_calcs']['epc'] = [(nrb - 1) / nrb * (1 - fitalpha), fitalphaerr / fitalpha] fit['q%d' % qubit]['fit_calcs']['epc'][1] *= fit['q%d' % qubit]['fit_calcs']['epc'][0] return fit
[ "Take", "the", "rb", "fit", "data", "and", "convert", "it", "into", "EPC", "(", "error", "per", "Clifford", ")" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qcvv/fitters.py#L93-L119
[ "def", "rb_epc", "(", "fit", ",", "rb_pattern", ")", ":", "for", "patterns", "in", "rb_pattern", ":", "for", "qubit", "in", "patterns", ":", "fitalpha", "=", "fit", "[", "'q%d'", "%", "qubit", "]", "[", "'fit'", "]", "[", "1", "]", "fitalphaerr", "=", "fit", "[", "'q%d'", "%", "qubit", "]", "[", "'fiterr'", "]", "[", "1", "]", "nrb", "=", "2", "**", "len", "(", "patterns", ")", "fit", "[", "'q%d'", "%", "qubit", "]", "[", "'fit_calcs'", "]", "=", "{", "}", "fit", "[", "'q%d'", "%", "qubit", "]", "[", "'fit_calcs'", "]", "[", "'epc'", "]", "=", "[", "(", "nrb", "-", "1", ")", "/", "nrb", "*", "(", "1", "-", "fitalpha", ")", ",", "fitalphaerr", "/", "fitalpha", "]", "fit", "[", "'q%d'", "%", "qubit", "]", "[", "'fit_calcs'", "]", "[", "'epc'", "]", "[", "1", "]", "*=", "fit", "[", "'q%d'", "%", "qubit", "]", "[", "'fit_calcs'", "]", "[", "'epc'", "]", "[", "0", "]", "return", "fit" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
plot_rb_data
Plot randomized benchmarking data. Args: xdata (list): list of subsequence lengths ydatas (list): list of lists of survival probabilities for each sequence yavg (list): mean of the survival probabilities at each sequence length yerr (list): error of the survival fit (list): fit parameters survival_prob (callable): function that computes survival probability ax (Axes or None): plot axis (if passed in) show_plt (bool): display the plot. Raises: ImportError: If matplotlib is not installed.
qiskit/tools/qcvv/fitters.py
def plot_rb_data(xdata, ydatas, yavg, yerr, fit, survival_prob, ax=None, show_plt=True): """Plot randomized benchmarking data. Args: xdata (list): list of subsequence lengths ydatas (list): list of lists of survival probabilities for each sequence yavg (list): mean of the survival probabilities at each sequence length yerr (list): error of the survival fit (list): fit parameters survival_prob (callable): function that computes survival probability ax (Axes or None): plot axis (if passed in) show_plt (bool): display the plot. Raises: ImportError: If matplotlib is not installed. """ # pylint: disable=invalid-name if not HAS_MATPLOTLIB: raise ImportError('The function plot_rb_data needs matplotlib. ' 'Run "pip install matplotlib" before.') if ax is None: plt.figure() ax = plt.gca() # Plot the result for each sequence for ydata in ydatas: ax.plot(xdata, ydata, color='gray', linestyle='none', marker='x') # Plot the mean with error bars ax.errorbar(xdata, yavg, yerr=yerr, color='r', linestyle='--', linewidth=3) # Plot the fit ax.plot(xdata, survival_prob(xdata, *fit), color='blue', linestyle='-', linewidth=2) ax.tick_params(labelsize=14) # ax.tick_params(axis='x',labelrotation=70) ax.set_xlabel('Clifford Length', fontsize=16) ax.set_ylabel('Z', fontsize=16) ax.grid(True) if show_plt: plt.show()
def plot_rb_data(xdata, ydatas, yavg, yerr, fit, survival_prob, ax=None, show_plt=True): """Plot randomized benchmarking data. Args: xdata (list): list of subsequence lengths ydatas (list): list of lists of survival probabilities for each sequence yavg (list): mean of the survival probabilities at each sequence length yerr (list): error of the survival fit (list): fit parameters survival_prob (callable): function that computes survival probability ax (Axes or None): plot axis (if passed in) show_plt (bool): display the plot. Raises: ImportError: If matplotlib is not installed. """ # pylint: disable=invalid-name if not HAS_MATPLOTLIB: raise ImportError('The function plot_rb_data needs matplotlib. ' 'Run "pip install matplotlib" before.') if ax is None: plt.figure() ax = plt.gca() # Plot the result for each sequence for ydata in ydatas: ax.plot(xdata, ydata, color='gray', linestyle='none', marker='x') # Plot the mean with error bars ax.errorbar(xdata, yavg, yerr=yerr, color='r', linestyle='--', linewidth=3) # Plot the fit ax.plot(xdata, survival_prob(xdata, *fit), color='blue', linestyle='-', linewidth=2) ax.tick_params(labelsize=14) # ax.tick_params(axis='x',labelrotation=70) ax.set_xlabel('Clifford Length', fontsize=16) ax.set_ylabel('Z', fontsize=16) ax.grid(True) if show_plt: plt.show()
[ "Plot", "randomized", "benchmarking", "data", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qcvv/fitters.py#L122-L166
[ "def", "plot_rb_data", "(", "xdata", ",", "ydatas", ",", "yavg", ",", "yerr", ",", "fit", ",", "survival_prob", ",", "ax", "=", "None", ",", "show_plt", "=", "True", ")", ":", "# pylint: disable=invalid-name", "if", "not", "HAS_MATPLOTLIB", ":", "raise", "ImportError", "(", "'The function plot_rb_data needs matplotlib. '", "'Run \"pip install matplotlib\" before.'", ")", "if", "ax", "is", "None", ":", "plt", ".", "figure", "(", ")", "ax", "=", "plt", ".", "gca", "(", ")", "# Plot the result for each sequence", "for", "ydata", "in", "ydatas", ":", "ax", ".", "plot", "(", "xdata", ",", "ydata", ",", "color", "=", "'gray'", ",", "linestyle", "=", "'none'", ",", "marker", "=", "'x'", ")", "# Plot the mean with error bars", "ax", ".", "errorbar", "(", "xdata", ",", "yavg", ",", "yerr", "=", "yerr", ",", "color", "=", "'r'", ",", "linestyle", "=", "'--'", ",", "linewidth", "=", "3", ")", "# Plot the fit", "ax", ".", "plot", "(", "xdata", ",", "survival_prob", "(", "xdata", ",", "*", "fit", ")", ",", "color", "=", "'blue'", ",", "linestyle", "=", "'-'", ",", "linewidth", "=", "2", ")", "ax", ".", "tick_params", "(", "labelsize", "=", "14", ")", "# ax.tick_params(axis='x',labelrotation=70)", "ax", ".", "set_xlabel", "(", "'Clifford Length'", ",", "fontsize", "=", "16", ")", "ax", ".", "set_ylabel", "(", "'Z'", ",", "fontsize", "=", "16", ")", "ax", ".", "grid", "(", "True", ")", "if", "show_plt", ":", "plt", ".", "show", "(", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_split_runs_on_parameters
Finds runs containing parameterized gates and splits them into sequential runs excluding the parameterized gates.
qiskit/transpiler/passes/optimize_1q_gates.py
def _split_runs_on_parameters(runs): """Finds runs containing parameterized gates and splits them into sequential runs excluding the parameterized gates. """ def _is_dagnode_parameterized(node): return any(isinstance(param, Parameter) for param in node.op.params) out = [] for run in runs: groups = groupby(run, _is_dagnode_parameterized) for group_is_parameterized, gates in groups: if not group_is_parameterized: out.append(list(gates)) return out
def _split_runs_on_parameters(runs): """Finds runs containing parameterized gates and splits them into sequential runs excluding the parameterized gates. """ def _is_dagnode_parameterized(node): return any(isinstance(param, Parameter) for param in node.op.params) out = [] for run in runs: groups = groupby(run, _is_dagnode_parameterized) for group_is_parameterized, gates in groups: if not group_is_parameterized: out.append(list(gates)) return out
[ "Finds", "runs", "containing", "parameterized", "gates", "and", "splits", "them", "into", "sequential", "runs", "excluding", "the", "parameterized", "gates", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/optimize_1q_gates.py#L238-L254
[ "def", "_split_runs_on_parameters", "(", "runs", ")", ":", "def", "_is_dagnode_parameterized", "(", "node", ")", ":", "return", "any", "(", "isinstance", "(", "param", ",", "Parameter", ")", "for", "param", "in", "node", ".", "op", ".", "params", ")", "out", "=", "[", "]", "for", "run", "in", "runs", ":", "groups", "=", "groupby", "(", "run", ",", "_is_dagnode_parameterized", ")", "for", "group_is_parameterized", ",", "gates", "in", "groups", ":", "if", "not", "group_is_parameterized", ":", "out", ".", "append", "(", "list", "(", "gates", ")", ")", "return", "out" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Optimize1qGates.run
Return a new circuit that has been optimized.
qiskit/transpiler/passes/optimize_1q_gates.py
def run(self, dag): """Return a new circuit that has been optimized.""" runs = dag.collect_runs(["u1", "u2", "u3", "id"]) runs = _split_runs_on_parameters(runs) for run in runs: right_name = "u1" right_parameters = (0, 0, 0) # (theta, phi, lambda) for current_node in run: left_name = current_node.name if (current_node.condition is not None or len(current_node.qargs) != 1 or left_name not in ["u1", "u2", "u3", "id"]): raise TranspilerError("internal error") if left_name == "u1": left_parameters = (0, 0, current_node.op.params[0]) elif left_name == "u2": left_parameters = (np.pi / 2, current_node.op.params[0], current_node.op.params[1]) elif left_name == "u3": left_parameters = tuple(current_node.op.params) else: left_name = "u1" # replace id with u1 left_parameters = (0, 0, 0) # If there are any sympy objects coming from the gate convert # to numpy. left_parameters = tuple([float(x) for x in left_parameters]) # Compose gates name_tuple = (left_name, right_name) if name_tuple == ("u1", "u1"): # u1(lambda1) * u1(lambda2) = u1(lambda1 + lambda2) right_parameters = (0, 0, right_parameters[2] + left_parameters[2]) elif name_tuple == ("u1", "u2"): # u1(lambda1) * u2(phi2, lambda2) = u2(phi2 + lambda1, lambda2) right_parameters = (np.pi / 2, right_parameters[1] + left_parameters[2], right_parameters[2]) elif name_tuple == ("u2", "u1"): # u2(phi1, lambda1) * u1(lambda2) = u2(phi1, lambda1 + lambda2) right_name = "u2" right_parameters = (np.pi / 2, left_parameters[1], right_parameters[2] + left_parameters[2]) elif name_tuple == ("u1", "u3"): # u1(lambda1) * u3(theta2, phi2, lambda2) = # u3(theta2, phi2 + lambda1, lambda2) right_parameters = (right_parameters[0], right_parameters[1] + left_parameters[2], right_parameters[2]) elif name_tuple == ("u3", "u1"): # u3(theta1, phi1, lambda1) * u1(lambda2) = # u3(theta1, phi1, lambda1 + lambda2) right_name = "u3" right_parameters = (left_parameters[0], left_parameters[1], right_parameters[2] + left_parameters[2]) elif name_tuple == ("u2", "u2"): # Using Ry(pi/2).Rz(2*lambda).Ry(pi/2) = # Rz(pi/2).Ry(pi-2*lambda).Rz(pi/2), # u2(phi1, lambda1) * u2(phi2, lambda2) = # u3(pi - lambda1 - phi2, phi1 + pi/2, lambda2 + pi/2) right_name = "u3" right_parameters = (np.pi - left_parameters[2] - right_parameters[1], left_parameters[1] + np.pi / 2, right_parameters[2] + np.pi / 2) elif name_tuple[1] == "nop": right_name = left_name right_parameters = left_parameters else: # For composing u3's or u2's with u3's, use # u2(phi, lambda) = u3(pi/2, phi, lambda) # together with the qiskit.mapper.compose_u3 method. right_name = "u3" # Evaluate the symbolic expressions for efficiency right_parameters = Optimize1qGates.compose_u3(left_parameters[0], left_parameters[1], left_parameters[2], right_parameters[0], right_parameters[1], right_parameters[2]) # Why evalf()? This program: # OPENQASM 2.0; # include "qelib1.inc"; # qreg q[2]; # creg c[2]; # u3(0.518016983430947*pi,1.37051598592907*pi,1.36816383603222*pi) q[0]; # u3(1.69867232277986*pi,0.371448347747471*pi,0.461117217930936*pi) q[0]; # u3(0.294319836336836*pi,0.450325871124225*pi,1.46804720442555*pi) q[0]; # measure q -> c; # took >630 seconds (did not complete) to optimize without # calling evalf() at all, 19 seconds to optimize calling # evalf() AFTER compose_u3, and 1 second to optimize # calling evalf() BEFORE compose_u3. # 1. Here down, when we simplify, we add f(theta) to lambda to # correct the global phase when f(theta) is 2*pi. This isn't # necessary but the other steps preserve the global phase, so # we continue in that manner. # 2. The final step will remove Z rotations by 2*pi. # 3. Note that is_zero is true only if the expression is exactly # zero. If the input expressions have already been evaluated # then these final simplifications will not occur. # TODO After we refactor, we should have separate passes for # exact and approximate rewriting. # Y rotation is 0 mod 2*pi, so the gate is a u1 if np.mod(right_parameters[0], (2 * np.pi)) == 0 \ and right_name != "u1": right_name = "u1" right_parameters = (0, 0, right_parameters[1] + right_parameters[2] + right_parameters[0]) # Y rotation is pi/2 or -pi/2 mod 2*pi, so the gate is a u2 if right_name == "u3": # theta = pi/2 + 2*k*pi if np.mod((right_parameters[0] - np.pi / 2), (2 * np.pi)) == 0: right_name = "u2" right_parameters = (np.pi / 2, right_parameters[1], right_parameters[2] + (right_parameters[0] - np.pi / 2)) # theta = -pi/2 + 2*k*pi if np.mod((right_parameters[0] + np.pi / 2), (2 * np.pi)) == 0: right_name = "u2" right_parameters = (np.pi / 2, right_parameters[1] + np.pi, right_parameters[2] - np.pi + (right_parameters[0] + np.pi / 2)) # u1 and lambda is 0 mod 2*pi so gate is nop (up to a global phase) if right_name == "u1" and np.mod(right_parameters[2], (2 * np.pi)) == 0: right_name = "nop" # Replace the the first node in the run with a dummy DAG which contains a dummy # qubit. The name is irrelevant, because substitute_node_with_dag will take care of # putting it in the right place. run_qarg = (QuantumRegister(1, 'q'), 0) new_op = Gate(name="", num_qubits=1, params=[]) if right_name == "u1": new_op = U1Gate(right_parameters[2]) if right_name == "u2": new_op = U2Gate(right_parameters[1], right_parameters[2]) if right_name == "u3": new_op = U3Gate(*right_parameters) if right_name != 'nop': new_dag = DAGCircuit() new_dag.add_qreg(run_qarg[0]) new_dag.apply_operation_back(new_op, [run_qarg], []) dag.substitute_node_with_dag(run[0], new_dag) # Delete the other nodes in the run for current_node in run[1:]: dag.remove_op_node(current_node) if right_name == "nop": dag.remove_op_node(run[0]) return dag
def run(self, dag): """Return a new circuit that has been optimized.""" runs = dag.collect_runs(["u1", "u2", "u3", "id"]) runs = _split_runs_on_parameters(runs) for run in runs: right_name = "u1" right_parameters = (0, 0, 0) # (theta, phi, lambda) for current_node in run: left_name = current_node.name if (current_node.condition is not None or len(current_node.qargs) != 1 or left_name not in ["u1", "u2", "u3", "id"]): raise TranspilerError("internal error") if left_name == "u1": left_parameters = (0, 0, current_node.op.params[0]) elif left_name == "u2": left_parameters = (np.pi / 2, current_node.op.params[0], current_node.op.params[1]) elif left_name == "u3": left_parameters = tuple(current_node.op.params) else: left_name = "u1" # replace id with u1 left_parameters = (0, 0, 0) # If there are any sympy objects coming from the gate convert # to numpy. left_parameters = tuple([float(x) for x in left_parameters]) # Compose gates name_tuple = (left_name, right_name) if name_tuple == ("u1", "u1"): # u1(lambda1) * u1(lambda2) = u1(lambda1 + lambda2) right_parameters = (0, 0, right_parameters[2] + left_parameters[2]) elif name_tuple == ("u1", "u2"): # u1(lambda1) * u2(phi2, lambda2) = u2(phi2 + lambda1, lambda2) right_parameters = (np.pi / 2, right_parameters[1] + left_parameters[2], right_parameters[2]) elif name_tuple == ("u2", "u1"): # u2(phi1, lambda1) * u1(lambda2) = u2(phi1, lambda1 + lambda2) right_name = "u2" right_parameters = (np.pi / 2, left_parameters[1], right_parameters[2] + left_parameters[2]) elif name_tuple == ("u1", "u3"): # u1(lambda1) * u3(theta2, phi2, lambda2) = # u3(theta2, phi2 + lambda1, lambda2) right_parameters = (right_parameters[0], right_parameters[1] + left_parameters[2], right_parameters[2]) elif name_tuple == ("u3", "u1"): # u3(theta1, phi1, lambda1) * u1(lambda2) = # u3(theta1, phi1, lambda1 + lambda2) right_name = "u3" right_parameters = (left_parameters[0], left_parameters[1], right_parameters[2] + left_parameters[2]) elif name_tuple == ("u2", "u2"): # Using Ry(pi/2).Rz(2*lambda).Ry(pi/2) = # Rz(pi/2).Ry(pi-2*lambda).Rz(pi/2), # u2(phi1, lambda1) * u2(phi2, lambda2) = # u3(pi - lambda1 - phi2, phi1 + pi/2, lambda2 + pi/2) right_name = "u3" right_parameters = (np.pi - left_parameters[2] - right_parameters[1], left_parameters[1] + np.pi / 2, right_parameters[2] + np.pi / 2) elif name_tuple[1] == "nop": right_name = left_name right_parameters = left_parameters else: # For composing u3's or u2's with u3's, use # u2(phi, lambda) = u3(pi/2, phi, lambda) # together with the qiskit.mapper.compose_u3 method. right_name = "u3" # Evaluate the symbolic expressions for efficiency right_parameters = Optimize1qGates.compose_u3(left_parameters[0], left_parameters[1], left_parameters[2], right_parameters[0], right_parameters[1], right_parameters[2]) # Why evalf()? This program: # OPENQASM 2.0; # include "qelib1.inc"; # qreg q[2]; # creg c[2]; # u3(0.518016983430947*pi,1.37051598592907*pi,1.36816383603222*pi) q[0]; # u3(1.69867232277986*pi,0.371448347747471*pi,0.461117217930936*pi) q[0]; # u3(0.294319836336836*pi,0.450325871124225*pi,1.46804720442555*pi) q[0]; # measure q -> c; # took >630 seconds (did not complete) to optimize without # calling evalf() at all, 19 seconds to optimize calling # evalf() AFTER compose_u3, and 1 second to optimize # calling evalf() BEFORE compose_u3. # 1. Here down, when we simplify, we add f(theta) to lambda to # correct the global phase when f(theta) is 2*pi. This isn't # necessary but the other steps preserve the global phase, so # we continue in that manner. # 2. The final step will remove Z rotations by 2*pi. # 3. Note that is_zero is true only if the expression is exactly # zero. If the input expressions have already been evaluated # then these final simplifications will not occur. # TODO After we refactor, we should have separate passes for # exact and approximate rewriting. # Y rotation is 0 mod 2*pi, so the gate is a u1 if np.mod(right_parameters[0], (2 * np.pi)) == 0 \ and right_name != "u1": right_name = "u1" right_parameters = (0, 0, right_parameters[1] + right_parameters[2] + right_parameters[0]) # Y rotation is pi/2 or -pi/2 mod 2*pi, so the gate is a u2 if right_name == "u3": # theta = pi/2 + 2*k*pi if np.mod((right_parameters[0] - np.pi / 2), (2 * np.pi)) == 0: right_name = "u2" right_parameters = (np.pi / 2, right_parameters[1], right_parameters[2] + (right_parameters[0] - np.pi / 2)) # theta = -pi/2 + 2*k*pi if np.mod((right_parameters[0] + np.pi / 2), (2 * np.pi)) == 0: right_name = "u2" right_parameters = (np.pi / 2, right_parameters[1] + np.pi, right_parameters[2] - np.pi + (right_parameters[0] + np.pi / 2)) # u1 and lambda is 0 mod 2*pi so gate is nop (up to a global phase) if right_name == "u1" and np.mod(right_parameters[2], (2 * np.pi)) == 0: right_name = "nop" # Replace the the first node in the run with a dummy DAG which contains a dummy # qubit. The name is irrelevant, because substitute_node_with_dag will take care of # putting it in the right place. run_qarg = (QuantumRegister(1, 'q'), 0) new_op = Gate(name="", num_qubits=1, params=[]) if right_name == "u1": new_op = U1Gate(right_parameters[2]) if right_name == "u2": new_op = U2Gate(right_parameters[1], right_parameters[2]) if right_name == "u3": new_op = U3Gate(*right_parameters) if right_name != 'nop': new_dag = DAGCircuit() new_dag.add_qreg(run_qarg[0]) new_dag.apply_operation_back(new_op, [run_qarg], []) dag.substitute_node_with_dag(run[0], new_dag) # Delete the other nodes in the run for current_node in run[1:]: dag.remove_op_node(current_node) if right_name == "nop": dag.remove_op_node(run[0]) 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_1q_gates.py#L39-L191
[ "def", "run", "(", "self", ",", "dag", ")", ":", "runs", "=", "dag", ".", "collect_runs", "(", "[", "\"u1\"", ",", "\"u2\"", ",", "\"u3\"", ",", "\"id\"", "]", ")", "runs", "=", "_split_runs_on_parameters", "(", "runs", ")", "for", "run", "in", "runs", ":", "right_name", "=", "\"u1\"", "right_parameters", "=", "(", "0", ",", "0", ",", "0", ")", "# (theta, phi, lambda)", "for", "current_node", "in", "run", ":", "left_name", "=", "current_node", ".", "name", "if", "(", "current_node", ".", "condition", "is", "not", "None", "or", "len", "(", "current_node", ".", "qargs", ")", "!=", "1", "or", "left_name", "not", "in", "[", "\"u1\"", ",", "\"u2\"", ",", "\"u3\"", ",", "\"id\"", "]", ")", ":", "raise", "TranspilerError", "(", "\"internal error\"", ")", "if", "left_name", "==", "\"u1\"", ":", "left_parameters", "=", "(", "0", ",", "0", ",", "current_node", ".", "op", ".", "params", "[", "0", "]", ")", "elif", "left_name", "==", "\"u2\"", ":", "left_parameters", "=", "(", "np", ".", "pi", "/", "2", ",", "current_node", ".", "op", ".", "params", "[", "0", "]", ",", "current_node", ".", "op", ".", "params", "[", "1", "]", ")", "elif", "left_name", "==", "\"u3\"", ":", "left_parameters", "=", "tuple", "(", "current_node", ".", "op", ".", "params", ")", "else", ":", "left_name", "=", "\"u1\"", "# replace id with u1", "left_parameters", "=", "(", "0", ",", "0", ",", "0", ")", "# If there are any sympy objects coming from the gate convert", "# to numpy.", "left_parameters", "=", "tuple", "(", "[", "float", "(", "x", ")", "for", "x", "in", "left_parameters", "]", ")", "# Compose gates", "name_tuple", "=", "(", "left_name", ",", "right_name", ")", "if", "name_tuple", "==", "(", "\"u1\"", ",", "\"u1\"", ")", ":", "# u1(lambda1) * u1(lambda2) = u1(lambda1 + lambda2)", "right_parameters", "=", "(", "0", ",", "0", ",", "right_parameters", "[", "2", "]", "+", "left_parameters", "[", "2", "]", ")", "elif", "name_tuple", "==", "(", "\"u1\"", ",", "\"u2\"", ")", ":", "# u1(lambda1) * u2(phi2, lambda2) = u2(phi2 + lambda1, lambda2)", "right_parameters", "=", "(", "np", ".", "pi", "/", "2", ",", "right_parameters", "[", "1", "]", "+", "left_parameters", "[", "2", "]", ",", "right_parameters", "[", "2", "]", ")", "elif", "name_tuple", "==", "(", "\"u2\"", ",", "\"u1\"", ")", ":", "# u2(phi1, lambda1) * u1(lambda2) = u2(phi1, lambda1 + lambda2)", "right_name", "=", "\"u2\"", "right_parameters", "=", "(", "np", ".", "pi", "/", "2", ",", "left_parameters", "[", "1", "]", ",", "right_parameters", "[", "2", "]", "+", "left_parameters", "[", "2", "]", ")", "elif", "name_tuple", "==", "(", "\"u1\"", ",", "\"u3\"", ")", ":", "# u1(lambda1) * u3(theta2, phi2, lambda2) =", "# u3(theta2, phi2 + lambda1, lambda2)", "right_parameters", "=", "(", "right_parameters", "[", "0", "]", ",", "right_parameters", "[", "1", "]", "+", "left_parameters", "[", "2", "]", ",", "right_parameters", "[", "2", "]", ")", "elif", "name_tuple", "==", "(", "\"u3\"", ",", "\"u1\"", ")", ":", "# u3(theta1, phi1, lambda1) * u1(lambda2) =", "# u3(theta1, phi1, lambda1 + lambda2)", "right_name", "=", "\"u3\"", "right_parameters", "=", "(", "left_parameters", "[", "0", "]", ",", "left_parameters", "[", "1", "]", ",", "right_parameters", "[", "2", "]", "+", "left_parameters", "[", "2", "]", ")", "elif", "name_tuple", "==", "(", "\"u2\"", ",", "\"u2\"", ")", ":", "# Using Ry(pi/2).Rz(2*lambda).Ry(pi/2) =", "# Rz(pi/2).Ry(pi-2*lambda).Rz(pi/2),", "# u2(phi1, lambda1) * u2(phi2, lambda2) =", "# u3(pi - lambda1 - phi2, phi1 + pi/2, lambda2 + pi/2)", "right_name", "=", "\"u3\"", "right_parameters", "=", "(", "np", ".", "pi", "-", "left_parameters", "[", "2", "]", "-", "right_parameters", "[", "1", "]", ",", "left_parameters", "[", "1", "]", "+", "np", ".", "pi", "/", "2", ",", "right_parameters", "[", "2", "]", "+", "np", ".", "pi", "/", "2", ")", "elif", "name_tuple", "[", "1", "]", "==", "\"nop\"", ":", "right_name", "=", "left_name", "right_parameters", "=", "left_parameters", "else", ":", "# For composing u3's or u2's with u3's, use", "# u2(phi, lambda) = u3(pi/2, phi, lambda)", "# together with the qiskit.mapper.compose_u3 method.", "right_name", "=", "\"u3\"", "# Evaluate the symbolic expressions for efficiency", "right_parameters", "=", "Optimize1qGates", ".", "compose_u3", "(", "left_parameters", "[", "0", "]", ",", "left_parameters", "[", "1", "]", ",", "left_parameters", "[", "2", "]", ",", "right_parameters", "[", "0", "]", ",", "right_parameters", "[", "1", "]", ",", "right_parameters", "[", "2", "]", ")", "# Why evalf()? This program:", "# OPENQASM 2.0;", "# include \"qelib1.inc\";", "# qreg q[2];", "# creg c[2];", "# u3(0.518016983430947*pi,1.37051598592907*pi,1.36816383603222*pi) q[0];", "# u3(1.69867232277986*pi,0.371448347747471*pi,0.461117217930936*pi) q[0];", "# u3(0.294319836336836*pi,0.450325871124225*pi,1.46804720442555*pi) q[0];", "# measure q -> c;", "# took >630 seconds (did not complete) to optimize without", "# calling evalf() at all, 19 seconds to optimize calling", "# evalf() AFTER compose_u3, and 1 second to optimize", "# calling evalf() BEFORE compose_u3.", "# 1. Here down, when we simplify, we add f(theta) to lambda to", "# correct the global phase when f(theta) is 2*pi. This isn't", "# necessary but the other steps preserve the global phase, so", "# we continue in that manner.", "# 2. The final step will remove Z rotations by 2*pi.", "# 3. Note that is_zero is true only if the expression is exactly", "# zero. If the input expressions have already been evaluated", "# then these final simplifications will not occur.", "# TODO After we refactor, we should have separate passes for", "# exact and approximate rewriting.", "# Y rotation is 0 mod 2*pi, so the gate is a u1", "if", "np", ".", "mod", "(", "right_parameters", "[", "0", "]", ",", "(", "2", "*", "np", ".", "pi", ")", ")", "==", "0", "and", "right_name", "!=", "\"u1\"", ":", "right_name", "=", "\"u1\"", "right_parameters", "=", "(", "0", ",", "0", ",", "right_parameters", "[", "1", "]", "+", "right_parameters", "[", "2", "]", "+", "right_parameters", "[", "0", "]", ")", "# Y rotation is pi/2 or -pi/2 mod 2*pi, so the gate is a u2", "if", "right_name", "==", "\"u3\"", ":", "# theta = pi/2 + 2*k*pi", "if", "np", ".", "mod", "(", "(", "right_parameters", "[", "0", "]", "-", "np", ".", "pi", "/", "2", ")", ",", "(", "2", "*", "np", ".", "pi", ")", ")", "==", "0", ":", "right_name", "=", "\"u2\"", "right_parameters", "=", "(", "np", ".", "pi", "/", "2", ",", "right_parameters", "[", "1", "]", ",", "right_parameters", "[", "2", "]", "+", "(", "right_parameters", "[", "0", "]", "-", "np", ".", "pi", "/", "2", ")", ")", "# theta = -pi/2 + 2*k*pi", "if", "np", ".", "mod", "(", "(", "right_parameters", "[", "0", "]", "+", "np", ".", "pi", "/", "2", ")", ",", "(", "2", "*", "np", ".", "pi", ")", ")", "==", "0", ":", "right_name", "=", "\"u2\"", "right_parameters", "=", "(", "np", ".", "pi", "/", "2", ",", "right_parameters", "[", "1", "]", "+", "np", ".", "pi", ",", "right_parameters", "[", "2", "]", "-", "np", ".", "pi", "+", "(", "right_parameters", "[", "0", "]", "+", "np", ".", "pi", "/", "2", ")", ")", "# u1 and lambda is 0 mod 2*pi so gate is nop (up to a global phase)", "if", "right_name", "==", "\"u1\"", "and", "np", ".", "mod", "(", "right_parameters", "[", "2", "]", ",", "(", "2", "*", "np", ".", "pi", ")", ")", "==", "0", ":", "right_name", "=", "\"nop\"", "# Replace the the first node in the run with a dummy DAG which contains a dummy", "# qubit. The name is irrelevant, because substitute_node_with_dag will take care of", "# putting it in the right place.", "run_qarg", "=", "(", "QuantumRegister", "(", "1", ",", "'q'", ")", ",", "0", ")", "new_op", "=", "Gate", "(", "name", "=", "\"\"", ",", "num_qubits", "=", "1", ",", "params", "=", "[", "]", ")", "if", "right_name", "==", "\"u1\"", ":", "new_op", "=", "U1Gate", "(", "right_parameters", "[", "2", "]", ")", "if", "right_name", "==", "\"u2\"", ":", "new_op", "=", "U2Gate", "(", "right_parameters", "[", "1", "]", ",", "right_parameters", "[", "2", "]", ")", "if", "right_name", "==", "\"u3\"", ":", "new_op", "=", "U3Gate", "(", "*", "right_parameters", ")", "if", "right_name", "!=", "'nop'", ":", "new_dag", "=", "DAGCircuit", "(", ")", "new_dag", ".", "add_qreg", "(", "run_qarg", "[", "0", "]", ")", "new_dag", ".", "apply_operation_back", "(", "new_op", ",", "[", "run_qarg", "]", ",", "[", "]", ")", "dag", ".", "substitute_node_with_dag", "(", "run", "[", "0", "]", ",", "new_dag", ")", "# Delete the other nodes in the run", "for", "current_node", "in", "run", "[", "1", ":", "]", ":", "dag", ".", "remove_op_node", "(", "current_node", ")", "if", "right_name", "==", "\"nop\"", ":", "dag", ".", "remove_op_node", "(", "run", "[", "0", "]", ")", "return", "dag" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Optimize1qGates.compose_u3
Return a triple theta, phi, lambda for the product. u3(theta, phi, lambda) = u3(theta1, phi1, lambda1).u3(theta2, phi2, lambda2) = Rz(phi1).Ry(theta1).Rz(lambda1+phi2).Ry(theta2).Rz(lambda2) = Rz(phi1).Rz(phi').Ry(theta').Rz(lambda').Rz(lambda2) = u3(theta', phi1 + phi', lambda2 + lambda') Return theta, phi, lambda.
qiskit/transpiler/passes/optimize_1q_gates.py
def compose_u3(theta1, phi1, lambda1, theta2, phi2, lambda2): """Return a triple theta, phi, lambda for the product. u3(theta, phi, lambda) = u3(theta1, phi1, lambda1).u3(theta2, phi2, lambda2) = Rz(phi1).Ry(theta1).Rz(lambda1+phi2).Ry(theta2).Rz(lambda2) = Rz(phi1).Rz(phi').Ry(theta').Rz(lambda').Rz(lambda2) = u3(theta', phi1 + phi', lambda2 + lambda') Return theta, phi, lambda. """ # Careful with the factor of two in yzy_to_zyz thetap, phip, lambdap = Optimize1qGates.yzy_to_zyz((lambda1 + phi2), theta1, theta2) (theta, phi, lamb) = (thetap, phi1 + phip, lambda2 + lambdap) return (theta, phi, lamb)
def compose_u3(theta1, phi1, lambda1, theta2, phi2, lambda2): """Return a triple theta, phi, lambda for the product. u3(theta, phi, lambda) = u3(theta1, phi1, lambda1).u3(theta2, phi2, lambda2) = Rz(phi1).Ry(theta1).Rz(lambda1+phi2).Ry(theta2).Rz(lambda2) = Rz(phi1).Rz(phi').Ry(theta').Rz(lambda').Rz(lambda2) = u3(theta', phi1 + phi', lambda2 + lambda') Return theta, phi, lambda. """ # Careful with the factor of two in yzy_to_zyz thetap, phip, lambdap = Optimize1qGates.yzy_to_zyz((lambda1 + phi2), theta1, theta2) (theta, phi, lamb) = (thetap, phi1 + phip, lambda2 + lambdap) return (theta, phi, lamb)
[ "Return", "a", "triple", "theta", "phi", "lambda", "for", "the", "product", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/optimize_1q_gates.py#L194-L209
[ "def", "compose_u3", "(", "theta1", ",", "phi1", ",", "lambda1", ",", "theta2", ",", "phi2", ",", "lambda2", ")", ":", "# Careful with the factor of two in yzy_to_zyz", "thetap", ",", "phip", ",", "lambdap", "=", "Optimize1qGates", ".", "yzy_to_zyz", "(", "(", "lambda1", "+", "phi2", ")", ",", "theta1", ",", "theta2", ")", "(", "theta", ",", "phi", ",", "lamb", ")", "=", "(", "thetap", ",", "phi1", "+", "phip", ",", "lambda2", "+", "lambdap", ")", "return", "(", "theta", ",", "phi", ",", "lamb", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Optimize1qGates.yzy_to_zyz
Express a Y.Z.Y single qubit gate as a Z.Y.Z gate. Solve the equation .. math:: Ry(theta1).Rz(xi).Ry(theta2) = Rz(phi).Ry(theta).Rz(lambda) for theta, phi, and lambda. Return a solution theta, phi, and lambda.
qiskit/transpiler/passes/optimize_1q_gates.py
def yzy_to_zyz(xi, theta1, theta2, eps=1e-9): # pylint: disable=invalid-name """Express a Y.Z.Y single qubit gate as a Z.Y.Z gate. Solve the equation .. math:: Ry(theta1).Rz(xi).Ry(theta2) = Rz(phi).Ry(theta).Rz(lambda) for theta, phi, and lambda. Return a solution theta, phi, and lambda. """ quaternion_yzy = quaternion_from_euler([theta1, xi, theta2], 'yzy') euler = quaternion_yzy.to_zyz() quaternion_zyz = quaternion_from_euler(euler, 'zyz') # output order different than rotation order out_angles = (euler[1], euler[0], euler[2]) abs_inner = abs(quaternion_zyz.data.dot(quaternion_yzy.data)) if not np.allclose(abs_inner, 1, eps): raise TranspilerError('YZY and ZYZ angles do not give same rotation matrix.') out_angles = tuple(0 if np.abs(angle) < _CHOP_THRESHOLD else angle for angle in out_angles) return out_angles
def yzy_to_zyz(xi, theta1, theta2, eps=1e-9): # pylint: disable=invalid-name """Express a Y.Z.Y single qubit gate as a Z.Y.Z gate. Solve the equation .. math:: Ry(theta1).Rz(xi).Ry(theta2) = Rz(phi).Ry(theta).Rz(lambda) for theta, phi, and lambda. Return a solution theta, phi, and lambda. """ quaternion_yzy = quaternion_from_euler([theta1, xi, theta2], 'yzy') euler = quaternion_yzy.to_zyz() quaternion_zyz = quaternion_from_euler(euler, 'zyz') # output order different than rotation order out_angles = (euler[1], euler[0], euler[2]) abs_inner = abs(quaternion_zyz.data.dot(quaternion_yzy.data)) if not np.allclose(abs_inner, 1, eps): raise TranspilerError('YZY and ZYZ angles do not give same rotation matrix.') out_angles = tuple(0 if np.abs(angle) < _CHOP_THRESHOLD else angle for angle in out_angles) return out_angles
[ "Express", "a", "Y", ".", "Z", ".", "Y", "single", "qubit", "gate", "as", "a", "Z", ".", "Y", ".", "Z", "gate", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/optimize_1q_gates.py#L212-L235
[ "def", "yzy_to_zyz", "(", "xi", ",", "theta1", ",", "theta2", ",", "eps", "=", "1e-9", ")", ":", "# pylint: disable=invalid-name", "quaternion_yzy", "=", "quaternion_from_euler", "(", "[", "theta1", ",", "xi", ",", "theta2", "]", ",", "'yzy'", ")", "euler", "=", "quaternion_yzy", ".", "to_zyz", "(", ")", "quaternion_zyz", "=", "quaternion_from_euler", "(", "euler", ",", "'zyz'", ")", "# output order different than rotation order", "out_angles", "=", "(", "euler", "[", "1", "]", ",", "euler", "[", "0", "]", ",", "euler", "[", "2", "]", ")", "abs_inner", "=", "abs", "(", "quaternion_zyz", ".", "data", ".", "dot", "(", "quaternion_yzy", ".", "data", ")", ")", "if", "not", "np", ".", "allclose", "(", "abs_inner", ",", "1", ",", "eps", ")", ":", "raise", "TranspilerError", "(", "'YZY and ZYZ angles do not give same rotation matrix.'", ")", "out_angles", "=", "tuple", "(", "0", "if", "np", ".", "abs", "(", "angle", ")", "<", "_CHOP_THRESHOLD", "else", "angle", "for", "angle", "in", "out_angles", ")", "return", "out_angles" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
FullAncillaAllocation.run
Extend the layout with new (physical qubit, virtual qubit) pairs. The dag signals which virtual qubits are already in the circuit. This pass will allocate new virtual qubits such that no collision occurs (i.e. Layout bijectivity is preserved) The coupling_map and layout together determine which physical qubits are free. Args: dag (DAGCircuit): circuit to analyze Returns: DAGCircuit: returns the same dag circuit, unmodified Raises: TranspilerError: If there is not layout in the property set or not set at init time.
qiskit/transpiler/passes/mapping/full_ancilla_allocation.py
def run(self, dag): """ Extend the layout with new (physical qubit, virtual qubit) pairs. The dag signals which virtual qubits are already in the circuit. This pass will allocate new virtual qubits such that no collision occurs (i.e. Layout bijectivity is preserved) The coupling_map and layout together determine which physical qubits are free. Args: dag (DAGCircuit): circuit to analyze Returns: DAGCircuit: returns the same dag circuit, unmodified Raises: TranspilerError: If there is not layout in the property set or not set at init time. """ self.layout = self.layout or self.property_set.get('layout') if self.layout is None: raise TranspilerError("FullAncilla pass requires property_set[\"layout\"] or" " \"layout\" parameter to run") layout_physical_qubits = self.layout.get_physical_bits().keys() coupling_physical_qubits = self.coupling_map.physical_qubits idle_physical_qubits = [q for q in coupling_physical_qubits if q not in layout_physical_qubits] if idle_physical_qubits: if self.ancilla_name in dag.qregs: save_prefix = QuantumRegister.prefix QuantumRegister.prefix = self.ancilla_name qreg = QuantumRegister(len(idle_physical_qubits)) QuantumRegister.prefix = save_prefix else: qreg = QuantumRegister(len(idle_physical_qubits), name=self.ancilla_name) for idx, idle_q in enumerate(idle_physical_qubits): self.property_set['layout'][idle_q] = qreg[idx] return dag
def run(self, dag): """ Extend the layout with new (physical qubit, virtual qubit) pairs. The dag signals which virtual qubits are already in the circuit. This pass will allocate new virtual qubits such that no collision occurs (i.e. Layout bijectivity is preserved) The coupling_map and layout together determine which physical qubits are free. Args: dag (DAGCircuit): circuit to analyze Returns: DAGCircuit: returns the same dag circuit, unmodified Raises: TranspilerError: If there is not layout in the property set or not set at init time. """ self.layout = self.layout or self.property_set.get('layout') if self.layout is None: raise TranspilerError("FullAncilla pass requires property_set[\"layout\"] or" " \"layout\" parameter to run") layout_physical_qubits = self.layout.get_physical_bits().keys() coupling_physical_qubits = self.coupling_map.physical_qubits idle_physical_qubits = [q for q in coupling_physical_qubits if q not in layout_physical_qubits] if idle_physical_qubits: if self.ancilla_name in dag.qregs: save_prefix = QuantumRegister.prefix QuantumRegister.prefix = self.ancilla_name qreg = QuantumRegister(len(idle_physical_qubits)) QuantumRegister.prefix = save_prefix else: qreg = QuantumRegister(len(idle_physical_qubits), name=self.ancilla_name) for idx, idle_q in enumerate(idle_physical_qubits): self.property_set['layout'][idle_q] = qreg[idx] return dag
[ "Extend", "the", "layout", "with", "new", "(", "physical", "qubit", "virtual", "qubit", ")", "pairs", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/full_ancilla_allocation.py#L41-L83
[ "def", "run", "(", "self", ",", "dag", ")", ":", "self", ".", "layout", "=", "self", ".", "layout", "or", "self", ".", "property_set", ".", "get", "(", "'layout'", ")", "if", "self", ".", "layout", "is", "None", ":", "raise", "TranspilerError", "(", "\"FullAncilla pass requires property_set[\\\"layout\\\"] or\"", "\" \\\"layout\\\" parameter to run\"", ")", "layout_physical_qubits", "=", "self", ".", "layout", ".", "get_physical_bits", "(", ")", ".", "keys", "(", ")", "coupling_physical_qubits", "=", "self", ".", "coupling_map", ".", "physical_qubits", "idle_physical_qubits", "=", "[", "q", "for", "q", "in", "coupling_physical_qubits", "if", "q", "not", "in", "layout_physical_qubits", "]", "if", "idle_physical_qubits", ":", "if", "self", ".", "ancilla_name", "in", "dag", ".", "qregs", ":", "save_prefix", "=", "QuantumRegister", ".", "prefix", "QuantumRegister", ".", "prefix", "=", "self", ".", "ancilla_name", "qreg", "=", "QuantumRegister", "(", "len", "(", "idle_physical_qubits", ")", ")", "QuantumRegister", ".", "prefix", "=", "save_prefix", "else", ":", "qreg", "=", "QuantumRegister", "(", "len", "(", "idle_physical_qubits", ")", ",", "name", "=", "self", ".", "ancilla_name", ")", "for", "idx", ",", "idle_q", "in", "enumerate", "(", "idle_physical_qubits", ")", ":", "self", ".", "property_set", "[", "'layout'", "]", "[", "idle_q", "]", "=", "qreg", "[", "idx", "]", "return", "dag" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_validate_input_state
Validates the input to state visualization functions. Args: quantum_state (ndarray): Input state / density matrix. Returns: rho: A 2d numpy array for the density matrix. Raises: VisualizationError: Invalid input.
qiskit/visualization/utils.py
def _validate_input_state(quantum_state): """Validates the input to state visualization functions. Args: quantum_state (ndarray): Input state / density matrix. Returns: rho: A 2d numpy array for the density matrix. Raises: VisualizationError: Invalid input. """ rho = np.asarray(quantum_state) if rho.ndim == 1: rho = np.outer(rho, np.conj(rho)) # Check the shape of the input is a square matrix shape = np.shape(rho) if len(shape) != 2 or shape[0] != shape[1]: raise VisualizationError("Input is not a valid quantum state.") # Check state is an n-qubit state num = int(np.log2(rho.shape[0])) if 2 ** num != rho.shape[0]: raise VisualizationError("Input is not a multi-qubit quantum state.") return rho
def _validate_input_state(quantum_state): """Validates the input to state visualization functions. Args: quantum_state (ndarray): Input state / density matrix. Returns: rho: A 2d numpy array for the density matrix. Raises: VisualizationError: Invalid input. """ rho = np.asarray(quantum_state) if rho.ndim == 1: rho = np.outer(rho, np.conj(rho)) # Check the shape of the input is a square matrix shape = np.shape(rho) if len(shape) != 2 or shape[0] != shape[1]: raise VisualizationError("Input is not a valid quantum state.") # Check state is an n-qubit state num = int(np.log2(rho.shape[0])) if 2 ** num != rho.shape[0]: raise VisualizationError("Input is not a multi-qubit quantum state.") return rho
[ "Validates", "the", "input", "to", "state", "visualization", "functions", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/utils.py#L16-L37
[ "def", "_validate_input_state", "(", "quantum_state", ")", ":", "rho", "=", "np", ".", "asarray", "(", "quantum_state", ")", "if", "rho", ".", "ndim", "==", "1", ":", "rho", "=", "np", ".", "outer", "(", "rho", ",", "np", ".", "conj", "(", "rho", ")", ")", "# Check the shape of the input is a square matrix", "shape", "=", "np", ".", "shape", "(", "rho", ")", "if", "len", "(", "shape", ")", "!=", "2", "or", "shape", "[", "0", "]", "!=", "shape", "[", "1", "]", ":", "raise", "VisualizationError", "(", "\"Input is not a valid quantum state.\"", ")", "# Check state is an n-qubit state", "num", "=", "int", "(", "np", ".", "log2", "(", "rho", ".", "shape", "[", "0", "]", ")", ")", "if", "2", "**", "num", "!=", "rho", ".", "shape", "[", "0", "]", ":", "raise", "VisualizationError", "(", "\"Input is not a multi-qubit quantum state.\"", ")", "return", "rho" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_trim
Trim a PIL image and remove white space.
qiskit/visualization/utils.py
def _trim(image): """Trim a PIL image and remove white space.""" background = PIL.Image.new(image.mode, image.size, image.getpixel((0, 0))) diff = PIL.ImageChops.difference(image, background) diff = PIL.ImageChops.add(diff, diff, 2.0, -100) bbox = diff.getbbox() if bbox: image = image.crop(bbox) return image
def _trim(image): """Trim a PIL image and remove white space.""" background = PIL.Image.new(image.mode, image.size, image.getpixel((0, 0))) diff = PIL.ImageChops.difference(image, background) diff = PIL.ImageChops.add(diff, diff, 2.0, -100) bbox = diff.getbbox() if bbox: image = image.crop(bbox) return image
[ "Trim", "a", "PIL", "image", "and", "remove", "white", "space", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/utils.py#L40-L48
[ "def", "_trim", "(", "image", ")", ":", "background", "=", "PIL", ".", "Image", ".", "new", "(", "image", ".", "mode", ",", "image", ".", "size", ",", "image", ".", "getpixel", "(", "(", "0", ",", "0", ")", ")", ")", "diff", "=", "PIL", ".", "ImageChops", ".", "difference", "(", "image", ",", "background", ")", "diff", "=", "PIL", ".", "ImageChops", ".", "add", "(", "diff", ",", "diff", ",", "2.0", ",", "-", "100", ")", "bbox", "=", "diff", ".", "getbbox", "(", ")", "if", "bbox", ":", "image", "=", "image", ".", "crop", "(", "bbox", ")", "return", "image" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_get_layered_instructions
Given a circuit, return a tuple (qregs, cregs, ops) where qregs and cregs are the quantum and classical registers in order (based on reverse_bits) and ops is a list of DAG nodes which type is "operation". Args: circuit (QuantumCircuit): From where the information is extracted. reverse_bits (bool): If true the order of the bits in the registers is reversed. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: Tuple(list,list,list): To be consumed by the visualizer directly.
qiskit/visualization/utils.py
def _get_layered_instructions(circuit, reverse_bits=False, justify=None): """ Given a circuit, return a tuple (qregs, cregs, ops) where qregs and cregs are the quantum and classical registers in order (based on reverse_bits) and ops is a list of DAG nodes which type is "operation". Args: circuit (QuantumCircuit): From where the information is extracted. reverse_bits (bool): If true the order of the bits in the registers is reversed. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: Tuple(list,list,list): To be consumed by the visualizer directly. """ if justify: justify = justify.lower() # default to left justify = justify if justify in ('right', 'none') else 'left' dag = circuit_to_dag(circuit) ops = [] qregs = [] cregs = [] for qreg in dag.qregs.values(): qregs += [(qreg, bitno) for bitno in range(qreg.size)] for creg in dag.cregs.values(): cregs += [(creg, bitno) for bitno in range(creg.size)] if justify == 'none': for node in dag.topological_op_nodes(): ops.append([node]) if justify == 'left': for dag_layer in dag.layers(): layers = [] current_layer = [] dag_nodes = dag_layer['graph'].op_nodes() dag_nodes.sort(key=lambda nd: nd._node_id) for node in dag_nodes: multibit_gate = len(node.qargs) + len(node.cargs) > 1 if multibit_gate: # need to see if it crosses over any other nodes gate_span = _get_gate_span(qregs, node) all_indices = [] for check_node in dag_nodes: if check_node != node: all_indices += _get_gate_span(qregs, check_node) if any(i in gate_span for i in all_indices): # needs to be a new layer layers.append([node]) else: # can be added current_layer.append(node) else: current_layer.append(node) if current_layer: layers.append(current_layer) ops += layers if justify == 'right': dag_layers = [] for dag_layer in dag.layers(): dag_layers.append(dag_layer) # Have to work from the end of the circuit dag_layers.reverse() # Dict per layer, keys are qubits and values are the gate layer_dicts = [{}] for dag_layer in dag_layers: dag_instructions = dag_layer['graph'].op_nodes() # sort into the order they were input dag_instructions.sort(key=lambda nd: nd._node_id) for instruction_node in dag_instructions: gate_span = _get_gate_span(qregs, instruction_node) added = False for i in range(len(layer_dicts)): # iterate from the end curr_dict = layer_dicts[-1 - i] if any(index in curr_dict for index in gate_span): added = True if i == 0: new_dict = {} for index in gate_span: new_dict[index] = instruction_node layer_dicts.append(new_dict) else: curr_dict = layer_dicts[-i] for index in gate_span: curr_dict[index] = instruction_node break if not added: for index in gate_span: layer_dicts[0][index] = instruction_node # need to convert from dict format to layers layer_dicts.reverse() ops = [list(layer.values()) for layer in layer_dicts] if reverse_bits: qregs.reverse() cregs.reverse() return qregs, cregs, ops
def _get_layered_instructions(circuit, reverse_bits=False, justify=None): """ Given a circuit, return a tuple (qregs, cregs, ops) where qregs and cregs are the quantum and classical registers in order (based on reverse_bits) and ops is a list of DAG nodes which type is "operation". Args: circuit (QuantumCircuit): From where the information is extracted. reverse_bits (bool): If true the order of the bits in the registers is reversed. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: Tuple(list,list,list): To be consumed by the visualizer directly. """ if justify: justify = justify.lower() # default to left justify = justify if justify in ('right', 'none') else 'left' dag = circuit_to_dag(circuit) ops = [] qregs = [] cregs = [] for qreg in dag.qregs.values(): qregs += [(qreg, bitno) for bitno in range(qreg.size)] for creg in dag.cregs.values(): cregs += [(creg, bitno) for bitno in range(creg.size)] if justify == 'none': for node in dag.topological_op_nodes(): ops.append([node]) if justify == 'left': for dag_layer in dag.layers(): layers = [] current_layer = [] dag_nodes = dag_layer['graph'].op_nodes() dag_nodes.sort(key=lambda nd: nd._node_id) for node in dag_nodes: multibit_gate = len(node.qargs) + len(node.cargs) > 1 if multibit_gate: # need to see if it crosses over any other nodes gate_span = _get_gate_span(qregs, node) all_indices = [] for check_node in dag_nodes: if check_node != node: all_indices += _get_gate_span(qregs, check_node) if any(i in gate_span for i in all_indices): # needs to be a new layer layers.append([node]) else: # can be added current_layer.append(node) else: current_layer.append(node) if current_layer: layers.append(current_layer) ops += layers if justify == 'right': dag_layers = [] for dag_layer in dag.layers(): dag_layers.append(dag_layer) # Have to work from the end of the circuit dag_layers.reverse() # Dict per layer, keys are qubits and values are the gate layer_dicts = [{}] for dag_layer in dag_layers: dag_instructions = dag_layer['graph'].op_nodes() # sort into the order they were input dag_instructions.sort(key=lambda nd: nd._node_id) for instruction_node in dag_instructions: gate_span = _get_gate_span(qregs, instruction_node) added = False for i in range(len(layer_dicts)): # iterate from the end curr_dict = layer_dicts[-1 - i] if any(index in curr_dict for index in gate_span): added = True if i == 0: new_dict = {} for index in gate_span: new_dict[index] = instruction_node layer_dicts.append(new_dict) else: curr_dict = layer_dicts[-i] for index in gate_span: curr_dict[index] = instruction_node break if not added: for index in gate_span: layer_dicts[0][index] = instruction_node # need to convert from dict format to layers layer_dicts.reverse() ops = [list(layer.values()) for layer in layer_dicts] if reverse_bits: qregs.reverse() cregs.reverse() return qregs, cregs, ops
[ "Given", "a", "circuit", "return", "a", "tuple", "(", "qregs", "cregs", "ops", ")", "where", "qregs", "and", "cregs", "are", "the", "quantum", "and", "classical", "registers", "in", "order", "(", "based", "on", "reverse_bits", ")", "and", "ops", "is", "a", "list", "of", "DAG", "nodes", "which", "type", "is", "operation", ".", "Args", ":", "circuit", "(", "QuantumCircuit", ")", ":", "From", "where", "the", "information", "is", "extracted", ".", "reverse_bits", "(", "bool", ")", ":", "If", "true", "the", "order", "of", "the", "bits", "in", "the", "registers", "is", "reversed", ".", "justify", "(", "str", ")", ":", "left", "right", "or", "none", ".", "Defaults", "to", "left", ".", "Says", "how", "the", "circuit", "should", "be", "justified", ".", "Returns", ":", "Tuple", "(", "list", "list", "list", ")", ":", "To", "be", "consumed", "by", "the", "visualizer", "directly", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/utils.py#L51-L175
[ "def", "_get_layered_instructions", "(", "circuit", ",", "reverse_bits", "=", "False", ",", "justify", "=", "None", ")", ":", "if", "justify", ":", "justify", "=", "justify", ".", "lower", "(", ")", "# default to left", "justify", "=", "justify", "if", "justify", "in", "(", "'right'", ",", "'none'", ")", "else", "'left'", "dag", "=", "circuit_to_dag", "(", "circuit", ")", "ops", "=", "[", "]", "qregs", "=", "[", "]", "cregs", "=", "[", "]", "for", "qreg", "in", "dag", ".", "qregs", ".", "values", "(", ")", ":", "qregs", "+=", "[", "(", "qreg", ",", "bitno", ")", "for", "bitno", "in", "range", "(", "qreg", ".", "size", ")", "]", "for", "creg", "in", "dag", ".", "cregs", ".", "values", "(", ")", ":", "cregs", "+=", "[", "(", "creg", ",", "bitno", ")", "for", "bitno", "in", "range", "(", "creg", ".", "size", ")", "]", "if", "justify", "==", "'none'", ":", "for", "node", "in", "dag", ".", "topological_op_nodes", "(", ")", ":", "ops", ".", "append", "(", "[", "node", "]", ")", "if", "justify", "==", "'left'", ":", "for", "dag_layer", "in", "dag", ".", "layers", "(", ")", ":", "layers", "=", "[", "]", "current_layer", "=", "[", "]", "dag_nodes", "=", "dag_layer", "[", "'graph'", "]", ".", "op_nodes", "(", ")", "dag_nodes", ".", "sort", "(", "key", "=", "lambda", "nd", ":", "nd", ".", "_node_id", ")", "for", "node", "in", "dag_nodes", ":", "multibit_gate", "=", "len", "(", "node", ".", "qargs", ")", "+", "len", "(", "node", ".", "cargs", ")", ">", "1", "if", "multibit_gate", ":", "# need to see if it crosses over any other nodes", "gate_span", "=", "_get_gate_span", "(", "qregs", ",", "node", ")", "all_indices", "=", "[", "]", "for", "check_node", "in", "dag_nodes", ":", "if", "check_node", "!=", "node", ":", "all_indices", "+=", "_get_gate_span", "(", "qregs", ",", "check_node", ")", "if", "any", "(", "i", "in", "gate_span", "for", "i", "in", "all_indices", ")", ":", "# needs to be a new layer", "layers", ".", "append", "(", "[", "node", "]", ")", "else", ":", "# can be added", "current_layer", ".", "append", "(", "node", ")", "else", ":", "current_layer", ".", "append", "(", "node", ")", "if", "current_layer", ":", "layers", ".", "append", "(", "current_layer", ")", "ops", "+=", "layers", "if", "justify", "==", "'right'", ":", "dag_layers", "=", "[", "]", "for", "dag_layer", "in", "dag", ".", "layers", "(", ")", ":", "dag_layers", ".", "append", "(", "dag_layer", ")", "# Have to work from the end of the circuit", "dag_layers", ".", "reverse", "(", ")", "# Dict per layer, keys are qubits and values are the gate", "layer_dicts", "=", "[", "{", "}", "]", "for", "dag_layer", "in", "dag_layers", ":", "dag_instructions", "=", "dag_layer", "[", "'graph'", "]", ".", "op_nodes", "(", ")", "# sort into the order they were input", "dag_instructions", ".", "sort", "(", "key", "=", "lambda", "nd", ":", "nd", ".", "_node_id", ")", "for", "instruction_node", "in", "dag_instructions", ":", "gate_span", "=", "_get_gate_span", "(", "qregs", ",", "instruction_node", ")", "added", "=", "False", "for", "i", "in", "range", "(", "len", "(", "layer_dicts", ")", ")", ":", "# iterate from the end", "curr_dict", "=", "layer_dicts", "[", "-", "1", "-", "i", "]", "if", "any", "(", "index", "in", "curr_dict", "for", "index", "in", "gate_span", ")", ":", "added", "=", "True", "if", "i", "==", "0", ":", "new_dict", "=", "{", "}", "for", "index", "in", "gate_span", ":", "new_dict", "[", "index", "]", "=", "instruction_node", "layer_dicts", ".", "append", "(", "new_dict", ")", "else", ":", "curr_dict", "=", "layer_dicts", "[", "-", "i", "]", "for", "index", "in", "gate_span", ":", "curr_dict", "[", "index", "]", "=", "instruction_node", "break", "if", "not", "added", ":", "for", "index", "in", "gate_span", ":", "layer_dicts", "[", "0", "]", "[", "index", "]", "=", "instruction_node", "# need to convert from dict format to layers", "layer_dicts", ".", "reverse", "(", ")", "ops", "=", "[", "list", "(", "layer", ".", "values", "(", ")", ")", "for", "layer", "in", "layer_dicts", "]", "if", "reverse_bits", ":", "qregs", ".", "reverse", "(", ")", "cregs", ".", "reverse", "(", ")", "return", "qregs", ",", "cregs", ",", "ops" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_get_gate_span
Get the list of qubits drawing this gate would cover
qiskit/visualization/utils.py
def _get_gate_span(qregs, instruction): """Get the list of qubits drawing this gate would cover""" min_index = len(qregs) max_index = 0 for qreg in instruction.qargs: index = qregs.index(qreg) if index < min_index: min_index = index if index > max_index: max_index = index if instruction.cargs: return qregs[min_index:] return qregs[min_index:max_index + 1]
def _get_gate_span(qregs, instruction): """Get the list of qubits drawing this gate would cover""" min_index = len(qregs) max_index = 0 for qreg in instruction.qargs: index = qregs.index(qreg) if index < min_index: min_index = index if index > max_index: max_index = index if instruction.cargs: return qregs[min_index:] return qregs[min_index:max_index + 1]
[ "Get", "the", "list", "of", "qubits", "drawing", "this", "gate", "would", "cover" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/utils.py#L178-L194
[ "def", "_get_gate_span", "(", "qregs", ",", "instruction", ")", ":", "min_index", "=", "len", "(", "qregs", ")", "max_index", "=", "0", "for", "qreg", "in", "instruction", ".", "qargs", ":", "index", "=", "qregs", ".", "index", "(", "qreg", ")", "if", "index", "<", "min_index", ":", "min_index", "=", "index", "if", "index", ">", "max_index", ":", "max_index", "=", "index", "if", "instruction", ".", "cargs", ":", "return", "qregs", "[", "min_index", ":", "]", "return", "qregs", "[", "min_index", ":", "max_index", "+", "1", "]" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
circuit_to_instruction
Build an ``Instruction`` object from a ``QuantumCircuit``. The instruction is anonymous (not tied to a named quantum register), and so can be inserted into another circuit. The instruction will have the same string name as the circuit. Args: circuit (QuantumCircuit): the input circuit. Return: Instruction: an instruction equivalent to the action of the input circuit. Upon decomposition, this instruction will yield the components comprising the original circuit.
qiskit/converters/circuit_to_instruction.py
def circuit_to_instruction(circuit): """Build an ``Instruction`` object from a ``QuantumCircuit``. The instruction is anonymous (not tied to a named quantum register), and so can be inserted into another circuit. The instruction will have the same string name as the circuit. Args: circuit (QuantumCircuit): the input circuit. Return: Instruction: an instruction equivalent to the action of the input circuit. Upon decomposition, this instruction will yield the components comprising the original circuit. """ instruction = Instruction(name=circuit.name, num_qubits=sum([qreg.size for qreg in circuit.qregs]), num_clbits=sum([creg.size for creg in circuit.cregs]), params=[]) instruction.control = None def find_bit_position(bit): """find the index of a given bit (Register, int) within a flat ordered list of bits of the circuit """ if isinstance(bit[0], QuantumRegister): ordered_regs = circuit.qregs else: ordered_regs = circuit.cregs reg_index = ordered_regs.index(bit[0]) return sum([reg.size for reg in ordered_regs[:reg_index]]) + bit[1] definition = circuit.data.copy() if instruction.num_qubits > 0: q = QuantumRegister(instruction.num_qubits, 'q') if instruction.num_clbits > 0: c = ClassicalRegister(instruction.num_clbits, 'c') definition = list(map(lambda x: (x[0], list(map(lambda y: (q, find_bit_position(y)), x[1])), list(map(lambda y: (c, find_bit_position(y)), x[2]))), definition)) instruction.definition = definition return instruction
def circuit_to_instruction(circuit): """Build an ``Instruction`` object from a ``QuantumCircuit``. The instruction is anonymous (not tied to a named quantum register), and so can be inserted into another circuit. The instruction will have the same string name as the circuit. Args: circuit (QuantumCircuit): the input circuit. Return: Instruction: an instruction equivalent to the action of the input circuit. Upon decomposition, this instruction will yield the components comprising the original circuit. """ instruction = Instruction(name=circuit.name, num_qubits=sum([qreg.size for qreg in circuit.qregs]), num_clbits=sum([creg.size for creg in circuit.cregs]), params=[]) instruction.control = None def find_bit_position(bit): """find the index of a given bit (Register, int) within a flat ordered list of bits of the circuit """ if isinstance(bit[0], QuantumRegister): ordered_regs = circuit.qregs else: ordered_regs = circuit.cregs reg_index = ordered_regs.index(bit[0]) return sum([reg.size for reg in ordered_regs[:reg_index]]) + bit[1] definition = circuit.data.copy() if instruction.num_qubits > 0: q = QuantumRegister(instruction.num_qubits, 'q') if instruction.num_clbits > 0: c = ClassicalRegister(instruction.num_clbits, 'c') definition = list(map(lambda x: (x[0], list(map(lambda y: (q, find_bit_position(y)), x[1])), list(map(lambda y: (c, find_bit_position(y)), x[2]))), definition)) instruction.definition = definition return instruction
[ "Build", "an", "Instruction", "object", "from", "a", "QuantumCircuit", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/converters/circuit_to_instruction.py#L15-L60
[ "def", "circuit_to_instruction", "(", "circuit", ")", ":", "instruction", "=", "Instruction", "(", "name", "=", "circuit", ".", "name", ",", "num_qubits", "=", "sum", "(", "[", "qreg", ".", "size", "for", "qreg", "in", "circuit", ".", "qregs", "]", ")", ",", "num_clbits", "=", "sum", "(", "[", "creg", ".", "size", "for", "creg", "in", "circuit", ".", "cregs", "]", ")", ",", "params", "=", "[", "]", ")", "instruction", ".", "control", "=", "None", "def", "find_bit_position", "(", "bit", ")", ":", "\"\"\"find the index of a given bit (Register, int) within\n a flat ordered list of bits of the circuit\n \"\"\"", "if", "isinstance", "(", "bit", "[", "0", "]", ",", "QuantumRegister", ")", ":", "ordered_regs", "=", "circuit", ".", "qregs", "else", ":", "ordered_regs", "=", "circuit", ".", "cregs", "reg_index", "=", "ordered_regs", ".", "index", "(", "bit", "[", "0", "]", ")", "return", "sum", "(", "[", "reg", ".", "size", "for", "reg", "in", "ordered_regs", "[", ":", "reg_index", "]", "]", ")", "+", "bit", "[", "1", "]", "definition", "=", "circuit", ".", "data", ".", "copy", "(", ")", "if", "instruction", ".", "num_qubits", ">", "0", ":", "q", "=", "QuantumRegister", "(", "instruction", ".", "num_qubits", ",", "'q'", ")", "if", "instruction", ".", "num_clbits", ">", "0", ":", "c", "=", "ClassicalRegister", "(", "instruction", ".", "num_clbits", ",", "'c'", ")", "definition", "=", "list", "(", "map", "(", "lambda", "x", ":", "(", "x", "[", "0", "]", ",", "list", "(", "map", "(", "lambda", "y", ":", "(", "q", ",", "find_bit_position", "(", "y", ")", ")", ",", "x", "[", "1", "]", ")", ")", ",", "list", "(", "map", "(", "lambda", "y", ":", "(", "c", ",", "find_bit_position", "(", "y", ")", ")", ",", "x", "[", "2", "]", ")", ")", ")", ",", "definition", ")", ")", "instruction", ".", "definition", "=", "definition", "return", "instruction" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
DenseLayout.run
Pick a convenient layout depending on the best matching qubit connectivity, and set the property `layout`. Args: dag (DAGCircuit): DAG to find layout for. Raises: TranspilerError: if dag wider than self.coupling_map
qiskit/transpiler/passes/mapping/dense_layout.py
def run(self, dag): """ Pick a convenient layout depending on the best matching qubit connectivity, and set the property `layout`. Args: dag (DAGCircuit): DAG to find layout for. Raises: TranspilerError: if dag wider than self.coupling_map """ num_dag_qubits = sum([qreg.size for qreg in dag.qregs.values()]) if num_dag_qubits > self.coupling_map.size(): raise TranspilerError('Number of qubits greater than device.') best_sub = self._best_subset(num_dag_qubits) layout = Layout() map_iter = 0 for qreg in dag.qregs.values(): for i in range(qreg.size): layout[(qreg, i)] = int(best_sub[map_iter]) map_iter += 1 self.property_set['layout'] = layout
def run(self, dag): """ Pick a convenient layout depending on the best matching qubit connectivity, and set the property `layout`. Args: dag (DAGCircuit): DAG to find layout for. Raises: TranspilerError: if dag wider than self.coupling_map """ num_dag_qubits = sum([qreg.size for qreg in dag.qregs.values()]) if num_dag_qubits > self.coupling_map.size(): raise TranspilerError('Number of qubits greater than device.') best_sub = self._best_subset(num_dag_qubits) layout = Layout() map_iter = 0 for qreg in dag.qregs.values(): for i in range(qreg.size): layout[(qreg, i)] = int(best_sub[map_iter]) map_iter += 1 self.property_set['layout'] = layout
[ "Pick", "a", "convenient", "layout", "depending", "on", "the", "best", "matching", "qubit", "connectivity", "and", "set", "the", "property", "layout", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/dense_layout.py#L45-L66
[ "def", "run", "(", "self", ",", "dag", ")", ":", "num_dag_qubits", "=", "sum", "(", "[", "qreg", ".", "size", "for", "qreg", "in", "dag", ".", "qregs", ".", "values", "(", ")", "]", ")", "if", "num_dag_qubits", ">", "self", ".", "coupling_map", ".", "size", "(", ")", ":", "raise", "TranspilerError", "(", "'Number of qubits greater than device.'", ")", "best_sub", "=", "self", ".", "_best_subset", "(", "num_dag_qubits", ")", "layout", "=", "Layout", "(", ")", "map_iter", "=", "0", "for", "qreg", "in", "dag", ".", "qregs", ".", "values", "(", ")", ":", "for", "i", "in", "range", "(", "qreg", ".", "size", ")", ":", "layout", "[", "(", "qreg", ",", "i", ")", "]", "=", "int", "(", "best_sub", "[", "map_iter", "]", ")", "map_iter", "+=", "1", "self", ".", "property_set", "[", "'layout'", "]", "=", "layout" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
DenseLayout._best_subset
Computes the qubit mapping with the best connectivity. Args: n_qubits (int): Number of subset qubits to consider. Returns: ndarray: Array of qubits to use for best connectivity mapping.
qiskit/transpiler/passes/mapping/dense_layout.py
def _best_subset(self, n_qubits): """Computes the qubit mapping with the best connectivity. Args: n_qubits (int): Number of subset qubits to consider. Returns: ndarray: Array of qubits to use for best connectivity mapping. """ if n_qubits == 1: return np.array([0]) device_qubits = self.coupling_map.size() cmap = np.asarray(self.coupling_map.get_edges()) data = np.ones_like(cmap[:, 0]) sp_cmap = sp.coo_matrix((data, (cmap[:, 0], cmap[:, 1])), shape=(device_qubits, device_qubits)).tocsr() best = 0 best_map = None # do bfs with each node as starting point for k in range(sp_cmap.shape[0]): bfs = cs.breadth_first_order(sp_cmap, i_start=k, directed=False, return_predecessors=False) connection_count = 0 sub_graph = [] for i in range(n_qubits): node_idx = bfs[i] for j in range(sp_cmap.indptr[node_idx], sp_cmap.indptr[node_idx + 1]): node = sp_cmap.indices[j] for counter in range(n_qubits): if node == bfs[counter]: connection_count += 1 sub_graph.append([node_idx, node]) break if connection_count > best: best = connection_count best_map = bfs[0:n_qubits] # Return a best mapping that has reduced bandwidth mapping = {} for edge in range(best_map.shape[0]): mapping[best_map[edge]] = edge new_cmap = [[mapping[c[0]], mapping[c[1]]] for c in sub_graph] rows = [edge[0] for edge in new_cmap] cols = [edge[1] for edge in new_cmap] data = [1]*len(rows) sp_sub_graph = sp.coo_matrix((data, (rows, cols)), shape=(n_qubits, n_qubits)).tocsr() perm = cs.reverse_cuthill_mckee(sp_sub_graph) best_map = best_map[perm] return best_map
def _best_subset(self, n_qubits): """Computes the qubit mapping with the best connectivity. Args: n_qubits (int): Number of subset qubits to consider. Returns: ndarray: Array of qubits to use for best connectivity mapping. """ if n_qubits == 1: return np.array([0]) device_qubits = self.coupling_map.size() cmap = np.asarray(self.coupling_map.get_edges()) data = np.ones_like(cmap[:, 0]) sp_cmap = sp.coo_matrix((data, (cmap[:, 0], cmap[:, 1])), shape=(device_qubits, device_qubits)).tocsr() best = 0 best_map = None # do bfs with each node as starting point for k in range(sp_cmap.shape[0]): bfs = cs.breadth_first_order(sp_cmap, i_start=k, directed=False, return_predecessors=False) connection_count = 0 sub_graph = [] for i in range(n_qubits): node_idx = bfs[i] for j in range(sp_cmap.indptr[node_idx], sp_cmap.indptr[node_idx + 1]): node = sp_cmap.indices[j] for counter in range(n_qubits): if node == bfs[counter]: connection_count += 1 sub_graph.append([node_idx, node]) break if connection_count > best: best = connection_count best_map = bfs[0:n_qubits] # Return a best mapping that has reduced bandwidth mapping = {} for edge in range(best_map.shape[0]): mapping[best_map[edge]] = edge new_cmap = [[mapping[c[0]], mapping[c[1]]] for c in sub_graph] rows = [edge[0] for edge in new_cmap] cols = [edge[1] for edge in new_cmap] data = [1]*len(rows) sp_sub_graph = sp.coo_matrix((data, (rows, cols)), shape=(n_qubits, n_qubits)).tocsr() perm = cs.reverse_cuthill_mckee(sp_sub_graph) best_map = best_map[perm] return best_map
[ "Computes", "the", "qubit", "mapping", "with", "the", "best", "connectivity", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/dense_layout.py#L68-L121
[ "def", "_best_subset", "(", "self", ",", "n_qubits", ")", ":", "if", "n_qubits", "==", "1", ":", "return", "np", ".", "array", "(", "[", "0", "]", ")", "device_qubits", "=", "self", ".", "coupling_map", ".", "size", "(", ")", "cmap", "=", "np", ".", "asarray", "(", "self", ".", "coupling_map", ".", "get_edges", "(", ")", ")", "data", "=", "np", ".", "ones_like", "(", "cmap", "[", ":", ",", "0", "]", ")", "sp_cmap", "=", "sp", ".", "coo_matrix", "(", "(", "data", ",", "(", "cmap", "[", ":", ",", "0", "]", ",", "cmap", "[", ":", ",", "1", "]", ")", ")", ",", "shape", "=", "(", "device_qubits", ",", "device_qubits", ")", ")", ".", "tocsr", "(", ")", "best", "=", "0", "best_map", "=", "None", "# do bfs with each node as starting point", "for", "k", "in", "range", "(", "sp_cmap", ".", "shape", "[", "0", "]", ")", ":", "bfs", "=", "cs", ".", "breadth_first_order", "(", "sp_cmap", ",", "i_start", "=", "k", ",", "directed", "=", "False", ",", "return_predecessors", "=", "False", ")", "connection_count", "=", "0", "sub_graph", "=", "[", "]", "for", "i", "in", "range", "(", "n_qubits", ")", ":", "node_idx", "=", "bfs", "[", "i", "]", "for", "j", "in", "range", "(", "sp_cmap", ".", "indptr", "[", "node_idx", "]", ",", "sp_cmap", ".", "indptr", "[", "node_idx", "+", "1", "]", ")", ":", "node", "=", "sp_cmap", ".", "indices", "[", "j", "]", "for", "counter", "in", "range", "(", "n_qubits", ")", ":", "if", "node", "==", "bfs", "[", "counter", "]", ":", "connection_count", "+=", "1", "sub_graph", ".", "append", "(", "[", "node_idx", ",", "node", "]", ")", "break", "if", "connection_count", ">", "best", ":", "best", "=", "connection_count", "best_map", "=", "bfs", "[", "0", ":", "n_qubits", "]", "# Return a best mapping that has reduced bandwidth", "mapping", "=", "{", "}", "for", "edge", "in", "range", "(", "best_map", ".", "shape", "[", "0", "]", ")", ":", "mapping", "[", "best_map", "[", "edge", "]", "]", "=", "edge", "new_cmap", "=", "[", "[", "mapping", "[", "c", "[", "0", "]", "]", ",", "mapping", "[", "c", "[", "1", "]", "]", "]", "for", "c", "in", "sub_graph", "]", "rows", "=", "[", "edge", "[", "0", "]", "for", "edge", "in", "new_cmap", "]", "cols", "=", "[", "edge", "[", "1", "]", "for", "edge", "in", "new_cmap", "]", "data", "=", "[", "1", "]", "*", "len", "(", "rows", ")", "sp_sub_graph", "=", "sp", ".", "coo_matrix", "(", "(", "data", ",", "(", "rows", ",", "cols", ")", ")", ",", "shape", "=", "(", "n_qubits", ",", "n_qubits", ")", ")", ".", "tocsr", "(", ")", "perm", "=", "cs", ".", "reverse_cuthill_mckee", "(", "sp_sub_graph", ")", "best_map", "=", "best_map", "[", "perm", "]", "return", "best_map" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Kraus.is_cptp
Return True if completely-positive trace-preserving.
qiskit/quantum_info/operators/channel/kraus.py
def is_cptp(self, atol=None, rtol=None): """Return True if completely-positive trace-preserving.""" if self._data[1] is not None: return False if atol is None: atol = self._atol if rtol is None: rtol = self._rtol accum = 0j for op in self._data[0]: accum += np.dot(np.transpose(np.conj(op)), op) return is_identity_matrix(accum, rtol=rtol, atol=atol)
def is_cptp(self, atol=None, rtol=None): """Return True if completely-positive trace-preserving.""" if self._data[1] is not None: return False if atol is None: atol = self._atol if rtol is None: rtol = self._rtol accum = 0j for op in self._data[0]: accum += np.dot(np.transpose(np.conj(op)), op) return is_identity_matrix(accum, rtol=rtol, atol=atol)
[ "Return", "True", "if", "completely", "-", "positive", "trace", "-", "preserving", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/kraus.py#L166-L177
[ "def", "is_cptp", "(", "self", ",", "atol", "=", "None", ",", "rtol", "=", "None", ")", ":", "if", "self", ".", "_data", "[", "1", "]", "is", "not", "None", ":", "return", "False", "if", "atol", "is", "None", ":", "atol", "=", "self", ".", "_atol", "if", "rtol", "is", "None", ":", "rtol", "=", "self", ".", "_rtol", "accum", "=", "0j", "for", "op", "in", "self", ".", "_data", "[", "0", "]", ":", "accum", "+=", "np", ".", "dot", "(", "np", ".", "transpose", "(", "np", ".", "conj", "(", "op", ")", ")", ",", "op", ")", "return", "is_identity_matrix", "(", "accum", ",", "rtol", "=", "rtol", ",", "atol", "=", "atol", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Kraus.conjugate
Return the conjugate of the QuantumChannel.
qiskit/quantum_info/operators/channel/kraus.py
def conjugate(self): """Return the conjugate of the QuantumChannel.""" kraus_l, kraus_r = self._data kraus_l = [k.conj() for k in kraus_l] if kraus_r is not None: kraus_r = [k.conj() for k in kraus_r] return Kraus((kraus_l, kraus_r), self.input_dims(), self.output_dims())
def conjugate(self): """Return the conjugate of the QuantumChannel.""" kraus_l, kraus_r = self._data kraus_l = [k.conj() for k in kraus_l] if kraus_r is not None: kraus_r = [k.conj() for k in kraus_r] return Kraus((kraus_l, kraus_r), self.input_dims(), self.output_dims())
[ "Return", "the", "conjugate", "of", "the", "QuantumChannel", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/kraus.py#L179-L185
[ "def", "conjugate", "(", "self", ")", ":", "kraus_l", ",", "kraus_r", "=", "self", ".", "_data", "kraus_l", "=", "[", "k", ".", "conj", "(", ")", "for", "k", "in", "kraus_l", "]", "if", "kraus_r", "is", "not", "None", ":", "kraus_r", "=", "[", "k", ".", "conj", "(", ")", "for", "k", "in", "kraus_r", "]", "return", "Kraus", "(", "(", "kraus_l", ",", "kraus_r", ")", ",", "self", ".", "input_dims", "(", ")", ",", "self", ".", "output_dims", "(", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Kraus.transpose
Return the transpose of the QuantumChannel.
qiskit/quantum_info/operators/channel/kraus.py
def transpose(self): """Return the transpose of the QuantumChannel.""" kraus_l, kraus_r = self._data kraus_l = [k.T for k in kraus_l] if kraus_r is not None: kraus_r = [k.T for k in kraus_r] return Kraus((kraus_l, kraus_r), input_dims=self.output_dims(), output_dims=self.input_dims())
def transpose(self): """Return the transpose of the QuantumChannel.""" kraus_l, kraus_r = self._data kraus_l = [k.T for k in kraus_l] if kraus_r is not None: kraus_r = [k.T for k in kraus_r] return Kraus((kraus_l, kraus_r), input_dims=self.output_dims(), output_dims=self.input_dims())
[ "Return", "the", "transpose", "of", "the", "QuantumChannel", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/kraus.py#L187-L195
[ "def", "transpose", "(", "self", ")", ":", "kraus_l", ",", "kraus_r", "=", "self", ".", "_data", "kraus_l", "=", "[", "k", ".", "T", "for", "k", "in", "kraus_l", "]", "if", "kraus_r", "is", "not", "None", ":", "kraus_r", "=", "[", "k", ".", "T", "for", "k", "in", "kraus_r", "]", "return", "Kraus", "(", "(", "kraus_l", ",", "kraus_r", ")", ",", "input_dims", "=", "self", ".", "output_dims", "(", ")", ",", "output_dims", "=", "self", ".", "input_dims", "(", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Kraus.compose
Return the composition channel self∘other. Args: other (QuantumChannel): a quantum channel subclass. 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: Kraus: The composition channel as a Kraus object. Raises: QiskitError: if other cannot be converted to a channel, or has incompatible dimensions.
qiskit/quantum_info/operators/channel/kraus.py
def compose(self, other, qargs=None, front=False): """Return the composition channel self∘other. Args: other (QuantumChannel): a quantum channel subclass. 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: Kraus: The composition channel as a Kraus object. Raises: QiskitError: if other cannot be converted to a channel, or has incompatible dimensions. """ if qargs is not None: return Kraus( SuperOp(self).compose(other, qargs=qargs, front=front)) if not isinstance(other, Kraus): other = Kraus(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: ka_l, ka_r = self._data kb_l, kb_r = other._data input_dim = other._input_dim output_dim = self._output_dim else: ka_l, ka_r = other._data kb_l, kb_r = self._data input_dim = self._input_dim output_dim = other._output_dim kab_l = [np.dot(a, b) for a in ka_l for b in kb_l] if ka_r is None and kb_r is None: kab_r = None elif ka_r is None: kab_r = [np.dot(a, b) for a in ka_l for b in kb_r] elif kb_r is None: kab_r = [np.dot(a, b) for a in ka_r for b in kb_l] else: kab_r = [np.dot(a, b) for a in ka_r for b in kb_r] return Kraus((kab_l, kab_r), input_dim, output_dim)
def compose(self, other, qargs=None, front=False): """Return the composition channel self∘other. Args: other (QuantumChannel): a quantum channel subclass. 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: Kraus: The composition channel as a Kraus object. Raises: QiskitError: if other cannot be converted to a channel, or has incompatible dimensions. """ if qargs is not None: return Kraus( SuperOp(self).compose(other, qargs=qargs, front=front)) if not isinstance(other, Kraus): other = Kraus(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: ka_l, ka_r = self._data kb_l, kb_r = other._data input_dim = other._input_dim output_dim = self._output_dim else: ka_l, ka_r = other._data kb_l, kb_r = self._data input_dim = self._input_dim output_dim = other._output_dim kab_l = [np.dot(a, b) for a in ka_l for b in kb_l] if ka_r is None and kb_r is None: kab_r = None elif ka_r is None: kab_r = [np.dot(a, b) for a in ka_l for b in kb_r] elif kb_r is None: kab_r = [np.dot(a, b) for a in ka_r for b in kb_l] else: kab_r = [np.dot(a, b) for a in ka_r for b in kb_r] return Kraus((kab_l, kab_r), 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/kraus.py#L197-L248
[ "def", "compose", "(", "self", ",", "other", ",", "qargs", "=", "None", ",", "front", "=", "False", ")", ":", "if", "qargs", "is", "not", "None", ":", "return", "Kraus", "(", "SuperOp", "(", "self", ")", ".", "compose", "(", "other", ",", "qargs", "=", "qargs", ",", "front", "=", "front", ")", ")", "if", "not", "isinstance", "(", "other", ",", "Kraus", ")", ":", "other", "=", "Kraus", "(", "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", ":", "ka_l", ",", "ka_r", "=", "self", ".", "_data", "kb_l", ",", "kb_r", "=", "other", ".", "_data", "input_dim", "=", "other", ".", "_input_dim", "output_dim", "=", "self", ".", "_output_dim", "else", ":", "ka_l", ",", "ka_r", "=", "other", ".", "_data", "kb_l", ",", "kb_r", "=", "self", ".", "_data", "input_dim", "=", "self", ".", "_input_dim", "output_dim", "=", "other", ".", "_output_dim", "kab_l", "=", "[", "np", ".", "dot", "(", "a", ",", "b", ")", "for", "a", "in", "ka_l", "for", "b", "in", "kb_l", "]", "if", "ka_r", "is", "None", "and", "kb_r", "is", "None", ":", "kab_r", "=", "None", "elif", "ka_r", "is", "None", ":", "kab_r", "=", "[", "np", ".", "dot", "(", "a", ",", "b", ")", "for", "a", "in", "ka_l", "for", "b", "in", "kb_r", "]", "elif", "kb_r", "is", "None", ":", "kab_r", "=", "[", "np", ".", "dot", "(", "a", ",", "b", ")", "for", "a", "in", "ka_r", "for", "b", "in", "kb_l", "]", "else", ":", "kab_r", "=", "[", "np", ".", "dot", "(", "a", ",", "b", ")", "for", "a", "in", "ka_r", "for", "b", "in", "kb_r", "]", "return", "Kraus", "(", "(", "kab_l", ",", "kab_r", ")", ",", "input_dim", ",", "output_dim", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Kraus.power
The matrix power of the channel. Args: n (int): compute the matrix power of the superoperator matrix. Returns: Kraus: the matrix power of the SuperOp converted to a Kraus 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/kraus.py
def power(self, n): """The matrix power of the channel. Args: n (int): compute the matrix power of the superoperator matrix. Returns: Kraus: the matrix power of the SuperOp converted to a Kraus 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 Kraus(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: Kraus: the matrix power of the SuperOp converted to a Kraus 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 Kraus(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/kraus.py#L250-L265
[ "def", "power", "(", "self", ",", "n", ")", ":", "if", "n", ">", "0", ":", "return", "super", "(", ")", ".", "power", "(", "n", ")", "return", "Kraus", "(", "SuperOp", "(", "self", ")", ".", "power", "(", "n", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Kraus.multiply
Return the QuantumChannel self + other. Args: other (complex): a complex number. Returns: Kraus: the scalar multiplication other * self as a Kraus object. Raises: QiskitError: if other is not a valid scalar.
qiskit/quantum_info/operators/channel/kraus.py
def multiply(self, other): """Return the QuantumChannel self + other. Args: other (complex): a complex number. Returns: Kraus: the scalar multiplication other * self as a Kraus object. Raises: QiskitError: if other is not a valid scalar. """ if not isinstance(other, Number): raise QiskitError("other is not a number") # If the number is complex we need to convert to general # kraus channel so we multiply via Choi representation if isinstance(other, complex) or other < 0: # Convert to Choi-matrix return Kraus(Choi(self).multiply(other)) # If the number is real we can update the Kraus operators # directly val = np.sqrt(other) kraus_r = None kraus_l = [val * k for k in self._data[0]] if self._data[1] is not None: kraus_r = [val * k for k in self._data[1]] return Kraus((kraus_l, kraus_r), self._input_dim, self._output_dim)
def multiply(self, other): """Return the QuantumChannel self + other. Args: other (complex): a complex number. Returns: Kraus: the scalar multiplication other * self as a Kraus object. Raises: QiskitError: if other is not a valid scalar. """ if not isinstance(other, Number): raise QiskitError("other is not a number") # If the number is complex we need to convert to general # kraus channel so we multiply via Choi representation if isinstance(other, complex) or other < 0: # Convert to Choi-matrix return Kraus(Choi(self).multiply(other)) # If the number is real we can update the Kraus operators # directly val = np.sqrt(other) kraus_r = None kraus_l = [val * k for k in self._data[0]] if self._data[1] is not None: kraus_r = [val * k for k in self._data[1]] return Kraus((kraus_l, kraus_r), self._input_dim, self._output_dim)
[ "Return", "the", "QuantumChannel", "self", "+", "other", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/kraus.py#L333-L359
[ "def", "multiply", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "Number", ")", ":", "raise", "QiskitError", "(", "\"other is not a number\"", ")", "# If the number is complex we need to convert to general", "# kraus channel so we multiply via Choi representation", "if", "isinstance", "(", "other", ",", "complex", ")", "or", "other", "<", "0", ":", "# Convert to Choi-matrix", "return", "Kraus", "(", "Choi", "(", "self", ")", ".", "multiply", "(", "other", ")", ")", "# If the number is real we can update the Kraus operators", "# directly", "val", "=", "np", ".", "sqrt", "(", "other", ")", "kraus_r", "=", "None", "kraus_l", "=", "[", "val", "*", "k", "for", "k", "in", "self", ".", "_data", "[", "0", "]", "]", "if", "self", ".", "_data", "[", "1", "]", "is", "not", "None", ":", "kraus_r", "=", "[", "val", "*", "k", "for", "k", "in", "self", ".", "_data", "[", "1", "]", "]", "return", "Kraus", "(", "(", "kraus_l", ",", "kraus_r", ")", ",", "self", ".", "_input_dim", ",", "self", ".", "_output_dim", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Kraus._evolve
Evolve a quantum state by the QuantumChannel. Args: state (QuantumState): The input statevector or density matrix. qargs (list): a list of QuantumState subsystem positions to apply the operator on. Returns: QuantumState: the output quantum state. Raises: QiskitError: if the operator dimension does not match the specified QuantumState subsystem dimensions.
qiskit/quantum_info/operators/channel/kraus.py
def _evolve(self, state, qargs=None): """Evolve a quantum state by the QuantumChannel. Args: state (QuantumState): The input statevector or density matrix. qargs (list): a list of QuantumState subsystem positions to apply the operator on. Returns: QuantumState: the output quantum state. Raises: QiskitError: if the operator dimension does not match the specified QuantumState subsystem dimensions. """ # If subsystem evolution we use the SuperOp representation if qargs is not None: return SuperOp(self)._evolve(state, qargs) # Otherwise we compute full evolution directly state = self._format_state(state) if state.shape[0] != self._input_dim: raise QiskitError( "QuantumChannel input dimension is not equal to state dimension." ) if state.ndim == 1 and self._data[1] is None and len( self._data[0]) == 1: # If we only have a single Kraus operator we can implement unitary-type # evolution of a state vector psi -> K[0].psi return np.dot(self._data[0][0], state) # Otherwise we always return a density matrix state = self._format_state(state, density_matrix=True) kraus_l, kraus_r = self._data if kraus_r is None: kraus_r = kraus_l return np.einsum('AiB,BC,AjC->ij', kraus_l, state, np.conjugate(kraus_r))
def _evolve(self, state, qargs=None): """Evolve a quantum state by the QuantumChannel. Args: state (QuantumState): The input statevector or density matrix. qargs (list): a list of QuantumState subsystem positions to apply the operator on. Returns: QuantumState: the output quantum state. Raises: QiskitError: if the operator dimension does not match the specified QuantumState subsystem dimensions. """ # If subsystem evolution we use the SuperOp representation if qargs is not None: return SuperOp(self)._evolve(state, qargs) # Otherwise we compute full evolution directly state = self._format_state(state) if state.shape[0] != self._input_dim: raise QiskitError( "QuantumChannel input dimension is not equal to state dimension." ) if state.ndim == 1 and self._data[1] is None and len( self._data[0]) == 1: # If we only have a single Kraus operator we can implement unitary-type # evolution of a state vector psi -> K[0].psi return np.dot(self._data[0][0], state) # Otherwise we always return a density matrix state = self._format_state(state, density_matrix=True) kraus_l, kraus_r = self._data if kraus_r is None: kraus_r = kraus_l return np.einsum('AiB,BC,AjC->ij', kraus_l, state, np.conjugate(kraus_r))
[ "Evolve", "a", "quantum", "state", "by", "the", "QuantumChannel", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/kraus.py#L361-L397
[ "def", "_evolve", "(", "self", ",", "state", ",", "qargs", "=", "None", ")", ":", "# If subsystem evolution we use the SuperOp representation", "if", "qargs", "is", "not", "None", ":", "return", "SuperOp", "(", "self", ")", ".", "_evolve", "(", "state", ",", "qargs", ")", "# Otherwise we compute full evolution directly", "state", "=", "self", ".", "_format_state", "(", "state", ")", "if", "state", ".", "shape", "[", "0", "]", "!=", "self", ".", "_input_dim", ":", "raise", "QiskitError", "(", "\"QuantumChannel input dimension is not equal to state dimension.\"", ")", "if", "state", ".", "ndim", "==", "1", "and", "self", ".", "_data", "[", "1", "]", "is", "None", "and", "len", "(", "self", ".", "_data", "[", "0", "]", ")", "==", "1", ":", "# If we only have a single Kraus operator we can implement unitary-type", "# evolution of a state vector psi -> K[0].psi", "return", "np", ".", "dot", "(", "self", ".", "_data", "[", "0", "]", "[", "0", "]", ",", "state", ")", "# Otherwise we always return a density matrix", "state", "=", "self", ".", "_format_state", "(", "state", ",", "density_matrix", "=", "True", ")", "kraus_l", ",", "kraus_r", "=", "self", ".", "_data", "if", "kraus_r", "is", "None", ":", "kraus_r", "=", "kraus_l", "return", "np", ".", "einsum", "(", "'AiB,BC,AjC->ij'", ",", "kraus_l", ",", "state", ",", "np", ".", "conjugate", "(", "kraus_r", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Kraus._tensor_product
Return the tensor product channel. Args: other (QuantumChannel): a quantum channel subclass. reverse (bool): If False return self ⊗ other, if True return if True return (other ⊗ self) [Default: False Returns: Kraus: the tensor product channel as a Kraus object. Raises: QiskitError: if other cannot be converted to a channel.
qiskit/quantum_info/operators/channel/kraus.py
def _tensor_product(self, other, reverse=False): """Return the tensor product channel. Args: other (QuantumChannel): a quantum channel subclass. reverse (bool): If False return self ⊗ other, if True return if True return (other ⊗ self) [Default: False Returns: Kraus: the tensor product channel as a Kraus object. Raises: QiskitError: if other cannot be converted to a channel. """ # Convert other to Kraus if not isinstance(other, Kraus): other = Kraus(other) # Get tensor matrix ka_l, ka_r = self._data kb_l, kb_r = other._data if reverse: input_dims = self.input_dims() + other.input_dims() output_dims = self.output_dims() + other.output_dims() kab_l = [np.kron(b, a) for a in ka_l for b in kb_l] else: input_dims = other.input_dims() + self.input_dims() output_dims = other.output_dims() + self.output_dims() kab_l = [np.kron(a, b) for a in ka_l for b in kb_l] if ka_r is None and kb_r is None: kab_r = None else: if ka_r is None: ka_r = ka_l if kb_r is None: kb_r = kb_l if reverse: kab_r = [np.kron(b, a) for a in ka_r for b in kb_r] else: kab_r = [np.kron(a, b) for a in ka_r for b in kb_r] data = (kab_l, kab_r) return Kraus(data, input_dims, output_dims)
def _tensor_product(self, other, reverse=False): """Return the tensor product channel. Args: other (QuantumChannel): a quantum channel subclass. reverse (bool): If False return self ⊗ other, if True return if True return (other ⊗ self) [Default: False Returns: Kraus: the tensor product channel as a Kraus object. Raises: QiskitError: if other cannot be converted to a channel. """ # Convert other to Kraus if not isinstance(other, Kraus): other = Kraus(other) # Get tensor matrix ka_l, ka_r = self._data kb_l, kb_r = other._data if reverse: input_dims = self.input_dims() + other.input_dims() output_dims = self.output_dims() + other.output_dims() kab_l = [np.kron(b, a) for a in ka_l for b in kb_l] else: input_dims = other.input_dims() + self.input_dims() output_dims = other.output_dims() + self.output_dims() kab_l = [np.kron(a, b) for a in ka_l for b in kb_l] if ka_r is None and kb_r is None: kab_r = None else: if ka_r is None: ka_r = ka_l if kb_r is None: kb_r = kb_l if reverse: kab_r = [np.kron(b, a) for a in ka_r for b in kb_r] else: kab_r = [np.kron(a, b) for a in ka_r for b in kb_r] data = (kab_l, kab_r) return Kraus(data, input_dims, output_dims)
[ "Return", "the", "tensor", "product", "channel", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/kraus.py#L399-L439
[ "def", "_tensor_product", "(", "self", ",", "other", ",", "reverse", "=", "False", ")", ":", "# Convert other to Kraus", "if", "not", "isinstance", "(", "other", ",", "Kraus", ")", ":", "other", "=", "Kraus", "(", "other", ")", "# Get tensor matrix", "ka_l", ",", "ka_r", "=", "self", ".", "_data", "kb_l", ",", "kb_r", "=", "other", ".", "_data", "if", "reverse", ":", "input_dims", "=", "self", ".", "input_dims", "(", ")", "+", "other", ".", "input_dims", "(", ")", "output_dims", "=", "self", ".", "output_dims", "(", ")", "+", "other", ".", "output_dims", "(", ")", "kab_l", "=", "[", "np", ".", "kron", "(", "b", ",", "a", ")", "for", "a", "in", "ka_l", "for", "b", "in", "kb_l", "]", "else", ":", "input_dims", "=", "other", ".", "input_dims", "(", ")", "+", "self", ".", "input_dims", "(", ")", "output_dims", "=", "other", ".", "output_dims", "(", ")", "+", "self", ".", "output_dims", "(", ")", "kab_l", "=", "[", "np", ".", "kron", "(", "a", ",", "b", ")", "for", "a", "in", "ka_l", "for", "b", "in", "kb_l", "]", "if", "ka_r", "is", "None", "and", "kb_r", "is", "None", ":", "kab_r", "=", "None", "else", ":", "if", "ka_r", "is", "None", ":", "ka_r", "=", "ka_l", "if", "kb_r", "is", "None", ":", "kb_r", "=", "kb_l", "if", "reverse", ":", "kab_r", "=", "[", "np", ".", "kron", "(", "b", ",", "a", ")", "for", "a", "in", "ka_r", "for", "b", "in", "kb_r", "]", "else", ":", "kab_r", "=", "[", "np", ".", "kron", "(", "a", ",", "b", ")", "for", "a", "in", "ka_r", "for", "b", "in", "kb_r", "]", "data", "=", "(", "kab_l", ",", "kab_r", ")", "return", "Kraus", "(", "data", ",", "input_dims", ",", "output_dims", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
functional_pulse
A decorator for generating SamplePulse from python callable. Args: func (callable): A function describing pulse envelope. Raises: PulseError: when invalid function is specified.
qiskit/pulse/commands/pulse_decorators.py
def functional_pulse(func): """A decorator for generating SamplePulse from python callable. Args: func (callable): A function describing pulse envelope. Raises: PulseError: when invalid function is specified. """ @functools.wraps(func) def to_pulse(duration, *args, name=None, **kwargs): """Return SamplePulse.""" if isinstance(duration, int) and duration > 0: samples = func(duration, *args, **kwargs) samples = np.asarray(samples, dtype=np.complex128) return SamplePulse(samples=samples, name=name) raise PulseError('The first argument must be an integer value representing duration.') return to_pulse
def functional_pulse(func): """A decorator for generating SamplePulse from python callable. Args: func (callable): A function describing pulse envelope. Raises: PulseError: when invalid function is specified. """ @functools.wraps(func) def to_pulse(duration, *args, name=None, **kwargs): """Return SamplePulse.""" if isinstance(duration, int) and duration > 0: samples = func(duration, *args, **kwargs) samples = np.asarray(samples, dtype=np.complex128) return SamplePulse(samples=samples, name=name) raise PulseError('The first argument must be an integer value representing duration.') return to_pulse
[ "A", "decorator", "for", "generating", "SamplePulse", "from", "python", "callable", ".", "Args", ":", "func", "(", "callable", ")", ":", "A", "function", "describing", "pulse", "envelope", ".", "Raises", ":", "PulseError", ":", "when", "invalid", "function", "is", "specified", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/commands/pulse_decorators.py#L21-L37
[ "def", "functional_pulse", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "to_pulse", "(", "duration", ",", "*", "args", ",", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Return SamplePulse.\"\"\"", "if", "isinstance", "(", "duration", ",", "int", ")", "and", "duration", ">", "0", ":", "samples", "=", "func", "(", "duration", ",", "*", "args", ",", "*", "*", "kwargs", ")", "samples", "=", "np", ".", "asarray", "(", "samples", ",", "dtype", "=", "np", ".", "complex128", ")", "return", "SamplePulse", "(", "samples", "=", "samples", ",", "name", "=", "name", ")", "raise", "PulseError", "(", "'The first argument must be an integer value representing duration.'", ")", "return", "to_pulse" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BinaryOp.real
Return the correspond floating point number.
qiskit/qasm/node/binaryop.py
def real(self, nested_scope=None): """Return the correspond floating point number.""" operation = self.children[0].operation() lhs = self.children[1].real(nested_scope) rhs = self.children[2].real(nested_scope) return operation(lhs, rhs)
def real(self, nested_scope=None): """Return the correspond floating point number.""" operation = self.children[0].operation() lhs = self.children[1].real(nested_scope) rhs = self.children[2].real(nested_scope) return operation(lhs, rhs)
[ "Return", "the", "correspond", "floating", "point", "number", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/node/binaryop.py#L38-L43
[ "def", "real", "(", "self", ",", "nested_scope", "=", "None", ")", ":", "operation", "=", "self", ".", "children", "[", "0", "]", ".", "operation", "(", ")", "lhs", "=", "self", ".", "children", "[", "1", "]", ".", "real", "(", "nested_scope", ")", "rhs", "=", "self", ".", "children", "[", "2", "]", ".", "real", "(", "nested_scope", ")", "return", "operation", "(", "lhs", ",", "rhs", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BinaryOp.sym
Return the correspond symbolic number.
qiskit/qasm/node/binaryop.py
def sym(self, nested_scope=None): """Return the correspond symbolic number.""" operation = self.children[0].operation() lhs = self.children[1].sym(nested_scope) rhs = self.children[2].sym(nested_scope) return operation(lhs, rhs)
def sym(self, nested_scope=None): """Return the correspond symbolic number.""" operation = self.children[0].operation() lhs = self.children[1].sym(nested_scope) rhs = self.children[2].sym(nested_scope) return operation(lhs, rhs)
[ "Return", "the", "correspond", "symbolic", "number", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/node/binaryop.py#L45-L50
[ "def", "sym", "(", "self", ",", "nested_scope", "=", "None", ")", ":", "operation", "=", "self", ".", "children", "[", "0", "]", ".", "operation", "(", ")", "lhs", "=", "self", ".", "children", "[", "1", "]", ".", "sym", "(", "nested_scope", ")", "rhs", "=", "self", ".", "children", "[", "2", "]", ".", "sym", "(", "nested_scope", ")", "return", "operation", "(", "lhs", ",", "rhs", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
barrier
Apply barrier to circuit. If qargs is None, applies to all the qbits. Args is a list of QuantumRegister or single qubits. For QuantumRegister, applies barrier to all the qubits in that register.
qiskit/extensions/standard/barrier.py
def barrier(self, *qargs): """Apply barrier to circuit. If qargs is None, applies to all the qbits. Args is a list of QuantumRegister or single qubits. For QuantumRegister, applies barrier to all the qubits in that register.""" qubits = [] qargs = _convert_to_bits(qargs, [qbit for qreg in self.qregs for qbit in qreg]) if not qargs: # None for qreg in self.qregs: for j in range(qreg.size): qubits.append((qreg, j)) for qarg in qargs: if isinstance(qarg, (QuantumRegister, list)): if isinstance(qarg, QuantumRegister): qubits.extend([(qarg, j) for j in range(qarg.size)]) else: qubits.extend(qarg) else: qubits.append(qarg) return self.append(Barrier(len(qubits)), qubits, [])
def barrier(self, *qargs): """Apply barrier to circuit. If qargs is None, applies to all the qbits. Args is a list of QuantumRegister or single qubits. For QuantumRegister, applies barrier to all the qubits in that register.""" qubits = [] qargs = _convert_to_bits(qargs, [qbit for qreg in self.qregs for qbit in qreg]) if not qargs: # None for qreg in self.qregs: for j in range(qreg.size): qubits.append((qreg, j)) for qarg in qargs: if isinstance(qarg, (QuantumRegister, list)): if isinstance(qarg, QuantumRegister): qubits.extend([(qarg, j) for j in range(qarg.size)]) else: qubits.extend(qarg) else: qubits.append(qarg) return self.append(Barrier(len(qubits)), qubits, [])
[ "Apply", "barrier", "to", "circuit", ".", "If", "qargs", "is", "None", "applies", "to", "all", "the", "qbits", ".", "Args", "is", "a", "list", "of", "QuantumRegister", "or", "single", "qubits", ".", "For", "QuantumRegister", "applies", "barrier", "to", "all", "the", "qubits", "in", "that", "register", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/standard/barrier.py#L30-L53
[ "def", "barrier", "(", "self", ",", "*", "qargs", ")", ":", "qubits", "=", "[", "]", "qargs", "=", "_convert_to_bits", "(", "qargs", ",", "[", "qbit", "for", "qreg", "in", "self", ".", "qregs", "for", "qbit", "in", "qreg", "]", ")", "if", "not", "qargs", ":", "# None", "for", "qreg", "in", "self", ".", "qregs", ":", "for", "j", "in", "range", "(", "qreg", ".", "size", ")", ":", "qubits", ".", "append", "(", "(", "qreg", ",", "j", ")", ")", "for", "qarg", "in", "qargs", ":", "if", "isinstance", "(", "qarg", ",", "(", "QuantumRegister", ",", "list", ")", ")", ":", "if", "isinstance", "(", "qarg", ",", "QuantumRegister", ")", ":", "qubits", ".", "extend", "(", "[", "(", "qarg", ",", "j", ")", "for", "j", "in", "range", "(", "qarg", ".", "size", ")", "]", ")", "else", ":", "qubits", ".", "extend", "(", "qarg", ")", "else", ":", "qubits", ".", "append", "(", "qarg", ")", "return", "self", ".", "append", "(", "Barrier", "(", "len", "(", "qubits", ")", ")", ",", "qubits", ",", "[", "]", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
average_data
Compute the mean value of an diagonal observable. Takes in a diagonal observable in dictionary, list or matrix format and then calculates the sum_i value(i) P(i) where value(i) is the value of the observable for state i. Args: counts (dict): a dict of outcomes from an experiment observable (dict or matrix or list): The observable to be averaged over. As an example, ZZ on qubits can be given as: * dict: {"00": 1, "11": 1, "01": -1, "10": -1} * matrix: [[1, 0, 0, 0], [0, -1, 0, 0, ], [0, 0, -1, 0], [0, 0, 0, 1]] * matrix diagonal (list): [1, -1, -1, 1] Returns: Double: Average of the observable
qiskit/quantum_info/analyzation/average.py
def average_data(counts, observable): """Compute the mean value of an diagonal observable. Takes in a diagonal observable in dictionary, list or matrix format and then calculates the sum_i value(i) P(i) where value(i) is the value of the observable for state i. Args: counts (dict): a dict of outcomes from an experiment observable (dict or matrix or list): The observable to be averaged over. As an example, ZZ on qubits can be given as: * dict: {"00": 1, "11": 1, "01": -1, "10": -1} * matrix: [[1, 0, 0, 0], [0, -1, 0, 0, ], [0, 0, -1, 0], [0, 0, 0, 1]] * matrix diagonal (list): [1, -1, -1, 1] Returns: Double: Average of the observable """ if not isinstance(observable, dict): observable = make_dict_observable(observable) temp = 0 tot = sum(counts.values()) for key in counts: if key in observable: temp += counts[key] * observable[key] / tot return temp
def average_data(counts, observable): """Compute the mean value of an diagonal observable. Takes in a diagonal observable in dictionary, list or matrix format and then calculates the sum_i value(i) P(i) where value(i) is the value of the observable for state i. Args: counts (dict): a dict of outcomes from an experiment observable (dict or matrix or list): The observable to be averaged over. As an example, ZZ on qubits can be given as: * dict: {"00": 1, "11": 1, "01": -1, "10": -1} * matrix: [[1, 0, 0, 0], [0, -1, 0, 0, ], [0, 0, -1, 0], [0, 0, 0, 1]] * matrix diagonal (list): [1, -1, -1, 1] Returns: Double: Average of the observable """ if not isinstance(observable, dict): observable = make_dict_observable(observable) temp = 0 tot = sum(counts.values()) for key in counts: if key in observable: temp += counts[key] * observable[key] / tot return temp
[ "Compute", "the", "mean", "value", "of", "an", "diagonal", "observable", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/analyzation/average.py#L13-L38
[ "def", "average_data", "(", "counts", ",", "observable", ")", ":", "if", "not", "isinstance", "(", "observable", ",", "dict", ")", ":", "observable", "=", "make_dict_observable", "(", "observable", ")", "temp", "=", "0", "tot", "=", "sum", "(", "counts", ".", "values", "(", ")", ")", "for", "key", "in", "counts", ":", "if", "key", "in", "observable", ":", "temp", "+=", "counts", "[", "key", "]", "*", "observable", "[", "key", "]", "/", "tot", "return", "temp" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
AstInterpreter._process_bit_id
Process an Id or IndexedId node as a bit or register type. Return a list of tuples (Register,index).
qiskit/converters/ast_to_dag.py
def _process_bit_id(self, node): """Process an Id or IndexedId node as a bit or register type. Return a list of tuples (Register,index). """ # pylint: disable=inconsistent-return-statements reg = None if node.name in self.dag.qregs: reg = self.dag.qregs[node.name] elif node.name in self.dag.cregs: reg = self.dag.cregs[node.name] else: raise QiskitError("expected qreg or creg name:", "line=%s" % node.line, "file=%s" % node.file) if node.type == "indexed_id": # An indexed bit or qubit return [(reg, node.index)] elif node.type == "id": # A qubit or qreg or creg if not self.bit_stack[-1]: # Global scope return [(reg, j) for j in range(reg.size)] else: # local scope if node.name in self.bit_stack[-1]: return [self.bit_stack[-1][node.name]] raise QiskitError("expected local bit name:", "line=%s" % node.line, "file=%s" % node.file) return None
def _process_bit_id(self, node): """Process an Id or IndexedId node as a bit or register type. Return a list of tuples (Register,index). """ # pylint: disable=inconsistent-return-statements reg = None if node.name in self.dag.qregs: reg = self.dag.qregs[node.name] elif node.name in self.dag.cregs: reg = self.dag.cregs[node.name] else: raise QiskitError("expected qreg or creg name:", "line=%s" % node.line, "file=%s" % node.file) if node.type == "indexed_id": # An indexed bit or qubit return [(reg, node.index)] elif node.type == "id": # A qubit or qreg or creg if not self.bit_stack[-1]: # Global scope return [(reg, j) for j in range(reg.size)] else: # local scope if node.name in self.bit_stack[-1]: return [self.bit_stack[-1][node.name]] raise QiskitError("expected local bit name:", "line=%s" % node.line, "file=%s" % node.file) return None
[ "Process", "an", "Id", "or", "IndexedId", "node", "as", "a", "bit", "or", "register", "type", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/converters/ast_to_dag.py#L89-L120
[ "def", "_process_bit_id", "(", "self", ",", "node", ")", ":", "# pylint: disable=inconsistent-return-statements", "reg", "=", "None", "if", "node", ".", "name", "in", "self", ".", "dag", ".", "qregs", ":", "reg", "=", "self", ".", "dag", ".", "qregs", "[", "node", ".", "name", "]", "elif", "node", ".", "name", "in", "self", ".", "dag", ".", "cregs", ":", "reg", "=", "self", ".", "dag", ".", "cregs", "[", "node", ".", "name", "]", "else", ":", "raise", "QiskitError", "(", "\"expected qreg or creg name:\"", ",", "\"line=%s\"", "%", "node", ".", "line", ",", "\"file=%s\"", "%", "node", ".", "file", ")", "if", "node", ".", "type", "==", "\"indexed_id\"", ":", "# An indexed bit or qubit", "return", "[", "(", "reg", ",", "node", ".", "index", ")", "]", "elif", "node", ".", "type", "==", "\"id\"", ":", "# A qubit or qreg or creg", "if", "not", "self", ".", "bit_stack", "[", "-", "1", "]", ":", "# Global scope", "return", "[", "(", "reg", ",", "j", ")", "for", "j", "in", "range", "(", "reg", ".", "size", ")", "]", "else", ":", "# local scope", "if", "node", ".", "name", "in", "self", ".", "bit_stack", "[", "-", "1", "]", ":", "return", "[", "self", ".", "bit_stack", "[", "-", "1", "]", "[", "node", ".", "name", "]", "]", "raise", "QiskitError", "(", "\"expected local bit name:\"", ",", "\"line=%s\"", "%", "node", ".", "line", ",", "\"file=%s\"", "%", "node", ".", "file", ")", "return", "None" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
AstInterpreter._process_custom_unitary
Process a custom unitary node.
qiskit/converters/ast_to_dag.py
def _process_custom_unitary(self, node): """Process a custom unitary node.""" name = node.name if node.arguments is not None: args = self._process_node(node.arguments) else: args = [] bits = [self._process_bit_id(node_element) for node_element in node.bitlist.children] if name in self.gates: gargs = self.gates[name]["args"] gbits = self.gates[name]["bits"] # Loop over register arguments, if any. maxidx = max(map(len, bits)) for idx in range(maxidx): self.arg_stack.append({gargs[j]: args[j] for j in range(len(gargs))}) # Only index into register arguments. element = [idx*x for x in [len(bits[j]) > 1 for j in range(len(bits))]] self.bit_stack.append({gbits[j]: bits[j][element[j]] for j in range(len(gbits))}) self._create_dag_op(name, [self.arg_stack[-1][s].sym() for s in gargs], [self.bit_stack[-1][s] for s in gbits]) self.arg_stack.pop() self.bit_stack.pop() else: raise QiskitError("internal error undefined gate:", "line=%s" % node.line, "file=%s" % node.file)
def _process_custom_unitary(self, node): """Process a custom unitary node.""" name = node.name if node.arguments is not None: args = self._process_node(node.arguments) else: args = [] bits = [self._process_bit_id(node_element) for node_element in node.bitlist.children] if name in self.gates: gargs = self.gates[name]["args"] gbits = self.gates[name]["bits"] # Loop over register arguments, if any. maxidx = max(map(len, bits)) for idx in range(maxidx): self.arg_stack.append({gargs[j]: args[j] for j in range(len(gargs))}) # Only index into register arguments. element = [idx*x for x in [len(bits[j]) > 1 for j in range(len(bits))]] self.bit_stack.append({gbits[j]: bits[j][element[j]] for j in range(len(gbits))}) self._create_dag_op(name, [self.arg_stack[-1][s].sym() for s in gargs], [self.bit_stack[-1][s] for s in gbits]) self.arg_stack.pop() self.bit_stack.pop() else: raise QiskitError("internal error undefined gate:", "line=%s" % node.line, "file=%s" % node.file)
[ "Process", "a", "custom", "unitary", "node", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/converters/ast_to_dag.py#L122-L151
[ "def", "_process_custom_unitary", "(", "self", ",", "node", ")", ":", "name", "=", "node", ".", "name", "if", "node", ".", "arguments", "is", "not", "None", ":", "args", "=", "self", ".", "_process_node", "(", "node", ".", "arguments", ")", "else", ":", "args", "=", "[", "]", "bits", "=", "[", "self", ".", "_process_bit_id", "(", "node_element", ")", "for", "node_element", "in", "node", ".", "bitlist", ".", "children", "]", "if", "name", "in", "self", ".", "gates", ":", "gargs", "=", "self", ".", "gates", "[", "name", "]", "[", "\"args\"", "]", "gbits", "=", "self", ".", "gates", "[", "name", "]", "[", "\"bits\"", "]", "# Loop over register arguments, if any.", "maxidx", "=", "max", "(", "map", "(", "len", ",", "bits", ")", ")", "for", "idx", "in", "range", "(", "maxidx", ")", ":", "self", ".", "arg_stack", ".", "append", "(", "{", "gargs", "[", "j", "]", ":", "args", "[", "j", "]", "for", "j", "in", "range", "(", "len", "(", "gargs", ")", ")", "}", ")", "# Only index into register arguments.", "element", "=", "[", "idx", "*", "x", "for", "x", "in", "[", "len", "(", "bits", "[", "j", "]", ")", ">", "1", "for", "j", "in", "range", "(", "len", "(", "bits", ")", ")", "]", "]", "self", ".", "bit_stack", ".", "append", "(", "{", "gbits", "[", "j", "]", ":", "bits", "[", "j", "]", "[", "element", "[", "j", "]", "]", "for", "j", "in", "range", "(", "len", "(", "gbits", ")", ")", "}", ")", "self", ".", "_create_dag_op", "(", "name", ",", "[", "self", ".", "arg_stack", "[", "-", "1", "]", "[", "s", "]", ".", "sym", "(", ")", "for", "s", "in", "gargs", "]", ",", "[", "self", ".", "bit_stack", "[", "-", "1", "]", "[", "s", "]", "for", "s", "in", "gbits", "]", ")", "self", ".", "arg_stack", ".", "pop", "(", ")", "self", ".", "bit_stack", ".", "pop", "(", ")", "else", ":", "raise", "QiskitError", "(", "\"internal error undefined gate:\"", ",", "\"line=%s\"", "%", "node", ".", "line", ",", "\"file=%s\"", "%", "node", ".", "file", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
AstInterpreter._process_gate
Process a gate node. If opaque is True, process the node as an opaque gate node.
qiskit/converters/ast_to_dag.py
def _process_gate(self, node, opaque=False): """Process a gate node. If opaque is True, process the node as an opaque gate node. """ self.gates[node.name] = {} de_gate = self.gates[node.name] de_gate["print"] = True # default de_gate["opaque"] = opaque de_gate["n_args"] = node.n_args() de_gate["n_bits"] = node.n_bits() if node.n_args() > 0: de_gate["args"] = [element.name for element in node.arguments.children] else: de_gate["args"] = [] de_gate["bits"] = [c.name for c in node.bitlist.children] if opaque: de_gate["body"] = None else: de_gate["body"] = node.body
def _process_gate(self, node, opaque=False): """Process a gate node. If opaque is True, process the node as an opaque gate node. """ self.gates[node.name] = {} de_gate = self.gates[node.name] de_gate["print"] = True # default de_gate["opaque"] = opaque de_gate["n_args"] = node.n_args() de_gate["n_bits"] = node.n_bits() if node.n_args() > 0: de_gate["args"] = [element.name for element in node.arguments.children] else: de_gate["args"] = [] de_gate["bits"] = [c.name for c in node.bitlist.children] if opaque: de_gate["body"] = None else: de_gate["body"] = node.body
[ "Process", "a", "gate", "node", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/converters/ast_to_dag.py#L153-L172
[ "def", "_process_gate", "(", "self", ",", "node", ",", "opaque", "=", "False", ")", ":", "self", ".", "gates", "[", "node", ".", "name", "]", "=", "{", "}", "de_gate", "=", "self", ".", "gates", "[", "node", ".", "name", "]", "de_gate", "[", "\"print\"", "]", "=", "True", "# default", "de_gate", "[", "\"opaque\"", "]", "=", "opaque", "de_gate", "[", "\"n_args\"", "]", "=", "node", ".", "n_args", "(", ")", "de_gate", "[", "\"n_bits\"", "]", "=", "node", ".", "n_bits", "(", ")", "if", "node", ".", "n_args", "(", ")", ">", "0", ":", "de_gate", "[", "\"args\"", "]", "=", "[", "element", ".", "name", "for", "element", "in", "node", ".", "arguments", ".", "children", "]", "else", ":", "de_gate", "[", "\"args\"", "]", "=", "[", "]", "de_gate", "[", "\"bits\"", "]", "=", "[", "c", ".", "name", "for", "c", "in", "node", ".", "bitlist", ".", "children", "]", "if", "opaque", ":", "de_gate", "[", "\"body\"", "]", "=", "None", "else", ":", "de_gate", "[", "\"body\"", "]", "=", "node", ".", "body" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
AstInterpreter._process_cnot
Process a CNOT gate node.
qiskit/converters/ast_to_dag.py
def _process_cnot(self, node): """Process a CNOT gate node.""" id0 = self._process_bit_id(node.children[0]) id1 = self._process_bit_id(node.children[1]) if not(len(id0) == len(id1) or len(id0) == 1 or len(id1) == 1): raise QiskitError("internal error: qreg size mismatch", "line=%s" % node.line, "file=%s" % node.file) maxidx = max([len(id0), len(id1)]) for idx in range(maxidx): if len(id0) > 1 and len(id1) > 1: self.dag.apply_operation_back(CXBase(), [id0[idx], id1[idx]], [], self.condition) elif len(id0) > 1: self.dag.apply_operation_back(CXBase(), [id0[idx], id1[0]], [], self.condition) else: self.dag.apply_operation_back(CXBase(), [id0[0], id1[idx]], [], self.condition)
def _process_cnot(self, node): """Process a CNOT gate node.""" id0 = self._process_bit_id(node.children[0]) id1 = self._process_bit_id(node.children[1]) if not(len(id0) == len(id1) or len(id0) == 1 or len(id1) == 1): raise QiskitError("internal error: qreg size mismatch", "line=%s" % node.line, "file=%s" % node.file) maxidx = max([len(id0), len(id1)]) for idx in range(maxidx): if len(id0) > 1 and len(id1) > 1: self.dag.apply_operation_back(CXBase(), [id0[idx], id1[idx]], [], self.condition) elif len(id0) > 1: self.dag.apply_operation_back(CXBase(), [id0[idx], id1[0]], [], self.condition) else: self.dag.apply_operation_back(CXBase(), [id0[0], id1[idx]], [], self.condition)
[ "Process", "a", "CNOT", "gate", "node", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/converters/ast_to_dag.py#L174-L188
[ "def", "_process_cnot", "(", "self", ",", "node", ")", ":", "id0", "=", "self", ".", "_process_bit_id", "(", "node", ".", "children", "[", "0", "]", ")", "id1", "=", "self", ".", "_process_bit_id", "(", "node", ".", "children", "[", "1", "]", ")", "if", "not", "(", "len", "(", "id0", ")", "==", "len", "(", "id1", ")", "or", "len", "(", "id0", ")", "==", "1", "or", "len", "(", "id1", ")", "==", "1", ")", ":", "raise", "QiskitError", "(", "\"internal error: qreg size mismatch\"", ",", "\"line=%s\"", "%", "node", ".", "line", ",", "\"file=%s\"", "%", "node", ".", "file", ")", "maxidx", "=", "max", "(", "[", "len", "(", "id0", ")", ",", "len", "(", "id1", ")", "]", ")", "for", "idx", "in", "range", "(", "maxidx", ")", ":", "if", "len", "(", "id0", ")", ">", "1", "and", "len", "(", "id1", ")", ">", "1", ":", "self", ".", "dag", ".", "apply_operation_back", "(", "CXBase", "(", ")", ",", "[", "id0", "[", "idx", "]", ",", "id1", "[", "idx", "]", "]", ",", "[", "]", ",", "self", ".", "condition", ")", "elif", "len", "(", "id0", ")", ">", "1", ":", "self", ".", "dag", ".", "apply_operation_back", "(", "CXBase", "(", ")", ",", "[", "id0", "[", "idx", "]", ",", "id1", "[", "0", "]", "]", ",", "[", "]", ",", "self", ".", "condition", ")", "else", ":", "self", ".", "dag", ".", "apply_operation_back", "(", "CXBase", "(", ")", ",", "[", "id0", "[", "0", "]", ",", "id1", "[", "idx", "]", "]", ",", "[", "]", ",", "self", ".", "condition", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
AstInterpreter._process_measure
Process a measurement node.
qiskit/converters/ast_to_dag.py
def _process_measure(self, node): """Process a measurement node.""" id0 = self._process_bit_id(node.children[0]) id1 = self._process_bit_id(node.children[1]) if len(id0) != len(id1): raise QiskitError("internal error: reg size mismatch", "line=%s" % node.line, "file=%s" % node.file) for idx, idy in zip(id0, id1): self.dag.apply_operation_back(Measure(), [idx], [idy], self.condition)
def _process_measure(self, node): """Process a measurement node.""" id0 = self._process_bit_id(node.children[0]) id1 = self._process_bit_id(node.children[1]) if len(id0) != len(id1): raise QiskitError("internal error: reg size mismatch", "line=%s" % node.line, "file=%s" % node.file) for idx, idy in zip(id0, id1): self.dag.apply_operation_back(Measure(), [idx], [idy], self.condition)
[ "Process", "a", "measurement", "node", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/converters/ast_to_dag.py#L190-L198
[ "def", "_process_measure", "(", "self", ",", "node", ")", ":", "id0", "=", "self", ".", "_process_bit_id", "(", "node", ".", "children", "[", "0", "]", ")", "id1", "=", "self", ".", "_process_bit_id", "(", "node", ".", "children", "[", "1", "]", ")", "if", "len", "(", "id0", ")", "!=", "len", "(", "id1", ")", ":", "raise", "QiskitError", "(", "\"internal error: reg size mismatch\"", ",", "\"line=%s\"", "%", "node", ".", "line", ",", "\"file=%s\"", "%", "node", ".", "file", ")", "for", "idx", ",", "idy", "in", "zip", "(", "id0", ",", "id1", ")", ":", "self", ".", "dag", ".", "apply_operation_back", "(", "Measure", "(", ")", ",", "[", "idx", "]", ",", "[", "idy", "]", ",", "self", ".", "condition", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
AstInterpreter._process_if
Process an if node.
qiskit/converters/ast_to_dag.py
def _process_if(self, node): """Process an if node.""" creg_name = node.children[0].name creg = self.dag.cregs[creg_name] cval = node.children[1].value self.condition = (creg, cval) self._process_node(node.children[2]) self.condition = None
def _process_if(self, node): """Process an if node.""" creg_name = node.children[0].name creg = self.dag.cregs[creg_name] cval = node.children[1].value self.condition = (creg, cval) self._process_node(node.children[2]) self.condition = None
[ "Process", "an", "if", "node", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/converters/ast_to_dag.py#L200-L207
[ "def", "_process_if", "(", "self", ",", "node", ")", ":", "creg_name", "=", "node", ".", "children", "[", "0", "]", ".", "name", "creg", "=", "self", ".", "dag", ".", "cregs", "[", "creg_name", "]", "cval", "=", "node", ".", "children", "[", "1", "]", ".", "value", "self", ".", "condition", "=", "(", "creg", ",", "cval", ")", "self", ".", "_process_node", "(", "node", ".", "children", "[", "2", "]", ")", "self", ".", "condition", "=", "None" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
AstInterpreter._process_node
Carry out the action associated with a node.
qiskit/converters/ast_to_dag.py
def _process_node(self, node): """Carry out the action associated with a node.""" if node.type == "program": self._process_children(node) elif node.type == "qreg": qreg = QuantumRegister(node.index, node.name) self.dag.add_qreg(qreg) elif node.type == "creg": creg = ClassicalRegister(node.index, node.name) self.dag.add_creg(creg) elif node.type == "id": raise QiskitError("internal error: _process_node on id") elif node.type == "int": raise QiskitError("internal error: _process_node on int") elif node.type == "real": raise QiskitError("internal error: _process_node on real") elif node.type == "indexed_id": raise QiskitError("internal error: _process_node on indexed_id") elif node.type == "id_list": # We process id_list nodes when they are leaves of barriers. return [self._process_bit_id(node_children) for node_children in node.children] elif node.type == "primary_list": # We should only be called for a barrier. return [self._process_bit_id(m) for m in node.children] elif node.type == "gate": self._process_gate(node) elif node.type == "custom_unitary": self._process_custom_unitary(node) elif node.type == "universal_unitary": args = self._process_node(node.children[0]) qid = self._process_bit_id(node.children[1]) for element in qid: self.dag.apply_operation_back(UBase(*args, element), self.condition) elif node.type == "cnot": self._process_cnot(node) elif node.type == "expression_list": return node.children elif node.type == "binop": raise QiskitError("internal error: _process_node on binop") elif node.type == "prefix": raise QiskitError("internal error: _process_node on prefix") elif node.type == "measure": self._process_measure(node) elif node.type == "format": self.version = node.version() elif node.type == "barrier": ids = self._process_node(node.children[0]) qubits = [] for qubit in ids: for j, _ in enumerate(qubit): qubits.append(qubit[j]) self.dag.apply_operation_back(Barrier(len(qubits)), qubits, []) elif node.type == "reset": id0 = self._process_bit_id(node.children[0]) for i, _ in enumerate(id0): self.dag.apply_operation_back(Reset(), [id0[i]], [], self.condition) elif node.type == "if": self._process_if(node) elif node.type == "opaque": self._process_gate(node, opaque=True) elif node.type == "external": raise QiskitError("internal error: _process_node on external") else: raise QiskitError("internal error: undefined node type", node.type, "line=%s" % node.line, "file=%s" % node.file) return None
def _process_node(self, node): """Carry out the action associated with a node.""" if node.type == "program": self._process_children(node) elif node.type == "qreg": qreg = QuantumRegister(node.index, node.name) self.dag.add_qreg(qreg) elif node.type == "creg": creg = ClassicalRegister(node.index, node.name) self.dag.add_creg(creg) elif node.type == "id": raise QiskitError("internal error: _process_node on id") elif node.type == "int": raise QiskitError("internal error: _process_node on int") elif node.type == "real": raise QiskitError("internal error: _process_node on real") elif node.type == "indexed_id": raise QiskitError("internal error: _process_node on indexed_id") elif node.type == "id_list": # We process id_list nodes when they are leaves of barriers. return [self._process_bit_id(node_children) for node_children in node.children] elif node.type == "primary_list": # We should only be called for a barrier. return [self._process_bit_id(m) for m in node.children] elif node.type == "gate": self._process_gate(node) elif node.type == "custom_unitary": self._process_custom_unitary(node) elif node.type == "universal_unitary": args = self._process_node(node.children[0]) qid = self._process_bit_id(node.children[1]) for element in qid: self.dag.apply_operation_back(UBase(*args, element), self.condition) elif node.type == "cnot": self._process_cnot(node) elif node.type == "expression_list": return node.children elif node.type == "binop": raise QiskitError("internal error: _process_node on binop") elif node.type == "prefix": raise QiskitError("internal error: _process_node on prefix") elif node.type == "measure": self._process_measure(node) elif node.type == "format": self.version = node.version() elif node.type == "barrier": ids = self._process_node(node.children[0]) qubits = [] for qubit in ids: for j, _ in enumerate(qubit): qubits.append(qubit[j]) self.dag.apply_operation_back(Barrier(len(qubits)), qubits, []) elif node.type == "reset": id0 = self._process_bit_id(node.children[0]) for i, _ in enumerate(id0): self.dag.apply_operation_back(Reset(), [id0[i]], [], self.condition) elif node.type == "if": self._process_if(node) elif node.type == "opaque": self._process_gate(node, opaque=True) elif node.type == "external": raise QiskitError("internal error: _process_node on external") else: raise QiskitError("internal error: undefined node type", node.type, "line=%s" % node.line, "file=%s" % node.file) return None
[ "Carry", "out", "the", "action", "associated", "with", "a", "node", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/converters/ast_to_dag.py#L214-L304
[ "def", "_process_node", "(", "self", ",", "node", ")", ":", "if", "node", ".", "type", "==", "\"program\"", ":", "self", ".", "_process_children", "(", "node", ")", "elif", "node", ".", "type", "==", "\"qreg\"", ":", "qreg", "=", "QuantumRegister", "(", "node", ".", "index", ",", "node", ".", "name", ")", "self", ".", "dag", ".", "add_qreg", "(", "qreg", ")", "elif", "node", ".", "type", "==", "\"creg\"", ":", "creg", "=", "ClassicalRegister", "(", "node", ".", "index", ",", "node", ".", "name", ")", "self", ".", "dag", ".", "add_creg", "(", "creg", ")", "elif", "node", ".", "type", "==", "\"id\"", ":", "raise", "QiskitError", "(", "\"internal error: _process_node on id\"", ")", "elif", "node", ".", "type", "==", "\"int\"", ":", "raise", "QiskitError", "(", "\"internal error: _process_node on int\"", ")", "elif", "node", ".", "type", "==", "\"real\"", ":", "raise", "QiskitError", "(", "\"internal error: _process_node on real\"", ")", "elif", "node", ".", "type", "==", "\"indexed_id\"", ":", "raise", "QiskitError", "(", "\"internal error: _process_node on indexed_id\"", ")", "elif", "node", ".", "type", "==", "\"id_list\"", ":", "# We process id_list nodes when they are leaves of barriers.", "return", "[", "self", ".", "_process_bit_id", "(", "node_children", ")", "for", "node_children", "in", "node", ".", "children", "]", "elif", "node", ".", "type", "==", "\"primary_list\"", ":", "# We should only be called for a barrier.", "return", "[", "self", ".", "_process_bit_id", "(", "m", ")", "for", "m", "in", "node", ".", "children", "]", "elif", "node", ".", "type", "==", "\"gate\"", ":", "self", ".", "_process_gate", "(", "node", ")", "elif", "node", ".", "type", "==", "\"custom_unitary\"", ":", "self", ".", "_process_custom_unitary", "(", "node", ")", "elif", "node", ".", "type", "==", "\"universal_unitary\"", ":", "args", "=", "self", ".", "_process_node", "(", "node", ".", "children", "[", "0", "]", ")", "qid", "=", "self", ".", "_process_bit_id", "(", "node", ".", "children", "[", "1", "]", ")", "for", "element", "in", "qid", ":", "self", ".", "dag", ".", "apply_operation_back", "(", "UBase", "(", "*", "args", ",", "element", ")", ",", "self", ".", "condition", ")", "elif", "node", ".", "type", "==", "\"cnot\"", ":", "self", ".", "_process_cnot", "(", "node", ")", "elif", "node", ".", "type", "==", "\"expression_list\"", ":", "return", "node", ".", "children", "elif", "node", ".", "type", "==", "\"binop\"", ":", "raise", "QiskitError", "(", "\"internal error: _process_node on binop\"", ")", "elif", "node", ".", "type", "==", "\"prefix\"", ":", "raise", "QiskitError", "(", "\"internal error: _process_node on prefix\"", ")", "elif", "node", ".", "type", "==", "\"measure\"", ":", "self", ".", "_process_measure", "(", "node", ")", "elif", "node", ".", "type", "==", "\"format\"", ":", "self", ".", "version", "=", "node", ".", "version", "(", ")", "elif", "node", ".", "type", "==", "\"barrier\"", ":", "ids", "=", "self", ".", "_process_node", "(", "node", ".", "children", "[", "0", "]", ")", "qubits", "=", "[", "]", "for", "qubit", "in", "ids", ":", "for", "j", ",", "_", "in", "enumerate", "(", "qubit", ")", ":", "qubits", ".", "append", "(", "qubit", "[", "j", "]", ")", "self", ".", "dag", ".", "apply_operation_back", "(", "Barrier", "(", "len", "(", "qubits", ")", ")", ",", "qubits", ",", "[", "]", ")", "elif", "node", ".", "type", "==", "\"reset\"", ":", "id0", "=", "self", ".", "_process_bit_id", "(", "node", ".", "children", "[", "0", "]", ")", "for", "i", ",", "_", "in", "enumerate", "(", "id0", ")", ":", "self", ".", "dag", ".", "apply_operation_back", "(", "Reset", "(", ")", ",", "[", "id0", "[", "i", "]", "]", ",", "[", "]", ",", "self", ".", "condition", ")", "elif", "node", ".", "type", "==", "\"if\"", ":", "self", ".", "_process_if", "(", "node", ")", "elif", "node", ".", "type", "==", "\"opaque\"", ":", "self", ".", "_process_gate", "(", "node", ",", "opaque", "=", "True", ")", "elif", "node", ".", "type", "==", "\"external\"", ":", "raise", "QiskitError", "(", "\"internal error: _process_node on external\"", ")", "else", ":", "raise", "QiskitError", "(", "\"internal error: undefined node type\"", ",", "node", ".", "type", ",", "\"line=%s\"", "%", "node", ".", "line", ",", "\"file=%s\"", "%", "node", ".", "file", ")", "return", "None" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
AstInterpreter._create_dag_op
Create a DAG node out of a parsed AST op node. Args: name (str): operation name to apply to the dag. params (list): op parameters qargs (list(QuantumRegister, int)): qubits to attach to Raises: QiskitError: if encountering a non-basis opaque gate
qiskit/converters/ast_to_dag.py
def _create_dag_op(self, name, params, qargs): """ Create a DAG node out of a parsed AST op node. Args: name (str): operation name to apply to the dag. params (list): op parameters qargs (list(QuantumRegister, int)): qubits to attach to Raises: QiskitError: if encountering a non-basis opaque gate """ if name == "u0": op_class = U0Gate elif name == "u1": op_class = U1Gate elif name == "u2": op_class = U2Gate elif name == "u3": op_class = U3Gate elif name == "x": op_class = XGate elif name == "y": op_class = YGate elif name == "z": op_class = ZGate elif name == "t": op_class = TGate elif name == "tdg": op_class = TdgGate elif name == "s": op_class = SGate elif name == "sdg": op_class = SdgGate elif name == "swap": op_class = SwapGate elif name == "rx": op_class = RXGate elif name == "ry": op_class = RYGate elif name == "rz": op_class = RZGate elif name == "rzz": op_class = RZZGate elif name == "id": op_class = IdGate elif name == "h": op_class = HGate elif name == "cx": op_class = CnotGate elif name == "cy": op_class = CyGate elif name == "cz": op_class = CzGate elif name == "ch": op_class = CHGate elif name == "crz": op_class = CrzGate elif name == "cu1": op_class = Cu1Gate elif name == "cu3": op_class = Cu3Gate elif name == "ccx": op_class = ToffoliGate elif name == "cswap": op_class = FredkinGate else: raise QiskitError("unknown operation for ast node name %s" % name) op = op_class(*params) self.dag.apply_operation_back(op, qargs, [], condition=self.condition)
def _create_dag_op(self, name, params, qargs): """ Create a DAG node out of a parsed AST op node. Args: name (str): operation name to apply to the dag. params (list): op parameters qargs (list(QuantumRegister, int)): qubits to attach to Raises: QiskitError: if encountering a non-basis opaque gate """ if name == "u0": op_class = U0Gate elif name == "u1": op_class = U1Gate elif name == "u2": op_class = U2Gate elif name == "u3": op_class = U3Gate elif name == "x": op_class = XGate elif name == "y": op_class = YGate elif name == "z": op_class = ZGate elif name == "t": op_class = TGate elif name == "tdg": op_class = TdgGate elif name == "s": op_class = SGate elif name == "sdg": op_class = SdgGate elif name == "swap": op_class = SwapGate elif name == "rx": op_class = RXGate elif name == "ry": op_class = RYGate elif name == "rz": op_class = RZGate elif name == "rzz": op_class = RZZGate elif name == "id": op_class = IdGate elif name == "h": op_class = HGate elif name == "cx": op_class = CnotGate elif name == "cy": op_class = CyGate elif name == "cz": op_class = CzGate elif name == "ch": op_class = CHGate elif name == "crz": op_class = CrzGate elif name == "cu1": op_class = Cu1Gate elif name == "cu3": op_class = Cu3Gate elif name == "ccx": op_class = ToffoliGate elif name == "cswap": op_class = FredkinGate else: raise QiskitError("unknown operation for ast node name %s" % name) op = op_class(*params) self.dag.apply_operation_back(op, qargs, [], condition=self.condition)
[ "Create", "a", "DAG", "node", "out", "of", "a", "parsed", "AST", "op", "node", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/converters/ast_to_dag.py#L306-L377
[ "def", "_create_dag_op", "(", "self", ",", "name", ",", "params", ",", "qargs", ")", ":", "if", "name", "==", "\"u0\"", ":", "op_class", "=", "U0Gate", "elif", "name", "==", "\"u1\"", ":", "op_class", "=", "U1Gate", "elif", "name", "==", "\"u2\"", ":", "op_class", "=", "U2Gate", "elif", "name", "==", "\"u3\"", ":", "op_class", "=", "U3Gate", "elif", "name", "==", "\"x\"", ":", "op_class", "=", "XGate", "elif", "name", "==", "\"y\"", ":", "op_class", "=", "YGate", "elif", "name", "==", "\"z\"", ":", "op_class", "=", "ZGate", "elif", "name", "==", "\"t\"", ":", "op_class", "=", "TGate", "elif", "name", "==", "\"tdg\"", ":", "op_class", "=", "TdgGate", "elif", "name", "==", "\"s\"", ":", "op_class", "=", "SGate", "elif", "name", "==", "\"sdg\"", ":", "op_class", "=", "SdgGate", "elif", "name", "==", "\"swap\"", ":", "op_class", "=", "SwapGate", "elif", "name", "==", "\"rx\"", ":", "op_class", "=", "RXGate", "elif", "name", "==", "\"ry\"", ":", "op_class", "=", "RYGate", "elif", "name", "==", "\"rz\"", ":", "op_class", "=", "RZGate", "elif", "name", "==", "\"rzz\"", ":", "op_class", "=", "RZZGate", "elif", "name", "==", "\"id\"", ":", "op_class", "=", "IdGate", "elif", "name", "==", "\"h\"", ":", "op_class", "=", "HGate", "elif", "name", "==", "\"cx\"", ":", "op_class", "=", "CnotGate", "elif", "name", "==", "\"cy\"", ":", "op_class", "=", "CyGate", "elif", "name", "==", "\"cz\"", ":", "op_class", "=", "CzGate", "elif", "name", "==", "\"ch\"", ":", "op_class", "=", "CHGate", "elif", "name", "==", "\"crz\"", ":", "op_class", "=", "CrzGate", "elif", "name", "==", "\"cu1\"", ":", "op_class", "=", "Cu1Gate", "elif", "name", "==", "\"cu3\"", ":", "op_class", "=", "Cu3Gate", "elif", "name", "==", "\"ccx\"", ":", "op_class", "=", "ToffoliGate", "elif", "name", "==", "\"cswap\"", ":", "op_class", "=", "FredkinGate", "else", ":", "raise", "QiskitError", "(", "\"unknown operation for ast node name %s\"", "%", "name", ")", "op", "=", "op_class", "(", "*", "params", ")", "self", ".", "dag", ".", "apply_operation_back", "(", "op", ",", "qargs", ",", "[", "]", ",", "condition", "=", "self", ".", "condition", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Measure.qasm
Return the corresponding OPENQASM string.
qiskit/qasm/node/measure.py
def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" return "measure " + self.children[0].qasm(prec) + " -> " + \ self.children[1].qasm(prec) + ";"
def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" return "measure " + self.children[0].qasm(prec) + " -> " + \ self.children[1].qasm(prec) + ";"
[ "Return", "the", "corresponding", "OPENQASM", "string", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/node/measure.py#L24-L27
[ "def", "qasm", "(", "self", ",", "prec", "=", "15", ")", ":", "return", "\"measure \"", "+", "self", ".", "children", "[", "0", "]", ".", "qasm", "(", "prec", ")", "+", "\" -> \"", "+", "self", ".", "children", "[", "1", "]", ".", "qasm", "(", "prec", ")", "+", "\";\"" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Schedule.ch_duration
Return duration of supplied channels. Args: *channels: Supplied channels
qiskit/pulse/schedule.py
def ch_duration(self, *channels: List[Channel]) -> int: """Return duration of supplied channels. Args: *channels: Supplied channels """ return self.timeslots.ch_duration(*channels)
def ch_duration(self, *channels: List[Channel]) -> int: """Return duration of supplied channels. Args: *channels: Supplied channels """ return self.timeslots.ch_duration(*channels)
[ "Return", "duration", "of", "supplied", "channels", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/schedule.py#L100-L106
[ "def", "ch_duration", "(", "self", ",", "*", "channels", ":", "List", "[", "Channel", "]", ")", "->", "int", ":", "return", "self", ".", "timeslots", ".", "ch_duration", "(", "*", "channels", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Schedule.ch_start_time
Return minimum start time for supplied channels. Args: *channels: Supplied channels
qiskit/pulse/schedule.py
def ch_start_time(self, *channels: List[Channel]) -> int: """Return minimum start time for supplied channels. Args: *channels: Supplied channels """ return self.timeslots.ch_start_time(*channels)
def ch_start_time(self, *channels: List[Channel]) -> int: """Return minimum start time for supplied channels. Args: *channels: Supplied channels """ return self.timeslots.ch_start_time(*channels)
[ "Return", "minimum", "start", "time", "for", "supplied", "channels", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/schedule.py#L108-L114
[ "def", "ch_start_time", "(", "self", ",", "*", "channels", ":", "List", "[", "Channel", "]", ")", "->", "int", ":", "return", "self", ".", "timeslots", ".", "ch_start_time", "(", "*", "channels", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Schedule.ch_stop_time
Return maximum start time for supplied channels. Args: *channels: Supplied channels
qiskit/pulse/schedule.py
def ch_stop_time(self, *channels: List[Channel]) -> int: """Return maximum start time for supplied channels. Args: *channels: Supplied channels """ return self.timeslots.ch_stop_time(*channels)
def ch_stop_time(self, *channels: List[Channel]) -> int: """Return maximum start time for supplied channels. Args: *channels: Supplied channels """ return self.timeslots.ch_stop_time(*channels)
[ "Return", "maximum", "start", "time", "for", "supplied", "channels", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/schedule.py#L116-L122
[ "def", "ch_stop_time", "(", "self", ",", "*", "channels", ":", "List", "[", "Channel", "]", ")", "->", "int", ":", "return", "self", ".", "timeslots", ".", "ch_stop_time", "(", "*", "channels", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Schedule._instructions
Iterable for flattening Schedule tree. Args: time: Shifted time due to parent Yields: Tuple[int, ScheduleComponent]: Tuple containing time `ScheduleComponent` starts at and the flattened `ScheduleComponent`.
qiskit/pulse/schedule.py
def _instructions(self, time: int = 0) -> Iterable[Tuple[int, 'Instruction']]: """Iterable for flattening Schedule tree. Args: time: Shifted time due to parent Yields: Tuple[int, ScheduleComponent]: Tuple containing time `ScheduleComponent` starts at and the flattened `ScheduleComponent`. """ for insert_time, child_sched in self.children: yield from child_sched._instructions(time + insert_time)
def _instructions(self, time: int = 0) -> Iterable[Tuple[int, 'Instruction']]: """Iterable for flattening Schedule tree. Args: time: Shifted time due to parent Yields: Tuple[int, ScheduleComponent]: Tuple containing time `ScheduleComponent` starts at and the flattened `ScheduleComponent`. """ for insert_time, child_sched in self.children: yield from child_sched._instructions(time + insert_time)
[ "Iterable", "for", "flattening", "Schedule", "tree", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/schedule.py#L124-L135
[ "def", "_instructions", "(", "self", ",", "time", ":", "int", "=", "0", ")", "->", "Iterable", "[", "Tuple", "[", "int", ",", "'Instruction'", "]", "]", ":", "for", "insert_time", ",", "child_sched", "in", "self", ".", "children", ":", "yield", "from", "child_sched", ".", "_instructions", "(", "time", "+", "insert_time", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
IndexedId.to_string
Print with indent.
qiskit/qasm/node/indexedid.py
def to_string(self, indent): """Print with indent.""" ind = indent * ' ' print(ind, 'indexed_id', self.name, self.index)
def to_string(self, indent): """Print with indent.""" ind = indent * ' ' print(ind, 'indexed_id', self.name, self.index)
[ "Print", "with", "indent", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/node/indexedid.py#L31-L34
[ "def", "to_string", "(", "self", ",", "indent", ")", ":", "ind", "=", "indent", "*", "' '", "print", "(", "ind", ",", "'indexed_id'", ",", "self", ".", "name", ",", "self", ".", "index", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
ModelTypeValidator.check_type
Validates a value against the correct type of the field. It calls ``_expected_types`` to get a list of valid types. Subclasses can do one of the following: 1. They can override the ``valid_types`` property with a tuple with the expected types for this field. 2. They can override the ``_expected_types`` method to return a tuple of expected types for the field. 3. They can change ``check_type`` completely to customize validation. This method or the overrides must return the ``value`` parameter untouched.
qiskit/validation/base.py
def check_type(self, value, attr, data): """Validates a value against the correct type of the field. It calls ``_expected_types`` to get a list of valid types. Subclasses can do one of the following: 1. They can override the ``valid_types`` property with a tuple with the expected types for this field. 2. They can override the ``_expected_types`` method to return a tuple of expected types for the field. 3. They can change ``check_type`` completely to customize validation. This method or the overrides must return the ``value`` parameter untouched. """ expected_types = self._expected_types() if not isinstance(value, expected_types): raise self._not_expected_type( value, expected_types, fields=[self], field_names=attr, data=data) return value
def check_type(self, value, attr, data): """Validates a value against the correct type of the field. It calls ``_expected_types`` to get a list of valid types. Subclasses can do one of the following: 1. They can override the ``valid_types`` property with a tuple with the expected types for this field. 2. They can override the ``_expected_types`` method to return a tuple of expected types for the field. 3. They can change ``check_type`` completely to customize validation. This method or the overrides must return the ``value`` parameter untouched. """ expected_types = self._expected_types() if not isinstance(value, expected_types): raise self._not_expected_type( value, expected_types, fields=[self], field_names=attr, data=data) return value
[ "Validates", "a", "value", "against", "the", "correct", "type", "of", "the", "field", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/validation/base.py#L45-L68
[ "def", "check_type", "(", "self", ",", "value", ",", "attr", ",", "data", ")", ":", "expected_types", "=", "self", ".", "_expected_types", "(", ")", "if", "not", "isinstance", "(", "value", ",", "expected_types", ")", ":", "raise", "self", ".", "_not_expected_type", "(", "value", ",", "expected_types", ",", "fields", "=", "[", "self", "]", ",", "field_names", "=", "attr", ",", "data", "=", "data", ")", "return", "value" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BaseSchema.dump_additional_data
Include unknown fields after dumping. Unknown fields are added with no processing at all. Args: valid_data (dict or list): data collected and returned by ``dump()``. many (bool): if True, data and original_data are a list. original_data (object or list): object passed to ``dump()`` in the first place. Returns: dict: the same ``valid_data`` extended with the unknown attributes. Inspired by https://github.com/marshmallow-code/marshmallow/pull/595.
qiskit/validation/base.py
def dump_additional_data(self, valid_data, many, original_data): """Include unknown fields after dumping. Unknown fields are added with no processing at all. Args: valid_data (dict or list): data collected and returned by ``dump()``. many (bool): if True, data and original_data are a list. original_data (object or list): object passed to ``dump()`` in the first place. Returns: dict: the same ``valid_data`` extended with the unknown attributes. Inspired by https://github.com/marshmallow-code/marshmallow/pull/595. """ if many: for i, _ in enumerate(valid_data): additional_keys = set(original_data[i].__dict__) - set(valid_data[i]) for key in additional_keys: valid_data[i][key] = getattr(original_data[i], key) else: additional_keys = set(original_data.__dict__) - set(valid_data) for key in additional_keys: valid_data[key] = getattr(original_data, key) return valid_data
def dump_additional_data(self, valid_data, many, original_data): """Include unknown fields after dumping. Unknown fields are added with no processing at all. Args: valid_data (dict or list): data collected and returned by ``dump()``. many (bool): if True, data and original_data are a list. original_data (object or list): object passed to ``dump()`` in the first place. Returns: dict: the same ``valid_data`` extended with the unknown attributes. Inspired by https://github.com/marshmallow-code/marshmallow/pull/595. """ if many: for i, _ in enumerate(valid_data): additional_keys = set(original_data[i].__dict__) - set(valid_data[i]) for key in additional_keys: valid_data[i][key] = getattr(original_data[i], key) else: additional_keys = set(original_data.__dict__) - set(valid_data) for key in additional_keys: valid_data[key] = getattr(original_data, key) return valid_data
[ "Include", "unknown", "fields", "after", "dumping", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/validation/base.py#L105-L131
[ "def", "dump_additional_data", "(", "self", ",", "valid_data", ",", "many", ",", "original_data", ")", ":", "if", "many", ":", "for", "i", ",", "_", "in", "enumerate", "(", "valid_data", ")", ":", "additional_keys", "=", "set", "(", "original_data", "[", "i", "]", ".", "__dict__", ")", "-", "set", "(", "valid_data", "[", "i", "]", ")", "for", "key", "in", "additional_keys", ":", "valid_data", "[", "i", "]", "[", "key", "]", "=", "getattr", "(", "original_data", "[", "i", "]", ",", "key", ")", "else", ":", "additional_keys", "=", "set", "(", "original_data", ".", "__dict__", ")", "-", "set", "(", "valid_data", ")", "for", "key", "in", "additional_keys", ":", "valid_data", "[", "key", "]", "=", "getattr", "(", "original_data", ",", "key", ")", "return", "valid_data" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BaseSchema.load_additional_data
Include unknown fields after load. Unknown fields are added with no processing at all. Args: valid_data (dict or list): validated data returned by ``load()``. many (bool): if True, data and original_data are a list. original_data (dict or list): data passed to ``load()`` in the first place. Returns: dict: the same ``valid_data`` extended with the unknown attributes. Inspired by https://github.com/marshmallow-code/marshmallow/pull/595.
qiskit/validation/base.py
def load_additional_data(self, valid_data, many, original_data): """Include unknown fields after load. Unknown fields are added with no processing at all. Args: valid_data (dict or list): validated data returned by ``load()``. many (bool): if True, data and original_data are a list. original_data (dict or list): data passed to ``load()`` in the first place. Returns: dict: the same ``valid_data`` extended with the unknown attributes. Inspired by https://github.com/marshmallow-code/marshmallow/pull/595. """ if many: for i, _ in enumerate(valid_data): additional_keys = set(original_data[i]) - set(valid_data[i]) for key in additional_keys: valid_data[i][key] = original_data[i][key] else: additional_keys = set(original_data) - set(valid_data) for key in additional_keys: valid_data[key] = original_data[key] return valid_data
def load_additional_data(self, valid_data, many, original_data): """Include unknown fields after load. Unknown fields are added with no processing at all. Args: valid_data (dict or list): validated data returned by ``load()``. many (bool): if True, data and original_data are a list. original_data (dict or list): data passed to ``load()`` in the first place. Returns: dict: the same ``valid_data`` extended with the unknown attributes. Inspired by https://github.com/marshmallow-code/marshmallow/pull/595. """ if many: for i, _ in enumerate(valid_data): additional_keys = set(original_data[i]) - set(valid_data[i]) for key in additional_keys: valid_data[i][key] = original_data[i][key] else: additional_keys = set(original_data) - set(valid_data) for key in additional_keys: valid_data[key] = original_data[key] return valid_data
[ "Include", "unknown", "fields", "after", "load", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/validation/base.py#L134-L160
[ "def", "load_additional_data", "(", "self", ",", "valid_data", ",", "many", ",", "original_data", ")", ":", "if", "many", ":", "for", "i", ",", "_", "in", "enumerate", "(", "valid_data", ")", ":", "additional_keys", "=", "set", "(", "original_data", "[", "i", "]", ")", "-", "set", "(", "valid_data", "[", "i", "]", ")", "for", "key", "in", "additional_keys", ":", "valid_data", "[", "i", "]", "[", "key", "]", "=", "original_data", "[", "i", "]", "[", "key", "]", "else", ":", "additional_keys", "=", "set", "(", "original_data", ")", "-", "set", "(", "valid_data", ")", "for", "key", "in", "additional_keys", ":", "valid_data", "[", "key", "]", "=", "original_data", "[", "key", "]", "return", "valid_data" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_SchemaBinder._create_validation_schema
Create a patched Schema for validating models. Model validation is not part of Marshmallow. Schemas have a ``validate`` method but this delegates execution on ``load`` and discards the result. Similarly, ``load`` will call ``_deserialize`` on every field in the schema. This function patches the ``_deserialize`` instance method of each field to make it call a custom defined method ``check_type`` provided by Qiskit in the different fields at ``qiskit.validation.fields``. Returns: BaseSchema: a copy of the original Schema, overriding the ``_deserialize()`` call of its fields.
qiskit/validation/base.py
def _create_validation_schema(schema_cls): """Create a patched Schema for validating models. Model validation is not part of Marshmallow. Schemas have a ``validate`` method but this delegates execution on ``load`` and discards the result. Similarly, ``load`` will call ``_deserialize`` on every field in the schema. This function patches the ``_deserialize`` instance method of each field to make it call a custom defined method ``check_type`` provided by Qiskit in the different fields at ``qiskit.validation.fields``. Returns: BaseSchema: a copy of the original Schema, overriding the ``_deserialize()`` call of its fields. """ validation_schema = schema_cls() for _, field in validation_schema.fields.items(): if isinstance(field, ModelTypeValidator): validate_function = field.__class__.check_type field._deserialize = MethodType(validate_function, field) return validation_schema
def _create_validation_schema(schema_cls): """Create a patched Schema for validating models. Model validation is not part of Marshmallow. Schemas have a ``validate`` method but this delegates execution on ``load`` and discards the result. Similarly, ``load`` will call ``_deserialize`` on every field in the schema. This function patches the ``_deserialize`` instance method of each field to make it call a custom defined method ``check_type`` provided by Qiskit in the different fields at ``qiskit.validation.fields``. Returns: BaseSchema: a copy of the original Schema, overriding the ``_deserialize()`` call of its fields. """ validation_schema = schema_cls() for _, field in validation_schema.fields.items(): if isinstance(field, ModelTypeValidator): validate_function = field.__class__.check_type field._deserialize = MethodType(validate_function, field) return validation_schema
[ "Create", "a", "patched", "Schema", "for", "validating", "models", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/validation/base.py#L201-L224
[ "def", "_create_validation_schema", "(", "schema_cls", ")", ":", "validation_schema", "=", "schema_cls", "(", ")", "for", "_", ",", "field", "in", "validation_schema", ".", "fields", ".", "items", "(", ")", ":", "if", "isinstance", "(", "field", ",", "ModelTypeValidator", ")", ":", "validate_function", "=", "field", ".", "__class__", ".", "check_type", "field", ".", "_deserialize", "=", "MethodType", "(", "validate_function", ",", "field", ")", "return", "validation_schema" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_SchemaBinder._validate
Validate the internal representation of the instance.
qiskit/validation/base.py
def _validate(instance): """Validate the internal representation of the instance.""" try: _ = instance.schema.validate(instance.to_dict()) except ValidationError as ex: raise ModelValidationError( ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs)
def _validate(instance): """Validate the internal representation of the instance.""" try: _ = instance.schema.validate(instance.to_dict()) except ValidationError as ex: raise ModelValidationError( ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs)
[ "Validate", "the", "internal", "representation", "of", "the", "instance", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/validation/base.py#L227-L233
[ "def", "_validate", "(", "instance", ")", ":", "try", ":", "_", "=", "instance", ".", "schema", ".", "validate", "(", "instance", ".", "to_dict", "(", ")", ")", "except", "ValidationError", "as", "ex", ":", "raise", "ModelValidationError", "(", "ex", ".", "messages", ",", "ex", ".", "field_names", ",", "ex", ".", "fields", ",", "ex", ".", "data", ",", "*", "*", "ex", ".", "kwargs", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_SchemaBinder._validate_after_init
Add validation after instantiation.
qiskit/validation/base.py
def _validate_after_init(init_method): """Add validation after instantiation.""" @wraps(init_method) def _decorated(self, **kwargs): try: _ = self.shallow_schema.validate(kwargs) except ValidationError as ex: raise ModelValidationError( ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs) from None init_method(self, **kwargs) return _decorated
def _validate_after_init(init_method): """Add validation after instantiation.""" @wraps(init_method) def _decorated(self, **kwargs): try: _ = self.shallow_schema.validate(kwargs) except ValidationError as ex: raise ModelValidationError( ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs) from None init_method(self, **kwargs) return _decorated
[ "Add", "validation", "after", "instantiation", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/validation/base.py#L236-L249
[ "def", "_validate_after_init", "(", "init_method", ")", ":", "@", "wraps", "(", "init_method", ")", "def", "_decorated", "(", "self", ",", "*", "*", "kwargs", ")", ":", "try", ":", "_", "=", "self", ".", "shallow_schema", ".", "validate", "(", "kwargs", ")", "except", "ValidationError", "as", "ex", ":", "raise", "ModelValidationError", "(", "ex", ".", "messages", ",", "ex", ".", "field_names", ",", "ex", ".", "fields", ",", "ex", ".", "data", ",", "*", "*", "ex", ".", "kwargs", ")", "from", "None", "init_method", "(", "self", ",", "*", "*", "kwargs", ")", "return", "_decorated" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BaseModel.to_dict
Serialize the model into a Python dict of simple types. Note that this method requires that the model is bound with ``@bind_schema``.
qiskit/validation/base.py
def to_dict(self): """Serialize the model into a Python dict of simple types. Note that this method requires that the model is bound with ``@bind_schema``. """ try: data, _ = self.schema.dump(self) except ValidationError as ex: raise ModelValidationError( ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs) from None return data
def to_dict(self): """Serialize the model into a Python dict of simple types. Note that this method requires that the model is bound with ``@bind_schema``. """ try: data, _ = self.schema.dump(self) except ValidationError as ex: raise ModelValidationError( ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs) from None return data
[ "Serialize", "the", "model", "into", "a", "Python", "dict", "of", "simple", "types", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/validation/base.py#L320-L332
[ "def", "to_dict", "(", "self", ")", ":", "try", ":", "data", ",", "_", "=", "self", ".", "schema", ".", "dump", "(", "self", ")", "except", "ValidationError", "as", "ex", ":", "raise", "ModelValidationError", "(", "ex", ".", "messages", ",", "ex", ".", "field_names", ",", "ex", ".", "fields", ",", "ex", ".", "data", ",", "*", "*", "ex", ".", "kwargs", ")", "from", "None", "return", "data" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BaseModel.from_dict
Deserialize a dict of simple types into an instance of this class. Note that this method requires that the model is bound with ``@bind_schema``.
qiskit/validation/base.py
def from_dict(cls, dict_): """Deserialize a dict of simple types into an instance of this class. Note that this method requires that the model is bound with ``@bind_schema``. """ try: data, _ = cls.schema.load(dict_) except ValidationError as ex: raise ModelValidationError( ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs) from None return data
def from_dict(cls, dict_): """Deserialize a dict of simple types into an instance of this class. Note that this method requires that the model is bound with ``@bind_schema``. """ try: data, _ = cls.schema.load(dict_) except ValidationError as ex: raise ModelValidationError( ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs) from None return data
[ "Deserialize", "a", "dict", "of", "simple", "types", "into", "an", "instance", "of", "this", "class", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/validation/base.py#L335-L347
[ "def", "from_dict", "(", "cls", ",", "dict_", ")", ":", "try", ":", "data", ",", "_", "=", "cls", ".", "schema", ".", "load", "(", "dict_", ")", "except", "ValidationError", "as", "ex", ":", "raise", "ModelValidationError", "(", "ex", ".", "messages", ",", "ex", ".", "field_names", ",", "ex", ".", "fields", ",", "ex", ".", "data", ",", "*", "*", "ex", ".", "kwargs", ")", "from", "None", "return", "data" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
qft
n-qubit QFT on q in circ.
qiskit/tools/qi/qi.py
def qft(circ, q, n): """n-qubit QFT on q in circ.""" for j in range(n): for k in range(j): circ.cu1(math.pi / float(2**(j - k)), q[j], q[k]) circ.h(q[j])
def qft(circ, q, n): """n-qubit QFT on q in circ.""" for j in range(n): for k in range(j): circ.cu1(math.pi / float(2**(j - k)), q[j], q[k]) circ.h(q[j])
[ "n", "-", "qubit", "QFT", "on", "q", "in", "circ", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qi/qi.py#L35-L40
[ "def", "qft", "(", "circ", ",", "q", ",", "n", ")", ":", "for", "j", "in", "range", "(", "n", ")", ":", "for", "k", "in", "range", "(", "j", ")", ":", "circ", ".", "cu1", "(", "math", ".", "pi", "/", "float", "(", "2", "**", "(", "j", "-", "k", ")", ")", ",", "q", "[", "j", "]", ",", "q", "[", "k", "]", ")", "circ", ".", "h", "(", "q", "[", "j", "]", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
partial_trace
Partial trace over subsystems of multi-partite matrix. Note that subsystems are ordered as rho012 = rho0(x)rho1(x)rho2. Args: state (matrix_like): a matrix NxN trace_systems (list(int)): a list of subsystems (starting from 0) to trace over. dimensions (list(int)): a list of the dimensions of the subsystems. If this is not set it will assume all subsystems are qubits. reverse (bool): ordering of systems in operator. If True system-0 is the right most system in tensor product. If False system-0 is the left most system in tensor product. Returns: matrix_like: A density matrix with the appropriate subsystems traced over. Raises: Exception: if input is not a multi-qubit state.
qiskit/tools/qi/qi.py
def partial_trace(state, trace_systems, dimensions=None, reverse=True): """ Partial trace over subsystems of multi-partite matrix. Note that subsystems are ordered as rho012 = rho0(x)rho1(x)rho2. Args: state (matrix_like): a matrix NxN trace_systems (list(int)): a list of subsystems (starting from 0) to trace over. dimensions (list(int)): a list of the dimensions of the subsystems. If this is not set it will assume all subsystems are qubits. reverse (bool): ordering of systems in operator. If True system-0 is the right most system in tensor product. If False system-0 is the left most system in tensor product. Returns: matrix_like: A density matrix with the appropriate subsystems traced over. Raises: Exception: if input is not a multi-qubit state. """ state = np.array(state) # convert op to density matrix if dimensions is None: # compute dims if not specified num_qubits = int(np.log2(len(state))) dimensions = [2 for _ in range(num_qubits)] if len(state) != 2 ** num_qubits: raise Exception("Input is not a multi-qubit state, " "specify input state dims") else: dimensions = list(dimensions) if isinstance(trace_systems, int): trace_systems = [trace_systems] else: # reverse sort trace sys trace_systems = sorted(trace_systems, reverse=True) # trace out subsystems if state.ndim == 1: # optimized partial trace for input state vector return __partial_trace_vec(state, trace_systems, dimensions, reverse) # standard partial trace for input density matrix return __partial_trace_mat(state, trace_systems, dimensions, reverse)
def partial_trace(state, trace_systems, dimensions=None, reverse=True): """ Partial trace over subsystems of multi-partite matrix. Note that subsystems are ordered as rho012 = rho0(x)rho1(x)rho2. Args: state (matrix_like): a matrix NxN trace_systems (list(int)): a list of subsystems (starting from 0) to trace over. dimensions (list(int)): a list of the dimensions of the subsystems. If this is not set it will assume all subsystems are qubits. reverse (bool): ordering of systems in operator. If True system-0 is the right most system in tensor product. If False system-0 is the left most system in tensor product. Returns: matrix_like: A density matrix with the appropriate subsystems traced over. Raises: Exception: if input is not a multi-qubit state. """ state = np.array(state) # convert op to density matrix if dimensions is None: # compute dims if not specified num_qubits = int(np.log2(len(state))) dimensions = [2 for _ in range(num_qubits)] if len(state) != 2 ** num_qubits: raise Exception("Input is not a multi-qubit state, " "specify input state dims") else: dimensions = list(dimensions) if isinstance(trace_systems, int): trace_systems = [trace_systems] else: # reverse sort trace sys trace_systems = sorted(trace_systems, reverse=True) # trace out subsystems if state.ndim == 1: # optimized partial trace for input state vector return __partial_trace_vec(state, trace_systems, dimensions, reverse) # standard partial trace for input density matrix return __partial_trace_mat(state, trace_systems, dimensions, reverse)
[ "Partial", "trace", "over", "subsystems", "of", "multi", "-", "partite", "matrix", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qi/qi.py#L48-L92
[ "def", "partial_trace", "(", "state", ",", "trace_systems", ",", "dimensions", "=", "None", ",", "reverse", "=", "True", ")", ":", "state", "=", "np", ".", "array", "(", "state", ")", "# convert op to density matrix", "if", "dimensions", "is", "None", ":", "# compute dims if not specified", "num_qubits", "=", "int", "(", "np", ".", "log2", "(", "len", "(", "state", ")", ")", ")", "dimensions", "=", "[", "2", "for", "_", "in", "range", "(", "num_qubits", ")", "]", "if", "len", "(", "state", ")", "!=", "2", "**", "num_qubits", ":", "raise", "Exception", "(", "\"Input is not a multi-qubit state, \"", "\"specify input state dims\"", ")", "else", ":", "dimensions", "=", "list", "(", "dimensions", ")", "if", "isinstance", "(", "trace_systems", ",", "int", ")", ":", "trace_systems", "=", "[", "trace_systems", "]", "else", ":", "# reverse sort trace sys", "trace_systems", "=", "sorted", "(", "trace_systems", ",", "reverse", "=", "True", ")", "# trace out subsystems", "if", "state", ".", "ndim", "==", "1", ":", "# optimized partial trace for input state vector", "return", "__partial_trace_vec", "(", "state", ",", "trace_systems", ",", "dimensions", ",", "reverse", ")", "# standard partial trace for input density matrix", "return", "__partial_trace_mat", "(", "state", ",", "trace_systems", ",", "dimensions", ",", "reverse", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
__partial_trace_vec
Partial trace over subsystems of multi-partite vector. Args: vec (vector_like): complex vector N trace_systems (list(int)): a list of subsystems (starting from 0) to trace over. dimensions (list(int)): a list of the dimensions of the subsystems. If this is not set it will assume all subsystems are qubits. reverse (bool): ordering of systems in operator. If True system-0 is the right most system in tensor product. If False system-0 is the left most system in tensor product. Returns: ndarray: A density matrix with the appropriate subsystems traced over.
qiskit/tools/qi/qi.py
def __partial_trace_vec(vec, trace_systems, dimensions, reverse=True): """ Partial trace over subsystems of multi-partite vector. Args: vec (vector_like): complex vector N trace_systems (list(int)): a list of subsystems (starting from 0) to trace over. dimensions (list(int)): a list of the dimensions of the subsystems. If this is not set it will assume all subsystems are qubits. reverse (bool): ordering of systems in operator. If True system-0 is the right most system in tensor product. If False system-0 is the left most system in tensor product. Returns: ndarray: A density matrix with the appropriate subsystems traced over. """ # trace sys positions if reverse: dimensions = dimensions[::-1] trace_systems = len(dimensions) - 1 - np.array(trace_systems) rho = vec.reshape(dimensions) rho = np.tensordot(rho, rho.conj(), axes=(trace_systems, trace_systems)) d = int(np.sqrt(np.product(rho.shape))) return rho.reshape(d, d)
def __partial_trace_vec(vec, trace_systems, dimensions, reverse=True): """ Partial trace over subsystems of multi-partite vector. Args: vec (vector_like): complex vector N trace_systems (list(int)): a list of subsystems (starting from 0) to trace over. dimensions (list(int)): a list of the dimensions of the subsystems. If this is not set it will assume all subsystems are qubits. reverse (bool): ordering of systems in operator. If True system-0 is the right most system in tensor product. If False system-0 is the left most system in tensor product. Returns: ndarray: A density matrix with the appropriate subsystems traced over. """ # trace sys positions if reverse: dimensions = dimensions[::-1] trace_systems = len(dimensions) - 1 - np.array(trace_systems) rho = vec.reshape(dimensions) rho = np.tensordot(rho, rho.conj(), axes=(trace_systems, trace_systems)) d = int(np.sqrt(np.product(rho.shape))) return rho.reshape(d, d)
[ "Partial", "trace", "over", "subsystems", "of", "multi", "-", "partite", "vector", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qi/qi.py#L95-L123
[ "def", "__partial_trace_vec", "(", "vec", ",", "trace_systems", ",", "dimensions", ",", "reverse", "=", "True", ")", ":", "# trace sys positions", "if", "reverse", ":", "dimensions", "=", "dimensions", "[", ":", ":", "-", "1", "]", "trace_systems", "=", "len", "(", "dimensions", ")", "-", "1", "-", "np", ".", "array", "(", "trace_systems", ")", "rho", "=", "vec", ".", "reshape", "(", "dimensions", ")", "rho", "=", "np", ".", "tensordot", "(", "rho", ",", "rho", ".", "conj", "(", ")", ",", "axes", "=", "(", "trace_systems", ",", "trace_systems", ")", ")", "d", "=", "int", "(", "np", ".", "sqrt", "(", "np", ".", "product", "(", "rho", ".", "shape", ")", ")", ")", "return", "rho", ".", "reshape", "(", "d", ",", "d", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
__partial_trace_mat
Partial trace over subsystems of multi-partite matrix. Note that subsystems are ordered as rho012 = rho0(x)rho1(x)rho2. Args: mat (matrix_like): a matrix NxN. trace_systems (list(int)): a list of subsystems (starting from 0) to trace over. dimensions (list(int)): a list of the dimensions of the subsystems. If this is not set it will assume all subsystems are qubits. reverse (bool): ordering of systems in operator. If True system-0 is the right most system in tensor product. If False system-0 is the left most system in tensor product. Returns: ndarray: A density matrix with the appropriate subsystems traced over.
qiskit/tools/qi/qi.py
def __partial_trace_mat(mat, trace_systems, dimensions, reverse=True): """ Partial trace over subsystems of multi-partite matrix. Note that subsystems are ordered as rho012 = rho0(x)rho1(x)rho2. Args: mat (matrix_like): a matrix NxN. trace_systems (list(int)): a list of subsystems (starting from 0) to trace over. dimensions (list(int)): a list of the dimensions of the subsystems. If this is not set it will assume all subsystems are qubits. reverse (bool): ordering of systems in operator. If True system-0 is the right most system in tensor product. If False system-0 is the left most system in tensor product. Returns: ndarray: A density matrix with the appropriate subsystems traced over. """ trace_systems = sorted(trace_systems, reverse=True) for j in trace_systems: # Partition subsystem dimensions dimension_trace = int(dimensions[j]) # traced out system if reverse: left_dimensions = dimensions[j + 1:] right_dimensions = dimensions[:j] dimensions = right_dimensions + left_dimensions else: left_dimensions = dimensions[:j] right_dimensions = dimensions[j + 1:] dimensions = left_dimensions + right_dimensions # Contract remaining dimensions dimension_left = int(np.prod(left_dimensions)) dimension_right = int(np.prod(right_dimensions)) # Reshape input array into tri-partite system with system to be # traced as the middle index mat = mat.reshape([dimension_left, dimension_trace, dimension_right, dimension_left, dimension_trace, dimension_right]) # trace out the middle system and reshape back to a matrix mat = mat.trace(axis1=1, axis2=4).reshape( dimension_left * dimension_right, dimension_left * dimension_right) return mat
def __partial_trace_mat(mat, trace_systems, dimensions, reverse=True): """ Partial trace over subsystems of multi-partite matrix. Note that subsystems are ordered as rho012 = rho0(x)rho1(x)rho2. Args: mat (matrix_like): a matrix NxN. trace_systems (list(int)): a list of subsystems (starting from 0) to trace over. dimensions (list(int)): a list of the dimensions of the subsystems. If this is not set it will assume all subsystems are qubits. reverse (bool): ordering of systems in operator. If True system-0 is the right most system in tensor product. If False system-0 is the left most system in tensor product. Returns: ndarray: A density matrix with the appropriate subsystems traced over. """ trace_systems = sorted(trace_systems, reverse=True) for j in trace_systems: # Partition subsystem dimensions dimension_trace = int(dimensions[j]) # traced out system if reverse: left_dimensions = dimensions[j + 1:] right_dimensions = dimensions[:j] dimensions = right_dimensions + left_dimensions else: left_dimensions = dimensions[:j] right_dimensions = dimensions[j + 1:] dimensions = left_dimensions + right_dimensions # Contract remaining dimensions dimension_left = int(np.prod(left_dimensions)) dimension_right = int(np.prod(right_dimensions)) # Reshape input array into tri-partite system with system to be # traced as the middle index mat = mat.reshape([dimension_left, dimension_trace, dimension_right, dimension_left, dimension_trace, dimension_right]) # trace out the middle system and reshape back to a matrix mat = mat.trace(axis1=1, axis2=4).reshape( dimension_left * dimension_right, dimension_left * dimension_right) return mat
[ "Partial", "trace", "over", "subsystems", "of", "multi", "-", "partite", "matrix", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qi/qi.py#L126-L171
[ "def", "__partial_trace_mat", "(", "mat", ",", "trace_systems", ",", "dimensions", ",", "reverse", "=", "True", ")", ":", "trace_systems", "=", "sorted", "(", "trace_systems", ",", "reverse", "=", "True", ")", "for", "j", "in", "trace_systems", ":", "# Partition subsystem dimensions", "dimension_trace", "=", "int", "(", "dimensions", "[", "j", "]", ")", "# traced out system", "if", "reverse", ":", "left_dimensions", "=", "dimensions", "[", "j", "+", "1", ":", "]", "right_dimensions", "=", "dimensions", "[", ":", "j", "]", "dimensions", "=", "right_dimensions", "+", "left_dimensions", "else", ":", "left_dimensions", "=", "dimensions", "[", ":", "j", "]", "right_dimensions", "=", "dimensions", "[", "j", "+", "1", ":", "]", "dimensions", "=", "left_dimensions", "+", "right_dimensions", "# Contract remaining dimensions", "dimension_left", "=", "int", "(", "np", ".", "prod", "(", "left_dimensions", ")", ")", "dimension_right", "=", "int", "(", "np", ".", "prod", "(", "right_dimensions", ")", ")", "# Reshape input array into tri-partite system with system to be", "# traced as the middle index", "mat", "=", "mat", ".", "reshape", "(", "[", "dimension_left", ",", "dimension_trace", ",", "dimension_right", ",", "dimension_left", ",", "dimension_trace", ",", "dimension_right", "]", ")", "# trace out the middle system and reshape back to a matrix", "mat", "=", "mat", ".", "trace", "(", "axis1", "=", "1", ",", "axis2", "=", "4", ")", ".", "reshape", "(", "dimension_left", "*", "dimension_right", ",", "dimension_left", "*", "dimension_right", ")", "return", "mat" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
vectorize
Flatten an operator to a vector in a specified basis. Args: density_matrix (ndarray): a density matrix. method (str): the method of vectorization. Allowed values are - 'col' (default) flattens to column-major vector. - 'row' flattens to row-major vector. - 'pauli'flattens in the n-qubit Pauli basis. - 'pauli-weights': flattens in the n-qubit Pauli basis ordered by weight. Returns: ndarray: the resulting vector. Raises: Exception: if input state is not a n-qubit state
qiskit/tools/qi/qi.py
def vectorize(density_matrix, method='col'): """Flatten an operator to a vector in a specified basis. Args: density_matrix (ndarray): a density matrix. method (str): the method of vectorization. Allowed values are - 'col' (default) flattens to column-major vector. - 'row' flattens to row-major vector. - 'pauli'flattens in the n-qubit Pauli basis. - 'pauli-weights': flattens in the n-qubit Pauli basis ordered by weight. Returns: ndarray: the resulting vector. Raises: Exception: if input state is not a n-qubit state """ density_matrix = np.array(density_matrix) if method == 'col': return density_matrix.flatten(order='F') elif method == 'row': return density_matrix.flatten(order='C') elif method in ['pauli', 'pauli_weights']: num = int(np.log2(len(density_matrix))) # number of qubits if len(density_matrix) != 2**num: raise Exception('Input state must be n-qubit state') if method == 'pauli_weights': pgroup = pauli_group(num, case='weight') else: pgroup = pauli_group(num, case='tensor') vals = [np.trace(np.dot(p.to_matrix(), density_matrix)) for p in pgroup] return np.array(vals) return None
def vectorize(density_matrix, method='col'): """Flatten an operator to a vector in a specified basis. Args: density_matrix (ndarray): a density matrix. method (str): the method of vectorization. Allowed values are - 'col' (default) flattens to column-major vector. - 'row' flattens to row-major vector. - 'pauli'flattens in the n-qubit Pauli basis. - 'pauli-weights': flattens in the n-qubit Pauli basis ordered by weight. Returns: ndarray: the resulting vector. Raises: Exception: if input state is not a n-qubit state """ density_matrix = np.array(density_matrix) if method == 'col': return density_matrix.flatten(order='F') elif method == 'row': return density_matrix.flatten(order='C') elif method in ['pauli', 'pauli_weights']: num = int(np.log2(len(density_matrix))) # number of qubits if len(density_matrix) != 2**num: raise Exception('Input state must be n-qubit state') if method == 'pauli_weights': pgroup = pauli_group(num, case='weight') else: pgroup = pauli_group(num, case='tensor') vals = [np.trace(np.dot(p.to_matrix(), density_matrix)) for p in pgroup] return np.array(vals) return None
[ "Flatten", "an", "operator", "to", "a", "vector", "in", "a", "specified", "basis", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qi/qi.py#L174-L207
[ "def", "vectorize", "(", "density_matrix", ",", "method", "=", "'col'", ")", ":", "density_matrix", "=", "np", ".", "array", "(", "density_matrix", ")", "if", "method", "==", "'col'", ":", "return", "density_matrix", ".", "flatten", "(", "order", "=", "'F'", ")", "elif", "method", "==", "'row'", ":", "return", "density_matrix", ".", "flatten", "(", "order", "=", "'C'", ")", "elif", "method", "in", "[", "'pauli'", ",", "'pauli_weights'", "]", ":", "num", "=", "int", "(", "np", ".", "log2", "(", "len", "(", "density_matrix", ")", ")", ")", "# number of qubits", "if", "len", "(", "density_matrix", ")", "!=", "2", "**", "num", ":", "raise", "Exception", "(", "'Input state must be n-qubit state'", ")", "if", "method", "==", "'pauli_weights'", ":", "pgroup", "=", "pauli_group", "(", "num", ",", "case", "=", "'weight'", ")", "else", ":", "pgroup", "=", "pauli_group", "(", "num", ",", "case", "=", "'tensor'", ")", "vals", "=", "[", "np", ".", "trace", "(", "np", ".", "dot", "(", "p", ".", "to_matrix", "(", ")", ",", "density_matrix", ")", ")", "for", "p", "in", "pgroup", "]", "return", "np", ".", "array", "(", "vals", ")", "return", "None" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
devectorize
Devectorize a vectorized square matrix. Args: vectorized_mat (ndarray): a vectorized density matrix. method (str): the method of devectorization. Allowed values are - 'col' (default): flattens to column-major vector. - 'row': flattens to row-major vector. - 'pauli': flattens in the n-qubit Pauli basis. - 'pauli-weights': flattens in the n-qubit Pauli basis ordered by weight. Returns: ndarray: the resulting matrix. Raises: Exception: if input state is not a n-qubit state
qiskit/tools/qi/qi.py
def devectorize(vectorized_mat, method='col'): """Devectorize a vectorized square matrix. Args: vectorized_mat (ndarray): a vectorized density matrix. method (str): the method of devectorization. Allowed values are - 'col' (default): flattens to column-major vector. - 'row': flattens to row-major vector. - 'pauli': flattens in the n-qubit Pauli basis. - 'pauli-weights': flattens in the n-qubit Pauli basis ordered by weight. Returns: ndarray: the resulting matrix. Raises: Exception: if input state is not a n-qubit state """ vectorized_mat = np.array(vectorized_mat) dimension = int(np.sqrt(vectorized_mat.size)) if len(vectorized_mat) != dimension * dimension: raise Exception('Input is not a vectorized square matrix') if method == 'col': return vectorized_mat.reshape(dimension, dimension, order='F') elif method == 'row': return vectorized_mat.reshape(dimension, dimension, order='C') elif method in ['pauli', 'pauli_weights']: num_qubits = int(np.log2(dimension)) # number of qubits if dimension != 2 ** num_qubits: raise Exception('Input state must be n-qubit state') if method == 'pauli_weights': pgroup = pauli_group(num_qubits, case='weight') else: pgroup = pauli_group(num_qubits, case='tensor') pbasis = np.array([p.to_matrix() for p in pgroup]) / 2 ** num_qubits return np.tensordot(vectorized_mat, pbasis, axes=1) return None
def devectorize(vectorized_mat, method='col'): """Devectorize a vectorized square matrix. Args: vectorized_mat (ndarray): a vectorized density matrix. method (str): the method of devectorization. Allowed values are - 'col' (default): flattens to column-major vector. - 'row': flattens to row-major vector. - 'pauli': flattens in the n-qubit Pauli basis. - 'pauli-weights': flattens in the n-qubit Pauli basis ordered by weight. Returns: ndarray: the resulting matrix. Raises: Exception: if input state is not a n-qubit state """ vectorized_mat = np.array(vectorized_mat) dimension = int(np.sqrt(vectorized_mat.size)) if len(vectorized_mat) != dimension * dimension: raise Exception('Input is not a vectorized square matrix') if method == 'col': return vectorized_mat.reshape(dimension, dimension, order='F') elif method == 'row': return vectorized_mat.reshape(dimension, dimension, order='C') elif method in ['pauli', 'pauli_weights']: num_qubits = int(np.log2(dimension)) # number of qubits if dimension != 2 ** num_qubits: raise Exception('Input state must be n-qubit state') if method == 'pauli_weights': pgroup = pauli_group(num_qubits, case='weight') else: pgroup = pauli_group(num_qubits, case='tensor') pbasis = np.array([p.to_matrix() for p in pgroup]) / 2 ** num_qubits return np.tensordot(vectorized_mat, pbasis, axes=1) return None
[ "Devectorize", "a", "vectorized", "square", "matrix", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qi/qi.py#L210-L246
[ "def", "devectorize", "(", "vectorized_mat", ",", "method", "=", "'col'", ")", ":", "vectorized_mat", "=", "np", ".", "array", "(", "vectorized_mat", ")", "dimension", "=", "int", "(", "np", ".", "sqrt", "(", "vectorized_mat", ".", "size", ")", ")", "if", "len", "(", "vectorized_mat", ")", "!=", "dimension", "*", "dimension", ":", "raise", "Exception", "(", "'Input is not a vectorized square matrix'", ")", "if", "method", "==", "'col'", ":", "return", "vectorized_mat", ".", "reshape", "(", "dimension", ",", "dimension", ",", "order", "=", "'F'", ")", "elif", "method", "==", "'row'", ":", "return", "vectorized_mat", ".", "reshape", "(", "dimension", ",", "dimension", ",", "order", "=", "'C'", ")", "elif", "method", "in", "[", "'pauli'", ",", "'pauli_weights'", "]", ":", "num_qubits", "=", "int", "(", "np", ".", "log2", "(", "dimension", ")", ")", "# number of qubits", "if", "dimension", "!=", "2", "**", "num_qubits", ":", "raise", "Exception", "(", "'Input state must be n-qubit state'", ")", "if", "method", "==", "'pauli_weights'", ":", "pgroup", "=", "pauli_group", "(", "num_qubits", ",", "case", "=", "'weight'", ")", "else", ":", "pgroup", "=", "pauli_group", "(", "num_qubits", ",", "case", "=", "'tensor'", ")", "pbasis", "=", "np", ".", "array", "(", "[", "p", ".", "to_matrix", "(", ")", "for", "p", "in", "pgroup", "]", ")", "/", "2", "**", "num_qubits", "return", "np", ".", "tensordot", "(", "vectorized_mat", ",", "pbasis", ",", "axes", "=", "1", ")", "return", "None" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
choi_to_rauli
Convert a Choi-matrix to a Pauli-basis superoperator. Note that this function assumes that the Choi-matrix is defined in the standard column-stacking convention and is normalized to have trace 1. For a channel E this is defined as: choi = (I \\otimes E)(bell_state). The resulting 'rauli' R acts on input states as |rho_out>_p = R.|rho_in>_p where |rho> = vectorize(rho, method='pauli') for order=1 and |rho> = vectorize(rho, method='pauli_weights') for order=0. Args: choi (matrix): the input Choi-matrix. order (int): ordering of the Pauli group vector. order=1 (default) is standard lexicographic ordering. Eg: [II, IX, IY, IZ, XI, XX, XY,...] order=0 is ordered by weights. Eg. [II, IX, IY, IZ, XI, XY, XZ, XX, XY,...] Returns: np.array: A superoperator in the Pauli basis.
qiskit/tools/qi/qi.py
def choi_to_rauli(choi, order=1): """ Convert a Choi-matrix to a Pauli-basis superoperator. Note that this function assumes that the Choi-matrix is defined in the standard column-stacking convention and is normalized to have trace 1. For a channel E this is defined as: choi = (I \\otimes E)(bell_state). The resulting 'rauli' R acts on input states as |rho_out>_p = R.|rho_in>_p where |rho> = vectorize(rho, method='pauli') for order=1 and |rho> = vectorize(rho, method='pauli_weights') for order=0. Args: choi (matrix): the input Choi-matrix. order (int): ordering of the Pauli group vector. order=1 (default) is standard lexicographic ordering. Eg: [II, IX, IY, IZ, XI, XX, XY,...] order=0 is ordered by weights. Eg. [II, IX, IY, IZ, XI, XY, XZ, XX, XY,...] Returns: np.array: A superoperator in the Pauli basis. """ if order == 0: order = 'weight' elif order == 1: order = 'tensor' # get number of qubits' num_qubits = int(np.log2(np.sqrt(len(choi)))) pgp = pauli_group(num_qubits, case=order) rauli = [] for i in pgp: for j in pgp: pauliop = np.kron(j.to_matrix().T, i.to_matrix()) rauli += [np.trace(np.dot(choi, pauliop))] return np.array(rauli).reshape(4 ** num_qubits, 4 ** num_qubits)
def choi_to_rauli(choi, order=1): """ Convert a Choi-matrix to a Pauli-basis superoperator. Note that this function assumes that the Choi-matrix is defined in the standard column-stacking convention and is normalized to have trace 1. For a channel E this is defined as: choi = (I \\otimes E)(bell_state). The resulting 'rauli' R acts on input states as |rho_out>_p = R.|rho_in>_p where |rho> = vectorize(rho, method='pauli') for order=1 and |rho> = vectorize(rho, method='pauli_weights') for order=0. Args: choi (matrix): the input Choi-matrix. order (int): ordering of the Pauli group vector. order=1 (default) is standard lexicographic ordering. Eg: [II, IX, IY, IZ, XI, XX, XY,...] order=0 is ordered by weights. Eg. [II, IX, IY, IZ, XI, XY, XZ, XX, XY,...] Returns: np.array: A superoperator in the Pauli basis. """ if order == 0: order = 'weight' elif order == 1: order = 'tensor' # get number of qubits' num_qubits = int(np.log2(np.sqrt(len(choi)))) pgp = pauli_group(num_qubits, case=order) rauli = [] for i in pgp: for j in pgp: pauliop = np.kron(j.to_matrix().T, i.to_matrix()) rauli += [np.trace(np.dot(choi, pauliop))] return np.array(rauli).reshape(4 ** num_qubits, 4 ** num_qubits)
[ "Convert", "a", "Choi", "-", "matrix", "to", "a", "Pauli", "-", "basis", "superoperator", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qi/qi.py#L249-L287
[ "def", "choi_to_rauli", "(", "choi", ",", "order", "=", "1", ")", ":", "if", "order", "==", "0", ":", "order", "=", "'weight'", "elif", "order", "==", "1", ":", "order", "=", "'tensor'", "# get number of qubits'", "num_qubits", "=", "int", "(", "np", ".", "log2", "(", "np", ".", "sqrt", "(", "len", "(", "choi", ")", ")", ")", ")", "pgp", "=", "pauli_group", "(", "num_qubits", ",", "case", "=", "order", ")", "rauli", "=", "[", "]", "for", "i", "in", "pgp", ":", "for", "j", "in", "pgp", ":", "pauliop", "=", "np", ".", "kron", "(", "j", ".", "to_matrix", "(", ")", ".", "T", ",", "i", ".", "to_matrix", "(", ")", ")", "rauli", "+=", "[", "np", ".", "trace", "(", "np", ".", "dot", "(", "choi", ",", "pauliop", ")", ")", "]", "return", "np", ".", "array", "(", "rauli", ")", ".", "reshape", "(", "4", "**", "num_qubits", ",", "4", "**", "num_qubits", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
chop
Truncate small values of a complex array. Args: array (array_like): array to truncte small values. epsilon (float): threshold. Returns: np.array: A new operator with small values set to zero.
qiskit/tools/qi/qi.py
def chop(array, epsilon=1e-10): """ Truncate small values of a complex array. Args: array (array_like): array to truncte small values. epsilon (float): threshold. Returns: np.array: A new operator with small values set to zero. """ ret = np.array(array) if np.isrealobj(ret): ret[abs(ret) < epsilon] = 0.0 else: ret.real[abs(ret.real) < epsilon] = 0.0 ret.imag[abs(ret.imag) < epsilon] = 0.0 return ret
def chop(array, epsilon=1e-10): """ Truncate small values of a complex array. Args: array (array_like): array to truncte small values. epsilon (float): threshold. Returns: np.array: A new operator with small values set to zero. """ ret = np.array(array) if np.isrealobj(ret): ret[abs(ret) < epsilon] = 0.0 else: ret.real[abs(ret.real) < epsilon] = 0.0 ret.imag[abs(ret.imag) < epsilon] = 0.0 return ret
[ "Truncate", "small", "values", "of", "a", "complex", "array", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qi/qi.py#L290-L308
[ "def", "chop", "(", "array", ",", "epsilon", "=", "1e-10", ")", ":", "ret", "=", "np", ".", "array", "(", "array", ")", "if", "np", ".", "isrealobj", "(", "ret", ")", ":", "ret", "[", "abs", "(", "ret", ")", "<", "epsilon", "]", "=", "0.0", "else", ":", "ret", ".", "real", "[", "abs", "(", "ret", ".", "real", ")", "<", "epsilon", "]", "=", "0.0", "ret", ".", "imag", "[", "abs", "(", "ret", ".", "imag", ")", "<", "epsilon", "]", "=", "0.0", "return", "ret" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
outer
Construct the outer product of two vectors. The second vector argument is optional, if absent the projector of the first vector will be returned. Args: vector1 (ndarray): the first vector. vector2 (ndarray): the (optional) second vector. Returns: np.array: The matrix |v1><v2|.
qiskit/tools/qi/qi.py
def outer(vector1, vector2=None): """ Construct the outer product of two vectors. The second vector argument is optional, if absent the projector of the first vector will be returned. Args: vector1 (ndarray): the first vector. vector2 (ndarray): the (optional) second vector. Returns: np.array: The matrix |v1><v2|. """ if vector2 is None: vector2 = np.array(vector1).conj() else: vector2 = np.array(vector2).conj() return np.outer(vector1, vector2)
def outer(vector1, vector2=None): """ Construct the outer product of two vectors. The second vector argument is optional, if absent the projector of the first vector will be returned. Args: vector1 (ndarray): the first vector. vector2 (ndarray): the (optional) second vector. Returns: np.array: The matrix |v1><v2|. """ if vector2 is None: vector2 = np.array(vector1).conj() else: vector2 = np.array(vector2).conj() return np.outer(vector1, vector2)
[ "Construct", "the", "outer", "product", "of", "two", "vectors", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qi/qi.py#L311-L330
[ "def", "outer", "(", "vector1", ",", "vector2", "=", "None", ")", ":", "if", "vector2", "is", "None", ":", "vector2", "=", "np", ".", "array", "(", "vector1", ")", ".", "conj", "(", ")", "else", ":", "vector2", "=", "np", ".", "array", "(", "vector2", ")", ".", "conj", "(", ")", "return", "np", ".", "outer", "(", "vector1", ",", "vector2", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
random_unitary_matrix
Deprecated in 0.8+
qiskit/tools/qi/qi.py
def random_unitary_matrix(dim, seed=None): """Deprecated in 0.8+ """ warnings.warn('The random_unitary_matrix() function in qiskit.tools.qi has been ' 'deprecated and will be removed in the future. Instead use ' 'the function in qiskit.quantum_info.random', DeprecationWarning) return random.random_unitary(dim, seed).data
def random_unitary_matrix(dim, seed=None): """Deprecated in 0.8+ """ warnings.warn('The random_unitary_matrix() function in qiskit.tools.qi has been ' 'deprecated and will be removed in the future. Instead use ' 'the function in qiskit.quantum_info.random', DeprecationWarning) return random.random_unitary(dim, seed).data
[ "Deprecated", "in", "0", ".", "8", "+" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qi/qi.py#L337-L344
[ "def", "random_unitary_matrix", "(", "dim", ",", "seed", "=", "None", ")", ":", "warnings", ".", "warn", "(", "'The random_unitary_matrix() function in qiskit.tools.qi has been '", "'deprecated and will be removed in the future. Instead use '", "'the function in qiskit.quantum_info.random'", ",", "DeprecationWarning", ")", "return", "random", ".", "random_unitary", "(", "dim", ",", "seed", ")", ".", "data" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
random_density_matrix
Deprecated in 0.8+
qiskit/tools/qi/qi.py
def random_density_matrix(length, rank=None, method='Hilbert-Schmidt', seed=None): """Deprecated in 0.8+ """ warnings.warn('The random_density_matrix() function in qiskit.tools.qi has been ' 'deprecated and will be removed in the future. Instead use ' 'the function in qiskit.quantum_info.random', DeprecationWarning) return random.random_density_matrix(length, rank, method, seed)
def random_density_matrix(length, rank=None, method='Hilbert-Schmidt', seed=None): """Deprecated in 0.8+ """ warnings.warn('The random_density_matrix() function in qiskit.tools.qi has been ' 'deprecated and will be removed in the future. Instead use ' 'the function in qiskit.quantum_info.random', DeprecationWarning) return random.random_density_matrix(length, rank, method, seed)
[ "Deprecated", "in", "0", ".", "8", "+" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qi/qi.py#L347-L354
[ "def", "random_density_matrix", "(", "length", ",", "rank", "=", "None", ",", "method", "=", "'Hilbert-Schmidt'", ",", "seed", "=", "None", ")", ":", "warnings", ".", "warn", "(", "'The random_density_matrix() function in qiskit.tools.qi has been '", "'deprecated and will be removed in the future. Instead use '", "'the function in qiskit.quantum_info.random'", ",", "DeprecationWarning", ")", "return", "random", ".", "random_density_matrix", "(", "length", ",", "rank", ",", "method", ",", "seed", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
concurrence
Calculate the concurrence. Args: state (np.array): a quantum state (1x4 array) or a density matrix (4x4 array) Returns: float: concurrence. Raises: Exception: if attempted on more than two qubits.
qiskit/tools/qi/qi.py
def concurrence(state): """Calculate the concurrence. Args: state (np.array): a quantum state (1x4 array) or a density matrix (4x4 array) Returns: float: concurrence. Raises: Exception: if attempted on more than two qubits. """ rho = np.array(state) if rho.ndim == 1: rho = outer(state) if len(state) != 4: raise Exception("Concurrence is only defined for more than two qubits") YY = np.fliplr(np.diag([-1, 1, 1, -1])) A = rho.dot(YY).dot(rho.conj()).dot(YY) w = la.eigh(A, eigvals_only=True) w = np.sqrt(np.maximum(w, 0)) return max(0.0, w[-1] - np.sum(w[0:-1]))
def concurrence(state): """Calculate the concurrence. Args: state (np.array): a quantum state (1x4 array) or a density matrix (4x4 array) Returns: float: concurrence. Raises: Exception: if attempted on more than two qubits. """ rho = np.array(state) if rho.ndim == 1: rho = outer(state) if len(state) != 4: raise Exception("Concurrence is only defined for more than two qubits") YY = np.fliplr(np.diag([-1, 1, 1, -1])) A = rho.dot(YY).dot(rho.conj()).dot(YY) w = la.eigh(A, eigvals_only=True) w = np.sqrt(np.maximum(w, 0)) return max(0.0, w[-1] - np.sum(w[0:-1]))
[ "Calculate", "the", "concurrence", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qi/qi.py#L377-L398
[ "def", "concurrence", "(", "state", ")", ":", "rho", "=", "np", ".", "array", "(", "state", ")", "if", "rho", ".", "ndim", "==", "1", ":", "rho", "=", "outer", "(", "state", ")", "if", "len", "(", "state", ")", "!=", "4", ":", "raise", "Exception", "(", "\"Concurrence is only defined for more than two qubits\"", ")", "YY", "=", "np", ".", "fliplr", "(", "np", ".", "diag", "(", "[", "-", "1", ",", "1", ",", "1", ",", "-", "1", "]", ")", ")", "A", "=", "rho", ".", "dot", "(", "YY", ")", ".", "dot", "(", "rho", ".", "conj", "(", ")", ")", ".", "dot", "(", "YY", ")", "w", "=", "la", ".", "eigh", "(", "A", ",", "eigvals_only", "=", "True", ")", "w", "=", "np", ".", "sqrt", "(", "np", ".", "maximum", "(", "w", ",", "0", ")", ")", "return", "max", "(", "0.0", ",", "w", "[", "-", "1", "]", "-", "np", ".", "sum", "(", "w", "[", "0", ":", "-", "1", "]", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
shannon_entropy
Compute the Shannon entropy of a probability vector. The shannon entropy of a probability vector pv is defined as $H(pv) = - \\sum_j pv[j] log_b (pv[j])$ where $0 log_b 0 = 0$. Args: pvec (array_like): a probability vector. base (int): the base of the logarith Returns: float: The Shannon entropy H(pvec).
qiskit/tools/qi/qi.py
def shannon_entropy(pvec, base=2): """ Compute the Shannon entropy of a probability vector. The shannon entropy of a probability vector pv is defined as $H(pv) = - \\sum_j pv[j] log_b (pv[j])$ where $0 log_b 0 = 0$. Args: pvec (array_like): a probability vector. base (int): the base of the logarith Returns: float: The Shannon entropy H(pvec). """ # pylint: disable=missing-docstring if base == 2: def logfn(x): return - x * np.log2(x) elif base == np.e: def logfn(x): return - x * np.log(x) else: def logfn(x): return -x * np.log(x) / np.log(base) h = 0. for x in pvec: if 0 < x < 1: h += logfn(x) return h
def shannon_entropy(pvec, base=2): """ Compute the Shannon entropy of a probability vector. The shannon entropy of a probability vector pv is defined as $H(pv) = - \\sum_j pv[j] log_b (pv[j])$ where $0 log_b 0 = 0$. Args: pvec (array_like): a probability vector. base (int): the base of the logarith Returns: float: The Shannon entropy H(pvec). """ # pylint: disable=missing-docstring if base == 2: def logfn(x): return - x * np.log2(x) elif base == np.e: def logfn(x): return - x * np.log(x) else: def logfn(x): return -x * np.log(x) / np.log(base) h = 0. for x in pvec: if 0 < x < 1: h += logfn(x) return h
[ "Compute", "the", "Shannon", "entropy", "of", "a", "probability", "vector", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qi/qi.py#L401-L430
[ "def", "shannon_entropy", "(", "pvec", ",", "base", "=", "2", ")", ":", "# pylint: disable=missing-docstring", "if", "base", "==", "2", ":", "def", "logfn", "(", "x", ")", ":", "return", "-", "x", "*", "np", ".", "log2", "(", "x", ")", "elif", "base", "==", "np", ".", "e", ":", "def", "logfn", "(", "x", ")", ":", "return", "-", "x", "*", "np", ".", "log", "(", "x", ")", "else", ":", "def", "logfn", "(", "x", ")", ":", "return", "-", "x", "*", "np", ".", "log", "(", "x", ")", "/", "np", ".", "log", "(", "base", ")", "h", "=", "0.", "for", "x", "in", "pvec", ":", "if", "0", "<", "x", "<", "1", ":", "h", "+=", "logfn", "(", "x", ")", "return", "h" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
entropy
Compute the von-Neumann entropy of a quantum state. Args: state (array_like): a density matrix or state vector. Returns: float: The von-Neumann entropy S(rho).
qiskit/tools/qi/qi.py
def entropy(state): """ Compute the von-Neumann entropy of a quantum state. Args: state (array_like): a density matrix or state vector. Returns: float: The von-Neumann entropy S(rho). """ rho = np.array(state) if rho.ndim == 1: return 0 evals = np.maximum(np.linalg.eigvalsh(state), 0.) return shannon_entropy(evals, base=np.e)
def entropy(state): """ Compute the von-Neumann entropy of a quantum state. Args: state (array_like): a density matrix or state vector. Returns: float: The von-Neumann entropy S(rho). """ rho = np.array(state) if rho.ndim == 1: return 0 evals = np.maximum(np.linalg.eigvalsh(state), 0.) return shannon_entropy(evals, base=np.e)
[ "Compute", "the", "von", "-", "Neumann", "entropy", "of", "a", "quantum", "state", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qi/qi.py#L433-L448
[ "def", "entropy", "(", "state", ")", ":", "rho", "=", "np", ".", "array", "(", "state", ")", "if", "rho", ".", "ndim", "==", "1", ":", "return", "0", "evals", "=", "np", ".", "maximum", "(", "np", ".", "linalg", ".", "eigvalsh", "(", "state", ")", ",", "0.", ")", "return", "shannon_entropy", "(", "evals", ",", "base", "=", "np", ".", "e", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
mutual_information
Compute the mutual information of a bipartite state. Args: state (array_like): a bipartite state-vector or density-matrix. d0 (int): dimension of the first subsystem. d1 (int or None): dimension of the second subsystem. Returns: float: The mutual information S(rho_A) + S(rho_B) - S(rho_AB).
qiskit/tools/qi/qi.py
def mutual_information(state, d0, d1=None): """ Compute the mutual information of a bipartite state. Args: state (array_like): a bipartite state-vector or density-matrix. d0 (int): dimension of the first subsystem. d1 (int or None): dimension of the second subsystem. Returns: float: The mutual information S(rho_A) + S(rho_B) - S(rho_AB). """ if d1 is None: d1 = int(len(state) / d0) mi = entropy(partial_trace(state, [0], dimensions=[d0, d1])) mi += entropy(partial_trace(state, [1], dimensions=[d0, d1])) mi -= entropy(state) return mi
def mutual_information(state, d0, d1=None): """ Compute the mutual information of a bipartite state. Args: state (array_like): a bipartite state-vector or density-matrix. d0 (int): dimension of the first subsystem. d1 (int or None): dimension of the second subsystem. Returns: float: The mutual information S(rho_A) + S(rho_B) - S(rho_AB). """ if d1 is None: d1 = int(len(state) / d0) mi = entropy(partial_trace(state, [0], dimensions=[d0, d1])) mi += entropy(partial_trace(state, [1], dimensions=[d0, d1])) mi -= entropy(state) return mi
[ "Compute", "the", "mutual", "information", "of", "a", "bipartite", "state", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qi/qi.py#L451-L468
[ "def", "mutual_information", "(", "state", ",", "d0", ",", "d1", "=", "None", ")", ":", "if", "d1", "is", "None", ":", "d1", "=", "int", "(", "len", "(", "state", ")", "/", "d0", ")", "mi", "=", "entropy", "(", "partial_trace", "(", "state", ",", "[", "0", "]", ",", "dimensions", "=", "[", "d0", ",", "d1", "]", ")", ")", "mi", "+=", "entropy", "(", "partial_trace", "(", "state", ",", "[", "1", "]", ",", "dimensions", "=", "[", "d0", ",", "d1", "]", ")", ")", "mi", "-=", "entropy", "(", "state", ")", "return", "mi" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
entanglement_of_formation
Compute the entanglement of formation of quantum state. The input quantum state must be either a bipartite state vector, or a 2-qubit density matrix. Args: state (array_like): (N) array_like or (4,4) array_like, a bipartite quantum state. d0 (int): the dimension of the first subsystem. d1 (int or None): the dimension of the second subsystem. Returns: float: The entanglement of formation.
qiskit/tools/qi/qi.py
def entanglement_of_formation(state, d0, d1=None): """ Compute the entanglement of formation of quantum state. The input quantum state must be either a bipartite state vector, or a 2-qubit density matrix. Args: state (array_like): (N) array_like or (4,4) array_like, a bipartite quantum state. d0 (int): the dimension of the first subsystem. d1 (int or None): the dimension of the second subsystem. Returns: float: The entanglement of formation. """ state = np.array(state) if d1 is None: d1 = int(len(state) / d0) if state.ndim == 2 and len(state) == 4 and d0 == 2 and d1 == 2: return __eof_qubit(state) elif state.ndim == 1: # trace out largest dimension if d0 < d1: tr = [1] else: tr = [0] state = partial_trace(state, tr, dimensions=[d0, d1]) return entropy(state) else: print('Input must be a state-vector or 2-qubit density matrix.') return None
def entanglement_of_formation(state, d0, d1=None): """ Compute the entanglement of formation of quantum state. The input quantum state must be either a bipartite state vector, or a 2-qubit density matrix. Args: state (array_like): (N) array_like or (4,4) array_like, a bipartite quantum state. d0 (int): the dimension of the first subsystem. d1 (int or None): the dimension of the second subsystem. Returns: float: The entanglement of formation. """ state = np.array(state) if d1 is None: d1 = int(len(state) / d0) if state.ndim == 2 and len(state) == 4 and d0 == 2 and d1 == 2: return __eof_qubit(state) elif state.ndim == 1: # trace out largest dimension if d0 < d1: tr = [1] else: tr = [0] state = partial_trace(state, tr, dimensions=[d0, d1]) return entropy(state) else: print('Input must be a state-vector or 2-qubit density matrix.') return None
[ "Compute", "the", "entanglement", "of", "formation", "of", "quantum", "state", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qi/qi.py#L471-L504
[ "def", "entanglement_of_formation", "(", "state", ",", "d0", ",", "d1", "=", "None", ")", ":", "state", "=", "np", ".", "array", "(", "state", ")", "if", "d1", "is", "None", ":", "d1", "=", "int", "(", "len", "(", "state", ")", "/", "d0", ")", "if", "state", ".", "ndim", "==", "2", "and", "len", "(", "state", ")", "==", "4", "and", "d0", "==", "2", "and", "d1", "==", "2", ":", "return", "__eof_qubit", "(", "state", ")", "elif", "state", ".", "ndim", "==", "1", ":", "# trace out largest dimension", "if", "d0", "<", "d1", ":", "tr", "=", "[", "1", "]", "else", ":", "tr", "=", "[", "0", "]", "state", "=", "partial_trace", "(", "state", ",", "tr", ",", "dimensions", "=", "[", "d0", ",", "d1", "]", ")", "return", "entropy", "(", "state", ")", "else", ":", "print", "(", "'Input must be a state-vector or 2-qubit density matrix.'", ")", "return", "None" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
__eof_qubit
Compute the Entanglement of Formation of a 2-qubit density matrix. Args: rho ((array_like): (4,4) array_like, input density matrix. Returns: float: The entanglement of formation.
qiskit/tools/qi/qi.py
def __eof_qubit(rho): """ Compute the Entanglement of Formation of a 2-qubit density matrix. Args: rho ((array_like): (4,4) array_like, input density matrix. Returns: float: The entanglement of formation. """ c = concurrence(rho) c = 0.5 + 0.5 * np.sqrt(1 - c * c) return shannon_entropy([c, 1 - c])
def __eof_qubit(rho): """ Compute the Entanglement of Formation of a 2-qubit density matrix. Args: rho ((array_like): (4,4) array_like, input density matrix. Returns: float: The entanglement of formation. """ c = concurrence(rho) c = 0.5 + 0.5 * np.sqrt(1 - c * c) return shannon_entropy([c, 1 - c])
[ "Compute", "the", "Entanglement", "of", "Formation", "of", "a", "2", "-", "qubit", "density", "matrix", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qi/qi.py#L507-L519
[ "def", "__eof_qubit", "(", "rho", ")", ":", "c", "=", "concurrence", "(", "rho", ")", "c", "=", "0.5", "+", "0.5", "*", "np", ".", "sqrt", "(", "1", "-", "c", "*", "c", ")", "return", "shannon_entropy", "(", "[", "c", ",", "1", "-", "c", "]", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
union
Create a union (and also shift if desired) of all input `Schedule`s. Args: *schedules: Schedules to take the union of name: Name of the new schedule. Defaults to first element of `schedules`
qiskit/pulse/ops.py
def union(*schedules: List[Union[ScheduleComponent, Tuple[int, ScheduleComponent]]], name: str = None) -> Schedule: """Create a union (and also shift if desired) of all input `Schedule`s. Args: *schedules: Schedules to take the union of name: Name of the new schedule. Defaults to first element of `schedules` """ if name is None and schedules: sched = schedules[0] if isinstance(sched, (list, tuple)): name = sched[1].name else: name = sched.name return Schedule(*schedules, name=name)
def union(*schedules: List[Union[ScheduleComponent, Tuple[int, ScheduleComponent]]], name: str = None) -> Schedule: """Create a union (and also shift if desired) of all input `Schedule`s. Args: *schedules: Schedules to take the union of name: Name of the new schedule. Defaults to first element of `schedules` """ if name is None and schedules: sched = schedules[0] if isinstance(sched, (list, tuple)): name = sched[1].name else: name = sched.name return Schedule(*schedules, name=name)
[ "Create", "a", "union", "(", "and", "also", "shift", "if", "desired", ")", "of", "all", "input", "Schedule", "s", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/ops.py#L22-L36
[ "def", "union", "(", "*", "schedules", ":", "List", "[", "Union", "[", "ScheduleComponent", ",", "Tuple", "[", "int", ",", "ScheduleComponent", "]", "]", "]", ",", "name", ":", "str", "=", "None", ")", "->", "Schedule", ":", "if", "name", "is", "None", "and", "schedules", ":", "sched", "=", "schedules", "[", "0", "]", "if", "isinstance", "(", "sched", ",", "(", "list", ",", "tuple", ")", ")", ":", "name", "=", "sched", "[", "1", "]", ".", "name", "else", ":", "name", "=", "sched", ".", "name", "return", "Schedule", "(", "*", "schedules", ",", "name", "=", "name", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
flatten
Create a flattened schedule. Args: schedule: Schedules to flatten name: Name of the new schedule. Defaults to first element of `schedules`
qiskit/pulse/ops.py
def flatten(schedule: ScheduleComponent, name: str = None) -> Schedule: """Create a flattened schedule. Args: schedule: Schedules to flatten name: Name of the new schedule. Defaults to first element of `schedules` """ if name is None: name = schedule.name return Schedule(*schedule.instructions, name=name)
def flatten(schedule: ScheduleComponent, name: str = None) -> Schedule: """Create a flattened schedule. Args: schedule: Schedules to flatten name: Name of the new schedule. Defaults to first element of `schedules` """ if name is None: name = schedule.name return Schedule(*schedule.instructions, name=name)
[ "Create", "a", "flattened", "schedule", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/ops.py#L41-L51
[ "def", "flatten", "(", "schedule", ":", "ScheduleComponent", ",", "name", ":", "str", "=", "None", ")", "->", "Schedule", ":", "if", "name", "is", "None", ":", "name", "=", "schedule", ".", "name", "return", "Schedule", "(", "*", "schedule", ".", "instructions", ",", "name", "=", "name", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
shift
Return schedule shifted by `time`. Args: schedule: The schedule to shift time: The time to shift by name: Name of shifted schedule. Defaults to name of `schedule`
qiskit/pulse/ops.py
def shift(schedule: ScheduleComponent, time: int, name: str = None) -> Schedule: """Return schedule shifted by `time`. Args: schedule: The schedule to shift time: The time to shift by name: Name of shifted schedule. Defaults to name of `schedule` """ if name is None: name = schedule.name return union((time, schedule), name=name)
def shift(schedule: ScheduleComponent, time: int, name: str = None) -> Schedule: """Return schedule shifted by `time`. Args: schedule: The schedule to shift time: The time to shift by name: Name of shifted schedule. Defaults to name of `schedule` """ if name is None: name = schedule.name return union((time, schedule), name=name)
[ "Return", "schedule", "shifted", "by", "time", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/ops.py#L54-L64
[ "def", "shift", "(", "schedule", ":", "ScheduleComponent", ",", "time", ":", "int", ",", "name", ":", "str", "=", "None", ")", "->", "Schedule", ":", "if", "name", "is", "None", ":", "name", "=", "schedule", ".", "name", "return", "union", "(", "(", "time", ",", "schedule", ")", ",", "name", "=", "name", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
insert
Return a new schedule with the `child` schedule inserted into the `parent` at `start_time`. Args: parent: Schedule to be inserted into time: Time to be inserted defined with respect to `parent` child: Schedule to insert name: Name of the new schedule. Defaults to name of parent
qiskit/pulse/ops.py
def insert(parent: ScheduleComponent, time: int, child: ScheduleComponent, name: str = None) -> Schedule: """Return a new schedule with the `child` schedule inserted into the `parent` at `start_time`. Args: parent: Schedule to be inserted into time: Time to be inserted defined with respect to `parent` child: Schedule to insert name: Name of the new schedule. Defaults to name of parent """ return union(parent, (time, child), name=name)
def insert(parent: ScheduleComponent, time: int, child: ScheduleComponent, name: str = None) -> Schedule: """Return a new schedule with the `child` schedule inserted into the `parent` at `start_time`. Args: parent: Schedule to be inserted into time: Time to be inserted defined with respect to `parent` child: Schedule to insert name: Name of the new schedule. Defaults to name of parent """ return union(parent, (time, child), name=name)
[ "Return", "a", "new", "schedule", "with", "the", "child", "schedule", "inserted", "into", "the", "parent", "at", "start_time", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/ops.py#L67-L77
[ "def", "insert", "(", "parent", ":", "ScheduleComponent", ",", "time", ":", "int", ",", "child", ":", "ScheduleComponent", ",", "name", ":", "str", "=", "None", ")", "->", "Schedule", ":", "return", "union", "(", "parent", ",", "(", "time", ",", "child", ")", ",", "name", "=", "name", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
append
r"""Return a new schedule with by appending `child` to `parent` at the last time of the `parent` schedule's channels over the intersection of the parent and child schedule's channels. $t = \textrm{max}({x.stop\_time |x \in parent.channels \cap child.channels})$ Args: parent: The schedule to be inserted into child: The schedule to insert name: Name of the new schedule. Defaults to name of parent
qiskit/pulse/ops.py
def append(parent: ScheduleComponent, child: ScheduleComponent, name: str = None) -> Schedule: r"""Return a new schedule with by appending `child` to `parent` at the last time of the `parent` schedule's channels over the intersection of the parent and child schedule's channels. $t = \textrm{max}({x.stop\_time |x \in parent.channels \cap child.channels})$ Args: parent: The schedule to be inserted into child: The schedule to insert name: Name of the new schedule. Defaults to name of parent """ common_channels = set(parent.channels) & set(child.channels) insertion_time = parent.ch_stop_time(*common_channels) return insert(parent, insertion_time, child, name=name)
def append(parent: ScheduleComponent, child: ScheduleComponent, name: str = None) -> Schedule: r"""Return a new schedule with by appending `child` to `parent` at the last time of the `parent` schedule's channels over the intersection of the parent and child schedule's channels. $t = \textrm{max}({x.stop\_time |x \in parent.channels \cap child.channels})$ Args: parent: The schedule to be inserted into child: The schedule to insert name: Name of the new schedule. Defaults to name of parent """ common_channels = set(parent.channels) & set(child.channels) insertion_time = parent.ch_stop_time(*common_channels) return insert(parent, insertion_time, child, name=name)
[ "r", "Return", "a", "new", "schedule", "with", "by", "appending", "child", "to", "parent", "at", "the", "last", "time", "of", "the", "parent", "schedule", "s", "channels", "over", "the", "intersection", "of", "the", "parent", "and", "child", "schedule", "s", "channels", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/ops.py#L80-L95
[ "def", "append", "(", "parent", ":", "ScheduleComponent", ",", "child", ":", "ScheduleComponent", ",", "name", ":", "str", "=", "None", ")", "->", "Schedule", ":", "common_channels", "=", "set", "(", "parent", ".", "channels", ")", "&", "set", "(", "child", ".", "channels", ")", "insertion_time", "=", "parent", ".", "ch_stop_time", "(", "*", "common_channels", ")", "return", "insert", "(", "parent", ",", "insertion_time", ",", "child", ",", "name", "=", "name", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
u3
Apply u3 to q.
qiskit/extensions/standard/u3.py
def u3(self, theta, phi, lam, q): """Apply u3 to q.""" return self.append(U3Gate(theta, phi, lam), [q], [])
def u3(self, theta, phi, lam, q): """Apply u3 to q.""" return self.append(U3Gate(theta, phi, lam), [q], [])
[ "Apply", "u3", "to", "q", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/standard/u3.py#L62-L64
[ "def", "u3", "(", "self", ",", "theta", ",", "phi", ",", "lam", ",", "q", ")", ":", "return", "self", ".", "append", "(", "U3Gate", "(", "theta", ",", "phi", ",", "lam", ")", ",", "[", "q", "]", ",", "[", "]", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BaseBackend.status
Return backend status. Returns: BackendStatus: the status of the backend.
qiskit/providers/basebackend.py
def status(self): """Return backend status. Returns: BackendStatus: the status of the backend. """ return BackendStatus(backend_name=self.name(), backend_version=__version__, operational=True, pending_jobs=0, status_msg='')
def status(self): """Return backend status. Returns: BackendStatus: the status of the backend. """ return BackendStatus(backend_name=self.name(), backend_version=__version__, operational=True, pending_jobs=0, status_msg='')
[ "Return", "backend", "status", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basebackend.py#L71-L81
[ "def", "status", "(", "self", ")", ":", "return", "BackendStatus", "(", "backend_name", "=", "self", ".", "name", "(", ")", ",", "backend_version", "=", "__version__", ",", "operational", "=", "True", ",", "pending_jobs", "=", "0", ",", "status_msg", "=", "''", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BaseProgressBar.start
Start the progress bar. Parameters: iterations (int): Number of iterations.
qiskit/tools/events/progressbar.py
def start(self, iterations): """Start the progress bar. Parameters: iterations (int): Number of iterations. """ self.touched = True self.iter = int(iterations) self.t_start = time.time()
def start(self, iterations): """Start the progress bar. Parameters: iterations (int): Number of iterations. """ self.touched = True self.iter = int(iterations) self.t_start = time.time()
[ "Start", "the", "progress", "bar", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/events/progressbar.py#L60-L68
[ "def", "start", "(", "self", ",", "iterations", ")", ":", "self", ".", "touched", "=", "True", "self", ".", "iter", "=", "int", "(", "iterations", ")", "self", ".", "t_start", "=", "time", ".", "time", "(", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BaseProgressBar.time_remaining_est
Estimate the remaining time left. Parameters: completed_iter (int): Number of iterations completed. Returns: est_time: Estimated time remaining.
qiskit/tools/events/progressbar.py
def time_remaining_est(self, completed_iter): """Estimate the remaining time left. Parameters: completed_iter (int): Number of iterations completed. Returns: est_time: Estimated time remaining. """ if completed_iter: t_r_est = (time.time() - self.t_start) / \ completed_iter*(self.iter-completed_iter) else: t_r_est = 0 date_time = datetime.datetime(1, 1, 1) + datetime.timedelta(seconds=t_r_est) time_string = "%02d:%02d:%02d:%02d" % \ (date_time.day - 1, date_time.hour, date_time.minute, date_time.second) return time_string
def time_remaining_est(self, completed_iter): """Estimate the remaining time left. Parameters: completed_iter (int): Number of iterations completed. Returns: est_time: Estimated time remaining. """ if completed_iter: t_r_est = (time.time() - self.t_start) / \ completed_iter*(self.iter-completed_iter) else: t_r_est = 0 date_time = datetime.datetime(1, 1, 1) + datetime.timedelta(seconds=t_r_est) time_string = "%02d:%02d:%02d:%02d" % \ (date_time.day - 1, date_time.hour, date_time.minute, date_time.second) return time_string
[ "Estimate", "the", "remaining", "time", "left", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/events/progressbar.py#L83-L101
[ "def", "time_remaining_est", "(", "self", ",", "completed_iter", ")", ":", "if", "completed_iter", ":", "t_r_est", "=", "(", "time", ".", "time", "(", ")", "-", "self", ".", "t_start", ")", "/", "completed_iter", "*", "(", "self", ".", "iter", "-", "completed_iter", ")", "else", ":", "t_r_est", "=", "0", "date_time", "=", "datetime", ".", "datetime", "(", "1", ",", "1", ",", "1", ")", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "t_r_est", ")", "time_string", "=", "\"%02d:%02d:%02d:%02d\"", "%", "(", "date_time", ".", "day", "-", "1", ",", "date_time", ".", "hour", ",", "date_time", ".", "minute", ",", "date_time", ".", "second", ")", "return", "time_string" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
CommutativeCancellation.run
Run the CommutativeCancellation pass on a dag Args: dag (DAGCircuit): the DAG to be optimized. Returns: DAGCircuit: the optimized DAG. Raises: TranspilerError: when the 1 qubit rotation gates are not found
qiskit/transpiler/passes/commutative_cancellation.py
def run(self, dag): """Run the CommutativeCancellation pass on a dag Args: dag (DAGCircuit): the DAG to be optimized. Returns: DAGCircuit: the optimized DAG. Raises: TranspilerError: when the 1 qubit rotation gates are not found """ q_gate_list = ['cx', 'cy', 'cz', 'h', 'x', 'y', 'z'] # Gate sets to be cancelled cancellation_sets = defaultdict(lambda: []) for wire in dag.wires: wire_name = "{0}[{1}]".format(str(wire[0].name), str(wire[1])) wire_commutation_set = self.property_set['commutation_set'][wire_name] for com_set_idx, com_set in enumerate(wire_commutation_set): if com_set[0].type in ['in', 'out']: continue for node in com_set: num_qargs = len(node.qargs) if num_qargs == 1 and node.name in q_gate_list: cancellation_sets[(node.name, wire_name, com_set_idx)].append(node) if num_qargs == 1 and node.name in ['u1', 'rz', 't', 's']: cancellation_sets[('z_rotation', wire_name, com_set_idx)].append(node) elif num_qargs == 2 and node.qargs[0] == wire: second_op_name = "{0}[{1}]".format(str(node.qargs[1][0].name), str(node.qargs[1][1])) q2_key = (node.name, wire_name, second_op_name, self.property_set['commutation_set'][(node, second_op_name)]) cancellation_sets[q2_key].append(node) for cancel_set_key in cancellation_sets: set_len = len(cancellation_sets[cancel_set_key]) if ((set_len) > 1 and cancel_set_key[0] in q_gate_list): gates_to_cancel = cancellation_sets[cancel_set_key] for c_node in gates_to_cancel[:(set_len // 2) * 2]: dag.remove_op_node(c_node) elif((set_len) > 1 and cancel_set_key[0] == 'z_rotation'): run = cancellation_sets[cancel_set_key] run_qarg = run[0].qargs[0] total_angle = 0.0 # lambda for current_node in run: if (current_node.condition is not None or len(current_node.qargs) != 1 or current_node.qargs[0] != run_qarg): raise TranspilerError("internal error") if current_node.name in ['u1', 'rz']: current_angle = float(current_node.op.params[0]) elif current_node.name == 't': current_angle = sympy.pi / 4 elif current_node.name == 's': current_angle = sympy.pi / 2 # Compose gates total_angle = current_angle + total_angle # Replace the data of the first node in the run new_op = U1Gate(total_angle) new_qarg = (QuantumRegister(1, 'q'), 0) new_dag = DAGCircuit() new_dag.add_qreg(new_qarg[0]) new_dag.apply_operation_back(new_op, [new_qarg]) dag.substitute_node_with_dag(run[0], new_dag) # Delete the other nodes in the run for current_node in run[1:]: dag.remove_op_node(current_node) return dag
def run(self, dag): """Run the CommutativeCancellation pass on a dag Args: dag (DAGCircuit): the DAG to be optimized. Returns: DAGCircuit: the optimized DAG. Raises: TranspilerError: when the 1 qubit rotation gates are not found """ q_gate_list = ['cx', 'cy', 'cz', 'h', 'x', 'y', 'z'] # Gate sets to be cancelled cancellation_sets = defaultdict(lambda: []) for wire in dag.wires: wire_name = "{0}[{1}]".format(str(wire[0].name), str(wire[1])) wire_commutation_set = self.property_set['commutation_set'][wire_name] for com_set_idx, com_set in enumerate(wire_commutation_set): if com_set[0].type in ['in', 'out']: continue for node in com_set: num_qargs = len(node.qargs) if num_qargs == 1 and node.name in q_gate_list: cancellation_sets[(node.name, wire_name, com_set_idx)].append(node) if num_qargs == 1 and node.name in ['u1', 'rz', 't', 's']: cancellation_sets[('z_rotation', wire_name, com_set_idx)].append(node) elif num_qargs == 2 and node.qargs[0] == wire: second_op_name = "{0}[{1}]".format(str(node.qargs[1][0].name), str(node.qargs[1][1])) q2_key = (node.name, wire_name, second_op_name, self.property_set['commutation_set'][(node, second_op_name)]) cancellation_sets[q2_key].append(node) for cancel_set_key in cancellation_sets: set_len = len(cancellation_sets[cancel_set_key]) if ((set_len) > 1 and cancel_set_key[0] in q_gate_list): gates_to_cancel = cancellation_sets[cancel_set_key] for c_node in gates_to_cancel[:(set_len // 2) * 2]: dag.remove_op_node(c_node) elif((set_len) > 1 and cancel_set_key[0] == 'z_rotation'): run = cancellation_sets[cancel_set_key] run_qarg = run[0].qargs[0] total_angle = 0.0 # lambda for current_node in run: if (current_node.condition is not None or len(current_node.qargs) != 1 or current_node.qargs[0] != run_qarg): raise TranspilerError("internal error") if current_node.name in ['u1', 'rz']: current_angle = float(current_node.op.params[0]) elif current_node.name == 't': current_angle = sympy.pi / 4 elif current_node.name == 's': current_angle = sympy.pi / 2 # Compose gates total_angle = current_angle + total_angle # Replace the data of the first node in the run new_op = U1Gate(total_angle) new_qarg = (QuantumRegister(1, 'q'), 0) new_dag = DAGCircuit() new_dag.add_qreg(new_qarg[0]) new_dag.apply_operation_back(new_op, [new_qarg]) dag.substitute_node_with_dag(run[0], new_dag) # Delete the other nodes in the run for current_node in run[1:]: dag.remove_op_node(current_node) return dag
[ "Run", "the", "CommutativeCancellation", "pass", "on", "a", "dag" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/commutative_cancellation.py#L33-L110
[ "def", "run", "(", "self", ",", "dag", ")", ":", "q_gate_list", "=", "[", "'cx'", ",", "'cy'", ",", "'cz'", ",", "'h'", ",", "'x'", ",", "'y'", ",", "'z'", "]", "# Gate sets to be cancelled", "cancellation_sets", "=", "defaultdict", "(", "lambda", ":", "[", "]", ")", "for", "wire", "in", "dag", ".", "wires", ":", "wire_name", "=", "\"{0}[{1}]\"", ".", "format", "(", "str", "(", "wire", "[", "0", "]", ".", "name", ")", ",", "str", "(", "wire", "[", "1", "]", ")", ")", "wire_commutation_set", "=", "self", ".", "property_set", "[", "'commutation_set'", "]", "[", "wire_name", "]", "for", "com_set_idx", ",", "com_set", "in", "enumerate", "(", "wire_commutation_set", ")", ":", "if", "com_set", "[", "0", "]", ".", "type", "in", "[", "'in'", ",", "'out'", "]", ":", "continue", "for", "node", "in", "com_set", ":", "num_qargs", "=", "len", "(", "node", ".", "qargs", ")", "if", "num_qargs", "==", "1", "and", "node", ".", "name", "in", "q_gate_list", ":", "cancellation_sets", "[", "(", "node", ".", "name", ",", "wire_name", ",", "com_set_idx", ")", "]", ".", "append", "(", "node", ")", "if", "num_qargs", "==", "1", "and", "node", ".", "name", "in", "[", "'u1'", ",", "'rz'", ",", "'t'", ",", "'s'", "]", ":", "cancellation_sets", "[", "(", "'z_rotation'", ",", "wire_name", ",", "com_set_idx", ")", "]", ".", "append", "(", "node", ")", "elif", "num_qargs", "==", "2", "and", "node", ".", "qargs", "[", "0", "]", "==", "wire", ":", "second_op_name", "=", "\"{0}[{1}]\"", ".", "format", "(", "str", "(", "node", ".", "qargs", "[", "1", "]", "[", "0", "]", ".", "name", ")", ",", "str", "(", "node", ".", "qargs", "[", "1", "]", "[", "1", "]", ")", ")", "q2_key", "=", "(", "node", ".", "name", ",", "wire_name", ",", "second_op_name", ",", "self", ".", "property_set", "[", "'commutation_set'", "]", "[", "(", "node", ",", "second_op_name", ")", "]", ")", "cancellation_sets", "[", "q2_key", "]", ".", "append", "(", "node", ")", "for", "cancel_set_key", "in", "cancellation_sets", ":", "set_len", "=", "len", "(", "cancellation_sets", "[", "cancel_set_key", "]", ")", "if", "(", "(", "set_len", ")", ">", "1", "and", "cancel_set_key", "[", "0", "]", "in", "q_gate_list", ")", ":", "gates_to_cancel", "=", "cancellation_sets", "[", "cancel_set_key", "]", "for", "c_node", "in", "gates_to_cancel", "[", ":", "(", "set_len", "//", "2", ")", "*", "2", "]", ":", "dag", ".", "remove_op_node", "(", "c_node", ")", "elif", "(", "(", "set_len", ")", ">", "1", "and", "cancel_set_key", "[", "0", "]", "==", "'z_rotation'", ")", ":", "run", "=", "cancellation_sets", "[", "cancel_set_key", "]", "run_qarg", "=", "run", "[", "0", "]", ".", "qargs", "[", "0", "]", "total_angle", "=", "0.0", "# lambda", "for", "current_node", "in", "run", ":", "if", "(", "current_node", ".", "condition", "is", "not", "None", "or", "len", "(", "current_node", ".", "qargs", ")", "!=", "1", "or", "current_node", ".", "qargs", "[", "0", "]", "!=", "run_qarg", ")", ":", "raise", "TranspilerError", "(", "\"internal error\"", ")", "if", "current_node", ".", "name", "in", "[", "'u1'", ",", "'rz'", "]", ":", "current_angle", "=", "float", "(", "current_node", ".", "op", ".", "params", "[", "0", "]", ")", "elif", "current_node", ".", "name", "==", "'t'", ":", "current_angle", "=", "sympy", ".", "pi", "/", "4", "elif", "current_node", ".", "name", "==", "'s'", ":", "current_angle", "=", "sympy", ".", "pi", "/", "2", "# Compose gates", "total_angle", "=", "current_angle", "+", "total_angle", "# Replace the data of the first node in the run", "new_op", "=", "U1Gate", "(", "total_angle", ")", "new_qarg", "=", "(", "QuantumRegister", "(", "1", ",", "'q'", ")", ",", "0", ")", "new_dag", "=", "DAGCircuit", "(", ")", "new_dag", ".", "add_qreg", "(", "new_qarg", "[", "0", "]", ")", "new_dag", ".", "apply_operation_back", "(", "new_op", ",", "[", "new_qarg", "]", ")", "dag", ".", "substitute_node_with_dag", "(", "run", "[", "0", "]", ",", "new_dag", ")", "# Delete the other nodes in the run", "for", "current_node", "in", "run", "[", "1", ":", "]", ":", "dag", ".", "remove_op_node", "(", "current_node", ")", "return", "dag" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_experiments_to_circuits
Return a list of QuantumCircuit object(s) from a qobj Args: qobj (Qobj): The Qobj object to convert to QuantumCircuits Returns: list: A list of QuantumCircuit objects from the qobj
qiskit/compiler/disassembler.py
def _experiments_to_circuits(qobj): """Return a list of QuantumCircuit object(s) from a qobj Args: qobj (Qobj): The Qobj object to convert to QuantumCircuits Returns: list: A list of QuantumCircuit objects from the qobj """ if qobj.experiments: circuits = [] for x in qobj.experiments: quantum_registers = [QuantumRegister(i[1], name=i[0]) for i in x.header.qreg_sizes] classical_registers = [ClassicalRegister(i[1], name=i[0]) for i in x.header.creg_sizes] circuit = QuantumCircuit(*quantum_registers, *classical_registers, name=x.header.name) qreg_dict = {} creg_dict = {} for reg in quantum_registers: qreg_dict[reg.name] = reg for reg in classical_registers: creg_dict[reg.name] = reg for i in x.instructions: instr_method = getattr(circuit, i.name) qubits = [] try: for qubit in i.qubits: qubit_label = x.header.qubit_labels[qubit] qubits.append( qreg_dict[qubit_label[0]][qubit_label[1]]) except Exception: # pylint: disable=broad-except pass clbits = [] try: for clbit in i.memory: clbit_label = x.header.clbit_labels[clbit] clbits.append( creg_dict[clbit_label[0]][clbit_label[1]]) except Exception: # pylint: disable=broad-except pass params = [] try: params = i.params except Exception: # pylint: disable=broad-except pass if i.name in ['snapshot']: instr_method( i.label, snapshot_type=i.snapshot_type, qubits=qubits, params=params) elif i.name == 'initialize': instr_method(params, qubits) else: instr_method(*params, *qubits, *clbits) circuits.append(circuit) return circuits return None
def _experiments_to_circuits(qobj): """Return a list of QuantumCircuit object(s) from a qobj Args: qobj (Qobj): The Qobj object to convert to QuantumCircuits Returns: list: A list of QuantumCircuit objects from the qobj """ if qobj.experiments: circuits = [] for x in qobj.experiments: quantum_registers = [QuantumRegister(i[1], name=i[0]) for i in x.header.qreg_sizes] classical_registers = [ClassicalRegister(i[1], name=i[0]) for i in x.header.creg_sizes] circuit = QuantumCircuit(*quantum_registers, *classical_registers, name=x.header.name) qreg_dict = {} creg_dict = {} for reg in quantum_registers: qreg_dict[reg.name] = reg for reg in classical_registers: creg_dict[reg.name] = reg for i in x.instructions: instr_method = getattr(circuit, i.name) qubits = [] try: for qubit in i.qubits: qubit_label = x.header.qubit_labels[qubit] qubits.append( qreg_dict[qubit_label[0]][qubit_label[1]]) except Exception: # pylint: disable=broad-except pass clbits = [] try: for clbit in i.memory: clbit_label = x.header.clbit_labels[clbit] clbits.append( creg_dict[clbit_label[0]][clbit_label[1]]) except Exception: # pylint: disable=broad-except pass params = [] try: params = i.params except Exception: # pylint: disable=broad-except pass if i.name in ['snapshot']: instr_method( i.label, snapshot_type=i.snapshot_type, qubits=qubits, params=params) elif i.name == 'initialize': instr_method(params, qubits) else: instr_method(*params, *qubits, *clbits) circuits.append(circuit) return circuits return None
[ "Return", "a", "list", "of", "QuantumCircuit", "object", "(", "s", ")", "from", "a", "qobj" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/compiler/disassembler.py#L18-L78
[ "def", "_experiments_to_circuits", "(", "qobj", ")", ":", "if", "qobj", ".", "experiments", ":", "circuits", "=", "[", "]", "for", "x", "in", "qobj", ".", "experiments", ":", "quantum_registers", "=", "[", "QuantumRegister", "(", "i", "[", "1", "]", ",", "name", "=", "i", "[", "0", "]", ")", "for", "i", "in", "x", ".", "header", ".", "qreg_sizes", "]", "classical_registers", "=", "[", "ClassicalRegister", "(", "i", "[", "1", "]", ",", "name", "=", "i", "[", "0", "]", ")", "for", "i", "in", "x", ".", "header", ".", "creg_sizes", "]", "circuit", "=", "QuantumCircuit", "(", "*", "quantum_registers", ",", "*", "classical_registers", ",", "name", "=", "x", ".", "header", ".", "name", ")", "qreg_dict", "=", "{", "}", "creg_dict", "=", "{", "}", "for", "reg", "in", "quantum_registers", ":", "qreg_dict", "[", "reg", ".", "name", "]", "=", "reg", "for", "reg", "in", "classical_registers", ":", "creg_dict", "[", "reg", ".", "name", "]", "=", "reg", "for", "i", "in", "x", ".", "instructions", ":", "instr_method", "=", "getattr", "(", "circuit", ",", "i", ".", "name", ")", "qubits", "=", "[", "]", "try", ":", "for", "qubit", "in", "i", ".", "qubits", ":", "qubit_label", "=", "x", ".", "header", ".", "qubit_labels", "[", "qubit", "]", "qubits", ".", "append", "(", "qreg_dict", "[", "qubit_label", "[", "0", "]", "]", "[", "qubit_label", "[", "1", "]", "]", ")", "except", "Exception", ":", "# pylint: disable=broad-except", "pass", "clbits", "=", "[", "]", "try", ":", "for", "clbit", "in", "i", ".", "memory", ":", "clbit_label", "=", "x", ".", "header", ".", "clbit_labels", "[", "clbit", "]", "clbits", ".", "append", "(", "creg_dict", "[", "clbit_label", "[", "0", "]", "]", "[", "clbit_label", "[", "1", "]", "]", ")", "except", "Exception", ":", "# pylint: disable=broad-except", "pass", "params", "=", "[", "]", "try", ":", "params", "=", "i", ".", "params", "except", "Exception", ":", "# pylint: disable=broad-except", "pass", "if", "i", ".", "name", "in", "[", "'snapshot'", "]", ":", "instr_method", "(", "i", ".", "label", ",", "snapshot_type", "=", "i", ".", "snapshot_type", ",", "qubits", "=", "qubits", ",", "params", "=", "params", ")", "elif", "i", ".", "name", "==", "'initialize'", ":", "instr_method", "(", "params", ",", "qubits", ")", "else", ":", "instr_method", "(", "*", "params", ",", "*", "qubits", ",", "*", "clbits", ")", "circuits", ".", "append", "(", "circuit", ")", "return", "circuits", "return", "None" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
disassemble
Dissasemble a qobj and return the circuits, run_config, and user header Args: qobj (Qobj): The input qobj object to dissasemble Returns: circuits (list): A list of quantum circuits run_config (dict): The dist of the run config user_qobj_header (dict): The dict of any user headers in the qobj
qiskit/compiler/disassembler.py
def disassemble(qobj): """Dissasemble a qobj and return the circuits, run_config, and user header Args: qobj (Qobj): The input qobj object to dissasemble Returns: circuits (list): A list of quantum circuits run_config (dict): The dist of the run config user_qobj_header (dict): The dict of any user headers in the qobj """ run_config = qobj.config.to_dict() user_qobj_header = qobj.header.to_dict() circuits = _experiments_to_circuits(qobj) return circuits, run_config, user_qobj_header
def disassemble(qobj): """Dissasemble a qobj and return the circuits, run_config, and user header Args: qobj (Qobj): The input qobj object to dissasemble Returns: circuits (list): A list of quantum circuits run_config (dict): The dist of the run config user_qobj_header (dict): The dict of any user headers in the qobj """ run_config = qobj.config.to_dict() user_qobj_header = qobj.header.to_dict() circuits = _experiments_to_circuits(qobj) return circuits, run_config, user_qobj_header
[ "Dissasemble", "a", "qobj", "and", "return", "the", "circuits", "run_config", "and", "user", "header" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/compiler/disassembler.py#L81-L96
[ "def", "disassemble", "(", "qobj", ")", ":", "run_config", "=", "qobj", ".", "config", ".", "to_dict", "(", ")", "user_qobj_header", "=", "qobj", ".", "header", ".", "to_dict", "(", ")", "circuits", "=", "_experiments_to_circuits", "(", "qobj", ")", "return", "circuits", ",", "run_config", ",", "user_qobj_header" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
hamming_distance
Calculate the Hamming distance between two bit strings Args: str1 (str): First string. str2 (str): Second string. Returns: int: Distance between strings. Raises: VisualizationError: Strings not same length
qiskit/visualization/counts_visualization.py
def hamming_distance(str1, str2): """Calculate the Hamming distance between two bit strings Args: str1 (str): First string. str2 (str): Second string. Returns: int: Distance between strings. Raises: VisualizationError: Strings not same length """ if len(str1) != len(str2): raise VisualizationError('Strings not same length.') return sum(s1 != s2 for s1, s2 in zip(str1, str2))
def hamming_distance(str1, str2): """Calculate the Hamming distance between two bit strings Args: str1 (str): First string. str2 (str): Second string. Returns: int: Distance between strings. Raises: VisualizationError: Strings not same length """ if len(str1) != len(str2): raise VisualizationError('Strings not same length.') return sum(s1 != s2 for s1, s2 in zip(str1, str2))
[ "Calculate", "the", "Hamming", "distance", "between", "two", "bit", "strings" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/counts_visualization.py#L25-L38
[ "def", "hamming_distance", "(", "str1", ",", "str2", ")", ":", "if", "len", "(", "str1", ")", "!=", "len", "(", "str2", ")", ":", "raise", "VisualizationError", "(", "'Strings not same length.'", ")", "return", "sum", "(", "s1", "!=", "s2", "for", "s1", ",", "s2", "in", "zip", "(", "str1", ",", "str2", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
plot_histogram
Plot a histogram of data. Args: data (list or dict): This is either a list of dictionaries or a single dict containing the values to represent (ex {'001': 130}) figsize (tuple): Figure size in inches. color (list or str): String or list of strings for histogram bar colors. number_to_keep (int): The number of terms to plot and rest is made into a single bar called 'rest'. sort (string): Could be 'asc', 'desc', or 'hamming'. target_string (str): Target string if 'sort' is a distance measure. legend(list): A list of strings to use for labels of the data. The number of entries must match the length of data (if data is a list or 1 if it's a dict) bar_labels (bool): Label each bar in histogram with probability value. title (str): A string to use for the plot title Returns: matplotlib.Figure: A figure for the rendered histogram. Raises: ImportError: Matplotlib not available. VisualizationError: When legend is provided and the length doesn't match the input data.
qiskit/visualization/counts_visualization.py
def plot_histogram(data, figsize=(7, 5), color=None, number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, title=None): """Plot a histogram of data. Args: data (list or dict): This is either a list of dictionaries or a single dict containing the values to represent (ex {'001': 130}) figsize (tuple): Figure size in inches. color (list or str): String or list of strings for histogram bar colors. number_to_keep (int): The number of terms to plot and rest is made into a single bar called 'rest'. sort (string): Could be 'asc', 'desc', or 'hamming'. target_string (str): Target string if 'sort' is a distance measure. legend(list): A list of strings to use for labels of the data. The number of entries must match the length of data (if data is a list or 1 if it's a dict) bar_labels (bool): Label each bar in histogram with probability value. title (str): A string to use for the plot title Returns: matplotlib.Figure: A figure for the rendered histogram. Raises: ImportError: Matplotlib not available. VisualizationError: When legend is provided and the length doesn't match the input data. """ if not HAS_MATPLOTLIB: raise ImportError('Must have Matplotlib installed.') if sort not in VALID_SORTS: raise VisualizationError("Value of sort option, %s, isn't a " "valid choice. Must be 'asc', " "'desc', or 'hamming'") elif sort in DIST_MEAS.keys() and target_string is None: err_msg = 'Must define target_string when using distance measure.' raise VisualizationError(err_msg) if isinstance(data, dict): data = [data] if legend and len(legend) != len(data): raise VisualizationError("Length of legendL (%s) doesn't match " "number of input executions: %s" % (len(legend), len(data))) fig, ax = plt.subplots(figsize=figsize) labels = list(sorted( functools.reduce(lambda x, y: x.union(y.keys()), data, set()))) if number_to_keep is not None: labels.append('rest') if sort in DIST_MEAS.keys(): dist = [] for item in labels: dist.append(DIST_MEAS[sort](item, target_string)) labels = [list(x) for x in zip(*sorted(zip(dist, labels), key=lambda pair: pair[0]))][1] labels_dict = OrderedDict() # Set bar colors if color is None: color = ['#648fff', '#dc267f', '#785ef0', '#ffb000', '#fe6100'] elif isinstance(color, str): color = [color] all_pvalues = [] length = len(data) for item, execution in enumerate(data): if number_to_keep is not None: data_temp = dict(Counter(execution).most_common(number_to_keep)) data_temp["rest"] = sum(execution.values()) - sum(data_temp.values()) execution = data_temp values = [] for key in labels: if key not in execution: if number_to_keep is None: labels_dict[key] = 1 values.append(0) else: values.append(-1) else: labels_dict[key] = 1 values.append(execution[key]) values = np.array(values, dtype=float) where_idx = np.where(values >= 0)[0] pvalues = values[where_idx] / sum(values[where_idx]) for value in pvalues: all_pvalues.append(value) numelem = len(values[where_idx]) ind = np.arange(numelem) # the x locations for the groups width = 1/(len(data)+1) # the width of the bars rects = [] for idx, val in enumerate(pvalues): label = None if not idx and legend: label = legend[item] if val >= 0: rects.append(ax.bar(idx+item*width, val, width, label=label, color=color[item % len(color)], zorder=2)) bar_center = (width / 2) * (length - 1) ax.set_xticks(ind + bar_center) ax.set_xticklabels(labels_dict.keys(), fontsize=14, rotation=70) # attach some text labels if bar_labels: for rect in rects: for rec in rect: height = rec.get_height() if height >= 1e-3: ax.text(rec.get_x() + rec.get_width() / 2., 1.05 * height, '%.3f' % float(height), ha='center', va='bottom', zorder=3) else: ax.text(rec.get_x() + rec.get_width() / 2., 1.05 * height, '0', ha='center', va='bottom', zorder=3) # add some text for labels, title, and axes ticks ax.set_ylabel('Probabilities', fontsize=14) ax.set_ylim([0., min([1.2, max([1.2 * val for val in all_pvalues])])]) if sort == 'desc': ax.invert_xaxis() ax.yaxis.set_major_locator(MaxNLocator(5)) for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(14) ax.set_facecolor('#eeeeee') plt.grid(which='major', axis='y', zorder=0, linestyle='--') if title: plt.title(title) if legend: ax.legend(loc='upper left', bbox_to_anchor=(1.01, 1.0), ncol=1, borderaxespad=0, frameon=True, fontsize=12) if fig: plt.close(fig) return fig
def plot_histogram(data, figsize=(7, 5), color=None, number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, title=None): """Plot a histogram of data. Args: data (list or dict): This is either a list of dictionaries or a single dict containing the values to represent (ex {'001': 130}) figsize (tuple): Figure size in inches. color (list or str): String or list of strings for histogram bar colors. number_to_keep (int): The number of terms to plot and rest is made into a single bar called 'rest'. sort (string): Could be 'asc', 'desc', or 'hamming'. target_string (str): Target string if 'sort' is a distance measure. legend(list): A list of strings to use for labels of the data. The number of entries must match the length of data (if data is a list or 1 if it's a dict) bar_labels (bool): Label each bar in histogram with probability value. title (str): A string to use for the plot title Returns: matplotlib.Figure: A figure for the rendered histogram. Raises: ImportError: Matplotlib not available. VisualizationError: When legend is provided and the length doesn't match the input data. """ if not HAS_MATPLOTLIB: raise ImportError('Must have Matplotlib installed.') if sort not in VALID_SORTS: raise VisualizationError("Value of sort option, %s, isn't a " "valid choice. Must be 'asc', " "'desc', or 'hamming'") elif sort in DIST_MEAS.keys() and target_string is None: err_msg = 'Must define target_string when using distance measure.' raise VisualizationError(err_msg) if isinstance(data, dict): data = [data] if legend and len(legend) != len(data): raise VisualizationError("Length of legendL (%s) doesn't match " "number of input executions: %s" % (len(legend), len(data))) fig, ax = plt.subplots(figsize=figsize) labels = list(sorted( functools.reduce(lambda x, y: x.union(y.keys()), data, set()))) if number_to_keep is not None: labels.append('rest') if sort in DIST_MEAS.keys(): dist = [] for item in labels: dist.append(DIST_MEAS[sort](item, target_string)) labels = [list(x) for x in zip(*sorted(zip(dist, labels), key=lambda pair: pair[0]))][1] labels_dict = OrderedDict() # Set bar colors if color is None: color = ['#648fff', '#dc267f', '#785ef0', '#ffb000', '#fe6100'] elif isinstance(color, str): color = [color] all_pvalues = [] length = len(data) for item, execution in enumerate(data): if number_to_keep is not None: data_temp = dict(Counter(execution).most_common(number_to_keep)) data_temp["rest"] = sum(execution.values()) - sum(data_temp.values()) execution = data_temp values = [] for key in labels: if key not in execution: if number_to_keep is None: labels_dict[key] = 1 values.append(0) else: values.append(-1) else: labels_dict[key] = 1 values.append(execution[key]) values = np.array(values, dtype=float) where_idx = np.where(values >= 0)[0] pvalues = values[where_idx] / sum(values[where_idx]) for value in pvalues: all_pvalues.append(value) numelem = len(values[where_idx]) ind = np.arange(numelem) # the x locations for the groups width = 1/(len(data)+1) # the width of the bars rects = [] for idx, val in enumerate(pvalues): label = None if not idx and legend: label = legend[item] if val >= 0: rects.append(ax.bar(idx+item*width, val, width, label=label, color=color[item % len(color)], zorder=2)) bar_center = (width / 2) * (length - 1) ax.set_xticks(ind + bar_center) ax.set_xticklabels(labels_dict.keys(), fontsize=14, rotation=70) # attach some text labels if bar_labels: for rect in rects: for rec in rect: height = rec.get_height() if height >= 1e-3: ax.text(rec.get_x() + rec.get_width() / 2., 1.05 * height, '%.3f' % float(height), ha='center', va='bottom', zorder=3) else: ax.text(rec.get_x() + rec.get_width() / 2., 1.05 * height, '0', ha='center', va='bottom', zorder=3) # add some text for labels, title, and axes ticks ax.set_ylabel('Probabilities', fontsize=14) ax.set_ylim([0., min([1.2, max([1.2 * val for val in all_pvalues])])]) if sort == 'desc': ax.invert_xaxis() ax.yaxis.set_major_locator(MaxNLocator(5)) for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(14) ax.set_facecolor('#eeeeee') plt.grid(which='major', axis='y', zorder=0, linestyle='--') if title: plt.title(title) if legend: ax.legend(loc='upper left', bbox_to_anchor=(1.01, 1.0), ncol=1, borderaxespad=0, frameon=True, fontsize=12) if fig: plt.close(fig) return fig
[ "Plot", "a", "histogram", "of", "data", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/counts_visualization.py#L45-L184
[ "def", "plot_histogram", "(", "data", ",", "figsize", "=", "(", "7", ",", "5", ")", ",", "color", "=", "None", ",", "number_to_keep", "=", "None", ",", "sort", "=", "'asc'", ",", "target_string", "=", "None", ",", "legend", "=", "None", ",", "bar_labels", "=", "True", ",", "title", "=", "None", ")", ":", "if", "not", "HAS_MATPLOTLIB", ":", "raise", "ImportError", "(", "'Must have Matplotlib installed.'", ")", "if", "sort", "not", "in", "VALID_SORTS", ":", "raise", "VisualizationError", "(", "\"Value of sort option, %s, isn't a \"", "\"valid choice. Must be 'asc', \"", "\"'desc', or 'hamming'\"", ")", "elif", "sort", "in", "DIST_MEAS", ".", "keys", "(", ")", "and", "target_string", "is", "None", ":", "err_msg", "=", "'Must define target_string when using distance measure.'", "raise", "VisualizationError", "(", "err_msg", ")", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "data", "=", "[", "data", "]", "if", "legend", "and", "len", "(", "legend", ")", "!=", "len", "(", "data", ")", ":", "raise", "VisualizationError", "(", "\"Length of legendL (%s) doesn't match \"", "\"number of input executions: %s\"", "%", "(", "len", "(", "legend", ")", ",", "len", "(", "data", ")", ")", ")", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", "figsize", "=", "figsize", ")", "labels", "=", "list", "(", "sorted", "(", "functools", ".", "reduce", "(", "lambda", "x", ",", "y", ":", "x", ".", "union", "(", "y", ".", "keys", "(", ")", ")", ",", "data", ",", "set", "(", ")", ")", ")", ")", "if", "number_to_keep", "is", "not", "None", ":", "labels", ".", "append", "(", "'rest'", ")", "if", "sort", "in", "DIST_MEAS", ".", "keys", "(", ")", ":", "dist", "=", "[", "]", "for", "item", "in", "labels", ":", "dist", ".", "append", "(", "DIST_MEAS", "[", "sort", "]", "(", "item", ",", "target_string", ")", ")", "labels", "=", "[", "list", "(", "x", ")", "for", "x", "in", "zip", "(", "*", "sorted", "(", "zip", "(", "dist", ",", "labels", ")", ",", "key", "=", "lambda", "pair", ":", "pair", "[", "0", "]", ")", ")", "]", "[", "1", "]", "labels_dict", "=", "OrderedDict", "(", ")", "# Set bar colors", "if", "color", "is", "None", ":", "color", "=", "[", "'#648fff'", ",", "'#dc267f'", ",", "'#785ef0'", ",", "'#ffb000'", ",", "'#fe6100'", "]", "elif", "isinstance", "(", "color", ",", "str", ")", ":", "color", "=", "[", "color", "]", "all_pvalues", "=", "[", "]", "length", "=", "len", "(", "data", ")", "for", "item", ",", "execution", "in", "enumerate", "(", "data", ")", ":", "if", "number_to_keep", "is", "not", "None", ":", "data_temp", "=", "dict", "(", "Counter", "(", "execution", ")", ".", "most_common", "(", "number_to_keep", ")", ")", "data_temp", "[", "\"rest\"", "]", "=", "sum", "(", "execution", ".", "values", "(", ")", ")", "-", "sum", "(", "data_temp", ".", "values", "(", ")", ")", "execution", "=", "data_temp", "values", "=", "[", "]", "for", "key", "in", "labels", ":", "if", "key", "not", "in", "execution", ":", "if", "number_to_keep", "is", "None", ":", "labels_dict", "[", "key", "]", "=", "1", "values", ".", "append", "(", "0", ")", "else", ":", "values", ".", "append", "(", "-", "1", ")", "else", ":", "labels_dict", "[", "key", "]", "=", "1", "values", ".", "append", "(", "execution", "[", "key", "]", ")", "values", "=", "np", ".", "array", "(", "values", ",", "dtype", "=", "float", ")", "where_idx", "=", "np", ".", "where", "(", "values", ">=", "0", ")", "[", "0", "]", "pvalues", "=", "values", "[", "where_idx", "]", "/", "sum", "(", "values", "[", "where_idx", "]", ")", "for", "value", "in", "pvalues", ":", "all_pvalues", ".", "append", "(", "value", ")", "numelem", "=", "len", "(", "values", "[", "where_idx", "]", ")", "ind", "=", "np", ".", "arange", "(", "numelem", ")", "# the x locations for the groups", "width", "=", "1", "/", "(", "len", "(", "data", ")", "+", "1", ")", "# the width of the bars", "rects", "=", "[", "]", "for", "idx", ",", "val", "in", "enumerate", "(", "pvalues", ")", ":", "label", "=", "None", "if", "not", "idx", "and", "legend", ":", "label", "=", "legend", "[", "item", "]", "if", "val", ">=", "0", ":", "rects", ".", "append", "(", "ax", ".", "bar", "(", "idx", "+", "item", "*", "width", ",", "val", ",", "width", ",", "label", "=", "label", ",", "color", "=", "color", "[", "item", "%", "len", "(", "color", ")", "]", ",", "zorder", "=", "2", ")", ")", "bar_center", "=", "(", "width", "/", "2", ")", "*", "(", "length", "-", "1", ")", "ax", ".", "set_xticks", "(", "ind", "+", "bar_center", ")", "ax", ".", "set_xticklabels", "(", "labels_dict", ".", "keys", "(", ")", ",", "fontsize", "=", "14", ",", "rotation", "=", "70", ")", "# attach some text labels", "if", "bar_labels", ":", "for", "rect", "in", "rects", ":", "for", "rec", "in", "rect", ":", "height", "=", "rec", ".", "get_height", "(", ")", "if", "height", ">=", "1e-3", ":", "ax", ".", "text", "(", "rec", ".", "get_x", "(", ")", "+", "rec", ".", "get_width", "(", ")", "/", "2.", ",", "1.05", "*", "height", ",", "'%.3f'", "%", "float", "(", "height", ")", ",", "ha", "=", "'center'", ",", "va", "=", "'bottom'", ",", "zorder", "=", "3", ")", "else", ":", "ax", ".", "text", "(", "rec", ".", "get_x", "(", ")", "+", "rec", ".", "get_width", "(", ")", "/", "2.", ",", "1.05", "*", "height", ",", "'0'", ",", "ha", "=", "'center'", ",", "va", "=", "'bottom'", ",", "zorder", "=", "3", ")", "# add some text for labels, title, and axes ticks", "ax", ".", "set_ylabel", "(", "'Probabilities'", ",", "fontsize", "=", "14", ")", "ax", ".", "set_ylim", "(", "[", "0.", ",", "min", "(", "[", "1.2", ",", "max", "(", "[", "1.2", "*", "val", "for", "val", "in", "all_pvalues", "]", ")", "]", ")", "]", ")", "if", "sort", "==", "'desc'", ":", "ax", ".", "invert_xaxis", "(", ")", "ax", ".", "yaxis", ".", "set_major_locator", "(", "MaxNLocator", "(", "5", ")", ")", "for", "tick", "in", "ax", ".", "yaxis", ".", "get_major_ticks", "(", ")", ":", "tick", ".", "label", ".", "set_fontsize", "(", "14", ")", "ax", ".", "set_facecolor", "(", "'#eeeeee'", ")", "plt", ".", "grid", "(", "which", "=", "'major'", ",", "axis", "=", "'y'", ",", "zorder", "=", "0", ",", "linestyle", "=", "'--'", ")", "if", "title", ":", "plt", ".", "title", "(", "title", ")", "if", "legend", ":", "ax", ".", "legend", "(", "loc", "=", "'upper left'", ",", "bbox_to_anchor", "=", "(", "1.01", ",", "1.0", ")", ",", "ncol", "=", "1", ",", "borderaxespad", "=", "0", ",", "frameon", "=", "True", ",", "fontsize", "=", "12", ")", "if", "fig", ":", "plt", ".", "close", "(", "fig", ")", "return", "fig" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
quaternion_from_axis_rotation
Return quaternion for rotation about given axis. Args: angle (float): Angle in radians. axis (str): Axis for rotation Returns: Quaternion: Quaternion for axis rotation. Raises: ValueError: Invalid input axis.
qiskit/quantum_info/operators/quaternion.py
def quaternion_from_axis_rotation(angle, axis): """Return quaternion for rotation about given axis. Args: angle (float): Angle in radians. axis (str): Axis for rotation Returns: Quaternion: Quaternion for axis rotation. Raises: ValueError: Invalid input axis. """ out = np.zeros(4, dtype=float) if axis == 'x': out[1] = 1 elif axis == 'y': out[2] = 1 elif axis == 'z': out[3] = 1 else: raise ValueError('Invalid axis input.') out *= math.sin(angle/2.0) out[0] = math.cos(angle/2.0) return Quaternion(out)
def quaternion_from_axis_rotation(angle, axis): """Return quaternion for rotation about given axis. Args: angle (float): Angle in radians. axis (str): Axis for rotation Returns: Quaternion: Quaternion for axis rotation. Raises: ValueError: Invalid input axis. """ out = np.zeros(4, dtype=float) if axis == 'x': out[1] = 1 elif axis == 'y': out[2] = 1 elif axis == 'z': out[3] = 1 else: raise ValueError('Invalid axis input.') out *= math.sin(angle/2.0) out[0] = math.cos(angle/2.0) return Quaternion(out)
[ "Return", "quaternion", "for", "rotation", "about", "given", "axis", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/quaternion.py#L104-L128
[ "def", "quaternion_from_axis_rotation", "(", "angle", ",", "axis", ")", ":", "out", "=", "np", ".", "zeros", "(", "4", ",", "dtype", "=", "float", ")", "if", "axis", "==", "'x'", ":", "out", "[", "1", "]", "=", "1", "elif", "axis", "==", "'y'", ":", "out", "[", "2", "]", "=", "1", "elif", "axis", "==", "'z'", ":", "out", "[", "3", "]", "=", "1", "else", ":", "raise", "ValueError", "(", "'Invalid axis input.'", ")", "out", "*=", "math", ".", "sin", "(", "angle", "/", "2.0", ")", "out", "[", "0", "]", "=", "math", ".", "cos", "(", "angle", "/", "2.0", ")", "return", "Quaternion", "(", "out", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
quaternion_from_euler
Generate a quaternion from a set of Euler angles. Args: angles (array_like): Array of Euler angles. order (str): Order of Euler rotations. 'yzy' is default. Returns: Quaternion: Quaternion representation of Euler rotation.
qiskit/quantum_info/operators/quaternion.py
def quaternion_from_euler(angles, order='yzy'): """Generate a quaternion from a set of Euler angles. Args: angles (array_like): Array of Euler angles. order (str): Order of Euler rotations. 'yzy' is default. Returns: Quaternion: Quaternion representation of Euler rotation. """ angles = np.asarray(angles, dtype=float) quat = quaternion_from_axis_rotation(angles[0], order[0])\ * (quaternion_from_axis_rotation(angles[1], order[1]) * quaternion_from_axis_rotation(angles[2], order[2])) quat.normalize(inplace=True) return quat
def quaternion_from_euler(angles, order='yzy'): """Generate a quaternion from a set of Euler angles. Args: angles (array_like): Array of Euler angles. order (str): Order of Euler rotations. 'yzy' is default. Returns: Quaternion: Quaternion representation of Euler rotation. """ angles = np.asarray(angles, dtype=float) quat = quaternion_from_axis_rotation(angles[0], order[0])\ * (quaternion_from_axis_rotation(angles[1], order[1]) * quaternion_from_axis_rotation(angles[2], order[2])) quat.normalize(inplace=True) return quat
[ "Generate", "a", "quaternion", "from", "a", "set", "of", "Euler", "angles", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/quaternion.py#L131-L146
[ "def", "quaternion_from_euler", "(", "angles", ",", "order", "=", "'yzy'", ")", ":", "angles", "=", "np", ".", "asarray", "(", "angles", ",", "dtype", "=", "float", ")", "quat", "=", "quaternion_from_axis_rotation", "(", "angles", "[", "0", "]", ",", "order", "[", "0", "]", ")", "*", "(", "quaternion_from_axis_rotation", "(", "angles", "[", "1", "]", ",", "order", "[", "1", "]", ")", "*", "quaternion_from_axis_rotation", "(", "angles", "[", "2", "]", ",", "order", "[", "2", "]", ")", ")", "quat", ".", "normalize", "(", "inplace", "=", "True", ")", "return", "quat" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Quaternion.normalize
Normalizes a Quaternion to unit length so that it represents a valid rotation. Args: inplace (bool): Do an inplace normalization. Returns: Quaternion: Normalized quaternion.
qiskit/quantum_info/operators/quaternion.py
def normalize(self, inplace=False): """Normalizes a Quaternion to unit length so that it represents a valid rotation. Args: inplace (bool): Do an inplace normalization. Returns: Quaternion: Normalized quaternion. """ if inplace: nrm = self.norm() self.data /= nrm return None nrm = self.norm() data_copy = np.array(self.data, copy=True) data_copy /= nrm return Quaternion(data_copy)
def normalize(self, inplace=False): """Normalizes a Quaternion to unit length so that it represents a valid rotation. Args: inplace (bool): Do an inplace normalization. Returns: Quaternion: Normalized quaternion. """ if inplace: nrm = self.norm() self.data /= nrm return None nrm = self.norm() data_copy = np.array(self.data, copy=True) data_copy /= nrm return Quaternion(data_copy)
[ "Normalizes", "a", "Quaternion", "to", "unit", "length", "so", "that", "it", "represents", "a", "valid", "rotation", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/quaternion.py#L49-L66
[ "def", "normalize", "(", "self", ",", "inplace", "=", "False", ")", ":", "if", "inplace", ":", "nrm", "=", "self", ".", "norm", "(", ")", "self", ".", "data", "/=", "nrm", "return", "None", "nrm", "=", "self", ".", "norm", "(", ")", "data_copy", "=", "np", ".", "array", "(", "self", ".", "data", ",", "copy", "=", "True", ")", "data_copy", "/=", "nrm", "return", "Quaternion", "(", "data_copy", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Quaternion.to_matrix
Converts a unit-length quaternion to a rotation matrix. Returns: ndarray: Rotation matrix.
qiskit/quantum_info/operators/quaternion.py
def to_matrix(self): """Converts a unit-length quaternion to a rotation matrix. Returns: ndarray: Rotation matrix. """ w, x, y, z = self.normalize().data # pylint: disable=C0103 mat = np.array([ [1-2*y**2-2*z**2, 2*x*y-2*z*w, 2*x*z+2*y*w], [2*x*y+2*z*w, 1-2*x**2-2*z**2, 2*y*z-2*x*w], [2*x*z-2*y*w, 2*y*z+2*x*w, 1-2*x**2-2*y**2] ], dtype=float) return mat
def to_matrix(self): """Converts a unit-length quaternion to a rotation matrix. Returns: ndarray: Rotation matrix. """ w, x, y, z = self.normalize().data # pylint: disable=C0103 mat = np.array([ [1-2*y**2-2*z**2, 2*x*y-2*z*w, 2*x*z+2*y*w], [2*x*y+2*z*w, 1-2*x**2-2*z**2, 2*y*z-2*x*w], [2*x*z-2*y*w, 2*y*z+2*x*w, 1-2*x**2-2*y**2] ], dtype=float) return mat
[ "Converts", "a", "unit", "-", "length", "quaternion", "to", "a", "rotation", "matrix", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/quaternion.py#L68-L80
[ "def", "to_matrix", "(", "self", ")", ":", "w", ",", "x", ",", "y", ",", "z", "=", "self", ".", "normalize", "(", ")", ".", "data", "# pylint: disable=C0103", "mat", "=", "np", ".", "array", "(", "[", "[", "1", "-", "2", "*", "y", "**", "2", "-", "2", "*", "z", "**", "2", ",", "2", "*", "x", "*", "y", "-", "2", "*", "z", "*", "w", ",", "2", "*", "x", "*", "z", "+", "2", "*", "y", "*", "w", "]", ",", "[", "2", "*", "x", "*", "y", "+", "2", "*", "z", "*", "w", ",", "1", "-", "2", "*", "x", "**", "2", "-", "2", "*", "z", "**", "2", ",", "2", "*", "y", "*", "z", "-", "2", "*", "x", "*", "w", "]", ",", "[", "2", "*", "x", "*", "z", "-", "2", "*", "y", "*", "w", ",", "2", "*", "y", "*", "z", "+", "2", "*", "x", "*", "w", ",", "1", "-", "2", "*", "x", "**", "2", "-", "2", "*", "y", "**", "2", "]", "]", ",", "dtype", "=", "float", ")", "return", "mat" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Quaternion.to_zyz
Converts a unit-length quaternion to a sequence of ZYZ Euler angles. Returns: ndarray: Array of Euler angles.
qiskit/quantum_info/operators/quaternion.py
def to_zyz(self): """Converts a unit-length quaternion to a sequence of ZYZ Euler angles. Returns: ndarray: Array of Euler angles. """ mat = self.to_matrix() euler = np.zeros(3, dtype=float) if mat[2, 2] < 1: if mat[2, 2] > -1: euler[0] = math.atan2(mat[1, 2], mat[0, 2]) euler[1] = math.acos(mat[2, 2]) euler[2] = math.atan2(mat[2, 1], -mat[2, 0]) else: euler[0] = -math.atan2(mat[1, 0], mat[1, 1]) euler[1] = np.pi else: euler[0] = math.atan2(mat[1, 0], mat[1, 1]) return euler
def to_zyz(self): """Converts a unit-length quaternion to a sequence of ZYZ Euler angles. Returns: ndarray: Array of Euler angles. """ mat = self.to_matrix() euler = np.zeros(3, dtype=float) if mat[2, 2] < 1: if mat[2, 2] > -1: euler[0] = math.atan2(mat[1, 2], mat[0, 2]) euler[1] = math.acos(mat[2, 2]) euler[2] = math.atan2(mat[2, 1], -mat[2, 0]) else: euler[0] = -math.atan2(mat[1, 0], mat[1, 1]) euler[1] = np.pi else: euler[0] = math.atan2(mat[1, 0], mat[1, 1]) return euler
[ "Converts", "a", "unit", "-", "length", "quaternion", "to", "a", "sequence", "of", "ZYZ", "Euler", "angles", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/quaternion.py#L82-L101
[ "def", "to_zyz", "(", "self", ")", ":", "mat", "=", "self", ".", "to_matrix", "(", ")", "euler", "=", "np", ".", "zeros", "(", "3", ",", "dtype", "=", "float", ")", "if", "mat", "[", "2", ",", "2", "]", "<", "1", ":", "if", "mat", "[", "2", ",", "2", "]", ">", "-", "1", ":", "euler", "[", "0", "]", "=", "math", ".", "atan2", "(", "mat", "[", "1", ",", "2", "]", ",", "mat", "[", "0", ",", "2", "]", ")", "euler", "[", "1", "]", "=", "math", ".", "acos", "(", "mat", "[", "2", ",", "2", "]", ")", "euler", "[", "2", "]", "=", "math", ".", "atan2", "(", "mat", "[", "2", ",", "1", "]", ",", "-", "mat", "[", "2", ",", "0", "]", ")", "else", ":", "euler", "[", "0", "]", "=", "-", "math", ".", "atan2", "(", "mat", "[", "1", ",", "0", "]", ",", "mat", "[", "1", ",", "1", "]", ")", "euler", "[", "1", "]", "=", "np", ".", "pi", "else", ":", "euler", "[", "0", "]", "=", "math", ".", "atan2", "(", "mat", "[", "1", ",", "0", "]", ",", "mat", "[", "1", ",", "1", "]", ")", "return", "euler" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
process_data
Prepare received data for representation. Args: data (dict): values to represent (ex. {'001' : 130}) number_to_keep (int): number of elements to show individually. Returns: dict: processed data to show.
qiskit/visualization/interactive/iplot_histogram.py
def process_data(data, number_to_keep): """ Prepare received data for representation. Args: data (dict): values to represent (ex. {'001' : 130}) number_to_keep (int): number of elements to show individually. Returns: dict: processed data to show. """ result = dict() if number_to_keep != 0: data_temp = dict(Counter(data).most_common(number_to_keep)) data_temp['rest'] = sum(data.values()) - sum(data_temp.values()) data = data_temp labels = data values = np.array([data[key] for key in labels], dtype=float) pvalues = values / sum(values) for position, label in enumerate(labels): result[label] = round(pvalues[position], 5) return result
def process_data(data, number_to_keep): """ Prepare received data for representation. Args: data (dict): values to represent (ex. {'001' : 130}) number_to_keep (int): number of elements to show individually. Returns: dict: processed data to show. """ result = dict() if number_to_keep != 0: data_temp = dict(Counter(data).most_common(number_to_keep)) data_temp['rest'] = sum(data.values()) - sum(data_temp.values()) data = data_temp labels = data values = np.array([data[key] for key in labels], dtype=float) pvalues = values / sum(values) for position, label in enumerate(labels): result[label] = round(pvalues[position], 5) return result
[ "Prepare", "received", "data", "for", "representation", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/interactive/iplot_histogram.py#L26-L50
[ "def", "process_data", "(", "data", ",", "number_to_keep", ")", ":", "result", "=", "dict", "(", ")", "if", "number_to_keep", "!=", "0", ":", "data_temp", "=", "dict", "(", "Counter", "(", "data", ")", ".", "most_common", "(", "number_to_keep", ")", ")", "data_temp", "[", "'rest'", "]", "=", "sum", "(", "data", ".", "values", "(", ")", ")", "-", "sum", "(", "data_temp", ".", "values", "(", ")", ")", "data", "=", "data_temp", "labels", "=", "data", "values", "=", "np", ".", "array", "(", "[", "data", "[", "key", "]", "for", "key", "in", "labels", "]", ",", "dtype", "=", "float", ")", "pvalues", "=", "values", "/", "sum", "(", "values", ")", "for", "position", ",", "label", "in", "enumerate", "(", "labels", ")", ":", "result", "[", "label", "]", "=", "round", "(", "pvalues", "[", "position", "]", ",", "5", ")", "return", "result" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
iplot_histogram
Create a histogram representation. Graphical representation of the input array using a vertical bars style graph. Args: data (list or dict): This is either a list of dicts or a single dict containing the values to represent (ex. {'001' : 130}) figsize (tuple): Figure size in pixels. number_to_keep (int): The number of terms to plot and rest is made into a single bar called other values sort (string): Could be 'asc' or 'desc' legend (list): A list of strings to use for labels of the data. The number of entries must match the length of data. Raises: VisualizationError: When legend is provided and the length doesn't match the input data.
qiskit/visualization/interactive/iplot_histogram.py
def iplot_histogram(data, figsize=None, number_to_keep=None, sort='asc', legend=None): """ Create a histogram representation. Graphical representation of the input array using a vertical bars style graph. Args: data (list or dict): This is either a list of dicts or a single dict containing the values to represent (ex. {'001' : 130}) figsize (tuple): Figure size in pixels. number_to_keep (int): The number of terms to plot and rest is made into a single bar called other values sort (string): Could be 'asc' or 'desc' legend (list): A list of strings to use for labels of the data. The number of entries must match the length of data. Raises: VisualizationError: When legend is provided and the length doesn't match the input data. """ # HTML html_template = Template(""" <p> <div id="histogram_$divNumber"></div> </p> """) # JavaScript javascript_template = Template(""" <script> requirejs.config({ paths: { qVisualization: "https://qvisualization.mybluemix.net/q-visualizations" } }); require(["qVisualization"], function(qVisualizations) { qVisualizations.plotState("histogram_$divNumber", "histogram", $executions, $options); }); </script> """) # Process data and execute div_number = str(time.time()) div_number = re.sub('[.]', '', div_number) # set default figure size if none provided if figsize is None: figsize = (7, 5) options = {'number_to_keep': 0 if number_to_keep is None else number_to_keep, 'sort': sort, 'show_legend': 0, 'width': int(figsize[0]), 'height': int(figsize[1])} if legend: options['show_legend'] = 1 data_to_plot = [] if isinstance(data, dict): data = [data] if legend and len(legend) != len(data): raise VisualizationError("Length of legendL (%s) doesn't match number " "of input executions: %s" % (len(legend), len(data))) for item, execution in enumerate(data): exec_data = process_data(execution, options['number_to_keep']) out_dict = {'data': exec_data} if legend: out_dict['name'] = legend[item] data_to_plot.append(out_dict) html = html_template.substitute({ 'divNumber': div_number }) javascript = javascript_template.substitute({ 'divNumber': div_number, 'executions': data_to_plot, 'options': options }) display(HTML(html + javascript))
def iplot_histogram(data, figsize=None, number_to_keep=None, sort='asc', legend=None): """ Create a histogram representation. Graphical representation of the input array using a vertical bars style graph. Args: data (list or dict): This is either a list of dicts or a single dict containing the values to represent (ex. {'001' : 130}) figsize (tuple): Figure size in pixels. number_to_keep (int): The number of terms to plot and rest is made into a single bar called other values sort (string): Could be 'asc' or 'desc' legend (list): A list of strings to use for labels of the data. The number of entries must match the length of data. Raises: VisualizationError: When legend is provided and the length doesn't match the input data. """ # HTML html_template = Template(""" <p> <div id="histogram_$divNumber"></div> </p> """) # JavaScript javascript_template = Template(""" <script> requirejs.config({ paths: { qVisualization: "https://qvisualization.mybluemix.net/q-visualizations" } }); require(["qVisualization"], function(qVisualizations) { qVisualizations.plotState("histogram_$divNumber", "histogram", $executions, $options); }); </script> """) # Process data and execute div_number = str(time.time()) div_number = re.sub('[.]', '', div_number) # set default figure size if none provided if figsize is None: figsize = (7, 5) options = {'number_to_keep': 0 if number_to_keep is None else number_to_keep, 'sort': sort, 'show_legend': 0, 'width': int(figsize[0]), 'height': int(figsize[1])} if legend: options['show_legend'] = 1 data_to_plot = [] if isinstance(data, dict): data = [data] if legend and len(legend) != len(data): raise VisualizationError("Length of legendL (%s) doesn't match number " "of input executions: %s" % (len(legend), len(data))) for item, execution in enumerate(data): exec_data = process_data(execution, options['number_to_keep']) out_dict = {'data': exec_data} if legend: out_dict['name'] = legend[item] data_to_plot.append(out_dict) html = html_template.substitute({ 'divNumber': div_number }) javascript = javascript_template.substitute({ 'divNumber': div_number, 'executions': data_to_plot, 'options': options }) display(HTML(html + javascript))
[ "Create", "a", "histogram", "representation", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/interactive/iplot_histogram.py#L53-L141
[ "def", "iplot_histogram", "(", "data", ",", "figsize", "=", "None", ",", "number_to_keep", "=", "None", ",", "sort", "=", "'asc'", ",", "legend", "=", "None", ")", ":", "# HTML", "html_template", "=", "Template", "(", "\"\"\"\n <p>\n <div id=\"histogram_$divNumber\"></div>\n </p>\n \"\"\"", ")", "# JavaScript", "javascript_template", "=", "Template", "(", "\"\"\"\n <script>\n requirejs.config({\n paths: {\n qVisualization: \"https://qvisualization.mybluemix.net/q-visualizations\"\n }\n });\n\n require([\"qVisualization\"], function(qVisualizations) {\n qVisualizations.plotState(\"histogram_$divNumber\",\n \"histogram\",\n $executions,\n $options);\n });\n </script>\n \"\"\"", ")", "# Process data and execute", "div_number", "=", "str", "(", "time", ".", "time", "(", ")", ")", "div_number", "=", "re", ".", "sub", "(", "'[.]'", ",", "''", ",", "div_number", ")", "# set default figure size if none provided", "if", "figsize", "is", "None", ":", "figsize", "=", "(", "7", ",", "5", ")", "options", "=", "{", "'number_to_keep'", ":", "0", "if", "number_to_keep", "is", "None", "else", "number_to_keep", ",", "'sort'", ":", "sort", ",", "'show_legend'", ":", "0", ",", "'width'", ":", "int", "(", "figsize", "[", "0", "]", ")", ",", "'height'", ":", "int", "(", "figsize", "[", "1", "]", ")", "}", "if", "legend", ":", "options", "[", "'show_legend'", "]", "=", "1", "data_to_plot", "=", "[", "]", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "data", "=", "[", "data", "]", "if", "legend", "and", "len", "(", "legend", ")", "!=", "len", "(", "data", ")", ":", "raise", "VisualizationError", "(", "\"Length of legendL (%s) doesn't match number \"", "\"of input executions: %s\"", "%", "(", "len", "(", "legend", ")", ",", "len", "(", "data", ")", ")", ")", "for", "item", ",", "execution", "in", "enumerate", "(", "data", ")", ":", "exec_data", "=", "process_data", "(", "execution", ",", "options", "[", "'number_to_keep'", "]", ")", "out_dict", "=", "{", "'data'", ":", "exec_data", "}", "if", "legend", ":", "out_dict", "[", "'name'", "]", "=", "legend", "[", "item", "]", "data_to_plot", ".", "append", "(", "out_dict", ")", "html", "=", "html_template", ".", "substitute", "(", "{", "'divNumber'", ":", "div_number", "}", ")", "javascript", "=", "javascript_template", ".", "substitute", "(", "{", "'divNumber'", ":", "div_number", ",", "'executions'", ":", "data_to_plot", ",", "'options'", ":", "options", "}", ")", "display", "(", "HTML", "(", "html", "+", "javascript", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
InstructionParameter.check_type
Customize check_type for handling containers.
qiskit/validation/fields/custom.py
def check_type(self, value, attr, data): """Customize check_type for handling containers.""" # Check the type in the standard way first, in order to fail quickly # in case of invalid values. root_value = super(InstructionParameter, self).check_type( value, attr, data) if is_collection(value): _ = [super(InstructionParameter, self).check_type(item, attr, data) for item in value] return root_value
def check_type(self, value, attr, data): """Customize check_type for handling containers.""" # Check the type in the standard way first, in order to fail quickly # in case of invalid values. root_value = super(InstructionParameter, self).check_type( value, attr, data) if is_collection(value): _ = [super(InstructionParameter, self).check_type(item, attr, data) for item in value] return root_value
[ "Customize", "check_type", "for", "handling", "containers", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/validation/fields/custom.py#L113-L124
[ "def", "check_type", "(", "self", ",", "value", ",", "attr", ",", "data", ")", ":", "# Check the type in the standard way first, in order to fail quickly", "# in case of invalid values.", "root_value", "=", "super", "(", "InstructionParameter", ",", "self", ")", ".", "check_type", "(", "value", ",", "attr", ",", "data", ")", "if", "is_collection", "(", "value", ")", ":", "_", "=", "[", "super", "(", "InstructionParameter", ",", "self", ")", ".", "check_type", "(", "item", ",", "attr", ",", "data", ")", "for", "item", "in", "value", "]", "return", "root_value" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Register.check_range
Check that j is a valid index into self.
qiskit/circuit/register.py
def check_range(self, j): """Check that j is a valid index into self.""" if isinstance(j, int): if j < 0 or j >= self.size: raise QiskitIndexError("register index out of range") elif isinstance(j, slice): if j.start < 0 or j.stop >= self.size or (j.step is not None and j.step <= 0): raise QiskitIndexError("register index slice out of range")
def check_range(self, j): """Check that j is a valid index into self.""" if isinstance(j, int): if j < 0 or j >= self.size: raise QiskitIndexError("register index out of range") elif isinstance(j, slice): if j.start < 0 or j.stop >= self.size or (j.step is not None and j.step <= 0): raise QiskitIndexError("register index slice out of range")
[ "Check", "that", "j", "is", "a", "valid", "index", "into", "self", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/register.py#L57-L65
[ "def", "check_range", "(", "self", ",", "j", ")", ":", "if", "isinstance", "(", "j", ",", "int", ")", ":", "if", "j", "<", "0", "or", "j", ">=", "self", ".", "size", ":", "raise", "QiskitIndexError", "(", "\"register index out of range\"", ")", "elif", "isinstance", "(", "j", ",", "slice", ")", ":", "if", "j", ".", "start", "<", "0", "or", "j", ".", "stop", ">=", "self", ".", "size", "or", "(", "j", ".", "step", "is", "not", "None", "and", "j", ".", "step", "<=", "0", ")", ":", "raise", "QiskitIndexError", "(", "\"register index slice out of range\"", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Node.to_string
Print with indent.
qiskit/qasm/node/node.py
def to_string(self, indent): """Print with indent.""" ind = indent * ' ' if self.root: print(ind, self.type, '---', self.root) else: print(ind, self.type) indent = indent + 3 ind = indent * ' ' for children in self.children: if children is None: print("OOPS! type of parent is", type(self)) print(self.children) if isinstance(children, str): print(ind, children) elif isinstance(children, int): print(ind, str(children)) elif isinstance(children, float): print(ind, str(children)) else: children.to_string(indent)
def to_string(self, indent): """Print with indent.""" ind = indent * ' ' if self.root: print(ind, self.type, '---', self.root) else: print(ind, self.type) indent = indent + 3 ind = indent * ' ' for children in self.children: if children is None: print("OOPS! type of parent is", type(self)) print(self.children) if isinstance(children, str): print(ind, children) elif isinstance(children, int): print(ind, str(children)) elif isinstance(children, float): print(ind, str(children)) else: children.to_string(indent)
[ "Print", "with", "indent", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/node/node.py#L34-L54
[ "def", "to_string", "(", "self", ",", "indent", ")", ":", "ind", "=", "indent", "*", "' '", "if", "self", ".", "root", ":", "print", "(", "ind", ",", "self", ".", "type", ",", "'---'", ",", "self", ".", "root", ")", "else", ":", "print", "(", "ind", ",", "self", ".", "type", ")", "indent", "=", "indent", "+", "3", "ind", "=", "indent", "*", "' '", "for", "children", "in", "self", ".", "children", ":", "if", "children", "is", "None", ":", "print", "(", "\"OOPS! type of parent is\"", ",", "type", "(", "self", ")", ")", "print", "(", "self", ".", "children", ")", "if", "isinstance", "(", "children", ",", "str", ")", ":", "print", "(", "ind", ",", "children", ")", "elif", "isinstance", "(", "children", ",", "int", ")", ":", "print", "(", "ind", ",", "str", "(", "children", ")", ")", "elif", "isinstance", "(", "children", ",", "float", ")", ":", "print", "(", "ind", ",", "str", "(", "children", ")", ")", "else", ":", "children", ".", "to_string", "(", "indent", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Gate.assemble
Assemble a QasmQobjInstruction
qiskit/circuit/gate.py
def assemble(self): """Assemble a QasmQobjInstruction""" instruction = super().assemble() if self.label: instruction.label = self.label return instruction
def assemble(self): """Assemble a QasmQobjInstruction""" instruction = super().assemble() if self.label: instruction.label = self.label return instruction
[ "Assemble", "a", "QasmQobjInstruction" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/gate.py#L41-L46
[ "def", "assemble", "(", "self", ")", ":", "instruction", "=", "super", "(", ")", ".", "assemble", "(", ")", "if", "self", ".", "label", ":", "instruction", ".", "label", "=", "self", ".", "label", "return", "instruction" ]
d4f58d903bc96341b816f7c35df936d6421267d1