math.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import numpy as np
  2. EPS = np.finfo(float).eps
  3. def get_arrays_tol(*arrays):
  4. """
  5. Get a relative tolerance for a set of arrays.
  6. Parameters
  7. ----------
  8. *arrays: tuple
  9. Set of `numpy.ndarray` to get the tolerance for.
  10. Returns
  11. -------
  12. float
  13. Relative tolerance for the set of arrays.
  14. Raises
  15. ------
  16. ValueError
  17. If no array is provided.
  18. """
  19. if len(arrays) == 0:
  20. raise ValueError("At least one array must be provided.")
  21. size = max(array.size for array in arrays)
  22. weight = max(
  23. np.max(np.abs(array[np.isfinite(array)]), initial=1.0)
  24. for array in arrays
  25. )
  26. return 10.0 * EPS * max(size, 1.0) * weight
  27. def exact_1d_array(x, message):
  28. """
  29. Preprocess a 1-dimensional array.
  30. Parameters
  31. ----------
  32. x : array_like
  33. Array to be preprocessed.
  34. message : str
  35. Error message if `x` cannot be interpreter as a 1-dimensional array.
  36. Returns
  37. -------
  38. `numpy.ndarray`
  39. Preprocessed array.
  40. """
  41. x = np.atleast_1d(np.squeeze(x)).astype(float)
  42. if x.ndim != 1:
  43. raise ValueError(message)
  44. return x
  45. def exact_2d_array(x, message):
  46. """
  47. Preprocess a 2-dimensional array.
  48. Parameters
  49. ----------
  50. x : array_like
  51. Array to be preprocessed.
  52. message : str
  53. Error message if `x` cannot be interpreter as a 2-dimensional array.
  54. Returns
  55. -------
  56. `numpy.ndarray`
  57. Preprocessed array.
  58. """
  59. x = np.atleast_2d(x).astype(float)
  60. if x.ndim != 2:
  61. raise ValueError(message)
  62. return x