Python hypothesis.strategies.floats() Examples
The following are 30
code examples of hypothesis.strategies.floats().
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: test_negative_log_likelihood.py From MyGrad with MIT License | 6 votes |
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 #2
Source File: test_output_mask.py From telepresence with Apache License 2.0 | 6 votes |
def generate_dictionary_with_fixed_tokens(draw): """ Builds random nested dictionary structure which is then used as JSON to mask two fixed "token" keys. Structure is based on TEST_JSON sample fixture defined above. """ base = draw( st.fixed_dictionaries({'token': st.text(printable, min_size=10)}) ) optional = draw( st.nothing() | st.dictionaries( st.text(ascii_letters, min_size=1), st.floats() | st.integers() | st.text(printable) | st.booleans() | st.nothing(), min_size=10, max_size=50 ) ) return {**base, **optional}
Example #3
Source File: test_float.py From segpy with GNU Affero General Public License v3.0 | 6 votes |
def ibm_compatible_floats(draw, min_value=None, max_value=None): if min_value is None: min_value = MIN_IBM_FLOAT if max_value is None: max_value = MAX_IBM_FLOAT truncated_min_f = max(min_value, MIN_IBM_FLOAT) truncated_max_f = min(max_value, MAX_IBM_FLOAT) strategies = [] if truncated_min_f <= LARGEST_NEGATIVE_NORMAL_IBM_FLOAT <= truncated_max_f: strategies.append(floats(truncated_min_f, LARGEST_NEGATIVE_NORMAL_IBM_FLOAT)) if truncated_min_f <= SMALLEST_POSITIVE_NORMAL_IBM_FLOAT <= truncated_max_f: strategies.append(floats(SMALLEST_POSITIVE_NORMAL_IBM_FLOAT, truncated_max_f)) if truncated_min_f <= 0 <= truncated_max_f: strategies.append(just(0.0)) if len(strategies) == 0: strategies.append(floats(truncated_min_f, truncated_max_f)) ibm = draw(one_of(*strategies)) return ibm
Example #4
Source File: base.py From sidekick with MIT License | 6 votes |
def choice(values): """ One value from a limited set. Args: values: Iterable with values that will be produced by strategy. Python enums are iterable and thus can be used as arguments for this strategy. Examples: >>> from hypothesis import strategies as st, given >>> from math import sin, cos >>> @given(choice([sin, cos]), st.floats(-1000, 1000)) ... def check_range(fn, x): ... assert -1 <= fn(x) <= 1 """ values = list(values) return st.integers(min_value=0, max_value=len(values) - 1).map(values.__getitem__)
Example #5
Source File: _testtools.py From tmtoolkit with Apache License 2.0 | 6 votes |
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 #6
Source File: tough-bonus-problems.py From escape-from-automanual-testing with GNU Affero General Public License v3.0 | 6 votes |
def from_schema(schema): """Returns a strategy for objects that match the given schema.""" check_schema(schema) # TODO: actually handle constraints on number/string/array schemas return dict( null=st.none(), bool=st.booleans(), number=st.floats(allow_nan=False), string=st.text(), array=st.lists(st.nothing()), )[schema["type"]] # `@st.composite` is one way to write this - another would be to define a # bare function, and `return st.one_of(st.none(), st.booleans(), ...)` so # each strategy can be defined individually. Use whichever seems more # natural to you - the important thing in tests is usually readability!
Example #7
Source File: hypothesis_util.py From bayesmark with Apache License 2.0 | 6 votes |
def close_enough(x, y, equal_nan=False, rtol=1e-5, atol=1e-8): # Might want to adjust rtol and atol for lower precision floats x, y = np.asarray(x), np.asarray(y) if x.shape != y.shape: return False if x.dtype != y.dtype: return False if x.dtype.kind == "f": assert y.dtype.kind == "f" # Note: equal_nan only considered in both float case! return np.allclose(x, y, equal_nan=equal_nan, rtol=rtol, atol=atol) return np.all(x == y)
Example #8
Source File: __init__.py From cattrs with MIT License | 6 votes |
def enums_of_primitives(draw): """Generate enum classes with primitive values.""" names = draw(st.sets(st.text(min_size=1), min_size=1)) n = len(names) vals = draw( st.one_of( st.sets( st.one_of( st.integers(), st.floats(allow_nan=False), st.text(min_size=1), ), min_size=n, max_size=n, ) ) ) return Enum("HypEnum", list(zip(names, vals)))
Example #9
Source File: uber.py From MyGrad with MIT License | 6 votes |
def arrays(self, i: int) -> st.SearchStrategy: """ Hypothesis search strategy for drawing an array y to be passed to f(x, ..., y_i,...). By default, y is drawn to have a shape that is broadcast-compatible with x. Parameters ---------- i : int The argument index-location of y in the signature of f. Returns ------- hypothesis.searchstrategy.SearchStrategy""" return hnp.arrays( shape=self.index_to_arr_shapes.get(i), dtype=float, elements=st.floats(*self.index_to_bnds.get(i, self.default_bnds)), )
Example #10
Source File: test_geometry.py From wellpathpy with GNU Lesser General Public License v3.0 | 6 votes |
def test_spherical_list(nev): """The same_len_lists can draw values that when squared overflow floats. For regular floats, this doesn't flag, but numpy warns on it. It's considered a caller problem if the value does overflow. TODO ---- Consider either properly warning or consistently failing when a partial computation overflows. A solution could be to coerce even regular floats to numpy, and look for the warning. For now, do the python thing and just carry on. """ n, e, v = nev inc, azi = spherical(n, e, v) assert np.all(0 <= azi) assert np.all(azi < 360)
Example #11
Source File: primitivestrategies.py From swagger-conformance with MIT License | 6 votes |
def strategy(self): if self._multiple_of is not None: maximum = self._maximum if maximum is not None: maximum = math.floor(maximum / self._multiple_of) minimum = self._minimum if minimum is not None: minimum = math.ceil(minimum / self._multiple_of) strategy = hy_st.integers(min_value=minimum, max_value=maximum) strategy = strategy.map(lambda x: x * self._multiple_of) else: strategy = hy_st.floats(min_value=self._minimum, max_value=self._maximum) if self._exclusive_maximum: strategy = strategy.filter(lambda x: x < self._maximum) if self._exclusive_minimum: strategy = strategy.filter(lambda x: x > self._minimum) return strategy
Example #12
Source File: test_conv.py From MyGrad with MIT License | 6 votes |
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 #13
Source File: _from_schema.py From hypothesis-jsonschema with Mozilla Public License 2.0 | 5 votes |
def number_schema(schema: dict) -> st.SearchStrategy[float]: """Handle numeric schemata.""" min_value, max_value, exclude_min, exclude_max = get_number_bounds(schema) if "multipleOf" in schema: return _numeric_with_multiplier(min_value, max_value, schema) return st.floats( min_value=min_value, max_value=max_value, allow_nan=False, allow_infinity=False, exclude_min=exclude_min, exclude_max=exclude_max, # Filter out negative-zero as it does not exist in JSON ).filter(lambda n: n != 0 or math.copysign(1, n) == 1)
Example #14
Source File: hypothesis_util.py From bayesmark with Apache License 2.0 | 5 votes |
def mfloats(): return floats(min_value=-1e3, max_value=1e3)
Example #15
Source File: test_bem_green_functions.py From capytaine with GNU General Public License v3.0 | 5 votes |
def test_exponential_integral(x, y): z = x + 1j*y # Compare with Scipy implementation assert np.isclose(E1(z), exp1(z), rtol=1e-3) # Test property (A3.5) of the function according to [Del, p.367]. if y != 0.0: assert np.isclose(E1(np.conjugate(z)), np.conjugate(E1(z)), rtol=1e-3) # BROKEN... # def derivative_of_complex_function(f, z, **kwargs): # direction = 1 # return derivative(lambda eps: f(z + eps*direction), 0.0, **kwargs) # if abs(x) > 1 and abs(y) > 1: # assert np.isclose( # derivative_of_complex_function(Delhommeau_f90.initialize_green_wave.gg, z), # Delhommeau_f90.initialize_green_wave.gg(z) - 1.0/z, # atol=1e-2) # CHECK OF THE THEORY, NOT THE CODE ITSELF # Not necessary to run every time... # # @given(r=floats(min_value=0, max_value=1e2), # z=floats(min_value=-16, max_value=-1), # k=floats(min_value=0.1, max_value=10) # ) # def test_zeta(r, z, k): # """Check expression k/π ∫ 1/ζ(θ) dθ = - 1/r """ # def one_over_zeta(theta): # return np.real(1/(k*(z + 1j*r*np.cos(theta)))) # int_one_over_zeta, *_ = quad(one_over_zeta, -pi/2, pi/2) # assert np.isclose(k/pi * int_one_over_zeta, # -1/(np.sqrt(r**2 + z**2)), # rtol=1e-4)
Example #16
Source File: lib_test.py From pyjson5 with Apache License 2.0 | 5 votes |
def test_numbers(self): # decimal literals self.check('1', 1) self.check('-1', -1) self.check('+1', 1) # hex literals self.check('0xf', 15) self.check('0xfe', 254) self.check('0xfff', 4095) self.check('0XABCD', 43981) self.check('0x123456', 1193046) # floats self.check('1.5', 1.5) self.check('1.5e3', 1500.0) self.check('-0.5e-2', -0.005) # names self.check('Infinity', float('inf')) self.check('-Infinity', float('-inf')) self.assertTrue(math.isnan(json5.loads('NaN'))) self.assertTrue(math.isnan(json5.loads('-NaN'))) # syntax errors self.check_fail('14d', '<string>:1 Unexpected "d" at column 3')
Example #17
Source File: __init__.py From cattrs with MIT License | 5 votes |
def float_attrs(draw, defaults=None): """ Generate a tuple of an attribute and a strategy that yields floats for that attribute. """ default = NOTHING if defaults is True or (defaults is None and draw(st.booleans())): default = draw(st.floats()) return (attr.ib(default=default), st.floats())
Example #18
Source File: decoder_test.py From tacotron2 with BSD 3-Clause "New" or "Revised" License | 5 votes |
def memory_tensor(draw, batch_size, source_length=integers(5, 20), embed_dim=integers(4, 20).filter(even_number), elements=floats(-1.0, 1.0)): il = draw(source_length) source_length = np.repeat(il, batch_size) md = draw(embed_dim) memory = draw(arrays(dtype=np.float32, shape=[batch_size, il, md], elements=elements)) return memory, source_length
Example #19
Source File: space_test.py From bayesmark with Apache License 2.0 | 5 votes |
def test_int_range_warp_unwarp(warp, args): """Warning: this explicitly ignores issues with min max if going to int limit, since >>> np.array(INT_MAX).astype(np.float32).astype(np.int32) array(-2147483648, dtype=int32) Without any warning from numpy. """ x, range_ = args # We could split out log into diff function without this pruning if we # start failing hypothesis health check. if warp == "log": range_ = range_[range_ > 0] range_ = np.sort(range_) assume(len(range_) == 2 and range_[0] < range_[1]) x = np.clip(x, range_[0], range_[1]).astype(range_.dtype) S = sp.Integer(warp=warp, range_=range_) y = S.warp(x) assert y.shape == x.shape + (1,) assert y.dtype == sp.WARPED_DTYPE # Test bounds lower, upper = S.get_bounds().T assert np.all(lower <= y) assert np.all(y <= upper) y2 = S.validate_warped(y) assert close_enough(y, y2) x2 = S.unwarp(y) assert x2.shape == x.shape x3 = S.validate(x2) assert close_enough(x2, x3) assert x.dtype == x2.dtype # Close enough when evaluated as floats assert close_enough(x.astype("f"), x2.astype("f"))
Example #20
Source File: test_wateroil_saturation.py From pyscal with GNU Lesser General Public License v3.0 | 5 votes |
def test_wateroil_dual(param1, param2): """Test combination of 2 floats as parameters""" try: wateroil = WaterOil(swl=param1, sorw=param2) check_table(wateroil.table) # Will fail when swl > 1 - sorw except AssertionError: pass try: wateroil = WaterOil(swl=param1, swirr=param2) check_table(wateroil.table) except AssertionError: pass try: wateroil = WaterOil(swcr=param1, sorw=param2) check_table(wateroil.table) except AssertionError: pass try: wateroil = WaterOil(swirr=param1, sorw=param2) check_table(wateroil.table) except AssertionError: pass
Example #21
Source File: space_test.py From bayesmark with Apache License 2.0 | 5 votes |
def test_decode_broadcast_float(): broadcast_tester( sp.decode, "(m,n),(n),()->(m)", otype=CAT_DTYPE, excluded=(1, 2), dtype=[np.float_, CAT_DTYPE, np.bool_], elements=[floats(), from_dtype(np.dtype(CAT_DTYPE)), booleans()], unique=[False, True, False], min_side={"n": 1}, map_=decoder_gen_broadcast, )
Example #22
Source File: gen_schemas.py From hypothesis-jsonschema with Mozilla Public License 2.0 | 5 votes |
def gen_number(draw: Any, kind: str) -> Dict[str, Union[str, float]]: """Draw a numeric schema.""" max_int_float = 2 ** 53 lower = draw(st.none() | st.integers(-max_int_float, max_int_float)) upper = draw(st.none() | st.integers(-max_int_float, max_int_float)) if lower is not None and upper is not None and lower > upper: lower, upper = upper, lower multiple_of = draw( st.none() | st.integers(2, 100) | st.floats(1 / 1024, 100, exclude_min=True) ) assume(None in (multiple_of, lower, upper) or multiple_of <= (upper - lower)) assert kind in ("integer", "number") out: Dict[str, Union[str, float]] = {"type": kind} # Generate the latest draft supported by jsonschema. assert hasattr(jsonschema, "Draft7Validator") if lower is not None: if draw(st.booleans(), label="exclusiveMinimum"): out["exclusiveMinimum"] = lower - 1 else: out["minimum"] = lower if upper is not None: if draw(st.booleans(), label="exclusiveMaximum"): out["exclusiveMaximum"] = upper + 1 else: out["maximum"] = upper if multiple_of is not None: out["multipleOf"] = multiple_of return out
Example #23
Source File: _testtools.py From geovoronoi with Apache License 2.0 | 5 votes |
def coords_2d_array(): return st_numpy.arrays(np.float_, st_numpy.array_shapes(min_dims=2, max_dims=2), elements=st.floats(allow_nan=False, allow_infinity=False))\ .filter(lambda arr: arr.shape[1] == 2)
Example #24
Source File: test_MarketAnalysis.py From MikaLendingBot with MIT License | 5 votes |
def random_rates(): return lists(floats(min_value=0.00001, max_value=100, allow_nan=False, allow_infinity=False), min_size=0, max_size=100).example()
Example #25
Source File: hypothesis_util.py From bayesmark with Apache License 2.0 | 5 votes |
def probs(): return floats(min_value=1e-3, max_value=1 - 1e-3)
Example #26
Source File: experiment_aggregate_test.py From bayesmark with Apache License 2.0 | 5 votes |
def perf_dataarrays(): dims = (ITER, SUGGEST) elements = floats(allow_nan=False) S = simple_dataarrays(dims, dtype=np.float_, elements=elements) return S
Example #27
Source File: experiment_aggregate_test.py From bayesmark with Apache License 2.0 | 5 votes |
def time_datasets(): vars_to_dims = {SUGGEST_PHASE: (ITER,), EVAL_PHASE: (ITER, SUGGEST), OBS_PHASE: (ITER,)} dtype = {SUGGEST_PHASE: np.float_, EVAL_PHASE: np.float_, OBS_PHASE: np.float_} elements = floats(min_value=0, allow_infinity=False, allow_nan=False) S = simple_datasets(vars_to_dims, dtype=dtype, elements=elements, min_side=1) return S
Example #28
Source File: test_util_accum.py From lkpy with MIT License | 5 votes |
def test_kvp_add_middle(data): "Test that KVP works in the middle of an array." ks = np.full(100, -1, dtype=np.int32) vs = np.full(100, np.nan) n = 25 avs = [] values = st.floats(-100, 100) for k in range(25): v = data.draw(values) avs.append(v) n = kvp_minheap_insert(25, n, 10, k, v, ks, vs) assert n == 35 # all the keys assert all(ks[25:35] >= 0) # value is the smallest assert vs[25] == np.min(vs[25:35]) # highest-ranked keys assert all(np.sort(vs[25:35]) == np.sort(avs)[15:]) # early is untouched assert all(ks[:25] == -1) assert all(np.isnan(vs[:25])) assert all(ks[35:] == -1) assert all(np.isnan(vs[35:]))
Example #29
Source File: test_common.py From pyvista with MIT License | 5 votes |
def n_numbers(draw, n): numbers = [] for _ in range(n): number = draw(one_of(floats(), integers())) numbers.append(number) return numbers
Example #30
Source File: test_float.py From segpy with GNU Affero General Public License v3.0 | 5 votes |
def ibm_compatible_positive_floats(draw): return draw(floats(SMALLEST_POSITIVE_NORMAL_IBM_FLOAT, MAX_IBM_FLOAT))