docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
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 | def random(cls, num_qubits, seed=None):
if seed is not None:
np.random.seed(seed)
z = np.random.randint(2, size=num_qubits).astype(np.bool)
x = np.random.randint(2, size=num_qubits).astype(np.bool)
return cls(z, x) | 159,530 |
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): pauli
Returns:
Pauli: single qubit pauli | def pauli_single(cls, num_qubits, index, pauli_label):
tmp = Pauli.from_label(pauli_label)
z = np.zeros(num_qubits, dtype=np.bool)
x = np.zeros(num_qubits, dtype=np.bool)
z[index] = tmp.z[0]
x[index] = tmp.x[0]
return cls(z, x) | 159,531 |
Apply an arbitrary 1-qubit unitary matrix.
Args:
gate (matrix_like): a single qubit gate matrix
qubit (int): the qubit to apply gate to | def _add_unitary_single(self, gate, qubit):
# Compute einsum index string for 1-qubit matrix multiplication
indexes = einsum_vecmul_index([qubit], self._number_of_qubits)
# Convert to complex rank-2 tensor
gate_tensor = np.array(gate, dtype=complex)
# Apply matrix multip... | 159,534 |
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 | def _add_unitary_two(self, gate, qubit0, qubit1):
# Compute einsum index string for 1-qubit matrix multiplication
indexes = einsum_vecmul_index([qubit0, qubit1], self._number_of_qubits)
# Convert to complex rank-4 tensor
gate_tensor = np.reshape(np.array(gate, dtype=complex), 4 ... | 159,535 |
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. | def _get_measure_outcome(self, qubit):
# Axis for numpy.sum to compute probabilities
axis = list(range(self._number_of_qubits))
axis.remove(self._number_of_qubits - 1 - qubit)
probabilities = np.sum(np.abs(self._statevector) ** 2, axis=tuple(axis))
# Compute einsum index... | 159,536 |
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 o... | def _add_sample_measure(self, measure_params, num_samples):
# 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(r... | 159,537 |
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. | def _add_qasm_measure(self, qubit, cmembit, cregbit=None):
# 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) << cmembi... | 159,538 |
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. | def _add_qasm_reset(self, qubit):
# get measure outcome
outcome, probability = self._get_measure_outcome(qubit)
# update quantum state
if outcome == '0':
update = [[1 / np.sqrt(probability), 0], [0, 0]]
self._add_unitary_single(update, qubit)
else... | 159,539 |
Determine if measure sampling is allowed for an experiment
Args:
experiment (QobjExperiment): a qobj experiment. | def _validate_measure_sampling(self, 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._sam... | 159,544 |
Run experiments in qobj
Args:
job_id (str): unique id for the job.
qobj (Qobj): job description
Returns:
Result: Result object | def _run_job(self, job_id, qobj):
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:
... | 159,546 |
Apply an arbitrary 1-qubit unitary matrix.
Args:
gate (matrix_like): a single qubit gate matrix
qubit (int): the qubit to apply gate to | def _add_unitary_single(self, gate, qubit):
# Convert to complex rank-2 tensor
gate_tensor = np.array(gate, dtype=complex)
# Compute einsum index string for 1-qubit matrix multiplication
indexes = einsum_matmul_index([qubit], self._number_of_qubits)
# Apply matrix multip... | 159,550 |
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 | def _add_unitary_two(self, gate, qubit0, qubit1):
# Convert to complex rank-4 tensor
gate_tensor = np.reshape(np.array(gate, dtype=complex), 4 * [2])
# Compute einsum index string for 2-qubit matrix multiplication
indexes = einsum_matmul_index([qubit0, qubit1], self._number_of... | 159,551 |
Run experiments in qobj.
Args:
job_id (str): unique id for the job.
qobj (Qobj): job description
Returns:
Result: Result object | def _run_job(self, job_id, qobj):
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(),
... | 159,556 |
Decorator for expanding an operation across a whole register or register subset.
Args:
n_bits (int): the number of register bit arguments the decorated function takes
func (function): used for decorators with keyword args
broadcastable (list(bool)): list of bool for which register args can b... | def _op_expand(n_bits, func=None, broadcastable=None):
if func is None:
return functools.partial(_op_expand, n_bits, broadcastable=broadcastable)
@functools.wraps(func)
def wrapper(self, *args):
params = args[0:-n_bits] if len(args) > n_bits else tuple()
rargs = args[-n_bits:]
... | 159,562 |
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 | def run(self, dag):
num_dag_qubits = sum([qreg.size for qreg in dag.qregs.values()])
if num_dag_qubits > self.coupling_map.size():
raise TranspilerError('Number of qubits greater than device.')
self.property_set['layout'] = Layout.generate_trivial_layout(*dag.qregs.values()) | 159,565 |
Create an interval = (begin, end))
Args:
begin: begin time of this interval
end: end time of this interval
Raises:
PulseError: when invalid time or duration is specified | def __init__(self, begin: int, end: int):
if begin < 0:
raise PulseError("Cannot create Interval with negative begin time")
if end < 0:
raise PulseError("Cannot create Interval with negative end time")
self._begin = begin
self._end = end | 159,566 |
Check if self has overlap with `interval`.
Args:
interval: interval to be examined
Returns:
bool: True if self has overlap with `interval` otherwise False | def has_overlap(self, interval: 'Interval') -> bool:
if self.begin < interval.end and interval.begin < self.end:
return True
return False | 159,567 |
Return a new interval shifted by `time` from self
Args:
time: time to be shifted
Returns:
Interval: interval shifted by `time` | def shift(self, time: int) -> 'Interval':
return Interval(self._begin + time, self._end + time) | 159,568 |
Two intervals are the same if they have the same begin and end.
Args:
other (Interval): other Interval
Returns:
bool: are self and other equal. | def __eq__(self, other):
if self._begin == other._begin and self._end == other._end:
return True
return False | 159,569 |
Return a new Timeslot shifted by `time`.
Args:
time: time to be shifted | def shift(self, time: int) -> 'Timeslot':
return Timeslot(self.interval.shift(time), self.channel) | 159,571 |
Two time-slots are the same if they have the same interval and channel.
Args:
other (Timeslot): other Timeslot | def __eq__(self, other) -> bool:
if self.interval == other.interval and self.channel == other.channel:
return True
return False | 159,572 |
Create a new time-slot collection.
Args:
*timeslots: list of time slots
Raises:
PulseError: when overlapped time slots are specified | def __init__(self, *timeslots: List[Timeslot]):
self._table = defaultdict(list)
for slot in timeslots:
for interval in self._table[slot.channel]:
if slot.interval.has_overlap(interval):
raise PulseError("Cannot create TimeslotCollection from over... | 159,573 |
Return earliest start time in this collection.
Args:
*channels: Channels over which to obtain start_time. | def ch_start_time(self, *channels: List[Channel]) -> int:
intervals = list(itertools.chain(*(self._table[chan] for chan in channels
if chan in self._table)))
if intervals:
return min((interval.begin for interval in intervals))
retur... | 159,574 |
Return maximum time of timeslots over all channels.
Args:
*channels: Channels over which to obtain stop time. | def ch_stop_time(self, *channels: List[Channel]) -> int:
intervals = list(itertools.chain(*(self._table[chan] for chan in channels
if chan in self._table)))
if intervals:
return max((interval.end for interval in intervals))
return 0 | 159,575 |
Return if self is mergeable with `timeslots`.
Args:
timeslots: TimeslotCollection to be checked | def is_mergeable_with(self, timeslots: 'TimeslotCollection') -> bool:
for slot in timeslots.timeslots:
for interval in self._table[slot.channel]:
if slot.interval.has_overlap(interval):
return False
return True | 159,576 |
Return a new TimeslotCollection merged with a specified `timeslots`
Args:
timeslots: TimeslotCollection to be merged | def merged(self, timeslots: 'TimeslotCollection') -> 'TimeslotCollection':
slots = [Timeslot(slot.interval, slot.channel) for slot in self.timeslots]
slots.extend([Timeslot(slot.interval, slot.channel) for slot in timeslots.timeslots])
return TimeslotCollection(*slots) | 159,577 |
Return a new TimeslotCollection shifted by `time`.
Args:
time: time to be shifted by | def shift(self, time: int) -> 'TimeslotCollection':
slots = [Timeslot(slot.interval.shift(time), slot.channel) for slot in self.timeslots]
return TimeslotCollection(*slots) | 159,578 |
Two time-slot collections are the same if they have the same time-slots.
Args:
other (TimeslotCollection): other TimeslotCollection | def __eq__(self, other) -> bool:
if self.timeslots == other.timeslots:
return True
return False | 159,579 |
create new persistent value command.
Args:
value (complex): Complex value to apply, bounded by an absolute value of 1.
The allowable precision is device specific.
Raises:
PulseError: when input value exceed 1. | def __init__(self, value):
super().__init__(duration=0)
if abs(value) > 1:
raise PulseError("Absolute value of PV amplitude exceeds 1.")
self._value = complex(value) | 159,583 |
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 | def iplot_state_paulivec(rho, figsize=None, slider=False, show_legend=False):
# HTML
html_template = Template()
# JavaScript
javascript_template = Template()
rho = _validate_input_state(rho)
# set default figure size if none given
if figsize is None:
figsize = (7, 5)
opti... | 159,596 |
Plot the quantum state.
Args:
quantum_state (ndarray): statevector or density matrix
representation of a quantum state.
method (str): Plotting method to use.
figsize (tuple): Figure size in pixels.
Raises:
VisualizationError: if the input is not... | def iplot_state(quantum_state, method='city', figsize=None):
warnings.warn("iplot_state is deprecated, and will be removed in \
the 0.9 release. Use the iplot_state_ * functions \
instead.",
DeprecationWarning)
rho = _validate_input_state(quantum_state)... | 159,597 |
Chooses a Noise Adaptive Layout
Args:
backend_prop (BackendProperties): backend properties object
Raises:
TranspilerError: if invalid options | def __init__(self, backend_prop):
super().__init__()
self.backend_prop = backend_prop
self.swap_graph = nx.DiGraph()
self.cx_errors = {}
self.readout_errors = {}
self.available_hw_qubits = []
self.gate_list = []
self.gate_cost = {}
self.sw... | 159,601 |
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 i... | def power(self, n):
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 power with input_dims = output_dims.")
# Override base class power so we can impl... | 159,617 |
Return the operator self + other.
Args:
other (Operator): an operator object.
Returns:
Operator: the operator self + other.
Raises:
QiskitError: if other is not an operator, or has incompatible
dimensions. | def add(self, other):
if not isinstance(other, Operator):
other = Operator(other)
if self.dim != other.dim:
raise QiskitError("other operator has different dimensions.")
return Operator(self.data + other.data, self.input_dims(),
self.outpu... | 159,618 |
Return the operator self + other.
Args:
other (complex): a complex number.
Returns:
Operator: the operator other * self.
Raises:
QiskitError: if other is not a valid complex number. | def multiply(self, other):
if not isinstance(other, Number):
raise QiskitError("other is not a number")
return Operator(other * self.data, self.input_dims(),
self.output_dims()) | 159,619 |
Evolve a quantum state by the operator.
Args:
state (QuantumState): The input statevector or density matrix.
qargs (list): a list of QuantumState subsystem positions to apply
the operator on.
Returns:
QuantumState: the output quantum state... | def _evolve(self, state, qargs=None):
state = self._format_state(state)
if qargs is None:
if state.shape[0] != self._input_dim:
raise QiskitError(
"Operator input dimension is not equal to state dimension."
)
if state.n... | 159,621 |
Evolve a quantum state by the operator.
Args:
state (QuantumState): The input statevector or density matrix.
qargs (list): a list of QuantumState subsystem positions to apply
the operator on.
Returns:
QuantumState: the output quantum state... | def _evolve_subsystem(self, state, qargs):
mat = np.reshape(self.data, self._shape)
# Hack to assume state is a N-qubit state until a proper class for states
# is in place
state_size = len(state)
state_dims = self._automatic_dims(None, state_size)
if self.input_d... | 159,622 |
Maps a DAGCircuit onto a `coupling_map` using swap gates.
Args:
coupling_map (CouplingMap): Directed graph represented a coupling map.
initial_layout (Layout): initial layout of qubits in mapping
trials (int): the number of attempts the randomized algorithm makes.
... | def __init__(self,
coupling_map,
initial_layout=None,
trials=20,
seed=None):
super().__init__()
self.coupling_map = coupling_map
self.initial_layout = initial_layout
self.trials = trials
self.seed = seed... | 159,626 |
Convert nested list of shape (..., 2) to complex numpy array with shape (...)
Args:
complex_list (list): List to convert.
Returns:
np.ndarray: Complex numpy aray
Raises:
QiskitError: If inner most array of input nested list is not of length 2. | def _list_to_complex_array(complex_list):
arr = np.asarray(complex_list, dtype=np.complex_)
if not arr.shape[-1] == 2:
raise QiskitError('Inner most nested list is not of length 2.')
return arr[..., 0] + 1j*arr[..., 1] | 159,636 |
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:
Qis... | def format_level_0_memory(memory):
formatted_memory = _list_to_complex_array(memory)
# infer meas_return from shape of returned data.
if not 2 <= len(formatted_memory.shape) <= 3:
raise QiskitError('Level zero memory is not of correct shape.')
return formatted_memory | 159,637 |
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:
Qis... | def format_level_1_memory(memory):
formatted_memory = _list_to_complex_array(memory)
# infer meas_return from shape of returned data.
if not 1 <= len(formatted_memory.shape) <= 2:
raise QiskitError('Level one memory is not of correct shape.')
return formatted_memory | 159,638 |
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.
Returns:
list[str]: List... | def format_level_2_memory(memory, header=None):
memory_list = []
for shot_memory in memory:
memory_list.append(format_counts_memory(shot_memory, header))
return memory_list | 159,639 |
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:
dict: a formatted coun... | def format_counts(counts, header=None):
counts_dict = {}
for key, val in counts.items():
key = format_counts_memory(key, header)
counts_dict[key] = val
return counts_dict | 159,640 |
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 complex numbers. | def format_statevector(vec, decimals=None):
num_basis = len(vec)
vec_complex = np.zeros(num_basis, dtype=complex)
for i in range(num_basis):
vec_complex[i] = vec[i][0] + 1j * vec[i][1]
if decimals:
vec_complex = np.around(vec_complex, decimals=decimals)
return vec_complex | 159,641 |
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]]: a matrix of comple... | def format_unitary(mat, decimals=None):
num_basis = len(mat)
mat_complex = np.zeros((num_basis, num_basis), dtype=complex)
for i, vec in enumerate(mat):
mat_complex[i] = format_statevector(vec, decimals)
return mat_complex | 159,642 |
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. | def requires_submit(func):
@functools.wraps(func)
def _wrapper(self, *args, **kwargs):
if self._future is None:
raise JobError("Job not submitted yet!. You have to .submit() first!")
return func(self, *args, **kwargs)
return _wrapper | 159,644 |
Whether `lo_freq` is within the `LoRange`.
Args:
lo_freq: LO frequency to be checked
Returns:
bool: True if lo_freq is included in this range, otherwise False | def includes(self, lo_freq: float) -> bool:
if self._lb <= lo_freq <= self._ub:
return True
return False | 159,649 |
Two LO ranges are the same if they are of the same type, and
have the same frequency range
Args:
other (LoRange): other LoRange
Returns:
bool: are self and other equal. | def __eq__(self, other):
if (type(self) is type(other) and
self._ub == other._ub and
self._lb == other._lb):
return True
return False | 159,650 |
Create new drive (d) channel.
Args:
index (int): index of the channel
lo_freq (float): default frequency of LO (local oscillator)
lo_freq_range (tuple): feasible range of LO frequency | def __init__(self, index: int,
lo_freq: float = None,
lo_freq_range: Tuple[float, float] = (0, float("inf"))):
super().__init__(index, lo_freq, lo_freq_range) | 159,652 |
Create a bloch sphere representation.
Graphical representation of the input array, using as much bloch
spheres as qubit are required.
Args:
rho (array): State vector or density matrix
figsize (tuple): Figure size in pixels. | def iplot_bloch_multivector(rho, figsize=None):
# HTML
html_template = Template()
# JavaScript
javascript_template = Template()
rho = _validate_input_state(rho)
if figsize is None:
options = {}
else:
options = {'width': figsize[0], 'height': figsize[1]}
# Process ... | 159,653 |
Create new converter.
Args:
qobj_model (PulseQobjExperimentConfig): qobj model for experiment config.
default_qubit_los (list): List of default qubit lo frequencies.
default_meas_los (list): List of default meas lo frequencies.
run_config (dict): experimental con... | def __init__(self, qobj_model, default_qubit_los, default_meas_los, **run_config):
self.qobj_model = qobj_model
self.default_qubit_los = default_qubit_los
self.default_meas_los = default_meas_los
self.run_config = run_config | 159,655 |
Return PulseQobjExperimentConfig
Args:
user_lo_config (LoConfig): A dictionary of LOs to format.
Returns:
PulseQobjExperimentConfig: qobj. | def __call__(self, user_lo_config):
lo_config = {}
q_los = self.get_qubit_los(user_lo_config)
if q_los:
lo_config['qubit_lo_freq'] = q_los
m_los = self.get_meas_los(user_lo_config)
if m_los:
lo_config['meas_lo_freq'] = m_los
return self.... | 159,656 |
Embed default qubit LO frequencies from backend and format them to list object.
If configured lo frequency is the same as default, this method returns `None`.
Args:
user_lo_config (LoConfig): A dictionary of LOs to format.
Returns:
list: A list of qubit LOs.
Ra... | def get_qubit_los(self, user_lo_config):
try:
_q_los = self.default_qubit_los.copy()
except KeyError:
raise PulseError('Qubit default frequencies not exist.')
for channel, lo_freq in user_lo_config.qubit_lo_dict().items():
_q_los[channel.index] = lo_... | 159,657 |
Embed default meas LO frequencies from backend and format them to list object.
If configured lo frequency is the same as default, this method returns `None`.
Args:
user_lo_config (LoConfig): A dictionary of LOs to format.
Returns:
list: A list of meas LOs.
Rais... | def get_meas_los(self, user_lo_config):
try:
_m_los = self.default_meas_los.copy()
except KeyError:
raise PulseError('Default measurement frequencies not exist.')
for channel, lo_freq in user_lo_config.meas_lo_dict().items():
_m_los[channel.index] = ... | 159,658 |
Expand all op nodes to the given basis.
Args:
dag(DAGCircuit): input dag
Raises:
QiskitError: if unable to unroll given the basis due to undefined
decomposition rules (such as a bad basis) or excessive recursion.
Returns:
DAGCircuit: output unro... | def run(self, dag):
# Walk through the DAG and expand each non-basis node
for node in dag.op_nodes():
basic_insts = ['measure', 'reset', 'barrier', 'snapshot']
if node.name in basic_insts:
# TODO: this is legacy behavior.Basis_insts should be removed that... | 159,659 |
Create a Q sphere representation.
Graphical representation of the input array, using a Q sphere for each
eigenvalue.
Args:
rho (array): State vector or density matrix.
figsize (tuple): Figure size in pixels. | def iplot_state_qsphere(rho, figsize=None):
# HTML
html_template = Template()
# JavaScript
javascript_template = Template()
rho = _validate_input_state(rho)
if figsize is None:
options = {}
else:
options = {'width': figsize[0], 'height': figsize[1]}
qspheres_data ... | 159,660 |
Return the number of combinations for n choose k.
Args:
n (int): the total number of options .
k (int): The number of elements.
Returns:
int: returns the binomial coefficient | def n_choose_k(n, k):
if n == 0:
return 0
return reduce(lambda x, y: x * y[0] / y[1],
zip(range(n - k + 1, n + 1),
range(1, k + 1)), 1) | 159,661 |
Return the lex index of a combination..
Args:
n (int): the total number of options .
k (int): The number of elements.
lst (list): list
Returns:
int: returns int index for lex order
Raises:
VisualizationError: if length of list is not equal to k | def lex_index(n, k, lst):
if len(lst) != k:
raise VisualizationError("list should have length k")
comb = list(map(lambda x: n - 1 - x, lst))
dualm = sum([n_choose_k(comb[k - 1 - i], i + 1) for i in range(k)])
return int(dualm) | 159,663 |
Plot a hinton diagram for the quanum state.
Args:
rho (ndarray): Numpy array for state vector or density matrix.
title (str): a string that represents the plot title
figsize (tuple): Figure size in inches.
Returns:
matplotlib.Figure: The matplotlib.Figure of the visualization
... | def plot_state_hinton(rho, title='', figsize=None):
if not HAS_MATPLOTLIB:
raise ImportError('Must have Matplotlib installed.')
rho = _validate_input_state(rho)
if figsize is None:
figsize = (8, 5)
num = int(np.log2(len(rho)))
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize... | 159,664 |
Plot the Bloch sphere.
Plot a sphere, axes, the Bloch vector, and its projections onto each axis.
Args:
rho (ndarray): Numpy array for state vector or density matrix.
title (str): a string that represents the plot title
figsize (tuple): Has no effect, here for compatibility only.
... | def plot_bloch_multivector(rho, title='', figsize=None):
if not HAS_MATPLOTLIB:
raise ImportError('Must have Matplotlib installed.')
rho = _validate_input_state(rho)
num = int(np.log2(len(rho)))
width, height = plt.figaspect(1/num)
fig = plt.figure(figsize=(width, height))
for i in ... | 159,666 |
Plot the qsphere representation of a quantum state.
Args:
rho (ndarray): State vector or density matrix representation.
of quantum state.
figsize (tuple): Figure size in inches.
Returns:
Figure: A matplotlib figure instance.
Raises:
ImportError: Requires matplotlib... | def plot_state_qsphere(rho, figsize=None):
if not HAS_MATPLOTLIB:
raise ImportError('Must have Matplotlib installed.')
rho = _validate_input_state(rho)
if figsize is None:
figsize = (7, 7)
num = int(np.log2(len(rho)))
# get the eigenvectors and eigenvalues
we, stateall = lin... | 159,671 |
Monitor a single IBMQ backend.
Args:
backend (IBMQBackend): Backend to monitor.
Raises:
QiskitError: Input is not a IBMQ backend. | def backend_monitor(backend):
if not isinstance(backend, IBMQBackend):
raise QiskitError('Input variable is not of type IBMQBackend.')
config = backend.configuration().to_dict()
status = backend.status().to_dict()
config_dict = {**status, **config}
if not config['simulator']:
pr... | 159,677 |
Check if DAG nodes are considered equivalent, e.g. as a node_match for nx.is_isomorphic.
Args:
node1 (DAGNode): A node to compare.
node2 (DAGNode): The other node to compare.
Return:
Bool: If node1 == node2 | def semantic_eq(node1, node2):
# For barriers, qarg order is not significant so compare as sets
if 'barrier' == node1.name == node2.name:
return set(node1.qargs) == set(node2.qargs)
return node1.data_dict == node2.data_dict | 159,682 |
Generates constant-sampled `SamplePulse`.
Applies `left` sampling strategy to generate discrete pulse from continuous function.
Args:
duration: Duration of pulse. Must be greater than zero.
amp: Complex pulse amplitude.
name: Name of pulse. | def constant(duration: int, amp: complex, name: str = None) -> SamplePulse:
return _sampled_constant_pulse(duration, amp, name=name) | 159,683 |
Generates zero-sampled `SamplePulse`.
Args:
duration: Duration of pulse. Must be greater than zero.
name: Name of pulse. | def zero(duration: int, name: str = None) -> SamplePulse:
return _sampled_zero_pulse(duration, name=name) | 159,684 |
Generates square wave `SamplePulse`.
Applies `left` sampling strategy to generate discrete pulse from continuous function.
Args:
duration: Duration of pulse. Must be greater than zero.
amp: Pulse amplitude. Wave range is [-amp, amp].
period: Pulse period, units of dt. If `None` default... | def square(duration: int, amp: complex, period: float = None,
phase: float = 0, name: str = None) -> SamplePulse:
if period is None:
period = duration
return _sampled_square_pulse(duration, amp, period, phase=phase, name=name) | 159,685 |
Generates sawtooth wave `SamplePulse`.
Args:
duration: Duration of pulse. Must be greater than zero.
amp: Pulse amplitude. Wave range is [-amp, amp].
period: Pulse period, units of dt. If `None` defaults to single cycle.
phase: Pulse phase.
name: Name of pulse. | def sawtooth(duration: int, amp: complex, period: float = None,
phase: float = 0, name: str = None) -> SamplePulse:
if period is None:
period = duration
return _sampled_sawtooth_pulse(duration, amp, period, phase=phase, name=name) | 159,686 |
Generates triangle wave `SamplePulse`.
Applies `left` sampling strategy to generate discrete pulse from continuous function.
Args:
duration: Duration of pulse. Must be greater than zero.
amp: Pulse amplitude. Wave range is [-amp, amp].
period: Pulse period, units of dt. If `None` defau... | def triangle(duration: int, amp: complex, period: float = None,
phase: float = 0, name: str = None) -> SamplePulse:
if period is None:
period = duration
return _sampled_triangle_pulse(duration, amp, period, phase=phase, name=name) | 159,687 |
Generates cosine wave `SamplePulse`.
Applies `left` sampling strategy to generate discrete pulse from continuous function.
Args:
duration: Duration of pulse. Must be greater than zero.
amp: Pulse amplitude.
freq: Pulse frequency, units of 1/dt. If `None` defaults to single cycle.
... | def cos(duration: int, amp: complex, freq: float = None,
phase: float = 0, name: str = None) -> SamplePulse:
if freq is None:
freq = 1/duration
return _sampled_cos_pulse(duration, amp, freq, phase=phase, name=name) | 159,688 |
Generates sine wave `SamplePulse`.
Args:
duration: Duration of pulse. Must be greater than zero.
amp: Pulse amplitude.
freq: Pulse frequency, units of 1/dt. If `None` defaults to single cycle.
phase: Pulse phase.
name: Name of pulse. | def sin(duration: int, amp: complex, freq: float = None,
phase: float = 0, name: str = None) -> SamplePulse:
if freq is None:
freq = 1/duration
return _sampled_sin_pulse(duration, amp, freq, phase=phase, name=name) | 159,689 |
r"""Generates unnormalized gaussian derivative `SamplePulse`.
Applies `left` sampling strategy to generate discrete pulse from continuous function.
Args:
duration: Duration of pulse. Must be greater than zero.
amp: Pulse amplitude at `center`.
sigma: Width (standard deviation) of pulse... | def gaussian_deriv(duration: int, amp: complex, sigma: float, name: str = None) -> SamplePulse:
r
center = duration/2
return _sampled_gaussian_deriv_pulse(duration, amp, center, sigma, name=name) | 159,691 |
Return an instance of a backend from its class.
Args:
backend_cls (class): Backend class.
Returns:
BaseBackend: a backend instance.
Raises:
QiskitError: if the backend could not be instantiated. | def _get_backend_instance(self, backend_cls):
# Verify that the backend can be instantiated.
try:
backend_instance = backend_cls(provider=self)
except Exception as err:
raise QiskitError('Backend %s could not be instantiated: %s' %
(... | 159,705 |
Add a qubit or bit to the circuit.
Args:
wire (tuple): (Register,int) containing a register instance and index
This adds a pair of in and out nodes connected by an edge.
Raises:
DAGCircuitError: if trying to add duplicate wire | def _add_wire(self, wire):
if wire not in self.wires:
self.wires.append(wire)
self._max_node_id += 1
input_map_wire = self.input_map[wire] = self._max_node_id
self._max_node_id += 1
output_map_wire = self._max_node_id
wire_name =... | 159,713 |
Verify that the condition is valid.
Args:
name (string): used for error reporting
condition (tuple or None): a condition tuple (ClassicalRegister,int)
Raises:
DAGCircuitError: if conditioning on an invalid register | def _check_condition(self, name, condition):
# Verify creg exists
if condition is not None and condition[0].name not in self.cregs:
raise DAGCircuitError("invalid creg in condition for %s" % name) | 159,714 |
Check the values of a list of (qu)bit arguments.
For each element of args, check that amap contains it.
Args:
args (list): (register,idx) tuples
amap (dict): a dictionary keyed on (register,idx) tuples
Raises:
DAGCircuitError: if a qubit is not contained in... | def _check_bits(self, args, amap):
# Check for each wire
for wire in args:
if wire not in amap:
raise DAGCircuitError("(qu)bit %s[%d] not found" %
(wire[0].name, wire[1])) | 159,715 |
Return a list of bits in the given condition.
Args:
cond (tuple or None): optional condition (ClassicalRegister, int)
Returns:
list[(ClassicalRegister, idx)]: list of bits | def _bits_in_condition(self, cond):
all_bits = []
if cond is not None:
all_bits.extend([(cond[0], j) for j in range(self.cregs[cond[0].name].size)])
return all_bits | 159,716 |
Add a new operation node to the graph and assign properties.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list): list of quantum wires to attach to.
cargs (list): list of classical wires to attach to.
condition (tuple or None): option... | def _add_op_node(self, op, qargs, cargs, condition=None):
node_properties = {
"type": "op",
"op": op,
"name": op.name,
"qargs": qargs,
"cargs": cargs,
"condition": condition
}
# Add a new operation node to the grap... | 159,717 |
Check that the wiremap is consistent.
Check that the wiremap refers to valid wires and that
those wires have consistent types.
Args:
wire_map (dict): map from (register,idx) in keymap to
(register,idx) in valmap
keymap (dict): a map whose keys are wire_m... | def _check_wiremap_validity(self, wire_map, keymap, valmap):
for k, v in wire_map.items():
kname = "%s[%d]" % (k[0].name, k[1])
vname = "%s[%d]" % (v[0].name, v[1])
if k not in keymap:
raise DAGCircuitError("invalid wire mapping key %s" % kname)
... | 159,720 |
Use the wire_map dict to change the condition tuple's creg name.
Args:
wire_map (dict): a map from wires to wires
condition (tuple): (ClassicalRegister,int)
Returns:
tuple(ClassicalRegister,int): new condition | def _map_condition(self, wire_map, condition):
if condition is None:
new_condition = None
else:
# Map the register name, using fact that registers must not be
# fragmented by the wire_map (this must have been checked
# elsewhere)
bit0 ... | 159,721 |
Check that a list of wires is compatible with a node to be replaced.
- no duplicate names
- correct length for operation
Raise an exception otherwise.
Args:
wires (list[register, index]): gives an order for (qu)bits
in the input circuit that is replacing the... | def _check_wires_list(self, wires, node):
if len(set(wires)) != len(wires):
raise DAGCircuitError("duplicate wires")
wire_tot = len(node.qargs) + len(node.cargs)
if node.condition is not None:
wire_tot += node.condition[0].size
if len(wires) != wire_tot... | 159,725 |
Return predecessor and successor dictionaries.
Args:
node (DAGNode): reference to multi_graph node
Returns:
tuple(dict): tuple(predecessor_map, successor_map)
These map from wire (Register, int) to predecessor (successor)
nodes of n. | def _make_pred_succ_maps(self, node):
pred_map = {e[2]['wire']: e[0] for e in
self._multi_graph.in_edges(nbunch=node, data=True)}
succ_map = {e[2]['wire']: e[1] for e in
self._multi_graph.out_edges(nbunch=node, data=True)}
return pred_map, succ_m... | 159,726 |
Replace one node with dag.
Args:
node (DAGNode): node to substitute
input_dag (DAGCircuit): circuit that will substitute the node
wires (list[(Register, index)]): gives an order for (qu)bits
in the input circuit. This order gets matched to the node wires
... | def substitute_node_with_dag(self, node, input_dag, wires=None):
if isinstance(node, int):
warnings.warn('Calling substitute_node_with_dag() with a node id is deprecated,'
' use a DAGNode instead',
DeprecationWarning, 2)
node ... | 159,730 |
Get the list of "op" nodes in the dag.
Args:
op (Type): Instruction subclass op nodes to return. if op=None, return
all op nodes.
Returns:
list[DAGNode]: the list of node ids containing the given op. | def op_nodes(self, op=None):
nodes = []
for node in self._multi_graph.nodes():
if node.type == "op":
if op is None or isinstance(node.op, op):
nodes.append(node)
return nodes | 159,733 |
Iterator for nodes that affect a given wire
Args:
wire (tuple(Register, index)): the wire to be looked at.
only_ops (bool): True if only the ops nodes are wanted
otherwise all nodes are returned.
Yield:
DAGNode: the successive ops on the give... | def nodes_on_wire(self, wire, only_ops=False):
current_node = self.input_map.get(wire, None)
if not current_node:
raise DAGCircuitError('The given wire %s is not present in the circuit'
% str(wire))
more_nodes = True
while more_nod... | 159,755 |
Sets list of Instructions that depend on Parameter.
Args:
parameter (Parameter): the parameter to set
instr_params (list): List of (Instruction, int) tuples. Int is the
parameter index at which the parameter appears in the instruction. | def __setitem__(self, parameter, instr_params):
for instruction, param_index in instr_params:
assert isinstance(instruction, Instruction)
assert isinstance(param_index, int)
self._table[parameter] = instr_params | 159,758 |
Generate a TomographyBasis object.
See TomographyBasis for further details.abs
Args:
prep_fun (callable) optional: the function which adds preparation
gates to a circuit.
meas_fun (callable) optional: the function which adds measurement
gates to a circuit.
Returns:... | def tomography_basis(basis, prep_fun=None, meas_fun=None):
ret = TomographyBasis(basis)
ret.prep_fun = prep_fun
ret.meas_fun = meas_fun
return ret | 159,759 |
Return a results dict for a state or process tomography experiment.
Args:
results (Result): Results from execution of a process tomography
circuits on a backend.
name (string): The name of the circuit being reconstructed.
tomoset (tomography_set): the dict of tomography configur... | def tomography_data(results, name, tomoset):
labels = tomography_circuit_names(tomoset, name)
circuits = tomoset['circuits']
data = []
prep = None
for j, _ in enumerate(labels):
counts = marginal_counts(results.get_counts(labels[j]),
tomoset['qubits'])
... | 159,766 |
Reconstruct a matrix through linear inversion.
Args:
freqs (list[float]): list of observed frequences.
ops (list[np.array]): list of corresponding projectors.
weights (list[float] or array_like):
weights to be used for weighted fitting.
trace (float or None): trace of re... | def __tomo_linear_inv(freqs, ops, weights=None, trace=None):
# get weights matrix
if weights is not None:
W = np.array(weights)
if W.ndim == 1:
W = np.diag(W)
# Get basis S matrix
S = np.array([vectorize(m).conj()
for m in ops]).reshape(len(ops), ops[0... | 159,771 |
Returns the nearest positive semidefinite operator to an operator.
This method is based on reference [1]. It constrains positivity
by setting negative eigenvalues to zero and rescaling the positive
eigenvalues.
Args:
rho (array_like): the input operator.
epsilon(float or None): thresho... | def __wizard(rho, epsilon=None):
if epsilon is None:
epsilon = 0. # default value
dim = len(rho)
rho_wizard = np.zeros([dim, dim])
v, w = np.linalg.eigh(rho) # v eigenvecrors v[0] < v[1] <...
for j in range(dim):
if v[j] < epsilon:
tmp = v[j]
v[j] = 0.... | 159,772 |
Get the value of the Wigner function from measurement results.
Args:
q_result (Result): Results from execution of a state tomography
circuits on a backend.
meas_qubits (list[int]): a list of the qubit indexes measured.
labels (list[str]): a list of names of the c... | def wigner_data(q_result, meas_qubits, labels, shots=None):
num = len(meas_qubits)
dim = 2**num
p = [0.5 + 0.5 * np.sqrt(3), 0.5 - 0.5 * np.sqrt(3)]
parity = 1
for i in range(num):
parity = np.kron(parity, p)
w = [0] * len(labels)
wpt = 0
counts = [marginal_counts(q_resul... | 159,774 |
Add state preparation gates to a circuit.
Args:
circuit (QuantumCircuit): circuit to add a preparation to.
qreg (tuple(QuantumRegister,int)): quantum register to apply
preparation to.
op (tuple(str, int)): the basis label and index for the
preparation... | def prep_gate(self, circuit, qreg, op):
if self.prep_fun is None:
pass
else:
self.prep_fun(circuit, qreg, op) | 159,775 |
Add measurement gates to a circuit.
Args:
circuit (QuantumCircuit): circuit to add measurement to.
qreg (tuple(QuantumRegister,int)): quantum register being measured.
op (str): the basis label for the measurement. | def meas_gate(self, circuit, qreg, op):
if self.meas_fun is None:
pass
else:
self.meas_fun(circuit, qreg, op) | 159,776 |
A text-based job status checker
Args:
job (BaseJob): The job to check.
interval (int): The interval at which to check.
_interval_set (bool): Was interval time set by user?
quiet (bool): If True, do not print status messages.
output (file): The file like object to write statu... | def _text_checker(job, interval, _interval_set=False, quiet=False, output=sys.stdout):
status = job.status()
msg = status.value
prev_msg = msg
msg_len = len(msg)
if not quiet:
print('\r%s: %s' % ('Job Status', msg), end='', file=output)
while status.name not in ['DONE', 'CANCELLED'... | 159,779 |
Compute Euler angles for a single-qubit gate.
Find angles (theta, phi, lambda) such that
unitary_matrix = phase * Rz(phi) * Ry(theta) * Rz(lambda)
Args:
unitary_matrix (ndarray): 2x2 unitary matrix
Returns:
tuple: (theta, phi, lambda) Euler angles of SU(2)
Raises:
QiskitE... | def euler_angles_1q(unitary_matrix):
if unitary_matrix.shape != (2, 2):
raise QiskitError("euler_angles_1q: expected 2x2 matrix")
phase = la.det(unitary_matrix)**(-1.0/2.0)
U = phase * unitary_matrix # U in SU(2)
# OpenQASM SU(2) parameterization:
# U[0, 0] = exp(-i(phi+lambda)/2) * co... | 159,781 |
Return the gate u1, u2, or u3 implementing U with the fewest pulses.
The returned gate implements U exactly, not up to a global phase.
Args:
theta, phi, lam: input Euler rotation angles for a general U gate
Returns:
Gate: one of IdGate, U1Gate, U2Gate, U3Gate. | def simplify_U(theta, phi, lam):
gate = U3Gate(theta, phi, lam)
# Y rotation is 0 mod 2*pi, so the gate is a u1
if abs(gate.params[0] % (2.0 * math.pi)) < _CUTOFF_PRECISION:
gate = U1Gate(gate.params[0] + gate.params[1] + gate.params[2])
# Y rotation is pi/2 or -pi/2 mod 2*pi, so the gate i... | 159,782 |
Decompose a two-qubit gate over SU(2)+CNOT using the KAK decomposition.
Args:
unitary (Operator): a 4x4 unitary operator to decompose.
Returns:
QuantumCircuit: a circuit implementing the unitary over SU(2)+CNOT
Raises:
QiskitError: input not a unitary, or error in KAK decompositio... | def two_qubit_kak(unitary):
if hasattr(unitary, 'to_operator'):
# If input is a BaseOperator subclass this attempts to convert
# the object to an Operator so that we can extract the underlying
# numpy matrix from `Operator.data`.
unitary = unitary.to_operator().data
if hasat... | 159,783 |
Extends dag with virtual qubits that are in layout but not in the circuit yet.
Args:
dag (DAGCircuit): DAG to extend.
Returns:
DAGCircuit: An extended DAG.
Raises:
TranspilerError: If there is not layout in the property set or not set at init time. | def run(self, dag):
self.layout = self.layout or self.property_set['layout']
if self.layout is None:
raise TranspilerError("EnlargeWithAncilla requires property_set[\"layout\"] or"
" \"layout\" parameter to run")
layout_virtual_qubits = se... | 159,784 |
The backend configuration widget.
Args:
backend (IBMQbackend): The backend.
Returns:
grid: A GridBox widget. | def config_tab(backend):
status = backend.status().to_dict()
config = backend.configuration().to_dict()
config_dict = {**status, **config}
upper_list = ['n_qubits', 'operational',
'status_msg', 'pending_jobs',
'basis_gates', 'local', 'simulator']
lower_lis... | 159,786 |
The qubits properties widget
Args:
backend (IBMQbackend): The backend.
Returns:
VBox: A VBox widget. | def qubits_tab(backend):
props = backend.properties().to_dict()
header_html = "<div><font style='font-weight:bold'>{key}</font>: {value}</div>"
header_html = header_html.format(key='last_update_date',
value=props['last_update_date'])
update_date_widget = widget... | 159,787 |
The multiple qubit gate error widget.
Args:
backend (IBMQbackend): The backend.
Returns:
VBox: A VBox widget. | def gates_tab(backend):
config = backend.configuration().to_dict()
props = backend.properties().to_dict()
multi_qubit_gates = props['gates'][3*config['n_qubits']:]
header_html = "<div><font style='font-weight:bold'>{key}</font>: {value}</div>"
header_html = header_html.format(key='last_update... | 159,788 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.