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 multiplication
self._statevector = np.einsum(indexes, gate_tensor,
self._statevector,
dtype=complex,
casting='no') | 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 * [2])
# Apply matrix multiplication
self._statevector = np.einsum(indexes, gate_tensor,
self._statevector,
dtype=complex,
casting='no') | 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 string for 1-qubit matrix multiplication
random_number = self._local_random.rand()
if random_number < probabilities[0]:
return '0', probabilities[0]
# Else outcome was '1'
return '1', probabilities[1] | 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 of memory values in hex format. | 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(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)),
2 ** num_measured)
# Generate samples on measured qubits
samples = self._local_random.choice(range(2 ** num_measured),
num_samples, p=probabilities)
# Convert to bit-strings
memory = []
for sample in samples:
classical_memory = self._classical_memory
for count, (qubit, cmembit) in enumerate(sorted(measure_params)):
qubit_outcome = int((sample & (1 << count)) >> count)
membit = 1 << cmembit
classical_memory = (classical_memory & (~membit)) | (qubit_outcome << cmembit)
value = bin(classical_memory)[2:]
memory.append(hex(int(value, 2)))
return memory | 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) << cmembit)
if cregbit is not None:
regbit = 1 << cregbit
self._classical_register = \
(self._classical_register & (~regbit)) | (int(outcome) << cregbit)
# update quantum state
if outcome == '0':
update_diag = [[1 / np.sqrt(probability), 0], [0, 0]]
else:
update_diag = [[0, 0], [0, 1 / np.sqrt(probability)]]
# update classical state
self._add_unitary_single(update_diag, qubit) | 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:
update = [[0, 1 / np.sqrt(probability)], [0, 0]]
self._add_unitary_single(update, qubit) | 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._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
return
# If circuit contains a measure option then we can
# sample only if all following operations are measures
if measure_flag:
# If we find a non-measure instruction
# we cannot do measure sampling
if instruction.name not in ["measure", "barrier", "id", "u0"]:
self._sample_measure = False
return
elif instruction.name == "measure":
measure_flag = True
# If we made it to the end of the circuit without returning
# measure sampling is allowed
self._sample_measure = True | 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:
result_list.append(self.run_experiment(experiment))
end = time.time()
result = {'backend_name': self.name(),
'backend_version': self._configuration.backend_version,
'qobj_id': qobj.qobj_id,
'job_id': job_id,
'results': result_list,
'status': 'COMPLETED',
'success': True,
'time_taken': (end - start),
'header': qobj.header.as_dict()}
return Result.from_dict(result) | 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 multiplication
self._unitary = np.einsum(indexes, gate_tensor, self._unitary,
dtype=complex, casting='no') | 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_qubits)
# Apply matrix multiplication
self._unitary = np.einsum(indexes, gate_tensor, self._unitary,
dtype=complex, casting='no') | 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(),
'backend_version': self._configuration.backend_version,
'qobj_id': qobj.qobj_id,
'job_id': job_id,
'results': result_list,
'status': 'COMPLETED',
'success': True,
'time_taken': (end - start),
'header': qobj.header.as_dict()}
return Result.from_dict(result) | 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 be
broadcast from 1 bit to the max size of the rest of the args. Defaults
to all True if not specified.
Return:
type: partial function object | 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:]
if broadcastable is None:
blist = [True] * len(rargs)
else:
blist = broadcastable
if not all([_is_bit(arg) for arg in rargs]):
rarg_size = [1] * n_bits
for iarg, arg in enumerate(rargs):
if isinstance(arg, Register):
rarg_size[iarg] = len(arg)
elif isinstance(arg, list) and all([_is_bit(bit) for bit in arg]):
rarg_size[iarg] = len(arg)
elif _is_bit(arg):
rarg_size[iarg] = 1
else:
raise QiskitError('operation arguments must be qubits/cbits')
broadcast_size = max(rarg_size)
expanded_rargs = []
for arg, broadcast in zip(rargs, blist):
if isinstance(arg, Register):
arg = [(arg, i) for i in range(len(arg))]
elif isinstance(arg, tuple):
arg = [arg]
# now we should have a list of qubits
if isinstance(arg, list) and len(arg) == 1 and broadcast:
arg = arg * broadcast_size
if len(arg) != broadcast_size:
raise QiskitError('register size error')
expanded_rargs.append(arg)
rargs = expanded_rargs
if all([isinstance(arg, list) for arg in rargs]):
if all(rargs):
instructions = InstructionSet()
for irargs in zip(*rargs):
instructions.add(func(self, *params, *irargs),
[i for i in irargs if isinstance(i[0], QuantumRegister)],
[i for i in irargs if isinstance(i[0], ClassicalRegister)])
return instructions
else:
raise QiskitError('empty control or target argument')
return func(self, *params, *rargs)
return wrapper | 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 overlapped timeslots")
self._table[slot.channel].append(slot.interval)
self._timeslots = tuple(timeslots) | 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))
return 0 | 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)
options = {'width': figsize[0], 'height': figsize[1],
'slider': int(slider), 'show_legend': int(show_legend)}
# Process data and execute
div_number = str(time.time())
div_number = re.sub('[.]', '', div_number)
data_to_plot = []
rho_data = process_data(rho)
data_to_plot.append(dict(
data=rho_data
))
html = html_template.substitute({
'divNumber': div_number
})
javascript = javascript_template.substitute({
'divNumber': div_number,
'executions': data_to_plot,
'options': options
})
display(HTML(html + javascript)) | 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 a statevector or density
matrix, or if the state is not an multi-qubit quantum state. | 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)
if method == "city":
iplot_state_city(rho, figsize=figsize)
elif method == "paulivec":
iplot_state_paulivec(rho, figsize=figsize)
elif method == "qsphere":
iplot_state_qsphere(rho, figsize=figsize)
elif method == "bloch":
iplot_bloch_multivector(rho, figsize=figsize)
elif method == "hinton":
iplot_state_hinton(rho, figsize=figsize)
else:
raise VisualizationError('Invalid plot state method.') | 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.swap_paths = {}
self.swap_costs = {}
self.prog_graph = nx.Graph()
self.qarg_to_id = {}
self.pending_program_edges = []
self.prog2hw = {} | 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 is not a positive integer. | 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 implement more efficiently
# using Numpy.matrix_power
return Operator(
np.linalg.matrix_power(self.data, n), self.input_dims(),
self.output_dims()) | 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.output_dims()) | 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.
Raises:
QiskitError: if the operator dimension does not match the
specified QuantumState subsystem dimensions. | 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.ndim == 1:
# Return evolved statevector
return np.dot(self.data, state)
# Return evolved density matrix
return np.dot(
np.dot(self.data, state), np.transpose(np.conj(self.data)))
# Subsystem evolution
return self._evolve_subsystem(state, qargs) | 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.
Raises:
QiskitError: if the operator dimension does not match the
specified QuantumState subsystem dimensions. | 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_dims() != len(qargs) * (2,):
raise QiskitError(
"Operator input dimensions are not compatible with state subsystem dimensions."
)
if state.ndim == 1:
# Return evolved statevector
tensor = np.reshape(state, state_dims)
indices = [len(state_dims) - 1 - qubit for qubit in qargs]
tensor = self._einsum_matmul(tensor, mat, indices)
return np.reshape(tensor, state_size)
# Return evolved density matrix
tensor = np.reshape(state, 2 * state_dims)
indices = [len(state_dims) - 1 - qubit for qubit in qargs]
right_shift = len(state_dims)
# Left multiply by operator
tensor = self._einsum_matmul(tensor, mat, indices)
# Right multiply by adjoint operator
# We implement the transpose by doing left multiplication instead of right
# in the _einsum_matmul function
tensor = self._einsum_matmul(
tensor, np.conj(mat), indices, shift=right_shift)
return np.reshape(tensor, [state_size, state_size]) | 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.
seed (int): initial seed. | 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
self.requires.append(BarrierBeforeFinalMeasurements()) | 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:
QiskitError: If the returned numpy array does not have 2 (avg) or 3 (single)
indicies. | 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:
QiskitError: If the returned numpy array does not have 1 (avg) or 2 (single)
indicies. | 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 of bitstrings | 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 counts | 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 complex numbers | 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 data and execute
num = int(np.log2(len(rho)))
bloch_data = []
for i in range(num):
pauli_singles = [Pauli.pauli_single(num, i, 'X'), Pauli.pauli_single(num, i, 'Y'),
Pauli.pauli_single(num, i, 'Z')]
bloch_state = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_singles))
bloch_data.append(bloch_state)
div_number = str(time.time())
div_number = re.sub('[.]', '', div_number)
html = html_template.substitute({
'divNumber': div_number
})
javascript = javascript_template.substitute({
'data': bloch_data,
'divNumber': div_number,
'options': options
})
display(HTML(html + javascript)) | 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 configuration. | 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.qobj_model(**lo_config) | 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.
Raises:
PulseError: when LO frequencies are missing. | 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_freq
if _q_los == self.default_qubit_los:
return None
return _q_los | 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.
Raises:
PulseError: when LO frequencies are missing. | 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] = lo_freq
if _m_los == self.default_meas_los:
return None
return _m_los | 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 unrolled dag | 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 these
# instructions should be part of the device-reported basis. Currently, no
# backend reports "measure", for example.
continue
if node.name in self.basis: # If already a base, ignore.
continue
# TODO: allow choosing other possible decompositions
rule = node.op.definition
if not rule:
raise QiskitError("Cannot unroll the circuit to the given basis, %s. "
"No rule to expand instruction %s." %
(str(self.basis), node.op.name))
# hacky way to build a dag on the same register as the rule is defined
# TODO: need anonymous rules to address wires by index
decomposition = DAGCircuit()
decomposition.add_qreg(rule[0][1][0][0])
for inst in rule:
decomposition.apply_operation_back(*inst)
unrolled_dag = self.run(decomposition) # recursively unroll ops
dag.substitute_node_with_dag(node, unrolled_dag)
return dag | 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 = []
# Process data and execute
num = int(np.log2(len(rho)))
# get the eigenvectors and eigenvalues
weig, stateall = linalg.eigh(rho)
for _ in range(2**num):
# start with the max
probmix = weig.max()
prob_location = weig.argmax()
if probmix > 0.001:
# print("The " + str(k) + "th eigenvalue = " + str(probmix))
# get the max eigenvalue
state = stateall[:, prob_location]
loc = np.absolute(state).argmax()
# get the element location closes to lowest bin representation.
for j in range(2**num):
test = np.absolute(np.absolute(state[j]) -
np.absolute(state[loc]))
if test < 0.001:
loc = j
break
# remove the global phase
angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi)
angleset = np.exp(-1j*angles)
state = angleset*state
state.flatten()
spherepoints = []
for i in range(2**num):
# get x,y,z points
element = bin(i)[2:].zfill(num)
weight = element.count("1")
number_of_divisions = n_choose_k(num, weight)
weight_order = bit_string_index(element)
angle = weight_order * 2 * np.pi / number_of_divisions
zvalue = -2 * weight / num + 1
xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle)
yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle)
# get prob and angle - prob will be shade and angle color
prob = np.real(np.dot(state[i], state[i].conj()))
angles = (np.angle(state[i]) + 2 * np.pi) % (2 * np.pi)
qpoint = {
'x': xvalue,
'y': yvalue,
'z': zvalue,
'prob': prob,
'phase': angles
}
spherepoints.append(qpoint)
# Associate all points to one sphere
sphere = {
'points': spherepoints,
'eigenvalue': probmix
}
# Add sphere to the spheres array
qspheres_data.append(sphere)
weig[prob_location] = 0
div_number = str(time.time())
div_number = re.sub('[.]', '', div_number)
html = html_template.substitute({
'divNumber': div_number
})
javascript = javascript_template.substitute({
'data': qspheres_data,
'divNumber': div_number,
'options': options
})
display(HTML(html + javascript)) | 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
Raises:
ImportError: Requires matplotlib. | 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)
max_weight = 2 ** np.ceil(np.log(np.abs(rho).max()) / np.log(2))
datareal = np.real(rho)
dataimag = np.imag(rho)
column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
row_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
lx = len(datareal[0]) # Work out matrix dimensions
ly = len(datareal[:, 0])
# Real
ax1.patch.set_facecolor('gray')
ax1.set_aspect('equal', 'box')
ax1.xaxis.set_major_locator(plt.NullLocator())
ax1.yaxis.set_major_locator(plt.NullLocator())
for (x, y), w in np.ndenumerate(datareal):
color = 'white' if w > 0 else 'black'
size = np.sqrt(np.abs(w) / max_weight)
rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,
facecolor=color, edgecolor=color)
ax1.add_patch(rect)
ax1.set_xticks(np.arange(0, lx+0.5, 1))
ax1.set_yticks(np.arange(0, ly+0.5, 1))
ax1.set_yticklabels(row_names, fontsize=14)
ax1.set_xticklabels(column_names, fontsize=14, rotation=90)
ax1.autoscale_view()
ax1.invert_yaxis()
ax1.set_title('Real[rho]', fontsize=14)
# Imaginary
ax2.patch.set_facecolor('gray')
ax2.set_aspect('equal', 'box')
ax2.xaxis.set_major_locator(plt.NullLocator())
ax2.yaxis.set_major_locator(plt.NullLocator())
for (x, y), w in np.ndenumerate(dataimag):
color = 'white' if w > 0 else 'black'
size = np.sqrt(np.abs(w) / max_weight)
rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,
facecolor=color, edgecolor=color)
ax2.add_patch(rect)
if np.any(dataimag != 0):
ax2.set_xticks(np.arange(0, lx+0.5, 1))
ax2.set_yticks(np.arange(0, ly+0.5, 1))
ax2.set_yticklabels(row_names, fontsize=14)
ax2.set_xticklabels(column_names, fontsize=14, rotation=90)
ax2.autoscale_view()
ax2.invert_yaxis()
ax2.set_title('Imag[rho]', fontsize=14)
if title:
fig.suptitle(title, fontsize=16)
plt.tight_layout()
plt.close(fig)
return fig | 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.
Returns:
Figure: A matplotlib figure instance if `ax = None`.
Raises:
ImportError: Requires matplotlib. | 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 range(num):
ax = fig.add_subplot(1, num, i + 1, projection='3d')
pauli_singles = [
Pauli.pauli_single(num, i, 'X'),
Pauli.pauli_single(num, i, 'Y'),
Pauli.pauli_single(num, i, 'Z')
]
bloch_state = list(
map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_singles))
plot_bloch_vector(bloch_state, "qubit " + str(i), ax=ax,
figsize=figsize)
fig.suptitle(title, fontsize=16)
plt.close(fig)
return fig | 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 = linalg.eigh(rho)
for _ in range(2**num):
# start with the max
probmix = we.max()
prob_location = we.argmax()
if probmix > 0.001:
# get the max eigenvalue
state = stateall[:, prob_location]
loc = np.absolute(state).argmax()
# get the element location closes to lowest bin representation.
for j in range(2**num):
test = np.absolute(np.absolute(state[j]) -
np.absolute(state[loc]))
if test < 0.001:
loc = j
break
# remove the global phase
angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi)
angleset = np.exp(-1j*angles)
# print(state)
# print(angles)
state = angleset*state
# print(state)
state.flatten()
# start the plotting
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111, projection='3d')
ax.axes.set_xlim3d(-1.0, 1.0)
ax.axes.set_ylim3d(-1.0, 1.0)
ax.axes.set_zlim3d(-1.0, 1.0)
ax.set_aspect("equal")
ax.axes.grid(False)
# Plot semi-transparent sphere
u = np.linspace(0, 2 * np.pi, 25)
v = np.linspace(0, np.pi, 25)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(x, y, z, rstride=1, cstride=1, color='k',
alpha=0.05, linewidth=0)
# wireframe
# Get rid of the panes
ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the spines
ax.w_xaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.w_yaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.w_zaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
d = num
for i in range(2**num):
# get x,y,z points
element = bin(i)[2:].zfill(num)
weight = element.count("1")
zvalue = -2 * weight / d + 1
number_of_divisions = n_choose_k(d, weight)
weight_order = bit_string_index(element)
# if weight_order >= number_of_divisions / 2:
# com_key = compliment(element)
# weight_order_temp = bit_string_index(com_key)
# weight_order = np.floor(
# number_of_divisions / 2) + weight_order_temp + 1
angle = weight_order * 2 * np.pi / number_of_divisions
xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle)
yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle)
ax.plot([xvalue], [yvalue], [zvalue],
markerfacecolor=(.5, .5, .5),
markeredgecolor=(.5, .5, .5),
marker='o', markersize=10, alpha=1)
# get prob and angle - prob will be shade and angle color
prob = np.real(np.dot(state[i], state[i].conj()))
colorstate = phase_to_color_wheel(state[i])
a = Arrow3D([0, xvalue], [0, yvalue], [0, zvalue],
mutation_scale=20, alpha=prob, arrowstyle="-",
color=colorstate, lw=10)
ax.add_artist(a)
# add weight lines
for weight in range(d + 1):
theta = np.linspace(-2 * np.pi, 2 * np.pi, 100)
z = -2 * weight / d + 1
r = np.sqrt(1 - z**2)
x = r * np.cos(theta)
y = r * np.sin(theta)
ax.plot(x, y, z, color=(.5, .5, .5))
# add center point
ax.plot([0], [0], [0], markerfacecolor=(.5, .5, .5),
markeredgecolor=(.5, .5, .5), marker='o', markersize=10,
alpha=1)
we[prob_location] = 0
else:
break
plt.tight_layout()
plt.close(fig)
return fig | 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']:
props = backend.properties().to_dict()
print(backend.name())
print('='*len(backend.name()))
print('Configuration')
print('-'*13)
offset = ' '
upper_list = ['n_qubits', 'operational',
'status_msg', 'pending_jobs',
'basis_gates', 'local', 'simulator']
lower_list = list(set(config_dict.keys()).difference(upper_list))
# Remove gates because they are in a different tab
lower_list.remove('gates')
for item in upper_list+lower_list:
print(offset+item+':', config_dict[item])
# Stop here if simulator
if config['simulator']:
return
print()
qubit_header = 'Qubits [Name / Freq / T1 / T2 / U1 err / U2 err / U3 err / Readout err]'
print(qubit_header)
print('-'*len(qubit_header))
sep = ' / '
for qub in range(len(props['qubits'])):
name = 'Q%s' % qub
qubit_data = props['qubits'][qub]
gate_data = props['gates'][3*qub:3*qub+3]
t1_info = qubit_data[0]
t2_info = qubit_data[1]
freq_info = qubit_data[2]
readout_info = qubit_data[3]
freq = str(round(freq_info['value'], 5))+' '+freq_info['unit']
T1 = str(round(t1_info['value'], # pylint: disable=invalid-name
5))+' ' + t1_info['unit']
T2 = str(round(t2_info['value'], # pylint: disable=invalid-name
5))+' ' + t2_info['unit']
# pylint: disable=invalid-name
U1 = str(round(gate_data[0]['parameters'][0]['value'], 5))
# pylint: disable=invalid-name
U2 = str(round(gate_data[1]['parameters'][0]['value'], 5))
# pylint: disable=invalid-name
U3 = str(round(gate_data[2]['parameters'][0]['value'], 5))
readout_error = str(round(readout_info['value'], 5))
qstr = sep.join([name, freq, T1, T2, U1, U2, U3, readout_error])
print(offset+qstr)
print()
multi_qubit_gates = props['gates'][3*config['n_qubits']:]
multi_header = 'Multi-Qubit Gates [Name / Type / Gate Error]'
print(multi_header)
print('-'*len(multi_header))
for gate in multi_qubit_gates:
name = gate['name']
ttype = gate['gate']
error = str(round(gate['parameters'][0]['value'], 5))
mstr = sep.join([name, ttype, error])
print(offset+mstr) | 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` defaults to single cycle.
phase: Pulse phase.
name: Name of pulse. | 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` defaults to single cycle.
phase: Pulse phase.
name: Name of pulse. | 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.
phase: Pulse phase.
name: Name of pulse. | 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.
name: Name 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' %
(backend_cls, err))
return backend_instance | 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 = "%s[%s]" % (wire[0].name, wire[1])
inp_node = DAGNode(data_dict={'type': 'in', 'name': wire_name, 'wire': wire},
nid=input_map_wire)
outp_node = DAGNode(data_dict={'type': 'out', 'name': wire_name, 'wire': wire},
nid=output_map_wire)
self._id_to_node[input_map_wire] = inp_node
self._id_to_node[output_map_wire] = outp_node
self.input_map[wire] = inp_node
self.output_map[wire] = outp_node
self._multi_graph.add_node(inp_node)
self._multi_graph.add_node(outp_node)
self._multi_graph.add_edge(inp_node,
outp_node)
self._multi_graph.adj[inp_node][outp_node][0]["name"] \
= "%s[%s]" % (wire[0].name, wire[1])
self._multi_graph.adj[inp_node][outp_node][0]["wire"] \
= wire
else:
raise DAGCircuitError("duplicate wire %s" % (wire,)) | 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 amap | 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): optional condition (ClassicalRegister, int) | 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 graph
self._max_node_id += 1
new_node = DAGNode(data_dict=node_properties, nid=self._max_node_id)
self._multi_graph.add_node(new_node)
self._id_to_node[self._max_node_id] = new_node | 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_map keys
valmap (dict): a map whose keys are wire_map values
Raises:
DAGCircuitError: if wire_map not valid | 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)
if v not in valmap:
raise DAGCircuitError("invalid wire mapping value %s" % vname)
if type(k) is not type(v):
raise DAGCircuitError("inconsistent wire_map at (%s,%s)" %
(kname, vname)) | 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 = (condition[0], 0)
new_condition = (wire_map.get(bit0, bit0)[0], condition[1])
return new_condition | 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 node.
node (DAGNode): a node in the dag
Raises:
DAGCircuitError: if check doesn't pass. | 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:
raise DAGCircuitError("expected %d wires, got %d"
% (wire_tot, len(wires))) | 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_map | 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
by qargs first, then cargs, then conditions.
Raises:
DAGCircuitError: if met with unexpected predecessor/successors | 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 = self._id_to_node[node]
condition = node.condition
# the dag must be ammended if used in a
# conditional context. delete the op nodes and replay
# them with the condition.
if condition:
input_dag.add_creg(condition[0])
to_replay = []
for sorted_node in input_dag.topological_nodes():
if sorted_node.type == "op":
sorted_node.op.control = condition
to_replay.append(sorted_node)
for input_node in input_dag.op_nodes():
input_dag.remove_op_node(input_node)
for replay_node in to_replay:
input_dag.apply_operation_back(replay_node.op, replay_node.qargs,
replay_node.cargs, condition=condition)
if wires is None:
qwires = [w for w in input_dag.wires if isinstance(w[0], QuantumRegister)]
cwires = [w for w in input_dag.wires if isinstance(w[0], ClassicalRegister)]
wires = qwires + cwires
self._check_wires_list(wires, node)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: QuantumRegister(1, 'proxy') for w in wires}
add_qregs = self._check_edgemap_registers(proxy_map,
input_dag.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(proxy_map,
input_dag.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Replace the node by iterating through the input_circuit.
# Constructing and checking the validity of the wire_map.
# If a gate is conditioned, we expect the replacement subcircuit
# to depend on those control bits as well.
if node.type != "op":
raise DAGCircuitError("expected node type \"op\", got %s"
% node.type)
condition_bit_list = self._bits_in_condition(node.condition)
wire_map = {k: v for k, v in zip(wires,
[i for s in [node.qargs,
node.cargs,
condition_bit_list]
for i in s])}
self._check_wiremap_validity(wire_map, wires, self.input_map)
pred_map, succ_map = self._make_pred_succ_maps(node)
full_pred_map, full_succ_map = self._full_pred_succ_maps(pred_map, succ_map,
input_dag, wire_map)
# Now that we know the connections, delete node
self._multi_graph.remove_node(node)
# Iterate over nodes of input_circuit
for sorted_node in input_dag.topological_op_nodes():
# Insert a new node
condition = self._map_condition(wire_map, sorted_node.condition)
m_qargs = list(map(lambda x: wire_map.get(x, x),
sorted_node.qargs))
m_cargs = list(map(lambda x: wire_map.get(x, x),
sorted_node.cargs))
self._add_op_node(sorted_node.op, m_qargs, m_cargs, condition)
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self._multi_graph.add_edge(full_pred_map[q],
self._id_to_node[self._max_node_id],
name="%s[%s]" % (q[0].name, q[1]),
wire=q)
full_pred_map[q] = self._id_to_node[self._max_node_id]
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self._multi_graph.add_edge(full_pred_map[w],
full_succ_map[w],
name="%s[%s]" % (w[0].name, w[1]),
wire=w)
o_pred = list(self._multi_graph.predecessors(self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise DAGCircuitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise DAGCircuitError("expected 1 predecessor to pass filter")
self._multi_graph.remove_edge(p[0], self.output_map[w]) | 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 given wire
Raises:
DAGCircuitError: if the given wire doesn't exist in the DAG | 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_nodes:
more_nodes = False
# allow user to just get ops on the wire - not the input/output nodes
if current_node.type == 'op' or not only_ops:
yield current_node
# find the adjacent node that takes the wire being looked at as input
for node, edges in self._multi_graph.adj[current_node].items():
if any(wire == edge['wire'] for edge in edges.values()):
current_node = node
more_nodes = True
break | 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:
TomographyBasis: A tomography basis. | 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 configurations.
Returns:
list: A list of dicts for the outcome of each process tomography
measurement circuit. | 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'])
shots = sum(counts.values())
meas = circuits[j]['meas']
prep = circuits[j].get('prep', None)
meas_qubits = sorted(meas.keys())
if prep:
prep_qubits = sorted(prep.keys())
circuit = {}
for c in counts.keys():
circuit[c] = {}
circuit[c]['meas'] = [(meas[meas_qubits[k]], int(c[-1 - k]))
for k in range(len(meas_qubits))]
if prep:
circuit[c]['prep'] = [prep[prep_qubits[k]]
for k in range(len(prep_qubits))]
data.append({'counts': counts, 'shots': shots, 'circuit': circuit})
ret = {'data': data, 'meas_basis': tomoset['meas_basis']}
if prep:
ret['prep_basis'] = tomoset['prep_basis']
return ret | 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 returned operator.
Returns:
numpy.array: A numpy array of the reconstructed operator. | 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].size)
if weights is not None:
S = np.dot(W, S) # W.S
# get frequencies vec
v = np.array(freqs) # |f>
if weights is not None:
v = np.dot(W, freqs) # W.|f>
Sdg = S.T.conj() # S^*.W^*
inv = np.linalg.pinv(np.dot(Sdg, S)) # (S^*.W^*.W.S)^-1
# linear inversion of freqs
ret = devectorize(np.dot(inv, np.dot(Sdg, v)))
# renormalize to input trace value
if trace is not None:
ret = trace * ret / np.trace(ret)
return ret | 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): threshold (>=0) for truncating small
eigenvalues values to zero.
Returns:
numpy.array: A positive semidefinite numpy array. | 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.
# redistribute loop
x = 0.
for k in range(j + 1, dim):
x += tmp / (dim - (j + 1))
v[k] = v[k] + tmp / (dim - (j + 1))
for j in range(dim):
rho_wizard = rho_wizard + v[j] * outer(w[:, j])
return rho_wizard | 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 circuits
shots (int): number of shots
Returns:
list: The values of the Wigner function at measured points in
phase space | 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_result.get_counts(circ), meas_qubits)
for circ in labels]
for entry in counts:
x = [0] * dim
for i in range(dim):
if bin(i)[2:].zfill(num) in entry:
x[i] = float(entry[bin(i)[2:].zfill(num)])
if shots is None:
shots = np.sum(x)
for i in range(dim):
w[wpt] = w[wpt] + (x[i] / shots) * parity[i]
wpt += 1
return w | 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 op. | 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 status messages to.
By default this is sys.stdout. | 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', 'ERROR']:
time.sleep(interval)
status = job.status()
msg = status.value
if status.name == 'QUEUED':
msg += ' (%s)' % job.queue_position()
if not _interval_set:
interval = max(job.queue_position(), 2)
else:
if not _interval_set:
interval = 2
# Adjust length of message so there are no artifacts
if len(msg) < msg_len:
msg += ' ' * (msg_len - len(msg))
elif len(msg) > msg_len:
msg_len = len(msg)
if msg != prev_msg and not quiet:
print('\r%s: %s' % ('Job Status', msg), end='', file=output)
prev_msg = msg
if not quiet:
print('', file=output) | 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:
QiskitError: if unitary_matrix not 2x2, or failure | 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) * cos(theta/2)
# U[0, 1] = -exp(-i(phi-lambda)/2) * sin(theta/2)
# U[1, 0] = exp(i(phi-lambda)/2) * sin(theta/2)
# U[1, 1] = exp(i(phi+lambda)/2) * cos(theta/2)
# Find theta
if abs(U[0, 0]) > _CUTOFF_PRECISION:
theta = 2 * math.acos(abs(U[0, 0]))
else:
theta = 2 * math.asin(abs(U[1, 0]))
# Find phi and lambda
phase11 = 0.0
phase10 = 0.0
if abs(math.cos(theta/2.0)) > _CUTOFF_PRECISION:
phase11 = U[1, 1] / math.cos(theta/2.0)
if abs(math.sin(theta/2.0)) > _CUTOFF_PRECISION:
phase10 = U[1, 0] / math.sin(theta/2.0)
phiplambda = 2 * math.atan2(np.imag(phase11), np.real(phase11))
phimlambda = 2 * math.atan2(np.imag(phase10), np.real(phase10))
phi = 0.0
if abs(U[0, 0]) > _CUTOFF_PRECISION and abs(U[1, 0]) > _CUTOFF_PRECISION:
phi = (phiplambda + phimlambda) / 2.0
lamb = (phiplambda - phimlambda) / 2.0
else:
if abs(U[0, 0]) < _CUTOFF_PRECISION:
lamb = -phimlambda
else:
lamb = phiplambda
# Check the solution
Rzphi = np.array([[np.exp(-1j*phi/2.0), 0],
[0, np.exp(1j*phi/2.0)]], dtype=complex)
Rytheta = np.array([[np.cos(theta/2.0), -np.sin(theta/2.0)],
[np.sin(theta/2.0), np.cos(theta/2.0)]], dtype=complex)
Rzlambda = np.array([[np.exp(-1j*lamb/2.0), 0],
[0, np.exp(1j*lamb/2.0)]], dtype=complex)
V = np.dot(Rzphi, np.dot(Rytheta, Rzlambda))
if la.norm(V - U) > _CUTOFF_PRECISION:
raise QiskitError("euler_angles_1q: incorrect result")
return theta, phi, lamb | 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 is a u2
if isinstance(gate, U3Gate):
# theta = pi/2 + 2*k*pi
if abs((gate.params[0] - math.pi / 2) % (2.0 * math.pi)) < _CUTOFF_PRECISION:
gate = U2Gate(gate.params[1],
gate.params[2] + (gate.params[0] - math.pi / 2))
# theta = -pi/2 + 2*k*pi
if abs((gate.params[0] + math.pi / 2) % (2.0 * math.pi)) < _CUTOFF_PRECISION:
gate = U2Gate(gate.params[1] + math.pi,
gate.params[2] - math.pi + (gate.params[0] + math.pi / 2))
# u1 and lambda is 0 mod 4*pi so gate is nop
if isinstance(gate, U1Gate) and abs(gate.params[0] % (4.0 * math.pi)) < _CUTOFF_PRECISION:
gate = IdGate()
return gate | 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 decomposition. | 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 hasattr(unitary, 'to_matrix'):
# If input is Gate subclass or some other class object that has
# a to_matrix method this will call that method.
unitary = unitary.to_matrix()
# Convert to numpy array incase not already an array
unitary_matrix = np.array(unitary, dtype=complex)
# Check input is a 2-qubit unitary
if unitary_matrix.shape != (4, 4):
raise QiskitError("two_qubit_kak: Expected 4x4 matrix")
if not is_unitary_matrix(unitary_matrix):
raise QiskitError("Input matrix is not unitary.")
phase = la.det(unitary_matrix)**(-1.0/4.0)
# Make it in SU(4), correct phase at the end
U = phase * unitary_matrix
# B changes to the Bell basis
B = (1.0/math.sqrt(2)) * np.array([[1, 1j, 0, 0],
[0, 0, 1j, 1],
[0, 0, 1j, -1],
[1, -1j, 0, 0]], dtype=complex)
# We also need B.conj().T below
Bdag = B.conj().T
# U' = Bdag . U . B
Uprime = Bdag.dot(U.dot(B))
# M^2 = trans(U') . U'
M2 = Uprime.T.dot(Uprime)
# Diagonalize M2
# Must use diagonalization routine which finds a real orthogonal matrix P
# when M2 is real.
D, P = la.eig(M2)
D = np.diag(D)
# If det(P) == -1 then in O(4), apply a swap to make P in SO(4)
if abs(la.det(P)+1) < 1e-5:
swap = np.array([[1, 0, 0, 0],
[0, 0, 1, 0],
[0, 1, 0, 0],
[0, 0, 0, 1]], dtype=complex)
P = P.dot(swap)
D = swap.dot(D.dot(swap))
Q = np.sqrt(D) # array from elementwise sqrt
# Want to take square root so that Q has determinant 1
if abs(la.det(Q)+1) < 1e-5:
Q[0, 0] = -Q[0, 0]
# Q^-1*P.T = P' -> QP' = P.T (solve for P' using Ax=b)
Pprime = la.solve(Q, P.T)
# K' now just U' * P * P'
Kprime = Uprime.dot(P.dot(Pprime))
K1 = B.dot(Kprime.dot(P.dot(Bdag)))
A = B.dot(Q.dot(Bdag))
K2 = B.dot(P.T.dot(Bdag))
# KAK = K1 * A * K2
KAK = K1.dot(A.dot(K2))
# Verify decomp matches input unitary.
if la.norm(KAK - U) > 1e-6:
raise QiskitError("two_qubit_kak: KAK decomposition " +
"does not return input unitary.")
# Compute parameters alpha, beta, gamma so that
# A = exp(i * (alpha * XX + beta * YY + gamma * ZZ))
xx = np.array([[0, 0, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 0],
[1, 0, 0, 0]], dtype=complex)
yy = np.array([[0, 0, 0, -1],
[0, 0, 1, 0],
[0, 1, 0, 0],
[-1, 0, 0, 0]], dtype=complex)
zz = np.array([[1, 0, 0, 0],
[0, -1, 0, 0],
[0, 0, -1, 0],
[0, 0, 0, 1]], dtype=complex)
A_real_tr = A.real.trace()
alpha = math.atan2(A.dot(xx).imag.trace(), A_real_tr)
beta = math.atan2(A.dot(yy).imag.trace(), A_real_tr)
gamma = math.atan2(A.dot(zz).imag.trace(), A_real_tr)
# K1 = kron(U1, U2) and K2 = kron(V1, V2)
# Find the matrices U1, U2, V1, V2
# Find a block in K1 where U1_ij * [U2] is not zero
L = K1[0:2, 0:2]
if la.norm(L) < 1e-9:
L = K1[0:2, 2:4]
if la.norm(L) < 1e-9:
L = K1[2:4, 2:4]
# Remove the U1_ij prefactor
Q = L.dot(L.conj().T)
U2 = L / math.sqrt(Q[0, 0].real)
# Now grab U1 given we know U2
R = K1.dot(np.kron(np.identity(2), U2.conj().T))
U1 = np.zeros((2, 2), dtype=complex)
U1[0, 0] = R[0, 0]
U1[0, 1] = R[0, 2]
U1[1, 0] = R[2, 0]
U1[1, 1] = R[2, 2]
# Repeat K1 routine for K2
L = K2[0:2, 0:2]
if la.norm(L) < 1e-9:
L = K2[0:2, 2:4]
if la.norm(L) < 1e-9:
L = K2[2:4, 2:4]
Q = np.dot(L, np.transpose(L.conjugate()))
V2 = L / np.sqrt(Q[0, 0])
R = np.dot(K2, np.kron(np.identity(2), np.transpose(V2.conjugate())))
V1 = np.zeros_like(U1)
V1[0, 0] = R[0, 0]
V1[0, 1] = R[0, 2]
V1[1, 0] = R[2, 0]
V1[1, 1] = R[2, 2]
if la.norm(np.kron(U1, U2) - K1) > 1e-4:
raise QiskitError("two_qubit_kak: K1 != U1 x U2")
if la.norm(np.kron(V1, V2) - K2) > 1e-4:
raise QiskitError("two_qubit_kak: K2 != V1 x V2")
test = la.expm(1j*(alpha * xx + beta * yy + gamma * zz))
if la.norm(A - test) > 1e-4:
raise QiskitError("two_qubit_kak: " +
"Matrix A does not match xx,yy,zz decomposition.")
# Circuit that implements K1 * A * K2 (up to phase), using
# Vatan and Williams Fig. 6 of quant-ph/0308006v3
# Include prefix and suffix single-qubit gates into U2, V1 respectively.
V2 = np.array([[np.exp(1j*np.pi/4), 0],
[0, np.exp(-1j*np.pi/4)]], dtype=complex).dot(V2)
U1 = U1.dot(np.array([[np.exp(-1j*np.pi/4), 0],
[0, np.exp(1j*np.pi/4)]], dtype=complex))
# Corrects global phase: exp(ipi/4)*phase'
U1 = U1.dot(np.array([[np.exp(1j*np.pi/4), 0],
[0, np.exp(1j*np.pi/4)]], dtype=complex))
U1 = phase.conjugate() * U1
# Test
g1 = np.kron(V1, V2)
g2 = np.array([[1, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 0]], dtype=complex)
theta = 2*gamma - np.pi/2
Ztheta = np.array([[np.exp(1j*theta/2), 0],
[0, np.exp(-1j*theta/2)]], dtype=complex)
kappa = np.pi/2 - 2*alpha
Ykappa = np.array([[math.cos(kappa/2), math.sin(kappa/2)],
[-math.sin(kappa/2), math.cos(kappa/2)]], dtype=complex)
g3 = np.kron(Ztheta, Ykappa)
g4 = np.array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0]], dtype=complex)
zeta = 2*beta - np.pi/2
Yzeta = np.array([[math.cos(zeta/2), math.sin(zeta/2)],
[-math.sin(zeta/2), math.cos(zeta/2)]], dtype=complex)
g5 = np.kron(np.identity(2), Yzeta)
g6 = g2
g7 = np.kron(U1, U2)
V = g2.dot(g1)
V = g3.dot(V)
V = g4.dot(V)
V = g5.dot(V)
V = g6.dot(V)
V = g7.dot(V)
if la.norm(V - U*phase.conjugate()) > 1e-6:
raise QiskitError("two_qubit_kak: " +
"sequence incorrect, unknown error")
v1_param = euler_angles_1q(V1)
v2_param = euler_angles_1q(V2)
u1_param = euler_angles_1q(U1)
u2_param = euler_angles_1q(U2)
v1_gate = U3Gate(v1_param[0], v1_param[1], v1_param[2])
v2_gate = U3Gate(v2_param[0], v2_param[1], v2_param[2])
u1_gate = U3Gate(u1_param[0], u1_param[1], u1_param[2])
u2_gate = U3Gate(u2_param[0], u2_param[1], u2_param[2])
q = QuantumRegister(2)
return_circuit = QuantumCircuit(q)
return_circuit.append(v1_gate, [q[1]])
return_circuit.append(v2_gate, [q[0]])
return_circuit.append(CnotGate(), [q[0], q[1]])
gate = U3Gate(0.0, 0.0, -2.0*gamma + np.pi/2.0)
return_circuit.append(gate, [q[1]])
gate = U3Gate(-np.pi/2.0 + 2.0*alpha, 0.0, 0.0)
return_circuit.append(gate, [q[0]])
return_circuit.append(CnotGate(), [q[1], q[0]])
gate = U3Gate(-2.0*beta + np.pi/2.0, 0.0, 0.0)
return_circuit.append(gate, [q[0]])
return_circuit.append(CnotGate(), [q[0], q[1]])
return_circuit.append(u1_gate, [q[1]])
return_circuit.append(u2_gate, [q[0]])
return return_circuit | 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 = self.layout.get_virtual_bits().keys()
new_qregs = set(virtual_qubit[0] for virtual_qubit in layout_virtual_qubits
if virtual_qubit not in dag.wires)
for qreg in new_qregs:
dag.add_qreg(qreg)
return dag | 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_list = list(set(config_dict.keys()).difference(upper_list))
# Remove gates because they are in a different tab
lower_list.remove('gates')
upper_str = "<table>"
upper_str +=
footer = "</table>"
# Upper HBox widget data
upper_str += "<tr><th>Property</th><th>Value</th></tr>"
for key in upper_list:
upper_str += "<tr><td><font style='font-weight:bold'>%s</font></td><td>%s</td></tr>" % (
key, config_dict[key])
upper_str += footer
upper_table = widgets.HTML(
value=upper_str, layout=widgets.Layout(width='100%', grid_area='left'))
image_widget = widgets.Output(
layout=widgets.Layout(display='flex-inline', grid_area='right',
padding='10px 10px 10px 10px',
width='auto', max_height='300px',
align_items='center'))
if not config['simulator']:
with image_widget:
gate_map = plot_gate_map(backend)
display(gate_map)
plt.close(gate_map)
lower_str = "<table>"
lower_str +=
lower_str += "<tr><th></th><th></th></tr>"
for key in lower_list:
if key != 'name':
lower_str += "<tr><td>%s</td><td>%s</td></tr>" % (
key, config_dict[key])
lower_str += footer
lower_table = widgets.HTML(value=lower_str,
layout=widgets.Layout(
width='auto',
grid_area='bottom'))
grid = widgets.GridBox(children=[upper_table, image_widget, lower_table],
layout=widgets.Layout(
grid_template_rows='auto auto',
grid_template_columns='25% 25% 25% 25%',
grid_template_areas=,
grid_gap='0px 0px'))
return grid | 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 = widgets.HTML(value=header_html)
qubit_html = "<table>"
qubit_html +=
qubit_html += "<tr><th></th><th>Frequency</th><th>T1</th><th>T2</th>"
qubit_html += "<th>U1 gate error</th><th>U2 gate error</th><th>U3 gate error</th>"
qubit_html += "<th>Readout error</th></tr>"
qubit_footer = "</table>"
for qub in range(len(props['qubits'])):
name = 'Q%s' % qub
qubit_data = props['qubits'][qub]
gate_data = props['gates'][3*qub:3*qub+3]
t1_info = qubit_data[0]
t2_info = qubit_data[1]
freq_info = qubit_data[2]
readout_info = qubit_data[3]
freq = str(round(freq_info['value'], 5))+' '+freq_info['unit']
T1 = str(round(t1_info['value'], # pylint: disable=invalid-name
5))+' ' + t1_info['unit']
T2 = str(round(t2_info['value'], # pylint: disable=invalid-name
5))+' ' + t2_info['unit']
# pylint: disable=invalid-name
U1 = str(round(gate_data[0]['parameters'][0]['value'], 5))
# pylint: disable=invalid-name
U2 = str(round(gate_data[1]['parameters'][0]['value'], 5))
# pylint: disable=invalid-name
U3 = str(round(gate_data[2]['parameters'][0]['value'], 5))
readout_error = round(readout_info['value'], 5)
qubit_html += "<tr><td><font style='font-weight:bold'>%s</font></td><td>%s</td>"
qubit_html += "<td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>"
qubit_html = qubit_html % (name, freq, T1, T2, U1, U2, U3, readout_error)
qubit_html += qubit_footer
qubit_widget = widgets.HTML(value=qubit_html)
out = widgets.VBox([update_date_widget,
qubit_widget])
return out | 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_date',
value=props['last_update_date'])
update_date_widget = widgets.HTML(value=header_html,
layout=widgets.Layout(grid_area='top'))
gate_html = "<table>"
gate_html +=
gate_html += "<tr><th></th><th>Type</th><th>Gate error</th></tr>"
gate_footer = "</table>"
# Split gates into two columns
left_num = math.ceil(len(multi_qubit_gates)/3)
mid_num = math.ceil((len(multi_qubit_gates)-left_num)/2)
left_table = gate_html
for qub in range(left_num):
gate = multi_qubit_gates[qub]
name = gate['name']
ttype = gate['gate']
error = round(gate['parameters'][0]['value'], 5)
left_table += "<tr><td><font style='font-weight:bold'>%s</font>"
left_table += "</td><td>%s</td><td>%s</td></tr>"
left_table = left_table % (name, ttype, error)
left_table += gate_footer
middle_table = gate_html
for qub in range(left_num, left_num+mid_num):
gate = multi_qubit_gates[qub]
name = gate['name']
ttype = gate['gate']
error = round(gate['parameters'][0]['value'], 5)
middle_table += "<tr><td><font style='font-weight:bold'>%s</font>"
middle_table += "</td><td>%s</td><td>%s</td></tr>"
middle_table = middle_table % (name, ttype, error)
middle_table += gate_footer
right_table = gate_html
for qub in range(left_num+mid_num, len(multi_qubit_gates)):
gate = multi_qubit_gates[qub]
name = gate['name']
ttype = gate['gate']
error = round(gate['parameters'][0]['value'], 5)
right_table += "<tr><td><font style='font-weight:bold'>%s</font>"
right_table += "</td><td>%s</td><td>%s</td></tr>"
right_table = right_table % (name, ttype, error)
right_table += gate_footer
left_table_widget = widgets.HTML(value=left_table,
layout=widgets.Layout(grid_area='left'))
middle_table_widget = widgets.HTML(value=middle_table,
layout=widgets.Layout(grid_area='middle'))
right_table_widget = widgets.HTML(value=right_table,
layout=widgets.Layout(grid_area='right'))
grid = widgets.GridBox(children=[update_date_widget,
left_table_widget,
middle_table_widget,
right_table_widget],
layout=widgets.Layout(
grid_template_rows='auto auto',
grid_template_columns='33% 33% 33%',
grid_template_areas=,
grid_gap='0px 0px'))
return grid | 159,788 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.