fixpoint_solver.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Copyright 2019 The FATE Authors. All Rights Reserved.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. #
  18. import numpy as np
  19. class FixedPointEncoder(object):
  20. def __init__(self, fixpoint_precision=2**23):
  21. self._fixpoint_precision = fixpoint_precision
  22. def encode(self, obj):
  23. if isinstance(obj, np.ndarray):
  24. fixed_obj = np.round(obj * self._fixpoint_precision, 0).astype(int)
  25. elif isinstance(obj, list):
  26. fixed_obj = np.round(np.array(obj) * self._fixpoint_precision, 0).astype(int).to_list()
  27. else:
  28. raise ValueError("FixPointEncoder Not support type {}".format(type(obj)))
  29. return fixed_obj
  30. def decode(self, obj):
  31. if isinstance(obj, np.ndarray):
  32. decode_obj = obj / self._fixpoint_precision
  33. elif isinstance(obj, list):
  34. decode_obj = (np.array(obj) / self._fixpoint_precision).to_list()
  35. else:
  36. raise ValueError("FixPointEncoder Not support type {}".format(type(obj)))
  37. return decode_obj