Python hypothesis.strategies.integers() Examples

The following are 30 code examples of hypothesis.strategies.integers(). 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 hypothesis.strategies , or try the search function .
Example #1
Source File: strategies.py    From pymtl3 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def bits( nbits, signed=False, min_value=None, max_value=None ):
  BitsN = mk_bits( nbits )

  if (min_value is not None or max_value is not None) and signed:
    raise ValueError("bits strategy currently doesn't support setting "
                     "signedness and min/max value at the same time")

  if min_value is None:
    min_value = (-(2**(nbits-1))) if signed else 0
  if max_value is None:
    max_value = (2**(nbits-1)-1)  if signed else (2**nbits - 1)

  strat = st.booleans() if nbits == 1 else st.integers( min_value, max_value )

  @st.composite
  def strategy_bits( draw ):
    return BitsN( draw( strat ) )

  return strategy_bits() # RETURN A STRATEGY INSTEAD OF FUNCTION

#-------------------------------------------------------------------------
# strategies.bitslists
#-------------------------------------------------------------------------
# Return the SearchStrategy for a list of Bits with the support of
# dictionary based min/max value limit 
Example #2
Source File: test_tensor_manip.py    From MyGrad with MIT License 6 votes vote down vote up
def gen_roll_args(draw, arr):
    shift = draw(st.integers() | st.tuples(*(st.integers() for i in arr.shape)))

    if arr.ndim:
        ax_strat = hnp.valid_tuple_axes(
            arr.ndim,
            **(
                dict(min_size=len(shift), max_size=len(shift))
                if isinstance(shift, tuple)
                else {}
            )
        )
        axis = draw(st.none() | st.integers(-arr.ndim, arr.ndim - 1) | ax_strat)
    else:
        axis = None
    return dict(shift=shift, axis=axis) 
Example #3
Source File: __init__.py    From wellpathpy with GNU Lesser General Public License v3.0 6 votes vote down vote up
def same_len_lists(draw, min_value = None, max_value = None):
    """Draw random arrays of equal lengths

    One precondition of the list version of spherical() is that its inputs must
    be of equal length.
    """
    n = draw(integers(min_value = 0, max_value = 50))
    fixlen = lists(
        floats(
            min_value = min_value,
            max_value = max_value,
            allow_nan = False,
            allow_infinity = False
        ),
        min_size = n,
        max_size = n,
    )
    fixnp = fixlen.map(np.array)
    return (draw(fixnp), draw(fixnp), draw(fixnp)) 
Example #4
Source File: custom_hypothesis_support.py    From pyta with GNU General Public License v3.0 6 votes vote down vote up
def arguments_node(draw, annotated=False):
    n = draw(hs.integers(min_value=1, max_value=5))
    args = draw(hs.lists(name_node(None), min_size=n, max_size=n))
    if annotated:
        annotations = draw(hs.lists(name_node(annotation), min_size=n, max_size=n))
    else:
        annotations = None
    node = astroid.Arguments()
    node.postinit(
        args,
        None,
        None,
        None,
        annotations
    )
    return node 
Example #5
Source File: test_negative_log_likelihood.py    From MyGrad with MIT License 6 votes vote down vote up
def test_negative_log_likelihood(data: st.DataObject, labels_as_tensor: bool):
    s = data.draw(
        hnp.arrays(
            shape=hnp.array_shapes(max_side=10, min_dims=2, max_dims=2),
            dtype=float,
            elements=st.floats(-100, 100),
        )
    )
    y_true = data.draw(
        hnp.arrays(
            shape=(s.shape[0],),
            dtype=hnp.integer_dtypes(),
            elements=st.integers(min_value=0, max_value=s.shape[1] - 1),
        ).map(Tensor if labels_as_tensor else lambda x: x)
    )
    scores = Tensor(s)
    nll = negative_log_likelihood(mg.log(mg.nnet.softmax(scores)), y_true)
    nll.backward()

    cross_entropy_scores = Tensor(s)
    ce = softmax_crossentropy(cross_entropy_scores, y_true)
    ce.backward()

    assert_allclose(nll.data, ce.data, atol=1e-5, rtol=1e-5)
    assert_allclose(scores.grad, cross_entropy_scores.grad, atol=1e-5, rtol=1e-5) 
