_sampling.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314
  1. import math
  2. import numbers
  3. import numpy as np
  4. from scipy import stats
  5. from scipy import special as sc
  6. from ._qmc import (check_random_state as check_random_state_qmc,
  7. Halton, QMCEngine)
  8. from ._unuran.unuran_wrapper import NumericalInversePolynomial
  9. from scipy._lib._util import check_random_state
  10. __all__ = ['FastGeneratorInversion', 'RatioUniforms']
  11. # define pdfs and other helper functions to create the generators
  12. def argus_pdf(x, chi):
  13. # approach follows Baumgarten/Hoermann: Generating ARGUS random variates
  14. # for chi > 5, use relationship of the ARGUS distribution to Gamma(1.5)
  15. if chi <= 5:
  16. y = 1 - x * x
  17. return x * math.sqrt(y) * math.exp(-0.5 * chi**2 * y)
  18. return math.sqrt(x) * math.exp(-x)
  19. def argus_gamma_trf(x, chi):
  20. if chi <= 5:
  21. return x
  22. return np.sqrt(1.0 - 2 * x / chi**2)
  23. def argus_gamma_inv_trf(x, chi):
  24. if chi <= 5:
  25. return x
  26. return 0.5 * chi**2 * (1 - x**2)
  27. def betaprime_pdf(x, a, b):
  28. if x > 0:
  29. logf = (a - 1) * math.log(x) - (a + b) * math.log1p(x) - sc.betaln(a, b)
  30. return math.exp(logf)
  31. else:
  32. # return pdf at x == 0 separately to avoid runtime warnings
  33. if a > 1:
  34. return 0
  35. elif a < 1:
  36. return np.inf
  37. else:
  38. return 1 / sc.beta(a, b)
  39. def beta_valid_params(a, b):
  40. return (min(a, b) >= 0.1) and (max(a, b) <= 700)
  41. def gamma_pdf(x, a):
  42. if x > 0:
  43. return math.exp(-math.lgamma(a) + (a - 1.0) * math.log(x) - x)
  44. else:
  45. return 0 if a >= 1 else np.inf
  46. def invgamma_pdf(x, a):
  47. if x > 0:
  48. return math.exp(-(a + 1.0) * math.log(x) - math.lgamma(a) - 1 / x)
  49. else:
  50. return 0 if a >= 1 else np.inf
  51. def burr_pdf(x, cc, dd):
  52. # note: we use np.exp instead of math.exp, otherwise an overflow
  53. # error can occur in the setup, e.g., for parameters
  54. # 1.89128135, 0.30195177, see test test_burr_overflow
  55. if x > 0:
  56. lx = math.log(x)
  57. return np.exp(-(cc + 1) * lx - (dd + 1) * math.log1p(np.exp(-cc * lx)))
  58. else:
  59. return 0
  60. def burr12_pdf(x, cc, dd):
  61. if x > 0:
  62. lx = math.log(x)
  63. logterm = math.log1p(math.exp(cc * lx))
  64. return math.exp((cc - 1) * lx - (dd + 1) * logterm + math.log(cc * dd))
  65. else:
  66. return 0
  67. def chi_pdf(x, a):
  68. if x > 0:
  69. return math.exp(
  70. (a - 1) * math.log(x)
  71. - 0.5 * (x * x)
  72. - (a / 2 - 1) * math.log(2)
  73. - math.lgamma(0.5 * a)
  74. )
  75. else:
  76. return 0 if a >= 1 else np.inf
  77. def chi2_pdf(x, df):
  78. if x > 0:
  79. return math.exp(
  80. (df / 2 - 1) * math.log(x)
  81. - 0.5 * x
  82. - (df / 2) * math.log(2)
  83. - math.lgamma(0.5 * df)
  84. )
  85. else:
  86. return 0 if df >= 1 else np.inf
  87. def alpha_pdf(x, a):
  88. if x > 0:
  89. return math.exp(-2.0 * math.log(x) - 0.5 * (a - 1.0 / x) ** 2)
  90. return 0.0
  91. def bradford_pdf(x, c):
  92. if 0 <= x <= 1:
  93. return 1.0 / (1.0 + c * x)
  94. return 0.0
  95. def crystalball_pdf(x, b, m):
  96. if x > -b:
  97. return math.exp(-0.5 * x * x)
  98. return math.exp(m * math.log(m / b) - 0.5 * b * b - m * math.log(m / b - b - x))
  99. def weibull_min_pdf(x, c):
  100. if x > 0:
  101. return c * math.exp((c - 1) * math.log(x) - x**c)
  102. return 0.0
  103. def weibull_max_pdf(x, c):
  104. if x < 0:
  105. return c * math.exp((c - 1) * math.log(-x) - ((-x) ** c))
  106. return 0.0
  107. def invweibull_pdf(x, c):
  108. if x > 0:
  109. return c * math.exp(-(c + 1) * math.log(x) - x ** (-c))
  110. return 0.0
  111. def wald_pdf(x):
  112. if x > 0:
  113. return math.exp(-((x - 1) ** 2) / (2 * x)) / math.sqrt(x**3)
  114. return 0.0
  115. def geninvgauss_mode(p, b):
  116. if p > 1: # equivalent mode formulas numerical more stable versions
  117. return (math.sqrt((1 - p) ** 2 + b**2) - (1 - p)) / b
  118. return b / (math.sqrt((1 - p) ** 2 + b**2) + (1 - p))
  119. def geninvgauss_pdf(x, p, b):
  120. m = geninvgauss_mode(p, b)
  121. lfm = (p - 1) * math.log(m) - 0.5 * b * (m + 1 / m)
  122. if x > 0:
  123. return math.exp((p - 1) * math.log(x) - 0.5 * b * (x + 1 / x) - lfm)
  124. return 0.0
  125. def invgauss_mode(mu):
  126. return 1.0 / (math.sqrt(1.5 * 1.5 + 1 / (mu * mu)) + 1.5)
  127. def invgauss_pdf(x, mu):
  128. m = invgauss_mode(mu)
  129. lfm = -1.5 * math.log(m) - (m - mu) ** 2 / (2 * m * mu**2)
  130. if x > 0:
  131. return math.exp(-1.5 * math.log(x) - (x - mu) ** 2 / (2 * x * mu**2) - lfm)
  132. return 0.0
  133. def powerlaw_pdf(x, a):
  134. if x > 0:
  135. return x ** (a - 1)
  136. return 0.0
  137. # Define a dictionary: for a given distribution (keys), another dictionary
  138. # (values) specifies the parameters for NumericalInversePolynomial (PINV).
  139. # The keys of the latter dictionary are:
  140. # - pdf: the pdf of the distribution (callable). The signature of the pdf
  141. # is float -> float (i.e., the function does not have to be vectorized).
  142. # If possible, functions like log or exp from the module math should be
  143. # preferred over functions from numpy since the PINV setup will be faster
  144. # in that case.
  145. # - check_pinv_params: callable f that returns true if the shape parameters
  146. # (args) are recommended parameters for PINV (i.e., the u-error does
  147. # not exceed the default tolerance)
  148. # - center: scalar if the center does not depend on args, otherwise
  149. # callable that returns the center as a function of the shape parameters
  150. # - rvs_transform: a callable that can be used to transform the rvs that
  151. # are distributed according to the pdf to the target distribution
  152. # (as an example, see the entry for the beta distribution)
  153. # - rvs_transform_inv: the inverse of rvs_transform (it is required
  154. # for the transformed ppf)
  155. # - mirror_uniform: boolean or a callable that returns true or false
  156. # depending on the shape parameters. If True, the ppf is applied
  157. # to 1-u instead of u to generate rvs, where u is a uniform rv.
  158. # While both u and 1-u are uniform, it can be required to use 1-u
  159. # to compute the u-error correctly. This is only relevant for the argus
  160. # distribution.
  161. # The only required keys are "pdf" and "check_pinv_params".
  162. # All other keys are optional.
  163. PINV_CONFIG = {
  164. "alpha": {
  165. "pdf": alpha_pdf,
  166. "check_pinv_params": lambda a: 1.0e-11 <= a < 2.1e5,
  167. "center": lambda a: 0.25 * (math.sqrt(a * a + 8.0) - a),
  168. },
  169. "anglit": {
  170. "pdf": lambda x: math.cos(2 * x) + 1.0e-13,
  171. # +1.e-13 is necessary, otherwise PINV has strange problems as
  172. # f(upper border) is very close to 0
  173. "center": 0,
  174. },
  175. "argus": {
  176. "pdf": argus_pdf,
  177. "center": lambda chi: 0.7 if chi <= 5 else 0.5,
  178. "check_pinv_params": lambda chi: 1e-20 < chi < 901,
  179. "rvs_transform": argus_gamma_trf,
  180. "rvs_transform_inv": argus_gamma_inv_trf,
  181. "mirror_uniform": lambda chi: chi > 5,
  182. },
  183. "beta": {
  184. "pdf": betaprime_pdf,
  185. "center": lambda a, b: max(0.1, (a - 1) / (b + 1)),
  186. "check_pinv_params": beta_valid_params,
  187. "rvs_transform": lambda x, *args: x / (1 + x),
  188. "rvs_transform_inv": lambda x, *args: x / (1 - x) if x < 1 else np.inf,
  189. },
  190. "betaprime": {
  191. "pdf": betaprime_pdf,
  192. "center": lambda a, b: max(0.1, (a - 1) / (b + 1)),
  193. "check_pinv_params": beta_valid_params,
  194. },
  195. "bradford": {
  196. "pdf": bradford_pdf,
  197. "check_pinv_params": lambda a: 1.0e-6 <= a <= 1e9,
  198. "center": 0.5,
  199. },
  200. "burr": {
  201. "pdf": burr_pdf,
  202. "center": lambda a, b: (2 ** (1 / b) - 1) ** (-1 / a),
  203. "check_pinv_params": lambda a, b: (min(a, b) >= 0.3) and (max(a, b) <= 50),
  204. },
  205. "burr12": {
  206. "pdf": burr12_pdf,
  207. "center": lambda a, b: (2 ** (1 / b) - 1) ** (1 / a),
  208. "check_pinv_params": lambda a, b: (min(a, b) >= 0.2) and (max(a, b) <= 50),
  209. },
  210. "cauchy": {
  211. "pdf": lambda x: 1 / (1 + (x * x)),
  212. "center": 0,
  213. },
  214. "chi": {
  215. "pdf": chi_pdf,
  216. "check_pinv_params": lambda df: 0.05 <= df <= 1.0e6,
  217. "center": lambda a: math.sqrt(a),
  218. },
  219. "chi2": {
  220. "pdf": chi2_pdf,
  221. "check_pinv_params": lambda df: 0.07 <= df <= 1e6,
  222. "center": lambda a: a,
  223. },
  224. "cosine": {
  225. "pdf": lambda x: 1 + math.cos(x),
  226. "center": 0,
  227. },
  228. "crystalball": {
  229. "pdf": crystalball_pdf,
  230. "check_pinv_params": lambda b, m: (0.01 <= b <= 5.5)
  231. and (1.1 <= m <= 75.1),
  232. "center": 0.0,
  233. },
  234. "expon": {
  235. "pdf": lambda x: math.exp(-x),
  236. "center": 1.0,
  237. },
  238. "gamma": {
  239. "pdf": gamma_pdf,
  240. "check_pinv_params": lambda a: 0.04 <= a <= 1e6,
  241. "center": lambda a: a,
  242. },
  243. "gennorm": {
  244. "pdf": lambda x, b: math.exp(-abs(x) ** b),
  245. "check_pinv_params": lambda b: 0.081 <= b <= 45.0,
  246. "center": 0.0,
  247. },
  248. "geninvgauss": {
  249. "pdf": geninvgauss_pdf,
  250. "check_pinv_params": lambda p, b: (abs(p) <= 1200.0)
  251. and (1.0e-10 <= b <= 1200.0),
  252. "center": geninvgauss_mode,
  253. },
  254. "gumbel_l": {
  255. "pdf": lambda x: math.exp(x - math.exp(x)),
  256. "center": -0.6,
  257. },
  258. "gumbel_r": {
  259. "pdf": lambda x: math.exp(-x - math.exp(-x)),
  260. "center": 0.6,
  261. },
  262. "hypsecant": {
  263. "pdf": lambda x: 1.0 / (math.exp(x) + math.exp(-x)),
  264. "center": 0.0,
  265. },
  266. "invgamma": {
  267. "pdf": invgamma_pdf,
  268. "check_pinv_params": lambda a: 0.04 <= a <= 1e6,
  269. "center": lambda a: 1 / a,
  270. },
  271. "invgauss": {
  272. "pdf": invgauss_pdf,
  273. "check_pinv_params": lambda mu: 1.0e-10 <= mu <= 1.0e9,
  274. "center": invgauss_mode,
  275. },
  276. "invweibull": {
  277. "pdf": invweibull_pdf,
  278. "check_pinv_params": lambda a: 0.12 <= a <= 512,
  279. "center": 1.0,
  280. },
  281. "laplace": {
  282. "pdf": lambda x: math.exp(-abs(x)),
  283. "center": 0.0,
  284. },
  285. "logistic": {
  286. "pdf": lambda x: math.exp(-x) / (1 + math.exp(-x)) ** 2,
  287. "center": 0.0,
  288. },
  289. "maxwell": {
  290. "pdf": lambda x: x * x * math.exp(-0.5 * x * x),
  291. "center": 1.41421,
  292. },
  293. "moyal": {
  294. "pdf": lambda x: math.exp(-(x + math.exp(-x)) / 2),
  295. "center": 1.2,
  296. },
  297. "norm": {
  298. "pdf": lambda x: math.exp(-x * x / 2),
  299. "center": 0.0,
  300. },
  301. "pareto": {
  302. "pdf": lambda x, b: x ** -(b + 1),
  303. "center": lambda b: b / (b - 1) if b > 2 else 1.5,
  304. "check_pinv_params": lambda b: 0.08 <= b <= 400000,
  305. },
  306. "powerlaw": {
  307. "pdf": powerlaw_pdf,
  308. "center": 1.0,
  309. "check_pinv_params": lambda a: 0.06 <= a <= 1.0e5,
  310. },
  311. "t": {
  312. "pdf": lambda x, df: (1 + x * x / df) ** (-0.5 * (df + 1)),
  313. "check_pinv_params": lambda a: 0.07 <= a <= 1e6,
  314. "center": 0.0,
  315. },
  316. "rayleigh": {
  317. "pdf": lambda x: x * math.exp(-0.5 * (x * x)),
  318. "center": 1.0,
  319. },
  320. "semicircular": {
  321. "pdf": lambda x: math.sqrt(1.0 - (x * x)),
  322. "center": 0,
  323. },
  324. "wald": {
  325. "pdf": wald_pdf,
  326. "center": 1.0,
  327. },
  328. "weibull_max": {
  329. "pdf": weibull_max_pdf,
  330. "check_pinv_params": lambda a: 0.25 <= a <= 512,
  331. "center": -1.0,
  332. },
  333. "weibull_min": {
  334. "pdf": weibull_min_pdf,
  335. "check_pinv_params": lambda a: 0.25 <= a <= 512,
  336. "center": 1.0,
  337. },
  338. }
  339. def _validate_qmc_input(qmc_engine, d, seed):
  340. # Input validation for `qmc_engine` and `d`
  341. # Error messages for invalid `d` are raised by QMCEngine
  342. # we could probably use a stats.qmc.check_qrandom_state
  343. if isinstance(qmc_engine, QMCEngine):
  344. if d is not None and qmc_engine.d != d:
  345. message = "`d` must be consistent with dimension of `qmc_engine`."
  346. raise ValueError(message)
  347. d = qmc_engine.d if d is None else d
  348. elif qmc_engine is None:
  349. d = 1 if d is None else d
  350. qmc_engine = Halton(d, seed=seed)
  351. else:
  352. message = (
  353. "`qmc_engine` must be an instance of "
  354. "`scipy.stats.qmc.QMCEngine` or `None`."
  355. )
  356. raise ValueError(message)
  357. return qmc_engine, d
  358. class CustomDistPINV:
  359. def __init__(self, pdf, args):
  360. self._pdf = lambda x: pdf(x, *args)
  361. def pdf(self, x):
  362. return self._pdf(x)
  363. class FastGeneratorInversion:
  364. """
  365. Fast sampling by numerical inversion of the CDF for a large class of
  366. continuous distributions in `scipy.stats`.
  367. Parameters
  368. ----------
  369. dist : rv_frozen object
  370. Frozen distribution object from `scipy.stats`. The list of supported
  371. distributions can be found in the Notes section. The shape parameters,
  372. `loc` and `scale` used to create the distributions must be scalars.
  373. For example, for the Gamma distribution with shape parameter `p`,
  374. `p` has to be a float, and for the beta distribution with shape
  375. parameters (a, b), both a and b have to be floats.
  376. domain : tuple of floats, optional
  377. If one wishes to sample from a truncated/conditional distribution,
  378. the domain has to be specified.
  379. The default is None. In that case, the random variates are not
  380. truncated, and the domain is inferred from the support of the
  381. distribution.
  382. ignore_shape_range : boolean, optional.
  383. If False, shape parameters that are outside of the valid range
  384. of values to ensure that the numerical accuracy (see Notes) is
  385. high, raise a ValueError. If True, any shape parameters that are valid
  386. for the distribution are accepted. This can be useful for testing.
  387. The default is False.
  388. random_state : {None, int, `numpy.random.Generator`,
  389. `numpy.random.RandomState`}, optional
  390. A NumPy random number generator or seed for the underlying NumPy
  391. random number generator used to generate the stream of uniform
  392. random numbers.
  393. If `random_state` is None, it uses ``self.random_state``.
  394. If `random_state` is an int,
  395. ``np.random.default_rng(random_state)`` is used.
  396. If `random_state` is already a ``Generator`` or ``RandomState``
  397. instance then that instance is used.
  398. Attributes
  399. ----------
  400. loc : float
  401. The location parameter.
  402. random_state : {`numpy.random.Generator`, `numpy.random.RandomState`}
  403. The random state used in relevant methods like `rvs` (unless
  404. another `random_state` is passed as an argument to these methods).
  405. scale : float
  406. The scale parameter.
  407. Methods
  408. -------
  409. cdf
  410. evaluate_error
  411. ppf
  412. qrvs
  413. rvs
  414. support
  415. Notes
  416. -----
  417. The class creates an object for continuous distributions specified
  418. by `dist`. The method `rvs` uses a generator from
  419. `scipy.stats.sampling` that is created when the object is instantiated.
  420. In addition, the methods `qrvs` and `ppf` are added.
  421. `qrvs` generate samples based on quasi-random numbers from
  422. `scipy.stats.qmc`. `ppf` is the PPF based on the
  423. numerical inversion method in [1]_ (`NumericalInversePolynomial`) that is
  424. used to generate random variates.
  425. Supported distributions (`distname`) are:
  426. ``alpha``, ``anglit``, ``argus``, ``beta``, ``betaprime``, ``bradford``,
  427. ``burr``, ``burr12``, ``cauchy``, ``chi``, ``chi2``, ``cosine``,
  428. ``crystalball``, ``expon``, ``gamma``, ``gennorm``, ``geninvgauss``,
  429. ``gumbel_l``, ``gumbel_r``, ``hypsecant``, ``invgamma``, ``invgauss``,
  430. ``invweibull``, ``laplace``, ``logistic``, ``maxwell``, ``moyal``,
  431. ``norm``, ``pareto``, ``powerlaw``, ``t``, ``rayleigh``, ``semicircular``,
  432. ``wald``, ``weibull_max``, ``weibull_min``.
  433. `rvs` relies on the accuracy of the numerical inversion. If very extreme
  434. shape parameters are used, the numerical inversion might not work. However,
  435. for all implemented distributions, the admissible shape parameters have
  436. been tested, and an error will be raised if the user supplies values
  437. outside of the allowed range. The u-error should not exceed 1e-10 for all
  438. valid parameters. Note that warnings might be raised even if parameters
  439. are within the valid range when the object is instantiated.
  440. To check numerical accuracy, the method `evaluate_error` can be used.
  441. Note that all implemented distributions are also part of `scipy.stats`, and
  442. the object created by `FastGeneratorInversion` relies on methods like
  443. `ppf`, `cdf` and `pdf` from `rv_frozen`. The main benefit of using this
  444. class can be summarized as follows: Once the generator to sample random
  445. variates is created in the setup step, sampling and evaluation of
  446. the PPF using `ppf` are very fast,
  447. and performance is essentially independent of the distribution. Therefore,
  448. a substantial speed-up can be achieved for many distributions if large
  449. numbers of random variates are required. It is important to know that this
  450. fast sampling is achieved by inversion of the CDF. Thus, one uniform
  451. random variate is transformed into a non-uniform variate, which is an
  452. advantage for several simulation methods, e.g., when
  453. the variance reduction methods of common random variates or
  454. antithetic variates are be used ([2]_).
  455. In addition, inversion makes it possible to
  456. - to use a QMC generator from `scipy.stats.qmc` (method `qrvs`),
  457. - to generate random variates truncated to an interval. For example, if
  458. one aims to sample standard normal random variates from
  459. the interval (2, 4), this can be easily achieved by using the parameter
  460. `domain`.
  461. The location and scale that are initially defined by `dist`
  462. can be reset without having to rerun the setup
  463. step to create the generator that is used for sampling. The relation
  464. of the distribution `Y` with `loc` and `scale` to the standard
  465. distribution `X` (i.e., ``loc=0`` and ``scale=1``) is given by
  466. ``Y = loc + scale * X``.
  467. References
  468. ----------
  469. .. [1] Derflinger, Gerhard, Wolfgang Hörmann, and Josef Leydold.
  470. "Random variate generation by numerical inversion when only the
  471. density is known." ACM Transactions on Modeling and Computer
  472. Simulation (TOMACS) 20.4 (2010): 1-25.
  473. .. [2] Hörmann, Wolfgang, Josef Leydold and Gerhard Derflinger.
  474. "Automatic nonuniform random number generation."
  475. Springer, 2004.
  476. Examples
  477. --------
  478. >>> import numpy as np
  479. >>> from scipy import stats
  480. >>> from scipy.stats.sampling import FastGeneratorInversion
  481. Let's start with a simple example to illustrate the main features:
  482. >>> gamma_frozen = stats.gamma(1.5)
  483. >>> gamma_dist = FastGeneratorInversion(gamma_frozen)
  484. >>> r = gamma_dist.rvs(size=1000)
  485. The mean should be approximately equal to the shape parameter 1.5:
  486. >>> r.mean()
  487. 1.52423591130436 # may vary
  488. Similarly, we can draw a sample based on quasi-random numbers:
  489. >>> r = gamma_dist.qrvs(size=1000)
  490. >>> r.mean()
  491. 1.4996639255942914 # may vary
  492. Compare the PPF against approximation `ppf`.
  493. >>> q = [0.001, 0.2, 0.5, 0.8, 0.999]
  494. >>> np.max(np.abs(gamma_frozen.ppf(q) - gamma_dist.ppf(q)))
  495. 4.313394796895409e-08
  496. To confirm that the numerical inversion is accurate, we evaluate the
  497. approximation error (u-error), which should be below 1e-10 (for more
  498. details, refer to the documentation of `evaluate_error`):
  499. >>> gamma_dist.evaluate_error()
  500. (7.446320551265581e-11, nan) # may vary
  501. Note that the location and scale can be changed without instantiating a
  502. new generator:
  503. >>> gamma_dist.loc = 2
  504. >>> gamma_dist.scale = 3
  505. >>> r = gamma_dist.rvs(size=1000)
  506. The mean should be approximately 2 + 3*1.5 = 6.5.
  507. >>> r.mean()
  508. 6.399549295242894 # may vary
  509. Let us also illustrate how truncation can be applied:
  510. >>> trunc_norm = FastGeneratorInversion(stats.norm(), domain=(3, 4))
  511. >>> r = trunc_norm.rvs(size=1000)
  512. >>> 3 < r.min() < r.max() < 4
  513. True
  514. Check the mean:
  515. >>> r.mean()
  516. 3.250433367078603 # may vary
  517. >>> stats.norm.expect(lb=3, ub=4, conditional=True)
  518. 3.260454285589997
  519. In this particular, case, `scipy.stats.truncnorm` could also be used to
  520. generate truncated normal random variates.
  521. """
  522. def __init__(
  523. self,
  524. dist,
  525. *,
  526. domain=None,
  527. ignore_shape_range=False,
  528. random_state=None,
  529. ):
  530. if isinstance(dist, stats.distributions.rv_frozen):
  531. distname = dist.dist.name
  532. if distname not in PINV_CONFIG.keys():
  533. raise ValueError(
  534. f"Distribution '{distname}' is not supported."
  535. f"It must be one of {list(PINV_CONFIG.keys())}"
  536. )
  537. else:
  538. raise ValueError("`dist` must be a frozen distribution object")
  539. loc = dist.kwds.get("loc", 0)
  540. scale = dist.kwds.get("scale", 1)
  541. args = dist.args
  542. if not np.isscalar(loc):
  543. raise ValueError("loc must be scalar.")
  544. if not np.isscalar(scale):
  545. raise ValueError("scale must be scalar.")
  546. self._frozendist = getattr(stats, distname)(
  547. *args,
  548. loc=loc,
  549. scale=scale,
  550. )
  551. self._distname = distname
  552. nargs = np.broadcast_arrays(args)[0].size
  553. nargs_expected = self._frozendist.dist.numargs
  554. if nargs != nargs_expected:
  555. raise ValueError(
  556. f"Each of the {nargs_expected} shape parameters must be a "
  557. f"scalar, but {nargs} values are provided."
  558. )
  559. self.random_state = random_state
  560. if domain is None:
  561. self._domain = self._frozendist.support()
  562. self._p_lower = 0.0
  563. self._p_domain = 1.0
  564. else:
  565. self._domain = domain
  566. self._p_lower = self._frozendist.cdf(self._domain[0])
  567. _p_domain = self._frozendist.cdf(self._domain[1]) - self._p_lower
  568. self._p_domain = _p_domain
  569. self._set_domain_adj()
  570. self._ignore_shape_range = ignore_shape_range
  571. # the domain to be passed to NumericalInversePolynomial
  572. # define a separate variable since in case of a transformation,
  573. # domain_pinv will not be the same as self._domain
  574. self._domain_pinv = self._domain
  575. # get information about the distribution from the config to set up
  576. # the generator
  577. dist = self._process_config(distname, args)
  578. if self._rvs_transform_inv is not None:
  579. d0 = self._rvs_transform_inv(self._domain[0], *args)
  580. d1 = self._rvs_transform_inv(self._domain[1], *args)
  581. if d0 > d1:
  582. # swap values if transformation if decreasing
  583. d0, d1 = d1, d0
  584. # only update _domain_pinv and not _domain
  585. # _domain refers to the original distribution, _domain_pinv
  586. # to the transformed distribution
  587. self._domain_pinv = d0, d1
  588. # self._center has been set by the call self._process_config
  589. # check if self._center is inside the transformed domain
  590. # _domain_pinv, otherwise move it to the endpoint that is closer
  591. if self._center is not None:
  592. if self._center < self._domain_pinv[0]:
  593. self._center = self._domain_pinv[0]
  594. elif self._center > self._domain_pinv[1]:
  595. self._center = self._domain_pinv[1]
  596. self._rng = NumericalInversePolynomial(
  597. dist,
  598. random_state=self.random_state,
  599. domain=self._domain_pinv,
  600. center=self._center,
  601. )
  602. @property
  603. def random_state(self):
  604. return self._random_state
  605. @random_state.setter
  606. def random_state(self, random_state):
  607. self._random_state = check_random_state_qmc(random_state)
  608. @property
  609. def loc(self):
  610. return self._frozendist.kwds.get("loc", 0)
  611. @loc.setter
  612. def loc(self, loc):
  613. if not np.isscalar(loc):
  614. raise ValueError("loc must be scalar.")
  615. self._frozendist.kwds["loc"] = loc
  616. # update the adjusted domain that depends on loc and scale
  617. self._set_domain_adj()
  618. @property
  619. def scale(self):
  620. return self._frozendist.kwds.get("scale", 0)
  621. @scale.setter
  622. def scale(self, scale):
  623. if not np.isscalar(scale):
  624. raise ValueError("scale must be scalar.")
  625. self._frozendist.kwds["scale"] = scale
  626. # update the adjusted domain that depends on loc and scale
  627. self._set_domain_adj()
  628. def _set_domain_adj(self):
  629. """ Adjust the domain based on loc and scale. """
  630. loc = self.loc
  631. scale = self.scale
  632. lb = self._domain[0] * scale + loc
  633. ub = self._domain[1] * scale + loc
  634. self._domain_adj = (lb, ub)
  635. def _process_config(self, distname, args):
  636. cfg = PINV_CONFIG[distname]
  637. if "check_pinv_params" in cfg:
  638. if not self._ignore_shape_range:
  639. if not cfg["check_pinv_params"](*args):
  640. msg = ("No generator is defined for the shape parameters "
  641. f"{args}. Use ignore_shape_range to proceed "
  642. "with the selected values.")
  643. raise ValueError(msg)
  644. if "center" in cfg.keys():
  645. if not np.isscalar(cfg["center"]):
  646. self._center = cfg["center"](*args)
  647. else:
  648. self._center = cfg["center"]
  649. else:
  650. self._center = None
  651. self._rvs_transform = cfg.get("rvs_transform", None)
  652. self._rvs_transform_inv = cfg.get("rvs_transform_inv", None)
  653. _mirror_uniform = cfg.get("mirror_uniform", None)
  654. if _mirror_uniform is None:
  655. self._mirror_uniform = False
  656. else:
  657. self._mirror_uniform = _mirror_uniform(*args)
  658. return CustomDistPINV(cfg["pdf"], args)
  659. def rvs(self, size=None):
  660. """
  661. Sample from the distribution by inversion.
  662. Parameters
  663. ----------
  664. size : int or tuple, optional
  665. The shape of samples. Default is ``None`` in which case a scalar
  666. sample is returned.
  667. Returns
  668. -------
  669. rvs : array_like
  670. A NumPy array of random variates.
  671. Notes
  672. -----
  673. Random variates are generated by numerical inversion of the CDF, i.e.,
  674. `ppf` computed by `NumericalInversePolynomial` when the class
  675. is instantiated. Note that the
  676. default ``rvs`` method of the rv_continuous class is
  677. overwritten. Hence, a different stream of random numbers is generated
  678. even if the same seed is used.
  679. """
  680. # note: we cannot use self._rng.rvs directly in case
  681. # self._mirror_uniform is true
  682. u = self.random_state.uniform(size=size)
  683. if self._mirror_uniform:
  684. u = 1 - u
  685. r = self._rng.ppf(u)
  686. if self._rvs_transform is not None:
  687. r = self._rvs_transform(r, *self._frozendist.args)
  688. return self.loc + self.scale * r
  689. def ppf(self, q):
  690. """
  691. Very fast PPF (inverse CDF) of the distribution which
  692. is a very close approximation of the exact PPF values.
  693. Parameters
  694. ----------
  695. u : array_like
  696. Array with probabilities.
  697. Returns
  698. -------
  699. ppf : array_like
  700. Quantiles corresponding to the values in `u`.
  701. Notes
  702. -----
  703. The evaluation of the PPF is very fast but it may have a large
  704. relative error in the far tails. The numerical precision of the PPF
  705. is controlled by the u-error, that is,
  706. ``max |u - CDF(PPF(u))|`` where the max is taken over points in
  707. the interval [0,1], see `evaluate_error`.
  708. Note that this PPF is designed to generate random samples.
  709. """
  710. q = np.asarray(q)
  711. if self._mirror_uniform:
  712. x = self._rng.ppf(1 - q)
  713. else:
  714. x = self._rng.ppf(q)
  715. if self._rvs_transform is not None:
  716. x = self._rvs_transform(x, *self._frozendist.args)
  717. return self.scale * x + self.loc
  718. def qrvs(self, size=None, d=None, qmc_engine=None):
  719. """
  720. Quasi-random variates of the given distribution.
  721. The `qmc_engine` is used to draw uniform quasi-random variates, and
  722. these are converted to quasi-random variates of the given distribution
  723. using inverse transform sampling.
  724. Parameters
  725. ----------
  726. size : int, tuple of ints, or None; optional
  727. Defines shape of random variates array. Default is ``None``.
  728. d : int or None, optional
  729. Defines dimension of uniform quasi-random variates to be
  730. transformed. Default is ``None``.
  731. qmc_engine : scipy.stats.qmc.QMCEngine(d=1), optional
  732. Defines the object to use for drawing
  733. quasi-random variates. Default is ``None``, which uses
  734. `scipy.stats.qmc.Halton(1)`.
  735. Returns
  736. -------
  737. rvs : ndarray or scalar
  738. Quasi-random variates. See Notes for shape information.
  739. Notes
  740. -----
  741. The shape of the output array depends on `size`, `d`, and `qmc_engine`.
  742. The intent is for the interface to be natural, but the detailed rules
  743. to achieve this are complicated.
  744. - If `qmc_engine` is ``None``, a `scipy.stats.qmc.Halton` instance is
  745. created with dimension `d`. If `d` is not provided, ``d=1``.
  746. - If `qmc_engine` is not ``None`` and `d` is ``None``, `d` is
  747. determined from the dimension of the `qmc_engine`.
  748. - If `qmc_engine` is not ``None`` and `d` is not ``None`` but the
  749. dimensions are inconsistent, a ``ValueError`` is raised.
  750. - After `d` is determined according to the rules above, the output
  751. shape is ``tuple_shape + d_shape``, where:
  752. - ``tuple_shape = tuple()`` if `size` is ``None``,
  753. - ``tuple_shape = (size,)`` if `size` is an ``int``,
  754. - ``tuple_shape = size`` if `size` is a sequence,
  755. - ``d_shape = tuple()`` if `d` is ``None`` or `d` is 1, and
  756. - ``d_shape = (d,)`` if `d` is greater than 1.
  757. The elements of the returned array are part of a low-discrepancy
  758. sequence. If `d` is 1, this means that none of the samples are truly
  759. independent. If `d` > 1, each slice ``rvs[..., i]`` will be of a
  760. quasi-independent sequence; see `scipy.stats.qmc.QMCEngine` for
  761. details. Note that when `d` > 1, the samples returned are still those
  762. of the provided univariate distribution, not a multivariate
  763. generalization of that distribution.
  764. """
  765. qmc_engine, d = _validate_qmc_input(qmc_engine, d, self.random_state)
  766. # mainly copied from unuran_wrapper.pyx.templ
  767. # `rvs` is flexible about whether `size` is an int or tuple, so this
  768. # should be, too.
  769. try:
  770. if size is None:
  771. tuple_size = (1,)
  772. else:
  773. tuple_size = tuple(size)
  774. except TypeError:
  775. tuple_size = (size,)
  776. # we do not use rng.qrvs directly since we need to be
  777. # able to apply the ppf to 1 - u
  778. N = 1 if size is None else np.prod(size)
  779. u = qmc_engine.random(N)
  780. if self._mirror_uniform:
  781. u = 1 - u
  782. qrvs = self._ppf(u)
  783. if self._rvs_transform is not None:
  784. qrvs = self._rvs_transform(qrvs, *self._frozendist.args)
  785. if size is None:
  786. qrvs = qrvs.squeeze()[()]
  787. else:
  788. if d == 1:
  789. qrvs = qrvs.reshape(tuple_size)
  790. else:
  791. qrvs = qrvs.reshape(tuple_size + (d,))
  792. return self.loc + self.scale * qrvs
  793. def evaluate_error(self, size=100000, random_state=None, x_error=False):
  794. """
  795. Evaluate the numerical accuracy of the inversion (u- and x-error).
  796. Parameters
  797. ----------
  798. size : int, optional
  799. The number of random points over which the error is estimated.
  800. Default is ``100000``.
  801. random_state : {None, int, `numpy.random.Generator`,
  802. `numpy.random.RandomState`}, optional
  803. A NumPy random number generator or seed for the underlying NumPy
  804. random number generator used to generate the stream of uniform
  805. random numbers.
  806. If `random_state` is None, use ``self.random_state``.
  807. If `random_state` is an int,
  808. ``np.random.default_rng(random_state)`` is used.
  809. If `random_state` is already a ``Generator`` or ``RandomState``
  810. instance then that instance is used.
  811. Returns
  812. -------
  813. u_error, x_error : tuple of floats
  814. A NumPy array of random variates.
  815. Notes
  816. -----
  817. The numerical precision of the inverse CDF `ppf` is controlled by
  818. the u-error. It is computed as follows:
  819. ``max |u - CDF(PPF(u))|`` where the max is taken `size` random
  820. points in the interval [0,1]. `random_state` determines the random
  821. sample. Note that if `ppf` was exact, the u-error would be zero.
  822. The x-error measures the direct distance between the exact PPF
  823. and `ppf`. If ``x_error`` is set to ``True`, it is
  824. computed as the maximum of the minimum of the relative and absolute
  825. x-error:
  826. ``max(min(x_error_abs[i], x_error_rel[i]))`` where
  827. ``x_error_abs[i] = |PPF(u[i]) - PPF_fast(u[i])|``,
  828. ``x_error_rel[i] = max |(PPF(u[i]) - PPF_fast(u[i])) / PPF(u[i])|``.
  829. Note that it is important to consider the relative x-error in the case
  830. that ``PPF(u)`` is close to zero or very large.
  831. By default, only the u-error is evaluated and the x-error is set to
  832. ``np.nan``. Note that the evaluation of the x-error will be very slow
  833. if the implementation of the PPF is slow.
  834. Further information about these error measures can be found in [1]_.
  835. References
  836. ----------
  837. .. [1] Derflinger, Gerhard, Wolfgang Hörmann, and Josef Leydold.
  838. "Random variate generation by numerical inversion when only the
  839. density is known." ACM Transactions on Modeling and Computer
  840. Simulation (TOMACS) 20.4 (2010): 1-25.
  841. Examples
  842. --------
  843. >>> import numpy as np
  844. >>> from scipy import stats
  845. >>> from scipy.stats.sampling import FastGeneratorInversion
  846. Create an object for the normal distribution:
  847. >>> d_norm_frozen = stats.norm()
  848. >>> d_norm = FastGeneratorInversion(d_norm_frozen)
  849. To confirm that the numerical inversion is accurate, we evaluate the
  850. approximation error (u-error and x-error).
  851. >>> u_error, x_error = d_norm.evaluate_error(x_error=True)
  852. The u-error should be below 1e-10:
  853. >>> u_error
  854. 8.785783212061915e-11 # may vary
  855. Compare the PPF against approximation `ppf`:
  856. >>> q = [0.001, 0.2, 0.4, 0.6, 0.8, 0.999]
  857. >>> diff = np.abs(d_norm_frozen.ppf(q) - d_norm.ppf(q))
  858. >>> x_error_abs = np.max(diff)
  859. >>> x_error_abs
  860. 1.2937954707581412e-08
  861. This is the absolute x-error evaluated at the points q. The relative
  862. error is given by
  863. >>> x_error_rel = np.max(diff / np.abs(d_norm_frozen.ppf(q)))
  864. >>> x_error_rel
  865. 4.186725600453555e-09
  866. The x_error computed above is derived in a very similar way over a
  867. much larger set of random values q. At each value q[i], the minimum
  868. of the relative and absolute error is taken. The final value is then
  869. derived as the maximum of these values. In our example, we get the
  870. following value:
  871. >>> x_error
  872. 4.507068014335139e-07 # may vary
  873. """
  874. if not isinstance(size, numbers.Integral | np.integer):
  875. raise ValueError("size must be an integer.")
  876. # urng will be used to draw the samples for testing the error
  877. # it must not interfere with self.random_state. therefore, do not
  878. # call self.rvs, but draw uniform random numbers and apply
  879. # self.ppf (note: like in rvs, consider self._mirror_uniform)
  880. urng = check_random_state_qmc(random_state)
  881. u = urng.uniform(size=size)
  882. if self._mirror_uniform:
  883. u = 1 - u
  884. x = self.ppf(u)
  885. uerr = np.max(np.abs(self._cdf(x) - u))
  886. if not x_error:
  887. return uerr, np.nan
  888. ppf_u = self._ppf(u)
  889. x_error_abs = np.abs(self.ppf(u)-ppf_u)
  890. x_error_rel = x_error_abs / np.abs(ppf_u)
  891. x_error_combined = np.array([x_error_abs, x_error_rel]).min(axis=0)
  892. return uerr, np.max(x_error_combined)
  893. def support(self):
  894. """Support of the distribution.
  895. Returns
  896. -------
  897. a, b : float
  898. end-points of the distribution's support.
  899. Notes
  900. -----
  901. Note that the support of the distribution depends on `loc`,
  902. `scale` and `domain`.
  903. Examples
  904. --------
  905. >>> from scipy import stats
  906. >>> from scipy.stats.sampling import FastGeneratorInversion
  907. Define a truncated normal distribution:
  908. >>> d_norm = FastGeneratorInversion(stats.norm(), domain=(0, 1))
  909. >>> d_norm.support()
  910. (0, 1)
  911. Shift the distribution:
  912. >>> d_norm.loc = 2.5
  913. >>> d_norm.support()
  914. (2.5, 3.5)
  915. """
  916. return self._domain_adj
  917. def _cdf(self, x):
  918. """Cumulative distribution function (CDF)
  919. Parameters
  920. ----------
  921. x : array_like
  922. The values where the CDF is evaluated
  923. Returns
  924. -------
  925. y : ndarray
  926. CDF evaluated at x
  927. """
  928. y = self._frozendist.cdf(x)
  929. if self._p_domain == 1.0:
  930. return y
  931. return np.clip((y - self._p_lower) / self._p_domain, 0, 1)
  932. def _ppf(self, q):
  933. """Percent point function (inverse of `cdf`)
  934. Parameters
  935. ----------
  936. q : array_like
  937. lower tail probability
  938. Returns
  939. -------
  940. x : array_like
  941. quantile corresponding to the lower tail probability q.
  942. """
  943. if self._p_domain == 1.0:
  944. return self._frozendist.ppf(q)
  945. x = self._frozendist.ppf(self._p_domain * np.array(q) + self._p_lower)
  946. return np.clip(x, self._domain_adj[0], self._domain_adj[1])
  947. class RatioUniforms:
  948. """
  949. Generate random samples from a probability density function using the
  950. ratio-of-uniforms method.
  951. Parameters
  952. ----------
  953. pdf : callable
  954. A function with signature `pdf(x)` that is proportional to the
  955. probability density function of the distribution.
  956. umax : float
  957. The upper bound of the bounding rectangle in the u-direction.
  958. vmin : float
  959. The lower bound of the bounding rectangle in the v-direction.
  960. vmax : float
  961. The upper bound of the bounding rectangle in the v-direction.
  962. c : float, optional.
  963. Shift parameter of ratio-of-uniforms method, see Notes. Default is 0.
  964. random_state : {None, int, `numpy.random.Generator`,
  965. `numpy.random.RandomState`}, optional
  966. If `seed` is None (or `np.random`), the `numpy.random.RandomState`
  967. singleton is used.
  968. If `seed` is an int, a new ``RandomState`` instance is used,
  969. seeded with `seed`.
  970. If `seed` is already a ``Generator`` or ``RandomState`` instance then
  971. that instance is used.
  972. Methods
  973. -------
  974. rvs
  975. Notes
  976. -----
  977. Given a univariate probability density function `pdf` and a constant `c`,
  978. define the set ``A = {(u, v) : 0 < u <= sqrt(pdf(v/u + c))}``.
  979. If ``(U, V)`` is a random vector uniformly distributed over ``A``,
  980. then ``V/U + c`` follows a distribution according to `pdf`.
  981. The above result (see [1]_, [2]_) can be used to sample random variables
  982. using only the PDF, i.e. no inversion of the CDF is required. Typical
  983. choices of `c` are zero or the mode of `pdf`. The set ``A`` is a subset of
  984. the rectangle ``R = [0, umax] x [vmin, vmax]`` where
  985. - ``umax = sup sqrt(pdf(x))``
  986. - ``vmin = inf (x - c) sqrt(pdf(x))``
  987. - ``vmax = sup (x - c) sqrt(pdf(x))``
  988. In particular, these values are finite if `pdf` is bounded and
  989. ``x**2 * pdf(x)`` is bounded (i.e. subquadratic tails).
  990. One can generate ``(U, V)`` uniformly on ``R`` and return
  991. ``V/U + c`` if ``(U, V)`` are also in ``A`` which can be directly
  992. verified.
  993. The algorithm is not changed if one replaces `pdf` by k * `pdf` for any
  994. constant k > 0. Thus, it is often convenient to work with a function
  995. that is proportional to the probability density function by dropping
  996. unnecessary normalization factors.
  997. Intuitively, the method works well if ``A`` fills up most of the
  998. enclosing rectangle such that the probability is high that ``(U, V)``
  999. lies in ``A`` whenever it lies in ``R`` as the number of required
  1000. iterations becomes too large otherwise. To be more precise, note that
  1001. the expected number of iterations to draw ``(U, V)`` uniformly
  1002. distributed on ``R`` such that ``(U, V)`` is also in ``A`` is given by
  1003. the ratio ``area(R) / area(A) = 2 * umax * (vmax - vmin) / area(pdf)``,
  1004. where `area(pdf)` is the integral of `pdf` (which is equal to one if the
  1005. probability density function is used but can take on other values if a
  1006. function proportional to the density is used). The equality holds since
  1007. the area of ``A`` is equal to ``0.5 * area(pdf)`` (Theorem 7.1 in [1]_).
  1008. If the sampling fails to generate a single random variate after 50000
  1009. iterations (i.e. not a single draw is in ``A``), an exception is raised.
  1010. If the bounding rectangle is not correctly specified (i.e. if it does not
  1011. contain ``A``), the algorithm samples from a distribution different from
  1012. the one given by `pdf`. It is therefore recommended to perform a
  1013. test such as `~scipy.stats.kstest` as a check.
  1014. References
  1015. ----------
  1016. .. [1] L. Devroye, "Non-Uniform Random Variate Generation",
  1017. Springer-Verlag, 1986.
  1018. .. [2] W. Hoermann and J. Leydold, "Generating generalized inverse Gaussian
  1019. random variates", Statistics and Computing, 24(4), p. 547--557, 2014.
  1020. .. [3] A.J. Kinderman and J.F. Monahan, "Computer Generation of Random
  1021. Variables Using the Ratio of Uniform Deviates",
  1022. ACM Transactions on Mathematical Software, 3(3), p. 257--260, 1977.
  1023. Examples
  1024. --------
  1025. >>> import numpy as np
  1026. >>> from scipy import stats
  1027. >>> from scipy.stats.sampling import RatioUniforms
  1028. >>> rng = np.random.default_rng()
  1029. Simulate normally distributed random variables. It is easy to compute the
  1030. bounding rectangle explicitly in that case. For simplicity, we drop the
  1031. normalization factor of the density.
  1032. >>> f = lambda x: np.exp(-x**2 / 2)
  1033. >>> v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
  1034. >>> umax = np.sqrt(f(0))
  1035. >>> gen = RatioUniforms(f, umax=umax, vmin=-v, vmax=v, random_state=rng)
  1036. >>> r = gen.rvs(size=2500)
  1037. The K-S test confirms that the random variates are indeed normally
  1038. distributed (normality is not rejected at 5% significance level):
  1039. >>> stats.kstest(r, 'norm')[1]
  1040. 0.250634764150542
  1041. The exponential distribution provides another example where the bounding
  1042. rectangle can be determined explicitly.
  1043. >>> gen = RatioUniforms(lambda x: np.exp(-x), umax=1, vmin=0,
  1044. ... vmax=2*np.exp(-1), random_state=rng)
  1045. >>> r = gen.rvs(1000)
  1046. >>> stats.kstest(r, 'expon')[1]
  1047. 0.21121052054580314
  1048. """
  1049. def __init__(self, pdf, *, umax, vmin, vmax, c=0, random_state=None):
  1050. if vmin >= vmax:
  1051. raise ValueError("vmin must be smaller than vmax.")
  1052. if umax <= 0:
  1053. raise ValueError("umax must be positive.")
  1054. self._pdf = pdf
  1055. self._umax = umax
  1056. self._vmin = vmin
  1057. self._vmax = vmax
  1058. self._c = c
  1059. self._rng = check_random_state(random_state)
  1060. def rvs(self, size=1):
  1061. """Sampling of random variates
  1062. Parameters
  1063. ----------
  1064. size : int or tuple of ints, optional
  1065. Number of random variates to be generated (default is 1).
  1066. Returns
  1067. -------
  1068. rvs : ndarray
  1069. The random variates distributed according to the probability
  1070. distribution defined by the pdf.
  1071. """
  1072. size1d = tuple(np.atleast_1d(size))
  1073. N = np.prod(size1d) # number of rvs needed, reshape upon return
  1074. # start sampling using ratio of uniforms method
  1075. x = np.zeros(N)
  1076. simulated, i = 0, 1
  1077. # loop until N rvs have been generated: expected runtime is finite.
  1078. # to avoid infinite loop, raise exception if not a single rv has been
  1079. # generated after 50000 tries. even if the expected number of iterations
  1080. # is 1000, the probability of this event is (1-1/1000)**50000
  1081. # which is of order 10e-22
  1082. while simulated < N:
  1083. k = N - simulated
  1084. # simulate uniform rvs on [0, umax] and [vmin, vmax]
  1085. u1 = self._umax * self._rng.uniform(size=k)
  1086. v1 = self._rng.uniform(self._vmin, self._vmax, size=k)
  1087. # apply rejection method
  1088. rvs = v1 / u1 + self._c
  1089. accept = (u1**2 <= self._pdf(rvs))
  1090. num_accept = np.sum(accept)
  1091. if num_accept > 0:
  1092. x[simulated:(simulated + num_accept)] = rvs[accept]
  1093. simulated += num_accept
  1094. if (simulated == 0) and (i*N >= 50000):
  1095. msg = (
  1096. f"Not a single random variate could be generated in {i*N} "
  1097. "attempts. The ratio of uniforms method does not appear "
  1098. "to work for the provided parameters. Please check the "
  1099. "pdf and the bounds."
  1100. )
  1101. raise RuntimeError(msg)
  1102. i += 1
  1103. return np.reshape(x, size1d)