random.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #
  2. # Copyright 2019 The FATE Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. from numpy.random import RandomState
  17. class RandomPads(object):
  18. """random pads utils for secret homogeneous aggregation
  19. currently use numpy.random, which use bit generator MT19937
  20. other algorithms such as pcg and xoroshiro may be supported in the future
  21. """
  22. def __init__(self, init_seed=None):
  23. self._rand = RandomState(init_seed)
  24. def rand(self, d0, *more, **kwargs):
  25. return self._rand.rand(d0, *more, **kwargs)
  26. def randn(self, d0, *more, **kwargs):
  27. return self._rand.randn(d0, *more, **kwargs)
  28. def add_randn_pads(self, a, w):
  29. """a + r * w,
  30. where r is random array with nominal distribution N(0,1) and r.shape == a.shape
  31. """
  32. return a + self._rand.randn(*a.shape) * w
  33. def add_rand_pads(self, a, w):
  34. """a + r * w,
  35. where r is random array with uniform distribution U[0,1) and r.shape == a.shape
  36. """
  37. return a + self._rand.rand(*a.shape) * w