INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Add registers.
def add_register(self, *regs): """Add registers.""" if not regs: return if any([isinstance(reg, int) for reg in regs]): # QuantumCircuit defined without registers if len(regs) == 1 and isinstance(regs[0], int): # QuantumCircuit with anonymous ...
Raise exception if list of qubits contains duplicates.
def _check_dups(self, qubits): """Raise exception if list of qubits contains duplicates.""" squbits = set(qubits) if len(squbits) != len(qubits): raise QiskitError("duplicate qubit arguments")
Raise exception if a qarg is not in this circuit or bad format.
def _check_qargs(self, qargs): """Raise exception if a qarg is not in this circuit or bad format.""" if not all(isinstance(i, tuple) and isinstance(i[0], QuantumRegister) and isinstance(i[1], int) for i in qargs): raise QiskitError("qarg not (QuantumRegi...
Raise exception if clbit is not in this circuit or bad format.
def _check_cargs(self, cargs): """Raise exception if clbit is not in this circuit or bad format.""" if not all(isinstance(i, tuple) and isinstance(i[0], ClassicalRegister) and isinstance(i[1], int) for i in cargs): raise QiskitError("carg not (ClassicalR...
Call a decomposition pass on this circuit to decompose one level ( shallow decompose ).
def decompose(self): """Call a decomposition pass on this circuit, to decompose one level (shallow decompose). Returns: QuantumCircuit: a circuit one level decomposed """ from qiskit.transpiler.passes.decompose import Decompose from qiskit.converters.circuit_...
Raise exception if the circuits are defined on incompatible registers
def _check_compatible_regs(self, rhs): """Raise exception if the circuits are defined on incompatible registers""" list1 = self.qregs + self.cregs list2 = rhs.qregs + rhs.cregs for element1 in list1: for element2 in list2: if element2.name == element1.name: ...
Return OpenQASM string.
def qasm(self): """Return OpenQASM string.""" string_temp = self.header + "\n" string_temp += self.extension_lib + "\n" for register in self.qregs: string_temp += register.qasm() + "\n" for register in self.cregs: string_temp += register.qasm() + "\n" ...
Draw the quantum circuit
def draw(self, scale=0.7, filename=None, style=None, output='text', interactive=False, line_length=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw the quantum circuit Using the output parameter you can specify the format. The choices are: 0. text: ...
Returns total number of gate operations in circuit.
def size(self): """Returns total number of gate operations in circuit. Returns: int: Total number of gate operations. """ gate_ops = 0 for instr, _, _ in self.data: if instr.name not in ['barrier', 'snapshot']: gate_ops += 1 return...
Return circuit depth ( i. e. length of critical path ). This does not include compiler or simulator directives such as barrier or snapshot.
def depth(self): """Return circuit depth (i.e. length of critical path). This does not include compiler or simulator directives such as 'barrier' or 'snapshot'. Returns: int: Depth of circuit. Notes: The circuit depth and the DAG depth need not bt the ...
Return number of qubits plus clbits in circuit.
def width(self): """Return number of qubits plus clbits in circuit. Returns: int: Width of circuit. """ return sum(reg.size for reg in self.qregs+self.cregs)
Count each operation kind in the circuit.
def count_ops(self): """Count each operation kind in the circuit. Returns: dict: a breakdown of how many operations of each kind. """ count_ops = {} for instr, _, _ in self.data: if instr.name in count_ops.keys(): count_ops[instr.name] += ...
How many non - entangled subcircuits can the circuit be factored to.
def num_connected_components(self, unitary_only=False): """How many non-entangled subcircuits can the circuit be factored to. Args: unitary_only (bool): Compute only unitary part of graph. Returns: int: Number of connected components in circuit. """ # Co...
Assign parameters to values yielding a new circuit.
def bind_parameters(self, value_dict): """Assign parameters to values yielding a new circuit. Args: value_dict (dict): {parameter: value, ...} Raises: QiskitError: If value_dict contains parameters not present in the circuit Returns: QuantumCircuit:...
Assigns a parameter value to matching instructions in - place.
def _bind_parameter(self, parameter, value): """Assigns a parameter value to matching instructions in-place.""" for (instr, param_index) in self._parameter_table[parameter]: instr.params[param_index] = value
Plot the interpolated envelope of pulse
def pulse_drawer(samples, duration, dt=None, interp_method='None', filename=None, interactive=False, dpi=150, nop=1000, size=(6, 5)): """Plot the interpolated envelope of pulse Args: samples (ndarray): Data points of complex pulse envelope. duration (int): Puls...
Search for SWAPs which allow for application of largest number of gates.
def _search_forward_n_swaps(layout, gates, coupling_map, depth=SEARCH_DEPTH, width=SEARCH_WIDTH): """Search for SWAPs which allow for application of largest number of gates. Arguments: layout (Layout): Map from virtual qubit index to physical qubit index. gates (list...
Map all gates that can be executed with the current layout.
def _map_free_gates(layout, gates, coupling_map): """Map all gates that can be executed with the current layout. Args: layout (Layout): Map from virtual qubit index to physical qubit index. gates (list): Gates to be mapped. coupling_map (CouplingMap): CouplingMap for target device topol...
Return the sum of the distances of two - qubit pairs in each CNOT in gates according to the layout and the coupling.
def _calc_layout_distance(gates, coupling_map, layout, max_gates=None): """Return the sum of the distances of two-qubit pairs in each CNOT in gates according to the layout and the coupling. """ if max_gates is None: max_gates = 50 + 10 * len(coupling_map.physical_qubits) return sum(couplin...
Count the mapped two - qubit gates less the number of added SWAPs.
def _score_step(step): """Count the mapped two-qubit gates, less the number of added SWAPs.""" # Each added swap will add 3 ops to gates_mapped, so subtract 3. return len([g for g in step['gates_mapped'] if len(g.qargs) == 2]) - 3 * step['swaps_added']
Return a copy of source_dag with metadata but empty. Generate only a single qreg in the output DAG matching the size of the coupling_map.
def _copy_circuit_metadata(source_dag, coupling_map): """Return a copy of source_dag with metadata but empty. Generate only a single qreg in the output DAG, matching the size of the coupling_map.""" target_dag = DAGCircuit() target_dag.name = source_dag.name for creg in source_dag.cregs.values...
Return op implementing a virtual gate on given layout.
def _transform_gate_for_layout(gate, layout): """Return op implementing a virtual gate on given layout.""" mapped_op_node = deepcopy([n for n in gate['graph'].nodes() if n.type == 'op'][0]) # Workaround until #1816, apply mapped to qargs to both DAGNode and op device_qreg = QuantumRegister(len(layout....
Generate list of ops to implement a SWAP gate along a coupling edge.
def _swap_ops_from_edge(edge, layout): """Generate list of ops to implement a SWAP gate along a coupling edge.""" device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q') qreg_edge = [(device_qreg, i) for i in edge] # TODO shouldn't be making other nodes not by the DAG!! return [ ...
Run one pass of the lookahead mapper on the provided DAG.
def run(self, dag): """Run one pass of the lookahead mapper on the provided DAG. Args: dag (DAGCircuit): the directed acyclic graph to be mapped Returns: DAGCircuit: A dag mapped to be compatible with the coupling_map in the property_set. Raises: ...
Add a physical qubit to the coupling graph as a node.
def add_physical_qubit(self, physical_qubit): """Add a physical qubit to the coupling graph as a node. physical_qubit (int): An integer representing a physical qubit. Raises: CouplingError: if trying to add duplicate qubit """ if not isinstance(physical_qubit, int):...
Add directed edge to coupling graph.
def add_edge(self, src, dst): """ Add directed edge to coupling graph. src (int): source physical qubit dst (int): destination physical qubit """ if src not in self.physical_qubits: self.add_physical_qubit(src) if dst not in self.physical_qubits: ...
Return a CouplingMap object for a subgraph of self.
def subgraph(self, nodelist): """Return a CouplingMap object for a subgraph of self. nodelist (list): list of integer node labels """ subcoupling = CouplingMap() subcoupling.graph = self.graph.subgraph(nodelist) for node in nodelist: if node not in subcouplin...
Returns a sorted list of physical_qubits
def physical_qubits(self): """Returns a sorted list of physical_qubits""" if self._qubit_list is None: self._qubit_list = sorted([pqubit for pqubit in self.graph.nodes]) return self._qubit_list
Test if the graph is connected.
def is_connected(self): """ Test if the graph is connected. Return True if connected, False otherwise """ try: return nx.is_weakly_connected(self.graph) except nx.exception.NetworkXException: return False
Compute the full distance matrix on pairs of nodes.
def _compute_distance_matrix(self): """Compute the full distance matrix on pairs of nodes. The distance map self._dist_matrix is computed from the graph using all_pairs_shortest_path_length. """ if not self.is_connected(): raise CouplingError("coupling graph not conn...
Returns the undirected distance between physical_qubit1 and physical_qubit2.
def distance(self, physical_qubit1, physical_qubit2): """Returns the undirected distance between physical_qubit1 and physical_qubit2. Args: physical_qubit1 (int): A physical qubit physical_qubit2 (int): Another physical qubit Returns: int: The undirected dis...
transpile one or more circuits.
def transpile(circuits, backend=None, basis_gates=None, coupling_map=None, initial_layout=None, seed_mapper=None, pass_manager=None): """transpile one or more circuits. Args: circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile backend (BaseBackend): a backend to...
Deprecated - Use qiskit. compiler. transpile for transpiling from circuits to circuits. Transform a dag circuit into another dag circuit ( transpile ) through consecutive passes on the dag.
def transpile_dag(dag, basis_gates=None, coupling_map=None, initial_layout=None, seed_mapper=None, pass_manager=None): """Deprecated - Use qiskit.compiler.transpile for transpiling from circuits to circuits. Transform a dag circuit into another dag circuit (transpile), through consecut...
Apply cu1 from ctl to tgt with angle theta.
def cu1(self, theta, ctl, tgt): """Apply cu1 from ctl to tgt with angle theta.""" return self.append(Cu1Gate(theta), [ctl, tgt], [])
Add an instruction and its context ( where it s attached ).
def add(self, gate, qargs, cargs): """Add an instruction and its context (where it's attached).""" if not isinstance(gate, Instruction): raise QiskitError("attempt to add non-Instruction" + " to InstructionSet") self.instructions.append(gate) sel...
Invert all instructions.
def inverse(self): """Invert all instructions.""" for index, instruction in enumerate(self.instructions): self.instructions[index] = instruction.inverse() return self
Add controls to all instructions.
def q_if(self, *qregs): """Add controls to all instructions.""" for gate in self.instructions: gate.q_if(*qregs) return self
Add classical control register to all instructions.
def c_if(self, classical, val): """Add classical control register to all instructions.""" for gate in self.instructions: gate.c_if(classical, val) return self
Subscribes to an event so when it s emitted all the callbacks subscribed will be executed. We are not allowing double registration.
def subscribe(self, event, callback): """Subscribes to an event, so when it's emitted all the callbacks subscribed, will be executed. We are not allowing double registration. Args event (string): The event to subscribed in the form of: "terra.<component>....
Emits an event if there are any subscribers.
def dispatch(self, event, *args, **kwargs): """Emits an event if there are any subscribers. Args event (String): The event to be emitted args: Arguments linked with the event kwargs: Named arguments linked with the event """ # No event, no subscribers...
Unsubscribe the specific callback to the event.
def unsubscribe(self, event, callback): """ Unsubscribe the specific callback to the event. Args event (String): The event to unsubscribe callback (callable): The callback that won't be executed anymore Returns True: if we have successfully unsubscribed to t...
Triggers an event and associates some data to it so if there are any subscribers their callback will be called synchronously.
def publish(self, event, *args, **kwargs): """ Triggers an event, and associates some data to it, so if there are any subscribers, their callback will be called synchronously. """ return self._broker.dispatch(event, *args, **kwargs)
Apply initialize to circuit.
def initialize(self, params, qubits): """Apply initialize to circuit.""" if isinstance(qubits, QuantumRegister): qubits = qubits[:] else: qubits = _convert_to_bits([qubits], [qbit for qreg in self.qregs for qbit in qreg])[0] return self.append(Initialize(params), qubits)
Calculate a subcircuit that implements this initialization
def _define(self): """Calculate a subcircuit that implements this initialization Implements a recursive initialization algorithm, including optimizations, from "Synthesis of Quantum Logic Circuits" Shende, Bullock, Markov https://arxiv.org/abs/quant-ph/0406176v5 Additionally im...
Call to create a circuit with gates that take the desired vector to zero.
def gates_to_uncompute(self): """ Call to create a circuit with gates that take the desired vector to zero. Returns: QuantumCircuit: circuit to take self.params vector to |00..0> """ q = QuantumRegister(self.num_qubits) circuit = QuantumCircuit(q, nam...
Static internal method to work out Ry and Rz rotation angles used to disentangle the LSB qubit. These rotations make up the block diagonal matrix U ( i. e. multiplexor ) that disentangles the LSB.
def _rotations_to_disentangle(local_param): """ Static internal method to work out Ry and Rz rotation angles used to disentangle the LSB qubit. These rotations make up the block diagonal matrix U (i.e. multiplexor) that disentangles the LSB. [[Ry(theta_1).Rz(phi_1) 0 ...
Static internal method to work out rotation to create the passed in qubit from the zero vector.
def _bloch_angles(pair_of_complex): """ Static internal method to work out rotation to create the passed in qubit from the zero vector. """ [a_complex, b_complex] = pair_of_complex # Force a and b to be complex, as otherwise numpy.angle might fail. a_complex = com...
Return a recursive implementation of a multiplexor circuit where each instruction itself has a decomposition based on smaller multiplexors.
def _multiplex(self, target_gate, list_of_angles): """ Return a recursive implementation of a multiplexor circuit, where each instruction itself has a decomposition based on smaller multiplexors. The LSB is the multiplexor "data" and the other bits are multiplexor "select". ...
Populates a Layout from a dictionary. The dictionary must be a bijective mapping between virtual qubits ( tuple ) and physical qubits ( int ).
def from_dict(self, input_dict): """ Populates a Layout from a dictionary. The dictionary must be a bijective mapping between virtual qubits (tuple) and physical qubits (int). Args: input_dict (dict): e.g.: {(QuantumRegister(3, 'qr'), ...
decides which one is physical/ virtual based on the type. Returns ( virtual physical )
def order_based_on_type(value1, value2): """decides which one is physical/virtual based on the type. Returns (virtual, physical)""" if isinstance(value1, int) and Layout.is_virtual(value2): physical = value1 virtual = value2 elif isinstance(value2, int) and Layout.is_virt...
Checks if value has the format of a virtual qubit
def is_virtual(value): """Checks if value has the format of a virtual qubit """ return value is None or isinstance(value, tuple) and len(value) == 2 and isinstance( value[0], Register) and isinstance(value[1], int)
Returns a copy of a Layout instance.
def copy(self): """Returns a copy of a Layout instance.""" layout_copy = type(self)() layout_copy._p2v = self._p2v.copy() layout_copy._v2p = self._v2p.copy() return layout_copy
Adds a map element between bit and physical_bit. If physical_bit is not defined bit will be mapped to a new physical bit ( extending the length of the layout by one. ) Args: virtual_bit ( tuple ): A ( qu ) bit. For example ( QuantumRegister ( 3 qr ) 2 ). physical_bit ( int ): A physical bit. For example 3.
def add(self, virtual_bit, physical_bit=None): """ Adds a map element between `bit` and `physical_bit`. If `physical_bit` is not defined, `bit` will be mapped to a new physical bit (extending the length of the layout by one.) Args: virtual_bit (tuple): A (qu)bit. For ...
Swaps the map between left and right. Args: left ( tuple or int ): Item to swap with right. right ( tuple or int ): Item to swap with left. Raises: LayoutError: If left and right have not the same type.
def swap(self, left, right): """Swaps the map between left and right. Args: left (tuple or int): Item to swap with right. right (tuple or int): Item to swap with left. Raises: LayoutError: If left and right have not the same type. """ if type(l...
Combines self and another_layout into an edge map.
def combine_into_edge_map(self, another_layout): """Combines self and another_layout into an "edge map". For example:: self another_layout resulting edge map qr_1 -> 0 0 <- q_2 qr_1 -> q_2 qr_2 -> 2 2 <- q_1 qr_2 -> q_1 ...
Creates a trivial ( one - to - one ) Layout with the registers in regs. Args: * regs ( Registers ): registers to include in the layout. Returns: Layout: A layout with all the regs in the given order.
def generate_trivial_layout(*regs): """ Creates a trivial ("one-to-one") Layout with the registers in `regs`. Args: *regs (Registers): registers to include in the layout. Returns: Layout: A layout with all the `regs` in the given order. """ layout ...
Converts a list of integers to a Layout mapping virtual qubits ( index of the list ) to physical qubits ( the list values ).
def from_intlist(int_list, *qregs): """Converts a list of integers to a Layout mapping virtual qubits (index of the list) to physical qubits (the list values). Args: int_list (list): A list of integers. *qregs (QuantumRegisters): The quantum registers to apply ...
Populates a Layout from a list containing virtual qubits --- ( QuantumRegister int ) tuples --- or None.
def from_tuplelist(tuple_list): """ Populates a Layout from a list containing virtual qubits---(QuantumRegister, int) tuples---, or None. Args: tuple_list (list): e.g.: [qr[0], None, qr[2], qr[3]] Returns: Layout: the corresponding Layout ...
Apply Toffoli to from ctl1 and ctl2 to tgt.
def ccx(self, ctl1, ctl2, tgt): """Apply Toffoli to from ctl1 and ctl2 to tgt.""" return self.append(ToffoliGate(), [ctl1, ctl2, tgt], [])
gate ccx a b c { h c ; cx b c ; tdg c ; cx a c ; t c ; cx b c ; tdg c ; cx a c ; t b ; t c ; h c ; cx a b ; t a ; tdg b ; cx a b ; }
def _define(self): """ gate ccx a,b,c { h c; cx b,c; tdg c; cx a,c; t c; cx b,c; tdg c; cx a,c; t b; t c; h c; cx a,b; t a; tdg b; cx a,b;} """ definition = [] q = QuantumRegister(3, "q") rule = [ (HGate(), [q[2]], []), ...
collect blocks of adjacent gates acting on a pair of cx qubits.
def run(self, dag): """collect blocks of adjacent gates acting on a pair of "cx" qubits. The blocks contain "op" nodes in topological sort order such that all gates in a block act on the same pair of qubits and are adjacent in the circuit. the blocks are built by examining prede...
Apply u2 to q.
def u2(self, phi, lam, q): """Apply u2 to q.""" return self.append(U2Gate(phi, lam), [q], [])
Return a Numpy. array for the U3 gate.
def to_matrix(self): """Return a Numpy.array for the U3 gate.""" isqrt2 = 1 / numpy.sqrt(2) phi, lam = self.params phi, lam = float(phi), float(lam) return numpy.array([[isqrt2, -numpy.exp(1j * lam) * isqrt2], [ numpy.ex...
Return a new schedule with schedule inserted within self at start_time.
def insert(self, start_time: int, schedule: ScheduleComponent) -> 'ScheduleComponent': """Return a new schedule with `schedule` inserted within `self` at `start_time`. Args: start_time: time to be inserted schedule: schedule to be inserted """ return ops.insert(s...
Checks if the attribute name is in the list of attributes to protect. If so raises TranspilerAccessError.
def _check_if_fenced(self, name): """ Checks if the attribute name is in the list of attributes to protect. If so, raises TranspilerAccessError. Args: name (string): the attribute name to check Raises: TranspilerAccessError: when name is the list of attr...
Return True if completely - positive trace - preserving.
def is_cptp(self, atol=None, rtol=None): """Return True if completely-positive trace-preserving.""" if atol is None: atol = self._atol if rtol is None: rtol = self._rtol if self._data[1] is not None: return False check = np.dot(np.transpose(np....
Return the conjugate of the QuantumChannel.
def conjugate(self): """Return the conjugate of the QuantumChannel.""" # pylint: disable=assignment-from-no-return stine_l = np.conjugate(self._data[0]) stine_r = None if self._data[1] is not None: stine_r = np.conjugate(self._data[1]) return Stinespring((stin...
Return the transpose of the QuantumChannel.
def transpose(self): """Return the transpose of the QuantumChannel.""" din, dout = self.dim dtr = self._data[0].shape[0] // dout stine = [None, None] for i, mat in enumerate(self._data): if mat is not None: stine[i] = np.reshape( np...
Return the composition channel self∘other.
def compose(self, other, qargs=None, front=False): """Return the composition channel self∘other. Args: other (QuantumChannel): a quantum channel subclass. qargs (list): a list of subsystem positions to compose other on. front (bool): If False compose in standard orde...
The matrix power of the channel.
def power(self, n): """The matrix power of the channel. Args: n (int): compute the matrix power of the superoperator matrix. Returns: Stinespring: the matrix power of the SuperOp converted to a Stinespring channel. Raises: QiskitError: i...
Return the QuantumChannel self + other.
def multiply(self, other): """Return the QuantumChannel self + other. Args: other (complex): a complex number. Returns: Stinespring: the scalar multiplication other * self as a Stinespring object. Raises: QiskitError: if other is not a v...
Evolve a quantum state by the QuantumChannel.
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. Retu...
Return the tensor product channel.
def _tensor_product(self, other, reverse=False): """Return the tensor product channel. Args: other (QuantumChannel): a quantum channel subclass. reverse (bool): If False return self ⊗ other, if True return if True return (other ⊗ self) [Default: False...
Runs the BasicSwap pass on dag. Args: dag ( DAGCircuit ): DAG to map.
def run(self, dag): """ Runs the BasicSwap pass on `dag`. Args: dag (DAGCircuit): DAG to map. Returns: DAGCircuit: A mapped DAG. Raises: TranspilerError: if the coupling map or the layout are not compatible with the DAG ""...
Find a swap circuit that implements a permutation for this layer.
def _layer_permutation(layer_partition, initial_layout, layout, qubit_subset, coupling, trials, qregs, rng): """Find a swap circuit that implements a permutation for this layer. Args: layer_partition (list): The layer_partition is a list of (qu)bit lists and each qubi...
Takes ( QuantumRegister int ) tuples and converts them into an integer array.
def regtuple_to_numeric(items, qregs): """Takes (QuantumRegister, int) tuples and converts them into an integer array. Args: items (list): List of tuples of (QuantumRegister, int) to convert. qregs (dict): List of )QuantumRegister, int) tuples. Returns: nda...
Converts gate tuples into a nested list of integers.
def gates_to_idx(gates, qregs): """Converts gate tuples into a nested list of integers. Args: gates (list): List of (QuantumRegister, int) pairs representing gates. qregs (dict): List of )QuantumRegister, int) tuples. Returns: list: Nested list of integers for...
Run the StochasticSwap pass on dag.
def run(self, dag): """ Run the StochasticSwap pass on `dag`. Args: dag (DAGCircuit): DAG to map. Returns: DAGCircuit: A mapped DAG. Raises: TranspilerError: if the coupling map or the layout are not compatible with the DAG ...
Find a swap circuit that implements a permutation for this layer.
def _layer_permutation(self, layer_partition, layout, qubit_subset, coupling, trials): """Find a swap circuit that implements a permutation for this layer. The goal is to swap qubits such that qubits in the same two-qubit gates are adjacent. Based on S. Bravy...
Provide a DAGCircuit for a new mapped layer.
def _layer_update(self, i, first_layer, best_layout, best_depth, best_circuit, layer_list): """Provide a DAGCircuit for a new mapped layer. i (int) = layer number first_layer (bool) = True if this is the first layer in the circuit with any multi-qubit gates ...
Map a DAGCircuit onto a CouplingMap using swap gates.
def _mapper(self, circuit_graph, coupling_graph, trials=20): """Map a DAGCircuit onto a CouplingMap using swap gates. Use self.initial_layout for the initial layout. Args: circuit_graph (DAGCircuit): input DAG circuit coupling_graph (CouplingMap): coupli...
Return the Pauli group with 4^n elements.
def pauli_group(number_of_qubits, case='weight'): """Return the Pauli group with 4^n elements. The phases have been removed. case 'weight' is ordered by Pauli weights and case 'tensor' is ordered by I,X,Y,Z counting lowest qubit fastest. Args: number_of_qubits (int): number of qubits ...
r Take pauli string to construct pauli.
def from_label(cls, label): r"""Take pauli string to construct pauli. The qubit index of pauli label is q_{n-1} ... q_0. E.g., a pauli is $P_{n-1} \otimes ... \otimes P_0$ Args: label (str): pauli label Returns: Pauli: the constructed pauli Rai...
Construct pauli from boolean array.
def _init_from_bool(self, z, x): """Construct pauli from boolean array. Args: z (numpy.ndarray): boolean, z vector x (numpy.ndarray): boolean, x vector Returns: Pauli: self Raises: QiskitError: if z or x are None or the length of z and x...
r Multiply two Paulis and track the phase.
def sgn_prod(p1, p2): r""" Multiply two Paulis and track the phase. $P_3 = P_1 \otimes P_2$: X*Y Args: p1 (Pauli): pauli 1 p2 (Pauli): pauli 2 Returns: Pauli: the multiplied pauli complex: the sign of the multiplication, 1, -1, 1...
r Convert Pauli to a sparse matrix representation ( CSR format ).
def to_spmatrix(self): r""" Convert Pauli to a sparse matrix representation (CSR format). Order is q_{n-1} .... q_0, i.e., $P_{n-1} \otimes ... P_0$ Returns: scipy.sparse.csr_matrix: a sparse matrix with CSR format that represnets the pauli. """ ...
Convert to Operator object.
def to_operator(self): """Convert to Operator object.""" # Place import here to avoid cyclic import from circuit visualization from qiskit.quantum_info.operators.operator import Operator return Operator(self.to_matrix())
Convert to Pauli circuit instruction.
def to_instruction(self): """Convert to Pauli circuit instruction.""" from qiskit.circuit import QuantumCircuit, QuantumRegister from qiskit.extensions.standard import IdGate, XGate, YGate, ZGate gates = {'I': IdGate(), 'X': XGate(), 'Y': YGate(), 'Z': ZGate()} label = self.to_la...
Update partial or entire z.
def update_z(self, z, indices=None): """ Update partial or entire z. Args: z (numpy.ndarray or list): to-be-updated z indices (numpy.ndarray or list or optional): to-be-updated qubit indices Returns: Pauli: self Raises: QiskitErr...
Update partial or entire x.
def update_x(self, x, indices=None): """ Update partial or entire x. Args: x (numpy.ndarray or list): to-be-updated x indices (numpy.ndarray or list or optional): to-be-updated qubit indices Returns: Pauli: self Raises: QiskitErr...
Insert or append pauli to the targeted indices.
def insert_paulis(self, indices=None, paulis=None, pauli_labels=None): """ Insert or append pauli to the targeted indices. If indices is None, it means append at the end. Args: indices (list[int]): the qubit indices to be inserted paulis (Pauli): the to-be-inser...
Append pauli at the end.
def append_paulis(self, paulis=None, pauli_labels=None): """ Append pauli at the end. Args: paulis (Pauli): the to-be-inserted or appended pauli pauli_labels (list[str]): the to-be-inserted or appended pauli label Returns: Pauli: self """ ...
Delete pauli at the indices.
def delete_qubits(self, indices): """ Delete pauli at the indices. Args: indices(list[int]): the indices of to-be-deleted paulis Returns: Pauli: self """ if not isinstance(indices, list): indices = [indices] self._z = np.dele...
Return a random Pauli on number of qubits.
def random(cls, num_qubits, seed=None): """Return a random Pauli on number of qubits. Args: num_qubits (int): the number of qubits seed (int): Optional. To set a random seed. Returns: Pauli: the random pauli """ if seed is not None: ...
Generate single qubit pauli at index with pauli_label with length num_qubits.
def pauli_single(cls, num_qubits, index, pauli_label): """ Generate single qubit pauli at index with pauli_label with length num_qubits. Args: num_qubits (int): the length of pauli index (int): the qubit index to insert the single qubii pauli_label (str): pau...
Apply an arbitrary 1 - qubit unitary matrix.
def _add_unitary_single(self, gate, qubit): """Apply an arbitrary 1-qubit unitary matrix. Args: gate (matrix_like): a single qubit gate matrix qubit (int): the qubit to apply gate to """ # Compute einsum index string for 1-qubit matrix multiplication inde...
Apply a two - qubit unitary matrix.
def _add_unitary_two(self, gate, qubit0, qubit1): """Apply a two-qubit unitary matrix. Args: gate (matrix_like): a the two-qubit gate matrix qubit0 (int): gate qubit-0 qubit1 (int): gate qubit-1 """ # Compute einsum index string for 1-qubit matrix mul...
Simulate the outcome of measurement of a qubit.
def _get_measure_outcome(self, qubit): """Simulate the outcome of measurement of a qubit. Args: qubit (int): the qubit to measure Return: tuple: pair (outcome, probability) where outcome is '0' or '1' and probability is the probability of the returned outcom...
Generate memory samples from current statevector.
def _add_sample_measure(self, measure_params, num_samples): """Generate memory samples from current statevector. Args: measure_params (list): List of (qubit, cmembit) values for measure instructions to sample. num_samples (int): The number of m...
Apply a measure instruction to a qubit.
def _add_qasm_measure(self, qubit, cmembit, cregbit=None): """Apply a measure instruction to a qubit. Args: qubit (int): qubit is the qubit measured. cmembit (int): is the classical memory bit to store outcome in. cregbit (int, optional): is the classical register bi...