Search is not available for this dataset
text
stringlengths
75
104k
def dist_abs(self): """Distance abs """ bounds = self.ax.get_xlim() if self.x else self.ax.get_ylim() return bounds[0] - bounds[1]
def to_string(self, indent): """Print the node data, with indent.""" ind = indent * ' ' print(ind, 'qreg') self.children[0].to_string(indent + 3)
def _verify_backends(self): """ Return the Basic Aer backends in `BACKENDS` that are effectively available (as some of them might depend on the presence of an optional dependency or on the existence of a binary). Returns: dict[str:BaseBackend]: a dict of Basic Aer ba...
def _get_backend_instance(self, backend_cls): """ Return an instance of a backend from its class. Args: backend_cls (class): Backend class. Returns: BaseBackend: a backend instance. Raises: QiskitError: if the backend could not be instantiated...
def qubits(self): """Return a list of qubits as (QuantumRegister, index) pairs.""" return [(v, i) for k, v in self.qregs.items() for i in range(v.size)]
def clbits(self): """Return a list of bits as (ClassicalRegister, index) pairs.""" return [(v, i) for k, v in self.cregs.items() for i in range(v.size)]
def rename_register(self, regname, newname): """Rename a classical or quantum register throughout the circuit. regname = existing register name string newname = replacement register name string """ if regname == newname: return if newname in self.qregs or new...
def remove_all_ops_named(self, opname): """Remove all operation nodes with the given name.""" for n in self.named_nodes(opname): self.remove_op_node(n)
def add_qreg(self, qreg): """Add all wires in a quantum register.""" if not isinstance(qreg, QuantumRegister): raise DAGCircuitError("not a QuantumRegister instance.") if qreg.name in self.qregs: raise DAGCircuitError("duplicate register %s" % qreg.name) self.qreg...
def add_creg(self, creg): """Add all wires in a classical register.""" if not isinstance(creg, ClassicalRegister): raise DAGCircuitError("not a ClassicalRegister instance.") if creg.name in self.cregs: raise DAGCircuitError("duplicate register %s" % creg.name) sel...
def _add_wire(self, wire): """Add a qubit or bit to the circuit. Args: wire (tuple): (Register,int) containing a register instance and index This adds a pair of in and out nodes connected by an edge. Raises: DAGCircuitError: if trying to add duplicate wire ...
def _check_condition(self, name, condition): """Verify that the condition is valid. Args: name (string): used for error reporting condition (tuple or None): a condition tuple (ClassicalRegister,int) Raises: DAGCircuitError: if conditioning on an invalid regi...
def _check_bits(self, args, amap): """Check the values of a list of (qu)bit arguments. For each element of args, check that amap contains it. Args: args (list): (register,idx) tuples amap (dict): a dictionary keyed on (register,idx) tuples Raises: D...
def _bits_in_condition(self, cond): """Return a list of bits in the given condition. Args: cond (tuple or None): optional condition (ClassicalRegister, int) Returns: list[(ClassicalRegister, idx)]: list of bits """ all_bits = [] if cond is not No...
def _add_op_node(self, op, qargs, cargs, condition=None): """Add a new operation node to the graph and assign properties. Args: op (Instruction): the operation associated with the DAG node qargs (list): list of quantum wires to attach to. cargs (list): list of classi...
def apply_operation_back(self, op, qargs=None, cargs=None, condition=None): """Apply an operation to the output of the circuit. Args: op (Instruction): the operation associated with the DAG node qargs (list[tuple]): qubits that op will be applied to cargs (list[tuple...
def _check_edgemap_registers(self, edge_map, keyregs, valregs, valreg=True): """Check that wiremap neither fragments nor leaves duplicate registers. 1. There are no fragmented registers. A register in keyregs is fragmented if not all of its (qu)bits are renamed by edge_map. 2. There are...
def _check_wiremap_validity(self, wire_map, keymap, valmap): """Check that the wiremap is consistent. Check that the wiremap refers to valid wires and that those wires have consistent types. Args: wire_map (dict): map from (register,idx) in keymap to (regist...
def _map_condition(self, wire_map, condition): """Use the wire_map dict to change the condition tuple's creg name. Args: wire_map (dict): a map from wires to wires condition (tuple): (ClassicalRegister,int) Returns: tuple(ClassicalRegister,int): new condition...
def extend_back(self, dag, edge_map=None): """Add `dag` at the end of `self`, using `edge_map`. """ edge_map = edge_map or {} for qreg in dag.qregs.values(): if qreg.name not in self.qregs: self.add_qreg(QuantumRegister(qreg.size, qreg.name)) edge_...
def compose_back(self, input_circuit, edge_map=None): """Apply the input circuit to the output of this circuit. The two bases must be "compatible" or an exception occurs. A subset of input qubits of the input circuit are mapped to a subset of output qubits of this circuit. Args...
def depth(self): """Return the circuit depth. Returns: int: the circuit depth Raises: DAGCircuitError: if not a directed acyclic graph """ if not nx.is_directed_acyclic_graph(self._multi_graph): raise DAGCircuitError("not a DAG") depth...
def _check_wires_list(self, wires, node): """Check that a list of wires is compatible with a node to be replaced. - no duplicate names - correct length for operation Raise an exception otherwise. Args: wires (list[register, index]): gives an order for (qu)bits ...
def _make_pred_succ_maps(self, node): """Return predecessor and successor dictionaries. Args: node (DAGNode): reference to multi_graph node Returns: tuple(dict): tuple(predecessor_map, successor_map) These map from wire (Register, int) to predecessor (su...
def _full_pred_succ_maps(self, pred_map, succ_map, input_circuit, wire_map): """Map all wires of the input circuit. Map all wires of the input circuit to predecessor and successor nodes in self, keyed on wires in self. Args: pred_map (dict): com...
def topological_nodes(self): """ Yield nodes in topological order. Returns: generator(DAGNode): node in topological order """ return nx.lexicographical_topological_sort(self._multi_graph, key=lambda x: str(x.qargs))
def substitute_node_with_dag(self, node, input_dag, wires=None): """Replace one node with dag. Args: node (DAGNode): node to substitute input_dag (DAGCircuit): circuit that will substitute the node wires (list[(Register, index)]): gives an order for (qu)bits ...
def edges(self, nodes=None): """Iterator for node values. Yield: node: the node. """ for source_node, dest_node, edge_data in self._multi_graph.edges(nodes, data=True): yield source_node, dest_node, edge_data
def get_op_nodes(self, op=None, data=False): """Deprecated. Use op_nodes().""" warnings.warn('The method get_op_nodes() is being replaced by op_nodes().' 'Returning a list of node_ids/(node_id, data) tuples is ' 'also deprecated, op_nodes() returns a list of ...
def op_nodes(self, op=None): """Get the list of "op" nodes in the dag. Args: op (Type): Instruction subclass op nodes to return. if op=None, return all op nodes. Returns: list[DAGNode]: the list of node ids containing the given op. """ nod...
def get_gate_nodes(self, data=False): """Deprecated. Use gate_nodes().""" warnings.warn('The method get_gate_nodes() is being replaced by gate_nodes().' 'Returning a list of node_ids/(node_id, data) tuples is also ' 'deprecated, gate_nodes() returns a list of ...
def gate_nodes(self): """Get the list of gate nodes in the dag. Returns: list: the list of node ids that represent gates. """ nodes = [] for node in self.op_nodes(): if isinstance(node.op, Gate): nodes.append(node) return nodes
def get_named_nodes(self, *names): """Deprecated. Use named_nodes().""" warnings.warn('The method get_named_nodes() is being replaced by named_nodes()', 'Returning a list of node_ids is also deprecated, named_nodes() ' 'returns a list of DAGNodes ', ...
def named_nodes(self, *names): """Get the set of "op" nodes with the given name.""" named_nodes = [] for node in self._multi_graph.nodes(): if node.type == 'op' and node.op.name in names: named_nodes.append(node) return named_nodes
def get_2q_nodes(self): """Deprecated. Use twoQ_gates().""" warnings.warn('The method get_2q_nodes() is being replaced by twoQ_gates()', 'Returning a list of data_dicts is also deprecated, twoQ_gates() ' 'returns a list of DAGNodes.', Dep...
def twoQ_gates(self): """Get list of 2-qubit gates. Ignore snapshot, barriers, and the like.""" two_q_gates = [] for node in self.gate_nodes(): if len(node.qargs) == 2: two_q_gates.append(node) return two_q_gates
def get_3q_or_more_nodes(self): """Deprecated. Use threeQ_or_more_gates().""" warnings.warn('The method get_3q_or_more_nodes() is being replaced by' ' threeQ_or_more_gates()', 'Returning a list of (node_id, data) tuples is also deprecated, ' ...
def threeQ_or_more_gates(self): """Get list of 3-or-more-qubit gates: (id, data).""" three_q_gates = [] for node in self.gate_nodes(): if len(node.qargs) >= 3: three_q_gates.append(node) return three_q_gates
def predecessors(self, node): """Returns list of the predecessors of a node as DAGNodes.""" if isinstance(node, int): warnings.warn('Calling predecessors() with a node id is deprecated,' ' use a DAGNode instead', DeprecationWarning, 2) ...
def quantum_predecessors(self, node): """Returns list of the predecessors of a node that are connected by a quantum edge as DAGNodes.""" predecessors = [] for predecessor in self.predecessors(node): if isinstance(self._multi_graph.get_edge_data(predecessor, node, key=0)['wir...
def ancestors(self, node): """Returns set of the ancestors of a node as DAGNodes.""" if isinstance(node, int): warnings.warn('Calling ancestors() with a node id is deprecated,' ' use a DAGNode instead', DeprecationWarning, 2) no...
def quantum_successors(self, node): """Returns list of the successors of a node that are connected by a quantum edge as DAGNodes.""" if isinstance(node, int): warnings.warn('Calling quantum_successors() with a node id is deprecated,' ' use a DAGNode instead'...
def remove_op_node(self, node): """Remove an operation node n. Add edges from predecessors to successors. """ if isinstance(node, int): warnings.warn('Calling remove_op_node() with a node id is deprecated,' ' use a DAGNode instead', ...
def remove_ancestors_of(self, node): """Remove all of the ancestor operation nodes of node.""" if isinstance(node, int): warnings.warn('Calling remove_ancestors_of() with a node id is deprecated,' ' use a DAGNode instead', DeprecationWarnin...
def remove_descendants_of(self, node): """Remove all of the descendant operation nodes of node.""" if isinstance(node, int): warnings.warn('Calling remove_descendants_of() with a node id is deprecated,' ' use a DAGNode instead', Deprecation...
def remove_nonancestors_of(self, node): """Remove all of the non-ancestors operation nodes of node.""" if isinstance(node, int): warnings.warn('Calling remove_nonancestors_of() with a node id is deprecated,' ' use a DAGNode instead', Deprec...
def remove_nondescendants_of(self, node): """Remove all of the non-descendants operation nodes of node.""" if isinstance(node, int): warnings.warn('Calling remove_nondescendants_of() with a node id is deprecated,' ' use a DAGNode instead', ...
def layers(self): """Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit. A layer is a circuit whose gates act on disjoint qubits, i.e. a layer has depth 1. The total number of layers equals the circuit depth d. The layers are indexed from 0 to d-1 with t...
def serial_layers(self): """Yield a layer for all gates of this circuit. A serial layer is a circuit with one gate. The layers have the same structure as in layers(). """ for next_node in self.topological_op_nodes(): new_layer = DAGCircuit() for qreg in s...
def multigraph_layers(self): """Yield layers of the multigraph.""" predecessor_count = dict() # Dict[node, predecessors not visited] cur_layer = [node for node in self.input_map.values()] yield cur_layer next_layer = [] while cur_layer: for node in cur_layer:...
def collect_runs(self, namelist): """Return a set of non-conditional runs of "op" nodes with the given names. For example, "... h q[0]; cx q[0],q[1]; cx q[0],q[1]; h q[1]; .." would produce the tuple of cx nodes as an element of the set returned from a call to collect_runs(["cx"]). If i...
def nodes_on_wire(self, wire, only_ops=False): """ Iterator for nodes that affect a given wire Args: wire (tuple(Register, index)): the wire to be looked at. only_ops (bool): True if only the ops nodes are wanted otherwise all nodes are returned. ...
def count_ops(self): """Count the occurrences of operation names. Returns a dictionary of counts keyed on the operation name. """ op_dict = {} for node in self.topological_op_nodes(): name = node.name if name not in op_dict: op_dict[name] ...
def properties(self): """Return a dictionary of circuit properties.""" summary = {"size": self.size(), "depth": self.depth(), "width": self.width(), "bits": self.num_cbits(), "factors": self.num_tensor_factors(), ...
def tomography_basis(basis, prep_fun=None, meas_fun=None): """ Generate a TomographyBasis object. See TomographyBasis for further details.abs Args: prep_fun (callable) optional: the function which adds preparation gates to a circuit. meas_fun (callable) optional: the functi...
def __pauli_prep_gates(circuit, qreg, op): """ Add state preparation gates to a circuit. """ bas, proj = op if bas not in ['X', 'Y', 'Z']: raise QiskitError("There's no X, Y or Z basis for this Pauli " "preparation") if bas == "X": if proj == 1: ...
def __pauli_meas_gates(circuit, qreg, op): """ Add state measurement gates to a circuit. """ if op not in ['X', 'Y', 'Z']: raise QiskitError("There's no X, Y or Z basis for this Pauli " "measurement") if op == "X": circuit.u2(0., np.pi, qreg) # H elif ...
def __sic_prep_gates(circuit, qreg, op): """ Add state preparation gates to a circuit. """ bas, proj = op if bas != 'S': raise QiskitError('Not in SIC basis!') theta = -2 * np.arctan(np.sqrt(2)) if proj == 1: circuit.u3(theta, np.pi, 0.0, qreg) elif proj == 2: c...
def tomography_set(meas_qubits, meas_basis='Pauli', prep_qubits=None, prep_basis=None): """ Generate a dictionary of tomography experiment configurations. This returns a data structure that is used by other tomography functions to generate state ...
def process_tomography_set(meas_qubits, meas_basis='Pauli', prep_qubits=None, prep_basis='SIC'): """ Generate a dictionary of process tomography experiment configurations. This returns a data structure that is used by other tomography functions to generate state and process t...
def create_tomography_circuits(circuit, qreg, creg, tomoset): """ Add tomography measurement circuits to a QuantumProgram. The quantum program must contain a circuit 'name', which is treated as a state preparation circuit for state tomography, or as teh circuit being measured for process tomography...
def tomography_data(results, name, tomoset): """ Return a results dict for a state or process tomography experiment. Args: results (Result): Results from execution of a process tomography circuits on a backend. name (string): The name of the circuit being reconstructed. ...
def marginal_counts(counts, meas_qubits): """ Compute the marginal counts for a subset of measured qubits. Args: counts (dict): the counts returned from a backend ({str: int}). meas_qubits (list[int]): the qubits to return the marginal counts distribution fo...
def fit_tomography_data(tomo_data, method='wizard', options=None): """ Reconstruct a density matrix or process-matrix from tomography data. If the input data is state_tomography_data the returned operator will be a density matrix. If the input data is process_tomography_data the returned operator w...
def __leastsq_fit(tomo_data, weights=None, trace=None, beta=None): """ Reconstruct a state from unconstrained least-squares fitting. Args: tomo_data (list[dict]): state or process tomography data. weights (list or array or None): weights to use for least squares fitting. The def...
def __projector(op_list, basis): """Returns a projectors. """ ret = 1 # list is from qubit 0 to 1 for op in op_list: label, eigenstate = op ret = np.kron(basis[label][eigenstate], ret) return ret
def __tomo_linear_inv(freqs, ops, weights=None, trace=None): """ Reconstruct a matrix through linear inversion. Args: freqs (list[float]): list of observed frequences. ops (list[np.array]): list of corresponding projectors. weights (list[float] or array_like): weights to...
def __wizard(rho, epsilon=None): """ Returns the nearest positive semidefinite operator to an operator. This method is based on reference [1]. It constrains positivity by setting negative eigenvalues to zero and rescaling the positive eigenvalues. Args: rho (array_like): the input oper...
def build_wigner_circuits(circuit, phis, thetas, qubits, qreg, creg): """Create the circuits to rotate to points in phase space Args: circuit (QuantumCircuit): The circuit to be appended with tomography state preparation and/or measurements. ...
def wigner_data(q_result, meas_qubits, labels, shots=None): """Get the value of the Wigner function from measurement results. Args: q_result (Result): Results from execution of a state tomography circuits on a backend. meas_qubits (list[int]): a list of the qubit ind...
def prep_gate(self, circuit, qreg, op): """ Add state preparation gates to a circuit. Args: circuit (QuantumCircuit): circuit to add a preparation to. qreg (tuple(QuantumRegister,int)): quantum register to apply preparation to. op (tuple(str, int)...
def meas_gate(self, circuit, qreg, op): """ Add measurement gates to a circuit. Args: circuit (QuantumCircuit): circuit to add measurement to. qreg (tuple(QuantumRegister,int)): quantum register being measured. op (str): the basis label for the measurement. ...
def _text_checker(job, interval, _interval_set=False, quiet=False, output=sys.stdout): """A text-based job status checker Args: job (BaseJob): The job to check. interval (int): The interval at which to check. _interval_set (bool): Was interval time set by user? quiet (bool): If ...
def job_monitor(job, interval=None, monitor_async=False, quiet=False, output=sys.stdout): """Monitor the status of a IBMQJob instance. Args: job (BaseJob): Job to monitor. interval (int): Time interval between status queries. monitor_async (bool): Monitor asyncronously (in Jupyter only)...
def euler_angles_1q(unitary_matrix): """Compute Euler angles for a single-qubit gate. Find angles (theta, phi, lambda) such that unitary_matrix = phase * Rz(phi) * Ry(theta) * Rz(lambda) Args: unitary_matrix (ndarray): 2x2 unitary matrix Returns: tuple: (theta, phi, lambda) Euler ...
def simplify_U(theta, phi, lam): """Return the gate u1, u2, or u3 implementing U with the fewest pulses. The returned gate implements U exactly, not up to a global phase. Args: theta, phi, lam: input Euler rotation angles for a general U gate Returns: Gate: one of IdGate, U1Gate, U2Ga...
def two_qubit_kak(unitary): """Decompose a two-qubit gate over SU(2)+CNOT using the KAK decomposition. Args: unitary (Operator): a 4x4 unitary operator to decompose. Returns: QuantumCircuit: a circuit implementing the unitary over SU(2)+CNOT Raises: QiskitError: input not a un...
def run(self, dag): """ Extends dag with virtual qubits that are in layout but not in the circuit yet. Args: dag (DAGCircuit): DAG to extend. Returns: DAGCircuit: An extended DAG. Raises: TranspilerError: If there is not layout in the proper...
def _define(self): """ gate ch a,b { h b; sdg b; cx a,b; h b; t b; cx a,b; t b; h b; s b; x b; s a;} """ definition = [] q = QuantumRegister(2, "q") rule = [ (HGate(), [q[1...
def config_tab(backend): """The backend configuration widget. Args: backend (IBMQbackend): The backend. Returns: grid: A GridBox widget. """ status = backend.status().to_dict() config = backend.configuration().to_dict() config_dict = {**status, **config} upper_list = ...
def qubits_tab(backend): """The qubits properties widget Args: backend (IBMQbackend): The backend. Returns: VBox: A VBox widget. """ props = backend.properties().to_dict() header_html = "<div><font style='font-weight:bold'>{key}</font>: {value}</div>" header_html = header_...
def gates_tab(backend): """The multiple qubit gate error widget. Args: backend (IBMQbackend): The backend. Returns: VBox: A VBox widget. """ config = backend.configuration().to_dict() props = backend.properties().to_dict() multi_qubit_gates = props['gates'][3*config['n_qub...
def detailed_map(backend): """Widget for displaying detailed noise map. Args: backend (IBMQbackend): The backend. Returns: GridBox: Widget holding noise map images. """ props = backend.properties().to_dict() config = backend.configuration().to_dict() single_gate_errors = [q...
def job_history(backend): """Widget for displaying job history Args: backend (IBMQbackend): The backend. Returns: Tab: A tab widget for history images. """ year = widgets.Output(layout=widgets.Layout(display='flex-inline', align_items='c...
def plot_job_history(jobs, interval='year'): """Plots the job history of the user from the given list of jobs. Args: jobs (list): A list of jobs with type IBMQjob. interval (str): Interval over which to examine. Returns: fig: A Matplotlib figure instance. """ def get_date(j...
def run(self, dag): """Return a new circuit that has been optimized.""" resets = dag.op_nodes(Reset) for reset in resets: predecessor = next(dag.predecessors(reset)) if predecessor.type == 'in': dag.remove_op_node(reset) return dag
def draw(self, **kwargs): """Plot the interpolated envelope of pulse. Keyword Args: dt (float): Time interval of samples. interp_method (str): Method of interpolation (set `None` for turn off the interpolation). filename (str): Name required to save p...
def cu3(self, theta, phi, lam, ctl, tgt): """Apply cu3 from ctl to tgt with angle theta, phi, lam.""" return self.append(Cu3Gate(theta, phi, lam), [ctl, tgt], [])
def _define(self): """ gate cu3(theta,phi,lambda) c, t { u1((lambda-phi)/2) t; cx c,t; u3(-theta/2,0,-(phi+lambda)/2) t; cx c,t; u3(theta/2,phi,0) t; } """ definition = [] q = QuantumRegister(2, "q") rule = [ (U1Gate((self.p...
def build_bell_circuit(): """Returns a circuit putting 2 qubits in the Bell state.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q, c) return qc
def transpile(circuits, backend=None, basis_gates=None, coupling_map=None, backend_properties=None, initial_layout=None, seed_transpiler=None, optimization_level=None, pass_manager=None, seed_mapper=None): # deprecated """transpile...
def _transpile_circuit(circuit_config_tuple): """Select a PassManager and run a single circuit through it. Args: circuit_config_tuple (tuple): circuit (QuantumCircuit): circuit to transpile transpile_config (TranspileConfig): configuration dictating how to transpile Returns...
def _parse_transpile_args(circuits, backend, basis_gates, coupling_map, backend_properties, initial_layout, seed_transpiler, optimization_level, pass_manager): """Resolve the various types of args allowed to the transpile() function throu...
def execute(experiments, backend, basis_gates=None, coupling_map=None, # circuit transpile options backend_properties=None, initial_layout=None, seed_transpiler=None, optimization_level=None, pass_manager=None, qobj_id=None, qobj_header=None, shots=1024, # common run op...
def drive(self) -> DriveChannel: """Return the primary drive channel of this qubit.""" if self._drives: return self._drives[0] else: raise PulseError("No drive channels in q[%d]" % self._index)
def control(self) -> ControlChannel: """Return the primary control channel of this qubit.""" if self._controls: return self._controls[0] else: raise PulseError("No control channels in q[%d]" % self._index)
def measure(self) -> MeasureChannel: """Return the primary measure channel of this qubit.""" if self._measures: return self._measures[0] else: raise PulseError("No measurement channels in q[%d]" % self._index)
def acquire(self) -> AcquireChannel: """Return the primary acquire channel of this qubit.""" if self._acquires: return self._acquires[0] else: raise PulseError("No acquire channels in q[%d]" % self._index)
def input_state(circ, q, n): """n-qubit input state for QFT that produces output 1.""" for j in range(n): circ.h(q[j]) circ.u1(math.pi/float(2**(j)), q[j]).inverse()
def assemble_circuits(circuits, qobj_id=None, qobj_header=None, run_config=None): """Assembles a list of circuits into a qobj which can be run on the backend. Args: circuits (list[QuantumCircuits]): circuit(s) to assemble qobj_id (int): identifier for the generated qobj qobj_header (Qob...