Python typing.Sized() Examples

The following are 16 code examples of typing.Sized(). 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 typing , or try the search function .
Example #1
Source File: itertools.py    From deep_pipe with MIT License 5 votes vote down vote up
def zip_equal(*args: Union[Sized, Iterable]) -> Iterable[Tuple]:
    """
    zip over the given iterables, but enforce that all of them exhaust simultaneously.

    Examples
    --------
    >>> zip_equal([1, 2, 3], [4, 5, 6]) # ok
    >>> zip_equal([1, 2, 3], [4, 5, 6, 7]) # raises ValueError
    # ValueError is raised even if the lengths are not known
    >>> zip_equal([1, 2, 3], map(np.sqrt, [4, 5, 6])) # ok
    >>> zip_equal([1, 2, 3], map(np.sqrt, [4, 5, 6, 7])) # raises ValueError
    """
    if not args:
        return

    lengths = []
    all_lengths = []
    for arg in args:
        try:
            lengths.append(len(arg))
            all_lengths.append(len(arg))
        except TypeError:
            all_lengths.append('?')

    if lengths and not all(x == lengths[0] for x in lengths):
        from .checks import join
        raise ValueError(f'The arguments have different lengths: {join(all_lengths)}.')

    iterables = [iter(arg) for arg in args]
    while True:
        result = []
        for it in iterables:
            with suppress(StopIteration):
                result.append(next(it))

        if len(result) != len(args):
            break
        yield tuple(result)

    if len(result) != 0:
        raise ValueError(f'The iterables did not exhaust simultaneously.') 
Example #2
Source File: test_typing.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_sized(self):
        assert isinstance([], typing.Sized)
        assert not isinstance(42, typing.Sized) 
Example #3
Source File: model.py    From FractalAI with GNU Affero General Public License v3.0 5 votes vote down vote up
def predict_batch(self, observations: [Sized, Iterable]) -> np.ndarray:
        """
        Returns a vector of actions chosen at random.
        :param observations: Represents a vector of observations. Only used in determining the size
        of the returned array.
        :return: Numpy array containing the action chosen for each observation.
        """

        if not self.use_block:
            return np.random.randint(0, high=int(self.n_actions), size=(len(observations),))
        self._i += 1
        return self.noise[: len(observations), self._i % self.samples] 
Example #4
Source File: model.py    From FractalAI with GNU Affero General Public License v3.0 5 votes vote down vote up
def predict_batch(self, observations: [Sized, Iterable]) -> np.ndarray:
        """
        Returns a vector of actions chosen at random.
        :param observations: Represents a vector of observations. Only used in determining the size
        of the returned array.
        :return: Numpy array containing the action chosen for each observation.
        """

        return np.random.randint(1, high=13, size=(len(observations),)) 
Example #5
Source File: model.py    From FractalAI with GNU Affero General Public License v3.0 5 votes vote down vote up
def predict_batch(self, observations: [Sized, Iterable]) -> np.ndarray:
        """
        Returns a vector of actions chosen at random.
        :param observations: Represents a vector of observations. Only used in determining the size
        of the returned array.
        :return: Numpy array containing the action chosen for each observation.
        """

        perturbations = []
        for i in range(len(observations)):
            x = [np.random.randn(*shape) * self.sigma for shape in self.weigths_shapes]
            perturbations.append(x)
        return np.array(perturbations) 
Example #6
Source File: dataset_type.py    From ebonite with Apache License 2.0 5 votes vote down vote up
def serialize(self, instance: Sized):
        _check_type_and_size(instance, self.actual_type, len(self.items), SerializationError)
        return self.actual_type(serialize(o, t) for t, o in zip(self.items, instance)) 
Example #7
Source File: spaces.py    From habitat-api with MIT License 5 votes vote down vote up
def contains(self, x):
        if not isinstance(x, Sized):
            return False

        if not (self.min_seq_length <= len(x) <= self.max_seq_length):
            return False

        return all([self.space.contains(el) for el in x]) 
Example #8
Source File: data_io.py    From sockeye with Apache License 2.0 5 votes vote down vote up
def are_none(sequences: Sequence[Sized]) -> bool:
    """
    Returns True if all sequences are None.
    """
    if not sequences:
        return True
    return all(s is None for s in sequences) 
Example #9
Source File: data_io.py    From sockeye with Apache License 2.0 5 votes vote down vote up
def are_token_parallel(sequences: Sequence[Sized]) -> bool:
    """
    Returns True if all sequences in the list have the same length.
    """
    if not sequences or len(sequences) == 1:
        return True
    return all(len(s) == len(sequences[0]) for s in sequences) 
Example #10
Source File: test_typing.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_sized(self):
        self.assertIsInstance([], typing.Sized)
        self.assertNotIsInstance(42, typing.Sized) 
