_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | 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)
| 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() | python | {
"resource": ""
} |
q268302 | CouplingMap.physical_qubits | test | def physical_qubits(self):
"""Returns a sorted list of physical_qubits"""
if 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 | 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 connected")
lengths = nx.all_pairs_shortest_path_length(self.graph.to_undirected(as_view=True))
lengths = dict(lengths)
size = len(lengths) | 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 distance
Raises:
CouplingError: if the qubits do not exist in the CouplingMap
"""
if physical_qubit1 not in self.physical_qubits:
raise CouplingError("%s not in coupling graph" % (physical_qubit1,))
if | 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 compile for
basis_gates (list[str]): list of basis gate names supported by the
target. Default: ['u1','u2','u3','cx','id']
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (Layout or dict or list):
Initial position of virtual qubits on physical qubits. The final
| python | {
"resource": ""
} |
q268307 | cu1 | test | def cu1(self, theta, ctl, tgt):
"""Apply cu1 from ctl to tgt with angle theta."""
| python | {
"resource": ""
} |
q268308 | InstructionSet.inverse | test | def inverse(self):
"""Invert all instructions."""
for index, instruction in enumerate(self.instructions):
| python | {
"resource": ""
} |
q268309 | InstructionSet.q_if | test | def q_if(self, *qregs):
"""Add controls to all instructions."""
for | python | {
"resource": ""
} |
q268310 | InstructionSet.c_if | test | def c_if(self, classical, val):
"""Add classical control register to all instructions."""
| 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>.<method>.<action>"
callback (callable): The callback that will be executed when an event is
emitted.
"""
if not callable(callback):
| 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
"""
| 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 the event
| 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 | python | {
"resource": ""
} |
q268315 | initialize | test | def initialize(self, params, qubits):
"""Apply initialize to circuit."""
if isinstance(qubits, QuantumRegister):
qubits = qubits[:]
else:
| 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 implements some extra optimizations: remove zero rotations and
double cnots.
"""
# call to generate the circuit that takes the desired vector to zero
disentangling_circuit = self.gates_to_uncompute()
# invert the circuit to create the desired vector from zero (assuming
# the qubits are in the zero state)
initialize_instr = | 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, name='disentangler')
# kick start the peeling loop, and disentangle one-by-one from LSB to MSB
remaining_param = self.params
for i in range(self.num_qubits):
# work out which rotations must be done to disentangle the LSB
# qubit (we peel away one qubit at a time)
(remaining_param,
thetas, | 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 = complex(a_complex)
b_complex = complex(b_complex)
mag_a = np.absolute(a_complex)
final_r = float(np.sqrt(mag_a ** 2 + np.absolute(b_complex) ** 2))
if final_r < _EPS:
theta = 0
phi = 0
| 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".
Args:
target_gate (Gate): Ry or Rz gate to apply to target qubit, multiplexed
over all other "select" qubits
list_of_angles (list[float]): list of rotation angles to apply Ry and Rz
Returns:
DAGCircuit: the circuit implementing the multiplexor's action
"""
list_len = len(list_of_angles)
local_num_qubits = int(math.log2(list_len)) + 1
q = QuantumRegister(local_num_qubits)
circuit = QuantumCircuit(q, name="multiplex" + local_num_qubits.__str__())
lsb = q[0]
msb = q[local_num_qubits - 1]
# case of no multiplexing: base case for recursion
if local_num_qubits == 1:
circuit.append(target_gate(list_of_angles[0]), [q[0]])
return circuit
# calc angle weights, assuming recursion (that is the lower-level
# requested angles have been correctly implemented by recursion
angle_weight = scipy.kron([[0.5, 0.5], [0.5, -0.5]],
np.identity(2 ** (local_num_qubits - 2)))
# calc the combo | 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) == | 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()
| 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
qr_3 -> 3 3 <- q_0 qr_3 -> q_0
The edge map is used to compose dags via, for example, compose_back.
Args:
another_layout (Layout): The other layout to combine.
Returns:
dict: A "edge map".
Raises:
| python | {
"resource": ""
} |
q268323 | ccx | test | def ccx(self, ctl1, ctl2, tgt):
"""Apply Toffoli to from ctl1 and ctl2 to 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
| 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 attributes to protect.
""" | 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 gates.
"""
sizes = [qr.size for qr in qregs.values()]
reg_idx = np.cumsum([0]+sizes)
regint = {}
| 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
"""
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
if len(dag.qubits()) != len(self.initial_layout):
raise TranspilerError('The layout does not match the amount of qubits in the DAG')
if len(self.coupling_map.physical_qubits) != len(self.initial_layout):
raise TranspilerError(
| 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
best_layout (Layout) = layout returned from _layer_permutation
best_depth (int) = depth returned from _layer_permutation
best_circuit (DAGCircuit) = swap circuit returned
from _layer_permutation
layer_list (list) = list of DAGCircuit objects for each layer,
output of DAGCircuit layers() method
Return a DAGCircuit object to append to the output DAGCircuit
that the _mapper method is building.
"""
layout = best_layout
logger.debug("layer_update: layout = %s", pformat(layout))
logger.debug("layer_update: self.initial_layout = %s", pformat(self.initial_layout))
dagcircuit_output = DAGCircuit()
for register in layout.get_virtual_bits().keys():
if register[0] not in | 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
case (str): determines ordering of group elements ('weight' or 'tensor')
Returns:
list: list of Pauli objects
Raises:
QiskitError: case is not 'weight' or 'tensor'
QiskitError: number_of_qubits is larger than 4
"""
if number_of_qubits < 5:
temp_set = []
if case == 'weight':
tmp = pauli_group(number_of_qubits, case='tensor')
# sort on the weight of the Pauli operator
return sorted(tmp, key=lambda x: -np.count_nonzero(
np.array(x.to_label(), 'c') == b'I'))
elif case == 'tensor':
# the Pauli set is in tensor order II IX IY IZ XI ...
for k in range(4 ** number_of_qubits):
z = np.zeros(number_of_qubits, dtype=np.bool)
x = np.zeros(number_of_qubits, dtype=np.bool)
# looping over all the qubits
| 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
Raises:
QiskitError: invalid character in the label
"""
| 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 are different.
"""
if z is None:
raise QiskitError("z vector must not be None.")
if x is None:
raise QiskitError("x vector must not be None.")
| 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
| 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
| 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_label()
n_qubits = self.numberofqubits
| 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:
QiskitError: when updating whole z, the number of qubits must be the same.
"""
z = _make_np_bool(z)
if indices is None:
if len(self._z) != len(z):
raise QiskitError("During updating whole | 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:
QiskitError: when updating whole x, the number of qubits must be the same.
"""
x = _make_np_bool(x)
if indices is None:
if len(self._x) != len(x):
raise QiskitError("During updating whole | 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-inserted or appended pauli
pauli_labels (list[str]): the to-be-inserted or appended pauli label
Note:
the indices refers to the localion of original paulis,
e.g. if indices = [0, 2], pauli_labels = ['Z', 'I'] and original pauli = 'ZYXI'
the pauli will be updated to ZY'I'XI'Z'
'Z' and 'I' are inserted before the qubit at 0 and 2.
Returns:
Pauli: self
Raises:
QiskitError: provide both `paulis` and `pauli_labels` at the same time
"""
if pauli_labels is not None:
if paulis is not None:
raise QiskitError("Please only provide either `paulis` or `pauli_labels`")
| 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 | 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
"""
| 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.
| 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 | 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 outcome.
"""
# Axis for numpy.sum to compute probabilities
axis = list(range(self._number_of_qubits))
axis.remove(self._number_of_qubits - 1 - qubit)
| 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 memory samples to generate.
Returns:
list: A list of memory values in hex format.
"""
# Get unique qubits that are actually measured
measured_qubits = list({qubit for qubit, cmembit in measure_params})
num_measured = len(measured_qubits)
# Axis for numpy.sum to compute probabilities
axis = list(range(self._number_of_qubits))
for qubit in reversed(measured_qubits):
# Remove from largest qubit to smallest so list position is correct
# with respect to position from end of the list
axis.remove(self._number_of_qubits - 1 - qubit)
probabilities = np.reshape(np.sum(np.abs(self._statevector) ** 2,
axis=tuple(axis)),
| 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 bit to store outcome in.
"""
# get measure outcome
outcome, probability = self._get_measure_outcome(qubit)
# update classical state
membit = 1 << cmembit
self._classical_memory = (self._classical_memory & (~membit)) | (int(outcome) << cmembit)
if cregbit is not None:
regbit = 1 << cregbit | 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 outcome
outcome, probability = self._get_measure_outcome(qubit)
# update quantum state
if outcome == '0':
update = [[1 / | 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._initial_statevector)
required_dim = 2 ** self._number_of_qubits
| 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)
self._statevector[0] = 1
else:
| 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
| 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 simulator to return the
# correct final statevector without silently dropping final measurements.
if self._shots <= 1:
self._sample_measure = False
return
# Check for config flag
if hasattr(experiment.config, 'allows_measure_sampling'):
self._sample_measure = experiment.config.allows_measure_sampling
# If flag isn't found do a simple test to see if a circuit contains
# no reset instructions, and no gates instructions after
# the first measure.
else:
measure_flag = False
for instruction in experiment.instructions:
# If circuit contains reset operations we cannot sample
if instruction.name == "reset":
self._sample_measure = False
| 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_options: Is a dict of options for the backend. It may contain
* "initial_statevector": vector_like
The "initial_statevector" option specifies a custom initial
initial statevector for the simulator to be used instead of the all
zero state. This size of this vector must be correct for the number
of qubits in all experiments in the | 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.config.shots
self._memory = getattr(qobj.config, 'memory', False)
self._qobj_config = qobj.config
start = time.time()
for experiment in qobj.experiments:
result_list.append(self.run_experiment(experiment))
end = time.time()
result = {'backend_name': self.name(),
| 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) +
'is greater than maximum ({}) '.format(max_qubits) +
'for "{}".'.format(self.name()))
for experiment in qobj.experiments:
name = experiment.header.name
| 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_unitary)
required_shape = (2 ** self._number_of_qubits,
| 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, | 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
| 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()
for experiment in qobj.experiments:
result_list.append(self.run_experiment(experiment))
end = time.time()
result = {'backend_name': self.name(),
'backend_version': self._configuration.backend_version,
| 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_qubits
if n_qubits > max_qubits:
raise BasicAerError('Number of qubits {} '.format(n_qubits) +
'is greater than maximum ({}) '.format(max_qubits) +
'for "{}".'.format(self.name()))
if hasattr(qobj.config, 'shots') and qobj.config.shots != 1:
logger.info('"%s" only supports 1 shot. Setting shots=1.',
self.name())
qobj.config.shots = 1
for experiment in qobj.experiments:
name = experiment.header.name
if getattr(experiment.config, 'shots', 1) != 1:
logger.info('"%s" only supports 1 shot. '
| 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:
| 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 qreg in dag.qregs.values()])
| 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
| 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:
| python | {
"resource": ""
} |
q268362 | Timeslot.shift | test | def shift(self, time: int) -> 'Timeslot':
"""Return a new Timeslot shifted by `time`.
| 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:
| 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
"""
| 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 | 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 twice about the same failure.
Args:
branch (str): branch name to report about.
commit (str): commit hash at which the build fails.
infourl (str): URL with extra info about the failure | 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)))
| 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 (bool): activate slider
show_legend (bool): show legend of graph content
"""
# HTML
html_template = Template("""
<p>
<div id="paulivec_$divNumber"></div>
</p>
""")
# JavaScript
javascript_template = Template("""
<script>
requirejs.config({
paths: {
qVisualization: "https://qvisualization.mybluemix.net/q-visualizations"
}
});
require(["qVisualization"], function(qVisualizations) {
qVisualizations.plotState("paulivec_$divNumber",
"paulivec",
$executions,
| python | {
"resource": ""
} |
q268371 | rzz | test | def rzz(self, theta, qubit1, qubit2):
"""Apply RZZ | python | {
"resource": ""
} |
q268372 | cswap | test | def cswap(self, ctl, tgt1, tgt2):
"""Apply Fredkin | 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 == 'gate_error':
g_reliab = 1.0 - item.value
break
else:
g_reliab = 1.0
swap_reliab = -math.log(pow(g_reliab, 3))
self.swap_graph.add_edge(ginfo.qubits[0], ginfo.qubits[1], weight=swap_reliab)
self.swap_graph.add_edge(ginfo.qubits[1], ginfo.qubits[0], weight=swap_reliab)
self.cx_errors[(ginfo.qubits[0], ginfo.qubits[1])] = g_reliab
self.gate_list.append((ginfo.qubits[0], ginfo.qubits[1]))
idx = 0
for q in backend_prop.qubits:
for nduv in q:
if nduv.name == 'readout_error':
self.readout_errors[idx] = 1.0 - nduv.value
self.available_hw_qubits.append(idx)
idx += 1
for edge in self.cx_errors:
self.gate_cost[edge] = self.cx_errors[edge] * self.readout_errors[edge[0]] *\
self.readout_errors[edge[1]]
self.swap_paths, swap_costs_temp = nx.algorithms.shortest_paths.dense.\
| 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 in dag.qubits():
self.qarg_to_id[q[0].name + str(q[1])] = idx
idx += 1
for gate in dag.twoQ_gates():
qid1 = self._qarg_to_id(gate.qargs[0])
qid2 = self._qarg_to_id(gate.qargs[1])
| 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
| 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
if chk1 and chk2:
candidates.append(gate)
best_reliab = 0
best_item = None
| 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):
if n in self.prog2hw:
reliab *= self.swap_costs[self.prog2hw[n]][hw_qubit]
reliab *= self.readout_errors[hw_qubit]
reliab_store[hw_qubit] = reliab
| 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, _ in sorted(self.prog_graph.edges(data=True),
key=lambda x: x[2]['weight'], reverse=True):
self.pending_program_edges.append((end1, end2))
while self.pending_program_edges:
edge = self._select_next_edge()
q1_mapped = edge[0] in self.prog2hw
q2_mapped = edge[1] in self.prog2hw
if (not q1_mapped) and (not q2_mapped):
best_hw_edge = self._select_best_remaining_cx()
self.prog2hw[edge[0]] = best_hw_edge[0]
self.prog2hw[edge[1]] = best_hw_edge[1]
self.available_hw_qubits.remove(best_hw_edge[0])
self.available_hw_qubits.remove(best_hw_edge[1])
elif not q1_mapped:
best_hw_qubit = self._select_best_remaining_qubit(edge[0])
self.prog2hw[edge[0]] = best_hw_qubit
self.available_hw_qubits.remove(best_hw_qubit)
else:
| 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 | python | {
"resource": ""
} |
q268380 | CompositeGate.inverse | test | def inverse(self):
"""Invert this gate."""
self.data = [gate.inverse() for gate in reversed(self.data)]
| python | {
"resource": ""
} |
q268381 | CompositeGate.q_if | test | def q_if(self, *qregs):
"""Add controls to this gate."""
self.data | python | {
"resource": ""
} |
q268382 | CompositeGate.c_if | test | def c_if(self, classical, val):
"""Add classical control register."""
self.data | 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:
| python | {
"resource": ""
} |
q268384 | Operator.conjugate | test | def conjugate(self):
"""Return the conjugate of the operator."""
return Operator(
| python | {
"resource": ""
} |
q268385 | Operator.transpose | test | def transpose(self):
"""Return the transpose of the operator."""
return Operator(
| 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
are not equal, or the power is not a positive integer.
"""
if not isinstance(n, int):
raise QiskitError("Can only take integer powers of Operator.")
if self.input_dims() != self.output_dims():
raise QiskitError("Can only | python | {
"resource": ""
} |
q268387 | Operator._shape | test | def _shape(self):
"""Return the tensor shape of the matrix operator"""
return | 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):
| 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 = layout returned from swap algorithm
best_d = depth returned from swap algorithm
best_circ = swap circuit returned from swap algorithm
layer_list = list of circuit objects for each layer
Return DAGCircuit object to append to the output DAGCircuit.
"""
layout = best_layout
dagcircuit_output = DAGCircuit()
| 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): | 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 complex numpy array
Raises:
QiskitError: If the returned numpy array does not have 2 (avg) or 3 (single)
| 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 complex numpy array
Raises:
QiskitError: If the returned numpy array does not have 1 (avg) or 2 (single)
| 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 for postprocessing.
| 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 postprocessing.
Returns:
| 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:
list[complex]: a list of | 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:
list[list[complex]]: | 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.
"""
| 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.
"""
# The order is important here
if self._future.running():
_status = JobStatus.RUNNING
elif self._future.cancelled():
_status = JobStatus.CANCELLED
elif self._future.done():
_status = JobStatus.DONE if self._future.exception() is None else JobStatus.ERROR
else:
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.