Python collections.abc.Sequence() Examples

The following are 30 code examples of collections.abc.Sequence(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module collections.abc , or try the search function .
Example #1
Source File: pools.py    From python-pool-performance with MIT License 6 votes vote down vote up
def run_test(work_type: FunctionType, job_sets: Sequence, trials: int,
             pool_class: type, worker_count: int) -> Mapping:
    pool = pool_class(worker_count)
    if work_type == 'compute':
        test_func = pool.run_compute_test
    elif work_type == 'network':
        test_func = pool.run_network_test
    else:
        raise Exception("Invalid work type: {}".format(work_type))
    results = map(
        lambda jobs: test_func(jobs, trials, show_progress=True),
        tqdm(job_sets, desc=pool_class.__name__),
    )
    summarized_results = list(map(summarize_test, results))
    pool.destroy_pool()
    return summarized_results 
Example #2
Source File: engine.py    From hiku with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _check_store_fields(node, fields, ids, result):
    if node.name is not None:
        assert ids is not None
        if (
            isinstance(result, Sequence)
            and len(result) == len(ids)
            and all(isinstance(r, Sequence) and len(r) == len(fields)
                    for r in result)
        ):
            return
        else:
            expected = ('list (len: {}) of lists (len: {})'
                        .format(len(ids), len(fields)))
    else:
        if isinstance(result, Sequence) and len(result) == len(fields):
            return
        else:
            expected = 'list (len: {})'.format(len(fields))
    raise TypeError('Can\'t store field values, node: {!r}, fields: {!r}, '
                    'expected: {}, returned: {!r}'
                    .format(node.name or '__root__', [f.name for f in fields],
                            expected, result)) 
Example #3
Source File: recall.py    From mmdetection with Apache License 2.0 6 votes vote down vote up
def set_recall_param(proposal_nums, iou_thrs):
    """Check proposal_nums and iou_thrs and set correct format."""
    if isinstance(proposal_nums, Sequence):
        _proposal_nums = np.array(proposal_nums)
    elif isinstance(proposal_nums, int):
        _proposal_nums = np.array([proposal_nums])
    else:
        _proposal_nums = proposal_nums

    if iou_thrs is None:
        _iou_thrs = np.array([0.5])
    elif isinstance(iou_thrs, Sequence):
        _iou_thrs = np.array(iou_thrs)
    elif isinstance(iou_thrs, float):
        _iou_thrs = np.array([iou_thrs])
    else:
        _iou_thrs = iou_thrs

    return _proposal_nums, _iou_thrs 
Example #4
Source File: scan.py    From ms_deisotope with Apache License 2.0 6 votes vote down vote up
def isolation_window(self, value):
        if isinstance(value, IsolationWindow) or value is None:
            self._isolation_window = value
        elif isinstance(value, Sequence):
            if len(value) == 2:
                lo, hi = value
                width = (hi - lo) / 2.
                center = lo + width
                self._isolation_window = IsolationWindow(center, width, width)
            elif len(value) == 3:
                lo, center, hi = value
                self._isolation_window = IsolationWindow(lo, center, hi)
            else:
                raise ValueError("Could not convert %r to an %r" %
                                 (value, IsolationWindow))
        else:
            raise TypeError(
                "isolation_window must be an either an %r instance or a sequence of two or three elements" % (
                    IsolationWindow)) 
Example #5
Source File: dispatch.py    From ms_deisotope with Apache License 2.0 6 votes vote down vote up
def _resolve(self, key):
        if key in self.mapping:
            return self.mapping[key]
        for k, v in self.mapping.items():
            if not isinstance(k, Sequence):
                continue
            if key in k:
                return v
        best_substr = None
        best_substr_len = -1
        if not isinstance(key, Sequence):
            raise KeyError(key)
        for k, v in self.mapping.items():
            if k in key:
                substr_len = len(k)
                if substr_len > best_substr_len:
                    best_substr = k
                    best_substr_len = substr_len
        if best_substr_len > 0:
            return self.mapping[best_substr]
        raise KeyError(key) 
Example #6
Source File: __init__.py    From mongoquery with The Unlicense 6 votes vote down vote up
def _path_exists(self, operator, condition, entry):
        keys_list = list(operator.split('.'))
        for i, k in enumerate(keys_list):
            if isinstance(entry, Sequence) and not k.isdigit():
                for elem in entry:
                    operator = '.'.join(keys_list[i:])
                    if self._path_exists(operator, condition, elem) == condition:
                        return condition
                return not condition
            elif isinstance(entry, Sequence):
                k = int(k)
            try:
                entry = entry[k]
            except (TypeError, IndexError, KeyError):
                return not condition
        return condition 
Example #7
Source File: electrodes.py    From pulse2percept with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, x, y, z):
        if isinstance(x, (Sequence, np.ndarray)):
            raise TypeError("x must be a scalar, not %s." % (type(x)))
        if isinstance(y, (Sequence, np.ndarray)):
            raise TypeError("y must be a scalar, not %s." % type(y))
        if isinstance(z, (Sequence, np.ndarray)):
            raise TypeError("z must be a scalar, not %s." % type(z))
        self.x = x
        self.y = y
        self.z = z
        # A matplotlib.patches object (e.g., Circle, Rectangle) that can be
        # used to plot the electrode:
        self.plot_patch = None
        # Any keyword arguments that should be passed to the call above:
        # (e.g., {'radius': 5}):
        self.plot_kwargs = {} 