Example #6
Source File: _testtools.py    From tmtoolkit with Apache License 2.0 6 votes vote down vote up
def _strategy_2d_array(dtype, minval=0, maxval=None, **kwargs):
    if 'min_side' in kwargs:
        min_side = kwargs.pop('min_side')
    else:
        min_side = 1

    if 'max_side' in kwargs:
        max_side = kwargs.pop('max_side')
    else:
        max_side = None

    if dtype is np.int:
        elems = st.integers(minval, maxval, **kwargs)
    elif dtype is np.float:
        elems = st.floats(minval, maxval, **kwargs)
    elif dtype is np.str:
        elems = st.text(min_size=minval, max_size=maxval, **kwargs)
    else:
        raise ValueError('no elements strategy for dtype', dtype)

    return arrays(dtype, array_shapes(2, 2, min_side, max_side), elements=elems) 
Example #7
Source File: test_browser.py    From crocoite with MIT License 6 votes vote down vote up
def chromeResponseReceived (reqid, url):
    mimeTypeSt = st.one_of (st.none (), st.just ('text/html'))
    remoteIpAddressSt = st.one_of (st.none (), st.just ('127.0.0.1'))
    protocolSt = st.one_of (st.none (), st.just ('h2'))
    statusCodeSt = st.integers (min_value=100, max_value=999)
    typeSt = st.sampled_from (['Document', 'Stylesheet', 'Image', 'Media',
            'Font', 'Script', 'TextTrack', 'XHR', 'Fetch', 'EventSource',
            'WebSocket', 'Manifest', 'SignedExchange', 'Ping',
            'CSPViolationReport', 'Other'])
    return st.fixed_dictionaries ({
            'requestId': reqid,
            'timestamp': timestamp,
            'type': typeSt,
            'response': st.fixed_dictionaries ({
                'url': url,
                'requestHeaders': chromeHeaders (), # XXX: make this optional
                'headers': chromeHeaders (),
                'status': statusCodeSt,
                'statusText': asciiText,
                'mimeType': mimeTypeSt,
                'remoteIPAddress': remoteIpAddressSt,
                'protocol': protocolSt,
                })
            }) 
Example #8
Source File: test_conv.py    From MyGrad with MIT License 6 votes vote down vote up
def test_padding(ndim: int, data: st.DataObject):
    """Ensure that convolving a padding-only image with a commensurate kernel yields the single entry: 0"""
    padding = data.draw(
        st.integers(1, 3) | st.tuples(*[st.integers(1, 3)] * ndim), label="padding"
    )
    x = Tensor(
        data.draw(
            hnp.arrays(shape=(1, 1) + (0,) * ndim, dtype=float, elements=st.floats()),
            label="x",
        )
    )
    pad_tuple = padding if isinstance(padding, tuple) else (padding,) * ndim
    kernel = data.draw(
        hnp.arrays(
            shape=(1, 1) + tuple(2 * p for p in pad_tuple),
            dtype=float,
            elements=st.floats(allow_nan=False, allow_infinity=False),
        )
    )
    out = conv_nd(x, kernel, padding=padding, stride=1)
    assert out.shape == (1,) * x.ndim
    assert out.item() == 0.0

    out.sum().backward()
    assert x.grad.shape == x.shape 
Example #9
Source File: test_service.py    From txacme with MIT License 5 votes vote down vote up
def panicing_certs_fixture(draw):
    now = draw(datetimes(
        min_value=datetime(1971, 1, 1), max_value=datetime(2030, 1, 1)))
    panic = timedelta(seconds=draw(
        s.integers(min_value=60, max_value=60 * 60 * 24)))
    certs = dict(
        draw(
            s.lists(
                panicing_cert(now, panic),
                min_size=1,
                max_size=5,
                unique_by=lambda i: i[0])))
    return AcmeFixture(now=now, panic_interval=panic, certs=certs) 
