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
QuantumCircuit.add_register
Add registers.
qiskit/circuit/quantumcircuit.py
def add_register(self, *regs): """Add registers.""" if not regs: return if any([isinstance(reg, int) for reg in regs]): # QuantumCircuit defined without registers if len(regs) == 1 and isinstance(regs[0], int): # QuantumCircuit with anonymous quantum wires e.g. QuantumCircuit(2) regs = (QuantumRegister(regs[0], 'q'),) elif len(regs) == 2 and all([isinstance(reg, int) for reg in regs]): # QuantumCircuit with anonymous wires e.g. QuantumCircuit(2, 3) regs = (QuantumRegister(regs[0], 'q'), ClassicalRegister(regs[1], 'c')) else: raise QiskitError("QuantumCircuit parameters can be Registers or Integers." " If Integers, up to 2 arguments. QuantumCircuit was called" " with %s." % (regs,)) for register in regs: if register in self.qregs or register in self.cregs: raise QiskitError("register name \"%s\" already exists" % register.name) if isinstance(register, QuantumRegister): self.qregs.append(register) elif isinstance(register, ClassicalRegister): self.cregs.append(register) else: raise QiskitError("expected a register")
def add_register(self, *regs): """Add registers.""" if not regs: return if any([isinstance(reg, int) for reg in regs]): # QuantumCircuit defined without registers if len(regs) == 1 and isinstance(regs[0], int): # QuantumCircuit with anonymous quantum wires e.g. QuantumCircuit(2) regs = (QuantumRegister(regs[0], 'q'),) elif len(regs) == 2 and all([isinstance(reg, int) for reg in regs]): # QuantumCircuit with anonymous wires e.g. QuantumCircuit(2, 3) regs = (QuantumRegister(regs[0], 'q'), ClassicalRegister(regs[1], 'c')) else: raise QiskitError("QuantumCircuit parameters can be Registers or Integers." " If Integers, up to 2 arguments. QuantumCircuit was called" " with %s." % (regs,)) for register in regs: if register in self.qregs or register in self.cregs: raise QiskitError("register name \"%s\" already exists" % register.name) if isinstance(register, QuantumRegister): self.qregs.append(register) elif isinstance(register, ClassicalRegister): self.cregs.append(register) else: raise QiskitError("expected a register")
[ "Add", "registers", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L296-L323
[ "def", "add_register", "(", "self", ",", "*", "regs", ")", ":", "if", "not", "regs", ":", "return", "if", "any", "(", "[", "isinstance", "(", "reg", ",", "int", ")", "for", "reg", "in", "regs", "]", ")", ":", "# QuantumCircuit defined without registers", "if", "len", "(", "regs", ")", "==", "1", "and", "isinstance", "(", "regs", "[", "0", "]", ",", "int", ")", ":", "# QuantumCircuit with anonymous quantum wires e.g. QuantumCircuit(2)", "regs", "=", "(", "QuantumRegister", "(", "regs", "[", "0", "]", ",", "'q'", ")", ",", ")", "elif", "len", "(", "regs", ")", "==", "2", "and", "all", "(", "[", "isinstance", "(", "reg", ",", "int", ")", "for", "reg", "in", "regs", "]", ")", ":", "# QuantumCircuit with anonymous wires e.g. QuantumCircuit(2, 3)", "regs", "=", "(", "QuantumRegister", "(", "regs", "[", "0", "]", ",", "'q'", ")", ",", "ClassicalRegister", "(", "regs", "[", "1", "]", ",", "'c'", ")", ")", "else", ":", "raise", "QiskitError", "(", "\"QuantumCircuit parameters can be Registers or Integers.\"", "\" If Integers, up to 2 arguments. QuantumCircuit was called\"", "\" with %s.\"", "%", "(", "regs", ",", ")", ")", "for", "register", "in", "regs", ":", "if", "register", "in", "self", ".", "qregs", "or", "register", "in", "self", ".", "cregs", ":", "raise", "QiskitError", "(", "\"register name \\\"%s\\\" already exists\"", "%", "register", ".", "name", ")", "if", "isinstance", "(", "register", ",", "QuantumRegister", ")", ":", "self", ".", "qregs", ".", "append", "(", "register", ")", "elif", "isinstance", "(", "register", ",", "ClassicalRegister", ")", ":", "self", ".", "cregs", ".", "append", "(", "register", ")", "else", ":", "raise", "QiskitError", "(", "\"expected a register\"", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumCircuit._check_dups
Raise exception if list of qubits contains duplicates.
qiskit/circuit/quantumcircuit.py
def _check_dups(self, qubits): """Raise exception if list of qubits contains duplicates.""" squbits = set(qubits) if len(squbits) != len(qubits): raise QiskitError("duplicate qubit arguments")
def _check_dups(self, qubits): """Raise exception if list of qubits contains duplicates.""" squbits = set(qubits) if len(squbits) != len(qubits): raise QiskitError("duplicate qubit arguments")
[ "Raise", "exception", "if", "list", "of", "qubits", "contains", "duplicates", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L325-L329
[ "def", "_check_dups", "(", "self", ",", "qubits", ")", ":", "squbits", "=", "set", "(", "qubits", ")", "if", "len", "(", "squbits", ")", "!=", "len", "(", "qubits", ")", ":", "raise", "QiskitError", "(", "\"duplicate qubit arguments\"", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumCircuit._check_qargs
Raise exception if a qarg is not in this circuit or bad format.
qiskit/circuit/quantumcircuit.py
def _check_qargs(self, qargs): """Raise exception if a qarg is not in this circuit or bad format.""" if not all(isinstance(i, tuple) and isinstance(i[0], QuantumRegister) and isinstance(i[1], int) for i in qargs): raise QiskitError("qarg not (QuantumRegister, int) tuple") if not all(self.has_register(i[0]) for i in qargs): raise QiskitError("register not in this circuit") for qubit in qargs: qubit[0].check_range(qubit[1])
def _check_qargs(self, qargs): """Raise exception if a qarg is not in this circuit or bad format.""" if not all(isinstance(i, tuple) and isinstance(i[0], QuantumRegister) and isinstance(i[1], int) for i in qargs): raise QiskitError("qarg not (QuantumRegister, int) tuple") if not all(self.has_register(i[0]) for i in qargs): raise QiskitError("register not in this circuit") for qubit in qargs: qubit[0].check_range(qubit[1])
[ "Raise", "exception", "if", "a", "qarg", "is", "not", "in", "this", "circuit", "or", "bad", "format", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L331-L340
[ "def", "_check_qargs", "(", "self", ",", "qargs", ")", ":", "if", "not", "all", "(", "isinstance", "(", "i", ",", "tuple", ")", "and", "isinstance", "(", "i", "[", "0", "]", ",", "QuantumRegister", ")", "and", "isinstance", "(", "i", "[", "1", "]", ",", "int", ")", "for", "i", "in", "qargs", ")", ":", "raise", "QiskitError", "(", "\"qarg not (QuantumRegister, int) tuple\"", ")", "if", "not", "all", "(", "self", ".", "has_register", "(", "i", "[", "0", "]", ")", "for", "i", "in", "qargs", ")", ":", "raise", "QiskitError", "(", "\"register not in this circuit\"", ")", "for", "qubit", "in", "qargs", ":", "qubit", "[", "0", "]", ".", "check_range", "(", "qubit", "[", "1", "]", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumCircuit._check_cargs
Raise exception if clbit is not in this circuit or bad format.
qiskit/circuit/quantumcircuit.py
def _check_cargs(self, cargs): """Raise exception if clbit is not in this circuit or bad format.""" if not all(isinstance(i, tuple) and isinstance(i[0], ClassicalRegister) and isinstance(i[1], int) for i in cargs): raise QiskitError("carg not (ClassicalRegister, int) tuple") if not all(self.has_register(i[0]) for i in cargs): raise QiskitError("register not in this circuit") for clbit in cargs: clbit[0].check_range(clbit[1])
def _check_cargs(self, cargs): """Raise exception if clbit is not in this circuit or bad format.""" if not all(isinstance(i, tuple) and isinstance(i[0], ClassicalRegister) and isinstance(i[1], int) for i in cargs): raise QiskitError("carg not (ClassicalRegister, int) tuple") if not all(self.has_register(i[0]) for i in cargs): raise QiskitError("register not in this circuit") for clbit in cargs: clbit[0].check_range(clbit[1])
[ "Raise", "exception", "if", "clbit", "is", "not", "in", "this", "circuit", "or", "bad", "format", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L342-L351
[ "def", "_check_cargs", "(", "self", ",", "cargs", ")", ":", "if", "not", "all", "(", "isinstance", "(", "i", ",", "tuple", ")", "and", "isinstance", "(", "i", "[", "0", "]", ",", "ClassicalRegister", ")", "and", "isinstance", "(", "i", "[", "1", "]", ",", "int", ")", "for", "i", "in", "cargs", ")", ":", "raise", "QiskitError", "(", "\"carg not (ClassicalRegister, int) tuple\"", ")", "if", "not", "all", "(", "self", ".", "has_register", "(", "i", "[", "0", "]", ")", "for", "i", "in", "cargs", ")", ":", "raise", "QiskitError", "(", "\"register not in this circuit\"", ")", "for", "clbit", "in", "cargs", ":", "clbit", "[", "0", "]", ".", "check_range", "(", "clbit", "[", "1", "]", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumCircuit.decompose
Call a decomposition pass on this circuit, to decompose one level (shallow decompose). Returns: QuantumCircuit: a circuit one level decomposed
qiskit/circuit/quantumcircuit.py
def decompose(self): """Call a decomposition pass on this circuit, to decompose one level (shallow decompose). Returns: QuantumCircuit: a circuit one level decomposed """ from qiskit.transpiler.passes.decompose import Decompose from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.converters.dag_to_circuit import dag_to_circuit pass_ = Decompose() decomposed_dag = pass_.run(circuit_to_dag(self)) return dag_to_circuit(decomposed_dag)
def decompose(self): """Call a decomposition pass on this circuit, to decompose one level (shallow decompose). Returns: QuantumCircuit: a circuit one level decomposed """ from qiskit.transpiler.passes.decompose import Decompose from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.converters.dag_to_circuit import dag_to_circuit pass_ = Decompose() decomposed_dag = pass_.run(circuit_to_dag(self)) return dag_to_circuit(decomposed_dag)
[ "Call", "a", "decomposition", "pass", "on", "this", "circuit", "to", "decompose", "one", "level", "(", "shallow", "decompose", ")", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L363-L375
[ "def", "decompose", "(", "self", ")", ":", "from", "qiskit", ".", "transpiler", ".", "passes", ".", "decompose", "import", "Decompose", "from", "qiskit", ".", "converters", ".", "circuit_to_dag", "import", "circuit_to_dag", "from", "qiskit", ".", "converters", ".", "dag_to_circuit", "import", "dag_to_circuit", "pass_", "=", "Decompose", "(", ")", "decomposed_dag", "=", "pass_", ".", "run", "(", "circuit_to_dag", "(", "self", ")", ")", "return", "dag_to_circuit", "(", "decomposed_dag", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumCircuit._check_compatible_regs
Raise exception if the circuits are defined on incompatible registers
qiskit/circuit/quantumcircuit.py
def _check_compatible_regs(self, rhs): """Raise exception if the circuits are defined on incompatible registers""" list1 = self.qregs + self.cregs list2 = rhs.qregs + rhs.cregs for element1 in list1: for element2 in list2: if element2.name == element1.name: if element1 != element2: raise QiskitError("circuits are not compatible")
def _check_compatible_regs(self, rhs): """Raise exception if the circuits are defined on incompatible registers""" list1 = self.qregs + self.cregs list2 = rhs.qregs + rhs.cregs for element1 in list1: for element2 in list2: if element2.name == element1.name: if element1 != element2: raise QiskitError("circuits are not compatible")
[ "Raise", "exception", "if", "the", "circuits", "are", "defined", "on", "incompatible", "registers" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L377-L385
[ "def", "_check_compatible_regs", "(", "self", ",", "rhs", ")", ":", "list1", "=", "self", ".", "qregs", "+", "self", ".", "cregs", "list2", "=", "rhs", ".", "qregs", "+", "rhs", ".", "cregs", "for", "element1", "in", "list1", ":", "for", "element2", "in", "list2", ":", "if", "element2", ".", "name", "==", "element1", ".", "name", ":", "if", "element1", "!=", "element2", ":", "raise", "QiskitError", "(", "\"circuits are not compatible\"", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumCircuit.qasm
Return OpenQASM string.
qiskit/circuit/quantumcircuit.py
def qasm(self): """Return OpenQASM string.""" string_temp = self.header + "\n" string_temp += self.extension_lib + "\n" for register in self.qregs: string_temp += register.qasm() + "\n" for register in self.cregs: string_temp += register.qasm() + "\n" for instruction, qargs, cargs in self.data: if instruction.name == 'measure': qubit = qargs[0] clbit = cargs[0] string_temp += "%s %s[%d] -> %s[%d];\n" % (instruction.qasm(), qubit[0].name, qubit[1], clbit[0].name, clbit[1]) else: string_temp += "%s %s;\n" % (instruction.qasm(), ",".join(["%s[%d]" % (j[0].name, j[1]) for j in qargs + cargs])) return string_temp
def qasm(self): """Return OpenQASM string.""" string_temp = self.header + "\n" string_temp += self.extension_lib + "\n" for register in self.qregs: string_temp += register.qasm() + "\n" for register in self.cregs: string_temp += register.qasm() + "\n" for instruction, qargs, cargs in self.data: if instruction.name == 'measure': qubit = qargs[0] clbit = cargs[0] string_temp += "%s %s[%d] -> %s[%d];\n" % (instruction.qasm(), qubit[0].name, qubit[1], clbit[0].name, clbit[1]) else: string_temp += "%s %s;\n" % (instruction.qasm(), ",".join(["%s[%d]" % (j[0].name, j[1]) for j in qargs + cargs])) return string_temp
[ "Return", "OpenQASM", "string", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L387-L406
[ "def", "qasm", "(", "self", ")", ":", "string_temp", "=", "self", ".", "header", "+", "\"\\n\"", "string_temp", "+=", "self", ".", "extension_lib", "+", "\"\\n\"", "for", "register", "in", "self", ".", "qregs", ":", "string_temp", "+=", "register", ".", "qasm", "(", ")", "+", "\"\\n\"", "for", "register", "in", "self", ".", "cregs", ":", "string_temp", "+=", "register", ".", "qasm", "(", ")", "+", "\"\\n\"", "for", "instruction", ",", "qargs", ",", "cargs", "in", "self", ".", "data", ":", "if", "instruction", ".", "name", "==", "'measure'", ":", "qubit", "=", "qargs", "[", "0", "]", "clbit", "=", "cargs", "[", "0", "]", "string_temp", "+=", "\"%s %s[%d] -> %s[%d];\\n\"", "%", "(", "instruction", ".", "qasm", "(", ")", ",", "qubit", "[", "0", "]", ".", "name", ",", "qubit", "[", "1", "]", ",", "clbit", "[", "0", "]", ".", "name", ",", "clbit", "[", "1", "]", ")", "else", ":", "string_temp", "+=", "\"%s %s;\\n\"", "%", "(", "instruction", ".", "qasm", "(", ")", ",", "\",\"", ".", "join", "(", "[", "\"%s[%d]\"", "%", "(", "j", "[", "0", "]", ".", "name", ",", "j", "[", "1", "]", ")", "for", "j", "in", "qargs", "+", "cargs", "]", ")", ")", "return", "string_temp" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumCircuit.draw
Draw the quantum circuit Using the output parameter you can specify the format. The choices are: 0. text: ASCII art string 1. latex: high-quality images, but heavy external software dependencies 2. matplotlib: purely in Python with no external dependencies Defaults to an overcomplete basis, in order to not alter gates. Args: scale (float): scale of image to draw (shrink if < 1) filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file. You can refer to the :ref:`Style Dict Doc <style-dict-doc>` for more information on the contents. output (str): Select the output method to use for drawing the circuit. Valid choices are `text`, `latex`, `latex_source`, `mpl`. interactive (bool): when set true show the circuit in a new window (for `mpl` this depends on the matplotlib backend being used supporting this). Note when used with either the `text` or the `latex_source` output type this has no effect and will be silently ignored. line_length (int): sets the length of the lines generated by `text` reverse_bits (bool): When set to True reverse the bit order inside registers for the output visualization. plot_barriers (bool): Enable/disable drawing barriers in the output circuit. Defaults to True. justify (string): Options are `left`, `right` or `none`, if anything else is supplied it defaults to left justified. It refers to where gates should be placed in the output circuit if there is an option. `none` results in each gate being placed in its own column. Currently only supported by text drawer. Returns: PIL.Image or matplotlib.figure or str or TextDrawing: * PIL.Image: (output `latex`) an in-memory representation of the image of the circuit diagram. * matplotlib.figure: (output `mpl`) a matplotlib figure object for the circuit diagram. * str: (output `latex_source`). The LaTeX source code. * TextDrawing: (output `text`). A drawing that can be printed as ascii art Raises: VisualizationError: when an invalid output method is selected
qiskit/circuit/quantumcircuit.py
def draw(self, scale=0.7, filename=None, style=None, output='text', interactive=False, line_length=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw the quantum circuit Using the output parameter you can specify the format. The choices are: 0. text: ASCII art string 1. latex: high-quality images, but heavy external software dependencies 2. matplotlib: purely in Python with no external dependencies Defaults to an overcomplete basis, in order to not alter gates. Args: scale (float): scale of image to draw (shrink if < 1) filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file. You can refer to the :ref:`Style Dict Doc <style-dict-doc>` for more information on the contents. output (str): Select the output method to use for drawing the circuit. Valid choices are `text`, `latex`, `latex_source`, `mpl`. interactive (bool): when set true show the circuit in a new window (for `mpl` this depends on the matplotlib backend being used supporting this). Note when used with either the `text` or the `latex_source` output type this has no effect and will be silently ignored. line_length (int): sets the length of the lines generated by `text` reverse_bits (bool): When set to True reverse the bit order inside registers for the output visualization. plot_barriers (bool): Enable/disable drawing barriers in the output circuit. Defaults to True. justify (string): Options are `left`, `right` or `none`, if anything else is supplied it defaults to left justified. It refers to where gates should be placed in the output circuit if there is an option. `none` results in each gate being placed in its own column. Currently only supported by text drawer. Returns: PIL.Image or matplotlib.figure or str or TextDrawing: * PIL.Image: (output `latex`) an in-memory representation of the image of the circuit diagram. * matplotlib.figure: (output `mpl`) a matplotlib figure object for the circuit diagram. * str: (output `latex_source`). The LaTeX source code. * TextDrawing: (output `text`). A drawing that can be printed as ascii art Raises: VisualizationError: when an invalid output method is selected """ from qiskit.tools import visualization return visualization.circuit_drawer(self, scale=scale, filename=filename, style=style, output=output, interactive=interactive, line_length=line_length, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify)
def draw(self, scale=0.7, filename=None, style=None, output='text', interactive=False, line_length=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw the quantum circuit Using the output parameter you can specify the format. The choices are: 0. text: ASCII art string 1. latex: high-quality images, but heavy external software dependencies 2. matplotlib: purely in Python with no external dependencies Defaults to an overcomplete basis, in order to not alter gates. Args: scale (float): scale of image to draw (shrink if < 1) filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file. You can refer to the :ref:`Style Dict Doc <style-dict-doc>` for more information on the contents. output (str): Select the output method to use for drawing the circuit. Valid choices are `text`, `latex`, `latex_source`, `mpl`. interactive (bool): when set true show the circuit in a new window (for `mpl` this depends on the matplotlib backend being used supporting this). Note when used with either the `text` or the `latex_source` output type this has no effect and will be silently ignored. line_length (int): sets the length of the lines generated by `text` reverse_bits (bool): When set to True reverse the bit order inside registers for the output visualization. plot_barriers (bool): Enable/disable drawing barriers in the output circuit. Defaults to True. justify (string): Options are `left`, `right` or `none`, if anything else is supplied it defaults to left justified. It refers to where gates should be placed in the output circuit if there is an option. `none` results in each gate being placed in its own column. Currently only supported by text drawer. Returns: PIL.Image or matplotlib.figure or str or TextDrawing: * PIL.Image: (output `latex`) an in-memory representation of the image of the circuit diagram. * matplotlib.figure: (output `mpl`) a matplotlib figure object for the circuit diagram. * str: (output `latex_source`). The LaTeX source code. * TextDrawing: (output `text`). A drawing that can be printed as ascii art Raises: VisualizationError: when an invalid output method is selected """ from qiskit.tools import visualization return visualization.circuit_drawer(self, scale=scale, filename=filename, style=style, output=output, interactive=interactive, line_length=line_length, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify)
[ "Draw", "the", "quantum", "circuit" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L408-L467
[ "def", "draw", "(", "self", ",", "scale", "=", "0.7", ",", "filename", "=", "None", ",", "style", "=", "None", ",", "output", "=", "'text'", ",", "interactive", "=", "False", ",", "line_length", "=", "None", ",", "plot_barriers", "=", "True", ",", "reverse_bits", "=", "False", ",", "justify", "=", "None", ")", ":", "from", "qiskit", ".", "tools", "import", "visualization", "return", "visualization", ".", "circuit_drawer", "(", "self", ",", "scale", "=", "scale", ",", "filename", "=", "filename", ",", "style", "=", "style", ",", "output", "=", "output", ",", "interactive", "=", "interactive", ",", "line_length", "=", "line_length", ",", "plot_barriers", "=", "plot_barriers", ",", "reverse_bits", "=", "reverse_bits", ",", "justify", "=", "justify", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumCircuit.size
Returns total number of gate operations in circuit. Returns: int: Total number of gate operations.
qiskit/circuit/quantumcircuit.py
def size(self): """Returns total number of gate operations in circuit. Returns: int: Total number of gate operations. """ gate_ops = 0 for instr, _, _ in self.data: if instr.name not in ['barrier', 'snapshot']: gate_ops += 1 return gate_ops
def size(self): """Returns total number of gate operations in circuit. Returns: int: Total number of gate operations. """ gate_ops = 0 for instr, _, _ in self.data: if instr.name not in ['barrier', 'snapshot']: gate_ops += 1 return gate_ops
[ "Returns", "total", "number", "of", "gate", "operations", "in", "circuit", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L469-L479
[ "def", "size", "(", "self", ")", ":", "gate_ops", "=", "0", "for", "instr", ",", "_", ",", "_", "in", "self", ".", "data", ":", "if", "instr", ".", "name", "not", "in", "[", "'barrier'", ",", "'snapshot'", "]", ":", "gate_ops", "+=", "1", "return", "gate_ops" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumCircuit.depth
Return circuit depth (i.e. length of critical path). This does not include compiler or simulator directives such as 'barrier' or 'snapshot'. Returns: int: Depth of circuit. Notes: The circuit depth and the DAG depth need not bt the same.
qiskit/circuit/quantumcircuit.py
def depth(self): """Return circuit depth (i.e. length of critical path). This does not include compiler or simulator directives such as 'barrier' or 'snapshot'. Returns: int: Depth of circuit. Notes: The circuit depth and the DAG depth need not bt the same. """ # Labels the registers by ints # and then the qubit position in # a register is given by reg_int+qubit_num reg_offset = 0 reg_map = {} for reg in self.qregs+self.cregs: reg_map[reg.name] = reg_offset reg_offset += reg.size # A list that holds the height of each qubit # and classical bit. op_stack = [0]*reg_offset # Here we are playing a modified version of # Tetris where we stack gates, but multi-qubit # gates, or measurements have a block for each # qubit or cbit that are connected by a virtual # line so that they all stacked at the same depth. # Conditional gates act on all cbits in the register # they are conditioned on. # We do not consider barriers or snapshots as # They are transpiler and simulator directives. # The max stack height is the circuit depth. for instr, qargs, cargs in self.data: if instr.name not in ['barrier', 'snapshot']: levels = [] reg_ints = [] for ind, reg in enumerate(qargs+cargs): # Add to the stacks of the qubits and # cbits used in the gate. reg_ints.append(reg_map[reg[0].name]+reg[1]) levels.append(op_stack[reg_ints[ind]] + 1) if instr.control: # Controls operate over all bits in the # classical register they use. cint = reg_map[instr.control[0].name] for off in range(instr.control[0].size): if cint+off not in reg_ints: reg_ints.append(cint+off) levels.append(op_stack[cint+off]+1) max_level = max(levels) for ind in reg_ints: op_stack[ind] = max_level return max(op_stack)
def depth(self): """Return circuit depth (i.e. length of critical path). This does not include compiler or simulator directives such as 'barrier' or 'snapshot'. Returns: int: Depth of circuit. Notes: The circuit depth and the DAG depth need not bt the same. """ # Labels the registers by ints # and then the qubit position in # a register is given by reg_int+qubit_num reg_offset = 0 reg_map = {} for reg in self.qregs+self.cregs: reg_map[reg.name] = reg_offset reg_offset += reg.size # A list that holds the height of each qubit # and classical bit. op_stack = [0]*reg_offset # Here we are playing a modified version of # Tetris where we stack gates, but multi-qubit # gates, or measurements have a block for each # qubit or cbit that are connected by a virtual # line so that they all stacked at the same depth. # Conditional gates act on all cbits in the register # they are conditioned on. # We do not consider barriers or snapshots as # They are transpiler and simulator directives. # The max stack height is the circuit depth. for instr, qargs, cargs in self.data: if instr.name not in ['barrier', 'snapshot']: levels = [] reg_ints = [] for ind, reg in enumerate(qargs+cargs): # Add to the stacks of the qubits and # cbits used in the gate. reg_ints.append(reg_map[reg[0].name]+reg[1]) levels.append(op_stack[reg_ints[ind]] + 1) if instr.control: # Controls operate over all bits in the # classical register they use. cint = reg_map[instr.control[0].name] for off in range(instr.control[0].size): if cint+off not in reg_ints: reg_ints.append(cint+off) levels.append(op_stack[cint+off]+1) max_level = max(levels) for ind in reg_ints: op_stack[ind] = max_level return max(op_stack)
[ "Return", "circuit", "depth", "(", "i", ".", "e", ".", "length", "of", "critical", "path", ")", ".", "This", "does", "not", "include", "compiler", "or", "simulator", "directives", "such", "as", "barrier", "or", "snapshot", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L481-L536
[ "def", "depth", "(", "self", ")", ":", "# Labels the registers by ints", "# and then the qubit position in", "# a register is given by reg_int+qubit_num", "reg_offset", "=", "0", "reg_map", "=", "{", "}", "for", "reg", "in", "self", ".", "qregs", "+", "self", ".", "cregs", ":", "reg_map", "[", "reg", ".", "name", "]", "=", "reg_offset", "reg_offset", "+=", "reg", ".", "size", "# A list that holds the height of each qubit", "# and classical bit.", "op_stack", "=", "[", "0", "]", "*", "reg_offset", "# Here we are playing a modified version of", "# Tetris where we stack gates, but multi-qubit", "# gates, or measurements have a block for each", "# qubit or cbit that are connected by a virtual", "# line so that they all stacked at the same depth.", "# Conditional gates act on all cbits in the register", "# they are conditioned on.", "# We do not consider barriers or snapshots as", "# They are transpiler and simulator directives.", "# The max stack height is the circuit depth.", "for", "instr", ",", "qargs", ",", "cargs", "in", "self", ".", "data", ":", "if", "instr", ".", "name", "not", "in", "[", "'barrier'", ",", "'snapshot'", "]", ":", "levels", "=", "[", "]", "reg_ints", "=", "[", "]", "for", "ind", ",", "reg", "in", "enumerate", "(", "qargs", "+", "cargs", ")", ":", "# Add to the stacks of the qubits and", "# cbits used in the gate.", "reg_ints", ".", "append", "(", "reg_map", "[", "reg", "[", "0", "]", ".", "name", "]", "+", "reg", "[", "1", "]", ")", "levels", ".", "append", "(", "op_stack", "[", "reg_ints", "[", "ind", "]", "]", "+", "1", ")", "if", "instr", ".", "control", ":", "# Controls operate over all bits in the", "# classical register they use.", "cint", "=", "reg_map", "[", "instr", ".", "control", "[", "0", "]", ".", "name", "]", "for", "off", "in", "range", "(", "instr", ".", "control", "[", "0", "]", ".", "size", ")", ":", "if", "cint", "+", "off", "not", "in", "reg_ints", ":", "reg_ints", ".", "append", "(", "cint", "+", "off", ")", "levels", ".", "append", "(", "op_stack", "[", "cint", "+", "off", "]", "+", "1", ")", "max_level", "=", "max", "(", "levels", ")", "for", "ind", "in", "reg_ints", ":", "op_stack", "[", "ind", "]", "=", "max_level", "return", "max", "(", "op_stack", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumCircuit.width
Return number of qubits plus clbits in circuit. Returns: int: Width of circuit.
qiskit/circuit/quantumcircuit.py
def width(self): """Return number of qubits plus clbits in circuit. Returns: int: Width of circuit. """ return sum(reg.size for reg in self.qregs+self.cregs)
def width(self): """Return number of qubits plus clbits in circuit. Returns: int: Width of circuit. """ return sum(reg.size for reg in self.qregs+self.cregs)
[ "Return", "number", "of", "qubits", "plus", "clbits", "in", "circuit", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L538-L545
[ "def", "width", "(", "self", ")", ":", "return", "sum", "(", "reg", ".", "size", "for", "reg", "in", "self", ".", "qregs", "+", "self", ".", "cregs", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumCircuit.count_ops
Count each operation kind in the circuit. Returns: dict: a breakdown of how many operations of each kind.
qiskit/circuit/quantumcircuit.py
def count_ops(self): """Count each operation kind in the circuit. Returns: dict: a breakdown of how many operations of each kind. """ count_ops = {} for instr, _, _ in self.data: if instr.name in count_ops.keys(): count_ops[instr.name] += 1 else: count_ops[instr.name] = 1 return count_ops
def count_ops(self): """Count each operation kind in the circuit. Returns: dict: a breakdown of how many operations of each kind. """ count_ops = {} for instr, _, _ in self.data: if instr.name in count_ops.keys(): count_ops[instr.name] += 1 else: count_ops[instr.name] = 1 return count_ops
[ "Count", "each", "operation", "kind", "in", "the", "circuit", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L547-L559
[ "def", "count_ops", "(", "self", ")", ":", "count_ops", "=", "{", "}", "for", "instr", ",", "_", ",", "_", "in", "self", ".", "data", ":", "if", "instr", ".", "name", "in", "count_ops", ".", "keys", "(", ")", ":", "count_ops", "[", "instr", ".", "name", "]", "+=", "1", "else", ":", "count_ops", "[", "instr", ".", "name", "]", "=", "1", "return", "count_ops" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumCircuit.num_connected_components
How many non-entangled subcircuits can the circuit be factored to. Args: unitary_only (bool): Compute only unitary part of graph. Returns: int: Number of connected components in circuit.
qiskit/circuit/quantumcircuit.py
def num_connected_components(self, unitary_only=False): """How many non-entangled subcircuits can the circuit be factored to. Args: unitary_only (bool): Compute only unitary part of graph. Returns: int: Number of connected components in circuit. """ # Convert registers to ints (as done in depth). reg_offset = 0 reg_map = {} if unitary_only: regs = self.qregs else: regs = self.qregs+self.cregs for reg in regs: reg_map[reg.name] = reg_offset reg_offset += reg.size # Start with each qubit or cbit being its own subgraph. sub_graphs = [[bit] for bit in range(reg_offset)] num_sub_graphs = len(sub_graphs) # Here we are traversing the gates and looking to see # which of the sub_graphs the gate joins together. for instr, qargs, cargs in self.data: if unitary_only: args = qargs num_qargs = len(args) else: args = qargs+cargs num_qargs = len(args) + (1 if instr.control else 0) if num_qargs >= 2 and instr.name not in ['barrier', 'snapshot']: graphs_touched = [] num_touched = 0 # Controls necessarily join all the cbits in the # register that they use. if instr.control and not unitary_only: creg = instr.control[0] creg_int = reg_map[creg.name] for coff in range(creg.size): temp_int = creg_int+coff for k in range(num_sub_graphs): if temp_int in sub_graphs[k]: graphs_touched.append(k) num_touched += 1 break for item in args: reg_int = reg_map[item[0].name]+item[1] for k in range(num_sub_graphs): if reg_int in sub_graphs[k]: if k not in graphs_touched: graphs_touched.append(k) num_touched += 1 break # If the gate touches more than one subgraph # join those graphs together and return # reduced number of subgraphs if num_touched > 1: connections = [] for idx in graphs_touched: connections.extend(sub_graphs[idx]) _sub_graphs = [] for idx in range(num_sub_graphs): if idx not in graphs_touched: _sub_graphs.append(sub_graphs[idx]) _sub_graphs.append(connections) sub_graphs = _sub_graphs num_sub_graphs -= (num_touched-1) # Cannot go lower than one so break if num_sub_graphs == 1: break return num_sub_graphs
def num_connected_components(self, unitary_only=False): """How many non-entangled subcircuits can the circuit be factored to. Args: unitary_only (bool): Compute only unitary part of graph. Returns: int: Number of connected components in circuit. """ # Convert registers to ints (as done in depth). reg_offset = 0 reg_map = {} if unitary_only: regs = self.qregs else: regs = self.qregs+self.cregs for reg in regs: reg_map[reg.name] = reg_offset reg_offset += reg.size # Start with each qubit or cbit being its own subgraph. sub_graphs = [[bit] for bit in range(reg_offset)] num_sub_graphs = len(sub_graphs) # Here we are traversing the gates and looking to see # which of the sub_graphs the gate joins together. for instr, qargs, cargs in self.data: if unitary_only: args = qargs num_qargs = len(args) else: args = qargs+cargs num_qargs = len(args) + (1 if instr.control else 0) if num_qargs >= 2 and instr.name not in ['barrier', 'snapshot']: graphs_touched = [] num_touched = 0 # Controls necessarily join all the cbits in the # register that they use. if instr.control and not unitary_only: creg = instr.control[0] creg_int = reg_map[creg.name] for coff in range(creg.size): temp_int = creg_int+coff for k in range(num_sub_graphs): if temp_int in sub_graphs[k]: graphs_touched.append(k) num_touched += 1 break for item in args: reg_int = reg_map[item[0].name]+item[1] for k in range(num_sub_graphs): if reg_int in sub_graphs[k]: if k not in graphs_touched: graphs_touched.append(k) num_touched += 1 break # If the gate touches more than one subgraph # join those graphs together and return # reduced number of subgraphs if num_touched > 1: connections = [] for idx in graphs_touched: connections.extend(sub_graphs[idx]) _sub_graphs = [] for idx in range(num_sub_graphs): if idx not in graphs_touched: _sub_graphs.append(sub_graphs[idx]) _sub_graphs.append(connections) sub_graphs = _sub_graphs num_sub_graphs -= (num_touched-1) # Cannot go lower than one so break if num_sub_graphs == 1: break return num_sub_graphs
[ "How", "many", "non", "-", "entangled", "subcircuits", "can", "the", "circuit", "be", "factored", "to", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L561-L639
[ "def", "num_connected_components", "(", "self", ",", "unitary_only", "=", "False", ")", ":", "# Convert registers to ints (as done in depth).", "reg_offset", "=", "0", "reg_map", "=", "{", "}", "if", "unitary_only", ":", "regs", "=", "self", ".", "qregs", "else", ":", "regs", "=", "self", ".", "qregs", "+", "self", ".", "cregs", "for", "reg", "in", "regs", ":", "reg_map", "[", "reg", ".", "name", "]", "=", "reg_offset", "reg_offset", "+=", "reg", ".", "size", "# Start with each qubit or cbit being its own subgraph.", "sub_graphs", "=", "[", "[", "bit", "]", "for", "bit", "in", "range", "(", "reg_offset", ")", "]", "num_sub_graphs", "=", "len", "(", "sub_graphs", ")", "# Here we are traversing the gates and looking to see", "# which of the sub_graphs the gate joins together.", "for", "instr", ",", "qargs", ",", "cargs", "in", "self", ".", "data", ":", "if", "unitary_only", ":", "args", "=", "qargs", "num_qargs", "=", "len", "(", "args", ")", "else", ":", "args", "=", "qargs", "+", "cargs", "num_qargs", "=", "len", "(", "args", ")", "+", "(", "1", "if", "instr", ".", "control", "else", "0", ")", "if", "num_qargs", ">=", "2", "and", "instr", ".", "name", "not", "in", "[", "'barrier'", ",", "'snapshot'", "]", ":", "graphs_touched", "=", "[", "]", "num_touched", "=", "0", "# Controls necessarily join all the cbits in the", "# register that they use.", "if", "instr", ".", "control", "and", "not", "unitary_only", ":", "creg", "=", "instr", ".", "control", "[", "0", "]", "creg_int", "=", "reg_map", "[", "creg", ".", "name", "]", "for", "coff", "in", "range", "(", "creg", ".", "size", ")", ":", "temp_int", "=", "creg_int", "+", "coff", "for", "k", "in", "range", "(", "num_sub_graphs", ")", ":", "if", "temp_int", "in", "sub_graphs", "[", "k", "]", ":", "graphs_touched", ".", "append", "(", "k", ")", "num_touched", "+=", "1", "break", "for", "item", "in", "args", ":", "reg_int", "=", "reg_map", "[", "item", "[", "0", "]", ".", "name", "]", "+", "item", "[", "1", "]", "for", "k", "in", "range", "(", "num_sub_graphs", ")", ":", "if", "reg_int", "in", "sub_graphs", "[", "k", "]", ":", "if", "k", "not", "in", "graphs_touched", ":", "graphs_touched", ".", "append", "(", "k", ")", "num_touched", "+=", "1", "break", "# If the gate touches more than one subgraph", "# join those graphs together and return", "# reduced number of subgraphs", "if", "num_touched", ">", "1", ":", "connections", "=", "[", "]", "for", "idx", "in", "graphs_touched", ":", "connections", ".", "extend", "(", "sub_graphs", "[", "idx", "]", ")", "_sub_graphs", "=", "[", "]", "for", "idx", "in", "range", "(", "num_sub_graphs", ")", ":", "if", "idx", "not", "in", "graphs_touched", ":", "_sub_graphs", ".", "append", "(", "sub_graphs", "[", "idx", "]", ")", "_sub_graphs", ".", "append", "(", "connections", ")", "sub_graphs", "=", "_sub_graphs", "num_sub_graphs", "-=", "(", "num_touched", "-", "1", ")", "# Cannot go lower than one so break", "if", "num_sub_graphs", "==", "1", ":", "break", "return", "num_sub_graphs" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumCircuit.bind_parameters
Assign parameters to values yielding a new circuit. Args: value_dict (dict): {parameter: value, ...} Raises: QiskitError: If value_dict contains parameters not present in the circuit Returns: QuantumCircuit: copy of self with assignment substitution.
qiskit/circuit/quantumcircuit.py
def bind_parameters(self, value_dict): """Assign parameters to values yielding a new circuit. Args: value_dict (dict): {parameter: value, ...} Raises: QiskitError: If value_dict contains parameters not present in the circuit Returns: QuantumCircuit: copy of self with assignment substitution. """ new_circuit = self.copy() if value_dict.keys() > self.parameters: raise QiskitError('Cannot bind parameters ({}) not present in the circuit.'.format( [str(p) for p in value_dict.keys() - self.parameters])) for parameter, value in value_dict.items(): new_circuit._bind_parameter(parameter, value) # clear evaluated expressions for parameter in value_dict: del new_circuit._parameter_table[parameter] return new_circuit
def bind_parameters(self, value_dict): """Assign parameters to values yielding a new circuit. Args: value_dict (dict): {parameter: value, ...} Raises: QiskitError: If value_dict contains parameters not present in the circuit Returns: QuantumCircuit: copy of self with assignment substitution. """ new_circuit = self.copy() if value_dict.keys() > self.parameters: raise QiskitError('Cannot bind parameters ({}) not present in the circuit.'.format( [str(p) for p in value_dict.keys() - self.parameters])) for parameter, value in value_dict.items(): new_circuit._bind_parameter(parameter, value) # clear evaluated expressions for parameter in value_dict: del new_circuit._parameter_table[parameter] return new_circuit
[ "Assign", "parameters", "to", "values", "yielding", "a", "new", "circuit", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L700-L723
[ "def", "bind_parameters", "(", "self", ",", "value_dict", ")", ":", "new_circuit", "=", "self", ".", "copy", "(", ")", "if", "value_dict", ".", "keys", "(", ")", ">", "self", ".", "parameters", ":", "raise", "QiskitError", "(", "'Cannot bind parameters ({}) not present in the circuit.'", ".", "format", "(", "[", "str", "(", "p", ")", "for", "p", "in", "value_dict", ".", "keys", "(", ")", "-", "self", ".", "parameters", "]", ")", ")", "for", "parameter", ",", "value", "in", "value_dict", ".", "items", "(", ")", ":", "new_circuit", ".", "_bind_parameter", "(", "parameter", ",", "value", ")", "# clear evaluated expressions", "for", "parameter", "in", "value_dict", ":", "del", "new_circuit", ".", "_parameter_table", "[", "parameter", "]", "return", "new_circuit" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumCircuit._bind_parameter
Assigns a parameter value to matching instructions in-place.
qiskit/circuit/quantumcircuit.py
def _bind_parameter(self, parameter, value): """Assigns a parameter value to matching instructions in-place.""" for (instr, param_index) in self._parameter_table[parameter]: instr.params[param_index] = value
def _bind_parameter(self, parameter, value): """Assigns a parameter value to matching instructions in-place.""" for (instr, param_index) in self._parameter_table[parameter]: instr.params[param_index] = value
[ "Assigns", "a", "parameter", "value", "to", "matching", "instructions", "in", "-", "place", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L725-L728
[ "def", "_bind_parameter", "(", "self", ",", "parameter", ",", "value", ")", ":", "for", "(", "instr", ",", "param_index", ")", "in", "self", ".", "_parameter_table", "[", "parameter", "]", ":", "instr", ".", "params", "[", "param_index", "]", "=", "value" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
pulse_drawer
Plot the interpolated envelope of pulse Args: samples (ndarray): Data points of complex pulse envelope. duration (int): Pulse length (number of points). dt (float): Time interval of samples. interp_method (str): Method of interpolation (set `None` for turn off the interpolation). filename (str): Name required to save pulse image. interactive (bool): When set true show the circuit in a new window (this depends on the matplotlib backend being used supporting this). dpi (int): Resolution of saved image. nop (int): Data points for interpolation. size (tuple): Size of figure. Returns: matplotlib.figure: A matplotlib figure object for the pulse envelope. Raises: ImportError: when the output methods requieres non-installed libraries. QiskitError: when invalid interpolation method is specified.
qiskit/visualization/pulse_visualization.py
def pulse_drawer(samples, duration, dt=None, interp_method='None', filename=None, interactive=False, dpi=150, nop=1000, size=(6, 5)): """Plot the interpolated envelope of pulse Args: samples (ndarray): Data points of complex pulse envelope. duration (int): Pulse length (number of points). dt (float): Time interval of samples. interp_method (str): Method of interpolation (set `None` for turn off the interpolation). filename (str): Name required to save pulse image. interactive (bool): When set true show the circuit in a new window (this depends on the matplotlib backend being used supporting this). dpi (int): Resolution of saved image. nop (int): Data points for interpolation. size (tuple): Size of figure. Returns: matplotlib.figure: A matplotlib figure object for the pulse envelope. Raises: ImportError: when the output methods requieres non-installed libraries. QiskitError: when invalid interpolation method is specified. """ try: from matplotlib import pyplot as plt except ImportError: raise ImportError('pulse_drawer need matplotlib. ' 'Run "pip install matplotlib" before.') if dt: _dt = dt else: _dt = 1 re_y = np.real(samples) im_y = np.imag(samples) image = plt.figure(figsize=size) ax0 = image.add_subplot(111) if interp_method == 'CubicSpline': # spline interpolation, use mid-point of dt time = np.arange(0, duration + 1) * _dt + 0.5 * _dt cs_ry = CubicSpline(time[:-1], re_y) cs_iy = CubicSpline(time[:-1], im_y) _time = np.linspace(0, duration * _dt, nop) _re_y = cs_ry(_time) _im_y = cs_iy(_time) elif interp_method == 'None': # pseudo-DAC output time = np.arange(0, duration + 1) * _dt _time = np.r_[time[0], np.repeat(time[1:-1], 2), time[-1]] _re_y = np.repeat(re_y, 2) _im_y = np.repeat(im_y, 2) else: raise QiskitError('Invalid interpolation method "%s"' % interp_method) # plot ax0.fill_between(x=_time, y1=_re_y, y2=np.zeros_like(_time), facecolor='red', alpha=0.3, edgecolor='red', linewidth=1.5, label='real part') ax0.fill_between(x=_time, y1=_im_y, y2=np.zeros_like(_time), facecolor='blue', alpha=0.3, edgecolor='blue', linewidth=1.5, label='imaginary part') ax0.set_xlim(0, duration * _dt) ax0.grid(b=True, linestyle='-') ax0.legend(bbox_to_anchor=(0.5, 1.00), loc='lower center', ncol=2, frameon=False, fontsize=14) if filename: image.savefig(filename, dpi=dpi, bbox_inches='tight') plt.close(image) if image and interactive: plt.show(image) return image
def pulse_drawer(samples, duration, dt=None, interp_method='None', filename=None, interactive=False, dpi=150, nop=1000, size=(6, 5)): """Plot the interpolated envelope of pulse Args: samples (ndarray): Data points of complex pulse envelope. duration (int): Pulse length (number of points). dt (float): Time interval of samples. interp_method (str): Method of interpolation (set `None` for turn off the interpolation). filename (str): Name required to save pulse image. interactive (bool): When set true show the circuit in a new window (this depends on the matplotlib backend being used supporting this). dpi (int): Resolution of saved image. nop (int): Data points for interpolation. size (tuple): Size of figure. Returns: matplotlib.figure: A matplotlib figure object for the pulse envelope. Raises: ImportError: when the output methods requieres non-installed libraries. QiskitError: when invalid interpolation method is specified. """ try: from matplotlib import pyplot as plt except ImportError: raise ImportError('pulse_drawer need matplotlib. ' 'Run "pip install matplotlib" before.') if dt: _dt = dt else: _dt = 1 re_y = np.real(samples) im_y = np.imag(samples) image = plt.figure(figsize=size) ax0 = image.add_subplot(111) if interp_method == 'CubicSpline': # spline interpolation, use mid-point of dt time = np.arange(0, duration + 1) * _dt + 0.5 * _dt cs_ry = CubicSpline(time[:-1], re_y) cs_iy = CubicSpline(time[:-1], im_y) _time = np.linspace(0, duration * _dt, nop) _re_y = cs_ry(_time) _im_y = cs_iy(_time) elif interp_method == 'None': # pseudo-DAC output time = np.arange(0, duration + 1) * _dt _time = np.r_[time[0], np.repeat(time[1:-1], 2), time[-1]] _re_y = np.repeat(re_y, 2) _im_y = np.repeat(im_y, 2) else: raise QiskitError('Invalid interpolation method "%s"' % interp_method) # plot ax0.fill_between(x=_time, y1=_re_y, y2=np.zeros_like(_time), facecolor='red', alpha=0.3, edgecolor='red', linewidth=1.5, label='real part') ax0.fill_between(x=_time, y1=_im_y, y2=np.zeros_like(_time), facecolor='blue', alpha=0.3, edgecolor='blue', linewidth=1.5, label='imaginary part') ax0.set_xlim(0, duration * _dt) ax0.grid(b=True, linestyle='-') ax0.legend(bbox_to_anchor=(0.5, 1.00), loc='lower center', ncol=2, frameon=False, fontsize=14) if filename: image.savefig(filename, dpi=dpi, bbox_inches='tight') plt.close(image) if image and interactive: plt.show(image) return image
[ "Plot", "the", "interpolated", "envelope", "of", "pulse" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/pulse_visualization.py#L20-L103
[ "def", "pulse_drawer", "(", "samples", ",", "duration", ",", "dt", "=", "None", ",", "interp_method", "=", "'None'", ",", "filename", "=", "None", ",", "interactive", "=", "False", ",", "dpi", "=", "150", ",", "nop", "=", "1000", ",", "size", "=", "(", "6", ",", "5", ")", ")", ":", "try", ":", "from", "matplotlib", "import", "pyplot", "as", "plt", "except", "ImportError", ":", "raise", "ImportError", "(", "'pulse_drawer need matplotlib. '", "'Run \"pip install matplotlib\" before.'", ")", "if", "dt", ":", "_dt", "=", "dt", "else", ":", "_dt", "=", "1", "re_y", "=", "np", ".", "real", "(", "samples", ")", "im_y", "=", "np", ".", "imag", "(", "samples", ")", "image", "=", "plt", ".", "figure", "(", "figsize", "=", "size", ")", "ax0", "=", "image", ".", "add_subplot", "(", "111", ")", "if", "interp_method", "==", "'CubicSpline'", ":", "# spline interpolation, use mid-point of dt", "time", "=", "np", ".", "arange", "(", "0", ",", "duration", "+", "1", ")", "*", "_dt", "+", "0.5", "*", "_dt", "cs_ry", "=", "CubicSpline", "(", "time", "[", ":", "-", "1", "]", ",", "re_y", ")", "cs_iy", "=", "CubicSpline", "(", "time", "[", ":", "-", "1", "]", ",", "im_y", ")", "_time", "=", "np", ".", "linspace", "(", "0", ",", "duration", "*", "_dt", ",", "nop", ")", "_re_y", "=", "cs_ry", "(", "_time", ")", "_im_y", "=", "cs_iy", "(", "_time", ")", "elif", "interp_method", "==", "'None'", ":", "# pseudo-DAC output", "time", "=", "np", ".", "arange", "(", "0", ",", "duration", "+", "1", ")", "*", "_dt", "_time", "=", "np", ".", "r_", "[", "time", "[", "0", "]", ",", "np", ".", "repeat", "(", "time", "[", "1", ":", "-", "1", "]", ",", "2", ")", ",", "time", "[", "-", "1", "]", "]", "_re_y", "=", "np", ".", "repeat", "(", "re_y", ",", "2", ")", "_im_y", "=", "np", ".", "repeat", "(", "im_y", ",", "2", ")", "else", ":", "raise", "QiskitError", "(", "'Invalid interpolation method \"%s\"'", "%", "interp_method", ")", "# plot", "ax0", ".", "fill_between", "(", "x", "=", "_time", ",", "y1", "=", "_re_y", ",", "y2", "=", "np", ".", "zeros_like", "(", "_time", ")", ",", "facecolor", "=", "'red'", ",", "alpha", "=", "0.3", ",", "edgecolor", "=", "'red'", ",", "linewidth", "=", "1.5", ",", "label", "=", "'real part'", ")", "ax0", ".", "fill_between", "(", "x", "=", "_time", ",", "y1", "=", "_im_y", ",", "y2", "=", "np", ".", "zeros_like", "(", "_time", ")", ",", "facecolor", "=", "'blue'", ",", "alpha", "=", "0.3", ",", "edgecolor", "=", "'blue'", ",", "linewidth", "=", "1.5", ",", "label", "=", "'imaginary part'", ")", "ax0", ".", "set_xlim", "(", "0", ",", "duration", "*", "_dt", ")", "ax0", ".", "grid", "(", "b", "=", "True", ",", "linestyle", "=", "'-'", ")", "ax0", ".", "legend", "(", "bbox_to_anchor", "=", "(", "0.5", ",", "1.00", ")", ",", "loc", "=", "'lower center'", ",", "ncol", "=", "2", ",", "frameon", "=", "False", ",", "fontsize", "=", "14", ")", "if", "filename", ":", "image", ".", "savefig", "(", "filename", ",", "dpi", "=", "dpi", ",", "bbox_inches", "=", "'tight'", ")", "plt", ".", "close", "(", "image", ")", "if", "image", "and", "interactive", ":", "plt", ".", "show", "(", "image", ")", "return", "image" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_search_forward_n_swaps
Search for SWAPs which allow for application of largest number of gates. Arguments: layout (Layout): Map from virtual qubit index to physical qubit index. gates (list): Gates to be mapped. coupling_map (CouplingMap): CouplingMap of the target backend. depth (int): Number of SWAP layers to search before choosing a result. width (int): Number of SWAPs to consider at each layer. Returns: dict: Describes solution step found. layout (Layout): Virtual to physical qubit map after SWAPs. gates_remaining (list): Gates that could not be mapped. gates_mapped (list): Gates that were mapped, including added SWAPs.
qiskit/transpiler/passes/mapping/lookahead_swap.py
def _search_forward_n_swaps(layout, gates, coupling_map, depth=SEARCH_DEPTH, width=SEARCH_WIDTH): """Search for SWAPs which allow for application of largest number of gates. Arguments: layout (Layout): Map from virtual qubit index to physical qubit index. gates (list): Gates to be mapped. coupling_map (CouplingMap): CouplingMap of the target backend. depth (int): Number of SWAP layers to search before choosing a result. width (int): Number of SWAPs to consider at each layer. Returns: dict: Describes solution step found. layout (Layout): Virtual to physical qubit map after SWAPs. gates_remaining (list): Gates that could not be mapped. gates_mapped (list): Gates that were mapped, including added SWAPs. """ gates_mapped, gates_remaining = _map_free_gates(layout, gates, coupling_map) base_step = {'layout': layout, 'swaps_added': 0, 'gates_mapped': gates_mapped, 'gates_remaining': gates_remaining} if not gates_remaining or depth == 0: return base_step possible_swaps = coupling_map.get_edges() def _score_swap(swap): """Calculate the relative score for a given SWAP.""" trial_layout = layout.copy() trial_layout.swap(*swap) return _calc_layout_distance(gates, coupling_map, trial_layout) ranked_swaps = sorted(possible_swaps, key=_score_swap) best_swap, best_step = None, None for swap in ranked_swaps[:width]: trial_layout = layout.copy() trial_layout.swap(*swap) next_step = _search_forward_n_swaps(trial_layout, gates_remaining, coupling_map, depth - 1, width) # ranked_swaps already sorted by distance, so distance is the tie-breaker. if best_swap is None or _score_step(next_step) > _score_step(best_step): best_swap, best_step = swap, next_step best_swap_gate = _swap_ops_from_edge(best_swap, layout) return { 'layout': best_step['layout'], 'swaps_added': 1 + best_step['swaps_added'], 'gates_remaining': best_step['gates_remaining'], 'gates_mapped': gates_mapped + best_swap_gate + best_step['gates_mapped'], }
def _search_forward_n_swaps(layout, gates, coupling_map, depth=SEARCH_DEPTH, width=SEARCH_WIDTH): """Search for SWAPs which allow for application of largest number of gates. Arguments: layout (Layout): Map from virtual qubit index to physical qubit index. gates (list): Gates to be mapped. coupling_map (CouplingMap): CouplingMap of the target backend. depth (int): Number of SWAP layers to search before choosing a result. width (int): Number of SWAPs to consider at each layer. Returns: dict: Describes solution step found. layout (Layout): Virtual to physical qubit map after SWAPs. gates_remaining (list): Gates that could not be mapped. gates_mapped (list): Gates that were mapped, including added SWAPs. """ gates_mapped, gates_remaining = _map_free_gates(layout, gates, coupling_map) base_step = {'layout': layout, 'swaps_added': 0, 'gates_mapped': gates_mapped, 'gates_remaining': gates_remaining} if not gates_remaining or depth == 0: return base_step possible_swaps = coupling_map.get_edges() def _score_swap(swap): """Calculate the relative score for a given SWAP.""" trial_layout = layout.copy() trial_layout.swap(*swap) return _calc_layout_distance(gates, coupling_map, trial_layout) ranked_swaps = sorted(possible_swaps, key=_score_swap) best_swap, best_step = None, None for swap in ranked_swaps[:width]: trial_layout = layout.copy() trial_layout.swap(*swap) next_step = _search_forward_n_swaps(trial_layout, gates_remaining, coupling_map, depth - 1, width) # ranked_swaps already sorted by distance, so distance is the tie-breaker. if best_swap is None or _score_step(next_step) > _score_step(best_step): best_swap, best_step = swap, next_step best_swap_gate = _swap_ops_from_edge(best_swap, layout) return { 'layout': best_step['layout'], 'swaps_added': 1 + best_step['swaps_added'], 'gates_remaining': best_step['gates_remaining'], 'gates_mapped': gates_mapped + best_swap_gate + best_step['gates_mapped'], }
[ "Search", "for", "SWAPs", "which", "allow", "for", "application", "of", "largest", "number", "of", "gates", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/lookahead_swap.py#L126-L181
[ "def", "_search_forward_n_swaps", "(", "layout", ",", "gates", ",", "coupling_map", ",", "depth", "=", "SEARCH_DEPTH", ",", "width", "=", "SEARCH_WIDTH", ")", ":", "gates_mapped", ",", "gates_remaining", "=", "_map_free_gates", "(", "layout", ",", "gates", ",", "coupling_map", ")", "base_step", "=", "{", "'layout'", ":", "layout", ",", "'swaps_added'", ":", "0", ",", "'gates_mapped'", ":", "gates_mapped", ",", "'gates_remaining'", ":", "gates_remaining", "}", "if", "not", "gates_remaining", "or", "depth", "==", "0", ":", "return", "base_step", "possible_swaps", "=", "coupling_map", ".", "get_edges", "(", ")", "def", "_score_swap", "(", "swap", ")", ":", "\"\"\"Calculate the relative score for a given SWAP.\"\"\"", "trial_layout", "=", "layout", ".", "copy", "(", ")", "trial_layout", ".", "swap", "(", "*", "swap", ")", "return", "_calc_layout_distance", "(", "gates", ",", "coupling_map", ",", "trial_layout", ")", "ranked_swaps", "=", "sorted", "(", "possible_swaps", ",", "key", "=", "_score_swap", ")", "best_swap", ",", "best_step", "=", "None", ",", "None", "for", "swap", "in", "ranked_swaps", "[", ":", "width", "]", ":", "trial_layout", "=", "layout", ".", "copy", "(", ")", "trial_layout", ".", "swap", "(", "*", "swap", ")", "next_step", "=", "_search_forward_n_swaps", "(", "trial_layout", ",", "gates_remaining", ",", "coupling_map", ",", "depth", "-", "1", ",", "width", ")", "# ranked_swaps already sorted by distance, so distance is the tie-breaker.", "if", "best_swap", "is", "None", "or", "_score_step", "(", "next_step", ")", ">", "_score_step", "(", "best_step", ")", ":", "best_swap", ",", "best_step", "=", "swap", ",", "next_step", "best_swap_gate", "=", "_swap_ops_from_edge", "(", "best_swap", ",", "layout", ")", "return", "{", "'layout'", ":", "best_step", "[", "'layout'", "]", ",", "'swaps_added'", ":", "1", "+", "best_step", "[", "'swaps_added'", "]", ",", "'gates_remaining'", ":", "best_step", "[", "'gates_remaining'", "]", ",", "'gates_mapped'", ":", "gates_mapped", "+", "best_swap_gate", "+", "best_step", "[", "'gates_mapped'", "]", ",", "}" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_map_free_gates
Map all gates that can be executed with the current layout. Args: layout (Layout): Map from virtual qubit index to physical qubit index. gates (list): Gates to be mapped. coupling_map (CouplingMap): CouplingMap for target device topology. Returns: tuple: mapped_gates (list): ops for gates that can be executed, mapped onto layout. remaining_gates (list): gates that cannot be executed on the layout.
qiskit/transpiler/passes/mapping/lookahead_swap.py
def _map_free_gates(layout, gates, coupling_map): """Map all gates that can be executed with the current layout. Args: layout (Layout): Map from virtual qubit index to physical qubit index. gates (list): Gates to be mapped. coupling_map (CouplingMap): CouplingMap for target device topology. Returns: tuple: mapped_gates (list): ops for gates that can be executed, mapped onto layout. remaining_gates (list): gates that cannot be executed on the layout. """ blocked_qubits = set() mapped_gates = [] remaining_gates = [] for gate in gates: # Gates without a partition (barrier, snapshot, save, load, noise) may # still have associated qubits. Look for them in the qargs. if not gate['partition']: qubits = [n for n in gate['graph'].nodes() if n.type == 'op'][0].qargs if not qubits: continue if blocked_qubits.intersection(qubits): blocked_qubits.update(qubits) remaining_gates.append(gate) else: mapped_gate = _transform_gate_for_layout(gate, layout) mapped_gates.append(mapped_gate) continue qubits = gate['partition'][0] if blocked_qubits.intersection(qubits): blocked_qubits.update(qubits) remaining_gates.append(gate) elif len(qubits) == 1: mapped_gate = _transform_gate_for_layout(gate, layout) mapped_gates.append(mapped_gate) elif coupling_map.distance(*[layout[q] for q in qubits]) == 1: mapped_gate = _transform_gate_for_layout(gate, layout) mapped_gates.append(mapped_gate) else: blocked_qubits.update(qubits) remaining_gates.append(gate) return mapped_gates, remaining_gates
def _map_free_gates(layout, gates, coupling_map): """Map all gates that can be executed with the current layout. Args: layout (Layout): Map from virtual qubit index to physical qubit index. gates (list): Gates to be mapped. coupling_map (CouplingMap): CouplingMap for target device topology. Returns: tuple: mapped_gates (list): ops for gates that can be executed, mapped onto layout. remaining_gates (list): gates that cannot be executed on the layout. """ blocked_qubits = set() mapped_gates = [] remaining_gates = [] for gate in gates: # Gates without a partition (barrier, snapshot, save, load, noise) may # still have associated qubits. Look for them in the qargs. if not gate['partition']: qubits = [n for n in gate['graph'].nodes() if n.type == 'op'][0].qargs if not qubits: continue if blocked_qubits.intersection(qubits): blocked_qubits.update(qubits) remaining_gates.append(gate) else: mapped_gate = _transform_gate_for_layout(gate, layout) mapped_gates.append(mapped_gate) continue qubits = gate['partition'][0] if blocked_qubits.intersection(qubits): blocked_qubits.update(qubits) remaining_gates.append(gate) elif len(qubits) == 1: mapped_gate = _transform_gate_for_layout(gate, layout) mapped_gates.append(mapped_gate) elif coupling_map.distance(*[layout[q] for q in qubits]) == 1: mapped_gate = _transform_gate_for_layout(gate, layout) mapped_gates.append(mapped_gate) else: blocked_qubits.update(qubits) remaining_gates.append(gate) return mapped_gates, remaining_gates
[ "Map", "all", "gates", "that", "can", "be", "executed", "with", "the", "current", "layout", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/lookahead_swap.py#L184-L236
[ "def", "_map_free_gates", "(", "layout", ",", "gates", ",", "coupling_map", ")", ":", "blocked_qubits", "=", "set", "(", ")", "mapped_gates", "=", "[", "]", "remaining_gates", "=", "[", "]", "for", "gate", "in", "gates", ":", "# Gates without a partition (barrier, snapshot, save, load, noise) may", "# still have associated qubits. Look for them in the qargs.", "if", "not", "gate", "[", "'partition'", "]", ":", "qubits", "=", "[", "n", "for", "n", "in", "gate", "[", "'graph'", "]", ".", "nodes", "(", ")", "if", "n", ".", "type", "==", "'op'", "]", "[", "0", "]", ".", "qargs", "if", "not", "qubits", ":", "continue", "if", "blocked_qubits", ".", "intersection", "(", "qubits", ")", ":", "blocked_qubits", ".", "update", "(", "qubits", ")", "remaining_gates", ".", "append", "(", "gate", ")", "else", ":", "mapped_gate", "=", "_transform_gate_for_layout", "(", "gate", ",", "layout", ")", "mapped_gates", ".", "append", "(", "mapped_gate", ")", "continue", "qubits", "=", "gate", "[", "'partition'", "]", "[", "0", "]", "if", "blocked_qubits", ".", "intersection", "(", "qubits", ")", ":", "blocked_qubits", ".", "update", "(", "qubits", ")", "remaining_gates", ".", "append", "(", "gate", ")", "elif", "len", "(", "qubits", ")", "==", "1", ":", "mapped_gate", "=", "_transform_gate_for_layout", "(", "gate", ",", "layout", ")", "mapped_gates", ".", "append", "(", "mapped_gate", ")", "elif", "coupling_map", ".", "distance", "(", "*", "[", "layout", "[", "q", "]", "for", "q", "in", "qubits", "]", ")", "==", "1", ":", "mapped_gate", "=", "_transform_gate_for_layout", "(", "gate", ",", "layout", ")", "mapped_gates", ".", "append", "(", "mapped_gate", ")", "else", ":", "blocked_qubits", ".", "update", "(", "qubits", ")", "remaining_gates", ".", "append", "(", "gate", ")", "return", "mapped_gates", ",", "remaining_gates" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_calc_layout_distance
Return the sum of the distances of two-qubit pairs in each CNOT in gates according to the layout and the coupling.
qiskit/transpiler/passes/mapping/lookahead_swap.py
def _calc_layout_distance(gates, coupling_map, layout, max_gates=None): """Return the sum of the distances of two-qubit pairs in each CNOT in gates according to the layout and the coupling. """ if max_gates is None: max_gates = 50 + 10 * len(coupling_map.physical_qubits) return sum(coupling_map.distance(*[layout[q] for q in gate['partition'][0]]) for gate in gates[:max_gates] if gate['partition'] and len(gate['partition'][0]) == 2)
def _calc_layout_distance(gates, coupling_map, layout, max_gates=None): """Return the sum of the distances of two-qubit pairs in each CNOT in gates according to the layout and the coupling. """ if max_gates is None: max_gates = 50 + 10 * len(coupling_map.physical_qubits) return sum(coupling_map.distance(*[layout[q] for q in gate['partition'][0]]) for gate in gates[:max_gates] if gate['partition'] and len(gate['partition'][0]) == 2)
[ "Return", "the", "sum", "of", "the", "distances", "of", "two", "-", "qubit", "pairs", "in", "each", "CNOT", "in", "gates", "according", "to", "the", "layout", "and", "the", "coupling", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/lookahead_swap.py#L239-L249
[ "def", "_calc_layout_distance", "(", "gates", ",", "coupling_map", ",", "layout", ",", "max_gates", "=", "None", ")", ":", "if", "max_gates", "is", "None", ":", "max_gates", "=", "50", "+", "10", "*", "len", "(", "coupling_map", ".", "physical_qubits", ")", "return", "sum", "(", "coupling_map", ".", "distance", "(", "*", "[", "layout", "[", "q", "]", "for", "q", "in", "gate", "[", "'partition'", "]", "[", "0", "]", "]", ")", "for", "gate", "in", "gates", "[", ":", "max_gates", "]", "if", "gate", "[", "'partition'", "]", "and", "len", "(", "gate", "[", "'partition'", "]", "[", "0", "]", ")", "==", "2", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_score_step
Count the mapped two-qubit gates, less the number of added SWAPs.
qiskit/transpiler/passes/mapping/lookahead_swap.py
def _score_step(step): """Count the mapped two-qubit gates, less the number of added SWAPs.""" # Each added swap will add 3 ops to gates_mapped, so subtract 3. return len([g for g in step['gates_mapped'] if len(g.qargs) == 2]) - 3 * step['swaps_added']
def _score_step(step): """Count the mapped two-qubit gates, less the number of added SWAPs.""" # Each added swap will add 3 ops to gates_mapped, so subtract 3. return len([g for g in step['gates_mapped'] if len(g.qargs) == 2]) - 3 * step['swaps_added']
[ "Count", "the", "mapped", "two", "-", "qubit", "gates", "less", "the", "number", "of", "added", "SWAPs", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/lookahead_swap.py#L252-L257
[ "def", "_score_step", "(", "step", ")", ":", "# Each added swap will add 3 ops to gates_mapped, so subtract 3.", "return", "len", "(", "[", "g", "for", "g", "in", "step", "[", "'gates_mapped'", "]", "if", "len", "(", "g", ".", "qargs", ")", "==", "2", "]", ")", "-", "3", "*", "step", "[", "'swaps_added'", "]" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_copy_circuit_metadata
Return a copy of source_dag with metadata but empty. Generate only a single qreg in the output DAG, matching the size of the coupling_map.
qiskit/transpiler/passes/mapping/lookahead_swap.py
def _copy_circuit_metadata(source_dag, coupling_map): """Return a copy of source_dag with metadata but empty. Generate only a single qreg in the output DAG, matching the size of the coupling_map.""" target_dag = DAGCircuit() target_dag.name = source_dag.name for creg in source_dag.cregs.values(): target_dag.add_creg(creg) device_qreg = QuantumRegister(len(coupling_map.physical_qubits), 'q') target_dag.add_qreg(device_qreg) return target_dag
def _copy_circuit_metadata(source_dag, coupling_map): """Return a copy of source_dag with metadata but empty. Generate only a single qreg in the output DAG, matching the size of the coupling_map.""" target_dag = DAGCircuit() target_dag.name = source_dag.name for creg in source_dag.cregs.values(): target_dag.add_creg(creg) device_qreg = QuantumRegister(len(coupling_map.physical_qubits), 'q') target_dag.add_qreg(device_qreg) return target_dag
[ "Return", "a", "copy", "of", "source_dag", "with", "metadata", "but", "empty", ".", "Generate", "only", "a", "single", "qreg", "in", "the", "output", "DAG", "matching", "the", "size", "of", "the", "coupling_map", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/lookahead_swap.py#L260-L274
[ "def", "_copy_circuit_metadata", "(", "source_dag", ",", "coupling_map", ")", ":", "target_dag", "=", "DAGCircuit", "(", ")", "target_dag", ".", "name", "=", "source_dag", ".", "name", "for", "creg", "in", "source_dag", ".", "cregs", ".", "values", "(", ")", ":", "target_dag", ".", "add_creg", "(", "creg", ")", "device_qreg", "=", "QuantumRegister", "(", "len", "(", "coupling_map", ".", "physical_qubits", ")", ",", "'q'", ")", "target_dag", ".", "add_qreg", "(", "device_qreg", ")", "return", "target_dag" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_transform_gate_for_layout
Return op implementing a virtual gate on given layout.
qiskit/transpiler/passes/mapping/lookahead_swap.py
def _transform_gate_for_layout(gate, layout): """Return op implementing a virtual gate on given layout.""" mapped_op_node = deepcopy([n for n in gate['graph'].nodes() if n.type == 'op'][0]) # Workaround until #1816, apply mapped to qargs to both DAGNode and op device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q') mapped_qargs = [(device_qreg, layout[a]) for a in mapped_op_node.qargs] mapped_op_node.qargs = mapped_op_node.op.qargs = mapped_qargs mapped_op_node.pop('name') return mapped_op_node
def _transform_gate_for_layout(gate, layout): """Return op implementing a virtual gate on given layout.""" mapped_op_node = deepcopy([n for n in gate['graph'].nodes() if n.type == 'op'][0]) # Workaround until #1816, apply mapped to qargs to both DAGNode and op device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q') mapped_qargs = [(device_qreg, layout[a]) for a in mapped_op_node.qargs] mapped_op_node.qargs = mapped_op_node.op.qargs = mapped_qargs mapped_op_node.pop('name') return mapped_op_node
[ "Return", "op", "implementing", "a", "virtual", "gate", "on", "given", "layout", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/lookahead_swap.py#L277-L289
[ "def", "_transform_gate_for_layout", "(", "gate", ",", "layout", ")", ":", "mapped_op_node", "=", "deepcopy", "(", "[", "n", "for", "n", "in", "gate", "[", "'graph'", "]", ".", "nodes", "(", ")", "if", "n", ".", "type", "==", "'op'", "]", "[", "0", "]", ")", "# Workaround until #1816, apply mapped to qargs to both DAGNode and op", "device_qreg", "=", "QuantumRegister", "(", "len", "(", "layout", ".", "get_physical_bits", "(", ")", ")", ",", "'q'", ")", "mapped_qargs", "=", "[", "(", "device_qreg", ",", "layout", "[", "a", "]", ")", "for", "a", "in", "mapped_op_node", ".", "qargs", "]", "mapped_op_node", ".", "qargs", "=", "mapped_op_node", ".", "op", ".", "qargs", "=", "mapped_qargs", "mapped_op_node", ".", "pop", "(", "'name'", ")", "return", "mapped_op_node" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_swap_ops_from_edge
Generate list of ops to implement a SWAP gate along a coupling edge.
qiskit/transpiler/passes/mapping/lookahead_swap.py
def _swap_ops_from_edge(edge, layout): """Generate list of ops to implement a SWAP gate along a coupling edge.""" device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q') qreg_edge = [(device_qreg, i) for i in edge] # TODO shouldn't be making other nodes not by the DAG!! return [ DAGNode({'op': SwapGate(), 'qargs': qreg_edge, 'cargs': [], 'type': 'op'}) ]
def _swap_ops_from_edge(edge, layout): """Generate list of ops to implement a SWAP gate along a coupling edge.""" device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q') qreg_edge = [(device_qreg, i) for i in edge] # TODO shouldn't be making other nodes not by the DAG!! return [ DAGNode({'op': SwapGate(), 'qargs': qreg_edge, 'cargs': [], 'type': 'op'}) ]
[ "Generate", "list", "of", "ops", "to", "implement", "a", "SWAP", "gate", "along", "a", "coupling", "edge", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/lookahead_swap.py#L292-L301
[ "def", "_swap_ops_from_edge", "(", "edge", ",", "layout", ")", ":", "device_qreg", "=", "QuantumRegister", "(", "len", "(", "layout", ".", "get_physical_bits", "(", ")", ")", ",", "'q'", ")", "qreg_edge", "=", "[", "(", "device_qreg", ",", "i", ")", "for", "i", "in", "edge", "]", "# TODO shouldn't be making other nodes not by the DAG!!", "return", "[", "DAGNode", "(", "{", "'op'", ":", "SwapGate", "(", ")", ",", "'qargs'", ":", "qreg_edge", ",", "'cargs'", ":", "[", "]", ",", "'type'", ":", "'op'", "}", ")", "]" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
LookaheadSwap.run
Run one pass of the lookahead mapper on the provided DAG. Args: dag (DAGCircuit): the directed acyclic graph to be mapped Returns: DAGCircuit: A dag mapped to be compatible with the coupling_map in the property_set. Raises: TranspilerError: if the coupling map or the layout are not compatible with the DAG
qiskit/transpiler/passes/mapping/lookahead_swap.py
def run(self, dag): """Run one pass of the lookahead mapper on the provided DAG. Args: dag (DAGCircuit): the directed acyclic graph to be mapped Returns: DAGCircuit: A dag mapped to be compatible with the coupling_map in the property_set. Raises: TranspilerError: if the coupling map or the layout are not compatible with the DAG """ coupling_map = self._coupling_map ordered_virtual_gates = list(dag.serial_layers()) if self.initial_layout is None: if self.property_set["layout"]: self.initial_layout = self.property_set["layout"] else: self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values()) if len(dag.qubits()) != len(self.initial_layout): raise TranspilerError('The layout does not match the amount of qubits in the DAG') if len(self._coupling_map.physical_qubits) != len(self.initial_layout): raise TranspilerError( "Mappers require to have the layout to be the same size as the coupling map") mapped_gates = [] layout = self.initial_layout.copy() gates_remaining = ordered_virtual_gates.copy() while gates_remaining: best_step = _search_forward_n_swaps(layout, gates_remaining, coupling_map) layout = best_step['layout'] gates_mapped = best_step['gates_mapped'] gates_remaining = best_step['gates_remaining'] mapped_gates.extend(gates_mapped) # Preserve input DAG's name, regs, wire_map, etc. but replace the graph. mapped_dag = _copy_circuit_metadata(dag, coupling_map) for node in mapped_gates: mapped_dag.apply_operation_back(op=node.op, qargs=node.qargs, cargs=node.cargs) return mapped_dag
def run(self, dag): """Run one pass of the lookahead mapper on the provided DAG. Args: dag (DAGCircuit): the directed acyclic graph to be mapped Returns: DAGCircuit: A dag mapped to be compatible with the coupling_map in the property_set. Raises: TranspilerError: if the coupling map or the layout are not compatible with the DAG """ coupling_map = self._coupling_map ordered_virtual_gates = list(dag.serial_layers()) if self.initial_layout is None: if self.property_set["layout"]: self.initial_layout = self.property_set["layout"] else: self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values()) if len(dag.qubits()) != len(self.initial_layout): raise TranspilerError('The layout does not match the amount of qubits in the DAG') if len(self._coupling_map.physical_qubits) != len(self.initial_layout): raise TranspilerError( "Mappers require to have the layout to be the same size as the coupling map") mapped_gates = [] layout = self.initial_layout.copy() gates_remaining = ordered_virtual_gates.copy() while gates_remaining: best_step = _search_forward_n_swaps(layout, gates_remaining, coupling_map) layout = best_step['layout'] gates_mapped = best_step['gates_mapped'] gates_remaining = best_step['gates_remaining'] mapped_gates.extend(gates_mapped) # Preserve input DAG's name, regs, wire_map, etc. but replace the graph. mapped_dag = _copy_circuit_metadata(dag, coupling_map) for node in mapped_gates: mapped_dag.apply_operation_back(op=node.op, qargs=node.qargs, cargs=node.cargs) return mapped_dag
[ "Run", "one", "pass", "of", "the", "lookahead", "mapper", "on", "the", "provided", "DAG", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/lookahead_swap.py#L75-L123
[ "def", "run", "(", "self", ",", "dag", ")", ":", "coupling_map", "=", "self", ".", "_coupling_map", "ordered_virtual_gates", "=", "list", "(", "dag", ".", "serial_layers", "(", ")", ")", "if", "self", ".", "initial_layout", "is", "None", ":", "if", "self", ".", "property_set", "[", "\"layout\"", "]", ":", "self", ".", "initial_layout", "=", "self", ".", "property_set", "[", "\"layout\"", "]", "else", ":", "self", ".", "initial_layout", "=", "Layout", ".", "generate_trivial_layout", "(", "*", "dag", ".", "qregs", ".", "values", "(", ")", ")", "if", "len", "(", "dag", ".", "qubits", "(", ")", ")", "!=", "len", "(", "self", ".", "initial_layout", ")", ":", "raise", "TranspilerError", "(", "'The layout does not match the amount of qubits in the DAG'", ")", "if", "len", "(", "self", ".", "_coupling_map", ".", "physical_qubits", ")", "!=", "len", "(", "self", ".", "initial_layout", ")", ":", "raise", "TranspilerError", "(", "\"Mappers require to have the layout to be the same size as the coupling map\"", ")", "mapped_gates", "=", "[", "]", "layout", "=", "self", ".", "initial_layout", ".", "copy", "(", ")", "gates_remaining", "=", "ordered_virtual_gates", ".", "copy", "(", ")", "while", "gates_remaining", ":", "best_step", "=", "_search_forward_n_swaps", "(", "layout", ",", "gates_remaining", ",", "coupling_map", ")", "layout", "=", "best_step", "[", "'layout'", "]", "gates_mapped", "=", "best_step", "[", "'gates_mapped'", "]", "gates_remaining", "=", "best_step", "[", "'gates_remaining'", "]", "mapped_gates", ".", "extend", "(", "gates_mapped", ")", "# Preserve input DAG's name, regs, wire_map, etc. but replace the graph.", "mapped_dag", "=", "_copy_circuit_metadata", "(", "dag", ",", "coupling_map", ")", "for", "node", "in", "mapped_gates", ":", "mapped_dag", ".", "apply_operation_back", "(", "op", "=", "node", ".", "op", ",", "qargs", "=", "node", ".", "qargs", ",", "cargs", "=", "node", ".", "cargs", ")", "return", "mapped_dag" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
CouplingMap.add_physical_qubit
Add a physical qubit to the coupling graph as a node. physical_qubit (int): An integer representing a physical qubit. Raises: CouplingError: if trying to add duplicate qubit
qiskit/transpiler/coupling.py
def add_physical_qubit(self, physical_qubit): """Add a physical qubit to the coupling graph as a node. physical_qubit (int): An integer representing a physical qubit. Raises: CouplingError: if trying to add duplicate qubit """ if not isinstance(physical_qubit, int): raise CouplingError("Physical qubits should be integers.") if physical_qubit in self.physical_qubits: raise CouplingError( "The physical qubit %s is already in the coupling graph" % physical_qubit) self.graph.add_node(physical_qubit) self._dist_matrix = None # invalidate self._qubit_list = None
def add_physical_qubit(self, physical_qubit): """Add a physical qubit to the coupling graph as a node. physical_qubit (int): An integer representing a physical qubit. Raises: CouplingError: if trying to add duplicate qubit """ if not isinstance(physical_qubit, int): raise CouplingError("Physical qubits should be integers.") if physical_qubit in self.physical_qubits: raise CouplingError( "The physical qubit %s is already in the coupling graph" % physical_qubit) self.graph.add_node(physical_qubit) self._dist_matrix = None # invalidate self._qubit_list = None
[ "Add", "a", "physical", "qubit", "to", "the", "coupling", "graph", "as", "a", "node", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/coupling.py#L65-L80
[ "def", "add_physical_qubit", "(", "self", ",", "physical_qubit", ")", ":", "if", "not", "isinstance", "(", "physical_qubit", ",", "int", ")", ":", "raise", "CouplingError", "(", "\"Physical qubits should be integers.\"", ")", "if", "physical_qubit", "in", "self", ".", "physical_qubits", ":", "raise", "CouplingError", "(", "\"The physical qubit %s is already in the coupling graph\"", "%", "physical_qubit", ")", "self", ".", "graph", ".", "add_node", "(", "physical_qubit", ")", "self", ".", "_dist_matrix", "=", "None", "# invalidate", "self", ".", "_qubit_list", "=", "None" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
CouplingMap.add_edge
Add directed edge to coupling graph. src (int): source physical qubit dst (int): destination physical qubit
qiskit/transpiler/coupling.py
def add_edge(self, src, dst): """ Add directed edge to coupling graph. src (int): source physical qubit dst (int): destination physical qubit """ if src not in self.physical_qubits: self.add_physical_qubit(src) if dst not in self.physical_qubits: self.add_physical_qubit(dst) self.graph.add_edge(src, dst) self._dist_matrix = None
def add_edge(self, src, dst): """ Add directed edge to coupling graph. src (int): source physical qubit dst (int): destination physical qubit """ if src not in self.physical_qubits: self.add_physical_qubit(src) if dst not in self.physical_qubits: self.add_physical_qubit(dst) self.graph.add_edge(src, dst) self._dist_matrix = None
[ "Add", "directed", "edge", "to", "coupling", "graph", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/coupling.py#L82-L94
[ "def", "add_edge", "(", "self", ",", "src", ",", "dst", ")", ":", "if", "src", "not", "in", "self", ".", "physical_qubits", ":", "self", ".", "add_physical_qubit", "(", "src", ")", "if", "dst", "not", "in", "self", ".", "physical_qubits", ":", "self", ".", "add_physical_qubit", "(", "dst", ")", "self", ".", "graph", ".", "add_edge", "(", "src", ",", "dst", ")", "self", ".", "_dist_matrix", "=", "None" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
CouplingMap.subgraph
Return a CouplingMap object for a subgraph of self. nodelist (list): list of integer node labels
qiskit/transpiler/coupling.py
def subgraph(self, nodelist): """Return a CouplingMap object for a subgraph of self. nodelist (list): list of integer node labels """ subcoupling = CouplingMap() subcoupling.graph = self.graph.subgraph(nodelist) for node in nodelist: if node not in subcoupling.physical_qubits: subcoupling.add_physical_qubit(node) return subcoupling
def subgraph(self, nodelist): """Return a CouplingMap object for a subgraph of self. nodelist (list): list of integer node labels """ subcoupling = CouplingMap() subcoupling.graph = self.graph.subgraph(nodelist) for node in nodelist: if node not in subcoupling.physical_qubits: subcoupling.add_physical_qubit(node) return subcoupling
[ "Return", "a", "CouplingMap", "object", "for", "a", "subgraph", "of", "self", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/coupling.py#L96-L106
[ "def", "subgraph", "(", "self", ",", "nodelist", ")", ":", "subcoupling", "=", "CouplingMap", "(", ")", "subcoupling", ".", "graph", "=", "self", ".", "graph", ".", "subgraph", "(", "nodelist", ")", "for", "node", "in", "nodelist", ":", "if", "node", "not", "in", "subcoupling", ".", "physical_qubits", ":", "subcoupling", ".", "add_physical_qubit", "(", "node", ")", "return", "subcoupling" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
CouplingMap.physical_qubits
Returns a sorted list of physical_qubits
qiskit/transpiler/coupling.py
def physical_qubits(self): """Returns a sorted list of physical_qubits""" if self._qubit_list is None: self._qubit_list = sorted([pqubit for pqubit in self.graph.nodes]) return self._qubit_list
def physical_qubits(self): """Returns a sorted list of physical_qubits""" if self._qubit_list is None: self._qubit_list = sorted([pqubit for pqubit in self.graph.nodes]) return self._qubit_list
[ "Returns", "a", "sorted", "list", "of", "physical_qubits" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/coupling.py#L109-L113
[ "def", "physical_qubits", "(", "self", ")", ":", "if", "self", ".", "_qubit_list", "is", "None", ":", "self", ".", "_qubit_list", "=", "sorted", "(", "[", "pqubit", "for", "pqubit", "in", "self", ".", "graph", ".", "nodes", "]", ")", "return", "self", ".", "_qubit_list" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
CouplingMap.is_connected
Test if the graph is connected. Return True if connected, False otherwise
qiskit/transpiler/coupling.py
def is_connected(self): """ Test if the graph is connected. Return True if connected, False otherwise """ try: return nx.is_weakly_connected(self.graph) except nx.exception.NetworkXException: return False
def is_connected(self): """ Test if the graph is connected. Return True if connected, False otherwise """ try: return nx.is_weakly_connected(self.graph) except nx.exception.NetworkXException: return False
[ "Test", "if", "the", "graph", "is", "connected", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/coupling.py#L115-L124
[ "def", "is_connected", "(", "self", ")", ":", "try", ":", "return", "nx", ".", "is_weakly_connected", "(", "self", ".", "graph", ")", "except", "nx", ".", "exception", ".", "NetworkXException", ":", "return", "False" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
CouplingMap._compute_distance_matrix
Compute the full distance matrix on pairs of nodes. The distance map self._dist_matrix is computed from the graph using all_pairs_shortest_path_length.
qiskit/transpiler/coupling.py
def _compute_distance_matrix(self): """Compute the full distance matrix on pairs of nodes. The distance map self._dist_matrix is computed from the graph using all_pairs_shortest_path_length. """ if not self.is_connected(): raise CouplingError("coupling graph not connected") lengths = nx.all_pairs_shortest_path_length(self.graph.to_undirected(as_view=True)) lengths = dict(lengths) size = len(lengths) cmap = np.zeros((size, size)) for idx in range(size): cmap[idx, np.fromiter(lengths[idx].keys(), dtype=int)] = np.fromiter( lengths[idx].values(), dtype=int) self._dist_matrix = cmap
def _compute_distance_matrix(self): """Compute the full distance matrix on pairs of nodes. The distance map self._dist_matrix is computed from the graph using all_pairs_shortest_path_length. """ if not self.is_connected(): raise CouplingError("coupling graph not connected") lengths = nx.all_pairs_shortest_path_length(self.graph.to_undirected(as_view=True)) lengths = dict(lengths) size = len(lengths) cmap = np.zeros((size, size)) for idx in range(size): cmap[idx, np.fromiter(lengths[idx].keys(), dtype=int)] = np.fromiter( lengths[idx].values(), dtype=int) self._dist_matrix = cmap
[ "Compute", "the", "full", "distance", "matrix", "on", "pairs", "of", "nodes", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/coupling.py#L126-L141
[ "def", "_compute_distance_matrix", "(", "self", ")", ":", "if", "not", "self", ".", "is_connected", "(", ")", ":", "raise", "CouplingError", "(", "\"coupling graph not connected\"", ")", "lengths", "=", "nx", ".", "all_pairs_shortest_path_length", "(", "self", ".", "graph", ".", "to_undirected", "(", "as_view", "=", "True", ")", ")", "lengths", "=", "dict", "(", "lengths", ")", "size", "=", "len", "(", "lengths", ")", "cmap", "=", "np", ".", "zeros", "(", "(", "size", ",", "size", ")", ")", "for", "idx", "in", "range", "(", "size", ")", ":", "cmap", "[", "idx", ",", "np", ".", "fromiter", "(", "lengths", "[", "idx", "]", ".", "keys", "(", ")", ",", "dtype", "=", "int", ")", "]", "=", "np", ".", "fromiter", "(", "lengths", "[", "idx", "]", ".", "values", "(", ")", ",", "dtype", "=", "int", ")", "self", ".", "_dist_matrix", "=", "cmap" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
CouplingMap.distance
Returns the undirected distance between physical_qubit1 and physical_qubit2. Args: physical_qubit1 (int): A physical qubit physical_qubit2 (int): Another physical qubit Returns: int: The undirected distance Raises: CouplingError: if the qubits do not exist in the CouplingMap
qiskit/transpiler/coupling.py
def distance(self, physical_qubit1, physical_qubit2): """Returns the undirected distance between physical_qubit1 and physical_qubit2. Args: physical_qubit1 (int): A physical qubit physical_qubit2 (int): Another physical qubit Returns: int: The undirected distance Raises: CouplingError: if the qubits do not exist in the CouplingMap """ if physical_qubit1 not in self.physical_qubits: raise CouplingError("%s not in coupling graph" % (physical_qubit1,)) if physical_qubit2 not in self.physical_qubits: raise CouplingError("%s not in coupling graph" % (physical_qubit2,)) if self._dist_matrix is None: self._compute_distance_matrix() return self._dist_matrix[physical_qubit1, physical_qubit2]
def distance(self, physical_qubit1, physical_qubit2): """Returns the undirected distance between physical_qubit1 and physical_qubit2. Args: physical_qubit1 (int): A physical qubit physical_qubit2 (int): Another physical qubit Returns: int: The undirected distance Raises: CouplingError: if the qubits do not exist in the CouplingMap """ if physical_qubit1 not in self.physical_qubits: raise CouplingError("%s not in coupling graph" % (physical_qubit1,)) if physical_qubit2 not in self.physical_qubits: raise CouplingError("%s not in coupling graph" % (physical_qubit2,)) if self._dist_matrix is None: self._compute_distance_matrix() return self._dist_matrix[physical_qubit1, physical_qubit2]
[ "Returns", "the", "undirected", "distance", "between", "physical_qubit1", "and", "physical_qubit2", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/coupling.py#L143-L162
[ "def", "distance", "(", "self", ",", "physical_qubit1", ",", "physical_qubit2", ")", ":", "if", "physical_qubit1", "not", "in", "self", ".", "physical_qubits", ":", "raise", "CouplingError", "(", "\"%s not in coupling graph\"", "%", "(", "physical_qubit1", ",", ")", ")", "if", "physical_qubit2", "not", "in", "self", ".", "physical_qubits", ":", "raise", "CouplingError", "(", "\"%s not in coupling graph\"", "%", "(", "physical_qubit2", ",", ")", ")", "if", "self", ".", "_dist_matrix", "is", "None", ":", "self", ".", "_compute_distance_matrix", "(", ")", "return", "self", ".", "_dist_matrix", "[", "physical_qubit1", ",", "physical_qubit2", "]" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
transpile
transpile one or more circuits. Args: circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile backend (BaseBackend): a backend to compile for basis_gates (list[str]): list of basis gate names supported by the target. Default: ['u1','u2','u3','cx','id'] coupling_map (list): coupling map (perhaps custom) to target in mapping initial_layout (Layout or dict or list): Initial position of virtual qubits on physical qubits. The final layout is not guaranteed to be the same, as the transpiler may permute qubits through swaps or other means. seed_mapper (int): random seed for the swap_mapper pass_manager (PassManager): a pass_manager for the transpiler stages Returns: QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s). Raises: TranspilerError: in case of bad inputs to transpiler or errors in passes
qiskit/transpiler/transpiler.py
def transpile(circuits, backend=None, basis_gates=None, coupling_map=None, initial_layout=None, seed_mapper=None, pass_manager=None): """transpile one or more circuits. Args: circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile backend (BaseBackend): a backend to compile for basis_gates (list[str]): list of basis gate names supported by the target. Default: ['u1','u2','u3','cx','id'] coupling_map (list): coupling map (perhaps custom) to target in mapping initial_layout (Layout or dict or list): Initial position of virtual qubits on physical qubits. The final layout is not guaranteed to be the same, as the transpiler may permute qubits through swaps or other means. seed_mapper (int): random seed for the swap_mapper pass_manager (PassManager): a pass_manager for the transpiler stages Returns: QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s). Raises: TranspilerError: in case of bad inputs to transpiler or errors in passes """ warnings.warn("qiskit.transpiler.transpile() has been deprecated and will be " "removed in the 0.9 release. Use qiskit.compiler.transpile() instead.", DeprecationWarning) return compiler.transpile(circuits=circuits, backend=backend, basis_gates=basis_gates, coupling_map=coupling_map, initial_layout=initial_layout, seed_transpiler=seed_mapper, pass_manager=pass_manager)
def transpile(circuits, backend=None, basis_gates=None, coupling_map=None, initial_layout=None, seed_mapper=None, pass_manager=None): """transpile one or more circuits. Args: circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile backend (BaseBackend): a backend to compile for basis_gates (list[str]): list of basis gate names supported by the target. Default: ['u1','u2','u3','cx','id'] coupling_map (list): coupling map (perhaps custom) to target in mapping initial_layout (Layout or dict or list): Initial position of virtual qubits on physical qubits. The final layout is not guaranteed to be the same, as the transpiler may permute qubits through swaps or other means. seed_mapper (int): random seed for the swap_mapper pass_manager (PassManager): a pass_manager for the transpiler stages Returns: QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s). Raises: TranspilerError: in case of bad inputs to transpiler or errors in passes """ warnings.warn("qiskit.transpiler.transpile() has been deprecated and will be " "removed in the 0.9 release. Use qiskit.compiler.transpile() instead.", DeprecationWarning) return compiler.transpile(circuits=circuits, backend=backend, basis_gates=basis_gates, coupling_map=coupling_map, initial_layout=initial_layout, seed_transpiler=seed_mapper, pass_manager=pass_manager)
[ "transpile", "one", "or", "more", "circuits", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/transpiler.py#L19-L50
[ "def", "transpile", "(", "circuits", ",", "backend", "=", "None", ",", "basis_gates", "=", "None", ",", "coupling_map", "=", "None", ",", "initial_layout", "=", "None", ",", "seed_mapper", "=", "None", ",", "pass_manager", "=", "None", ")", ":", "warnings", ".", "warn", "(", "\"qiskit.transpiler.transpile() has been deprecated and will be \"", "\"removed in the 0.9 release. Use qiskit.compiler.transpile() instead.\"", ",", "DeprecationWarning", ")", "return", "compiler", ".", "transpile", "(", "circuits", "=", "circuits", ",", "backend", "=", "backend", ",", "basis_gates", "=", "basis_gates", ",", "coupling_map", "=", "coupling_map", ",", "initial_layout", "=", "initial_layout", ",", "seed_transpiler", "=", "seed_mapper", ",", "pass_manager", "=", "pass_manager", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
transpile_dag
Deprecated - Use qiskit.compiler.transpile for transpiling from circuits to circuits. Transform a dag circuit into another dag circuit (transpile), through consecutive passes on the dag. Args: dag (DAGCircuit): dag circuit to transform via transpilation basis_gates (list[str]): list of basis gate names supported by the target. Default: ['u1','u2','u3','cx','id'] coupling_map (list): A graph of coupling:: [ [control0(int), target0(int)], [control1(int), target1(int)], ] eg. [[0, 2], [1, 2], [1, 3], [3, 4]} initial_layout (Layout or None): A layout object seed_mapper (int): random seed_mapper for the swap mapper pass_manager (PassManager): pass manager instance for the transpilation process If None, a default set of passes are run. Otherwise, the passes defined in it will run. If contains no passes in it, no dag transformations occur. Returns: DAGCircuit: transformed dag
qiskit/transpiler/transpiler.py
def transpile_dag(dag, basis_gates=None, coupling_map=None, initial_layout=None, seed_mapper=None, pass_manager=None): """Deprecated - Use qiskit.compiler.transpile for transpiling from circuits to circuits. Transform a dag circuit into another dag circuit (transpile), through consecutive passes on the dag. Args: dag (DAGCircuit): dag circuit to transform via transpilation basis_gates (list[str]): list of basis gate names supported by the target. Default: ['u1','u2','u3','cx','id'] coupling_map (list): A graph of coupling:: [ [control0(int), target0(int)], [control1(int), target1(int)], ] eg. [[0, 2], [1, 2], [1, 3], [3, 4]} initial_layout (Layout or None): A layout object seed_mapper (int): random seed_mapper for the swap mapper pass_manager (PassManager): pass manager instance for the transpilation process If None, a default set of passes are run. Otherwise, the passes defined in it will run. If contains no passes in it, no dag transformations occur. Returns: DAGCircuit: transformed dag """ warnings.warn("transpile_dag has been deprecated and will be removed in the " "0.9 release. Circuits can be transpiled directly to other " "circuits with the transpile function.", DeprecationWarning) if basis_gates is None: basis_gates = ['u1', 'u2', 'u3', 'cx', 'id'] if pass_manager is None: # default set of passes # if a coupling map is given compile to the map if coupling_map: pass_manager = default_pass_manager(basis_gates, CouplingMap(coupling_map), initial_layout, seed_transpiler=seed_mapper) else: pass_manager = default_pass_manager_simulator(basis_gates) # run the passes specified by the pass manager # TODO return the property set too. See #1086 name = dag.name circuit = dag_to_circuit(dag) circuit = pass_manager.run(circuit) dag = circuit_to_dag(circuit) dag.name = name return dag
def transpile_dag(dag, basis_gates=None, coupling_map=None, initial_layout=None, seed_mapper=None, pass_manager=None): """Deprecated - Use qiskit.compiler.transpile for transpiling from circuits to circuits. Transform a dag circuit into another dag circuit (transpile), through consecutive passes on the dag. Args: dag (DAGCircuit): dag circuit to transform via transpilation basis_gates (list[str]): list of basis gate names supported by the target. Default: ['u1','u2','u3','cx','id'] coupling_map (list): A graph of coupling:: [ [control0(int), target0(int)], [control1(int), target1(int)], ] eg. [[0, 2], [1, 2], [1, 3], [3, 4]} initial_layout (Layout or None): A layout object seed_mapper (int): random seed_mapper for the swap mapper pass_manager (PassManager): pass manager instance for the transpilation process If None, a default set of passes are run. Otherwise, the passes defined in it will run. If contains no passes in it, no dag transformations occur. Returns: DAGCircuit: transformed dag """ warnings.warn("transpile_dag has been deprecated and will be removed in the " "0.9 release. Circuits can be transpiled directly to other " "circuits with the transpile function.", DeprecationWarning) if basis_gates is None: basis_gates = ['u1', 'u2', 'u3', 'cx', 'id'] if pass_manager is None: # default set of passes # if a coupling map is given compile to the map if coupling_map: pass_manager = default_pass_manager(basis_gates, CouplingMap(coupling_map), initial_layout, seed_transpiler=seed_mapper) else: pass_manager = default_pass_manager_simulator(basis_gates) # run the passes specified by the pass manager # TODO return the property set too. See #1086 name = dag.name circuit = dag_to_circuit(dag) circuit = pass_manager.run(circuit) dag = circuit_to_dag(circuit) dag.name = name return dag
[ "Deprecated", "-", "Use", "qiskit", ".", "compiler", ".", "transpile", "for", "transpiling", "from", "circuits", "to", "circuits", ".", "Transform", "a", "dag", "circuit", "into", "another", "dag", "circuit", "(", "transpile", ")", "through", "consecutive", "passes", "on", "the", "dag", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/transpiler.py#L53-L110
[ "def", "transpile_dag", "(", "dag", ",", "basis_gates", "=", "None", ",", "coupling_map", "=", "None", ",", "initial_layout", "=", "None", ",", "seed_mapper", "=", "None", ",", "pass_manager", "=", "None", ")", ":", "warnings", ".", "warn", "(", "\"transpile_dag has been deprecated and will be removed in the \"", "\"0.9 release. Circuits can be transpiled directly to other \"", "\"circuits with the transpile function.\"", ",", "DeprecationWarning", ")", "if", "basis_gates", "is", "None", ":", "basis_gates", "=", "[", "'u1'", ",", "'u2'", ",", "'u3'", ",", "'cx'", ",", "'id'", "]", "if", "pass_manager", "is", "None", ":", "# default set of passes", "# if a coupling map is given compile to the map", "if", "coupling_map", ":", "pass_manager", "=", "default_pass_manager", "(", "basis_gates", ",", "CouplingMap", "(", "coupling_map", ")", ",", "initial_layout", ",", "seed_transpiler", "=", "seed_mapper", ")", "else", ":", "pass_manager", "=", "default_pass_manager_simulator", "(", "basis_gates", ")", "# run the passes specified by the pass manager", "# TODO return the property set too. See #1086", "name", "=", "dag", ".", "name", "circuit", "=", "dag_to_circuit", "(", "dag", ")", "circuit", "=", "pass_manager", ".", "run", "(", "circuit", ")", "dag", "=", "circuit_to_dag", "(", "circuit", ")", "dag", ".", "name", "=", "name", "return", "dag" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
cu1
Apply cu1 from ctl to tgt with angle theta.
qiskit/extensions/standard/cu1.py
def cu1(self, theta, ctl, tgt): """Apply cu1 from ctl to tgt with angle theta.""" return self.append(Cu1Gate(theta), [ctl, tgt], [])
def cu1(self, theta, ctl, tgt): """Apply cu1 from ctl to tgt with angle theta.""" return self.append(Cu1Gate(theta), [ctl, tgt], [])
[ "Apply", "cu1", "from", "ctl", "to", "tgt", "with", "angle", "theta", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/standard/cu1.py#L55-L57
[ "def", "cu1", "(", "self", ",", "theta", ",", "ctl", ",", "tgt", ")", ":", "return", "self", ".", "append", "(", "Cu1Gate", "(", "theta", ")", ",", "[", "ctl", ",", "tgt", "]", ",", "[", "]", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
InstructionSet.add
Add an instruction and its context (where it's attached).
qiskit/circuit/instructionset.py
def add(self, gate, qargs, cargs): """Add an instruction and its context (where it's attached).""" if not isinstance(gate, Instruction): raise QiskitError("attempt to add non-Instruction" + " to InstructionSet") self.instructions.append(gate) self.qargs.append(qargs) self.cargs.append(cargs)
def add(self, gate, qargs, cargs): """Add an instruction and its context (where it's attached).""" if not isinstance(gate, Instruction): raise QiskitError("attempt to add non-Instruction" + " to InstructionSet") self.instructions.append(gate) self.qargs.append(qargs) self.cargs.append(cargs)
[ "Add", "an", "instruction", "and", "its", "context", "(", "where", "it", "s", "attached", ")", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/instructionset.py#L36-L43
[ "def", "add", "(", "self", ",", "gate", ",", "qargs", ",", "cargs", ")", ":", "if", "not", "isinstance", "(", "gate", ",", "Instruction", ")", ":", "raise", "QiskitError", "(", "\"attempt to add non-Instruction\"", "+", "\" to InstructionSet\"", ")", "self", ".", "instructions", ".", "append", "(", "gate", ")", "self", ".", "qargs", ".", "append", "(", "qargs", ")", "self", ".", "cargs", ".", "append", "(", "cargs", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
InstructionSet.inverse
Invert all instructions.
qiskit/circuit/instructionset.py
def inverse(self): """Invert all instructions.""" for index, instruction in enumerate(self.instructions): self.instructions[index] = instruction.inverse() return self
def inverse(self): """Invert all instructions.""" for index, instruction in enumerate(self.instructions): self.instructions[index] = instruction.inverse() return self
[ "Invert", "all", "instructions", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/instructionset.py#L45-L49
[ "def", "inverse", "(", "self", ")", ":", "for", "index", ",", "instruction", "in", "enumerate", "(", "self", ".", "instructions", ")", ":", "self", ".", "instructions", "[", "index", "]", "=", "instruction", ".", "inverse", "(", ")", "return", "self" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
InstructionSet.q_if
Add controls to all instructions.
qiskit/circuit/instructionset.py
def q_if(self, *qregs): """Add controls to all instructions.""" for gate in self.instructions: gate.q_if(*qregs) return self
def q_if(self, *qregs): """Add controls to all instructions.""" for gate in self.instructions: gate.q_if(*qregs) return self
[ "Add", "controls", "to", "all", "instructions", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/instructionset.py#L51-L55
[ "def", "q_if", "(", "self", ",", "*", "qregs", ")", ":", "for", "gate", "in", "self", ".", "instructions", ":", "gate", ".", "q_if", "(", "*", "qregs", ")", "return", "self" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
InstructionSet.c_if
Add classical control register to all instructions.
qiskit/circuit/instructionset.py
def c_if(self, classical, val): """Add classical control register to all instructions.""" for gate in self.instructions: gate.c_if(classical, val) return self
def c_if(self, classical, val): """Add classical control register to all instructions.""" for gate in self.instructions: gate.c_if(classical, val) return self
[ "Add", "classical", "control", "register", "to", "all", "instructions", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/instructionset.py#L57-L61
[ "def", "c_if", "(", "self", ",", "classical", ",", "val", ")", ":", "for", "gate", "in", "self", ".", "instructions", ":", "gate", ".", "c_if", "(", "classical", ",", "val", ")", "return", "self" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_Broker.subscribe
Subscribes to an event, so when it's emitted all the callbacks subscribed, will be executed. We are not allowing double registration. Args event (string): The event to subscribed in the form of: "terra.<component>.<method>.<action>" callback (callable): The callback that will be executed when an event is emitted.
qiskit/tools/events/pubsub.py
def subscribe(self, event, callback): """Subscribes to an event, so when it's emitted all the callbacks subscribed, will be executed. We are not allowing double registration. Args event (string): The event to subscribed in the form of: "terra.<component>.<method>.<action>" callback (callable): The callback that will be executed when an event is emitted. """ if not callable(callback): raise QiskitError("Callback is not a callable!") if event not in self._subscribers: self._subscribers[event] = [] new_subscription = self._Subscription(event, callback) if new_subscription in self._subscribers[event]: # We are not allowing double subscription return False self._subscribers[event].append(new_subscription) return True
def subscribe(self, event, callback): """Subscribes to an event, so when it's emitted all the callbacks subscribed, will be executed. We are not allowing double registration. Args event (string): The event to subscribed in the form of: "terra.<component>.<method>.<action>" callback (callable): The callback that will be executed when an event is emitted. """ if not callable(callback): raise QiskitError("Callback is not a callable!") if event not in self._subscribers: self._subscribers[event] = [] new_subscription = self._Subscription(event, callback) if new_subscription in self._subscribers[event]: # We are not allowing double subscription return False self._subscribers[event].append(new_subscription) return True
[ "Subscribes", "to", "an", "event", "so", "when", "it", "s", "emitted", "all", "the", "callbacks", "subscribed", "will", "be", "executed", ".", "We", "are", "not", "allowing", "double", "registration", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/events/pubsub.py#L53-L75
[ "def", "subscribe", "(", "self", ",", "event", ",", "callback", ")", ":", "if", "not", "callable", "(", "callback", ")", ":", "raise", "QiskitError", "(", "\"Callback is not a callable!\"", ")", "if", "event", "not", "in", "self", ".", "_subscribers", ":", "self", ".", "_subscribers", "[", "event", "]", "=", "[", "]", "new_subscription", "=", "self", ".", "_Subscription", "(", "event", ",", "callback", ")", "if", "new_subscription", "in", "self", ".", "_subscribers", "[", "event", "]", ":", "# We are not allowing double subscription", "return", "False", "self", ".", "_subscribers", "[", "event", "]", ".", "append", "(", "new_subscription", ")", "return", "True" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_Broker.dispatch
Emits an event if there are any subscribers. Args event (String): The event to be emitted args: Arguments linked with the event kwargs: Named arguments linked with the event
qiskit/tools/events/pubsub.py
def dispatch(self, event, *args, **kwargs): """Emits an event if there are any subscribers. Args event (String): The event to be emitted args: Arguments linked with the event kwargs: Named arguments linked with the event """ # No event, no subscribers. if event not in self._subscribers: return for subscriber in self._subscribers[event]: subscriber.callback(*args, **kwargs)
def dispatch(self, event, *args, **kwargs): """Emits an event if there are any subscribers. Args event (String): The event to be emitted args: Arguments linked with the event kwargs: Named arguments linked with the event """ # No event, no subscribers. if event not in self._subscribers: return for subscriber in self._subscribers[event]: subscriber.callback(*args, **kwargs)
[ "Emits", "an", "event", "if", "there", "are", "any", "subscribers", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/events/pubsub.py#L77-L90
[ "def", "dispatch", "(", "self", ",", "event", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# No event, no subscribers.", "if", "event", "not", "in", "self", ".", "_subscribers", ":", "return", "for", "subscriber", "in", "self", ".", "_subscribers", "[", "event", "]", ":", "subscriber", ".", "callback", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_Broker.unsubscribe
Unsubscribe the specific callback to the event. Args event (String): The event to unsubscribe callback (callable): The callback that won't be executed anymore Returns True: if we have successfully unsubscribed to the event False: if there's no callback previously registered
qiskit/tools/events/pubsub.py
def unsubscribe(self, event, callback): """ Unsubscribe the specific callback to the event. Args event (String): The event to unsubscribe callback (callable): The callback that won't be executed anymore Returns True: if we have successfully unsubscribed to the event False: if there's no callback previously registered """ try: self._subscribers[event].remove(self._Subscription(event, callback)) except KeyError: return False return True
def unsubscribe(self, event, callback): """ Unsubscribe the specific callback to the event. Args event (String): The event to unsubscribe callback (callable): The callback that won't be executed anymore Returns True: if we have successfully unsubscribed to the event False: if there's no callback previously registered """ try: self._subscribers[event].remove(self._Subscription(event, callback)) except KeyError: return False return True
[ "Unsubscribe", "the", "specific", "callback", "to", "the", "event", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/events/pubsub.py#L92-L109
[ "def", "unsubscribe", "(", "self", ",", "event", ",", "callback", ")", ":", "try", ":", "self", ".", "_subscribers", "[", "event", "]", ".", "remove", "(", "self", ".", "_Subscription", "(", "event", ",", "callback", ")", ")", "except", "KeyError", ":", "return", "False", "return", "True" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Publisher.publish
Triggers an event, and associates some data to it, so if there are any subscribers, their callback will be called synchronously.
qiskit/tools/events/pubsub.py
def publish(self, event, *args, **kwargs): """ Triggers an event, and associates some data to it, so if there are any subscribers, their callback will be called synchronously. """ return self._broker.dispatch(event, *args, **kwargs)
def publish(self, event, *args, **kwargs): """ Triggers an event, and associates some data to it, so if there are any subscribers, their callback will be called synchronously. """ return self._broker.dispatch(event, *args, **kwargs)
[ "Triggers", "an", "event", "and", "associates", "some", "data", "to", "it", "so", "if", "there", "are", "any", "subscribers", "their", "callback", "will", "be", "called", "synchronously", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/events/pubsub.py#L125-L128
[ "def", "publish", "(", "self", ",", "event", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_broker", ".", "dispatch", "(", "event", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
initialize
Apply initialize to circuit.
qiskit/extensions/initializer.py
def initialize(self, params, qubits): """Apply initialize to circuit.""" if isinstance(qubits, QuantumRegister): qubits = qubits[:] else: qubits = _convert_to_bits([qubits], [qbit for qreg in self.qregs for qbit in qreg])[0] return self.append(Initialize(params), qubits)
def initialize(self, params, qubits): """Apply initialize to circuit.""" if isinstance(qubits, QuantumRegister): qubits = qubits[:] else: qubits = _convert_to_bits([qubits], [qbit for qreg in self.qregs for qbit in qreg])[0] return self.append(Initialize(params), qubits)
[ "Apply", "initialize", "to", "circuit", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/initializer.py#L236-L242
[ "def", "initialize", "(", "self", ",", "params", ",", "qubits", ")", ":", "if", "isinstance", "(", "qubits", ",", "QuantumRegister", ")", ":", "qubits", "=", "qubits", "[", ":", "]", "else", ":", "qubits", "=", "_convert_to_bits", "(", "[", "qubits", "]", ",", "[", "qbit", "for", "qreg", "in", "self", ".", "qregs", "for", "qbit", "in", "qreg", "]", ")", "[", "0", "]", "return", "self", ".", "append", "(", "Initialize", "(", "params", ")", ",", "qubits", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Initialize._define
Calculate a subcircuit that implements this initialization Implements a recursive initialization algorithm, including optimizations, from "Synthesis of Quantum Logic Circuits" Shende, Bullock, Markov https://arxiv.org/abs/quant-ph/0406176v5 Additionally implements some extra optimizations: remove zero rotations and double cnots.
qiskit/extensions/initializer.py
def _define(self): """Calculate a subcircuit that implements this initialization Implements a recursive initialization algorithm, including optimizations, from "Synthesis of Quantum Logic Circuits" Shende, Bullock, Markov https://arxiv.org/abs/quant-ph/0406176v5 Additionally implements some extra optimizations: remove zero rotations and double cnots. """ # call to generate the circuit that takes the desired vector to zero disentangling_circuit = self.gates_to_uncompute() # invert the circuit to create the desired vector from zero (assuming # the qubits are in the zero state) initialize_instr = disentangling_circuit.to_instruction().inverse() q = QuantumRegister(self.num_qubits, 'q') initialize_circuit = QuantumCircuit(q, name='init_def') for qubit in q: initialize_circuit.append(Reset(), [qubit]) initialize_circuit.append(initialize_instr, q[:]) self.definition = initialize_circuit.data
def _define(self): """Calculate a subcircuit that implements this initialization Implements a recursive initialization algorithm, including optimizations, from "Synthesis of Quantum Logic Circuits" Shende, Bullock, Markov https://arxiv.org/abs/quant-ph/0406176v5 Additionally implements some extra optimizations: remove zero rotations and double cnots. """ # call to generate the circuit that takes the desired vector to zero disentangling_circuit = self.gates_to_uncompute() # invert the circuit to create the desired vector from zero (assuming # the qubits are in the zero state) initialize_instr = disentangling_circuit.to_instruction().inverse() q = QuantumRegister(self.num_qubits, 'q') initialize_circuit = QuantumCircuit(q, name='init_def') for qubit in q: initialize_circuit.append(Reset(), [qubit]) initialize_circuit.append(initialize_instr, q[:]) self.definition = initialize_circuit.data
[ "Calculate", "a", "subcircuit", "that", "implements", "this", "initialization" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/initializer.py#L57-L80
[ "def", "_define", "(", "self", ")", ":", "# call to generate the circuit that takes the desired vector to zero", "disentangling_circuit", "=", "self", ".", "gates_to_uncompute", "(", ")", "# invert the circuit to create the desired vector from zero (assuming", "# the qubits are in the zero state)", "initialize_instr", "=", "disentangling_circuit", ".", "to_instruction", "(", ")", ".", "inverse", "(", ")", "q", "=", "QuantumRegister", "(", "self", ".", "num_qubits", ",", "'q'", ")", "initialize_circuit", "=", "QuantumCircuit", "(", "q", ",", "name", "=", "'init_def'", ")", "for", "qubit", "in", "q", ":", "initialize_circuit", ".", "append", "(", "Reset", "(", ")", ",", "[", "qubit", "]", ")", "initialize_circuit", ".", "append", "(", "initialize_instr", ",", "q", "[", ":", "]", ")", "self", ".", "definition", "=", "initialize_circuit", ".", "data" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Initialize.gates_to_uncompute
Call to create a circuit with gates that take the desired vector to zero. Returns: QuantumCircuit: circuit to take self.params vector to |00..0>
qiskit/extensions/initializer.py
def gates_to_uncompute(self): """ Call to create a circuit with gates that take the desired vector to zero. Returns: QuantumCircuit: circuit to take self.params vector to |00..0> """ q = QuantumRegister(self.num_qubits) circuit = QuantumCircuit(q, name='disentangler') # kick start the peeling loop, and disentangle one-by-one from LSB to MSB remaining_param = self.params for i in range(self.num_qubits): # work out which rotations must be done to disentangle the LSB # qubit (we peel away one qubit at a time) (remaining_param, thetas, phis) = Initialize._rotations_to_disentangle(remaining_param) # perform the required rotations to decouple the LSB qubit (so that # it can be "factored" out, leaving a shorter amplitude vector to peel away) rz_mult = self._multiplex(RZGate, phis) ry_mult = self._multiplex(RYGate, thetas) circuit.append(rz_mult.to_instruction(), q[i:self.num_qubits]) circuit.append(ry_mult.to_instruction(), q[i:self.num_qubits]) return circuit
def gates_to_uncompute(self): """ Call to create a circuit with gates that take the desired vector to zero. Returns: QuantumCircuit: circuit to take self.params vector to |00..0> """ q = QuantumRegister(self.num_qubits) circuit = QuantumCircuit(q, name='disentangler') # kick start the peeling loop, and disentangle one-by-one from LSB to MSB remaining_param = self.params for i in range(self.num_qubits): # work out which rotations must be done to disentangle the LSB # qubit (we peel away one qubit at a time) (remaining_param, thetas, phis) = Initialize._rotations_to_disentangle(remaining_param) # perform the required rotations to decouple the LSB qubit (so that # it can be "factored" out, leaving a shorter amplitude vector to peel away) rz_mult = self._multiplex(RZGate, phis) ry_mult = self._multiplex(RYGate, thetas) circuit.append(rz_mult.to_instruction(), q[i:self.num_qubits]) circuit.append(ry_mult.to_instruction(), q[i:self.num_qubits]) return circuit
[ "Call", "to", "create", "a", "circuit", "with", "gates", "that", "take", "the", "desired", "vector", "to", "zero", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/initializer.py#L82-L109
[ "def", "gates_to_uncompute", "(", "self", ")", ":", "q", "=", "QuantumRegister", "(", "self", ".", "num_qubits", ")", "circuit", "=", "QuantumCircuit", "(", "q", ",", "name", "=", "'disentangler'", ")", "# kick start the peeling loop, and disentangle one-by-one from LSB to MSB", "remaining_param", "=", "self", ".", "params", "for", "i", "in", "range", "(", "self", ".", "num_qubits", ")", ":", "# work out which rotations must be done to disentangle the LSB", "# qubit (we peel away one qubit at a time)", "(", "remaining_param", ",", "thetas", ",", "phis", ")", "=", "Initialize", ".", "_rotations_to_disentangle", "(", "remaining_param", ")", "# perform the required rotations to decouple the LSB qubit (so that", "# it can be \"factored\" out, leaving a shorter amplitude vector to peel away)", "rz_mult", "=", "self", ".", "_multiplex", "(", "RZGate", ",", "phis", ")", "ry_mult", "=", "self", ".", "_multiplex", "(", "RYGate", ",", "thetas", ")", "circuit", ".", "append", "(", "rz_mult", ".", "to_instruction", "(", ")", ",", "q", "[", "i", ":", "self", ".", "num_qubits", "]", ")", "circuit", ".", "append", "(", "ry_mult", ".", "to_instruction", "(", ")", ",", "q", "[", "i", ":", "self", ".", "num_qubits", "]", ")", "return", "circuit" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Initialize._rotations_to_disentangle
Static internal method to work out Ry and Rz rotation angles used to disentangle the LSB qubit. These rotations make up the block diagonal matrix U (i.e. multiplexor) that disentangles the LSB. [[Ry(theta_1).Rz(phi_1) 0 . . 0], [0 Ry(theta_2).Rz(phi_2) . 0], . . 0 0 Ry(theta_2^n).Rz(phi_2^n)]]
qiskit/extensions/initializer.py
def _rotations_to_disentangle(local_param): """ Static internal method to work out Ry and Rz rotation angles used to disentangle the LSB qubit. These rotations make up the block diagonal matrix U (i.e. multiplexor) that disentangles the LSB. [[Ry(theta_1).Rz(phi_1) 0 . . 0], [0 Ry(theta_2).Rz(phi_2) . 0], . . 0 0 Ry(theta_2^n).Rz(phi_2^n)]] """ remaining_vector = [] thetas = [] phis = [] param_len = len(local_param) for i in range(param_len // 2): # Ry and Rz rotations to move bloch vector from 0 to "imaginary" # qubit # (imagine a qubit state signified by the amplitudes at index 2*i # and 2*(i+1), corresponding to the select qubits of the # multiplexor being in state |i>) (remains, add_theta, add_phi) = Initialize._bloch_angles(local_param[2 * i: 2 * (i + 1)]) remaining_vector.append(remains) # rotations for all imaginary qubits of the full vector # to move from where it is to zero, hence the negative sign thetas.append(-add_theta) phis.append(-add_phi) return remaining_vector, thetas, phis
def _rotations_to_disentangle(local_param): """ Static internal method to work out Ry and Rz rotation angles used to disentangle the LSB qubit. These rotations make up the block diagonal matrix U (i.e. multiplexor) that disentangles the LSB. [[Ry(theta_1).Rz(phi_1) 0 . . 0], [0 Ry(theta_2).Rz(phi_2) . 0], . . 0 0 Ry(theta_2^n).Rz(phi_2^n)]] """ remaining_vector = [] thetas = [] phis = [] param_len = len(local_param) for i in range(param_len // 2): # Ry and Rz rotations to move bloch vector from 0 to "imaginary" # qubit # (imagine a qubit state signified by the amplitudes at index 2*i # and 2*(i+1), corresponding to the select qubits of the # multiplexor being in state |i>) (remains, add_theta, add_phi) = Initialize._bloch_angles(local_param[2 * i: 2 * (i + 1)]) remaining_vector.append(remains) # rotations for all imaginary qubits of the full vector # to move from where it is to zero, hence the negative sign thetas.append(-add_theta) phis.append(-add_phi) return remaining_vector, thetas, phis
[ "Static", "internal", "method", "to", "work", "out", "Ry", "and", "Rz", "rotation", "angles", "used", "to", "disentangle", "the", "LSB", "qubit", ".", "These", "rotations", "make", "up", "the", "block", "diagonal", "matrix", "U", "(", "i", ".", "e", ".", "multiplexor", ")", "that", "disentangles", "the", "LSB", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/initializer.py#L112-L148
[ "def", "_rotations_to_disentangle", "(", "local_param", ")", ":", "remaining_vector", "=", "[", "]", "thetas", "=", "[", "]", "phis", "=", "[", "]", "param_len", "=", "len", "(", "local_param", ")", "for", "i", "in", "range", "(", "param_len", "//", "2", ")", ":", "# Ry and Rz rotations to move bloch vector from 0 to \"imaginary\"", "# qubit", "# (imagine a qubit state signified by the amplitudes at index 2*i", "# and 2*(i+1), corresponding to the select qubits of the", "# multiplexor being in state |i>)", "(", "remains", ",", "add_theta", ",", "add_phi", ")", "=", "Initialize", ".", "_bloch_angles", "(", "local_param", "[", "2", "*", "i", ":", "2", "*", "(", "i", "+", "1", ")", "]", ")", "remaining_vector", ".", "append", "(", "remains", ")", "# rotations for all imaginary qubits of the full vector", "# to move from where it is to zero, hence the negative sign", "thetas", ".", "append", "(", "-", "add_theta", ")", "phis", ".", "append", "(", "-", "add_phi", ")", "return", "remaining_vector", ",", "thetas", ",", "phis" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Initialize._bloch_angles
Static internal method to work out rotation to create the passed in qubit from the zero vector.
qiskit/extensions/initializer.py
def _bloch_angles(pair_of_complex): """ Static internal method to work out rotation to create the passed in qubit from the zero vector. """ [a_complex, b_complex] = pair_of_complex # Force a and b to be complex, as otherwise numpy.angle might fail. a_complex = complex(a_complex) b_complex = complex(b_complex) mag_a = np.absolute(a_complex) final_r = float(np.sqrt(mag_a ** 2 + np.absolute(b_complex) ** 2)) if final_r < _EPS: theta = 0 phi = 0 final_r = 0 final_t = 0 else: theta = float(2 * np.arccos(mag_a / final_r)) a_arg = np.angle(a_complex) b_arg = np.angle(b_complex) final_t = a_arg + b_arg phi = b_arg - a_arg return final_r * np.exp(1.J * final_t / 2), theta, phi
def _bloch_angles(pair_of_complex): """ Static internal method to work out rotation to create the passed in qubit from the zero vector. """ [a_complex, b_complex] = pair_of_complex # Force a and b to be complex, as otherwise numpy.angle might fail. a_complex = complex(a_complex) b_complex = complex(b_complex) mag_a = np.absolute(a_complex) final_r = float(np.sqrt(mag_a ** 2 + np.absolute(b_complex) ** 2)) if final_r < _EPS: theta = 0 phi = 0 final_r = 0 final_t = 0 else: theta = float(2 * np.arccos(mag_a / final_r)) a_arg = np.angle(a_complex) b_arg = np.angle(b_complex) final_t = a_arg + b_arg phi = b_arg - a_arg return final_r * np.exp(1.J * final_t / 2), theta, phi
[ "Static", "internal", "method", "to", "work", "out", "rotation", "to", "create", "the", "passed", "in", "qubit", "from", "the", "zero", "vector", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/initializer.py#L151-L174
[ "def", "_bloch_angles", "(", "pair_of_complex", ")", ":", "[", "a_complex", ",", "b_complex", "]", "=", "pair_of_complex", "# Force a and b to be complex, as otherwise numpy.angle might fail.", "a_complex", "=", "complex", "(", "a_complex", ")", "b_complex", "=", "complex", "(", "b_complex", ")", "mag_a", "=", "np", ".", "absolute", "(", "a_complex", ")", "final_r", "=", "float", "(", "np", ".", "sqrt", "(", "mag_a", "**", "2", "+", "np", ".", "absolute", "(", "b_complex", ")", "**", "2", ")", ")", "if", "final_r", "<", "_EPS", ":", "theta", "=", "0", "phi", "=", "0", "final_r", "=", "0", "final_t", "=", "0", "else", ":", "theta", "=", "float", "(", "2", "*", "np", ".", "arccos", "(", "mag_a", "/", "final_r", ")", ")", "a_arg", "=", "np", ".", "angle", "(", "a_complex", ")", "b_arg", "=", "np", ".", "angle", "(", "b_complex", ")", "final_t", "=", "a_arg", "+", "b_arg", "phi", "=", "b_arg", "-", "a_arg", "return", "final_r", "*", "np", ".", "exp", "(", "1.J", "*", "final_t", "/", "2", ")", ",", "theta", ",", "phi" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Initialize._multiplex
Return a recursive implementation of a multiplexor circuit, where each instruction itself has a decomposition based on smaller multiplexors. The LSB is the multiplexor "data" and the other bits are multiplexor "select". Args: target_gate (Gate): Ry or Rz gate to apply to target qubit, multiplexed over all other "select" qubits list_of_angles (list[float]): list of rotation angles to apply Ry and Rz Returns: DAGCircuit: the circuit implementing the multiplexor's action
qiskit/extensions/initializer.py
def _multiplex(self, target_gate, list_of_angles): """ Return a recursive implementation of a multiplexor circuit, where each instruction itself has a decomposition based on smaller multiplexors. The LSB is the multiplexor "data" and the other bits are multiplexor "select". Args: target_gate (Gate): Ry or Rz gate to apply to target qubit, multiplexed over all other "select" qubits list_of_angles (list[float]): list of rotation angles to apply Ry and Rz Returns: DAGCircuit: the circuit implementing the multiplexor's action """ list_len = len(list_of_angles) local_num_qubits = int(math.log2(list_len)) + 1 q = QuantumRegister(local_num_qubits) circuit = QuantumCircuit(q, name="multiplex" + local_num_qubits.__str__()) lsb = q[0] msb = q[local_num_qubits - 1] # case of no multiplexing: base case for recursion if local_num_qubits == 1: circuit.append(target_gate(list_of_angles[0]), [q[0]]) return circuit # calc angle weights, assuming recursion (that is the lower-level # requested angles have been correctly implemented by recursion angle_weight = scipy.kron([[0.5, 0.5], [0.5, -0.5]], np.identity(2 ** (local_num_qubits - 2))) # calc the combo angles list_of_angles = angle_weight.dot(np.array(list_of_angles)).tolist() # recursive step on half the angles fulfilling the above assumption multiplex_1 = self._multiplex(target_gate, list_of_angles[0:(list_len // 2)]) circuit.append(multiplex_1.to_instruction(), q[0:-1]) # attach CNOT as follows, thereby flipping the LSB qubit circuit.append(CnotGate(), [msb, lsb]) # implement extra efficiency from the paper of cancelling adjacent # CNOTs (by leaving out last CNOT and reversing (NOT inverting) the # second lower-level multiplex) multiplex_2 = self._multiplex(target_gate, list_of_angles[(list_len // 2):]) if list_len > 1: circuit.append(multiplex_2.to_instruction().mirror(), q[0:-1]) else: circuit.append(multiplex_2.to_instruction(), q[0:-1]) # attach a final CNOT circuit.append(CnotGate(), [msb, lsb]) return circuit
def _multiplex(self, target_gate, list_of_angles): """ Return a recursive implementation of a multiplexor circuit, where each instruction itself has a decomposition based on smaller multiplexors. The LSB is the multiplexor "data" and the other bits are multiplexor "select". Args: target_gate (Gate): Ry or Rz gate to apply to target qubit, multiplexed over all other "select" qubits list_of_angles (list[float]): list of rotation angles to apply Ry and Rz Returns: DAGCircuit: the circuit implementing the multiplexor's action """ list_len = len(list_of_angles) local_num_qubits = int(math.log2(list_len)) + 1 q = QuantumRegister(local_num_qubits) circuit = QuantumCircuit(q, name="multiplex" + local_num_qubits.__str__()) lsb = q[0] msb = q[local_num_qubits - 1] # case of no multiplexing: base case for recursion if local_num_qubits == 1: circuit.append(target_gate(list_of_angles[0]), [q[0]]) return circuit # calc angle weights, assuming recursion (that is the lower-level # requested angles have been correctly implemented by recursion angle_weight = scipy.kron([[0.5, 0.5], [0.5, -0.5]], np.identity(2 ** (local_num_qubits - 2))) # calc the combo angles list_of_angles = angle_weight.dot(np.array(list_of_angles)).tolist() # recursive step on half the angles fulfilling the above assumption multiplex_1 = self._multiplex(target_gate, list_of_angles[0:(list_len // 2)]) circuit.append(multiplex_1.to_instruction(), q[0:-1]) # attach CNOT as follows, thereby flipping the LSB qubit circuit.append(CnotGate(), [msb, lsb]) # implement extra efficiency from the paper of cancelling adjacent # CNOTs (by leaving out last CNOT and reversing (NOT inverting) the # second lower-level multiplex) multiplex_2 = self._multiplex(target_gate, list_of_angles[(list_len // 2):]) if list_len > 1: circuit.append(multiplex_2.to_instruction().mirror(), q[0:-1]) else: circuit.append(multiplex_2.to_instruction(), q[0:-1]) # attach a final CNOT circuit.append(CnotGate(), [msb, lsb]) return circuit
[ "Return", "a", "recursive", "implementation", "of", "a", "multiplexor", "circuit", "where", "each", "instruction", "itself", "has", "a", "decomposition", "based", "on", "smaller", "multiplexors", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/initializer.py#L176-L233
[ "def", "_multiplex", "(", "self", ",", "target_gate", ",", "list_of_angles", ")", ":", "list_len", "=", "len", "(", "list_of_angles", ")", "local_num_qubits", "=", "int", "(", "math", ".", "log2", "(", "list_len", ")", ")", "+", "1", "q", "=", "QuantumRegister", "(", "local_num_qubits", ")", "circuit", "=", "QuantumCircuit", "(", "q", ",", "name", "=", "\"multiplex\"", "+", "local_num_qubits", ".", "__str__", "(", ")", ")", "lsb", "=", "q", "[", "0", "]", "msb", "=", "q", "[", "local_num_qubits", "-", "1", "]", "# case of no multiplexing: base case for recursion", "if", "local_num_qubits", "==", "1", ":", "circuit", ".", "append", "(", "target_gate", "(", "list_of_angles", "[", "0", "]", ")", ",", "[", "q", "[", "0", "]", "]", ")", "return", "circuit", "# calc angle weights, assuming recursion (that is the lower-level", "# requested angles have been correctly implemented by recursion", "angle_weight", "=", "scipy", ".", "kron", "(", "[", "[", "0.5", ",", "0.5", "]", ",", "[", "0.5", ",", "-", "0.5", "]", "]", ",", "np", ".", "identity", "(", "2", "**", "(", "local_num_qubits", "-", "2", ")", ")", ")", "# calc the combo angles", "list_of_angles", "=", "angle_weight", ".", "dot", "(", "np", ".", "array", "(", "list_of_angles", ")", ")", ".", "tolist", "(", ")", "# recursive step on half the angles fulfilling the above assumption", "multiplex_1", "=", "self", ".", "_multiplex", "(", "target_gate", ",", "list_of_angles", "[", "0", ":", "(", "list_len", "//", "2", ")", "]", ")", "circuit", ".", "append", "(", "multiplex_1", ".", "to_instruction", "(", ")", ",", "q", "[", "0", ":", "-", "1", "]", ")", "# attach CNOT as follows, thereby flipping the LSB qubit", "circuit", ".", "append", "(", "CnotGate", "(", ")", ",", "[", "msb", ",", "lsb", "]", ")", "# implement extra efficiency from the paper of cancelling adjacent", "# CNOTs (by leaving out last CNOT and reversing (NOT inverting) the", "# second lower-level multiplex)", "multiplex_2", "=", "self", ".", "_multiplex", "(", "target_gate", ",", "list_of_angles", "[", "(", "list_len", "//", "2", ")", ":", "]", ")", "if", "list_len", ">", "1", ":", "circuit", ".", "append", "(", "multiplex_2", ".", "to_instruction", "(", ")", ".", "mirror", "(", ")", ",", "q", "[", "0", ":", "-", "1", "]", ")", "else", ":", "circuit", ".", "append", "(", "multiplex_2", ".", "to_instruction", "(", ")", ",", "q", "[", "0", ":", "-", "1", "]", ")", "# attach a final CNOT", "circuit", ".", "append", "(", "CnotGate", "(", ")", ",", "[", "msb", ",", "lsb", "]", ")", "return", "circuit" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Layout.from_dict
Populates a Layout from a dictionary. The dictionary must be a bijective mapping between virtual qubits (tuple) and physical qubits (int). Args: input_dict (dict): e.g.: {(QuantumRegister(3, 'qr'), 0): 0, (QuantumRegister(3, 'qr'), 1): 1, (QuantumRegister(3, 'qr'), 2): 2} Can be written more concisely as follows: virtual to physical: {qr[0]: 0, qr[1]: 1, qr[2]: 2} physical to virtual: {0: qr[0], 1: qr[1], 2: qr[2]}
qiskit/transpiler/layout.py
def from_dict(self, input_dict): """ Populates a Layout from a dictionary. The dictionary must be a bijective mapping between virtual qubits (tuple) and physical qubits (int). Args: input_dict (dict): e.g.: {(QuantumRegister(3, 'qr'), 0): 0, (QuantumRegister(3, 'qr'), 1): 1, (QuantumRegister(3, 'qr'), 2): 2} Can be written more concisely as follows: virtual to physical: {qr[0]: 0, qr[1]: 1, qr[2]: 2} physical to virtual: {0: qr[0], 1: qr[1], 2: qr[2]} """ # TODO (luciano): Remove this full block after 0.8. # its here to support {("qr", 0): ("q", 0),...} if len(input_dict) >= 1: key = list(input_dict.keys())[0] value = input_dict[key] if (isinstance(key, tuple) and # pylint: disable=too-many-boolean-expressions len(key) == 2 and isinstance(key[0], str) and isinstance(key[1], int) and isinstance(value, tuple) and len(value) == 2 and isinstance(key[0], str) and isinstance(key[1], int)): warnings.warn("This form of dictionary (i.e. {(\"%s\",%s):(\"%s\",%s), ...} is " "going to be deprecated after 0.8." % (key + value), DeprecationWarning) qreg_names = {qubit[0] for qubit in input_dict.keys()} qregs = {} for qreg_name in qreg_names: qregs[qreg_name] = QuantumRegister( max([qubit[1] for qubit in input_dict.keys() if qubit[0] == qreg_name]) + 1, qreg_name) new_input_dict = {} for key, value in input_dict.items(): new_input_dict[value[1]] = (qregs[key[0]], key[1]) input_dict = new_input_dict for key, value in input_dict.items(): virtual, physical = Layout.order_based_on_type(key, value) self._p2v[physical] = virtual if virtual is None: continue self._v2p[virtual] = physical
def from_dict(self, input_dict): """ Populates a Layout from a dictionary. The dictionary must be a bijective mapping between virtual qubits (tuple) and physical qubits (int). Args: input_dict (dict): e.g.: {(QuantumRegister(3, 'qr'), 0): 0, (QuantumRegister(3, 'qr'), 1): 1, (QuantumRegister(3, 'qr'), 2): 2} Can be written more concisely as follows: virtual to physical: {qr[0]: 0, qr[1]: 1, qr[2]: 2} physical to virtual: {0: qr[0], 1: qr[1], 2: qr[2]} """ # TODO (luciano): Remove this full block after 0.8. # its here to support {("qr", 0): ("q", 0),...} if len(input_dict) >= 1: key = list(input_dict.keys())[0] value = input_dict[key] if (isinstance(key, tuple) and # pylint: disable=too-many-boolean-expressions len(key) == 2 and isinstance(key[0], str) and isinstance(key[1], int) and isinstance(value, tuple) and len(value) == 2 and isinstance(key[0], str) and isinstance(key[1], int)): warnings.warn("This form of dictionary (i.e. {(\"%s\",%s):(\"%s\",%s), ...} is " "going to be deprecated after 0.8." % (key + value), DeprecationWarning) qreg_names = {qubit[0] for qubit in input_dict.keys()} qregs = {} for qreg_name in qreg_names: qregs[qreg_name] = QuantumRegister( max([qubit[1] for qubit in input_dict.keys() if qubit[0] == qreg_name]) + 1, qreg_name) new_input_dict = {} for key, value in input_dict.items(): new_input_dict[value[1]] = (qregs[key[0]], key[1]) input_dict = new_input_dict for key, value in input_dict.items(): virtual, physical = Layout.order_based_on_type(key, value) self._p2v[physical] = virtual if virtual is None: continue self._v2p[virtual] = physical
[ "Populates", "a", "Layout", "from", "a", "dictionary", ".", "The", "dictionary", "must", "be", "a", "bijective", "mapping", "between", "virtual", "qubits", "(", "tuple", ")", "and", "physical", "qubits", "(", "int", ")", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/layout.py#L44-L101
[ "def", "from_dict", "(", "self", ",", "input_dict", ")", ":", "# TODO (luciano): Remove this full block after 0.8.", "# its here to support {(\"qr\", 0): (\"q\", 0),...}", "if", "len", "(", "input_dict", ")", ">=", "1", ":", "key", "=", "list", "(", "input_dict", ".", "keys", "(", ")", ")", "[", "0", "]", "value", "=", "input_dict", "[", "key", "]", "if", "(", "isinstance", "(", "key", ",", "tuple", ")", "and", "# pylint: disable=too-many-boolean-expressions", "len", "(", "key", ")", "==", "2", "and", "isinstance", "(", "key", "[", "0", "]", ",", "str", ")", "and", "isinstance", "(", "key", "[", "1", "]", ",", "int", ")", "and", "isinstance", "(", "value", ",", "tuple", ")", "and", "len", "(", "value", ")", "==", "2", "and", "isinstance", "(", "key", "[", "0", "]", ",", "str", ")", "and", "isinstance", "(", "key", "[", "1", "]", ",", "int", ")", ")", ":", "warnings", ".", "warn", "(", "\"This form of dictionary (i.e. {(\\\"%s\\\",%s):(\\\"%s\\\",%s), ...} is \"", "\"going to be deprecated after 0.8.\"", "%", "(", "key", "+", "value", ")", ",", "DeprecationWarning", ")", "qreg_names", "=", "{", "qubit", "[", "0", "]", "for", "qubit", "in", "input_dict", ".", "keys", "(", ")", "}", "qregs", "=", "{", "}", "for", "qreg_name", "in", "qreg_names", ":", "qregs", "[", "qreg_name", "]", "=", "QuantumRegister", "(", "max", "(", "[", "qubit", "[", "1", "]", "for", "qubit", "in", "input_dict", ".", "keys", "(", ")", "if", "qubit", "[", "0", "]", "==", "qreg_name", "]", ")", "+", "1", ",", "qreg_name", ")", "new_input_dict", "=", "{", "}", "for", "key", ",", "value", "in", "input_dict", ".", "items", "(", ")", ":", "new_input_dict", "[", "value", "[", "1", "]", "]", "=", "(", "qregs", "[", "key", "[", "0", "]", "]", ",", "key", "[", "1", "]", ")", "input_dict", "=", "new_input_dict", "for", "key", ",", "value", "in", "input_dict", ".", "items", "(", ")", ":", "virtual", ",", "physical", "=", "Layout", ".", "order_based_on_type", "(", "key", ",", "value", ")", "self", ".", "_p2v", "[", "physical", "]", "=", "virtual", "if", "virtual", "is", "None", ":", "continue", "self", ".", "_v2p", "[", "virtual", "]", "=", "physical" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Layout.order_based_on_type
decides which one is physical/virtual based on the type. Returns (virtual, physical)
qiskit/transpiler/layout.py
def order_based_on_type(value1, value2): """decides which one is physical/virtual based on the type. Returns (virtual, physical)""" if isinstance(value1, int) and Layout.is_virtual(value2): physical = value1 virtual = value2 elif isinstance(value2, int) and Layout.is_virtual(value1): physical = value2 virtual = value1 else: raise LayoutError('The map (%s -> %s) has to be a ((Register, integer) -> integer)' ' or the other way around.' % (type(value1), type(value2))) return virtual, physical
def order_based_on_type(value1, value2): """decides which one is physical/virtual based on the type. Returns (virtual, physical)""" if isinstance(value1, int) and Layout.is_virtual(value2): physical = value1 virtual = value2 elif isinstance(value2, int) and Layout.is_virtual(value1): physical = value2 virtual = value1 else: raise LayoutError('The map (%s -> %s) has to be a ((Register, integer) -> integer)' ' or the other way around.' % (type(value1), type(value2))) return virtual, physical
[ "decides", "which", "one", "is", "physical", "/", "virtual", "based", "on", "the", "type", ".", "Returns", "(", "virtual", "physical", ")" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/layout.py#L104-L115
[ "def", "order_based_on_type", "(", "value1", ",", "value2", ")", ":", "if", "isinstance", "(", "value1", ",", "int", ")", "and", "Layout", ".", "is_virtual", "(", "value2", ")", ":", "physical", "=", "value1", "virtual", "=", "value2", "elif", "isinstance", "(", "value2", ",", "int", ")", "and", "Layout", ".", "is_virtual", "(", "value1", ")", ":", "physical", "=", "value2", "virtual", "=", "value1", "else", ":", "raise", "LayoutError", "(", "'The map (%s -> %s) has to be a ((Register, integer) -> integer)'", "' or the other way around.'", "%", "(", "type", "(", "value1", ")", ",", "type", "(", "value2", ")", ")", ")", "return", "virtual", ",", "physical" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Layout.is_virtual
Checks if value has the format of a virtual qubit
qiskit/transpiler/layout.py
def is_virtual(value): """Checks if value has the format of a virtual qubit """ return value is None or isinstance(value, tuple) and len(value) == 2 and isinstance( value[0], Register) and isinstance(value[1], int)
def is_virtual(value): """Checks if value has the format of a virtual qubit """ return value is None or isinstance(value, tuple) and len(value) == 2 and isinstance( value[0], Register) and isinstance(value[1], int)
[ "Checks", "if", "value", "has", "the", "format", "of", "a", "virtual", "qubit" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/layout.py#L118-L121
[ "def", "is_virtual", "(", "value", ")", ":", "return", "value", "is", "None", "or", "isinstance", "(", "value", ",", "tuple", ")", "and", "len", "(", "value", ")", "==", "2", "and", "isinstance", "(", "value", "[", "0", "]", ",", "Register", ")", "and", "isinstance", "(", "value", "[", "1", "]", ",", "int", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Layout.copy
Returns a copy of a Layout instance.
qiskit/transpiler/layout.py
def copy(self): """Returns a copy of a Layout instance.""" layout_copy = type(self)() layout_copy._p2v = self._p2v.copy() layout_copy._v2p = self._v2p.copy() return layout_copy
def copy(self): """Returns a copy of a Layout instance.""" layout_copy = type(self)() layout_copy._p2v = self._p2v.copy() layout_copy._v2p = self._v2p.copy() return layout_copy
[ "Returns", "a", "copy", "of", "a", "Layout", "instance", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/layout.py#L160-L167
[ "def", "copy", "(", "self", ")", ":", "layout_copy", "=", "type", "(", "self", ")", "(", ")", "layout_copy", ".", "_p2v", "=", "self", ".", "_p2v", ".", "copy", "(", ")", "layout_copy", ".", "_v2p", "=", "self", ".", "_v2p", ".", "copy", "(", ")", "return", "layout_copy" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Layout.add
Adds a map element between `bit` and `physical_bit`. If `physical_bit` is not defined, `bit` will be mapped to a new physical bit (extending the length of the layout by one.) Args: virtual_bit (tuple): A (qu)bit. For example, (QuantumRegister(3, 'qr'), 2). physical_bit (int): A physical bit. For example, 3.
qiskit/transpiler/layout.py
def add(self, virtual_bit, physical_bit=None): """ Adds a map element between `bit` and `physical_bit`. If `physical_bit` is not defined, `bit` will be mapped to a new physical bit (extending the length of the layout by one.) Args: virtual_bit (tuple): A (qu)bit. For example, (QuantumRegister(3, 'qr'), 2). physical_bit (int): A physical bit. For example, 3. """ if physical_bit is None: physical_candidate = len(self) while physical_candidate in self._p2v: physical_candidate += 1 physical_bit = physical_candidate self[virtual_bit] = physical_bit
def add(self, virtual_bit, physical_bit=None): """ Adds a map element between `bit` and `physical_bit`. If `physical_bit` is not defined, `bit` will be mapped to a new physical bit (extending the length of the layout by one.) Args: virtual_bit (tuple): A (qu)bit. For example, (QuantumRegister(3, 'qr'), 2). physical_bit (int): A physical bit. For example, 3. """ if physical_bit is None: physical_candidate = len(self) while physical_candidate in self._p2v: physical_candidate += 1 physical_bit = physical_candidate self[virtual_bit] = physical_bit
[ "Adds", "a", "map", "element", "between", "bit", "and", "physical_bit", ".", "If", "physical_bit", "is", "not", "defined", "bit", "will", "be", "mapped", "to", "a", "new", "physical", "bit", "(", "extending", "the", "length", "of", "the", "layout", "by", "one", ".", ")", "Args", ":", "virtual_bit", "(", "tuple", ")", ":", "A", "(", "qu", ")", "bit", ".", "For", "example", "(", "QuantumRegister", "(", "3", "qr", ")", "2", ")", ".", "physical_bit", "(", "int", ")", ":", "A", "physical", "bit", ".", "For", "example", "3", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/layout.py#L169-L183
[ "def", "add", "(", "self", ",", "virtual_bit", ",", "physical_bit", "=", "None", ")", ":", "if", "physical_bit", "is", "None", ":", "physical_candidate", "=", "len", "(", "self", ")", "while", "physical_candidate", "in", "self", ".", "_p2v", ":", "physical_candidate", "+=", "1", "physical_bit", "=", "physical_candidate", "self", "[", "virtual_bit", "]", "=", "physical_bit" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Layout.swap
Swaps the map between left and right. Args: left (tuple or int): Item to swap with right. right (tuple or int): Item to swap with left. Raises: LayoutError: If left and right have not the same type.
qiskit/transpiler/layout.py
def swap(self, left, right): """Swaps the map between left and right. Args: left (tuple or int): Item to swap with right. right (tuple or int): Item to swap with left. Raises: LayoutError: If left and right have not the same type. """ if type(left) is not type(right): raise LayoutError('The method swap only works with elements of the same type.') temp = self[left] self[left] = self[right] self[right] = temp
def swap(self, left, right): """Swaps the map between left and right. Args: left (tuple or int): Item to swap with right. right (tuple or int): Item to swap with left. Raises: LayoutError: If left and right have not the same type. """ if type(left) is not type(right): raise LayoutError('The method swap only works with elements of the same type.') temp = self[left] self[left] = self[right] self[right] = temp
[ "Swaps", "the", "map", "between", "left", "and", "right", ".", "Args", ":", "left", "(", "tuple", "or", "int", ")", ":", "Item", "to", "swap", "with", "right", ".", "right", "(", "tuple", "or", "int", ")", ":", "Item", "to", "swap", "with", "left", ".", "Raises", ":", "LayoutError", ":", "If", "left", "and", "right", "have", "not", "the", "same", "type", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/layout.py#L216-L228
[ "def", "swap", "(", "self", ",", "left", ",", "right", ")", ":", "if", "type", "(", "left", ")", "is", "not", "type", "(", "right", ")", ":", "raise", "LayoutError", "(", "'The method swap only works with elements of the same type.'", ")", "temp", "=", "self", "[", "left", "]", "self", "[", "left", "]", "=", "self", "[", "right", "]", "self", "[", "right", "]", "=", "temp" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Layout.combine_into_edge_map
Combines self and another_layout into an "edge map". For example:: self another_layout resulting edge map qr_1 -> 0 0 <- q_2 qr_1 -> q_2 qr_2 -> 2 2 <- q_1 qr_2 -> q_1 qr_3 -> 3 3 <- q_0 qr_3 -> q_0 The edge map is used to compose dags via, for example, compose_back. Args: another_layout (Layout): The other layout to combine. Returns: dict: A "edge map". Raises: LayoutError: another_layout can be bigger than self, but not smaller. Otherwise, raises.
qiskit/transpiler/layout.py
def combine_into_edge_map(self, another_layout): """Combines self and another_layout into an "edge map". For example:: self another_layout resulting edge map qr_1 -> 0 0 <- q_2 qr_1 -> q_2 qr_2 -> 2 2 <- q_1 qr_2 -> q_1 qr_3 -> 3 3 <- q_0 qr_3 -> q_0 The edge map is used to compose dags via, for example, compose_back. Args: another_layout (Layout): The other layout to combine. Returns: dict: A "edge map". Raises: LayoutError: another_layout can be bigger than self, but not smaller. Otherwise, raises. """ edge_map = dict() for virtual, physical in self.get_virtual_bits().items(): if physical not in another_layout._p2v: raise LayoutError('The wire_map_from_layouts() method does not support when the' ' other layout (another_layout) is smaller.') edge_map[virtual] = another_layout[physical] return edge_map
def combine_into_edge_map(self, another_layout): """Combines self and another_layout into an "edge map". For example:: self another_layout resulting edge map qr_1 -> 0 0 <- q_2 qr_1 -> q_2 qr_2 -> 2 2 <- q_1 qr_2 -> q_1 qr_3 -> 3 3 <- q_0 qr_3 -> q_0 The edge map is used to compose dags via, for example, compose_back. Args: another_layout (Layout): The other layout to combine. Returns: dict: A "edge map". Raises: LayoutError: another_layout can be bigger than self, but not smaller. Otherwise, raises. """ edge_map = dict() for virtual, physical in self.get_virtual_bits().items(): if physical not in another_layout._p2v: raise LayoutError('The wire_map_from_layouts() method does not support when the' ' other layout (another_layout) is smaller.') edge_map[virtual] = another_layout[physical] return edge_map
[ "Combines", "self", "and", "another_layout", "into", "an", "edge", "map", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/layout.py#L230-L257
[ "def", "combine_into_edge_map", "(", "self", ",", "another_layout", ")", ":", "edge_map", "=", "dict", "(", ")", "for", "virtual", ",", "physical", "in", "self", ".", "get_virtual_bits", "(", ")", ".", "items", "(", ")", ":", "if", "physical", "not", "in", "another_layout", ".", "_p2v", ":", "raise", "LayoutError", "(", "'The wire_map_from_layouts() method does not support when the'", "' other layout (another_layout) is smaller.'", ")", "edge_map", "[", "virtual", "]", "=", "another_layout", "[", "physical", "]", "return", "edge_map" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Layout.generate_trivial_layout
Creates a trivial ("one-to-one") Layout with the registers in `regs`. Args: *regs (Registers): registers to include in the layout. Returns: Layout: A layout with all the `regs` in the given order.
qiskit/transpiler/layout.py
def generate_trivial_layout(*regs): """ Creates a trivial ("one-to-one") Layout with the registers in `regs`. Args: *regs (Registers): registers to include in the layout. Returns: Layout: A layout with all the `regs` in the given order. """ layout = Layout() for reg in regs: layout.add_register(reg) return layout
def generate_trivial_layout(*regs): """ Creates a trivial ("one-to-one") Layout with the registers in `regs`. Args: *regs (Registers): registers to include in the layout. Returns: Layout: A layout with all the `regs` in the given order. """ layout = Layout() for reg in regs: layout.add_register(reg) return layout
[ "Creates", "a", "trivial", "(", "one", "-", "to", "-", "one", ")", "Layout", "with", "the", "registers", "in", "regs", ".", "Args", ":", "*", "regs", "(", "Registers", ")", ":", "registers", "to", "include", "in", "the", "layout", ".", "Returns", ":", "Layout", ":", "A", "layout", "with", "all", "the", "regs", "in", "the", "given", "order", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/layout.py#L260-L271
[ "def", "generate_trivial_layout", "(", "*", "regs", ")", ":", "layout", "=", "Layout", "(", ")", "for", "reg", "in", "regs", ":", "layout", ".", "add_register", "(", "reg", ")", "return", "layout" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Layout.from_intlist
Converts a list of integers to a Layout mapping virtual qubits (index of the list) to physical qubits (the list values). Args: int_list (list): A list of integers. *qregs (QuantumRegisters): The quantum registers to apply the layout to. Returns: Layout: The corresponding Layout object. Raises: LayoutError: Invalid input layout.
qiskit/transpiler/layout.py
def from_intlist(int_list, *qregs): """Converts a list of integers to a Layout mapping virtual qubits (index of the list) to physical qubits (the list values). Args: int_list (list): A list of integers. *qregs (QuantumRegisters): The quantum registers to apply the layout to. Returns: Layout: The corresponding Layout object. Raises: LayoutError: Invalid input layout. """ if not all((isinstance(i, int) for i in int_list)): raise LayoutError('Expected a list of ints') if len(int_list) != len(set(int_list)): raise LayoutError('Duplicate values not permitted; Layout is bijective.') n_qubits = sum(reg.size for reg in qregs) # Check if list is too short to cover all qubits if len(int_list) < n_qubits: err_msg = 'Integer list length must equal number of qubits in circuit.' raise LayoutError(err_msg) out = Layout() main_idx = 0 for qreg in qregs: for idx in range(qreg.size): out[(qreg, idx)] = int_list[main_idx] main_idx += 1 if main_idx != len(int_list): for int_item in int_list[main_idx:]: out[int_item] = None return out
def from_intlist(int_list, *qregs): """Converts a list of integers to a Layout mapping virtual qubits (index of the list) to physical qubits (the list values). Args: int_list (list): A list of integers. *qregs (QuantumRegisters): The quantum registers to apply the layout to. Returns: Layout: The corresponding Layout object. Raises: LayoutError: Invalid input layout. """ if not all((isinstance(i, int) for i in int_list)): raise LayoutError('Expected a list of ints') if len(int_list) != len(set(int_list)): raise LayoutError('Duplicate values not permitted; Layout is bijective.') n_qubits = sum(reg.size for reg in qregs) # Check if list is too short to cover all qubits if len(int_list) < n_qubits: err_msg = 'Integer list length must equal number of qubits in circuit.' raise LayoutError(err_msg) out = Layout() main_idx = 0 for qreg in qregs: for idx in range(qreg.size): out[(qreg, idx)] = int_list[main_idx] main_idx += 1 if main_idx != len(int_list): for int_item in int_list[main_idx:]: out[int_item] = None return out
[ "Converts", "a", "list", "of", "integers", "to", "a", "Layout", "mapping", "virtual", "qubits", "(", "index", "of", "the", "list", ")", "to", "physical", "qubits", "(", "the", "list", "values", ")", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/layout.py#L274-L306
[ "def", "from_intlist", "(", "int_list", ",", "*", "qregs", ")", ":", "if", "not", "all", "(", "(", "isinstance", "(", "i", ",", "int", ")", "for", "i", "in", "int_list", ")", ")", ":", "raise", "LayoutError", "(", "'Expected a list of ints'", ")", "if", "len", "(", "int_list", ")", "!=", "len", "(", "set", "(", "int_list", ")", ")", ":", "raise", "LayoutError", "(", "'Duplicate values not permitted; Layout is bijective.'", ")", "n_qubits", "=", "sum", "(", "reg", ".", "size", "for", "reg", "in", "qregs", ")", "# Check if list is too short to cover all qubits", "if", "len", "(", "int_list", ")", "<", "n_qubits", ":", "err_msg", "=", "'Integer list length must equal number of qubits in circuit.'", "raise", "LayoutError", "(", "err_msg", ")", "out", "=", "Layout", "(", ")", "main_idx", "=", "0", "for", "qreg", "in", "qregs", ":", "for", "idx", "in", "range", "(", "qreg", ".", "size", ")", ":", "out", "[", "(", "qreg", ",", "idx", ")", "]", "=", "int_list", "[", "main_idx", "]", "main_idx", "+=", "1", "if", "main_idx", "!=", "len", "(", "int_list", ")", ":", "for", "int_item", "in", "int_list", "[", "main_idx", ":", "]", ":", "out", "[", "int_item", "]", "=", "None", "return", "out" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Layout.from_tuplelist
Populates a Layout from a list containing virtual qubits---(QuantumRegister, int) tuples---, or None. Args: tuple_list (list): e.g.: [qr[0], None, qr[2], qr[3]] Returns: Layout: the corresponding Layout object Raises: LayoutError: If the elements are not (Register, integer) or None
qiskit/transpiler/layout.py
def from_tuplelist(tuple_list): """ Populates a Layout from a list containing virtual qubits---(QuantumRegister, int) tuples---, or None. Args: tuple_list (list): e.g.: [qr[0], None, qr[2], qr[3]] Returns: Layout: the corresponding Layout object Raises: LayoutError: If the elements are not (Register, integer) or None """ out = Layout() for physical, virtual in enumerate(tuple_list): if virtual is None: continue elif Layout.is_virtual(virtual): if virtual in out._v2p: raise LayoutError('Duplicate values not permitted; Layout is bijective.') out[virtual] = physical else: raise LayoutError("The list should contain elements of the form" " (Register, integer) or None") return out
def from_tuplelist(tuple_list): """ Populates a Layout from a list containing virtual qubits---(QuantumRegister, int) tuples---, or None. Args: tuple_list (list): e.g.: [qr[0], None, qr[2], qr[3]] Returns: Layout: the corresponding Layout object Raises: LayoutError: If the elements are not (Register, integer) or None """ out = Layout() for physical, virtual in enumerate(tuple_list): if virtual is None: continue elif Layout.is_virtual(virtual): if virtual in out._v2p: raise LayoutError('Duplicate values not permitted; Layout is bijective.') out[virtual] = physical else: raise LayoutError("The list should contain elements of the form" " (Register, integer) or None") return out
[ "Populates", "a", "Layout", "from", "a", "list", "containing", "virtual", "qubits", "---", "(", "QuantumRegister", "int", ")", "tuples", "---", "or", "None", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/layout.py#L309-L333
[ "def", "from_tuplelist", "(", "tuple_list", ")", ":", "out", "=", "Layout", "(", ")", "for", "physical", ",", "virtual", "in", "enumerate", "(", "tuple_list", ")", ":", "if", "virtual", "is", "None", ":", "continue", "elif", "Layout", ".", "is_virtual", "(", "virtual", ")", ":", "if", "virtual", "in", "out", ".", "_v2p", ":", "raise", "LayoutError", "(", "'Duplicate values not permitted; Layout is bijective.'", ")", "out", "[", "virtual", "]", "=", "physical", "else", ":", "raise", "LayoutError", "(", "\"The list should contain elements of the form\"", "\" (Register, integer) or None\"", ")", "return", "out" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
ccx
Apply Toffoli to from ctl1 and ctl2 to tgt.
qiskit/extensions/standard/ccx.py
def ccx(self, ctl1, ctl2, tgt): """Apply Toffoli to from ctl1 and ctl2 to tgt.""" return self.append(ToffoliGate(), [ctl1, ctl2, tgt], [])
def ccx(self, ctl1, ctl2, tgt): """Apply Toffoli to from ctl1 and ctl2 to tgt.""" return self.append(ToffoliGate(), [ctl1, ctl2, tgt], [])
[ "Apply", "Toffoli", "to", "from", "ctl1", "and", "ctl2", "to", "tgt", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/standard/ccx.py#L82-L84
[ "def", "ccx", "(", "self", ",", "ctl1", ",", "ctl2", ",", "tgt", ")", ":", "return", "self", ".", "append", "(", "ToffoliGate", "(", ")", ",", "[", "ctl1", ",", "ctl2", ",", "tgt", "]", ",", "[", "]", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
ToffoliGate._define
gate ccx a,b,c { h c; cx b,c; tdg c; cx a,c; t c; cx b,c; tdg c; cx a,c; t b; t c; h c; cx a,b; t a; tdg b; cx a,b;}
qiskit/extensions/standard/ccx.py
def _define(self): """ gate ccx a,b,c { h c; cx b,c; tdg c; cx a,c; t c; cx b,c; tdg c; cx a,c; t b; t c; h c; cx a,b; t a; tdg b; cx a,b;} """ definition = [] q = QuantumRegister(3, "q") rule = [ (HGate(), [q[2]], []), (CnotGate(), [q[1], q[2]], []), (TdgGate(), [q[2]], []), (CnotGate(), [q[0], q[2]], []), (TGate(), [q[2]], []), (CnotGate(), [q[1], q[2]], []), (TdgGate(), [q[2]], []), (CnotGate(), [q[0], q[2]], []), (TGate(), [q[1]], []), (TGate(), [q[2]], []), (HGate(), [q[2]], []), (CnotGate(), [q[0], q[1]], []), (TGate(), [q[0]], []), (TdgGate(), [q[1]], []), (CnotGate(), [q[0], q[1]], []) ] for inst in rule: definition.append(inst) self.definition = definition
def _define(self): """ gate ccx a,b,c { h c; cx b,c; tdg c; cx a,c; t c; cx b,c; tdg c; cx a,c; t b; t c; h c; cx a,b; t a; tdg b; cx a,b;} """ definition = [] q = QuantumRegister(3, "q") rule = [ (HGate(), [q[2]], []), (CnotGate(), [q[1], q[2]], []), (TdgGate(), [q[2]], []), (CnotGate(), [q[0], q[2]], []), (TGate(), [q[2]], []), (CnotGate(), [q[1], q[2]], []), (TdgGate(), [q[2]], []), (CnotGate(), [q[0], q[2]], []), (TGate(), [q[1]], []), (TGate(), [q[2]], []), (HGate(), [q[2]], []), (CnotGate(), [q[0], q[1]], []), (TGate(), [q[0]], []), (TdgGate(), [q[1]], []), (CnotGate(), [q[0], q[1]], []) ] for inst in rule: definition.append(inst) self.definition = definition
[ "gate", "ccx", "a", "b", "c", "{", "h", "c", ";", "cx", "b", "c", ";", "tdg", "c", ";", "cx", "a", "c", ";", "t", "c", ";", "cx", "b", "c", ";", "tdg", "c", ";", "cx", "a", "c", ";", "t", "b", ";", "t", "c", ";", "h", "c", ";", "cx", "a", "b", ";", "t", "a", ";", "tdg", "b", ";", "cx", "a", "b", ";", "}" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/standard/ccx.py#L32-L62
[ "def", "_define", "(", "self", ")", ":", "definition", "=", "[", "]", "q", "=", "QuantumRegister", "(", "3", ",", "\"q\"", ")", "rule", "=", "[", "(", "HGate", "(", ")", ",", "[", "q", "[", "2", "]", "]", ",", "[", "]", ")", ",", "(", "CnotGate", "(", ")", ",", "[", "q", "[", "1", "]", ",", "q", "[", "2", "]", "]", ",", "[", "]", ")", ",", "(", "TdgGate", "(", ")", ",", "[", "q", "[", "2", "]", "]", ",", "[", "]", ")", ",", "(", "CnotGate", "(", ")", ",", "[", "q", "[", "0", "]", ",", "q", "[", "2", "]", "]", ",", "[", "]", ")", ",", "(", "TGate", "(", ")", ",", "[", "q", "[", "2", "]", "]", ",", "[", "]", ")", ",", "(", "CnotGate", "(", ")", ",", "[", "q", "[", "1", "]", ",", "q", "[", "2", "]", "]", ",", "[", "]", ")", ",", "(", "TdgGate", "(", ")", ",", "[", "q", "[", "2", "]", "]", ",", "[", "]", ")", ",", "(", "CnotGate", "(", ")", ",", "[", "q", "[", "0", "]", ",", "q", "[", "2", "]", "]", ",", "[", "]", ")", ",", "(", "TGate", "(", ")", ",", "[", "q", "[", "1", "]", "]", ",", "[", "]", ")", ",", "(", "TGate", "(", ")", ",", "[", "q", "[", "2", "]", "]", ",", "[", "]", ")", ",", "(", "HGate", "(", ")", ",", "[", "q", "[", "2", "]", "]", ",", "[", "]", ")", ",", "(", "CnotGate", "(", ")", ",", "[", "q", "[", "0", "]", ",", "q", "[", "1", "]", "]", ",", "[", "]", ")", ",", "(", "TGate", "(", ")", ",", "[", "q", "[", "0", "]", "]", ",", "[", "]", ")", ",", "(", "TdgGate", "(", ")", ",", "[", "q", "[", "1", "]", "]", ",", "[", "]", ")", ",", "(", "CnotGate", "(", ")", ",", "[", "q", "[", "0", "]", ",", "q", "[", "1", "]", "]", ",", "[", "]", ")", "]", "for", "inst", "in", "rule", ":", "definition", ".", "append", "(", "inst", ")", "self", ".", "definition", "=", "definition" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Collect2qBlocks.run
collect blocks of adjacent gates acting on a pair of "cx" qubits. The blocks contain "op" nodes in topological sort order such that all gates in a block act on the same pair of qubits and are adjacent in the circuit. the blocks are built by examining predecessors and successors of "cx" gates in the circuit. u1, u2, u3, cx, id gates will be included. Return a list of tuples of "op" node labels.
qiskit/transpiler/passes/collect_2q_blocks.py
def run(self, dag): """collect blocks of adjacent gates acting on a pair of "cx" qubits. The blocks contain "op" nodes in topological sort order such that all gates in a block act on the same pair of qubits and are adjacent in the circuit. the blocks are built by examining predecessors and successors of "cx" gates in the circuit. u1, u2, u3, cx, id gates will be included. Return a list of tuples of "op" node labels. """ # Initiate the commutation set self.property_set['commutation_set'] = defaultdict(list) good_names = ["cx", "u1", "u2", "u3", "id"] block_list = [] nodes = list(dag.topological_nodes()) nodes_seen = dict(zip(nodes, [False] * len(nodes))) for nd in dag.topological_op_nodes(): group = [] # Explore predecessors and successors of cx gates if nd.name == "cx" and nd.condition is None and not nodes_seen[nd]: these_qubits = sorted(nd.qargs) # Explore predecessors of the "cx" node pred = list(dag.predecessors(nd)) explore = True while explore: pred_next = [] # If there is one predecessor, add it if it's on the right qubits if len(pred) == 1 and not nodes_seen[pred[0]]: pnd = pred[0] if pnd.name in good_names: if (pnd.name == "cx" and sorted(pnd.qargs) == these_qubits) or \ pnd.name != "cx": group.append(pnd) nodes_seen[pnd] = True pred_next.extend(dag.predecessors(pnd)) # If there are two, then we consider cases elif len(pred) == 2: # First, check if there is a relationship if pred[0] in dag.predecessors(pred[1]): sorted_pred = [pred[1]] # was [pred[1], pred[0]] elif pred[1] in dag.predecessors(pred[0]): sorted_pred = [pred[0]] # was [pred[0], pred[1]] else: # We need to avoid accidentally adding a cx on these_qubits # since these must have a dependency through the other predecessor # in this case if pred[0].name == "cx" and sorted(pred[0].qargs) == these_qubits: sorted_pred = [pred[1]] elif pred[1].name == "cx" and sorted(pred[1].qargs) == these_qubits: sorted_pred = [pred[0]] else: sorted_pred = pred if len(sorted_pred) == 2 and sorted_pred[0].name == "cx" and \ sorted_pred[1].name == "cx": break # stop immediately if we hit a pair of cx # Examine each predecessor for pnd in sorted_pred: if pnd.name not in good_names: continue # If a predecessor is a single qubit gate, add it if pnd.name != "cx": if not nodes_seen[pnd]: group.append(pnd) nodes_seen[pnd] = True pred_next.extend(dag.predecessors(pnd)) # If cx, check qubits else: pred_qubits = sorted(pnd.qargs) if pred_qubits == these_qubits: # add if on same qubits if not nodes_seen[pnd]: group.append(pnd) nodes_seen[pnd] = True pred_next.extend(dag.predecessors(pnd)) else: # remove qubit from consideration if not these_qubits = list(set(these_qubits) - set(pred_qubits)) # Update predecessors # Stop if there aren't any more pred = list(set(pred_next)) if not pred: explore = False # Reverse the predecessor list and append the "cx" node group.reverse() group.append(nd) nodes_seen[nd] = True # Reset these_qubits these_qubits = sorted(nd.qargs) # Explore successors of the "cx" node succ = list(dag.successors(nd)) explore = True while explore: succ_next = [] # If there is one successor, add it if its on the right qubits if len(succ) == 1 and not nodes_seen[succ[0]]: snd = succ[0] if snd.name in good_names: if (snd.name == "cx" and sorted(snd.qargs) == these_qubits) or \ snd.name != "cx": group.append(snd) nodes_seen[snd] = True succ_next.extend(dag.successors(snd)) # If there are two, then we consider cases elif len(succ) == 2: # First, check if there is a relationship if succ[0] in dag.successors(succ[1]): sorted_succ = [succ[1]] # was [succ[1], succ[0]] elif succ[1] in dag.successors(succ[0]): sorted_succ = [succ[0]] # was [succ[0], succ[1]] else: # We need to avoid accidentally adding a cx on these_qubits # since these must have a dependency through the other successor # in this case if succ[0].name == "cx" and sorted(succ[0].qargs) == these_qubits: sorted_succ = [succ[1]] elif succ[1].name == "cx" and sorted(succ[1].qargs) == these_qubits: sorted_succ = [succ[0]] else: sorted_succ = succ if len(sorted_succ) == 2 and \ sorted_succ[0].name == "cx" and \ sorted_succ[1].name == "cx": break # stop immediately if we hit a pair of cx # Examine each successor for snd in sorted_succ: if snd.name not in good_names: continue # If a successor is a single qubit gate, add it if snd.name != "cx": if not nodes_seen[snd]: group.append(snd) nodes_seen[snd] = True succ_next.extend(dag.successors(snd)) else: # If cx, check qubits succ_qubits = sorted(snd.qargs) if succ_qubits == these_qubits: # add if on same qubits if not nodes_seen[snd]: group.append(snd) nodes_seen[snd] = True succ_next.extend(dag.successors(snd)) else: # remove qubit from consideration if not these_qubits = list(set(these_qubits) - set(succ_qubits)) # Update successors # Stop if there aren't any more succ = list(set(succ_next)) if not succ: explore = False block_list.append(tuple(group)) self.property_set['block_list'] = block_list return dag
def run(self, dag): """collect blocks of adjacent gates acting on a pair of "cx" qubits. The blocks contain "op" nodes in topological sort order such that all gates in a block act on the same pair of qubits and are adjacent in the circuit. the blocks are built by examining predecessors and successors of "cx" gates in the circuit. u1, u2, u3, cx, id gates will be included. Return a list of tuples of "op" node labels. """ # Initiate the commutation set self.property_set['commutation_set'] = defaultdict(list) good_names = ["cx", "u1", "u2", "u3", "id"] block_list = [] nodes = list(dag.topological_nodes()) nodes_seen = dict(zip(nodes, [False] * len(nodes))) for nd in dag.topological_op_nodes(): group = [] # Explore predecessors and successors of cx gates if nd.name == "cx" and nd.condition is None and not nodes_seen[nd]: these_qubits = sorted(nd.qargs) # Explore predecessors of the "cx" node pred = list(dag.predecessors(nd)) explore = True while explore: pred_next = [] # If there is one predecessor, add it if it's on the right qubits if len(pred) == 1 and not nodes_seen[pred[0]]: pnd = pred[0] if pnd.name in good_names: if (pnd.name == "cx" and sorted(pnd.qargs) == these_qubits) or \ pnd.name != "cx": group.append(pnd) nodes_seen[pnd] = True pred_next.extend(dag.predecessors(pnd)) # If there are two, then we consider cases elif len(pred) == 2: # First, check if there is a relationship if pred[0] in dag.predecessors(pred[1]): sorted_pred = [pred[1]] # was [pred[1], pred[0]] elif pred[1] in dag.predecessors(pred[0]): sorted_pred = [pred[0]] # was [pred[0], pred[1]] else: # We need to avoid accidentally adding a cx on these_qubits # since these must have a dependency through the other predecessor # in this case if pred[0].name == "cx" and sorted(pred[0].qargs) == these_qubits: sorted_pred = [pred[1]] elif pred[1].name == "cx" and sorted(pred[1].qargs) == these_qubits: sorted_pred = [pred[0]] else: sorted_pred = pred if len(sorted_pred) == 2 and sorted_pred[0].name == "cx" and \ sorted_pred[1].name == "cx": break # stop immediately if we hit a pair of cx # Examine each predecessor for pnd in sorted_pred: if pnd.name not in good_names: continue # If a predecessor is a single qubit gate, add it if pnd.name != "cx": if not nodes_seen[pnd]: group.append(pnd) nodes_seen[pnd] = True pred_next.extend(dag.predecessors(pnd)) # If cx, check qubits else: pred_qubits = sorted(pnd.qargs) if pred_qubits == these_qubits: # add if on same qubits if not nodes_seen[pnd]: group.append(pnd) nodes_seen[pnd] = True pred_next.extend(dag.predecessors(pnd)) else: # remove qubit from consideration if not these_qubits = list(set(these_qubits) - set(pred_qubits)) # Update predecessors # Stop if there aren't any more pred = list(set(pred_next)) if not pred: explore = False # Reverse the predecessor list and append the "cx" node group.reverse() group.append(nd) nodes_seen[nd] = True # Reset these_qubits these_qubits = sorted(nd.qargs) # Explore successors of the "cx" node succ = list(dag.successors(nd)) explore = True while explore: succ_next = [] # If there is one successor, add it if its on the right qubits if len(succ) == 1 and not nodes_seen[succ[0]]: snd = succ[0] if snd.name in good_names: if (snd.name == "cx" and sorted(snd.qargs) == these_qubits) or \ snd.name != "cx": group.append(snd) nodes_seen[snd] = True succ_next.extend(dag.successors(snd)) # If there are two, then we consider cases elif len(succ) == 2: # First, check if there is a relationship if succ[0] in dag.successors(succ[1]): sorted_succ = [succ[1]] # was [succ[1], succ[0]] elif succ[1] in dag.successors(succ[0]): sorted_succ = [succ[0]] # was [succ[0], succ[1]] else: # We need to avoid accidentally adding a cx on these_qubits # since these must have a dependency through the other successor # in this case if succ[0].name == "cx" and sorted(succ[0].qargs) == these_qubits: sorted_succ = [succ[1]] elif succ[1].name == "cx" and sorted(succ[1].qargs) == these_qubits: sorted_succ = [succ[0]] else: sorted_succ = succ if len(sorted_succ) == 2 and \ sorted_succ[0].name == "cx" and \ sorted_succ[1].name == "cx": break # stop immediately if we hit a pair of cx # Examine each successor for snd in sorted_succ: if snd.name not in good_names: continue # If a successor is a single qubit gate, add it if snd.name != "cx": if not nodes_seen[snd]: group.append(snd) nodes_seen[snd] = True succ_next.extend(dag.successors(snd)) else: # If cx, check qubits succ_qubits = sorted(snd.qargs) if succ_qubits == these_qubits: # add if on same qubits if not nodes_seen[snd]: group.append(snd) nodes_seen[snd] = True succ_next.extend(dag.successors(snd)) else: # remove qubit from consideration if not these_qubits = list(set(these_qubits) - set(succ_qubits)) # Update successors # Stop if there aren't any more succ = list(set(succ_next)) if not succ: explore = False block_list.append(tuple(group)) self.property_set['block_list'] = block_list return dag
[ "collect", "blocks", "of", "adjacent", "gates", "acting", "on", "a", "pair", "of", "cx", "qubits", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/collect_2q_blocks.py#L30-L189
[ "def", "run", "(", "self", ",", "dag", ")", ":", "# Initiate the commutation set", "self", ".", "property_set", "[", "'commutation_set'", "]", "=", "defaultdict", "(", "list", ")", "good_names", "=", "[", "\"cx\"", ",", "\"u1\"", ",", "\"u2\"", ",", "\"u3\"", ",", "\"id\"", "]", "block_list", "=", "[", "]", "nodes", "=", "list", "(", "dag", ".", "topological_nodes", "(", ")", ")", "nodes_seen", "=", "dict", "(", "zip", "(", "nodes", ",", "[", "False", "]", "*", "len", "(", "nodes", ")", ")", ")", "for", "nd", "in", "dag", ".", "topological_op_nodes", "(", ")", ":", "group", "=", "[", "]", "# Explore predecessors and successors of cx gates", "if", "nd", ".", "name", "==", "\"cx\"", "and", "nd", ".", "condition", "is", "None", "and", "not", "nodes_seen", "[", "nd", "]", ":", "these_qubits", "=", "sorted", "(", "nd", ".", "qargs", ")", "# Explore predecessors of the \"cx\" node", "pred", "=", "list", "(", "dag", ".", "predecessors", "(", "nd", ")", ")", "explore", "=", "True", "while", "explore", ":", "pred_next", "=", "[", "]", "# If there is one predecessor, add it if it's on the right qubits", "if", "len", "(", "pred", ")", "==", "1", "and", "not", "nodes_seen", "[", "pred", "[", "0", "]", "]", ":", "pnd", "=", "pred", "[", "0", "]", "if", "pnd", ".", "name", "in", "good_names", ":", "if", "(", "pnd", ".", "name", "==", "\"cx\"", "and", "sorted", "(", "pnd", ".", "qargs", ")", "==", "these_qubits", ")", "or", "pnd", ".", "name", "!=", "\"cx\"", ":", "group", ".", "append", "(", "pnd", ")", "nodes_seen", "[", "pnd", "]", "=", "True", "pred_next", ".", "extend", "(", "dag", ".", "predecessors", "(", "pnd", ")", ")", "# If there are two, then we consider cases", "elif", "len", "(", "pred", ")", "==", "2", ":", "# First, check if there is a relationship", "if", "pred", "[", "0", "]", "in", "dag", ".", "predecessors", "(", "pred", "[", "1", "]", ")", ":", "sorted_pred", "=", "[", "pred", "[", "1", "]", "]", "# was [pred[1], pred[0]]", "elif", "pred", "[", "1", "]", "in", "dag", ".", "predecessors", "(", "pred", "[", "0", "]", ")", ":", "sorted_pred", "=", "[", "pred", "[", "0", "]", "]", "# was [pred[0], pred[1]]", "else", ":", "# We need to avoid accidentally adding a cx on these_qubits", "# since these must have a dependency through the other predecessor", "# in this case", "if", "pred", "[", "0", "]", ".", "name", "==", "\"cx\"", "and", "sorted", "(", "pred", "[", "0", "]", ".", "qargs", ")", "==", "these_qubits", ":", "sorted_pred", "=", "[", "pred", "[", "1", "]", "]", "elif", "pred", "[", "1", "]", ".", "name", "==", "\"cx\"", "and", "sorted", "(", "pred", "[", "1", "]", ".", "qargs", ")", "==", "these_qubits", ":", "sorted_pred", "=", "[", "pred", "[", "0", "]", "]", "else", ":", "sorted_pred", "=", "pred", "if", "len", "(", "sorted_pred", ")", "==", "2", "and", "sorted_pred", "[", "0", "]", ".", "name", "==", "\"cx\"", "and", "sorted_pred", "[", "1", "]", ".", "name", "==", "\"cx\"", ":", "break", "# stop immediately if we hit a pair of cx", "# Examine each predecessor", "for", "pnd", "in", "sorted_pred", ":", "if", "pnd", ".", "name", "not", "in", "good_names", ":", "continue", "# If a predecessor is a single qubit gate, add it", "if", "pnd", ".", "name", "!=", "\"cx\"", ":", "if", "not", "nodes_seen", "[", "pnd", "]", ":", "group", ".", "append", "(", "pnd", ")", "nodes_seen", "[", "pnd", "]", "=", "True", "pred_next", ".", "extend", "(", "dag", ".", "predecessors", "(", "pnd", ")", ")", "# If cx, check qubits", "else", ":", "pred_qubits", "=", "sorted", "(", "pnd", ".", "qargs", ")", "if", "pred_qubits", "==", "these_qubits", ":", "# add if on same qubits", "if", "not", "nodes_seen", "[", "pnd", "]", ":", "group", ".", "append", "(", "pnd", ")", "nodes_seen", "[", "pnd", "]", "=", "True", "pred_next", ".", "extend", "(", "dag", ".", "predecessors", "(", "pnd", ")", ")", "else", ":", "# remove qubit from consideration if not", "these_qubits", "=", "list", "(", "set", "(", "these_qubits", ")", "-", "set", "(", "pred_qubits", ")", ")", "# Update predecessors", "# Stop if there aren't any more", "pred", "=", "list", "(", "set", "(", "pred_next", ")", ")", "if", "not", "pred", ":", "explore", "=", "False", "# Reverse the predecessor list and append the \"cx\" node", "group", ".", "reverse", "(", ")", "group", ".", "append", "(", "nd", ")", "nodes_seen", "[", "nd", "]", "=", "True", "# Reset these_qubits", "these_qubits", "=", "sorted", "(", "nd", ".", "qargs", ")", "# Explore successors of the \"cx\" node", "succ", "=", "list", "(", "dag", ".", "successors", "(", "nd", ")", ")", "explore", "=", "True", "while", "explore", ":", "succ_next", "=", "[", "]", "# If there is one successor, add it if its on the right qubits", "if", "len", "(", "succ", ")", "==", "1", "and", "not", "nodes_seen", "[", "succ", "[", "0", "]", "]", ":", "snd", "=", "succ", "[", "0", "]", "if", "snd", ".", "name", "in", "good_names", ":", "if", "(", "snd", ".", "name", "==", "\"cx\"", "and", "sorted", "(", "snd", ".", "qargs", ")", "==", "these_qubits", ")", "or", "snd", ".", "name", "!=", "\"cx\"", ":", "group", ".", "append", "(", "snd", ")", "nodes_seen", "[", "snd", "]", "=", "True", "succ_next", ".", "extend", "(", "dag", ".", "successors", "(", "snd", ")", ")", "# If there are two, then we consider cases", "elif", "len", "(", "succ", ")", "==", "2", ":", "# First, check if there is a relationship", "if", "succ", "[", "0", "]", "in", "dag", ".", "successors", "(", "succ", "[", "1", "]", ")", ":", "sorted_succ", "=", "[", "succ", "[", "1", "]", "]", "# was [succ[1], succ[0]]", "elif", "succ", "[", "1", "]", "in", "dag", ".", "successors", "(", "succ", "[", "0", "]", ")", ":", "sorted_succ", "=", "[", "succ", "[", "0", "]", "]", "# was [succ[0], succ[1]]", "else", ":", "# We need to avoid accidentally adding a cx on these_qubits", "# since these must have a dependency through the other successor", "# in this case", "if", "succ", "[", "0", "]", ".", "name", "==", "\"cx\"", "and", "sorted", "(", "succ", "[", "0", "]", ".", "qargs", ")", "==", "these_qubits", ":", "sorted_succ", "=", "[", "succ", "[", "1", "]", "]", "elif", "succ", "[", "1", "]", ".", "name", "==", "\"cx\"", "and", "sorted", "(", "succ", "[", "1", "]", ".", "qargs", ")", "==", "these_qubits", ":", "sorted_succ", "=", "[", "succ", "[", "0", "]", "]", "else", ":", "sorted_succ", "=", "succ", "if", "len", "(", "sorted_succ", ")", "==", "2", "and", "sorted_succ", "[", "0", "]", ".", "name", "==", "\"cx\"", "and", "sorted_succ", "[", "1", "]", ".", "name", "==", "\"cx\"", ":", "break", "# stop immediately if we hit a pair of cx", "# Examine each successor", "for", "snd", "in", "sorted_succ", ":", "if", "snd", ".", "name", "not", "in", "good_names", ":", "continue", "# If a successor is a single qubit gate, add it", "if", "snd", ".", "name", "!=", "\"cx\"", ":", "if", "not", "nodes_seen", "[", "snd", "]", ":", "group", ".", "append", "(", "snd", ")", "nodes_seen", "[", "snd", "]", "=", "True", "succ_next", ".", "extend", "(", "dag", ".", "successors", "(", "snd", ")", ")", "else", ":", "# If cx, check qubits", "succ_qubits", "=", "sorted", "(", "snd", ".", "qargs", ")", "if", "succ_qubits", "==", "these_qubits", ":", "# add if on same qubits", "if", "not", "nodes_seen", "[", "snd", "]", ":", "group", ".", "append", "(", "snd", ")", "nodes_seen", "[", "snd", "]", "=", "True", "succ_next", ".", "extend", "(", "dag", ".", "successors", "(", "snd", ")", ")", "else", ":", "# remove qubit from consideration if not", "these_qubits", "=", "list", "(", "set", "(", "these_qubits", ")", "-", "set", "(", "succ_qubits", ")", ")", "# Update successors", "# Stop if there aren't any more", "succ", "=", "list", "(", "set", "(", "succ_next", ")", ")", "if", "not", "succ", ":", "explore", "=", "False", "block_list", ".", "append", "(", "tuple", "(", "group", ")", ")", "self", ".", "property_set", "[", "'block_list'", "]", "=", "block_list", "return", "dag" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
u2
Apply u2 to q.
qiskit/extensions/standard/u2.py
def u2(self, phi, lam, q): """Apply u2 to q.""" return self.append(U2Gate(phi, lam), [q], [])
def u2(self, phi, lam, q): """Apply u2 to q.""" return self.append(U2Gate(phi, lam), [q], [])
[ "Apply", "u2", "to", "q", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/standard/u2.py#L59-L61
[ "def", "u2", "(", "self", ",", "phi", ",", "lam", ",", "q", ")", ":", "return", "self", ".", "append", "(", "U2Gate", "(", "phi", ",", "lam", ")", ",", "[", "q", "]", ",", "[", "]", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
U2Gate.to_matrix
Return a Numpy.array for the U3 gate.
qiskit/extensions/standard/u2.py
def to_matrix(self): """Return a Numpy.array for the U3 gate.""" isqrt2 = 1 / numpy.sqrt(2) phi, lam = self.params phi, lam = float(phi), float(lam) return numpy.array([[isqrt2, -numpy.exp(1j * lam) * isqrt2], [ numpy.exp(1j * phi) * isqrt2, numpy.exp(1j * (phi + lam)) * isqrt2 ]], dtype=complex)
def to_matrix(self): """Return a Numpy.array for the U3 gate.""" isqrt2 = 1 / numpy.sqrt(2) phi, lam = self.params phi, lam = float(phi), float(lam) return numpy.array([[isqrt2, -numpy.exp(1j * lam) * isqrt2], [ numpy.exp(1j * phi) * isqrt2, numpy.exp(1j * (phi + lam)) * isqrt2 ]], dtype=complex)
[ "Return", "a", "Numpy", ".", "array", "for", "the", "U3", "gate", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/standard/u2.py#L44-L54
[ "def", "to_matrix", "(", "self", ")", ":", "isqrt2", "=", "1", "/", "numpy", ".", "sqrt", "(", "2", ")", "phi", ",", "lam", "=", "self", ".", "params", "phi", ",", "lam", "=", "float", "(", "phi", ")", ",", "float", "(", "lam", ")", "return", "numpy", ".", "array", "(", "[", "[", "isqrt2", ",", "-", "numpy", ".", "exp", "(", "1j", "*", "lam", ")", "*", "isqrt2", "]", ",", "[", "numpy", ".", "exp", "(", "1j", "*", "phi", ")", "*", "isqrt2", ",", "numpy", ".", "exp", "(", "1j", "*", "(", "phi", "+", "lam", ")", ")", "*", "isqrt2", "]", "]", ",", "dtype", "=", "complex", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Instruction.insert
Return a new schedule with `schedule` inserted within `self` at `start_time`. Args: start_time: time to be inserted schedule: schedule to be inserted
qiskit/pulse/commands/instruction.py
def insert(self, start_time: int, schedule: ScheduleComponent) -> 'ScheduleComponent': """Return a new schedule with `schedule` inserted within `self` at `start_time`. Args: start_time: time to be inserted schedule: schedule to be inserted """ return ops.insert(self, start_time, schedule)
def insert(self, start_time: int, schedule: ScheduleComponent) -> 'ScheduleComponent': """Return a new schedule with `schedule` inserted within `self` at `start_time`. Args: start_time: time to be inserted schedule: schedule to be inserted """ return ops.insert(self, start_time, schedule)
[ "Return", "a", "new", "schedule", "with", "schedule", "inserted", "within", "self", "at", "start_time", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/commands/instruction.py#L154-L161
[ "def", "insert", "(", "self", ",", "start_time", ":", "int", ",", "schedule", ":", "ScheduleComponent", ")", "->", "'ScheduleComponent'", ":", "return", "ops", ".", "insert", "(", "self", ",", "start_time", ",", "schedule", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
FencedObject._check_if_fenced
Checks if the attribute name is in the list of attributes to protect. If so, raises TranspilerAccessError. Args: name (string): the attribute name to check Raises: TranspilerAccessError: when name is the list of attributes to protect.
qiskit/transpiler/fencedobjs.py
def _check_if_fenced(self, name): """ Checks if the attribute name is in the list of attributes to protect. If so, raises TranspilerAccessError. Args: name (string): the attribute name to check Raises: TranspilerAccessError: when name is the list of attributes to protect. """ if name in object.__getattribute__(self, '_attributes_to_fence'): raise TranspilerAccessError("The fenced %s has the property %s protected" % (type(object.__getattribute__(self, '_wrapped')), name))
def _check_if_fenced(self, name): """ Checks if the attribute name is in the list of attributes to protect. If so, raises TranspilerAccessError. Args: name (string): the attribute name to check Raises: TranspilerAccessError: when name is the list of attributes to protect. """ if name in object.__getattribute__(self, '_attributes_to_fence'): raise TranspilerAccessError("The fenced %s has the property %s protected" % (type(object.__getattribute__(self, '_wrapped')), name))
[ "Checks", "if", "the", "attribute", "name", "is", "in", "the", "list", "of", "attributes", "to", "protect", ".", "If", "so", "raises", "TranspilerAccessError", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/fencedobjs.py#L33-L46
[ "def", "_check_if_fenced", "(", "self", ",", "name", ")", ":", "if", "name", "in", "object", ".", "__getattribute__", "(", "self", ",", "'_attributes_to_fence'", ")", ":", "raise", "TranspilerAccessError", "(", "\"The fenced %s has the property %s protected\"", "%", "(", "type", "(", "object", ".", "__getattribute__", "(", "self", ",", "'_wrapped'", ")", ")", ",", "name", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Stinespring.is_cptp
Return True if completely-positive trace-preserving.
qiskit/quantum_info/operators/channel/stinespring.py
def is_cptp(self, atol=None, rtol=None): """Return True if completely-positive trace-preserving.""" if atol is None: atol = self._atol if rtol is None: rtol = self._rtol if self._data[1] is not None: return False check = np.dot(np.transpose(np.conj(self._data[0])), self._data[0]) return is_identity_matrix(check, rtol=self._rtol, atol=self._atol)
def is_cptp(self, atol=None, rtol=None): """Return True if completely-positive trace-preserving.""" if atol is None: atol = self._atol if rtol is None: rtol = self._rtol if self._data[1] is not None: return False check = np.dot(np.transpose(np.conj(self._data[0])), self._data[0]) return is_identity_matrix(check, rtol=self._rtol, atol=self._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/stinespring.py#L143-L152
[ "def", "is_cptp", "(", "self", ",", "atol", "=", "None", ",", "rtol", "=", "None", ")", ":", "if", "atol", "is", "None", ":", "atol", "=", "self", ".", "_atol", "if", "rtol", "is", "None", ":", "rtol", "=", "self", ".", "_rtol", "if", "self", ".", "_data", "[", "1", "]", "is", "not", "None", ":", "return", "False", "check", "=", "np", ".", "dot", "(", "np", ".", "transpose", "(", "np", ".", "conj", "(", "self", ".", "_data", "[", "0", "]", ")", ")", ",", "self", ".", "_data", "[", "0", "]", ")", "return", "is_identity_matrix", "(", "check", ",", "rtol", "=", "self", ".", "_rtol", ",", "atol", "=", "self", ".", "_atol", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Stinespring.conjugate
Return the conjugate of the QuantumChannel.
qiskit/quantum_info/operators/channel/stinespring.py
def conjugate(self): """Return the conjugate of the QuantumChannel.""" # pylint: disable=assignment-from-no-return stine_l = np.conjugate(self._data[0]) stine_r = None if self._data[1] is not None: stine_r = np.conjugate(self._data[1]) return Stinespring((stine_l, stine_r), self.input_dims(), self.output_dims())
def conjugate(self): """Return the conjugate of the QuantumChannel.""" # pylint: disable=assignment-from-no-return stine_l = np.conjugate(self._data[0]) stine_r = None if self._data[1] is not None: stine_r = np.conjugate(self._data[1]) return Stinespring((stine_l, stine_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/stinespring.py#L154-L162
[ "def", "conjugate", "(", "self", ")", ":", "# pylint: disable=assignment-from-no-return", "stine_l", "=", "np", ".", "conjugate", "(", "self", ".", "_data", "[", "0", "]", ")", "stine_r", "=", "None", "if", "self", ".", "_data", "[", "1", "]", "is", "not", "None", ":", "stine_r", "=", "np", ".", "conjugate", "(", "self", ".", "_data", "[", "1", "]", ")", "return", "Stinespring", "(", "(", "stine_l", ",", "stine_r", ")", ",", "self", ".", "input_dims", "(", ")", ",", "self", ".", "output_dims", "(", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Stinespring.transpose
Return the transpose of the QuantumChannel.
qiskit/quantum_info/operators/channel/stinespring.py
def transpose(self): """Return the transpose of the QuantumChannel.""" din, dout = self.dim dtr = self._data[0].shape[0] // dout stine = [None, None] for i, mat in enumerate(self._data): if mat is not None: stine[i] = np.reshape( np.transpose(np.reshape(mat, (dout, dtr, din)), (2, 1, 0)), (din * dtr, dout)) return Stinespring( tuple(stine), input_dims=self.output_dims(), output_dims=self.input_dims())
def transpose(self): """Return the transpose of the QuantumChannel.""" din, dout = self.dim dtr = self._data[0].shape[0] // dout stine = [None, None] for i, mat in enumerate(self._data): if mat is not None: stine[i] = np.reshape( np.transpose(np.reshape(mat, (dout, dtr, din)), (2, 1, 0)), (din * dtr, dout)) return Stinespring( tuple(stine), 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/stinespring.py#L164-L177
[ "def", "transpose", "(", "self", ")", ":", "din", ",", "dout", "=", "self", ".", "dim", "dtr", "=", "self", ".", "_data", "[", "0", "]", ".", "shape", "[", "0", "]", "//", "dout", "stine", "=", "[", "None", ",", "None", "]", "for", "i", ",", "mat", "in", "enumerate", "(", "self", ".", "_data", ")", ":", "if", "mat", "is", "not", "None", ":", "stine", "[", "i", "]", "=", "np", ".", "reshape", "(", "np", ".", "transpose", "(", "np", ".", "reshape", "(", "mat", ",", "(", "dout", ",", "dtr", ",", "din", ")", ")", ",", "(", "2", ",", "1", ",", "0", ")", ")", ",", "(", "din", "*", "dtr", ",", "dout", ")", ")", "return", "Stinespring", "(", "tuple", "(", "stine", ")", ",", "input_dims", "=", "self", ".", "output_dims", "(", ")", ",", "output_dims", "=", "self", ".", "input_dims", "(", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Stinespring.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: Stinespring: The composition channel as a Stinespring object. Raises: QiskitError: if other cannot be converted to a channel or has incompatible dimensions.
qiskit/quantum_info/operators/channel/stinespring.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: Stinespring: The composition channel as a Stinespring object. Raises: QiskitError: if other cannot be converted to a channel or has incompatible dimensions. """ if qargs is not None: return Stinespring( SuperOp(self).compose(other, qargs=qargs, front=front)) # Convert other to Kraus 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') # Since we cannot directly compose two channels in Stinespring # representation we convert to the Kraus representation return Stinespring(Kraus(self).compose(other, front=front))
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: Stinespring: The composition channel as a Stinespring object. Raises: QiskitError: if other cannot be converted to a channel or has incompatible dimensions. """ if qargs is not None: return Stinespring( SuperOp(self).compose(other, qargs=qargs, front=front)) # Convert other to Kraus 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') # Since we cannot directly compose two channels in Stinespring # representation we convert to the Kraus representation return Stinespring(Kraus(self).compose(other, front=front))
[ "Return", "the", "composition", "channel", "self∘other", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/stinespring.py#L179-L212
[ "def", "compose", "(", "self", ",", "other", ",", "qargs", "=", "None", ",", "front", "=", "False", ")", ":", "if", "qargs", "is", "not", "None", ":", "return", "Stinespring", "(", "SuperOp", "(", "self", ")", ".", "compose", "(", "other", ",", "qargs", "=", "qargs", ",", "front", "=", "front", ")", ")", "# Convert other to Kraus", "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'", ")", "# Since we cannot directly compose two channels in Stinespring", "# representation we convert to the Kraus representation", "return", "Stinespring", "(", "Kraus", "(", "self", ")", ".", "compose", "(", "other", ",", "front", "=", "front", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Stinespring.power
The matrix power of the channel. Args: n (int): compute the matrix power of the superoperator matrix. Returns: Stinespring: the matrix power of the SuperOp converted to a Stinespring 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/stinespring.py
def power(self, n): """The matrix power of the channel. Args: n (int): compute the matrix power of the superoperator matrix. Returns: Stinespring: the matrix power of the SuperOp converted to a Stinespring 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 Stinespring(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: Stinespring: the matrix power of the SuperOp converted to a Stinespring 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 Stinespring(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/stinespring.py#L214-L230
[ "def", "power", "(", "self", ",", "n", ")", ":", "if", "n", ">", "0", ":", "return", "super", "(", ")", ".", "power", "(", "n", ")", "return", "Stinespring", "(", "SuperOp", "(", "self", ")", ".", "power", "(", "n", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Stinespring.multiply
Return the QuantumChannel self + other. Args: other (complex): a complex number. Returns: Stinespring: the scalar multiplication other * self as a Stinespring object. Raises: QiskitError: if other is not a valid scalar.
qiskit/quantum_info/operators/channel/stinespring.py
def multiply(self, other): """Return the QuantumChannel self + other. Args: other (complex): a complex number. Returns: Stinespring: the scalar multiplication other * self as a Stinespring 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 or negative we need to convert to # general Stinespring representation so we first convert to # the Choi representation if isinstance(other, complex) or other < 1: # Convert to Choi-matrix return Stinespring(Choi(self).multiply(other)) # If the number is real we can update the Kraus operators # directly num = np.sqrt(other) stine_l, stine_r = self._data stine_l = num * self._data[0] stine_r = None if self._data[1] is not None: stine_r = num * self._data[1] return Stinespring((stine_l, stine_r), self.input_dims(), self.output_dims())
def multiply(self, other): """Return the QuantumChannel self + other. Args: other (complex): a complex number. Returns: Stinespring: the scalar multiplication other * self as a Stinespring 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 or negative we need to convert to # general Stinespring representation so we first convert to # the Choi representation if isinstance(other, complex) or other < 1: # Convert to Choi-matrix return Stinespring(Choi(self).multiply(other)) # If the number is real we can update the Kraus operators # directly num = np.sqrt(other) stine_l, stine_r = self._data stine_l = num * self._data[0] stine_r = None if self._data[1] is not None: stine_r = num * self._data[1] return Stinespring((stine_l, stine_r), self.input_dims(), self.output_dims())
[ "Return", "the", "QuantumChannel", "self", "+", "other", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/stinespring.py#L298-L328
[ "def", "multiply", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "Number", ")", ":", "raise", "QiskitError", "(", "\"other is not a number\"", ")", "# If the number is complex or negative we need to convert to", "# general Stinespring representation so we first convert to", "# the Choi representation", "if", "isinstance", "(", "other", ",", "complex", ")", "or", "other", "<", "1", ":", "# Convert to Choi-matrix", "return", "Stinespring", "(", "Choi", "(", "self", ")", ".", "multiply", "(", "other", ")", ")", "# If the number is real we can update the Kraus operators", "# directly", "num", "=", "np", ".", "sqrt", "(", "other", ")", "stine_l", ",", "stine_r", "=", "self", ".", "_data", "stine_l", "=", "num", "*", "self", ".", "_data", "[", "0", "]", "stine_r", "=", "None", "if", "self", ".", "_data", "[", "1", "]", "is", "not", "None", ":", "stine_r", "=", "num", "*", "self", ".", "_data", "[", "1", "]", "return", "Stinespring", "(", "(", "stine_l", ",", "stine_r", ")", ",", "self", ".", "input_dims", "(", ")", ",", "self", ".", "output_dims", "(", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Stinespring._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/stinespring.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 \ self._data[0].shape[0] // self._output_dim == 1: # If the shape of the stinespring operator is equal to the output_dim # evolution of a state vector psi -> stine.psi return np.dot(self._data[0], state) # Otherwise we always return a density matrix state = self._format_state(state, density_matrix=True) stine_l, stine_r = self._data if stine_r is None: stine_r = stine_l din, dout = self.dim dtr = stine_l.shape[0] // dout shape = (dout, dtr, din) return np.einsum('iAB,BC,jAC->ij', np.reshape(stine_l, shape), state, np.reshape(np.conjugate(stine_r), shape))
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 \ self._data[0].shape[0] // self._output_dim == 1: # If the shape of the stinespring operator is equal to the output_dim # evolution of a state vector psi -> stine.psi return np.dot(self._data[0], state) # Otherwise we always return a density matrix state = self._format_state(state, density_matrix=True) stine_l, stine_r = self._data if stine_r is None: stine_r = stine_l din, dout = self.dim dtr = stine_l.shape[0] // dout shape = (dout, dtr, din) return np.einsum('iAB,BC,jAC->ij', np.reshape(stine_l, shape), state, np.reshape(np.conjugate(stine_r), shape))
[ "Evolve", "a", "quantum", "state", "by", "the", "QuantumChannel", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/stinespring.py#L330-L369
[ "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", "self", ".", "_data", "[", "0", "]", ".", "shape", "[", "0", "]", "//", "self", ".", "_output_dim", "==", "1", ":", "# If the shape of the stinespring operator is equal to the output_dim", "# evolution of a state vector psi -> stine.psi", "return", "np", ".", "dot", "(", "self", ".", "_data", "[", "0", "]", ",", "state", ")", "# Otherwise we always return a density matrix", "state", "=", "self", ".", "_format_state", "(", "state", ",", "density_matrix", "=", "True", ")", "stine_l", ",", "stine_r", "=", "self", ".", "_data", "if", "stine_r", "is", "None", ":", "stine_r", "=", "stine_l", "din", ",", "dout", "=", "self", ".", "dim", "dtr", "=", "stine_l", ".", "shape", "[", "0", "]", "//", "dout", "shape", "=", "(", "dout", ",", "dtr", ",", "din", ")", "return", "np", ".", "einsum", "(", "'iAB,BC,jAC->ij'", ",", "np", ".", "reshape", "(", "stine_l", ",", "shape", ")", ",", "state", ",", "np", ".", "reshape", "(", "np", ".", "conjugate", "(", "stine_r", ")", ",", "shape", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Stinespring._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: Stinespring: the tensor product channel as a Stinespring object. Raises: QiskitError: if other cannot be converted to a channel.
qiskit/quantum_info/operators/channel/stinespring.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: Stinespring: the tensor product channel as a Stinespring object. Raises: QiskitError: if other cannot be converted to a channel. """ # Convert other to Stinespring if not isinstance(other, Stinespring): other = Stinespring(other) # Tensor stinespring ops sa_l, sa_r = self._data sb_l, sb_r = other._data # Reshuffle tensor dimensions din_a, dout_a = self.dim din_b, dout_b = other.dim dtr_a = sa_l.shape[0] // dout_a dtr_b = sb_l.shape[0] // dout_b if reverse: shape_in = (dout_b, dtr_b, dout_a, dtr_a, din_b * din_a) shape_out = (dout_b * dtr_b * dout_a * dtr_a, din_b * din_a) else: shape_in = (dout_a, dtr_a, dout_b, dtr_b, din_a * din_b) shape_out = (dout_a * dtr_a * dout_b * dtr_b, din_a * din_b) # Compute left stinepsring op if reverse: input_dims = self.input_dims() + other.input_dims() output_dims = self.output_dims() + other.output_dims() sab_l = np.kron(sb_l, sa_l) else: input_dims = other.input_dims() + self.input_dims() output_dims = other.output_dims() + self.output_dims() sab_l = np.kron(sa_l, sb_l) # Reravel indicies sab_l = np.reshape( np.transpose(np.reshape(sab_l, shape_in), (0, 2, 1, 3, 4)), shape_out) # Compute right stinespring op if sa_r is None and sb_r is None: sab_r = None else: if sa_r is None: sa_r = sa_l elif sb_r is None: sb_r = sb_l if reverse: sab_r = np.kron(sb_r, sa_r) else: sab_r = np.kron(sa_r, sb_r) # Reravel indicies sab_r = np.reshape( np.transpose(np.reshape(sab_r, shape_in), (0, 2, 1, 3, 4)), shape_out) return Stinespring((sab_l, sab_r), 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: Stinespring: the tensor product channel as a Stinespring object. Raises: QiskitError: if other cannot be converted to a channel. """ # Convert other to Stinespring if not isinstance(other, Stinespring): other = Stinespring(other) # Tensor stinespring ops sa_l, sa_r = self._data sb_l, sb_r = other._data # Reshuffle tensor dimensions din_a, dout_a = self.dim din_b, dout_b = other.dim dtr_a = sa_l.shape[0] // dout_a dtr_b = sb_l.shape[0] // dout_b if reverse: shape_in = (dout_b, dtr_b, dout_a, dtr_a, din_b * din_a) shape_out = (dout_b * dtr_b * dout_a * dtr_a, din_b * din_a) else: shape_in = (dout_a, dtr_a, dout_b, dtr_b, din_a * din_b) shape_out = (dout_a * dtr_a * dout_b * dtr_b, din_a * din_b) # Compute left stinepsring op if reverse: input_dims = self.input_dims() + other.input_dims() output_dims = self.output_dims() + other.output_dims() sab_l = np.kron(sb_l, sa_l) else: input_dims = other.input_dims() + self.input_dims() output_dims = other.output_dims() + self.output_dims() sab_l = np.kron(sa_l, sb_l) # Reravel indicies sab_l = np.reshape( np.transpose(np.reshape(sab_l, shape_in), (0, 2, 1, 3, 4)), shape_out) # Compute right stinespring op if sa_r is None and sb_r is None: sab_r = None else: if sa_r is None: sa_r = sa_l elif sb_r is None: sb_r = sb_l if reverse: sab_r = np.kron(sb_r, sa_r) else: sab_r = np.kron(sa_r, sb_r) # Reravel indicies sab_r = np.reshape( np.transpose(np.reshape(sab_r, shape_in), (0, 2, 1, 3, 4)), shape_out) return Stinespring((sab_l, sab_r), 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/stinespring.py#L371-L434
[ "def", "_tensor_product", "(", "self", ",", "other", ",", "reverse", "=", "False", ")", ":", "# Convert other to Stinespring", "if", "not", "isinstance", "(", "other", ",", "Stinespring", ")", ":", "other", "=", "Stinespring", "(", "other", ")", "# Tensor stinespring ops", "sa_l", ",", "sa_r", "=", "self", ".", "_data", "sb_l", ",", "sb_r", "=", "other", ".", "_data", "# Reshuffle tensor dimensions", "din_a", ",", "dout_a", "=", "self", ".", "dim", "din_b", ",", "dout_b", "=", "other", ".", "dim", "dtr_a", "=", "sa_l", ".", "shape", "[", "0", "]", "//", "dout_a", "dtr_b", "=", "sb_l", ".", "shape", "[", "0", "]", "//", "dout_b", "if", "reverse", ":", "shape_in", "=", "(", "dout_b", ",", "dtr_b", ",", "dout_a", ",", "dtr_a", ",", "din_b", "*", "din_a", ")", "shape_out", "=", "(", "dout_b", "*", "dtr_b", "*", "dout_a", "*", "dtr_a", ",", "din_b", "*", "din_a", ")", "else", ":", "shape_in", "=", "(", "dout_a", ",", "dtr_a", ",", "dout_b", ",", "dtr_b", ",", "din_a", "*", "din_b", ")", "shape_out", "=", "(", "dout_a", "*", "dtr_a", "*", "dout_b", "*", "dtr_b", ",", "din_a", "*", "din_b", ")", "# Compute left stinepsring op", "if", "reverse", ":", "input_dims", "=", "self", ".", "input_dims", "(", ")", "+", "other", ".", "input_dims", "(", ")", "output_dims", "=", "self", ".", "output_dims", "(", ")", "+", "other", ".", "output_dims", "(", ")", "sab_l", "=", "np", ".", "kron", "(", "sb_l", ",", "sa_l", ")", "else", ":", "input_dims", "=", "other", ".", "input_dims", "(", ")", "+", "self", ".", "input_dims", "(", ")", "output_dims", "=", "other", ".", "output_dims", "(", ")", "+", "self", ".", "output_dims", "(", ")", "sab_l", "=", "np", ".", "kron", "(", "sa_l", ",", "sb_l", ")", "# Reravel indicies", "sab_l", "=", "np", ".", "reshape", "(", "np", ".", "transpose", "(", "np", ".", "reshape", "(", "sab_l", ",", "shape_in", ")", ",", "(", "0", ",", "2", ",", "1", ",", "3", ",", "4", ")", ")", ",", "shape_out", ")", "# Compute right stinespring op", "if", "sa_r", "is", "None", "and", "sb_r", "is", "None", ":", "sab_r", "=", "None", "else", ":", "if", "sa_r", "is", "None", ":", "sa_r", "=", "sa_l", "elif", "sb_r", "is", "None", ":", "sb_r", "=", "sb_l", "if", "reverse", ":", "sab_r", "=", "np", ".", "kron", "(", "sb_r", ",", "sa_r", ")", "else", ":", "sab_r", "=", "np", ".", "kron", "(", "sa_r", ",", "sb_r", ")", "# Reravel indicies", "sab_r", "=", "np", ".", "reshape", "(", "np", ".", "transpose", "(", "np", ".", "reshape", "(", "sab_r", ",", "shape_in", ")", ",", "(", "0", ",", "2", ",", "1", ",", "3", ",", "4", ")", ")", ",", "shape_out", ")", "return", "Stinespring", "(", "(", "sab_l", ",", "sab_r", ")", ",", "input_dims", ",", "output_dims", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BasicSwap.run
Runs the BasicSwap pass on `dag`. Args: dag (DAGCircuit): DAG to map. Returns: DAGCircuit: A mapped DAG. Raises: TranspilerError: if the coupling map or the layout are not compatible with the DAG
qiskit/transpiler/passes/mapping/basic_swap.py
def run(self, dag): """ Runs the BasicSwap pass on `dag`. Args: dag (DAGCircuit): DAG to map. Returns: DAGCircuit: A mapped DAG. Raises: TranspilerError: if the coupling map or the layout are not compatible with the DAG """ new_dag = DAGCircuit() if self.initial_layout is None: if self.property_set["layout"]: self.initial_layout = self.property_set["layout"] else: self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values()) if len(dag.qubits()) != len(self.initial_layout): raise TranspilerError('The layout does not match the amount of qubits in the DAG') if len(self.coupling_map.physical_qubits) != len(self.initial_layout): raise TranspilerError( "Mappers require to have the layout to be the same size as the coupling map") current_layout = self.initial_layout.copy() for layer in dag.serial_layers(): subdag = layer['graph'] for gate in subdag.twoQ_gates(): physical_q0 = current_layout[gate.qargs[0]] physical_q1 = current_layout[gate.qargs[1]] if self.coupling_map.distance(physical_q0, physical_q1) != 1: # Insert a new layer with the SWAP(s). swap_layer = DAGCircuit() path = self.coupling_map.shortest_undirected_path(physical_q0, physical_q1) for swap in range(len(path) - 2): connected_wire_1 = path[swap] connected_wire_2 = path[swap + 1] qubit_1 = current_layout[connected_wire_1] qubit_2 = current_layout[connected_wire_2] # create qregs for qreg in current_layout.get_registers(): if qreg not in swap_layer.qregs.values(): swap_layer.add_qreg(qreg) # create the swap operation swap_layer.apply_operation_back(SwapGate(), qargs=[qubit_1, qubit_2], cargs=[]) # layer insertion edge_map = current_layout.combine_into_edge_map(self.initial_layout) new_dag.compose_back(swap_layer, edge_map) # update current_layout for swap in range(len(path) - 2): current_layout.swap(path[swap], path[swap + 1]) edge_map = current_layout.combine_into_edge_map(self.initial_layout) new_dag.extend_back(subdag, edge_map) return new_dag
def run(self, dag): """ Runs the BasicSwap pass on `dag`. Args: dag (DAGCircuit): DAG to map. Returns: DAGCircuit: A mapped DAG. Raises: TranspilerError: if the coupling map or the layout are not compatible with the DAG """ new_dag = DAGCircuit() if self.initial_layout is None: if self.property_set["layout"]: self.initial_layout = self.property_set["layout"] else: self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values()) if len(dag.qubits()) != len(self.initial_layout): raise TranspilerError('The layout does not match the amount of qubits in the DAG') if len(self.coupling_map.physical_qubits) != len(self.initial_layout): raise TranspilerError( "Mappers require to have the layout to be the same size as the coupling map") current_layout = self.initial_layout.copy() for layer in dag.serial_layers(): subdag = layer['graph'] for gate in subdag.twoQ_gates(): physical_q0 = current_layout[gate.qargs[0]] physical_q1 = current_layout[gate.qargs[1]] if self.coupling_map.distance(physical_q0, physical_q1) != 1: # Insert a new layer with the SWAP(s). swap_layer = DAGCircuit() path = self.coupling_map.shortest_undirected_path(physical_q0, physical_q1) for swap in range(len(path) - 2): connected_wire_1 = path[swap] connected_wire_2 = path[swap + 1] qubit_1 = current_layout[connected_wire_1] qubit_2 = current_layout[connected_wire_2] # create qregs for qreg in current_layout.get_registers(): if qreg not in swap_layer.qregs.values(): swap_layer.add_qreg(qreg) # create the swap operation swap_layer.apply_operation_back(SwapGate(), qargs=[qubit_1, qubit_2], cargs=[]) # layer insertion edge_map = current_layout.combine_into_edge_map(self.initial_layout) new_dag.compose_back(swap_layer, edge_map) # update current_layout for swap in range(len(path) - 2): current_layout.swap(path[swap], path[swap + 1]) edge_map = current_layout.combine_into_edge_map(self.initial_layout) new_dag.extend_back(subdag, edge_map) return new_dag
[ "Runs", "the", "BasicSwap", "pass", "on", "dag", ".", "Args", ":", "dag", "(", "DAGCircuit", ")", ":", "DAG", "to", "map", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/basic_swap.py#L43-L112
[ "def", "run", "(", "self", ",", "dag", ")", ":", "new_dag", "=", "DAGCircuit", "(", ")", "if", "self", ".", "initial_layout", "is", "None", ":", "if", "self", ".", "property_set", "[", "\"layout\"", "]", ":", "self", ".", "initial_layout", "=", "self", ".", "property_set", "[", "\"layout\"", "]", "else", ":", "self", ".", "initial_layout", "=", "Layout", ".", "generate_trivial_layout", "(", "*", "dag", ".", "qregs", ".", "values", "(", ")", ")", "if", "len", "(", "dag", ".", "qubits", "(", ")", ")", "!=", "len", "(", "self", ".", "initial_layout", ")", ":", "raise", "TranspilerError", "(", "'The layout does not match the amount of qubits in the DAG'", ")", "if", "len", "(", "self", ".", "coupling_map", ".", "physical_qubits", ")", "!=", "len", "(", "self", ".", "initial_layout", ")", ":", "raise", "TranspilerError", "(", "\"Mappers require to have the layout to be the same size as the coupling map\"", ")", "current_layout", "=", "self", ".", "initial_layout", ".", "copy", "(", ")", "for", "layer", "in", "dag", ".", "serial_layers", "(", ")", ":", "subdag", "=", "layer", "[", "'graph'", "]", "for", "gate", "in", "subdag", ".", "twoQ_gates", "(", ")", ":", "physical_q0", "=", "current_layout", "[", "gate", ".", "qargs", "[", "0", "]", "]", "physical_q1", "=", "current_layout", "[", "gate", ".", "qargs", "[", "1", "]", "]", "if", "self", ".", "coupling_map", ".", "distance", "(", "physical_q0", ",", "physical_q1", ")", "!=", "1", ":", "# Insert a new layer with the SWAP(s).", "swap_layer", "=", "DAGCircuit", "(", ")", "path", "=", "self", ".", "coupling_map", ".", "shortest_undirected_path", "(", "physical_q0", ",", "physical_q1", ")", "for", "swap", "in", "range", "(", "len", "(", "path", ")", "-", "2", ")", ":", "connected_wire_1", "=", "path", "[", "swap", "]", "connected_wire_2", "=", "path", "[", "swap", "+", "1", "]", "qubit_1", "=", "current_layout", "[", "connected_wire_1", "]", "qubit_2", "=", "current_layout", "[", "connected_wire_2", "]", "# create qregs", "for", "qreg", "in", "current_layout", ".", "get_registers", "(", ")", ":", "if", "qreg", "not", "in", "swap_layer", ".", "qregs", ".", "values", "(", ")", ":", "swap_layer", ".", "add_qreg", "(", "qreg", ")", "# create the swap operation", "swap_layer", ".", "apply_operation_back", "(", "SwapGate", "(", ")", ",", "qargs", "=", "[", "qubit_1", ",", "qubit_2", "]", ",", "cargs", "=", "[", "]", ")", "# layer insertion", "edge_map", "=", "current_layout", ".", "combine_into_edge_map", "(", "self", ".", "initial_layout", ")", "new_dag", ".", "compose_back", "(", "swap_layer", ",", "edge_map", ")", "# update current_layout", "for", "swap", "in", "range", "(", "len", "(", "path", ")", "-", "2", ")", ":", "current_layout", ".", "swap", "(", "path", "[", "swap", "]", ",", "path", "[", "swap", "+", "1", "]", ")", "edge_map", "=", "current_layout", ".", "combine_into_edge_map", "(", "self", ".", "initial_layout", ")", "new_dag", ".", "extend_back", "(", "subdag", ",", "edge_map", ")", "return", "new_dag" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_layer_permutation
Find a swap circuit that implements a permutation for this layer. Args: layer_partition (list): The layer_partition is a list of (qu)bit lists and each qubit is a tuple (qreg, index). initial_layout (Layout): The initial layout passed. layout (Layout): The layout is a Layout object mapping virtual qubits in the input circuit to physical qubits in the coupling graph. It reflects the current positions of the data. qubit_subset (list): The qubit_subset is the set of qubits in the coupling graph that we have chosen to map into, as tuples (Register, index). coupling (CouplingMap): Directed graph representing a coupling map. This coupling map should be one that was provided to the stochastic mapper. trials (int): Number of attempts the randomized algorithm makes. qregs (OrderedDict): Ordered dict of registers from input DAG. rng (RandomState): Random number generator. Returns: Tuple: success_flag, best_circuit, best_depth, best_layout, trivial_flag Raises: TranspilerError: if anything went wrong.
qiskit/transpiler/passes/mapping/stochastic_swap.py
def _layer_permutation(layer_partition, initial_layout, layout, qubit_subset, coupling, trials, qregs, rng): """Find a swap circuit that implements a permutation for this layer. Args: layer_partition (list): The layer_partition is a list of (qu)bit lists and each qubit is a tuple (qreg, index). initial_layout (Layout): The initial layout passed. layout (Layout): The layout is a Layout object mapping virtual qubits in the input circuit to physical qubits in the coupling graph. It reflects the current positions of the data. qubit_subset (list): The qubit_subset is the set of qubits in the coupling graph that we have chosen to map into, as tuples (Register, index). coupling (CouplingMap): Directed graph representing a coupling map. This coupling map should be one that was provided to the stochastic mapper. trials (int): Number of attempts the randomized algorithm makes. qregs (OrderedDict): Ordered dict of registers from input DAG. rng (RandomState): Random number generator. Returns: Tuple: success_flag, best_circuit, best_depth, best_layout, trivial_flag Raises: TranspilerError: if anything went wrong. """ logger.debug("layer_permutation: layer_partition = %s", pformat(layer_partition)) logger.debug("layer_permutation: layout = %s", pformat(layout.get_virtual_bits())) logger.debug("layer_permutation: qubit_subset = %s", pformat(qubit_subset)) logger.debug("layer_permutation: trials = %s", trials) gates = [] # list of lists of tuples [[(register, index), ...], ...] for gate_args in layer_partition: if len(gate_args) > 2: raise TranspilerError("Layer contains > 2-qubit gates") elif len(gate_args) == 2: gates.append(tuple(gate_args)) logger.debug("layer_permutation: gates = %s", pformat(gates)) # Can we already apply the gates? If so, there is no work to do. dist = sum([coupling.distance(layout[g[0]], layout[g[1]]) for g in gates]) logger.debug("layer_permutation: distance = %s", dist) if dist == len(gates): logger.debug("layer_permutation: nothing to do") circ = DAGCircuit() for register in layout.get_virtual_bits().keys(): if register[0] not in circ.qregs.values(): circ.add_qreg(register[0]) return True, circ, 0, layout, (not bool(gates)) # Begin loop over trials of randomized algorithm num_qubits = len(layout) best_depth = inf # initialize best depth best_edges = None # best edges found best_circuit = None # initialize best swap circuit best_layout = None # initialize best final layout cdist2 = coupling._dist_matrix**2 # Scaling matrix scale = np.zeros((num_qubits, num_qubits)) int_qubit_subset = regtuple_to_numeric(qubit_subset, qregs) int_gates = gates_to_idx(gates, qregs) int_layout = nlayout_from_layout(layout, qregs, coupling.size()) trial_circuit = DAGCircuit() # SWAP circuit for this trial for register in layout.get_virtual_bits().keys(): if register[0] not in trial_circuit.qregs.values(): trial_circuit.add_qreg(register[0]) slice_circuit = DAGCircuit() # circuit for this swap slice for register in layout.get_virtual_bits().keys(): if register[0] not in slice_circuit.qregs.values(): slice_circuit.add_qreg(register[0]) edges = np.asarray(coupling.get_edges(), dtype=np.int32).ravel() cdist = coupling._dist_matrix for trial in range(trials): logger.debug("layer_permutation: trial %s", trial) # This is one Trial -------------------------------------- dist, optim_edges, trial_layout, depth_step = swap_trial(num_qubits, int_layout, int_qubit_subset, int_gates, cdist2, cdist, edges, scale, rng) logger.debug("layer_permutation: final distance for this trial = %s", dist) if dist == len(gates) and depth_step < best_depth: logger.debug("layer_permutation: got circuit with improved depth %s", depth_step) best_edges = optim_edges best_layout = trial_layout best_depth = min(best_depth, depth_step) # Break out of trial loop if we found a depth 1 circuit # since we can't improve it further if best_depth == 1: break # If we have no best circuit for this layer, all of the # trials have failed if best_layout is None: logger.debug("layer_permutation: failed!") return False, None, None, None, False edgs = best_edges.edges() for idx in range(best_edges.size//2): slice_circuit.apply_operation_back( SwapGate(), [initial_layout[edgs[2*idx]], initial_layout[edgs[2*idx+1]]], []) trial_circuit.extend_back(slice_circuit) best_circuit = trial_circuit # Otherwise, we return our result for this layer logger.debug("layer_permutation: success!") best_lay = best_layout.to_layout(qregs) return True, best_circuit, best_depth, best_lay, False
def _layer_permutation(layer_partition, initial_layout, layout, qubit_subset, coupling, trials, qregs, rng): """Find a swap circuit that implements a permutation for this layer. Args: layer_partition (list): The layer_partition is a list of (qu)bit lists and each qubit is a tuple (qreg, index). initial_layout (Layout): The initial layout passed. layout (Layout): The layout is a Layout object mapping virtual qubits in the input circuit to physical qubits in the coupling graph. It reflects the current positions of the data. qubit_subset (list): The qubit_subset is the set of qubits in the coupling graph that we have chosen to map into, as tuples (Register, index). coupling (CouplingMap): Directed graph representing a coupling map. This coupling map should be one that was provided to the stochastic mapper. trials (int): Number of attempts the randomized algorithm makes. qregs (OrderedDict): Ordered dict of registers from input DAG. rng (RandomState): Random number generator. Returns: Tuple: success_flag, best_circuit, best_depth, best_layout, trivial_flag Raises: TranspilerError: if anything went wrong. """ logger.debug("layer_permutation: layer_partition = %s", pformat(layer_partition)) logger.debug("layer_permutation: layout = %s", pformat(layout.get_virtual_bits())) logger.debug("layer_permutation: qubit_subset = %s", pformat(qubit_subset)) logger.debug("layer_permutation: trials = %s", trials) gates = [] # list of lists of tuples [[(register, index), ...], ...] for gate_args in layer_partition: if len(gate_args) > 2: raise TranspilerError("Layer contains > 2-qubit gates") elif len(gate_args) == 2: gates.append(tuple(gate_args)) logger.debug("layer_permutation: gates = %s", pformat(gates)) # Can we already apply the gates? If so, there is no work to do. dist = sum([coupling.distance(layout[g[0]], layout[g[1]]) for g in gates]) logger.debug("layer_permutation: distance = %s", dist) if dist == len(gates): logger.debug("layer_permutation: nothing to do") circ = DAGCircuit() for register in layout.get_virtual_bits().keys(): if register[0] not in circ.qregs.values(): circ.add_qreg(register[0]) return True, circ, 0, layout, (not bool(gates)) # Begin loop over trials of randomized algorithm num_qubits = len(layout) best_depth = inf # initialize best depth best_edges = None # best edges found best_circuit = None # initialize best swap circuit best_layout = None # initialize best final layout cdist2 = coupling._dist_matrix**2 # Scaling matrix scale = np.zeros((num_qubits, num_qubits)) int_qubit_subset = regtuple_to_numeric(qubit_subset, qregs) int_gates = gates_to_idx(gates, qregs) int_layout = nlayout_from_layout(layout, qregs, coupling.size()) trial_circuit = DAGCircuit() # SWAP circuit for this trial for register in layout.get_virtual_bits().keys(): if register[0] not in trial_circuit.qregs.values(): trial_circuit.add_qreg(register[0]) slice_circuit = DAGCircuit() # circuit for this swap slice for register in layout.get_virtual_bits().keys(): if register[0] not in slice_circuit.qregs.values(): slice_circuit.add_qreg(register[0]) edges = np.asarray(coupling.get_edges(), dtype=np.int32).ravel() cdist = coupling._dist_matrix for trial in range(trials): logger.debug("layer_permutation: trial %s", trial) # This is one Trial -------------------------------------- dist, optim_edges, trial_layout, depth_step = swap_trial(num_qubits, int_layout, int_qubit_subset, int_gates, cdist2, cdist, edges, scale, rng) logger.debug("layer_permutation: final distance for this trial = %s", dist) if dist == len(gates) and depth_step < best_depth: logger.debug("layer_permutation: got circuit with improved depth %s", depth_step) best_edges = optim_edges best_layout = trial_layout best_depth = min(best_depth, depth_step) # Break out of trial loop if we found a depth 1 circuit # since we can't improve it further if best_depth == 1: break # If we have no best circuit for this layer, all of the # trials have failed if best_layout is None: logger.debug("layer_permutation: failed!") return False, None, None, None, False edgs = best_edges.edges() for idx in range(best_edges.size//2): slice_circuit.apply_operation_back( SwapGate(), [initial_layout[edgs[2*idx]], initial_layout[edgs[2*idx+1]]], []) trial_circuit.extend_back(slice_circuit) best_circuit = trial_circuit # Otherwise, we return our result for this layer logger.debug("layer_permutation: success!") best_lay = best_layout.to_layout(qregs) return True, best_circuit, best_depth, best_lay, False
[ "Find", "a", "swap", "circuit", "that", "implements", "a", "permutation", "for", "this", "layer", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/stochastic_swap.py#L390-L509
[ "def", "_layer_permutation", "(", "layer_partition", ",", "initial_layout", ",", "layout", ",", "qubit_subset", ",", "coupling", ",", "trials", ",", "qregs", ",", "rng", ")", ":", "logger", ".", "debug", "(", "\"layer_permutation: layer_partition = %s\"", ",", "pformat", "(", "layer_partition", ")", ")", "logger", ".", "debug", "(", "\"layer_permutation: layout = %s\"", ",", "pformat", "(", "layout", ".", "get_virtual_bits", "(", ")", ")", ")", "logger", ".", "debug", "(", "\"layer_permutation: qubit_subset = %s\"", ",", "pformat", "(", "qubit_subset", ")", ")", "logger", ".", "debug", "(", "\"layer_permutation: trials = %s\"", ",", "trials", ")", "gates", "=", "[", "]", "# list of lists of tuples [[(register, index), ...], ...]", "for", "gate_args", "in", "layer_partition", ":", "if", "len", "(", "gate_args", ")", ">", "2", ":", "raise", "TranspilerError", "(", "\"Layer contains > 2-qubit gates\"", ")", "elif", "len", "(", "gate_args", ")", "==", "2", ":", "gates", ".", "append", "(", "tuple", "(", "gate_args", ")", ")", "logger", ".", "debug", "(", "\"layer_permutation: gates = %s\"", ",", "pformat", "(", "gates", ")", ")", "# Can we already apply the gates? If so, there is no work to do.", "dist", "=", "sum", "(", "[", "coupling", ".", "distance", "(", "layout", "[", "g", "[", "0", "]", "]", ",", "layout", "[", "g", "[", "1", "]", "]", ")", "for", "g", "in", "gates", "]", ")", "logger", ".", "debug", "(", "\"layer_permutation: distance = %s\"", ",", "dist", ")", "if", "dist", "==", "len", "(", "gates", ")", ":", "logger", ".", "debug", "(", "\"layer_permutation: nothing to do\"", ")", "circ", "=", "DAGCircuit", "(", ")", "for", "register", "in", "layout", ".", "get_virtual_bits", "(", ")", ".", "keys", "(", ")", ":", "if", "register", "[", "0", "]", "not", "in", "circ", ".", "qregs", ".", "values", "(", ")", ":", "circ", ".", "add_qreg", "(", "register", "[", "0", "]", ")", "return", "True", ",", "circ", ",", "0", ",", "layout", ",", "(", "not", "bool", "(", "gates", ")", ")", "# Begin loop over trials of randomized algorithm", "num_qubits", "=", "len", "(", "layout", ")", "best_depth", "=", "inf", "# initialize best depth", "best_edges", "=", "None", "# best edges found", "best_circuit", "=", "None", "# initialize best swap circuit", "best_layout", "=", "None", "# initialize best final layout", "cdist2", "=", "coupling", ".", "_dist_matrix", "**", "2", "# Scaling matrix", "scale", "=", "np", ".", "zeros", "(", "(", "num_qubits", ",", "num_qubits", ")", ")", "int_qubit_subset", "=", "regtuple_to_numeric", "(", "qubit_subset", ",", "qregs", ")", "int_gates", "=", "gates_to_idx", "(", "gates", ",", "qregs", ")", "int_layout", "=", "nlayout_from_layout", "(", "layout", ",", "qregs", ",", "coupling", ".", "size", "(", ")", ")", "trial_circuit", "=", "DAGCircuit", "(", ")", "# SWAP circuit for this trial", "for", "register", "in", "layout", ".", "get_virtual_bits", "(", ")", ".", "keys", "(", ")", ":", "if", "register", "[", "0", "]", "not", "in", "trial_circuit", ".", "qregs", ".", "values", "(", ")", ":", "trial_circuit", ".", "add_qreg", "(", "register", "[", "0", "]", ")", "slice_circuit", "=", "DAGCircuit", "(", ")", "# circuit for this swap slice", "for", "register", "in", "layout", ".", "get_virtual_bits", "(", ")", ".", "keys", "(", ")", ":", "if", "register", "[", "0", "]", "not", "in", "slice_circuit", ".", "qregs", ".", "values", "(", ")", ":", "slice_circuit", ".", "add_qreg", "(", "register", "[", "0", "]", ")", "edges", "=", "np", ".", "asarray", "(", "coupling", ".", "get_edges", "(", ")", ",", "dtype", "=", "np", ".", "int32", ")", ".", "ravel", "(", ")", "cdist", "=", "coupling", ".", "_dist_matrix", "for", "trial", "in", "range", "(", "trials", ")", ":", "logger", ".", "debug", "(", "\"layer_permutation: trial %s\"", ",", "trial", ")", "# This is one Trial --------------------------------------", "dist", ",", "optim_edges", ",", "trial_layout", ",", "depth_step", "=", "swap_trial", "(", "num_qubits", ",", "int_layout", ",", "int_qubit_subset", ",", "int_gates", ",", "cdist2", ",", "cdist", ",", "edges", ",", "scale", ",", "rng", ")", "logger", ".", "debug", "(", "\"layer_permutation: final distance for this trial = %s\"", ",", "dist", ")", "if", "dist", "==", "len", "(", "gates", ")", "and", "depth_step", "<", "best_depth", ":", "logger", ".", "debug", "(", "\"layer_permutation: got circuit with improved depth %s\"", ",", "depth_step", ")", "best_edges", "=", "optim_edges", "best_layout", "=", "trial_layout", "best_depth", "=", "min", "(", "best_depth", ",", "depth_step", ")", "# Break out of trial loop if we found a depth 1 circuit", "# since we can't improve it further", "if", "best_depth", "==", "1", ":", "break", "# If we have no best circuit for this layer, all of the", "# trials have failed", "if", "best_layout", "is", "None", ":", "logger", ".", "debug", "(", "\"layer_permutation: failed!\"", ")", "return", "False", ",", "None", ",", "None", ",", "None", ",", "False", "edgs", "=", "best_edges", ".", "edges", "(", ")", "for", "idx", "in", "range", "(", "best_edges", ".", "size", "//", "2", ")", ":", "slice_circuit", ".", "apply_operation_back", "(", "SwapGate", "(", ")", ",", "[", "initial_layout", "[", "edgs", "[", "2", "*", "idx", "]", "]", ",", "initial_layout", "[", "edgs", "[", "2", "*", "idx", "+", "1", "]", "]", "]", ",", "[", "]", ")", "trial_circuit", ".", "extend_back", "(", "slice_circuit", ")", "best_circuit", "=", "trial_circuit", "# Otherwise, we return our result for this layer", "logger", ".", "debug", "(", "\"layer_permutation: success!\"", ")", "best_lay", "=", "best_layout", ".", "to_layout", "(", "qregs", ")", "return", "True", ",", "best_circuit", ",", "best_depth", ",", "best_lay", ",", "False" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
regtuple_to_numeric
Takes (QuantumRegister, int) tuples and converts them into an integer array. Args: items (list): List of tuples of (QuantumRegister, int) to convert. qregs (dict): List of )QuantumRegister, int) tuples. Returns: ndarray: Array of integers.
qiskit/transpiler/passes/mapping/stochastic_swap.py
def regtuple_to_numeric(items, qregs): """Takes (QuantumRegister, int) tuples and converts them into an integer array. Args: items (list): List of tuples of (QuantumRegister, int) to convert. qregs (dict): List of )QuantumRegister, int) tuples. Returns: ndarray: Array of integers. """ sizes = [qr.size for qr in qregs.values()] reg_idx = np.cumsum([0]+sizes) regint = {} for ind, qreg in enumerate(qregs.values()): regint[qreg] = ind out = np.zeros(len(items), dtype=np.int32) for idx, val in enumerate(items): out[idx] = reg_idx[regint[val[0]]]+val[1] return out
def regtuple_to_numeric(items, qregs): """Takes (QuantumRegister, int) tuples and converts them into an integer array. Args: items (list): List of tuples of (QuantumRegister, int) to convert. qregs (dict): List of )QuantumRegister, int) tuples. Returns: ndarray: Array of integers. """ sizes = [qr.size for qr in qregs.values()] reg_idx = np.cumsum([0]+sizes) regint = {} for ind, qreg in enumerate(qregs.values()): regint[qreg] = ind out = np.zeros(len(items), dtype=np.int32) for idx, val in enumerate(items): out[idx] = reg_idx[regint[val[0]]]+val[1] return out
[ "Takes", "(", "QuantumRegister", "int", ")", "tuples", "and", "converts", "them", "into", "an", "integer", "array", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/stochastic_swap.py#L512-L532
[ "def", "regtuple_to_numeric", "(", "items", ",", "qregs", ")", ":", "sizes", "=", "[", "qr", ".", "size", "for", "qr", "in", "qregs", ".", "values", "(", ")", "]", "reg_idx", "=", "np", ".", "cumsum", "(", "[", "0", "]", "+", "sizes", ")", "regint", "=", "{", "}", "for", "ind", ",", "qreg", "in", "enumerate", "(", "qregs", ".", "values", "(", ")", ")", ":", "regint", "[", "qreg", "]", "=", "ind", "out", "=", "np", ".", "zeros", "(", "len", "(", "items", ")", ",", "dtype", "=", "np", ".", "int32", ")", "for", "idx", ",", "val", "in", "enumerate", "(", "items", ")", ":", "out", "[", "idx", "]", "=", "reg_idx", "[", "regint", "[", "val", "[", "0", "]", "]", "]", "+", "val", "[", "1", "]", "return", "out" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
gates_to_idx
Converts gate tuples into a nested list of integers. Args: gates (list): List of (QuantumRegister, int) pairs representing gates. qregs (dict): List of )QuantumRegister, int) tuples. Returns: list: Nested list of integers for gates.
qiskit/transpiler/passes/mapping/stochastic_swap.py
def gates_to_idx(gates, qregs): """Converts gate tuples into a nested list of integers. Args: gates (list): List of (QuantumRegister, int) pairs representing gates. qregs (dict): List of )QuantumRegister, int) tuples. Returns: list: Nested list of integers for gates. """ sizes = [qr.size for qr in qregs.values()] reg_idx = np.cumsum([0]+sizes) regint = {} for ind, qreg in enumerate(qregs.values()): regint[qreg] = ind out = np.zeros(2*len(gates), dtype=np.int32) for idx, gate in enumerate(gates): out[2*idx] = reg_idx[regint[gate[0][0]]]+gate[0][1] out[2*idx+1] = reg_idx[regint[gate[1][0]]]+gate[1][1] return out
def gates_to_idx(gates, qregs): """Converts gate tuples into a nested list of integers. Args: gates (list): List of (QuantumRegister, int) pairs representing gates. qregs (dict): List of )QuantumRegister, int) tuples. Returns: list: Nested list of integers for gates. """ sizes = [qr.size for qr in qregs.values()] reg_idx = np.cumsum([0]+sizes) regint = {} for ind, qreg in enumerate(qregs.values()): regint[qreg] = ind out = np.zeros(2*len(gates), dtype=np.int32) for idx, gate in enumerate(gates): out[2*idx] = reg_idx[regint[gate[0][0]]]+gate[0][1] out[2*idx+1] = reg_idx[regint[gate[1][0]]]+gate[1][1] return out
[ "Converts", "gate", "tuples", "into", "a", "nested", "list", "of", "integers", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/stochastic_swap.py#L535-L555
[ "def", "gates_to_idx", "(", "gates", ",", "qregs", ")", ":", "sizes", "=", "[", "qr", ".", "size", "for", "qr", "in", "qregs", ".", "values", "(", ")", "]", "reg_idx", "=", "np", ".", "cumsum", "(", "[", "0", "]", "+", "sizes", ")", "regint", "=", "{", "}", "for", "ind", ",", "qreg", "in", "enumerate", "(", "qregs", ".", "values", "(", ")", ")", ":", "regint", "[", "qreg", "]", "=", "ind", "out", "=", "np", ".", "zeros", "(", "2", "*", "len", "(", "gates", ")", ",", "dtype", "=", "np", ".", "int32", ")", "for", "idx", ",", "gate", "in", "enumerate", "(", "gates", ")", ":", "out", "[", "2", "*", "idx", "]", "=", "reg_idx", "[", "regint", "[", "gate", "[", "0", "]", "[", "0", "]", "]", "]", "+", "gate", "[", "0", "]", "[", "1", "]", "out", "[", "2", "*", "idx", "+", "1", "]", "=", "reg_idx", "[", "regint", "[", "gate", "[", "1", "]", "[", "0", "]", "]", "]", "+", "gate", "[", "1", "]", "[", "1", "]", "return", "out" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
StochasticSwap.run
Run the StochasticSwap pass on `dag`. Args: dag (DAGCircuit): DAG to map. Returns: DAGCircuit: A mapped DAG. Raises: TranspilerError: if the coupling map or the layout are not compatible with the DAG
qiskit/transpiler/passes/mapping/stochastic_swap.py
def run(self, dag): """ Run the StochasticSwap pass on `dag`. Args: dag (DAGCircuit): DAG to map. Returns: DAGCircuit: A mapped DAG. Raises: TranspilerError: if the coupling map or the layout are not compatible with the DAG """ if self.initial_layout is None: if self.property_set["layout"]: self.initial_layout = self.property_set["layout"] else: self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values()) if len(dag.qubits()) != len(self.initial_layout): raise TranspilerError('The layout does not match the amount of qubits in the DAG') if len(self.coupling_map.physical_qubits) != len(self.initial_layout): raise TranspilerError( "Mappers require to have the layout to be the same size as the coupling map") self.input_layout = self.initial_layout.copy() self.qregs = dag.qregs if self.seed is None: self.seed = np.random.randint(0, np.iinfo(np.int32).max) self.rng = np.random.RandomState(self.seed) logger.debug("StochasticSwap RandomState seeded with seed=%s", self.seed) new_dag = self._mapper(dag, self.coupling_map, trials=self.trials) # self.property_set["layout"] = self.initial_layout return new_dag
def run(self, dag): """ Run the StochasticSwap pass on `dag`. Args: dag (DAGCircuit): DAG to map. Returns: DAGCircuit: A mapped DAG. Raises: TranspilerError: if the coupling map or the layout are not compatible with the DAG """ if self.initial_layout is None: if self.property_set["layout"]: self.initial_layout = self.property_set["layout"] else: self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values()) if len(dag.qubits()) != len(self.initial_layout): raise TranspilerError('The layout does not match the amount of qubits in the DAG') if len(self.coupling_map.physical_qubits) != len(self.initial_layout): raise TranspilerError( "Mappers require to have the layout to be the same size as the coupling map") self.input_layout = self.initial_layout.copy() self.qregs = dag.qregs if self.seed is None: self.seed = np.random.randint(0, np.iinfo(np.int32).max) self.rng = np.random.RandomState(self.seed) logger.debug("StochasticSwap RandomState seeded with seed=%s", self.seed) new_dag = self._mapper(dag, self.coupling_map, trials=self.trials) # self.property_set["layout"] = self.initial_layout return new_dag
[ "Run", "the", "StochasticSwap", "pass", "on", "dag", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/stochastic_swap.py#L82-L120
[ "def", "run", "(", "self", ",", "dag", ")", ":", "if", "self", ".", "initial_layout", "is", "None", ":", "if", "self", ".", "property_set", "[", "\"layout\"", "]", ":", "self", ".", "initial_layout", "=", "self", ".", "property_set", "[", "\"layout\"", "]", "else", ":", "self", ".", "initial_layout", "=", "Layout", ".", "generate_trivial_layout", "(", "*", "dag", ".", "qregs", ".", "values", "(", ")", ")", "if", "len", "(", "dag", ".", "qubits", "(", ")", ")", "!=", "len", "(", "self", ".", "initial_layout", ")", ":", "raise", "TranspilerError", "(", "'The layout does not match the amount of qubits in the DAG'", ")", "if", "len", "(", "self", ".", "coupling_map", ".", "physical_qubits", ")", "!=", "len", "(", "self", ".", "initial_layout", ")", ":", "raise", "TranspilerError", "(", "\"Mappers require to have the layout to be the same size as the coupling map\"", ")", "self", ".", "input_layout", "=", "self", ".", "initial_layout", ".", "copy", "(", ")", "self", ".", "qregs", "=", "dag", ".", "qregs", "if", "self", ".", "seed", "is", "None", ":", "self", ".", "seed", "=", "np", ".", "random", ".", "randint", "(", "0", ",", "np", ".", "iinfo", "(", "np", ".", "int32", ")", ".", "max", ")", "self", ".", "rng", "=", "np", ".", "random", ".", "RandomState", "(", "self", ".", "seed", ")", "logger", ".", "debug", "(", "\"StochasticSwap RandomState seeded with seed=%s\"", ",", "self", ".", "seed", ")", "new_dag", "=", "self", ".", "_mapper", "(", "dag", ",", "self", ".", "coupling_map", ",", "trials", "=", "self", ".", "trials", ")", "# self.property_set[\"layout\"] = self.initial_layout", "return", "new_dag" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
StochasticSwap._layer_permutation
Find a swap circuit that implements a permutation for this layer. The goal is to swap qubits such that qubits in the same two-qubit gates are adjacent. Based on S. Bravyi's algorithm. layer_partition (list): The layer_partition is a list of (qu)bit lists and each qubit is a tuple (qreg, index). layout (Layout): The layout is a Layout object mapping virtual qubits in the input circuit to physical qubits in the coupling graph. It reflects the current positions of the data. qubit_subset (list): The qubit_subset is the set of qubits in the coupling graph that we have chosen to map into, as tuples (Register, index). coupling (CouplingMap): Directed graph representing a coupling map. This coupling map should be one that was provided to the stochastic mapper. trials (int): Number of attempts the randomized algorithm makes. Returns: Tuple: success_flag, best_circuit, best_depth, best_layout, trivial_flag If success_flag is True, then best_circuit contains a DAGCircuit with the swap circuit, best_depth contains the depth of the swap circuit, and best_layout contains the new positions of the data qubits after the swap circuit has been applied. The trivial_flag is set if the layer has no multi-qubit gates. Raises: TranspilerError: if anything went wrong.
qiskit/transpiler/passes/mapping/stochastic_swap.py
def _layer_permutation(self, layer_partition, layout, qubit_subset, coupling, trials): """Find a swap circuit that implements a permutation for this layer. The goal is to swap qubits such that qubits in the same two-qubit gates are adjacent. Based on S. Bravyi's algorithm. layer_partition (list): The layer_partition is a list of (qu)bit lists and each qubit is a tuple (qreg, index). layout (Layout): The layout is a Layout object mapping virtual qubits in the input circuit to physical qubits in the coupling graph. It reflects the current positions of the data. qubit_subset (list): The qubit_subset is the set of qubits in the coupling graph that we have chosen to map into, as tuples (Register, index). coupling (CouplingMap): Directed graph representing a coupling map. This coupling map should be one that was provided to the stochastic mapper. trials (int): Number of attempts the randomized algorithm makes. Returns: Tuple: success_flag, best_circuit, best_depth, best_layout, trivial_flag If success_flag is True, then best_circuit contains a DAGCircuit with the swap circuit, best_depth contains the depth of the swap circuit, and best_layout contains the new positions of the data qubits after the swap circuit has been applied. The trivial_flag is set if the layer has no multi-qubit gates. Raises: TranspilerError: if anything went wrong. """ return _layer_permutation(layer_partition, self.initial_layout, layout, qubit_subset, coupling, trials, self.qregs, self.rng)
def _layer_permutation(self, layer_partition, layout, qubit_subset, coupling, trials): """Find a swap circuit that implements a permutation for this layer. The goal is to swap qubits such that qubits in the same two-qubit gates are adjacent. Based on S. Bravyi's algorithm. layer_partition (list): The layer_partition is a list of (qu)bit lists and each qubit is a tuple (qreg, index). layout (Layout): The layout is a Layout object mapping virtual qubits in the input circuit to physical qubits in the coupling graph. It reflects the current positions of the data. qubit_subset (list): The qubit_subset is the set of qubits in the coupling graph that we have chosen to map into, as tuples (Register, index). coupling (CouplingMap): Directed graph representing a coupling map. This coupling map should be one that was provided to the stochastic mapper. trials (int): Number of attempts the randomized algorithm makes. Returns: Tuple: success_flag, best_circuit, best_depth, best_layout, trivial_flag If success_flag is True, then best_circuit contains a DAGCircuit with the swap circuit, best_depth contains the depth of the swap circuit, and best_layout contains the new positions of the data qubits after the swap circuit has been applied. The trivial_flag is set if the layer has no multi-qubit gates. Raises: TranspilerError: if anything went wrong. """ return _layer_permutation(layer_partition, self.initial_layout, layout, qubit_subset, coupling, trials, self.qregs, self.rng)
[ "Find", "a", "swap", "circuit", "that", "implements", "a", "permutation", "for", "this", "layer", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/stochastic_swap.py#L122-L159
[ "def", "_layer_permutation", "(", "self", ",", "layer_partition", ",", "layout", ",", "qubit_subset", ",", "coupling", ",", "trials", ")", ":", "return", "_layer_permutation", "(", "layer_partition", ",", "self", ".", "initial_layout", ",", "layout", ",", "qubit_subset", ",", "coupling", ",", "trials", ",", "self", ".", "qregs", ",", "self", ".", "rng", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
StochasticSwap._layer_update
Provide a DAGCircuit for a new mapped layer. i (int) = layer number first_layer (bool) = True if this is the first layer in the circuit with any multi-qubit gates best_layout (Layout) = layout returned from _layer_permutation best_depth (int) = depth returned from _layer_permutation best_circuit (DAGCircuit) = swap circuit returned from _layer_permutation layer_list (list) = list of DAGCircuit objects for each layer, output of DAGCircuit layers() method Return a DAGCircuit object to append to the output DAGCircuit that the _mapper method is building.
qiskit/transpiler/passes/mapping/stochastic_swap.py
def _layer_update(self, i, first_layer, best_layout, best_depth, best_circuit, layer_list): """Provide a DAGCircuit for a new mapped layer. i (int) = layer number first_layer (bool) = True if this is the first layer in the circuit with any multi-qubit gates best_layout (Layout) = layout returned from _layer_permutation best_depth (int) = depth returned from _layer_permutation best_circuit (DAGCircuit) = swap circuit returned from _layer_permutation layer_list (list) = list of DAGCircuit objects for each layer, output of DAGCircuit layers() method Return a DAGCircuit object to append to the output DAGCircuit that the _mapper method is building. """ layout = best_layout logger.debug("layer_update: layout = %s", pformat(layout)) logger.debug("layer_update: self.initial_layout = %s", pformat(self.initial_layout)) dagcircuit_output = DAGCircuit() for register in layout.get_virtual_bits().keys(): if register[0] not in dagcircuit_output.qregs.values(): dagcircuit_output.add_qreg(register[0]) # If this is the first layer with multi-qubit gates, # output all layers up to this point and ignore any # swap gates. Set the initial layout. if first_layer: logger.debug("layer_update: first multi-qubit gate layer") # Output all layers up to this point for j in range(i + 1): # Make qubit edge map and extend by classical bits edge_map = layout.combine_into_edge_map(self.initial_layout) for bit in dagcircuit_output.clbits(): edge_map[bit] = bit dagcircuit_output.compose_back(layer_list[j]["graph"], edge_map) # Otherwise, we output the current layer and the associated swap gates. else: # Output any swaps if best_depth > 0: logger.debug("layer_update: there are swaps in this layer, " "depth %d", best_depth) dagcircuit_output.extend_back(best_circuit) else: logger.debug("layer_update: there are no swaps in this layer") # Make qubit edge map and extend by classical bits edge_map = layout.combine_into_edge_map(self.initial_layout) for bit in dagcircuit_output.clbits(): edge_map[bit] = bit # Output this layer dagcircuit_output.compose_back(layer_list[i]["graph"], edge_map) return dagcircuit_output
def _layer_update(self, i, first_layer, best_layout, best_depth, best_circuit, layer_list): """Provide a DAGCircuit for a new mapped layer. i (int) = layer number first_layer (bool) = True if this is the first layer in the circuit with any multi-qubit gates best_layout (Layout) = layout returned from _layer_permutation best_depth (int) = depth returned from _layer_permutation best_circuit (DAGCircuit) = swap circuit returned from _layer_permutation layer_list (list) = list of DAGCircuit objects for each layer, output of DAGCircuit layers() method Return a DAGCircuit object to append to the output DAGCircuit that the _mapper method is building. """ layout = best_layout logger.debug("layer_update: layout = %s", pformat(layout)) logger.debug("layer_update: self.initial_layout = %s", pformat(self.initial_layout)) dagcircuit_output = DAGCircuit() for register in layout.get_virtual_bits().keys(): if register[0] not in dagcircuit_output.qregs.values(): dagcircuit_output.add_qreg(register[0]) # If this is the first layer with multi-qubit gates, # output all layers up to this point and ignore any # swap gates. Set the initial layout. if first_layer: logger.debug("layer_update: first multi-qubit gate layer") # Output all layers up to this point for j in range(i + 1): # Make qubit edge map and extend by classical bits edge_map = layout.combine_into_edge_map(self.initial_layout) for bit in dagcircuit_output.clbits(): edge_map[bit] = bit dagcircuit_output.compose_back(layer_list[j]["graph"], edge_map) # Otherwise, we output the current layer and the associated swap gates. else: # Output any swaps if best_depth > 0: logger.debug("layer_update: there are swaps in this layer, " "depth %d", best_depth) dagcircuit_output.extend_back(best_circuit) else: logger.debug("layer_update: there are no swaps in this layer") # Make qubit edge map and extend by classical bits edge_map = layout.combine_into_edge_map(self.initial_layout) for bit in dagcircuit_output.clbits(): edge_map[bit] = bit # Output this layer dagcircuit_output.compose_back(layer_list[i]["graph"], edge_map) return dagcircuit_output
[ "Provide", "a", "DAGCircuit", "for", "a", "new", "mapped", "layer", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/stochastic_swap.py#L161-L214
[ "def", "_layer_update", "(", "self", ",", "i", ",", "first_layer", ",", "best_layout", ",", "best_depth", ",", "best_circuit", ",", "layer_list", ")", ":", "layout", "=", "best_layout", "logger", ".", "debug", "(", "\"layer_update: layout = %s\"", ",", "pformat", "(", "layout", ")", ")", "logger", ".", "debug", "(", "\"layer_update: self.initial_layout = %s\"", ",", "pformat", "(", "self", ".", "initial_layout", ")", ")", "dagcircuit_output", "=", "DAGCircuit", "(", ")", "for", "register", "in", "layout", ".", "get_virtual_bits", "(", ")", ".", "keys", "(", ")", ":", "if", "register", "[", "0", "]", "not", "in", "dagcircuit_output", ".", "qregs", ".", "values", "(", ")", ":", "dagcircuit_output", ".", "add_qreg", "(", "register", "[", "0", "]", ")", "# If this is the first layer with multi-qubit gates,", "# output all layers up to this point and ignore any", "# swap gates. Set the initial layout.", "if", "first_layer", ":", "logger", ".", "debug", "(", "\"layer_update: first multi-qubit gate layer\"", ")", "# Output all layers up to this point", "for", "j", "in", "range", "(", "i", "+", "1", ")", ":", "# Make qubit edge map and extend by classical bits", "edge_map", "=", "layout", ".", "combine_into_edge_map", "(", "self", ".", "initial_layout", ")", "for", "bit", "in", "dagcircuit_output", ".", "clbits", "(", ")", ":", "edge_map", "[", "bit", "]", "=", "bit", "dagcircuit_output", ".", "compose_back", "(", "layer_list", "[", "j", "]", "[", "\"graph\"", "]", ",", "edge_map", ")", "# Otherwise, we output the current layer and the associated swap gates.", "else", ":", "# Output any swaps", "if", "best_depth", ">", "0", ":", "logger", ".", "debug", "(", "\"layer_update: there are swaps in this layer, \"", "\"depth %d\"", ",", "best_depth", ")", "dagcircuit_output", ".", "extend_back", "(", "best_circuit", ")", "else", ":", "logger", ".", "debug", "(", "\"layer_update: there are no swaps in this layer\"", ")", "# Make qubit edge map and extend by classical bits", "edge_map", "=", "layout", ".", "combine_into_edge_map", "(", "self", ".", "initial_layout", ")", "for", "bit", "in", "dagcircuit_output", ".", "clbits", "(", ")", ":", "edge_map", "[", "bit", "]", "=", "bit", "# Output this layer", "dagcircuit_output", ".", "compose_back", "(", "layer_list", "[", "i", "]", "[", "\"graph\"", "]", ",", "edge_map", ")", "return", "dagcircuit_output" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
StochasticSwap._mapper
Map a DAGCircuit onto a CouplingMap using swap gates. Use self.initial_layout for the initial layout. Args: circuit_graph (DAGCircuit): input DAG circuit coupling_graph (CouplingMap): coupling graph to map onto trials (int): number of trials. Returns: DAGCircuit: object containing a circuit equivalent to circuit_graph that respects couplings in coupling_graph Layout: a layout object mapping qubits of circuit_graph into qubits of coupling_graph. The layout may differ from the initial_layout if the first layer of gates cannot be executed on the initial_layout, since in this case it is more efficient to modify the layout instead of swapping Dict: a final-layer qubit permutation Raises: TranspilerError: if there was any error during the mapping or with the parameters.
qiskit/transpiler/passes/mapping/stochastic_swap.py
def _mapper(self, circuit_graph, coupling_graph, trials=20): """Map a DAGCircuit onto a CouplingMap using swap gates. Use self.initial_layout for the initial layout. Args: circuit_graph (DAGCircuit): input DAG circuit coupling_graph (CouplingMap): coupling graph to map onto trials (int): number of trials. Returns: DAGCircuit: object containing a circuit equivalent to circuit_graph that respects couplings in coupling_graph Layout: a layout object mapping qubits of circuit_graph into qubits of coupling_graph. The layout may differ from the initial_layout if the first layer of gates cannot be executed on the initial_layout, since in this case it is more efficient to modify the layout instead of swapping Dict: a final-layer qubit permutation Raises: TranspilerError: if there was any error during the mapping or with the parameters. """ # Schedule the input circuit by calling layers() layerlist = list(circuit_graph.layers()) logger.debug("schedule:") for i, v in enumerate(layerlist): logger.debug(" %d: %s", i, v["partition"]) if self.initial_layout is not None: qubit_subset = self.initial_layout.get_virtual_bits().keys() else: # Supply a default layout for this dag self.initial_layout = Layout() physical_qubit = 0 for qreg in circuit_graph.qregs.values(): for index in range(qreg.size): self.initial_layout[(qreg, index)] = physical_qubit physical_qubit += 1 qubit_subset = self.initial_layout.get_virtual_bits().keys() # Restrict the coupling map to the image of the layout coupling_graph = coupling_graph.subgraph( self.initial_layout.get_physical_bits().keys()) if coupling_graph.size() < len(self.initial_layout): raise TranspilerError("Coupling map too small for default layout") self.input_layout = self.initial_layout.copy() # Find swap circuit to preceed to each layer of input circuit layout = self.initial_layout.copy() # Construct an empty DAGCircuit with the same set of # qregs and cregs as the input circuit dagcircuit_output = DAGCircuit() dagcircuit_output.name = circuit_graph.name for qreg in circuit_graph.qregs.values(): dagcircuit_output.add_qreg(qreg) for creg in circuit_graph.cregs.values(): dagcircuit_output.add_creg(creg) # Make a trivial wire mapping between the subcircuits # returned by _layer_update and the circuit we build identity_wire_map = {} for qubit in circuit_graph.qubits(): identity_wire_map[qubit] = qubit for bit in circuit_graph.clbits(): identity_wire_map[bit] = bit first_layer = True # True until first layer is output logger.debug("initial_layout = %s", layout) # Iterate over layers for i, layer in enumerate(layerlist): # Attempt to find a permutation for this layer success_flag, best_circuit, best_depth, best_layout, trivial_flag \ = self._layer_permutation(layer["partition"], layout, qubit_subset, coupling_graph, trials) logger.debug("mapper: layer %d", i) logger.debug("mapper: success_flag=%s,best_depth=%s,trivial_flag=%s", success_flag, str(best_depth), trivial_flag) # If this fails, try one gate at a time in this layer if not success_flag: logger.debug("mapper: failed, layer %d, " "retrying sequentially", i) serial_layerlist = list(layer["graph"].serial_layers()) # Go through each gate in the layer for j, serial_layer in enumerate(serial_layerlist): success_flag, best_circuit, best_depth, best_layout, trivial_flag = \ self._layer_permutation( serial_layer["partition"], layout, qubit_subset, coupling_graph, trials) logger.debug("mapper: layer %d, sublayer %d", i, j) logger.debug("mapper: success_flag=%s,best_depth=%s," "trivial_flag=%s", success_flag, str(best_depth), trivial_flag) # Give up if we fail again if not success_flag: raise TranspilerError("swap mapper failed: " + "layer %d, sublayer %d" % (i, j)) # If this layer is only single-qubit gates, # and we have yet to see multi-qubit gates, # continue to the next inner iteration if trivial_flag and first_layer: logger.debug("mapper: skip to next sublayer") continue if first_layer: self.initial_layout = layout # Update the record of qubit positions # for each inner iteration layout = best_layout # Update the DAG dagcircuit_output.extend_back( self._layer_update(j, first_layer, best_layout, best_depth, best_circuit, serial_layerlist), identity_wire_map) if first_layer: first_layer = False else: # Update the record of qubit positions for each iteration layout = best_layout if first_layer: self.initial_layout = layout # Update the DAG dagcircuit_output.extend_back( self._layer_update(i, first_layer, best_layout, best_depth, best_circuit, layerlist), identity_wire_map) if first_layer: first_layer = False # This is the final edgemap. We might use it to correctly replace # any measurements that needed to be removed earlier. logger.debug("mapper: self.initial_layout = %s", pformat(self.initial_layout)) logger.debug("mapper: layout = %s", pformat(layout)) last_edgemap = layout.combine_into_edge_map(self.initial_layout) logger.debug("mapper: last_edgemap = %s", pformat(last_edgemap)) # If first_layer is still set, the circuit only has single-qubit gates # so we can use the initial layout to output the entire circuit # This code is dead due to changes to first_layer above. if first_layer: logger.debug("mapper: first_layer flag still set") layout = self.initial_layout for i, layer in enumerate(layerlist): edge_map = layout.combine_into_edge_map(self.initial_layout) dagcircuit_output.compose_back(layer["graph"], edge_map) return dagcircuit_output
def _mapper(self, circuit_graph, coupling_graph, trials=20): """Map a DAGCircuit onto a CouplingMap using swap gates. Use self.initial_layout for the initial layout. Args: circuit_graph (DAGCircuit): input DAG circuit coupling_graph (CouplingMap): coupling graph to map onto trials (int): number of trials. Returns: DAGCircuit: object containing a circuit equivalent to circuit_graph that respects couplings in coupling_graph Layout: a layout object mapping qubits of circuit_graph into qubits of coupling_graph. The layout may differ from the initial_layout if the first layer of gates cannot be executed on the initial_layout, since in this case it is more efficient to modify the layout instead of swapping Dict: a final-layer qubit permutation Raises: TranspilerError: if there was any error during the mapping or with the parameters. """ # Schedule the input circuit by calling layers() layerlist = list(circuit_graph.layers()) logger.debug("schedule:") for i, v in enumerate(layerlist): logger.debug(" %d: %s", i, v["partition"]) if self.initial_layout is not None: qubit_subset = self.initial_layout.get_virtual_bits().keys() else: # Supply a default layout for this dag self.initial_layout = Layout() physical_qubit = 0 for qreg in circuit_graph.qregs.values(): for index in range(qreg.size): self.initial_layout[(qreg, index)] = physical_qubit physical_qubit += 1 qubit_subset = self.initial_layout.get_virtual_bits().keys() # Restrict the coupling map to the image of the layout coupling_graph = coupling_graph.subgraph( self.initial_layout.get_physical_bits().keys()) if coupling_graph.size() < len(self.initial_layout): raise TranspilerError("Coupling map too small for default layout") self.input_layout = self.initial_layout.copy() # Find swap circuit to preceed to each layer of input circuit layout = self.initial_layout.copy() # Construct an empty DAGCircuit with the same set of # qregs and cregs as the input circuit dagcircuit_output = DAGCircuit() dagcircuit_output.name = circuit_graph.name for qreg in circuit_graph.qregs.values(): dagcircuit_output.add_qreg(qreg) for creg in circuit_graph.cregs.values(): dagcircuit_output.add_creg(creg) # Make a trivial wire mapping between the subcircuits # returned by _layer_update and the circuit we build identity_wire_map = {} for qubit in circuit_graph.qubits(): identity_wire_map[qubit] = qubit for bit in circuit_graph.clbits(): identity_wire_map[bit] = bit first_layer = True # True until first layer is output logger.debug("initial_layout = %s", layout) # Iterate over layers for i, layer in enumerate(layerlist): # Attempt to find a permutation for this layer success_flag, best_circuit, best_depth, best_layout, trivial_flag \ = self._layer_permutation(layer["partition"], layout, qubit_subset, coupling_graph, trials) logger.debug("mapper: layer %d", i) logger.debug("mapper: success_flag=%s,best_depth=%s,trivial_flag=%s", success_flag, str(best_depth), trivial_flag) # If this fails, try one gate at a time in this layer if not success_flag: logger.debug("mapper: failed, layer %d, " "retrying sequentially", i) serial_layerlist = list(layer["graph"].serial_layers()) # Go through each gate in the layer for j, serial_layer in enumerate(serial_layerlist): success_flag, best_circuit, best_depth, best_layout, trivial_flag = \ self._layer_permutation( serial_layer["partition"], layout, qubit_subset, coupling_graph, trials) logger.debug("mapper: layer %d, sublayer %d", i, j) logger.debug("mapper: success_flag=%s,best_depth=%s," "trivial_flag=%s", success_flag, str(best_depth), trivial_flag) # Give up if we fail again if not success_flag: raise TranspilerError("swap mapper failed: " + "layer %d, sublayer %d" % (i, j)) # If this layer is only single-qubit gates, # and we have yet to see multi-qubit gates, # continue to the next inner iteration if trivial_flag and first_layer: logger.debug("mapper: skip to next sublayer") continue if first_layer: self.initial_layout = layout # Update the record of qubit positions # for each inner iteration layout = best_layout # Update the DAG dagcircuit_output.extend_back( self._layer_update(j, first_layer, best_layout, best_depth, best_circuit, serial_layerlist), identity_wire_map) if first_layer: first_layer = False else: # Update the record of qubit positions for each iteration layout = best_layout if first_layer: self.initial_layout = layout # Update the DAG dagcircuit_output.extend_back( self._layer_update(i, first_layer, best_layout, best_depth, best_circuit, layerlist), identity_wire_map) if first_layer: first_layer = False # This is the final edgemap. We might use it to correctly replace # any measurements that needed to be removed earlier. logger.debug("mapper: self.initial_layout = %s", pformat(self.initial_layout)) logger.debug("mapper: layout = %s", pformat(layout)) last_edgemap = layout.combine_into_edge_map(self.initial_layout) logger.debug("mapper: last_edgemap = %s", pformat(last_edgemap)) # If first_layer is still set, the circuit only has single-qubit gates # so we can use the initial layout to output the entire circuit # This code is dead due to changes to first_layer above. if first_layer: logger.debug("mapper: first_layer flag still set") layout = self.initial_layout for i, layer in enumerate(layerlist): edge_map = layout.combine_into_edge_map(self.initial_layout) dagcircuit_output.compose_back(layer["graph"], edge_map) return dagcircuit_output
[ "Map", "a", "DAGCircuit", "onto", "a", "CouplingMap", "using", "swap", "gates", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/stochastic_swap.py#L216-L387
[ "def", "_mapper", "(", "self", ",", "circuit_graph", ",", "coupling_graph", ",", "trials", "=", "20", ")", ":", "# Schedule the input circuit by calling layers()", "layerlist", "=", "list", "(", "circuit_graph", ".", "layers", "(", ")", ")", "logger", ".", "debug", "(", "\"schedule:\"", ")", "for", "i", ",", "v", "in", "enumerate", "(", "layerlist", ")", ":", "logger", ".", "debug", "(", "\" %d: %s\"", ",", "i", ",", "v", "[", "\"partition\"", "]", ")", "if", "self", ".", "initial_layout", "is", "not", "None", ":", "qubit_subset", "=", "self", ".", "initial_layout", ".", "get_virtual_bits", "(", ")", ".", "keys", "(", ")", "else", ":", "# Supply a default layout for this dag", "self", ".", "initial_layout", "=", "Layout", "(", ")", "physical_qubit", "=", "0", "for", "qreg", "in", "circuit_graph", ".", "qregs", ".", "values", "(", ")", ":", "for", "index", "in", "range", "(", "qreg", ".", "size", ")", ":", "self", ".", "initial_layout", "[", "(", "qreg", ",", "index", ")", "]", "=", "physical_qubit", "physical_qubit", "+=", "1", "qubit_subset", "=", "self", ".", "initial_layout", ".", "get_virtual_bits", "(", ")", ".", "keys", "(", ")", "# Restrict the coupling map to the image of the layout", "coupling_graph", "=", "coupling_graph", ".", "subgraph", "(", "self", ".", "initial_layout", ".", "get_physical_bits", "(", ")", ".", "keys", "(", ")", ")", "if", "coupling_graph", ".", "size", "(", ")", "<", "len", "(", "self", ".", "initial_layout", ")", ":", "raise", "TranspilerError", "(", "\"Coupling map too small for default layout\"", ")", "self", ".", "input_layout", "=", "self", ".", "initial_layout", ".", "copy", "(", ")", "# Find swap circuit to preceed to each layer of input circuit", "layout", "=", "self", ".", "initial_layout", ".", "copy", "(", ")", "# Construct an empty DAGCircuit with the same set of", "# qregs and cregs as the input circuit", "dagcircuit_output", "=", "DAGCircuit", "(", ")", "dagcircuit_output", ".", "name", "=", "circuit_graph", ".", "name", "for", "qreg", "in", "circuit_graph", ".", "qregs", ".", "values", "(", ")", ":", "dagcircuit_output", ".", "add_qreg", "(", "qreg", ")", "for", "creg", "in", "circuit_graph", ".", "cregs", ".", "values", "(", ")", ":", "dagcircuit_output", ".", "add_creg", "(", "creg", ")", "# Make a trivial wire mapping between the subcircuits", "# returned by _layer_update and the circuit we build", "identity_wire_map", "=", "{", "}", "for", "qubit", "in", "circuit_graph", ".", "qubits", "(", ")", ":", "identity_wire_map", "[", "qubit", "]", "=", "qubit", "for", "bit", "in", "circuit_graph", ".", "clbits", "(", ")", ":", "identity_wire_map", "[", "bit", "]", "=", "bit", "first_layer", "=", "True", "# True until first layer is output", "logger", ".", "debug", "(", "\"initial_layout = %s\"", ",", "layout", ")", "# Iterate over layers", "for", "i", ",", "layer", "in", "enumerate", "(", "layerlist", ")", ":", "# Attempt to find a permutation for this layer", "success_flag", ",", "best_circuit", ",", "best_depth", ",", "best_layout", ",", "trivial_flag", "=", "self", ".", "_layer_permutation", "(", "layer", "[", "\"partition\"", "]", ",", "layout", ",", "qubit_subset", ",", "coupling_graph", ",", "trials", ")", "logger", ".", "debug", "(", "\"mapper: layer %d\"", ",", "i", ")", "logger", ".", "debug", "(", "\"mapper: success_flag=%s,best_depth=%s,trivial_flag=%s\"", ",", "success_flag", ",", "str", "(", "best_depth", ")", ",", "trivial_flag", ")", "# If this fails, try one gate at a time in this layer", "if", "not", "success_flag", ":", "logger", ".", "debug", "(", "\"mapper: failed, layer %d, \"", "\"retrying sequentially\"", ",", "i", ")", "serial_layerlist", "=", "list", "(", "layer", "[", "\"graph\"", "]", ".", "serial_layers", "(", ")", ")", "# Go through each gate in the layer", "for", "j", ",", "serial_layer", "in", "enumerate", "(", "serial_layerlist", ")", ":", "success_flag", ",", "best_circuit", ",", "best_depth", ",", "best_layout", ",", "trivial_flag", "=", "self", ".", "_layer_permutation", "(", "serial_layer", "[", "\"partition\"", "]", ",", "layout", ",", "qubit_subset", ",", "coupling_graph", ",", "trials", ")", "logger", ".", "debug", "(", "\"mapper: layer %d, sublayer %d\"", ",", "i", ",", "j", ")", "logger", ".", "debug", "(", "\"mapper: success_flag=%s,best_depth=%s,\"", "\"trivial_flag=%s\"", ",", "success_flag", ",", "str", "(", "best_depth", ")", ",", "trivial_flag", ")", "# Give up if we fail again", "if", "not", "success_flag", ":", "raise", "TranspilerError", "(", "\"swap mapper failed: \"", "+", "\"layer %d, sublayer %d\"", "%", "(", "i", ",", "j", ")", ")", "# If this layer is only single-qubit gates,", "# and we have yet to see multi-qubit gates,", "# continue to the next inner iteration", "if", "trivial_flag", "and", "first_layer", ":", "logger", ".", "debug", "(", "\"mapper: skip to next sublayer\"", ")", "continue", "if", "first_layer", ":", "self", ".", "initial_layout", "=", "layout", "# Update the record of qubit positions", "# for each inner iteration", "layout", "=", "best_layout", "# Update the DAG", "dagcircuit_output", ".", "extend_back", "(", "self", ".", "_layer_update", "(", "j", ",", "first_layer", ",", "best_layout", ",", "best_depth", ",", "best_circuit", ",", "serial_layerlist", ")", ",", "identity_wire_map", ")", "if", "first_layer", ":", "first_layer", "=", "False", "else", ":", "# Update the record of qubit positions for each iteration", "layout", "=", "best_layout", "if", "first_layer", ":", "self", ".", "initial_layout", "=", "layout", "# Update the DAG", "dagcircuit_output", ".", "extend_back", "(", "self", ".", "_layer_update", "(", "i", ",", "first_layer", ",", "best_layout", ",", "best_depth", ",", "best_circuit", ",", "layerlist", ")", ",", "identity_wire_map", ")", "if", "first_layer", ":", "first_layer", "=", "False", "# This is the final edgemap. We might use it to correctly replace", "# any measurements that needed to be removed earlier.", "logger", ".", "debug", "(", "\"mapper: self.initial_layout = %s\"", ",", "pformat", "(", "self", ".", "initial_layout", ")", ")", "logger", ".", "debug", "(", "\"mapper: layout = %s\"", ",", "pformat", "(", "layout", ")", ")", "last_edgemap", "=", "layout", ".", "combine_into_edge_map", "(", "self", ".", "initial_layout", ")", "logger", ".", "debug", "(", "\"mapper: last_edgemap = %s\"", ",", "pformat", "(", "last_edgemap", ")", ")", "# If first_layer is still set, the circuit only has single-qubit gates", "# so we can use the initial layout to output the entire circuit", "# This code is dead due to changes to first_layer above.", "if", "first_layer", ":", "logger", ".", "debug", "(", "\"mapper: first_layer flag still set\"", ")", "layout", "=", "self", ".", "initial_layout", "for", "i", ",", "layer", "in", "enumerate", "(", "layerlist", ")", ":", "edge_map", "=", "layout", ".", "combine_into_edge_map", "(", "self", ".", "initial_layout", ")", "dagcircuit_output", ".", "compose_back", "(", "layer", "[", "\"graph\"", "]", ",", "edge_map", ")", "return", "dagcircuit_output" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
pauli_group
Return the Pauli group with 4^n elements. The phases have been removed. case 'weight' is ordered by Pauli weights and case 'tensor' is ordered by I,X,Y,Z counting lowest qubit fastest. Args: number_of_qubits (int): number of qubits case (str): determines ordering of group elements ('weight' or 'tensor') Returns: list: list of Pauli objects Raises: QiskitError: case is not 'weight' or 'tensor' QiskitError: number_of_qubits is larger than 4
qiskit/quantum_info/operators/pauli.py
def pauli_group(number_of_qubits, case='weight'): """Return the Pauli group with 4^n elements. The phases have been removed. case 'weight' is ordered by Pauli weights and case 'tensor' is ordered by I,X,Y,Z counting lowest qubit fastest. Args: number_of_qubits (int): number of qubits case (str): determines ordering of group elements ('weight' or 'tensor') Returns: list: list of Pauli objects Raises: QiskitError: case is not 'weight' or 'tensor' QiskitError: number_of_qubits is larger than 4 """ if number_of_qubits < 5: temp_set = [] if case == 'weight': tmp = pauli_group(number_of_qubits, case='tensor') # sort on the weight of the Pauli operator return sorted(tmp, key=lambda x: -np.count_nonzero( np.array(x.to_label(), 'c') == b'I')) elif case == 'tensor': # the Pauli set is in tensor order II IX IY IZ XI ... for k in range(4 ** number_of_qubits): z = np.zeros(number_of_qubits, dtype=np.bool) x = np.zeros(number_of_qubits, dtype=np.bool) # looping over all the qubits for j in range(number_of_qubits): # making the Pauli for each j fill it in from the # end first element = (k // (4 ** j)) % 4 if element == 1: x[j] = True elif element == 2: z[j] = True x[j] = True elif element == 3: z[j] = True temp_set.append(Pauli(z, x)) return temp_set else: raise QiskitError("Only support 'weight' or 'tensor' cases " "but you have {}.".format(case)) raise QiskitError("Only support number of qubits is less than 5")
def pauli_group(number_of_qubits, case='weight'): """Return the Pauli group with 4^n elements. The phases have been removed. case 'weight' is ordered by Pauli weights and case 'tensor' is ordered by I,X,Y,Z counting lowest qubit fastest. Args: number_of_qubits (int): number of qubits case (str): determines ordering of group elements ('weight' or 'tensor') Returns: list: list of Pauli objects Raises: QiskitError: case is not 'weight' or 'tensor' QiskitError: number_of_qubits is larger than 4 """ if number_of_qubits < 5: temp_set = [] if case == 'weight': tmp = pauli_group(number_of_qubits, case='tensor') # sort on the weight of the Pauli operator return sorted(tmp, key=lambda x: -np.count_nonzero( np.array(x.to_label(), 'c') == b'I')) elif case == 'tensor': # the Pauli set is in tensor order II IX IY IZ XI ... for k in range(4 ** number_of_qubits): z = np.zeros(number_of_qubits, dtype=np.bool) x = np.zeros(number_of_qubits, dtype=np.bool) # looping over all the qubits for j in range(number_of_qubits): # making the Pauli for each j fill it in from the # end first element = (k // (4 ** j)) % 4 if element == 1: x[j] = True elif element == 2: z[j] = True x[j] = True elif element == 3: z[j] = True temp_set.append(Pauli(z, x)) return temp_set else: raise QiskitError("Only support 'weight' or 'tensor' cases " "but you have {}.".format(case)) raise QiskitError("Only support number of qubits is less than 5")
[ "Return", "the", "Pauli", "group", "with", "4^n", "elements", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/pauli.py#L517-L566
[ "def", "pauli_group", "(", "number_of_qubits", ",", "case", "=", "'weight'", ")", ":", "if", "number_of_qubits", "<", "5", ":", "temp_set", "=", "[", "]", "if", "case", "==", "'weight'", ":", "tmp", "=", "pauli_group", "(", "number_of_qubits", ",", "case", "=", "'tensor'", ")", "# sort on the weight of the Pauli operator", "return", "sorted", "(", "tmp", ",", "key", "=", "lambda", "x", ":", "-", "np", ".", "count_nonzero", "(", "np", ".", "array", "(", "x", ".", "to_label", "(", ")", ",", "'c'", ")", "==", "b'I'", ")", ")", "elif", "case", "==", "'tensor'", ":", "# the Pauli set is in tensor order II IX IY IZ XI ...", "for", "k", "in", "range", "(", "4", "**", "number_of_qubits", ")", ":", "z", "=", "np", ".", "zeros", "(", "number_of_qubits", ",", "dtype", "=", "np", ".", "bool", ")", "x", "=", "np", ".", "zeros", "(", "number_of_qubits", ",", "dtype", "=", "np", ".", "bool", ")", "# looping over all the qubits", "for", "j", "in", "range", "(", "number_of_qubits", ")", ":", "# making the Pauli for each j fill it in from the", "# end first", "element", "=", "(", "k", "//", "(", "4", "**", "j", ")", ")", "%", "4", "if", "element", "==", "1", ":", "x", "[", "j", "]", "=", "True", "elif", "element", "==", "2", ":", "z", "[", "j", "]", "=", "True", "x", "[", "j", "]", "=", "True", "elif", "element", "==", "3", ":", "z", "[", "j", "]", "=", "True", "temp_set", ".", "append", "(", "Pauli", "(", "z", ",", "x", ")", ")", "return", "temp_set", "else", ":", "raise", "QiskitError", "(", "\"Only support 'weight' or 'tensor' cases \"", "\"but you have {}.\"", ".", "format", "(", "case", ")", ")", "raise", "QiskitError", "(", "\"Only support number of qubits is less than 5\"", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Pauli.from_label
r"""Take pauli string to construct pauli. The qubit index of pauli label is q_{n-1} ... q_0. E.g., a pauli is $P_{n-1} \otimes ... \otimes P_0$ Args: label (str): pauli label Returns: Pauli: the constructed pauli Raises: QiskitError: invalid character in the label
qiskit/quantum_info/operators/pauli.py
def from_label(cls, label): r"""Take pauli string to construct pauli. The qubit index of pauli label is q_{n-1} ... q_0. E.g., a pauli is $P_{n-1} \otimes ... \otimes P_0$ Args: label (str): pauli label Returns: Pauli: the constructed pauli Raises: QiskitError: invalid character in the label """ z = np.zeros(len(label), dtype=np.bool) x = np.zeros(len(label), dtype=np.bool) for i, char in enumerate(label): if char == 'X': x[-i - 1] = True elif char == 'Z': z[-i - 1] = True elif char == 'Y': z[-i - 1] = True x[-i - 1] = True elif char != 'I': raise QiskitError("Pauli string must be only consisted of 'I', 'X', " "'Y' or 'Z' but you have {}.".format(char)) return cls(z=z, x=x)
def from_label(cls, label): r"""Take pauli string to construct pauli. The qubit index of pauli label is q_{n-1} ... q_0. E.g., a pauli is $P_{n-1} \otimes ... \otimes P_0$ Args: label (str): pauli label Returns: Pauli: the constructed pauli Raises: QiskitError: invalid character in the label """ z = np.zeros(len(label), dtype=np.bool) x = np.zeros(len(label), dtype=np.bool) for i, char in enumerate(label): if char == 'X': x[-i - 1] = True elif char == 'Z': z[-i - 1] = True elif char == 'Y': z[-i - 1] = True x[-i - 1] = True elif char != 'I': raise QiskitError("Pauli string must be only consisted of 'I', 'X', " "'Y' or 'Z' but you have {}.".format(char)) return cls(z=z, x=x)
[ "r", "Take", "pauli", "string", "to", "construct", "pauli", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/pauli.py#L82-L110
[ "def", "from_label", "(", "cls", ",", "label", ")", ":", "z", "=", "np", ".", "zeros", "(", "len", "(", "label", ")", ",", "dtype", "=", "np", ".", "bool", ")", "x", "=", "np", ".", "zeros", "(", "len", "(", "label", ")", ",", "dtype", "=", "np", ".", "bool", ")", "for", "i", ",", "char", "in", "enumerate", "(", "label", ")", ":", "if", "char", "==", "'X'", ":", "x", "[", "-", "i", "-", "1", "]", "=", "True", "elif", "char", "==", "'Z'", ":", "z", "[", "-", "i", "-", "1", "]", "=", "True", "elif", "char", "==", "'Y'", ":", "z", "[", "-", "i", "-", "1", "]", "=", "True", "x", "[", "-", "i", "-", "1", "]", "=", "True", "elif", "char", "!=", "'I'", ":", "raise", "QiskitError", "(", "\"Pauli string must be only consisted of 'I', 'X', \"", "\"'Y' or 'Z' but you have {}.\"", ".", "format", "(", "char", ")", ")", "return", "cls", "(", "z", "=", "z", ",", "x", "=", "x", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Pauli._init_from_bool
Construct pauli from boolean array. Args: z (numpy.ndarray): boolean, z vector x (numpy.ndarray): boolean, x vector Returns: Pauli: self Raises: QiskitError: if z or x are None or the length of z and x are different.
qiskit/quantum_info/operators/pauli.py
def _init_from_bool(self, z, x): """Construct pauli from boolean array. Args: z (numpy.ndarray): boolean, z vector x (numpy.ndarray): boolean, x vector Returns: Pauli: self Raises: QiskitError: if z or x are None or the length of z and x are different. """ if z is None: raise QiskitError("z vector must not be None.") if x is None: raise QiskitError("x vector must not be None.") if len(z) != len(x): raise QiskitError("length of z and x vectors must be " "the same. (z: {} vs x: {})".format(len(z), len(x))) z = _make_np_bool(z) x = _make_np_bool(x) self._z = z self._x = x return self
def _init_from_bool(self, z, x): """Construct pauli from boolean array. Args: z (numpy.ndarray): boolean, z vector x (numpy.ndarray): boolean, x vector Returns: Pauli: self Raises: QiskitError: if z or x are None or the length of z and x are different. """ if z is None: raise QiskitError("z vector must not be None.") if x is None: raise QiskitError("x vector must not be None.") if len(z) != len(x): raise QiskitError("length of z and x vectors must be " "the same. (z: {} vs x: {})".format(len(z), len(x))) z = _make_np_bool(z) x = _make_np_bool(x) self._z = z self._x = x return self
[ "Construct", "pauli", "from", "boolean", "array", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/pauli.py#L112-L138
[ "def", "_init_from_bool", "(", "self", ",", "z", ",", "x", ")", ":", "if", "z", "is", "None", ":", "raise", "QiskitError", "(", "\"z vector must not be None.\"", ")", "if", "x", "is", "None", ":", "raise", "QiskitError", "(", "\"x vector must not be None.\"", ")", "if", "len", "(", "z", ")", "!=", "len", "(", "x", ")", ":", "raise", "QiskitError", "(", "\"length of z and x vectors must be \"", "\"the same. (z: {} vs x: {})\"", ".", "format", "(", "len", "(", "z", ")", ",", "len", "(", "x", ")", ")", ")", "z", "=", "_make_np_bool", "(", "z", ")", "x", "=", "_make_np_bool", "(", "x", ")", "self", ".", "_z", "=", "z", "self", ".", "_x", "=", "x", "return", "self" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Pauli.sgn_prod
r""" Multiply two Paulis and track the phase. $P_3 = P_1 \otimes P_2$: X*Y Args: p1 (Pauli): pauli 1 p2 (Pauli): pauli 2 Returns: Pauli: the multiplied pauli complex: the sign of the multiplication, 1, -1, 1j or -1j
qiskit/quantum_info/operators/pauli.py
def sgn_prod(p1, p2): r""" Multiply two Paulis and track the phase. $P_3 = P_1 \otimes P_2$: X*Y Args: p1 (Pauli): pauli 1 p2 (Pauli): pauli 2 Returns: Pauli: the multiplied pauli complex: the sign of the multiplication, 1, -1, 1j or -1j """ phase = Pauli._prod_phase(p1, p2) new_pauli = p1 * p2 return new_pauli, phase
def sgn_prod(p1, p2): r""" Multiply two Paulis and track the phase. $P_3 = P_1 \otimes P_2$: X*Y Args: p1 (Pauli): pauli 1 p2 (Pauli): pauli 2 Returns: Pauli: the multiplied pauli complex: the sign of the multiplication, 1, -1, 1j or -1j """ phase = Pauli._prod_phase(p1, p2) new_pauli = p1 * p2 return new_pauli, phase
[ "r", "Multiply", "two", "Paulis", "and", "track", "the", "phase", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/pauli.py#L228-L244
[ "def", "sgn_prod", "(", "p1", ",", "p2", ")", ":", "phase", "=", "Pauli", ".", "_prod_phase", "(", "p1", ",", "p2", ")", "new_pauli", "=", "p1", "*", "p2", "return", "new_pauli", ",", "phase" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Pauli.to_spmatrix
r""" Convert Pauli to a sparse matrix representation (CSR format). Order is q_{n-1} .... q_0, i.e., $P_{n-1} \otimes ... P_0$ Returns: scipy.sparse.csr_matrix: a sparse matrix with CSR format that represnets the pauli.
qiskit/quantum_info/operators/pauli.py
def to_spmatrix(self): r""" Convert Pauli to a sparse matrix representation (CSR format). Order is q_{n-1} .... q_0, i.e., $P_{n-1} \otimes ... P_0$ Returns: scipy.sparse.csr_matrix: a sparse matrix with CSR format that represnets the pauli. """ mat = sparse.coo_matrix(1) for z, x in zip(self._z, self._x): if not z and not x: # I mat = sparse.bmat([[mat, None], [None, mat]], format='coo') elif z and not x: # Z mat = sparse.bmat([[mat, None], [None, -mat]], format='coo') elif not z and x: # X mat = sparse.bmat([[None, mat], [mat, None]], format='coo') else: # Y mat = mat * 1j mat = sparse.bmat([[None, -mat], [mat, None]], format='coo') return mat.tocsr()
def to_spmatrix(self): r""" Convert Pauli to a sparse matrix representation (CSR format). Order is q_{n-1} .... q_0, i.e., $P_{n-1} \otimes ... P_0$ Returns: scipy.sparse.csr_matrix: a sparse matrix with CSR format that represnets the pauli. """ mat = sparse.coo_matrix(1) for z, x in zip(self._z, self._x): if not z and not x: # I mat = sparse.bmat([[mat, None], [None, mat]], format='coo') elif z and not x: # Z mat = sparse.bmat([[mat, None], [None, -mat]], format='coo') elif not z and x: # X mat = sparse.bmat([[None, mat], [mat, None]], format='coo') else: # Y mat = mat * 1j mat = sparse.bmat([[None, -mat], [mat, None]], format='coo') return mat.tocsr()
[ "r", "Convert", "Pauli", "to", "a", "sparse", "matrix", "representation", "(", "CSR", "format", ")", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/pauli.py#L273-L295
[ "def", "to_spmatrix", "(", "self", ")", ":", "mat", "=", "sparse", ".", "coo_matrix", "(", "1", ")", "for", "z", ",", "x", "in", "zip", "(", "self", ".", "_z", ",", "self", ".", "_x", ")", ":", "if", "not", "z", "and", "not", "x", ":", "# I", "mat", "=", "sparse", ".", "bmat", "(", "[", "[", "mat", ",", "None", "]", ",", "[", "None", ",", "mat", "]", "]", ",", "format", "=", "'coo'", ")", "elif", "z", "and", "not", "x", ":", "# Z", "mat", "=", "sparse", ".", "bmat", "(", "[", "[", "mat", ",", "None", "]", ",", "[", "None", ",", "-", "mat", "]", "]", ",", "format", "=", "'coo'", ")", "elif", "not", "z", "and", "x", ":", "# X", "mat", "=", "sparse", ".", "bmat", "(", "[", "[", "None", ",", "mat", "]", ",", "[", "mat", ",", "None", "]", "]", ",", "format", "=", "'coo'", ")", "else", ":", "# Y", "mat", "=", "mat", "*", "1j", "mat", "=", "sparse", ".", "bmat", "(", "[", "[", "None", ",", "-", "mat", "]", ",", "[", "mat", ",", "None", "]", "]", ",", "format", "=", "'coo'", ")", "return", "mat", ".", "tocsr", "(", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Pauli.to_operator
Convert to Operator object.
qiskit/quantum_info/operators/pauli.py
def to_operator(self): """Convert to Operator object.""" # Place import here to avoid cyclic import from circuit visualization from qiskit.quantum_info.operators.operator import Operator return Operator(self.to_matrix())
def to_operator(self): """Convert to Operator object.""" # Place import here to avoid cyclic import from circuit visualization from qiskit.quantum_info.operators.operator import Operator return Operator(self.to_matrix())
[ "Convert", "to", "Operator", "object", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/pauli.py#L297-L301
[ "def", "to_operator", "(", "self", ")", ":", "# Place import here to avoid cyclic import from circuit visualization", "from", "qiskit", ".", "quantum_info", ".", "operators", ".", "operator", "import", "Operator", "return", "Operator", "(", "self", ".", "to_matrix", "(", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Pauli.to_instruction
Convert to Pauli circuit instruction.
qiskit/quantum_info/operators/pauli.py
def to_instruction(self): """Convert to Pauli circuit instruction.""" from qiskit.circuit import QuantumCircuit, QuantumRegister from qiskit.extensions.standard import IdGate, XGate, YGate, ZGate gates = {'I': IdGate(), 'X': XGate(), 'Y': YGate(), 'Z': ZGate()} label = self.to_label() n_qubits = self.numberofqubits qreg = QuantumRegister(n_qubits) circuit = QuantumCircuit(qreg, name='Pauli:{}'.format(label)) for i, pauli in enumerate(reversed(label)): circuit.append(gates[pauli], [qreg[i]]) return circuit.to_instruction()
def to_instruction(self): """Convert to Pauli circuit instruction.""" from qiskit.circuit import QuantumCircuit, QuantumRegister from qiskit.extensions.standard import IdGate, XGate, YGate, ZGate gates = {'I': IdGate(), 'X': XGate(), 'Y': YGate(), 'Z': ZGate()} label = self.to_label() n_qubits = self.numberofqubits qreg = QuantumRegister(n_qubits) circuit = QuantumCircuit(qreg, name='Pauli:{}'.format(label)) for i, pauli in enumerate(reversed(label)): circuit.append(gates[pauli], [qreg[i]]) return circuit.to_instruction()
[ "Convert", "to", "Pauli", "circuit", "instruction", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/pauli.py#L303-L314
[ "def", "to_instruction", "(", "self", ")", ":", "from", "qiskit", ".", "circuit", "import", "QuantumCircuit", ",", "QuantumRegister", "from", "qiskit", ".", "extensions", ".", "standard", "import", "IdGate", ",", "XGate", ",", "YGate", ",", "ZGate", "gates", "=", "{", "'I'", ":", "IdGate", "(", ")", ",", "'X'", ":", "XGate", "(", ")", ",", "'Y'", ":", "YGate", "(", ")", ",", "'Z'", ":", "ZGate", "(", ")", "}", "label", "=", "self", ".", "to_label", "(", ")", "n_qubits", "=", "self", ".", "numberofqubits", "qreg", "=", "QuantumRegister", "(", "n_qubits", ")", "circuit", "=", "QuantumCircuit", "(", "qreg", ",", "name", "=", "'Pauli:{}'", ".", "format", "(", "label", ")", ")", "for", "i", ",", "pauli", "in", "enumerate", "(", "reversed", "(", "label", ")", ")", ":", "circuit", ".", "append", "(", "gates", "[", "pauli", "]", ",", "[", "qreg", "[", "i", "]", "]", ")", "return", "circuit", ".", "to_instruction", "(", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Pauli.update_z
Update partial or entire z. Args: z (numpy.ndarray or list): to-be-updated z indices (numpy.ndarray or list or optional): to-be-updated qubit indices Returns: Pauli: self Raises: QiskitError: when updating whole z, the number of qubits must be the same.
qiskit/quantum_info/operators/pauli.py
def update_z(self, z, indices=None): """ Update partial or entire z. Args: z (numpy.ndarray or list): to-be-updated z indices (numpy.ndarray or list or optional): to-be-updated qubit indices Returns: Pauli: self Raises: QiskitError: when updating whole z, the number of qubits must be the same. """ z = _make_np_bool(z) if indices is None: if len(self._z) != len(z): raise QiskitError("During updating whole z, you can not " "change the number of qubits.") self._z = z else: if not isinstance(indices, list) and not isinstance(indices, np.ndarray): indices = [indices] for p, idx in enumerate(indices): self._z[idx] = z[p] return self
def update_z(self, z, indices=None): """ Update partial or entire z. Args: z (numpy.ndarray or list): to-be-updated z indices (numpy.ndarray or list or optional): to-be-updated qubit indices Returns: Pauli: self Raises: QiskitError: when updating whole z, the number of qubits must be the same. """ z = _make_np_bool(z) if indices is None: if len(self._z) != len(z): raise QiskitError("During updating whole z, you can not " "change the number of qubits.") self._z = z else: if not isinstance(indices, list) and not isinstance(indices, np.ndarray): indices = [indices] for p, idx in enumerate(indices): self._z[idx] = z[p] return self
[ "Update", "partial", "or", "entire", "z", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/pauli.py#L316-L342
[ "def", "update_z", "(", "self", ",", "z", ",", "indices", "=", "None", ")", ":", "z", "=", "_make_np_bool", "(", "z", ")", "if", "indices", "is", "None", ":", "if", "len", "(", "self", ".", "_z", ")", "!=", "len", "(", "z", ")", ":", "raise", "QiskitError", "(", "\"During updating whole z, you can not \"", "\"change the number of qubits.\"", ")", "self", ".", "_z", "=", "z", "else", ":", "if", "not", "isinstance", "(", "indices", ",", "list", ")", "and", "not", "isinstance", "(", "indices", ",", "np", ".", "ndarray", ")", ":", "indices", "=", "[", "indices", "]", "for", "p", ",", "idx", "in", "enumerate", "(", "indices", ")", ":", "self", ".", "_z", "[", "idx", "]", "=", "z", "[", "p", "]", "return", "self" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Pauli.update_x
Update partial or entire x. Args: x (numpy.ndarray or list): to-be-updated x indices (numpy.ndarray or list or optional): to-be-updated qubit indices Returns: Pauli: self Raises: QiskitError: when updating whole x, the number of qubits must be the same.
qiskit/quantum_info/operators/pauli.py
def update_x(self, x, indices=None): """ Update partial or entire x. Args: x (numpy.ndarray or list): to-be-updated x indices (numpy.ndarray or list or optional): to-be-updated qubit indices Returns: Pauli: self Raises: QiskitError: when updating whole x, the number of qubits must be the same. """ x = _make_np_bool(x) if indices is None: if len(self._x) != len(x): raise QiskitError("During updating whole x, you can not change " "the number of qubits.") self._x = x else: if not isinstance(indices, list) and not isinstance(indices, np.ndarray): indices = [indices] for p, idx in enumerate(indices): self._x[idx] = x[p] return self
def update_x(self, x, indices=None): """ Update partial or entire x. Args: x (numpy.ndarray or list): to-be-updated x indices (numpy.ndarray or list or optional): to-be-updated qubit indices Returns: Pauli: self Raises: QiskitError: when updating whole x, the number of qubits must be the same. """ x = _make_np_bool(x) if indices is None: if len(self._x) != len(x): raise QiskitError("During updating whole x, you can not change " "the number of qubits.") self._x = x else: if not isinstance(indices, list) and not isinstance(indices, np.ndarray): indices = [indices] for p, idx in enumerate(indices): self._x[idx] = x[p] return self
[ "Update", "partial", "or", "entire", "x", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/pauli.py#L344-L370
[ "def", "update_x", "(", "self", ",", "x", ",", "indices", "=", "None", ")", ":", "x", "=", "_make_np_bool", "(", "x", ")", "if", "indices", "is", "None", ":", "if", "len", "(", "self", ".", "_x", ")", "!=", "len", "(", "x", ")", ":", "raise", "QiskitError", "(", "\"During updating whole x, you can not change \"", "\"the number of qubits.\"", ")", "self", ".", "_x", "=", "x", "else", ":", "if", "not", "isinstance", "(", "indices", ",", "list", ")", "and", "not", "isinstance", "(", "indices", ",", "np", ".", "ndarray", ")", ":", "indices", "=", "[", "indices", "]", "for", "p", ",", "idx", "in", "enumerate", "(", "indices", ")", ":", "self", ".", "_x", "[", "idx", "]", "=", "x", "[", "p", "]", "return", "self" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Pauli.insert_paulis
Insert or append pauli to the targeted indices. If indices is None, it means append at the end. Args: indices (list[int]): the qubit indices to be inserted paulis (Pauli): the to-be-inserted or appended pauli pauli_labels (list[str]): the to-be-inserted or appended pauli label Note: the indices refers to the localion of original paulis, e.g. if indices = [0, 2], pauli_labels = ['Z', 'I'] and original pauli = 'ZYXI' the pauli will be updated to ZY'I'XI'Z' 'Z' and 'I' are inserted before the qubit at 0 and 2. Returns: Pauli: self Raises: QiskitError: provide both `paulis` and `pauli_labels` at the same time
qiskit/quantum_info/operators/pauli.py
def insert_paulis(self, indices=None, paulis=None, pauli_labels=None): """ Insert or append pauli to the targeted indices. If indices is None, it means append at the end. Args: indices (list[int]): the qubit indices to be inserted paulis (Pauli): the to-be-inserted or appended pauli pauli_labels (list[str]): the to-be-inserted or appended pauli label Note: the indices refers to the localion of original paulis, e.g. if indices = [0, 2], pauli_labels = ['Z', 'I'] and original pauli = 'ZYXI' the pauli will be updated to ZY'I'XI'Z' 'Z' and 'I' are inserted before the qubit at 0 and 2. Returns: Pauli: self Raises: QiskitError: provide both `paulis` and `pauli_labels` at the same time """ if pauli_labels is not None: if paulis is not None: raise QiskitError("Please only provide either `paulis` or `pauli_labels`") if isinstance(pauli_labels, str): pauli_labels = list(pauli_labels) # since pauli label is in reversed order. paulis = Pauli.from_label(pauli_labels[::-1]) if indices is None: # append self._z = np.concatenate((self._z, paulis.z)) self._x = np.concatenate((self._x, paulis.x)) else: if not isinstance(indices, list): indices = [indices] self._z = np.insert(self._z, indices, paulis.z) self._x = np.insert(self._x, indices, paulis.x) return self
def insert_paulis(self, indices=None, paulis=None, pauli_labels=None): """ Insert or append pauli to the targeted indices. If indices is None, it means append at the end. Args: indices (list[int]): the qubit indices to be inserted paulis (Pauli): the to-be-inserted or appended pauli pauli_labels (list[str]): the to-be-inserted or appended pauli label Note: the indices refers to the localion of original paulis, e.g. if indices = [0, 2], pauli_labels = ['Z', 'I'] and original pauli = 'ZYXI' the pauli will be updated to ZY'I'XI'Z' 'Z' and 'I' are inserted before the qubit at 0 and 2. Returns: Pauli: self Raises: QiskitError: provide both `paulis` and `pauli_labels` at the same time """ if pauli_labels is not None: if paulis is not None: raise QiskitError("Please only provide either `paulis` or `pauli_labels`") if isinstance(pauli_labels, str): pauli_labels = list(pauli_labels) # since pauli label is in reversed order. paulis = Pauli.from_label(pauli_labels[::-1]) if indices is None: # append self._z = np.concatenate((self._z, paulis.z)) self._x = np.concatenate((self._x, paulis.x)) else: if not isinstance(indices, list): indices = [indices] self._z = np.insert(self._z, indices, paulis.z) self._x = np.insert(self._x, indices, paulis.x) return self
[ "Insert", "or", "append", "pauli", "to", "the", "targeted", "indices", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/pauli.py#L372-L412
[ "def", "insert_paulis", "(", "self", ",", "indices", "=", "None", ",", "paulis", "=", "None", ",", "pauli_labels", "=", "None", ")", ":", "if", "pauli_labels", "is", "not", "None", ":", "if", "paulis", "is", "not", "None", ":", "raise", "QiskitError", "(", "\"Please only provide either `paulis` or `pauli_labels`\"", ")", "if", "isinstance", "(", "pauli_labels", ",", "str", ")", ":", "pauli_labels", "=", "list", "(", "pauli_labels", ")", "# since pauli label is in reversed order.", "paulis", "=", "Pauli", ".", "from_label", "(", "pauli_labels", "[", ":", ":", "-", "1", "]", ")", "if", "indices", "is", "None", ":", "# append", "self", ".", "_z", "=", "np", ".", "concatenate", "(", "(", "self", ".", "_z", ",", "paulis", ".", "z", ")", ")", "self", ".", "_x", "=", "np", ".", "concatenate", "(", "(", "self", ".", "_x", ",", "paulis", ".", "x", ")", ")", "else", ":", "if", "not", "isinstance", "(", "indices", ",", "list", ")", ":", "indices", "=", "[", "indices", "]", "self", ".", "_z", "=", "np", ".", "insert", "(", "self", ".", "_z", ",", "indices", ",", "paulis", ".", "z", ")", "self", ".", "_x", "=", "np", ".", "insert", "(", "self", ".", "_x", ",", "indices", ",", "paulis", ".", "x", ")", "return", "self" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Pauli.append_paulis
Append pauli at the end. Args: paulis (Pauli): the to-be-inserted or appended pauli pauli_labels (list[str]): the to-be-inserted or appended pauli label Returns: Pauli: self
qiskit/quantum_info/operators/pauli.py
def append_paulis(self, paulis=None, pauli_labels=None): """ Append pauli at the end. Args: paulis (Pauli): the to-be-inserted or appended pauli pauli_labels (list[str]): the to-be-inserted or appended pauli label Returns: Pauli: self """ return self.insert_paulis(None, paulis=paulis, pauli_labels=pauli_labels)
def append_paulis(self, paulis=None, pauli_labels=None): """ Append pauli at the end. Args: paulis (Pauli): the to-be-inserted or appended pauli pauli_labels (list[str]): the to-be-inserted or appended pauli label Returns: Pauli: self """ return self.insert_paulis(None, paulis=paulis, pauli_labels=pauli_labels)
[ "Append", "pauli", "at", "the", "end", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/pauli.py#L414-L425
[ "def", "append_paulis", "(", "self", ",", "paulis", "=", "None", ",", "pauli_labels", "=", "None", ")", ":", "return", "self", ".", "insert_paulis", "(", "None", ",", "paulis", "=", "paulis", ",", "pauli_labels", "=", "pauli_labels", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Pauli.delete_qubits
Delete pauli at the indices. Args: indices(list[int]): the indices of to-be-deleted paulis Returns: Pauli: self
qiskit/quantum_info/operators/pauli.py
def delete_qubits(self, indices): """ Delete pauli at the indices. Args: indices(list[int]): the indices of to-be-deleted paulis Returns: Pauli: self """ if not isinstance(indices, list): indices = [indices] self._z = np.delete(self._z, indices) self._x = np.delete(self._x, indices) return self
def delete_qubits(self, indices): """ Delete pauli at the indices. Args: indices(list[int]): the indices of to-be-deleted paulis Returns: Pauli: self """ if not isinstance(indices, list): indices = [indices] self._z = np.delete(self._z, indices) self._x = np.delete(self._x, indices) return self
[ "Delete", "pauli", "at", "the", "indices", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/pauli.py#L427-L443
[ "def", "delete_qubits", "(", "self", ",", "indices", ")", ":", "if", "not", "isinstance", "(", "indices", ",", "list", ")", ":", "indices", "=", "[", "indices", "]", "self", ".", "_z", "=", "np", ".", "delete", "(", "self", ".", "_z", ",", "indices", ")", "self", ".", "_x", "=", "np", ".", "delete", "(", "self", ".", "_x", ",", "indices", ")", "return", "self" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Pauli.random
Return a random Pauli on number of qubits. Args: num_qubits (int): the number of qubits seed (int): Optional. To set a random seed. Returns: Pauli: the random pauli
qiskit/quantum_info/operators/pauli.py
def random(cls, num_qubits, seed=None): """Return a random Pauli on number of qubits. Args: num_qubits (int): the number of qubits seed (int): Optional. To set a random seed. Returns: Pauli: the random pauli """ if seed is not None: np.random.seed(seed) z = np.random.randint(2, size=num_qubits).astype(np.bool) x = np.random.randint(2, size=num_qubits).astype(np.bool) return cls(z, x)
def random(cls, num_qubits, seed=None): """Return a random Pauli on number of qubits. Args: num_qubits (int): the number of qubits seed (int): Optional. To set a random seed. Returns: Pauli: the random pauli """ if seed is not None: np.random.seed(seed) z = np.random.randint(2, size=num_qubits).astype(np.bool) x = np.random.randint(2, size=num_qubits).astype(np.bool) return cls(z, x)
[ "Return", "a", "random", "Pauli", "on", "number", "of", "qubits", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/pauli.py#L446-L459
[ "def", "random", "(", "cls", ",", "num_qubits", ",", "seed", "=", "None", ")", ":", "if", "seed", "is", "not", "None", ":", "np", ".", "random", ".", "seed", "(", "seed", ")", "z", "=", "np", ".", "random", ".", "randint", "(", "2", ",", "size", "=", "num_qubits", ")", ".", "astype", "(", "np", ".", "bool", ")", "x", "=", "np", ".", "random", ".", "randint", "(", "2", ",", "size", "=", "num_qubits", ")", ".", "astype", "(", "np", ".", "bool", ")", "return", "cls", "(", "z", ",", "x", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Pauli.pauli_single
Generate single qubit pauli at index with pauli_label with length num_qubits. Args: num_qubits (int): the length of pauli index (int): the qubit index to insert the single qubii pauli_label (str): pauli Returns: Pauli: single qubit pauli
qiskit/quantum_info/operators/pauli.py
def pauli_single(cls, num_qubits, index, pauli_label): """ Generate single qubit pauli at index with pauli_label with length num_qubits. Args: num_qubits (int): the length of pauli index (int): the qubit index to insert the single qubii pauli_label (str): pauli Returns: Pauli: single qubit pauli """ tmp = Pauli.from_label(pauli_label) z = np.zeros(num_qubits, dtype=np.bool) x = np.zeros(num_qubits, dtype=np.bool) z[index] = tmp.z[0] x[index] = tmp.x[0] return cls(z, x)
def pauli_single(cls, num_qubits, index, pauli_label): """ Generate single qubit pauli at index with pauli_label with length num_qubits. Args: num_qubits (int): the length of pauli index (int): the qubit index to insert the single qubii pauli_label (str): pauli Returns: Pauli: single qubit pauli """ tmp = Pauli.from_label(pauli_label) z = np.zeros(num_qubits, dtype=np.bool) x = np.zeros(num_qubits, dtype=np.bool) z[index] = tmp.z[0] x[index] = tmp.x[0] return cls(z, x)
[ "Generate", "single", "qubit", "pauli", "at", "index", "with", "pauli_label", "with", "length", "num_qubits", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/pauli.py#L462-L481
[ "def", "pauli_single", "(", "cls", ",", "num_qubits", ",", "index", ",", "pauli_label", ")", ":", "tmp", "=", "Pauli", ".", "from_label", "(", "pauli_label", ")", "z", "=", "np", ".", "zeros", "(", "num_qubits", ",", "dtype", "=", "np", ".", "bool", ")", "x", "=", "np", ".", "zeros", "(", "num_qubits", ",", "dtype", "=", "np", ".", "bool", ")", "z", "[", "index", "]", "=", "tmp", ".", "z", "[", "0", "]", "x", "[", "index", "]", "=", "tmp", ".", "x", "[", "0", "]", "return", "cls", "(", "z", ",", "x", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QasmSimulatorPy._add_unitary_single
Apply an arbitrary 1-qubit unitary matrix. Args: gate (matrix_like): a single qubit gate matrix qubit (int): the qubit to apply gate to
qiskit/providers/basicaer/qasm_simulator.py
def _add_unitary_single(self, gate, qubit): """Apply an arbitrary 1-qubit unitary matrix. Args: gate (matrix_like): a single qubit gate matrix qubit (int): the qubit to apply gate to """ # Compute einsum index string for 1-qubit matrix multiplication indexes = einsum_vecmul_index([qubit], self._number_of_qubits) # Convert to complex rank-2 tensor gate_tensor = np.array(gate, dtype=complex) # Apply matrix multiplication self._statevector = np.einsum(indexes, gate_tensor, self._statevector, dtype=complex, casting='no')
def _add_unitary_single(self, gate, qubit): """Apply an arbitrary 1-qubit unitary matrix. Args: gate (matrix_like): a single qubit gate matrix qubit (int): the qubit to apply gate to """ # Compute einsum index string for 1-qubit matrix multiplication indexes = einsum_vecmul_index([qubit], self._number_of_qubits) # Convert to complex rank-2 tensor gate_tensor = np.array(gate, dtype=complex) # Apply matrix multiplication self._statevector = np.einsum(indexes, gate_tensor, self._statevector, dtype=complex, casting='no')
[ "Apply", "an", "arbitrary", "1", "-", "qubit", "unitary", "matrix", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/qasm_simulator.py#L130-L145
[ "def", "_add_unitary_single", "(", "self", ",", "gate", ",", "qubit", ")", ":", "# Compute einsum index string for 1-qubit matrix multiplication", "indexes", "=", "einsum_vecmul_index", "(", "[", "qubit", "]", ",", "self", ".", "_number_of_qubits", ")", "# Convert to complex rank-2 tensor", "gate_tensor", "=", "np", ".", "array", "(", "gate", ",", "dtype", "=", "complex", ")", "# Apply matrix multiplication", "self", ".", "_statevector", "=", "np", ".", "einsum", "(", "indexes", ",", "gate_tensor", ",", "self", ".", "_statevector", ",", "dtype", "=", "complex", ",", "casting", "=", "'no'", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QasmSimulatorPy._add_unitary_two
Apply a two-qubit unitary matrix. Args: gate (matrix_like): a the two-qubit gate matrix qubit0 (int): gate qubit-0 qubit1 (int): gate qubit-1
qiskit/providers/basicaer/qasm_simulator.py
def _add_unitary_two(self, gate, qubit0, qubit1): """Apply a two-qubit unitary matrix. Args: gate (matrix_like): a the two-qubit gate matrix qubit0 (int): gate qubit-0 qubit1 (int): gate qubit-1 """ # Compute einsum index string for 1-qubit matrix multiplication indexes = einsum_vecmul_index([qubit0, qubit1], self._number_of_qubits) # Convert to complex rank-4 tensor gate_tensor = np.reshape(np.array(gate, dtype=complex), 4 * [2]) # Apply matrix multiplication self._statevector = np.einsum(indexes, gate_tensor, self._statevector, dtype=complex, casting='no')
def _add_unitary_two(self, gate, qubit0, qubit1): """Apply a two-qubit unitary matrix. Args: gate (matrix_like): a the two-qubit gate matrix qubit0 (int): gate qubit-0 qubit1 (int): gate qubit-1 """ # Compute einsum index string for 1-qubit matrix multiplication indexes = einsum_vecmul_index([qubit0, qubit1], self._number_of_qubits) # Convert to complex rank-4 tensor gate_tensor = np.reshape(np.array(gate, dtype=complex), 4 * [2]) # Apply matrix multiplication self._statevector = np.einsum(indexes, gate_tensor, self._statevector, dtype=complex, casting='no')
[ "Apply", "a", "two", "-", "qubit", "unitary", "matrix", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/qasm_simulator.py#L147-L163
[ "def", "_add_unitary_two", "(", "self", ",", "gate", ",", "qubit0", ",", "qubit1", ")", ":", "# Compute einsum index string for 1-qubit matrix multiplication", "indexes", "=", "einsum_vecmul_index", "(", "[", "qubit0", ",", "qubit1", "]", ",", "self", ".", "_number_of_qubits", ")", "# Convert to complex rank-4 tensor", "gate_tensor", "=", "np", ".", "reshape", "(", "np", ".", "array", "(", "gate", ",", "dtype", "=", "complex", ")", ",", "4", "*", "[", "2", "]", ")", "# Apply matrix multiplication", "self", ".", "_statevector", "=", "np", ".", "einsum", "(", "indexes", ",", "gate_tensor", ",", "self", ".", "_statevector", ",", "dtype", "=", "complex", ",", "casting", "=", "'no'", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QasmSimulatorPy._get_measure_outcome
Simulate the outcome of measurement of a qubit. Args: qubit (int): the qubit to measure Return: tuple: pair (outcome, probability) where outcome is '0' or '1' and probability is the probability of the returned outcome.
qiskit/providers/basicaer/qasm_simulator.py
def _get_measure_outcome(self, qubit): """Simulate the outcome of measurement of a qubit. Args: qubit (int): the qubit to measure Return: tuple: pair (outcome, probability) where outcome is '0' or '1' and probability is the probability of the returned outcome. """ # Axis for numpy.sum to compute probabilities axis = list(range(self._number_of_qubits)) axis.remove(self._number_of_qubits - 1 - qubit) probabilities = np.sum(np.abs(self._statevector) ** 2, axis=tuple(axis)) # Compute einsum index string for 1-qubit matrix multiplication random_number = self._local_random.rand() if random_number < probabilities[0]: return '0', probabilities[0] # Else outcome was '1' return '1', probabilities[1]
def _get_measure_outcome(self, qubit): """Simulate the outcome of measurement of a qubit. Args: qubit (int): the qubit to measure Return: tuple: pair (outcome, probability) where outcome is '0' or '1' and probability is the probability of the returned outcome. """ # Axis for numpy.sum to compute probabilities axis = list(range(self._number_of_qubits)) axis.remove(self._number_of_qubits - 1 - qubit) probabilities = np.sum(np.abs(self._statevector) ** 2, axis=tuple(axis)) # Compute einsum index string for 1-qubit matrix multiplication random_number = self._local_random.rand() if random_number < probabilities[0]: return '0', probabilities[0] # Else outcome was '1' return '1', probabilities[1]
[ "Simulate", "the", "outcome", "of", "measurement", "of", "a", "qubit", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/qasm_simulator.py#L165-L184
[ "def", "_get_measure_outcome", "(", "self", ",", "qubit", ")", ":", "# Axis for numpy.sum to compute probabilities", "axis", "=", "list", "(", "range", "(", "self", ".", "_number_of_qubits", ")", ")", "axis", ".", "remove", "(", "self", ".", "_number_of_qubits", "-", "1", "-", "qubit", ")", "probabilities", "=", "np", ".", "sum", "(", "np", ".", "abs", "(", "self", ".", "_statevector", ")", "**", "2", ",", "axis", "=", "tuple", "(", "axis", ")", ")", "# Compute einsum index string for 1-qubit matrix multiplication", "random_number", "=", "self", ".", "_local_random", ".", "rand", "(", ")", "if", "random_number", "<", "probabilities", "[", "0", "]", ":", "return", "'0'", ",", "probabilities", "[", "0", "]", "# Else outcome was '1'", "return", "'1'", ",", "probabilities", "[", "1", "]" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QasmSimulatorPy._add_sample_measure
Generate memory samples from current statevector. Args: measure_params (list): List of (qubit, cmembit) values for measure instructions to sample. num_samples (int): The number of memory samples to generate. Returns: list: A list of memory values in hex format.
qiskit/providers/basicaer/qasm_simulator.py
def _add_sample_measure(self, measure_params, num_samples): """Generate memory samples from current statevector. Args: measure_params (list): List of (qubit, cmembit) values for measure instructions to sample. num_samples (int): The number of memory samples to generate. Returns: list: A list of memory values in hex format. """ # Get unique qubits that are actually measured measured_qubits = list({qubit for qubit, cmembit in measure_params}) num_measured = len(measured_qubits) # Axis for numpy.sum to compute probabilities axis = list(range(self._number_of_qubits)) for qubit in reversed(measured_qubits): # Remove from largest qubit to smallest so list position is correct # with respect to position from end of the list axis.remove(self._number_of_qubits - 1 - qubit) probabilities = np.reshape(np.sum(np.abs(self._statevector) ** 2, axis=tuple(axis)), 2 ** num_measured) # Generate samples on measured qubits samples = self._local_random.choice(range(2 ** num_measured), num_samples, p=probabilities) # Convert to bit-strings memory = [] for sample in samples: classical_memory = self._classical_memory for count, (qubit, cmembit) in enumerate(sorted(measure_params)): qubit_outcome = int((sample & (1 << count)) >> count) membit = 1 << cmembit classical_memory = (classical_memory & (~membit)) | (qubit_outcome << cmembit) value = bin(classical_memory)[2:] memory.append(hex(int(value, 2))) return memory
def _add_sample_measure(self, measure_params, num_samples): """Generate memory samples from current statevector. Args: measure_params (list): List of (qubit, cmembit) values for measure instructions to sample. num_samples (int): The number of memory samples to generate. Returns: list: A list of memory values in hex format. """ # Get unique qubits that are actually measured measured_qubits = list({qubit for qubit, cmembit in measure_params}) num_measured = len(measured_qubits) # Axis for numpy.sum to compute probabilities axis = list(range(self._number_of_qubits)) for qubit in reversed(measured_qubits): # Remove from largest qubit to smallest so list position is correct # with respect to position from end of the list axis.remove(self._number_of_qubits - 1 - qubit) probabilities = np.reshape(np.sum(np.abs(self._statevector) ** 2, axis=tuple(axis)), 2 ** num_measured) # Generate samples on measured qubits samples = self._local_random.choice(range(2 ** num_measured), num_samples, p=probabilities) # Convert to bit-strings memory = [] for sample in samples: classical_memory = self._classical_memory for count, (qubit, cmembit) in enumerate(sorted(measure_params)): qubit_outcome = int((sample & (1 << count)) >> count) membit = 1 << cmembit classical_memory = (classical_memory & (~membit)) | (qubit_outcome << cmembit) value = bin(classical_memory)[2:] memory.append(hex(int(value, 2))) return memory
[ "Generate", "memory", "samples", "from", "current", "statevector", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/qasm_simulator.py#L186-L222
[ "def", "_add_sample_measure", "(", "self", ",", "measure_params", ",", "num_samples", ")", ":", "# Get unique qubits that are actually measured", "measured_qubits", "=", "list", "(", "{", "qubit", "for", "qubit", ",", "cmembit", "in", "measure_params", "}", ")", "num_measured", "=", "len", "(", "measured_qubits", ")", "# Axis for numpy.sum to compute probabilities", "axis", "=", "list", "(", "range", "(", "self", ".", "_number_of_qubits", ")", ")", "for", "qubit", "in", "reversed", "(", "measured_qubits", ")", ":", "# Remove from largest qubit to smallest so list position is correct", "# with respect to position from end of the list", "axis", ".", "remove", "(", "self", ".", "_number_of_qubits", "-", "1", "-", "qubit", ")", "probabilities", "=", "np", ".", "reshape", "(", "np", ".", "sum", "(", "np", ".", "abs", "(", "self", ".", "_statevector", ")", "**", "2", ",", "axis", "=", "tuple", "(", "axis", ")", ")", ",", "2", "**", "num_measured", ")", "# Generate samples on measured qubits", "samples", "=", "self", ".", "_local_random", ".", "choice", "(", "range", "(", "2", "**", "num_measured", ")", ",", "num_samples", ",", "p", "=", "probabilities", ")", "# Convert to bit-strings", "memory", "=", "[", "]", "for", "sample", "in", "samples", ":", "classical_memory", "=", "self", ".", "_classical_memory", "for", "count", ",", "(", "qubit", ",", "cmembit", ")", "in", "enumerate", "(", "sorted", "(", "measure_params", ")", ")", ":", "qubit_outcome", "=", "int", "(", "(", "sample", "&", "(", "1", "<<", "count", ")", ")", ">>", "count", ")", "membit", "=", "1", "<<", "cmembit", "classical_memory", "=", "(", "classical_memory", "&", "(", "~", "membit", ")", ")", "|", "(", "qubit_outcome", "<<", "cmembit", ")", "value", "=", "bin", "(", "classical_memory", ")", "[", "2", ":", "]", "memory", ".", "append", "(", "hex", "(", "int", "(", "value", ",", "2", ")", ")", ")", "return", "memory" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QasmSimulatorPy._add_qasm_measure
Apply a measure instruction to a qubit. Args: qubit (int): qubit is the qubit measured. cmembit (int): is the classical memory bit to store outcome in. cregbit (int, optional): is the classical register bit to store outcome in.
qiskit/providers/basicaer/qasm_simulator.py
def _add_qasm_measure(self, qubit, cmembit, cregbit=None): """Apply a measure instruction to a qubit. Args: qubit (int): qubit is the qubit measured. cmembit (int): is the classical memory bit to store outcome in. cregbit (int, optional): is the classical register bit to store outcome in. """ # get measure outcome outcome, probability = self._get_measure_outcome(qubit) # update classical state membit = 1 << cmembit self._classical_memory = (self._classical_memory & (~membit)) | (int(outcome) << cmembit) if cregbit is not None: regbit = 1 << cregbit self._classical_register = \ (self._classical_register & (~regbit)) | (int(outcome) << cregbit) # update quantum state if outcome == '0': update_diag = [[1 / np.sqrt(probability), 0], [0, 0]] else: update_diag = [[0, 0], [0, 1 / np.sqrt(probability)]] # update classical state self._add_unitary_single(update_diag, qubit)
def _add_qasm_measure(self, qubit, cmembit, cregbit=None): """Apply a measure instruction to a qubit. Args: qubit (int): qubit is the qubit measured. cmembit (int): is the classical memory bit to store outcome in. cregbit (int, optional): is the classical register bit to store outcome in. """ # get measure outcome outcome, probability = self._get_measure_outcome(qubit) # update classical state membit = 1 << cmembit self._classical_memory = (self._classical_memory & (~membit)) | (int(outcome) << cmembit) if cregbit is not None: regbit = 1 << cregbit self._classical_register = \ (self._classical_register & (~regbit)) | (int(outcome) << cregbit) # update quantum state if outcome == '0': update_diag = [[1 / np.sqrt(probability), 0], [0, 0]] else: update_diag = [[0, 0], [0, 1 / np.sqrt(probability)]] # update classical state self._add_unitary_single(update_diag, qubit)
[ "Apply", "a", "measure", "instruction", "to", "a", "qubit", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/qasm_simulator.py#L224-L249
[ "def", "_add_qasm_measure", "(", "self", ",", "qubit", ",", "cmembit", ",", "cregbit", "=", "None", ")", ":", "# get measure outcome", "outcome", ",", "probability", "=", "self", ".", "_get_measure_outcome", "(", "qubit", ")", "# update classical state", "membit", "=", "1", "<<", "cmembit", "self", ".", "_classical_memory", "=", "(", "self", ".", "_classical_memory", "&", "(", "~", "membit", ")", ")", "|", "(", "int", "(", "outcome", ")", "<<", "cmembit", ")", "if", "cregbit", "is", "not", "None", ":", "regbit", "=", "1", "<<", "cregbit", "self", ".", "_classical_register", "=", "(", "self", ".", "_classical_register", "&", "(", "~", "regbit", ")", ")", "|", "(", "int", "(", "outcome", ")", "<<", "cregbit", ")", "# update quantum state", "if", "outcome", "==", "'0'", ":", "update_diag", "=", "[", "[", "1", "/", "np", ".", "sqrt", "(", "probability", ")", ",", "0", "]", ",", "[", "0", ",", "0", "]", "]", "else", ":", "update_diag", "=", "[", "[", "0", ",", "0", "]", ",", "[", "0", ",", "1", "/", "np", ".", "sqrt", "(", "probability", ")", "]", "]", "# update classical state", "self", ".", "_add_unitary_single", "(", "update_diag", ",", "qubit", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1