quantile.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. // from https://github.com/simple-statistics
  2. /**
  3. * This is the internal implementation of quantiles: when you know
  4. * that the order is sorted, you don't need to re-sort it, and the computations
  5. * are faster.
  6. *
  7. * @param {Array<number>} x sample of one or more data points
  8. * @param {number} p desired quantile: a number between 0 to 1, inclusive
  9. * @returns {number} quantile value
  10. * @throws {Error} if p ix outside of the range from 0 to 1
  11. * @throws {Error} if x is empty
  12. * @example
  13. * quantileSorted([3, 6, 7, 8, 8, 9, 10, 13, 15, 16, 20], 0.5); // => 9
  14. */
  15. export function quantileSorted(x, p) {
  16. var idx = x.length * p;
  17. if (x.length === 0) {
  18. throw new Error('quantile requires at least one data point.');
  19. }
  20. else if (p < 0 || p > 1) {
  21. throw new Error('quantiles must be between 0 and 1');
  22. }
  23. else if (p === 1) {
  24. // If p is 1, directly return the last element
  25. return x[x.length - 1];
  26. }
  27. else if (p === 0) {
  28. // If p is 0, directly return the first element
  29. return x[0];
  30. }
  31. else if (idx % 1 !== 0) {
  32. // If p is not integer, return the next element in array
  33. return x[Math.ceil(idx) - 1];
  34. }
  35. else if (x.length % 2 === 0) {
  36. // If the list has even-length, we'll take the average of this number
  37. // and the next value, if there is one
  38. return (x[idx - 1] + x[idx]) / 2;
  39. }
  40. else {
  41. // Finally, in the simple case of an integer value
  42. // with an odd-length list, return the x value at the index.
  43. return x[idx];
  44. }
  45. }
  46. /**
  47. * 交换数组位置
  48. * @param arr T[]
  49. * @param i number
  50. * @param j number
  51. */
  52. export function swap(arr, i, j) {
  53. var tmp = arr[i];
  54. arr[i] = arr[j];
  55. arr[j] = tmp;
  56. }
  57. /**
  58. * Rearrange items in `arr` so that all items in `[left, k]` range are the smallest.
  59. * The `k`-th element will have the `(k - left + 1)`-th smallest value in `[left, right]`.
  60. *
  61. * Implements Floyd-Rivest selection algorithm https://en.wikipedia.org/wiki/Floyd-Rivest_algorithm
  62. *
  63. * @param {Array<number>} arr input array
  64. * @param {number} k pivot index
  65. * @param {number} [left] left index
  66. * @param {number} [right] right index
  67. * @returns {void} mutates input array
  68. * @example
  69. * var arr = [65, 28, 59, 33, 21, 56, 22, 95, 50, 12, 90, 53, 28, 77, 39];
  70. * quickselect(arr, 8);
  71. * // = [39, 28, 28, 33, 21, 12, 22, 50, 53, 56, 59, 65, 90, 77, 95]
  72. */
  73. export function quickselect(arr, k, left, right) {
  74. left = left || 0;
  75. right = right || arr.length - 1;
  76. while (right > left) {
  77. // 600 and 0.5 are arbitrary constants chosen in the original paper to minimize execution time
  78. if (right - left > 600) {
  79. var n = right - left + 1;
  80. var m = k - left + 1;
  81. var z = Math.log(n);
  82. var s = 0.5 * Math.exp((2 * z) / 3);
  83. var sd = 0.5 * Math.sqrt((z * s * (n - s)) / n);
  84. if (m - n / 2 < 0)
  85. sd *= -1;
  86. var newLeft = Math.max(left, Math.floor(k - (m * s) / n + sd));
  87. var newRight = Math.min(right, Math.floor(k + ((n - m) * s) / n + sd));
  88. quickselect(arr, k, newLeft, newRight);
  89. }
  90. var t = arr[k];
  91. var i = left;
  92. var j = right;
  93. swap(arr, left, k);
  94. if (arr[right] > t)
  95. swap(arr, left, right);
  96. while (i < j) {
  97. swap(arr, i, j);
  98. i++;
  99. j--;
  100. while (arr[i] < t)
  101. i++;
  102. while (arr[j] > t)
  103. j--;
  104. }
  105. if (arr[left] === t)
  106. swap(arr, left, j);
  107. else {
  108. j++;
  109. swap(arr, j, right);
  110. }
  111. if (j <= k)
  112. left = j + 1;
  113. if (k <= j)
  114. right = j - 1;
  115. }
  116. }
  117. function quantile(x, p) {
  118. var copy = x.slice();
  119. if (Array.isArray(p)) {
  120. // rearrange elements so that each element corresponding to a requested
  121. // quantile is on a place it would be if the array was fully sorted
  122. multiQuantileSelect(copy, p);
  123. // Initialize the result array
  124. var results = [];
  125. // For each requested quantile
  126. for (var i = 0; i < p.length; i++) {
  127. results[i] = quantileSorted(copy, p[i]);
  128. }
  129. return results;
  130. }
  131. else {
  132. var idx = quantileIndex(copy.length, p);
  133. quantileSelect(copy, idx, 0, copy.length - 1);
  134. return quantileSorted(copy, p);
  135. }
  136. }
  137. function quantileSelect(arr, k, left, right) {
  138. if (k % 1 === 0) {
  139. quickselect(arr, k, left, right);
  140. }
  141. else {
  142. k = Math.floor(k);
  143. quickselect(arr, k, left, right);
  144. quickselect(arr, k + 1, k + 1, right);
  145. }
  146. }
  147. function multiQuantileSelect(arr, p) {
  148. var indices = [0];
  149. for (var i = 0; i < p.length; i++) {
  150. indices.push(quantileIndex(arr.length, p[i]));
  151. }
  152. indices.push(arr.length - 1);
  153. indices.sort(compare);
  154. var stack = [0, indices.length - 1];
  155. while (stack.length) {
  156. var r = Math.ceil(stack.pop());
  157. var l = Math.floor(stack.pop());
  158. if (r - l <= 1)
  159. continue;
  160. var m = Math.floor((l + r) / 2);
  161. quantileSelect(arr, indices[m], Math.floor(indices[l]), Math.ceil(indices[r]));
  162. stack.push(l, m, m, r);
  163. }
  164. }
  165. function compare(a, b) {
  166. return a - b;
  167. }
  168. function quantileIndex(len, p) {
  169. var idx = len * p;
  170. if (p === 1) {
  171. // If p is 1, directly return the last index
  172. return len - 1;
  173. }
  174. else if (p === 0) {
  175. // If p is 0, directly return the first index
  176. return 0;
  177. }
  178. else if (idx % 1 !== 0) {
  179. // If index is not integer, return the next index in array
  180. return Math.ceil(idx) - 1;
  181. }
  182. else if (len % 2 === 0) {
  183. // If the list has even-length, we'll return the middle of two indices
  184. // around quantile to indicate that we need an average value of the two
  185. return idx - 0.5;
  186. }
  187. else {
  188. // Finally, in the simple case of an integer index
  189. // with an odd-length list, return the index
  190. return idx;
  191. }
  192. }
  193. export { quantile };
  194. //# sourceMappingURL=quantile.js.map