Пример #1
0
def array_dtypes(
    subtype_strategy=scalar_dtypes(),  # type: st.SearchStrategy[np.dtype]
    min_size=1,  # type: int
    max_size=5,  # type: int
    allow_subarrays=False,  # type: bool
):
    # type: (...) -> st.SearchStrategy[np.dtype]
    """Return a strategy for generating array (compound) dtypes, with members
    drawn from the given subtype strategy."""
    order_check("size", 0, min_size, max_size)
    # Field names must be native strings and the empty string is weird; see #1963.
    if PY2:
        field_names = st.binary(min_size=1)
    else:
        field_names = st.text(min_size=1)
    elements = st.tuples(field_names, subtype_strategy)
    if allow_subarrays:
        elements |= st.tuples(
            field_names, subtype_strategy, array_shapes(max_dims=2, max_side=2)
        )
    return st.lists(
        elements=elements,
        min_size=min_size,
        max_size=max_size,
        unique_by=lambda d: d[0],
    )
Пример #2
0
def array_shapes(min_dims=1, max_dims=None, min_side=1, max_side=None):
    # type: (int, int, int, int) -> st.SearchStrategy[Shape]
    """Return a strategy for array shapes (tuples of int >= 1)."""
    check_type(integer_types, min_dims, "min_dims")
    check_type(integer_types, min_side, "min_side")
    if min_dims > 32:
        raise InvalidArgument(
            "Got min_dims=%r, but numpy does not support arrays greater than 32 dimensions"
            % min_dims
        )
    if max_dims is None:
        max_dims = min(min_dims + 2, 32)
    check_type(integer_types, max_dims, "max_dims")
    if max_dims > 32:
        raise InvalidArgument(
            "Got max_dims=%r, but numpy does not support arrays greater than 32 dimensions"
            % max_dims
        )
    if max_side is None:
        max_side = min_side + 5
    check_type(integer_types, max_side, "max_side")
    order_check("dims", 0, min_dims, max_dims)
    order_check("side", 0, min_side, max_side)

    return st.lists(
        st.integers(min_side, max_side), min_size=min_dims, max_size=max_dims
    ).map(tuple)
Пример #3
0
def array_shapes(min_dims=1, max_dims=3, min_side=1, max_side=10):
    # type: (int, int, int, int) -> st.SearchStrategy[Tuple[int, ...]]
    """Return a strategy for array shapes (tuples of int >= 1)."""
    order_check("dims", 0, min_dims, max_dims)
    order_check("side", 0, min_side, max_side)
    return st.lists(st.integers(min_side, max_side),
                    min_size=min_dims,
                    max_size=max_dims).map(tuple)
Пример #4
0
def domains():
    """A strategy for :rfc:`1035` fully qualified domain names."""
    atoms = st.text(
        string.ascii_letters + "0123456789-", min_size=1, max_size=63
    ).filter(lambda s: "-" not in s[0] + s[-1])
    return st.builds(
        lambda x, y: ".".join(x + [y]),
        st.lists(atoms, min_size=1),
        # TODO: be more devious about top-level domains
        st.sampled_from(["com", "net", "org", "biz", "info"]),
    ).filter(lambda url: len(url) <= 255)
Пример #5
0
def urls():
    # type: () -> SearchStrategy[Text]
    """A strategy for :rfc:`3986`, generating http/https URLs."""
    def url_encode(s):
        return "".join(c if c in URL_SAFE_CHARACTERS else "%%%02X" % ord(c)
                       for c in s)

    schemes = st.sampled_from(["http", "https"])
    ports = st.integers(min_value=0, max_value=2**16 - 1).map(":{}".format)
    paths = st.lists(st.text(string.printable).map(url_encode)).map("/".join)

    return st.builds(u"{}://{}{}/{}".format, schemes, domains(),
                     st.just(u"") | ports, paths)
Пример #6
0
def all_types(draw):
    return draw(
        one_of(
            text(),
            integers(),
            none(),
            booleans(),
            floats(),
            tuples(),
            times(),
            uuids(),
            lists(integers()),
            dictionaries(text(), text()),
        ))