Example #10
Source File: test_tensor_manip.py    From MyGrad with MIT License 5 votes vote down vote up
def gen_int_repeat_args(arr: Tensor) -> st.SearchStrategy[dict]:
    valid_axis = st.none()
    valid_axis |= st.integers(-arr.ndim, arr.ndim - 1) if arr.ndim else st.just(0)
    return st.fixed_dictionaries(
        dict(repeats=st.integers(min_value=0, max_value=5), axis=valid_axis,)
    ) 
Example #11
Source File: test_multiscale_crop_video.py    From torchvideo with Mozilla Public License 2.0 5 votes vote down vote up
def test_transform_always_yields_crops_of_the_correct_size(self, data):
        crop_height = data.draw(st.integers(1, 10))
        crop_width = data.draw(st.integers(1, 10))
        duration = data.draw(st.integers(1, 10))
        fixed_crops = data.draw(st.booleans())
        if fixed_crops:
            more_fixed_crops = data.draw(st.booleans())
        else:
            more_fixed_crops = False
        height = data.draw(st.integers(crop_height, crop_height * 100))
        width = data.draw(st.integers(crop_width, crop_width * 100))

        video_shape = (duration, height, width, 3)

        scale_strategy = st.floats(
            min_value=min(crop_width, crop_height) / min(height, width), max_value=1
        )
        scales = data.draw(st.lists(scale_strategy, min_size=1, max_size=5))
        max_distortion = data.draw(st.integers(0, len(scales)))
        video = NDArrayToPILVideo()(np.ones(video_shape, dtype=np.uint8))
        transform = MultiScaleCropVideo(
            size=ImageShape(height=crop_height, width=crop_width),
            scales=scales,
            max_distortion=max_distortion,
            fixed_crops=fixed_crops,
            more_fixed_crops=more_fixed_crops,
        )
        transformed_video = list(transform(video))
        print("video_shape", video_shape)
        print("scales", scales)
        print("max_distortion", max_distortion)
        print("fixed_crops", fixed_crops)
        print("more_fixed_crops", more_fixed_crops)

        assert len(transformed_video) == duration
        for frame in transformed_video:
            print("crop_size", np.array(frame).shape)
            np.testing.assert_allclose(np.array(frame), np.ones_like(frame))
            assert frame.height == crop_height
            assert frame.width == crop_width 
Example #12
Source File: test_negative_log_likelihood.py    From MyGrad with MIT License 5 votes vote down vote up
def test_weighted_negative_log_likelihood(data: st.DataObject, labels_as_tensor: bool):
    s = data.draw(
        hnp.arrays(
            shape=hnp.array_shapes(min_side=1, max_side=10, min_dims=2, max_dims=2),
            dtype=float,
            elements=st.floats(-100, 100),
        )
    )
    y_true = data.draw(
        hnp.arrays(
            shape=(s.shape[0],),
            dtype=hnp.integer_dtypes(),
            elements=st.integers(min_value=0, max_value=s.shape[1] - 1),
        ).map(Tensor if labels_as_tensor else lambda x: x)
    )
    weights = data.draw(
        hnp.arrays(
            shape=(s.shape[1],),
            dtype=float,
            elements=st.floats(1e-8, 100),
        )
    )
    scores = Tensor(s)
    weights = Tensor(weights)

    for score, y in zip(scores, y_true):
        score = mg.log(mg.nnet.softmax(score.reshape(1, -1)))
        y = y.reshape(-1)
        nll = negative_log_likelihood(score, y)
        weighted_nll = negative_log_likelihood(score, y, weights=weights)
        assert np.isclose(weighted_nll.data, weights[y.data].data * nll.data) 
