Search is not available for this dataset
text stringlengths 75 104k |
|---|
def _get_qubit_index(self, qubit):
"""Get the index number for a quantum bit
Args:
qubit (tuple): The tuple of the bit of the form
(register_name, bit_number)
Returns:
int: The index in the bit list
Raises:
VisualizationError: If the bi... |
def _load_schema(file_path, name=None):
"""Loads the QObj schema for use in future validations.
Caches schema in _SCHEMAS module attribute.
Args:
file_path(str): Path to schema.
name(str): Given name for schema. Defaults to file_path filename
without schema.
Return:
sc... |
def _get_validator(name, schema=None, check_schema=True,
validator_class=None, **validator_kwargs):
"""Generate validator for JSON schema.
Args:
name (str): Name for validator. Will be validator key in
`_VALIDATORS` dict.
schema (dict): JSON schema `dict`. If not ... |
def _load_schemas_and_validators():
"""Load all default schemas into `_SCHEMAS`."""
schema_base_path = os.path.join(os.path.dirname(__file__), '../..')
for name, path in _DEFAULT_SCHEMA_PATHS.items():
_load_schema(os.path.join(schema_base_path, path), name)
_get_validator(name) |
def validate_json_against_schema(json_dict, schema,
err_msg=None):
"""Validates JSON dict against a schema.
Args:
json_dict (dict): JSON to be validated.
schema (dict or str): JSON schema dictionary or the name of one of the
standards schemas in Qisk... |
def _format_causes(err, level=0):
"""Return a cascading explanation of the validation error.
Returns a cascading explanation of the validation error in the form of::
<validator> failed @ <subfield_path> because of:
<validator> failed @ <subfield_path> because of:
...
... |
def qasm(self, prec=15):
"""Return the corresponding OPENQASM string."""
return ",".join([self.children[j].qasm(prec)
for j in range(self.size())]) |
def majority(p, a, b, c):
"""Majority gate."""
p.cx(c, b)
p.cx(c, a)
p.ccx(a, b, c) |
def unmajority(p, a, b, c):
"""Unmajority gate."""
p.ccx(a, b, c)
p.cx(c, a)
p.cx(a, b) |
def _collect_potential_merges(dag, barriers):
"""
Returns a dict of DAGNode : Barrier objects, where the barrier needs to be
inserted where the corresponding DAGNode appears in the main DAG
"""
# if only got 1 or 0 barriers then can't merge
if len(barriers) < 2:
... |
def circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
output='text',
interactive=False,
line_length=None,
plot_barriers=True,
reverse_bits=False,
... |
def _text_circuit_drawer(circuit, filename=None, line_length=None, reverse_bits=False,
plotbarriers=True, justify=None, vertically_compressed=True):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename t... |
def _latex_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False,
justify=None):
"""Draw a quantum circuit based ... |
def _generate_latex_source(circuit, filename=None,
scale=0.7, style=None, reverse_bits=False,
plot_barriers=True, justify=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image sc... |
def _matplotlib_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False,
justify=None):
... |
def random_state(dim, seed=None):
"""
Return a random quantum state from the uniform (Haar) measure on
state space.
Args:
dim (int): the dim of the state spaxe
seed (int): Optional. To set a random seed.
Returns:
ndarray: state(2**num) a random quantum state.
"""
i... |
def random_unitary(dim, seed=None):
"""
Return a random dim x dim unitary Operator from the Haar measure.
Args:
dim (int): the dim of the state space.
seed (int): Optional. To set a random seed.
Returns:
Operator: (dim, dim) unitary operator.
Raises:
QiskitError: i... |
def random_density_matrix(length, rank=None, method='Hilbert-Schmidt', seed=None):
"""
Generate a random density matrix rho.
Args:
length (int): the length of the density matrix.
rank (int or None): the rank of the density matrix. The default
value is full-rank.
method (... |
def __ginibre_matrix(nrow, ncol=None, seed=None):
"""
Return a normally distributed complex random matrix.
Args:
nrow (int): number of rows in output matrix.
ncol (int): number of columns in output matrix.
seed (int): Optional. To set a random seed.
Returns:
ndarray: A c... |
def __random_density_hs(N, rank=None, seed=None):
"""
Generate a random density matrix from the Hilbert-Schmidt metric.
Args:
N (int): the length of the density matrix.
rank (int or None): the rank of the density matrix. The default
value is full-rank.
seed (int): Option... |
def __random_density_bures(N, rank=None, seed=None):
"""
Generate a random density matrix from the Bures metric.
Args:
N (int): the length of the density matrix.
rank (int or None): the rank of the density matrix. The default
value is full-rank.
seed (int): Optional. To ... |
def qasm(self, prec=15):
"""Return the corresponding OPENQASM string."""
string = ""
for children in self.children:
string += " " + children.qasm(prec) + "\n"
return string |
def calls(self):
"""Return a list of custom gate names in this gate body."""
lst = []
for children in self.children:
if children.type == "custom_unitary":
lst.append(children.name)
return lst |
def qasm(self, prec=15):
"""Return the corresponding OPENQASM string."""
if self.value == pi:
return "pi"
return ccode(self.value, precision=prec) |
def _define(self):
"""
gate sdg a { u1(-pi/2) a; }
"""
definition = []
q = QuantumRegister(1, "q")
rule = [
(U1Gate(-pi/2), [q[0]], [])
]
for inst in rule:
definition.append(inst)
self.definition = definition |
def compose(self, other, qargs=None, front=False):
"""Return the composition channel self∘other.
Args:
other (QuantumChannel): a quantum channel.
qargs (list): a list of subsystem positions to compose other on.
front (bool): If False compose in standard order other(s... |
def power(self, n):
"""The matrix power of the channel.
Args:
n (int): compute the matrix power of the superoperator matrix.
Returns:
Chi: the matrix power of the SuperOp converted to a Chi channel.
Raises:
QiskitError: if the input and output dimen... |
def add(self, other):
"""Return the QuantumChannel self + other.
Args:
other (QuantumChannel): a quantum channel.
Returns:
Chi: the linear addition self + other as a Chi object.
Raises:
QiskitError: if other is not a QuantumChannel subclass, or
... |
def multiply(self, other):
"""Return the QuantumChannel self + other.
Args:
other (complex): a complex number.
Returns:
Chi: the scalar multiplication other * self as a Chi object.
Raises:
QiskitError: if other is not a valid scalar.
"""
... |
def _tensor_product(self, other, reverse=False):
"""Return the tensor product channel.
Args:
other (QuantumChannel): a quantum channel.
reverse (bool): If False return self ⊗ other, if True return
if True return (other ⊗ self) [Default: False
... |
def conjugate(self):
"""Return the conjugate of the QuantumChannel."""
return SuperOp(
np.conj(self._data), self.input_dims(), self.output_dims()) |
def transpose(self):
"""Return the transpose of the QuantumChannel."""
return SuperOp(
np.transpose(self._data),
input_dims=self.output_dims(),
output_dims=self.input_dims()) |
def compose(self, other, qargs=None, front=False):
"""Return the composition channel self∘other.
Args:
other (QuantumChannel): a quantum channel.
qargs (list): a list of subsystem positions to compose other on.
front (bool): If False compose in standard order other(s... |
def power(self, n):
"""Return the compose of a QuantumChannel with itself n times.
Args:
n (int): compute the matrix power of the superoperator matrix.
Returns:
SuperOp: the n-times composition channel as a SuperOp object.
Raises:
QiskitError: if th... |
def add(self, other):
"""Return the QuantumChannel self + other.
Args:
other (QuantumChannel): a quantum channel.
Returns:
SuperOp: the linear addition self + other as a SuperOp object.
Raises:
QiskitError: if other cannot be converted to a channel ... |
def multiply(self, other):
"""Return the QuantumChannel self + other.
Args:
other (complex): a complex number.
Returns:
SuperOp: the scalar multiplication other * self as a SuperOp object.
Raises:
QiskitError: if other is not a valid scalar.
... |
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... |
def _compose_subsystem(self, other, qargs, front=False):
"""Return the composition channel."""
# Compute tensor contraction indices from qargs
input_dims = list(self.input_dims())
output_dims = list(self.output_dims())
if front:
num_indices = len(self.input_dims())
... |
def _evolve_subsystem(self, state, qargs):
"""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.
Retur... |
def _instruction_to_superop(cls, instruction):
"""Convert a QuantumCircuit or Instruction to a SuperOp."""
# Convert circuit to an instruction
if isinstance(instruction, QuantumCircuit):
instruction = instruction.to_instruction()
# Initialize an identity superoperator of the ... |
def _append_instruction(self, obj, qargs=None):
"""Update the current Operator by apply an instruction."""
if isinstance(obj, Instruction):
chan = None
if obj.name == 'reset':
# For superoperator evolution we can simulate a reset as
# a non-unitary... |
def run(self, dag):
"""Return a circuit with a barrier before last measurements."""
# Collect DAG nodes which are followed only by barriers or other measures.
final_op_types = ['measure', 'barrier']
final_ops = []
for candidate_node in dag.named_nodes(*final_op_types):
... |
def circuits_to_qobj(circuits, qobj_header=None,
qobj_id=None, backend_name=None,
config=None, shots=None, max_credits=None,
basis_gates=None,
coupling_map=None, seed=None, memory=None):
"""Convert a list of circuits into a qobj.
... |
def run(self, dag):
"""Expand 3+ qubit gates using their decomposition rules.
Args:
dag(DAGCircuit): input dag
Returns:
DAGCircuit: output dag with maximum node degrees of 2
Raises:
QiskitError: if a 3q+ gate is not decomposable
"""
fo... |
def run(self, dag):
"""Expand a given gate into its decomposition.
Args:
dag(DAGCircuit): input dag
Returns:
DAGCircuit: output dag where gate was expanded.
"""
# Walk through the DAG and expand each non-basis node
for node in dag.op_nodes(self.ga... |
def unitary(self, obj, qubits, label=None):
"""Apply u2 to q."""
if isinstance(qubits, QuantumRegister):
qubits = qubits[:]
return self.append(UnitaryGate(obj, label=label), qubits, []) |
def _define(self):
"""Calculate a subcircuit that implements this unitary."""
if self.num_qubits == 1:
q = QuantumRegister(1, "q")
angles = euler_angles_1q(self.to_matrix())
self.definition = [(U3Gate(*angles), [q[0]], [])]
if self.num_qubits == 2:
... |
def check_type(self, value, attr, data):
"""Validate if the value is of the type of the schema's model.
Assumes the nested schema is a ``BaseSchema``.
"""
if self.many and not is_collection(value):
raise self._not_expected_type(
value, Iterable, fields=[self]... |
def check_type(self, value, attr, data):
"""Validate if it's a list of valid item-field values.
Check if each element in the list can be validated by the item-field
passed during construction.
"""
super().check_type(value, attr, data)
errors = []
for idx, v in e... |
def dag_drawer(dag, scale=0.7, filename=None, style='color'):
"""Plot the directed acyclic graph (dag) to represent operation dependencies
in a quantum circuit.
Note this function leverages
`pydot <https://github.com/erocarrera/pydot>`_ (via
`nxpd <https://github.com/chebee7i/nxpd`_) to generate th... |
def _atol(self, atol):
"""Set the absolute tolerence parameter for float comparisons."""
# NOTE: that this overrides the class value so applies to all
# instances of the class.
max_tol = self.__class__.MAX_TOL
if atol < 0:
raise QiskitError("Invalid atol: must be non-... |
def _rtol(self, rtol):
"""Set the relative tolerence parameter for float comparisons."""
# NOTE: that this overrides the class value so applies to all
# instances of the class.
max_tol = self.__class__.MAX_TOL
if rtol < 0:
raise QiskitError("Invalid rtol: must be non-... |
def _reshape(self, input_dims=None, output_dims=None):
"""Reshape input and output dimensions of operator.
Arg:
input_dims (tuple): new subsystem input dimensions.
output_dims (tuple): new subsystem output dimensions.
Returns:
Operator: returns self with res... |
def input_dims(self, qargs=None):
"""Return tuple of input dimension for specified subsystems."""
if qargs is None:
return self._input_dims
return tuple(self._input_dims[i] for i in qargs) |
def output_dims(self, qargs=None):
"""Return tuple of output dimension for specified subsystems."""
if qargs is None:
return self._output_dims
return tuple(self._output_dims[i] for i in qargs) |
def copy(self):
"""Make a copy of current operator."""
# pylint: disable=no-value-for-parameter
# The constructor of subclasses from raw data should be a copy
return self.__class__(self.data, self.input_dims(), self.output_dims()) |
def power(self, n):
"""Return the compose of a operator with itself n times.
Args:
n (int): the number of times to compose with self (n>0).
Returns:
BaseOperator: the n-times composed operator.
Raises:
QiskitError: if the input and output dimensions... |
def _automatic_dims(cls, dims, size):
"""Check if input dimension corresponds to qubit subsystems."""
if dims is None:
dims = size
elif np.product(dims) != size:
raise QiskitError("dimensions do not match size.")
if isinstance(dims, (int, np.integer)):
... |
def _einsum_matmul(cls, tensor, mat, indices, shift=0, right_mul=False):
"""Perform a contraction using Numpy.einsum
Args:
tensor (np.array): a vector or matrix reshaped to a rank-N tensor.
mat (np.array): a matrix reshaped to a rank-2M tensor.
indices (list): tensor... |
def _deserialize(self, value, attr, data):
"""Override ``_deserialize`` for customizing the exception raised."""
try:
return super()._deserialize(value, attr, data)
except ValidationError as ex:
if 'deserialization_schema_selector' in ex.messages[0]:
ex.me... |
def _serialize(self, value, key, obj):
"""Override ``_serialize`` for customizing the exception raised."""
try:
return super()._serialize(value, key, obj)
except TypeError as ex:
if 'serialization_schema_selector' in str(ex):
raise ValidationError('Data fr... |
def check_type(self, value, attr, data):
"""Check if at least one of the possible choices validates the value.
Possible choices are assumed to be ``ModelTypeValidator`` fields.
"""
for field in self.choices:
if isinstance(field, ModelTypeValidator):
try:
... |
def state_fidelity(state1, state2):
"""Return the state fidelity between two quantum states.
Either input may be a state vector, or a density matrix. The state
fidelity (F) for two density matrices is defined as::
F(rho1, rho2) = Tr[sqrt(sqrt(rho1).rho2.sqrt(rho1))] ^ 2
For a pure state and m... |
def _funm_svd(a, func):
"""Apply real scalar function to singular values of a matrix.
Args:
a (array_like): (N, N) Matrix at which to evaluate the function.
func (callable): Callable object that evaluates a scalar function f.
Returns:
ndarray: funm (N, N) Value of the matrix functi... |
def run(self, dag):
"""
If `dag` is mapped to `coupling_map`, the property
`is_swap_mapped` is set to True (or to False otherwise).
Args:
dag (DAGCircuit): DAG to map.
"""
if self.layout is None:
if self.property_set["layout"]:
sel... |
def snapshot(self,
label,
snapshot_type='statevector',
qubits=None,
params=None):
"""Take a statevector snapshot of the internal simulator representation.
Works on all qubits, and prevents reordering (like barrier).
For other types of snapshots use the Sn... |
def assemble(self):
"""Assemble a QasmQobjInstruction"""
instruction = super().assemble()
instruction.label = self._label
instruction.snapshot_type = self._snapshot_type
return instruction |
def inverse(self):
"""Special case. Return self."""
return Snapshot(self.num_qubits, self.num_clbits, self.params[0],
self.params[1]) |
def label(self, name):
"""Set snapshot label to name
Args:
name (str or None): label to assign unitary
Raises:
TypeError: name is not string or None.
"""
if isinstance(name, str):
self._label = name
else:
raise TypeError('... |
def is_cptp(self, atol=None, rtol=None):
"""Return True if completely-positive trace-preserving (CPTP)."""
choi = _to_choi(self.rep, self._data, *self.dim)
return self._is_cp_helper(choi, atol, rtol) and self._is_tp_helper(
choi, atol, rtol) |
def is_tp(self, atol=None, rtol=None):
"""Test if a channel is completely-positive (CP)"""
choi = _to_choi(self.rep, self._data, *self.dim)
return self._is_tp_helper(choi, atol, rtol) |
def is_cp(self, atol=None, rtol=None):
"""Test if Choi-matrix is completely-positive (CP)"""
choi = _to_choi(self.rep, self._data, *self.dim)
return self._is_cp_helper(choi, atol, rtol) |
def is_unitary(self, atol=None, rtol=None):
"""Return True if QuantumChannel is a unitary channel."""
try:
op = self.to_operator()
return op.is_unitary(atol=atol, rtol=rtol)
except QiskitError:
return False |
def to_operator(self):
"""Try to convert channel to a unitary representation Operator."""
mat = _to_operator(self.rep, self._data, *self.dim)
return Operator(mat, self.input_dims(), self.output_dims()) |
def to_instruction(self):
"""Convert to a Kraus or UnitaryGate circuit instruction.
If the channel is unitary it will be added as a unitary gate,
otherwise it will be added as a kraus simulator instruction.
Returns:
Instruction: A kraus instruction for the channel.
... |
def _is_cp_helper(self, choi, atol, rtol):
"""Test if a channel is completely-positive (CP)"""
if atol is None:
atol = self._atol
if rtol is None:
rtol = self._rtol
return is_positive_semidefinite_matrix(choi, rtol=rtol, atol=atol) |
def _is_tp_helper(self, choi, atol, rtol):
"""Test if Choi-matrix is trace-preserving (TP)"""
if atol is None:
atol = self._atol
if rtol is None:
rtol = self._rtol
# Check if the partial trace is the identity matrix
d_in, d_out = self.dim
mat = np.... |
def _format_state(self, state, density_matrix=False):
"""Format input state so it is statevector or density matrix"""
state = np.array(state)
shape = state.shape
ndim = state.ndim
if ndim > 2:
raise QiskitError('Input state is not a vector or matrix.')
# Flatt... |
def _init_transformer(cls, data):
"""Convert input into a QuantumChannel subclass object or Operator object"""
# This handles common conversion for all QuantumChannel subclasses.
# If the input is already a QuantumChannel subclass it will return
# the original object
if isinstanc... |
def run(self, dag):
"""
If `dag` is mapped and the direction is correct the property
`is_direction_mapped` is set to True (or to False otherwise).
Args:
dag (DAGCircuit): DAG to check.
"""
if self.layout is None:
if self.property_set["layout"]:
... |
def sort_enum_for_model(cls, name=None, symbol_name=_symbol_name):
"""Create Graphene Enum for sorting a SQLAlchemy class query
Parameters
- cls : Sqlalchemy model class
Model used to create the sort enumerator
- name : str, optional, default None
Name to use for the enumerator. If not ... |
def sort_argument_for_model(cls, has_default=True):
"""Returns a Graphene argument for the sort field that accepts a list of sorting directions for a model.
If `has_default` is True (the default) it will sort the result by the primary key(s)
"""
enum, default = _sort_enum_for_model(cls)
if not has_d... |
def search_dates(text, languages=None, settings=None, add_detected_language=False):
"""Find all substrings of the given string which represent date and/or time and parse them.
:param text:
A string in a natural language which may contain date and/or time expressions.
:type text: str|uni... |
def patch_strptime():
"""Monkey patching _strptime to avoid problems related with non-english
locale changes on the system.
For example, if system's locale is set to fr_FR. Parser won't recognize
any date since all languages are translated to english dates.
"""
_strptime = imp.load_module(
... |
def get_locale_map(self, languages=None, locales=None, region=None,
use_given_order=False, allow_conflicting_locales=False):
"""
Get an ordered mapping with locale codes as keys
and corresponding locale instances as values.
:param languages:
A list of ... |
def get_locales(self, languages=None, locales=None, region=None,
use_given_order=False, allow_conflicting_locales=False):
"""
Yield locale instances.
:param languages:
A list of language codes, e.g. ['en', 'es', 'zh-Hant'].
If locales are not given, l... |
def are_tokens_valid(self, tokens):
"""
Check if tokens are valid tokens for the locale.
:param tokens:
a list of string or unicode tokens.
:type tokens: list
:return: True if tokens are valid, False otherwise.
"""
match_relative_regex = self._get_ma... |
def split(self, string, keep_formatting=False):
"""
Split the date string using translations in locale info.
:param string:
Date string to be splitted.
:type string:
str|unicode
:param keep_formatting:
If True, retain formatting of the date s... |
def search_dates(self, text, languages=None, settings=None):
"""
Find all substrings of the given string which represent date and/or time and parse them.
:param text:
A string in a natural language which may contain date and/or time expressions.
:type text: str|unicode
... |
def parse(date_string, date_formats=None, languages=None, locales=None, region=None, settings=None):
"""Parse date and time from given date string.
:param date_string:
A string representing date and/or time in a recognizably valid format.
:type date_string: str|unicode
:param date_formats:
... |
def _parse_time(self, date_string, settings):
"""Attemps to parse time part of date strings like '1 day ago, 2 PM' """
date_string = PATTERN.sub('', date_string)
date_string = re.sub(r'\b(?:ago|in)\b', '', date_string)
try:
return time_parser(date_string)
except:
... |
def is_applicable(self, date_string, strip_timezone=False, settings=None):
"""
Check if the locale is applicable to translate date string.
:param date_string:
A string representing date and/or time in a recognizably valid format.
:type date_string: str|unicode
:para... |
def translate(self, date_string, keep_formatting=False, settings=None):
"""
Translate the date string to its English equivalent.
:param date_string:
A string representing date and/or time in a recognizably valid format.
:type date_string: str|unicode
:param keep_for... |
def parse_with_formats(date_string, date_formats, settings):
""" Parse with formats and return a dictionary with 'period' and 'obj_date'.
:returns: :class:`datetime.datetime`, dict or None
"""
period = 'day'
for date_format in date_formats:
try:
date_obj = datetime.strptime(dat... |
def get_date_data(self, date_string, date_formats=None):
"""
Parse string representing date and/or time in recognizable localized formats.
Supports parsing multiple languages and timezones.
:param date_string:
A string representing date and/or time in a recognizably valid fo... |
def get_load_plan(self):
"""
return load plan (timestamps generator)
"""
if self.rps_schedule and self.instances_schedule:
raise StepperConfigurationError(
'Both rps and instances schedules specified. You must specify only one of them'
)
el... |
def get_ammo_generator(self):
"""
return ammo generator
"""
af_readers = {
'phantom': missile.AmmoFileReader,
'slowlog': missile.SlowLogReader,
'line': missile.LineReader,
'uri': missile.UriReader,
'uripost': missile.UriPostRead... |
def _exc_to_net(param1, success):
""" translate http code to net code. if accertion failed, set net code to 314 """
if len(param1) <= 3:
# FIXME: we're unable to use better logic here, because we should support non-http codes
# but, we should look for core.util.HTTP or some other common logic
... |
def _exc_to_http(param1):
""" translate exception str to http code"""
if len(param1) <= 3:
try:
int(param1)
except BaseException:
logger.error(
"JMeter wrote some strange data into codes column: %s", param1)
else:
return int(param1)
... |
def read_config(self):
""" Read phantom tool specific options """
self.threads = self.cfg["threads"] or str(int(multiprocessing.cpu_count() / 2) + 1)
self.phantom_modules_path = self.cfg["phantom_modules_path"]
self.additional_libs = ' '.join(self.cfg["additional_libs"])
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.