Add loan-advisor-agent (part 7)
Browse filesFiles changed (13)
- loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_odds_ratio.pyAdded+148
- loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_qmc.pyAdded+1534
- loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_quantile.pyAdded+412
- loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_rank.pyAdded+348
- loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_relative_risk.pyAdded+95
- loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_resampling.pyAdded+2046
- loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_sampling.pyAdded+1448
- loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_sensitivity_analysis.pyAdded+310
- loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_stats.pyAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_survival.pyAdded+466
- loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_tukeylambda_stats.pyAdded+85
- loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_variation.pyAdded+214
- loan-advisor-agent/.venv/Lib/site-packages/scipy/version.pyAdded+12
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148import pytest
import numpy as np
from numpy.testing import assert_equal, assert_allclose
from .._discrete_distns import nchypergeom_fisher, hypergeom
from scipy.stats._odds_ratio import odds_ratio
from .data.fisher_exact_results_from_r import data
class TestOddsRatio:
@pytest.mark.parametrize('parameters, rresult', data)
def test_results_from_r(self, parameters, rresult):
alternative = parameters.alternative.replace('.', '-')
result = odds_ratio(parameters.table)
# The results computed by R are not very accurate.
if result.statistic < 400:
or_rtol = 5e-4
ci_rtol = 2e-2
else:
or_rtol = 5e-2
ci_rtol = 1e-1
assert_allclose(result.statistic,
rresult.conditional_odds_ratio, rtol=or_rtol)
ci = result.confidence_interval(parameters.confidence_level,
alternative)
assert_allclose((ci.low, ci.high), rresult.conditional_odds_ratio_ci,
rtol=ci_rtol)
# Also do a self-check for the conditional odds ratio.
# With the computed conditional odds ratio as the noncentrality
# parameter of the noncentral hypergeometric distribution with
# parameters table.sum(), table[0].sum(), and table[:,0].sum() as
# total, ngood and nsample, respectively, the mean of the distribution
# should equal table[0, 0].
cor = result.statistic
table = np.array(parameters.table)
total = table.sum()
ngood = table[0].sum()
nsample = table[:, 0].sum()
# nchypergeom_fisher does not allow the edge cases where the
# noncentrality parameter is 0 or inf, so handle those values
# separately here.
if cor == 0:
nchg_mean = hypergeom.support(total, ngood, nsample)[0]
elif cor == np.inf:
nchg_mean = hypergeom.support(total, ngood, nsample)[1]
else:
nchg_mean = nchypergeom_fisher.mean(total, ngood, nsample, cor)
assert_allclose(nchg_mean, table[0, 0], rtol=1e-13)
# Check that the confidence interval is correct.
alpha = 1 - parameters.confidence_level
if alternative == 'two-sided':
if ci.low > 0:
sf = nchypergeom_fisher.sf(table[0, 0] - 1,
total, ngood, nsample, ci.low)
assert_allclose(sf, alpha/2, rtol=1e-11)
if np.isfinite(ci.high):
cdf = nchypergeom_fisher.cdf(table[0, 0],
total, ngood, nsample, ci.high)
assert_allclose(cdf, alpha/2, rtol=1e-11)
elif alternative == 'less':
if np.isfinite(ci.high):
cdf = nchypergeom_fisher.cdf(table[0, 0],
total, ngood, nsample, ci.high)
assert_allclose(cdf, alpha, rtol=1e-11)
else:
# alternative == 'greater'
if ci.low > 0:
sf = nchypergeom_fisher.sf(table[0, 0] - 1,
total, ngood, nsample, ci.low)
assert_allclose(sf, alpha, rtol=1e-11)
@pytest.mark.parametrize('table', [
[[0, 0], [5, 10]],
[[5, 10], [0, 0]],
[[0, 5], [0, 10]],
[[5, 0], [10, 0]],
])
def test_row_or_col_zero(self, table):
result = odds_ratio(table)
assert_equal(result.statistic, np.nan)
ci = result.confidence_interval()
assert_equal((ci.low, ci.high), (0, np.inf))
@pytest.mark.parametrize("case",
[[0.95, 'two-sided', 0.4879913, 2.635883],
[0.90, 'two-sided', 0.5588516, 2.301663]])
def test_sample_odds_ratio_ci(self, case):
# Compare the sample odds ratio confidence interval to the R function
# oddsratio.wald from the epitools package, e.g.
# > library(epitools)
# > table = matrix(c(10, 20, 41, 93), nrow=2, ncol=2, byrow=TRUE)
# > result = oddsratio.wald(table)
# > result$measure
# odds ratio with 95% C.I.
# Predictor estimate lower upper
# Exposed1 1.000000 NA NA
# Exposed2 1.134146 0.4879913 2.635883
confidence_level, alternative, ref_low, ref_high = case
table = [[10, 20], [41, 93]]
result = odds_ratio(table, kind='sample')
assert_allclose(result.statistic, 1.134146, rtol=1e-6)
ci = result.confidence_interval(confidence_level, alternative)
assert_allclose([ci.low, ci.high], [ref_low, ref_high], rtol=1e-6)
@pytest.mark.slow
@pytest.mark.parametrize('alternative', ['less', 'greater', 'two-sided'])
def test_sample_odds_ratio_one_sided_ci(self, alternative):
# can't find a good reference for one-sided CI, so bump up the sample
# size and compare against the conditional odds ratio CI
table = [[1000, 2000], [4100, 9300]]
res = odds_ratio(table, kind='sample')
ref = odds_ratio(table, kind='conditional')
assert_allclose(res.statistic, ref.statistic, atol=1e-5)
assert_allclose(res.confidence_interval(alternative=alternative),
ref.confidence_interval(alternative=alternative),
atol=2e-3)
@pytest.mark.parametrize('kind', ['sample', 'conditional'])
@pytest.mark.parametrize('bad_table', [123, "foo", [10, 11, 12]])
def test_invalid_table_shape(self, kind, bad_table):
with pytest.raises(ValueError, match="Invalid shape"):
odds_ratio(bad_table, kind=kind)
def test_invalid_table_type(self):
with pytest.raises(ValueError, match='must be an array of integers'):
odds_ratio([[1.0, 3.4], [5.0, 9.9]])
def test_negative_table_values(self):
with pytest.raises(ValueError, match='must be nonnegative'):
odds_ratio([[1, 2], [3, -4]])
def test_invalid_kind(self):
with pytest.raises(ValueError, match='`kind` must be'):
odds_ratio([[10, 20], [30, 14]], kind='magnetoreluctance')
def test_invalid_alternative(self):
result = odds_ratio([[5, 10], [2, 32]])
with pytest.raises(ValueError, match='`alternative` must be'):
result.confidence_interval(alternative='depleneration')
@pytest.mark.parametrize('level', [-0.5, 1.5])
def test_invalid_confidence_level(self, level):
result = odds_ratio([[5, 10], [2, 32]])
with pytest.raises(ValueError, match='must be between 0 and 1'):
result.confidence_interval(confidence_level=level)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534import os
from collections import Counter
from itertools import combinations, product
import pytest
import numpy as np
from numpy.testing import (assert_allclose, assert_equal, assert_array_equal,
assert_array_less)
from scipy.spatial import distance
from scipy.stats import shapiro
from scipy.stats._sobol import _test_find_index, _test_low_0_bit
from scipy.stats import qmc
from scipy.stats._qmc import (
van_der_corput, n_primes, primes_from_2_to,
update_discrepancy, QMCEngine, _l1_norm,
_perturb_discrepancy, _lloyd_centroidal_voronoi_tessellation
)
class TestUtils:
def test_scale(self):
# 1d scalar
space = [[0], [1], [0.5]]
out = [[-2], [6], [2]]
scaled_space = qmc.scale(space, l_bounds=-2, u_bounds=6)
assert_allclose(scaled_space, out)
# 2d space
space = [[0, 0], [1, 1], [0.5, 0.5]]
bounds = np.array([[-2, 0], [6, 5]])
out = [[-2, 0], [6, 5], [2, 2.5]]
scaled_space = qmc.scale(space, l_bounds=bounds[0], u_bounds=bounds[1])
assert_allclose(scaled_space, out)
scaled_back_space = qmc.scale(scaled_space, l_bounds=bounds[0],
u_bounds=bounds[1], reverse=True)
assert_allclose(scaled_back_space, space)
# broadcast
space = [[0, 0, 0], [1, 1, 1], [0.5, 0.5, 0.5]]
l_bounds, u_bounds = 0, [6, 5, 3]
out = [[0, 0, 0], [6, 5, 3], [3, 2.5, 1.5]]
scaled_space = qmc.scale(space, l_bounds=l_bounds, u_bounds=u_bounds)
assert_allclose(scaled_space, out)
def test_scale_random(self):
rng = np.random.default_rng(317589836511269190194010915937762468165)
sample = rng.random((30, 10))
a = -rng.random(10) * 10
b = rng.random(10) * 10
scaled = qmc.scale(sample, a, b, reverse=False)
unscaled = qmc.scale(scaled, a, b, reverse=True)
assert_allclose(unscaled, sample)
def test_scale_errors(self):
with pytest.raises(ValueError, match=r"Sample is not a 2D array"):
space = [0, 1, 0.5]
qmc.scale(space, l_bounds=-2, u_bounds=6)
with pytest.raises(ValueError, match=r"Bounds are not consistent"):
space = [[0, 0], [1, 1], [0.5, 0.5]]
bounds = np.array([[-2, 6], [6, 5]])
qmc.scale(space, l_bounds=bounds[0], u_bounds=bounds[1])
with pytest.raises(ValueError, match=r"'l_bounds' and 'u_bounds'"
r" must be broadcastable"):
space = [[0, 0], [1, 1], [0.5, 0.5]]
l_bounds, u_bounds = [-2, 0, 2], [6, 5]
qmc.scale(space, l_bounds=l_bounds, u_bounds=u_bounds)
with pytest.raises(ValueError, match=r"'l_bounds' and 'u_bounds'"
r" must be broadcastable"):
space = [[0, 0], [1, 1], [0.5, 0.5]]
bounds = np.array([[-2, 0, 2], [6, 5, 5]])
qmc.scale(space, l_bounds=bounds[0], u_bounds=bounds[1])
with pytest.raises(ValueError, match=r"Sample is not in unit "
r"hypercube"):
space = [[0, 0], [1, 1.5], [0.5, 0.5]]
bounds = np.array([[-2, 0], [6, 5]])
qmc.scale(space, l_bounds=bounds[0], u_bounds=bounds[1])
with pytest.raises(ValueError, match=r"Sample is out of bounds"):
out = [[-2, 0], [6, 5], [8, 2.5]]
bounds = np.array([[-2, 0], [6, 5]])
qmc.scale(out, l_bounds=bounds[0], u_bounds=bounds[1],
reverse=True)
def test_discrepancy(self):
space_1 = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]])
space_1 = (2.0 * space_1 - 1.0) / (2.0 * 6.0)
space_2 = np.array([[1, 5], [2, 4], [3, 3], [4, 2], [5, 1], [6, 6]])
space_2 = (2.0 * space_2 - 1.0) / (2.0 * 6.0)
# From Fang et al. Design and modeling for computer experiments, 2006
assert_allclose(qmc.discrepancy(space_1), 0.0081, atol=1e-4)
assert_allclose(qmc.discrepancy(space_2), 0.0105, atol=1e-4)
# From Zhou Y.-D. et al. Mixture discrepancy for quasi-random point
# sets. Journal of Complexity, 29 (3-4), pp. 283-301, 2013.
# Example 4 on Page 298
sample = np.array([[2, 1, 1, 2, 2, 2],
[1, 2, 2, 2, 2, 2],
[2, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 2, 2],
[1, 2, 2, 2, 1, 1],
[2, 2, 2, 2, 1, 1],
[2, 2, 2, 1, 2, 2]])
sample = (2.0 * sample - 1.0) / (2.0 * 2.0)
assert_allclose(qmc.discrepancy(sample, method='MD'), 2.5000,
atol=1e-4)
assert_allclose(qmc.discrepancy(sample, method='WD'), 1.3680,
atol=1e-4)
assert_allclose(qmc.discrepancy(sample, method='CD'), 0.3172,
atol=1e-4)
# From Tim P. et al. Minimizing the L2 and Linf star discrepancies
# of a single point in the unit hypercube. JCAM, 2005
# Table 1 on Page 283
for dim in [2, 4, 8, 16, 32, 64]:
ref = np.sqrt(3**(-dim))
assert_allclose(qmc.discrepancy(np.array([[1]*dim]),
method='L2-star'), ref)
def test_discrepancy_errors(self):
sample = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]])
with pytest.raises(
ValueError, match=r"Sample is not in unit hypercube"
):
qmc.discrepancy(sample)
with pytest.raises(ValueError, match=r"Sample is not a 2D array"):
qmc.discrepancy([1, 3])
sample = [[0, 0], [1, 1], [0.5, 0.5]]
with pytest.raises(ValueError, match=r"'toto' is not a valid ..."):
qmc.discrepancy(sample, method="toto")
def test_discrepancy_parallel(self, monkeypatch):
sample = np.array([[2, 1, 1, 2, 2, 2],
[1, 2, 2, 2, 2, 2],
[2, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 2, 2],
[1, 2, 2, 2, 1, 1],
[2, 2, 2, 2, 1, 1],
[2, 2, 2, 1, 2, 2]])
sample = (2.0 * sample - 1.0) / (2.0 * 2.0)
assert_allclose(qmc.discrepancy(sample, method='MD', workers=8),
2.5000,
atol=1e-4)
assert_allclose(qmc.discrepancy(sample, method='WD', workers=8),
1.3680,
atol=1e-4)
assert_allclose(qmc.discrepancy(sample, method='CD', workers=8),
0.3172,
atol=1e-4)
# From Tim P. et al. Minimizing the L2 and Linf star discrepancies
# of a single point in the unit hypercube. JCAM, 2005
# Table 1 on Page 283
for dim in [2, 4, 8, 16, 32, 64]:
ref = np.sqrt(3 ** (-dim))
assert_allclose(qmc.discrepancy(np.array([[1] * dim]),
method='L2-star', workers=-1), ref)
monkeypatch.setattr(os, 'cpu_count', lambda: None)
with pytest.raises(NotImplementedError, match="Cannot determine the"):
qmc.discrepancy(sample, workers=-1)
with pytest.raises(ValueError, match="Invalid number of workers..."):
qmc.discrepancy(sample, workers=-2)
def test_geometric_discrepancy_errors(self):
sample = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]])
with pytest.raises(ValueError, match=r"Sample is not in unit hypercube"):
qmc.geometric_discrepancy(sample)
with pytest.raises(ValueError, match=r"Sample is not a 2D array"):
qmc.geometric_discrepancy([1, 3])
sample = [[0, 0], [1, 1], [0.5, 0.5]]
with pytest.raises(ValueError, match=r"'toto' is not a valid ..."):
qmc.geometric_discrepancy(sample, method="toto")
sample = np.array([[0, 0], [0, 0], [0, 1]])
with pytest.warns(UserWarning, match="Sample contains duplicate points."):
qmc.geometric_discrepancy(sample)
sample = np.array([[0.5, 0.5]])
with pytest.raises(ValueError, match="Sample must contain at least two points"):
qmc.geometric_discrepancy(sample)
def test_geometric_discrepancy(self):
sample = np.array([[0, 0], [1, 1]])
assert_allclose(qmc.geometric_discrepancy(sample), np.sqrt(2))
assert_allclose(qmc.geometric_discrepancy(sample, method="mst"), np.sqrt(2))
sample = np.array([[0, 0], [0, 1], [0.5, 1]])
assert_allclose(qmc.geometric_discrepancy(sample), 0.5)
assert_allclose(qmc.geometric_discrepancy(sample, method="mst"), 0.75)
sample = np.array([[0, 0], [0.25, 0.25], [1, 1]])
assert_allclose(qmc.geometric_discrepancy(sample), np.sqrt(2) / 4)
assert_allclose(qmc.geometric_discrepancy(sample, method="mst"), np.sqrt(2) / 2)
assert_allclose(qmc.geometric_discrepancy(sample, metric="chebyshev"), 0.25)
assert_allclose(
qmc.geometric_discrepancy(sample, method="mst", metric="chebyshev"), 0.5
)
rng = np.random.default_rng(191468432622931918890291693003068437394)
sample = qmc.LatinHypercube(d=3, rng=rng).random(50)
assert_allclose(qmc.geometric_discrepancy(sample), 0.05106012076093356)
assert_allclose(
qmc.geometric_discrepancy(sample, method='mst'), 0.19704396643366182
)
@pytest.mark.xfail(
reason="minimum_spanning_tree ignores zero distances (#18892)",
strict=True,
)
@pytest.mark.thread_unsafe
def test_geometric_discrepancy_mst_with_zero_distances(self):
sample = np.array([[0, 0], [0, 0], [0, 1]])
assert_allclose(qmc.geometric_discrepancy(sample, method='mst'), 0.5)
def test_update_discrepancy(self):
# From Fang et al. Design and modeling for computer experiments, 2006
space_1 = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]])
space_1 = (2.0 * space_1 - 1.0) / (2.0 * 6.0)
disc_init = qmc.discrepancy(space_1[:-1], iterative=True)
disc_iter = update_discrepancy(space_1[-1], space_1[:-1], disc_init)
assert_allclose(disc_iter, 0.0081, atol=1e-4)
# n<d
rng = np.random.default_rng(241557431858162136881731220526394276199)
space_1 = rng.random((4, 10))
disc_ref = qmc.discrepancy(space_1)
disc_init = qmc.discrepancy(space_1[:-1], iterative=True)
disc_iter = update_discrepancy(space_1[-1], space_1[:-1], disc_init)
assert_allclose(disc_iter, disc_ref, atol=1e-4)
# errors
with pytest.raises(ValueError, match=r"Sample is not in unit "
r"hypercube"):
update_discrepancy(space_1[-1], space_1[:-1] + 1, disc_init)
with pytest.raises(ValueError, match=r"Sample is not a 2D array"):
update_discrepancy(space_1[-1], space_1[0], disc_init)
x_new = [1, 3]
with pytest.raises(ValueError, match=r"x_new is not in unit "
r"hypercube"):
update_discrepancy(x_new, space_1[:-1], disc_init)
x_new = [[0.5, 0.5]]
with pytest.raises(ValueError, match=r"x_new is not a 1D array"):
update_discrepancy(x_new, space_1[:-1], disc_init)
x_new = [0.3, 0.1, 0]
with pytest.raises(ValueError, match=r"x_new and sample must be "
r"broadcastable"):
update_discrepancy(x_new, space_1[:-1], disc_init)
def test_perm_discrepancy(self):
rng = np.random.default_rng(46449423132557934943847369749645759997)
qmc_gen = qmc.LatinHypercube(5, rng=rng)
sample = qmc_gen.random(10)
disc = qmc.discrepancy(sample)
for i in range(100):
row_1 = rng.integers(10)
row_2 = rng.integers(10)
col = rng.integers(5)
disc = _perturb_discrepancy(sample, row_1, row_2, col, disc)
sample[row_1, col], sample[row_2, col] = (
sample[row_2, col], sample[row_1, col])
disc_reference = qmc.discrepancy(sample)
assert_allclose(disc, disc_reference)
def test_discrepancy_alternative_implementation(self):
"""Alternative definitions from Matt Haberland."""
def disc_c2(x):
n, s = x.shape
xij = x
disc1 = np.sum(np.prod((1
+ 1/2*np.abs(xij-0.5)
- 1/2*np.abs(xij-0.5)**2), axis=1))
xij = x[None, :, :]
xkj = x[:, None, :]
disc2 = np.sum(np.sum(np.prod(1
+ 1/2*np.abs(xij - 0.5)
+ 1/2*np.abs(xkj - 0.5)
- 1/2*np.abs(xij - xkj), axis=2),
axis=0))
return (13/12)**s - 2/n * disc1 + 1/n**2*disc2
def disc_wd(x):
n, s = x.shape
xij = x[None, :, :]
xkj = x[:, None, :]
disc = np.sum(np.sum(np.prod(3/2
- np.abs(xij - xkj)
+ np.abs(xij - xkj)**2, axis=2),
axis=0))
return -(4/3)**s + 1/n**2 * disc
def disc_md(x):
n, s = x.shape
xij = x
disc1 = np.sum(np.prod((5/3
- 1/4*np.abs(xij-0.5)
- 1/4*np.abs(xij-0.5)**2), axis=1))
xij = x[None, :, :]
xkj = x[:, None, :]
disc2 = np.sum(np.sum(np.prod(15/8
- 1/4*np.abs(xij - 0.5)
- 1/4*np.abs(xkj - 0.5)
- 3/4*np.abs(xij - xkj)
+ 1/2*np.abs(xij - xkj)**2,
axis=2), axis=0))
return (19/12)**s - 2/n * disc1 + 1/n**2*disc2
def disc_star_l2(x):
n, s = x.shape
return np.sqrt(
3 ** (-s) - 2 ** (1 - s) / n
* np.sum(np.prod(1 - x ** 2, axis=1))
+ np.sum([
np.prod(1 - np.maximum(x[k, :], x[j, :]))
for k in range(n) for j in range(n)
]) / n ** 2
)
rng = np.random.default_rng(117065081482921065782761407107747179201)
sample = rng.random((30, 10))
disc_curr = qmc.discrepancy(sample, method='CD')
disc_alt = disc_c2(sample)
assert_allclose(disc_curr, disc_alt)
disc_curr = qmc.discrepancy(sample, method='WD')
disc_alt = disc_wd(sample)
assert_allclose(disc_curr, disc_alt)
disc_curr = qmc.discrepancy(sample, method='MD')
disc_alt = disc_md(sample)
assert_allclose(disc_curr, disc_alt)
disc_curr = qmc.discrepancy(sample, method='L2-star')
disc_alt = disc_star_l2(sample)
assert_allclose(disc_curr, disc_alt)
def test_n_primes(self):
primes = n_primes(10)
assert primes[-1] == 29
primes = n_primes(168)
assert primes[-1] == 997
primes = n_primes(350)
assert primes[-1] == 2357
def test_primes(self):
primes = primes_from_2_to(50)
out = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
assert_allclose(primes, out)
class TestVDC:
def test_van_der_corput(self):
sample = van_der_corput(10)
out = [0.0, 0.5, 0.25, 0.75, 0.125, 0.625,
0.375, 0.875, 0.0625, 0.5625]
assert_allclose(sample, out)
sample = van_der_corput(10, workers=4)
assert_allclose(sample, out)
sample = van_der_corput(10, workers=8)
assert_allclose(sample, out)
sample = van_der_corput(7, start_index=3)
assert_allclose(sample, out[3:])
def test_van_der_corput_scramble(self):
rng = 338213789010180879520345496831675783177
out = van_der_corput(10, scramble=True, rng=rng)
sample = van_der_corput(7, start_index=3, scramble=True, rng=rng)
assert_allclose(sample, out[3:])
sample = van_der_corput(
7, start_index=3, scramble=True, rng=rng, workers=4
)
assert_allclose(sample, out[3:])
sample = van_der_corput(
7, start_index=3, scramble=True, rng=rng, workers=8
)
assert_allclose(sample, out[3:])
def test_invalid_base_error(self):
with pytest.raises(ValueError, match=r"'base' must be at least 2"):
van_der_corput(10, base=1)
class RandomEngine(qmc.QMCEngine):
def __init__(self, d, optimization=None, rng=None):
super().__init__(d=d, optimization=optimization, rng=rng)
def _random(self, n=1, *, workers=1):
sample = self.rng.random((n, self.d))
return sample
def test_subclassing_QMCEngine():
engine = RandomEngine(2, rng=175180605424926556207367152557812293274)
sample_1 = engine.random(n=5)
sample_2 = engine.random(n=7)
assert engine.num_generated == 12
# reset and re-sample
engine.reset()
assert engine.num_generated == 0
sample_1_test = engine.random(n=5)
assert_equal(sample_1, sample_1_test)
# repeat reset and fast forward
engine.reset()
engine.fast_forward(n=5)
sample_2_test = engine.random(n=7)
assert_equal(sample_2, sample_2_test)
assert engine.num_generated == 12
def test_raises():
# input validation
with pytest.raises(ValueError, match=r"d must be a non-negative integer"):
RandomEngine((2,))
with pytest.raises(ValueError, match=r"d must be a non-negative integer"):
RandomEngine(-1)
msg = r"'u_bounds' and 'l_bounds' must be integers"
with pytest.raises(ValueError, match=msg):
engine = RandomEngine(1)
engine.integers(l_bounds=1, u_bounds=1.1)
def test_integers():
engine = RandomEngine(1, rng=231195739755290648063853336582377368684)
# basic tests
sample = engine.integers(1, n=10)
assert_equal(np.unique(sample), [0])
assert sample.dtype == np.dtype('int64')
sample = engine.integers(1, n=10, endpoint=True)
assert_equal(np.unique(sample), [0, 1])
low = -5
high = 7
# scaling logic
engine.reset()
ref_sample = engine.random(20)
ref_sample = ref_sample * (high - low) + low
ref_sample = np.floor(ref_sample).astype(np.int64)
engine.reset()
sample = engine.integers(low, u_bounds=high, n=20, endpoint=False)
assert_equal(sample, ref_sample)
# up to bounds, no less, no more
sample = engine.integers(low, u_bounds=high, n=100, endpoint=False)
assert_equal((sample.min(), sample.max()), (low, high-1))
sample = engine.integers(low, u_bounds=high, n=100, endpoint=True)
assert_equal((sample.min(), sample.max()), (low, high))
def test_integers_nd():
d = 10
rng = np.random.default_rng(3716505122102428560615700415287450951)
low = rng.integers(low=-5, high=-1, size=d)
high = rng.integers(low=1, high=5, size=d, endpoint=True)
engine = RandomEngine(d, rng=rng)
sample = engine.integers(low, u_bounds=high, n=100, endpoint=False)
assert_equal(sample.min(axis=0), low)
assert_equal(sample.max(axis=0), high-1)
sample = engine.integers(low, u_bounds=high, n=100, endpoint=True)
assert_equal(sample.min(axis=0), low)
assert_equal(sample.max(axis=0), high)
class QMCEngineTests:
"""Generic tests for QMC engines."""
qmce = NotImplemented
can_scramble = NotImplemented
unscramble_nd = NotImplemented
scramble_nd = NotImplemented
scramble = [True, False]
ids = ["Scrambled", "Unscrambled"]
def engine(
self, scramble: bool,
rng=170382760648021597650530316304495310428,
**kwargs
) -> QMCEngine:
# preserve use of `seed` during SPEC 7 transition because
# some tests rely on behavior with integer `seed` (which is
# different from behavior with integer `rng`)
if self.can_scramble:
return self.qmce(scramble=scramble, seed=rng, **kwargs)
else:
if scramble:
pytest.skip()
else:
return self.qmce(seed=rng, **kwargs)
def reference(self, scramble: bool) -> np.ndarray:
return self.scramble_nd if scramble else self.unscramble_nd
@pytest.mark.parametrize("scramble", scramble, ids=ids)
def test_0dim(self, scramble):
engine = self.engine(d=0, scramble=scramble)
sample = engine.random(4)
assert_array_equal(np.empty((4, 0)), sample)
@pytest.mark.parametrize("scramble", scramble, ids=ids)
def test_0sample(self, scramble):
engine = self.engine(d=2, scramble=scramble)
sample = engine.random(0)
assert_array_equal(np.empty((0, 2)), sample)
@pytest.mark.parametrize("scramble", scramble, ids=ids)
def test_1sample(self, scramble):
engine = self.engine(d=2, scramble=scramble)
sample = engine.random(1)
assert (1, 2) == sample.shape
@pytest.mark.parametrize("scramble", scramble, ids=ids)
def test_bounds(self, scramble):
engine = self.engine(d=100, scramble=scramble)
sample = engine.random(512)
assert np.all(sample >= 0)
assert np.all(sample <= 1)
@pytest.mark.parametrize("scramble", scramble, ids=ids)
def test_sample(self, scramble):
ref_sample = self.reference(scramble=scramble)
engine = self.engine(d=2, scramble=scramble)
sample = engine.random(n=len(ref_sample))
assert_allclose(sample, ref_sample, atol=1e-1)
assert engine.num_generated == len(ref_sample)
@pytest.mark.parametrize("scramble", scramble, ids=ids)
def test_continuing(self, scramble):
engine = self.engine(d=2, scramble=scramble)
ref_sample = engine.random(n=8)
engine = self.engine(d=2, scramble=scramble)
n_half = len(ref_sample) // 2
_ = engine.random(n=n_half)
sample = engine.random(n=n_half)
assert_allclose(sample, ref_sample[n_half:], atol=1e-1)
@pytest.mark.parametrize("scramble", scramble, ids=ids)
@pytest.mark.parametrize(
"rng",
(
170382760648021597650530316304495310428,
lambda: np.random.default_rng(170382760648021597650530316304495310428),
pytest.param(None, marks=pytest.mark.thread_unsafe),
),
)
def test_reset(self, scramble, rng):
if callable(rng):
# Initialize local RNG here to make it thread-local in pytest-run-parallel
rng = rng()
engine = self.engine(d=2, scramble=scramble, rng=rng)
ref_sample = engine.random(n=8)
engine.reset()
assert engine.num_generated == 0
sample = engine.random(n=8)
assert_allclose(sample, ref_sample)
@pytest.mark.parametrize("scramble", scramble, ids=ids)
def test_fast_forward(self, scramble):
engine = self.engine(d=2, scramble=scramble)
ref_sample = engine.random(n=8)
engine = self.engine(d=2, scramble=scramble)
engine.fast_forward(4)
sample = engine.random(n=4)
assert_allclose(sample, ref_sample[4:], atol=1e-1)
# alternate fast forwarding with sampling
engine.reset()
even_draws = []
for i in range(8):
if i % 2 == 0:
even_draws.append(engine.random())
else:
engine.fast_forward(1)
assert_allclose(
ref_sample[[i for i in range(8) if i % 2 == 0]],
np.concatenate(even_draws),
atol=1e-5
)
@pytest.mark.parametrize("scramble", [True])
def test_distribution(self, scramble):
d = 50
engine = self.engine(d=d, scramble=scramble)
sample = engine.random(1024)
assert_allclose(
np.mean(sample, axis=0), np.repeat(0.5, d), atol=1e-2
)
assert_allclose(
np.percentile(sample, 25, axis=0), np.repeat(0.25, d), atol=1e-2
)
assert_allclose(
np.percentile(sample, 75, axis=0), np.repeat(0.75, d), atol=1e-2
)
def test_raises_optimizer(self):
message = r"'toto' is not a valid optimization method"
with pytest.raises(ValueError, match=message):
self.engine(d=1, scramble=False, optimization="toto")
@pytest.mark.parametrize(
"optimization,metric",
[
("random-CD", qmc.discrepancy),
("lloyd", lambda sample: -_l1_norm(sample))]
)
def test_optimizers(self, optimization, metric):
engine = self.engine(d=2, scramble=False)
sample_ref = engine.random(n=64)
metric_ref = metric(sample_ref)
optimal_ = self.engine(d=2, scramble=False, optimization=optimization)
sample_ = optimal_.random(n=64)
metric_ = metric(sample_)
assert metric_ < metric_ref
def test_consume_prng_state(self):
rng = np.random.default_rng(0xa29cabb11cfdf44ff6cac8bec254c2a0)
sample = []
for i in range(3):
engine = self.engine(d=2, scramble=True, rng=rng)
sample.append(engine.random(4))
with pytest.raises(AssertionError, match="Arrays are not equal"):
assert_equal(sample[0], sample[1])
with pytest.raises(AssertionError, match="Arrays are not equal"):
assert_equal(sample[0], sample[2])
class TestHalton(QMCEngineTests):
qmce = qmc.Halton
can_scramble = True
# theoretical values known from Van der Corput
unscramble_nd = np.array([[0, 0], [1 / 2, 1 / 3],
[1 / 4, 2 / 3], [3 / 4, 1 / 9],
[1 / 8, 4 / 9], [5 / 8, 7 / 9],
[3 / 8, 2 / 9], [7 / 8, 5 / 9]])
# theoretical values unknown: convergence properties checked
scramble_nd = np.array([[0.50246036, 0.93382481],
[0.00246036, 0.26715815],
[0.75246036, 0.60049148],
[0.25246036, 0.8227137 ],
[0.62746036, 0.15604704],
[0.12746036, 0.48938037],
[0.87746036, 0.71160259],
[0.37746036, 0.04493592]])
def test_workers(self):
ref_sample = self.reference(scramble=True)
engine = self.engine(d=2, scramble=True)
sample = engine.random(n=len(ref_sample), workers=8)
assert_allclose(sample, ref_sample, atol=1e-3)
# worker + integers
engine.reset()
ref_sample = engine.integers(10)
engine.reset()
sample = engine.integers(10, workers=8)
assert_equal(sample, ref_sample)
class TestLHS(QMCEngineTests):
qmce = qmc.LatinHypercube
can_scramble = True
def test_continuing(self, *args):
pytest.skip("Not applicable: not a sequence.")
def test_fast_forward(self, *args):
pytest.skip("Not applicable: not a sequence.")
def test_sample(self, *args):
pytest.skip("Not applicable: the value of reference sample is"
" implementation dependent.")
@pytest.mark.parametrize("strength", [1, 2])
@pytest.mark.parametrize("scramble", [False, True])
@pytest.mark.parametrize("optimization", [None, "random-CD"])
def test_sample_stratified(self, optimization, scramble, strength):
rng = np.random.default_rng(37511836202578819870665127532742111260)
p = 5
n = p**2
d = 6
engine = qmc.LatinHypercube(d=d, scramble=scramble,
strength=strength,
optimization=optimization,
rng=rng)
sample = engine.random(n=n)
assert sample.shape == (n, d)
assert engine.num_generated == n
# centering stratifies samples in the middle of equal segments:
# * inter-sample distance is constant in 1D sub-projections
# * after ordering, columns are equal
expected1d = (np.arange(n) + 0.5) / n
expected = np.broadcast_to(expected1d, (d, n)).T
assert np.any(sample != expected)
sorted_sample = np.sort(sample, axis=0)
tol = 0.5 / n if scramble else 0
assert_allclose(sorted_sample, expected, atol=tol)
assert np.any(sample - expected > tol)
if strength == 2 and optimization is None:
unique_elements = np.arange(p)
desired = set(product(unique_elements, unique_elements))
for i, j in combinations(range(engine.d), 2):
samples_2d = sample[:, [i, j]]
res = (samples_2d * p).astype(int)
res_set = {tuple(row) for row in res}
assert_equal(res_set, desired)
def test_optimizer_1d(self):
# discrepancy measures are invariant under permuting factors and runs
engine = self.engine(d=1, scramble=False)
sample_ref = engine.random(n=64)
optimal_ = self.engine(d=1, scramble=False, optimization="random-CD")
sample_ = optimal_.random(n=64)
assert_array_equal(sample_ref, sample_)
def test_raises(self):
message = r"not a valid strength"
with pytest.raises(ValueError, match=message):
qmc.LatinHypercube(1, strength=3)
message = r"n is not the square of a prime number"
with pytest.raises(ValueError, match=message):
engine = qmc.LatinHypercube(d=2, strength=2)
engine.random(16)
message = r"n is not the square of a prime number"
with pytest.raises(ValueError, match=message):
engine = qmc.LatinHypercube(d=2, strength=2)
engine.random(5) # because int(sqrt(5)) would result in 2
message = r"n is too small for d"
with pytest.raises(ValueError, match=message):
engine = qmc.LatinHypercube(d=5, strength=2)
engine.random(9)
class TestSobol(QMCEngineTests):
qmce = qmc.Sobol
can_scramble = True
# theoretical values from Joe Kuo2010
unscramble_nd = np.array([[0., 0.],
[0.5, 0.5],
[0.75, 0.25],
[0.25, 0.75],
[0.375, 0.375],
[0.875, 0.875],
[0.625, 0.125],
[0.125, 0.625]])
# theoretical values unknown: convergence properties checked
scramble_nd = np.array([[0.25331921, 0.41371179],
[0.8654213, 0.9821167],
[0.70097554, 0.03664616],
[0.18027647, 0.60895735],
[0.10521339, 0.21897069],
[0.53019685, 0.66619033],
[0.91122276, 0.34580743],
[0.45337471, 0.78912079]])
def test_warning(self):
with pytest.warns(UserWarning, match=r"The balance properties of "
r"Sobol' points"):
engine = qmc.Sobol(1)
engine.random(10)
def test_random_base2(self):
engine = qmc.Sobol(2, scramble=False)
sample = engine.random_base2(2)
assert_array_equal(self.unscramble_nd[:4], sample)
# resampling still having N=2**n
sample = engine.random_base2(2)
assert_array_equal(self.unscramble_nd[4:8], sample)
# resampling again but leading to N!=2**n
with pytest.raises(ValueError, match=r"The balance properties of "
r"Sobol' points"):
engine.random_base2(2)
def test_raise(self):
with pytest.raises(ValueError, match=r"Maximum supported "
r"dimensionality"):
qmc.Sobol(qmc.Sobol.MAXDIM + 1)
with pytest.raises(ValueError, match=r"Maximum supported "
r"'bits' is 64"):
qmc.Sobol(1, bits=65)
def test_high_dim(self):
engine = qmc.Sobol(1111, scramble=False)
count1 = Counter(engine.random().flatten().tolist())
count2 = Counter(engine.random().flatten().tolist())
assert_equal(count1, Counter({0.0: 1111}))
assert_equal(count2, Counter({0.5: 1111}))
@pytest.mark.parametrize("bits", [2, 3])
def test_bits(self, bits):
engine = qmc.Sobol(2, scramble=False, bits=bits)
ns = 2**bits
sample = engine.random(ns)
assert_array_equal(self.unscramble_nd[:ns], sample)
with pytest.raises(ValueError, match="increasing `bits`"):
engine.random()
def test_64bits(self):
engine = qmc.Sobol(2, scramble=False, bits=64)
sample = engine.random(8)
assert_array_equal(self.unscramble_nd, sample)
class TestLow0Bit:
def test_examples(self):
test_vector = [
# from low_0_bit's docstring
(0b0000, 1),
(0b0001, 2),
(0b0010, 1),
(0b0101, 2),
(0b0111, 4),
# gh-23409
(2 ** 32 - 1, 33),
(2 ** 32, 1),
(2 ** 33 - 1, 34),
(2 ** 64 - 1, 65),
]
for in_, out in test_vector:
assert_equal(_test_low_0_bit(in_), out)
class TestPoisson(QMCEngineTests):
qmce = qmc.PoissonDisk
can_scramble = False
def test_bounds(self, *args):
pytest.skip("Too costly in memory.")
def test_fast_forward(self, *args):
pytest.skip("Not applicable: recursive process.")
def test_sample(self, *args):
pytest.skip("Not applicable: the value of reference sample is"
" implementation dependent.")
def test_continuing(self, *args):
# can continue a sampling, but will not preserve the same order
# because candidates are lost, so we will not select the same center
radius = 0.05
ns = 6
engine = self.engine(d=2, radius=radius, scramble=False)
sample_init = engine.random(n=ns)
assert len(sample_init) <= ns
assert l2_norm(sample_init) >= radius
sample_continued = engine.random(n=ns)
assert len(sample_continued) <= ns
assert l2_norm(sample_continued) >= radius
sample = np.concatenate([sample_init, sample_continued], axis=0)
assert len(sample) <= ns * 2
assert l2_norm(sample) >= radius
def test_mindist(self):
rng = np.random.default_rng(132074951149370773672162394161442690287)
ns = 50
low, high = 0.08, 0.2
radii = (high - low) * rng.random(5) + low
dimensions = [1, 3, 4]
hypersphere_methods = ["volume", "surface"]
gen = product(dimensions, radii, hypersphere_methods)
for d, radius, hypersphere in gen:
engine = self.qmce(
d=d, radius=radius, hypersphere=hypersphere, rng=rng
)
sample = engine.random(ns)
assert len(sample) <= ns
assert l2_norm(sample) >= radius
@pytest.mark.parametrize("l_bounds, u_bounds", # add bounds to test gh-22819
[(None, None), ([-5, -5], [5, 5]), ([1.1, 1.1], [5.1, 5.1])])
def test_fill_space(self, l_bounds, u_bounds):
radius = 0.2
engine = self.qmce(d=2, radius=radius, l_bounds=l_bounds, u_bounds=u_bounds)
sample = engine.fill_space()
# circle packing problem is np complex
assert l2_norm(sample) >= radius
def test_bounds_shift_scale(self):
# test a reasonable property: as long as shape of region is a hypercube,
# bounds just shift and scale the sample.
radius = 0.2 # arbitrary parameters
shift = np.asarray([-2.1, 3.4])
scale = 2.6
rng = np.random.default_rng(8504196751)
engine = self.qmce(d=2, radius=radius*scale, rng=rng,
l_bounds=shift, u_bounds=shift + scale)
res = engine.fill_space()
rng = np.random.default_rng(8504196751)
engine = self.qmce(d=2, radius=radius, rng=rng)
ref = engine.fill_space()
# circle packing problem is np complex
assert l2_norm(res) >= radius
assert_allclose(res, ref*scale + shift)
@pytest.mark.parametrize("l_bounds", [[-1, -2, -1], [1, 2, 1]])
def test_sample_inside_lower_bounds(self, l_bounds):
radius = 0.2
u_bounds=[3, 3, 2]
engine = self.qmce(
d=3, radius=radius, l_bounds=l_bounds, u_bounds=u_bounds
)
sample = engine.random(30)
for point in sample:
assert_array_less(point, u_bounds)
assert_array_less(l_bounds, point)
@pytest.mark.parametrize("u_bounds", [[-1, -2, -1], [1, 2, 1]])
def test_sample_inside_upper_bounds(self, u_bounds):
radius = 0.2
l_bounds=[-3, -3, -2]
engine = self.qmce(
d=3, radius=radius, l_bounds=l_bounds, u_bounds=u_bounds
)
sample = engine.random(30)
for point in sample:
assert_array_less(point, u_bounds)
assert_array_less(l_bounds, point)
def test_inconsistent_bound_value(self):
radius = 0.2
l_bounds=[3, 2, 1]
u_bounds=[-1, -2, -1]
with pytest.raises(
ValueError,
match="Bounds are not consistent 'l_bounds' < 'u_bounds'"):
self.qmce(d=3, radius=radius, l_bounds=l_bounds, u_bounds=u_bounds)
@pytest.mark.parametrize("u_bounds", [[-1, -2, -1], [-1, -2]])
@pytest.mark.parametrize("l_bounds", [[3, 2]])
def test_inconsistent_bounds(self, u_bounds, l_bounds):
radius = 0.2
with pytest.raises(
ValueError,
match="'l_bounds' and 'u_bounds' must be broadcastable and respect"
" the sample dimension"):
self.qmce(
d=3, radius=radius,
l_bounds=l_bounds, u_bounds=u_bounds
)
def test_raises(self):
message = r"'toto' is not a valid hypersphere sampling"
with pytest.raises(ValueError, match=message):
qmc.PoissonDisk(1, hypersphere="toto")
class TestMultinomialQMC:
def test_validations(self):
# negative Ps
p = np.array([0.12, 0.26, -0.05, 0.35, 0.22])
with pytest.raises(ValueError, match=r"Elements of pvals must "
r"be non-negative."):
qmc.MultinomialQMC(p, n_trials=10)
# sum of P too large
p = np.array([0.12, 0.26, 0.1, 0.35, 0.22])
message = r"Elements of pvals must sum to 1."
with pytest.raises(ValueError, match=message):
qmc.MultinomialQMC(p, n_trials=10)
p = np.array([0.12, 0.26, 0.05, 0.35, 0.22])
message = r"Dimension of `engine` must be 1."
with pytest.raises(ValueError, match=message):
qmc.MultinomialQMC(p, n_trials=10, engine=qmc.Sobol(d=2))
message = r"`engine` must be an instance of..."
with pytest.raises(ValueError, match=message):
qmc.MultinomialQMC(p, n_trials=10, engine=np.random.default_rng())
@pytest.mark.filterwarnings('ignore::UserWarning')
def test_MultinomialBasicDraw(self):
rng = np.random.default_rng(6955663962957011631562466584467607969)
p = np.array([0.12, 0.26, 0.05, 0.35, 0.22])
n_trials = 100
expected = np.atleast_2d(n_trials * p).astype(int)
# preserve use of legacy keyword during SPEC 7 transition
engine = qmc.MultinomialQMC(p, n_trials=n_trials, seed=rng)
assert_allclose(engine.random(1), expected, atol=1)
def test_MultinomialDistribution(self):
rng = np.random.default_rng(77797854505813727292048130876699859000)
p = np.array([0.12, 0.26, 0.05, 0.35, 0.22])
engine = qmc.MultinomialQMC(p, n_trials=8192, rng=rng)
draws = engine.random(1)
assert_allclose(draws / np.sum(draws), np.atleast_2d(p), atol=1e-4)
def test_FindIndex(self):
p_cumulative = np.array([0.1, 0.4, 0.45, 0.6, 0.75, 0.9, 0.99, 1.0])
size = len(p_cumulative)
assert_equal(_test_find_index(p_cumulative, size, 0.0), 0)
assert_equal(_test_find_index(p_cumulative, size, 0.4), 2)
assert_equal(_test_find_index(p_cumulative, size, 0.44999), 2)
assert_equal(_test_find_index(p_cumulative, size, 0.45001), 3)
assert_equal(_test_find_index(p_cumulative, size, 1.0), size - 1)
@pytest.mark.filterwarnings('ignore::UserWarning')
def test_other_engine(self):
# same as test_MultinomialBasicDraw with different engine
rng = np.random.default_rng(283753519042773243071753037669078065412)
p = np.array([0.12, 0.26, 0.05, 0.35, 0.22])
n_trials = 100
expected = np.atleast_2d(n_trials * p).astype(int)
base_engine = qmc.Sobol(1, scramble=True, rng=rng)
engine = qmc.MultinomialQMC(p, n_trials=n_trials, engine=base_engine,
rng=rng)
assert_allclose(engine.random(1), expected, atol=1)
class TestNormalQMC:
def test_NormalQMC(self):
# d = 1
engine = qmc.MultivariateNormalQMC(mean=np.zeros(1))
samples = engine.random()
assert_equal(samples.shape, (1, 1))
samples = engine.random(n=5)
assert_equal(samples.shape, (5, 1))
# d = 2
engine = qmc.MultivariateNormalQMC(mean=np.zeros(2))
samples = engine.random()
assert_equal(samples.shape, (1, 2))
samples = engine.random(n=5)
assert_equal(samples.shape, (5, 2))
def test_NormalQMCInvTransform(self):
# d = 1
engine = qmc.MultivariateNormalQMC(
mean=np.zeros(1), inv_transform=True)
samples = engine.random()
assert_equal(samples.shape, (1, 1))
samples = engine.random(n=5)
assert_equal(samples.shape, (5, 1))
# d = 2
engine = qmc.MultivariateNormalQMC(
mean=np.zeros(2), inv_transform=True)
samples = engine.random()
assert_equal(samples.shape, (1, 2))
samples = engine.random(n=5)
assert_equal(samples.shape, (5, 2))
def test_NormalQMCSeeded(self):
# test even dimension
rng = np.random.default_rng(274600237797326520096085022671371676017)
# preserve use of legacy keyword during SPEC 7 transition
engine = qmc.MultivariateNormalQMC(
mean=np.zeros(2), inv_transform=False, seed=rng)
samples = engine.random(n=2)
samples_expected = np.array([[-0.932001, -0.522923],
[-1.477655, 0.846851]])
assert_allclose(samples, samples_expected, atol=1e-4)
# test odd dimension
rng = np.random.default_rng(274600237797326520096085022671371676017)
engine = qmc.MultivariateNormalQMC(
mean=np.zeros(3), inv_transform=False, rng=rng)
samples = engine.random(n=2)
samples_expected = np.array([[-0.932001, -0.522923, 0.036578],
[-1.778011, 0.912428, -0.065421]])
assert_allclose(samples, samples_expected, atol=1e-4)
# same test with another engine
rng = np.random.default_rng(274600237797326520096085022671371676017)
base_engine = qmc.Sobol(4, scramble=True, rng=rng)
engine = qmc.MultivariateNormalQMC(
mean=np.zeros(3), inv_transform=False,
engine=base_engine, rng=rng
)
samples = engine.random(n=2)
samples_expected = np.array([[-0.932001, -0.522923, 0.036578],
[-1.778011, 0.912428, -0.065421]])
assert_allclose(samples, samples_expected, atol=1e-4)
def test_NormalQMCSeededInvTransform(self):
# test even dimension
rng = np.random.default_rng(288527772707286126646493545351112463929)
engine = qmc.MultivariateNormalQMC(
mean=np.zeros(2), rng=rng, inv_transform=True)
samples = engine.random(n=2)
samples_expected = np.array([[-0.913237, -0.964026],
[0.255904, 0.003068]])
assert_allclose(samples, samples_expected, atol=1e-4)
# test odd dimension
rng = np.random.default_rng(288527772707286126646493545351112463929)
engine = qmc.MultivariateNormalQMC(
mean=np.zeros(3), rng=rng, inv_transform=True)
samples = engine.random(n=2)
samples_expected = np.array([[-0.913237, -0.964026, 0.355501],
[0.699261, 2.90213 , -0.6418]])
assert_allclose(samples, samples_expected, atol=1e-4)
def test_other_engine(self):
for d in (0, 1, 2):
base_engine = qmc.Sobol(d=d, scramble=False)
engine = qmc.MultivariateNormalQMC(mean=np.zeros(d),
engine=base_engine,
inv_transform=True)
samples = engine.random()
assert_equal(samples.shape, (1, d))
def test_NormalQMCShapiro(self):
rng = np.random.default_rng(13242)
engine = qmc.MultivariateNormalQMC(mean=np.zeros(2), rng=rng)
samples = engine.random(n=256)
assert all(np.abs(samples.mean(axis=0)) < 1e-2)
assert all(np.abs(samples.std(axis=0) - 1) < 1e-2)
# perform Shapiro-Wilk test for normality
for i in (0, 1):
_, pval = shapiro(samples[:, i])
assert pval > 0.9
# make sure samples are uncorrelated
cov = np.cov(samples.transpose())
assert np.abs(cov[0, 1]) < 1e-2
def test_NormalQMCShapiroInvTransform(self):
rng = np.random.default_rng(32344554)
engine = qmc.MultivariateNormalQMC(
mean=np.zeros(2), inv_transform=True, rng=rng)
samples = engine.random(n=256)
assert all(np.abs(samples.mean(axis=0)) < 1e-2)
assert all(np.abs(samples.std(axis=0) - 1) < 1e-2)
# perform Shapiro-Wilk test for normality
for i in (0, 1):
_, pval = shapiro(samples[:, i])
assert pval > 0.9
# make sure samples are uncorrelated
cov = np.cov(samples.transpose())
assert np.abs(cov[0, 1]) < 1e-2
class TestMultivariateNormalQMC:
def test_validations(self):
message = r"Dimension of `engine` must be consistent"
with pytest.raises(ValueError, match=message):
qmc.MultivariateNormalQMC([0], engine=qmc.Sobol(d=2))
message = r"Dimension of `engine` must be consistent"
with pytest.raises(ValueError, match=message):
qmc.MultivariateNormalQMC([0, 0, 0], engine=qmc.Sobol(d=4))
message = r"`engine` must be an instance of..."
with pytest.raises(ValueError, match=message):
qmc.MultivariateNormalQMC([0, 0], engine=np.random.default_rng())
message = r"Covariance matrix not PSD."
with pytest.raises(ValueError, match=message):
qmc.MultivariateNormalQMC([0, 0], [[1, 2], [2, 1]])
message = r"Covariance matrix is not symmetric."
with pytest.raises(ValueError, match=message):
qmc.MultivariateNormalQMC([0, 0], [[1, 0], [2, 1]])
message = r"Dimension mismatch between mean and covariance."
with pytest.raises(ValueError, match=message):
qmc.MultivariateNormalQMC([0], [[1, 0], [0, 1]])
def test_MultivariateNormalQMCNonPD(self):
# try with non-pd but psd cov; should work
engine = qmc.MultivariateNormalQMC(
[0, 0, 0], [[1, 0, 1], [0, 1, 1], [1, 1, 2]],
)
assert engine._corr_matrix is not None
def test_MultivariateNormalQMC(self):
# d = 1 scalar
engine = qmc.MultivariateNormalQMC(mean=0, cov=5)
samples = engine.random()
assert_equal(samples.shape, (1, 1))
samples = engine.random(n=5)
assert_equal(samples.shape, (5, 1))
# d = 2 list
engine = qmc.MultivariateNormalQMC(mean=[0, 1], cov=[[1, 0], [0, 1]])
samples = engine.random()
assert_equal(samples.shape, (1, 2))
samples = engine.random(n=5)
assert_equal(samples.shape, (5, 2))
# d = 3 np.array
mean = np.array([0, 1, 2])
cov = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
engine = qmc.MultivariateNormalQMC(mean, cov)
samples = engine.random()
assert_equal(samples.shape, (1, 3))
samples = engine.random(n=5)
assert_equal(samples.shape, (5, 3))
def test_MultivariateNormalQMCInvTransform(self):
# d = 1 scalar
engine = qmc.MultivariateNormalQMC(mean=0, cov=5, inv_transform=True)
samples = engine.random()
assert_equal(samples.shape, (1, 1))
samples = engine.random(n=5)
assert_equal(samples.shape, (5, 1))
# d = 2 list
engine = qmc.MultivariateNormalQMC(
mean=[0, 1], cov=[[1, 0], [0, 1]], inv_transform=True,
)
samples = engine.random()
assert_equal(samples.shape, (1, 2))
samples = engine.random(n=5)
assert_equal(samples.shape, (5, 2))
# d = 3 np.array
mean = np.array([0, 1, 2])
cov = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
engine = qmc.MultivariateNormalQMC(mean, cov, inv_transform=True)
samples = engine.random()
assert_equal(samples.shape, (1, 3))
samples = engine.random(n=5)
assert_equal(samples.shape, (5, 3))
def test_MultivariateNormalQMCSeeded(self):
# test even dimension
rng = np.random.default_rng(180182791534511062935571481899241825000)
a = rng.standard_normal((2, 2))
A = a @ a.transpose() + np.diag(rng.random(2))
engine = qmc.MultivariateNormalQMC(np.array([0, 0]), A,
inv_transform=False, rng=rng)
samples = engine.random(n=2)
samples_expected = np.array([[-0.64419, -0.882413],
[0.837199, 2.045301]])
assert_allclose(samples, samples_expected, atol=1e-4)
# test odd dimension
rng = np.random.default_rng(180182791534511062935571481899241825000)
a = rng.standard_normal((3, 3))
A = a @ a.transpose() + np.diag(rng.random(3))
engine = qmc.MultivariateNormalQMC(np.array([0, 0, 0]), A,
inv_transform=False, rng=rng)
samples = engine.random(n=2)
samples_expected = np.array([[-0.693853, -1.265338, -0.088024],
[1.620193, 2.679222, 0.457343]])
assert_allclose(samples, samples_expected, atol=1e-4)
def test_MultivariateNormalQMCSeededInvTransform(self):
# test even dimension
rng = np.random.default_rng(224125808928297329711992996940871155974)
a = rng.standard_normal((2, 2))
A = a @ a.transpose() + np.diag(rng.random(2))
engine = qmc.MultivariateNormalQMC(
np.array([0, 0]), A, rng=rng, inv_transform=True
)
samples = engine.random(n=2)
samples_expected = np.array([[0.682171, -3.114233],
[-0.098463, 0.668069]])
assert_allclose(samples, samples_expected, atol=1e-4)
# test odd dimension
rng = np.random.default_rng(224125808928297329711992996940871155974)
a = rng.standard_normal((3, 3))
A = a @ a.transpose() + np.diag(rng.random(3))
engine = qmc.MultivariateNormalQMC(
np.array([0, 0, 0]), A, rng=rng, inv_transform=True
)
samples = engine.random(n=2)
samples_expected = np.array([[0.988061, -1.644089, -0.877035],
[-1.771731, 1.096988, 2.024744]])
assert_allclose(samples, samples_expected, atol=1e-4)
def test_MultivariateNormalQMCShapiro(self):
# test the standard case
rng = np.random.default_rng(188960007281846377164494575845971640)
engine = qmc.MultivariateNormalQMC(
mean=[0, 0], cov=[[1, 0], [0, 1]], rng=rng
)
samples = engine.random(n=256)
assert all(np.abs(samples.mean(axis=0)) < 1e-2)
assert all(np.abs(samples.std(axis=0) - 1) < 1e-2)
# perform Shapiro-Wilk test for normality
for i in (0, 1):
_, pval = shapiro(samples[:, i])
assert pval > 0.9
# make sure samples are uncorrelated
cov = np.cov(samples.transpose())
assert np.abs(cov[0, 1]) < 1e-2
# test the correlated, non-zero mean case
engine = qmc.MultivariateNormalQMC(
mean=[1.0, 2.0], cov=[[1.5, 0.5], [0.5, 1.5]], rng=rng
)
samples = engine.random(n=256)
assert all(np.abs(samples.mean(axis=0) - [1, 2]) < 1e-2)
assert all(np.abs(samples.std(axis=0) - np.sqrt(1.5)) < 1e-2)
# perform Shapiro-Wilk test for normality
for i in (0, 1):
_, pval = shapiro(samples[:, i])
assert pval > 0.9
# check covariance
cov = np.cov(samples.transpose())
assert np.abs(cov[0, 1] - 0.5) < 1e-2
def test_MultivariateNormalQMCShapiroInvTransform(self):
# test the standard case
rng = np.random.default_rng(200089821034563288698994840831440331329)
engine = qmc.MultivariateNormalQMC(
mean=[0, 0], cov=[[1, 0], [0, 1]], rng=rng, inv_transform=True
)
samples = engine.random(n=256)
assert all(np.abs(samples.mean(axis=0)) < 1e-2)
assert all(np.abs(samples.std(axis=0) - 1) < 1e-2)
# perform Shapiro-Wilk test for normality
for i in (0, 1):
_, pval = shapiro(samples[:, i])
assert pval > 0.9
# make sure samples are uncorrelated
cov = np.cov(samples.transpose())
assert np.abs(cov[0, 1]) < 1e-2
# test the correlated, non-zero mean case
engine = qmc.MultivariateNormalQMC(
mean=[1.0, 2.0],
cov=[[1.5, 0.5], [0.5, 1.5]],
rng=rng,
inv_transform=True,
)
samples = engine.random(n=256)
assert all(np.abs(samples.mean(axis=0) - [1, 2]) < 1e-2)
assert all(np.abs(samples.std(axis=0) - np.sqrt(1.5)) < 1e-2)
# perform Shapiro-Wilk test for normality
for i in (0, 1):
_, pval = shapiro(samples[:, i])
assert pval > 0.9
# check covariance
cov = np.cov(samples.transpose())
assert np.abs(cov[0, 1] - 0.5) < 1e-2
def test_MultivariateNormalQMCDegenerate(self):
# X, Y iid standard Normal and Z = X + Y, random vector (X, Y, Z)
rng = np.random.default_rng(16320637417581448357869821654290448620)
engine = qmc.MultivariateNormalQMC(
mean=[0.0, 0.0, 0.0],
cov=[[1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [1.0, 1.0, 2.0]],
rng=rng,
)
samples = engine.random(n=512)
assert all(np.abs(samples.mean(axis=0)) < 1e-2)
assert np.abs(np.std(samples[:, 0]) - 1) < 1e-2
assert np.abs(np.std(samples[:, 1]) - 1) < 1e-2
assert np.abs(np.std(samples[:, 2]) - np.sqrt(2)) < 1e-2
for i in (0, 1, 2):
_, pval = shapiro(samples[:, i])
assert pval > 0.8
cov = np.cov(samples.transpose())
assert np.abs(cov[0, 1]) < 1e-2
assert np.abs(cov[0, 2] - 1) < 1e-2
# check to see if X + Y = Z almost exactly
assert all(np.abs(samples[:, 0] + samples[:, 1] - samples[:, 2])
< 1e-5)
class TestLloyd:
def test_lloyd(self):
# quite sensible seed as it can go up before going further down
rng = np.random.RandomState(1809831)
sample = rng.uniform(0, 1, size=(128, 2))
base_l1 = _l1_norm(sample)
base_l2 = l2_norm(sample)
for _ in range(4):
sample_lloyd = _lloyd_centroidal_voronoi_tessellation(
sample, maxiter=1,
)
curr_l1 = _l1_norm(sample_lloyd)
curr_l2 = l2_norm(sample_lloyd)
# higher is better for the distance measures
assert base_l1 < curr_l1
assert base_l2 < curr_l2
base_l1 = curr_l1
base_l2 = curr_l2
sample = sample_lloyd
def test_lloyd_non_mutating(self):
"""
Verify that the input samples are not mutated in place and that they do
not share memory with the output.
"""
sample_orig = np.array([[0.1, 0.1],
[0.1, 0.2],
[0.2, 0.1],
[0.2, 0.2]])
sample_copy = sample_orig.copy()
new_sample = _lloyd_centroidal_voronoi_tessellation(
sample=sample_orig
)
assert_allclose(sample_orig, sample_copy)
assert not np.may_share_memory(sample_orig, new_sample)
def test_lloyd_errors(self):
with pytest.raises(ValueError, match=r"`sample` is not a 2D array"):
sample = [0, 1, 0.5]
_lloyd_centroidal_voronoi_tessellation(sample)
msg = r"`sample` dimension is not >= 2"
with pytest.raises(ValueError, match=msg):
sample = [[0], [0.4], [1]]
_lloyd_centroidal_voronoi_tessellation(sample)
msg = r"`sample` is not in unit hypercube"
with pytest.raises(ValueError, match=msg):
sample = [[-1.1, 0], [0.1, 0.4], [1, 2]]
_lloyd_centroidal_voronoi_tessellation(sample)
# mindist
def l2_norm(sample):
return distance.pdist(sample).min()
@pytest.mark.parametrize('engine', [qmc.Halton, qmc.Sobol,
qmc.LatinHypercube, qmc.PoissonDisk])
def test_deterministic(engine):
seed_number = 2359834584
rng = np.random.RandomState(seed_number)
res1 = engine(d=1, seed=rng).random(4)
rng = np.random.RandomState(seed_number)
res2 = engine(d=1, seed=rng).random(4)
assert_equal(res1, res2)
rng = np.random.default_rng(seed_number)
res1 = engine(d=1, seed=rng).random(4)
res2 = engine(d=1, rng=seed_number).random(4)
assert_equal(res1, res2)
rng = np.random.default_rng(seed_number)
res3 = engine(d=1, rng=rng).random(4)
assert_equal(res2, res1)
assert_equal(res3, res1)
message = "got multiple values for argument now known as `rng`"
with pytest.raises(TypeError, match=message):
engine(d=1, rng=seed_number, seed=seed_number)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412import pytest
import numpy as np
from scipy import stats
from scipy.stats._quantile import _xp_searchsorted
from scipy._lib._array_api import (
xp_default_dtype,
is_numpy,
is_torch,
is_jax,
make_xp_test_case,
SCIPY_ARRAY_API,
xp_size,
xp_copy,
)
from scipy._lib._array_api_no_0d import xp_assert_close, xp_assert_equal
from scipy._lib._util import _apply_over_batch
skip_xp_backends = pytest.mark.skip_xp_backends
lazy_xp_modules = [stats]
@_apply_over_batch(('x', 1), ('p', 1))
def quantile_reference_last_axis(x, p, nan_policy, method):
if nan_policy == 'omit':
x = x[~np.isnan(x)]
p_mask = np.isnan(p)
p = p.copy()
p[p_mask] = 0.5
if method == 'harrell-davis':
# hdquantiles returns masked element if length along axis is 1 (bug)
res = (np.full_like(p, x[0]) if x.size == 1
else stats.mstats.hdquantiles(x, p).data)
elif method.startswith('round'):
res = winsor_reference_1d(np.sort(x), p, method)
else:
res = np.quantile(x, p, method=method)
res = np.asarray(res)
if nan_policy == 'propagate' and np.any(np.isnan(x)):
res[:] = np.nan
res[p_mask] = np.nan
return res
@np.vectorize(excluded={0, 2}) # type: ignore[call-arg]
def winsor_reference_1d(y, p, method):
# Adapted directly from the documentation
# Note: `y` is the sorted data array
n = len(y)
if method == 'round_nearest':
j = int(np.round(p * n) if p < 0.5 else np.round(n * p - 1))
elif method == 'round_outward':
j = int(np.floor(p * n) if p < 0.5 else np.ceil(n * p - 1))
elif method == 'round_inward':
j = int(np.ceil(p * n) if p < 0.5 else np.floor(n * p - 1))
return y[j]
def quantile_reference(x, p, *, axis, nan_policy, keepdims, method):
x, p = np.moveaxis(x, axis, -1), np.moveaxis(np.atleast_1d(p), axis, -1)
res = quantile_reference_last_axis(x, p, nan_policy, method)
res = np.moveaxis(res, -1, axis)
if not keepdims:
res = np.squeeze(res, axis=axis)
return res
@make_xp_test_case(stats.quantile)
class TestQuantile:
def test_input_validation(self, xp):
x = xp.asarray([1, 2, 3])
p = xp.asarray(0.5)
message = "`x` must have real dtype."
with pytest.raises(ValueError, match=message):
stats.quantile(xp.asarray([True, False]), p)
with pytest.raises(ValueError):
stats.quantile(xp.asarray([1+1j, 2]), p)
message = "`p` must have real floating dtype."
with pytest.raises(ValueError, match=message):
stats.quantile(x, xp.asarray([0, 1]))
message = "`weights` must have real dtype."
with pytest.raises(ValueError, match=message):
stats.quantile(x, p, weights=xp.astype(x, xp.complex64))
message = "`axis` must be an integer or None."
with pytest.raises(ValueError, match=message):
stats.quantile(x, p, axis=0.5)
with pytest.raises(ValueError, match=message):
stats.quantile(x, p, axis=(0, -1))
message = "`axis` is not compatible with the shapes of the inputs."
with pytest.raises(ValueError, match=message):
stats.quantile(x, p, axis=2)
if not is_jax(xp): # no data-dependent input validation for lazy arrays
message = "The input contains nan values"
with pytest.raises(ValueError, match=message):
stats.quantile(xp.asarray([xp.nan, 1, 2]), p, nan_policy='raise')
message = "`method` must be one of..."
with pytest.raises(ValueError, match=message):
stats.quantile(x, p, method='a duck')
message = "`method='harrell-davis'` does not support `weights`."
with pytest.raises(ValueError, match=message):
stats.quantile(x, p, weights=x, method='harrell-davis')
message = "`method='round_nearest'` does not support `weights`."
with pytest.raises(ValueError, match=message):
stats.quantile(x, p, weights=x, method='round_nearest')
message = "If specified, `keepdims` must be True or False."
with pytest.raises(ValueError, match=message):
stats.quantile(x, p, keepdims=42)
message = "`keepdims` may be False only if the length of `p` along `axis` is 1."
with pytest.raises(ValueError, match=message):
stats.quantile(x, xp.asarray([0.5, 0.6]), keepdims=False)
def _get_weights_x_rep(self, x, axis, rng):
x = np.swapaxes(x, axis, -1)
ndim = x.ndim
x = np.atleast_2d(x)
counts = rng.integers(10, size=x.shape[-1], dtype=np.int32)
x_rep = []
weights = []
for x_ in x:
counts_ = rng.permuted(counts)
x_rep.append(np.repeat(x_, counts_))
weights.append(counts_)
x_rep, weights = np.stack(x_rep), np.stack(weights)
if ndim < 2:
x_rep, weights = np.squeeze(x_rep, axis=0), np.squeeze(weights, axis=0)
x_rep, weights = np.swapaxes(x_rep, -1, axis), np.swapaxes(weights, -1, axis)
weights = np.asarray(weights, dtype=x.dtype)
return weights, x_rep
@skip_xp_backends(cpu_only=True, reason="PyTorch doesn't have `betainc`.",
exceptions=['cupy'])
@pytest.mark.parametrize('method',
['inverted_cdf', 'averaged_inverted_cdf', 'closest_observation',
'hazen', 'interpolated_inverted_cdf', 'linear',
'median_unbiased', 'normal_unbiased', 'weibull',
'harrell-davis', 'round_nearest', 'round_outward', 'round_inward',
'_lower', '_higher', '_midpoint', '_nearest'])
@pytest.mark.parametrize('shape_x, shape_p, axis',
[(10, None, -1), (10, 10, -1), (10, (2, 3), -1), ((10, 2), None, 0)])
@pytest.mark.parametrize('weights', [False, True])
def test_against_reference(self, method, shape_x, shape_p, axis, weights, xp):
# Test all methods with various data shapes
if weights and (method.startswith('_') or method.startswith('round')
or method=='harrell-davis'):
pytest.skip('`weights` not supported by private (legacy) methods.')
dtype = xp_default_dtype(xp)
rng = np.random.default_rng(23458924568734956)
x = rng.random(size=shape_x)
p = rng.random(size=shape_p)
if weights:
weights, x_rep = self._get_weights_x_rep(x, axis, rng)
else:
weights, x_rep = None, x
ref = quantile_reference(
x_rep, p, method=method[1:] if method.startswith('_') else method,
axis=axis, nan_policy='propagate', keepdims=shape_p is not None)
x, p = xp.asarray(x, dtype=dtype), xp.asarray(p, dtype=dtype)
weights = weights if weights is None else xp.asarray(weights, dtype=dtype)
res = stats.quantile(x, p, method=method, weights=weights, axis=axis)
xp_assert_close(res, xp.asarray(ref, dtype=dtype))
@pytest.mark.filterwarnings("ignore:torch.searchsorted:UserWarning")
@skip_xp_backends(cpu_only=True, reason="PyTorch doesn't have `betainc`.",
exceptions=['cupy', 'jax.numpy'])
@pytest.mark.parametrize('axis', [0, 1])
@pytest.mark.parametrize('keepdims', [False, True])
@pytest.mark.parametrize('nan_policy', ['omit', 'propagate', 'marray'])
@pytest.mark.parametrize('dtype', ['float32', 'float64'])
@pytest.mark.parametrize('method', ['linear', 'harrell-davis', 'round_nearest'])
@pytest.mark.parametrize('weights', [False, True])
def test_against_reference_2(self, axis, keepdims, nan_policy,
dtype, method, weights, xp):
# Test some methods with various combinations of arguments
if is_jax(xp) and nan_policy == 'marray': # mdhaber/marray#146
pytest.skip("`marray` currently incompatible with JAX")
if weights and method in {'harrell-davis', 'round_nearest'}:
pytest.skip("These methods don't yet support weights")
rng = np.random.default_rng(23458924568734956)
shape = (5, 6)
x = rng.random(size=shape).astype(dtype)
p = rng.random(size=shape).astype(dtype)
mask = rng.random(size=shape) > 0.8
assert np.any(mask)
x[mask] = np.nan
if not keepdims:
p = np.mean(p, axis=axis, keepdims=True)
# inject p = 0 and p = 1 to test edge cases
# Currently would fail with CuPy/JAX (cupy/cupy#8934, jax-ml/jax#21900);
# remove the `if` when those are resolved.
if is_numpy(xp):
p0 = p.ravel()
p0[1] = 0.
p0[-2] = 1.
dtype = getattr(xp, dtype)
if weights:
weights, x_rep = self._get_weights_x_rep(x, axis, rng)
weights = weights if weights is None else xp.asarray(weights)
else:
weights, x_rep = None, x
if nan_policy == 'marray':
if not SCIPY_ARRAY_API:
pytest.skip("MArray is only available if SCIPY_ARRAY_API=1")
if weights is not None:
pytest.skip("MArray is not yet compatible with weights")
marray = pytest.importorskip('marray')
kwargs = dict(axis=axis, keepdims=keepdims, method=method)
mxp = marray._get_namespace(xp)
x_mp = mxp.asarray(x, mask=mask)
weights = weights if weights is None else mxp.asarray(weights)
res = stats.quantile(x_mp, mxp.asarray(p), weights=weights, **kwargs)
ref = quantile_reference(x_rep, p, nan_policy='omit', **kwargs)
xp_assert_close(res.data, xp.asarray(ref, dtype=dtype))
return
kwargs = dict(axis=axis, keepdims=keepdims,
nan_policy=nan_policy, method=method)
res = stats.quantile(xp.asarray(x), xp.asarray(p), weights=weights, **kwargs)
ref = quantile_reference(x_rep, p, **kwargs)
xp_assert_close(res, xp.asarray(ref, dtype=dtype))
def test_integer_input_output_dtype(self, xp):
res = stats.quantile(xp.arange(10, dtype=xp.int64), 0.5)
assert res.dtype == xp_default_dtype(xp)
@pytest.mark.parametrize('x, p, ref, kwargs',
[([], 0.5, np.nan, {}),
([1, 2, 3], [-1, 0, 1, 1.5, np.nan], [np.nan, 1, 3, np.nan, np.nan], {}),
([1, 2, 3], [], [], {}),
([[np.nan, 2]], 0.5, [np.nan, 2], {'nan_policy': 'omit'}),
([[], []], 0.5, np.full(2, np.nan), {'axis': -1}),
([[], []], 0.5, np.zeros((0,)), {'axis': 0, 'keepdims': False}),
([[], []], 0.5, np.zeros((1, 0)), {'axis': 0, 'keepdims': True}),
([], [0.5, 0.6], np.full(2, np.nan), {}),
(np.arange(1, 28).reshape((3, 3, 3)), 0.5, [[[14.]]],
{'axis': None, 'keepdims': True}),
([[1, 2], [3, 4]], [0.25, 0.5, 0.75], [[1.75, 2.5, 3.25]],
{'axis': None, 'keepdims': True}),
# Known issue:
# ([1, 2, 3], 0.5, 2., {'weights': [0, 0, 0]})
# See https://github.com/scipy/scipy/pull/23941#issuecomment-3503554361
])
def test_edge_cases(self, x, p, ref, kwargs, xp):
default_dtype = xp_default_dtype(xp)
x, p, ref = xp.asarray(x), xp.asarray(p), xp.asarray(ref, dtype=default_dtype)
res = stats.quantile(x, p, **kwargs)
xp_assert_equal(res, ref)
@pytest.mark.parametrize('axis', [0, 1, 2])
@pytest.mark.parametrize('keepdims', [False, True])
def test_size_0(self, axis, keepdims, xp):
shape = [3, 4, 0]
out_shape = shape.copy()
if keepdims:
out_shape[axis] = 1
else:
out_shape.pop(axis)
res = stats.quantile(xp.zeros(tuple(shape)), 0.5, axis=axis, keepdims=keepdims)
assert res.shape == tuple(out_shape)
@pytest.mark.parametrize('method',
['inverted_cdf', 'averaged_inverted_cdf', 'closest_observation',
'_lower', '_higher', '_midpoint', '_nearest'])
def test_transition(self, method, xp):
# test that values of discontinuous estimators are correct when
# p*n + m - 1 is integral.
if method == 'closest_observation' and np.__version__ < '2.0.1':
pytest.skip('Bug in np.quantile (numpy/numpy#26656) fixed in 2.0.1')
x = np.arange(8., dtype=np.float64)
p = np.arange(0, 1.03125, 0.03125)
res = stats.quantile(xp.asarray(x), xp.asarray(p), method=method)
ref = np.quantile(x, p, method=method[1:] if method.startswith('_') else method)
xp_assert_equal(res, xp.asarray(ref, dtype=xp.float64))
@pytest.mark.parametrize('zero_weights', [False, True])
def test_weights_against_numpy(self, zero_weights, xp):
if is_numpy(xp) and xp.__version__ < "2.0":
pytest.skip('`weights` not supported by NumPy < 2.0.')
dtype = xp_default_dtype(xp)
rng = np.random.default_rng(85468924398205602)
method = 'inverted_cdf'
x = rng.random(size=100)
weights = rng.random(size=100)
if zero_weights:
weights[weights < 0.5] = 0
p = np.linspace(0., 1., 300)
res = stats.quantile(xp.asarray(x, dtype=dtype), xp.asarray(p, dtype=dtype),
method=method, weights=xp.asarray(weights, dtype=dtype))
ref = np.quantile(x, p, method=method, weights=weights)
xp_assert_close(res, xp.asarray(ref, dtype=dtype))
@pytest.mark.parametrize('method',
['inverted_cdf', 'averaged_inverted_cdf', 'closest_observation', 'hazen',
'interpolated_inverted_cdf', 'linear','median_unbiased', 'normal_unbiased',
'weibull'])
def test_zero_weights(self, method, xp):
rng = np.random.default_rng(85468924398205602)
# test 1-D versus eliminating zero-weighted values
n = 100
x = xp.asarray(rng.random(size=n))
x0 = xp_copy(x)
p = xp.asarray(rng.random(size=n))
i_zero = xp.asarray(rng.random(size=n) < 0.1)
weights = xp.asarray(rng.random(size=n))
weights = xp.where(i_zero, 0., weights)
res = stats.quantile(x, p, weights=weights, method=method)
ref = stats.quantile(x[~i_zero], p, weights=weights[~i_zero], method=method)
xp_assert_close(res, ref)
xp_assert_equal(x, x0) # no input mutation
# test multi-D versus `nan_policy='omit'`
shape = (5, 100)
x = xp.asarray(rng.random(size=shape))
x0 = xp_copy(x)
p = xp.asarray(rng.random(size=shape))
i_zero = xp.asarray(rng.random(size=shape) < 0.1)
weights = xp.asarray(rng.random(size=shape))
x_nanned = xp.where(i_zero, xp.nan, x)
weights_zeroed = xp.where(i_zero, 0., weights)
res = stats.quantile(x, p, weights=weights_zeroed, method=method, axis=-1)
ref = stats.quantile(x_nanned, p, weights=weights,
nan_policy='omit', method=method, axis=-1)
xp_assert_close(res, ref)
xp_assert_equal(x, x0) # no input mutation
@pytest.mark.filterwarnings("ignore:torch.searchsorted:UserWarning")
@pytest.mark.parametrize('method',
['inverted_cdf', 'averaged_inverted_cdf', 'closest_observation', 'hazen',
'interpolated_inverted_cdf', 'linear','median_unbiased', 'normal_unbiased',
'weibull'])
@pytest.mark.parametrize('shape', [50, (50, 3)])
def test_unity_weights(self, method, shape, xp):
# Check that result is unchanged if all weights are `1.0`
rng = np.random.default_rng(28546892439820560)
x = xp.asarray(rng.random(size=shape))
p = xp.asarray(rng.random(size=shape))
weights = xp.ones_like(x)
res = stats.quantile(x, p, weights=weights, method=method)
ref = stats.quantile(x, p, method=method)
xp_assert_close(res, ref)
@_apply_over_batch(('a', 1), ('v', 1))
def np_searchsorted(a, v, side):
return np.searchsorted(a, v, side=side)
@make_xp_test_case(_xp_searchsorted)
class Test_XPSearchsorted:
@pytest.mark.parametrize('side', ['left', 'right'])
@pytest.mark.parametrize('ties', [False, True])
@pytest.mark.parametrize('shape', [0, 1, 2, 10, 11, 1000, 10001,
(2, 0), (0, 2), (2, 10), (2, 3, 11)])
@pytest.mark.parametrize('nans_x', [False, True])
@pytest.mark.parametrize('infs_x', [False, True])
def test_nd(self, side, ties, shape, nans_x, infs_x, xp):
if nans_x and is_torch(xp):
pytest.skip('torch sorts NaNs differently')
rng = np.random.default_rng(945298725498274853)
if ties:
x = rng.integers(5, size=shape)
else:
x = rng.random(shape)
# float32 is to accommodate JAX - nextafter with `float64` is too small?
x = np.asarray(x, dtype=np.float32)
xr = np.nextafter(x, np.inf)
xl = np.nextafter(x, -np.inf)
x_ = np.asarray([-np.inf, np.inf, np.nan])
x_ = np.broadcast_to(x_, x.shape[:-1] + (3,))
y = rng.permuted(np.concatenate((xl, x, xr, x_), axis=-1), axis=-1)
if nans_x:
mask = rng.random(shape) < 0.1
x[mask] = np.nan
if infs_x:
mask = rng.random(shape) < 0.1
x[mask] = -np.inf
mask = rng.random(shape) > 0.9
x[mask] = np.inf
x = np.sort(x, axis=-1)
x, y = np.asarray(x, dtype=np.float64), np.asarray(y, dtype=np.float64)
xp_default_int = xp.asarray(1).dtype
if xp_size(x) == 0 and x.ndim > 0 and x.shape[-1] != 0:
ref = xp.empty(x.shape[:-1] + (y.shape[-1],), dtype=xp_default_int)
else:
ref = xp.asarray(np_searchsorted(x, y, side=side), dtype=xp_default_int)
x, y = xp.asarray(x), xp.asarray(y)
res = _xp_searchsorted(x, y, side=side)
xp_assert_equal(res, ref)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348import numpy as np
from numpy.testing import assert_equal, assert_array_equal
import pytest
from scipy import stats
from scipy.conftest import skip_xp_invalid_arg
from scipy.stats import rankdata, tiecorrect
from scipy._lib._array_api import xp_assert_equal, make_xp_test_case
skip_xp_backends = pytest.mark.skip_xp_backends
class TestTieCorrect:
def test_empty(self):
"""An empty array requires no correction, should return 1.0."""
ranks = np.array([], dtype=np.float64)
c = tiecorrect(ranks)
assert_equal(c, 1.0)
def test_one(self):
"""A single element requires no correction, should return 1.0."""
ranks = np.array([1.0], dtype=np.float64)
c = tiecorrect(ranks)
assert_equal(c, 1.0)
def test_no_correction(self):
"""Arrays with no ties require no correction."""
ranks = np.arange(2.0)
c = tiecorrect(ranks)
assert_equal(c, 1.0)
ranks = np.arange(3.0)
c = tiecorrect(ranks)
assert_equal(c, 1.0)
def test_basic(self):
"""Check a few basic examples of the tie correction factor."""
# One tie of two elements
ranks = np.array([1.0, 2.5, 2.5])
c = tiecorrect(ranks)
T = 2.0
N = ranks.size
expected = 1.0 - (T**3 - T) / (N**3 - N)
assert_equal(c, expected)
# One tie of two elements (same as above, but tie is not at the end)
ranks = np.array([1.5, 1.5, 3.0])
c = tiecorrect(ranks)
T = 2.0
N = ranks.size
expected = 1.0 - (T**3 - T) / (N**3 - N)
assert_equal(c, expected)
# One tie of three elements
ranks = np.array([1.0, 3.0, 3.0, 3.0])
c = tiecorrect(ranks)
T = 3.0
N = ranks.size
expected = 1.0 - (T**3 - T) / (N**3 - N)
assert_equal(c, expected)
# Two ties, lengths 2 and 3.
ranks = np.array([1.5, 1.5, 4.0, 4.0, 4.0])
c = tiecorrect(ranks)
T1 = 2.0
T2 = 3.0
N = ranks.size
expected = 1.0 - ((T1**3 - T1) + (T2**3 - T2)) / (N**3 - N)
assert_equal(c, expected)
def test_overflow(self):
ntie, k = 2000, 5
a = np.repeat(np.arange(k), ntie)
n = a.size # ntie * k
out = tiecorrect(rankdata(a))
assert_equal(out, 1.0 - k * (ntie**3 - ntie) / float(n**3 - n))
@make_xp_test_case(stats.rankdata)
class TestRankData:
def desired_dtype(self, method='average', has_nans=False, *, xp):
if has_nans:
return xp.asarray(1.).dtype
return xp.asarray(1.).dtype if method=='average' else xp.asarray(1).dtype
def test_empty(self, xp):
"""stats.rankdata of empty array should return an empty array."""
a = xp.asarray([], dtype=xp.int64)
r = rankdata(a)
xp_assert_equal(r, xp.asarray([], dtype=self.desired_dtype(xp=xp)))
def test_list(self):
# test that NumPy still accepts lists
r = rankdata([])
assert_array_equal(r, np.array([]))
r = rankdata([40, 10, 30, 10, 50])
assert_equal(r, [4.0, 1.5, 3.0, 1.5, 5.0])
@pytest.mark.parametrize("shape", [(0, 1, 2)])
@pytest.mark.parametrize("axis", [None, *range(3)])
def test_empty_multidim(self, shape, axis, xp):
a = xp.empty(shape, dtype=xp.int64)
r = rankdata(a, axis=axis)
expected_shape = (0,) if axis is None else shape
xp_assert_equal(r, xp.empty(expected_shape, dtype=self.desired_dtype(xp=xp)))
def test_one(self, xp):
"""Check stats.rankdata with an array of length 1."""
data = [100]
a = xp.asarray(data, dtype=xp.int64)
r = rankdata(a)
xp_assert_equal(r, xp.asarray([1.0], dtype=self.desired_dtype(xp=xp)))
def test_basic(self, xp):
"""Basic tests of stats.rankdata."""
desired_dtype = self.desired_dtype(xp=xp)
data = [100, 10, 50]
expected = xp.asarray([3.0, 1.0, 2.0], dtype=desired_dtype)
a = xp.asarray(data, dtype=xp.int64)
r = rankdata(a)
xp_assert_equal(r, expected)
data = [40, 10, 30, 10, 50]
expected = xp.asarray([4.0, 1.5, 3.0, 1.5, 5.0], dtype=desired_dtype)
a = xp.asarray(data, dtype=xp.int64)
r = rankdata(a)
xp_assert_equal(r, expected)
data = [20, 20, 20, 10, 10, 10]
expected = xp.asarray([5.0, 5.0, 5.0, 2.0, 2.0, 2.0], dtype=desired_dtype)
a = xp.asarray(data, dtype=xp.int64)
r = rankdata(a)
xp_assert_equal(r, expected)
# # The docstring states explicitly that the argument is flattened.
a2d = xp.reshape(a, (2, 3))
r = rankdata(a2d)
xp_assert_equal(r, expected)
@skip_xp_invalid_arg
def test_rankdata_object_string(self):
def min_rank(a):
return [1 + sum(i < j for i in a) for j in a]
def max_rank(a):
return [sum(i <= j for i in a) for j in a]
def ordinal_rank(a):
return min_rank([(x, i) for i, x in enumerate(a)])
def average_rank(a):
return [(i + j) / 2.0 for i, j in zip(min_rank(a), max_rank(a))]
def dense_rank(a):
b = np.unique(a)
return [1 + sum(i < j for i in b) for j in a]
rankf = dict(min=min_rank, max=max_rank, ordinal=ordinal_rank,
average=average_rank, dense=dense_rank)
def check_ranks(a):
for method in 'min', 'max', 'dense', 'ordinal', 'average':
out = rankdata(a, method=method)
assert_array_equal(out, rankf[method](a))
val = ['foo', 'bar', 'qux', 'xyz', 'abc', 'efg', 'ace', 'qwe', 'qaz']
check_ranks(np.random.choice(val, 200))
check_ranks(np.random.choice(val, 200).astype('object'))
val = np.array([0, 1, 2, 2.718, 3, 3.141], dtype='object')
check_ranks(np.random.choice(val, 200).astype('object'))
@pytest.mark.skip_xp_backends("torch", reason="`take_along_axis` fails with uint64")
def test_large_uint(self, xp):
data = xp.asarray([2**60, 2**60+1], dtype=xp.uint64)
r = rankdata(data)
xp_assert_equal(r, xp.asarray([1.0, 2.0], dtype=self.desired_dtype(xp=xp)))
def test_large_int(self, xp):
data = xp.asarray([2**60, 2**60+1], dtype=xp.int64)
r = rankdata(data)
xp_assert_equal(r, xp.asarray([1.0, 2.0], dtype=self.desired_dtype(xp=xp)))
data = xp.asarray([2**60, -2**60+1], dtype=xp.int64)
r = rankdata(data)
xp_assert_equal(r, xp.asarray([2.0, 1.0], dtype=self.desired_dtype(xp=xp)))
@pytest.mark.parametrize('n', [10000, 100000, 1000000])
def test_big_tie(self, n, xp):
data = xp.ones(n)
r = rankdata(data)
expected_rank = 0.5 * (n + 1)
ref = xp.asarray(expected_rank * data, dtype=self.desired_dtype(xp=xp))
xp_assert_equal(r, ref)
def test_axis(self, xp):
data = xp.asarray([[0, 2, 1], [4, 2, 2]])
expected0 = xp.asarray([[1., 1.5, 1.], [2., 1.5, 2.]])
r0 = rankdata(data, axis=0)
xp_assert_equal(r0, expected0)
expected1 = xp.asarray([[1., 3., 2.], [3., 1.5, 1.5]])
r1 = rankdata(data, axis=1)
xp_assert_equal(r1, expected1)
methods= ["average", "min", "max", "dense", "ordinal"]
@pytest.mark.parametrize("axis", [0, 1])
@pytest.mark.parametrize("method", methods)
def test_size_0_axis(self, axis, method, xp):
shape = (3, 0)
desired_dtype = self.desired_dtype(method, xp=xp)
data = xp.zeros(shape)
r = rankdata(data, method=method, axis=axis)
assert_equal(r.shape, shape)
assert_equal(r.dtype, desired_dtype)
xp_assert_equal(r, xp.empty(shape, dtype=desired_dtype))
@pytest.mark.parametrize('axis', range(3))
@pytest.mark.parametrize('method', methods)
def test_nan_policy_omit_3d(self, axis, method):
shape = (20, 21, 22)
rng = np.random.RandomState(23983242)
a = rng.random(size=shape)
i = rng.random(size=shape) < 0.4
j = rng.random(size=shape) < 0.1
k = rng.random(size=shape) < 0.1
a[i] = np.nan
a[j] = -np.inf
a[k] - np.inf
def rank_1d_omit(a, method):
out = np.zeros_like(a)
i = np.isnan(a)
a_compressed = a[~i]
res = rankdata(a_compressed, method)
out[~i] = res
out[i] = np.nan
return out
def rank_omit(a, method, axis):
return np.apply_along_axis(lambda a: rank_1d_omit(a, method),
axis, a)
res = rankdata(a, method, axis=axis, nan_policy='omit')
res0 = rank_omit(a, method, axis=axis)
assert_array_equal(res, res0)
def test_nan_policy_2d_axis_none(self):
# 2 2d-array test with axis=None
data = [[0, np.nan, 3],
[4, 2, np.nan],
[1, 2, 2]]
assert_array_equal(rankdata(data, axis=None, nan_policy='omit'),
[1., np.nan, 6., 7., 4., np.nan, 2., 4., 4.])
assert_array_equal(rankdata(data, axis=None, nan_policy='propagate'),
[np.nan, np.nan, np.nan, np.nan, np.nan, np.nan,
np.nan, np.nan, np.nan])
def test_nan_policy_raise(self):
# 1 1d-array test
data = [0, 2, 3, -2, np.nan, np.nan]
with pytest.raises(ValueError, match="The input contains nan"):
rankdata(data, nan_policy='raise')
# 2 2d-array test
data = [[0, np.nan, 3],
[4, 2, np.nan],
[np.nan, 2, 2]]
with pytest.raises(ValueError, match="The input contains nan"):
rankdata(data, axis=0, nan_policy="raise")
with pytest.raises(ValueError, match="The input contains nan"):
rankdata(data, axis=1, nan_policy="raise")
def test_nan_policy_propagate(self):
# 1 1d-array test
data = [0, 2, 3, -2, np.nan, np.nan]
assert_array_equal(rankdata(data, nan_policy='propagate'),
[np.nan, np.nan, np.nan, np.nan, np.nan, np.nan])
# 2 2d-array test
data = [[0, np.nan, 3],
[4, 2, np.nan],
[1, 2, 2]]
assert_array_equal(rankdata(data, axis=0, nan_policy='propagate'),
[[1, np.nan, np.nan],
[3, np.nan, np.nan],
[2, np.nan, np.nan]])
assert_array_equal(rankdata(data, axis=1, nan_policy='propagate'),
[[np.nan, np.nan, np.nan],
[np.nan, np.nan, np.nan],
[1, 2.5, 2.5]])
_rankdata_cases = (
# values, method, expected
([], 'average', []),
([], 'min', []),
([], 'max', []),
([], 'dense', []),
([], 'ordinal', []),
#
([100], 'average', [1.0]),
([100], 'min', [1.0]),
([100], 'max', [1.0]),
([100], 'dense', [1.0]),
([100], 'ordinal', [1.0]),
#
([100, 100, 100], 'average', [2.0, 2.0, 2.0]),
([100, 100, 100], 'min', [1.0, 1.0, 1.0]),
([100, 100, 100], 'max', [3.0, 3.0, 3.0]),
([100, 100, 100], 'dense', [1.0, 1.0, 1.0]),
([100, 100, 100], 'ordinal', [1.0, 2.0, 3.0]),
#
([100, 300, 200], 'average', [1.0, 3.0, 2.0]),
([100, 300, 200], 'min', [1.0, 3.0, 2.0]),
([100, 300, 200], 'max', [1.0, 3.0, 2.0]),
([100, 300, 200], 'dense', [1.0, 3.0, 2.0]),
([100, 300, 200], 'ordinal', [1.0, 3.0, 2.0]),
#
([100, 200, 300, 200], 'average', [1.0, 2.5, 4.0, 2.5]),
([100, 200, 300, 200], 'min', [1.0, 2.0, 4.0, 2.0]),
([100, 200, 300, 200], 'max', [1.0, 3.0, 4.0, 3.0]),
([100, 200, 300, 200], 'dense', [1.0, 2.0, 3.0, 2.0]),
([100, 200, 300, 200], 'ordinal', [1.0, 2.0, 4.0, 3.0]),
#
([100, 200, 300, 200, 100], 'average', [1.5, 3.5, 5.0, 3.5, 1.5]),
([100, 200, 300, 200, 100], 'min', [1.0, 3.0, 5.0, 3.0, 1.0]),
([100, 200, 300, 200, 100], 'max', [2.0, 4.0, 5.0, 4.0, 2.0]),
([100, 200, 300, 200, 100], 'dense', [1.0, 2.0, 3.0, 2.0, 1.0]),
([100, 200, 300, 200, 100], 'ordinal', [1.0, 3.0, 5.0, 4.0, 2.0]),
#
([10] * 30, 'ordinal', np.arange(1.0, 31.0)),
)
@pytest.mark.parametrize('case', _rankdata_cases)
def test_cases(self, case, xp):
values, method, expected = case
r = rankdata(xp.asarray(values), method=method)
ref = xp.asarray(expected, dtype=self.desired_dtype(method, xp=xp))
xp_assert_equal(r, ref)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495import pytest
import numpy as np
from numpy.testing import assert_allclose, assert_equal
from scipy.stats.contingency import relative_risk
# Test just the calculation of the relative risk, including edge
# cases that result in a relative risk of 0, inf or nan.
@pytest.mark.parametrize(
'exposed_cases, exposed_total, control_cases, control_total, expected_rr',
[(1, 4, 3, 8, 0.25 / 0.375),
(0, 10, 5, 20, 0),
(0, 10, 0, 20, np.nan),
(5, 15, 0, 20, np.inf)]
)
def test_relative_risk(exposed_cases, exposed_total,
control_cases, control_total, expected_rr):
result = relative_risk(exposed_cases, exposed_total,
control_cases, control_total)
assert_allclose(result.relative_risk, expected_rr, rtol=1e-13)
def test_relative_risk_confidence_interval():
result = relative_risk(exposed_cases=16, exposed_total=128,
control_cases=24, control_total=256)
rr = result.relative_risk
ci = result.confidence_interval(confidence_level=0.95)
# The corresponding calculation in R using the epitools package.
#
# > library(epitools)
# > c <- matrix(c(232, 112, 24, 16), nrow=2)
# > result <- riskratio(c)
# > result$measure
# risk ratio with 95% C.I.
# Predictor estimate lower upper
# Exposed1 1.000000 NA NA
# Exposed2 1.333333 0.7347317 2.419628
#
# The last line is the result that we want.
assert_allclose(rr, 4/3)
assert_allclose((ci.low, ci.high), (0.7347317, 2.419628), rtol=5e-7)
def test_relative_risk_ci_conflevel0():
result = relative_risk(exposed_cases=4, exposed_total=12,
control_cases=5, control_total=30)
rr = result.relative_risk
assert_allclose(rr, 2.0, rtol=1e-14)
ci = result.confidence_interval(0)
assert_allclose((ci.low, ci.high), (2.0, 2.0), rtol=1e-12)
def test_relative_risk_ci_conflevel1():
result = relative_risk(exposed_cases=4, exposed_total=12,
control_cases=5, control_total=30)
ci = result.confidence_interval(1)
assert_equal((ci.low, ci.high), (0, np.inf))
def test_relative_risk_ci_edge_cases_00():
result = relative_risk(exposed_cases=0, exposed_total=12,
control_cases=0, control_total=30)
assert_equal(result.relative_risk, np.nan)
ci = result.confidence_interval()
assert_equal((ci.low, ci.high), (np.nan, np.nan))
def test_relative_risk_ci_edge_cases_01():
result = relative_risk(exposed_cases=0, exposed_total=12,
control_cases=1, control_total=30)
assert_equal(result.relative_risk, 0)
ci = result.confidence_interval()
assert_equal((ci.low, ci.high), (0.0, np.nan))
def test_relative_risk_ci_edge_cases_10():
result = relative_risk(exposed_cases=1, exposed_total=12,
control_cases=0, control_total=30)
assert_equal(result.relative_risk, np.inf)
ci = result.confidence_interval()
assert_equal((ci.low, ci.high), (np.nan, np.inf))
@pytest.mark.parametrize('ec, et, cc, ct', [(0, 0, 10, 20),
(-1, 10, 1, 5),
(1, 10, 0, 0),
(1, 10, -1, 4)])
def test_relative_risk_bad_value(ec, et, cc, ct):
with pytest.raises(ValueError, match="must be an integer not less than"):
relative_risk(ec, et, cc, ct)
def test_relative_risk_bad_type():
with pytest.raises(TypeError, match="must be an integer"):
relative_risk(1, 10, 2.0, 40)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046import warnings
import pytest
import numpy as np
from numpy.testing import assert_allclose, assert_equal
from scipy._lib._util import rng_integers
from scipy._lib._array_api import (is_numpy, make_xp_test_case, xp_default_dtype,
xp_size, array_namespace, _xp_copy_to_numpy)
from scipy._lib._array_api_no_0d import xp_assert_close, xp_assert_equal
from scipy._lib import array_api_extra as xpx
from scipy import stats, special
from scipy.fft.tests.test_fftlog import skip_xp_backends
from scipy.optimize import root
from scipy.stats import bootstrap, monte_carlo_test, permutation_test, power
import scipy.stats._resampling as _resampling
@make_xp_test_case(bootstrap)
class TestBootstrap:
@skip_xp_backends('numpy', reason='NumPy does not raise')
def test_bootstrap_iv_other(self, xp):
message = f"When using array library {xp.__name__}"
with pytest.raises(TypeError, match=message):
bootstrap((xp.asarray([1, 2, 3]),), lambda x: xp.mean(x))
def test_bootstrap_iv(self, xp):
sample = xp.asarray([1, 2, 3])
message = "`data` must contain at least one sample."
with pytest.raises(ValueError, match=message):
bootstrap(tuple(), xp.mean)
message = "each sample in `data` must contain two or more observations..."
with pytest.raises(ValueError, match=message):
bootstrap((sample, xp.asarray([1])), xp.mean)
message = ("When `paired is True`, all samples must have the same length ")
with pytest.raises(ValueError, match=message):
bootstrap((sample, xp.asarray([1, 2, 3, 4])), xp.mean, paired=True)
message = "`vectorized` must be `True`, `False`, or `None`."
with pytest.raises(ValueError, match=message):
bootstrap(sample, xp.mean, vectorized='ekki')
message = "`axis` must be an integer."
with pytest.raises(ValueError, match=message):
bootstrap((sample,), xp.mean, axis=1.5)
message = "could not convert string to float"
with pytest.raises(ValueError, match=message):
bootstrap((sample,), xp.mean, confidence_level='ni')
message = "`n_resamples` must be a non-negative integer."
with pytest.raises(ValueError, match=message):
bootstrap((sample,), xp.mean, n_resamples=-1000)
message = "`n_resamples` must be a non-negative integer."
with pytest.raises(ValueError, match=message):
bootstrap((sample,), xp.mean, n_resamples=1000.5)
message = "`batch` must be a positive integer or None."
with pytest.raises(ValueError, match=message):
bootstrap((sample,), xp.mean, batch=-1000)
message = "`batch` must be a positive integer or None."
with pytest.raises(ValueError, match=message):
bootstrap((sample,), xp.mean, batch=1000.5)
message = "`method` must be in"
with pytest.raises(ValueError, match=message):
bootstrap((sample,), xp.mean, method='ekki')
message = "`bootstrap_result` must have attribute `bootstrap_distribution'"
with pytest.raises(ValueError, match=message):
bootstrap((sample,), xp.mean, bootstrap_result=10)
message = "Either `bootstrap_result.bootstrap_distribution.size`"
with pytest.raises(ValueError, match=message):
bootstrap((sample,), xp.mean, n_resamples=0)
message = "SeedSequence expects int or sequence of ints"
with pytest.raises(TypeError, match=message):
bootstrap((sample,), xp.mean, rng='herring')
@pytest.mark.parametrize("method", ['basic', 'percentile', 'BCa'])
@pytest.mark.parametrize("axis", [0, 1, 2])
def test_bootstrap_batch(self, method, axis, xp):
# for one-sample statistics, batch size shouldn't affect the result
rng = np.random.RandomState(0)
x = rng.rand(10, 11, 12)
# SPEC-007 leave one call with random_state to ensure it still works
res1 = bootstrap((xp.asarray(x),), xp.mean, batch=None, method=method,
random_state=0, axis=axis, n_resamples=100)
rng = np.random.RandomState(0)
res2 = bootstrap((xp.asarray(x),), xp.mean, batch=10, method=method,
axis=axis, n_resamples=100, random_state=rng)
xp_assert_equal(res2.confidence_interval.low, res1.confidence_interval.low)
xp_assert_equal(res2.confidence_interval.high, res1.confidence_interval.high)
xp_assert_equal(res2.standard_error, res1.standard_error)
@pytest.mark.parametrize("method", ['basic', 'percentile', 'BCa'])
def test_bootstrap_paired(self, method, xp):
# test that `paired` works as expected
rng = np.random.RandomState(0)
n = 100
x = xp.asarray(rng.rand(n))
y = xp.asarray(rng.rand(n))
def my_statistic(x, y, axis=-1):
return xp.mean((x-y)**2, axis=axis)
def my_paired_statistic(i, axis=-1):
a = x[i]
b = y[i]
res = my_statistic(a, b)
return res
i = xp.arange(x.shape[0])
res1 = bootstrap((i,), my_paired_statistic, rng=0)
res2 = bootstrap((x, y), my_statistic, paired=True, rng=0)
xp_assert_close(res1.confidence_interval.low, res2.confidence_interval.low)
xp_assert_close(res1.confidence_interval.high, res2.confidence_interval.high)
xp_assert_close(res1.standard_error, res2.standard_error)
@pytest.mark.parametrize("method", ['basic', 'percentile', 'BCa'])
@pytest.mark.parametrize("axis", [0, 1, 2])
@pytest.mark.parametrize("paired", [True, False])
def test_bootstrap_vectorized(self, method, axis, paired, xp):
# test that paired is vectorized as expected: when samples are tiled,
# CI and standard_error of each axis-slice is the same as those of the
# original 1d sample
rng = np.random.RandomState(0)
def my_statistic(x, y, z, axis=-1):
return xp.mean(x, axis=axis) + xp.mean(y, axis=axis) + xp.mean(z, axis=axis)
shape = 10, 11, 12
n_samples = shape[axis]
x = rng.rand(n_samples)
y = rng.rand(n_samples)
z = rng.rand(n_samples)
x, y, z = xp.asarray(x), xp.asarray(y), xp.asarray(z)
res1 = bootstrap((x, y, z), my_statistic, paired=paired, method=method,
rng=0, axis=0, n_resamples=100)
assert (res1.bootstrap_distribution.shape
== res1.standard_error.shape + (100,))
reshape = [1, 1, 1]
reshape[axis] = n_samples
reshape = tuple(reshape)
x = xp.broadcast_to(xp.reshape(x, reshape), shape)
y = xp.broadcast_to(xp.reshape(y, reshape), shape)
z = xp.broadcast_to(xp.reshape(z, reshape), shape)
res2 = bootstrap((x, y, z), my_statistic, paired=paired, method=method,
rng=0, axis=axis, n_resamples=100)
result_shape = list(shape)
result_shape.pop(axis)
ref_ci_low = xp.broadcast_to(res2.confidence_interval.low, result_shape)
ref_ci_high = xp.broadcast_to(res2.confidence_interval.high, result_shape)
ref_ci_standard_error = xp.broadcast_to(res2.standard_error, result_shape)
xp_assert_close(res2.confidence_interval.low, ref_ci_low)
xp_assert_close(res2.confidence_interval.high, ref_ci_high)
xp_assert_close(res2.standard_error, ref_ci_standard_error)
@pytest.mark.slow
@pytest.mark.xfail_on_32bit("MemoryError with BCa observed in CI")
@pytest.mark.parametrize("method", ['basic', 'percentile', 'BCa'])
def test_bootstrap_against_theory(self, method, xp):
# based on https://www.statology.org/confidence-intervals-python/
rng = np.random.default_rng(2442101192988600726)
data = stats.norm.rvs(loc=5, scale=2, size=5000, random_state=rng)
alpha = 0.95
dist = stats.t(df=len(data)-1, loc=np.mean(data), scale=stats.sem(data))
ref_low, ref_high = dist.interval(confidence=alpha)
ref_se = dist.std()
config = dict(data=(xp.asarray(data),), statistic=xp.mean, n_resamples=5000,
method=method, rng=rng)
res = bootstrap(**config, confidence_level=alpha)
xp_assert_close(res.confidence_interval.low, xp.asarray(ref_low), rtol=5e-4)
xp_assert_close(res.confidence_interval.high, xp.asarray(ref_high), rtol=5e-4)
xp_assert_close(res.standard_error, xp.asarray(ref_se), atol=3e-4)
config.update(dict(n_resamples=0, bootstrap_result=res))
res = bootstrap(**config, confidence_level=alpha, alternative='less')
xp_assert_close(res.confidence_interval.high,
xp.asarray(dist.ppf(alpha)), rtol=5e-4)
config.update(dict(n_resamples=0, bootstrap_result=res))
res = bootstrap(**config, confidence_level=alpha, alternative='greater')
xp_assert_close(res.confidence_interval.low,
xp.asarray(dist.ppf(1-alpha)), rtol=5e-4)
tests_R = [("basic", 23.77, 79.12),
("percentile", 28.86, 84.21),
("BCa", 32.31, 91.43)]
@pytest.mark.parametrize("method, ref_low, ref_high", tests_R)
def test_bootstrap_against_R(self, method, ref_low, ref_high, xp):
# Compare against R's "boot" library
# library(boot)
# stat <- function (x, a) {
# mean(x[a])
# }
# x <- c(10, 12, 12.5, 12.5, 13.9, 15, 21, 22,
# 23, 34, 50, 81, 89, 121, 134, 213)
# # Use a large value so we get a few significant digits for the CI.
# n = 1000000
# bootresult = boot(x, stat, n)
# result <- boot.ci(bootresult)
# print(result)
x = xp.asarray([10, 12, 12.5, 12.5, 13.9, 15, 21, 22,
23, 34, 50, 81, 89, 121, 134, 213])
res = bootstrap((x,), xp.mean, n_resamples=1000000, method=method, rng=0)
xp_assert_close(res.confidence_interval.low, xp.asarray(ref_low), rtol=0.005)
xp_assert_close(res.confidence_interval.high, xp.asarray(ref_high), rtol=0.005)
def test_multisample_BCa_against_R(self, xp):
# Because bootstrap is stochastic, it's tricky to test against reference
# behavior. Here, we show that SciPy's BCa CI matches R wboot's BCa CI
# much more closely than the other SciPy CIs do.
# arbitrary skewed data
x = xp.asarray([0.75859206, 0.5910282, -0.4419409, -0.36654601,
0.34955357, -1.38835871, 0.76735821])
y = xp.asarray([1.41186073, 0.49775975, 0.08275588, 0.24086388,
0.03567057, 0.52024419, 0.31966611, 1.32067634])
# a multi-sample statistic for which the BCa CI tends to be different
# from the other CIs
def statistic(x, y, axis):
s1 = stats.skew(x, axis=axis)
s2 = stats.skew(y, axis=axis)
return s1 - s2
# compute confidence intervals using each method
rng = np.random.default_rng(468865032284792692)
res_basic = stats.bootstrap((x, y), statistic, method='basic',
batch=100, rng=rng)
res_percent = stats.bootstrap((x, y), statistic, method='percentile',
batch=100, rng=rng)
res_bca = stats.bootstrap((x, y), statistic, method='bca',
batch=100, rng=rng)
# compute midpoints so we can compare just one number for each
mid_basic = xp.mean(xp.stack(res_basic.confidence_interval))
mid_percent = xp.mean(xp.stack(res_percent.confidence_interval))
mid_bca = xp.mean(xp.stack(res_bca.confidence_interval))
# reference for BCA CI computed using R wboot package:
# library(wBoot)
# library(moments)
# x = c(0.75859206, 0.5910282, -0.4419409, -0.36654601,
# 0.34955357, -1.38835871, 0.76735821)
# y = c(1.41186073, 0.49775975, 0.08275588, 0.24086388,
# 0.03567057, 0.52024419, 0.31966611, 1.32067634)
# twoskew <- function(x1, y1) {skewness(x1) - skewness(y1)}
# boot.two.bca(x, y, skewness, conf.level = 0.95,
# R = 9999, stacked = FALSE)
mid_wboot = -1.5519
# compute percent difference relative to wboot BCA method
diff_basic = (mid_basic - mid_wboot)/abs(mid_wboot)
diff_percent = (mid_percent - mid_wboot)/abs(mid_wboot)
diff_bca = (mid_bca - mid_wboot)/abs(mid_wboot)
# SciPy's BCa CI midpoint is much closer than that of the other methods
assert diff_basic < -0.15
assert diff_percent > 0.15
assert abs(diff_bca) < 0.03
def test_BCa_acceleration_against_reference(self, xp):
# Compare the (deterministic) acceleration parameter for a multi-sample
# problem against a reference value. The example is from [1], but Efron's
# value seems inaccurate. Straightforward code for computing the
# reference acceleration (0.011008228344026734) is available at:
# https://github.com/scipy/scipy/pull/16455#issuecomment-1193400981
y = xp.asarray([10., 27., 31., 40., 46., 50., 52., 104., 146.])
z = xp.asarray([16., 23., 38., 94., 99., 141., 197.])
def statistic(z, y, axis=0):
return xp.mean(z, axis=axis) - xp.mean(y, axis=axis)
data = [z, y]
res = stats.bootstrap(data, statistic)
axis = -1
alpha = 0.95
theta_hat_b = res.bootstrap_distribution
batch = 100
_, _, a_hat = _resampling._bca_interval(data, statistic, axis, alpha,
theta_hat_b, batch, xp)
xp_assert_close(a_hat, xp.asarray(0.011008228344026734))
tests_against_itself_1samp = {"basic": 1789,
"percentile": 1790,
"BCa": 1789}
@pytest.mark.slow
@pytest.mark.parametrize("method, expected",
tests_against_itself_1samp.items())
def test_bootstrap_against_itself_1samp(self, method, expected, xp):
# The expected values in this test were generated using bootstrap
# to check for unintended changes in behavior. The test also makes sure
# that bootstrap works with multi-sample statistics and that the
# `axis` argument works as expected / function is vectorized.
rng = np.random.default_rng(9123847)
n = 100 # size of sample
n_resamples = 999 # number of bootstrap resamples used to form each CI
confidence_level = 0.9
# The true mean is 5
dist = stats.norm(loc=5, scale=1)
stat_true = float(dist.mean())
# Do the same thing 2000 times. (The code is fully vectorized.)
n_replications = 2000
data = dist.rvs(size=(n_replications, n), random_state=rng)
res = bootstrap((xp.asarray(data),),
statistic=xp.mean,
confidence_level=confidence_level,
n_resamples=n_resamples,
batch=50,
method=method,
axis=-1,
rng=rng)
ci = res.confidence_interval
# ci contains vectors of lower and upper confidence interval bounds
ci_contains_true = xp.count_nonzero((ci[0] < stat_true) & (stat_true < ci[1]))
assert ci_contains_true == expected
# ci_contains_true is not inconsistent with confidence_level
pvalue = stats.binomtest(int(ci_contains_true), n_replications,
confidence_level).pvalue
assert pvalue > 0.1
tests_against_itself_2samp = {"basic": 892,
"percentile": 890}
@pytest.mark.slow
@pytest.mark.parametrize("method, expected",
tests_against_itself_2samp.items())
def test_bootstrap_against_itself_2samp(self, method, expected, xp):
# The expected values in this test were generated using bootstrap
# to check for unintended changes in behavior. The test also makes sure
# that bootstrap works with multi-sample statistics and that the
# `axis` argument works as expected / function is vectorized.
rng = np.random.RandomState(0)
n1 = 100 # size of sample 1
n2 = 120 # size of sample 2
n_resamples = 999 # number of bootstrap resamples used to form each CI
confidence_level = 0.9
# The statistic we're interested in is the difference in means
def my_stat(data1, data2, axis=-1):
mean1 = xp.mean(data1, axis=axis)
mean2 = xp.mean(data2, axis=axis)
return mean1 - mean2
# The true difference in the means is -0.1
dist1 = stats.norm(loc=0, scale=1)
dist2 = stats.norm(loc=0.1, scale=1)
stat_true = float(dist1.mean() - dist2.mean())
# Do the same thing 1000 times. (The code is fully vectorized.)
n_replications = 1000
data1 = dist1.rvs(size=(n_replications, n1), random_state=rng)
data2 = dist2.rvs(size=(n_replications, n2), random_state=rng)
res = bootstrap((xp.asarray(data1), xp.asarray(data2)),
statistic=my_stat,
confidence_level=confidence_level,
n_resamples=n_resamples,
batch=50,
method=method,
axis=-1,
random_state=rng)
ci = res.confidence_interval
# ci contains vectors of lower and upper confidence interval bounds
ci_contains_true = xp.count_nonzero((ci[0] < stat_true) & (stat_true < ci[1]))
assert ci_contains_true == expected
# ci_contains_true is not inconsistent with confidence_level
pvalue = stats.binomtest(int(ci_contains_true), n_replications,
confidence_level).pvalue
assert pvalue > 0.1
@pytest.mark.parametrize("method", ["basic", "percentile", "BCa"])
@pytest.mark.parametrize("axis", [0, 1])
@pytest.mark.parametrize("dtype", ['float32', 'float64'])
def test_bootstrap_vectorized_3samp(self, method, axis, dtype, xp):
def statistic(*data, axis=0):
# an arbitrary, vectorized statistic
return sum(xp.mean(sample, axis=axis) for sample in data)
def statistic_1d(*data):
# the same statistic, not vectorized
for sample in data:
assert sample.ndim == 1
return np.asarray(sum(sample.mean() for sample in data), dtype=dtype)
rng = np.random.RandomState(0)
x = rng.rand(4, 5).astype(dtype)
y = rng.rand(4, 5).astype(dtype)
z = rng.rand(4, 5).astype(dtype)
res1 = bootstrap((xp.asarray(x), xp.asarray(y), xp.asarray(z)),
statistic, vectorized=True, axis=axis, n_resamples=100,
method=method, rng=0)
res2 = bootstrap((x, y, z), statistic_1d, vectorized=False,
axis=axis, n_resamples=100, method=method, rng=0)
rtol = 1e-6 if dtype == 'float32' else 1e-14
xp_assert_close(res1.confidence_interval.low,
xp.asarray(res2.confidence_interval.low), rtol=rtol)
xp_assert_close(res1.confidence_interval.high,
xp.asarray(res2.confidence_interval.high), rtol=rtol)
xp_assert_close(res1.standard_error, xp.asarray(res2.standard_error), rtol=rtol)
@pytest.mark.xfail_on_32bit("Failure is not concerning; see gh-14107")
@pytest.mark.parametrize("method", ["basic", "percentile", "BCa"])
@pytest.mark.parametrize("axis", [0, 1])
def test_bootstrap_vectorized_1samp(self, method, axis, xp):
def statistic(x, axis=0):
# an arbitrary, vectorized statistic
return xp.mean(x, axis=axis)
def statistic_1d(x):
# the same statistic, not vectorized
assert x.ndim == 1
return x.mean(axis=0)
rng = np.random.default_rng(7939952824)
x = rng.random((2, 3))
res1 = bootstrap((xp.asarray(x),), statistic, vectorized=True, axis=axis,
n_resamples=100, batch=None, method=method, rng=0)
res2 = bootstrap((x,), statistic_1d, vectorized=False, axis=axis,
n_resamples=100, batch=10, method=method, rng=0)
xp_assert_close(res1.confidence_interval.low,
xp.asarray(res2.confidence_interval.low))
xp_assert_close(res1.confidence_interval.high,
xp.asarray(res2.confidence_interval.high))
xp_assert_close(res1.standard_error, xp.asarray(res2.standard_error))
@pytest.mark.parametrize("method", ["basic", "percentile", "BCa"])
def test_bootstrap_degenerate(self, method, xp):
data = xp.full((35,), 10000.)
if method == "BCa":
with np.errstate(invalid='ignore'):
msg = "The BCa confidence interval cannot be calculated"
with pytest.warns(stats.DegenerateDataWarning, match=msg):
res = bootstrap([data, ], xp.mean, method=method)
xp_assert_equal(res.confidence_interval.low, xp.asarray(xp.nan))
xp_assert_equal(res.confidence_interval.high, xp.asarray(xp.nan))
else:
res = bootstrap([data, ], xp.mean, method=method)
xp_assert_equal(res.confidence_interval.low, xp.asarray(10000.))
xp_assert_equal(res.confidence_interval.high, xp.asarray(10000.))
xp_assert_equal(res.standard_error, xp.asarray(0.))
@pytest.mark.parametrize("method", ["BCa", "basic", "percentile"])
def test_bootstrap_gh15678(self, method, xp):
# Check that gh-15678 is fixed: when statistic function returned a Python
# float, method="BCa" failed when trying to add a dimension to the float
rng = np.random.default_rng(354645618886684)
dist = stats.norm(loc=2, scale=4)
data = dist.rvs(size=100, random_state=rng)
res = bootstrap((xp.asarray(data),), stats.skew, method=method, n_resamples=100,
rng=np.random.default_rng(9563))
# this always worked because np.apply_along_axis returns NumPy data type
ref = bootstrap((data,), stats.skew, method=method, n_resamples=100,
rng=np.random.default_rng(9563), vectorized=False)
xp_assert_close(res.confidence_interval.low,
xp.asarray(ref.confidence_interval.low))
xp_assert_close(res.confidence_interval.high,
xp.asarray(ref.confidence_interval.high))
xp_assert_close(res.standard_error, xp.asarray(ref.standard_error))
def test_bootstrap_min(self, xp):
# Check that gh-15883 is fixed: percentileofscore should
# behave according to the 'mean' behavior and not trigger nan for BCa
rng = np.random.default_rng(1891289180021102)
dist = stats.norm(loc=2, scale=4)
data = dist.rvs(size=100, random_state=rng)
true_min = np.min(data)
data = xp.asarray(data)
res = bootstrap((data,), xp.min, method="BCa", n_resamples=100,
rng=np.random.default_rng(3942))
xp_assert_equal(res.confidence_interval.low, xp.asarray(true_min))
res2 = bootstrap((-data,), xp.max, method="BCa", n_resamples=100,
rng=np.random.default_rng(3942))
xp_assert_close(-res.confidence_interval.low, res2.confidence_interval.high)
xp_assert_close(-res.confidence_interval.high, res2.confidence_interval.low)
@pytest.mark.parametrize("additional_resamples", [0, 1000])
def test_re_bootstrap(self, additional_resamples, xp):
# Test behavior of parameter `bootstrap_result`
rng = np.random.default_rng(8958153316228384)
x = rng.random(size=100)
n1 = 1000
n2 = additional_resamples
n3 = n1 + additional_resamples
rng = np.random.default_rng(296689032789913033)
res = stats.bootstrap((xp.asarray(x),), xp.mean, n_resamples=n1, rng=rng,
confidence_level=0.95, method='percentile')
res = stats.bootstrap((xp.asarray(x),), xp.mean, n_resamples=n2, rng=rng,
confidence_level=0.90, method='BCa',
bootstrap_result=res)
rng = np.random.default_rng(296689032789913033)
ref = stats.bootstrap((xp.asarray(x),), xp.mean, n_resamples=n3, rng=rng,
confidence_level=0.90, method='BCa')
xp_assert_close(res.confidence_interval.low,
xp.asarray(ref.confidence_interval.low),
rtol=1e-14)
xp_assert_close(res.confidence_interval.high,
xp.asarray(ref.confidence_interval.high),
rtol=1e-14)
xp_assert_close(res.standard_error, xp.asarray(ref.standard_error), rtol=1e-14)
@pytest.mark.xfail_on_32bit("Sensitive to machine precision")
@pytest.mark.parametrize("method", ['basic', 'percentile', 'BCa'])
def test_bootstrap_alternative(self, method, xp):
rng = np.random.default_rng(5894822712842015040)
dist = stats.norm(loc=2, scale=4)
data = (xp.asarray(dist.rvs(size=(100), random_state=rng)),)
config = dict(data=data, statistic=xp.std, rng=rng, axis=-1)
t = stats.bootstrap(**config, confidence_level=0.9)
config.update(dict(n_resamples=0, bootstrap_result=t))
l = stats.bootstrap(**config, confidence_level=0.95, alternative='less')
g = stats.bootstrap(**config, confidence_level=0.95, alternative='greater')
xp_assert_close(l.confidence_interval.high, t.confidence_interval.high,
rtol=1e-14)
xp_assert_close(g.confidence_interval.low, t.confidence_interval.low,
rtol=1e-14)
assert xp.isinf(l.confidence_interval.low) and l.confidence_interval.low < 0
assert xp.isinf(g.confidence_interval.high) and g.confidence_interval.high > 0
with pytest.raises(ValueError, match='`alternative` must be one of'):
stats.bootstrap(**config, alternative='ekki-ekki')
def test_jackknife_resample(self, xp):
shape = 3, 4, 5, 6
rng = np.random.default_rng(5274950392)
x = rng.random(size=shape)
y = next(_resampling._jackknife_resample(xp.asarray(x), xp=xp))
for i in range(shape[-1]):
# each resample is indexed along second to last axis
# (last axis is the one the statistic will be taken over / consumed)
slc = y[..., i, :]
expected = np.delete(x, i, axis=-1)
xp_assert_equal(slc, xp.asarray(expected))
y2 = list(_resampling._jackknife_resample(xp.asarray(x), batch=2, xp=xp))
xp_assert_equal(xp.concat(y2, axis=-2), y)
@pytest.mark.skip_xp_backends("array_api_strict",
reason="Test uses ... + fancy indexing")
@pytest.mark.parametrize("rng_name", ["RandomState", "default_rng"])
def test_bootstrap_resample(self, rng_name, xp):
rng_gen = getattr(np.random, rng_name)
rng1 = rng_gen(3949441460)
rng2 = rng_gen(3949441460)
n_resamples = 10
shape = 3, 4, 5, 6
rng = np.random.default_rng(5274950392)
x = xp.asarray(rng.random(shape))
y = _resampling._bootstrap_resample(x, n_resamples, rng=rng1, xp=xp)
for i in range(n_resamples):
# each resample is indexed along second to last axis
# (last axis is the one the statistic will be taken over / consumed)
slc = y[..., i, :]
js = xp.asarray(rng_integers(rng2, 0, shape[-1], shape[-1]))
expected = x[..., js]
xp_assert_equal(slc, expected)
@pytest.mark.parametrize("score", [0, 0.5, 1])
@pytest.mark.parametrize("axis", [0, 1, 2])
def test_percentile_of_score(self, score, axis, xp):
shape = 10, 20, 30
rng = np.random.default_rng(5903363153)
x = rng.random(shape)
dtype = xp_default_dtype(xp)
p = _resampling._percentile_of_score(xp.asarray(x, dtype=dtype),
xp.asarray(score, dtype=dtype),
axis=-1, xp=xp)
def vectorized_pos(a, score, axis):
return np.apply_along_axis(stats.percentileofscore, axis, a, score)
p2 = vectorized_pos(x, score, axis=-1)/100
xp_assert_close(p, xp.asarray(p2, dtype=dtype), rtol=1e-15)
@pytest.mark.parametrize("axis", [0, 1, 2])
def test_vectorize_statistic(self, axis):
# test that _vectorize_statistic vectorizes a statistic along `axis`
# only used with NumPy arrays
def statistic(*data, axis):
# an arbitrary, vectorized statistic
return sum(sample.mean(axis) for sample in data)
def statistic_1d(*data):
# the same statistic, not vectorized
for sample in data:
assert sample.ndim == 1
return statistic(*data, axis=0)
# vectorize the non-vectorized statistic
statistic2 = _resampling._vectorize_statistic(statistic_1d)
rng = np.random.RandomState(0)
x = rng.rand(4, 5, 6)
y = rng.rand(4, 1, 6)
z = rng.rand(1, 5, 6)
res1 = statistic(x, y, z, axis=axis)
res2 = statistic2(x, y, z, axis=axis)
assert_allclose(res1, res2)
@pytest.mark.slow
@pytest.mark.parametrize("method", ["basic", "percentile", "BCa"])
def test_vector_valued_statistic(self, method, xp):
# Generate 95% confidence interval around MLE of normal distribution
# parameters. Repeat 100 times, each time on sample of size 100.
# Check that confidence interval contains true parameters ~95 times.
# Confidence intervals are estimated and stochastic; a test failure
# does not necessarily indicate that something is wrong. More important
# than values of `counts` below is that the shapes of the outputs are
# correct.
rng = np.random.default_rng(2196847219)
params = 1, 0.5
sample = xp.asarray(rng.normal(*params, size=(100, 100)))
def statistic(data, axis):
return xp.stack([xp.mean(data, axis=axis),
xp.std(data, axis=axis, correction=1)])
res = bootstrap((sample,), statistic, method=method, axis=-1,
n_resamples=9999, batch=200, random_state=rng)
params = xp.asarray([1, 0.5])
counts = xp.count_nonzero((res.confidence_interval.low.T < params)
& (res.confidence_interval.high.T > params),
axis=0)
assert xp.all(counts >= 90)
assert xp.all(counts <= 100)
assert res.confidence_interval.low.shape == (2, 100)
assert res.confidence_interval.high.shape == (2, 100)
assert res.standard_error.shape == (2, 100)
assert res.bootstrap_distribution.shape == (2, 100, 9999)
@pytest.mark.slow
@pytest.mark.filterwarnings('ignore::RuntimeWarning')
def test_vector_valued_statistic_gh17715(self):
# gh-17715 reported a mistake introduced in the extension of BCa to
# multi-sample statistics; a `len` should have been `.shape[-1]`. Check
# that this is resolved.
# If this is resolved for NumPy, it's resolved for the rest,
# let's only run this for NumPy.
rng = np.random.default_rng(141921000979291141)
def concordance(x, y, axis):
xm = x.mean(axis)
ym = y.mean(axis)
cov = ((x - xm[..., None]) * (y - ym[..., None])).mean(axis)
return (2 * cov) / (x.var(axis) + y.var(axis) + (xm - ym) ** 2)
def statistic(tp, tn, fp, fn, axis):
actual = tp + fp
expected = tp + fn
return np.nan_to_num(concordance(actual, expected, axis))
def statistic_extradim(*args, axis):
return statistic(*args, axis)[np.newaxis, ...]
data = [[4, 0, 0, 2], # (tp, tn, fp, fn)
[2, 1, 2, 1],
[0, 6, 0, 0],
[0, 6, 3, 0],
[0, 8, 1, 0]]
data = np.array(data).T
res = bootstrap(data, statistic_extradim, rng=rng, paired=True)
ref = bootstrap(data, statistic, rng=rng, paired=True)
assert_allclose(res.confidence_interval.low[0],
ref.confidence_interval.low, atol=1e-15)
assert_allclose(res.confidence_interval.high[0],
ref.confidence_interval.high, atol=1e-15)
# torch doesn't have T distribution CDF and can't fall back to NumPy on GPU
@pytest.mark.skip_xp_backends(np_only=True, exceptions=['cupy'])
def test_gh_20850(self, xp):
rng = np.random.default_rng(2085020850)
x = xp.asarray(rng.random((10, 2)))
y = xp.asarray(rng.random((11, 2)))
def statistic(x, y, axis):
return stats.ttest_ind(x, y, axis=axis).statistic
# The shapes do *not* need to be the same along axis
stats.bootstrap((x, y), statistic)
stats.bootstrap((x.T, y.T), statistic, axis=1)
# But even when the shapes *are* the same along axis, the lengths
# along other dimensions have to be the same (or `bootstrap` warns).
message = "Array shapes are incompatible for broadcasting."
with pytest.raises(ValueError, match=message):
stats.bootstrap((x, y[:10, 0]), statistic) # this won't work after 1.16
stats.bootstrap((x, y[:10, 0:1]), statistic) # this will
stats.bootstrap((x.T, y.T[0:1, :10]), statistic, axis=1) # this will
# --- Test Monte Carlo Hypothesis Test --- #
@make_xp_test_case(monte_carlo_test)
class TestMonteCarloHypothesisTest:
atol = 2.5e-2 # for comparing p-value
def get_rvs(self, rvs_in, rs, dtype=None, xp=np):
return lambda *args, **kwds: xp.asarray(rvs_in(*args, random_state=rs, **kwds),
dtype=dtype)
def get_statistic(self, xp):
def statistic(x, axis):
m = xp.mean(x, axis=axis)
v = xp.var(x, axis=axis, correction=1)
n = x.shape[axis]
return m / (v/n)**0.5
# return stats.ttest_1samp(x, popmean=0., axis=axis).statistic)
return statistic
def test_input_validation(self, xp):
# test that the appropriate error messages are raised for invalid input
data = xp.asarray([1., 2., 3.])
def stat(x, axis=None):
return xp.mean(x, axis=axis)
message = "Array shapes are incompatible for broadcasting."
temp = (xp.zeros((2, 5)), xp.zeros((3, 5)))
rvs = (stats.norm.rvs, stats.norm.rvs)
with pytest.raises(ValueError, match=message):
monte_carlo_test(temp, rvs, lambda x, y, axis: 1, axis=-1)
message = "`axis` must be an integer."
with pytest.raises(ValueError, match=message):
monte_carlo_test(data, stats.norm.rvs, stat, axis=1.5)
message = "`vectorized` must be `True`, `False`, or `None`."
with pytest.raises(ValueError, match=message):
monte_carlo_test(data, stats.norm.rvs, stat, vectorized=1.5)
message = "`rvs` must be callable or sequence of callables."
with pytest.raises(TypeError, match=message):
monte_carlo_test(data, None, stat)
with pytest.raises(TypeError, match=message):
temp = xp.asarray([[1., 2.], [3., 4.]])
monte_carlo_test(temp, [lambda x: x, None], stat)
message = "If `rvs` is a sequence..."
with pytest.raises(ValueError, match=message):
temp = xp.asarray([[1., 2., 3.]])
monte_carlo_test(temp, [lambda x: x, lambda x: x], stat)
message = "`statistic` must be callable."
with pytest.raises(TypeError, match=message):
monte_carlo_test(data, stats.norm.rvs, None)
message = "`n_resamples` must be a positive integer."
with pytest.raises(ValueError, match=message):
monte_carlo_test(data, stats.norm.rvs, stat, n_resamples=-1000)
message = "`n_resamples` must be a positive integer."
with pytest.raises(ValueError, match=message):
monte_carlo_test(data, stats.norm.rvs, stat, n_resamples=1000.5)
message = "`batch` must be a positive integer or None."
with pytest.raises(ValueError, match=message):
monte_carlo_test(data, stats.norm.rvs, stat, batch=-1000)
message = "`batch` must be a positive integer or None."
with pytest.raises(ValueError, match=message):
monte_carlo_test(data, stats.norm.rvs, stat, batch=1000.5)
message = "`alternative` must be in..."
with pytest.raises(ValueError, match=message):
monte_carlo_test(data, stats.norm.rvs, stat, alternative='ekki')
# *If* this raises a value error, make sure it has the intended message
message = "Signature inspection of statistic"
def rvs(size):
return xp.asarray(stats.norm.rvs(size=size))
try:
monte_carlo_test(data, rvs, xp.mean)
except ValueError as e:
assert str(e).startswith(message)
def test_input_validation_xp(self, xp):
def non_vectorized_statistic(x):
return xp.mean(x)
message = "`statistic` must be vectorized..."
sample = xp.asarray([1., 2., 3.])
if is_numpy(xp):
monte_carlo_test(sample, stats.norm.rvs, non_vectorized_statistic)
return
with pytest.raises(ValueError, match=message):
monte_carlo_test(sample, stats.norm.rvs, non_vectorized_statistic)
with pytest.raises(ValueError, match=message):
monte_carlo_test(sample, stats.norm.rvs, xp.mean, vectorized=False)
@pytest.mark.xslow
def test_batch(self, xp):
# make sure that the `batch` parameter is respected by checking the
# maximum batch size provided in calls to `statistic`
rng = np.random.default_rng(23492340193)
x = xp.asarray(rng.standard_normal(size=10))
def statistic(x, axis):
batch_size = 1 if x.ndim == 1 else x.shape[0]
statistic.batch_size = max(batch_size, statistic.batch_size)
statistic.counter += 1
return self.get_statistic(xp)(x, axis=axis)
statistic.counter = 0
statistic.batch_size = 0
kwds = {'sample': x, 'statistic': statistic,
'n_resamples': 1000, 'vectorized': True}
kwds['rvs'] = self.get_rvs(stats.norm.rvs, np.random.default_rng(328423), xp=xp)
res1 = monte_carlo_test(batch=1, **kwds)
assert_equal(statistic.counter, 1001)
assert_equal(statistic.batch_size, 1)
kwds['rvs'] = self.get_rvs(stats.norm.rvs, np.random.default_rng(328423), xp=xp)
statistic.counter = 0
res2 = monte_carlo_test(batch=50, **kwds)
assert_equal(statistic.counter, 21)
assert_equal(statistic.batch_size, 50)
kwds['rvs'] = self.get_rvs(stats.norm.rvs, np.random.default_rng(328423), xp=xp)
statistic.counter = 0
res3 = monte_carlo_test(**kwds)
assert_equal(statistic.counter, 2)
assert_equal(statistic.batch_size, 1000)
xp_assert_equal(res1.pvalue, res3.pvalue)
xp_assert_equal(res2.pvalue, res3.pvalue)
@pytest.mark.parametrize('axis', range(-3, 3))
def test_axis_dtype(self, axis, xp):
# test that Nd-array samples are handled correctly for valid values
# of the `axis` parameter; also make sure non-default dtype is maintained
rng = np.random.default_rng(2389234)
size = [2, 3, 4]
size[axis] = 100
# Determine non-default dtype
dtype_default = xp.asarray(1.).dtype
dtype_str = 'float32'if ("64" in str(dtype_default)) else 'float64'
dtype_np = getattr(np, dtype_str)
dtype = getattr(xp, dtype_str)
# ttest_1samp is CPU array-API compatible, but it would be good to
# include CuPy in this test. We'll perform ttest_1samp with a
# NumPy array, but all the rest with be done with fully array-API
# compatible code.
x = rng.standard_normal(size=size, dtype=dtype_np)
expected = stats.ttest_1samp(x, popmean=0., axis=axis)
x = xp.asarray(x, dtype=dtype)
statistic = self.get_statistic(xp)
rvs = self.get_rvs(stats.norm.rvs, rng, dtype=dtype, xp=xp)
res = monte_carlo_test(x, rvs, statistic, vectorized=True,
n_resamples=20000, axis=axis)
ref_statistic = xp.asarray(expected.statistic, dtype=dtype)
ref_pvalue = xp.asarray(expected.pvalue, dtype=dtype)
xp_assert_close(res.statistic, ref_statistic)
xp_assert_close(res.pvalue, ref_pvalue, atol=self.atol)
@pytest.mark.parametrize('alternative', ("two-sided", "less", "greater"))
def test_alternative(self, alternative, xp):
# test that `alternative` is working as expected
rng = np.random.default_rng(65723433)
x = rng.standard_normal(size=30)
ref = stats.ttest_1samp(x, 0., alternative=alternative)
x = xp.asarray(x)
statistic = self.get_statistic(xp)
rvs = self.get_rvs(stats.norm.rvs, rng, xp=xp)
res = monte_carlo_test(x, rvs, statistic, alternative=alternative)
xp_assert_close(res.statistic, xp.asarray(ref.statistic))
xp_assert_close(res.pvalue, xp.asarray(ref.pvalue), atol=self.atol)
# Tests below involve statistics that are not yet array-API compatible.
# They can be converted when the statistics are converted.
@pytest.mark.slow
@pytest.mark.parametrize('alternative', ("less", "greater"))
@pytest.mark.parametrize('a', np.linspace(-0.5, 0.5, 5)) # skewness
def test_against_ks_1samp(self, alternative, a):
# test that monte_carlo_test can reproduce pvalue of ks_1samp
rng = np.random.default_rng(65723433)
x = stats.skewnorm.rvs(a=a, size=30, random_state=rng)
expected = stats.ks_1samp(x, stats.norm.cdf, alternative=alternative)
def statistic1d(x):
return stats.ks_1samp(x, stats.norm.cdf, mode='asymp',
alternative=alternative).statistic
norm_rvs = self.get_rvs(stats.norm.rvs, rng)
res = monte_carlo_test(x, norm_rvs, statistic1d,
n_resamples=1000, vectorized=False,
alternative=alternative)
assert_allclose(res.statistic, expected.statistic)
if alternative == 'greater':
assert_allclose(res.pvalue, expected.pvalue, atol=self.atol)
elif alternative == 'less':
assert_allclose(1-res.pvalue, expected.pvalue, atol=self.atol)
@pytest.mark.parametrize('hypotest', (stats.skewtest, stats.kurtosistest))
@pytest.mark.parametrize('alternative', ("less", "greater", "two-sided"))
@pytest.mark.parametrize('a', np.linspace(-2, 2, 5)) # skewness
def test_against_normality_tests(self, hypotest, alternative, a):
# test that monte_carlo_test can reproduce pvalue of normality tests
rng = np.random.default_rng(85723405)
x = stats.skewnorm.rvs(a=a, size=150, random_state=rng)
expected = hypotest(x, alternative=alternative)
def statistic(x, axis):
return hypotest(x, axis=axis).statistic
norm_rvs = self.get_rvs(stats.norm.rvs, rng)
res = monte_carlo_test(x, norm_rvs, statistic, vectorized=True,
alternative=alternative)
assert_allclose(res.statistic, expected.statistic)
assert_allclose(res.pvalue, expected.pvalue, atol=self.atol)
@pytest.mark.parametrize('a', np.arange(-2, 3)) # skewness parameter
def test_against_normaltest(self, a):
# test that monte_carlo_test can reproduce pvalue of normaltest
rng = np.random.default_rng(12340513)
x = stats.skewnorm.rvs(a=a, size=150, random_state=rng)
expected = stats.normaltest(x)
def statistic(x, axis):
return stats.normaltest(x, axis=axis).statistic
norm_rvs = self.get_rvs(stats.norm.rvs, rng)
res = monte_carlo_test(x, norm_rvs, statistic, vectorized=True,
alternative='greater')
assert_allclose(res.statistic, expected.statistic)
assert_allclose(res.pvalue, expected.pvalue, atol=self.atol)
@pytest.mark.xslow
@pytest.mark.parametrize('a', np.linspace(-0.5, 0.5, 5)) # skewness
def test_against_cramervonmises(self, a):
# test that monte_carlo_test can reproduce pvalue of cramervonmises
rng = np.random.default_rng(234874135)
x = stats.skewnorm.rvs(a=a, size=30, random_state=rng)
expected = stats.cramervonmises(x, stats.norm.cdf)
def statistic1d(x):
return stats.cramervonmises(x, stats.norm.cdf).statistic
norm_rvs = self.get_rvs(stats.norm.rvs, rng)
res = monte_carlo_test(x, norm_rvs, statistic1d,
n_resamples=1000, vectorized=False,
alternative='greater')
assert_allclose(res.statistic, expected.statistic)
assert_allclose(res.pvalue, expected.pvalue, atol=self.atol)
@pytest.mark.slow
@pytest.mark.parametrize('dist_name', ['norm', 'logistic'])
@pytest.mark.parametrize('target_statistic', [0.6, 0.7, 0.8])
def test_against_anderson(self, dist_name, target_statistic):
# test that monte_carlo_test can reproduce results of `anderson`.
# find the skewness for which the sample statistic is within the range of
# values tubulated by `anderson`
def fun(a):
rng = np.random.default_rng(394295467)
x = stats.tukeylambda.rvs(a, size=100, random_state=rng)
expected = stats.anderson(x, dist_name, method='interpolate')
return expected.statistic - target_statistic
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
sol = root(fun, x0=0)
assert sol.success
# get the significance level (p-value) associated with that critical
# value
a = sol.x[0]
rng = np.random.default_rng(394295467)
x = stats.tukeylambda.rvs(a, size=100, random_state=rng)
expected = stats.anderson(x, dist_name, method='interpolate')
expected_stat = expected.statistic
expected_p = expected.pvalue
# perform equivalent Monte Carlo test and compare results
def statistic1d(x):
return stats.anderson(x, dist_name, method='interpolate').statistic
dist_rvs = self.get_rvs(getattr(stats, dist_name).rvs, rng)
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
res = monte_carlo_test(x, dist_rvs,
statistic1d, n_resamples=1000,
vectorized=False, alternative='greater')
assert_allclose(res.statistic, expected_stat)
assert_allclose(res.pvalue, expected_p, atol=2*self.atol)
def test_p_never_zero(self):
# Use biased estimate of p-value to ensure that p-value is never zero
# per monte_carlo_test reference [1]
rng = np.random.default_rng(2190176673029737545)
x = np.zeros(100)
res = monte_carlo_test(x, rng.random, np.mean,
vectorized=True, alternative='less')
assert res.pvalue == 0.0001
def test_against_ttest_ind(self):
# test that `monte_carlo_test` can reproduce results of `ttest_ind`.
rng = np.random.default_rng(219017667302737545)
data = rng.random(size=(2, 5)), rng.random(size=7) # broadcastable
rvs = rng.normal, rng.normal
def statistic(x, y, axis):
return stats.ttest_ind(x, y, axis=axis).statistic
res = stats.monte_carlo_test(data, rvs, statistic, axis=-1)
ref = stats.ttest_ind(data[0], [data[1]], axis=-1)
assert_allclose(res.statistic, ref.statistic)
assert_allclose(res.pvalue, ref.pvalue, rtol=2e-2)
def test_against_f_oneway(self):
# test that `monte_carlo_test` can reproduce results of `f_oneway`.
rng = np.random.default_rng(219017667302737545)
data = (rng.random(size=(2, 100)), rng.random(size=(2, 101)),
rng.random(size=(2, 102)), rng.random(size=(2, 103)))
rvs = rng.normal, rng.normal, rng.normal, rng.normal
def statistic(*args, axis):
return stats.f_oneway(*args, axis=axis).statistic
res = stats.monte_carlo_test(data, rvs, statistic, axis=-1,
alternative='greater')
ref = stats.f_oneway(*data, axis=-1)
assert_allclose(res.statistic, ref.statistic)
assert_allclose(res.pvalue, ref.pvalue, atol=1e-2)
@pytest.mark.fail_slow(2)
@pytest.mark.xfail_on_32bit("Statistic may not depend on sample order on 32-bit")
def test_finite_precision_statistic(self):
# Some statistics return numerically distinct values when the values
# should be equal in theory. Test that `monte_carlo_test` accounts
# for this in some way.
rng = np.random.default_rng(2549824598234528)
n_resamples = 9999
def rvs(size):
return 1. * stats.bernoulli(p=0.333).rvs(size=size, random_state=rng)
x = rvs(100)
res = stats.monte_carlo_test(x, rvs, np.var, alternative='less',
n_resamples=n_resamples)
# show that having a tolerance matters
c0 = np.sum(res.null_distribution <= res.statistic)
c1 = np.sum(res.null_distribution <= res.statistic*(1+1e-15))
assert c0 != c1
assert res.pvalue == (c1 + 1)/(n_resamples + 1)
@make_xp_test_case(power)
class TestPower:
def xp_normal(self, rng, *, xp, dtype=None):
dtype = xp_default_dtype(xp) if dtype is None else dtype
return lambda size: xp.asarray(rng.normal(size=size), dtype=dtype)
def test_input_validation(self, xp):
# test that the appropriate error messages are raised for invalid input
rng = np.random.default_rng(8519895914314711673)
test = stats.ttest_ind
rvs = (self.xp_normal(rng, xp=xp), self.xp_normal(rng, xp=xp))
n_observations = (xp.asarray(10), xp.asarray(12))
message = "`vectorized` must be `True`, `False`, or `None`."
with pytest.raises(ValueError, match=message):
power(test, rvs, n_observations, vectorized=1.5)
message = "`rvs` must be callable or sequence of callables."
with pytest.raises(TypeError, match=message):
power(test, None, n_observations)
with pytest.raises(TypeError, match=message):
power(test, (self.xp_normal(rng, xp=xp), 'ekki'), n_observations)
message = "If `rvs` is a sequence..."
with pytest.raises(ValueError, match=message):
power(test, (self.xp_normal(rng, xp=xp),), n_observations)
with pytest.raises(ValueError, match=message):
power(test, rvs, (10,))
message = "`significance` must contain floats between 0 and 1."
with pytest.raises(ValueError, match=message):
power(test, rvs, n_observations, significance=2)
with pytest.raises(ValueError, match=message):
power(test, rvs, n_observations, significance=xp.linspace(-1, 1, 50))
message = "`kwargs` must be a dictionary"
with pytest.raises(TypeError, match=message):
power(test, rvs, n_observations, kwargs=(1, 2, 3))
message = "not be broadcast|Chunks do not add|Incompatible shapes"
with pytest.raises((ValueError, RuntimeError), match=message):
power(test, rvs, (xp.asarray([10, 11]), xp.asarray([12, 13, 14])))
with pytest.raises((ValueError, RuntimeError), match=message):
power(test, rvs, (xp.asarray([10, 11]), xp.asarray([12, 13])),
kwargs={'x': xp.asarray([1, 2, 3])})
message = "`test` must be callable"
with pytest.raises(TypeError, match=message):
power(None, rvs, n_observations)
message = "`n_resamples` must be a positive integer"
with pytest.raises(ValueError, match=message):
power(test, rvs, n_observations, n_resamples=-10)
with pytest.raises(ValueError, match=message):
power(test, rvs, n_observations, n_resamples=10.5)
message = "`batch` must be a positive integer"
with pytest.raises(ValueError, match=message):
power(test, rvs, n_observations, batch=-10)
with pytest.raises(ValueError, match=message):
power(test, rvs, n_observations, batch=10.5)
@pytest.mark.slow
def test_batch(self, xp):
# make sure that the `batch` parameter is respected by checking the
# maximum batch size provided in calls to `test`
rng = np.random.default_rng(23492340193)
def test(x, axis):
batch_size = 1 if x.ndim == 1 else x.shape[0]
test.batch_size = max(batch_size, test.batch_size)
test.counter += 1
return stats.ttest_1samp(x, xp.asarray(0.), axis=axis).pvalue
test.counter = 0
test.batch_size = 0
kwds = dict(test=test,
n_observations=xp.asarray(10),
n_resamples=1000)
rng = np.random.default_rng(23492340193)
res1 = power(**kwds, rvs=self.xp_normal(rng, xp=xp), batch=1)
assert test.counter == 1000
assert test.batch_size == 1
rng = np.random.default_rng(23492340193)
test.counter = 0
res2 = power(**kwds, rvs=self.xp_normal(rng, xp=xp), batch=50)
assert test.counter == 20
assert test.batch_size == 50
rng = np.random.default_rng(23492340193)
test.counter = 0
res3 = power(**kwds, rvs=self.xp_normal(rng, xp=xp), batch=1000)
assert test.counter == 1
assert test.batch_size == 1000
xp_assert_equal(res1.power, res3.power)
xp_assert_equal(res2.power, res3.power)
@pytest.mark.slow
def test_vectorization(self, xp):
# Test that `power` is vectorized as expected
rng = np.random.default_rng(25495254834552)
alternatives = {-1: 'less', 0:'two-sided', 1: 'greater'}
# Single vectorized call
popmeans = xp.asarray([0, 0.2])
def test(x, alternative, axis=-1):
# ensure that popmeans axis is zeroth and orthogonal to the rest
popmeans_expanded = xpx.expand_dims(popmeans,
axis=tuple(range(1, x.ndim + 1)))
alternative = alternatives[int(alternative)]
return stats.ttest_1samp(x, popmeans_expanded, alternative=alternative,
axis=axis)
# nx and kwargs broadcast against one another
nx = xp.asarray([10, 15, 20, 50, 100])[:, xp.newaxis]
kwargs = {'alternative': xp.asarray([-1, 0, 1])}
# This dimension is added to the beginning
significance = xp.asarray([0.01, 0.025, 0.05, 0.1])
res = stats.power(test, self.xp_normal(rng, xp=xp), nx,
significance=significance, kwargs=kwargs)
# Looping over all combinations
ref = []
for significance_i in significance:
for i in range(nx.shape[0]):
nx_i = nx[i, ...]
for alternative_i in kwargs['alternative']:
for j in range(popmeans.shape[0]):
popmean_j = popmeans[j]
def test2(x, axis=-1):
return stats.ttest_1samp(x, popmean_j, axis=axis,
alternative=alternatives[int(alternative_i)])
tmp = stats.power(test2, self.xp_normal(rng, xp=xp), nx_i,
significance=significance_i)
ref.append(tmp.power)
ref = xp.reshape(xp.stack(ref), res.power.shape)
# Show that results are similar
xp_assert_close(res.power, ref, rtol=2e-2, atol=1e-2)
@pytest.mark.skip_xp_backends(cpu_only=True,
exceptions=['cupy', 'jax.numpy', 'dask.array'])
def test_ttest_ind_null(self, xp):
# Check that the p-values of `ttest_ind` are uniformly distributed under
# the null hypothesis
rng = np.random.default_rng(254952548345528)
test = stats.ttest_ind
n_observations = (xp.asarray(rng.integers(10, 100, size=(10))),
xp.asarray(rng.integers(10, 100, size=(10))))
rvs = self.xp_normal(rng, xp=xp), self.xp_normal(rng, xp=xp)
significance = xp.asarray([0.01, 0.05, 0.1])
res = stats.power(test, rvs, n_observations, significance=significance)
significance = xp.broadcast_to(significance[:, xp.newaxis], res.power.shape)
xp_assert_close(res.power, significance, atol=1e-2)
@pytest.mark.skip_xp_backends('array_api_strict',
reason='currently combines integer and float arrays')
@pytest.mark.skip_xp_backends(cpu_only=True,
exceptions=['cupy', 'jax.numpy', 'dask.array'])
def test_ttest_1samp_power(self, xp):
# Check simulated ttest_1samp power against reference
rng = np.random.default_rng(254952548345528)
# Reference values computed with statmodels
# import numpy as np
# from statsmodels.stats.power import tt_solve_power
# tt_solve_power = np.vectorize(tt_solve_power)
# tt_solve_power([0.1, 0.5, 0.9], [[10], [20]], [[[0.01]], [[0.05]]])
ref = [[[0.0126515 , 0.10269751, 0.40415802],
[0.01657775, 0.29734608, 0.86228288]],
[[0.0592903 , 0.29317561, 0.71718121],
[0.07094116, 0.56450441, 0.96815163]]]
kwargs = {'popmean': xp.asarray([0.1, 0.5, 0.9])}
n_observations = xp.asarray([[10], [20]])
significance = xp.asarray([0.01, 0.05])
res = stats.power(stats.ttest_1samp, self.xp_normal(rng, xp=xp), n_observations,
significance=significance, kwargs=kwargs)
xp_assert_close(res.power, xp.asarray(ref), atol=1e-2)
@make_xp_test_case(permutation_test)
class TestPermutationTest:
rtol = 1e-14
def setup_method(self):
self.rng = np.random.default_rng(7170559330470561044)
# -- Input validation -- #
def test_permutation_test_iv(self, xp):
def stat(x, y, axis):
return stats.ttest_ind((x, y), axis).statistic
data = (xp.asarray([1, 2, 3]), xp.asarray([1, 2, 3]))
message = "each sample in `data` must contain two or more ..."
with pytest.raises(ValueError, match=message):
permutation_test((data[0], xp.asarray([0])), stat)
message = "`data` must be a tuple containing at least two samples"
with pytest.raises(ValueError, match=message):
permutation_test((1,), stat)
with pytest.raises(TypeError, match=message):
permutation_test(1, stat)
message = "`axis` must be an integer."
with pytest.raises(ValueError, match=message):
permutation_test(data, stat, axis=1.5)
message = "`permutation_type` must be in..."
with pytest.raises(ValueError, match=message):
permutation_test(data, stat,
permutation_type="ekki")
message = "`vectorized` must be `True`, `False`, or `None`."
with pytest.raises(ValueError, match=message):
permutation_test(data, stat, vectorized=1.5)
message = "`n_resamples` must be a positive integer."
with pytest.raises(ValueError, match=message):
permutation_test(data, stat, n_resamples=-1000)
message = "`n_resamples` must be a positive integer."
with pytest.raises(ValueError, match=message):
permutation_test(data, stat, n_resamples=1000.5)
message = "`batch` must be a positive integer or None."
with pytest.raises(ValueError, match=message):
permutation_test(data, stat, batch=-1000)
message = "`batch` must be a positive integer or None."
with pytest.raises(ValueError, match=message):
permutation_test(data, stat, batch=1000.5)
message = "`alternative` must be in..."
with pytest.raises(ValueError, match=message):
permutation_test(data, stat, alternative='ekki')
message = "SeedSequence expects int or sequence of ints"
with pytest.raises(TypeError, match=message):
permutation_test(data, stat, rng='herring')
# -- Test Parameters -- #
# SPEC-007 leave one call with seed to check it still works
@pytest.mark.parametrize('random_state', [np.random.RandomState,
np.random.default_rng])
@pytest.mark.parametrize('permutation_type',
['pairings', 'samples', 'independent'])
def test_batch(self, permutation_type, random_state, xp):
# make sure that the `batch` parameter is respected by checking the
# maximum batch size provided in calls to `statistic`
x = xp.asarray(self.rng.random(10))
y = xp.asarray(self.rng.random(10))
def statistic(x, y, axis):
batch_size = 1 if x.ndim == 1 else x.shape[0]
statistic.batch_size = max(batch_size, statistic.batch_size)
statistic.counter += 1
return xp.mean(x, axis=axis) - xp.mean(y, axis=axis)
statistic.counter = 0
statistic.batch_size = 0
kwds = {'n_resamples': 1000, 'permutation_type': permutation_type,
'vectorized': True}
res1 = stats.permutation_test((x, y), statistic, batch=1,
random_state=random_state(0), **kwds)
assert statistic.counter == 1001
assert statistic.batch_size == 1
statistic.counter = 0
res2 = stats.permutation_test((x, y), statistic, batch=50,
random_state=random_state(0), **kwds)
assert statistic.counter == 21
assert statistic.batch_size == 50
statistic.counter = 0
res3 = stats.permutation_test((x, y), statistic, batch=1000,
random_state=random_state(0), **kwds)
assert statistic.counter == 2
assert statistic.batch_size == 1000
xp_assert_equal(res1.pvalue, res3.pvalue)
xp_assert_equal(res2.pvalue, res3.pvalue)
# SPEC-007 leave at least one call with seed to check it still works
@pytest.mark.parametrize('random_state', [np.random.RandomState,
np.random.default_rng])
@pytest.mark.parametrize('permutation_type, exact_size',
[('pairings', special.factorial(3)**2),
('samples', 2**3),
('independent', special.binom(6, 3))])
def test_permutations(self, permutation_type, exact_size, random_state, xp):
# make sure that the `permutations` parameter is respected by checking
# the size of the null distribution
x = xp.asarray(self.rng.random(3))
y = xp.asarray(self.rng.random(3))
def statistic(x, y, axis):
return xp.mean(x, axis=axis) - xp.mean(y, axis=axis)
kwds = {'permutation_type': permutation_type,
'vectorized': True}
res = stats.permutation_test((x, y), statistic, n_resamples=3,
random_state=random_state(0), **kwds)
assert xp_size(res.null_distribution) == 3
res = stats.permutation_test((x, y), statistic, **kwds)
assert xp_size(res.null_distribution) == exact_size
# -- Randomized Permutation Tests -- #
# To get reasonable accuracy, these next three tests are somewhat slow.
# Originally, I had them passing for all combinations of permutation type,
# alternative, and RNG, but that takes too long for CI. Instead, split
# into three tests, each testing a particular combination of the three
# parameters.
def test_randomized_test_against_exact_both(self, xp):
# check that the randomized and exact tests agree to reasonable
# precision for permutation_type='both
alternative, rng = 'less', 0
nx, ny, permutations = 8, 9, 24000
assert special.binom(nx + ny, nx) > permutations
rng = np.random.default_rng(8235259808)
x = xp.asarray(rng.standard_normal(size=nx))
y = xp.asarray(rng.standard_normal(size=ny))
data = x, y
def statistic(x, y, axis):
return xp.mean(x, axis=axis) - xp.mean(y, axis=axis)
kwds = {'vectorized': True, 'permutation_type': 'independent',
'batch': 100, 'alternative': alternative, 'rng': rng}
res = permutation_test(data, statistic, n_resamples=permutations, **kwds)
res2 = permutation_test(data, statistic, n_resamples=xp.inf, **kwds)
assert res.statistic == res2.statistic
xp_assert_close(res.pvalue, res2.pvalue, atol=1e-2)
@pytest.mark.slow()
def test_randomized_test_against_exact_samples(self, xp):
# check that the randomized and exact tests agree to reasonable
# precision for permutation_type='samples'
alternative, rng = 'greater', None
nx, ny, permutations = 15, 15, 32000
assert 2**nx > permutations
rng = np.random.default_rng(8235259808)
x = xp.asarray(rng.standard_normal(size=nx))
y = xp.asarray(rng.standard_normal(size=ny))
data = x, y
def statistic(x, y, axis):
return xp.mean(x - y, axis=axis)
kwds = {'vectorized': True, 'permutation_type': 'samples',
'batch': 100, 'alternative': alternative, 'rng': rng}
res = permutation_test(data, statistic, n_resamples=permutations, **kwds)
res2 = permutation_test(data, statistic, n_resamples=xp.inf, **kwds)
assert res.statistic == res2.statistic
xp_assert_close(res.pvalue, res2.pvalue, atol=1e-2)
# I only need to skip torch on GPU because it doesn't have betaincc for pearsonr
@pytest.mark.skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'])
def test_randomized_test_against_exact_pairings(self, xp):
# check that the randomized and exact tests agree to reasonable
# precision for permutation_type='pairings'
alternative, rng = 'two-sided', self.rng
nx, ny, permutations = 8, 8, 40000
assert special.factorial(nx) > permutations
rng = np.random.default_rng(8235259808)
x = xp.asarray(rng.standard_normal(size=nx))
y = xp.asarray(rng.standard_normal(size=ny))
data = [x]
def statistic(x, axis):
return stats.pearsonr(x, y, axis=axis).statistic
kwds = {'vectorized': True, 'permutation_type': 'samples',
'batch': 100, 'alternative': alternative, 'rng': rng}
res = permutation_test(data, statistic, n_resamples=permutations, **kwds)
res2 = permutation_test(data, statistic, n_resamples=xp.inf, **kwds)
assert res.statistic == res2.statistic
xp_assert_close(res.pvalue, res2.pvalue, atol=1e-2)
# -- Independent (Unpaired) Sample Tests -- #
@pytest.mark.skip_xp_backends(eager_only=True) # TODO: change to jax_jit=False
@pytest.mark.parametrize('alternative', ("less", "greater", "two-sided"))
def test_against_ks_2samp(self, alternative, xp):
x = self.rng.normal(size=4, scale=1)
y = self.rng.normal(size=5, loc=3, scale=3)
expected = stats.ks_2samp(x, y, alternative=alternative, mode='exact')
def statistic(x, y, axis):
# todo: use `xp` as backend when `ks_2samp` is translated to array API
x, y = _xp_copy_to_numpy(x), _xp_copy_to_numpy(y)
res = stats.ks_2samp(x, y, axis=axis, mode='asymp', alternative=alternative)
res = xp.asarray(res.statistic)
return res[()] if res.ndim == 0 else res
# ks_2samp is always a one-tailed 'greater' test
# it's the statistic that changes (D+ vs D- vs max(D+, D-))
x, y = xp.asarray(x), xp.asarray(y)
res = permutation_test((x, y), statistic, n_resamples=np.inf,
alternative='greater', rng=self.rng)
xp_assert_close(res.statistic, xp.asarray(expected.statistic), rtol=self.rtol)
xp_assert_close(res.pvalue, xp.asarray(expected.pvalue), rtol=self.rtol)
@pytest.mark.skip_xp_backends(eager_only=True) # TODO: change to jax_jit=False
@pytest.mark.parametrize('alternative', ("less", "greater", "two-sided"))
def test_against_ansari(self, alternative, xp):
x = self.rng.normal(size=4, scale=1)
y = self.rng.normal(size=5, scale=3)
# ansari has a different convention for 'alternative'
alternative_correspondence = {"less": "greater",
"greater": "less",
"two-sided": "two-sided"}
alternative_scipy = alternative_correspondence[alternative]
expected = stats.ansari(x, y, alternative=alternative_scipy)
def statistic(x, y, axis):
# todo: use `xp` as backend when `ansari` is translated to array API
x, y = _xp_copy_to_numpy(x), _xp_copy_to_numpy(y)
res = stats.ansari(x, y, axis=axis)
res = xp.asarray(res.statistic)
return res[()] if res.ndim == 0 else res
x, y = xp.asarray(x), xp.asarray(y)
res = permutation_test((x, y), statistic, n_resamples=np.inf,
alternative=alternative, rng=self.rng)
xp_assert_close(res.statistic, xp.asarray(expected.statistic), rtol=self.rtol)
xp_assert_close(res.pvalue, xp.asarray(expected.pvalue), rtol=self.rtol)
@skip_xp_backends('cupy', reason='needs mannwhitneyu')
@skip_xp_backends(eager_only=True) # mannwhitneyu does input validation
@pytest.mark.parametrize('alternative', ("less", "greater", "two-sided"))
def test_against_mannwhitneyu(self, alternative, xp):
x = stats.uniform.rvs(size=(3, 5, 2), loc=0, random_state=self.rng)
y = stats.uniform.rvs(size=(3, 5, 2), loc=0.05, random_state=self.rng)
expected = stats.mannwhitneyu(x, y, axis=1, alternative=alternative)
def statistic(x, y, axis):
return stats.mannwhitneyu(x, y, axis=axis, method='asymptotic').statistic
x, y = xp.asarray(x), xp.asarray(y)
res = permutation_test((x, y), statistic, vectorized=True,
n_resamples=xp.inf, alternative=alternative,
axis=1, rng=self.rng)
xp_assert_close(res.statistic, xp.asarray(expected.statistic), rtol=self.rtol)
xp_assert_close(res.pvalue, xp.asarray(expected.pvalue), rtol=self.rtol)
@skip_xp_backends('cupy', reason='needs cramervonmises_2samp')
@skip_xp_backends(eager_only=True) # cramervonmises_2samp does input validation
@skip_xp_backends(cpu_only=True) # torch doesn't have `kv`
def test_against_cvm(self, xp):
x = stats.norm.rvs(size=4, scale=1, random_state=self.rng)
y = stats.norm.rvs(size=5, loc=3, scale=3, random_state=self.rng)
expected = stats.cramervonmises_2samp(x, y, method='exact')
def statistic(x, y, axis):
res = stats.cramervonmises_2samp(x, y, axis=axis, method='asymptotic')
return res.statistic
# cramervonmises_2samp has only one alternative, greater
x, y = xp.asarray(x), xp.asarray(y)
res = permutation_test((x, y), statistic, n_resamples=np.inf,
alternative='greater', rng=self.rng)
xp_assert_close(res.statistic, xp.asarray(expected.statistic), rtol=self.rtol)
xp_assert_close(res.pvalue, xp.asarray(expected.pvalue), rtol=self.rtol)
@skip_xp_backends('cupy', reason='needs kruskal')
@skip_xp_backends(eager_only=True) # kruskal does input validation
@pytest.mark.parametrize('axis', (-1, 2))
def test_vectorized_nsamp_ptype_both(self, axis, xp):
# statistic only available for NumPy
# Test that permutation_test with permutation_type='independent' works
# properly for a 3-sample statistic with nd array samples of different
# (but compatible) shapes and ndims. Show that exact permutation test
# and random permutation tests approximate SciPy's asymptotic pvalues
# and that exact and random permutation test results are even closer
# to one another (than they are to the asymptotic results).
# Three samples, different (but compatible) shapes with different ndims
rng = np.random.default_rng(6709265303529651545)
x = rng.random(size=(3))
y = rng.random(size=(1, 3, 2))
z = rng.random(size=(2, 1, 4))
data = (x, y, z)
expected = stats.kruskal(*data, axis=axis)
# Define the statistic (and pvalue for comparison)
def statistic(*data, axis):
return stats.kruskal(*data, axis=axis).statistic
# Calculate exact and randomized permutation results
kwds = {'axis': axis, 'alternative': 'greater',
'permutation_type': 'independent', 'rng': rng}
data = [xp.asarray(data_) for data_ in data]
res = permutation_test(data, statistic, n_resamples=xp.inf, **kwds)
res2 = permutation_test(data, statistic, n_resamples=1000, **kwds)
# Check results
xp_assert_close(res.statistic, xp.asarray(expected.statistic), rtol=self.rtol*5)
xp_assert_close(res.statistic, res2.statistic, rtol=self.rtol*5)
xp_assert_close(res.pvalue, xp.asarray(expected.pvalue), atol=6e-2)
xp_assert_close(res.pvalue, res2.pvalue, atol=3e-2)
# -- Paired-Sample Tests -- #
@pytest.mark.skip_xp_backends(eager_only=True) # TODO: change to jax_jit=False
@pytest.mark.parametrize('alternative', ("less", "greater", "two-sided"))
def test_against_wilcoxon(self, alternative, xp):
x = stats.uniform.rvs(size=(3, 6, 2), loc=0, random_state=self.rng)
y = stats.uniform.rvs(size=(3, 6, 2), loc=0.05, random_state=self.rng)
expected = stats.wilcoxon(x, y, alternative=alternative, axis=1)
# We'll check both 1- and 2-sample versions of the same test;
# we expect identical results to wilcoxon in all cases.
def statistic_1samp_1d(z, axis):
# todo: use `xp` as backend when `wilcoxon` is translated to array API
# 'less' ensures we get the same of two statistics every time
z = _xp_copy_to_numpy(z)
res = stats.wilcoxon(z, alternative='less', axis=axis)
res = xp.asarray(res.statistic)
return res[()] if res.ndim == 0 else res
def statistic_2samp_1d(x, y, axis):
# todo: use `xp` as backend when `wilcoxon` is translated to array API
x, y = _xp_copy_to_numpy(x), _xp_copy_to_numpy(y)
res = stats.wilcoxon(x, y, alternative='less', axis=axis)
res = xp.asarray(res.statistic)
return res[()] if res.ndim == 0 else res
x, y = xp.asarray(x), xp.asarray(y)
kwds = {'axis': 1, 'alternative': alternative, 'permutation_type': 'samples',
'rng': self.rng, 'n_resamples': np.inf}
res1 = permutation_test((x-y,), statistic_1samp_1d, **kwds)
res2 = permutation_test((x, y), statistic_2samp_1d, **kwds)
# `wilcoxon` returns a different statistic with 'two-sided'
xp_assert_close(res1.statistic, res2.statistic, rtol=self.rtol)
if alternative != 'two-sided':
xp_assert_close(res2.statistic, xp.asarray(expected.statistic),
rtol=self.rtol)
xp_assert_close(res2.pvalue, xp.asarray(expected.pvalue), rtol=self.rtol)
xp_assert_close(res1.pvalue, res2.pvalue, rtol=self.rtol)
@pytest.mark.parametrize('alternative', ("less", "greater", "two-sided"))
def test_against_binomtest(self, alternative, xp):
x = self.rng.integers(0, 2, size=10)
x[x == 0] = -1
# More naturally, the test would flip elements between 0 and one.
# However, permutation_test will flip the _signs_ of the elements.
# So we have to work with +1/-1 instead of 1/0.
def statistic(x, axis=0):
xp_ = array_namespace(x)
return xp_.count_nonzero(x > 0, axis=axis)
k, n, p = statistic(x), 10, 0.5
expected = stats.binomtest(k, n, p, alternative=alternative)
res = stats.permutation_test((xp.asarray(x, dtype=xp.float64),), statistic,
vectorized=True,
permutation_type='samples', n_resamples=xp.inf,
rng=self.rng, alternative=alternative)
xp_assert_close(res.pvalue, xp.asarray(expected.pvalue), rtol=self.rtol)
# -- Exact Association Tests -- #
@pytest.mark.skip_xp_backends(eager_only=True) # TODO: change to jax_jit=False
def test_against_kendalltau(self, xp):
x = self.rng.normal(size=6)
y = x + self.rng.normal(size=6)
expected = stats.kendalltau(x, y, method='exact')
def statistic(x, axis):
# todo: use `xp` as backend when `kendalltau` is translated to array API
x = _xp_copy_to_numpy(x)
res = stats.kendalltau(x, y, method='asymptotic', axis=axis)
res = xp.asarray(res.statistic)
return res[()] if res.ndim == 0 else res
# kendalltau currently has only one alternative, two-sided
x = xp.asarray(x)
res = permutation_test((x,), statistic, permutation_type='pairings',
n_resamples=np.inf, rng=self.rng)
xp_assert_close(res.statistic, xp.asarray(expected.statistic), rtol=self.rtol)
xp_assert_close(res.pvalue, xp.asarray(expected.pvalue), rtol=self.rtol)
@pytest.mark.parametrize('alternative', ('less', 'greater', 'two-sided'))
def test_against_fisher_exact(self, alternative, xp):
# x and y are binary random variables with some dependence
rng = np.random.default_rng(6235696159000529929)
x = (rng.random(7) > 0.6).astype(float)
y = (rng.random(7) + 0.25*x > 0.6).astype(float)
tab = stats.contingency.crosstab(x, y)[1]
x, y = xp.asarray(x), xp.asarray(y)
def statistic(x, axis):
return xp.count_nonzero((x == 1) & (y == 1), axis=axis)
res = permutation_test((x,), statistic, permutation_type='pairings',
n_resamples=xp.inf, alternative=alternative,
rng=rng)
res2 = stats.fisher_exact(tab, alternative=alternative)
xp_assert_close(res.pvalue, xp.asarray(res2.pvalue, dtype=x.dtype))
@pytest.mark.xslow()
@pytest.mark.parametrize('axis', (-2, 1))
def test_vectorized_nsamp_ptype_samples(self, axis):
# statistic only available for NumPy, and it's a pain to vectorize
# Test that permutation_test with permutation_type='samples' works
# properly for a 3-sample statistic with nd array samples of different
# (but compatible) shapes and ndims. Show that exact permutation test
# reproduces SciPy's exact pvalue and that random permutation test
# approximates it.
x = self.rng.random(size=(2, 4, 3))
y = self.rng.random(size=(1, 4, 3))
z = self.rng.random(size=(2, 4, 1))
x = stats.rankdata(x, axis=axis)
y = stats.rankdata(y, axis=axis)
z = stats.rankdata(z, axis=axis)
y = y[0] # to check broadcast with different ndim
data = (x, y, z)
def statistic1d(*data):
return stats.page_trend_test(data, ranked=True,
method='asymptotic').statistic
def pvalue1d(*data):
return stats.page_trend_test(data, ranked=True,
method='exact').pvalue
statistic = _resampling._vectorize_statistic(statistic1d)
pvalue = _resampling._vectorize_statistic(pvalue1d)
expected_statistic = statistic(*np.broadcast_arrays(*data), axis=axis)
expected_pvalue = pvalue(*np.broadcast_arrays(*data), axis=axis)
# Let's forgive this use of an integer seed, please.
kwds = {'vectorized': False, 'axis': axis, 'alternative': 'greater',
'permutation_type': 'pairings', 'rng': 0}
res = permutation_test(data, statistic1d, n_resamples=np.inf, **kwds)
res2 = permutation_test(data, statistic1d, n_resamples=5000, **kwds)
assert_allclose(res.statistic, expected_statistic, rtol=self.rtol)
assert_allclose(res.statistic, res2.statistic, rtol=self.rtol)
assert_allclose(res.pvalue, expected_pvalue, rtol=self.rtol)
assert_allclose(res.pvalue, res2.pvalue, atol=3e-2)
# -- Test Against External References -- #
tie_case_1 = {'x': [1, 2, 3, 4], 'y': [1.5, 2, 2.5],
'expected_less': 0.2000000000,
'expected_2sided': 0.4, # 2*expected_less
'expected_Pr_gte_S_mean': 0.3428571429, # see note below
'expected_statistic': 7.5,
'expected_avg': 9.142857, 'expected_std': 1.40698}
tie_case_2 = {'x': [111, 107, 100, 99, 102, 106, 109, 108],
'y': [107, 108, 106, 98, 105, 103, 110, 105, 104],
'expected_less': 0.1555738379,
'expected_2sided': 0.3111476758,
'expected_Pr_gte_S_mean': 0.2969971205, # see note below
'expected_statistic': 32.5,
'expected_avg': 38.117647, 'expected_std': 5.172124}
@pytest.mark.skip_xp_backends(eager_only=True) # TODO: change to jax_jit=False
@pytest.mark.xslow() # only the second case is slow, really
@pytest.mark.parametrize('case', (tie_case_1, tie_case_2))
def test_with_ties(self, case, xp):
"""
Results above from SAS PROC NPAR1WAY, e.g.
DATA myData;
INPUT X Y;
CARDS;
1 1
1 2
1 3
1 4
2 1.5
2 2
2 2.5
ods graphics on;
proc npar1way AB data=myData;
class X;
EXACT;
run;
ods graphics off;
Note: SAS provides Pr >= |S-Mean|, which is different from our
definition of a two-sided p-value.
"""
x = case['x']
y = case['y']
expected_statistic = xp.asarray(case['expected_statistic'])
expected_less = xp.asarray(case['expected_less'])
expected_2sided = xp.asarray(case['expected_2sided'])
expected_Pr_gte_S_mean = xp.asarray(case['expected_Pr_gte_S_mean'])
expected_avg = xp.asarray(case['expected_avg'])
expected_std = xp.asarray(case['expected_std'])
def statistic(x, y, axis):
# todo: use `xp` as backend when `ansari` is translated to array API
x, y = _xp_copy_to_numpy(x), _xp_copy_to_numpy(y)
res = stats.ansari(x, y, axis=axis)
res = xp.asarray(res.statistic)
return res[()] if res.ndim == 0 else res
dtype = xp_default_dtype(xp)
x, y = xp.asarray(x, dtype=dtype), xp.asarray(y, dtype=dtype)
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore", "Ties preclude use of exact statistic", UserWarning)
res = permutation_test((x, y), statistic, n_resamples=np.inf,
alternative='less')
res2 = permutation_test((x, y), statistic, n_resamples=np.inf,
alternative='two-sided')
xp_assert_close(res.statistic, expected_statistic, rtol=self.rtol)
xp_assert_close(res.pvalue, expected_less, atol=1e-10)
xp_assert_close(res2.pvalue, expected_2sided, atol=1e-10)
xp_assert_close(xp.mean(res2.null_distribution), expected_avg, rtol=1e-6)
xp_assert_close(xp.std(res2.null_distribution), expected_std, rtol=1e-6)
# SAS provides Pr >= |S-Mean|; might as well check against that, too
S = res.statistic
mean = xp.mean(res.null_distribution)
n = res.null_distribution.shape[0]
Pr_gte_S_mean = xp.astype(xp.count_nonzero(
xp.abs(res.null_distribution-mean) >= xp.abs(S-mean)), S.dtype) / n
xp_assert_close(Pr_gte_S_mean, expected_Pr_gte_S_mean)
@pytest.mark.slow
@pytest.mark.parametrize('alternative, expected_pvalue',
(('less', 0.9708333333333),
('greater', 0.05138888888889),
('two-sided', 0.1027777777778)))
# I only need to skip torch on GPU because it doesn't have betaincc for pearsonr
@pytest.mark.skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'])
@pytest.mark.skip_xp_backends(eager_only=True) # TODO: change to jax_jit=False
def test_against_spearmanr_in_R(self, alternative, expected_pvalue, xp):
"""
Results above from R cor.test, e.g.
options(digits=16)
x <- c(1.76405235, 0.40015721, 0.97873798,
2.2408932, 1.86755799, -0.97727788)
y <- c(2.71414076, 0.2488, 0.87551913,
2.6514917, 2.01160156, 0.47699563)
cor.test(x, y, method = "spearm", alternative = "t")
"""
# data comes from
# np.random.seed(0)
# x = stats.norm.rvs(size=6)
# y = x + stats.norm.rvs(size=6)
x = xp.asarray([1.76405235, 0.40015721, 0.97873798,
2.2408932, 1.86755799, -0.97727788])
y = xp.asarray([2.71414076, 0.2488, 0.87551913,
2.6514917, 2.01160156, 0.47699563])
expected_statistic = 0.7714285714285715
y = xp.asarray(stats.rankdata(_xp_copy_to_numpy(y)))
def statistic(x, axis):
# `spearmanr` is not array api compatible, but `pearsonr` is. So for now
# use _xp_copy_to_numpy just for ranking so we can run this test w/ CuPy.
# TODO: use `xp` as backend when cupy works with `rankdata`
x = xp.asarray(stats.rankdata(_xp_copy_to_numpy(x), axis=axis))
return stats.pearsonr(x, y, axis=axis).statistic
res = permutation_test((x,), statistic, permutation_type='pairings',
n_resamples=xp.inf, alternative=alternative)
xp_assert_close(res.statistic, xp.asarray(expected_statistic), rtol=self.rtol)
xp_assert_close(res.pvalue, xp.asarray(expected_pvalue), atol=1e-13)
@pytest.mark.parametrize("batch", (-1, 0))
def test_batch_generator_iv(self, batch):
with pytest.raises(ValueError, match="`batch` must be positive."):
list(_resampling._batch_generator([1, 2, 3], batch))
batch_generator_cases = [(range(0), 3, []),
(range(6), 3, [[0, 1, 2], [3, 4, 5]]),
(range(8), 3, [[0, 1, 2], [3, 4, 5], [6, 7]])]
@pytest.mark.parametrize("iterable, batch, expected",
batch_generator_cases)
def test_batch_generator(self, iterable, batch, expected):
got = list(_resampling._batch_generator(iterable, batch))
assert got == expected
@pytest.mark.fail_slow(2)
# I only need to skip torch on GPU because it doesn't have betaincc for pearsonr
@pytest.mark.skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'])
def test_finite_precision_statistic(self, xp):
# Some statistics return numerically distinct values when the values
# should be equal in theory. Test that `permutation_test` accounts
# for this in some way.
x = xp.asarray([1., 2., 4., 3.], dtype=xp.float64)
y = xp.asarray([2., 4., 6., 8.], dtype=xp.float64)
def statistic(x, y, axis):
return stats.pearsonr(x, y, axis=axis)[0]
res = stats.permutation_test((x, y), statistic,
permutation_type='pairings')
r, pvalue, null = res.statistic, res.pvalue, res.null_distribution
correct_p = 2 * float(xp.count_nonzero(null >= r - 1e-14)) / null.shape[0]
assert pvalue == correct_p == 1/3
# Compare against other exact correlation tests using R corr.test
# options(digits=16)
# x = c(1, 2, 4, 3)
# y = c(2, 4, 6, 8)
# cor.test(x, y, alternative = "t", method = "spearman") # 0.333333333
# cor.test(x, y, alternative = "t", method = "kendall") # 0.333333333
def test_all_partitions_concatenated():
# make sure that _all_paritions_concatenated produces the correct number
# of partitions of the data into samples of the given sizes and that
# all are unique
n = np.array([3, 2, 4], dtype=int)
nc = np.cumsum(n)
all_partitions = set()
counter = 0
for partition_concatenated in _resampling._all_partitions_concatenated(n):
counter += 1
partitioning = np.split(partition_concatenated, nc[:-1])
all_partitions.add(tuple([frozenset(i) for i in partitioning]))
expected = np.prod([special.binom(sum(n[i:]), sum(n[i+1:]))
for i in range(len(n)-1)])
assert_equal(counter, expected)
assert_equal(len(all_partitions), expected)
@pytest.mark.parametrize('fun_name',
['bootstrap', 'permutation_test', 'monte_carlo_test'])
def test_parameter_vectorized(fun_name):
# Check that parameter `vectorized` is working as desired for all
# resampling functions. Results don't matter; just don't fail asserts.
rng = np.random.default_rng(75245098234592)
sample = rng.random(size=10)
def rvs(size): # needed by `monte_carlo_test`
return stats.norm.rvs(size=size, random_state=rng)
fun_options = {'bootstrap': {'data': (sample,), 'rng': rng,
'method': 'percentile'},
'permutation_test': {'data': (sample,), 'rng': rng,
'permutation_type': 'samples'},
'monte_carlo_test': {'sample': sample, 'rvs': rvs}}
common_options = {'n_resamples': 100}
fun = getattr(stats, fun_name)
options = fun_options[fun_name]
options.update(common_options)
def statistic(x, axis):
assert x.ndim > 1 or np.array_equal(x, sample)
return np.mean(x, axis=axis)
fun(statistic=statistic, vectorized=None, **options)
fun(statistic=statistic, vectorized=True, **options)
def statistic(x):
assert x.ndim == 1
return np.mean(x)
fun(statistic=statistic, vectorized=None, **options)
fun(statistic=statistic, vectorized=False, **options)
class TestMonteCarloMethod:
def test_rvs_and_random_state(self):
message = "Use of `rvs` and `rng` are mutually exclusive."
rng = np.random.default_rng(34982345)
with pytest.raises(ValueError, match=message):
stats.MonteCarloMethod(rvs=rng.random, rng=rng)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448import threading
import pickle
import pytest
from copy import deepcopy
import platform
import sys
import math
import warnings
import numpy as np
from numpy.testing import assert_allclose, assert_equal
from scipy.stats.sampling import (
TransformedDensityRejection,
DiscreteAliasUrn,
DiscreteGuideTable,
NumericalInversePolynomial,
NumericalInverseHermite,
RatioUniforms,
SimpleRatioUniforms,
UNURANError
)
from pytest import raises as assert_raises
from scipy import stats
from scipy import special
from scipy.stats import chisquare, cramervonmises
from scipy.stats._distr_params import distdiscrete, distcont
from scipy._lib._util import check_random_state
# common test data: this data can be shared between all the tests.
# Normal distribution shared between all the continuous methods
class StandardNormal:
def pdf(self, x):
# normalization constant needed for NumericalInverseHermite
return 1./np.sqrt(2.*np.pi) * np.exp(-0.5 * x*x)
def dpdf(self, x):
return 1./np.sqrt(2.*np.pi) * -x * np.exp(-0.5 * x*x)
def cdf(self, x):
return special.ndtr(x)
all_methods = [
("TransformedDensityRejection", {"dist": StandardNormal()}),
("DiscreteAliasUrn", {"dist": [0.02, 0.18, 0.8]}),
("DiscreteGuideTable", {"dist": [0.02, 0.18, 0.8]}),
("NumericalInversePolynomial", {"dist": StandardNormal()}),
("NumericalInverseHermite", {"dist": StandardNormal()}),
("SimpleRatioUniforms", {"dist": StandardNormal(), "mode": 0})
]
if (sys.implementation.name == 'pypy'
and sys.implementation.version < (7, 3, 10)):
# changed in PyPy for v7.3.10
floaterr = r"unsupported operand type for float\(\): 'list'"
else:
floaterr = r"must be real number, not list"
# Make sure an internal error occurs in UNU.RAN when invalid callbacks are
# passed. Moreover, different generators throw different error messages.
# So, in case of an `UNURANError`, we do not validate the error message.
bad_pdfs_common = [
# Negative PDF
(lambda x: -x, UNURANError, r"..."),
# Returning wrong type
(lambda x: [], TypeError, floaterr),
# Undefined name inside the function
(lambda x: foo, NameError, r"name 'foo' is not defined"), # type: ignore[name-defined] # noqa: F821, E501
# Infinite value returned => Overflow error.
(lambda x: np.inf, UNURANError, r"..."),
# NaN value => internal error in UNU.RAN
(lambda x: np.nan, UNURANError, r"..."),
# signature of PDF wrong
(lambda: 1.0, TypeError, r"takes 0 positional arguments but 1 was given")
]
# same approach for dpdf
bad_dpdf_common = [
# Infinite value returned.
(lambda x: np.inf, UNURANError, r"..."),
# NaN value => internal error in UNU.RAN
(lambda x: np.nan, UNURANError, r"..."),
# Returning wrong type
(lambda x: [], TypeError, floaterr),
# Undefined name inside the function
(lambda x: foo, NameError, r"name 'foo' is not defined"), # type: ignore[name-defined] # noqa: F821, E501
# signature of dPDF wrong
(lambda: 1.0, TypeError, r"takes 0 positional arguments but 1 was given")
]
# same approach for logpdf
bad_logpdfs_common = [
# Returning wrong type
(lambda x: [], TypeError, floaterr),
# Undefined name inside the function
(lambda x: foo, NameError, r"name 'foo' is not defined"), # type: ignore[name-defined] # noqa: F821, E501
# Infinite value returned => Overflow error.
(lambda x: np.inf, UNURANError, r"..."),
# NaN value => internal error in UNU.RAN
(lambda x: np.nan, UNURANError, r"..."),
# signature of logpdf wrong
(lambda: 1.0, TypeError, r"takes 0 positional arguments but 1 was given")
]
bad_pv_common = [
([], r"must contain at least one element"),
([[1.0, 0.0]], r"wrong number of dimensions \(expected 1, got 2\)"),
([0.2, 0.4, np.nan, 0.8], r"must contain only finite / non-nan values"),
([0.2, 0.4, np.inf, 0.8], r"must contain only finite / non-nan values"),
([0.0, 0.0], r"must contain at least one non-zero value"),
]
# size of the domains is incorrect
bad_sized_domains = [
# > 2 elements in the domain
((1, 2, 3), ValueError, r"must be a length 2 tuple"),
# empty domain
((), ValueError, r"must be a length 2 tuple")
]
# domain values are incorrect
bad_domains = [
((2, 1), UNURANError, r"left >= right"),
((1, 1), UNURANError, r"left >= right"),
]
# infinite and nan values present in domain.
inf_nan_domains = [
# left >= right
((10, 10), UNURANError, r"left >= right"),
((np.inf, np.inf), UNURANError, r"left >= right"),
((-np.inf, -np.inf), UNURANError, r"left >= right"),
((np.inf, -np.inf), UNURANError, r"left >= right"),
# Also include nans in some of the domains.
((-np.inf, np.nan), ValueError, r"only non-nan values"),
((np.nan, np.inf), ValueError, r"only non-nan values")
]
# `nan` values present in domain. Some distributions don't support
# infinite tails, so don't mix the nan values with infinities.
nan_domains = [
((0, np.nan), ValueError, r"only non-nan values"),
((np.nan, np.nan), ValueError, r"only non-nan values")
]
# all the methods should throw errors for nan, bad sized, and bad valued
# domains.
@pytest.mark.parametrize("domain, err, msg",
bad_domains + bad_sized_domains +
nan_domains) # type: ignore[operator]
@pytest.mark.parametrize("method, kwargs", all_methods)
def test_bad_domain(domain, err, msg, method, kwargs):
Method = getattr(stats.sampling, method)
with pytest.raises(err, match=msg):
Method(**kwargs, domain=domain)
@pytest.mark.parametrize("method, kwargs", all_methods)
def test_random_state(method, kwargs):
Method = getattr(stats.sampling, method)
# simple seed that works for any version of NumPy
seed = 123
rng1 = Method(**kwargs, random_state=seed)
rng2 = Method(**kwargs, random_state=seed)
assert_equal(rng1.rvs(100), rng2.rvs(100))
# global seed
rng = np.random.RandomState(123)
rng1 = Method(**kwargs)
rvs1 = rng1.rvs(100, random_state=rng)
np.random.seed(None) # valid use of np.random.seed
rng2 = Method(**kwargs, random_state=123)
rvs2 = rng2.rvs(100)
assert_equal(rvs1, rvs2)
# Generator seed for new NumPy
# when a RandomState is given, it should take the bitgen_t
# member of the class and create a Generator instance.
seed1 = np.random.RandomState(np.random.MT19937(123))
seed2 = np.random.Generator(np.random.MT19937(123))
rng1 = Method(**kwargs, random_state=seed1)
rng2 = Method(**kwargs, random_state=seed2)
assert_equal(rng1.rvs(100), rng2.rvs(100))
def test_set_random_state():
rng1 = TransformedDensityRejection(StandardNormal(), random_state=123)
rng2 = TransformedDensityRejection(StandardNormal())
rng2.set_random_state(123)
assert_equal(rng1.rvs(100), rng2.rvs(100))
rng = TransformedDensityRejection(StandardNormal(), random_state=123)
rvs1 = rng.rvs(100)
rng.set_random_state(123)
rvs2 = rng.rvs(100)
assert_equal(rvs1, rvs2)
def test_threading_behaviour():
# Test if the API is thread-safe.
# This verifies if the lock mechanism and the use of `PyErr_Occurred`
# is correct.
errors = {"err1": None, "err2": None}
class Distribution:
def __init__(self, pdf_msg):
self.pdf_msg = pdf_msg
def pdf(self, x):
if 49.9 < x < 50.0:
raise ValueError(self.pdf_msg)
return x
def dpdf(self, x):
return 1
def func1():
dist = Distribution('foo')
rng = TransformedDensityRejection(dist, domain=(10, 100),
random_state=12)
try:
rng.rvs(100000)
except ValueError as e:
errors['err1'] = e.args[0]
def func2():
dist = Distribution('bar')
rng = TransformedDensityRejection(dist, domain=(10, 100),
random_state=2)
try:
rng.rvs(100000)
except ValueError as e:
errors['err2'] = e.args[0]
t1 = threading.Thread(target=func1)
t2 = threading.Thread(target=func2)
t1.start()
t2.start()
t1.join()
t2.join()
assert errors['err1'] == 'foo'
assert errors['err2'] == 'bar'
@pytest.mark.parametrize("method, kwargs", all_methods)
def test_pickle(method, kwargs):
Method = getattr(stats.sampling, method)
rng1 = Method(**kwargs, random_state=123)
obj = pickle.dumps(rng1)
rng2 = pickle.loads(obj)
assert_equal(rng1.rvs(100), rng2.rvs(100))
@pytest.mark.parametrize("size", [None, 0, (0, ), 1, (10, 3), (2, 3, 4, 5),
(0, 0), (0, 1)])
def test_rvs_size(size):
# As the `rvs` method is present in the base class and shared between
# all the classes, we can just test with one of the methods.
rng = TransformedDensityRejection(StandardNormal())
if size is None:
assert np.isscalar(rng.rvs(size))
else:
if np.isscalar(size):
size = (size, )
assert rng.rvs(size).shape == size
def test_with_scipy_distribution():
# test if the setup works with SciPy's rv_frozen distributions
dist = stats.norm()
urng = np.random.default_rng(0)
rng = NumericalInverseHermite(dist, random_state=urng)
u = np.linspace(0, 1, num=100)
check_cont_samples(rng, dist, dist.stats())
assert_allclose(dist.ppf(u), rng.ppf(u))
# test if it works with `loc` and `scale`
dist = stats.norm(loc=10., scale=5.)
rng = NumericalInverseHermite(dist, random_state=urng)
check_cont_samples(rng, dist, dist.stats())
assert_allclose(dist.ppf(u), rng.ppf(u))
# check for discrete distributions
dist = stats.binom(10, 0.2)
rng = DiscreteAliasUrn(dist, random_state=urng)
domain = dist.support()
pv = dist.pmf(np.arange(domain[0], domain[1]+1))
check_discr_samples(rng, pv, dist.stats())
def check_cont_samples(rng, dist, mv_ex, rtol=1e-7, atol=1e-1):
rvs = rng.rvs(100000)
mv = rvs.mean(), rvs.var()
# test the moments only if the variance is finite
if np.isfinite(mv_ex[1]):
assert_allclose(mv, mv_ex, rtol=rtol, atol=atol)
# Cramer Von Mises test for goodness-of-fit
rvs = rng.rvs(500)
dist.cdf = np.vectorize(dist.cdf)
pval = cramervonmises(rvs, dist.cdf).pvalue
assert pval > 0.1
def check_discr_samples(rng, pv, mv_ex, rtol=1e-3, atol=1e-1):
rvs = rng.rvs(100000)
# test if the first few moments match
mv = rvs.mean(), rvs.var()
assert_allclose(mv, mv_ex, rtol=rtol, atol=atol)
# normalize
pv = pv / pv.sum()
# chi-squared test for goodness-of-fit
obs_freqs = np.zeros_like(pv)
_, freqs = np.unique(rvs, return_counts=True)
freqs = freqs / freqs.sum()
obs_freqs[:freqs.size] = freqs
pval = chisquare(obs_freqs, pv).pvalue
assert pval > 0.1
def test_warning_center_not_in_domain():
# UNURAN will warn if the center provided or the one computed w/o the
# domain is outside of the domain
msg = "102 : center moved into domain of distribution"
with pytest.warns(RuntimeWarning, match=msg):
NumericalInversePolynomial(StandardNormal(), center=0, domain=(3, 5))
with pytest.warns(RuntimeWarning, match=msg):
NumericalInversePolynomial(StandardNormal(), domain=(3, 5))
@pytest.mark.parametrize('method', ["SimpleRatioUniforms",
"NumericalInversePolynomial",
"TransformedDensityRejection"])
def test_error_mode_not_in_domain(method):
# UNURAN raises an error if the mode is not in the domain
# the behavior is different compared to the case that center is not in the
# domain. mode is supposed to be the exact value, center can be an
# approximate value
Method = getattr(stats.sampling, method)
msg = "17 : mode not in domain"
with pytest.raises(UNURANError, match=msg):
Method(StandardNormal(), mode=0, domain=(3, 5))
@pytest.mark.parametrize('method', ["NumericalInverseHermite",
"NumericalInversePolynomial"])
class TestQRVS:
def test_input_validation(self, method):
match = "`qmc_engine` must be an instance of..."
with pytest.raises(ValueError, match=match):
Method = getattr(stats.sampling, method)
gen = Method(StandardNormal())
gen.qrvs(qmc_engine=0)
# issues with QMCEngines and old NumPy
Method = getattr(stats.sampling, method)
gen = Method(StandardNormal())
match = "`d` must be consistent with dimension of `qmc_engine`."
with pytest.raises(ValueError, match=match):
gen.qrvs(d=3, qmc_engine=stats.qmc.Halton(2))
qrngs = [None, stats.qmc.Sobol(1, seed=0), stats.qmc.Halton(3, seed=0)]
# `size=None` should not add anything to the shape, `size=1` should
sizes = [(None, tuple()), (1, (1,)), (4, (4,)),
((4,), (4,)), ((2, 4), (2, 4))] # type: ignore
# Neither `d=None` nor `d=1` should add anything to the shape
ds = [(None, tuple()), (1, tuple()), (3, (3,))]
@pytest.mark.parametrize('qrng', qrngs)
@pytest.mark.parametrize('size_in, size_out', sizes)
@pytest.mark.parametrize('d_in, d_out', ds)
@pytest.mark.thread_unsafe(reason="fails in parallel")
def test_QRVS_shape_consistency(self, qrng, size_in, size_out,
d_in, d_out, method):
w32 = sys.platform == "win32" and platform.architecture()[0] == "32bit"
if w32 and method == "NumericalInversePolynomial":
pytest.xfail("NumericalInversePolynomial.qrvs fails for Win "
"32-bit")
dist = StandardNormal()
Method = getattr(stats.sampling, method)
gen = Method(dist)
# If d and qrng.d are inconsistent, an error is raised
if d_in is not None and qrng is not None and qrng.d != d_in:
match = "`d` must be consistent with dimension of `qmc_engine`."
with pytest.raises(ValueError, match=match):
gen.qrvs(size_in, d=d_in, qmc_engine=qrng)
return
# Sometimes d is really determined by qrng
if d_in is None and qrng is not None and qrng.d != 1:
d_out = (qrng.d,)
shape_expected = size_out + d_out
qrng2 = deepcopy(qrng)
qrvs = gen.qrvs(size=size_in, d=d_in, qmc_engine=qrng)
if size_in is not None:
assert qrvs.shape == shape_expected
if qrng2 is not None:
uniform = qrng2.random(np.prod(size_in) or 1)
qrvs2 = stats.norm.ppf(uniform).reshape(shape_expected)
assert_allclose(qrvs, qrvs2, atol=1e-12)
def test_QRVS_size_tuple(self, method):
# QMCEngine samples are always of shape (n, d). When `size` is a tuple,
# we set `n = prod(size)` in the call to qmc_engine.random, transform
# the sample, and reshape it to the final dimensions. When we reshape,
# we need to be careful, because the _columns_ of the sample returned
# by a QMCEngine are "independent"-ish, but the elements within the
# columns are not. We need to make sure that this doesn't get mixed up
# by reshaping: qrvs[..., i] should remain "independent"-ish of
# qrvs[..., i+1], but the elements within qrvs[..., i] should be
# transformed from the same low-discrepancy sequence.
dist = StandardNormal()
Method = getattr(stats.sampling, method)
gen = Method(dist)
size = (3, 4)
d = 5
qrng = stats.qmc.Halton(d, seed=0)
qrng2 = stats.qmc.Halton(d, seed=0)
uniform = qrng2.random(np.prod(size))
qrvs = gen.qrvs(size=size, d=d, qmc_engine=qrng)
qrvs2 = stats.norm.ppf(uniform)
for i in range(d):
sample = qrvs[..., i]
sample2 = qrvs2[:, i].reshape(size)
assert_allclose(sample, sample2, atol=1e-12)
class TestTransformedDensityRejection:
# Simple Custom Distribution
class dist0:
def pdf(self, x):
return 3/4 * (1-x*x)
def dpdf(self, x):
return 3/4 * (-2*x)
def cdf(self, x):
return 3/4 * (x - x**3/3 + 2/3)
def support(self):
return -1, 1
# Standard Normal Distribution
class dist1:
def pdf(self, x):
return stats.norm._pdf(x / 0.1)
def dpdf(self, x):
return -x / 0.01 * stats.norm._pdf(x / 0.1)
def cdf(self, x):
return stats.norm._cdf(x / 0.1)
# pdf with piecewise linear function as transformed density
# with T = -1/sqrt with shift. Taken from UNU.RAN test suite
# (from file t_tdr_ps.c)
class dist2:
def __init__(self, shift):
self.shift = shift
def pdf(self, x):
x -= self.shift
y = 1. / (abs(x) + 1.)
return 0.5 * y * y
def dpdf(self, x):
x -= self.shift
y = 1. / (abs(x) + 1.)
y = y * y * y
return y if (x < 0.) else -y
def cdf(self, x):
x -= self.shift
if x <= 0.:
return 0.5 / (1. - x)
else:
return 1. - 0.5 / (1. + x)
dists = [dist0(), dist1(), dist2(0.), dist2(10000.)]
# exact mean and variance of the distributions in the list dists
mv0 = [0., 4./15.]
mv1 = [0., 0.01]
mv2 = [0., np.inf]
mv3 = [10000., np.inf]
mvs = [mv0, mv1, mv2, mv3]
@pytest.mark.parametrize("dist, mv_ex",
zip(dists, mvs))
@pytest.mark.thread_unsafe(reason="deadlocks for unknown reasons")
def test_basic(self, dist, mv_ex):
with warnings.catch_warnings():
# filter the warnings thrown by UNU.RAN
warnings.simplefilter("ignore", RuntimeWarning)
rng = TransformedDensityRejection(dist, random_state=42)
check_cont_samples(rng, dist, mv_ex)
# PDF 0 everywhere => bad construction points
bad_pdfs = [(lambda x: 0, UNURANError, r"50 : bad construction points.")]
bad_pdfs += bad_pdfs_common # type: ignore[arg-type]
@pytest.mark.parametrize("pdf, err, msg", bad_pdfs)
def test_bad_pdf(self, pdf, err, msg):
class dist:
pass
dist.pdf = pdf
dist.dpdf = lambda x: 1 # an arbitrary dPDF
with pytest.raises(err, match=msg):
TransformedDensityRejection(dist)
@pytest.mark.parametrize("dpdf, err, msg", bad_dpdf_common)
def test_bad_dpdf(self, dpdf, err, msg):
class dist:
pass
dist.pdf = lambda x: x
dist.dpdf = dpdf
with pytest.raises(err, match=msg):
TransformedDensityRejection(dist, domain=(1, 10))
# test domains with inf + nan in them. need to write a custom test for
# this because not all methods support infinite tails.
@pytest.mark.parametrize("domain, err, msg", inf_nan_domains)
def test_inf_nan_domains(self, domain, err, msg):
with pytest.raises(err, match=msg):
TransformedDensityRejection(StandardNormal(), domain=domain)
@pytest.mark.parametrize("construction_points", [-1, 0, 0.1])
def test_bad_construction_points_scalar(self, construction_points):
with pytest.raises(ValueError, match=r"`construction_points` must be "
r"a positive integer."):
TransformedDensityRejection(
StandardNormal(), construction_points=construction_points
)
def test_bad_construction_points_array(self):
# empty array
construction_points = []
with pytest.raises(ValueError, match=r"`construction_points` must "
r"either be a "
r"scalar or a non-empty array."):
TransformedDensityRejection(
StandardNormal(), construction_points=construction_points
)
# construction_points not monotonically increasing
construction_points = [1, 1, 1, 1, 1, 1]
with pytest.warns(RuntimeWarning, match=r"33 : starting points not "
r"strictly monotonically "
r"increasing"):
TransformedDensityRejection(
StandardNormal(), construction_points=construction_points
)
# construction_points containing nans
construction_points = [np.nan, np.nan, np.nan]
with pytest.raises(UNURANError, match=r"50 : bad construction "
r"points."):
TransformedDensityRejection(
StandardNormal(), construction_points=construction_points
)
# construction_points out of domain
construction_points = [-10, 10]
with pytest.warns(RuntimeWarning, match=r"50 : starting point out of "
r"domain"):
TransformedDensityRejection(
StandardNormal(), domain=(-3, 3),
construction_points=construction_points
)
@pytest.mark.parametrize("c", [-1., np.nan, np.inf, 0.1, 1.])
def test_bad_c(self, c):
msg = r"`c` must either be -0.5 or 0."
with pytest.raises(ValueError, match=msg):
TransformedDensityRejection(StandardNormal(), c=-1.)
u = [np.linspace(0, 1, num=1000), [], [[]], [np.nan],
[-np.inf, np.nan, np.inf], 0,
[[np.nan, 0.5, 0.1], [0.2, 0.4, np.inf], [-2, 3, 4]]]
@pytest.mark.parametrize("u", u)
def test_ppf_hat(self, u):
# Increase the `max_squeeze_hat_ratio` so the ppf_hat is more
# accurate.
rng = TransformedDensityRejection(StandardNormal(),
max_squeeze_hat_ratio=0.9999)
# Older versions of NumPy throw RuntimeWarnings for comparisons
# with nan.
with warnings.catch_warnings():
msg = "invalid value encountered in "
warnings.filterwarnings("ignore", msg + "greater", RuntimeWarning)
warnings.filterwarnings("ignore", msg + "greater_equal", RuntimeWarning)
warnings.filterwarnings("ignore", msg + "less", RuntimeWarning)
warnings.filterwarnings("ignore", msg + "less_equal", RuntimeWarning)
res = rng.ppf_hat(u)
expected = stats.norm.ppf(u)
assert_allclose(res, expected, rtol=1e-3, atol=1e-5)
assert res.shape == expected.shape
def test_bad_dist(self):
# Empty distribution
class dist:
...
msg = r"`pdf` required but not found."
with pytest.raises(ValueError, match=msg):
TransformedDensityRejection(dist)
# dPDF not present in dist
class dist:
pdf = lambda x: 1-x*x # noqa: E731
msg = r"`dpdf` required but not found."
with pytest.raises(ValueError, match=msg):
TransformedDensityRejection(dist)
class TestDiscreteAliasUrn:
# DAU fails on these probably because of large domains and small
# computation errors in PMF. Mean/SD match but chi-squared test fails.
basic_fail_dists = {
'nchypergeom_fisher', # numerical errors on tails
'nchypergeom_wallenius', # numerical errors on tails
'randint' # fails on 32-bit ubuntu
}
@pytest.mark.parametrize("distname, params", distdiscrete)
def test_basic(self, distname, params):
if distname in self.basic_fail_dists:
msg = ("DAU fails on these probably because of large domains "
"and small computation errors in PMF.")
pytest.skip(msg)
if not isinstance(distname, str):
dist = distname
else:
dist = getattr(stats, distname)
dist = dist(*params)
domain = dist.support()
if not np.isfinite(domain[1] - domain[0]):
# DAU only works with finite domain. So, skip the distributions
# with infinite tails.
pytest.skip("DAU only works with a finite domain.")
k = np.arange(domain[0], domain[1]+1)
pv = dist.pmf(k)
mv_ex = dist.stats('mv')
rng = DiscreteAliasUrn(dist, random_state=42)
check_discr_samples(rng, pv, mv_ex)
# Can't use bad_pmf_common here as we evaluate PMF early on to avoid
# unhelpful errors from UNU.RAN.
bad_pmf = [
# inf returned
(lambda x: np.inf, ValueError,
r"must contain only finite / non-nan values"),
# nan returned
(lambda x: np.nan, ValueError,
r"must contain only finite / non-nan values"),
# all zeros
(lambda x: 0.0, ValueError,
r"must contain at least one non-zero value"),
# Undefined name inside the function
(lambda x: foo, NameError, # type: ignore[name-defined] # noqa: F821
r"name 'foo' is not defined"),
# Returning wrong type.
(lambda x: [], ValueError,
r"setting an array element with a sequence."),
# probabilities < 0
(lambda x: -x, UNURANError,
r"50 : probability < 0"),
# signature of PMF wrong
(lambda: 1.0, TypeError,
r"takes 0 positional arguments but 1 was given")
]
@pytest.mark.parametrize("pmf, err, msg", bad_pmf)
def test_bad_pmf(self, pmf, err, msg):
class dist:
pass
dist.pmf = pmf
with pytest.raises(err, match=msg):
DiscreteAliasUrn(dist, domain=(1, 10))
@pytest.mark.parametrize("pv", [[0.18, 0.02, 0.8],
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]])
def test_sampling_with_pv(self, pv):
pv = np.asarray(pv, dtype=np.float64)
rng = DiscreteAliasUrn(pv, random_state=123)
rng.rvs(100_000)
pv = pv / pv.sum()
variates = np.arange(0, len(pv))
# test if the first few moments match
m_expected = np.average(variates, weights=pv)
v_expected = np.average((variates - m_expected) ** 2, weights=pv)
mv_expected = m_expected, v_expected
check_discr_samples(rng, pv, mv_expected)
@pytest.mark.parametrize("pv, msg", bad_pv_common)
def test_bad_pv(self, pv, msg):
with pytest.raises(ValueError, match=msg):
DiscreteAliasUrn(pv)
# DAU doesn't support infinite tails. So, it should throw an error when
# inf is present in the domain.
inf_domain = [(-np.inf, np.inf), (np.inf, np.inf), (-np.inf, -np.inf),
(0, np.inf), (-np.inf, 0)]
@pytest.mark.parametrize("domain", inf_domain)
def test_inf_domain(self, domain):
with pytest.raises(ValueError, match=r"must be finite"):
DiscreteAliasUrn(stats.binom(10, 0.2), domain=domain)
def test_bad_urn_factor(self):
with pytest.warns(RuntimeWarning, match=r"relative urn size < 1."):
DiscreteAliasUrn([0.5, 0.5], urn_factor=-1)
def test_bad_args(self):
msg = (r"`domain` must be provided when the "
r"probability vector is not available.")
class dist:
def pmf(self, x):
return x
with pytest.raises(ValueError, match=msg):
DiscreteAliasUrn(dist)
def test_gh19359(self):
pv = special.softmax(np.ones((1533,)))
rng = DiscreteAliasUrn(pv, random_state=42)
# check the correctness
check_discr_samples(rng, pv, (1532 / 2, (1532**2 - 1) / 12),
rtol=5e-3)
class TestNumericalInversePolynomial:
# Simple Custom Distribution
class dist0:
def pdf(self, x):
return 3/4 * (1-x*x)
def cdf(self, x):
return 3/4 * (x - x**3/3 + 2/3)
def support(self):
return -1, 1
# Standard Normal Distribution
class dist1:
def pdf(self, x):
return stats.norm._pdf(x / 0.1)
def cdf(self, x):
return stats.norm._cdf(x / 0.1)
# Sin 2 distribution
# / 0.05 + 0.45*(1 +sin(2 Pi x)) if |x| <= 1
# f(x) = <
# \ 0 otherwise
# Taken from UNU.RAN test suite (from file t_pinv.c)
class dist2:
def pdf(self, x):
return 0.05 + 0.45 * (1 + np.sin(2*np.pi*x))
def cdf(self, x):
return (0.05*(x + 1) +
0.9*(1. + 2.*np.pi*(1 + x) - np.cos(2.*np.pi*x)) /
(4.*np.pi))
def support(self):
return -1, 1
# Sin 10 distribution
# / 0.05 + 0.45*(1 +sin(2 Pi x)) if |x| <= 5
# f(x) = <
# \ 0 otherwise
# Taken from UNU.RAN test suite (from file t_pinv.c)
class dist3:
def pdf(self, x):
return 0.2 * (0.05 + 0.45 * (1 + np.sin(2*np.pi*x)))
def cdf(self, x):
return x/10. + 0.5 + 0.09/(2*np.pi) * (np.cos(10*np.pi) -
np.cos(2*np.pi*x))
def support(self):
return -5, 5
dists = [dist0(), dist1(), dist2(), dist3()]
# exact mean and variance of the distributions in the list dists
mv0 = [0., 4./15.]
mv1 = [0., 0.01]
mv2 = [-0.45/np.pi, 2/3*0.5 - 0.45**2/np.pi**2]
mv3 = [-0.45/np.pi, 0.2 * 250/3 * 0.5 - 0.45**2/np.pi**2]
mvs = [mv0, mv1, mv2, mv3]
@pytest.mark.thread_unsafe(reason="deadlocks for unknown reasons")
@pytest.mark.parametrize("dist, mv_ex",
zip(dists, mvs))
def test_basic(self, dist, mv_ex):
rng = NumericalInversePolynomial(dist, random_state=42)
check_cont_samples(rng, dist, mv_ex)
@pytest.mark.xslow
@pytest.mark.parametrize("distname, params", distcont)
def test_basic_all_scipy_dists(self, distname, params):
very_slow_dists = ['anglit', 'gausshyper', 'kappa4',
'ksone', 'kstwo', 'levy_l',
'levy_stable', 'studentized_range',
'trapezoid', 'triang', 'vonmises']
# for these distributions, some assertions fail due to minor
# numerical differences. They can be avoided either by changing
# the seed or by increasing the u_resolution.
fail_dists = ['chi2', 'fatiguelife', 'gibrat',
'halfgennorm', 'lognorm', 'ncf',
'ncx2', 'pareto', 't']
# for these distributions, skip the check for agreement between sample
# moments and true moments. We cannot expect them to pass due to the
# high variance of sample moments.
skip_sample_moment_check = ['rel_breitwigner']
if distname in very_slow_dists:
pytest.skip(f"PINV too slow for {distname}")
if distname in fail_dists:
pytest.skip(f"PINV fails for {distname}")
dist = (getattr(stats, distname)
if isinstance(distname, str)
else distname)
dist = dist(*params)
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
rng = NumericalInversePolynomial(dist, random_state=42)
if distname in skip_sample_moment_check:
return
check_cont_samples(rng, dist, [dist.mean(), dist.var()])
@pytest.mark.parametrize("pdf, err, msg", bad_pdfs_common)
def test_bad_pdf(self, pdf, err, msg):
class dist:
pass
dist.pdf = pdf
with pytest.raises(err, match=msg):
NumericalInversePolynomial(dist, domain=[0, 5])
@pytest.mark.parametrize("logpdf, err, msg", bad_logpdfs_common)
def test_bad_logpdf(self, logpdf, err, msg):
class dist:
pass
dist.logpdf = logpdf
with pytest.raises(err, match=msg):
NumericalInversePolynomial(dist, domain=[0, 5])
# test domains with inf + nan in them. need to write a custom test for
# this because not all methods support infinite tails.
@pytest.mark.parametrize("domain, err, msg", inf_nan_domains)
def test_inf_nan_domains(self, domain, err, msg):
with pytest.raises(err, match=msg):
NumericalInversePolynomial(StandardNormal(), domain=domain)
u = [
# test if quantile 0 and 1 return -inf and inf respectively and check
# the correctness of the PPF for equidistant points between 0 and 1.
np.linspace(0, 1, num=10000),
# test the PPF method for empty arrays
[], [[]],
# test if nans and infs return nan result.
[np.nan], [-np.inf, np.nan, np.inf],
# test if a scalar is returned for a scalar input.
0,
# test for arrays with nans, values greater than 1 and less than 0,
# and some valid values.
[[np.nan, 0.5, 0.1], [0.2, 0.4, np.inf], [-2, 3, 4]]
]
@pytest.mark.parametrize("u", u)
def test_ppf(self, u):
dist = StandardNormal()
rng = NumericalInversePolynomial(dist, u_resolution=1e-14)
# Older versions of NumPy throw RuntimeWarnings for comparisons
# with nan.
with warnings.catch_warnings():
msg = "invalid value encountered in "
warnings.filterwarnings("ignore", msg + "greater", RuntimeWarning)
warnings.filterwarnings("ignore", msg + "greater_equal", RuntimeWarning)
warnings.filterwarnings("ignore", msg + "less", RuntimeWarning)
warnings.filterwarnings("ignore", msg + "less_equal", RuntimeWarning)
res = rng.ppf(u)
expected = stats.norm.ppf(u)
assert_allclose(res, expected, rtol=1e-11, atol=1e-11)
assert res.shape == expected.shape
x = [np.linspace(-10, 10, num=10000), [], [[]], [np.nan],
[-np.inf, np.nan, np.inf], 0,
[[np.nan, 0.5, 0.1], [0.2, 0.4, np.inf], [-np.inf, 3, 4]]]
@pytest.mark.parametrize("x", x)
def test_cdf(self, x):
dist = StandardNormal()
rng = NumericalInversePolynomial(dist, u_resolution=1e-14)
# Older versions of NumPy throw RuntimeWarnings for comparisons
# with nan.
with warnings.catch_warnings():
msg = "invalid value encountered in "
warnings.filterwarnings("ignore", msg + "greater", RuntimeWarning)
warnings.filterwarnings("ignore", msg + "greater_equal", RuntimeWarning)
warnings.filterwarnings("ignore", msg + "less", RuntimeWarning)
warnings.filterwarnings("ignore", msg + "less_equal", RuntimeWarning)
res = rng.cdf(x)
expected = stats.norm.cdf(x)
assert_allclose(res, expected, rtol=1e-11, atol=1e-11)
assert res.shape == expected.shape
@pytest.mark.slow
def test_u_error(self):
dist = StandardNormal()
rng = NumericalInversePolynomial(dist, u_resolution=1e-10)
max_error, mae = rng.u_error()
assert max_error < 1e-10
assert mae <= max_error
rng = NumericalInversePolynomial(dist, u_resolution=1e-14)
max_error, mae = rng.u_error()
assert max_error < 1e-14
assert mae <= max_error
bad_orders = [1, 4.5, 20, np.inf, np.nan]
bad_u_resolution = [1e-20, 1e-1, np.inf, np.nan]
@pytest.mark.parametrize("order", bad_orders)
def test_bad_orders(self, order):
dist = StandardNormal()
msg = r"`order` must be an integer in the range \[3, 17\]."
with pytest.raises(ValueError, match=msg):
NumericalInversePolynomial(dist, order=order)
@pytest.mark.parametrize("u_resolution", bad_u_resolution)
def test_bad_u_resolution(self, u_resolution):
msg = r"`u_resolution` must be between 1e-15 and 1e-5."
with pytest.raises(ValueError, match=msg):
NumericalInversePolynomial(StandardNormal(),
u_resolution=u_resolution)
def test_bad_args(self):
class BadDist:
def cdf(self, x):
return stats.norm._cdf(x)
dist = BadDist()
msg = r"Either of the methods `pdf` or `logpdf` must be specified"
with pytest.raises(ValueError, match=msg):
rng = NumericalInversePolynomial(dist)
dist = StandardNormal()
rng = NumericalInversePolynomial(dist)
msg = r"`sample_size` must be greater than or equal to 1000."
with pytest.raises(ValueError, match=msg):
rng.u_error(10)
class Distribution:
def pdf(self, x):
return np.exp(-0.5 * x*x)
dist = Distribution()
rng = NumericalInversePolynomial(dist)
msg = r"Exact CDF required but not found."
with pytest.raises(ValueError, match=msg):
rng.u_error()
def test_logpdf_pdf_consistency(self):
# 1. check that PINV works with pdf and logpdf only
# 2. check that generated ppf is the same (up to a small tolerance)
class MyDist:
pass
# create generator from dist with only pdf
dist_pdf = MyDist()
dist_pdf.pdf = lambda x: math.exp(-x*x/2)
rng1 = NumericalInversePolynomial(dist_pdf)
# create dist with only logpdf
dist_logpdf = MyDist()
dist_logpdf.logpdf = lambda x: -x*x/2
rng2 = NumericalInversePolynomial(dist_logpdf)
q = np.linspace(1e-5, 1-1e-5, num=100)
assert_allclose(rng1.ppf(q), rng2.ppf(q))
class TestNumericalInverseHermite:
# / (1 +sin(2 Pi x))/2 if |x| <= 1
# f(x) = <
# \ 0 otherwise
# Taken from UNU.RAN test suite (from file t_hinv.c)
class dist0:
def pdf(self, x):
return 0.5*(1. + np.sin(2.*np.pi*x))
def dpdf(self, x):
return np.pi*np.cos(2.*np.pi*x)
def cdf(self, x):
return (1. + 2.*np.pi*(1 + x) - np.cos(2.*np.pi*x)) / (4.*np.pi)
def support(self):
return -1, 1
# / Max(sin(2 Pi x)),0)Pi/2 if -1 < x <0.5
# f(x) = <
# \ 0 otherwise
# Taken from UNU.RAN test suite (from file t_hinv.c)
class dist1:
def pdf(self, x):
if (x <= -0.5):
return np.sin((2. * np.pi) * x) * 0.5 * np.pi
if (x < 0.):
return 0.
if (x <= 0.5):
return np.sin((2. * np.pi) * x) * 0.5 * np.pi
def dpdf(self, x):
if (x <= -0.5):
return np.cos((2. * np.pi) * x) * np.pi * np.pi
if (x < 0.):
return 0.
if (x <= 0.5):
return np.cos((2. * np.pi) * x) * np.pi * np.pi
def cdf(self, x):
if (x <= -0.5):
return 0.25 * (1 - np.cos((2. * np.pi) * x))
if (x < 0.):
return 0.5
if (x <= 0.5):
return 0.75 - 0.25 * np.cos((2. * np.pi) * x)
def support(self):
return -1, 0.5
dists = [dist0(), dist1()]
# exact mean and variance of the distributions in the list dists
mv0 = [-1/(2*np.pi), 1/3 - 1/(4*np.pi*np.pi)]
mv1 = [-1/4, 3/8-1/(2*np.pi*np.pi) - 1/16]
mvs = [mv0, mv1]
@pytest.mark.parametrize("dist, mv_ex",
zip(dists, mvs))
@pytest.mark.parametrize("order", [3, 5])
@pytest.mark.thread_unsafe
def test_basic(self, dist, mv_ex, order):
rng = NumericalInverseHermite(dist, order=order, random_state=42)
check_cont_samples(rng, dist, mv_ex)
# test domains with inf + nan in them. need to write a custom test for
# this because not all methods support infinite tails.
@pytest.mark.parametrize("domain, err, msg", inf_nan_domains)
def test_inf_nan_domains(self, domain, err, msg):
with pytest.raises(err, match=msg):
NumericalInverseHermite(StandardNormal(), domain=domain)
def basic_test_all_scipy_dists(self, distname, shapes):
slow_dists = {'ksone', 'kstwo', 'levy_stable', 'skewnorm'}
fail_dists = {'beta', 'gausshyper', 'geninvgauss', 'ncf', 'nct',
'norminvgauss', 'genhyperbolic', 'studentized_range',
'vonmises', 'kappa4', 'invgauss', 'wald'}
if distname in slow_dists:
pytest.skip("Distribution is too slow")
if distname in fail_dists:
# specific reasons documented in gh-13319
# https://github.com/scipy/scipy/pull/13319#discussion_r626188955
pytest.xfail("Fails - usually due to inaccurate CDF/PDF")
rng = np.random.default_rng(0)
dist = getattr(stats, distname)(*shapes)
fni = NumericalInverseHermite(dist)
x = rng.random(10)
p_tol = np.max(np.abs(dist.ppf(x)-fni.ppf(x))/np.abs(dist.ppf(x)))
u_tol = np.max(np.abs(dist.cdf(fni.ppf(x)) - x))
assert p_tol < 1e-8
assert u_tol < 1e-12
@pytest.mark.filterwarnings('ignore::RuntimeWarning')
@pytest.mark.xslow
@pytest.mark.parametrize(("distname", "shapes"), distcont)
def test_basic_all_scipy_dists(self, distname, shapes):
# if distname == "truncnorm":
# pytest.skip("Tested separately")
self.basic_test_all_scipy_dists(distname, shapes)
@pytest.mark.fail_slow(5)
@pytest.mark.filterwarnings('ignore::RuntimeWarning')
@pytest.mark.parallel_threads_limit(4) # Very slow
def test_basic_truncnorm_gh17155(self):
self.basic_test_all_scipy_dists("truncnorm", (0.1, 2))
def test_input_validation(self):
match = r"`order` must be either 1, 3, or 5."
with pytest.raises(ValueError, match=match):
NumericalInverseHermite(StandardNormal(), order=2)
match = "`cdf` required but not found"
with pytest.raises(ValueError, match=match):
NumericalInverseHermite("norm")
match = "could not convert string to float"
with pytest.raises(ValueError, match=match):
NumericalInverseHermite(StandardNormal(),
u_resolution='ekki')
rngs = [None, 0, np.random.RandomState(0)]
rngs.append(np.random.default_rng(0)) # type: ignore
sizes = [(None, tuple()), (8, (8,)), ((4, 5, 6), (4, 5, 6))]
@pytest.mark.parametrize('rng', rngs)
@pytest.mark.parametrize('size_in, size_out', sizes)
@pytest.mark.thread_unsafe
def test_RVS(self, rng, size_in, size_out):
dist = StandardNormal()
fni = NumericalInverseHermite(dist)
rng2 = deepcopy(rng)
rvs = fni.rvs(size=size_in, random_state=rng)
if size_in is not None:
assert rvs.shape == size_out
if rng2 is not None:
rng2 = check_random_state(rng2)
uniform = rng2.uniform(size=size_in)
rvs2 = stats.norm.ppf(uniform)
assert_allclose(rvs, rvs2)
def test_inaccurate_CDF(self):
# CDF function with inaccurate tail cannot be inverted; see gh-13319
# https://github.com/scipy/scipy/pull/13319#discussion_r626188955
shapes = (2.3098496451481823, 0.6268795430096368)
match = ("98 : one or more intervals very short; possibly due to "
"numerical problems with a pole or very flat tail")
# fails with default tol
with pytest.warns(RuntimeWarning, match=match):
NumericalInverseHermite(stats.beta(*shapes))
# no error with coarser tol
NumericalInverseHermite(stats.beta(*shapes), u_resolution=1e-8)
def test_custom_distribution(self):
dist1 = StandardNormal()
fni1 = NumericalInverseHermite(dist1)
dist2 = stats.norm()
fni2 = NumericalInverseHermite(dist2)
assert_allclose(fni1.rvs(random_state=0), fni2.rvs(random_state=0))
u = [
# check the correctness of the PPF for equidistant points between
# 0.02 and 0.98.
np.linspace(0., 1., num=10000),
# test the PPF method for empty arrays
[], [[]],
# test if nans and infs return nan result.
[np.nan], [-np.inf, np.nan, np.inf],
# test if a scalar is returned for a scalar input.
0,
# test for arrays with nans, values greater than 1 and less than 0,
# and some valid values.
[[np.nan, 0.5, 0.1], [0.2, 0.4, np.inf], [-2, 3, 4]]
]
@pytest.mark.parametrize("u", u)
def test_ppf(self, u):
dist = StandardNormal()
rng = NumericalInverseHermite(dist, u_resolution=1e-12)
# Older versions of NumPy throw RuntimeWarnings for comparisons
# with nan.
with warnings.catch_warnings():
msg = "invalid value encountered in "
warnings.filterwarnings("ignore", msg + "greater", RuntimeWarning)
warnings.filterwarnings("ignore", msg + "greater_equal", RuntimeWarning)
warnings.filterwarnings("ignore", msg + "less", RuntimeWarning)
warnings.filterwarnings("ignore", msg + "less_equal", RuntimeWarning)
res = rng.ppf(u)
expected = stats.norm.ppf(u)
assert_allclose(res, expected, rtol=1e-9, atol=3e-10)
assert res.shape == expected.shape
@pytest.mark.slow
def test_u_error(self):
dist = StandardNormal()
rng = NumericalInverseHermite(dist, u_resolution=1e-10)
max_error, mae = rng.u_error()
assert max_error < 1e-10
assert mae <= max_error
with warnings.catch_warnings():
# ignore warning about u-resolution being too small.
warnings.simplefilter("ignore", RuntimeWarning)
rng = NumericalInverseHermite(dist, u_resolution=1e-14)
max_error, mae = rng.u_error()
assert max_error < 1e-14
assert mae <= max_error
class TestDiscreteGuideTable:
basic_fail_dists = {
'nchypergeom_fisher', # numerical errors on tails
'nchypergeom_wallenius', # numerical errors on tails
'randint' # fails on 32-bit ubuntu
}
def test_guide_factor_gt3_raises_warning(self):
pv = [0.1, 0.3, 0.6]
urng = np.random.default_rng()
with pytest.warns(RuntimeWarning):
DiscreteGuideTable(pv, random_state=urng, guide_factor=7)
def test_guide_factor_zero_raises_warning(self):
pv = [0.1, 0.3, 0.6]
urng = np.random.default_rng()
with pytest.warns(RuntimeWarning):
DiscreteGuideTable(pv, random_state=urng, guide_factor=0)
def test_negative_guide_factor_raises_warning(self):
# This occurs from the UNU.RAN wrapper automatically.
# however it already gives a useful warning
# Here we just test that a warning is raised.
pv = [0.1, 0.3, 0.6]
urng = np.random.default_rng()
with pytest.warns(RuntimeWarning):
DiscreteGuideTable(pv, random_state=urng, guide_factor=-1)
@pytest.mark.parametrize("distname, params", distdiscrete)
def test_basic(self, distname, params):
if distname in self.basic_fail_dists:
msg = ("DGT fails on these probably because of large domains "
"and small computation errors in PMF.")
pytest.skip(msg)
if not isinstance(distname, str):
dist = distname
else:
dist = getattr(stats, distname)
dist = dist(*params)
domain = dist.support()
if not np.isfinite(domain[1] - domain[0]):
# DGT only works with finite domain. So, skip the distributions
# with infinite tails.
pytest.skip("DGT only works with a finite domain.")
k = np.arange(domain[0], domain[1]+1)
pv = dist.pmf(k)
mv_ex = dist.stats('mv')
rng = DiscreteGuideTable(dist, random_state=42)
check_discr_samples(rng, pv, mv_ex)
u = [
# the correctness of the PPF for equidistant points between 0 and 1.
np.linspace(0, 1, num=10000),
# test the PPF method for empty arrays
[], [[]],
# test if nans and infs return nan result.
[np.nan], [-np.inf, np.nan, np.inf],
# test if a scalar is returned for a scalar input.
0,
# test for arrays with nans, values greater than 1 and less than 0,
# and some valid values.
[[np.nan, 0.5, 0.1], [0.2, 0.4, np.inf], [-2, 3, 4]]
]
@pytest.mark.parametrize('u', u)
def test_ppf(self, u):
n, p = 4, 0.1
dist = stats.binom(n, p)
rng = DiscreteGuideTable(dist, random_state=42)
# Older versions of NumPy throw RuntimeWarnings for comparisons
# with nan.
with warnings.catch_warnings():
msg = "invalid value encountered in "
warnings.filterwarnings("ignore", msg + "greater", RuntimeWarning)
warnings.filterwarnings("ignore", msg + "greater_equal", RuntimeWarning)
warnings.filterwarnings("ignore", msg + "less", RuntimeWarning)
warnings.filterwarnings("ignore", msg + "less_equal", RuntimeWarning)
res = rng.ppf(u)
expected = stats.binom.ppf(u, n, p)
assert_equal(res.shape, expected.shape)
assert_equal(res, expected)
@pytest.mark.parametrize("pv, msg", bad_pv_common)
def test_bad_pv(self, pv, msg):
with pytest.raises(ValueError, match=msg):
DiscreteGuideTable(pv)
# DGT doesn't support infinite tails. So, it should throw an error when
# inf is present in the domain.
inf_domain = [(-np.inf, np.inf), (np.inf, np.inf), (-np.inf, -np.inf),
(0, np.inf), (-np.inf, 0)]
@pytest.mark.parametrize("domain", inf_domain)
def test_inf_domain(self, domain):
with pytest.raises(ValueError, match=r"must be finite"):
DiscreteGuideTable(stats.binom(10, 0.2), domain=domain)
class TestSimpleRatioUniforms:
# pdf with piecewise linear function as transformed density
# with T = -1/sqrt with shift. Taken from UNU.RAN test suite
# (from file t_srou.c)
class dist:
def __init__(self, shift):
self.shift = shift
self.mode = shift
def pdf(self, x):
x -= self.shift
y = 1. / (abs(x) + 1.)
return 0.5 * y * y
def cdf(self, x):
x -= self.shift
if x <= 0.:
return 0.5 / (1. - x)
else:
return 1. - 0.5 / (1. + x)
dists = [dist(0.), dist(10000.)]
# exact mean and variance of the distributions in the list dists
mv1 = [0., np.inf]
mv2 = [10000., np.inf]
mvs = [mv1, mv2]
@pytest.mark.parametrize("dist, mv_ex",
zip(dists, mvs))
@pytest.mark.thread_unsafe
def test_basic(self, dist, mv_ex):
rng = SimpleRatioUniforms(dist, mode=dist.mode, random_state=42)
check_cont_samples(rng, dist, mv_ex)
rng = SimpleRatioUniforms(dist, mode=dist.mode,
cdf_at_mode=dist.cdf(dist.mode),
random_state=42)
check_cont_samples(rng, dist, mv_ex)
# test domains with inf + nan in them. need to write a custom test for
# this because not all methods support infinite tails.
@pytest.mark.parametrize("domain, err, msg", inf_nan_domains)
def test_inf_nan_domains(self, domain, err, msg):
with pytest.raises(err, match=msg):
SimpleRatioUniforms(StandardNormal(), domain=domain)
def test_bad_args(self):
# pdf_area < 0
with pytest.raises(ValueError, match=r"`pdf_area` must be > 0"):
SimpleRatioUniforms(StandardNormal(), mode=0, pdf_area=-1)
class TestRatioUniforms:
def test_rv_generation(self):
# use KS test to check distribution of rvs
# normal distribution
f = stats.norm.pdf
v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
u = np.sqrt(f(0))
gen = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=12345)
assert_equal(stats.kstest(gen.rvs(2500), 'norm')[1] > 0.25, True)
# exponential distribution
gen = RatioUniforms(lambda x: np.exp(-x), umax=1,
vmin=0, vmax=2*np.exp(-1), random_state=12345)
assert_equal(stats.kstest(gen.rvs(1000), 'expon')[1] > 0.25, True)
def test_shape(self):
# test shape of return value depending on size parameter
f = stats.norm.pdf
v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
u = np.sqrt(f(0))
gen1 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
gen2 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
gen3 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
r1, r2, r3 = gen1.rvs(3), gen2.rvs((3,)), gen3.rvs((3, 1))
assert_equal(r1, r2)
assert_equal(r2, r3.flatten())
assert_equal(r1.shape, (3,))
assert_equal(r3.shape, (3, 1))
gen4 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=12)
gen5 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=12)
r4, r5 = gen4.rvs(size=(3, 3, 3)), gen5.rvs(size=27)
assert_equal(r4.flatten(), r5)
assert_equal(r4.shape, (3, 3, 3))
gen6 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
gen7 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
gen8 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
r6, r7, r8 = gen6.rvs(), gen7.rvs(1), gen8.rvs((1,))
assert_equal(r6, r7)
assert_equal(r7, r8)
def test_random_state(self):
f = stats.norm.pdf
v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
umax = np.sqrt(f(0))
gen1 = RatioUniforms(f, umax=umax, vmin=-v, vmax=v, random_state=1234)
r1 = gen1.rvs(10)
rng = np.random.RandomState(1234)
gen2 = RatioUniforms(f, umax=umax, vmin=-v, vmax=v, random_state=rng)
r2 = gen2.rvs(10)
assert_equal(r1, r2)
def test_exceptions(self):
f = stats.norm.pdf
# need vmin < vmax
with assert_raises(ValueError, match="vmin must be smaller than vmax"):
RatioUniforms(pdf=f, umax=1, vmin=3, vmax=1)
with assert_raises(ValueError, match="vmin must be smaller than vmax"):
RatioUniforms(pdf=f, umax=1, vmin=1, vmax=1)
# need umax > 0
with assert_raises(ValueError, match="umax must be positive"):
RatioUniforms(pdf=f, umax=-1, vmin=1, vmax=3)
with assert_raises(ValueError, match="umax must be positive"):
RatioUniforms(pdf=f, umax=0, vmin=1, vmax=3)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310import numpy as np
from numpy.testing import assert_allclose, assert_array_less
import pytest
from scipy import stats
from scipy.stats import sobol_indices
from scipy.stats._resampling import BootstrapResult
from scipy.stats._sensitivity_analysis import (
BootstrapSobolResult, f_ishigami, sample_AB, sample_A_B
)
@pytest.fixture(scope='session')
def ishigami_ref_indices():
"""Reference values for Ishigami from Saltelli2007.
Chapter 4, exercise 5 pages 179-182.
"""
a = 7.
b = 0.1
var = 0.5 + a**2/8 + b*np.pi**4/5 + b**2*np.pi**8/18
v1 = 0.5 + b*np.pi**4/5 + b**2*np.pi**8/50
v2 = a**2/8
v3 = 0
v12 = 0
# v13: mistake in the book, see other derivations e.g. in 10.1002/nme.4856
v13 = b**2*np.pi**8*8/225
v23 = 0
s_first = np.array([v1, v2, v3])/var
s_second = np.array([
[0., 0., v13],
[v12, 0., v23],
[v13, v23, 0.]
])/var
s_total = s_first + s_second.sum(axis=1)
return s_first, s_total
def f_ishigami_vec(x):
"""Output of shape (2, n)."""
res = f_ishigami(x)
return res, res
class TestSobolIndices:
dists = [
stats.uniform(loc=-np.pi, scale=2*np.pi) # type: ignore[attr-defined]
] * 3
def test_sample_AB(self):
# (d, n)
A = np.array(
[[1, 4, 7, 10],
[2, 5, 8, 11],
[3, 6, 9, 12]]
)
B = A + 100
# (d, d, n)
ref = np.array(
[[[101, 104, 107, 110],
[2, 5, 8, 11],
[3, 6, 9, 12]],
[[1, 4, 7, 10],
[102, 105, 108, 111],
[3, 6, 9, 12]],
[[1, 4, 7, 10],
[2, 5, 8, 11],
[103, 106, 109, 112]]]
)
AB = sample_AB(A=A, B=B)
assert_allclose(AB, ref)
@pytest.mark.xslow
@pytest.mark.xfail_on_32bit("Can't create large array for test")
@pytest.mark.parametrize(
'func',
[f_ishigami, pytest.param(f_ishigami_vec, marks=pytest.mark.slow)],
ids=['scalar', 'vector']
)
def test_ishigami(self, ishigami_ref_indices, func):
rng = np.random.default_rng(28631265345463262246170309650372465332)
res = sobol_indices(
func=func, n=4096,
dists=self.dists,
rng=rng
)
if func.__name__ == 'f_ishigami_vec':
ishigami_ref_indices = [
[ishigami_ref_indices[0], ishigami_ref_indices[0]],
[ishigami_ref_indices[1], ishigami_ref_indices[1]]
]
assert_allclose(res.first_order, ishigami_ref_indices[0], atol=1e-2)
assert_allclose(res.total_order, ishigami_ref_indices[1], atol=1e-2)
assert res._bootstrap_result is None
bootstrap_res = res.bootstrap(n_resamples=99)
assert isinstance(bootstrap_res, BootstrapSobolResult)
assert isinstance(res._bootstrap_result, BootstrapResult)
assert res._bootstrap_result.confidence_interval.low.shape[0] == 2
assert res._bootstrap_result.confidence_interval.low[1].shape \
== res.first_order.shape
assert bootstrap_res.first_order.confidence_interval.low.shape \
== res.first_order.shape
assert bootstrap_res.total_order.confidence_interval.low.shape \
== res.total_order.shape
assert_array_less(
bootstrap_res.first_order.confidence_interval.low, res.first_order
)
assert_array_less(
res.first_order, bootstrap_res.first_order.confidence_interval.high
)
assert_array_less(
bootstrap_res.total_order.confidence_interval.low, res.total_order
)
assert_array_less(
res.total_order, bootstrap_res.total_order.confidence_interval.high
)
# call again to use previous results and change a param
assert isinstance(
res.bootstrap(confidence_level=0.9, n_resamples=99),
BootstrapSobolResult
)
assert isinstance(res._bootstrap_result, BootstrapResult)
def test_func_dict(self, ishigami_ref_indices):
rng = np.random.default_rng(28631265345463262246170309650372465332)
n = 4096
dists = [
stats.uniform(loc=-np.pi, scale=2*np.pi),
stats.uniform(loc=-np.pi, scale=2*np.pi),
stats.uniform(loc=-np.pi, scale=2*np.pi)
]
A, B = sample_A_B(n=n, dists=dists, rng=rng)
AB = sample_AB(A=A, B=B)
func = {
'f_A': f_ishigami(A).reshape(1, -1),
'f_B': f_ishigami(B).reshape(1, -1),
'f_AB': f_ishigami(AB).reshape((3, 1, -1))
}
# preserve use of old random_state during SPEC 7 transition
res = sobol_indices(
func=func, n=n,
dists=dists,
rng=rng
)
assert_allclose(res.first_order, ishigami_ref_indices[0], atol=1e-2)
res = sobol_indices(
func=func, n=n,
rng=rng
)
assert_allclose(res.first_order, ishigami_ref_indices[0], atol=1e-2)
# Ideally should be exactly equal but since f_ishigami
# uses floating point operations, so exact equality
# might not be possible (due to flakiness in computation).
# So, assert_allclose is used with default parameters
# Regression test for https://github.com/scipy/scipy/issues/21383
assert_allclose(f_ishigami(A).reshape(1, -1), func['f_A'])
assert_allclose(f_ishigami(B).reshape(1, -1), func['f_B'])
assert_allclose(f_ishigami(AB).reshape((3, 1, -1)), func['f_AB'])
def test_method(self, ishigami_ref_indices):
def jansen_sobol(f_A, f_B, f_AB):
"""Jansen for S and Sobol' for St.
From Saltelli2010, table 2 formulations (c) and (e)."""
var = np.var([f_A, f_B], axis=(0, -1))
s = (var - 0.5*np.mean((f_B - f_AB)**2, axis=-1)) / var
st = np.mean(f_A*(f_A - f_AB), axis=-1) / var
return s.T, st.T
rng = np.random.default_rng(28631265345463262246170309650372465332)
res = sobol_indices(
func=f_ishigami, n=4096,
dists=self.dists,
method=jansen_sobol,
rng=rng
)
assert_allclose(res.first_order, ishigami_ref_indices[0], atol=1e-2)
assert_allclose(res.total_order, ishigami_ref_indices[1], atol=1e-2)
def jansen_sobol_typed(
f_A: np.ndarray, f_B: np.ndarray, f_AB: np.ndarray
) -> tuple[np.ndarray, np.ndarray]:
return jansen_sobol(f_A, f_B, f_AB)
_ = sobol_indices(
func=f_ishigami, n=8,
dists=self.dists,
method=jansen_sobol_typed,
rng=rng
)
def test_normalization(self, ishigami_ref_indices):
rng = np.random.default_rng(28631265345463262246170309650372465332)
res = sobol_indices(
func=lambda x: f_ishigami(x) + 1000, n=4096,
dists=self.dists,
rng=rng
)
assert_allclose(res.first_order, ishigami_ref_indices[0], atol=1e-2)
assert_allclose(res.total_order, ishigami_ref_indices[1], atol=1e-2)
def test_constant_function(self, ishigami_ref_indices):
def f_ishigami_vec_const(x):
"""Output of shape (3, n)."""
res = f_ishigami(x)
return res, res * 0 + 10, res
rng = np.random.default_rng(28631265345463262246170309650372465332)
res = sobol_indices(
func=f_ishigami_vec_const, n=4096,
dists=self.dists,
rng=rng
)
ishigami_vec_indices = [
[ishigami_ref_indices[0], [0, 0, 0], ishigami_ref_indices[0]],
[ishigami_ref_indices[1], [0, 0, 0], ishigami_ref_indices[1]]
]
assert_allclose(res.first_order, ishigami_vec_indices[0], atol=1e-2)
assert_allclose(res.total_order, ishigami_vec_indices[1], atol=1e-2)
@pytest.mark.xfail_on_32bit("Can't create large array for test")
def test_more_converged(self, ishigami_ref_indices):
rng = np.random.default_rng(28631265345463262246170309650372465332)
res = sobol_indices(
func=f_ishigami, n=2**19, # 524288
dists=self.dists,
rng=rng
)
assert_allclose(res.first_order, ishigami_ref_indices[0], atol=1e-4)
assert_allclose(res.total_order, ishigami_ref_indices[1], atol=1e-4)
def test_raises(self):
message = r"Each distribution in `dists` must have method `ppf`"
with pytest.raises(ValueError, match=message):
sobol_indices(n=0, func=f_ishigami, dists="uniform")
with pytest.raises(ValueError, match=message):
sobol_indices(n=0, func=f_ishigami, dists=[lambda x: x])
message = r"The balance properties of Sobol'"
with pytest.raises(ValueError, match=message):
sobol_indices(n=7, func=f_ishigami, dists=[stats.uniform()])
with pytest.raises(ValueError, match=message):
sobol_indices(n=4.1, func=f_ishigami, dists=[stats.uniform()])
message = r"'toto' is not a valid 'method'"
with pytest.raises(ValueError, match=message):
sobol_indices(n=0, func=f_ishigami, method='toto')
message = r"must have the following signature"
with pytest.raises(ValueError, match=message):
sobol_indices(n=0, func=f_ishigami, method=lambda x: x)
message = r"'dists' must be defined when 'func' is a callable"
with pytest.raises(ValueError, match=message):
sobol_indices(n=0, func=f_ishigami)
def func_wrong_shape_output(x):
return x.reshape(-1, 1)
message = r"'func' output should have a shape"
with pytest.raises(ValueError, match=message):
sobol_indices(
n=2, func=func_wrong_shape_output, dists=[stats.uniform()]
)
message = r"When 'func' is a dictionary"
with pytest.raises(ValueError, match=message):
sobol_indices(
n=2, func={'f_A': [], 'f_AB': []}, dists=[stats.uniform()]
)
with pytest.raises(ValueError, match=message):
# f_B malformed
sobol_indices(
n=2,
func={'f_A': [1, 2], 'f_B': [3], 'f_AB': [5, 6, 7, 8]},
)
with pytest.raises(ValueError, match=message):
# f_AB malformed
sobol_indices(
n=2,
func={'f_A': [1, 2], 'f_B': [3, 4], 'f_AB': [5, 6, 7]},
)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466import pytest
import numpy as np
from numpy.testing import assert_equal, assert_allclose
from scipy import stats
from scipy.stats import _survival
def _kaplan_meier_reference(times, censored):
# This is a very straightforward implementation of the Kaplan-Meier
# estimator that does almost everything differently from the implementation
# in stats.ecdf.
# Begin by sorting the raw data. Note that the order of death and loss
# at a given time matters: death happens first. See [2] page 461:
# "These conventions may be paraphrased by saying that deaths recorded as
# of an age t are treated as if they occurred slightly before t, and losses
# recorded as of an age t are treated as occurring slightly after t."
# We implement this by sorting the data first by time, then by `censored`,
# (which is 0 when there is a death and 1 when there is only a loss).
dtype = [('time', float), ('censored', int)]
data = np.array([(t, d) for t, d in zip(times, censored)], dtype=dtype)
data = np.sort(data, order=('time', 'censored'))
times = data['time']
died = np.logical_not(data['censored'])
m = times.size
n = np.arange(m, 0, -1) # number at risk
sf = np.cumprod((n - died) / n)
# Find the indices of the *last* occurrence of unique times. The
# corresponding entries of `times` and `sf` are what we want.
_, indices = np.unique(times[::-1], return_index=True)
ref_times = times[-indices - 1]
ref_sf = sf[-indices - 1]
return ref_times, ref_sf
class TestSurvival:
@staticmethod
def get_random_sample(rng, n_unique):
# generate random sample
unique_times = rng.random(n_unique)
# convert to `np.int32` to resolve `np.repeat` failure in 32-bit CI
repeats = rng.integers(1, 4, n_unique).astype(np.int32)
times = rng.permuted(np.repeat(unique_times, repeats))
censored = rng.random(size=times.size) > rng.random()
sample = stats.CensoredData.right_censored(times, censored)
return sample, times, censored
def test_input_validation(self):
message = '`sample` must be a one-dimensional sequence.'
with pytest.raises(ValueError, match=message):
stats.ecdf([[1]])
with pytest.raises(ValueError, match=message):
stats.ecdf(1)
message = '`sample` must not contain nan'
with pytest.raises(ValueError, match=message):
stats.ecdf([np.nan])
message = 'Currently, only uncensored and right-censored data...'
with pytest.raises(NotImplementedError, match=message):
stats.ecdf(stats.CensoredData.left_censored([1], censored=[True]))
message = 'method` must be one of...'
res = stats.ecdf([1, 2, 3])
with pytest.raises(ValueError, match=message):
res.cdf.confidence_interval(method='ekki-ekki')
with pytest.raises(ValueError, match=message):
res.sf.confidence_interval(method='shrubbery')
message = 'confidence_level` must be a scalar between 0 and 1'
with pytest.raises(ValueError, match=message):
res.cdf.confidence_interval(-1)
with pytest.raises(ValueError, match=message):
res.sf.confidence_interval([0.5, 0.6])
message = 'The confidence interval is undefined at some observations.'
with pytest.warns(RuntimeWarning, match=message):
ci = res.cdf.confidence_interval()
message = 'Confidence interval bounds do not implement...'
with pytest.raises(NotImplementedError, match=message):
ci.low.confidence_interval()
with pytest.raises(NotImplementedError, match=message):
ci.high.confidence_interval()
def test_edge_cases(self):
res = stats.ecdf([])
assert_equal(res.cdf.quantiles, [])
assert_equal(res.cdf.probabilities, [])
res = stats.ecdf([1])
assert_equal(res.cdf.quantiles, [1])
assert_equal(res.cdf.probabilities, [1])
def test_unique(self):
# Example with unique observations; `stats.ecdf` ref. [1] page 80
sample = [6.23, 5.58, 7.06, 6.42, 5.20]
res = stats.ecdf(sample)
ref_x = np.sort(np.unique(sample))
ref_cdf = np.arange(1, 6) / 5
ref_sf = 1 - ref_cdf
assert_equal(res.cdf.quantiles, ref_x)
assert_equal(res.cdf.probabilities, ref_cdf)
assert_equal(res.sf.quantiles, ref_x)
assert_equal(res.sf.probabilities, ref_sf)
def test_nonunique(self):
# Example with non-unique observations; `stats.ecdf` ref. [1] page 82
sample = [0, 2, 1, 2, 3, 4]
res = stats.ecdf(sample)
ref_x = np.sort(np.unique(sample))
ref_cdf = np.array([1/6, 2/6, 4/6, 5/6, 1])
ref_sf = 1 - ref_cdf
assert_equal(res.cdf.quantiles, ref_x)
assert_equal(res.cdf.probabilities, ref_cdf)
assert_equal(res.sf.quantiles, ref_x)
assert_equal(res.sf.probabilities, ref_sf)
def test_evaluate_methods(self):
# Test CDF and SF `evaluate` methods
rng = np.random.default_rng(1162729143302572461)
sample, _, _ = self.get_random_sample(rng, 15)
res = stats.ecdf(sample)
x = res.cdf.quantiles
xr = x + np.diff(x, append=x[-1]+1)/2 # right shifted points
assert_equal(res.cdf.evaluate(x), res.cdf.probabilities)
assert_equal(res.cdf.evaluate(xr), res.cdf.probabilities)
assert_equal(res.cdf.evaluate(x[0]-1), 0) # CDF starts at 0
assert_equal(res.cdf.evaluate([-np.inf, np.inf]), [0, 1])
assert_equal(res.sf.evaluate(x), res.sf.probabilities)
assert_equal(res.sf.evaluate(xr), res.sf.probabilities)
assert_equal(res.sf.evaluate(x[0]-1), 1) # SF starts at 1
assert_equal(res.sf.evaluate([-np.inf, np.inf]), [1, 0])
# ref. [1] page 91
t1 = [37, 43, 47, 56, 60, 62, 71, 77, 80, 81] # times
d1 = [0, 0, 1, 1, 0, 0, 0, 1, 1, 1] # 1 means deaths (not censored)
r1 = [1, 1, 0.875, 0.75, 0.75, 0.75, 0.75, 0.5, 0.25, 0] # reference SF
# https://sphweb.bumc.bu.edu/otlt/mph-modules/bs/bs704_survival/BS704_Survival5.html
t2 = [8, 12, 26, 14, 21, 27, 8, 32, 20, 40]
d2 = [1, 1, 1, 1, 1, 1, 0, 0, 0, 0]
r2 = [0.9, 0.788, 0.675, 0.675, 0.54, 0.405, 0.27, 0.27, 0.27]
t3 = [33, 28, 41, 48, 48, 25, 37, 48, 25, 43]
d3 = [1, 1, 1, 0, 0, 0, 0, 0, 0, 0]
r3 = [1, 0.875, 0.75, 0.75, 0.6, 0.6, 0.6]
# https://sphweb.bumc.bu.edu/otlt/mph-modules/bs/bs704_survival/bs704_survival4.html
t4 = [24, 3, 11, 19, 24, 13, 14, 2, 18, 17,
24, 21, 12, 1, 10, 23, 6, 5, 9, 17]
d4 = [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1]
r4 = [0.95, 0.95, 0.897, 0.844, 0.844, 0.844, 0.844, 0.844, 0.844,
0.844, 0.76, 0.676, 0.676, 0.676, 0.676, 0.507, 0.507]
# https://www.real-statistics.com/survival-analysis/kaplan-meier-procedure/confidence-interval-for-the-survival-function/
t5 = [3, 5, 8, 10, 5, 5, 8, 12, 15, 14, 2, 11, 10, 9, 12, 5, 8, 11]
d5 = [1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1]
r5 = [0.944, 0.889, 0.722, 0.542, 0.542, 0.542, 0.361, 0.181, 0.181, 0.181]
@pytest.mark.parametrize("case", [(t1, d1, r1), (t2, d2, r2), (t3, d3, r3),
(t4, d4, r4), (t5, d5, r5)])
def test_right_censored_against_examples(self, case):
# test `ecdf` against other implementations on example problems
times, died, ref = case
sample = stats.CensoredData.right_censored(times, np.logical_not(died))
res = stats.ecdf(sample)
assert_allclose(res.sf.probabilities, ref, atol=1e-3)
assert_equal(res.sf.quantiles, np.sort(np.unique(times)))
# test reference implementation against other implementations
res = _kaplan_meier_reference(times, np.logical_not(died))
assert_equal(res[0], np.sort(np.unique(times)))
assert_allclose(res[1], ref, atol=1e-3)
@pytest.mark.parametrize('seed', [182746786639392128, 737379171436494115,
576033618403180168, 308115465002673650])
def test_right_censored_against_reference_implementation(self, seed):
# test `ecdf` against reference implementation on random problems
rng = np.random.default_rng(seed)
n_unique = rng.integers(10, 100)
sample, times, censored = self.get_random_sample(rng, n_unique)
res = stats.ecdf(sample)
ref = _kaplan_meier_reference(times, censored)
assert_allclose(res.sf.quantiles, ref[0])
assert_allclose(res.sf.probabilities, ref[1])
# If all observations are uncensored, the KM estimate should match
# the usual estimate for uncensored data
sample = stats.CensoredData(uncensored=times)
res = _survival._ecdf_right_censored(sample) # force Kaplan-Meier
ref = stats.ecdf(times)
assert_equal(res[0], ref.sf.quantiles)
assert_allclose(res[1], ref.cdf.probabilities, rtol=1e-14)
assert_allclose(res[2], ref.sf.probabilities, rtol=1e-14)
def test_right_censored_ci(self):
# test "greenwood" confidence interval against example 4 (URL above).
times, died = self.t4, self.d4
sample = stats.CensoredData.right_censored(times, np.logical_not(died))
res = stats.ecdf(sample)
ref_allowance = [0.096, 0.096, 0.135, 0.162, 0.162, 0.162, 0.162,
0.162, 0.162, 0.162, 0.214, 0.246, 0.246, 0.246,
0.246, 0.341, 0.341]
sf_ci = res.sf.confidence_interval()
cdf_ci = res.cdf.confidence_interval()
allowance = res.sf.probabilities - sf_ci.low.probabilities
assert_allclose(allowance, ref_allowance, atol=1e-3)
assert_allclose(sf_ci.low.probabilities,
np.clip(res.sf.probabilities - allowance, 0, 1))
assert_allclose(sf_ci.high.probabilities,
np.clip(res.sf.probabilities + allowance, 0, 1))
assert_allclose(cdf_ci.low.probabilities,
np.clip(res.cdf.probabilities - allowance, 0, 1))
assert_allclose(cdf_ci.high.probabilities,
np.clip(res.cdf.probabilities + allowance, 0, 1))
# test "log-log" confidence interval against Mathematica
# e = {24, 3, 11, 19, 24, 13, 14, 2, 18, 17, 24, 21, 12, 1, 10, 23, 6, 5,
# 9, 17}
# ci = {1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0}
# R = EventData[e, ci]
# S = SurvivalModelFit[R]
# S["PointwiseIntervals", ConfidenceLevel->0.95,
# ConfidenceTransform->"LogLog"]
ref_low = [0.694743, 0.694743, 0.647529, 0.591142, 0.591142, 0.591142,
0.591142, 0.591142, 0.591142, 0.591142, 0.464605, 0.370359,
0.370359, 0.370359, 0.370359, 0.160489, 0.160489]
ref_high = [0.992802, 0.992802, 0.973299, 0.947073, 0.947073, 0.947073,
0.947073, 0.947073, 0.947073, 0.947073, 0.906422, 0.856521,
0.856521, 0.856521, 0.856521, 0.776724, 0.776724]
sf_ci = res.sf.confidence_interval(method='log-log')
assert_allclose(sf_ci.low.probabilities, ref_low, atol=1e-6)
assert_allclose(sf_ci.high.probabilities, ref_high, atol=1e-6)
def test_right_censored_ci_example_5(self):
# test "exponential greenwood" confidence interval against example 5
times, died = self.t5, self.d5
sample = stats.CensoredData.right_censored(times, np.logical_not(died))
res = stats.ecdf(sample)
lower = np.array([0.66639, 0.624174, 0.456179, 0.287822, 0.287822,
0.287822, 0.128489, 0.030957, 0.030957, 0.030957])
upper = np.array([0.991983, 0.970995, 0.87378, 0.739467, 0.739467,
0.739467, 0.603133, 0.430365, 0.430365, 0.430365])
sf_ci = res.sf.confidence_interval(method='log-log')
cdf_ci = res.cdf.confidence_interval(method='log-log')
assert_allclose(sf_ci.low.probabilities, lower, atol=1e-5)
assert_allclose(sf_ci.high.probabilities, upper, atol=1e-5)
assert_allclose(cdf_ci.low.probabilities, 1-upper, atol=1e-5)
assert_allclose(cdf_ci.high.probabilities, 1-lower, atol=1e-5)
# Test against R's `survival` library `survfit` function, 90%CI
# library(survival)
# options(digits=16)
# time = c(3, 5, 8, 10, 5, 5, 8, 12, 15, 14, 2, 11, 10, 9, 12, 5, 8, 11)
# status = c(1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1)
# res = survfit(Surv(time, status)
# ~1, conf.type = "log-log", conf.int = 0.90)
# res$time; res$lower; res$upper
low = [0.74366748406861172, 0.68582332289196246, 0.50596835651480121,
0.32913131413336727, 0.32913131413336727, 0.32913131413336727,
0.15986912028781664, 0.04499539918147757, 0.04499539918147757,
0.04499539918147757]
high = [0.9890291867238429, 0.9638835422144144, 0.8560366823086629,
0.7130167643978450, 0.7130167643978450, 0.7130167643978450,
0.5678602982997164, 0.3887616766886558, 0.3887616766886558,
0.3887616766886558]
sf_ci = res.sf.confidence_interval(method='log-log',
confidence_level=0.9)
assert_allclose(sf_ci.low.probabilities, low)
assert_allclose(sf_ci.high.probabilities, high)
# And with conf.type = "plain"
low = [0.8556383113628162, 0.7670478794850761, 0.5485720663578469,
0.3441515412527123, 0.3441515412527123, 0.3441515412527123,
0.1449184105424544, 0., 0., 0.]
high = [1., 1., 0.8958723780865975, 0.7391817920806210,
0.7391817920806210, 0.7391817920806210, 0.5773038116797676,
0.3642270254596720, 0.3642270254596720, 0.3642270254596720]
sf_ci = res.sf.confidence_interval(confidence_level=0.9)
assert_allclose(sf_ci.low.probabilities, low)
assert_allclose(sf_ci.high.probabilities, high)
def test_right_censored_ci_nans(self):
# test `ecdf` confidence interval on a problem that results in NaNs
times, died = self.t1, self.d1
sample = stats.CensoredData.right_censored(times, np.logical_not(died))
res = stats.ecdf(sample)
# Reference values generated with Matlab
# format long
# t = [37 43 47 56 60 62 71 77 80 81];
# d = [0 0 1 1 0 0 0 1 1 1];
# censored = ~d1;
# [f, x, flo, fup] = ecdf(t, 'Censoring', censored, 'Alpha', 0.05);
x = [37, 47, 56, 77, 80, 81]
flo = [np.nan, 0, 0, 0.052701464070711, 0.337611126231790, np.nan]
fup = [np.nan, 0.35417230377, 0.5500569798, 0.9472985359, 1.0, np.nan]
i = np.searchsorted(res.cdf.quantiles, x)
message = "The confidence interval is undefined at some observations"
with pytest.warns(RuntimeWarning, match=message):
ci = res.cdf.confidence_interval()
# Matlab gives NaN as the first element of the CIs. Mathematica agrees,
# but R's survfit does not. It makes some sense, but it's not what the
# formula gives, so skip that element.
assert_allclose(ci.low.probabilities[i][1:], flo[1:])
assert_allclose(ci.high.probabilities[i][1:], fup[1:])
# [f, x, flo, fup] = ecdf(t, 'Censoring', censored, 'Function',
# 'survivor', 'Alpha', 0.05);
flo = [np.nan, 0.64582769623, 0.449943020228, 0.05270146407, 0, np.nan]
fup = [np.nan, 1.0, 1.0, 0.947298535929289, 0.662388873768210, np.nan]
i = np.searchsorted(res.cdf.quantiles, x)
with pytest.warns(RuntimeWarning, match=message):
ci = res.sf.confidence_interval()
assert_allclose(ci.low.probabilities[i][1:], flo[1:])
assert_allclose(ci.high.probabilities[i][1:], fup[1:])
# With the same data, R's `survival` library `survfit` function
# doesn't produce the leading NaN
# library(survival)
# options(digits=16)
# time = c(37, 43, 47, 56, 60, 62, 71, 77, 80, 81)
# status = c(0, 0, 1, 1, 0, 0, 0, 1, 1, 1)
# res = survfit(Surv(time, status)
# ~1, conf.type = "plain", conf.int = 0.95)
# res$time
# res$lower
# res$upper
low = [1., 1., 0.64582769623233816, 0.44994302022779326,
0.44994302022779326, 0.44994302022779326, 0.44994302022779326,
0.05270146407071086, 0., np.nan]
high = [1., 1., 1., 1., 1., 1., 1., 0.9472985359292891,
0.6623888737682101, np.nan]
assert_allclose(ci.low.probabilities, low)
assert_allclose(ci.high.probabilities, high)
# It does with conf.type="log-log", as do we
with pytest.warns(RuntimeWarning, match=message):
ci = res.sf.confidence_interval(method='log-log')
low = [np.nan, np.nan, 0.38700001403202522, 0.31480711370551911,
0.31480711370551911, 0.31480711370551911, 0.31480711370551911,
0.08048821148507734, 0.01049958986680601, np.nan]
high = [np.nan, np.nan, 0.9813929658789660, 0.9308983170906275,
0.9308983170906275, 0.9308983170906275, 0.9308983170906275,
0.8263946341076415, 0.6558775085110887, np.nan]
assert_allclose(ci.low.probabilities, low)
assert_allclose(ci.high.probabilities, high)
def test_right_censored_against_uncensored(self):
rng = np.random.default_rng(7463952748044886637)
sample = rng.integers(10, 100, size=1000)
censored = np.zeros_like(sample)
censored[np.argmax(sample)] = True
res = stats.ecdf(sample)
ref = stats.ecdf(stats.CensoredData.right_censored(sample, censored))
assert_equal(res.sf.quantiles, ref.sf.quantiles)
assert_equal(res.sf._n, ref.sf._n)
assert_equal(res.sf._d[:-1], ref.sf._d[:-1]) # difference @ [-1]
assert_allclose(res.sf._sf[:-1], ref.sf._sf[:-1], rtol=1e-14)
def test_plot_iv(self):
rng = np.random.default_rng(1769658657308472721)
n_unique = rng.integers(10, 100)
sample, _, _ = self.get_random_sample(rng, n_unique)
res = stats.ecdf(sample)
try:
import matplotlib.pyplot as plt # noqa: F401
res.sf.plot() # no other errors occur
except (ModuleNotFoundError, ImportError):
message = r"matplotlib must be installed to use method `plot`."
with pytest.raises(ModuleNotFoundError, match=message):
res.sf.plot()
class TestLogRank:
@pytest.mark.parametrize(
"x, y, statistic, pvalue",
# Results validate with R
# library(survival)
# options(digits=16)
#
# futime_1 <- c(8, 12, 26, 14, 21, 27, 8, 32, 20, 40)
# fustat_1 <- c(1, 1, 1, 1, 1, 1, 0, 0, 0, 0)
# rx_1 <- c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
#
# futime_2 <- c(33, 28, 41, 48, 48, 25, 37, 48, 25, 43)
# fustat_2 <- c(1, 1, 1, 0, 0, 0, 0, 0, 0, 0)
# rx_2 <- c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
#
# futime <- c(futime_1, futime_2)
# fustat <- c(fustat_1, fustat_2)
# rx <- c(rx_1, rx_2)
#
# survdiff(formula = Surv(futime, fustat) ~ rx)
#
# Also check against another library which handle alternatives
# library(nph)
# logrank.test(futime, fustat, rx, alternative = "two.sided")
# res["test"]
[(
# https://sphweb.bumc.bu.edu/otlt/mph-modules/bs/bs704_survival/BS704_Survival5.html
# uncensored, censored
[[8, 12, 26, 14, 21, 27], [8, 32, 20, 40]],
[[33, 28, 41], [48, 48, 25, 37, 48, 25, 43]],
# chi2, ["two-sided", "less", "greater"]
6.91598157449,
[0.008542873404, 0.9957285632979385, 0.004271436702061537]
),
(
# https://sphweb.bumc.bu.edu/otlt/mph-modules/bs/bs704_survival/BS704_Survival5.html
[[19, 6, 5, 4], [20, 19, 17, 14]],
[[16, 21, 7], [21, 15, 18, 18, 5]],
0.835004855038,
[0.3608293039, 0.8195853480676912, 0.1804146519323088]
),
(
# Bland, Altman, "The logrank test", BMJ, 2004
# https://www.bmj.com/content/328/7447/1073.short
[[6, 13, 21, 30, 37, 38, 49, 50, 63, 79, 86, 98, 202, 219],
[31, 47, 80, 82, 82, 149]],
[[10, 10, 12, 13, 14, 15, 16, 17, 18, 20, 24, 24, 25, 28, 30,
33, 35, 37, 40, 40, 46, 48, 76, 81, 82, 91, 112, 181],
[34, 40, 70]],
7.49659416854,
[0.006181578637, 0.003090789318730882, 0.9969092106812691]
)]
)
def test_log_rank(self, x, y, statistic, pvalue):
x = stats.CensoredData(uncensored=x[0], right=x[1])
y = stats.CensoredData(uncensored=y[0], right=y[1])
for i, alternative in enumerate(["two-sided", "less", "greater"]):
res = stats.logrank(x=x, y=y, alternative=alternative)
# we return z and use the normal distribution while other framework
# return z**2. The p-value are directly comparable, but we have to
# square the statistic
assert_allclose(res.statistic**2, statistic, atol=1e-10)
assert_allclose(res.pvalue, pvalue[i], atol=1e-10)
def test_raises(self):
sample = stats.CensoredData([1, 2])
msg = r"`y` must be"
with pytest.raises(ValueError, match=msg):
stats.logrank(x=sample, y=[[1, 2]])
msg = r"`x` must be"
with pytest.raises(ValueError, match=msg):
stats.logrank(x=[[1, 2]], y=sample)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485import numpy as np
from numpy.testing import assert_allclose, assert_equal
from scipy.stats._tukeylambda_stats import (tukeylambda_variance,
tukeylambda_kurtosis)
def test_tukeylambda_stats_known_exact():
"""Compare results with some known exact formulas."""
# Some exact values of the Tukey Lambda variance and kurtosis:
# lambda var kurtosis
# 0 pi**2/3 6/5 (logistic distribution)
# 0.5 4 - pi (5/3 - pi/2)/(pi/4 - 1)**2 - 3
# 1 1/3 -6/5 (uniform distribution on (-1,1))
# 2 1/12 -6/5 (uniform distribution on (-1/2, 1/2))
# lambda = 0
var = tukeylambda_variance(0)
assert_allclose(var, np.pi**2 / 3, atol=1e-12)
kurt = tukeylambda_kurtosis(0)
assert_allclose(kurt, 1.2, atol=1e-10)
# lambda = 0.5
var = tukeylambda_variance(0.5)
assert_allclose(var, 4 - np.pi, atol=1e-12)
kurt = tukeylambda_kurtosis(0.5)
desired = (5./3 - np.pi/2) / (np.pi/4 - 1)**2 - 3
assert_allclose(kurt, desired, atol=1e-10)
# lambda = 1
var = tukeylambda_variance(1)
assert_allclose(var, 1.0 / 3, atol=1e-12)
kurt = tukeylambda_kurtosis(1)
assert_allclose(kurt, -1.2, atol=1e-10)
# lambda = 2
var = tukeylambda_variance(2)
assert_allclose(var, 1.0 / 12, atol=1e-12)
kurt = tukeylambda_kurtosis(2)
assert_allclose(kurt, -1.2, atol=1e-10)
def test_tukeylambda_stats_mpmath():
"""Compare results with some values that were computed using mpmath."""
a10 = dict(atol=1e-10, rtol=0)
a12 = dict(atol=1e-12, rtol=0)
data = [
# lambda variance kurtosis
[-0.1, 4.78050217874253547, 3.78559520346454510],
[-0.0649, 4.16428023599895777, 2.52019675947435718],
[-0.05, 3.93672267890775277, 2.13129793057777277],
[-0.001, 3.30128380390964882, 1.21452460083542988],
[0.001, 3.27850775649572176, 1.18560634779287585],
[0.03125, 2.95927803254615800, 0.804487555161819980],
[0.05, 2.78281053405464501, 0.611604043886644327],
[0.0649, 2.65282386754100551, 0.476834119532774540],
[1.2, 0.242153920578588346, -1.23428047169049726],
[10.0, 0.00095237579757703597, 2.37810697355144933],
[20.0, 0.00012195121951131043, 7.37654321002709531],
]
for lam, var_expected, kurt_expected in data:
var = tukeylambda_variance(lam)
assert_allclose(var, var_expected, **a12)
kurt = tukeylambda_kurtosis(lam)
assert_allclose(kurt, kurt_expected, **a10)
# Test with vector arguments (most of the other tests are for single
# values).
lam, var_expected, kurt_expected = zip(*data)
var = tukeylambda_variance(lam)
assert_allclose(var, var_expected, **a12)
kurt = tukeylambda_kurtosis(lam)
assert_allclose(kurt, kurt_expected, **a10)
def test_tukeylambda_stats_invalid():
"""Test values of lambda outside the domains of the functions."""
lam = [-1.0, -0.5]
var = tukeylambda_variance(lam)
assert_equal(var, np.array([np.nan, np.inf]))
lam = [-1.0, -0.25]
kurt = tukeylambda_kurtosis(lam)
assert_equal(kurt, np.array([np.nan, np.inf]))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214import math
import numpy as np
import pytest
from scipy.stats import variation
from scipy._lib._util import AxisError
from scipy._lib._array_api import make_xp_test_case, eager_warns
from scipy._lib._array_api_no_0d import xp_assert_equal, xp_assert_close
from scipy.stats._axis_nan_policy import (too_small_nd_omit, too_small_nd_not_omit,
SmallSampleWarning)
skip_xp_backends = pytest.mark.skip_xp_backends
@make_xp_test_case(variation)
class TestVariation:
"""
Test class for scipy.stats.variation
"""
def test_ddof(self, xp):
x = xp.arange(9.0)
xp_assert_close(variation(x, ddof=1), xp.asarray(math.sqrt(60/8)/4))
@pytest.mark.parametrize('sgn', [1, -1])
def test_sign(self, sgn, xp):
x = xp.asarray([1., 2., 3., 4., 5.])
v = variation(sgn*x)
expected = xp.asarray(sgn*math.sqrt(2)/3)
xp_assert_close(v, expected, rtol=1e-10)
@skip_xp_backends(np_only=True, reason="test plain python scalar input")
def test_scalar(self, xp):
# A scalar is treated like a 1-d sequence with length 1.
assert variation(4.0) == 0.0
@pytest.mark.parametrize('nan_policy, expected',
[('propagate', np.nan),
('omit', np.sqrt(20/3)/4)])
@skip_xp_backends(np_only=True,
reason='`nan_policy` only supports NumPy backend')
def test_variation_nan(self, nan_policy, expected, xp):
x = xp.arange(10.)
x[9] = xp.nan
xp_assert_close(variation(x, nan_policy=nan_policy), expected)
@skip_xp_backends(np_only=True,
reason='`nan_policy` only supports NumPy backend')
def test_nan_policy_raise(self, xp):
x = xp.asarray([1.0, 2.0, xp.nan, 3.0])
with pytest.raises(ValueError, match='input contains nan'):
variation(x, nan_policy='raise')
@skip_xp_backends(np_only=True,
reason='`nan_policy` only supports NumPy backend')
def test_bad_nan_policy(self, xp):
with pytest.raises(ValueError, match='must be one of'):
variation([1, 2, 3], nan_policy='foobar')
@skip_xp_backends(np_only=True,
reason='`keepdims` only supports NumPy backend')
def test_keepdims(self, xp):
x = xp.reshape(xp.arange(10), (2, 5))
y = variation(x, axis=1, keepdims=True)
expected = np.array([[np.sqrt(2)/2],
[np.sqrt(2)/7]])
xp_assert_close(y, expected)
@skip_xp_backends(np_only=True,
reason='`keepdims` only supports NumPy backend')
@pytest.mark.parametrize('axis, expected',
[(0, np.empty((1, 0))),
(1, np.full((5, 1), fill_value=np.nan))])
def test_keepdims_size0(self, axis, expected, xp):
x = xp.zeros((5, 0))
if axis == 1:
with pytest.warns(SmallSampleWarning, match=too_small_nd_not_omit):
y = variation(x, axis=axis, keepdims=True)
else:
y = variation(x, axis=axis, keepdims=True)
xp_assert_equal(y, expected)
@skip_xp_backends(np_only=True,
reason='`keepdims` only supports NumPy backend')
@pytest.mark.parametrize('incr, expected_fill', [(0, np.inf), (1, np.nan)])
def test_keepdims_and_ddof_eq_len_plus_incr(self, incr, expected_fill, xp):
x = xp.asarray([[1, 1, 2, 2], [1, 2, 3, 3]])
y = variation(x, axis=1, ddof=x.shape[1] + incr, keepdims=True)
xp_assert_equal(y, xp.full((2, 1), fill_value=expected_fill))
@skip_xp_backends(np_only=True,
reason='`nan_policy` only supports NumPy backend')
def test_propagate_nan(self, xp):
# Check that the shape of the result is the same for inputs
# with and without nans, cf gh-5817
a = xp.reshape(xp.arange(8, dtype=float), (2, -1))
a[1, 0] = xp.nan
v = variation(a, axis=1, nan_policy="propagate")
xp_assert_close(v, [math.sqrt(5/4)/1.5, xp.nan], atol=1e-15)
@skip_xp_backends(np_only=True, reason='Python list input uses NumPy backend')
def test_axis_none(self, xp):
# Check that `variation` computes the result on the flattened
# input when axis is None.
y = variation([[0, 1], [2, 3]], axis=None)
xp_assert_close(y, math.sqrt(5/4)/1.5)
def test_bad_axis(self, xp):
# Check that an invalid axis raises np.exceptions.AxisError.
x = xp.asarray([[1, 2, 3], [4, 5, 6]])
with pytest.raises((AxisError, IndexError)):
variation(x, axis=10)
@pytest.mark.filterwarnings("ignore:divide by zero encountered:RuntimeWarning:dask")
def test_mean_zero(self, xp):
# Check that `variation` returns inf for a sequence that is not
# identically zero but whose mean is zero.
x = xp.asarray([10., -3., 1., -4., -4.])
y = variation(x)
xp_assert_equal(y, xp.asarray(xp.inf))
x2 = xp.stack([x, -10.*x])
y2 = variation(x2, axis=1)
xp_assert_equal(y2, xp.asarray([xp.inf, xp.inf]))
@pytest.mark.filterwarnings("ignore:invalid value encountered:RuntimeWarning:dask")
@pytest.mark.parametrize('x', [[0.]*5, [1, 2, np.inf, 9]])
def test_return_nan(self, x, xp):
x = xp.asarray(x)
# Test some cases where `variation` returns nan.
y = variation(x)
xp_assert_equal(y, xp.asarray(xp.nan, dtype=x.dtype))
@pytest.mark.filterwarnings('ignore:Invalid value encountered:RuntimeWarning:dask')
@pytest.mark.parametrize('axis, expected',
[(0, []), (1, [np.nan]*3), (None, np.nan)])
def test_2d_size_zero_with_axis(self, axis, expected, xp):
x = xp.empty((3, 0))
if axis != 0:
# specific message depends on `axis`, and `SmallSampleWarning`
# is specific enough.
with eager_warns(SmallSampleWarning, xp=xp):
y = variation(x, axis=axis)
else:
y = variation(x, axis=axis)
xp_assert_equal(y, xp.asarray(expected))
@pytest.mark.filterwarnings('ignore:divide by zero encountered:RuntimeWarning:dask')
def test_neg_inf(self, xp):
# Edge case that produces -inf: ddof equals the number of non-nan
# values, the values are not constant, and the mean is negative.
x1 = xp.asarray([-3., -5.])
xp_assert_equal(variation(x1, ddof=2), xp.asarray(-xp.inf))
@skip_xp_backends(np_only=True,
reason='`nan_policy` only supports NumPy backend')
def test_neg_inf_nan(self, xp):
x2 = xp.asarray([[xp.nan, 1, -10, xp.nan],
[-20, -3, xp.nan, xp.nan]])
xp_assert_equal(variation(x2, axis=1, ddof=2, nan_policy='omit'),
[-xp.inf, -xp.inf])
@skip_xp_backends(np_only=True,
reason='`nan_policy` only supports NumPy backend')
@pytest.mark.parametrize("nan_policy", ['propagate', 'omit'])
def test_combined_edge_cases(self, nan_policy, xp):
x = xp.asarray([[0, 10, xp.nan, 1],
[0, -5, xp.nan, 2],
[0, -5, xp.nan, 3]])
if nan_policy == 'omit':
with pytest.warns(SmallSampleWarning, match=too_small_nd_omit):
y = variation(x, axis=0, nan_policy=nan_policy)
else:
y = variation(x, axis=0, nan_policy=nan_policy)
xp_assert_close(y, [xp.nan, xp.inf, xp.nan, math.sqrt(2/3)/2])
@skip_xp_backends(np_only=True,
reason='`nan_policy` only supports NumPy backend')
@pytest.mark.parametrize(
'ddof, expected',
[(0, [np.sqrt(1/6), np.sqrt(5/8), np.inf, 0, np.nan, 0.0, np.nan]),
(1, [0.5, np.sqrt(5/6), np.inf, 0, np.nan, 0, np.nan]),
(2, [np.sqrt(0.5), np.sqrt(5/4), np.inf, np.nan, np.nan, 0, np.nan])]
)
def test_more_nan_policy_omit_tests(self, ddof, expected, xp):
# The slightly strange formatting in the follow array is my attempt to
# maintain a clean tabular arrangement of the data while satisfying
# the demands of pycodestyle. Currently, E201 and E241 are not
# disabled by the `noqa` annotation.
nan = xp.nan
x = xp.asarray([[1.0, 2.0, nan, 3.0],
[0.0, 4.0, 3.0, 1.0],
[nan, -.5, 0.5, nan],
[nan, 9.0, 9.0, nan],
[nan, nan, nan, nan],
[3.0, 3.0, 3.0, 3.0],
[0.0, 0.0, 0.0, 0.0]])
with pytest.warns(SmallSampleWarning, match=too_small_nd_omit):
v = variation(x, axis=1, ddof=ddof, nan_policy='omit')
xp_assert_close(v, expected)
@skip_xp_backends(np_only=True,
reason='`nan_policy` only supports NumPy backend')
def test_variation_ddof(self, xp):
# test variation with delta degrees of freedom
# regression test for gh-13341
a = xp.asarray([1., 2., 3., 4., 5.])
nan_a = xp.asarray([1, 2, 3, xp.nan, 4, 5, xp.nan])
y = variation(a, ddof=1)
nan_y = variation(nan_a, nan_policy="omit", ddof=1)
xp_assert_close(y, math.sqrt(5/2)/3)
assert y == nan_y123456789101112
"""
Module to expose more detailed version info for the installed `scipy`
"""
version = "1.17.1"
full_version = version
short_version = version.split('.dev')[0]
git_revision = "527eb7fd7953a1de068f94bf8b322f249b9405ae"
release = 'dev' not in version and '+' not in version
if not release:
version = full_versionloan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_odds_ratio.pyAdded+148
loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_qmc.pyAdded+1534
loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_quantile.pyAdded+412
loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_rank.pyAdded+348
loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_relative_risk.pyAdded+95
loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_resampling.pyAdded+2046
loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_sampling.pyAdded+1448
loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_sensitivity_analysis.pyAdded+310
loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_stats.pyAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_survival.pyAdded+466
loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_tukeylambda_stats.pyAdded+85
loan-advisor-agent/.venv/Lib/site-packages/scipy/stats/tests/test_variation.pyAdded+214
loan-advisor-agent/.venv/Lib/site-packages/scipy/version.pyAdded+12