Example #8
Source File: ops.py    From strawberryfields with Apache License 2.0 6 votes vote down vote up
def __or__(self, reg):
        """Apply the operation to a part of a quantum register.

        Appends the Operation to a :class:`.Program` instance.

        Args:
            reg (RegRef, Sequence[RegRef]): subsystem(s) the operation is acting on

        Returns:
            list[RegRef]: subsystem list as RegRefs
        """
        # into a list of subsystems
        reg = _seq_to_list(reg)
        if (not reg) or (self.ns is not None and self.ns != len(reg)):
            raise ValueError("Wrong number of subsystems.")
        # append it to the Program
        reg = pu.Program_current_context.append(self, reg)
        return reg 
Example #9
Source File: text_logger.py    From DenseMatchingBenchmark with MIT License 6 votes vote down vote up
def _checkout(self, item):
        if isinstance(item, container_abcs.Mapping):
            flag = True
            for key in item.keys():
                flag = flag and self._checkout(item[key])
            return flag

        if isinstance(item, container_abcs.Sequence):
            flag = True
            for val in item:
                flag = flag and self._checkout(val)
            return flag

        if isinstance(item, (np.ndarray)):
            if item.size > 1:
                return False
            else:
                return True
        if isinstance(item, (numbers.Number)):
            return True 
Example #10
Source File: misc.py    From vedaseg with Apache License 2.0 6 votes vote down vote up
def is_seq_of(seq, expected_type, seq_type=None):
    """Check whether it is a sequence of some type.

    Args:
        seq (Sequence): The sequence to be checked.
        expected_type (type): Expected type of sequence items.
        seq_type (type, optional): Expected sequence type.

    Returns:
        bool: Whether the sequence is valid.
    """
    if seq_type is None:
        exp_seq_type = collections_abc.Sequence
    else:
        assert isinstance(seq_type, type)
        exp_seq_type = seq_type
    if not isinstance(seq, exp_seq_type):
        return False
    for item in seq:
        if not isinstance(item, expected_type):
            return False
    return True 
Example #11
Source File: more.py    From python-netsurv with MIT License 6 votes vote down vote up
def always_reversible(iterable):
    """An extension of :func:`reversed` that supports all iterables, not
    just those which implement the ``Reversible`` or ``Sequence`` protocols.

        >>> print(*always_reversible(x for x in range(3)))
        2 1 0

    If the iterable is already reversible, this function returns the
    result of :func:`reversed()`. If the iterable is not reversible,
    this function will cache the remaining items in the iterable and
    yield them in reverse order, which may require significant storage.
    """
    try:
        return reversed(iterable)
    except TypeError:
        return reversed(list(iterable)) 
Example #12
Source File: more.py    From python-netsurv with MIT License 6 votes vote down vote up
def always_reversible(iterable):
    """An extension of :func:`reversed` that supports all iterables, not
    just those which implement the ``Reversible`` or ``Sequence`` protocols.

        >>> print(*always_reversible(x for x in range(3)))
        2 1 0

    If the iterable is already reversible, this function returns the
    result of :func:`reversed()`. If the iterable is not reversible,
    this function will cache the remaining items in the iterable and
    yield them in reverse order, which may require significant storage.
    """
    try:
        return reversed(iterable)
    except TypeError:
        return reversed(list(iterable)) 
Example #13
Source File: utils.py    From dimod with Apache License 2.0 5 votes vote down vote up
def serialize_ndarrays(obj, use_bytes=False, bytes_type=bytes):
    """Look through the object, serializing NumPy arrays.

    Developer note: this function was written for serializing info fields
    in the sample set and binary quadratic model objects. This is not a general
    serialization function.

    Notes:
        Lists and dicts are copies in the returned object. Does not attempt to
        only copy-on-write, even though that would be more performant.

        Does not check for recursive references.

    """
    if isinstance(obj, np.ndarray):
        return serialize_ndarray(obj, use_bytes=use_bytes, bytes_type=bytes_type)
    elif isinstance(obj, abc.Mapping):
        return {serialize_ndarrays(key): serialize_ndarrays(val)
                for key, val in obj.items()}
    elif isinstance(obj, abc.Sequence) and not isinstance(obj, str):
        return list(map(serialize_ndarrays, obj))
    if isinstance(obj, Integral):
        return int(obj)
    elif isinstance(obj, Number):
        return float(obj)
    return obj 
