_qmvnt.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. # Integration of multivariate normal and t distributions.
  2. # Adapted from the MATLAB original implementations by Dr. Alan Genz.
  3. # http://www.math.wsu.edu/faculty/genz/software/software.html
  4. # Copyright (C) 2013, Alan Genz, All rights reserved.
  5. # Python implementation is copyright (C) 2022, Robert Kern, All rights
  6. # reserved.
  7. # Redistribution and use in source and binary forms, with or without
  8. # modification, are permitted provided the following conditions are met:
  9. # 1. Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. # notice, this list of conditions and the following disclaimer in
  13. # the documentation and/or other materials provided with the
  14. # distribution.
  15. # 3. The contributor name(s) may not be used to endorse or promote
  16. # products derived from this software without specific prior
  17. # written permission.
  18. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  21. # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  22. # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  23. # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  24. # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  25. # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  26. # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  27. # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF USE
  28. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. import math
  30. import numpy as np
  31. from scipy.fft import fft, ifft
  32. from scipy.special import ndtr as phi, ndtri as phinv
  33. from scipy.stats._qmc import primes_from_2_to
  34. from scipy.stats._stats_pythran import _bvnu
  35. from ._qmvnt_cy import _qmvn_inner, _qmvt_inner
  36. def _factorize_int(n):
  37. """Return a sorted list of the unique prime factors of a positive integer.
  38. """
  39. # NOTE: There are lots faster ways to do this, but this isn't terrible.
  40. factors = set()
  41. for p in primes_from_2_to(int(np.sqrt(n)) + 1):
  42. while not (n % p):
  43. factors.add(p)
  44. n //= p
  45. if n == 1:
  46. break
  47. if n != 1:
  48. factors.add(n)
  49. return sorted(factors)
  50. def _primitive_root(p):
  51. """Compute a primitive root of the prime number `p`.
  52. Used in the CBC lattice construction.
  53. References
  54. ----------
  55. .. [1] https://en.wikipedia.org/wiki/Primitive_root_modulo_n
  56. """
  57. # p is prime
  58. pm = p - 1
  59. factors = _factorize_int(pm)
  60. n = len(factors)
  61. r = 2
  62. k = 0
  63. while k < n:
  64. d = pm // factors[k]
  65. # pow() doesn't like numpy scalar types.
  66. rd = pow(int(r), int(d), int(p))
  67. if rd == 1:
  68. r += 1
  69. k = 0
  70. else:
  71. k += 1
  72. return r
  73. def _cbc_lattice(n_dim, n_qmc_samples):
  74. """Compute a QMC lattice generator using a Fast CBC construction.
  75. Parameters
  76. ----------
  77. n_dim : int > 0
  78. The number of dimensions for the lattice.
  79. n_qmc_samples : int > 0
  80. The desired number of QMC samples. This will be rounded down to the
  81. nearest prime to enable the CBC construction.
  82. Returns
  83. -------
  84. q : float array : shape=(n_dim,)
  85. The lattice generator vector. All values are in the open interval
  86. ``(0, 1)``.
  87. actual_n_qmc_samples : int
  88. The prime number of QMC samples that must be used with this lattice,
  89. no more, no less.
  90. References
  91. ----------
  92. .. [1] Nuyens, D. and Cools, R. "Fast Component-by-Component Construction,
  93. a Reprise for Different Kernels", In H. Niederreiter and D. Talay,
  94. editors, Monte-Carlo and Quasi-Monte Carlo Methods 2004,
  95. Springer-Verlag, 2006, 371-385.
  96. """
  97. # Round down to the nearest prime number.
  98. primes = primes_from_2_to(n_qmc_samples + 1)
  99. n_qmc_samples = primes[-1]
  100. bt = np.ones(n_dim)
  101. gm = np.hstack([1.0, 0.8 ** np.arange(n_dim - 1)])
  102. q = 1
  103. w = 0
  104. z = np.arange(1, n_dim + 1)
  105. m = (n_qmc_samples - 1) // 2
  106. g = _primitive_root(n_qmc_samples)
  107. # Slightly faster way to compute perm[j] = pow(g, j, n_qmc_samples)
  108. # Shame that we don't have modulo pow() implemented as a ufunc.
  109. perm = np.ones(m, dtype=int)
  110. for j in range(m - 1):
  111. perm[j + 1] = (g * perm[j]) % n_qmc_samples
  112. perm = np.minimum(n_qmc_samples - perm, perm)
  113. pn = perm / n_qmc_samples
  114. c = pn * pn - pn + 1.0 / 6
  115. fc = fft(c)
  116. for s in range(1, n_dim):
  117. reordered = np.hstack([
  118. c[:w+1][::-1],
  119. c[w+1:m][::-1],
  120. ])
  121. q = q * (bt[s-1] + gm[s-1] * reordered)
  122. w = ifft(fc * fft(q)).real.argmin()
  123. z[s] = perm[w]
  124. q = z / n_qmc_samples
  125. return q, n_qmc_samples
  126. def _qauto(func, covar, low, high, rng, error=1e-3, limit=10_000, **kwds):
  127. """Automatically rerun the integration to get the required error bound.
  128. Parameters
  129. ----------
  130. func : callable
  131. Either :func:`_qmvn` or :func:`_qmvt`.
  132. covar, low, high : array
  133. As specified in :func:`_qmvn` and :func:`_qmvt`.
  134. rng : Generator, optional
  135. default_rng(), yada, yada
  136. error : float > 0
  137. The desired error bound.
  138. limit : int > 0:
  139. The rough limit of the number of integration points to consider. The
  140. integration will stop looping once this limit has been *exceeded*.
  141. **kwds :
  142. Other keyword arguments to pass to `func`. When using :func:`_qmvt`, be
  143. sure to include ``nu=`` as one of these.
  144. Returns
  145. -------
  146. prob : float
  147. The estimated probability mass within the bounds.
  148. est_error : float
  149. 3 times the standard error of the batch estimates.
  150. n_samples : int
  151. The number of integration points actually used.
  152. """
  153. n = len(covar)
  154. n_samples = 0
  155. if n == 1:
  156. prob = phi(high / covar**0.5) - phi(low / covar**0.5)
  157. # More or less
  158. est_error = 1e-15
  159. elif n == 2:
  160. prob = _bvn(low, high, covar)
  161. est_error = 1e-15
  162. else:
  163. mi = min(limit, n * 1000)
  164. prob = 0.0
  165. est_error = 1.0
  166. ei = 0.0
  167. while est_error > error and n_samples < limit:
  168. mi = round(np.sqrt(2) * mi)
  169. pi, ei, ni = func(mi, covar, low, high, rng=rng, **kwds)
  170. n_samples += ni
  171. wt = 1.0 / (1 + (ei / est_error)**2)
  172. prob += wt * (pi - prob)
  173. est_error = np.sqrt(wt) * ei
  174. return prob, est_error, n_samples
  175. def _qmvn(m, covar, low, high, rng, lattice='cbc', n_batches=10):
  176. """Multivariate normal integration over box bounds.
  177. Parameters
  178. ----------
  179. m : int > n_batches
  180. The number of points to sample. This number will be divided into
  181. `n_batches` batches that apply random offsets of the sampling lattice
  182. for each batch in order to estimate the error.
  183. covar : (n, n) float array
  184. Possibly singular, positive semidefinite symmetric covariance matrix.
  185. low, high : (n,) float array
  186. The low and high integration bounds.
  187. rng : Generator, optional
  188. default_rng(), yada, yada
  189. lattice : 'cbc' or callable
  190. The type of lattice rule to use to construct the integration points.
  191. n_batches : int > 0, optional
  192. The number of QMC batches to apply.
  193. Returns
  194. -------
  195. prob : float
  196. The estimated probability mass within the bounds.
  197. est_error : float
  198. 3 times the standard error of the batch estimates.
  199. """
  200. cho, lo, hi = _permuted_cholesky(covar, low, high)
  201. if not cho.flags.c_contiguous:
  202. # qmvn_inner expects contiguous buffers
  203. cho = cho.copy()
  204. n = cho.shape[0]
  205. q, n_qmc_samples = _cbc_lattice(n - 1, max(m // n_batches, 1))
  206. rndm = rng.random(size=(n_batches, n))
  207. prob, est_error, n_samples = _qmvn_inner(
  208. q, rndm, int(n_qmc_samples), int(n_batches), cho, lo, hi
  209. )
  210. return prob, est_error, n_samples
  211. # Note: this function is not currently used or tested by any SciPy code. It is
  212. # included in this file to facilitate the resolution of gh-8367, gh-16142, and
  213. # possibly gh-14286, but must be reviewed and tested before use.
  214. def _mvn_qmc_integrand(covar, low, high, use_tent=False):
  215. """Transform the multivariate normal integration into a QMC integrand over
  216. a unit hypercube.
  217. The dimensionality of the resulting hypercube integration domain is one
  218. less than the dimensionality of the original integrand. Note that this
  219. transformation subsumes the integration bounds in order to account for
  220. infinite bounds. The QMC integration one does with the returned integrand
  221. should be on the unit hypercube.
  222. Parameters
  223. ----------
  224. covar : (n, n) float array
  225. Possibly singular, positive semidefinite symmetric covariance matrix.
  226. low, high : (n,) float array
  227. The low and high integration bounds.
  228. use_tent : bool, optional
  229. If True, then use tent periodization. Only helpful for lattice rules.
  230. Returns
  231. -------
  232. integrand : Callable[[NDArray], NDArray]
  233. The QMC-integrable integrand. It takes an
  234. ``(n_qmc_samples, ndim_integrand)`` array of QMC samples in the unit
  235. hypercube and returns the ``(n_qmc_samples,)`` evaluations of at these
  236. QMC points.
  237. ndim_integrand : int
  238. The dimensionality of the integrand. Equal to ``n-1``.
  239. """
  240. cho, lo, hi = _permuted_cholesky(covar, low, high)
  241. n = cho.shape[0]
  242. ndim_integrand = n - 1
  243. ct = cho[0, 0]
  244. c = phi(lo[0] / ct)
  245. d = phi(hi[0] / ct)
  246. ci = c
  247. dci = d - ci
  248. def integrand(*zs):
  249. ndim_qmc = len(zs)
  250. n_qmc_samples = len(np.atleast_1d(zs[0]))
  251. assert ndim_qmc == ndim_integrand
  252. y = np.zeros((ndim_qmc, n_qmc_samples))
  253. c = np.full(n_qmc_samples, ci)
  254. dc = np.full(n_qmc_samples, dci)
  255. pv = dc.copy()
  256. for i in range(1, n):
  257. if use_tent:
  258. # Tent periodization transform.
  259. x = abs(2 * zs[i-1] - 1)
  260. else:
  261. x = zs[i-1]
  262. y[i - 1, :] = phinv(c + x * dc)
  263. s = cho[i, :i] @ y[:i, :]
  264. ct = cho[i, i]
  265. c = phi((lo[i] - s) / ct)
  266. d = phi((hi[i] - s) / ct)
  267. dc = d - c
  268. pv = pv * dc
  269. return pv
  270. return integrand, ndim_integrand
  271. def _qmvt(m, nu, covar, low, high, rng, lattice='cbc', n_batches=10):
  272. """Multivariate t integration over box bounds.
  273. Parameters
  274. ----------
  275. m : int > n_batches
  276. The number of points to sample. This number will be divided into
  277. `n_batches` batches that apply random offsets of the sampling lattice
  278. for each batch in order to estimate the error.
  279. nu : float >= 0
  280. The shape parameter of the multivariate t distribution.
  281. covar : (n, n) float array
  282. Possibly singular, positive semidefinite symmetric covariance matrix.
  283. low, high : (n,) float array
  284. The low and high integration bounds.
  285. rng : Generator, optional
  286. default_rng(), yada, yada
  287. lattice : 'cbc' or callable
  288. The type of lattice rule to use to construct the integration points.
  289. n_batches : int > 0, optional
  290. The number of QMC batches to apply.
  291. Returns
  292. -------
  293. prob : float
  294. The estimated probability mass within the bounds.
  295. est_error : float
  296. 3 times the standard error of the batch estimates.
  297. n_samples : int
  298. The number of samples actually used.
  299. """
  300. sn = max(1.0, np.sqrt(nu))
  301. low = np.asarray(low, dtype=np.float64)
  302. high = np.asarray(high, dtype=np.float64)
  303. cho, lo, hi = _permuted_cholesky(covar, low / sn, high / sn)
  304. n = cho.shape[0]
  305. q, n_qmc_samples = _cbc_lattice(n, max(m // n_batches, 1))
  306. rndm = rng.random(size=(n_batches, n))
  307. prob, est_error, n_samples = _qmvt_inner(
  308. q, rndm, int(n_qmc_samples), int(n_batches), cho, lo, hi, float(nu)
  309. )
  310. return prob, est_error, n_samples
  311. def _permuted_cholesky(covar, low, high, tol=1e-10):
  312. """Compute a scaled, permuted Cholesky factor, with integration bounds.
  313. The scaling and permuting of the dimensions accomplishes part of the
  314. transformation of the original integration problem into a more numerically
  315. tractable form. The lower-triangular Cholesky factor will then be used in
  316. the subsequent integration. The integration bounds will be scaled and
  317. permuted as well.
  318. Parameters
  319. ----------
  320. covar : (n, n) float array
  321. Possibly singular, positive semidefinite symmetric covariance matrix.
  322. low, high : (n,) float array
  323. The low and high integration bounds.
  324. tol : float, optional
  325. The singularity tolerance.
  326. Returns
  327. -------
  328. cho : (n, n) float array
  329. Lower Cholesky factor, scaled and permuted.
  330. new_low, new_high : (n,) float array
  331. The scaled and permuted low and high integration bounds.
  332. """
  333. # Make copies for outputting.
  334. cho = np.array(covar, dtype=np.float64)
  335. new_lo = np.array(low, dtype=np.float64)
  336. new_hi = np.array(high, dtype=np.float64)
  337. n = cho.shape[0]
  338. if cho.shape != (n, n):
  339. raise ValueError("expected a square symmetric array")
  340. if new_lo.shape != (n,) or new_hi.shape != (n,):
  341. raise ValueError(
  342. "expected integration boundaries the same dimensions "
  343. "as the covariance matrix"
  344. )
  345. # Scale by the sqrt of the diagonal.
  346. dc = np.sqrt(np.maximum(np.diag(cho), 0.0))
  347. # But don't divide by 0.
  348. dc[dc == 0.0] = 1.0
  349. new_lo /= dc
  350. new_hi /= dc
  351. cho /= dc
  352. cho /= dc[:, np.newaxis]
  353. y = np.zeros(n)
  354. sqtp = np.sqrt(2 * np.pi)
  355. for k in range(n):
  356. epk = (k + 1) * tol
  357. im = k
  358. ck = 0.0
  359. dem = 1.0
  360. s = 0.0
  361. lo_m = 0.0
  362. hi_m = 0.0
  363. for i in range(k, n):
  364. if cho[i, i] > tol:
  365. ci = np.sqrt(cho[i, i])
  366. if i > 0:
  367. s = cho[i, :k] @ y[:k]
  368. lo_i = (new_lo[i] - s) / ci
  369. hi_i = (new_hi[i] - s) / ci
  370. de = phi(hi_i) - phi(lo_i)
  371. if de <= dem:
  372. ck = ci
  373. dem = de
  374. lo_m = lo_i
  375. hi_m = hi_i
  376. im = i
  377. if im > k:
  378. # Swap im and k
  379. cho[im, im] = cho[k, k]
  380. _swap_slices(cho, np.s_[im, :k], np.s_[k, :k])
  381. _swap_slices(cho, np.s_[im + 1:, im], np.s_[im + 1:, k])
  382. _swap_slices(cho, np.s_[k + 1:im, k], np.s_[im, k + 1:im])
  383. _swap_slices(new_lo, k, im)
  384. _swap_slices(new_hi, k, im)
  385. if ck > epk:
  386. cho[k, k] = ck
  387. cho[k, k + 1:] = 0.0
  388. for i in range(k + 1, n):
  389. cho[i, k] /= ck
  390. cho[i, k + 1:i + 1] -= cho[i, k] * cho[k + 1:i + 1, k]
  391. if abs(dem) > tol:
  392. y[k] = ((np.exp(-lo_m * lo_m / 2) - np.exp(-hi_m * hi_m / 2)) /
  393. (sqtp * dem))
  394. else:
  395. y[k] = (lo_m + hi_m) / 2
  396. if lo_m < -10:
  397. y[k] = hi_m
  398. elif hi_m > 10:
  399. y[k] = lo_m
  400. cho[k, :k + 1] /= ck
  401. new_lo[k] /= ck
  402. new_hi[k] /= ck
  403. else:
  404. cho[k:, k] = 0.0
  405. y[k] = (new_lo[k] + new_hi[k]) / 2
  406. return cho, new_lo, new_hi
  407. def _swap_slices(x, slc1, slc2):
  408. t = x[slc1].copy()
  409. x[slc1] = x[slc2].copy()
  410. x[slc2] = t
  411. def _bvn(a, b, A):
  412. # covariance matrix is written [[s1**2, rho*s1*s2], [rho*s1*s2, s2**2]]
  413. # e.g. https://en.wikipedia.org/wiki/Multivariate_normal_distribution
  414. # therefore, s12 = rho*s1*s2 -> rho = s12/(s1*s2)
  415. s1 = math.sqrt(A[0, 0])
  416. s2 = math.sqrt(A[1, 1])
  417. s12 = A[0, 1]
  418. r = s12 / (s1 * s2)
  419. # the x and y coordinates seem to be normalized by the standard devs
  420. xl, xu = a[0] / s1, b[0] / s1
  421. yl, yu = a[1] / s2, b[1] / s2
  422. p = _bvnu(xl, yl, r) - _bvnu(xu, yl, r) - _bvnu(xl, yu, r) + _bvnu(xu, yu, r)
  423. p = max( 0., min( p, 1. ) )
  424. return p