1
0

utils.py 1.2 KB

12345678910111213141516171819202122232425262728
  1. """Short utility functions for use elsewhere"""
  2. import numpy as np
  3. def update_config(default, update):
  4. """Recursively updates a Python (configuration) dictionary"""
  5. for key in update:
  6. if isinstance(default[key], dict): #Recurse if it is a dictionary
  7. update_config(default[key], update[key])
  8. else: default[key] = update[key] #Simply copy the value otherwise
  9. def random_unit_vectors(size, mode='3D'):
  10. """Draws an array of size size corresponding to isotropically distributed
  11. random unit vectors (number of vectors, dimension). If mode is 2D, the
  12. vectors are instead distributed isotropically on the xy plane."""
  13. direction = np.random.normal(size=(size, 3))
  14. if mode == '2D': direction[:, -1] = 0
  15. return direction / np.linalg.norm(direction, axis=-1, keepdims=True)
  16. def cascade_round(arr):
  17. """Rounds the floats in an array to integers while preserving their total
  18. sum (as closely as possible). Follows the cascade rounding algorithm."""
  19. runningSurplus = 0
  20. for i in range(len(arr)):
  21. f = arr[i] + runningSurplus
  22. arr[i] = int(np.round(f))
  23. runningSurplus = f - arr[i]
  24. return arr