Example #14
Source File: fuzzylogic.py    From fylearn with MIT License 5 votes vote down vote up
def helper_np_array(X):
    if isinstance(X, (np.ndarray, np.generic)):
        return X
    elif isinstance(X, Sequence):
        return np.array(X)
    elif isinstance(X, numbers.Number):
        return np.array([X])
    else:
        raise ValueError("unsupported type for building np.array: %s" % (type(X),)) 
Example #15
Source File: asserts.py    From dimod with Apache License 2.0 5 votes vote down vote up
def assert_composite_api(composed_sampler):
    """Assert that an instantiated composed sampler exposes correct composite
    properties and methods.

    Args:
        sampler (:obj:`.Composite`):
            User-made dimod composed sampler.

    Raises:
        AssertionError: If the given sampler does not match the composite API.

    See also:
        :class:`.Composite` for the abstract base class that defines the composite API.

        :obj:`~.assert_sampler_api` to assert that the composed sampler matches the sampler API.

    """

    assert isinstance(composed_sampler, dimod.Composite)

    # properties

    msg = "instantiated composed sampler must have a 'children' property, set to a list (or Sequence)"
    assert hasattr(composed_sampler, 'children'), msg
    assert isinstance(composed_sampler.children, abc.Sequence), msg

    msg = "instantiated composed sampler must have a 'child' property, set to one of sampler.children"
    assert hasattr(composed_sampler, 'child'), msg
    assert composed_sampler.child in composed_sampler.children, msg 
Example #16
Source File: utils.py    From dimod with Apache License 2.0 5 votes vote down vote up
def deserialize_ndarrays(obj):
    """Inverse of dfs_serialize_ndarray."""
    if isinstance(obj, abc.Mapping):
        if obj.get('type', '') == 'array':
            return deserialize_ndarray(obj)
        return {key: deserialize_ndarrays(val) for key, val in obj.items()}
    elif isinstance(obj, abc.Sequence) and not isinstance(obj, str):
        return list(map(deserialize_ndarrays, obj))
    return obj 
Example #17
Source File: ops.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def apply(self, reg, backend, **kwargs):
        """Ask a local backend to execute the operation on the current register state right away.

        Takes care of parameter evaluations and any pending formal
        transformations (like dagger) and then calls :meth:`Operation._apply`.

        Args:
            reg (Sequence[RegRef]): subsystem(s) the operation is acting on
            backend (BaseBackend): backend to execute the operation

        Returns:
            Any: the result of self._apply
        """
        # NOTE: We cannot just replace all parameters with their evaluated
        # numerical values here. If we re-initialize a measured mode and
        # re-measure it, the corresponding MeasuredParameter value should change accordingly
        # when it is used again after the new measurement.

        # convert RegRefs back to indices for the backend API
        temp = [rr.ind for rr in reg]
        # call the child class specialized _apply method
        return self._apply(temp, backend, **kwargs)


# ====================================================================
# Derived operation classes
# ==================================================================== 
Example #18
Source File: ops.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def _apply(self, reg, backend, **kwargs):
        """Internal apply method. Uses numeric subsystem referencing.

        Args:
            reg (Sequence[int]): subsystem indices the operation is
                acting on (this is how the backend API wants them)
            backend (BaseBackend): backend to execute the operation

        Returns:
            array[Number] or None: Measurement results, if any; shape == (len(reg), shots).
        """
        raise NotImplementedError("Missing direct implementation: {}".format(self)) 
Example #19
Source File: ops.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def decompose(self, reg, **kwargs):
        """Decompose the operation into elementary operations supported by the backend API.

        See :mod:`strawberryfields.backends.base`.

        Args:
            reg (Sequence[RegRef]): subsystems the operation is acting on

        Returns:
            list[Command]: decomposition as a list of operations acting on specific subsystems
        """
        return self._decompose(reg, **kwargs) 
Example #20
Source File: samples.py    From dimod with Apache License 2.0 5 votes vote down vote up
def __iter__(self):
        # __iter__ is a mixin for Sequence but we can speed it up by
        # implementing it ourselves
        variables = self._variables
        for row in self._samples:
            yield SampleView(row, variables) 
Example #21
Source File: ops.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def _seq_to_list(s):
    "Converts a Sequence or a single object into a list."
    if not isinstance(s, Sequence):
        s = [s]
    return list(s) 
