docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
A decorator for generating SamplePulse from python callable.
Args:
func (callable): A function describing pulse envelope.
Raises:
PulseError: when invalid function is specified. | def functional_pulse(func):
@functools.wraps(func)
def to_pulse(duration, *args, name=None, **kwargs):
if isinstance(duration, int) and duration > 0:
samples = func(duration, *args, **kwargs)
samples = np.asarray(samples, dtype=np.complex128)
return Samp... | 159,170 |
Create a DAG node out of a parsed AST op node.
Args:
name (str): operation name to apply to the dag.
params (list): op parameters
qargs (list(QuantumRegister, int)): qubits to attach to
Raises:
QiskitError: if encountering a non-basis opaque gate | def _create_dag_op(self, name, params, qargs):
if name == "u0":
op_class = U0Gate
elif name == "u1":
op_class = U1Gate
elif name == "u2":
op_class = U2Gate
elif name == "u3":
op_class = U3Gate
elif name == "x":
... | 159,183 |
Create empty schedule.
Args:
*schedules: Child Schedules of this parent Schedule. May either be passed as
the list of schedules, or a list of (start_time, schedule) pairs
name: Name of this schedule
Raises:
PulseError: If timeslots intercept. | def __init__(self, *schedules: List[Union[ScheduleComponent, Tuple[int, ScheduleComponent]]],
name: str = None):
self._name = name
try:
timeslots = []
children = []
for sched_pair in schedules:
# recreate as sequence starting ... | 159,185 |
Return duration of supplied channels.
Args:
*channels: Supplied channels | def ch_duration(self, *channels: List[Channel]) -> int:
return self.timeslots.ch_duration(*channels) | 159,186 |
Return minimum start time for supplied channels.
Args:
*channels: Supplied channels | def ch_start_time(self, *channels: List[Channel]) -> int:
return self.timeslots.ch_start_time(*channels) | 159,187 |
Return maximum start time for supplied channels.
Args:
*channels: Supplied channels | def ch_stop_time(self, *channels: List[Channel]) -> int:
return self.timeslots.ch_stop_time(*channels) | 159,188 |
Iterable for flattening Schedule tree.
Args:
time: Shifted time due to parent
Yields:
Tuple[int, ScheduleComponent]: Tuple containing time `ScheduleComponent` starts
at and the flattened `ScheduleComponent`. | def _instructions(self, time: int = 0) -> Iterable[Tuple[int, 'Instruction']]:
for insert_time, child_sched in self.children:
yield from child_sched._instructions(time + insert_time) | 159,189 |
Truncate small values of a complex array.
Args:
array (array_like): array to truncte small values.
epsilon (float): threshold.
Returns:
np.array: A new operator with small values set to zero. | def chop(array, epsilon=1e-10):
ret = np.array(array)
if np.isrealobj(ret):
ret[abs(ret) < epsilon] = 0.0
else:
ret.real[abs(ret.real) < epsilon] = 0.0
ret.imag[abs(ret.imag) < epsilon] = 0.0
return ret | 159,209 |
Construct the outer product of two vectors.
The second vector argument is optional, if absent the projector
of the first vector will be returned.
Args:
vector1 (ndarray): the first vector.
vector2 (ndarray): the (optional) second vector.
Returns:
np.array: The matrix |v1><v2|. | def outer(vector1, vector2=None):
if vector2 is None:
vector2 = np.array(vector1).conj()
else:
vector2 = np.array(vector2).conj()
return np.outer(vector1, vector2) | 159,210 |
Calculate the concurrence.
Args:
state (np.array): a quantum state (1x4 array) or a density matrix (4x4
array)
Returns:
float: concurrence.
Raises:
Exception: if attempted on more than two qubits. | def concurrence(state):
rho = np.array(state)
if rho.ndim == 1:
rho = outer(state)
if len(state) != 4:
raise Exception("Concurrence is only defined for more than two qubits")
YY = np.fliplr(np.diag([-1, 1, 1, -1]))
A = rho.dot(YY).dot(rho.conj()).dot(YY)
w = la.eigh(A, eigv... | 159,213 |
Compute the Shannon entropy of a probability vector.
The shannon entropy of a probability vector pv is defined as
$H(pv) = - \\sum_j pv[j] log_b (pv[j])$ where $0 log_b 0 = 0$.
Args:
pvec (array_like): a probability vector.
base (int): the base of the logarith
Returns:
float: ... | def shannon_entropy(pvec, base=2):
# pylint: disable=missing-docstring
if base == 2:
def logfn(x):
return - x * np.log2(x)
elif base == np.e:
def logfn(x):
return - x * np.log(x)
else:
def logfn(x):
return -x * np.log(x) / np.log(base)
... | 159,214 |
Compute the von-Neumann entropy of a quantum state.
Args:
state (array_like): a density matrix or state vector.
Returns:
float: The von-Neumann entropy S(rho). | def entropy(state):
rho = np.array(state)
if rho.ndim == 1:
return 0
evals = np.maximum(np.linalg.eigvalsh(state), 0.)
return shannon_entropy(evals, base=np.e) | 159,215 |
Compute the mutual information of a bipartite state.
Args:
state (array_like): a bipartite state-vector or density-matrix.
d0 (int): dimension of the first subsystem.
d1 (int or None): dimension of the second subsystem.
Returns:
float: The mutual information S(rho_A) + S(rho_B)... | def mutual_information(state, d0, d1=None):
if d1 is None:
d1 = int(len(state) / d0)
mi = entropy(partial_trace(state, [0], dimensions=[d0, d1]))
mi += entropy(partial_trace(state, [1], dimensions=[d0, d1]))
mi -= entropy(state)
return mi | 159,216 |
Compute the entanglement of formation of quantum state.
The input quantum state must be either a bipartite state vector, or a
2-qubit density matrix.
Args:
state (array_like): (N) array_like or (4,4) array_like, a
bipartite quantum state.
d0 (int): the dimension of the first su... | def entanglement_of_formation(state, d0, d1=None):
state = np.array(state)
if d1 is None:
d1 = int(len(state) / d0)
if state.ndim == 2 and len(state) == 4 and d0 == 2 and d1 == 2:
return __eof_qubit(state)
elif state.ndim == 1:
# trace out largest dimension
if d0 <... | 159,217 |
Compute the Entanglement of Formation of a 2-qubit density matrix.
Args:
rho ((array_like): (4,4) array_like, input density matrix.
Returns:
float: The entanglement of formation. | def __eof_qubit(rho):
c = concurrence(rho)
c = 0.5 + 0.5 * np.sqrt(1 - c * c)
return shannon_entropy([c, 1 - c]) | 159,218 |
Create a union (and also shift if desired) of all input `Schedule`s.
Args:
*schedules: Schedules to take the union of
name: Name of the new schedule. Defaults to first element of `schedules` | def union(*schedules: List[Union[ScheduleComponent, Tuple[int, ScheduleComponent]]],
name: str = None) -> Schedule:
if name is None and schedules:
sched = schedules[0]
if isinstance(sched, (list, tuple)):
name = sched[1].name
else:
name = sched.name
... | 159,219 |
Create a flattened schedule.
Args:
schedule: Schedules to flatten
name: Name of the new schedule. Defaults to first element of `schedules` | def flatten(schedule: ScheduleComponent, name: str = None) -> Schedule:
if name is None:
name = schedule.name
return Schedule(*schedule.instructions, name=name) | 159,220 |
Return schedule shifted by `time`.
Args:
schedule: The schedule to shift
time: The time to shift by
name: Name of shifted schedule. Defaults to name of `schedule` | def shift(schedule: ScheduleComponent, time: int, name: str = None) -> Schedule:
if name is None:
name = schedule.name
return union((time, schedule), name=name) | 159,221 |
Return a new schedule with the `child` schedule inserted into the `parent` at `start_time`.
Args:
parent: Schedule to be inserted into
time: Time to be inserted defined with respect to `parent`
child: Schedule to insert
name: Name of the new schedule. Defaults to name of parent | def insert(parent: ScheduleComponent, time: int, child: ScheduleComponent,
name: str = None) -> Schedule:
return union(parent, (time, child), name=name) | 159,222 |
r"""Return a new schedule with by appending `child` to `parent` at
the last time of the `parent` schedule's channels
over the intersection of the parent and child schedule's channels.
$t = \textrm{max}({x.stop\_time |x \in parent.channels \cap child.channels})$
Args:
parent: The sched... | def append(parent: ScheduleComponent, child: ScheduleComponent,
name: str = None) -> Schedule:
r
common_channels = set(parent.channels) & set(child.channels)
insertion_time = parent.ch_stop_time(*common_channels)
return insert(parent, insertion_time, child, name=name) | 159,223 |
Base class for backends.
This method should initialize the module and its configuration, and
raise an exception if a component of the module is
not available.
Args:
configuration (BackendConfiguration): backend configuration
provider (BaseProvider): provider res... | def __init__(self, configuration, provider=None):
self._configuration = configuration
self._provider = provider | 159,225 |
Start the progress bar.
Parameters:
iterations (int): Number of iterations. | def start(self, iterations):
self.touched = True
self.iter = int(iterations)
self.t_start = time.time() | 159,229 |
Estimate the remaining time left.
Parameters:
completed_iter (int): Number of iterations completed.
Returns:
est_time: Estimated time remaining. | def time_remaining_est(self, completed_iter):
if completed_iter:
t_r_est = (time.time() - self.t_start) / \
completed_iter*(self.iter-completed_iter)
else:
t_r_est = 0
date_time = datetime.datetime(1, 1, 1) + datetime.timedelta(seconds=t_r_est)
... | 159,230 |
Run the CommutativeCancellation pass on a dag
Args:
dag (DAGCircuit): the DAG to be optimized.
Returns:
DAGCircuit: the optimized DAG.
Raises:
TranspilerError: when the 1 qubit rotation gates are not found | def run(self, dag):
q_gate_list = ['cx', 'cy', 'cz', 'h', 'x', 'y', 'z']
# Gate sets to be cancelled
cancellation_sets = defaultdict(lambda: [])
for wire in dag.wires:
wire_name = "{0}[{1}]".format(str(wire[0].name), str(wire[1]))
wire_commutation_set ... | 159,234 |
Return a list of QuantumCircuit object(s) from a qobj
Args:
qobj (Qobj): The Qobj object to convert to QuantumCircuits
Returns:
list: A list of QuantumCircuit objects from the qobj | def _experiments_to_circuits(qobj):
if qobj.experiments:
circuits = []
for x in qobj.experiments:
quantum_registers = [QuantumRegister(i[1], name=i[0])
for i in x.header.qreg_sizes]
classical_registers = [ClassicalRegister(i[1], name=i[0]... | 159,235 |
Dissasemble a qobj and return the circuits, run_config, and user header
Args:
qobj (Qobj): The input qobj object to dissasemble
Returns:
circuits (list): A list of quantum circuits
run_config (dict): The dist of the run config
user_qobj_header (dict): The dict of any user header... | def disassemble(qobj):
run_config = qobj.config.to_dict()
user_qobj_header = qobj.header.to_dict()
circuits = _experiments_to_circuits(qobj)
return circuits, run_config, user_qobj_header | 159,236 |
Calculate the Hamming distance between two bit strings
Args:
str1 (str): First string.
str2 (str): Second string.
Returns:
int: Distance between strings.
Raises:
VisualizationError: Strings not same length | def hamming_distance(str1, str2):
if len(str1) != len(str2):
raise VisualizationError('Strings not same length.')
return sum(s1 != s2 for s1, s2 in zip(str1, str2)) | 159,237 |
Return quaternion for rotation about given axis.
Args:
angle (float): Angle in radians.
axis (str): Axis for rotation
Returns:
Quaternion: Quaternion for axis rotation.
Raises:
ValueError: Invalid input axis. | def quaternion_from_axis_rotation(angle, axis):
out = np.zeros(4, dtype=float)
if axis == 'x':
out[1] = 1
elif axis == 'y':
out[2] = 1
elif axis == 'z':
out[3] = 1
else:
raise ValueError('Invalid axis input.')
out *= math.sin(angle/2.0)
out[0] = math.cos(... | 159,239 |
Generate a quaternion from a set of Euler angles.
Args:
angles (array_like): Array of Euler angles.
order (str): Order of Euler rotations. 'yzy' is default.
Returns:
Quaternion: Quaternion representation of Euler rotation. | def quaternion_from_euler(angles, order='yzy'):
angles = np.asarray(angles, dtype=float)
quat = quaternion_from_axis_rotation(angles[0], order[0])\
* (quaternion_from_axis_rotation(angles[1], order[1])
* quaternion_from_axis_rotation(angles[2], order[2]))
quat.normalize(inplace=True)... | 159,240 |
Normalizes a Quaternion to unit length
so that it represents a valid rotation.
Args:
inplace (bool): Do an inplace normalization.
Returns:
Quaternion: Normalized quaternion. | def normalize(self, inplace=False):
if inplace:
nrm = self.norm()
self.data /= nrm
return None
nrm = self.norm()
data_copy = np.array(self.data, copy=True)
data_copy /= nrm
return Quaternion(data_copy) | 159,243 |
Prepare received data for representation.
Args:
data (dict): values to represent (ex. {'001' : 130})
number_to_keep (int): number of elements to show individually.
Returns:
dict: processed data to show. | def process_data(data, number_to_keep):
result = dict()
if number_to_keep != 0:
data_temp = dict(Counter(data).most_common(number_to_keep))
data_temp['rest'] = sum(data.values()) - sum(data_temp.values())
data = data_temp
labels = data
values = np.array([data[key] for key... | 159,246 |
Create new model.
Args:
valid_value_types (tuple): valid types as values. | def __init__(self, valid_value_types, **kwargs):
# pylint: disable=missing-param-doc
super(DictParameters, self).__init__(**kwargs)
self.valid_value_types = valid_value_types | 159,253 |
Two Registers are the same if they are of the same type
(i.e. quantum/classical), and have the same name and size.
Args:
other (Register): other Register
Returns:
bool: are self and other equal. | def __eq__(self, other):
res = False
if type(self) is type(other) and \
self.name == other.name and \
self.size == other.size:
res = True
return res | 159,260 |
Create a new gate.
Args:
name (str): the Qobj name of the gate
num_qubits (int): the number of qubits the gate acts on.
params (list): a list of parameters.
label (str or None): An optional label for the gate [Default: None] | def __init__(self, name, num_qubits, params, label=None):
self._label = label
super().__init__(name, num_qubits, 0, params) | 159,263 |
Create new snapshot command.
Args:
name (str): Snapshot name which is used to identify the snapshot in the output.
snap_type (str): Type of snapshot, e.g., βstateβ (take a snapshot of the quantum state).
The types of snapshots offered are defined in a separate specificat... | def __init__(self, name: str, snap_type: str):
self._type = snap_type
self._channel = SnapshotChannel()
Command.__init__(self, duration=0, name=name)
Instruction.__init__(self, self, self._channel, name=name) | 159,278 |
Left sample a continuous function.
Args:
continuous_pulse: Continuous pulse function to sample.
duration: Duration to sample for.
*args: Continuous pulse function args.
**kwargs: Continuous pulse function kwargs. | def left_sample(continuous_pulse: Callable, duration: int, *args, **kwargs) -> np.ndarray:
times = np.arange(duration)
return continuous_pulse(times, *args, **kwargs) | 159,283 |
Add a list of data points to bloch sphere.
Args:
points (array_like):
Collection of data points.
meth (str):
Type of points to plot, use 'm' for multicolored, 'l' for points
connected with a line. | def add_points(self, points, meth='s'):
if not isinstance(points[0], (list, np.ndarray)):
points = [[points[0]], [points[1]], [points[2]]]
points = np.array(points)
if meth == 's':
if len(points[0]) == 1:
pnts = np.array([[points[0][0]],
... | 159,314 |
Add a list of vectors to Bloch sphere.
Args:
vectors (array_like):
Array with vectors of unit length or smaller. | def add_vectors(self, vectors):
if isinstance(vectors[0], (list, np.ndarray)):
for vec in vectors:
self.vectors.append(vec)
else:
self.vectors.append(vectors) | 159,315 |
Saves Bloch sphere to file of type ``format`` in directory ``dirc``.
Args:
name (str):
Name of saved image. Must include path and format as well.
i.e. '/Users/Paul/Desktop/bloch.png'
This overrides the 'format' and 'dirc' arguments.
output ... | def save(self, name=None, output='png', dirc=None):
self.render()
if dirc:
if not os.path.isdir(os.getcwd() + "/" + str(dirc)):
os.makedirs(os.getcwd() + "/" + str(dirc))
if name is None:
if dirc:
self.fig.savefig(os.getcwd() + "/... | 159,325 |
Connects boxes and elements using wire_char and setting proper connectors.
Args:
wire_char (char): For example 'β' or 'β'.
where (list["top", "bot"]): Where the connector should be set.
label (string): Some connectors have a label (see cu1, for example). | def connect(self, wire_char, where, label=None):
if 'top' in where and self.top_connector:
self.top_connect = self.top_connector[wire_char]
if 'bot' in where and self.bot_connector:
self.bot_connect = self.bot_connector[wire_char]
if label:
self.to... | 159,332 |
In multi-bit elements, the label is centered vertically.
Args:
input_length (int): Rhe amount of wires affected.
order (int): Which middle element is this one? | def center_label(self, input_length, order):
location_in_the_box = '*'.center(input_length * 2 - 1).index('*') + 1
top_limit = order * 2 + 2
bot_limit = top_limit + 2
if top_limit <= location_in_the_box < bot_limit:
if location_in_the_box == top_limit:
... | 159,336 |
Given a layer, replace the Nones in it with EmptyWire elements.
Args:
layer (list): The layer that contains Nones.
first_clbit (int): The first wire that is classic.
Returns:
list: The new layer, with no Nones. | def fillup_layer(layer, first_clbit):
for nones in [i for i, x in enumerate(layer) if x is None]:
layer[nones] = EmptyWire('β') if nones >= first_clbit else EmptyWire('β')
return layer | 159,347 |
Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer. | def fillup_layer(layer_length, arrow_char):
breakwire_layer = []
for _ in range(layer_length):
breakwire_layer.append(BreakWire(arrow_char))
return breakwire_layer | 159,349 |
Creates a layer with InputWire elements.
Args:
names (list): List of names for the wires.
Returns:
list: The new layer | def fillup_layer(names): # pylint: disable=arguments-differ
longest = max([len(name) for name in names])
inputs_wires = []
for name in names:
inputs_wires.append(InputWire(name.rjust(longest)))
return inputs_wires | 159,350 |
Dumps the ascii art in the file.
Args:
filename (str): File to dump the ascii art.
encoding (str): Optional. Default "utf-8". | def dump(self, filename, encoding="utf8"):
with open(filename, mode='w', encoding=encoding) as text_file:
text_file.write(self.single_string()) | 159,354 |
Returns a list of names for each wire.
Args:
with_initial_value (bool): Optional (Default: True). If true, adds the initial value to
the name.
Returns:
List: The list of wire names. | def wire_names(self, with_initial_value=True):
qubit_labels = self._get_qubit_labels()
clbit_labels = self._get_clbit_labels()
if with_initial_value:
qubit_labels = ['%s: |0>' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: 0 ' % clbit for clbit in clbit... | 159,356 |
Given a list of wires, creates a list of lines with the text drawing.
Args:
wires (list): A list of wires with instructions.
vertically_compressed (bool): Default is `True`. It merges the lines
so the drawing will take less vertical room.
Retu... | def draw_wires(wires, vertically_compressed=True):
lines = []
bot_line = None
for wire in wires:
# TOP
top_line = ''
for instruction in wire:
top_line += instruction.top
if bot_line is None:
lines.append(to... | 159,357 |
Merges two lines (top and bot) in the way that the overlapping make senses.
Args:
top (str): the top line
bot (str): the bottom line
icod (top or bot): in case of doubt, which line should have priority? Default: "top".
Returns:
str: The merge of both lines... | def merge_lines(top, bot, icod="top"):
ret = ""
for topc, botc in zip(top, bot):
if topc == botc:
ret += topc
elif topc in 'βΌβͺ' and botc == " ":
ret += "β"
elif topc == " ":
ret += botc
elif topc in ... | 159,360 |
When the elements of the layer have different widths, sets the width to the max elements.
Args:
layer (list): A list of elements. | def normalize_width(layer):
instructions = [instruction for instruction in filter(lambda x: x is not None, layer)]
longest = max([instruction.length for instruction in instructions])
for instruction in instructions:
instruction.layer_width = longest | 159,361 |
Sets the qubit to the element
Args:
qubit (qbit): Element of self.qregs.
element (DrawElement): Element to set in the qubit | def set_qubit(self, qubit, element):
self.qubit_layer[self.qregs.index(qubit)] = element | 159,365 |
Sets the clbit to the element
Args:
clbit (cbit): Element of self.cregs.
element (DrawElement): Element to set in the clbit | def set_clbit(self, clbit, element):
self.clbit_layer[self.cregs.index(clbit)] = element | 159,366 |
Sets the multi clbit box.
Args:
creg (string): The affected classical register.
label (string): The label for the multi clbit box.
top_connect (char): The char to connect the box on the top. | def set_cl_multibox(self, creg, label, top_connect='β΄'):
clbit = [bit for bit in self.cregs if bit[0] == creg]
self._set_multibox("cl", clbit, label, top_connect=top_connect) | 159,368 |
Connects the elements in the layer using wire_char.
Args:
wire_char (char): For example 'β' or 'β'. | def connect_with(self, wire_char):
if len([qbit for qbit in self.qubit_layer if qbit is not None]) == 1:
# Nothing to connect
return
for label, affected_bits in self.connections:
if not affected_bits:
continue
affected_bits[0].... | 159,369 |
Checks if internet connection exists to host via specified port.
If any exception is raised while trying to open a socket this will return
false.
Args:
hostname (str): Hostname to connect to.
port (int): Port to connect to
Returns:
bool: Has connection or not | def _has_connection(hostname, port):
try:
host = socket.gethostbyname(hostname)
socket.create_connection((host, port), 2)
return True
except Exception: # pylint: disable=broad-except
return False | 159,377 |
The matrix power of the channel.
Args:
n (int): compute the matrix power of the superoperator matrix.
Returns:
PTM: the matrix power of the SuperOp converted to a PTM channel.
Raises:
QiskitError: if the input and output dimensions of the
Quantu... | def power(self, n):
if n > 0:
return super().power(n)
return PTM(SuperOp(self).power(n)) | 159,380 |
Internal function that updates the status
of a HTML job monitor.
Args:
job_var (BaseJob): The job to keep track of.
interval (int): The status check interval
status (widget): HTML ipywidget for output ot screen
header (str): String representing HTML code for status.
_int... | def _html_checker(job_var, interval, status, header,
_interval_set=False):
job_status = job_var.status()
job_status_name = job_status.name
job_status_msg = job_status.value
status.value = header % (job_status_msg)
while job_status_name not in ['DONE', 'CANCELLED']:
tim... | 159,381 |
Continuous constant pulse.
Args:
times: Times to output pulse for.
amp: Complex pulse amplitude. | def constant(times: np.ndarray, amp: complex) -> np.ndarray:
return np.full(len(times), amp, dtype=np.complex_) | 159,383 |
Continuous square wave.
Args:
times: Times to output wave for.
amp: Pulse amplitude. Wave range is [-amp, amp].
period: Pulse period, units of dt.
phase: Pulse phase. | def square(times: np.ndarray, amp: complex, period: float, phase: float = 0) -> np.ndarray:
x = times/period+phase/np.pi
return amp*(2*(2*np.floor(x) - np.floor(2*x)) + 1).astype(np.complex_) | 159,384 |
Continuous triangle wave.
Args:
times: Times to output wave for.
amp: Pulse amplitude. Wave range is [-amp, amp].
period: Pulse period, units of dt.
phase: Pulse phase. | def triangle(times: np.ndarray, amp: complex, period: float, phase: float = 0) -> np.ndarray:
return amp*(-2*np.abs(sawtooth(times, 1, period, (phase-np.pi/2)/2)) + 1).astype(np.complex_) | 159,385 |
Continuous cosine wave.
Args:
times: Times to output wave for.
amp: Pulse amplitude.
freq: Pulse frequency, units of 1/dt.
phase: Pulse phase. | def cos(times: np.ndarray, amp: complex, freq: float, phase: float = 0) -> np.ndarray:
return amp*np.cos(2*np.pi*freq*times+phase).astype(np.complex_) | 159,386 |
Continuous unnormalized gaussian derivative pulse.
Args:
times: Times to output pulse for.
amp: Pulse amplitude at `center`.
center: Center (mean) of pulse.
sigma: Width (standard deviation) of pulse.
ret_gaussian: Return gaussian with which derivative was taken with. | def gaussian_deriv(times: np.ndarray, amp: complex, center: float, sigma: float,
ret_gaussian: bool = False) -> np.ndarray:
gauss, x = gaussian(times, amp=amp, center=center, sigma=sigma, ret_x=True)
gauss_deriv = -x/sigma*gauss
if ret_gaussian:
return gauss_deriv, gauss
... | 159,389 |
r"""Continuous gaussian square pulse.
Args:
times: Times to output pulse for.
amp: Pulse amplitude.
center: Center of the square pulse component.
width: Width of the square pulse component.
sigma: Width (standard deviation) of gaussian rise/fall portion of the pulse.
... | def gaussian_square(times: np.ndarray, amp: complex, center: float, width: float,
sigma: float, zeroed_width: Union[None, float] = None) -> np.ndarray:
r
square_start = center-width/2
square_stop = center+width/2
if zeroed_width:
zeroed_width = min(width, zeroed_width)
... | 159,390 |
The default pass manager that maps to the coupling map.
Args:
basis_gates (list[str]): list of basis gate names supported by the target.
coupling_map (CouplingMap): coupling map to target in mapping.
initial_layout (Layout or None): initial layout of virtual qubits on physical qubits
... | def default_pass_manager(basis_gates, coupling_map, initial_layout, seed_transpiler):
pass_manager = PassManager()
pass_manager.property_set['layout'] = initial_layout
pass_manager.append(Unroller(basis_gates))
# Use the trivial layout if no layout is found
pass_manager.append(TrivialLayout(c... | 159,392 |
The default pass manager without a coupling map.
Args:
basis_gates (list[str]): list of basis gate names to unroll to.
Returns:
PassManager: A passmanager that just unrolls, without any optimization. | def default_pass_manager_simulator(basis_gates):
pass_manager = PassManager()
pass_manager.append(Unroller(basis_gates))
pass_manager.append([RemoveResetInZeroState(), Depth(), FixedPoint('depth')],
do_while=lambda property_set: not property_set['depth_fixed_point'])
retu... | 159,393 |
Test if this circuit has the register r.
Args:
register (Register): a quantum or classical register.
Returns:
bool: True if the register is contained in this circuit. | def has_register(self, register):
has_reg = False
if (isinstance(register, QuantumRegister) and
register in self.qregs):
has_reg = True
elif (isinstance(register, ClassicalRegister) and
register in self.cregs):
has_reg = True
... | 159,397 |
How many non-entangled subcircuits can the circuit be factored to.
Args:
unitary_only (bool): Compute only unitary part of graph.
Returns:
int: Number of connected components in circuit. | def num_connected_components(self, unitary_only=False):
# Convert registers to ints (as done in depth).
reg_offset = 0
reg_map = {}
if unitary_only:
regs = self.qregs
else:
regs = self.qregs+self.cregs
for reg in regs:
reg_ma... | 159,416 |
Assign parameters to values yielding a new circuit.
Args:
value_dict (dict): {parameter: value, ...}
Raises:
QiskitError: If value_dict contains parameters not present in the circuit
Returns:
QuantumCircuit: copy of self with assignment substitution. | def bind_parameters(self, value_dict):
new_circuit = self.copy()
if value_dict.keys() > self.parameters:
raise QiskitError('Cannot bind parameters ({}) not present in the circuit.'.format(
[str(p) for p in value_dict.keys() - self.parameters]))
for paramete... | 159,417 |
Map all gates that can be executed with the current layout.
Args:
layout (Layout): Map from virtual qubit index to physical qubit index.
gates (list): Gates to be mapped.
coupling_map (CouplingMap): CouplingMap for target device topology.
Returns:
tuple:
mapped_gate... | def _map_free_gates(layout, gates, coupling_map):
blocked_qubits = set()
mapped_gates = []
remaining_gates = []
for gate in gates:
# Gates without a partition (barrier, snapshot, save, load, noise) may
# still have associated qubits. Look for them in the qargs.
if not gat... | 159,421 |
Initialize a LookaheadSwap instance.
Arguments:
coupling_map (CouplingMap): CouplingMap of the target backend.
initial_layout (Layout): The initial layout of the DAG to analyze. | def __init__(self, coupling_map, initial_layout=None):
super().__init__()
self._coupling_map = coupling_map
self.initial_layout = initial_layout
self.requires.append(BarrierBeforeFinalMeasurements()) | 159,427 |
Run one pass of the lookahead mapper on the provided DAG.
Args:
dag (DAGCircuit): the directed acyclic graph to be mapped
Returns:
DAGCircuit: A dag mapped to be compatible with the coupling_map in
the property_set.
Raises:
TranspilerError: if... | def run(self, dag):
coupling_map = self._coupling_map
ordered_virtual_gates = list(dag.serial_layers())
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.i... | 159,428 |
Create coupling graph. By default, the generated coupling has no nodes.
Args:
couplinglist (list or None): An initial coupling graph, specified as
an adjacency list containing couplings, e.g. [[0,1], [0,2], [1,2]]. | def __init__(self, couplinglist=None):
# the coupling map graph
self.graph = nx.DiGraph()
# a dict of dicts from node pairs to distances
self._dist_matrix = None
# a sorted list of physical qubits (integers) in this coupling map
self._qubit_list = None
... | 159,429 |
Returns the undirected distance between physical_qubit1 and physical_qubit2.
Args:
physical_qubit1 (int): A physical qubit
physical_qubit2 (int): Another physical qubit
Returns:
int: The undirected distance
Raises:
CouplingError: if the qubits d... | def distance(self, physical_qubit1, physical_qubit2):
if physical_qubit1 not in self.physical_qubits:
raise CouplingError("%s not in coupling graph" % (physical_qubit1,))
if physical_qubit2 not in self.physical_qubits:
raise CouplingError("%s not in coupling graph" % (ph... | 159,436 |
Returns the shortest undirected path between physical_qubit1 and physical_qubit2.
Args:
physical_qubit1 (int): A physical qubit
physical_qubit2 (int): Another physical qubit
Returns:
List: The shortest undirected path
Raises:
CouplingError: When th... | def shortest_undirected_path(self, physical_qubit1, physical_qubit2):
try:
return nx.shortest_path(self.graph.to_undirected(as_view=True), source=physical_qubit1,
target=physical_qubit2)
except nx.exception.NetworkXNoPath:
raise Coupli... | 159,437 |
Adds a map element between `bit` and `physical_bit`. If `physical_bit` is not
defined, `bit` will be mapped to a new physical bit (extending the length of the
layout by one.)
Args:
virtual_bit (tuple): A (qu)bit. For example, (QuantumRegister(3, 'qr'), 2).
physical_bit (i... | def add(self, virtual_bit, physical_bit=None):
if physical_bit is None:
physical_candidate = len(self)
while physical_candidate in self._p2v:
physical_candidate += 1
physical_bit = physical_candidate
self[virtual_bit] = physical_bit | 159,468 |
Swaps the map between left and right.
Args:
left (tuple or int): Item to swap with right.
right (tuple or int): Item to swap with left.
Raises:
LayoutError: If left and right have not the same type. | def swap(self, left, right):
if type(left) is not type(right):
raise LayoutError('The method swap only works with elements of the same type.')
temp = self[left]
self[left] = self[right]
self[right] = temp | 159,469 |
Creates a trivial ("one-to-one") Layout with the registers in `regs`.
Args:
*regs (Registers): registers to include in the layout.
Returns:
Layout: A layout with all the `regs` in the given order. | def generate_trivial_layout(*regs):
layout = Layout()
for reg in regs:
layout.add_register(reg)
return layout | 159,471 |
Converts a list of integers to a Layout
mapping virtual qubits (index of the list) to
physical qubits (the list values).
Args:
int_list (list): A list of integers.
*qregs (QuantumRegisters): The quantum registers to apply
the layout to.
Returns:
... | def from_intlist(int_list, *qregs):
if not all((isinstance(i, int) for i in int_list)):
raise LayoutError('Expected a list of ints')
if len(int_list) != len(set(int_list)):
raise LayoutError('Duplicate values not permitted; Layout is bijective.')
n_qubits = sum(r... | 159,472 |
Populates a Layout from a list containing virtual
qubits---(QuantumRegister, int) tuples---, or None.
Args:
tuple_list (list):
e.g.: [qr[0], None, qr[2], qr[3]]
Returns:
Layout: the corresponding Layout object
Raises:
LayoutError: If t... | def from_tuplelist(tuple_list):
out = Layout()
for physical, virtual in enumerate(tuple_list):
if virtual is None:
continue
elif Layout.is_virtual(virtual):
if virtual in out._v2p:
raise LayoutError('Duplicate values no... | 159,473 |
Return a new schedule with `schedule` inserted within `self` at `start_time`.
Args:
start_time: time to be inserted
schedule: schedule to be inserted | def insert(self, start_time: int, schedule: ScheduleComponent) -> 'ScheduleComponent':
return ops.insert(self, start_time, schedule) | 159,482 |
Checks if the attribute name is in the list of attributes to protect. If so, raises
TranspilerAccessError.
Args:
name (string): the attribute name to check
Raises:
TranspilerAccessError: when name is the list of attributes to protect. | def _check_if_fenced(self, name):
if name in object.__getattribute__(self, '_attributes_to_fence'):
raise TranspilerAccessError("The fenced %s has the property %s protected" %
(type(object.__getattribute__(self, '_wrapped')), name)) | 159,489 |
The matrix power of the channel.
Args:
n (int): compute the matrix power of the superoperator matrix.
Returns:
Stinespring: the matrix power of the SuperOp converted to a
Stinespring channel.
Raises:
QiskitError: if the input and output dimensio... | def power(self, n):
if n > 0:
return super().power(n)
return Stinespring(SuperOp(self).power(n)) | 159,495 |
Return the QuantumChannel self + other.
Args:
other (complex): a complex number.
Returns:
Stinespring: the scalar multiplication other * self as a
Stinespring object.
Raises:
QiskitError: if other is not a valid scalar. | def multiply(self, other):
if not isinstance(other, Number):
raise QiskitError("other is not a number")
# If the number is complex or negative we need to convert to
# general Stinespring representation so we first convert to
# the Choi representation
if isins... | 159,496 |
Evolve a quantum state by the QuantumChannel.
Args:
state (QuantumState): The input statevector or density matrix.
qargs (list): a list of QuantumState subsystem positions to apply
the operator on.
Returns:
QuantumState: the output quantum... | def _evolve(self, state, qargs=None):
# If subsystem evolution we use the SuperOp representation
if qargs is not None:
return SuperOp(self)._evolve(state, qargs)
# Otherwise we compute full evolution directly
state = self._format_state(state)
if state.shape[... | 159,497 |
Return the tensor product channel.
Args:
other (QuantumChannel): a quantum channel subclass.
reverse (bool): If False return self β other, if True return
if True return (other β self) [Default: False]
Returns:
Stinespring: the tensor produ... | def _tensor_product(self, other, reverse=False):
# Convert other to Stinespring
if not isinstance(other, Stinespring):
other = Stinespring(other)
# Tensor stinespring ops
sa_l, sa_r = self._data
sb_l, sb_r = other._data
# Reshuffle tensor dimensions... | 159,498 |
Create a new command.
Args:
duration (int): Duration of this command.
name (str): Name of this command.
Raises:
PulseError: when duration is not number of points. | def __init__(self, duration: int = None, name: str = None):
if isinstance(duration, int):
self._duration = duration
else:
raise PulseError('Pulse duration should be integer.')
if name:
self._name = name
else:
self._name = 'p%d' % ... | 159,499 |
Two Commands are the same if they are of the same type
and have the same duration and name.
Args:
other (Command): other Command.
Returns:
bool: are self and other equal. | def __eq__(self, other):
if type(self) is type(other) and \
self._duration == other._duration and \
self._name == other._name:
return True
return False | 159,500 |
Runs the BasicSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
Raises:
TranspilerError: if the coupling map or the layout are not
compatible with the DAG | def run(self, dag):
new_dag = DAGCircuit()
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
... | 159,501 |
Takes (QuantumRegister, int) tuples and converts
them into an integer array.
Args:
items (list): List of tuples of (QuantumRegister, int)
to convert.
qregs (dict): List of )QuantumRegister, int) tuples.
Returns:
ndarray: Array of integers. | def regtuple_to_numeric(items, qregs):
sizes = [qr.size for qr in qregs.values()]
reg_idx = np.cumsum([0]+sizes)
regint = {}
for ind, qreg in enumerate(qregs.values()):
regint[qreg] = ind
out = np.zeros(len(items), dtype=np.int32)
for idx, val in enumerate(items):
out[idx] =... | 159,503 |
Converts gate tuples into a nested list of integers.
Args:
gates (list): List of (QuantumRegister, int) pairs
representing gates.
qregs (dict): List of )QuantumRegister, int) tuples.
Returns:
list: Nested list of integers for gates. | def gates_to_idx(gates, qregs):
sizes = [qr.size for qr in qregs.values()]
reg_idx = np.cumsum([0]+sizes)
regint = {}
for ind, qreg in enumerate(qregs.values()):
regint[qreg] = ind
out = np.zeros(2*len(gates), dtype=np.int32)
for idx, gate in enumerate(gates):
out[2*idx] = r... | 159,504 |
Run the StochasticSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
Raises:
TranspilerError: if the coupling map or the layout are not
compatible with the DAG | def run(self, dag):
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
if len(dag.qubits()) !=... | 159,506 |
Two channels are the same if they are of the same type, and have the same index.
Args:
other (Channel): other Channel
Returns:
bool: are self and other equal. | def __eq__(self, other):
if type(self) is type(other) and \
self._index == other._index:
return True
return False | 159,510 |
r"""Make the Pauli object.
Note that, for the qubit index:
- Order of z, x vectors is q_0 ... q_{n-1},
- Order of pauli label is q_{n-1} ... q_0
E.g.,
- z and x vectors: z = [z_0 ... z_{n-1}], x = [x_0 ... x_{n-1}]
- a pauli is $P_{n-1} \otimes ... \otim... | def __init__(self, z=None, x=None, label=None):
r
if label is not None:
a = Pauli.from_label(label)
self._z = a.z
self._x = a.x
else:
self._init_from_bool(z, x) | 159,513 |
r"""Take pauli string to construct pauli.
The qubit index of pauli label is q_{n-1} ... q_0.
E.g., a pauli is $P_{n-1} \otimes ... \otimes P_0$
Args:
label (str): pauli label
Returns:
Pauli: the constructed pauli
Raises:
QiskitError: invali... | def from_label(cls, label):
r
z = np.zeros(len(label), dtype=np.bool)
x = np.zeros(len(label), dtype=np.bool)
for i, char in enumerate(label):
if char == 'X':
x[-i - 1] = True
elif char == 'Z':
z[-i - 1] = True
elif char... | 159,514 |
Construct pauli from boolean array.
Args:
z (numpy.ndarray): boolean, z vector
x (numpy.ndarray): boolean, x vector
Returns:
Pauli: self
Raises:
QiskitError: if z or x are None or the length of z and x are different. | def _init_from_bool(self, z, x):
if z is None:
raise QiskitError("z vector must not be None.")
if x is None:
raise QiskitError("x vector must not be None.")
if len(z) != len(x):
raise QiskitError("length of z and x vectors must be "
... | 159,515 |
Return True if all Pauli terms are equal.
Args:
other (Pauli): other pauli
Returns:
bool: are self and other equal. | def __eq__(self, other):
res = False
if len(self) == len(other):
if np.all(self._z == other.z) and np.all(self._x == other.x):
res = True
return res | 159,518 |
r"""
Multiply two Paulis and track the phase.
$P_3 = P_1 \otimes P_2$: X*Y
Args:
p1 (Pauli): pauli 1
p2 (Pauli): pauli 2
Returns:
Pauli: the multiplied pauli
complex: the sign of the multiplication, 1, -1, 1j or -1j | def sgn_prod(p1, p2):
r
phase = Pauli._prod_phase(p1, p2)
new_pauli = p1 * p2
return new_pauli, phase | 159,521 |
Update partial or entire z.
Args:
z (numpy.ndarray or list): to-be-updated z
indices (numpy.ndarray or list or optional): to-be-updated qubit indices
Returns:
Pauli: self
Raises:
QiskitError: when updating whole z, the number of qubits must be t... | def update_z(self, z, indices=None):
z = _make_np_bool(z)
if indices is None:
if len(self._z) != len(z):
raise QiskitError("During updating whole z, you can not "
"change the number of qubits.")
self._z = z
else:
... | 159,525 |
Update partial or entire x.
Args:
x (numpy.ndarray or list): to-be-updated x
indices (numpy.ndarray or list or optional): to-be-updated qubit indices
Returns:
Pauli: self
Raises:
QiskitError: when updating whole x, the number of qubits must be t... | def update_x(self, x, indices=None):
x = _make_np_bool(x)
if indices is None:
if len(self._x) != len(x):
raise QiskitError("During updating whole x, you can not change "
"the number of qubits.")
self._x = x
else:
... | 159,526 |
Append pauli at the end.
Args:
paulis (Pauli): the to-be-inserted or appended pauli
pauli_labels (list[str]): the to-be-inserted or appended pauli label
Returns:
Pauli: self | def append_paulis(self, paulis=None, pauli_labels=None):
return self.insert_paulis(None, paulis=paulis, pauli_labels=pauli_labels) | 159,528 |
Delete pauli at the indices.
Args:
indices(list[int]): the indices of to-be-deleted paulis
Returns:
Pauli: self | def delete_qubits(self, indices):
if not isinstance(indices, list):
indices = [indices]
self._z = np.delete(self._z, indices)
self._x = np.delete(self._x, indices)
return self | 159,529 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.