Repository navigation
Expand file tree
/
Copy path_stats_py.py
More file actions
10840 lines (8820 loc) · 409 KB
/
Copy path_stats_py.py
File metadata and controls
10840 lines (8820 loc) · 409 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2002 Gary Strangman. All rights reserved
# Copyright 2002-2016 The SciPy Developers
#
# The original code from Gary Strangman was heavily adapted for
# use in SciPy by Travis Oliphant. The original code came with the
# following disclaimer:
#
# This software is provided "as-is". There are no expressed or implied
# warranties of any kind, including, but not limited to, the warranties
# of merchantability and fitness for a given application. In no event
# shall Gary Strangman be liable for any direct, indirect, incidental,
# special, exemplary or consequential damages (including, but not limited
# to, loss of use, data or profits, or business interruption) however
# caused and on any theory of liability, whether in contract, strict
# liability or tort (including negligence or otherwise) arising in any way
# out of the use of this software, even if advised of the possibility of
# such damage.
"""
A collection of basic statistical functions for Python.
References
----------
.. [CRCProbStat2000] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
Probability and Statistics Tables and Formulae. Chapman & Hall: New
York. 2000.
"""
import math
import itertools
import operator
import warnings
from collections import namedtuple
from collections.abc import Sequence
import numpy as np
from numpy import array, asarray, ma
from scipy import sparse
from scipy.spatial import distance_matrix
from scipy.optimize import milp, LinearConstraint
from scipy._lib._util import _get_nan, _rename_parameter, _contains_nan, np_vecdot
import scipy.special as special
# Import unused here but needs to stay until end of deprecation periode
# See https://github.com/scipy/scipy/issues/15765#issuecomment-1875564522
from scipy import linalg # noqa: F401
from . import distributions
from . import _mstats_basic as mstats_basic
from ._stats_mstats_common import theilslopes, siegelslopes
from ._stats import _kendall_dis, _toint64, _weightedrankedtau
from dataclasses import dataclass, field
from ._stats_pythran import _compute_outer_prob_inside_method
from ._resampling import (MonteCarloMethod, PermutationMethod, BootstrapMethod,
monte_carlo_test, permutation_test, bootstrap,)
from ._axis_nan_policy import (_axis_nan_policy_factory, _broadcast_shapes,
_broadcast_array_shapes_remove_axis, SmallSampleWarning,
too_small_1d_not_omit, too_small_1d_omit,
too_small_nd_not_omit, too_small_nd_omit)
from ._binomtest import _binary_search_for_binom_tst as _binary_search
from scipy._lib._bunch import _make_tuple_bunch
from scipy import stats
from scipy.optimize import root_scalar
from scipy._lib._array_api import (
_asarray,
array_namespace,
is_lazy_array,
is_dask,
is_numpy,
is_cupy,
is_marray,
xp_size,
xp_vector_norm,
xp_promote,
xp_result_type,
xp_capabilities,
xp_ravel,
_length_nonmasked,
_share_masks,
xp_swapaxes,
xp_default_dtype,
xp_device,
)
import scipy._lib.array_api_extra as xpx
# Functions/classes in other files should be added in `__init__.py`, not here
__all__ = ['gmean', 'hmean', 'pmean', 'mode', 'tmean', 'tvar',
'tmin', 'tmax', 'tstd', 'tsem', 'moment',
'skew', 'kurtosis', 'describe', 'skewtest', 'kurtosistest',
'normaltest', 'jarque_bera',
'scoreatpercentile', 'percentileofscore',
'cumfreq', 'relfreq', 'obrientransform',
'sem', 'zmap', 'zscore', 'gzscore', 'iqr', 'gstd',
'median_abs_deviation',
'sigmaclip', 'trimboth', 'trim1', 'trim_mean',
'f_oneway', 'pearsonr', 'fisher_exact',
'spearmanr', 'pointbiserialr',
'kendalltau', 'weightedtau',
'linregress', 'siegelslopes', 'theilslopes', 'ttest_1samp',
'ttest_ind', 'ttest_ind_from_stats', 'ttest_rel',
'kstest', 'ks_1samp', 'ks_2samp',
'chisquare', 'power_divergence',
'tiecorrect', 'ranksums', 'kruskal', 'friedmanchisquare',
'rankdata', 'combine_pvalues', 'quantile_test',
'wasserstein_distance', 'wasserstein_distance_nd', 'energy_distance',
'brunnermunzel', 'alexandergovern',
'expectile', 'lmoment']
def _chk_asarray(a, axis, *, xp=None):
if xp is None:
xp = array_namespace(a)
if axis is None:
a = xp.reshape(a, (-1,))
outaxis = 0
else:
a = xp.asarray(a)
outaxis = axis
if a.ndim == 0:
a = xp.reshape(a, (-1,))
return a, outaxis
SignificanceResult = _make_tuple_bunch('SignificanceResult',
['statistic', 'pvalue'], [])
# Let's call a SignificanceResult with legacy :correlation" attribute a
# "CorrelationResult". Don't add to `extra_field_names`- shouldn't be in repr.
def _pack_CorrelationResult(statistic, pvalue, correlation):
res = SignificanceResult(statistic, pvalue)
res.correlation = correlation
return res
def _unpack_CorrelationResult(res, _):
return res.statistic, res.pvalue, res.correlation
# note that `weights` are paired with `x`
@xp_capabilities()
@_axis_nan_policy_factory(
lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True,
result_to_tuple=lambda x, _: (x,), kwd_samples=['weights'])
def gmean(a, axis=0, dtype=None, weights=None):
r"""Compute the weighted geometric mean along the specified axis.
The weighted geometric mean of the array :math:`a_i` associated to weights
:math:`w_i` is:
.. math::
\exp \left( \frac{ \sum_{i=1}^n w_i \ln a_i }{ \sum_{i=1}^n w_i }
\right) \, ,
and, with equal weights, it gives:
.. math::
\sqrt[n]{ \prod_{i=1}^n a_i } \, .
Parameters
----------
a : array_like
Input array or object that can be converted to an array.
axis : int or None, optional
Axis along which the geometric mean is computed. Default is 0.
If None, compute over the whole array `a`.
dtype : dtype, optional
Type to which the input arrays are cast before the calculation is
performed.
weights : array_like, optional
The `weights` array must be broadcastable to the same shape as `a`.
Default is None, which gives each value a weight of 1.0.
Returns
-------
gmean : ndarray
See `dtype` parameter above.
See Also
--------
numpy.mean : Arithmetic average
numpy.average : Weighted average
hmean : Harmonic mean
Notes
-----
The sample geometric mean is the exponential of the mean of the natural
logarithms of the observations.
Negative observations will produce NaNs in the output because the *natural*
logarithm (as opposed to the *complex* logarithm) is defined only for
non-negative reals.
References
----------
.. [1] "Weighted Geometric Mean", *Wikipedia*,
https://en.wikipedia.org/wiki/Weighted_geometric_mean.
.. [2] Grossman, J., Grossman, M., Katz, R., "Averages: A New Approach",
Archimedes Foundation, 1983
Examples
--------
>>> from scipy.stats import gmean
>>> gmean([1, 4])
2.0
>>> gmean([1, 2, 3, 4, 5, 6, 7])
3.3800151591412964
>>> gmean([1, 4, 7], weights=[3, 1, 3])
2.80668351922014
"""
xp = array_namespace(a, weights)
a = xp.asarray(a, dtype=dtype)
if weights is not None:
weights = xp.asarray(weights, dtype=dtype)
with np.errstate(divide='ignore'):
log_a = xp.log(a)
return xp.exp(_xp_mean(log_a, axis=axis, weights=weights))
@xp_capabilities(jax_jit=False, allow_dask_compute=1)
@_axis_nan_policy_factory(
lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True,
result_to_tuple=lambda x, _: (x,), kwd_samples=['weights'])
def hmean(a, axis=0, dtype=None, *, weights=None):
r"""Calculate the weighted harmonic mean along the specified axis.
The weighted harmonic mean of the array :math:`a_i` associated to weights
:math:`w_i` is:
.. math::
\frac{ \sum_{i=1}^n w_i }{ \sum_{i=1}^n \frac{w_i}{a_i} } \, ,
and, with equal weights, it gives:
.. math::
\frac{ n }{ \sum_{i=1}^n \frac{1}{a_i} } \, .
Parameters
----------
a : array_like
Input array, masked array or object that can be converted to an array.
axis : int or None, optional
Axis along which the harmonic mean is computed. Default is 0.
If None, compute over the whole array `a`.
dtype : dtype, optional
Type of the returned array and of the accumulator in which the
elements are summed. If `dtype` is not specified, it defaults to the
dtype of `a`, unless `a` has an integer `dtype` with a precision less
than that of the default platform integer. In that case, the default
platform integer is used.
weights : array_like, optional
The weights array can either be 1-D (in which case its length must be
the size of `a` along the given `axis`) or of the same shape as `a`.
Default is None, which gives each value a weight of 1.0.
.. versionadded:: 1.9
Returns
-------
hmean : ndarray
See `dtype` parameter above.
See Also
--------
numpy.mean : Arithmetic average
numpy.average : Weighted average
gmean : Geometric mean
Notes
-----
The sample harmonic mean is the reciprocal of the mean of the reciprocals
of the observations.
The harmonic mean is computed over a single dimension of the input
array, axis=0 by default, or all values in the array if axis=None.
float64 intermediate and return values are used for integer inputs.
The harmonic mean is only defined if all observations are non-negative;
otherwise, the result is NaN.
References
----------
.. [1] "Weighted Harmonic Mean", *Wikipedia*,
https://en.wikipedia.org/wiki/Harmonic_mean#Weighted_harmonic_mean
.. [2] Ferger, F., "The nature and use of the harmonic mean", Journal of
the American Statistical Association, vol. 26, pp. 36-40, 1931
Examples
--------
>>> from scipy.stats import hmean
>>> hmean([1, 4])
1.6000000000000001
>>> hmean([1, 2, 3, 4, 5, 6, 7])
2.6997245179063363
>>> hmean([1, 4, 7], weights=[3, 1, 3])
1.9029126213592233
"""
xp = array_namespace(a, weights)
a = xp.asarray(a, dtype=dtype)
if weights is not None:
weights = xp.asarray(weights, dtype=dtype)
negative_mask = a < 0
if xp.any(negative_mask):
# `where` avoids having to be careful about dtypes and will work with
# JAX. This is the exceptional case, so it's OK to be a little slower.
# Won't work for array_api_strict for now, but see data-apis/array-api#807
a = xp.where(negative_mask, xp.nan, a)
message = ("The harmonic mean is only defined if all elements are "
"non-negative; otherwise, the result is NaN.")
warnings.warn(message, RuntimeWarning, stacklevel=2)
with np.errstate(divide='ignore'):
return 1.0 / _xp_mean(1.0 / a, axis=axis, weights=weights)
@xp_capabilities(jax_jit=False, allow_dask_compute=1)
@_axis_nan_policy_factory(
lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True,
result_to_tuple=lambda x, _: (x,), kwd_samples=['weights'])
def pmean(a, p, *, axis=0, dtype=None, weights=None):
r"""Calculate the weighted power mean along the specified axis.
The weighted power mean of the array :math:`a_i` associated to weights
:math:`w_i` is:
.. math::
\left( \frac{ \sum_{i=1}^n w_i a_i^p }{ \sum_{i=1}^n w_i }
\right)^{ 1 / p } \, ,
and, with equal weights, it gives:
.. math::
\left( \frac{ 1 }{ n } \sum_{i=1}^n a_i^p \right)^{ 1 / p } \, .
When ``p=0``, it returns the geometric mean.
This mean is also called generalized mean or Hölder mean, and must not be
confused with the Kolmogorov generalized mean, also called
quasi-arithmetic mean or generalized f-mean [3]_.
Parameters
----------
a : array_like
Input array, masked array or object that can be converted to an array.
p : int or float
Exponent. Must be finite.
axis : int or None, optional
Axis along which the power mean is computed. Default is 0.
If None, compute over the whole array `a`.
dtype : dtype, optional
Type of the returned array and of the accumulator in which the
elements are summed. If `dtype` is not specified, it defaults to the
dtype of `a`, unless `a` has an integer `dtype` with a precision less
than that of the default platform integer. In that case, the default
platform integer is used.
weights : array_like, optional
The weights array can either be 1-D (in which case its length must be
the size of `a` along the given `axis`) or of the same shape as `a`.
Default is None, which gives each value a weight of 1.0.
Returns
-------
pmean : ndarray, see `dtype` parameter above.
Output array containing the power mean values.
See Also
--------
numpy.average : Weighted average
gmean : Geometric mean
hmean : Harmonic mean
Notes
-----
The power mean is computed over a single dimension of the input
array, ``axis=0`` by default, or all values in the array if ``axis=None``.
float64 intermediate and return values are used for integer inputs.
The power mean is only defined if all observations are non-negative;
otherwise, the result is NaN.
.. versionadded:: 1.9
References
----------
.. [1] "Generalized Mean", *Wikipedia*,
https://en.wikipedia.org/wiki/Generalized_mean
.. [2] Norris, N., "Convexity properties of generalized mean value
functions", The Annals of Mathematical Statistics, vol. 8,
pp. 118-120, 1937
.. [3] Bullen, P.S., Handbook of Means and Their Inequalities, 2003
Examples
--------
>>> from scipy.stats import pmean, hmean, gmean
>>> pmean([1, 4], 1.3)
2.639372938300652
>>> pmean([1, 2, 3, 4, 5, 6, 7], 1.3)
4.157111214492084
>>> pmean([1, 4, 7], -2, weights=[3, 1, 3])
1.4969684896631954
For p=-1, power mean is equal to harmonic mean:
>>> pmean([1, 4, 7], -1, weights=[3, 1, 3])
1.9029126213592233
>>> hmean([1, 4, 7], weights=[3, 1, 3])
1.9029126213592233
For p=0, power mean is defined as the geometric mean:
>>> pmean([1, 4, 7], 0, weights=[3, 1, 3])
2.80668351922014
>>> gmean([1, 4, 7], weights=[3, 1, 3])
2.80668351922014
"""
if not isinstance(p, int | float):
raise ValueError("Power mean only defined for exponent of type int or "
"float.")
if p == 0:
return gmean(a, axis=axis, dtype=dtype, weights=weights)
elif math.isinf(p):
message = "Power mean only implemented for finite `p`"
raise NotImplementedError(message)
xp = array_namespace(a, weights)
a = xp.asarray(a, dtype=dtype)
if weights is not None:
weights = xp.asarray(weights, dtype=dtype)
negative_mask = a < 0
if xp.any(negative_mask):
# `where` avoids having to be careful about dtypes and will work with
# JAX. This is the exceptional case, so it's OK to be a little slower.
# Won't work for array_api_strict for now, but see data-apis/array-api#807
a = xp.where(negative_mask, np.nan, a)
message = ("The power mean is only defined if all elements are "
"non-negative; otherwise, the result is NaN.")
warnings.warn(message, RuntimeWarning, stacklevel=2)
with np.errstate(divide='ignore', invalid='ignore'):
return _xp_mean(a**float(p), axis=axis, weights=weights)**(1/p)
ModeResult = namedtuple('ModeResult', ('mode', 'count'))
def _mode_result(mode, count):
# When a slice is empty, `_axis_nan_policy` automatically produces
# NaN for `mode` and `count`. This is a reasonable convention for `mode`,
# but `count` should not be NaN; it should be zero.
xp = array_namespace(mode, count)
i = xp.isnan(count)
if i.shape == ():
count = xp.asarray(0, dtype=count.dtype)[()] if i else count
else:
count = xpx.at(count)[i].set(0)
return ModeResult(mode, count)
@xp_capabilities(skip_backends=[('dask.array', "can't compute chunk size"),
('jax.numpy', "relies on _axis_nan_policy"),
('cupy', "data-apis/array-api-compat#312")])
@_axis_nan_policy_factory(_mode_result, override={'nan_propagation': False})
def mode(a, axis=0, nan_policy='propagate', keepdims=False):
r"""Return an array of the modal (most common) value in the passed array.
If there is more than one such value, only one is returned.
The bin-count for the modal bins is also returned.
Parameters
----------
a : array_like
Numeric, n-dimensional array of which to find mode(s).
axis : int or None, optional
Axis along which to operate. Default is 0. If None, compute over
the whole array `a`.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': treats nan as it would treat any other value
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
keepdims : bool, optional
If set to ``False``, the `axis` over which the statistic is taken
is consumed (eliminated from the output array). If set to ``True``,
the `axis` is retained with size one, and the result will broadcast
correctly against the input array.
Returns
-------
mode : ndarray
Array of modal values.
count : ndarray
Array of counts for each mode.
Notes
-----
The mode is calculated using `numpy.unique`.
In NumPy versions 1.21 and after, all NaNs - even those with different
binary representations - are treated as equivalent and counted as separate
instances of the same value.
By convention, the mode of an empty array is NaN, and the associated count
is zero.
Examples
--------
>>> import numpy as np
>>> a = np.array([[3, 0, 3, 7],
... [3, 2, 6, 2],
... [1, 7, 2, 8],
... [3, 0, 6, 1],
... [3, 2, 5, 5]])
>>> from scipy import stats
>>> stats.mode(a, keepdims=True)
ModeResult(mode=array([[3, 0, 6, 1]]), count=array([[4, 2, 2, 1]]))
To get mode of whole array, specify ``axis=None``:
>>> stats.mode(a, axis=None, keepdims=True)
ModeResult(mode=[[3]], count=[[5]])
>>> stats.mode(a, axis=None, keepdims=False)
ModeResult(mode=3, count=5)
"""
xp = array_namespace(a)
# `axis`, `nan_policy`, and `keepdims` are handled by `_axis_nan_policy`
if not xp.isdtype(a.dtype, 'numeric'):
message = ("Argument `a` is not recognized as numeric. "
"Support for input that cannot be coerced to a numeric "
"array was deprecated in SciPy 1.9.0 and removed in SciPy "
"1.11.0. Please consider `np.unique`.")
raise TypeError(message)
if xp_size(a) == 0:
NaN = _get_nan(a, xp=xp)
return ModeResult(*xp.asarray([NaN, 0], dtype=NaN.dtype))
if a.ndim == 1:
vals, cnts = xp.unique_counts(a)
# in contrast with np.unique, `unique_counts` treats all NaNs as distinct,
# but we have always grouped them. Replace `cnts` corresponding with NaNs
# with the number of NaNs.
mask = xp.isnan(vals)
cnts = xpx.at(cnts)[mask].set(xp.count_nonzero(mask))
modes, counts = vals[xp.argmax(cnts)], xp.max(cnts)
default_int = xp.asarray(1).dtype # fail slow CI job failed - incorrect dtype
counts = xp.astype(counts, default_int, copy=False)
modes = modes[()] if modes.ndim == 0 else modes
counts = counts[()] if counts.ndim == 0 else counts
return ModeResult(modes, counts)
# `axis` is always -1 after the `_axis_nan_policy` decorator
y = xp.sort(a, axis=-1)
# Get boolean array of elements that are different from the previous element
i = xp.concat([xp.ones(y.shape[:-1] + (1,), dtype=xp.bool),
(y[..., :-1] != y[..., 1:]) & ~xp.isnan(y[..., :-1])], axis=-1)
# Get linear integer indices of these elements in a raveled array
indices = xp.arange(xp_size(y), device=xp_device(y))[xp_ravel(i)]
# The difference between integer indices is the number of repeats
append = xp.full(indices.shape[:-1] + (1,), xp_size(y), dtype=indices.dtype)
counts = xp.diff(indices, append=append)
# Now we form an array of `counts` corresponding with each element of `y`...
counts = xp.reshape(xp.repeat(counts, counts), y.shape)
# ... so we can get the argmax of *each slice* separately.
k = xp.argmax(counts, axis=-1, keepdims=True)
# Extract the corresponding element/count, and eliminate the reduced dimension
modes = xp.take_along_axis(y, k, axis=-1)[..., 0]
counts = xp.take_along_axis(counts, k, axis=-1)[..., 0]
modes = modes[()] if modes.ndim == 0 else modes
counts = counts[()] if counts.ndim == 0 else counts
return ModeResult(modes, counts)
def _put_val_to_limits(a, limits, inclusive, val=np.nan, xp=None):
"""Replace elements outside limits with a value.
This is primarily a utility function.
Parameters
----------
a : array
limits : (float or None, float or None)
A tuple consisting of the (lower limit, upper limit). Elements in the
input array less than the lower limit or greater than the upper limit
will be replaced with `val`. None implies no limit.
inclusive : (bool, bool)
A tuple consisting of the (lower flag, upper flag). These flags
determine whether values exactly equal to lower or upper are allowed.
val : float, default: NaN
The value with which extreme elements of the array are replaced.
"""
xp = array_namespace(a) if xp is None else xp
mask = xp.zeros_like(a, dtype=xp.bool)
if limits is None:
return a, mask
lower_limit, upper_limit = limits
lower_include, upper_include = inclusive
if lower_limit is not None:
mask = mask | ((a < lower_limit) if lower_include else a <= lower_limit)
if upper_limit is not None:
mask = mask | ((a > upper_limit) if upper_include else a >= upper_limit)
lazy = is_lazy_array(mask)
if not lazy and xp.all(mask):
raise ValueError("No array values within given limits")
if lazy or xp.any(mask):
a = xp.where(mask, val, a)
return a, mask
@xp_capabilities()
@_axis_nan_policy_factory(
lambda x: x, n_outputs=1, default_axis=None,
result_to_tuple=lambda x, _: (x,)
)
def tmean(a, limits=None, inclusive=(True, True), axis=None):
"""Compute the trimmed mean.
This function finds the arithmetic mean of given values, ignoring values
outside the given `limits`.
Parameters
----------
a : array_like
Array of values.
limits : None or (lower limit, upper limit), optional
Values in the input array less than the lower limit or greater than the
upper limit will be ignored. When limits is None (default), then all
values are used. Either of the limit values in the tuple can also be
None representing a half-open interval.
inclusive : (bool, bool), optional
A tuple consisting of the (lower flag, upper flag). These flags
determine whether values exactly equal to the lower or upper limits
are included. The default value is (True, True).
axis : int or None, optional
Axis along which to compute test. Default is None.
Returns
-------
tmean : ndarray
Trimmed mean.
See Also
--------
trim_mean : Returns mean after trimming a proportion from both tails.
Examples
--------
>>> import numpy as np
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.tmean(x)
9.5
>>> stats.tmean(x, (3,17))
10.0
"""
xp = array_namespace(a)
a, mask = _put_val_to_limits(a, limits, inclusive, val=0., xp=xp)
# explicit dtype specification required due to data-apis/array-api-compat#152
sum = xp.sum(a, axis=axis, dtype=a.dtype)
n = xp.sum(xp.asarray(~mask, dtype=a.dtype, device=xp_device(a)), axis=axis,
dtype=a.dtype)
mean = xpx.apply_where(n != 0, (sum, n), operator.truediv, fill_value=xp.nan)
return mean[()] if mean.ndim == 0 else mean
@xp_capabilities()
@_axis_nan_policy_factory(
lambda x: x, n_outputs=1, result_to_tuple=lambda x, _: (x,)
)
def tvar(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
"""Compute the trimmed variance.
This function computes the sample variance of an array of values,
while ignoring values which are outside of given `limits`.
Parameters
----------
a : array_like
Array of values.
limits : None or (lower limit, upper limit), optional
Values in the input array less than the lower limit or greater than the
upper limit will be ignored. When limits is None, then all values are
used. Either of the limit values in the tuple can also be None
representing a half-open interval. The default value is None.
inclusive : (bool, bool), optional
A tuple consisting of the (lower flag, upper flag). These flags
determine whether values exactly equal to the lower or upper limits
are included. The default value is (True, True).
axis : int or None, optional
Axis along which to operate. Default is 0. If None, compute over the
whole array `a`.
ddof : int, optional
Delta degrees of freedom. Default is 1.
Returns
-------
tvar : float
Trimmed variance.
Notes
-----
`tvar` computes the unbiased sample variance, i.e. it uses a correction
factor ``n / (n - 1)``.
Examples
--------
>>> import numpy as np
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.tvar(x)
35.0
>>> stats.tvar(x, (3,17))
20.0
"""
xp = array_namespace(a)
a, _ = _put_val_to_limits(a, limits, inclusive, xp=xp)
with warnings.catch_warnings():
warnings.simplefilter("ignore", SmallSampleWarning)
# Currently, this behaves like nan_policy='omit' for alternative array
# backends, but nan_policy='propagate' will be handled for other backends
# by the axis_nan_policy decorator shortly.
return _xp_var(a, correction=ddof, axis=axis, nan_policy='omit', xp=xp)
@xp_capabilities()
@_axis_nan_policy_factory(
lambda x: x, n_outputs=1, result_to_tuple=lambda x, _: (x,)
)
def tmin(a, lowerlimit=None, axis=0, inclusive=True, nan_policy='propagate'):
"""Compute the trimmed minimum.
This function finds the minimum value of an array `a` along the
specified axis, but only considering values greater than a specified
lower limit.
Parameters
----------
a : array_like
Array of values.
lowerlimit : None or float, optional
Values in the input array less than the given limit will be ignored.
When lowerlimit is None, then all values are used. The default value
is None.
axis : int or None, optional
Axis along which to operate. Default is 0. If None, compute over the
whole array `a`.
inclusive : {True, False}, optional
This flag determines whether values exactly equal to the lower limit
are included. The default value is True.
Returns
-------
tmin : float, int or ndarray
Trimmed minimum.
Examples
--------
>>> import numpy as np
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.tmin(x)
0
>>> stats.tmin(x, 13)
13
>>> stats.tmin(x, 13, inclusive=False)
14
"""
xp = array_namespace(a)
max_ = xp.iinfo(a.dtype).max if xp.isdtype(a.dtype, 'integral') else xp.inf
a, mask = _put_val_to_limits(a, (lowerlimit, None), (inclusive, None),
val=max_, xp=xp)
res = xp.min(a, axis=axis)
invalid = xp.all(mask, axis=axis) # All elements are below lowerlimit
# For eager backends, output dtype is data-dependent
if is_lazy_array(invalid) or xp.any(invalid):
# Possible loss of precision for int types
res = xp_promote(res, force_floating=True, xp=xp)
res = xp.where(invalid, xp.nan, res)
return res[()] if res.ndim == 0 else res
@xp_capabilities()
@_axis_nan_policy_factory(
lambda x: x, n_outputs=1, result_to_tuple=lambda x, _: (x,)
)
def tmax(a, upperlimit=None, axis=0, inclusive=True, nan_policy='propagate'):
"""Compute the trimmed maximum.
This function computes the maximum value of an array along a given axis,
while ignoring values larger than a specified upper limit.
Parameters
----------
a : array_like
Array of values.
upperlimit : None or float, optional
Values in the input array greater than the given limit will be ignored.
When upperlimit is None, then all values are used. The default value
is None.
axis : int or None, optional
Axis along which to operate. Default is 0. If None, compute over the
whole array `a`.
inclusive : {True, False}, optional
This flag determines whether values exactly equal to the upper limit
are included. The default value is True.
Returns
-------
tmax : float, int or ndarray
Trimmed maximum.
Examples
--------
>>> import numpy as np
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.tmax(x)
19
>>> stats.tmax(x, 13)
13
>>> stats.tmax(x, 13, inclusive=False)
12
"""
xp = array_namespace(a)
min_ = xp.iinfo(a.dtype).min if xp.isdtype(a.dtype, 'integral') else -xp.inf
a, mask = _put_val_to_limits(a, (None, upperlimit), (None, inclusive),
val=min_, xp=xp)
res = xp.max(a, axis=axis)
invalid = xp.all(mask, axis=axis) # All elements are above upperlimit
# For eager backends, output dtype is data-dependent
if is_lazy_array(invalid) or xp.any(invalid):
# Possible loss of precision for int types
res = xp_promote(res, force_floating=True, xp=xp)
res = xp.where(invalid, xp.nan, res)
return res[()] if res.ndim == 0 else res
@xp_capabilities()
@_axis_nan_policy_factory(
lambda x: x, n_outputs=1, result_to_tuple=lambda x, _: (x,)
)
def tstd(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
"""Compute the trimmed sample standard deviation.
This function finds the sample standard deviation of given values,
ignoring values outside the given `limits`.
Parameters
----------
a : array_like
Array of values.
limits : None or (lower limit, upper limit), optional
Values in the input array less than the lower limit or greater than the
upper limit will be ignored. When limits is None, then all values are
used. Either of the limit values in the tuple can also be None
representing a half-open interval. The default value is None.
inclusive : (bool, bool), optional
A tuple consisting of the (lower flag, upper flag). These flags
determine whether values exactly equal to the lower or upper limits
are included. The default value is (True, True).
axis : int or None, optional
Axis along which to operate. Default is 0. If None, compute over the
whole array `a`.
ddof : int, optional
Delta degrees of freedom. Default is 1.
Returns
-------
tstd : float
Trimmed sample standard deviation.
Notes
-----
`tstd` computes the unbiased sample standard deviation, i.e. it uses a
correction factor ``n / (n - 1)``.
Examples
--------
>>> import numpy as np
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.tstd(x)
5.9160797830996161
>>> stats.tstd(x, (3,17))
4.4721359549995796
"""
return tvar(a, limits, inclusive, axis, ddof, _no_deco=True)**0.5
@xp_capabilities()
@_axis_nan_policy_factory(
lambda x: x, n_outputs=1, result_to_tuple=lambda x, _: (x,)
)
def tsem(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
"""Compute the trimmed standard error of the mean.
This function finds the standard error of the mean for given
values, ignoring values outside the given `limits`.
Parameters
----------
a : array_like
Array of values.
limits : None or (lower limit, upper limit), optional
Values in the input array less than the lower limit or greater than the
upper limit will be ignored. When limits is None, then all values are
used. Either of the limit values in the tuple can also be None
representing a half-open interval. The default value is None.
inclusive : (bool, bool), optional
A tuple consisting of the (lower flag, upper flag). These flags
determine whether values exactly equal to the lower or upper limits
are included. The default value is (True, True).
axis : int or None, optional
Axis along which to operate. Default is 0. If None, compute over the
whole array `a`.
ddof : int, optional
Delta degrees of freedom. Default is 1.
Returns
-------
tsem : float
Trimmed standard error of the mean.
Notes
-----
`tsem` uses unbiased sample standard deviation, i.e. it uses a
correction factor ``n / (n - 1)``.
Examples
--------
>>> import numpy as np
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.tsem(x)
1.3228756555322954
>>> stats.tsem(x, (3,17))
1.1547005383792515
"""
xp = array_namespace(a)
a, _ = _put_val_to_limits(a, limits, inclusive, xp=xp)
with warnings.catch_warnings():
warnings.simplefilter("ignore", SmallSampleWarning)
# Currently, this behaves like nan_policy='omit' for alternative array
# backends, but nan_policy='propagate' will be handled for other backends
# by the axis_nan_policy decorator shortly.
sd = _xp_var(a, correction=ddof, axis=axis, nan_policy='omit', xp=xp)**0.5
not_nan = xp.astype(~xp.isnan(a), a.dtype)
n_obs = xp.sum(not_nan, axis=axis, dtype=sd.dtype)
return sd / n_obs**0.5
#####################################
# MOMENTS #
#####################################