_backend.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. import scipy._lib.uarray as ua
  2. from . import _fftlog
  3. from . import _pocketfft
  4. class _ScipyBackend:
  5. """The default backend for fft calculations
  6. Notes
  7. -----
  8. We use the domain ``numpy.scipy`` rather than ``scipy`` because ``uarray``
  9. treats the domain as a hierarchy. This means the user can install a single
  10. backend for ``numpy`` and have it implement ``numpy.scipy.fft`` as well.
  11. """
  12. __ua_domain__ = "numpy.scipy.fft"
  13. @staticmethod
  14. def __ua_function__(method, args, kwargs):
  15. fn = getattr(_pocketfft, method.__name__, None)
  16. if fn is None:
  17. fn = getattr(_fftlog, method.__name__, None)
  18. if fn is None:
  19. return NotImplemented
  20. return fn(*args, **kwargs)
  21. _named_backends = {
  22. 'scipy': _ScipyBackend,
  23. }
  24. def _backend_from_arg(backend):
  25. """Maps strings to known backends and validates the backend"""
  26. if isinstance(backend, str):
  27. try:
  28. backend = _named_backends[backend]
  29. except KeyError as e:
  30. raise ValueError('Unknown backend {}'.format(backend)) from e
  31. if backend.__ua_domain__ != 'numpy.scipy.fft':
  32. raise ValueError('Backend does not implement "numpy.scipy.fft"')
  33. return backend
  34. def set_global_backend(backend, coerce=False, only=False, try_last=False):
  35. """Sets the global fft backend
  36. This utility method replaces the default backend for permanent use. It
  37. will be tried in the list of backends automatically, unless the
  38. ``only`` flag is set on a backend. This will be the first tried
  39. backend outside the :obj:`set_backend` context manager.
  40. Parameters
  41. ----------
  42. backend : {object, 'scipy'}
  43. The backend to use.
  44. Can either be a ``str`` containing the name of a known backend
  45. {'scipy'} or an object that implements the uarray protocol.
  46. coerce : bool
  47. Whether to coerce input types when trying this backend.
  48. only : bool
  49. If ``True``, no more backends will be tried if this fails.
  50. Implied by ``coerce=True``.
  51. try_last : bool
  52. If ``True``, the global backend is tried after registered backends.
  53. Raises
  54. ------
  55. ValueError: If the backend does not implement ``numpy.scipy.fft``.
  56. Notes
  57. -----
  58. This will overwrite the previously set global backend, which, by default, is
  59. the SciPy implementation.
  60. Examples
  61. --------
  62. We can set the global fft backend:
  63. >>> from scipy.fft import fft, set_global_backend
  64. >>> set_global_backend("scipy") # Sets global backend. "scipy" is the default backend.
  65. >>> fft([1]) # Calls the global backend
  66. array([1.+0.j])
  67. """
  68. backend = _backend_from_arg(backend)
  69. ua.set_global_backend(backend, coerce=coerce, only=only, try_last=try_last)
  70. def register_backend(backend):
  71. """
  72. Register a backend for permanent use.
  73. Registered backends have the lowest priority and will be tried after the
  74. global backend.
  75. Parameters
  76. ----------
  77. backend : {object, 'scipy'}
  78. The backend to use.
  79. Can either be a ``str`` containing the name of a known backend
  80. {'scipy'} or an object that implements the uarray protocol.
  81. Raises
  82. ------
  83. ValueError: If the backend does not implement ``numpy.scipy.fft``.
  84. Examples
  85. --------
  86. We can register a new fft backend:
  87. >>> from scipy.fft import fft, register_backend, set_global_backend
  88. >>> class NoopBackend: # Define an invalid Backend
  89. ... __ua_domain__ = "numpy.scipy.fft"
  90. ... def __ua_function__(self, func, args, kwargs):
  91. ... return NotImplemented
  92. >>> set_global_backend(NoopBackend()) # Set the invalid backend as global
  93. >>> register_backend("scipy") # Register a new backend
  94. >>> fft([1]) # The registered backend is called because the global backend returns `NotImplemented`
  95. array([1.+0.j])
  96. >>> set_global_backend("scipy") # Restore global backend to default
  97. """
  98. backend = _backend_from_arg(backend)
  99. ua.register_backend(backend)
  100. def set_backend(backend, coerce=False, only=False):
  101. """Context manager to set the backend within a fixed scope.
  102. Upon entering the ``with`` statement, the given backend will be added to
  103. the list of available backends with the highest priority. Upon exit, the
  104. backend is reset to the state before entering the scope.
  105. Parameters
  106. ----------
  107. backend : {object, 'scipy'}
  108. The backend to use.
  109. Can either be a ``str`` containing the name of a known backend
  110. {'scipy'} or an object that implements the uarray protocol.
  111. coerce : bool, optional
  112. Whether to allow expensive conversions for the ``x`` parameter. e.g.,
  113. copying a NumPy array to the GPU for a CuPy backend. Implies ``only``.
  114. only : bool, optional
  115. If only is ``True`` and this backend returns ``NotImplemented``, then a
  116. BackendNotImplemented error will be raised immediately. Ignoring any
  117. lower priority backends.
  118. Examples
  119. --------
  120. >>> import scipy.fft as fft
  121. >>> with fft.set_backend('scipy', only=True):
  122. ... fft.fft([1]) # Always calls the scipy implementation
  123. array([1.+0.j])
  124. """
  125. backend = _backend_from_arg(backend)
  126. return ua.set_backend(backend, coerce=coerce, only=only)
  127. def skip_backend(backend):
  128. """Context manager to skip a backend within a fixed scope.
  129. Within the context of a ``with`` statement, the given backend will not be
  130. called. This covers backends registered both locally and globally. Upon
  131. exit, the backend will again be considered.
  132. Parameters
  133. ----------
  134. backend : {object, 'scipy'}
  135. The backend to skip.
  136. Can either be a ``str`` containing the name of a known backend
  137. {'scipy'} or an object that implements the uarray protocol.
  138. Examples
  139. --------
  140. >>> import scipy.fft as fft
  141. >>> fft.fft([1]) # Calls default SciPy backend
  142. array([1.+0.j])
  143. >>> with fft.skip_backend('scipy'): # We explicitly skip the SciPy backend
  144. ... fft.fft([1]) # leaving no implementation available
  145. Traceback (most recent call last):
  146. ...
  147. BackendNotImplementedError: No selected backends had an implementation ...
  148. """
  149. backend = _backend_from_arg(backend)
  150. return ua.skip_backend(backend)
  151. set_global_backend('scipy', try_last=True)