Пример #7
0
def urls():
    """A strategy for :rfc:`3986`, generating http/https URLs."""

    def url_encode(s):
        safe_chars = set(string.ascii_letters + string.digits + "$-_.+!*'(),")
        return "".join(c if c in safe_chars else "%%%02X" % ord(c) for c in s)

    schemes = st.sampled_from(["http", "https"])
    ports = st.integers(min_value=0, max_value=2 ** 16 - 1).map(":{}".format)
    paths = st.lists(st.text(string.printable).map(url_encode)).map(
        lambda path: "/".join([""] + path)
    )

    return st.builds(
        "{}://{}{}{}".format, schemes, domains(), st.one_of(st.just(""), ports), paths
    )
Пример #8
0
def valid_tuple_axes(ndim, min_size=0, max_size=None):
    # type: (int, int, int) -> st.SearchStrategy[Shape]
    """Return a strategy for generating permissible tuple-values for the
    ``axis`` argument for a numpy sequential function (e.g.
    :func:`numpy:numpy.sum`), given an array of the specified
    dimensionality.

    All tuples will have an length >= min_size and <= max_size. The default
    value for max_size is ``ndim``.

    Examples from this strategy shrink towards an empty tuple, which render
    most sequential functions as no-ops.

    The following are some examples drawn from this strategy.

    .. code-block:: pycon

        >>> [valid_tuple_axes(3).example() for i in range(4)]
        [(-3, 1), (0, 1, -1), (0, 2), (0, -2, 2)]

    ``valid_tuple_axes`` can be joined with other strategies to generate
    any type of valid axis object, i.e. integers, tuples, and ``None``:

    .. code-block:: pycon

        any_axis_strategy = none() | integers(-ndim, ndim - 1) | valid_tuple_axes(ndim)

    """
    if max_size is None:
        max_size = ndim

    check_type(integer_types, ndim, "ndim")
    check_type(integer_types, min_size, "min_size")
    check_type(integer_types, max_size, "max_size")
    order_check("size", 0, min_size, max_size)
    check_valid_interval(max_size, ndim, "max_size", "ndim")

    # shrink axis values from negative to positive
    axes = st.integers(0, max(0, 2 * ndim - 1)).map(
        lambda x: x if x < ndim else x - 2 * ndim
    )
    return st.lists(axes, min_size, max_size, unique_by=lambda x: x % ndim).map(tuple)
Пример #9
0
def array_dtypes(
        subtype_strategy=scalar_dtypes(),  # type: st.SearchStrategy[np.dtype]
        min_size=1,  # type: int
        max_size=5,  # type: int
        allow_subarrays=False,  # type: bool
):
    # type: (...) -> st.SearchStrategy[np.dtype]
    """Return a strategy for generating array (compound) dtypes, with members
    drawn from the given subtype strategy."""
    order_check("size", 0, min_size, max_size)
    native_strings = st.from_type(str).filter(
        bool)  # See issue #1798 re: filter!
    elements = st.tuples(native_strings, subtype_strategy)
    if allow_subarrays:
        elements |= st.tuples(native_strings, subtype_strategy,
                              array_shapes(max_dims=2, max_side=2))
    return st.lists(
        elements=elements,
        min_size=min_size,
        max_size=max_size,
        unique_by=lambda d: d[0],
    )
Пример #10
0
def array_dtypes(
        subtype_strategy=scalar_dtypes(),  # type: st.SearchStrategy[np.dtype]
        min_size=1,  # type: int
        max_size=5,  # type: int
        allow_subarrays=False,  # type: bool
):
    # type: (...) -> st.SearchStrategy[np.dtype]
    """Return a strategy for generating array (compound) dtypes, with members
    drawn from the given subtype strategy."""
    order_check("size", 0, min_size, max_size)
    native_strings = st.text()  # type: SearchStrategy[Any]
    if text_type is not str:  # pragma: no cover
        native_strings = st.binary()
    elements = st.tuples(native_strings, subtype_strategy)
    if allow_subarrays:
        elements |= st.tuples(native_strings, subtype_strategy,
                              array_shapes(max_dims=2, max_side=2))
    return st.lists(
        elements=elements,
        min_size=min_size,
        max_size=max_size,
        unique_by=lambda d: d[0],
    )
Пример #11
0
    symbols[36] = carriers[14]
    symbols[37] = carriers[15]
    symbols[38] = carriers[16]
    symbols[39] = carriers[17]
    symbols[40] = carriers[18]
    symbols[41] = carriers[19]
    symbols[42] = carriers[20]
    # pilots[3] = carriers[21]
    symbols[43] = carriers[22]
    symbols[44] = carriers[23]
    symbols[45] = carriers[24]
    symbols[46] = carriers[25]
    symbols[47] = carriers[26]

    return list(symbols)