Example #13
Source File: test_sliding_window.py    From MyGrad with MIT License 5 votes vote down vote up
def test_sliding_window(data, x):
    """ Test variations of window-shape, step, and dilation for sliding window
        view of N-dimensional array."""

    win_dim = data.draw(st.integers(1, x.ndim), label="win_dim")
    win_shape = data.draw(
        st.tuples(*(st.integers(1, s) for s in x.shape[-win_dim:])), label="win_shape"
    )
    step = data.draw(
        st.tuples(*(st.integers(1, s) for s in x.shape[-win_dim:])), label="step"
    )

    max_dilation = np.array(x.shape[-win_dim:]) // win_shape
    dilation = data.draw(
        st.one_of(
            st.none()
            | st.integers(1, min(max_dilation))
            | st.tuples(*(st.integers(1, s) for s in max_dilation))
        ),
        label="dilation",
    )
    y = sliding_window_view(x, window_shape=win_shape, step=step, dilation=dilation)

    if dilation is None:
        dilation = np.ones((len(win_shape),), dtype=int)

    if isinstance(dilation, int):
        dilation = np.full((len(win_shape),), fill_value=dilation, dtype=int)

    for ind in np.ndindex(*y.shape[:win_dim]):
        slices = tuple(
            slice(i * s, i * s + w * d, d)
            for i, w, s, d in zip(ind, win_shape, step, dilation)
        )
        assert_allclose(actual=y[tuple([*ind])], desired=x[(..., *slices)]) 
Example #14
Source File: test_focal_loss.py    From MyGrad with MIT License 5 votes vote down vote up
def test_softmax_focal_loss(num_datum, num_classes, alpha, gamma, data, grad, target_type):
    scores = data.draw(
        hnp.arrays(shape=(num_datum, num_classes), dtype=float, elements=st.floats(1, 100))
    )
    assume((abs(scores.sum(axis=1)) > 0.001).all())

    scores_mygrad = Tensor(scores)
    scores_nn = Tensor(scores)

    truth = np.zeros((num_datum, num_classes))
    targets = data.draw(st.tuples(*(st.integers(0, num_classes - 1) for i in range(num_datum))))
    truth[range(num_datum), targets] = 1
    targets = target_type(targets)

    probs = softmax(scores_mygrad)
    mygrad_focal_loss = sum(truth * (-alpha * (1 - probs + 1e-14)**gamma * log(probs))) / num_datum
    mygrad_focal_loss.backward(grad)

    nn_loss = softmax_focal_loss(scores_nn, targets, alpha=alpha, gamma=gamma).mean()
    nn_loss.backward(grad)

    assert isinstance(nn_loss, Tensor) and nn_loss.ndim == 0
    assert_allclose(nn_loss.data, mygrad_focal_loss.data, atol=1e-4, rtol=1e-4)
    assert_allclose(scores_nn.grad, scores_mygrad.grad, atol=1e-4, rtol=1e-4)

    nn_loss.null_gradients()
    assert scores_nn.grad is None 
Example #15
Source File: test_focal_loss.py    From MyGrad with MIT License 5 votes vote down vote up
def test_focal_loss(num_datum, num_classes, alpha, gamma, data, grad, target_type):
    scores = data.draw(
        hnp.arrays(shape=(num_datum, num_classes), dtype=float, elements=st.floats(1, 100))
    )
    assume((abs(scores.sum(axis=1)) > 0.001).all())

    scores_mygrad = Tensor(scores)
    scores_nn = Tensor(scores)

    truth = np.zeros((num_datum, num_classes))
    targets = data.draw(st.tuples(*(st.integers(0, num_classes - 1) for i in range(num_datum))))
    truth[range(num_datum), targets] = 1
    targets = target_type(targets)

    fl = focal_loss(softmax(scores_mygrad), targets, alpha=alpha, gamma=gamma).mean()
    fl.backward(grad)

    nn_loss = softmax_focal_loss(scores_nn, targets, alpha=alpha, gamma=gamma).mean()
    nn_loss.backward(grad)

    assert isinstance(nn_loss, Tensor) and nn_loss.ndim == 0
    assert_allclose(nn_loss.data, fl.data, atol=1e-4, rtol=1e-4)
    assert_allclose(scores_nn.grad, scores_mygrad.grad, atol=1e-4, rtol=1e-4)

    nn_loss.null_gradients()
    assert scores_nn.grad is None 
