_page_trend_test.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. from itertools import permutations
  2. import numpy as np
  3. import math
  4. from ._continuous_distns import norm
  5. import scipy.stats
  6. from dataclasses import make_dataclass
  7. PageTrendTestResult = make_dataclass("PageTrendTestResult",
  8. ("statistic", "pvalue", "method"))
  9. def page_trend_test(data, ranked=False, predicted_ranks=None, method='auto'):
  10. r"""
  11. Perform Page's Test, a measure of trend in observations between treatments.
  12. Page's Test (also known as Page's :math:`L` test) is useful when:
  13. * there are :math:`n \geq 3` treatments,
  14. * :math:`m \geq 2` subjects are observed for each treatment, and
  15. * the observations are hypothesized to have a particular order.
  16. Specifically, the test considers the null hypothesis that
  17. .. math::
  18. m_1 = m_2 = m_3 \cdots = m_n,
  19. where :math:`m_j` is the mean of the observed quantity under treatment
  20. :math:`j`, against the alternative hypothesis that
  21. .. math::
  22. m_1 \leq m_2 \leq m_3 \leq \cdots \leq m_n,
  23. where at least one inequality is strict.
  24. As noted by [4]_, Page's :math:`L` test has greater statistical power than
  25. the Friedman test against the alternative that there is a difference in
  26. trend, as Friedman's test only considers a difference in the means of the
  27. observations without considering their order. Whereas Spearman :math:`\rho`
  28. considers the correlation between the ranked observations of two variables
  29. (e.g. the airspeed velocity of a swallow vs. the weight of the coconut it
  30. carries), Page's :math:`L` is concerned with a trend in an observation
  31. (e.g. the airspeed velocity of a swallow) across several distinct
  32. treatments (e.g. carrying each of five coconuts of different weight) even
  33. as the observation is repeated with multiple subjects (e.g. one European
  34. swallow and one African swallow).
  35. Parameters
  36. ----------
  37. data : array-like
  38. A :math:`m \times n` array; the element in row :math:`i` and
  39. column :math:`j` is the observation corresponding with subject
  40. :math:`i` and treatment :math:`j`. By default, the columns are
  41. assumed to be arranged in order of increasing predicted mean.
  42. ranked : boolean, optional
  43. By default, `data` is assumed to be observations rather than ranks;
  44. it will be ranked with `scipy.stats.rankdata` along ``axis=1``. If
  45. `data` is provided in the form of ranks, pass argument ``True``.
  46. predicted_ranks : array-like, optional
  47. The predicted ranks of the column means. If not specified,
  48. the columns are assumed to be arranged in order of increasing
  49. predicted mean, so the default `predicted_ranks` are
  50. :math:`[1, 2, \dots, n-1, n]`.
  51. method : {'auto', 'asymptotic', 'exact'}, optional
  52. Selects the method used to calculate the *p*-value. The following
  53. options are available.
  54. * 'auto': selects between 'exact' and 'asymptotic' to
  55. achieve reasonably accurate results in reasonable time (default)
  56. * 'asymptotic': compares the standardized test statistic against
  57. the normal distribution
  58. * 'exact': computes the exact *p*-value by comparing the observed
  59. :math:`L` statistic against those realized by all possible
  60. permutations of ranks (under the null hypothesis that each
  61. permutation is equally likely)
  62. Returns
  63. -------
  64. res : PageTrendTestResult
  65. An object containing attributes:
  66. statistic : float
  67. Page's :math:`L` test statistic.
  68. pvalue : float
  69. The associated *p*-value
  70. method : {'asymptotic', 'exact'}
  71. The method used to compute the *p*-value
  72. See Also
  73. --------
  74. rankdata, friedmanchisquare, spearmanr
  75. Notes
  76. -----
  77. As noted in [1]_, "the :math:`n` 'treatments' could just as well represent
  78. :math:`n` objects or events or performances or persons or trials ranked."
  79. Similarly, the :math:`m` 'subjects' could equally stand for :math:`m`
  80. "groupings by ability or some other control variable, or judges doing
  81. the ranking, or random replications of some other sort."
  82. The procedure for calculating the :math:`L` statistic, adapted from
  83. [1]_, is:
  84. 1. "Predetermine with careful logic the appropriate hypotheses
  85. concerning the predicted ording of the experimental results.
  86. If no reasonable basis for ordering any treatments is known, the
  87. :math:`L` test is not appropriate."
  88. 2. "As in other experiments, determine at what level of confidence
  89. you will reject the null hypothesis that there is no agreement of
  90. experimental results with the monotonic hypothesis."
  91. 3. "Cast the experimental material into a two-way table of :math:`n`
  92. columns (treatments, objects ranked, conditions) and :math:`m`
  93. rows (subjects, replication groups, levels of control variables)."
  94. 4. "When experimental observations are recorded, rank them across each
  95. row", e.g. ``ranks = scipy.stats.rankdata(data, axis=1)``.
  96. 5. "Add the ranks in each column", e.g.
  97. ``colsums = np.sum(ranks, axis=0)``.
  98. 6. "Multiply each sum of ranks by the predicted rank for that same
  99. column", e.g. ``products = predicted_ranks * colsums``.
  100. 7. "Sum all such products", e.g. ``L = products.sum()``.
  101. [1]_ continues by suggesting use of the standardized statistic
  102. .. math::
  103. \chi_L^2 = \frac{\left[12L-3mn(n+1)^2\right]^2}{mn^2(n^2-1)(n+1)}
  104. "which is distributed approximately as chi-square with 1 degree of
  105. freedom. The ordinary use of :math:`\chi^2` tables would be
  106. equivalent to a two-sided test of agreement. If a one-sided test
  107. is desired, *as will almost always be the case*, the probability
  108. discovered in the chi-square table should be *halved*."
  109. However, this standardized statistic does not distinguish between the
  110. observed values being well correlated with the predicted ranks and being
  111. _anti_-correlated with the predicted ranks. Instead, we follow [2]_
  112. and calculate the standardized statistic
  113. .. math::
  114. \Lambda = \frac{L - E_0}{\sqrt{V_0}},
  115. where :math:`E_0 = \frac{1}{4} mn(n+1)^2` and
  116. :math:`V_0 = \frac{1}{144} mn^2(n+1)(n^2-1)`, "which is asymptotically
  117. normal under the null hypothesis".
  118. The *p*-value for ``method='exact'`` is generated by comparing the observed
  119. value of :math:`L` against the :math:`L` values generated for all
  120. :math:`(n!)^m` possible permutations of ranks. The calculation is performed
  121. using the recursive method of [5].
  122. The *p*-values are not adjusted for the possibility of ties. When
  123. ties are present, the reported ``'exact'`` *p*-values may be somewhat
  124. larger (i.e. more conservative) than the true *p*-value [2]_. The
  125. ``'asymptotic'``` *p*-values, however, tend to be smaller (i.e. less
  126. conservative) than the ``'exact'`` *p*-values.
  127. References
  128. ----------
  129. .. [1] Ellis Batten Page, "Ordered hypotheses for multiple treatments:
  130. a significant test for linear ranks", *Journal of the American
  131. Statistical Association* 58(301), p. 216--230, 1963.
  132. .. [2] Markus Neuhauser, *Nonparametric Statistical Test: A computational
  133. approach*, CRC Press, p. 150--152, 2012.
  134. .. [3] Statext LLC, "Page's L Trend Test - Easy Statistics", *Statext -
  135. Statistics Study*, https://www.statext.com/practice/PageTrendTest03.php,
  136. Accessed July 12, 2020.
  137. .. [4] "Page's Trend Test", *Wikipedia*, WikimediaFoundation,
  138. https://en.wikipedia.org/wiki/Page%27s_trend_test,
  139. Accessed July 12, 2020.
  140. .. [5] Robert E. Odeh, "The exact distribution of Page's L-statistic in
  141. the two-way layout", *Communications in Statistics - Simulation and
  142. Computation*, 6(1), p. 49--61, 1977.
  143. Examples
  144. --------
  145. We use the example from [3]_: 10 students are asked to rate three
  146. teaching methods - tutorial, lecture, and seminar - on a scale of 1-5,
  147. with 1 being the lowest and 5 being the highest. We have decided that
  148. a confidence level of 99% is required to reject the null hypothesis in
  149. favor of our alternative: that the seminar will have the highest ratings
  150. and the tutorial will have the lowest. Initially, the data have been
  151. tabulated with each row representing an individual student's ratings of
  152. the three methods in the following order: tutorial, lecture, seminar.
  153. >>> table = [[3, 4, 3],
  154. ... [2, 2, 4],
  155. ... [3, 3, 5],
  156. ... [1, 3, 2],
  157. ... [2, 3, 2],
  158. ... [2, 4, 5],
  159. ... [1, 2, 4],
  160. ... [3, 4, 4],
  161. ... [2, 4, 5],
  162. ... [1, 3, 4]]
  163. Because the tutorial is hypothesized to have the lowest ratings, the
  164. column corresponding with tutorial rankings should be first; the seminar
  165. is hypothesized to have the highest ratings, so its column should be last.
  166. Since the columns are already arranged in this order of increasing
  167. predicted mean, we can pass the table directly into `page_trend_test`.
  168. >>> from scipy.stats import page_trend_test
  169. >>> res = page_trend_test(table)
  170. >>> res
  171. PageTrendTestResult(statistic=133.5, pvalue=0.0018191161948127822,
  172. method='exact')
  173. This *p*-value indicates that there is a 0.1819% chance that
  174. the :math:`L` statistic would reach such an extreme value under the null
  175. hypothesis. Because 0.1819% is less than 1%, we have evidence to reject
  176. the null hypothesis in favor of our alternative at a 99% confidence level.
  177. The value of the :math:`L` statistic is 133.5. To check this manually,
  178. we rank the data such that high scores correspond with high ranks, settling
  179. ties with an average rank:
  180. >>> from scipy.stats import rankdata
  181. >>> ranks = rankdata(table, axis=1)
  182. >>> ranks
  183. array([[1.5, 3. , 1.5],
  184. [1.5, 1.5, 3. ],
  185. [1.5, 1.5, 3. ],
  186. [1. , 3. , 2. ],
  187. [1.5, 3. , 1.5],
  188. [1. , 2. , 3. ],
  189. [1. , 2. , 3. ],
  190. [1. , 2.5, 2.5],
  191. [1. , 2. , 3. ],
  192. [1. , 2. , 3. ]])
  193. We add the ranks within each column, multiply the sums by the
  194. predicted ranks, and sum the products.
  195. >>> import numpy as np
  196. >>> m, n = ranks.shape
  197. >>> predicted_ranks = np.arange(1, n+1)
  198. >>> L = (predicted_ranks * np.sum(ranks, axis=0)).sum()
  199. >>> res.statistic == L
  200. True
  201. As presented in [3]_, the asymptotic approximation of the *p*-value is the
  202. survival function of the normal distribution evaluated at the standardized
  203. test statistic:
  204. >>> from scipy.stats import norm
  205. >>> E0 = (m*n*(n+1)**2)/4
  206. >>> V0 = (m*n**2*(n+1)*(n**2-1))/144
  207. >>> Lambda = (L-E0)/np.sqrt(V0)
  208. >>> p = norm.sf(Lambda)
  209. >>> p
  210. 0.0012693433690751756
  211. This does not precisely match the *p*-value reported by `page_trend_test`
  212. above. The asymptotic distribution is not very accurate, nor conservative,
  213. for :math:`m \leq 12` and :math:`n \leq 8`, so `page_trend_test` chose to
  214. use ``method='exact'`` based on the dimensions of the table and the
  215. recommendations in Page's original paper [1]_. To override
  216. `page_trend_test`'s choice, provide the `method` argument.
  217. >>> res = page_trend_test(table, method="asymptotic")
  218. >>> res
  219. PageTrendTestResult(statistic=133.5, pvalue=0.0012693433690751756,
  220. method='asymptotic')
  221. If the data are already ranked, we can pass in the ``ranks`` instead of
  222. the ``table`` to save computation time.
  223. >>> res = page_trend_test(ranks, # ranks of data
  224. ... ranked=True, # data is already ranked
  225. ... )
  226. >>> res
  227. PageTrendTestResult(statistic=133.5, pvalue=0.0018191161948127822,
  228. method='exact')
  229. Suppose the raw data had been tabulated in an order different from the
  230. order of predicted means, say lecture, seminar, tutorial.
  231. >>> table = np.asarray(table)[:, [1, 2, 0]]
  232. Since the arrangement of this table is not consistent with the assumed
  233. ordering, we can either rearrange the table or provide the
  234. `predicted_ranks`. Remembering that the lecture is predicted
  235. to have the middle rank, the seminar the highest, and tutorial the lowest,
  236. we pass:
  237. >>> res = page_trend_test(table, # data as originally tabulated
  238. ... predicted_ranks=[2, 3, 1], # our predicted order
  239. ... )
  240. >>> res
  241. PageTrendTestResult(statistic=133.5, pvalue=0.0018191161948127822,
  242. method='exact')
  243. """
  244. # Possible values of the method parameter and the corresponding function
  245. # used to evaluate the p value
  246. methods = {"asymptotic": _l_p_asymptotic,
  247. "exact": _l_p_exact,
  248. "auto": None}
  249. if method not in methods:
  250. raise ValueError(f"`method` must be in {set(methods)}")
  251. ranks = np.array(data, copy=False)
  252. if ranks.ndim != 2: # TODO: relax this to accept 3d arrays?
  253. raise ValueError("`data` must be a 2d array.")
  254. m, n = ranks.shape
  255. if m < 2 or n < 3:
  256. raise ValueError("Page's L is only appropriate for data with two "
  257. "or more rows and three or more columns.")
  258. if np.any(np.isnan(data)):
  259. raise ValueError("`data` contains NaNs, which cannot be ranked "
  260. "meaningfully")
  261. # ensure NumPy array and rank the data if it's not already ranked
  262. if ranked:
  263. # Only a basic check on whether data is ranked. Checking that the data
  264. # is properly ranked could take as much time as ranking it.
  265. if not (ranks.min() >= 1 and ranks.max() <= ranks.shape[1]):
  266. raise ValueError("`data` is not properly ranked. Rank the data or "
  267. "pass `ranked=False`.")
  268. else:
  269. ranks = scipy.stats.rankdata(data, axis=-1)
  270. # generate predicted ranks if not provided, ensure valid NumPy array
  271. if predicted_ranks is None:
  272. predicted_ranks = np.arange(1, n+1)
  273. else:
  274. predicted_ranks = np.array(predicted_ranks, copy=False)
  275. if (predicted_ranks.ndim < 1 or
  276. (set(predicted_ranks) != set(range(1, n+1)) or
  277. len(predicted_ranks) != n)):
  278. raise ValueError(f"`predicted_ranks` must include each integer "
  279. f"from 1 to {n} (the number of columns in "
  280. f"`data`) exactly once.")
  281. if type(ranked) is not bool:
  282. raise TypeError("`ranked` must be boolean.")
  283. # Calculate the L statistic
  284. L = _l_vectorized(ranks, predicted_ranks)
  285. # Calculate the p-value
  286. if method == "auto":
  287. method = _choose_method(ranks)
  288. p_fun = methods[method] # get the function corresponding with the method
  289. p = p_fun(L, m, n)
  290. page_result = PageTrendTestResult(statistic=L, pvalue=p, method=method)
  291. return page_result
  292. def _choose_method(ranks):
  293. '''Choose method for computing p-value automatically'''
  294. m, n = ranks.shape
  295. if n > 8 or (m > 12 and n > 3) or m > 20: # as in [1], [4]
  296. method = "asymptotic"
  297. else:
  298. method = "exact"
  299. return method
  300. def _l_vectorized(ranks, predicted_ranks):
  301. '''Calculate's Page's L statistic for each page of a 3d array'''
  302. colsums = ranks.sum(axis=-2, keepdims=True)
  303. products = predicted_ranks * colsums
  304. Ls = products.sum(axis=-1)
  305. Ls = Ls[0] if Ls.size == 1 else Ls.ravel()
  306. return Ls
  307. def _l_p_asymptotic(L, m, n):
  308. '''Calculate the p-value of Page's L from the asymptotic distribution'''
  309. # Using [1] as a reference, the asymptotic p-value would be calculated as:
  310. # chi_L = (12*L - 3*m*n*(n+1)**2)**2/(m*n**2*(n**2-1)*(n+1))
  311. # p = chi2.sf(chi_L, df=1, loc=0, scale=1)/2
  312. # but this is insentive to the direction of the hypothesized ranking
  313. # See [2] page 151
  314. E0 = (m*n*(n+1)**2)/4
  315. V0 = (m*n**2*(n+1)*(n**2-1))/144
  316. Lambda = (L-E0)/np.sqrt(V0)
  317. # This is a one-sided "greater" test - calculate the probability that the
  318. # L statistic under H0 would be greater than the observed L statistic
  319. p = norm.sf(Lambda)
  320. return p
  321. def _l_p_exact(L, m, n):
  322. '''Calculate the p-value of Page's L exactly'''
  323. # [1] uses m, n; [5] uses n, k.
  324. # Switch convention here because exact calculation code references [5].
  325. L, n, k = int(L), int(m), int(n)
  326. _pagel_state.set_k(k)
  327. return _pagel_state.sf(L, n)
  328. class _PageL:
  329. '''Maintains state between `page_trend_test` executions'''
  330. def __init__(self):
  331. '''Lightweight initialization'''
  332. self.all_pmfs = {}
  333. def set_k(self, k):
  334. '''Calculate lower and upper limits of L for single row'''
  335. self.k = k
  336. # See [5] top of page 52
  337. self.a, self.b = (k*(k+1)*(k+2))//6, (k*(k+1)*(2*k+1))//6
  338. def sf(self, l, n):
  339. '''Survival function of Page's L statistic'''
  340. ps = [self.pmf(l, n) for l in range(l, n*self.b + 1)]
  341. return np.sum(ps)
  342. def p_l_k_1(self):
  343. '''Relative frequency of each L value over all possible single rows'''
  344. # See [5] Equation (6)
  345. ranks = range(1, self.k+1)
  346. # generate all possible rows of length k
  347. rank_perms = np.array(list(permutations(ranks)))
  348. # compute Page's L for all possible rows
  349. Ls = (ranks*rank_perms).sum(axis=1)
  350. # count occurences of each L value
  351. counts = np.histogram(Ls, np.arange(self.a-0.5, self.b+1.5))[0]
  352. # factorial(k) is number of possible permutations
  353. return counts/math.factorial(self.k)
  354. def pmf(self, l, n):
  355. '''Recursive function to evaluate p(l, k, n); see [5] Equation 1'''
  356. if n not in self.all_pmfs:
  357. self.all_pmfs[n] = {}
  358. if self.k not in self.all_pmfs[n]:
  359. self.all_pmfs[n][self.k] = {}
  360. # Cache results to avoid repeating calculation. Initially this was
  361. # written with lru_cache, but this seems faster? Also, we could add
  362. # an option to save this for future lookup.
  363. if l in self.all_pmfs[n][self.k]:
  364. return self.all_pmfs[n][self.k][l]
  365. if n == 1:
  366. ps = self.p_l_k_1() # [5] Equation 6
  367. ls = range(self.a, self.b+1)
  368. # not fast, but we'll only be here once
  369. self.all_pmfs[n][self.k] = {l: p for l, p in zip(ls, ps)}
  370. return self.all_pmfs[n][self.k][l]
  371. p = 0
  372. low = max(l-(n-1)*self.b, self.a) # [5] Equation 2
  373. high = min(l-(n-1)*self.a, self.b)
  374. # [5] Equation 1
  375. for t in range(low, high+1):
  376. p1 = self.pmf(l-t, n-1)
  377. p2 = self.pmf(t, 1)
  378. p += p1*p2
  379. self.all_pmfs[n][self.k][l] = p
  380. return p
  381. # Maintain state for faster repeat calls to page_trend_test w/ method='exact'
  382. _pagel_state = _PageL()