def do(symbols: List[Symbol]) -> List[Carriers]:
    return [do_one(chunk) for chunk in chunked(symbols, 48)]


def undo(carriers: List[Carriers]) -> List[Symbol]:
    return list(flatten([undo_one(carrier) for carrier in carriers]))


@given(lists(arrays(complex, 48), min_size=1))
def test_hypothesis(data):
    data = np.hstack(data).tolist()
    un = undo(do(data))
    np.testing.assert_equal(data, un)
Пример #12
0
    n = randint(1, 100)
    r = set(l)
    for _ in range(n):
        r.add(random())
    return r


def test_empty_to_empty() -> None:
    matches, unmatched_1, unmatched_2, _ = linear_sum_match([], [], euclidean)

    assert matches == []
    assert unmatched_1 == []
    assert unmatched_2 == []


@given(lists(floats(min_value=1e-5, max_value=100.0)))
def test_list_to_empty(fs: List[float]) -> None:
    matches, unmatched_1, unmatched_2, _ = linear_sum_match(fs, [], euclidean)

    assert matches == []
    assert unmatched_1 == list(range(len(fs)))
    assert unmatched_2 == []


@given(lists(floats(min_value=1e-5, max_value=100.0)))
def test_list_to_self(fs: List[float]) -> None:
    matches, unmatched_1, unmatched_2, _ = linear_sum_match(fs, fs, euclidean)

    assert matches == list(zip(range(len(fs)), range(len(fs))))
    assert unmatched_1 == []
    assert unmatched_2 == []
Пример #13
0
from typing import List
import numpy as np
from hypothesis import given
from hypothesis._strategies import lists, complex_numbers
from wifi.to_time_domain import OFDMFrame

SIZE = 16


def do(frames: List[OFDMFrame]) -> List[OFDMFrame]:
    return [frame[-SIZE:] + frame for frame in frames]


def undo(frames: List[OFDMFrame]) -> List[OFDMFrame]:
    return [frame[SIZE:] for frame in frames]


@given(
    lists(lists(complex_numbers(), min_size=64, max_size=64),
          min_size=1,
          max_size=32))
def test_hypothesis(data):
    un = undo(do(data))
    np.testing.assert_equal(data, un)
Пример #14
0
# not a perfect reconstuction!
def undo(iq):
    short = iq[:160]
    long = iq[160:320]

    frame_size = guard_interval.SIZE + 64
    frames = list(chunked(iq[320:], frame_size))
    if len(frames[-1]) != frame_size:
        frames = frames[:-1]

    return short, long, frames


@given(
    lists(lists(complex_numbers(), min_size=80, max_size=80),
          min_size=1,
          max_size=32))
def test_hypothesis(frames):
    from wifi import preambler
    short = preambler.short_training_sequence()
    long = preambler.long_training_sequence()

    res_short, res_long, res_frames = undo(do(short, long, frames))

    # 'do' contaminates the first sample of each symbol, cannot be restored with 'undo'
    assert res_short[1:] == short[1:]
    assert res_long[1:] == long[1:]
    for frame, res_frame in zip(frames, res_frames):
        assert frame[1:] == res_frame[1:]
Пример #15
0

def undo_one(carriers: Carriers, index_in_package: int) -> Carriers:

    pilots = np.empty(4, dtype=complex)
    pilots[0] = carriers[-21]
    pilots[1] = carriers[-7]
    pilots[2] = carriers[7]
    pilots[3] = carriers[21]

    # remove latent frequency offset by using pilot symbols
    pilots *= PILOT_POLARITY[index_in_package % 127]
    mean_phase_offset = np.angle(np.mean(pilots))
    carriers = np.array(carriers) * np.exp(-1j * mean_phase_offset)

    return carriers.tolist()


def do(carriers: List[Carriers]) -> List[Carriers]:
    return [do_one(carrier, index) for index, carrier in enumerate(carriers)]


def undo(carriers: List[Carriers]) -> List[Carriers]:
    return [undo_one(carrier, index) for index, carrier in enumerate(carriers)]


@given(lists(lists(complex_numbers(allow_nan=False, allow_infinity=False), min_size=64, max_size=64), min_size=1, max_size=32))
def test_hypothesis(data):
    un = undo(do(data))
    np.testing.assert_allclose(data, un, rtol=1e-16, atol=1e-16)