Example #16
Source File: test_softmaxcrossentropy.py    From MyGrad with MIT License 5 votes vote down vote up
def test_softmax_crossentropy(data: st.DataObject, labels_as_tensor: bool):
    s = data.draw(
        hnp.arrays(
            shape=hnp.array_shapes(max_side=10, min_dims=2, max_dims=2),
            dtype=float,
            elements=st.floats(-100, 100),
        )
    )
    y_true = data.draw(
        hnp.arrays(
            shape=(s.shape[0],),
            dtype=hnp.integer_dtypes(),
            elements=st.integers(min_value=0, max_value=s.shape[1] - 1),
        ).map(Tensor if labels_as_tensor else lambda x: x)
    )
    scores = Tensor(s)
    softmax_cross = softmax_crossentropy(scores, y_true, constant=False)
    softmax_cross.backward()

    mygrad_scores = Tensor(s)
    probs = softmax(mygrad_scores)

    correct_labels = (range(len(y_true)), y_true.data if labels_as_tensor else y_true)
    truth = np.zeros(mygrad_scores.shape)
    truth[correct_labels] = 1

    mygrad_cross = (-1 / s.shape[0]) * (log(probs) * truth).sum()
    mygrad_cross.backward()
    assert_allclose(softmax_cross.data, mygrad_cross.data, atol=1e-5, rtol=1e-5)
    assert_allclose(scores.grad, mygrad_scores.grad, atol=1e-5, rtol=1e-5) 
Example #17
Source File: test_tensor_manip.py    From MyGrad with MIT License 5 votes vote down vote up
def _swap_axes_axis(arr):
    return st.integers(-arr.ndim, arr.ndim - 1) if arr.ndim else st.just(0) 
Example #18
Source File: test_tensor_manip.py    From MyGrad with MIT License 5 votes vote down vote up
def gen_tuple_repeat_args(draw: st.DataObject.draw, arr: Tensor):

    valid_axis = draw(
        st.none() | (st.integers(-arr.ndim, arr.ndim - 1) if arr.ndim else st.just(0))
    )

    num_repeats = (
        arr.shape[valid_axis] if valid_axis is not None and arr.ndim else arr.size
    )
    repeats = draw(st.tuples(*[st.integers(0, 5)] * num_repeats))
    return dict(repeats=repeats, axis=valid_axis,) 
Example #19
Source File: test_samplers.py    From torchvideo with Mozilla Public License 2.0 5 votes vote down vote up
def temporal_segment_sampler():
    segment_count = st.integers(1, 100).example()
    snippet_length = st.integers(1, 1000).example()
    return TemporalSegmentSampler(segment_count, snippet_length) 
Example #20
Source File: test_service.py    From txacme with MIT License 5 votes vote down vote up
def panicing_cert(draw, now, panic):
    server_name = draw(ts.dns_names())
    offset = timedelta(seconds=draw(
        s.integers(
                min_value=-1000,
                max_value=int(panic.total_seconds()))))
    return (server_name,
            _generate_cert(
                server_name,
                not_valid_before=now + offset - timedelta(seconds=1),
                not_valid_after=now + offset)) 
Example #21
Source File: test_transpiler_equivalence.py    From qiskit-terra with Apache License 2.0 5 votes vote down vote up
def add_c_if_last_gate(self, carg, data):
        """Modify the last gate to be conditional on a classical register."""
        creg = carg.register
        val = data.draw(st.integers(min_value=0, max_value=2**len(creg)-1))

        last_gate = self.qc.data[-1]

        # Conditional instructions are not supported
        assume(isinstance(last_gate[0], Gate))

        last_gate[0].c_if(creg, val)

    # Properties to check 
