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
purity
Calculate the purity of a quantum state. Args: state (ndarray): a quantum state Returns: float: purity.
qiskit/quantum_info/states/states.py
def purity(state): """Calculate the purity of a quantum state. Args: state (ndarray): a quantum state Returns: float: purity. """ rho = np.array(state) if rho.ndim == 1: return 1.0 return np.real(np.trace(rho.dot(rho)))
def purity(state): """Calculate the purity of a quantum state. Args: state (ndarray): a quantum state Returns: float: purity. """ rho = np.array(state) if rho.ndim == 1: return 1.0 return np.real(np.trace(rho.dot(rho)))
[ "Calculate", "the", "purity", "of", "a", "quantum", "state", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/states/states.py#L60-L71
[ "def", "purity", "(", "state", ")", ":", "rho", "=", "np", ".", "array", "(", "state", ")", "if", "rho", ".", "ndim", "==", "1", ":", "return", "1.0", "return", "np", ".", "real", "(", "np", ".", "trace", "(", "rho", ".", "dot", "(", "rho", ")", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Gate.qasm
Return the corresponding OPENQASM string.
qiskit/qasm/node/gate.py
def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" string = "gate " + self.name if self.arguments is not None: string += "(" + self.arguments.qasm(prec) + ")" string += " " + self.bitlist.qasm(prec) + "\n" string += "{\n" + self.body.qasm(prec) + "}" return string
def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" string = "gate " + self.name if self.arguments is not None: string += "(" + self.arguments.qasm(prec) + ")" string += " " + self.bitlist.qasm(prec) + "\n" string += "{\n" + self.body.qasm(prec) + "}" return string
[ "Return", "the", "corresponding", "OPENQASM", "string", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/node/gate.py#L53-L60
[ "def", "qasm", "(", "self", ",", "prec", "=", "15", ")", ":", "string", "=", "\"gate \"", "+", "self", ".", "name", "if", "self", ".", "arguments", "is", "not", "None", ":", "string", "+=", "\"(\"", "+", "self", ".", "arguments", ".", "qasm", "(", "prec", ")", "+", "\")\"", "string", "+=", "\" \"", "+", "self", ".", "bitlist", ".", "qasm", "(", "prec", ")", "+", "\"\\n\"", "string", "+=", "\"{\\n\"", "+", "self", ".", "body", ".", "qasm", "(", "prec", ")", "+", "\"}\"", "return", "string" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
CommutationAnalysis.run
Run the pass on the DAG, and write the discovered commutation relations into the property_set.
qiskit/transpiler/passes/commutation_analysis.py
def run(self, dag): """ Run the pass on the DAG, and write the discovered commutation relations into the property_set. """ # Initiate the commutation set self.property_set['commutation_set'] = defaultdict(list) # Build a dictionary to keep track of the gates on each qubit for wire in dag.wires: wire_name = "{0}[{1}]".format(str(wire[0].name), str(wire[1])) self.property_set['commutation_set'][wire_name] = [] # Add edges to the dictionary for each qubit for node in dag.topological_op_nodes(): for (_, _, edge_data) in dag.edges(node): edge_name = edge_data['name'] self.property_set['commutation_set'][(node, edge_name)] = -1 for wire in dag.wires: wire_name = "{0}[{1}]".format(str(wire[0].name), str(wire[1])) for current_gate in dag.nodes_on_wire(wire): current_comm_set = self.property_set['commutation_set'][wire_name] if not current_comm_set: current_comm_set.append([current_gate]) if current_gate not in current_comm_set[-1]: prev_gate = current_comm_set[-1][-1] if _commute(current_gate, prev_gate): current_comm_set[-1].append(current_gate) else: current_comm_set.append([current_gate]) temp_len = len(current_comm_set) self.property_set['commutation_set'][(current_gate, wire_name)] = temp_len - 1
def run(self, dag): """ Run the pass on the DAG, and write the discovered commutation relations into the property_set. """ # Initiate the commutation set self.property_set['commutation_set'] = defaultdict(list) # Build a dictionary to keep track of the gates on each qubit for wire in dag.wires: wire_name = "{0}[{1}]".format(str(wire[0].name), str(wire[1])) self.property_set['commutation_set'][wire_name] = [] # Add edges to the dictionary for each qubit for node in dag.topological_op_nodes(): for (_, _, edge_data) in dag.edges(node): edge_name = edge_data['name'] self.property_set['commutation_set'][(node, edge_name)] = -1 for wire in dag.wires: wire_name = "{0}[{1}]".format(str(wire[0].name), str(wire[1])) for current_gate in dag.nodes_on_wire(wire): current_comm_set = self.property_set['commutation_set'][wire_name] if not current_comm_set: current_comm_set.append([current_gate]) if current_gate not in current_comm_set[-1]: prev_gate = current_comm_set[-1][-1] if _commute(current_gate, prev_gate): current_comm_set[-1].append(current_gate) else: current_comm_set.append([current_gate]) temp_len = len(current_comm_set) self.property_set['commutation_set'][(current_gate, wire_name)] = temp_len - 1
[ "Run", "the", "pass", "on", "the", "DAG", "and", "write", "the", "discovered", "commutation", "relations", "into", "the", "property_set", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/commutation_analysis.py#L38-L76
[ "def", "run", "(", "self", ",", "dag", ")", ":", "# Initiate the commutation set", "self", ".", "property_set", "[", "'commutation_set'", "]", "=", "defaultdict", "(", "list", ")", "# Build a dictionary to keep track of the gates on each qubit", "for", "wire", "in", "dag", ".", "wires", ":", "wire_name", "=", "\"{0}[{1}]\"", ".", "format", "(", "str", "(", "wire", "[", "0", "]", ".", "name", ")", ",", "str", "(", "wire", "[", "1", "]", ")", ")", "self", ".", "property_set", "[", "'commutation_set'", "]", "[", "wire_name", "]", "=", "[", "]", "# Add edges to the dictionary for each qubit", "for", "node", "in", "dag", ".", "topological_op_nodes", "(", ")", ":", "for", "(", "_", ",", "_", ",", "edge_data", ")", "in", "dag", ".", "edges", "(", "node", ")", ":", "edge_name", "=", "edge_data", "[", "'name'", "]", "self", ".", "property_set", "[", "'commutation_set'", "]", "[", "(", "node", ",", "edge_name", ")", "]", "=", "-", "1", "for", "wire", "in", "dag", ".", "wires", ":", "wire_name", "=", "\"{0}[{1}]\"", ".", "format", "(", "str", "(", "wire", "[", "0", "]", ".", "name", ")", ",", "str", "(", "wire", "[", "1", "]", ")", ")", "for", "current_gate", "in", "dag", ".", "nodes_on_wire", "(", "wire", ")", ":", "current_comm_set", "=", "self", ".", "property_set", "[", "'commutation_set'", "]", "[", "wire_name", "]", "if", "not", "current_comm_set", ":", "current_comm_set", ".", "append", "(", "[", "current_gate", "]", ")", "if", "current_gate", "not", "in", "current_comm_set", "[", "-", "1", "]", ":", "prev_gate", "=", "current_comm_set", "[", "-", "1", "]", "[", "-", "1", "]", "if", "_commute", "(", "current_gate", ",", "prev_gate", ")", ":", "current_comm_set", "[", "-", "1", "]", ".", "append", "(", "current_gate", ")", "else", ":", "current_comm_set", ".", "append", "(", "[", "current_gate", "]", ")", "temp_len", "=", "len", "(", "current_comm_set", ")", "self", ".", "property_set", "[", "'commutation_set'", "]", "[", "(", "current_gate", ",", "wire_name", ")", "]", "=", "temp_len", "-", "1" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
backend_widget
Creates a backend widget.
qiskit/tools/jupyter/backend_overview.py
def backend_widget(backend): """Creates a backend widget. """ config = backend.configuration().to_dict() props = backend.properties().to_dict() name = widgets.HTML(value="<h4>{name}</h4>".format(name=backend.name()), layout=widgets.Layout()) n_qubits = config['n_qubits'] qubit_count = widgets.HTML(value="<h5><b>{qubits}</b></h5>".format(qubits=n_qubits), layout=widgets.Layout(justify_content='center')) cmap = widgets.Output(layout=widgets.Layout(min_width='250px', max_width='250px', max_height='250px', min_height='250px', justify_content='center', align_items='center', margin='0px 0px 0px 0px')) with cmap: _cmap_fig = plot_gate_map(backend, plot_directed=False, label_qubits=False) if _cmap_fig is not None: display(_cmap_fig) # Prevents plot from showing up twice. plt.close(_cmap_fig) pending = generate_jobs_pending_widget() is_oper = widgets.HTML(value="<h5></h5>", layout=widgets.Layout(justify_content='center')) least_busy = widgets.HTML(value="<h5></h5>", layout=widgets.Layout(justify_content='center')) t1_units = props['qubits'][0][0]['unit'] avg_t1 = round(sum([q[0]['value'] for q in props['qubits']])/n_qubits, 1) t1_widget = widgets.HTML(value="<h5>{t1} {units}</h5>".format(t1=avg_t1, units=t1_units), layout=widgets.Layout()) t2_units = props['qubits'][0][1]['unit'] avg_t2 = round(sum([q[1]['value'] for q in props['qubits']])/n_qubits, 1) t2_widget = widgets.HTML(value="<h5>{t2} {units}</h5>".format(t2=avg_t2, units=t2_units), layout=widgets.Layout()) out = widgets.VBox([name, cmap, qubit_count, pending, least_busy, is_oper, t1_widget, t2_widget], layout=widgets.Layout(display='inline-flex', flex_flow='column', align_items='center')) out._is_alive = True return out
def backend_widget(backend): """Creates a backend widget. """ config = backend.configuration().to_dict() props = backend.properties().to_dict() name = widgets.HTML(value="<h4>{name}</h4>".format(name=backend.name()), layout=widgets.Layout()) n_qubits = config['n_qubits'] qubit_count = widgets.HTML(value="<h5><b>{qubits}</b></h5>".format(qubits=n_qubits), layout=widgets.Layout(justify_content='center')) cmap = widgets.Output(layout=widgets.Layout(min_width='250px', max_width='250px', max_height='250px', min_height='250px', justify_content='center', align_items='center', margin='0px 0px 0px 0px')) with cmap: _cmap_fig = plot_gate_map(backend, plot_directed=False, label_qubits=False) if _cmap_fig is not None: display(_cmap_fig) # Prevents plot from showing up twice. plt.close(_cmap_fig) pending = generate_jobs_pending_widget() is_oper = widgets.HTML(value="<h5></h5>", layout=widgets.Layout(justify_content='center')) least_busy = widgets.HTML(value="<h5></h5>", layout=widgets.Layout(justify_content='center')) t1_units = props['qubits'][0][0]['unit'] avg_t1 = round(sum([q[0]['value'] for q in props['qubits']])/n_qubits, 1) t1_widget = widgets.HTML(value="<h5>{t1} {units}</h5>".format(t1=avg_t1, units=t1_units), layout=widgets.Layout()) t2_units = props['qubits'][0][1]['unit'] avg_t2 = round(sum([q[1]['value'] for q in props['qubits']])/n_qubits, 1) t2_widget = widgets.HTML(value="<h5>{t2} {units}</h5>".format(t2=avg_t2, units=t2_units), layout=widgets.Layout()) out = widgets.VBox([name, cmap, qubit_count, pending, least_busy, is_oper, t1_widget, t2_widget], layout=widgets.Layout(display='inline-flex', flex_flow='column', align_items='center')) out._is_alive = True return out
[ "Creates", "a", "backend", "widget", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/jupyter/backend_overview.py#L112-L167
[ "def", "backend_widget", "(", "backend", ")", ":", "config", "=", "backend", ".", "configuration", "(", ")", ".", "to_dict", "(", ")", "props", "=", "backend", ".", "properties", "(", ")", ".", "to_dict", "(", ")", "name", "=", "widgets", ".", "HTML", "(", "value", "=", "\"<h4>{name}</h4>\"", ".", "format", "(", "name", "=", "backend", ".", "name", "(", ")", ")", ",", "layout", "=", "widgets", ".", "Layout", "(", ")", ")", "n_qubits", "=", "config", "[", "'n_qubits'", "]", "qubit_count", "=", "widgets", ".", "HTML", "(", "value", "=", "\"<h5><b>{qubits}</b></h5>\"", ".", "format", "(", "qubits", "=", "n_qubits", ")", ",", "layout", "=", "widgets", ".", "Layout", "(", "justify_content", "=", "'center'", ")", ")", "cmap", "=", "widgets", ".", "Output", "(", "layout", "=", "widgets", ".", "Layout", "(", "min_width", "=", "'250px'", ",", "max_width", "=", "'250px'", ",", "max_height", "=", "'250px'", ",", "min_height", "=", "'250px'", ",", "justify_content", "=", "'center'", ",", "align_items", "=", "'center'", ",", "margin", "=", "'0px 0px 0px 0px'", ")", ")", "with", "cmap", ":", "_cmap_fig", "=", "plot_gate_map", "(", "backend", ",", "plot_directed", "=", "False", ",", "label_qubits", "=", "False", ")", "if", "_cmap_fig", "is", "not", "None", ":", "display", "(", "_cmap_fig", ")", "# Prevents plot from showing up twice.", "plt", ".", "close", "(", "_cmap_fig", ")", "pending", "=", "generate_jobs_pending_widget", "(", ")", "is_oper", "=", "widgets", ".", "HTML", "(", "value", "=", "\"<h5></h5>\"", ",", "layout", "=", "widgets", ".", "Layout", "(", "justify_content", "=", "'center'", ")", ")", "least_busy", "=", "widgets", ".", "HTML", "(", "value", "=", "\"<h5></h5>\"", ",", "layout", "=", "widgets", ".", "Layout", "(", "justify_content", "=", "'center'", ")", ")", "t1_units", "=", "props", "[", "'qubits'", "]", "[", "0", "]", "[", "0", "]", "[", "'unit'", "]", "avg_t1", "=", "round", "(", "sum", "(", "[", "q", "[", "0", "]", "[", "'value'", "]", "for", "q", "in", "props", "[", "'qubits'", "]", "]", ")", "/", "n_qubits", ",", "1", ")", "t1_widget", "=", "widgets", ".", "HTML", "(", "value", "=", "\"<h5>{t1} {units}</h5>\"", ".", "format", "(", "t1", "=", "avg_t1", ",", "units", "=", "t1_units", ")", ",", "layout", "=", "widgets", ".", "Layout", "(", ")", ")", "t2_units", "=", "props", "[", "'qubits'", "]", "[", "0", "]", "[", "1", "]", "[", "'unit'", "]", "avg_t2", "=", "round", "(", "sum", "(", "[", "q", "[", "1", "]", "[", "'value'", "]", "for", "q", "in", "props", "[", "'qubits'", "]", "]", ")", "/", "n_qubits", ",", "1", ")", "t2_widget", "=", "widgets", ".", "HTML", "(", "value", "=", "\"<h5>{t2} {units}</h5>\"", ".", "format", "(", "t2", "=", "avg_t2", ",", "units", "=", "t2_units", ")", ",", "layout", "=", "widgets", ".", "Layout", "(", ")", ")", "out", "=", "widgets", ".", "VBox", "(", "[", "name", ",", "cmap", ",", "qubit_count", ",", "pending", ",", "least_busy", ",", "is_oper", ",", "t1_widget", ",", "t2_widget", "]", ",", "layout", "=", "widgets", ".", "Layout", "(", "display", "=", "'inline-flex'", ",", "flex_flow", "=", "'column'", ",", "align_items", "=", "'center'", ")", ")", "out", ".", "_is_alive", "=", "True", "return", "out" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
update_backend_info
Updates the monitor info Called from another thread.
qiskit/tools/jupyter/backend_overview.py
def update_backend_info(self, interval=60): """Updates the monitor info Called from another thread. """ my_thread = threading.currentThread() current_interval = 0 started = False all_dead = False stati = [None]*len(self._backends) while getattr(my_thread, "do_run", True) and not all_dead: if current_interval == interval or started is False: for ind, back in enumerate(self._backends): _value = self.children[ind].children[2].value _head = _value.split('<b>')[0] try: _status = back.status() stati[ind] = _status except Exception: # pylint: disable=W0703 self.children[ind].children[2].value = _value.replace( _head, "<h5 style='color:#ff5c49'>") self.children[ind]._is_alive = False else: self.children[ind]._is_alive = True self.children[ind].children[2].value = _value.replace( _head, "<h5>") idx = list(range(len(self._backends))) pending = [s.pending_jobs for s in stati] _, least_idx = zip(*sorted(zip(pending, idx))) # Make sure least pending is operational for ind in least_idx: if stati[ind].operational: least_pending_idx = ind break for var in idx: if var == least_pending_idx: self.children[var].children[4].value = "<h5 style='color:#34bc6e'>True</h5>" else: self.children[var].children[4].value = "<h5 style='color:#dc267f'>False</h5>" self.children[var].children[3].children[1].value = pending[var] self.children[var].children[3].children[1].max = max( self.children[var].children[3].children[1].max, pending[var]+10) if stati[var].operational: self.children[var].children[5].value = "<h5 style='color:#34bc6e'>True</h5>" else: self.children[var].children[5].value = "<h5 style='color:#dc267f'>False</h5>" started = True current_interval = 0 time.sleep(1) all_dead = not any([wid._is_alive for wid in self.children]) current_interval += 1
def update_backend_info(self, interval=60): """Updates the monitor info Called from another thread. """ my_thread = threading.currentThread() current_interval = 0 started = False all_dead = False stati = [None]*len(self._backends) while getattr(my_thread, "do_run", True) and not all_dead: if current_interval == interval or started is False: for ind, back in enumerate(self._backends): _value = self.children[ind].children[2].value _head = _value.split('<b>')[0] try: _status = back.status() stati[ind] = _status except Exception: # pylint: disable=W0703 self.children[ind].children[2].value = _value.replace( _head, "<h5 style='color:#ff5c49'>") self.children[ind]._is_alive = False else: self.children[ind]._is_alive = True self.children[ind].children[2].value = _value.replace( _head, "<h5>") idx = list(range(len(self._backends))) pending = [s.pending_jobs for s in stati] _, least_idx = zip(*sorted(zip(pending, idx))) # Make sure least pending is operational for ind in least_idx: if stati[ind].operational: least_pending_idx = ind break for var in idx: if var == least_pending_idx: self.children[var].children[4].value = "<h5 style='color:#34bc6e'>True</h5>" else: self.children[var].children[4].value = "<h5 style='color:#dc267f'>False</h5>" self.children[var].children[3].children[1].value = pending[var] self.children[var].children[3].children[1].max = max( self.children[var].children[3].children[1].max, pending[var]+10) if stati[var].operational: self.children[var].children[5].value = "<h5 style='color:#34bc6e'>True</h5>" else: self.children[var].children[5].value = "<h5 style='color:#dc267f'>False</h5>" started = True current_interval = 0 time.sleep(1) all_dead = not any([wid._is_alive for wid in self.children]) current_interval += 1
[ "Updates", "the", "monitor", "info", "Called", "from", "another", "thread", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/jupyter/backend_overview.py#L170-L224
[ "def", "update_backend_info", "(", "self", ",", "interval", "=", "60", ")", ":", "my_thread", "=", "threading", ".", "currentThread", "(", ")", "current_interval", "=", "0", "started", "=", "False", "all_dead", "=", "False", "stati", "=", "[", "None", "]", "*", "len", "(", "self", ".", "_backends", ")", "while", "getattr", "(", "my_thread", ",", "\"do_run\"", ",", "True", ")", "and", "not", "all_dead", ":", "if", "current_interval", "==", "interval", "or", "started", "is", "False", ":", "for", "ind", ",", "back", "in", "enumerate", "(", "self", ".", "_backends", ")", ":", "_value", "=", "self", ".", "children", "[", "ind", "]", ".", "children", "[", "2", "]", ".", "value", "_head", "=", "_value", ".", "split", "(", "'<b>'", ")", "[", "0", "]", "try", ":", "_status", "=", "back", ".", "status", "(", ")", "stati", "[", "ind", "]", "=", "_status", "except", "Exception", ":", "# pylint: disable=W0703", "self", ".", "children", "[", "ind", "]", ".", "children", "[", "2", "]", ".", "value", "=", "_value", ".", "replace", "(", "_head", ",", "\"<h5 style='color:#ff5c49'>\"", ")", "self", ".", "children", "[", "ind", "]", ".", "_is_alive", "=", "False", "else", ":", "self", ".", "children", "[", "ind", "]", ".", "_is_alive", "=", "True", "self", ".", "children", "[", "ind", "]", ".", "children", "[", "2", "]", ".", "value", "=", "_value", ".", "replace", "(", "_head", ",", "\"<h5>\"", ")", "idx", "=", "list", "(", "range", "(", "len", "(", "self", ".", "_backends", ")", ")", ")", "pending", "=", "[", "s", ".", "pending_jobs", "for", "s", "in", "stati", "]", "_", ",", "least_idx", "=", "zip", "(", "*", "sorted", "(", "zip", "(", "pending", ",", "idx", ")", ")", ")", "# Make sure least pending is operational", "for", "ind", "in", "least_idx", ":", "if", "stati", "[", "ind", "]", ".", "operational", ":", "least_pending_idx", "=", "ind", "break", "for", "var", "in", "idx", ":", "if", "var", "==", "least_pending_idx", ":", "self", ".", "children", "[", "var", "]", ".", "children", "[", "4", "]", ".", "value", "=", "\"<h5 style='color:#34bc6e'>True</h5>\"", "else", ":", "self", ".", "children", "[", "var", "]", ".", "children", "[", "4", "]", ".", "value", "=", "\"<h5 style='color:#dc267f'>False</h5>\"", "self", ".", "children", "[", "var", "]", ".", "children", "[", "3", "]", ".", "children", "[", "1", "]", ".", "value", "=", "pending", "[", "var", "]", "self", ".", "children", "[", "var", "]", ".", "children", "[", "3", "]", ".", "children", "[", "1", "]", ".", "max", "=", "max", "(", "self", ".", "children", "[", "var", "]", ".", "children", "[", "3", "]", ".", "children", "[", "1", "]", ".", "max", ",", "pending", "[", "var", "]", "+", "10", ")", "if", "stati", "[", "var", "]", ".", "operational", ":", "self", ".", "children", "[", "var", "]", ".", "children", "[", "5", "]", ".", "value", "=", "\"<h5 style='color:#34bc6e'>True</h5>\"", "else", ":", "self", ".", "children", "[", "var", "]", ".", "children", "[", "5", "]", ".", "value", "=", "\"<h5 style='color:#dc267f'>False</h5>\"", "started", "=", "True", "current_interval", "=", "0", "time", ".", "sleep", "(", "1", ")", "all_dead", "=", "not", "any", "(", "[", "wid", ".", "_is_alive", "for", "wid", "in", "self", ".", "children", "]", ")", "current_interval", "+=", "1" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
generate_jobs_pending_widget
Generates a jobs_pending progress bar widget.
qiskit/tools/jupyter/backend_overview.py
def generate_jobs_pending_widget(): """Generates a jobs_pending progress bar widget. """ pbar = widgets.IntProgress( value=0, min=0, max=50, description='', orientation='horizontal', layout=widgets.Layout(max_width='180px')) pbar.style.bar_color = '#71cddd' pbar_current = widgets.Label( value=str(pbar.value), layout=widgets.Layout(min_width='auto')) pbar_max = widgets.Label( value=str(pbar.max), layout=widgets.Layout(min_width='auto')) def _on_max_change(change): pbar_max.value = str(change['new']) def _on_val_change(change): pbar_current.value = str(change['new']) pbar.observe(_on_max_change, names='max') pbar.observe(_on_val_change, names='value') jobs_widget = widgets.HBox([pbar_current, pbar, pbar_max], layout=widgets.Layout(max_width='250px', min_width='250px', justify_content='center')) return jobs_widget
def generate_jobs_pending_widget(): """Generates a jobs_pending progress bar widget. """ pbar = widgets.IntProgress( value=0, min=0, max=50, description='', orientation='horizontal', layout=widgets.Layout(max_width='180px')) pbar.style.bar_color = '#71cddd' pbar_current = widgets.Label( value=str(pbar.value), layout=widgets.Layout(min_width='auto')) pbar_max = widgets.Label( value=str(pbar.max), layout=widgets.Layout(min_width='auto')) def _on_max_change(change): pbar_max.value = str(change['new']) def _on_val_change(change): pbar_current.value = str(change['new']) pbar.observe(_on_max_change, names='max') pbar.observe(_on_val_change, names='value') jobs_widget = widgets.HBox([pbar_current, pbar, pbar_max], layout=widgets.Layout(max_width='250px', min_width='250px', justify_content='center')) return jobs_widget
[ "Generates", "a", "jobs_pending", "progress", "bar", "widget", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/jupyter/backend_overview.py#L227-L257
[ "def", "generate_jobs_pending_widget", "(", ")", ":", "pbar", "=", "widgets", ".", "IntProgress", "(", "value", "=", "0", ",", "min", "=", "0", ",", "max", "=", "50", ",", "description", "=", "''", ",", "orientation", "=", "'horizontal'", ",", "layout", "=", "widgets", ".", "Layout", "(", "max_width", "=", "'180px'", ")", ")", "pbar", ".", "style", ".", "bar_color", "=", "'#71cddd'", "pbar_current", "=", "widgets", ".", "Label", "(", "value", "=", "str", "(", "pbar", ".", "value", ")", ",", "layout", "=", "widgets", ".", "Layout", "(", "min_width", "=", "'auto'", ")", ")", "pbar_max", "=", "widgets", ".", "Label", "(", "value", "=", "str", "(", "pbar", ".", "max", ")", ",", "layout", "=", "widgets", ".", "Layout", "(", "min_width", "=", "'auto'", ")", ")", "def", "_on_max_change", "(", "change", ")", ":", "pbar_max", ".", "value", "=", "str", "(", "change", "[", "'new'", "]", ")", "def", "_on_val_change", "(", "change", ")", ":", "pbar_current", ".", "value", "=", "str", "(", "change", "[", "'new'", "]", ")", "pbar", ".", "observe", "(", "_on_max_change", ",", "names", "=", "'max'", ")", "pbar", ".", "observe", "(", "_on_val_change", ",", "names", "=", "'value'", ")", "jobs_widget", "=", "widgets", ".", "HBox", "(", "[", "pbar_current", ",", "pbar", ",", "pbar_max", "]", ",", "layout", "=", "widgets", ".", "Layout", "(", "max_width", "=", "'250px'", ",", "min_width", "=", "'250px'", ",", "justify_content", "=", "'center'", ")", ")", "return", "jobs_widget" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
CXDirection.run
Flips the cx nodes to match the directed coupling map. Args: dag (DAGCircuit): DAG to map. Returns: DAGCircuit: The rearranged dag for the coupling map Raises: TranspilerError: If the circuit cannot be mapped just by flipping the cx nodes.
qiskit/transpiler/passes/mapping/cx_direction.py
def run(self, dag): """ Flips the cx nodes to match the directed coupling map. Args: dag (DAGCircuit): DAG to map. Returns: DAGCircuit: The rearranged dag for the coupling map Raises: TranspilerError: If the circuit cannot be mapped just by flipping the cx nodes. """ new_dag = DAGCircuit() if self.layout is None: # LegacySwap renames the register in the DAG and does not match the property set self.layout = Layout.generate_trivial_layout(*dag.qregs.values()) for layer in dag.serial_layers(): subdag = layer['graph'] for cnot_node in subdag.named_nodes('cx', 'CX'): control = cnot_node.qargs[0] target = cnot_node.qargs[1] physical_q0 = self.layout[control] physical_q1 = self.layout[target] if self.coupling_map.distance(physical_q0, physical_q1) != 1: raise TranspilerError('The circuit requires a connection between physical ' 'qubits %s and %s' % (physical_q0, physical_q1)) if (physical_q0, physical_q1) not in self.coupling_map.get_edges(): # A flip needs to be done # Create the involved registers if control[0] not in subdag.qregs.values(): subdag.add_qreg(control[0]) if target[0] not in subdag.qregs.values(): subdag.add_qreg(target[0]) # Add H gates around subdag.apply_operation_back(HGate(), [target], []) subdag.apply_operation_back(HGate(), [control], []) subdag.apply_operation_front(HGate(), [target], []) subdag.apply_operation_front(HGate(), [control], []) # Flips the CX cnot_node.qargs[0], cnot_node.qargs[1] = target, control new_dag.extend_back(subdag) return new_dag
def run(self, dag): """ Flips the cx nodes to match the directed coupling map. Args: dag (DAGCircuit): DAG to map. Returns: DAGCircuit: The rearranged dag for the coupling map Raises: TranspilerError: If the circuit cannot be mapped just by flipping the cx nodes. """ new_dag = DAGCircuit() if self.layout is None: # LegacySwap renames the register in the DAG and does not match the property set self.layout = Layout.generate_trivial_layout(*dag.qregs.values()) for layer in dag.serial_layers(): subdag = layer['graph'] for cnot_node in subdag.named_nodes('cx', 'CX'): control = cnot_node.qargs[0] target = cnot_node.qargs[1] physical_q0 = self.layout[control] physical_q1 = self.layout[target] if self.coupling_map.distance(physical_q0, physical_q1) != 1: raise TranspilerError('The circuit requires a connection between physical ' 'qubits %s and %s' % (physical_q0, physical_q1)) if (physical_q0, physical_q1) not in self.coupling_map.get_edges(): # A flip needs to be done # Create the involved registers if control[0] not in subdag.qregs.values(): subdag.add_qreg(control[0]) if target[0] not in subdag.qregs.values(): subdag.add_qreg(target[0]) # Add H gates around subdag.apply_operation_back(HGate(), [target], []) subdag.apply_operation_back(HGate(), [control], []) subdag.apply_operation_front(HGate(), [target], []) subdag.apply_operation_front(HGate(), [control], []) # Flips the CX cnot_node.qargs[0], cnot_node.qargs[1] = target, control new_dag.extend_back(subdag) return new_dag
[ "Flips", "the", "cx", "nodes", "to", "match", "the", "directed", "coupling", "map", ".", "Args", ":", "dag", "(", "DAGCircuit", ")", ":", "DAG", "to", "map", ".", "Returns", ":", "DAGCircuit", ":", "The", "rearranged", "dag", "for", "the", "coupling", "map" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/cx_direction.py#L44-L95
[ "def", "run", "(", "self", ",", "dag", ")", ":", "new_dag", "=", "DAGCircuit", "(", ")", "if", "self", ".", "layout", "is", "None", ":", "# LegacySwap renames the register in the DAG and does not match the property set", "self", ".", "layout", "=", "Layout", ".", "generate_trivial_layout", "(", "*", "dag", ".", "qregs", ".", "values", "(", ")", ")", "for", "layer", "in", "dag", ".", "serial_layers", "(", ")", ":", "subdag", "=", "layer", "[", "'graph'", "]", "for", "cnot_node", "in", "subdag", ".", "named_nodes", "(", "'cx'", ",", "'CX'", ")", ":", "control", "=", "cnot_node", ".", "qargs", "[", "0", "]", "target", "=", "cnot_node", ".", "qargs", "[", "1", "]", "physical_q0", "=", "self", ".", "layout", "[", "control", "]", "physical_q1", "=", "self", ".", "layout", "[", "target", "]", "if", "self", ".", "coupling_map", ".", "distance", "(", "physical_q0", ",", "physical_q1", ")", "!=", "1", ":", "raise", "TranspilerError", "(", "'The circuit requires a connection between physical '", "'qubits %s and %s'", "%", "(", "physical_q0", ",", "physical_q1", ")", ")", "if", "(", "physical_q0", ",", "physical_q1", ")", "not", "in", "self", ".", "coupling_map", ".", "get_edges", "(", ")", ":", "# A flip needs to be done", "# Create the involved registers", "if", "control", "[", "0", "]", "not", "in", "subdag", ".", "qregs", ".", "values", "(", ")", ":", "subdag", ".", "add_qreg", "(", "control", "[", "0", "]", ")", "if", "target", "[", "0", "]", "not", "in", "subdag", ".", "qregs", ".", "values", "(", ")", ":", "subdag", ".", "add_qreg", "(", "target", "[", "0", "]", ")", "# Add H gates around", "subdag", ".", "apply_operation_back", "(", "HGate", "(", ")", ",", "[", "target", "]", ",", "[", "]", ")", "subdag", ".", "apply_operation_back", "(", "HGate", "(", ")", ",", "[", "control", "]", ",", "[", "]", ")", "subdag", ".", "apply_operation_front", "(", "HGate", "(", ")", ",", "[", "target", "]", ",", "[", "]", ")", "subdag", ".", "apply_operation_front", "(", "HGate", "(", ")", ",", "[", "control", "]", ",", "[", "]", ")", "# Flips the CX", "cnot_node", ".", "qargs", "[", "0", "]", ",", "cnot_node", ".", "qargs", "[", "1", "]", "=", "target", ",", "control", "new_dag", ".", "extend_back", "(", "subdag", ")", "return", "new_dag" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
CXCancellation.run
Run one pass of cx cancellation on the circuit Args: dag (DAGCircuit): the directed acyclic graph to run on. Returns: DAGCircuit: Transformed DAG.
qiskit/transpiler/passes/cx_cancellation.py
def run(self, dag): """ Run one pass of cx cancellation on the circuit Args: dag (DAGCircuit): the directed acyclic graph to run on. Returns: DAGCircuit: Transformed DAG. """ cx_runs = dag.collect_runs(["cx"]) for cx_run in cx_runs: # Partition the cx_run into chunks with equal gate arguments partition = [] chunk = [] for i in range(len(cx_run) - 1): chunk.append(cx_run[i]) qargs0 = cx_run[i].qargs qargs1 = cx_run[i + 1].qargs if qargs0 != qargs1: partition.append(chunk) chunk = [] chunk.append(cx_run[-1]) partition.append(chunk) # Simplify each chunk in the partition for chunk in partition: if len(chunk) % 2 == 0: for n in chunk: dag.remove_op_node(n) else: for n in chunk[1:]: dag.remove_op_node(n) return dag
def run(self, dag): """ Run one pass of cx cancellation on the circuit Args: dag (DAGCircuit): the directed acyclic graph to run on. Returns: DAGCircuit: Transformed DAG. """ cx_runs = dag.collect_runs(["cx"]) for cx_run in cx_runs: # Partition the cx_run into chunks with equal gate arguments partition = [] chunk = [] for i in range(len(cx_run) - 1): chunk.append(cx_run[i]) qargs0 = cx_run[i].qargs qargs1 = cx_run[i + 1].qargs if qargs0 != qargs1: partition.append(chunk) chunk = [] chunk.append(cx_run[-1]) partition.append(chunk) # Simplify each chunk in the partition for chunk in partition: if len(chunk) % 2 == 0: for n in chunk: dag.remove_op_node(n) else: for n in chunk[1:]: dag.remove_op_node(n) return dag
[ "Run", "one", "pass", "of", "cx", "cancellation", "on", "the", "circuit" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/cx_cancellation.py#L16-L49
[ "def", "run", "(", "self", ",", "dag", ")", ":", "cx_runs", "=", "dag", ".", "collect_runs", "(", "[", "\"cx\"", "]", ")", "for", "cx_run", "in", "cx_runs", ":", "# Partition the cx_run into chunks with equal gate arguments", "partition", "=", "[", "]", "chunk", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "cx_run", ")", "-", "1", ")", ":", "chunk", ".", "append", "(", "cx_run", "[", "i", "]", ")", "qargs0", "=", "cx_run", "[", "i", "]", ".", "qargs", "qargs1", "=", "cx_run", "[", "i", "+", "1", "]", ".", "qargs", "if", "qargs0", "!=", "qargs1", ":", "partition", ".", "append", "(", "chunk", ")", "chunk", "=", "[", "]", "chunk", ".", "append", "(", "cx_run", "[", "-", "1", "]", ")", "partition", ".", "append", "(", "chunk", ")", "# Simplify each chunk in the partition", "for", "chunk", "in", "partition", ":", "if", "len", "(", "chunk", ")", "%", "2", "==", "0", ":", "for", "n", "in", "chunk", ":", "dag", ".", "remove_op_node", "(", "n", ")", "else", ":", "for", "n", "in", "chunk", "[", "1", ":", "]", ":", "dag", ".", "remove_op_node", "(", "n", ")", "return", "dag" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BaseProvider.get_backend
Return a single backend matching the specified filtering. Args: name (str): name of the backend. **kwargs (dict): dict used for filtering. Returns: BaseBackend: a backend matching the filtering. Raises: QiskitBackendNotFoundError: if no backend could be found or more than one backend matches.
qiskit/providers/baseprovider.py
def get_backend(self, name=None, **kwargs): """Return a single backend matching the specified filtering. Args: name (str): name of the backend. **kwargs (dict): dict used for filtering. Returns: BaseBackend: a backend matching the filtering. Raises: QiskitBackendNotFoundError: if no backend could be found or more than one backend matches. """ backends = self.backends(name, **kwargs) if len(backends) > 1: raise QiskitBackendNotFoundError('More than one backend matches the criteria') elif not backends: raise QiskitBackendNotFoundError('No backend matches the criteria') return backends[0]
def get_backend(self, name=None, **kwargs): """Return a single backend matching the specified filtering. Args: name (str): name of the backend. **kwargs (dict): dict used for filtering. Returns: BaseBackend: a backend matching the filtering. Raises: QiskitBackendNotFoundError: if no backend could be found or more than one backend matches. """ backends = self.backends(name, **kwargs) if len(backends) > 1: raise QiskitBackendNotFoundError('More than one backend matches the criteria') elif not backends: raise QiskitBackendNotFoundError('No backend matches the criteria') return backends[0]
[ "Return", "a", "single", "backend", "matching", "the", "specified", "filtering", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/baseprovider.py#L28-L48
[ "def", "get_backend", "(", "self", ",", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "backends", "=", "self", ".", "backends", "(", "name", ",", "*", "*", "kwargs", ")", "if", "len", "(", "backends", ")", ">", "1", ":", "raise", "QiskitBackendNotFoundError", "(", "'More than one backend matches the criteria'", ")", "elif", "not", "backends", ":", "raise", "QiskitBackendNotFoundError", "(", "'No backend matches the criteria'", ")", "return", "backends", "[", "0", "]" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Choi._bipartite_shape
Return the shape for bipartite matrix
qiskit/quantum_info/operators/channel/choi.py
def _bipartite_shape(self): """Return the shape for bipartite matrix""" return (self._input_dim, self._output_dim, self._input_dim, self._output_dim)
def _bipartite_shape(self): """Return the shape for bipartite matrix""" return (self._input_dim, self._output_dim, self._input_dim, self._output_dim)
[ "Return", "the", "shape", "for", "bipartite", "matrix" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/choi.py#L113-L116
[ "def", "_bipartite_shape", "(", "self", ")", ":", "return", "(", "self", ".", "_input_dim", ",", "self", ".", "_output_dim", ",", "self", ".", "_input_dim", ",", "self", ".", "_output_dim", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Choi.conjugate
Return the conjugate of the QuantumChannel.
qiskit/quantum_info/operators/channel/choi.py
def conjugate(self): """Return the conjugate of the QuantumChannel.""" return Choi(np.conj(self._data), self.input_dims(), self.output_dims())
def conjugate(self): """Return the conjugate of the QuantumChannel.""" return Choi(np.conj(self._data), 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/choi.py#L118-L120
[ "def", "conjugate", "(", "self", ")", ":", "return", "Choi", "(", "np", ".", "conj", "(", "self", ".", "_data", ")", ",", "self", ".", "input_dims", "(", ")", ",", "self", ".", "output_dims", "(", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Choi.transpose
Return the transpose of the QuantumChannel.
qiskit/quantum_info/operators/channel/choi.py
def transpose(self): """Return the transpose of the QuantumChannel.""" # Make bipartite matrix d_in, d_out = self.dim data = np.reshape(self._data, (d_in, d_out, d_in, d_out)) # Swap input and output indicies on bipartite matrix data = np.transpose(data, (1, 0, 3, 2)) # Transpose channel has input and output dimensions swapped data = np.reshape(data, (d_in * d_out, d_in * d_out)) return Choi( data, input_dims=self.output_dims(), output_dims=self.input_dims())
def transpose(self): """Return the transpose of the QuantumChannel.""" # Make bipartite matrix d_in, d_out = self.dim data = np.reshape(self._data, (d_in, d_out, d_in, d_out)) # Swap input and output indicies on bipartite matrix data = np.transpose(data, (1, 0, 3, 2)) # Transpose channel has input and output dimensions swapped data = np.reshape(data, (d_in * d_out, d_in * d_out)) return Choi( data, 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/choi.py#L122-L132
[ "def", "transpose", "(", "self", ")", ":", "# Make bipartite matrix", "d_in", ",", "d_out", "=", "self", ".", "dim", "data", "=", "np", ".", "reshape", "(", "self", ".", "_data", ",", "(", "d_in", ",", "d_out", ",", "d_in", ",", "d_out", ")", ")", "# Swap input and output indicies on bipartite matrix", "data", "=", "np", ".", "transpose", "(", "data", ",", "(", "1", ",", "0", ",", "3", ",", "2", ")", ")", "# Transpose channel has input and output dimensions swapped", "data", "=", "np", ".", "reshape", "(", "data", ",", "(", "d_in", "*", "d_out", ",", "d_in", "*", "d_out", ")", ")", "return", "Choi", "(", "data", ",", "input_dims", "=", "self", ".", "output_dims", "(", ")", ",", "output_dims", "=", "self", ".", "input_dims", "(", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Choi.compose
Return the composition channel self∘other. Args: other (QuantumChannel): a quantum channel. qargs (list): a list of subsystem positions to compose other on. front (bool): If False compose in standard order other(self(input)) otherwise compose in reverse order self(other(input)) [default: False] Returns: Choi: The composition channel as a Choi object. Raises: QiskitError: if other cannot be converted to a channel or has incompatible dimensions.
qiskit/quantum_info/operators/channel/choi.py
def compose(self, other, qargs=None, front=False): """Return the composition channel self∘other. Args: other (QuantumChannel): a quantum channel. qargs (list): a list of subsystem positions to compose other on. front (bool): If False compose in standard order other(self(input)) otherwise compose in reverse order self(other(input)) [default: False] Returns: Choi: The composition channel as a Choi object. Raises: QiskitError: if other cannot be converted to a channel or has incompatible dimensions. """ if qargs is not None: return Choi( SuperOp(self).compose(other, qargs=qargs, front=front)) # Convert to Choi matrix if not isinstance(other, Choi): other = Choi(other) # Check dimensions match up if front and self._input_dim != other._output_dim: raise QiskitError( 'input_dim of self must match output_dim of other') if not front and self._output_dim != other._input_dim: raise QiskitError( 'input_dim of other must match output_dim of self') if front: first = np.reshape(other._data, other._bipartite_shape) second = np.reshape(self._data, self._bipartite_shape) input_dim = other._input_dim input_dims = other.input_dims() output_dim = self._output_dim output_dims = self.output_dims() else: first = np.reshape(self._data, self._bipartite_shape) second = np.reshape(other._data, other._bipartite_shape) input_dim = self._input_dim input_dims = self.input_dims() output_dim = other._output_dim output_dims = other.output_dims() # Contract Choi matrices for composition data = np.reshape( np.einsum('iAjB,AkBl->ikjl', first, second), (input_dim * output_dim, input_dim * output_dim)) return Choi(data, input_dims, output_dims)
def compose(self, other, qargs=None, front=False): """Return the composition channel self∘other. Args: other (QuantumChannel): a quantum channel. qargs (list): a list of subsystem positions to compose other on. front (bool): If False compose in standard order other(self(input)) otherwise compose in reverse order self(other(input)) [default: False] Returns: Choi: The composition channel as a Choi object. Raises: QiskitError: if other cannot be converted to a channel or has incompatible dimensions. """ if qargs is not None: return Choi( SuperOp(self).compose(other, qargs=qargs, front=front)) # Convert to Choi matrix if not isinstance(other, Choi): other = Choi(other) # Check dimensions match up if front and self._input_dim != other._output_dim: raise QiskitError( 'input_dim of self must match output_dim of other') if not front and self._output_dim != other._input_dim: raise QiskitError( 'input_dim of other must match output_dim of self') if front: first = np.reshape(other._data, other._bipartite_shape) second = np.reshape(self._data, self._bipartite_shape) input_dim = other._input_dim input_dims = other.input_dims() output_dim = self._output_dim output_dims = self.output_dims() else: first = np.reshape(self._data, self._bipartite_shape) second = np.reshape(other._data, other._bipartite_shape) input_dim = self._input_dim input_dims = self.input_dims() output_dim = other._output_dim output_dims = other.output_dims() # Contract Choi matrices for composition data = np.reshape( np.einsum('iAjB,AkBl->ikjl', first, second), (input_dim * output_dim, input_dim * output_dim)) return Choi(data, input_dims, output_dims)
[ "Return", "the", "composition", "channel", "self∘other", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/choi.py#L134-L185
[ "def", "compose", "(", "self", ",", "other", ",", "qargs", "=", "None", ",", "front", "=", "False", ")", ":", "if", "qargs", "is", "not", "None", ":", "return", "Choi", "(", "SuperOp", "(", "self", ")", ".", "compose", "(", "other", ",", "qargs", "=", "qargs", ",", "front", "=", "front", ")", ")", "# Convert to Choi matrix", "if", "not", "isinstance", "(", "other", ",", "Choi", ")", ":", "other", "=", "Choi", "(", "other", ")", "# Check dimensions match up", "if", "front", "and", "self", ".", "_input_dim", "!=", "other", ".", "_output_dim", ":", "raise", "QiskitError", "(", "'input_dim of self must match output_dim of other'", ")", "if", "not", "front", "and", "self", ".", "_output_dim", "!=", "other", ".", "_input_dim", ":", "raise", "QiskitError", "(", "'input_dim of other must match output_dim of self'", ")", "if", "front", ":", "first", "=", "np", ".", "reshape", "(", "other", ".", "_data", ",", "other", ".", "_bipartite_shape", ")", "second", "=", "np", ".", "reshape", "(", "self", ".", "_data", ",", "self", ".", "_bipartite_shape", ")", "input_dim", "=", "other", ".", "_input_dim", "input_dims", "=", "other", ".", "input_dims", "(", ")", "output_dim", "=", "self", ".", "_output_dim", "output_dims", "=", "self", ".", "output_dims", "(", ")", "else", ":", "first", "=", "np", ".", "reshape", "(", "self", ".", "_data", ",", "self", ".", "_bipartite_shape", ")", "second", "=", "np", ".", "reshape", "(", "other", ".", "_data", ",", "other", ".", "_bipartite_shape", ")", "input_dim", "=", "self", ".", "_input_dim", "input_dims", "=", "self", ".", "input_dims", "(", ")", "output_dim", "=", "other", ".", "_output_dim", "output_dims", "=", "other", ".", "output_dims", "(", ")", "# Contract Choi matrices for composition", "data", "=", "np", ".", "reshape", "(", "np", ".", "einsum", "(", "'iAjB,AkBl->ikjl'", ",", "first", ",", "second", ")", ",", "(", "input_dim", "*", "output_dim", ",", "input_dim", "*", "output_dim", ")", ")", "return", "Choi", "(", "data", ",", "input_dims", ",", "output_dims", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Choi.power
The matrix power of the channel. Args: n (int): compute the matrix power of the superoperator matrix. Returns: Choi: the matrix power of the SuperOp converted to a Choi 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/choi.py
def power(self, n): """The matrix power of the channel. Args: n (int): compute the matrix power of the superoperator matrix. Returns: Choi: the matrix power of the SuperOp converted to a Choi 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 Choi(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: Choi: the matrix power of the SuperOp converted to a Choi 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 Choi(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/choi.py#L187-L202
[ "def", "power", "(", "self", ",", "n", ")", ":", "if", "n", ">", "0", ":", "return", "super", "(", ")", ".", "power", "(", "n", ")", "return", "Choi", "(", "SuperOp", "(", "self", ")", ".", "power", "(", "n", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Choi._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: DensityMatrix: the output quantum state as a density matrix. Raises: QiskitError: if the operator dimension does not match the specified QuantumState subsystem dimensions.
qiskit/quantum_info/operators/channel/choi.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: DensityMatrix: the output quantum state as a density matrix. 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, density_matrix=True) if state.shape[0] != self._input_dim: raise QiskitError( "QuantumChannel input dimension is not equal to state dimension." ) return np.einsum('AB,AiBj->ij', state, np.reshape(self._data, self._bipartite_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: DensityMatrix: the output quantum state as a density matrix. 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, density_matrix=True) if state.shape[0] != self._input_dim: raise QiskitError( "QuantumChannel input dimension is not equal to state dimension." ) return np.einsum('AB,AiBj->ij', state, np.reshape(self._data, self._bipartite_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/choi.py#L288-L313
[ "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", ",", "density_matrix", "=", "True", ")", "if", "state", ".", "shape", "[", "0", "]", "!=", "self", ".", "_input_dim", ":", "raise", "QiskitError", "(", "\"QuantumChannel input dimension is not equal to state dimension.\"", ")", "return", "np", ".", "einsum", "(", "'AB,AiBj->ij'", ",", "state", ",", "np", ".", "reshape", "(", "self", ".", "_data", ",", "self", ".", "_bipartite_shape", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Choi._tensor_product
Return the tensor product channel. Args: other (QuantumChannel): a quantum channel. reverse (bool): If False return self ⊗ other, if True return if True return (other ⊗ self) [Default: False Returns: Choi: the tensor product channel as a Choi object. Raises: QiskitError: if other is not a QuantumChannel subclass.
qiskit/quantum_info/operators/channel/choi.py
def _tensor_product(self, other, reverse=False): """Return the tensor product channel. Args: other (QuantumChannel): a quantum channel. reverse (bool): If False return self ⊗ other, if True return if True return (other ⊗ self) [Default: False Returns: Choi: the tensor product channel as a Choi object. Raises: QiskitError: if other is not a QuantumChannel subclass. """ # Convert other to Choi if not isinstance(other, Choi): other = Choi(other) if reverse: input_dims = self.input_dims() + other.input_dims() output_dims = self.output_dims() + other.output_dims() data = _bipartite_tensor( other.data, self._data, shape1=other._bipartite_shape, shape2=self._bipartite_shape) else: input_dims = other.input_dims() + self.input_dims() output_dims = other.output_dims() + self.output_dims() data = _bipartite_tensor( self._data, other.data, shape1=self._bipartite_shape, shape2=other._bipartite_shape) return Choi(data, input_dims, output_dims)
def _tensor_product(self, other, reverse=False): """Return the tensor product channel. Args: other (QuantumChannel): a quantum channel. reverse (bool): If False return self ⊗ other, if True return if True return (other ⊗ self) [Default: False Returns: Choi: the tensor product channel as a Choi object. Raises: QiskitError: if other is not a QuantumChannel subclass. """ # Convert other to Choi if not isinstance(other, Choi): other = Choi(other) if reverse: input_dims = self.input_dims() + other.input_dims() output_dims = self.output_dims() + other.output_dims() data = _bipartite_tensor( other.data, self._data, shape1=other._bipartite_shape, shape2=self._bipartite_shape) else: input_dims = other.input_dims() + self.input_dims() output_dims = other.output_dims() + self.output_dims() data = _bipartite_tensor( self._data, other.data, shape1=self._bipartite_shape, shape2=other._bipartite_shape) return Choi(data, input_dims, output_dims)
[ "Return", "the", "tensor", "product", "channel", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/choi.py#L315-L348
[ "def", "_tensor_product", "(", "self", ",", "other", ",", "reverse", "=", "False", ")", ":", "# Convert other to Choi", "if", "not", "isinstance", "(", "other", ",", "Choi", ")", ":", "other", "=", "Choi", "(", "other", ")", "if", "reverse", ":", "input_dims", "=", "self", ".", "input_dims", "(", ")", "+", "other", ".", "input_dims", "(", ")", "output_dims", "=", "self", ".", "output_dims", "(", ")", "+", "other", ".", "output_dims", "(", ")", "data", "=", "_bipartite_tensor", "(", "other", ".", "data", ",", "self", ".", "_data", ",", "shape1", "=", "other", ".", "_bipartite_shape", ",", "shape2", "=", "self", ".", "_bipartite_shape", ")", "else", ":", "input_dims", "=", "other", ".", "input_dims", "(", ")", "+", "self", ".", "input_dims", "(", ")", "output_dims", "=", "other", ".", "output_dims", "(", ")", "+", "self", ".", "output_dims", "(", ")", "data", "=", "_bipartite_tensor", "(", "self", ".", "_data", ",", "other", ".", "data", ",", "shape1", "=", "self", ".", "_bipartite_shape", ",", "shape2", "=", "other", ".", "_bipartite_shape", ")", "return", "Choi", "(", "data", ",", "input_dims", ",", "output_dims", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_get_register_specs
Get the number and size of unique registers from bit_labels list. Args: bit_labels (list): this list is of the form:: [['reg1', 0], ['reg1', 1], ['reg2', 0]] which indicates a register named "reg1" of size 2 and a register named "reg2" of size 1. This is the format of classic and quantum bit labels in qobj header. Yields: tuple: iterator of register_name:size pairs.
qiskit/visualization/latex.py
def _get_register_specs(bit_labels): """Get the number and size of unique registers from bit_labels list. Args: bit_labels (list): this list is of the form:: [['reg1', 0], ['reg1', 1], ['reg2', 0]] which indicates a register named "reg1" of size 2 and a register named "reg2" of size 1. This is the format of classic and quantum bit labels in qobj header. Yields: tuple: iterator of register_name:size pairs. """ it = itertools.groupby(bit_labels, operator.itemgetter(0)) for register_name, sub_it in it: yield register_name, max(ind[1] for ind in sub_it) + 1
def _get_register_specs(bit_labels): """Get the number and size of unique registers from bit_labels list. Args: bit_labels (list): this list is of the form:: [['reg1', 0], ['reg1', 1], ['reg2', 0]] which indicates a register named "reg1" of size 2 and a register named "reg2" of size 1. This is the format of classic and quantum bit labels in qobj header. Yields: tuple: iterator of register_name:size pairs. """ it = itertools.groupby(bit_labels, operator.itemgetter(0)) for register_name, sub_it in it: yield register_name, max(ind[1] for ind in sub_it) + 1
[ "Get", "the", "number", "and", "size", "of", "unique", "registers", "from", "bit_labels", "list", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/latex.py#L748-L766
[ "def", "_get_register_specs", "(", "bit_labels", ")", ":", "it", "=", "itertools", ".", "groupby", "(", "bit_labels", ",", "operator", ".", "itemgetter", "(", "0", ")", ")", "for", "register_name", ",", "sub_it", "in", "it", ":", "yield", "register_name", ",", "max", "(", "ind", "[", "1", "]", "for", "ind", "in", "sub_it", ")", "+", "1" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_truncate_float
Truncate long floats Args: matchobj (re.Match): contains original float format_str (str): format specifier Returns: str: returns truncated float
qiskit/visualization/latex.py
def _truncate_float(matchobj, format_str='0.2g'): """Truncate long floats Args: matchobj (re.Match): contains original float format_str (str): format specifier Returns: str: returns truncated float """ if matchobj.group(0): return format(float(matchobj.group(0)), format_str) return ''
def _truncate_float(matchobj, format_str='0.2g'): """Truncate long floats Args: matchobj (re.Match): contains original float format_str (str): format specifier Returns: str: returns truncated float """ if matchobj.group(0): return format(float(matchobj.group(0)), format_str) return ''
[ "Truncate", "long", "floats" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/latex.py#L769-L780
[ "def", "_truncate_float", "(", "matchobj", ",", "format_str", "=", "'0.2g'", ")", ":", "if", "matchobj", ".", "group", "(", "0", ")", ":", "return", "format", "(", "float", "(", "matchobj", ".", "group", "(", "0", ")", ")", ",", "format_str", ")", "return", "''" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QCircuitImage.latex
Return LaTeX string representation of circuit. This method uses the LaTeX Qconfig package to create a graphical representation of the circuit. Returns: string: for writing to a LaTeX file.
qiskit/visualization/latex.py
def latex(self, aliases=None): """Return LaTeX string representation of circuit. This method uses the LaTeX Qconfig package to create a graphical representation of the circuit. Returns: string: for writing to a LaTeX file. """ self._initialize_latex_array(aliases) self._build_latex_array(aliases) header_1 = r"""% \documentclass[preview]{standalone} % If the image is too large to fit on this documentclass use \documentclass[draft]{beamer} """ beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n" header_2 = r"""% instead and customize the height and width (in cm) to fit. % Large images may run out of memory quickly. % To fix this use the LuaLaTeX compiler, which dynamically % allocates memory. \usepackage[braket, qm]{qcircuit} \usepackage{amsmath} \pdfmapfile{+sansmathaccent.map} % \usepackage[landscape]{geometry} % Comment out the above line if using the beamer documentclass. \begin{document} \begin{equation*}""" qcircuit_line = r""" \Qcircuit @C=%.1fem @R=%.1fem @!R { """ output = io.StringIO() output.write(header_1) output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth)) output.write(beamer_line % self._get_beamer_page()) output.write(header_2) output.write(qcircuit_line % (self.column_separation, self.row_separation)) for i in range(self.img_width): output.write("\t \t") for j in range(self.img_depth + 1): cell_str = self._latex[i][j] # Don't truncate offset float if drawing a barrier if 'barrier' in cell_str: output.write(cell_str) else: # floats can cause "Dimension too large" latex error in # xymatrix this truncates floats to avoid issue. cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, cell_str) output.write(cell_str) if j != self.img_depth: output.write(" & ") else: output.write(r'\\' + '\n') output.write('\t }\n') output.write('\\end{equation*}\n\n') output.write('\\end{document}') contents = output.getvalue() output.close() return contents
def latex(self, aliases=None): """Return LaTeX string representation of circuit. This method uses the LaTeX Qconfig package to create a graphical representation of the circuit. Returns: string: for writing to a LaTeX file. """ self._initialize_latex_array(aliases) self._build_latex_array(aliases) header_1 = r"""% \documentclass[preview]{standalone} % If the image is too large to fit on this documentclass use \documentclass[draft]{beamer} """ beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n" header_2 = r"""% instead and customize the height and width (in cm) to fit. % Large images may run out of memory quickly. % To fix this use the LuaLaTeX compiler, which dynamically % allocates memory. \usepackage[braket, qm]{qcircuit} \usepackage{amsmath} \pdfmapfile{+sansmathaccent.map} % \usepackage[landscape]{geometry} % Comment out the above line if using the beamer documentclass. \begin{document} \begin{equation*}""" qcircuit_line = r""" \Qcircuit @C=%.1fem @R=%.1fem @!R { """ output = io.StringIO() output.write(header_1) output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth)) output.write(beamer_line % self._get_beamer_page()) output.write(header_2) output.write(qcircuit_line % (self.column_separation, self.row_separation)) for i in range(self.img_width): output.write("\t \t") for j in range(self.img_depth + 1): cell_str = self._latex[i][j] # Don't truncate offset float if drawing a barrier if 'barrier' in cell_str: output.write(cell_str) else: # floats can cause "Dimension too large" latex error in # xymatrix this truncates floats to avoid issue. cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, cell_str) output.write(cell_str) if j != self.img_depth: output.write(" & ") else: output.write(r'\\' + '\n') output.write('\t }\n') output.write('\\end{equation*}\n\n') output.write('\\end{document}') contents = output.getvalue() output.close() return contents
[ "Return", "LaTeX", "string", "representation", "of", "circuit", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/latex.py#L119-L179
[ "def", "latex", "(", "self", ",", "aliases", "=", "None", ")", ":", "self", ".", "_initialize_latex_array", "(", "aliases", ")", "self", ".", "_build_latex_array", "(", "aliases", ")", "header_1", "=", "r\"\"\"% \\documentclass[preview]{standalone}\n% If the image is too large to fit on this documentclass use\n\\documentclass[draft]{beamer}\n\"\"\"", "beamer_line", "=", "\"\\\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\\n\"", "header_2", "=", "r\"\"\"% instead and customize the height and width (in cm) to fit.\n% Large images may run out of memory quickly.\n% To fix this use the LuaLaTeX compiler, which dynamically\n% allocates memory.\n\\usepackage[braket, qm]{qcircuit}\n\\usepackage{amsmath}\n\\pdfmapfile{+sansmathaccent.map}\n% \\usepackage[landscape]{geometry}\n% Comment out the above line if using the beamer documentclass.\n\\begin{document}\n\\begin{equation*}\"\"\"", "qcircuit_line", "=", "r\"\"\"\n \\Qcircuit @C=%.1fem @R=%.1fem @!R {\n\"\"\"", "output", "=", "io", ".", "StringIO", "(", ")", "output", ".", "write", "(", "header_1", ")", "output", ".", "write", "(", "'%% img_width = %d, img_depth = %d\\n'", "%", "(", "self", ".", "img_width", ",", "self", ".", "img_depth", ")", ")", "output", ".", "write", "(", "beamer_line", "%", "self", ".", "_get_beamer_page", "(", ")", ")", "output", ".", "write", "(", "header_2", ")", "output", ".", "write", "(", "qcircuit_line", "%", "(", "self", ".", "column_separation", ",", "self", ".", "row_separation", ")", ")", "for", "i", "in", "range", "(", "self", ".", "img_width", ")", ":", "output", ".", "write", "(", "\"\\t \\t\"", ")", "for", "j", "in", "range", "(", "self", ".", "img_depth", "+", "1", ")", ":", "cell_str", "=", "self", ".", "_latex", "[", "i", "]", "[", "j", "]", "# Don't truncate offset float if drawing a barrier", "if", "'barrier'", "in", "cell_str", ":", "output", ".", "write", "(", "cell_str", ")", "else", ":", "# floats can cause \"Dimension too large\" latex error in", "# xymatrix this truncates floats to avoid issue.", "cell_str", "=", "re", ".", "sub", "(", "r'[-+]?\\d*\\.\\d{2,}|\\d{2,}'", ",", "_truncate_float", ",", "cell_str", ")", "output", ".", "write", "(", "cell_str", ")", "if", "j", "!=", "self", ".", "img_depth", ":", "output", ".", "write", "(", "\" & \"", ")", "else", ":", "output", ".", "write", "(", "r'\\\\'", "+", "'\\n'", ")", "output", ".", "write", "(", "'\\t }\\n'", ")", "output", ".", "write", "(", "'\\\\end{equation*}\\n\\n'", ")", "output", ".", "write", "(", "'\\\\end{document}'", ")", "contents", "=", "output", ".", "getvalue", "(", ")", "output", ".", "close", "(", ")", "return", "contents" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QCircuitImage._get_image_depth
Get depth information for the circuit. Returns: int: number of columns in the circuit int: total size of columns in the circuit
qiskit/visualization/latex.py
def _get_image_depth(self): """Get depth information for the circuit. Returns: int: number of columns in the circuit int: total size of columns in the circuit """ max_column_widths = [] for layer in self.ops: # store the max width for the layer current_max = 0 for op in layer: # update current op width arg_str_len = 0 # the wide gates for arg in op.op.params: arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, str(arg)) arg_str_len += len(arg_str) # the width of the column is the max of all the gates in the column current_max = max(arg_str_len, current_max) max_column_widths.append(current_max) # wires in the beginning and end columns = 2 # each layer is one column columns += len(self.ops) # every 3 characters is roughly one extra 'unit' of width in the cell # the gate name is 1 extra 'unit' # the qubit/cbit labels plus initial states is 2 more # the wires poking out at the ends is 2 more sum_column_widths = sum(1 + v / 3 for v in max_column_widths) # could be a fraction so ceil return columns, math.ceil(sum_column_widths) + 4
def _get_image_depth(self): """Get depth information for the circuit. Returns: int: number of columns in the circuit int: total size of columns in the circuit """ max_column_widths = [] for layer in self.ops: # store the max width for the layer current_max = 0 for op in layer: # update current op width arg_str_len = 0 # the wide gates for arg in op.op.params: arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, str(arg)) arg_str_len += len(arg_str) # the width of the column is the max of all the gates in the column current_max = max(arg_str_len, current_max) max_column_widths.append(current_max) # wires in the beginning and end columns = 2 # each layer is one column columns += len(self.ops) # every 3 characters is roughly one extra 'unit' of width in the cell # the gate name is 1 extra 'unit' # the qubit/cbit labels plus initial states is 2 more # the wires poking out at the ends is 2 more sum_column_widths = sum(1 + v / 3 for v in max_column_widths) # could be a fraction so ceil return columns, math.ceil(sum_column_widths) + 4
[ "Get", "depth", "information", "for", "the", "circuit", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/latex.py#L208-L251
[ "def", "_get_image_depth", "(", "self", ")", ":", "max_column_widths", "=", "[", "]", "for", "layer", "in", "self", ".", "ops", ":", "# store the max width for the layer", "current_max", "=", "0", "for", "op", "in", "layer", ":", "# update current op width", "arg_str_len", "=", "0", "# the wide gates", "for", "arg", "in", "op", ".", "op", ".", "params", ":", "arg_str", "=", "re", ".", "sub", "(", "r'[-+]?\\d*\\.\\d{2,}|\\d{2,}'", ",", "_truncate_float", ",", "str", "(", "arg", ")", ")", "arg_str_len", "+=", "len", "(", "arg_str", ")", "# the width of the column is the max of all the gates in the column", "current_max", "=", "max", "(", "arg_str_len", ",", "current_max", ")", "max_column_widths", ".", "append", "(", "current_max", ")", "# wires in the beginning and end", "columns", "=", "2", "# each layer is one column", "columns", "+=", "len", "(", "self", ".", "ops", ")", "# every 3 characters is roughly one extra 'unit' of width in the cell", "# the gate name is 1 extra 'unit'", "# the qubit/cbit labels plus initial states is 2 more", "# the wires poking out at the ends is 2 more", "sum_column_widths", "=", "sum", "(", "1", "+", "v", "/", "3", "for", "v", "in", "max_column_widths", ")", "# could be a fraction so ceil", "return", "columns", ",", "math", ".", "ceil", "(", "sum_column_widths", ")", "+", "4" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QCircuitImage._get_beamer_page
Get height, width & scale attributes for the beamer page. Returns: tuple: (height, width, scale) desirable page attributes
qiskit/visualization/latex.py
def _get_beamer_page(self): """Get height, width & scale attributes for the beamer page. Returns: tuple: (height, width, scale) desirable page attributes """ # PIL python package limits image size to around a quarter gigabyte # this means the beamer image should be limited to < 50000 # if you want to avoid a "warning" too, set it to < 25000 PIL_limit = 40000 # the beamer latex template limits each dimension to < 19 feet # (i.e. 575cm) beamer_limit = 550 # columns are roughly twice as big as rows aspect_ratio = self.sum_row_heights / self.sum_column_widths # choose a page margin so circuit is not cropped margin_factor = 1.5 height = min(self.sum_row_heights * margin_factor, beamer_limit) width = min(self.sum_column_widths * margin_factor, beamer_limit) # if too large, make it fit if height * width > PIL_limit: height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit) width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit) # if too small, give it a minimum size height = max(height, 10) width = max(width, 10) return (height, width, self.scale)
def _get_beamer_page(self): """Get height, width & scale attributes for the beamer page. Returns: tuple: (height, width, scale) desirable page attributes """ # PIL python package limits image size to around a quarter gigabyte # this means the beamer image should be limited to < 50000 # if you want to avoid a "warning" too, set it to < 25000 PIL_limit = 40000 # the beamer latex template limits each dimension to < 19 feet # (i.e. 575cm) beamer_limit = 550 # columns are roughly twice as big as rows aspect_ratio = self.sum_row_heights / self.sum_column_widths # choose a page margin so circuit is not cropped margin_factor = 1.5 height = min(self.sum_row_heights * margin_factor, beamer_limit) width = min(self.sum_column_widths * margin_factor, beamer_limit) # if too large, make it fit if height * width > PIL_limit: height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit) width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit) # if too small, give it a minimum size height = max(height, 10) width = max(width, 10) return (height, width, self.scale)
[ "Get", "height", "width", "&", "scale", "attributes", "for", "the", "beamer", "page", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/latex.py#L253-L285
[ "def", "_get_beamer_page", "(", "self", ")", ":", "# PIL python package limits image size to around a quarter gigabyte", "# this means the beamer image should be limited to < 50000", "# if you want to avoid a \"warning\" too, set it to < 25000", "PIL_limit", "=", "40000", "# the beamer latex template limits each dimension to < 19 feet", "# (i.e. 575cm)", "beamer_limit", "=", "550", "# columns are roughly twice as big as rows", "aspect_ratio", "=", "self", ".", "sum_row_heights", "/", "self", ".", "sum_column_widths", "# choose a page margin so circuit is not cropped", "margin_factor", "=", "1.5", "height", "=", "min", "(", "self", ".", "sum_row_heights", "*", "margin_factor", ",", "beamer_limit", ")", "width", "=", "min", "(", "self", ".", "sum_column_widths", "*", "margin_factor", ",", "beamer_limit", ")", "# if too large, make it fit", "if", "height", "*", "width", ">", "PIL_limit", ":", "height", "=", "min", "(", "np", ".", "sqrt", "(", "PIL_limit", "*", "aspect_ratio", ")", ",", "beamer_limit", ")", "width", "=", "min", "(", "np", ".", "sqrt", "(", "PIL_limit", "/", "aspect_ratio", ")", ",", "beamer_limit", ")", "# if too small, give it a minimum size", "height", "=", "max", "(", "height", ",", "10", ")", "width", "=", "max", "(", "width", ",", "10", ")", "return", "(", "height", ",", "width", ",", "self", ".", "scale", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QCircuitImage._build_latex_array
Returns an array of strings containing \\LaTeX for this circuit. If aliases is not None, aliases contains a dict mapping the current qubits in the circuit to new qubit names. We will deduce the register names and sizes from aliases.
qiskit/visualization/latex.py
def _build_latex_array(self, aliases=None): """Returns an array of strings containing \\LaTeX for this circuit. If aliases is not None, aliases contains a dict mapping the current qubits in the circuit to new qubit names. We will deduce the register names and sizes from aliases. """ columns = 1 # Rename qregs if necessary if aliases: qregdata = {} for q in aliases.values(): if q[0] not in qregdata: qregdata[q[0]] = q[1] + 1 elif qregdata[q[0]] < q[1] + 1: qregdata[q[0]] = q[1] + 1 else: qregdata = self.qregs for column, layer in enumerate(self.ops, 1): for op in layer: if op.condition: mask = self._get_mask(op.condition[0]) cl_reg = self.clbit_list[self._ffs(mask)] if_reg = cl_reg[0] pos_2 = self.img_regs[cl_reg] if_value = format(op.condition[1], 'b').zfill(self.cregs[if_reg])[::-1] if op.name not in ['measure', 'barrier', 'snapshot', 'load', 'save', 'noise']: nm = op.name qarglist = op.qargs if aliases is not None: qarglist = map(lambda x: aliases[x], qarglist) if len(qarglist) == 1: pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])] if op.condition: mask = self._get_mask(op.condition[0]) cl_reg = self.clbit_list[self._ffs(mask)] if_reg = cl_reg[0] pos_2 = self.img_regs[cl_reg] if nm == "x": self._latex[pos_1][column] = "\\gate{X}" elif nm == "y": self._latex[pos_1][column] = "\\gate{Y}" elif nm == "z": self._latex[pos_1][column] = "\\gate{Z}" elif nm == "h": self._latex[pos_1][column] = "\\gate{H}" elif nm == "s": self._latex[pos_1][column] = "\\gate{S}" elif nm == "sdg": self._latex[pos_1][column] = "\\gate{S^\\dag}" elif nm == "t": self._latex[pos_1][column] = "\\gate{T}" elif nm == "tdg": self._latex[pos_1][column] = "\\gate{T^\\dag}" elif nm == "u0": self._latex[pos_1][column] = "\\gate{U_0(%s)}" % ( op.op.params[0]) elif nm == "u1": self._latex[pos_1][column] = "\\gate{U_1(%s)}" % ( op.op.params[0]) elif nm == "u2": self._latex[pos_1][column] = \ "\\gate{U_2\\left(%s,%s\\right)}" % ( op.op.params[0], op.op.params[1]) elif nm == "u3": self._latex[pos_1][column] = ("\\gate{U_3(%s,%s,%s)}" % ( op.op.params[0], op.op.params[1], op.op.params[2])) elif nm == "rx": self._latex[pos_1][column] = "\\gate{R_x(%s)}" % ( op.op.params[0]) elif nm == "ry": self._latex[pos_1][column] = "\\gate{R_y(%s)}" % ( op.op.params[0]) elif nm == "rz": self._latex[pos_1][column] = "\\gate{R_z(%s)}" % ( op.op.params[0]) else: self._latex[pos_1][columns] = "\\gate{%s}" % nm gap = pos_2 - pos_1 for i in range(self.cregs[if_reg]): if if_value[i] == '1': self._latex[pos_2 + i][column] = \ "\\control \\cw \\cwx[-" + str(gap) + "]" gap = 1 else: self._latex[pos_2 + i][column] = \ "\\controlo \\cw \\cwx[-" + str(gap) + "]" gap = 1 else: if nm == "x": self._latex[pos_1][column] = "\\gate{X}" elif nm == "y": self._latex[pos_1][column] = "\\gate{Y}" elif nm == "z": self._latex[pos_1][column] = "\\gate{Z}" elif nm == "h": self._latex[pos_1][column] = "\\gate{H}" elif nm == "s": self._latex[pos_1][column] = "\\gate{S}" elif nm == "sdg": self._latex[pos_1][column] = "\\gate{S^\\dag}" elif nm == "t": self._latex[pos_1][column] = "\\gate{T}" elif nm == "tdg": self._latex[pos_1][column] = "\\gate{T^\\dag}" elif nm == "u0": self._latex[pos_1][column] = "\\gate{U_0(%s)}" % ( op.op.params[0]) elif nm == "u1": self._latex[pos_1][column] = "\\gate{U_1(%s)}" % ( op.op.params[0]) elif nm == "u2": self._latex[pos_1][column] = \ "\\gate{U_2\\left(%s,%s\\right)}" % ( op.op.params[0], op.op.params[1]) elif nm == "u3": self._latex[pos_1][column] = ("\\gate{U_3(%s,%s,%s)}" % ( op.op.params[0], op.op.params[1], op.op.params[2])) elif nm == "rx": self._latex[pos_1][column] = "\\gate{R_x(%s)}" % ( op.op.params[0]) elif nm == "ry": self._latex[pos_1][column] = "\\gate{R_y(%s)}" % ( op.op.params[0]) elif nm == "rz": self._latex[pos_1][column] = "\\gate{R_z(%s)}" % ( op.op.params[0]) elif nm == "reset": self._latex[pos_1][column] = ( "\\push{\\rule{.6em}{0em}\\ket{0}\\" "rule{.2em}{0em}} \\qw") else: self._latex[pos_1][columns] = "\\gate{%s}" % nm elif len(qarglist) == 2: pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])] pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])] if op.condition: pos_3 = self.img_regs[(if_reg, 0)] temp = [pos_1, pos_2, pos_3] temp.sort(key=int) bottom = temp[1] gap = pos_3 - bottom for i in range(self.cregs[if_reg]): if if_value[i] == '1': self._latex[pos_3 + i][column] = \ "\\control \\cw \\cwx[-" + str(gap) + "]" gap = 1 else: self._latex[pos_3 + i][column] = \ "\\controlo \\cw \\cwx[-" + str(gap) + "]" gap = 1 if nm == "cx": self._latex[pos_1][column] = \ "\\ctrl{" + str(pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\targ" elif nm == "cz": self._latex[pos_1][column] = \ "\\ctrl{" + str(pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\control\\qw" elif nm == "cy": self._latex[pos_1][column] = \ "\\ctrl{" + str(pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\gate{Y}" elif nm == "ch": self._latex[pos_1][column] = \ "\\ctrl{" + str(pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\gate{H}" elif nm == "swap": self._latex[pos_1][column] = "\\qswap" self._latex[pos_2][column] = \ "\\qswap \\qwx[" + str(pos_1 - pos_2) + "]" elif nm == "crz": self._latex[pos_1][column] = \ "\\ctrl{" + str(pos_2 - pos_1) + "}" self._latex[pos_2][column] = \ "\\gate{R_z(%s)}" % (op.op.params[0]) elif nm == "cu1": self._latex[pos_1][column - 1] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column - 1] = "\\control\\qw" self._latex[min(pos_1, pos_2)][column] = \ "\\dstick{%s}\\qw" % (op.op.params[0]) self._latex[max(pos_1, pos_2)][column] = "\\qw" elif nm == "cu3": self._latex[pos_1][column] = \ "\\ctrl{" + str(pos_2 - pos_1) + "}" self._latex[pos_2][column] = \ "\\gate{U_3(%s,%s,%s)}" % (op.op.params[0], op.op.params[1], op.op.params[2]) else: temp = [pos_1, pos_2] temp.sort(key=int) if nm == "cx": self._latex[pos_1][column] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\targ" elif nm == "cz": self._latex[pos_1][column] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\control\\qw" elif nm == "cy": self._latex[pos_1][column] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\gate{Y}" elif nm == "ch": self._latex[pos_1][column] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\gate{H}" elif nm == "swap": self._latex[pos_1][column] = "\\qswap" self._latex[pos_2][column] = \ "\\qswap \\qwx[" + str(pos_1 - pos_2) + "]" elif nm == "crz": self._latex[pos_1][column] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column] = \ "\\gate{R_z(%s)}" % (op.op.params[0]) elif nm == "cu1": self._latex[pos_1][column - 1] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column - 1] = "\\control\\qw" self._latex[min(pos_1, pos_2)][column] = \ "\\dstick{%s}\\qw" % (op.op.params[0]) self._latex[max(pos_1, pos_2)][column] = "\\qw" elif nm == "cu3": self._latex[pos_1][column] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column] = ("\\gate{U_3(%s,%s,%s)}" % ( op.op.params[0], op.op.params[1], op.op.params[2])) else: start_pos = min([pos_1, pos_2]) stop_pos = max([pos_1, pos_2]) if stop_pos - start_pos >= 2: delta = stop_pos - start_pos self._latex[start_pos][columns] = ( "\\multigate{%s}{%s}" % (delta, nm)) for i_pos in range(start_pos + 1, stop_pos + 1): self._latex[i_pos][columns] = "\\ghost{%s}" % nm else: self._latex[start_pos][columns] = ( "\\multigate{1}{%s}" % nm) self._latex[stop_pos][columns] = "\\ghost{%s}" % nm elif len(qarglist) == 3: pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])] pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])] pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])] if op.condition: pos_4 = self.img_regs[(if_reg, 0)] temp = [pos_1, pos_2, pos_3, pos_4] temp.sort(key=int) bottom = temp[2] prev_column = [x[column - 1] for x in self._latex] for item, prev_entry in enumerate(prev_column): if 'barrier' in prev_entry: span = re.search('barrier{(.*)}', prev_entry) if span and any(i in temp for i in range( item, int(span.group(1)))): self._latex[item][column - 1] = \ prev_entry.replace( '\\barrier{', '\\barrier[-0.65em]{') gap = pos_4 - bottom for i in range(self.cregs[if_reg]): if if_value[i] == '1': self._latex[pos_4 + i][column] = \ "\\control \\cw \\cwx[-" + str(gap) + "]" gap = 1 else: self._latex[pos_4 + i][column] = \ "\\controlo \\cw \\cwx[-" + str(gap) + "]" gap = 1 if nm == "ccx": self._latex[pos_1][column] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\ctrl{" + str( pos_3 - pos_2) + "}" self._latex[pos_3][column] = "\\targ" if nm == "cswap": self._latex[pos_1][column] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\qswap" self._latex[pos_3][column] = \ "\\qswap \\qwx[" + str(pos_2 - pos_3) + "]" else: temp = [pos_1, pos_2, pos_3] temp.sort(key=int) prev_column = [x[column - 1] for x in self._latex] for item, prev_entry in enumerate(prev_column): if 'barrier' in prev_entry: span = re.search('barrier{(.*)}', prev_entry) if span and any(i in temp for i in range( item, int(span.group(1)))): self._latex[item][column - 1] = \ prev_entry.replace( '\\barrier{', '\\barrier[-0.65em]{') if nm == "ccx": self._latex[pos_1][column] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\ctrl{" + str( pos_3 - pos_2) + "}" self._latex[pos_3][column] = "\\targ" elif nm == "cswap": self._latex[pos_1][column] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\qswap" self._latex[pos_3][column] = \ "\\qswap \\qwx[" + str(pos_2 - pos_3) + "]" else: start_pos = min([pos_1, pos_2, pos_3]) stop_pos = max([pos_1, pos_2, pos_3]) if stop_pos - start_pos >= 3: delta = stop_pos - start_pos self._latex[start_pos][columns] = ( "\\multigate{%s}{%s}" % (delta, nm)) for i_pos in range(start_pos + 1, stop_pos + 1): self._latex[i_pos][columns] = "\\ghost{%s}" % nm else: self._latex[pos_1][columns] = ( "\\multigate{2}{%s}" % nm) self._latex[pos_2][columns] = "\\ghost{%s}" % nm self._latex[pos_3][columns] = "\\ghost{%s}" % nm elif len(qarglist) > 3: nbits = len(qarglist) pos_array = [self.img_regs[(qarglist[0][0], qarglist[0][1])]] for i in range(1, nbits): pos_array.append(self.img_regs[(qarglist[i][0], qarglist[i][1])]) pos_start = min(pos_array) pos_stop = max(pos_array) delta = pos_stop - pos_start self._latex[pos_start][columns] = ( "\\multigate{%s}{%s}" % (nbits - 1, nm)) for pos in range(pos_start + 1, pos_stop + 1): self._latex[pos][columns] = "\\ghost{%s}" % nm elif op.name == "measure": if (len(op.cargs) != 1 or len(op.qargs) != 1 or op.op.params): raise exceptions.VisualizationError("bad operation record") if op.condition: raise exceptions.VisualizationError( "If controlled measures currently not supported.") qname, qindex = op.qargs[0] cname, cindex = op.cargs[0] if aliases: newq = aliases[(qname, qindex)] qname = newq[0] qindex = newq[1] pos_1 = self.img_regs[(qname, qindex)] pos_2 = self.img_regs[(cname, cindex)] try: self._latex[pos_1][column] = "\\meter" prev_column = [x[column - 1] for x in self._latex] for item, prev_entry in enumerate(prev_column): if 'barrier' in prev_entry: span = re.search('barrier{(.*)}', prev_entry) if span and ( item + int(span.group(1))) - pos_1 >= 0: self._latex[item][column - 1] = \ prev_entry.replace( '\\barrier{', '\\barrier[-1.15em]{') self._latex[pos_2][column] = \ "\\cw \\cwx[-" + str(pos_2 - pos_1) + "]" except Exception as e: raise exceptions.VisualizationError( 'Error during Latex building: %s' % str(e)) elif op.name in ['barrier', 'snapshot', 'load', 'save', 'noise']: if self.plot_barriers: qarglist = op.qargs indexes = [self._get_qubit_index(x) for x in qarglist] start_bit = self.qubit_list[min(indexes)] if aliases is not None: qarglist = map(lambda x: aliases[x], qarglist) start = self.img_regs[start_bit] span = len(op.qargs) - 1 self._latex[start][column] = "\\qw \\barrier{" + str( span) + "}" else: raise exceptions.VisualizationError("bad node data")
def _build_latex_array(self, aliases=None): """Returns an array of strings containing \\LaTeX for this circuit. If aliases is not None, aliases contains a dict mapping the current qubits in the circuit to new qubit names. We will deduce the register names and sizes from aliases. """ columns = 1 # Rename qregs if necessary if aliases: qregdata = {} for q in aliases.values(): if q[0] not in qregdata: qregdata[q[0]] = q[1] + 1 elif qregdata[q[0]] < q[1] + 1: qregdata[q[0]] = q[1] + 1 else: qregdata = self.qregs for column, layer in enumerate(self.ops, 1): for op in layer: if op.condition: mask = self._get_mask(op.condition[0]) cl_reg = self.clbit_list[self._ffs(mask)] if_reg = cl_reg[0] pos_2 = self.img_regs[cl_reg] if_value = format(op.condition[1], 'b').zfill(self.cregs[if_reg])[::-1] if op.name not in ['measure', 'barrier', 'snapshot', 'load', 'save', 'noise']: nm = op.name qarglist = op.qargs if aliases is not None: qarglist = map(lambda x: aliases[x], qarglist) if len(qarglist) == 1: pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])] if op.condition: mask = self._get_mask(op.condition[0]) cl_reg = self.clbit_list[self._ffs(mask)] if_reg = cl_reg[0] pos_2 = self.img_regs[cl_reg] if nm == "x": self._latex[pos_1][column] = "\\gate{X}" elif nm == "y": self._latex[pos_1][column] = "\\gate{Y}" elif nm == "z": self._latex[pos_1][column] = "\\gate{Z}" elif nm == "h": self._latex[pos_1][column] = "\\gate{H}" elif nm == "s": self._latex[pos_1][column] = "\\gate{S}" elif nm == "sdg": self._latex[pos_1][column] = "\\gate{S^\\dag}" elif nm == "t": self._latex[pos_1][column] = "\\gate{T}" elif nm == "tdg": self._latex[pos_1][column] = "\\gate{T^\\dag}" elif nm == "u0": self._latex[pos_1][column] = "\\gate{U_0(%s)}" % ( op.op.params[0]) elif nm == "u1": self._latex[pos_1][column] = "\\gate{U_1(%s)}" % ( op.op.params[0]) elif nm == "u2": self._latex[pos_1][column] = \ "\\gate{U_2\\left(%s,%s\\right)}" % ( op.op.params[0], op.op.params[1]) elif nm == "u3": self._latex[pos_1][column] = ("\\gate{U_3(%s,%s,%s)}" % ( op.op.params[0], op.op.params[1], op.op.params[2])) elif nm == "rx": self._latex[pos_1][column] = "\\gate{R_x(%s)}" % ( op.op.params[0]) elif nm == "ry": self._latex[pos_1][column] = "\\gate{R_y(%s)}" % ( op.op.params[0]) elif nm == "rz": self._latex[pos_1][column] = "\\gate{R_z(%s)}" % ( op.op.params[0]) else: self._latex[pos_1][columns] = "\\gate{%s}" % nm gap = pos_2 - pos_1 for i in range(self.cregs[if_reg]): if if_value[i] == '1': self._latex[pos_2 + i][column] = \ "\\control \\cw \\cwx[-" + str(gap) + "]" gap = 1 else: self._latex[pos_2 + i][column] = \ "\\controlo \\cw \\cwx[-" + str(gap) + "]" gap = 1 else: if nm == "x": self._latex[pos_1][column] = "\\gate{X}" elif nm == "y": self._latex[pos_1][column] = "\\gate{Y}" elif nm == "z": self._latex[pos_1][column] = "\\gate{Z}" elif nm == "h": self._latex[pos_1][column] = "\\gate{H}" elif nm == "s": self._latex[pos_1][column] = "\\gate{S}" elif nm == "sdg": self._latex[pos_1][column] = "\\gate{S^\\dag}" elif nm == "t": self._latex[pos_1][column] = "\\gate{T}" elif nm == "tdg": self._latex[pos_1][column] = "\\gate{T^\\dag}" elif nm == "u0": self._latex[pos_1][column] = "\\gate{U_0(%s)}" % ( op.op.params[0]) elif nm == "u1": self._latex[pos_1][column] = "\\gate{U_1(%s)}" % ( op.op.params[0]) elif nm == "u2": self._latex[pos_1][column] = \ "\\gate{U_2\\left(%s,%s\\right)}" % ( op.op.params[0], op.op.params[1]) elif nm == "u3": self._latex[pos_1][column] = ("\\gate{U_3(%s,%s,%s)}" % ( op.op.params[0], op.op.params[1], op.op.params[2])) elif nm == "rx": self._latex[pos_1][column] = "\\gate{R_x(%s)}" % ( op.op.params[0]) elif nm == "ry": self._latex[pos_1][column] = "\\gate{R_y(%s)}" % ( op.op.params[0]) elif nm == "rz": self._latex[pos_1][column] = "\\gate{R_z(%s)}" % ( op.op.params[0]) elif nm == "reset": self._latex[pos_1][column] = ( "\\push{\\rule{.6em}{0em}\\ket{0}\\" "rule{.2em}{0em}} \\qw") else: self._latex[pos_1][columns] = "\\gate{%s}" % nm elif len(qarglist) == 2: pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])] pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])] if op.condition: pos_3 = self.img_regs[(if_reg, 0)] temp = [pos_1, pos_2, pos_3] temp.sort(key=int) bottom = temp[1] gap = pos_3 - bottom for i in range(self.cregs[if_reg]): if if_value[i] == '1': self._latex[pos_3 + i][column] = \ "\\control \\cw \\cwx[-" + str(gap) + "]" gap = 1 else: self._latex[pos_3 + i][column] = \ "\\controlo \\cw \\cwx[-" + str(gap) + "]" gap = 1 if nm == "cx": self._latex[pos_1][column] = \ "\\ctrl{" + str(pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\targ" elif nm == "cz": self._latex[pos_1][column] = \ "\\ctrl{" + str(pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\control\\qw" elif nm == "cy": self._latex[pos_1][column] = \ "\\ctrl{" + str(pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\gate{Y}" elif nm == "ch": self._latex[pos_1][column] = \ "\\ctrl{" + str(pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\gate{H}" elif nm == "swap": self._latex[pos_1][column] = "\\qswap" self._latex[pos_2][column] = \ "\\qswap \\qwx[" + str(pos_1 - pos_2) + "]" elif nm == "crz": self._latex[pos_1][column] = \ "\\ctrl{" + str(pos_2 - pos_1) + "}" self._latex[pos_2][column] = \ "\\gate{R_z(%s)}" % (op.op.params[0]) elif nm == "cu1": self._latex[pos_1][column - 1] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column - 1] = "\\control\\qw" self._latex[min(pos_1, pos_2)][column] = \ "\\dstick{%s}\\qw" % (op.op.params[0]) self._latex[max(pos_1, pos_2)][column] = "\\qw" elif nm == "cu3": self._latex[pos_1][column] = \ "\\ctrl{" + str(pos_2 - pos_1) + "}" self._latex[pos_2][column] = \ "\\gate{U_3(%s,%s,%s)}" % (op.op.params[0], op.op.params[1], op.op.params[2]) else: temp = [pos_1, pos_2] temp.sort(key=int) if nm == "cx": self._latex[pos_1][column] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\targ" elif nm == "cz": self._latex[pos_1][column] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\control\\qw" elif nm == "cy": self._latex[pos_1][column] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\gate{Y}" elif nm == "ch": self._latex[pos_1][column] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\gate{H}" elif nm == "swap": self._latex[pos_1][column] = "\\qswap" self._latex[pos_2][column] = \ "\\qswap \\qwx[" + str(pos_1 - pos_2) + "]" elif nm == "crz": self._latex[pos_1][column] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column] = \ "\\gate{R_z(%s)}" % (op.op.params[0]) elif nm == "cu1": self._latex[pos_1][column - 1] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column - 1] = "\\control\\qw" self._latex[min(pos_1, pos_2)][column] = \ "\\dstick{%s}\\qw" % (op.op.params[0]) self._latex[max(pos_1, pos_2)][column] = "\\qw" elif nm == "cu3": self._latex[pos_1][column] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column] = ("\\gate{U_3(%s,%s,%s)}" % ( op.op.params[0], op.op.params[1], op.op.params[2])) else: start_pos = min([pos_1, pos_2]) stop_pos = max([pos_1, pos_2]) if stop_pos - start_pos >= 2: delta = stop_pos - start_pos self._latex[start_pos][columns] = ( "\\multigate{%s}{%s}" % (delta, nm)) for i_pos in range(start_pos + 1, stop_pos + 1): self._latex[i_pos][columns] = "\\ghost{%s}" % nm else: self._latex[start_pos][columns] = ( "\\multigate{1}{%s}" % nm) self._latex[stop_pos][columns] = "\\ghost{%s}" % nm elif len(qarglist) == 3: pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])] pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])] pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])] if op.condition: pos_4 = self.img_regs[(if_reg, 0)] temp = [pos_1, pos_2, pos_3, pos_4] temp.sort(key=int) bottom = temp[2] prev_column = [x[column - 1] for x in self._latex] for item, prev_entry in enumerate(prev_column): if 'barrier' in prev_entry: span = re.search('barrier{(.*)}', prev_entry) if span and any(i in temp for i in range( item, int(span.group(1)))): self._latex[item][column - 1] = \ prev_entry.replace( '\\barrier{', '\\barrier[-0.65em]{') gap = pos_4 - bottom for i in range(self.cregs[if_reg]): if if_value[i] == '1': self._latex[pos_4 + i][column] = \ "\\control \\cw \\cwx[-" + str(gap) + "]" gap = 1 else: self._latex[pos_4 + i][column] = \ "\\controlo \\cw \\cwx[-" + str(gap) + "]" gap = 1 if nm == "ccx": self._latex[pos_1][column] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\ctrl{" + str( pos_3 - pos_2) + "}" self._latex[pos_3][column] = "\\targ" if nm == "cswap": self._latex[pos_1][column] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\qswap" self._latex[pos_3][column] = \ "\\qswap \\qwx[" + str(pos_2 - pos_3) + "]" else: temp = [pos_1, pos_2, pos_3] temp.sort(key=int) prev_column = [x[column - 1] for x in self._latex] for item, prev_entry in enumerate(prev_column): if 'barrier' in prev_entry: span = re.search('barrier{(.*)}', prev_entry) if span and any(i in temp for i in range( item, int(span.group(1)))): self._latex[item][column - 1] = \ prev_entry.replace( '\\barrier{', '\\barrier[-0.65em]{') if nm == "ccx": self._latex[pos_1][column] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\ctrl{" + str( pos_3 - pos_2) + "}" self._latex[pos_3][column] = "\\targ" elif nm == "cswap": self._latex[pos_1][column] = "\\ctrl{" + str( pos_2 - pos_1) + "}" self._latex[pos_2][column] = "\\qswap" self._latex[pos_3][column] = \ "\\qswap \\qwx[" + str(pos_2 - pos_3) + "]" else: start_pos = min([pos_1, pos_2, pos_3]) stop_pos = max([pos_1, pos_2, pos_3]) if stop_pos - start_pos >= 3: delta = stop_pos - start_pos self._latex[start_pos][columns] = ( "\\multigate{%s}{%s}" % (delta, nm)) for i_pos in range(start_pos + 1, stop_pos + 1): self._latex[i_pos][columns] = "\\ghost{%s}" % nm else: self._latex[pos_1][columns] = ( "\\multigate{2}{%s}" % nm) self._latex[pos_2][columns] = "\\ghost{%s}" % nm self._latex[pos_3][columns] = "\\ghost{%s}" % nm elif len(qarglist) > 3: nbits = len(qarglist) pos_array = [self.img_regs[(qarglist[0][0], qarglist[0][1])]] for i in range(1, nbits): pos_array.append(self.img_regs[(qarglist[i][0], qarglist[i][1])]) pos_start = min(pos_array) pos_stop = max(pos_array) delta = pos_stop - pos_start self._latex[pos_start][columns] = ( "\\multigate{%s}{%s}" % (nbits - 1, nm)) for pos in range(pos_start + 1, pos_stop + 1): self._latex[pos][columns] = "\\ghost{%s}" % nm elif op.name == "measure": if (len(op.cargs) != 1 or len(op.qargs) != 1 or op.op.params): raise exceptions.VisualizationError("bad operation record") if op.condition: raise exceptions.VisualizationError( "If controlled measures currently not supported.") qname, qindex = op.qargs[0] cname, cindex = op.cargs[0] if aliases: newq = aliases[(qname, qindex)] qname = newq[0] qindex = newq[1] pos_1 = self.img_regs[(qname, qindex)] pos_2 = self.img_regs[(cname, cindex)] try: self._latex[pos_1][column] = "\\meter" prev_column = [x[column - 1] for x in self._latex] for item, prev_entry in enumerate(prev_column): if 'barrier' in prev_entry: span = re.search('barrier{(.*)}', prev_entry) if span and ( item + int(span.group(1))) - pos_1 >= 0: self._latex[item][column - 1] = \ prev_entry.replace( '\\barrier{', '\\barrier[-1.15em]{') self._latex[pos_2][column] = \ "\\cw \\cwx[-" + str(pos_2 - pos_1) + "]" except Exception as e: raise exceptions.VisualizationError( 'Error during Latex building: %s' % str(e)) elif op.name in ['barrier', 'snapshot', 'load', 'save', 'noise']: if self.plot_barriers: qarglist = op.qargs indexes = [self._get_qubit_index(x) for x in qarglist] start_bit = self.qubit_list[min(indexes)] if aliases is not None: qarglist = map(lambda x: aliases[x], qarglist) start = self.img_regs[start_bit] span = len(op.qargs) - 1 self._latex[start][column] = "\\qw \\barrier{" + str( span) + "}" else: raise exceptions.VisualizationError("bad node data")
[ "Returns", "an", "array", "of", "strings", "containing", "\\\\", "LaTeX", "for", "this", "circuit", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/latex.py#L294-L716
[ "def", "_build_latex_array", "(", "self", ",", "aliases", "=", "None", ")", ":", "columns", "=", "1", "# Rename qregs if necessary", "if", "aliases", ":", "qregdata", "=", "{", "}", "for", "q", "in", "aliases", ".", "values", "(", ")", ":", "if", "q", "[", "0", "]", "not", "in", "qregdata", ":", "qregdata", "[", "q", "[", "0", "]", "]", "=", "q", "[", "1", "]", "+", "1", "elif", "qregdata", "[", "q", "[", "0", "]", "]", "<", "q", "[", "1", "]", "+", "1", ":", "qregdata", "[", "q", "[", "0", "]", "]", "=", "q", "[", "1", "]", "+", "1", "else", ":", "qregdata", "=", "self", ".", "qregs", "for", "column", ",", "layer", "in", "enumerate", "(", "self", ".", "ops", ",", "1", ")", ":", "for", "op", "in", "layer", ":", "if", "op", ".", "condition", ":", "mask", "=", "self", ".", "_get_mask", "(", "op", ".", "condition", "[", "0", "]", ")", "cl_reg", "=", "self", ".", "clbit_list", "[", "self", ".", "_ffs", "(", "mask", ")", "]", "if_reg", "=", "cl_reg", "[", "0", "]", "pos_2", "=", "self", ".", "img_regs", "[", "cl_reg", "]", "if_value", "=", "format", "(", "op", ".", "condition", "[", "1", "]", ",", "'b'", ")", ".", "zfill", "(", "self", ".", "cregs", "[", "if_reg", "]", ")", "[", ":", ":", "-", "1", "]", "if", "op", ".", "name", "not", "in", "[", "'measure'", ",", "'barrier'", ",", "'snapshot'", ",", "'load'", ",", "'save'", ",", "'noise'", "]", ":", "nm", "=", "op", ".", "name", "qarglist", "=", "op", ".", "qargs", "if", "aliases", "is", "not", "None", ":", "qarglist", "=", "map", "(", "lambda", "x", ":", "aliases", "[", "x", "]", ",", "qarglist", ")", "if", "len", "(", "qarglist", ")", "==", "1", ":", "pos_1", "=", "self", ".", "img_regs", "[", "(", "qarglist", "[", "0", "]", "[", "0", "]", ",", "qarglist", "[", "0", "]", "[", "1", "]", ")", "]", "if", "op", ".", "condition", ":", "mask", "=", "self", ".", "_get_mask", "(", "op", ".", "condition", "[", "0", "]", ")", "cl_reg", "=", "self", ".", "clbit_list", "[", "self", ".", "_ffs", "(", "mask", ")", "]", "if_reg", "=", "cl_reg", "[", "0", "]", "pos_2", "=", "self", ".", "img_regs", "[", "cl_reg", "]", "if", "nm", "==", "\"x\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{X}\"", "elif", "nm", "==", "\"y\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{Y}\"", "elif", "nm", "==", "\"z\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{Z}\"", "elif", "nm", "==", "\"h\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{H}\"", "elif", "nm", "==", "\"s\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{S}\"", "elif", "nm", "==", "\"sdg\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{S^\\\\dag}\"", "elif", "nm", "==", "\"t\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{T}\"", "elif", "nm", "==", "\"tdg\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{T^\\\\dag}\"", "elif", "nm", "==", "\"u0\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{U_0(%s)}\"", "%", "(", "op", ".", "op", ".", "params", "[", "0", "]", ")", "elif", "nm", "==", "\"u1\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{U_1(%s)}\"", "%", "(", "op", ".", "op", ".", "params", "[", "0", "]", ")", "elif", "nm", "==", "\"u2\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{U_2\\\\left(%s,%s\\\\right)}\"", "%", "(", "op", ".", "op", ".", "params", "[", "0", "]", ",", "op", ".", "op", ".", "params", "[", "1", "]", ")", "elif", "nm", "==", "\"u3\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "(", "\"\\\\gate{U_3(%s,%s,%s)}\"", "%", "(", "op", ".", "op", ".", "params", "[", "0", "]", ",", "op", ".", "op", ".", "params", "[", "1", "]", ",", "op", ".", "op", ".", "params", "[", "2", "]", ")", ")", "elif", "nm", "==", "\"rx\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{R_x(%s)}\"", "%", "(", "op", ".", "op", ".", "params", "[", "0", "]", ")", "elif", "nm", "==", "\"ry\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{R_y(%s)}\"", "%", "(", "op", ".", "op", ".", "params", "[", "0", "]", ")", "elif", "nm", "==", "\"rz\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{R_z(%s)}\"", "%", "(", "op", ".", "op", ".", "params", "[", "0", "]", ")", "else", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "columns", "]", "=", "\"\\\\gate{%s}\"", "%", "nm", "gap", "=", "pos_2", "-", "pos_1", "for", "i", "in", "range", "(", "self", ".", "cregs", "[", "if_reg", "]", ")", ":", "if", "if_value", "[", "i", "]", "==", "'1'", ":", "self", ".", "_latex", "[", "pos_2", "+", "i", "]", "[", "column", "]", "=", "\"\\\\control \\\\cw \\\\cwx[-\"", "+", "str", "(", "gap", ")", "+", "\"]\"", "gap", "=", "1", "else", ":", "self", ".", "_latex", "[", "pos_2", "+", "i", "]", "[", "column", "]", "=", "\"\\\\controlo \\\\cw \\\\cwx[-\"", "+", "str", "(", "gap", ")", "+", "\"]\"", "gap", "=", "1", "else", ":", "if", "nm", "==", "\"x\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{X}\"", "elif", "nm", "==", "\"y\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{Y}\"", "elif", "nm", "==", "\"z\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{Z}\"", "elif", "nm", "==", "\"h\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{H}\"", "elif", "nm", "==", "\"s\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{S}\"", "elif", "nm", "==", "\"sdg\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{S^\\\\dag}\"", "elif", "nm", "==", "\"t\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{T}\"", "elif", "nm", "==", "\"tdg\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{T^\\\\dag}\"", "elif", "nm", "==", "\"u0\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{U_0(%s)}\"", "%", "(", "op", ".", "op", ".", "params", "[", "0", "]", ")", "elif", "nm", "==", "\"u1\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{U_1(%s)}\"", "%", "(", "op", ".", "op", ".", "params", "[", "0", "]", ")", "elif", "nm", "==", "\"u2\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{U_2\\\\left(%s,%s\\\\right)}\"", "%", "(", "op", ".", "op", ".", "params", "[", "0", "]", ",", "op", ".", "op", ".", "params", "[", "1", "]", ")", "elif", "nm", "==", "\"u3\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "(", "\"\\\\gate{U_3(%s,%s,%s)}\"", "%", "(", "op", ".", "op", ".", "params", "[", "0", "]", ",", "op", ".", "op", ".", "params", "[", "1", "]", ",", "op", ".", "op", ".", "params", "[", "2", "]", ")", ")", "elif", "nm", "==", "\"rx\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{R_x(%s)}\"", "%", "(", "op", ".", "op", ".", "params", "[", "0", "]", ")", "elif", "nm", "==", "\"ry\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{R_y(%s)}\"", "%", "(", "op", ".", "op", ".", "params", "[", "0", "]", ")", "elif", "nm", "==", "\"rz\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\gate{R_z(%s)}\"", "%", "(", "op", ".", "op", ".", "params", "[", "0", "]", ")", "elif", "nm", "==", "\"reset\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "(", "\"\\\\push{\\\\rule{.6em}{0em}\\\\ket{0}\\\\\"", "\"rule{.2em}{0em}} \\\\qw\"", ")", "else", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "columns", "]", "=", "\"\\\\gate{%s}\"", "%", "nm", "elif", "len", "(", "qarglist", ")", "==", "2", ":", "pos_1", "=", "self", ".", "img_regs", "[", "(", "qarglist", "[", "0", "]", "[", "0", "]", ",", "qarglist", "[", "0", "]", "[", "1", "]", ")", "]", "pos_2", "=", "self", ".", "img_regs", "[", "(", "qarglist", "[", "1", "]", "[", "0", "]", ",", "qarglist", "[", "1", "]", "[", "1", "]", ")", "]", "if", "op", ".", "condition", ":", "pos_3", "=", "self", ".", "img_regs", "[", "(", "if_reg", ",", "0", ")", "]", "temp", "=", "[", "pos_1", ",", "pos_2", ",", "pos_3", "]", "temp", ".", "sort", "(", "key", "=", "int", ")", "bottom", "=", "temp", "[", "1", "]", "gap", "=", "pos_3", "-", "bottom", "for", "i", "in", "range", "(", "self", ".", "cregs", "[", "if_reg", "]", ")", ":", "if", "if_value", "[", "i", "]", "==", "'1'", ":", "self", ".", "_latex", "[", "pos_3", "+", "i", "]", "[", "column", "]", "=", "\"\\\\control \\\\cw \\\\cwx[-\"", "+", "str", "(", "gap", ")", "+", "\"]\"", "gap", "=", "1", "else", ":", "self", ".", "_latex", "[", "pos_3", "+", "i", "]", "[", "column", "]", "=", "\"\\\\controlo \\\\cw \\\\cwx[-\"", "+", "str", "(", "gap", ")", "+", "\"]\"", "gap", "=", "1", "if", "nm", "==", "\"cx\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\ctrl{\"", "+", "str", "(", "pos_2", "-", "pos_1", ")", "+", "\"}\"", "self", ".", "_latex", "[", "pos_2", "]", "[", "column", "]", "=", "\"\\\\targ\"", "elif", "nm", "==", "\"cz\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\ctrl{\"", "+", "str", "(", "pos_2", "-", "pos_1", ")", "+", "\"}\"", "self", ".", "_latex", "[", "pos_2", "]", "[", "column", "]", "=", "\"\\\\control\\\\qw\"", "elif", "nm", "==", "\"cy\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\ctrl{\"", "+", "str", "(", "pos_2", "-", "pos_1", ")", "+", "\"}\"", "self", ".", "_latex", "[", "pos_2", "]", "[", "column", "]", "=", "\"\\\\gate{Y}\"", "elif", "nm", "==", "\"ch\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\ctrl{\"", "+", "str", "(", "pos_2", "-", "pos_1", ")", "+", "\"}\"", "self", ".", "_latex", "[", "pos_2", "]", "[", "column", "]", "=", "\"\\\\gate{H}\"", "elif", "nm", "==", "\"swap\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\qswap\"", "self", ".", "_latex", "[", "pos_2", "]", "[", "column", "]", "=", "\"\\\\qswap \\\\qwx[\"", "+", "str", "(", "pos_1", "-", "pos_2", ")", "+", "\"]\"", "elif", "nm", "==", "\"crz\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\ctrl{\"", "+", "str", "(", "pos_2", "-", "pos_1", ")", "+", "\"}\"", "self", ".", "_latex", "[", "pos_2", "]", "[", "column", "]", "=", "\"\\\\gate{R_z(%s)}\"", "%", "(", "op", ".", "op", ".", "params", "[", "0", "]", ")", "elif", "nm", "==", "\"cu1\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "-", "1", "]", "=", "\"\\\\ctrl{\"", "+", "str", "(", "pos_2", "-", "pos_1", ")", "+", "\"}\"", "self", ".", "_latex", "[", "pos_2", "]", "[", "column", "-", "1", "]", "=", "\"\\\\control\\\\qw\"", "self", ".", "_latex", "[", "min", "(", "pos_1", ",", "pos_2", ")", "]", "[", "column", "]", "=", "\"\\\\dstick{%s}\\\\qw\"", "%", "(", "op", ".", "op", ".", "params", "[", "0", "]", ")", "self", ".", "_latex", "[", "max", "(", "pos_1", ",", "pos_2", ")", "]", "[", "column", "]", "=", "\"\\\\qw\"", "elif", "nm", "==", "\"cu3\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\ctrl{\"", "+", "str", "(", "pos_2", "-", "pos_1", ")", "+", "\"}\"", "self", ".", "_latex", "[", "pos_2", "]", "[", "column", "]", "=", "\"\\\\gate{U_3(%s,%s,%s)}\"", "%", "(", "op", ".", "op", ".", "params", "[", "0", "]", ",", "op", ".", "op", ".", "params", "[", "1", "]", ",", "op", ".", "op", ".", "params", "[", "2", "]", ")", "else", ":", "temp", "=", "[", "pos_1", ",", "pos_2", "]", "temp", ".", "sort", "(", "key", "=", "int", ")", "if", "nm", "==", "\"cx\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\ctrl{\"", "+", "str", "(", "pos_2", "-", "pos_1", ")", "+", "\"}\"", "self", ".", "_latex", "[", "pos_2", "]", "[", "column", "]", "=", "\"\\\\targ\"", "elif", "nm", "==", "\"cz\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\ctrl{\"", "+", "str", "(", "pos_2", "-", "pos_1", ")", "+", "\"}\"", "self", ".", "_latex", "[", "pos_2", "]", "[", "column", "]", "=", "\"\\\\control\\\\qw\"", "elif", "nm", "==", "\"cy\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\ctrl{\"", "+", "str", "(", "pos_2", "-", "pos_1", ")", "+", "\"}\"", "self", ".", "_latex", "[", "pos_2", "]", "[", "column", "]", "=", "\"\\\\gate{Y}\"", "elif", "nm", "==", "\"ch\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\ctrl{\"", "+", "str", "(", "pos_2", "-", "pos_1", ")", "+", "\"}\"", "self", ".", "_latex", "[", "pos_2", "]", "[", "column", "]", "=", "\"\\\\gate{H}\"", "elif", "nm", "==", "\"swap\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\qswap\"", "self", ".", "_latex", "[", "pos_2", "]", "[", "column", "]", "=", "\"\\\\qswap \\\\qwx[\"", "+", "str", "(", "pos_1", "-", "pos_2", ")", "+", "\"]\"", "elif", "nm", "==", "\"crz\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\ctrl{\"", "+", "str", "(", "pos_2", "-", "pos_1", ")", "+", "\"}\"", "self", ".", "_latex", "[", "pos_2", "]", "[", "column", "]", "=", "\"\\\\gate{R_z(%s)}\"", "%", "(", "op", ".", "op", ".", "params", "[", "0", "]", ")", "elif", "nm", "==", "\"cu1\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "-", "1", "]", "=", "\"\\\\ctrl{\"", "+", "str", "(", "pos_2", "-", "pos_1", ")", "+", "\"}\"", "self", ".", "_latex", "[", "pos_2", "]", "[", "column", "-", "1", "]", "=", "\"\\\\control\\\\qw\"", "self", ".", "_latex", "[", "min", "(", "pos_1", ",", "pos_2", ")", "]", "[", "column", "]", "=", "\"\\\\dstick{%s}\\\\qw\"", "%", "(", "op", ".", "op", ".", "params", "[", "0", "]", ")", "self", ".", "_latex", "[", "max", "(", "pos_1", ",", "pos_2", ")", "]", "[", "column", "]", "=", "\"\\\\qw\"", "elif", "nm", "==", "\"cu3\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\ctrl{\"", "+", "str", "(", "pos_2", "-", "pos_1", ")", "+", "\"}\"", "self", ".", "_latex", "[", "pos_2", "]", "[", "column", "]", "=", "(", "\"\\\\gate{U_3(%s,%s,%s)}\"", "%", "(", "op", ".", "op", ".", "params", "[", "0", "]", ",", "op", ".", "op", ".", "params", "[", "1", "]", ",", "op", ".", "op", ".", "params", "[", "2", "]", ")", ")", "else", ":", "start_pos", "=", "min", "(", "[", "pos_1", ",", "pos_2", "]", ")", "stop_pos", "=", "max", "(", "[", "pos_1", ",", "pos_2", "]", ")", "if", "stop_pos", "-", "start_pos", ">=", "2", ":", "delta", "=", "stop_pos", "-", "start_pos", "self", ".", "_latex", "[", "start_pos", "]", "[", "columns", "]", "=", "(", "\"\\\\multigate{%s}{%s}\"", "%", "(", "delta", ",", "nm", ")", ")", "for", "i_pos", "in", "range", "(", "start_pos", "+", "1", ",", "stop_pos", "+", "1", ")", ":", "self", ".", "_latex", "[", "i_pos", "]", "[", "columns", "]", "=", "\"\\\\ghost{%s}\"", "%", "nm", "else", ":", "self", ".", "_latex", "[", "start_pos", "]", "[", "columns", "]", "=", "(", "\"\\\\multigate{1}{%s}\"", "%", "nm", ")", "self", ".", "_latex", "[", "stop_pos", "]", "[", "columns", "]", "=", "\"\\\\ghost{%s}\"", "%", "nm", "elif", "len", "(", "qarglist", ")", "==", "3", ":", "pos_1", "=", "self", ".", "img_regs", "[", "(", "qarglist", "[", "0", "]", "[", "0", "]", ",", "qarglist", "[", "0", "]", "[", "1", "]", ")", "]", "pos_2", "=", "self", ".", "img_regs", "[", "(", "qarglist", "[", "1", "]", "[", "0", "]", ",", "qarglist", "[", "1", "]", "[", "1", "]", ")", "]", "pos_3", "=", "self", ".", "img_regs", "[", "(", "qarglist", "[", "2", "]", "[", "0", "]", ",", "qarglist", "[", "2", "]", "[", "1", "]", ")", "]", "if", "op", ".", "condition", ":", "pos_4", "=", "self", ".", "img_regs", "[", "(", "if_reg", ",", "0", ")", "]", "temp", "=", "[", "pos_1", ",", "pos_2", ",", "pos_3", ",", "pos_4", "]", "temp", ".", "sort", "(", "key", "=", "int", ")", "bottom", "=", "temp", "[", "2", "]", "prev_column", "=", "[", "x", "[", "column", "-", "1", "]", "for", "x", "in", "self", ".", "_latex", "]", "for", "item", ",", "prev_entry", "in", "enumerate", "(", "prev_column", ")", ":", "if", "'barrier'", "in", "prev_entry", ":", "span", "=", "re", ".", "search", "(", "'barrier{(.*)}'", ",", "prev_entry", ")", "if", "span", "and", "any", "(", "i", "in", "temp", "for", "i", "in", "range", "(", "item", ",", "int", "(", "span", ".", "group", "(", "1", ")", ")", ")", ")", ":", "self", ".", "_latex", "[", "item", "]", "[", "column", "-", "1", "]", "=", "prev_entry", ".", "replace", "(", "'\\\\barrier{'", ",", "'\\\\barrier[-0.65em]{'", ")", "gap", "=", "pos_4", "-", "bottom", "for", "i", "in", "range", "(", "self", ".", "cregs", "[", "if_reg", "]", ")", ":", "if", "if_value", "[", "i", "]", "==", "'1'", ":", "self", ".", "_latex", "[", "pos_4", "+", "i", "]", "[", "column", "]", "=", "\"\\\\control \\\\cw \\\\cwx[-\"", "+", "str", "(", "gap", ")", "+", "\"]\"", "gap", "=", "1", "else", ":", "self", ".", "_latex", "[", "pos_4", "+", "i", "]", "[", "column", "]", "=", "\"\\\\controlo \\\\cw \\\\cwx[-\"", "+", "str", "(", "gap", ")", "+", "\"]\"", "gap", "=", "1", "if", "nm", "==", "\"ccx\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\ctrl{\"", "+", "str", "(", "pos_2", "-", "pos_1", ")", "+", "\"}\"", "self", ".", "_latex", "[", "pos_2", "]", "[", "column", "]", "=", "\"\\\\ctrl{\"", "+", "str", "(", "pos_3", "-", "pos_2", ")", "+", "\"}\"", "self", ".", "_latex", "[", "pos_3", "]", "[", "column", "]", "=", "\"\\\\targ\"", "if", "nm", "==", "\"cswap\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\ctrl{\"", "+", "str", "(", "pos_2", "-", "pos_1", ")", "+", "\"}\"", "self", ".", "_latex", "[", "pos_2", "]", "[", "column", "]", "=", "\"\\\\qswap\"", "self", ".", "_latex", "[", "pos_3", "]", "[", "column", "]", "=", "\"\\\\qswap \\\\qwx[\"", "+", "str", "(", "pos_2", "-", "pos_3", ")", "+", "\"]\"", "else", ":", "temp", "=", "[", "pos_1", ",", "pos_2", ",", "pos_3", "]", "temp", ".", "sort", "(", "key", "=", "int", ")", "prev_column", "=", "[", "x", "[", "column", "-", "1", "]", "for", "x", "in", "self", ".", "_latex", "]", "for", "item", ",", "prev_entry", "in", "enumerate", "(", "prev_column", ")", ":", "if", "'barrier'", "in", "prev_entry", ":", "span", "=", "re", ".", "search", "(", "'barrier{(.*)}'", ",", "prev_entry", ")", "if", "span", "and", "any", "(", "i", "in", "temp", "for", "i", "in", "range", "(", "item", ",", "int", "(", "span", ".", "group", "(", "1", ")", ")", ")", ")", ":", "self", ".", "_latex", "[", "item", "]", "[", "column", "-", "1", "]", "=", "prev_entry", ".", "replace", "(", "'\\\\barrier{'", ",", "'\\\\barrier[-0.65em]{'", ")", "if", "nm", "==", "\"ccx\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\ctrl{\"", "+", "str", "(", "pos_2", "-", "pos_1", ")", "+", "\"}\"", "self", ".", "_latex", "[", "pos_2", "]", "[", "column", "]", "=", "\"\\\\ctrl{\"", "+", "str", "(", "pos_3", "-", "pos_2", ")", "+", "\"}\"", "self", ".", "_latex", "[", "pos_3", "]", "[", "column", "]", "=", "\"\\\\targ\"", "elif", "nm", "==", "\"cswap\"", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\ctrl{\"", "+", "str", "(", "pos_2", "-", "pos_1", ")", "+", "\"}\"", "self", ".", "_latex", "[", "pos_2", "]", "[", "column", "]", "=", "\"\\\\qswap\"", "self", ".", "_latex", "[", "pos_3", "]", "[", "column", "]", "=", "\"\\\\qswap \\\\qwx[\"", "+", "str", "(", "pos_2", "-", "pos_3", ")", "+", "\"]\"", "else", ":", "start_pos", "=", "min", "(", "[", "pos_1", ",", "pos_2", ",", "pos_3", "]", ")", "stop_pos", "=", "max", "(", "[", "pos_1", ",", "pos_2", ",", "pos_3", "]", ")", "if", "stop_pos", "-", "start_pos", ">=", "3", ":", "delta", "=", "stop_pos", "-", "start_pos", "self", ".", "_latex", "[", "start_pos", "]", "[", "columns", "]", "=", "(", "\"\\\\multigate{%s}{%s}\"", "%", "(", "delta", ",", "nm", ")", ")", "for", "i_pos", "in", "range", "(", "start_pos", "+", "1", ",", "stop_pos", "+", "1", ")", ":", "self", ".", "_latex", "[", "i_pos", "]", "[", "columns", "]", "=", "\"\\\\ghost{%s}\"", "%", "nm", "else", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "columns", "]", "=", "(", "\"\\\\multigate{2}{%s}\"", "%", "nm", ")", "self", ".", "_latex", "[", "pos_2", "]", "[", "columns", "]", "=", "\"\\\\ghost{%s}\"", "%", "nm", "self", ".", "_latex", "[", "pos_3", "]", "[", "columns", "]", "=", "\"\\\\ghost{%s}\"", "%", "nm", "elif", "len", "(", "qarglist", ")", ">", "3", ":", "nbits", "=", "len", "(", "qarglist", ")", "pos_array", "=", "[", "self", ".", "img_regs", "[", "(", "qarglist", "[", "0", "]", "[", "0", "]", ",", "qarglist", "[", "0", "]", "[", "1", "]", ")", "]", "]", "for", "i", "in", "range", "(", "1", ",", "nbits", ")", ":", "pos_array", ".", "append", "(", "self", ".", "img_regs", "[", "(", "qarglist", "[", "i", "]", "[", "0", "]", ",", "qarglist", "[", "i", "]", "[", "1", "]", ")", "]", ")", "pos_start", "=", "min", "(", "pos_array", ")", "pos_stop", "=", "max", "(", "pos_array", ")", "delta", "=", "pos_stop", "-", "pos_start", "self", ".", "_latex", "[", "pos_start", "]", "[", "columns", "]", "=", "(", "\"\\\\multigate{%s}{%s}\"", "%", "(", "nbits", "-", "1", ",", "nm", ")", ")", "for", "pos", "in", "range", "(", "pos_start", "+", "1", ",", "pos_stop", "+", "1", ")", ":", "self", ".", "_latex", "[", "pos", "]", "[", "columns", "]", "=", "\"\\\\ghost{%s}\"", "%", "nm", "elif", "op", ".", "name", "==", "\"measure\"", ":", "if", "(", "len", "(", "op", ".", "cargs", ")", "!=", "1", "or", "len", "(", "op", ".", "qargs", ")", "!=", "1", "or", "op", ".", "op", ".", "params", ")", ":", "raise", "exceptions", ".", "VisualizationError", "(", "\"bad operation record\"", ")", "if", "op", ".", "condition", ":", "raise", "exceptions", ".", "VisualizationError", "(", "\"If controlled measures currently not supported.\"", ")", "qname", ",", "qindex", "=", "op", ".", "qargs", "[", "0", "]", "cname", ",", "cindex", "=", "op", ".", "cargs", "[", "0", "]", "if", "aliases", ":", "newq", "=", "aliases", "[", "(", "qname", ",", "qindex", ")", "]", "qname", "=", "newq", "[", "0", "]", "qindex", "=", "newq", "[", "1", "]", "pos_1", "=", "self", ".", "img_regs", "[", "(", "qname", ",", "qindex", ")", "]", "pos_2", "=", "self", ".", "img_regs", "[", "(", "cname", ",", "cindex", ")", "]", "try", ":", "self", ".", "_latex", "[", "pos_1", "]", "[", "column", "]", "=", "\"\\\\meter\"", "prev_column", "=", "[", "x", "[", "column", "-", "1", "]", "for", "x", "in", "self", ".", "_latex", "]", "for", "item", ",", "prev_entry", "in", "enumerate", "(", "prev_column", ")", ":", "if", "'barrier'", "in", "prev_entry", ":", "span", "=", "re", ".", "search", "(", "'barrier{(.*)}'", ",", "prev_entry", ")", "if", "span", "and", "(", "item", "+", "int", "(", "span", ".", "group", "(", "1", ")", ")", ")", "-", "pos_1", ">=", "0", ":", "self", ".", "_latex", "[", "item", "]", "[", "column", "-", "1", "]", "=", "prev_entry", ".", "replace", "(", "'\\\\barrier{'", ",", "'\\\\barrier[-1.15em]{'", ")", "self", ".", "_latex", "[", "pos_2", "]", "[", "column", "]", "=", "\"\\\\cw \\\\cwx[-\"", "+", "str", "(", "pos_2", "-", "pos_1", ")", "+", "\"]\"", "except", "Exception", "as", "e", ":", "raise", "exceptions", ".", "VisualizationError", "(", "'Error during Latex building: %s'", "%", "str", "(", "e", ")", ")", "elif", "op", ".", "name", "in", "[", "'barrier'", ",", "'snapshot'", ",", "'load'", ",", "'save'", ",", "'noise'", "]", ":", "if", "self", ".", "plot_barriers", ":", "qarglist", "=", "op", ".", "qargs", "indexes", "=", "[", "self", ".", "_get_qubit_index", "(", "x", ")", "for", "x", "in", "qarglist", "]", "start_bit", "=", "self", ".", "qubit_list", "[", "min", "(", "indexes", ")", "]", "if", "aliases", "is", "not", "None", ":", "qarglist", "=", "map", "(", "lambda", "x", ":", "aliases", "[", "x", "]", ",", "qarglist", ")", "start", "=", "self", ".", "img_regs", "[", "start_bit", "]", "span", "=", "len", "(", "op", ".", "qargs", ")", "-", "1", "self", ".", "_latex", "[", "start", "]", "[", "column", "]", "=", "\"\\\\qw \\\\barrier{\"", "+", "str", "(", "span", ")", "+", "\"}\"", "else", ":", "raise", "exceptions", ".", "VisualizationError", "(", "\"bad node data\"", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QCircuitImage._get_qubit_index
Get the index number for a quantum bit Args: qubit (tuple): The tuple of the bit of the form (register_name, bit_number) Returns: int: The index in the bit list Raises: VisualizationError: If the bit isn't found
qiskit/visualization/latex.py
def _get_qubit_index(self, qubit): """Get the index number for a quantum bit Args: qubit (tuple): The tuple of the bit of the form (register_name, bit_number) Returns: int: The index in the bit list Raises: VisualizationError: If the bit isn't found """ for i, bit in enumerate(self.qubit_list): if qubit == bit: qindex = i break else: raise exceptions.VisualizationError("unable to find bit for operation") return qindex
def _get_qubit_index(self, qubit): """Get the index number for a quantum bit Args: qubit (tuple): The tuple of the bit of the form (register_name, bit_number) Returns: int: The index in the bit list Raises: VisualizationError: If the bit isn't found """ for i, bit in enumerate(self.qubit_list): if qubit == bit: qindex = i break else: raise exceptions.VisualizationError("unable to find bit for operation") return qindex
[ "Get", "the", "index", "number", "for", "a", "quantum", "bit", "Args", ":", "qubit", "(", "tuple", ")", ":", "The", "tuple", "of", "the", "bit", "of", "the", "form", "(", "register_name", "bit_number", ")", "Returns", ":", "int", ":", "The", "index", "in", "the", "bit", "list", "Raises", ":", "VisualizationError", ":", "If", "the", "bit", "isn", "t", "found" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/latex.py#L718-L734
[ "def", "_get_qubit_index", "(", "self", ",", "qubit", ")", ":", "for", "i", ",", "bit", "in", "enumerate", "(", "self", ".", "qubit_list", ")", ":", "if", "qubit", "==", "bit", ":", "qindex", "=", "i", "break", "else", ":", "raise", "exceptions", ".", "VisualizationError", "(", "\"unable to find bit for operation\"", ")", "return", "qindex" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_load_schema
Loads the QObj schema for use in future validations. Caches schema in _SCHEMAS module attribute. Args: file_path(str): Path to schema. name(str): Given name for schema. Defaults to file_path filename without schema. Return: schema(dict): Loaded schema.
qiskit/validation/jsonschema/schema_validation.py
def _load_schema(file_path, name=None): """Loads the QObj schema for use in future validations. Caches schema in _SCHEMAS module attribute. Args: file_path(str): Path to schema. name(str): Given name for schema. Defaults to file_path filename without schema. Return: schema(dict): Loaded schema. """ if name is None: # filename without extension name = os.path.splitext(os.path.basename(file_path))[0] if name not in _SCHEMAS: with open(file_path, 'r') as schema_file: _SCHEMAS[name] = json.load(schema_file) return _SCHEMAS[name]
def _load_schema(file_path, name=None): """Loads the QObj schema for use in future validations. Caches schema in _SCHEMAS module attribute. Args: file_path(str): Path to schema. name(str): Given name for schema. Defaults to file_path filename without schema. Return: schema(dict): Loaded schema. """ if name is None: # filename without extension name = os.path.splitext(os.path.basename(file_path))[0] if name not in _SCHEMAS: with open(file_path, 'r') as schema_file: _SCHEMAS[name] = json.load(schema_file) return _SCHEMAS[name]
[ "Loads", "the", "QObj", "schema", "for", "use", "in", "future", "validations", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/validation/jsonschema/schema_validation.py#L33-L52
[ "def", "_load_schema", "(", "file_path", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "# filename without extension", "name", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "file_path", ")", ")", "[", "0", "]", "if", "name", "not", "in", "_SCHEMAS", ":", "with", "open", "(", "file_path", ",", "'r'", ")", "as", "schema_file", ":", "_SCHEMAS", "[", "name", "]", "=", "json", ".", "load", "(", "schema_file", ")", "return", "_SCHEMAS", "[", "name", "]" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_get_validator
Generate validator for JSON schema. Args: name (str): Name for validator. Will be validator key in `_VALIDATORS` dict. schema (dict): JSON schema `dict`. If not provided searches for schema in `_SCHEMAS`. check_schema (bool): Verify schema is valid. validator_class (jsonschema.IValidator): jsonschema IValidator instance. Default behavior is to determine this from the schema `$schema` field. **validator_kwargs (dict): Additional keyword arguments for validator. Return: jsonschema.IValidator: Validator for JSON schema. Raises: SchemaValidationError: Raised if validation fails.
qiskit/validation/jsonschema/schema_validation.py
def _get_validator(name, schema=None, check_schema=True, validator_class=None, **validator_kwargs): """Generate validator for JSON schema. Args: name (str): Name for validator. Will be validator key in `_VALIDATORS` dict. schema (dict): JSON schema `dict`. If not provided searches for schema in `_SCHEMAS`. check_schema (bool): Verify schema is valid. validator_class (jsonschema.IValidator): jsonschema IValidator instance. Default behavior is to determine this from the schema `$schema` field. **validator_kwargs (dict): Additional keyword arguments for validator. Return: jsonschema.IValidator: Validator for JSON schema. Raises: SchemaValidationError: Raised if validation fails. """ if schema is None: try: schema = _SCHEMAS[name] except KeyError: raise SchemaValidationError("Valid schema name or schema must " "be provided.") if name not in _VALIDATORS: # Resolve JSON spec from schema if needed if validator_class is None: validator_class = jsonschema.validators.validator_for(schema) # Generate and store validator in _VALIDATORS _VALIDATORS[name] = validator_class(schema, **validator_kwargs) validator = _VALIDATORS[name] if check_schema: validator.check_schema(schema) return validator
def _get_validator(name, schema=None, check_schema=True, validator_class=None, **validator_kwargs): """Generate validator for JSON schema. Args: name (str): Name for validator. Will be validator key in `_VALIDATORS` dict. schema (dict): JSON schema `dict`. If not provided searches for schema in `_SCHEMAS`. check_schema (bool): Verify schema is valid. validator_class (jsonschema.IValidator): jsonschema IValidator instance. Default behavior is to determine this from the schema `$schema` field. **validator_kwargs (dict): Additional keyword arguments for validator. Return: jsonschema.IValidator: Validator for JSON schema. Raises: SchemaValidationError: Raised if validation fails. """ if schema is None: try: schema = _SCHEMAS[name] except KeyError: raise SchemaValidationError("Valid schema name or schema must " "be provided.") if name not in _VALIDATORS: # Resolve JSON spec from schema if needed if validator_class is None: validator_class = jsonschema.validators.validator_for(schema) # Generate and store validator in _VALIDATORS _VALIDATORS[name] = validator_class(schema, **validator_kwargs) validator = _VALIDATORS[name] if check_schema: validator.check_schema(schema) return validator
[ "Generate", "validator", "for", "JSON", "schema", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/validation/jsonschema/schema_validation.py#L55-L97
[ "def", "_get_validator", "(", "name", ",", "schema", "=", "None", ",", "check_schema", "=", "True", ",", "validator_class", "=", "None", ",", "*", "*", "validator_kwargs", ")", ":", "if", "schema", "is", "None", ":", "try", ":", "schema", "=", "_SCHEMAS", "[", "name", "]", "except", "KeyError", ":", "raise", "SchemaValidationError", "(", "\"Valid schema name or schema must \"", "\"be provided.\"", ")", "if", "name", "not", "in", "_VALIDATORS", ":", "# Resolve JSON spec from schema if needed", "if", "validator_class", "is", "None", ":", "validator_class", "=", "jsonschema", ".", "validators", ".", "validator_for", "(", "schema", ")", "# Generate and store validator in _VALIDATORS", "_VALIDATORS", "[", "name", "]", "=", "validator_class", "(", "schema", ",", "*", "*", "validator_kwargs", ")", "validator", "=", "_VALIDATORS", "[", "name", "]", "if", "check_schema", ":", "validator", ".", "check_schema", "(", "schema", ")", "return", "validator" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_load_schemas_and_validators
Load all default schemas into `_SCHEMAS`.
qiskit/validation/jsonschema/schema_validation.py
def _load_schemas_and_validators(): """Load all default schemas into `_SCHEMAS`.""" schema_base_path = os.path.join(os.path.dirname(__file__), '../..') for name, path in _DEFAULT_SCHEMA_PATHS.items(): _load_schema(os.path.join(schema_base_path, path), name) _get_validator(name)
def _load_schemas_and_validators(): """Load all default schemas into `_SCHEMAS`.""" schema_base_path = os.path.join(os.path.dirname(__file__), '../..') for name, path in _DEFAULT_SCHEMA_PATHS.items(): _load_schema(os.path.join(schema_base_path, path), name) _get_validator(name)
[ "Load", "all", "default", "schemas", "into", "_SCHEMAS", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/validation/jsonschema/schema_validation.py#L100-L105
[ "def", "_load_schemas_and_validators", "(", ")", ":", "schema_base_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'../..'", ")", "for", "name", ",", "path", "in", "_DEFAULT_SCHEMA_PATHS", ".", "items", "(", ")", ":", "_load_schema", "(", "os", ".", "path", ".", "join", "(", "schema_base_path", ",", "path", ")", ",", "name", ")", "_get_validator", "(", "name", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
validate_json_against_schema
Validates JSON dict against a schema. Args: json_dict (dict): JSON to be validated. schema (dict or str): JSON schema dictionary or the name of one of the standards schemas in Qiskit to validate against it. The list of standard schemas is: ``backend_configuration``, ``backend_properties``, ``backend_status``, ``default_pulse_configuration``, ``job_status``, ``qobj``, ``result``. err_msg (str): Optional error message. Raises: SchemaValidationError: Raised if validation fails.
qiskit/validation/jsonschema/schema_validation.py
def validate_json_against_schema(json_dict, schema, err_msg=None): """Validates JSON dict against a schema. Args: json_dict (dict): JSON to be validated. schema (dict or str): JSON schema dictionary or the name of one of the standards schemas in Qiskit to validate against it. The list of standard schemas is: ``backend_configuration``, ``backend_properties``, ``backend_status``, ``default_pulse_configuration``, ``job_status``, ``qobj``, ``result``. err_msg (str): Optional error message. Raises: SchemaValidationError: Raised if validation fails. """ try: if isinstance(schema, str): schema_name = schema schema = _SCHEMAS[schema_name] validator = _get_validator(schema_name) validator.validate(json_dict) else: jsonschema.validate(json_dict, schema) except jsonschema.ValidationError as err: if err_msg is None: err_msg = "JSON failed validation. Set Qiskit log level to DEBUG " \ "for further information." newerr = SchemaValidationError(err_msg) newerr.__cause__ = _SummaryValidationError(err) logger.debug('%s', _format_causes(err)) raise newerr
def validate_json_against_schema(json_dict, schema, err_msg=None): """Validates JSON dict against a schema. Args: json_dict (dict): JSON to be validated. schema (dict or str): JSON schema dictionary or the name of one of the standards schemas in Qiskit to validate against it. The list of standard schemas is: ``backend_configuration``, ``backend_properties``, ``backend_status``, ``default_pulse_configuration``, ``job_status``, ``qobj``, ``result``. err_msg (str): Optional error message. Raises: SchemaValidationError: Raised if validation fails. """ try: if isinstance(schema, str): schema_name = schema schema = _SCHEMAS[schema_name] validator = _get_validator(schema_name) validator.validate(json_dict) else: jsonschema.validate(json_dict, schema) except jsonschema.ValidationError as err: if err_msg is None: err_msg = "JSON failed validation. Set Qiskit log level to DEBUG " \ "for further information." newerr = SchemaValidationError(err_msg) newerr.__cause__ = _SummaryValidationError(err) logger.debug('%s', _format_causes(err)) raise newerr
[ "Validates", "JSON", "dict", "against", "a", "schema", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/validation/jsonschema/schema_validation.py#L112-L145
[ "def", "validate_json_against_schema", "(", "json_dict", ",", "schema", ",", "err_msg", "=", "None", ")", ":", "try", ":", "if", "isinstance", "(", "schema", ",", "str", ")", ":", "schema_name", "=", "schema", "schema", "=", "_SCHEMAS", "[", "schema_name", "]", "validator", "=", "_get_validator", "(", "schema_name", ")", "validator", ".", "validate", "(", "json_dict", ")", "else", ":", "jsonschema", ".", "validate", "(", "json_dict", ",", "schema", ")", "except", "jsonschema", ".", "ValidationError", "as", "err", ":", "if", "err_msg", "is", "None", ":", "err_msg", "=", "\"JSON failed validation. Set Qiskit log level to DEBUG \"", "\"for further information.\"", "newerr", "=", "SchemaValidationError", "(", "err_msg", ")", "newerr", ".", "__cause__", "=", "_SummaryValidationError", "(", "err", ")", "logger", ".", "debug", "(", "'%s'", ",", "_format_causes", "(", "err", ")", ")", "raise", "newerr" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_format_causes
Return a cascading explanation of the validation error. Returns a cascading explanation of the validation error in the form of:: <validator> failed @ <subfield_path> because of: <validator> failed @ <subfield_path> because of: ... <validator> failed @ <subfield_path> because of: ... ... For example:: 'oneOf' failed @ '<root>' because of: 'required' failed @ '<root>.config' because of: 'meas_level' is a required property Meaning the validator 'oneOf' failed while validating the whole object because of the validator 'required' failing while validating the property 'config' because its 'meas_level' field is missing. The cascade repeats the format "<validator> failed @ <path> because of" until there are no deeper causes. In this case, the string representation of the error is shown. Args: err (jsonschema.ValidationError): the instance to explain. level (int): starting level of indentation for the cascade of explanations. Return: str: a formatted string with the explanation of the error.
qiskit/validation/jsonschema/schema_validation.py
def _format_causes(err, level=0): """Return a cascading explanation of the validation error. Returns a cascading explanation of the validation error in the form of:: <validator> failed @ <subfield_path> because of: <validator> failed @ <subfield_path> because of: ... <validator> failed @ <subfield_path> because of: ... ... For example:: 'oneOf' failed @ '<root>' because of: 'required' failed @ '<root>.config' because of: 'meas_level' is a required property Meaning the validator 'oneOf' failed while validating the whole object because of the validator 'required' failing while validating the property 'config' because its 'meas_level' field is missing. The cascade repeats the format "<validator> failed @ <path> because of" until there are no deeper causes. In this case, the string representation of the error is shown. Args: err (jsonschema.ValidationError): the instance to explain. level (int): starting level of indentation for the cascade of explanations. Return: str: a formatted string with the explanation of the error. """ lines = [] def _print(string, offset=0): lines.append(_pad(string, offset=offset)) def _pad(string, offset=0): padding = ' ' * (level + offset) padded_lines = [padding + line for line in string.split('\n')] return '\n'.join(padded_lines) def _format_path(path): def _format(item): if isinstance(item, str): return '.{}'.format(item) return '[{}]'.format(item) return ''.join(['<root>'] + list(map(_format, path))) _print('\'{}\' failed @ \'{}\' because of:'.format( err.validator, _format_path(err.absolute_path))) if not err.context: _print(str(err.message), offset=1) else: for suberr in err.context: lines.append(_format_causes(suberr, level+1)) return '\n'.join(lines)
def _format_causes(err, level=0): """Return a cascading explanation of the validation error. Returns a cascading explanation of the validation error in the form of:: <validator> failed @ <subfield_path> because of: <validator> failed @ <subfield_path> because of: ... <validator> failed @ <subfield_path> because of: ... ... For example:: 'oneOf' failed @ '<root>' because of: 'required' failed @ '<root>.config' because of: 'meas_level' is a required property Meaning the validator 'oneOf' failed while validating the whole object because of the validator 'required' failing while validating the property 'config' because its 'meas_level' field is missing. The cascade repeats the format "<validator> failed @ <path> because of" until there are no deeper causes. In this case, the string representation of the error is shown. Args: err (jsonschema.ValidationError): the instance to explain. level (int): starting level of indentation for the cascade of explanations. Return: str: a formatted string with the explanation of the error. """ lines = [] def _print(string, offset=0): lines.append(_pad(string, offset=offset)) def _pad(string, offset=0): padding = ' ' * (level + offset) padded_lines = [padding + line for line in string.split('\n')] return '\n'.join(padded_lines) def _format_path(path): def _format(item): if isinstance(item, str): return '.{}'.format(item) return '[{}]'.format(item) return ''.join(['<root>'] + list(map(_format, path))) _print('\'{}\' failed @ \'{}\' because of:'.format( err.validator, _format_path(err.absolute_path))) if not err.context: _print(str(err.message), offset=1) else: for suberr in err.context: lines.append(_format_causes(suberr, level+1)) return '\n'.join(lines)
[ "Return", "a", "cascading", "explanation", "of", "the", "validation", "error", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/validation/jsonschema/schema_validation.py#L148-L211
[ "def", "_format_causes", "(", "err", ",", "level", "=", "0", ")", ":", "lines", "=", "[", "]", "def", "_print", "(", "string", ",", "offset", "=", "0", ")", ":", "lines", ".", "append", "(", "_pad", "(", "string", ",", "offset", "=", "offset", ")", ")", "def", "_pad", "(", "string", ",", "offset", "=", "0", ")", ":", "padding", "=", "' '", "*", "(", "level", "+", "offset", ")", "padded_lines", "=", "[", "padding", "+", "line", "for", "line", "in", "string", ".", "split", "(", "'\\n'", ")", "]", "return", "'\\n'", ".", "join", "(", "padded_lines", ")", "def", "_format_path", "(", "path", ")", ":", "def", "_format", "(", "item", ")", ":", "if", "isinstance", "(", "item", ",", "str", ")", ":", "return", "'.{}'", ".", "format", "(", "item", ")", "return", "'[{}]'", ".", "format", "(", "item", ")", "return", "''", ".", "join", "(", "[", "'<root>'", "]", "+", "list", "(", "map", "(", "_format", ",", "path", ")", ")", ")", "_print", "(", "'\\'{}\\' failed @ \\'{}\\' because of:'", ".", "format", "(", "err", ".", "validator", ",", "_format_path", "(", "err", ".", "absolute_path", ")", ")", ")", "if", "not", "err", ".", "context", ":", "_print", "(", "str", "(", "err", ".", "message", ")", ",", "offset", "=", "1", ")", "else", ":", "for", "suberr", "in", "err", ".", "context", ":", "lines", ".", "append", "(", "_format_causes", "(", "suberr", ",", "level", "+", "1", ")", ")", "return", "'\\n'", ".", "join", "(", "lines", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
IdList.qasm
Return the corresponding OPENQASM string.
qiskit/qasm/node/idlist.py
def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" return ",".join([self.children[j].qasm(prec) for j in range(self.size())])
def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" return ",".join([self.children[j].qasm(prec) for j in range(self.size())])
[ "Return", "the", "corresponding", "OPENQASM", "string", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/node/idlist.py#L27-L30
[ "def", "qasm", "(", "self", ",", "prec", "=", "15", ")", ":", "return", "\",\"", ".", "join", "(", "[", "self", ".", "children", "[", "j", "]", ".", "qasm", "(", "prec", ")", "for", "j", "in", "range", "(", "self", ".", "size", "(", ")", ")", "]", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
majority
Majority gate.
examples/python/rippleadd.py
def majority(p, a, b, c): """Majority gate.""" p.cx(c, b) p.cx(c, a) p.ccx(a, b, c)
def majority(p, a, b, c): """Majority gate.""" p.cx(c, b) p.cx(c, a) p.ccx(a, b, c)
[ "Majority", "gate", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/examples/python/rippleadd.py#L40-L44
[ "def", "majority", "(", "p", ",", "a", ",", "b", ",", "c", ")", ":", "p", ".", "cx", "(", "c", ",", "b", ")", "p", ".", "cx", "(", "c", ",", "a", ")", "p", ".", "ccx", "(", "a", ",", "b", ",", "c", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
unmajority
Unmajority gate.
examples/python/rippleadd.py
def unmajority(p, a, b, c): """Unmajority gate.""" p.ccx(a, b, c) p.cx(c, a) p.cx(a, b)
def unmajority(p, a, b, c): """Unmajority gate.""" p.ccx(a, b, c) p.cx(c, a) p.cx(a, b)
[ "Unmajority", "gate", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/examples/python/rippleadd.py#L47-L51
[ "def", "unmajority", "(", "p", ",", "a", ",", "b", ",", "c", ")", ":", "p", ".", "ccx", "(", "a", ",", "b", ",", "c", ")", "p", ".", "cx", "(", "c", ",", "a", ")", "p", ".", "cx", "(", "a", ",", "b", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
MergeAdjacentBarriers._collect_potential_merges
Returns a dict of DAGNode : Barrier objects, where the barrier needs to be inserted where the corresponding DAGNode appears in the main DAG
qiskit/transpiler/passes/merge_adjacent_barriers.py
def _collect_potential_merges(dag, barriers): """ Returns a dict of DAGNode : Barrier objects, where the barrier needs to be inserted where the corresponding DAGNode appears in the main DAG """ # if only got 1 or 0 barriers then can't merge if len(barriers) < 2: return None # mapping from the node that will be the main barrier to the # barrier object that gets built up node_to_barrier_qubits = {} # Start from the first barrier current_barrier = barriers[0] end_of_barrier = current_barrier current_barrier_nodes = [current_barrier] current_qubits = set(current_barrier.qargs) current_ancestors = dag.ancestors(current_barrier) current_descendants = dag.descendants(current_barrier) barrier_to_add = Barrier(len(current_qubits)) for next_barrier in barriers[1:]: # Remove all barriers that have already been included in this new barrier from the set # of ancestors/descendants as they will be removed from the new DAG when it is created next_ancestors = {nd for nd in dag.ancestors(next_barrier) if nd not in current_barrier_nodes} next_descendants = {nd for nd in dag.descendants(next_barrier) if nd not in current_barrier_nodes} next_qubits = set(next_barrier.qargs) if ( not current_qubits.isdisjoint(next_qubits) and current_ancestors.isdisjoint(next_descendants) and current_descendants.isdisjoint(next_ancestors) ): # can be merged current_ancestors = current_ancestors | next_ancestors current_descendants = current_descendants | next_descendants current_qubits = current_qubits | next_qubits # update the barrier that will be added back to include this barrier barrier_to_add = Barrier(len(current_qubits)) else: # store the previously made barrier if barrier_to_add: node_to_barrier_qubits[end_of_barrier] = current_qubits # reset the properties current_qubits = set(next_barrier.qargs) current_ancestors = dag.ancestors(next_barrier) current_descendants = dag.descendants(next_barrier) barrier_to_add = Barrier(len(current_qubits)) current_barrier_nodes = [] end_of_barrier = next_barrier current_barrier_nodes.append(end_of_barrier) if barrier_to_add: node_to_barrier_qubits[end_of_barrier] = current_qubits return node_to_barrier_qubits
def _collect_potential_merges(dag, barriers): """ Returns a dict of DAGNode : Barrier objects, where the barrier needs to be inserted where the corresponding DAGNode appears in the main DAG """ # if only got 1 or 0 barriers then can't merge if len(barriers) < 2: return None # mapping from the node that will be the main barrier to the # barrier object that gets built up node_to_barrier_qubits = {} # Start from the first barrier current_barrier = barriers[0] end_of_barrier = current_barrier current_barrier_nodes = [current_barrier] current_qubits = set(current_barrier.qargs) current_ancestors = dag.ancestors(current_barrier) current_descendants = dag.descendants(current_barrier) barrier_to_add = Barrier(len(current_qubits)) for next_barrier in barriers[1:]: # Remove all barriers that have already been included in this new barrier from the set # of ancestors/descendants as they will be removed from the new DAG when it is created next_ancestors = {nd for nd in dag.ancestors(next_barrier) if nd not in current_barrier_nodes} next_descendants = {nd for nd in dag.descendants(next_barrier) if nd not in current_barrier_nodes} next_qubits = set(next_barrier.qargs) if ( not current_qubits.isdisjoint(next_qubits) and current_ancestors.isdisjoint(next_descendants) and current_descendants.isdisjoint(next_ancestors) ): # can be merged current_ancestors = current_ancestors | next_ancestors current_descendants = current_descendants | next_descendants current_qubits = current_qubits | next_qubits # update the barrier that will be added back to include this barrier barrier_to_add = Barrier(len(current_qubits)) else: # store the previously made barrier if barrier_to_add: node_to_barrier_qubits[end_of_barrier] = current_qubits # reset the properties current_qubits = set(next_barrier.qargs) current_ancestors = dag.ancestors(next_barrier) current_descendants = dag.descendants(next_barrier) barrier_to_add = Barrier(len(current_qubits)) current_barrier_nodes = [] end_of_barrier = next_barrier current_barrier_nodes.append(end_of_barrier) if barrier_to_add: node_to_barrier_qubits[end_of_barrier] = current_qubits return node_to_barrier_qubits
[ "Returns", "a", "dict", "of", "DAGNode", ":", "Barrier", "objects", "where", "the", "barrier", "needs", "to", "be", "inserted", "where", "the", "corresponding", "DAGNode", "appears", "in", "the", "main", "DAG" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/merge_adjacent_barriers.py#L76-L143
[ "def", "_collect_potential_merges", "(", "dag", ",", "barriers", ")", ":", "# if only got 1 or 0 barriers then can't merge", "if", "len", "(", "barriers", ")", "<", "2", ":", "return", "None", "# mapping from the node that will be the main barrier to the", "# barrier object that gets built up", "node_to_barrier_qubits", "=", "{", "}", "# Start from the first barrier", "current_barrier", "=", "barriers", "[", "0", "]", "end_of_barrier", "=", "current_barrier", "current_barrier_nodes", "=", "[", "current_barrier", "]", "current_qubits", "=", "set", "(", "current_barrier", ".", "qargs", ")", "current_ancestors", "=", "dag", ".", "ancestors", "(", "current_barrier", ")", "current_descendants", "=", "dag", ".", "descendants", "(", "current_barrier", ")", "barrier_to_add", "=", "Barrier", "(", "len", "(", "current_qubits", ")", ")", "for", "next_barrier", "in", "barriers", "[", "1", ":", "]", ":", "# Remove all barriers that have already been included in this new barrier from the set", "# of ancestors/descendants as they will be removed from the new DAG when it is created", "next_ancestors", "=", "{", "nd", "for", "nd", "in", "dag", ".", "ancestors", "(", "next_barrier", ")", "if", "nd", "not", "in", "current_barrier_nodes", "}", "next_descendants", "=", "{", "nd", "for", "nd", "in", "dag", ".", "descendants", "(", "next_barrier", ")", "if", "nd", "not", "in", "current_barrier_nodes", "}", "next_qubits", "=", "set", "(", "next_barrier", ".", "qargs", ")", "if", "(", "not", "current_qubits", ".", "isdisjoint", "(", "next_qubits", ")", "and", "current_ancestors", ".", "isdisjoint", "(", "next_descendants", ")", "and", "current_descendants", ".", "isdisjoint", "(", "next_ancestors", ")", ")", ":", "# can be merged", "current_ancestors", "=", "current_ancestors", "|", "next_ancestors", "current_descendants", "=", "current_descendants", "|", "next_descendants", "current_qubits", "=", "current_qubits", "|", "next_qubits", "# update the barrier that will be added back to include this barrier", "barrier_to_add", "=", "Barrier", "(", "len", "(", "current_qubits", ")", ")", "else", ":", "# store the previously made barrier", "if", "barrier_to_add", ":", "node_to_barrier_qubits", "[", "end_of_barrier", "]", "=", "current_qubits", "# reset the properties", "current_qubits", "=", "set", "(", "next_barrier", ".", "qargs", ")", "current_ancestors", "=", "dag", ".", "ancestors", "(", "next_barrier", ")", "current_descendants", "=", "dag", ".", "descendants", "(", "next_barrier", ")", "barrier_to_add", "=", "Barrier", "(", "len", "(", "current_qubits", ")", ")", "current_barrier_nodes", "=", "[", "]", "end_of_barrier", "=", "next_barrier", "current_barrier_nodes", ".", "append", "(", "end_of_barrier", ")", "if", "barrier_to_add", ":", "node_to_barrier_qubits", "[", "end_of_barrier", "]", "=", "current_qubits", "return", "node_to_barrier_qubits" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
circuit_drawer
Draw a quantum circuit to different formats (set by output parameter): 0. text: ASCII art TextDrawing that can be printed in the console. 1. latex: high-quality images, but heavy external software dependencies 2. matplotlib: purely in Python with no external dependencies Args: circuit (QuantumCircuit): the quantum circuit to draw 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. This option is only used by the `mpl`, `latex`, and `latex_source` output types. If a str is passed in that is the path to a json file which contains that will be open, parsed, and then used just as the input dict. output (TextDrawing): Select the output method to use for drawing the circuit. Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if one is not specified it will use latex and if that fails fallback to mpl. However this behavior is deprecated and in a future release the default will change. 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` output type. This useful when the drawing does not fit in the console. If None (default), it will try to guess the console width using shutil.get_terminal_size(). However, if you're running in jupyter the default line length is set to 80 characters. If you don't want pagination at all, set `line_length=-1`. 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: (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. String: (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 ImportError: when the output methods requieres non-installed libraries. .. _style-dict-doc: The style dict kwarg contains numerous options that define the style of the output circuit visualization. While the style dict is used by the `mpl`, `latex`, and `latex_source` outputs some options in that are only used by the `mpl` output. These options are defined below, if it is only used by the `mpl` output it is marked as such: textcolor (str): The color code to use for text. Defaults to `'#000000'` (`mpl` only) subtextcolor (str): The color code to use for subtext. Defaults to `'#000000'` (`mpl` only) linecolor (str): The color code to use for lines. Defaults to `'#000000'` (`mpl` only) creglinecolor (str): The color code to use for classical register lines `'#778899'`(`mpl` only) gatetextcolor (str): The color code to use for gate text `'#000000'` (`mpl` only) gatefacecolor (str): The color code to use for gates. Defaults to `'#ffffff'` (`mpl` only) barrierfacecolor (str): The color code to use for barriers. Defaults to `'#bdbdbd'` (`mpl` only) backgroundcolor (str): The color code to use for the background. Defaults to `'#ffffff'` (`mpl` only) fontsize (int): The font size to use for text. Defaults to 13 (`mpl` only) subfontsize (int): The font size to use for subtext. Defaults to 8 (`mpl` only) displaytext (dict): A dictionary of the text to use for each element type in the output visualization. The default values are: { 'id': 'id', 'u0': 'U_0', 'u1': 'U_1', 'u2': 'U_2', 'u3': 'U_3', 'x': 'X', 'y': 'Y', 'z': 'Z', 'h': 'H', 's': 'S', 'sdg': 'S^\\dagger', 't': 'T', 'tdg': 'T^\\dagger', 'rx': 'R_x', 'ry': 'R_y', 'rz': 'R_z', 'reset': '\\left|0\\right\\rangle' } You must specify all the necessary values if using this. There is no provision for passing an incomplete dict in. (`mpl` only) displaycolor (dict): The color codes to use for each circuit element. By default all values default to the value of `gatefacecolor` and the keys are the same as `displaytext`. Also, just like `displaytext` there is no provision for an incomplete dict passed in. (`mpl` only) latexdrawerstyle (bool): When set to True enable latex mode which will draw gates like the `latex` output modes. (`mpl` only) usepiformat (bool): When set to True use radians for output (`mpl` only) fold (int): The number of circuit elements to fold the circuit at. Defaults to 20 (`mpl` only) cregbundle (bool): If set True bundle classical registers (`mpl` only) showindex (bool): If set True draw an index. (`mpl` only) compress (bool): If set True draw a compressed circuit (`mpl` only) figwidth (int): The maximum width (in inches) for the output figure. (`mpl` only) dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl` only) margin (list): `mpl` only creglinestyle (str): The style of line to use for classical registers. Choices are `'solid'`, `'doublet'`, or any valid matplotlib `linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
qiskit/visualization/circuit_visualization.py
def circuit_drawer(circuit, scale=0.7, filename=None, style=None, output='text', interactive=False, line_length=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw a quantum circuit to different formats (set by output parameter): 0. text: ASCII art TextDrawing that can be printed in the console. 1. latex: high-quality images, but heavy external software dependencies 2. matplotlib: purely in Python with no external dependencies Args: circuit (QuantumCircuit): the quantum circuit to draw 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. This option is only used by the `mpl`, `latex`, and `latex_source` output types. If a str is passed in that is the path to a json file which contains that will be open, parsed, and then used just as the input dict. output (TextDrawing): Select the output method to use for drawing the circuit. Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if one is not specified it will use latex and if that fails fallback to mpl. However this behavior is deprecated and in a future release the default will change. 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` output type. This useful when the drawing does not fit in the console. If None (default), it will try to guess the console width using shutil.get_terminal_size(). However, if you're running in jupyter the default line length is set to 80 characters. If you don't want pagination at all, set `line_length=-1`. 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: (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. String: (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 ImportError: when the output methods requieres non-installed libraries. .. _style-dict-doc: The style dict kwarg contains numerous options that define the style of the output circuit visualization. While the style dict is used by the `mpl`, `latex`, and `latex_source` outputs some options in that are only used by the `mpl` output. These options are defined below, if it is only used by the `mpl` output it is marked as such: textcolor (str): The color code to use for text. Defaults to `'#000000'` (`mpl` only) subtextcolor (str): The color code to use for subtext. Defaults to `'#000000'` (`mpl` only) linecolor (str): The color code to use for lines. Defaults to `'#000000'` (`mpl` only) creglinecolor (str): The color code to use for classical register lines `'#778899'`(`mpl` only) gatetextcolor (str): The color code to use for gate text `'#000000'` (`mpl` only) gatefacecolor (str): The color code to use for gates. Defaults to `'#ffffff'` (`mpl` only) barrierfacecolor (str): The color code to use for barriers. Defaults to `'#bdbdbd'` (`mpl` only) backgroundcolor (str): The color code to use for the background. Defaults to `'#ffffff'` (`mpl` only) fontsize (int): The font size to use for text. Defaults to 13 (`mpl` only) subfontsize (int): The font size to use for subtext. Defaults to 8 (`mpl` only) displaytext (dict): A dictionary of the text to use for each element type in the output visualization. The default values are: { 'id': 'id', 'u0': 'U_0', 'u1': 'U_1', 'u2': 'U_2', 'u3': 'U_3', 'x': 'X', 'y': 'Y', 'z': 'Z', 'h': 'H', 's': 'S', 'sdg': 'S^\\dagger', 't': 'T', 'tdg': 'T^\\dagger', 'rx': 'R_x', 'ry': 'R_y', 'rz': 'R_z', 'reset': '\\left|0\\right\\rangle' } You must specify all the necessary values if using this. There is no provision for passing an incomplete dict in. (`mpl` only) displaycolor (dict): The color codes to use for each circuit element. By default all values default to the value of `gatefacecolor` and the keys are the same as `displaytext`. Also, just like `displaytext` there is no provision for an incomplete dict passed in. (`mpl` only) latexdrawerstyle (bool): When set to True enable latex mode which will draw gates like the `latex` output modes. (`mpl` only) usepiformat (bool): When set to True use radians for output (`mpl` only) fold (int): The number of circuit elements to fold the circuit at. Defaults to 20 (`mpl` only) cregbundle (bool): If set True bundle classical registers (`mpl` only) showindex (bool): If set True draw an index. (`mpl` only) compress (bool): If set True draw a compressed circuit (`mpl` only) figwidth (int): The maximum width (in inches) for the output figure. (`mpl` only) dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl` only) margin (list): `mpl` only creglinestyle (str): The style of line to use for classical registers. Choices are `'solid'`, `'doublet'`, or any valid matplotlib `linestyle` kwarg value. Defaults to `doublet`(`mpl` only) """ image = None if output == 'text': return _text_circuit_drawer(circuit, filename=filename, line_length=line_length, reverse_bits=reverse_bits, plotbarriers=plot_barriers, justify=justify) elif output == 'latex': image = _latex_circuit_drawer(circuit, scale=scale, filename=filename, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) elif output == 'latex_source': return _generate_latex_source(circuit, filename=filename, scale=scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) elif output == 'mpl': image = _matplotlib_circuit_drawer(circuit, scale=scale, filename=filename, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) else: raise exceptions.VisualizationError( 'Invalid output type %s selected. The only valid choices ' 'are latex, latex_source, text, and mpl' % output) if image and interactive: image.show() return image
def circuit_drawer(circuit, scale=0.7, filename=None, style=None, output='text', interactive=False, line_length=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw a quantum circuit to different formats (set by output parameter): 0. text: ASCII art TextDrawing that can be printed in the console. 1. latex: high-quality images, but heavy external software dependencies 2. matplotlib: purely in Python with no external dependencies Args: circuit (QuantumCircuit): the quantum circuit to draw 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. This option is only used by the `mpl`, `latex`, and `latex_source` output types. If a str is passed in that is the path to a json file which contains that will be open, parsed, and then used just as the input dict. output (TextDrawing): Select the output method to use for drawing the circuit. Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if one is not specified it will use latex and if that fails fallback to mpl. However this behavior is deprecated and in a future release the default will change. 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` output type. This useful when the drawing does not fit in the console. If None (default), it will try to guess the console width using shutil.get_terminal_size(). However, if you're running in jupyter the default line length is set to 80 characters. If you don't want pagination at all, set `line_length=-1`. 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: (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. String: (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 ImportError: when the output methods requieres non-installed libraries. .. _style-dict-doc: The style dict kwarg contains numerous options that define the style of the output circuit visualization. While the style dict is used by the `mpl`, `latex`, and `latex_source` outputs some options in that are only used by the `mpl` output. These options are defined below, if it is only used by the `mpl` output it is marked as such: textcolor (str): The color code to use for text. Defaults to `'#000000'` (`mpl` only) subtextcolor (str): The color code to use for subtext. Defaults to `'#000000'` (`mpl` only) linecolor (str): The color code to use for lines. Defaults to `'#000000'` (`mpl` only) creglinecolor (str): The color code to use for classical register lines `'#778899'`(`mpl` only) gatetextcolor (str): The color code to use for gate text `'#000000'` (`mpl` only) gatefacecolor (str): The color code to use for gates. Defaults to `'#ffffff'` (`mpl` only) barrierfacecolor (str): The color code to use for barriers. Defaults to `'#bdbdbd'` (`mpl` only) backgroundcolor (str): The color code to use for the background. Defaults to `'#ffffff'` (`mpl` only) fontsize (int): The font size to use for text. Defaults to 13 (`mpl` only) subfontsize (int): The font size to use for subtext. Defaults to 8 (`mpl` only) displaytext (dict): A dictionary of the text to use for each element type in the output visualization. The default values are: { 'id': 'id', 'u0': 'U_0', 'u1': 'U_1', 'u2': 'U_2', 'u3': 'U_3', 'x': 'X', 'y': 'Y', 'z': 'Z', 'h': 'H', 's': 'S', 'sdg': 'S^\\dagger', 't': 'T', 'tdg': 'T^\\dagger', 'rx': 'R_x', 'ry': 'R_y', 'rz': 'R_z', 'reset': '\\left|0\\right\\rangle' } You must specify all the necessary values if using this. There is no provision for passing an incomplete dict in. (`mpl` only) displaycolor (dict): The color codes to use for each circuit element. By default all values default to the value of `gatefacecolor` and the keys are the same as `displaytext`. Also, just like `displaytext` there is no provision for an incomplete dict passed in. (`mpl` only) latexdrawerstyle (bool): When set to True enable latex mode which will draw gates like the `latex` output modes. (`mpl` only) usepiformat (bool): When set to True use radians for output (`mpl` only) fold (int): The number of circuit elements to fold the circuit at. Defaults to 20 (`mpl` only) cregbundle (bool): If set True bundle classical registers (`mpl` only) showindex (bool): If set True draw an index. (`mpl` only) compress (bool): If set True draw a compressed circuit (`mpl` only) figwidth (int): The maximum width (in inches) for the output figure. (`mpl` only) dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl` only) margin (list): `mpl` only creglinestyle (str): The style of line to use for classical registers. Choices are `'solid'`, `'doublet'`, or any valid matplotlib `linestyle` kwarg value. Defaults to `doublet`(`mpl` only) """ image = None if output == 'text': return _text_circuit_drawer(circuit, filename=filename, line_length=line_length, reverse_bits=reverse_bits, plotbarriers=plot_barriers, justify=justify) elif output == 'latex': image = _latex_circuit_drawer(circuit, scale=scale, filename=filename, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) elif output == 'latex_source': return _generate_latex_source(circuit, filename=filename, scale=scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) elif output == 'mpl': image = _matplotlib_circuit_drawer(circuit, scale=scale, filename=filename, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) else: raise exceptions.VisualizationError( 'Invalid output type %s selected. The only valid choices ' 'are latex, latex_source, text, and mpl' % output) if image and interactive: image.show() return image
[ "Draw", "a", "quantum", "circuit", "to", "different", "formats", "(", "set", "by", "output", "parameter", ")", ":", "0", ".", "text", ":", "ASCII", "art", "TextDrawing", "that", "can", "be", "printed", "in", "the", "console", ".", "1", ".", "latex", ":", "high", "-", "quality", "images", "but", "heavy", "external", "software", "dependencies", "2", ".", "matplotlib", ":", "purely", "in", "Python", "with", "no", "external", "dependencies" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/circuit_visualization.py#L36-L204
[ "def", "circuit_drawer", "(", "circuit", ",", "scale", "=", "0.7", ",", "filename", "=", "None", ",", "style", "=", "None", ",", "output", "=", "'text'", ",", "interactive", "=", "False", ",", "line_length", "=", "None", ",", "plot_barriers", "=", "True", ",", "reverse_bits", "=", "False", ",", "justify", "=", "None", ")", ":", "image", "=", "None", "if", "output", "==", "'text'", ":", "return", "_text_circuit_drawer", "(", "circuit", ",", "filename", "=", "filename", ",", "line_length", "=", "line_length", ",", "reverse_bits", "=", "reverse_bits", ",", "plotbarriers", "=", "plot_barriers", ",", "justify", "=", "justify", ")", "elif", "output", "==", "'latex'", ":", "image", "=", "_latex_circuit_drawer", "(", "circuit", ",", "scale", "=", "scale", ",", "filename", "=", "filename", ",", "style", "=", "style", ",", "plot_barriers", "=", "plot_barriers", ",", "reverse_bits", "=", "reverse_bits", ",", "justify", "=", "justify", ")", "elif", "output", "==", "'latex_source'", ":", "return", "_generate_latex_source", "(", "circuit", ",", "filename", "=", "filename", ",", "scale", "=", "scale", ",", "style", "=", "style", ",", "plot_barriers", "=", "plot_barriers", ",", "reverse_bits", "=", "reverse_bits", ",", "justify", "=", "justify", ")", "elif", "output", "==", "'mpl'", ":", "image", "=", "_matplotlib_circuit_drawer", "(", "circuit", ",", "scale", "=", "scale", ",", "filename", "=", "filename", ",", "style", "=", "style", ",", "plot_barriers", "=", "plot_barriers", ",", "reverse_bits", "=", "reverse_bits", ",", "justify", "=", "justify", ")", "else", ":", "raise", "exceptions", ".", "VisualizationError", "(", "'Invalid output type %s selected. The only valid choices '", "'are latex, latex_source, text, and mpl'", "%", "output", ")", "if", "image", "and", "interactive", ":", "image", ".", "show", "(", ")", "return", "image" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_text_circuit_drawer
Draws a circuit using ascii art. Args: circuit (QuantumCircuit): Input circuit filename (str): optional filename to write the result line_length (int): Optional. Breaks the circuit drawing to this length. This useful when the drawing does not fit in the console. If None (default), it will try to guess the console width using shutil.get_terminal_size(). If you don't want pagination at all, set line_length=-1. reverse_bits (bool): Rearrange the bits in reverse order. plotbarriers (bool): Draws the barriers when they are there. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. vertically_compressed (bool): Default is `True`. It merges the lines so the drawing will take less vertical room. Returns: TextDrawing: An instances that, when printed, draws the circuit in ascii art.
qiskit/visualization/circuit_visualization.py
def _text_circuit_drawer(circuit, filename=None, line_length=None, reverse_bits=False, plotbarriers=True, justify=None, vertically_compressed=True): """ Draws a circuit using ascii art. Args: circuit (QuantumCircuit): Input circuit filename (str): optional filename to write the result line_length (int): Optional. Breaks the circuit drawing to this length. This useful when the drawing does not fit in the console. If None (default), it will try to guess the console width using shutil.get_terminal_size(). If you don't want pagination at all, set line_length=-1. reverse_bits (bool): Rearrange the bits in reverse order. plotbarriers (bool): Draws the barriers when they are there. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. vertically_compressed (bool): Default is `True`. It merges the lines so the drawing will take less vertical room. Returns: TextDrawing: An instances that, when printed, draws the circuit in ascii art. """ qregs, cregs, ops = utils._get_layered_instructions(circuit, reverse_bits=reverse_bits, justify=justify) text_drawing = _text.TextDrawing(qregs, cregs, ops) text_drawing.plotbarriers = plotbarriers text_drawing.line_length = line_length text_drawing.vertically_compressed = vertically_compressed if filename: text_drawing.dump(filename) return text_drawing
def _text_circuit_drawer(circuit, filename=None, line_length=None, reverse_bits=False, plotbarriers=True, justify=None, vertically_compressed=True): """ Draws a circuit using ascii art. Args: circuit (QuantumCircuit): Input circuit filename (str): optional filename to write the result line_length (int): Optional. Breaks the circuit drawing to this length. This useful when the drawing does not fit in the console. If None (default), it will try to guess the console width using shutil.get_terminal_size(). If you don't want pagination at all, set line_length=-1. reverse_bits (bool): Rearrange the bits in reverse order. plotbarriers (bool): Draws the barriers when they are there. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. vertically_compressed (bool): Default is `True`. It merges the lines so the drawing will take less vertical room. Returns: TextDrawing: An instances that, when printed, draws the circuit in ascii art. """ qregs, cregs, ops = utils._get_layered_instructions(circuit, reverse_bits=reverse_bits, justify=justify) text_drawing = _text.TextDrawing(qregs, cregs, ops) text_drawing.plotbarriers = plotbarriers text_drawing.line_length = line_length text_drawing.vertically_compressed = vertically_compressed if filename: text_drawing.dump(filename) return text_drawing
[ "Draws", "a", "circuit", "using", "ascii", "art", ".", "Args", ":", "circuit", "(", "QuantumCircuit", ")", ":", "Input", "circuit", "filename", "(", "str", ")", ":", "optional", "filename", "to", "write", "the", "result", "line_length", "(", "int", ")", ":", "Optional", ".", "Breaks", "the", "circuit", "drawing", "to", "this", "length", ".", "This", "useful", "when", "the", "drawing", "does", "not", "fit", "in", "the", "console", ".", "If", "None", "(", "default", ")", "it", "will", "try", "to", "guess", "the", "console", "width", "using", "shutil", ".", "get_terminal_size", "()", ".", "If", "you", "don", "t", "want", "pagination", "at", "all", "set", "line_length", "=", "-", "1", ".", "reverse_bits", "(", "bool", ")", ":", "Rearrange", "the", "bits", "in", "reverse", "order", ".", "plotbarriers", "(", "bool", ")", ":", "Draws", "the", "barriers", "when", "they", "are", "there", ".", "justify", "(", "str", ")", ":", "left", "right", "or", "none", ".", "Defaults", "to", "left", ".", "Says", "how", "the", "circuit", "should", "be", "justified", ".", "vertically_compressed", "(", "bool", ")", ":", "Default", "is", "True", ".", "It", "merges", "the", "lines", "so", "the", "drawing", "will", "take", "less", "vertical", "room", ".", "Returns", ":", "TextDrawing", ":", "An", "instances", "that", "when", "printed", "draws", "the", "circuit", "in", "ascii", "art", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/circuit_visualization.py#L284-L315
[ "def", "_text_circuit_drawer", "(", "circuit", ",", "filename", "=", "None", ",", "line_length", "=", "None", ",", "reverse_bits", "=", "False", ",", "plotbarriers", "=", "True", ",", "justify", "=", "None", ",", "vertically_compressed", "=", "True", ")", ":", "qregs", ",", "cregs", ",", "ops", "=", "utils", ".", "_get_layered_instructions", "(", "circuit", ",", "reverse_bits", "=", "reverse_bits", ",", "justify", "=", "justify", ")", "text_drawing", "=", "_text", ".", "TextDrawing", "(", "qregs", ",", "cregs", ",", "ops", ")", "text_drawing", ".", "plotbarriers", "=", "plotbarriers", "text_drawing", ".", "line_length", "=", "line_length", "text_drawing", ".", "vertically_compressed", "=", "vertically_compressed", "if", "filename", ":", "text_drawing", ".", "dump", "(", "filename", ")", "return", "text_drawing" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_latex_circuit_drawer
Draw a quantum circuit based on latex (Qcircuit package) Requires version >=2.6.0 of the qcircuit LaTeX package. Args: circuit (QuantumCircuit): a quantum circuit scale (float): scaling factor filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file 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 (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: PIL.Image: an in-memory representation of the circuit diagram Raises: OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is missing. CalledProcessError: usually points errors during diagram creation.
qiskit/visualization/circuit_visualization.py
def _latex_circuit_drawer(circuit, scale=0.7, filename=None, style=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw a quantum circuit based on latex (Qcircuit package) Requires version >=2.6.0 of the qcircuit LaTeX package. Args: circuit (QuantumCircuit): a quantum circuit scale (float): scaling factor filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file 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 (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: PIL.Image: an in-memory representation of the circuit diagram Raises: OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is missing. CalledProcessError: usually points errors during diagram creation. """ tmpfilename = 'circuit' with tempfile.TemporaryDirectory() as tmpdirname: tmppath = os.path.join(tmpdirname, tmpfilename + '.tex') _generate_latex_source(circuit, filename=tmppath, scale=scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) image = None try: subprocess.run(["pdflatex", "-halt-on-error", "-output-directory={}".format(tmpdirname), "{}".format(tmpfilename + '.tex')], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=True) except OSError as ex: if ex.errno == errno.ENOENT: logger.warning('WARNING: Unable to compile latex. ' 'Is `pdflatex` installed? ' 'Skipping latex circuit drawing...') raise except subprocess.CalledProcessError as ex: with open('latex_error.log', 'wb') as error_file: error_file.write(ex.stdout) logger.warning('WARNING Unable to compile latex. ' 'The output from the pdflatex command can ' 'be found in latex_error.log') raise else: try: base = os.path.join(tmpdirname, tmpfilename) subprocess.run(["pdftocairo", "-singlefile", "-png", "-q", base + '.pdf', base]) image = Image.open(base + '.png') image = utils._trim(image) os.remove(base + '.png') if filename: image.save(filename, 'PNG') except OSError as ex: if ex.errno == errno.ENOENT: logger.warning('WARNING: Unable to convert pdf to image. ' 'Is `poppler` installed? ' 'Skipping circuit drawing...') raise return image
def _latex_circuit_drawer(circuit, scale=0.7, filename=None, style=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw a quantum circuit based on latex (Qcircuit package) Requires version >=2.6.0 of the qcircuit LaTeX package. Args: circuit (QuantumCircuit): a quantum circuit scale (float): scaling factor filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file 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 (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: PIL.Image: an in-memory representation of the circuit diagram Raises: OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is missing. CalledProcessError: usually points errors during diagram creation. """ tmpfilename = 'circuit' with tempfile.TemporaryDirectory() as tmpdirname: tmppath = os.path.join(tmpdirname, tmpfilename + '.tex') _generate_latex_source(circuit, filename=tmppath, scale=scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) image = None try: subprocess.run(["pdflatex", "-halt-on-error", "-output-directory={}".format(tmpdirname), "{}".format(tmpfilename + '.tex')], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=True) except OSError as ex: if ex.errno == errno.ENOENT: logger.warning('WARNING: Unable to compile latex. ' 'Is `pdflatex` installed? ' 'Skipping latex circuit drawing...') raise except subprocess.CalledProcessError as ex: with open('latex_error.log', 'wb') as error_file: error_file.write(ex.stdout) logger.warning('WARNING Unable to compile latex. ' 'The output from the pdflatex command can ' 'be found in latex_error.log') raise else: try: base = os.path.join(tmpdirname, tmpfilename) subprocess.run(["pdftocairo", "-singlefile", "-png", "-q", base + '.pdf', base]) image = Image.open(base + '.png') image = utils._trim(image) os.remove(base + '.png') if filename: image.save(filename, 'PNG') except OSError as ex: if ex.errno == errno.ENOENT: logger.warning('WARNING: Unable to convert pdf to image. ' 'Is `poppler` installed? ' 'Skipping circuit drawing...') raise return image
[ "Draw", "a", "quantum", "circuit", "based", "on", "latex", "(", "Qcircuit", "package", ")" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/circuit_visualization.py#L323-L398
[ "def", "_latex_circuit_drawer", "(", "circuit", ",", "scale", "=", "0.7", ",", "filename", "=", "None", ",", "style", "=", "None", ",", "plot_barriers", "=", "True", ",", "reverse_bits", "=", "False", ",", "justify", "=", "None", ")", ":", "tmpfilename", "=", "'circuit'", "with", "tempfile", ".", "TemporaryDirectory", "(", ")", "as", "tmpdirname", ":", "tmppath", "=", "os", ".", "path", ".", "join", "(", "tmpdirname", ",", "tmpfilename", "+", "'.tex'", ")", "_generate_latex_source", "(", "circuit", ",", "filename", "=", "tmppath", ",", "scale", "=", "scale", ",", "style", "=", "style", ",", "plot_barriers", "=", "plot_barriers", ",", "reverse_bits", "=", "reverse_bits", ",", "justify", "=", "justify", ")", "image", "=", "None", "try", ":", "subprocess", ".", "run", "(", "[", "\"pdflatex\"", ",", "\"-halt-on-error\"", ",", "\"-output-directory={}\"", ".", "format", "(", "tmpdirname", ")", ",", "\"{}\"", ".", "format", "(", "tmpfilename", "+", "'.tex'", ")", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "DEVNULL", ",", "check", "=", "True", ")", "except", "OSError", "as", "ex", ":", "if", "ex", ".", "errno", "==", "errno", ".", "ENOENT", ":", "logger", ".", "warning", "(", "'WARNING: Unable to compile latex. '", "'Is `pdflatex` installed? '", "'Skipping latex circuit drawing...'", ")", "raise", "except", "subprocess", ".", "CalledProcessError", "as", "ex", ":", "with", "open", "(", "'latex_error.log'", ",", "'wb'", ")", "as", "error_file", ":", "error_file", ".", "write", "(", "ex", ".", "stdout", ")", "logger", ".", "warning", "(", "'WARNING Unable to compile latex. '", "'The output from the pdflatex command can '", "'be found in latex_error.log'", ")", "raise", "else", ":", "try", ":", "base", "=", "os", ".", "path", ".", "join", "(", "tmpdirname", ",", "tmpfilename", ")", "subprocess", ".", "run", "(", "[", "\"pdftocairo\"", ",", "\"-singlefile\"", ",", "\"-png\"", ",", "\"-q\"", ",", "base", "+", "'.pdf'", ",", "base", "]", ")", "image", "=", "Image", ".", "open", "(", "base", "+", "'.png'", ")", "image", "=", "utils", ".", "_trim", "(", "image", ")", "os", ".", "remove", "(", "base", "+", "'.png'", ")", "if", "filename", ":", "image", ".", "save", "(", "filename", ",", "'PNG'", ")", "except", "OSError", "as", "ex", ":", "if", "ex", ".", "errno", "==", "errno", ".", "ENOENT", ":", "logger", ".", "warning", "(", "'WARNING: Unable to convert pdf to image. '", "'Is `poppler` installed? '", "'Skipping circuit drawing...'", ")", "raise", "return", "image" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_generate_latex_source
Convert QuantumCircuit to LaTeX string. Args: circuit (QuantumCircuit): input circuit scale (float): image scaling filename (str): optional filename to write latex style (dict or str): dictionary of style or file name of style file 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 (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: str: Latex string appropriate for writing to file.
qiskit/visualization/circuit_visualization.py
def _generate_latex_source(circuit, filename=None, scale=0.7, style=None, reverse_bits=False, plot_barriers=True, justify=None): """Convert QuantumCircuit to LaTeX string. Args: circuit (QuantumCircuit): input circuit scale (float): image scaling filename (str): optional filename to write latex style (dict or str): dictionary of style or file name of style file 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 (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: str: Latex string appropriate for writing to file. """ qregs, cregs, ops = utils._get_layered_instructions(circuit, reverse_bits=reverse_bits, justify=justify) qcimg = _latex.QCircuitImage(qregs, cregs, ops, scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits) latex = qcimg.latex() if filename: with open(filename, 'w') as latex_file: latex_file.write(latex) return latex
def _generate_latex_source(circuit, filename=None, scale=0.7, style=None, reverse_bits=False, plot_barriers=True, justify=None): """Convert QuantumCircuit to LaTeX string. Args: circuit (QuantumCircuit): input circuit scale (float): image scaling filename (str): optional filename to write latex style (dict or str): dictionary of style or file name of style file 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 (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: str: Latex string appropriate for writing to file. """ qregs, cregs, ops = utils._get_layered_instructions(circuit, reverse_bits=reverse_bits, justify=justify) qcimg = _latex.QCircuitImage(qregs, cregs, ops, scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits) latex = qcimg.latex() if filename: with open(filename, 'w') as latex_file: latex_file.write(latex) return latex
[ "Convert", "QuantumCircuit", "to", "LaTeX", "string", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/circuit_visualization.py#L401-L433
[ "def", "_generate_latex_source", "(", "circuit", ",", "filename", "=", "None", ",", "scale", "=", "0.7", ",", "style", "=", "None", ",", "reverse_bits", "=", "False", ",", "plot_barriers", "=", "True", ",", "justify", "=", "None", ")", ":", "qregs", ",", "cregs", ",", "ops", "=", "utils", ".", "_get_layered_instructions", "(", "circuit", ",", "reverse_bits", "=", "reverse_bits", ",", "justify", "=", "justify", ")", "qcimg", "=", "_latex", ".", "QCircuitImage", "(", "qregs", ",", "cregs", ",", "ops", ",", "scale", ",", "style", "=", "style", ",", "plot_barriers", "=", "plot_barriers", ",", "reverse_bits", "=", "reverse_bits", ")", "latex", "=", "qcimg", ".", "latex", "(", ")", "if", "filename", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "latex_file", ":", "latex_file", ".", "write", "(", "latex", ")", "return", "latex" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_matplotlib_circuit_drawer
Draw a quantum circuit based on matplotlib. If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline. We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization. Args: circuit (QuantumCircuit): a quantum circuit scale (float): scaling factor filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file 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 (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: matplotlib.figure: a matplotlib figure object for the circuit diagram
qiskit/visualization/circuit_visualization.py
def _matplotlib_circuit_drawer(circuit, scale=0.7, filename=None, style=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw a quantum circuit based on matplotlib. If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline. We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization. Args: circuit (QuantumCircuit): a quantum circuit scale (float): scaling factor filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file 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 (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: matplotlib.figure: a matplotlib figure object for the circuit diagram """ qregs, cregs, ops = utils._get_layered_instructions(circuit, reverse_bits=reverse_bits, justify=justify) qcd = _matplotlib.MatplotlibDrawer(qregs, cregs, ops, scale=scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits) return qcd.draw(filename)
def _matplotlib_circuit_drawer(circuit, scale=0.7, filename=None, style=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw a quantum circuit based on matplotlib. If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline. We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization. Args: circuit (QuantumCircuit): a quantum circuit scale (float): scaling factor filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file 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 (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: matplotlib.figure: a matplotlib figure object for the circuit diagram """ qregs, cregs, ops = utils._get_layered_instructions(circuit, reverse_bits=reverse_bits, justify=justify) qcd = _matplotlib.MatplotlibDrawer(qregs, cregs, ops, scale=scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits) return qcd.draw(filename)
[ "Draw", "a", "quantum", "circuit", "based", "on", "matplotlib", ".", "If", "%matplotlib", "inline", "is", "invoked", "in", "a", "Jupyter", "notebook", "it", "visualizes", "a", "circuit", "inline", ".", "We", "recommend", "%config", "InlineBackend", ".", "figure_format", "=", "svg", "for", "the", "inline", "visualization", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/circuit_visualization.py#L441-L475
[ "def", "_matplotlib_circuit_drawer", "(", "circuit", ",", "scale", "=", "0.7", ",", "filename", "=", "None", ",", "style", "=", "None", ",", "plot_barriers", "=", "True", ",", "reverse_bits", "=", "False", ",", "justify", "=", "None", ")", ":", "qregs", ",", "cregs", ",", "ops", "=", "utils", ".", "_get_layered_instructions", "(", "circuit", ",", "reverse_bits", "=", "reverse_bits", ",", "justify", "=", "justify", ")", "qcd", "=", "_matplotlib", ".", "MatplotlibDrawer", "(", "qregs", ",", "cregs", ",", "ops", ",", "scale", "=", "scale", ",", "style", "=", "style", ",", "plot_barriers", "=", "plot_barriers", ",", "reverse_bits", "=", "reverse_bits", ")", "return", "qcd", ".", "draw", "(", "filename", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
random_state
Return a random quantum state from the uniform (Haar) measure on state space. Args: dim (int): the dim of the state spaxe seed (int): Optional. To set a random seed. Returns: ndarray: state(2**num) a random quantum state.
qiskit/quantum_info/random/utils.py
def random_state(dim, seed=None): """ Return a random quantum state from the uniform (Haar) measure on state space. Args: dim (int): the dim of the state spaxe seed (int): Optional. To set a random seed. Returns: ndarray: state(2**num) a random quantum state. """ if seed is None: seed = np.random.randint(0, np.iinfo(np.int32).max) rng = np.random.RandomState(seed) # Random array over interval (0, 1] x = rng.rand(dim) x += x == 0 x = -np.log(x) sumx = sum(x) phases = rng.rand(dim)*2.0*np.pi return np.sqrt(x/sumx)*np.exp(1j*phases)
def random_state(dim, seed=None): """ Return a random quantum state from the uniform (Haar) measure on state space. Args: dim (int): the dim of the state spaxe seed (int): Optional. To set a random seed. Returns: ndarray: state(2**num) a random quantum state. """ if seed is None: seed = np.random.randint(0, np.iinfo(np.int32).max) rng = np.random.RandomState(seed) # Random array over interval (0, 1] x = rng.rand(dim) x += x == 0 x = -np.log(x) sumx = sum(x) phases = rng.rand(dim)*2.0*np.pi return np.sqrt(x/sumx)*np.exp(1j*phases)
[ "Return", "a", "random", "quantum", "state", "from", "the", "uniform", "(", "Haar", ")", "measure", "on", "state", "space", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/random/utils.py#L23-L44
[ "def", "random_state", "(", "dim", ",", "seed", "=", "None", ")", ":", "if", "seed", "is", "None", ":", "seed", "=", "np", ".", "random", ".", "randint", "(", "0", ",", "np", ".", "iinfo", "(", "np", ".", "int32", ")", ".", "max", ")", "rng", "=", "np", ".", "random", ".", "RandomState", "(", "seed", ")", "# Random array over interval (0, 1]", "x", "=", "rng", ".", "rand", "(", "dim", ")", "x", "+=", "x", "==", "0", "x", "=", "-", "np", ".", "log", "(", "x", ")", "sumx", "=", "sum", "(", "x", ")", "phases", "=", "rng", ".", "rand", "(", "dim", ")", "*", "2.0", "*", "np", ".", "pi", "return", "np", ".", "sqrt", "(", "x", "/", "sumx", ")", "*", "np", ".", "exp", "(", "1j", "*", "phases", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
random_unitary
Return a random dim x dim unitary Operator from the Haar measure. Args: dim (int): the dim of the state space. seed (int): Optional. To set a random seed. Returns: Operator: (dim, dim) unitary operator. Raises: QiskitError: if dim is not a positive power of 2.
qiskit/quantum_info/random/utils.py
def random_unitary(dim, seed=None): """ Return a random dim x dim unitary Operator from the Haar measure. Args: dim (int): the dim of the state space. seed (int): Optional. To set a random seed. Returns: Operator: (dim, dim) unitary operator. Raises: QiskitError: if dim is not a positive power of 2. """ if dim == 0 or not math.log2(dim).is_integer(): raise QiskitError("Desired unitary dimension not a positive power of 2.") matrix = np.zeros([dim, dim], dtype=complex) for j in range(dim): if j == 0: a = random_state(dim, seed) else: a = random_state(dim) matrix[:, j] = np.copy(a) # Grahm-Schmidt Orthogonalize i = j-1 while i >= 0: dc = np.vdot(matrix[:, i], a) matrix[:, j] = matrix[:, j]-dc*matrix[:, i] i = i - 1 # normalize matrix[:, j] = matrix[:, j] * (1.0 / np.sqrt(np.vdot(matrix[:, j], matrix[:, j]))) return Operator(matrix)
def random_unitary(dim, seed=None): """ Return a random dim x dim unitary Operator from the Haar measure. Args: dim (int): the dim of the state space. seed (int): Optional. To set a random seed. Returns: Operator: (dim, dim) unitary operator. Raises: QiskitError: if dim is not a positive power of 2. """ if dim == 0 or not math.log2(dim).is_integer(): raise QiskitError("Desired unitary dimension not a positive power of 2.") matrix = np.zeros([dim, dim], dtype=complex) for j in range(dim): if j == 0: a = random_state(dim, seed) else: a = random_state(dim) matrix[:, j] = np.copy(a) # Grahm-Schmidt Orthogonalize i = j-1 while i >= 0: dc = np.vdot(matrix[:, i], a) matrix[:, j] = matrix[:, j]-dc*matrix[:, i] i = i - 1 # normalize matrix[:, j] = matrix[:, j] * (1.0 / np.sqrt(np.vdot(matrix[:, j], matrix[:, j]))) return Operator(matrix)
[ "Return", "a", "random", "dim", "x", "dim", "unitary", "Operator", "from", "the", "Haar", "measure", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/random/utils.py#L47-L78
[ "def", "random_unitary", "(", "dim", ",", "seed", "=", "None", ")", ":", "if", "dim", "==", "0", "or", "not", "math", ".", "log2", "(", "dim", ")", ".", "is_integer", "(", ")", ":", "raise", "QiskitError", "(", "\"Desired unitary dimension not a positive power of 2.\"", ")", "matrix", "=", "np", ".", "zeros", "(", "[", "dim", ",", "dim", "]", ",", "dtype", "=", "complex", ")", "for", "j", "in", "range", "(", "dim", ")", ":", "if", "j", "==", "0", ":", "a", "=", "random_state", "(", "dim", ",", "seed", ")", "else", ":", "a", "=", "random_state", "(", "dim", ")", "matrix", "[", ":", ",", "j", "]", "=", "np", ".", "copy", "(", "a", ")", "# Grahm-Schmidt Orthogonalize", "i", "=", "j", "-", "1", "while", "i", ">=", "0", ":", "dc", "=", "np", ".", "vdot", "(", "matrix", "[", ":", ",", "i", "]", ",", "a", ")", "matrix", "[", ":", ",", "j", "]", "=", "matrix", "[", ":", ",", "j", "]", "-", "dc", "*", "matrix", "[", ":", ",", "i", "]", "i", "=", "i", "-", "1", "# normalize", "matrix", "[", ":", ",", "j", "]", "=", "matrix", "[", ":", ",", "j", "]", "*", "(", "1.0", "/", "np", ".", "sqrt", "(", "np", ".", "vdot", "(", "matrix", "[", ":", ",", "j", "]", ",", "matrix", "[", ":", ",", "j", "]", ")", ")", ")", "return", "Operator", "(", "matrix", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
random_density_matrix
Generate a random density matrix rho. Args: length (int): the length of the density matrix. rank (int or None): the rank of the density matrix. The default value is full-rank. method (string): the method to use. 'Hilbert-Schmidt': sample rho from the Hilbert-Schmidt metric. 'Bures': sample rho from the Bures metric. seed (int): Optional. To set a random seed. Returns: ndarray: rho (length, length) a density matrix. Raises: QiskitError: if the method is not valid.
qiskit/quantum_info/random/utils.py
def random_density_matrix(length, rank=None, method='Hilbert-Schmidt', seed=None): """ Generate a random density matrix rho. Args: length (int): the length of the density matrix. rank (int or None): the rank of the density matrix. The default value is full-rank. method (string): the method to use. 'Hilbert-Schmidt': sample rho from the Hilbert-Schmidt metric. 'Bures': sample rho from the Bures metric. seed (int): Optional. To set a random seed. Returns: ndarray: rho (length, length) a density matrix. Raises: QiskitError: if the method is not valid. """ if method == 'Hilbert-Schmidt': return __random_density_hs(length, rank, seed) elif method == 'Bures': return __random_density_bures(length, rank, seed) else: raise QiskitError('Error: unrecognized method {}'.format(method))
def random_density_matrix(length, rank=None, method='Hilbert-Schmidt', seed=None): """ Generate a random density matrix rho. Args: length (int): the length of the density matrix. rank (int or None): the rank of the density matrix. The default value is full-rank. method (string): the method to use. 'Hilbert-Schmidt': sample rho from the Hilbert-Schmidt metric. 'Bures': sample rho from the Bures metric. seed (int): Optional. To set a random seed. Returns: ndarray: rho (length, length) a density matrix. Raises: QiskitError: if the method is not valid. """ if method == 'Hilbert-Schmidt': return __random_density_hs(length, rank, seed) elif method == 'Bures': return __random_density_bures(length, rank, seed) else: raise QiskitError('Error: unrecognized method {}'.format(method))
[ "Generate", "a", "random", "density", "matrix", "rho", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/random/utils.py#L82-L104
[ "def", "random_density_matrix", "(", "length", ",", "rank", "=", "None", ",", "method", "=", "'Hilbert-Schmidt'", ",", "seed", "=", "None", ")", ":", "if", "method", "==", "'Hilbert-Schmidt'", ":", "return", "__random_density_hs", "(", "length", ",", "rank", ",", "seed", ")", "elif", "method", "==", "'Bures'", ":", "return", "__random_density_bures", "(", "length", ",", "rank", ",", "seed", ")", "else", ":", "raise", "QiskitError", "(", "'Error: unrecognized method {}'", ".", "format", "(", "method", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
__ginibre_matrix
Return a normally distributed complex random matrix. Args: nrow (int): number of rows in output matrix. ncol (int): number of columns in output matrix. seed (int): Optional. To set a random seed. Returns: ndarray: A complex rectangular matrix where each real and imaginary entry is sampled from the normal distribution.
qiskit/quantum_info/random/utils.py
def __ginibre_matrix(nrow, ncol=None, seed=None): """ Return a normally distributed complex random matrix. Args: nrow (int): number of rows in output matrix. ncol (int): number of columns in output matrix. seed (int): Optional. To set a random seed. Returns: ndarray: A complex rectangular matrix where each real and imaginary entry is sampled from the normal distribution. """ if ncol is None: ncol = nrow if seed is not None: np.random.seed(seed) G = np.random.normal(size=(nrow, ncol)) + \ np.random.normal(size=(nrow, ncol)) * 1j return G
def __ginibre_matrix(nrow, ncol=None, seed=None): """ Return a normally distributed complex random matrix. Args: nrow (int): number of rows in output matrix. ncol (int): number of columns in output matrix. seed (int): Optional. To set a random seed. Returns: ndarray: A complex rectangular matrix where each real and imaginary entry is sampled from the normal distribution. """ if ncol is None: ncol = nrow if seed is not None: np.random.seed(seed) G = np.random.normal(size=(nrow, ncol)) + \ np.random.normal(size=(nrow, ncol)) * 1j return G
[ "Return", "a", "normally", "distributed", "complex", "random", "matrix", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/random/utils.py#L107-L125
[ "def", "__ginibre_matrix", "(", "nrow", ",", "ncol", "=", "None", ",", "seed", "=", "None", ")", ":", "if", "ncol", "is", "None", ":", "ncol", "=", "nrow", "if", "seed", "is", "not", "None", ":", "np", ".", "random", ".", "seed", "(", "seed", ")", "G", "=", "np", ".", "random", ".", "normal", "(", "size", "=", "(", "nrow", ",", "ncol", ")", ")", "+", "np", ".", "random", ".", "normal", "(", "size", "=", "(", "nrow", ",", "ncol", ")", ")", "*", "1j", "return", "G" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
__random_density_hs
Generate a random density matrix from the Hilbert-Schmidt metric. Args: N (int): the length of the density matrix. rank (int or None): the rank of the density matrix. The default value is full-rank. seed (int): Optional. To set a random seed. Returns: ndarray: rho (N,N a density matrix.
qiskit/quantum_info/random/utils.py
def __random_density_hs(N, rank=None, seed=None): """ Generate a random density matrix from the Hilbert-Schmidt metric. Args: N (int): the length of the density matrix. rank (int or None): the rank of the density matrix. The default value is full-rank. seed (int): Optional. To set a random seed. Returns: ndarray: rho (N,N a density matrix. """ G = __ginibre_matrix(N, rank, seed) G = G.dot(G.conj().T) return G / np.trace(G)
def __random_density_hs(N, rank=None, seed=None): """ Generate a random density matrix from the Hilbert-Schmidt metric. Args: N (int): the length of the density matrix. rank (int or None): the rank of the density matrix. The default value is full-rank. seed (int): Optional. To set a random seed. Returns: ndarray: rho (N,N a density matrix. """ G = __ginibre_matrix(N, rank, seed) G = G.dot(G.conj().T) return G / np.trace(G)
[ "Generate", "a", "random", "density", "matrix", "from", "the", "Hilbert", "-", "Schmidt", "metric", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/random/utils.py#L128-L142
[ "def", "__random_density_hs", "(", "N", ",", "rank", "=", "None", ",", "seed", "=", "None", ")", ":", "G", "=", "__ginibre_matrix", "(", "N", ",", "rank", ",", "seed", ")", "G", "=", "G", ".", "dot", "(", "G", ".", "conj", "(", ")", ".", "T", ")", "return", "G", "/", "np", ".", "trace", "(", "G", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
__random_density_bures
Generate a random density matrix from the Bures metric. Args: N (int): the length of the density matrix. rank (int or None): the rank of the density matrix. The default value is full-rank. seed (int): Optional. To set a random seed. Returns: ndarray: rho (N,N) a density matrix.
qiskit/quantum_info/random/utils.py
def __random_density_bures(N, rank=None, seed=None): """ Generate a random density matrix from the Bures metric. Args: N (int): the length of the density matrix. rank (int or None): the rank of the density matrix. The default value is full-rank. seed (int): Optional. To set a random seed. Returns: ndarray: rho (N,N) a density matrix. """ P = np.eye(N) + random_unitary(N).data G = P.dot(__ginibre_matrix(N, rank, seed)) G = G.dot(G.conj().T) return G / np.trace(G)
def __random_density_bures(N, rank=None, seed=None): """ Generate a random density matrix from the Bures metric. Args: N (int): the length of the density matrix. rank (int or None): the rank of the density matrix. The default value is full-rank. seed (int): Optional. To set a random seed. Returns: ndarray: rho (N,N) a density matrix. """ P = np.eye(N) + random_unitary(N).data G = P.dot(__ginibre_matrix(N, rank, seed)) G = G.dot(G.conj().T) return G / np.trace(G)
[ "Generate", "a", "random", "density", "matrix", "from", "the", "Bures", "metric", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/random/utils.py#L145-L160
[ "def", "__random_density_bures", "(", "N", ",", "rank", "=", "None", ",", "seed", "=", "None", ")", ":", "P", "=", "np", ".", "eye", "(", "N", ")", "+", "random_unitary", "(", "N", ")", ".", "data", "G", "=", "P", ".", "dot", "(", "__ginibre_matrix", "(", "N", ",", "rank", ",", "seed", ")", ")", "G", "=", "G", ".", "dot", "(", "G", ".", "conj", "(", ")", ".", "T", ")", "return", "G", "/", "np", ".", "trace", "(", "G", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
GateBody.qasm
Return the corresponding OPENQASM string.
qiskit/qasm/node/gatebody.py
def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" string = "" for children in self.children: string += " " + children.qasm(prec) + "\n" return string
def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" string = "" for children in self.children: string += " " + children.qasm(prec) + "\n" return string
[ "Return", "the", "corresponding", "OPENQASM", "string", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/node/gatebody.py#L24-L29
[ "def", "qasm", "(", "self", ",", "prec", "=", "15", ")", ":", "string", "=", "\"\"", "for", "children", "in", "self", ".", "children", ":", "string", "+=", "\" \"", "+", "children", ".", "qasm", "(", "prec", ")", "+", "\"\\n\"", "return", "string" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
GateBody.calls
Return a list of custom gate names in this gate body.
qiskit/qasm/node/gatebody.py
def calls(self): """Return a list of custom gate names in this gate body.""" lst = [] for children in self.children: if children.type == "custom_unitary": lst.append(children.name) return lst
def calls(self): """Return a list of custom gate names in this gate body.""" lst = [] for children in self.children: if children.type == "custom_unitary": lst.append(children.name) return lst
[ "Return", "a", "list", "of", "custom", "gate", "names", "in", "this", "gate", "body", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/node/gatebody.py#L31-L37
[ "def", "calls", "(", "self", ")", ":", "lst", "=", "[", "]", "for", "children", "in", "self", ".", "children", ":", "if", "children", ".", "type", "==", "\"custom_unitary\"", ":", "lst", ".", "append", "(", "children", ".", "name", ")", "return", "lst" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Real.qasm
Return the corresponding OPENQASM string.
qiskit/qasm/node/real.py
def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" if self.value == pi: return "pi" return ccode(self.value, precision=prec)
def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" if self.value == pi: return "pi" return ccode(self.value, precision=prec)
[ "Return", "the", "corresponding", "OPENQASM", "string", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/node/real.py#L32-L37
[ "def", "qasm", "(", "self", ",", "prec", "=", "15", ")", ":", "if", "self", ".", "value", "==", "pi", ":", "return", "\"pi\"", "return", "ccode", "(", "self", ".", "value", ",", "precision", "=", "prec", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
SdgGate._define
gate sdg a { u1(-pi/2) a; }
qiskit/extensions/standard/s.py
def _define(self): """ gate sdg a { u1(-pi/2) a; } """ definition = [] q = QuantumRegister(1, "q") rule = [ (U1Gate(-pi/2), [q[0]], []) ] for inst in rule: definition.append(inst) self.definition = definition
def _define(self): """ gate sdg a { u1(-pi/2) a; } """ definition = [] q = QuantumRegister(1, "q") rule = [ (U1Gate(-pi/2), [q[0]], []) ] for inst in rule: definition.append(inst) self.definition = definition
[ "gate", "sdg", "a", "{", "u1", "(", "-", "pi", "/", "2", ")", "a", ";", "}" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/standard/s.py#L60-L71
[ "def", "_define", "(", "self", ")", ":", "definition", "=", "[", "]", "q", "=", "QuantumRegister", "(", "1", ",", "\"q\"", ")", "rule", "=", "[", "(", "U1Gate", "(", "-", "pi", "/", "2", ")", ",", "[", "q", "[", "0", "]", "]", ",", "[", "]", ")", "]", "for", "inst", "in", "rule", ":", "definition", ".", "append", "(", "inst", ")", "self", ".", "definition", "=", "definition" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Chi.compose
Return the composition channel self∘other. Args: other (QuantumChannel): a quantum channel. qargs (list): a list of subsystem positions to compose other on. front (bool): If False compose in standard order other(self(input)) otherwise compose in reverse order self(other(input)) [default: False] Returns: Chi: The composition channel as a Chi object. Raises: QiskitError: if other is not a QuantumChannel subclass, or has incompatible dimensions.
qiskit/quantum_info/operators/channel/chi.py
def compose(self, other, qargs=None, front=False): """Return the composition channel self∘other. Args: other (QuantumChannel): a quantum channel. qargs (list): a list of subsystem positions to compose other on. front (bool): If False compose in standard order other(self(input)) otherwise compose in reverse order self(other(input)) [default: False] Returns: Chi: The composition channel as a Chi object. Raises: QiskitError: if other is not a QuantumChannel subclass, or has incompatible dimensions. """ if qargs is not None: return Chi( SuperOp(self).compose(other, qargs=qargs, front=front)) # Convert other to Choi since we convert via Choi if not isinstance(other, Choi): other = Choi(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 add two channels in the Chi # representation we convert to the Choi representation return Chi(Choi(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. 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: Chi: The composition channel as a Chi object. Raises: QiskitError: if other is not a QuantumChannel subclass, or has incompatible dimensions. """ if qargs is not None: return Chi( SuperOp(self).compose(other, qargs=qargs, front=front)) # Convert other to Choi since we convert via Choi if not isinstance(other, Choi): other = Choi(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 add two channels in the Chi # representation we convert to the Choi representation return Chi(Choi(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/chi.py#L136-L169
[ "def", "compose", "(", "self", ",", "other", ",", "qargs", "=", "None", ",", "front", "=", "False", ")", ":", "if", "qargs", "is", "not", "None", ":", "return", "Chi", "(", "SuperOp", "(", "self", ")", ".", "compose", "(", "other", ",", "qargs", "=", "qargs", ",", "front", "=", "front", ")", ")", "# Convert other to Choi since we convert via Choi", "if", "not", "isinstance", "(", "other", ",", "Choi", ")", ":", "other", "=", "Choi", "(", "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 add two channels in the Chi", "# representation we convert to the Choi representation", "return", "Chi", "(", "Choi", "(", "self", ")", ".", "compose", "(", "other", ",", "front", "=", "front", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Chi.power
The matrix power of the channel. Args: n (int): compute the matrix power of the superoperator matrix. Returns: Chi: the matrix power of the SuperOp converted to a Chi 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/chi.py
def power(self, n): """The matrix power of the channel. Args: n (int): compute the matrix power of the superoperator matrix. Returns: Chi: the matrix power of the SuperOp converted to a Chi 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 Chi(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: Chi: the matrix power of the SuperOp converted to a Chi 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 Chi(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/chi.py#L171-L186
[ "def", "power", "(", "self", ",", "n", ")", ":", "if", "n", ">", "0", ":", "return", "super", "(", ")", ".", "power", "(", "n", ")", "return", "Chi", "(", "SuperOp", "(", "self", ")", ".", "power", "(", "n", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Chi.add
Return the QuantumChannel self + other. Args: other (QuantumChannel): a quantum channel. Returns: Chi: the linear addition self + other as a Chi object. Raises: QiskitError: if other is not a QuantumChannel subclass, or has incompatible dimensions.
qiskit/quantum_info/operators/channel/chi.py
def add(self, other): """Return the QuantumChannel self + other. Args: other (QuantumChannel): a quantum channel. Returns: Chi: the linear addition self + other as a Chi object. Raises: QiskitError: if other is not a QuantumChannel subclass, or has incompatible dimensions. """ if not isinstance(other, Chi): other = Chi(other) if self.dim != other.dim: raise QiskitError("other QuantumChannel dimensions are not equal") return Chi(self._data + other.data, self._input_dims, self._output_dims)
def add(self, other): """Return the QuantumChannel self + other. Args: other (QuantumChannel): a quantum channel. Returns: Chi: the linear addition self + other as a Chi object. Raises: QiskitError: if other is not a QuantumChannel subclass, or has incompatible dimensions. """ if not isinstance(other, Chi): other = Chi(other) if self.dim != other.dim: raise QiskitError("other QuantumChannel dimensions are not equal") return Chi(self._data + other.data, 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/chi.py#L216-L234
[ "def", "add", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "Chi", ")", ":", "other", "=", "Chi", "(", "other", ")", "if", "self", ".", "dim", "!=", "other", ".", "dim", ":", "raise", "QiskitError", "(", "\"other QuantumChannel dimensions are not equal\"", ")", "return", "Chi", "(", "self", ".", "_data", "+", "other", ".", "data", ",", "self", ".", "_input_dims", ",", "self", ".", "_output_dims", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Chi.multiply
Return the QuantumChannel self + other. Args: other (complex): a complex number. Returns: Chi: the scalar multiplication other * self as a Chi object. Raises: QiskitError: if other is not a valid scalar.
qiskit/quantum_info/operators/channel/chi.py
def multiply(self, other): """Return the QuantumChannel self + other. Args: other (complex): a complex number. Returns: Chi: the scalar multiplication other * self as a Chi object. Raises: QiskitError: if other is not a valid scalar. """ if not isinstance(other, Number): raise QiskitError("other is not a number") return Chi(other * self._data, self._input_dims, self._output_dims)
def multiply(self, other): """Return the QuantumChannel self + other. Args: other (complex): a complex number. Returns: Chi: the scalar multiplication other * self as a Chi object. Raises: QiskitError: if other is not a valid scalar. """ if not isinstance(other, Number): raise QiskitError("other is not a number") return Chi(other * self._data, 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/chi.py#L256-L270
[ "def", "multiply", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "Number", ")", ":", "raise", "QiskitError", "(", "\"other is not a number\"", ")", "return", "Chi", "(", "other", "*", "self", ".", "_data", ",", "self", ".", "_input_dims", ",", "self", ".", "_output_dims", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Chi._tensor_product
Return the tensor product channel. Args: other (QuantumChannel): a quantum channel. reverse (bool): If False return self ⊗ other, if True return if True return (other ⊗ self) [Default: False Returns: Chi: the tensor product channel as a Chi object. Raises: QiskitError: if other is not a QuantumChannel subclass.
qiskit/quantum_info/operators/channel/chi.py
def _tensor_product(self, other, reverse=False): """Return the tensor product channel. Args: other (QuantumChannel): a quantum channel. reverse (bool): If False return self ⊗ other, if True return if True return (other ⊗ self) [Default: False Returns: Chi: the tensor product channel as a Chi object. Raises: QiskitError: if other is not a QuantumChannel subclass. """ if not isinstance(other, Chi): other = Chi(other) if reverse: input_dims = self.input_dims() + other.input_dims() output_dims = self.output_dims() + other.output_dims() data = np.kron(other.data, self._data) else: input_dims = other.input_dims() + self.input_dims() output_dims = other.output_dims() + self.output_dims() data = np.kron(self._data, other.data) return Chi(data, input_dims, output_dims)
def _tensor_product(self, other, reverse=False): """Return the tensor product channel. Args: other (QuantumChannel): a quantum channel. reverse (bool): If False return self ⊗ other, if True return if True return (other ⊗ self) [Default: False Returns: Chi: the tensor product channel as a Chi object. Raises: QiskitError: if other is not a QuantumChannel subclass. """ if not isinstance(other, Chi): other = Chi(other) if reverse: input_dims = self.input_dims() + other.input_dims() output_dims = self.output_dims() + other.output_dims() data = np.kron(other.data, self._data) else: input_dims = other.input_dims() + self.input_dims() output_dims = other.output_dims() + self.output_dims() data = np.kron(self._data, other.data) return Chi(data, input_dims, output_dims)
[ "Return", "the", "tensor", "product", "channel", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/chi.py#L285-L308
[ "def", "_tensor_product", "(", "self", ",", "other", ",", "reverse", "=", "False", ")", ":", "if", "not", "isinstance", "(", "other", ",", "Chi", ")", ":", "other", "=", "Chi", "(", "other", ")", "if", "reverse", ":", "input_dims", "=", "self", ".", "input_dims", "(", ")", "+", "other", ".", "input_dims", "(", ")", "output_dims", "=", "self", ".", "output_dims", "(", ")", "+", "other", ".", "output_dims", "(", ")", "data", "=", "np", ".", "kron", "(", "other", ".", "data", ",", "self", ".", "_data", ")", "else", ":", "input_dims", "=", "other", ".", "input_dims", "(", ")", "+", "self", ".", "input_dims", "(", ")", "output_dims", "=", "other", ".", "output_dims", "(", ")", "+", "self", ".", "output_dims", "(", ")", "data", "=", "np", ".", "kron", "(", "self", ".", "_data", ",", "other", ".", "data", ")", "return", "Chi", "(", "data", ",", "input_dims", ",", "output_dims", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
SuperOp.conjugate
Return the conjugate of the QuantumChannel.
qiskit/quantum_info/operators/channel/superop.py
def conjugate(self): """Return the conjugate of the QuantumChannel.""" return SuperOp( np.conj(self._data), self.input_dims(), self.output_dims())
def conjugate(self): """Return the conjugate of the QuantumChannel.""" return SuperOp( np.conj(self._data), 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/superop.py#L117-L120
[ "def", "conjugate", "(", "self", ")", ":", "return", "SuperOp", "(", "np", ".", "conj", "(", "self", ".", "_data", ")", ",", "self", ".", "input_dims", "(", ")", ",", "self", ".", "output_dims", "(", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
SuperOp.transpose
Return the transpose of the QuantumChannel.
qiskit/quantum_info/operators/channel/superop.py
def transpose(self): """Return the transpose of the QuantumChannel.""" return SuperOp( np.transpose(self._data), input_dims=self.output_dims(), output_dims=self.input_dims())
def transpose(self): """Return the transpose of the QuantumChannel.""" return SuperOp( np.transpose(self._data), 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/superop.py#L122-L127
[ "def", "transpose", "(", "self", ")", ":", "return", "SuperOp", "(", "np", ".", "transpose", "(", "self", ".", "_data", ")", ",", "input_dims", "=", "self", ".", "output_dims", "(", ")", ",", "output_dims", "=", "self", ".", "input_dims", "(", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
SuperOp.compose
Return the composition channel self∘other. Args: other (QuantumChannel): a quantum channel. qargs (list): a list of subsystem positions to compose other on. front (bool): If False compose in standard order other(self(input)) otherwise compose in reverse order self(other(input)) [default: False] Returns: SuperOp: The composition channel as a SuperOp object. Raises: QiskitError: if other is not a QuantumChannel subclass, or has incompatible dimensions.
qiskit/quantum_info/operators/channel/superop.py
def compose(self, other, qargs=None, front=False): """Return the composition channel self∘other. Args: other (QuantumChannel): a quantum channel. qargs (list): a list of subsystem positions to compose other on. front (bool): If False compose in standard order other(self(input)) otherwise compose in reverse order self(other(input)) [default: False] Returns: SuperOp: The composition channel as a SuperOp object. Raises: QiskitError: if other is not a QuantumChannel subclass, or has incompatible dimensions. """ # Convert other to SuperOp if not isinstance(other, SuperOp): other = SuperOp(other) # Check dimensions are compatible if front and self.input_dims(qargs=qargs) != other.output_dims(): raise QiskitError( 'output_dims of other must match subsystem input_dims') if not front and self.output_dims(qargs=qargs) != other.input_dims(): raise QiskitError( 'input_dims of other must match subsystem output_dims') # Full composition of superoperators if qargs is None: if front: # Composition A(B(input)) return SuperOp( np.dot(self._data, other.data), input_dims=other.input_dims(), output_dims=self.output_dims()) # Composition B(A(input)) return SuperOp( np.dot(other.data, self._data), input_dims=self.input_dims(), output_dims=other.output_dims()) # Composition on subsystem return self._compose_subsystem(other, qargs, front)
def compose(self, other, qargs=None, front=False): """Return the composition channel self∘other. Args: other (QuantumChannel): a quantum channel. qargs (list): a list of subsystem positions to compose other on. front (bool): If False compose in standard order other(self(input)) otherwise compose in reverse order self(other(input)) [default: False] Returns: SuperOp: The composition channel as a SuperOp object. Raises: QiskitError: if other is not a QuantumChannel subclass, or has incompatible dimensions. """ # Convert other to SuperOp if not isinstance(other, SuperOp): other = SuperOp(other) # Check dimensions are compatible if front and self.input_dims(qargs=qargs) != other.output_dims(): raise QiskitError( 'output_dims of other must match subsystem input_dims') if not front and self.output_dims(qargs=qargs) != other.input_dims(): raise QiskitError( 'input_dims of other must match subsystem output_dims') # Full composition of superoperators if qargs is None: if front: # Composition A(B(input)) return SuperOp( np.dot(self._data, other.data), input_dims=other.input_dims(), output_dims=self.output_dims()) # Composition B(A(input)) return SuperOp( np.dot(other.data, self._data), input_dims=self.input_dims(), output_dims=other.output_dims()) # Composition on subsystem return self._compose_subsystem(other, qargs, front)
[ "Return", "the", "composition", "channel", "self∘other", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/superop.py#L129-L171
[ "def", "compose", "(", "self", ",", "other", ",", "qargs", "=", "None", ",", "front", "=", "False", ")", ":", "# Convert other to SuperOp", "if", "not", "isinstance", "(", "other", ",", "SuperOp", ")", ":", "other", "=", "SuperOp", "(", "other", ")", "# Check dimensions are compatible", "if", "front", "and", "self", ".", "input_dims", "(", "qargs", "=", "qargs", ")", "!=", "other", ".", "output_dims", "(", ")", ":", "raise", "QiskitError", "(", "'output_dims of other must match subsystem input_dims'", ")", "if", "not", "front", "and", "self", ".", "output_dims", "(", "qargs", "=", "qargs", ")", "!=", "other", ".", "input_dims", "(", ")", ":", "raise", "QiskitError", "(", "'input_dims of other must match subsystem output_dims'", ")", "# Full composition of superoperators", "if", "qargs", "is", "None", ":", "if", "front", ":", "# Composition A(B(input))", "return", "SuperOp", "(", "np", ".", "dot", "(", "self", ".", "_data", ",", "other", ".", "data", ")", ",", "input_dims", "=", "other", ".", "input_dims", "(", ")", ",", "output_dims", "=", "self", ".", "output_dims", "(", ")", ")", "# Composition B(A(input))", "return", "SuperOp", "(", "np", ".", "dot", "(", "other", ".", "data", ",", "self", ".", "_data", ")", ",", "input_dims", "=", "self", ".", "input_dims", "(", ")", ",", "output_dims", "=", "other", ".", "output_dims", "(", ")", ")", "# Composition on subsystem", "return", "self", ".", "_compose_subsystem", "(", "other", ",", "qargs", ",", "front", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
SuperOp.power
Return the compose of a QuantumChannel with itself n times. Args: n (int): compute the matrix power of the superoperator matrix. Returns: SuperOp: the n-times composition channel as a SuperOp object. 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/superop.py
def power(self, n): """Return the compose of a QuantumChannel with itself n times. Args: n (int): compute the matrix power of the superoperator matrix. Returns: SuperOp: the n-times composition channel as a SuperOp object. Raises: QiskitError: if the input and output dimensions of the QuantumChannel are not equal, or the power is not an integer. """ if not isinstance(n, (int, np.integer)): raise QiskitError("Can only power with integer powers.") if self._input_dim != self._output_dim: raise QiskitError("Can only power with input_dim = output_dim.") # Override base class power so we can implement more efficiently # using Numpy.matrix_power return SuperOp( np.linalg.matrix_power(self._data, n), self.input_dims(), self.output_dims())
def power(self, n): """Return the compose of a QuantumChannel with itself n times. Args: n (int): compute the matrix power of the superoperator matrix. Returns: SuperOp: the n-times composition channel as a SuperOp object. Raises: QiskitError: if the input and output dimensions of the QuantumChannel are not equal, or the power is not an integer. """ if not isinstance(n, (int, np.integer)): raise QiskitError("Can only power with integer powers.") if self._input_dim != self._output_dim: raise QiskitError("Can only power with input_dim = output_dim.") # Override base class power so we can implement more efficiently # using Numpy.matrix_power return SuperOp( np.linalg.matrix_power(self._data, n), self.input_dims(), self.output_dims())
[ "Return", "the", "compose", "of", "a", "QuantumChannel", "with", "itself", "n", "times", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/superop.py#L173-L194
[ "def", "power", "(", "self", ",", "n", ")", ":", "if", "not", "isinstance", "(", "n", ",", "(", "int", ",", "np", ".", "integer", ")", ")", ":", "raise", "QiskitError", "(", "\"Can only power with integer powers.\"", ")", "if", "self", ".", "_input_dim", "!=", "self", ".", "_output_dim", ":", "raise", "QiskitError", "(", "\"Can only power with input_dim = output_dim.\"", ")", "# Override base class power so we can implement more efficiently", "# using Numpy.matrix_power", "return", "SuperOp", "(", "np", ".", "linalg", ".", "matrix_power", "(", "self", ".", "_data", ",", "n", ")", ",", "self", ".", "input_dims", "(", ")", ",", "self", ".", "output_dims", "(", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
SuperOp.add
Return the QuantumChannel self + other. Args: other (QuantumChannel): a quantum channel. Returns: SuperOp: the linear addition self + other as a SuperOp object. Raises: QiskitError: if other cannot be converted to a channel or has incompatible dimensions.
qiskit/quantum_info/operators/channel/superop.py
def add(self, other): """Return the QuantumChannel self + other. Args: other (QuantumChannel): a quantum channel. Returns: SuperOp: the linear addition self + other as a SuperOp object. Raises: QiskitError: if other cannot be converted to a channel or has incompatible dimensions. """ # Convert other to SuperOp if not isinstance(other, SuperOp): other = SuperOp(other) if self.dim != other.dim: raise QiskitError("other QuantumChannel dimensions are not equal") return SuperOp(self._data + other.data, self.input_dims(), self.output_dims())
def add(self, other): """Return the QuantumChannel self + other. Args: other (QuantumChannel): a quantum channel. Returns: SuperOp: the linear addition self + other as a SuperOp object. Raises: QiskitError: if other cannot be converted to a channel or has incompatible dimensions. """ # Convert other to SuperOp if not isinstance(other, SuperOp): other = SuperOp(other) if self.dim != other.dim: raise QiskitError("other QuantumChannel dimensions are not equal") return SuperOp(self._data + other.data, 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/superop.py#L226-L245
[ "def", "add", "(", "self", ",", "other", ")", ":", "# Convert other to SuperOp", "if", "not", "isinstance", "(", "other", ",", "SuperOp", ")", ":", "other", "=", "SuperOp", "(", "other", ")", "if", "self", ".", "dim", "!=", "other", ".", "dim", ":", "raise", "QiskitError", "(", "\"other QuantumChannel dimensions are not equal\"", ")", "return", "SuperOp", "(", "self", ".", "_data", "+", "other", ".", "data", ",", "self", ".", "input_dims", "(", ")", ",", "self", ".", "output_dims", "(", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
SuperOp.multiply
Return the QuantumChannel self + other. Args: other (complex): a complex number. Returns: SuperOp: the scalar multiplication other * self as a SuperOp object. Raises: QiskitError: if other is not a valid scalar.
qiskit/quantum_info/operators/channel/superop.py
def multiply(self, other): """Return the QuantumChannel self + other. Args: other (complex): a complex number. Returns: SuperOp: the scalar multiplication other * self as a SuperOp object. Raises: QiskitError: if other is not a valid scalar. """ if not isinstance(other, Number): raise QiskitError("other is not a number") return SuperOp(other * self._data, self.input_dims(), self.output_dims())
def multiply(self, other): """Return the QuantumChannel self + other. Args: other (complex): a complex number. Returns: SuperOp: the scalar multiplication other * self as a SuperOp object. Raises: QiskitError: if other is not a valid scalar. """ if not isinstance(other, Number): raise QiskitError("other is not a number") return SuperOp(other * self._data, 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/superop.py#L268-L283
[ "def", "multiply", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "Number", ")", ":", "raise", "QiskitError", "(", "\"other is not a number\"", ")", "return", "SuperOp", "(", "other", "*", "self", ".", "_data", ",", "self", ".", "input_dims", "(", ")", ",", "self", ".", "output_dims", "(", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
SuperOp._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: DensityMatrix: the output quantum state as a density matrix. Raises: QiskitError: if the operator dimension does not match the specified QuantumState subsystem dimensions.
qiskit/quantum_info/operators/channel/superop.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: DensityMatrix: the output quantum state as a density matrix. Raises: QiskitError: if the operator dimension does not match the specified QuantumState subsystem dimensions. """ state = self._format_state(state, density_matrix=True) if qargs is None: if state.shape[0] != self._input_dim: raise QiskitError( "QuantumChannel input dimension is not equal to state dimension." ) shape_in = self._input_dim * self._input_dim shape_out = (self._output_dim, self._output_dim) # Return evolved density matrix return np.reshape( np.dot(self._data, np.reshape(state, shape_in, order='F')), shape_out, order='F') # Subsystem evolution return self._evolve_subsystem(state, qargs)
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: DensityMatrix: the output quantum state as a density matrix. Raises: QiskitError: if the operator dimension does not match the specified QuantumState subsystem dimensions. """ state = self._format_state(state, density_matrix=True) if qargs is None: if state.shape[0] != self._input_dim: raise QiskitError( "QuantumChannel input dimension is not equal to state dimension." ) shape_in = self._input_dim * self._input_dim shape_out = (self._output_dim, self._output_dim) # Return evolved density matrix return np.reshape( np.dot(self._data, np.reshape(state, shape_in, order='F')), shape_out, order='F') # Subsystem evolution return self._evolve_subsystem(state, qargs)
[ "Evolve", "a", "quantum", "state", "by", "the", "QuantumChannel", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/superop.py#L285-L314
[ "def", "_evolve", "(", "self", ",", "state", ",", "qargs", "=", "None", ")", ":", "state", "=", "self", ".", "_format_state", "(", "state", ",", "density_matrix", "=", "True", ")", "if", "qargs", "is", "None", ":", "if", "state", ".", "shape", "[", "0", "]", "!=", "self", ".", "_input_dim", ":", "raise", "QiskitError", "(", "\"QuantumChannel input dimension is not equal to state dimension.\"", ")", "shape_in", "=", "self", ".", "_input_dim", "*", "self", ".", "_input_dim", "shape_out", "=", "(", "self", ".", "_output_dim", ",", "self", ".", "_output_dim", ")", "# Return evolved density matrix", "return", "np", ".", "reshape", "(", "np", ".", "dot", "(", "self", ".", "_data", ",", "np", ".", "reshape", "(", "state", ",", "shape_in", ",", "order", "=", "'F'", ")", ")", ",", "shape_out", ",", "order", "=", "'F'", ")", "# Subsystem evolution", "return", "self", ".", "_evolve_subsystem", "(", "state", ",", "qargs", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
SuperOp._compose_subsystem
Return the composition channel.
qiskit/quantum_info/operators/channel/superop.py
def _compose_subsystem(self, other, qargs, front=False): """Return the composition channel.""" # Compute tensor contraction indices from qargs input_dims = list(self.input_dims()) output_dims = list(self.output_dims()) if front: num_indices = len(self.input_dims()) shift = 2 * len(self.output_dims()) right_mul = True for pos, qubit in enumerate(qargs): input_dims[qubit] = other._input_dims[pos] else: num_indices = len(self.output_dims()) shift = 0 right_mul = False for pos, qubit in enumerate(qargs): output_dims[qubit] = other._output_dims[pos] # Reshape current matrix # Note that we must reverse the subsystem dimension order as # qubit 0 corresponds to the right-most position in the tensor # product, which is the last tensor wire index. tensor = np.reshape(self.data, self._shape) mat = np.reshape(other.data, other._shape) # Add first set of indicies indices = [2 * num_indices - 1 - qubit for qubit in qargs ] + [num_indices - 1 - qubit for qubit in qargs] final_shape = [np.product(output_dims)**2, np.product(input_dims)**2] data = np.reshape( self._einsum_matmul(tensor, mat, indices, shift, right_mul), final_shape) return SuperOp(data, input_dims, output_dims)
def _compose_subsystem(self, other, qargs, front=False): """Return the composition channel.""" # Compute tensor contraction indices from qargs input_dims = list(self.input_dims()) output_dims = list(self.output_dims()) if front: num_indices = len(self.input_dims()) shift = 2 * len(self.output_dims()) right_mul = True for pos, qubit in enumerate(qargs): input_dims[qubit] = other._input_dims[pos] else: num_indices = len(self.output_dims()) shift = 0 right_mul = False for pos, qubit in enumerate(qargs): output_dims[qubit] = other._output_dims[pos] # Reshape current matrix # Note that we must reverse the subsystem dimension order as # qubit 0 corresponds to the right-most position in the tensor # product, which is the last tensor wire index. tensor = np.reshape(self.data, self._shape) mat = np.reshape(other.data, other._shape) # Add first set of indicies indices = [2 * num_indices - 1 - qubit for qubit in qargs ] + [num_indices - 1 - qubit for qubit in qargs] final_shape = [np.product(output_dims)**2, np.product(input_dims)**2] data = np.reshape( self._einsum_matmul(tensor, mat, indices, shift, right_mul), final_shape) return SuperOp(data, input_dims, output_dims)
[ "Return", "the", "composition", "channel", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/superop.py#L316-L346
[ "def", "_compose_subsystem", "(", "self", ",", "other", ",", "qargs", ",", "front", "=", "False", ")", ":", "# Compute tensor contraction indices from qargs", "input_dims", "=", "list", "(", "self", ".", "input_dims", "(", ")", ")", "output_dims", "=", "list", "(", "self", ".", "output_dims", "(", ")", ")", "if", "front", ":", "num_indices", "=", "len", "(", "self", ".", "input_dims", "(", ")", ")", "shift", "=", "2", "*", "len", "(", "self", ".", "output_dims", "(", ")", ")", "right_mul", "=", "True", "for", "pos", ",", "qubit", "in", "enumerate", "(", "qargs", ")", ":", "input_dims", "[", "qubit", "]", "=", "other", ".", "_input_dims", "[", "pos", "]", "else", ":", "num_indices", "=", "len", "(", "self", ".", "output_dims", "(", ")", ")", "shift", "=", "0", "right_mul", "=", "False", "for", "pos", ",", "qubit", "in", "enumerate", "(", "qargs", ")", ":", "output_dims", "[", "qubit", "]", "=", "other", ".", "_output_dims", "[", "pos", "]", "# Reshape current matrix", "# Note that we must reverse the subsystem dimension order as", "# qubit 0 corresponds to the right-most position in the tensor", "# product, which is the last tensor wire index.", "tensor", "=", "np", ".", "reshape", "(", "self", ".", "data", ",", "self", ".", "_shape", ")", "mat", "=", "np", ".", "reshape", "(", "other", ".", "data", ",", "other", ".", "_shape", ")", "# Add first set of indicies", "indices", "=", "[", "2", "*", "num_indices", "-", "1", "-", "qubit", "for", "qubit", "in", "qargs", "]", "+", "[", "num_indices", "-", "1", "-", "qubit", "for", "qubit", "in", "qargs", "]", "final_shape", "=", "[", "np", ".", "product", "(", "output_dims", ")", "**", "2", ",", "np", ".", "product", "(", "input_dims", ")", "**", "2", "]", "data", "=", "np", ".", "reshape", "(", "self", ".", "_einsum_matmul", "(", "tensor", ",", "mat", ",", "indices", ",", "shift", ",", "right_mul", ")", ",", "final_shape", ")", "return", "SuperOp", "(", "data", ",", "input_dims", ",", "output_dims", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
SuperOp._evolve_subsystem
Evolve a quantum state by the operator. 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/superop.py
def _evolve_subsystem(self, state, qargs): """Evolve a quantum state by the operator. 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. """ mat = np.reshape(self.data, self._shape) # Hack to assume state is a N-qubit state until a proper class for states # is in place state_size = len(state) state_dims = self._automatic_dims(None, state_size) if self.input_dims() != len(qargs) * (2, ): raise QiskitError( "Channel input dimensions are not compatible with state subsystem dimensions." ) # Return evolved density matrix tensor = np.reshape(state, 2 * state_dims) num_inidices = len(state_dims) indices = [num_inidices - 1 - qubit for qubit in qargs ] + [2 * num_inidices - 1 - qubit for qubit in qargs] tensor = self._einsum_matmul(tensor, mat, indices) return np.reshape(tensor, [state_size, state_size])
def _evolve_subsystem(self, state, qargs): """Evolve a quantum state by the operator. 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. """ mat = np.reshape(self.data, self._shape) # Hack to assume state is a N-qubit state until a proper class for states # is in place state_size = len(state) state_dims = self._automatic_dims(None, state_size) if self.input_dims() != len(qargs) * (2, ): raise QiskitError( "Channel input dimensions are not compatible with state subsystem dimensions." ) # Return evolved density matrix tensor = np.reshape(state, 2 * state_dims) num_inidices = len(state_dims) indices = [num_inidices - 1 - qubit for qubit in qargs ] + [2 * num_inidices - 1 - qubit for qubit in qargs] tensor = self._einsum_matmul(tensor, mat, indices) return np.reshape(tensor, [state_size, state_size])
[ "Evolve", "a", "quantum", "state", "by", "the", "operator", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/superop.py#L348-L378
[ "def", "_evolve_subsystem", "(", "self", ",", "state", ",", "qargs", ")", ":", "mat", "=", "np", ".", "reshape", "(", "self", ".", "data", ",", "self", ".", "_shape", ")", "# Hack to assume state is a N-qubit state until a proper class for states", "# is in place", "state_size", "=", "len", "(", "state", ")", "state_dims", "=", "self", ".", "_automatic_dims", "(", "None", ",", "state_size", ")", "if", "self", ".", "input_dims", "(", ")", "!=", "len", "(", "qargs", ")", "*", "(", "2", ",", ")", ":", "raise", "QiskitError", "(", "\"Channel input dimensions are not compatible with state subsystem dimensions.\"", ")", "# Return evolved density matrix", "tensor", "=", "np", ".", "reshape", "(", "state", ",", "2", "*", "state_dims", ")", "num_inidices", "=", "len", "(", "state_dims", ")", "indices", "=", "[", "num_inidices", "-", "1", "-", "qubit", "for", "qubit", "in", "qargs", "]", "+", "[", "2", "*", "num_inidices", "-", "1", "-", "qubit", "for", "qubit", "in", "qargs", "]", "tensor", "=", "self", ".", "_einsum_matmul", "(", "tensor", ",", "mat", ",", "indices", ")", "return", "np", ".", "reshape", "(", "tensor", ",", "[", "state_size", ",", "state_size", "]", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
SuperOp._instruction_to_superop
Convert a QuantumCircuit or Instruction to a SuperOp.
qiskit/quantum_info/operators/channel/superop.py
def _instruction_to_superop(cls, instruction): """Convert a QuantumCircuit or Instruction to a SuperOp.""" # Convert circuit to an instruction if isinstance(instruction, QuantumCircuit): instruction = instruction.to_instruction() # Initialize an identity superoperator of the correct size # of the circuit op = SuperOp(np.eye(4 ** instruction.num_qubits)) op._append_instruction(instruction) return op
def _instruction_to_superop(cls, instruction): """Convert a QuantumCircuit or Instruction to a SuperOp.""" # Convert circuit to an instruction if isinstance(instruction, QuantumCircuit): instruction = instruction.to_instruction() # Initialize an identity superoperator of the correct size # of the circuit op = SuperOp(np.eye(4 ** instruction.num_qubits)) op._append_instruction(instruction) return op
[ "Convert", "a", "QuantumCircuit", "or", "Instruction", "to", "a", "SuperOp", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/superop.py#L416-L425
[ "def", "_instruction_to_superop", "(", "cls", ",", "instruction", ")", ":", "# Convert circuit to an instruction", "if", "isinstance", "(", "instruction", ",", "QuantumCircuit", ")", ":", "instruction", "=", "instruction", ".", "to_instruction", "(", ")", "# Initialize an identity superoperator of the correct size", "# of the circuit", "op", "=", "SuperOp", "(", "np", ".", "eye", "(", "4", "**", "instruction", ".", "num_qubits", ")", ")", "op", ".", "_append_instruction", "(", "instruction", ")", "return", "op" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
SuperOp._append_instruction
Update the current Operator by apply an instruction.
qiskit/quantum_info/operators/channel/superop.py
def _append_instruction(self, obj, qargs=None): """Update the current Operator by apply an instruction.""" if isinstance(obj, Instruction): chan = None if obj.name == 'reset': # For superoperator evolution we can simulate a reset as # a non-unitary supeorperator matrix chan = SuperOp( np.array([[1, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])) if obj.name == 'kraus': kraus = obj.params dim = len(kraus[0]) chan = SuperOp(_to_superop('Kraus', (kraus, None), dim, dim)) elif hasattr(obj, 'to_matrix'): # If instruction is a gate first we see if it has a # `to_matrix` definition and if so use that. try: kraus = [obj.to_matrix()] dim = len(kraus[0]) chan = SuperOp( _to_superop('Kraus', (kraus, None), dim, dim)) except QiskitError: pass if chan is not None: # Perform the composition and inplace update the current state # of the operator op = self.compose(chan, qargs=qargs) self._data = op.data else: # If the instruction doesn't have a matrix defined we use its # circuit decomposition definition if it exists, otherwise we # cannot compose this gate and raise an error. if obj.definition is None: raise QiskitError('Cannot apply Instruction: {}'.format( obj.name)) for instr, qregs, cregs in obj.definition: if cregs: raise QiskitError( 'Cannot apply instruction with classical registers: {}' .format(instr.name)) # Get the integer position of the flat register new_qargs = [tup[1] for tup in qregs] self._append_instruction(instr, qargs=new_qargs) else: raise QiskitError('Input is not an instruction.')
def _append_instruction(self, obj, qargs=None): """Update the current Operator by apply an instruction.""" if isinstance(obj, Instruction): chan = None if obj.name == 'reset': # For superoperator evolution we can simulate a reset as # a non-unitary supeorperator matrix chan = SuperOp( np.array([[1, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])) if obj.name == 'kraus': kraus = obj.params dim = len(kraus[0]) chan = SuperOp(_to_superop('Kraus', (kraus, None), dim, dim)) elif hasattr(obj, 'to_matrix'): # If instruction is a gate first we see if it has a # `to_matrix` definition and if so use that. try: kraus = [obj.to_matrix()] dim = len(kraus[0]) chan = SuperOp( _to_superop('Kraus', (kraus, None), dim, dim)) except QiskitError: pass if chan is not None: # Perform the composition and inplace update the current state # of the operator op = self.compose(chan, qargs=qargs) self._data = op.data else: # If the instruction doesn't have a matrix defined we use its # circuit decomposition definition if it exists, otherwise we # cannot compose this gate and raise an error. if obj.definition is None: raise QiskitError('Cannot apply Instruction: {}'.format( obj.name)) for instr, qregs, cregs in obj.definition: if cregs: raise QiskitError( 'Cannot apply instruction with classical registers: {}' .format(instr.name)) # Get the integer position of the flat register new_qargs = [tup[1] for tup in qregs] self._append_instruction(instr, qargs=new_qargs) else: raise QiskitError('Input is not an instruction.')
[ "Update", "the", "current", "Operator", "by", "apply", "an", "instruction", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/superop.py#L427-L472
[ "def", "_append_instruction", "(", "self", ",", "obj", ",", "qargs", "=", "None", ")", ":", "if", "isinstance", "(", "obj", ",", "Instruction", ")", ":", "chan", "=", "None", "if", "obj", ".", "name", "==", "'reset'", ":", "# For superoperator evolution we can simulate a reset as", "# a non-unitary supeorperator matrix", "chan", "=", "SuperOp", "(", "np", ".", "array", "(", "[", "[", "1", ",", "0", ",", "0", ",", "1", "]", ",", "[", "0", ",", "0", ",", "0", ",", "0", "]", ",", "[", "0", ",", "0", ",", "0", ",", "0", "]", ",", "[", "0", ",", "0", ",", "0", ",", "0", "]", "]", ")", ")", "if", "obj", ".", "name", "==", "'kraus'", ":", "kraus", "=", "obj", ".", "params", "dim", "=", "len", "(", "kraus", "[", "0", "]", ")", "chan", "=", "SuperOp", "(", "_to_superop", "(", "'Kraus'", ",", "(", "kraus", ",", "None", ")", ",", "dim", ",", "dim", ")", ")", "elif", "hasattr", "(", "obj", ",", "'to_matrix'", ")", ":", "# If instruction is a gate first we see if it has a", "# `to_matrix` definition and if so use that.", "try", ":", "kraus", "=", "[", "obj", ".", "to_matrix", "(", ")", "]", "dim", "=", "len", "(", "kraus", "[", "0", "]", ")", "chan", "=", "SuperOp", "(", "_to_superop", "(", "'Kraus'", ",", "(", "kraus", ",", "None", ")", ",", "dim", ",", "dim", ")", ")", "except", "QiskitError", ":", "pass", "if", "chan", "is", "not", "None", ":", "# Perform the composition and inplace update the current state", "# of the operator", "op", "=", "self", ".", "compose", "(", "chan", ",", "qargs", "=", "qargs", ")", "self", ".", "_data", "=", "op", ".", "data", "else", ":", "# If the instruction doesn't have a matrix defined we use its", "# circuit decomposition definition if it exists, otherwise we", "# cannot compose this gate and raise an error.", "if", "obj", ".", "definition", "is", "None", ":", "raise", "QiskitError", "(", "'Cannot apply Instruction: {}'", ".", "format", "(", "obj", ".", "name", ")", ")", "for", "instr", ",", "qregs", ",", "cregs", "in", "obj", ".", "definition", ":", "if", "cregs", ":", "raise", "QiskitError", "(", "'Cannot apply instruction with classical registers: {}'", ".", "format", "(", "instr", ".", "name", ")", ")", "# Get the integer position of the flat register", "new_qargs", "=", "[", "tup", "[", "1", "]", "for", "tup", "in", "qregs", "]", "self", ".", "_append_instruction", "(", "instr", ",", "qargs", "=", "new_qargs", ")", "else", ":", "raise", "QiskitError", "(", "'Input is not an instruction.'", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BarrierBeforeFinalMeasurements.run
Return a circuit with a barrier before last measurements.
qiskit/transpiler/passes/mapping/barrier_before_final_measurements.py
def run(self, dag): """Return a circuit with a barrier before last measurements.""" # Collect DAG nodes which are followed only by barriers or other measures. final_op_types = ['measure', 'barrier'] final_ops = [] for candidate_node in dag.named_nodes(*final_op_types): is_final_op = True for _, child_successors in dag.bfs_successors(candidate_node): if any(suc.type == 'op' and suc.name not in final_op_types for suc in child_successors): is_final_op = False break if is_final_op: final_ops.append(candidate_node) if not final_ops: return dag # Create a layer with the barrier and add registers from the original dag. barrier_layer = DAGCircuit() for qreg in dag.qregs.values(): barrier_layer.add_qreg(qreg) for creg in dag.cregs.values(): barrier_layer.add_creg(creg) final_qubits = set(final_op.qargs[0] for final_op in final_ops) barrier_layer.apply_operation_back( Barrier(len(final_qubits)), list(final_qubits), []) # Preserve order of final ops collected earlier from the original DAG. ordered_final_nodes = [node for node in dag.topological_op_nodes() if node in set(final_ops)] # Move final ops to the new layer and append the new layer to the DAG. for final_node in ordered_final_nodes: barrier_layer.apply_operation_back(final_node.op, final_node.qargs, final_node.cargs) for final_op in final_ops: dag.remove_op_node(final_op) dag.extend_back(barrier_layer) # Merge the new barrier into any other barriers adjacent_pass = MergeAdjacentBarriers() return adjacent_pass.run(dag)
def run(self, dag): """Return a circuit with a barrier before last measurements.""" # Collect DAG nodes which are followed only by barriers or other measures. final_op_types = ['measure', 'barrier'] final_ops = [] for candidate_node in dag.named_nodes(*final_op_types): is_final_op = True for _, child_successors in dag.bfs_successors(candidate_node): if any(suc.type == 'op' and suc.name not in final_op_types for suc in child_successors): is_final_op = False break if is_final_op: final_ops.append(candidate_node) if not final_ops: return dag # Create a layer with the barrier and add registers from the original dag. barrier_layer = DAGCircuit() for qreg in dag.qregs.values(): barrier_layer.add_qreg(qreg) for creg in dag.cregs.values(): barrier_layer.add_creg(creg) final_qubits = set(final_op.qargs[0] for final_op in final_ops) barrier_layer.apply_operation_back( Barrier(len(final_qubits)), list(final_qubits), []) # Preserve order of final ops collected earlier from the original DAG. ordered_final_nodes = [node for node in dag.topological_op_nodes() if node in set(final_ops)] # Move final ops to the new layer and append the new layer to the DAG. for final_node in ordered_final_nodes: barrier_layer.apply_operation_back(final_node.op, final_node.qargs, final_node.cargs) for final_op in final_ops: dag.remove_op_node(final_op) dag.extend_back(barrier_layer) # Merge the new barrier into any other barriers adjacent_pass = MergeAdjacentBarriers() return adjacent_pass.run(dag)
[ "Return", "a", "circuit", "with", "a", "barrier", "before", "last", "measurements", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/barrier_before_final_measurements.py#L25-L76
[ "def", "run", "(", "self", ",", "dag", ")", ":", "# Collect DAG nodes which are followed only by barriers or other measures.", "final_op_types", "=", "[", "'measure'", ",", "'barrier'", "]", "final_ops", "=", "[", "]", "for", "candidate_node", "in", "dag", ".", "named_nodes", "(", "*", "final_op_types", ")", ":", "is_final_op", "=", "True", "for", "_", ",", "child_successors", "in", "dag", ".", "bfs_successors", "(", "candidate_node", ")", ":", "if", "any", "(", "suc", ".", "type", "==", "'op'", "and", "suc", ".", "name", "not", "in", "final_op_types", "for", "suc", "in", "child_successors", ")", ":", "is_final_op", "=", "False", "break", "if", "is_final_op", ":", "final_ops", ".", "append", "(", "candidate_node", ")", "if", "not", "final_ops", ":", "return", "dag", "# Create a layer with the barrier and add registers from the original dag.", "barrier_layer", "=", "DAGCircuit", "(", ")", "for", "qreg", "in", "dag", ".", "qregs", ".", "values", "(", ")", ":", "barrier_layer", ".", "add_qreg", "(", "qreg", ")", "for", "creg", "in", "dag", ".", "cregs", ".", "values", "(", ")", ":", "barrier_layer", ".", "add_creg", "(", "creg", ")", "final_qubits", "=", "set", "(", "final_op", ".", "qargs", "[", "0", "]", "for", "final_op", "in", "final_ops", ")", "barrier_layer", ".", "apply_operation_back", "(", "Barrier", "(", "len", "(", "final_qubits", ")", ")", ",", "list", "(", "final_qubits", ")", ",", "[", "]", ")", "# Preserve order of final ops collected earlier from the original DAG.", "ordered_final_nodes", "=", "[", "node", "for", "node", "in", "dag", ".", "topological_op_nodes", "(", ")", "if", "node", "in", "set", "(", "final_ops", ")", "]", "# Move final ops to the new layer and append the new layer to the DAG.", "for", "final_node", "in", "ordered_final_nodes", ":", "barrier_layer", ".", "apply_operation_back", "(", "final_node", ".", "op", ",", "final_node", ".", "qargs", ",", "final_node", ".", "cargs", ")", "for", "final_op", "in", "final_ops", ":", "dag", ".", "remove_op_node", "(", "final_op", ")", "dag", ".", "extend_back", "(", "barrier_layer", ")", "# Merge the new barrier into any other barriers", "adjacent_pass", "=", "MergeAdjacentBarriers", "(", ")", "return", "adjacent_pass", ".", "run", "(", "dag", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
circuits_to_qobj
Convert a list of circuits into a qobj. Args: circuits (list[QuantumCircuits] or QuantumCircuit): circuits to compile qobj_header (QobjHeader): header to pass to the results qobj_id (int): TODO: delete after qiskit-terra 0.8 backend_name (str): TODO: delete after qiskit-terra 0.8 config (dict): TODO: delete after qiskit-terra 0.8 shots (int): TODO: delete after qiskit-terra 0.8 max_credits (int): TODO: delete after qiskit-terra 0.8 basis_gates (str): TODO: delete after qiskit-terra 0.8 coupling_map (list): TODO: delete after qiskit-terra 0.8 seed (int): TODO: delete after qiskit-terra 0.8 memory (bool): TODO: delete after qiskit-terra 0.8 Returns: Qobj: the Qobj to be run on the backends
qiskit/converters/circuits_to_qobj.py
def circuits_to_qobj(circuits, qobj_header=None, qobj_id=None, backend_name=None, config=None, shots=None, max_credits=None, basis_gates=None, coupling_map=None, seed=None, memory=None): """Convert a list of circuits into a qobj. Args: circuits (list[QuantumCircuits] or QuantumCircuit): circuits to compile qobj_header (QobjHeader): header to pass to the results qobj_id (int): TODO: delete after qiskit-terra 0.8 backend_name (str): TODO: delete after qiskit-terra 0.8 config (dict): TODO: delete after qiskit-terra 0.8 shots (int): TODO: delete after qiskit-terra 0.8 max_credits (int): TODO: delete after qiskit-terra 0.8 basis_gates (str): TODO: delete after qiskit-terra 0.8 coupling_map (list): TODO: delete after qiskit-terra 0.8 seed (int): TODO: delete after qiskit-terra 0.8 memory (bool): TODO: delete after qiskit-terra 0.8 Returns: Qobj: the Qobj to be run on the backends """ warnings.warn('circuits_to_qobj is deprecated and will be removed in Qiskit Terra 0.9. ' 'Use qiskit.compiler.assemble() to serialize circuits into a qobj.', DeprecationWarning) qobj_header = qobj_header or QobjHeader() if backend_name: qobj_header.backend_name = backend_name if basis_gates: warnings.warn('basis_gates was unused and will be removed.', DeprecationWarning) if coupling_map: warnings.warn('coupling_map was unused and will be removed.', DeprecationWarning) qobj = assemble(experiments=circuits, qobj_id=qobj_id, qobj_header=qobj_header, shots=shots, memory=memory, max_credits=max_credits, seed_simulator=seed, config=config) return qobj
def circuits_to_qobj(circuits, qobj_header=None, qobj_id=None, backend_name=None, config=None, shots=None, max_credits=None, basis_gates=None, coupling_map=None, seed=None, memory=None): """Convert a list of circuits into a qobj. Args: circuits (list[QuantumCircuits] or QuantumCircuit): circuits to compile qobj_header (QobjHeader): header to pass to the results qobj_id (int): TODO: delete after qiskit-terra 0.8 backend_name (str): TODO: delete after qiskit-terra 0.8 config (dict): TODO: delete after qiskit-terra 0.8 shots (int): TODO: delete after qiskit-terra 0.8 max_credits (int): TODO: delete after qiskit-terra 0.8 basis_gates (str): TODO: delete after qiskit-terra 0.8 coupling_map (list): TODO: delete after qiskit-terra 0.8 seed (int): TODO: delete after qiskit-terra 0.8 memory (bool): TODO: delete after qiskit-terra 0.8 Returns: Qobj: the Qobj to be run on the backends """ warnings.warn('circuits_to_qobj is deprecated and will be removed in Qiskit Terra 0.9. ' 'Use qiskit.compiler.assemble() to serialize circuits into a qobj.', DeprecationWarning) qobj_header = qobj_header or QobjHeader() if backend_name: qobj_header.backend_name = backend_name if basis_gates: warnings.warn('basis_gates was unused and will be removed.', DeprecationWarning) if coupling_map: warnings.warn('coupling_map was unused and will be removed.', DeprecationWarning) qobj = assemble(experiments=circuits, qobj_id=qobj_id, qobj_header=qobj_header, shots=shots, memory=memory, max_credits=max_credits, seed_simulator=seed, config=config) return qobj
[ "Convert", "a", "list", "of", "circuits", "into", "a", "qobj", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/converters/circuits_to_qobj.py#L15-L60
[ "def", "circuits_to_qobj", "(", "circuits", ",", "qobj_header", "=", "None", ",", "qobj_id", "=", "None", ",", "backend_name", "=", "None", ",", "config", "=", "None", ",", "shots", "=", "None", ",", "max_credits", "=", "None", ",", "basis_gates", "=", "None", ",", "coupling_map", "=", "None", ",", "seed", "=", "None", ",", "memory", "=", "None", ")", ":", "warnings", ".", "warn", "(", "'circuits_to_qobj is deprecated and will be removed in Qiskit Terra 0.9. '", "'Use qiskit.compiler.assemble() to serialize circuits into a qobj.'", ",", "DeprecationWarning", ")", "qobj_header", "=", "qobj_header", "or", "QobjHeader", "(", ")", "if", "backend_name", ":", "qobj_header", ".", "backend_name", "=", "backend_name", "if", "basis_gates", ":", "warnings", ".", "warn", "(", "'basis_gates was unused and will be removed.'", ",", "DeprecationWarning", ")", "if", "coupling_map", ":", "warnings", ".", "warn", "(", "'coupling_map was unused and will be removed.'", ",", "DeprecationWarning", ")", "qobj", "=", "assemble", "(", "experiments", "=", "circuits", ",", "qobj_id", "=", "qobj_id", ",", "qobj_header", "=", "qobj_header", ",", "shots", "=", "shots", ",", "memory", "=", "memory", ",", "max_credits", "=", "max_credits", ",", "seed_simulator", "=", "seed", ",", "config", "=", "config", ")", "return", "qobj" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Unroll3qOrMore.run
Expand 3+ qubit gates using their decomposition rules. Args: dag(DAGCircuit): input dag Returns: DAGCircuit: output dag with maximum node degrees of 2 Raises: QiskitError: if a 3q+ gate is not decomposable
qiskit/transpiler/passes/unroll_3q_or_more.py
def run(self, dag): """Expand 3+ qubit gates using their decomposition rules. Args: dag(DAGCircuit): input dag Returns: DAGCircuit: output dag with maximum node degrees of 2 Raises: QiskitError: if a 3q+ gate is not decomposable """ for node in dag.threeQ_or_more_gates(): # TODO: allow choosing other possible decompositions rule = node.op.definition if not rule: raise QiskitError("Cannot unroll all 3q or more gates. " "No rule to expand instruction %s." % node.op.name) # hacky way to build a dag on the same register as the rule is defined # TODO: need anonymous rules to address wires by index decomposition = DAGCircuit() decomposition.add_qreg(rule[0][1][0][0]) for inst in rule: decomposition.apply_operation_back(*inst) decomposition = self.run(decomposition) # recursively unroll dag.substitute_node_with_dag(node, decomposition) return dag
def run(self, dag): """Expand 3+ qubit gates using their decomposition rules. Args: dag(DAGCircuit): input dag Returns: DAGCircuit: output dag with maximum node degrees of 2 Raises: QiskitError: if a 3q+ gate is not decomposable """ for node in dag.threeQ_or_more_gates(): # TODO: allow choosing other possible decompositions rule = node.op.definition if not rule: raise QiskitError("Cannot unroll all 3q or more gates. " "No rule to expand instruction %s." % node.op.name) # hacky way to build a dag on the same register as the rule is defined # TODO: need anonymous rules to address wires by index decomposition = DAGCircuit() decomposition.add_qreg(rule[0][1][0][0]) for inst in rule: decomposition.apply_operation_back(*inst) decomposition = self.run(decomposition) # recursively unroll dag.substitute_node_with_dag(node, decomposition) return dag
[ "Expand", "3", "+", "qubit", "gates", "using", "their", "decomposition", "rules", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/unroll_3q_or_more.py#L21-L47
[ "def", "run", "(", "self", ",", "dag", ")", ":", "for", "node", "in", "dag", ".", "threeQ_or_more_gates", "(", ")", ":", "# TODO: allow choosing other possible decompositions", "rule", "=", "node", ".", "op", ".", "definition", "if", "not", "rule", ":", "raise", "QiskitError", "(", "\"Cannot unroll all 3q or more gates. \"", "\"No rule to expand instruction %s.\"", "%", "node", ".", "op", ".", "name", ")", "# hacky way to build a dag on the same register as the rule is defined", "# TODO: need anonymous rules to address wires by index", "decomposition", "=", "DAGCircuit", "(", ")", "decomposition", ".", "add_qreg", "(", "rule", "[", "0", "]", "[", "1", "]", "[", "0", "]", "[", "0", "]", ")", "for", "inst", "in", "rule", ":", "decomposition", ".", "apply_operation_back", "(", "*", "inst", ")", "decomposition", "=", "self", ".", "run", "(", "decomposition", ")", "# recursively unroll", "dag", ".", "substitute_node_with_dag", "(", "node", ",", "decomposition", ")", "return", "dag" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Decompose.run
Expand a given gate into its decomposition. Args: dag(DAGCircuit): input dag Returns: DAGCircuit: output dag where gate was expanded.
qiskit/transpiler/passes/decompose.py
def run(self, dag): """Expand a given gate into its decomposition. Args: dag(DAGCircuit): input dag Returns: DAGCircuit: output dag where gate was expanded. """ # Walk through the DAG and expand each non-basis node for node in dag.op_nodes(self.gate): # opaque or built-in gates are not decomposable if not node.op.definition: continue # TODO: allow choosing among multiple decomposition rules rule = node.op.definition # hacky way to build a dag on the same register as the rule is defined # TODO: need anonymous rules to address wires by index decomposition = DAGCircuit() decomposition.add_qreg(rule[0][1][0][0]) if rule[0][2]: decomposition.add_creg(rule[0][2][0][0]) for inst in rule: decomposition.apply_operation_back(*inst) dag.substitute_node_with_dag(node, decomposition) return dag
def run(self, dag): """Expand a given gate into its decomposition. Args: dag(DAGCircuit): input dag Returns: DAGCircuit: output dag where gate was expanded. """ # Walk through the DAG and expand each non-basis node for node in dag.op_nodes(self.gate): # opaque or built-in gates are not decomposable if not node.op.definition: continue # TODO: allow choosing among multiple decomposition rules rule = node.op.definition # hacky way to build a dag on the same register as the rule is defined # TODO: need anonymous rules to address wires by index decomposition = DAGCircuit() decomposition.add_qreg(rule[0][1][0][0]) if rule[0][2]: decomposition.add_creg(rule[0][2][0][0]) for inst in rule: decomposition.apply_operation_back(*inst) dag.substitute_node_with_dag(node, decomposition) return dag
[ "Expand", "a", "given", "gate", "into", "its", "decomposition", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/decompose.py#L27-L51
[ "def", "run", "(", "self", ",", "dag", ")", ":", "# Walk through the DAG and expand each non-basis node", "for", "node", "in", "dag", ".", "op_nodes", "(", "self", ".", "gate", ")", ":", "# opaque or built-in gates are not decomposable", "if", "not", "node", ".", "op", ".", "definition", ":", "continue", "# TODO: allow choosing among multiple decomposition rules", "rule", "=", "node", ".", "op", ".", "definition", "# hacky way to build a dag on the same register as the rule is defined", "# TODO: need anonymous rules to address wires by index", "decomposition", "=", "DAGCircuit", "(", ")", "decomposition", ".", "add_qreg", "(", "rule", "[", "0", "]", "[", "1", "]", "[", "0", "]", "[", "0", "]", ")", "if", "rule", "[", "0", "]", "[", "2", "]", ":", "decomposition", ".", "add_creg", "(", "rule", "[", "0", "]", "[", "2", "]", "[", "0", "]", "[", "0", "]", ")", "for", "inst", "in", "rule", ":", "decomposition", ".", "apply_operation_back", "(", "*", "inst", ")", "dag", ".", "substitute_node_with_dag", "(", "node", ",", "decomposition", ")", "return", "dag" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
unitary
Apply u2 to q.
qiskit/extensions/unitary.py
def unitary(self, obj, qubits, label=None): """Apply u2 to q.""" if isinstance(qubits, QuantumRegister): qubits = qubits[:] return self.append(UnitaryGate(obj, label=label), qubits, [])
def unitary(self, obj, qubits, label=None): """Apply u2 to q.""" if isinstance(qubits, QuantumRegister): qubits = qubits[:] return self.append(UnitaryGate(obj, label=label), qubits, [])
[ "Apply", "u2", "to", "q", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/unitary.py#L102-L106
[ "def", "unitary", "(", "self", ",", "obj", ",", "qubits", ",", "label", "=", "None", ")", ":", "if", "isinstance", "(", "qubits", ",", "QuantumRegister", ")", ":", "qubits", "=", "qubits", "[", ":", "]", "return", "self", ".", "append", "(", "UnitaryGate", "(", "obj", ",", "label", "=", "label", ")", ",", "qubits", ",", "[", "]", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
UnitaryGate._define
Calculate a subcircuit that implements this unitary.
qiskit/extensions/unitary.py
def _define(self): """Calculate a subcircuit that implements this unitary.""" if self.num_qubits == 1: q = QuantumRegister(1, "q") angles = euler_angles_1q(self.to_matrix()) self.definition = [(U3Gate(*angles), [q[0]], [])] if self.num_qubits == 2: self.definition = two_qubit_kak(self.to_matrix())
def _define(self): """Calculate a subcircuit that implements this unitary.""" if self.num_qubits == 1: q = QuantumRegister(1, "q") angles = euler_angles_1q(self.to_matrix()) self.definition = [(U3Gate(*angles), [q[0]], [])] if self.num_qubits == 2: self.definition = two_qubit_kak(self.to_matrix())
[ "Calculate", "a", "subcircuit", "that", "implements", "this", "unitary", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/unitary.py#L92-L99
[ "def", "_define", "(", "self", ")", ":", "if", "self", ".", "num_qubits", "==", "1", ":", "q", "=", "QuantumRegister", "(", "1", ",", "\"q\"", ")", "angles", "=", "euler_angles_1q", "(", "self", ".", "to_matrix", "(", ")", ")", "self", ".", "definition", "=", "[", "(", "U3Gate", "(", "*", "angles", ")", ",", "[", "q", "[", "0", "]", "]", ",", "[", "]", ")", "]", "if", "self", ".", "num_qubits", "==", "2", ":", "self", ".", "definition", "=", "two_qubit_kak", "(", "self", ".", "to_matrix", "(", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Nested.check_type
Validate if the value is of the type of the schema's model. Assumes the nested schema is a ``BaseSchema``.
qiskit/validation/fields/containers.py
def check_type(self, value, attr, data): """Validate if the value is of the type of the schema's model. Assumes the nested schema is a ``BaseSchema``. """ if self.many and not is_collection(value): raise self._not_expected_type( value, Iterable, fields=[self], field_names=attr, data=data) _check_type = super().check_type errors = [] values = value if self.many else [value] for idx, v in enumerate(values): try: _check_type(v, idx, values) except ValidationError as err: errors.append(err.messages) if errors: errors = errors if self.many else errors[0] raise ValidationError(errors) return value
def check_type(self, value, attr, data): """Validate if the value is of the type of the schema's model. Assumes the nested schema is a ``BaseSchema``. """ if self.many and not is_collection(value): raise self._not_expected_type( value, Iterable, fields=[self], field_names=attr, data=data) _check_type = super().check_type errors = [] values = value if self.many else [value] for idx, v in enumerate(values): try: _check_type(v, idx, values) except ValidationError as err: errors.append(err.messages) if errors: errors = errors if self.many else errors[0] raise ValidationError(errors) return value
[ "Validate", "if", "the", "value", "is", "of", "the", "type", "of", "the", "schema", "s", "model", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/validation/fields/containers.py#L26-L49
[ "def", "check_type", "(", "self", ",", "value", ",", "attr", ",", "data", ")", ":", "if", "self", ".", "many", "and", "not", "is_collection", "(", "value", ")", ":", "raise", "self", ".", "_not_expected_type", "(", "value", ",", "Iterable", ",", "fields", "=", "[", "self", "]", ",", "field_names", "=", "attr", ",", "data", "=", "data", ")", "_check_type", "=", "super", "(", ")", ".", "check_type", "errors", "=", "[", "]", "values", "=", "value", "if", "self", ".", "many", "else", "[", "value", "]", "for", "idx", ",", "v", "in", "enumerate", "(", "values", ")", ":", "try", ":", "_check_type", "(", "v", ",", "idx", ",", "values", ")", "except", "ValidationError", "as", "err", ":", "errors", ".", "append", "(", "err", ".", "messages", ")", "if", "errors", ":", "errors", "=", "errors", "if", "self", ".", "many", "else", "errors", "[", "0", "]", "raise", "ValidationError", "(", "errors", ")", "return", "value" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
List.check_type
Validate if it's a list of valid item-field values. Check if each element in the list can be validated by the item-field passed during construction.
qiskit/validation/fields/containers.py
def check_type(self, value, attr, data): """Validate if it's a list of valid item-field values. Check if each element in the list can be validated by the item-field passed during construction. """ super().check_type(value, attr, data) errors = [] for idx, v in enumerate(value): try: self.container.check_type(v, idx, value) except ValidationError as err: errors.append(err.messages) if errors: raise ValidationError(errors) return value
def check_type(self, value, attr, data): """Validate if it's a list of valid item-field values. Check if each element in the list can be validated by the item-field passed during construction. """ super().check_type(value, attr, data) errors = [] for idx, v in enumerate(value): try: self.container.check_type(v, idx, value) except ValidationError as err: errors.append(err.messages) if errors: raise ValidationError(errors) return value
[ "Validate", "if", "it", "s", "a", "list", "of", "valid", "item", "-", "field", "values", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/validation/fields/containers.py#L58-L76
[ "def", "check_type", "(", "self", ",", "value", ",", "attr", ",", "data", ")", ":", "super", "(", ")", ".", "check_type", "(", "value", ",", "attr", ",", "data", ")", "errors", "=", "[", "]", "for", "idx", ",", "v", "in", "enumerate", "(", "value", ")", ":", "try", ":", "self", ".", "container", ".", "check_type", "(", "v", ",", "idx", ",", "value", ")", "except", "ValidationError", "as", "err", ":", "errors", ".", "append", "(", "err", ".", "messages", ")", "if", "errors", ":", "raise", "ValidationError", "(", "errors", ")", "return", "value" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
dag_drawer
Plot the directed acyclic graph (dag) to represent operation dependencies in a quantum circuit. Note this function leverages `pydot <https://github.com/erocarrera/pydot>`_ (via `nxpd <https://github.com/chebee7i/nxpd`_) to generate the graph, which means that having `Graphviz <https://www.graphviz.org/>`_ installed on your system is required for this to work. Args: dag (DAGCircuit): The dag to draw. scale (float): scaling factor filename (str): file path to save image to (format inferred from name) style (str): 'plain': B&W graph 'color' (default): color input/output/op nodes Returns: Ipython.display.Image: if in Jupyter notebook and not saving to file, otherwise None. Raises: VisualizationError: when style is not recognized. ImportError: when nxpd or pydot not installed.
qiskit/visualization/dag_visualization.py
def dag_drawer(dag, scale=0.7, filename=None, style='color'): """Plot the directed acyclic graph (dag) to represent operation dependencies in a quantum circuit. Note this function leverages `pydot <https://github.com/erocarrera/pydot>`_ (via `nxpd <https://github.com/chebee7i/nxpd`_) to generate the graph, which means that having `Graphviz <https://www.graphviz.org/>`_ installed on your system is required for this to work. Args: dag (DAGCircuit): The dag to draw. scale (float): scaling factor filename (str): file path to save image to (format inferred from name) style (str): 'plain': B&W graph 'color' (default): color input/output/op nodes Returns: Ipython.display.Image: if in Jupyter notebook and not saving to file, otherwise None. Raises: VisualizationError: when style is not recognized. ImportError: when nxpd or pydot not installed. """ try: import nxpd import pydot # pylint: disable=unused-import except ImportError: raise ImportError("dag_drawer requires nxpd, pydot, and Graphviz. " "Run 'pip install nxpd pydot', and install graphviz") G = dag.to_networkx() G.graph['dpi'] = 100 * scale if style == 'plain': pass elif style == 'color': for node in G.nodes: n = G.nodes[node] n['label'] = node.name if node.type == 'op': n['color'] = 'blue' n['style'] = 'filled' n['fillcolor'] = 'lightblue' if node.type == 'in': n['color'] = 'black' n['style'] = 'filled' n['fillcolor'] = 'green' if node.type == 'out': n['color'] = 'black' n['style'] = 'filled' n['fillcolor'] = 'red' for e in G.edges(data=True): e[2]['label'] = e[2]['name'] else: raise VisualizationError("Unrecognized style for the dag_drawer.") if filename: show = False elif ('ipykernel' in sys.modules) and ('spyder' not in sys.modules): show = 'ipynb' else: show = True return nxpd.draw(G, filename=filename, show=show)
def dag_drawer(dag, scale=0.7, filename=None, style='color'): """Plot the directed acyclic graph (dag) to represent operation dependencies in a quantum circuit. Note this function leverages `pydot <https://github.com/erocarrera/pydot>`_ (via `nxpd <https://github.com/chebee7i/nxpd`_) to generate the graph, which means that having `Graphviz <https://www.graphviz.org/>`_ installed on your system is required for this to work. Args: dag (DAGCircuit): The dag to draw. scale (float): scaling factor filename (str): file path to save image to (format inferred from name) style (str): 'plain': B&W graph 'color' (default): color input/output/op nodes Returns: Ipython.display.Image: if in Jupyter notebook and not saving to file, otherwise None. Raises: VisualizationError: when style is not recognized. ImportError: when nxpd or pydot not installed. """ try: import nxpd import pydot # pylint: disable=unused-import except ImportError: raise ImportError("dag_drawer requires nxpd, pydot, and Graphviz. " "Run 'pip install nxpd pydot', and install graphviz") G = dag.to_networkx() G.graph['dpi'] = 100 * scale if style == 'plain': pass elif style == 'color': for node in G.nodes: n = G.nodes[node] n['label'] = node.name if node.type == 'op': n['color'] = 'blue' n['style'] = 'filled' n['fillcolor'] = 'lightblue' if node.type == 'in': n['color'] = 'black' n['style'] = 'filled' n['fillcolor'] = 'green' if node.type == 'out': n['color'] = 'black' n['style'] = 'filled' n['fillcolor'] = 'red' for e in G.edges(data=True): e[2]['label'] = e[2]['name'] else: raise VisualizationError("Unrecognized style for the dag_drawer.") if filename: show = False elif ('ipykernel' in sys.modules) and ('spyder' not in sys.modules): show = 'ipynb' else: show = True return nxpd.draw(G, filename=filename, show=show)
[ "Plot", "the", "directed", "acyclic", "graph", "(", "dag", ")", "to", "represent", "operation", "dependencies", "in", "a", "quantum", "circuit", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/dag_visualization.py#L18-L83
[ "def", "dag_drawer", "(", "dag", ",", "scale", "=", "0.7", ",", "filename", "=", "None", ",", "style", "=", "'color'", ")", ":", "try", ":", "import", "nxpd", "import", "pydot", "# pylint: disable=unused-import", "except", "ImportError", ":", "raise", "ImportError", "(", "\"dag_drawer requires nxpd, pydot, and Graphviz. \"", "\"Run 'pip install nxpd pydot', and install graphviz\"", ")", "G", "=", "dag", ".", "to_networkx", "(", ")", "G", ".", "graph", "[", "'dpi'", "]", "=", "100", "*", "scale", "if", "style", "==", "'plain'", ":", "pass", "elif", "style", "==", "'color'", ":", "for", "node", "in", "G", ".", "nodes", ":", "n", "=", "G", ".", "nodes", "[", "node", "]", "n", "[", "'label'", "]", "=", "node", ".", "name", "if", "node", ".", "type", "==", "'op'", ":", "n", "[", "'color'", "]", "=", "'blue'", "n", "[", "'style'", "]", "=", "'filled'", "n", "[", "'fillcolor'", "]", "=", "'lightblue'", "if", "node", ".", "type", "==", "'in'", ":", "n", "[", "'color'", "]", "=", "'black'", "n", "[", "'style'", "]", "=", "'filled'", "n", "[", "'fillcolor'", "]", "=", "'green'", "if", "node", ".", "type", "==", "'out'", ":", "n", "[", "'color'", "]", "=", "'black'", "n", "[", "'style'", "]", "=", "'filled'", "n", "[", "'fillcolor'", "]", "=", "'red'", "for", "e", "in", "G", ".", "edges", "(", "data", "=", "True", ")", ":", "e", "[", "2", "]", "[", "'label'", "]", "=", "e", "[", "2", "]", "[", "'name'", "]", "else", ":", "raise", "VisualizationError", "(", "\"Unrecognized style for the dag_drawer.\"", ")", "if", "filename", ":", "show", "=", "False", "elif", "(", "'ipykernel'", "in", "sys", ".", "modules", ")", "and", "(", "'spyder'", "not", "in", "sys", ".", "modules", ")", ":", "show", "=", "'ipynb'", "else", ":", "show", "=", "True", "return", "nxpd", ".", "draw", "(", "G", ",", "filename", "=", "filename", ",", "show", "=", "show", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BaseOperator._atol
Set the absolute tolerence parameter for float comparisons.
qiskit/quantum_info/operators/base_operator.py
def _atol(self, atol): """Set the absolute tolerence parameter for float comparisons.""" # NOTE: that this overrides the class value so applies to all # instances of the class. max_tol = self.__class__.MAX_TOL if atol < 0: raise QiskitError("Invalid atol: must be non-negative.") if atol > max_tol: raise QiskitError( "Invalid atol: must be less than {}.".format(max_tol)) self.__class__.ATOL = atol
def _atol(self, atol): """Set the absolute tolerence parameter for float comparisons.""" # NOTE: that this overrides the class value so applies to all # instances of the class. max_tol = self.__class__.MAX_TOL if atol < 0: raise QiskitError("Invalid atol: must be non-negative.") if atol > max_tol: raise QiskitError( "Invalid atol: must be less than {}.".format(max_tol)) self.__class__.ATOL = atol
[ "Set", "the", "absolute", "tolerence", "parameter", "for", "float", "comparisons", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/base_operator.py#L75-L85
[ "def", "_atol", "(", "self", ",", "atol", ")", ":", "# NOTE: that this overrides the class value so applies to all", "# instances of the class.", "max_tol", "=", "self", ".", "__class__", ".", "MAX_TOL", "if", "atol", "<", "0", ":", "raise", "QiskitError", "(", "\"Invalid atol: must be non-negative.\"", ")", "if", "atol", ">", "max_tol", ":", "raise", "QiskitError", "(", "\"Invalid atol: must be less than {}.\"", ".", "format", "(", "max_tol", ")", ")", "self", ".", "__class__", ".", "ATOL", "=", "atol" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BaseOperator._rtol
Set the relative tolerence parameter for float comparisons.
qiskit/quantum_info/operators/base_operator.py
def _rtol(self, rtol): """Set the relative tolerence parameter for float comparisons.""" # NOTE: that this overrides the class value so applies to all # instances of the class. max_tol = self.__class__.MAX_TOL if rtol < 0: raise QiskitError("Invalid rtol: must be non-negative.") if rtol > max_tol: raise QiskitError( "Invalid rtol: must be less than {}.".format(max_tol)) self.__class__.RTOL = rtol
def _rtol(self, rtol): """Set the relative tolerence parameter for float comparisons.""" # NOTE: that this overrides the class value so applies to all # instances of the class. max_tol = self.__class__.MAX_TOL if rtol < 0: raise QiskitError("Invalid rtol: must be non-negative.") if rtol > max_tol: raise QiskitError( "Invalid rtol: must be less than {}.".format(max_tol)) self.__class__.RTOL = rtol
[ "Set", "the", "relative", "tolerence", "parameter", "for", "float", "comparisons", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/base_operator.py#L93-L103
[ "def", "_rtol", "(", "self", ",", "rtol", ")", ":", "# NOTE: that this overrides the class value so applies to all", "# instances of the class.", "max_tol", "=", "self", ".", "__class__", ".", "MAX_TOL", "if", "rtol", "<", "0", ":", "raise", "QiskitError", "(", "\"Invalid rtol: must be non-negative.\"", ")", "if", "rtol", ">", "max_tol", ":", "raise", "QiskitError", "(", "\"Invalid rtol: must be less than {}.\"", ".", "format", "(", "max_tol", ")", ")", "self", ".", "__class__", ".", "RTOL", "=", "rtol" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BaseOperator._reshape
Reshape input and output dimensions of operator. Arg: input_dims (tuple): new subsystem input dimensions. output_dims (tuple): new subsystem output dimensions. Returns: Operator: returns self with reshaped input and output dimensions. Raises: QiskitError: if combined size of all subsystem input dimension or subsystem output dimensions is not constant.
qiskit/quantum_info/operators/base_operator.py
def _reshape(self, input_dims=None, output_dims=None): """Reshape input and output dimensions of operator. Arg: input_dims (tuple): new subsystem input dimensions. output_dims (tuple): new subsystem output dimensions. Returns: Operator: returns self with reshaped input and output dimensions. Raises: QiskitError: if combined size of all subsystem input dimension or subsystem output dimensions is not constant. """ if input_dims is not None: if np.product(input_dims) != self._input_dim: raise QiskitError( "Reshaped input_dims are incompatible with combined input dimension." ) self._input_dims = tuple(input_dims) if output_dims is not None: if np.product(output_dims) != self._output_dim: raise QiskitError( "Reshaped input_dims are incompatible with combined input dimension." ) self._output_dims = tuple(output_dims) return self
def _reshape(self, input_dims=None, output_dims=None): """Reshape input and output dimensions of operator. Arg: input_dims (tuple): new subsystem input dimensions. output_dims (tuple): new subsystem output dimensions. Returns: Operator: returns self with reshaped input and output dimensions. Raises: QiskitError: if combined size of all subsystem input dimension or subsystem output dimensions is not constant. """ if input_dims is not None: if np.product(input_dims) != self._input_dim: raise QiskitError( "Reshaped input_dims are incompatible with combined input dimension." ) self._input_dims = tuple(input_dims) if output_dims is not None: if np.product(output_dims) != self._output_dim: raise QiskitError( "Reshaped input_dims are incompatible with combined input dimension." ) self._output_dims = tuple(output_dims) return self
[ "Reshape", "input", "and", "output", "dimensions", "of", "operator", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/base_operator.py#L105-L131
[ "def", "_reshape", "(", "self", ",", "input_dims", "=", "None", ",", "output_dims", "=", "None", ")", ":", "if", "input_dims", "is", "not", "None", ":", "if", "np", ".", "product", "(", "input_dims", ")", "!=", "self", ".", "_input_dim", ":", "raise", "QiskitError", "(", "\"Reshaped input_dims are incompatible with combined input dimension.\"", ")", "self", ".", "_input_dims", "=", "tuple", "(", "input_dims", ")", "if", "output_dims", "is", "not", "None", ":", "if", "np", ".", "product", "(", "output_dims", ")", "!=", "self", ".", "_output_dim", ":", "raise", "QiskitError", "(", "\"Reshaped input_dims are incompatible with combined input dimension.\"", ")", "self", ".", "_output_dims", "=", "tuple", "(", "output_dims", ")", "return", "self" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BaseOperator.input_dims
Return tuple of input dimension for specified subsystems.
qiskit/quantum_info/operators/base_operator.py
def input_dims(self, qargs=None): """Return tuple of input dimension for specified subsystems.""" if qargs is None: return self._input_dims return tuple(self._input_dims[i] for i in qargs)
def input_dims(self, qargs=None): """Return tuple of input dimension for specified subsystems.""" if qargs is None: return self._input_dims return tuple(self._input_dims[i] for i in qargs)
[ "Return", "tuple", "of", "input", "dimension", "for", "specified", "subsystems", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/base_operator.py#L133-L137
[ "def", "input_dims", "(", "self", ",", "qargs", "=", "None", ")", ":", "if", "qargs", "is", "None", ":", "return", "self", ".", "_input_dims", "return", "tuple", "(", "self", ".", "_input_dims", "[", "i", "]", "for", "i", "in", "qargs", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BaseOperator.output_dims
Return tuple of output dimension for specified subsystems.
qiskit/quantum_info/operators/base_operator.py
def output_dims(self, qargs=None): """Return tuple of output dimension for specified subsystems.""" if qargs is None: return self._output_dims return tuple(self._output_dims[i] for i in qargs)
def output_dims(self, qargs=None): """Return tuple of output dimension for specified subsystems.""" if qargs is None: return self._output_dims return tuple(self._output_dims[i] for i in qargs)
[ "Return", "tuple", "of", "output", "dimension", "for", "specified", "subsystems", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/base_operator.py#L139-L143
[ "def", "output_dims", "(", "self", ",", "qargs", "=", "None", ")", ":", "if", "qargs", "is", "None", ":", "return", "self", ".", "_output_dims", "return", "tuple", "(", "self", ".", "_output_dims", "[", "i", "]", "for", "i", "in", "qargs", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BaseOperator.copy
Make a copy of current operator.
qiskit/quantum_info/operators/base_operator.py
def copy(self): """Make a copy of current operator.""" # pylint: disable=no-value-for-parameter # The constructor of subclasses from raw data should be a copy return self.__class__(self.data, self.input_dims(), self.output_dims())
def copy(self): """Make a copy of current operator.""" # pylint: disable=no-value-for-parameter # The constructor of subclasses from raw data should be a copy return self.__class__(self.data, self.input_dims(), self.output_dims())
[ "Make", "a", "copy", "of", "current", "operator", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/base_operator.py#L145-L149
[ "def", "copy", "(", "self", ")", ":", "# pylint: disable=no-value-for-parameter", "# The constructor of subclasses from raw data should be a copy", "return", "self", ".", "__class__", "(", "self", ".", "data", ",", "self", ".", "input_dims", "(", ")", ",", "self", ".", "output_dims", "(", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BaseOperator.power
Return the compose of a operator with itself n times. Args: n (int): the number of times to compose with self (n>0). Returns: BaseOperator: the n-times composed operator. Raises: QiskitError: if the input and output dimensions of the operator are not equal, or the power is not a positive integer.
qiskit/quantum_info/operators/base_operator.py
def power(self, n): """Return the compose of a operator with itself n times. Args: n (int): the number of times to compose with self (n>0). Returns: BaseOperator: the n-times composed operator. Raises: QiskitError: if the input and output dimensions of the operator are not equal, or the power is not a positive integer. """ # NOTE: if a subclass can have negative or non-integer powers # this method should be overriden in that class. if not isinstance(n, (int, np.integer)) or n < 1: raise QiskitError("Can only power with positive integer powers.") if self._input_dim != self._output_dim: raise QiskitError("Can only power with input_dim = output_dim.") ret = self.copy() for _ in range(1, n): ret = ret.compose(self) return ret
def power(self, n): """Return the compose of a operator with itself n times. Args: n (int): the number of times to compose with self (n>0). Returns: BaseOperator: the n-times composed operator. Raises: QiskitError: if the input and output dimensions of the operator are not equal, or the power is not a positive integer. """ # NOTE: if a subclass can have negative or non-integer powers # this method should be overriden in that class. if not isinstance(n, (int, np.integer)) or n < 1: raise QiskitError("Can only power with positive integer powers.") if self._input_dim != self._output_dim: raise QiskitError("Can only power with input_dim = output_dim.") ret = self.copy() for _ in range(1, n): ret = ret.compose(self) return ret
[ "Return", "the", "compose", "of", "a", "operator", "with", "itself", "n", "times", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/base_operator.py#L195-L217
[ "def", "power", "(", "self", ",", "n", ")", ":", "# NOTE: if a subclass can have negative or non-integer powers", "# this method should be overriden in that class.", "if", "not", "isinstance", "(", "n", ",", "(", "int", ",", "np", ".", "integer", ")", ")", "or", "n", "<", "1", ":", "raise", "QiskitError", "(", "\"Can only power with positive integer powers.\"", ")", "if", "self", ".", "_input_dim", "!=", "self", ".", "_output_dim", ":", "raise", "QiskitError", "(", "\"Can only power with input_dim = output_dim.\"", ")", "ret", "=", "self", ".", "copy", "(", ")", "for", "_", "in", "range", "(", "1", ",", "n", ")", ":", "ret", "=", "ret", ".", "compose", "(", "self", ")", "return", "ret" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BaseOperator._automatic_dims
Check if input dimension corresponds to qubit subsystems.
qiskit/quantum_info/operators/base_operator.py
def _automatic_dims(cls, dims, size): """Check if input dimension corresponds to qubit subsystems.""" if dims is None: dims = size elif np.product(dims) != size: raise QiskitError("dimensions do not match size.") if isinstance(dims, (int, np.integer)): num_qubits = int(np.log2(dims)) if 2 ** num_qubits == size: return num_qubits * (2,) return (dims,) return tuple(dims)
def _automatic_dims(cls, dims, size): """Check if input dimension corresponds to qubit subsystems.""" if dims is None: dims = size elif np.product(dims) != size: raise QiskitError("dimensions do not match size.") if isinstance(dims, (int, np.integer)): num_qubits = int(np.log2(dims)) if 2 ** num_qubits == size: return num_qubits * (2,) return (dims,) return tuple(dims)
[ "Check", "if", "input", "dimension", "corresponds", "to", "qubit", "subsystems", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/base_operator.py#L315-L326
[ "def", "_automatic_dims", "(", "cls", ",", "dims", ",", "size", ")", ":", "if", "dims", "is", "None", ":", "dims", "=", "size", "elif", "np", ".", "product", "(", "dims", ")", "!=", "size", ":", "raise", "QiskitError", "(", "\"dimensions do not match size.\"", ")", "if", "isinstance", "(", "dims", ",", "(", "int", ",", "np", ".", "integer", ")", ")", ":", "num_qubits", "=", "int", "(", "np", ".", "log2", "(", "dims", ")", ")", "if", "2", "**", "num_qubits", "==", "size", ":", "return", "num_qubits", "*", "(", "2", ",", ")", "return", "(", "dims", ",", ")", "return", "tuple", "(", "dims", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BaseOperator._einsum_matmul
Perform a contraction using Numpy.einsum Args: tensor (np.array): a vector or matrix reshaped to a rank-N tensor. mat (np.array): a matrix reshaped to a rank-2M tensor. indices (list): tensor indices to contract with mat. shift (int): shift for indicies of tensor to contract [Default: 0]. right_mul (bool): if True right multiply tensor by mat (else left multiply) [Default: False]. Returns: Numpy.ndarray: the matrix multiplied rank-N tensor. Raises: QiskitError: if mat is not an even rank tensor.
qiskit/quantum_info/operators/base_operator.py
def _einsum_matmul(cls, tensor, mat, indices, shift=0, right_mul=False): """Perform a contraction using Numpy.einsum Args: tensor (np.array): a vector or matrix reshaped to a rank-N tensor. mat (np.array): a matrix reshaped to a rank-2M tensor. indices (list): tensor indices to contract with mat. shift (int): shift for indicies of tensor to contract [Default: 0]. right_mul (bool): if True right multiply tensor by mat (else left multiply) [Default: False]. Returns: Numpy.ndarray: the matrix multiplied rank-N tensor. Raises: QiskitError: if mat is not an even rank tensor. """ rank = tensor.ndim rank_mat = mat.ndim if rank_mat % 2 != 0: raise QiskitError( "Contracted matrix must have an even number of indices.") # Get einsum indices for tensor indices_tensor = list(range(rank)) for j, index in enumerate(indices): indices_tensor[index + shift] = rank + j # Get einsum indces for mat mat_contract = list(reversed(range(rank, rank + len(indices)))) mat_free = [index + shift for index in reversed(indices)] if right_mul: indices_mat = mat_contract + mat_free else: indices_mat = mat_free + mat_contract return np.einsum(tensor, indices_tensor, mat, indices_mat)
def _einsum_matmul(cls, tensor, mat, indices, shift=0, right_mul=False): """Perform a contraction using Numpy.einsum Args: tensor (np.array): a vector or matrix reshaped to a rank-N tensor. mat (np.array): a matrix reshaped to a rank-2M tensor. indices (list): tensor indices to contract with mat. shift (int): shift for indicies of tensor to contract [Default: 0]. right_mul (bool): if True right multiply tensor by mat (else left multiply) [Default: False]. Returns: Numpy.ndarray: the matrix multiplied rank-N tensor. Raises: QiskitError: if mat is not an even rank tensor. """ rank = tensor.ndim rank_mat = mat.ndim if rank_mat % 2 != 0: raise QiskitError( "Contracted matrix must have an even number of indices.") # Get einsum indices for tensor indices_tensor = list(range(rank)) for j, index in enumerate(indices): indices_tensor[index + shift] = rank + j # Get einsum indces for mat mat_contract = list(reversed(range(rank, rank + len(indices)))) mat_free = [index + shift for index in reversed(indices)] if right_mul: indices_mat = mat_contract + mat_free else: indices_mat = mat_free + mat_contract return np.einsum(tensor, indices_tensor, mat, indices_mat)
[ "Perform", "a", "contraction", "using", "Numpy", ".", "einsum" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/base_operator.py#L329-L362
[ "def", "_einsum_matmul", "(", "cls", ",", "tensor", ",", "mat", ",", "indices", ",", "shift", "=", "0", ",", "right_mul", "=", "False", ")", ":", "rank", "=", "tensor", ".", "ndim", "rank_mat", "=", "mat", ".", "ndim", "if", "rank_mat", "%", "2", "!=", "0", ":", "raise", "QiskitError", "(", "\"Contracted matrix must have an even number of indices.\"", ")", "# Get einsum indices for tensor", "indices_tensor", "=", "list", "(", "range", "(", "rank", ")", ")", "for", "j", ",", "index", "in", "enumerate", "(", "indices", ")", ":", "indices_tensor", "[", "index", "+", "shift", "]", "=", "rank", "+", "j", "# Get einsum indces for mat", "mat_contract", "=", "list", "(", "reversed", "(", "range", "(", "rank", ",", "rank", "+", "len", "(", "indices", ")", ")", ")", ")", "mat_free", "=", "[", "index", "+", "shift", "for", "index", "in", "reversed", "(", "indices", ")", "]", "if", "right_mul", ":", "indices_mat", "=", "mat_contract", "+", "mat_free", "else", ":", "indices_mat", "=", "mat_free", "+", "mat_contract", "return", "np", ".", "einsum", "(", "tensor", ",", "indices_tensor", ",", "mat", ",", "indices_mat", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BasePolyField._deserialize
Override ``_deserialize`` for customizing the exception raised.
qiskit/validation/fields/polymorphic.py
def _deserialize(self, value, attr, data): """Override ``_deserialize`` for customizing the exception raised.""" try: return super()._deserialize(value, attr, data) except ValidationError as ex: if 'deserialization_schema_selector' in ex.messages[0]: ex.messages[0] = 'Cannot find a valid schema among the choices' raise
def _deserialize(self, value, attr, data): """Override ``_deserialize`` for customizing the exception raised.""" try: return super()._deserialize(value, attr, data) except ValidationError as ex: if 'deserialization_schema_selector' in ex.messages[0]: ex.messages[0] = 'Cannot find a valid schema among the choices' raise
[ "Override", "_deserialize", "for", "customizing", "the", "exception", "raised", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/validation/fields/polymorphic.py#L61-L68
[ "def", "_deserialize", "(", "self", ",", "value", ",", "attr", ",", "data", ")", ":", "try", ":", "return", "super", "(", ")", ".", "_deserialize", "(", "value", ",", "attr", ",", "data", ")", "except", "ValidationError", "as", "ex", ":", "if", "'deserialization_schema_selector'", "in", "ex", ".", "messages", "[", "0", "]", ":", "ex", ".", "messages", "[", "0", "]", "=", "'Cannot find a valid schema among the choices'", "raise" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
BasePolyField._serialize
Override ``_serialize`` for customizing the exception raised.
qiskit/validation/fields/polymorphic.py
def _serialize(self, value, key, obj): """Override ``_serialize`` for customizing the exception raised.""" try: return super()._serialize(value, key, obj) except TypeError as ex: if 'serialization_schema_selector' in str(ex): raise ValidationError('Data from an invalid schema') raise
def _serialize(self, value, key, obj): """Override ``_serialize`` for customizing the exception raised.""" try: return super()._serialize(value, key, obj) except TypeError as ex: if 'serialization_schema_selector' in str(ex): raise ValidationError('Data from an invalid schema') raise
[ "Override", "_serialize", "for", "customizing", "the", "exception", "raised", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/validation/fields/polymorphic.py#L70-L77
[ "def", "_serialize", "(", "self", ",", "value", ",", "key", ",", "obj", ")", ":", "try", ":", "return", "super", "(", ")", ".", "_serialize", "(", "value", ",", "key", ",", "obj", ")", "except", "TypeError", "as", "ex", ":", "if", "'serialization_schema_selector'", "in", "str", "(", "ex", ")", ":", "raise", "ValidationError", "(", "'Data from an invalid schema'", ")", "raise" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
ByType.check_type
Check if at least one of the possible choices validates the value. Possible choices are assumed to be ``ModelTypeValidator`` fields.
qiskit/validation/fields/polymorphic.py
def check_type(self, value, attr, data): """Check if at least one of the possible choices validates the value. Possible choices are assumed to be ``ModelTypeValidator`` fields. """ for field in self.choices: if isinstance(field, ModelTypeValidator): try: return field.check_type(value, attr, data) except ValidationError: pass raise self._not_expected_type( value, [field.__class__ for field in self.choices], fields=[self], field_names=attr, data=data)
def check_type(self, value, attr, data): """Check if at least one of the possible choices validates the value. Possible choices are assumed to be ``ModelTypeValidator`` fields. """ for field in self.choices: if isinstance(field, ModelTypeValidator): try: return field.check_type(value, attr, data) except ValidationError: pass raise self._not_expected_type( value, [field.__class__ for field in self.choices], fields=[self], field_names=attr, data=data)
[ "Check", "if", "at", "least", "one", "of", "the", "possible", "choices", "validates", "the", "value", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/validation/fields/polymorphic.py#L229-L243
[ "def", "check_type", "(", "self", ",", "value", ",", "attr", ",", "data", ")", ":", "for", "field", "in", "self", ".", "choices", ":", "if", "isinstance", "(", "field", ",", "ModelTypeValidator", ")", ":", "try", ":", "return", "field", ".", "check_type", "(", "value", ",", "attr", ",", "data", ")", "except", "ValidationError", ":", "pass", "raise", "self", ".", "_not_expected_type", "(", "value", ",", "[", "field", ".", "__class__", "for", "field", "in", "self", ".", "choices", "]", ",", "fields", "=", "[", "self", "]", ",", "field_names", "=", "attr", ",", "data", "=", "data", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
state_fidelity
Return the state fidelity between two quantum states. Either input may be a state vector, or a density matrix. The state fidelity (F) for two density matrices is defined as:: F(rho1, rho2) = Tr[sqrt(sqrt(rho1).rho2.sqrt(rho1))] ^ 2 For a pure state and mixed state the fidelity is given by:: F(|psi1>, rho2) = <psi1|rho2|psi1> For two pure states the fidelity is given by:: F(|psi1>, |psi2>) = |<psi1|psi2>|^2 Args: state1 (array_like): a quantum state vector or density matrix. state2 (array_like): a quantum state vector or density matrix. Returns: array_like: The state fidelity F(state1, state2).
qiskit/quantum_info/states/measures.py
def state_fidelity(state1, state2): """Return the state fidelity between two quantum states. Either input may be a state vector, or a density matrix. The state fidelity (F) for two density matrices is defined as:: F(rho1, rho2) = Tr[sqrt(sqrt(rho1).rho2.sqrt(rho1))] ^ 2 For a pure state and mixed state the fidelity is given by:: F(|psi1>, rho2) = <psi1|rho2|psi1> For two pure states the fidelity is given by:: F(|psi1>, |psi2>) = |<psi1|psi2>|^2 Args: state1 (array_like): a quantum state vector or density matrix. state2 (array_like): a quantum state vector or density matrix. Returns: array_like: The state fidelity F(state1, state2). """ # convert input to numpy arrays s1 = np.array(state1) s2 = np.array(state2) # fidelity of two state vectors if s1.ndim == 1 and s2.ndim == 1: return np.abs(s2.conj().dot(s1)) ** 2 # fidelity of vector and density matrix elif s1.ndim == 1: # psi = s1, rho = s2 return np.abs(s1.conj().dot(s2).dot(s1)) elif s2.ndim == 1: # psi = s2, rho = s1 return np.abs(s2.conj().dot(s1).dot(s2)) # fidelity of two density matrices s1sq = _funm_svd(s1, np.sqrt) s2sq = _funm_svd(s2, np.sqrt) return np.linalg.norm(s1sq.dot(s2sq), ord='nuc') ** 2
def state_fidelity(state1, state2): """Return the state fidelity between two quantum states. Either input may be a state vector, or a density matrix. The state fidelity (F) for two density matrices is defined as:: F(rho1, rho2) = Tr[sqrt(sqrt(rho1).rho2.sqrt(rho1))] ^ 2 For a pure state and mixed state the fidelity is given by:: F(|psi1>, rho2) = <psi1|rho2|psi1> For two pure states the fidelity is given by:: F(|psi1>, |psi2>) = |<psi1|psi2>|^2 Args: state1 (array_like): a quantum state vector or density matrix. state2 (array_like): a quantum state vector or density matrix. Returns: array_like: The state fidelity F(state1, state2). """ # convert input to numpy arrays s1 = np.array(state1) s2 = np.array(state2) # fidelity of two state vectors if s1.ndim == 1 and s2.ndim == 1: return np.abs(s2.conj().dot(s1)) ** 2 # fidelity of vector and density matrix elif s1.ndim == 1: # psi = s1, rho = s2 return np.abs(s1.conj().dot(s2).dot(s1)) elif s2.ndim == 1: # psi = s2, rho = s1 return np.abs(s2.conj().dot(s1).dot(s2)) # fidelity of two density matrices s1sq = _funm_svd(s1, np.sqrt) s2sq = _funm_svd(s2, np.sqrt) return np.linalg.norm(s1sq.dot(s2sq), ord='nuc') ** 2
[ "Return", "the", "state", "fidelity", "between", "two", "quantum", "states", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/states/measures.py#L20-L60
[ "def", "state_fidelity", "(", "state1", ",", "state2", ")", ":", "# convert input to numpy arrays", "s1", "=", "np", ".", "array", "(", "state1", ")", "s2", "=", "np", ".", "array", "(", "state2", ")", "# fidelity of two state vectors", "if", "s1", ".", "ndim", "==", "1", "and", "s2", ".", "ndim", "==", "1", ":", "return", "np", ".", "abs", "(", "s2", ".", "conj", "(", ")", ".", "dot", "(", "s1", ")", ")", "**", "2", "# fidelity of vector and density matrix", "elif", "s1", ".", "ndim", "==", "1", ":", "# psi = s1, rho = s2", "return", "np", ".", "abs", "(", "s1", ".", "conj", "(", ")", ".", "dot", "(", "s2", ")", ".", "dot", "(", "s1", ")", ")", "elif", "s2", ".", "ndim", "==", "1", ":", "# psi = s2, rho = s1", "return", "np", ".", "abs", "(", "s2", ".", "conj", "(", ")", ".", "dot", "(", "s1", ")", ".", "dot", "(", "s2", ")", ")", "# fidelity of two density matrices", "s1sq", "=", "_funm_svd", "(", "s1", ",", "np", ".", "sqrt", ")", "s2sq", "=", "_funm_svd", "(", "s2", ",", "np", ".", "sqrt", ")", "return", "np", ".", "linalg", ".", "norm", "(", "s1sq", ".", "dot", "(", "s2sq", ")", ",", "ord", "=", "'nuc'", ")", "**", "2" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
_funm_svd
Apply real scalar function to singular values of a matrix. Args: a (array_like): (N, N) Matrix at which to evaluate the function. func (callable): Callable object that evaluates a scalar function f. Returns: ndarray: funm (N, N) Value of the matrix function specified by func evaluated at `A`.
qiskit/quantum_info/states/measures.py
def _funm_svd(a, func): """Apply real scalar function to singular values of a matrix. Args: a (array_like): (N, N) Matrix at which to evaluate the function. func (callable): Callable object that evaluates a scalar function f. Returns: ndarray: funm (N, N) Value of the matrix function specified by func evaluated at `A`. """ U, s, Vh = la.svd(a, lapack_driver='gesvd') S = np.diag(func(s)) return U.dot(S).dot(Vh)
def _funm_svd(a, func): """Apply real scalar function to singular values of a matrix. Args: a (array_like): (N, N) Matrix at which to evaluate the function. func (callable): Callable object that evaluates a scalar function f. Returns: ndarray: funm (N, N) Value of the matrix function specified by func evaluated at `A`. """ U, s, Vh = la.svd(a, lapack_driver='gesvd') S = np.diag(func(s)) return U.dot(S).dot(Vh)
[ "Apply", "real", "scalar", "function", "to", "singular", "values", "of", "a", "matrix", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/states/measures.py#L63-L76
[ "def", "_funm_svd", "(", "a", ",", "func", ")", ":", "U", ",", "s", ",", "Vh", "=", "la", ".", "svd", "(", "a", ",", "lapack_driver", "=", "'gesvd'", ")", "S", "=", "np", ".", "diag", "(", "func", "(", "s", ")", ")", "return", "U", ".", "dot", "(", "S", ")", ".", "dot", "(", "Vh", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
CheckMap.run
If `dag` is mapped to `coupling_map`, the property `is_swap_mapped` is set to True (or to False otherwise). Args: dag (DAGCircuit): DAG to map.
qiskit/transpiler/passes/mapping/check_map.py
def run(self, dag): """ If `dag` is mapped to `coupling_map`, the property `is_swap_mapped` is set to True (or to False otherwise). Args: dag (DAGCircuit): DAG to map. """ if self.layout is None: if self.property_set["layout"]: self.layout = self.property_set["layout"] else: self.layout = Layout.generate_trivial_layout(*dag.qregs.values()) self.property_set['is_swap_mapped'] = True for gate in dag.twoQ_gates(): physical_q0 = self.layout[gate.qargs[0]] physical_q1 = self.layout[gate.qargs[1]] if self.coupling_map.distance(physical_q0, physical_q1) != 1: self.property_set['is_swap_mapped'] = False return
def run(self, dag): """ If `dag` is mapped to `coupling_map`, the property `is_swap_mapped` is set to True (or to False otherwise). Args: dag (DAGCircuit): DAG to map. """ if self.layout is None: if self.property_set["layout"]: self.layout = self.property_set["layout"] else: self.layout = Layout.generate_trivial_layout(*dag.qregs.values()) self.property_set['is_swap_mapped'] = True for gate in dag.twoQ_gates(): physical_q0 = self.layout[gate.qargs[0]] physical_q1 = self.layout[gate.qargs[1]] if self.coupling_map.distance(physical_q0, physical_q1) != 1: self.property_set['is_swap_mapped'] = False return
[ "If", "dag", "is", "mapped", "to", "coupling_map", "the", "property", "is_swap_mapped", "is", "set", "to", "True", "(", "or", "to", "False", "otherwise", ")", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/check_map.py#L34-L56
[ "def", "run", "(", "self", ",", "dag", ")", ":", "if", "self", ".", "layout", "is", "None", ":", "if", "self", ".", "property_set", "[", "\"layout\"", "]", ":", "self", ".", "layout", "=", "self", ".", "property_set", "[", "\"layout\"", "]", "else", ":", "self", ".", "layout", "=", "Layout", ".", "generate_trivial_layout", "(", "*", "dag", ".", "qregs", ".", "values", "(", ")", ")", "self", ".", "property_set", "[", "'is_swap_mapped'", "]", "=", "True", "for", "gate", "in", "dag", ".", "twoQ_gates", "(", ")", ":", "physical_q0", "=", "self", ".", "layout", "[", "gate", ".", "qargs", "[", "0", "]", "]", "physical_q1", "=", "self", ".", "layout", "[", "gate", ".", "qargs", "[", "1", "]", "]", "if", "self", ".", "coupling_map", ".", "distance", "(", "physical_q0", ",", "physical_q1", ")", "!=", "1", ":", "self", ".", "property_set", "[", "'is_swap_mapped'", "]", "=", "False", "return" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
snapshot
Take a statevector snapshot of the internal simulator representation. Works on all qubits, and prevents reordering (like barrier). For other types of snapshots use the Snapshot extension directly. Args: label (str): a snapshot label to report the result snapshot_type (str): the type of the snapshot. qubits (list or None): the qubits to apply snapshot to [Default: None]. params (list or None): the parameters for snapshot_type [Default: None]. Returns: QuantumCircuit: with attached command Raises: ExtensionError: malformed command
qiskit/extensions/simulator/snapshot.py
def snapshot(self, label, snapshot_type='statevector', qubits=None, params=None): """Take a statevector snapshot of the internal simulator representation. Works on all qubits, and prevents reordering (like barrier). For other types of snapshots use the Snapshot extension directly. Args: label (str): a snapshot label to report the result snapshot_type (str): the type of the snapshot. qubits (list or None): the qubits to apply snapshot to [Default: None]. params (list or None): the parameters for snapshot_type [Default: None]. Returns: QuantumCircuit: with attached command Raises: ExtensionError: malformed command """ # Convert label to string for backwards compatibility if not isinstance(label, str): warnings.warn( "Snapshot label should be a string, " "implicit conversion is depreciated.", DeprecationWarning) label = str(label) # If no qubits are specified we add all qubits so it acts as a barrier # This is needed for full register snapshots like statevector if isinstance(qubits, QuantumRegister): qubits = qubits[:] if not qubits: tuples = [] if isinstance(self, QuantumCircuit): for register in self.qregs: tuples.append(register) if not tuples: raise ExtensionError('no qubits for snapshot') qubits = [] for tuple_element in tuples: if isinstance(tuple_element, QuantumRegister): for j in range(tuple_element.size): qubits.append((tuple_element, j)) else: qubits.append(tuple_element) return self.append( Snapshot( label, snapshot_type=snapshot_type, num_qubits=len(qubits), params=params), qubits)
def snapshot(self, label, snapshot_type='statevector', qubits=None, params=None): """Take a statevector snapshot of the internal simulator representation. Works on all qubits, and prevents reordering (like barrier). For other types of snapshots use the Snapshot extension directly. Args: label (str): a snapshot label to report the result snapshot_type (str): the type of the snapshot. qubits (list or None): the qubits to apply snapshot to [Default: None]. params (list or None): the parameters for snapshot_type [Default: None]. Returns: QuantumCircuit: with attached command Raises: ExtensionError: malformed command """ # Convert label to string for backwards compatibility if not isinstance(label, str): warnings.warn( "Snapshot label should be a string, " "implicit conversion is depreciated.", DeprecationWarning) label = str(label) # If no qubits are specified we add all qubits so it acts as a barrier # This is needed for full register snapshots like statevector if isinstance(qubits, QuantumRegister): qubits = qubits[:] if not qubits: tuples = [] if isinstance(self, QuantumCircuit): for register in self.qregs: tuples.append(register) if not tuples: raise ExtensionError('no qubits for snapshot') qubits = [] for tuple_element in tuples: if isinstance(tuple_element, QuantumRegister): for j in range(tuple_element.size): qubits.append((tuple_element, j)) else: qubits.append(tuple_element) return self.append( Snapshot( label, snapshot_type=snapshot_type, num_qubits=len(qubits), params=params), qubits)
[ "Take", "a", "statevector", "snapshot", "of", "the", "internal", "simulator", "representation", ".", "Works", "on", "all", "qubits", "and", "prevents", "reordering", "(", "like", "barrier", ")", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/simulator/snapshot.py#L87-L138
[ "def", "snapshot", "(", "self", ",", "label", ",", "snapshot_type", "=", "'statevector'", ",", "qubits", "=", "None", ",", "params", "=", "None", ")", ":", "# Convert label to string for backwards compatibility", "if", "not", "isinstance", "(", "label", ",", "str", ")", ":", "warnings", ".", "warn", "(", "\"Snapshot label should be a string, \"", "\"implicit conversion is depreciated.\"", ",", "DeprecationWarning", ")", "label", "=", "str", "(", "label", ")", "# If no qubits are specified we add all qubits so it acts as a barrier", "# This is needed for full register snapshots like statevector", "if", "isinstance", "(", "qubits", ",", "QuantumRegister", ")", ":", "qubits", "=", "qubits", "[", ":", "]", "if", "not", "qubits", ":", "tuples", "=", "[", "]", "if", "isinstance", "(", "self", ",", "QuantumCircuit", ")", ":", "for", "register", "in", "self", ".", "qregs", ":", "tuples", ".", "append", "(", "register", ")", "if", "not", "tuples", ":", "raise", "ExtensionError", "(", "'no qubits for snapshot'", ")", "qubits", "=", "[", "]", "for", "tuple_element", "in", "tuples", ":", "if", "isinstance", "(", "tuple_element", ",", "QuantumRegister", ")", ":", "for", "j", "in", "range", "(", "tuple_element", ".", "size", ")", ":", "qubits", ".", "append", "(", "(", "tuple_element", ",", "j", ")", ")", "else", ":", "qubits", ".", "append", "(", "tuple_element", ")", "return", "self", ".", "append", "(", "Snapshot", "(", "label", ",", "snapshot_type", "=", "snapshot_type", ",", "num_qubits", "=", "len", "(", "qubits", ")", ",", "params", "=", "params", ")", ",", "qubits", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Snapshot.assemble
Assemble a QasmQobjInstruction
qiskit/extensions/simulator/snapshot.py
def assemble(self): """Assemble a QasmQobjInstruction""" instruction = super().assemble() instruction.label = self._label instruction.snapshot_type = self._snapshot_type return instruction
def assemble(self): """Assemble a QasmQobjInstruction""" instruction = super().assemble() instruction.label = self._label instruction.snapshot_type = self._snapshot_type return instruction
[ "Assemble", "a", "QasmQobjInstruction" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/simulator/snapshot.py#L49-L54
[ "def", "assemble", "(", "self", ")", ":", "instruction", "=", "super", "(", ")", ".", "assemble", "(", ")", "instruction", ".", "label", "=", "self", ".", "_label", "instruction", ".", "snapshot_type", "=", "self", ".", "_snapshot_type", "return", "instruction" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Snapshot.inverse
Special case. Return self.
qiskit/extensions/simulator/snapshot.py
def inverse(self): """Special case. Return self.""" return Snapshot(self.num_qubits, self.num_clbits, self.params[0], self.params[1])
def inverse(self): """Special case. Return self.""" return Snapshot(self.num_qubits, self.num_clbits, self.params[0], self.params[1])
[ "Special", "case", ".", "Return", "self", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/simulator/snapshot.py#L56-L59
[ "def", "inverse", "(", "self", ")", ":", "return", "Snapshot", "(", "self", ".", "num_qubits", ",", "self", ".", "num_clbits", ",", "self", ".", "params", "[", "0", "]", ",", "self", ".", "params", "[", "1", "]", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Snapshot.label
Set snapshot label to name Args: name (str or None): label to assign unitary Raises: TypeError: name is not string or None.
qiskit/extensions/simulator/snapshot.py
def label(self, name): """Set snapshot label to name Args: name (str or None): label to assign unitary Raises: TypeError: name is not string or None. """ if isinstance(name, str): self._label = name else: raise TypeError('label expects a string')
def label(self, name): """Set snapshot label to name Args: name (str or None): label to assign unitary Raises: TypeError: name is not string or None. """ if isinstance(name, str): self._label = name else: raise TypeError('label expects a string')
[ "Set", "snapshot", "label", "to", "name" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/simulator/snapshot.py#L72-L84
[ "def", "label", "(", "self", ",", "name", ")", ":", "if", "isinstance", "(", "name", ",", "str", ")", ":", "self", ".", "_label", "=", "name", "else", ":", "raise", "TypeError", "(", "'label expects a string'", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumChannel.is_cptp
Return True if completely-positive trace-preserving (CPTP).
qiskit/quantum_info/operators/channel/quantum_channel.py
def is_cptp(self, atol=None, rtol=None): """Return True if completely-positive trace-preserving (CPTP).""" choi = _to_choi(self.rep, self._data, *self.dim) return self._is_cp_helper(choi, atol, rtol) and self._is_tp_helper( choi, atol, rtol)
def is_cptp(self, atol=None, rtol=None): """Return True if completely-positive trace-preserving (CPTP).""" choi = _to_choi(self.rep, self._data, *self.dim) return self._is_cp_helper(choi, atol, rtol) and self._is_tp_helper( choi, atol, rtol)
[ "Return", "True", "if", "completely", "-", "positive", "trace", "-", "preserving", "(", "CPTP", ")", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/quantum_channel.py#L28-L32
[ "def", "is_cptp", "(", "self", ",", "atol", "=", "None", ",", "rtol", "=", "None", ")", ":", "choi", "=", "_to_choi", "(", "self", ".", "rep", ",", "self", ".", "_data", ",", "*", "self", ".", "dim", ")", "return", "self", ".", "_is_cp_helper", "(", "choi", ",", "atol", ",", "rtol", ")", "and", "self", ".", "_is_tp_helper", "(", "choi", ",", "atol", ",", "rtol", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumChannel.is_tp
Test if a channel is completely-positive (CP)
qiskit/quantum_info/operators/channel/quantum_channel.py
def is_tp(self, atol=None, rtol=None): """Test if a channel is completely-positive (CP)""" choi = _to_choi(self.rep, self._data, *self.dim) return self._is_tp_helper(choi, atol, rtol)
def is_tp(self, atol=None, rtol=None): """Test if a channel is completely-positive (CP)""" choi = _to_choi(self.rep, self._data, *self.dim) return self._is_tp_helper(choi, atol, rtol)
[ "Test", "if", "a", "channel", "is", "completely", "-", "positive", "(", "CP", ")" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/quantum_channel.py#L34-L37
[ "def", "is_tp", "(", "self", ",", "atol", "=", "None", ",", "rtol", "=", "None", ")", ":", "choi", "=", "_to_choi", "(", "self", ".", "rep", ",", "self", ".", "_data", ",", "*", "self", ".", "dim", ")", "return", "self", ".", "_is_tp_helper", "(", "choi", ",", "atol", ",", "rtol", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumChannel.is_cp
Test if Choi-matrix is completely-positive (CP)
qiskit/quantum_info/operators/channel/quantum_channel.py
def is_cp(self, atol=None, rtol=None): """Test if Choi-matrix is completely-positive (CP)""" choi = _to_choi(self.rep, self._data, *self.dim) return self._is_cp_helper(choi, atol, rtol)
def is_cp(self, atol=None, rtol=None): """Test if Choi-matrix is completely-positive (CP)""" choi = _to_choi(self.rep, self._data, *self.dim) return self._is_cp_helper(choi, atol, rtol)
[ "Test", "if", "Choi", "-", "matrix", "is", "completely", "-", "positive", "(", "CP", ")" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/quantum_channel.py#L39-L42
[ "def", "is_cp", "(", "self", ",", "atol", "=", "None", ",", "rtol", "=", "None", ")", ":", "choi", "=", "_to_choi", "(", "self", ".", "rep", ",", "self", ".", "_data", ",", "*", "self", ".", "dim", ")", "return", "self", ".", "_is_cp_helper", "(", "choi", ",", "atol", ",", "rtol", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumChannel.is_unitary
Return True if QuantumChannel is a unitary channel.
qiskit/quantum_info/operators/channel/quantum_channel.py
def is_unitary(self, atol=None, rtol=None): """Return True if QuantumChannel is a unitary channel.""" try: op = self.to_operator() return op.is_unitary(atol=atol, rtol=rtol) except QiskitError: return False
def is_unitary(self, atol=None, rtol=None): """Return True if QuantumChannel is a unitary channel.""" try: op = self.to_operator() return op.is_unitary(atol=atol, rtol=rtol) except QiskitError: return False
[ "Return", "True", "if", "QuantumChannel", "is", "a", "unitary", "channel", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/quantum_channel.py#L44-L50
[ "def", "is_unitary", "(", "self", ",", "atol", "=", "None", ",", "rtol", "=", "None", ")", ":", "try", ":", "op", "=", "self", ".", "to_operator", "(", ")", "return", "op", ".", "is_unitary", "(", "atol", "=", "atol", ",", "rtol", "=", "rtol", ")", "except", "QiskitError", ":", "return", "False" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumChannel.to_operator
Try to convert channel to a unitary representation Operator.
qiskit/quantum_info/operators/channel/quantum_channel.py
def to_operator(self): """Try to convert channel to a unitary representation Operator.""" mat = _to_operator(self.rep, self._data, *self.dim) return Operator(mat, self.input_dims(), self.output_dims())
def to_operator(self): """Try to convert channel to a unitary representation Operator.""" mat = _to_operator(self.rep, self._data, *self.dim) return Operator(mat, self.input_dims(), self.output_dims())
[ "Try", "to", "convert", "channel", "to", "a", "unitary", "representation", "Operator", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/quantum_channel.py#L52-L55
[ "def", "to_operator", "(", "self", ")", ":", "mat", "=", "_to_operator", "(", "self", ".", "rep", ",", "self", ".", "_data", ",", "*", "self", ".", "dim", ")", "return", "Operator", "(", "mat", ",", "self", ".", "input_dims", "(", ")", ",", "self", ".", "output_dims", "(", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumChannel.to_instruction
Convert to a Kraus or UnitaryGate circuit instruction. If the channel is unitary it will be added as a unitary gate, otherwise it will be added as a kraus simulator instruction. Returns: Instruction: A kraus instruction for the channel. Raises: QiskitError: if input data is not an N-qubit CPTP quantum channel.
qiskit/quantum_info/operators/channel/quantum_channel.py
def to_instruction(self): """Convert to a Kraus or UnitaryGate circuit instruction. If the channel is unitary it will be added as a unitary gate, otherwise it will be added as a kraus simulator instruction. Returns: Instruction: A kraus instruction for the channel. Raises: QiskitError: if input data is not an N-qubit CPTP quantum channel. """ from qiskit.circuit.instruction import Instruction # Check if input is an N-qubit CPTP channel. n_qubits = int(np.log2(self._input_dim)) if self._input_dim != self._output_dim or 2**n_qubits != self._input_dim: raise QiskitError( 'Cannot convert QuantumChannel to Instruction: channel is not an N-qubit channel.' ) if not self.is_cptp(): raise QiskitError( 'Cannot convert QuantumChannel to Instruction: channel is not CPTP.' ) # Next we convert to the Kraus representation. Since channel is CPTP we know # that there is only a single set of Kraus operators kraus, _ = _to_kraus(self.rep, self._data, *self.dim) # If we only have a single Kraus operator then the channel is # a unitary channel so can be converted to a UnitaryGate. We do this by # converting to an Operator and using its to_instruction method if len(kraus) == 1: return Operator(kraus[0]).to_instruction() return Instruction('kraus', n_qubits, 0, kraus)
def to_instruction(self): """Convert to a Kraus or UnitaryGate circuit instruction. If the channel is unitary it will be added as a unitary gate, otherwise it will be added as a kraus simulator instruction. Returns: Instruction: A kraus instruction for the channel. Raises: QiskitError: if input data is not an N-qubit CPTP quantum channel. """ from qiskit.circuit.instruction import Instruction # Check if input is an N-qubit CPTP channel. n_qubits = int(np.log2(self._input_dim)) if self._input_dim != self._output_dim or 2**n_qubits != self._input_dim: raise QiskitError( 'Cannot convert QuantumChannel to Instruction: channel is not an N-qubit channel.' ) if not self.is_cptp(): raise QiskitError( 'Cannot convert QuantumChannel to Instruction: channel is not CPTP.' ) # Next we convert to the Kraus representation. Since channel is CPTP we know # that there is only a single set of Kraus operators kraus, _ = _to_kraus(self.rep, self._data, *self.dim) # If we only have a single Kraus operator then the channel is # a unitary channel so can be converted to a UnitaryGate. We do this by # converting to an Operator and using its to_instruction method if len(kraus) == 1: return Operator(kraus[0]).to_instruction() return Instruction('kraus', n_qubits, 0, kraus)
[ "Convert", "to", "a", "Kraus", "or", "UnitaryGate", "circuit", "instruction", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/quantum_channel.py#L57-L88
[ "def", "to_instruction", "(", "self", ")", ":", "from", "qiskit", ".", "circuit", ".", "instruction", "import", "Instruction", "# Check if input is an N-qubit CPTP channel.", "n_qubits", "=", "int", "(", "np", ".", "log2", "(", "self", ".", "_input_dim", ")", ")", "if", "self", ".", "_input_dim", "!=", "self", ".", "_output_dim", "or", "2", "**", "n_qubits", "!=", "self", ".", "_input_dim", ":", "raise", "QiskitError", "(", "'Cannot convert QuantumChannel to Instruction: channel is not an N-qubit channel.'", ")", "if", "not", "self", ".", "is_cptp", "(", ")", ":", "raise", "QiskitError", "(", "'Cannot convert QuantumChannel to Instruction: channel is not CPTP.'", ")", "# Next we convert to the Kraus representation. Since channel is CPTP we know", "# that there is only a single set of Kraus operators", "kraus", ",", "_", "=", "_to_kraus", "(", "self", ".", "rep", ",", "self", ".", "_data", ",", "*", "self", ".", "dim", ")", "# If we only have a single Kraus operator then the channel is", "# a unitary channel so can be converted to a UnitaryGate. We do this by", "# converting to an Operator and using its to_instruction method", "if", "len", "(", "kraus", ")", "==", "1", ":", "return", "Operator", "(", "kraus", "[", "0", "]", ")", ".", "to_instruction", "(", ")", "return", "Instruction", "(", "'kraus'", ",", "n_qubits", ",", "0", ",", "kraus", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumChannel._is_cp_helper
Test if a channel is completely-positive (CP)
qiskit/quantum_info/operators/channel/quantum_channel.py
def _is_cp_helper(self, choi, atol, rtol): """Test if a channel is completely-positive (CP)""" if atol is None: atol = self._atol if rtol is None: rtol = self._rtol return is_positive_semidefinite_matrix(choi, rtol=rtol, atol=atol)
def _is_cp_helper(self, choi, atol, rtol): """Test if a channel is completely-positive (CP)""" if atol is None: atol = self._atol if rtol is None: rtol = self._rtol return is_positive_semidefinite_matrix(choi, rtol=rtol, atol=atol)
[ "Test", "if", "a", "channel", "is", "completely", "-", "positive", "(", "CP", ")" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/quantum_channel.py#L90-L96
[ "def", "_is_cp_helper", "(", "self", ",", "choi", ",", "atol", ",", "rtol", ")", ":", "if", "atol", "is", "None", ":", "atol", "=", "self", ".", "_atol", "if", "rtol", "is", "None", ":", "rtol", "=", "self", ".", "_rtol", "return", "is_positive_semidefinite_matrix", "(", "choi", ",", "rtol", "=", "rtol", ",", "atol", "=", "atol", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumChannel._is_tp_helper
Test if Choi-matrix is trace-preserving (TP)
qiskit/quantum_info/operators/channel/quantum_channel.py
def _is_tp_helper(self, choi, atol, rtol): """Test if Choi-matrix is trace-preserving (TP)""" if atol is None: atol = self._atol if rtol is None: rtol = self._rtol # Check if the partial trace is the identity matrix d_in, d_out = self.dim mat = np.trace( np.reshape(choi, (d_in, d_out, d_in, d_out)), axis1=1, axis2=3) return is_identity_matrix(mat, rtol=rtol, atol=atol)
def _is_tp_helper(self, choi, atol, rtol): """Test if Choi-matrix is trace-preserving (TP)""" if atol is None: atol = self._atol if rtol is None: rtol = self._rtol # Check if the partial trace is the identity matrix d_in, d_out = self.dim mat = np.trace( np.reshape(choi, (d_in, d_out, d_in, d_out)), axis1=1, axis2=3) return is_identity_matrix(mat, rtol=rtol, atol=atol)
[ "Test", "if", "Choi", "-", "matrix", "is", "trace", "-", "preserving", "(", "TP", ")" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/quantum_channel.py#L98-L108
[ "def", "_is_tp_helper", "(", "self", ",", "choi", ",", "atol", ",", "rtol", ")", ":", "if", "atol", "is", "None", ":", "atol", "=", "self", ".", "_atol", "if", "rtol", "is", "None", ":", "rtol", "=", "self", ".", "_rtol", "# Check if the partial trace is the identity matrix", "d_in", ",", "d_out", "=", "self", ".", "dim", "mat", "=", "np", ".", "trace", "(", "np", ".", "reshape", "(", "choi", ",", "(", "d_in", ",", "d_out", ",", "d_in", ",", "d_out", ")", ")", ",", "axis1", "=", "1", ",", "axis2", "=", "3", ")", "return", "is_identity_matrix", "(", "mat", ",", "rtol", "=", "rtol", ",", "atol", "=", "atol", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
QuantumChannel._format_state
Format input state so it is statevector or density matrix
qiskit/quantum_info/operators/channel/quantum_channel.py
def _format_state(self, state, density_matrix=False): """Format input state so it is statevector or density matrix""" state = np.array(state) shape = state.shape ndim = state.ndim if ndim > 2: raise QiskitError('Input state is not a vector or matrix.') # Flatten column-vector to vector if ndim == 2: if shape[1] != 1 and shape[1] != shape[0]: raise QiskitError('Input state is not a vector or matrix.') if shape[1] == 1: # flatten colum-vector to vector state = np.reshape(state, shape[0]) # Convert statevector to density matrix if required if density_matrix and ndim == 1: state = np.outer(state, np.transpose(np.conj(state))) return state
def _format_state(self, state, density_matrix=False): """Format input state so it is statevector or density matrix""" state = np.array(state) shape = state.shape ndim = state.ndim if ndim > 2: raise QiskitError('Input state is not a vector or matrix.') # Flatten column-vector to vector if ndim == 2: if shape[1] != 1 and shape[1] != shape[0]: raise QiskitError('Input state is not a vector or matrix.') if shape[1] == 1: # flatten colum-vector to vector state = np.reshape(state, shape[0]) # Convert statevector to density matrix if required if density_matrix and ndim == 1: state = np.outer(state, np.transpose(np.conj(state))) return state
[ "Format", "input", "state", "so", "it", "is", "statevector", "or", "density", "matrix" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/quantum_channel.py#L110-L127
[ "def", "_format_state", "(", "self", ",", "state", ",", "density_matrix", "=", "False", ")", ":", "state", "=", "np", ".", "array", "(", "state", ")", "shape", "=", "state", ".", "shape", "ndim", "=", "state", ".", "ndim", "if", "ndim", ">", "2", ":", "raise", "QiskitError", "(", "'Input state is not a vector or matrix.'", ")", "# Flatten column-vector to vector", "if", "ndim", "==", "2", ":", "if", "shape", "[", "1", "]", "!=", "1", "and", "shape", "[", "1", "]", "!=", "shape", "[", "0", "]", ":", "raise", "QiskitError", "(", "'Input state is not a vector or matrix.'", ")", "if", "shape", "[", "1", "]", "==", "1", ":", "# flatten colum-vector to vector", "state", "=", "np", ".", "reshape", "(", "state", ",", "shape", "[", "0", "]", ")", "# Convert statevector to density matrix if required", "if", "density_matrix", "and", "ndim", "==", "1", ":", "state", "=", "np", ".", "outer", "(", "state", ",", "np", ".", "transpose", "(", "np", ".", "conj", "(", "state", ")", ")", ")", "return", "state" ]
d4f58d903bc96341b816f7c35df936d6421267d1