Example #22
Source File: base.py    From ms_deisotope with Apache License 2.0 5 votes vote down vote up
def _is_raw_sequence(self):
        if self.is_scan:
            return False
        else:
            if hasattr(self.scan, 'has_peak'):
                return False
            return isinstance(self.scan, _SequenceABC) 
Example #23
Source File: program_utils.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def __init__(self, op, reg):
        # accept a single RegRef in addition to a Sequence
        if not isinstance(reg, Sequence):
            reg = [reg]

        #: Operation: quantum operation to apply
        self.op = op
        #: Sequence[RegRef]: subsystems to which the operation is applied
        self.reg = reg 
Example #24
Source File: qcontainer.py    From avocado-vt with GNU General Public License v2.0 5 votes vote down vote up
def allocate_iothread(self, iothread, device):
        """
        Allocate iothread for device to use.

        :param iothread: iothread specified in params
                         could be:
                         'auto': allocate iothread based on schems specified by
                                 'iothread_scheme'.
                         iothread id: request specific iothread to use.
        :param device: device object
        :return: iothread object allocated
        """
        if self.is_dev_iothread_supported(device):
            iothread = self.__iothread_manager.request_iothread(iothread)
            dev_iothread_parent = {"busid": iothread.iothread_bus.busid}
            if device.parent_bus:
                if isinstance(device.parent_bus, Sequence):
                    device.parent_bus += (dev_iothread_parent,)
                else:
                    device.parent_bus = \
                        (device.parent_bus, dev_iothread_parent)
            else:
                device.parent_bus = (dev_iothread_parent,)
            return iothread
        else:
            err_msg = "Device %s(%s) not support iothread" % \
                (device.get_aid(), device.get_param("driver"))
            raise TypeError(err_msg) 
Example #25
Source File: more.py    From python-netsurv with MIT License 5 votes vote down vote up
def __init__(self, target):
        if not isinstance(target, Sequence):
            raise TypeError
        self._target = target 
Example #26
Source File: scan.py    From ms_deisotope with Apache License 2.0 5 votes vote down vote up
def arrays(self, value):
        if isinstance(value, RawDataArrays) or value is None:
            self._arrays = value
        elif isinstance(value, Sequence):
            if len(value) == 2:
                self._arrays = RawDataArrays(*map(np.asanyarray, value))
            elif len(value) == 3:
                self._arrays = RawDataArrays(*map(np.asanyarray, value[:2]), arrays=dict(value[2]))
            else:
                raise ValueError("Too many values to convert. Please provide two arrays, "
                                 "or two arrays and a dictionary of additional arrays.")
        else:
            raise TypeError(
                "arrays must be an instance of RawDataArrays or a pair of numpy arrays") 
Example #27
Source File: pytester.py    From python-netsurv with MIT License 5 votes vote down vote up
def _match_lines(self, lines2, match_func, match_nickname):
        """Underlying implementation of ``fnmatch_lines`` and ``re_match_lines``.

        :param list[str] lines2: list of string patterns to match. The actual
            format depends on ``match_func``
        :param match_func: a callable ``match_func(line, pattern)`` where line
            is the captured line from stdout/stderr and pattern is the matching
            pattern
        :param str match_nickname: the nickname for the match function that
            will be logged to stdout when a match occurs

        """
        assert isinstance(lines2, Sequence)
        lines2 = self._getlines(lines2)
        lines1 = self.lines[:]
        nextline = None
        extralines = []
        __tracebackhide__ = True
        for line in lines2:
            nomatchprinted = False
            while lines1:
                nextline = lines1.pop(0)
                if line == nextline:
                    self._log("exact match:", repr(line))
                    break
                elif match_func(nextline, line):
                    self._log("%s:" % match_nickname, repr(line))
                    self._log("   with:", repr(nextline))
                    break
                else:
                    if not nomatchprinted:
                        self._log("nomatch:", repr(line))
                        nomatchprinted = True
                    self._log("    and:", repr(nextline))
                extralines.append(nextline)
            else:
                self._log("remains unmatched: {!r}".format(line))
                pytest.fail(self._log_text) 
Example #28
Source File: more.py    From python-netsurv with MIT License 5 votes vote down vote up
def __init__(self, target):
        if not isinstance(target, Sequence):
            raise TypeError
        self._target = target 
Example #29
Source File: util.py    From python-netsurv with MIT License 5 votes vote down vote up
def issequence(x):
    return isinstance(x, Sequence) and not isinstance(x, str) 
Example #30
Source File: ops.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def __init__(self, par, select=None):
        super().__init__(par)
        #: None, Sequence[Number]: postselection values, one for each measured subsystem
        self.select = select