test_spfun_stats.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import numpy as np
  2. from numpy.testing import (assert_array_equal,
  3. assert_array_almost_equal_nulp, assert_almost_equal)
  4. from pytest import raises as assert_raises
  5. from scipy.special import gammaln, multigammaln
  6. class TestMultiGammaLn:
  7. def test1(self):
  8. # A test of the identity
  9. # Gamma_1(a) = Gamma(a)
  10. np.random.seed(1234)
  11. a = np.abs(np.random.randn())
  12. assert_array_equal(multigammaln(a, 1), gammaln(a))
  13. def test2(self):
  14. # A test of the identity
  15. # Gamma_2(a) = sqrt(pi) * Gamma(a) * Gamma(a - 0.5)
  16. a = np.array([2.5, 10.0])
  17. result = multigammaln(a, 2)
  18. expected = np.log(np.sqrt(np.pi)) + gammaln(a) + gammaln(a - 0.5)
  19. assert_almost_equal(result, expected)
  20. def test_bararg(self):
  21. assert_raises(ValueError, multigammaln, 0.5, 1.2)
  22. def _check_multigammaln_array_result(a, d):
  23. # Test that the shape of the array returned by multigammaln
  24. # matches the input shape, and that all the values match
  25. # the value computed when multigammaln is called with a scalar.
  26. result = multigammaln(a, d)
  27. assert_array_equal(a.shape, result.shape)
  28. a1 = a.ravel()
  29. result1 = result.ravel()
  30. for i in range(a.size):
  31. assert_array_almost_equal_nulp(result1[i], multigammaln(a1[i], d))
  32. def test_multigammaln_array_arg():
  33. # Check that the array returned by multigammaln has the correct
  34. # shape and contains the correct values. The cases have arrays
  35. # with several differnent shapes.
  36. # The cases include a regression test for ticket #1849
  37. # (a = np.array([2.0]), an array with a single element).
  38. np.random.seed(1234)
  39. cases = [
  40. # a, d
  41. (np.abs(np.random.randn(3, 2)) + 5, 5),
  42. (np.abs(np.random.randn(1, 2)) + 5, 5),
  43. (np.arange(10.0, 18.0).reshape(2, 2, 2), 3),
  44. (np.array([2.0]), 3),
  45. (np.float64(2.0), 3),
  46. ]
  47. for a, d in cases:
  48. _check_multigammaln_array_result(a, d)