Example #11
Source File: utils.py    From DeepPavlov with Apache License 2.0 5 votes vote down vote up
def _get_all_dimensions(batch: Sequence, level: int = 0, res: Optional[List[List[int]]] = None) -> List[List[int]]:
    """Return all presented element sizes of each dimension.

    Args:
        batch: Data array.
        level: Recursion level.
        res: List containing element sizes of each dimension.

    Return:
        List, i-th element of which is list containing all presented sized of batch's i-th dimension.

    Examples:
        >>> x = [[[1], [2, 3]], [[4], [5, 6, 7], [8, 9]]]
        >>> _get_all_dimensions(x)
        [[2], [2, 3], [1, 2, 1, 3, 2]]

    """
    if not level:
        res = [[len(batch)]]
    if len(batch) and isinstance(batch[0], Sized) and not isinstance(batch[0], str):
        level += 1
        if len(res) <= level:
            res.append([])
        for item in batch:
            res[level].append(len(item))
            _get_all_dimensions(item, level, res)
    return res 
Example #12
Source File: robot.py    From pybotics with MIT License 5 votes vote down vote up
def from_parameters(cls, parameters: Sequence[float]) -> Sized:
        """Construct Robot from Kinematic Chain parameters."""
        # FIXME: assumes MDH revolute robot
        kc = MDHKinematicChain.from_parameters(parameters)
        return cls(kinematic_chain=kc) 
Example #13
Source File: model.py    From FractalAI with GNU Affero General Public License v3.0 5 votes vote down vote up
def predict_batch(self, observations: [Sized, Iterable]) -> np.ndarray:
        """
        Returns a vector of actions chosen at random.
        :param observations: Represents a vector of observations. Only used in determining the size
        of the returned array.
        :return: Numpy array containing the action chosen for each observation.
        """

        if not self.use_block:
            return np.random.randint(0, high=int(self.n_actions), size=(len(observations),))
        self._i += 1
        return self.noise[:len(observations), self._i % self.samples] 
Example #14
Source File: model.py    From FractalAI with GNU Affero General Public License v3.0 5 votes vote down vote up
def predict_batch(self, observations: [Sized, Iterable]) -> np.ndarray:
        """
        Returns a vector of actions chosen at random.
        :param observations: Represents a vector of observations. Only used in determining the size
        of the returned array.
        :return: Numpy array containing the action chosen for each observation.
        """

        perturbations = []
        for i in range(len(observations)):
            x = [np.random.randn(*shape) * self.sigma for shape in self.weigths_shapes]
            perturbations.append(x)
        return np.array(perturbations) 
Example #15
Source File: miscellaneous_routes.py    From FACT_core with GNU General Public License v3.0 5 votes vote down vote up
def _count_values(dictionary: Dict[str, Sized]) -> int:
        return sum(len(e) for e in dictionary.values()) 
Example #16
Source File: plotting.py    From bindsnet with GNU Affero General Public License v3.0 4 votes vote down vote up
def plot_assignments(
    assignments: torch.Tensor,
    im: Optional[AxesImage] = None,
    figsize: Tuple[int, int] = (5, 5),
    classes: Optional[Sized] = None,
) -> AxesImage:
    # language=rst
    """
    Plot the two-dimensional neuron assignments.

    :param assignments: Vector of neuron label assignments.
    :param im: Used for re-drawing the assignments plot.
    :param figsize: Horizontal, vertical figure size in inches.
    :param classes: Iterable of labels for colorbar ticks corresponding to data labels.
    :return: Used for re-drawing the assigments plot.
    """
    locals_assignments = assignments.detach().clone().cpu().numpy()
    if not im:
        fig, ax = plt.subplots(figsize=figsize)
        ax.set_title("Categorical assignments")

        if classes is None:
            color = plt.get_cmap("RdBu", 11)
            im = ax.matshow(
                locals_assignments, cmap=color, vmin=-1.5, vmax=9.5
            )
        else:
            color = plt.get_cmap("RdBu", len(classes) + 1)
            im = ax.matshow(
                locals_assignments,
                cmap=color,
                vmin=-1.5,
                vmax=len(classes) - 0.5,
            )

        div = make_axes_locatable(ax)
        cax = div.append_axes("right", size="5%", pad=0.05)

        if classes is None:
            cbar = plt.colorbar(im, cax=cax, ticks=list(range(-1, 11)))
            cbar.ax.set_yticklabels(["none"] + list(range(10)))
        else:
            cbar = plt.colorbar(im, cax=cax, ticks=np.arange(-1, len(classes)))
            cbar.ax.set_yticklabels(["none"] + list(classes))

        ax.set_xticks(())
        ax.set_yticks(())
        fig.tight_layout()
    else:
        im.set_data(locals_assignments)

    return im