INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Get the matrix for a single qubit. | def single_gate_matrix(gate, params=None):
"""Get the matrix for a single qubit.
Args:
gate(str): the single qubit gate name
params(list): the operation parameters op['params']
Returns:
array: A numpy array representing the matrix
"""
# Converting sym to floats improves the... |
Return the index string for Numpy. eignsum matrix - matrix multiplication. | def einsum_matmul_index(gate_indices, number_of_qubits):
"""Return the index string for Numpy.eignsum matrix-matrix multiplication.
The returned indices are to perform a matrix multiplication A.B where
the matrix A is an M-qubit matrix, matrix B is an N-qubit matrix, and
M <= N, and identity matrices a... |
Return the index string for Numpy. eignsum matrix - vector multiplication. | def einsum_vecmul_index(gate_indices, number_of_qubits):
"""Return the index string for Numpy.eignsum matrix-vector multiplication.
The returned indices are to perform a matrix multiplication A.v where
the matrix A is an M-qubit matrix, vector v is an N-qubit vector, and
M <= N, and identity matrices a... |
Return the index string for Numpy. eignsum matrix multiplication. | def _einsum_matmul_index_helper(gate_indices, number_of_qubits):
"""Return the index string for Numpy.eignsum matrix multiplication.
The returned indices are to perform a matrix multiplication A.v where
the matrix A is an M-qubit matrix, matrix v is an N-qubit vector, and
M <= N, and identity matrices ... |
Build a DAGCircuit object from a QuantumCircuit. | def circuit_to_dag(circuit):
"""Build a ``DAGCircuit`` object from a ``QuantumCircuit``.
Args:
circuit (QuantumCircuit): the input circuit.
Return:
DAGCircuit: the DAG representing the input circuit.
"""
dagcircuit = DAGCircuit()
dagcircuit.name = circuit.name
for register ... |
Function used to fit the exponential decay. | def exp_fit_fun(x, a, tau, c):
"""Function used to fit the exponential decay."""
# pylint: disable=invalid-name
return a * np.exp(-x / tau) + c |
Function used to fit the decay cosine. | def osc_fit_fun(x, a, tau, f, phi, c):
"""Function used to fit the decay cosine."""
# pylint: disable=invalid-name
return a * np.exp(-x / tau) * np.cos(2 * np.pi * f * x + phi) + c |
Plot coherence data. | def plot_coherence(xdata, ydata, std_error, fit, fit_function, xunit, exp_str,
qubit_label):
"""Plot coherence data.
Args:
xdata
ydata
std_error
fit
fit_function
xunit
exp_str
qubit_label
Raises:
ImportError: If matp... |
Take the raw rb data and convert it into averages and std dev | def shape_rb_data(raw_rb):
"""Take the raw rb data and convert it into averages and std dev
Args:
raw_rb (numpy.array): m x n x l list where m is the number of seeds, n
is the number of Clifford sequences and l is the number of qubits
Return:
numpy_array: 2 x n x l list where i... |
Take the rb fit data and convert it into EPC ( error per Clifford ) | def rb_epc(fit, rb_pattern):
"""Take the rb fit data and convert it into EPC (error per Clifford)
Args:
fit (dict): dictionary of the fit quantities (A, alpha, B) with the
keys 'qn' where n is the qubit and subkeys 'fit', e.g.
{'q0':{'fit': [1, 0, 0.9], 'fiterr': [0, 0, 0]}}}
... |
Plot randomized benchmarking data. | def plot_rb_data(xdata, ydatas, yavg, yerr, fit, survival_prob, ax=None,
show_plt=True):
"""Plot randomized benchmarking data.
Args:
xdata (list): list of subsequence lengths
ydatas (list): list of lists of survival probabilities for each
sequence
yavg (list... |
Finds runs containing parameterized gates and splits them into sequential runs excluding the parameterized gates. | def _split_runs_on_parameters(runs):
"""Finds runs containing parameterized gates and splits them into sequential
runs excluding the parameterized gates.
"""
def _is_dagnode_parameterized(node):
return any(isinstance(param, Parameter) for param in node.op.params)
out = []
for run in ru... |
Return a new circuit that has been optimized. | def run(self, dag):
"""Return a new circuit that has been optimized."""
runs = dag.collect_runs(["u1", "u2", "u3", "id"])
runs = _split_runs_on_parameters(runs)
for run in runs:
right_name = "u1"
right_parameters = (0, 0, 0) # (theta, phi, lambda)
fo... |
Return a triple theta phi lambda for the product. | def compose_u3(theta1, phi1, lambda1, theta2, phi2, lambda2):
"""Return a triple theta, phi, lambda for the product.
u3(theta, phi, lambda)
= u3(theta1, phi1, lambda1).u3(theta2, phi2, lambda2)
= Rz(phi1).Ry(theta1).Rz(lambda1+phi2).Ry(theta2).Rz(lambda2)
= Rz(phi1).Rz(... |
Express a Y. Z. Y single qubit gate as a Z. Y. Z gate. | def yzy_to_zyz(xi, theta1, theta2, eps=1e-9): # pylint: disable=invalid-name
"""Express a Y.Z.Y single qubit gate as a Z.Y.Z gate.
Solve the equation
.. math::
Ry(theta1).Rz(xi).Ry(theta2) = Rz(phi).Ry(theta).Rz(lambda)
for theta, phi, and lambda.
Return a solution ... |
Extend the layout with new ( physical qubit virtual qubit ) pairs. | def run(self, dag):
"""
Extend the layout with new (physical qubit, virtual qubit) pairs.
The dag signals which virtual qubits are already in the circuit.
This pass will allocate new virtual qubits such that no collision occurs
(i.e. Layout bijectivity is preserved)
The... |
Validates the input to state visualization functions. | def _validate_input_state(quantum_state):
"""Validates the input to state visualization functions.
Args:
quantum_state (ndarray): Input state / density matrix.
Returns:
rho: A 2d numpy array for the density matrix.
Raises:
VisualizationError: Invalid input.
"""
rho = np.... |
Trim a PIL image and remove white space. | def _trim(image):
"""Trim a PIL image and remove white space."""
background = PIL.Image.new(image.mode, image.size, image.getpixel((0, 0)))
diff = PIL.ImageChops.difference(image, background)
diff = PIL.ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
image = image.cr... |
Given a circuit return a tuple ( qregs cregs ops ) where qregs and cregs are the quantum and classical registers in order ( based on reverse_bits ) and ops is a list of DAG nodes which type is operation. Args: circuit ( QuantumCircuit ): From where the information is extracted. reverse_bits ( bool ): If true the order ... | def _get_layered_instructions(circuit, reverse_bits=False, justify=None):
"""
Given a circuit, return a tuple (qregs, cregs, ops) where
qregs and cregs are the quantum and classical registers
in order (based on reverse_bits) and ops is a list
of DAG nodes which type is "operation".
Args:
... |
Get the list of qubits drawing this gate would cover | def _get_gate_span(qregs, instruction):
"""Get the list of qubits drawing this gate would cover"""
min_index = len(qregs)
max_index = 0
for qreg in instruction.qargs:
index = qregs.index(qreg)
if index < min_index:
min_index = index
if index > max_index:
... |
Build an Instruction object from a QuantumCircuit. | def circuit_to_instruction(circuit):
"""Build an ``Instruction`` object from a ``QuantumCircuit``.
The instruction is anonymous (not tied to a named quantum register),
and so can be inserted into another circuit. The instruction will
have the same string name as the circuit.
Args:
circuit ... |
Pick a convenient layout depending on the best matching qubit connectivity and set the property layout. | def run(self, dag):
"""
Pick a convenient layout depending on the best matching
qubit connectivity, and set the property `layout`.
Args:
dag (DAGCircuit): DAG to find layout for.
Raises:
TranspilerError: if dag wider than self.coupling_map
"""
... |
Computes the qubit mapping with the best connectivity. | def _best_subset(self, n_qubits):
"""Computes the qubit mapping with the best connectivity.
Args:
n_qubits (int): Number of subset qubits to consider.
Returns:
ndarray: Array of qubits to use for best connectivity mapping.
"""
if n_qubits == 1:
... |
Return True if completely - positive trace - preserving. | def is_cptp(self, atol=None, rtol=None):
"""Return True if completely-positive trace-preserving."""
if self._data[1] is not None:
return False
if atol is None:
atol = self._atol
if rtol is None:
rtol = self._rtol
accum = 0j
for op in se... |
Return the conjugate of the QuantumChannel. | def conjugate(self):
"""Return the conjugate of the QuantumChannel."""
kraus_l, kraus_r = self._data
kraus_l = [k.conj() for k in kraus_l]
if kraus_r is not None:
kraus_r = [k.conj() for k in kraus_r]
return Kraus((kraus_l, kraus_r), self.input_dims(), self.output_dim... |
Return the transpose of the QuantumChannel. | def transpose(self):
"""Return the transpose of the QuantumChannel."""
kraus_l, kraus_r = self._data
kraus_l = [k.T for k in kraus_l]
if kraus_r is not None:
kraus_r = [k.T for k in kraus_r]
return Kraus((kraus_l, kraus_r),
input_dims=self.output_... |
Return the composition channel self∘other. | def compose(self, other, qargs=None, front=False):
"""Return the composition channel self∘other.
Args:
other (QuantumChannel): a quantum channel subclass.
qargs (list): a list of subsystem positions to compose other on.
front (bool): If False compose in standard orde... |
The matrix power of the channel. | def power(self, n):
"""The matrix power of the channel.
Args:
n (int): compute the matrix power of the superoperator matrix.
Returns:
Kraus: the matrix power of the SuperOp converted to a Kraus channel.
Raises:
QiskitError: if the input and output d... |
Return the QuantumChannel self + other. | def multiply(self, other):
"""Return the QuantumChannel self + other.
Args:
other (complex): a complex number.
Returns:
Kraus: the scalar multiplication other * self as a Kraus object.
Raises:
QiskitError: if other is not a valid scalar.
"""... |
Evolve a quantum state by the QuantumChannel. | def _evolve(self, state, qargs=None):
"""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.
Retu... |
Return the tensor product channel. | def _tensor_product(self, other, reverse=False):
"""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... |
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):
"""A decorator for generating SamplePulse from python callable.
Args:
func (callable): A function describing pulse envelope.
Raises:
PulseError: when invalid function is specified.
"""
@functools.wraps(func)
def to_pulse(duration, *args, name=None, **k... |
Return the correspond floating point number. | def real(self, nested_scope=None):
"""Return the correspond floating point number."""
operation = self.children[0].operation()
lhs = self.children[1].real(nested_scope)
rhs = self.children[2].real(nested_scope)
return operation(lhs, rhs) |
Return the correspond symbolic number. | def sym(self, nested_scope=None):
"""Return the correspond symbolic number."""
operation = self.children[0].operation()
lhs = self.children[1].sym(nested_scope)
rhs = self.children[2].sym(nested_scope)
return operation(lhs, rhs) |
Apply barrier to circuit. If qargs is None applies to all the qbits. Args is a list of QuantumRegister or single qubits. For QuantumRegister applies barrier to all the qubits in that register. | def barrier(self, *qargs):
"""Apply barrier to circuit.
If qargs is None, applies to all the qbits.
Args is a list of QuantumRegister or single qubits.
For QuantumRegister, applies barrier to all the qubits in that register."""
qubits = []
qargs = _convert_to_bits(qargs, [qbit for qreg in self.... |
Compute the mean value of an diagonal observable. | def average_data(counts, observable):
"""Compute the mean value of an diagonal observable.
Takes in a diagonal observable in dictionary, list or matrix format and then
calculates the sum_i value(i) P(i) where value(i) is the value of the
observable for state i.
Args:
counts (dict): a dict ... |
Process an Id or IndexedId node as a bit or register type. | def _process_bit_id(self, node):
"""Process an Id or IndexedId node as a bit or register type.
Return a list of tuples (Register,index).
"""
# pylint: disable=inconsistent-return-statements
reg = None
if node.name in self.dag.qregs:
reg = self.dag.qregs[node.... |
Process a custom unitary node. | def _process_custom_unitary(self, node):
"""Process a custom unitary node."""
name = node.name
if node.arguments is not None:
args = self._process_node(node.arguments)
else:
args = []
bits = [self._process_bit_id(node_element)
for node_elem... |
Process a gate node. | def _process_gate(self, node, opaque=False):
"""Process a gate node.
If opaque is True, process the node as an opaque gate node.
"""
self.gates[node.name] = {}
de_gate = self.gates[node.name]
de_gate["print"] = True # default
de_gate["opaque"] = opaque
d... |
Process a CNOT gate node. | def _process_cnot(self, node):
"""Process a CNOT gate node."""
id0 = self._process_bit_id(node.children[0])
id1 = self._process_bit_id(node.children[1])
if not(len(id0) == len(id1) or len(id0) == 1 or len(id1) == 1):
raise QiskitError("internal error: qreg size mismatch",
... |
Process a measurement node. | def _process_measure(self, node):
"""Process a measurement node."""
id0 = self._process_bit_id(node.children[0])
id1 = self._process_bit_id(node.children[1])
if len(id0) != len(id1):
raise QiskitError("internal error: reg size mismatch",
"line=%s... |
Process an if node. | def _process_if(self, node):
"""Process an if node."""
creg_name = node.children[0].name
creg = self.dag.cregs[creg_name]
cval = node.children[1].value
self.condition = (creg, cval)
self._process_node(node.children[2])
self.condition = None |
Carry out the action associated with a node. | def _process_node(self, node):
"""Carry out the action associated with a node."""
if node.type == "program":
self._process_children(node)
elif node.type == "qreg":
qreg = QuantumRegister(node.index, node.name)
self.dag.add_qreg(qreg)
elif node.type =... |
Create a DAG node out of a parsed AST op node. | def _create_dag_op(self, name, params, qargs):
"""
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:
... |
Return the corresponding OPENQASM string. | def qasm(self, prec=15):
"""Return the corresponding OPENQASM string."""
return "measure " + self.children[0].qasm(prec) + " -> " + \
self.children[1].qasm(prec) + ";" |
Return duration of supplied channels. | def ch_duration(self, *channels: List[Channel]) -> int:
"""Return duration of supplied channels.
Args:
*channels: Supplied channels
"""
return self.timeslots.ch_duration(*channels) |
Return minimum start time for supplied channels. | def ch_start_time(self, *channels: List[Channel]) -> int:
"""Return minimum start time for supplied channels.
Args:
*channels: Supplied channels
"""
return self.timeslots.ch_start_time(*channels) |
Return maximum start time for supplied channels. | def ch_stop_time(self, *channels: List[Channel]) -> int:
"""Return maximum start time for supplied channels.
Args:
*channels: Supplied channels
"""
return self.timeslots.ch_stop_time(*channels) |
Iterable for flattening Schedule tree. | def _instructions(self, time: int = 0) -> Iterable[Tuple[int, 'Instruction']]:
"""Iterable for flattening Schedule tree.
Args:
time: Shifted time due to parent
Yields:
Tuple[int, ScheduleComponent]: Tuple containing time `ScheduleComponent` starts
at and... |
Print with indent. | def to_string(self, indent):
"""Print with indent."""
ind = indent * ' '
print(ind, 'indexed_id', self.name, self.index) |
Validates a value against the correct type of the field. | def check_type(self, value, attr, data):
"""Validates a value against the correct type of the field.
It calls ``_expected_types`` to get a list of valid types.
Subclasses can do one of the following:
1. They can override the ``valid_types`` property with a tuple with
t... |
Include unknown fields after dumping. | def dump_additional_data(self, valid_data, many, original_data):
"""Include unknown fields after dumping.
Unknown fields are added with no processing at all.
Args:
valid_data (dict or list): data collected and returned by ``dump()``.
many (bool): if True, data and origi... |
Include unknown fields after load. | def load_additional_data(self, valid_data, many, original_data):
"""Include unknown fields after load.
Unknown fields are added with no processing at all.
Args:
valid_data (dict or list): validated data returned by ``load()``.
many (bool): if True, data and original_dat... |
Create a patched Schema for validating models. | def _create_validation_schema(schema_cls):
"""Create a patched Schema for validating models.
Model validation is not part of Marshmallow. Schemas have a ``validate``
method but this delegates execution on ``load`` and discards the result.
Similarly, ``load`` will call ``_deserialize`` o... |
Validate the internal representation of the instance. | def _validate(instance):
"""Validate the internal representation of the instance."""
try:
_ = instance.schema.validate(instance.to_dict())
except ValidationError as ex:
raise ModelValidationError(
ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwarg... |
Add validation after instantiation. | def _validate_after_init(init_method):
"""Add validation after instantiation."""
@wraps(init_method)
def _decorated(self, **kwargs):
try:
_ = self.shallow_schema.validate(kwargs)
except ValidationError as ex:
raise ModelValidationError(
... |
Serialize the model into a Python dict of simple types. | def to_dict(self):
"""Serialize the model into a Python dict of simple types.
Note that this method requires that the model is bound with
``@bind_schema``.
"""
try:
data, _ = self.schema.dump(self)
except ValidationError as ex:
raise ModelValidati... |
Deserialize a dict of simple types into an instance of this class. | def from_dict(cls, dict_):
"""Deserialize a dict of simple types into an instance of this class.
Note that this method requires that the model is bound with
``@bind_schema``.
"""
try:
data, _ = cls.schema.load(dict_)
except ValidationError as ex:
... |
n - qubit QFT on q in circ. | def qft(circ, q, n):
"""n-qubit QFT on q in circ."""
for j in range(n):
for k in range(j):
circ.cu1(math.pi / float(2**(j - k)), q[j], q[k])
circ.h(q[j]) |
Partial trace over subsystems of multi - partite matrix. | def partial_trace(state, trace_systems, dimensions=None, reverse=True):
"""
Partial trace over subsystems of multi-partite matrix.
Note that subsystems are ordered as rho012 = rho0(x)rho1(x)rho2.
Args:
state (matrix_like): a matrix NxN
trace_systems (list(int)): a list of subsystems (s... |
Partial trace over subsystems of multi - partite vector. | def __partial_trace_vec(vec, trace_systems, dimensions, reverse=True):
"""
Partial trace over subsystems of multi-partite vector.
Args:
vec (vector_like): complex vector N
trace_systems (list(int)): a list of subsystems (starting from 0) to
trace over.
... |
Partial trace over subsystems of multi - partite matrix. | def __partial_trace_mat(mat, trace_systems, dimensions, reverse=True):
"""
Partial trace over subsystems of multi-partite matrix.
Note that subsystems are ordered as rho012 = rho0(x)rho1(x)rho2.
Args:
mat (matrix_like): a matrix NxN.
trace_systems (list(int)): a list of subsystems (sta... |
Flatten an operator to a vector in a specified basis. | def vectorize(density_matrix, method='col'):
"""Flatten an operator to a vector in a specified basis.
Args:
density_matrix (ndarray): a density matrix.
method (str): the method of vectorization. Allowed values are
- 'col' (default) flattens to column-major vector.
- 'row... |
Devectorize a vectorized square matrix. | def devectorize(vectorized_mat, method='col'):
"""Devectorize a vectorized square matrix.
Args:
vectorized_mat (ndarray): a vectorized density matrix.
method (str): the method of devectorization. Allowed values are
- 'col' (default): flattens to column-major vector.
- 'r... |
Convert a Choi - matrix to a Pauli - basis superoperator. | def choi_to_rauli(choi, order=1):
"""
Convert a Choi-matrix to a Pauli-basis superoperator.
Note that this function assumes that the Choi-matrix
is defined in the standard column-stacking convention
and is normalized to have trace 1. For a channel E this
is defined as: choi = (I \\otimes E)(bel... |
Truncate small values of a complex array. | def chop(array, epsilon=1e-10):
"""
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.
"""
ret = np.array(array)
if np.isrea... |
Construct the outer product of two vectors. | def outer(vector1, vector2=None):
"""
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.
R... |
Deprecated in 0. 8 + | def random_unitary_matrix(dim, seed=None):
"""Deprecated in 0.8+
"""
warnings.warn('The random_unitary_matrix() function in qiskit.tools.qi has been '
'deprecated and will be removed in the future. Instead use '
'the function in qiskit.quantum_info.random',
... |
Deprecated in 0. 8 + | def random_density_matrix(length, rank=None, method='Hilbert-Schmidt', seed=None):
"""Deprecated in 0.8+
"""
warnings.warn('The random_density_matrix() function in qiskit.tools.qi has been '
'deprecated and will be removed in the future. Instead use '
'the function in qis... |
Calculate the concurrence. | def concurrence(state):
"""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.
"""
rho = np.array(st... |
Compute the Shannon entropy of a probability vector. | def shannon_entropy(pvec, base=2):
"""
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 bas... |
Compute the von - Neumann entropy of a quantum state. | def entropy(state):
"""
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).
"""
rho = np.array(state)
if rho.ndim == 1:
return 0
evals = np.maximum(np.li... |
Compute the mutual information of a bipartite state. | def mutual_information(state, d0, d1=None):
"""
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:
... |
Compute the entanglement of formation of quantum state. | def entanglement_of_formation(state, d0, d1=None):
"""
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... |
Compute the Entanglement of Formation of a 2 - qubit density matrix. | def __eof_qubit(rho):
"""
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.
"""
c = concurrence(rho)
c = 0.5 + 0.5 * np.sqrt(1 - c * c)
retur... |
Create a union ( and also shift if desired ) of all input Schedule s. | def union(*schedules: List[Union[ScheduleComponent, Tuple[int, ScheduleComponent]]],
name: str = None) -> Schedule:
"""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 firs... |
Create a flattened schedule. | def flatten(schedule: ScheduleComponent, name: str = None) -> Schedule:
"""Create a flattened schedule.
Args:
schedule: Schedules to flatten
name: Name of the new schedule. Defaults to first element of `schedules`
"""
if name is None:
name = schedule.name
return Schedule(*s... |
Return schedule shifted by time. | def shift(schedule: ScheduleComponent, time: int, name: str = None) -> Schedule:
"""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`
"""
if name is None:
nam... |
Return a new schedule with the child schedule inserted into the parent at start_time. | def insert(parent: ScheduleComponent, time: int, child: ScheduleComponent,
name: str = None) -> Schedule:
"""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 r... |
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. | def append(parent: ScheduleComponent, child: ScheduleComponent,
name: str = None) -> Schedule:
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 =... |
Apply u3 to q. | def u3(self, theta, phi, lam, q):
"""Apply u3 to q."""
return self.append(U3Gate(theta, phi, lam), [q], []) |
Return backend status. | def status(self):
"""Return backend status.
Returns:
BackendStatus: the status of the backend.
"""
return BackendStatus(backend_name=self.name(),
backend_version=__version__,
operational=True,
... |
Start the progress bar. | def start(self, iterations):
"""Start the progress bar.
Parameters:
iterations (int): Number of iterations.
"""
self.touched = True
self.iter = int(iterations)
self.t_start = time.time() |
Estimate the remaining time left. | def time_remaining_est(self, completed_iter):
"""Estimate the remaining time left.
Parameters:
completed_iter (int): Number of iterations completed.
Returns:
est_time: Estimated time remaining.
"""
if completed_iter:
t_r_est = (time.time() - ... |
Run the CommutativeCancellation pass on a dag | def run(self, dag):
"""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
"""
... |
Return a list of QuantumCircuit object ( s ) from a qobj | def _experiments_to_circuits(qobj):
"""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
"""
if qobj.experiments:
circuits = []
for x i... |
Dissasemble a qobj and return the circuits run_config and user header | def disassemble(qobj):
"""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... |
Calculate the Hamming distance between two bit strings | def hamming_distance(str1, str2):
"""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
"""
if len(str1) != ... |
Plot a histogram of data. | def plot_histogram(data, figsize=(7, 5), color=None, number_to_keep=None,
sort='asc', target_string=None,
legend=None, bar_labels=True, title=None):
"""Plot a histogram of data.
Args:
data (list or dict): This is either a list of dictionaries or a single
... |
Return quaternion for rotation about given axis. | def quaternion_from_axis_rotation(angle, axis):
"""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.
"""
... |
Generate a quaternion from a set of Euler angles. | def quaternion_from_euler(angles, order='yzy'):
"""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.
"""... |
Normalizes a Quaternion to unit length so that it represents a valid rotation. | def normalize(self, inplace=False):
"""Normalizes a Quaternion to unit length
so that it represents a valid rotation.
Args:
inplace (bool): Do an inplace normalization.
Returns:
Quaternion: Normalized quaternion.
"""
if inplace:
nrm =... |
Converts a unit - length quaternion to a rotation matrix. | def to_matrix(self):
"""Converts a unit-length quaternion to a rotation matrix.
Returns:
ndarray: Rotation matrix.
"""
w, x, y, z = self.normalize().data # pylint: disable=C0103
mat = np.array([
[1-2*y**2-2*z**2, 2*x*y-2*z*w, 2*x*z+2*y*w],
[2... |
Converts a unit - length quaternion to a sequence of ZYZ Euler angles. | def to_zyz(self):
"""Converts a unit-length quaternion to a sequence
of ZYZ Euler angles.
Returns:
ndarray: Array of Euler angles.
"""
mat = self.to_matrix()
euler = np.zeros(3, dtype=float)
if mat[2, 2] < 1:
if mat[2, 2] > -1:
... |
Prepare received data for representation. | def process_data(data, number_to_keep):
""" 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.
"""
re... |
Create a histogram representation. | def iplot_histogram(data, figsize=None, number_to_keep=None,
sort='asc', legend=None):
""" Create a histogram representation.
Graphical representation of the input array using a vertical bars
style graph.
Args:
data (list or dict): This is either a list of ... |
Customize check_type for handling containers. | def check_type(self, value, attr, data):
"""Customize check_type for handling containers."""
# Check the type in the standard way first, in order to fail quickly
# in case of invalid values.
root_value = super(InstructionParameter, self).check_type(
value, attr, data)
... |
Check that j is a valid index into self. | def check_range(self, j):
"""Check that j is a valid index into self."""
if isinstance(j, int):
if j < 0 or j >= self.size:
raise QiskitIndexError("register index out of range")
elif isinstance(j, slice):
if j.start < 0 or j.stop >= self.size or (j... |
Print with indent. | def to_string(self, indent):
"""Print with indent."""
ind = indent * ' '
if self.root:
print(ind, self.type, '---', self.root)
else:
print(ind, self.type)
indent = indent + 3
ind = indent * ' '
for children in self.children:
if ... |
Assemble a QasmQobjInstruction | def assemble(self):
"""Assemble a QasmQobjInstruction"""
instruction = super().assemble()
if self.label:
instruction.label = self.label
return instruction |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.