Example #22
Source File: test_ticks.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def test_tick_add_sub(cls, n, m):
    # For all Tick subclasses and all integers n, m, we should have
    # tick(n) + tick(m) == tick(n+m)
    # tick(n) - tick(m) == tick(n-m)
    left = cls(n)
    right = cls(m)
    expected = cls(n + m)

    assert left + right == expected
    assert left.apply(right) == expected

    expected = cls(n - m)
    assert left - right == expected 
Example #23
Source File: fuzzer.py    From fuzz-lightyear with Apache License 2.0 5 votes vote down vote up
def _fuzz_integer(
    parameter: Dict[str, Any],
    **kwargs: Any,
) -> SearchStrategy:
    # TODO: Handle all the optional qualifiers for numbers.
    # https://swagger.io/docs/specification/data-models/data-types/#numbers
    bounds = _find_bounds(parameter)

    return st.integers(**bounds) 
Example #24
Source File: test_browser.py    From crocoite with MIT License 5 votes vote down vote up
def urls ():
    """ Build http/https URL """
    scheme = st.sampled_from (['http', 'https'])
    # Path must start with a slash
    pathSt = st.builds (lambda x: '/' + x, st.text ())
    args = st.fixed_dictionaries ({
            'scheme': scheme,
            'host': domains (),
            'port': st.one_of (st.none (), st.integers (min_value=1, max_value=2**16-1)),
            'path': pathSt,
            'query_string': st.text (),
            'fragment': st.text (),
            })
    return st.builds (lambda x: URL.build (**x), args) 
Example #25
Source File: test_warc.py    From crocoite with MIT License 5 votes vote down vote up
def event ():
    return st.one_of (
            st.builds (ControllerStart, jsonObject ()),
            st.builds (Script.fromStr, st.text (), st.one_of(st.none (), st.text ())),
            st.builds (ScreenshotEvent, urls (), st.integers (), st.binary ()),
            st.builds (DomSnapshotEvent, urls (), st.builds (lambda x: x.encode ('utf-8'), st.text ()), viewport()),
            requestResponsePair (),
            ) 
Example #26
Source File: test_warc.py    From crocoite with MIT License 5 votes vote down vote up
def viewport ():
    return st.builds (lambda x, y: f'{x}x{y}', st.integers (), st.integers ()) 
Example #27
Source File: test_warc.py    From crocoite with MIT License 5 votes vote down vote up
def jsonObject ():
    """ JSON-encodable objects """
    return st.dictionaries (st.text (), st.one_of (st.integers (), st.text ())) 
Example #28
Source File: test_explode.py    From KiField with MIT License 5 votes vote down vote up
def random_reference(draw, prefix = random_prefix()):
    number = st.integers(min_value = 0)
    return draw(st.tuples(prefix, number)) 
Example #29
Source File: test_persistence.py    From flocker with Apache License 2.0 5 votes vote down vote up
def test_strings_and_jsonable_types_differ(self):
        """
        Strings and integers hash to different values.
        """
        self.assertThat(
            generation_hash(5),
            Not(Equals(generation_hash('5')))
        ) 
Example #30
Source File: testtools.py    From flocker with Apache License 2.0 5 votes vote down vote up
def application_strategy(draw, min_number_of_ports=0, stateful=False):
    """
    A hypothesis strategy to generate an ``Application``

    :param int min_number_of_ports: The minimum number of ports that the
        Application should have.
    """
    num_ports = draw(
        st.integers(
            min_value=min_number_of_ports,
            max_value=max(8, min_number_of_ports+1)
        )
    )
    dataset_id = unicode(uuid4())
    application = Application(
        name=draw(unique_name_strategy()),
        image=draw(docker_image_strategy()),
        ports=frozenset(
            Port(
                internal_port=8000+i,
                external_port=8000+i+1
            ) for i in xrange(num_ports)
        ),
    )
    if stateful:
        application = application.set(
            'volume',
            AttachedVolume(
                manifestation=Manifestation(
                    dataset=Dataset(
                        dataset_id=dataset_id,
                        deleted=False,
                    ),
                    primary=True,
                ),
                mountpoint=FilePath('/flocker').child(dataset_id)
            )
        )
    return application