constraint.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import paddle
  15. class Constraint:
  16. """Constraint condition for random variable."""
  17. def __call__(self, value):
  18. raise NotImplementedError
  19. class Real(Constraint):
  20. def __call__(self, value):
  21. return value == value
  22. class Range(Constraint):
  23. def __init__(self, lower, upper):
  24. self._lower = lower
  25. self._upper = upper
  26. super().__init__()
  27. def __call__(self, value):
  28. return self._lower <= value <= self._upper
  29. class Positive(Constraint):
  30. def __call__(self, value):
  31. return value >= 0.0
  32. class Simplex(Constraint):
  33. def __call__(self, value):
  34. return paddle.all(value >= 0, axis=-1) and (
  35. (value.sum(-1) - 1).abs() < 1e-6
  36. )
  37. real = Real()
  38. positive = Positive()
  39. simplex = Simplex()