utils.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # Copyright 2016 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. import copy
  5. import functools
  6. import math
  7. import random
  8. def RandomLowInteger(low, high, beta=31.0):
  9. """Like random.randint, but heavily skewed toward the low end"""
  10. assert low <= high
  11. return low + int(math.floor(random.betavariate(1.0, beta) * (high - low)))
  12. def UniformExpoInteger(low, high, base=2):
  13. """Returns base to a power uniformly distributed between low and high.
  14. This is useful for exploring large ranges of integers while ensuring that
  15. values of all different sizes are represented.
  16. """
  17. return int(math.floor(math.pow(base, random.uniform(low, high))))
  18. def WeightedChoice(choices): # pylint: disable=inconsistent-return-statements
  19. """Chooses an item given a sequence of (choice, weight) tuples"""
  20. total = sum(w for c, w in choices)
  21. r = random.uniform(0, total)
  22. upto = 0
  23. for c, w in choices:
  24. upto += w
  25. if upto >= r:
  26. return c
  27. assert False
  28. def Pipeline(*funcs):
  29. """Given a number of single-argument functions, returns a single-argument
  30. function which computes their composition. Each of the functions are applied
  31. to the input in order from left to right, with the result of each function
  32. passed as the argument to the next function."""
  33. return reduce(lambda f, g: lambda x: g(f(x)), funcs)
  34. def DeepMemoize(obj):
  35. """A memoizing decorator that returns deep copies of the function results."""
  36. cache = obj.cache = {}
  37. @functools.wraps(obj)
  38. def Memoize(*args):
  39. if args not in cache:
  40. cache[args] = copy.deepcopy(obj(*args))
  41. return copy.deepcopy(cache[args])
  42. return Memoize