_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q268300
CouplingMap.add_edge
test
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: ...
python
{ "resource": "" }
q268301
CouplingMap.subgraph
test
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...
python
{ "resource": "" }
q268302
CouplingMap.physical_qubits
test
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
python
{ "resource": "" }
q268303
CouplingMap.is_connected
test
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
python
{ "resource": "" }
q268304
CouplingMap._compute_distance_matrix
test
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...
python
{ "resource": "" }
q268305
CouplingMap.distance
test
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...
python
{ "resource": "" }
q268306
transpile
test
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...
python
{ "resource": "" }
q268307
cu1
test
def cu1(self, theta, ctl, tgt): """Apply cu1 from ctl to tgt with angle theta.""" return self.append(Cu1Gate(theta), [ctl, tgt], [])
python
{ "resource": "" }
q268308
InstructionSet.inverse
test
def inverse(self): """Invert all instructions.""" for index, instruction in enumerate(self.instructions): self.instructions[index] = instruction.inverse() return self
python
{ "resource": "" }
q268309
InstructionSet.q_if
test
def q_if(self, *qregs): """Add controls to all instructions.""" for gate in self.instructions: gate.q_if(*qregs) return self
python
{ "resource": "" }
q268310
InstructionSet.c_if
test
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
python
{ "resource": "" }
q268311
_Broker.subscribe
test
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>....
python
{ "resource": "" }
q268312
_Broker.dispatch
test
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...
python
{ "resource": "" }
q268313
_Broker.unsubscribe
test
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...
python
{ "resource": "" }
q268314
Publisher.publish
test
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)
python
{ "resource": "" }
q268315
initialize
test
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)
python
{ "resource": "" }
q268316
Initialize._define
test
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...
python
{ "resource": "" }
q268317
Initialize.gates_to_uncompute
test
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...
python
{ "resource": "" }
q268318
Initialize._bloch_angles
test
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...
python
{ "resource": "" }
q268319
Initialize._multiplex
test
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". ...
python
{ "resource": "" }
q268320
Layout.is_virtual
test
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)
python
{ "resource": "" }
q268321
Layout.copy
test
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
python
{ "resource": "" }
q268322
Layout.combine_into_edge_map
test
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 ...
python
{ "resource": "" }
q268323
ccx
test
def ccx(self, ctl1, ctl2, tgt): """Apply Toffoli to from ctl1 and ctl2 to tgt.""" return self.append(ToffoliGate(), [ctl1, ctl2, tgt], [])
python
{ "resource": "" }
q268324
Instruction.insert
test
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...
python
{ "resource": "" }
q268325
FencedObject._check_if_fenced
test
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...
python
{ "resource": "" }
q268326
gates_to_idx
test
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...
python
{ "resource": "" }
q268327
StochasticSwap.run
test
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 ...
python
{ "resource": "" }
q268328
StochasticSwap._layer_update
test
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 ...
python
{ "resource": "" }
q268329
pauli_group
test
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 ...
python
{ "resource": "" }
q268330
Pauli.from_label
test
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...
python
{ "resource": "" }
q268331
Pauli._init_from_bool
test
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...
python
{ "resource": "" }
q268332
Pauli.sgn_prod
test
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...
python
{ "resource": "" }
q268333
Pauli.to_operator
test
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())
python
{ "resource": "" }
q268334
Pauli.to_instruction
test
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...
python
{ "resource": "" }
q268335
Pauli.update_z
test
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...
python
{ "resource": "" }
q268336
Pauli.update_x
test
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...
python
{ "resource": "" }
q268337
Pauli.insert_paulis
test
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...
python
{ "resource": "" }
q268338
Pauli.append_paulis
test
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 """ ...
python
{ "resource": "" }
q268339
Pauli.delete_qubits
test
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...
python
{ "resource": "" }
q268340
Pauli.random
test
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: ...
python
{ "resource": "" }
q268341
Pauli.pauli_single
test
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...
python
{ "resource": "" }
q268342
QasmSimulatorPy._get_measure_outcome
test
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...
python
{ "resource": "" }
q268343
QasmSimulatorPy._add_sample_measure
test
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...
python
{ "resource": "" }
q268344
QasmSimulatorPy._add_qasm_measure
test
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...
python
{ "resource": "" }
q268345
QasmSimulatorPy._add_qasm_reset
test
def _add_qasm_reset(self, qubit): """Apply a reset instruction to a qubit. Args: qubit (int): the qubit being rest This is done by doing a simulating a measurement outcome and projecting onto the outcome state while renormalizing. """ # get measure o...
python
{ "resource": "" }
q268346
QasmSimulatorPy._validate_initial_statevector
test
def _validate_initial_statevector(self): """Validate an initial statevector""" # If initial statevector isn't set we don't need to validate if self._initial_statevector is None: return # Check statevector is correct length for number of qubits length = len(self._initi...
python
{ "resource": "" }
q268347
QasmSimulatorPy._initialize_statevector
test
def _initialize_statevector(self): """Set the initial statevector for simulation""" if self._initial_statevector is None: # Set to default state of all qubits in |0> self._statevector = np.zeros(2 ** self._number_of_qubits, dtype=complex) ...
python
{ "resource": "" }
q268348
QasmSimulatorPy._get_statevector
test
def _get_statevector(self): """Return the current statevector in JSON Result spec format""" vec = np.reshape(self._statevector, 2 ** self._number_of_qubits) # Expand complex numbers vec = np.stack([vec.real, vec.imag], axis=1) # Truncate small values vec[abs(vec) < self._...
python
{ "resource": "" }
q268349
QasmSimulatorPy._validate_measure_sampling
test
def _validate_measure_sampling(self, experiment): """Determine if measure sampling is allowed for an experiment Args: experiment (QobjExperiment): a qobj experiment. """ # If shots=1 we should disable measure sampling. # This is also required for statevector simulato...
python
{ "resource": "" }
q268350
QasmSimulatorPy.run
test
def run(self, qobj, backend_options=None): """Run qobj asynchronously. Args: qobj (Qobj): payload of the experiment backend_options (dict): backend options Returns: BasicAerJob: derived from BaseJob Additional Information: backend_option...
python
{ "resource": "" }
q268351
QasmSimulatorPy._run_job
test
def _run_job(self, job_id, qobj): """Run experiments in qobj Args: job_id (str): unique id for the job. qobj (Qobj): job description Returns: Result: Result object """ self._validate(qobj) result_list = [] self._shots = qobj.c...
python
{ "resource": "" }
q268352
QasmSimulatorPy._validate
test
def _validate(self, qobj): """Semantic validations of the qobj which cannot be done via schemas.""" n_qubits = qobj.config.n_qubits max_qubits = self.configuration().n_qubits if n_qubits > max_qubits: raise BasicAerError('Number of qubits {} '.format(n_qubits) + ...
python
{ "resource": "" }
q268353
UnitarySimulatorPy._validate_initial_unitary
test
def _validate_initial_unitary(self): """Validate an initial unitary matrix""" # If initial unitary isn't set we don't need to validate if self._initial_unitary is None: return # Check unitary is correct length for number of qubits shape = np.shape(self._initial_unitar...
python
{ "resource": "" }
q268354
UnitarySimulatorPy._initialize_unitary
test
def _initialize_unitary(self): """Set the initial unitary for simulation""" self._validate_initial_unitary() if self._initial_unitary is None: # Set to identity matrix self._unitary = np.eye(2 ** self._number_of_qubits, dtype=complex) ...
python
{ "resource": "" }
q268355
UnitarySimulatorPy._get_unitary
test
def _get_unitary(self): """Return the current unitary in JSON Result spec format""" unitary = np.reshape(self._unitary, 2 * [2 ** self._number_of_qubits]) # Expand complex numbers unitary = np.stack((unitary.real, unitary.imag), axis=-1) # Truncate small values unitary[ab...
python
{ "resource": "" }
q268356
UnitarySimulatorPy._run_job
test
def _run_job(self, job_id, qobj): """Run experiments in qobj. Args: job_id (str): unique id for the job. qobj (Qobj): job description Returns: Result: Result object """ self._validate(qobj) result_list = [] start = time.time()...
python
{ "resource": "" }
q268357
UnitarySimulatorPy._validate
test
def _validate(self, qobj): """Semantic validations of the qobj which cannot be done via schemas. Some of these may later move to backend schemas. 1. No shots 2. No measurements in the middle """ n_qubits = qobj.config.n_qubits max_qubits = self.configuration().n_q...
python
{ "resource": "" }
q268358
_is_bit
test
def _is_bit(obj): """Determine if obj is a bit""" # If there is a bit type this could be replaced by isinstance. if isinstance(obj, tuple) and len(obj) == 2: if isinstance(obj[0], Register) and isinstance(obj[1], int) and obj[1] < len(obj[0]): return True return False
python
{ "resource": "" }
q268359
TrivialLayout.run
test
def run(self, dag): """ Pick a layout by assigning n circuit qubits to device qubits 0, .., n-1. Args: dag (DAGCircuit): DAG to find layout for. Raises: TranspilerError: if dag wider than self.coupling_map """ num_dag_qubits = sum([qreg.size for ...
python
{ "resource": "" }
q268360
Interval.has_overlap
test
def has_overlap(self, interval: 'Interval') -> bool: """Check if self has overlap with `interval`. Args: interval: interval to be examined Returns: bool: True if self has overlap with `interval` otherwise False """ if self.begin < interval.end and interv...
python
{ "resource": "" }
q268361
Interval.shift
test
def shift(self, time: int) -> 'Interval': """Return a new interval shifted by `time` from self Args: time: time to be shifted Returns: Interval: interval shifted by `time` """ return Interval(self._begin + time, self._end + time)
python
{ "resource": "" }
q268362
Timeslot.shift
test
def shift(self, time: int) -> 'Timeslot': """Return a new Timeslot shifted by `time`. Args: time: time to be shifted """ return Timeslot(self.interval.shift(time), self.channel)
python
{ "resource": "" }
q268363
TimeslotCollection.ch_start_time
test
def ch_start_time(self, *channels: List[Channel]) -> int: """Return earliest start time in this collection. Args: *channels: Channels over which to obtain start_time. """ intervals = list(itertools.chain(*(self._table[chan] for chan in channels ...
python
{ "resource": "" }
q268364
TimeslotCollection.ch_stop_time
test
def ch_stop_time(self, *channels: List[Channel]) -> int: """Return maximum time of timeslots over all channels. Args: *channels: Channels over which to obtain stop time. """ intervals = list(itertools.chain(*(self._table[chan] for chan in channels ...
python
{ "resource": "" }
q268365
TimeslotCollection.is_mergeable_with
test
def is_mergeable_with(self, timeslots: 'TimeslotCollection') -> bool: """Return if self is mergeable with `timeslots`. Args: timeslots: TimeslotCollection to be checked """ for slot in timeslots.timeslots: for interval in self._table[slot.channel]: ...
python
{ "resource": "" }
q268366
TimeslotCollection.merged
test
def merged(self, timeslots: 'TimeslotCollection') -> 'TimeslotCollection': """Return a new TimeslotCollection merged with a specified `timeslots` Args: timeslots: TimeslotCollection to be merged """ slots = [Timeslot(slot.interval, slot.channel) for slot in self.timeslots] ...
python
{ "resource": "" }
q268367
TimeslotCollection.shift
test
def shift(self, time: int) -> 'TimeslotCollection': """Return a new TimeslotCollection shifted by `time`. Args: time: time to be shifted by """ slots = [Timeslot(slot.interval.shift(time), slot.channel) for slot in self.timeslots] return TimeslotCollection(*slots)
python
{ "resource": "" }
q268368
CIFailureReporter.report
test
def report(self, branch, commit, infourl=None): """Report on GitHub that the specified branch is failing to build at the specified commit. The method will open an issue indicating that the branch is failing. If there is an issue already open, it will add a comment avoiding to report twic...
python
{ "resource": "" }
q268369
process_data
test
def process_data(rho): """ Sort rho data """ result = dict() num = int(np.log2(len(rho))) labels = list(map(lambda x: x.to_label(), pauli_group(num))) values = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))), pauli_group(num))) for position, label in enum...
python
{ "resource": "" }
q268370
iplot_state_paulivec
test
def iplot_state_paulivec(rho, figsize=None, slider=False, show_legend=False): """ Create a paulivec representation. Graphical representation of the input array. Args: rho (array): State vector or density matrix. figsize (tuple): Figure size in pixels. slider (bo...
python
{ "resource": "" }
q268371
rzz
test
def rzz(self, theta, qubit1, qubit2): """Apply RZZ to circuit.""" return self.append(RZZGate(theta), [qubit1, qubit2], [])
python
{ "resource": "" }
q268372
cswap
test
def cswap(self, ctl, tgt1, tgt2): """Apply Fredkin to circuit.""" return self.append(FredkinGate(), [ctl, tgt1, tgt2], [])
python
{ "resource": "" }
q268373
NoiseAdaptiveLayout._initialize_backend_prop
test
def _initialize_backend_prop(self): """ Extract readout and CNOT errors and compute swap costs. """ backend_prop = self.backend_prop for ginfo in backend_prop.gates: if ginfo.gate == 'cx': for item in ginfo.parameters: if item.name ...
python
{ "resource": "" }
q268374
NoiseAdaptiveLayout._create_program_graph
test
def _create_program_graph(self, dag): """ Program graph has virtual qubits as nodes. Two nodes have an edge if the corresponding virtual qubits participate in a 2-qubit gate. The edge is weighted by the number of CNOTs between the pair. """ idx = 0 for q i...
python
{ "resource": "" }
q268375
NoiseAdaptiveLayout._select_next_edge
test
def _select_next_edge(self): """ If there is an edge with one endpoint mapped, return it. Else return in the first edge """ for edge in self.pending_program_edges: q1_mapped = edge[0] in self.prog2hw q2_mapped = edge[1] in self.prog2hw assert n...
python
{ "resource": "" }
q268376
NoiseAdaptiveLayout._select_best_remaining_cx
test
def _select_best_remaining_cx(self): """ Select best remaining CNOT in the hardware for the next program edge. """ candidates = [] for gate in self.gate_list: chk1 = gate[0] in self.available_hw_qubits chk2 = gate[1] in self.available_hw_qubits ...
python
{ "resource": "" }
q268377
NoiseAdaptiveLayout._select_best_remaining_qubit
test
def _select_best_remaining_qubit(self, prog_qubit): """ Select the best remaining hardware qubit for the next program qubit. """ reliab_store = {} for hw_qubit in self.available_hw_qubits: reliab = 1 for n in self.prog_graph.neighbors(prog_qubit): ...
python
{ "resource": "" }
q268378
NoiseAdaptiveLayout.run
test
def run(self, dag): """Main run method for the noise adaptive layout.""" self._initialize_backend_prop() num_qubits = self._create_program_graph(dag) if num_qubits > len(self.swap_graph): raise TranspilerError('Number of qubits greater than device.') for end1, end2, _...
python
{ "resource": "" }
q268379
CompositeGate.instruction_list
test
def instruction_list(self): """Return a list of instructions for this CompositeGate. If the CompositeGate itself contains composites, call this method recursively. """ instruction_list = [] for instruction in self.data: if isinstance(instruction, CompositeGat...
python
{ "resource": "" }
q268380
CompositeGate.inverse
test
def inverse(self): """Invert this gate.""" self.data = [gate.inverse() for gate in reversed(self.data)] self.inverse_flag = not self.inverse_flag return self
python
{ "resource": "" }
q268381
CompositeGate.q_if
test
def q_if(self, *qregs): """Add controls to this gate.""" self.data = [gate.q_if(qregs) for gate in self.data] return self
python
{ "resource": "" }
q268382
CompositeGate.c_if
test
def c_if(self, classical, val): """Add classical control register.""" self.data = [gate.c_if(classical, val) for gate in self.data] return self
python
{ "resource": "" }
q268383
Operator.is_unitary
test
def is_unitary(self, atol=None, rtol=None): """Return True if operator is a unitary matrix.""" if atol is None: atol = self._atol if rtol is None: rtol = self._rtol return is_unitary_matrix(self._data, rtol=rtol, atol=atol)
python
{ "resource": "" }
q268384
Operator.conjugate
test
def conjugate(self): """Return the conjugate of the operator.""" return Operator( np.conj(self.data), self.input_dims(), self.output_dims())
python
{ "resource": "" }
q268385
Operator.transpose
test
def transpose(self): """Return the transpose of the operator.""" return Operator( np.transpose(self.data), self.input_dims(), self.output_dims())
python
{ "resource": "" }
q268386
Operator.power
test
def power(self, n): """Return the matrix power of the operator. Args: n (int): the power to raise the matrix to. Returns: BaseOperator: the n-times composed operator. Raises: QiskitError: if the input and output dimensions of the operator ...
python
{ "resource": "" }
q268387
Operator._shape
test
def _shape(self): """Return the tensor shape of the matrix operator""" return tuple(reversed(self.output_dims())) + tuple( reversed(self.input_dims()))
python
{ "resource": "" }
q268388
Operator._instruction_to_operator
test
def _instruction_to_operator(cls, instruction): """Convert a QuantumCircuit or Instruction to an Operator.""" # Convert circuit to an instruction if isinstance(instruction, QuantumCircuit): instruction = instruction.to_instruction() # Initialize an identity operator of the co...
python
{ "resource": "" }
q268389
LegacySwap.swap_mapper_layer_update
test
def swap_mapper_layer_update(self, i, first_layer, best_layout, best_d, best_circ, layer_list): """Update the QASM string for an iteration of swap_mapper. i = layer number first_layer = True if this is the first layer with multi-qubit gates best_layout =...
python
{ "resource": "" }
q268390
_separate_bitstring
test
def _separate_bitstring(bitstring, creg_sizes): """Separate a bitstring according to the registers defined in the result header.""" substrings = [] running_index = 0 for _, size in reversed(creg_sizes): substrings.append(bitstring[running_index: running_index + size]) running_index += si...
python
{ "resource": "" }
q268391
format_level_0_memory
test
def format_level_0_memory(memory): """ Format an experiment result memory object for measurement level 0. Args: memory (list): Memory from experiment with `meas_level==1`. `avg` or `single` will be inferred from shape of result memory. Returns: np.ndarray: Measurement level 0 c...
python
{ "resource": "" }
q268392
format_level_1_memory
test
def format_level_1_memory(memory): """ Format an experiment result memory object for measurement level 1. Args: memory (list): Memory from experiment with `meas_level==1`. `avg` or `single` will be inferred from shape of result memory. Returns: np.ndarray: Measurement level 1 c...
python
{ "resource": "" }
q268393
format_level_2_memory
test
def format_level_2_memory(memory, header=None): """ Format an experiment result memory object for measurement level 2. Args: memory (list): Memory from experiment with `meas_level==2` and `memory==True`. header (dict): the experiment header dictionary containing useful information f...
python
{ "resource": "" }
q268394
format_counts
test
def format_counts(counts, header=None): """Format a single experiment result coming from backend to present to the Qiskit user. Args: counts (dict): counts histogram of multiple shots header (dict): the experiment header dictionary containing useful information for postprocessin...
python
{ "resource": "" }
q268395
format_statevector
test
def format_statevector(vec, decimals=None): """Format statevector coming from the backend to present to the Qiskit user. Args: vec (list): a list of [re, im] complex numbers. decimals (int): the number of decimals in the statevector. If None, no rounding is done. Returns: ...
python
{ "resource": "" }
q268396
format_unitary
test
def format_unitary(mat, decimals=None): """Format unitary coming from the backend to present to the Qiskit user. Args: mat (list[list]): a list of list of [re, im] complex numbers decimals (int): the number of decimals in the statevector. If None, no rounding is done. Returns: ...
python
{ "resource": "" }
q268397
requires_submit
test
def requires_submit(func): """ Decorator to ensure that a submit has been performed before calling the method. Args: func (callable): test function to be decorated. Returns: callable: the decorated function. """ @functools.wraps(func) def _wrapper(self, *args, **kwargs)...
python
{ "resource": "" }
q268398
BasicAerJob.submit
test
def submit(self): """Submit the job to the backend for execution. Raises: QobjValidationError: if the JSON serialization of the Qobj passed during construction does not validate against the Qobj schema. JobError: if trying to re-submit the job. """ i...
python
{ "resource": "" }
q268399
BasicAerJob.status
test
def status(self): """Gets the status of the job by querying the Python's future Returns: qiskit.providers.JobStatus: The current JobStatus Raises: JobError: If the future is in unexpected state concurrent.futures.TimeoutError: if timeout occurred. ""...
python
{ "resource": "" }