misc.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. """
  2. =============
  3. Miscellaneous
  4. =============
  5. IEEE 754 Floating Point Special Values
  6. --------------------------------------
  7. Special values defined in numpy: nan, inf,
  8. NaNs can be used as a poor-man's mask (if you don't care what the
  9. original value was)
  10. Note: cannot use equality to test NaNs. E.g.: ::
  11. >>> myarr = np.array([1., 0., np.nan, 3.])
  12. >>> np.where(myarr == np.nan)
  13. >>> np.nan == np.nan # is always False! Use special numpy functions instead.
  14. False
  15. >>> myarr[myarr == np.nan] = 0. # doesn't work
  16. >>> myarr
  17. array([ 1., 0., NaN, 3.])
  18. >>> myarr[np.isnan(myarr)] = 0. # use this instead find
  19. >>> myarr
  20. array([ 1., 0., 0., 3.])
  21. Other related special value functions: ::
  22. isinf(): True if value is inf
  23. isfinite(): True if not nan or inf
  24. nan_to_num(): Map nan to 0, inf to max float, -inf to min float
  25. The following corresponds to the usual functions except that nans are excluded
  26. from the results: ::
  27. nansum()
  28. nanmax()
  29. nanmin()
  30. nanargmax()
  31. nanargmin()
  32. >>> x = np.arange(10.)
  33. >>> x[3] = np.nan
  34. >>> x.sum()
  35. nan
  36. >>> np.nansum(x)
  37. 42.0
  38. How numpy handles numerical exceptions
  39. --------------------------------------
  40. The default is to ``'warn'`` for ``invalid``, ``divide``, and ``overflow``
  41. and ``'ignore'`` for ``underflow``. But this can be changed, and it can be
  42. set individually for different kinds of exceptions. The different behaviors
  43. are:
  44. - 'ignore' : Take no action when the exception occurs.
  45. - 'warn' : Print a `RuntimeWarning` (via the Python `warnings` module).
  46. - 'raise' : Raise a `FloatingPointError`.
  47. - 'call' : Call a function specified using the `seterrcall` function.
  48. - 'print' : Print a warning directly to ``stdout``.
  49. - 'log' : Record error in a Log object specified by `seterrcall`.
  50. These behaviors can be set for all kinds of errors or specific ones:
  51. - all : apply to all numeric exceptions
  52. - invalid : when NaNs are generated
  53. - divide : divide by zero (for integers as well!)
  54. - overflow : floating point overflows
  55. - underflow : floating point underflows
  56. Note that integer divide-by-zero is handled by the same machinery.
  57. These behaviors are set on a per-thread basis.
  58. Examples
  59. --------
  60. ::
  61. >>> oldsettings = np.seterr(all='warn')
  62. >>> np.zeros(5,dtype=np.float32)/0.
  63. invalid value encountered in divide
  64. >>> j = np.seterr(under='ignore')
  65. >>> np.array([1.e-100])**10
  66. >>> j = np.seterr(invalid='raise')
  67. >>> np.sqrt(np.array([-1.]))
  68. FloatingPointError: invalid value encountered in sqrt
  69. >>> def errorhandler(errstr, errflag):
  70. ... print("saw stupid error!")
  71. >>> np.seterrcall(errorhandler)
  72. <function err_handler at 0x...>
  73. >>> j = np.seterr(all='call')
  74. >>> np.zeros(5, dtype=np.int32)/0
  75. FloatingPointError: invalid value encountered in divide
  76. saw stupid error!
  77. >>> j = np.seterr(**oldsettings) # restore previous
  78. ... # error-handling settings
  79. Interfacing to C
  80. ----------------
  81. Only a survey of the choices. Little detail on how each works.
  82. 1) Bare metal, wrap your own C-code manually.
  83. - Plusses:
  84. - Efficient
  85. - No dependencies on other tools
  86. - Minuses:
  87. - Lots of learning overhead:
  88. - need to learn basics of Python C API
  89. - need to learn basics of numpy C API
  90. - need to learn how to handle reference counting and love it.
  91. - Reference counting often difficult to get right.
  92. - getting it wrong leads to memory leaks, and worse, segfaults
  93. - API will change for Python 3.0!
  94. 2) Cython
  95. - Plusses:
  96. - avoid learning C API's
  97. - no dealing with reference counting
  98. - can code in pseudo python and generate C code
  99. - can also interface to existing C code
  100. - should shield you from changes to Python C api
  101. - has become the de-facto standard within the scientific Python community
  102. - fast indexing support for arrays
  103. - Minuses:
  104. - Can write code in non-standard form which may become obsolete
  105. - Not as flexible as manual wrapping
  106. 3) ctypes
  107. - Plusses:
  108. - part of Python standard library
  109. - good for interfacing to existing sharable libraries, particularly
  110. Windows DLLs
  111. - avoids API/reference counting issues
  112. - good numpy support: arrays have all these in their ctypes
  113. attribute: ::
  114. a.ctypes.data a.ctypes.get_strides
  115. a.ctypes.data_as a.ctypes.shape
  116. a.ctypes.get_as_parameter a.ctypes.shape_as
  117. a.ctypes.get_data a.ctypes.strides
  118. a.ctypes.get_shape a.ctypes.strides_as
  119. - Minuses:
  120. - can't use for writing code to be turned into C extensions, only a wrapper
  121. tool.
  122. 4) SWIG (automatic wrapper generator)
  123. - Plusses:
  124. - around a long time
  125. - multiple scripting language support
  126. - C++ support
  127. - Good for wrapping large (many functions) existing C libraries
  128. - Minuses:
  129. - generates lots of code between Python and the C code
  130. - can cause performance problems that are nearly impossible to optimize
  131. out
  132. - interface files can be hard to write
  133. - doesn't necessarily avoid reference counting issues or needing to know
  134. API's
  135. 5) scipy.weave
  136. - Plusses:
  137. - can turn many numpy expressions into C code
  138. - dynamic compiling and loading of generated C code
  139. - can embed pure C code in Python module and have weave extract, generate
  140. interfaces and compile, etc.
  141. - Minuses:
  142. - Future very uncertain: it's the only part of Scipy not ported to Python 3
  143. and is effectively deprecated in favor of Cython.
  144. 6) Psyco
  145. - Plusses:
  146. - Turns pure python into efficient machine code through jit-like
  147. optimizations
  148. - very fast when it optimizes well
  149. - Minuses:
  150. - Only on intel (windows?)
  151. - Doesn't do much for numpy?
  152. Interfacing to Fortran:
  153. -----------------------
  154. The clear choice to wrap Fortran code is
  155. `f2py <http://docs.scipy.org/doc/numpy-dev/f2py/>`_.
  156. Pyfort is an older alternative, but not supported any longer.
  157. Fwrap is a newer project that looked promising but isn't being developed any
  158. longer.
  159. Interfacing to C++:
  160. -------------------
  161. 1) Cython
  162. 2) CXX
  163. 3) Boost.python
  164. 4) SWIG
  165. 5) SIP (used mainly in PyQT)
  166. """
  167. from __future__ import division, absolute_import, print_function